Unnamed: 0
int64
0
4.69k
program_id
stringclasses
25 values
project_id
stringlengths
13
16
source
stringlengths
5
7.62M
source_diag
float64
ground_truth
stringlengths
3
7.62M
path
float64
100
CWE-787
CVE-2018-8786
/** * FreeRDP: A Remote Desktop Protocol Implementation * Update Data PDUs * * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com> * Copyright 2016 Armin Novak <armin.novak@thincast.com> * Copyright 2016 Thincast Technologies GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <winpr/crt.h> #include <winpr/print.h> #include <winpr/synch.h> #include <winpr/thread.h> #include <winpr/collections.h> #include "update.h" #include "surface.h" #include "message.h" #include "info.h" #include "window.h" #include <freerdp/log.h> #include <freerdp/peer.h> #include <freerdp/codec/bitmap.h> #include "../cache/pointer.h" #include "../cache/palette.h" #include "../cache/bitmap.h" #define TAG FREERDP_TAG("core.update") static const char* const UPDATE_TYPE_STRINGS[] = { "Orders", "Bitmap", "Palette", "Synchronize" }; static const char* update_type_to_string(UINT16 updateType) { if (updateType >= ARRAYSIZE(UPDATE_TYPE_STRINGS)) return "UNKNOWN"; return UPDATE_TYPE_STRINGS[updateType]; } static BOOL update_recv_orders(rdpUpdate* update, wStream* s) { UINT16 numberOrders; if (Stream_GetRemainingLength(s) < 6) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 6"); return FALSE; } Stream_Seek_UINT16(s); /* pad2OctetsA (2 bytes) */ Stream_Read_UINT16(s, numberOrders); /* numberOrders (2 bytes) */ Stream_Seek_UINT16(s); /* pad2OctetsB (2 bytes) */ while (numberOrders > 0) { if (!update_recv_order(update, s)) { WLog_ERR(TAG, "update_recv_order() failed"); return FALSE; } numberOrders--; } return TRUE; } static BOOL update_read_bitmap_data(rdpUpdate* update, wStream* s, BITMAP_DATA* bitmapData) { if (Stream_GetRemainingLength(s) < 18) return FALSE; Stream_Read_UINT16(s, bitmapData->destLeft); Stream_Read_UINT16(s, bitmapData->destTop); Stream_Read_UINT16(s, bitmapData->destRight); Stream_Read_UINT16(s, bitmapData->destBottom); Stream_Read_UINT16(s, bitmapData->width); Stream_Read_UINT16(s, bitmapData->height); Stream_Read_UINT16(s, bitmapData->bitsPerPixel); Stream_Read_UINT16(s, bitmapData->flags); Stream_Read_UINT16(s, bitmapData->bitmapLength); if (bitmapData->flags & BITMAP_COMPRESSION) { if (!(bitmapData->flags & NO_BITMAP_COMPRESSION_HDR)) { Stream_Read_UINT16(s, bitmapData->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbScanWidth); /* cbScanWidth (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */ bitmapData->bitmapLength = bitmapData->cbCompMainBodySize; } bitmapData->compressed = TRUE; } else bitmapData->compressed = FALSE; if (Stream_GetRemainingLength(s) < bitmapData->bitmapLength) return FALSE; if (bitmapData->bitmapLength > 0) { bitmapData->bitmapDataStream = malloc(bitmapData->bitmapLength); if (!bitmapData->bitmapDataStream) return FALSE; memcpy(bitmapData->bitmapDataStream, Stream_Pointer(s), bitmapData->bitmapLength); Stream_Seek(s, bitmapData->bitmapLength); } return TRUE; } static BOOL update_write_bitmap_data(rdpUpdate* update, wStream* s, BITMAP_DATA* bitmapData) { if (!Stream_EnsureRemainingCapacity(s, 64 + bitmapData->bitmapLength)) return FALSE; bitmapData->flags = 0; bitmapData->cbCompFirstRowSize = 0; if (bitmapData->compressed) bitmapData->flags |= BITMAP_COMPRESSION; if (update->context->settings->NoBitmapCompressionHeader) { bitmapData->flags |= NO_BITMAP_COMPRESSION_HDR; bitmapData->cbCompMainBodySize = bitmapData->bitmapLength; } Stream_Write_UINT16(s, bitmapData->destLeft); Stream_Write_UINT16(s, bitmapData->destTop); Stream_Write_UINT16(s, bitmapData->destRight); Stream_Write_UINT16(s, bitmapData->destBottom); Stream_Write_UINT16(s, bitmapData->width); Stream_Write_UINT16(s, bitmapData->height); Stream_Write_UINT16(s, bitmapData->bitsPerPixel); Stream_Write_UINT16(s, bitmapData->flags); Stream_Write_UINT16(s, bitmapData->bitmapLength); if (bitmapData->flags & BITMAP_COMPRESSION) { if (!(bitmapData->flags & NO_BITMAP_COMPRESSION_HDR)) { Stream_Write_UINT16(s, bitmapData->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */ Stream_Write_UINT16(s, bitmapData->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */ Stream_Write_UINT16(s, bitmapData->cbScanWidth); /* cbScanWidth (2 bytes) */ Stream_Write_UINT16(s, bitmapData->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */ } Stream_Write(s, bitmapData->bitmapDataStream, bitmapData->bitmapLength); } else { Stream_Write(s, bitmapData->bitmapDataStream, bitmapData->bitmapLength); } return TRUE; } BITMAP_UPDATE* update_read_bitmap_update(rdpUpdate* update, wStream* s) { UINT32 i; BITMAP_UPDATE* bitmapUpdate = calloc(1, sizeof(BITMAP_UPDATE)); if (!bitmapUpdate) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */ WLog_Print(update->log, WLOG_TRACE, "BitmapUpdate: %"PRIu32"", bitmapUpdate->number); if (bitmapUpdate->number > bitmapUpdate->count) { UINT16 count; BITMAP_DATA* newdata; count = bitmapUpdate->number * 2; newdata = (BITMAP_DATA*) realloc(bitmapUpdate->rectangles, sizeof(BITMAP_DATA) * count); if (!newdata) goto fail; bitmapUpdate->rectangles = newdata; ZeroMemory(&bitmapUpdate->rectangles[bitmapUpdate->count], sizeof(BITMAP_DATA) * (count - bitmapUpdate->count)); bitmapUpdate->count = count; } /* rectangles */ for (i = 0; i < bitmapUpdate->number; i++) { if (!update_read_bitmap_data(update, s, &bitmapUpdate->rectangles[i])) goto fail; } return bitmapUpdate; fail: free_bitmap_update(update->context, bitmapUpdate); return NULL; } static BOOL update_write_bitmap_update(rdpUpdate* update, wStream* s, const BITMAP_UPDATE* bitmapUpdate) { int i; if (!Stream_EnsureRemainingCapacity(s, 32)) return FALSE; Stream_Write_UINT16(s, UPDATE_TYPE_BITMAP); /* updateType */ Stream_Write_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */ /* rectangles */ for (i = 0; i < (int) bitmapUpdate->number; i++) { if (!update_write_bitmap_data(update, s, &bitmapUpdate->rectangles[i])) return FALSE; } return TRUE; } PALETTE_UPDATE* update_read_palette(rdpUpdate* update, wStream* s) { int i; PALETTE_ENTRY* entry; PALETTE_UPDATE* palette_update = calloc(1, sizeof(PALETTE_UPDATE)); if (!palette_update) goto fail; if (Stream_GetRemainingLength(s) < 6) goto fail; Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */ Stream_Read_UINT32(s, palette_update->number); /* numberColors (4 bytes), must be set to 256 */ if (palette_update->number > 256) palette_update->number = 256; if (Stream_GetRemainingLength(s) < palette_update->number * 3) goto fail; /* paletteEntries */ for (i = 0; i < (int) palette_update->number; i++) { entry = &palette_update->entries[i]; Stream_Read_UINT8(s, entry->red); Stream_Read_UINT8(s, entry->green); Stream_Read_UINT8(s, entry->blue); } return palette_update; fail: free_palette_update(update->context, palette_update); return NULL; } static void update_read_synchronize(rdpUpdate* update, wStream* s) { Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */ /** * The Synchronize Update is an artifact from the * T.128 protocol and should be ignored. */ } static BOOL update_read_play_sound(wStream* s, PLAY_SOUND_UPDATE* play_sound) { if (Stream_GetRemainingLength(s) < 8) return FALSE; Stream_Read_UINT32(s, play_sound->duration); /* duration (4 bytes) */ Stream_Read_UINT32(s, play_sound->frequency); /* frequency (4 bytes) */ return TRUE; } BOOL update_recv_play_sound(rdpUpdate* update, wStream* s) { PLAY_SOUND_UPDATE play_sound; if (!update_read_play_sound(s, &play_sound)) return FALSE; return IFCALLRESULT(FALSE, update->PlaySound, update->context, &play_sound); } POINTER_POSITION_UPDATE* update_read_pointer_position(rdpUpdate* update, wStream* s) { POINTER_POSITION_UPDATE* pointer_position = calloc(1, sizeof(POINTER_POSITION_UPDATE)); if (!pointer_position) goto fail; if (Stream_GetRemainingLength(s) < 4) goto fail; Stream_Read_UINT16(s, pointer_position->xPos); /* xPos (2 bytes) */ Stream_Read_UINT16(s, pointer_position->yPos); /* yPos (2 bytes) */ return pointer_position; fail: free_pointer_position_update(update->context, pointer_position); return NULL; } POINTER_SYSTEM_UPDATE* update_read_pointer_system(rdpUpdate* update, wStream* s) { POINTER_SYSTEM_UPDATE* pointer_system = calloc(1, sizeof(POINTER_SYSTEM_UPDATE)); if (!pointer_system) goto fail; if (Stream_GetRemainingLength(s) < 4) goto fail; Stream_Read_UINT32(s, pointer_system->type); /* systemPointerType (4 bytes) */ return pointer_system; fail: free_pointer_system_update(update->context, pointer_system); return NULL; } static BOOL _update_read_pointer_color(wStream* s, POINTER_COLOR_UPDATE* pointer_color, BYTE xorBpp) { BYTE* newMask; UINT32 scanlineSize; if (!pointer_color) goto fail; if (Stream_GetRemainingLength(s) < 14) goto fail; Stream_Read_UINT16(s, pointer_color->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Read_UINT16(s, pointer_color->xPos); /* xPos (2 bytes) */ Stream_Read_UINT16(s, pointer_color->yPos); /* yPos (2 bytes) */ /** * As stated in 2.2.9.1.1.4.4 Color Pointer Update: * The maximum allowed pointer width/height is 96 pixels if the client indicated support * for large pointers by setting the LARGE_POINTER_FLAG (0x00000001) in the Large * Pointer Capability Set (section 2.2.7.2.7). If the LARGE_POINTER_FLAG was not * set, the maximum allowed pointer width/height is 32 pixels. * * So we check for a maximum of 96 for CVE-2014-0250. */ Stream_Read_UINT16(s, pointer_color->width); /* width (2 bytes) */ Stream_Read_UINT16(s, pointer_color->height); /* height (2 bytes) */ if ((pointer_color->width > 96) || (pointer_color->height > 96)) goto fail; Stream_Read_UINT16(s, pointer_color->lengthAndMask); /* lengthAndMask (2 bytes) */ Stream_Read_UINT16(s, pointer_color->lengthXorMask); /* lengthXorMask (2 bytes) */ /** * There does not seem to be any documentation on why * xPos / yPos can be larger than width / height * so it is missing in documentation or a bug in implementation * 2.2.9.1.1.4.4 Color Pointer Update (TS_COLORPOINTERATTRIBUTE) */ if (pointer_color->xPos >= pointer_color->width) pointer_color->xPos = 0; if (pointer_color->yPos >= pointer_color->height) pointer_color->yPos = 0; if (pointer_color->lengthXorMask > 0) { /** * Spec states that: * * xorMaskData (variable): A variable-length array of bytes. Contains the 24-bpp, bottom-up * XOR mask scan-line data. The XOR mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 3x3 pixel cursor is being sent, then each scan-line will consume 10 * bytes (3 pixels per scan-line multiplied by 3 bytes per pixel, rounded up to the next even * number of bytes). * * In fact instead of 24-bpp, the bpp parameter is given by the containing packet. */ if (Stream_GetRemainingLength(s) < pointer_color->lengthXorMask) goto fail; scanlineSize = (7 + xorBpp * pointer_color->width) / 8; scanlineSize = ((scanlineSize + 1) / 2) * 2; if (scanlineSize * pointer_color->height != pointer_color->lengthXorMask) { WLog_ERR(TAG, "invalid lengthXorMask: width=%"PRIu32" height=%"PRIu32", %"PRIu32" instead of %"PRIu32"", pointer_color->width, pointer_color->height, pointer_color->lengthXorMask, scanlineSize * pointer_color->height); goto fail; } newMask = realloc(pointer_color->xorMaskData, pointer_color->lengthXorMask); if (!newMask) goto fail; pointer_color->xorMaskData = newMask; Stream_Read(s, pointer_color->xorMaskData, pointer_color->lengthXorMask); } if (pointer_color->lengthAndMask > 0) { /** * andMaskData (variable): A variable-length array of bytes. Contains the 1-bpp, bottom-up * AND mask scan-line data. The AND mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 7x7 pixel cursor is being sent, then each scan-line will consume 2 * bytes (7 pixels per scan-line multiplied by 1 bpp, rounded up to the next even number of * bytes). */ if (Stream_GetRemainingLength(s) < pointer_color->lengthAndMask) goto fail; scanlineSize = ((7 + pointer_color->width) / 8); scanlineSize = ((1 + scanlineSize) / 2) * 2; if (scanlineSize * pointer_color->height != pointer_color->lengthAndMask) { WLog_ERR(TAG, "invalid lengthAndMask: %"PRIu32" instead of %"PRIu32"", pointer_color->lengthAndMask, scanlineSize * pointer_color->height); goto fail; } newMask = realloc(pointer_color->andMaskData, pointer_color->lengthAndMask); if (!newMask) goto fail; pointer_color->andMaskData = newMask; Stream_Read(s, pointer_color->andMaskData, pointer_color->lengthAndMask); } if (Stream_GetRemainingLength(s) > 0) Stream_Seek_UINT8(s); /* pad (1 byte) */ return TRUE; fail: return FALSE; } POINTER_COLOR_UPDATE* update_read_pointer_color(rdpUpdate* update, wStream* s, BYTE xorBpp) { POINTER_COLOR_UPDATE* pointer_color = calloc(1, sizeof(POINTER_COLOR_UPDATE)); if (!pointer_color) goto fail; if (!_update_read_pointer_color(s, pointer_color, xorBpp)) goto fail; return pointer_color; fail: free_pointer_color_update(update->context, pointer_color); return NULL; } POINTER_NEW_UPDATE* update_read_pointer_new(rdpUpdate* update, wStream* s) { POINTER_NEW_UPDATE* pointer_new = calloc(1, sizeof(POINTER_NEW_UPDATE)); if (!pointer_new) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, pointer_new->xorBpp); /* xorBpp (2 bytes) */ if ((pointer_new->xorBpp < 1) || (pointer_new->xorBpp > 32)) { WLog_ERR(TAG, "invalid xorBpp %"PRIu32"", pointer_new->xorBpp); goto fail; } if (!_update_read_pointer_color(s, &pointer_new->colorPtrAttr, pointer_new->xorBpp)) /* colorPtrAttr */ goto fail; return pointer_new; fail: free_pointer_new_update(update->context, pointer_new); return NULL; } POINTER_CACHED_UPDATE* update_read_pointer_cached(rdpUpdate* update, wStream* s) { POINTER_CACHED_UPDATE* pointer = calloc(1, sizeof(POINTER_CACHED_UPDATE)); if (!pointer) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, pointer->cacheIndex); /* cacheIndex (2 bytes) */ return pointer; fail: free_pointer_cached_update(update->context, pointer); return NULL; } BOOL update_recv_pointer(rdpUpdate* update, wStream* s) { BOOL rc = FALSE; UINT16 messageType; rdpContext* context = update->context; rdpPointerUpdate* pointer = update->pointer; if (Stream_GetRemainingLength(s) < 2 + 2) return FALSE; Stream_Read_UINT16(s, messageType); /* messageType (2 bytes) */ Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */ switch (messageType) { case PTR_MSG_TYPE_POSITION: { POINTER_POSITION_UPDATE* pointer_position = update_read_pointer_position(update, s); if (pointer_position) { rc = IFCALLRESULT(FALSE, pointer->PointerPosition, context, pointer_position); free_pointer_position_update(context, pointer_position); } } break; case PTR_MSG_TYPE_SYSTEM: { POINTER_SYSTEM_UPDATE* pointer_system = update_read_pointer_system(update, s); if (pointer_system) { rc = IFCALLRESULT(FALSE, pointer->PointerSystem, context, pointer_system); free_pointer_system_update(context, pointer_system); } } break; case PTR_MSG_TYPE_COLOR: { POINTER_COLOR_UPDATE* pointer_color = update_read_pointer_color(update, s, 24); if (pointer_color) { rc = IFCALLRESULT(FALSE, pointer->PointerColor, context, pointer_color); free_pointer_color_update(context, pointer_color); } } break; case PTR_MSG_TYPE_POINTER: { POINTER_NEW_UPDATE* pointer_new = update_read_pointer_new(update, s); if (pointer_new) { rc = IFCALLRESULT(FALSE, pointer->PointerNew, context, pointer_new); free_pointer_new_update(context, pointer_new); } } break; case PTR_MSG_TYPE_CACHED: { POINTER_CACHED_UPDATE* pointer_cached = update_read_pointer_cached(update, s); if (pointer_cached) { rc = IFCALLRESULT(FALSE, pointer->PointerCached, context, pointer_cached); free_pointer_cached_update(context, pointer_cached); } } break; default: break; } return rc; } BOOL update_recv(rdpUpdate* update, wStream* s) { BOOL rc = FALSE; UINT16 updateType; rdpContext* context = update->context; if (Stream_GetRemainingLength(s) < 2) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 2"); return FALSE; } Stream_Read_UINT16(s, updateType); /* updateType (2 bytes) */ WLog_Print(update->log, WLOG_TRACE, "%s Update Data PDU", UPDATE_TYPE_STRINGS[updateType]); if (!IFCALLRESULT(TRUE, update->BeginPaint, context)) return FALSE; switch (updateType) { case UPDATE_TYPE_ORDERS: rc = update_recv_orders(update, s); break; case UPDATE_TYPE_BITMAP: { BITMAP_UPDATE* bitmap_update = update_read_bitmap_update(update, s); if (!bitmap_update) { WLog_ERR(TAG, "UPDATE_TYPE_BITMAP - update_read_bitmap_update() failed"); return FALSE; } rc = IFCALLRESULT(FALSE, update->BitmapUpdate, context, bitmap_update); free_bitmap_update(update->context, bitmap_update); } break; case UPDATE_TYPE_PALETTE: { PALETTE_UPDATE* palette_update = update_read_palette(update, s); if (!palette_update) { WLog_ERR(TAG, "UPDATE_TYPE_PALETTE - update_read_palette() failed"); return FALSE; } rc = IFCALLRESULT(FALSE, update->Palette, context, palette_update); free_palette_update(context, palette_update); } break; case UPDATE_TYPE_SYNCHRONIZE: update_read_synchronize(update, s); rc = IFCALLRESULT(TRUE, update->Synchronize, context); break; default: break; } if (!rc) { WLog_ERR(TAG, "UPDATE_TYPE %s [%"PRIu16"] failed", update_type_to_string(updateType), updateType); return FALSE; } if (!IFCALLRESULT(FALSE, update->EndPaint, context)) return FALSE; return TRUE; } void update_reset_state(rdpUpdate* update) { rdpPrimaryUpdate* primary = update->primary; rdpAltSecUpdate* altsec = update->altsec; if (primary->fast_glyph.glyphData.aj) { free(primary->fast_glyph.glyphData.aj); primary->fast_glyph.glyphData.aj = NULL; } ZeroMemory(&primary->order_info, sizeof(ORDER_INFO)); ZeroMemory(&primary->dstblt, sizeof(DSTBLT_ORDER)); ZeroMemory(&primary->patblt, sizeof(PATBLT_ORDER)); ZeroMemory(&primary->scrblt, sizeof(SCRBLT_ORDER)); ZeroMemory(&primary->opaque_rect, sizeof(OPAQUE_RECT_ORDER)); ZeroMemory(&primary->draw_nine_grid, sizeof(DRAW_NINE_GRID_ORDER)); ZeroMemory(&primary->multi_dstblt, sizeof(MULTI_DSTBLT_ORDER)); ZeroMemory(&primary->multi_patblt, sizeof(MULTI_PATBLT_ORDER)); ZeroMemory(&primary->multi_scrblt, sizeof(MULTI_SCRBLT_ORDER)); ZeroMemory(&primary->multi_opaque_rect, sizeof(MULTI_OPAQUE_RECT_ORDER)); ZeroMemory(&primary->multi_draw_nine_grid, sizeof(MULTI_DRAW_NINE_GRID_ORDER)); ZeroMemory(&primary->line_to, sizeof(LINE_TO_ORDER)); ZeroMemory(&primary->polyline, sizeof(POLYLINE_ORDER)); ZeroMemory(&primary->memblt, sizeof(MEMBLT_ORDER)); ZeroMemory(&primary->mem3blt, sizeof(MEM3BLT_ORDER)); ZeroMemory(&primary->save_bitmap, sizeof(SAVE_BITMAP_ORDER)); ZeroMemory(&primary->glyph_index, sizeof(GLYPH_INDEX_ORDER)); ZeroMemory(&primary->fast_index, sizeof(FAST_INDEX_ORDER)); ZeroMemory(&primary->fast_glyph, sizeof(FAST_GLYPH_ORDER)); ZeroMemory(&primary->polygon_sc, sizeof(POLYGON_SC_ORDER)); ZeroMemory(&primary->polygon_cb, sizeof(POLYGON_CB_ORDER)); ZeroMemory(&primary->ellipse_sc, sizeof(ELLIPSE_SC_ORDER)); ZeroMemory(&primary->ellipse_cb, sizeof(ELLIPSE_CB_ORDER)); primary->order_info.orderType = ORDER_TYPE_PATBLT; if (!update->initialState) { altsec->switch_surface.bitmapId = SCREEN_BITMAP_SURFACE; IFCALL(altsec->SwitchSurface, update->context, &(altsec->switch_surface)); } } BOOL update_post_connect(rdpUpdate* update) { update->asynchronous = update->context->settings->AsyncUpdate; if (update->asynchronous) if (!(update->proxy = update_message_proxy_new(update))) return FALSE; update->altsec->switch_surface.bitmapId = SCREEN_BITMAP_SURFACE; IFCALL(update->altsec->SwitchSurface, update->context, &(update->altsec->switch_surface)); update->initialState = FALSE; return TRUE; } void update_post_disconnect(rdpUpdate* update) { update->asynchronous = update->context->settings->AsyncUpdate; if (update->asynchronous) update_message_proxy_free(update->proxy); update->initialState = TRUE; } static BOOL update_begin_paint(rdpContext* context) { wStream* s; rdpUpdate* update = context->update; if (update->us) update->EndPaint(context); s = fastpath_update_pdu_init_new(context->rdp->fastpath); if (!s) return FALSE; Stream_SealLength(s); Stream_Seek(s, 2); /* numberOrders (2 bytes) */ update->combineUpdates = TRUE; update->numberOrders = 0; update->us = s; return TRUE; } static BOOL update_end_paint(rdpContext* context) { wStream* s; int headerLength; rdpUpdate* update = context->update; if (!update->us) return FALSE; s = update->us; headerLength = Stream_Length(s); Stream_SealLength(s); Stream_SetPosition(s, headerLength); Stream_Write_UINT16(s, update->numberOrders); /* numberOrders (2 bytes) */ Stream_SetPosition(s, Stream_Length(s)); if (update->numberOrders > 0) { WLog_ERR(TAG, "sending %"PRIu16" orders", update->numberOrders); fastpath_send_update_pdu(context->rdp->fastpath, FASTPATH_UPDATETYPE_ORDERS, s, FALSE); } update->combineUpdates = FALSE; update->numberOrders = 0; update->us = NULL; Stream_Free(s, TRUE); return TRUE; } static void update_flush(rdpContext* context) { rdpUpdate* update = context->update; if (update->numberOrders > 0) { update->EndPaint(context); update->BeginPaint(context); } } static void update_force_flush(rdpContext* context) { rdpUpdate* update = context->update; if (update->numberOrders > 0) { update->EndPaint(context); update->BeginPaint(context); } } static BOOL update_check_flush(rdpContext* context, int size) { wStream* s; rdpUpdate* update = context->update; s = update->us; if (!update->us) { update->BeginPaint(context); return FALSE; } if (Stream_GetPosition(s) + size + 64 >= 0x3FFF) { update_flush(context); return TRUE; } return FALSE; } static BOOL update_set_bounds(rdpContext* context, const rdpBounds* bounds) { rdpUpdate* update = context->update; CopyMemory(&update->previousBounds, &update->currentBounds, sizeof(rdpBounds)); if (!bounds) ZeroMemory(&update->currentBounds, sizeof(rdpBounds)); else CopyMemory(&update->currentBounds, bounds, sizeof(rdpBounds)); return TRUE; } BOOL update_bounds_is_null(rdpBounds* bounds) { if ((bounds->left == 0) && (bounds->top == 0) && (bounds->right == 0) && (bounds->bottom == 0)) return TRUE; return FALSE; } BOOL update_bounds_equals(rdpBounds* bounds1, rdpBounds* bounds2) { if ((bounds1->left == bounds2->left) && (bounds1->top == bounds2->top) && (bounds1->right == bounds2->right) && (bounds1->bottom == bounds2->bottom)) return TRUE; return FALSE; } int update_prepare_bounds(rdpContext* context, ORDER_INFO* orderInfo) { int length = 0; rdpUpdate* update = context->update; orderInfo->boundsFlags = 0; if (update_bounds_is_null(&update->currentBounds)) return 0; orderInfo->controlFlags |= ORDER_BOUNDS; if (update_bounds_equals(&update->previousBounds, &update->currentBounds)) { orderInfo->controlFlags |= ORDER_ZERO_BOUNDS_DELTAS; return 0; } else { length += 1; if (update->previousBounds.left != update->currentBounds.left) { orderInfo->bounds.left = update->currentBounds.left; orderInfo->boundsFlags |= BOUND_LEFT; length += 2; } if (update->previousBounds.top != update->currentBounds.top) { orderInfo->bounds.top = update->currentBounds.top; orderInfo->boundsFlags |= BOUND_TOP; length += 2; } if (update->previousBounds.right != update->currentBounds.right) { orderInfo->bounds.right = update->currentBounds.right; orderInfo->boundsFlags |= BOUND_RIGHT; length += 2; } if (update->previousBounds.bottom != update->currentBounds.bottom) { orderInfo->bounds.bottom = update->currentBounds.bottom; orderInfo->boundsFlags |= BOUND_BOTTOM; length += 2; } } return length; } static int update_prepare_order_info(rdpContext* context, ORDER_INFO* orderInfo, UINT32 orderType) { int length = 1; orderInfo->fieldFlags = 0; orderInfo->orderType = orderType; orderInfo->controlFlags = ORDER_STANDARD; orderInfo->controlFlags |= ORDER_TYPE_CHANGE; length += 1; length += PRIMARY_DRAWING_ORDER_FIELD_BYTES[orderInfo->orderType]; length += update_prepare_bounds(context, orderInfo); return length; } int update_write_order_info(rdpContext* context, wStream* s, ORDER_INFO* orderInfo, int offset) { size_t position; position = Stream_GetPosition(s); Stream_SetPosition(s, offset); Stream_Write_UINT8(s, orderInfo->controlFlags); /* controlFlags (1 byte) */ if (orderInfo->controlFlags & ORDER_TYPE_CHANGE) Stream_Write_UINT8(s, orderInfo->orderType); /* orderType (1 byte) */ update_write_field_flags(s, orderInfo->fieldFlags, orderInfo->controlFlags, PRIMARY_DRAWING_ORDER_FIELD_BYTES[orderInfo->orderType]); update_write_bounds(s, orderInfo); Stream_SetPosition(s, position); return 0; } static void update_write_refresh_rect(wStream* s, BYTE count, const RECTANGLE_16* areas) { int i; Stream_Write_UINT8(s, count); /* numberOfAreas (1 byte) */ Stream_Seek(s, 3); /* pad3Octets (3 bytes) */ for (i = 0; i < count; i++) { Stream_Write_UINT16(s, areas[i].left); /* left (2 bytes) */ Stream_Write_UINT16(s, areas[i].top); /* top (2 bytes) */ Stream_Write_UINT16(s, areas[i].right); /* right (2 bytes) */ Stream_Write_UINT16(s, areas[i].bottom); /* bottom (2 bytes) */ } } static BOOL update_send_refresh_rect(rdpContext* context, BYTE count, const RECTANGLE_16* areas) { rdpRdp* rdp = context->rdp; if (rdp->settings->RefreshRect) { wStream* s = rdp_data_pdu_init(rdp); if (!s) return FALSE; update_write_refresh_rect(s, count, areas); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_REFRESH_RECT, rdp->mcs->userId); } return TRUE; } static void update_write_suppress_output(wStream* s, BYTE allow, const RECTANGLE_16* area) { Stream_Write_UINT8(s, allow); /* allowDisplayUpdates (1 byte) */ /* Use zeros for padding (like mstsc) for compatibility with legacy servers */ Stream_Zero(s, 3); /* pad3Octets (3 bytes) */ if (allow > 0) { Stream_Write_UINT16(s, area->left); /* left (2 bytes) */ Stream_Write_UINT16(s, area->top); /* top (2 bytes) */ Stream_Write_UINT16(s, area->right); /* right (2 bytes) */ Stream_Write_UINT16(s, area->bottom); /* bottom (2 bytes) */ } } static BOOL update_send_suppress_output(rdpContext* context, BYTE allow, const RECTANGLE_16* area) { rdpRdp* rdp = context->rdp; if (rdp->settings->SuppressOutput) { wStream* s = rdp_data_pdu_init(rdp); if (!s) return FALSE; update_write_suppress_output(s, allow, area); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SUPPRESS_OUTPUT, rdp->mcs->userId); } return TRUE; } static BOOL update_send_surface_command(rdpContext* context, wStream* s) { wStream* update; rdpRdp* rdp = context->rdp; BOOL ret; update = fastpath_update_pdu_init(rdp->fastpath); if (!update) return FALSE; if (!Stream_EnsureRemainingCapacity(update, Stream_GetPosition(s))) { ret = FALSE; goto out; } Stream_Write(update, Stream_Buffer(s), Stream_GetPosition(s)); ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, update, FALSE); out: Stream_Release(update); return ret; } static BOOL update_send_surface_bits(rdpContext* context, const SURFACE_BITS_COMMAND* surfaceBitsCommand) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_surfcmd_surface_bits(s, surfaceBitsCommand)) goto out_fail; if (!fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s, surfaceBitsCommand->skipCompression)) goto out_fail; update_force_flush(context); ret = TRUE; out_fail: Stream_Release(s); return ret; } static BOOL update_send_surface_frame_marker(rdpContext* context, const SURFACE_FRAME_MARKER* surfaceFrameMarker) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_surfcmd_frame_marker(s, surfaceFrameMarker->frameAction, surfaceFrameMarker->frameId) || !fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s, FALSE)) goto out_fail; update_force_flush(context); ret = TRUE; out_fail: Stream_Release(s); return ret; } static BOOL update_send_surface_frame_bits(rdpContext* context, const SURFACE_BITS_COMMAND* cmd, BOOL first, BOOL last, UINT32 frameId) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (first) { if (!update_write_surfcmd_frame_marker(s, SURFACECMD_FRAMEACTION_BEGIN, frameId)) goto out_fail; } if (!update_write_surfcmd_surface_bits(s, cmd)) goto out_fail; if (last) { if (!update_write_surfcmd_frame_marker(s, SURFACECMD_FRAMEACTION_END, frameId)) goto out_fail; } ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s, cmd->skipCompression); update_force_flush(context); out_fail: Stream_Release(s); return ret; } static BOOL update_send_frame_acknowledge(rdpContext* context, UINT32 frameId) { rdpRdp* rdp = context->rdp; if (rdp->settings->ReceivedCapabilities[CAPSET_TYPE_FRAME_ACKNOWLEDGE]) { wStream* s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT32(s, frameId); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_FRAME_ACKNOWLEDGE, rdp->mcs->userId); } return TRUE; } static BOOL update_send_synchronize(rdpContext* context) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; Stream_Zero(s, 2); /* pad2Octets (2 bytes) */ ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SYNCHRONIZE, s, FALSE); Stream_Release(s); return ret; } static BOOL update_send_desktop_resize(rdpContext* context) { return rdp_server_reactivate(context->rdp); } static BOOL update_send_bitmap_update(rdpContext* context, const BITMAP_UPDATE* bitmapUpdate) { wStream* s; rdpRdp* rdp = context->rdp; rdpUpdate* update = context->update; BOOL ret = TRUE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_bitmap_update(update, s, bitmapUpdate) || !fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_BITMAP, s, bitmapUpdate->skipCompression)) { ret = FALSE; goto out_fail; } update_force_flush(context); out_fail: Stream_Release(s); return ret; } static BOOL update_send_play_sound(rdpContext* context, const PLAY_SOUND_UPDATE* play_sound) { wStream* s; rdpRdp* rdp = context->rdp; if (!rdp->settings->ReceivedCapabilities[CAPSET_TYPE_SOUND]) { return TRUE; } s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT32(s, play_sound->duration); Stream_Write_UINT32(s, play_sound->frequency); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_PLAY_SOUND, rdp->mcs->userId); } /** * Primary Drawing Orders */ static BOOL update_send_dstblt(rdpContext* context, const DSTBLT_ORDER* dstblt) { wStream* s; UINT32 offset; UINT32 headerLength; ORDER_INFO orderInfo; int inf; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_DSTBLT); inf = update_approximate_dstblt_order(&orderInfo, dstblt); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_dstblt_order(s, &orderInfo, dstblt)) return FALSE; update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_patblt(rdpContext* context, PATBLT_ORDER* patblt) { wStream* s; size_t offset; int headerLength; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_PATBLT); update_check_flush(context, headerLength + update_approximate_patblt_order(&orderInfo, patblt)); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_patblt_order(s, &orderInfo, patblt); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_scrblt(rdpContext* context, const SCRBLT_ORDER* scrblt) { wStream* s; UINT32 offset; UINT32 headerLength; ORDER_INFO orderInfo; int inf; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_SCRBLT); inf = update_approximate_scrblt_order(&orderInfo, scrblt); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return TRUE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_scrblt_order(s, &orderInfo, scrblt); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_opaque_rect(rdpContext* context, const OPAQUE_RECT_ORDER* opaque_rect) { wStream* s; size_t offset; int headerLength; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_OPAQUE_RECT); update_check_flush(context, headerLength + update_approximate_opaque_rect_order(&orderInfo, opaque_rect)); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_opaque_rect_order(s, &orderInfo, opaque_rect); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_line_to(rdpContext* context, const LINE_TO_ORDER* line_to) { wStream* s; int offset; int headerLength; ORDER_INFO orderInfo; int inf; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_LINE_TO); inf = update_approximate_line_to_order(&orderInfo, line_to); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_line_to_order(s, &orderInfo, line_to); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_memblt(rdpContext* context, MEMBLT_ORDER* memblt) { wStream* s; size_t offset; int headerLength; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_MEMBLT); update_check_flush(context, headerLength + update_approximate_memblt_order(&orderInfo, memblt)); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_memblt_order(s, &orderInfo, memblt); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_glyph_index(rdpContext* context, GLYPH_INDEX_ORDER* glyph_index) { wStream* s; size_t offset; int headerLength; int inf; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_GLYPH_INDEX); inf = update_approximate_glyph_index_order(&orderInfo, glyph_index); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_glyph_index_order(s, &orderInfo, glyph_index); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } /* * Secondary Drawing Orders */ static BOOL update_send_cache_bitmap(rdpContext* context, const CACHE_BITMAP_ORDER* cache_bitmap) { wStream* s; size_t bm, em; BYTE orderType; int headerLength; int inf; UINT16 extraFlags; INT16 orderLength; rdpUpdate* update = context->update; extraFlags = 0; headerLength = 6; orderType = cache_bitmap->compressed ? ORDER_TYPE_CACHE_BITMAP_COMPRESSED : ORDER_TYPE_BITMAP_UNCOMPRESSED; inf = update_approximate_cache_bitmap_order(cache_bitmap, cache_bitmap->compressed, &extraFlags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_bitmap_order(s, cache_bitmap, cache_bitmap->compressed, &extraFlags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_bitmap_v2(rdpContext* context, CACHE_BITMAP_V2_ORDER* cache_bitmap_v2) { wStream* s; size_t bm, em; BYTE orderType; int headerLength; UINT16 extraFlags; INT16 orderLength; rdpUpdate* update = context->update; extraFlags = 0; headerLength = 6; orderType = cache_bitmap_v2->compressed ? ORDER_TYPE_BITMAP_COMPRESSED_V2 : ORDER_TYPE_BITMAP_UNCOMPRESSED_V2; if (context->settings->NoBitmapCompressionHeader) cache_bitmap_v2->flags |= CBR2_NO_BITMAP_COMPRESSION_HDR; update_check_flush(context, headerLength + update_approximate_cache_bitmap_v2_order(cache_bitmap_v2, cache_bitmap_v2->compressed, &extraFlags)); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_bitmap_v2_order(s, cache_bitmap_v2, cache_bitmap_v2->compressed, &extraFlags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_bitmap_v3(rdpContext* context, CACHE_BITMAP_V3_ORDER* cache_bitmap_v3) { wStream* s; size_t bm, em; BYTE orderType; int headerLength; UINT16 extraFlags; INT16 orderLength; rdpUpdate* update = context->update; extraFlags = 0; headerLength = 6; orderType = ORDER_TYPE_BITMAP_COMPRESSED_V3; update_check_flush(context, headerLength + update_approximate_cache_bitmap_v3_order(cache_bitmap_v3, &extraFlags)); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_bitmap_v3_order(s, cache_bitmap_v3, &extraFlags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_color_table(rdpContext* context, const CACHE_COLOR_TABLE_ORDER* cache_color_table) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_color_table_order(cache_color_table, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_color_table_order(s, cache_color_table, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_COLOR_TABLE); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_glyph(rdpContext* context, const CACHE_GLYPH_ORDER* cache_glyph) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_glyph_order(cache_glyph, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_glyph_order(s, cache_glyph, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_GLYPH); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_glyph_v2(rdpContext* context, const CACHE_GLYPH_V2_ORDER* cache_glyph_v2) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_glyph_v2_order(cache_glyph_v2, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_glyph_v2_order(s, cache_glyph_v2, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_GLYPH); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_brush(rdpContext* context, const CACHE_BRUSH_ORDER* cache_brush) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_brush_order(cache_brush, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_brush_order(s, cache_brush, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_BRUSH); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } /** * Alternate Secondary Drawing Orders */ static BOOL update_send_create_offscreen_bitmap_order( rdpContext* context, const CREATE_OFFSCREEN_BITMAP_ORDER* create_offscreen_bitmap) { wStream* s; size_t bm, em, inf; BYTE orderType; BYTE controlFlags; int headerLength; rdpUpdate* update = context->update; headerLength = 1; orderType = ORDER_TYPE_CREATE_OFFSCREEN_BITMAP; controlFlags = ORDER_SECONDARY | (orderType << 2); inf = update_approximate_create_offscreen_bitmap_order( create_offscreen_bitmap); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_create_offscreen_bitmap_order(s, create_offscreen_bitmap)) return FALSE; em = Stream_GetPosition(s); Stream_SetPosition(s, bm); Stream_Write_UINT8(s, controlFlags); /* controlFlags (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_switch_surface_order( rdpContext* context, const SWITCH_SURFACE_ORDER* switch_surface) { wStream* s; size_t bm, em, inf; BYTE orderType; BYTE controlFlags; int headerLength; rdpUpdate* update; if (!context || !switch_surface || !context->update) return FALSE; update = context->update; headerLength = 1; orderType = ORDER_TYPE_SWITCH_SURFACE; controlFlags = ORDER_SECONDARY | (orderType << 2); inf = update_approximate_switch_surface_order(switch_surface); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_switch_surface_order(s, switch_surface)) return FALSE; em = Stream_GetPosition(s); Stream_SetPosition(s, bm); Stream_Write_UINT8(s, controlFlags); /* controlFlags (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_pointer_system(rdpContext* context, const POINTER_SYSTEM_UPDATE* pointer_system) { wStream* s; BYTE updateCode; rdpRdp* rdp = context->rdp; BOOL ret; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (pointer_system->type == SYSPTR_NULL) updateCode = FASTPATH_UPDATETYPE_PTR_NULL; else updateCode = FASTPATH_UPDATETYPE_PTR_DEFAULT; ret = fastpath_send_update_pdu(rdp->fastpath, updateCode, s, FALSE); Stream_Release(s); return ret; } static BOOL update_send_pointer_position(rdpContext* context, const POINTER_POSITION_UPDATE* pointerPosition) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, 16)) goto out_fail; Stream_Write_UINT16(s, pointerPosition->xPos); /* xPos (2 bytes) */ Stream_Write_UINT16(s, pointerPosition->yPos); /* yPos (2 bytes) */ ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_PTR_POSITION, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_write_pointer_color(wStream* s, const POINTER_COLOR_UPDATE* pointer_color) { if (!Stream_EnsureRemainingCapacity(s, 32 + pointer_color->lengthAndMask + pointer_color->lengthXorMask)) return FALSE; Stream_Write_UINT16(s, pointer_color->cacheIndex); Stream_Write_UINT16(s, pointer_color->xPos); Stream_Write_UINT16(s, pointer_color->yPos); Stream_Write_UINT16(s, pointer_color->width); Stream_Write_UINT16(s, pointer_color->height); Stream_Write_UINT16(s, pointer_color->lengthAndMask); Stream_Write_UINT16(s, pointer_color->lengthXorMask); if (pointer_color->lengthXorMask > 0) Stream_Write(s, pointer_color->xorMaskData, pointer_color->lengthXorMask); if (pointer_color->lengthAndMask > 0) Stream_Write(s, pointer_color->andMaskData, pointer_color->lengthAndMask); Stream_Write_UINT8(s, 0); /* pad (1 byte) */ return TRUE; } static BOOL update_send_pointer_color(rdpContext* context, const POINTER_COLOR_UPDATE* pointer_color) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_pointer_color(s, pointer_color)) goto out_fail; ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_COLOR, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_send_pointer_new(rdpContext* context, const POINTER_NEW_UPDATE* pointer_new) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, 16)) goto out_fail; Stream_Write_UINT16(s, pointer_new->xorBpp); /* xorBpp (2 bytes) */ update_write_pointer_color(s, &pointer_new->colorPtrAttr); ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_POINTER, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_send_pointer_cached(rdpContext* context, const POINTER_CACHED_UPDATE* pointer_cached) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; Stream_Write_UINT16(s, pointer_cached->cacheIndex); /* cacheIndex (2 bytes) */ ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_CACHED, s, FALSE); Stream_Release(s); return ret; } BOOL update_read_refresh_rect(rdpUpdate* update, wStream* s) { int index; BYTE numberOfAreas; RECTANGLE_16* areas; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT8(s, numberOfAreas); Stream_Seek(s, 3); /* pad3Octects */ if (Stream_GetRemainingLength(s) < ((size_t) numberOfAreas * 4 * 2)) return FALSE; areas = (RECTANGLE_16*) calloc(numberOfAreas, sizeof(RECTANGLE_16)); if (!areas) return FALSE; for (index = 0; index < numberOfAreas; index++) { Stream_Read_UINT16(s, areas[index].left); Stream_Read_UINT16(s, areas[index].top); Stream_Read_UINT16(s, areas[index].right); Stream_Read_UINT16(s, areas[index].bottom); } if (update->context->settings->RefreshRect) IFCALL(update->RefreshRect, update->context, numberOfAreas, areas); else WLog_Print(update->log, WLOG_WARN, "ignoring refresh rect request from client"); free(areas); return TRUE; } BOOL update_read_suppress_output(rdpUpdate* update, wStream* s) { BYTE allowDisplayUpdates; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT8(s, allowDisplayUpdates); Stream_Seek(s, 3); /* pad3Octects */ if (allowDisplayUpdates > 0 && Stream_GetRemainingLength(s) < 8) return FALSE; if (update->context->settings->SuppressOutput) IFCALL(update->SuppressOutput, update->context, allowDisplayUpdates, allowDisplayUpdates > 0 ? (RECTANGLE_16*) Stream_Pointer(s) : NULL); else WLog_Print(update->log, WLOG_WARN, "ignoring suppress output request from client"); return TRUE; } static BOOL update_send_set_keyboard_indicators(rdpContext* context, UINT16 led_flags) { wStream* s; rdpRdp* rdp = context->rdp; s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT16(s, 0); /* unitId should be 0 according to MS-RDPBCGR 2.2.8.2.1.1 */ Stream_Write_UINT16(s, led_flags); /* ledFlags (2 bytes) */ return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SET_KEYBOARD_INDICATORS, rdp->mcs->userId); } static BOOL update_send_set_keyboard_ime_status(rdpContext* context, UINT16 imeId, UINT32 imeState, UINT32 imeConvMode) { wStream* s; rdpRdp* rdp = context->rdp; s = rdp_data_pdu_init(rdp); if (!s) return FALSE; /* unitId should be 0 according to MS-RDPBCGR 2.2.8.2.2.1 */ Stream_Write_UINT16(s, imeId); Stream_Write_UINT32(s, imeState); Stream_Write_UINT32(s, imeConvMode); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SET_KEYBOARD_IME_STATUS, rdp->mcs->userId); } void update_register_server_callbacks(rdpUpdate* update) { update->BeginPaint = update_begin_paint; update->EndPaint = update_end_paint; update->SetBounds = update_set_bounds; update->Synchronize = update_send_synchronize; update->DesktopResize = update_send_desktop_resize; update->BitmapUpdate = update_send_bitmap_update; update->SurfaceBits = update_send_surface_bits; update->SurfaceFrameMarker = update_send_surface_frame_marker; update->SurfaceCommand = update_send_surface_command; update->SurfaceFrameBits = update_send_surface_frame_bits; update->PlaySound = update_send_play_sound; update->SetKeyboardIndicators = update_send_set_keyboard_indicators; update->SetKeyboardImeStatus = update_send_set_keyboard_ime_status; update->SaveSessionInfo = rdp_send_save_session_info; update->primary->DstBlt = update_send_dstblt; update->primary->PatBlt = update_send_patblt; update->primary->ScrBlt = update_send_scrblt; update->primary->OpaqueRect = update_send_opaque_rect; update->primary->LineTo = update_send_line_to; update->primary->MemBlt = update_send_memblt; update->primary->GlyphIndex = update_send_glyph_index; update->secondary->CacheBitmap = update_send_cache_bitmap; update->secondary->CacheBitmapV2 = update_send_cache_bitmap_v2; update->secondary->CacheBitmapV3 = update_send_cache_bitmap_v3; update->secondary->CacheColorTable = update_send_cache_color_table; update->secondary->CacheGlyph = update_send_cache_glyph; update->secondary->CacheGlyphV2 = update_send_cache_glyph_v2; update->secondary->CacheBrush = update_send_cache_brush; update->altsec->CreateOffscreenBitmap = update_send_create_offscreen_bitmap_order; update->altsec->SwitchSurface = update_send_switch_surface_order; update->pointer->PointerSystem = update_send_pointer_system; update->pointer->PointerPosition = update_send_pointer_position; update->pointer->PointerColor = update_send_pointer_color; update->pointer->PointerNew = update_send_pointer_new; update->pointer->PointerCached = update_send_pointer_cached; } void update_register_client_callbacks(rdpUpdate* update) { update->RefreshRect = update_send_refresh_rect; update->SuppressOutput = update_send_suppress_output; update->SurfaceFrameAcknowledge = update_send_frame_acknowledge; } int update_process_messages(rdpUpdate* update) { return update_message_queue_process_pending_messages(update); } static void update_free_queued_message(void* obj) { wMessage* msg = (wMessage*)obj; update_message_queue_free_message(msg); } static void update_free_window_state(WINDOW_STATE_ORDER* window_state) { if (!window_state) return; free(window_state->titleInfo.string); window_state->titleInfo.string = NULL; free(window_state->windowRects); window_state->windowRects = NULL; free(window_state->visibilityRects); window_state->visibilityRects = NULL; } rdpUpdate* update_new(rdpRdp* rdp) { const wObject cb = { NULL, NULL, NULL, update_free_queued_message, NULL }; rdpUpdate* update; OFFSCREEN_DELETE_LIST* deleteList; update = (rdpUpdate*) calloc(1, sizeof(rdpUpdate)); if (!update) return NULL; update->log = WLog_Get("com.freerdp.core.update"); update->pointer = (rdpPointerUpdate*) calloc(1, sizeof(rdpPointerUpdate)); if (!update->pointer) goto fail; update->primary = (rdpPrimaryUpdate*) calloc(1, sizeof(rdpPrimaryUpdate)); if (!update->primary) goto fail; update->secondary = (rdpSecondaryUpdate*) calloc(1, sizeof(rdpSecondaryUpdate)); if (!update->secondary) goto fail; update->altsec = (rdpAltSecUpdate*) calloc(1, sizeof(rdpAltSecUpdate)); if (!update->altsec) goto fail; update->window = (rdpWindowUpdate*) calloc(1, sizeof(rdpWindowUpdate)); if (!update->window) goto fail; deleteList = &(update->altsec->create_offscreen_bitmap.deleteList); deleteList->sIndices = 64; deleteList->indices = calloc(deleteList->sIndices, 2); if (!deleteList->indices) goto fail; deleteList->cIndices = 0; update->SuppressOutput = update_send_suppress_output; update->initialState = TRUE; update->queue = MessageQueue_New(&cb); if (!update->queue) goto fail; return update; fail: update_free(update); return NULL; } void update_free(rdpUpdate* update) { if (update != NULL) { OFFSCREEN_DELETE_LIST* deleteList = &(update->altsec->create_offscreen_bitmap.deleteList); if (deleteList) free(deleteList->indices); free(update->pointer); if (update->primary) { free(update->primary->polyline.points); free(update->primary->polygon_sc.points); free(update->primary->fast_glyph.glyphData.aj); free(update->primary); } free(update->secondary); free(update->altsec); if (update->window) { free(update->window->monitored_desktop.windowIds); update_free_window_state(&update->window->window_state); update_free_window_icon_info(update->window->window_icon.iconInfo); free(update->window); } MessageQueue_Free(update->queue); free(update); } }
null
/** * FreeRDP: A Remote Desktop Protocol Implementation * Update Data PDUs * * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com> * Copyright 2016 Armin Novak <armin.novak@thincast.com> * Copyright 2016 Thincast Technologies GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <winpr/crt.h> #include <winpr/print.h> #include <winpr/synch.h> #include <winpr/thread.h> #include <winpr/collections.h> #include "update.h" #include "surface.h" #include "message.h" #include "info.h" #include "window.h" #include <freerdp/log.h> #include <freerdp/peer.h> #include <freerdp/codec/bitmap.h> #include "../cache/pointer.h" #include "../cache/palette.h" #include "../cache/bitmap.h" #define TAG FREERDP_TAG("core.update") static const char* const UPDATE_TYPE_STRINGS[] = { "Orders", "Bitmap", "Palette", "Synchronize" }; static const char* update_type_to_string(UINT16 updateType) { if (updateType >= ARRAYSIZE(UPDATE_TYPE_STRINGS)) return "UNKNOWN"; return UPDATE_TYPE_STRINGS[updateType]; } static BOOL update_recv_orders(rdpUpdate* update, wStream* s) { UINT16 numberOrders; if (Stream_GetRemainingLength(s) < 6) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 6"); return FALSE; } Stream_Seek_UINT16(s); /* pad2OctetsA (2 bytes) */ Stream_Read_UINT16(s, numberOrders); /* numberOrders (2 bytes) */ Stream_Seek_UINT16(s); /* pad2OctetsB (2 bytes) */ while (numberOrders > 0) { if (!update_recv_order(update, s)) { WLog_ERR(TAG, "update_recv_order() failed"); return FALSE; } numberOrders--; } return TRUE; } static BOOL update_read_bitmap_data(rdpUpdate* update, wStream* s, BITMAP_DATA* bitmapData) { if (Stream_GetRemainingLength(s) < 18) return FALSE; Stream_Read_UINT16(s, bitmapData->destLeft); Stream_Read_UINT16(s, bitmapData->destTop); Stream_Read_UINT16(s, bitmapData->destRight); Stream_Read_UINT16(s, bitmapData->destBottom); Stream_Read_UINT16(s, bitmapData->width); Stream_Read_UINT16(s, bitmapData->height); Stream_Read_UINT16(s, bitmapData->bitsPerPixel); Stream_Read_UINT16(s, bitmapData->flags); Stream_Read_UINT16(s, bitmapData->bitmapLength); if (bitmapData->flags & BITMAP_COMPRESSION) { if (!(bitmapData->flags & NO_BITMAP_COMPRESSION_HDR)) { Stream_Read_UINT16(s, bitmapData->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbScanWidth); /* cbScanWidth (2 bytes) */ Stream_Read_UINT16(s, bitmapData->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */ bitmapData->bitmapLength = bitmapData->cbCompMainBodySize; } bitmapData->compressed = TRUE; } else bitmapData->compressed = FALSE; if (Stream_GetRemainingLength(s) < bitmapData->bitmapLength) return FALSE; if (bitmapData->bitmapLength > 0) { bitmapData->bitmapDataStream = malloc(bitmapData->bitmapLength); if (!bitmapData->bitmapDataStream) return FALSE; memcpy(bitmapData->bitmapDataStream, Stream_Pointer(s), bitmapData->bitmapLength); Stream_Seek(s, bitmapData->bitmapLength); } return TRUE; } static BOOL update_write_bitmap_data(rdpUpdate* update, wStream* s, BITMAP_DATA* bitmapData) { if (!Stream_EnsureRemainingCapacity(s, 64 + bitmapData->bitmapLength)) return FALSE; bitmapData->flags = 0; bitmapData->cbCompFirstRowSize = 0; if (bitmapData->compressed) bitmapData->flags |= BITMAP_COMPRESSION; if (update->context->settings->NoBitmapCompressionHeader) { bitmapData->flags |= NO_BITMAP_COMPRESSION_HDR; bitmapData->cbCompMainBodySize = bitmapData->bitmapLength; } Stream_Write_UINT16(s, bitmapData->destLeft); Stream_Write_UINT16(s, bitmapData->destTop); Stream_Write_UINT16(s, bitmapData->destRight); Stream_Write_UINT16(s, bitmapData->destBottom); Stream_Write_UINT16(s, bitmapData->width); Stream_Write_UINT16(s, bitmapData->height); Stream_Write_UINT16(s, bitmapData->bitsPerPixel); Stream_Write_UINT16(s, bitmapData->flags); Stream_Write_UINT16(s, bitmapData->bitmapLength); if (bitmapData->flags & BITMAP_COMPRESSION) { if (!(bitmapData->flags & NO_BITMAP_COMPRESSION_HDR)) { Stream_Write_UINT16(s, bitmapData->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */ Stream_Write_UINT16(s, bitmapData->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */ Stream_Write_UINT16(s, bitmapData->cbScanWidth); /* cbScanWidth (2 bytes) */ Stream_Write_UINT16(s, bitmapData->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */ } Stream_Write(s, bitmapData->bitmapDataStream, bitmapData->bitmapLength); } else { Stream_Write(s, bitmapData->bitmapDataStream, bitmapData->bitmapLength); } return TRUE; } BITMAP_UPDATE* update_read_bitmap_update(rdpUpdate* update, wStream* s) { UINT32 i; BITMAP_UPDATE* bitmapUpdate = calloc(1, sizeof(BITMAP_UPDATE)); if (!bitmapUpdate) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */ WLog_Print(update->log, WLOG_TRACE, "BitmapUpdate: %"PRIu32"", bitmapUpdate->number); if (bitmapUpdate->number > bitmapUpdate->count) { UINT32 count = bitmapUpdate->number * 2; BITMAP_DATA* newdata = (BITMAP_DATA*) realloc(bitmapUpdate->rectangles, sizeof(BITMAP_DATA) * count); if (!newdata) goto fail; bitmapUpdate->rectangles = newdata; ZeroMemory(&bitmapUpdate->rectangles[bitmapUpdate->count], sizeof(BITMAP_DATA) * (count - bitmapUpdate->count)); bitmapUpdate->count = count; } /* rectangles */ for (i = 0; i < bitmapUpdate->number; i++) { if (!update_read_bitmap_data(update, s, &bitmapUpdate->rectangles[i])) goto fail; } return bitmapUpdate; fail: free_bitmap_update(update->context, bitmapUpdate); return NULL; } static BOOL update_write_bitmap_update(rdpUpdate* update, wStream* s, const BITMAP_UPDATE* bitmapUpdate) { int i; if (!Stream_EnsureRemainingCapacity(s, 32)) return FALSE; Stream_Write_UINT16(s, UPDATE_TYPE_BITMAP); /* updateType */ Stream_Write_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */ /* rectangles */ for (i = 0; i < (int) bitmapUpdate->number; i++) { if (!update_write_bitmap_data(update, s, &bitmapUpdate->rectangles[i])) return FALSE; } return TRUE; } PALETTE_UPDATE* update_read_palette(rdpUpdate* update, wStream* s) { int i; PALETTE_ENTRY* entry; PALETTE_UPDATE* palette_update = calloc(1, sizeof(PALETTE_UPDATE)); if (!palette_update) goto fail; if (Stream_GetRemainingLength(s) < 6) goto fail; Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */ Stream_Read_UINT32(s, palette_update->number); /* numberColors (4 bytes), must be set to 256 */ if (palette_update->number > 256) palette_update->number = 256; if (Stream_GetRemainingLength(s) < palette_update->number * 3) goto fail; /* paletteEntries */ for (i = 0; i < (int) palette_update->number; i++) { entry = &palette_update->entries[i]; Stream_Read_UINT8(s, entry->red); Stream_Read_UINT8(s, entry->green); Stream_Read_UINT8(s, entry->blue); } return palette_update; fail: free_palette_update(update->context, palette_update); return NULL; } static void update_read_synchronize(rdpUpdate* update, wStream* s) { Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */ /** * The Synchronize Update is an artifact from the * T.128 protocol and should be ignored. */ } static BOOL update_read_play_sound(wStream* s, PLAY_SOUND_UPDATE* play_sound) { if (Stream_GetRemainingLength(s) < 8) return FALSE; Stream_Read_UINT32(s, play_sound->duration); /* duration (4 bytes) */ Stream_Read_UINT32(s, play_sound->frequency); /* frequency (4 bytes) */ return TRUE; } BOOL update_recv_play_sound(rdpUpdate* update, wStream* s) { PLAY_SOUND_UPDATE play_sound; if (!update_read_play_sound(s, &play_sound)) return FALSE; return IFCALLRESULT(FALSE, update->PlaySound, update->context, &play_sound); } POINTER_POSITION_UPDATE* update_read_pointer_position(rdpUpdate* update, wStream* s) { POINTER_POSITION_UPDATE* pointer_position = calloc(1, sizeof(POINTER_POSITION_UPDATE)); if (!pointer_position) goto fail; if (Stream_GetRemainingLength(s) < 4) goto fail; Stream_Read_UINT16(s, pointer_position->xPos); /* xPos (2 bytes) */ Stream_Read_UINT16(s, pointer_position->yPos); /* yPos (2 bytes) */ return pointer_position; fail: free_pointer_position_update(update->context, pointer_position); return NULL; } POINTER_SYSTEM_UPDATE* update_read_pointer_system(rdpUpdate* update, wStream* s) { POINTER_SYSTEM_UPDATE* pointer_system = calloc(1, sizeof(POINTER_SYSTEM_UPDATE)); if (!pointer_system) goto fail; if (Stream_GetRemainingLength(s) < 4) goto fail; Stream_Read_UINT32(s, pointer_system->type); /* systemPointerType (4 bytes) */ return pointer_system; fail: free_pointer_system_update(update->context, pointer_system); return NULL; } static BOOL _update_read_pointer_color(wStream* s, POINTER_COLOR_UPDATE* pointer_color, BYTE xorBpp) { BYTE* newMask; UINT32 scanlineSize; if (!pointer_color) goto fail; if (Stream_GetRemainingLength(s) < 14) goto fail; Stream_Read_UINT16(s, pointer_color->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Read_UINT16(s, pointer_color->xPos); /* xPos (2 bytes) */ Stream_Read_UINT16(s, pointer_color->yPos); /* yPos (2 bytes) */ /** * As stated in 2.2.9.1.1.4.4 Color Pointer Update: * The maximum allowed pointer width/height is 96 pixels if the client indicated support * for large pointers by setting the LARGE_POINTER_FLAG (0x00000001) in the Large * Pointer Capability Set (section 2.2.7.2.7). If the LARGE_POINTER_FLAG was not * set, the maximum allowed pointer width/height is 32 pixels. * * So we check for a maximum of 96 for CVE-2014-0250. */ Stream_Read_UINT16(s, pointer_color->width); /* width (2 bytes) */ Stream_Read_UINT16(s, pointer_color->height); /* height (2 bytes) */ if ((pointer_color->width > 96) || (pointer_color->height > 96)) goto fail; Stream_Read_UINT16(s, pointer_color->lengthAndMask); /* lengthAndMask (2 bytes) */ Stream_Read_UINT16(s, pointer_color->lengthXorMask); /* lengthXorMask (2 bytes) */ /** * There does not seem to be any documentation on why * xPos / yPos can be larger than width / height * so it is missing in documentation or a bug in implementation * 2.2.9.1.1.4.4 Color Pointer Update (TS_COLORPOINTERATTRIBUTE) */ if (pointer_color->xPos >= pointer_color->width) pointer_color->xPos = 0; if (pointer_color->yPos >= pointer_color->height) pointer_color->yPos = 0; if (pointer_color->lengthXorMask > 0) { /** * Spec states that: * * xorMaskData (variable): A variable-length array of bytes. Contains the 24-bpp, bottom-up * XOR mask scan-line data. The XOR mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 3x3 pixel cursor is being sent, then each scan-line will consume 10 * bytes (3 pixels per scan-line multiplied by 3 bytes per pixel, rounded up to the next even * number of bytes). * * In fact instead of 24-bpp, the bpp parameter is given by the containing packet. */ if (Stream_GetRemainingLength(s) < pointer_color->lengthXorMask) goto fail; scanlineSize = (7 + xorBpp * pointer_color->width) / 8; scanlineSize = ((scanlineSize + 1) / 2) * 2; if (scanlineSize * pointer_color->height != pointer_color->lengthXorMask) { WLog_ERR(TAG, "invalid lengthXorMask: width=%"PRIu32" height=%"PRIu32", %"PRIu32" instead of %"PRIu32"", pointer_color->width, pointer_color->height, pointer_color->lengthXorMask, scanlineSize * pointer_color->height); goto fail; } newMask = realloc(pointer_color->xorMaskData, pointer_color->lengthXorMask); if (!newMask) goto fail; pointer_color->xorMaskData = newMask; Stream_Read(s, pointer_color->xorMaskData, pointer_color->lengthXorMask); } if (pointer_color->lengthAndMask > 0) { /** * andMaskData (variable): A variable-length array of bytes. Contains the 1-bpp, bottom-up * AND mask scan-line data. The AND mask is padded to a 2-byte boundary for each encoded * scan-line. For example, if a 7x7 pixel cursor is being sent, then each scan-line will consume 2 * bytes (7 pixels per scan-line multiplied by 1 bpp, rounded up to the next even number of * bytes). */ if (Stream_GetRemainingLength(s) < pointer_color->lengthAndMask) goto fail; scanlineSize = ((7 + pointer_color->width) / 8); scanlineSize = ((1 + scanlineSize) / 2) * 2; if (scanlineSize * pointer_color->height != pointer_color->lengthAndMask) { WLog_ERR(TAG, "invalid lengthAndMask: %"PRIu32" instead of %"PRIu32"", pointer_color->lengthAndMask, scanlineSize * pointer_color->height); goto fail; } newMask = realloc(pointer_color->andMaskData, pointer_color->lengthAndMask); if (!newMask) goto fail; pointer_color->andMaskData = newMask; Stream_Read(s, pointer_color->andMaskData, pointer_color->lengthAndMask); } if (Stream_GetRemainingLength(s) > 0) Stream_Seek_UINT8(s); /* pad (1 byte) */ return TRUE; fail: return FALSE; } POINTER_COLOR_UPDATE* update_read_pointer_color(rdpUpdate* update, wStream* s, BYTE xorBpp) { POINTER_COLOR_UPDATE* pointer_color = calloc(1, sizeof(POINTER_COLOR_UPDATE)); if (!pointer_color) goto fail; if (!_update_read_pointer_color(s, pointer_color, xorBpp)) goto fail; return pointer_color; fail: free_pointer_color_update(update->context, pointer_color); return NULL; } POINTER_NEW_UPDATE* update_read_pointer_new(rdpUpdate* update, wStream* s) { POINTER_NEW_UPDATE* pointer_new = calloc(1, sizeof(POINTER_NEW_UPDATE)); if (!pointer_new) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, pointer_new->xorBpp); /* xorBpp (2 bytes) */ if ((pointer_new->xorBpp < 1) || (pointer_new->xorBpp > 32)) { WLog_ERR(TAG, "invalid xorBpp %"PRIu32"", pointer_new->xorBpp); goto fail; } if (!_update_read_pointer_color(s, &pointer_new->colorPtrAttr, pointer_new->xorBpp)) /* colorPtrAttr */ goto fail; return pointer_new; fail: free_pointer_new_update(update->context, pointer_new); return NULL; } POINTER_CACHED_UPDATE* update_read_pointer_cached(rdpUpdate* update, wStream* s) { POINTER_CACHED_UPDATE* pointer = calloc(1, sizeof(POINTER_CACHED_UPDATE)); if (!pointer) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, pointer->cacheIndex); /* cacheIndex (2 bytes) */ return pointer; fail: free_pointer_cached_update(update->context, pointer); return NULL; } BOOL update_recv_pointer(rdpUpdate* update, wStream* s) { BOOL rc = FALSE; UINT16 messageType; rdpContext* context = update->context; rdpPointerUpdate* pointer = update->pointer; if (Stream_GetRemainingLength(s) < 2 + 2) return FALSE; Stream_Read_UINT16(s, messageType); /* messageType (2 bytes) */ Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */ switch (messageType) { case PTR_MSG_TYPE_POSITION: { POINTER_POSITION_UPDATE* pointer_position = update_read_pointer_position(update, s); if (pointer_position) { rc = IFCALLRESULT(FALSE, pointer->PointerPosition, context, pointer_position); free_pointer_position_update(context, pointer_position); } } break; case PTR_MSG_TYPE_SYSTEM: { POINTER_SYSTEM_UPDATE* pointer_system = update_read_pointer_system(update, s); if (pointer_system) { rc = IFCALLRESULT(FALSE, pointer->PointerSystem, context, pointer_system); free_pointer_system_update(context, pointer_system); } } break; case PTR_MSG_TYPE_COLOR: { POINTER_COLOR_UPDATE* pointer_color = update_read_pointer_color(update, s, 24); if (pointer_color) { rc = IFCALLRESULT(FALSE, pointer->PointerColor, context, pointer_color); free_pointer_color_update(context, pointer_color); } } break; case PTR_MSG_TYPE_POINTER: { POINTER_NEW_UPDATE* pointer_new = update_read_pointer_new(update, s); if (pointer_new) { rc = IFCALLRESULT(FALSE, pointer->PointerNew, context, pointer_new); free_pointer_new_update(context, pointer_new); } } break; case PTR_MSG_TYPE_CACHED: { POINTER_CACHED_UPDATE* pointer_cached = update_read_pointer_cached(update, s); if (pointer_cached) { rc = IFCALLRESULT(FALSE, pointer->PointerCached, context, pointer_cached); free_pointer_cached_update(context, pointer_cached); } } break; default: break; } return rc; } BOOL update_recv(rdpUpdate* update, wStream* s) { BOOL rc = FALSE; UINT16 updateType; rdpContext* context = update->context; if (Stream_GetRemainingLength(s) < 2) { WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 2"); return FALSE; } Stream_Read_UINT16(s, updateType); /* updateType (2 bytes) */ WLog_Print(update->log, WLOG_TRACE, "%s Update Data PDU", UPDATE_TYPE_STRINGS[updateType]); if (!IFCALLRESULT(TRUE, update->BeginPaint, context)) return FALSE; switch (updateType) { case UPDATE_TYPE_ORDERS: rc = update_recv_orders(update, s); break; case UPDATE_TYPE_BITMAP: { BITMAP_UPDATE* bitmap_update = update_read_bitmap_update(update, s); if (!bitmap_update) { WLog_ERR(TAG, "UPDATE_TYPE_BITMAP - update_read_bitmap_update() failed"); return FALSE; } rc = IFCALLRESULT(FALSE, update->BitmapUpdate, context, bitmap_update); free_bitmap_update(update->context, bitmap_update); } break; case UPDATE_TYPE_PALETTE: { PALETTE_UPDATE* palette_update = update_read_palette(update, s); if (!palette_update) { WLog_ERR(TAG, "UPDATE_TYPE_PALETTE - update_read_palette() failed"); return FALSE; } rc = IFCALLRESULT(FALSE, update->Palette, context, palette_update); free_palette_update(context, palette_update); } break; case UPDATE_TYPE_SYNCHRONIZE: update_read_synchronize(update, s); rc = IFCALLRESULT(TRUE, update->Synchronize, context); break; default: break; } if (!rc) { WLog_ERR(TAG, "UPDATE_TYPE %s [%"PRIu16"] failed", update_type_to_string(updateType), updateType); return FALSE; } if (!IFCALLRESULT(FALSE, update->EndPaint, context)) return FALSE; return TRUE; } void update_reset_state(rdpUpdate* update) { rdpPrimaryUpdate* primary = update->primary; rdpAltSecUpdate* altsec = update->altsec; if (primary->fast_glyph.glyphData.aj) { free(primary->fast_glyph.glyphData.aj); primary->fast_glyph.glyphData.aj = NULL; } ZeroMemory(&primary->order_info, sizeof(ORDER_INFO)); ZeroMemory(&primary->dstblt, sizeof(DSTBLT_ORDER)); ZeroMemory(&primary->patblt, sizeof(PATBLT_ORDER)); ZeroMemory(&primary->scrblt, sizeof(SCRBLT_ORDER)); ZeroMemory(&primary->opaque_rect, sizeof(OPAQUE_RECT_ORDER)); ZeroMemory(&primary->draw_nine_grid, sizeof(DRAW_NINE_GRID_ORDER)); ZeroMemory(&primary->multi_dstblt, sizeof(MULTI_DSTBLT_ORDER)); ZeroMemory(&primary->multi_patblt, sizeof(MULTI_PATBLT_ORDER)); ZeroMemory(&primary->multi_scrblt, sizeof(MULTI_SCRBLT_ORDER)); ZeroMemory(&primary->multi_opaque_rect, sizeof(MULTI_OPAQUE_RECT_ORDER)); ZeroMemory(&primary->multi_draw_nine_grid, sizeof(MULTI_DRAW_NINE_GRID_ORDER)); ZeroMemory(&primary->line_to, sizeof(LINE_TO_ORDER)); ZeroMemory(&primary->polyline, sizeof(POLYLINE_ORDER)); ZeroMemory(&primary->memblt, sizeof(MEMBLT_ORDER)); ZeroMemory(&primary->mem3blt, sizeof(MEM3BLT_ORDER)); ZeroMemory(&primary->save_bitmap, sizeof(SAVE_BITMAP_ORDER)); ZeroMemory(&primary->glyph_index, sizeof(GLYPH_INDEX_ORDER)); ZeroMemory(&primary->fast_index, sizeof(FAST_INDEX_ORDER)); ZeroMemory(&primary->fast_glyph, sizeof(FAST_GLYPH_ORDER)); ZeroMemory(&primary->polygon_sc, sizeof(POLYGON_SC_ORDER)); ZeroMemory(&primary->polygon_cb, sizeof(POLYGON_CB_ORDER)); ZeroMemory(&primary->ellipse_sc, sizeof(ELLIPSE_SC_ORDER)); ZeroMemory(&primary->ellipse_cb, sizeof(ELLIPSE_CB_ORDER)); primary->order_info.orderType = ORDER_TYPE_PATBLT; if (!update->initialState) { altsec->switch_surface.bitmapId = SCREEN_BITMAP_SURFACE; IFCALL(altsec->SwitchSurface, update->context, &(altsec->switch_surface)); } } BOOL update_post_connect(rdpUpdate* update) { update->asynchronous = update->context->settings->AsyncUpdate; if (update->asynchronous) if (!(update->proxy = update_message_proxy_new(update))) return FALSE; update->altsec->switch_surface.bitmapId = SCREEN_BITMAP_SURFACE; IFCALL(update->altsec->SwitchSurface, update->context, &(update->altsec->switch_surface)); update->initialState = FALSE; return TRUE; } void update_post_disconnect(rdpUpdate* update) { update->asynchronous = update->context->settings->AsyncUpdate; if (update->asynchronous) update_message_proxy_free(update->proxy); update->initialState = TRUE; } static BOOL update_begin_paint(rdpContext* context) { wStream* s; rdpUpdate* update = context->update; if (update->us) update->EndPaint(context); s = fastpath_update_pdu_init_new(context->rdp->fastpath); if (!s) return FALSE; Stream_SealLength(s); Stream_Seek(s, 2); /* numberOrders (2 bytes) */ update->combineUpdates = TRUE; update->numberOrders = 0; update->us = s; return TRUE; } static BOOL update_end_paint(rdpContext* context) { wStream* s; int headerLength; rdpUpdate* update = context->update; if (!update->us) return FALSE; s = update->us; headerLength = Stream_Length(s); Stream_SealLength(s); Stream_SetPosition(s, headerLength); Stream_Write_UINT16(s, update->numberOrders); /* numberOrders (2 bytes) */ Stream_SetPosition(s, Stream_Length(s)); if (update->numberOrders > 0) { WLog_ERR(TAG, "sending %"PRIu16" orders", update->numberOrders); fastpath_send_update_pdu(context->rdp->fastpath, FASTPATH_UPDATETYPE_ORDERS, s, FALSE); } update->combineUpdates = FALSE; update->numberOrders = 0; update->us = NULL; Stream_Free(s, TRUE); return TRUE; } static void update_flush(rdpContext* context) { rdpUpdate* update = context->update; if (update->numberOrders > 0) { update->EndPaint(context); update->BeginPaint(context); } } static void update_force_flush(rdpContext* context) { rdpUpdate* update = context->update; if (update->numberOrders > 0) { update->EndPaint(context); update->BeginPaint(context); } } static BOOL update_check_flush(rdpContext* context, int size) { wStream* s; rdpUpdate* update = context->update; s = update->us; if (!update->us) { update->BeginPaint(context); return FALSE; } if (Stream_GetPosition(s) + size + 64 >= 0x3FFF) { update_flush(context); return TRUE; } return FALSE; } static BOOL update_set_bounds(rdpContext* context, const rdpBounds* bounds) { rdpUpdate* update = context->update; CopyMemory(&update->previousBounds, &update->currentBounds, sizeof(rdpBounds)); if (!bounds) ZeroMemory(&update->currentBounds, sizeof(rdpBounds)); else CopyMemory(&update->currentBounds, bounds, sizeof(rdpBounds)); return TRUE; } BOOL update_bounds_is_null(rdpBounds* bounds) { if ((bounds->left == 0) && (bounds->top == 0) && (bounds->right == 0) && (bounds->bottom == 0)) return TRUE; return FALSE; } BOOL update_bounds_equals(rdpBounds* bounds1, rdpBounds* bounds2) { if ((bounds1->left == bounds2->left) && (bounds1->top == bounds2->top) && (bounds1->right == bounds2->right) && (bounds1->bottom == bounds2->bottom)) return TRUE; return FALSE; } int update_prepare_bounds(rdpContext* context, ORDER_INFO* orderInfo) { int length = 0; rdpUpdate* update = context->update; orderInfo->boundsFlags = 0; if (update_bounds_is_null(&update->currentBounds)) return 0; orderInfo->controlFlags |= ORDER_BOUNDS; if (update_bounds_equals(&update->previousBounds, &update->currentBounds)) { orderInfo->controlFlags |= ORDER_ZERO_BOUNDS_DELTAS; return 0; } else { length += 1; if (update->previousBounds.left != update->currentBounds.left) { orderInfo->bounds.left = update->currentBounds.left; orderInfo->boundsFlags |= BOUND_LEFT; length += 2; } if (update->previousBounds.top != update->currentBounds.top) { orderInfo->bounds.top = update->currentBounds.top; orderInfo->boundsFlags |= BOUND_TOP; length += 2; } if (update->previousBounds.right != update->currentBounds.right) { orderInfo->bounds.right = update->currentBounds.right; orderInfo->boundsFlags |= BOUND_RIGHT; length += 2; } if (update->previousBounds.bottom != update->currentBounds.bottom) { orderInfo->bounds.bottom = update->currentBounds.bottom; orderInfo->boundsFlags |= BOUND_BOTTOM; length += 2; } } return length; } static int update_prepare_order_info(rdpContext* context, ORDER_INFO* orderInfo, UINT32 orderType) { int length = 1; orderInfo->fieldFlags = 0; orderInfo->orderType = orderType; orderInfo->controlFlags = ORDER_STANDARD; orderInfo->controlFlags |= ORDER_TYPE_CHANGE; length += 1; length += PRIMARY_DRAWING_ORDER_FIELD_BYTES[orderInfo->orderType]; length += update_prepare_bounds(context, orderInfo); return length; } int update_write_order_info(rdpContext* context, wStream* s, ORDER_INFO* orderInfo, int offset) { size_t position; position = Stream_GetPosition(s); Stream_SetPosition(s, offset); Stream_Write_UINT8(s, orderInfo->controlFlags); /* controlFlags (1 byte) */ if (orderInfo->controlFlags & ORDER_TYPE_CHANGE) Stream_Write_UINT8(s, orderInfo->orderType); /* orderType (1 byte) */ update_write_field_flags(s, orderInfo->fieldFlags, orderInfo->controlFlags, PRIMARY_DRAWING_ORDER_FIELD_BYTES[orderInfo->orderType]); update_write_bounds(s, orderInfo); Stream_SetPosition(s, position); return 0; } static void update_write_refresh_rect(wStream* s, BYTE count, const RECTANGLE_16* areas) { int i; Stream_Write_UINT8(s, count); /* numberOfAreas (1 byte) */ Stream_Seek(s, 3); /* pad3Octets (3 bytes) */ for (i = 0; i < count; i++) { Stream_Write_UINT16(s, areas[i].left); /* left (2 bytes) */ Stream_Write_UINT16(s, areas[i].top); /* top (2 bytes) */ Stream_Write_UINT16(s, areas[i].right); /* right (2 bytes) */ Stream_Write_UINT16(s, areas[i].bottom); /* bottom (2 bytes) */ } } static BOOL update_send_refresh_rect(rdpContext* context, BYTE count, const RECTANGLE_16* areas) { rdpRdp* rdp = context->rdp; if (rdp->settings->RefreshRect) { wStream* s = rdp_data_pdu_init(rdp); if (!s) return FALSE; update_write_refresh_rect(s, count, areas); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_REFRESH_RECT, rdp->mcs->userId); } return TRUE; } static void update_write_suppress_output(wStream* s, BYTE allow, const RECTANGLE_16* area) { Stream_Write_UINT8(s, allow); /* allowDisplayUpdates (1 byte) */ /* Use zeros for padding (like mstsc) for compatibility with legacy servers */ Stream_Zero(s, 3); /* pad3Octets (3 bytes) */ if (allow > 0) { Stream_Write_UINT16(s, area->left); /* left (2 bytes) */ Stream_Write_UINT16(s, area->top); /* top (2 bytes) */ Stream_Write_UINT16(s, area->right); /* right (2 bytes) */ Stream_Write_UINT16(s, area->bottom); /* bottom (2 bytes) */ } } static BOOL update_send_suppress_output(rdpContext* context, BYTE allow, const RECTANGLE_16* area) { rdpRdp* rdp = context->rdp; if (rdp->settings->SuppressOutput) { wStream* s = rdp_data_pdu_init(rdp); if (!s) return FALSE; update_write_suppress_output(s, allow, area); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SUPPRESS_OUTPUT, rdp->mcs->userId); } return TRUE; } static BOOL update_send_surface_command(rdpContext* context, wStream* s) { wStream* update; rdpRdp* rdp = context->rdp; BOOL ret; update = fastpath_update_pdu_init(rdp->fastpath); if (!update) return FALSE; if (!Stream_EnsureRemainingCapacity(update, Stream_GetPosition(s))) { ret = FALSE; goto out; } Stream_Write(update, Stream_Buffer(s), Stream_GetPosition(s)); ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, update, FALSE); out: Stream_Release(update); return ret; } static BOOL update_send_surface_bits(rdpContext* context, const SURFACE_BITS_COMMAND* surfaceBitsCommand) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_surfcmd_surface_bits(s, surfaceBitsCommand)) goto out_fail; if (!fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s, surfaceBitsCommand->skipCompression)) goto out_fail; update_force_flush(context); ret = TRUE; out_fail: Stream_Release(s); return ret; } static BOOL update_send_surface_frame_marker(rdpContext* context, const SURFACE_FRAME_MARKER* surfaceFrameMarker) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_surfcmd_frame_marker(s, surfaceFrameMarker->frameAction, surfaceFrameMarker->frameId) || !fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s, FALSE)) goto out_fail; update_force_flush(context); ret = TRUE; out_fail: Stream_Release(s); return ret; } static BOOL update_send_surface_frame_bits(rdpContext* context, const SURFACE_BITS_COMMAND* cmd, BOOL first, BOOL last, UINT32 frameId) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (first) { if (!update_write_surfcmd_frame_marker(s, SURFACECMD_FRAMEACTION_BEGIN, frameId)) goto out_fail; } if (!update_write_surfcmd_surface_bits(s, cmd)) goto out_fail; if (last) { if (!update_write_surfcmd_frame_marker(s, SURFACECMD_FRAMEACTION_END, frameId)) goto out_fail; } ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SURFCMDS, s, cmd->skipCompression); update_force_flush(context); out_fail: Stream_Release(s); return ret; } static BOOL update_send_frame_acknowledge(rdpContext* context, UINT32 frameId) { rdpRdp* rdp = context->rdp; if (rdp->settings->ReceivedCapabilities[CAPSET_TYPE_FRAME_ACKNOWLEDGE]) { wStream* s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT32(s, frameId); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_FRAME_ACKNOWLEDGE, rdp->mcs->userId); } return TRUE; } static BOOL update_send_synchronize(rdpContext* context) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; Stream_Zero(s, 2); /* pad2Octets (2 bytes) */ ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_SYNCHRONIZE, s, FALSE); Stream_Release(s); return ret; } static BOOL update_send_desktop_resize(rdpContext* context) { return rdp_server_reactivate(context->rdp); } static BOOL update_send_bitmap_update(rdpContext* context, const BITMAP_UPDATE* bitmapUpdate) { wStream* s; rdpRdp* rdp = context->rdp; rdpUpdate* update = context->update; BOOL ret = TRUE; update_force_flush(context); s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_bitmap_update(update, s, bitmapUpdate) || !fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_BITMAP, s, bitmapUpdate->skipCompression)) { ret = FALSE; goto out_fail; } update_force_flush(context); out_fail: Stream_Release(s); return ret; } static BOOL update_send_play_sound(rdpContext* context, const PLAY_SOUND_UPDATE* play_sound) { wStream* s; rdpRdp* rdp = context->rdp; if (!rdp->settings->ReceivedCapabilities[CAPSET_TYPE_SOUND]) { return TRUE; } s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT32(s, play_sound->duration); Stream_Write_UINT32(s, play_sound->frequency); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_PLAY_SOUND, rdp->mcs->userId); } /** * Primary Drawing Orders */ static BOOL update_send_dstblt(rdpContext* context, const DSTBLT_ORDER* dstblt) { wStream* s; UINT32 offset; UINT32 headerLength; ORDER_INFO orderInfo; int inf; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_DSTBLT); inf = update_approximate_dstblt_order(&orderInfo, dstblt); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_dstblt_order(s, &orderInfo, dstblt)) return FALSE; update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_patblt(rdpContext* context, PATBLT_ORDER* patblt) { wStream* s; size_t offset; int headerLength; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_PATBLT); update_check_flush(context, headerLength + update_approximate_patblt_order(&orderInfo, patblt)); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_patblt_order(s, &orderInfo, patblt); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_scrblt(rdpContext* context, const SCRBLT_ORDER* scrblt) { wStream* s; UINT32 offset; UINT32 headerLength; ORDER_INFO orderInfo; int inf; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_SCRBLT); inf = update_approximate_scrblt_order(&orderInfo, scrblt); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return TRUE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_scrblt_order(s, &orderInfo, scrblt); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_opaque_rect(rdpContext* context, const OPAQUE_RECT_ORDER* opaque_rect) { wStream* s; size_t offset; int headerLength; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_OPAQUE_RECT); update_check_flush(context, headerLength + update_approximate_opaque_rect_order(&orderInfo, opaque_rect)); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_opaque_rect_order(s, &orderInfo, opaque_rect); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_line_to(rdpContext* context, const LINE_TO_ORDER* line_to) { wStream* s; int offset; int headerLength; ORDER_INFO orderInfo; int inf; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_LINE_TO); inf = update_approximate_line_to_order(&orderInfo, line_to); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_line_to_order(s, &orderInfo, line_to); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_memblt(rdpContext* context, MEMBLT_ORDER* memblt) { wStream* s; size_t offset; int headerLength; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_MEMBLT); update_check_flush(context, headerLength + update_approximate_memblt_order(&orderInfo, memblt)); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_memblt_order(s, &orderInfo, memblt); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } static BOOL update_send_glyph_index(rdpContext* context, GLYPH_INDEX_ORDER* glyph_index) { wStream* s; size_t offset; int headerLength; int inf; ORDER_INFO orderInfo; rdpUpdate* update = context->update; headerLength = update_prepare_order_info(context, &orderInfo, ORDER_TYPE_GLYPH_INDEX); inf = update_approximate_glyph_index_order(&orderInfo, glyph_index); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; offset = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); update_write_glyph_index_order(s, &orderInfo, glyph_index); update_write_order_info(context, s, &orderInfo, offset); update->numberOrders++; return TRUE; } /* * Secondary Drawing Orders */ static BOOL update_send_cache_bitmap(rdpContext* context, const CACHE_BITMAP_ORDER* cache_bitmap) { wStream* s; size_t bm, em; BYTE orderType; int headerLength; int inf; UINT16 extraFlags; INT16 orderLength; rdpUpdate* update = context->update; extraFlags = 0; headerLength = 6; orderType = cache_bitmap->compressed ? ORDER_TYPE_CACHE_BITMAP_COMPRESSED : ORDER_TYPE_BITMAP_UNCOMPRESSED; inf = update_approximate_cache_bitmap_order(cache_bitmap, cache_bitmap->compressed, &extraFlags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_bitmap_order(s, cache_bitmap, cache_bitmap->compressed, &extraFlags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_bitmap_v2(rdpContext* context, CACHE_BITMAP_V2_ORDER* cache_bitmap_v2) { wStream* s; size_t bm, em; BYTE orderType; int headerLength; UINT16 extraFlags; INT16 orderLength; rdpUpdate* update = context->update; extraFlags = 0; headerLength = 6; orderType = cache_bitmap_v2->compressed ? ORDER_TYPE_BITMAP_COMPRESSED_V2 : ORDER_TYPE_BITMAP_UNCOMPRESSED_V2; if (context->settings->NoBitmapCompressionHeader) cache_bitmap_v2->flags |= CBR2_NO_BITMAP_COMPRESSION_HDR; update_check_flush(context, headerLength + update_approximate_cache_bitmap_v2_order(cache_bitmap_v2, cache_bitmap_v2->compressed, &extraFlags)); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_bitmap_v2_order(s, cache_bitmap_v2, cache_bitmap_v2->compressed, &extraFlags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_bitmap_v3(rdpContext* context, CACHE_BITMAP_V3_ORDER* cache_bitmap_v3) { wStream* s; size_t bm, em; BYTE orderType; int headerLength; UINT16 extraFlags; INT16 orderLength; rdpUpdate* update = context->update; extraFlags = 0; headerLength = 6; orderType = ORDER_TYPE_BITMAP_COMPRESSED_V3; update_check_flush(context, headerLength + update_approximate_cache_bitmap_v3_order(cache_bitmap_v3, &extraFlags)); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_bitmap_v3_order(s, cache_bitmap_v3, &extraFlags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, orderType); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_color_table(rdpContext* context, const CACHE_COLOR_TABLE_ORDER* cache_color_table) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_color_table_order(cache_color_table, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_color_table_order(s, cache_color_table, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_COLOR_TABLE); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_glyph(rdpContext* context, const CACHE_GLYPH_ORDER* cache_glyph) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_glyph_order(cache_glyph, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_glyph_order(s, cache_glyph, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_GLYPH); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_glyph_v2(rdpContext* context, const CACHE_GLYPH_V2_ORDER* cache_glyph_v2) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_glyph_v2_order(cache_glyph_v2, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_glyph_v2_order(s, cache_glyph_v2, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_GLYPH); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_cache_brush(rdpContext* context, const CACHE_BRUSH_ORDER* cache_brush) { wStream* s; UINT16 flags; size_t bm, em, inf; int headerLength; INT16 orderLength; rdpUpdate* update = context->update; flags = 0; headerLength = 6; inf = update_approximate_cache_brush_order(cache_brush, &flags); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_cache_brush_order(s, cache_brush, &flags)) return FALSE; em = Stream_GetPosition(s); orderLength = (em - bm) - 13; Stream_SetPosition(s, bm); Stream_Write_UINT8(s, ORDER_STANDARD | ORDER_SECONDARY); /* controlFlags (1 byte) */ Stream_Write_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Write_UINT16(s, flags); /* extraFlags (2 bytes) */ Stream_Write_UINT8(s, ORDER_TYPE_CACHE_BRUSH); /* orderType (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } /** * Alternate Secondary Drawing Orders */ static BOOL update_send_create_offscreen_bitmap_order( rdpContext* context, const CREATE_OFFSCREEN_BITMAP_ORDER* create_offscreen_bitmap) { wStream* s; size_t bm, em, inf; BYTE orderType; BYTE controlFlags; int headerLength; rdpUpdate* update = context->update; headerLength = 1; orderType = ORDER_TYPE_CREATE_OFFSCREEN_BITMAP; controlFlags = ORDER_SECONDARY | (orderType << 2); inf = update_approximate_create_offscreen_bitmap_order( create_offscreen_bitmap); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_create_offscreen_bitmap_order(s, create_offscreen_bitmap)) return FALSE; em = Stream_GetPosition(s); Stream_SetPosition(s, bm); Stream_Write_UINT8(s, controlFlags); /* controlFlags (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_switch_surface_order( rdpContext* context, const SWITCH_SURFACE_ORDER* switch_surface) { wStream* s; size_t bm, em, inf; BYTE orderType; BYTE controlFlags; int headerLength; rdpUpdate* update; if (!context || !switch_surface || !context->update) return FALSE; update = context->update; headerLength = 1; orderType = ORDER_TYPE_SWITCH_SURFACE; controlFlags = ORDER_SECONDARY | (orderType << 2); inf = update_approximate_switch_surface_order(switch_surface); update_check_flush(context, headerLength + inf); s = update->us; if (!s) return FALSE; bm = Stream_GetPosition(s); if (!Stream_EnsureRemainingCapacity(s, headerLength)) return FALSE; Stream_Seek(s, headerLength); if (!update_write_switch_surface_order(s, switch_surface)) return FALSE; em = Stream_GetPosition(s); Stream_SetPosition(s, bm); Stream_Write_UINT8(s, controlFlags); /* controlFlags (1 byte) */ Stream_SetPosition(s, em); update->numberOrders++; return TRUE; } static BOOL update_send_pointer_system(rdpContext* context, const POINTER_SYSTEM_UPDATE* pointer_system) { wStream* s; BYTE updateCode; rdpRdp* rdp = context->rdp; BOOL ret; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (pointer_system->type == SYSPTR_NULL) updateCode = FASTPATH_UPDATETYPE_PTR_NULL; else updateCode = FASTPATH_UPDATETYPE_PTR_DEFAULT; ret = fastpath_send_update_pdu(rdp->fastpath, updateCode, s, FALSE); Stream_Release(s); return ret; } static BOOL update_send_pointer_position(rdpContext* context, const POINTER_POSITION_UPDATE* pointerPosition) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, 16)) goto out_fail; Stream_Write_UINT16(s, pointerPosition->xPos); /* xPos (2 bytes) */ Stream_Write_UINT16(s, pointerPosition->yPos); /* yPos (2 bytes) */ ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_PTR_POSITION, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_write_pointer_color(wStream* s, const POINTER_COLOR_UPDATE* pointer_color) { if (!Stream_EnsureRemainingCapacity(s, 32 + pointer_color->lengthAndMask + pointer_color->lengthXorMask)) return FALSE; Stream_Write_UINT16(s, pointer_color->cacheIndex); Stream_Write_UINT16(s, pointer_color->xPos); Stream_Write_UINT16(s, pointer_color->yPos); Stream_Write_UINT16(s, pointer_color->width); Stream_Write_UINT16(s, pointer_color->height); Stream_Write_UINT16(s, pointer_color->lengthAndMask); Stream_Write_UINT16(s, pointer_color->lengthXorMask); if (pointer_color->lengthXorMask > 0) Stream_Write(s, pointer_color->xorMaskData, pointer_color->lengthXorMask); if (pointer_color->lengthAndMask > 0) Stream_Write(s, pointer_color->andMaskData, pointer_color->lengthAndMask); Stream_Write_UINT8(s, 0); /* pad (1 byte) */ return TRUE; } static BOOL update_send_pointer_color(rdpContext* context, const POINTER_COLOR_UPDATE* pointer_color) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_pointer_color(s, pointer_color)) goto out_fail; ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_COLOR, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_send_pointer_new(rdpContext* context, const POINTER_NEW_UPDATE* pointer_new) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!Stream_EnsureRemainingCapacity(s, 16)) goto out_fail; Stream_Write_UINT16(s, pointer_new->xorBpp); /* xorBpp (2 bytes) */ update_write_pointer_color(s, &pointer_new->colorPtrAttr); ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_POINTER, s, FALSE); out_fail: Stream_Release(s); return ret; } static BOOL update_send_pointer_cached(rdpContext* context, const POINTER_CACHED_UPDATE* pointer_cached) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; Stream_Write_UINT16(s, pointer_cached->cacheIndex); /* cacheIndex (2 bytes) */ ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_CACHED, s, FALSE); Stream_Release(s); return ret; } BOOL update_read_refresh_rect(rdpUpdate* update, wStream* s) { int index; BYTE numberOfAreas; RECTANGLE_16* areas; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT8(s, numberOfAreas); Stream_Seek(s, 3); /* pad3Octects */ if (Stream_GetRemainingLength(s) < ((size_t) numberOfAreas * 4 * 2)) return FALSE; areas = (RECTANGLE_16*) calloc(numberOfAreas, sizeof(RECTANGLE_16)); if (!areas) return FALSE; for (index = 0; index < numberOfAreas; index++) { Stream_Read_UINT16(s, areas[index].left); Stream_Read_UINT16(s, areas[index].top); Stream_Read_UINT16(s, areas[index].right); Stream_Read_UINT16(s, areas[index].bottom); } if (update->context->settings->RefreshRect) IFCALL(update->RefreshRect, update->context, numberOfAreas, areas); else WLog_Print(update->log, WLOG_WARN, "ignoring refresh rect request from client"); free(areas); return TRUE; } BOOL update_read_suppress_output(rdpUpdate* update, wStream* s) { BYTE allowDisplayUpdates; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT8(s, allowDisplayUpdates); Stream_Seek(s, 3); /* pad3Octects */ if (allowDisplayUpdates > 0 && Stream_GetRemainingLength(s) < 8) return FALSE; if (update->context->settings->SuppressOutput) IFCALL(update->SuppressOutput, update->context, allowDisplayUpdates, allowDisplayUpdates > 0 ? (RECTANGLE_16*) Stream_Pointer(s) : NULL); else WLog_Print(update->log, WLOG_WARN, "ignoring suppress output request from client"); return TRUE; } static BOOL update_send_set_keyboard_indicators(rdpContext* context, UINT16 led_flags) { wStream* s; rdpRdp* rdp = context->rdp; s = rdp_data_pdu_init(rdp); if (!s) return FALSE; Stream_Write_UINT16(s, 0); /* unitId should be 0 according to MS-RDPBCGR 2.2.8.2.1.1 */ Stream_Write_UINT16(s, led_flags); /* ledFlags (2 bytes) */ return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SET_KEYBOARD_INDICATORS, rdp->mcs->userId); } static BOOL update_send_set_keyboard_ime_status(rdpContext* context, UINT16 imeId, UINT32 imeState, UINT32 imeConvMode) { wStream* s; rdpRdp* rdp = context->rdp; s = rdp_data_pdu_init(rdp); if (!s) return FALSE; /* unitId should be 0 according to MS-RDPBCGR 2.2.8.2.2.1 */ Stream_Write_UINT16(s, imeId); Stream_Write_UINT32(s, imeState); Stream_Write_UINT32(s, imeConvMode); return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_SET_KEYBOARD_IME_STATUS, rdp->mcs->userId); } void update_register_server_callbacks(rdpUpdate* update) { update->BeginPaint = update_begin_paint; update->EndPaint = update_end_paint; update->SetBounds = update_set_bounds; update->Synchronize = update_send_synchronize; update->DesktopResize = update_send_desktop_resize; update->BitmapUpdate = update_send_bitmap_update; update->SurfaceBits = update_send_surface_bits; update->SurfaceFrameMarker = update_send_surface_frame_marker; update->SurfaceCommand = update_send_surface_command; update->SurfaceFrameBits = update_send_surface_frame_bits; update->PlaySound = update_send_play_sound; update->SetKeyboardIndicators = update_send_set_keyboard_indicators; update->SetKeyboardImeStatus = update_send_set_keyboard_ime_status; update->SaveSessionInfo = rdp_send_save_session_info; update->primary->DstBlt = update_send_dstblt; update->primary->PatBlt = update_send_patblt; update->primary->ScrBlt = update_send_scrblt; update->primary->OpaqueRect = update_send_opaque_rect; update->primary->LineTo = update_send_line_to; update->primary->MemBlt = update_send_memblt; update->primary->GlyphIndex = update_send_glyph_index; update->secondary->CacheBitmap = update_send_cache_bitmap; update->secondary->CacheBitmapV2 = update_send_cache_bitmap_v2; update->secondary->CacheBitmapV3 = update_send_cache_bitmap_v3; update->secondary->CacheColorTable = update_send_cache_color_table; update->secondary->CacheGlyph = update_send_cache_glyph; update->secondary->CacheGlyphV2 = update_send_cache_glyph_v2; update->secondary->CacheBrush = update_send_cache_brush; update->altsec->CreateOffscreenBitmap = update_send_create_offscreen_bitmap_order; update->altsec->SwitchSurface = update_send_switch_surface_order; update->pointer->PointerSystem = update_send_pointer_system; update->pointer->PointerPosition = update_send_pointer_position; update->pointer->PointerColor = update_send_pointer_color; update->pointer->PointerNew = update_send_pointer_new; update->pointer->PointerCached = update_send_pointer_cached; } void update_register_client_callbacks(rdpUpdate* update) { update->RefreshRect = update_send_refresh_rect; update->SuppressOutput = update_send_suppress_output; update->SurfaceFrameAcknowledge = update_send_frame_acknowledge; } int update_process_messages(rdpUpdate* update) { return update_message_queue_process_pending_messages(update); } static void update_free_queued_message(void* obj) { wMessage* msg = (wMessage*)obj; update_message_queue_free_message(msg); } static void update_free_window_state(WINDOW_STATE_ORDER* window_state) { if (!window_state) return; free(window_state->titleInfo.string); window_state->titleInfo.string = NULL; free(window_state->windowRects); window_state->windowRects = NULL; free(window_state->visibilityRects); window_state->visibilityRects = NULL; } rdpUpdate* update_new(rdpRdp* rdp) { const wObject cb = { NULL, NULL, NULL, update_free_queued_message, NULL }; rdpUpdate* update; OFFSCREEN_DELETE_LIST* deleteList; update = (rdpUpdate*) calloc(1, sizeof(rdpUpdate)); if (!update) return NULL; update->log = WLog_Get("com.freerdp.core.update"); update->pointer = (rdpPointerUpdate*) calloc(1, sizeof(rdpPointerUpdate)); if (!update->pointer) goto fail; update->primary = (rdpPrimaryUpdate*) calloc(1, sizeof(rdpPrimaryUpdate)); if (!update->primary) goto fail; update->secondary = (rdpSecondaryUpdate*) calloc(1, sizeof(rdpSecondaryUpdate)); if (!update->secondary) goto fail; update->altsec = (rdpAltSecUpdate*) calloc(1, sizeof(rdpAltSecUpdate)); if (!update->altsec) goto fail; update->window = (rdpWindowUpdate*) calloc(1, sizeof(rdpWindowUpdate)); if (!update->window) goto fail; deleteList = &(update->altsec->create_offscreen_bitmap.deleteList); deleteList->sIndices = 64; deleteList->indices = calloc(deleteList->sIndices, 2); if (!deleteList->indices) goto fail; deleteList->cIndices = 0; update->SuppressOutput = update_send_suppress_output; update->initialState = TRUE; update->queue = MessageQueue_New(&cb); if (!update->queue) goto fail; return update; fail: update_free(update); return NULL; } void update_free(rdpUpdate* update) { if (update != NULL) { OFFSCREEN_DELETE_LIST* deleteList = &(update->altsec->create_offscreen_bitmap.deleteList); if (deleteList) free(deleteList->indices); free(update->pointer); if (update->primary) { free(update->primary->polyline.points); free(update->primary->polygon_sc.points); free(update->primary->fast_glyph.glyphData.aj); free(update->primary); } free(update->secondary); free(update->altsec); if (update->window) { free(update->window->monitored_desktop.windowIds); update_free_window_state(&update->window->window_state); update_free_window_icon_info(update->window->window_icon.iconInfo); free(update->window); } MessageQueue_Free(update->queue); free(update); } }
null
101
CWE-787
CVE-2018-8787
/** * FreeRDP: A Remote Desktop Protocol Implementation * Graphical Objects * * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com> * Copyright 2016 Armin Novak <armin.novak@thincast.com> * Copyright 2016 Thincast Technologies GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <winpr/crt.h> #include <freerdp/log.h> #include <freerdp/gdi/dc.h> #include <freerdp/gdi/shape.h> #include <freerdp/gdi/region.h> #include <freerdp/gdi/bitmap.h> #include "clipping.h" #include "drawing.h" #include "brush.h" #include "graphics.h" #define TAG FREERDP_TAG("gdi") /* Bitmap Class */ HGDI_BITMAP gdi_create_bitmap(rdpGdi* gdi, UINT32 nWidth, UINT32 nHeight, UINT32 SrcFormat, BYTE* data) { UINT32 nSrcStep; UINT32 nDstStep; BYTE* pSrcData; BYTE* pDstData; HGDI_BITMAP bitmap; if (!gdi) return NULL; nDstStep = nWidth * GetBytesPerPixel(gdi->dstFormat); pDstData = _aligned_malloc(nHeight * nDstStep, 16); if (!pDstData) return NULL; pSrcData = data; nSrcStep = nWidth * GetBytesPerPixel(SrcFormat); if (!freerdp_image_copy(pDstData, gdi->dstFormat, nDstStep, 0, 0, nWidth, nHeight, pSrcData, SrcFormat, nSrcStep, 0, 0, &gdi->palette, FREERDP_FLIP_NONE)) { _aligned_free(pDstData); return NULL; } bitmap = gdi_CreateBitmap(nWidth, nHeight, gdi->dstFormat, pDstData); return bitmap; } static BOOL gdi_Bitmap_New(rdpContext* context, rdpBitmap* bitmap) { gdiBitmap* gdi_bitmap; rdpGdi* gdi = context->gdi; gdi_bitmap = (gdiBitmap*) bitmap; gdi_bitmap->hdc = gdi_CreateCompatibleDC(gdi->hdc); if (!gdi_bitmap->hdc) return FALSE; if (!bitmap->data) gdi_bitmap->bitmap = gdi_CreateCompatibleBitmap( gdi->hdc, bitmap->width, bitmap->height); else { UINT32 format = bitmap->format; gdi_bitmap->bitmap = gdi_create_bitmap(gdi, bitmap->width, bitmap->height, format, bitmap->data); } if (!gdi_bitmap->bitmap) { gdi_DeleteDC(gdi_bitmap->hdc); return FALSE; } gdi_bitmap->hdc->format = gdi_bitmap->bitmap->format; gdi_SelectObject(gdi_bitmap->hdc, (HGDIOBJECT) gdi_bitmap->bitmap); gdi_bitmap->org_bitmap = NULL; return TRUE; } static void gdi_Bitmap_Free(rdpContext* context, rdpBitmap* bitmap) { gdiBitmap* gdi_bitmap = (gdiBitmap*) bitmap; if (gdi_bitmap) { if (gdi_bitmap->hdc) gdi_SelectObject(gdi_bitmap->hdc, (HGDIOBJECT) gdi_bitmap->org_bitmap); gdi_DeleteObject((HGDIOBJECT) gdi_bitmap->bitmap); gdi_DeleteDC(gdi_bitmap->hdc); _aligned_free(bitmap->data); } free(bitmap); } static BOOL gdi_Bitmap_Paint(rdpContext* context, rdpBitmap* bitmap) { gdiBitmap* gdi_bitmap = (gdiBitmap*) bitmap; UINT32 width = bitmap->right - bitmap->left + 1; UINT32 height = bitmap->bottom - bitmap->top + 1; return gdi_BitBlt(context->gdi->primary->hdc, bitmap->left, bitmap->top, width, height, gdi_bitmap->hdc, 0, 0, GDI_SRCCOPY, &context->gdi->palette); } static BOOL gdi_Bitmap_Decompress(rdpContext* context, rdpBitmap* bitmap, const BYTE* pSrcData, UINT32 DstWidth, UINT32 DstHeight, UINT32 bpp, UINT32 length, BOOL compressed, UINT32 codecId) { UINT32 SrcSize = length; rdpGdi* gdi = context->gdi; bitmap->compressed = FALSE; bitmap->format = gdi->dstFormat; bitmap->length = DstWidth * DstHeight * GetBytesPerPixel(bitmap->format); bitmap->data = (BYTE*) _aligned_malloc(bitmap->length, 16); if (!bitmap->data) return FALSE; if (compressed) { if (bpp < 32) { if (!interleaved_decompress(context->codecs->interleaved, pSrcData, SrcSize, DstWidth, DstHeight, bpp, bitmap->data, bitmap->format, 0, 0, 0, DstWidth, DstHeight, &gdi->palette)) return FALSE; } else { if (!planar_decompress(context->codecs->planar, pSrcData, SrcSize, DstWidth, DstHeight, bitmap->data, bitmap->format, 0, 0, 0, DstWidth, DstHeight, TRUE)) return FALSE; } } else { const UINT32 SrcFormat = gdi_get_pixel_format(bpp); const size_t sbpp = GetBytesPerPixel(SrcFormat); const size_t dbpp = GetBytesPerPixel(bitmap->format); if ((sbpp == 0) || (dbpp == 0)) return FALSE; else { const size_t dstSize = SrcSize * dbpp / sbpp; if (dstSize < bitmap->length) return FALSE; } if (!freerdp_image_copy(bitmap->data, bitmap->format, 0, 0, 0, DstWidth, DstHeight, pSrcData, SrcFormat, 0, 0, 0, &gdi->palette, FREERDP_FLIP_VERTICAL)) return FALSE; } return TRUE; } static BOOL gdi_Bitmap_SetSurface(rdpContext* context, rdpBitmap* bitmap, BOOL primary) { rdpGdi* gdi; if (!context) return FALSE; gdi = context->gdi; if (!gdi) return FALSE; if (primary) gdi->drawing = gdi->primary; else gdi->drawing = (gdiBitmap*) bitmap; return TRUE; } /* Glyph Class */ static BOOL gdi_Glyph_New(rdpContext* context, const rdpGlyph* glyph) { BYTE* data; gdiGlyph* gdi_glyph; if (!context || !glyph) return FALSE; gdi_glyph = (gdiGlyph*) glyph; gdi_glyph->hdc = gdi_GetDC(); if (!gdi_glyph->hdc) return FALSE; gdi_glyph->hdc->format = PIXEL_FORMAT_MONO; data = freerdp_glyph_convert(glyph->cx, glyph->cy, glyph->aj); if (!data) { gdi_DeleteDC(gdi_glyph->hdc); return FALSE; } gdi_glyph->bitmap = gdi_CreateBitmap(glyph->cx, glyph->cy, PIXEL_FORMAT_MONO, data); if (!gdi_glyph->bitmap) { gdi_DeleteDC(gdi_glyph->hdc); _aligned_free(data); return FALSE; } gdi_SelectObject(gdi_glyph->hdc, (HGDIOBJECT) gdi_glyph->bitmap); gdi_glyph->org_bitmap = NULL; return TRUE; } static void gdi_Glyph_Free(rdpContext* context, rdpGlyph* glyph) { gdiGlyph* gdi_glyph; gdi_glyph = (gdiGlyph*) glyph; if (gdi_glyph) { gdi_SelectObject(gdi_glyph->hdc, (HGDIOBJECT) gdi_glyph->org_bitmap); gdi_DeleteObject((HGDIOBJECT) gdi_glyph->bitmap); gdi_DeleteDC(gdi_glyph->hdc); free(glyph->aj); free(glyph); } } static BOOL gdi_Glyph_Draw(rdpContext* context, const rdpGlyph* glyph, INT32 x, INT32 y, INT32 w, INT32 h, INT32 sx, INT32 sy, BOOL fOpRedundant) { gdiGlyph* gdi_glyph; rdpGdi* gdi; HGDI_BRUSH brush; BOOL rc = FALSE; if (!context || !glyph) return FALSE; gdi = context->gdi; gdi_glyph = (gdiGlyph*) glyph; if (!fOpRedundant && 0) { GDI_RECT rect = { 0 }; if (x > 0) rect.left = x; if (y > 0) rect.top = y; if (x + w > 0) rect.right = x + w - 1; if (y + h > 0) rect.bottom = y + h - 1; if ((rect.left < rect.right) && (rect.top < rect.bottom)) { brush = gdi_CreateSolidBrush(gdi->drawing->hdc->bkColor); if (!brush) return FALSE; gdi_FillRect(gdi->drawing->hdc, &rect, brush); gdi_DeleteObject((HGDIOBJECT)brush); } } brush = gdi_CreateSolidBrush(gdi->drawing->hdc->textColor); if (!brush) return FALSE; gdi_SelectObject(gdi->drawing->hdc, (HGDIOBJECT)brush); rc = gdi_BitBlt(gdi->drawing->hdc, x, y, w, h, gdi_glyph->hdc, sx, sy, GDI_GLYPH_ORDER, &context->gdi->palette); gdi_DeleteObject((HGDIOBJECT)brush); return rc; } static BOOL gdi_Glyph_SetBounds(rdpContext* context, INT32 x, INT32 y, INT32 width, INT32 height) { rdpGdi* gdi; if (!context || !context->gdi) return FALSE; gdi = context->gdi; if (!gdi->drawing || !gdi->drawing->hdc) return FALSE; return gdi_SetClipRgn(gdi->drawing->hdc, x, y, width, height); } static BOOL gdi_Glyph_BeginDraw(rdpContext* context, INT32 x, INT32 y, INT32 width, INT32 height, UINT32 bgcolor, UINT32 fgcolor, BOOL fOpRedundant) { rdpGdi* gdi; if (!context || !context->gdi) return FALSE; gdi = context->gdi; if (!gdi->drawing || !gdi->drawing->hdc) return FALSE; if (!fOpRedundant) { if (!gdi_decode_color(gdi, bgcolor, &bgcolor, NULL)) return FALSE; if (!gdi_decode_color(gdi, fgcolor, &fgcolor, NULL)) return FALSE; gdi_SetClipRgn(gdi->drawing->hdc, x, y, width, height); gdi_SetTextColor(gdi->drawing->hdc, bgcolor); gdi_SetBkColor(gdi->drawing->hdc, fgcolor); if (1) { GDI_RECT rect = { 0 }; HGDI_BRUSH brush = gdi_CreateSolidBrush(fgcolor); if (!brush) return FALSE; if (x > 0) rect.left = x; if (y > 0) rect.top = y; rect.right = x + width - 1; rect.bottom = y + height - 1; if ((x + width > rect.left) && (y + height > rect.top)) gdi_FillRect(gdi->drawing->hdc, &rect, brush); gdi_DeleteObject((HGDIOBJECT)brush); } return gdi_SetNullClipRgn(gdi->drawing->hdc); } return TRUE; } static BOOL gdi_Glyph_EndDraw(rdpContext* context, INT32 x, INT32 y, INT32 width, INT32 height, UINT32 bgcolor, UINT32 fgcolor) { rdpGdi* gdi; if (!context || !context->gdi) return FALSE; gdi = context->gdi; if (!gdi->drawing || !gdi->drawing->hdc) return FALSE; gdi_SetNullClipRgn(gdi->drawing->hdc); return TRUE; } /* Graphics Module */ BOOL gdi_register_graphics(rdpGraphics* graphics) { rdpBitmap bitmap; rdpGlyph glyph; bitmap.size = sizeof(gdiBitmap); bitmap.New = gdi_Bitmap_New; bitmap.Free = gdi_Bitmap_Free; bitmap.Paint = gdi_Bitmap_Paint; bitmap.Decompress = gdi_Bitmap_Decompress; bitmap.SetSurface = gdi_Bitmap_SetSurface; graphics_register_bitmap(graphics, &bitmap); glyph.size = sizeof(gdiGlyph); glyph.New = gdi_Glyph_New; glyph.Free = gdi_Glyph_Free; glyph.Draw = gdi_Glyph_Draw; glyph.BeginDraw = gdi_Glyph_BeginDraw; glyph.EndDraw = gdi_Glyph_EndDraw; glyph.SetBounds = gdi_Glyph_SetBounds; graphics_register_glyph(graphics, &glyph); return TRUE; }
null
/** * FreeRDP: A Remote Desktop Protocol Implementation * Graphical Objects * * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com> * Copyright 2016 Armin Novak <armin.novak@thincast.com> * Copyright 2016 Thincast Technologies GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <winpr/crt.h> #include <freerdp/log.h> #include <freerdp/gdi/dc.h> #include <freerdp/gdi/shape.h> #include <freerdp/gdi/region.h> #include <freerdp/gdi/bitmap.h> #include "clipping.h" #include "drawing.h" #include "brush.h" #include "graphics.h" #define TAG FREERDP_TAG("gdi") /* Bitmap Class */ HGDI_BITMAP gdi_create_bitmap(rdpGdi* gdi, UINT32 nWidth, UINT32 nHeight, UINT32 SrcFormat, BYTE* data) { UINT32 nSrcStep; UINT32 nDstStep; BYTE* pSrcData; BYTE* pDstData; HGDI_BITMAP bitmap; if (!gdi) return NULL; nDstStep = nWidth * GetBytesPerPixel(gdi->dstFormat); pDstData = _aligned_malloc(nHeight * nDstStep, 16); if (!pDstData) return NULL; pSrcData = data; nSrcStep = nWidth * GetBytesPerPixel(SrcFormat); if (!freerdp_image_copy(pDstData, gdi->dstFormat, nDstStep, 0, 0, nWidth, nHeight, pSrcData, SrcFormat, nSrcStep, 0, 0, &gdi->palette, FREERDP_FLIP_NONE)) { _aligned_free(pDstData); return NULL; } bitmap = gdi_CreateBitmap(nWidth, nHeight, gdi->dstFormat, pDstData); return bitmap; } static BOOL gdi_Bitmap_New(rdpContext* context, rdpBitmap* bitmap) { gdiBitmap* gdi_bitmap; rdpGdi* gdi = context->gdi; gdi_bitmap = (gdiBitmap*) bitmap; gdi_bitmap->hdc = gdi_CreateCompatibleDC(gdi->hdc); if (!gdi_bitmap->hdc) return FALSE; if (!bitmap->data) gdi_bitmap->bitmap = gdi_CreateCompatibleBitmap( gdi->hdc, bitmap->width, bitmap->height); else { UINT32 format = bitmap->format; gdi_bitmap->bitmap = gdi_create_bitmap(gdi, bitmap->width, bitmap->height, format, bitmap->data); } if (!gdi_bitmap->bitmap) { gdi_DeleteDC(gdi_bitmap->hdc); return FALSE; } gdi_bitmap->hdc->format = gdi_bitmap->bitmap->format; gdi_SelectObject(gdi_bitmap->hdc, (HGDIOBJECT) gdi_bitmap->bitmap); gdi_bitmap->org_bitmap = NULL; return TRUE; } static void gdi_Bitmap_Free(rdpContext* context, rdpBitmap* bitmap) { gdiBitmap* gdi_bitmap = (gdiBitmap*) bitmap; if (gdi_bitmap) { if (gdi_bitmap->hdc) gdi_SelectObject(gdi_bitmap->hdc, (HGDIOBJECT) gdi_bitmap->org_bitmap); gdi_DeleteObject((HGDIOBJECT) gdi_bitmap->bitmap); gdi_DeleteDC(gdi_bitmap->hdc); _aligned_free(bitmap->data); } free(bitmap); } static BOOL gdi_Bitmap_Paint(rdpContext* context, rdpBitmap* bitmap) { gdiBitmap* gdi_bitmap = (gdiBitmap*) bitmap; UINT32 width = bitmap->right - bitmap->left + 1; UINT32 height = bitmap->bottom - bitmap->top + 1; return gdi_BitBlt(context->gdi->primary->hdc, bitmap->left, bitmap->top, width, height, gdi_bitmap->hdc, 0, 0, GDI_SRCCOPY, &context->gdi->palette); } static BOOL gdi_Bitmap_Decompress(rdpContext* context, rdpBitmap* bitmap, const BYTE* pSrcData, UINT32 DstWidth, UINT32 DstHeight, UINT32 bpp, UINT32 length, BOOL compressed, UINT32 codecId) { UINT32 SrcSize = length; rdpGdi* gdi = context->gdi; UINT32 size = DstWidth * DstHeight; bitmap->compressed = FALSE; bitmap->format = gdi->dstFormat; if ((GetBytesPerPixel(bitmap->format) == 0) || (DstWidth == 0) || (DstHeight == 0) || (DstWidth > UINT32_MAX / DstHeight) || (size > (UINT32_MAX / GetBytesPerPixel(bitmap->format)))) return FALSE; size *= GetBytesPerPixel(bitmap->format); bitmap->length = size; bitmap->data = (BYTE*) _aligned_malloc(bitmap->length, 16); if (!bitmap->data) return FALSE; if (compressed) { if (bpp < 32) { if (!interleaved_decompress(context->codecs->interleaved, pSrcData, SrcSize, DstWidth, DstHeight, bpp, bitmap->data, bitmap->format, 0, 0, 0, DstWidth, DstHeight, &gdi->palette)) return FALSE; } else { if (!planar_decompress(context->codecs->planar, pSrcData, SrcSize, DstWidth, DstHeight, bitmap->data, bitmap->format, 0, 0, 0, DstWidth, DstHeight, TRUE)) return FALSE; } } else { const UINT32 SrcFormat = gdi_get_pixel_format(bpp); const size_t sbpp = GetBytesPerPixel(SrcFormat); const size_t dbpp = GetBytesPerPixel(bitmap->format); if ((sbpp == 0) || (dbpp == 0)) return FALSE; else { const size_t dstSize = SrcSize * dbpp / sbpp; if (dstSize < bitmap->length) return FALSE; } if (!freerdp_image_copy(bitmap->data, bitmap->format, 0, 0, 0, DstWidth, DstHeight, pSrcData, SrcFormat, 0, 0, 0, &gdi->palette, FREERDP_FLIP_VERTICAL)) return FALSE; } return TRUE; } static BOOL gdi_Bitmap_SetSurface(rdpContext* context, rdpBitmap* bitmap, BOOL primary) { rdpGdi* gdi; if (!context) return FALSE; gdi = context->gdi; if (!gdi) return FALSE; if (primary) gdi->drawing = gdi->primary; else gdi->drawing = (gdiBitmap*) bitmap; return TRUE; } /* Glyph Class */ static BOOL gdi_Glyph_New(rdpContext* context, const rdpGlyph* glyph) { BYTE* data; gdiGlyph* gdi_glyph; if (!context || !glyph) return FALSE; gdi_glyph = (gdiGlyph*) glyph; gdi_glyph->hdc = gdi_GetDC(); if (!gdi_glyph->hdc) return FALSE; gdi_glyph->hdc->format = PIXEL_FORMAT_MONO; data = freerdp_glyph_convert(glyph->cx, glyph->cy, glyph->aj); if (!data) { gdi_DeleteDC(gdi_glyph->hdc); return FALSE; } gdi_glyph->bitmap = gdi_CreateBitmap(glyph->cx, glyph->cy, PIXEL_FORMAT_MONO, data); if (!gdi_glyph->bitmap) { gdi_DeleteDC(gdi_glyph->hdc); _aligned_free(data); return FALSE; } gdi_SelectObject(gdi_glyph->hdc, (HGDIOBJECT) gdi_glyph->bitmap); gdi_glyph->org_bitmap = NULL; return TRUE; } static void gdi_Glyph_Free(rdpContext* context, rdpGlyph* glyph) { gdiGlyph* gdi_glyph; gdi_glyph = (gdiGlyph*) glyph; if (gdi_glyph) { gdi_SelectObject(gdi_glyph->hdc, (HGDIOBJECT) gdi_glyph->org_bitmap); gdi_DeleteObject((HGDIOBJECT) gdi_glyph->bitmap); gdi_DeleteDC(gdi_glyph->hdc); free(glyph->aj); free(glyph); } } static BOOL gdi_Glyph_Draw(rdpContext* context, const rdpGlyph* glyph, INT32 x, INT32 y, INT32 w, INT32 h, INT32 sx, INT32 sy, BOOL fOpRedundant) { gdiGlyph* gdi_glyph; rdpGdi* gdi; HGDI_BRUSH brush; BOOL rc = FALSE; if (!context || !glyph) return FALSE; gdi = context->gdi; gdi_glyph = (gdiGlyph*) glyph; if (!fOpRedundant && 0) { GDI_RECT rect = { 0 }; if (x > 0) rect.left = x; if (y > 0) rect.top = y; if (x + w > 0) rect.right = x + w - 1; if (y + h > 0) rect.bottom = y + h - 1; if ((rect.left < rect.right) && (rect.top < rect.bottom)) { brush = gdi_CreateSolidBrush(gdi->drawing->hdc->bkColor); if (!brush) return FALSE; gdi_FillRect(gdi->drawing->hdc, &rect, brush); gdi_DeleteObject((HGDIOBJECT)brush); } } brush = gdi_CreateSolidBrush(gdi->drawing->hdc->textColor); if (!brush) return FALSE; gdi_SelectObject(gdi->drawing->hdc, (HGDIOBJECT)brush); rc = gdi_BitBlt(gdi->drawing->hdc, x, y, w, h, gdi_glyph->hdc, sx, sy, GDI_GLYPH_ORDER, &context->gdi->palette); gdi_DeleteObject((HGDIOBJECT)brush); return rc; } static BOOL gdi_Glyph_SetBounds(rdpContext* context, INT32 x, INT32 y, INT32 width, INT32 height) { rdpGdi* gdi; if (!context || !context->gdi) return FALSE; gdi = context->gdi; if (!gdi->drawing || !gdi->drawing->hdc) return FALSE; return gdi_SetClipRgn(gdi->drawing->hdc, x, y, width, height); } static BOOL gdi_Glyph_BeginDraw(rdpContext* context, INT32 x, INT32 y, INT32 width, INT32 height, UINT32 bgcolor, UINT32 fgcolor, BOOL fOpRedundant) { rdpGdi* gdi; if (!context || !context->gdi) return FALSE; gdi = context->gdi; if (!gdi->drawing || !gdi->drawing->hdc) return FALSE; if (!fOpRedundant) { if (!gdi_decode_color(gdi, bgcolor, &bgcolor, NULL)) return FALSE; if (!gdi_decode_color(gdi, fgcolor, &fgcolor, NULL)) return FALSE; gdi_SetClipRgn(gdi->drawing->hdc, x, y, width, height); gdi_SetTextColor(gdi->drawing->hdc, bgcolor); gdi_SetBkColor(gdi->drawing->hdc, fgcolor); if (1) { GDI_RECT rect = { 0 }; HGDI_BRUSH brush = gdi_CreateSolidBrush(fgcolor); if (!brush) return FALSE; if (x > 0) rect.left = x; if (y > 0) rect.top = y; rect.right = x + width - 1; rect.bottom = y + height - 1; if ((x + width > rect.left) && (y + height > rect.top)) gdi_FillRect(gdi->drawing->hdc, &rect, brush); gdi_DeleteObject((HGDIOBJECT)brush); } return gdi_SetNullClipRgn(gdi->drawing->hdc); } return TRUE; } static BOOL gdi_Glyph_EndDraw(rdpContext* context, INT32 x, INT32 y, INT32 width, INT32 height, UINT32 bgcolor, UINT32 fgcolor) { rdpGdi* gdi; if (!context || !context->gdi) return FALSE; gdi = context->gdi; if (!gdi->drawing || !gdi->drawing->hdc) return FALSE; gdi_SetNullClipRgn(gdi->drawing->hdc); return TRUE; } /* Graphics Module */ BOOL gdi_register_graphics(rdpGraphics* graphics) { rdpBitmap bitmap; rdpGlyph glyph; bitmap.size = sizeof(gdiBitmap); bitmap.New = gdi_Bitmap_New; bitmap.Free = gdi_Bitmap_Free; bitmap.Paint = gdi_Bitmap_Paint; bitmap.Decompress = gdi_Bitmap_Decompress; bitmap.SetSurface = gdi_Bitmap_SetSurface; graphics_register_bitmap(graphics, &bitmap); glyph.size = sizeof(gdiGlyph); glyph.New = gdi_Glyph_New; glyph.Free = gdi_Glyph_Free; glyph.Draw = gdi_Glyph_Draw; glyph.BeginDraw = gdi_Glyph_BeginDraw; glyph.EndDraw = gdi_Glyph_EndDraw; glyph.SetBounds = gdi_Glyph_SetBounds; graphics_register_glyph(graphics, &glyph); return TRUE; }
null
102
CWE-787
CVE-2018-8788
/** * FreeRDP: A Remote Desktop Protocol Implementation * NSCodec Encoder * * Copyright 2012 Vic Lee * Copyright 2016 Armin Novak <armin.novak@thincast.com> * Copyright 2016 Thincast Technologies GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <winpr/crt.h> #include <freerdp/codec/nsc.h> #include <freerdp/codec/color.h> #include "nsc_types.h" #include "nsc_encode.h" static BOOL nsc_context_initialize_encode(NSC_CONTEXT* context) { int i; UINT32 length; UINT32 tempWidth; UINT32 tempHeight; tempWidth = ROUND_UP_TO(context->width, 8); tempHeight = ROUND_UP_TO(context->height, 2); /* The maximum length a decoded plane can reach in all cases */ length = tempWidth * tempHeight + 16; if (length > context->priv->PlaneBuffersLength) { for (i = 0; i < 5; i++) { BYTE* tmp = (BYTE*) realloc(context->priv->PlaneBuffers[i], length); if (!tmp) goto fail; context->priv->PlaneBuffers[i] = tmp; } context->priv->PlaneBuffersLength = length; } if (context->ChromaSubsamplingLevel) { context->OrgByteCount[0] = tempWidth * context->height; context->OrgByteCount[1] = tempWidth * tempHeight / 4; context->OrgByteCount[2] = tempWidth * tempHeight / 4; context->OrgByteCount[3] = context->width * context->height; } else { context->OrgByteCount[0] = context->width * context->height; context->OrgByteCount[1] = context->width * context->height; context->OrgByteCount[2] = context->width * context->height; context->OrgByteCount[3] = context->width * context->height; } return TRUE; fail: if (length > context->priv->PlaneBuffersLength) { for (i = 0; i < 5; i++) free(context->priv->PlaneBuffers[i]); } return FALSE; } static void nsc_encode_argb_to_aycocg(NSC_CONTEXT* context, const BYTE* data, UINT32 scanline) { UINT16 x; UINT16 y; UINT16 rw; BYTE ccl; const BYTE* src; BYTE* yplane = NULL; BYTE* coplane = NULL; BYTE* cgplane = NULL; BYTE* aplane = NULL; INT16 r_val; INT16 g_val; INT16 b_val; BYTE a_val; UINT32 tempWidth; tempWidth = ROUND_UP_TO(context->width, 8); rw = (context->ChromaSubsamplingLevel ? tempWidth : context->width); ccl = context->ColorLossLevel; for (y = 0; y < context->height; y++) { src = data + (context->height - 1 - y) * scanline; yplane = context->priv->PlaneBuffers[0] + y * rw; coplane = context->priv->PlaneBuffers[1] + y * rw; cgplane = context->priv->PlaneBuffers[2] + y * rw; aplane = context->priv->PlaneBuffers[3] + y * context->width; for (x = 0; x < context->width; x++) { switch (context->format) { case PIXEL_FORMAT_BGRX32: b_val = *src++; g_val = *src++; r_val = *src++; src++; a_val = 0xFF; break; case PIXEL_FORMAT_BGRA32: b_val = *src++; g_val = *src++; r_val = *src++; a_val = *src++; break; case PIXEL_FORMAT_RGBX32: r_val = *src++; g_val = *src++; b_val = *src++; src++; a_val = 0xFF; break; case PIXEL_FORMAT_RGBA32: r_val = *src++; g_val = *src++; b_val = *src++; a_val = *src++; break; case PIXEL_FORMAT_BGR24: b_val = *src++; g_val = *src++; r_val = *src++; a_val = 0xFF; break; case PIXEL_FORMAT_RGB24: r_val = *src++; g_val = *src++; b_val = *src++; a_val = 0xFF; break; case PIXEL_FORMAT_BGR16: b_val = (INT16)(((*(src + 1)) & 0xF8) | ((*(src + 1)) >> 5)); g_val = (INT16)((((*(src + 1)) & 0x07) << 5) | (((*src) & 0xE0) >> 3)); r_val = (INT16)((((*src) & 0x1F) << 3) | (((*src) >> 2) & 0x07)); a_val = 0xFF; src += 2; break; case PIXEL_FORMAT_RGB16: r_val = (INT16)(((*(src + 1)) & 0xF8) | ((*(src + 1)) >> 5)); g_val = (INT16)((((*(src + 1)) & 0x07) << 5) | (((*src) & 0xE0) >> 3)); b_val = (INT16)((((*src) & 0x1F) << 3) | (((*src) >> 2) & 0x07)); a_val = 0xFF; src += 2; break; case PIXEL_FORMAT_A4: { int shift; BYTE idx; shift = (7 - (x % 8)); idx = ((*src) >> shift) & 1; idx |= (((*(src + 1)) >> shift) & 1) << 1; idx |= (((*(src + 2)) >> shift) & 1) << 2; idx |= (((*(src + 3)) >> shift) & 1) << 3; idx *= 3; r_val = (INT16) context->palette[idx]; g_val = (INT16) context->palette[idx + 1]; b_val = (INT16) context->palette[idx + 2]; if (shift == 0) src += 4; } a_val = 0xFF; break; case PIXEL_FORMAT_RGB8: { int idx = (*src) * 3; r_val = (INT16) context->palette[idx]; g_val = (INT16) context->palette[idx + 1]; b_val = (INT16) context->palette[idx + 2]; src++; } a_val = 0xFF; break; default: r_val = g_val = b_val = a_val = 0; break; } *yplane++ = (BYTE)((r_val >> 2) + (g_val >> 1) + (b_val >> 2)); /* Perform color loss reduction here */ *coplane++ = (BYTE)((r_val - b_val) >> ccl); *cgplane++ = (BYTE)((-(r_val >> 1) + g_val - (b_val >> 1)) >> ccl); *aplane++ = a_val; } if (context->ChromaSubsamplingLevel && (x % 2) == 1) { *yplane = *(yplane - 1); *coplane = *(coplane - 1); *cgplane = *(cgplane - 1); } } if (context->ChromaSubsamplingLevel && (y % 2) == 1) { yplane = context->priv->PlaneBuffers[0] + y * rw; coplane = context->priv->PlaneBuffers[1] + y * rw; cgplane = context->priv->PlaneBuffers[2] + y * rw; CopyMemory(yplane, yplane - rw, rw); CopyMemory(coplane, coplane - rw, rw); CopyMemory(cgplane, cgplane - rw, rw); } } static void nsc_encode_subsampling(NSC_CONTEXT* context) { UINT16 x; UINT16 y; BYTE* co_dst; BYTE* cg_dst; INT8* co_src0; INT8* co_src1; INT8* cg_src0; INT8* cg_src1; UINT32 tempWidth; UINT32 tempHeight; tempWidth = ROUND_UP_TO(context->width, 8); tempHeight = ROUND_UP_TO(context->height, 2); for (y = 0; y < tempHeight >> 1; y++) { co_dst = context->priv->PlaneBuffers[1] + y * (tempWidth >> 1); cg_dst = context->priv->PlaneBuffers[2] + y * (tempWidth >> 1); co_src0 = (INT8*) context->priv->PlaneBuffers[1] + (y << 1) * tempWidth; co_src1 = co_src0 + tempWidth; cg_src0 = (INT8*) context->priv->PlaneBuffers[2] + (y << 1) * tempWidth; cg_src1 = cg_src0 + tempWidth; for (x = 0; x < tempWidth >> 1; x++) { *co_dst++ = (BYTE)(((INT16) * co_src0 + (INT16) * (co_src0 + 1) + (INT16) * co_src1 + (INT16) * (co_src1 + 1)) >> 2); *cg_dst++ = (BYTE)(((INT16) * cg_src0 + (INT16) * (cg_src0 + 1) + (INT16) * cg_src1 + (INT16) * (cg_src1 + 1)) >> 2); co_src0 += 2; co_src1 += 2; cg_src0 += 2; cg_src1 += 2; } } } void nsc_encode(NSC_CONTEXT* context, const BYTE* bmpdata, UINT32 rowstride) { nsc_encode_argb_to_aycocg(context, bmpdata, rowstride); if (context->ChromaSubsamplingLevel) { nsc_encode_subsampling(context); } } static UINT32 nsc_rle_encode(BYTE* in, BYTE* out, UINT32 originalSize) { UINT32 left; UINT32 runlength = 1; UINT32 planeSize = 0; left = originalSize; /** * We quit the loop if the running compressed size is larger than the original. * In such cases data will be sent uncompressed. */ while (left > 4 && planeSize < originalSize - 4) { if (left > 5 && *in == *(in + 1)) { runlength++; } else if (runlength == 1) { *out++ = *in; planeSize++; } else if (runlength < 256) { *out++ = *in; *out++ = *in; *out++ = runlength - 2; runlength = 1; planeSize += 3; } else { *out++ = *in; *out++ = *in; *out++ = 0xFF; *out++ = (runlength & 0x000000FF); *out++ = (runlength & 0x0000FF00) >> 8; *out++ = (runlength & 0x00FF0000) >> 16; *out++ = (runlength & 0xFF000000) >> 24; runlength = 1; planeSize += 7; } in++; left--; } if (planeSize < originalSize - 4) CopyMemory(out, in, 4); planeSize += 4; return planeSize; } static void nsc_rle_compress_data(NSC_CONTEXT* context) { UINT16 i; UINT32 planeSize; UINT32 originalSize; for (i = 0; i < 4; i++) { originalSize = context->OrgByteCount[i]; if (originalSize == 0) { planeSize = 0; } else { planeSize = nsc_rle_encode(context->priv->PlaneBuffers[i], context->priv->PlaneBuffers[4], originalSize); if (planeSize < originalSize) CopyMemory(context->priv->PlaneBuffers[i], context->priv->PlaneBuffers[4], planeSize); else planeSize = originalSize; } context->PlaneByteCount[i] = planeSize; } } UINT32 nsc_compute_byte_count(NSC_CONTEXT* context, UINT32* ByteCount, UINT32 width, UINT32 height) { UINT32 tempWidth; UINT32 tempHeight; UINT32 maxPlaneSize; tempWidth = ROUND_UP_TO(width, 8); tempHeight = ROUND_UP_TO(height, 2); maxPlaneSize = tempWidth * tempHeight + 16; if (context->ChromaSubsamplingLevel) { ByteCount[0] = tempWidth * height; ByteCount[1] = tempWidth * tempHeight / 4; ByteCount[2] = tempWidth * tempHeight / 4; ByteCount[3] = width * height; } else { ByteCount[0] = width * height; ByteCount[1] = width * height; ByteCount[2] = width * height; ByteCount[3] = width * height; } return maxPlaneSize; } NSC_MESSAGE* nsc_encode_messages(NSC_CONTEXT* context, const BYTE* data, UINT32 x, UINT32 y, UINT32 width, UINT32 height, UINT32 scanline, UINT32* numMessages, UINT32 maxDataSize) { UINT32 i, j, k; UINT32 dataOffset; UINT32 rows, cols; UINT32 BytesPerPixel; UINT32 MaxRegionWidth; UINT32 MaxRegionHeight; UINT32 ByteCount[4]; UINT32 MaxPlaneSize; UINT32 MaxMessageSize; NSC_MESSAGE* messages; UINT32 PaddedMaxPlaneSize; k = 0; MaxRegionWidth = 64 * 4; MaxRegionHeight = 64 * 2; BytesPerPixel = GetBytesPerPixel(context->format); rows = (width + (MaxRegionWidth - (width % MaxRegionWidth))) / MaxRegionWidth; cols = (height + (MaxRegionHeight - (height % MaxRegionHeight))) / MaxRegionHeight; *numMessages = rows * cols; MaxPlaneSize = nsc_compute_byte_count(context, (UINT32*) ByteCount, width, height); MaxMessageSize = ByteCount[0] + ByteCount[1] + ByteCount[2] + ByteCount[3] + 20; maxDataSize -= 1024; /* reserve enough space for headers */ messages = (NSC_MESSAGE*) calloc(*numMessages, sizeof(NSC_MESSAGE)); if (!messages) return NULL; for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { messages[k].x = x + (i * MaxRegionWidth); messages[k].y = y + (j * MaxRegionHeight); messages[k].width = (i < (rows - 1)) ? MaxRegionWidth : width - (i * MaxRegionWidth); messages[k].height = (j < (cols - 1)) ? MaxRegionHeight : height - (j * MaxRegionHeight); messages[k].data = data; messages[k].scanline = scanline; messages[k].MaxPlaneSize = nsc_compute_byte_count(context, (UINT32*) messages[k].OrgByteCount, messages[k].width, messages[k].height); k++; } } *numMessages = k; for (i = 0; i < *numMessages; i++) { PaddedMaxPlaneSize = messages[i].MaxPlaneSize + 32; messages[i].PlaneBuffer = (BYTE*) BufferPool_Take(context->priv->PlanePool, PaddedMaxPlaneSize * 5); if (!messages[i].PlaneBuffer) goto fail; messages[i].PlaneBuffers[0] = (BYTE*) & (messages[i].PlaneBuffer[(PaddedMaxPlaneSize * 0) + 16]); messages[i].PlaneBuffers[1] = (BYTE*) & (messages[i].PlaneBuffer[(PaddedMaxPlaneSize * 1) + 16]); messages[i].PlaneBuffers[2] = (BYTE*) & (messages[i].PlaneBuffer[(PaddedMaxPlaneSize * 2) + 16]); messages[i].PlaneBuffers[3] = (BYTE*) & (messages[i].PlaneBuffer[(PaddedMaxPlaneSize * 3) + 16]); messages[i].PlaneBuffers[4] = (BYTE*) & (messages[i].PlaneBuffer[(PaddedMaxPlaneSize * 4) + 16]); } for (i = 0; i < *numMessages; i++) { context->width = messages[i].width; context->height = messages[i].height; context->OrgByteCount[0] = messages[i].OrgByteCount[0]; context->OrgByteCount[1] = messages[i].OrgByteCount[1]; context->OrgByteCount[2] = messages[i].OrgByteCount[2]; context->OrgByteCount[3] = messages[i].OrgByteCount[3]; context->priv->PlaneBuffersLength = messages[i].MaxPlaneSize; context->priv->PlaneBuffers[0] = messages[i].PlaneBuffers[0]; context->priv->PlaneBuffers[1] = messages[i].PlaneBuffers[1]; context->priv->PlaneBuffers[2] = messages[i].PlaneBuffers[2]; context->priv->PlaneBuffers[3] = messages[i].PlaneBuffers[3]; context->priv->PlaneBuffers[4] = messages[i].PlaneBuffers[4]; dataOffset = (messages[i].y * messages[i].scanline) + (messages[i].x * BytesPerPixel); PROFILER_ENTER(context->priv->prof_nsc_encode) context->encode(context, &data[dataOffset], scanline); PROFILER_EXIT(context->priv->prof_nsc_encode) PROFILER_ENTER(context->priv->prof_nsc_rle_compress_data) nsc_rle_compress_data(context); PROFILER_EXIT(context->priv->prof_nsc_rle_compress_data) messages[i].LumaPlaneByteCount = context->PlaneByteCount[0]; messages[i].OrangeChromaPlaneByteCount = context->PlaneByteCount[1]; messages[i].GreenChromaPlaneByteCount = context->PlaneByteCount[2]; messages[i].AlphaPlaneByteCount = context->PlaneByteCount[3]; messages[i].ColorLossLevel = context->ColorLossLevel; messages[i].ChromaSubsamplingLevel = context->ChromaSubsamplingLevel; } context->priv->PlaneBuffers[0] = NULL; context->priv->PlaneBuffers[1] = NULL; context->priv->PlaneBuffers[2] = NULL; context->priv->PlaneBuffers[3] = NULL; context->priv->PlaneBuffers[4] = NULL; return messages; fail: for (i = 0; i < *numMessages; i++) BufferPool_Return(context->priv->PlanePool, messages[i].PlaneBuffer); free(messages); return NULL; } BOOL nsc_write_message(NSC_CONTEXT* context, wStream* s, NSC_MESSAGE* message) { UINT32 totalPlaneByteCount; totalPlaneByteCount = message->LumaPlaneByteCount + message->OrangeChromaPlaneByteCount + message->GreenChromaPlaneByteCount + message->AlphaPlaneByteCount; if (!Stream_EnsureRemainingCapacity(s, 20 + totalPlaneByteCount)) return -1; Stream_Write_UINT32(s, message->LumaPlaneByteCount); /* LumaPlaneByteCount (4 bytes) */ Stream_Write_UINT32(s, message->OrangeChromaPlaneByteCount); /* OrangeChromaPlaneByteCount (4 bytes) */ Stream_Write_UINT32(s, message->GreenChromaPlaneByteCount); /* GreenChromaPlaneByteCount (4 bytes) */ Stream_Write_UINT32(s, message->AlphaPlaneByteCount); /* AlphaPlaneByteCount (4 bytes) */ Stream_Write_UINT8(s, message->ColorLossLevel); /* ColorLossLevel (1 byte) */ Stream_Write_UINT8(s, message->ChromaSubsamplingLevel); /* ChromaSubsamplingLevel (1 byte) */ Stream_Write_UINT16(s, 0); /* Reserved (2 bytes) */ if (message->LumaPlaneByteCount) Stream_Write(s, message->PlaneBuffers[0], message->LumaPlaneByteCount); /* LumaPlane */ if (message->OrangeChromaPlaneByteCount) Stream_Write(s, message->PlaneBuffers[1], message->OrangeChromaPlaneByteCount); /* OrangeChromaPlane */ if (message->GreenChromaPlaneByteCount) Stream_Write(s, message->PlaneBuffers[2], message->GreenChromaPlaneByteCount); /* GreenChromaPlane */ if (message->AlphaPlaneByteCount) Stream_Write(s, message->PlaneBuffers[3], message->AlphaPlaneByteCount); /* AlphaPlane */ return TRUE; } void nsc_message_free(NSC_CONTEXT* context, NSC_MESSAGE* message) { BufferPool_Return(context->priv->PlanePool, message->PlaneBuffer); } BOOL nsc_compose_message(NSC_CONTEXT* context, wStream* s, const BYTE* data, UINT32 width, UINT32 height, UINT32 scanline) { NSC_MESSAGE s_message = { 0 }; NSC_MESSAGE* message = &s_message; context->width = width; context->height = height; if (!nsc_context_initialize_encode(context)) return FALSE; /* ARGB to AYCoCg conversion, chroma subsampling and colorloss reduction */ PROFILER_ENTER(context->priv->prof_nsc_encode) context->encode(context, data, scanline); PROFILER_EXIT(context->priv->prof_nsc_encode) /* RLE encode */ PROFILER_ENTER(context->priv->prof_nsc_rle_compress_data) nsc_rle_compress_data(context); PROFILER_EXIT(context->priv->prof_nsc_rle_compress_data) message->PlaneBuffers[0] = context->priv->PlaneBuffers[0]; message->PlaneBuffers[1] = context->priv->PlaneBuffers[1]; message->PlaneBuffers[2] = context->priv->PlaneBuffers[2]; message->PlaneBuffers[3] = context->priv->PlaneBuffers[3]; message->LumaPlaneByteCount = context->PlaneByteCount[0]; message->OrangeChromaPlaneByteCount = context->PlaneByteCount[1]; message->GreenChromaPlaneByteCount = context->PlaneByteCount[2]; message->AlphaPlaneByteCount = context->PlaneByteCount[3]; message->ColorLossLevel = context->ColorLossLevel; message->ChromaSubsamplingLevel = context->ChromaSubsamplingLevel; return nsc_write_message(context, s, message); }
null
/** * FreeRDP: A Remote Desktop Protocol Implementation * NSCodec Encoder * * Copyright 2012 Vic Lee * Copyright 2016 Armin Novak <armin.novak@thincast.com> * Copyright 2016 Thincast Technologies GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <winpr/crt.h> #include <freerdp/codec/nsc.h> #include <freerdp/codec/color.h> #include "nsc_types.h" #include "nsc_encode.h" static BOOL nsc_context_initialize_encode(NSC_CONTEXT* context) { int i; UINT32 length; UINT32 tempWidth; UINT32 tempHeight; tempWidth = ROUND_UP_TO(context->width, 8); tempHeight = ROUND_UP_TO(context->height, 2); /* The maximum length a decoded plane can reach in all cases */ length = tempWidth * tempHeight + 16; if (length > context->priv->PlaneBuffersLength) { for (i = 0; i < 5; i++) { BYTE* tmp = (BYTE*) realloc(context->priv->PlaneBuffers[i], length); if (!tmp) goto fail; context->priv->PlaneBuffers[i] = tmp; } context->priv->PlaneBuffersLength = length; } if (context->ChromaSubsamplingLevel) { context->OrgByteCount[0] = tempWidth * context->height; context->OrgByteCount[1] = tempWidth * tempHeight / 4; context->OrgByteCount[2] = tempWidth * tempHeight / 4; context->OrgByteCount[3] = context->width * context->height; } else { context->OrgByteCount[0] = context->width * context->height; context->OrgByteCount[1] = context->width * context->height; context->OrgByteCount[2] = context->width * context->height; context->OrgByteCount[3] = context->width * context->height; } return TRUE; fail: if (length > context->priv->PlaneBuffersLength) { for (i = 0; i < 5; i++) free(context->priv->PlaneBuffers[i]); } return FALSE; } static BOOL nsc_encode_argb_to_aycocg(NSC_CONTEXT* context, const BYTE* data, UINT32 scanline) { UINT16 x; UINT16 y; UINT16 rw; BYTE ccl; const BYTE* src; BYTE* yplane = NULL; BYTE* coplane = NULL; BYTE* cgplane = NULL; BYTE* aplane = NULL; INT16 r_val; INT16 g_val; INT16 b_val; BYTE a_val; UINT32 tempWidth; if (!context || data || (scanline == 0)) return FALSE; tempWidth = ROUND_UP_TO(context->width, 8); rw = (context->ChromaSubsamplingLevel ? tempWidth : context->width); ccl = context->ColorLossLevel; if (context->priv->PlaneBuffersLength < rw * scanline) return FALSE; if (rw < scanline * 2) return FALSE; for (y = 0; y < context->height; y++) { src = data + (context->height - 1 - y) * scanline; yplane = context->priv->PlaneBuffers[0] + y * rw; coplane = context->priv->PlaneBuffers[1] + y * rw; cgplane = context->priv->PlaneBuffers[2] + y * rw; aplane = context->priv->PlaneBuffers[3] + y * context->width; for (x = 0; x < context->width; x++) { switch (context->format) { case PIXEL_FORMAT_BGRX32: b_val = *src++; g_val = *src++; r_val = *src++; src++; a_val = 0xFF; break; case PIXEL_FORMAT_BGRA32: b_val = *src++; g_val = *src++; r_val = *src++; a_val = *src++; break; case PIXEL_FORMAT_RGBX32: r_val = *src++; g_val = *src++; b_val = *src++; src++; a_val = 0xFF; break; case PIXEL_FORMAT_RGBA32: r_val = *src++; g_val = *src++; b_val = *src++; a_val = *src++; break; case PIXEL_FORMAT_BGR24: b_val = *src++; g_val = *src++; r_val = *src++; a_val = 0xFF; break; case PIXEL_FORMAT_RGB24: r_val = *src++; g_val = *src++; b_val = *src++; a_val = 0xFF; break; case PIXEL_FORMAT_BGR16: b_val = (INT16)(((*(src + 1)) & 0xF8) | ((*(src + 1)) >> 5)); g_val = (INT16)((((*(src + 1)) & 0x07) << 5) | (((*src) & 0xE0) >> 3)); r_val = (INT16)((((*src) & 0x1F) << 3) | (((*src) >> 2) & 0x07)); a_val = 0xFF; src += 2; break; case PIXEL_FORMAT_RGB16: r_val = (INT16)(((*(src + 1)) & 0xF8) | ((*(src + 1)) >> 5)); g_val = (INT16)((((*(src + 1)) & 0x07) << 5) | (((*src) & 0xE0) >> 3)); b_val = (INT16)((((*src) & 0x1F) << 3) | (((*src) >> 2) & 0x07)); a_val = 0xFF; src += 2; break; case PIXEL_FORMAT_A4: { int shift; BYTE idx; shift = (7 - (x % 8)); idx = ((*src) >> shift) & 1; idx |= (((*(src + 1)) >> shift) & 1) << 1; idx |= (((*(src + 2)) >> shift) & 1) << 2; idx |= (((*(src + 3)) >> shift) & 1) << 3; idx *= 3; r_val = (INT16) context->palette[idx]; g_val = (INT16) context->palette[idx + 1]; b_val = (INT16) context->palette[idx + 2]; if (shift == 0) src += 4; } a_val = 0xFF; break; case PIXEL_FORMAT_RGB8: { int idx = (*src) * 3; r_val = (INT16) context->palette[idx]; g_val = (INT16) context->palette[idx + 1]; b_val = (INT16) context->palette[idx + 2]; src++; } a_val = 0xFF; break; default: r_val = g_val = b_val = a_val = 0; break; } *yplane++ = (BYTE)((r_val >> 2) + (g_val >> 1) + (b_val >> 2)); /* Perform color loss reduction here */ *coplane++ = (BYTE)((r_val - b_val) >> ccl); *cgplane++ = (BYTE)((-(r_val >> 1) + g_val - (b_val >> 1)) >> ccl); *aplane++ = a_val; } if (context->ChromaSubsamplingLevel && (x % 2) == 1) { *yplane = *(yplane - 1); *coplane = *(coplane - 1); *cgplane = *(cgplane - 1); } } if (context->ChromaSubsamplingLevel && (y % 2) == 1) { yplane = context->priv->PlaneBuffers[0] + y * rw; coplane = context->priv->PlaneBuffers[1] + y * rw; cgplane = context->priv->PlaneBuffers[2] + y * rw; CopyMemory(yplane, yplane - rw, rw); CopyMemory(coplane, coplane - rw, rw); CopyMemory(cgplane, cgplane - rw, rw); } return TRUE; } static BOOL nsc_encode_subsampling(NSC_CONTEXT* context) { UINT16 x; UINT16 y; UINT32 tempWidth; UINT32 tempHeight; if (!context) return FALSE; tempWidth = ROUND_UP_TO(context->width, 8); tempHeight = ROUND_UP_TO(context->height, 2); if (tempHeight == 0) return FALSE; if (tempWidth > context->priv->PlaneBuffersLength / tempHeight) return FALSE; for (y = 0; y < tempHeight >> 1; y++) { BYTE* co_dst = context->priv->PlaneBuffers[1] + y * (tempWidth >> 1); BYTE* cg_dst = context->priv->PlaneBuffers[2] + y * (tempWidth >> 1); const INT8* co_src0 = (INT8*) context->priv->PlaneBuffers[1] + (y << 1) * tempWidth; const INT8* co_src1 = co_src0 + tempWidth; const INT8* cg_src0 = (INT8*) context->priv->PlaneBuffers[2] + (y << 1) * tempWidth; const INT8* cg_src1 = cg_src0 + tempWidth; for (x = 0; x < tempWidth >> 1; x++) { *co_dst++ = (BYTE)(((INT16) * co_src0 + (INT16) * (co_src0 + 1) + (INT16) * co_src1 + (INT16) * (co_src1 + 1)) >> 2); *cg_dst++ = (BYTE)(((INT16) * cg_src0 + (INT16) * (cg_src0 + 1) + (INT16) * cg_src1 + (INT16) * (cg_src1 + 1)) >> 2); co_src0 += 2; co_src1 += 2; cg_src0 += 2; cg_src1 += 2; } } return TRUE; } BOOL nsc_encode(NSC_CONTEXT* context, const BYTE* bmpdata, UINT32 rowstride) { if (!context || !bmpdata || (rowstride == 0)) return FALSE; if (!nsc_encode_argb_to_aycocg(context, bmpdata, rowstride)) return FALSE; if (context->ChromaSubsamplingLevel) { if (!nsc_encode_subsampling(context)) return FALSE; } return TRUE; } static UINT32 nsc_rle_encode(const BYTE* in, BYTE* out, UINT32 originalSize) { UINT32 left; UINT32 runlength = 1; UINT32 planeSize = 0; left = originalSize; /** * We quit the loop if the running compressed size is larger than the original. * In such cases data will be sent uncompressed. */ while (left > 4 && planeSize < originalSize - 4) { if (left > 5 && *in == *(in + 1)) { runlength++; } else if (runlength == 1) { *out++ = *in; planeSize++; } else if (runlength < 256) { *out++ = *in; *out++ = *in; *out++ = runlength - 2; runlength = 1; planeSize += 3; } else { *out++ = *in; *out++ = *in; *out++ = 0xFF; *out++ = (runlength & 0x000000FF); *out++ = (runlength & 0x0000FF00) >> 8; *out++ = (runlength & 0x00FF0000) >> 16; *out++ = (runlength & 0xFF000000) >> 24; runlength = 1; planeSize += 7; } in++; left--; } if (planeSize < originalSize - 4) CopyMemory(out, in, 4); planeSize += 4; return planeSize; } static void nsc_rle_compress_data(NSC_CONTEXT* context) { UINT16 i; UINT32 planeSize; UINT32 originalSize; for (i = 0; i < 4; i++) { originalSize = context->OrgByteCount[i]; if (originalSize == 0) { planeSize = 0; } else { planeSize = nsc_rle_encode(context->priv->PlaneBuffers[i], context->priv->PlaneBuffers[4], originalSize); if (planeSize < originalSize) CopyMemory(context->priv->PlaneBuffers[i], context->priv->PlaneBuffers[4], planeSize); else planeSize = originalSize; } context->PlaneByteCount[i] = planeSize; } } UINT32 nsc_compute_byte_count(NSC_CONTEXT* context, UINT32* ByteCount, UINT32 width, UINT32 height) { UINT32 tempWidth; UINT32 tempHeight; UINT32 maxPlaneSize; tempWidth = ROUND_UP_TO(width, 8); tempHeight = ROUND_UP_TO(height, 2); maxPlaneSize = tempWidth * tempHeight + 16; if (context->ChromaSubsamplingLevel) { ByteCount[0] = tempWidth * height; ByteCount[1] = tempWidth * tempHeight / 4; ByteCount[2] = tempWidth * tempHeight / 4; ByteCount[3] = width * height; } else { ByteCount[0] = width * height; ByteCount[1] = width * height; ByteCount[2] = width * height; ByteCount[3] = width * height; } return maxPlaneSize; } NSC_MESSAGE* nsc_encode_messages(NSC_CONTEXT* context, const BYTE* data, UINT32 x, UINT32 y, UINT32 width, UINT32 height, UINT32 scanline, UINT32* numMessages, UINT32 maxDataSize) { UINT32 i, j, k; UINT32 dataOffset; UINT32 rows, cols; UINT32 BytesPerPixel; UINT32 MaxRegionWidth; UINT32 MaxRegionHeight; UINT32 ByteCount[4]; UINT32 MaxPlaneSize; UINT32 MaxMessageSize; NSC_MESSAGE* messages; UINT32 PaddedMaxPlaneSize; k = 0; MaxRegionWidth = 64 * 4; MaxRegionHeight = 64 * 2; BytesPerPixel = GetBytesPerPixel(context->format); rows = (width + (MaxRegionWidth - (width % MaxRegionWidth))) / MaxRegionWidth; cols = (height + (MaxRegionHeight - (height % MaxRegionHeight))) / MaxRegionHeight; *numMessages = rows * cols; MaxPlaneSize = nsc_compute_byte_count(context, (UINT32*) ByteCount, width, height); MaxMessageSize = ByteCount[0] + ByteCount[1] + ByteCount[2] + ByteCount[3] + 20; maxDataSize -= 1024; /* reserve enough space for headers */ messages = (NSC_MESSAGE*) calloc(*numMessages, sizeof(NSC_MESSAGE)); if (!messages) return NULL; for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { messages[k].x = x + (i * MaxRegionWidth); messages[k].y = y + (j * MaxRegionHeight); messages[k].width = (i < (rows - 1)) ? MaxRegionWidth : width - (i * MaxRegionWidth); messages[k].height = (j < (cols - 1)) ? MaxRegionHeight : height - (j * MaxRegionHeight); messages[k].data = data; messages[k].scanline = scanline; messages[k].MaxPlaneSize = nsc_compute_byte_count(context, (UINT32*) messages[k].OrgByteCount, messages[k].width, messages[k].height); k++; } } *numMessages = k; for (i = 0; i < *numMessages; i++) { PaddedMaxPlaneSize = messages[i].MaxPlaneSize + 32; messages[i].PlaneBuffer = (BYTE*) BufferPool_Take(context->priv->PlanePool, PaddedMaxPlaneSize * 5); if (!messages[i].PlaneBuffer) goto fail; messages[i].PlaneBuffers[0] = (BYTE*) & (messages[i].PlaneBuffer[(PaddedMaxPlaneSize * 0) + 16]); messages[i].PlaneBuffers[1] = (BYTE*) & (messages[i].PlaneBuffer[(PaddedMaxPlaneSize * 1) + 16]); messages[i].PlaneBuffers[2] = (BYTE*) & (messages[i].PlaneBuffer[(PaddedMaxPlaneSize * 2) + 16]); messages[i].PlaneBuffers[3] = (BYTE*) & (messages[i].PlaneBuffer[(PaddedMaxPlaneSize * 3) + 16]); messages[i].PlaneBuffers[4] = (BYTE*) & (messages[i].PlaneBuffer[(PaddedMaxPlaneSize * 4) + 16]); } for (i = 0; i < *numMessages; i++) { context->width = messages[i].width; context->height = messages[i].height; context->OrgByteCount[0] = messages[i].OrgByteCount[0]; context->OrgByteCount[1] = messages[i].OrgByteCount[1]; context->OrgByteCount[2] = messages[i].OrgByteCount[2]; context->OrgByteCount[3] = messages[i].OrgByteCount[3]; context->priv->PlaneBuffersLength = messages[i].MaxPlaneSize; context->priv->PlaneBuffers[0] = messages[i].PlaneBuffers[0]; context->priv->PlaneBuffers[1] = messages[i].PlaneBuffers[1]; context->priv->PlaneBuffers[2] = messages[i].PlaneBuffers[2]; context->priv->PlaneBuffers[3] = messages[i].PlaneBuffers[3]; context->priv->PlaneBuffers[4] = messages[i].PlaneBuffers[4]; dataOffset = (messages[i].y * messages[i].scanline) + (messages[i].x * BytesPerPixel); PROFILER_ENTER(context->priv->prof_nsc_encode) context->encode(context, &data[dataOffset], scanline); PROFILER_EXIT(context->priv->prof_nsc_encode) PROFILER_ENTER(context->priv->prof_nsc_rle_compress_data) nsc_rle_compress_data(context); PROFILER_EXIT(context->priv->prof_nsc_rle_compress_data) messages[i].LumaPlaneByteCount = context->PlaneByteCount[0]; messages[i].OrangeChromaPlaneByteCount = context->PlaneByteCount[1]; messages[i].GreenChromaPlaneByteCount = context->PlaneByteCount[2]; messages[i].AlphaPlaneByteCount = context->PlaneByteCount[3]; messages[i].ColorLossLevel = context->ColorLossLevel; messages[i].ChromaSubsamplingLevel = context->ChromaSubsamplingLevel; } context->priv->PlaneBuffers[0] = NULL; context->priv->PlaneBuffers[1] = NULL; context->priv->PlaneBuffers[2] = NULL; context->priv->PlaneBuffers[3] = NULL; context->priv->PlaneBuffers[4] = NULL; return messages; fail: for (i = 0; i < *numMessages; i++) BufferPool_Return(context->priv->PlanePool, messages[i].PlaneBuffer); free(messages); return NULL; } BOOL nsc_write_message(NSC_CONTEXT* context, wStream* s, NSC_MESSAGE* message) { UINT32 totalPlaneByteCount; totalPlaneByteCount = message->LumaPlaneByteCount + message->OrangeChromaPlaneByteCount + message->GreenChromaPlaneByteCount + message->AlphaPlaneByteCount; if (!Stream_EnsureRemainingCapacity(s, 20 + totalPlaneByteCount)) return -1; Stream_Write_UINT32(s, message->LumaPlaneByteCount); /* LumaPlaneByteCount (4 bytes) */ Stream_Write_UINT32(s, message->OrangeChromaPlaneByteCount); /* OrangeChromaPlaneByteCount (4 bytes) */ Stream_Write_UINT32(s, message->GreenChromaPlaneByteCount); /* GreenChromaPlaneByteCount (4 bytes) */ Stream_Write_UINT32(s, message->AlphaPlaneByteCount); /* AlphaPlaneByteCount (4 bytes) */ Stream_Write_UINT8(s, message->ColorLossLevel); /* ColorLossLevel (1 byte) */ Stream_Write_UINT8(s, message->ChromaSubsamplingLevel); /* ChromaSubsamplingLevel (1 byte) */ Stream_Write_UINT16(s, 0); /* Reserved (2 bytes) */ if (message->LumaPlaneByteCount) Stream_Write(s, message->PlaneBuffers[0], message->LumaPlaneByteCount); /* LumaPlane */ if (message->OrangeChromaPlaneByteCount) Stream_Write(s, message->PlaneBuffers[1], message->OrangeChromaPlaneByteCount); /* OrangeChromaPlane */ if (message->GreenChromaPlaneByteCount) Stream_Write(s, message->PlaneBuffers[2], message->GreenChromaPlaneByteCount); /* GreenChromaPlane */ if (message->AlphaPlaneByteCount) Stream_Write(s, message->PlaneBuffers[3], message->AlphaPlaneByteCount); /* AlphaPlane */ return TRUE; } void nsc_message_free(NSC_CONTEXT* context, NSC_MESSAGE* message) { BufferPool_Return(context->priv->PlanePool, message->PlaneBuffer); } BOOL nsc_compose_message(NSC_CONTEXT* context, wStream* s, const BYTE* data, UINT32 width, UINT32 height, UINT32 scanline) { NSC_MESSAGE s_message = { 0 }; NSC_MESSAGE* message = &s_message; context->width = width; context->height = height; if (!nsc_context_initialize_encode(context)) return FALSE; /* ARGB to AYCoCg conversion, chroma subsampling and colorloss reduction */ PROFILER_ENTER(context->priv->prof_nsc_encode) context->encode(context, data, scanline); PROFILER_EXIT(context->priv->prof_nsc_encode) /* RLE encode */ PROFILER_ENTER(context->priv->prof_nsc_rle_compress_data) nsc_rle_compress_data(context); PROFILER_EXIT(context->priv->prof_nsc_rle_compress_data) message->PlaneBuffers[0] = context->priv->PlaneBuffers[0]; message->PlaneBuffers[1] = context->priv->PlaneBuffers[1]; message->PlaneBuffers[2] = context->priv->PlaneBuffers[2]; message->PlaneBuffers[3] = context->priv->PlaneBuffers[3]; message->LumaPlaneByteCount = context->PlaneByteCount[0]; message->OrangeChromaPlaneByteCount = context->PlaneByteCount[1]; message->GreenChromaPlaneByteCount = context->PlaneByteCount[2]; message->AlphaPlaneByteCount = context->PlaneByteCount[3]; message->ColorLossLevel = context->ColorLossLevel; message->ChromaSubsamplingLevel = context->ChromaSubsamplingLevel; return nsc_write_message(context, s, message); }
null
103
CWE-787
CVE-2018-8793
/* -*- c-basic-offset: 8 -*- rdesktop: A Remote Desktop Protocol client. Support for the Matrox "lspci" channel Copyright (C) 2005 Matrox Graphics Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "rdesktop.h" #include <sys/types.h> #include <unistd.h> static VCHANNEL *lspci_channel; typedef struct _pci_device { uint16 klass; uint16 vendor; uint16 device; uint16 subvendor; uint16 subdevice; uint8 revision; uint8 progif; } pci_device; static pci_device current_device; static void lspci_send(const char *output); /* Handle one line of output from the lspci subprocess */ static RD_BOOL handle_child_line(const char *line, void *data) { UNUSED(data); const char *val; char buf[1024]; if (str_startswith(line, "Class:")) { val = line + sizeof("Class:"); /* Skip whitespace and second Class: occurrence */ val += strspn(val, " \t") + sizeof("Class"); current_device.klass = strtol(val, NULL, 16); } else if (str_startswith(line, "Vendor:")) { val = line + sizeof("Vendor:"); current_device.vendor = strtol(val, NULL, 16); } else if (str_startswith(line, "Device:")) { val = line + sizeof("Device:"); /* Sigh, there are *two* lines tagged as Device:. We are not interested in the domain/bus/slot/func */ if (!strchr(val, ':')) current_device.device = strtol(val, NULL, 16); } else if (str_startswith(line, "SVendor:")) { val = line + sizeof("SVendor:"); current_device.subvendor = strtol(val, NULL, 16); } else if (str_startswith(line, "SDevice:")) { val = line + sizeof("SDevice:"); current_device.subdevice = strtol(val, NULL, 16); } else if (str_startswith(line, "Rev:")) { val = line + sizeof("Rev:"); current_device.revision = strtol(val, NULL, 16); } else if (str_startswith(line, "ProgIf:")) { val = line + sizeof("ProgIf:"); current_device.progif = strtol(val, NULL, 16); } else if (strspn(line, " \t") == strlen(line)) { /* Blank line. Send collected information over channel */ snprintf(buf, sizeof(buf), "%04x,%04x,%04x,%04x,%04x,%02x,%02x\n", current_device.klass, current_device.vendor, current_device.device, current_device.subvendor, current_device.subdevice, current_device.revision, current_device.progif); lspci_send(buf); memset(&current_device, 0, sizeof(current_device)); } else { logger(Core, Warning, "handle_child_line(), Unrecognized lspci line '%s'", line); } return True; } /* Process one line of input from virtual channel */ static RD_BOOL lspci_process_line(const char *line, void *data) { UNUSED(data); char *lspci_command[5] = { "lspci", "-m", "-n", "-v", NULL }; if (!strcmp(line, "LSPCI")) { memset(&current_device, 0, sizeof(current_device)); subprocess(lspci_command, handle_child_line, NULL); /* Send single dot to indicate end of enumeration */ lspci_send(".\n"); } else { logger(Core, Error, "lspci_process_line(), invalid line '%s'", line); } return True; } /* Process new data from the virtual channel */ static void lspci_process(STREAM s) { unsigned int pkglen; static char *rest = NULL; char *buf; pkglen = s->end - s->p; /* str_handle_lines requires null terminated strings */ buf = xmalloc(pkglen + 1); STRNCPY(buf, (char *) s->p, pkglen + 1); str_handle_lines(buf, &rest, lspci_process_line, NULL); xfree(buf); } /* Initialize this module: Register the lspci channel */ RD_BOOL lspci_init(void) { lspci_channel = channel_register("lspci", CHANNEL_OPTION_INITIALIZED | CHANNEL_OPTION_ENCRYPT_RDP, lspci_process); return (lspci_channel != NULL); } /* Send data to channel */ static void lspci_send(const char *output) { STREAM s; size_t len; len = strlen(output); s = channel_init(lspci_channel, len); out_uint8p(s, output, len) s_mark_end(s); channel_send(s, lspci_channel); }
null
/* -*- c-basic-offset: 8 -*- rdesktop: A Remote Desktop Protocol client. Support for the Matrox "lspci" channel Copyright (C) 2005 Matrox Graphics Inc. Copyright 2018 Henrik Andersson <hean01@cendio.se> for Cendio AB This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "rdesktop.h" #include <sys/types.h> #include <unistd.h> static VCHANNEL *lspci_channel; typedef struct _pci_device { uint16 klass; uint16 vendor; uint16 device; uint16 subvendor; uint16 subdevice; uint8 revision; uint8 progif; } pci_device; static pci_device current_device; static void lspci_send(const char *output); /* Handle one line of output from the lspci subprocess */ static RD_BOOL handle_child_line(const char *line, void *data) { UNUSED(data); const char *val; char buf[1024]; if (str_startswith(line, "Class:")) { val = line + sizeof("Class:"); /* Skip whitespace and second Class: occurrence */ val += strspn(val, " \t") + sizeof("Class"); current_device.klass = strtol(val, NULL, 16); } else if (str_startswith(line, "Vendor:")) { val = line + sizeof("Vendor:"); current_device.vendor = strtol(val, NULL, 16); } else if (str_startswith(line, "Device:")) { val = line + sizeof("Device:"); /* Sigh, there are *two* lines tagged as Device:. We are not interested in the domain/bus/slot/func */ if (!strchr(val, ':')) current_device.device = strtol(val, NULL, 16); } else if (str_startswith(line, "SVendor:")) { val = line + sizeof("SVendor:"); current_device.subvendor = strtol(val, NULL, 16); } else if (str_startswith(line, "SDevice:")) { val = line + sizeof("SDevice:"); current_device.subdevice = strtol(val, NULL, 16); } else if (str_startswith(line, "Rev:")) { val = line + sizeof("Rev:"); current_device.revision = strtol(val, NULL, 16); } else if (str_startswith(line, "ProgIf:")) { val = line + sizeof("ProgIf:"); current_device.progif = strtol(val, NULL, 16); } else if (strspn(line, " \t") == strlen(line)) { /* Blank line. Send collected information over channel */ snprintf(buf, sizeof(buf), "%04x,%04x,%04x,%04x,%04x,%02x,%02x\n", current_device.klass, current_device.vendor, current_device.device, current_device.subvendor, current_device.subdevice, current_device.revision, current_device.progif); lspci_send(buf); memset(&current_device, 0, sizeof(current_device)); } else { logger(Core, Warning, "handle_child_line(), Unrecognized lspci line '%s'", line); } return True; } /* Process one line of input from virtual channel */ static RD_BOOL lspci_process_line(const char *line, void *data) { UNUSED(data); char *lspci_command[5] = { "lspci", "-m", "-n", "-v", NULL }; if (!strcmp(line, "LSPCI")) { memset(&current_device, 0, sizeof(current_device)); subprocess(lspci_command, handle_child_line, NULL); /* Send single dot to indicate end of enumeration */ lspci_send(".\n"); } else { logger(Core, Error, "lspci_process_line(), invalid line '%s'", line); } return True; } /* Process new data from the virtual channel */ static void lspci_process(STREAM s) { unsigned int pkglen; static char *rest = NULL; char *buf; struct stream packet = *s; if (!s_check(s)) { rdp_protocol_error("lspci_process(), stream is in unstable state", &packet); } pkglen = s->end - s->p; /* str_handle_lines requires null terminated strings */ buf = xmalloc(pkglen + 1); STRNCPY(buf, (char *) s->p, pkglen + 1); str_handle_lines(buf, &rest, lspci_process_line, NULL); xfree(buf); } /* Initialize this module: Register the lspci channel */ RD_BOOL lspci_init(void) { lspci_channel = channel_register("lspci", CHANNEL_OPTION_INITIALIZED | CHANNEL_OPTION_ENCRYPT_RDP, lspci_process); return (lspci_channel != NULL); } /* Send data to channel */ static void lspci_send(const char *output) { STREAM s; size_t len; len = strlen(output); s = channel_init(lspci_channel, len); out_uint8p(s, output, len) s_mark_end(s); channel_send(s, lspci_channel); }
null
104
CWE-787
CVE-2018-8794
/* -*- c-basic-offset: 8 -*- rdesktop: A Remote Desktop Protocol client. Support for the Matrox "lspci" channel Copyright (C) 2005 Matrox Graphics Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "rdesktop.h" #include <sys/types.h> #include <unistd.h> static VCHANNEL *lspci_channel; typedef struct _pci_device { uint16 klass; uint16 vendor; uint16 device; uint16 subvendor; uint16 subdevice; uint8 revision; uint8 progif; } pci_device; static pci_device current_device; static void lspci_send(const char *output); /* Handle one line of output from the lspci subprocess */ static RD_BOOL handle_child_line(const char *line, void *data) { UNUSED(data); const char *val; char buf[1024]; if (str_startswith(line, "Class:")) { val = line + sizeof("Class:"); /* Skip whitespace and second Class: occurrence */ val += strspn(val, " \t") + sizeof("Class"); current_device.klass = strtol(val, NULL, 16); } else if (str_startswith(line, "Vendor:")) { val = line + sizeof("Vendor:"); current_device.vendor = strtol(val, NULL, 16); } else if (str_startswith(line, "Device:")) { val = line + sizeof("Device:"); /* Sigh, there are *two* lines tagged as Device:. We are not interested in the domain/bus/slot/func */ if (!strchr(val, ':')) current_device.device = strtol(val, NULL, 16); } else if (str_startswith(line, "SVendor:")) { val = line + sizeof("SVendor:"); current_device.subvendor = strtol(val, NULL, 16); } else if (str_startswith(line, "SDevice:")) { val = line + sizeof("SDevice:"); current_device.subdevice = strtol(val, NULL, 16); } else if (str_startswith(line, "Rev:")) { val = line + sizeof("Rev:"); current_device.revision = strtol(val, NULL, 16); } else if (str_startswith(line, "ProgIf:")) { val = line + sizeof("ProgIf:"); current_device.progif = strtol(val, NULL, 16); } else if (strspn(line, " \t") == strlen(line)) { /* Blank line. Send collected information over channel */ snprintf(buf, sizeof(buf), "%04x,%04x,%04x,%04x,%04x,%02x,%02x\n", current_device.klass, current_device.vendor, current_device.device, current_device.subvendor, current_device.subdevice, current_device.revision, current_device.progif); lspci_send(buf); memset(&current_device, 0, sizeof(current_device)); } else { logger(Core, Warning, "handle_child_line(), Unrecognized lspci line '%s'", line); } return True; } /* Process one line of input from virtual channel */ static RD_BOOL lspci_process_line(const char *line, void *data) { UNUSED(data); char *lspci_command[5] = { "lspci", "-m", "-n", "-v", NULL }; if (!strcmp(line, "LSPCI")) { memset(&current_device, 0, sizeof(current_device)); subprocess(lspci_command, handle_child_line, NULL); /* Send single dot to indicate end of enumeration */ lspci_send(".\n"); } else { logger(Core, Error, "lspci_process_line(), invalid line '%s'", line); } return True; } /* Process new data from the virtual channel */ static void lspci_process(STREAM s) { unsigned int pkglen; static char *rest = NULL; char *buf; pkglen = s->end - s->p; /* str_handle_lines requires null terminated strings */ buf = xmalloc(pkglen + 1); STRNCPY(buf, (char *) s->p, pkglen + 1); str_handle_lines(buf, &rest, lspci_process_line, NULL); xfree(buf); } /* Initialize this module: Register the lspci channel */ RD_BOOL lspci_init(void) { lspci_channel = channel_register("lspci", CHANNEL_OPTION_INITIALIZED | CHANNEL_OPTION_ENCRYPT_RDP, lspci_process); return (lspci_channel != NULL); } /* Send data to channel */ static void lspci_send(const char *output) { STREAM s; size_t len; len = strlen(output); s = channel_init(lspci_channel, len); out_uint8p(s, output, len) s_mark_end(s); channel_send(s, lspci_channel); }
null
/* -*- c-basic-offset: 8 -*- rdesktop: A Remote Desktop Protocol client. Support for the Matrox "lspci" channel Copyright (C) 2005 Matrox Graphics Inc. Copyright 2018 Henrik Andersson <hean01@cendio.se> for Cendio AB This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "rdesktop.h" #include <sys/types.h> #include <unistd.h> static VCHANNEL *lspci_channel; typedef struct _pci_device { uint16 klass; uint16 vendor; uint16 device; uint16 subvendor; uint16 subdevice; uint8 revision; uint8 progif; } pci_device; static pci_device current_device; static void lspci_send(const char *output); /* Handle one line of output from the lspci subprocess */ static RD_BOOL handle_child_line(const char *line, void *data) { UNUSED(data); const char *val; char buf[1024]; if (str_startswith(line, "Class:")) { val = line + sizeof("Class:"); /* Skip whitespace and second Class: occurrence */ val += strspn(val, " \t") + sizeof("Class"); current_device.klass = strtol(val, NULL, 16); } else if (str_startswith(line, "Vendor:")) { val = line + sizeof("Vendor:"); current_device.vendor = strtol(val, NULL, 16); } else if (str_startswith(line, "Device:")) { val = line + sizeof("Device:"); /* Sigh, there are *two* lines tagged as Device:. We are not interested in the domain/bus/slot/func */ if (!strchr(val, ':')) current_device.device = strtol(val, NULL, 16); } else if (str_startswith(line, "SVendor:")) { val = line + sizeof("SVendor:"); current_device.subvendor = strtol(val, NULL, 16); } else if (str_startswith(line, "SDevice:")) { val = line + sizeof("SDevice:"); current_device.subdevice = strtol(val, NULL, 16); } else if (str_startswith(line, "Rev:")) { val = line + sizeof("Rev:"); current_device.revision = strtol(val, NULL, 16); } else if (str_startswith(line, "ProgIf:")) { val = line + sizeof("ProgIf:"); current_device.progif = strtol(val, NULL, 16); } else if (strspn(line, " \t") == strlen(line)) { /* Blank line. Send collected information over channel */ snprintf(buf, sizeof(buf), "%04x,%04x,%04x,%04x,%04x,%02x,%02x\n", current_device.klass, current_device.vendor, current_device.device, current_device.subvendor, current_device.subdevice, current_device.revision, current_device.progif); lspci_send(buf); memset(&current_device, 0, sizeof(current_device)); } else { logger(Core, Warning, "handle_child_line(), Unrecognized lspci line '%s'", line); } return True; } /* Process one line of input from virtual channel */ static RD_BOOL lspci_process_line(const char *line, void *data) { UNUSED(data); char *lspci_command[5] = { "lspci", "-m", "-n", "-v", NULL }; if (!strcmp(line, "LSPCI")) { memset(&current_device, 0, sizeof(current_device)); subprocess(lspci_command, handle_child_line, NULL); /* Send single dot to indicate end of enumeration */ lspci_send(".\n"); } else { logger(Core, Error, "lspci_process_line(), invalid line '%s'", line); } return True; } /* Process new data from the virtual channel */ static void lspci_process(STREAM s) { unsigned int pkglen; static char *rest = NULL; char *buf; struct stream packet = *s; if (!s_check(s)) { rdp_protocol_error("lspci_process(), stream is in unstable state", &packet); } pkglen = s->end - s->p; /* str_handle_lines requires null terminated strings */ buf = xmalloc(pkglen + 1); STRNCPY(buf, (char *) s->p, pkglen + 1); str_handle_lines(buf, &rest, lspci_process_line, NULL); xfree(buf); } /* Initialize this module: Register the lspci channel */ RD_BOOL lspci_init(void) { lspci_channel = channel_register("lspci", CHANNEL_OPTION_INITIALIZED | CHANNEL_OPTION_ENCRYPT_RDP, lspci_process); return (lspci_channel != NULL); } /* Send data to channel */ static void lspci_send(const char *output) { STREAM s; size_t len; len = strlen(output); s = channel_init(lspci_channel, len); out_uint8p(s, output, len) s_mark_end(s); channel_send(s, lspci_channel); }
null
105
CWE-787
CVE-2018-8795
/* -*- c-basic-offset: 8 -*- rdesktop: A Remote Desktop Protocol client. Support for the Matrox "lspci" channel Copyright (C) 2005 Matrox Graphics Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "rdesktop.h" #include <sys/types.h> #include <unistd.h> static VCHANNEL *lspci_channel; typedef struct _pci_device { uint16 klass; uint16 vendor; uint16 device; uint16 subvendor; uint16 subdevice; uint8 revision; uint8 progif; } pci_device; static pci_device current_device; static void lspci_send(const char *output); /* Handle one line of output from the lspci subprocess */ static RD_BOOL handle_child_line(const char *line, void *data) { UNUSED(data); const char *val; char buf[1024]; if (str_startswith(line, "Class:")) { val = line + sizeof("Class:"); /* Skip whitespace and second Class: occurrence */ val += strspn(val, " \t") + sizeof("Class"); current_device.klass = strtol(val, NULL, 16); } else if (str_startswith(line, "Vendor:")) { val = line + sizeof("Vendor:"); current_device.vendor = strtol(val, NULL, 16); } else if (str_startswith(line, "Device:")) { val = line + sizeof("Device:"); /* Sigh, there are *two* lines tagged as Device:. We are not interested in the domain/bus/slot/func */ if (!strchr(val, ':')) current_device.device = strtol(val, NULL, 16); } else if (str_startswith(line, "SVendor:")) { val = line + sizeof("SVendor:"); current_device.subvendor = strtol(val, NULL, 16); } else if (str_startswith(line, "SDevice:")) { val = line + sizeof("SDevice:"); current_device.subdevice = strtol(val, NULL, 16); } else if (str_startswith(line, "Rev:")) { val = line + sizeof("Rev:"); current_device.revision = strtol(val, NULL, 16); } else if (str_startswith(line, "ProgIf:")) { val = line + sizeof("ProgIf:"); current_device.progif = strtol(val, NULL, 16); } else if (strspn(line, " \t") == strlen(line)) { /* Blank line. Send collected information over channel */ snprintf(buf, sizeof(buf), "%04x,%04x,%04x,%04x,%04x,%02x,%02x\n", current_device.klass, current_device.vendor, current_device.device, current_device.subvendor, current_device.subdevice, current_device.revision, current_device.progif); lspci_send(buf); memset(&current_device, 0, sizeof(current_device)); } else { logger(Core, Warning, "handle_child_line(), Unrecognized lspci line '%s'", line); } return True; } /* Process one line of input from virtual channel */ static RD_BOOL lspci_process_line(const char *line, void *data) { UNUSED(data); char *lspci_command[5] = { "lspci", "-m", "-n", "-v", NULL }; if (!strcmp(line, "LSPCI")) { memset(&current_device, 0, sizeof(current_device)); subprocess(lspci_command, handle_child_line, NULL); /* Send single dot to indicate end of enumeration */ lspci_send(".\n"); } else { logger(Core, Error, "lspci_process_line(), invalid line '%s'", line); } return True; } /* Process new data from the virtual channel */ static void lspci_process(STREAM s) { unsigned int pkglen; static char *rest = NULL; char *buf; pkglen = s->end - s->p; /* str_handle_lines requires null terminated strings */ buf = xmalloc(pkglen + 1); STRNCPY(buf, (char *) s->p, pkglen + 1); str_handle_lines(buf, &rest, lspci_process_line, NULL); xfree(buf); } /* Initialize this module: Register the lspci channel */ RD_BOOL lspci_init(void) { lspci_channel = channel_register("lspci", CHANNEL_OPTION_INITIALIZED | CHANNEL_OPTION_ENCRYPT_RDP, lspci_process); return (lspci_channel != NULL); } /* Send data to channel */ static void lspci_send(const char *output) { STREAM s; size_t len; len = strlen(output); s = channel_init(lspci_channel, len); out_uint8p(s, output, len) s_mark_end(s); channel_send(s, lspci_channel); }
null
/* -*- c-basic-offset: 8 -*- rdesktop: A Remote Desktop Protocol client. Support for the Matrox "lspci" channel Copyright (C) 2005 Matrox Graphics Inc. Copyright 2018 Henrik Andersson <hean01@cendio.se> for Cendio AB This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "rdesktop.h" #include <sys/types.h> #include <unistd.h> static VCHANNEL *lspci_channel; typedef struct _pci_device { uint16 klass; uint16 vendor; uint16 device; uint16 subvendor; uint16 subdevice; uint8 revision; uint8 progif; } pci_device; static pci_device current_device; static void lspci_send(const char *output); /* Handle one line of output from the lspci subprocess */ static RD_BOOL handle_child_line(const char *line, void *data) { UNUSED(data); const char *val; char buf[1024]; if (str_startswith(line, "Class:")) { val = line + sizeof("Class:"); /* Skip whitespace and second Class: occurrence */ val += strspn(val, " \t") + sizeof("Class"); current_device.klass = strtol(val, NULL, 16); } else if (str_startswith(line, "Vendor:")) { val = line + sizeof("Vendor:"); current_device.vendor = strtol(val, NULL, 16); } else if (str_startswith(line, "Device:")) { val = line + sizeof("Device:"); /* Sigh, there are *two* lines tagged as Device:. We are not interested in the domain/bus/slot/func */ if (!strchr(val, ':')) current_device.device = strtol(val, NULL, 16); } else if (str_startswith(line, "SVendor:")) { val = line + sizeof("SVendor:"); current_device.subvendor = strtol(val, NULL, 16); } else if (str_startswith(line, "SDevice:")) { val = line + sizeof("SDevice:"); current_device.subdevice = strtol(val, NULL, 16); } else if (str_startswith(line, "Rev:")) { val = line + sizeof("Rev:"); current_device.revision = strtol(val, NULL, 16); } else if (str_startswith(line, "ProgIf:")) { val = line + sizeof("ProgIf:"); current_device.progif = strtol(val, NULL, 16); } else if (strspn(line, " \t") == strlen(line)) { /* Blank line. Send collected information over channel */ snprintf(buf, sizeof(buf), "%04x,%04x,%04x,%04x,%04x,%02x,%02x\n", current_device.klass, current_device.vendor, current_device.device, current_device.subvendor, current_device.subdevice, current_device.revision, current_device.progif); lspci_send(buf); memset(&current_device, 0, sizeof(current_device)); } else { logger(Core, Warning, "handle_child_line(), Unrecognized lspci line '%s'", line); } return True; } /* Process one line of input from virtual channel */ static RD_BOOL lspci_process_line(const char *line, void *data) { UNUSED(data); char *lspci_command[5] = { "lspci", "-m", "-n", "-v", NULL }; if (!strcmp(line, "LSPCI")) { memset(&current_device, 0, sizeof(current_device)); subprocess(lspci_command, handle_child_line, NULL); /* Send single dot to indicate end of enumeration */ lspci_send(".\n"); } else { logger(Core, Error, "lspci_process_line(), invalid line '%s'", line); } return True; } /* Process new data from the virtual channel */ static void lspci_process(STREAM s) { unsigned int pkglen; static char *rest = NULL; char *buf; struct stream packet = *s; if (!s_check(s)) { rdp_protocol_error("lspci_process(), stream is in unstable state", &packet); } pkglen = s->end - s->p; /* str_handle_lines requires null terminated strings */ buf = xmalloc(pkglen + 1); STRNCPY(buf, (char *) s->p, pkglen + 1); str_handle_lines(buf, &rest, lspci_process_line, NULL); xfree(buf); } /* Initialize this module: Register the lspci channel */ RD_BOOL lspci_init(void) { lspci_channel = channel_register("lspci", CHANNEL_OPTION_INITIALIZED | CHANNEL_OPTION_ENCRYPT_RDP, lspci_process); return (lspci_channel != NULL); } /* Send data to channel */ static void lspci_send(const char *output) { STREAM s; size_t len; len = strlen(output); s = channel_init(lspci_channel, len); out_uint8p(s, output, len) s_mark_end(s); channel_send(s, lspci_channel); }
null
106
CWE-787
CVE-2018-8797
/* -*- c-basic-offset: 8 -*- rdesktop: A Remote Desktop Protocol client. Support for the Matrox "lspci" channel Copyright (C) 2005 Matrox Graphics Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "rdesktop.h" #include <sys/types.h> #include <unistd.h> static VCHANNEL *lspci_channel; typedef struct _pci_device { uint16 klass; uint16 vendor; uint16 device; uint16 subvendor; uint16 subdevice; uint8 revision; uint8 progif; } pci_device; static pci_device current_device; static void lspci_send(const char *output); /* Handle one line of output from the lspci subprocess */ static RD_BOOL handle_child_line(const char *line, void *data) { UNUSED(data); const char *val; char buf[1024]; if (str_startswith(line, "Class:")) { val = line + sizeof("Class:"); /* Skip whitespace and second Class: occurrence */ val += strspn(val, " \t") + sizeof("Class"); current_device.klass = strtol(val, NULL, 16); } else if (str_startswith(line, "Vendor:")) { val = line + sizeof("Vendor:"); current_device.vendor = strtol(val, NULL, 16); } else if (str_startswith(line, "Device:")) { val = line + sizeof("Device:"); /* Sigh, there are *two* lines tagged as Device:. We are not interested in the domain/bus/slot/func */ if (!strchr(val, ':')) current_device.device = strtol(val, NULL, 16); } else if (str_startswith(line, "SVendor:")) { val = line + sizeof("SVendor:"); current_device.subvendor = strtol(val, NULL, 16); } else if (str_startswith(line, "SDevice:")) { val = line + sizeof("SDevice:"); current_device.subdevice = strtol(val, NULL, 16); } else if (str_startswith(line, "Rev:")) { val = line + sizeof("Rev:"); current_device.revision = strtol(val, NULL, 16); } else if (str_startswith(line, "ProgIf:")) { val = line + sizeof("ProgIf:"); current_device.progif = strtol(val, NULL, 16); } else if (strspn(line, " \t") == strlen(line)) { /* Blank line. Send collected information over channel */ snprintf(buf, sizeof(buf), "%04x,%04x,%04x,%04x,%04x,%02x,%02x\n", current_device.klass, current_device.vendor, current_device.device, current_device.subvendor, current_device.subdevice, current_device.revision, current_device.progif); lspci_send(buf); memset(&current_device, 0, sizeof(current_device)); } else { logger(Core, Warning, "handle_child_line(), Unrecognized lspci line '%s'", line); } return True; } /* Process one line of input from virtual channel */ static RD_BOOL lspci_process_line(const char *line, void *data) { UNUSED(data); char *lspci_command[5] = { "lspci", "-m", "-n", "-v", NULL }; if (!strcmp(line, "LSPCI")) { memset(&current_device, 0, sizeof(current_device)); subprocess(lspci_command, handle_child_line, NULL); /* Send single dot to indicate end of enumeration */ lspci_send(".\n"); } else { logger(Core, Error, "lspci_process_line(), invalid line '%s'", line); } return True; } /* Process new data from the virtual channel */ static void lspci_process(STREAM s) { unsigned int pkglen; static char *rest = NULL; char *buf; pkglen = s->end - s->p; /* str_handle_lines requires null terminated strings */ buf = xmalloc(pkglen + 1); STRNCPY(buf, (char *) s->p, pkglen + 1); str_handle_lines(buf, &rest, lspci_process_line, NULL); xfree(buf); } /* Initialize this module: Register the lspci channel */ RD_BOOL lspci_init(void) { lspci_channel = channel_register("lspci", CHANNEL_OPTION_INITIALIZED | CHANNEL_OPTION_ENCRYPT_RDP, lspci_process); return (lspci_channel != NULL); } /* Send data to channel */ static void lspci_send(const char *output) { STREAM s; size_t len; len = strlen(output); s = channel_init(lspci_channel, len); out_uint8p(s, output, len) s_mark_end(s); channel_send(s, lspci_channel); }
null
/* -*- c-basic-offset: 8 -*- rdesktop: A Remote Desktop Protocol client. Support for the Matrox "lspci" channel Copyright (C) 2005 Matrox Graphics Inc. Copyright 2018 Henrik Andersson <hean01@cendio.se> for Cendio AB This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "rdesktop.h" #include <sys/types.h> #include <unistd.h> static VCHANNEL *lspci_channel; typedef struct _pci_device { uint16 klass; uint16 vendor; uint16 device; uint16 subvendor; uint16 subdevice; uint8 revision; uint8 progif; } pci_device; static pci_device current_device; static void lspci_send(const char *output); /* Handle one line of output from the lspci subprocess */ static RD_BOOL handle_child_line(const char *line, void *data) { UNUSED(data); const char *val; char buf[1024]; if (str_startswith(line, "Class:")) { val = line + sizeof("Class:"); /* Skip whitespace and second Class: occurrence */ val += strspn(val, " \t") + sizeof("Class"); current_device.klass = strtol(val, NULL, 16); } else if (str_startswith(line, "Vendor:")) { val = line + sizeof("Vendor:"); current_device.vendor = strtol(val, NULL, 16); } else if (str_startswith(line, "Device:")) { val = line + sizeof("Device:"); /* Sigh, there are *two* lines tagged as Device:. We are not interested in the domain/bus/slot/func */ if (!strchr(val, ':')) current_device.device = strtol(val, NULL, 16); } else if (str_startswith(line, "SVendor:")) { val = line + sizeof("SVendor:"); current_device.subvendor = strtol(val, NULL, 16); } else if (str_startswith(line, "SDevice:")) { val = line + sizeof("SDevice:"); current_device.subdevice = strtol(val, NULL, 16); } else if (str_startswith(line, "Rev:")) { val = line + sizeof("Rev:"); current_device.revision = strtol(val, NULL, 16); } else if (str_startswith(line, "ProgIf:")) { val = line + sizeof("ProgIf:"); current_device.progif = strtol(val, NULL, 16); } else if (strspn(line, " \t") == strlen(line)) { /* Blank line. Send collected information over channel */ snprintf(buf, sizeof(buf), "%04x,%04x,%04x,%04x,%04x,%02x,%02x\n", current_device.klass, current_device.vendor, current_device.device, current_device.subvendor, current_device.subdevice, current_device.revision, current_device.progif); lspci_send(buf); memset(&current_device, 0, sizeof(current_device)); } else { logger(Core, Warning, "handle_child_line(), Unrecognized lspci line '%s'", line); } return True; } /* Process one line of input from virtual channel */ static RD_BOOL lspci_process_line(const char *line, void *data) { UNUSED(data); char *lspci_command[5] = { "lspci", "-m", "-n", "-v", NULL }; if (!strcmp(line, "LSPCI")) { memset(&current_device, 0, sizeof(current_device)); subprocess(lspci_command, handle_child_line, NULL); /* Send single dot to indicate end of enumeration */ lspci_send(".\n"); } else { logger(Core, Error, "lspci_process_line(), invalid line '%s'", line); } return True; } /* Process new data from the virtual channel */ static void lspci_process(STREAM s) { unsigned int pkglen; static char *rest = NULL; char *buf; struct stream packet = *s; if (!s_check(s)) { rdp_protocol_error("lspci_process(), stream is in unstable state", &packet); } pkglen = s->end - s->p; /* str_handle_lines requires null terminated strings */ buf = xmalloc(pkglen + 1); STRNCPY(buf, (char *) s->p, pkglen + 1); str_handle_lines(buf, &rest, lspci_process_line, NULL); xfree(buf); } /* Initialize this module: Register the lspci channel */ RD_BOOL lspci_init(void) { lspci_channel = channel_register("lspci", CHANNEL_OPTION_INITIALIZED | CHANNEL_OPTION_ENCRYPT_RDP, lspci_process); return (lspci_channel != NULL); } /* Send data to channel */ static void lspci_send(const char *output) { STREAM s; size_t len; len = strlen(output); s = channel_init(lspci_channel, len); out_uint8p(s, output, len) s_mark_end(s); channel_send(s, lspci_channel); }
null
107
CWE-787
CVE-2018-8800
/* -*- c-basic-offset: 8 -*- rdesktop: A Remote Desktop Protocol client. Support for the Matrox "lspci" channel Copyright (C) 2005 Matrox Graphics Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "rdesktop.h" #include <sys/types.h> #include <unistd.h> static VCHANNEL *lspci_channel; typedef struct _pci_device { uint16 klass; uint16 vendor; uint16 device; uint16 subvendor; uint16 subdevice; uint8 revision; uint8 progif; } pci_device; static pci_device current_device; static void lspci_send(const char *output); /* Handle one line of output from the lspci subprocess */ static RD_BOOL handle_child_line(const char *line, void *data) { UNUSED(data); const char *val; char buf[1024]; if (str_startswith(line, "Class:")) { val = line + sizeof("Class:"); /* Skip whitespace and second Class: occurrence */ val += strspn(val, " \t") + sizeof("Class"); current_device.klass = strtol(val, NULL, 16); } else if (str_startswith(line, "Vendor:")) { val = line + sizeof("Vendor:"); current_device.vendor = strtol(val, NULL, 16); } else if (str_startswith(line, "Device:")) { val = line + sizeof("Device:"); /* Sigh, there are *two* lines tagged as Device:. We are not interested in the domain/bus/slot/func */ if (!strchr(val, ':')) current_device.device = strtol(val, NULL, 16); } else if (str_startswith(line, "SVendor:")) { val = line + sizeof("SVendor:"); current_device.subvendor = strtol(val, NULL, 16); } else if (str_startswith(line, "SDevice:")) { val = line + sizeof("SDevice:"); current_device.subdevice = strtol(val, NULL, 16); } else if (str_startswith(line, "Rev:")) { val = line + sizeof("Rev:"); current_device.revision = strtol(val, NULL, 16); } else if (str_startswith(line, "ProgIf:")) { val = line + sizeof("ProgIf:"); current_device.progif = strtol(val, NULL, 16); } else if (strspn(line, " \t") == strlen(line)) { /* Blank line. Send collected information over channel */ snprintf(buf, sizeof(buf), "%04x,%04x,%04x,%04x,%04x,%02x,%02x\n", current_device.klass, current_device.vendor, current_device.device, current_device.subvendor, current_device.subdevice, current_device.revision, current_device.progif); lspci_send(buf); memset(&current_device, 0, sizeof(current_device)); } else { logger(Core, Warning, "handle_child_line(), Unrecognized lspci line '%s'", line); } return True; } /* Process one line of input from virtual channel */ static RD_BOOL lspci_process_line(const char *line, void *data) { UNUSED(data); char *lspci_command[5] = { "lspci", "-m", "-n", "-v", NULL }; if (!strcmp(line, "LSPCI")) { memset(&current_device, 0, sizeof(current_device)); subprocess(lspci_command, handle_child_line, NULL); /* Send single dot to indicate end of enumeration */ lspci_send(".\n"); } else { logger(Core, Error, "lspci_process_line(), invalid line '%s'", line); } return True; } /* Process new data from the virtual channel */ static void lspci_process(STREAM s) { unsigned int pkglen; static char *rest = NULL; char *buf; pkglen = s->end - s->p; /* str_handle_lines requires null terminated strings */ buf = xmalloc(pkglen + 1); STRNCPY(buf, (char *) s->p, pkglen + 1); str_handle_lines(buf, &rest, lspci_process_line, NULL); xfree(buf); } /* Initialize this module: Register the lspci channel */ RD_BOOL lspci_init(void) { lspci_channel = channel_register("lspci", CHANNEL_OPTION_INITIALIZED | CHANNEL_OPTION_ENCRYPT_RDP, lspci_process); return (lspci_channel != NULL); } /* Send data to channel */ static void lspci_send(const char *output) { STREAM s; size_t len; len = strlen(output); s = channel_init(lspci_channel, len); out_uint8p(s, output, len) s_mark_end(s); channel_send(s, lspci_channel); }
null
/* -*- c-basic-offset: 8 -*- rdesktop: A Remote Desktop Protocol client. Support for the Matrox "lspci" channel Copyright (C) 2005 Matrox Graphics Inc. Copyright 2018 Henrik Andersson <hean01@cendio.se> for Cendio AB This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "rdesktop.h" #include <sys/types.h> #include <unistd.h> static VCHANNEL *lspci_channel; typedef struct _pci_device { uint16 klass; uint16 vendor; uint16 device; uint16 subvendor; uint16 subdevice; uint8 revision; uint8 progif; } pci_device; static pci_device current_device; static void lspci_send(const char *output); /* Handle one line of output from the lspci subprocess */ static RD_BOOL handle_child_line(const char *line, void *data) { UNUSED(data); const char *val; char buf[1024]; if (str_startswith(line, "Class:")) { val = line + sizeof("Class:"); /* Skip whitespace and second Class: occurrence */ val += strspn(val, " \t") + sizeof("Class"); current_device.klass = strtol(val, NULL, 16); } else if (str_startswith(line, "Vendor:")) { val = line + sizeof("Vendor:"); current_device.vendor = strtol(val, NULL, 16); } else if (str_startswith(line, "Device:")) { val = line + sizeof("Device:"); /* Sigh, there are *two* lines tagged as Device:. We are not interested in the domain/bus/slot/func */ if (!strchr(val, ':')) current_device.device = strtol(val, NULL, 16); } else if (str_startswith(line, "SVendor:")) { val = line + sizeof("SVendor:"); current_device.subvendor = strtol(val, NULL, 16); } else if (str_startswith(line, "SDevice:")) { val = line + sizeof("SDevice:"); current_device.subdevice = strtol(val, NULL, 16); } else if (str_startswith(line, "Rev:")) { val = line + sizeof("Rev:"); current_device.revision = strtol(val, NULL, 16); } else if (str_startswith(line, "ProgIf:")) { val = line + sizeof("ProgIf:"); current_device.progif = strtol(val, NULL, 16); } else if (strspn(line, " \t") == strlen(line)) { /* Blank line. Send collected information over channel */ snprintf(buf, sizeof(buf), "%04x,%04x,%04x,%04x,%04x,%02x,%02x\n", current_device.klass, current_device.vendor, current_device.device, current_device.subvendor, current_device.subdevice, current_device.revision, current_device.progif); lspci_send(buf); memset(&current_device, 0, sizeof(current_device)); } else { logger(Core, Warning, "handle_child_line(), Unrecognized lspci line '%s'", line); } return True; } /* Process one line of input from virtual channel */ static RD_BOOL lspci_process_line(const char *line, void *data) { UNUSED(data); char *lspci_command[5] = { "lspci", "-m", "-n", "-v", NULL }; if (!strcmp(line, "LSPCI")) { memset(&current_device, 0, sizeof(current_device)); subprocess(lspci_command, handle_child_line, NULL); /* Send single dot to indicate end of enumeration */ lspci_send(".\n"); } else { logger(Core, Error, "lspci_process_line(), invalid line '%s'", line); } return True; } /* Process new data from the virtual channel */ static void lspci_process(STREAM s) { unsigned int pkglen; static char *rest = NULL; char *buf; struct stream packet = *s; if (!s_check(s)) { rdp_protocol_error("lspci_process(), stream is in unstable state", &packet); } pkglen = s->end - s->p; /* str_handle_lines requires null terminated strings */ buf = xmalloc(pkglen + 1); STRNCPY(buf, (char *) s->p, pkglen + 1); str_handle_lines(buf, &rest, lspci_process_line, NULL); xfree(buf); } /* Initialize this module: Register the lspci channel */ RD_BOOL lspci_init(void) { lspci_channel = channel_register("lspci", CHANNEL_OPTION_INITIALIZED | CHANNEL_OPTION_ENCRYPT_RDP, lspci_process); return (lspci_channel != NULL); } /* Send data to channel */ static void lspci_send(const char *output) { STREAM s; size_t len; len = strlen(output); s = channel_init(lspci_channel, len); out_uint8p(s, output, len) s_mark_end(s); channel_send(s, lspci_channel); }
null
108
CWE-787
CVE-2018-8828
/* * Copyright (C) 2014 Daniel-Constantin Mierla (asipto.com) * * This file is part of kamailio, a free SIP server. * * Kamailio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version * * Kamailio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /*! \file * \brief TMX :: Pretran * * \ingroup tm * - Module: \ref tm */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include "../../core/dprint.h" #include "../../core/mem/shm_mem.h" #include "../../core/locking.h" #include "../../core/hashes.h" #include "../../core/config.h" #include "../../core/parser/parse_via.h" #include "../../core/parser/parse_from.h" #include "../../core/route.h" #include "../../core/trim.h" #include "../../core/pt.h" #include "tmx_pretran.h" typedef struct _pretran { unsigned int hid; unsigned int linked; str callid; str ftag; str cseqnum; str cseqmet; unsigned int cseqmetid; str vbranch; str dbuf; int pid; struct _pretran *next; struct _pretran *prev; } pretran_t; typedef struct pretran_slot { pretran_t *plist; gen_lock_t lock; } pretran_slot_t; static pretran_t *_tmx_proc_ptran = NULL; static pretran_slot_t *_tmx_ptran_table = NULL; static int _tmx_ptran_size = 0; /** * */ int tmx_init_pretran_table(void) { int n; int pn; pn = get_max_procs(); if(pn<=0) return -1; if(_tmx_ptran_table!=NULL) return -1; /* get the highest power of two less than number of processes */ n = -1; while (pn >> ++n > 0); n--; if(n<=1) n = 2; if(n>8) n = 8; _tmx_ptran_size = 1<<n; _tmx_ptran_table = (pretran_slot_t*)shm_malloc(_tmx_ptran_size*sizeof(pretran_slot_t)); if(_tmx_ptran_table == NULL) { LM_ERR("not enough shared memory\n"); return -1; } memset(_tmx_ptran_table, 0, _tmx_ptran_size*sizeof(pretran_slot_t)); for(n=0; n<_tmx_ptran_size; n++) { if(lock_init(&_tmx_ptran_table[n].lock)==NULL) { LM_ERR("cannot init the lock %d\n", n); n--; while(n>=0) { lock_destroy(&_tmx_ptran_table[n].lock); n--; } shm_free(_tmx_ptran_table); _tmx_ptran_table = 0; _tmx_ptran_size = 0; return -1; } } return 0; } /** * */ void tmx_pretran_link_safe(int slotid) { if(_tmx_proc_ptran==NULL) return; if(_tmx_ptran_table[slotid].plist==NULL) { _tmx_ptran_table[slotid].plist = _tmx_proc_ptran; _tmx_proc_ptran->linked = 1; return; } _tmx_proc_ptran->next = _tmx_ptran_table[slotid].plist; _tmx_ptran_table[slotid].plist->prev = _tmx_proc_ptran; _tmx_ptran_table[slotid].plist = _tmx_proc_ptran; _tmx_proc_ptran->linked = 1; return; } /** * */ void tmx_pretran_unlink_safe(int slotid) { if(_tmx_proc_ptran==NULL) return; if(_tmx_proc_ptran->linked == 0) return; if(_tmx_ptran_table[slotid].plist==NULL) { _tmx_proc_ptran->prev = _tmx_proc_ptran->next = NULL; _tmx_proc_ptran->linked = 0; return; } if(_tmx_proc_ptran->prev==NULL) { _tmx_ptran_table[slotid].plist = _tmx_proc_ptran->next; if(_tmx_ptran_table[slotid].plist!=NULL) _tmx_ptran_table[slotid].plist->prev = NULL; } else { _tmx_proc_ptran->prev->next = _tmx_proc_ptran->next; if(_tmx_proc_ptran->next) _tmx_proc_ptran->next->prev = _tmx_proc_ptran->prev; } _tmx_proc_ptran->prev = _tmx_proc_ptran->next = NULL; _tmx_proc_ptran->linked = 0; return; } /** * */ void tmx_pretran_unlink(void) { int slotid; if(_tmx_proc_ptran==NULL) return; slotid = _tmx_proc_ptran->hid & (_tmx_ptran_size-1); lock_get(&_tmx_ptran_table[slotid].lock); tmx_pretran_unlink_safe(slotid); lock_release(&_tmx_ptran_table[slotid].lock); } /** * return: * - -1: error * - 0: not found * - 1: found */ int tmx_check_pretran(sip_msg_t *msg) { unsigned int chid; unsigned int slotid; int dsize; struct via_param *vbr; str scallid; str scseqmet; str scseqnum; str sftag; str svbranch = {NULL, 0}; pretran_t *it; if(_tmx_ptran_table==NULL) { LM_ERR("pretran hash table not initialized yet\n"); return -1; } if(get_route_type()!=REQUEST_ROUTE) { LM_ERR("invalid usage - not in request route\n"); return -1; } if(msg->first_line.type!=SIP_REQUEST) { LM_ERR("invalid usage - not a sip request\n"); return -1; } if(parse_headers(msg, HDR_FROM_F|HDR_VIA1_F|HDR_CALLID_F|HDR_CSEQ_F, 0)<0) { LM_ERR("failed to parse required headers\n"); return -1; } if(msg->cseq==NULL || msg->cseq->parsed==NULL) { LM_ERR("failed to parse cseq headers\n"); return -1; } if(get_cseq(msg)->method_id==METHOD_ACK || get_cseq(msg)->method_id==METHOD_CANCEL) { LM_DBG("no pre-transaction management for ACK or CANCEL\n"); return -1; } if (msg->via1==0) { LM_ERR("failed to get Via header\n"); return -1; } if (parse_from_header(msg)<0 || get_from(msg)->tag_value.len==0) { LM_ERR("failed to get From header\n"); return -1; } if (msg->callid==NULL || msg->callid->body.s==NULL) { LM_ERR("failed to parse callid headers\n"); return -1; } vbr = msg->via1->branch; scallid = msg->callid->body; trim(&scallid); scseqmet = get_cseq(msg)->method; trim(&scseqmet); scseqnum = get_cseq(msg)->number; trim(&scseqnum); sftag = get_from(msg)->tag_value; trim(&sftag); chid = get_hash1_raw(msg->callid->body.s, msg->callid->body.len); slotid = chid & (_tmx_ptran_size-1); if(unlikely(_tmx_proc_ptran == NULL)) { _tmx_proc_ptran = (pretran_t*)shm_malloc(sizeof(pretran_t)); if(_tmx_proc_ptran == NULL) { LM_ERR("not enough memory for pretran structure\n"); return -1; } memset(_tmx_proc_ptran, 0, sizeof(pretran_t)); _tmx_proc_ptran->pid = my_pid(); } dsize = scallid.len + scseqnum.len + scseqmet.len + sftag.len + 4; if(likely(vbr!=NULL)) { svbranch = vbr->value; trim(&svbranch); dsize += svbranch.len; } if(dsize<256) dsize = 256; tmx_pretran_unlink(); if(dsize > _tmx_proc_ptran->dbuf.len) { if(_tmx_proc_ptran->dbuf.s) shm_free(_tmx_proc_ptran->dbuf.s); _tmx_proc_ptran->dbuf.s = (char*)shm_malloc(dsize); if(_tmx_proc_ptran->dbuf.s==NULL) { LM_ERR("not enough memory for pretran data\n"); return -1; } _tmx_proc_ptran->dbuf.len = dsize; } _tmx_proc_ptran->hid = chid; _tmx_proc_ptran->cseqmetid = (get_cseq(msg))->method_id; _tmx_proc_ptran->callid.s = _tmx_proc_ptran->dbuf.s; memcpy(_tmx_proc_ptran->callid.s, scallid.s, scallid.len); _tmx_proc_ptran->callid.len = scallid.len; _tmx_proc_ptran->callid.s[_tmx_proc_ptran->callid.len] = '\0'; _tmx_proc_ptran->ftag.s = _tmx_proc_ptran->callid.s + _tmx_proc_ptran->callid.len + 1; memcpy(_tmx_proc_ptran->ftag.s, sftag.s, sftag.len); _tmx_proc_ptran->ftag.len = sftag.len; _tmx_proc_ptran->ftag.s[_tmx_proc_ptran->ftag.len] = '\0'; _tmx_proc_ptran->cseqnum.s = _tmx_proc_ptran->ftag.s + _tmx_proc_ptran->ftag.len + 1; memcpy(_tmx_proc_ptran->cseqnum.s, scseqnum.s, scseqnum.len); _tmx_proc_ptran->cseqnum.len = scseqnum.len; _tmx_proc_ptran->cseqnum.s[_tmx_proc_ptran->cseqnum.len] = '\0'; _tmx_proc_ptran->cseqmet.s = _tmx_proc_ptran->cseqnum.s + _tmx_proc_ptran->cseqnum.len + 1; memcpy(_tmx_proc_ptran->cseqmet.s, scseqmet.s, scseqmet.len); _tmx_proc_ptran->cseqmet.len = scseqmet.len; _tmx_proc_ptran->cseqmet.s[_tmx_proc_ptran->cseqmet.len] = '\0'; if(likely(vbr!=NULL)) { _tmx_proc_ptran->vbranch.s = _tmx_proc_ptran->cseqmet.s + _tmx_proc_ptran->cseqmet.len + 1; memcpy(_tmx_proc_ptran->vbranch.s, svbranch.s, svbranch.len); _tmx_proc_ptran->vbranch.len = svbranch.len; _tmx_proc_ptran->vbranch.s[_tmx_proc_ptran->vbranch.len] = '\0'; } else { _tmx_proc_ptran->vbranch.s = NULL; _tmx_proc_ptran->vbranch.len = 0; } lock_get(&_tmx_ptran_table[slotid].lock); it = _tmx_ptran_table[slotid].plist; tmx_pretran_link_safe(slotid); for(; it!=NULL; it=it->next) { if(_tmx_proc_ptran->hid != it->hid || _tmx_proc_ptran->cseqmetid != it->cseqmetid || _tmx_proc_ptran->callid.len != it->callid.len || _tmx_proc_ptran->ftag.len != it->ftag.len || _tmx_proc_ptran->cseqmet.len != it->cseqmet.len || _tmx_proc_ptran->cseqnum.len != it->cseqnum.len) continue; if(_tmx_proc_ptran->vbranch.s != NULL && it->vbranch.s != NULL) { if(_tmx_proc_ptran->vbranch.len != it->vbranch.len) continue; /* shortcut - check last char in Via branch * - kamailio/ser adds there branch index => in case of paralel * forking by previous hop, catch it here quickly */ if(_tmx_proc_ptran->vbranch.s[it->vbranch.len-1] != it->vbranch.s[it->vbranch.len-1]) continue; if(memcmp(_tmx_proc_ptran->vbranch.s, it->vbranch.s, it->vbranch.len)!=0) continue; /* shall stop by matching magic cookie? * if (vbr && vbr->value.s && vbr->value.len > MCOOKIE_LEN * && memcmp(vbr->value.s, MCOOKIE, MCOOKIE_LEN)==0) { * LM_DBG("rfc3261 cookie found in Via branch\n"); * } */ } if(memcmp(_tmx_proc_ptran->callid.s, it->callid.s, it->callid.len)!=0 || memcmp(_tmx_proc_ptran->ftag.s, it->ftag.s, it->ftag.len)!=0 || memcmp(_tmx_proc_ptran->cseqnum.s, it->cseqnum.s, it->cseqnum.len)!=0) continue; if((it->cseqmetid==METHOD_OTHER || it->cseqmetid==METHOD_UNDEF) && memcmp(_tmx_proc_ptran->cseqmet.s, it->cseqmet.s, it->cseqmet.len)!=0) continue; LM_DBG("matched another pre-transaction by pid %d for [%.*s]\n", it->pid, it->callid.len, it->callid.s); lock_release(&_tmx_ptran_table[slotid].lock); return 1; } lock_release(&_tmx_ptran_table[slotid].lock); return 0; }
null
/* * Copyright (C) 2014 Daniel-Constantin Mierla (asipto.com) * * This file is part of kamailio, a free SIP server. * * Kamailio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version * * Kamailio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /*! \file * \brief TMX :: Pretran * * \ingroup tm * - Module: \ref tm */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include "../../core/dprint.h" #include "../../core/mem/shm_mem.h" #include "../../core/locking.h" #include "../../core/hashes.h" #include "../../core/config.h" #include "../../core/parser/parse_via.h" #include "../../core/parser/parse_from.h" #include "../../core/route.h" #include "../../core/trim.h" #include "../../core/pt.h" #include "tmx_pretran.h" typedef struct _pretran { unsigned int hid; unsigned int linked; str callid; str ftag; str cseqnum; str cseqmet; unsigned int cseqmetid; str vbranch; str dbuf; int pid; struct _pretran *next; struct _pretran *prev; } pretran_t; typedef struct pretran_slot { pretran_t *plist; gen_lock_t lock; } pretran_slot_t; static pretran_t *_tmx_proc_ptran = NULL; static pretran_slot_t *_tmx_ptran_table = NULL; static int _tmx_ptran_size = 0; /** * */ int tmx_init_pretran_table(void) { int n; int pn; pn = get_max_procs(); if(pn<=0) return -1; if(_tmx_ptran_table!=NULL) return -1; /* get the highest power of two less than number of processes */ n = -1; while (pn >> ++n > 0); n--; if(n<=1) n = 2; if(n>8) n = 8; _tmx_ptran_size = 1<<n; _tmx_ptran_table = (pretran_slot_t*)shm_malloc(_tmx_ptran_size*sizeof(pretran_slot_t)); if(_tmx_ptran_table == NULL) { LM_ERR("not enough shared memory\n"); return -1; } memset(_tmx_ptran_table, 0, _tmx_ptran_size*sizeof(pretran_slot_t)); for(n=0; n<_tmx_ptran_size; n++) { if(lock_init(&_tmx_ptran_table[n].lock)==NULL) { LM_ERR("cannot init the lock %d\n", n); n--; while(n>=0) { lock_destroy(&_tmx_ptran_table[n].lock); n--; } shm_free(_tmx_ptran_table); _tmx_ptran_table = 0; _tmx_ptran_size = 0; return -1; } } return 0; } /** * */ void tmx_pretran_link_safe(int slotid) { if(_tmx_proc_ptran==NULL) return; if(_tmx_ptran_table[slotid].plist==NULL) { _tmx_ptran_table[slotid].plist = _tmx_proc_ptran; _tmx_proc_ptran->linked = 1; return; } _tmx_proc_ptran->next = _tmx_ptran_table[slotid].plist; _tmx_ptran_table[slotid].plist->prev = _tmx_proc_ptran; _tmx_ptran_table[slotid].plist = _tmx_proc_ptran; _tmx_proc_ptran->linked = 1; return; } /** * */ void tmx_pretran_unlink_safe(int slotid) { if(_tmx_proc_ptran==NULL) return; if(_tmx_proc_ptran->linked == 0) return; if(_tmx_ptran_table[slotid].plist==NULL) { _tmx_proc_ptran->prev = _tmx_proc_ptran->next = NULL; _tmx_proc_ptran->linked = 0; return; } if(_tmx_proc_ptran->prev==NULL) { _tmx_ptran_table[slotid].plist = _tmx_proc_ptran->next; if(_tmx_ptran_table[slotid].plist!=NULL) _tmx_ptran_table[slotid].plist->prev = NULL; } else { _tmx_proc_ptran->prev->next = _tmx_proc_ptran->next; if(_tmx_proc_ptran->next) _tmx_proc_ptran->next->prev = _tmx_proc_ptran->prev; } _tmx_proc_ptran->prev = _tmx_proc_ptran->next = NULL; _tmx_proc_ptran->linked = 0; return; } /** * */ void tmx_pretran_unlink(void) { int slotid; if(_tmx_proc_ptran==NULL) return; slotid = _tmx_proc_ptran->hid & (_tmx_ptran_size-1); lock_get(&_tmx_ptran_table[slotid].lock); tmx_pretran_unlink_safe(slotid); lock_release(&_tmx_ptran_table[slotid].lock); } /** * return: * - -1: error * - 0: not found * - 1: found */ int tmx_check_pretran(sip_msg_t *msg) { unsigned int chid; unsigned int slotid; int dsize; struct via_param *vbr; str scallid; str scseqmet; str scseqnum; str sftag; str svbranch = {NULL, 0}; pretran_t *it; if(_tmx_ptran_table==NULL) { LM_ERR("pretran hash table not initialized yet\n"); return -1; } if(get_route_type()!=REQUEST_ROUTE) { LM_ERR("invalid usage - not in request route\n"); return -1; } if(msg->first_line.type!=SIP_REQUEST) { LM_ERR("invalid usage - not a sip request\n"); return -1; } if(parse_headers(msg, HDR_FROM_F|HDR_VIA1_F|HDR_CALLID_F|HDR_CSEQ_F, 0)<0) { LM_ERR("failed to parse required headers\n"); return -1; } if(msg->cseq==NULL || msg->cseq->parsed==NULL) { LM_ERR("failed to parse cseq headers\n"); return -1; } if(get_cseq(msg)->method_id==METHOD_ACK || get_cseq(msg)->method_id==METHOD_CANCEL) { LM_DBG("no pre-transaction management for ACK or CANCEL\n"); return -1; } if (msg->via1==0) { LM_ERR("failed to get Via header\n"); return -1; } if (parse_from_header(msg)<0 || get_from(msg)->tag_value.len==0) { LM_ERR("failed to get From header\n"); return -1; } if (msg->callid==NULL || msg->callid->body.s==NULL) { LM_ERR("failed to parse callid headers\n"); return -1; } vbr = msg->via1->branch; scallid = msg->callid->body; trim(&scallid); scseqmet = get_cseq(msg)->method; trim(&scseqmet); scseqnum = get_cseq(msg)->number; trim(&scseqnum); sftag = get_from(msg)->tag_value; trim(&sftag); chid = get_hash1_raw(msg->callid->body.s, msg->callid->body.len); slotid = chid & (_tmx_ptran_size-1); if(unlikely(_tmx_proc_ptran == NULL)) { _tmx_proc_ptran = (pretran_t*)shm_malloc(sizeof(pretran_t)); if(_tmx_proc_ptran == NULL) { LM_ERR("not enough memory for pretran structure\n"); return -1; } memset(_tmx_proc_ptran, 0, sizeof(pretran_t)); _tmx_proc_ptran->pid = my_pid(); } dsize = scallid.len + scseqnum.len + scseqmet.len + sftag.len + 4; if(likely(vbr!=NULL)) { svbranch = vbr->value; trim(&svbranch); dsize += svbranch.len + 1; } if(dsize<256) dsize = 256; tmx_pretran_unlink(); if(dsize > _tmx_proc_ptran->dbuf.len) { if(_tmx_proc_ptran->dbuf.s) shm_free(_tmx_proc_ptran->dbuf.s); _tmx_proc_ptran->dbuf.s = (char*)shm_malloc(dsize); if(_tmx_proc_ptran->dbuf.s==NULL) { LM_ERR("not enough memory for pretran data\n"); return -1; } _tmx_proc_ptran->dbuf.len = dsize; } _tmx_proc_ptran->hid = chid; _tmx_proc_ptran->cseqmetid = (get_cseq(msg))->method_id; _tmx_proc_ptran->callid.s = _tmx_proc_ptran->dbuf.s; memcpy(_tmx_proc_ptran->callid.s, scallid.s, scallid.len); _tmx_proc_ptran->callid.len = scallid.len; _tmx_proc_ptran->callid.s[_tmx_proc_ptran->callid.len] = '\0'; _tmx_proc_ptran->ftag.s = _tmx_proc_ptran->callid.s + _tmx_proc_ptran->callid.len + 1; memcpy(_tmx_proc_ptran->ftag.s, sftag.s, sftag.len); _tmx_proc_ptran->ftag.len = sftag.len; _tmx_proc_ptran->ftag.s[_tmx_proc_ptran->ftag.len] = '\0'; _tmx_proc_ptran->cseqnum.s = _tmx_proc_ptran->ftag.s + _tmx_proc_ptran->ftag.len + 1; memcpy(_tmx_proc_ptran->cseqnum.s, scseqnum.s, scseqnum.len); _tmx_proc_ptran->cseqnum.len = scseqnum.len; _tmx_proc_ptran->cseqnum.s[_tmx_proc_ptran->cseqnum.len] = '\0'; _tmx_proc_ptran->cseqmet.s = _tmx_proc_ptran->cseqnum.s + _tmx_proc_ptran->cseqnum.len + 1; memcpy(_tmx_proc_ptran->cseqmet.s, scseqmet.s, scseqmet.len); _tmx_proc_ptran->cseqmet.len = scseqmet.len; _tmx_proc_ptran->cseqmet.s[_tmx_proc_ptran->cseqmet.len] = '\0'; if(likely(vbr!=NULL)) { _tmx_proc_ptran->vbranch.s = _tmx_proc_ptran->cseqmet.s + _tmx_proc_ptran->cseqmet.len + 1; memcpy(_tmx_proc_ptran->vbranch.s, svbranch.s, svbranch.len); _tmx_proc_ptran->vbranch.len = svbranch.len; _tmx_proc_ptran->vbranch.s[_tmx_proc_ptran->vbranch.len] = '\0'; } else { _tmx_proc_ptran->vbranch.s = NULL; _tmx_proc_ptran->vbranch.len = 0; } lock_get(&_tmx_ptran_table[slotid].lock); it = _tmx_ptran_table[slotid].plist; tmx_pretran_link_safe(slotid); for(; it!=NULL; it=it->next) { if(_tmx_proc_ptran->hid != it->hid || _tmx_proc_ptran->cseqmetid != it->cseqmetid || _tmx_proc_ptran->callid.len != it->callid.len || _tmx_proc_ptran->ftag.len != it->ftag.len || _tmx_proc_ptran->cseqmet.len != it->cseqmet.len || _tmx_proc_ptran->cseqnum.len != it->cseqnum.len) continue; if(_tmx_proc_ptran->vbranch.s != NULL && it->vbranch.s != NULL) { if(_tmx_proc_ptran->vbranch.len != it->vbranch.len) continue; /* shortcut - check last char in Via branch * - kamailio/ser adds there branch index => in case of paralel * forking by previous hop, catch it here quickly */ if(_tmx_proc_ptran->vbranch.s[it->vbranch.len-1] != it->vbranch.s[it->vbranch.len-1]) continue; if(memcmp(_tmx_proc_ptran->vbranch.s, it->vbranch.s, it->vbranch.len)!=0) continue; /* shall stop by matching magic cookie? * if (vbr && vbr->value.s && vbr->value.len > MCOOKIE_LEN * && memcmp(vbr->value.s, MCOOKIE, MCOOKIE_LEN)==0) { * LM_DBG("rfc3261 cookie found in Via branch\n"); * } */ } if(memcmp(_tmx_proc_ptran->callid.s, it->callid.s, it->callid.len)!=0 || memcmp(_tmx_proc_ptran->ftag.s, it->ftag.s, it->ftag.len)!=0 || memcmp(_tmx_proc_ptran->cseqnum.s, it->cseqnum.s, it->cseqnum.len)!=0) continue; if((it->cseqmetid==METHOD_OTHER || it->cseqmetid==METHOD_UNDEF) && memcmp(_tmx_proc_ptran->cseqmet.s, it->cseqmet.s, it->cseqmet.len)!=0) continue; LM_DBG("matched another pre-transaction by pid %d for [%.*s]\n", it->pid, it->callid.len, it->callid.s); lock_release(&_tmx_ptran_table[slotid].lock); return 1; } lock_release(&_tmx_ptran_table[slotid].lock); return 0; }
null
109
CWE-787
CVE-2018-8905
/* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ #include "tiffiop.h" #ifdef LZW_SUPPORT /* * TIFF Library. * Rev 5.0 Lempel-Ziv & Welch Compression Support * * This code is derived from the compress program whose code is * derived from software contributed to Berkeley by James A. Woods, * derived from original work by Spencer Thomas and Joseph Orost. * * The original Berkeley copyright notice appears below in its entirety. */ #include "tif_predict.h" #include <stdio.h> /* * NB: The 5.0 spec describes a different algorithm than Aldus * implements. Specifically, Aldus does code length transitions * one code earlier than should be done (for real LZW). * Earlier versions of this library implemented the correct * LZW algorithm, but emitted codes in a bit order opposite * to the TIFF spec. Thus, to maintain compatibility w/ Aldus * we interpret MSB-LSB ordered codes to be images written w/ * old versions of this library, but otherwise adhere to the * Aldus "off by one" algorithm. * * Future revisions to the TIFF spec are expected to "clarify this issue". */ #define LZW_COMPAT /* include backwards compatibility code */ /* * Each strip of data is supposed to be terminated by a CODE_EOI. * If the following #define is included, the decoder will also * check for end-of-strip w/o seeing this code. This makes the * library more robust, but also slower. */ #define LZW_CHECKEOS /* include checks for strips w/o EOI code */ #define MAXCODE(n) ((1L<<(n))-1) /* * The TIFF spec specifies that encoded bit * strings range from 9 to 12 bits. */ #define BITS_MIN 9 /* start with 9 bits */ #define BITS_MAX 12 /* max of 12 bit strings */ /* predefined codes */ #define CODE_CLEAR 256 /* code to clear string table */ #define CODE_EOI 257 /* end-of-information code */ #define CODE_FIRST 258 /* first free code entry */ #define CODE_MAX MAXCODE(BITS_MAX) #define HSIZE 9001L /* 91% occupancy */ #define HSHIFT (13-8) #ifdef LZW_COMPAT /* NB: +1024 is for compatibility with old files */ #define CSIZE (MAXCODE(BITS_MAX)+1024L) #else #define CSIZE (MAXCODE(BITS_MAX)+1L) #endif /* * State block for each open TIFF file using LZW * compression/decompression. Note that the predictor * state block must be first in this data structure. */ typedef struct { TIFFPredictorState predict; /* predictor super class */ unsigned short nbits; /* # of bits/code */ unsigned short maxcode; /* maximum code for lzw_nbits */ unsigned short free_ent; /* next free entry in hash table */ unsigned long nextdata; /* next bits of i/o */ long nextbits; /* # of valid bits in lzw_nextdata */ int rw_mode; /* preserve rw_mode from init */ } LZWBaseState; #define lzw_nbits base.nbits #define lzw_maxcode base.maxcode #define lzw_free_ent base.free_ent #define lzw_nextdata base.nextdata #define lzw_nextbits base.nextbits /* * Encoding-specific state. */ typedef uint16 hcode_t; /* codes fit in 16 bits */ typedef struct { long hash; hcode_t code; } hash_t; /* * Decoding-specific state. */ typedef struct code_ent { struct code_ent *next; unsigned short length; /* string len, including this token */ unsigned char value; /* data value */ unsigned char firstchar; /* first token of string */ } code_t; typedef int (*decodeFunc)(TIFF*, uint8*, tmsize_t, uint16); typedef struct { LZWBaseState base; /* Decoding specific data */ long dec_nbitsmask; /* lzw_nbits 1 bits, right adjusted */ long dec_restart; /* restart count */ #ifdef LZW_CHECKEOS uint64 dec_bitsleft; /* available bits in raw data */ #endif decodeFunc dec_decode; /* regular or backwards compatible */ code_t* dec_codep; /* current recognized code */ code_t* dec_oldcodep; /* previously recognized code */ code_t* dec_free_entp; /* next free entry */ code_t* dec_maxcodep; /* max available entry */ code_t* dec_codetab; /* kept separate for small machines */ /* Encoding specific data */ int enc_oldcode; /* last code encountered */ long enc_checkpoint; /* point at which to clear table */ #define CHECK_GAP 10000 /* enc_ratio check interval */ long enc_ratio; /* current compression ratio */ long enc_incount; /* (input) data bytes encoded */ long enc_outcount; /* encoded (output) bytes */ uint8* enc_rawlimit; /* bound on tif_rawdata buffer */ hash_t* enc_hashtab; /* kept separate for small machines */ } LZWCodecState; #define LZWState(tif) ((LZWBaseState*) (tif)->tif_data) #define DecoderState(tif) ((LZWCodecState*) LZWState(tif)) #define EncoderState(tif) ((LZWCodecState*) LZWState(tif)) static int LZWDecode(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s); #ifdef LZW_COMPAT static int LZWDecodeCompat(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s); #endif static void cl_hash(LZWCodecState*); /* * LZW Decoder. */ #ifdef LZW_CHECKEOS /* * This check shouldn't be necessary because each * strip is suppose to be terminated with CODE_EOI. */ #define NextCode(_tif, _sp, _bp, _code, _get) { \ if ((_sp)->dec_bitsleft < (uint64)nbits) { \ TIFFWarningExt(_tif->tif_clientdata, module, \ "LZWDecode: Strip %d not terminated with EOI code", \ _tif->tif_curstrip); \ _code = CODE_EOI; \ } else { \ _get(_sp,_bp,_code); \ (_sp)->dec_bitsleft -= nbits; \ } \ } #else #define NextCode(tif, sp, bp, code, get) get(sp, bp, code) #endif static int LZWFixupTags(TIFF* tif) { (void) tif; return (1); } static int LZWSetupDecode(TIFF* tif) { static const char module[] = "LZWSetupDecode"; LZWCodecState* sp = DecoderState(tif); int code; if( sp == NULL ) { /* * Allocate state block so tag methods have storage to record * values. */ tif->tif_data = (uint8*) _TIFFmalloc(sizeof(LZWCodecState)); if (tif->tif_data == NULL) { TIFFErrorExt(tif->tif_clientdata, module, "No space for LZW state block"); return (0); } DecoderState(tif)->dec_codetab = NULL; DecoderState(tif)->dec_decode = NULL; /* * Setup predictor setup. */ (void) TIFFPredictorInit(tif); sp = DecoderState(tif); } assert(sp != NULL); if (sp->dec_codetab == NULL) { sp->dec_codetab = (code_t*)_TIFFmalloc(CSIZE*sizeof (code_t)); if (sp->dec_codetab == NULL) { TIFFErrorExt(tif->tif_clientdata, module, "No space for LZW code table"); return (0); } /* * Pre-load the table. */ code = 255; do { sp->dec_codetab[code].value = (unsigned char)code; sp->dec_codetab[code].firstchar = (unsigned char)code; sp->dec_codetab[code].length = 1; sp->dec_codetab[code].next = NULL; } while (code--); /* * Zero-out the unused entries */ _TIFFmemset(&sp->dec_codetab[CODE_CLEAR], 0, (CODE_FIRST - CODE_CLEAR) * sizeof (code_t)); } return (1); } /* * Setup state for decoding a strip. */ static int LZWPreDecode(TIFF* tif, uint16 s) { static const char module[] = "LZWPreDecode"; LZWCodecState *sp = DecoderState(tif); (void) s; assert(sp != NULL); if( sp->dec_codetab == NULL ) { tif->tif_setupdecode( tif ); if( sp->dec_codetab == NULL ) return (0); } /* * Check for old bit-reversed codes. */ if (tif->tif_rawcc >= 2 && tif->tif_rawdata[0] == 0 && (tif->tif_rawdata[1] & 0x1)) { #ifdef LZW_COMPAT if (!sp->dec_decode) { TIFFWarningExt(tif->tif_clientdata, module, "Old-style LZW codes, convert file"); /* * Override default decoding methods with * ones that deal with the old coding. * Otherwise the predictor versions set * above will call the compatibility routines * through the dec_decode method. */ tif->tif_decoderow = LZWDecodeCompat; tif->tif_decodestrip = LZWDecodeCompat; tif->tif_decodetile = LZWDecodeCompat; /* * If doing horizontal differencing, must * re-setup the predictor logic since we * switched the basic decoder methods... */ (*tif->tif_setupdecode)(tif); sp->dec_decode = LZWDecodeCompat; } sp->lzw_maxcode = MAXCODE(BITS_MIN); #else /* !LZW_COMPAT */ if (!sp->dec_decode) { TIFFErrorExt(tif->tif_clientdata, module, "Old-style LZW codes not supported"); sp->dec_decode = LZWDecode; } return (0); #endif/* !LZW_COMPAT */ } else { sp->lzw_maxcode = MAXCODE(BITS_MIN)-1; sp->dec_decode = LZWDecode; } sp->lzw_nbits = BITS_MIN; sp->lzw_nextbits = 0; sp->lzw_nextdata = 0; sp->dec_restart = 0; sp->dec_nbitsmask = MAXCODE(BITS_MIN); #ifdef LZW_CHECKEOS sp->dec_bitsleft = 0; #endif sp->dec_free_entp = sp->dec_codetab + CODE_FIRST; /* * Zero entries that are not yet filled in. We do * this to guard against bogus input data that causes * us to index into undefined entries. If you can * come up with a way to safely bounds-check input codes * while decoding then you can remove this operation. */ _TIFFmemset(sp->dec_free_entp, 0, (CSIZE-CODE_FIRST)*sizeof (code_t)); sp->dec_oldcodep = &sp->dec_codetab[-1]; sp->dec_maxcodep = &sp->dec_codetab[sp->dec_nbitsmask-1]; return (1); } /* * Decode a "hunk of data". */ #define GetNextCode(sp, bp, code) { \ nextdata = (nextdata<<8) | *(bp)++; \ nextbits += 8; \ if (nextbits < nbits) { \ nextdata = (nextdata<<8) | *(bp)++; \ nextbits += 8; \ } \ code = (hcode_t)((nextdata >> (nextbits-nbits)) & nbitsmask); \ nextbits -= nbits; \ } static void codeLoop(TIFF* tif, const char* module) { TIFFErrorExt(tif->tif_clientdata, module, "Bogus encoding, loop in the code table; scanline %d", tif->tif_row); } static int LZWDecode(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s) { static const char module[] = "LZWDecode"; LZWCodecState *sp = DecoderState(tif); char *op = (char*) op0; long occ = (long) occ0; char *tp; unsigned char *bp; hcode_t code; int len; long nbits, nextbits, nbitsmask; unsigned long nextdata; code_t *codep, *free_entp, *maxcodep, *oldcodep; (void) s; assert(sp != NULL); assert(sp->dec_codetab != NULL); /* Fail if value does not fit in long. */ if ((tmsize_t) occ != occ0) return (0); /* * Restart interrupted output operation. */ if (sp->dec_restart) { long residue; codep = sp->dec_codep; residue = codep->length - sp->dec_restart; if (residue > occ) { /* * Residue from previous decode is sufficient * to satisfy decode request. Skip to the * start of the decoded string, place decoded * values in the output buffer, and return. */ sp->dec_restart += occ; do { codep = codep->next; } while (--residue > occ && codep); if (codep) { tp = op + occ; do { *--tp = codep->value; codep = codep->next; } while (--occ && codep); } return (1); } /* * Residue satisfies only part of the decode request. */ op += residue; occ -= residue; tp = op; do { int t; --tp; t = codep->value; codep = codep->next; *tp = (char)t; } while (--residue && codep); sp->dec_restart = 0; } bp = (unsigned char *)tif->tif_rawcp; #ifdef LZW_CHECKEOS sp->dec_bitsleft = (((uint64)tif->tif_rawcc) << 3); #endif nbits = sp->lzw_nbits; nextdata = sp->lzw_nextdata; nextbits = sp->lzw_nextbits; nbitsmask = sp->dec_nbitsmask; oldcodep = sp->dec_oldcodep; free_entp = sp->dec_free_entp; maxcodep = sp->dec_maxcodep; while (occ > 0) { NextCode(tif, sp, bp, code, GetNextCode); if (code == CODE_EOI) break; if (code == CODE_CLEAR) { do { free_entp = sp->dec_codetab + CODE_FIRST; _TIFFmemset(free_entp, 0, (CSIZE - CODE_FIRST) * sizeof (code_t)); nbits = BITS_MIN; nbitsmask = MAXCODE(BITS_MIN); maxcodep = sp->dec_codetab + nbitsmask-1; NextCode(tif, sp, bp, code, GetNextCode); } while (code == CODE_CLEAR); /* consecutive CODE_CLEAR codes */ if (code == CODE_EOI) break; if (code > CODE_CLEAR) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "LZWDecode: Corrupted LZW table at scanline %d", tif->tif_row); return (0); } *op++ = (char)code; occ--; oldcodep = sp->dec_codetab + code; continue; } codep = sp->dec_codetab + code; /* * Add the new entry to the code table. */ if (free_entp < &sp->dec_codetab[0] || free_entp >= &sp->dec_codetab[CSIZE]) { TIFFErrorExt(tif->tif_clientdata, module, "Corrupted LZW table at scanline %d", tif->tif_row); return (0); } free_entp->next = oldcodep; if (free_entp->next < &sp->dec_codetab[0] || free_entp->next >= &sp->dec_codetab[CSIZE]) { TIFFErrorExt(tif->tif_clientdata, module, "Corrupted LZW table at scanline %d", tif->tif_row); return (0); } free_entp->firstchar = free_entp->next->firstchar; free_entp->length = free_entp->next->length+1; free_entp->value = (codep < free_entp) ? codep->firstchar : free_entp->firstchar; if (++free_entp > maxcodep) { if (++nbits > BITS_MAX) /* should not happen */ nbits = BITS_MAX; nbitsmask = MAXCODE(nbits); maxcodep = sp->dec_codetab + nbitsmask-1; } oldcodep = codep; if (code >= 256) { /* * Code maps to a string, copy string * value to output (written in reverse). */ if(codep->length == 0) { TIFFErrorExt(tif->tif_clientdata, module, "Wrong length of decoded string: " "data probably corrupted at scanline %d", tif->tif_row); return (0); } if (codep->length > occ) { /* * String is too long for decode buffer, * locate portion that will fit, copy to * the decode buffer, and setup restart * logic for the next decoding call. */ sp->dec_codep = codep; do { codep = codep->next; } while (codep && codep->length > occ); if (codep) { sp->dec_restart = (long)occ; tp = op + occ; do { *--tp = codep->value; codep = codep->next; } while (--occ && codep); if (codep) codeLoop(tif, module); } break; } len = codep->length; tp = op + len; do { int t; --tp; t = codep->value; codep = codep->next; *tp = (char)t; } while (codep && tp > op); if (codep) { codeLoop(tif, module); break; } assert(occ >= len); op += len; occ -= len; } else { *op++ = (char)code; occ--; } } tif->tif_rawcc -= (tmsize_t)( (uint8*) bp - tif->tif_rawcp ); tif->tif_rawcp = (uint8*) bp; sp->lzw_nbits = (unsigned short) nbits; sp->lzw_nextdata = nextdata; sp->lzw_nextbits = nextbits; sp->dec_nbitsmask = nbitsmask; sp->dec_oldcodep = oldcodep; sp->dec_free_entp = free_entp; sp->dec_maxcodep = maxcodep; if (occ > 0) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Not enough data at scanline %d (short %I64d bytes)", tif->tif_row, (unsigned __int64) occ); #else TIFFErrorExt(tif->tif_clientdata, module, "Not enough data at scanline %d (short %llu bytes)", tif->tif_row, (unsigned long long) occ); #endif return (0); } return (1); } #ifdef LZW_COMPAT /* * Decode a "hunk of data" for old images. */ #define GetNextCodeCompat(sp, bp, code) { \ nextdata |= (unsigned long) *(bp)++ << nextbits; \ nextbits += 8; \ if (nextbits < nbits) { \ nextdata |= (unsigned long) *(bp)++ << nextbits;\ nextbits += 8; \ } \ code = (hcode_t)(nextdata & nbitsmask); \ nextdata >>= nbits; \ nextbits -= nbits; \ } static int LZWDecodeCompat(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s) { static const char module[] = "LZWDecodeCompat"; LZWCodecState *sp = DecoderState(tif); char *op = (char*) op0; long occ = (long) occ0; char *tp; unsigned char *bp; int code, nbits; long nextbits, nextdata, nbitsmask; code_t *codep, *free_entp, *maxcodep, *oldcodep; (void) s; assert(sp != NULL); /* Fail if value does not fit in long. */ if ((tmsize_t) occ != occ0) return (0); /* * Restart interrupted output operation. */ if (sp->dec_restart) { long residue; codep = sp->dec_codep; residue = codep->length - sp->dec_restart; if (residue > occ) { /* * Residue from previous decode is sufficient * to satisfy decode request. Skip to the * start of the decoded string, place decoded * values in the output buffer, and return. */ sp->dec_restart += occ; do { codep = codep->next; } while (--residue > occ); tp = op + occ; do { *--tp = codep->value; codep = codep->next; } while (--occ); return (1); } /* * Residue satisfies only part of the decode request. */ op += residue; occ -= residue; tp = op; do { *--tp = codep->value; codep = codep->next; } while (--residue); sp->dec_restart = 0; } bp = (unsigned char *)tif->tif_rawcp; #ifdef LZW_CHECKEOS sp->dec_bitsleft = (((uint64)tif->tif_rawcc) << 3); #endif nbits = sp->lzw_nbits; nextdata = sp->lzw_nextdata; nextbits = sp->lzw_nextbits; nbitsmask = sp->dec_nbitsmask; oldcodep = sp->dec_oldcodep; free_entp = sp->dec_free_entp; maxcodep = sp->dec_maxcodep; while (occ > 0) { NextCode(tif, sp, bp, code, GetNextCodeCompat); if (code == CODE_EOI) break; if (code == CODE_CLEAR) { do { free_entp = sp->dec_codetab + CODE_FIRST; _TIFFmemset(free_entp, 0, (CSIZE - CODE_FIRST) * sizeof (code_t)); nbits = BITS_MIN; nbitsmask = MAXCODE(BITS_MIN); maxcodep = sp->dec_codetab + nbitsmask; NextCode(tif, sp, bp, code, GetNextCodeCompat); } while (code == CODE_CLEAR); /* consecutive CODE_CLEAR codes */ if (code == CODE_EOI) break; if (code > CODE_CLEAR) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "LZWDecode: Corrupted LZW table at scanline %d", tif->tif_row); return (0); } *op++ = (char)code; occ--; oldcodep = sp->dec_codetab + code; continue; } codep = sp->dec_codetab + code; /* * Add the new entry to the code table. */ if (free_entp < &sp->dec_codetab[0] || free_entp >= &sp->dec_codetab[CSIZE]) { TIFFErrorExt(tif->tif_clientdata, module, "Corrupted LZW table at scanline %d", tif->tif_row); return (0); } free_entp->next = oldcodep; if (free_entp->next < &sp->dec_codetab[0] || free_entp->next >= &sp->dec_codetab[CSIZE]) { TIFFErrorExt(tif->tif_clientdata, module, "Corrupted LZW table at scanline %d", tif->tif_row); return (0); } free_entp->firstchar = free_entp->next->firstchar; free_entp->length = free_entp->next->length+1; free_entp->value = (codep < free_entp) ? codep->firstchar : free_entp->firstchar; if (++free_entp > maxcodep) { if (++nbits > BITS_MAX) /* should not happen */ nbits = BITS_MAX; nbitsmask = MAXCODE(nbits); maxcodep = sp->dec_codetab + nbitsmask; } oldcodep = codep; if (code >= 256) { /* * Code maps to a string, copy string * value to output (written in reverse). */ if(codep->length == 0) { TIFFErrorExt(tif->tif_clientdata, module, "Wrong length of decoded " "string: data probably corrupted at scanline %d", tif->tif_row); return (0); } if (codep->length > occ) { /* * String is too long for decode buffer, * locate portion that will fit, copy to * the decode buffer, and setup restart * logic for the next decoding call. */ sp->dec_codep = codep; do { codep = codep->next; } while (codep->length > occ); sp->dec_restart = occ; tp = op + occ; do { *--tp = codep->value; codep = codep->next; } while (--occ); break; } assert(occ >= codep->length); op += codep->length; occ -= codep->length; tp = op; do { *--tp = codep->value; } while( (codep = codep->next) != NULL ); } else { *op++ = (char)code; occ--; } } tif->tif_rawcc -= (tmsize_t)( (uint8*) bp - tif->tif_rawcp ); tif->tif_rawcp = (uint8*) bp; sp->lzw_nbits = (unsigned short)nbits; sp->lzw_nextdata = nextdata; sp->lzw_nextbits = nextbits; sp->dec_nbitsmask = nbitsmask; sp->dec_oldcodep = oldcodep; sp->dec_free_entp = free_entp; sp->dec_maxcodep = maxcodep; if (occ > 0) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Not enough data at scanline %d (short %I64d bytes)", tif->tif_row, (unsigned __int64) occ); #else TIFFErrorExt(tif->tif_clientdata, module, "Not enough data at scanline %d (short %llu bytes)", tif->tif_row, (unsigned long long) occ); #endif return (0); } return (1); } #endif /* LZW_COMPAT */ /* * LZW Encoding. */ static int LZWSetupEncode(TIFF* tif) { static const char module[] = "LZWSetupEncode"; LZWCodecState* sp = EncoderState(tif); assert(sp != NULL); sp->enc_hashtab = (hash_t*) _TIFFmalloc(HSIZE*sizeof (hash_t)); if (sp->enc_hashtab == NULL) { TIFFErrorExt(tif->tif_clientdata, module, "No space for LZW hash table"); return (0); } return (1); } /* * Reset encoding state at the start of a strip. */ static int LZWPreEncode(TIFF* tif, uint16 s) { LZWCodecState *sp = EncoderState(tif); (void) s; assert(sp != NULL); if( sp->enc_hashtab == NULL ) { tif->tif_setupencode( tif ); } sp->lzw_nbits = BITS_MIN; sp->lzw_maxcode = MAXCODE(BITS_MIN); sp->lzw_free_ent = CODE_FIRST; sp->lzw_nextbits = 0; sp->lzw_nextdata = 0; sp->enc_checkpoint = CHECK_GAP; sp->enc_ratio = 0; sp->enc_incount = 0; sp->enc_outcount = 0; /* * The 4 here insures there is space for 2 max-sized * codes in LZWEncode and LZWPostDecode. */ sp->enc_rawlimit = tif->tif_rawdata + tif->tif_rawdatasize-1 - 4; cl_hash(sp); /* clear hash table */ sp->enc_oldcode = (hcode_t) -1; /* generates CODE_CLEAR in LZWEncode */ return (1); } #define CALCRATIO(sp, rat) { \ if (incount > 0x007fffff) { /* NB: shift will overflow */\ rat = outcount >> 8; \ rat = (rat == 0 ? 0x7fffffff : incount/rat); \ } else \ rat = (incount<<8) / outcount; \ } /* Explicit 0xff masking to make icc -check=conversions happy */ #define PutNextCode(op, c) { \ nextdata = (nextdata << nbits) | c; \ nextbits += nbits; \ *op++ = (unsigned char)((nextdata >> (nextbits-8))&0xff); \ nextbits -= 8; \ if (nextbits >= 8) { \ *op++ = (unsigned char)((nextdata >> (nextbits-8))&0xff); \ nextbits -= 8; \ } \ outcount += nbits; \ } /* * Encode a chunk of pixels. * * Uses an open addressing double hashing (no chaining) on the * prefix code/next character combination. We do a variant of * Knuth's algorithm D (vol. 3, sec. 6.4) along with G. Knott's * relatively-prime secondary probe. Here, the modular division * first probe is gives way to a faster exclusive-or manipulation. * Also do block compression with an adaptive reset, whereby the * code table is cleared when the compression ratio decreases, * but after the table fills. The variable-length output codes * are re-sized at this point, and a CODE_CLEAR is generated * for the decoder. */ static int LZWEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s) { register LZWCodecState *sp = EncoderState(tif); register long fcode; register hash_t *hp; register int h, c; hcode_t ent; long disp; long incount, outcount, checkpoint; unsigned long nextdata; long nextbits; int free_ent, maxcode, nbits; uint8* op; uint8* limit; (void) s; if (sp == NULL) return (0); assert(sp->enc_hashtab != NULL); /* * Load local state. */ incount = sp->enc_incount; outcount = sp->enc_outcount; checkpoint = sp->enc_checkpoint; nextdata = sp->lzw_nextdata; nextbits = sp->lzw_nextbits; free_ent = sp->lzw_free_ent; maxcode = sp->lzw_maxcode; nbits = sp->lzw_nbits; op = tif->tif_rawcp; limit = sp->enc_rawlimit; ent = (hcode_t)sp->enc_oldcode; if (ent == (hcode_t) -1 && cc > 0) { /* * NB: This is safe because it can only happen * at the start of a strip where we know there * is space in the data buffer. */ PutNextCode(op, CODE_CLEAR); ent = *bp++; cc--; incount++; } while (cc > 0) { c = *bp++; cc--; incount++; fcode = ((long)c << BITS_MAX) + ent; h = (c << HSHIFT) ^ ent; /* xor hashing */ #ifdef _WINDOWS /* * Check hash index for an overflow. */ if (h >= HSIZE) h -= HSIZE; #endif hp = &sp->enc_hashtab[h]; if (hp->hash == fcode) { ent = hp->code; continue; } if (hp->hash >= 0) { /* * Primary hash failed, check secondary hash. */ disp = HSIZE - h; if (h == 0) disp = 1; do { /* * Avoid pointer arithmetic because of * wraparound problems with segments. */ if ((h -= disp) < 0) h += HSIZE; hp = &sp->enc_hashtab[h]; if (hp->hash == fcode) { ent = hp->code; goto hit; } } while (hp->hash >= 0); } /* * New entry, emit code and add to table. */ /* * Verify there is space in the buffer for the code * and any potential Clear code that might be emitted * below. The value of limit is setup so that there * are at least 4 bytes free--room for 2 codes. */ if (op > limit) { tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata); if( !TIFFFlushData1(tif) ) return 0; op = tif->tif_rawdata; } PutNextCode(op, ent); ent = (hcode_t)c; hp->code = (hcode_t)(free_ent++); hp->hash = fcode; if (free_ent == CODE_MAX-1) { /* table is full, emit clear code and reset */ cl_hash(sp); sp->enc_ratio = 0; incount = 0; outcount = 0; free_ent = CODE_FIRST; PutNextCode(op, CODE_CLEAR); nbits = BITS_MIN; maxcode = MAXCODE(BITS_MIN); } else { /* * If the next entry is going to be too big for * the code size, then increase it, if possible. */ if (free_ent > maxcode) { nbits++; assert(nbits <= BITS_MAX); maxcode = (int) MAXCODE(nbits); } else if (incount >= checkpoint) { long rat; /* * Check compression ratio and, if things seem * to be slipping, clear the hash table and * reset state. The compression ratio is a * 24+8-bit fractional number. */ checkpoint = incount+CHECK_GAP; CALCRATIO(sp, rat); if (rat <= sp->enc_ratio) { cl_hash(sp); sp->enc_ratio = 0; incount = 0; outcount = 0; free_ent = CODE_FIRST; PutNextCode(op, CODE_CLEAR); nbits = BITS_MIN; maxcode = MAXCODE(BITS_MIN); } else sp->enc_ratio = rat; } } hit: ; } /* * Restore global state. */ sp->enc_incount = incount; sp->enc_outcount = outcount; sp->enc_checkpoint = checkpoint; sp->enc_oldcode = ent; sp->lzw_nextdata = nextdata; sp->lzw_nextbits = nextbits; sp->lzw_free_ent = (unsigned short)free_ent; sp->lzw_maxcode = (unsigned short)maxcode; sp->lzw_nbits = (unsigned short)nbits; tif->tif_rawcp = op; return (1); } /* * Finish off an encoded strip by flushing the last * string and tacking on an End Of Information code. */ static int LZWPostEncode(TIFF* tif) { register LZWCodecState *sp = EncoderState(tif); uint8* op = tif->tif_rawcp; long nextbits = sp->lzw_nextbits; unsigned long nextdata = sp->lzw_nextdata; long outcount = sp->enc_outcount; int nbits = sp->lzw_nbits; if (op > sp->enc_rawlimit) { tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata); if( !TIFFFlushData1(tif) ) return 0; op = tif->tif_rawdata; } if (sp->enc_oldcode != (hcode_t) -1) { int free_ent = sp->lzw_free_ent; PutNextCode(op, sp->enc_oldcode); sp->enc_oldcode = (hcode_t) -1; free_ent ++; if (free_ent == CODE_MAX-1) { /* table is full, emit clear code and reset */ outcount = 0; PutNextCode(op, CODE_CLEAR); nbits = BITS_MIN; } else { /* * If the next entry is going to be too big for * the code size, then increase it, if possible. */ if (free_ent > sp->lzw_maxcode) { nbits++; assert(nbits <= BITS_MAX); } } } PutNextCode(op, CODE_EOI); /* Explicit 0xff masking to make icc -check=conversions happy */ if (nextbits > 0) *op++ = (unsigned char)((nextdata << (8-nextbits))&0xff); tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata); return (1); } /* * Reset encoding hash table. */ static void cl_hash(LZWCodecState* sp) { register hash_t *hp = &sp->enc_hashtab[HSIZE-1]; register long i = HSIZE-8; do { i -= 8; hp[-7].hash = -1; hp[-6].hash = -1; hp[-5].hash = -1; hp[-4].hash = -1; hp[-3].hash = -1; hp[-2].hash = -1; hp[-1].hash = -1; hp[ 0].hash = -1; hp -= 8; } while (i >= 0); for (i += 8; i > 0; i--, hp--) hp->hash = -1; } static void LZWCleanup(TIFF* tif) { (void)TIFFPredictorCleanup(tif); assert(tif->tif_data != 0); if (DecoderState(tif)->dec_codetab) _TIFFfree(DecoderState(tif)->dec_codetab); if (EncoderState(tif)->enc_hashtab) _TIFFfree(EncoderState(tif)->enc_hashtab); _TIFFfree(tif->tif_data); tif->tif_data = NULL; _TIFFSetDefaultCompressionState(tif); } int TIFFInitLZW(TIFF* tif, int scheme) { static const char module[] = "TIFFInitLZW"; assert(scheme == COMPRESSION_LZW); /* * Allocate state block so tag methods have storage to record values. */ tif->tif_data = (uint8*) _TIFFmalloc(sizeof (LZWCodecState)); if (tif->tif_data == NULL) goto bad; DecoderState(tif)->dec_codetab = NULL; DecoderState(tif)->dec_decode = NULL; EncoderState(tif)->enc_hashtab = NULL; LZWState(tif)->rw_mode = tif->tif_mode; /* * Install codec methods. */ tif->tif_fixuptags = LZWFixupTags; tif->tif_setupdecode = LZWSetupDecode; tif->tif_predecode = LZWPreDecode; tif->tif_decoderow = LZWDecode; tif->tif_decodestrip = LZWDecode; tif->tif_decodetile = LZWDecode; tif->tif_setupencode = LZWSetupEncode; tif->tif_preencode = LZWPreEncode; tif->tif_postencode = LZWPostEncode; tif->tif_encoderow = LZWEncode; tif->tif_encodestrip = LZWEncode; tif->tif_encodetile = LZWEncode; tif->tif_cleanup = LZWCleanup; /* * Setup predictor setup. */ (void) TIFFPredictorInit(tif); return (1); bad: TIFFErrorExt(tif->tif_clientdata, module, "No space for LZW state block"); return (0); } /* * Copyright (c) 1985, 1986 The Regents of the University of California. * All rights reserved. * * This code is derived from software contributed to Berkeley by * James A. Woods, derived from original work by Spencer Thomas * and Joseph Orost. * * Redistribution and use in source and binary forms are permitted * provided that the above copyright notice and this paragraph are * duplicated in all such forms and that any documentation, * advertising materials, and other materials related to such * distribution and use acknowledge that the software was developed * by the University of California, Berkeley. The name of the * University may not be used to endorse or promote products derived * from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #endif /* LZW_SUPPORT */ /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
null
/* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ #include "tiffiop.h" #ifdef LZW_SUPPORT /* * TIFF Library. * Rev 5.0 Lempel-Ziv & Welch Compression Support * * This code is derived from the compress program whose code is * derived from software contributed to Berkeley by James A. Woods, * derived from original work by Spencer Thomas and Joseph Orost. * * The original Berkeley copyright notice appears below in its entirety. */ #include "tif_predict.h" #include <stdio.h> /* * NB: The 5.0 spec describes a different algorithm than Aldus * implements. Specifically, Aldus does code length transitions * one code earlier than should be done (for real LZW). * Earlier versions of this library implemented the correct * LZW algorithm, but emitted codes in a bit order opposite * to the TIFF spec. Thus, to maintain compatibility w/ Aldus * we interpret MSB-LSB ordered codes to be images written w/ * old versions of this library, but otherwise adhere to the * Aldus "off by one" algorithm. * * Future revisions to the TIFF spec are expected to "clarify this issue". */ #define LZW_COMPAT /* include backwards compatibility code */ /* * Each strip of data is supposed to be terminated by a CODE_EOI. * If the following #define is included, the decoder will also * check for end-of-strip w/o seeing this code. This makes the * library more robust, but also slower. */ #define LZW_CHECKEOS /* include checks for strips w/o EOI code */ #define MAXCODE(n) ((1L<<(n))-1) /* * The TIFF spec specifies that encoded bit * strings range from 9 to 12 bits. */ #define BITS_MIN 9 /* start with 9 bits */ #define BITS_MAX 12 /* max of 12 bit strings */ /* predefined codes */ #define CODE_CLEAR 256 /* code to clear string table */ #define CODE_EOI 257 /* end-of-information code */ #define CODE_FIRST 258 /* first free code entry */ #define CODE_MAX MAXCODE(BITS_MAX) #define HSIZE 9001L /* 91% occupancy */ #define HSHIFT (13-8) #ifdef LZW_COMPAT /* NB: +1024 is for compatibility with old files */ #define CSIZE (MAXCODE(BITS_MAX)+1024L) #else #define CSIZE (MAXCODE(BITS_MAX)+1L) #endif /* * State block for each open TIFF file using LZW * compression/decompression. Note that the predictor * state block must be first in this data structure. */ typedef struct { TIFFPredictorState predict; /* predictor super class */ unsigned short nbits; /* # of bits/code */ unsigned short maxcode; /* maximum code for lzw_nbits */ unsigned short free_ent; /* next free entry in hash table */ unsigned long nextdata; /* next bits of i/o */ long nextbits; /* # of valid bits in lzw_nextdata */ int rw_mode; /* preserve rw_mode from init */ } LZWBaseState; #define lzw_nbits base.nbits #define lzw_maxcode base.maxcode #define lzw_free_ent base.free_ent #define lzw_nextdata base.nextdata #define lzw_nextbits base.nextbits /* * Encoding-specific state. */ typedef uint16 hcode_t; /* codes fit in 16 bits */ typedef struct { long hash; hcode_t code; } hash_t; /* * Decoding-specific state. */ typedef struct code_ent { struct code_ent *next; unsigned short length; /* string len, including this token */ unsigned char value; /* data value */ unsigned char firstchar; /* first token of string */ } code_t; typedef int (*decodeFunc)(TIFF*, uint8*, tmsize_t, uint16); typedef struct { LZWBaseState base; /* Decoding specific data */ long dec_nbitsmask; /* lzw_nbits 1 bits, right adjusted */ long dec_restart; /* restart count */ #ifdef LZW_CHECKEOS uint64 dec_bitsleft; /* available bits in raw data */ #endif decodeFunc dec_decode; /* regular or backwards compatible */ code_t* dec_codep; /* current recognized code */ code_t* dec_oldcodep; /* previously recognized code */ code_t* dec_free_entp; /* next free entry */ code_t* dec_maxcodep; /* max available entry */ code_t* dec_codetab; /* kept separate for small machines */ /* Encoding specific data */ int enc_oldcode; /* last code encountered */ long enc_checkpoint; /* point at which to clear table */ #define CHECK_GAP 10000 /* enc_ratio check interval */ long enc_ratio; /* current compression ratio */ long enc_incount; /* (input) data bytes encoded */ long enc_outcount; /* encoded (output) bytes */ uint8* enc_rawlimit; /* bound on tif_rawdata buffer */ hash_t* enc_hashtab; /* kept separate for small machines */ } LZWCodecState; #define LZWState(tif) ((LZWBaseState*) (tif)->tif_data) #define DecoderState(tif) ((LZWCodecState*) LZWState(tif)) #define EncoderState(tif) ((LZWCodecState*) LZWState(tif)) static int LZWDecode(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s); #ifdef LZW_COMPAT static int LZWDecodeCompat(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s); #endif static void cl_hash(LZWCodecState*); /* * LZW Decoder. */ #ifdef LZW_CHECKEOS /* * This check shouldn't be necessary because each * strip is suppose to be terminated with CODE_EOI. */ #define NextCode(_tif, _sp, _bp, _code, _get) { \ if ((_sp)->dec_bitsleft < (uint64)nbits) { \ TIFFWarningExt(_tif->tif_clientdata, module, \ "LZWDecode: Strip %d not terminated with EOI code", \ _tif->tif_curstrip); \ _code = CODE_EOI; \ } else { \ _get(_sp,_bp,_code); \ (_sp)->dec_bitsleft -= nbits; \ } \ } #else #define NextCode(tif, sp, bp, code, get) get(sp, bp, code) #endif static int LZWFixupTags(TIFF* tif) { (void) tif; return (1); } static int LZWSetupDecode(TIFF* tif) { static const char module[] = "LZWSetupDecode"; LZWCodecState* sp = DecoderState(tif); int code; if( sp == NULL ) { /* * Allocate state block so tag methods have storage to record * values. */ tif->tif_data = (uint8*) _TIFFmalloc(sizeof(LZWCodecState)); if (tif->tif_data == NULL) { TIFFErrorExt(tif->tif_clientdata, module, "No space for LZW state block"); return (0); } DecoderState(tif)->dec_codetab = NULL; DecoderState(tif)->dec_decode = NULL; /* * Setup predictor setup. */ (void) TIFFPredictorInit(tif); sp = DecoderState(tif); } assert(sp != NULL); if (sp->dec_codetab == NULL) { sp->dec_codetab = (code_t*)_TIFFmalloc(CSIZE*sizeof (code_t)); if (sp->dec_codetab == NULL) { TIFFErrorExt(tif->tif_clientdata, module, "No space for LZW code table"); return (0); } /* * Pre-load the table. */ code = 255; do { sp->dec_codetab[code].value = (unsigned char)code; sp->dec_codetab[code].firstchar = (unsigned char)code; sp->dec_codetab[code].length = 1; sp->dec_codetab[code].next = NULL; } while (code--); /* * Zero-out the unused entries */ _TIFFmemset(&sp->dec_codetab[CODE_CLEAR], 0, (CODE_FIRST - CODE_CLEAR) * sizeof (code_t)); } return (1); } /* * Setup state for decoding a strip. */ static int LZWPreDecode(TIFF* tif, uint16 s) { static const char module[] = "LZWPreDecode"; LZWCodecState *sp = DecoderState(tif); (void) s; assert(sp != NULL); if( sp->dec_codetab == NULL ) { tif->tif_setupdecode( tif ); if( sp->dec_codetab == NULL ) return (0); } /* * Check for old bit-reversed codes. */ if (tif->tif_rawcc >= 2 && tif->tif_rawdata[0] == 0 && (tif->tif_rawdata[1] & 0x1)) { #ifdef LZW_COMPAT if (!sp->dec_decode) { TIFFWarningExt(tif->tif_clientdata, module, "Old-style LZW codes, convert file"); /* * Override default decoding methods with * ones that deal with the old coding. * Otherwise the predictor versions set * above will call the compatibility routines * through the dec_decode method. */ tif->tif_decoderow = LZWDecodeCompat; tif->tif_decodestrip = LZWDecodeCompat; tif->tif_decodetile = LZWDecodeCompat; /* * If doing horizontal differencing, must * re-setup the predictor logic since we * switched the basic decoder methods... */ (*tif->tif_setupdecode)(tif); sp->dec_decode = LZWDecodeCompat; } sp->lzw_maxcode = MAXCODE(BITS_MIN); #else /* !LZW_COMPAT */ if (!sp->dec_decode) { TIFFErrorExt(tif->tif_clientdata, module, "Old-style LZW codes not supported"); sp->dec_decode = LZWDecode; } return (0); #endif/* !LZW_COMPAT */ } else { sp->lzw_maxcode = MAXCODE(BITS_MIN)-1; sp->dec_decode = LZWDecode; } sp->lzw_nbits = BITS_MIN; sp->lzw_nextbits = 0; sp->lzw_nextdata = 0; sp->dec_restart = 0; sp->dec_nbitsmask = MAXCODE(BITS_MIN); #ifdef LZW_CHECKEOS sp->dec_bitsleft = 0; #endif sp->dec_free_entp = sp->dec_codetab + CODE_FIRST; /* * Zero entries that are not yet filled in. We do * this to guard against bogus input data that causes * us to index into undefined entries. If you can * come up with a way to safely bounds-check input codes * while decoding then you can remove this operation. */ _TIFFmemset(sp->dec_free_entp, 0, (CSIZE-CODE_FIRST)*sizeof (code_t)); sp->dec_oldcodep = &sp->dec_codetab[-1]; sp->dec_maxcodep = &sp->dec_codetab[sp->dec_nbitsmask-1]; return (1); } /* * Decode a "hunk of data". */ #define GetNextCode(sp, bp, code) { \ nextdata = (nextdata<<8) | *(bp)++; \ nextbits += 8; \ if (nextbits < nbits) { \ nextdata = (nextdata<<8) | *(bp)++; \ nextbits += 8; \ } \ code = (hcode_t)((nextdata >> (nextbits-nbits)) & nbitsmask); \ nextbits -= nbits; \ } static void codeLoop(TIFF* tif, const char* module) { TIFFErrorExt(tif->tif_clientdata, module, "Bogus encoding, loop in the code table; scanline %d", tif->tif_row); } static int LZWDecode(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s) { static const char module[] = "LZWDecode"; LZWCodecState *sp = DecoderState(tif); char *op = (char*) op0; long occ = (long) occ0; char *tp; unsigned char *bp; hcode_t code; int len; long nbits, nextbits, nbitsmask; unsigned long nextdata; code_t *codep, *free_entp, *maxcodep, *oldcodep; (void) s; assert(sp != NULL); assert(sp->dec_codetab != NULL); /* Fail if value does not fit in long. */ if ((tmsize_t) occ != occ0) return (0); /* * Restart interrupted output operation. */ if (sp->dec_restart) { long residue; codep = sp->dec_codep; residue = codep->length - sp->dec_restart; if (residue > occ) { /* * Residue from previous decode is sufficient * to satisfy decode request. Skip to the * start of the decoded string, place decoded * values in the output buffer, and return. */ sp->dec_restart += occ; do { codep = codep->next; } while (--residue > occ && codep); if (codep) { tp = op + occ; do { *--tp = codep->value; codep = codep->next; } while (--occ && codep); } return (1); } /* * Residue satisfies only part of the decode request. */ op += residue; occ -= residue; tp = op; do { int t; --tp; t = codep->value; codep = codep->next; *tp = (char)t; } while (--residue && codep); sp->dec_restart = 0; } bp = (unsigned char *)tif->tif_rawcp; #ifdef LZW_CHECKEOS sp->dec_bitsleft = (((uint64)tif->tif_rawcc) << 3); #endif nbits = sp->lzw_nbits; nextdata = sp->lzw_nextdata; nextbits = sp->lzw_nextbits; nbitsmask = sp->dec_nbitsmask; oldcodep = sp->dec_oldcodep; free_entp = sp->dec_free_entp; maxcodep = sp->dec_maxcodep; while (occ > 0) { NextCode(tif, sp, bp, code, GetNextCode); if (code == CODE_EOI) break; if (code == CODE_CLEAR) { do { free_entp = sp->dec_codetab + CODE_FIRST; _TIFFmemset(free_entp, 0, (CSIZE - CODE_FIRST) * sizeof (code_t)); nbits = BITS_MIN; nbitsmask = MAXCODE(BITS_MIN); maxcodep = sp->dec_codetab + nbitsmask-1; NextCode(tif, sp, bp, code, GetNextCode); } while (code == CODE_CLEAR); /* consecutive CODE_CLEAR codes */ if (code == CODE_EOI) break; if (code > CODE_CLEAR) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "LZWDecode: Corrupted LZW table at scanline %d", tif->tif_row); return (0); } *op++ = (char)code; occ--; oldcodep = sp->dec_codetab + code; continue; } codep = sp->dec_codetab + code; /* * Add the new entry to the code table. */ if (free_entp < &sp->dec_codetab[0] || free_entp >= &sp->dec_codetab[CSIZE]) { TIFFErrorExt(tif->tif_clientdata, module, "Corrupted LZW table at scanline %d", tif->tif_row); return (0); } free_entp->next = oldcodep; if (free_entp->next < &sp->dec_codetab[0] || free_entp->next >= &sp->dec_codetab[CSIZE]) { TIFFErrorExt(tif->tif_clientdata, module, "Corrupted LZW table at scanline %d", tif->tif_row); return (0); } free_entp->firstchar = free_entp->next->firstchar; free_entp->length = free_entp->next->length+1; free_entp->value = (codep < free_entp) ? codep->firstchar : free_entp->firstchar; if (++free_entp > maxcodep) { if (++nbits > BITS_MAX) /* should not happen */ nbits = BITS_MAX; nbitsmask = MAXCODE(nbits); maxcodep = sp->dec_codetab + nbitsmask-1; } oldcodep = codep; if (code >= 256) { /* * Code maps to a string, copy string * value to output (written in reverse). */ if(codep->length == 0) { TIFFErrorExt(tif->tif_clientdata, module, "Wrong length of decoded string: " "data probably corrupted at scanline %d", tif->tif_row); return (0); } if (codep->length > occ) { /* * String is too long for decode buffer, * locate portion that will fit, copy to * the decode buffer, and setup restart * logic for the next decoding call. */ sp->dec_codep = codep; do { codep = codep->next; } while (codep && codep->length > occ); if (codep) { sp->dec_restart = (long)occ; tp = op + occ; do { *--tp = codep->value; codep = codep->next; } while (--occ && codep); if (codep) codeLoop(tif, module); } break; } len = codep->length; tp = op + len; do { int t; --tp; t = codep->value; codep = codep->next; *tp = (char)t; } while (codep && tp > op); if (codep) { codeLoop(tif, module); break; } assert(occ >= len); op += len; occ -= len; } else { *op++ = (char)code; occ--; } } tif->tif_rawcc -= (tmsize_t)( (uint8*) bp - tif->tif_rawcp ); tif->tif_rawcp = (uint8*) bp; sp->lzw_nbits = (unsigned short) nbits; sp->lzw_nextdata = nextdata; sp->lzw_nextbits = nextbits; sp->dec_nbitsmask = nbitsmask; sp->dec_oldcodep = oldcodep; sp->dec_free_entp = free_entp; sp->dec_maxcodep = maxcodep; if (occ > 0) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Not enough data at scanline %d (short %I64d bytes)", tif->tif_row, (unsigned __int64) occ); #else TIFFErrorExt(tif->tif_clientdata, module, "Not enough data at scanline %d (short %llu bytes)", tif->tif_row, (unsigned long long) occ); #endif return (0); } return (1); } #ifdef LZW_COMPAT /* * Decode a "hunk of data" for old images. */ #define GetNextCodeCompat(sp, bp, code) { \ nextdata |= (unsigned long) *(bp)++ << nextbits; \ nextbits += 8; \ if (nextbits < nbits) { \ nextdata |= (unsigned long) *(bp)++ << nextbits;\ nextbits += 8; \ } \ code = (hcode_t)(nextdata & nbitsmask); \ nextdata >>= nbits; \ nextbits -= nbits; \ } static int LZWDecodeCompat(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s) { static const char module[] = "LZWDecodeCompat"; LZWCodecState *sp = DecoderState(tif); char *op = (char*) op0; long occ = (long) occ0; char *tp; unsigned char *bp; int code, nbits; int len; long nextbits, nextdata, nbitsmask; code_t *codep, *free_entp, *maxcodep, *oldcodep; (void) s; assert(sp != NULL); /* Fail if value does not fit in long. */ if ((tmsize_t) occ != occ0) return (0); /* * Restart interrupted output operation. */ if (sp->dec_restart) { long residue; codep = sp->dec_codep; residue = codep->length - sp->dec_restart; if (residue > occ) { /* * Residue from previous decode is sufficient * to satisfy decode request. Skip to the * start of the decoded string, place decoded * values in the output buffer, and return. */ sp->dec_restart += occ; do { codep = codep->next; } while (--residue > occ); tp = op + occ; do { *--tp = codep->value; codep = codep->next; } while (--occ); return (1); } /* * Residue satisfies only part of the decode request. */ op += residue; occ -= residue; tp = op; do { *--tp = codep->value; codep = codep->next; } while (--residue); sp->dec_restart = 0; } bp = (unsigned char *)tif->tif_rawcp; #ifdef LZW_CHECKEOS sp->dec_bitsleft = (((uint64)tif->tif_rawcc) << 3); #endif nbits = sp->lzw_nbits; nextdata = sp->lzw_nextdata; nextbits = sp->lzw_nextbits; nbitsmask = sp->dec_nbitsmask; oldcodep = sp->dec_oldcodep; free_entp = sp->dec_free_entp; maxcodep = sp->dec_maxcodep; while (occ > 0) { NextCode(tif, sp, bp, code, GetNextCodeCompat); if (code == CODE_EOI) break; if (code == CODE_CLEAR) { do { free_entp = sp->dec_codetab + CODE_FIRST; _TIFFmemset(free_entp, 0, (CSIZE - CODE_FIRST) * sizeof (code_t)); nbits = BITS_MIN; nbitsmask = MAXCODE(BITS_MIN); maxcodep = sp->dec_codetab + nbitsmask; NextCode(tif, sp, bp, code, GetNextCodeCompat); } while (code == CODE_CLEAR); /* consecutive CODE_CLEAR codes */ if (code == CODE_EOI) break; if (code > CODE_CLEAR) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "LZWDecode: Corrupted LZW table at scanline %d", tif->tif_row); return (0); } *op++ = (char)code; occ--; oldcodep = sp->dec_codetab + code; continue; } codep = sp->dec_codetab + code; /* * Add the new entry to the code table. */ if (free_entp < &sp->dec_codetab[0] || free_entp >= &sp->dec_codetab[CSIZE]) { TIFFErrorExt(tif->tif_clientdata, module, "Corrupted LZW table at scanline %d", tif->tif_row); return (0); } free_entp->next = oldcodep; if (free_entp->next < &sp->dec_codetab[0] || free_entp->next >= &sp->dec_codetab[CSIZE]) { TIFFErrorExt(tif->tif_clientdata, module, "Corrupted LZW table at scanline %d", tif->tif_row); return (0); } free_entp->firstchar = free_entp->next->firstchar; free_entp->length = free_entp->next->length+1; free_entp->value = (codep < free_entp) ? codep->firstchar : free_entp->firstchar; if (++free_entp > maxcodep) { if (++nbits > BITS_MAX) /* should not happen */ nbits = BITS_MAX; nbitsmask = MAXCODE(nbits); maxcodep = sp->dec_codetab + nbitsmask; } oldcodep = codep; if (code >= 256) { /* * Code maps to a string, copy string * value to output (written in reverse). */ if(codep->length == 0) { TIFFErrorExt(tif->tif_clientdata, module, "Wrong length of decoded " "string: data probably corrupted at scanline %d", tif->tif_row); return (0); } if (codep->length > occ) { /* * String is too long for decode buffer, * locate portion that will fit, copy to * the decode buffer, and setup restart * logic for the next decoding call. */ sp->dec_codep = codep; do { codep = codep->next; } while (codep->length > occ); sp->dec_restart = occ; tp = op + occ; do { *--tp = codep->value; codep = codep->next; } while (--occ); break; } len = codep->length; tp = op + len; do { int t; --tp; t = codep->value; codep = codep->next; *tp = (char)t; } while (codep && tp > op); assert(occ >= len); op += len; occ -= len; } else { *op++ = (char)code; occ--; } } tif->tif_rawcc -= (tmsize_t)( (uint8*) bp - tif->tif_rawcp ); tif->tif_rawcp = (uint8*) bp; sp->lzw_nbits = (unsigned short)nbits; sp->lzw_nextdata = nextdata; sp->lzw_nextbits = nextbits; sp->dec_nbitsmask = nbitsmask; sp->dec_oldcodep = oldcodep; sp->dec_free_entp = free_entp; sp->dec_maxcodep = maxcodep; if (occ > 0) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Not enough data at scanline %d (short %I64d bytes)", tif->tif_row, (unsigned __int64) occ); #else TIFFErrorExt(tif->tif_clientdata, module, "Not enough data at scanline %d (short %llu bytes)", tif->tif_row, (unsigned long long) occ); #endif return (0); } return (1); } #endif /* LZW_COMPAT */ /* * LZW Encoding. */ static int LZWSetupEncode(TIFF* tif) { static const char module[] = "LZWSetupEncode"; LZWCodecState* sp = EncoderState(tif); assert(sp != NULL); sp->enc_hashtab = (hash_t*) _TIFFmalloc(HSIZE*sizeof (hash_t)); if (sp->enc_hashtab == NULL) { TIFFErrorExt(tif->tif_clientdata, module, "No space for LZW hash table"); return (0); } return (1); } /* * Reset encoding state at the start of a strip. */ static int LZWPreEncode(TIFF* tif, uint16 s) { LZWCodecState *sp = EncoderState(tif); (void) s; assert(sp != NULL); if( sp->enc_hashtab == NULL ) { tif->tif_setupencode( tif ); } sp->lzw_nbits = BITS_MIN; sp->lzw_maxcode = MAXCODE(BITS_MIN); sp->lzw_free_ent = CODE_FIRST; sp->lzw_nextbits = 0; sp->lzw_nextdata = 0; sp->enc_checkpoint = CHECK_GAP; sp->enc_ratio = 0; sp->enc_incount = 0; sp->enc_outcount = 0; /* * The 4 here insures there is space for 2 max-sized * codes in LZWEncode and LZWPostDecode. */ sp->enc_rawlimit = tif->tif_rawdata + tif->tif_rawdatasize-1 - 4; cl_hash(sp); /* clear hash table */ sp->enc_oldcode = (hcode_t) -1; /* generates CODE_CLEAR in LZWEncode */ return (1); } #define CALCRATIO(sp, rat) { \ if (incount > 0x007fffff) { /* NB: shift will overflow */\ rat = outcount >> 8; \ rat = (rat == 0 ? 0x7fffffff : incount/rat); \ } else \ rat = (incount<<8) / outcount; \ } /* Explicit 0xff masking to make icc -check=conversions happy */ #define PutNextCode(op, c) { \ nextdata = (nextdata << nbits) | c; \ nextbits += nbits; \ *op++ = (unsigned char)((nextdata >> (nextbits-8))&0xff); \ nextbits -= 8; \ if (nextbits >= 8) { \ *op++ = (unsigned char)((nextdata >> (nextbits-8))&0xff); \ nextbits -= 8; \ } \ outcount += nbits; \ } /* * Encode a chunk of pixels. * * Uses an open addressing double hashing (no chaining) on the * prefix code/next character combination. We do a variant of * Knuth's algorithm D (vol. 3, sec. 6.4) along with G. Knott's * relatively-prime secondary probe. Here, the modular division * first probe is gives way to a faster exclusive-or manipulation. * Also do block compression with an adaptive reset, whereby the * code table is cleared when the compression ratio decreases, * but after the table fills. The variable-length output codes * are re-sized at this point, and a CODE_CLEAR is generated * for the decoder. */ static int LZWEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s) { register LZWCodecState *sp = EncoderState(tif); register long fcode; register hash_t *hp; register int h, c; hcode_t ent; long disp; long incount, outcount, checkpoint; unsigned long nextdata; long nextbits; int free_ent, maxcode, nbits; uint8* op; uint8* limit; (void) s; if (sp == NULL) return (0); assert(sp->enc_hashtab != NULL); /* * Load local state. */ incount = sp->enc_incount; outcount = sp->enc_outcount; checkpoint = sp->enc_checkpoint; nextdata = sp->lzw_nextdata; nextbits = sp->lzw_nextbits; free_ent = sp->lzw_free_ent; maxcode = sp->lzw_maxcode; nbits = sp->lzw_nbits; op = tif->tif_rawcp; limit = sp->enc_rawlimit; ent = (hcode_t)sp->enc_oldcode; if (ent == (hcode_t) -1 && cc > 0) { /* * NB: This is safe because it can only happen * at the start of a strip where we know there * is space in the data buffer. */ PutNextCode(op, CODE_CLEAR); ent = *bp++; cc--; incount++; } while (cc > 0) { c = *bp++; cc--; incount++; fcode = ((long)c << BITS_MAX) + ent; h = (c << HSHIFT) ^ ent; /* xor hashing */ #ifdef _WINDOWS /* * Check hash index for an overflow. */ if (h >= HSIZE) h -= HSIZE; #endif hp = &sp->enc_hashtab[h]; if (hp->hash == fcode) { ent = hp->code; continue; } if (hp->hash >= 0) { /* * Primary hash failed, check secondary hash. */ disp = HSIZE - h; if (h == 0) disp = 1; do { /* * Avoid pointer arithmetic because of * wraparound problems with segments. */ if ((h -= disp) < 0) h += HSIZE; hp = &sp->enc_hashtab[h]; if (hp->hash == fcode) { ent = hp->code; goto hit; } } while (hp->hash >= 0); } /* * New entry, emit code and add to table. */ /* * Verify there is space in the buffer for the code * and any potential Clear code that might be emitted * below. The value of limit is setup so that there * are at least 4 bytes free--room for 2 codes. */ if (op > limit) { tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata); if( !TIFFFlushData1(tif) ) return 0; op = tif->tif_rawdata; } PutNextCode(op, ent); ent = (hcode_t)c; hp->code = (hcode_t)(free_ent++); hp->hash = fcode; if (free_ent == CODE_MAX-1) { /* table is full, emit clear code and reset */ cl_hash(sp); sp->enc_ratio = 0; incount = 0; outcount = 0; free_ent = CODE_FIRST; PutNextCode(op, CODE_CLEAR); nbits = BITS_MIN; maxcode = MAXCODE(BITS_MIN); } else { /* * If the next entry is going to be too big for * the code size, then increase it, if possible. */ if (free_ent > maxcode) { nbits++; assert(nbits <= BITS_MAX); maxcode = (int) MAXCODE(nbits); } else if (incount >= checkpoint) { long rat; /* * Check compression ratio and, if things seem * to be slipping, clear the hash table and * reset state. The compression ratio is a * 24+8-bit fractional number. */ checkpoint = incount+CHECK_GAP; CALCRATIO(sp, rat); if (rat <= sp->enc_ratio) { cl_hash(sp); sp->enc_ratio = 0; incount = 0; outcount = 0; free_ent = CODE_FIRST; PutNextCode(op, CODE_CLEAR); nbits = BITS_MIN; maxcode = MAXCODE(BITS_MIN); } else sp->enc_ratio = rat; } } hit: ; } /* * Restore global state. */ sp->enc_incount = incount; sp->enc_outcount = outcount; sp->enc_checkpoint = checkpoint; sp->enc_oldcode = ent; sp->lzw_nextdata = nextdata; sp->lzw_nextbits = nextbits; sp->lzw_free_ent = (unsigned short)free_ent; sp->lzw_maxcode = (unsigned short)maxcode; sp->lzw_nbits = (unsigned short)nbits; tif->tif_rawcp = op; return (1); } /* * Finish off an encoded strip by flushing the last * string and tacking on an End Of Information code. */ static int LZWPostEncode(TIFF* tif) { register LZWCodecState *sp = EncoderState(tif); uint8* op = tif->tif_rawcp; long nextbits = sp->lzw_nextbits; unsigned long nextdata = sp->lzw_nextdata; long outcount = sp->enc_outcount; int nbits = sp->lzw_nbits; if (op > sp->enc_rawlimit) { tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata); if( !TIFFFlushData1(tif) ) return 0; op = tif->tif_rawdata; } if (sp->enc_oldcode != (hcode_t) -1) { int free_ent = sp->lzw_free_ent; PutNextCode(op, sp->enc_oldcode); sp->enc_oldcode = (hcode_t) -1; free_ent ++; if (free_ent == CODE_MAX-1) { /* table is full, emit clear code and reset */ outcount = 0; PutNextCode(op, CODE_CLEAR); nbits = BITS_MIN; } else { /* * If the next entry is going to be too big for * the code size, then increase it, if possible. */ if (free_ent > sp->lzw_maxcode) { nbits++; assert(nbits <= BITS_MAX); } } } PutNextCode(op, CODE_EOI); /* Explicit 0xff masking to make icc -check=conversions happy */ if (nextbits > 0) *op++ = (unsigned char)((nextdata << (8-nextbits))&0xff); tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata); return (1); } /* * Reset encoding hash table. */ static void cl_hash(LZWCodecState* sp) { register hash_t *hp = &sp->enc_hashtab[HSIZE-1]; register long i = HSIZE-8; do { i -= 8; hp[-7].hash = -1; hp[-6].hash = -1; hp[-5].hash = -1; hp[-4].hash = -1; hp[-3].hash = -1; hp[-2].hash = -1; hp[-1].hash = -1; hp[ 0].hash = -1; hp -= 8; } while (i >= 0); for (i += 8; i > 0; i--, hp--) hp->hash = -1; } static void LZWCleanup(TIFF* tif) { (void)TIFFPredictorCleanup(tif); assert(tif->tif_data != 0); if (DecoderState(tif)->dec_codetab) _TIFFfree(DecoderState(tif)->dec_codetab); if (EncoderState(tif)->enc_hashtab) _TIFFfree(EncoderState(tif)->enc_hashtab); _TIFFfree(tif->tif_data); tif->tif_data = NULL; _TIFFSetDefaultCompressionState(tif); } int TIFFInitLZW(TIFF* tif, int scheme) { static const char module[] = "TIFFInitLZW"; assert(scheme == COMPRESSION_LZW); /* * Allocate state block so tag methods have storage to record values. */ tif->tif_data = (uint8*) _TIFFmalloc(sizeof (LZWCodecState)); if (tif->tif_data == NULL) goto bad; DecoderState(tif)->dec_codetab = NULL; DecoderState(tif)->dec_decode = NULL; EncoderState(tif)->enc_hashtab = NULL; LZWState(tif)->rw_mode = tif->tif_mode; /* * Install codec methods. */ tif->tif_fixuptags = LZWFixupTags; tif->tif_setupdecode = LZWSetupDecode; tif->tif_predecode = LZWPreDecode; tif->tif_decoderow = LZWDecode; tif->tif_decodestrip = LZWDecode; tif->tif_decodetile = LZWDecode; tif->tif_setupencode = LZWSetupEncode; tif->tif_preencode = LZWPreEncode; tif->tif_postencode = LZWPostEncode; tif->tif_encoderow = LZWEncode; tif->tif_encodestrip = LZWEncode; tif->tif_encodetile = LZWEncode; tif->tif_cleanup = LZWCleanup; /* * Setup predictor setup. */ (void) TIFFPredictorInit(tif); return (1); bad: TIFFErrorExt(tif->tif_clientdata, module, "No space for LZW state block"); return (0); } /* * Copyright (c) 1985, 1986 The Regents of the University of California. * All rights reserved. * * This code is derived from software contributed to Berkeley by * James A. Woods, derived from original work by Spencer Thomas * and Joseph Orost. * * Redistribution and use in source and binary forms are permitted * provided that the above copyright notice and this paragraph are * duplicated in all such forms and that any documentation, * advertising materials, and other materials related to such * distribution and use acknowledge that the software was developed * by the University of California, Berkeley. The name of the * University may not be used to endorse or promote products derived * from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #endif /* LZW_SUPPORT */ /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
null
110
CWE-787
CVE-2019-1010292
// SPDX-License-Identifier: BSD-2-Clause /* * Copyright (c) 2015-2016, Linaro Limited * Copyright (c) 2014, STMicroelectronics International N.V. */ #include <assert.h> #include <bench.h> #include <compiler.h> #include <initcall.h> #include <io.h> #include <kernel/linker.h> #include <kernel/msg_param.h> #include <kernel/panic.h> #include <kernel/tee_misc.h> #include <mm/core_memprot.h> #include <mm/core_mmu.h> #include <mm/mobj.h> #include <optee_msg.h> #include <sm/optee_smc.h> #include <string.h> #include <tee/entry_std.h> #include <tee/tee_cryp_utl.h> #include <tee/uuid.h> #include <util.h> #define SHM_CACHE_ATTRS \ (uint32_t)(core_mmu_is_shm_cached() ? OPTEE_SMC_SHM_CACHED : 0) /* Sessions opened from normal world */ static struct tee_ta_session_head tee_open_sessions = TAILQ_HEAD_INITIALIZER(tee_open_sessions); static struct mobj *shm_mobj; #ifdef CFG_SECURE_DATA_PATH static struct mobj **sdp_mem_mobjs; #endif static unsigned int session_pnum; static bool param_mem_from_mobj(struct param_mem *mem, struct mobj *mobj, const paddr_t pa, const size_t sz) { paddr_t b; if (mobj_get_pa(mobj, 0, 0, &b) != TEE_SUCCESS) panic("mobj_get_pa failed"); if (!core_is_buffer_inside(pa, MAX(sz, 1UL), b, mobj->size)) return false; mem->mobj = mobj; mem->offs = pa - b; mem->size = sz; return true; } /* fill 'struct param_mem' structure if buffer matches a valid memory object */ static TEE_Result set_tmem_param(const struct optee_msg_param_tmem *tmem, uint32_t attr, struct param_mem *mem) { struct mobj __maybe_unused **mobj; paddr_t pa = READ_ONCE(tmem->buf_ptr); size_t sz = READ_ONCE(tmem->size); /* NULL Memory Rerefence? */ if (!pa && !sz) { mem->mobj = NULL; mem->offs = 0; mem->size = 0; return TEE_SUCCESS; } /* Non-contigous buffer from non sec DDR? */ if (attr & OPTEE_MSG_ATTR_NONCONTIG) { uint64_t shm_ref = READ_ONCE(tmem->shm_ref); mem->mobj = msg_param_mobj_from_noncontig(pa, sz, shm_ref, false); if (!mem->mobj) return TEE_ERROR_BAD_PARAMETERS; mem->offs = 0; mem->size = sz; return TEE_SUCCESS; } /* Belongs to nonsecure shared memory? */ if (param_mem_from_mobj(mem, shm_mobj, pa, sz)) return TEE_SUCCESS; #ifdef CFG_SECURE_DATA_PATH /* Belongs to SDP memories? */ for (mobj = sdp_mem_mobjs; *mobj; mobj++) if (param_mem_from_mobj(mem, *mobj, pa, sz)) return TEE_SUCCESS; #endif return TEE_ERROR_BAD_PARAMETERS; } static TEE_Result set_rmem_param(const struct optee_msg_param_rmem *rmem, struct param_mem *mem) { uint64_t shm_ref = READ_ONCE(rmem->shm_ref); mem->mobj = mobj_reg_shm_get_by_cookie(shm_ref); if (!mem->mobj) return TEE_ERROR_BAD_PARAMETERS; mem->offs = READ_ONCE(rmem->offs); mem->size = READ_ONCE(rmem->size); return TEE_SUCCESS; } static TEE_Result copy_in_params(const struct optee_msg_param *params, uint32_t num_params, struct tee_ta_param *ta_param, uint64_t *saved_attr) { TEE_Result res; size_t n; uint8_t pt[TEE_NUM_PARAMS] = { 0 }; if (num_params > TEE_NUM_PARAMS) return TEE_ERROR_BAD_PARAMETERS; memset(ta_param, 0, sizeof(*ta_param)); for (n = 0; n < num_params; n++) { uint32_t attr; saved_attr[n] = READ_ONCE(params[n].attr); if (saved_attr[n] & OPTEE_MSG_ATTR_META) return TEE_ERROR_BAD_PARAMETERS; attr = saved_attr[n] & OPTEE_MSG_ATTR_TYPE_MASK; switch (attr) { case OPTEE_MSG_ATTR_TYPE_NONE: pt[n] = TEE_PARAM_TYPE_NONE; break; case OPTEE_MSG_ATTR_TYPE_VALUE_INPUT: case OPTEE_MSG_ATTR_TYPE_VALUE_OUTPUT: case OPTEE_MSG_ATTR_TYPE_VALUE_INOUT: pt[n] = TEE_PARAM_TYPE_VALUE_INPUT + attr - OPTEE_MSG_ATTR_TYPE_VALUE_INPUT; ta_param->u[n].val.a = READ_ONCE(params[n].u.value.a); ta_param->u[n].val.b = READ_ONCE(params[n].u.value.b); break; case OPTEE_MSG_ATTR_TYPE_TMEM_INPUT: case OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT: case OPTEE_MSG_ATTR_TYPE_TMEM_INOUT: res = set_tmem_param(&params[n].u.tmem, saved_attr[n], &ta_param->u[n].mem); if (res) return res; pt[n] = TEE_PARAM_TYPE_MEMREF_INPUT + attr - OPTEE_MSG_ATTR_TYPE_TMEM_INPUT; break; case OPTEE_MSG_ATTR_TYPE_RMEM_INPUT: case OPTEE_MSG_ATTR_TYPE_RMEM_OUTPUT: case OPTEE_MSG_ATTR_TYPE_RMEM_INOUT: res = set_rmem_param(&params[n].u.rmem, &ta_param->u[n].mem); if (res) return res; pt[n] = TEE_PARAM_TYPE_MEMREF_INPUT + attr - OPTEE_MSG_ATTR_TYPE_RMEM_INPUT; break; default: return TEE_ERROR_BAD_PARAMETERS; } } ta_param->types = TEE_PARAM_TYPES(pt[0], pt[1], pt[2], pt[3]); return TEE_SUCCESS; } static void cleanup_shm_refs(const uint64_t *saved_attr, struct tee_ta_param *param, uint32_t num_params) { size_t n; for (n = 0; n < num_params; n++) { switch (saved_attr[n]) { case OPTEE_MSG_ATTR_TYPE_TMEM_INPUT: case OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT: case OPTEE_MSG_ATTR_TYPE_TMEM_INOUT: if (saved_attr[n] & OPTEE_MSG_ATTR_NONCONTIG) mobj_free(param->u[n].mem.mobj); break; case OPTEE_MSG_ATTR_TYPE_RMEM_INPUT: case OPTEE_MSG_ATTR_TYPE_RMEM_OUTPUT: case OPTEE_MSG_ATTR_TYPE_RMEM_INOUT: mobj_reg_shm_put(param->u[n].mem.mobj); break; default: break; } } } static void copy_out_param(struct tee_ta_param *ta_param, uint32_t num_params, struct optee_msg_param *params, uint64_t *saved_attr) { size_t n; for (n = 0; n < num_params; n++) { switch (TEE_PARAM_TYPE_GET(ta_param->types, n)) { case TEE_PARAM_TYPE_MEMREF_OUTPUT: case TEE_PARAM_TYPE_MEMREF_INOUT: switch (saved_attr[n] & OPTEE_MSG_ATTR_TYPE_MASK) { case OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT: case OPTEE_MSG_ATTR_TYPE_TMEM_INOUT: params[n].u.tmem.size = ta_param->u[n].mem.size; break; case OPTEE_MSG_ATTR_TYPE_RMEM_OUTPUT: case OPTEE_MSG_ATTR_TYPE_RMEM_INOUT: params[n].u.rmem.size = ta_param->u[n].mem.size; break; default: break; } break; case TEE_PARAM_TYPE_VALUE_OUTPUT: case TEE_PARAM_TYPE_VALUE_INOUT: params[n].u.value.a = ta_param->u[n].val.a; params[n].u.value.b = ta_param->u[n].val.b; break; default: break; } } } /* * Extracts mandatory parameter for open session. * * Returns * false : mandatory parameter wasn't found or malformatted * true : paramater found and OK */ static TEE_Result get_open_session_meta(size_t num_params, struct optee_msg_param *params, size_t *num_meta, TEE_UUID *uuid, TEE_Identity *clnt_id) { const uint32_t req_attr = OPTEE_MSG_ATTR_META | OPTEE_MSG_ATTR_TYPE_VALUE_INPUT; if (num_params < 2) return TEE_ERROR_BAD_PARAMETERS; if (params[0].attr != req_attr || params[1].attr != req_attr) return TEE_ERROR_BAD_PARAMETERS; tee_uuid_from_octets(uuid, (void *)&params[0].u.value); clnt_id->login = params[1].u.value.c; switch (clnt_id->login) { case TEE_LOGIN_PUBLIC: memset(&clnt_id->uuid, 0, sizeof(clnt_id->uuid)); break; case TEE_LOGIN_USER: case TEE_LOGIN_GROUP: case TEE_LOGIN_APPLICATION: case TEE_LOGIN_APPLICATION_USER: case TEE_LOGIN_APPLICATION_GROUP: tee_uuid_from_octets(&clnt_id->uuid, (void *)&params[1].u.value); break; default: return TEE_ERROR_BAD_PARAMETERS; } *num_meta = 2; return TEE_SUCCESS; } static void entry_open_session(struct thread_smc_args *smc_args, struct optee_msg_arg *arg, uint32_t num_params) { TEE_Result res; TEE_ErrorOrigin err_orig = TEE_ORIGIN_TEE; struct tee_ta_session *s = NULL; TEE_Identity clnt_id; TEE_UUID uuid; struct tee_ta_param param; size_t num_meta; uint64_t saved_attr[TEE_NUM_PARAMS] = { 0 }; res = get_open_session_meta(num_params, arg->params, &num_meta, &uuid, &clnt_id); if (res != TEE_SUCCESS) goto out; res = copy_in_params(arg->params + num_meta, num_params - num_meta, &param, saved_attr); if (res != TEE_SUCCESS) goto cleanup_shm_refs; res = tee_ta_open_session(&err_orig, &s, &tee_open_sessions, &uuid, &clnt_id, TEE_TIMEOUT_INFINITE, &param); if (res != TEE_SUCCESS) s = NULL; copy_out_param(&param, num_params - num_meta, arg->params + num_meta, saved_attr); /* * The occurrence of open/close session command is usually * un-predictable, using this property to increase randomness * of prng */ plat_prng_add_jitter_entropy(CRYPTO_RNG_SRC_JITTER_SESSION, &session_pnum); cleanup_shm_refs: cleanup_shm_refs(saved_attr, &param, num_params - num_meta); out: if (s) arg->session = (vaddr_t)s; else arg->session = 0; arg->ret = res; arg->ret_origin = err_orig; smc_args->a0 = OPTEE_SMC_RETURN_OK; } static void entry_close_session(struct thread_smc_args *smc_args, struct optee_msg_arg *arg, uint32_t num_params) { TEE_Result res; struct tee_ta_session *s; if (num_params) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } plat_prng_add_jitter_entropy(CRYPTO_RNG_SRC_JITTER_SESSION, &session_pnum); s = (struct tee_ta_session *)(vaddr_t)arg->session; res = tee_ta_close_session(s, &tee_open_sessions, NSAPP_IDENTITY); out: arg->ret = res; arg->ret_origin = TEE_ORIGIN_TEE; smc_args->a0 = OPTEE_SMC_RETURN_OK; } static void entry_invoke_command(struct thread_smc_args *smc_args, struct optee_msg_arg *arg, uint32_t num_params) { TEE_Result res; TEE_ErrorOrigin err_orig = TEE_ORIGIN_TEE; struct tee_ta_session *s; struct tee_ta_param param = { 0 }; uint64_t saved_attr[TEE_NUM_PARAMS] = { 0 }; bm_timestamp(); res = copy_in_params(arg->params, num_params, &param, saved_attr); if (res != TEE_SUCCESS) goto out; s = tee_ta_get_session(arg->session, true, &tee_open_sessions); if (!s) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_ta_invoke_command(&err_orig, s, NSAPP_IDENTITY, TEE_TIMEOUT_INFINITE, arg->func, &param); bm_timestamp(); tee_ta_put_session(s); copy_out_param(&param, num_params, arg->params, saved_attr); out: cleanup_shm_refs(saved_attr, &param, num_params); arg->ret = res; arg->ret_origin = err_orig; smc_args->a0 = OPTEE_SMC_RETURN_OK; } static void entry_cancel(struct thread_smc_args *smc_args, struct optee_msg_arg *arg, uint32_t num_params) { TEE_Result res; TEE_ErrorOrigin err_orig = TEE_ORIGIN_TEE; struct tee_ta_session *s; if (num_params) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } s = tee_ta_get_session(arg->session, false, &tee_open_sessions); if (!s) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_ta_cancel_command(&err_orig, s, NSAPP_IDENTITY); tee_ta_put_session(s); out: arg->ret = res; arg->ret_origin = err_orig; smc_args->a0 = OPTEE_SMC_RETURN_OK; } static void register_shm(struct thread_smc_args *smc_args, struct optee_msg_arg *arg, uint32_t num_params) { arg->ret = TEE_ERROR_BAD_PARAMETERS; smc_args->a0 = OPTEE_SMC_RETURN_OK; if (num_params != 1 || (arg->params[0].attr != (OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT | OPTEE_MSG_ATTR_NONCONTIG))) return; struct optee_msg_param_tmem *tmem = &arg->params[0].u.tmem; struct mobj *mobj = msg_param_mobj_from_noncontig(tmem->buf_ptr, tmem->size, tmem->shm_ref, false); if (!mobj) return; mobj_reg_shm_unguard(mobj); arg->ret = TEE_SUCCESS; } static void unregister_shm(struct thread_smc_args *smc_args, struct optee_msg_arg *arg, uint32_t num_params) { if (num_params == 1) { uint64_t cookie = arg->params[0].u.rmem.shm_ref; TEE_Result res = mobj_reg_shm_release_by_cookie(cookie); if (res) EMSG("Can't find mapping with given cookie"); arg->ret = res; } else { arg->ret = TEE_ERROR_BAD_PARAMETERS; arg->ret_origin = TEE_ORIGIN_TEE; } smc_args->a0 = OPTEE_SMC_RETURN_OK; } static struct mobj *map_cmd_buffer(paddr_t parg, uint32_t *num_params) { struct mobj *mobj; struct optee_msg_arg *arg; size_t args_size; assert(!(parg & SMALL_PAGE_MASK)); /* mobj_mapped_shm_alloc checks if parg resides in nonsec ddr */ mobj = mobj_mapped_shm_alloc(&parg, 1, 0, 0); if (!mobj) return NULL; arg = mobj_get_va(mobj, 0); if (!arg) { mobj_free(mobj); return NULL; } *num_params = READ_ONCE(arg->num_params); args_size = OPTEE_MSG_GET_ARG_SIZE(*num_params); if (args_size > SMALL_PAGE_SIZE) { EMSG("Command buffer spans across page boundary"); mobj_free(mobj); return NULL; } return mobj; } static struct mobj *get_cmd_buffer(paddr_t parg, uint32_t *num_params) { struct optee_msg_arg *arg; size_t args_size; arg = phys_to_virt(parg, MEM_AREA_NSEC_SHM); if (!arg) return NULL; *num_params = READ_ONCE(arg->num_params); args_size = OPTEE_MSG_GET_ARG_SIZE(*num_params); return mobj_shm_alloc(parg, args_size, 0); } /* * Note: this function is weak just to make it possible to exclude it from * the unpaged area. */ void __weak tee_entry_std(struct thread_smc_args *smc_args) { paddr_t parg; struct optee_msg_arg *arg = NULL; /* fix gcc warning */ uint32_t num_params = 0; /* fix gcc warning */ struct mobj *mobj; if (smc_args->a0 != OPTEE_SMC_CALL_WITH_ARG) { EMSG("Unknown SMC 0x%" PRIx64, (uint64_t)smc_args->a0); DMSG("Expected 0x%x\n", OPTEE_SMC_CALL_WITH_ARG); smc_args->a0 = OPTEE_SMC_RETURN_EBADCMD; return; } parg = (uint64_t)smc_args->a1 << 32 | smc_args->a2; /* Check if this region is in static shared space */ if (core_pbuf_is(CORE_MEM_NSEC_SHM, parg, sizeof(struct optee_msg_arg))) { mobj = get_cmd_buffer(parg, &num_params); } else { if (parg & SMALL_PAGE_MASK) { smc_args->a0 = OPTEE_SMC_RETURN_EBADADDR; return; } mobj = map_cmd_buffer(parg, &num_params); } if (!mobj || !ALIGNMENT_IS_OK(parg, struct optee_msg_arg)) { EMSG("Bad arg address 0x%" PRIxPA, parg); smc_args->a0 = OPTEE_SMC_RETURN_EBADADDR; mobj_free(mobj); return; } arg = mobj_get_va(mobj, 0); assert(arg && mobj_is_nonsec(mobj)); /* Enable foreign interrupts for STD calls */ thread_set_foreign_intr(true); switch (arg->cmd) { case OPTEE_MSG_CMD_OPEN_SESSION: entry_open_session(smc_args, arg, num_params); break; case OPTEE_MSG_CMD_CLOSE_SESSION: entry_close_session(smc_args, arg, num_params); break; case OPTEE_MSG_CMD_INVOKE_COMMAND: entry_invoke_command(smc_args, arg, num_params); break; case OPTEE_MSG_CMD_CANCEL: entry_cancel(smc_args, arg, num_params); break; case OPTEE_MSG_CMD_REGISTER_SHM: register_shm(smc_args, arg, num_params); break; case OPTEE_MSG_CMD_UNREGISTER_SHM: unregister_shm(smc_args, arg, num_params); break; default: EMSG("Unknown cmd 0x%x\n", arg->cmd); smc_args->a0 = OPTEE_SMC_RETURN_EBADCMD; } mobj_free(mobj); } static TEE_Result default_mobj_init(void) { shm_mobj = mobj_phys_alloc(default_nsec_shm_paddr, default_nsec_shm_size, SHM_CACHE_ATTRS, CORE_MEM_NSEC_SHM); if (!shm_mobj) panic("Failed to register shared memory"); #ifdef CFG_SECURE_DATA_PATH sdp_mem_mobjs = core_sdp_mem_create_mobjs(); if (!sdp_mem_mobjs) panic("Failed to register SDP memory"); #endif return TEE_SUCCESS; } driver_init_late(default_mobj_init);
null
// SPDX-License-Identifier: BSD-2-Clause /* * Copyright (c) 2015-2016, Linaro Limited * Copyright (c) 2014, STMicroelectronics International N.V. */ #include <assert.h> #include <bench.h> #include <compiler.h> #include <initcall.h> #include <io.h> #include <kernel/linker.h> #include <kernel/msg_param.h> #include <kernel/panic.h> #include <kernel/tee_misc.h> #include <mm/core_memprot.h> #include <mm/core_mmu.h> #include <mm/mobj.h> #include <optee_msg.h> #include <sm/optee_smc.h> #include <string.h> #include <tee/entry_std.h> #include <tee/tee_cryp_utl.h> #include <tee/uuid.h> #include <util.h> #define SHM_CACHE_ATTRS \ (uint32_t)(core_mmu_is_shm_cached() ? OPTEE_SMC_SHM_CACHED : 0) /* Sessions opened from normal world */ static struct tee_ta_session_head tee_open_sessions = TAILQ_HEAD_INITIALIZER(tee_open_sessions); static struct mobj *shm_mobj; #ifdef CFG_SECURE_DATA_PATH static struct mobj **sdp_mem_mobjs; #endif static unsigned int session_pnum; static bool param_mem_from_mobj(struct param_mem *mem, struct mobj *mobj, const paddr_t pa, const size_t sz) { paddr_t b; if (mobj_get_pa(mobj, 0, 0, &b) != TEE_SUCCESS) panic("mobj_get_pa failed"); if (!core_is_buffer_inside(pa, MAX(sz, 1UL), b, mobj->size)) return false; mem->mobj = mobj; mem->offs = pa - b; mem->size = sz; return true; } /* fill 'struct param_mem' structure if buffer matches a valid memory object */ static TEE_Result set_tmem_param(const struct optee_msg_param_tmem *tmem, uint32_t attr, struct param_mem *mem) { struct mobj __maybe_unused **mobj; paddr_t pa = READ_ONCE(tmem->buf_ptr); size_t sz = READ_ONCE(tmem->size); /* NULL Memory Rerefence? */ if (!pa && !sz) { mem->mobj = NULL; mem->offs = 0; mem->size = 0; return TEE_SUCCESS; } /* Non-contigous buffer from non sec DDR? */ if (attr & OPTEE_MSG_ATTR_NONCONTIG) { uint64_t shm_ref = READ_ONCE(tmem->shm_ref); mem->mobj = msg_param_mobj_from_noncontig(pa, sz, shm_ref, false); if (!mem->mobj) return TEE_ERROR_BAD_PARAMETERS; mem->offs = 0; mem->size = sz; return TEE_SUCCESS; } /* Belongs to nonsecure shared memory? */ if (param_mem_from_mobj(mem, shm_mobj, pa, sz)) return TEE_SUCCESS; #ifdef CFG_SECURE_DATA_PATH /* Belongs to SDP memories? */ for (mobj = sdp_mem_mobjs; *mobj; mobj++) if (param_mem_from_mobj(mem, *mobj, pa, sz)) return TEE_SUCCESS; #endif return TEE_ERROR_BAD_PARAMETERS; } static TEE_Result set_rmem_param(const struct optee_msg_param_rmem *rmem, struct param_mem *mem) { size_t req_size = 0; uint64_t shm_ref = READ_ONCE(rmem->shm_ref); mem->mobj = mobj_reg_shm_get_by_cookie(shm_ref); if (!mem->mobj) return TEE_ERROR_BAD_PARAMETERS; mem->offs = READ_ONCE(rmem->offs); mem->size = READ_ONCE(rmem->size); /* * Check that the supplied offset and size is covered by the * previously verified MOBJ. */ if (ADD_OVERFLOW(mem->offs, mem->size, &req_size) || mem->mobj->size < req_size) return TEE_ERROR_SECURITY; return TEE_SUCCESS; } static TEE_Result copy_in_params(const struct optee_msg_param *params, uint32_t num_params, struct tee_ta_param *ta_param, uint64_t *saved_attr) { TEE_Result res; size_t n; uint8_t pt[TEE_NUM_PARAMS] = { 0 }; if (num_params > TEE_NUM_PARAMS) return TEE_ERROR_BAD_PARAMETERS; memset(ta_param, 0, sizeof(*ta_param)); for (n = 0; n < num_params; n++) { uint32_t attr; saved_attr[n] = READ_ONCE(params[n].attr); if (saved_attr[n] & OPTEE_MSG_ATTR_META) return TEE_ERROR_BAD_PARAMETERS; attr = saved_attr[n] & OPTEE_MSG_ATTR_TYPE_MASK; switch (attr) { case OPTEE_MSG_ATTR_TYPE_NONE: pt[n] = TEE_PARAM_TYPE_NONE; break; case OPTEE_MSG_ATTR_TYPE_VALUE_INPUT: case OPTEE_MSG_ATTR_TYPE_VALUE_OUTPUT: case OPTEE_MSG_ATTR_TYPE_VALUE_INOUT: pt[n] = TEE_PARAM_TYPE_VALUE_INPUT + attr - OPTEE_MSG_ATTR_TYPE_VALUE_INPUT; ta_param->u[n].val.a = READ_ONCE(params[n].u.value.a); ta_param->u[n].val.b = READ_ONCE(params[n].u.value.b); break; case OPTEE_MSG_ATTR_TYPE_TMEM_INPUT: case OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT: case OPTEE_MSG_ATTR_TYPE_TMEM_INOUT: res = set_tmem_param(&params[n].u.tmem, saved_attr[n], &ta_param->u[n].mem); if (res) return res; pt[n] = TEE_PARAM_TYPE_MEMREF_INPUT + attr - OPTEE_MSG_ATTR_TYPE_TMEM_INPUT; break; case OPTEE_MSG_ATTR_TYPE_RMEM_INPUT: case OPTEE_MSG_ATTR_TYPE_RMEM_OUTPUT: case OPTEE_MSG_ATTR_TYPE_RMEM_INOUT: res = set_rmem_param(&params[n].u.rmem, &ta_param->u[n].mem); if (res) return res; pt[n] = TEE_PARAM_TYPE_MEMREF_INPUT + attr - OPTEE_MSG_ATTR_TYPE_RMEM_INPUT; break; default: return TEE_ERROR_BAD_PARAMETERS; } } ta_param->types = TEE_PARAM_TYPES(pt[0], pt[1], pt[2], pt[3]); return TEE_SUCCESS; } static void cleanup_shm_refs(const uint64_t *saved_attr, struct tee_ta_param *param, uint32_t num_params) { size_t n; for (n = 0; n < num_params; n++) { switch (saved_attr[n]) { case OPTEE_MSG_ATTR_TYPE_TMEM_INPUT: case OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT: case OPTEE_MSG_ATTR_TYPE_TMEM_INOUT: if (saved_attr[n] & OPTEE_MSG_ATTR_NONCONTIG) mobj_free(param->u[n].mem.mobj); break; case OPTEE_MSG_ATTR_TYPE_RMEM_INPUT: case OPTEE_MSG_ATTR_TYPE_RMEM_OUTPUT: case OPTEE_MSG_ATTR_TYPE_RMEM_INOUT: mobj_reg_shm_put(param->u[n].mem.mobj); break; default: break; } } } static void copy_out_param(struct tee_ta_param *ta_param, uint32_t num_params, struct optee_msg_param *params, uint64_t *saved_attr) { size_t n; for (n = 0; n < num_params; n++) { switch (TEE_PARAM_TYPE_GET(ta_param->types, n)) { case TEE_PARAM_TYPE_MEMREF_OUTPUT: case TEE_PARAM_TYPE_MEMREF_INOUT: switch (saved_attr[n] & OPTEE_MSG_ATTR_TYPE_MASK) { case OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT: case OPTEE_MSG_ATTR_TYPE_TMEM_INOUT: params[n].u.tmem.size = ta_param->u[n].mem.size; break; case OPTEE_MSG_ATTR_TYPE_RMEM_OUTPUT: case OPTEE_MSG_ATTR_TYPE_RMEM_INOUT: params[n].u.rmem.size = ta_param->u[n].mem.size; break; default: break; } break; case TEE_PARAM_TYPE_VALUE_OUTPUT: case TEE_PARAM_TYPE_VALUE_INOUT: params[n].u.value.a = ta_param->u[n].val.a; params[n].u.value.b = ta_param->u[n].val.b; break; default: break; } } } /* * Extracts mandatory parameter for open session. * * Returns * false : mandatory parameter wasn't found or malformatted * true : paramater found and OK */ static TEE_Result get_open_session_meta(size_t num_params, struct optee_msg_param *params, size_t *num_meta, TEE_UUID *uuid, TEE_Identity *clnt_id) { const uint32_t req_attr = OPTEE_MSG_ATTR_META | OPTEE_MSG_ATTR_TYPE_VALUE_INPUT; if (num_params < 2) return TEE_ERROR_BAD_PARAMETERS; if (params[0].attr != req_attr || params[1].attr != req_attr) return TEE_ERROR_BAD_PARAMETERS; tee_uuid_from_octets(uuid, (void *)&params[0].u.value); clnt_id->login = params[1].u.value.c; switch (clnt_id->login) { case TEE_LOGIN_PUBLIC: memset(&clnt_id->uuid, 0, sizeof(clnt_id->uuid)); break; case TEE_LOGIN_USER: case TEE_LOGIN_GROUP: case TEE_LOGIN_APPLICATION: case TEE_LOGIN_APPLICATION_USER: case TEE_LOGIN_APPLICATION_GROUP: tee_uuid_from_octets(&clnt_id->uuid, (void *)&params[1].u.value); break; default: return TEE_ERROR_BAD_PARAMETERS; } *num_meta = 2; return TEE_SUCCESS; } static void entry_open_session(struct thread_smc_args *smc_args, struct optee_msg_arg *arg, uint32_t num_params) { TEE_Result res; TEE_ErrorOrigin err_orig = TEE_ORIGIN_TEE; struct tee_ta_session *s = NULL; TEE_Identity clnt_id; TEE_UUID uuid; struct tee_ta_param param; size_t num_meta; uint64_t saved_attr[TEE_NUM_PARAMS] = { 0 }; res = get_open_session_meta(num_params, arg->params, &num_meta, &uuid, &clnt_id); if (res != TEE_SUCCESS) goto out; res = copy_in_params(arg->params + num_meta, num_params - num_meta, &param, saved_attr); if (res != TEE_SUCCESS) goto cleanup_shm_refs; res = tee_ta_open_session(&err_orig, &s, &tee_open_sessions, &uuid, &clnt_id, TEE_TIMEOUT_INFINITE, &param); if (res != TEE_SUCCESS) s = NULL; copy_out_param(&param, num_params - num_meta, arg->params + num_meta, saved_attr); /* * The occurrence of open/close session command is usually * un-predictable, using this property to increase randomness * of prng */ plat_prng_add_jitter_entropy(CRYPTO_RNG_SRC_JITTER_SESSION, &session_pnum); cleanup_shm_refs: cleanup_shm_refs(saved_attr, &param, num_params - num_meta); out: if (s) arg->session = (vaddr_t)s; else arg->session = 0; arg->ret = res; arg->ret_origin = err_orig; smc_args->a0 = OPTEE_SMC_RETURN_OK; } static void entry_close_session(struct thread_smc_args *smc_args, struct optee_msg_arg *arg, uint32_t num_params) { TEE_Result res; struct tee_ta_session *s; if (num_params) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } plat_prng_add_jitter_entropy(CRYPTO_RNG_SRC_JITTER_SESSION, &session_pnum); s = (struct tee_ta_session *)(vaddr_t)arg->session; res = tee_ta_close_session(s, &tee_open_sessions, NSAPP_IDENTITY); out: arg->ret = res; arg->ret_origin = TEE_ORIGIN_TEE; smc_args->a0 = OPTEE_SMC_RETURN_OK; } static void entry_invoke_command(struct thread_smc_args *smc_args, struct optee_msg_arg *arg, uint32_t num_params) { TEE_Result res; TEE_ErrorOrigin err_orig = TEE_ORIGIN_TEE; struct tee_ta_session *s; struct tee_ta_param param = { 0 }; uint64_t saved_attr[TEE_NUM_PARAMS] = { 0 }; bm_timestamp(); res = copy_in_params(arg->params, num_params, &param, saved_attr); if (res != TEE_SUCCESS) goto out; s = tee_ta_get_session(arg->session, true, &tee_open_sessions); if (!s) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_ta_invoke_command(&err_orig, s, NSAPP_IDENTITY, TEE_TIMEOUT_INFINITE, arg->func, &param); bm_timestamp(); tee_ta_put_session(s); copy_out_param(&param, num_params, arg->params, saved_attr); out: cleanup_shm_refs(saved_attr, &param, num_params); arg->ret = res; arg->ret_origin = err_orig; smc_args->a0 = OPTEE_SMC_RETURN_OK; } static void entry_cancel(struct thread_smc_args *smc_args, struct optee_msg_arg *arg, uint32_t num_params) { TEE_Result res; TEE_ErrorOrigin err_orig = TEE_ORIGIN_TEE; struct tee_ta_session *s; if (num_params) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } s = tee_ta_get_session(arg->session, false, &tee_open_sessions); if (!s) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_ta_cancel_command(&err_orig, s, NSAPP_IDENTITY); tee_ta_put_session(s); out: arg->ret = res; arg->ret_origin = err_orig; smc_args->a0 = OPTEE_SMC_RETURN_OK; } static void register_shm(struct thread_smc_args *smc_args, struct optee_msg_arg *arg, uint32_t num_params) { arg->ret = TEE_ERROR_BAD_PARAMETERS; smc_args->a0 = OPTEE_SMC_RETURN_OK; if (num_params != 1 || (arg->params[0].attr != (OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT | OPTEE_MSG_ATTR_NONCONTIG))) return; struct optee_msg_param_tmem *tmem = &arg->params[0].u.tmem; struct mobj *mobj = msg_param_mobj_from_noncontig(tmem->buf_ptr, tmem->size, tmem->shm_ref, false); if (!mobj) return; mobj_reg_shm_unguard(mobj); arg->ret = TEE_SUCCESS; } static void unregister_shm(struct thread_smc_args *smc_args, struct optee_msg_arg *arg, uint32_t num_params) { if (num_params == 1) { uint64_t cookie = arg->params[0].u.rmem.shm_ref; TEE_Result res = mobj_reg_shm_release_by_cookie(cookie); if (res) EMSG("Can't find mapping with given cookie"); arg->ret = res; } else { arg->ret = TEE_ERROR_BAD_PARAMETERS; arg->ret_origin = TEE_ORIGIN_TEE; } smc_args->a0 = OPTEE_SMC_RETURN_OK; } static struct mobj *map_cmd_buffer(paddr_t parg, uint32_t *num_params) { struct mobj *mobj; struct optee_msg_arg *arg; size_t args_size; assert(!(parg & SMALL_PAGE_MASK)); /* mobj_mapped_shm_alloc checks if parg resides in nonsec ddr */ mobj = mobj_mapped_shm_alloc(&parg, 1, 0, 0); if (!mobj) return NULL; arg = mobj_get_va(mobj, 0); if (!arg) { mobj_free(mobj); return NULL; } *num_params = READ_ONCE(arg->num_params); args_size = OPTEE_MSG_GET_ARG_SIZE(*num_params); if (args_size > SMALL_PAGE_SIZE) { EMSG("Command buffer spans across page boundary"); mobj_free(mobj); return NULL; } return mobj; } static struct mobj *get_cmd_buffer(paddr_t parg, uint32_t *num_params) { struct optee_msg_arg *arg; size_t args_size; arg = phys_to_virt(parg, MEM_AREA_NSEC_SHM); if (!arg) return NULL; *num_params = READ_ONCE(arg->num_params); args_size = OPTEE_MSG_GET_ARG_SIZE(*num_params); return mobj_shm_alloc(parg, args_size, 0); } /* * Note: this function is weak just to make it possible to exclude it from * the unpaged area. */ void __weak tee_entry_std(struct thread_smc_args *smc_args) { paddr_t parg; struct optee_msg_arg *arg = NULL; /* fix gcc warning */ uint32_t num_params = 0; /* fix gcc warning */ struct mobj *mobj; if (smc_args->a0 != OPTEE_SMC_CALL_WITH_ARG) { EMSG("Unknown SMC 0x%" PRIx64, (uint64_t)smc_args->a0); DMSG("Expected 0x%x\n", OPTEE_SMC_CALL_WITH_ARG); smc_args->a0 = OPTEE_SMC_RETURN_EBADCMD; return; } parg = (uint64_t)smc_args->a1 << 32 | smc_args->a2; /* Check if this region is in static shared space */ if (core_pbuf_is(CORE_MEM_NSEC_SHM, parg, sizeof(struct optee_msg_arg))) { mobj = get_cmd_buffer(parg, &num_params); } else { if (parg & SMALL_PAGE_MASK) { smc_args->a0 = OPTEE_SMC_RETURN_EBADADDR; return; } mobj = map_cmd_buffer(parg, &num_params); } if (!mobj || !ALIGNMENT_IS_OK(parg, struct optee_msg_arg)) { EMSG("Bad arg address 0x%" PRIxPA, parg); smc_args->a0 = OPTEE_SMC_RETURN_EBADADDR; mobj_free(mobj); return; } arg = mobj_get_va(mobj, 0); assert(arg && mobj_is_nonsec(mobj)); /* Enable foreign interrupts for STD calls */ thread_set_foreign_intr(true); switch (arg->cmd) { case OPTEE_MSG_CMD_OPEN_SESSION: entry_open_session(smc_args, arg, num_params); break; case OPTEE_MSG_CMD_CLOSE_SESSION: entry_close_session(smc_args, arg, num_params); break; case OPTEE_MSG_CMD_INVOKE_COMMAND: entry_invoke_command(smc_args, arg, num_params); break; case OPTEE_MSG_CMD_CANCEL: entry_cancel(smc_args, arg, num_params); break; case OPTEE_MSG_CMD_REGISTER_SHM: register_shm(smc_args, arg, num_params); break; case OPTEE_MSG_CMD_UNREGISTER_SHM: unregister_shm(smc_args, arg, num_params); break; default: EMSG("Unknown cmd 0x%x\n", arg->cmd); smc_args->a0 = OPTEE_SMC_RETURN_EBADCMD; } mobj_free(mobj); } static TEE_Result default_mobj_init(void) { shm_mobj = mobj_phys_alloc(default_nsec_shm_paddr, default_nsec_shm_size, SHM_CACHE_ATTRS, CORE_MEM_NSEC_SHM); if (!shm_mobj) panic("Failed to register shared memory"); #ifdef CFG_SECURE_DATA_PATH sdp_mem_mobjs = core_sdp_mem_create_mobjs(); if (!sdp_mem_mobjs) panic("Failed to register SDP memory"); #endif return TEE_SUCCESS; } driver_init_late(default_mobj_init);
null
111
CWE-787
CVE-2019-1010293
// SPDX-License-Identifier: BSD-2-Clause /* * Copyright (c) 2016, Linaro Limited * Copyright (c) 2014, STMicroelectronics International N.V. */ #include <arm.h> #include <assert.h> #include <kernel/panic.h> #include <kernel/spinlock.h> #include <kernel/tee_common.h> #include <kernel/tee_misc.h> #include <kernel/tlb_helpers.h> #include <mm/core_memprot.h> #include <mm/core_mmu.h> #include <mm/mobj.h> #include <mm/pgt_cache.h> #include <mm/tee_mm.h> #include <mm/tee_mmu.h> #include <mm/tee_mmu_types.h> #include <mm/tee_pager.h> #include <sm/optee_smc.h> #include <stdlib.h> #include <tee_api_defines_extensions.h> #include <tee_api_types.h> #include <trace.h> #include <types_ext.h> #include <user_ta_header.h> #include <util.h> #ifdef CFG_PL310 #include <kernel/tee_l2cc_mutex.h> #endif #define TEE_MMU_UDATA_ATTR (TEE_MATTR_VALID_BLOCK | \ TEE_MATTR_PRW | TEE_MATTR_URW | \ TEE_MATTR_SECURE) #define TEE_MMU_UCODE_ATTR (TEE_MATTR_VALID_BLOCK | \ TEE_MATTR_PRW | TEE_MATTR_URWX | \ TEE_MATTR_SECURE) #define TEE_MMU_UCACHE_DEFAULT_ATTR (TEE_MATTR_CACHE_CACHED << \ TEE_MATTR_CACHE_SHIFT) static vaddr_t select_va_in_range(vaddr_t prev_end, uint32_t prev_attr, vaddr_t next_begin, uint32_t next_attr, const struct vm_region *reg) { size_t granul; const uint32_t a = TEE_MATTR_EPHEMERAL | TEE_MATTR_PERMANENT; size_t pad; vaddr_t begin_va; vaddr_t end_va; /* * Insert an unmapped entry to separate regions with differing * TEE_MATTR_EPHEMERAL TEE_MATTR_PERMANENT bits as they never are * to be contiguous with another region. */ if (prev_attr && (prev_attr & a) != (reg->attr & a)) pad = SMALL_PAGE_SIZE; else pad = 0; granul = SMALL_PAGE_SIZE; #ifndef CFG_WITH_LPAE if ((prev_attr & TEE_MATTR_SECURE) != (reg->attr & TEE_MATTR_SECURE)) granul = CORE_MMU_PGDIR_SIZE; #endif begin_va = ROUNDUP(prev_end + pad, granul); if (reg->va) { if (reg->va < begin_va) return 0; begin_va = reg->va; } if (next_attr && (next_attr & a) != (reg->attr & a)) pad = SMALL_PAGE_SIZE; else pad = 0; granul = SMALL_PAGE_SIZE; #ifndef CFG_WITH_LPAE if ((next_attr & TEE_MATTR_SECURE) != (reg->attr & TEE_MATTR_SECURE)) granul = CORE_MMU_PGDIR_SIZE; #endif end_va = ROUNDUP(begin_va + reg->size + pad, granul); if (end_va <= next_begin) { assert(!reg->va || reg->va == begin_va); return begin_va; } return 0; } static size_t get_num_req_pgts(struct user_ta_ctx *utc, vaddr_t *begin, vaddr_t *end) { vaddr_t b; vaddr_t e; if (TAILQ_EMPTY(&utc->vm_info->regions)) { core_mmu_get_user_va_range(&b, NULL); e = b; } else { struct vm_region *r; b = TAILQ_FIRST(&utc->vm_info->regions)->va; r = TAILQ_LAST(&utc->vm_info->regions, vm_region_head); e = r->va + r->size; b = ROUNDDOWN(b, CORE_MMU_PGDIR_SIZE); e = ROUNDUP(e, CORE_MMU_PGDIR_SIZE); } if (begin) *begin = b; if (end) *end = e; return (e - b) >> CORE_MMU_PGDIR_SHIFT; } static TEE_Result alloc_pgt(struct user_ta_ctx *utc) { struct thread_specific_data *tsd __maybe_unused; vaddr_t b; vaddr_t e; size_t ntbl; ntbl = get_num_req_pgts(utc, &b, &e); if (!pgt_check_avail(ntbl)) { EMSG("%zu page tables not available", ntbl); return TEE_ERROR_OUT_OF_MEMORY; } #ifdef CFG_PAGED_USER_TA tsd = thread_get_tsd(); if (&utc->ctx == tsd->ctx) { /* * The supplied utc is the current active utc, allocate the * page tables too as the pager needs to use them soon. */ pgt_alloc(&tsd->pgt_cache, &utc->ctx, b, e - 1); } #endif return TEE_SUCCESS; } static void free_pgt(struct user_ta_ctx *utc, vaddr_t base, size_t size) { struct thread_specific_data *tsd = thread_get_tsd(); struct pgt_cache *pgt_cache = NULL; if (&utc->ctx == tsd->ctx) pgt_cache = &tsd->pgt_cache; pgt_flush_ctx_range(pgt_cache, &utc->ctx, base, base + size); } static TEE_Result umap_add_region(struct vm_info *vmi, struct vm_region *reg) { struct vm_region *r; struct vm_region *prev_r; vaddr_t va_range_base; size_t va_range_size; vaddr_t va; core_mmu_get_user_va_range(&va_range_base, &va_range_size); /* Check alignment, it has to be at least SMALL_PAGE based */ if ((reg->va | reg->size) & SMALL_PAGE_MASK) return TEE_ERROR_ACCESS_CONFLICT; /* Check that the mobj is defined for the entire range */ if ((reg->offset + reg->size) > ROUNDUP(reg->mobj->size, SMALL_PAGE_SIZE)) return TEE_ERROR_BAD_PARAMETERS; prev_r = NULL; TAILQ_FOREACH(r, &vmi->regions, link) { if (TAILQ_FIRST(&vmi->regions) == r) { va = select_va_in_range(va_range_base, 0, r->va, r->attr, reg); if (va) { reg->va = va; TAILQ_INSERT_HEAD(&vmi->regions, reg, link); return TEE_SUCCESS; } } else { va = select_va_in_range(prev_r->va + prev_r->size, prev_r->attr, r->va, r->attr, reg); if (va) { reg->va = va; TAILQ_INSERT_BEFORE(r, reg, link); return TEE_SUCCESS; } } prev_r = r; } r = TAILQ_LAST(&vmi->regions, vm_region_head); if (r) { va = select_va_in_range(r->va + r->size, r->attr, va_range_base + va_range_size, 0, reg); if (va) { reg->va = va; TAILQ_INSERT_TAIL(&vmi->regions, reg, link); return TEE_SUCCESS; } } else { va = select_va_in_range(va_range_base, 0, va_range_base + va_range_size, 0, reg); if (va) { reg->va = va; TAILQ_INSERT_HEAD(&vmi->regions, reg, link); return TEE_SUCCESS; } } return TEE_ERROR_ACCESS_CONFLICT; } TEE_Result vm_map(struct user_ta_ctx *utc, vaddr_t *va, size_t len, uint32_t prot, struct mobj *mobj, size_t offs) { TEE_Result res; struct vm_region *reg = calloc(1, sizeof(*reg)); uint32_t attr = 0; const uint32_t prot_mask = TEE_MATTR_PROT_MASK | TEE_MATTR_PERMANENT | TEE_MATTR_EPHEMERAL; if (!reg) return TEE_ERROR_OUT_OF_MEMORY; if (prot & ~prot_mask) { res = TEE_ERROR_BAD_PARAMETERS; goto err_free_reg; } if (!mobj_is_paged(mobj)) { uint32_t cattr; res = mobj_get_cattr(mobj, &cattr); if (res) goto err_free_reg; attr |= cattr << TEE_MATTR_CACHE_SHIFT; } attr |= TEE_MATTR_VALID_BLOCK; if (mobj_is_secure(mobj)) attr |= TEE_MATTR_SECURE; reg->mobj = mobj; reg->offset = offs; reg->va = *va; reg->size = ROUNDUP(len, SMALL_PAGE_SIZE); reg->attr = attr | prot; res = umap_add_region(utc->vm_info, reg); if (res) goto err_free_reg; res = alloc_pgt(utc); if (res) goto err_rem_reg; if (!(reg->attr & (TEE_MATTR_EPHEMERAL | TEE_MATTR_PERMANENT)) && mobj_is_paged(mobj)) { if (!tee_pager_add_uta_area(utc, reg->va, reg->size)) { res = TEE_ERROR_GENERIC; goto err_rem_reg; } } /* * If the context currently is active set it again to update * the mapping. */ if (thread_get_tsd()->ctx == &utc->ctx) tee_mmu_set_ctx(&utc->ctx); *va = reg->va; return TEE_SUCCESS; err_rem_reg: TAILQ_REMOVE(&utc->vm_info->regions, reg, link); err_free_reg: free(reg); return res; } TEE_Result vm_set_prot(struct user_ta_ctx *utc, vaddr_t va, size_t len, uint32_t prot) { struct vm_region *r; /* * To keep thing simple: specified va and len has to match exactly * with an already registered region. */ TAILQ_FOREACH(r, &utc->vm_info->regions, link) { if (core_is_buffer_intersect(r->va, r->size, va, len)) { if (r->va != va || r->size != len) return TEE_ERROR_BAD_PARAMETERS; if (mobj_is_paged(r->mobj)) { if (!tee_pager_set_uta_area_attr(utc, va, len, prot)) return TEE_ERROR_GENERIC; } else if ((prot & TEE_MATTR_UX) && (r->attr & (TEE_MATTR_UW | TEE_MATTR_PW))) { cache_op_inner(DCACHE_AREA_CLEAN, (void *)va, len); cache_op_inner(ICACHE_AREA_INVALIDATE, (void *)va, len); } r->attr &= ~TEE_MATTR_PROT_MASK; r->attr |= prot & TEE_MATTR_PROT_MASK; return TEE_SUCCESS; } } return TEE_ERROR_ITEM_NOT_FOUND; } static TEE_Result map_kinit(struct user_ta_ctx *utc __maybe_unused) { TEE_Result res; struct mobj *mobj; size_t offs; vaddr_t va; size_t sz; thread_get_user_kcode(&mobj, &offs, &va, &sz); if (sz) { res = vm_map(utc, &va, sz, TEE_MATTR_PRX | TEE_MATTR_PERMANENT, mobj, offs); if (res) return res; } thread_get_user_kdata(&mobj, &offs, &va, &sz); if (sz) return vm_map(utc, &va, sz, TEE_MATTR_PRW | TEE_MATTR_PERMANENT, mobj, offs); return TEE_SUCCESS; } TEE_Result vm_info_init(struct user_ta_ctx *utc) { TEE_Result res; uint32_t asid = asid_alloc(); if (!asid) { DMSG("Failed to allocate ASID"); return TEE_ERROR_GENERIC; } utc->vm_info = calloc(1, sizeof(*utc->vm_info)); if (!utc->vm_info) { asid_free(asid); return TEE_ERROR_OUT_OF_MEMORY; } TAILQ_INIT(&utc->vm_info->regions); utc->vm_info->asid = asid; res = map_kinit(utc); if (res) vm_info_final(utc); return res; } static void umap_remove_region(struct vm_info *vmi, struct vm_region *reg) { TAILQ_REMOVE(&vmi->regions, reg, link); free(reg); } static void clear_param_map(struct user_ta_ctx *utc) { struct vm_region *next_r; struct vm_region *r; TAILQ_FOREACH_SAFE(r, &utc->vm_info->regions, link, next_r) if (r->attr & TEE_MATTR_EPHEMERAL) umap_remove_region(utc->vm_info, r); } static TEE_Result param_mem_to_user_va(struct user_ta_ctx *utc, struct param_mem *mem, void **user_va) { struct vm_region *region; TAILQ_FOREACH(region, &utc->vm_info->regions, link) { vaddr_t va; size_t phys_offs; if (!(region->attr & TEE_MATTR_EPHEMERAL)) continue; if (mem->mobj != region->mobj) continue; if (mem->offs < region->offset) continue; if (mem->offs >= (region->offset + region->size)) continue; phys_offs = mobj_get_phys_offs(mem->mobj, CORE_MMU_USER_PARAM_SIZE); va = region->va + mem->offs + phys_offs - region->offset; *user_va = (void *)va; return TEE_SUCCESS; } return TEE_ERROR_GENERIC; } static int cmp_param_mem(const void *a0, const void *a1) { const struct param_mem *m1 = a1; const struct param_mem *m0 = a0; int ret; /* Make sure that invalid param_mem are placed last in the array */ if (!m0->size && !m1->size) return 0; if (!m0->size) return 1; if (!m1->size) return -1; ret = CMP_TRILEAN(mobj_is_secure(m0->mobj), mobj_is_secure(m1->mobj)); if (ret) return ret; ret = CMP_TRILEAN((vaddr_t)m0->mobj, (vaddr_t)m1->mobj); if (ret) return ret; ret = CMP_TRILEAN(m0->offs, m1->offs); if (ret) return ret; return CMP_TRILEAN(m0->size, m1->size); } TEE_Result tee_mmu_map_param(struct user_ta_ctx *utc, struct tee_ta_param *param, void *param_va[TEE_NUM_PARAMS]) { TEE_Result res = TEE_SUCCESS; size_t n; size_t m; struct param_mem mem[TEE_NUM_PARAMS]; memset(mem, 0, sizeof(mem)); for (n = 0; n < TEE_NUM_PARAMS; n++) { uint32_t param_type = TEE_PARAM_TYPE_GET(param->types, n); size_t phys_offs; if (param_type != TEE_PARAM_TYPE_MEMREF_INPUT && param_type != TEE_PARAM_TYPE_MEMREF_OUTPUT && param_type != TEE_PARAM_TYPE_MEMREF_INOUT) continue; phys_offs = mobj_get_phys_offs(param->u[n].mem.mobj, CORE_MMU_USER_PARAM_SIZE); mem[n].mobj = param->u[n].mem.mobj; mem[n].offs = ROUNDDOWN(phys_offs + param->u[n].mem.offs, CORE_MMU_USER_PARAM_SIZE); mem[n].size = ROUNDUP(phys_offs + param->u[n].mem.offs - mem[n].offs + param->u[n].mem.size, CORE_MMU_USER_PARAM_SIZE); } /* * Sort arguments so size = 0 is last, secure mobjs first, then by * mobj pointer value since those entries can't be merged either, * finally by offset. * * This should result in a list where all mergeable entries are * next to each other and unused/invalid entries are at the end. */ qsort(mem, TEE_NUM_PARAMS, sizeof(struct param_mem), cmp_param_mem); for (n = 1, m = 0; n < TEE_NUM_PARAMS && mem[n].size; n++) { if (mem[n].mobj == mem[m].mobj && (mem[n].offs == (mem[m].offs + mem[m].size) || core_is_buffer_intersect(mem[m].offs, mem[m].size, mem[n].offs, mem[n].size))) { mem[m].size = mem[n].offs + mem[n].size - mem[m].offs; continue; } m++; if (n != m) mem[m] = mem[n]; } /* * We'd like 'm' to be the number of valid entries. Here 'm' is the * index of the last valid entry if the first entry is valid, else * 0. */ if (mem[0].size) m++; /* Clear all the param entries as they can hold old information */ clear_param_map(utc); for (n = 0; n < m; n++) { vaddr_t va = 0; const uint32_t prot = TEE_MATTR_PRW | TEE_MATTR_URW | TEE_MATTR_EPHEMERAL; res = vm_map(utc, &va, mem[n].size, prot, mem[n].mobj, mem[n].offs); if (res) return res; } for (n = 0; n < TEE_NUM_PARAMS; n++) { uint32_t param_type = TEE_PARAM_TYPE_GET(param->types, n); if (param_type != TEE_PARAM_TYPE_MEMREF_INPUT && param_type != TEE_PARAM_TYPE_MEMREF_OUTPUT && param_type != TEE_PARAM_TYPE_MEMREF_INOUT) continue; if (param->u[n].mem.size == 0) continue; res = param_mem_to_user_va(utc, &param->u[n].mem, param_va + n); if (res != TEE_SUCCESS) return res; } return alloc_pgt(utc); } TEE_Result tee_mmu_add_rwmem(struct user_ta_ctx *utc, struct mobj *mobj, vaddr_t *va) { TEE_Result res; struct vm_region *reg = calloc(1, sizeof(*reg)); if (!reg) return TEE_ERROR_OUT_OF_MEMORY; reg->mobj = mobj; reg->offset = 0; reg->va = 0; reg->size = ROUNDUP(mobj->size, SMALL_PAGE_SIZE); if (mobj_is_secure(mobj)) reg->attr = TEE_MATTR_SECURE; else reg->attr = 0; res = umap_add_region(utc->vm_info, reg); if (res) { free(reg); return res; } res = alloc_pgt(utc); if (res) umap_remove_region(utc->vm_info, reg); else *va = reg->va; return res; } void tee_mmu_rem_rwmem(struct user_ta_ctx *utc, struct mobj *mobj, vaddr_t va) { struct vm_region *reg; TAILQ_FOREACH(reg, &utc->vm_info->regions, link) { if (reg->mobj == mobj && reg->va == va) { free_pgt(utc, reg->va, reg->size); umap_remove_region(utc->vm_info, reg); return; } } } void vm_info_final(struct user_ta_ctx *utc) { if (!utc->vm_info) return; /* clear MMU entries to avoid clash when asid is reused */ tlbi_asid(utc->vm_info->asid); asid_free(utc->vm_info->asid); while (!TAILQ_EMPTY(&utc->vm_info->regions)) umap_remove_region(utc->vm_info, TAILQ_FIRST(&utc->vm_info->regions)); free(utc->vm_info); utc->vm_info = NULL; } /* return true only if buffer fits inside TA private memory */ bool tee_mmu_is_vbuf_inside_ta_private(const struct user_ta_ctx *utc, const void *va, size_t size) { struct vm_region *r; TAILQ_FOREACH(r, &utc->vm_info->regions, link) { if (r->attr & (TEE_MATTR_EPHEMERAL | TEE_MATTR_PERMANENT)) continue; if (core_is_buffer_inside(va, size, r->va, r->size)) return true; } return false; } /* return true only if buffer intersects TA private memory */ bool tee_mmu_is_vbuf_intersect_ta_private(const struct user_ta_ctx *utc, const void *va, size_t size) { struct vm_region *r; TAILQ_FOREACH(r, &utc->vm_info->regions, link) { if (r->attr & (TEE_MATTR_EPHEMERAL | TEE_MATTR_PERMANENT)) continue; if (core_is_buffer_intersect(va, size, r->va, r->size)) return true; } return false; } TEE_Result tee_mmu_vbuf_to_mobj_offs(const struct user_ta_ctx *utc, const void *va, size_t size, struct mobj **mobj, size_t *offs) { struct vm_region *r; TAILQ_FOREACH(r, &utc->vm_info->regions, link) { if (!r->mobj) continue; if (core_is_buffer_inside(va, size, r->va, r->size)) { size_t poffs; poffs = mobj_get_phys_offs(r->mobj, CORE_MMU_USER_PARAM_SIZE); *mobj = r->mobj; *offs = (vaddr_t)va - r->va + r->offset - poffs; return TEE_SUCCESS; } } return TEE_ERROR_BAD_PARAMETERS; } static TEE_Result tee_mmu_user_va2pa_attr(const struct user_ta_ctx *utc, void *ua, paddr_t *pa, uint32_t *attr) { struct vm_region *region; TAILQ_FOREACH(region, &utc->vm_info->regions, link) { if (!core_is_buffer_inside(ua, 1, region->va, region->size)) continue; if (pa) { TEE_Result res; paddr_t p; size_t offset; size_t granule; /* * mobj and input user address may each include * a specific offset-in-granule position. * Drop both to get target physical page base * address then apply only user address * offset-in-granule. * Mapping lowest granule is the small page. */ granule = MAX(region->mobj->phys_granule, (size_t)SMALL_PAGE_SIZE); assert(!granule || IS_POWER_OF_TWO(granule)); offset = region->offset + ROUNDDOWN((vaddr_t)ua - region->va, granule); res = mobj_get_pa(region->mobj, offset, granule, &p); if (res != TEE_SUCCESS) return res; *pa = p | ((vaddr_t)ua & (granule - 1)); } if (attr) *attr = region->attr; return TEE_SUCCESS; } return TEE_ERROR_ACCESS_DENIED; } TEE_Result tee_mmu_user_va2pa_helper(const struct user_ta_ctx *utc, void *ua, paddr_t *pa) { return tee_mmu_user_va2pa_attr(utc, ua, pa, NULL); } /* */ TEE_Result tee_mmu_user_pa2va_helper(const struct user_ta_ctx *utc, paddr_t pa, void **va) { TEE_Result res; paddr_t p; struct vm_region *region; TAILQ_FOREACH(region, &utc->vm_info->regions, link) { size_t granule; size_t size; size_t ofs; /* pa2va is expected only for memory tracked through mobj */ if (!region->mobj) continue; /* Physically granulated memory object must be scanned */ granule = region->mobj->phys_granule; assert(!granule || IS_POWER_OF_TWO(granule)); for (ofs = region->offset; ofs < region->size; ofs += size) { if (granule) { /* From current offset to buffer/granule end */ size = granule - (ofs & (granule - 1)); if (size > (region->size - ofs)) size = region->size - ofs; } else size = region->size; res = mobj_get_pa(region->mobj, ofs, granule, &p); if (res != TEE_SUCCESS) return res; if (core_is_buffer_inside(pa, 1, p, size)) { /* Remove region offset (mobj phys offset) */ ofs -= region->offset; /* Get offset-in-granule */ p = pa - p; *va = (void *)(region->va + ofs + (vaddr_t)p); return TEE_SUCCESS; } } } return TEE_ERROR_ACCESS_DENIED; } TEE_Result tee_mmu_check_access_rights(const struct user_ta_ctx *utc, uint32_t flags, uaddr_t uaddr, size_t len) { uaddr_t a; size_t addr_incr = MIN(CORE_MMU_USER_CODE_SIZE, CORE_MMU_USER_PARAM_SIZE); if (ADD_OVERFLOW(uaddr, len, &a)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_NONSECURE) && (flags & TEE_MEMORY_ACCESS_SECURE)) return TEE_ERROR_ACCESS_DENIED; /* * Rely on TA private memory test to check if address range is private * to TA or not. */ if (!(flags & TEE_MEMORY_ACCESS_ANY_OWNER) && !tee_mmu_is_vbuf_inside_ta_private(utc, (void *)uaddr, len)) return TEE_ERROR_ACCESS_DENIED; for (a = uaddr; a < (uaddr + len); a += addr_incr) { uint32_t attr; TEE_Result res; res = tee_mmu_user_va2pa_attr(utc, (void *)a, NULL, &attr); if (res != TEE_SUCCESS) return res; if ((flags & TEE_MEMORY_ACCESS_NONSECURE) && (attr & TEE_MATTR_SECURE)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_SECURE) && !(attr & TEE_MATTR_SECURE)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_WRITE) && !(attr & TEE_MATTR_UW)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_READ) && !(attr & TEE_MATTR_UR)) return TEE_ERROR_ACCESS_DENIED; } return TEE_SUCCESS; } void tee_mmu_set_ctx(struct tee_ta_ctx *ctx) { struct thread_specific_data *tsd = thread_get_tsd(); core_mmu_set_user_map(NULL); /* * No matter what happens below, the current user TA will not be * current any longer. Make sure pager is in sync with that. * This function has to be called before there's a chance that * pgt_free_unlocked() is called. * * Save translation tables in a cache if it's a user TA. */ pgt_free(&tsd->pgt_cache, tsd->ctx && is_user_ta_ctx(tsd->ctx)); if (ctx && is_user_ta_ctx(ctx)) { struct core_mmu_user_map map; struct user_ta_ctx *utc = to_user_ta_ctx(ctx); core_mmu_create_user_map(utc, &map); core_mmu_set_user_map(&map); tee_pager_assign_uta_tables(utc); } tsd->ctx = ctx; } struct tee_ta_ctx *tee_mmu_get_ctx(void) { return thread_get_tsd()->ctx; } void teecore_init_ta_ram(void) { vaddr_t s; vaddr_t e; paddr_t ps; paddr_t pe; /* get virtual addr/size of RAM where TA are loaded/executedNSec * shared mem allcated from teecore */ core_mmu_get_mem_by_type(MEM_AREA_TA_RAM, &s, &e); ps = virt_to_phys((void *)s); pe = virt_to_phys((void *)(e - 1)) + 1; if (!ps || (ps & CORE_MMU_USER_CODE_MASK) || !pe || (pe & CORE_MMU_USER_CODE_MASK)) panic("invalid TA RAM"); /* extra check: we could rely on core_mmu_get_mem_by_type() */ if (!tee_pbuf_is_sec(ps, pe - ps)) panic("TA RAM is not secure"); if (!tee_mm_is_empty(&tee_mm_sec_ddr)) panic("TA RAM pool is not empty"); /* remove previous config and init TA ddr memory pool */ tee_mm_final(&tee_mm_sec_ddr); tee_mm_init(&tee_mm_sec_ddr, ps, pe, CORE_MMU_USER_CODE_SHIFT, TEE_MM_POOL_NO_FLAGS); } void teecore_init_pub_ram(void) { vaddr_t s; vaddr_t e; /* get virtual addr/size of NSec shared mem allcated from teecore */ core_mmu_get_mem_by_type(MEM_AREA_NSEC_SHM, &s, &e); if (s >= e || s & SMALL_PAGE_MASK || e & SMALL_PAGE_MASK) panic("invalid PUB RAM"); /* extra check: we could rely on core_mmu_get_mem_by_type() */ if (!tee_vbuf_is_non_sec(s, e - s)) panic("PUB RAM is not non-secure"); #ifdef CFG_PL310 /* Allocate statically the l2cc mutex */ tee_l2cc_store_mutex_boot_pa(virt_to_phys((void *)s)); s += sizeof(uint32_t); /* size of a pl310 mutex */ s = ROUNDUP(s, SMALL_PAGE_SIZE); /* keep required alignment */ #endif default_nsec_shm_paddr = virt_to_phys((void *)s); default_nsec_shm_size = e - s; } uint32_t tee_mmu_user_get_cache_attr(struct user_ta_ctx *utc, void *va) { uint32_t attr; if (tee_mmu_user_va2pa_attr(utc, va, NULL, &attr) != TEE_SUCCESS) panic("cannot get attr"); return (attr >> TEE_MATTR_CACHE_SHIFT) & TEE_MATTR_CACHE_MASK; }
null
// SPDX-License-Identifier: BSD-2-Clause /* * Copyright (c) 2016, Linaro Limited * Copyright (c) 2014, STMicroelectronics International N.V. */ #include <arm.h> #include <assert.h> #include <kernel/panic.h> #include <kernel/spinlock.h> #include <kernel/tee_common.h> #include <kernel/tee_misc.h> #include <kernel/tlb_helpers.h> #include <mm/core_memprot.h> #include <mm/core_mmu.h> #include <mm/mobj.h> #include <mm/pgt_cache.h> #include <mm/tee_mm.h> #include <mm/tee_mmu.h> #include <mm/tee_mmu_types.h> #include <mm/tee_pager.h> #include <sm/optee_smc.h> #include <stdlib.h> #include <tee_api_defines_extensions.h> #include <tee_api_types.h> #include <trace.h> #include <types_ext.h> #include <user_ta_header.h> #include <util.h> #ifdef CFG_PL310 #include <kernel/tee_l2cc_mutex.h> #endif #define TEE_MMU_UDATA_ATTR (TEE_MATTR_VALID_BLOCK | \ TEE_MATTR_PRW | TEE_MATTR_URW | \ TEE_MATTR_SECURE) #define TEE_MMU_UCODE_ATTR (TEE_MATTR_VALID_BLOCK | \ TEE_MATTR_PRW | TEE_MATTR_URWX | \ TEE_MATTR_SECURE) #define TEE_MMU_UCACHE_DEFAULT_ATTR (TEE_MATTR_CACHE_CACHED << \ TEE_MATTR_CACHE_SHIFT) static vaddr_t select_va_in_range(vaddr_t prev_end, uint32_t prev_attr, vaddr_t next_begin, uint32_t next_attr, const struct vm_region *reg) { size_t granul; const uint32_t a = TEE_MATTR_EPHEMERAL | TEE_MATTR_PERMANENT; size_t pad; vaddr_t begin_va; vaddr_t end_va; /* * Insert an unmapped entry to separate regions with differing * TEE_MATTR_EPHEMERAL TEE_MATTR_PERMANENT bits as they never are * to be contiguous with another region. */ if (prev_attr && (prev_attr & a) != (reg->attr & a)) pad = SMALL_PAGE_SIZE; else pad = 0; granul = SMALL_PAGE_SIZE; #ifndef CFG_WITH_LPAE if ((prev_attr & TEE_MATTR_SECURE) != (reg->attr & TEE_MATTR_SECURE)) granul = CORE_MMU_PGDIR_SIZE; #endif begin_va = ROUNDUP(prev_end + pad, granul); if (reg->va) { if (reg->va < begin_va) return 0; begin_va = reg->va; } if (next_attr && (next_attr & a) != (reg->attr & a)) pad = SMALL_PAGE_SIZE; else pad = 0; granul = SMALL_PAGE_SIZE; #ifndef CFG_WITH_LPAE if ((next_attr & TEE_MATTR_SECURE) != (reg->attr & TEE_MATTR_SECURE)) granul = CORE_MMU_PGDIR_SIZE; #endif end_va = ROUNDUP(begin_va + reg->size + pad, granul); if (end_va <= next_begin) { assert(!reg->va || reg->va == begin_va); return begin_va; } return 0; } static size_t get_num_req_pgts(struct user_ta_ctx *utc, vaddr_t *begin, vaddr_t *end) { vaddr_t b; vaddr_t e; if (TAILQ_EMPTY(&utc->vm_info->regions)) { core_mmu_get_user_va_range(&b, NULL); e = b; } else { struct vm_region *r; b = TAILQ_FIRST(&utc->vm_info->regions)->va; r = TAILQ_LAST(&utc->vm_info->regions, vm_region_head); e = r->va + r->size; b = ROUNDDOWN(b, CORE_MMU_PGDIR_SIZE); e = ROUNDUP(e, CORE_MMU_PGDIR_SIZE); } if (begin) *begin = b; if (end) *end = e; return (e - b) >> CORE_MMU_PGDIR_SHIFT; } static TEE_Result alloc_pgt(struct user_ta_ctx *utc) { struct thread_specific_data *tsd __maybe_unused; vaddr_t b; vaddr_t e; size_t ntbl; ntbl = get_num_req_pgts(utc, &b, &e); if (!pgt_check_avail(ntbl)) { EMSG("%zu page tables not available", ntbl); return TEE_ERROR_OUT_OF_MEMORY; } #ifdef CFG_PAGED_USER_TA tsd = thread_get_tsd(); if (&utc->ctx == tsd->ctx) { /* * The supplied utc is the current active utc, allocate the * page tables too as the pager needs to use them soon. */ pgt_alloc(&tsd->pgt_cache, &utc->ctx, b, e - 1); } #endif return TEE_SUCCESS; } static void free_pgt(struct user_ta_ctx *utc, vaddr_t base, size_t size) { struct thread_specific_data *tsd = thread_get_tsd(); struct pgt_cache *pgt_cache = NULL; if (&utc->ctx == tsd->ctx) pgt_cache = &tsd->pgt_cache; pgt_flush_ctx_range(pgt_cache, &utc->ctx, base, base + size); } static TEE_Result umap_add_region(struct vm_info *vmi, struct vm_region *reg) { struct vm_region *r; struct vm_region *prev_r; vaddr_t va_range_base; size_t va_range_size; vaddr_t va; core_mmu_get_user_va_range(&va_range_base, &va_range_size); /* Check alignment, it has to be at least SMALL_PAGE based */ if ((reg->va | reg->size) & SMALL_PAGE_MASK) return TEE_ERROR_ACCESS_CONFLICT; /* Check that the mobj is defined for the entire range */ if ((reg->offset + reg->size) > ROUNDUP(reg->mobj->size, SMALL_PAGE_SIZE)) return TEE_ERROR_BAD_PARAMETERS; prev_r = NULL; TAILQ_FOREACH(r, &vmi->regions, link) { if (TAILQ_FIRST(&vmi->regions) == r) { va = select_va_in_range(va_range_base, 0, r->va, r->attr, reg); if (va) { reg->va = va; TAILQ_INSERT_HEAD(&vmi->regions, reg, link); return TEE_SUCCESS; } } else { va = select_va_in_range(prev_r->va + prev_r->size, prev_r->attr, r->va, r->attr, reg); if (va) { reg->va = va; TAILQ_INSERT_BEFORE(r, reg, link); return TEE_SUCCESS; } } prev_r = r; } r = TAILQ_LAST(&vmi->regions, vm_region_head); if (r) { va = select_va_in_range(r->va + r->size, r->attr, va_range_base + va_range_size, 0, reg); if (va) { reg->va = va; TAILQ_INSERT_TAIL(&vmi->regions, reg, link); return TEE_SUCCESS; } } else { va = select_va_in_range(va_range_base, 0, va_range_base + va_range_size, 0, reg); if (va) { reg->va = va; TAILQ_INSERT_HEAD(&vmi->regions, reg, link); return TEE_SUCCESS; } } return TEE_ERROR_ACCESS_CONFLICT; } TEE_Result vm_map(struct user_ta_ctx *utc, vaddr_t *va, size_t len, uint32_t prot, struct mobj *mobj, size_t offs) { TEE_Result res; struct vm_region *reg = calloc(1, sizeof(*reg)); uint32_t attr = 0; const uint32_t prot_mask = TEE_MATTR_PROT_MASK | TEE_MATTR_PERMANENT | TEE_MATTR_EPHEMERAL; if (!reg) return TEE_ERROR_OUT_OF_MEMORY; if (prot & ~prot_mask) { res = TEE_ERROR_BAD_PARAMETERS; goto err_free_reg; } if (!mobj_is_paged(mobj)) { uint32_t cattr; res = mobj_get_cattr(mobj, &cattr); if (res) goto err_free_reg; attr |= cattr << TEE_MATTR_CACHE_SHIFT; } attr |= TEE_MATTR_VALID_BLOCK; if (mobj_is_secure(mobj)) attr |= TEE_MATTR_SECURE; reg->mobj = mobj; reg->offset = offs; reg->va = *va; reg->size = ROUNDUP(len, SMALL_PAGE_SIZE); reg->attr = attr | prot; res = umap_add_region(utc->vm_info, reg); if (res) goto err_free_reg; res = alloc_pgt(utc); if (res) goto err_rem_reg; if (!(reg->attr & (TEE_MATTR_EPHEMERAL | TEE_MATTR_PERMANENT)) && mobj_is_paged(mobj)) { if (!tee_pager_add_uta_area(utc, reg->va, reg->size)) { res = TEE_ERROR_GENERIC; goto err_rem_reg; } } /* * If the context currently is active set it again to update * the mapping. */ if (thread_get_tsd()->ctx == &utc->ctx) tee_mmu_set_ctx(&utc->ctx); *va = reg->va; return TEE_SUCCESS; err_rem_reg: TAILQ_REMOVE(&utc->vm_info->regions, reg, link); err_free_reg: free(reg); return res; } TEE_Result vm_set_prot(struct user_ta_ctx *utc, vaddr_t va, size_t len, uint32_t prot) { struct vm_region *r; /* * To keep thing simple: specified va and len has to match exactly * with an already registered region. */ TAILQ_FOREACH(r, &utc->vm_info->regions, link) { if (core_is_buffer_intersect(r->va, r->size, va, len)) { if (r->va != va || r->size != len) return TEE_ERROR_BAD_PARAMETERS; if (mobj_is_paged(r->mobj)) { if (!tee_pager_set_uta_area_attr(utc, va, len, prot)) return TEE_ERROR_GENERIC; } else if ((prot & TEE_MATTR_UX) && (r->attr & (TEE_MATTR_UW | TEE_MATTR_PW))) { cache_op_inner(DCACHE_AREA_CLEAN, (void *)va, len); cache_op_inner(ICACHE_AREA_INVALIDATE, (void *)va, len); } r->attr &= ~TEE_MATTR_PROT_MASK; r->attr |= prot & TEE_MATTR_PROT_MASK; return TEE_SUCCESS; } } return TEE_ERROR_ITEM_NOT_FOUND; } static TEE_Result map_kinit(struct user_ta_ctx *utc __maybe_unused) { TEE_Result res; struct mobj *mobj; size_t offs; vaddr_t va; size_t sz; thread_get_user_kcode(&mobj, &offs, &va, &sz); if (sz) { res = vm_map(utc, &va, sz, TEE_MATTR_PRX | TEE_MATTR_PERMANENT, mobj, offs); if (res) return res; } thread_get_user_kdata(&mobj, &offs, &va, &sz); if (sz) return vm_map(utc, &va, sz, TEE_MATTR_PRW | TEE_MATTR_PERMANENT, mobj, offs); return TEE_SUCCESS; } TEE_Result vm_info_init(struct user_ta_ctx *utc) { TEE_Result res; uint32_t asid = asid_alloc(); if (!asid) { DMSG("Failed to allocate ASID"); return TEE_ERROR_GENERIC; } utc->vm_info = calloc(1, sizeof(*utc->vm_info)); if (!utc->vm_info) { asid_free(asid); return TEE_ERROR_OUT_OF_MEMORY; } TAILQ_INIT(&utc->vm_info->regions); utc->vm_info->asid = asid; res = map_kinit(utc); if (res) vm_info_final(utc); return res; } static void umap_remove_region(struct vm_info *vmi, struct vm_region *reg) { TAILQ_REMOVE(&vmi->regions, reg, link); free(reg); } static void clear_param_map(struct user_ta_ctx *utc) { struct vm_region *next_r; struct vm_region *r; TAILQ_FOREACH_SAFE(r, &utc->vm_info->regions, link, next_r) if (r->attr & TEE_MATTR_EPHEMERAL) umap_remove_region(utc->vm_info, r); } static TEE_Result param_mem_to_user_va(struct user_ta_ctx *utc, struct param_mem *mem, void **user_va) { struct vm_region *region; TAILQ_FOREACH(region, &utc->vm_info->regions, link) { vaddr_t va; size_t phys_offs; if (!(region->attr & TEE_MATTR_EPHEMERAL)) continue; if (mem->mobj != region->mobj) continue; if (mem->offs < region->offset) continue; if (mem->offs >= (region->offset + region->size)) continue; phys_offs = mobj_get_phys_offs(mem->mobj, CORE_MMU_USER_PARAM_SIZE); va = region->va + mem->offs + phys_offs - region->offset; *user_va = (void *)va; return TEE_SUCCESS; } return TEE_ERROR_GENERIC; } static int cmp_param_mem(const void *a0, const void *a1) { const struct param_mem *m1 = a1; const struct param_mem *m0 = a0; int ret; /* Make sure that invalid param_mem are placed last in the array */ if (!m0->size && !m1->size) return 0; if (!m0->size) return 1; if (!m1->size) return -1; ret = CMP_TRILEAN(mobj_is_secure(m0->mobj), mobj_is_secure(m1->mobj)); if (ret) return ret; ret = CMP_TRILEAN((vaddr_t)m0->mobj, (vaddr_t)m1->mobj); if (ret) return ret; ret = CMP_TRILEAN(m0->offs, m1->offs); if (ret) return ret; return CMP_TRILEAN(m0->size, m1->size); } TEE_Result tee_mmu_map_param(struct user_ta_ctx *utc, struct tee_ta_param *param, void *param_va[TEE_NUM_PARAMS]) { TEE_Result res = TEE_SUCCESS; size_t n; size_t m; struct param_mem mem[TEE_NUM_PARAMS]; memset(mem, 0, sizeof(mem)); for (n = 0; n < TEE_NUM_PARAMS; n++) { uint32_t param_type = TEE_PARAM_TYPE_GET(param->types, n); size_t phys_offs; if (param_type != TEE_PARAM_TYPE_MEMREF_INPUT && param_type != TEE_PARAM_TYPE_MEMREF_OUTPUT && param_type != TEE_PARAM_TYPE_MEMREF_INOUT) continue; phys_offs = mobj_get_phys_offs(param->u[n].mem.mobj, CORE_MMU_USER_PARAM_SIZE); mem[n].mobj = param->u[n].mem.mobj; mem[n].offs = ROUNDDOWN(phys_offs + param->u[n].mem.offs, CORE_MMU_USER_PARAM_SIZE); mem[n].size = ROUNDUP(phys_offs + param->u[n].mem.offs - mem[n].offs + param->u[n].mem.size, CORE_MMU_USER_PARAM_SIZE); } /* * Sort arguments so size = 0 is last, secure mobjs first, then by * mobj pointer value since those entries can't be merged either, * finally by offset. * * This should result in a list where all mergeable entries are * next to each other and unused/invalid entries are at the end. */ qsort(mem, TEE_NUM_PARAMS, sizeof(struct param_mem), cmp_param_mem); for (n = 1, m = 0; n < TEE_NUM_PARAMS && mem[n].size; n++) { if (mem[n].mobj == mem[m].mobj && (mem[n].offs == (mem[m].offs + mem[m].size) || core_is_buffer_intersect(mem[m].offs, mem[m].size, mem[n].offs, mem[n].size))) { mem[m].size = mem[n].offs + mem[n].size - mem[m].offs; continue; } m++; if (n != m) mem[m] = mem[n]; } /* * We'd like 'm' to be the number of valid entries. Here 'm' is the * index of the last valid entry if the first entry is valid, else * 0. */ if (mem[0].size) m++; /* Clear all the param entries as they can hold old information */ clear_param_map(utc); for (n = 0; n < m; n++) { vaddr_t va = 0; const uint32_t prot = TEE_MATTR_PRW | TEE_MATTR_URW | TEE_MATTR_EPHEMERAL; res = vm_map(utc, &va, mem[n].size, prot, mem[n].mobj, mem[n].offs); if (res) return res; } for (n = 0; n < TEE_NUM_PARAMS; n++) { uint32_t param_type = TEE_PARAM_TYPE_GET(param->types, n); if (param_type != TEE_PARAM_TYPE_MEMREF_INPUT && param_type != TEE_PARAM_TYPE_MEMREF_OUTPUT && param_type != TEE_PARAM_TYPE_MEMREF_INOUT) continue; if (param->u[n].mem.size == 0) continue; res = param_mem_to_user_va(utc, &param->u[n].mem, param_va + n); if (res != TEE_SUCCESS) return res; } return alloc_pgt(utc); } TEE_Result tee_mmu_add_rwmem(struct user_ta_ctx *utc, struct mobj *mobj, vaddr_t *va) { TEE_Result res; struct vm_region *reg = calloc(1, sizeof(*reg)); if (!reg) return TEE_ERROR_OUT_OF_MEMORY; reg->mobj = mobj; reg->offset = 0; reg->va = 0; reg->size = ROUNDUP(mobj->size, SMALL_PAGE_SIZE); if (mobj_is_secure(mobj)) reg->attr = TEE_MATTR_SECURE; else reg->attr = 0; res = umap_add_region(utc->vm_info, reg); if (res) { free(reg); return res; } res = alloc_pgt(utc); if (res) umap_remove_region(utc->vm_info, reg); else *va = reg->va; return res; } void tee_mmu_rem_rwmem(struct user_ta_ctx *utc, struct mobj *mobj, vaddr_t va) { struct vm_region *reg; TAILQ_FOREACH(reg, &utc->vm_info->regions, link) { if (reg->mobj == mobj && reg->va == va) { free_pgt(utc, reg->va, reg->size); umap_remove_region(utc->vm_info, reg); return; } } } void vm_info_final(struct user_ta_ctx *utc) { if (!utc->vm_info) return; /* clear MMU entries to avoid clash when asid is reused */ tlbi_asid(utc->vm_info->asid); asid_free(utc->vm_info->asid); while (!TAILQ_EMPTY(&utc->vm_info->regions)) umap_remove_region(utc->vm_info, TAILQ_FIRST(&utc->vm_info->regions)); free(utc->vm_info); utc->vm_info = NULL; } /* return true only if buffer fits inside TA private memory */ bool tee_mmu_is_vbuf_inside_ta_private(const struct user_ta_ctx *utc, const void *va, size_t size) { struct vm_region *r; TAILQ_FOREACH(r, &utc->vm_info->regions, link) { if (r->attr & (TEE_MATTR_EPHEMERAL | TEE_MATTR_PERMANENT)) continue; if (core_is_buffer_inside(va, size, r->va, r->size)) return true; } return false; } /* return true only if buffer intersects TA private memory */ bool tee_mmu_is_vbuf_intersect_ta_private(const struct user_ta_ctx *utc, const void *va, size_t size) { struct vm_region *r; TAILQ_FOREACH(r, &utc->vm_info->regions, link) { if (r->attr & (TEE_MATTR_EPHEMERAL | TEE_MATTR_PERMANENT)) continue; if (core_is_buffer_intersect(va, size, r->va, r->size)) return true; } return false; } TEE_Result tee_mmu_vbuf_to_mobj_offs(const struct user_ta_ctx *utc, const void *va, size_t size, struct mobj **mobj, size_t *offs) { struct vm_region *r; TAILQ_FOREACH(r, &utc->vm_info->regions, link) { if (!r->mobj) continue; if (core_is_buffer_inside(va, size, r->va, r->size)) { size_t poffs; poffs = mobj_get_phys_offs(r->mobj, CORE_MMU_USER_PARAM_SIZE); *mobj = r->mobj; *offs = (vaddr_t)va - r->va + r->offset - poffs; return TEE_SUCCESS; } } return TEE_ERROR_BAD_PARAMETERS; } static TEE_Result tee_mmu_user_va2pa_attr(const struct user_ta_ctx *utc, void *ua, paddr_t *pa, uint32_t *attr) { struct vm_region *region; TAILQ_FOREACH(region, &utc->vm_info->regions, link) { if (!core_is_buffer_inside(ua, 1, region->va, region->size)) continue; if (pa) { TEE_Result res; paddr_t p; size_t offset; size_t granule; /* * mobj and input user address may each include * a specific offset-in-granule position. * Drop both to get target physical page base * address then apply only user address * offset-in-granule. * Mapping lowest granule is the small page. */ granule = MAX(region->mobj->phys_granule, (size_t)SMALL_PAGE_SIZE); assert(!granule || IS_POWER_OF_TWO(granule)); offset = region->offset + ROUNDDOWN((vaddr_t)ua - region->va, granule); res = mobj_get_pa(region->mobj, offset, granule, &p); if (res != TEE_SUCCESS) return res; *pa = p | ((vaddr_t)ua & (granule - 1)); } if (attr) *attr = region->attr; return TEE_SUCCESS; } return TEE_ERROR_ACCESS_DENIED; } TEE_Result tee_mmu_user_va2pa_helper(const struct user_ta_ctx *utc, void *ua, paddr_t *pa) { return tee_mmu_user_va2pa_attr(utc, ua, pa, NULL); } /* */ TEE_Result tee_mmu_user_pa2va_helper(const struct user_ta_ctx *utc, paddr_t pa, void **va) { TEE_Result res; paddr_t p; struct vm_region *region; TAILQ_FOREACH(region, &utc->vm_info->regions, link) { size_t granule; size_t size; size_t ofs; /* pa2va is expected only for memory tracked through mobj */ if (!region->mobj) continue; /* Physically granulated memory object must be scanned */ granule = region->mobj->phys_granule; assert(!granule || IS_POWER_OF_TWO(granule)); for (ofs = region->offset; ofs < region->size; ofs += size) { if (granule) { /* From current offset to buffer/granule end */ size = granule - (ofs & (granule - 1)); if (size > (region->size - ofs)) size = region->size - ofs; } else size = region->size; res = mobj_get_pa(region->mobj, ofs, granule, &p); if (res != TEE_SUCCESS) return res; if (core_is_buffer_inside(pa, 1, p, size)) { /* Remove region offset (mobj phys offset) */ ofs -= region->offset; /* Get offset-in-granule */ p = pa - p; *va = (void *)(region->va + ofs + (vaddr_t)p); return TEE_SUCCESS; } } } return TEE_ERROR_ACCESS_DENIED; } TEE_Result tee_mmu_check_access_rights(const struct user_ta_ctx *utc, uint32_t flags, uaddr_t uaddr, size_t len) { uaddr_t a; uaddr_t end_addr = 0; size_t addr_incr = MIN(CORE_MMU_USER_CODE_SIZE, CORE_MMU_USER_PARAM_SIZE); if (ADD_OVERFLOW(uaddr, len, &end_addr)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_NONSECURE) && (flags & TEE_MEMORY_ACCESS_SECURE)) return TEE_ERROR_ACCESS_DENIED; /* * Rely on TA private memory test to check if address range is private * to TA or not. */ if (!(flags & TEE_MEMORY_ACCESS_ANY_OWNER) && !tee_mmu_is_vbuf_inside_ta_private(utc, (void *)uaddr, len)) return TEE_ERROR_ACCESS_DENIED; for (a = ROUNDDOWN(uaddr, addr_incr); a < end_addr; a += addr_incr) { uint32_t attr; TEE_Result res; res = tee_mmu_user_va2pa_attr(utc, (void *)a, NULL, &attr); if (res != TEE_SUCCESS) return res; if ((flags & TEE_MEMORY_ACCESS_NONSECURE) && (attr & TEE_MATTR_SECURE)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_SECURE) && !(attr & TEE_MATTR_SECURE)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_WRITE) && !(attr & TEE_MATTR_UW)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_READ) && !(attr & TEE_MATTR_UR)) return TEE_ERROR_ACCESS_DENIED; } return TEE_SUCCESS; } void tee_mmu_set_ctx(struct tee_ta_ctx *ctx) { struct thread_specific_data *tsd = thread_get_tsd(); core_mmu_set_user_map(NULL); /* * No matter what happens below, the current user TA will not be * current any longer. Make sure pager is in sync with that. * This function has to be called before there's a chance that * pgt_free_unlocked() is called. * * Save translation tables in a cache if it's a user TA. */ pgt_free(&tsd->pgt_cache, tsd->ctx && is_user_ta_ctx(tsd->ctx)); if (ctx && is_user_ta_ctx(ctx)) { struct core_mmu_user_map map; struct user_ta_ctx *utc = to_user_ta_ctx(ctx); core_mmu_create_user_map(utc, &map); core_mmu_set_user_map(&map); tee_pager_assign_uta_tables(utc); } tsd->ctx = ctx; } struct tee_ta_ctx *tee_mmu_get_ctx(void) { return thread_get_tsd()->ctx; } void teecore_init_ta_ram(void) { vaddr_t s; vaddr_t e; paddr_t ps; paddr_t pe; /* get virtual addr/size of RAM where TA are loaded/executedNSec * shared mem allcated from teecore */ core_mmu_get_mem_by_type(MEM_AREA_TA_RAM, &s, &e); ps = virt_to_phys((void *)s); pe = virt_to_phys((void *)(e - 1)) + 1; if (!ps || (ps & CORE_MMU_USER_CODE_MASK) || !pe || (pe & CORE_MMU_USER_CODE_MASK)) panic("invalid TA RAM"); /* extra check: we could rely on core_mmu_get_mem_by_type() */ if (!tee_pbuf_is_sec(ps, pe - ps)) panic("TA RAM is not secure"); if (!tee_mm_is_empty(&tee_mm_sec_ddr)) panic("TA RAM pool is not empty"); /* remove previous config and init TA ddr memory pool */ tee_mm_final(&tee_mm_sec_ddr); tee_mm_init(&tee_mm_sec_ddr, ps, pe, CORE_MMU_USER_CODE_SHIFT, TEE_MM_POOL_NO_FLAGS); } void teecore_init_pub_ram(void) { vaddr_t s; vaddr_t e; /* get virtual addr/size of NSec shared mem allcated from teecore */ core_mmu_get_mem_by_type(MEM_AREA_NSEC_SHM, &s, &e); if (s >= e || s & SMALL_PAGE_MASK || e & SMALL_PAGE_MASK) panic("invalid PUB RAM"); /* extra check: we could rely on core_mmu_get_mem_by_type() */ if (!tee_vbuf_is_non_sec(s, e - s)) panic("PUB RAM is not non-secure"); #ifdef CFG_PL310 /* Allocate statically the l2cc mutex */ tee_l2cc_store_mutex_boot_pa(virt_to_phys((void *)s)); s += sizeof(uint32_t); /* size of a pl310 mutex */ s = ROUNDUP(s, SMALL_PAGE_SIZE); /* keep required alignment */ #endif default_nsec_shm_paddr = virt_to_phys((void *)s); default_nsec_shm_size = e - s; } uint32_t tee_mmu_user_get_cache_attr(struct user_ta_ctx *utc, void *va) { uint32_t attr; if (tee_mmu_user_va2pa_attr(utc, va, NULL, &attr) != TEE_SUCCESS) panic("cannot get attr"); return (attr >> TEE_MATTR_CACHE_SHIFT) & TEE_MATTR_CACHE_MASK; }
null
112
CWE-787
CVE-2019-1010295
// SPDX-License-Identifier: BSD-2-Clause /* * Copyright (c) 2014, STMicroelectronics International N.V. */ #include <util.h> #include <kernel/tee_common_otp.h> #include <kernel/tee_common.h> #include <tee_api_types.h> #include <kernel/tee_ta_manager.h> #include <utee_types.h> #include <tee/tee_svc.h> #include <tee/tee_cryp_utl.h> #include <mm/tee_mmu.h> #include <mm/tee_mm.h> #include <mm/core_memprot.h> #include <kernel/tee_time.h> #include <user_ta_header.h> #include <trace.h> #include <kernel/trace_ta.h> #include <kernel/chip_services.h> #include <kernel/pseudo_ta.h> #include <mm/mobj.h> vaddr_t tee_svc_uref_base; void syscall_log(const void *buf __maybe_unused, size_t len __maybe_unused) { #ifdef CFG_TEE_CORE_TA_TRACE char *kbuf; if (len == 0) return; kbuf = malloc(len + 1); if (kbuf == NULL) return; if (tee_svc_copy_from_user(kbuf, buf, len) == TEE_SUCCESS) { kbuf[len] = '\0'; trace_ext_puts(kbuf); } free(kbuf); #endif } TEE_Result syscall_not_supported(void) { return TEE_ERROR_NOT_SUPPORTED; } /* Configuration properties */ /* API implementation version */ static const char api_vers[] = TO_STR(CFG_TEE_API_VERSION); /* Implementation description (implementation-dependent) */ static const char descr[] = TO_STR(CFG_TEE_IMPL_DESCR); /* * TA persistent time protection level * 100: Persistent time based on an REE-controlled real-time clock * and on the TEE Trusted Storage for the storage of origins (default). * 1000: Persistent time based on a TEE-controlled real-time clock * and the TEE Trusted Storage. * The real-time clock MUST be out of reach of software attacks * from the REE. */ static const uint32_t ta_time_prot_lvl = 100; /* Elliptic Curve Cryptographic support */ #ifdef CFG_CRYPTO_ECC static const bool crypto_ecc_en = 1; #else static const bool crypto_ecc_en; #endif /* * Trusted storage anti rollback protection level * 0 (or missing): No antirollback protection (default) * 100: Antirollback enforced at REE level * 1000: Antirollback TEE-controlled hardware */ #ifdef CFG_RPMB_FS static const uint32_t ts_antiroll_prot_lvl = 1000; #else static const uint32_t ts_antiroll_prot_lvl; #endif /* Trusted OS implementation version */ static const char trustedos_impl_version[] = TO_STR(TEE_IMPL_VERSION); /* Trusted OS implementation version (binary value) */ static const uint32_t trustedos_impl_bin_version; /* 0 by default */ /* Trusted OS implementation manufacturer name */ static const char trustedos_manufacturer[] = TO_STR(CFG_TEE_MANUFACTURER); /* Trusted firmware version */ static const char fw_impl_version[] = TO_STR(CFG_TEE_FW_IMPL_VERSION); /* Trusted firmware version (binary value) */ static const uint32_t fw_impl_bin_version; /* 0 by default */ /* Trusted firmware manufacturer name */ static const char fw_manufacturer[] = TO_STR(CFG_TEE_FW_MANUFACTURER); static TEE_Result get_prop_tee_dev_id(struct tee_ta_session *sess __unused, void *buf, size_t *blen) { TEE_Result res; TEE_UUID uuid; const size_t nslen = 5; uint8_t data[5 + FVR_DIE_ID_NUM_REGS * sizeof(uint32_t)] = { 'O', 'P', 'T', 'E', 'E' }; if (*blen < sizeof(uuid)) { *blen = sizeof(uuid); return TEE_ERROR_SHORT_BUFFER; } *blen = sizeof(uuid); if (tee_otp_get_die_id(data + nslen, sizeof(data) - nslen)) return TEE_ERROR_BAD_STATE; res = tee_hash_createdigest(TEE_ALG_SHA256, data, sizeof(data), (uint8_t *)&uuid, sizeof(uuid)); if (res != TEE_SUCCESS) return TEE_ERROR_BAD_STATE; /* * Changes the random value into and UUID as specifiec * in RFC 4122. The magic values are from the example * code in the RFC. * * TEE_UUID is defined slightly different from the RFC, * but close enough for our purpose. */ uuid.timeHiAndVersion &= 0x0fff; uuid.timeHiAndVersion |= 5 << 12; /* uuid.clock_seq_hi_and_reserved in the RFC */ uuid.clockSeqAndNode[0] &= 0x3f; uuid.clockSeqAndNode[0] |= 0x80; return tee_svc_copy_to_user(buf, &uuid, sizeof(TEE_UUID)); } static TEE_Result get_prop_tee_sys_time_prot_level( struct tee_ta_session *sess __unused, void *buf, size_t *blen) { uint32_t prot; if (*blen < sizeof(prot)) { *blen = sizeof(prot); return TEE_ERROR_SHORT_BUFFER; } *blen = sizeof(prot); prot = tee_time_get_sys_time_protection_level(); return tee_svc_copy_to_user(buf, &prot, sizeof(prot)); } static TEE_Result get_prop_client_id(struct tee_ta_session *sess __unused, void *buf, size_t *blen) { if (*blen < sizeof(TEE_Identity)) { *blen = sizeof(TEE_Identity); return TEE_ERROR_SHORT_BUFFER; } *blen = sizeof(TEE_Identity); return tee_svc_copy_to_user(buf, &sess->clnt_id, sizeof(TEE_Identity)); } static TEE_Result get_prop_ta_app_id(struct tee_ta_session *sess, void *buf, size_t *blen) { if (*blen < sizeof(TEE_UUID)) { *blen = sizeof(TEE_UUID); return TEE_ERROR_SHORT_BUFFER; } *blen = sizeof(TEE_UUID); return tee_svc_copy_to_user(buf, &sess->ctx->uuid, sizeof(TEE_UUID)); } /* Properties of the set TEE_PROPSET_CURRENT_CLIENT */ const struct tee_props tee_propset_client[] = { { .name = "gpd.client.identity", .prop_type = USER_TA_PROP_TYPE_IDENTITY, .get_prop_func = get_prop_client_id }, }; /* Properties of the set TEE_PROPSET_CURRENT_TA */ const struct tee_props tee_propset_ta[] = { { .name = "gpd.ta.appID", .prop_type = USER_TA_PROP_TYPE_UUID, .get_prop_func = get_prop_ta_app_id }, /* * Following properties are processed directly in libutee: * TA_PROP_STR_SINGLE_INSTANCE * TA_PROP_STR_MULTI_SESSION * TA_PROP_STR_KEEP_ALIVE * TA_PROP_STR_DATA_SIZE * TA_PROP_STR_STACK_SIZE * TA_PROP_STR_VERSION * TA_PROP_STR_DESCRIPTION * USER_TA_PROP_TYPE_STRING, * TA_DESCRIPTION */ }; /* Properties of the set TEE_PROPSET_TEE_IMPLEMENTATION */ const struct tee_props tee_propset_tee[] = { { .name = "gpd.tee.apiversion", .prop_type = USER_TA_PROP_TYPE_STRING, .data = api_vers, .len = sizeof(api_vers), }, { .name = "gpd.tee.description", .prop_type = USER_TA_PROP_TYPE_STRING, .data = descr, .len = sizeof(descr) }, { .name = "gpd.tee.deviceID", .prop_type = USER_TA_PROP_TYPE_UUID, .get_prop_func = get_prop_tee_dev_id }, { .name = "gpd.tee.systemTime.protectionLevel", .prop_type = USER_TA_PROP_TYPE_U32, .get_prop_func = get_prop_tee_sys_time_prot_level }, { .name = "gpd.tee.TAPersistentTime.protectionLevel", .prop_type = USER_TA_PROP_TYPE_U32, .data = &ta_time_prot_lvl, .len = sizeof(ta_time_prot_lvl) }, { .name = "gpd.tee.cryptography.ecc", .prop_type = USER_TA_PROP_TYPE_BOOL, .data = &crypto_ecc_en, .len = sizeof(crypto_ecc_en) }, { .name = "gpd.tee.trustedStorage.antiRollback.protectionLevel", .prop_type = USER_TA_PROP_TYPE_U32, .data = &ts_antiroll_prot_lvl, .len = sizeof(ts_antiroll_prot_lvl) }, { .name = "gpd.tee.trustedos.implementation.version", .prop_type = USER_TA_PROP_TYPE_STRING, .data = trustedos_impl_version, .len = sizeof(trustedos_impl_version) }, { .name = "gpd.tee.trustedos.implementation.binaryversion", .prop_type = USER_TA_PROP_TYPE_U32, .data = &trustedos_impl_bin_version, .len = sizeof(trustedos_impl_bin_version) }, { .name = "gpd.tee.trustedos.manufacturer", .prop_type = USER_TA_PROP_TYPE_STRING, .data = trustedos_manufacturer, .len = sizeof(trustedos_manufacturer) }, { .name = "gpd.tee.firmware.implementation.version", .prop_type = USER_TA_PROP_TYPE_STRING, .data = fw_impl_version, .len = sizeof(fw_impl_version) }, { .name = "gpd.tee.firmware.implementation.binaryversion", .prop_type = USER_TA_PROP_TYPE_U32, .data = &fw_impl_bin_version, .len = sizeof(fw_impl_bin_version) }, { .name = "gpd.tee.firmware.manufacturer", .prop_type = USER_TA_PROP_TYPE_STRING, .data = fw_manufacturer, .len = sizeof(fw_manufacturer) }, /* * Following properties are processed directly in libutee: * gpd.tee.arith.maxBigIntSize */ }; __weak const struct tee_vendor_props vendor_props_client; __weak const struct tee_vendor_props vendor_props_ta; __weak const struct tee_vendor_props vendor_props_tee; static void get_prop_set(unsigned long prop_set, const struct tee_props **props, size_t *size, const struct tee_props **vendor_props, size_t *vendor_size) { if ((TEE_PropSetHandle)prop_set == TEE_PROPSET_CURRENT_CLIENT) { *props = tee_propset_client; *size = ARRAY_SIZE(tee_propset_client); *vendor_props = vendor_props_client.props; *vendor_size = vendor_props_client.len; } else if ((TEE_PropSetHandle)prop_set == TEE_PROPSET_CURRENT_TA) { *props = tee_propset_ta; *size = ARRAY_SIZE(tee_propset_ta); *vendor_props = vendor_props_ta.props; *vendor_size = vendor_props_ta.len; } else if ((TEE_PropSetHandle)prop_set == TEE_PROPSET_TEE_IMPLEMENTATION) { *props = tee_propset_tee; *size = ARRAY_SIZE(tee_propset_tee); *vendor_props = vendor_props_tee.props; *vendor_size = vendor_props_tee.len; } else { *props = NULL; *size = 0; *vendor_props = NULL; *vendor_size = 0; } } static const struct tee_props *get_prop_struct(unsigned long prop_set, unsigned long index) { const struct tee_props *props; const struct tee_props *vendor_props; size_t size; size_t vendor_size; get_prop_set(prop_set, &props, &size, &vendor_props, &vendor_size); if (index < size) return &(props[index]); index -= size; if (index < vendor_size) return &(vendor_props[index]); return NULL; } /* * prop_set is part of TEE_PROPSET_xxx * index is the index in the Property Set to retrieve * if name is not NULL, the name of "index" property is returned * if buf is not NULL, the property is returned */ TEE_Result syscall_get_property(unsigned long prop_set, unsigned long index, void *name, uint32_t *name_len, void *buf, uint32_t *blen, uint32_t *prop_type) { struct tee_ta_session *sess; TEE_Result res; TEE_Result res2; const struct tee_props *prop; uint32_t klen; size_t klen_size; uint32_t elen; prop = get_prop_struct(prop_set, index); if (!prop) return TEE_ERROR_ITEM_NOT_FOUND; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; /* Get the property type */ if (prop_type) { res = tee_svc_copy_to_user(prop_type, &prop->prop_type, sizeof(*prop_type)); if (res != TEE_SUCCESS) return res; } /* Get the property */ if (buf && blen) { res = tee_svc_copy_from_user(&klen, blen, sizeof(klen)); if (res != TEE_SUCCESS) return res; if (prop->get_prop_func) { klen_size = klen; res = prop->get_prop_func(sess, buf, &klen_size); klen = klen_size; res2 = tee_svc_copy_to_user(blen, &klen, sizeof(*blen)); } else { if (klen < prop->len) res = TEE_ERROR_SHORT_BUFFER; else res = tee_svc_copy_to_user(buf, prop->data, prop->len); res2 = tee_svc_copy_to_user(blen, &prop->len, sizeof(*blen)); } if (res2 != TEE_SUCCESS) return res2; if (res != TEE_SUCCESS) return res; } /* Get the property name */ if (name && name_len) { res = tee_svc_copy_from_user(&klen, name_len, sizeof(klen)); if (res != TEE_SUCCESS) return res; elen = strlen(prop->name) + 1; if (klen < elen) res = TEE_ERROR_SHORT_BUFFER; else res = tee_svc_copy_to_user(name, prop->name, elen); res2 = tee_svc_copy_to_user(name_len, &elen, sizeof(*name_len)); if (res2 != TEE_SUCCESS) return res2; if (res != TEE_SUCCESS) return res; } return res; } /* * prop_set is part of TEE_PROPSET_xxx */ TEE_Result syscall_get_property_name_to_index(unsigned long prop_set, void *name, unsigned long name_len, uint32_t *index) { TEE_Result res; struct tee_ta_session *sess; const struct tee_props *props; size_t size; const struct tee_props *vendor_props; size_t vendor_size; char *kname = 0; uint32_t i; get_prop_set(prop_set, &props, &size, &vendor_props, &vendor_size); if (!props) return TEE_ERROR_ITEM_NOT_FOUND; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) goto out; if (!name || !name_len) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } kname = malloc(name_len); if (!kname) return TEE_ERROR_OUT_OF_MEMORY; res = tee_svc_copy_from_user(kname, name, name_len); if (res != TEE_SUCCESS) goto out; kname[name_len - 1] = 0; res = TEE_ERROR_ITEM_NOT_FOUND; for (i = 0; i < size; i++) { if (!strcmp(kname, props[i].name)) { res = tee_svc_copy_to_user(index, &i, sizeof(*index)); goto out; } } for (i = size; i < size + vendor_size; i++) { if (!strcmp(kname, vendor_props[i - size].name)) { res = tee_svc_copy_to_user(index, &i, sizeof(*index)); goto out; } } out: free(kname); return res; } static void utee_param_to_param(struct tee_ta_param *p, struct utee_params *up) { size_t n; uint32_t types = up->types; p->types = types; for (n = 0; n < TEE_NUM_PARAMS; n++) { uintptr_t a = up->vals[n * 2]; size_t b = up->vals[n * 2 + 1]; switch (TEE_PARAM_TYPE_GET(types, n)) { case TEE_PARAM_TYPE_MEMREF_INPUT: case TEE_PARAM_TYPE_MEMREF_OUTPUT: case TEE_PARAM_TYPE_MEMREF_INOUT: p->u[n].mem.mobj = &mobj_virt; p->u[n].mem.offs = a; p->u[n].mem.size = b; break; case TEE_PARAM_TYPE_VALUE_INPUT: case TEE_PARAM_TYPE_VALUE_INOUT: p->u[n].val.a = a; p->u[n].val.b = b; break; default: memset(&p->u[n], 0, sizeof(p->u[n])); break; } } } static TEE_Result alloc_temp_sec_mem(size_t size, struct mobj **mobj, uint8_t **va) { /* Allocate section in secure DDR */ #ifdef CFG_PAGED_USER_TA *mobj = mobj_seccpy_shm_alloc(size); #else *mobj = mobj_mm_alloc(mobj_sec_ddr, size, &tee_mm_sec_ddr); #endif if (!*mobj) return TEE_ERROR_GENERIC; *va = mobj_get_va(*mobj, 0); return TEE_SUCCESS; } /* * TA invokes some TA with parameter. * If some parameters are memory references: * - either the memref is inside TA private RAM: TA is not allowed to expose * its private RAM: use a temporary memory buffer and copy the data. * - or the memref is not in the TA private RAM: * - if the memref was mapped to the TA, TA is allowed to expose it. * - if so, converts memref virtual address into a physical address. */ static TEE_Result tee_svc_copy_param(struct tee_ta_session *sess, struct tee_ta_session *called_sess, struct utee_params *callee_params, struct tee_ta_param *param, void *tmp_buf_va[TEE_NUM_PARAMS], struct mobj **mobj_tmp) { size_t n; TEE_Result res; size_t req_mem = 0; size_t s; uint8_t *dst = 0; bool ta_private_memref[TEE_NUM_PARAMS]; struct user_ta_ctx *utc = to_user_ta_ctx(sess->ctx); void *va; size_t dst_offs; /* fill 'param' input struct with caller params description buffer */ if (!callee_params) { memset(param, 0, sizeof(*param)); } else { res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)callee_params, sizeof(struct utee_params)); if (res != TEE_SUCCESS) return res; utee_param_to_param(param, callee_params); } if (called_sess && is_pseudo_ta_ctx(called_sess->ctx)) { /* pseudo TA borrows the mapping of the calling TA */ return TEE_SUCCESS; } /* All mobj in param are of type MOJB_TYPE_VIRT */ for (n = 0; n < TEE_NUM_PARAMS; n++) { ta_private_memref[n] = false; switch (TEE_PARAM_TYPE_GET(param->types, n)) { case TEE_PARAM_TYPE_MEMREF_INPUT: case TEE_PARAM_TYPE_MEMREF_OUTPUT: case TEE_PARAM_TYPE_MEMREF_INOUT: va = (void *)param->u[n].mem.offs; s = param->u[n].mem.size; if (!va) { if (s) return TEE_ERROR_BAD_PARAMETERS; break; } /* uTA cannot expose its private memory */ if (tee_mmu_is_vbuf_inside_ta_private(utc, va, s)) { s = ROUNDUP(s, sizeof(uint32_t)); if (ADD_OVERFLOW(req_mem, s, &req_mem)) return TEE_ERROR_BAD_PARAMETERS; ta_private_memref[n] = true; break; } res = tee_mmu_vbuf_to_mobj_offs(utc, va, s, &param->u[n].mem.mobj, &param->u[n].mem.offs); if (res != TEE_SUCCESS) return res; break; default: break; } } if (req_mem == 0) return TEE_SUCCESS; res = alloc_temp_sec_mem(req_mem, mobj_tmp, &dst); if (res != TEE_SUCCESS) return res; dst_offs = 0; for (n = 0; n < TEE_NUM_PARAMS; n++) { if (!ta_private_memref[n]) continue; s = ROUNDUP(param->u[n].mem.size, sizeof(uint32_t)); switch (TEE_PARAM_TYPE_GET(param->types, n)) { case TEE_PARAM_TYPE_MEMREF_INPUT: case TEE_PARAM_TYPE_MEMREF_INOUT: va = (void *)param->u[n].mem.offs; if (va) { res = tee_svc_copy_from_user(dst, va, param->u[n].mem.size); if (res != TEE_SUCCESS) return res; param->u[n].mem.offs = dst_offs; param->u[n].mem.mobj = *mobj_tmp; tmp_buf_va[n] = dst; dst += s; dst_offs += s; } break; case TEE_PARAM_TYPE_MEMREF_OUTPUT: va = (void *)param->u[n].mem.offs; if (va) { param->u[n].mem.offs = dst_offs; param->u[n].mem.mobj = *mobj_tmp; tmp_buf_va[n] = dst; dst += s; dst_offs += s; } break; default: continue; } } return TEE_SUCCESS; } /* * Back from execution of service: update parameters passed from TA: * If some parameters were memory references: * - either the memref was temporary: copy back data and update size * - or it was the original TA memref: update only the size value. */ static TEE_Result tee_svc_update_out_param( struct tee_ta_param *param, void *tmp_buf_va[TEE_NUM_PARAMS], struct utee_params *usr_param) { size_t n; uint64_t *vals = usr_param->vals; for (n = 0; n < TEE_NUM_PARAMS; n++) { switch (TEE_PARAM_TYPE_GET(param->types, n)) { case TEE_PARAM_TYPE_MEMREF_OUTPUT: case TEE_PARAM_TYPE_MEMREF_INOUT: /* * Memory copy is only needed if there's a temporary * buffer involved, tmp_buf_va[n] is only update if * a temporary buffer is used. Otherwise only the * size needs to be updated. */ if (tmp_buf_va[n] && param->u[n].mem.size <= vals[n * 2 + 1]) { void *src = tmp_buf_va[n]; void *dst = (void *)(uintptr_t)vals[n * 2]; TEE_Result res; res = tee_svc_copy_to_user(dst, src, param->u[n].mem.size); if (res != TEE_SUCCESS) return res; } usr_param->vals[n * 2 + 1] = param->u[n].mem.size; break; case TEE_PARAM_TYPE_VALUE_OUTPUT: case TEE_PARAM_TYPE_VALUE_INOUT: vals[n * 2] = param->u[n].val.a; vals[n * 2 + 1] = param->u[n].val.b; break; default: continue; } } return TEE_SUCCESS; } /* Called when a TA calls an OpenSession on another TA */ TEE_Result syscall_open_ta_session(const TEE_UUID *dest, unsigned long cancel_req_to, struct utee_params *usr_param, uint32_t *ta_sess, uint32_t *ret_orig) { TEE_Result res; uint32_t ret_o = TEE_ORIGIN_TEE; struct tee_ta_session *s = NULL; struct tee_ta_session *sess; struct mobj *mobj_param = NULL; TEE_UUID *uuid = malloc(sizeof(TEE_UUID)); struct tee_ta_param *param = malloc(sizeof(struct tee_ta_param)); TEE_Identity *clnt_id = malloc(sizeof(TEE_Identity)); void *tmp_buf_va[TEE_NUM_PARAMS] = { NULL }; struct user_ta_ctx *utc; if (uuid == NULL || param == NULL || clnt_id == NULL) { res = TEE_ERROR_OUT_OF_MEMORY; goto out_free_only; } memset(param, 0, sizeof(struct tee_ta_param)); res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) goto out_free_only; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_copy_from_user(uuid, dest, sizeof(TEE_UUID)); if (res != TEE_SUCCESS) goto function_exit; clnt_id->login = TEE_LOGIN_TRUSTED_APP; memcpy(&clnt_id->uuid, &sess->ctx->uuid, sizeof(TEE_UUID)); res = tee_svc_copy_param(sess, NULL, usr_param, param, tmp_buf_va, &mobj_param); if (res != TEE_SUCCESS) goto function_exit; res = tee_ta_open_session(&ret_o, &s, &utc->open_sessions, uuid, clnt_id, cancel_req_to, param); tee_mmu_set_ctx(&utc->ctx); if (res != TEE_SUCCESS) goto function_exit; res = tee_svc_update_out_param(param, tmp_buf_va, usr_param); function_exit: mobj_free(mobj_param); if (res == TEE_SUCCESS) tee_svc_copy_kaddr_to_uref(ta_sess, s); tee_svc_copy_to_user(ret_orig, &ret_o, sizeof(ret_o)); out_free_only: free(param); free(uuid); free(clnt_id); return res; } TEE_Result syscall_close_ta_session(unsigned long ta_sess) { TEE_Result res; struct tee_ta_session *sess; TEE_Identity clnt_id; struct tee_ta_session *s = tee_svc_uref_to_kaddr(ta_sess); struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); clnt_id.login = TEE_LOGIN_TRUSTED_APP; memcpy(&clnt_id.uuid, &sess->ctx->uuid, sizeof(TEE_UUID)); return tee_ta_close_session(s, &utc->open_sessions, &clnt_id); } TEE_Result syscall_invoke_ta_command(unsigned long ta_sess, unsigned long cancel_req_to, unsigned long cmd_id, struct utee_params *usr_param, uint32_t *ret_orig) { TEE_Result res; TEE_Result res2; uint32_t ret_o = TEE_ORIGIN_TEE; struct tee_ta_param param = { 0 }; TEE_Identity clnt_id; struct tee_ta_session *sess; struct tee_ta_session *called_sess; struct mobj *mobj_param = NULL; void *tmp_buf_va[TEE_NUM_PARAMS] = { NULL }; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); called_sess = tee_ta_get_session( (vaddr_t)tee_svc_uref_to_kaddr(ta_sess), true, &utc->open_sessions); if (!called_sess) return TEE_ERROR_BAD_PARAMETERS; clnt_id.login = TEE_LOGIN_TRUSTED_APP; memcpy(&clnt_id.uuid, &sess->ctx->uuid, sizeof(TEE_UUID)); res = tee_svc_copy_param(sess, called_sess, usr_param, &param, tmp_buf_va, &mobj_param); if (res != TEE_SUCCESS) goto function_exit; res = tee_ta_invoke_command(&ret_o, called_sess, &clnt_id, cancel_req_to, cmd_id, &param); res2 = tee_svc_update_out_param(&param, tmp_buf_va, usr_param); if (res2 != TEE_SUCCESS) { /* * Spec for TEE_InvokeTACommand() says: * "If the return origin is different from * TEE_ORIGIN_TRUSTED_APP, then the function has failed * before it could reach the destination Trusted * Application." * * But if we can't update params to the caller we have no * choice we need to return some error to indicate that * parameters aren't updated as expected. */ ret_o = TEE_ORIGIN_TEE; res = res2; } function_exit: tee_ta_put_session(called_sess); mobj_free(mobj_param); if (ret_orig) tee_svc_copy_to_user(ret_orig, &ret_o, sizeof(ret_o)); return res; } TEE_Result syscall_check_access_rights(unsigned long flags, const void *buf, size_t len) { TEE_Result res; struct tee_ta_session *s; res = tee_ta_get_current_session(&s); if (res != TEE_SUCCESS) return res; return tee_mmu_check_access_rights(to_user_ta_ctx(s->ctx), flags, (uaddr_t)buf, len); } TEE_Result tee_svc_copy_from_user(void *kaddr, const void *uaddr, size_t len) { TEE_Result res; struct tee_ta_session *s; res = tee_ta_get_current_session(&s); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(s->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)uaddr, len); if (res != TEE_SUCCESS) return res; memcpy(kaddr, uaddr, len); return TEE_SUCCESS; } TEE_Result tee_svc_copy_to_user(void *uaddr, const void *kaddr, size_t len) { TEE_Result res; struct tee_ta_session *s; res = tee_ta_get_current_session(&s); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(s->ctx), TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)uaddr, len); if (res != TEE_SUCCESS) return res; memcpy(uaddr, kaddr, len); return TEE_SUCCESS; } TEE_Result tee_svc_copy_kaddr_to_uref(uint32_t *uref, void *kaddr) { uint32_t ref = tee_svc_kaddr_to_uref(kaddr); return tee_svc_copy_to_user(uref, &ref, sizeof(ref)); } TEE_Result syscall_get_cancellation_flag(uint32_t *cancel) { TEE_Result res; struct tee_ta_session *s = NULL; uint32_t c; res = tee_ta_get_current_session(&s); if (res != TEE_SUCCESS) return res; c = tee_ta_session_is_cancelled(s, NULL); return tee_svc_copy_to_user(cancel, &c, sizeof(c)); } TEE_Result syscall_unmask_cancellation(uint32_t *old_mask) { TEE_Result res; struct tee_ta_session *s = NULL; uint32_t m; res = tee_ta_get_current_session(&s); if (res != TEE_SUCCESS) return res; m = s->cancel_mask; s->cancel_mask = false; return tee_svc_copy_to_user(old_mask, &m, sizeof(m)); } TEE_Result syscall_mask_cancellation(uint32_t *old_mask) { TEE_Result res; struct tee_ta_session *s = NULL; uint32_t m; res = tee_ta_get_current_session(&s); if (res != TEE_SUCCESS) return res; m = s->cancel_mask; s->cancel_mask = true; return tee_svc_copy_to_user(old_mask, &m, sizeof(m)); } TEE_Result syscall_wait(unsigned long timeout) { TEE_Result res = TEE_SUCCESS; uint32_t mytime = 0; struct tee_ta_session *s; TEE_Time base_time; TEE_Time current_time; res = tee_ta_get_current_session(&s); if (res != TEE_SUCCESS) return res; res = tee_time_get_sys_time(&base_time); if (res != TEE_SUCCESS) return res; while (true) { res = tee_time_get_sys_time(&current_time); if (res != TEE_SUCCESS) return res; if (tee_ta_session_is_cancelled(s, &current_time)) return TEE_ERROR_CANCEL; mytime = (current_time.seconds - base_time.seconds) * 1000 + (int)current_time.millis - (int)base_time.millis; if (mytime >= timeout) return TEE_SUCCESS; tee_time_wait(timeout - mytime); } return res; } TEE_Result syscall_get_time(unsigned long cat, TEE_Time *mytime) { TEE_Result res, res2; struct tee_ta_session *s = NULL; TEE_Time t; res = tee_ta_get_current_session(&s); if (res != TEE_SUCCESS) return res; switch (cat) { case UTEE_TIME_CAT_SYSTEM: res = tee_time_get_sys_time(&t); break; case UTEE_TIME_CAT_TA_PERSISTENT: res = tee_time_get_ta_time((const void *)&s->ctx->uuid, &t); break; case UTEE_TIME_CAT_REE: res = tee_time_get_ree_time(&t); break; default: res = TEE_ERROR_BAD_PARAMETERS; break; } if (res == TEE_SUCCESS || res == TEE_ERROR_OVERFLOW) { res2 = tee_svc_copy_to_user(mytime, &t, sizeof(t)); if (res2 != TEE_SUCCESS) res = res2; } return res; } TEE_Result syscall_set_ta_time(const TEE_Time *mytime) { TEE_Result res; struct tee_ta_session *s = NULL; TEE_Time t; res = tee_ta_get_current_session(&s); if (res != TEE_SUCCESS) return res; res = tee_svc_copy_from_user(&t, mytime, sizeof(t)); if (res != TEE_SUCCESS) return res; return tee_time_set_ta_time((const void *)&s->ctx->uuid, &t); }
null
// SPDX-License-Identifier: BSD-2-Clause /* * Copyright (c) 2014, STMicroelectronics International N.V. */ #include <util.h> #include <kernel/tee_common_otp.h> #include <kernel/tee_common.h> #include <tee_api_types.h> #include <kernel/tee_ta_manager.h> #include <utee_types.h> #include <tee/tee_svc.h> #include <tee/tee_cryp_utl.h> #include <mm/tee_mmu.h> #include <mm/tee_mm.h> #include <mm/core_memprot.h> #include <kernel/tee_time.h> #include <user_ta_header.h> #include <trace.h> #include <kernel/trace_ta.h> #include <kernel/chip_services.h> #include <kernel/pseudo_ta.h> #include <mm/mobj.h> vaddr_t tee_svc_uref_base; void syscall_log(const void *buf __maybe_unused, size_t len __maybe_unused) { #ifdef CFG_TEE_CORE_TA_TRACE char *kbuf; if (len == 0) return; kbuf = malloc(len + 1); if (kbuf == NULL) return; if (tee_svc_copy_from_user(kbuf, buf, len) == TEE_SUCCESS) { kbuf[len] = '\0'; trace_ext_puts(kbuf); } free(kbuf); #endif } TEE_Result syscall_not_supported(void) { return TEE_ERROR_NOT_SUPPORTED; } /* Configuration properties */ /* API implementation version */ static const char api_vers[] = TO_STR(CFG_TEE_API_VERSION); /* Implementation description (implementation-dependent) */ static const char descr[] = TO_STR(CFG_TEE_IMPL_DESCR); /* * TA persistent time protection level * 100: Persistent time based on an REE-controlled real-time clock * and on the TEE Trusted Storage for the storage of origins (default). * 1000: Persistent time based on a TEE-controlled real-time clock * and the TEE Trusted Storage. * The real-time clock MUST be out of reach of software attacks * from the REE. */ static const uint32_t ta_time_prot_lvl = 100; /* Elliptic Curve Cryptographic support */ #ifdef CFG_CRYPTO_ECC static const bool crypto_ecc_en = 1; #else static const bool crypto_ecc_en; #endif /* * Trusted storage anti rollback protection level * 0 (or missing): No antirollback protection (default) * 100: Antirollback enforced at REE level * 1000: Antirollback TEE-controlled hardware */ #ifdef CFG_RPMB_FS static const uint32_t ts_antiroll_prot_lvl = 1000; #else static const uint32_t ts_antiroll_prot_lvl; #endif /* Trusted OS implementation version */ static const char trustedos_impl_version[] = TO_STR(TEE_IMPL_VERSION); /* Trusted OS implementation version (binary value) */ static const uint32_t trustedos_impl_bin_version; /* 0 by default */ /* Trusted OS implementation manufacturer name */ static const char trustedos_manufacturer[] = TO_STR(CFG_TEE_MANUFACTURER); /* Trusted firmware version */ static const char fw_impl_version[] = TO_STR(CFG_TEE_FW_IMPL_VERSION); /* Trusted firmware version (binary value) */ static const uint32_t fw_impl_bin_version; /* 0 by default */ /* Trusted firmware manufacturer name */ static const char fw_manufacturer[] = TO_STR(CFG_TEE_FW_MANUFACTURER); static TEE_Result get_prop_tee_dev_id(struct tee_ta_session *sess __unused, void *buf, size_t *blen) { TEE_Result res; TEE_UUID uuid; const size_t nslen = 5; uint8_t data[5 + FVR_DIE_ID_NUM_REGS * sizeof(uint32_t)] = { 'O', 'P', 'T', 'E', 'E' }; if (*blen < sizeof(uuid)) { *blen = sizeof(uuid); return TEE_ERROR_SHORT_BUFFER; } *blen = sizeof(uuid); if (tee_otp_get_die_id(data + nslen, sizeof(data) - nslen)) return TEE_ERROR_BAD_STATE; res = tee_hash_createdigest(TEE_ALG_SHA256, data, sizeof(data), (uint8_t *)&uuid, sizeof(uuid)); if (res != TEE_SUCCESS) return TEE_ERROR_BAD_STATE; /* * Changes the random value into and UUID as specifiec * in RFC 4122. The magic values are from the example * code in the RFC. * * TEE_UUID is defined slightly different from the RFC, * but close enough for our purpose. */ uuid.timeHiAndVersion &= 0x0fff; uuid.timeHiAndVersion |= 5 << 12; /* uuid.clock_seq_hi_and_reserved in the RFC */ uuid.clockSeqAndNode[0] &= 0x3f; uuid.clockSeqAndNode[0] |= 0x80; return tee_svc_copy_to_user(buf, &uuid, sizeof(TEE_UUID)); } static TEE_Result get_prop_tee_sys_time_prot_level( struct tee_ta_session *sess __unused, void *buf, size_t *blen) { uint32_t prot; if (*blen < sizeof(prot)) { *blen = sizeof(prot); return TEE_ERROR_SHORT_BUFFER; } *blen = sizeof(prot); prot = tee_time_get_sys_time_protection_level(); return tee_svc_copy_to_user(buf, &prot, sizeof(prot)); } static TEE_Result get_prop_client_id(struct tee_ta_session *sess __unused, void *buf, size_t *blen) { if (*blen < sizeof(TEE_Identity)) { *blen = sizeof(TEE_Identity); return TEE_ERROR_SHORT_BUFFER; } *blen = sizeof(TEE_Identity); return tee_svc_copy_to_user(buf, &sess->clnt_id, sizeof(TEE_Identity)); } static TEE_Result get_prop_ta_app_id(struct tee_ta_session *sess, void *buf, size_t *blen) { if (*blen < sizeof(TEE_UUID)) { *blen = sizeof(TEE_UUID); return TEE_ERROR_SHORT_BUFFER; } *blen = sizeof(TEE_UUID); return tee_svc_copy_to_user(buf, &sess->ctx->uuid, sizeof(TEE_UUID)); } /* Properties of the set TEE_PROPSET_CURRENT_CLIENT */ const struct tee_props tee_propset_client[] = { { .name = "gpd.client.identity", .prop_type = USER_TA_PROP_TYPE_IDENTITY, .get_prop_func = get_prop_client_id }, }; /* Properties of the set TEE_PROPSET_CURRENT_TA */ const struct tee_props tee_propset_ta[] = { { .name = "gpd.ta.appID", .prop_type = USER_TA_PROP_TYPE_UUID, .get_prop_func = get_prop_ta_app_id }, /* * Following properties are processed directly in libutee: * TA_PROP_STR_SINGLE_INSTANCE * TA_PROP_STR_MULTI_SESSION * TA_PROP_STR_KEEP_ALIVE * TA_PROP_STR_DATA_SIZE * TA_PROP_STR_STACK_SIZE * TA_PROP_STR_VERSION * TA_PROP_STR_DESCRIPTION * USER_TA_PROP_TYPE_STRING, * TA_DESCRIPTION */ }; /* Properties of the set TEE_PROPSET_TEE_IMPLEMENTATION */ const struct tee_props tee_propset_tee[] = { { .name = "gpd.tee.apiversion", .prop_type = USER_TA_PROP_TYPE_STRING, .data = api_vers, .len = sizeof(api_vers), }, { .name = "gpd.tee.description", .prop_type = USER_TA_PROP_TYPE_STRING, .data = descr, .len = sizeof(descr) }, { .name = "gpd.tee.deviceID", .prop_type = USER_TA_PROP_TYPE_UUID, .get_prop_func = get_prop_tee_dev_id }, { .name = "gpd.tee.systemTime.protectionLevel", .prop_type = USER_TA_PROP_TYPE_U32, .get_prop_func = get_prop_tee_sys_time_prot_level }, { .name = "gpd.tee.TAPersistentTime.protectionLevel", .prop_type = USER_TA_PROP_TYPE_U32, .data = &ta_time_prot_lvl, .len = sizeof(ta_time_prot_lvl) }, { .name = "gpd.tee.cryptography.ecc", .prop_type = USER_TA_PROP_TYPE_BOOL, .data = &crypto_ecc_en, .len = sizeof(crypto_ecc_en) }, { .name = "gpd.tee.trustedStorage.antiRollback.protectionLevel", .prop_type = USER_TA_PROP_TYPE_U32, .data = &ts_antiroll_prot_lvl, .len = sizeof(ts_antiroll_prot_lvl) }, { .name = "gpd.tee.trustedos.implementation.version", .prop_type = USER_TA_PROP_TYPE_STRING, .data = trustedos_impl_version, .len = sizeof(trustedos_impl_version) }, { .name = "gpd.tee.trustedos.implementation.binaryversion", .prop_type = USER_TA_PROP_TYPE_U32, .data = &trustedos_impl_bin_version, .len = sizeof(trustedos_impl_bin_version) }, { .name = "gpd.tee.trustedos.manufacturer", .prop_type = USER_TA_PROP_TYPE_STRING, .data = trustedos_manufacturer, .len = sizeof(trustedos_manufacturer) }, { .name = "gpd.tee.firmware.implementation.version", .prop_type = USER_TA_PROP_TYPE_STRING, .data = fw_impl_version, .len = sizeof(fw_impl_version) }, { .name = "gpd.tee.firmware.implementation.binaryversion", .prop_type = USER_TA_PROP_TYPE_U32, .data = &fw_impl_bin_version, .len = sizeof(fw_impl_bin_version) }, { .name = "gpd.tee.firmware.manufacturer", .prop_type = USER_TA_PROP_TYPE_STRING, .data = fw_manufacturer, .len = sizeof(fw_manufacturer) }, /* * Following properties are processed directly in libutee: * gpd.tee.arith.maxBigIntSize */ }; __weak const struct tee_vendor_props vendor_props_client; __weak const struct tee_vendor_props vendor_props_ta; __weak const struct tee_vendor_props vendor_props_tee; static void get_prop_set(unsigned long prop_set, const struct tee_props **props, size_t *size, const struct tee_props **vendor_props, size_t *vendor_size) { if ((TEE_PropSetHandle)prop_set == TEE_PROPSET_CURRENT_CLIENT) { *props = tee_propset_client; *size = ARRAY_SIZE(tee_propset_client); *vendor_props = vendor_props_client.props; *vendor_size = vendor_props_client.len; } else if ((TEE_PropSetHandle)prop_set == TEE_PROPSET_CURRENT_TA) { *props = tee_propset_ta; *size = ARRAY_SIZE(tee_propset_ta); *vendor_props = vendor_props_ta.props; *vendor_size = vendor_props_ta.len; } else if ((TEE_PropSetHandle)prop_set == TEE_PROPSET_TEE_IMPLEMENTATION) { *props = tee_propset_tee; *size = ARRAY_SIZE(tee_propset_tee); *vendor_props = vendor_props_tee.props; *vendor_size = vendor_props_tee.len; } else { *props = NULL; *size = 0; *vendor_props = NULL; *vendor_size = 0; } } static const struct tee_props *get_prop_struct(unsigned long prop_set, unsigned long index) { const struct tee_props *props; const struct tee_props *vendor_props; size_t size; size_t vendor_size; get_prop_set(prop_set, &props, &size, &vendor_props, &vendor_size); if (index < size) return &(props[index]); index -= size; if (index < vendor_size) return &(vendor_props[index]); return NULL; } /* * prop_set is part of TEE_PROPSET_xxx * index is the index in the Property Set to retrieve * if name is not NULL, the name of "index" property is returned * if buf is not NULL, the property is returned */ TEE_Result syscall_get_property(unsigned long prop_set, unsigned long index, void *name, uint32_t *name_len, void *buf, uint32_t *blen, uint32_t *prop_type) { struct tee_ta_session *sess; TEE_Result res; TEE_Result res2; const struct tee_props *prop; uint32_t klen; size_t klen_size; uint32_t elen; prop = get_prop_struct(prop_set, index); if (!prop) return TEE_ERROR_ITEM_NOT_FOUND; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; /* Get the property type */ if (prop_type) { res = tee_svc_copy_to_user(prop_type, &prop->prop_type, sizeof(*prop_type)); if (res != TEE_SUCCESS) return res; } /* Get the property */ if (buf && blen) { res = tee_svc_copy_from_user(&klen, blen, sizeof(klen)); if (res != TEE_SUCCESS) return res; if (prop->get_prop_func) { klen_size = klen; res = prop->get_prop_func(sess, buf, &klen_size); klen = klen_size; res2 = tee_svc_copy_to_user(blen, &klen, sizeof(*blen)); } else { if (klen < prop->len) res = TEE_ERROR_SHORT_BUFFER; else res = tee_svc_copy_to_user(buf, prop->data, prop->len); res2 = tee_svc_copy_to_user(blen, &prop->len, sizeof(*blen)); } if (res2 != TEE_SUCCESS) return res2; if (res != TEE_SUCCESS) return res; } /* Get the property name */ if (name && name_len) { res = tee_svc_copy_from_user(&klen, name_len, sizeof(klen)); if (res != TEE_SUCCESS) return res; elen = strlen(prop->name) + 1; if (klen < elen) res = TEE_ERROR_SHORT_BUFFER; else res = tee_svc_copy_to_user(name, prop->name, elen); res2 = tee_svc_copy_to_user(name_len, &elen, sizeof(*name_len)); if (res2 != TEE_SUCCESS) return res2; if (res != TEE_SUCCESS) return res; } return res; } /* * prop_set is part of TEE_PROPSET_xxx */ TEE_Result syscall_get_property_name_to_index(unsigned long prop_set, void *name, unsigned long name_len, uint32_t *index) { TEE_Result res; struct tee_ta_session *sess; const struct tee_props *props; size_t size; const struct tee_props *vendor_props; size_t vendor_size; char *kname = 0; uint32_t i; get_prop_set(prop_set, &props, &size, &vendor_props, &vendor_size); if (!props) return TEE_ERROR_ITEM_NOT_FOUND; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) goto out; if (!name || !name_len) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } kname = malloc(name_len); if (!kname) return TEE_ERROR_OUT_OF_MEMORY; res = tee_svc_copy_from_user(kname, name, name_len); if (res != TEE_SUCCESS) goto out; kname[name_len - 1] = 0; res = TEE_ERROR_ITEM_NOT_FOUND; for (i = 0; i < size; i++) { if (!strcmp(kname, props[i].name)) { res = tee_svc_copy_to_user(index, &i, sizeof(*index)); goto out; } } for (i = size; i < size + vendor_size; i++) { if (!strcmp(kname, vendor_props[i - size].name)) { res = tee_svc_copy_to_user(index, &i, sizeof(*index)); goto out; } } out: free(kname); return res; } static TEE_Result utee_param_to_param(struct user_ta_ctx *utc, struct tee_ta_param *p, struct utee_params *up) { size_t n; uint32_t types = up->types; p->types = types; for (n = 0; n < TEE_NUM_PARAMS; n++) { uintptr_t a = up->vals[n * 2]; size_t b = up->vals[n * 2 + 1]; uint32_t flags = TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER; switch (TEE_PARAM_TYPE_GET(types, n)) { case TEE_PARAM_TYPE_MEMREF_OUTPUT: case TEE_PARAM_TYPE_MEMREF_INOUT: flags |= TEE_MEMORY_ACCESS_WRITE; /*FALLTHROUGH*/ case TEE_PARAM_TYPE_MEMREF_INPUT: p->u[n].mem.mobj = &mobj_virt; p->u[n].mem.offs = a; p->u[n].mem.size = b; if (tee_mmu_check_access_rights(utc, flags, a, b)) return TEE_ERROR_ACCESS_DENIED; break; case TEE_PARAM_TYPE_VALUE_INPUT: case TEE_PARAM_TYPE_VALUE_INOUT: p->u[n].val.a = a; p->u[n].val.b = b; break; default: memset(&p->u[n], 0, sizeof(p->u[n])); break; } } return TEE_SUCCESS; } static TEE_Result alloc_temp_sec_mem(size_t size, struct mobj **mobj, uint8_t **va) { /* Allocate section in secure DDR */ #ifdef CFG_PAGED_USER_TA *mobj = mobj_seccpy_shm_alloc(size); #else *mobj = mobj_mm_alloc(mobj_sec_ddr, size, &tee_mm_sec_ddr); #endif if (!*mobj) return TEE_ERROR_GENERIC; *va = mobj_get_va(*mobj, 0); return TEE_SUCCESS; } /* * TA invokes some TA with parameter. * If some parameters are memory references: * - either the memref is inside TA private RAM: TA is not allowed to expose * its private RAM: use a temporary memory buffer and copy the data. * - or the memref is not in the TA private RAM: * - if the memref was mapped to the TA, TA is allowed to expose it. * - if so, converts memref virtual address into a physical address. */ static TEE_Result tee_svc_copy_param(struct tee_ta_session *sess, struct tee_ta_session *called_sess, struct utee_params *callee_params, struct tee_ta_param *param, void *tmp_buf_va[TEE_NUM_PARAMS], struct mobj **mobj_tmp) { size_t n; TEE_Result res; size_t req_mem = 0; size_t s; uint8_t *dst = 0; bool ta_private_memref[TEE_NUM_PARAMS]; struct user_ta_ctx *utc = to_user_ta_ctx(sess->ctx); void *va; size_t dst_offs; /* fill 'param' input struct with caller params description buffer */ if (!callee_params) { memset(param, 0, sizeof(*param)); } else { res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)callee_params, sizeof(struct utee_params)); if (res != TEE_SUCCESS) return res; res = utee_param_to_param(utc, param, callee_params); if (res != TEE_SUCCESS) return res; } if (called_sess && is_pseudo_ta_ctx(called_sess->ctx)) { /* pseudo TA borrows the mapping of the calling TA */ return TEE_SUCCESS; } /* All mobj in param are of type MOJB_TYPE_VIRT */ for (n = 0; n < TEE_NUM_PARAMS; n++) { ta_private_memref[n] = false; switch (TEE_PARAM_TYPE_GET(param->types, n)) { case TEE_PARAM_TYPE_MEMREF_INPUT: case TEE_PARAM_TYPE_MEMREF_OUTPUT: case TEE_PARAM_TYPE_MEMREF_INOUT: va = (void *)param->u[n].mem.offs; s = param->u[n].mem.size; if (!va) { if (s) return TEE_ERROR_BAD_PARAMETERS; break; } /* uTA cannot expose its private memory */ if (tee_mmu_is_vbuf_inside_ta_private(utc, va, s)) { s = ROUNDUP(s, sizeof(uint32_t)); if (ADD_OVERFLOW(req_mem, s, &req_mem)) return TEE_ERROR_BAD_PARAMETERS; ta_private_memref[n] = true; break; } res = tee_mmu_vbuf_to_mobj_offs(utc, va, s, &param->u[n].mem.mobj, &param->u[n].mem.offs); if (res != TEE_SUCCESS) return res; break; default: break; } } if (req_mem == 0) return TEE_SUCCESS; res = alloc_temp_sec_mem(req_mem, mobj_tmp, &dst); if (res != TEE_SUCCESS) return res; dst_offs = 0; for (n = 0; n < TEE_NUM_PARAMS; n++) { if (!ta_private_memref[n]) continue; s = ROUNDUP(param->u[n].mem.size, sizeof(uint32_t)); switch (TEE_PARAM_TYPE_GET(param->types, n)) { case TEE_PARAM_TYPE_MEMREF_INPUT: case TEE_PARAM_TYPE_MEMREF_INOUT: va = (void *)param->u[n].mem.offs; if (va) { res = tee_svc_copy_from_user(dst, va, param->u[n].mem.size); if (res != TEE_SUCCESS) return res; param->u[n].mem.offs = dst_offs; param->u[n].mem.mobj = *mobj_tmp; tmp_buf_va[n] = dst; dst += s; dst_offs += s; } break; case TEE_PARAM_TYPE_MEMREF_OUTPUT: va = (void *)param->u[n].mem.offs; if (va) { param->u[n].mem.offs = dst_offs; param->u[n].mem.mobj = *mobj_tmp; tmp_buf_va[n] = dst; dst += s; dst_offs += s; } break; default: continue; } } return TEE_SUCCESS; } /* * Back from execution of service: update parameters passed from TA: * If some parameters were memory references: * - either the memref was temporary: copy back data and update size * - or it was the original TA memref: update only the size value. */ static TEE_Result tee_svc_update_out_param( struct tee_ta_param *param, void *tmp_buf_va[TEE_NUM_PARAMS], struct utee_params *usr_param) { size_t n; uint64_t *vals = usr_param->vals; for (n = 0; n < TEE_NUM_PARAMS; n++) { switch (TEE_PARAM_TYPE_GET(param->types, n)) { case TEE_PARAM_TYPE_MEMREF_OUTPUT: case TEE_PARAM_TYPE_MEMREF_INOUT: /* * Memory copy is only needed if there's a temporary * buffer involved, tmp_buf_va[n] is only update if * a temporary buffer is used. Otherwise only the * size needs to be updated. */ if (tmp_buf_va[n] && param->u[n].mem.size <= vals[n * 2 + 1]) { void *src = tmp_buf_va[n]; void *dst = (void *)(uintptr_t)vals[n * 2]; TEE_Result res; res = tee_svc_copy_to_user(dst, src, param->u[n].mem.size); if (res != TEE_SUCCESS) return res; } usr_param->vals[n * 2 + 1] = param->u[n].mem.size; break; case TEE_PARAM_TYPE_VALUE_OUTPUT: case TEE_PARAM_TYPE_VALUE_INOUT: vals[n * 2] = param->u[n].val.a; vals[n * 2 + 1] = param->u[n].val.b; break; default: continue; } } return TEE_SUCCESS; } /* Called when a TA calls an OpenSession on another TA */ TEE_Result syscall_open_ta_session(const TEE_UUID *dest, unsigned long cancel_req_to, struct utee_params *usr_param, uint32_t *ta_sess, uint32_t *ret_orig) { TEE_Result res; uint32_t ret_o = TEE_ORIGIN_TEE; struct tee_ta_session *s = NULL; struct tee_ta_session *sess; struct mobj *mobj_param = NULL; TEE_UUID *uuid = malloc(sizeof(TEE_UUID)); struct tee_ta_param *param = malloc(sizeof(struct tee_ta_param)); TEE_Identity *clnt_id = malloc(sizeof(TEE_Identity)); void *tmp_buf_va[TEE_NUM_PARAMS] = { NULL }; struct user_ta_ctx *utc; if (uuid == NULL || param == NULL || clnt_id == NULL) { res = TEE_ERROR_OUT_OF_MEMORY; goto out_free_only; } memset(param, 0, sizeof(struct tee_ta_param)); res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) goto out_free_only; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_copy_from_user(uuid, dest, sizeof(TEE_UUID)); if (res != TEE_SUCCESS) goto function_exit; clnt_id->login = TEE_LOGIN_TRUSTED_APP; memcpy(&clnt_id->uuid, &sess->ctx->uuid, sizeof(TEE_UUID)); res = tee_svc_copy_param(sess, NULL, usr_param, param, tmp_buf_va, &mobj_param); if (res != TEE_SUCCESS) goto function_exit; res = tee_ta_open_session(&ret_o, &s, &utc->open_sessions, uuid, clnt_id, cancel_req_to, param); tee_mmu_set_ctx(&utc->ctx); if (res != TEE_SUCCESS) goto function_exit; res = tee_svc_update_out_param(param, tmp_buf_va, usr_param); function_exit: mobj_free(mobj_param); if (res == TEE_SUCCESS) tee_svc_copy_kaddr_to_uref(ta_sess, s); tee_svc_copy_to_user(ret_orig, &ret_o, sizeof(ret_o)); out_free_only: free(param); free(uuid); free(clnt_id); return res; } TEE_Result syscall_close_ta_session(unsigned long ta_sess) { TEE_Result res; struct tee_ta_session *sess; TEE_Identity clnt_id; struct tee_ta_session *s = tee_svc_uref_to_kaddr(ta_sess); struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); clnt_id.login = TEE_LOGIN_TRUSTED_APP; memcpy(&clnt_id.uuid, &sess->ctx->uuid, sizeof(TEE_UUID)); return tee_ta_close_session(s, &utc->open_sessions, &clnt_id); } TEE_Result syscall_invoke_ta_command(unsigned long ta_sess, unsigned long cancel_req_to, unsigned long cmd_id, struct utee_params *usr_param, uint32_t *ret_orig) { TEE_Result res; TEE_Result res2; uint32_t ret_o = TEE_ORIGIN_TEE; struct tee_ta_param param = { 0 }; TEE_Identity clnt_id; struct tee_ta_session *sess; struct tee_ta_session *called_sess; struct mobj *mobj_param = NULL; void *tmp_buf_va[TEE_NUM_PARAMS] = { NULL }; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); called_sess = tee_ta_get_session( (vaddr_t)tee_svc_uref_to_kaddr(ta_sess), true, &utc->open_sessions); if (!called_sess) return TEE_ERROR_BAD_PARAMETERS; clnt_id.login = TEE_LOGIN_TRUSTED_APP; memcpy(&clnt_id.uuid, &sess->ctx->uuid, sizeof(TEE_UUID)); res = tee_svc_copy_param(sess, called_sess, usr_param, &param, tmp_buf_va, &mobj_param); if (res != TEE_SUCCESS) goto function_exit; res = tee_ta_invoke_command(&ret_o, called_sess, &clnt_id, cancel_req_to, cmd_id, &param); res2 = tee_svc_update_out_param(&param, tmp_buf_va, usr_param); if (res2 != TEE_SUCCESS) { /* * Spec for TEE_InvokeTACommand() says: * "If the return origin is different from * TEE_ORIGIN_TRUSTED_APP, then the function has failed * before it could reach the destination Trusted * Application." * * But if we can't update params to the caller we have no * choice we need to return some error to indicate that * parameters aren't updated as expected. */ ret_o = TEE_ORIGIN_TEE; res = res2; } function_exit: tee_ta_put_session(called_sess); mobj_free(mobj_param); if (ret_orig) tee_svc_copy_to_user(ret_orig, &ret_o, sizeof(ret_o)); return res; } TEE_Result syscall_check_access_rights(unsigned long flags, const void *buf, size_t len) { TEE_Result res; struct tee_ta_session *s; res = tee_ta_get_current_session(&s); if (res != TEE_SUCCESS) return res; return tee_mmu_check_access_rights(to_user_ta_ctx(s->ctx), flags, (uaddr_t)buf, len); } TEE_Result tee_svc_copy_from_user(void *kaddr, const void *uaddr, size_t len) { TEE_Result res; struct tee_ta_session *s; res = tee_ta_get_current_session(&s); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(s->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)uaddr, len); if (res != TEE_SUCCESS) return res; memcpy(kaddr, uaddr, len); return TEE_SUCCESS; } TEE_Result tee_svc_copy_to_user(void *uaddr, const void *kaddr, size_t len) { TEE_Result res; struct tee_ta_session *s; res = tee_ta_get_current_session(&s); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(s->ctx), TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)uaddr, len); if (res != TEE_SUCCESS) return res; memcpy(uaddr, kaddr, len); return TEE_SUCCESS; } TEE_Result tee_svc_copy_kaddr_to_uref(uint32_t *uref, void *kaddr) { uint32_t ref = tee_svc_kaddr_to_uref(kaddr); return tee_svc_copy_to_user(uref, &ref, sizeof(ref)); } TEE_Result syscall_get_cancellation_flag(uint32_t *cancel) { TEE_Result res; struct tee_ta_session *s = NULL; uint32_t c; res = tee_ta_get_current_session(&s); if (res != TEE_SUCCESS) return res; c = tee_ta_session_is_cancelled(s, NULL); return tee_svc_copy_to_user(cancel, &c, sizeof(c)); } TEE_Result syscall_unmask_cancellation(uint32_t *old_mask) { TEE_Result res; struct tee_ta_session *s = NULL; uint32_t m; res = tee_ta_get_current_session(&s); if (res != TEE_SUCCESS) return res; m = s->cancel_mask; s->cancel_mask = false; return tee_svc_copy_to_user(old_mask, &m, sizeof(m)); } TEE_Result syscall_mask_cancellation(uint32_t *old_mask) { TEE_Result res; struct tee_ta_session *s = NULL; uint32_t m; res = tee_ta_get_current_session(&s); if (res != TEE_SUCCESS) return res; m = s->cancel_mask; s->cancel_mask = true; return tee_svc_copy_to_user(old_mask, &m, sizeof(m)); } TEE_Result syscall_wait(unsigned long timeout) { TEE_Result res = TEE_SUCCESS; uint32_t mytime = 0; struct tee_ta_session *s; TEE_Time base_time; TEE_Time current_time; res = tee_ta_get_current_session(&s); if (res != TEE_SUCCESS) return res; res = tee_time_get_sys_time(&base_time); if (res != TEE_SUCCESS) return res; while (true) { res = tee_time_get_sys_time(&current_time); if (res != TEE_SUCCESS) return res; if (tee_ta_session_is_cancelled(s, &current_time)) return TEE_ERROR_CANCEL; mytime = (current_time.seconds - base_time.seconds) * 1000 + (int)current_time.millis - (int)base_time.millis; if (mytime >= timeout) return TEE_SUCCESS; tee_time_wait(timeout - mytime); } return res; } TEE_Result syscall_get_time(unsigned long cat, TEE_Time *mytime) { TEE_Result res, res2; struct tee_ta_session *s = NULL; TEE_Time t; res = tee_ta_get_current_session(&s); if (res != TEE_SUCCESS) return res; switch (cat) { case UTEE_TIME_CAT_SYSTEM: res = tee_time_get_sys_time(&t); break; case UTEE_TIME_CAT_TA_PERSISTENT: res = tee_time_get_ta_time((const void *)&s->ctx->uuid, &t); break; case UTEE_TIME_CAT_REE: res = tee_time_get_ree_time(&t); break; default: res = TEE_ERROR_BAD_PARAMETERS; break; } if (res == TEE_SUCCESS || res == TEE_ERROR_OVERFLOW) { res2 = tee_svc_copy_to_user(mytime, &t, sizeof(t)); if (res2 != TEE_SUCCESS) res = res2; } return res; } TEE_Result syscall_set_ta_time(const TEE_Time *mytime) { TEE_Result res; struct tee_ta_session *s = NULL; TEE_Time t; res = tee_ta_get_current_session(&s); if (res != TEE_SUCCESS) return res; res = tee_svc_copy_from_user(&t, mytime, sizeof(t)); if (res != TEE_SUCCESS) return res; return tee_time_set_ta_time((const void *)&s->ctx->uuid, &t); }
null
113
CWE-787
CVE-2019-1010296
// SPDX-License-Identifier: BSD-2-Clause /* * Copyright (c) 2014, STMicroelectronics International N.V. */ #include <assert.h> #include <crypto/crypto.h> #include <kernel/tee_ta_manager.h> #include <mm/tee_mmu.h> #include <string_ext.h> #include <string.h> #include <sys/queue.h> #include <tee_api_types.h> #include <tee/tee_cryp_utl.h> #include <tee/tee_obj.h> #include <tee/tee_svc_cryp.h> #include <tee/tee_svc.h> #include <trace.h> #include <utee_defines.h> #include <util.h> #include <tee_api_defines_extensions.h> #if defined(CFG_CRYPTO_HKDF) #include <tee/tee_cryp_hkdf.h> #endif #if defined(CFG_CRYPTO_CONCAT_KDF) #include <tee/tee_cryp_concat_kdf.h> #endif #if defined(CFG_CRYPTO_PBKDF2) #include <tee/tee_cryp_pbkdf2.h> #endif typedef void (*tee_cryp_ctx_finalize_func_t) (void *ctx, uint32_t algo); struct tee_cryp_state { TAILQ_ENTRY(tee_cryp_state) link; uint32_t algo; uint32_t mode; vaddr_t key1; vaddr_t key2; void *ctx; tee_cryp_ctx_finalize_func_t ctx_finalize; }; struct tee_cryp_obj_secret { uint32_t key_size; uint32_t alloc_size; /* * Pseudo code visualize layout of structure * Next follows data, such as: * uint8_t data[alloc_size] * key_size must never exceed alloc_size */ }; #define TEE_TYPE_ATTR_OPTIONAL 0x0 #define TEE_TYPE_ATTR_REQUIRED 0x1 #define TEE_TYPE_ATTR_OPTIONAL_GROUP 0x2 #define TEE_TYPE_ATTR_SIZE_INDICATOR 0x4 #define TEE_TYPE_ATTR_GEN_KEY_OPT 0x8 #define TEE_TYPE_ATTR_GEN_KEY_REQ 0x10 /* Handle storing of generic secret keys of varying lengths */ #define ATTR_OPS_INDEX_SECRET 0 /* Convert to/from big-endian byte array and provider-specific bignum */ #define ATTR_OPS_INDEX_BIGNUM 1 /* Convert to/from value attribute depending on direction */ #define ATTR_OPS_INDEX_VALUE 2 struct tee_cryp_obj_type_attrs { uint32_t attr_id; uint16_t flags; uint16_t ops_index; uint16_t raw_offs; uint16_t raw_size; }; #define RAW_DATA(_x, _y) \ .raw_offs = offsetof(_x, _y), .raw_size = MEMBER_SIZE(_x, _y) static const struct tee_cryp_obj_type_attrs tee_cryp_obj_secret_value_attrs[] = { { .attr_id = TEE_ATTR_SECRET_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_SECRET, .raw_offs = 0, .raw_size = 0 }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_rsa_pub_key_attrs[] = { { .attr_id = TEE_ATTR_RSA_MODULUS, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_public_key, n) }, { .attr_id = TEE_ATTR_RSA_PUBLIC_EXPONENT, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_public_key, e) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_rsa_keypair_attrs[] = { { .attr_id = TEE_ATTR_RSA_MODULUS, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, n) }, { .attr_id = TEE_ATTR_RSA_PUBLIC_EXPONENT, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, e) }, { .attr_id = TEE_ATTR_RSA_PRIVATE_EXPONENT, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, d) }, { .attr_id = TEE_ATTR_RSA_PRIME1, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, p) }, { .attr_id = TEE_ATTR_RSA_PRIME2, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, q) }, { .attr_id = TEE_ATTR_RSA_EXPONENT1, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, dp) }, { .attr_id = TEE_ATTR_RSA_EXPONENT2, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, dq) }, { .attr_id = TEE_ATTR_RSA_COEFFICIENT, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, qp) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dsa_pub_key_attrs[] = { { .attr_id = TEE_ATTR_DSA_PRIME, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_public_key, p) }, { .attr_id = TEE_ATTR_DSA_SUBPRIME, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_public_key, q) }, { .attr_id = TEE_ATTR_DSA_BASE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_public_key, g) }, { .attr_id = TEE_ATTR_DSA_PUBLIC_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_public_key, y) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dsa_keypair_attrs[] = { { .attr_id = TEE_ATTR_DSA_PRIME, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, p) }, { .attr_id = TEE_ATTR_DSA_SUBPRIME, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, q) }, { .attr_id = TEE_ATTR_DSA_BASE, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, g) }, { .attr_id = TEE_ATTR_DSA_PRIVATE_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, x) }, { .attr_id = TEE_ATTR_DSA_PUBLIC_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, y) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dh_keypair_attrs[] = { { .attr_id = TEE_ATTR_DH_PRIME, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, p) }, { .attr_id = TEE_ATTR_DH_BASE, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, g) }, { .attr_id = TEE_ATTR_DH_PUBLIC_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, y) }, { .attr_id = TEE_ATTR_DH_PRIVATE_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, x) }, { .attr_id = TEE_ATTR_DH_SUBPRIME, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP | TEE_TYPE_ATTR_GEN_KEY_OPT, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, q) }, { .attr_id = TEE_ATTR_DH_X_BITS, .flags = TEE_TYPE_ATTR_GEN_KEY_OPT, .ops_index = ATTR_OPS_INDEX_VALUE, RAW_DATA(struct dh_keypair, xbits) }, }; #if defined(CFG_CRYPTO_HKDF) static const struct tee_cryp_obj_type_attrs tee_cryp_obj_hkdf_ikm_attrs[] = { { .attr_id = TEE_ATTR_HKDF_IKM, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_SECRET, .raw_offs = 0, .raw_size = 0 }, }; #endif #if defined(CFG_CRYPTO_CONCAT_KDF) static const struct tee_cryp_obj_type_attrs tee_cryp_obj_concat_kdf_z_attrs[] = { { .attr_id = TEE_ATTR_CONCAT_KDF_Z, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_SECRET, .raw_offs = 0, .raw_size = 0 }, }; #endif #if defined(CFG_CRYPTO_PBKDF2) static const struct tee_cryp_obj_type_attrs tee_cryp_obj_pbkdf2_passwd_attrs[] = { { .attr_id = TEE_ATTR_PBKDF2_PASSWORD, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_SECRET, .raw_offs = 0, .raw_size = 0 }, }; #endif static const struct tee_cryp_obj_type_attrs tee_cryp_obj_ecc_pub_key_attrs[] = { { .attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_X, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_public_key, x) }, { .attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_Y, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_public_key, y) }, { .attr_id = TEE_ATTR_ECC_CURVE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_VALUE, RAW_DATA(struct ecc_public_key, curve) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_ecc_keypair_attrs[] = { { .attr_id = TEE_ATTR_ECC_PRIVATE_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_keypair, d) }, { .attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_X, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_keypair, x) }, { .attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_Y, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_keypair, y) }, { .attr_id = TEE_ATTR_ECC_CURVE, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_VALUE, RAW_DATA(struct ecc_keypair, curve) }, }; struct tee_cryp_obj_type_props { TEE_ObjectType obj_type; uint16_t min_size; /* may not be smaller than this */ uint16_t max_size; /* may not be larger than this */ uint16_t alloc_size; /* this many bytes are allocated to hold data */ uint8_t quanta; /* may only be an multiple of this */ uint8_t num_type_attrs; const struct tee_cryp_obj_type_attrs *type_attrs; }; #define PROP(obj_type, quanta, min_size, max_size, alloc_size, type_attrs) \ { (obj_type), (min_size), (max_size), (alloc_size), (quanta), \ ARRAY_SIZE(type_attrs), (type_attrs) } static const struct tee_cryp_obj_type_props tee_cryp_obj_props[] = { PROP(TEE_TYPE_AES, 64, 128, 256, /* valid sizes 128, 192, 256 */ 256 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_DES, 56, 56, 56, /* * Valid size 56 without parity, note that we still allocate * for 64 bits since the key is supplied with parity. */ 64 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_DES3, 56, 112, 168, /* * Valid sizes 112, 168 without parity, note that we still * allocate for with space for the parity since the key is * supplied with parity. */ 192 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_MD5, 8, 64, 512, 512 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA1, 8, 80, 512, 512 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA224, 8, 112, 512, 512 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA256, 8, 192, 1024, 1024 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA384, 8, 256, 1024, 1024 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA512, 8, 256, 1024, 1024 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_GENERIC_SECRET, 8, 0, 4096, 4096 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), #if defined(CFG_CRYPTO_HKDF) PROP(TEE_TYPE_HKDF_IKM, 8, 0, 4096, 4096 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_hkdf_ikm_attrs), #endif #if defined(CFG_CRYPTO_CONCAT_KDF) PROP(TEE_TYPE_CONCAT_KDF_Z, 8, 0, 4096, 4096 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_concat_kdf_z_attrs), #endif #if defined(CFG_CRYPTO_PBKDF2) PROP(TEE_TYPE_PBKDF2_PASSWORD, 8, 0, 4096, 4096 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_pbkdf2_passwd_attrs), #endif PROP(TEE_TYPE_RSA_PUBLIC_KEY, 1, 256, CFG_CORE_BIGNUM_MAX_BITS, sizeof(struct rsa_public_key), tee_cryp_obj_rsa_pub_key_attrs), PROP(TEE_TYPE_RSA_KEYPAIR, 1, 256, CFG_CORE_BIGNUM_MAX_BITS, sizeof(struct rsa_keypair), tee_cryp_obj_rsa_keypair_attrs), PROP(TEE_TYPE_DSA_PUBLIC_KEY, 64, 512, 3072, sizeof(struct dsa_public_key), tee_cryp_obj_dsa_pub_key_attrs), PROP(TEE_TYPE_DSA_KEYPAIR, 64, 512, 3072, sizeof(struct dsa_keypair), tee_cryp_obj_dsa_keypair_attrs), PROP(TEE_TYPE_DH_KEYPAIR, 1, 256, 2048, sizeof(struct dh_keypair), tee_cryp_obj_dh_keypair_attrs), PROP(TEE_TYPE_ECDSA_PUBLIC_KEY, 1, 192, 521, sizeof(struct ecc_public_key), tee_cryp_obj_ecc_pub_key_attrs), PROP(TEE_TYPE_ECDSA_KEYPAIR, 1, 192, 521, sizeof(struct ecc_keypair), tee_cryp_obj_ecc_keypair_attrs), PROP(TEE_TYPE_ECDH_PUBLIC_KEY, 1, 192, 521, sizeof(struct ecc_public_key), tee_cryp_obj_ecc_pub_key_attrs), PROP(TEE_TYPE_ECDH_KEYPAIR, 1, 192, 521, sizeof(struct ecc_keypair), tee_cryp_obj_ecc_keypair_attrs), }; struct attr_ops { TEE_Result (*from_user)(void *attr, const void *buffer, size_t size); TEE_Result (*to_user)(void *attr, struct tee_ta_session *sess, void *buffer, uint64_t *size); TEE_Result (*to_binary)(void *attr, void *data, size_t data_len, size_t *offs); bool (*from_binary)(void *attr, const void *data, size_t data_len, size_t *offs); TEE_Result (*from_obj)(void *attr, void *src_attr); void (*free)(void *attr); void (*clear)(void *attr); }; static TEE_Result op_u32_to_binary_helper(uint32_t v, uint8_t *data, size_t data_len, size_t *offs) { uint32_t field; size_t next_offs; if (ADD_OVERFLOW(*offs, sizeof(field), &next_offs)) return TEE_ERROR_OVERFLOW; if (data && next_offs <= data_len) { field = TEE_U32_TO_BIG_ENDIAN(v); memcpy(data + *offs, &field, sizeof(field)); } (*offs) = next_offs; return TEE_SUCCESS; } static bool op_u32_from_binary_helper(uint32_t *v, const uint8_t *data, size_t data_len, size_t *offs) { uint32_t field; if (!data || (*offs + sizeof(field)) > data_len) return false; memcpy(&field, data + *offs, sizeof(field)); *v = TEE_U32_FROM_BIG_ENDIAN(field); (*offs) += sizeof(field); return true; } static TEE_Result op_attr_secret_value_from_user(void *attr, const void *buffer, size_t size) { struct tee_cryp_obj_secret *key = attr; /* Data size has to fit in allocated buffer */ if (size > key->alloc_size) return TEE_ERROR_SECURITY; memcpy(key + 1, buffer, size); key->key_size = size; return TEE_SUCCESS; } static TEE_Result op_attr_secret_value_to_user(void *attr, struct tee_ta_session *sess __unused, void *buffer, uint64_t *size) { TEE_Result res; struct tee_cryp_obj_secret *key = attr; uint64_t s; uint64_t key_size; res = tee_svc_copy_from_user(&s, size, sizeof(s)); if (res != TEE_SUCCESS) return res; key_size = key->key_size; res = tee_svc_copy_to_user(size, &key_size, sizeof(key_size)); if (res != TEE_SUCCESS) return res; if (s < key->key_size || !buffer) return TEE_ERROR_SHORT_BUFFER; return tee_svc_copy_to_user(buffer, key + 1, key->key_size); } static TEE_Result op_attr_secret_value_to_binary(void *attr, void *data, size_t data_len, size_t *offs) { TEE_Result res; struct tee_cryp_obj_secret *key = attr; size_t next_offs; res = op_u32_to_binary_helper(key->key_size, data, data_len, offs); if (res != TEE_SUCCESS) return res; if (ADD_OVERFLOW(*offs, key->key_size, &next_offs)) return TEE_ERROR_OVERFLOW; if (data && next_offs <= data_len) memcpy((uint8_t *)data + *offs, key + 1, key->key_size); (*offs) = next_offs; return TEE_SUCCESS; } static bool op_attr_secret_value_from_binary(void *attr, const void *data, size_t data_len, size_t *offs) { struct tee_cryp_obj_secret *key = attr; uint32_t s; if (!op_u32_from_binary_helper(&s, data, data_len, offs)) return false; if ((*offs + s) > data_len) return false; /* Data size has to fit in allocated buffer */ if (s > key->alloc_size) return false; key->key_size = s; memcpy(key + 1, (const uint8_t *)data + *offs, s); (*offs) += s; return true; } static TEE_Result op_attr_secret_value_from_obj(void *attr, void *src_attr) { struct tee_cryp_obj_secret *key = attr; struct tee_cryp_obj_secret *src_key = src_attr; if (src_key->key_size > key->alloc_size) return TEE_ERROR_BAD_STATE; memcpy(key + 1, src_key + 1, src_key->key_size); key->key_size = src_key->key_size; return TEE_SUCCESS; } static void op_attr_secret_value_clear(void *attr) { struct tee_cryp_obj_secret *key = attr; key->key_size = 0; memset(key + 1, 0, key->alloc_size); } static TEE_Result op_attr_bignum_from_user(void *attr, const void *buffer, size_t size) { struct bignum **bn = attr; return crypto_bignum_bin2bn(buffer, size, *bn); } static TEE_Result op_attr_bignum_to_user(void *attr, struct tee_ta_session *sess, void *buffer, uint64_t *size) { TEE_Result res; struct bignum **bn = attr; uint64_t req_size; uint64_t s; res = tee_svc_copy_from_user(&s, size, sizeof(s)); if (res != TEE_SUCCESS) return res; req_size = crypto_bignum_num_bytes(*bn); res = tee_svc_copy_to_user(size, &req_size, sizeof(req_size)); if (res != TEE_SUCCESS) return res; if (!req_size) return TEE_SUCCESS; if (s < req_size || !buffer) return TEE_ERROR_SHORT_BUFFER; /* Check we can access data using supplied user mode pointer */ res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)buffer, req_size); if (res != TEE_SUCCESS) return res; /* * Write the bignum (wich raw data points to) into an array of * bytes (stored in buffer) */ crypto_bignum_bn2bin(*bn, buffer); return TEE_SUCCESS; } static TEE_Result op_attr_bignum_to_binary(void *attr, void *data, size_t data_len, size_t *offs) { TEE_Result res; struct bignum **bn = attr; uint32_t n = crypto_bignum_num_bytes(*bn); size_t next_offs; res = op_u32_to_binary_helper(n, data, data_len, offs); if (res != TEE_SUCCESS) return res; if (ADD_OVERFLOW(*offs, n, &next_offs)) return TEE_ERROR_OVERFLOW; if (data && next_offs <= data_len) crypto_bignum_bn2bin(*bn, (uint8_t *)data + *offs); (*offs) = next_offs; return TEE_SUCCESS; } static bool op_attr_bignum_from_binary(void *attr, const void *data, size_t data_len, size_t *offs) { struct bignum **bn = attr; uint32_t n; if (!op_u32_from_binary_helper(&n, data, data_len, offs)) return false; if ((*offs + n) > data_len) return false; if (crypto_bignum_bin2bn((const uint8_t *)data + *offs, n, *bn)) return false; (*offs) += n; return true; } static TEE_Result op_attr_bignum_from_obj(void *attr, void *src_attr) { struct bignum **bn = attr; struct bignum **src_bn = src_attr; crypto_bignum_copy(*bn, *src_bn); return TEE_SUCCESS; } static void op_attr_bignum_clear(void *attr) { struct bignum **bn = attr; crypto_bignum_clear(*bn); } static void op_attr_bignum_free(void *attr) { struct bignum **bn = attr; crypto_bignum_free(*bn); *bn = NULL; } static TEE_Result op_attr_value_from_user(void *attr, const void *buffer, size_t size) { uint32_t *v = attr; if (size != sizeof(uint32_t) * 2) return TEE_ERROR_GENERIC; /* "can't happen */ /* Note that only the first value is copied */ memcpy(v, buffer, sizeof(uint32_t)); return TEE_SUCCESS; } static TEE_Result op_attr_value_to_user(void *attr, struct tee_ta_session *sess __unused, void *buffer, uint64_t *size) { TEE_Result res; uint32_t *v = attr; uint64_t s; uint32_t value[2] = { *v }; uint64_t req_size = sizeof(value); res = tee_svc_copy_from_user(&s, size, sizeof(s)); if (res != TEE_SUCCESS) return res; if (s < req_size || !buffer) return TEE_ERROR_SHORT_BUFFER; return tee_svc_copy_to_user(buffer, value, req_size); } static TEE_Result op_attr_value_to_binary(void *attr, void *data, size_t data_len, size_t *offs) { uint32_t *v = attr; return op_u32_to_binary_helper(*v, data, data_len, offs); } static bool op_attr_value_from_binary(void *attr, const void *data, size_t data_len, size_t *offs) { uint32_t *v = attr; return op_u32_from_binary_helper(v, data, data_len, offs); } static TEE_Result op_attr_value_from_obj(void *attr, void *src_attr) { uint32_t *v = attr; uint32_t *src_v = src_attr; *v = *src_v; return TEE_SUCCESS; } static void op_attr_value_clear(void *attr) { uint32_t *v = attr; *v = 0; } static const struct attr_ops attr_ops[] = { [ATTR_OPS_INDEX_SECRET] = { .from_user = op_attr_secret_value_from_user, .to_user = op_attr_secret_value_to_user, .to_binary = op_attr_secret_value_to_binary, .from_binary = op_attr_secret_value_from_binary, .from_obj = op_attr_secret_value_from_obj, .free = op_attr_secret_value_clear, /* not a typo */ .clear = op_attr_secret_value_clear, }, [ATTR_OPS_INDEX_BIGNUM] = { .from_user = op_attr_bignum_from_user, .to_user = op_attr_bignum_to_user, .to_binary = op_attr_bignum_to_binary, .from_binary = op_attr_bignum_from_binary, .from_obj = op_attr_bignum_from_obj, .free = op_attr_bignum_free, .clear = op_attr_bignum_clear, }, [ATTR_OPS_INDEX_VALUE] = { .from_user = op_attr_value_from_user, .to_user = op_attr_value_to_user, .to_binary = op_attr_value_to_binary, .from_binary = op_attr_value_from_binary, .from_obj = op_attr_value_from_obj, .free = op_attr_value_clear, /* not a typo */ .clear = op_attr_value_clear, }, }; TEE_Result syscall_cryp_obj_get_info(unsigned long obj, TEE_ObjectInfo *info) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) goto exit; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) goto exit; res = tee_svc_copy_to_user(info, &o->info, sizeof(o->info)); exit: return res; } TEE_Result syscall_cryp_obj_restrict_usage(unsigned long obj, unsigned long usage) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) goto exit; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) goto exit; o->info.objectUsage &= usage; exit: return res; } static int tee_svc_cryp_obj_find_type_attr_idx( uint32_t attr_id, const struct tee_cryp_obj_type_props *type_props) { size_t n; for (n = 0; n < type_props->num_type_attrs; n++) { if (attr_id == type_props->type_attrs[n].attr_id) return n; } return -1; } static const struct tee_cryp_obj_type_props *tee_svc_find_type_props( TEE_ObjectType obj_type) { size_t n; for (n = 0; n < ARRAY_SIZE(tee_cryp_obj_props); n++) { if (tee_cryp_obj_props[n].obj_type == obj_type) return tee_cryp_obj_props + n; } return NULL; } /* Set an attribute on an object */ static void set_attribute(struct tee_obj *o, const struct tee_cryp_obj_type_props *props, uint32_t attr) { int idx = tee_svc_cryp_obj_find_type_attr_idx(attr, props); if (idx < 0) return; o->have_attrs |= BIT(idx); } /* Get an attribute on an object */ static uint32_t get_attribute(const struct tee_obj *o, const struct tee_cryp_obj_type_props *props, uint32_t attr) { int idx = tee_svc_cryp_obj_find_type_attr_idx(attr, props); if (idx < 0) return 0; return o->have_attrs & BIT(idx); } TEE_Result syscall_cryp_obj_get_attr(unsigned long obj, unsigned long attr_id, void *buffer, uint64_t *size) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; const struct tee_cryp_obj_type_props *type_props; int idx; const struct attr_ops *ops; void *attr; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return TEE_ERROR_ITEM_NOT_FOUND; /* Check that the object is initialized */ if (!(o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED)) return TEE_ERROR_BAD_PARAMETERS; /* Check that getting the attribute is allowed */ if (!(attr_id & TEE_ATTR_BIT_PROTECTED) && !(o->info.objectUsage & TEE_USAGE_EXTRACTABLE)) return TEE_ERROR_BAD_PARAMETERS; type_props = tee_svc_find_type_props(o->info.objectType); if (!type_props) { /* Unknown object type, "can't happen" */ return TEE_ERROR_BAD_STATE; } idx = tee_svc_cryp_obj_find_type_attr_idx(attr_id, type_props); if ((idx < 0) || ((o->have_attrs & (1 << idx)) == 0)) return TEE_ERROR_ITEM_NOT_FOUND; ops = attr_ops + type_props->type_attrs[idx].ops_index; attr = (uint8_t *)o->attr + type_props->type_attrs[idx].raw_offs; return ops->to_user(attr, sess, buffer, size); } void tee_obj_attr_free(struct tee_obj *o) { const struct tee_cryp_obj_type_props *tp; size_t n; if (!o->attr) return; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return; for (n = 0; n < tp->num_type_attrs; n++) { const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n; attr_ops[ta->ops_index].free((uint8_t *)o->attr + ta->raw_offs); } } void tee_obj_attr_clear(struct tee_obj *o) { const struct tee_cryp_obj_type_props *tp; size_t n; if (!o->attr) return; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return; for (n = 0; n < tp->num_type_attrs; n++) { const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n; attr_ops[ta->ops_index].clear((uint8_t *)o->attr + ta->raw_offs); } } TEE_Result tee_obj_attr_to_binary(struct tee_obj *o, void *data, size_t *data_len) { const struct tee_cryp_obj_type_props *tp; size_t n; size_t offs = 0; size_t len = data ? *data_len : 0; TEE_Result res; if (o->info.objectType == TEE_TYPE_DATA) { *data_len = 0; return TEE_SUCCESS; /* pure data object */ } if (!o->attr) return TEE_ERROR_BAD_STATE; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return TEE_ERROR_BAD_STATE; for (n = 0; n < tp->num_type_attrs; n++) { const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n; void *attr = (uint8_t *)o->attr + ta->raw_offs; res = attr_ops[ta->ops_index].to_binary(attr, data, len, &offs); if (res != TEE_SUCCESS) return res; } *data_len = offs; if (data && offs > len) return TEE_ERROR_SHORT_BUFFER; return TEE_SUCCESS; } TEE_Result tee_obj_attr_from_binary(struct tee_obj *o, const void *data, size_t data_len) { const struct tee_cryp_obj_type_props *tp; size_t n; size_t offs = 0; if (o->info.objectType == TEE_TYPE_DATA) return TEE_SUCCESS; /* pure data object */ if (!o->attr) return TEE_ERROR_BAD_STATE; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return TEE_ERROR_BAD_STATE; for (n = 0; n < tp->num_type_attrs; n++) { const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n; void *attr = (uint8_t *)o->attr + ta->raw_offs; if (!attr_ops[ta->ops_index].from_binary(attr, data, data_len, &offs)) return TEE_ERROR_CORRUPT_OBJECT; } return TEE_SUCCESS; } TEE_Result tee_obj_attr_copy_from(struct tee_obj *o, const struct tee_obj *src) { TEE_Result res; const struct tee_cryp_obj_type_props *tp; const struct tee_cryp_obj_type_attrs *ta; size_t n; uint32_t have_attrs = 0; void *attr; void *src_attr; if (o->info.objectType == TEE_TYPE_DATA) return TEE_SUCCESS; /* pure data object */ if (!o->attr) return TEE_ERROR_BAD_STATE; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return TEE_ERROR_BAD_STATE; if (o->info.objectType == src->info.objectType) { have_attrs = src->have_attrs; for (n = 0; n < tp->num_type_attrs; n++) { ta = tp->type_attrs + n; attr = (uint8_t *)o->attr + ta->raw_offs; src_attr = (uint8_t *)src->attr + ta->raw_offs; res = attr_ops[ta->ops_index].from_obj(attr, src_attr); if (res != TEE_SUCCESS) return res; } } else { const struct tee_cryp_obj_type_props *tp_src; int idx; if (o->info.objectType == TEE_TYPE_RSA_PUBLIC_KEY) { if (src->info.objectType != TEE_TYPE_RSA_KEYPAIR) return TEE_ERROR_BAD_PARAMETERS; } else if (o->info.objectType == TEE_TYPE_DSA_PUBLIC_KEY) { if (src->info.objectType != TEE_TYPE_DSA_KEYPAIR) return TEE_ERROR_BAD_PARAMETERS; } else if (o->info.objectType == TEE_TYPE_ECDSA_PUBLIC_KEY) { if (src->info.objectType != TEE_TYPE_ECDSA_KEYPAIR) return TEE_ERROR_BAD_PARAMETERS; } else if (o->info.objectType == TEE_TYPE_ECDH_PUBLIC_KEY) { if (src->info.objectType != TEE_TYPE_ECDH_KEYPAIR) return TEE_ERROR_BAD_PARAMETERS; } else { return TEE_ERROR_BAD_PARAMETERS; } tp_src = tee_svc_find_type_props(src->info.objectType); if (!tp_src) return TEE_ERROR_BAD_STATE; have_attrs = BIT32(tp->num_type_attrs) - 1; for (n = 0; n < tp->num_type_attrs; n++) { ta = tp->type_attrs + n; idx = tee_svc_cryp_obj_find_type_attr_idx(ta->attr_id, tp_src); if (idx < 0) return TEE_ERROR_BAD_STATE; attr = (uint8_t *)o->attr + ta->raw_offs; src_attr = (uint8_t *)src->attr + tp_src->type_attrs[idx].raw_offs; res = attr_ops[ta->ops_index].from_obj(attr, src_attr); if (res != TEE_SUCCESS) return res; } } o->have_attrs = have_attrs; return TEE_SUCCESS; } TEE_Result tee_obj_set_type(struct tee_obj *o, uint32_t obj_type, size_t max_key_size) { TEE_Result res = TEE_SUCCESS; const struct tee_cryp_obj_type_props *type_props; /* Can only set type for newly allocated objs */ if (o->attr) return TEE_ERROR_BAD_STATE; /* * Verify that maxKeySize is supported and find out how * much should be allocated. */ if (obj_type == TEE_TYPE_DATA) { if (max_key_size) return TEE_ERROR_NOT_SUPPORTED; } else { /* Find description of object */ type_props = tee_svc_find_type_props(obj_type); if (!type_props) return TEE_ERROR_NOT_SUPPORTED; /* Check that maxKeySize follows restrictions */ if (max_key_size % type_props->quanta != 0) return TEE_ERROR_NOT_SUPPORTED; if (max_key_size < type_props->min_size) return TEE_ERROR_NOT_SUPPORTED; if (max_key_size > type_props->max_size) return TEE_ERROR_NOT_SUPPORTED; o->attr = calloc(1, type_props->alloc_size); if (!o->attr) return TEE_ERROR_OUT_OF_MEMORY; } /* If we have a key structure, pre-allocate the bignums inside */ switch (obj_type) { case TEE_TYPE_RSA_PUBLIC_KEY: res = crypto_acipher_alloc_rsa_public_key(o->attr, max_key_size); break; case TEE_TYPE_RSA_KEYPAIR: res = crypto_acipher_alloc_rsa_keypair(o->attr, max_key_size); break; case TEE_TYPE_DSA_PUBLIC_KEY: res = crypto_acipher_alloc_dsa_public_key(o->attr, max_key_size); break; case TEE_TYPE_DSA_KEYPAIR: res = crypto_acipher_alloc_dsa_keypair(o->attr, max_key_size); break; case TEE_TYPE_DH_KEYPAIR: res = crypto_acipher_alloc_dh_keypair(o->attr, max_key_size); break; case TEE_TYPE_ECDSA_PUBLIC_KEY: case TEE_TYPE_ECDH_PUBLIC_KEY: res = crypto_acipher_alloc_ecc_public_key(o->attr, max_key_size); break; case TEE_TYPE_ECDSA_KEYPAIR: case TEE_TYPE_ECDH_KEYPAIR: res = crypto_acipher_alloc_ecc_keypair(o->attr, max_key_size); break; default: if (obj_type != TEE_TYPE_DATA) { struct tee_cryp_obj_secret *key = o->attr; key->alloc_size = type_props->alloc_size - sizeof(*key); } break; } if (res != TEE_SUCCESS) return res; o->info.objectType = obj_type; o->info.maxKeySize = max_key_size; o->info.objectUsage = TEE_USAGE_DEFAULT; return TEE_SUCCESS; } TEE_Result syscall_cryp_obj_alloc(unsigned long obj_type, unsigned long max_key_size, uint32_t *obj) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; if (obj_type == TEE_TYPE_DATA) return TEE_ERROR_NOT_SUPPORTED; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; o = tee_obj_alloc(); if (!o) return TEE_ERROR_OUT_OF_MEMORY; res = tee_obj_set_type(o, obj_type, max_key_size); if (res != TEE_SUCCESS) { tee_obj_free(o); return res; } tee_obj_add(to_user_ta_ctx(sess->ctx), o); res = tee_svc_copy_kaddr_to_uref(obj, o); if (res != TEE_SUCCESS) tee_obj_close(to_user_ta_ctx(sess->ctx), o); return res; } TEE_Result syscall_cryp_obj_close(unsigned long obj) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; /* * If it's busy it's used by an operation, a client should never have * this handle. */ if (o->busy) return TEE_ERROR_ITEM_NOT_FOUND; tee_obj_close(to_user_ta_ctx(sess->ctx), o); return TEE_SUCCESS; } TEE_Result syscall_cryp_obj_reset(unsigned long obj) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) == 0) { tee_obj_attr_clear(o); o->info.keySize = 0; o->info.objectUsage = TEE_USAGE_DEFAULT; } else { return TEE_ERROR_BAD_PARAMETERS; } /* the object is no more initialized */ o->info.handleFlags &= ~TEE_HANDLE_FLAG_INITIALIZED; return TEE_SUCCESS; } static TEE_Result copy_in_attrs(struct user_ta_ctx *utc, const struct utee_attribute *usr_attrs, uint32_t attr_count, TEE_Attribute *attrs) { TEE_Result res; uint32_t n; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)usr_attrs, attr_count * sizeof(struct utee_attribute)); if (res != TEE_SUCCESS) return res; for (n = 0; n < attr_count; n++) { attrs[n].attributeID = usr_attrs[n].attribute_id; if (attrs[n].attributeID & TEE_ATTR_BIT_VALUE) { attrs[n].content.value.a = usr_attrs[n].a; attrs[n].content.value.b = usr_attrs[n].b; } else { uintptr_t buf = usr_attrs[n].a; size_t len = usr_attrs[n].b; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, buf, len); if (res != TEE_SUCCESS) return res; attrs[n].content.ref.buffer = (void *)buf; attrs[n].content.ref.length = len; } } return TEE_SUCCESS; } enum attr_usage { ATTR_USAGE_POPULATE, ATTR_USAGE_GENERATE_KEY }; static TEE_Result tee_svc_cryp_check_attr(enum attr_usage usage, const struct tee_cryp_obj_type_props *type_props, const TEE_Attribute *attrs, uint32_t attr_count) { uint32_t required_flag; uint32_t opt_flag; bool all_opt_needed; uint32_t req_attrs = 0; uint32_t opt_grp_attrs = 0; uint32_t attrs_found = 0; size_t n; uint32_t bit; uint32_t flags; int idx; if (usage == ATTR_USAGE_POPULATE) { required_flag = TEE_TYPE_ATTR_REQUIRED; opt_flag = TEE_TYPE_ATTR_OPTIONAL_GROUP; all_opt_needed = true; } else { required_flag = TEE_TYPE_ATTR_GEN_KEY_REQ; opt_flag = TEE_TYPE_ATTR_GEN_KEY_OPT; all_opt_needed = false; } /* * First find out which attributes are required and which belong to * the optional group */ for (n = 0; n < type_props->num_type_attrs; n++) { bit = 1 << n; flags = type_props->type_attrs[n].flags; if (flags & required_flag) req_attrs |= bit; else if (flags & opt_flag) opt_grp_attrs |= bit; } /* * Verify that all required attributes are in place and * that the same attribute isn't repeated. */ for (n = 0; n < attr_count; n++) { idx = tee_svc_cryp_obj_find_type_attr_idx( attrs[n].attributeID, type_props); /* attribute not defined in current object type */ if (idx < 0) return TEE_ERROR_ITEM_NOT_FOUND; bit = 1 << idx; /* attribute not repeated */ if ((attrs_found & bit) != 0) return TEE_ERROR_ITEM_NOT_FOUND; attrs_found |= bit; } /* Required attribute missing */ if ((attrs_found & req_attrs) != req_attrs) return TEE_ERROR_ITEM_NOT_FOUND; /* * If the flag says that "if one of the optional attributes are included * all of them has to be included" this must be checked. */ if (all_opt_needed && (attrs_found & opt_grp_attrs) != 0 && (attrs_found & opt_grp_attrs) != opt_grp_attrs) return TEE_ERROR_ITEM_NOT_FOUND; return TEE_SUCCESS; } static TEE_Result get_ec_key_size(uint32_t curve, size_t *key_size) { switch (curve) { case TEE_ECC_CURVE_NIST_P192: *key_size = 192; break; case TEE_ECC_CURVE_NIST_P224: *key_size = 224; break; case TEE_ECC_CURVE_NIST_P256: *key_size = 256; break; case TEE_ECC_CURVE_NIST_P384: *key_size = 384; break; case TEE_ECC_CURVE_NIST_P521: *key_size = 521; break; default: return TEE_ERROR_NOT_SUPPORTED; } return TEE_SUCCESS; } static TEE_Result tee_svc_cryp_obj_populate_type( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, const TEE_Attribute *attrs, uint32_t attr_count) { TEE_Result res; uint32_t have_attrs = 0; size_t obj_size = 0; size_t n; int idx; const struct attr_ops *ops; void *attr; for (n = 0; n < attr_count; n++) { idx = tee_svc_cryp_obj_find_type_attr_idx( attrs[n].attributeID, type_props); /* attribute not defined in current object type */ if (idx < 0) return TEE_ERROR_ITEM_NOT_FOUND; have_attrs |= BIT32(idx); ops = attr_ops + type_props->type_attrs[idx].ops_index; attr = (uint8_t *)o->attr + type_props->type_attrs[idx].raw_offs; if (attrs[n].attributeID & TEE_ATTR_BIT_VALUE) res = ops->from_user(attr, &attrs[n].content.value, sizeof(attrs[n].content.value)); else res = ops->from_user(attr, attrs[n].content.ref.buffer, attrs[n].content.ref.length); if (res != TEE_SUCCESS) return res; /* * First attr_idx signifies the attribute that gives the size * of the object */ if (type_props->type_attrs[idx].flags & TEE_TYPE_ATTR_SIZE_INDICATOR) { /* * For ECDSA/ECDH we need to translate curve into * object size */ if (attrs[n].attributeID == TEE_ATTR_ECC_CURVE) { res = get_ec_key_size(attrs[n].content.value.a, &obj_size); if (res != TEE_SUCCESS) return res; } else { obj_size += (attrs[n].content.ref.length * 8); } } } /* * We have to do it like this because the parity bits aren't counted * when telling the size of the key in bits. */ if (o->info.objectType == TEE_TYPE_DES || o->info.objectType == TEE_TYPE_DES3) obj_size -= obj_size / 8; /* Exclude parity in size of key */ o->have_attrs = have_attrs; o->info.keySize = obj_size; return TEE_SUCCESS; } TEE_Result syscall_cryp_obj_populate(unsigned long obj, struct utee_attribute *usr_attrs, unsigned long attr_count) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; const struct tee_cryp_obj_type_props *type_props; TEE_Attribute *attrs = NULL; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; /* Must be a transient object */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0) return TEE_ERROR_BAD_PARAMETERS; /* Must not be initialized already */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0) return TEE_ERROR_BAD_PARAMETERS; type_props = tee_svc_find_type_props(o->info.objectType); if (!type_props) return TEE_ERROR_NOT_IMPLEMENTED; attrs = malloc(sizeof(TEE_Attribute) * attr_count); if (!attrs) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_attrs, attr_count, attrs); if (res != TEE_SUCCESS) goto out; res = tee_svc_cryp_check_attr(ATTR_USAGE_POPULATE, type_props, attrs, attr_count); if (res != TEE_SUCCESS) goto out; res = tee_svc_cryp_obj_populate_type(o, type_props, attrs, attr_count); if (res == TEE_SUCCESS) o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; out: free(attrs); return res; } TEE_Result syscall_cryp_obj_copy(unsigned long dst, unsigned long src) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *dst_o; struct tee_obj *src_o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(dst), &dst_o); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(src), &src_o); if (res != TEE_SUCCESS) return res; if ((src_o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; if ((dst_o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0) return TEE_ERROR_BAD_PARAMETERS; if ((dst_o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0) return TEE_ERROR_BAD_PARAMETERS; res = tee_obj_attr_copy_from(dst_o, src_o); if (res != TEE_SUCCESS) return res; dst_o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; dst_o->info.keySize = src_o->info.keySize; dst_o->info.objectUsage = src_o->info.objectUsage; return TEE_SUCCESS; } static TEE_Result tee_svc_obj_generate_key_rsa( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, uint32_t key_size, const TEE_Attribute *params, uint32_t param_count) { TEE_Result res; struct rsa_keypair *key = o->attr; uint32_t e = TEE_U32_TO_BIG_ENDIAN(65537); /* Copy the present attributes into the obj before starting */ res = tee_svc_cryp_obj_populate_type(o, type_props, params, param_count); if (res != TEE_SUCCESS) return res; if (!get_attribute(o, type_props, TEE_ATTR_RSA_PUBLIC_EXPONENT)) crypto_bignum_bin2bn((const uint8_t *)&e, sizeof(e), key->e); res = crypto_acipher_gen_rsa_key(key, key_size); if (res != TEE_SUCCESS) return res; /* Set bits for all known attributes for this object type */ o->have_attrs = (1 << type_props->num_type_attrs) - 1; return TEE_SUCCESS; } static TEE_Result tee_svc_obj_generate_key_dsa( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, uint32_t key_size) { TEE_Result res; res = crypto_acipher_gen_dsa_key(o->attr, key_size); if (res != TEE_SUCCESS) return res; /* Set bits for all known attributes for this object type */ o->have_attrs = (1 << type_props->num_type_attrs) - 1; return TEE_SUCCESS; } static TEE_Result tee_svc_obj_generate_key_dh( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, uint32_t key_size __unused, const TEE_Attribute *params, uint32_t param_count) { TEE_Result res; struct dh_keypair *tee_dh_key; struct bignum *dh_q = NULL; uint32_t dh_xbits = 0; /* Copy the present attributes into the obj before starting */ res = tee_svc_cryp_obj_populate_type(o, type_props, params, param_count); if (res != TEE_SUCCESS) return res; tee_dh_key = (struct dh_keypair *)o->attr; if (get_attribute(o, type_props, TEE_ATTR_DH_SUBPRIME)) dh_q = tee_dh_key->q; if (get_attribute(o, type_props, TEE_ATTR_DH_X_BITS)) dh_xbits = tee_dh_key->xbits; res = crypto_acipher_gen_dh_key(tee_dh_key, dh_q, dh_xbits); if (res != TEE_SUCCESS) return res; /* Set bits for the generated public and private key */ set_attribute(o, type_props, TEE_ATTR_DH_PUBLIC_VALUE); set_attribute(o, type_props, TEE_ATTR_DH_PRIVATE_VALUE); set_attribute(o, type_props, TEE_ATTR_DH_X_BITS); return TEE_SUCCESS; } static TEE_Result tee_svc_obj_generate_key_ecc( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, uint32_t key_size __unused, const TEE_Attribute *params, uint32_t param_count) { TEE_Result res; struct ecc_keypair *tee_ecc_key; /* Copy the present attributes into the obj before starting */ res = tee_svc_cryp_obj_populate_type(o, type_props, params, param_count); if (res != TEE_SUCCESS) return res; tee_ecc_key = (struct ecc_keypair *)o->attr; res = crypto_acipher_gen_ecc_key(tee_ecc_key); if (res != TEE_SUCCESS) return res; /* Set bits for the generated public and private key */ set_attribute(o, type_props, TEE_ATTR_ECC_PRIVATE_VALUE); set_attribute(o, type_props, TEE_ATTR_ECC_PUBLIC_VALUE_X); set_attribute(o, type_props, TEE_ATTR_ECC_PUBLIC_VALUE_Y); set_attribute(o, type_props, TEE_ATTR_ECC_CURVE); return TEE_SUCCESS; } TEE_Result syscall_obj_generate_key(unsigned long obj, unsigned long key_size, const struct utee_attribute *usr_params, unsigned long param_count) { TEE_Result res; struct tee_ta_session *sess; const struct tee_cryp_obj_type_props *type_props; struct tee_obj *o; struct tee_cryp_obj_secret *key; size_t byte_size; TEE_Attribute *params = NULL; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; /* Must be a transient object */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0) return TEE_ERROR_BAD_STATE; /* Must not be initialized already */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0) return TEE_ERROR_BAD_STATE; /* Find description of object */ type_props = tee_svc_find_type_props(o->info.objectType); if (!type_props) return TEE_ERROR_NOT_SUPPORTED; /* Check that maxKeySize follows restrictions */ if (key_size % type_props->quanta != 0) return TEE_ERROR_NOT_SUPPORTED; if (key_size < type_props->min_size) return TEE_ERROR_NOT_SUPPORTED; if (key_size > type_props->max_size) return TEE_ERROR_NOT_SUPPORTED; params = malloc(sizeof(TEE_Attribute) * param_count); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_params, param_count, params); if (res != TEE_SUCCESS) goto out; res = tee_svc_cryp_check_attr(ATTR_USAGE_GENERATE_KEY, type_props, params, param_count); if (res != TEE_SUCCESS) goto out; switch (o->info.objectType) { case TEE_TYPE_AES: case TEE_TYPE_DES: case TEE_TYPE_DES3: case TEE_TYPE_HMAC_MD5: case TEE_TYPE_HMAC_SHA1: case TEE_TYPE_HMAC_SHA224: case TEE_TYPE_HMAC_SHA256: case TEE_TYPE_HMAC_SHA384: case TEE_TYPE_HMAC_SHA512: case TEE_TYPE_GENERIC_SECRET: byte_size = key_size / 8; /* * We have to do it like this because the parity bits aren't * counted when telling the size of the key in bits. */ if (o->info.objectType == TEE_TYPE_DES || o->info.objectType == TEE_TYPE_DES3) { byte_size = (key_size + key_size / 7) / 8; } key = (struct tee_cryp_obj_secret *)o->attr; if (byte_size > key->alloc_size) { res = TEE_ERROR_EXCESS_DATA; goto out; } res = crypto_rng_read((void *)(key + 1), byte_size); if (res != TEE_SUCCESS) goto out; key->key_size = byte_size; /* Set bits for all known attributes for this object type */ o->have_attrs = (1 << type_props->num_type_attrs) - 1; break; case TEE_TYPE_RSA_KEYPAIR: res = tee_svc_obj_generate_key_rsa(o, type_props, key_size, params, param_count); if (res != TEE_SUCCESS) goto out; break; case TEE_TYPE_DSA_KEYPAIR: res = tee_svc_obj_generate_key_dsa(o, type_props, key_size); if (res != TEE_SUCCESS) goto out; break; case TEE_TYPE_DH_KEYPAIR: res = tee_svc_obj_generate_key_dh(o, type_props, key_size, params, param_count); if (res != TEE_SUCCESS) goto out; break; case TEE_TYPE_ECDSA_KEYPAIR: case TEE_TYPE_ECDH_KEYPAIR: res = tee_svc_obj_generate_key_ecc(o, type_props, key_size, params, param_count); if (res != TEE_SUCCESS) goto out; break; default: res = TEE_ERROR_BAD_FORMAT; } out: free(params); if (res == TEE_SUCCESS) { o->info.keySize = key_size; o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; } return res; } static TEE_Result tee_svc_cryp_get_state(struct tee_ta_session *sess, uint32_t state_id, struct tee_cryp_state **state) { struct tee_cryp_state *s; struct user_ta_ctx *utc = to_user_ta_ctx(sess->ctx); TAILQ_FOREACH(s, &utc->cryp_states, link) { if (state_id == (vaddr_t)s) { *state = s; return TEE_SUCCESS; } } return TEE_ERROR_BAD_PARAMETERS; } static void cryp_state_free(struct user_ta_ctx *utc, struct tee_cryp_state *cs) { struct tee_obj *o; if (tee_obj_get(utc, cs->key1, &o) == TEE_SUCCESS) tee_obj_close(utc, o); if (tee_obj_get(utc, cs->key2, &o) == TEE_SUCCESS) tee_obj_close(utc, o); TAILQ_REMOVE(&utc->cryp_states, cs, link); if (cs->ctx_finalize != NULL) cs->ctx_finalize(cs->ctx, cs->algo); switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_CIPHER: crypto_cipher_free_ctx(cs->ctx, cs->algo); break; case TEE_OPERATION_AE: crypto_authenc_free_ctx(cs->ctx, cs->algo); break; case TEE_OPERATION_DIGEST: crypto_hash_free_ctx(cs->ctx, cs->algo); break; case TEE_OPERATION_MAC: crypto_mac_free_ctx(cs->ctx, cs->algo); break; default: assert(!cs->ctx); } free(cs); } static TEE_Result tee_svc_cryp_check_key_type(const struct tee_obj *o, uint32_t algo, TEE_OperationMode mode) { uint32_t req_key_type; uint32_t req_key_type2 = 0; switch (TEE_ALG_GET_MAIN_ALG(algo)) { case TEE_MAIN_ALGO_MD5: req_key_type = TEE_TYPE_HMAC_MD5; break; case TEE_MAIN_ALGO_SHA1: req_key_type = TEE_TYPE_HMAC_SHA1; break; case TEE_MAIN_ALGO_SHA224: req_key_type = TEE_TYPE_HMAC_SHA224; break; case TEE_MAIN_ALGO_SHA256: req_key_type = TEE_TYPE_HMAC_SHA256; break; case TEE_MAIN_ALGO_SHA384: req_key_type = TEE_TYPE_HMAC_SHA384; break; case TEE_MAIN_ALGO_SHA512: req_key_type = TEE_TYPE_HMAC_SHA512; break; case TEE_MAIN_ALGO_AES: req_key_type = TEE_TYPE_AES; break; case TEE_MAIN_ALGO_DES: req_key_type = TEE_TYPE_DES; break; case TEE_MAIN_ALGO_DES3: req_key_type = TEE_TYPE_DES3; break; case TEE_MAIN_ALGO_RSA: req_key_type = TEE_TYPE_RSA_KEYPAIR; if (mode == TEE_MODE_ENCRYPT || mode == TEE_MODE_VERIFY) req_key_type2 = TEE_TYPE_RSA_PUBLIC_KEY; break; case TEE_MAIN_ALGO_DSA: req_key_type = TEE_TYPE_DSA_KEYPAIR; if (mode == TEE_MODE_ENCRYPT || mode == TEE_MODE_VERIFY) req_key_type2 = TEE_TYPE_DSA_PUBLIC_KEY; break; case TEE_MAIN_ALGO_DH: req_key_type = TEE_TYPE_DH_KEYPAIR; break; case TEE_MAIN_ALGO_ECDSA: req_key_type = TEE_TYPE_ECDSA_KEYPAIR; if (mode == TEE_MODE_VERIFY) req_key_type2 = TEE_TYPE_ECDSA_PUBLIC_KEY; break; case TEE_MAIN_ALGO_ECDH: req_key_type = TEE_TYPE_ECDH_KEYPAIR; break; #if defined(CFG_CRYPTO_HKDF) case TEE_MAIN_ALGO_HKDF: req_key_type = TEE_TYPE_HKDF_IKM; break; #endif #if defined(CFG_CRYPTO_CONCAT_KDF) case TEE_MAIN_ALGO_CONCAT_KDF: req_key_type = TEE_TYPE_CONCAT_KDF_Z; break; #endif #if defined(CFG_CRYPTO_PBKDF2) case TEE_MAIN_ALGO_PBKDF2: req_key_type = TEE_TYPE_PBKDF2_PASSWORD; break; #endif default: return TEE_ERROR_BAD_PARAMETERS; } if (req_key_type != o->info.objectType && req_key_type2 != o->info.objectType) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } TEE_Result syscall_cryp_state_alloc(unsigned long algo, unsigned long mode, unsigned long key1, unsigned long key2, uint32_t *state) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; struct tee_obj *o1 = NULL; struct tee_obj *o2 = NULL; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); if (key1 != 0) { res = tee_obj_get(utc, tee_svc_uref_to_vaddr(key1), &o1); if (res != TEE_SUCCESS) return res; if (o1->busy) return TEE_ERROR_BAD_PARAMETERS; res = tee_svc_cryp_check_key_type(o1, algo, mode); if (res != TEE_SUCCESS) return res; } if (key2 != 0) { res = tee_obj_get(utc, tee_svc_uref_to_vaddr(key2), &o2); if (res != TEE_SUCCESS) return res; if (o2->busy) return TEE_ERROR_BAD_PARAMETERS; res = tee_svc_cryp_check_key_type(o2, algo, mode); if (res != TEE_SUCCESS) return res; } cs = calloc(1, sizeof(struct tee_cryp_state)); if (!cs) return TEE_ERROR_OUT_OF_MEMORY; TAILQ_INSERT_TAIL(&utc->cryp_states, cs, link); cs->algo = algo; cs->mode = mode; switch (TEE_ALG_GET_CLASS(algo)) { case TEE_OPERATION_EXTENSION: #ifdef CFG_CRYPTO_RSASSA_NA1 if (algo == TEE_ALG_RSASSA_PKCS1_V1_5) goto rsassa_na1; #endif res = TEE_ERROR_NOT_SUPPORTED; break; case TEE_OPERATION_CIPHER: if ((algo == TEE_ALG_AES_XTS && (key1 == 0 || key2 == 0)) || (algo != TEE_ALG_AES_XTS && (key1 == 0 || key2 != 0))) { res = TEE_ERROR_BAD_PARAMETERS; } else { res = crypto_cipher_alloc_ctx(&cs->ctx, algo); if (res != TEE_SUCCESS) break; } break; case TEE_OPERATION_AE: if (key1 == 0 || key2 != 0) { res = TEE_ERROR_BAD_PARAMETERS; } else { res = crypto_authenc_alloc_ctx(&cs->ctx, algo); if (res != TEE_SUCCESS) break; } break; case TEE_OPERATION_MAC: if (key1 == 0 || key2 != 0) { res = TEE_ERROR_BAD_PARAMETERS; } else { res = crypto_mac_alloc_ctx(&cs->ctx, algo); if (res != TEE_SUCCESS) break; } break; case TEE_OPERATION_DIGEST: if (key1 != 0 || key2 != 0) { res = TEE_ERROR_BAD_PARAMETERS; } else { res = crypto_hash_alloc_ctx(&cs->ctx, algo); if (res != TEE_SUCCESS) break; } break; case TEE_OPERATION_ASYMMETRIC_CIPHER: case TEE_OPERATION_ASYMMETRIC_SIGNATURE: rsassa_na1: __maybe_unused if (key1 == 0 || key2 != 0) res = TEE_ERROR_BAD_PARAMETERS; break; case TEE_OPERATION_KEY_DERIVATION: if (key1 == 0 || key2 != 0) res = TEE_ERROR_BAD_PARAMETERS; break; default: res = TEE_ERROR_NOT_SUPPORTED; break; } if (res != TEE_SUCCESS) goto out; res = tee_svc_copy_kaddr_to_uref(state, cs); if (res != TEE_SUCCESS) goto out; /* Register keys */ if (o1 != NULL) { o1->busy = true; cs->key1 = (vaddr_t)o1; } if (o2 != NULL) { o2->busy = true; cs->key2 = (vaddr_t)o2; } out: if (res != TEE_SUCCESS) cryp_state_free(utc, cs); return res; } TEE_Result syscall_cryp_state_copy(unsigned long dst, unsigned long src) { TEE_Result res; struct tee_cryp_state *cs_dst; struct tee_cryp_state *cs_src; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(dst), &cs_dst); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(src), &cs_src); if (res != TEE_SUCCESS) return res; if (cs_dst->algo != cs_src->algo || cs_dst->mode != cs_src->mode) return TEE_ERROR_BAD_PARAMETERS; switch (TEE_ALG_GET_CLASS(cs_src->algo)) { case TEE_OPERATION_CIPHER: crypto_cipher_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo); break; case TEE_OPERATION_AE: crypto_authenc_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo); break; case TEE_OPERATION_DIGEST: crypto_hash_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo); break; case TEE_OPERATION_MAC: crypto_mac_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo); break; default: return TEE_ERROR_BAD_STATE; } return TEE_SUCCESS; } void tee_svc_cryp_free_states(struct user_ta_ctx *utc) { struct tee_cryp_state_head *states = &utc->cryp_states; while (!TAILQ_EMPTY(states)) cryp_state_free(utc, TAILQ_FIRST(states)); } TEE_Result syscall_cryp_state_free(unsigned long state) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; cryp_state_free(to_user_ta_ctx(sess->ctx), cs); return TEE_SUCCESS; } TEE_Result syscall_hash_init(unsigned long state, const void *iv __maybe_unused, size_t iv_len __maybe_unused) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_DIGEST: res = crypto_hash_init(cs->ctx, cs->algo); if (res != TEE_SUCCESS) return res; break; case TEE_OPERATION_MAC: { struct tee_obj *o; struct tee_cryp_obj_secret *key; res = tee_obj_get(to_user_ta_ctx(sess->ctx), cs->key1, &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; key = (struct tee_cryp_obj_secret *)o->attr; res = crypto_mac_init(cs->ctx, cs->algo, (void *)(key + 1), key->key_size); if (res != TEE_SUCCESS) return res; break; } default: return TEE_ERROR_BAD_PARAMETERS; } return TEE_SUCCESS; } TEE_Result syscall_hash_update(unsigned long state, const void *chunk, size_t chunk_size) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; /* No data, but size provided isn't valid parameters. */ if (!chunk && chunk_size) return TEE_ERROR_BAD_PARAMETERS; /* Zero length hash is valid, but nothing we need to do. */ if (!chunk_size) return TEE_SUCCESS; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)chunk, chunk_size); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_DIGEST: res = crypto_hash_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; break; case TEE_OPERATION_MAC: res = crypto_mac_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; break; default: return TEE_ERROR_BAD_PARAMETERS; } return TEE_SUCCESS; } TEE_Result syscall_hash_final(unsigned long state, const void *chunk, size_t chunk_size, void *hash, uint64_t *hash_len) { TEE_Result res, res2; size_t hash_size; uint64_t hlen; struct tee_cryp_state *cs; struct tee_ta_session *sess; /* No data, but size provided isn't valid parameters. */ if (!chunk && chunk_size) return TEE_ERROR_BAD_PARAMETERS; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)chunk, chunk_size); if (res != TEE_SUCCESS) return res; res = tee_svc_copy_from_user(&hlen, hash_len, sizeof(hlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)hash, hlen); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_DIGEST: res = tee_hash_get_digest_size(cs->algo, &hash_size); if (res != TEE_SUCCESS) return res; if (*hash_len < hash_size) { res = TEE_ERROR_SHORT_BUFFER; goto out; } if (chunk_size) { res = crypto_hash_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; } res = crypto_hash_final(cs->ctx, cs->algo, hash, hash_size); if (res != TEE_SUCCESS) return res; break; case TEE_OPERATION_MAC: res = tee_mac_get_digest_size(cs->algo, &hash_size); if (res != TEE_SUCCESS) return res; if (*hash_len < hash_size) { res = TEE_ERROR_SHORT_BUFFER; goto out; } if (chunk_size) { res = crypto_mac_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; } res = crypto_mac_final(cs->ctx, cs->algo, hash, hash_size); if (res != TEE_SUCCESS) return res; break; default: return TEE_ERROR_BAD_PARAMETERS; } out: hlen = hash_size; res2 = tee_svc_copy_to_user(hash_len, &hlen, sizeof(*hash_len)); if (res2 != TEE_SUCCESS) return res2; return res; } TEE_Result syscall_cipher_init(unsigned long state, const void *iv, size_t iv_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; struct tee_obj *o; struct tee_cryp_obj_secret *key1; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) iv, iv_len); if (res != TEE_SUCCESS) return res; res = tee_obj_get(utc, cs->key1, &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; key1 = o->attr; if (tee_obj_get(utc, cs->key2, &o) == TEE_SUCCESS) { struct tee_cryp_obj_secret *key2 = o->attr; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; res = crypto_cipher_init(cs->ctx, cs->algo, cs->mode, (uint8_t *)(key1 + 1), key1->key_size, (uint8_t *)(key2 + 1), key2->key_size, iv, iv_len); } else { res = crypto_cipher_init(cs->ctx, cs->algo, cs->mode, (uint8_t *)(key1 + 1), key1->key_size, NULL, 0, iv, iv_len); } if (res != TEE_SUCCESS) return res; cs->ctx_finalize = crypto_cipher_final; return TEE_SUCCESS; } static TEE_Result tee_svc_cipher_update_helper(unsigned long state, bool last_block, const void *src, size_t src_len, void *dst, uint64_t *dst_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)src, src_len); if (res != TEE_SUCCESS) return res; if (!dst_len) { dlen = 0; } else { res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)dst, dlen); if (res != TEE_SUCCESS) return res; } if (dlen < src_len) { res = TEE_ERROR_SHORT_BUFFER; goto out; } if (src_len > 0) { /* Permit src_len == 0 to finalize the operation */ res = tee_do_cipher_update(cs->ctx, cs->algo, cs->mode, last_block, src, src_len, dst); } if (last_block && cs->ctx_finalize != NULL) { cs->ctx_finalize(cs->ctx, cs->algo); cs->ctx_finalize = NULL; } out: if ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) && dst_len != NULL) { TEE_Result res2; dlen = src_len; res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) res = res2; } return res; } TEE_Result syscall_cipher_update(unsigned long state, const void *src, size_t src_len, void *dst, uint64_t *dst_len) { return tee_svc_cipher_update_helper(state, false /* last_block */, src, src_len, dst, dst_len); } TEE_Result syscall_cipher_final(unsigned long state, const void *src, size_t src_len, void *dst, uint64_t *dst_len) { return tee_svc_cipher_update_helper(state, true /* last_block */, src, src_len, dst, dst_len); } #if defined(CFG_CRYPTO_HKDF) static TEE_Result get_hkdf_params(const TEE_Attribute *params, uint32_t param_count, void **salt, size_t *salt_len, void **info, size_t *info_len, size_t *okm_len) { size_t n; enum { SALT = 0x1, LENGTH = 0x2, INFO = 0x4 }; uint8_t found = 0; *salt = *info = NULL; *salt_len = *info_len = *okm_len = 0; for (n = 0; n < param_count; n++) { switch (params[n].attributeID) { case TEE_ATTR_HKDF_SALT: if (!(found & SALT)) { *salt = params[n].content.ref.buffer; *salt_len = params[n].content.ref.length; found |= SALT; } break; case TEE_ATTR_HKDF_OKM_LENGTH: if (!(found & LENGTH)) { *okm_len = params[n].content.value.a; found |= LENGTH; } break; case TEE_ATTR_HKDF_INFO: if (!(found & INFO)) { *info = params[n].content.ref.buffer; *info_len = params[n].content.ref.length; found |= INFO; } break; default: /* Unexpected attribute */ return TEE_ERROR_BAD_PARAMETERS; } } if (!(found & LENGTH)) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } #endif #if defined(CFG_CRYPTO_CONCAT_KDF) static TEE_Result get_concat_kdf_params(const TEE_Attribute *params, uint32_t param_count, void **other_info, size_t *other_info_len, size_t *derived_key_len) { size_t n; enum { LENGTH = 0x1, INFO = 0x2 }; uint8_t found = 0; *other_info = NULL; *other_info_len = *derived_key_len = 0; for (n = 0; n < param_count; n++) { switch (params[n].attributeID) { case TEE_ATTR_CONCAT_KDF_OTHER_INFO: if (!(found & INFO)) { *other_info = params[n].content.ref.buffer; *other_info_len = params[n].content.ref.length; found |= INFO; } break; case TEE_ATTR_CONCAT_KDF_DKM_LENGTH: if (!(found & LENGTH)) { *derived_key_len = params[n].content.value.a; found |= LENGTH; } break; default: /* Unexpected attribute */ return TEE_ERROR_BAD_PARAMETERS; } } if (!(found & LENGTH)) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } #endif #if defined(CFG_CRYPTO_PBKDF2) static TEE_Result get_pbkdf2_params(const TEE_Attribute *params, uint32_t param_count, void **salt, size_t *salt_len, size_t *derived_key_len, size_t *iteration_count) { size_t n; enum { SALT = 0x1, LENGTH = 0x2, COUNT = 0x4 }; uint8_t found = 0; *salt = NULL; *salt_len = *derived_key_len = *iteration_count = 0; for (n = 0; n < param_count; n++) { switch (params[n].attributeID) { case TEE_ATTR_PBKDF2_SALT: if (!(found & SALT)) { *salt = params[n].content.ref.buffer; *salt_len = params[n].content.ref.length; found |= SALT; } break; case TEE_ATTR_PBKDF2_DKM_LENGTH: if (!(found & LENGTH)) { *derived_key_len = params[n].content.value.a; found |= LENGTH; } break; case TEE_ATTR_PBKDF2_ITERATION_COUNT: if (!(found & COUNT)) { *iteration_count = params[n].content.value.a; found |= COUNT; } break; default: /* Unexpected attribute */ return TEE_ERROR_BAD_PARAMETERS; } } if ((found & (LENGTH|COUNT)) != (LENGTH|COUNT)) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } #endif TEE_Result syscall_cryp_derive_key(unsigned long state, const struct utee_attribute *usr_params, unsigned long param_count, unsigned long derived_key) { TEE_Result res = TEE_ERROR_NOT_SUPPORTED; struct tee_ta_session *sess; struct tee_obj *ko; struct tee_obj *so; struct tee_cryp_state *cs; struct tee_cryp_obj_secret *sk; const struct tee_cryp_obj_type_props *type_props; TEE_Attribute *params = NULL; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; params = malloc(sizeof(TEE_Attribute) * param_count); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(utc, usr_params, param_count, params); if (res != TEE_SUCCESS) goto out; /* Get key set in operation */ res = tee_obj_get(utc, cs->key1, &ko); if (res != TEE_SUCCESS) goto out; res = tee_obj_get(utc, tee_svc_uref_to_vaddr(derived_key), &so); if (res != TEE_SUCCESS) goto out; /* Find information needed about the object to initialize */ sk = so->attr; /* Find description of object */ type_props = tee_svc_find_type_props(so->info.objectType); if (!type_props) { res = TEE_ERROR_NOT_SUPPORTED; goto out; } if (cs->algo == TEE_ALG_DH_DERIVE_SHARED_SECRET) { size_t alloc_size; struct bignum *pub; struct bignum *ss; if (param_count != 1 || params[0].attributeID != TEE_ATTR_DH_PUBLIC_VALUE) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } alloc_size = params[0].content.ref.length * 8; pub = crypto_bignum_allocate(alloc_size); ss = crypto_bignum_allocate(alloc_size); if (pub && ss) { crypto_bignum_bin2bn(params[0].content.ref.buffer, params[0].content.ref.length, pub); res = crypto_acipher_dh_shared_secret(ko->attr, pub, ss); if (res == TEE_SUCCESS) { sk->key_size = crypto_bignum_num_bytes(ss); crypto_bignum_bn2bin(ss, (uint8_t *)(sk + 1)); so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } else { res = TEE_ERROR_OUT_OF_MEMORY; } crypto_bignum_free(pub); crypto_bignum_free(ss); } else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_ECDH) { size_t alloc_size; struct ecc_public_key key_public; uint8_t *pt_secret; unsigned long pt_secret_len; if (param_count != 2 || params[0].attributeID != TEE_ATTR_ECC_PUBLIC_VALUE_X || params[1].attributeID != TEE_ATTR_ECC_PUBLIC_VALUE_Y) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } switch (cs->algo) { case TEE_ALG_ECDH_P192: alloc_size = 192; break; case TEE_ALG_ECDH_P224: alloc_size = 224; break; case TEE_ALG_ECDH_P256: alloc_size = 256; break; case TEE_ALG_ECDH_P384: alloc_size = 384; break; case TEE_ALG_ECDH_P521: alloc_size = 521; break; default: res = TEE_ERROR_NOT_IMPLEMENTED; goto out; } /* Create the public key */ res = crypto_acipher_alloc_ecc_public_key(&key_public, alloc_size); if (res != TEE_SUCCESS) goto out; key_public.curve = ((struct ecc_keypair *)ko->attr)->curve; crypto_bignum_bin2bn(params[0].content.ref.buffer, params[0].content.ref.length, key_public.x); crypto_bignum_bin2bn(params[1].content.ref.buffer, params[1].content.ref.length, key_public.y); pt_secret = (uint8_t *)(sk + 1); pt_secret_len = sk->alloc_size; res = crypto_acipher_ecc_shared_secret(ko->attr, &key_public, pt_secret, &pt_secret_len); if (res == TEE_SUCCESS) { sk->key_size = pt_secret_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } /* free the public key */ crypto_acipher_free_ecc_public_key(&key_public); } #if defined(CFG_CRYPTO_HKDF) else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_HKDF) { void *salt, *info; size_t salt_len, info_len, okm_len; uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo); struct tee_cryp_obj_secret *ik = ko->attr; const uint8_t *ikm = (const uint8_t *)(ik + 1); res = get_hkdf_params(params, param_count, &salt, &salt_len, &info, &info_len, &okm_len); if (res != TEE_SUCCESS) goto out; /* Requested size must fit into the output object's buffer */ if (okm_len > ik->alloc_size) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_cryp_hkdf(hash_id, ikm, ik->key_size, salt, salt_len, info, info_len, (uint8_t *)(sk + 1), okm_len); if (res == TEE_SUCCESS) { sk->key_size = okm_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } #endif #if defined(CFG_CRYPTO_CONCAT_KDF) else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_CONCAT_KDF) { void *info; size_t info_len, derived_key_len; uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo); struct tee_cryp_obj_secret *ss = ko->attr; const uint8_t *shared_secret = (const uint8_t *)(ss + 1); res = get_concat_kdf_params(params, param_count, &info, &info_len, &derived_key_len); if (res != TEE_SUCCESS) goto out; /* Requested size must fit into the output object's buffer */ if (derived_key_len > ss->alloc_size) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_cryp_concat_kdf(hash_id, shared_secret, ss->key_size, info, info_len, (uint8_t *)(sk + 1), derived_key_len); if (res == TEE_SUCCESS) { sk->key_size = derived_key_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } #endif #if defined(CFG_CRYPTO_PBKDF2) else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_PBKDF2) { void *salt; size_t salt_len, iteration_count, derived_key_len; uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo); struct tee_cryp_obj_secret *ss = ko->attr; const uint8_t *password = (const uint8_t *)(ss + 1); res = get_pbkdf2_params(params, param_count, &salt, &salt_len, &derived_key_len, &iteration_count); if (res != TEE_SUCCESS) goto out; /* Requested size must fit into the output object's buffer */ if (derived_key_len > ss->alloc_size) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_cryp_pbkdf2(hash_id, password, ss->key_size, salt, salt_len, iteration_count, (uint8_t *)(sk + 1), derived_key_len); if (res == TEE_SUCCESS) { sk->key_size = derived_key_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } #endif else res = TEE_ERROR_NOT_SUPPORTED; out: free(params); return res; } TEE_Result syscall_cryp_random_number_generate(void *buf, size_t blen) { TEE_Result res; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)buf, blen); if (res != TEE_SUCCESS) return res; res = crypto_rng_read(buf, blen); if (res != TEE_SUCCESS) return res; return res; } TEE_Result syscall_authenc_init(unsigned long state, const void *nonce, size_t nonce_len, size_t tag_len, size_t aad_len, size_t payload_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; struct tee_obj *o; struct tee_cryp_obj_secret *key; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), cs->key1, &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; key = o->attr; res = crypto_authenc_init(cs->ctx, cs->algo, cs->mode, (uint8_t *)(key + 1), key->key_size, nonce, nonce_len, tag_len, aad_len, payload_len); if (res != TEE_SUCCESS) return res; cs->ctx_finalize = (tee_cryp_ctx_finalize_func_t)crypto_authenc_final; return TEE_SUCCESS; } TEE_Result syscall_authenc_update_aad(unsigned long state, const void *aad_data, size_t aad_data_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) aad_data, aad_data_len); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = crypto_authenc_update_aad(cs->ctx, cs->algo, cs->mode, aad_data, aad_data_len); if (res != TEE_SUCCESS) return res; return TEE_SUCCESS; } TEE_Result syscall_authenc_update_payload(unsigned long state, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen; size_t tmp_dlen; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) src_data, src_len); if (res != TEE_SUCCESS) return res; res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)dst_data, dlen); if (res != TEE_SUCCESS) return res; if (dlen < src_len) { res = TEE_ERROR_SHORT_BUFFER; goto out; } tmp_dlen = dlen; res = crypto_authenc_update_payload(cs->ctx, cs->algo, cs->mode, src_data, src_len, dst_data, &tmp_dlen); dlen = tmp_dlen; out: if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) { TEE_Result res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) res = res2; } return res; } TEE_Result syscall_authenc_enc_final(unsigned long state, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len, void *tag, uint64_t *tag_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen; uint64_t tlen = 0; size_t tmp_dlen; size_t tmp_tlen; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; if (cs->mode != TEE_MODE_ENCRYPT) return TEE_ERROR_BAD_PARAMETERS; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)src_data, src_len); if (res != TEE_SUCCESS) return res; if (!dst_len) { dlen = 0; } else { res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)dst_data, dlen); if (res != TEE_SUCCESS) return res; } if (dlen < src_len) { res = TEE_ERROR_SHORT_BUFFER; goto out; } res = tee_svc_copy_from_user(&tlen, tag_len, sizeof(tlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)tag, tlen); if (res != TEE_SUCCESS) return res; tmp_dlen = dlen; tmp_tlen = tlen; res = crypto_authenc_enc_final(cs->ctx, cs->algo, src_data, src_len, dst_data, &tmp_dlen, tag, &tmp_tlen); dlen = tmp_dlen; tlen = tmp_tlen; out: if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) { TEE_Result res2; if (dst_len != NULL) { res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) return res2; } res2 = tee_svc_copy_to_user(tag_len, &tlen, sizeof(*tag_len)); if (res2 != TEE_SUCCESS) return res2; } return res; } TEE_Result syscall_authenc_dec_final(unsigned long state, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len, const void *tag, size_t tag_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen; size_t tmp_dlen; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; if (cs->mode != TEE_MODE_DECRYPT) return TEE_ERROR_BAD_PARAMETERS; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)src_data, src_len); if (res != TEE_SUCCESS) return res; if (!dst_len) { dlen = 0; } else { res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)dst_data, dlen); if (res != TEE_SUCCESS) return res; } if (dlen < src_len) { res = TEE_ERROR_SHORT_BUFFER; goto out; } res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)tag, tag_len); if (res != TEE_SUCCESS) return res; tmp_dlen = dlen; res = crypto_authenc_dec_final(cs->ctx, cs->algo, src_data, src_len, dst_data, &tmp_dlen, tag, tag_len); dlen = tmp_dlen; out: if ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) && dst_len != NULL) { TEE_Result res2; res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) return res2; } return res; } static int pkcs1_get_salt_len(const TEE_Attribute *params, uint32_t num_params, size_t default_len) { size_t n; assert(default_len < INT_MAX); for (n = 0; n < num_params; n++) { if (params[n].attributeID == TEE_ATTR_RSA_PSS_SALT_LENGTH) { if (params[n].content.value.a < INT_MAX) return params[n].content.value.a; break; } } /* * If salt length isn't provided use the default value which is * the length of the digest. */ return default_len; } TEE_Result syscall_asymm_operate(unsigned long state, const struct utee_attribute *usr_params, size_t num_params, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen64; size_t dlen; struct tee_obj *o; void *label = NULL; size_t label_len = 0; size_t n; int salt_len; TEE_Attribute *params = NULL; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights( utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) src_data, src_len); if (res != TEE_SUCCESS) return res; res = tee_svc_copy_from_user(&dlen64, dst_len, sizeof(dlen64)); if (res != TEE_SUCCESS) return res; dlen = dlen64; res = tee_mmu_check_access_rights( utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) dst_data, dlen); if (res != TEE_SUCCESS) return res; params = malloc(sizeof(TEE_Attribute) * num_params); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(utc, usr_params, num_params, params); if (res != TEE_SUCCESS) goto out; res = tee_obj_get(utc, cs->key1, &o); if (res != TEE_SUCCESS) goto out; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) { res = TEE_ERROR_GENERIC; goto out; } switch (cs->algo) { case TEE_ALG_RSA_NOPAD: if (cs->mode == TEE_MODE_ENCRYPT) { res = crypto_acipher_rsanopad_encrypt(o->attr, src_data, src_len, dst_data, &dlen); } else if (cs->mode == TEE_MODE_DECRYPT) { res = crypto_acipher_rsanopad_decrypt(o->attr, src_data, src_len, dst_data, &dlen); } else { /* * We will panic because "the mode is not compatible * with the function" */ res = TEE_ERROR_GENERIC; } break; case TEE_ALG_RSAES_PKCS1_V1_5: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512: for (n = 0; n < num_params; n++) { if (params[n].attributeID == TEE_ATTR_RSA_OAEP_LABEL) { label = params[n].content.ref.buffer; label_len = params[n].content.ref.length; break; } } if (cs->mode == TEE_MODE_ENCRYPT) { res = crypto_acipher_rsaes_encrypt(cs->algo, o->attr, label, label_len, src_data, src_len, dst_data, &dlen); } else if (cs->mode == TEE_MODE_DECRYPT) { res = crypto_acipher_rsaes_decrypt( cs->algo, o->attr, label, label_len, src_data, src_len, dst_data, &dlen); } else { res = TEE_ERROR_BAD_PARAMETERS; } break; #if defined(CFG_CRYPTO_RSASSA_NA1) case TEE_ALG_RSASSA_PKCS1_V1_5: #endif case TEE_ALG_RSASSA_PKCS1_V1_5_MD5: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512: if (cs->mode != TEE_MODE_SIGN) { res = TEE_ERROR_BAD_PARAMETERS; break; } salt_len = pkcs1_get_salt_len(params, num_params, src_len); res = crypto_acipher_rsassa_sign(cs->algo, o->attr, salt_len, src_data, src_len, dst_data, &dlen); break; case TEE_ALG_DSA_SHA1: case TEE_ALG_DSA_SHA224: case TEE_ALG_DSA_SHA256: res = crypto_acipher_dsa_sign(cs->algo, o->attr, src_data, src_len, dst_data, &dlen); break; case TEE_ALG_ECDSA_P192: case TEE_ALG_ECDSA_P224: case TEE_ALG_ECDSA_P256: case TEE_ALG_ECDSA_P384: case TEE_ALG_ECDSA_P521: res = crypto_acipher_ecc_sign(cs->algo, o->attr, src_data, src_len, dst_data, &dlen); break; default: res = TEE_ERROR_BAD_PARAMETERS; break; } out: free(params); if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) { TEE_Result res2; dlen64 = dlen; res2 = tee_svc_copy_to_user(dst_len, &dlen64, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) return res2; } return res; } TEE_Result syscall_asymm_verify(unsigned long state, const struct utee_attribute *usr_params, size_t num_params, const void *data, size_t data_len, const void *sig, size_t sig_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; struct tee_obj *o; size_t hash_size; int salt_len = 0; TEE_Attribute *params = NULL; uint32_t hash_algo; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; if (cs->mode != TEE_MODE_VERIFY) return TEE_ERROR_BAD_PARAMETERS; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)data, data_len); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)sig, sig_len); if (res != TEE_SUCCESS) return res; params = malloc(sizeof(TEE_Attribute) * num_params); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(utc, usr_params, num_params, params); if (res != TEE_SUCCESS) goto out; res = tee_obj_get(utc, cs->key1, &o); if (res != TEE_SUCCESS) goto out; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } switch (TEE_ALG_GET_MAIN_ALG(cs->algo)) { case TEE_MAIN_ALGO_RSA: if (cs->algo != TEE_ALG_RSASSA_PKCS1_V1_5) { hash_algo = TEE_DIGEST_HASH_TO_ALGO(cs->algo); res = tee_hash_get_digest_size(hash_algo, &hash_size); if (res != TEE_SUCCESS) break; if (data_len != hash_size) { res = TEE_ERROR_BAD_PARAMETERS; break; } salt_len = pkcs1_get_salt_len(params, num_params, hash_size); } res = crypto_acipher_rsassa_verify(cs->algo, o->attr, salt_len, data, data_len, sig, sig_len); break; case TEE_MAIN_ALGO_DSA: hash_algo = TEE_DIGEST_HASH_TO_ALGO(cs->algo); res = tee_hash_get_digest_size(hash_algo, &hash_size); if (res != TEE_SUCCESS) break; /* * Depending on the DSA algorithm (NIST), the digital signature * output size may be truncated to the size of a key pair * (Q prime size). Q prime size must be less or equal than the * hash output length of the hash algorithm involved. */ if (data_len > hash_size) { res = TEE_ERROR_BAD_PARAMETERS; break; } res = crypto_acipher_dsa_verify(cs->algo, o->attr, data, data_len, sig, sig_len); break; case TEE_MAIN_ALGO_ECDSA: res = crypto_acipher_ecc_verify(cs->algo, o->attr, data, data_len, sig, sig_len); break; default: res = TEE_ERROR_NOT_SUPPORTED; } out: free(params); return res; }
null
// SPDX-License-Identifier: BSD-2-Clause /* * Copyright (c) 2014, STMicroelectronics International N.V. */ #include <assert.h> #include <compiler.h> #include <crypto/crypto.h> #include <kernel/tee_ta_manager.h> #include <mm/tee_mmu.h> #include <string_ext.h> #include <string.h> #include <sys/queue.h> #include <tee_api_types.h> #include <tee/tee_cryp_utl.h> #include <tee/tee_obj.h> #include <tee/tee_svc_cryp.h> #include <tee/tee_svc.h> #include <trace.h> #include <utee_defines.h> #include <util.h> #include <tee_api_defines_extensions.h> #if defined(CFG_CRYPTO_HKDF) #include <tee/tee_cryp_hkdf.h> #endif #if defined(CFG_CRYPTO_CONCAT_KDF) #include <tee/tee_cryp_concat_kdf.h> #endif #if defined(CFG_CRYPTO_PBKDF2) #include <tee/tee_cryp_pbkdf2.h> #endif typedef void (*tee_cryp_ctx_finalize_func_t) (void *ctx, uint32_t algo); struct tee_cryp_state { TAILQ_ENTRY(tee_cryp_state) link; uint32_t algo; uint32_t mode; vaddr_t key1; vaddr_t key2; void *ctx; tee_cryp_ctx_finalize_func_t ctx_finalize; }; struct tee_cryp_obj_secret { uint32_t key_size; uint32_t alloc_size; /* * Pseudo code visualize layout of structure * Next follows data, such as: * uint8_t data[alloc_size] * key_size must never exceed alloc_size */ }; #define TEE_TYPE_ATTR_OPTIONAL 0x0 #define TEE_TYPE_ATTR_REQUIRED 0x1 #define TEE_TYPE_ATTR_OPTIONAL_GROUP 0x2 #define TEE_TYPE_ATTR_SIZE_INDICATOR 0x4 #define TEE_TYPE_ATTR_GEN_KEY_OPT 0x8 #define TEE_TYPE_ATTR_GEN_KEY_REQ 0x10 /* Handle storing of generic secret keys of varying lengths */ #define ATTR_OPS_INDEX_SECRET 0 /* Convert to/from big-endian byte array and provider-specific bignum */ #define ATTR_OPS_INDEX_BIGNUM 1 /* Convert to/from value attribute depending on direction */ #define ATTR_OPS_INDEX_VALUE 2 struct tee_cryp_obj_type_attrs { uint32_t attr_id; uint16_t flags; uint16_t ops_index; uint16_t raw_offs; uint16_t raw_size; }; #define RAW_DATA(_x, _y) \ .raw_offs = offsetof(_x, _y), .raw_size = MEMBER_SIZE(_x, _y) static const struct tee_cryp_obj_type_attrs tee_cryp_obj_secret_value_attrs[] = { { .attr_id = TEE_ATTR_SECRET_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_SECRET, .raw_offs = 0, .raw_size = 0 }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_rsa_pub_key_attrs[] = { { .attr_id = TEE_ATTR_RSA_MODULUS, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_public_key, n) }, { .attr_id = TEE_ATTR_RSA_PUBLIC_EXPONENT, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_public_key, e) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_rsa_keypair_attrs[] = { { .attr_id = TEE_ATTR_RSA_MODULUS, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, n) }, { .attr_id = TEE_ATTR_RSA_PUBLIC_EXPONENT, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, e) }, { .attr_id = TEE_ATTR_RSA_PRIVATE_EXPONENT, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, d) }, { .attr_id = TEE_ATTR_RSA_PRIME1, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, p) }, { .attr_id = TEE_ATTR_RSA_PRIME2, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, q) }, { .attr_id = TEE_ATTR_RSA_EXPONENT1, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, dp) }, { .attr_id = TEE_ATTR_RSA_EXPONENT2, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, dq) }, { .attr_id = TEE_ATTR_RSA_COEFFICIENT, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, qp) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dsa_pub_key_attrs[] = { { .attr_id = TEE_ATTR_DSA_PRIME, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_public_key, p) }, { .attr_id = TEE_ATTR_DSA_SUBPRIME, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_public_key, q) }, { .attr_id = TEE_ATTR_DSA_BASE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_public_key, g) }, { .attr_id = TEE_ATTR_DSA_PUBLIC_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_public_key, y) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dsa_keypair_attrs[] = { { .attr_id = TEE_ATTR_DSA_PRIME, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, p) }, { .attr_id = TEE_ATTR_DSA_SUBPRIME, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, q) }, { .attr_id = TEE_ATTR_DSA_BASE, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, g) }, { .attr_id = TEE_ATTR_DSA_PRIVATE_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, x) }, { .attr_id = TEE_ATTR_DSA_PUBLIC_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, y) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dh_keypair_attrs[] = { { .attr_id = TEE_ATTR_DH_PRIME, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, p) }, { .attr_id = TEE_ATTR_DH_BASE, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, g) }, { .attr_id = TEE_ATTR_DH_PUBLIC_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, y) }, { .attr_id = TEE_ATTR_DH_PRIVATE_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, x) }, { .attr_id = TEE_ATTR_DH_SUBPRIME, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP | TEE_TYPE_ATTR_GEN_KEY_OPT, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, q) }, { .attr_id = TEE_ATTR_DH_X_BITS, .flags = TEE_TYPE_ATTR_GEN_KEY_OPT, .ops_index = ATTR_OPS_INDEX_VALUE, RAW_DATA(struct dh_keypair, xbits) }, }; #if defined(CFG_CRYPTO_HKDF) static const struct tee_cryp_obj_type_attrs tee_cryp_obj_hkdf_ikm_attrs[] = { { .attr_id = TEE_ATTR_HKDF_IKM, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_SECRET, .raw_offs = 0, .raw_size = 0 }, }; #endif #if defined(CFG_CRYPTO_CONCAT_KDF) static const struct tee_cryp_obj_type_attrs tee_cryp_obj_concat_kdf_z_attrs[] = { { .attr_id = TEE_ATTR_CONCAT_KDF_Z, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_SECRET, .raw_offs = 0, .raw_size = 0 }, }; #endif #if defined(CFG_CRYPTO_PBKDF2) static const struct tee_cryp_obj_type_attrs tee_cryp_obj_pbkdf2_passwd_attrs[] = { { .attr_id = TEE_ATTR_PBKDF2_PASSWORD, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_SECRET, .raw_offs = 0, .raw_size = 0 }, }; #endif static const struct tee_cryp_obj_type_attrs tee_cryp_obj_ecc_pub_key_attrs[] = { { .attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_X, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_public_key, x) }, { .attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_Y, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_public_key, y) }, { .attr_id = TEE_ATTR_ECC_CURVE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_VALUE, RAW_DATA(struct ecc_public_key, curve) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_ecc_keypair_attrs[] = { { .attr_id = TEE_ATTR_ECC_PRIVATE_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_keypair, d) }, { .attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_X, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_keypair, x) }, { .attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_Y, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_keypair, y) }, { .attr_id = TEE_ATTR_ECC_CURVE, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_VALUE, RAW_DATA(struct ecc_keypair, curve) }, }; struct tee_cryp_obj_type_props { TEE_ObjectType obj_type; uint16_t min_size; /* may not be smaller than this */ uint16_t max_size; /* may not be larger than this */ uint16_t alloc_size; /* this many bytes are allocated to hold data */ uint8_t quanta; /* may only be an multiple of this */ uint8_t num_type_attrs; const struct tee_cryp_obj_type_attrs *type_attrs; }; #define PROP(obj_type, quanta, min_size, max_size, alloc_size, type_attrs) \ { (obj_type), (min_size), (max_size), (alloc_size), (quanta), \ ARRAY_SIZE(type_attrs), (type_attrs) } static const struct tee_cryp_obj_type_props tee_cryp_obj_props[] = { PROP(TEE_TYPE_AES, 64, 128, 256, /* valid sizes 128, 192, 256 */ 256 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_DES, 56, 56, 56, /* * Valid size 56 without parity, note that we still allocate * for 64 bits since the key is supplied with parity. */ 64 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_DES3, 56, 112, 168, /* * Valid sizes 112, 168 without parity, note that we still * allocate for with space for the parity since the key is * supplied with parity. */ 192 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_MD5, 8, 64, 512, 512 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA1, 8, 80, 512, 512 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA224, 8, 112, 512, 512 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA256, 8, 192, 1024, 1024 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA384, 8, 256, 1024, 1024 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA512, 8, 256, 1024, 1024 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_GENERIC_SECRET, 8, 0, 4096, 4096 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), #if defined(CFG_CRYPTO_HKDF) PROP(TEE_TYPE_HKDF_IKM, 8, 0, 4096, 4096 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_hkdf_ikm_attrs), #endif #if defined(CFG_CRYPTO_CONCAT_KDF) PROP(TEE_TYPE_CONCAT_KDF_Z, 8, 0, 4096, 4096 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_concat_kdf_z_attrs), #endif #if defined(CFG_CRYPTO_PBKDF2) PROP(TEE_TYPE_PBKDF2_PASSWORD, 8, 0, 4096, 4096 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_pbkdf2_passwd_attrs), #endif PROP(TEE_TYPE_RSA_PUBLIC_KEY, 1, 256, CFG_CORE_BIGNUM_MAX_BITS, sizeof(struct rsa_public_key), tee_cryp_obj_rsa_pub_key_attrs), PROP(TEE_TYPE_RSA_KEYPAIR, 1, 256, CFG_CORE_BIGNUM_MAX_BITS, sizeof(struct rsa_keypair), tee_cryp_obj_rsa_keypair_attrs), PROP(TEE_TYPE_DSA_PUBLIC_KEY, 64, 512, 3072, sizeof(struct dsa_public_key), tee_cryp_obj_dsa_pub_key_attrs), PROP(TEE_TYPE_DSA_KEYPAIR, 64, 512, 3072, sizeof(struct dsa_keypair), tee_cryp_obj_dsa_keypair_attrs), PROP(TEE_TYPE_DH_KEYPAIR, 1, 256, 2048, sizeof(struct dh_keypair), tee_cryp_obj_dh_keypair_attrs), PROP(TEE_TYPE_ECDSA_PUBLIC_KEY, 1, 192, 521, sizeof(struct ecc_public_key), tee_cryp_obj_ecc_pub_key_attrs), PROP(TEE_TYPE_ECDSA_KEYPAIR, 1, 192, 521, sizeof(struct ecc_keypair), tee_cryp_obj_ecc_keypair_attrs), PROP(TEE_TYPE_ECDH_PUBLIC_KEY, 1, 192, 521, sizeof(struct ecc_public_key), tee_cryp_obj_ecc_pub_key_attrs), PROP(TEE_TYPE_ECDH_KEYPAIR, 1, 192, 521, sizeof(struct ecc_keypair), tee_cryp_obj_ecc_keypair_attrs), }; struct attr_ops { TEE_Result (*from_user)(void *attr, const void *buffer, size_t size); TEE_Result (*to_user)(void *attr, struct tee_ta_session *sess, void *buffer, uint64_t *size); TEE_Result (*to_binary)(void *attr, void *data, size_t data_len, size_t *offs); bool (*from_binary)(void *attr, const void *data, size_t data_len, size_t *offs); TEE_Result (*from_obj)(void *attr, void *src_attr); void (*free)(void *attr); void (*clear)(void *attr); }; static TEE_Result op_u32_to_binary_helper(uint32_t v, uint8_t *data, size_t data_len, size_t *offs) { uint32_t field; size_t next_offs; if (ADD_OVERFLOW(*offs, sizeof(field), &next_offs)) return TEE_ERROR_OVERFLOW; if (data && next_offs <= data_len) { field = TEE_U32_TO_BIG_ENDIAN(v); memcpy(data + *offs, &field, sizeof(field)); } (*offs) = next_offs; return TEE_SUCCESS; } static bool op_u32_from_binary_helper(uint32_t *v, const uint8_t *data, size_t data_len, size_t *offs) { uint32_t field; if (!data || (*offs + sizeof(field)) > data_len) return false; memcpy(&field, data + *offs, sizeof(field)); *v = TEE_U32_FROM_BIG_ENDIAN(field); (*offs) += sizeof(field); return true; } static TEE_Result op_attr_secret_value_from_user(void *attr, const void *buffer, size_t size) { struct tee_cryp_obj_secret *key = attr; /* Data size has to fit in allocated buffer */ if (size > key->alloc_size) return TEE_ERROR_SECURITY; memcpy(key + 1, buffer, size); key->key_size = size; return TEE_SUCCESS; } static TEE_Result op_attr_secret_value_to_user(void *attr, struct tee_ta_session *sess __unused, void *buffer, uint64_t *size) { TEE_Result res; struct tee_cryp_obj_secret *key = attr; uint64_t s; uint64_t key_size; res = tee_svc_copy_from_user(&s, size, sizeof(s)); if (res != TEE_SUCCESS) return res; key_size = key->key_size; res = tee_svc_copy_to_user(size, &key_size, sizeof(key_size)); if (res != TEE_SUCCESS) return res; if (s < key->key_size || !buffer) return TEE_ERROR_SHORT_BUFFER; return tee_svc_copy_to_user(buffer, key + 1, key->key_size); } static TEE_Result op_attr_secret_value_to_binary(void *attr, void *data, size_t data_len, size_t *offs) { TEE_Result res; struct tee_cryp_obj_secret *key = attr; size_t next_offs; res = op_u32_to_binary_helper(key->key_size, data, data_len, offs); if (res != TEE_SUCCESS) return res; if (ADD_OVERFLOW(*offs, key->key_size, &next_offs)) return TEE_ERROR_OVERFLOW; if (data && next_offs <= data_len) memcpy((uint8_t *)data + *offs, key + 1, key->key_size); (*offs) = next_offs; return TEE_SUCCESS; } static bool op_attr_secret_value_from_binary(void *attr, const void *data, size_t data_len, size_t *offs) { struct tee_cryp_obj_secret *key = attr; uint32_t s; if (!op_u32_from_binary_helper(&s, data, data_len, offs)) return false; if ((*offs + s) > data_len) return false; /* Data size has to fit in allocated buffer */ if (s > key->alloc_size) return false; key->key_size = s; memcpy(key + 1, (const uint8_t *)data + *offs, s); (*offs) += s; return true; } static TEE_Result op_attr_secret_value_from_obj(void *attr, void *src_attr) { struct tee_cryp_obj_secret *key = attr; struct tee_cryp_obj_secret *src_key = src_attr; if (src_key->key_size > key->alloc_size) return TEE_ERROR_BAD_STATE; memcpy(key + 1, src_key + 1, src_key->key_size); key->key_size = src_key->key_size; return TEE_SUCCESS; } static void op_attr_secret_value_clear(void *attr) { struct tee_cryp_obj_secret *key = attr; key->key_size = 0; memset(key + 1, 0, key->alloc_size); } static TEE_Result op_attr_bignum_from_user(void *attr, const void *buffer, size_t size) { struct bignum **bn = attr; return crypto_bignum_bin2bn(buffer, size, *bn); } static TEE_Result op_attr_bignum_to_user(void *attr, struct tee_ta_session *sess, void *buffer, uint64_t *size) { TEE_Result res; struct bignum **bn = attr; uint64_t req_size; uint64_t s; res = tee_svc_copy_from_user(&s, size, sizeof(s)); if (res != TEE_SUCCESS) return res; req_size = crypto_bignum_num_bytes(*bn); res = tee_svc_copy_to_user(size, &req_size, sizeof(req_size)); if (res != TEE_SUCCESS) return res; if (!req_size) return TEE_SUCCESS; if (s < req_size || !buffer) return TEE_ERROR_SHORT_BUFFER; /* Check we can access data using supplied user mode pointer */ res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)buffer, req_size); if (res != TEE_SUCCESS) return res; /* * Write the bignum (wich raw data points to) into an array of * bytes (stored in buffer) */ crypto_bignum_bn2bin(*bn, buffer); return TEE_SUCCESS; } static TEE_Result op_attr_bignum_to_binary(void *attr, void *data, size_t data_len, size_t *offs) { TEE_Result res; struct bignum **bn = attr; uint32_t n = crypto_bignum_num_bytes(*bn); size_t next_offs; res = op_u32_to_binary_helper(n, data, data_len, offs); if (res != TEE_SUCCESS) return res; if (ADD_OVERFLOW(*offs, n, &next_offs)) return TEE_ERROR_OVERFLOW; if (data && next_offs <= data_len) crypto_bignum_bn2bin(*bn, (uint8_t *)data + *offs); (*offs) = next_offs; return TEE_SUCCESS; } static bool op_attr_bignum_from_binary(void *attr, const void *data, size_t data_len, size_t *offs) { struct bignum **bn = attr; uint32_t n; if (!op_u32_from_binary_helper(&n, data, data_len, offs)) return false; if ((*offs + n) > data_len) return false; if (crypto_bignum_bin2bn((const uint8_t *)data + *offs, n, *bn)) return false; (*offs) += n; return true; } static TEE_Result op_attr_bignum_from_obj(void *attr, void *src_attr) { struct bignum **bn = attr; struct bignum **src_bn = src_attr; crypto_bignum_copy(*bn, *src_bn); return TEE_SUCCESS; } static void op_attr_bignum_clear(void *attr) { struct bignum **bn = attr; crypto_bignum_clear(*bn); } static void op_attr_bignum_free(void *attr) { struct bignum **bn = attr; crypto_bignum_free(*bn); *bn = NULL; } static TEE_Result op_attr_value_from_user(void *attr, const void *buffer, size_t size) { uint32_t *v = attr; if (size != sizeof(uint32_t) * 2) return TEE_ERROR_GENERIC; /* "can't happen */ /* Note that only the first value is copied */ memcpy(v, buffer, sizeof(uint32_t)); return TEE_SUCCESS; } static TEE_Result op_attr_value_to_user(void *attr, struct tee_ta_session *sess __unused, void *buffer, uint64_t *size) { TEE_Result res; uint32_t *v = attr; uint64_t s; uint32_t value[2] = { *v }; uint64_t req_size = sizeof(value); res = tee_svc_copy_from_user(&s, size, sizeof(s)); if (res != TEE_SUCCESS) return res; if (s < req_size || !buffer) return TEE_ERROR_SHORT_BUFFER; return tee_svc_copy_to_user(buffer, value, req_size); } static TEE_Result op_attr_value_to_binary(void *attr, void *data, size_t data_len, size_t *offs) { uint32_t *v = attr; return op_u32_to_binary_helper(*v, data, data_len, offs); } static bool op_attr_value_from_binary(void *attr, const void *data, size_t data_len, size_t *offs) { uint32_t *v = attr; return op_u32_from_binary_helper(v, data, data_len, offs); } static TEE_Result op_attr_value_from_obj(void *attr, void *src_attr) { uint32_t *v = attr; uint32_t *src_v = src_attr; *v = *src_v; return TEE_SUCCESS; } static void op_attr_value_clear(void *attr) { uint32_t *v = attr; *v = 0; } static const struct attr_ops attr_ops[] = { [ATTR_OPS_INDEX_SECRET] = { .from_user = op_attr_secret_value_from_user, .to_user = op_attr_secret_value_to_user, .to_binary = op_attr_secret_value_to_binary, .from_binary = op_attr_secret_value_from_binary, .from_obj = op_attr_secret_value_from_obj, .free = op_attr_secret_value_clear, /* not a typo */ .clear = op_attr_secret_value_clear, }, [ATTR_OPS_INDEX_BIGNUM] = { .from_user = op_attr_bignum_from_user, .to_user = op_attr_bignum_to_user, .to_binary = op_attr_bignum_to_binary, .from_binary = op_attr_bignum_from_binary, .from_obj = op_attr_bignum_from_obj, .free = op_attr_bignum_free, .clear = op_attr_bignum_clear, }, [ATTR_OPS_INDEX_VALUE] = { .from_user = op_attr_value_from_user, .to_user = op_attr_value_to_user, .to_binary = op_attr_value_to_binary, .from_binary = op_attr_value_from_binary, .from_obj = op_attr_value_from_obj, .free = op_attr_value_clear, /* not a typo */ .clear = op_attr_value_clear, }, }; TEE_Result syscall_cryp_obj_get_info(unsigned long obj, TEE_ObjectInfo *info) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) goto exit; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) goto exit; res = tee_svc_copy_to_user(info, &o->info, sizeof(o->info)); exit: return res; } TEE_Result syscall_cryp_obj_restrict_usage(unsigned long obj, unsigned long usage) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) goto exit; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) goto exit; o->info.objectUsage &= usage; exit: return res; } static int tee_svc_cryp_obj_find_type_attr_idx( uint32_t attr_id, const struct tee_cryp_obj_type_props *type_props) { size_t n; for (n = 0; n < type_props->num_type_attrs; n++) { if (attr_id == type_props->type_attrs[n].attr_id) return n; } return -1; } static const struct tee_cryp_obj_type_props *tee_svc_find_type_props( TEE_ObjectType obj_type) { size_t n; for (n = 0; n < ARRAY_SIZE(tee_cryp_obj_props); n++) { if (tee_cryp_obj_props[n].obj_type == obj_type) return tee_cryp_obj_props + n; } return NULL; } /* Set an attribute on an object */ static void set_attribute(struct tee_obj *o, const struct tee_cryp_obj_type_props *props, uint32_t attr) { int idx = tee_svc_cryp_obj_find_type_attr_idx(attr, props); if (idx < 0) return; o->have_attrs |= BIT(idx); } /* Get an attribute on an object */ static uint32_t get_attribute(const struct tee_obj *o, const struct tee_cryp_obj_type_props *props, uint32_t attr) { int idx = tee_svc_cryp_obj_find_type_attr_idx(attr, props); if (idx < 0) return 0; return o->have_attrs & BIT(idx); } TEE_Result syscall_cryp_obj_get_attr(unsigned long obj, unsigned long attr_id, void *buffer, uint64_t *size) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; const struct tee_cryp_obj_type_props *type_props; int idx; const struct attr_ops *ops; void *attr; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return TEE_ERROR_ITEM_NOT_FOUND; /* Check that the object is initialized */ if (!(o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED)) return TEE_ERROR_BAD_PARAMETERS; /* Check that getting the attribute is allowed */ if (!(attr_id & TEE_ATTR_BIT_PROTECTED) && !(o->info.objectUsage & TEE_USAGE_EXTRACTABLE)) return TEE_ERROR_BAD_PARAMETERS; type_props = tee_svc_find_type_props(o->info.objectType); if (!type_props) { /* Unknown object type, "can't happen" */ return TEE_ERROR_BAD_STATE; } idx = tee_svc_cryp_obj_find_type_attr_idx(attr_id, type_props); if ((idx < 0) || ((o->have_attrs & (1 << idx)) == 0)) return TEE_ERROR_ITEM_NOT_FOUND; ops = attr_ops + type_props->type_attrs[idx].ops_index; attr = (uint8_t *)o->attr + type_props->type_attrs[idx].raw_offs; return ops->to_user(attr, sess, buffer, size); } void tee_obj_attr_free(struct tee_obj *o) { const struct tee_cryp_obj_type_props *tp; size_t n; if (!o->attr) return; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return; for (n = 0; n < tp->num_type_attrs; n++) { const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n; attr_ops[ta->ops_index].free((uint8_t *)o->attr + ta->raw_offs); } } void tee_obj_attr_clear(struct tee_obj *o) { const struct tee_cryp_obj_type_props *tp; size_t n; if (!o->attr) return; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return; for (n = 0; n < tp->num_type_attrs; n++) { const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n; attr_ops[ta->ops_index].clear((uint8_t *)o->attr + ta->raw_offs); } } TEE_Result tee_obj_attr_to_binary(struct tee_obj *o, void *data, size_t *data_len) { const struct tee_cryp_obj_type_props *tp; size_t n; size_t offs = 0; size_t len = data ? *data_len : 0; TEE_Result res; if (o->info.objectType == TEE_TYPE_DATA) { *data_len = 0; return TEE_SUCCESS; /* pure data object */ } if (!o->attr) return TEE_ERROR_BAD_STATE; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return TEE_ERROR_BAD_STATE; for (n = 0; n < tp->num_type_attrs; n++) { const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n; void *attr = (uint8_t *)o->attr + ta->raw_offs; res = attr_ops[ta->ops_index].to_binary(attr, data, len, &offs); if (res != TEE_SUCCESS) return res; } *data_len = offs; if (data && offs > len) return TEE_ERROR_SHORT_BUFFER; return TEE_SUCCESS; } TEE_Result tee_obj_attr_from_binary(struct tee_obj *o, const void *data, size_t data_len) { const struct tee_cryp_obj_type_props *tp; size_t n; size_t offs = 0; if (o->info.objectType == TEE_TYPE_DATA) return TEE_SUCCESS; /* pure data object */ if (!o->attr) return TEE_ERROR_BAD_STATE; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return TEE_ERROR_BAD_STATE; for (n = 0; n < tp->num_type_attrs; n++) { const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n; void *attr = (uint8_t *)o->attr + ta->raw_offs; if (!attr_ops[ta->ops_index].from_binary(attr, data, data_len, &offs)) return TEE_ERROR_CORRUPT_OBJECT; } return TEE_SUCCESS; } TEE_Result tee_obj_attr_copy_from(struct tee_obj *o, const struct tee_obj *src) { TEE_Result res; const struct tee_cryp_obj_type_props *tp; const struct tee_cryp_obj_type_attrs *ta; size_t n; uint32_t have_attrs = 0; void *attr; void *src_attr; if (o->info.objectType == TEE_TYPE_DATA) return TEE_SUCCESS; /* pure data object */ if (!o->attr) return TEE_ERROR_BAD_STATE; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return TEE_ERROR_BAD_STATE; if (o->info.objectType == src->info.objectType) { have_attrs = src->have_attrs; for (n = 0; n < tp->num_type_attrs; n++) { ta = tp->type_attrs + n; attr = (uint8_t *)o->attr + ta->raw_offs; src_attr = (uint8_t *)src->attr + ta->raw_offs; res = attr_ops[ta->ops_index].from_obj(attr, src_attr); if (res != TEE_SUCCESS) return res; } } else { const struct tee_cryp_obj_type_props *tp_src; int idx; if (o->info.objectType == TEE_TYPE_RSA_PUBLIC_KEY) { if (src->info.objectType != TEE_TYPE_RSA_KEYPAIR) return TEE_ERROR_BAD_PARAMETERS; } else if (o->info.objectType == TEE_TYPE_DSA_PUBLIC_KEY) { if (src->info.objectType != TEE_TYPE_DSA_KEYPAIR) return TEE_ERROR_BAD_PARAMETERS; } else if (o->info.objectType == TEE_TYPE_ECDSA_PUBLIC_KEY) { if (src->info.objectType != TEE_TYPE_ECDSA_KEYPAIR) return TEE_ERROR_BAD_PARAMETERS; } else if (o->info.objectType == TEE_TYPE_ECDH_PUBLIC_KEY) { if (src->info.objectType != TEE_TYPE_ECDH_KEYPAIR) return TEE_ERROR_BAD_PARAMETERS; } else { return TEE_ERROR_BAD_PARAMETERS; } tp_src = tee_svc_find_type_props(src->info.objectType); if (!tp_src) return TEE_ERROR_BAD_STATE; have_attrs = BIT32(tp->num_type_attrs) - 1; for (n = 0; n < tp->num_type_attrs; n++) { ta = tp->type_attrs + n; idx = tee_svc_cryp_obj_find_type_attr_idx(ta->attr_id, tp_src); if (idx < 0) return TEE_ERROR_BAD_STATE; attr = (uint8_t *)o->attr + ta->raw_offs; src_attr = (uint8_t *)src->attr + tp_src->type_attrs[idx].raw_offs; res = attr_ops[ta->ops_index].from_obj(attr, src_attr); if (res != TEE_SUCCESS) return res; } } o->have_attrs = have_attrs; return TEE_SUCCESS; } TEE_Result tee_obj_set_type(struct tee_obj *o, uint32_t obj_type, size_t max_key_size) { TEE_Result res = TEE_SUCCESS; const struct tee_cryp_obj_type_props *type_props; /* Can only set type for newly allocated objs */ if (o->attr) return TEE_ERROR_BAD_STATE; /* * Verify that maxKeySize is supported and find out how * much should be allocated. */ if (obj_type == TEE_TYPE_DATA) { if (max_key_size) return TEE_ERROR_NOT_SUPPORTED; } else { /* Find description of object */ type_props = tee_svc_find_type_props(obj_type); if (!type_props) return TEE_ERROR_NOT_SUPPORTED; /* Check that maxKeySize follows restrictions */ if (max_key_size % type_props->quanta != 0) return TEE_ERROR_NOT_SUPPORTED; if (max_key_size < type_props->min_size) return TEE_ERROR_NOT_SUPPORTED; if (max_key_size > type_props->max_size) return TEE_ERROR_NOT_SUPPORTED; o->attr = calloc(1, type_props->alloc_size); if (!o->attr) return TEE_ERROR_OUT_OF_MEMORY; } /* If we have a key structure, pre-allocate the bignums inside */ switch (obj_type) { case TEE_TYPE_RSA_PUBLIC_KEY: res = crypto_acipher_alloc_rsa_public_key(o->attr, max_key_size); break; case TEE_TYPE_RSA_KEYPAIR: res = crypto_acipher_alloc_rsa_keypair(o->attr, max_key_size); break; case TEE_TYPE_DSA_PUBLIC_KEY: res = crypto_acipher_alloc_dsa_public_key(o->attr, max_key_size); break; case TEE_TYPE_DSA_KEYPAIR: res = crypto_acipher_alloc_dsa_keypair(o->attr, max_key_size); break; case TEE_TYPE_DH_KEYPAIR: res = crypto_acipher_alloc_dh_keypair(o->attr, max_key_size); break; case TEE_TYPE_ECDSA_PUBLIC_KEY: case TEE_TYPE_ECDH_PUBLIC_KEY: res = crypto_acipher_alloc_ecc_public_key(o->attr, max_key_size); break; case TEE_TYPE_ECDSA_KEYPAIR: case TEE_TYPE_ECDH_KEYPAIR: res = crypto_acipher_alloc_ecc_keypair(o->attr, max_key_size); break; default: if (obj_type != TEE_TYPE_DATA) { struct tee_cryp_obj_secret *key = o->attr; key->alloc_size = type_props->alloc_size - sizeof(*key); } break; } if (res != TEE_SUCCESS) return res; o->info.objectType = obj_type; o->info.maxKeySize = max_key_size; o->info.objectUsage = TEE_USAGE_DEFAULT; return TEE_SUCCESS; } TEE_Result syscall_cryp_obj_alloc(unsigned long obj_type, unsigned long max_key_size, uint32_t *obj) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; if (obj_type == TEE_TYPE_DATA) return TEE_ERROR_NOT_SUPPORTED; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; o = tee_obj_alloc(); if (!o) return TEE_ERROR_OUT_OF_MEMORY; res = tee_obj_set_type(o, obj_type, max_key_size); if (res != TEE_SUCCESS) { tee_obj_free(o); return res; } tee_obj_add(to_user_ta_ctx(sess->ctx), o); res = tee_svc_copy_kaddr_to_uref(obj, o); if (res != TEE_SUCCESS) tee_obj_close(to_user_ta_ctx(sess->ctx), o); return res; } TEE_Result syscall_cryp_obj_close(unsigned long obj) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; /* * If it's busy it's used by an operation, a client should never have * this handle. */ if (o->busy) return TEE_ERROR_ITEM_NOT_FOUND; tee_obj_close(to_user_ta_ctx(sess->ctx), o); return TEE_SUCCESS; } TEE_Result syscall_cryp_obj_reset(unsigned long obj) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) == 0) { tee_obj_attr_clear(o); o->info.keySize = 0; o->info.objectUsage = TEE_USAGE_DEFAULT; } else { return TEE_ERROR_BAD_PARAMETERS; } /* the object is no more initialized */ o->info.handleFlags &= ~TEE_HANDLE_FLAG_INITIALIZED; return TEE_SUCCESS; } static TEE_Result copy_in_attrs(struct user_ta_ctx *utc, const struct utee_attribute *usr_attrs, uint32_t attr_count, TEE_Attribute *attrs) { TEE_Result res; uint32_t n; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)usr_attrs, attr_count * sizeof(struct utee_attribute)); if (res != TEE_SUCCESS) return res; for (n = 0; n < attr_count; n++) { attrs[n].attributeID = usr_attrs[n].attribute_id; if (attrs[n].attributeID & TEE_ATTR_BIT_VALUE) { attrs[n].content.value.a = usr_attrs[n].a; attrs[n].content.value.b = usr_attrs[n].b; } else { uintptr_t buf = usr_attrs[n].a; size_t len = usr_attrs[n].b; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, buf, len); if (res != TEE_SUCCESS) return res; attrs[n].content.ref.buffer = (void *)buf; attrs[n].content.ref.length = len; } } return TEE_SUCCESS; } enum attr_usage { ATTR_USAGE_POPULATE, ATTR_USAGE_GENERATE_KEY }; static TEE_Result tee_svc_cryp_check_attr(enum attr_usage usage, const struct tee_cryp_obj_type_props *type_props, const TEE_Attribute *attrs, uint32_t attr_count) { uint32_t required_flag; uint32_t opt_flag; bool all_opt_needed; uint32_t req_attrs = 0; uint32_t opt_grp_attrs = 0; uint32_t attrs_found = 0; size_t n; uint32_t bit; uint32_t flags; int idx; if (usage == ATTR_USAGE_POPULATE) { required_flag = TEE_TYPE_ATTR_REQUIRED; opt_flag = TEE_TYPE_ATTR_OPTIONAL_GROUP; all_opt_needed = true; } else { required_flag = TEE_TYPE_ATTR_GEN_KEY_REQ; opt_flag = TEE_TYPE_ATTR_GEN_KEY_OPT; all_opt_needed = false; } /* * First find out which attributes are required and which belong to * the optional group */ for (n = 0; n < type_props->num_type_attrs; n++) { bit = 1 << n; flags = type_props->type_attrs[n].flags; if (flags & required_flag) req_attrs |= bit; else if (flags & opt_flag) opt_grp_attrs |= bit; } /* * Verify that all required attributes are in place and * that the same attribute isn't repeated. */ for (n = 0; n < attr_count; n++) { idx = tee_svc_cryp_obj_find_type_attr_idx( attrs[n].attributeID, type_props); /* attribute not defined in current object type */ if (idx < 0) return TEE_ERROR_ITEM_NOT_FOUND; bit = 1 << idx; /* attribute not repeated */ if ((attrs_found & bit) != 0) return TEE_ERROR_ITEM_NOT_FOUND; attrs_found |= bit; } /* Required attribute missing */ if ((attrs_found & req_attrs) != req_attrs) return TEE_ERROR_ITEM_NOT_FOUND; /* * If the flag says that "if one of the optional attributes are included * all of them has to be included" this must be checked. */ if (all_opt_needed && (attrs_found & opt_grp_attrs) != 0 && (attrs_found & opt_grp_attrs) != opt_grp_attrs) return TEE_ERROR_ITEM_NOT_FOUND; return TEE_SUCCESS; } static TEE_Result get_ec_key_size(uint32_t curve, size_t *key_size) { switch (curve) { case TEE_ECC_CURVE_NIST_P192: *key_size = 192; break; case TEE_ECC_CURVE_NIST_P224: *key_size = 224; break; case TEE_ECC_CURVE_NIST_P256: *key_size = 256; break; case TEE_ECC_CURVE_NIST_P384: *key_size = 384; break; case TEE_ECC_CURVE_NIST_P521: *key_size = 521; break; default: return TEE_ERROR_NOT_SUPPORTED; } return TEE_SUCCESS; } static TEE_Result tee_svc_cryp_obj_populate_type( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, const TEE_Attribute *attrs, uint32_t attr_count) { TEE_Result res; uint32_t have_attrs = 0; size_t obj_size = 0; size_t n; int idx; const struct attr_ops *ops; void *attr; for (n = 0; n < attr_count; n++) { idx = tee_svc_cryp_obj_find_type_attr_idx( attrs[n].attributeID, type_props); /* attribute not defined in current object type */ if (idx < 0) return TEE_ERROR_ITEM_NOT_FOUND; have_attrs |= BIT32(idx); ops = attr_ops + type_props->type_attrs[idx].ops_index; attr = (uint8_t *)o->attr + type_props->type_attrs[idx].raw_offs; if (attrs[n].attributeID & TEE_ATTR_BIT_VALUE) res = ops->from_user(attr, &attrs[n].content.value, sizeof(attrs[n].content.value)); else res = ops->from_user(attr, attrs[n].content.ref.buffer, attrs[n].content.ref.length); if (res != TEE_SUCCESS) return res; /* * First attr_idx signifies the attribute that gives the size * of the object */ if (type_props->type_attrs[idx].flags & TEE_TYPE_ATTR_SIZE_INDICATOR) { /* * For ECDSA/ECDH we need to translate curve into * object size */ if (attrs[n].attributeID == TEE_ATTR_ECC_CURVE) { res = get_ec_key_size(attrs[n].content.value.a, &obj_size); if (res != TEE_SUCCESS) return res; } else { obj_size += (attrs[n].content.ref.length * 8); } } } /* * We have to do it like this because the parity bits aren't counted * when telling the size of the key in bits. */ if (o->info.objectType == TEE_TYPE_DES || o->info.objectType == TEE_TYPE_DES3) obj_size -= obj_size / 8; /* Exclude parity in size of key */ o->have_attrs = have_attrs; o->info.keySize = obj_size; return TEE_SUCCESS; } TEE_Result syscall_cryp_obj_populate(unsigned long obj, struct utee_attribute *usr_attrs, unsigned long attr_count) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; const struct tee_cryp_obj_type_props *type_props; TEE_Attribute *attrs = NULL; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; /* Must be a transient object */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0) return TEE_ERROR_BAD_PARAMETERS; /* Must not be initialized already */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0) return TEE_ERROR_BAD_PARAMETERS; type_props = tee_svc_find_type_props(o->info.objectType); if (!type_props) return TEE_ERROR_NOT_IMPLEMENTED; size_t alloc_size = 0; if (MUL_OVERFLOW(sizeof(TEE_Attribute), attr_count, &alloc_size)) return TEE_ERROR_OVERFLOW; attrs = malloc(alloc_size); if (!attrs) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_attrs, attr_count, attrs); if (res != TEE_SUCCESS) goto out; res = tee_svc_cryp_check_attr(ATTR_USAGE_POPULATE, type_props, attrs, attr_count); if (res != TEE_SUCCESS) goto out; res = tee_svc_cryp_obj_populate_type(o, type_props, attrs, attr_count); if (res == TEE_SUCCESS) o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; out: free(attrs); return res; } TEE_Result syscall_cryp_obj_copy(unsigned long dst, unsigned long src) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *dst_o; struct tee_obj *src_o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(dst), &dst_o); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(src), &src_o); if (res != TEE_SUCCESS) return res; if ((src_o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; if ((dst_o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0) return TEE_ERROR_BAD_PARAMETERS; if ((dst_o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0) return TEE_ERROR_BAD_PARAMETERS; res = tee_obj_attr_copy_from(dst_o, src_o); if (res != TEE_SUCCESS) return res; dst_o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; dst_o->info.keySize = src_o->info.keySize; dst_o->info.objectUsage = src_o->info.objectUsage; return TEE_SUCCESS; } static TEE_Result tee_svc_obj_generate_key_rsa( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, uint32_t key_size, const TEE_Attribute *params, uint32_t param_count) { TEE_Result res; struct rsa_keypair *key = o->attr; uint32_t e = TEE_U32_TO_BIG_ENDIAN(65537); /* Copy the present attributes into the obj before starting */ res = tee_svc_cryp_obj_populate_type(o, type_props, params, param_count); if (res != TEE_SUCCESS) return res; if (!get_attribute(o, type_props, TEE_ATTR_RSA_PUBLIC_EXPONENT)) crypto_bignum_bin2bn((const uint8_t *)&e, sizeof(e), key->e); res = crypto_acipher_gen_rsa_key(key, key_size); if (res != TEE_SUCCESS) return res; /* Set bits for all known attributes for this object type */ o->have_attrs = (1 << type_props->num_type_attrs) - 1; return TEE_SUCCESS; } static TEE_Result tee_svc_obj_generate_key_dsa( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, uint32_t key_size) { TEE_Result res; res = crypto_acipher_gen_dsa_key(o->attr, key_size); if (res != TEE_SUCCESS) return res; /* Set bits for all known attributes for this object type */ o->have_attrs = (1 << type_props->num_type_attrs) - 1; return TEE_SUCCESS; } static TEE_Result tee_svc_obj_generate_key_dh( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, uint32_t key_size __unused, const TEE_Attribute *params, uint32_t param_count) { TEE_Result res; struct dh_keypair *tee_dh_key; struct bignum *dh_q = NULL; uint32_t dh_xbits = 0; /* Copy the present attributes into the obj before starting */ res = tee_svc_cryp_obj_populate_type(o, type_props, params, param_count); if (res != TEE_SUCCESS) return res; tee_dh_key = (struct dh_keypair *)o->attr; if (get_attribute(o, type_props, TEE_ATTR_DH_SUBPRIME)) dh_q = tee_dh_key->q; if (get_attribute(o, type_props, TEE_ATTR_DH_X_BITS)) dh_xbits = tee_dh_key->xbits; res = crypto_acipher_gen_dh_key(tee_dh_key, dh_q, dh_xbits); if (res != TEE_SUCCESS) return res; /* Set bits for the generated public and private key */ set_attribute(o, type_props, TEE_ATTR_DH_PUBLIC_VALUE); set_attribute(o, type_props, TEE_ATTR_DH_PRIVATE_VALUE); set_attribute(o, type_props, TEE_ATTR_DH_X_BITS); return TEE_SUCCESS; } static TEE_Result tee_svc_obj_generate_key_ecc( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, uint32_t key_size __unused, const TEE_Attribute *params, uint32_t param_count) { TEE_Result res; struct ecc_keypair *tee_ecc_key; /* Copy the present attributes into the obj before starting */ res = tee_svc_cryp_obj_populate_type(o, type_props, params, param_count); if (res != TEE_SUCCESS) return res; tee_ecc_key = (struct ecc_keypair *)o->attr; res = crypto_acipher_gen_ecc_key(tee_ecc_key); if (res != TEE_SUCCESS) return res; /* Set bits for the generated public and private key */ set_attribute(o, type_props, TEE_ATTR_ECC_PRIVATE_VALUE); set_attribute(o, type_props, TEE_ATTR_ECC_PUBLIC_VALUE_X); set_attribute(o, type_props, TEE_ATTR_ECC_PUBLIC_VALUE_Y); set_attribute(o, type_props, TEE_ATTR_ECC_CURVE); return TEE_SUCCESS; } TEE_Result syscall_obj_generate_key(unsigned long obj, unsigned long key_size, const struct utee_attribute *usr_params, unsigned long param_count) { TEE_Result res; struct tee_ta_session *sess; const struct tee_cryp_obj_type_props *type_props; struct tee_obj *o; struct tee_cryp_obj_secret *key; size_t byte_size; TEE_Attribute *params = NULL; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; /* Must be a transient object */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0) return TEE_ERROR_BAD_STATE; /* Must not be initialized already */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0) return TEE_ERROR_BAD_STATE; /* Find description of object */ type_props = tee_svc_find_type_props(o->info.objectType); if (!type_props) return TEE_ERROR_NOT_SUPPORTED; /* Check that maxKeySize follows restrictions */ if (key_size % type_props->quanta != 0) return TEE_ERROR_NOT_SUPPORTED; if (key_size < type_props->min_size) return TEE_ERROR_NOT_SUPPORTED; if (key_size > type_props->max_size) return TEE_ERROR_NOT_SUPPORTED; params = malloc(sizeof(TEE_Attribute) * param_count); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_params, param_count, params); if (res != TEE_SUCCESS) goto out; res = tee_svc_cryp_check_attr(ATTR_USAGE_GENERATE_KEY, type_props, params, param_count); if (res != TEE_SUCCESS) goto out; switch (o->info.objectType) { case TEE_TYPE_AES: case TEE_TYPE_DES: case TEE_TYPE_DES3: case TEE_TYPE_HMAC_MD5: case TEE_TYPE_HMAC_SHA1: case TEE_TYPE_HMAC_SHA224: case TEE_TYPE_HMAC_SHA256: case TEE_TYPE_HMAC_SHA384: case TEE_TYPE_HMAC_SHA512: case TEE_TYPE_GENERIC_SECRET: byte_size = key_size / 8; /* * We have to do it like this because the parity bits aren't * counted when telling the size of the key in bits. */ if (o->info.objectType == TEE_TYPE_DES || o->info.objectType == TEE_TYPE_DES3) { byte_size = (key_size + key_size / 7) / 8; } key = (struct tee_cryp_obj_secret *)o->attr; if (byte_size > key->alloc_size) { res = TEE_ERROR_EXCESS_DATA; goto out; } res = crypto_rng_read((void *)(key + 1), byte_size); if (res != TEE_SUCCESS) goto out; key->key_size = byte_size; /* Set bits for all known attributes for this object type */ o->have_attrs = (1 << type_props->num_type_attrs) - 1; break; case TEE_TYPE_RSA_KEYPAIR: res = tee_svc_obj_generate_key_rsa(o, type_props, key_size, params, param_count); if (res != TEE_SUCCESS) goto out; break; case TEE_TYPE_DSA_KEYPAIR: res = tee_svc_obj_generate_key_dsa(o, type_props, key_size); if (res != TEE_SUCCESS) goto out; break; case TEE_TYPE_DH_KEYPAIR: res = tee_svc_obj_generate_key_dh(o, type_props, key_size, params, param_count); if (res != TEE_SUCCESS) goto out; break; case TEE_TYPE_ECDSA_KEYPAIR: case TEE_TYPE_ECDH_KEYPAIR: res = tee_svc_obj_generate_key_ecc(o, type_props, key_size, params, param_count); if (res != TEE_SUCCESS) goto out; break; default: res = TEE_ERROR_BAD_FORMAT; } out: free(params); if (res == TEE_SUCCESS) { o->info.keySize = key_size; o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; } return res; } static TEE_Result tee_svc_cryp_get_state(struct tee_ta_session *sess, uint32_t state_id, struct tee_cryp_state **state) { struct tee_cryp_state *s; struct user_ta_ctx *utc = to_user_ta_ctx(sess->ctx); TAILQ_FOREACH(s, &utc->cryp_states, link) { if (state_id == (vaddr_t)s) { *state = s; return TEE_SUCCESS; } } return TEE_ERROR_BAD_PARAMETERS; } static void cryp_state_free(struct user_ta_ctx *utc, struct tee_cryp_state *cs) { struct tee_obj *o; if (tee_obj_get(utc, cs->key1, &o) == TEE_SUCCESS) tee_obj_close(utc, o); if (tee_obj_get(utc, cs->key2, &o) == TEE_SUCCESS) tee_obj_close(utc, o); TAILQ_REMOVE(&utc->cryp_states, cs, link); if (cs->ctx_finalize != NULL) cs->ctx_finalize(cs->ctx, cs->algo); switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_CIPHER: crypto_cipher_free_ctx(cs->ctx, cs->algo); break; case TEE_OPERATION_AE: crypto_authenc_free_ctx(cs->ctx, cs->algo); break; case TEE_OPERATION_DIGEST: crypto_hash_free_ctx(cs->ctx, cs->algo); break; case TEE_OPERATION_MAC: crypto_mac_free_ctx(cs->ctx, cs->algo); break; default: assert(!cs->ctx); } free(cs); } static TEE_Result tee_svc_cryp_check_key_type(const struct tee_obj *o, uint32_t algo, TEE_OperationMode mode) { uint32_t req_key_type; uint32_t req_key_type2 = 0; switch (TEE_ALG_GET_MAIN_ALG(algo)) { case TEE_MAIN_ALGO_MD5: req_key_type = TEE_TYPE_HMAC_MD5; break; case TEE_MAIN_ALGO_SHA1: req_key_type = TEE_TYPE_HMAC_SHA1; break; case TEE_MAIN_ALGO_SHA224: req_key_type = TEE_TYPE_HMAC_SHA224; break; case TEE_MAIN_ALGO_SHA256: req_key_type = TEE_TYPE_HMAC_SHA256; break; case TEE_MAIN_ALGO_SHA384: req_key_type = TEE_TYPE_HMAC_SHA384; break; case TEE_MAIN_ALGO_SHA512: req_key_type = TEE_TYPE_HMAC_SHA512; break; case TEE_MAIN_ALGO_AES: req_key_type = TEE_TYPE_AES; break; case TEE_MAIN_ALGO_DES: req_key_type = TEE_TYPE_DES; break; case TEE_MAIN_ALGO_DES3: req_key_type = TEE_TYPE_DES3; break; case TEE_MAIN_ALGO_RSA: req_key_type = TEE_TYPE_RSA_KEYPAIR; if (mode == TEE_MODE_ENCRYPT || mode == TEE_MODE_VERIFY) req_key_type2 = TEE_TYPE_RSA_PUBLIC_KEY; break; case TEE_MAIN_ALGO_DSA: req_key_type = TEE_TYPE_DSA_KEYPAIR; if (mode == TEE_MODE_ENCRYPT || mode == TEE_MODE_VERIFY) req_key_type2 = TEE_TYPE_DSA_PUBLIC_KEY; break; case TEE_MAIN_ALGO_DH: req_key_type = TEE_TYPE_DH_KEYPAIR; break; case TEE_MAIN_ALGO_ECDSA: req_key_type = TEE_TYPE_ECDSA_KEYPAIR; if (mode == TEE_MODE_VERIFY) req_key_type2 = TEE_TYPE_ECDSA_PUBLIC_KEY; break; case TEE_MAIN_ALGO_ECDH: req_key_type = TEE_TYPE_ECDH_KEYPAIR; break; #if defined(CFG_CRYPTO_HKDF) case TEE_MAIN_ALGO_HKDF: req_key_type = TEE_TYPE_HKDF_IKM; break; #endif #if defined(CFG_CRYPTO_CONCAT_KDF) case TEE_MAIN_ALGO_CONCAT_KDF: req_key_type = TEE_TYPE_CONCAT_KDF_Z; break; #endif #if defined(CFG_CRYPTO_PBKDF2) case TEE_MAIN_ALGO_PBKDF2: req_key_type = TEE_TYPE_PBKDF2_PASSWORD; break; #endif default: return TEE_ERROR_BAD_PARAMETERS; } if (req_key_type != o->info.objectType && req_key_type2 != o->info.objectType) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } TEE_Result syscall_cryp_state_alloc(unsigned long algo, unsigned long mode, unsigned long key1, unsigned long key2, uint32_t *state) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; struct tee_obj *o1 = NULL; struct tee_obj *o2 = NULL; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); if (key1 != 0) { res = tee_obj_get(utc, tee_svc_uref_to_vaddr(key1), &o1); if (res != TEE_SUCCESS) return res; if (o1->busy) return TEE_ERROR_BAD_PARAMETERS; res = tee_svc_cryp_check_key_type(o1, algo, mode); if (res != TEE_SUCCESS) return res; } if (key2 != 0) { res = tee_obj_get(utc, tee_svc_uref_to_vaddr(key2), &o2); if (res != TEE_SUCCESS) return res; if (o2->busy) return TEE_ERROR_BAD_PARAMETERS; res = tee_svc_cryp_check_key_type(o2, algo, mode); if (res != TEE_SUCCESS) return res; } cs = calloc(1, sizeof(struct tee_cryp_state)); if (!cs) return TEE_ERROR_OUT_OF_MEMORY; TAILQ_INSERT_TAIL(&utc->cryp_states, cs, link); cs->algo = algo; cs->mode = mode; switch (TEE_ALG_GET_CLASS(algo)) { case TEE_OPERATION_EXTENSION: #ifdef CFG_CRYPTO_RSASSA_NA1 if (algo == TEE_ALG_RSASSA_PKCS1_V1_5) goto rsassa_na1; #endif res = TEE_ERROR_NOT_SUPPORTED; break; case TEE_OPERATION_CIPHER: if ((algo == TEE_ALG_AES_XTS && (key1 == 0 || key2 == 0)) || (algo != TEE_ALG_AES_XTS && (key1 == 0 || key2 != 0))) { res = TEE_ERROR_BAD_PARAMETERS; } else { res = crypto_cipher_alloc_ctx(&cs->ctx, algo); if (res != TEE_SUCCESS) break; } break; case TEE_OPERATION_AE: if (key1 == 0 || key2 != 0) { res = TEE_ERROR_BAD_PARAMETERS; } else { res = crypto_authenc_alloc_ctx(&cs->ctx, algo); if (res != TEE_SUCCESS) break; } break; case TEE_OPERATION_MAC: if (key1 == 0 || key2 != 0) { res = TEE_ERROR_BAD_PARAMETERS; } else { res = crypto_mac_alloc_ctx(&cs->ctx, algo); if (res != TEE_SUCCESS) break; } break; case TEE_OPERATION_DIGEST: if (key1 != 0 || key2 != 0) { res = TEE_ERROR_BAD_PARAMETERS; } else { res = crypto_hash_alloc_ctx(&cs->ctx, algo); if (res != TEE_SUCCESS) break; } break; case TEE_OPERATION_ASYMMETRIC_CIPHER: case TEE_OPERATION_ASYMMETRIC_SIGNATURE: rsassa_na1: __maybe_unused if (key1 == 0 || key2 != 0) res = TEE_ERROR_BAD_PARAMETERS; break; case TEE_OPERATION_KEY_DERIVATION: if (key1 == 0 || key2 != 0) res = TEE_ERROR_BAD_PARAMETERS; break; default: res = TEE_ERROR_NOT_SUPPORTED; break; } if (res != TEE_SUCCESS) goto out; res = tee_svc_copy_kaddr_to_uref(state, cs); if (res != TEE_SUCCESS) goto out; /* Register keys */ if (o1 != NULL) { o1->busy = true; cs->key1 = (vaddr_t)o1; } if (o2 != NULL) { o2->busy = true; cs->key2 = (vaddr_t)o2; } out: if (res != TEE_SUCCESS) cryp_state_free(utc, cs); return res; } TEE_Result syscall_cryp_state_copy(unsigned long dst, unsigned long src) { TEE_Result res; struct tee_cryp_state *cs_dst; struct tee_cryp_state *cs_src; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(dst), &cs_dst); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(src), &cs_src); if (res != TEE_SUCCESS) return res; if (cs_dst->algo != cs_src->algo || cs_dst->mode != cs_src->mode) return TEE_ERROR_BAD_PARAMETERS; switch (TEE_ALG_GET_CLASS(cs_src->algo)) { case TEE_OPERATION_CIPHER: crypto_cipher_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo); break; case TEE_OPERATION_AE: crypto_authenc_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo); break; case TEE_OPERATION_DIGEST: crypto_hash_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo); break; case TEE_OPERATION_MAC: crypto_mac_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo); break; default: return TEE_ERROR_BAD_STATE; } return TEE_SUCCESS; } void tee_svc_cryp_free_states(struct user_ta_ctx *utc) { struct tee_cryp_state_head *states = &utc->cryp_states; while (!TAILQ_EMPTY(states)) cryp_state_free(utc, TAILQ_FIRST(states)); } TEE_Result syscall_cryp_state_free(unsigned long state) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; cryp_state_free(to_user_ta_ctx(sess->ctx), cs); return TEE_SUCCESS; } TEE_Result syscall_hash_init(unsigned long state, const void *iv __maybe_unused, size_t iv_len __maybe_unused) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_DIGEST: res = crypto_hash_init(cs->ctx, cs->algo); if (res != TEE_SUCCESS) return res; break; case TEE_OPERATION_MAC: { struct tee_obj *o; struct tee_cryp_obj_secret *key; res = tee_obj_get(to_user_ta_ctx(sess->ctx), cs->key1, &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; key = (struct tee_cryp_obj_secret *)o->attr; res = crypto_mac_init(cs->ctx, cs->algo, (void *)(key + 1), key->key_size); if (res != TEE_SUCCESS) return res; break; } default: return TEE_ERROR_BAD_PARAMETERS; } return TEE_SUCCESS; } TEE_Result syscall_hash_update(unsigned long state, const void *chunk, size_t chunk_size) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; /* No data, but size provided isn't valid parameters. */ if (!chunk && chunk_size) return TEE_ERROR_BAD_PARAMETERS; /* Zero length hash is valid, but nothing we need to do. */ if (!chunk_size) return TEE_SUCCESS; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)chunk, chunk_size); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_DIGEST: res = crypto_hash_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; break; case TEE_OPERATION_MAC: res = crypto_mac_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; break; default: return TEE_ERROR_BAD_PARAMETERS; } return TEE_SUCCESS; } TEE_Result syscall_hash_final(unsigned long state, const void *chunk, size_t chunk_size, void *hash, uint64_t *hash_len) { TEE_Result res, res2; size_t hash_size; uint64_t hlen; struct tee_cryp_state *cs; struct tee_ta_session *sess; /* No data, but size provided isn't valid parameters. */ if (!chunk && chunk_size) return TEE_ERROR_BAD_PARAMETERS; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)chunk, chunk_size); if (res != TEE_SUCCESS) return res; res = tee_svc_copy_from_user(&hlen, hash_len, sizeof(hlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)hash, hlen); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_DIGEST: res = tee_hash_get_digest_size(cs->algo, &hash_size); if (res != TEE_SUCCESS) return res; if (*hash_len < hash_size) { res = TEE_ERROR_SHORT_BUFFER; goto out; } if (chunk_size) { res = crypto_hash_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; } res = crypto_hash_final(cs->ctx, cs->algo, hash, hash_size); if (res != TEE_SUCCESS) return res; break; case TEE_OPERATION_MAC: res = tee_mac_get_digest_size(cs->algo, &hash_size); if (res != TEE_SUCCESS) return res; if (*hash_len < hash_size) { res = TEE_ERROR_SHORT_BUFFER; goto out; } if (chunk_size) { res = crypto_mac_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; } res = crypto_mac_final(cs->ctx, cs->algo, hash, hash_size); if (res != TEE_SUCCESS) return res; break; default: return TEE_ERROR_BAD_PARAMETERS; } out: hlen = hash_size; res2 = tee_svc_copy_to_user(hash_len, &hlen, sizeof(*hash_len)); if (res2 != TEE_SUCCESS) return res2; return res; } TEE_Result syscall_cipher_init(unsigned long state, const void *iv, size_t iv_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; struct tee_obj *o; struct tee_cryp_obj_secret *key1; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) iv, iv_len); if (res != TEE_SUCCESS) return res; res = tee_obj_get(utc, cs->key1, &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; key1 = o->attr; if (tee_obj_get(utc, cs->key2, &o) == TEE_SUCCESS) { struct tee_cryp_obj_secret *key2 = o->attr; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; res = crypto_cipher_init(cs->ctx, cs->algo, cs->mode, (uint8_t *)(key1 + 1), key1->key_size, (uint8_t *)(key2 + 1), key2->key_size, iv, iv_len); } else { res = crypto_cipher_init(cs->ctx, cs->algo, cs->mode, (uint8_t *)(key1 + 1), key1->key_size, NULL, 0, iv, iv_len); } if (res != TEE_SUCCESS) return res; cs->ctx_finalize = crypto_cipher_final; return TEE_SUCCESS; } static TEE_Result tee_svc_cipher_update_helper(unsigned long state, bool last_block, const void *src, size_t src_len, void *dst, uint64_t *dst_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)src, src_len); if (res != TEE_SUCCESS) return res; if (!dst_len) { dlen = 0; } else { res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)dst, dlen); if (res != TEE_SUCCESS) return res; } if (dlen < src_len) { res = TEE_ERROR_SHORT_BUFFER; goto out; } if (src_len > 0) { /* Permit src_len == 0 to finalize the operation */ res = tee_do_cipher_update(cs->ctx, cs->algo, cs->mode, last_block, src, src_len, dst); } if (last_block && cs->ctx_finalize != NULL) { cs->ctx_finalize(cs->ctx, cs->algo); cs->ctx_finalize = NULL; } out: if ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) && dst_len != NULL) { TEE_Result res2; dlen = src_len; res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) res = res2; } return res; } TEE_Result syscall_cipher_update(unsigned long state, const void *src, size_t src_len, void *dst, uint64_t *dst_len) { return tee_svc_cipher_update_helper(state, false /* last_block */, src, src_len, dst, dst_len); } TEE_Result syscall_cipher_final(unsigned long state, const void *src, size_t src_len, void *dst, uint64_t *dst_len) { return tee_svc_cipher_update_helper(state, true /* last_block */, src, src_len, dst, dst_len); } #if defined(CFG_CRYPTO_HKDF) static TEE_Result get_hkdf_params(const TEE_Attribute *params, uint32_t param_count, void **salt, size_t *salt_len, void **info, size_t *info_len, size_t *okm_len) { size_t n; enum { SALT = 0x1, LENGTH = 0x2, INFO = 0x4 }; uint8_t found = 0; *salt = *info = NULL; *salt_len = *info_len = *okm_len = 0; for (n = 0; n < param_count; n++) { switch (params[n].attributeID) { case TEE_ATTR_HKDF_SALT: if (!(found & SALT)) { *salt = params[n].content.ref.buffer; *salt_len = params[n].content.ref.length; found |= SALT; } break; case TEE_ATTR_HKDF_OKM_LENGTH: if (!(found & LENGTH)) { *okm_len = params[n].content.value.a; found |= LENGTH; } break; case TEE_ATTR_HKDF_INFO: if (!(found & INFO)) { *info = params[n].content.ref.buffer; *info_len = params[n].content.ref.length; found |= INFO; } break; default: /* Unexpected attribute */ return TEE_ERROR_BAD_PARAMETERS; } } if (!(found & LENGTH)) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } #endif #if defined(CFG_CRYPTO_CONCAT_KDF) static TEE_Result get_concat_kdf_params(const TEE_Attribute *params, uint32_t param_count, void **other_info, size_t *other_info_len, size_t *derived_key_len) { size_t n; enum { LENGTH = 0x1, INFO = 0x2 }; uint8_t found = 0; *other_info = NULL; *other_info_len = *derived_key_len = 0; for (n = 0; n < param_count; n++) { switch (params[n].attributeID) { case TEE_ATTR_CONCAT_KDF_OTHER_INFO: if (!(found & INFO)) { *other_info = params[n].content.ref.buffer; *other_info_len = params[n].content.ref.length; found |= INFO; } break; case TEE_ATTR_CONCAT_KDF_DKM_LENGTH: if (!(found & LENGTH)) { *derived_key_len = params[n].content.value.a; found |= LENGTH; } break; default: /* Unexpected attribute */ return TEE_ERROR_BAD_PARAMETERS; } } if (!(found & LENGTH)) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } #endif #if defined(CFG_CRYPTO_PBKDF2) static TEE_Result get_pbkdf2_params(const TEE_Attribute *params, uint32_t param_count, void **salt, size_t *salt_len, size_t *derived_key_len, size_t *iteration_count) { size_t n; enum { SALT = 0x1, LENGTH = 0x2, COUNT = 0x4 }; uint8_t found = 0; *salt = NULL; *salt_len = *derived_key_len = *iteration_count = 0; for (n = 0; n < param_count; n++) { switch (params[n].attributeID) { case TEE_ATTR_PBKDF2_SALT: if (!(found & SALT)) { *salt = params[n].content.ref.buffer; *salt_len = params[n].content.ref.length; found |= SALT; } break; case TEE_ATTR_PBKDF2_DKM_LENGTH: if (!(found & LENGTH)) { *derived_key_len = params[n].content.value.a; found |= LENGTH; } break; case TEE_ATTR_PBKDF2_ITERATION_COUNT: if (!(found & COUNT)) { *iteration_count = params[n].content.value.a; found |= COUNT; } break; default: /* Unexpected attribute */ return TEE_ERROR_BAD_PARAMETERS; } } if ((found & (LENGTH|COUNT)) != (LENGTH|COUNT)) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } #endif TEE_Result syscall_cryp_derive_key(unsigned long state, const struct utee_attribute *usr_params, unsigned long param_count, unsigned long derived_key) { TEE_Result res = TEE_ERROR_NOT_SUPPORTED; struct tee_ta_session *sess; struct tee_obj *ko; struct tee_obj *so; struct tee_cryp_state *cs; struct tee_cryp_obj_secret *sk; const struct tee_cryp_obj_type_props *type_props; TEE_Attribute *params = NULL; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; params = malloc(sizeof(TEE_Attribute) * param_count); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(utc, usr_params, param_count, params); if (res != TEE_SUCCESS) goto out; /* Get key set in operation */ res = tee_obj_get(utc, cs->key1, &ko); if (res != TEE_SUCCESS) goto out; res = tee_obj_get(utc, tee_svc_uref_to_vaddr(derived_key), &so); if (res != TEE_SUCCESS) goto out; /* Find information needed about the object to initialize */ sk = so->attr; /* Find description of object */ type_props = tee_svc_find_type_props(so->info.objectType); if (!type_props) { res = TEE_ERROR_NOT_SUPPORTED; goto out; } if (cs->algo == TEE_ALG_DH_DERIVE_SHARED_SECRET) { size_t alloc_size; struct bignum *pub; struct bignum *ss; if (param_count != 1 || params[0].attributeID != TEE_ATTR_DH_PUBLIC_VALUE) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } alloc_size = params[0].content.ref.length * 8; pub = crypto_bignum_allocate(alloc_size); ss = crypto_bignum_allocate(alloc_size); if (pub && ss) { crypto_bignum_bin2bn(params[0].content.ref.buffer, params[0].content.ref.length, pub); res = crypto_acipher_dh_shared_secret(ko->attr, pub, ss); if (res == TEE_SUCCESS) { sk->key_size = crypto_bignum_num_bytes(ss); crypto_bignum_bn2bin(ss, (uint8_t *)(sk + 1)); so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } else { res = TEE_ERROR_OUT_OF_MEMORY; } crypto_bignum_free(pub); crypto_bignum_free(ss); } else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_ECDH) { size_t alloc_size; struct ecc_public_key key_public; uint8_t *pt_secret; unsigned long pt_secret_len; if (param_count != 2 || params[0].attributeID != TEE_ATTR_ECC_PUBLIC_VALUE_X || params[1].attributeID != TEE_ATTR_ECC_PUBLIC_VALUE_Y) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } switch (cs->algo) { case TEE_ALG_ECDH_P192: alloc_size = 192; break; case TEE_ALG_ECDH_P224: alloc_size = 224; break; case TEE_ALG_ECDH_P256: alloc_size = 256; break; case TEE_ALG_ECDH_P384: alloc_size = 384; break; case TEE_ALG_ECDH_P521: alloc_size = 521; break; default: res = TEE_ERROR_NOT_IMPLEMENTED; goto out; } /* Create the public key */ res = crypto_acipher_alloc_ecc_public_key(&key_public, alloc_size); if (res != TEE_SUCCESS) goto out; key_public.curve = ((struct ecc_keypair *)ko->attr)->curve; crypto_bignum_bin2bn(params[0].content.ref.buffer, params[0].content.ref.length, key_public.x); crypto_bignum_bin2bn(params[1].content.ref.buffer, params[1].content.ref.length, key_public.y); pt_secret = (uint8_t *)(sk + 1); pt_secret_len = sk->alloc_size; res = crypto_acipher_ecc_shared_secret(ko->attr, &key_public, pt_secret, &pt_secret_len); if (res == TEE_SUCCESS) { sk->key_size = pt_secret_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } /* free the public key */ crypto_acipher_free_ecc_public_key(&key_public); } #if defined(CFG_CRYPTO_HKDF) else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_HKDF) { void *salt, *info; size_t salt_len, info_len, okm_len; uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo); struct tee_cryp_obj_secret *ik = ko->attr; const uint8_t *ikm = (const uint8_t *)(ik + 1); res = get_hkdf_params(params, param_count, &salt, &salt_len, &info, &info_len, &okm_len); if (res != TEE_SUCCESS) goto out; /* Requested size must fit into the output object's buffer */ if (okm_len > ik->alloc_size) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_cryp_hkdf(hash_id, ikm, ik->key_size, salt, salt_len, info, info_len, (uint8_t *)(sk + 1), okm_len); if (res == TEE_SUCCESS) { sk->key_size = okm_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } #endif #if defined(CFG_CRYPTO_CONCAT_KDF) else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_CONCAT_KDF) { void *info; size_t info_len, derived_key_len; uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo); struct tee_cryp_obj_secret *ss = ko->attr; const uint8_t *shared_secret = (const uint8_t *)(ss + 1); res = get_concat_kdf_params(params, param_count, &info, &info_len, &derived_key_len); if (res != TEE_SUCCESS) goto out; /* Requested size must fit into the output object's buffer */ if (derived_key_len > ss->alloc_size) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_cryp_concat_kdf(hash_id, shared_secret, ss->key_size, info, info_len, (uint8_t *)(sk + 1), derived_key_len); if (res == TEE_SUCCESS) { sk->key_size = derived_key_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } #endif #if defined(CFG_CRYPTO_PBKDF2) else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_PBKDF2) { void *salt; size_t salt_len, iteration_count, derived_key_len; uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo); struct tee_cryp_obj_secret *ss = ko->attr; const uint8_t *password = (const uint8_t *)(ss + 1); res = get_pbkdf2_params(params, param_count, &salt, &salt_len, &derived_key_len, &iteration_count); if (res != TEE_SUCCESS) goto out; /* Requested size must fit into the output object's buffer */ if (derived_key_len > ss->alloc_size) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_cryp_pbkdf2(hash_id, password, ss->key_size, salt, salt_len, iteration_count, (uint8_t *)(sk + 1), derived_key_len); if (res == TEE_SUCCESS) { sk->key_size = derived_key_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } #endif else res = TEE_ERROR_NOT_SUPPORTED; out: free(params); return res; } TEE_Result syscall_cryp_random_number_generate(void *buf, size_t blen) { TEE_Result res; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)buf, blen); if (res != TEE_SUCCESS) return res; res = crypto_rng_read(buf, blen); if (res != TEE_SUCCESS) return res; return res; } TEE_Result syscall_authenc_init(unsigned long state, const void *nonce, size_t nonce_len, size_t tag_len, size_t aad_len, size_t payload_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; struct tee_obj *o; struct tee_cryp_obj_secret *key; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), cs->key1, &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; key = o->attr; res = crypto_authenc_init(cs->ctx, cs->algo, cs->mode, (uint8_t *)(key + 1), key->key_size, nonce, nonce_len, tag_len, aad_len, payload_len); if (res != TEE_SUCCESS) return res; cs->ctx_finalize = (tee_cryp_ctx_finalize_func_t)crypto_authenc_final; return TEE_SUCCESS; } TEE_Result syscall_authenc_update_aad(unsigned long state, const void *aad_data, size_t aad_data_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) aad_data, aad_data_len); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = crypto_authenc_update_aad(cs->ctx, cs->algo, cs->mode, aad_data, aad_data_len); if (res != TEE_SUCCESS) return res; return TEE_SUCCESS; } TEE_Result syscall_authenc_update_payload(unsigned long state, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen; size_t tmp_dlen; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) src_data, src_len); if (res != TEE_SUCCESS) return res; res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)dst_data, dlen); if (res != TEE_SUCCESS) return res; if (dlen < src_len) { res = TEE_ERROR_SHORT_BUFFER; goto out; } tmp_dlen = dlen; res = crypto_authenc_update_payload(cs->ctx, cs->algo, cs->mode, src_data, src_len, dst_data, &tmp_dlen); dlen = tmp_dlen; out: if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) { TEE_Result res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) res = res2; } return res; } TEE_Result syscall_authenc_enc_final(unsigned long state, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len, void *tag, uint64_t *tag_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen; uint64_t tlen = 0; size_t tmp_dlen; size_t tmp_tlen; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; if (cs->mode != TEE_MODE_ENCRYPT) return TEE_ERROR_BAD_PARAMETERS; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)src_data, src_len); if (res != TEE_SUCCESS) return res; if (!dst_len) { dlen = 0; } else { res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)dst_data, dlen); if (res != TEE_SUCCESS) return res; } if (dlen < src_len) { res = TEE_ERROR_SHORT_BUFFER; goto out; } res = tee_svc_copy_from_user(&tlen, tag_len, sizeof(tlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)tag, tlen); if (res != TEE_SUCCESS) return res; tmp_dlen = dlen; tmp_tlen = tlen; res = crypto_authenc_enc_final(cs->ctx, cs->algo, src_data, src_len, dst_data, &tmp_dlen, tag, &tmp_tlen); dlen = tmp_dlen; tlen = tmp_tlen; out: if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) { TEE_Result res2; if (dst_len != NULL) { res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) return res2; } res2 = tee_svc_copy_to_user(tag_len, &tlen, sizeof(*tag_len)); if (res2 != TEE_SUCCESS) return res2; } return res; } TEE_Result syscall_authenc_dec_final(unsigned long state, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len, const void *tag, size_t tag_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen; size_t tmp_dlen; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; if (cs->mode != TEE_MODE_DECRYPT) return TEE_ERROR_BAD_PARAMETERS; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)src_data, src_len); if (res != TEE_SUCCESS) return res; if (!dst_len) { dlen = 0; } else { res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)dst_data, dlen); if (res != TEE_SUCCESS) return res; } if (dlen < src_len) { res = TEE_ERROR_SHORT_BUFFER; goto out; } res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)tag, tag_len); if (res != TEE_SUCCESS) return res; tmp_dlen = dlen; res = crypto_authenc_dec_final(cs->ctx, cs->algo, src_data, src_len, dst_data, &tmp_dlen, tag, tag_len); dlen = tmp_dlen; out: if ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) && dst_len != NULL) { TEE_Result res2; res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) return res2; } return res; } static int pkcs1_get_salt_len(const TEE_Attribute *params, uint32_t num_params, size_t default_len) { size_t n; assert(default_len < INT_MAX); for (n = 0; n < num_params; n++) { if (params[n].attributeID == TEE_ATTR_RSA_PSS_SALT_LENGTH) { if (params[n].content.value.a < INT_MAX) return params[n].content.value.a; break; } } /* * If salt length isn't provided use the default value which is * the length of the digest. */ return default_len; } TEE_Result syscall_asymm_operate(unsigned long state, const struct utee_attribute *usr_params, size_t num_params, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen64; size_t dlen; struct tee_obj *o; void *label = NULL; size_t label_len = 0; size_t n; int salt_len; TEE_Attribute *params = NULL; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights( utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) src_data, src_len); if (res != TEE_SUCCESS) return res; res = tee_svc_copy_from_user(&dlen64, dst_len, sizeof(dlen64)); if (res != TEE_SUCCESS) return res; dlen = dlen64; res = tee_mmu_check_access_rights( utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) dst_data, dlen); if (res != TEE_SUCCESS) return res; params = malloc(sizeof(TEE_Attribute) * num_params); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(utc, usr_params, num_params, params); if (res != TEE_SUCCESS) goto out; res = tee_obj_get(utc, cs->key1, &o); if (res != TEE_SUCCESS) goto out; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) { res = TEE_ERROR_GENERIC; goto out; } switch (cs->algo) { case TEE_ALG_RSA_NOPAD: if (cs->mode == TEE_MODE_ENCRYPT) { res = crypto_acipher_rsanopad_encrypt(o->attr, src_data, src_len, dst_data, &dlen); } else if (cs->mode == TEE_MODE_DECRYPT) { res = crypto_acipher_rsanopad_decrypt(o->attr, src_data, src_len, dst_data, &dlen); } else { /* * We will panic because "the mode is not compatible * with the function" */ res = TEE_ERROR_GENERIC; } break; case TEE_ALG_RSAES_PKCS1_V1_5: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512: for (n = 0; n < num_params; n++) { if (params[n].attributeID == TEE_ATTR_RSA_OAEP_LABEL) { label = params[n].content.ref.buffer; label_len = params[n].content.ref.length; break; } } if (cs->mode == TEE_MODE_ENCRYPT) { res = crypto_acipher_rsaes_encrypt(cs->algo, o->attr, label, label_len, src_data, src_len, dst_data, &dlen); } else if (cs->mode == TEE_MODE_DECRYPT) { res = crypto_acipher_rsaes_decrypt( cs->algo, o->attr, label, label_len, src_data, src_len, dst_data, &dlen); } else { res = TEE_ERROR_BAD_PARAMETERS; } break; #if defined(CFG_CRYPTO_RSASSA_NA1) case TEE_ALG_RSASSA_PKCS1_V1_5: #endif case TEE_ALG_RSASSA_PKCS1_V1_5_MD5: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512: if (cs->mode != TEE_MODE_SIGN) { res = TEE_ERROR_BAD_PARAMETERS; break; } salt_len = pkcs1_get_salt_len(params, num_params, src_len); res = crypto_acipher_rsassa_sign(cs->algo, o->attr, salt_len, src_data, src_len, dst_data, &dlen); break; case TEE_ALG_DSA_SHA1: case TEE_ALG_DSA_SHA224: case TEE_ALG_DSA_SHA256: res = crypto_acipher_dsa_sign(cs->algo, o->attr, src_data, src_len, dst_data, &dlen); break; case TEE_ALG_ECDSA_P192: case TEE_ALG_ECDSA_P224: case TEE_ALG_ECDSA_P256: case TEE_ALG_ECDSA_P384: case TEE_ALG_ECDSA_P521: res = crypto_acipher_ecc_sign(cs->algo, o->attr, src_data, src_len, dst_data, &dlen); break; default: res = TEE_ERROR_BAD_PARAMETERS; break; } out: free(params); if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) { TEE_Result res2; dlen64 = dlen; res2 = tee_svc_copy_to_user(dst_len, &dlen64, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) return res2; } return res; } TEE_Result syscall_asymm_verify(unsigned long state, const struct utee_attribute *usr_params, size_t num_params, const void *data, size_t data_len, const void *sig, size_t sig_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; struct tee_obj *o; size_t hash_size; int salt_len = 0; TEE_Attribute *params = NULL; uint32_t hash_algo; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; if (cs->mode != TEE_MODE_VERIFY) return TEE_ERROR_BAD_PARAMETERS; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)data, data_len); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)sig, sig_len); if (res != TEE_SUCCESS) return res; params = malloc(sizeof(TEE_Attribute) * num_params); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(utc, usr_params, num_params, params); if (res != TEE_SUCCESS) goto out; res = tee_obj_get(utc, cs->key1, &o); if (res != TEE_SUCCESS) goto out; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } switch (TEE_ALG_GET_MAIN_ALG(cs->algo)) { case TEE_MAIN_ALGO_RSA: if (cs->algo != TEE_ALG_RSASSA_PKCS1_V1_5) { hash_algo = TEE_DIGEST_HASH_TO_ALGO(cs->algo); res = tee_hash_get_digest_size(hash_algo, &hash_size); if (res != TEE_SUCCESS) break; if (data_len != hash_size) { res = TEE_ERROR_BAD_PARAMETERS; break; } salt_len = pkcs1_get_salt_len(params, num_params, hash_size); } res = crypto_acipher_rsassa_verify(cs->algo, o->attr, salt_len, data, data_len, sig, sig_len); break; case TEE_MAIN_ALGO_DSA: hash_algo = TEE_DIGEST_HASH_TO_ALGO(cs->algo); res = tee_hash_get_digest_size(hash_algo, &hash_size); if (res != TEE_SUCCESS) break; /* * Depending on the DSA algorithm (NIST), the digital signature * output size may be truncated to the size of a key pair * (Q prime size). Q prime size must be less or equal than the * hash output length of the hash algorithm involved. */ if (data_len > hash_size) { res = TEE_ERROR_BAD_PARAMETERS; break; } res = crypto_acipher_dsa_verify(cs->algo, o->attr, data, data_len, sig, sig_len); break; case TEE_MAIN_ALGO_ECDSA: res = crypto_acipher_ecc_verify(cs->algo, o->attr, data, data_len, sig, sig_len); break; default: res = TEE_ERROR_NOT_SUPPORTED; } out: free(params); return res; }
null
114
CWE-787
CVE-2019-1010297
// SPDX-License-Identifier: BSD-2-Clause /* * Copyright (c) 2014, STMicroelectronics International N.V. */ #include <assert.h> #include <compiler.h> #include <crypto/crypto.h> #include <kernel/tee_ta_manager.h> #include <mm/tee_mmu.h> #include <string_ext.h> #include <string.h> #include <sys/queue.h> #include <tee_api_types.h> #include <tee/tee_cryp_utl.h> #include <tee/tee_obj.h> #include <tee/tee_svc_cryp.h> #include <tee/tee_svc.h> #include <trace.h> #include <utee_defines.h> #include <util.h> #include <tee_api_defines_extensions.h> #if defined(CFG_CRYPTO_HKDF) #include <tee/tee_cryp_hkdf.h> #endif #if defined(CFG_CRYPTO_CONCAT_KDF) #include <tee/tee_cryp_concat_kdf.h> #endif #if defined(CFG_CRYPTO_PBKDF2) #include <tee/tee_cryp_pbkdf2.h> #endif typedef void (*tee_cryp_ctx_finalize_func_t) (void *ctx, uint32_t algo); struct tee_cryp_state { TAILQ_ENTRY(tee_cryp_state) link; uint32_t algo; uint32_t mode; vaddr_t key1; vaddr_t key2; void *ctx; tee_cryp_ctx_finalize_func_t ctx_finalize; }; struct tee_cryp_obj_secret { uint32_t key_size; uint32_t alloc_size; /* * Pseudo code visualize layout of structure * Next follows data, such as: * uint8_t data[alloc_size] * key_size must never exceed alloc_size */ }; #define TEE_TYPE_ATTR_OPTIONAL 0x0 #define TEE_TYPE_ATTR_REQUIRED 0x1 #define TEE_TYPE_ATTR_OPTIONAL_GROUP 0x2 #define TEE_TYPE_ATTR_SIZE_INDICATOR 0x4 #define TEE_TYPE_ATTR_GEN_KEY_OPT 0x8 #define TEE_TYPE_ATTR_GEN_KEY_REQ 0x10 /* Handle storing of generic secret keys of varying lengths */ #define ATTR_OPS_INDEX_SECRET 0 /* Convert to/from big-endian byte array and provider-specific bignum */ #define ATTR_OPS_INDEX_BIGNUM 1 /* Convert to/from value attribute depending on direction */ #define ATTR_OPS_INDEX_VALUE 2 struct tee_cryp_obj_type_attrs { uint32_t attr_id; uint16_t flags; uint16_t ops_index; uint16_t raw_offs; uint16_t raw_size; }; #define RAW_DATA(_x, _y) \ .raw_offs = offsetof(_x, _y), .raw_size = MEMBER_SIZE(_x, _y) static const struct tee_cryp_obj_type_attrs tee_cryp_obj_secret_value_attrs[] = { { .attr_id = TEE_ATTR_SECRET_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_SECRET, .raw_offs = 0, .raw_size = 0 }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_rsa_pub_key_attrs[] = { { .attr_id = TEE_ATTR_RSA_MODULUS, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_public_key, n) }, { .attr_id = TEE_ATTR_RSA_PUBLIC_EXPONENT, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_public_key, e) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_rsa_keypair_attrs[] = { { .attr_id = TEE_ATTR_RSA_MODULUS, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, n) }, { .attr_id = TEE_ATTR_RSA_PUBLIC_EXPONENT, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, e) }, { .attr_id = TEE_ATTR_RSA_PRIVATE_EXPONENT, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, d) }, { .attr_id = TEE_ATTR_RSA_PRIME1, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, p) }, { .attr_id = TEE_ATTR_RSA_PRIME2, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, q) }, { .attr_id = TEE_ATTR_RSA_EXPONENT1, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, dp) }, { .attr_id = TEE_ATTR_RSA_EXPONENT2, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, dq) }, { .attr_id = TEE_ATTR_RSA_COEFFICIENT, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, qp) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dsa_pub_key_attrs[] = { { .attr_id = TEE_ATTR_DSA_PRIME, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_public_key, p) }, { .attr_id = TEE_ATTR_DSA_SUBPRIME, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_public_key, q) }, { .attr_id = TEE_ATTR_DSA_BASE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_public_key, g) }, { .attr_id = TEE_ATTR_DSA_PUBLIC_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_public_key, y) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dsa_keypair_attrs[] = { { .attr_id = TEE_ATTR_DSA_PRIME, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, p) }, { .attr_id = TEE_ATTR_DSA_SUBPRIME, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, q) }, { .attr_id = TEE_ATTR_DSA_BASE, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, g) }, { .attr_id = TEE_ATTR_DSA_PRIVATE_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, x) }, { .attr_id = TEE_ATTR_DSA_PUBLIC_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, y) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dh_keypair_attrs[] = { { .attr_id = TEE_ATTR_DH_PRIME, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, p) }, { .attr_id = TEE_ATTR_DH_BASE, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, g) }, { .attr_id = TEE_ATTR_DH_PUBLIC_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, y) }, { .attr_id = TEE_ATTR_DH_PRIVATE_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, x) }, { .attr_id = TEE_ATTR_DH_SUBPRIME, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP | TEE_TYPE_ATTR_GEN_KEY_OPT, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, q) }, { .attr_id = TEE_ATTR_DH_X_BITS, .flags = TEE_TYPE_ATTR_GEN_KEY_OPT, .ops_index = ATTR_OPS_INDEX_VALUE, RAW_DATA(struct dh_keypair, xbits) }, }; #if defined(CFG_CRYPTO_HKDF) static const struct tee_cryp_obj_type_attrs tee_cryp_obj_hkdf_ikm_attrs[] = { { .attr_id = TEE_ATTR_HKDF_IKM, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_SECRET, .raw_offs = 0, .raw_size = 0 }, }; #endif #if defined(CFG_CRYPTO_CONCAT_KDF) static const struct tee_cryp_obj_type_attrs tee_cryp_obj_concat_kdf_z_attrs[] = { { .attr_id = TEE_ATTR_CONCAT_KDF_Z, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_SECRET, .raw_offs = 0, .raw_size = 0 }, }; #endif #if defined(CFG_CRYPTO_PBKDF2) static const struct tee_cryp_obj_type_attrs tee_cryp_obj_pbkdf2_passwd_attrs[] = { { .attr_id = TEE_ATTR_PBKDF2_PASSWORD, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_SECRET, .raw_offs = 0, .raw_size = 0 }, }; #endif static const struct tee_cryp_obj_type_attrs tee_cryp_obj_ecc_pub_key_attrs[] = { { .attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_X, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_public_key, x) }, { .attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_Y, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_public_key, y) }, { .attr_id = TEE_ATTR_ECC_CURVE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_VALUE, RAW_DATA(struct ecc_public_key, curve) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_ecc_keypair_attrs[] = { { .attr_id = TEE_ATTR_ECC_PRIVATE_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_keypair, d) }, { .attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_X, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_keypair, x) }, { .attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_Y, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_keypair, y) }, { .attr_id = TEE_ATTR_ECC_CURVE, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_VALUE, RAW_DATA(struct ecc_keypair, curve) }, }; struct tee_cryp_obj_type_props { TEE_ObjectType obj_type; uint16_t min_size; /* may not be smaller than this */ uint16_t max_size; /* may not be larger than this */ uint16_t alloc_size; /* this many bytes are allocated to hold data */ uint8_t quanta; /* may only be an multiple of this */ uint8_t num_type_attrs; const struct tee_cryp_obj_type_attrs *type_attrs; }; #define PROP(obj_type, quanta, min_size, max_size, alloc_size, type_attrs) \ { (obj_type), (min_size), (max_size), (alloc_size), (quanta), \ ARRAY_SIZE(type_attrs), (type_attrs) } static const struct tee_cryp_obj_type_props tee_cryp_obj_props[] = { PROP(TEE_TYPE_AES, 64, 128, 256, /* valid sizes 128, 192, 256 */ 256 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_DES, 56, 56, 56, /* * Valid size 56 without parity, note that we still allocate * for 64 bits since the key is supplied with parity. */ 64 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_DES3, 56, 112, 168, /* * Valid sizes 112, 168 without parity, note that we still * allocate for with space for the parity since the key is * supplied with parity. */ 192 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_MD5, 8, 64, 512, 512 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA1, 8, 80, 512, 512 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA224, 8, 112, 512, 512 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA256, 8, 192, 1024, 1024 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA384, 8, 256, 1024, 1024 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA512, 8, 256, 1024, 1024 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_GENERIC_SECRET, 8, 0, 4096, 4096 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), #if defined(CFG_CRYPTO_HKDF) PROP(TEE_TYPE_HKDF_IKM, 8, 0, 4096, 4096 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_hkdf_ikm_attrs), #endif #if defined(CFG_CRYPTO_CONCAT_KDF) PROP(TEE_TYPE_CONCAT_KDF_Z, 8, 0, 4096, 4096 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_concat_kdf_z_attrs), #endif #if defined(CFG_CRYPTO_PBKDF2) PROP(TEE_TYPE_PBKDF2_PASSWORD, 8, 0, 4096, 4096 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_pbkdf2_passwd_attrs), #endif PROP(TEE_TYPE_RSA_PUBLIC_KEY, 1, 256, CFG_CORE_BIGNUM_MAX_BITS, sizeof(struct rsa_public_key), tee_cryp_obj_rsa_pub_key_attrs), PROP(TEE_TYPE_RSA_KEYPAIR, 1, 256, CFG_CORE_BIGNUM_MAX_BITS, sizeof(struct rsa_keypair), tee_cryp_obj_rsa_keypair_attrs), PROP(TEE_TYPE_DSA_PUBLIC_KEY, 64, 512, 3072, sizeof(struct dsa_public_key), tee_cryp_obj_dsa_pub_key_attrs), PROP(TEE_TYPE_DSA_KEYPAIR, 64, 512, 3072, sizeof(struct dsa_keypair), tee_cryp_obj_dsa_keypair_attrs), PROP(TEE_TYPE_DH_KEYPAIR, 1, 256, 2048, sizeof(struct dh_keypair), tee_cryp_obj_dh_keypair_attrs), PROP(TEE_TYPE_ECDSA_PUBLIC_KEY, 1, 192, 521, sizeof(struct ecc_public_key), tee_cryp_obj_ecc_pub_key_attrs), PROP(TEE_TYPE_ECDSA_KEYPAIR, 1, 192, 521, sizeof(struct ecc_keypair), tee_cryp_obj_ecc_keypair_attrs), PROP(TEE_TYPE_ECDH_PUBLIC_KEY, 1, 192, 521, sizeof(struct ecc_public_key), tee_cryp_obj_ecc_pub_key_attrs), PROP(TEE_TYPE_ECDH_KEYPAIR, 1, 192, 521, sizeof(struct ecc_keypair), tee_cryp_obj_ecc_keypair_attrs), }; struct attr_ops { TEE_Result (*from_user)(void *attr, const void *buffer, size_t size); TEE_Result (*to_user)(void *attr, struct tee_ta_session *sess, void *buffer, uint64_t *size); TEE_Result (*to_binary)(void *attr, void *data, size_t data_len, size_t *offs); bool (*from_binary)(void *attr, const void *data, size_t data_len, size_t *offs); TEE_Result (*from_obj)(void *attr, void *src_attr); void (*free)(void *attr); void (*clear)(void *attr); }; static TEE_Result op_u32_to_binary_helper(uint32_t v, uint8_t *data, size_t data_len, size_t *offs) { uint32_t field; size_t next_offs; if (ADD_OVERFLOW(*offs, sizeof(field), &next_offs)) return TEE_ERROR_OVERFLOW; if (data && next_offs <= data_len) { field = TEE_U32_TO_BIG_ENDIAN(v); memcpy(data + *offs, &field, sizeof(field)); } (*offs) = next_offs; return TEE_SUCCESS; } static bool op_u32_from_binary_helper(uint32_t *v, const uint8_t *data, size_t data_len, size_t *offs) { uint32_t field; if (!data || (*offs + sizeof(field)) > data_len) return false; memcpy(&field, data + *offs, sizeof(field)); *v = TEE_U32_FROM_BIG_ENDIAN(field); (*offs) += sizeof(field); return true; } static TEE_Result op_attr_secret_value_from_user(void *attr, const void *buffer, size_t size) { struct tee_cryp_obj_secret *key = attr; /* Data size has to fit in allocated buffer */ if (size > key->alloc_size) return TEE_ERROR_SECURITY; memcpy(key + 1, buffer, size); key->key_size = size; return TEE_SUCCESS; } static TEE_Result op_attr_secret_value_to_user(void *attr, struct tee_ta_session *sess __unused, void *buffer, uint64_t *size) { TEE_Result res; struct tee_cryp_obj_secret *key = attr; uint64_t s; uint64_t key_size; res = tee_svc_copy_from_user(&s, size, sizeof(s)); if (res != TEE_SUCCESS) return res; key_size = key->key_size; res = tee_svc_copy_to_user(size, &key_size, sizeof(key_size)); if (res != TEE_SUCCESS) return res; if (s < key->key_size || !buffer) return TEE_ERROR_SHORT_BUFFER; return tee_svc_copy_to_user(buffer, key + 1, key->key_size); } static TEE_Result op_attr_secret_value_to_binary(void *attr, void *data, size_t data_len, size_t *offs) { TEE_Result res; struct tee_cryp_obj_secret *key = attr; size_t next_offs; res = op_u32_to_binary_helper(key->key_size, data, data_len, offs); if (res != TEE_SUCCESS) return res; if (ADD_OVERFLOW(*offs, key->key_size, &next_offs)) return TEE_ERROR_OVERFLOW; if (data && next_offs <= data_len) memcpy((uint8_t *)data + *offs, key + 1, key->key_size); (*offs) = next_offs; return TEE_SUCCESS; } static bool op_attr_secret_value_from_binary(void *attr, const void *data, size_t data_len, size_t *offs) { struct tee_cryp_obj_secret *key = attr; uint32_t s; if (!op_u32_from_binary_helper(&s, data, data_len, offs)) return false; if ((*offs + s) > data_len) return false; /* Data size has to fit in allocated buffer */ if (s > key->alloc_size) return false; key->key_size = s; memcpy(key + 1, (const uint8_t *)data + *offs, s); (*offs) += s; return true; } static TEE_Result op_attr_secret_value_from_obj(void *attr, void *src_attr) { struct tee_cryp_obj_secret *key = attr; struct tee_cryp_obj_secret *src_key = src_attr; if (src_key->key_size > key->alloc_size) return TEE_ERROR_BAD_STATE; memcpy(key + 1, src_key + 1, src_key->key_size); key->key_size = src_key->key_size; return TEE_SUCCESS; } static void op_attr_secret_value_clear(void *attr) { struct tee_cryp_obj_secret *key = attr; key->key_size = 0; memset(key + 1, 0, key->alloc_size); } static TEE_Result op_attr_bignum_from_user(void *attr, const void *buffer, size_t size) { struct bignum **bn = attr; return crypto_bignum_bin2bn(buffer, size, *bn); } static TEE_Result op_attr_bignum_to_user(void *attr, struct tee_ta_session *sess, void *buffer, uint64_t *size) { TEE_Result res; struct bignum **bn = attr; uint64_t req_size; uint64_t s; res = tee_svc_copy_from_user(&s, size, sizeof(s)); if (res != TEE_SUCCESS) return res; req_size = crypto_bignum_num_bytes(*bn); res = tee_svc_copy_to_user(size, &req_size, sizeof(req_size)); if (res != TEE_SUCCESS) return res; if (!req_size) return TEE_SUCCESS; if (s < req_size || !buffer) return TEE_ERROR_SHORT_BUFFER; /* Check we can access data using supplied user mode pointer */ res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)buffer, req_size); if (res != TEE_SUCCESS) return res; /* * Write the bignum (wich raw data points to) into an array of * bytes (stored in buffer) */ crypto_bignum_bn2bin(*bn, buffer); return TEE_SUCCESS; } static TEE_Result op_attr_bignum_to_binary(void *attr, void *data, size_t data_len, size_t *offs) { TEE_Result res; struct bignum **bn = attr; uint32_t n = crypto_bignum_num_bytes(*bn); size_t next_offs; res = op_u32_to_binary_helper(n, data, data_len, offs); if (res != TEE_SUCCESS) return res; if (ADD_OVERFLOW(*offs, n, &next_offs)) return TEE_ERROR_OVERFLOW; if (data && next_offs <= data_len) crypto_bignum_bn2bin(*bn, (uint8_t *)data + *offs); (*offs) = next_offs; return TEE_SUCCESS; } static bool op_attr_bignum_from_binary(void *attr, const void *data, size_t data_len, size_t *offs) { struct bignum **bn = attr; uint32_t n; if (!op_u32_from_binary_helper(&n, data, data_len, offs)) return false; if ((*offs + n) > data_len) return false; if (crypto_bignum_bin2bn((const uint8_t *)data + *offs, n, *bn)) return false; (*offs) += n; return true; } static TEE_Result op_attr_bignum_from_obj(void *attr, void *src_attr) { struct bignum **bn = attr; struct bignum **src_bn = src_attr; crypto_bignum_copy(*bn, *src_bn); return TEE_SUCCESS; } static void op_attr_bignum_clear(void *attr) { struct bignum **bn = attr; crypto_bignum_clear(*bn); } static void op_attr_bignum_free(void *attr) { struct bignum **bn = attr; crypto_bignum_free(*bn); *bn = NULL; } static TEE_Result op_attr_value_from_user(void *attr, const void *buffer, size_t size) { uint32_t *v = attr; if (size != sizeof(uint32_t) * 2) return TEE_ERROR_GENERIC; /* "can't happen */ /* Note that only the first value is copied */ memcpy(v, buffer, sizeof(uint32_t)); return TEE_SUCCESS; } static TEE_Result op_attr_value_to_user(void *attr, struct tee_ta_session *sess __unused, void *buffer, uint64_t *size) { TEE_Result res; uint32_t *v = attr; uint64_t s; uint32_t value[2] = { *v }; uint64_t req_size = sizeof(value); res = tee_svc_copy_from_user(&s, size, sizeof(s)); if (res != TEE_SUCCESS) return res; if (s < req_size || !buffer) return TEE_ERROR_SHORT_BUFFER; return tee_svc_copy_to_user(buffer, value, req_size); } static TEE_Result op_attr_value_to_binary(void *attr, void *data, size_t data_len, size_t *offs) { uint32_t *v = attr; return op_u32_to_binary_helper(*v, data, data_len, offs); } static bool op_attr_value_from_binary(void *attr, const void *data, size_t data_len, size_t *offs) { uint32_t *v = attr; return op_u32_from_binary_helper(v, data, data_len, offs); } static TEE_Result op_attr_value_from_obj(void *attr, void *src_attr) { uint32_t *v = attr; uint32_t *src_v = src_attr; *v = *src_v; return TEE_SUCCESS; } static void op_attr_value_clear(void *attr) { uint32_t *v = attr; *v = 0; } static const struct attr_ops attr_ops[] = { [ATTR_OPS_INDEX_SECRET] = { .from_user = op_attr_secret_value_from_user, .to_user = op_attr_secret_value_to_user, .to_binary = op_attr_secret_value_to_binary, .from_binary = op_attr_secret_value_from_binary, .from_obj = op_attr_secret_value_from_obj, .free = op_attr_secret_value_clear, /* not a typo */ .clear = op_attr_secret_value_clear, }, [ATTR_OPS_INDEX_BIGNUM] = { .from_user = op_attr_bignum_from_user, .to_user = op_attr_bignum_to_user, .to_binary = op_attr_bignum_to_binary, .from_binary = op_attr_bignum_from_binary, .from_obj = op_attr_bignum_from_obj, .free = op_attr_bignum_free, .clear = op_attr_bignum_clear, }, [ATTR_OPS_INDEX_VALUE] = { .from_user = op_attr_value_from_user, .to_user = op_attr_value_to_user, .to_binary = op_attr_value_to_binary, .from_binary = op_attr_value_from_binary, .from_obj = op_attr_value_from_obj, .free = op_attr_value_clear, /* not a typo */ .clear = op_attr_value_clear, }, }; TEE_Result syscall_cryp_obj_get_info(unsigned long obj, TEE_ObjectInfo *info) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) goto exit; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) goto exit; res = tee_svc_copy_to_user(info, &o->info, sizeof(o->info)); exit: return res; } TEE_Result syscall_cryp_obj_restrict_usage(unsigned long obj, unsigned long usage) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) goto exit; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) goto exit; o->info.objectUsage &= usage; exit: return res; } static int tee_svc_cryp_obj_find_type_attr_idx( uint32_t attr_id, const struct tee_cryp_obj_type_props *type_props) { size_t n; for (n = 0; n < type_props->num_type_attrs; n++) { if (attr_id == type_props->type_attrs[n].attr_id) return n; } return -1; } static const struct tee_cryp_obj_type_props *tee_svc_find_type_props( TEE_ObjectType obj_type) { size_t n; for (n = 0; n < ARRAY_SIZE(tee_cryp_obj_props); n++) { if (tee_cryp_obj_props[n].obj_type == obj_type) return tee_cryp_obj_props + n; } return NULL; } /* Set an attribute on an object */ static void set_attribute(struct tee_obj *o, const struct tee_cryp_obj_type_props *props, uint32_t attr) { int idx = tee_svc_cryp_obj_find_type_attr_idx(attr, props); if (idx < 0) return; o->have_attrs |= BIT(idx); } /* Get an attribute on an object */ static uint32_t get_attribute(const struct tee_obj *o, const struct tee_cryp_obj_type_props *props, uint32_t attr) { int idx = tee_svc_cryp_obj_find_type_attr_idx(attr, props); if (idx < 0) return 0; return o->have_attrs & BIT(idx); } TEE_Result syscall_cryp_obj_get_attr(unsigned long obj, unsigned long attr_id, void *buffer, uint64_t *size) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; const struct tee_cryp_obj_type_props *type_props; int idx; const struct attr_ops *ops; void *attr; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return TEE_ERROR_ITEM_NOT_FOUND; /* Check that the object is initialized */ if (!(o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED)) return TEE_ERROR_BAD_PARAMETERS; /* Check that getting the attribute is allowed */ if (!(attr_id & TEE_ATTR_BIT_PROTECTED) && !(o->info.objectUsage & TEE_USAGE_EXTRACTABLE)) return TEE_ERROR_BAD_PARAMETERS; type_props = tee_svc_find_type_props(o->info.objectType); if (!type_props) { /* Unknown object type, "can't happen" */ return TEE_ERROR_BAD_STATE; } idx = tee_svc_cryp_obj_find_type_attr_idx(attr_id, type_props); if ((idx < 0) || ((o->have_attrs & (1 << idx)) == 0)) return TEE_ERROR_ITEM_NOT_FOUND; ops = attr_ops + type_props->type_attrs[idx].ops_index; attr = (uint8_t *)o->attr + type_props->type_attrs[idx].raw_offs; return ops->to_user(attr, sess, buffer, size); } void tee_obj_attr_free(struct tee_obj *o) { const struct tee_cryp_obj_type_props *tp; size_t n; if (!o->attr) return; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return; for (n = 0; n < tp->num_type_attrs; n++) { const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n; attr_ops[ta->ops_index].free((uint8_t *)o->attr + ta->raw_offs); } } void tee_obj_attr_clear(struct tee_obj *o) { const struct tee_cryp_obj_type_props *tp; size_t n; if (!o->attr) return; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return; for (n = 0; n < tp->num_type_attrs; n++) { const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n; attr_ops[ta->ops_index].clear((uint8_t *)o->attr + ta->raw_offs); } } TEE_Result tee_obj_attr_to_binary(struct tee_obj *o, void *data, size_t *data_len) { const struct tee_cryp_obj_type_props *tp; size_t n; size_t offs = 0; size_t len = data ? *data_len : 0; TEE_Result res; if (o->info.objectType == TEE_TYPE_DATA) { *data_len = 0; return TEE_SUCCESS; /* pure data object */ } if (!o->attr) return TEE_ERROR_BAD_STATE; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return TEE_ERROR_BAD_STATE; for (n = 0; n < tp->num_type_attrs; n++) { const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n; void *attr = (uint8_t *)o->attr + ta->raw_offs; res = attr_ops[ta->ops_index].to_binary(attr, data, len, &offs); if (res != TEE_SUCCESS) return res; } *data_len = offs; if (data && offs > len) return TEE_ERROR_SHORT_BUFFER; return TEE_SUCCESS; } TEE_Result tee_obj_attr_from_binary(struct tee_obj *o, const void *data, size_t data_len) { const struct tee_cryp_obj_type_props *tp; size_t n; size_t offs = 0; if (o->info.objectType == TEE_TYPE_DATA) return TEE_SUCCESS; /* pure data object */ if (!o->attr) return TEE_ERROR_BAD_STATE; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return TEE_ERROR_BAD_STATE; for (n = 0; n < tp->num_type_attrs; n++) { const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n; void *attr = (uint8_t *)o->attr + ta->raw_offs; if (!attr_ops[ta->ops_index].from_binary(attr, data, data_len, &offs)) return TEE_ERROR_CORRUPT_OBJECT; } return TEE_SUCCESS; } TEE_Result tee_obj_attr_copy_from(struct tee_obj *o, const struct tee_obj *src) { TEE_Result res; const struct tee_cryp_obj_type_props *tp; const struct tee_cryp_obj_type_attrs *ta; size_t n; uint32_t have_attrs = 0; void *attr; void *src_attr; if (o->info.objectType == TEE_TYPE_DATA) return TEE_SUCCESS; /* pure data object */ if (!o->attr) return TEE_ERROR_BAD_STATE; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return TEE_ERROR_BAD_STATE; if (o->info.objectType == src->info.objectType) { have_attrs = src->have_attrs; for (n = 0; n < tp->num_type_attrs; n++) { ta = tp->type_attrs + n; attr = (uint8_t *)o->attr + ta->raw_offs; src_attr = (uint8_t *)src->attr + ta->raw_offs; res = attr_ops[ta->ops_index].from_obj(attr, src_attr); if (res != TEE_SUCCESS) return res; } } else { const struct tee_cryp_obj_type_props *tp_src; int idx; if (o->info.objectType == TEE_TYPE_RSA_PUBLIC_KEY) { if (src->info.objectType != TEE_TYPE_RSA_KEYPAIR) return TEE_ERROR_BAD_PARAMETERS; } else if (o->info.objectType == TEE_TYPE_DSA_PUBLIC_KEY) { if (src->info.objectType != TEE_TYPE_DSA_KEYPAIR) return TEE_ERROR_BAD_PARAMETERS; } else if (o->info.objectType == TEE_TYPE_ECDSA_PUBLIC_KEY) { if (src->info.objectType != TEE_TYPE_ECDSA_KEYPAIR) return TEE_ERROR_BAD_PARAMETERS; } else if (o->info.objectType == TEE_TYPE_ECDH_PUBLIC_KEY) { if (src->info.objectType != TEE_TYPE_ECDH_KEYPAIR) return TEE_ERROR_BAD_PARAMETERS; } else { return TEE_ERROR_BAD_PARAMETERS; } tp_src = tee_svc_find_type_props(src->info.objectType); if (!tp_src) return TEE_ERROR_BAD_STATE; have_attrs = BIT32(tp->num_type_attrs) - 1; for (n = 0; n < tp->num_type_attrs; n++) { ta = tp->type_attrs + n; idx = tee_svc_cryp_obj_find_type_attr_idx(ta->attr_id, tp_src); if (idx < 0) return TEE_ERROR_BAD_STATE; attr = (uint8_t *)o->attr + ta->raw_offs; src_attr = (uint8_t *)src->attr + tp_src->type_attrs[idx].raw_offs; res = attr_ops[ta->ops_index].from_obj(attr, src_attr); if (res != TEE_SUCCESS) return res; } } o->have_attrs = have_attrs; return TEE_SUCCESS; } TEE_Result tee_obj_set_type(struct tee_obj *o, uint32_t obj_type, size_t max_key_size) { TEE_Result res = TEE_SUCCESS; const struct tee_cryp_obj_type_props *type_props; /* Can only set type for newly allocated objs */ if (o->attr) return TEE_ERROR_BAD_STATE; /* * Verify that maxKeySize is supported and find out how * much should be allocated. */ if (obj_type == TEE_TYPE_DATA) { if (max_key_size) return TEE_ERROR_NOT_SUPPORTED; } else { /* Find description of object */ type_props = tee_svc_find_type_props(obj_type); if (!type_props) return TEE_ERROR_NOT_SUPPORTED; /* Check that maxKeySize follows restrictions */ if (max_key_size % type_props->quanta != 0) return TEE_ERROR_NOT_SUPPORTED; if (max_key_size < type_props->min_size) return TEE_ERROR_NOT_SUPPORTED; if (max_key_size > type_props->max_size) return TEE_ERROR_NOT_SUPPORTED; o->attr = calloc(1, type_props->alloc_size); if (!o->attr) return TEE_ERROR_OUT_OF_MEMORY; } /* If we have a key structure, pre-allocate the bignums inside */ switch (obj_type) { case TEE_TYPE_RSA_PUBLIC_KEY: res = crypto_acipher_alloc_rsa_public_key(o->attr, max_key_size); break; case TEE_TYPE_RSA_KEYPAIR: res = crypto_acipher_alloc_rsa_keypair(o->attr, max_key_size); break; case TEE_TYPE_DSA_PUBLIC_KEY: res = crypto_acipher_alloc_dsa_public_key(o->attr, max_key_size); break; case TEE_TYPE_DSA_KEYPAIR: res = crypto_acipher_alloc_dsa_keypair(o->attr, max_key_size); break; case TEE_TYPE_DH_KEYPAIR: res = crypto_acipher_alloc_dh_keypair(o->attr, max_key_size); break; case TEE_TYPE_ECDSA_PUBLIC_KEY: case TEE_TYPE_ECDH_PUBLIC_KEY: res = crypto_acipher_alloc_ecc_public_key(o->attr, max_key_size); break; case TEE_TYPE_ECDSA_KEYPAIR: case TEE_TYPE_ECDH_KEYPAIR: res = crypto_acipher_alloc_ecc_keypair(o->attr, max_key_size); break; default: if (obj_type != TEE_TYPE_DATA) { struct tee_cryp_obj_secret *key = o->attr; key->alloc_size = type_props->alloc_size - sizeof(*key); } break; } if (res != TEE_SUCCESS) return res; o->info.objectType = obj_type; o->info.maxKeySize = max_key_size; o->info.objectUsage = TEE_USAGE_DEFAULT; return TEE_SUCCESS; } TEE_Result syscall_cryp_obj_alloc(unsigned long obj_type, unsigned long max_key_size, uint32_t *obj) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; if (obj_type == TEE_TYPE_DATA) return TEE_ERROR_NOT_SUPPORTED; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; o = tee_obj_alloc(); if (!o) return TEE_ERROR_OUT_OF_MEMORY; res = tee_obj_set_type(o, obj_type, max_key_size); if (res != TEE_SUCCESS) { tee_obj_free(o); return res; } tee_obj_add(to_user_ta_ctx(sess->ctx), o); res = tee_svc_copy_kaddr_to_uref(obj, o); if (res != TEE_SUCCESS) tee_obj_close(to_user_ta_ctx(sess->ctx), o); return res; } TEE_Result syscall_cryp_obj_close(unsigned long obj) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; /* * If it's busy it's used by an operation, a client should never have * this handle. */ if (o->busy) return TEE_ERROR_ITEM_NOT_FOUND; tee_obj_close(to_user_ta_ctx(sess->ctx), o); return TEE_SUCCESS; } TEE_Result syscall_cryp_obj_reset(unsigned long obj) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) == 0) { tee_obj_attr_clear(o); o->info.keySize = 0; o->info.objectUsage = TEE_USAGE_DEFAULT; } else { return TEE_ERROR_BAD_PARAMETERS; } /* the object is no more initialized */ o->info.handleFlags &= ~TEE_HANDLE_FLAG_INITIALIZED; return TEE_SUCCESS; } static TEE_Result copy_in_attrs(struct user_ta_ctx *utc, const struct utee_attribute *usr_attrs, uint32_t attr_count, TEE_Attribute *attrs) { TEE_Result res; uint32_t n; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)usr_attrs, attr_count * sizeof(struct utee_attribute)); if (res != TEE_SUCCESS) return res; for (n = 0; n < attr_count; n++) { attrs[n].attributeID = usr_attrs[n].attribute_id; if (attrs[n].attributeID & TEE_ATTR_BIT_VALUE) { attrs[n].content.value.a = usr_attrs[n].a; attrs[n].content.value.b = usr_attrs[n].b; } else { uintptr_t buf = usr_attrs[n].a; size_t len = usr_attrs[n].b; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, buf, len); if (res != TEE_SUCCESS) return res; attrs[n].content.ref.buffer = (void *)buf; attrs[n].content.ref.length = len; } } return TEE_SUCCESS; } enum attr_usage { ATTR_USAGE_POPULATE, ATTR_USAGE_GENERATE_KEY }; static TEE_Result tee_svc_cryp_check_attr(enum attr_usage usage, const struct tee_cryp_obj_type_props *type_props, const TEE_Attribute *attrs, uint32_t attr_count) { uint32_t required_flag; uint32_t opt_flag; bool all_opt_needed; uint32_t req_attrs = 0; uint32_t opt_grp_attrs = 0; uint32_t attrs_found = 0; size_t n; uint32_t bit; uint32_t flags; int idx; if (usage == ATTR_USAGE_POPULATE) { required_flag = TEE_TYPE_ATTR_REQUIRED; opt_flag = TEE_TYPE_ATTR_OPTIONAL_GROUP; all_opt_needed = true; } else { required_flag = TEE_TYPE_ATTR_GEN_KEY_REQ; opt_flag = TEE_TYPE_ATTR_GEN_KEY_OPT; all_opt_needed = false; } /* * First find out which attributes are required and which belong to * the optional group */ for (n = 0; n < type_props->num_type_attrs; n++) { bit = 1 << n; flags = type_props->type_attrs[n].flags; if (flags & required_flag) req_attrs |= bit; else if (flags & opt_flag) opt_grp_attrs |= bit; } /* * Verify that all required attributes are in place and * that the same attribute isn't repeated. */ for (n = 0; n < attr_count; n++) { idx = tee_svc_cryp_obj_find_type_attr_idx( attrs[n].attributeID, type_props); /* attribute not defined in current object type */ if (idx < 0) return TEE_ERROR_ITEM_NOT_FOUND; bit = 1 << idx; /* attribute not repeated */ if ((attrs_found & bit) != 0) return TEE_ERROR_ITEM_NOT_FOUND; attrs_found |= bit; } /* Required attribute missing */ if ((attrs_found & req_attrs) != req_attrs) return TEE_ERROR_ITEM_NOT_FOUND; /* * If the flag says that "if one of the optional attributes are included * all of them has to be included" this must be checked. */ if (all_opt_needed && (attrs_found & opt_grp_attrs) != 0 && (attrs_found & opt_grp_attrs) != opt_grp_attrs) return TEE_ERROR_ITEM_NOT_FOUND; return TEE_SUCCESS; } static TEE_Result get_ec_key_size(uint32_t curve, size_t *key_size) { switch (curve) { case TEE_ECC_CURVE_NIST_P192: *key_size = 192; break; case TEE_ECC_CURVE_NIST_P224: *key_size = 224; break; case TEE_ECC_CURVE_NIST_P256: *key_size = 256; break; case TEE_ECC_CURVE_NIST_P384: *key_size = 384; break; case TEE_ECC_CURVE_NIST_P521: *key_size = 521; break; default: return TEE_ERROR_NOT_SUPPORTED; } return TEE_SUCCESS; } static TEE_Result tee_svc_cryp_obj_populate_type( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, const TEE_Attribute *attrs, uint32_t attr_count) { TEE_Result res; uint32_t have_attrs = 0; size_t obj_size = 0; size_t n; int idx; const struct attr_ops *ops; void *attr; for (n = 0; n < attr_count; n++) { idx = tee_svc_cryp_obj_find_type_attr_idx( attrs[n].attributeID, type_props); /* attribute not defined in current object type */ if (idx < 0) return TEE_ERROR_ITEM_NOT_FOUND; have_attrs |= BIT32(idx); ops = attr_ops + type_props->type_attrs[idx].ops_index; attr = (uint8_t *)o->attr + type_props->type_attrs[idx].raw_offs; if (attrs[n].attributeID & TEE_ATTR_BIT_VALUE) res = ops->from_user(attr, &attrs[n].content.value, sizeof(attrs[n].content.value)); else res = ops->from_user(attr, attrs[n].content.ref.buffer, attrs[n].content.ref.length); if (res != TEE_SUCCESS) return res; /* * First attr_idx signifies the attribute that gives the size * of the object */ if (type_props->type_attrs[idx].flags & TEE_TYPE_ATTR_SIZE_INDICATOR) { /* * For ECDSA/ECDH we need to translate curve into * object size */ if (attrs[n].attributeID == TEE_ATTR_ECC_CURVE) { res = get_ec_key_size(attrs[n].content.value.a, &obj_size); if (res != TEE_SUCCESS) return res; } else { obj_size += (attrs[n].content.ref.length * 8); } } } /* * We have to do it like this because the parity bits aren't counted * when telling the size of the key in bits. */ if (o->info.objectType == TEE_TYPE_DES || o->info.objectType == TEE_TYPE_DES3) obj_size -= obj_size / 8; /* Exclude parity in size of key */ o->have_attrs = have_attrs; o->info.keySize = obj_size; return TEE_SUCCESS; } TEE_Result syscall_cryp_obj_populate(unsigned long obj, struct utee_attribute *usr_attrs, unsigned long attr_count) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; const struct tee_cryp_obj_type_props *type_props; TEE_Attribute *attrs = NULL; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; /* Must be a transient object */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0) return TEE_ERROR_BAD_PARAMETERS; /* Must not be initialized already */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0) return TEE_ERROR_BAD_PARAMETERS; type_props = tee_svc_find_type_props(o->info.objectType); if (!type_props) return TEE_ERROR_NOT_IMPLEMENTED; size_t alloc_size = 0; if (MUL_OVERFLOW(sizeof(TEE_Attribute), attr_count, &alloc_size)) return TEE_ERROR_OVERFLOW; attrs = malloc(alloc_size); if (!attrs) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_attrs, attr_count, attrs); if (res != TEE_SUCCESS) goto out; res = tee_svc_cryp_check_attr(ATTR_USAGE_POPULATE, type_props, attrs, attr_count); if (res != TEE_SUCCESS) goto out; res = tee_svc_cryp_obj_populate_type(o, type_props, attrs, attr_count); if (res == TEE_SUCCESS) o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; out: free(attrs); return res; } TEE_Result syscall_cryp_obj_copy(unsigned long dst, unsigned long src) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *dst_o; struct tee_obj *src_o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(dst), &dst_o); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(src), &src_o); if (res != TEE_SUCCESS) return res; if ((src_o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; if ((dst_o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0) return TEE_ERROR_BAD_PARAMETERS; if ((dst_o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0) return TEE_ERROR_BAD_PARAMETERS; res = tee_obj_attr_copy_from(dst_o, src_o); if (res != TEE_SUCCESS) return res; dst_o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; dst_o->info.keySize = src_o->info.keySize; dst_o->info.objectUsage = src_o->info.objectUsage; return TEE_SUCCESS; } static TEE_Result tee_svc_obj_generate_key_rsa( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, uint32_t key_size, const TEE_Attribute *params, uint32_t param_count) { TEE_Result res; struct rsa_keypair *key = o->attr; uint32_t e = TEE_U32_TO_BIG_ENDIAN(65537); /* Copy the present attributes into the obj before starting */ res = tee_svc_cryp_obj_populate_type(o, type_props, params, param_count); if (res != TEE_SUCCESS) return res; if (!get_attribute(o, type_props, TEE_ATTR_RSA_PUBLIC_EXPONENT)) crypto_bignum_bin2bn((const uint8_t *)&e, sizeof(e), key->e); res = crypto_acipher_gen_rsa_key(key, key_size); if (res != TEE_SUCCESS) return res; /* Set bits for all known attributes for this object type */ o->have_attrs = (1 << type_props->num_type_attrs) - 1; return TEE_SUCCESS; } static TEE_Result tee_svc_obj_generate_key_dsa( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, uint32_t key_size) { TEE_Result res; res = crypto_acipher_gen_dsa_key(o->attr, key_size); if (res != TEE_SUCCESS) return res; /* Set bits for all known attributes for this object type */ o->have_attrs = (1 << type_props->num_type_attrs) - 1; return TEE_SUCCESS; } static TEE_Result tee_svc_obj_generate_key_dh( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, uint32_t key_size __unused, const TEE_Attribute *params, uint32_t param_count) { TEE_Result res; struct dh_keypair *tee_dh_key; struct bignum *dh_q = NULL; uint32_t dh_xbits = 0; /* Copy the present attributes into the obj before starting */ res = tee_svc_cryp_obj_populate_type(o, type_props, params, param_count); if (res != TEE_SUCCESS) return res; tee_dh_key = (struct dh_keypair *)o->attr; if (get_attribute(o, type_props, TEE_ATTR_DH_SUBPRIME)) dh_q = tee_dh_key->q; if (get_attribute(o, type_props, TEE_ATTR_DH_X_BITS)) dh_xbits = tee_dh_key->xbits; res = crypto_acipher_gen_dh_key(tee_dh_key, dh_q, dh_xbits); if (res != TEE_SUCCESS) return res; /* Set bits for the generated public and private key */ set_attribute(o, type_props, TEE_ATTR_DH_PUBLIC_VALUE); set_attribute(o, type_props, TEE_ATTR_DH_PRIVATE_VALUE); set_attribute(o, type_props, TEE_ATTR_DH_X_BITS); return TEE_SUCCESS; } static TEE_Result tee_svc_obj_generate_key_ecc( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, uint32_t key_size __unused, const TEE_Attribute *params, uint32_t param_count) { TEE_Result res; struct ecc_keypair *tee_ecc_key; /* Copy the present attributes into the obj before starting */ res = tee_svc_cryp_obj_populate_type(o, type_props, params, param_count); if (res != TEE_SUCCESS) return res; tee_ecc_key = (struct ecc_keypair *)o->attr; res = crypto_acipher_gen_ecc_key(tee_ecc_key); if (res != TEE_SUCCESS) return res; /* Set bits for the generated public and private key */ set_attribute(o, type_props, TEE_ATTR_ECC_PRIVATE_VALUE); set_attribute(o, type_props, TEE_ATTR_ECC_PUBLIC_VALUE_X); set_attribute(o, type_props, TEE_ATTR_ECC_PUBLIC_VALUE_Y); set_attribute(o, type_props, TEE_ATTR_ECC_CURVE); return TEE_SUCCESS; } TEE_Result syscall_obj_generate_key(unsigned long obj, unsigned long key_size, const struct utee_attribute *usr_params, unsigned long param_count) { TEE_Result res; struct tee_ta_session *sess; const struct tee_cryp_obj_type_props *type_props; struct tee_obj *o; struct tee_cryp_obj_secret *key; size_t byte_size; TEE_Attribute *params = NULL; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; /* Must be a transient object */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0) return TEE_ERROR_BAD_STATE; /* Must not be initialized already */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0) return TEE_ERROR_BAD_STATE; /* Find description of object */ type_props = tee_svc_find_type_props(o->info.objectType); if (!type_props) return TEE_ERROR_NOT_SUPPORTED; /* Check that maxKeySize follows restrictions */ if (key_size % type_props->quanta != 0) return TEE_ERROR_NOT_SUPPORTED; if (key_size < type_props->min_size) return TEE_ERROR_NOT_SUPPORTED; if (key_size > type_props->max_size) return TEE_ERROR_NOT_SUPPORTED; params = malloc(sizeof(TEE_Attribute) * param_count); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_params, param_count, params); if (res != TEE_SUCCESS) goto out; res = tee_svc_cryp_check_attr(ATTR_USAGE_GENERATE_KEY, type_props, params, param_count); if (res != TEE_SUCCESS) goto out; switch (o->info.objectType) { case TEE_TYPE_AES: case TEE_TYPE_DES: case TEE_TYPE_DES3: case TEE_TYPE_HMAC_MD5: case TEE_TYPE_HMAC_SHA1: case TEE_TYPE_HMAC_SHA224: case TEE_TYPE_HMAC_SHA256: case TEE_TYPE_HMAC_SHA384: case TEE_TYPE_HMAC_SHA512: case TEE_TYPE_GENERIC_SECRET: byte_size = key_size / 8; /* * We have to do it like this because the parity bits aren't * counted when telling the size of the key in bits. */ if (o->info.objectType == TEE_TYPE_DES || o->info.objectType == TEE_TYPE_DES3) { byte_size = (key_size + key_size / 7) / 8; } key = (struct tee_cryp_obj_secret *)o->attr; if (byte_size > key->alloc_size) { res = TEE_ERROR_EXCESS_DATA; goto out; } res = crypto_rng_read((void *)(key + 1), byte_size); if (res != TEE_SUCCESS) goto out; key->key_size = byte_size; /* Set bits for all known attributes for this object type */ o->have_attrs = (1 << type_props->num_type_attrs) - 1; break; case TEE_TYPE_RSA_KEYPAIR: res = tee_svc_obj_generate_key_rsa(o, type_props, key_size, params, param_count); if (res != TEE_SUCCESS) goto out; break; case TEE_TYPE_DSA_KEYPAIR: res = tee_svc_obj_generate_key_dsa(o, type_props, key_size); if (res != TEE_SUCCESS) goto out; break; case TEE_TYPE_DH_KEYPAIR: res = tee_svc_obj_generate_key_dh(o, type_props, key_size, params, param_count); if (res != TEE_SUCCESS) goto out; break; case TEE_TYPE_ECDSA_KEYPAIR: case TEE_TYPE_ECDH_KEYPAIR: res = tee_svc_obj_generate_key_ecc(o, type_props, key_size, params, param_count); if (res != TEE_SUCCESS) goto out; break; default: res = TEE_ERROR_BAD_FORMAT; } out: free(params); if (res == TEE_SUCCESS) { o->info.keySize = key_size; o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; } return res; } static TEE_Result tee_svc_cryp_get_state(struct tee_ta_session *sess, uint32_t state_id, struct tee_cryp_state **state) { struct tee_cryp_state *s; struct user_ta_ctx *utc = to_user_ta_ctx(sess->ctx); TAILQ_FOREACH(s, &utc->cryp_states, link) { if (state_id == (vaddr_t)s) { *state = s; return TEE_SUCCESS; } } return TEE_ERROR_BAD_PARAMETERS; } static void cryp_state_free(struct user_ta_ctx *utc, struct tee_cryp_state *cs) { struct tee_obj *o; if (tee_obj_get(utc, cs->key1, &o) == TEE_SUCCESS) tee_obj_close(utc, o); if (tee_obj_get(utc, cs->key2, &o) == TEE_SUCCESS) tee_obj_close(utc, o); TAILQ_REMOVE(&utc->cryp_states, cs, link); if (cs->ctx_finalize != NULL) cs->ctx_finalize(cs->ctx, cs->algo); switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_CIPHER: crypto_cipher_free_ctx(cs->ctx, cs->algo); break; case TEE_OPERATION_AE: crypto_authenc_free_ctx(cs->ctx, cs->algo); break; case TEE_OPERATION_DIGEST: crypto_hash_free_ctx(cs->ctx, cs->algo); break; case TEE_OPERATION_MAC: crypto_mac_free_ctx(cs->ctx, cs->algo); break; default: assert(!cs->ctx); } free(cs); } static TEE_Result tee_svc_cryp_check_key_type(const struct tee_obj *o, uint32_t algo, TEE_OperationMode mode) { uint32_t req_key_type; uint32_t req_key_type2 = 0; switch (TEE_ALG_GET_MAIN_ALG(algo)) { case TEE_MAIN_ALGO_MD5: req_key_type = TEE_TYPE_HMAC_MD5; break; case TEE_MAIN_ALGO_SHA1: req_key_type = TEE_TYPE_HMAC_SHA1; break; case TEE_MAIN_ALGO_SHA224: req_key_type = TEE_TYPE_HMAC_SHA224; break; case TEE_MAIN_ALGO_SHA256: req_key_type = TEE_TYPE_HMAC_SHA256; break; case TEE_MAIN_ALGO_SHA384: req_key_type = TEE_TYPE_HMAC_SHA384; break; case TEE_MAIN_ALGO_SHA512: req_key_type = TEE_TYPE_HMAC_SHA512; break; case TEE_MAIN_ALGO_AES: req_key_type = TEE_TYPE_AES; break; case TEE_MAIN_ALGO_DES: req_key_type = TEE_TYPE_DES; break; case TEE_MAIN_ALGO_DES3: req_key_type = TEE_TYPE_DES3; break; case TEE_MAIN_ALGO_RSA: req_key_type = TEE_TYPE_RSA_KEYPAIR; if (mode == TEE_MODE_ENCRYPT || mode == TEE_MODE_VERIFY) req_key_type2 = TEE_TYPE_RSA_PUBLIC_KEY; break; case TEE_MAIN_ALGO_DSA: req_key_type = TEE_TYPE_DSA_KEYPAIR; if (mode == TEE_MODE_ENCRYPT || mode == TEE_MODE_VERIFY) req_key_type2 = TEE_TYPE_DSA_PUBLIC_KEY; break; case TEE_MAIN_ALGO_DH: req_key_type = TEE_TYPE_DH_KEYPAIR; break; case TEE_MAIN_ALGO_ECDSA: req_key_type = TEE_TYPE_ECDSA_KEYPAIR; if (mode == TEE_MODE_VERIFY) req_key_type2 = TEE_TYPE_ECDSA_PUBLIC_KEY; break; case TEE_MAIN_ALGO_ECDH: req_key_type = TEE_TYPE_ECDH_KEYPAIR; break; #if defined(CFG_CRYPTO_HKDF) case TEE_MAIN_ALGO_HKDF: req_key_type = TEE_TYPE_HKDF_IKM; break; #endif #if defined(CFG_CRYPTO_CONCAT_KDF) case TEE_MAIN_ALGO_CONCAT_KDF: req_key_type = TEE_TYPE_CONCAT_KDF_Z; break; #endif #if defined(CFG_CRYPTO_PBKDF2) case TEE_MAIN_ALGO_PBKDF2: req_key_type = TEE_TYPE_PBKDF2_PASSWORD; break; #endif default: return TEE_ERROR_BAD_PARAMETERS; } if (req_key_type != o->info.objectType && req_key_type2 != o->info.objectType) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } TEE_Result syscall_cryp_state_alloc(unsigned long algo, unsigned long mode, unsigned long key1, unsigned long key2, uint32_t *state) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; struct tee_obj *o1 = NULL; struct tee_obj *o2 = NULL; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); if (key1 != 0) { res = tee_obj_get(utc, tee_svc_uref_to_vaddr(key1), &o1); if (res != TEE_SUCCESS) return res; if (o1->busy) return TEE_ERROR_BAD_PARAMETERS; res = tee_svc_cryp_check_key_type(o1, algo, mode); if (res != TEE_SUCCESS) return res; } if (key2 != 0) { res = tee_obj_get(utc, tee_svc_uref_to_vaddr(key2), &o2); if (res != TEE_SUCCESS) return res; if (o2->busy) return TEE_ERROR_BAD_PARAMETERS; res = tee_svc_cryp_check_key_type(o2, algo, mode); if (res != TEE_SUCCESS) return res; } cs = calloc(1, sizeof(struct tee_cryp_state)); if (!cs) return TEE_ERROR_OUT_OF_MEMORY; TAILQ_INSERT_TAIL(&utc->cryp_states, cs, link); cs->algo = algo; cs->mode = mode; switch (TEE_ALG_GET_CLASS(algo)) { case TEE_OPERATION_EXTENSION: #ifdef CFG_CRYPTO_RSASSA_NA1 if (algo == TEE_ALG_RSASSA_PKCS1_V1_5) goto rsassa_na1; #endif res = TEE_ERROR_NOT_SUPPORTED; break; case TEE_OPERATION_CIPHER: if ((algo == TEE_ALG_AES_XTS && (key1 == 0 || key2 == 0)) || (algo != TEE_ALG_AES_XTS && (key1 == 0 || key2 != 0))) { res = TEE_ERROR_BAD_PARAMETERS; } else { res = crypto_cipher_alloc_ctx(&cs->ctx, algo); if (res != TEE_SUCCESS) break; } break; case TEE_OPERATION_AE: if (key1 == 0 || key2 != 0) { res = TEE_ERROR_BAD_PARAMETERS; } else { res = crypto_authenc_alloc_ctx(&cs->ctx, algo); if (res != TEE_SUCCESS) break; } break; case TEE_OPERATION_MAC: if (key1 == 0 || key2 != 0) { res = TEE_ERROR_BAD_PARAMETERS; } else { res = crypto_mac_alloc_ctx(&cs->ctx, algo); if (res != TEE_SUCCESS) break; } break; case TEE_OPERATION_DIGEST: if (key1 != 0 || key2 != 0) { res = TEE_ERROR_BAD_PARAMETERS; } else { res = crypto_hash_alloc_ctx(&cs->ctx, algo); if (res != TEE_SUCCESS) break; } break; case TEE_OPERATION_ASYMMETRIC_CIPHER: case TEE_OPERATION_ASYMMETRIC_SIGNATURE: rsassa_na1: __maybe_unused if (key1 == 0 || key2 != 0) res = TEE_ERROR_BAD_PARAMETERS; break; case TEE_OPERATION_KEY_DERIVATION: if (key1 == 0 || key2 != 0) res = TEE_ERROR_BAD_PARAMETERS; break; default: res = TEE_ERROR_NOT_SUPPORTED; break; } if (res != TEE_SUCCESS) goto out; res = tee_svc_copy_kaddr_to_uref(state, cs); if (res != TEE_SUCCESS) goto out; /* Register keys */ if (o1 != NULL) { o1->busy = true; cs->key1 = (vaddr_t)o1; } if (o2 != NULL) { o2->busy = true; cs->key2 = (vaddr_t)o2; } out: if (res != TEE_SUCCESS) cryp_state_free(utc, cs); return res; } TEE_Result syscall_cryp_state_copy(unsigned long dst, unsigned long src) { TEE_Result res; struct tee_cryp_state *cs_dst; struct tee_cryp_state *cs_src; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(dst), &cs_dst); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(src), &cs_src); if (res != TEE_SUCCESS) return res; if (cs_dst->algo != cs_src->algo || cs_dst->mode != cs_src->mode) return TEE_ERROR_BAD_PARAMETERS; switch (TEE_ALG_GET_CLASS(cs_src->algo)) { case TEE_OPERATION_CIPHER: crypto_cipher_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo); break; case TEE_OPERATION_AE: crypto_authenc_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo); break; case TEE_OPERATION_DIGEST: crypto_hash_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo); break; case TEE_OPERATION_MAC: crypto_mac_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo); break; default: return TEE_ERROR_BAD_STATE; } return TEE_SUCCESS; } void tee_svc_cryp_free_states(struct user_ta_ctx *utc) { struct tee_cryp_state_head *states = &utc->cryp_states; while (!TAILQ_EMPTY(states)) cryp_state_free(utc, TAILQ_FIRST(states)); } TEE_Result syscall_cryp_state_free(unsigned long state) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; cryp_state_free(to_user_ta_ctx(sess->ctx), cs); return TEE_SUCCESS; } TEE_Result syscall_hash_init(unsigned long state, const void *iv __maybe_unused, size_t iv_len __maybe_unused) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_DIGEST: res = crypto_hash_init(cs->ctx, cs->algo); if (res != TEE_SUCCESS) return res; break; case TEE_OPERATION_MAC: { struct tee_obj *o; struct tee_cryp_obj_secret *key; res = tee_obj_get(to_user_ta_ctx(sess->ctx), cs->key1, &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; key = (struct tee_cryp_obj_secret *)o->attr; res = crypto_mac_init(cs->ctx, cs->algo, (void *)(key + 1), key->key_size); if (res != TEE_SUCCESS) return res; break; } default: return TEE_ERROR_BAD_PARAMETERS; } return TEE_SUCCESS; } TEE_Result syscall_hash_update(unsigned long state, const void *chunk, size_t chunk_size) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; /* No data, but size provided isn't valid parameters. */ if (!chunk && chunk_size) return TEE_ERROR_BAD_PARAMETERS; /* Zero length hash is valid, but nothing we need to do. */ if (!chunk_size) return TEE_SUCCESS; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)chunk, chunk_size); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_DIGEST: res = crypto_hash_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; break; case TEE_OPERATION_MAC: res = crypto_mac_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; break; default: return TEE_ERROR_BAD_PARAMETERS; } return TEE_SUCCESS; } TEE_Result syscall_hash_final(unsigned long state, const void *chunk, size_t chunk_size, void *hash, uint64_t *hash_len) { TEE_Result res, res2; size_t hash_size; uint64_t hlen; struct tee_cryp_state *cs; struct tee_ta_session *sess; /* No data, but size provided isn't valid parameters. */ if (!chunk && chunk_size) return TEE_ERROR_BAD_PARAMETERS; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)chunk, chunk_size); if (res != TEE_SUCCESS) return res; res = tee_svc_copy_from_user(&hlen, hash_len, sizeof(hlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)hash, hlen); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_DIGEST: res = tee_hash_get_digest_size(cs->algo, &hash_size); if (res != TEE_SUCCESS) return res; if (*hash_len < hash_size) { res = TEE_ERROR_SHORT_BUFFER; goto out; } if (chunk_size) { res = crypto_hash_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; } res = crypto_hash_final(cs->ctx, cs->algo, hash, hash_size); if (res != TEE_SUCCESS) return res; break; case TEE_OPERATION_MAC: res = tee_mac_get_digest_size(cs->algo, &hash_size); if (res != TEE_SUCCESS) return res; if (*hash_len < hash_size) { res = TEE_ERROR_SHORT_BUFFER; goto out; } if (chunk_size) { res = crypto_mac_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; } res = crypto_mac_final(cs->ctx, cs->algo, hash, hash_size); if (res != TEE_SUCCESS) return res; break; default: return TEE_ERROR_BAD_PARAMETERS; } out: hlen = hash_size; res2 = tee_svc_copy_to_user(hash_len, &hlen, sizeof(*hash_len)); if (res2 != TEE_SUCCESS) return res2; return res; } TEE_Result syscall_cipher_init(unsigned long state, const void *iv, size_t iv_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; struct tee_obj *o; struct tee_cryp_obj_secret *key1; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) iv, iv_len); if (res != TEE_SUCCESS) return res; res = tee_obj_get(utc, cs->key1, &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; key1 = o->attr; if (tee_obj_get(utc, cs->key2, &o) == TEE_SUCCESS) { struct tee_cryp_obj_secret *key2 = o->attr; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; res = crypto_cipher_init(cs->ctx, cs->algo, cs->mode, (uint8_t *)(key1 + 1), key1->key_size, (uint8_t *)(key2 + 1), key2->key_size, iv, iv_len); } else { res = crypto_cipher_init(cs->ctx, cs->algo, cs->mode, (uint8_t *)(key1 + 1), key1->key_size, NULL, 0, iv, iv_len); } if (res != TEE_SUCCESS) return res; cs->ctx_finalize = crypto_cipher_final; return TEE_SUCCESS; } static TEE_Result tee_svc_cipher_update_helper(unsigned long state, bool last_block, const void *src, size_t src_len, void *dst, uint64_t *dst_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)src, src_len); if (res != TEE_SUCCESS) return res; if (!dst_len) { dlen = 0; } else { res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)dst, dlen); if (res != TEE_SUCCESS) return res; } if (dlen < src_len) { res = TEE_ERROR_SHORT_BUFFER; goto out; } if (src_len > 0) { /* Permit src_len == 0 to finalize the operation */ res = tee_do_cipher_update(cs->ctx, cs->algo, cs->mode, last_block, src, src_len, dst); } if (last_block && cs->ctx_finalize != NULL) { cs->ctx_finalize(cs->ctx, cs->algo); cs->ctx_finalize = NULL; } out: if ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) && dst_len != NULL) { TEE_Result res2; dlen = src_len; res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) res = res2; } return res; } TEE_Result syscall_cipher_update(unsigned long state, const void *src, size_t src_len, void *dst, uint64_t *dst_len) { return tee_svc_cipher_update_helper(state, false /* last_block */, src, src_len, dst, dst_len); } TEE_Result syscall_cipher_final(unsigned long state, const void *src, size_t src_len, void *dst, uint64_t *dst_len) { return tee_svc_cipher_update_helper(state, true /* last_block */, src, src_len, dst, dst_len); } #if defined(CFG_CRYPTO_HKDF) static TEE_Result get_hkdf_params(const TEE_Attribute *params, uint32_t param_count, void **salt, size_t *salt_len, void **info, size_t *info_len, size_t *okm_len) { size_t n; enum { SALT = 0x1, LENGTH = 0x2, INFO = 0x4 }; uint8_t found = 0; *salt = *info = NULL; *salt_len = *info_len = *okm_len = 0; for (n = 0; n < param_count; n++) { switch (params[n].attributeID) { case TEE_ATTR_HKDF_SALT: if (!(found & SALT)) { *salt = params[n].content.ref.buffer; *salt_len = params[n].content.ref.length; found |= SALT; } break; case TEE_ATTR_HKDF_OKM_LENGTH: if (!(found & LENGTH)) { *okm_len = params[n].content.value.a; found |= LENGTH; } break; case TEE_ATTR_HKDF_INFO: if (!(found & INFO)) { *info = params[n].content.ref.buffer; *info_len = params[n].content.ref.length; found |= INFO; } break; default: /* Unexpected attribute */ return TEE_ERROR_BAD_PARAMETERS; } } if (!(found & LENGTH)) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } #endif #if defined(CFG_CRYPTO_CONCAT_KDF) static TEE_Result get_concat_kdf_params(const TEE_Attribute *params, uint32_t param_count, void **other_info, size_t *other_info_len, size_t *derived_key_len) { size_t n; enum { LENGTH = 0x1, INFO = 0x2 }; uint8_t found = 0; *other_info = NULL; *other_info_len = *derived_key_len = 0; for (n = 0; n < param_count; n++) { switch (params[n].attributeID) { case TEE_ATTR_CONCAT_KDF_OTHER_INFO: if (!(found & INFO)) { *other_info = params[n].content.ref.buffer; *other_info_len = params[n].content.ref.length; found |= INFO; } break; case TEE_ATTR_CONCAT_KDF_DKM_LENGTH: if (!(found & LENGTH)) { *derived_key_len = params[n].content.value.a; found |= LENGTH; } break; default: /* Unexpected attribute */ return TEE_ERROR_BAD_PARAMETERS; } } if (!(found & LENGTH)) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } #endif #if defined(CFG_CRYPTO_PBKDF2) static TEE_Result get_pbkdf2_params(const TEE_Attribute *params, uint32_t param_count, void **salt, size_t *salt_len, size_t *derived_key_len, size_t *iteration_count) { size_t n; enum { SALT = 0x1, LENGTH = 0x2, COUNT = 0x4 }; uint8_t found = 0; *salt = NULL; *salt_len = *derived_key_len = *iteration_count = 0; for (n = 0; n < param_count; n++) { switch (params[n].attributeID) { case TEE_ATTR_PBKDF2_SALT: if (!(found & SALT)) { *salt = params[n].content.ref.buffer; *salt_len = params[n].content.ref.length; found |= SALT; } break; case TEE_ATTR_PBKDF2_DKM_LENGTH: if (!(found & LENGTH)) { *derived_key_len = params[n].content.value.a; found |= LENGTH; } break; case TEE_ATTR_PBKDF2_ITERATION_COUNT: if (!(found & COUNT)) { *iteration_count = params[n].content.value.a; found |= COUNT; } break; default: /* Unexpected attribute */ return TEE_ERROR_BAD_PARAMETERS; } } if ((found & (LENGTH|COUNT)) != (LENGTH|COUNT)) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } #endif TEE_Result syscall_cryp_derive_key(unsigned long state, const struct utee_attribute *usr_params, unsigned long param_count, unsigned long derived_key) { TEE_Result res = TEE_ERROR_NOT_SUPPORTED; struct tee_ta_session *sess; struct tee_obj *ko; struct tee_obj *so; struct tee_cryp_state *cs; struct tee_cryp_obj_secret *sk; const struct tee_cryp_obj_type_props *type_props; TEE_Attribute *params = NULL; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; params = malloc(sizeof(TEE_Attribute) * param_count); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(utc, usr_params, param_count, params); if (res != TEE_SUCCESS) goto out; /* Get key set in operation */ res = tee_obj_get(utc, cs->key1, &ko); if (res != TEE_SUCCESS) goto out; res = tee_obj_get(utc, tee_svc_uref_to_vaddr(derived_key), &so); if (res != TEE_SUCCESS) goto out; /* Find information needed about the object to initialize */ sk = so->attr; /* Find description of object */ type_props = tee_svc_find_type_props(so->info.objectType); if (!type_props) { res = TEE_ERROR_NOT_SUPPORTED; goto out; } if (cs->algo == TEE_ALG_DH_DERIVE_SHARED_SECRET) { size_t alloc_size; struct bignum *pub; struct bignum *ss; if (param_count != 1 || params[0].attributeID != TEE_ATTR_DH_PUBLIC_VALUE) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } alloc_size = params[0].content.ref.length * 8; pub = crypto_bignum_allocate(alloc_size); ss = crypto_bignum_allocate(alloc_size); if (pub && ss) { crypto_bignum_bin2bn(params[0].content.ref.buffer, params[0].content.ref.length, pub); res = crypto_acipher_dh_shared_secret(ko->attr, pub, ss); if (res == TEE_SUCCESS) { sk->key_size = crypto_bignum_num_bytes(ss); crypto_bignum_bn2bin(ss, (uint8_t *)(sk + 1)); so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } else { res = TEE_ERROR_OUT_OF_MEMORY; } crypto_bignum_free(pub); crypto_bignum_free(ss); } else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_ECDH) { size_t alloc_size; struct ecc_public_key key_public; uint8_t *pt_secret; unsigned long pt_secret_len; if (param_count != 2 || params[0].attributeID != TEE_ATTR_ECC_PUBLIC_VALUE_X || params[1].attributeID != TEE_ATTR_ECC_PUBLIC_VALUE_Y) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } switch (cs->algo) { case TEE_ALG_ECDH_P192: alloc_size = 192; break; case TEE_ALG_ECDH_P224: alloc_size = 224; break; case TEE_ALG_ECDH_P256: alloc_size = 256; break; case TEE_ALG_ECDH_P384: alloc_size = 384; break; case TEE_ALG_ECDH_P521: alloc_size = 521; break; default: res = TEE_ERROR_NOT_IMPLEMENTED; goto out; } /* Create the public key */ res = crypto_acipher_alloc_ecc_public_key(&key_public, alloc_size); if (res != TEE_SUCCESS) goto out; key_public.curve = ((struct ecc_keypair *)ko->attr)->curve; crypto_bignum_bin2bn(params[0].content.ref.buffer, params[0].content.ref.length, key_public.x); crypto_bignum_bin2bn(params[1].content.ref.buffer, params[1].content.ref.length, key_public.y); pt_secret = (uint8_t *)(sk + 1); pt_secret_len = sk->alloc_size; res = crypto_acipher_ecc_shared_secret(ko->attr, &key_public, pt_secret, &pt_secret_len); if (res == TEE_SUCCESS) { sk->key_size = pt_secret_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } /* free the public key */ crypto_acipher_free_ecc_public_key(&key_public); } #if defined(CFG_CRYPTO_HKDF) else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_HKDF) { void *salt, *info; size_t salt_len, info_len, okm_len; uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo); struct tee_cryp_obj_secret *ik = ko->attr; const uint8_t *ikm = (const uint8_t *)(ik + 1); res = get_hkdf_params(params, param_count, &salt, &salt_len, &info, &info_len, &okm_len); if (res != TEE_SUCCESS) goto out; /* Requested size must fit into the output object's buffer */ if (okm_len > ik->alloc_size) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_cryp_hkdf(hash_id, ikm, ik->key_size, salt, salt_len, info, info_len, (uint8_t *)(sk + 1), okm_len); if (res == TEE_SUCCESS) { sk->key_size = okm_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } #endif #if defined(CFG_CRYPTO_CONCAT_KDF) else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_CONCAT_KDF) { void *info; size_t info_len, derived_key_len; uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo); struct tee_cryp_obj_secret *ss = ko->attr; const uint8_t *shared_secret = (const uint8_t *)(ss + 1); res = get_concat_kdf_params(params, param_count, &info, &info_len, &derived_key_len); if (res != TEE_SUCCESS) goto out; /* Requested size must fit into the output object's buffer */ if (derived_key_len > ss->alloc_size) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_cryp_concat_kdf(hash_id, shared_secret, ss->key_size, info, info_len, (uint8_t *)(sk + 1), derived_key_len); if (res == TEE_SUCCESS) { sk->key_size = derived_key_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } #endif #if defined(CFG_CRYPTO_PBKDF2) else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_PBKDF2) { void *salt; size_t salt_len, iteration_count, derived_key_len; uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo); struct tee_cryp_obj_secret *ss = ko->attr; const uint8_t *password = (const uint8_t *)(ss + 1); res = get_pbkdf2_params(params, param_count, &salt, &salt_len, &derived_key_len, &iteration_count); if (res != TEE_SUCCESS) goto out; /* Requested size must fit into the output object's buffer */ if (derived_key_len > ss->alloc_size) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_cryp_pbkdf2(hash_id, password, ss->key_size, salt, salt_len, iteration_count, (uint8_t *)(sk + 1), derived_key_len); if (res == TEE_SUCCESS) { sk->key_size = derived_key_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } #endif else res = TEE_ERROR_NOT_SUPPORTED; out: free(params); return res; } TEE_Result syscall_cryp_random_number_generate(void *buf, size_t blen) { TEE_Result res; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)buf, blen); if (res != TEE_SUCCESS) return res; res = crypto_rng_read(buf, blen); if (res != TEE_SUCCESS) return res; return res; } TEE_Result syscall_authenc_init(unsigned long state, const void *nonce, size_t nonce_len, size_t tag_len, size_t aad_len, size_t payload_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; struct tee_obj *o; struct tee_cryp_obj_secret *key; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), cs->key1, &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; key = o->attr; res = crypto_authenc_init(cs->ctx, cs->algo, cs->mode, (uint8_t *)(key + 1), key->key_size, nonce, nonce_len, tag_len, aad_len, payload_len); if (res != TEE_SUCCESS) return res; cs->ctx_finalize = (tee_cryp_ctx_finalize_func_t)crypto_authenc_final; return TEE_SUCCESS; } TEE_Result syscall_authenc_update_aad(unsigned long state, const void *aad_data, size_t aad_data_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) aad_data, aad_data_len); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = crypto_authenc_update_aad(cs->ctx, cs->algo, cs->mode, aad_data, aad_data_len); if (res != TEE_SUCCESS) return res; return TEE_SUCCESS; } TEE_Result syscall_authenc_update_payload(unsigned long state, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen; size_t tmp_dlen; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) src_data, src_len); if (res != TEE_SUCCESS) return res; res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)dst_data, dlen); if (res != TEE_SUCCESS) return res; if (dlen < src_len) { res = TEE_ERROR_SHORT_BUFFER; goto out; } tmp_dlen = dlen; res = crypto_authenc_update_payload(cs->ctx, cs->algo, cs->mode, src_data, src_len, dst_data, &tmp_dlen); dlen = tmp_dlen; out: if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) { TEE_Result res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) res = res2; } return res; } TEE_Result syscall_authenc_enc_final(unsigned long state, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len, void *tag, uint64_t *tag_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen; uint64_t tlen = 0; size_t tmp_dlen; size_t tmp_tlen; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; if (cs->mode != TEE_MODE_ENCRYPT) return TEE_ERROR_BAD_PARAMETERS; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)src_data, src_len); if (res != TEE_SUCCESS) return res; if (!dst_len) { dlen = 0; } else { res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)dst_data, dlen); if (res != TEE_SUCCESS) return res; } if (dlen < src_len) { res = TEE_ERROR_SHORT_BUFFER; goto out; } res = tee_svc_copy_from_user(&tlen, tag_len, sizeof(tlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)tag, tlen); if (res != TEE_SUCCESS) return res; tmp_dlen = dlen; tmp_tlen = tlen; res = crypto_authenc_enc_final(cs->ctx, cs->algo, src_data, src_len, dst_data, &tmp_dlen, tag, &tmp_tlen); dlen = tmp_dlen; tlen = tmp_tlen; out: if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) { TEE_Result res2; if (dst_len != NULL) { res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) return res2; } res2 = tee_svc_copy_to_user(tag_len, &tlen, sizeof(*tag_len)); if (res2 != TEE_SUCCESS) return res2; } return res; } TEE_Result syscall_authenc_dec_final(unsigned long state, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len, const void *tag, size_t tag_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen; size_t tmp_dlen; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; if (cs->mode != TEE_MODE_DECRYPT) return TEE_ERROR_BAD_PARAMETERS; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)src_data, src_len); if (res != TEE_SUCCESS) return res; if (!dst_len) { dlen = 0; } else { res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)dst_data, dlen); if (res != TEE_SUCCESS) return res; } if (dlen < src_len) { res = TEE_ERROR_SHORT_BUFFER; goto out; } res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)tag, tag_len); if (res != TEE_SUCCESS) return res; tmp_dlen = dlen; res = crypto_authenc_dec_final(cs->ctx, cs->algo, src_data, src_len, dst_data, &tmp_dlen, tag, tag_len); dlen = tmp_dlen; out: if ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) && dst_len != NULL) { TEE_Result res2; res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) return res2; } return res; } static int pkcs1_get_salt_len(const TEE_Attribute *params, uint32_t num_params, size_t default_len) { size_t n; assert(default_len < INT_MAX); for (n = 0; n < num_params; n++) { if (params[n].attributeID == TEE_ATTR_RSA_PSS_SALT_LENGTH) { if (params[n].content.value.a < INT_MAX) return params[n].content.value.a; break; } } /* * If salt length isn't provided use the default value which is * the length of the digest. */ return default_len; } TEE_Result syscall_asymm_operate(unsigned long state, const struct utee_attribute *usr_params, size_t num_params, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen64; size_t dlen; struct tee_obj *o; void *label = NULL; size_t label_len = 0; size_t n; int salt_len; TEE_Attribute *params = NULL; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights( utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) src_data, src_len); if (res != TEE_SUCCESS) return res; res = tee_svc_copy_from_user(&dlen64, dst_len, sizeof(dlen64)); if (res != TEE_SUCCESS) return res; dlen = dlen64; res = tee_mmu_check_access_rights( utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) dst_data, dlen); if (res != TEE_SUCCESS) return res; params = malloc(sizeof(TEE_Attribute) * num_params); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(utc, usr_params, num_params, params); if (res != TEE_SUCCESS) goto out; res = tee_obj_get(utc, cs->key1, &o); if (res != TEE_SUCCESS) goto out; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) { res = TEE_ERROR_GENERIC; goto out; } switch (cs->algo) { case TEE_ALG_RSA_NOPAD: if (cs->mode == TEE_MODE_ENCRYPT) { res = crypto_acipher_rsanopad_encrypt(o->attr, src_data, src_len, dst_data, &dlen); } else if (cs->mode == TEE_MODE_DECRYPT) { res = crypto_acipher_rsanopad_decrypt(o->attr, src_data, src_len, dst_data, &dlen); } else { /* * We will panic because "the mode is not compatible * with the function" */ res = TEE_ERROR_GENERIC; } break; case TEE_ALG_RSAES_PKCS1_V1_5: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512: for (n = 0; n < num_params; n++) { if (params[n].attributeID == TEE_ATTR_RSA_OAEP_LABEL) { label = params[n].content.ref.buffer; label_len = params[n].content.ref.length; break; } } if (cs->mode == TEE_MODE_ENCRYPT) { res = crypto_acipher_rsaes_encrypt(cs->algo, o->attr, label, label_len, src_data, src_len, dst_data, &dlen); } else if (cs->mode == TEE_MODE_DECRYPT) { res = crypto_acipher_rsaes_decrypt( cs->algo, o->attr, label, label_len, src_data, src_len, dst_data, &dlen); } else { res = TEE_ERROR_BAD_PARAMETERS; } break; #if defined(CFG_CRYPTO_RSASSA_NA1) case TEE_ALG_RSASSA_PKCS1_V1_5: #endif case TEE_ALG_RSASSA_PKCS1_V1_5_MD5: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512: if (cs->mode != TEE_MODE_SIGN) { res = TEE_ERROR_BAD_PARAMETERS; break; } salt_len = pkcs1_get_salt_len(params, num_params, src_len); res = crypto_acipher_rsassa_sign(cs->algo, o->attr, salt_len, src_data, src_len, dst_data, &dlen); break; case TEE_ALG_DSA_SHA1: case TEE_ALG_DSA_SHA224: case TEE_ALG_DSA_SHA256: res = crypto_acipher_dsa_sign(cs->algo, o->attr, src_data, src_len, dst_data, &dlen); break; case TEE_ALG_ECDSA_P192: case TEE_ALG_ECDSA_P224: case TEE_ALG_ECDSA_P256: case TEE_ALG_ECDSA_P384: case TEE_ALG_ECDSA_P521: res = crypto_acipher_ecc_sign(cs->algo, o->attr, src_data, src_len, dst_data, &dlen); break; default: res = TEE_ERROR_BAD_PARAMETERS; break; } out: free(params); if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) { TEE_Result res2; dlen64 = dlen; res2 = tee_svc_copy_to_user(dst_len, &dlen64, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) return res2; } return res; } TEE_Result syscall_asymm_verify(unsigned long state, const struct utee_attribute *usr_params, size_t num_params, const void *data, size_t data_len, const void *sig, size_t sig_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; struct tee_obj *o; size_t hash_size; int salt_len = 0; TEE_Attribute *params = NULL; uint32_t hash_algo; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; if (cs->mode != TEE_MODE_VERIFY) return TEE_ERROR_BAD_PARAMETERS; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)data, data_len); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)sig, sig_len); if (res != TEE_SUCCESS) return res; params = malloc(sizeof(TEE_Attribute) * num_params); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(utc, usr_params, num_params, params); if (res != TEE_SUCCESS) goto out; res = tee_obj_get(utc, cs->key1, &o); if (res != TEE_SUCCESS) goto out; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } switch (TEE_ALG_GET_MAIN_ALG(cs->algo)) { case TEE_MAIN_ALGO_RSA: if (cs->algo != TEE_ALG_RSASSA_PKCS1_V1_5) { hash_algo = TEE_DIGEST_HASH_TO_ALGO(cs->algo); res = tee_hash_get_digest_size(hash_algo, &hash_size); if (res != TEE_SUCCESS) break; if (data_len != hash_size) { res = TEE_ERROR_BAD_PARAMETERS; break; } salt_len = pkcs1_get_salt_len(params, num_params, hash_size); } res = crypto_acipher_rsassa_verify(cs->algo, o->attr, salt_len, data, data_len, sig, sig_len); break; case TEE_MAIN_ALGO_DSA: hash_algo = TEE_DIGEST_HASH_TO_ALGO(cs->algo); res = tee_hash_get_digest_size(hash_algo, &hash_size); if (res != TEE_SUCCESS) break; /* * Depending on the DSA algorithm (NIST), the digital signature * output size may be truncated to the size of a key pair * (Q prime size). Q prime size must be less or equal than the * hash output length of the hash algorithm involved. */ if (data_len > hash_size) { res = TEE_ERROR_BAD_PARAMETERS; break; } res = crypto_acipher_dsa_verify(cs->algo, o->attr, data, data_len, sig, sig_len); break; case TEE_MAIN_ALGO_ECDSA: res = crypto_acipher_ecc_verify(cs->algo, o->attr, data, data_len, sig, sig_len); break; default: res = TEE_ERROR_NOT_SUPPORTED; } out: free(params); return res; }
null
// SPDX-License-Identifier: BSD-2-Clause /* * Copyright (c) 2014, STMicroelectronics International N.V. */ #include <assert.h> #include <compiler.h> #include <crypto/crypto.h> #include <kernel/tee_ta_manager.h> #include <mm/tee_mmu.h> #include <string_ext.h> #include <string.h> #include <sys/queue.h> #include <tee_api_types.h> #include <tee/tee_cryp_utl.h> #include <tee/tee_obj.h> #include <tee/tee_svc_cryp.h> #include <tee/tee_svc.h> #include <trace.h> #include <utee_defines.h> #include <util.h> #include <tee_api_defines_extensions.h> #if defined(CFG_CRYPTO_HKDF) #include <tee/tee_cryp_hkdf.h> #endif #if defined(CFG_CRYPTO_CONCAT_KDF) #include <tee/tee_cryp_concat_kdf.h> #endif #if defined(CFG_CRYPTO_PBKDF2) #include <tee/tee_cryp_pbkdf2.h> #endif typedef void (*tee_cryp_ctx_finalize_func_t) (void *ctx, uint32_t algo); struct tee_cryp_state { TAILQ_ENTRY(tee_cryp_state) link; uint32_t algo; uint32_t mode; vaddr_t key1; vaddr_t key2; void *ctx; tee_cryp_ctx_finalize_func_t ctx_finalize; }; struct tee_cryp_obj_secret { uint32_t key_size; uint32_t alloc_size; /* * Pseudo code visualize layout of structure * Next follows data, such as: * uint8_t data[alloc_size] * key_size must never exceed alloc_size */ }; #define TEE_TYPE_ATTR_OPTIONAL 0x0 #define TEE_TYPE_ATTR_REQUIRED 0x1 #define TEE_TYPE_ATTR_OPTIONAL_GROUP 0x2 #define TEE_TYPE_ATTR_SIZE_INDICATOR 0x4 #define TEE_TYPE_ATTR_GEN_KEY_OPT 0x8 #define TEE_TYPE_ATTR_GEN_KEY_REQ 0x10 /* Handle storing of generic secret keys of varying lengths */ #define ATTR_OPS_INDEX_SECRET 0 /* Convert to/from big-endian byte array and provider-specific bignum */ #define ATTR_OPS_INDEX_BIGNUM 1 /* Convert to/from value attribute depending on direction */ #define ATTR_OPS_INDEX_VALUE 2 struct tee_cryp_obj_type_attrs { uint32_t attr_id; uint16_t flags; uint16_t ops_index; uint16_t raw_offs; uint16_t raw_size; }; #define RAW_DATA(_x, _y) \ .raw_offs = offsetof(_x, _y), .raw_size = MEMBER_SIZE(_x, _y) static const struct tee_cryp_obj_type_attrs tee_cryp_obj_secret_value_attrs[] = { { .attr_id = TEE_ATTR_SECRET_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_SECRET, .raw_offs = 0, .raw_size = 0 }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_rsa_pub_key_attrs[] = { { .attr_id = TEE_ATTR_RSA_MODULUS, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_public_key, n) }, { .attr_id = TEE_ATTR_RSA_PUBLIC_EXPONENT, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_public_key, e) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_rsa_keypair_attrs[] = { { .attr_id = TEE_ATTR_RSA_MODULUS, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, n) }, { .attr_id = TEE_ATTR_RSA_PUBLIC_EXPONENT, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, e) }, { .attr_id = TEE_ATTR_RSA_PRIVATE_EXPONENT, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, d) }, { .attr_id = TEE_ATTR_RSA_PRIME1, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, p) }, { .attr_id = TEE_ATTR_RSA_PRIME2, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, q) }, { .attr_id = TEE_ATTR_RSA_EXPONENT1, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, dp) }, { .attr_id = TEE_ATTR_RSA_EXPONENT2, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, dq) }, { .attr_id = TEE_ATTR_RSA_COEFFICIENT, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, qp) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dsa_pub_key_attrs[] = { { .attr_id = TEE_ATTR_DSA_PRIME, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_public_key, p) }, { .attr_id = TEE_ATTR_DSA_SUBPRIME, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_public_key, q) }, { .attr_id = TEE_ATTR_DSA_BASE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_public_key, g) }, { .attr_id = TEE_ATTR_DSA_PUBLIC_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_public_key, y) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dsa_keypair_attrs[] = { { .attr_id = TEE_ATTR_DSA_PRIME, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, p) }, { .attr_id = TEE_ATTR_DSA_SUBPRIME, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, q) }, { .attr_id = TEE_ATTR_DSA_BASE, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, g) }, { .attr_id = TEE_ATTR_DSA_PRIVATE_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, x) }, { .attr_id = TEE_ATTR_DSA_PUBLIC_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, y) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dh_keypair_attrs[] = { { .attr_id = TEE_ATTR_DH_PRIME, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, p) }, { .attr_id = TEE_ATTR_DH_BASE, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, g) }, { .attr_id = TEE_ATTR_DH_PUBLIC_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, y) }, { .attr_id = TEE_ATTR_DH_PRIVATE_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, x) }, { .attr_id = TEE_ATTR_DH_SUBPRIME, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP | TEE_TYPE_ATTR_GEN_KEY_OPT, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, q) }, { .attr_id = TEE_ATTR_DH_X_BITS, .flags = TEE_TYPE_ATTR_GEN_KEY_OPT, .ops_index = ATTR_OPS_INDEX_VALUE, RAW_DATA(struct dh_keypair, xbits) }, }; #if defined(CFG_CRYPTO_HKDF) static const struct tee_cryp_obj_type_attrs tee_cryp_obj_hkdf_ikm_attrs[] = { { .attr_id = TEE_ATTR_HKDF_IKM, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_SECRET, .raw_offs = 0, .raw_size = 0 }, }; #endif #if defined(CFG_CRYPTO_CONCAT_KDF) static const struct tee_cryp_obj_type_attrs tee_cryp_obj_concat_kdf_z_attrs[] = { { .attr_id = TEE_ATTR_CONCAT_KDF_Z, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_SECRET, .raw_offs = 0, .raw_size = 0 }, }; #endif #if defined(CFG_CRYPTO_PBKDF2) static const struct tee_cryp_obj_type_attrs tee_cryp_obj_pbkdf2_passwd_attrs[] = { { .attr_id = TEE_ATTR_PBKDF2_PASSWORD, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_SECRET, .raw_offs = 0, .raw_size = 0 }, }; #endif static const struct tee_cryp_obj_type_attrs tee_cryp_obj_ecc_pub_key_attrs[] = { { .attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_X, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_public_key, x) }, { .attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_Y, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_public_key, y) }, { .attr_id = TEE_ATTR_ECC_CURVE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_VALUE, RAW_DATA(struct ecc_public_key, curve) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_ecc_keypair_attrs[] = { { .attr_id = TEE_ATTR_ECC_PRIVATE_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_keypair, d) }, { .attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_X, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_keypair, x) }, { .attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_Y, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_keypair, y) }, { .attr_id = TEE_ATTR_ECC_CURVE, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_VALUE, RAW_DATA(struct ecc_keypair, curve) }, }; struct tee_cryp_obj_type_props { TEE_ObjectType obj_type; uint16_t min_size; /* may not be smaller than this */ uint16_t max_size; /* may not be larger than this */ uint16_t alloc_size; /* this many bytes are allocated to hold data */ uint8_t quanta; /* may only be an multiple of this */ uint8_t num_type_attrs; const struct tee_cryp_obj_type_attrs *type_attrs; }; #define PROP(obj_type, quanta, min_size, max_size, alloc_size, type_attrs) \ { (obj_type), (min_size), (max_size), (alloc_size), (quanta), \ ARRAY_SIZE(type_attrs), (type_attrs) } static const struct tee_cryp_obj_type_props tee_cryp_obj_props[] = { PROP(TEE_TYPE_AES, 64, 128, 256, /* valid sizes 128, 192, 256 */ 256 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_DES, 56, 56, 56, /* * Valid size 56 without parity, note that we still allocate * for 64 bits since the key is supplied with parity. */ 64 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_DES3, 56, 112, 168, /* * Valid sizes 112, 168 without parity, note that we still * allocate for with space for the parity since the key is * supplied with parity. */ 192 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_MD5, 8, 64, 512, 512 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA1, 8, 80, 512, 512 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA224, 8, 112, 512, 512 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA256, 8, 192, 1024, 1024 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA384, 8, 256, 1024, 1024 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA512, 8, 256, 1024, 1024 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_GENERIC_SECRET, 8, 0, 4096, 4096 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), #if defined(CFG_CRYPTO_HKDF) PROP(TEE_TYPE_HKDF_IKM, 8, 0, 4096, 4096 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_hkdf_ikm_attrs), #endif #if defined(CFG_CRYPTO_CONCAT_KDF) PROP(TEE_TYPE_CONCAT_KDF_Z, 8, 0, 4096, 4096 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_concat_kdf_z_attrs), #endif #if defined(CFG_CRYPTO_PBKDF2) PROP(TEE_TYPE_PBKDF2_PASSWORD, 8, 0, 4096, 4096 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_pbkdf2_passwd_attrs), #endif PROP(TEE_TYPE_RSA_PUBLIC_KEY, 1, 256, CFG_CORE_BIGNUM_MAX_BITS, sizeof(struct rsa_public_key), tee_cryp_obj_rsa_pub_key_attrs), PROP(TEE_TYPE_RSA_KEYPAIR, 1, 256, CFG_CORE_BIGNUM_MAX_BITS, sizeof(struct rsa_keypair), tee_cryp_obj_rsa_keypair_attrs), PROP(TEE_TYPE_DSA_PUBLIC_KEY, 64, 512, 3072, sizeof(struct dsa_public_key), tee_cryp_obj_dsa_pub_key_attrs), PROP(TEE_TYPE_DSA_KEYPAIR, 64, 512, 3072, sizeof(struct dsa_keypair), tee_cryp_obj_dsa_keypair_attrs), PROP(TEE_TYPE_DH_KEYPAIR, 1, 256, 2048, sizeof(struct dh_keypair), tee_cryp_obj_dh_keypair_attrs), PROP(TEE_TYPE_ECDSA_PUBLIC_KEY, 1, 192, 521, sizeof(struct ecc_public_key), tee_cryp_obj_ecc_pub_key_attrs), PROP(TEE_TYPE_ECDSA_KEYPAIR, 1, 192, 521, sizeof(struct ecc_keypair), tee_cryp_obj_ecc_keypair_attrs), PROP(TEE_TYPE_ECDH_PUBLIC_KEY, 1, 192, 521, sizeof(struct ecc_public_key), tee_cryp_obj_ecc_pub_key_attrs), PROP(TEE_TYPE_ECDH_KEYPAIR, 1, 192, 521, sizeof(struct ecc_keypair), tee_cryp_obj_ecc_keypair_attrs), }; struct attr_ops { TEE_Result (*from_user)(void *attr, const void *buffer, size_t size); TEE_Result (*to_user)(void *attr, struct tee_ta_session *sess, void *buffer, uint64_t *size); TEE_Result (*to_binary)(void *attr, void *data, size_t data_len, size_t *offs); bool (*from_binary)(void *attr, const void *data, size_t data_len, size_t *offs); TEE_Result (*from_obj)(void *attr, void *src_attr); void (*free)(void *attr); void (*clear)(void *attr); }; static TEE_Result op_u32_to_binary_helper(uint32_t v, uint8_t *data, size_t data_len, size_t *offs) { uint32_t field; size_t next_offs; if (ADD_OVERFLOW(*offs, sizeof(field), &next_offs)) return TEE_ERROR_OVERFLOW; if (data && next_offs <= data_len) { field = TEE_U32_TO_BIG_ENDIAN(v); memcpy(data + *offs, &field, sizeof(field)); } (*offs) = next_offs; return TEE_SUCCESS; } static bool op_u32_from_binary_helper(uint32_t *v, const uint8_t *data, size_t data_len, size_t *offs) { uint32_t field; if (!data || (*offs + sizeof(field)) > data_len) return false; memcpy(&field, data + *offs, sizeof(field)); *v = TEE_U32_FROM_BIG_ENDIAN(field); (*offs) += sizeof(field); return true; } static TEE_Result op_attr_secret_value_from_user(void *attr, const void *buffer, size_t size) { struct tee_cryp_obj_secret *key = attr; /* Data size has to fit in allocated buffer */ if (size > key->alloc_size) return TEE_ERROR_SECURITY; memcpy(key + 1, buffer, size); key->key_size = size; return TEE_SUCCESS; } static TEE_Result op_attr_secret_value_to_user(void *attr, struct tee_ta_session *sess __unused, void *buffer, uint64_t *size) { TEE_Result res; struct tee_cryp_obj_secret *key = attr; uint64_t s; uint64_t key_size; res = tee_svc_copy_from_user(&s, size, sizeof(s)); if (res != TEE_SUCCESS) return res; key_size = key->key_size; res = tee_svc_copy_to_user(size, &key_size, sizeof(key_size)); if (res != TEE_SUCCESS) return res; if (s < key->key_size || !buffer) return TEE_ERROR_SHORT_BUFFER; return tee_svc_copy_to_user(buffer, key + 1, key->key_size); } static TEE_Result op_attr_secret_value_to_binary(void *attr, void *data, size_t data_len, size_t *offs) { TEE_Result res; struct tee_cryp_obj_secret *key = attr; size_t next_offs; res = op_u32_to_binary_helper(key->key_size, data, data_len, offs); if (res != TEE_SUCCESS) return res; if (ADD_OVERFLOW(*offs, key->key_size, &next_offs)) return TEE_ERROR_OVERFLOW; if (data && next_offs <= data_len) memcpy((uint8_t *)data + *offs, key + 1, key->key_size); (*offs) = next_offs; return TEE_SUCCESS; } static bool op_attr_secret_value_from_binary(void *attr, const void *data, size_t data_len, size_t *offs) { struct tee_cryp_obj_secret *key = attr; uint32_t s; if (!op_u32_from_binary_helper(&s, data, data_len, offs)) return false; if ((*offs + s) > data_len) return false; /* Data size has to fit in allocated buffer */ if (s > key->alloc_size) return false; key->key_size = s; memcpy(key + 1, (const uint8_t *)data + *offs, s); (*offs) += s; return true; } static TEE_Result op_attr_secret_value_from_obj(void *attr, void *src_attr) { struct tee_cryp_obj_secret *key = attr; struct tee_cryp_obj_secret *src_key = src_attr; if (src_key->key_size > key->alloc_size) return TEE_ERROR_BAD_STATE; memcpy(key + 1, src_key + 1, src_key->key_size); key->key_size = src_key->key_size; return TEE_SUCCESS; } static void op_attr_secret_value_clear(void *attr) { struct tee_cryp_obj_secret *key = attr; key->key_size = 0; memset(key + 1, 0, key->alloc_size); } static TEE_Result op_attr_bignum_from_user(void *attr, const void *buffer, size_t size) { struct bignum **bn = attr; return crypto_bignum_bin2bn(buffer, size, *bn); } static TEE_Result op_attr_bignum_to_user(void *attr, struct tee_ta_session *sess, void *buffer, uint64_t *size) { TEE_Result res; struct bignum **bn = attr; uint64_t req_size; uint64_t s; res = tee_svc_copy_from_user(&s, size, sizeof(s)); if (res != TEE_SUCCESS) return res; req_size = crypto_bignum_num_bytes(*bn); res = tee_svc_copy_to_user(size, &req_size, sizeof(req_size)); if (res != TEE_SUCCESS) return res; if (!req_size) return TEE_SUCCESS; if (s < req_size || !buffer) return TEE_ERROR_SHORT_BUFFER; /* Check we can access data using supplied user mode pointer */ res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)buffer, req_size); if (res != TEE_SUCCESS) return res; /* * Write the bignum (wich raw data points to) into an array of * bytes (stored in buffer) */ crypto_bignum_bn2bin(*bn, buffer); return TEE_SUCCESS; } static TEE_Result op_attr_bignum_to_binary(void *attr, void *data, size_t data_len, size_t *offs) { TEE_Result res; struct bignum **bn = attr; uint32_t n = crypto_bignum_num_bytes(*bn); size_t next_offs; res = op_u32_to_binary_helper(n, data, data_len, offs); if (res != TEE_SUCCESS) return res; if (ADD_OVERFLOW(*offs, n, &next_offs)) return TEE_ERROR_OVERFLOW; if (data && next_offs <= data_len) crypto_bignum_bn2bin(*bn, (uint8_t *)data + *offs); (*offs) = next_offs; return TEE_SUCCESS; } static bool op_attr_bignum_from_binary(void *attr, const void *data, size_t data_len, size_t *offs) { struct bignum **bn = attr; uint32_t n; if (!op_u32_from_binary_helper(&n, data, data_len, offs)) return false; if ((*offs + n) > data_len) return false; if (crypto_bignum_bin2bn((const uint8_t *)data + *offs, n, *bn)) return false; (*offs) += n; return true; } static TEE_Result op_attr_bignum_from_obj(void *attr, void *src_attr) { struct bignum **bn = attr; struct bignum **src_bn = src_attr; crypto_bignum_copy(*bn, *src_bn); return TEE_SUCCESS; } static void op_attr_bignum_clear(void *attr) { struct bignum **bn = attr; crypto_bignum_clear(*bn); } static void op_attr_bignum_free(void *attr) { struct bignum **bn = attr; crypto_bignum_free(*bn); *bn = NULL; } static TEE_Result op_attr_value_from_user(void *attr, const void *buffer, size_t size) { uint32_t *v = attr; if (size != sizeof(uint32_t) * 2) return TEE_ERROR_GENERIC; /* "can't happen */ /* Note that only the first value is copied */ memcpy(v, buffer, sizeof(uint32_t)); return TEE_SUCCESS; } static TEE_Result op_attr_value_to_user(void *attr, struct tee_ta_session *sess __unused, void *buffer, uint64_t *size) { TEE_Result res; uint32_t *v = attr; uint64_t s; uint32_t value[2] = { *v }; uint64_t req_size = sizeof(value); res = tee_svc_copy_from_user(&s, size, sizeof(s)); if (res != TEE_SUCCESS) return res; if (s < req_size || !buffer) return TEE_ERROR_SHORT_BUFFER; return tee_svc_copy_to_user(buffer, value, req_size); } static TEE_Result op_attr_value_to_binary(void *attr, void *data, size_t data_len, size_t *offs) { uint32_t *v = attr; return op_u32_to_binary_helper(*v, data, data_len, offs); } static bool op_attr_value_from_binary(void *attr, const void *data, size_t data_len, size_t *offs) { uint32_t *v = attr; return op_u32_from_binary_helper(v, data, data_len, offs); } static TEE_Result op_attr_value_from_obj(void *attr, void *src_attr) { uint32_t *v = attr; uint32_t *src_v = src_attr; *v = *src_v; return TEE_SUCCESS; } static void op_attr_value_clear(void *attr) { uint32_t *v = attr; *v = 0; } static const struct attr_ops attr_ops[] = { [ATTR_OPS_INDEX_SECRET] = { .from_user = op_attr_secret_value_from_user, .to_user = op_attr_secret_value_to_user, .to_binary = op_attr_secret_value_to_binary, .from_binary = op_attr_secret_value_from_binary, .from_obj = op_attr_secret_value_from_obj, .free = op_attr_secret_value_clear, /* not a typo */ .clear = op_attr_secret_value_clear, }, [ATTR_OPS_INDEX_BIGNUM] = { .from_user = op_attr_bignum_from_user, .to_user = op_attr_bignum_to_user, .to_binary = op_attr_bignum_to_binary, .from_binary = op_attr_bignum_from_binary, .from_obj = op_attr_bignum_from_obj, .free = op_attr_bignum_free, .clear = op_attr_bignum_clear, }, [ATTR_OPS_INDEX_VALUE] = { .from_user = op_attr_value_from_user, .to_user = op_attr_value_to_user, .to_binary = op_attr_value_to_binary, .from_binary = op_attr_value_from_binary, .from_obj = op_attr_value_from_obj, .free = op_attr_value_clear, /* not a typo */ .clear = op_attr_value_clear, }, }; TEE_Result syscall_cryp_obj_get_info(unsigned long obj, TEE_ObjectInfo *info) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) goto exit; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) goto exit; res = tee_svc_copy_to_user(info, &o->info, sizeof(o->info)); exit: return res; } TEE_Result syscall_cryp_obj_restrict_usage(unsigned long obj, unsigned long usage) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) goto exit; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) goto exit; o->info.objectUsage &= usage; exit: return res; } static int tee_svc_cryp_obj_find_type_attr_idx( uint32_t attr_id, const struct tee_cryp_obj_type_props *type_props) { size_t n; for (n = 0; n < type_props->num_type_attrs; n++) { if (attr_id == type_props->type_attrs[n].attr_id) return n; } return -1; } static const struct tee_cryp_obj_type_props *tee_svc_find_type_props( TEE_ObjectType obj_type) { size_t n; for (n = 0; n < ARRAY_SIZE(tee_cryp_obj_props); n++) { if (tee_cryp_obj_props[n].obj_type == obj_type) return tee_cryp_obj_props + n; } return NULL; } /* Set an attribute on an object */ static void set_attribute(struct tee_obj *o, const struct tee_cryp_obj_type_props *props, uint32_t attr) { int idx = tee_svc_cryp_obj_find_type_attr_idx(attr, props); if (idx < 0) return; o->have_attrs |= BIT(idx); } /* Get an attribute on an object */ static uint32_t get_attribute(const struct tee_obj *o, const struct tee_cryp_obj_type_props *props, uint32_t attr) { int idx = tee_svc_cryp_obj_find_type_attr_idx(attr, props); if (idx < 0) return 0; return o->have_attrs & BIT(idx); } TEE_Result syscall_cryp_obj_get_attr(unsigned long obj, unsigned long attr_id, void *buffer, uint64_t *size) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; const struct tee_cryp_obj_type_props *type_props; int idx; const struct attr_ops *ops; void *attr; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return TEE_ERROR_ITEM_NOT_FOUND; /* Check that the object is initialized */ if (!(o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED)) return TEE_ERROR_BAD_PARAMETERS; /* Check that getting the attribute is allowed */ if (!(attr_id & TEE_ATTR_BIT_PROTECTED) && !(o->info.objectUsage & TEE_USAGE_EXTRACTABLE)) return TEE_ERROR_BAD_PARAMETERS; type_props = tee_svc_find_type_props(o->info.objectType); if (!type_props) { /* Unknown object type, "can't happen" */ return TEE_ERROR_BAD_STATE; } idx = tee_svc_cryp_obj_find_type_attr_idx(attr_id, type_props); if ((idx < 0) || ((o->have_attrs & (1 << idx)) == 0)) return TEE_ERROR_ITEM_NOT_FOUND; ops = attr_ops + type_props->type_attrs[idx].ops_index; attr = (uint8_t *)o->attr + type_props->type_attrs[idx].raw_offs; return ops->to_user(attr, sess, buffer, size); } void tee_obj_attr_free(struct tee_obj *o) { const struct tee_cryp_obj_type_props *tp; size_t n; if (!o->attr) return; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return; for (n = 0; n < tp->num_type_attrs; n++) { const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n; attr_ops[ta->ops_index].free((uint8_t *)o->attr + ta->raw_offs); } } void tee_obj_attr_clear(struct tee_obj *o) { const struct tee_cryp_obj_type_props *tp; size_t n; if (!o->attr) return; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return; for (n = 0; n < tp->num_type_attrs; n++) { const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n; attr_ops[ta->ops_index].clear((uint8_t *)o->attr + ta->raw_offs); } } TEE_Result tee_obj_attr_to_binary(struct tee_obj *o, void *data, size_t *data_len) { const struct tee_cryp_obj_type_props *tp; size_t n; size_t offs = 0; size_t len = data ? *data_len : 0; TEE_Result res; if (o->info.objectType == TEE_TYPE_DATA) { *data_len = 0; return TEE_SUCCESS; /* pure data object */ } if (!o->attr) return TEE_ERROR_BAD_STATE; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return TEE_ERROR_BAD_STATE; for (n = 0; n < tp->num_type_attrs; n++) { const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n; void *attr = (uint8_t *)o->attr + ta->raw_offs; res = attr_ops[ta->ops_index].to_binary(attr, data, len, &offs); if (res != TEE_SUCCESS) return res; } *data_len = offs; if (data && offs > len) return TEE_ERROR_SHORT_BUFFER; return TEE_SUCCESS; } TEE_Result tee_obj_attr_from_binary(struct tee_obj *o, const void *data, size_t data_len) { const struct tee_cryp_obj_type_props *tp; size_t n; size_t offs = 0; if (o->info.objectType == TEE_TYPE_DATA) return TEE_SUCCESS; /* pure data object */ if (!o->attr) return TEE_ERROR_BAD_STATE; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return TEE_ERROR_BAD_STATE; for (n = 0; n < tp->num_type_attrs; n++) { const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n; void *attr = (uint8_t *)o->attr + ta->raw_offs; if (!attr_ops[ta->ops_index].from_binary(attr, data, data_len, &offs)) return TEE_ERROR_CORRUPT_OBJECT; } return TEE_SUCCESS; } TEE_Result tee_obj_attr_copy_from(struct tee_obj *o, const struct tee_obj *src) { TEE_Result res; const struct tee_cryp_obj_type_props *tp; const struct tee_cryp_obj_type_attrs *ta; size_t n; uint32_t have_attrs = 0; void *attr; void *src_attr; if (o->info.objectType == TEE_TYPE_DATA) return TEE_SUCCESS; /* pure data object */ if (!o->attr) return TEE_ERROR_BAD_STATE; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return TEE_ERROR_BAD_STATE; if (o->info.objectType == src->info.objectType) { have_attrs = src->have_attrs; for (n = 0; n < tp->num_type_attrs; n++) { ta = tp->type_attrs + n; attr = (uint8_t *)o->attr + ta->raw_offs; src_attr = (uint8_t *)src->attr + ta->raw_offs; res = attr_ops[ta->ops_index].from_obj(attr, src_attr); if (res != TEE_SUCCESS) return res; } } else { const struct tee_cryp_obj_type_props *tp_src; int idx; if (o->info.objectType == TEE_TYPE_RSA_PUBLIC_KEY) { if (src->info.objectType != TEE_TYPE_RSA_KEYPAIR) return TEE_ERROR_BAD_PARAMETERS; } else if (o->info.objectType == TEE_TYPE_DSA_PUBLIC_KEY) { if (src->info.objectType != TEE_TYPE_DSA_KEYPAIR) return TEE_ERROR_BAD_PARAMETERS; } else if (o->info.objectType == TEE_TYPE_ECDSA_PUBLIC_KEY) { if (src->info.objectType != TEE_TYPE_ECDSA_KEYPAIR) return TEE_ERROR_BAD_PARAMETERS; } else if (o->info.objectType == TEE_TYPE_ECDH_PUBLIC_KEY) { if (src->info.objectType != TEE_TYPE_ECDH_KEYPAIR) return TEE_ERROR_BAD_PARAMETERS; } else { return TEE_ERROR_BAD_PARAMETERS; } tp_src = tee_svc_find_type_props(src->info.objectType); if (!tp_src) return TEE_ERROR_BAD_STATE; have_attrs = BIT32(tp->num_type_attrs) - 1; for (n = 0; n < tp->num_type_attrs; n++) { ta = tp->type_attrs + n; idx = tee_svc_cryp_obj_find_type_attr_idx(ta->attr_id, tp_src); if (idx < 0) return TEE_ERROR_BAD_STATE; attr = (uint8_t *)o->attr + ta->raw_offs; src_attr = (uint8_t *)src->attr + tp_src->type_attrs[idx].raw_offs; res = attr_ops[ta->ops_index].from_obj(attr, src_attr); if (res != TEE_SUCCESS) return res; } } o->have_attrs = have_attrs; return TEE_SUCCESS; } TEE_Result tee_obj_set_type(struct tee_obj *o, uint32_t obj_type, size_t max_key_size) { TEE_Result res = TEE_SUCCESS; const struct tee_cryp_obj_type_props *type_props; /* Can only set type for newly allocated objs */ if (o->attr) return TEE_ERROR_BAD_STATE; /* * Verify that maxKeySize is supported and find out how * much should be allocated. */ if (obj_type == TEE_TYPE_DATA) { if (max_key_size) return TEE_ERROR_NOT_SUPPORTED; } else { /* Find description of object */ type_props = tee_svc_find_type_props(obj_type); if (!type_props) return TEE_ERROR_NOT_SUPPORTED; /* Check that maxKeySize follows restrictions */ if (max_key_size % type_props->quanta != 0) return TEE_ERROR_NOT_SUPPORTED; if (max_key_size < type_props->min_size) return TEE_ERROR_NOT_SUPPORTED; if (max_key_size > type_props->max_size) return TEE_ERROR_NOT_SUPPORTED; o->attr = calloc(1, type_props->alloc_size); if (!o->attr) return TEE_ERROR_OUT_OF_MEMORY; } /* If we have a key structure, pre-allocate the bignums inside */ switch (obj_type) { case TEE_TYPE_RSA_PUBLIC_KEY: res = crypto_acipher_alloc_rsa_public_key(o->attr, max_key_size); break; case TEE_TYPE_RSA_KEYPAIR: res = crypto_acipher_alloc_rsa_keypair(o->attr, max_key_size); break; case TEE_TYPE_DSA_PUBLIC_KEY: res = crypto_acipher_alloc_dsa_public_key(o->attr, max_key_size); break; case TEE_TYPE_DSA_KEYPAIR: res = crypto_acipher_alloc_dsa_keypair(o->attr, max_key_size); break; case TEE_TYPE_DH_KEYPAIR: res = crypto_acipher_alloc_dh_keypair(o->attr, max_key_size); break; case TEE_TYPE_ECDSA_PUBLIC_KEY: case TEE_TYPE_ECDH_PUBLIC_KEY: res = crypto_acipher_alloc_ecc_public_key(o->attr, max_key_size); break; case TEE_TYPE_ECDSA_KEYPAIR: case TEE_TYPE_ECDH_KEYPAIR: res = crypto_acipher_alloc_ecc_keypair(o->attr, max_key_size); break; default: if (obj_type != TEE_TYPE_DATA) { struct tee_cryp_obj_secret *key = o->attr; key->alloc_size = type_props->alloc_size - sizeof(*key); } break; } if (res != TEE_SUCCESS) return res; o->info.objectType = obj_type; o->info.maxKeySize = max_key_size; o->info.objectUsage = TEE_USAGE_DEFAULT; return TEE_SUCCESS; } TEE_Result syscall_cryp_obj_alloc(unsigned long obj_type, unsigned long max_key_size, uint32_t *obj) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; if (obj_type == TEE_TYPE_DATA) return TEE_ERROR_NOT_SUPPORTED; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; o = tee_obj_alloc(); if (!o) return TEE_ERROR_OUT_OF_MEMORY; res = tee_obj_set_type(o, obj_type, max_key_size); if (res != TEE_SUCCESS) { tee_obj_free(o); return res; } tee_obj_add(to_user_ta_ctx(sess->ctx), o); res = tee_svc_copy_kaddr_to_uref(obj, o); if (res != TEE_SUCCESS) tee_obj_close(to_user_ta_ctx(sess->ctx), o); return res; } TEE_Result syscall_cryp_obj_close(unsigned long obj) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; /* * If it's busy it's used by an operation, a client should never have * this handle. */ if (o->busy) return TEE_ERROR_ITEM_NOT_FOUND; tee_obj_close(to_user_ta_ctx(sess->ctx), o); return TEE_SUCCESS; } TEE_Result syscall_cryp_obj_reset(unsigned long obj) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) == 0) { tee_obj_attr_clear(o); o->info.keySize = 0; o->info.objectUsage = TEE_USAGE_DEFAULT; } else { return TEE_ERROR_BAD_PARAMETERS; } /* the object is no more initialized */ o->info.handleFlags &= ~TEE_HANDLE_FLAG_INITIALIZED; return TEE_SUCCESS; } static TEE_Result copy_in_attrs(struct user_ta_ctx *utc, const struct utee_attribute *usr_attrs, uint32_t attr_count, TEE_Attribute *attrs) { TEE_Result res; uint32_t n; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)usr_attrs, attr_count * sizeof(struct utee_attribute)); if (res != TEE_SUCCESS) return res; for (n = 0; n < attr_count; n++) { attrs[n].attributeID = usr_attrs[n].attribute_id; if (attrs[n].attributeID & TEE_ATTR_BIT_VALUE) { attrs[n].content.value.a = usr_attrs[n].a; attrs[n].content.value.b = usr_attrs[n].b; } else { uintptr_t buf = usr_attrs[n].a; size_t len = usr_attrs[n].b; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, buf, len); if (res != TEE_SUCCESS) return res; attrs[n].content.ref.buffer = (void *)buf; attrs[n].content.ref.length = len; } } return TEE_SUCCESS; } enum attr_usage { ATTR_USAGE_POPULATE, ATTR_USAGE_GENERATE_KEY }; static TEE_Result tee_svc_cryp_check_attr(enum attr_usage usage, const struct tee_cryp_obj_type_props *type_props, const TEE_Attribute *attrs, uint32_t attr_count) { uint32_t required_flag; uint32_t opt_flag; bool all_opt_needed; uint32_t req_attrs = 0; uint32_t opt_grp_attrs = 0; uint32_t attrs_found = 0; size_t n; uint32_t bit; uint32_t flags; int idx; if (usage == ATTR_USAGE_POPULATE) { required_flag = TEE_TYPE_ATTR_REQUIRED; opt_flag = TEE_TYPE_ATTR_OPTIONAL_GROUP; all_opt_needed = true; } else { required_flag = TEE_TYPE_ATTR_GEN_KEY_REQ; opt_flag = TEE_TYPE_ATTR_GEN_KEY_OPT; all_opt_needed = false; } /* * First find out which attributes are required and which belong to * the optional group */ for (n = 0; n < type_props->num_type_attrs; n++) { bit = 1 << n; flags = type_props->type_attrs[n].flags; if (flags & required_flag) req_attrs |= bit; else if (flags & opt_flag) opt_grp_attrs |= bit; } /* * Verify that all required attributes are in place and * that the same attribute isn't repeated. */ for (n = 0; n < attr_count; n++) { idx = tee_svc_cryp_obj_find_type_attr_idx( attrs[n].attributeID, type_props); /* attribute not defined in current object type */ if (idx < 0) return TEE_ERROR_ITEM_NOT_FOUND; bit = 1 << idx; /* attribute not repeated */ if ((attrs_found & bit) != 0) return TEE_ERROR_ITEM_NOT_FOUND; attrs_found |= bit; } /* Required attribute missing */ if ((attrs_found & req_attrs) != req_attrs) return TEE_ERROR_ITEM_NOT_FOUND; /* * If the flag says that "if one of the optional attributes are included * all of them has to be included" this must be checked. */ if (all_opt_needed && (attrs_found & opt_grp_attrs) != 0 && (attrs_found & opt_grp_attrs) != opt_grp_attrs) return TEE_ERROR_ITEM_NOT_FOUND; return TEE_SUCCESS; } static TEE_Result get_ec_key_size(uint32_t curve, size_t *key_size) { switch (curve) { case TEE_ECC_CURVE_NIST_P192: *key_size = 192; break; case TEE_ECC_CURVE_NIST_P224: *key_size = 224; break; case TEE_ECC_CURVE_NIST_P256: *key_size = 256; break; case TEE_ECC_CURVE_NIST_P384: *key_size = 384; break; case TEE_ECC_CURVE_NIST_P521: *key_size = 521; break; default: return TEE_ERROR_NOT_SUPPORTED; } return TEE_SUCCESS; } static TEE_Result tee_svc_cryp_obj_populate_type( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, const TEE_Attribute *attrs, uint32_t attr_count) { TEE_Result res; uint32_t have_attrs = 0; size_t obj_size = 0; size_t n; int idx; const struct attr_ops *ops; void *attr; for (n = 0; n < attr_count; n++) { idx = tee_svc_cryp_obj_find_type_attr_idx( attrs[n].attributeID, type_props); /* attribute not defined in current object type */ if (idx < 0) return TEE_ERROR_ITEM_NOT_FOUND; have_attrs |= BIT32(idx); ops = attr_ops + type_props->type_attrs[idx].ops_index; attr = (uint8_t *)o->attr + type_props->type_attrs[idx].raw_offs; if (attrs[n].attributeID & TEE_ATTR_BIT_VALUE) res = ops->from_user(attr, &attrs[n].content.value, sizeof(attrs[n].content.value)); else res = ops->from_user(attr, attrs[n].content.ref.buffer, attrs[n].content.ref.length); if (res != TEE_SUCCESS) return res; /* * First attr_idx signifies the attribute that gives the size * of the object */ if (type_props->type_attrs[idx].flags & TEE_TYPE_ATTR_SIZE_INDICATOR) { /* * For ECDSA/ECDH we need to translate curve into * object size */ if (attrs[n].attributeID == TEE_ATTR_ECC_CURVE) { res = get_ec_key_size(attrs[n].content.value.a, &obj_size); if (res != TEE_SUCCESS) return res; } else { obj_size += (attrs[n].content.ref.length * 8); } } } /* * We have to do it like this because the parity bits aren't counted * when telling the size of the key in bits. */ if (o->info.objectType == TEE_TYPE_DES || o->info.objectType == TEE_TYPE_DES3) obj_size -= obj_size / 8; /* Exclude parity in size of key */ o->have_attrs = have_attrs; o->info.keySize = obj_size; return TEE_SUCCESS; } TEE_Result syscall_cryp_obj_populate(unsigned long obj, struct utee_attribute *usr_attrs, unsigned long attr_count) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; const struct tee_cryp_obj_type_props *type_props; TEE_Attribute *attrs = NULL; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; /* Must be a transient object */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0) return TEE_ERROR_BAD_PARAMETERS; /* Must not be initialized already */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0) return TEE_ERROR_BAD_PARAMETERS; type_props = tee_svc_find_type_props(o->info.objectType); if (!type_props) return TEE_ERROR_NOT_IMPLEMENTED; size_t alloc_size = 0; if (MUL_OVERFLOW(sizeof(TEE_Attribute), attr_count, &alloc_size)) return TEE_ERROR_OVERFLOW; attrs = malloc(alloc_size); if (!attrs) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_attrs, attr_count, attrs); if (res != TEE_SUCCESS) goto out; res = tee_svc_cryp_check_attr(ATTR_USAGE_POPULATE, type_props, attrs, attr_count); if (res != TEE_SUCCESS) goto out; res = tee_svc_cryp_obj_populate_type(o, type_props, attrs, attr_count); if (res == TEE_SUCCESS) o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; out: free(attrs); return res; } TEE_Result syscall_cryp_obj_copy(unsigned long dst, unsigned long src) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *dst_o; struct tee_obj *src_o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(dst), &dst_o); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(src), &src_o); if (res != TEE_SUCCESS) return res; if ((src_o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; if ((dst_o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0) return TEE_ERROR_BAD_PARAMETERS; if ((dst_o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0) return TEE_ERROR_BAD_PARAMETERS; res = tee_obj_attr_copy_from(dst_o, src_o); if (res != TEE_SUCCESS) return res; dst_o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; dst_o->info.keySize = src_o->info.keySize; dst_o->info.objectUsage = src_o->info.objectUsage; return TEE_SUCCESS; } static TEE_Result tee_svc_obj_generate_key_rsa( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, uint32_t key_size, const TEE_Attribute *params, uint32_t param_count) { TEE_Result res; struct rsa_keypair *key = o->attr; uint32_t e = TEE_U32_TO_BIG_ENDIAN(65537); /* Copy the present attributes into the obj before starting */ res = tee_svc_cryp_obj_populate_type(o, type_props, params, param_count); if (res != TEE_SUCCESS) return res; if (!get_attribute(o, type_props, TEE_ATTR_RSA_PUBLIC_EXPONENT)) crypto_bignum_bin2bn((const uint8_t *)&e, sizeof(e), key->e); res = crypto_acipher_gen_rsa_key(key, key_size); if (res != TEE_SUCCESS) return res; /* Set bits for all known attributes for this object type */ o->have_attrs = (1 << type_props->num_type_attrs) - 1; return TEE_SUCCESS; } static TEE_Result tee_svc_obj_generate_key_dsa( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, uint32_t key_size) { TEE_Result res; res = crypto_acipher_gen_dsa_key(o->attr, key_size); if (res != TEE_SUCCESS) return res; /* Set bits for all known attributes for this object type */ o->have_attrs = (1 << type_props->num_type_attrs) - 1; return TEE_SUCCESS; } static TEE_Result tee_svc_obj_generate_key_dh( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, uint32_t key_size __unused, const TEE_Attribute *params, uint32_t param_count) { TEE_Result res; struct dh_keypair *tee_dh_key; struct bignum *dh_q = NULL; uint32_t dh_xbits = 0; /* Copy the present attributes into the obj before starting */ res = tee_svc_cryp_obj_populate_type(o, type_props, params, param_count); if (res != TEE_SUCCESS) return res; tee_dh_key = (struct dh_keypair *)o->attr; if (get_attribute(o, type_props, TEE_ATTR_DH_SUBPRIME)) dh_q = tee_dh_key->q; if (get_attribute(o, type_props, TEE_ATTR_DH_X_BITS)) dh_xbits = tee_dh_key->xbits; res = crypto_acipher_gen_dh_key(tee_dh_key, dh_q, dh_xbits); if (res != TEE_SUCCESS) return res; /* Set bits for the generated public and private key */ set_attribute(o, type_props, TEE_ATTR_DH_PUBLIC_VALUE); set_attribute(o, type_props, TEE_ATTR_DH_PRIVATE_VALUE); set_attribute(o, type_props, TEE_ATTR_DH_X_BITS); return TEE_SUCCESS; } static TEE_Result tee_svc_obj_generate_key_ecc( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, uint32_t key_size __unused, const TEE_Attribute *params, uint32_t param_count) { TEE_Result res; struct ecc_keypair *tee_ecc_key; /* Copy the present attributes into the obj before starting */ res = tee_svc_cryp_obj_populate_type(o, type_props, params, param_count); if (res != TEE_SUCCESS) return res; tee_ecc_key = (struct ecc_keypair *)o->attr; res = crypto_acipher_gen_ecc_key(tee_ecc_key); if (res != TEE_SUCCESS) return res; /* Set bits for the generated public and private key */ set_attribute(o, type_props, TEE_ATTR_ECC_PRIVATE_VALUE); set_attribute(o, type_props, TEE_ATTR_ECC_PUBLIC_VALUE_X); set_attribute(o, type_props, TEE_ATTR_ECC_PUBLIC_VALUE_Y); set_attribute(o, type_props, TEE_ATTR_ECC_CURVE); return TEE_SUCCESS; } TEE_Result syscall_obj_generate_key(unsigned long obj, unsigned long key_size, const struct utee_attribute *usr_params, unsigned long param_count) { TEE_Result res; struct tee_ta_session *sess; const struct tee_cryp_obj_type_props *type_props; struct tee_obj *o; struct tee_cryp_obj_secret *key; size_t byte_size; TEE_Attribute *params = NULL; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; /* Must be a transient object */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0) return TEE_ERROR_BAD_STATE; /* Must not be initialized already */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0) return TEE_ERROR_BAD_STATE; /* Find description of object */ type_props = tee_svc_find_type_props(o->info.objectType); if (!type_props) return TEE_ERROR_NOT_SUPPORTED; /* Check that maxKeySize follows restrictions */ if (key_size % type_props->quanta != 0) return TEE_ERROR_NOT_SUPPORTED; if (key_size < type_props->min_size) return TEE_ERROR_NOT_SUPPORTED; if (key_size > type_props->max_size) return TEE_ERROR_NOT_SUPPORTED; size_t alloc_size = 0; if (MUL_OVERFLOW(sizeof(TEE_Attribute), param_count, &alloc_size)) return TEE_ERROR_OVERFLOW; params = malloc(alloc_size); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_params, param_count, params); if (res != TEE_SUCCESS) goto out; res = tee_svc_cryp_check_attr(ATTR_USAGE_GENERATE_KEY, type_props, params, param_count); if (res != TEE_SUCCESS) goto out; switch (o->info.objectType) { case TEE_TYPE_AES: case TEE_TYPE_DES: case TEE_TYPE_DES3: case TEE_TYPE_HMAC_MD5: case TEE_TYPE_HMAC_SHA1: case TEE_TYPE_HMAC_SHA224: case TEE_TYPE_HMAC_SHA256: case TEE_TYPE_HMAC_SHA384: case TEE_TYPE_HMAC_SHA512: case TEE_TYPE_GENERIC_SECRET: byte_size = key_size / 8; /* * We have to do it like this because the parity bits aren't * counted when telling the size of the key in bits. */ if (o->info.objectType == TEE_TYPE_DES || o->info.objectType == TEE_TYPE_DES3) { byte_size = (key_size + key_size / 7) / 8; } key = (struct tee_cryp_obj_secret *)o->attr; if (byte_size > key->alloc_size) { res = TEE_ERROR_EXCESS_DATA; goto out; } res = crypto_rng_read((void *)(key + 1), byte_size); if (res != TEE_SUCCESS) goto out; key->key_size = byte_size; /* Set bits for all known attributes for this object type */ o->have_attrs = (1 << type_props->num_type_attrs) - 1; break; case TEE_TYPE_RSA_KEYPAIR: res = tee_svc_obj_generate_key_rsa(o, type_props, key_size, params, param_count); if (res != TEE_SUCCESS) goto out; break; case TEE_TYPE_DSA_KEYPAIR: res = tee_svc_obj_generate_key_dsa(o, type_props, key_size); if (res != TEE_SUCCESS) goto out; break; case TEE_TYPE_DH_KEYPAIR: res = tee_svc_obj_generate_key_dh(o, type_props, key_size, params, param_count); if (res != TEE_SUCCESS) goto out; break; case TEE_TYPE_ECDSA_KEYPAIR: case TEE_TYPE_ECDH_KEYPAIR: res = tee_svc_obj_generate_key_ecc(o, type_props, key_size, params, param_count); if (res != TEE_SUCCESS) goto out; break; default: res = TEE_ERROR_BAD_FORMAT; } out: free(params); if (res == TEE_SUCCESS) { o->info.keySize = key_size; o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; } return res; } static TEE_Result tee_svc_cryp_get_state(struct tee_ta_session *sess, uint32_t state_id, struct tee_cryp_state **state) { struct tee_cryp_state *s; struct user_ta_ctx *utc = to_user_ta_ctx(sess->ctx); TAILQ_FOREACH(s, &utc->cryp_states, link) { if (state_id == (vaddr_t)s) { *state = s; return TEE_SUCCESS; } } return TEE_ERROR_BAD_PARAMETERS; } static void cryp_state_free(struct user_ta_ctx *utc, struct tee_cryp_state *cs) { struct tee_obj *o; if (tee_obj_get(utc, cs->key1, &o) == TEE_SUCCESS) tee_obj_close(utc, o); if (tee_obj_get(utc, cs->key2, &o) == TEE_SUCCESS) tee_obj_close(utc, o); TAILQ_REMOVE(&utc->cryp_states, cs, link); if (cs->ctx_finalize != NULL) cs->ctx_finalize(cs->ctx, cs->algo); switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_CIPHER: crypto_cipher_free_ctx(cs->ctx, cs->algo); break; case TEE_OPERATION_AE: crypto_authenc_free_ctx(cs->ctx, cs->algo); break; case TEE_OPERATION_DIGEST: crypto_hash_free_ctx(cs->ctx, cs->algo); break; case TEE_OPERATION_MAC: crypto_mac_free_ctx(cs->ctx, cs->algo); break; default: assert(!cs->ctx); } free(cs); } static TEE_Result tee_svc_cryp_check_key_type(const struct tee_obj *o, uint32_t algo, TEE_OperationMode mode) { uint32_t req_key_type; uint32_t req_key_type2 = 0; switch (TEE_ALG_GET_MAIN_ALG(algo)) { case TEE_MAIN_ALGO_MD5: req_key_type = TEE_TYPE_HMAC_MD5; break; case TEE_MAIN_ALGO_SHA1: req_key_type = TEE_TYPE_HMAC_SHA1; break; case TEE_MAIN_ALGO_SHA224: req_key_type = TEE_TYPE_HMAC_SHA224; break; case TEE_MAIN_ALGO_SHA256: req_key_type = TEE_TYPE_HMAC_SHA256; break; case TEE_MAIN_ALGO_SHA384: req_key_type = TEE_TYPE_HMAC_SHA384; break; case TEE_MAIN_ALGO_SHA512: req_key_type = TEE_TYPE_HMAC_SHA512; break; case TEE_MAIN_ALGO_AES: req_key_type = TEE_TYPE_AES; break; case TEE_MAIN_ALGO_DES: req_key_type = TEE_TYPE_DES; break; case TEE_MAIN_ALGO_DES3: req_key_type = TEE_TYPE_DES3; break; case TEE_MAIN_ALGO_RSA: req_key_type = TEE_TYPE_RSA_KEYPAIR; if (mode == TEE_MODE_ENCRYPT || mode == TEE_MODE_VERIFY) req_key_type2 = TEE_TYPE_RSA_PUBLIC_KEY; break; case TEE_MAIN_ALGO_DSA: req_key_type = TEE_TYPE_DSA_KEYPAIR; if (mode == TEE_MODE_ENCRYPT || mode == TEE_MODE_VERIFY) req_key_type2 = TEE_TYPE_DSA_PUBLIC_KEY; break; case TEE_MAIN_ALGO_DH: req_key_type = TEE_TYPE_DH_KEYPAIR; break; case TEE_MAIN_ALGO_ECDSA: req_key_type = TEE_TYPE_ECDSA_KEYPAIR; if (mode == TEE_MODE_VERIFY) req_key_type2 = TEE_TYPE_ECDSA_PUBLIC_KEY; break; case TEE_MAIN_ALGO_ECDH: req_key_type = TEE_TYPE_ECDH_KEYPAIR; break; #if defined(CFG_CRYPTO_HKDF) case TEE_MAIN_ALGO_HKDF: req_key_type = TEE_TYPE_HKDF_IKM; break; #endif #if defined(CFG_CRYPTO_CONCAT_KDF) case TEE_MAIN_ALGO_CONCAT_KDF: req_key_type = TEE_TYPE_CONCAT_KDF_Z; break; #endif #if defined(CFG_CRYPTO_PBKDF2) case TEE_MAIN_ALGO_PBKDF2: req_key_type = TEE_TYPE_PBKDF2_PASSWORD; break; #endif default: return TEE_ERROR_BAD_PARAMETERS; } if (req_key_type != o->info.objectType && req_key_type2 != o->info.objectType) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } TEE_Result syscall_cryp_state_alloc(unsigned long algo, unsigned long mode, unsigned long key1, unsigned long key2, uint32_t *state) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; struct tee_obj *o1 = NULL; struct tee_obj *o2 = NULL; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); if (key1 != 0) { res = tee_obj_get(utc, tee_svc_uref_to_vaddr(key1), &o1); if (res != TEE_SUCCESS) return res; if (o1->busy) return TEE_ERROR_BAD_PARAMETERS; res = tee_svc_cryp_check_key_type(o1, algo, mode); if (res != TEE_SUCCESS) return res; } if (key2 != 0) { res = tee_obj_get(utc, tee_svc_uref_to_vaddr(key2), &o2); if (res != TEE_SUCCESS) return res; if (o2->busy) return TEE_ERROR_BAD_PARAMETERS; res = tee_svc_cryp_check_key_type(o2, algo, mode); if (res != TEE_SUCCESS) return res; } cs = calloc(1, sizeof(struct tee_cryp_state)); if (!cs) return TEE_ERROR_OUT_OF_MEMORY; TAILQ_INSERT_TAIL(&utc->cryp_states, cs, link); cs->algo = algo; cs->mode = mode; switch (TEE_ALG_GET_CLASS(algo)) { case TEE_OPERATION_EXTENSION: #ifdef CFG_CRYPTO_RSASSA_NA1 if (algo == TEE_ALG_RSASSA_PKCS1_V1_5) goto rsassa_na1; #endif res = TEE_ERROR_NOT_SUPPORTED; break; case TEE_OPERATION_CIPHER: if ((algo == TEE_ALG_AES_XTS && (key1 == 0 || key2 == 0)) || (algo != TEE_ALG_AES_XTS && (key1 == 0 || key2 != 0))) { res = TEE_ERROR_BAD_PARAMETERS; } else { res = crypto_cipher_alloc_ctx(&cs->ctx, algo); if (res != TEE_SUCCESS) break; } break; case TEE_OPERATION_AE: if (key1 == 0 || key2 != 0) { res = TEE_ERROR_BAD_PARAMETERS; } else { res = crypto_authenc_alloc_ctx(&cs->ctx, algo); if (res != TEE_SUCCESS) break; } break; case TEE_OPERATION_MAC: if (key1 == 0 || key2 != 0) { res = TEE_ERROR_BAD_PARAMETERS; } else { res = crypto_mac_alloc_ctx(&cs->ctx, algo); if (res != TEE_SUCCESS) break; } break; case TEE_OPERATION_DIGEST: if (key1 != 0 || key2 != 0) { res = TEE_ERROR_BAD_PARAMETERS; } else { res = crypto_hash_alloc_ctx(&cs->ctx, algo); if (res != TEE_SUCCESS) break; } break; case TEE_OPERATION_ASYMMETRIC_CIPHER: case TEE_OPERATION_ASYMMETRIC_SIGNATURE: rsassa_na1: __maybe_unused if (key1 == 0 || key2 != 0) res = TEE_ERROR_BAD_PARAMETERS; break; case TEE_OPERATION_KEY_DERIVATION: if (key1 == 0 || key2 != 0) res = TEE_ERROR_BAD_PARAMETERS; break; default: res = TEE_ERROR_NOT_SUPPORTED; break; } if (res != TEE_SUCCESS) goto out; res = tee_svc_copy_kaddr_to_uref(state, cs); if (res != TEE_SUCCESS) goto out; /* Register keys */ if (o1 != NULL) { o1->busy = true; cs->key1 = (vaddr_t)o1; } if (o2 != NULL) { o2->busy = true; cs->key2 = (vaddr_t)o2; } out: if (res != TEE_SUCCESS) cryp_state_free(utc, cs); return res; } TEE_Result syscall_cryp_state_copy(unsigned long dst, unsigned long src) { TEE_Result res; struct tee_cryp_state *cs_dst; struct tee_cryp_state *cs_src; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(dst), &cs_dst); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(src), &cs_src); if (res != TEE_SUCCESS) return res; if (cs_dst->algo != cs_src->algo || cs_dst->mode != cs_src->mode) return TEE_ERROR_BAD_PARAMETERS; switch (TEE_ALG_GET_CLASS(cs_src->algo)) { case TEE_OPERATION_CIPHER: crypto_cipher_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo); break; case TEE_OPERATION_AE: crypto_authenc_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo); break; case TEE_OPERATION_DIGEST: crypto_hash_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo); break; case TEE_OPERATION_MAC: crypto_mac_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo); break; default: return TEE_ERROR_BAD_STATE; } return TEE_SUCCESS; } void tee_svc_cryp_free_states(struct user_ta_ctx *utc) { struct tee_cryp_state_head *states = &utc->cryp_states; while (!TAILQ_EMPTY(states)) cryp_state_free(utc, TAILQ_FIRST(states)); } TEE_Result syscall_cryp_state_free(unsigned long state) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; cryp_state_free(to_user_ta_ctx(sess->ctx), cs); return TEE_SUCCESS; } TEE_Result syscall_hash_init(unsigned long state, const void *iv __maybe_unused, size_t iv_len __maybe_unused) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_DIGEST: res = crypto_hash_init(cs->ctx, cs->algo); if (res != TEE_SUCCESS) return res; break; case TEE_OPERATION_MAC: { struct tee_obj *o; struct tee_cryp_obj_secret *key; res = tee_obj_get(to_user_ta_ctx(sess->ctx), cs->key1, &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; key = (struct tee_cryp_obj_secret *)o->attr; res = crypto_mac_init(cs->ctx, cs->algo, (void *)(key + 1), key->key_size); if (res != TEE_SUCCESS) return res; break; } default: return TEE_ERROR_BAD_PARAMETERS; } return TEE_SUCCESS; } TEE_Result syscall_hash_update(unsigned long state, const void *chunk, size_t chunk_size) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; /* No data, but size provided isn't valid parameters. */ if (!chunk && chunk_size) return TEE_ERROR_BAD_PARAMETERS; /* Zero length hash is valid, but nothing we need to do. */ if (!chunk_size) return TEE_SUCCESS; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)chunk, chunk_size); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_DIGEST: res = crypto_hash_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; break; case TEE_OPERATION_MAC: res = crypto_mac_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; break; default: return TEE_ERROR_BAD_PARAMETERS; } return TEE_SUCCESS; } TEE_Result syscall_hash_final(unsigned long state, const void *chunk, size_t chunk_size, void *hash, uint64_t *hash_len) { TEE_Result res, res2; size_t hash_size; uint64_t hlen; struct tee_cryp_state *cs; struct tee_ta_session *sess; /* No data, but size provided isn't valid parameters. */ if (!chunk && chunk_size) return TEE_ERROR_BAD_PARAMETERS; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)chunk, chunk_size); if (res != TEE_SUCCESS) return res; res = tee_svc_copy_from_user(&hlen, hash_len, sizeof(hlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)hash, hlen); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_DIGEST: res = tee_hash_get_digest_size(cs->algo, &hash_size); if (res != TEE_SUCCESS) return res; if (*hash_len < hash_size) { res = TEE_ERROR_SHORT_BUFFER; goto out; } if (chunk_size) { res = crypto_hash_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; } res = crypto_hash_final(cs->ctx, cs->algo, hash, hash_size); if (res != TEE_SUCCESS) return res; break; case TEE_OPERATION_MAC: res = tee_mac_get_digest_size(cs->algo, &hash_size); if (res != TEE_SUCCESS) return res; if (*hash_len < hash_size) { res = TEE_ERROR_SHORT_BUFFER; goto out; } if (chunk_size) { res = crypto_mac_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; } res = crypto_mac_final(cs->ctx, cs->algo, hash, hash_size); if (res != TEE_SUCCESS) return res; break; default: return TEE_ERROR_BAD_PARAMETERS; } out: hlen = hash_size; res2 = tee_svc_copy_to_user(hash_len, &hlen, sizeof(*hash_len)); if (res2 != TEE_SUCCESS) return res2; return res; } TEE_Result syscall_cipher_init(unsigned long state, const void *iv, size_t iv_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; struct tee_obj *o; struct tee_cryp_obj_secret *key1; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) iv, iv_len); if (res != TEE_SUCCESS) return res; res = tee_obj_get(utc, cs->key1, &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; key1 = o->attr; if (tee_obj_get(utc, cs->key2, &o) == TEE_SUCCESS) { struct tee_cryp_obj_secret *key2 = o->attr; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; res = crypto_cipher_init(cs->ctx, cs->algo, cs->mode, (uint8_t *)(key1 + 1), key1->key_size, (uint8_t *)(key2 + 1), key2->key_size, iv, iv_len); } else { res = crypto_cipher_init(cs->ctx, cs->algo, cs->mode, (uint8_t *)(key1 + 1), key1->key_size, NULL, 0, iv, iv_len); } if (res != TEE_SUCCESS) return res; cs->ctx_finalize = crypto_cipher_final; return TEE_SUCCESS; } static TEE_Result tee_svc_cipher_update_helper(unsigned long state, bool last_block, const void *src, size_t src_len, void *dst, uint64_t *dst_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)src, src_len); if (res != TEE_SUCCESS) return res; if (!dst_len) { dlen = 0; } else { res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)dst, dlen); if (res != TEE_SUCCESS) return res; } if (dlen < src_len) { res = TEE_ERROR_SHORT_BUFFER; goto out; } if (src_len > 0) { /* Permit src_len == 0 to finalize the operation */ res = tee_do_cipher_update(cs->ctx, cs->algo, cs->mode, last_block, src, src_len, dst); } if (last_block && cs->ctx_finalize != NULL) { cs->ctx_finalize(cs->ctx, cs->algo); cs->ctx_finalize = NULL; } out: if ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) && dst_len != NULL) { TEE_Result res2; dlen = src_len; res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) res = res2; } return res; } TEE_Result syscall_cipher_update(unsigned long state, const void *src, size_t src_len, void *dst, uint64_t *dst_len) { return tee_svc_cipher_update_helper(state, false /* last_block */, src, src_len, dst, dst_len); } TEE_Result syscall_cipher_final(unsigned long state, const void *src, size_t src_len, void *dst, uint64_t *dst_len) { return tee_svc_cipher_update_helper(state, true /* last_block */, src, src_len, dst, dst_len); } #if defined(CFG_CRYPTO_HKDF) static TEE_Result get_hkdf_params(const TEE_Attribute *params, uint32_t param_count, void **salt, size_t *salt_len, void **info, size_t *info_len, size_t *okm_len) { size_t n; enum { SALT = 0x1, LENGTH = 0x2, INFO = 0x4 }; uint8_t found = 0; *salt = *info = NULL; *salt_len = *info_len = *okm_len = 0; for (n = 0; n < param_count; n++) { switch (params[n].attributeID) { case TEE_ATTR_HKDF_SALT: if (!(found & SALT)) { *salt = params[n].content.ref.buffer; *salt_len = params[n].content.ref.length; found |= SALT; } break; case TEE_ATTR_HKDF_OKM_LENGTH: if (!(found & LENGTH)) { *okm_len = params[n].content.value.a; found |= LENGTH; } break; case TEE_ATTR_HKDF_INFO: if (!(found & INFO)) { *info = params[n].content.ref.buffer; *info_len = params[n].content.ref.length; found |= INFO; } break; default: /* Unexpected attribute */ return TEE_ERROR_BAD_PARAMETERS; } } if (!(found & LENGTH)) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } #endif #if defined(CFG_CRYPTO_CONCAT_KDF) static TEE_Result get_concat_kdf_params(const TEE_Attribute *params, uint32_t param_count, void **other_info, size_t *other_info_len, size_t *derived_key_len) { size_t n; enum { LENGTH = 0x1, INFO = 0x2 }; uint8_t found = 0; *other_info = NULL; *other_info_len = *derived_key_len = 0; for (n = 0; n < param_count; n++) { switch (params[n].attributeID) { case TEE_ATTR_CONCAT_KDF_OTHER_INFO: if (!(found & INFO)) { *other_info = params[n].content.ref.buffer; *other_info_len = params[n].content.ref.length; found |= INFO; } break; case TEE_ATTR_CONCAT_KDF_DKM_LENGTH: if (!(found & LENGTH)) { *derived_key_len = params[n].content.value.a; found |= LENGTH; } break; default: /* Unexpected attribute */ return TEE_ERROR_BAD_PARAMETERS; } } if (!(found & LENGTH)) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } #endif #if defined(CFG_CRYPTO_PBKDF2) static TEE_Result get_pbkdf2_params(const TEE_Attribute *params, uint32_t param_count, void **salt, size_t *salt_len, size_t *derived_key_len, size_t *iteration_count) { size_t n; enum { SALT = 0x1, LENGTH = 0x2, COUNT = 0x4 }; uint8_t found = 0; *salt = NULL; *salt_len = *derived_key_len = *iteration_count = 0; for (n = 0; n < param_count; n++) { switch (params[n].attributeID) { case TEE_ATTR_PBKDF2_SALT: if (!(found & SALT)) { *salt = params[n].content.ref.buffer; *salt_len = params[n].content.ref.length; found |= SALT; } break; case TEE_ATTR_PBKDF2_DKM_LENGTH: if (!(found & LENGTH)) { *derived_key_len = params[n].content.value.a; found |= LENGTH; } break; case TEE_ATTR_PBKDF2_ITERATION_COUNT: if (!(found & COUNT)) { *iteration_count = params[n].content.value.a; found |= COUNT; } break; default: /* Unexpected attribute */ return TEE_ERROR_BAD_PARAMETERS; } } if ((found & (LENGTH|COUNT)) != (LENGTH|COUNT)) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } #endif TEE_Result syscall_cryp_derive_key(unsigned long state, const struct utee_attribute *usr_params, unsigned long param_count, unsigned long derived_key) { TEE_Result res = TEE_ERROR_NOT_SUPPORTED; struct tee_ta_session *sess; struct tee_obj *ko; struct tee_obj *so; struct tee_cryp_state *cs; struct tee_cryp_obj_secret *sk; const struct tee_cryp_obj_type_props *type_props; TEE_Attribute *params = NULL; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; size_t alloc_size = 0; if (MUL_OVERFLOW(sizeof(TEE_Attribute), param_count, &alloc_size)) return TEE_ERROR_OVERFLOW; params = malloc(alloc_size); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(utc, usr_params, param_count, params); if (res != TEE_SUCCESS) goto out; /* Get key set in operation */ res = tee_obj_get(utc, cs->key1, &ko); if (res != TEE_SUCCESS) goto out; res = tee_obj_get(utc, tee_svc_uref_to_vaddr(derived_key), &so); if (res != TEE_SUCCESS) goto out; /* Find information needed about the object to initialize */ sk = so->attr; /* Find description of object */ type_props = tee_svc_find_type_props(so->info.objectType); if (!type_props) { res = TEE_ERROR_NOT_SUPPORTED; goto out; } if (cs->algo == TEE_ALG_DH_DERIVE_SHARED_SECRET) { size_t alloc_size; struct bignum *pub; struct bignum *ss; if (param_count != 1 || params[0].attributeID != TEE_ATTR_DH_PUBLIC_VALUE) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } alloc_size = params[0].content.ref.length * 8; pub = crypto_bignum_allocate(alloc_size); ss = crypto_bignum_allocate(alloc_size); if (pub && ss) { crypto_bignum_bin2bn(params[0].content.ref.buffer, params[0].content.ref.length, pub); res = crypto_acipher_dh_shared_secret(ko->attr, pub, ss); if (res == TEE_SUCCESS) { sk->key_size = crypto_bignum_num_bytes(ss); crypto_bignum_bn2bin(ss, (uint8_t *)(sk + 1)); so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } else { res = TEE_ERROR_OUT_OF_MEMORY; } crypto_bignum_free(pub); crypto_bignum_free(ss); } else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_ECDH) { size_t alloc_size; struct ecc_public_key key_public; uint8_t *pt_secret; unsigned long pt_secret_len; if (param_count != 2 || params[0].attributeID != TEE_ATTR_ECC_PUBLIC_VALUE_X || params[1].attributeID != TEE_ATTR_ECC_PUBLIC_VALUE_Y) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } switch (cs->algo) { case TEE_ALG_ECDH_P192: alloc_size = 192; break; case TEE_ALG_ECDH_P224: alloc_size = 224; break; case TEE_ALG_ECDH_P256: alloc_size = 256; break; case TEE_ALG_ECDH_P384: alloc_size = 384; break; case TEE_ALG_ECDH_P521: alloc_size = 521; break; default: res = TEE_ERROR_NOT_IMPLEMENTED; goto out; } /* Create the public key */ res = crypto_acipher_alloc_ecc_public_key(&key_public, alloc_size); if (res != TEE_SUCCESS) goto out; key_public.curve = ((struct ecc_keypair *)ko->attr)->curve; crypto_bignum_bin2bn(params[0].content.ref.buffer, params[0].content.ref.length, key_public.x); crypto_bignum_bin2bn(params[1].content.ref.buffer, params[1].content.ref.length, key_public.y); pt_secret = (uint8_t *)(sk + 1); pt_secret_len = sk->alloc_size; res = crypto_acipher_ecc_shared_secret(ko->attr, &key_public, pt_secret, &pt_secret_len); if (res == TEE_SUCCESS) { sk->key_size = pt_secret_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } /* free the public key */ crypto_acipher_free_ecc_public_key(&key_public); } #if defined(CFG_CRYPTO_HKDF) else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_HKDF) { void *salt, *info; size_t salt_len, info_len, okm_len; uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo); struct tee_cryp_obj_secret *ik = ko->attr; const uint8_t *ikm = (const uint8_t *)(ik + 1); res = get_hkdf_params(params, param_count, &salt, &salt_len, &info, &info_len, &okm_len); if (res != TEE_SUCCESS) goto out; /* Requested size must fit into the output object's buffer */ if (okm_len > ik->alloc_size) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_cryp_hkdf(hash_id, ikm, ik->key_size, salt, salt_len, info, info_len, (uint8_t *)(sk + 1), okm_len); if (res == TEE_SUCCESS) { sk->key_size = okm_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } #endif #if defined(CFG_CRYPTO_CONCAT_KDF) else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_CONCAT_KDF) { void *info; size_t info_len, derived_key_len; uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo); struct tee_cryp_obj_secret *ss = ko->attr; const uint8_t *shared_secret = (const uint8_t *)(ss + 1); res = get_concat_kdf_params(params, param_count, &info, &info_len, &derived_key_len); if (res != TEE_SUCCESS) goto out; /* Requested size must fit into the output object's buffer */ if (derived_key_len > ss->alloc_size) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_cryp_concat_kdf(hash_id, shared_secret, ss->key_size, info, info_len, (uint8_t *)(sk + 1), derived_key_len); if (res == TEE_SUCCESS) { sk->key_size = derived_key_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } #endif #if defined(CFG_CRYPTO_PBKDF2) else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_PBKDF2) { void *salt; size_t salt_len, iteration_count, derived_key_len; uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo); struct tee_cryp_obj_secret *ss = ko->attr; const uint8_t *password = (const uint8_t *)(ss + 1); res = get_pbkdf2_params(params, param_count, &salt, &salt_len, &derived_key_len, &iteration_count); if (res != TEE_SUCCESS) goto out; /* Requested size must fit into the output object's buffer */ if (derived_key_len > ss->alloc_size) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_cryp_pbkdf2(hash_id, password, ss->key_size, salt, salt_len, iteration_count, (uint8_t *)(sk + 1), derived_key_len); if (res == TEE_SUCCESS) { sk->key_size = derived_key_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } #endif else res = TEE_ERROR_NOT_SUPPORTED; out: free(params); return res; } TEE_Result syscall_cryp_random_number_generate(void *buf, size_t blen) { TEE_Result res; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)buf, blen); if (res != TEE_SUCCESS) return res; res = crypto_rng_read(buf, blen); if (res != TEE_SUCCESS) return res; return res; } TEE_Result syscall_authenc_init(unsigned long state, const void *nonce, size_t nonce_len, size_t tag_len, size_t aad_len, size_t payload_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; struct tee_obj *o; struct tee_cryp_obj_secret *key; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), cs->key1, &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; key = o->attr; res = crypto_authenc_init(cs->ctx, cs->algo, cs->mode, (uint8_t *)(key + 1), key->key_size, nonce, nonce_len, tag_len, aad_len, payload_len); if (res != TEE_SUCCESS) return res; cs->ctx_finalize = (tee_cryp_ctx_finalize_func_t)crypto_authenc_final; return TEE_SUCCESS; } TEE_Result syscall_authenc_update_aad(unsigned long state, const void *aad_data, size_t aad_data_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) aad_data, aad_data_len); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = crypto_authenc_update_aad(cs->ctx, cs->algo, cs->mode, aad_data, aad_data_len); if (res != TEE_SUCCESS) return res; return TEE_SUCCESS; } TEE_Result syscall_authenc_update_payload(unsigned long state, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen; size_t tmp_dlen; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) src_data, src_len); if (res != TEE_SUCCESS) return res; res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)dst_data, dlen); if (res != TEE_SUCCESS) return res; if (dlen < src_len) { res = TEE_ERROR_SHORT_BUFFER; goto out; } tmp_dlen = dlen; res = crypto_authenc_update_payload(cs->ctx, cs->algo, cs->mode, src_data, src_len, dst_data, &tmp_dlen); dlen = tmp_dlen; out: if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) { TEE_Result res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) res = res2; } return res; } TEE_Result syscall_authenc_enc_final(unsigned long state, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len, void *tag, uint64_t *tag_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen; uint64_t tlen = 0; size_t tmp_dlen; size_t tmp_tlen; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; if (cs->mode != TEE_MODE_ENCRYPT) return TEE_ERROR_BAD_PARAMETERS; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)src_data, src_len); if (res != TEE_SUCCESS) return res; if (!dst_len) { dlen = 0; } else { res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)dst_data, dlen); if (res != TEE_SUCCESS) return res; } if (dlen < src_len) { res = TEE_ERROR_SHORT_BUFFER; goto out; } res = tee_svc_copy_from_user(&tlen, tag_len, sizeof(tlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)tag, tlen); if (res != TEE_SUCCESS) return res; tmp_dlen = dlen; tmp_tlen = tlen; res = crypto_authenc_enc_final(cs->ctx, cs->algo, src_data, src_len, dst_data, &tmp_dlen, tag, &tmp_tlen); dlen = tmp_dlen; tlen = tmp_tlen; out: if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) { TEE_Result res2; if (dst_len != NULL) { res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) return res2; } res2 = tee_svc_copy_to_user(tag_len, &tlen, sizeof(*tag_len)); if (res2 != TEE_SUCCESS) return res2; } return res; } TEE_Result syscall_authenc_dec_final(unsigned long state, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len, const void *tag, size_t tag_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen; size_t tmp_dlen; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; if (cs->mode != TEE_MODE_DECRYPT) return TEE_ERROR_BAD_PARAMETERS; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)src_data, src_len); if (res != TEE_SUCCESS) return res; if (!dst_len) { dlen = 0; } else { res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)dst_data, dlen); if (res != TEE_SUCCESS) return res; } if (dlen < src_len) { res = TEE_ERROR_SHORT_BUFFER; goto out; } res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)tag, tag_len); if (res != TEE_SUCCESS) return res; tmp_dlen = dlen; res = crypto_authenc_dec_final(cs->ctx, cs->algo, src_data, src_len, dst_data, &tmp_dlen, tag, tag_len); dlen = tmp_dlen; out: if ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) && dst_len != NULL) { TEE_Result res2; res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) return res2; } return res; } static int pkcs1_get_salt_len(const TEE_Attribute *params, uint32_t num_params, size_t default_len) { size_t n; assert(default_len < INT_MAX); for (n = 0; n < num_params; n++) { if (params[n].attributeID == TEE_ATTR_RSA_PSS_SALT_LENGTH) { if (params[n].content.value.a < INT_MAX) return params[n].content.value.a; break; } } /* * If salt length isn't provided use the default value which is * the length of the digest. */ return default_len; } TEE_Result syscall_asymm_operate(unsigned long state, const struct utee_attribute *usr_params, size_t num_params, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen64; size_t dlen; struct tee_obj *o; void *label = NULL; size_t label_len = 0; size_t n; int salt_len; TEE_Attribute *params = NULL; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights( utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) src_data, src_len); if (res != TEE_SUCCESS) return res; res = tee_svc_copy_from_user(&dlen64, dst_len, sizeof(dlen64)); if (res != TEE_SUCCESS) return res; dlen = dlen64; res = tee_mmu_check_access_rights( utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) dst_data, dlen); if (res != TEE_SUCCESS) return res; params = malloc(sizeof(TEE_Attribute) * num_params); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(utc, usr_params, num_params, params); if (res != TEE_SUCCESS) goto out; res = tee_obj_get(utc, cs->key1, &o); if (res != TEE_SUCCESS) goto out; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) { res = TEE_ERROR_GENERIC; goto out; } switch (cs->algo) { case TEE_ALG_RSA_NOPAD: if (cs->mode == TEE_MODE_ENCRYPT) { res = crypto_acipher_rsanopad_encrypt(o->attr, src_data, src_len, dst_data, &dlen); } else if (cs->mode == TEE_MODE_DECRYPT) { res = crypto_acipher_rsanopad_decrypt(o->attr, src_data, src_len, dst_data, &dlen); } else { /* * We will panic because "the mode is not compatible * with the function" */ res = TEE_ERROR_GENERIC; } break; case TEE_ALG_RSAES_PKCS1_V1_5: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512: for (n = 0; n < num_params; n++) { if (params[n].attributeID == TEE_ATTR_RSA_OAEP_LABEL) { label = params[n].content.ref.buffer; label_len = params[n].content.ref.length; break; } } if (cs->mode == TEE_MODE_ENCRYPT) { res = crypto_acipher_rsaes_encrypt(cs->algo, o->attr, label, label_len, src_data, src_len, dst_data, &dlen); } else if (cs->mode == TEE_MODE_DECRYPT) { res = crypto_acipher_rsaes_decrypt( cs->algo, o->attr, label, label_len, src_data, src_len, dst_data, &dlen); } else { res = TEE_ERROR_BAD_PARAMETERS; } break; #if defined(CFG_CRYPTO_RSASSA_NA1) case TEE_ALG_RSASSA_PKCS1_V1_5: #endif case TEE_ALG_RSASSA_PKCS1_V1_5_MD5: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512: if (cs->mode != TEE_MODE_SIGN) { res = TEE_ERROR_BAD_PARAMETERS; break; } salt_len = pkcs1_get_salt_len(params, num_params, src_len); res = crypto_acipher_rsassa_sign(cs->algo, o->attr, salt_len, src_data, src_len, dst_data, &dlen); break; case TEE_ALG_DSA_SHA1: case TEE_ALG_DSA_SHA224: case TEE_ALG_DSA_SHA256: res = crypto_acipher_dsa_sign(cs->algo, o->attr, src_data, src_len, dst_data, &dlen); break; case TEE_ALG_ECDSA_P192: case TEE_ALG_ECDSA_P224: case TEE_ALG_ECDSA_P256: case TEE_ALG_ECDSA_P384: case TEE_ALG_ECDSA_P521: res = crypto_acipher_ecc_sign(cs->algo, o->attr, src_data, src_len, dst_data, &dlen); break; default: res = TEE_ERROR_BAD_PARAMETERS; break; } out: free(params); if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) { TEE_Result res2; dlen64 = dlen; res2 = tee_svc_copy_to_user(dst_len, &dlen64, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) return res2; } return res; } TEE_Result syscall_asymm_verify(unsigned long state, const struct utee_attribute *usr_params, size_t num_params, const void *data, size_t data_len, const void *sig, size_t sig_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; struct tee_obj *o; size_t hash_size; int salt_len = 0; TEE_Attribute *params = NULL; uint32_t hash_algo; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; if (cs->mode != TEE_MODE_VERIFY) return TEE_ERROR_BAD_PARAMETERS; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)data, data_len); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)sig, sig_len); if (res != TEE_SUCCESS) return res; params = malloc(sizeof(TEE_Attribute) * num_params); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(utc, usr_params, num_params, params); if (res != TEE_SUCCESS) goto out; res = tee_obj_get(utc, cs->key1, &o); if (res != TEE_SUCCESS) goto out; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } switch (TEE_ALG_GET_MAIN_ALG(cs->algo)) { case TEE_MAIN_ALGO_RSA: if (cs->algo != TEE_ALG_RSASSA_PKCS1_V1_5) { hash_algo = TEE_DIGEST_HASH_TO_ALGO(cs->algo); res = tee_hash_get_digest_size(hash_algo, &hash_size); if (res != TEE_SUCCESS) break; if (data_len != hash_size) { res = TEE_ERROR_BAD_PARAMETERS; break; } salt_len = pkcs1_get_salt_len(params, num_params, hash_size); } res = crypto_acipher_rsassa_verify(cs->algo, o->attr, salt_len, data, data_len, sig, sig_len); break; case TEE_MAIN_ALGO_DSA: hash_algo = TEE_DIGEST_HASH_TO_ALGO(cs->algo); res = tee_hash_get_digest_size(hash_algo, &hash_size); if (res != TEE_SUCCESS) break; /* * Depending on the DSA algorithm (NIST), the digital signature * output size may be truncated to the size of a key pair * (Q prime size). Q prime size must be less or equal than the * hash output length of the hash algorithm involved. */ if (data_len > hash_size) { res = TEE_ERROR_BAD_PARAMETERS; break; } res = crypto_acipher_dsa_verify(cs->algo, o->attr, data, data_len, sig, sig_len); break; case TEE_MAIN_ALGO_ECDSA: res = crypto_acipher_ecc_verify(cs->algo, o->attr, data, data_len, sig, sig_len); break; default: res = TEE_ERROR_NOT_SUPPORTED; } out: free(params); return res; }
null
115
CWE-787
CVE-2019-1010298
// SPDX-License-Identifier: BSD-2-Clause /* * Copyright (c) 2014, STMicroelectronics International N.V. */ #include <assert.h> #include <compiler.h> #include <crypto/crypto.h> #include <kernel/tee_ta_manager.h> #include <mm/tee_mmu.h> #include <string_ext.h> #include <string.h> #include <sys/queue.h> #include <tee_api_types.h> #include <tee/tee_cryp_utl.h> #include <tee/tee_obj.h> #include <tee/tee_svc_cryp.h> #include <tee/tee_svc.h> #include <trace.h> #include <utee_defines.h> #include <util.h> #include <tee_api_defines_extensions.h> #if defined(CFG_CRYPTO_HKDF) #include <tee/tee_cryp_hkdf.h> #endif #if defined(CFG_CRYPTO_CONCAT_KDF) #include <tee/tee_cryp_concat_kdf.h> #endif #if defined(CFG_CRYPTO_PBKDF2) #include <tee/tee_cryp_pbkdf2.h> #endif typedef void (*tee_cryp_ctx_finalize_func_t) (void *ctx, uint32_t algo); struct tee_cryp_state { TAILQ_ENTRY(tee_cryp_state) link; uint32_t algo; uint32_t mode; vaddr_t key1; vaddr_t key2; void *ctx; tee_cryp_ctx_finalize_func_t ctx_finalize; }; struct tee_cryp_obj_secret { uint32_t key_size; uint32_t alloc_size; /* * Pseudo code visualize layout of structure * Next follows data, such as: * uint8_t data[alloc_size] * key_size must never exceed alloc_size */ }; #define TEE_TYPE_ATTR_OPTIONAL 0x0 #define TEE_TYPE_ATTR_REQUIRED 0x1 #define TEE_TYPE_ATTR_OPTIONAL_GROUP 0x2 #define TEE_TYPE_ATTR_SIZE_INDICATOR 0x4 #define TEE_TYPE_ATTR_GEN_KEY_OPT 0x8 #define TEE_TYPE_ATTR_GEN_KEY_REQ 0x10 /* Handle storing of generic secret keys of varying lengths */ #define ATTR_OPS_INDEX_SECRET 0 /* Convert to/from big-endian byte array and provider-specific bignum */ #define ATTR_OPS_INDEX_BIGNUM 1 /* Convert to/from value attribute depending on direction */ #define ATTR_OPS_INDEX_VALUE 2 struct tee_cryp_obj_type_attrs { uint32_t attr_id; uint16_t flags; uint16_t ops_index; uint16_t raw_offs; uint16_t raw_size; }; #define RAW_DATA(_x, _y) \ .raw_offs = offsetof(_x, _y), .raw_size = MEMBER_SIZE(_x, _y) static const struct tee_cryp_obj_type_attrs tee_cryp_obj_secret_value_attrs[] = { { .attr_id = TEE_ATTR_SECRET_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_SECRET, .raw_offs = 0, .raw_size = 0 }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_rsa_pub_key_attrs[] = { { .attr_id = TEE_ATTR_RSA_MODULUS, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_public_key, n) }, { .attr_id = TEE_ATTR_RSA_PUBLIC_EXPONENT, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_public_key, e) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_rsa_keypair_attrs[] = { { .attr_id = TEE_ATTR_RSA_MODULUS, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, n) }, { .attr_id = TEE_ATTR_RSA_PUBLIC_EXPONENT, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, e) }, { .attr_id = TEE_ATTR_RSA_PRIVATE_EXPONENT, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, d) }, { .attr_id = TEE_ATTR_RSA_PRIME1, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, p) }, { .attr_id = TEE_ATTR_RSA_PRIME2, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, q) }, { .attr_id = TEE_ATTR_RSA_EXPONENT1, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, dp) }, { .attr_id = TEE_ATTR_RSA_EXPONENT2, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, dq) }, { .attr_id = TEE_ATTR_RSA_COEFFICIENT, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, qp) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dsa_pub_key_attrs[] = { { .attr_id = TEE_ATTR_DSA_PRIME, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_public_key, p) }, { .attr_id = TEE_ATTR_DSA_SUBPRIME, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_public_key, q) }, { .attr_id = TEE_ATTR_DSA_BASE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_public_key, g) }, { .attr_id = TEE_ATTR_DSA_PUBLIC_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_public_key, y) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dsa_keypair_attrs[] = { { .attr_id = TEE_ATTR_DSA_PRIME, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, p) }, { .attr_id = TEE_ATTR_DSA_SUBPRIME, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, q) }, { .attr_id = TEE_ATTR_DSA_BASE, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, g) }, { .attr_id = TEE_ATTR_DSA_PRIVATE_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, x) }, { .attr_id = TEE_ATTR_DSA_PUBLIC_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, y) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dh_keypair_attrs[] = { { .attr_id = TEE_ATTR_DH_PRIME, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, p) }, { .attr_id = TEE_ATTR_DH_BASE, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, g) }, { .attr_id = TEE_ATTR_DH_PUBLIC_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, y) }, { .attr_id = TEE_ATTR_DH_PRIVATE_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, x) }, { .attr_id = TEE_ATTR_DH_SUBPRIME, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP | TEE_TYPE_ATTR_GEN_KEY_OPT, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, q) }, { .attr_id = TEE_ATTR_DH_X_BITS, .flags = TEE_TYPE_ATTR_GEN_KEY_OPT, .ops_index = ATTR_OPS_INDEX_VALUE, RAW_DATA(struct dh_keypair, xbits) }, }; #if defined(CFG_CRYPTO_HKDF) static const struct tee_cryp_obj_type_attrs tee_cryp_obj_hkdf_ikm_attrs[] = { { .attr_id = TEE_ATTR_HKDF_IKM, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_SECRET, .raw_offs = 0, .raw_size = 0 }, }; #endif #if defined(CFG_CRYPTO_CONCAT_KDF) static const struct tee_cryp_obj_type_attrs tee_cryp_obj_concat_kdf_z_attrs[] = { { .attr_id = TEE_ATTR_CONCAT_KDF_Z, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_SECRET, .raw_offs = 0, .raw_size = 0 }, }; #endif #if defined(CFG_CRYPTO_PBKDF2) static const struct tee_cryp_obj_type_attrs tee_cryp_obj_pbkdf2_passwd_attrs[] = { { .attr_id = TEE_ATTR_PBKDF2_PASSWORD, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_SECRET, .raw_offs = 0, .raw_size = 0 }, }; #endif static const struct tee_cryp_obj_type_attrs tee_cryp_obj_ecc_pub_key_attrs[] = { { .attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_X, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_public_key, x) }, { .attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_Y, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_public_key, y) }, { .attr_id = TEE_ATTR_ECC_CURVE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_VALUE, RAW_DATA(struct ecc_public_key, curve) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_ecc_keypair_attrs[] = { { .attr_id = TEE_ATTR_ECC_PRIVATE_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_keypair, d) }, { .attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_X, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_keypair, x) }, { .attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_Y, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_keypair, y) }, { .attr_id = TEE_ATTR_ECC_CURVE, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_VALUE, RAW_DATA(struct ecc_keypair, curve) }, }; struct tee_cryp_obj_type_props { TEE_ObjectType obj_type; uint16_t min_size; /* may not be smaller than this */ uint16_t max_size; /* may not be larger than this */ uint16_t alloc_size; /* this many bytes are allocated to hold data */ uint8_t quanta; /* may only be an multiple of this */ uint8_t num_type_attrs; const struct tee_cryp_obj_type_attrs *type_attrs; }; #define PROP(obj_type, quanta, min_size, max_size, alloc_size, type_attrs) \ { (obj_type), (min_size), (max_size), (alloc_size), (quanta), \ ARRAY_SIZE(type_attrs), (type_attrs) } static const struct tee_cryp_obj_type_props tee_cryp_obj_props[] = { PROP(TEE_TYPE_AES, 64, 128, 256, /* valid sizes 128, 192, 256 */ 256 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_DES, 56, 56, 56, /* * Valid size 56 without parity, note that we still allocate * for 64 bits since the key is supplied with parity. */ 64 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_DES3, 56, 112, 168, /* * Valid sizes 112, 168 without parity, note that we still * allocate for with space for the parity since the key is * supplied with parity. */ 192 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_MD5, 8, 64, 512, 512 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA1, 8, 80, 512, 512 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA224, 8, 112, 512, 512 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA256, 8, 192, 1024, 1024 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA384, 8, 256, 1024, 1024 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA512, 8, 256, 1024, 1024 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_GENERIC_SECRET, 8, 0, 4096, 4096 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), #if defined(CFG_CRYPTO_HKDF) PROP(TEE_TYPE_HKDF_IKM, 8, 0, 4096, 4096 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_hkdf_ikm_attrs), #endif #if defined(CFG_CRYPTO_CONCAT_KDF) PROP(TEE_TYPE_CONCAT_KDF_Z, 8, 0, 4096, 4096 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_concat_kdf_z_attrs), #endif #if defined(CFG_CRYPTO_PBKDF2) PROP(TEE_TYPE_PBKDF2_PASSWORD, 8, 0, 4096, 4096 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_pbkdf2_passwd_attrs), #endif PROP(TEE_TYPE_RSA_PUBLIC_KEY, 1, 256, CFG_CORE_BIGNUM_MAX_BITS, sizeof(struct rsa_public_key), tee_cryp_obj_rsa_pub_key_attrs), PROP(TEE_TYPE_RSA_KEYPAIR, 1, 256, CFG_CORE_BIGNUM_MAX_BITS, sizeof(struct rsa_keypair), tee_cryp_obj_rsa_keypair_attrs), PROP(TEE_TYPE_DSA_PUBLIC_KEY, 64, 512, 3072, sizeof(struct dsa_public_key), tee_cryp_obj_dsa_pub_key_attrs), PROP(TEE_TYPE_DSA_KEYPAIR, 64, 512, 3072, sizeof(struct dsa_keypair), tee_cryp_obj_dsa_keypair_attrs), PROP(TEE_TYPE_DH_KEYPAIR, 1, 256, 2048, sizeof(struct dh_keypair), tee_cryp_obj_dh_keypair_attrs), PROP(TEE_TYPE_ECDSA_PUBLIC_KEY, 1, 192, 521, sizeof(struct ecc_public_key), tee_cryp_obj_ecc_pub_key_attrs), PROP(TEE_TYPE_ECDSA_KEYPAIR, 1, 192, 521, sizeof(struct ecc_keypair), tee_cryp_obj_ecc_keypair_attrs), PROP(TEE_TYPE_ECDH_PUBLIC_KEY, 1, 192, 521, sizeof(struct ecc_public_key), tee_cryp_obj_ecc_pub_key_attrs), PROP(TEE_TYPE_ECDH_KEYPAIR, 1, 192, 521, sizeof(struct ecc_keypair), tee_cryp_obj_ecc_keypair_attrs), }; struct attr_ops { TEE_Result (*from_user)(void *attr, const void *buffer, size_t size); TEE_Result (*to_user)(void *attr, struct tee_ta_session *sess, void *buffer, uint64_t *size); TEE_Result (*to_binary)(void *attr, void *data, size_t data_len, size_t *offs); bool (*from_binary)(void *attr, const void *data, size_t data_len, size_t *offs); TEE_Result (*from_obj)(void *attr, void *src_attr); void (*free)(void *attr); void (*clear)(void *attr); }; static TEE_Result op_u32_to_binary_helper(uint32_t v, uint8_t *data, size_t data_len, size_t *offs) { uint32_t field; size_t next_offs; if (ADD_OVERFLOW(*offs, sizeof(field), &next_offs)) return TEE_ERROR_OVERFLOW; if (data && next_offs <= data_len) { field = TEE_U32_TO_BIG_ENDIAN(v); memcpy(data + *offs, &field, sizeof(field)); } (*offs) = next_offs; return TEE_SUCCESS; } static bool op_u32_from_binary_helper(uint32_t *v, const uint8_t *data, size_t data_len, size_t *offs) { uint32_t field; if (!data || (*offs + sizeof(field)) > data_len) return false; memcpy(&field, data + *offs, sizeof(field)); *v = TEE_U32_FROM_BIG_ENDIAN(field); (*offs) += sizeof(field); return true; } static TEE_Result op_attr_secret_value_from_user(void *attr, const void *buffer, size_t size) { struct tee_cryp_obj_secret *key = attr; /* Data size has to fit in allocated buffer */ if (size > key->alloc_size) return TEE_ERROR_SECURITY; memcpy(key + 1, buffer, size); key->key_size = size; return TEE_SUCCESS; } static TEE_Result op_attr_secret_value_to_user(void *attr, struct tee_ta_session *sess __unused, void *buffer, uint64_t *size) { TEE_Result res; struct tee_cryp_obj_secret *key = attr; uint64_t s; uint64_t key_size; res = tee_svc_copy_from_user(&s, size, sizeof(s)); if (res != TEE_SUCCESS) return res; key_size = key->key_size; res = tee_svc_copy_to_user(size, &key_size, sizeof(key_size)); if (res != TEE_SUCCESS) return res; if (s < key->key_size || !buffer) return TEE_ERROR_SHORT_BUFFER; return tee_svc_copy_to_user(buffer, key + 1, key->key_size); } static TEE_Result op_attr_secret_value_to_binary(void *attr, void *data, size_t data_len, size_t *offs) { TEE_Result res; struct tee_cryp_obj_secret *key = attr; size_t next_offs; res = op_u32_to_binary_helper(key->key_size, data, data_len, offs); if (res != TEE_SUCCESS) return res; if (ADD_OVERFLOW(*offs, key->key_size, &next_offs)) return TEE_ERROR_OVERFLOW; if (data && next_offs <= data_len) memcpy((uint8_t *)data + *offs, key + 1, key->key_size); (*offs) = next_offs; return TEE_SUCCESS; } static bool op_attr_secret_value_from_binary(void *attr, const void *data, size_t data_len, size_t *offs) { struct tee_cryp_obj_secret *key = attr; uint32_t s; if (!op_u32_from_binary_helper(&s, data, data_len, offs)) return false; if ((*offs + s) > data_len) return false; /* Data size has to fit in allocated buffer */ if (s > key->alloc_size) return false; key->key_size = s; memcpy(key + 1, (const uint8_t *)data + *offs, s); (*offs) += s; return true; } static TEE_Result op_attr_secret_value_from_obj(void *attr, void *src_attr) { struct tee_cryp_obj_secret *key = attr; struct tee_cryp_obj_secret *src_key = src_attr; if (src_key->key_size > key->alloc_size) return TEE_ERROR_BAD_STATE; memcpy(key + 1, src_key + 1, src_key->key_size); key->key_size = src_key->key_size; return TEE_SUCCESS; } static void op_attr_secret_value_clear(void *attr) { struct tee_cryp_obj_secret *key = attr; key->key_size = 0; memset(key + 1, 0, key->alloc_size); } static TEE_Result op_attr_bignum_from_user(void *attr, const void *buffer, size_t size) { struct bignum **bn = attr; return crypto_bignum_bin2bn(buffer, size, *bn); } static TEE_Result op_attr_bignum_to_user(void *attr, struct tee_ta_session *sess, void *buffer, uint64_t *size) { TEE_Result res; struct bignum **bn = attr; uint64_t req_size; uint64_t s; res = tee_svc_copy_from_user(&s, size, sizeof(s)); if (res != TEE_SUCCESS) return res; req_size = crypto_bignum_num_bytes(*bn); res = tee_svc_copy_to_user(size, &req_size, sizeof(req_size)); if (res != TEE_SUCCESS) return res; if (!req_size) return TEE_SUCCESS; if (s < req_size || !buffer) return TEE_ERROR_SHORT_BUFFER; /* Check we can access data using supplied user mode pointer */ res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)buffer, req_size); if (res != TEE_SUCCESS) return res; /* * Write the bignum (wich raw data points to) into an array of * bytes (stored in buffer) */ crypto_bignum_bn2bin(*bn, buffer); return TEE_SUCCESS; } static TEE_Result op_attr_bignum_to_binary(void *attr, void *data, size_t data_len, size_t *offs) { TEE_Result res; struct bignum **bn = attr; uint32_t n = crypto_bignum_num_bytes(*bn); size_t next_offs; res = op_u32_to_binary_helper(n, data, data_len, offs); if (res != TEE_SUCCESS) return res; if (ADD_OVERFLOW(*offs, n, &next_offs)) return TEE_ERROR_OVERFLOW; if (data && next_offs <= data_len) crypto_bignum_bn2bin(*bn, (uint8_t *)data + *offs); (*offs) = next_offs; return TEE_SUCCESS; } static bool op_attr_bignum_from_binary(void *attr, const void *data, size_t data_len, size_t *offs) { struct bignum **bn = attr; uint32_t n; if (!op_u32_from_binary_helper(&n, data, data_len, offs)) return false; if ((*offs + n) > data_len) return false; if (crypto_bignum_bin2bn((const uint8_t *)data + *offs, n, *bn)) return false; (*offs) += n; return true; } static TEE_Result op_attr_bignum_from_obj(void *attr, void *src_attr) { struct bignum **bn = attr; struct bignum **src_bn = src_attr; crypto_bignum_copy(*bn, *src_bn); return TEE_SUCCESS; } static void op_attr_bignum_clear(void *attr) { struct bignum **bn = attr; crypto_bignum_clear(*bn); } static void op_attr_bignum_free(void *attr) { struct bignum **bn = attr; crypto_bignum_free(*bn); *bn = NULL; } static TEE_Result op_attr_value_from_user(void *attr, const void *buffer, size_t size) { uint32_t *v = attr; if (size != sizeof(uint32_t) * 2) return TEE_ERROR_GENERIC; /* "can't happen */ /* Note that only the first value is copied */ memcpy(v, buffer, sizeof(uint32_t)); return TEE_SUCCESS; } static TEE_Result op_attr_value_to_user(void *attr, struct tee_ta_session *sess __unused, void *buffer, uint64_t *size) { TEE_Result res; uint32_t *v = attr; uint64_t s; uint32_t value[2] = { *v }; uint64_t req_size = sizeof(value); res = tee_svc_copy_from_user(&s, size, sizeof(s)); if (res != TEE_SUCCESS) return res; if (s < req_size || !buffer) return TEE_ERROR_SHORT_BUFFER; return tee_svc_copy_to_user(buffer, value, req_size); } static TEE_Result op_attr_value_to_binary(void *attr, void *data, size_t data_len, size_t *offs) { uint32_t *v = attr; return op_u32_to_binary_helper(*v, data, data_len, offs); } static bool op_attr_value_from_binary(void *attr, const void *data, size_t data_len, size_t *offs) { uint32_t *v = attr; return op_u32_from_binary_helper(v, data, data_len, offs); } static TEE_Result op_attr_value_from_obj(void *attr, void *src_attr) { uint32_t *v = attr; uint32_t *src_v = src_attr; *v = *src_v; return TEE_SUCCESS; } static void op_attr_value_clear(void *attr) { uint32_t *v = attr; *v = 0; } static const struct attr_ops attr_ops[] = { [ATTR_OPS_INDEX_SECRET] = { .from_user = op_attr_secret_value_from_user, .to_user = op_attr_secret_value_to_user, .to_binary = op_attr_secret_value_to_binary, .from_binary = op_attr_secret_value_from_binary, .from_obj = op_attr_secret_value_from_obj, .free = op_attr_secret_value_clear, /* not a typo */ .clear = op_attr_secret_value_clear, }, [ATTR_OPS_INDEX_BIGNUM] = { .from_user = op_attr_bignum_from_user, .to_user = op_attr_bignum_to_user, .to_binary = op_attr_bignum_to_binary, .from_binary = op_attr_bignum_from_binary, .from_obj = op_attr_bignum_from_obj, .free = op_attr_bignum_free, .clear = op_attr_bignum_clear, }, [ATTR_OPS_INDEX_VALUE] = { .from_user = op_attr_value_from_user, .to_user = op_attr_value_to_user, .to_binary = op_attr_value_to_binary, .from_binary = op_attr_value_from_binary, .from_obj = op_attr_value_from_obj, .free = op_attr_value_clear, /* not a typo */ .clear = op_attr_value_clear, }, }; TEE_Result syscall_cryp_obj_get_info(unsigned long obj, TEE_ObjectInfo *info) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) goto exit; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) goto exit; res = tee_svc_copy_to_user(info, &o->info, sizeof(o->info)); exit: return res; } TEE_Result syscall_cryp_obj_restrict_usage(unsigned long obj, unsigned long usage) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) goto exit; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) goto exit; o->info.objectUsage &= usage; exit: return res; } static int tee_svc_cryp_obj_find_type_attr_idx( uint32_t attr_id, const struct tee_cryp_obj_type_props *type_props) { size_t n; for (n = 0; n < type_props->num_type_attrs; n++) { if (attr_id == type_props->type_attrs[n].attr_id) return n; } return -1; } static const struct tee_cryp_obj_type_props *tee_svc_find_type_props( TEE_ObjectType obj_type) { size_t n; for (n = 0; n < ARRAY_SIZE(tee_cryp_obj_props); n++) { if (tee_cryp_obj_props[n].obj_type == obj_type) return tee_cryp_obj_props + n; } return NULL; } /* Set an attribute on an object */ static void set_attribute(struct tee_obj *o, const struct tee_cryp_obj_type_props *props, uint32_t attr) { int idx = tee_svc_cryp_obj_find_type_attr_idx(attr, props); if (idx < 0) return; o->have_attrs |= BIT(idx); } /* Get an attribute on an object */ static uint32_t get_attribute(const struct tee_obj *o, const struct tee_cryp_obj_type_props *props, uint32_t attr) { int idx = tee_svc_cryp_obj_find_type_attr_idx(attr, props); if (idx < 0) return 0; return o->have_attrs & BIT(idx); } TEE_Result syscall_cryp_obj_get_attr(unsigned long obj, unsigned long attr_id, void *buffer, uint64_t *size) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; const struct tee_cryp_obj_type_props *type_props; int idx; const struct attr_ops *ops; void *attr; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return TEE_ERROR_ITEM_NOT_FOUND; /* Check that the object is initialized */ if (!(o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED)) return TEE_ERROR_BAD_PARAMETERS; /* Check that getting the attribute is allowed */ if (!(attr_id & TEE_ATTR_BIT_PROTECTED) && !(o->info.objectUsage & TEE_USAGE_EXTRACTABLE)) return TEE_ERROR_BAD_PARAMETERS; type_props = tee_svc_find_type_props(o->info.objectType); if (!type_props) { /* Unknown object type, "can't happen" */ return TEE_ERROR_BAD_STATE; } idx = tee_svc_cryp_obj_find_type_attr_idx(attr_id, type_props); if ((idx < 0) || ((o->have_attrs & (1 << idx)) == 0)) return TEE_ERROR_ITEM_NOT_FOUND; ops = attr_ops + type_props->type_attrs[idx].ops_index; attr = (uint8_t *)o->attr + type_props->type_attrs[idx].raw_offs; return ops->to_user(attr, sess, buffer, size); } void tee_obj_attr_free(struct tee_obj *o) { const struct tee_cryp_obj_type_props *tp; size_t n; if (!o->attr) return; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return; for (n = 0; n < tp->num_type_attrs; n++) { const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n; attr_ops[ta->ops_index].free((uint8_t *)o->attr + ta->raw_offs); } } void tee_obj_attr_clear(struct tee_obj *o) { const struct tee_cryp_obj_type_props *tp; size_t n; if (!o->attr) return; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return; for (n = 0; n < tp->num_type_attrs; n++) { const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n; attr_ops[ta->ops_index].clear((uint8_t *)o->attr + ta->raw_offs); } } TEE_Result tee_obj_attr_to_binary(struct tee_obj *o, void *data, size_t *data_len) { const struct tee_cryp_obj_type_props *tp; size_t n; size_t offs = 0; size_t len = data ? *data_len : 0; TEE_Result res; if (o->info.objectType == TEE_TYPE_DATA) { *data_len = 0; return TEE_SUCCESS; /* pure data object */ } if (!o->attr) return TEE_ERROR_BAD_STATE; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return TEE_ERROR_BAD_STATE; for (n = 0; n < tp->num_type_attrs; n++) { const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n; void *attr = (uint8_t *)o->attr + ta->raw_offs; res = attr_ops[ta->ops_index].to_binary(attr, data, len, &offs); if (res != TEE_SUCCESS) return res; } *data_len = offs; if (data && offs > len) return TEE_ERROR_SHORT_BUFFER; return TEE_SUCCESS; } TEE_Result tee_obj_attr_from_binary(struct tee_obj *o, const void *data, size_t data_len) { const struct tee_cryp_obj_type_props *tp; size_t n; size_t offs = 0; if (o->info.objectType == TEE_TYPE_DATA) return TEE_SUCCESS; /* pure data object */ if (!o->attr) return TEE_ERROR_BAD_STATE; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return TEE_ERROR_BAD_STATE; for (n = 0; n < tp->num_type_attrs; n++) { const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n; void *attr = (uint8_t *)o->attr + ta->raw_offs; if (!attr_ops[ta->ops_index].from_binary(attr, data, data_len, &offs)) return TEE_ERROR_CORRUPT_OBJECT; } return TEE_SUCCESS; } TEE_Result tee_obj_attr_copy_from(struct tee_obj *o, const struct tee_obj *src) { TEE_Result res; const struct tee_cryp_obj_type_props *tp; const struct tee_cryp_obj_type_attrs *ta; size_t n; uint32_t have_attrs = 0; void *attr; void *src_attr; if (o->info.objectType == TEE_TYPE_DATA) return TEE_SUCCESS; /* pure data object */ if (!o->attr) return TEE_ERROR_BAD_STATE; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return TEE_ERROR_BAD_STATE; if (o->info.objectType == src->info.objectType) { have_attrs = src->have_attrs; for (n = 0; n < tp->num_type_attrs; n++) { ta = tp->type_attrs + n; attr = (uint8_t *)o->attr + ta->raw_offs; src_attr = (uint8_t *)src->attr + ta->raw_offs; res = attr_ops[ta->ops_index].from_obj(attr, src_attr); if (res != TEE_SUCCESS) return res; } } else { const struct tee_cryp_obj_type_props *tp_src; int idx; if (o->info.objectType == TEE_TYPE_RSA_PUBLIC_KEY) { if (src->info.objectType != TEE_TYPE_RSA_KEYPAIR) return TEE_ERROR_BAD_PARAMETERS; } else if (o->info.objectType == TEE_TYPE_DSA_PUBLIC_KEY) { if (src->info.objectType != TEE_TYPE_DSA_KEYPAIR) return TEE_ERROR_BAD_PARAMETERS; } else if (o->info.objectType == TEE_TYPE_ECDSA_PUBLIC_KEY) { if (src->info.objectType != TEE_TYPE_ECDSA_KEYPAIR) return TEE_ERROR_BAD_PARAMETERS; } else if (o->info.objectType == TEE_TYPE_ECDH_PUBLIC_KEY) { if (src->info.objectType != TEE_TYPE_ECDH_KEYPAIR) return TEE_ERROR_BAD_PARAMETERS; } else { return TEE_ERROR_BAD_PARAMETERS; } tp_src = tee_svc_find_type_props(src->info.objectType); if (!tp_src) return TEE_ERROR_BAD_STATE; have_attrs = BIT32(tp->num_type_attrs) - 1; for (n = 0; n < tp->num_type_attrs; n++) { ta = tp->type_attrs + n; idx = tee_svc_cryp_obj_find_type_attr_idx(ta->attr_id, tp_src); if (idx < 0) return TEE_ERROR_BAD_STATE; attr = (uint8_t *)o->attr + ta->raw_offs; src_attr = (uint8_t *)src->attr + tp_src->type_attrs[idx].raw_offs; res = attr_ops[ta->ops_index].from_obj(attr, src_attr); if (res != TEE_SUCCESS) return res; } } o->have_attrs = have_attrs; return TEE_SUCCESS; } TEE_Result tee_obj_set_type(struct tee_obj *o, uint32_t obj_type, size_t max_key_size) { TEE_Result res = TEE_SUCCESS; const struct tee_cryp_obj_type_props *type_props; /* Can only set type for newly allocated objs */ if (o->attr) return TEE_ERROR_BAD_STATE; /* * Verify that maxKeySize is supported and find out how * much should be allocated. */ if (obj_type == TEE_TYPE_DATA) { if (max_key_size) return TEE_ERROR_NOT_SUPPORTED; } else { /* Find description of object */ type_props = tee_svc_find_type_props(obj_type); if (!type_props) return TEE_ERROR_NOT_SUPPORTED; /* Check that maxKeySize follows restrictions */ if (max_key_size % type_props->quanta != 0) return TEE_ERROR_NOT_SUPPORTED; if (max_key_size < type_props->min_size) return TEE_ERROR_NOT_SUPPORTED; if (max_key_size > type_props->max_size) return TEE_ERROR_NOT_SUPPORTED; o->attr = calloc(1, type_props->alloc_size); if (!o->attr) return TEE_ERROR_OUT_OF_MEMORY; } /* If we have a key structure, pre-allocate the bignums inside */ switch (obj_type) { case TEE_TYPE_RSA_PUBLIC_KEY: res = crypto_acipher_alloc_rsa_public_key(o->attr, max_key_size); break; case TEE_TYPE_RSA_KEYPAIR: res = crypto_acipher_alloc_rsa_keypair(o->attr, max_key_size); break; case TEE_TYPE_DSA_PUBLIC_KEY: res = crypto_acipher_alloc_dsa_public_key(o->attr, max_key_size); break; case TEE_TYPE_DSA_KEYPAIR: res = crypto_acipher_alloc_dsa_keypair(o->attr, max_key_size); break; case TEE_TYPE_DH_KEYPAIR: res = crypto_acipher_alloc_dh_keypair(o->attr, max_key_size); break; case TEE_TYPE_ECDSA_PUBLIC_KEY: case TEE_TYPE_ECDH_PUBLIC_KEY: res = crypto_acipher_alloc_ecc_public_key(o->attr, max_key_size); break; case TEE_TYPE_ECDSA_KEYPAIR: case TEE_TYPE_ECDH_KEYPAIR: res = crypto_acipher_alloc_ecc_keypair(o->attr, max_key_size); break; default: if (obj_type != TEE_TYPE_DATA) { struct tee_cryp_obj_secret *key = o->attr; key->alloc_size = type_props->alloc_size - sizeof(*key); } break; } if (res != TEE_SUCCESS) return res; o->info.objectType = obj_type; o->info.maxKeySize = max_key_size; o->info.objectUsage = TEE_USAGE_DEFAULT; return TEE_SUCCESS; } TEE_Result syscall_cryp_obj_alloc(unsigned long obj_type, unsigned long max_key_size, uint32_t *obj) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; if (obj_type == TEE_TYPE_DATA) return TEE_ERROR_NOT_SUPPORTED; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; o = tee_obj_alloc(); if (!o) return TEE_ERROR_OUT_OF_MEMORY; res = tee_obj_set_type(o, obj_type, max_key_size); if (res != TEE_SUCCESS) { tee_obj_free(o); return res; } tee_obj_add(to_user_ta_ctx(sess->ctx), o); res = tee_svc_copy_kaddr_to_uref(obj, o); if (res != TEE_SUCCESS) tee_obj_close(to_user_ta_ctx(sess->ctx), o); return res; } TEE_Result syscall_cryp_obj_close(unsigned long obj) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; /* * If it's busy it's used by an operation, a client should never have * this handle. */ if (o->busy) return TEE_ERROR_ITEM_NOT_FOUND; tee_obj_close(to_user_ta_ctx(sess->ctx), o); return TEE_SUCCESS; } TEE_Result syscall_cryp_obj_reset(unsigned long obj) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) == 0) { tee_obj_attr_clear(o); o->info.keySize = 0; o->info.objectUsage = TEE_USAGE_DEFAULT; } else { return TEE_ERROR_BAD_PARAMETERS; } /* the object is no more initialized */ o->info.handleFlags &= ~TEE_HANDLE_FLAG_INITIALIZED; return TEE_SUCCESS; } static TEE_Result copy_in_attrs(struct user_ta_ctx *utc, const struct utee_attribute *usr_attrs, uint32_t attr_count, TEE_Attribute *attrs) { TEE_Result res; uint32_t n; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)usr_attrs, attr_count * sizeof(struct utee_attribute)); if (res != TEE_SUCCESS) return res; for (n = 0; n < attr_count; n++) { attrs[n].attributeID = usr_attrs[n].attribute_id; if (attrs[n].attributeID & TEE_ATTR_BIT_VALUE) { attrs[n].content.value.a = usr_attrs[n].a; attrs[n].content.value.b = usr_attrs[n].b; } else { uintptr_t buf = usr_attrs[n].a; size_t len = usr_attrs[n].b; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, buf, len); if (res != TEE_SUCCESS) return res; attrs[n].content.ref.buffer = (void *)buf; attrs[n].content.ref.length = len; } } return TEE_SUCCESS; } enum attr_usage { ATTR_USAGE_POPULATE, ATTR_USAGE_GENERATE_KEY }; static TEE_Result tee_svc_cryp_check_attr(enum attr_usage usage, const struct tee_cryp_obj_type_props *type_props, const TEE_Attribute *attrs, uint32_t attr_count) { uint32_t required_flag; uint32_t opt_flag; bool all_opt_needed; uint32_t req_attrs = 0; uint32_t opt_grp_attrs = 0; uint32_t attrs_found = 0; size_t n; uint32_t bit; uint32_t flags; int idx; if (usage == ATTR_USAGE_POPULATE) { required_flag = TEE_TYPE_ATTR_REQUIRED; opt_flag = TEE_TYPE_ATTR_OPTIONAL_GROUP; all_opt_needed = true; } else { required_flag = TEE_TYPE_ATTR_GEN_KEY_REQ; opt_flag = TEE_TYPE_ATTR_GEN_KEY_OPT; all_opt_needed = false; } /* * First find out which attributes are required and which belong to * the optional group */ for (n = 0; n < type_props->num_type_attrs; n++) { bit = 1 << n; flags = type_props->type_attrs[n].flags; if (flags & required_flag) req_attrs |= bit; else if (flags & opt_flag) opt_grp_attrs |= bit; } /* * Verify that all required attributes are in place and * that the same attribute isn't repeated. */ for (n = 0; n < attr_count; n++) { idx = tee_svc_cryp_obj_find_type_attr_idx( attrs[n].attributeID, type_props); /* attribute not defined in current object type */ if (idx < 0) return TEE_ERROR_ITEM_NOT_FOUND; bit = 1 << idx; /* attribute not repeated */ if ((attrs_found & bit) != 0) return TEE_ERROR_ITEM_NOT_FOUND; attrs_found |= bit; } /* Required attribute missing */ if ((attrs_found & req_attrs) != req_attrs) return TEE_ERROR_ITEM_NOT_FOUND; /* * If the flag says that "if one of the optional attributes are included * all of them has to be included" this must be checked. */ if (all_opt_needed && (attrs_found & opt_grp_attrs) != 0 && (attrs_found & opt_grp_attrs) != opt_grp_attrs) return TEE_ERROR_ITEM_NOT_FOUND; return TEE_SUCCESS; } static TEE_Result get_ec_key_size(uint32_t curve, size_t *key_size) { switch (curve) { case TEE_ECC_CURVE_NIST_P192: *key_size = 192; break; case TEE_ECC_CURVE_NIST_P224: *key_size = 224; break; case TEE_ECC_CURVE_NIST_P256: *key_size = 256; break; case TEE_ECC_CURVE_NIST_P384: *key_size = 384; break; case TEE_ECC_CURVE_NIST_P521: *key_size = 521; break; default: return TEE_ERROR_NOT_SUPPORTED; } return TEE_SUCCESS; } static TEE_Result tee_svc_cryp_obj_populate_type( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, const TEE_Attribute *attrs, uint32_t attr_count) { TEE_Result res; uint32_t have_attrs = 0; size_t obj_size = 0; size_t n; int idx; const struct attr_ops *ops; void *attr; for (n = 0; n < attr_count; n++) { idx = tee_svc_cryp_obj_find_type_attr_idx( attrs[n].attributeID, type_props); /* attribute not defined in current object type */ if (idx < 0) return TEE_ERROR_ITEM_NOT_FOUND; have_attrs |= BIT32(idx); ops = attr_ops + type_props->type_attrs[idx].ops_index; attr = (uint8_t *)o->attr + type_props->type_attrs[idx].raw_offs; if (attrs[n].attributeID & TEE_ATTR_BIT_VALUE) res = ops->from_user(attr, &attrs[n].content.value, sizeof(attrs[n].content.value)); else res = ops->from_user(attr, attrs[n].content.ref.buffer, attrs[n].content.ref.length); if (res != TEE_SUCCESS) return res; /* * First attr_idx signifies the attribute that gives the size * of the object */ if (type_props->type_attrs[idx].flags & TEE_TYPE_ATTR_SIZE_INDICATOR) { /* * For ECDSA/ECDH we need to translate curve into * object size */ if (attrs[n].attributeID == TEE_ATTR_ECC_CURVE) { res = get_ec_key_size(attrs[n].content.value.a, &obj_size); if (res != TEE_SUCCESS) return res; } else { obj_size += (attrs[n].content.ref.length * 8); } } } /* * We have to do it like this because the parity bits aren't counted * when telling the size of the key in bits. */ if (o->info.objectType == TEE_TYPE_DES || o->info.objectType == TEE_TYPE_DES3) obj_size -= obj_size / 8; /* Exclude parity in size of key */ o->have_attrs = have_attrs; o->info.keySize = obj_size; return TEE_SUCCESS; } TEE_Result syscall_cryp_obj_populate(unsigned long obj, struct utee_attribute *usr_attrs, unsigned long attr_count) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; const struct tee_cryp_obj_type_props *type_props; TEE_Attribute *attrs = NULL; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; /* Must be a transient object */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0) return TEE_ERROR_BAD_PARAMETERS; /* Must not be initialized already */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0) return TEE_ERROR_BAD_PARAMETERS; type_props = tee_svc_find_type_props(o->info.objectType); if (!type_props) return TEE_ERROR_NOT_IMPLEMENTED; size_t alloc_size = 0; if (MUL_OVERFLOW(sizeof(TEE_Attribute), attr_count, &alloc_size)) return TEE_ERROR_OVERFLOW; attrs = malloc(alloc_size); if (!attrs) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_attrs, attr_count, attrs); if (res != TEE_SUCCESS) goto out; res = tee_svc_cryp_check_attr(ATTR_USAGE_POPULATE, type_props, attrs, attr_count); if (res != TEE_SUCCESS) goto out; res = tee_svc_cryp_obj_populate_type(o, type_props, attrs, attr_count); if (res == TEE_SUCCESS) o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; out: free(attrs); return res; } TEE_Result syscall_cryp_obj_copy(unsigned long dst, unsigned long src) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *dst_o; struct tee_obj *src_o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(dst), &dst_o); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(src), &src_o); if (res != TEE_SUCCESS) return res; if ((src_o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; if ((dst_o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0) return TEE_ERROR_BAD_PARAMETERS; if ((dst_o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0) return TEE_ERROR_BAD_PARAMETERS; res = tee_obj_attr_copy_from(dst_o, src_o); if (res != TEE_SUCCESS) return res; dst_o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; dst_o->info.keySize = src_o->info.keySize; dst_o->info.objectUsage = src_o->info.objectUsage; return TEE_SUCCESS; } static TEE_Result tee_svc_obj_generate_key_rsa( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, uint32_t key_size, const TEE_Attribute *params, uint32_t param_count) { TEE_Result res; struct rsa_keypair *key = o->attr; uint32_t e = TEE_U32_TO_BIG_ENDIAN(65537); /* Copy the present attributes into the obj before starting */ res = tee_svc_cryp_obj_populate_type(o, type_props, params, param_count); if (res != TEE_SUCCESS) return res; if (!get_attribute(o, type_props, TEE_ATTR_RSA_PUBLIC_EXPONENT)) crypto_bignum_bin2bn((const uint8_t *)&e, sizeof(e), key->e); res = crypto_acipher_gen_rsa_key(key, key_size); if (res != TEE_SUCCESS) return res; /* Set bits for all known attributes for this object type */ o->have_attrs = (1 << type_props->num_type_attrs) - 1; return TEE_SUCCESS; } static TEE_Result tee_svc_obj_generate_key_dsa( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, uint32_t key_size) { TEE_Result res; res = crypto_acipher_gen_dsa_key(o->attr, key_size); if (res != TEE_SUCCESS) return res; /* Set bits for all known attributes for this object type */ o->have_attrs = (1 << type_props->num_type_attrs) - 1; return TEE_SUCCESS; } static TEE_Result tee_svc_obj_generate_key_dh( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, uint32_t key_size __unused, const TEE_Attribute *params, uint32_t param_count) { TEE_Result res; struct dh_keypair *tee_dh_key; struct bignum *dh_q = NULL; uint32_t dh_xbits = 0; /* Copy the present attributes into the obj before starting */ res = tee_svc_cryp_obj_populate_type(o, type_props, params, param_count); if (res != TEE_SUCCESS) return res; tee_dh_key = (struct dh_keypair *)o->attr; if (get_attribute(o, type_props, TEE_ATTR_DH_SUBPRIME)) dh_q = tee_dh_key->q; if (get_attribute(o, type_props, TEE_ATTR_DH_X_BITS)) dh_xbits = tee_dh_key->xbits; res = crypto_acipher_gen_dh_key(tee_dh_key, dh_q, dh_xbits); if (res != TEE_SUCCESS) return res; /* Set bits for the generated public and private key */ set_attribute(o, type_props, TEE_ATTR_DH_PUBLIC_VALUE); set_attribute(o, type_props, TEE_ATTR_DH_PRIVATE_VALUE); set_attribute(o, type_props, TEE_ATTR_DH_X_BITS); return TEE_SUCCESS; } static TEE_Result tee_svc_obj_generate_key_ecc( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, uint32_t key_size __unused, const TEE_Attribute *params, uint32_t param_count) { TEE_Result res; struct ecc_keypair *tee_ecc_key; /* Copy the present attributes into the obj before starting */ res = tee_svc_cryp_obj_populate_type(o, type_props, params, param_count); if (res != TEE_SUCCESS) return res; tee_ecc_key = (struct ecc_keypair *)o->attr; res = crypto_acipher_gen_ecc_key(tee_ecc_key); if (res != TEE_SUCCESS) return res; /* Set bits for the generated public and private key */ set_attribute(o, type_props, TEE_ATTR_ECC_PRIVATE_VALUE); set_attribute(o, type_props, TEE_ATTR_ECC_PUBLIC_VALUE_X); set_attribute(o, type_props, TEE_ATTR_ECC_PUBLIC_VALUE_Y); set_attribute(o, type_props, TEE_ATTR_ECC_CURVE); return TEE_SUCCESS; } TEE_Result syscall_obj_generate_key(unsigned long obj, unsigned long key_size, const struct utee_attribute *usr_params, unsigned long param_count) { TEE_Result res; struct tee_ta_session *sess; const struct tee_cryp_obj_type_props *type_props; struct tee_obj *o; struct tee_cryp_obj_secret *key; size_t byte_size; TEE_Attribute *params = NULL; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; /* Must be a transient object */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0) return TEE_ERROR_BAD_STATE; /* Must not be initialized already */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0) return TEE_ERROR_BAD_STATE; /* Find description of object */ type_props = tee_svc_find_type_props(o->info.objectType); if (!type_props) return TEE_ERROR_NOT_SUPPORTED; /* Check that maxKeySize follows restrictions */ if (key_size % type_props->quanta != 0) return TEE_ERROR_NOT_SUPPORTED; if (key_size < type_props->min_size) return TEE_ERROR_NOT_SUPPORTED; if (key_size > type_props->max_size) return TEE_ERROR_NOT_SUPPORTED; size_t alloc_size = 0; if (MUL_OVERFLOW(sizeof(TEE_Attribute), param_count, &alloc_size)) return TEE_ERROR_OVERFLOW; params = malloc(alloc_size); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_params, param_count, params); if (res != TEE_SUCCESS) goto out; res = tee_svc_cryp_check_attr(ATTR_USAGE_GENERATE_KEY, type_props, params, param_count); if (res != TEE_SUCCESS) goto out; switch (o->info.objectType) { case TEE_TYPE_AES: case TEE_TYPE_DES: case TEE_TYPE_DES3: case TEE_TYPE_HMAC_MD5: case TEE_TYPE_HMAC_SHA1: case TEE_TYPE_HMAC_SHA224: case TEE_TYPE_HMAC_SHA256: case TEE_TYPE_HMAC_SHA384: case TEE_TYPE_HMAC_SHA512: case TEE_TYPE_GENERIC_SECRET: byte_size = key_size / 8; /* * We have to do it like this because the parity bits aren't * counted when telling the size of the key in bits. */ if (o->info.objectType == TEE_TYPE_DES || o->info.objectType == TEE_TYPE_DES3) { byte_size = (key_size + key_size / 7) / 8; } key = (struct tee_cryp_obj_secret *)o->attr; if (byte_size > key->alloc_size) { res = TEE_ERROR_EXCESS_DATA; goto out; } res = crypto_rng_read((void *)(key + 1), byte_size); if (res != TEE_SUCCESS) goto out; key->key_size = byte_size; /* Set bits for all known attributes for this object type */ o->have_attrs = (1 << type_props->num_type_attrs) - 1; break; case TEE_TYPE_RSA_KEYPAIR: res = tee_svc_obj_generate_key_rsa(o, type_props, key_size, params, param_count); if (res != TEE_SUCCESS) goto out; break; case TEE_TYPE_DSA_KEYPAIR: res = tee_svc_obj_generate_key_dsa(o, type_props, key_size); if (res != TEE_SUCCESS) goto out; break; case TEE_TYPE_DH_KEYPAIR: res = tee_svc_obj_generate_key_dh(o, type_props, key_size, params, param_count); if (res != TEE_SUCCESS) goto out; break; case TEE_TYPE_ECDSA_KEYPAIR: case TEE_TYPE_ECDH_KEYPAIR: res = tee_svc_obj_generate_key_ecc(o, type_props, key_size, params, param_count); if (res != TEE_SUCCESS) goto out; break; default: res = TEE_ERROR_BAD_FORMAT; } out: free(params); if (res == TEE_SUCCESS) { o->info.keySize = key_size; o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; } return res; } static TEE_Result tee_svc_cryp_get_state(struct tee_ta_session *sess, uint32_t state_id, struct tee_cryp_state **state) { struct tee_cryp_state *s; struct user_ta_ctx *utc = to_user_ta_ctx(sess->ctx); TAILQ_FOREACH(s, &utc->cryp_states, link) { if (state_id == (vaddr_t)s) { *state = s; return TEE_SUCCESS; } } return TEE_ERROR_BAD_PARAMETERS; } static void cryp_state_free(struct user_ta_ctx *utc, struct tee_cryp_state *cs) { struct tee_obj *o; if (tee_obj_get(utc, cs->key1, &o) == TEE_SUCCESS) tee_obj_close(utc, o); if (tee_obj_get(utc, cs->key2, &o) == TEE_SUCCESS) tee_obj_close(utc, o); TAILQ_REMOVE(&utc->cryp_states, cs, link); if (cs->ctx_finalize != NULL) cs->ctx_finalize(cs->ctx, cs->algo); switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_CIPHER: crypto_cipher_free_ctx(cs->ctx, cs->algo); break; case TEE_OPERATION_AE: crypto_authenc_free_ctx(cs->ctx, cs->algo); break; case TEE_OPERATION_DIGEST: crypto_hash_free_ctx(cs->ctx, cs->algo); break; case TEE_OPERATION_MAC: crypto_mac_free_ctx(cs->ctx, cs->algo); break; default: assert(!cs->ctx); } free(cs); } static TEE_Result tee_svc_cryp_check_key_type(const struct tee_obj *o, uint32_t algo, TEE_OperationMode mode) { uint32_t req_key_type; uint32_t req_key_type2 = 0; switch (TEE_ALG_GET_MAIN_ALG(algo)) { case TEE_MAIN_ALGO_MD5: req_key_type = TEE_TYPE_HMAC_MD5; break; case TEE_MAIN_ALGO_SHA1: req_key_type = TEE_TYPE_HMAC_SHA1; break; case TEE_MAIN_ALGO_SHA224: req_key_type = TEE_TYPE_HMAC_SHA224; break; case TEE_MAIN_ALGO_SHA256: req_key_type = TEE_TYPE_HMAC_SHA256; break; case TEE_MAIN_ALGO_SHA384: req_key_type = TEE_TYPE_HMAC_SHA384; break; case TEE_MAIN_ALGO_SHA512: req_key_type = TEE_TYPE_HMAC_SHA512; break; case TEE_MAIN_ALGO_AES: req_key_type = TEE_TYPE_AES; break; case TEE_MAIN_ALGO_DES: req_key_type = TEE_TYPE_DES; break; case TEE_MAIN_ALGO_DES3: req_key_type = TEE_TYPE_DES3; break; case TEE_MAIN_ALGO_RSA: req_key_type = TEE_TYPE_RSA_KEYPAIR; if (mode == TEE_MODE_ENCRYPT || mode == TEE_MODE_VERIFY) req_key_type2 = TEE_TYPE_RSA_PUBLIC_KEY; break; case TEE_MAIN_ALGO_DSA: req_key_type = TEE_TYPE_DSA_KEYPAIR; if (mode == TEE_MODE_ENCRYPT || mode == TEE_MODE_VERIFY) req_key_type2 = TEE_TYPE_DSA_PUBLIC_KEY; break; case TEE_MAIN_ALGO_DH: req_key_type = TEE_TYPE_DH_KEYPAIR; break; case TEE_MAIN_ALGO_ECDSA: req_key_type = TEE_TYPE_ECDSA_KEYPAIR; if (mode == TEE_MODE_VERIFY) req_key_type2 = TEE_TYPE_ECDSA_PUBLIC_KEY; break; case TEE_MAIN_ALGO_ECDH: req_key_type = TEE_TYPE_ECDH_KEYPAIR; break; #if defined(CFG_CRYPTO_HKDF) case TEE_MAIN_ALGO_HKDF: req_key_type = TEE_TYPE_HKDF_IKM; break; #endif #if defined(CFG_CRYPTO_CONCAT_KDF) case TEE_MAIN_ALGO_CONCAT_KDF: req_key_type = TEE_TYPE_CONCAT_KDF_Z; break; #endif #if defined(CFG_CRYPTO_PBKDF2) case TEE_MAIN_ALGO_PBKDF2: req_key_type = TEE_TYPE_PBKDF2_PASSWORD; break; #endif default: return TEE_ERROR_BAD_PARAMETERS; } if (req_key_type != o->info.objectType && req_key_type2 != o->info.objectType) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } TEE_Result syscall_cryp_state_alloc(unsigned long algo, unsigned long mode, unsigned long key1, unsigned long key2, uint32_t *state) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; struct tee_obj *o1 = NULL; struct tee_obj *o2 = NULL; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); if (key1 != 0) { res = tee_obj_get(utc, tee_svc_uref_to_vaddr(key1), &o1); if (res != TEE_SUCCESS) return res; if (o1->busy) return TEE_ERROR_BAD_PARAMETERS; res = tee_svc_cryp_check_key_type(o1, algo, mode); if (res != TEE_SUCCESS) return res; } if (key2 != 0) { res = tee_obj_get(utc, tee_svc_uref_to_vaddr(key2), &o2); if (res != TEE_SUCCESS) return res; if (o2->busy) return TEE_ERROR_BAD_PARAMETERS; res = tee_svc_cryp_check_key_type(o2, algo, mode); if (res != TEE_SUCCESS) return res; } cs = calloc(1, sizeof(struct tee_cryp_state)); if (!cs) return TEE_ERROR_OUT_OF_MEMORY; TAILQ_INSERT_TAIL(&utc->cryp_states, cs, link); cs->algo = algo; cs->mode = mode; switch (TEE_ALG_GET_CLASS(algo)) { case TEE_OPERATION_EXTENSION: #ifdef CFG_CRYPTO_RSASSA_NA1 if (algo == TEE_ALG_RSASSA_PKCS1_V1_5) goto rsassa_na1; #endif res = TEE_ERROR_NOT_SUPPORTED; break; case TEE_OPERATION_CIPHER: if ((algo == TEE_ALG_AES_XTS && (key1 == 0 || key2 == 0)) || (algo != TEE_ALG_AES_XTS && (key1 == 0 || key2 != 0))) { res = TEE_ERROR_BAD_PARAMETERS; } else { res = crypto_cipher_alloc_ctx(&cs->ctx, algo); if (res != TEE_SUCCESS) break; } break; case TEE_OPERATION_AE: if (key1 == 0 || key2 != 0) { res = TEE_ERROR_BAD_PARAMETERS; } else { res = crypto_authenc_alloc_ctx(&cs->ctx, algo); if (res != TEE_SUCCESS) break; } break; case TEE_OPERATION_MAC: if (key1 == 0 || key2 != 0) { res = TEE_ERROR_BAD_PARAMETERS; } else { res = crypto_mac_alloc_ctx(&cs->ctx, algo); if (res != TEE_SUCCESS) break; } break; case TEE_OPERATION_DIGEST: if (key1 != 0 || key2 != 0) { res = TEE_ERROR_BAD_PARAMETERS; } else { res = crypto_hash_alloc_ctx(&cs->ctx, algo); if (res != TEE_SUCCESS) break; } break; case TEE_OPERATION_ASYMMETRIC_CIPHER: case TEE_OPERATION_ASYMMETRIC_SIGNATURE: rsassa_na1: __maybe_unused if (key1 == 0 || key2 != 0) res = TEE_ERROR_BAD_PARAMETERS; break; case TEE_OPERATION_KEY_DERIVATION: if (key1 == 0 || key2 != 0) res = TEE_ERROR_BAD_PARAMETERS; break; default: res = TEE_ERROR_NOT_SUPPORTED; break; } if (res != TEE_SUCCESS) goto out; res = tee_svc_copy_kaddr_to_uref(state, cs); if (res != TEE_SUCCESS) goto out; /* Register keys */ if (o1 != NULL) { o1->busy = true; cs->key1 = (vaddr_t)o1; } if (o2 != NULL) { o2->busy = true; cs->key2 = (vaddr_t)o2; } out: if (res != TEE_SUCCESS) cryp_state_free(utc, cs); return res; } TEE_Result syscall_cryp_state_copy(unsigned long dst, unsigned long src) { TEE_Result res; struct tee_cryp_state *cs_dst; struct tee_cryp_state *cs_src; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(dst), &cs_dst); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(src), &cs_src); if (res != TEE_SUCCESS) return res; if (cs_dst->algo != cs_src->algo || cs_dst->mode != cs_src->mode) return TEE_ERROR_BAD_PARAMETERS; switch (TEE_ALG_GET_CLASS(cs_src->algo)) { case TEE_OPERATION_CIPHER: crypto_cipher_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo); break; case TEE_OPERATION_AE: crypto_authenc_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo); break; case TEE_OPERATION_DIGEST: crypto_hash_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo); break; case TEE_OPERATION_MAC: crypto_mac_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo); break; default: return TEE_ERROR_BAD_STATE; } return TEE_SUCCESS; } void tee_svc_cryp_free_states(struct user_ta_ctx *utc) { struct tee_cryp_state_head *states = &utc->cryp_states; while (!TAILQ_EMPTY(states)) cryp_state_free(utc, TAILQ_FIRST(states)); } TEE_Result syscall_cryp_state_free(unsigned long state) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; cryp_state_free(to_user_ta_ctx(sess->ctx), cs); return TEE_SUCCESS; } TEE_Result syscall_hash_init(unsigned long state, const void *iv __maybe_unused, size_t iv_len __maybe_unused) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_DIGEST: res = crypto_hash_init(cs->ctx, cs->algo); if (res != TEE_SUCCESS) return res; break; case TEE_OPERATION_MAC: { struct tee_obj *o; struct tee_cryp_obj_secret *key; res = tee_obj_get(to_user_ta_ctx(sess->ctx), cs->key1, &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; key = (struct tee_cryp_obj_secret *)o->attr; res = crypto_mac_init(cs->ctx, cs->algo, (void *)(key + 1), key->key_size); if (res != TEE_SUCCESS) return res; break; } default: return TEE_ERROR_BAD_PARAMETERS; } return TEE_SUCCESS; } TEE_Result syscall_hash_update(unsigned long state, const void *chunk, size_t chunk_size) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; /* No data, but size provided isn't valid parameters. */ if (!chunk && chunk_size) return TEE_ERROR_BAD_PARAMETERS; /* Zero length hash is valid, but nothing we need to do. */ if (!chunk_size) return TEE_SUCCESS; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)chunk, chunk_size); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_DIGEST: res = crypto_hash_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; break; case TEE_OPERATION_MAC: res = crypto_mac_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; break; default: return TEE_ERROR_BAD_PARAMETERS; } return TEE_SUCCESS; } TEE_Result syscall_hash_final(unsigned long state, const void *chunk, size_t chunk_size, void *hash, uint64_t *hash_len) { TEE_Result res, res2; size_t hash_size; uint64_t hlen; struct tee_cryp_state *cs; struct tee_ta_session *sess; /* No data, but size provided isn't valid parameters. */ if (!chunk && chunk_size) return TEE_ERROR_BAD_PARAMETERS; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)chunk, chunk_size); if (res != TEE_SUCCESS) return res; res = tee_svc_copy_from_user(&hlen, hash_len, sizeof(hlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)hash, hlen); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_DIGEST: res = tee_hash_get_digest_size(cs->algo, &hash_size); if (res != TEE_SUCCESS) return res; if (*hash_len < hash_size) { res = TEE_ERROR_SHORT_BUFFER; goto out; } if (chunk_size) { res = crypto_hash_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; } res = crypto_hash_final(cs->ctx, cs->algo, hash, hash_size); if (res != TEE_SUCCESS) return res; break; case TEE_OPERATION_MAC: res = tee_mac_get_digest_size(cs->algo, &hash_size); if (res != TEE_SUCCESS) return res; if (*hash_len < hash_size) { res = TEE_ERROR_SHORT_BUFFER; goto out; } if (chunk_size) { res = crypto_mac_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; } res = crypto_mac_final(cs->ctx, cs->algo, hash, hash_size); if (res != TEE_SUCCESS) return res; break; default: return TEE_ERROR_BAD_PARAMETERS; } out: hlen = hash_size; res2 = tee_svc_copy_to_user(hash_len, &hlen, sizeof(*hash_len)); if (res2 != TEE_SUCCESS) return res2; return res; } TEE_Result syscall_cipher_init(unsigned long state, const void *iv, size_t iv_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; struct tee_obj *o; struct tee_cryp_obj_secret *key1; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) iv, iv_len); if (res != TEE_SUCCESS) return res; res = tee_obj_get(utc, cs->key1, &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; key1 = o->attr; if (tee_obj_get(utc, cs->key2, &o) == TEE_SUCCESS) { struct tee_cryp_obj_secret *key2 = o->attr; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; res = crypto_cipher_init(cs->ctx, cs->algo, cs->mode, (uint8_t *)(key1 + 1), key1->key_size, (uint8_t *)(key2 + 1), key2->key_size, iv, iv_len); } else { res = crypto_cipher_init(cs->ctx, cs->algo, cs->mode, (uint8_t *)(key1 + 1), key1->key_size, NULL, 0, iv, iv_len); } if (res != TEE_SUCCESS) return res; cs->ctx_finalize = crypto_cipher_final; return TEE_SUCCESS; } static TEE_Result tee_svc_cipher_update_helper(unsigned long state, bool last_block, const void *src, size_t src_len, void *dst, uint64_t *dst_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)src, src_len); if (res != TEE_SUCCESS) return res; if (!dst_len) { dlen = 0; } else { res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)dst, dlen); if (res != TEE_SUCCESS) return res; } if (dlen < src_len) { res = TEE_ERROR_SHORT_BUFFER; goto out; } if (src_len > 0) { /* Permit src_len == 0 to finalize the operation */ res = tee_do_cipher_update(cs->ctx, cs->algo, cs->mode, last_block, src, src_len, dst); } if (last_block && cs->ctx_finalize != NULL) { cs->ctx_finalize(cs->ctx, cs->algo); cs->ctx_finalize = NULL; } out: if ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) && dst_len != NULL) { TEE_Result res2; dlen = src_len; res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) res = res2; } return res; } TEE_Result syscall_cipher_update(unsigned long state, const void *src, size_t src_len, void *dst, uint64_t *dst_len) { return tee_svc_cipher_update_helper(state, false /* last_block */, src, src_len, dst, dst_len); } TEE_Result syscall_cipher_final(unsigned long state, const void *src, size_t src_len, void *dst, uint64_t *dst_len) { return tee_svc_cipher_update_helper(state, true /* last_block */, src, src_len, dst, dst_len); } #if defined(CFG_CRYPTO_HKDF) static TEE_Result get_hkdf_params(const TEE_Attribute *params, uint32_t param_count, void **salt, size_t *salt_len, void **info, size_t *info_len, size_t *okm_len) { size_t n; enum { SALT = 0x1, LENGTH = 0x2, INFO = 0x4 }; uint8_t found = 0; *salt = *info = NULL; *salt_len = *info_len = *okm_len = 0; for (n = 0; n < param_count; n++) { switch (params[n].attributeID) { case TEE_ATTR_HKDF_SALT: if (!(found & SALT)) { *salt = params[n].content.ref.buffer; *salt_len = params[n].content.ref.length; found |= SALT; } break; case TEE_ATTR_HKDF_OKM_LENGTH: if (!(found & LENGTH)) { *okm_len = params[n].content.value.a; found |= LENGTH; } break; case TEE_ATTR_HKDF_INFO: if (!(found & INFO)) { *info = params[n].content.ref.buffer; *info_len = params[n].content.ref.length; found |= INFO; } break; default: /* Unexpected attribute */ return TEE_ERROR_BAD_PARAMETERS; } } if (!(found & LENGTH)) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } #endif #if defined(CFG_CRYPTO_CONCAT_KDF) static TEE_Result get_concat_kdf_params(const TEE_Attribute *params, uint32_t param_count, void **other_info, size_t *other_info_len, size_t *derived_key_len) { size_t n; enum { LENGTH = 0x1, INFO = 0x2 }; uint8_t found = 0; *other_info = NULL; *other_info_len = *derived_key_len = 0; for (n = 0; n < param_count; n++) { switch (params[n].attributeID) { case TEE_ATTR_CONCAT_KDF_OTHER_INFO: if (!(found & INFO)) { *other_info = params[n].content.ref.buffer; *other_info_len = params[n].content.ref.length; found |= INFO; } break; case TEE_ATTR_CONCAT_KDF_DKM_LENGTH: if (!(found & LENGTH)) { *derived_key_len = params[n].content.value.a; found |= LENGTH; } break; default: /* Unexpected attribute */ return TEE_ERROR_BAD_PARAMETERS; } } if (!(found & LENGTH)) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } #endif #if defined(CFG_CRYPTO_PBKDF2) static TEE_Result get_pbkdf2_params(const TEE_Attribute *params, uint32_t param_count, void **salt, size_t *salt_len, size_t *derived_key_len, size_t *iteration_count) { size_t n; enum { SALT = 0x1, LENGTH = 0x2, COUNT = 0x4 }; uint8_t found = 0; *salt = NULL; *salt_len = *derived_key_len = *iteration_count = 0; for (n = 0; n < param_count; n++) { switch (params[n].attributeID) { case TEE_ATTR_PBKDF2_SALT: if (!(found & SALT)) { *salt = params[n].content.ref.buffer; *salt_len = params[n].content.ref.length; found |= SALT; } break; case TEE_ATTR_PBKDF2_DKM_LENGTH: if (!(found & LENGTH)) { *derived_key_len = params[n].content.value.a; found |= LENGTH; } break; case TEE_ATTR_PBKDF2_ITERATION_COUNT: if (!(found & COUNT)) { *iteration_count = params[n].content.value.a; found |= COUNT; } break; default: /* Unexpected attribute */ return TEE_ERROR_BAD_PARAMETERS; } } if ((found & (LENGTH|COUNT)) != (LENGTH|COUNT)) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } #endif TEE_Result syscall_cryp_derive_key(unsigned long state, const struct utee_attribute *usr_params, unsigned long param_count, unsigned long derived_key) { TEE_Result res = TEE_ERROR_NOT_SUPPORTED; struct tee_ta_session *sess; struct tee_obj *ko; struct tee_obj *so; struct tee_cryp_state *cs; struct tee_cryp_obj_secret *sk; const struct tee_cryp_obj_type_props *type_props; TEE_Attribute *params = NULL; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; size_t alloc_size = 0; if (MUL_OVERFLOW(sizeof(TEE_Attribute), param_count, &alloc_size)) return TEE_ERROR_OVERFLOW; params = malloc(alloc_size); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(utc, usr_params, param_count, params); if (res != TEE_SUCCESS) goto out; /* Get key set in operation */ res = tee_obj_get(utc, cs->key1, &ko); if (res != TEE_SUCCESS) goto out; res = tee_obj_get(utc, tee_svc_uref_to_vaddr(derived_key), &so); if (res != TEE_SUCCESS) goto out; /* Find information needed about the object to initialize */ sk = so->attr; /* Find description of object */ type_props = tee_svc_find_type_props(so->info.objectType); if (!type_props) { res = TEE_ERROR_NOT_SUPPORTED; goto out; } if (cs->algo == TEE_ALG_DH_DERIVE_SHARED_SECRET) { size_t alloc_size; struct bignum *pub; struct bignum *ss; if (param_count != 1 || params[0].attributeID != TEE_ATTR_DH_PUBLIC_VALUE) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } alloc_size = params[0].content.ref.length * 8; pub = crypto_bignum_allocate(alloc_size); ss = crypto_bignum_allocate(alloc_size); if (pub && ss) { crypto_bignum_bin2bn(params[0].content.ref.buffer, params[0].content.ref.length, pub); res = crypto_acipher_dh_shared_secret(ko->attr, pub, ss); if (res == TEE_SUCCESS) { sk->key_size = crypto_bignum_num_bytes(ss); crypto_bignum_bn2bin(ss, (uint8_t *)(sk + 1)); so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } else { res = TEE_ERROR_OUT_OF_MEMORY; } crypto_bignum_free(pub); crypto_bignum_free(ss); } else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_ECDH) { size_t alloc_size; struct ecc_public_key key_public; uint8_t *pt_secret; unsigned long pt_secret_len; if (param_count != 2 || params[0].attributeID != TEE_ATTR_ECC_PUBLIC_VALUE_X || params[1].attributeID != TEE_ATTR_ECC_PUBLIC_VALUE_Y) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } switch (cs->algo) { case TEE_ALG_ECDH_P192: alloc_size = 192; break; case TEE_ALG_ECDH_P224: alloc_size = 224; break; case TEE_ALG_ECDH_P256: alloc_size = 256; break; case TEE_ALG_ECDH_P384: alloc_size = 384; break; case TEE_ALG_ECDH_P521: alloc_size = 521; break; default: res = TEE_ERROR_NOT_IMPLEMENTED; goto out; } /* Create the public key */ res = crypto_acipher_alloc_ecc_public_key(&key_public, alloc_size); if (res != TEE_SUCCESS) goto out; key_public.curve = ((struct ecc_keypair *)ko->attr)->curve; crypto_bignum_bin2bn(params[0].content.ref.buffer, params[0].content.ref.length, key_public.x); crypto_bignum_bin2bn(params[1].content.ref.buffer, params[1].content.ref.length, key_public.y); pt_secret = (uint8_t *)(sk + 1); pt_secret_len = sk->alloc_size; res = crypto_acipher_ecc_shared_secret(ko->attr, &key_public, pt_secret, &pt_secret_len); if (res == TEE_SUCCESS) { sk->key_size = pt_secret_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } /* free the public key */ crypto_acipher_free_ecc_public_key(&key_public); } #if defined(CFG_CRYPTO_HKDF) else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_HKDF) { void *salt, *info; size_t salt_len, info_len, okm_len; uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo); struct tee_cryp_obj_secret *ik = ko->attr; const uint8_t *ikm = (const uint8_t *)(ik + 1); res = get_hkdf_params(params, param_count, &salt, &salt_len, &info, &info_len, &okm_len); if (res != TEE_SUCCESS) goto out; /* Requested size must fit into the output object's buffer */ if (okm_len > ik->alloc_size) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_cryp_hkdf(hash_id, ikm, ik->key_size, salt, salt_len, info, info_len, (uint8_t *)(sk + 1), okm_len); if (res == TEE_SUCCESS) { sk->key_size = okm_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } #endif #if defined(CFG_CRYPTO_CONCAT_KDF) else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_CONCAT_KDF) { void *info; size_t info_len, derived_key_len; uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo); struct tee_cryp_obj_secret *ss = ko->attr; const uint8_t *shared_secret = (const uint8_t *)(ss + 1); res = get_concat_kdf_params(params, param_count, &info, &info_len, &derived_key_len); if (res != TEE_SUCCESS) goto out; /* Requested size must fit into the output object's buffer */ if (derived_key_len > ss->alloc_size) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_cryp_concat_kdf(hash_id, shared_secret, ss->key_size, info, info_len, (uint8_t *)(sk + 1), derived_key_len); if (res == TEE_SUCCESS) { sk->key_size = derived_key_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } #endif #if defined(CFG_CRYPTO_PBKDF2) else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_PBKDF2) { void *salt; size_t salt_len, iteration_count, derived_key_len; uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo); struct tee_cryp_obj_secret *ss = ko->attr; const uint8_t *password = (const uint8_t *)(ss + 1); res = get_pbkdf2_params(params, param_count, &salt, &salt_len, &derived_key_len, &iteration_count); if (res != TEE_SUCCESS) goto out; /* Requested size must fit into the output object's buffer */ if (derived_key_len > ss->alloc_size) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_cryp_pbkdf2(hash_id, password, ss->key_size, salt, salt_len, iteration_count, (uint8_t *)(sk + 1), derived_key_len); if (res == TEE_SUCCESS) { sk->key_size = derived_key_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } #endif else res = TEE_ERROR_NOT_SUPPORTED; out: free(params); return res; } TEE_Result syscall_cryp_random_number_generate(void *buf, size_t blen) { TEE_Result res; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)buf, blen); if (res != TEE_SUCCESS) return res; res = crypto_rng_read(buf, blen); if (res != TEE_SUCCESS) return res; return res; } TEE_Result syscall_authenc_init(unsigned long state, const void *nonce, size_t nonce_len, size_t tag_len, size_t aad_len, size_t payload_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; struct tee_obj *o; struct tee_cryp_obj_secret *key; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), cs->key1, &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; key = o->attr; res = crypto_authenc_init(cs->ctx, cs->algo, cs->mode, (uint8_t *)(key + 1), key->key_size, nonce, nonce_len, tag_len, aad_len, payload_len); if (res != TEE_SUCCESS) return res; cs->ctx_finalize = (tee_cryp_ctx_finalize_func_t)crypto_authenc_final; return TEE_SUCCESS; } TEE_Result syscall_authenc_update_aad(unsigned long state, const void *aad_data, size_t aad_data_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) aad_data, aad_data_len); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = crypto_authenc_update_aad(cs->ctx, cs->algo, cs->mode, aad_data, aad_data_len); if (res != TEE_SUCCESS) return res; return TEE_SUCCESS; } TEE_Result syscall_authenc_update_payload(unsigned long state, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen; size_t tmp_dlen; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) src_data, src_len); if (res != TEE_SUCCESS) return res; res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)dst_data, dlen); if (res != TEE_SUCCESS) return res; if (dlen < src_len) { res = TEE_ERROR_SHORT_BUFFER; goto out; } tmp_dlen = dlen; res = crypto_authenc_update_payload(cs->ctx, cs->algo, cs->mode, src_data, src_len, dst_data, &tmp_dlen); dlen = tmp_dlen; out: if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) { TEE_Result res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) res = res2; } return res; } TEE_Result syscall_authenc_enc_final(unsigned long state, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len, void *tag, uint64_t *tag_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen; uint64_t tlen = 0; size_t tmp_dlen; size_t tmp_tlen; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; if (cs->mode != TEE_MODE_ENCRYPT) return TEE_ERROR_BAD_PARAMETERS; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)src_data, src_len); if (res != TEE_SUCCESS) return res; if (!dst_len) { dlen = 0; } else { res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)dst_data, dlen); if (res != TEE_SUCCESS) return res; } if (dlen < src_len) { res = TEE_ERROR_SHORT_BUFFER; goto out; } res = tee_svc_copy_from_user(&tlen, tag_len, sizeof(tlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)tag, tlen); if (res != TEE_SUCCESS) return res; tmp_dlen = dlen; tmp_tlen = tlen; res = crypto_authenc_enc_final(cs->ctx, cs->algo, src_data, src_len, dst_data, &tmp_dlen, tag, &tmp_tlen); dlen = tmp_dlen; tlen = tmp_tlen; out: if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) { TEE_Result res2; if (dst_len != NULL) { res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) return res2; } res2 = tee_svc_copy_to_user(tag_len, &tlen, sizeof(*tag_len)); if (res2 != TEE_SUCCESS) return res2; } return res; } TEE_Result syscall_authenc_dec_final(unsigned long state, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len, const void *tag, size_t tag_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen; size_t tmp_dlen; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; if (cs->mode != TEE_MODE_DECRYPT) return TEE_ERROR_BAD_PARAMETERS; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)src_data, src_len); if (res != TEE_SUCCESS) return res; if (!dst_len) { dlen = 0; } else { res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)dst_data, dlen); if (res != TEE_SUCCESS) return res; } if (dlen < src_len) { res = TEE_ERROR_SHORT_BUFFER; goto out; } res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)tag, tag_len); if (res != TEE_SUCCESS) return res; tmp_dlen = dlen; res = crypto_authenc_dec_final(cs->ctx, cs->algo, src_data, src_len, dst_data, &tmp_dlen, tag, tag_len); dlen = tmp_dlen; out: if ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) && dst_len != NULL) { TEE_Result res2; res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) return res2; } return res; } static int pkcs1_get_salt_len(const TEE_Attribute *params, uint32_t num_params, size_t default_len) { size_t n; assert(default_len < INT_MAX); for (n = 0; n < num_params; n++) { if (params[n].attributeID == TEE_ATTR_RSA_PSS_SALT_LENGTH) { if (params[n].content.value.a < INT_MAX) return params[n].content.value.a; break; } } /* * If salt length isn't provided use the default value which is * the length of the digest. */ return default_len; } TEE_Result syscall_asymm_operate(unsigned long state, const struct utee_attribute *usr_params, size_t num_params, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen64; size_t dlen; struct tee_obj *o; void *label = NULL; size_t label_len = 0; size_t n; int salt_len; TEE_Attribute *params = NULL; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights( utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) src_data, src_len); if (res != TEE_SUCCESS) return res; res = tee_svc_copy_from_user(&dlen64, dst_len, sizeof(dlen64)); if (res != TEE_SUCCESS) return res; dlen = dlen64; res = tee_mmu_check_access_rights( utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) dst_data, dlen); if (res != TEE_SUCCESS) return res; params = malloc(sizeof(TEE_Attribute) * num_params); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(utc, usr_params, num_params, params); if (res != TEE_SUCCESS) goto out; res = tee_obj_get(utc, cs->key1, &o); if (res != TEE_SUCCESS) goto out; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) { res = TEE_ERROR_GENERIC; goto out; } switch (cs->algo) { case TEE_ALG_RSA_NOPAD: if (cs->mode == TEE_MODE_ENCRYPT) { res = crypto_acipher_rsanopad_encrypt(o->attr, src_data, src_len, dst_data, &dlen); } else if (cs->mode == TEE_MODE_DECRYPT) { res = crypto_acipher_rsanopad_decrypt(o->attr, src_data, src_len, dst_data, &dlen); } else { /* * We will panic because "the mode is not compatible * with the function" */ res = TEE_ERROR_GENERIC; } break; case TEE_ALG_RSAES_PKCS1_V1_5: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512: for (n = 0; n < num_params; n++) { if (params[n].attributeID == TEE_ATTR_RSA_OAEP_LABEL) { label = params[n].content.ref.buffer; label_len = params[n].content.ref.length; break; } } if (cs->mode == TEE_MODE_ENCRYPT) { res = crypto_acipher_rsaes_encrypt(cs->algo, o->attr, label, label_len, src_data, src_len, dst_data, &dlen); } else if (cs->mode == TEE_MODE_DECRYPT) { res = crypto_acipher_rsaes_decrypt( cs->algo, o->attr, label, label_len, src_data, src_len, dst_data, &dlen); } else { res = TEE_ERROR_BAD_PARAMETERS; } break; #if defined(CFG_CRYPTO_RSASSA_NA1) case TEE_ALG_RSASSA_PKCS1_V1_5: #endif case TEE_ALG_RSASSA_PKCS1_V1_5_MD5: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512: if (cs->mode != TEE_MODE_SIGN) { res = TEE_ERROR_BAD_PARAMETERS; break; } salt_len = pkcs1_get_salt_len(params, num_params, src_len); res = crypto_acipher_rsassa_sign(cs->algo, o->attr, salt_len, src_data, src_len, dst_data, &dlen); break; case TEE_ALG_DSA_SHA1: case TEE_ALG_DSA_SHA224: case TEE_ALG_DSA_SHA256: res = crypto_acipher_dsa_sign(cs->algo, o->attr, src_data, src_len, dst_data, &dlen); break; case TEE_ALG_ECDSA_P192: case TEE_ALG_ECDSA_P224: case TEE_ALG_ECDSA_P256: case TEE_ALG_ECDSA_P384: case TEE_ALG_ECDSA_P521: res = crypto_acipher_ecc_sign(cs->algo, o->attr, src_data, src_len, dst_data, &dlen); break; default: res = TEE_ERROR_BAD_PARAMETERS; break; } out: free(params); if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) { TEE_Result res2; dlen64 = dlen; res2 = tee_svc_copy_to_user(dst_len, &dlen64, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) return res2; } return res; } TEE_Result syscall_asymm_verify(unsigned long state, const struct utee_attribute *usr_params, size_t num_params, const void *data, size_t data_len, const void *sig, size_t sig_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; struct tee_obj *o; size_t hash_size; int salt_len = 0; TEE_Attribute *params = NULL; uint32_t hash_algo; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; if (cs->mode != TEE_MODE_VERIFY) return TEE_ERROR_BAD_PARAMETERS; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)data, data_len); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)sig, sig_len); if (res != TEE_SUCCESS) return res; params = malloc(sizeof(TEE_Attribute) * num_params); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(utc, usr_params, num_params, params); if (res != TEE_SUCCESS) goto out; res = tee_obj_get(utc, cs->key1, &o); if (res != TEE_SUCCESS) goto out; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } switch (TEE_ALG_GET_MAIN_ALG(cs->algo)) { case TEE_MAIN_ALGO_RSA: if (cs->algo != TEE_ALG_RSASSA_PKCS1_V1_5) { hash_algo = TEE_DIGEST_HASH_TO_ALGO(cs->algo); res = tee_hash_get_digest_size(hash_algo, &hash_size); if (res != TEE_SUCCESS) break; if (data_len != hash_size) { res = TEE_ERROR_BAD_PARAMETERS; break; } salt_len = pkcs1_get_salt_len(params, num_params, hash_size); } res = crypto_acipher_rsassa_verify(cs->algo, o->attr, salt_len, data, data_len, sig, sig_len); break; case TEE_MAIN_ALGO_DSA: hash_algo = TEE_DIGEST_HASH_TO_ALGO(cs->algo); res = tee_hash_get_digest_size(hash_algo, &hash_size); if (res != TEE_SUCCESS) break; /* * Depending on the DSA algorithm (NIST), the digital signature * output size may be truncated to the size of a key pair * (Q prime size). Q prime size must be less or equal than the * hash output length of the hash algorithm involved. */ if (data_len > hash_size) { res = TEE_ERROR_BAD_PARAMETERS; break; } res = crypto_acipher_dsa_verify(cs->algo, o->attr, data, data_len, sig, sig_len); break; case TEE_MAIN_ALGO_ECDSA: res = crypto_acipher_ecc_verify(cs->algo, o->attr, data, data_len, sig, sig_len); break; default: res = TEE_ERROR_NOT_SUPPORTED; } out: free(params); return res; }
null
// SPDX-License-Identifier: BSD-2-Clause /* * Copyright (c) 2014, STMicroelectronics International N.V. */ #include <assert.h> #include <compiler.h> #include <crypto/crypto.h> #include <kernel/tee_ta_manager.h> #include <mm/tee_mmu.h> #include <string_ext.h> #include <string.h> #include <sys/queue.h> #include <tee_api_types.h> #include <tee/tee_cryp_utl.h> #include <tee/tee_obj.h> #include <tee/tee_svc_cryp.h> #include <tee/tee_svc.h> #include <trace.h> #include <utee_defines.h> #include <util.h> #include <tee_api_defines_extensions.h> #if defined(CFG_CRYPTO_HKDF) #include <tee/tee_cryp_hkdf.h> #endif #if defined(CFG_CRYPTO_CONCAT_KDF) #include <tee/tee_cryp_concat_kdf.h> #endif #if defined(CFG_CRYPTO_PBKDF2) #include <tee/tee_cryp_pbkdf2.h> #endif typedef void (*tee_cryp_ctx_finalize_func_t) (void *ctx, uint32_t algo); struct tee_cryp_state { TAILQ_ENTRY(tee_cryp_state) link; uint32_t algo; uint32_t mode; vaddr_t key1; vaddr_t key2; void *ctx; tee_cryp_ctx_finalize_func_t ctx_finalize; }; struct tee_cryp_obj_secret { uint32_t key_size; uint32_t alloc_size; /* * Pseudo code visualize layout of structure * Next follows data, such as: * uint8_t data[alloc_size] * key_size must never exceed alloc_size */ }; #define TEE_TYPE_ATTR_OPTIONAL 0x0 #define TEE_TYPE_ATTR_REQUIRED 0x1 #define TEE_TYPE_ATTR_OPTIONAL_GROUP 0x2 #define TEE_TYPE_ATTR_SIZE_INDICATOR 0x4 #define TEE_TYPE_ATTR_GEN_KEY_OPT 0x8 #define TEE_TYPE_ATTR_GEN_KEY_REQ 0x10 /* Handle storing of generic secret keys of varying lengths */ #define ATTR_OPS_INDEX_SECRET 0 /* Convert to/from big-endian byte array and provider-specific bignum */ #define ATTR_OPS_INDEX_BIGNUM 1 /* Convert to/from value attribute depending on direction */ #define ATTR_OPS_INDEX_VALUE 2 struct tee_cryp_obj_type_attrs { uint32_t attr_id; uint16_t flags; uint16_t ops_index; uint16_t raw_offs; uint16_t raw_size; }; #define RAW_DATA(_x, _y) \ .raw_offs = offsetof(_x, _y), .raw_size = MEMBER_SIZE(_x, _y) static const struct tee_cryp_obj_type_attrs tee_cryp_obj_secret_value_attrs[] = { { .attr_id = TEE_ATTR_SECRET_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_SECRET, .raw_offs = 0, .raw_size = 0 }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_rsa_pub_key_attrs[] = { { .attr_id = TEE_ATTR_RSA_MODULUS, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_public_key, n) }, { .attr_id = TEE_ATTR_RSA_PUBLIC_EXPONENT, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_public_key, e) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_rsa_keypair_attrs[] = { { .attr_id = TEE_ATTR_RSA_MODULUS, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, n) }, { .attr_id = TEE_ATTR_RSA_PUBLIC_EXPONENT, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, e) }, { .attr_id = TEE_ATTR_RSA_PRIVATE_EXPONENT, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, d) }, { .attr_id = TEE_ATTR_RSA_PRIME1, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, p) }, { .attr_id = TEE_ATTR_RSA_PRIME2, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, q) }, { .attr_id = TEE_ATTR_RSA_EXPONENT1, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, dp) }, { .attr_id = TEE_ATTR_RSA_EXPONENT2, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, dq) }, { .attr_id = TEE_ATTR_RSA_COEFFICIENT, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct rsa_keypair, qp) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dsa_pub_key_attrs[] = { { .attr_id = TEE_ATTR_DSA_PRIME, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_public_key, p) }, { .attr_id = TEE_ATTR_DSA_SUBPRIME, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_public_key, q) }, { .attr_id = TEE_ATTR_DSA_BASE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_public_key, g) }, { .attr_id = TEE_ATTR_DSA_PUBLIC_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_public_key, y) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dsa_keypair_attrs[] = { { .attr_id = TEE_ATTR_DSA_PRIME, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, p) }, { .attr_id = TEE_ATTR_DSA_SUBPRIME, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, q) }, { .attr_id = TEE_ATTR_DSA_BASE, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, g) }, { .attr_id = TEE_ATTR_DSA_PRIVATE_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, x) }, { .attr_id = TEE_ATTR_DSA_PUBLIC_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dsa_keypair, y) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dh_keypair_attrs[] = { { .attr_id = TEE_ATTR_DH_PRIME, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, p) }, { .attr_id = TEE_ATTR_DH_BASE, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, g) }, { .attr_id = TEE_ATTR_DH_PUBLIC_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, y) }, { .attr_id = TEE_ATTR_DH_PRIVATE_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, x) }, { .attr_id = TEE_ATTR_DH_SUBPRIME, .flags = TEE_TYPE_ATTR_OPTIONAL_GROUP | TEE_TYPE_ATTR_GEN_KEY_OPT, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct dh_keypair, q) }, { .attr_id = TEE_ATTR_DH_X_BITS, .flags = TEE_TYPE_ATTR_GEN_KEY_OPT, .ops_index = ATTR_OPS_INDEX_VALUE, RAW_DATA(struct dh_keypair, xbits) }, }; #if defined(CFG_CRYPTO_HKDF) static const struct tee_cryp_obj_type_attrs tee_cryp_obj_hkdf_ikm_attrs[] = { { .attr_id = TEE_ATTR_HKDF_IKM, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_SECRET, .raw_offs = 0, .raw_size = 0 }, }; #endif #if defined(CFG_CRYPTO_CONCAT_KDF) static const struct tee_cryp_obj_type_attrs tee_cryp_obj_concat_kdf_z_attrs[] = { { .attr_id = TEE_ATTR_CONCAT_KDF_Z, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_SECRET, .raw_offs = 0, .raw_size = 0 }, }; #endif #if defined(CFG_CRYPTO_PBKDF2) static const struct tee_cryp_obj_type_attrs tee_cryp_obj_pbkdf2_passwd_attrs[] = { { .attr_id = TEE_ATTR_PBKDF2_PASSWORD, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_SECRET, .raw_offs = 0, .raw_size = 0 }, }; #endif static const struct tee_cryp_obj_type_attrs tee_cryp_obj_ecc_pub_key_attrs[] = { { .attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_X, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_public_key, x) }, { .attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_Y, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_public_key, y) }, { .attr_id = TEE_ATTR_ECC_CURVE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_VALUE, RAW_DATA(struct ecc_public_key, curve) }, }; static const struct tee_cryp_obj_type_attrs tee_cryp_obj_ecc_keypair_attrs[] = { { .attr_id = TEE_ATTR_ECC_PRIVATE_VALUE, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_keypair, d) }, { .attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_X, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_keypair, x) }, { .attr_id = TEE_ATTR_ECC_PUBLIC_VALUE_Y, .flags = TEE_TYPE_ATTR_REQUIRED, .ops_index = ATTR_OPS_INDEX_BIGNUM, RAW_DATA(struct ecc_keypair, y) }, { .attr_id = TEE_ATTR_ECC_CURVE, .flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR, .ops_index = ATTR_OPS_INDEX_VALUE, RAW_DATA(struct ecc_keypair, curve) }, }; struct tee_cryp_obj_type_props { TEE_ObjectType obj_type; uint16_t min_size; /* may not be smaller than this */ uint16_t max_size; /* may not be larger than this */ uint16_t alloc_size; /* this many bytes are allocated to hold data */ uint8_t quanta; /* may only be an multiple of this */ uint8_t num_type_attrs; const struct tee_cryp_obj_type_attrs *type_attrs; }; #define PROP(obj_type, quanta, min_size, max_size, alloc_size, type_attrs) \ { (obj_type), (min_size), (max_size), (alloc_size), (quanta), \ ARRAY_SIZE(type_attrs), (type_attrs) } static const struct tee_cryp_obj_type_props tee_cryp_obj_props[] = { PROP(TEE_TYPE_AES, 64, 128, 256, /* valid sizes 128, 192, 256 */ 256 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_DES, 56, 56, 56, /* * Valid size 56 without parity, note that we still allocate * for 64 bits since the key is supplied with parity. */ 64 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_DES3, 56, 112, 168, /* * Valid sizes 112, 168 without parity, note that we still * allocate for with space for the parity since the key is * supplied with parity. */ 192 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_MD5, 8, 64, 512, 512 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA1, 8, 80, 512, 512 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA224, 8, 112, 512, 512 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA256, 8, 192, 1024, 1024 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA384, 8, 256, 1024, 1024 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_HMAC_SHA512, 8, 256, 1024, 1024 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), PROP(TEE_TYPE_GENERIC_SECRET, 8, 0, 4096, 4096 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_secret_value_attrs), #if defined(CFG_CRYPTO_HKDF) PROP(TEE_TYPE_HKDF_IKM, 8, 0, 4096, 4096 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_hkdf_ikm_attrs), #endif #if defined(CFG_CRYPTO_CONCAT_KDF) PROP(TEE_TYPE_CONCAT_KDF_Z, 8, 0, 4096, 4096 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_concat_kdf_z_attrs), #endif #if defined(CFG_CRYPTO_PBKDF2) PROP(TEE_TYPE_PBKDF2_PASSWORD, 8, 0, 4096, 4096 / 8 + sizeof(struct tee_cryp_obj_secret), tee_cryp_obj_pbkdf2_passwd_attrs), #endif PROP(TEE_TYPE_RSA_PUBLIC_KEY, 1, 256, CFG_CORE_BIGNUM_MAX_BITS, sizeof(struct rsa_public_key), tee_cryp_obj_rsa_pub_key_attrs), PROP(TEE_TYPE_RSA_KEYPAIR, 1, 256, CFG_CORE_BIGNUM_MAX_BITS, sizeof(struct rsa_keypair), tee_cryp_obj_rsa_keypair_attrs), PROP(TEE_TYPE_DSA_PUBLIC_KEY, 64, 512, 3072, sizeof(struct dsa_public_key), tee_cryp_obj_dsa_pub_key_attrs), PROP(TEE_TYPE_DSA_KEYPAIR, 64, 512, 3072, sizeof(struct dsa_keypair), tee_cryp_obj_dsa_keypair_attrs), PROP(TEE_TYPE_DH_KEYPAIR, 1, 256, 2048, sizeof(struct dh_keypair), tee_cryp_obj_dh_keypair_attrs), PROP(TEE_TYPE_ECDSA_PUBLIC_KEY, 1, 192, 521, sizeof(struct ecc_public_key), tee_cryp_obj_ecc_pub_key_attrs), PROP(TEE_TYPE_ECDSA_KEYPAIR, 1, 192, 521, sizeof(struct ecc_keypair), tee_cryp_obj_ecc_keypair_attrs), PROP(TEE_TYPE_ECDH_PUBLIC_KEY, 1, 192, 521, sizeof(struct ecc_public_key), tee_cryp_obj_ecc_pub_key_attrs), PROP(TEE_TYPE_ECDH_KEYPAIR, 1, 192, 521, sizeof(struct ecc_keypair), tee_cryp_obj_ecc_keypair_attrs), }; struct attr_ops { TEE_Result (*from_user)(void *attr, const void *buffer, size_t size); TEE_Result (*to_user)(void *attr, struct tee_ta_session *sess, void *buffer, uint64_t *size); TEE_Result (*to_binary)(void *attr, void *data, size_t data_len, size_t *offs); bool (*from_binary)(void *attr, const void *data, size_t data_len, size_t *offs); TEE_Result (*from_obj)(void *attr, void *src_attr); void (*free)(void *attr); void (*clear)(void *attr); }; static TEE_Result op_u32_to_binary_helper(uint32_t v, uint8_t *data, size_t data_len, size_t *offs) { uint32_t field; size_t next_offs; if (ADD_OVERFLOW(*offs, sizeof(field), &next_offs)) return TEE_ERROR_OVERFLOW; if (data && next_offs <= data_len) { field = TEE_U32_TO_BIG_ENDIAN(v); memcpy(data + *offs, &field, sizeof(field)); } (*offs) = next_offs; return TEE_SUCCESS; } static bool op_u32_from_binary_helper(uint32_t *v, const uint8_t *data, size_t data_len, size_t *offs) { uint32_t field; if (!data || (*offs + sizeof(field)) > data_len) return false; memcpy(&field, data + *offs, sizeof(field)); *v = TEE_U32_FROM_BIG_ENDIAN(field); (*offs) += sizeof(field); return true; } static TEE_Result op_attr_secret_value_from_user(void *attr, const void *buffer, size_t size) { struct tee_cryp_obj_secret *key = attr; /* Data size has to fit in allocated buffer */ if (size > key->alloc_size) return TEE_ERROR_SECURITY; memcpy(key + 1, buffer, size); key->key_size = size; return TEE_SUCCESS; } static TEE_Result op_attr_secret_value_to_user(void *attr, struct tee_ta_session *sess __unused, void *buffer, uint64_t *size) { TEE_Result res; struct tee_cryp_obj_secret *key = attr; uint64_t s; uint64_t key_size; res = tee_svc_copy_from_user(&s, size, sizeof(s)); if (res != TEE_SUCCESS) return res; key_size = key->key_size; res = tee_svc_copy_to_user(size, &key_size, sizeof(key_size)); if (res != TEE_SUCCESS) return res; if (s < key->key_size || !buffer) return TEE_ERROR_SHORT_BUFFER; return tee_svc_copy_to_user(buffer, key + 1, key->key_size); } static TEE_Result op_attr_secret_value_to_binary(void *attr, void *data, size_t data_len, size_t *offs) { TEE_Result res; struct tee_cryp_obj_secret *key = attr; size_t next_offs; res = op_u32_to_binary_helper(key->key_size, data, data_len, offs); if (res != TEE_SUCCESS) return res; if (ADD_OVERFLOW(*offs, key->key_size, &next_offs)) return TEE_ERROR_OVERFLOW; if (data && next_offs <= data_len) memcpy((uint8_t *)data + *offs, key + 1, key->key_size); (*offs) = next_offs; return TEE_SUCCESS; } static bool op_attr_secret_value_from_binary(void *attr, const void *data, size_t data_len, size_t *offs) { struct tee_cryp_obj_secret *key = attr; uint32_t s; if (!op_u32_from_binary_helper(&s, data, data_len, offs)) return false; if ((*offs + s) > data_len) return false; /* Data size has to fit in allocated buffer */ if (s > key->alloc_size) return false; key->key_size = s; memcpy(key + 1, (const uint8_t *)data + *offs, s); (*offs) += s; return true; } static TEE_Result op_attr_secret_value_from_obj(void *attr, void *src_attr) { struct tee_cryp_obj_secret *key = attr; struct tee_cryp_obj_secret *src_key = src_attr; if (src_key->key_size > key->alloc_size) return TEE_ERROR_BAD_STATE; memcpy(key + 1, src_key + 1, src_key->key_size); key->key_size = src_key->key_size; return TEE_SUCCESS; } static void op_attr_secret_value_clear(void *attr) { struct tee_cryp_obj_secret *key = attr; key->key_size = 0; memset(key + 1, 0, key->alloc_size); } static TEE_Result op_attr_bignum_from_user(void *attr, const void *buffer, size_t size) { struct bignum **bn = attr; return crypto_bignum_bin2bn(buffer, size, *bn); } static TEE_Result op_attr_bignum_to_user(void *attr, struct tee_ta_session *sess, void *buffer, uint64_t *size) { TEE_Result res; struct bignum **bn = attr; uint64_t req_size; uint64_t s; res = tee_svc_copy_from_user(&s, size, sizeof(s)); if (res != TEE_SUCCESS) return res; req_size = crypto_bignum_num_bytes(*bn); res = tee_svc_copy_to_user(size, &req_size, sizeof(req_size)); if (res != TEE_SUCCESS) return res; if (!req_size) return TEE_SUCCESS; if (s < req_size || !buffer) return TEE_ERROR_SHORT_BUFFER; /* Check we can access data using supplied user mode pointer */ res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)buffer, req_size); if (res != TEE_SUCCESS) return res; /* * Write the bignum (wich raw data points to) into an array of * bytes (stored in buffer) */ crypto_bignum_bn2bin(*bn, buffer); return TEE_SUCCESS; } static TEE_Result op_attr_bignum_to_binary(void *attr, void *data, size_t data_len, size_t *offs) { TEE_Result res; struct bignum **bn = attr; uint32_t n = crypto_bignum_num_bytes(*bn); size_t next_offs; res = op_u32_to_binary_helper(n, data, data_len, offs); if (res != TEE_SUCCESS) return res; if (ADD_OVERFLOW(*offs, n, &next_offs)) return TEE_ERROR_OVERFLOW; if (data && next_offs <= data_len) crypto_bignum_bn2bin(*bn, (uint8_t *)data + *offs); (*offs) = next_offs; return TEE_SUCCESS; } static bool op_attr_bignum_from_binary(void *attr, const void *data, size_t data_len, size_t *offs) { struct bignum **bn = attr; uint32_t n; if (!op_u32_from_binary_helper(&n, data, data_len, offs)) return false; if ((*offs + n) > data_len) return false; if (crypto_bignum_bin2bn((const uint8_t *)data + *offs, n, *bn)) return false; (*offs) += n; return true; } static TEE_Result op_attr_bignum_from_obj(void *attr, void *src_attr) { struct bignum **bn = attr; struct bignum **src_bn = src_attr; crypto_bignum_copy(*bn, *src_bn); return TEE_SUCCESS; } static void op_attr_bignum_clear(void *attr) { struct bignum **bn = attr; crypto_bignum_clear(*bn); } static void op_attr_bignum_free(void *attr) { struct bignum **bn = attr; crypto_bignum_free(*bn); *bn = NULL; } static TEE_Result op_attr_value_from_user(void *attr, const void *buffer, size_t size) { uint32_t *v = attr; if (size != sizeof(uint32_t) * 2) return TEE_ERROR_GENERIC; /* "can't happen */ /* Note that only the first value is copied */ memcpy(v, buffer, sizeof(uint32_t)); return TEE_SUCCESS; } static TEE_Result op_attr_value_to_user(void *attr, struct tee_ta_session *sess __unused, void *buffer, uint64_t *size) { TEE_Result res; uint32_t *v = attr; uint64_t s; uint32_t value[2] = { *v }; uint64_t req_size = sizeof(value); res = tee_svc_copy_from_user(&s, size, sizeof(s)); if (res != TEE_SUCCESS) return res; if (s < req_size || !buffer) return TEE_ERROR_SHORT_BUFFER; return tee_svc_copy_to_user(buffer, value, req_size); } static TEE_Result op_attr_value_to_binary(void *attr, void *data, size_t data_len, size_t *offs) { uint32_t *v = attr; return op_u32_to_binary_helper(*v, data, data_len, offs); } static bool op_attr_value_from_binary(void *attr, const void *data, size_t data_len, size_t *offs) { uint32_t *v = attr; return op_u32_from_binary_helper(v, data, data_len, offs); } static TEE_Result op_attr_value_from_obj(void *attr, void *src_attr) { uint32_t *v = attr; uint32_t *src_v = src_attr; *v = *src_v; return TEE_SUCCESS; } static void op_attr_value_clear(void *attr) { uint32_t *v = attr; *v = 0; } static const struct attr_ops attr_ops[] = { [ATTR_OPS_INDEX_SECRET] = { .from_user = op_attr_secret_value_from_user, .to_user = op_attr_secret_value_to_user, .to_binary = op_attr_secret_value_to_binary, .from_binary = op_attr_secret_value_from_binary, .from_obj = op_attr_secret_value_from_obj, .free = op_attr_secret_value_clear, /* not a typo */ .clear = op_attr_secret_value_clear, }, [ATTR_OPS_INDEX_BIGNUM] = { .from_user = op_attr_bignum_from_user, .to_user = op_attr_bignum_to_user, .to_binary = op_attr_bignum_to_binary, .from_binary = op_attr_bignum_from_binary, .from_obj = op_attr_bignum_from_obj, .free = op_attr_bignum_free, .clear = op_attr_bignum_clear, }, [ATTR_OPS_INDEX_VALUE] = { .from_user = op_attr_value_from_user, .to_user = op_attr_value_to_user, .to_binary = op_attr_value_to_binary, .from_binary = op_attr_value_from_binary, .from_obj = op_attr_value_from_obj, .free = op_attr_value_clear, /* not a typo */ .clear = op_attr_value_clear, }, }; TEE_Result syscall_cryp_obj_get_info(unsigned long obj, TEE_ObjectInfo *info) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) goto exit; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) goto exit; res = tee_svc_copy_to_user(info, &o->info, sizeof(o->info)); exit: return res; } TEE_Result syscall_cryp_obj_restrict_usage(unsigned long obj, unsigned long usage) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) goto exit; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) goto exit; o->info.objectUsage &= usage; exit: return res; } static int tee_svc_cryp_obj_find_type_attr_idx( uint32_t attr_id, const struct tee_cryp_obj_type_props *type_props) { size_t n; for (n = 0; n < type_props->num_type_attrs; n++) { if (attr_id == type_props->type_attrs[n].attr_id) return n; } return -1; } static const struct tee_cryp_obj_type_props *tee_svc_find_type_props( TEE_ObjectType obj_type) { size_t n; for (n = 0; n < ARRAY_SIZE(tee_cryp_obj_props); n++) { if (tee_cryp_obj_props[n].obj_type == obj_type) return tee_cryp_obj_props + n; } return NULL; } /* Set an attribute on an object */ static void set_attribute(struct tee_obj *o, const struct tee_cryp_obj_type_props *props, uint32_t attr) { int idx = tee_svc_cryp_obj_find_type_attr_idx(attr, props); if (idx < 0) return; o->have_attrs |= BIT(idx); } /* Get an attribute on an object */ static uint32_t get_attribute(const struct tee_obj *o, const struct tee_cryp_obj_type_props *props, uint32_t attr) { int idx = tee_svc_cryp_obj_find_type_attr_idx(attr, props); if (idx < 0) return 0; return o->have_attrs & BIT(idx); } TEE_Result syscall_cryp_obj_get_attr(unsigned long obj, unsigned long attr_id, void *buffer, uint64_t *size) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; const struct tee_cryp_obj_type_props *type_props; int idx; const struct attr_ops *ops; void *attr; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return TEE_ERROR_ITEM_NOT_FOUND; /* Check that the object is initialized */ if (!(o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED)) return TEE_ERROR_BAD_PARAMETERS; /* Check that getting the attribute is allowed */ if (!(attr_id & TEE_ATTR_BIT_PROTECTED) && !(o->info.objectUsage & TEE_USAGE_EXTRACTABLE)) return TEE_ERROR_BAD_PARAMETERS; type_props = tee_svc_find_type_props(o->info.objectType); if (!type_props) { /* Unknown object type, "can't happen" */ return TEE_ERROR_BAD_STATE; } idx = tee_svc_cryp_obj_find_type_attr_idx(attr_id, type_props); if ((idx < 0) || ((o->have_attrs & (1 << idx)) == 0)) return TEE_ERROR_ITEM_NOT_FOUND; ops = attr_ops + type_props->type_attrs[idx].ops_index; attr = (uint8_t *)o->attr + type_props->type_attrs[idx].raw_offs; return ops->to_user(attr, sess, buffer, size); } void tee_obj_attr_free(struct tee_obj *o) { const struct tee_cryp_obj_type_props *tp; size_t n; if (!o->attr) return; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return; for (n = 0; n < tp->num_type_attrs; n++) { const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n; attr_ops[ta->ops_index].free((uint8_t *)o->attr + ta->raw_offs); } } void tee_obj_attr_clear(struct tee_obj *o) { const struct tee_cryp_obj_type_props *tp; size_t n; if (!o->attr) return; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return; for (n = 0; n < tp->num_type_attrs; n++) { const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n; attr_ops[ta->ops_index].clear((uint8_t *)o->attr + ta->raw_offs); } } TEE_Result tee_obj_attr_to_binary(struct tee_obj *o, void *data, size_t *data_len) { const struct tee_cryp_obj_type_props *tp; size_t n; size_t offs = 0; size_t len = data ? *data_len : 0; TEE_Result res; if (o->info.objectType == TEE_TYPE_DATA) { *data_len = 0; return TEE_SUCCESS; /* pure data object */ } if (!o->attr) return TEE_ERROR_BAD_STATE; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return TEE_ERROR_BAD_STATE; for (n = 0; n < tp->num_type_attrs; n++) { const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n; void *attr = (uint8_t *)o->attr + ta->raw_offs; res = attr_ops[ta->ops_index].to_binary(attr, data, len, &offs); if (res != TEE_SUCCESS) return res; } *data_len = offs; if (data && offs > len) return TEE_ERROR_SHORT_BUFFER; return TEE_SUCCESS; } TEE_Result tee_obj_attr_from_binary(struct tee_obj *o, const void *data, size_t data_len) { const struct tee_cryp_obj_type_props *tp; size_t n; size_t offs = 0; if (o->info.objectType == TEE_TYPE_DATA) return TEE_SUCCESS; /* pure data object */ if (!o->attr) return TEE_ERROR_BAD_STATE; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return TEE_ERROR_BAD_STATE; for (n = 0; n < tp->num_type_attrs; n++) { const struct tee_cryp_obj_type_attrs *ta = tp->type_attrs + n; void *attr = (uint8_t *)o->attr + ta->raw_offs; if (!attr_ops[ta->ops_index].from_binary(attr, data, data_len, &offs)) return TEE_ERROR_CORRUPT_OBJECT; } return TEE_SUCCESS; } TEE_Result tee_obj_attr_copy_from(struct tee_obj *o, const struct tee_obj *src) { TEE_Result res; const struct tee_cryp_obj_type_props *tp; const struct tee_cryp_obj_type_attrs *ta; size_t n; uint32_t have_attrs = 0; void *attr; void *src_attr; if (o->info.objectType == TEE_TYPE_DATA) return TEE_SUCCESS; /* pure data object */ if (!o->attr) return TEE_ERROR_BAD_STATE; tp = tee_svc_find_type_props(o->info.objectType); if (!tp) return TEE_ERROR_BAD_STATE; if (o->info.objectType == src->info.objectType) { have_attrs = src->have_attrs; for (n = 0; n < tp->num_type_attrs; n++) { ta = tp->type_attrs + n; attr = (uint8_t *)o->attr + ta->raw_offs; src_attr = (uint8_t *)src->attr + ta->raw_offs; res = attr_ops[ta->ops_index].from_obj(attr, src_attr); if (res != TEE_SUCCESS) return res; } } else { const struct tee_cryp_obj_type_props *tp_src; int idx; if (o->info.objectType == TEE_TYPE_RSA_PUBLIC_KEY) { if (src->info.objectType != TEE_TYPE_RSA_KEYPAIR) return TEE_ERROR_BAD_PARAMETERS; } else if (o->info.objectType == TEE_TYPE_DSA_PUBLIC_KEY) { if (src->info.objectType != TEE_TYPE_DSA_KEYPAIR) return TEE_ERROR_BAD_PARAMETERS; } else if (o->info.objectType == TEE_TYPE_ECDSA_PUBLIC_KEY) { if (src->info.objectType != TEE_TYPE_ECDSA_KEYPAIR) return TEE_ERROR_BAD_PARAMETERS; } else if (o->info.objectType == TEE_TYPE_ECDH_PUBLIC_KEY) { if (src->info.objectType != TEE_TYPE_ECDH_KEYPAIR) return TEE_ERROR_BAD_PARAMETERS; } else { return TEE_ERROR_BAD_PARAMETERS; } tp_src = tee_svc_find_type_props(src->info.objectType); if (!tp_src) return TEE_ERROR_BAD_STATE; have_attrs = BIT32(tp->num_type_attrs) - 1; for (n = 0; n < tp->num_type_attrs; n++) { ta = tp->type_attrs + n; idx = tee_svc_cryp_obj_find_type_attr_idx(ta->attr_id, tp_src); if (idx < 0) return TEE_ERROR_BAD_STATE; attr = (uint8_t *)o->attr + ta->raw_offs; src_attr = (uint8_t *)src->attr + tp_src->type_attrs[idx].raw_offs; res = attr_ops[ta->ops_index].from_obj(attr, src_attr); if (res != TEE_SUCCESS) return res; } } o->have_attrs = have_attrs; return TEE_SUCCESS; } TEE_Result tee_obj_set_type(struct tee_obj *o, uint32_t obj_type, size_t max_key_size) { TEE_Result res = TEE_SUCCESS; const struct tee_cryp_obj_type_props *type_props; /* Can only set type for newly allocated objs */ if (o->attr) return TEE_ERROR_BAD_STATE; /* * Verify that maxKeySize is supported and find out how * much should be allocated. */ if (obj_type == TEE_TYPE_DATA) { if (max_key_size) return TEE_ERROR_NOT_SUPPORTED; } else { /* Find description of object */ type_props = tee_svc_find_type_props(obj_type); if (!type_props) return TEE_ERROR_NOT_SUPPORTED; /* Check that maxKeySize follows restrictions */ if (max_key_size % type_props->quanta != 0) return TEE_ERROR_NOT_SUPPORTED; if (max_key_size < type_props->min_size) return TEE_ERROR_NOT_SUPPORTED; if (max_key_size > type_props->max_size) return TEE_ERROR_NOT_SUPPORTED; o->attr = calloc(1, type_props->alloc_size); if (!o->attr) return TEE_ERROR_OUT_OF_MEMORY; } /* If we have a key structure, pre-allocate the bignums inside */ switch (obj_type) { case TEE_TYPE_RSA_PUBLIC_KEY: res = crypto_acipher_alloc_rsa_public_key(o->attr, max_key_size); break; case TEE_TYPE_RSA_KEYPAIR: res = crypto_acipher_alloc_rsa_keypair(o->attr, max_key_size); break; case TEE_TYPE_DSA_PUBLIC_KEY: res = crypto_acipher_alloc_dsa_public_key(o->attr, max_key_size); break; case TEE_TYPE_DSA_KEYPAIR: res = crypto_acipher_alloc_dsa_keypair(o->attr, max_key_size); break; case TEE_TYPE_DH_KEYPAIR: res = crypto_acipher_alloc_dh_keypair(o->attr, max_key_size); break; case TEE_TYPE_ECDSA_PUBLIC_KEY: case TEE_TYPE_ECDH_PUBLIC_KEY: res = crypto_acipher_alloc_ecc_public_key(o->attr, max_key_size); break; case TEE_TYPE_ECDSA_KEYPAIR: case TEE_TYPE_ECDH_KEYPAIR: res = crypto_acipher_alloc_ecc_keypair(o->attr, max_key_size); break; default: if (obj_type != TEE_TYPE_DATA) { struct tee_cryp_obj_secret *key = o->attr; key->alloc_size = type_props->alloc_size - sizeof(*key); } break; } if (res != TEE_SUCCESS) return res; o->info.objectType = obj_type; o->info.maxKeySize = max_key_size; o->info.objectUsage = TEE_USAGE_DEFAULT; return TEE_SUCCESS; } TEE_Result syscall_cryp_obj_alloc(unsigned long obj_type, unsigned long max_key_size, uint32_t *obj) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; if (obj_type == TEE_TYPE_DATA) return TEE_ERROR_NOT_SUPPORTED; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; o = tee_obj_alloc(); if (!o) return TEE_ERROR_OUT_OF_MEMORY; res = tee_obj_set_type(o, obj_type, max_key_size); if (res != TEE_SUCCESS) { tee_obj_free(o); return res; } tee_obj_add(to_user_ta_ctx(sess->ctx), o); res = tee_svc_copy_kaddr_to_uref(obj, o); if (res != TEE_SUCCESS) tee_obj_close(to_user_ta_ctx(sess->ctx), o); return res; } TEE_Result syscall_cryp_obj_close(unsigned long obj) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; /* * If it's busy it's used by an operation, a client should never have * this handle. */ if (o->busy) return TEE_ERROR_ITEM_NOT_FOUND; tee_obj_close(to_user_ta_ctx(sess->ctx), o); return TEE_SUCCESS; } TEE_Result syscall_cryp_obj_reset(unsigned long obj) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) == 0) { tee_obj_attr_clear(o); o->info.keySize = 0; o->info.objectUsage = TEE_USAGE_DEFAULT; } else { return TEE_ERROR_BAD_PARAMETERS; } /* the object is no more initialized */ o->info.handleFlags &= ~TEE_HANDLE_FLAG_INITIALIZED; return TEE_SUCCESS; } static TEE_Result copy_in_attrs(struct user_ta_ctx *utc, const struct utee_attribute *usr_attrs, uint32_t attr_count, TEE_Attribute *attrs) { TEE_Result res; uint32_t n; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)usr_attrs, attr_count * sizeof(struct utee_attribute)); if (res != TEE_SUCCESS) return res; for (n = 0; n < attr_count; n++) { attrs[n].attributeID = usr_attrs[n].attribute_id; if (attrs[n].attributeID & TEE_ATTR_BIT_VALUE) { attrs[n].content.value.a = usr_attrs[n].a; attrs[n].content.value.b = usr_attrs[n].b; } else { uintptr_t buf = usr_attrs[n].a; size_t len = usr_attrs[n].b; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, buf, len); if (res != TEE_SUCCESS) return res; attrs[n].content.ref.buffer = (void *)buf; attrs[n].content.ref.length = len; } } return TEE_SUCCESS; } enum attr_usage { ATTR_USAGE_POPULATE, ATTR_USAGE_GENERATE_KEY }; static TEE_Result tee_svc_cryp_check_attr(enum attr_usage usage, const struct tee_cryp_obj_type_props *type_props, const TEE_Attribute *attrs, uint32_t attr_count) { uint32_t required_flag; uint32_t opt_flag; bool all_opt_needed; uint32_t req_attrs = 0; uint32_t opt_grp_attrs = 0; uint32_t attrs_found = 0; size_t n; uint32_t bit; uint32_t flags; int idx; if (usage == ATTR_USAGE_POPULATE) { required_flag = TEE_TYPE_ATTR_REQUIRED; opt_flag = TEE_TYPE_ATTR_OPTIONAL_GROUP; all_opt_needed = true; } else { required_flag = TEE_TYPE_ATTR_GEN_KEY_REQ; opt_flag = TEE_TYPE_ATTR_GEN_KEY_OPT; all_opt_needed = false; } /* * First find out which attributes are required and which belong to * the optional group */ for (n = 0; n < type_props->num_type_attrs; n++) { bit = 1 << n; flags = type_props->type_attrs[n].flags; if (flags & required_flag) req_attrs |= bit; else if (flags & opt_flag) opt_grp_attrs |= bit; } /* * Verify that all required attributes are in place and * that the same attribute isn't repeated. */ for (n = 0; n < attr_count; n++) { idx = tee_svc_cryp_obj_find_type_attr_idx( attrs[n].attributeID, type_props); /* attribute not defined in current object type */ if (idx < 0) return TEE_ERROR_ITEM_NOT_FOUND; bit = 1 << idx; /* attribute not repeated */ if ((attrs_found & bit) != 0) return TEE_ERROR_ITEM_NOT_FOUND; attrs_found |= bit; } /* Required attribute missing */ if ((attrs_found & req_attrs) != req_attrs) return TEE_ERROR_ITEM_NOT_FOUND; /* * If the flag says that "if one of the optional attributes are included * all of them has to be included" this must be checked. */ if (all_opt_needed && (attrs_found & opt_grp_attrs) != 0 && (attrs_found & opt_grp_attrs) != opt_grp_attrs) return TEE_ERROR_ITEM_NOT_FOUND; return TEE_SUCCESS; } static TEE_Result get_ec_key_size(uint32_t curve, size_t *key_size) { switch (curve) { case TEE_ECC_CURVE_NIST_P192: *key_size = 192; break; case TEE_ECC_CURVE_NIST_P224: *key_size = 224; break; case TEE_ECC_CURVE_NIST_P256: *key_size = 256; break; case TEE_ECC_CURVE_NIST_P384: *key_size = 384; break; case TEE_ECC_CURVE_NIST_P521: *key_size = 521; break; default: return TEE_ERROR_NOT_SUPPORTED; } return TEE_SUCCESS; } static TEE_Result tee_svc_cryp_obj_populate_type( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, const TEE_Attribute *attrs, uint32_t attr_count) { TEE_Result res; uint32_t have_attrs = 0; size_t obj_size = 0; size_t n; int idx; const struct attr_ops *ops; void *attr; for (n = 0; n < attr_count; n++) { idx = tee_svc_cryp_obj_find_type_attr_idx( attrs[n].attributeID, type_props); /* attribute not defined in current object type */ if (idx < 0) return TEE_ERROR_ITEM_NOT_FOUND; have_attrs |= BIT32(idx); ops = attr_ops + type_props->type_attrs[idx].ops_index; attr = (uint8_t *)o->attr + type_props->type_attrs[idx].raw_offs; if (attrs[n].attributeID & TEE_ATTR_BIT_VALUE) res = ops->from_user(attr, &attrs[n].content.value, sizeof(attrs[n].content.value)); else res = ops->from_user(attr, attrs[n].content.ref.buffer, attrs[n].content.ref.length); if (res != TEE_SUCCESS) return res; /* * First attr_idx signifies the attribute that gives the size * of the object */ if (type_props->type_attrs[idx].flags & TEE_TYPE_ATTR_SIZE_INDICATOR) { /* * For ECDSA/ECDH we need to translate curve into * object size */ if (attrs[n].attributeID == TEE_ATTR_ECC_CURVE) { res = get_ec_key_size(attrs[n].content.value.a, &obj_size); if (res != TEE_SUCCESS) return res; } else { obj_size += (attrs[n].content.ref.length * 8); } } } /* * We have to do it like this because the parity bits aren't counted * when telling the size of the key in bits. */ if (o->info.objectType == TEE_TYPE_DES || o->info.objectType == TEE_TYPE_DES3) obj_size -= obj_size / 8; /* Exclude parity in size of key */ o->have_attrs = have_attrs; o->info.keySize = obj_size; return TEE_SUCCESS; } TEE_Result syscall_cryp_obj_populate(unsigned long obj, struct utee_attribute *usr_attrs, unsigned long attr_count) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *o; const struct tee_cryp_obj_type_props *type_props; TEE_Attribute *attrs = NULL; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; /* Must be a transient object */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0) return TEE_ERROR_BAD_PARAMETERS; /* Must not be initialized already */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0) return TEE_ERROR_BAD_PARAMETERS; type_props = tee_svc_find_type_props(o->info.objectType); if (!type_props) return TEE_ERROR_NOT_IMPLEMENTED; size_t alloc_size = 0; if (MUL_OVERFLOW(sizeof(TEE_Attribute), attr_count, &alloc_size)) return TEE_ERROR_OVERFLOW; attrs = malloc(alloc_size); if (!attrs) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_attrs, attr_count, attrs); if (res != TEE_SUCCESS) goto out; res = tee_svc_cryp_check_attr(ATTR_USAGE_POPULATE, type_props, attrs, attr_count); if (res != TEE_SUCCESS) goto out; res = tee_svc_cryp_obj_populate_type(o, type_props, attrs, attr_count); if (res == TEE_SUCCESS) o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; out: free(attrs); return res; } TEE_Result syscall_cryp_obj_copy(unsigned long dst, unsigned long src) { TEE_Result res; struct tee_ta_session *sess; struct tee_obj *dst_o; struct tee_obj *src_o; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(dst), &dst_o); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(src), &src_o); if (res != TEE_SUCCESS) return res; if ((src_o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; if ((dst_o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0) return TEE_ERROR_BAD_PARAMETERS; if ((dst_o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0) return TEE_ERROR_BAD_PARAMETERS; res = tee_obj_attr_copy_from(dst_o, src_o); if (res != TEE_SUCCESS) return res; dst_o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; dst_o->info.keySize = src_o->info.keySize; dst_o->info.objectUsage = src_o->info.objectUsage; return TEE_SUCCESS; } static TEE_Result tee_svc_obj_generate_key_rsa( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, uint32_t key_size, const TEE_Attribute *params, uint32_t param_count) { TEE_Result res; struct rsa_keypair *key = o->attr; uint32_t e = TEE_U32_TO_BIG_ENDIAN(65537); /* Copy the present attributes into the obj before starting */ res = tee_svc_cryp_obj_populate_type(o, type_props, params, param_count); if (res != TEE_SUCCESS) return res; if (!get_attribute(o, type_props, TEE_ATTR_RSA_PUBLIC_EXPONENT)) crypto_bignum_bin2bn((const uint8_t *)&e, sizeof(e), key->e); res = crypto_acipher_gen_rsa_key(key, key_size); if (res != TEE_SUCCESS) return res; /* Set bits for all known attributes for this object type */ o->have_attrs = (1 << type_props->num_type_attrs) - 1; return TEE_SUCCESS; } static TEE_Result tee_svc_obj_generate_key_dsa( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, uint32_t key_size) { TEE_Result res; res = crypto_acipher_gen_dsa_key(o->attr, key_size); if (res != TEE_SUCCESS) return res; /* Set bits for all known attributes for this object type */ o->have_attrs = (1 << type_props->num_type_attrs) - 1; return TEE_SUCCESS; } static TEE_Result tee_svc_obj_generate_key_dh( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, uint32_t key_size __unused, const TEE_Attribute *params, uint32_t param_count) { TEE_Result res; struct dh_keypair *tee_dh_key; struct bignum *dh_q = NULL; uint32_t dh_xbits = 0; /* Copy the present attributes into the obj before starting */ res = tee_svc_cryp_obj_populate_type(o, type_props, params, param_count); if (res != TEE_SUCCESS) return res; tee_dh_key = (struct dh_keypair *)o->attr; if (get_attribute(o, type_props, TEE_ATTR_DH_SUBPRIME)) dh_q = tee_dh_key->q; if (get_attribute(o, type_props, TEE_ATTR_DH_X_BITS)) dh_xbits = tee_dh_key->xbits; res = crypto_acipher_gen_dh_key(tee_dh_key, dh_q, dh_xbits); if (res != TEE_SUCCESS) return res; /* Set bits for the generated public and private key */ set_attribute(o, type_props, TEE_ATTR_DH_PUBLIC_VALUE); set_attribute(o, type_props, TEE_ATTR_DH_PRIVATE_VALUE); set_attribute(o, type_props, TEE_ATTR_DH_X_BITS); return TEE_SUCCESS; } static TEE_Result tee_svc_obj_generate_key_ecc( struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props, uint32_t key_size __unused, const TEE_Attribute *params, uint32_t param_count) { TEE_Result res; struct ecc_keypair *tee_ecc_key; /* Copy the present attributes into the obj before starting */ res = tee_svc_cryp_obj_populate_type(o, type_props, params, param_count); if (res != TEE_SUCCESS) return res; tee_ecc_key = (struct ecc_keypair *)o->attr; res = crypto_acipher_gen_ecc_key(tee_ecc_key); if (res != TEE_SUCCESS) return res; /* Set bits for the generated public and private key */ set_attribute(o, type_props, TEE_ATTR_ECC_PRIVATE_VALUE); set_attribute(o, type_props, TEE_ATTR_ECC_PUBLIC_VALUE_X); set_attribute(o, type_props, TEE_ATTR_ECC_PUBLIC_VALUE_Y); set_attribute(o, type_props, TEE_ATTR_ECC_CURVE); return TEE_SUCCESS; } TEE_Result syscall_obj_generate_key(unsigned long obj, unsigned long key_size, const struct utee_attribute *usr_params, unsigned long param_count) { TEE_Result res; struct tee_ta_session *sess; const struct tee_cryp_obj_type_props *type_props; struct tee_obj *o; struct tee_cryp_obj_secret *key; size_t byte_size; TEE_Attribute *params = NULL; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), tee_svc_uref_to_vaddr(obj), &o); if (res != TEE_SUCCESS) return res; /* Must be a transient object */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0) return TEE_ERROR_BAD_STATE; /* Must not be initialized already */ if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0) return TEE_ERROR_BAD_STATE; /* Find description of object */ type_props = tee_svc_find_type_props(o->info.objectType); if (!type_props) return TEE_ERROR_NOT_SUPPORTED; /* Check that maxKeySize follows restrictions */ if (key_size % type_props->quanta != 0) return TEE_ERROR_NOT_SUPPORTED; if (key_size < type_props->min_size) return TEE_ERROR_NOT_SUPPORTED; if (key_size > type_props->max_size) return TEE_ERROR_NOT_SUPPORTED; size_t alloc_size = 0; if (MUL_OVERFLOW(sizeof(TEE_Attribute), param_count, &alloc_size)) return TEE_ERROR_OVERFLOW; params = malloc(alloc_size); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_params, param_count, params); if (res != TEE_SUCCESS) goto out; res = tee_svc_cryp_check_attr(ATTR_USAGE_GENERATE_KEY, type_props, params, param_count); if (res != TEE_SUCCESS) goto out; switch (o->info.objectType) { case TEE_TYPE_AES: case TEE_TYPE_DES: case TEE_TYPE_DES3: case TEE_TYPE_HMAC_MD5: case TEE_TYPE_HMAC_SHA1: case TEE_TYPE_HMAC_SHA224: case TEE_TYPE_HMAC_SHA256: case TEE_TYPE_HMAC_SHA384: case TEE_TYPE_HMAC_SHA512: case TEE_TYPE_GENERIC_SECRET: byte_size = key_size / 8; /* * We have to do it like this because the parity bits aren't * counted when telling the size of the key in bits. */ if (o->info.objectType == TEE_TYPE_DES || o->info.objectType == TEE_TYPE_DES3) { byte_size = (key_size + key_size / 7) / 8; } key = (struct tee_cryp_obj_secret *)o->attr; if (byte_size > key->alloc_size) { res = TEE_ERROR_EXCESS_DATA; goto out; } res = crypto_rng_read((void *)(key + 1), byte_size); if (res != TEE_SUCCESS) goto out; key->key_size = byte_size; /* Set bits for all known attributes for this object type */ o->have_attrs = (1 << type_props->num_type_attrs) - 1; break; case TEE_TYPE_RSA_KEYPAIR: res = tee_svc_obj_generate_key_rsa(o, type_props, key_size, params, param_count); if (res != TEE_SUCCESS) goto out; break; case TEE_TYPE_DSA_KEYPAIR: res = tee_svc_obj_generate_key_dsa(o, type_props, key_size); if (res != TEE_SUCCESS) goto out; break; case TEE_TYPE_DH_KEYPAIR: res = tee_svc_obj_generate_key_dh(o, type_props, key_size, params, param_count); if (res != TEE_SUCCESS) goto out; break; case TEE_TYPE_ECDSA_KEYPAIR: case TEE_TYPE_ECDH_KEYPAIR: res = tee_svc_obj_generate_key_ecc(o, type_props, key_size, params, param_count); if (res != TEE_SUCCESS) goto out; break; default: res = TEE_ERROR_BAD_FORMAT; } out: free(params); if (res == TEE_SUCCESS) { o->info.keySize = key_size; o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; } return res; } static TEE_Result tee_svc_cryp_get_state(struct tee_ta_session *sess, uint32_t state_id, struct tee_cryp_state **state) { struct tee_cryp_state *s; struct user_ta_ctx *utc = to_user_ta_ctx(sess->ctx); TAILQ_FOREACH(s, &utc->cryp_states, link) { if (state_id == (vaddr_t)s) { *state = s; return TEE_SUCCESS; } } return TEE_ERROR_BAD_PARAMETERS; } static void cryp_state_free(struct user_ta_ctx *utc, struct tee_cryp_state *cs) { struct tee_obj *o; if (tee_obj_get(utc, cs->key1, &o) == TEE_SUCCESS) tee_obj_close(utc, o); if (tee_obj_get(utc, cs->key2, &o) == TEE_SUCCESS) tee_obj_close(utc, o); TAILQ_REMOVE(&utc->cryp_states, cs, link); if (cs->ctx_finalize != NULL) cs->ctx_finalize(cs->ctx, cs->algo); switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_CIPHER: crypto_cipher_free_ctx(cs->ctx, cs->algo); break; case TEE_OPERATION_AE: crypto_authenc_free_ctx(cs->ctx, cs->algo); break; case TEE_OPERATION_DIGEST: crypto_hash_free_ctx(cs->ctx, cs->algo); break; case TEE_OPERATION_MAC: crypto_mac_free_ctx(cs->ctx, cs->algo); break; default: assert(!cs->ctx); } free(cs); } static TEE_Result tee_svc_cryp_check_key_type(const struct tee_obj *o, uint32_t algo, TEE_OperationMode mode) { uint32_t req_key_type; uint32_t req_key_type2 = 0; switch (TEE_ALG_GET_MAIN_ALG(algo)) { case TEE_MAIN_ALGO_MD5: req_key_type = TEE_TYPE_HMAC_MD5; break; case TEE_MAIN_ALGO_SHA1: req_key_type = TEE_TYPE_HMAC_SHA1; break; case TEE_MAIN_ALGO_SHA224: req_key_type = TEE_TYPE_HMAC_SHA224; break; case TEE_MAIN_ALGO_SHA256: req_key_type = TEE_TYPE_HMAC_SHA256; break; case TEE_MAIN_ALGO_SHA384: req_key_type = TEE_TYPE_HMAC_SHA384; break; case TEE_MAIN_ALGO_SHA512: req_key_type = TEE_TYPE_HMAC_SHA512; break; case TEE_MAIN_ALGO_AES: req_key_type = TEE_TYPE_AES; break; case TEE_MAIN_ALGO_DES: req_key_type = TEE_TYPE_DES; break; case TEE_MAIN_ALGO_DES3: req_key_type = TEE_TYPE_DES3; break; case TEE_MAIN_ALGO_RSA: req_key_type = TEE_TYPE_RSA_KEYPAIR; if (mode == TEE_MODE_ENCRYPT || mode == TEE_MODE_VERIFY) req_key_type2 = TEE_TYPE_RSA_PUBLIC_KEY; break; case TEE_MAIN_ALGO_DSA: req_key_type = TEE_TYPE_DSA_KEYPAIR; if (mode == TEE_MODE_ENCRYPT || mode == TEE_MODE_VERIFY) req_key_type2 = TEE_TYPE_DSA_PUBLIC_KEY; break; case TEE_MAIN_ALGO_DH: req_key_type = TEE_TYPE_DH_KEYPAIR; break; case TEE_MAIN_ALGO_ECDSA: req_key_type = TEE_TYPE_ECDSA_KEYPAIR; if (mode == TEE_MODE_VERIFY) req_key_type2 = TEE_TYPE_ECDSA_PUBLIC_KEY; break; case TEE_MAIN_ALGO_ECDH: req_key_type = TEE_TYPE_ECDH_KEYPAIR; break; #if defined(CFG_CRYPTO_HKDF) case TEE_MAIN_ALGO_HKDF: req_key_type = TEE_TYPE_HKDF_IKM; break; #endif #if defined(CFG_CRYPTO_CONCAT_KDF) case TEE_MAIN_ALGO_CONCAT_KDF: req_key_type = TEE_TYPE_CONCAT_KDF_Z; break; #endif #if defined(CFG_CRYPTO_PBKDF2) case TEE_MAIN_ALGO_PBKDF2: req_key_type = TEE_TYPE_PBKDF2_PASSWORD; break; #endif default: return TEE_ERROR_BAD_PARAMETERS; } if (req_key_type != o->info.objectType && req_key_type2 != o->info.objectType) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } TEE_Result syscall_cryp_state_alloc(unsigned long algo, unsigned long mode, unsigned long key1, unsigned long key2, uint32_t *state) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; struct tee_obj *o1 = NULL; struct tee_obj *o2 = NULL; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); if (key1 != 0) { res = tee_obj_get(utc, tee_svc_uref_to_vaddr(key1), &o1); if (res != TEE_SUCCESS) return res; if (o1->busy) return TEE_ERROR_BAD_PARAMETERS; res = tee_svc_cryp_check_key_type(o1, algo, mode); if (res != TEE_SUCCESS) return res; } if (key2 != 0) { res = tee_obj_get(utc, tee_svc_uref_to_vaddr(key2), &o2); if (res != TEE_SUCCESS) return res; if (o2->busy) return TEE_ERROR_BAD_PARAMETERS; res = tee_svc_cryp_check_key_type(o2, algo, mode); if (res != TEE_SUCCESS) return res; } cs = calloc(1, sizeof(struct tee_cryp_state)); if (!cs) return TEE_ERROR_OUT_OF_MEMORY; TAILQ_INSERT_TAIL(&utc->cryp_states, cs, link); cs->algo = algo; cs->mode = mode; switch (TEE_ALG_GET_CLASS(algo)) { case TEE_OPERATION_EXTENSION: #ifdef CFG_CRYPTO_RSASSA_NA1 if (algo == TEE_ALG_RSASSA_PKCS1_V1_5) goto rsassa_na1; #endif res = TEE_ERROR_NOT_SUPPORTED; break; case TEE_OPERATION_CIPHER: if ((algo == TEE_ALG_AES_XTS && (key1 == 0 || key2 == 0)) || (algo != TEE_ALG_AES_XTS && (key1 == 0 || key2 != 0))) { res = TEE_ERROR_BAD_PARAMETERS; } else { res = crypto_cipher_alloc_ctx(&cs->ctx, algo); if (res != TEE_SUCCESS) break; } break; case TEE_OPERATION_AE: if (key1 == 0 || key2 != 0) { res = TEE_ERROR_BAD_PARAMETERS; } else { res = crypto_authenc_alloc_ctx(&cs->ctx, algo); if (res != TEE_SUCCESS) break; } break; case TEE_OPERATION_MAC: if (key1 == 0 || key2 != 0) { res = TEE_ERROR_BAD_PARAMETERS; } else { res = crypto_mac_alloc_ctx(&cs->ctx, algo); if (res != TEE_SUCCESS) break; } break; case TEE_OPERATION_DIGEST: if (key1 != 0 || key2 != 0) { res = TEE_ERROR_BAD_PARAMETERS; } else { res = crypto_hash_alloc_ctx(&cs->ctx, algo); if (res != TEE_SUCCESS) break; } break; case TEE_OPERATION_ASYMMETRIC_CIPHER: case TEE_OPERATION_ASYMMETRIC_SIGNATURE: rsassa_na1: __maybe_unused if (key1 == 0 || key2 != 0) res = TEE_ERROR_BAD_PARAMETERS; break; case TEE_OPERATION_KEY_DERIVATION: if (key1 == 0 || key2 != 0) res = TEE_ERROR_BAD_PARAMETERS; break; default: res = TEE_ERROR_NOT_SUPPORTED; break; } if (res != TEE_SUCCESS) goto out; res = tee_svc_copy_kaddr_to_uref(state, cs); if (res != TEE_SUCCESS) goto out; /* Register keys */ if (o1 != NULL) { o1->busy = true; cs->key1 = (vaddr_t)o1; } if (o2 != NULL) { o2->busy = true; cs->key2 = (vaddr_t)o2; } out: if (res != TEE_SUCCESS) cryp_state_free(utc, cs); return res; } TEE_Result syscall_cryp_state_copy(unsigned long dst, unsigned long src) { TEE_Result res; struct tee_cryp_state *cs_dst; struct tee_cryp_state *cs_src; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(dst), &cs_dst); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(src), &cs_src); if (res != TEE_SUCCESS) return res; if (cs_dst->algo != cs_src->algo || cs_dst->mode != cs_src->mode) return TEE_ERROR_BAD_PARAMETERS; switch (TEE_ALG_GET_CLASS(cs_src->algo)) { case TEE_OPERATION_CIPHER: crypto_cipher_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo); break; case TEE_OPERATION_AE: crypto_authenc_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo); break; case TEE_OPERATION_DIGEST: crypto_hash_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo); break; case TEE_OPERATION_MAC: crypto_mac_copy_state(cs_dst->ctx, cs_src->ctx, cs_src->algo); break; default: return TEE_ERROR_BAD_STATE; } return TEE_SUCCESS; } void tee_svc_cryp_free_states(struct user_ta_ctx *utc) { struct tee_cryp_state_head *states = &utc->cryp_states; while (!TAILQ_EMPTY(states)) cryp_state_free(utc, TAILQ_FIRST(states)); } TEE_Result syscall_cryp_state_free(unsigned long state) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; cryp_state_free(to_user_ta_ctx(sess->ctx), cs); return TEE_SUCCESS; } TEE_Result syscall_hash_init(unsigned long state, const void *iv __maybe_unused, size_t iv_len __maybe_unused) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_DIGEST: res = crypto_hash_init(cs->ctx, cs->algo); if (res != TEE_SUCCESS) return res; break; case TEE_OPERATION_MAC: { struct tee_obj *o; struct tee_cryp_obj_secret *key; res = tee_obj_get(to_user_ta_ctx(sess->ctx), cs->key1, &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; key = (struct tee_cryp_obj_secret *)o->attr; res = crypto_mac_init(cs->ctx, cs->algo, (void *)(key + 1), key->key_size); if (res != TEE_SUCCESS) return res; break; } default: return TEE_ERROR_BAD_PARAMETERS; } return TEE_SUCCESS; } TEE_Result syscall_hash_update(unsigned long state, const void *chunk, size_t chunk_size) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; /* No data, but size provided isn't valid parameters. */ if (!chunk && chunk_size) return TEE_ERROR_BAD_PARAMETERS; /* Zero length hash is valid, but nothing we need to do. */ if (!chunk_size) return TEE_SUCCESS; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)chunk, chunk_size); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_DIGEST: res = crypto_hash_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; break; case TEE_OPERATION_MAC: res = crypto_mac_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; break; default: return TEE_ERROR_BAD_PARAMETERS; } return TEE_SUCCESS; } TEE_Result syscall_hash_final(unsigned long state, const void *chunk, size_t chunk_size, void *hash, uint64_t *hash_len) { TEE_Result res, res2; size_t hash_size; uint64_t hlen; struct tee_cryp_state *cs; struct tee_ta_session *sess; /* No data, but size provided isn't valid parameters. */ if (!chunk && chunk_size) return TEE_ERROR_BAD_PARAMETERS; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)chunk, chunk_size); if (res != TEE_SUCCESS) return res; res = tee_svc_copy_from_user(&hlen, hash_len, sizeof(hlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)hash, hlen); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_DIGEST: res = tee_hash_get_digest_size(cs->algo, &hash_size); if (res != TEE_SUCCESS) return res; if (*hash_len < hash_size) { res = TEE_ERROR_SHORT_BUFFER; goto out; } if (chunk_size) { res = crypto_hash_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; } res = crypto_hash_final(cs->ctx, cs->algo, hash, hash_size); if (res != TEE_SUCCESS) return res; break; case TEE_OPERATION_MAC: res = tee_mac_get_digest_size(cs->algo, &hash_size); if (res != TEE_SUCCESS) return res; if (*hash_len < hash_size) { res = TEE_ERROR_SHORT_BUFFER; goto out; } if (chunk_size) { res = crypto_mac_update(cs->ctx, cs->algo, chunk, chunk_size); if (res != TEE_SUCCESS) return res; } res = crypto_mac_final(cs->ctx, cs->algo, hash, hash_size); if (res != TEE_SUCCESS) return res; break; default: return TEE_ERROR_BAD_PARAMETERS; } out: hlen = hash_size; res2 = tee_svc_copy_to_user(hash_len, &hlen, sizeof(*hash_len)); if (res2 != TEE_SUCCESS) return res2; return res; } TEE_Result syscall_cipher_init(unsigned long state, const void *iv, size_t iv_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; struct tee_obj *o; struct tee_cryp_obj_secret *key1; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) iv, iv_len); if (res != TEE_SUCCESS) return res; res = tee_obj_get(utc, cs->key1, &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; key1 = o->attr; if (tee_obj_get(utc, cs->key2, &o) == TEE_SUCCESS) { struct tee_cryp_obj_secret *key2 = o->attr; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; res = crypto_cipher_init(cs->ctx, cs->algo, cs->mode, (uint8_t *)(key1 + 1), key1->key_size, (uint8_t *)(key2 + 1), key2->key_size, iv, iv_len); } else { res = crypto_cipher_init(cs->ctx, cs->algo, cs->mode, (uint8_t *)(key1 + 1), key1->key_size, NULL, 0, iv, iv_len); } if (res != TEE_SUCCESS) return res; cs->ctx_finalize = crypto_cipher_final; return TEE_SUCCESS; } static TEE_Result tee_svc_cipher_update_helper(unsigned long state, bool last_block, const void *src, size_t src_len, void *dst, uint64_t *dst_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)src, src_len); if (res != TEE_SUCCESS) return res; if (!dst_len) { dlen = 0; } else { res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)dst, dlen); if (res != TEE_SUCCESS) return res; } if (dlen < src_len) { res = TEE_ERROR_SHORT_BUFFER; goto out; } if (src_len > 0) { /* Permit src_len == 0 to finalize the operation */ res = tee_do_cipher_update(cs->ctx, cs->algo, cs->mode, last_block, src, src_len, dst); } if (last_block && cs->ctx_finalize != NULL) { cs->ctx_finalize(cs->ctx, cs->algo); cs->ctx_finalize = NULL; } out: if ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) && dst_len != NULL) { TEE_Result res2; dlen = src_len; res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) res = res2; } return res; } TEE_Result syscall_cipher_update(unsigned long state, const void *src, size_t src_len, void *dst, uint64_t *dst_len) { return tee_svc_cipher_update_helper(state, false /* last_block */, src, src_len, dst, dst_len); } TEE_Result syscall_cipher_final(unsigned long state, const void *src, size_t src_len, void *dst, uint64_t *dst_len) { return tee_svc_cipher_update_helper(state, true /* last_block */, src, src_len, dst, dst_len); } #if defined(CFG_CRYPTO_HKDF) static TEE_Result get_hkdf_params(const TEE_Attribute *params, uint32_t param_count, void **salt, size_t *salt_len, void **info, size_t *info_len, size_t *okm_len) { size_t n; enum { SALT = 0x1, LENGTH = 0x2, INFO = 0x4 }; uint8_t found = 0; *salt = *info = NULL; *salt_len = *info_len = *okm_len = 0; for (n = 0; n < param_count; n++) { switch (params[n].attributeID) { case TEE_ATTR_HKDF_SALT: if (!(found & SALT)) { *salt = params[n].content.ref.buffer; *salt_len = params[n].content.ref.length; found |= SALT; } break; case TEE_ATTR_HKDF_OKM_LENGTH: if (!(found & LENGTH)) { *okm_len = params[n].content.value.a; found |= LENGTH; } break; case TEE_ATTR_HKDF_INFO: if (!(found & INFO)) { *info = params[n].content.ref.buffer; *info_len = params[n].content.ref.length; found |= INFO; } break; default: /* Unexpected attribute */ return TEE_ERROR_BAD_PARAMETERS; } } if (!(found & LENGTH)) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } #endif #if defined(CFG_CRYPTO_CONCAT_KDF) static TEE_Result get_concat_kdf_params(const TEE_Attribute *params, uint32_t param_count, void **other_info, size_t *other_info_len, size_t *derived_key_len) { size_t n; enum { LENGTH = 0x1, INFO = 0x2 }; uint8_t found = 0; *other_info = NULL; *other_info_len = *derived_key_len = 0; for (n = 0; n < param_count; n++) { switch (params[n].attributeID) { case TEE_ATTR_CONCAT_KDF_OTHER_INFO: if (!(found & INFO)) { *other_info = params[n].content.ref.buffer; *other_info_len = params[n].content.ref.length; found |= INFO; } break; case TEE_ATTR_CONCAT_KDF_DKM_LENGTH: if (!(found & LENGTH)) { *derived_key_len = params[n].content.value.a; found |= LENGTH; } break; default: /* Unexpected attribute */ return TEE_ERROR_BAD_PARAMETERS; } } if (!(found & LENGTH)) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } #endif #if defined(CFG_CRYPTO_PBKDF2) static TEE_Result get_pbkdf2_params(const TEE_Attribute *params, uint32_t param_count, void **salt, size_t *salt_len, size_t *derived_key_len, size_t *iteration_count) { size_t n; enum { SALT = 0x1, LENGTH = 0x2, COUNT = 0x4 }; uint8_t found = 0; *salt = NULL; *salt_len = *derived_key_len = *iteration_count = 0; for (n = 0; n < param_count; n++) { switch (params[n].attributeID) { case TEE_ATTR_PBKDF2_SALT: if (!(found & SALT)) { *salt = params[n].content.ref.buffer; *salt_len = params[n].content.ref.length; found |= SALT; } break; case TEE_ATTR_PBKDF2_DKM_LENGTH: if (!(found & LENGTH)) { *derived_key_len = params[n].content.value.a; found |= LENGTH; } break; case TEE_ATTR_PBKDF2_ITERATION_COUNT: if (!(found & COUNT)) { *iteration_count = params[n].content.value.a; found |= COUNT; } break; default: /* Unexpected attribute */ return TEE_ERROR_BAD_PARAMETERS; } } if ((found & (LENGTH|COUNT)) != (LENGTH|COUNT)) return TEE_ERROR_BAD_PARAMETERS; return TEE_SUCCESS; } #endif TEE_Result syscall_cryp_derive_key(unsigned long state, const struct utee_attribute *usr_params, unsigned long param_count, unsigned long derived_key) { TEE_Result res = TEE_ERROR_NOT_SUPPORTED; struct tee_ta_session *sess; struct tee_obj *ko; struct tee_obj *so; struct tee_cryp_state *cs; struct tee_cryp_obj_secret *sk; const struct tee_cryp_obj_type_props *type_props; TEE_Attribute *params = NULL; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; size_t alloc_size = 0; if (MUL_OVERFLOW(sizeof(TEE_Attribute), param_count, &alloc_size)) return TEE_ERROR_OVERFLOW; params = malloc(alloc_size); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(utc, usr_params, param_count, params); if (res != TEE_SUCCESS) goto out; /* Get key set in operation */ res = tee_obj_get(utc, cs->key1, &ko); if (res != TEE_SUCCESS) goto out; res = tee_obj_get(utc, tee_svc_uref_to_vaddr(derived_key), &so); if (res != TEE_SUCCESS) goto out; /* Find information needed about the object to initialize */ sk = so->attr; /* Find description of object */ type_props = tee_svc_find_type_props(so->info.objectType); if (!type_props) { res = TEE_ERROR_NOT_SUPPORTED; goto out; } if (cs->algo == TEE_ALG_DH_DERIVE_SHARED_SECRET) { size_t alloc_size; struct bignum *pub; struct bignum *ss; if (param_count != 1 || params[0].attributeID != TEE_ATTR_DH_PUBLIC_VALUE) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } alloc_size = params[0].content.ref.length * 8; pub = crypto_bignum_allocate(alloc_size); ss = crypto_bignum_allocate(alloc_size); if (pub && ss) { crypto_bignum_bin2bn(params[0].content.ref.buffer, params[0].content.ref.length, pub); res = crypto_acipher_dh_shared_secret(ko->attr, pub, ss); if (res == TEE_SUCCESS) { sk->key_size = crypto_bignum_num_bytes(ss); crypto_bignum_bn2bin(ss, (uint8_t *)(sk + 1)); so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } else { res = TEE_ERROR_OUT_OF_MEMORY; } crypto_bignum_free(pub); crypto_bignum_free(ss); } else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_ECDH) { size_t alloc_size; struct ecc_public_key key_public; uint8_t *pt_secret; unsigned long pt_secret_len; if (param_count != 2 || params[0].attributeID != TEE_ATTR_ECC_PUBLIC_VALUE_X || params[1].attributeID != TEE_ATTR_ECC_PUBLIC_VALUE_Y) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } switch (cs->algo) { case TEE_ALG_ECDH_P192: alloc_size = 192; break; case TEE_ALG_ECDH_P224: alloc_size = 224; break; case TEE_ALG_ECDH_P256: alloc_size = 256; break; case TEE_ALG_ECDH_P384: alloc_size = 384; break; case TEE_ALG_ECDH_P521: alloc_size = 521; break; default: res = TEE_ERROR_NOT_IMPLEMENTED; goto out; } /* Create the public key */ res = crypto_acipher_alloc_ecc_public_key(&key_public, alloc_size); if (res != TEE_SUCCESS) goto out; key_public.curve = ((struct ecc_keypair *)ko->attr)->curve; crypto_bignum_bin2bn(params[0].content.ref.buffer, params[0].content.ref.length, key_public.x); crypto_bignum_bin2bn(params[1].content.ref.buffer, params[1].content.ref.length, key_public.y); pt_secret = (uint8_t *)(sk + 1); pt_secret_len = sk->alloc_size; res = crypto_acipher_ecc_shared_secret(ko->attr, &key_public, pt_secret, &pt_secret_len); if (res == TEE_SUCCESS) { sk->key_size = pt_secret_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } /* free the public key */ crypto_acipher_free_ecc_public_key(&key_public); } #if defined(CFG_CRYPTO_HKDF) else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_HKDF) { void *salt, *info; size_t salt_len, info_len, okm_len; uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo); struct tee_cryp_obj_secret *ik = ko->attr; const uint8_t *ikm = (const uint8_t *)(ik + 1); res = get_hkdf_params(params, param_count, &salt, &salt_len, &info, &info_len, &okm_len); if (res != TEE_SUCCESS) goto out; /* Requested size must fit into the output object's buffer */ if (okm_len > ik->alloc_size) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_cryp_hkdf(hash_id, ikm, ik->key_size, salt, salt_len, info, info_len, (uint8_t *)(sk + 1), okm_len); if (res == TEE_SUCCESS) { sk->key_size = okm_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } #endif #if defined(CFG_CRYPTO_CONCAT_KDF) else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_CONCAT_KDF) { void *info; size_t info_len, derived_key_len; uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo); struct tee_cryp_obj_secret *ss = ko->attr; const uint8_t *shared_secret = (const uint8_t *)(ss + 1); res = get_concat_kdf_params(params, param_count, &info, &info_len, &derived_key_len); if (res != TEE_SUCCESS) goto out; /* Requested size must fit into the output object's buffer */ if (derived_key_len > ss->alloc_size) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_cryp_concat_kdf(hash_id, shared_secret, ss->key_size, info, info_len, (uint8_t *)(sk + 1), derived_key_len); if (res == TEE_SUCCESS) { sk->key_size = derived_key_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } #endif #if defined(CFG_CRYPTO_PBKDF2) else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_PBKDF2) { void *salt; size_t salt_len, iteration_count, derived_key_len; uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo); struct tee_cryp_obj_secret *ss = ko->attr; const uint8_t *password = (const uint8_t *)(ss + 1); res = get_pbkdf2_params(params, param_count, &salt, &salt_len, &derived_key_len, &iteration_count); if (res != TEE_SUCCESS) goto out; /* Requested size must fit into the output object's buffer */ if (derived_key_len > ss->alloc_size) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_cryp_pbkdf2(hash_id, password, ss->key_size, salt, salt_len, iteration_count, (uint8_t *)(sk + 1), derived_key_len); if (res == TEE_SUCCESS) { sk->key_size = derived_key_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } #endif else res = TEE_ERROR_NOT_SUPPORTED; out: free(params); return res; } TEE_Result syscall_cryp_random_number_generate(void *buf, size_t blen) { TEE_Result res; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)buf, blen); if (res != TEE_SUCCESS) return res; res = crypto_rng_read(buf, blen); if (res != TEE_SUCCESS) return res; return res; } TEE_Result syscall_authenc_init(unsigned long state, const void *nonce, size_t nonce_len, size_t tag_len, size_t aad_len, size_t payload_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; struct tee_obj *o; struct tee_cryp_obj_secret *key; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_obj_get(to_user_ta_ctx(sess->ctx), cs->key1, &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; key = o->attr; res = crypto_authenc_init(cs->ctx, cs->algo, cs->mode, (uint8_t *)(key + 1), key->key_size, nonce, nonce_len, tag_len, aad_len, payload_len); if (res != TEE_SUCCESS) return res; cs->ctx_finalize = (tee_cryp_ctx_finalize_func_t)crypto_authenc_final; return TEE_SUCCESS; } TEE_Result syscall_authenc_update_aad(unsigned long state, const void *aad_data, size_t aad_data_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) aad_data, aad_data_len); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = crypto_authenc_update_aad(cs->ctx, cs->algo, cs->mode, aad_data, aad_data_len); if (res != TEE_SUCCESS) return res; return TEE_SUCCESS; } TEE_Result syscall_authenc_update_payload(unsigned long state, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen; size_t tmp_dlen; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) src_data, src_len); if (res != TEE_SUCCESS) return res; res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)dst_data, dlen); if (res != TEE_SUCCESS) return res; if (dlen < src_len) { res = TEE_ERROR_SHORT_BUFFER; goto out; } tmp_dlen = dlen; res = crypto_authenc_update_payload(cs->ctx, cs->algo, cs->mode, src_data, src_len, dst_data, &tmp_dlen); dlen = tmp_dlen; out: if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) { TEE_Result res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) res = res2; } return res; } TEE_Result syscall_authenc_enc_final(unsigned long state, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len, void *tag, uint64_t *tag_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen; uint64_t tlen = 0; size_t tmp_dlen; size_t tmp_tlen; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; if (cs->mode != TEE_MODE_ENCRYPT) return TEE_ERROR_BAD_PARAMETERS; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)src_data, src_len); if (res != TEE_SUCCESS) return res; if (!dst_len) { dlen = 0; } else { res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)dst_data, dlen); if (res != TEE_SUCCESS) return res; } if (dlen < src_len) { res = TEE_ERROR_SHORT_BUFFER; goto out; } res = tee_svc_copy_from_user(&tlen, tag_len, sizeof(tlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)tag, tlen); if (res != TEE_SUCCESS) return res; tmp_dlen = dlen; tmp_tlen = tlen; res = crypto_authenc_enc_final(cs->ctx, cs->algo, src_data, src_len, dst_data, &tmp_dlen, tag, &tmp_tlen); dlen = tmp_dlen; tlen = tmp_tlen; out: if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) { TEE_Result res2; if (dst_len != NULL) { res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) return res2; } res2 = tee_svc_copy_to_user(tag_len, &tlen, sizeof(*tag_len)); if (res2 != TEE_SUCCESS) return res2; } return res; } TEE_Result syscall_authenc_dec_final(unsigned long state, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len, const void *tag, size_t tag_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen; size_t tmp_dlen; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; if (cs->mode != TEE_MODE_DECRYPT) return TEE_ERROR_BAD_PARAMETERS; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)src_data, src_len); if (res != TEE_SUCCESS) return res; if (!dst_len) { dlen = 0; } else { res = tee_svc_copy_from_user(&dlen, dst_len, sizeof(dlen)); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)dst_data, dlen); if (res != TEE_SUCCESS) return res; } if (dlen < src_len) { res = TEE_ERROR_SHORT_BUFFER; goto out; } res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)tag, tag_len); if (res != TEE_SUCCESS) return res; tmp_dlen = dlen; res = crypto_authenc_dec_final(cs->ctx, cs->algo, src_data, src_len, dst_data, &tmp_dlen, tag, tag_len); dlen = tmp_dlen; out: if ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) && dst_len != NULL) { TEE_Result res2; res2 = tee_svc_copy_to_user(dst_len, &dlen, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) return res2; } return res; } static int pkcs1_get_salt_len(const TEE_Attribute *params, uint32_t num_params, size_t default_len) { size_t n; assert(default_len < INT_MAX); for (n = 0; n < num_params; n++) { if (params[n].attributeID == TEE_ATTR_RSA_PSS_SALT_LENGTH) { if (params[n].content.value.a < INT_MAX) return params[n].content.value.a; break; } } /* * If salt length isn't provided use the default value which is * the length of the digest. */ return default_len; } TEE_Result syscall_asymm_operate(unsigned long state, const struct utee_attribute *usr_params, size_t num_params, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen64; size_t dlen; struct tee_obj *o; void *label = NULL; size_t label_len = 0; size_t n; int salt_len; TEE_Attribute *params = NULL; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights( utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) src_data, src_len); if (res != TEE_SUCCESS) return res; res = tee_svc_copy_from_user(&dlen64, dst_len, sizeof(dlen64)); if (res != TEE_SUCCESS) return res; dlen = dlen64; res = tee_mmu_check_access_rights( utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) dst_data, dlen); if (res != TEE_SUCCESS) return res; size_t alloc_size = 0; if (MUL_OVERFLOW(sizeof(TEE_Attribute), num_params, &alloc_size)) return TEE_ERROR_OVERFLOW; params = malloc(alloc_size); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(utc, usr_params, num_params, params); if (res != TEE_SUCCESS) goto out; res = tee_obj_get(utc, cs->key1, &o); if (res != TEE_SUCCESS) goto out; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) { res = TEE_ERROR_GENERIC; goto out; } switch (cs->algo) { case TEE_ALG_RSA_NOPAD: if (cs->mode == TEE_MODE_ENCRYPT) { res = crypto_acipher_rsanopad_encrypt(o->attr, src_data, src_len, dst_data, &dlen); } else if (cs->mode == TEE_MODE_DECRYPT) { res = crypto_acipher_rsanopad_decrypt(o->attr, src_data, src_len, dst_data, &dlen); } else { /* * We will panic because "the mode is not compatible * with the function" */ res = TEE_ERROR_GENERIC; } break; case TEE_ALG_RSAES_PKCS1_V1_5: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512: for (n = 0; n < num_params; n++) { if (params[n].attributeID == TEE_ATTR_RSA_OAEP_LABEL) { label = params[n].content.ref.buffer; label_len = params[n].content.ref.length; break; } } if (cs->mode == TEE_MODE_ENCRYPT) { res = crypto_acipher_rsaes_encrypt(cs->algo, o->attr, label, label_len, src_data, src_len, dst_data, &dlen); } else if (cs->mode == TEE_MODE_DECRYPT) { res = crypto_acipher_rsaes_decrypt( cs->algo, o->attr, label, label_len, src_data, src_len, dst_data, &dlen); } else { res = TEE_ERROR_BAD_PARAMETERS; } break; #if defined(CFG_CRYPTO_RSASSA_NA1) case TEE_ALG_RSASSA_PKCS1_V1_5: #endif case TEE_ALG_RSASSA_PKCS1_V1_5_MD5: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512: if (cs->mode != TEE_MODE_SIGN) { res = TEE_ERROR_BAD_PARAMETERS; break; } salt_len = pkcs1_get_salt_len(params, num_params, src_len); res = crypto_acipher_rsassa_sign(cs->algo, o->attr, salt_len, src_data, src_len, dst_data, &dlen); break; case TEE_ALG_DSA_SHA1: case TEE_ALG_DSA_SHA224: case TEE_ALG_DSA_SHA256: res = crypto_acipher_dsa_sign(cs->algo, o->attr, src_data, src_len, dst_data, &dlen); break; case TEE_ALG_ECDSA_P192: case TEE_ALG_ECDSA_P224: case TEE_ALG_ECDSA_P256: case TEE_ALG_ECDSA_P384: case TEE_ALG_ECDSA_P521: res = crypto_acipher_ecc_sign(cs->algo, o->attr, src_data, src_len, dst_data, &dlen); break; default: res = TEE_ERROR_BAD_PARAMETERS; break; } out: free(params); if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) { TEE_Result res2; dlen64 = dlen; res2 = tee_svc_copy_to_user(dst_len, &dlen64, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) return res2; } return res; } TEE_Result syscall_asymm_verify(unsigned long state, const struct utee_attribute *usr_params, size_t num_params, const void *data, size_t data_len, const void *sig, size_t sig_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; struct tee_obj *o; size_t hash_size; int salt_len = 0; TEE_Attribute *params = NULL; uint32_t hash_algo; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; if (cs->mode != TEE_MODE_VERIFY) return TEE_ERROR_BAD_PARAMETERS; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)data, data_len); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)sig, sig_len); if (res != TEE_SUCCESS) return res; size_t alloc_size = 0; if (MUL_OVERFLOW(sizeof(TEE_Attribute), num_params, &alloc_size)) return TEE_ERROR_OVERFLOW; params = malloc(alloc_size); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(utc, usr_params, num_params, params); if (res != TEE_SUCCESS) goto out; res = tee_obj_get(utc, cs->key1, &o); if (res != TEE_SUCCESS) goto out; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } switch (TEE_ALG_GET_MAIN_ALG(cs->algo)) { case TEE_MAIN_ALGO_RSA: if (cs->algo != TEE_ALG_RSASSA_PKCS1_V1_5) { hash_algo = TEE_DIGEST_HASH_TO_ALGO(cs->algo); res = tee_hash_get_digest_size(hash_algo, &hash_size); if (res != TEE_SUCCESS) break; if (data_len != hash_size) { res = TEE_ERROR_BAD_PARAMETERS; break; } salt_len = pkcs1_get_salt_len(params, num_params, hash_size); } res = crypto_acipher_rsassa_verify(cs->algo, o->attr, salt_len, data, data_len, sig, sig_len); break; case TEE_MAIN_ALGO_DSA: hash_algo = TEE_DIGEST_HASH_TO_ALGO(cs->algo); res = tee_hash_get_digest_size(hash_algo, &hash_size); if (res != TEE_SUCCESS) break; /* * Depending on the DSA algorithm (NIST), the digital signature * output size may be truncated to the size of a key pair * (Q prime size). Q prime size must be less or equal than the * hash output length of the hash algorithm involved. */ if (data_len > hash_size) { res = TEE_ERROR_BAD_PARAMETERS; break; } res = crypto_acipher_dsa_verify(cs->algo, o->attr, data, data_len, sig, sig_len); break; case TEE_MAIN_ALGO_ECDSA: res = crypto_acipher_ecc_verify(cs->algo, o->attr, data, data_len, sig, sig_len); break; default: res = TEE_ERROR_NOT_SUPPORTED; } out: free(params); return res; }
null
116
CWE-787
CVE-2019-11222
/* * GPAC - Multimedia Framework C SDK * * Authors: Jean Le Feuvre * Copyright (c) Telecom ParisTech 2000-2012 * All rights reserved * * This file is part of GPAC / common tools sub-project * * GPAC is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * GPAC is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * */ #include <gpac/tools.h> #include <gpac/network.h> #if defined(_WIN32_WCE) #include <winbase.h> #include <winsock.h> #include <tlhelp32.h> //#include <direct.h> #if !defined(__GNUC__) #pragma comment(lib, "toolhelp") #endif #elif defined(WIN32) #include <time.h> #include <sys/timeb.h> #include <io.h> #include <windows.h> #include <tlhelp32.h> #include <direct.h> #if !defined(__GNUC__) #pragma comment(lib, "winmm") #endif #else #include <time.h> #include <sys/stat.h> #include <sys/time.h> #include <dirent.h> #include <unistd.h> #include <sys/times.h> #include <sys/resource.h> #ifndef __BEOS__ #include <errno.h> #endif #define SLEEP_ABS_SELECT 1 static u32 sys_start_time = 0; static u64 sys_start_time_hr = 0; #endif #ifndef _WIN32_WCE #include <locale.h> #endif #ifndef WIN32 GF_EXPORT u32 gf_sys_clock() { struct timeval now; gettimeofday(&now, NULL); return (u32) ( ( (now.tv_sec)*1000 + (now.tv_usec) / 1000) - sys_start_time ); } GF_EXPORT u64 gf_sys_clock_high_res() { struct timeval now; gettimeofday(&now, NULL); return (now.tv_sec)*1000000 + (now.tv_usec) - sys_start_time_hr; } #endif GF_EXPORT void gf_sleep(u32 ms) { #ifdef WIN32 Sleep(ms); #else s32 sel_err; struct timeval tv; #ifndef SLEEP_ABS_SELECT u32 prev, now, elapsed; #endif #ifdef SLEEP_ABS_SELECT tv.tv_sec = ms/1000; tv.tv_usec = (ms%1000)*1000; #else prev = gf_sys_clock(); #endif do { errno = 0; #ifndef SLEEP_ABS_SELECT now = gf_sys_clock(); elapsed = (now - prev); if ( elapsed >= ms ) { break; } prev = now; ms -= elapsed; tv.tv_sec = ms/1000; tv.tv_usec = (ms%1000)*1000; #endif sel_err = select(0, NULL, NULL, NULL, &tv); } while ( sel_err && (errno == EINTR) ); #endif } #ifndef gettimeofday #ifdef _WIN32_WCE #include <time.h> //#include <wce_time.h> /* * Author of first version (timeval.h): by Wu Yongwei * Author of Windows CE version: Mateusz Loskot (mateusz@loskot.net) * * All code here is considered in the public domain though we do wish our names * could be retained if anyone uses them. */ /* * Constants used internally by time functions. */ #ifndef _TM_DEFINED struct tm { int tm_sec; /* seconds after the minute - [0,59] */ int tm_min; /* minutes after the hour - [0,59] */ int tm_hour; /* hours since midnight - [0,23] */ int tm_mday; /* day of the month - [1,31] */ int tm_mon; /* months since January - [0,11] */ int tm_year; /* years since 1900 */ int tm_wday; /* days since Sunday - [0,6] */ int tm_yday; /* days since January 1 - [0,365] */ int tm_isdst; /* daylight savings time flag */ }; #define _TM_DEFINED #endif /* _TM_DEFINED */ #ifndef _TIMEZONE_DEFINED struct timezone { int tz_minuteswest; /* minutes W of Greenwich */ int tz_dsttime; /* type of dst correction */ }; #define _TIMEZONE_DEFINED #endif /* _TIMEZONE_DEFINED */ #if defined(_MSC_VER) || defined(__BORLANDC__) #define EPOCHFILETIME (116444736000000000i64) #else #define EPOCHFILETIME (116444736000000000LL) #endif int gettimeofday(struct timeval *tp, struct timezone *tzp) { SYSTEMTIME st; FILETIME ft; LARGE_INTEGER li; TIME_ZONE_INFORMATION tzi; __int64 t; static int tzflag; if (NULL != tp) { GetSystemTime(&st); SystemTimeToFileTime(&st, &ft); li.LowPart = ft.dwLowDateTime; li.HighPart = ft.dwHighDateTime; t = li.QuadPart; /* In 100-nanosecond intervals */ t -= EPOCHFILETIME; /* Offset to the Epoch time */ t /= 10; /* In microseconds */ tp->tv_sec = (long)(t / 1000000); tp->tv_usec = (long)(t % 1000000); } if (NULL != tzp) { GetTimeZoneInformation(&tzi); tzp->tz_minuteswest = tzi.Bias; if (tzi.StandardDate.wMonth != 0) { tzp->tz_minuteswest += tzi.StandardBias * 60; } if (tzi.DaylightDate.wMonth != 0) { tzp->tz_dsttime = 1; } else { tzp->tz_dsttime = 0; } } return 0; } #if _GPAC_UNUSED /* time between jan 1, 1601 and jan 1, 1970 in units of 100 nanoseconds FILETIME in Win32 is from jan 1, 1601 */ s32 __gettimeofday(struct timeval *tp, void *tz) { FILETIME ft; SYSTEMTIME st; s32 val; GetSystemTime(&st); SystemTimeToFileTime(&st, &ft); val = (s32) ((*(LONGLONG *) &ft - TIMESPEC_TO_FILETIME_OFFSET) / 10000000); tp->tv_sec = (u32) val; val = (s32 ) ((*(LONGLONG *) &ft - TIMESPEC_TO_FILETIME_OFFSET - ((LONGLONG) val * (LONGLONG) 10000000)) * 100); tp->tv_usec = val; return 0; } #endif #elif defined(WIN32) static s32 gettimeofday(struct timeval *tp, void *tz) { struct _timeb timebuffer; _ftime( &timebuffer ); tp->tv_sec = (long) (timebuffer.time); tp->tv_usec = timebuffer.millitm * 1000; return 0; } #endif #endif #ifdef _WIN32_WCE void CE_Assert(u32 valid, char *file, u32 line) { if (!valid) { char szBuf[2048]; u16 wcBuf[2048]; sprintf(szBuf, "File %s : line %d", file, line); CE_CharToWide(szBuf, wcBuf); MessageBox(NULL, wcBuf, _T("GPAC Assertion Failure"), MB_OK); exit(EXIT_FAILURE); } } void CE_WideToChar(unsigned short *w_str, char *str) { WideCharToMultiByte(CP_ACP, 0, w_str, -1, str, GF_MAX_PATH, NULL, NULL); } void CE_CharToWide(char *str, unsigned short *w_str) { MultiByteToWideChar(CP_ACP, 0, str, -1, w_str, GF_MAX_PATH); } #endif GF_EXPORT void gf_rand_init(Bool Reset) { if (Reset) { srand(1); } else { #if defined(_WIN32_WCE) srand( (u32) GetTickCount() ); #else srand( (u32) time(NULL) ); #endif } } GF_EXPORT u32 gf_rand() { return rand(); } #ifndef _WIN32_WCE #include <sys/stat.h> #endif GF_EXPORT void gf_utc_time_since_1970(u32 *sec, u32 *msec) { #if defined (WIN32) && !defined(_WIN32_WCE) struct _timeb tb; _ftime( &tb ); *sec = (u32) tb.time; *msec = tb.millitm; #else struct timeval tv; gettimeofday(&tv, NULL); *sec = (u32) tv.tv_sec; *msec = tv.tv_usec/1000; #endif } GF_EXPORT void gf_get_user_name(char *buf, u32 buf_size) { strcpy(buf, "mpeg4-user"); #if 0 s32 len; char *t; strcpy(buf, ""); len = 1024; GetUserName(buf, &len); if (!len) { t = getenv("USER"); if (t) strcpy(buf, t); } #endif #if 0 struct passwd *pw; pw = getpwuid(getuid()); strcpy(buf, ""); if (pw && pw->pw_name) strcpy(name, pw->pw_name); #endif } #ifndef WIN32 GF_EXPORT char * my_str_upr(char *str) { u32 i; for (i=0; i<strlen(str); i++) { str[i] = toupper(str[i]); } return str; } GF_EXPORT char * my_str_lwr(char *str) { u32 i; for (i=0; i<strlen(str); i++) { str[i] = tolower(str[i]); } return str; } #endif /*seems OK under mingw also*/ #ifdef WIN32 #ifdef _WIN32_WCE Bool gf_prompt_has_input() { return 0; } char gf_prompt_get_char() { return 0; } GF_EXPORT void gf_prompt_set_echo_off(Bool echo_off) { return; } #else #include <conio.h> #include <windows.h> Bool gf_prompt_has_input() { return kbhit(); } char gf_prompt_get_char() { return getchar(); } GF_EXPORT void gf_prompt_set_echo_off(Bool echo_off) { DWORD flags; HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE); BOOL ret = GetConsoleMode(hStdin, &flags); if (!ret) { DWORD err = GetLastError(); GF_LOG(GF_LOG_ERROR, GF_LOG_CONSOLE, ("[Console] GetConsoleMode() return with the following error code: %d\n", err)); } if (echo_off) flags &= ~ENABLE_ECHO_INPUT; else flags |= ENABLE_ECHO_INPUT; SetConsoleMode(hStdin, flags); } #endif #else /*linux kbhit/getchar- borrowed on debian mailing lists, (author Mike Brownlow)*/ #include <termios.h> static struct termios t_orig, t_new; static s32 ch_peek = -1; static void init_keyboard() { tcgetattr(0, &t_orig); t_new = t_orig; t_new.c_lflag &= ~ICANON; t_new.c_lflag &= ~ECHO; t_new.c_lflag &= ~ISIG; t_new.c_cc[VMIN] = 1; t_new.c_cc[VTIME] = 0; tcsetattr(0, TCSANOW, &t_new); } static void close_keyboard(Bool new_line) { tcsetattr(0,TCSANOW, &t_orig); if (new_line) fprintf(stderr, "\n"); } GF_EXPORT void gf_prompt_set_echo_off(Bool echo_off) { init_keyboard(); if (echo_off) t_orig.c_lflag &= ~ECHO; else t_orig.c_lflag |= ECHO; close_keyboard(0); } GF_EXPORT Bool gf_prompt_has_input() { u8 ch; s32 nread; pid_t fg = tcgetpgrp(STDIN_FILENO); //we are not foreground nor piped (used for IDEs), can't read stdin if ((fg!=-1) && (fg != getpgrp())) { return 0; } init_keyboard(); if (ch_peek != -1) return 1; t_new.c_cc[VMIN]=0; tcsetattr(0, TCSANOW, &t_new); nread = (s32) read(0, &ch, 1); t_new.c_cc[VMIN]=1; tcsetattr(0, TCSANOW, &t_new); if(nread == 1) { ch_peek = ch; return 1; } close_keyboard(0); return 0; } GF_EXPORT char gf_prompt_get_char() { char ch; if (ch_peek != -1) { ch = ch_peek; ch_peek = -1; close_keyboard(1); return ch; } if (0==read(0,&ch,1)) ch = 0; close_keyboard(1); return ch; } #endif static u32 sys_init = 0; static u32 last_update_time = 0; static u64 last_process_k_u_time = 0; GF_SystemRTInfo the_rti; #if defined(_WIN32_WCE) static LARGE_INTEGER frequency , init_counter; static u64 last_total_k_u_time = 0; static u32 mem_usage_at_startup = 0; #ifndef GetCurrentPermissions DWORD GetCurrentPermissions(); #endif #ifndef SetProcPermissions void SetProcPermissions(DWORD ); #endif #elif defined(WIN32) static LARGE_INTEGER frequency , init_counter; static u64 last_proc_idle_time = 0; static u64 last_proc_k_u_time = 0; static HINSTANCE psapi_hinst = NULL; typedef BOOL(WINAPI* NTGetSystemTimes)(VOID *,VOID *,VOID *); NTGetSystemTimes MyGetSystemTimes = NULL; typedef BOOL(WINAPI* NTGetProcessMemoryInfo)(HANDLE,VOID *,DWORD); NTGetProcessMemoryInfo MyGetProcessMemoryInfo = NULL; typedef int(WINAPI* NTQuerySystemInfo)(ULONG,PVOID,ULONG,PULONG); NTQuerySystemInfo MyQuerySystemInfo = NULL; #ifndef PROCESS_MEMORY_COUNTERS typedef struct _PROCESS_MEMORY_COUNTERS { DWORD cb; DWORD PageFaultCount; SIZE_T PeakWorkingSetSize; SIZE_T WorkingSetSize; SIZE_T QuotaPeakPagedPoolUsage; SIZE_T QuotaPagedPoolUsage; SIZE_T QuotaPeakNonPagedPoolUsage; SIZE_T QuotaNonPagedPoolUsage; SIZE_T PagefileUsage; SIZE_T PeakPagefileUsage; } PROCESS_MEMORY_COUNTERS; #endif #ifndef SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION typedef struct _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION { LARGE_INTEGER IdleTime; LARGE_INTEGER KernelTime; LARGE_INTEGER UserTime; LARGE_INTEGER Reserved1[2]; ULONG Reserved2; } SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION; #endif #else static u64 last_cpu_u_k_time = 0; static u64 last_cpu_idle_time = 0; static u64 mem_at_startup = 0; #endif #ifdef WIN32 static u32 (*OS_GetSysClock)(); u32 gf_sys_clock() { return OS_GetSysClock(); } static u64 (*OS_GetSysClockHR)(); u64 gf_sys_clock_high_res() { return OS_GetSysClockHR(); } #endif #ifdef WIN32 static u32 OS_GetSysClockHIGHRES() { LARGE_INTEGER now; QueryPerformanceCounter(&now); now.QuadPart -= init_counter.QuadPart; return (u32) ((now.QuadPart * 1000) / frequency.QuadPart); } static u64 OS_GetSysClockHIGHRES_FULL() { LARGE_INTEGER now; QueryPerformanceCounter(&now); now.QuadPart -= init_counter.QuadPart; return (u64) ((now.QuadPart * 1000000) / frequency.QuadPart); } static u32 OS_GetSysClockNORMAL() { #ifdef _WIN32_WCE return GetTickCount(); #else return timeGetTime(); #endif } static u64 OS_GetSysClockNORMAL_FULL() { u64 res = OS_GetSysClockNORMAL(); return res*1000; } #endif /* WIN32 */ #if defined(__sh__) /* Avoid exception for denormalized floating point values */ static int sh4_get_fpscr() { int ret; asm volatile ("sts fpscr,%0" : "=r" (ret)); return ret; } static void sh4_put_fpscr(int nv) { asm volatile ("lds %0,fpscr" : : "r" (nv)); } #define SH4_FPSCR_FR 0x00200000 #define SH4_FPSCR_SZ 0x00100000 #define SH4_FPSCR_PR 0x00080000 #define SH4_FPSCR_DN 0x00040000 #define SH4_FPSCR_RN 0x00000003 #define SH4_FPSCR_RN_N 0 #define SH4_FPSCR_RN_Z 1 extern int __fpscr_values[2]; void sh4_change_fpscr(int off, int on) { int b = sh4_get_fpscr(); off = ~off; off |= 0x00180000; on &= ~ 0x00180000; b &= off; b |= on; sh4_put_fpscr(b); __fpscr_values[0] &= off; __fpscr_values[0] |= on; __fpscr_values[1] &= off; __fpscr_values[1] |= on; } #endif #ifdef GPAC_MEMORY_TRACKING void gf_mem_enable_tracker(Bool enable_backtrace); #endif static u64 memory_at_gpac_startup = 0; static u32 gpac_argc = 0; const char **gpac_argv = NULL; GF_EXPORT void gf_sys_set_args(s32 argc, const char **argv) { //for OSX we allow overwrite of argc/argv due to different behavior between console-mode apps and GUI #if !defined(__DARWIN__) && !defined(__APPLE__) if (!gpac_argc && (argc>=0) ) #endif { gpac_argc = (u32) argc; gpac_argv = argv; } } GF_EXPORT u32 gf_sys_get_argc() { return gpac_argc; } GF_EXPORT const char *gf_sys_get_arg(u32 arg) { if (!gpac_argc || !gpac_argv) return NULL; if (arg>=gpac_argc) return NULL; return gpac_argv[arg]; } GF_EXPORT void gf_sys_init(GF_MemTrackerType mem_tracker_type) { if (!sys_init) { #if defined (WIN32) #if defined(_WIN32_WCE) MEMORYSTATUS ms; #else SYSTEM_INFO sysinfo; #endif #endif if (mem_tracker_type!=GF_MemTrackerNone) { #ifdef GPAC_MEMORY_TRACKING gf_mem_enable_tracker( (mem_tracker_type==GF_MemTrackerBackTrace) ? GF_TRUE : GF_FALSE); #endif } #ifndef GPAC_DISABLE_LOG /*by default log subsystem is initialized to error on all tools, and info on console to debug scripts*/ gf_log_set_tool_level(GF_LOG_ALL, GF_LOG_ERROR); gf_log_set_tool_level(GF_LOG_CONSOLE, GF_LOG_INFO); #endif #if defined(__sh__) /* Round all denormalized floatting point number to 0.0 */ sh4_change_fpscr(0,SH4_FPSCR_DN) ; #endif #if defined(WIN32) frequency.QuadPart = 0; /*clock setup*/ if (QueryPerformanceFrequency(&frequency)) { QueryPerformanceCounter(&init_counter); OS_GetSysClock = OS_GetSysClockHIGHRES; OS_GetSysClockHR = OS_GetSysClockHIGHRES_FULL; GF_LOG(GF_LOG_INFO, GF_LOG_CORE, ("[core] using WIN32 performance timer\n")); } else { OS_GetSysClock = OS_GetSysClockNORMAL; OS_GetSysClockHR = OS_GetSysClockNORMAL_FULL; GF_LOG(GF_LOG_INFO, GF_LOG_CORE, ("[core] using WIN32 regular timer\n")); } #ifndef _WIN32_WCE timeBeginPeriod(1); #endif GF_LOG(GF_LOG_INFO, GF_LOG_CORE, ("[core] checking for run-time info tools")); #if defined(_WIN32_WCE) last_total_k_u_time = last_process_k_u_time = 0; last_update_time = 0; memset(&the_rti, 0, sizeof(GF_SystemRTInfo)); the_rti.pid = GetCurrentProcessId(); the_rti.nb_cores = 1; GlobalMemoryStatus(&ms); mem_usage_at_startup = ms.dwAvailPhys; #else /*cpu usage tools are buried in win32 dlls...*/ MyGetSystemTimes = (NTGetSystemTimes) GetProcAddress(GetModuleHandle("kernel32.dll"), "GetSystemTimes"); if (!MyGetSystemTimes) { MyQuerySystemInfo = (NTQuerySystemInfo) GetProcAddress(GetModuleHandle("ntdll.dll"), "NtQuerySystemInformation"); if (MyQuerySystemInfo) { GF_LOG(GF_LOG_INFO, GF_LOG_CORE, (" - CPU: QuerySystemInformation")); } } else { GF_LOG(GF_LOG_INFO, GF_LOG_CORE, (" - CPU: GetSystemsTimes")); } psapi_hinst = LoadLibrary("psapi.dll"); MyGetProcessMemoryInfo = (NTGetProcessMemoryInfo) GetProcAddress(psapi_hinst, "GetProcessMemoryInfo"); if (MyGetProcessMemoryInfo) { GF_LOG(GF_LOG_INFO, GF_LOG_CORE, (" - memory: GetProcessMemoryInfo")); } last_process_k_u_time = last_proc_idle_time = last_proc_k_u_time = 0; last_update_time = 0; memset(&the_rti, 0, sizeof(GF_SystemRTInfo)); the_rti.pid = GetCurrentProcessId(); GetSystemInfo( &sysinfo ); the_rti.nb_cores = sysinfo.dwNumberOfProcessors; #endif GF_LOG(GF_LOG_INFO, GF_LOG_CORE, ("\n")); #else /*linux threads and OSX...*/ last_process_k_u_time = 0; last_cpu_u_k_time = last_cpu_idle_time = 0; last_update_time = 0; memset(&the_rti, 0, sizeof(GF_SystemRTInfo)); the_rti.pid = getpid(); the_rti.nb_cores = (u32) sysconf( _SC_NPROCESSORS_ONLN ); sys_start_time = gf_sys_clock(); sys_start_time_hr = gf_sys_clock_high_res(); #endif GF_LOG(GF_LOG_INFO, GF_LOG_CORE, ("[core] process id %d\n", the_rti.pid)); #ifndef _WIN32_WCE setlocale( LC_NUMERIC, "C" ); #endif } sys_init += 1; /*init RTI stats*/ if (!memory_at_gpac_startup) { GF_SystemRTInfo rti; if (gf_sys_get_rti(500, &rti, GF_RTI_SYSTEM_MEMORY_ONLY)) { memory_at_gpac_startup = rti.physical_memory_avail; GF_LOG(GF_LOG_INFO, GF_LOG_CORE, ("[core] System init OK - process id %d - %d MB physical RAM - %d cores\n", rti.pid, (u32) (rti.physical_memory/1024/1024), rti.nb_cores)); } else { memory_at_gpac_startup = 0; } } } GF_EXPORT void gf_sys_close() { if (sys_init > 0) { sys_init --; if (sys_init) return; /*prevent any call*/ last_update_time = 0xFFFFFFFF; #if defined(WIN32) && !defined(_WIN32_WCE) timeEndPeriod(1); MyGetSystemTimes = NULL; MyGetProcessMemoryInfo = NULL; MyQuerySystemInfo = NULL; if (psapi_hinst) FreeLibrary(psapi_hinst); psapi_hinst = NULL; #endif } } #ifdef GPAC_MEMORY_TRACKING extern size_t gpac_allocated_memory; extern size_t gpac_nb_alloc_blocs; #endif /*CPU and Memory Usage*/ #ifdef WIN32 Bool gf_sys_get_rti_os(u32 refresh_time_ms, GF_SystemRTInfo *rti, u32 flags) { #if defined(_WIN32_WCE) THREADENTRY32 tentry; u64 total_cpu_time, process_cpu_time; DWORD orig_perm; #endif MEMORYSTATUS ms; u64 creation, exit, kernel, user, process_k_u_time, proc_idle_time, proc_k_u_time; u32 entry_time; HANDLE hSnapShot; assert(sys_init); if (!rti) return GF_FALSE; proc_idle_time = proc_k_u_time = process_k_u_time = 0; entry_time = gf_sys_clock(); if (last_update_time && (entry_time - last_update_time < refresh_time_ms)) { memcpy(rti, &the_rti, sizeof(GF_SystemRTInfo)); return GF_FALSE; } if (flags & GF_RTI_SYSTEM_MEMORY_ONLY) { memset(rti, 0, sizeof(GF_SystemRTInfo)); rti->sampling_instant = last_update_time; GlobalMemoryStatus(&ms); rti->physical_memory = ms.dwTotalPhys; rti->physical_memory_avail = ms.dwAvailPhys; #ifdef GPAC_MEMORY_TRACKING rti->gpac_memory = (u64) gpac_allocated_memory; #endif return GF_TRUE; } #if defined (_WIN32_WCE) total_cpu_time = process_cpu_time = 0; /*get a snapshot of all running threads*/ orig_perm = GetCurrentPermissions(); SetProcPermissions(0xFFFFFFFF); hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); if (hSnapShot) { tentry.dwSize = sizeof(THREADENTRY32); the_rti.thread_count = 0; /*note we always act as if GF_RTI_ALL_PROCESSES_TIMES flag is set, since there is no other way to enumerate threads from a process, and GetProcessTimes doesn't exist on CE*/ if (Thread32First(hSnapShot, &tentry)) { do { /*get thread times*/ if (GetThreadTimes( (HANDLE) tentry.th32ThreadID, (FILETIME *) &creation, (FILETIME *) &exit, (FILETIME *) &kernel, (FILETIME *) &user)) { total_cpu_time += user + kernel; if (tentry.th32OwnerProcessID==the_rti.pid) { process_cpu_time += user + kernel; the_rti.thread_count ++; } } } while (Thread32Next(hSnapShot, &tentry)); } CloseToolhelp32Snapshot(hSnapShot); } if (flags & GF_RTI_PROCESS_MEMORY) { HEAPLIST32 hlentry; HEAPENTRY32 hentry; the_rti.process_memory = 0; hlentry.dwSize = sizeof(HEAPLIST32); hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPHEAPLIST, the_rti.pid); if (hSnapShot && Heap32ListFirst(hSnapShot, &hlentry)) { do { hentry.dwSize = sizeof(hentry); if (Heap32First(hSnapShot, &hentry, hlentry.th32ProcessID, hlentry.th32HeapID)) { do { the_rti.process_memory += hentry.dwBlockSize; } while (Heap32Next(hSnapShot, &hentry)); } } while (Heap32ListNext(hSnapShot, &hlentry)); } CloseToolhelp32Snapshot(hSnapShot); } SetProcPermissions(orig_perm); total_cpu_time /= 10; process_cpu_time /= 10; #else /*XP-SP1 and Win2003 servers only have GetSystemTimes support. This will give a better estimation of CPU usage since we can take into account the idle time*/ if (MyGetSystemTimes) { u64 u_time; MyGetSystemTimes(&proc_idle_time, &proc_k_u_time, &u_time); proc_k_u_time += u_time; proc_idle_time /= 10; proc_k_u_time /= 10; } /*same rq for NtQuerySystemInformation*/ else if (MyQuerySystemInfo) { DWORD ret; SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION info; MyQuerySystemInfo(0x8 /*SystemProcessorPerformanceInformation*/, &info, sizeof(info), &ret); if (ret && (ret<=sizeof(info))) { proc_idle_time = info.IdleTime.QuadPart / 10; proc_k_u_time = (info.KernelTime.QuadPart + info.UserTime.QuadPart) / 10; } } /*no special API available, ONLY FETCH TIMES if requested (may eat up some time)*/ else if (flags & GF_RTI_ALL_PROCESSES_TIMES) { PROCESSENTRY32 pentry; /*get a snapshot of all running threads*/ hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (!hSnapShot) return GF_FALSE; pentry.dwSize = sizeof(PROCESSENTRY32); if (Process32First(hSnapShot, &pentry)) { do { HANDLE procH = NULL; if (pentry.th32ProcessID) procH = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pentry.th32ProcessID); if (procH && GetProcessTimes(procH, (FILETIME *) &creation, (FILETIME *) &exit, (FILETIME *) &kernel, (FILETIME *) &user) ) { user += kernel; proc_k_u_time += user; if (pentry.th32ProcessID==the_rti.pid) { process_k_u_time = user; //nb_threads = pentry.cntThreads; } } if (procH) CloseHandle(procH); } while (Process32Next(hSnapShot, &pentry)); } CloseHandle(hSnapShot); proc_k_u_time /= 10; } if (!process_k_u_time) { HANDLE procH = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, the_rti.pid); if (procH && GetProcessTimes(procH, (FILETIME *) &creation, (FILETIME *) &exit, (FILETIME *) &kernel, (FILETIME *) &user) ) { process_k_u_time = user + kernel; } if (procH) CloseHandle(procH); if (!process_k_u_time) return GF_FALSE; } process_k_u_time /= 10; /*this won't cost a lot*/ if (MyGetProcessMemoryInfo) { PROCESS_MEMORY_COUNTERS pmc; HANDLE procH = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, the_rti.pid); MyGetProcessMemoryInfo(procH, &pmc, sizeof (pmc)); the_rti.process_memory = pmc.WorkingSetSize; if (procH) CloseHandle(procH); } /*THIS IS VERY HEAVY (eats up mem and time) - only perform if requested*/ else if (flags & GF_RTI_PROCESS_MEMORY) { HEAPLIST32 hlentry; HEAPENTRY32 hentry; the_rti.process_memory = 0; hlentry.dwSize = sizeof(HEAPLIST32); hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPHEAPLIST, the_rti.pid); if (hSnapShot && Heap32ListFirst(hSnapShot, &hlentry)) { do { hentry.dwSize = sizeof(hentry); if (Heap32First(&hentry, hlentry.th32ProcessID, hlentry.th32HeapID)) { do { the_rti.process_memory += hentry.dwBlockSize; } while (Heap32Next(&hentry)); } } while (Heap32ListNext(hSnapShot, &hlentry)); } CloseHandle(hSnapShot); } #endif the_rti.sampling_instant = last_update_time; if (last_update_time) { the_rti.sampling_period_duration = entry_time - last_update_time; the_rti.process_cpu_time_diff = (u32) ((process_k_u_time - last_process_k_u_time)/1000); #if defined(_WIN32_WCE) the_rti.total_cpu_time_diff = (u32) ((total_cpu_time - last_total_k_u_time)/1000); /*we're not that accurate....*/ if (the_rti.total_cpu_time_diff > the_rti.sampling_period_duration) the_rti.sampling_period_duration = the_rti.total_cpu_time_diff; /*rough values*/ the_rti.cpu_idle_time = the_rti.sampling_period_duration - the_rti.total_cpu_time_diff; if (!the_rti.sampling_period_duration) the_rti.sampling_period_duration=1; the_rti.total_cpu_usage = (u32) (100 * the_rti.total_cpu_time_diff / the_rti.sampling_period_duration); if (the_rti.total_cpu_time_diff + the_rti.cpu_idle_time==0) the_rti.total_cpu_time_diff ++; the_rti.process_cpu_usage = (u32) (100*the_rti.process_cpu_time_diff / (the_rti.total_cpu_time_diff + the_rti.cpu_idle_time) ); #else /*oops, we have no choice but to assume 100% cpu usage during this period*/ if (!proc_k_u_time) { the_rti.total_cpu_time_diff = the_rti.sampling_period_duration; proc_k_u_time = last_proc_k_u_time + the_rti.sampling_period_duration; the_rti.cpu_idle_time = 0; the_rti.total_cpu_usage = 100; if (the_rti.sampling_period_duration) the_rti.process_cpu_usage = (u32) (100*the_rti.process_cpu_time_diff / the_rti.sampling_period_duration); } else { u64 samp_sys_time, idle; the_rti.total_cpu_time_diff = (u32) ((proc_k_u_time - last_proc_k_u_time)/1000); /*we're not that accurate....*/ if (the_rti.total_cpu_time_diff > the_rti.sampling_period_duration) { the_rti.sampling_period_duration = the_rti.total_cpu_time_diff; } if (!proc_idle_time) proc_idle_time = last_proc_idle_time + (the_rti.sampling_period_duration - the_rti.total_cpu_time_diff); samp_sys_time = proc_k_u_time - last_proc_k_u_time; idle = proc_idle_time - last_proc_idle_time; the_rti.cpu_idle_time = (u32) (idle/1000); if (samp_sys_time) { the_rti.total_cpu_usage = (u32) ( (samp_sys_time - idle) / (samp_sys_time / 100) ); the_rti.process_cpu_usage = (u32) (100*the_rti.process_cpu_time_diff / (samp_sys_time/1000)); } } #endif } last_update_time = entry_time; last_process_k_u_time = process_k_u_time; GlobalMemoryStatus(&ms); the_rti.physical_memory = ms.dwTotalPhys; #ifdef GPAC_MEMORY_TRACKING the_rti.gpac_memory = (u64) gpac_allocated_memory; #endif the_rti.physical_memory_avail = ms.dwAvailPhys; #if defined(_WIN32_WCE) last_total_k_u_time = total_cpu_time; if (!the_rti.process_memory) the_rti.process_memory = mem_usage_at_startup - ms.dwAvailPhys; #else last_proc_idle_time = proc_idle_time; last_proc_k_u_time = proc_k_u_time; #endif if (!the_rti.gpac_memory) the_rti.gpac_memory = the_rti.process_memory; memcpy(rti, &the_rti, sizeof(GF_SystemRTInfo)); return GF_TRUE; } #elif defined(GPAC_CONFIG_DARWIN) && !defined(GPAC_IPHONE) #include <sys/types.h> #include <sys/sysctl.h> #include <sys/vmmeter.h> #include <mach/mach_init.h> #include <mach/mach_host.h> #include <mach/mach_port.h> #include <mach/mach_traps.h> #include <mach/task_info.h> #include <mach/thread_info.h> #include <mach/thread_act.h> #include <mach/vm_region.h> #include <mach/vm_map.h> #include <mach/task.h> #if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1060 #include <mach/shared_region.h> #else #include <mach/shared_memory_server.h> #endif #include <mach/mach_error.h> static u64 total_physical_memory = 0; Bool gf_sys_get_rti_os(u32 refresh_time_ms, GF_SystemRTInfo *rti, u32 flags) { size_t length; u32 entry_time, i, percent; int mib[6]; u64 result; int pagesize; u64 process_u_k_time; double utime, stime; vm_statistics_data_t vmstat; task_t task; kern_return_t error; thread_array_t thread_table; unsigned table_size; thread_basic_info_t thi; thread_basic_info_data_t thi_data; struct task_basic_info ti; mach_msg_type_number_t count = HOST_VM_INFO_COUNT, size = sizeof(ti); entry_time = gf_sys_clock(); if (last_update_time && (entry_time - last_update_time < refresh_time_ms)) { memcpy(rti, &the_rti, sizeof(GF_SystemRTInfo)); return 0; } mib[0] = CTL_HW; mib[1] = HW_PAGESIZE; length = sizeof(pagesize); if (sysctl(mib, 2, &pagesize, &length, NULL, 0) < 0) { return 0; } if (host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vmstat, &count) != KERN_SUCCESS) { return 0; } the_rti.physical_memory = (vmstat.wire_count + vmstat.active_count + vmstat.inactive_count + vmstat.free_count)* pagesize; the_rti.physical_memory_avail = vmstat.free_count * pagesize; if (!total_physical_memory) { mib[0] = CTL_HW; mib[1] = HW_MEMSIZE; length = sizeof(u64); if (sysctl(mib, 2, &result, &length, NULL, 0) >= 0) { total_physical_memory = result; } } the_rti.physical_memory = total_physical_memory; error = task_for_pid(mach_task_self(), the_rti.pid, &task); if (error) { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[RTI] Cannot get process task for PID %d: error %d\n", the_rti.pid, error)); return 0; } error = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&ti, &size); if (error) { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[RTI] Cannot get process task info (PID %d): error %d\n", the_rti.pid, error)); return 0; } percent = 0; utime = ti.user_time.seconds + ti.user_time.microseconds * 1e-6; stime = ti.system_time.seconds + ti.system_time.microseconds * 1e-6; error = task_threads(task, &thread_table, &table_size); if (error != KERN_SUCCESS) { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[RTI] Cannot get threads task for PID %d: error %d\n", the_rti.pid, error)); return 0; } thi = &thi_data; for (i = 0; i != table_size; ++i) { count = THREAD_BASIC_INFO_COUNT; error = thread_info(thread_table[i], THREAD_BASIC_INFO, (thread_info_t)thi, &count); if (error != KERN_SUCCESS) { mach_error("[RTI] Unexpected thread_info() call return", error); GF_LOG(GF_LOG_WARNING, GF_LOG_CORE, ("[RTI] Unexpected thread info for PID %d\n", the_rti.pid)); break; } if ((thi->flags & TH_FLAGS_IDLE) == 0) { utime += thi->user_time.seconds + thi->user_time.microseconds * 1e-6; stime += thi->system_time.seconds + thi->system_time.microseconds * 1e-6; percent += (u32) (100 * (double)thi->cpu_usage / TH_USAGE_SCALE); } } vm_deallocate(mach_task_self(), (vm_offset_t)thread_table, table_size * sizeof(thread_array_t)); mach_port_deallocate(mach_task_self(), task); process_u_k_time = utime + stime; the_rti.sampling_instant = last_update_time; if (last_update_time) { the_rti.sampling_period_duration = (entry_time - last_update_time); the_rti.process_cpu_time_diff = (process_u_k_time - last_process_k_u_time) * 10; the_rti.total_cpu_time_diff = the_rti.sampling_period_duration; /*TODO*/ the_rti.cpu_idle_time = 0; the_rti.total_cpu_usage = 0; if (!the_rti.process_cpu_time_diff) the_rti.process_cpu_time_diff = the_rti.total_cpu_time_diff; the_rti.process_cpu_usage = percent; } else { mem_at_startup = the_rti.physical_memory_avail; } the_rti.process_memory = mem_at_startup - the_rti.physical_memory_avail; #ifdef GPAC_MEMORY_TRACKING the_rti.gpac_memory = gpac_allocated_memory; #endif last_process_k_u_time = process_u_k_time; last_cpu_idle_time = 0; last_update_time = entry_time; memcpy(rti, &the_rti, sizeof(GF_SystemRTInfo)); return 1; } //linux #else Bool gf_sys_get_rti_os(u32 refresh_time_ms, GF_SystemRTInfo *rti, u32 flags) { u32 entry_time; u64 process_u_k_time; u32 u_k_time, idle_time; #if 0 char szProc[100]; #endif char line[2048]; FILE *f; assert(sys_init); entry_time = gf_sys_clock(); if (last_update_time && (entry_time - last_update_time < refresh_time_ms)) { memcpy(rti, &the_rti, sizeof(GF_SystemRTInfo)); return 0; } u_k_time = idle_time = 0; f = gf_fopen("/proc/stat", "r"); if (f) { u32 k_time, nice_time, u_time; if (fgets(line, 128, f) != NULL) { if (sscanf(line, "cpu %u %u %u %u\n", &u_time, &k_time, &nice_time, &idle_time) == 4) { u_k_time = u_time + k_time + nice_time; } } gf_fclose(f); } process_u_k_time = 0; the_rti.process_memory = 0; /*FIXME? under LinuxThreads this will only fetch stats for the calling thread, we would have to enumerate /proc to get the complete CPU usage of all therads of the process...*/ #if 0 sprintf(szProc, "/proc/%d/stat", the_rti.pid); f = gf_fopen(szProc, "r"); if (f) { fflush(f); if (fgets(line, 2048, f) != NULL) { char state; char *start; long cutime, cstime, priority, nice, itrealvalue, rss; int exit_signal, processor; unsigned long flags, minflt, cminflt, majflt, cmajflt, utime, stime,starttime, vsize, rlim, startcode, endcode, startstack, kstkesp, kstkeip, signal, blocked, sigignore, sigcatch, wchan, nswap, cnswap, rem; int ppid, pgrp ,session, tty_nr, tty_pgrp, res; start = strchr(line, ')'); if (start) start += 2; else { start = strchr(line, ' '); start++; } res = sscanf(start,"%c %d %d %d %d %d %lu %lu %lu %lu \ %lu %lu %lu %ld %ld %ld %ld %ld %ld %lu \ %lu %ld %lu %lu %lu %lu %lu %lu %lu %lu \ %lu %lu %lu %lu %lu %d %d", &state, &ppid, &pgrp, &session, &tty_nr, &tty_pgrp, &flags, &minflt, &cminflt, &majflt, &cmajflt, &utime, &stime, &cutime, &cstime, &priority, &nice, &itrealvalue, &rem, &starttime, &vsize, &rss, &rlim, &startcode, &endcode, &startstack, &kstkesp, &kstkeip, &signal, &blocked, &sigignore, &sigcatch, &wchan, &nswap, &cnswap, &exit_signal, &processor); if (res) process_u_k_time = (u64) (cutime + cstime); else { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[RTI] PROC %s parse error\n", szProc)); } } else { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[RTI] error reading pid/stat\n\n", szProc)); } gf_fclose(f); } else { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[RTI] cannot open %s\n", szProc)); } sprintf(szProc, "/proc/%d/status", the_rti.pid); f = gf_fopen(szProc, "r"); if (f) { while (fgets(line, 1024, f) != NULL) { if (!strnicmp(line, "VmSize:", 7)) { sscanf(line, "VmSize: %"LLD" kB", &the_rti.process_memory); the_rti.process_memory *= 1024; } } gf_fclose(f); } else { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[RTI] cannot open %s\n", szProc)); } #endif #ifndef GPAC_IPHONE the_rti.physical_memory = the_rti.physical_memory_avail = 0; f = gf_fopen("/proc/meminfo", "r"); if (f) { while (fgets(line, 1024, f) != NULL) { if (!strnicmp(line, "MemTotal:", 9)) { sscanf(line, "MemTotal: "LLU" kB", &the_rti.physical_memory); the_rti.physical_memory *= 1024; } else if (!strnicmp(line, "MemFree:", 8)) { sscanf(line, "MemFree: "LLU" kB", &the_rti.physical_memory_avail); the_rti.physical_memory_avail *= 1024; break; } } gf_fclose(f); } else { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[RTI] cannot open /proc/meminfo\n")); } #endif the_rti.sampling_instant = last_update_time; if (last_update_time) { the_rti.sampling_period_duration = (entry_time - last_update_time); the_rti.process_cpu_time_diff = (u32) (process_u_k_time - last_process_k_u_time) * 10; /*oops, we have no choice but to assume 100% cpu usage during this period*/ if (!u_k_time) { the_rti.total_cpu_time_diff = the_rti.sampling_period_duration; u_k_time = (u32) (last_cpu_u_k_time + the_rti.sampling_period_duration); the_rti.cpu_idle_time = 0; the_rti.total_cpu_usage = 100; if (!the_rti.process_cpu_time_diff) the_rti.process_cpu_time_diff = the_rti.total_cpu_time_diff; the_rti.process_cpu_usage = (u32) ( 100 * the_rti.process_cpu_time_diff / the_rti.sampling_period_duration); } else { u64 samp_sys_time; /*move to ms (/proc/stat gives times in 100 ms unit*/ the_rti.total_cpu_time_diff = (u32) (u_k_time - last_cpu_u_k_time)*10; /*we're not that accurate....*/ if (the_rti.total_cpu_time_diff > the_rti.sampling_period_duration) the_rti.sampling_period_duration = the_rti.total_cpu_time_diff; if (!idle_time) idle_time = (the_rti.sampling_period_duration - the_rti.total_cpu_time_diff)/10; samp_sys_time = u_k_time - last_cpu_u_k_time; the_rti.cpu_idle_time = (u32) (idle_time - last_cpu_idle_time); the_rti.total_cpu_usage = (u32) ( 100 * samp_sys_time / (the_rti.cpu_idle_time + samp_sys_time ) ); /*move to ms (/proc/stat gives times in 100 ms unit*/ the_rti.cpu_idle_time *= 10; if (!the_rti.process_cpu_time_diff) the_rti.process_cpu_time_diff = the_rti.total_cpu_time_diff; the_rti.process_cpu_usage = (u32) ( 100 * the_rti.process_cpu_time_diff / (the_rti.cpu_idle_time + 10*samp_sys_time ) ); } } else { mem_at_startup = the_rti.physical_memory_avail; } the_rti.process_memory = mem_at_startup - the_rti.physical_memory_avail; #ifdef GPAC_MEMORY_TRACKING the_rti.gpac_memory = gpac_allocated_memory; #endif last_process_k_u_time = process_u_k_time; last_cpu_idle_time = idle_time; last_cpu_u_k_time = u_k_time; last_update_time = entry_time; memcpy(rti, &the_rti, sizeof(GF_SystemRTInfo)); return 1; } #endif GF_EXPORT Bool gf_sys_get_rti(u32 refresh_time_ms, GF_SystemRTInfo *rti, u32 flags) { Bool res = gf_sys_get_rti_os(refresh_time_ms, rti, flags); if (res) { if (!rti->process_memory) rti->process_memory = memory_at_gpac_startup - rti->physical_memory_avail; if (!rti->gpac_memory) rti->gpac_memory = memory_at_gpac_startup - rti->physical_memory_avail; } return res; } GF_EXPORT char * gf_get_default_cache_directory() { char szPath[GF_MAX_PATH]; char* root_tmp; size_t len; #ifdef _WIN32_WCE strcpy(szPath, "\\windows\\temp" ); #elif defined(WIN32) GetTempPath(GF_MAX_PATH, szPath); #else strcpy(szPath, "/tmp"); #endif root_tmp = gf_strdup(szPath); len = strlen(szPath); if (szPath[len-1] != GF_PATH_SEPARATOR) { szPath[len] = GF_PATH_SEPARATOR; szPath[len+1] = 0; } strcat(szPath, "gpac_cache"); if ( !gf_dir_exists(szPath) && gf_mkdir(szPath)!=GF_OK ) { return root_tmp; } gf_free(root_tmp); return gf_strdup(szPath); } GF_EXPORT Bool gf_sys_get_battery_state(Bool *onBattery, u32 *onCharge, u32*level, u32 *batteryLifeTime, u32 *batteryFullLifeTime) { #if defined(_WIN32_WCE) SYSTEM_POWER_STATUS_EX sps; GetSystemPowerStatusEx(&sps, 0); if (onBattery) *onBattery = sps.ACLineStatus ? 0 : 1; if (onCharge) *onCharge = (sps.BatteryFlag & BATTERY_FLAG_CHARGING) ? 1 : 0; if (level) *level = sps.BatteryLifePercent; if (batteryLifeTime) *batteryLifeTime = sps.BatteryLifeTime; if (batteryFullLifeTime) *batteryFullLifeTime = sps.BatteryFullLifeTime; #elif defined(WIN32) SYSTEM_POWER_STATUS sps; GetSystemPowerStatus(&sps); if (onBattery) *onBattery = sps.ACLineStatus ? GF_FALSE : GF_TRUE; if (onCharge) *onCharge = (sps.BatteryFlag & BATTERY_FLAG_CHARGING) ? 1 : 0; if (level) *level = sps.BatteryLifePercent; if (batteryLifeTime) *batteryLifeTime = sps.BatteryLifeTime; if (batteryFullLifeTime) *batteryFullLifeTime = sps.BatteryFullLifeTime; #endif return GF_TRUE; } struct GF_GlobalLock { const char * resourceName; }; #ifndef WIN32 #define CPF_CLOEXEC 1 #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> struct _GF_GlobalLock_opaque { char * resourceName; char * pidFile; int fd; }; GF_GlobalLock * gf_create_PID_file( const char * resourceName ) { const char * prefix = "/gpac_lock_"; const char * dir = gf_get_default_cache_directory(); char * pidfile; int flags; int status; pidfile = gf_malloc(strlen(dir)+strlen(prefix)+strlen(resourceName)+1); strcpy(pidfile, dir); strcat(pidfile, prefix); /* Use only valid names for file */ { const char *res; char * pid = &(pidfile[strlen(pidfile)]); for (res = resourceName; *res ; res++) { if (*res >= 'A' && *res <= 'z') *pid = * res; else *pid = '_'; pid++; } *pid = '\0'; } int fd = open(pidfile, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); if (fd == -1) goto exit; /* Get the flags */ flags = fcntl(fd, F_GETFD); if (flags == -1) { goto exit; } /* Set FD_CLOEXEC, so exclusive lock will be removed on exit, so even if GPAC crashes, * lock will be allowed for next instance */ flags |= FD_CLOEXEC; /* Now, update the flags */ if (fcntl(fd, F_SETFD, flags) == -1) { goto exit; } /* Now, we try to lock the file */ { struct flock fl; fl.l_type = F_WRLCK; fl.l_whence = SEEK_SET; fl.l_start = fl.l_len = 0; status = fcntl(fd, F_SETLK, &fl); } if (status == -1) { goto exit; } if (ftruncate(fd, 0) == -1) { goto exit; } /* Write the PID */ { int sz = 100; char * buf = gf_malloc( sz ); sz = snprintf(buf, sz, "%ld\n", (long) getpid()); if (write(fd, buf, sz) != sz) { gf_free(buf); goto exit; } } sync(); { GF_GlobalLock * lock = gf_malloc( sizeof(GF_GlobalLock)); lock->resourceName = gf_strdup(resourceName); lock->pidFile = pidfile; lock->fd = fd; return lock; } exit: if (fd >= 0) close(fd); return NULL; } #else /* WIN32 */ struct _GF_GlobalLock_opaque { char * resourceName; HANDLE hMutex; /*a named mutex is a system-mode object on windows*/ }; #endif GF_EXPORT GF_GlobalLock * gf_global_resource_lock(const char * resourceName) { #ifdef WIN32 #ifdef _WIN32_WCE unsigned short sWResourceName[MAX_PATH]; #endif DWORD lastErr; GF_GlobalLock *lock = gf_malloc(sizeof(GF_GlobalLock)); lock->resourceName = gf_strdup(resourceName); /*first ensure mutex is created*/ #ifdef _WIN32_WCE CE_CharToWide((char *)resourceName, sWResourceName); lock->hMutex = CreateMutex(NULL, TRUE, sWResourceName); #else lock->hMutex = CreateMutex(NULL, TRUE, resourceName); #endif lastErr = GetLastError(); if (lastErr && lastErr == ERROR_ALREADY_EXISTS) return NULL; if (!lock->hMutex) { GF_LOG(GF_LOG_ERROR, GF_LOG_MUTEX, ("[Mutex] Couldn't create mutex for global lock: %d\n", lastErr)); return NULL; } /*then lock it*/ switch (WaitForSingleObject(lock->hMutex, INFINITE)) { case WAIT_ABANDONED: case WAIT_TIMEOUT: assert(0); /*serious error: someone has modified the object elsewhere*/ GF_LOG(GF_LOG_ERROR, GF_LOG_MUTEX, ("[Mutex] Couldn't get the global lock\n")); gf_global_resource_unlock(lock); return NULL; } return lock; #else /* WIN32 */ return gf_create_PID_file(resourceName); #endif /* WIN32 */ } /*! * Unlock a previouly locked resource * \param lock The resource to unlock * \return GF_OK if evertything went fine */ GF_EXPORT GF_Err gf_global_resource_unlock(GF_GlobalLock * lock) { if (!lock) return GF_BAD_PARAM; #ifndef WIN32 assert( lock->pidFile); close(lock->fd); if (unlink(lock->pidFile)) perror("Failed to unlink lock file"); gf_free(lock->pidFile); lock->pidFile = NULL; lock->fd = -1; #else /* WIN32 */ { /*MSDN: "The mutex object is destroyed when its last handle has been closed."*/ BOOL ret = ReleaseMutex(lock->hMutex); if (!ret) { DWORD err = GetLastError(); GF_LOG(GF_LOG_ERROR, GF_LOG_MUTEX, ("[Mutex] Couldn't release mutex for global lock: %d\n", err)); } ret = CloseHandle(lock->hMutex); if (!ret) { DWORD err = GetLastError(); GF_LOG(GF_LOG_ERROR, GF_LOG_MUTEX, ("[Mutex] Couldn't destroy mutex for global lock: %d\n", err)); } } #endif if (lock->resourceName) gf_free(lock->resourceName); lock->resourceName = NULL; gf_free(lock); return GF_OK; } #ifdef GPAC_ANDROID fm_callback_func fm_cbk = NULL; static void *fm_cbk_obj = NULL; void gf_fm_request_set_callback(void *cbk_obj, fm_callback_func cbk_func) { fm_cbk = cbk_func; fm_cbk_obj = cbk_obj; } void gf_fm_request_call(u32 type, u32 param, int *value) { if (fm_cbk) fm_cbk(fm_cbk_obj, type, param, value); } #endif //GPAC_ANDROID GF_EXPORT s32 gf_gettimeofday(struct timeval *tp, void *tz) { return gettimeofday(tp, tz); } static u32 ntp_shift = GF_NTP_SEC_1900_TO_1970; GF_EXPORT void gf_net_set_ntp_shift(s32 shift) { ntp_shift = GF_NTP_SEC_1900_TO_1970 + shift; } /* NTP tools */ GF_EXPORT void gf_net_get_ntp(u32 *sec, u32 *frac) { u64 frac_part; struct timeval now; gettimeofday(&now, NULL); if (sec) { *sec = (u32) (now.tv_sec) + ntp_shift; } if (frac) { frac_part = now.tv_usec * 0xFFFFFFFFULL; frac_part /= 1000000; *frac = (u32) ( frac_part ); } } GF_EXPORT u64 gf_net_get_ntp_ts() { u64 res; u32 sec, frac; gf_net_get_ntp(&sec, &frac); res = sec; res<<= 32; res |= frac; return res; } GF_EXPORT s32 gf_net_get_ntp_diff_ms(u64 ntp) { u32 remote_s, remote_f, local_s, local_f; s64 local, remote; remote_s = (ntp >> 32); remote_f = (u32) (ntp & 0xFFFFFFFFULL); gf_net_get_ntp(&local_s, &local_f); local = local_s; local *= 1000; local += ((u64) local_f)*1000 / 0xFFFFFFFFULL; remote = remote_s; remote *= 1000; remote += ((u64) remote_f)*1000 / 0xFFFFFFFFULL; return (s32) (local - remote); } GF_EXPORT s32 gf_net_get_timezone() { #if defined(_WIN32_WCE) return 0; #else //this has been commented due to some reports of broken implementation on some systems ... // s32 val = timezone; // return val; /*FIXME - avoid errors at midnight when estimating timezone this does not work !!*/ s32 t_timezone; struct tm t_gmt, t_local; time_t t_time; t_time = time(NULL); t_gmt = *gmtime(&t_time); t_local = *localtime(&t_time); t_timezone = (t_gmt.tm_hour - t_local.tm_hour) * 3600 + (t_gmt.tm_min - t_local.tm_min) * 60; return t_timezone; #endif } //no mkgmtime on mingw..., use our own #if (defined(WIN32) && defined(__GNUC__)) static Bool leap_year(u32 year) { year += 1900; return (year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0) ? GF_TRUE : GF_FALSE; } static time_t gf_mktime_utc(struct tm *tm) { static const u32 days_per_month[2][12] = { {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} }; time_t time=0; int i; for (i=70; i<tm->tm_year; i++) { time += leap_year(i) ? 366 : 365; } for (i=0; i<tm->tm_mon; ++i) { time += days_per_month[leap_year(tm->tm_year)][i]; } time += tm->tm_mday - 1; time *= 24; time += tm->tm_hour; time *= 60; time += tm->tm_min; time *= 60; time += tm->tm_sec; return time; } #elif defined(WIN32) static time_t gf_mktime_utc(struct tm *tm) { return _mkgmtime(tm); } #elif defined(GPAC_ANDROID) #include <time64.h> #if defined(__LP64__) static time_t gf_mktime_utc(struct tm *tm) { return timegm64(tm); } #else static time_t gf_mktime_utc(struct tm *tm) { static const time_t kTimeMax = ~(1L << (sizeof(time_t) * CHAR_BIT - 1)); static const time_t kTimeMin = (1L << (sizeof(time_t) * CHAR_BIT - 1)); time64_t result = timegm64(tm); if (result < kTimeMin || result > kTimeMax) return -1; return result; } #endif #else static time_t gf_mktime_utc(struct tm *tm) { return timegm(tm); } #endif GF_EXPORT u64 gf_net_parse_date(const char *val) { u64 current_time; char szDay[50], szMonth[50]; u32 year, month, day, h, m, s, ms; s32 oh, om; Float secs; Bool neg_time_zone = GF_FALSE; #ifdef _WIN32_WCE SYSTEMTIME syst; FILETIME filet; #else struct tm t; memset(&t, 0, sizeof(struct tm)); #endif szDay[0] = szMonth[0] = 0; year = month = day = h = m = s = 0; oh = om = 0; secs = 0; if (sscanf(val, "%d-%d-%dT%d:%d:%gZ", &year, &month, &day, &h, &m, &secs) == 6) { } else if (sscanf(val, "%d-%d-%dT%d:%d:%g-%d:%d", &year, &month, &day, &h, &m, &secs, &oh, &om) == 8) { neg_time_zone = GF_TRUE; } else if (sscanf(val, "%d-%d-%dT%d:%d:%g+%d:%d", &year, &month, &day, &h, &m, &secs, &oh, &om) == 8) { } else if (sscanf(val, "%3s, %d %3s %d %d:%d:%d", szDay, &day, szMonth, &year, &h, &m, &s)==7) { secs = (Float) s; } else if (sscanf(val, "%9s, %d-%3s-%d %02d:%02d:%02d GMT", szDay, &day, szMonth, &year, &h, &m, &s)==7) { secs = (Float) s; } else if (sscanf(val, "%3s %3s %d %02d:%02d:%02d %d", szDay, szMonth, &day, &year, &h, &m, &s)==7) { secs = (Float) s; } else { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[Core] Cannot parse date string %s\n", val)); return 0; } if (month) { month -= 1; } else { if (!strcmp(szMonth, "Jan")) month = 0; else if (!strcmp(szMonth, "Feb")) month = 1; else if (!strcmp(szMonth, "Mar")) month = 2; else if (!strcmp(szMonth, "Apr")) month = 3; else if (!strcmp(szMonth, "May")) month = 4; else if (!strcmp(szMonth, "Jun")) month = 5; else if (!strcmp(szMonth, "Jul")) month = 6; else if (!strcmp(szMonth, "Aug")) month = 7; else if (!strcmp(szMonth, "Sep")) month = 8; else if (!strcmp(szMonth, "Oct")) month = 9; else if (!strcmp(szMonth, "Nov")) month = 10; else if (!strcmp(szMonth, "Dec")) month = 11; } #ifdef _WIN32_WCE memset(&syst, 0, sizeof(SYSTEMTIME)); syst.wYear = year; syst.wMonth = month + 1; syst.wDay = day; syst.wHour = h; syst.wMinute = m; syst.wSecond = (u32) secs; SystemTimeToFileTime(&syst, &filet); current_time = (u64) ((*(LONGLONG *) &filet - TIMESPEC_TO_FILETIME_OFFSET) / 10000000); #else t.tm_year = year>1000 ? year-1900 : year; t.tm_mday = day; t.tm_hour = h; t.tm_min = m; t.tm_sec = (u32) secs; t.tm_mon = month; if (strlen(szDay) ) { if (!strcmp(szDay, "Mon") || !strcmp(szDay, "Monday")) t.tm_wday = 0; else if (!strcmp(szDay, "Tue") || !strcmp(szDay, "Tuesday")) t.tm_wday = 1; else if (!strcmp(szDay, "Wed") || !strcmp(szDay, "Wednesday")) t.tm_wday = 2; else if (!strcmp(szDay, "Thu") || !strcmp(szDay, "Thursday")) t.tm_wday = 3; else if (!strcmp(szDay, "Fri") || !strcmp(szDay, "Friday")) t.tm_wday = 4; else if (!strcmp(szDay, "Sat") || !strcmp(szDay, "Saturday")) t.tm_wday = 5; else if (!strcmp(szDay, "Sun") || !strcmp(szDay, "Sunday")) t.tm_wday = 6; } current_time = gf_mktime_utc(&t); if ((s64) current_time == -1) { //use 1 ms return 1; } if (current_time == 0) { //use 1 ms return 1; } #endif if (om || oh) { s32 diff = (60*oh + om)*60; if (neg_time_zone) diff = -diff; current_time = current_time + diff; } current_time *= 1000; ms = (u32) ( (secs - (u32) secs) * 1000); return current_time + ms; } GF_EXPORT u64 gf_net_get_utc() { u64 current_time; Double msec; u32 sec, frac; gf_net_get_ntp(&sec, &frac); current_time = sec - GF_NTP_SEC_1900_TO_1970; current_time *= 1000; msec = frac*1000.0; msec /= 0xFFFFFFFF; current_time += (u64) msec; return current_time; } GF_EXPORT GF_Err gf_bin128_parse(const char *string, bin128 value) { u32 len; u32 i=0; if (!strnicmp(string, "0x", 2)) string += 2; len = (u32) strlen(string); if (len >= 32) { u32 j; for (j=0; j<len; j+=2) { u32 v; char szV[5]; while (string[j] && !isalnum(string[j])) j++; if (!string[j]) break; sprintf(szV, "%c%c", string[j], string[j+1]); sscanf(szV, "%x", &v); value[i] = v; i++; } } if (i != 16) { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[CORE] 128bit blob is not 16-bytes long: %s\n", string)); return GF_BAD_PARAM; } return GF_OK; }
null
/* * GPAC - Multimedia Framework C SDK * * Authors: Jean Le Feuvre * Copyright (c) Telecom ParisTech 2000-2012 * All rights reserved * * This file is part of GPAC / common tools sub-project * * GPAC is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * GPAC is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * */ #include <gpac/tools.h> #include <gpac/network.h> #if defined(_WIN32_WCE) #include <winbase.h> #include <winsock.h> #include <tlhelp32.h> //#include <direct.h> #if !defined(__GNUC__) #pragma comment(lib, "toolhelp") #endif #elif defined(WIN32) #include <time.h> #include <sys/timeb.h> #include <io.h> #include <windows.h> #include <tlhelp32.h> #include <direct.h> #if !defined(__GNUC__) #pragma comment(lib, "winmm") #endif #else #include <time.h> #include <sys/stat.h> #include <sys/time.h> #include <dirent.h> #include <unistd.h> #include <sys/times.h> #include <sys/resource.h> #ifndef __BEOS__ #include <errno.h> #endif #define SLEEP_ABS_SELECT 1 static u32 sys_start_time = 0; static u64 sys_start_time_hr = 0; #endif #ifndef _WIN32_WCE #include <locale.h> #endif #ifndef WIN32 GF_EXPORT u32 gf_sys_clock() { struct timeval now; gettimeofday(&now, NULL); return (u32) ( ( (now.tv_sec)*1000 + (now.tv_usec) / 1000) - sys_start_time ); } GF_EXPORT u64 gf_sys_clock_high_res() { struct timeval now; gettimeofday(&now, NULL); return (now.tv_sec)*1000000 + (now.tv_usec) - sys_start_time_hr; } #endif GF_EXPORT void gf_sleep(u32 ms) { #ifdef WIN32 Sleep(ms); #else s32 sel_err; struct timeval tv; #ifndef SLEEP_ABS_SELECT u32 prev, now, elapsed; #endif #ifdef SLEEP_ABS_SELECT tv.tv_sec = ms/1000; tv.tv_usec = (ms%1000)*1000; #else prev = gf_sys_clock(); #endif do { errno = 0; #ifndef SLEEP_ABS_SELECT now = gf_sys_clock(); elapsed = (now - prev); if ( elapsed >= ms ) { break; } prev = now; ms -= elapsed; tv.tv_sec = ms/1000; tv.tv_usec = (ms%1000)*1000; #endif sel_err = select(0, NULL, NULL, NULL, &tv); } while ( sel_err && (errno == EINTR) ); #endif } #ifndef gettimeofday #ifdef _WIN32_WCE #include <time.h> //#include <wce_time.h> /* * Author of first version (timeval.h): by Wu Yongwei * Author of Windows CE version: Mateusz Loskot (mateusz@loskot.net) * * All code here is considered in the public domain though we do wish our names * could be retained if anyone uses them. */ /* * Constants used internally by time functions. */ #ifndef _TM_DEFINED struct tm { int tm_sec; /* seconds after the minute - [0,59] */ int tm_min; /* minutes after the hour - [0,59] */ int tm_hour; /* hours since midnight - [0,23] */ int tm_mday; /* day of the month - [1,31] */ int tm_mon; /* months since January - [0,11] */ int tm_year; /* years since 1900 */ int tm_wday; /* days since Sunday - [0,6] */ int tm_yday; /* days since January 1 - [0,365] */ int tm_isdst; /* daylight savings time flag */ }; #define _TM_DEFINED #endif /* _TM_DEFINED */ #ifndef _TIMEZONE_DEFINED struct timezone { int tz_minuteswest; /* minutes W of Greenwich */ int tz_dsttime; /* type of dst correction */ }; #define _TIMEZONE_DEFINED #endif /* _TIMEZONE_DEFINED */ #if defined(_MSC_VER) || defined(__BORLANDC__) #define EPOCHFILETIME (116444736000000000i64) #else #define EPOCHFILETIME (116444736000000000LL) #endif int gettimeofday(struct timeval *tp, struct timezone *tzp) { SYSTEMTIME st; FILETIME ft; LARGE_INTEGER li; TIME_ZONE_INFORMATION tzi; __int64 t; static int tzflag; if (NULL != tp) { GetSystemTime(&st); SystemTimeToFileTime(&st, &ft); li.LowPart = ft.dwLowDateTime; li.HighPart = ft.dwHighDateTime; t = li.QuadPart; /* In 100-nanosecond intervals */ t -= EPOCHFILETIME; /* Offset to the Epoch time */ t /= 10; /* In microseconds */ tp->tv_sec = (long)(t / 1000000); tp->tv_usec = (long)(t % 1000000); } if (NULL != tzp) { GetTimeZoneInformation(&tzi); tzp->tz_minuteswest = tzi.Bias; if (tzi.StandardDate.wMonth != 0) { tzp->tz_minuteswest += tzi.StandardBias * 60; } if (tzi.DaylightDate.wMonth != 0) { tzp->tz_dsttime = 1; } else { tzp->tz_dsttime = 0; } } return 0; } #if _GPAC_UNUSED /* time between jan 1, 1601 and jan 1, 1970 in units of 100 nanoseconds FILETIME in Win32 is from jan 1, 1601 */ s32 __gettimeofday(struct timeval *tp, void *tz) { FILETIME ft; SYSTEMTIME st; s32 val; GetSystemTime(&st); SystemTimeToFileTime(&st, &ft); val = (s32) ((*(LONGLONG *) &ft - TIMESPEC_TO_FILETIME_OFFSET) / 10000000); tp->tv_sec = (u32) val; val = (s32 ) ((*(LONGLONG *) &ft - TIMESPEC_TO_FILETIME_OFFSET - ((LONGLONG) val * (LONGLONG) 10000000)) * 100); tp->tv_usec = val; return 0; } #endif #elif defined(WIN32) static s32 gettimeofday(struct timeval *tp, void *tz) { struct _timeb timebuffer; _ftime( &timebuffer ); tp->tv_sec = (long) (timebuffer.time); tp->tv_usec = timebuffer.millitm * 1000; return 0; } #endif #endif #ifdef _WIN32_WCE void CE_Assert(u32 valid, char *file, u32 line) { if (!valid) { char szBuf[2048]; u16 wcBuf[2048]; sprintf(szBuf, "File %s : line %d", file, line); CE_CharToWide(szBuf, wcBuf); MessageBox(NULL, wcBuf, _T("GPAC Assertion Failure"), MB_OK); exit(EXIT_FAILURE); } } void CE_WideToChar(unsigned short *w_str, char *str) { WideCharToMultiByte(CP_ACP, 0, w_str, -1, str, GF_MAX_PATH, NULL, NULL); } void CE_CharToWide(char *str, unsigned short *w_str) { MultiByteToWideChar(CP_ACP, 0, str, -1, w_str, GF_MAX_PATH); } #endif GF_EXPORT void gf_rand_init(Bool Reset) { if (Reset) { srand(1); } else { #if defined(_WIN32_WCE) srand( (u32) GetTickCount() ); #else srand( (u32) time(NULL) ); #endif } } GF_EXPORT u32 gf_rand() { return rand(); } #ifndef _WIN32_WCE #include <sys/stat.h> #endif GF_EXPORT void gf_utc_time_since_1970(u32 *sec, u32 *msec) { #if defined (WIN32) && !defined(_WIN32_WCE) struct _timeb tb; _ftime( &tb ); *sec = (u32) tb.time; *msec = tb.millitm; #else struct timeval tv; gettimeofday(&tv, NULL); *sec = (u32) tv.tv_sec; *msec = tv.tv_usec/1000; #endif } GF_EXPORT void gf_get_user_name(char *buf, u32 buf_size) { strcpy(buf, "mpeg4-user"); #if 0 s32 len; char *t; strcpy(buf, ""); len = 1024; GetUserName(buf, &len); if (!len) { t = getenv("USER"); if (t) strcpy(buf, t); } #endif #if 0 struct passwd *pw; pw = getpwuid(getuid()); strcpy(buf, ""); if (pw && pw->pw_name) strcpy(name, pw->pw_name); #endif } #ifndef WIN32 GF_EXPORT char * my_str_upr(char *str) { u32 i; for (i=0; i<strlen(str); i++) { str[i] = toupper(str[i]); } return str; } GF_EXPORT char * my_str_lwr(char *str) { u32 i; for (i=0; i<strlen(str); i++) { str[i] = tolower(str[i]); } return str; } #endif /*seems OK under mingw also*/ #ifdef WIN32 #ifdef _WIN32_WCE Bool gf_prompt_has_input() { return 0; } char gf_prompt_get_char() { return 0; } GF_EXPORT void gf_prompt_set_echo_off(Bool echo_off) { return; } #else #include <conio.h> #include <windows.h> Bool gf_prompt_has_input() { return kbhit(); } char gf_prompt_get_char() { return getchar(); } GF_EXPORT void gf_prompt_set_echo_off(Bool echo_off) { DWORD flags; HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE); BOOL ret = GetConsoleMode(hStdin, &flags); if (!ret) { DWORD err = GetLastError(); GF_LOG(GF_LOG_ERROR, GF_LOG_CONSOLE, ("[Console] GetConsoleMode() return with the following error code: %d\n", err)); } if (echo_off) flags &= ~ENABLE_ECHO_INPUT; else flags |= ENABLE_ECHO_INPUT; SetConsoleMode(hStdin, flags); } #endif #else /*linux kbhit/getchar- borrowed on debian mailing lists, (author Mike Brownlow)*/ #include <termios.h> static struct termios t_orig, t_new; static s32 ch_peek = -1; static void init_keyboard() { tcgetattr(0, &t_orig); t_new = t_orig; t_new.c_lflag &= ~ICANON; t_new.c_lflag &= ~ECHO; t_new.c_lflag &= ~ISIG; t_new.c_cc[VMIN] = 1; t_new.c_cc[VTIME] = 0; tcsetattr(0, TCSANOW, &t_new); } static void close_keyboard(Bool new_line) { tcsetattr(0,TCSANOW, &t_orig); if (new_line) fprintf(stderr, "\n"); } GF_EXPORT void gf_prompt_set_echo_off(Bool echo_off) { init_keyboard(); if (echo_off) t_orig.c_lflag &= ~ECHO; else t_orig.c_lflag |= ECHO; close_keyboard(0); } GF_EXPORT Bool gf_prompt_has_input() { u8 ch; s32 nread; pid_t fg = tcgetpgrp(STDIN_FILENO); //we are not foreground nor piped (used for IDEs), can't read stdin if ((fg!=-1) && (fg != getpgrp())) { return 0; } init_keyboard(); if (ch_peek != -1) return 1; t_new.c_cc[VMIN]=0; tcsetattr(0, TCSANOW, &t_new); nread = (s32) read(0, &ch, 1); t_new.c_cc[VMIN]=1; tcsetattr(0, TCSANOW, &t_new); if(nread == 1) { ch_peek = ch; return 1; } close_keyboard(0); return 0; } GF_EXPORT char gf_prompt_get_char() { char ch; if (ch_peek != -1) { ch = ch_peek; ch_peek = -1; close_keyboard(1); return ch; } if (0==read(0,&ch,1)) ch = 0; close_keyboard(1); return ch; } #endif static u32 sys_init = 0; static u32 last_update_time = 0; static u64 last_process_k_u_time = 0; GF_SystemRTInfo the_rti; #if defined(_WIN32_WCE) static LARGE_INTEGER frequency , init_counter; static u64 last_total_k_u_time = 0; static u32 mem_usage_at_startup = 0; #ifndef GetCurrentPermissions DWORD GetCurrentPermissions(); #endif #ifndef SetProcPermissions void SetProcPermissions(DWORD ); #endif #elif defined(WIN32) static LARGE_INTEGER frequency , init_counter; static u64 last_proc_idle_time = 0; static u64 last_proc_k_u_time = 0; static HINSTANCE psapi_hinst = NULL; typedef BOOL(WINAPI* NTGetSystemTimes)(VOID *,VOID *,VOID *); NTGetSystemTimes MyGetSystemTimes = NULL; typedef BOOL(WINAPI* NTGetProcessMemoryInfo)(HANDLE,VOID *,DWORD); NTGetProcessMemoryInfo MyGetProcessMemoryInfo = NULL; typedef int(WINAPI* NTQuerySystemInfo)(ULONG,PVOID,ULONG,PULONG); NTQuerySystemInfo MyQuerySystemInfo = NULL; #ifndef PROCESS_MEMORY_COUNTERS typedef struct _PROCESS_MEMORY_COUNTERS { DWORD cb; DWORD PageFaultCount; SIZE_T PeakWorkingSetSize; SIZE_T WorkingSetSize; SIZE_T QuotaPeakPagedPoolUsage; SIZE_T QuotaPagedPoolUsage; SIZE_T QuotaPeakNonPagedPoolUsage; SIZE_T QuotaNonPagedPoolUsage; SIZE_T PagefileUsage; SIZE_T PeakPagefileUsage; } PROCESS_MEMORY_COUNTERS; #endif #ifndef SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION typedef struct _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION { LARGE_INTEGER IdleTime; LARGE_INTEGER KernelTime; LARGE_INTEGER UserTime; LARGE_INTEGER Reserved1[2]; ULONG Reserved2; } SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION; #endif #else static u64 last_cpu_u_k_time = 0; static u64 last_cpu_idle_time = 0; static u64 mem_at_startup = 0; #endif #ifdef WIN32 static u32 (*OS_GetSysClock)(); u32 gf_sys_clock() { return OS_GetSysClock(); } static u64 (*OS_GetSysClockHR)(); u64 gf_sys_clock_high_res() { return OS_GetSysClockHR(); } #endif #ifdef WIN32 static u32 OS_GetSysClockHIGHRES() { LARGE_INTEGER now; QueryPerformanceCounter(&now); now.QuadPart -= init_counter.QuadPart; return (u32) ((now.QuadPart * 1000) / frequency.QuadPart); } static u64 OS_GetSysClockHIGHRES_FULL() { LARGE_INTEGER now; QueryPerformanceCounter(&now); now.QuadPart -= init_counter.QuadPart; return (u64) ((now.QuadPart * 1000000) / frequency.QuadPart); } static u32 OS_GetSysClockNORMAL() { #ifdef _WIN32_WCE return GetTickCount(); #else return timeGetTime(); #endif } static u64 OS_GetSysClockNORMAL_FULL() { u64 res = OS_GetSysClockNORMAL(); return res*1000; } #endif /* WIN32 */ #if defined(__sh__) /* Avoid exception for denormalized floating point values */ static int sh4_get_fpscr() { int ret; asm volatile ("sts fpscr,%0" : "=r" (ret)); return ret; } static void sh4_put_fpscr(int nv) { asm volatile ("lds %0,fpscr" : : "r" (nv)); } #define SH4_FPSCR_FR 0x00200000 #define SH4_FPSCR_SZ 0x00100000 #define SH4_FPSCR_PR 0x00080000 #define SH4_FPSCR_DN 0x00040000 #define SH4_FPSCR_RN 0x00000003 #define SH4_FPSCR_RN_N 0 #define SH4_FPSCR_RN_Z 1 extern int __fpscr_values[2]; void sh4_change_fpscr(int off, int on) { int b = sh4_get_fpscr(); off = ~off; off |= 0x00180000; on &= ~ 0x00180000; b &= off; b |= on; sh4_put_fpscr(b); __fpscr_values[0] &= off; __fpscr_values[0] |= on; __fpscr_values[1] &= off; __fpscr_values[1] |= on; } #endif #ifdef GPAC_MEMORY_TRACKING void gf_mem_enable_tracker(Bool enable_backtrace); #endif static u64 memory_at_gpac_startup = 0; static u32 gpac_argc = 0; const char **gpac_argv = NULL; GF_EXPORT void gf_sys_set_args(s32 argc, const char **argv) { //for OSX we allow overwrite of argc/argv due to different behavior between console-mode apps and GUI #if !defined(__DARWIN__) && !defined(__APPLE__) if (!gpac_argc && (argc>=0) ) #endif { gpac_argc = (u32) argc; gpac_argv = argv; } } GF_EXPORT u32 gf_sys_get_argc() { return gpac_argc; } GF_EXPORT const char *gf_sys_get_arg(u32 arg) { if (!gpac_argc || !gpac_argv) return NULL; if (arg>=gpac_argc) return NULL; return gpac_argv[arg]; } GF_EXPORT void gf_sys_init(GF_MemTrackerType mem_tracker_type) { if (!sys_init) { #if defined (WIN32) #if defined(_WIN32_WCE) MEMORYSTATUS ms; #else SYSTEM_INFO sysinfo; #endif #endif if (mem_tracker_type!=GF_MemTrackerNone) { #ifdef GPAC_MEMORY_TRACKING gf_mem_enable_tracker( (mem_tracker_type==GF_MemTrackerBackTrace) ? GF_TRUE : GF_FALSE); #endif } #ifndef GPAC_DISABLE_LOG /*by default log subsystem is initialized to error on all tools, and info on console to debug scripts*/ gf_log_set_tool_level(GF_LOG_ALL, GF_LOG_ERROR); gf_log_set_tool_level(GF_LOG_CONSOLE, GF_LOG_INFO); #endif #if defined(__sh__) /* Round all denormalized floatting point number to 0.0 */ sh4_change_fpscr(0,SH4_FPSCR_DN) ; #endif #if defined(WIN32) frequency.QuadPart = 0; /*clock setup*/ if (QueryPerformanceFrequency(&frequency)) { QueryPerformanceCounter(&init_counter); OS_GetSysClock = OS_GetSysClockHIGHRES; OS_GetSysClockHR = OS_GetSysClockHIGHRES_FULL; GF_LOG(GF_LOG_INFO, GF_LOG_CORE, ("[core] using WIN32 performance timer\n")); } else { OS_GetSysClock = OS_GetSysClockNORMAL; OS_GetSysClockHR = OS_GetSysClockNORMAL_FULL; GF_LOG(GF_LOG_INFO, GF_LOG_CORE, ("[core] using WIN32 regular timer\n")); } #ifndef _WIN32_WCE timeBeginPeriod(1); #endif GF_LOG(GF_LOG_INFO, GF_LOG_CORE, ("[core] checking for run-time info tools")); #if defined(_WIN32_WCE) last_total_k_u_time = last_process_k_u_time = 0; last_update_time = 0; memset(&the_rti, 0, sizeof(GF_SystemRTInfo)); the_rti.pid = GetCurrentProcessId(); the_rti.nb_cores = 1; GlobalMemoryStatus(&ms); mem_usage_at_startup = ms.dwAvailPhys; #else /*cpu usage tools are buried in win32 dlls...*/ MyGetSystemTimes = (NTGetSystemTimes) GetProcAddress(GetModuleHandle("kernel32.dll"), "GetSystemTimes"); if (!MyGetSystemTimes) { MyQuerySystemInfo = (NTQuerySystemInfo) GetProcAddress(GetModuleHandle("ntdll.dll"), "NtQuerySystemInformation"); if (MyQuerySystemInfo) { GF_LOG(GF_LOG_INFO, GF_LOG_CORE, (" - CPU: QuerySystemInformation")); } } else { GF_LOG(GF_LOG_INFO, GF_LOG_CORE, (" - CPU: GetSystemsTimes")); } psapi_hinst = LoadLibrary("psapi.dll"); MyGetProcessMemoryInfo = (NTGetProcessMemoryInfo) GetProcAddress(psapi_hinst, "GetProcessMemoryInfo"); if (MyGetProcessMemoryInfo) { GF_LOG(GF_LOG_INFO, GF_LOG_CORE, (" - memory: GetProcessMemoryInfo")); } last_process_k_u_time = last_proc_idle_time = last_proc_k_u_time = 0; last_update_time = 0; memset(&the_rti, 0, sizeof(GF_SystemRTInfo)); the_rti.pid = GetCurrentProcessId(); GetSystemInfo( &sysinfo ); the_rti.nb_cores = sysinfo.dwNumberOfProcessors; #endif GF_LOG(GF_LOG_INFO, GF_LOG_CORE, ("\n")); #else /*linux threads and OSX...*/ last_process_k_u_time = 0; last_cpu_u_k_time = last_cpu_idle_time = 0; last_update_time = 0; memset(&the_rti, 0, sizeof(GF_SystemRTInfo)); the_rti.pid = getpid(); the_rti.nb_cores = (u32) sysconf( _SC_NPROCESSORS_ONLN ); sys_start_time = gf_sys_clock(); sys_start_time_hr = gf_sys_clock_high_res(); #endif GF_LOG(GF_LOG_INFO, GF_LOG_CORE, ("[core] process id %d\n", the_rti.pid)); #ifndef _WIN32_WCE setlocale( LC_NUMERIC, "C" ); #endif } sys_init += 1; /*init RTI stats*/ if (!memory_at_gpac_startup) { GF_SystemRTInfo rti; if (gf_sys_get_rti(500, &rti, GF_RTI_SYSTEM_MEMORY_ONLY)) { memory_at_gpac_startup = rti.physical_memory_avail; GF_LOG(GF_LOG_INFO, GF_LOG_CORE, ("[core] System init OK - process id %d - %d MB physical RAM - %d cores\n", rti.pid, (u32) (rti.physical_memory/1024/1024), rti.nb_cores)); } else { memory_at_gpac_startup = 0; } } } GF_EXPORT void gf_sys_close() { if (sys_init > 0) { sys_init --; if (sys_init) return; /*prevent any call*/ last_update_time = 0xFFFFFFFF; #if defined(WIN32) && !defined(_WIN32_WCE) timeEndPeriod(1); MyGetSystemTimes = NULL; MyGetProcessMemoryInfo = NULL; MyQuerySystemInfo = NULL; if (psapi_hinst) FreeLibrary(psapi_hinst); psapi_hinst = NULL; #endif } } #ifdef GPAC_MEMORY_TRACKING extern size_t gpac_allocated_memory; extern size_t gpac_nb_alloc_blocs; #endif /*CPU and Memory Usage*/ #ifdef WIN32 Bool gf_sys_get_rti_os(u32 refresh_time_ms, GF_SystemRTInfo *rti, u32 flags) { #if defined(_WIN32_WCE) THREADENTRY32 tentry; u64 total_cpu_time, process_cpu_time; DWORD orig_perm; #endif MEMORYSTATUS ms; u64 creation, exit, kernel, user, process_k_u_time, proc_idle_time, proc_k_u_time; u32 entry_time; HANDLE hSnapShot; assert(sys_init); if (!rti) return GF_FALSE; proc_idle_time = proc_k_u_time = process_k_u_time = 0; entry_time = gf_sys_clock(); if (last_update_time && (entry_time - last_update_time < refresh_time_ms)) { memcpy(rti, &the_rti, sizeof(GF_SystemRTInfo)); return GF_FALSE; } if (flags & GF_RTI_SYSTEM_MEMORY_ONLY) { memset(rti, 0, sizeof(GF_SystemRTInfo)); rti->sampling_instant = last_update_time; GlobalMemoryStatus(&ms); rti->physical_memory = ms.dwTotalPhys; rti->physical_memory_avail = ms.dwAvailPhys; #ifdef GPAC_MEMORY_TRACKING rti->gpac_memory = (u64) gpac_allocated_memory; #endif return GF_TRUE; } #if defined (_WIN32_WCE) total_cpu_time = process_cpu_time = 0; /*get a snapshot of all running threads*/ orig_perm = GetCurrentPermissions(); SetProcPermissions(0xFFFFFFFF); hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); if (hSnapShot) { tentry.dwSize = sizeof(THREADENTRY32); the_rti.thread_count = 0; /*note we always act as if GF_RTI_ALL_PROCESSES_TIMES flag is set, since there is no other way to enumerate threads from a process, and GetProcessTimes doesn't exist on CE*/ if (Thread32First(hSnapShot, &tentry)) { do { /*get thread times*/ if (GetThreadTimes( (HANDLE) tentry.th32ThreadID, (FILETIME *) &creation, (FILETIME *) &exit, (FILETIME *) &kernel, (FILETIME *) &user)) { total_cpu_time += user + kernel; if (tentry.th32OwnerProcessID==the_rti.pid) { process_cpu_time += user + kernel; the_rti.thread_count ++; } } } while (Thread32Next(hSnapShot, &tentry)); } CloseToolhelp32Snapshot(hSnapShot); } if (flags & GF_RTI_PROCESS_MEMORY) { HEAPLIST32 hlentry; HEAPENTRY32 hentry; the_rti.process_memory = 0; hlentry.dwSize = sizeof(HEAPLIST32); hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPHEAPLIST, the_rti.pid); if (hSnapShot && Heap32ListFirst(hSnapShot, &hlentry)) { do { hentry.dwSize = sizeof(hentry); if (Heap32First(hSnapShot, &hentry, hlentry.th32ProcessID, hlentry.th32HeapID)) { do { the_rti.process_memory += hentry.dwBlockSize; } while (Heap32Next(hSnapShot, &hentry)); } } while (Heap32ListNext(hSnapShot, &hlentry)); } CloseToolhelp32Snapshot(hSnapShot); } SetProcPermissions(orig_perm); total_cpu_time /= 10; process_cpu_time /= 10; #else /*XP-SP1 and Win2003 servers only have GetSystemTimes support. This will give a better estimation of CPU usage since we can take into account the idle time*/ if (MyGetSystemTimes) { u64 u_time; MyGetSystemTimes(&proc_idle_time, &proc_k_u_time, &u_time); proc_k_u_time += u_time; proc_idle_time /= 10; proc_k_u_time /= 10; } /*same rq for NtQuerySystemInformation*/ else if (MyQuerySystemInfo) { DWORD ret; SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION info; MyQuerySystemInfo(0x8 /*SystemProcessorPerformanceInformation*/, &info, sizeof(info), &ret); if (ret && (ret<=sizeof(info))) { proc_idle_time = info.IdleTime.QuadPart / 10; proc_k_u_time = (info.KernelTime.QuadPart + info.UserTime.QuadPart) / 10; } } /*no special API available, ONLY FETCH TIMES if requested (may eat up some time)*/ else if (flags & GF_RTI_ALL_PROCESSES_TIMES) { PROCESSENTRY32 pentry; /*get a snapshot of all running threads*/ hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (!hSnapShot) return GF_FALSE; pentry.dwSize = sizeof(PROCESSENTRY32); if (Process32First(hSnapShot, &pentry)) { do { HANDLE procH = NULL; if (pentry.th32ProcessID) procH = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pentry.th32ProcessID); if (procH && GetProcessTimes(procH, (FILETIME *) &creation, (FILETIME *) &exit, (FILETIME *) &kernel, (FILETIME *) &user) ) { user += kernel; proc_k_u_time += user; if (pentry.th32ProcessID==the_rti.pid) { process_k_u_time = user; //nb_threads = pentry.cntThreads; } } if (procH) CloseHandle(procH); } while (Process32Next(hSnapShot, &pentry)); } CloseHandle(hSnapShot); proc_k_u_time /= 10; } if (!process_k_u_time) { HANDLE procH = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, the_rti.pid); if (procH && GetProcessTimes(procH, (FILETIME *) &creation, (FILETIME *) &exit, (FILETIME *) &kernel, (FILETIME *) &user) ) { process_k_u_time = user + kernel; } if (procH) CloseHandle(procH); if (!process_k_u_time) return GF_FALSE; } process_k_u_time /= 10; /*this won't cost a lot*/ if (MyGetProcessMemoryInfo) { PROCESS_MEMORY_COUNTERS pmc; HANDLE procH = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, the_rti.pid); MyGetProcessMemoryInfo(procH, &pmc, sizeof (pmc)); the_rti.process_memory = pmc.WorkingSetSize; if (procH) CloseHandle(procH); } /*THIS IS VERY HEAVY (eats up mem and time) - only perform if requested*/ else if (flags & GF_RTI_PROCESS_MEMORY) { HEAPLIST32 hlentry; HEAPENTRY32 hentry; the_rti.process_memory = 0; hlentry.dwSize = sizeof(HEAPLIST32); hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPHEAPLIST, the_rti.pid); if (hSnapShot && Heap32ListFirst(hSnapShot, &hlentry)) { do { hentry.dwSize = sizeof(hentry); if (Heap32First(&hentry, hlentry.th32ProcessID, hlentry.th32HeapID)) { do { the_rti.process_memory += hentry.dwBlockSize; } while (Heap32Next(&hentry)); } } while (Heap32ListNext(hSnapShot, &hlentry)); } CloseHandle(hSnapShot); } #endif the_rti.sampling_instant = last_update_time; if (last_update_time) { the_rti.sampling_period_duration = entry_time - last_update_time; the_rti.process_cpu_time_diff = (u32) ((process_k_u_time - last_process_k_u_time)/1000); #if defined(_WIN32_WCE) the_rti.total_cpu_time_diff = (u32) ((total_cpu_time - last_total_k_u_time)/1000); /*we're not that accurate....*/ if (the_rti.total_cpu_time_diff > the_rti.sampling_period_duration) the_rti.sampling_period_duration = the_rti.total_cpu_time_diff; /*rough values*/ the_rti.cpu_idle_time = the_rti.sampling_period_duration - the_rti.total_cpu_time_diff; if (!the_rti.sampling_period_duration) the_rti.sampling_period_duration=1; the_rti.total_cpu_usage = (u32) (100 * the_rti.total_cpu_time_diff / the_rti.sampling_period_duration); if (the_rti.total_cpu_time_diff + the_rti.cpu_idle_time==0) the_rti.total_cpu_time_diff ++; the_rti.process_cpu_usage = (u32) (100*the_rti.process_cpu_time_diff / (the_rti.total_cpu_time_diff + the_rti.cpu_idle_time) ); #else /*oops, we have no choice but to assume 100% cpu usage during this period*/ if (!proc_k_u_time) { the_rti.total_cpu_time_diff = the_rti.sampling_period_duration; proc_k_u_time = last_proc_k_u_time + the_rti.sampling_period_duration; the_rti.cpu_idle_time = 0; the_rti.total_cpu_usage = 100; if (the_rti.sampling_period_duration) the_rti.process_cpu_usage = (u32) (100*the_rti.process_cpu_time_diff / the_rti.sampling_period_duration); } else { u64 samp_sys_time, idle; the_rti.total_cpu_time_diff = (u32) ((proc_k_u_time - last_proc_k_u_time)/1000); /*we're not that accurate....*/ if (the_rti.total_cpu_time_diff > the_rti.sampling_period_duration) { the_rti.sampling_period_duration = the_rti.total_cpu_time_diff; } if (!proc_idle_time) proc_idle_time = last_proc_idle_time + (the_rti.sampling_period_duration - the_rti.total_cpu_time_diff); samp_sys_time = proc_k_u_time - last_proc_k_u_time; idle = proc_idle_time - last_proc_idle_time; the_rti.cpu_idle_time = (u32) (idle/1000); if (samp_sys_time) { the_rti.total_cpu_usage = (u32) ( (samp_sys_time - idle) / (samp_sys_time / 100) ); the_rti.process_cpu_usage = (u32) (100*the_rti.process_cpu_time_diff / (samp_sys_time/1000)); } } #endif } last_update_time = entry_time; last_process_k_u_time = process_k_u_time; GlobalMemoryStatus(&ms); the_rti.physical_memory = ms.dwTotalPhys; #ifdef GPAC_MEMORY_TRACKING the_rti.gpac_memory = (u64) gpac_allocated_memory; #endif the_rti.physical_memory_avail = ms.dwAvailPhys; #if defined(_WIN32_WCE) last_total_k_u_time = total_cpu_time; if (!the_rti.process_memory) the_rti.process_memory = mem_usage_at_startup - ms.dwAvailPhys; #else last_proc_idle_time = proc_idle_time; last_proc_k_u_time = proc_k_u_time; #endif if (!the_rti.gpac_memory) the_rti.gpac_memory = the_rti.process_memory; memcpy(rti, &the_rti, sizeof(GF_SystemRTInfo)); return GF_TRUE; } #elif defined(GPAC_CONFIG_DARWIN) && !defined(GPAC_IPHONE) #include <sys/types.h> #include <sys/sysctl.h> #include <sys/vmmeter.h> #include <mach/mach_init.h> #include <mach/mach_host.h> #include <mach/mach_port.h> #include <mach/mach_traps.h> #include <mach/task_info.h> #include <mach/thread_info.h> #include <mach/thread_act.h> #include <mach/vm_region.h> #include <mach/vm_map.h> #include <mach/task.h> #if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1060 #include <mach/shared_region.h> #else #include <mach/shared_memory_server.h> #endif #include <mach/mach_error.h> static u64 total_physical_memory = 0; Bool gf_sys_get_rti_os(u32 refresh_time_ms, GF_SystemRTInfo *rti, u32 flags) { size_t length; u32 entry_time, i, percent; int mib[6]; u64 result; int pagesize; u64 process_u_k_time; double utime, stime; vm_statistics_data_t vmstat; task_t task; kern_return_t error; thread_array_t thread_table; unsigned table_size; thread_basic_info_t thi; thread_basic_info_data_t thi_data; struct task_basic_info ti; mach_msg_type_number_t count = HOST_VM_INFO_COUNT, size = sizeof(ti); entry_time = gf_sys_clock(); if (last_update_time && (entry_time - last_update_time < refresh_time_ms)) { memcpy(rti, &the_rti, sizeof(GF_SystemRTInfo)); return 0; } mib[0] = CTL_HW; mib[1] = HW_PAGESIZE; length = sizeof(pagesize); if (sysctl(mib, 2, &pagesize, &length, NULL, 0) < 0) { return 0; } if (host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vmstat, &count) != KERN_SUCCESS) { return 0; } the_rti.physical_memory = (vmstat.wire_count + vmstat.active_count + vmstat.inactive_count + vmstat.free_count)* pagesize; the_rti.physical_memory_avail = vmstat.free_count * pagesize; if (!total_physical_memory) { mib[0] = CTL_HW; mib[1] = HW_MEMSIZE; length = sizeof(u64); if (sysctl(mib, 2, &result, &length, NULL, 0) >= 0) { total_physical_memory = result; } } the_rti.physical_memory = total_physical_memory; error = task_for_pid(mach_task_self(), the_rti.pid, &task); if (error) { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[RTI] Cannot get process task for PID %d: error %d\n", the_rti.pid, error)); return 0; } error = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&ti, &size); if (error) { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[RTI] Cannot get process task info (PID %d): error %d\n", the_rti.pid, error)); return 0; } percent = 0; utime = ti.user_time.seconds + ti.user_time.microseconds * 1e-6; stime = ti.system_time.seconds + ti.system_time.microseconds * 1e-6; error = task_threads(task, &thread_table, &table_size); if (error != KERN_SUCCESS) { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[RTI] Cannot get threads task for PID %d: error %d\n", the_rti.pid, error)); return 0; } thi = &thi_data; for (i = 0; i != table_size; ++i) { count = THREAD_BASIC_INFO_COUNT; error = thread_info(thread_table[i], THREAD_BASIC_INFO, (thread_info_t)thi, &count); if (error != KERN_SUCCESS) { mach_error("[RTI] Unexpected thread_info() call return", error); GF_LOG(GF_LOG_WARNING, GF_LOG_CORE, ("[RTI] Unexpected thread info for PID %d\n", the_rti.pid)); break; } if ((thi->flags & TH_FLAGS_IDLE) == 0) { utime += thi->user_time.seconds + thi->user_time.microseconds * 1e-6; stime += thi->system_time.seconds + thi->system_time.microseconds * 1e-6; percent += (u32) (100 * (double)thi->cpu_usage / TH_USAGE_SCALE); } } vm_deallocate(mach_task_self(), (vm_offset_t)thread_table, table_size * sizeof(thread_array_t)); mach_port_deallocate(mach_task_self(), task); process_u_k_time = utime + stime; the_rti.sampling_instant = last_update_time; if (last_update_time) { the_rti.sampling_period_duration = (entry_time - last_update_time); the_rti.process_cpu_time_diff = (process_u_k_time - last_process_k_u_time) * 10; the_rti.total_cpu_time_diff = the_rti.sampling_period_duration; /*TODO*/ the_rti.cpu_idle_time = 0; the_rti.total_cpu_usage = 0; if (!the_rti.process_cpu_time_diff) the_rti.process_cpu_time_diff = the_rti.total_cpu_time_diff; the_rti.process_cpu_usage = percent; } else { mem_at_startup = the_rti.physical_memory_avail; } the_rti.process_memory = mem_at_startup - the_rti.physical_memory_avail; #ifdef GPAC_MEMORY_TRACKING the_rti.gpac_memory = gpac_allocated_memory; #endif last_process_k_u_time = process_u_k_time; last_cpu_idle_time = 0; last_update_time = entry_time; memcpy(rti, &the_rti, sizeof(GF_SystemRTInfo)); return 1; } //linux #else Bool gf_sys_get_rti_os(u32 refresh_time_ms, GF_SystemRTInfo *rti, u32 flags) { u32 entry_time; u64 process_u_k_time; u32 u_k_time, idle_time; #if 0 char szProc[100]; #endif char line[2048]; FILE *f; assert(sys_init); entry_time = gf_sys_clock(); if (last_update_time && (entry_time - last_update_time < refresh_time_ms)) { memcpy(rti, &the_rti, sizeof(GF_SystemRTInfo)); return 0; } u_k_time = idle_time = 0; f = gf_fopen("/proc/stat", "r"); if (f) { u32 k_time, nice_time, u_time; if (fgets(line, 128, f) != NULL) { if (sscanf(line, "cpu %u %u %u %u\n", &u_time, &k_time, &nice_time, &idle_time) == 4) { u_k_time = u_time + k_time + nice_time; } } gf_fclose(f); } process_u_k_time = 0; the_rti.process_memory = 0; /*FIXME? under LinuxThreads this will only fetch stats for the calling thread, we would have to enumerate /proc to get the complete CPU usage of all therads of the process...*/ #if 0 sprintf(szProc, "/proc/%d/stat", the_rti.pid); f = gf_fopen(szProc, "r"); if (f) { fflush(f); if (fgets(line, 2048, f) != NULL) { char state; char *start; long cutime, cstime, priority, nice, itrealvalue, rss; int exit_signal, processor; unsigned long flags, minflt, cminflt, majflt, cmajflt, utime, stime,starttime, vsize, rlim, startcode, endcode, startstack, kstkesp, kstkeip, signal, blocked, sigignore, sigcatch, wchan, nswap, cnswap, rem; int ppid, pgrp ,session, tty_nr, tty_pgrp, res; start = strchr(line, ')'); if (start) start += 2; else { start = strchr(line, ' '); start++; } res = sscanf(start,"%c %d %d %d %d %d %lu %lu %lu %lu \ %lu %lu %lu %ld %ld %ld %ld %ld %ld %lu \ %lu %ld %lu %lu %lu %lu %lu %lu %lu %lu \ %lu %lu %lu %lu %lu %d %d", &state, &ppid, &pgrp, &session, &tty_nr, &tty_pgrp, &flags, &minflt, &cminflt, &majflt, &cmajflt, &utime, &stime, &cutime, &cstime, &priority, &nice, &itrealvalue, &rem, &starttime, &vsize, &rss, &rlim, &startcode, &endcode, &startstack, &kstkesp, &kstkeip, &signal, &blocked, &sigignore, &sigcatch, &wchan, &nswap, &cnswap, &exit_signal, &processor); if (res) process_u_k_time = (u64) (cutime + cstime); else { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[RTI] PROC %s parse error\n", szProc)); } } else { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[RTI] error reading pid/stat\n\n", szProc)); } gf_fclose(f); } else { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[RTI] cannot open %s\n", szProc)); } sprintf(szProc, "/proc/%d/status", the_rti.pid); f = gf_fopen(szProc, "r"); if (f) { while (fgets(line, 1024, f) != NULL) { if (!strnicmp(line, "VmSize:", 7)) { sscanf(line, "VmSize: %"LLD" kB", &the_rti.process_memory); the_rti.process_memory *= 1024; } } gf_fclose(f); } else { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[RTI] cannot open %s\n", szProc)); } #endif #ifndef GPAC_IPHONE the_rti.physical_memory = the_rti.physical_memory_avail = 0; f = gf_fopen("/proc/meminfo", "r"); if (f) { while (fgets(line, 1024, f) != NULL) { if (!strnicmp(line, "MemTotal:", 9)) { sscanf(line, "MemTotal: "LLU" kB", &the_rti.physical_memory); the_rti.physical_memory *= 1024; } else if (!strnicmp(line, "MemFree:", 8)) { sscanf(line, "MemFree: "LLU" kB", &the_rti.physical_memory_avail); the_rti.physical_memory_avail *= 1024; break; } } gf_fclose(f); } else { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[RTI] cannot open /proc/meminfo\n")); } #endif the_rti.sampling_instant = last_update_time; if (last_update_time) { the_rti.sampling_period_duration = (entry_time - last_update_time); the_rti.process_cpu_time_diff = (u32) (process_u_k_time - last_process_k_u_time) * 10; /*oops, we have no choice but to assume 100% cpu usage during this period*/ if (!u_k_time) { the_rti.total_cpu_time_diff = the_rti.sampling_period_duration; u_k_time = (u32) (last_cpu_u_k_time + the_rti.sampling_period_duration); the_rti.cpu_idle_time = 0; the_rti.total_cpu_usage = 100; if (!the_rti.process_cpu_time_diff) the_rti.process_cpu_time_diff = the_rti.total_cpu_time_diff; the_rti.process_cpu_usage = (u32) ( 100 * the_rti.process_cpu_time_diff / the_rti.sampling_period_duration); } else { u64 samp_sys_time; /*move to ms (/proc/stat gives times in 100 ms unit*/ the_rti.total_cpu_time_diff = (u32) (u_k_time - last_cpu_u_k_time)*10; /*we're not that accurate....*/ if (the_rti.total_cpu_time_diff > the_rti.sampling_period_duration) the_rti.sampling_period_duration = the_rti.total_cpu_time_diff; if (!idle_time) idle_time = (the_rti.sampling_period_duration - the_rti.total_cpu_time_diff)/10; samp_sys_time = u_k_time - last_cpu_u_k_time; the_rti.cpu_idle_time = (u32) (idle_time - last_cpu_idle_time); the_rti.total_cpu_usage = (u32) ( 100 * samp_sys_time / (the_rti.cpu_idle_time + samp_sys_time ) ); /*move to ms (/proc/stat gives times in 100 ms unit*/ the_rti.cpu_idle_time *= 10; if (!the_rti.process_cpu_time_diff) the_rti.process_cpu_time_diff = the_rti.total_cpu_time_diff; the_rti.process_cpu_usage = (u32) ( 100 * the_rti.process_cpu_time_diff / (the_rti.cpu_idle_time + 10*samp_sys_time ) ); } } else { mem_at_startup = the_rti.physical_memory_avail; } the_rti.process_memory = mem_at_startup - the_rti.physical_memory_avail; #ifdef GPAC_MEMORY_TRACKING the_rti.gpac_memory = gpac_allocated_memory; #endif last_process_k_u_time = process_u_k_time; last_cpu_idle_time = idle_time; last_cpu_u_k_time = u_k_time; last_update_time = entry_time; memcpy(rti, &the_rti, sizeof(GF_SystemRTInfo)); return 1; } #endif GF_EXPORT Bool gf_sys_get_rti(u32 refresh_time_ms, GF_SystemRTInfo *rti, u32 flags) { Bool res = gf_sys_get_rti_os(refresh_time_ms, rti, flags); if (res) { if (!rti->process_memory) rti->process_memory = memory_at_gpac_startup - rti->physical_memory_avail; if (!rti->gpac_memory) rti->gpac_memory = memory_at_gpac_startup - rti->physical_memory_avail; } return res; } GF_EXPORT char * gf_get_default_cache_directory() { char szPath[GF_MAX_PATH]; char* root_tmp; size_t len; #ifdef _WIN32_WCE strcpy(szPath, "\\windows\\temp" ); #elif defined(WIN32) GetTempPath(GF_MAX_PATH, szPath); #else strcpy(szPath, "/tmp"); #endif root_tmp = gf_strdup(szPath); len = strlen(szPath); if (szPath[len-1] != GF_PATH_SEPARATOR) { szPath[len] = GF_PATH_SEPARATOR; szPath[len+1] = 0; } strcat(szPath, "gpac_cache"); if ( !gf_dir_exists(szPath) && gf_mkdir(szPath)!=GF_OK ) { return root_tmp; } gf_free(root_tmp); return gf_strdup(szPath); } GF_EXPORT Bool gf_sys_get_battery_state(Bool *onBattery, u32 *onCharge, u32*level, u32 *batteryLifeTime, u32 *batteryFullLifeTime) { #if defined(_WIN32_WCE) SYSTEM_POWER_STATUS_EX sps; GetSystemPowerStatusEx(&sps, 0); if (onBattery) *onBattery = sps.ACLineStatus ? 0 : 1; if (onCharge) *onCharge = (sps.BatteryFlag & BATTERY_FLAG_CHARGING) ? 1 : 0; if (level) *level = sps.BatteryLifePercent; if (batteryLifeTime) *batteryLifeTime = sps.BatteryLifeTime; if (batteryFullLifeTime) *batteryFullLifeTime = sps.BatteryFullLifeTime; #elif defined(WIN32) SYSTEM_POWER_STATUS sps; GetSystemPowerStatus(&sps); if (onBattery) *onBattery = sps.ACLineStatus ? GF_FALSE : GF_TRUE; if (onCharge) *onCharge = (sps.BatteryFlag & BATTERY_FLAG_CHARGING) ? 1 : 0; if (level) *level = sps.BatteryLifePercent; if (batteryLifeTime) *batteryLifeTime = sps.BatteryLifeTime; if (batteryFullLifeTime) *batteryFullLifeTime = sps.BatteryFullLifeTime; #endif return GF_TRUE; } struct GF_GlobalLock { const char * resourceName; }; #ifndef WIN32 #define CPF_CLOEXEC 1 #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> struct _GF_GlobalLock_opaque { char * resourceName; char * pidFile; int fd; }; GF_GlobalLock * gf_create_PID_file( const char * resourceName ) { const char * prefix = "/gpac_lock_"; const char * dir = gf_get_default_cache_directory(); char * pidfile; int flags; int status; pidfile = gf_malloc(strlen(dir)+strlen(prefix)+strlen(resourceName)+1); strcpy(pidfile, dir); strcat(pidfile, prefix); /* Use only valid names for file */ { const char *res; char * pid = &(pidfile[strlen(pidfile)]); for (res = resourceName; *res ; res++) { if (*res >= 'A' && *res <= 'z') *pid = * res; else *pid = '_'; pid++; } *pid = '\0'; } int fd = open(pidfile, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); if (fd == -1) goto exit; /* Get the flags */ flags = fcntl(fd, F_GETFD); if (flags == -1) { goto exit; } /* Set FD_CLOEXEC, so exclusive lock will be removed on exit, so even if GPAC crashes, * lock will be allowed for next instance */ flags |= FD_CLOEXEC; /* Now, update the flags */ if (fcntl(fd, F_SETFD, flags) == -1) { goto exit; } /* Now, we try to lock the file */ { struct flock fl; fl.l_type = F_WRLCK; fl.l_whence = SEEK_SET; fl.l_start = fl.l_len = 0; status = fcntl(fd, F_SETLK, &fl); } if (status == -1) { goto exit; } if (ftruncate(fd, 0) == -1) { goto exit; } /* Write the PID */ { int sz = 100; char * buf = gf_malloc( sz ); sz = snprintf(buf, sz, "%ld\n", (long) getpid()); if (write(fd, buf, sz) != sz) { gf_free(buf); goto exit; } } sync(); { GF_GlobalLock * lock = gf_malloc( sizeof(GF_GlobalLock)); lock->resourceName = gf_strdup(resourceName); lock->pidFile = pidfile; lock->fd = fd; return lock; } exit: if (fd >= 0) close(fd); return NULL; } #else /* WIN32 */ struct _GF_GlobalLock_opaque { char * resourceName; HANDLE hMutex; /*a named mutex is a system-mode object on windows*/ }; #endif GF_EXPORT GF_GlobalLock * gf_global_resource_lock(const char * resourceName) { #ifdef WIN32 #ifdef _WIN32_WCE unsigned short sWResourceName[MAX_PATH]; #endif DWORD lastErr; GF_GlobalLock *lock = gf_malloc(sizeof(GF_GlobalLock)); lock->resourceName = gf_strdup(resourceName); /*first ensure mutex is created*/ #ifdef _WIN32_WCE CE_CharToWide((char *)resourceName, sWResourceName); lock->hMutex = CreateMutex(NULL, TRUE, sWResourceName); #else lock->hMutex = CreateMutex(NULL, TRUE, resourceName); #endif lastErr = GetLastError(); if (lastErr && lastErr == ERROR_ALREADY_EXISTS) return NULL; if (!lock->hMutex) { GF_LOG(GF_LOG_ERROR, GF_LOG_MUTEX, ("[Mutex] Couldn't create mutex for global lock: %d\n", lastErr)); return NULL; } /*then lock it*/ switch (WaitForSingleObject(lock->hMutex, INFINITE)) { case WAIT_ABANDONED: case WAIT_TIMEOUT: assert(0); /*serious error: someone has modified the object elsewhere*/ GF_LOG(GF_LOG_ERROR, GF_LOG_MUTEX, ("[Mutex] Couldn't get the global lock\n")); gf_global_resource_unlock(lock); return NULL; } return lock; #else /* WIN32 */ return gf_create_PID_file(resourceName); #endif /* WIN32 */ } /*! * Unlock a previouly locked resource * \param lock The resource to unlock * \return GF_OK if evertything went fine */ GF_EXPORT GF_Err gf_global_resource_unlock(GF_GlobalLock * lock) { if (!lock) return GF_BAD_PARAM; #ifndef WIN32 assert( lock->pidFile); close(lock->fd); if (unlink(lock->pidFile)) perror("Failed to unlink lock file"); gf_free(lock->pidFile); lock->pidFile = NULL; lock->fd = -1; #else /* WIN32 */ { /*MSDN: "The mutex object is destroyed when its last handle has been closed."*/ BOOL ret = ReleaseMutex(lock->hMutex); if (!ret) { DWORD err = GetLastError(); GF_LOG(GF_LOG_ERROR, GF_LOG_MUTEX, ("[Mutex] Couldn't release mutex for global lock: %d\n", err)); } ret = CloseHandle(lock->hMutex); if (!ret) { DWORD err = GetLastError(); GF_LOG(GF_LOG_ERROR, GF_LOG_MUTEX, ("[Mutex] Couldn't destroy mutex for global lock: %d\n", err)); } } #endif if (lock->resourceName) gf_free(lock->resourceName); lock->resourceName = NULL; gf_free(lock); return GF_OK; } #ifdef GPAC_ANDROID fm_callback_func fm_cbk = NULL; static void *fm_cbk_obj = NULL; void gf_fm_request_set_callback(void *cbk_obj, fm_callback_func cbk_func) { fm_cbk = cbk_func; fm_cbk_obj = cbk_obj; } void gf_fm_request_call(u32 type, u32 param, int *value) { if (fm_cbk) fm_cbk(fm_cbk_obj, type, param, value); } #endif //GPAC_ANDROID GF_EXPORT s32 gf_gettimeofday(struct timeval *tp, void *tz) { return gettimeofday(tp, tz); } static u32 ntp_shift = GF_NTP_SEC_1900_TO_1970; GF_EXPORT void gf_net_set_ntp_shift(s32 shift) { ntp_shift = GF_NTP_SEC_1900_TO_1970 + shift; } /* NTP tools */ GF_EXPORT void gf_net_get_ntp(u32 *sec, u32 *frac) { u64 frac_part; struct timeval now; gettimeofday(&now, NULL); if (sec) { *sec = (u32) (now.tv_sec) + ntp_shift; } if (frac) { frac_part = now.tv_usec * 0xFFFFFFFFULL; frac_part /= 1000000; *frac = (u32) ( frac_part ); } } GF_EXPORT u64 gf_net_get_ntp_ts() { u64 res; u32 sec, frac; gf_net_get_ntp(&sec, &frac); res = sec; res<<= 32; res |= frac; return res; } GF_EXPORT s32 gf_net_get_ntp_diff_ms(u64 ntp) { u32 remote_s, remote_f, local_s, local_f; s64 local, remote; remote_s = (ntp >> 32); remote_f = (u32) (ntp & 0xFFFFFFFFULL); gf_net_get_ntp(&local_s, &local_f); local = local_s; local *= 1000; local += ((u64) local_f)*1000 / 0xFFFFFFFFULL; remote = remote_s; remote *= 1000; remote += ((u64) remote_f)*1000 / 0xFFFFFFFFULL; return (s32) (local - remote); } GF_EXPORT s32 gf_net_get_timezone() { #if defined(_WIN32_WCE) return 0; #else //this has been commented due to some reports of broken implementation on some systems ... // s32 val = timezone; // return val; /*FIXME - avoid errors at midnight when estimating timezone this does not work !!*/ s32 t_timezone; struct tm t_gmt, t_local; time_t t_time; t_time = time(NULL); t_gmt = *gmtime(&t_time); t_local = *localtime(&t_time); t_timezone = (t_gmt.tm_hour - t_local.tm_hour) * 3600 + (t_gmt.tm_min - t_local.tm_min) * 60; return t_timezone; #endif } //no mkgmtime on mingw..., use our own #if (defined(WIN32) && defined(__GNUC__)) static Bool leap_year(u32 year) { year += 1900; return (year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0) ? GF_TRUE : GF_FALSE; } static time_t gf_mktime_utc(struct tm *tm) { static const u32 days_per_month[2][12] = { {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} }; time_t time=0; int i; for (i=70; i<tm->tm_year; i++) { time += leap_year(i) ? 366 : 365; } for (i=0; i<tm->tm_mon; ++i) { time += days_per_month[leap_year(tm->tm_year)][i]; } time += tm->tm_mday - 1; time *= 24; time += tm->tm_hour; time *= 60; time += tm->tm_min; time *= 60; time += tm->tm_sec; return time; } #elif defined(WIN32) static time_t gf_mktime_utc(struct tm *tm) { return _mkgmtime(tm); } #elif defined(GPAC_ANDROID) #include <time64.h> #if defined(__LP64__) static time_t gf_mktime_utc(struct tm *tm) { return timegm64(tm); } #else static time_t gf_mktime_utc(struct tm *tm) { static const time_t kTimeMax = ~(1L << (sizeof(time_t) * CHAR_BIT - 1)); static const time_t kTimeMin = (1L << (sizeof(time_t) * CHAR_BIT - 1)); time64_t result = timegm64(tm); if (result < kTimeMin || result > kTimeMax) return -1; return result; } #endif #else static time_t gf_mktime_utc(struct tm *tm) { return timegm(tm); } #endif GF_EXPORT u64 gf_net_parse_date(const char *val) { u64 current_time; char szDay[50], szMonth[50]; u32 year, month, day, h, m, s, ms; s32 oh, om; Float secs; Bool neg_time_zone = GF_FALSE; #ifdef _WIN32_WCE SYSTEMTIME syst; FILETIME filet; #else struct tm t; memset(&t, 0, sizeof(struct tm)); #endif szDay[0] = szMonth[0] = 0; year = month = day = h = m = s = 0; oh = om = 0; secs = 0; if (sscanf(val, "%d-%d-%dT%d:%d:%gZ", &year, &month, &day, &h, &m, &secs) == 6) { } else if (sscanf(val, "%d-%d-%dT%d:%d:%g-%d:%d", &year, &month, &day, &h, &m, &secs, &oh, &om) == 8) { neg_time_zone = GF_TRUE; } else if (sscanf(val, "%d-%d-%dT%d:%d:%g+%d:%d", &year, &month, &day, &h, &m, &secs, &oh, &om) == 8) { } else if (sscanf(val, "%3s, %d %3s %d %d:%d:%d", szDay, &day, szMonth, &year, &h, &m, &s)==7) { secs = (Float) s; } else if (sscanf(val, "%9s, %d-%3s-%d %02d:%02d:%02d GMT", szDay, &day, szMonth, &year, &h, &m, &s)==7) { secs = (Float) s; } else if (sscanf(val, "%3s %3s %d %02d:%02d:%02d %d", szDay, szMonth, &day, &year, &h, &m, &s)==7) { secs = (Float) s; } else { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[Core] Cannot parse date string %s\n", val)); return 0; } if (month) { month -= 1; } else { if (!strcmp(szMonth, "Jan")) month = 0; else if (!strcmp(szMonth, "Feb")) month = 1; else if (!strcmp(szMonth, "Mar")) month = 2; else if (!strcmp(szMonth, "Apr")) month = 3; else if (!strcmp(szMonth, "May")) month = 4; else if (!strcmp(szMonth, "Jun")) month = 5; else if (!strcmp(szMonth, "Jul")) month = 6; else if (!strcmp(szMonth, "Aug")) month = 7; else if (!strcmp(szMonth, "Sep")) month = 8; else if (!strcmp(szMonth, "Oct")) month = 9; else if (!strcmp(szMonth, "Nov")) month = 10; else if (!strcmp(szMonth, "Dec")) month = 11; } #ifdef _WIN32_WCE memset(&syst, 0, sizeof(SYSTEMTIME)); syst.wYear = year; syst.wMonth = month + 1; syst.wDay = day; syst.wHour = h; syst.wMinute = m; syst.wSecond = (u32) secs; SystemTimeToFileTime(&syst, &filet); current_time = (u64) ((*(LONGLONG *) &filet - TIMESPEC_TO_FILETIME_OFFSET) / 10000000); #else t.tm_year = year>1000 ? year-1900 : year; t.tm_mday = day; t.tm_hour = h; t.tm_min = m; t.tm_sec = (u32) secs; t.tm_mon = month; if (strlen(szDay) ) { if (!strcmp(szDay, "Mon") || !strcmp(szDay, "Monday")) t.tm_wday = 0; else if (!strcmp(szDay, "Tue") || !strcmp(szDay, "Tuesday")) t.tm_wday = 1; else if (!strcmp(szDay, "Wed") || !strcmp(szDay, "Wednesday")) t.tm_wday = 2; else if (!strcmp(szDay, "Thu") || !strcmp(szDay, "Thursday")) t.tm_wday = 3; else if (!strcmp(szDay, "Fri") || !strcmp(szDay, "Friday")) t.tm_wday = 4; else if (!strcmp(szDay, "Sat") || !strcmp(szDay, "Saturday")) t.tm_wday = 5; else if (!strcmp(szDay, "Sun") || !strcmp(szDay, "Sunday")) t.tm_wday = 6; } current_time = gf_mktime_utc(&t); if ((s64) current_time == -1) { //use 1 ms return 1; } if (current_time == 0) { //use 1 ms return 1; } #endif if (om || oh) { s32 diff = (60*oh + om)*60; if (neg_time_zone) diff = -diff; current_time = current_time + diff; } current_time *= 1000; ms = (u32) ( (secs - (u32) secs) * 1000); return current_time + ms; } GF_EXPORT u64 gf_net_get_utc() { u64 current_time; Double msec; u32 sec, frac; gf_net_get_ntp(&sec, &frac); current_time = sec - GF_NTP_SEC_1900_TO_1970; current_time *= 1000; msec = frac*1000.0; msec /= 0xFFFFFFFF; current_time += (u64) msec; return current_time; } GF_EXPORT GF_Err gf_bin128_parse(const char *string, bin128 value) { u32 len; u32 i=0; if (!strnicmp(string, "0x", 2)) string += 2; len = (u32) strlen(string); if (len >= 32) { u32 j; for (j=0; j<len; j+=2) { u32 v; char szV[5]; while (string[j] && !isalnum(string[j])) j++; if (!string[j]) break; sprintf(szV, "%c%c", string[j], string[j+1]); sscanf(szV, "%x", &v); if (i > 15) { // force error check below i++; break; } value[i] = v; i++; } } if (i != 16) { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[CORE] 128bit blob is not 16-bytes long: %s\n", string)); return GF_BAD_PARAM; } return GF_OK; }
null
117
CWE-787
CVE-2019-11411
#include "jsi.h" #include "jsvalue.h" #include "jsbuiltin.h" #if defined(_MSC_VER) && (_MSC_VER < 1700) /* VS2012 has stdint.h */ typedef unsigned __int64 uint64_t; #else #include <stdint.h> #endif static void jsB_new_Number(js_State *J) { js_newnumber(J, js_gettop(J) > 1 ? js_tonumber(J, 1) : 0); } static void jsB_Number(js_State *J) { js_pushnumber(J, js_gettop(J) > 1 ? js_tonumber(J, 1) : 0); } static void Np_valueOf(js_State *J) { js_Object *self = js_toobject(J, 0); if (self->type != JS_CNUMBER) js_typeerror(J, "not a number"); js_pushnumber(J, self->u.number); } static void Np_toString(js_State *J) { char buf[32]; js_Object *self = js_toobject(J, 0); int radix = js_isundefined(J, 1) ? 10 : js_tointeger(J, 1); if (self->type != JS_CNUMBER) js_typeerror(J, "not a number"); if (radix == 10) { js_pushstring(J, jsV_numbertostring(J, buf, self->u.number)); return; } if (radix < 2 || radix > 36) js_rangeerror(J, "invalid radix"); /* lame number to string conversion for any radix from 2 to 36 */ { static const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz"; char buf[100]; double number = self->u.number; int sign = self->u.number < 0; js_Buffer *sb = NULL; uint64_t u, limit = ((uint64_t)1<<52); int ndigits, exp, point; if (number == 0) { js_pushstring(J, "0"); return; } if (isnan(number)) { js_pushstring(J, "NaN"); return; } if (isinf(number)) { js_pushstring(J, sign ? "-Infinity" : "Infinity"); return; } if (sign) number = -number; /* fit as many digits as we want in an int */ exp = 0; while (number * pow(radix, exp) > limit) --exp; while (number * pow(radix, exp+1) < limit) ++exp; u = number * pow(radix, exp) + 0.5; /* trim trailing zeros */ while (u > 0 && (u % radix) == 0) { u /= radix; --exp; } /* serialize digits */ ndigits = 0; while (u > 0) { buf[ndigits++] = digits[u % radix]; u /= radix; } point = ndigits - exp; if (js_try(J)) { js_free(J, sb); js_throw(J); } if (sign) js_putc(J, &sb, '-'); if (point <= 0) { js_putc(J, &sb, '0'); js_putc(J, &sb, '.'); while (point++ < 0) js_putc(J, &sb, '0'); while (ndigits-- > 0) js_putc(J, &sb, buf[ndigits]); } else { while (ndigits-- > 0) { js_putc(J, &sb, buf[ndigits]); if (--point == 0 && ndigits > 0) js_putc(J, &sb, '.'); } while (point-- > 0) js_putc(J, &sb, '0'); } js_putc(J, &sb, 0); js_pushstring(J, sb->s); js_endtry(J); js_free(J, sb); } } /* Customized ToString() on a number */ static void numtostr(js_State *J, const char *fmt, int w, double n) { char buf[32], *e; sprintf(buf, fmt, w, n); e = strchr(buf, 'e'); if (e) { int exp = atoi(e+1); sprintf(e, "e%+d", exp); } js_pushstring(J, buf); } static void Np_toFixed(js_State *J) { js_Object *self = js_toobject(J, 0); int width = js_tointeger(J, 1); char buf[32]; double x; if (self->type != JS_CNUMBER) js_typeerror(J, "not a number"); if (width < 0) js_rangeerror(J, "precision %d out of range", width); if (width > 20) js_rangeerror(J, "precision %d out of range", width); x = self->u.number; if (isnan(x) || isinf(x) || x <= -1e21 || x >= 1e21) js_pushstring(J, jsV_numbertostring(J, buf, x)); else numtostr(J, "%.*f", width, x); } static void Np_toExponential(js_State *J) { js_Object *self = js_toobject(J, 0); int width = js_tointeger(J, 1); char buf[32]; double x; if (self->type != JS_CNUMBER) js_typeerror(J, "not a number"); if (width < 0) js_rangeerror(J, "precision %d out of range", width); if (width > 20) js_rangeerror(J, "precision %d out of range", width); x = self->u.number; if (isnan(x) || isinf(x)) js_pushstring(J, jsV_numbertostring(J, buf, x)); else numtostr(J, "%.*e", width, self->u.number); } static void Np_toPrecision(js_State *J) { js_Object *self = js_toobject(J, 0); int width = js_tointeger(J, 1); char buf[32]; double x; if (self->type != JS_CNUMBER) js_typeerror(J, "not a number"); if (width < 1) js_rangeerror(J, "precision %d out of range", width); if (width > 21) js_rangeerror(J, "precision %d out of range", width); x = self->u.number; if (isnan(x) || isinf(x)) js_pushstring(J, jsV_numbertostring(J, buf, x)); else numtostr(J, "%.*g", width, self->u.number); } void jsB_initnumber(js_State *J) { J->Number_prototype->u.number = 0; js_pushobject(J, J->Number_prototype); { jsB_propf(J, "Number.prototype.valueOf", Np_valueOf, 0); jsB_propf(J, "Number.prototype.toString", Np_toString, 1); jsB_propf(J, "Number.prototype.toLocaleString", Np_toString, 0); jsB_propf(J, "Number.prototype.toFixed", Np_toFixed, 1); jsB_propf(J, "Number.prototype.toExponential", Np_toExponential, 1); jsB_propf(J, "Number.prototype.toPrecision", Np_toPrecision, 1); } js_newcconstructor(J, jsB_Number, jsB_new_Number, "Number", 0); /* 1 */ { jsB_propn(J, "MAX_VALUE", 1.7976931348623157e+308); jsB_propn(J, "MIN_VALUE", 5e-324); jsB_propn(J, "NaN", NAN); jsB_propn(J, "NEGATIVE_INFINITY", -INFINITY); jsB_propn(J, "POSITIVE_INFINITY", INFINITY); } js_defglobal(J, "Number", JS_DONTENUM); }
null
#include "jsi.h" #include "jsvalue.h" #include "jsbuiltin.h" #if defined(_MSC_VER) && (_MSC_VER < 1700) /* VS2012 has stdint.h */ typedef unsigned __int64 uint64_t; #else #include <stdint.h> #endif static void jsB_new_Number(js_State *J) { js_newnumber(J, js_gettop(J) > 1 ? js_tonumber(J, 1) : 0); } static void jsB_Number(js_State *J) { js_pushnumber(J, js_gettop(J) > 1 ? js_tonumber(J, 1) : 0); } static void Np_valueOf(js_State *J) { js_Object *self = js_toobject(J, 0); if (self->type != JS_CNUMBER) js_typeerror(J, "not a number"); js_pushnumber(J, self->u.number); } static void Np_toString(js_State *J) { char buf[100]; js_Object *self = js_toobject(J, 0); int radix = js_isundefined(J, 1) ? 10 : js_tointeger(J, 1); if (self->type != JS_CNUMBER) js_typeerror(J, "not a number"); if (radix == 10) { js_pushstring(J, jsV_numbertostring(J, buf, self->u.number)); return; } if (radix < 2 || radix > 36) js_rangeerror(J, "invalid radix"); /* lame number to string conversion for any radix from 2 to 36 */ { static const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz"; double number = self->u.number; int sign = self->u.number < 0; js_Buffer *sb = NULL; uint64_t u, limit = ((uint64_t)1<<52); int ndigits, exp, point; if (number == 0) { js_pushstring(J, "0"); return; } if (isnan(number)) { js_pushstring(J, "NaN"); return; } if (isinf(number)) { js_pushstring(J, sign ? "-Infinity" : "Infinity"); return; } if (sign) number = -number; /* fit as many digits as we want in an int */ exp = 0; while (number * pow(radix, exp) > limit) --exp; while (number * pow(radix, exp+1) < limit) ++exp; u = number * pow(radix, exp) + 0.5; /* trim trailing zeros */ while (u > 0 && (u % radix) == 0) { u /= radix; --exp; } /* serialize digits */ ndigits = 0; while (u > 0) { buf[ndigits++] = digits[u % radix]; u /= radix; } point = ndigits - exp; if (js_try(J)) { js_free(J, sb); js_throw(J); } if (sign) js_putc(J, &sb, '-'); if (point <= 0) { js_putc(J, &sb, '0'); js_putc(J, &sb, '.'); while (point++ < 0) js_putc(J, &sb, '0'); while (ndigits-- > 0) js_putc(J, &sb, buf[ndigits]); } else { while (ndigits-- > 0) { js_putc(J, &sb, buf[ndigits]); if (--point == 0 && ndigits > 0) js_putc(J, &sb, '.'); } while (point-- > 0) js_putc(J, &sb, '0'); } js_putc(J, &sb, 0); js_pushstring(J, sb->s); js_endtry(J); js_free(J, sb); } } /* Customized ToString() on a number */ static void numtostr(js_State *J, const char *fmt, int w, double n) { /* buf needs to fit printf("%.20f", 1e20) */ char buf[50], *e; sprintf(buf, fmt, w, n); e = strchr(buf, 'e'); if (e) { int exp = atoi(e+1); sprintf(e, "e%+d", exp); } js_pushstring(J, buf); } static void Np_toFixed(js_State *J) { js_Object *self = js_toobject(J, 0); int width = js_tointeger(J, 1); char buf[32]; double x; if (self->type != JS_CNUMBER) js_typeerror(J, "not a number"); if (width < 0) js_rangeerror(J, "precision %d out of range", width); if (width > 20) js_rangeerror(J, "precision %d out of range", width); x = self->u.number; if (isnan(x) || isinf(x) || x <= -1e21 || x >= 1e21) js_pushstring(J, jsV_numbertostring(J, buf, x)); else numtostr(J, "%.*f", width, x); } static void Np_toExponential(js_State *J) { js_Object *self = js_toobject(J, 0); int width = js_tointeger(J, 1); char buf[32]; double x; if (self->type != JS_CNUMBER) js_typeerror(J, "not a number"); if (width < 0) js_rangeerror(J, "precision %d out of range", width); if (width > 20) js_rangeerror(J, "precision %d out of range", width); x = self->u.number; if (isnan(x) || isinf(x)) js_pushstring(J, jsV_numbertostring(J, buf, x)); else numtostr(J, "%.*e", width, self->u.number); } static void Np_toPrecision(js_State *J) { js_Object *self = js_toobject(J, 0); int width = js_tointeger(J, 1); char buf[32]; double x; if (self->type != JS_CNUMBER) js_typeerror(J, "not a number"); if (width < 1) js_rangeerror(J, "precision %d out of range", width); if (width > 21) js_rangeerror(J, "precision %d out of range", width); x = self->u.number; if (isnan(x) || isinf(x)) js_pushstring(J, jsV_numbertostring(J, buf, x)); else numtostr(J, "%.*g", width, self->u.number); } void jsB_initnumber(js_State *J) { J->Number_prototype->u.number = 0; js_pushobject(J, J->Number_prototype); { jsB_propf(J, "Number.prototype.valueOf", Np_valueOf, 0); jsB_propf(J, "Number.prototype.toString", Np_toString, 1); jsB_propf(J, "Number.prototype.toLocaleString", Np_toString, 0); jsB_propf(J, "Number.prototype.toFixed", Np_toFixed, 1); jsB_propf(J, "Number.prototype.toExponential", Np_toExponential, 1); jsB_propf(J, "Number.prototype.toPrecision", Np_toPrecision, 1); } js_newcconstructor(J, jsB_Number, jsB_new_Number, "Number", 0); /* 1 */ { jsB_propn(J, "MAX_VALUE", 1.7976931348623157e+308); jsB_propn(J, "MIN_VALUE", 5e-324); jsB_propn(J, "NaN", NAN); jsB_propn(J, "NEGATIVE_INFINITY", -INFINITY); jsB_propn(J, "POSITIVE_INFINITY", INFINITY); } js_defglobal(J, "Number", JS_DONTENUM); }
null
118
CWE-787
CVE-2019-11921
/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "StructuredHeadersUtilities.h" #include <boost/archive/iterators/binary_from_base64.hpp> #include <boost/archive/iterators/base64_from_binary.hpp> #include <boost/archive/iterators/transform_width.hpp> #include "StructuredHeadersConstants.h" namespace proxygen { namespace StructuredHeaders { bool isLcAlpha(char c) { return c >= 0x61 && c <= 0x7A; } bool isValidIdentifierChar(char c) { return isLcAlpha(c) || std::isdigit(c) || c == '_' || c == '-' || c == '*' || c == '/'; } bool isValidEncodedBinaryContentChar( char c) { return std::isalpha(c) || std::isdigit(c) || c == '+' || c == '/' || c == '='; } bool isValidStringChar(char c) { /* * The difference between the character restriction here and that mentioned * in section 3.7 of version 6 of the Structured Headers draft is that this * function accepts \ and DQUOTE characters. These characters are allowed * as long as they are present as a part of an escape sequence, which is * checked for in the parseString() function in the StructuredHeadersBuffer. */ return c >= 0x20 && c <= 0x7E; } bool isValidIdentifier(const std::string& s) { if (s.size() == 0 || !isLcAlpha(s[0])) { return false; } for (char c : s) { if (!isValidIdentifierChar(c)) { return false; } } return true; } bool isValidString(const std::string& s) { for (char c : s) { if (!isValidStringChar(c)) { return false; } } return true; } bool isValidEncodedBinaryContent( const std::string& s) { if (s.size() % 4 != 0) { return false; } bool equalSeen = false; for (auto it = s.begin(); it != s.end(); it++) { if (*it == '=') { equalSeen = true; } else if (equalSeen || !isValidEncodedBinaryContentChar(*it)) { return false; } } return true; } bool itemTypeMatchesContent( const StructuredHeaderItem& input) { switch (input.tag) { case StructuredHeaderItem::Type::BINARYCONTENT: case StructuredHeaderItem::Type::IDENTIFIER: case StructuredHeaderItem::Type::STRING: return input.value.type() == typeid(std::string); case StructuredHeaderItem::Type::INT64: return input.value.type() == typeid(int64_t); case StructuredHeaderItem::Type::DOUBLE: return input.value.type() == typeid(double); case StructuredHeaderItem::Type::NONE: return true; } return false; } std::string decodeBase64( const std::string& encoded) { if (encoded.size() == 0) { // special case, to prevent an integer overflow down below. return ""; } using namespace boost::archive::iterators; using b64it = transform_width<binary_from_base64<std::string::const_iterator>, 8, 6>; std::string decoded = std::string(b64it(std::begin(encoded)), b64it(std::end(encoded))); uint32_t numPadding = std::count(encoded.begin(), encoded.end(), '='); decoded.erase(decoded.end() - numPadding, decoded.end()); return decoded; } std::string encodeBase64(const std::string& input) { using namespace boost::archive::iterators; using b64it = base64_from_binary<transform_width<const char*, 6, 8>>; auto data = input.data(); std::string encoded(b64it(data), b64it(data + (input.length()))); encoded.append((3 - (input.length() % 3)) % 3, '='); return encoded; } } }
null
/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "StructuredHeadersUtilities.h" #include "StructuredHeadersConstants.h" #include "proxygen/lib/utils/Base64.h" namespace proxygen { namespace StructuredHeaders { bool isLcAlpha(char c) { return c >= 0x61 && c <= 0x7A; } bool isValidIdentifierChar(char c) { return isLcAlpha(c) || std::isdigit(c) || c == '_' || c == '-' || c == '*' || c == '/'; } bool isValidEncodedBinaryContentChar( char c) { return std::isalpha(c) || std::isdigit(c) || c == '+' || c == '/' || c == '='; } bool isValidStringChar(char c) { /* * The difference between the character restriction here and that mentioned * in section 3.7 of version 6 of the Structured Headers draft is that this * function accepts \ and DQUOTE characters. These characters are allowed * as long as they are present as a part of an escape sequence, which is * checked for in the parseString() function in the StructuredHeadersBuffer. */ return c >= 0x20 && c <= 0x7E; } bool isValidIdentifier(const std::string& s) { if (s.size() == 0 || !isLcAlpha(s[0])) { return false; } for (char c : s) { if (!isValidIdentifierChar(c)) { return false; } } return true; } bool isValidString(const std::string& s) { for (char c : s) { if (!isValidStringChar(c)) { return false; } } return true; } bool isValidEncodedBinaryContent( const std::string& s) { if (s.size() % 4 != 0) { return false; } bool equalSeen = false; for (auto it = s.begin(); it != s.end(); it++) { if (*it == '=') { equalSeen = true; } else if (equalSeen || !isValidEncodedBinaryContentChar(*it)) { return false; } } return true; } bool itemTypeMatchesContent( const StructuredHeaderItem& input) { switch (input.tag) { case StructuredHeaderItem::Type::BINARYCONTENT: case StructuredHeaderItem::Type::IDENTIFIER: case StructuredHeaderItem::Type::STRING: return input.value.type() == typeid(std::string); case StructuredHeaderItem::Type::INT64: return input.value.type() == typeid(int64_t); case StructuredHeaderItem::Type::DOUBLE: return input.value.type() == typeid(double); case StructuredHeaderItem::Type::NONE: return true; } return false; } std::string decodeBase64( const std::string& encoded) { if (encoded.size() == 0) { // special case, to prevent an integer overflow down below. return std::string(); } int padding = 0; for (auto it = encoded.rbegin(); padding < 2 && it != encoded.rend() && *it == '='; ++it) { ++padding; } return Base64::decode(encoded, padding); } std::string encodeBase64(const std::string& input) { return Base64::encode(folly::ByteRange( reinterpret_cast<const uint8_t*>(input.c_str()), input.length())); } } }
null
119
CWE-787
CVE-2019-12900
/*-------------------------------------------------------------*/ /*--- Decompression machinery ---*/ /*--- decompress.c ---*/ /*-------------------------------------------------------------*/ /* ------------------------------------------------------------------ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. bzip2/libbzip2 version 1.0.6 of 6 September 2010 Copyright (C) 1996-2010 Julian Seward <jseward@acm.org> Please read the WARNING, DISCLAIMER and PATENTS sections in the README file. This program is released under the terms of the license contained in the file LICENSE. ------------------------------------------------------------------ */ #include "bzlib_private.h" /*---------------------------------------------------*/ static void makeMaps_d ( DState* s ) { Int32 i; s->nInUse = 0; for (i = 0; i < 256; i++) if (s->inUse[i]) { s->seqToUnseq[s->nInUse] = i; s->nInUse++; } } /*---------------------------------------------------*/ #define RETURN(rrr) \ { retVal = rrr; goto save_state_and_return; }; #define GET_BITS(lll,vvv,nnn) \ case lll: s->state = lll; \ while (True) { \ if (s->bsLive >= nnn) { \ UInt32 v; \ v = (s->bsBuff >> \ (s->bsLive-nnn)) & ((1 << nnn)-1); \ s->bsLive -= nnn; \ vvv = v; \ break; \ } \ if (s->strm->avail_in == 0) RETURN(BZ_OK); \ s->bsBuff \ = (s->bsBuff << 8) | \ ((UInt32) \ (*((UChar*)(s->strm->next_in)))); \ s->bsLive += 8; \ s->strm->next_in++; \ s->strm->avail_in--; \ s->strm->total_in_lo32++; \ if (s->strm->total_in_lo32 == 0) \ s->strm->total_in_hi32++; \ } #define GET_UCHAR(lll,uuu) \ GET_BITS(lll,uuu,8) #define GET_BIT(lll,uuu) \ GET_BITS(lll,uuu,1) /*---------------------------------------------------*/ #define GET_MTF_VAL(label1,label2,lval) \ { \ if (groupPos == 0) { \ groupNo++; \ if (groupNo >= nSelectors) \ RETURN(BZ_DATA_ERROR); \ groupPos = BZ_G_SIZE; \ gSel = s->selector[groupNo]; \ gMinlen = s->minLens[gSel]; \ gLimit = &(s->limit[gSel][0]); \ gPerm = &(s->perm[gSel][0]); \ gBase = &(s->base[gSel][0]); \ } \ groupPos--; \ zn = gMinlen; \ GET_BITS(label1, zvec, zn); \ while (1) { \ if (zn > 20 /* the longest code */) \ RETURN(BZ_DATA_ERROR); \ if (zvec <= gLimit[zn]) break; \ zn++; \ GET_BIT(label2, zj); \ zvec = (zvec << 1) | zj; \ }; \ if (zvec - gBase[zn] < 0 \ || zvec - gBase[zn] >= BZ_MAX_ALPHA_SIZE) \ RETURN(BZ_DATA_ERROR); \ lval = gPerm[zvec - gBase[zn]]; \ } /*---------------------------------------------------*/ Int32 BZ2_decompress ( DState* s ) { UChar uc; Int32 retVal; Int32 minLen, maxLen; bz_stream* strm = s->strm; /* stuff that needs to be saved/restored */ Int32 i; Int32 j; Int32 t; Int32 alphaSize; Int32 nGroups; Int32 nSelectors; Int32 EOB; Int32 groupNo; Int32 groupPos; Int32 nextSym; Int32 nblockMAX; Int32 nblock; Int32 es; Int32 N; Int32 curr; Int32 zt; Int32 zn; Int32 zvec; Int32 zj; Int32 gSel; Int32 gMinlen; Int32* gLimit; Int32* gBase; Int32* gPerm; if (s->state == BZ_X_MAGIC_1) { /*initialise the save area*/ s->save_i = 0; s->save_j = 0; s->save_t = 0; s->save_alphaSize = 0; s->save_nGroups = 0; s->save_nSelectors = 0; s->save_EOB = 0; s->save_groupNo = 0; s->save_groupPos = 0; s->save_nextSym = 0; s->save_nblockMAX = 0; s->save_nblock = 0; s->save_es = 0; s->save_N = 0; s->save_curr = 0; s->save_zt = 0; s->save_zn = 0; s->save_zvec = 0; s->save_zj = 0; s->save_gSel = 0; s->save_gMinlen = 0; s->save_gLimit = NULL; s->save_gBase = NULL; s->save_gPerm = NULL; } /*restore from the save area*/ i = s->save_i; j = s->save_j; t = s->save_t; alphaSize = s->save_alphaSize; nGroups = s->save_nGroups; nSelectors = s->save_nSelectors; EOB = s->save_EOB; groupNo = s->save_groupNo; groupPos = s->save_groupPos; nextSym = s->save_nextSym; nblockMAX = s->save_nblockMAX; nblock = s->save_nblock; es = s->save_es; N = s->save_N; curr = s->save_curr; zt = s->save_zt; zn = s->save_zn; zvec = s->save_zvec; zj = s->save_zj; gSel = s->save_gSel; gMinlen = s->save_gMinlen; gLimit = s->save_gLimit; gBase = s->save_gBase; gPerm = s->save_gPerm; retVal = BZ_OK; switch (s->state) { GET_UCHAR(BZ_X_MAGIC_1, uc); if (uc != BZ_HDR_B) RETURN(BZ_DATA_ERROR_MAGIC); GET_UCHAR(BZ_X_MAGIC_2, uc); if (uc != BZ_HDR_Z) RETURN(BZ_DATA_ERROR_MAGIC); GET_UCHAR(BZ_X_MAGIC_3, uc) if (uc != BZ_HDR_h) RETURN(BZ_DATA_ERROR_MAGIC); GET_BITS(BZ_X_MAGIC_4, s->blockSize100k, 8) if (s->blockSize100k < (BZ_HDR_0 + 1) || s->blockSize100k > (BZ_HDR_0 + 9)) RETURN(BZ_DATA_ERROR_MAGIC); s->blockSize100k -= BZ_HDR_0; if (s->smallDecompress) { s->ll16 = BZALLOC( s->blockSize100k * 100000 * sizeof(UInt16) ); s->ll4 = BZALLOC( ((1 + s->blockSize100k * 100000) >> 1) * sizeof(UChar) ); if (s->ll16 == NULL || s->ll4 == NULL) RETURN(BZ_MEM_ERROR); } else { s->tt = BZALLOC( s->blockSize100k * 100000 * sizeof(Int32) ); if (s->tt == NULL) RETURN(BZ_MEM_ERROR); } GET_UCHAR(BZ_X_BLKHDR_1, uc); if (uc == 0x17) goto endhdr_2; if (uc != 0x31) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_2, uc); if (uc != 0x41) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_3, uc); if (uc != 0x59) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_4, uc); if (uc != 0x26) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_5, uc); if (uc != 0x53) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_6, uc); if (uc != 0x59) RETURN(BZ_DATA_ERROR); s->currBlockNo++; if (s->verbosity >= 2) VPrintf1 ( "\n [%d: huff+mtf ", s->currBlockNo ); s->storedBlockCRC = 0; GET_UCHAR(BZ_X_BCRC_1, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_BCRC_2, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_BCRC_3, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_BCRC_4, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_BITS(BZ_X_RANDBIT, s->blockRandomised, 1); s->origPtr = 0; GET_UCHAR(BZ_X_ORIGPTR_1, uc); s->origPtr = (s->origPtr << 8) | ((Int32)uc); GET_UCHAR(BZ_X_ORIGPTR_2, uc); s->origPtr = (s->origPtr << 8) | ((Int32)uc); GET_UCHAR(BZ_X_ORIGPTR_3, uc); s->origPtr = (s->origPtr << 8) | ((Int32)uc); if (s->origPtr < 0) RETURN(BZ_DATA_ERROR); if (s->origPtr > 10 + 100000*s->blockSize100k) RETURN(BZ_DATA_ERROR); /*--- Receive the mapping table ---*/ for (i = 0; i < 16; i++) { GET_BIT(BZ_X_MAPPING_1, uc); if (uc == 1) s->inUse16[i] = True; else s->inUse16[i] = False; } for (i = 0; i < 256; i++) s->inUse[i] = False; for (i = 0; i < 16; i++) if (s->inUse16[i]) for (j = 0; j < 16; j++) { GET_BIT(BZ_X_MAPPING_2, uc); if (uc == 1) s->inUse[i * 16 + j] = True; } makeMaps_d ( s ); if (s->nInUse == 0) RETURN(BZ_DATA_ERROR); alphaSize = s->nInUse+2; /*--- Now the selectors ---*/ GET_BITS(BZ_X_SELECTOR_1, nGroups, 3); if (nGroups < 2 || nGroups > 6) RETURN(BZ_DATA_ERROR); GET_BITS(BZ_X_SELECTOR_2, nSelectors, 15); if (nSelectors < 1) RETURN(BZ_DATA_ERROR); for (i = 0; i < nSelectors; i++) { j = 0; while (True) { GET_BIT(BZ_X_SELECTOR_3, uc); if (uc == 0) break; j++; if (j >= nGroups) RETURN(BZ_DATA_ERROR); } s->selectorMtf[i] = j; } /*--- Undo the MTF values for the selectors. ---*/ { UChar pos[BZ_N_GROUPS], tmp, v; for (v = 0; v < nGroups; v++) pos[v] = v; for (i = 0; i < nSelectors; i++) { v = s->selectorMtf[i]; tmp = pos[v]; while (v > 0) { pos[v] = pos[v-1]; v--; } pos[0] = tmp; s->selector[i] = tmp; } } /*--- Now the coding tables ---*/ for (t = 0; t < nGroups; t++) { GET_BITS(BZ_X_CODING_1, curr, 5); for (i = 0; i < alphaSize; i++) { while (True) { if (curr < 1 || curr > 20) RETURN(BZ_DATA_ERROR); GET_BIT(BZ_X_CODING_2, uc); if (uc == 0) break; GET_BIT(BZ_X_CODING_3, uc); if (uc == 0) curr++; else curr--; } s->len[t][i] = curr; } } /*--- Create the Huffman decoding tables ---*/ for (t = 0; t < nGroups; t++) { minLen = 32; maxLen = 0; for (i = 0; i < alphaSize; i++) { if (s->len[t][i] > maxLen) maxLen = s->len[t][i]; if (s->len[t][i] < minLen) minLen = s->len[t][i]; } BZ2_hbCreateDecodeTables ( &(s->limit[t][0]), &(s->base[t][0]), &(s->perm[t][0]), &(s->len[t][0]), minLen, maxLen, alphaSize ); s->minLens[t] = minLen; } /*--- Now the MTF values ---*/ EOB = s->nInUse+1; nblockMAX = 100000 * s->blockSize100k; groupNo = -1; groupPos = 0; for (i = 0; i <= 255; i++) s->unzftab[i] = 0; /*-- MTF init --*/ { Int32 ii, jj, kk; kk = MTFA_SIZE-1; for (ii = 256 / MTFL_SIZE - 1; ii >= 0; ii--) { for (jj = MTFL_SIZE-1; jj >= 0; jj--) { s->mtfa[kk] = (UChar)(ii * MTFL_SIZE + jj); kk--; } s->mtfbase[ii] = kk + 1; } } /*-- end MTF init --*/ nblock = 0; GET_MTF_VAL(BZ_X_MTF_1, BZ_X_MTF_2, nextSym); while (True) { if (nextSym == EOB) break; if (nextSym == BZ_RUNA || nextSym == BZ_RUNB) { es = -1; N = 1; do { /* Check that N doesn't get too big, so that es doesn't go negative. The maximum value that can be RUNA/RUNB encoded is equal to the block size (post the initial RLE), viz, 900k, so bounding N at 2 million should guard against overflow without rejecting any legitimate inputs. */ if (N >= 2*1024*1024) RETURN(BZ_DATA_ERROR); if (nextSym == BZ_RUNA) es = es + (0+1) * N; else if (nextSym == BZ_RUNB) es = es + (1+1) * N; N = N * 2; GET_MTF_VAL(BZ_X_MTF_3, BZ_X_MTF_4, nextSym); } while (nextSym == BZ_RUNA || nextSym == BZ_RUNB); es++; uc = s->seqToUnseq[ s->mtfa[s->mtfbase[0]] ]; s->unzftab[uc] += es; if (s->smallDecompress) while (es > 0) { if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); s->ll16[nblock] = (UInt16)uc; nblock++; es--; } else while (es > 0) { if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); s->tt[nblock] = (UInt32)uc; nblock++; es--; }; continue; } else { if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); /*-- uc = MTF ( nextSym-1 ) --*/ { Int32 ii, jj, kk, pp, lno, off; UInt32 nn; nn = (UInt32)(nextSym - 1); if (nn < MTFL_SIZE) { /* avoid general-case expense */ pp = s->mtfbase[0]; uc = s->mtfa[pp+nn]; while (nn > 3) { Int32 z = pp+nn; s->mtfa[(z) ] = s->mtfa[(z)-1]; s->mtfa[(z)-1] = s->mtfa[(z)-2]; s->mtfa[(z)-2] = s->mtfa[(z)-3]; s->mtfa[(z)-3] = s->mtfa[(z)-4]; nn -= 4; } while (nn > 0) { s->mtfa[(pp+nn)] = s->mtfa[(pp+nn)-1]; nn--; }; s->mtfa[pp] = uc; } else { /* general case */ lno = nn / MTFL_SIZE; off = nn % MTFL_SIZE; pp = s->mtfbase[lno] + off; uc = s->mtfa[pp]; while (pp > s->mtfbase[lno]) { s->mtfa[pp] = s->mtfa[pp-1]; pp--; }; s->mtfbase[lno]++; while (lno > 0) { s->mtfbase[lno]--; s->mtfa[s->mtfbase[lno]] = s->mtfa[s->mtfbase[lno-1] + MTFL_SIZE - 1]; lno--; } s->mtfbase[0]--; s->mtfa[s->mtfbase[0]] = uc; if (s->mtfbase[0] == 0) { kk = MTFA_SIZE-1; for (ii = 256 / MTFL_SIZE-1; ii >= 0; ii--) { for (jj = MTFL_SIZE-1; jj >= 0; jj--) { s->mtfa[kk] = s->mtfa[s->mtfbase[ii] + jj]; kk--; } s->mtfbase[ii] = kk + 1; } } } } /*-- end uc = MTF ( nextSym-1 ) --*/ s->unzftab[s->seqToUnseq[uc]]++; if (s->smallDecompress) s->ll16[nblock] = (UInt16)(s->seqToUnseq[uc]); else s->tt[nblock] = (UInt32)(s->seqToUnseq[uc]); nblock++; GET_MTF_VAL(BZ_X_MTF_5, BZ_X_MTF_6, nextSym); continue; } } /* Now we know what nblock is, we can do a better sanity check on s->origPtr. */ if (s->origPtr < 0 || s->origPtr >= nblock) RETURN(BZ_DATA_ERROR); /*-- Set up cftab to facilitate generation of T^(-1) --*/ /* Check: unzftab entries in range. */ for (i = 0; i <= 255; i++) { if (s->unzftab[i] < 0 || s->unzftab[i] > nblock) RETURN(BZ_DATA_ERROR); } /* Actually generate cftab. */ s->cftab[0] = 0; for (i = 1; i <= 256; i++) s->cftab[i] = s->unzftab[i-1]; for (i = 1; i <= 256; i++) s->cftab[i] += s->cftab[i-1]; /* Check: cftab entries in range. */ for (i = 0; i <= 256; i++) { if (s->cftab[i] < 0 || s->cftab[i] > nblock) { /* s->cftab[i] can legitimately be == nblock */ RETURN(BZ_DATA_ERROR); } } /* Check: cftab entries non-descending. */ for (i = 1; i <= 256; i++) { if (s->cftab[i-1] > s->cftab[i]) { RETURN(BZ_DATA_ERROR); } } s->state_out_len = 0; s->state_out_ch = 0; BZ_INITIALISE_CRC ( s->calculatedBlockCRC ); s->state = BZ_X_OUTPUT; if (s->verbosity >= 2) VPrintf0 ( "rt+rld" ); if (s->smallDecompress) { /*-- Make a copy of cftab, used in generation of T --*/ for (i = 0; i <= 256; i++) s->cftabCopy[i] = s->cftab[i]; /*-- compute the T vector --*/ for (i = 0; i < nblock; i++) { uc = (UChar)(s->ll16[i]); SET_LL(i, s->cftabCopy[uc]); s->cftabCopy[uc]++; } /*-- Compute T^(-1) by pointer reversal on T --*/ i = s->origPtr; j = GET_LL(i); do { Int32 tmp = GET_LL(j); SET_LL(j, i); i = j; j = tmp; } while (i != s->origPtr); s->tPos = s->origPtr; s->nblock_used = 0; if (s->blockRandomised) { BZ_RAND_INIT_MASK; BZ_GET_SMALL(s->k0); s->nblock_used++; BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; } else { BZ_GET_SMALL(s->k0); s->nblock_used++; } } else { /*-- compute the T^(-1) vector --*/ for (i = 0; i < nblock; i++) { uc = (UChar)(s->tt[i] & 0xff); s->tt[s->cftab[uc]] |= (i << 8); s->cftab[uc]++; } s->tPos = s->tt[s->origPtr] >> 8; s->nblock_used = 0; if (s->blockRandomised) { BZ_RAND_INIT_MASK; BZ_GET_FAST(s->k0); s->nblock_used++; BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; } else { BZ_GET_FAST(s->k0); s->nblock_used++; } } RETURN(BZ_OK); endhdr_2: GET_UCHAR(BZ_X_ENDHDR_2, uc); if (uc != 0x72) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_3, uc); if (uc != 0x45) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_4, uc); if (uc != 0x38) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_5, uc); if (uc != 0x50) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_6, uc); if (uc != 0x90) RETURN(BZ_DATA_ERROR); s->storedCombinedCRC = 0; GET_UCHAR(BZ_X_CCRC_1, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_CCRC_2, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_CCRC_3, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_CCRC_4, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); s->state = BZ_X_IDLE; RETURN(BZ_STREAM_END); default: AssertH ( False, 4001 ); } AssertH ( False, 4002 ); save_state_and_return: s->save_i = i; s->save_j = j; s->save_t = t; s->save_alphaSize = alphaSize; s->save_nGroups = nGroups; s->save_nSelectors = nSelectors; s->save_EOB = EOB; s->save_groupNo = groupNo; s->save_groupPos = groupPos; s->save_nextSym = nextSym; s->save_nblockMAX = nblockMAX; s->save_nblock = nblock; s->save_es = es; s->save_N = N; s->save_curr = curr; s->save_zt = zt; s->save_zn = zn; s->save_zvec = zvec; s->save_zj = zj; s->save_gSel = gSel; s->save_gMinlen = gMinlen; s->save_gLimit = gLimit; s->save_gBase = gBase; s->save_gPerm = gPerm; return retVal; } /*-------------------------------------------------------------*/ /*--- end decompress.c ---*/ /*-------------------------------------------------------------*/
null
/*-------------------------------------------------------------*/ /*--- Decompression machinery ---*/ /*--- decompress.c ---*/ /*-------------------------------------------------------------*/ /* ------------------------------------------------------------------ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. bzip2/libbzip2 version 1.0.6 of 6 September 2010 Copyright (C) 1996-2010 Julian Seward <jseward@acm.org> Please read the WARNING, DISCLAIMER and PATENTS sections in the README file. This program is released under the terms of the license contained in the file LICENSE. ------------------------------------------------------------------ */ #include "bzlib_private.h" /*---------------------------------------------------*/ static void makeMaps_d ( DState* s ) { Int32 i; s->nInUse = 0; for (i = 0; i < 256; i++) if (s->inUse[i]) { s->seqToUnseq[s->nInUse] = i; s->nInUse++; } } /*---------------------------------------------------*/ #define RETURN(rrr) \ { retVal = rrr; goto save_state_and_return; }; #define GET_BITS(lll,vvv,nnn) \ case lll: s->state = lll; \ while (True) { \ if (s->bsLive >= nnn) { \ UInt32 v; \ v = (s->bsBuff >> \ (s->bsLive-nnn)) & ((1 << nnn)-1); \ s->bsLive -= nnn; \ vvv = v; \ break; \ } \ if (s->strm->avail_in == 0) RETURN(BZ_OK); \ s->bsBuff \ = (s->bsBuff << 8) | \ ((UInt32) \ (*((UChar*)(s->strm->next_in)))); \ s->bsLive += 8; \ s->strm->next_in++; \ s->strm->avail_in--; \ s->strm->total_in_lo32++; \ if (s->strm->total_in_lo32 == 0) \ s->strm->total_in_hi32++; \ } #define GET_UCHAR(lll,uuu) \ GET_BITS(lll,uuu,8) #define GET_BIT(lll,uuu) \ GET_BITS(lll,uuu,1) /*---------------------------------------------------*/ #define GET_MTF_VAL(label1,label2,lval) \ { \ if (groupPos == 0) { \ groupNo++; \ if (groupNo >= nSelectors) \ RETURN(BZ_DATA_ERROR); \ groupPos = BZ_G_SIZE; \ gSel = s->selector[groupNo]; \ gMinlen = s->minLens[gSel]; \ gLimit = &(s->limit[gSel][0]); \ gPerm = &(s->perm[gSel][0]); \ gBase = &(s->base[gSel][0]); \ } \ groupPos--; \ zn = gMinlen; \ GET_BITS(label1, zvec, zn); \ while (1) { \ if (zn > 20 /* the longest code */) \ RETURN(BZ_DATA_ERROR); \ if (zvec <= gLimit[zn]) break; \ zn++; \ GET_BIT(label2, zj); \ zvec = (zvec << 1) | zj; \ }; \ if (zvec - gBase[zn] < 0 \ || zvec - gBase[zn] >= BZ_MAX_ALPHA_SIZE) \ RETURN(BZ_DATA_ERROR); \ lval = gPerm[zvec - gBase[zn]]; \ } /*---------------------------------------------------*/ Int32 BZ2_decompress ( DState* s ) { UChar uc; Int32 retVal; Int32 minLen, maxLen; bz_stream* strm = s->strm; /* stuff that needs to be saved/restored */ Int32 i; Int32 j; Int32 t; Int32 alphaSize; Int32 nGroups; Int32 nSelectors; Int32 EOB; Int32 groupNo; Int32 groupPos; Int32 nextSym; Int32 nblockMAX; Int32 nblock; Int32 es; Int32 N; Int32 curr; Int32 zt; Int32 zn; Int32 zvec; Int32 zj; Int32 gSel; Int32 gMinlen; Int32* gLimit; Int32* gBase; Int32* gPerm; if (s->state == BZ_X_MAGIC_1) { /*initialise the save area*/ s->save_i = 0; s->save_j = 0; s->save_t = 0; s->save_alphaSize = 0; s->save_nGroups = 0; s->save_nSelectors = 0; s->save_EOB = 0; s->save_groupNo = 0; s->save_groupPos = 0; s->save_nextSym = 0; s->save_nblockMAX = 0; s->save_nblock = 0; s->save_es = 0; s->save_N = 0; s->save_curr = 0; s->save_zt = 0; s->save_zn = 0; s->save_zvec = 0; s->save_zj = 0; s->save_gSel = 0; s->save_gMinlen = 0; s->save_gLimit = NULL; s->save_gBase = NULL; s->save_gPerm = NULL; } /*restore from the save area*/ i = s->save_i; j = s->save_j; t = s->save_t; alphaSize = s->save_alphaSize; nGroups = s->save_nGroups; nSelectors = s->save_nSelectors; EOB = s->save_EOB; groupNo = s->save_groupNo; groupPos = s->save_groupPos; nextSym = s->save_nextSym; nblockMAX = s->save_nblockMAX; nblock = s->save_nblock; es = s->save_es; N = s->save_N; curr = s->save_curr; zt = s->save_zt; zn = s->save_zn; zvec = s->save_zvec; zj = s->save_zj; gSel = s->save_gSel; gMinlen = s->save_gMinlen; gLimit = s->save_gLimit; gBase = s->save_gBase; gPerm = s->save_gPerm; retVal = BZ_OK; switch (s->state) { GET_UCHAR(BZ_X_MAGIC_1, uc); if (uc != BZ_HDR_B) RETURN(BZ_DATA_ERROR_MAGIC); GET_UCHAR(BZ_X_MAGIC_2, uc); if (uc != BZ_HDR_Z) RETURN(BZ_DATA_ERROR_MAGIC); GET_UCHAR(BZ_X_MAGIC_3, uc) if (uc != BZ_HDR_h) RETURN(BZ_DATA_ERROR_MAGIC); GET_BITS(BZ_X_MAGIC_4, s->blockSize100k, 8) if (s->blockSize100k < (BZ_HDR_0 + 1) || s->blockSize100k > (BZ_HDR_0 + 9)) RETURN(BZ_DATA_ERROR_MAGIC); s->blockSize100k -= BZ_HDR_0; if (s->smallDecompress) { s->ll16 = BZALLOC( s->blockSize100k * 100000 * sizeof(UInt16) ); s->ll4 = BZALLOC( ((1 + s->blockSize100k * 100000) >> 1) * sizeof(UChar) ); if (s->ll16 == NULL || s->ll4 == NULL) RETURN(BZ_MEM_ERROR); } else { s->tt = BZALLOC( s->blockSize100k * 100000 * sizeof(Int32) ); if (s->tt == NULL) RETURN(BZ_MEM_ERROR); } GET_UCHAR(BZ_X_BLKHDR_1, uc); if (uc == 0x17) goto endhdr_2; if (uc != 0x31) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_2, uc); if (uc != 0x41) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_3, uc); if (uc != 0x59) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_4, uc); if (uc != 0x26) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_5, uc); if (uc != 0x53) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_BLKHDR_6, uc); if (uc != 0x59) RETURN(BZ_DATA_ERROR); s->currBlockNo++; if (s->verbosity >= 2) VPrintf1 ( "\n [%d: huff+mtf ", s->currBlockNo ); s->storedBlockCRC = 0; GET_UCHAR(BZ_X_BCRC_1, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_BCRC_2, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_BCRC_3, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_BCRC_4, uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); GET_BITS(BZ_X_RANDBIT, s->blockRandomised, 1); s->origPtr = 0; GET_UCHAR(BZ_X_ORIGPTR_1, uc); s->origPtr = (s->origPtr << 8) | ((Int32)uc); GET_UCHAR(BZ_X_ORIGPTR_2, uc); s->origPtr = (s->origPtr << 8) | ((Int32)uc); GET_UCHAR(BZ_X_ORIGPTR_3, uc); s->origPtr = (s->origPtr << 8) | ((Int32)uc); if (s->origPtr < 0) RETURN(BZ_DATA_ERROR); if (s->origPtr > 10 + 100000*s->blockSize100k) RETURN(BZ_DATA_ERROR); /*--- Receive the mapping table ---*/ for (i = 0; i < 16; i++) { GET_BIT(BZ_X_MAPPING_1, uc); if (uc == 1) s->inUse16[i] = True; else s->inUse16[i] = False; } for (i = 0; i < 256; i++) s->inUse[i] = False; for (i = 0; i < 16; i++) if (s->inUse16[i]) for (j = 0; j < 16; j++) { GET_BIT(BZ_X_MAPPING_2, uc); if (uc == 1) s->inUse[i * 16 + j] = True; } makeMaps_d ( s ); if (s->nInUse == 0) RETURN(BZ_DATA_ERROR); alphaSize = s->nInUse+2; /*--- Now the selectors ---*/ GET_BITS(BZ_X_SELECTOR_1, nGroups, 3); if (nGroups < 2 || nGroups > 6) RETURN(BZ_DATA_ERROR); GET_BITS(BZ_X_SELECTOR_2, nSelectors, 15); if (nSelectors < 1 || nSelectors > BZ_MAX_SELECTORS) RETURN(BZ_DATA_ERROR); for (i = 0; i < nSelectors; i++) { j = 0; while (True) { GET_BIT(BZ_X_SELECTOR_3, uc); if (uc == 0) break; j++; if (j >= nGroups) RETURN(BZ_DATA_ERROR); } s->selectorMtf[i] = j; } /*--- Undo the MTF values for the selectors. ---*/ { UChar pos[BZ_N_GROUPS], tmp, v; for (v = 0; v < nGroups; v++) pos[v] = v; for (i = 0; i < nSelectors; i++) { v = s->selectorMtf[i]; tmp = pos[v]; while (v > 0) { pos[v] = pos[v-1]; v--; } pos[0] = tmp; s->selector[i] = tmp; } } /*--- Now the coding tables ---*/ for (t = 0; t < nGroups; t++) { GET_BITS(BZ_X_CODING_1, curr, 5); for (i = 0; i < alphaSize; i++) { while (True) { if (curr < 1 || curr > 20) RETURN(BZ_DATA_ERROR); GET_BIT(BZ_X_CODING_2, uc); if (uc == 0) break; GET_BIT(BZ_X_CODING_3, uc); if (uc == 0) curr++; else curr--; } s->len[t][i] = curr; } } /*--- Create the Huffman decoding tables ---*/ for (t = 0; t < nGroups; t++) { minLen = 32; maxLen = 0; for (i = 0; i < alphaSize; i++) { if (s->len[t][i] > maxLen) maxLen = s->len[t][i]; if (s->len[t][i] < minLen) minLen = s->len[t][i]; } BZ2_hbCreateDecodeTables ( &(s->limit[t][0]), &(s->base[t][0]), &(s->perm[t][0]), &(s->len[t][0]), minLen, maxLen, alphaSize ); s->minLens[t] = minLen; } /*--- Now the MTF values ---*/ EOB = s->nInUse+1; nblockMAX = 100000 * s->blockSize100k; groupNo = -1; groupPos = 0; for (i = 0; i <= 255; i++) s->unzftab[i] = 0; /*-- MTF init --*/ { Int32 ii, jj, kk; kk = MTFA_SIZE-1; for (ii = 256 / MTFL_SIZE - 1; ii >= 0; ii--) { for (jj = MTFL_SIZE-1; jj >= 0; jj--) { s->mtfa[kk] = (UChar)(ii * MTFL_SIZE + jj); kk--; } s->mtfbase[ii] = kk + 1; } } /*-- end MTF init --*/ nblock = 0; GET_MTF_VAL(BZ_X_MTF_1, BZ_X_MTF_2, nextSym); while (True) { if (nextSym == EOB) break; if (nextSym == BZ_RUNA || nextSym == BZ_RUNB) { es = -1; N = 1; do { /* Check that N doesn't get too big, so that es doesn't go negative. The maximum value that can be RUNA/RUNB encoded is equal to the block size (post the initial RLE), viz, 900k, so bounding N at 2 million should guard against overflow without rejecting any legitimate inputs. */ if (N >= 2*1024*1024) RETURN(BZ_DATA_ERROR); if (nextSym == BZ_RUNA) es = es + (0+1) * N; else if (nextSym == BZ_RUNB) es = es + (1+1) * N; N = N * 2; GET_MTF_VAL(BZ_X_MTF_3, BZ_X_MTF_4, nextSym); } while (nextSym == BZ_RUNA || nextSym == BZ_RUNB); es++; uc = s->seqToUnseq[ s->mtfa[s->mtfbase[0]] ]; s->unzftab[uc] += es; if (s->smallDecompress) while (es > 0) { if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); s->ll16[nblock] = (UInt16)uc; nblock++; es--; } else while (es > 0) { if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); s->tt[nblock] = (UInt32)uc; nblock++; es--; }; continue; } else { if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); /*-- uc = MTF ( nextSym-1 ) --*/ { Int32 ii, jj, kk, pp, lno, off; UInt32 nn; nn = (UInt32)(nextSym - 1); if (nn < MTFL_SIZE) { /* avoid general-case expense */ pp = s->mtfbase[0]; uc = s->mtfa[pp+nn]; while (nn > 3) { Int32 z = pp+nn; s->mtfa[(z) ] = s->mtfa[(z)-1]; s->mtfa[(z)-1] = s->mtfa[(z)-2]; s->mtfa[(z)-2] = s->mtfa[(z)-3]; s->mtfa[(z)-3] = s->mtfa[(z)-4]; nn -= 4; } while (nn > 0) { s->mtfa[(pp+nn)] = s->mtfa[(pp+nn)-1]; nn--; }; s->mtfa[pp] = uc; } else { /* general case */ lno = nn / MTFL_SIZE; off = nn % MTFL_SIZE; pp = s->mtfbase[lno] + off; uc = s->mtfa[pp]; while (pp > s->mtfbase[lno]) { s->mtfa[pp] = s->mtfa[pp-1]; pp--; }; s->mtfbase[lno]++; while (lno > 0) { s->mtfbase[lno]--; s->mtfa[s->mtfbase[lno]] = s->mtfa[s->mtfbase[lno-1] + MTFL_SIZE - 1]; lno--; } s->mtfbase[0]--; s->mtfa[s->mtfbase[0]] = uc; if (s->mtfbase[0] == 0) { kk = MTFA_SIZE-1; for (ii = 256 / MTFL_SIZE-1; ii >= 0; ii--) { for (jj = MTFL_SIZE-1; jj >= 0; jj--) { s->mtfa[kk] = s->mtfa[s->mtfbase[ii] + jj]; kk--; } s->mtfbase[ii] = kk + 1; } } } } /*-- end uc = MTF ( nextSym-1 ) --*/ s->unzftab[s->seqToUnseq[uc]]++; if (s->smallDecompress) s->ll16[nblock] = (UInt16)(s->seqToUnseq[uc]); else s->tt[nblock] = (UInt32)(s->seqToUnseq[uc]); nblock++; GET_MTF_VAL(BZ_X_MTF_5, BZ_X_MTF_6, nextSym); continue; } } /* Now we know what nblock is, we can do a better sanity check on s->origPtr. */ if (s->origPtr < 0 || s->origPtr >= nblock) RETURN(BZ_DATA_ERROR); /*-- Set up cftab to facilitate generation of T^(-1) --*/ /* Check: unzftab entries in range. */ for (i = 0; i <= 255; i++) { if (s->unzftab[i] < 0 || s->unzftab[i] > nblock) RETURN(BZ_DATA_ERROR); } /* Actually generate cftab. */ s->cftab[0] = 0; for (i = 1; i <= 256; i++) s->cftab[i] = s->unzftab[i-1]; for (i = 1; i <= 256; i++) s->cftab[i] += s->cftab[i-1]; /* Check: cftab entries in range. */ for (i = 0; i <= 256; i++) { if (s->cftab[i] < 0 || s->cftab[i] > nblock) { /* s->cftab[i] can legitimately be == nblock */ RETURN(BZ_DATA_ERROR); } } /* Check: cftab entries non-descending. */ for (i = 1; i <= 256; i++) { if (s->cftab[i-1] > s->cftab[i]) { RETURN(BZ_DATA_ERROR); } } s->state_out_len = 0; s->state_out_ch = 0; BZ_INITIALISE_CRC ( s->calculatedBlockCRC ); s->state = BZ_X_OUTPUT; if (s->verbosity >= 2) VPrintf0 ( "rt+rld" ); if (s->smallDecompress) { /*-- Make a copy of cftab, used in generation of T --*/ for (i = 0; i <= 256; i++) s->cftabCopy[i] = s->cftab[i]; /*-- compute the T vector --*/ for (i = 0; i < nblock; i++) { uc = (UChar)(s->ll16[i]); SET_LL(i, s->cftabCopy[uc]); s->cftabCopy[uc]++; } /*-- Compute T^(-1) by pointer reversal on T --*/ i = s->origPtr; j = GET_LL(i); do { Int32 tmp = GET_LL(j); SET_LL(j, i); i = j; j = tmp; } while (i != s->origPtr); s->tPos = s->origPtr; s->nblock_used = 0; if (s->blockRandomised) { BZ_RAND_INIT_MASK; BZ_GET_SMALL(s->k0); s->nblock_used++; BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; } else { BZ_GET_SMALL(s->k0); s->nblock_used++; } } else { /*-- compute the T^(-1) vector --*/ for (i = 0; i < nblock; i++) { uc = (UChar)(s->tt[i] & 0xff); s->tt[s->cftab[uc]] |= (i << 8); s->cftab[uc]++; } s->tPos = s->tt[s->origPtr] >> 8; s->nblock_used = 0; if (s->blockRandomised) { BZ_RAND_INIT_MASK; BZ_GET_FAST(s->k0); s->nblock_used++; BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; } else { BZ_GET_FAST(s->k0); s->nblock_used++; } } RETURN(BZ_OK); endhdr_2: GET_UCHAR(BZ_X_ENDHDR_2, uc); if (uc != 0x72) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_3, uc); if (uc != 0x45) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_4, uc); if (uc != 0x38) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_5, uc); if (uc != 0x50) RETURN(BZ_DATA_ERROR); GET_UCHAR(BZ_X_ENDHDR_6, uc); if (uc != 0x90) RETURN(BZ_DATA_ERROR); s->storedCombinedCRC = 0; GET_UCHAR(BZ_X_CCRC_1, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_CCRC_2, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_CCRC_3, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); GET_UCHAR(BZ_X_CCRC_4, uc); s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); s->state = BZ_X_IDLE; RETURN(BZ_STREAM_END); default: AssertH ( False, 4001 ); } AssertH ( False, 4002 ); save_state_and_return: s->save_i = i; s->save_j = j; s->save_t = t; s->save_alphaSize = alphaSize; s->save_nGroups = nGroups; s->save_nSelectors = nSelectors; s->save_EOB = EOB; s->save_groupNo = groupNo; s->save_groupPos = groupPos; s->save_nextSym = nextSym; s->save_nblockMAX = nblockMAX; s->save_nblock = nblock; s->save_es = es; s->save_N = N; s->save_curr = curr; s->save_zt = zt; s->save_zn = zn; s->save_zvec = zvec; s->save_zj = zj; s->save_gSel = gSel; s->save_gMinlen = gMinlen; s->save_gLimit = gLimit; s->save_gBase = gBase; s->save_gPerm = gPerm; return retVal; } /*-------------------------------------------------------------*/ /*--- end decompress.c ---*/ /*-------------------------------------------------------------*/
null
120
CWE-787
CVE-2019-12951
#include "mongoose.h" #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_internal.h" #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ #ifndef CS_MONGOOSE_SRC_INTERNAL_H_ #define CS_MONGOOSE_SRC_INTERNAL_H_ /* Amalgamated: #include "common/mg_mem.h" */ #ifndef MBUF_REALLOC #define MBUF_REALLOC MG_REALLOC #endif #ifndef MBUF_FREE #define MBUF_FREE MG_FREE #endif #define MG_SET_PTRPTR(_ptr, _v) \ do { \ if (_ptr) *(_ptr) = _v; \ } while (0) #ifndef MG_INTERNAL #define MG_INTERNAL static #endif #ifdef PICOTCP #define NO_LIBC #define MG_DISABLE_PFS #endif /* Amalgamated: #include "common/cs_dbg.h" */ /* Amalgamated: #include "mg_http.h" */ /* Amalgamated: #include "mg_net.h" */ #ifndef MG_CTL_MSG_MESSAGE_SIZE #define MG_CTL_MSG_MESSAGE_SIZE 8192 #endif /* internals that need to be accessible in unit tests */ MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc, int proto, union socket_address *sa); MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa, int *proto, char *host, size_t host_len); MG_INTERNAL void mg_call(struct mg_connection *nc, mg_event_handler_t ev_handler, void *user_data, int ev, void *ev_data); void mg_forward(struct mg_connection *from, struct mg_connection *to); MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c); MG_INTERNAL void mg_remove_conn(struct mg_connection *c); MG_INTERNAL struct mg_connection *mg_create_connection( struct mg_mgr *mgr, mg_event_handler_t callback, struct mg_add_sock_opts opts); #ifdef _WIN32 /* Retur value is the same as for MultiByteToWideChar. */ int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len); #endif struct ctl_msg { mg_event_handler_t callback; char message[MG_CTL_MSG_MESSAGE_SIZE]; }; #if MG_ENABLE_MQTT struct mg_mqtt_message; #define MG_MQTT_ERROR_INCOMPLETE_MSG -1 #define MG_MQTT_ERROR_MALFORMED_MSG -2 MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm); #endif /* Forward declarations for testing. */ extern void *(*test_malloc)(size_t size); extern void *(*test_calloc)(size_t count, size_t size); #ifndef MIN #define MIN(a, b) ((a) < (b) ? (a) : (b)) #endif #if MG_ENABLE_HTTP struct mg_serve_http_opts; MG_INTERNAL struct mg_http_proto_data *mg_http_create_proto_data( struct mg_connection *c); /* * Reassemble the content of the buffer (buf, blen) which should be * in the HTTP chunked encoding, by collapsing data chunks to the * beginning of the buffer. * * If chunks get reassembled, modify hm->body to point to the reassembled * body and fire MG_EV_HTTP_CHUNK event. If handler sets MG_F_DELETE_CHUNK * in nc->flags, delete reassembled body from the mbuf. * * Return reassembled body size. */ MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc, struct http_message *hm, char *buf, size_t blen); #if MG_ENABLE_FILESYSTEM MG_INTERNAL int mg_uri_to_local_path(struct http_message *hm, const struct mg_serve_http_opts *opts, char **local_path, struct mg_str *remainder); MG_INTERNAL time_t mg_parse_date_string(const char *datetime); MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st); #endif #if MG_ENABLE_HTTP_CGI MG_INTERNAL void mg_handle_cgi(struct mg_connection *nc, const char *prog, const struct mg_str *path_info, const struct http_message *hm, const struct mg_serve_http_opts *opts); struct mg_http_proto_data_cgi; MG_INTERNAL void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d); #endif #if MG_ENABLE_HTTP_SSI MG_INTERNAL void mg_handle_ssi_request(struct mg_connection *nc, struct http_message *hm, const char *path, const struct mg_serve_http_opts *opts); #endif #if MG_ENABLE_HTTP_WEBDAV MG_INTERNAL int mg_is_dav_request(const struct mg_str *s); MG_INTERNAL void mg_handle_propfind(struct mg_connection *nc, const char *path, cs_stat_t *stp, struct http_message *hm, struct mg_serve_http_opts *opts); MG_INTERNAL void mg_handle_lock(struct mg_connection *nc, const char *path); MG_INTERNAL void mg_handle_mkcol(struct mg_connection *nc, const char *path, struct http_message *hm); MG_INTERNAL void mg_handle_move(struct mg_connection *c, const struct mg_serve_http_opts *opts, const char *path, struct http_message *hm); MG_INTERNAL void mg_handle_delete(struct mg_connection *nc, const struct mg_serve_http_opts *opts, const char *path); MG_INTERNAL void mg_handle_put(struct mg_connection *nc, const char *path, struct http_message *hm); #endif #if MG_ENABLE_HTTP_WEBSOCKET MG_INTERNAL void mg_ws_handler(struct mg_connection *nc, int ev, void *ev_data MG_UD_ARG(void *user_data)); MG_INTERNAL void mg_ws_handshake(struct mg_connection *nc, const struct mg_str *key, struct http_message *); #endif #endif /* MG_ENABLE_HTTP */ MG_INTERNAL int mg_get_errno(void); MG_INTERNAL void mg_close_conn(struct mg_connection *conn); #if MG_ENABLE_SNTP MG_INTERNAL int mg_sntp_parse_reply(const char *buf, int len, struct mg_sntp_message *msg); #endif #endif /* CS_MONGOOSE_SRC_INTERNAL_H_ */ #ifdef MG_MODULE_LINES #line 1 "common/mg_mem.h" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CS_COMMON_MG_MEM_H_ #define CS_COMMON_MG_MEM_H_ #ifdef __cplusplus extern "C" { #endif #ifndef MG_MALLOC #define MG_MALLOC malloc #endif #ifndef MG_CALLOC #define MG_CALLOC calloc #endif #ifndef MG_REALLOC #define MG_REALLOC realloc #endif #ifndef MG_FREE #define MG_FREE free #endif #ifdef __cplusplus } #endif #endif /* CS_COMMON_MG_MEM_H_ */ #ifdef MG_MODULE_LINES #line 1 "common/cs_base64.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef EXCLUDE_COMMON /* Amalgamated: #include "common/cs_base64.h" */ #include <string.h> /* Amalgamated: #include "common/cs_dbg.h" */ /* ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ */ #define NUM_UPPERCASES ('Z' - 'A' + 1) #define NUM_LETTERS (NUM_UPPERCASES * 2) #define NUM_DIGITS ('9' - '0' + 1) /* * Emit a base64 code char. * * Doesn't use memory, thus it's safe to use to safely dump memory in crashdumps */ static void cs_base64_emit_code(struct cs_base64_ctx *ctx, int v) { if (v < NUM_UPPERCASES) { ctx->b64_putc(v + 'A', ctx->user_data); } else if (v < (NUM_LETTERS)) { ctx->b64_putc(v - NUM_UPPERCASES + 'a', ctx->user_data); } else if (v < (NUM_LETTERS + NUM_DIGITS)) { ctx->b64_putc(v - NUM_LETTERS + '0', ctx->user_data); } else { ctx->b64_putc(v - NUM_LETTERS - NUM_DIGITS == 0 ? '+' : '/', ctx->user_data); } } static void cs_base64_emit_chunk(struct cs_base64_ctx *ctx) { int a, b, c; a = ctx->chunk[0]; b = ctx->chunk[1]; c = ctx->chunk[2]; cs_base64_emit_code(ctx, a >> 2); cs_base64_emit_code(ctx, ((a & 3) << 4) | (b >> 4)); if (ctx->chunk_size > 1) { cs_base64_emit_code(ctx, (b & 15) << 2 | (c >> 6)); } if (ctx->chunk_size > 2) { cs_base64_emit_code(ctx, c & 63); } } void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t b64_putc, void *user_data) { ctx->chunk_size = 0; ctx->b64_putc = b64_putc; ctx->user_data = user_data; } void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len) { const unsigned char *src = (const unsigned char *) str; size_t i; for (i = 0; i < len; i++) { ctx->chunk[ctx->chunk_size++] = src[i]; if (ctx->chunk_size == 3) { cs_base64_emit_chunk(ctx); ctx->chunk_size = 0; } } } void cs_base64_finish(struct cs_base64_ctx *ctx) { if (ctx->chunk_size > 0) { int i; memset(&ctx->chunk[ctx->chunk_size], 0, 3 - ctx->chunk_size); cs_base64_emit_chunk(ctx); for (i = 0; i < (3 - ctx->chunk_size); i++) { ctx->b64_putc('=', ctx->user_data); } } } #define BASE64_ENCODE_BODY \ static const char *b64 = \ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; \ int i, j, a, b, c; \ \ for (i = j = 0; i < src_len; i += 3) { \ a = src[i]; \ b = i + 1 >= src_len ? 0 : src[i + 1]; \ c = i + 2 >= src_len ? 0 : src[i + 2]; \ \ BASE64_OUT(b64[a >> 2]); \ BASE64_OUT(b64[((a & 3) << 4) | (b >> 4)]); \ if (i + 1 < src_len) { \ BASE64_OUT(b64[(b & 15) << 2 | (c >> 6)]); \ } \ if (i + 2 < src_len) { \ BASE64_OUT(b64[c & 63]); \ } \ } \ \ while (j % 4 != 0) { \ BASE64_OUT('='); \ } \ BASE64_FLUSH() #define BASE64_OUT(ch) \ do { \ dst[j++] = (ch); \ } while (0) #define BASE64_FLUSH() \ do { \ dst[j++] = '\0'; \ } while (0) void cs_base64_encode(const unsigned char *src, int src_len, char *dst) { BASE64_ENCODE_BODY; } #undef BASE64_OUT #undef BASE64_FLUSH #if CS_ENABLE_STDIO #define BASE64_OUT(ch) \ do { \ fprintf(f, "%c", (ch)); \ j++; \ } while (0) #define BASE64_FLUSH() void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len) { BASE64_ENCODE_BODY; } #undef BASE64_OUT #undef BASE64_FLUSH #endif /* CS_ENABLE_STDIO */ /* Convert one byte of encoded base64 input stream to 6-bit chunk */ static unsigned char from_b64(unsigned char ch) { /* Inverse lookup map */ static const unsigned char tab[128] = { 255, 255, 255, 255, 255, 255, 255, 255, /* 0 */ 255, 255, 255, 255, 255, 255, 255, 255, /* 8 */ 255, 255, 255, 255, 255, 255, 255, 255, /* 16 */ 255, 255, 255, 255, 255, 255, 255, 255, /* 24 */ 255, 255, 255, 255, 255, 255, 255, 255, /* 32 */ 255, 255, 255, 62, 255, 255, 255, 63, /* 40 */ 52, 53, 54, 55, 56, 57, 58, 59, /* 48 */ 60, 61, 255, 255, 255, 200, 255, 255, /* 56 '=' is 200, on index 61 */ 255, 0, 1, 2, 3, 4, 5, 6, /* 64 */ 7, 8, 9, 10, 11, 12, 13, 14, /* 72 */ 15, 16, 17, 18, 19, 20, 21, 22, /* 80 */ 23, 24, 25, 255, 255, 255, 255, 255, /* 88 */ 255, 26, 27, 28, 29, 30, 31, 32, /* 96 */ 33, 34, 35, 36, 37, 38, 39, 40, /* 104 */ 41, 42, 43, 44, 45, 46, 47, 48, /* 112 */ 49, 50, 51, 255, 255, 255, 255, 255, /* 120 */ }; return tab[ch & 127]; } int cs_base64_decode(const unsigned char *s, int len, char *dst, int *dec_len) { unsigned char a, b, c, d; int orig_len = len; char *orig_dst = dst; while (len >= 4 && (a = from_b64(s[0])) != 255 && (b = from_b64(s[1])) != 255 && (c = from_b64(s[2])) != 255 && (d = from_b64(s[3])) != 255) { s += 4; len -= 4; if (a == 200 || b == 200) break; /* '=' can't be there */ *dst++ = a << 2 | b >> 4; if (c == 200) break; *dst++ = b << 4 | c >> 2; if (d == 200) break; *dst++ = c << 6 | d; } *dst = 0; if (dec_len != NULL) *dec_len = (dst - orig_dst); return orig_len - len; } #endif /* EXCLUDE_COMMON */ #ifdef MG_MODULE_LINES #line 1 "common/cs_dbg.h" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CS_COMMON_CS_DBG_H_ #define CS_COMMON_CS_DBG_H_ /* Amalgamated: #include "common/platform.h" */ #if CS_ENABLE_STDIO #include <stdio.h> #endif #ifndef CS_ENABLE_DEBUG #define CS_ENABLE_DEBUG 0 #endif #ifndef CS_LOG_PREFIX_LEN #define CS_LOG_PREFIX_LEN 24 #endif #ifndef CS_LOG_ENABLE_TS_DIFF #define CS_LOG_ENABLE_TS_DIFF 0 #endif #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* * Log level; `LL_INFO` is the default. Use `cs_log_set_level()` to change it. */ enum cs_log_level { LL_NONE = -1, LL_ERROR = 0, LL_WARN = 1, LL_INFO = 2, LL_DEBUG = 3, LL_VERBOSE_DEBUG = 4, _LL_MIN = -2, _LL_MAX = 5, }; /* * Set max log level to print; messages with the level above the given one will * not be printed. */ void cs_log_set_level(enum cs_log_level level); /* * A comma-separated set of prefix=level. * prefix is matched against the log prefix exactly as printed, including line * number, but partial match is ok. Check stops on first matching entry. * If nothing matches, default level is used. * * Examples: * main.c:=4 - everything from main C at verbose debug level. * mongoose.c=1,mjs.c=1,=4 - everything at verbose debug except mg_* and mjs_* * */ void cs_log_set_file_level(const char *file_level); /* * Helper function which prints message prefix with the given `level`. * If message should be printed (according to the current log level * and filter), prints the prefix and returns 1, otherwise returns 0. * * Clients should typically just use `LOG()` macro. */ int cs_log_print_prefix(enum cs_log_level level, const char *fname, int line); extern enum cs_log_level cs_log_level; #if CS_ENABLE_STDIO /* * Set file to write logs into. If `NULL`, logs go to `stderr`. */ void cs_log_set_file(FILE *file); /* * Prints log to the current log file, appends "\n" in the end and flushes the * stream. */ void cs_log_printf(const char *fmt, ...) PRINTF_LIKE(1, 2); #if CS_ENABLE_STDIO /* * Format and print message `x` with the given level `l`. Example: * * ```c * LOG(LL_INFO, ("my info message: %d", 123)); * LOG(LL_DEBUG, ("my debug message: %d", 123)); * ``` */ #define LOG(l, x) \ do { \ if (cs_log_print_prefix(l, __FILE__, __LINE__)) { \ cs_log_printf x; \ } \ } while (0) #else #define LOG(l, x) ((void) l) #endif #ifndef CS_NDEBUG /* * Shortcut for `LOG(LL_VERBOSE_DEBUG, (...))` */ #define DBG(x) LOG(LL_VERBOSE_DEBUG, x) #else /* NDEBUG */ #define DBG(x) #endif #else /* CS_ENABLE_STDIO */ #define LOG(l, x) #define DBG(x) #endif #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* CS_COMMON_CS_DBG_H_ */ #ifdef MG_MODULE_LINES #line 1 "common/cs_dbg.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Amalgamated: #include "common/cs_dbg.h" */ #include <stdarg.h> #include <stdio.h> #include <string.h> /* Amalgamated: #include "common/cs_time.h" */ /* Amalgamated: #include "common/str_util.h" */ enum cs_log_level cs_log_level WEAK = #if CS_ENABLE_DEBUG LL_VERBOSE_DEBUG; #else LL_ERROR; #endif #if CS_ENABLE_STDIO static char *s_file_level = NULL; void cs_log_set_file_level(const char *file_level) WEAK; FILE *cs_log_file WEAK = NULL; #if CS_LOG_ENABLE_TS_DIFF double cs_log_ts WEAK; #endif enum cs_log_level cs_log_cur_msg_level WEAK = LL_NONE; void cs_log_set_file_level(const char *file_level) { char *fl = s_file_level; if (file_level != NULL) { s_file_level = strdup(file_level); } else { s_file_level = NULL; } free(fl); } int cs_log_print_prefix(enum cs_log_level level, const char *file, int ln) WEAK; int cs_log_print_prefix(enum cs_log_level level, const char *file, int ln) { char prefix[CS_LOG_PREFIX_LEN], *q; const char *p; size_t fl = 0, ll = 0, pl = 0; if (level > cs_log_level && s_file_level == NULL) return 0; p = file + strlen(file); while (p != file) { const char c = *(p - 1); if (c == '/' || c == '\\') break; p--; fl++; } ll = (ln < 10000 ? (ln < 1000 ? (ln < 100 ? (ln < 10 ? 1 : 2) : 3) : 4) : 5); if (fl > (sizeof(prefix) - ll - 2)) fl = (sizeof(prefix) - ll - 2); pl = fl + 1 + ll; memcpy(prefix, p, fl); q = prefix + pl; memset(q, ' ', sizeof(prefix) - pl); do { *(--q) = '0' + (ln % 10); ln /= 10; } while (ln > 0); *(--q) = ':'; if (s_file_level != NULL) { enum cs_log_level pll = cs_log_level; struct mg_str fl = mg_mk_str(s_file_level), ps = MG_MK_STR_N(prefix, pl); struct mg_str k, v; while ((fl = mg_next_comma_list_entry_n(fl, &k, &v)).p != NULL) { bool yes = !(!mg_str_starts_with(ps, k) || v.len == 0); if (!yes) continue; pll = (enum cs_log_level)(*v.p - '0'); break; } if (level > pll) return 0; } if (cs_log_file == NULL) cs_log_file = stderr; cs_log_cur_msg_level = level; fwrite(prefix, 1, sizeof(prefix), cs_log_file); #if CS_LOG_ENABLE_TS_DIFF { double now = cs_time(); fprintf(cs_log_file, "%7u ", (unsigned int) ((now - cs_log_ts) * 1000000)); cs_log_ts = now; } #endif return 1; } void cs_log_printf(const char *fmt, ...) WEAK; void cs_log_printf(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vfprintf(cs_log_file, fmt, ap); va_end(ap); fputc('\n', cs_log_file); fflush(cs_log_file); cs_log_cur_msg_level = LL_NONE; } void cs_log_set_file(FILE *file) WEAK; void cs_log_set_file(FILE *file) { cs_log_file = file; } #else void cs_log_set_file_level(const char *file_level) { (void) file_level; } #endif /* CS_ENABLE_STDIO */ void cs_log_set_level(enum cs_log_level level) WEAK; void cs_log_set_level(enum cs_log_level level) { cs_log_level = level; #if CS_LOG_ENABLE_TS_DIFF && CS_ENABLE_STDIO cs_log_ts = cs_time(); #endif } #ifdef MG_MODULE_LINES #line 1 "common/cs_dirent.h" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CS_COMMON_CS_DIRENT_H_ #define CS_COMMON_CS_DIRENT_H_ #include <limits.h> /* Amalgamated: #include "common/platform.h" */ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #ifdef CS_DEFINE_DIRENT typedef struct { int dummy; } DIR; struct dirent { int d_ino; #ifdef _WIN32 char d_name[MAX_PATH]; #else /* TODO(rojer): Use PATH_MAX but make sure it's sane on every platform */ char d_name[256]; #endif }; DIR *opendir(const char *dir_name); int closedir(DIR *dir); struct dirent *readdir(DIR *dir); #endif /* CS_DEFINE_DIRENT */ #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* CS_COMMON_CS_DIRENT_H_ */ #ifdef MG_MODULE_LINES #line 1 "common/cs_dirent.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef EXCLUDE_COMMON /* Amalgamated: #include "common/mg_mem.h" */ /* Amalgamated: #include "common/cs_dirent.h" */ /* * This file contains POSIX opendir/closedir/readdir API implementation * for systems which do not natively support it (e.g. Windows). */ #ifdef _WIN32 struct win32_dir { DIR d; HANDLE handle; WIN32_FIND_DATAW info; struct dirent result; }; DIR *opendir(const char *name) { struct win32_dir *dir = NULL; wchar_t wpath[MAX_PATH]; DWORD attrs; if (name == NULL) { SetLastError(ERROR_BAD_ARGUMENTS); } else if ((dir = (struct win32_dir *) MG_MALLOC(sizeof(*dir))) == NULL) { SetLastError(ERROR_NOT_ENOUGH_MEMORY); } else { to_wchar(name, wpath, ARRAY_SIZE(wpath)); attrs = GetFileAttributesW(wpath); if (attrs != 0xFFFFFFFF && (attrs & FILE_ATTRIBUTE_DIRECTORY)) { (void) wcscat(wpath, L"\\*"); dir->handle = FindFirstFileW(wpath, &dir->info); dir->result.d_name[0] = '\0'; } else { MG_FREE(dir); dir = NULL; } } return (DIR *) dir; } int closedir(DIR *d) { struct win32_dir *dir = (struct win32_dir *) d; int result = 0; if (dir != NULL) { if (dir->handle != INVALID_HANDLE_VALUE) result = FindClose(dir->handle) ? 0 : -1; MG_FREE(dir); } else { result = -1; SetLastError(ERROR_BAD_ARGUMENTS); } return result; } struct dirent *readdir(DIR *d) { struct win32_dir *dir = (struct win32_dir *) d; struct dirent *result = NULL; if (dir) { memset(&dir->result, 0, sizeof(dir->result)); if (dir->handle != INVALID_HANDLE_VALUE) { result = &dir->result; (void) WideCharToMultiByte(CP_UTF8, 0, dir->info.cFileName, -1, result->d_name, sizeof(result->d_name), NULL, NULL); if (!FindNextFileW(dir->handle, &dir->info)) { (void) FindClose(dir->handle); dir->handle = INVALID_HANDLE_VALUE; } } else { SetLastError(ERROR_FILE_NOT_FOUND); } } else { SetLastError(ERROR_BAD_ARGUMENTS); } return result; } #endif #endif /* EXCLUDE_COMMON */ /* ISO C requires a translation unit to contain at least one declaration */ typedef int cs_dirent_dummy; #ifdef MG_MODULE_LINES #line 1 "common/cs_time.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Amalgamated: #include "common/cs_time.h" */ #ifndef _WIN32 #include <stddef.h> /* * There is no sys/time.h on ARMCC. */ #if !(defined(__ARMCC_VERSION) || defined(__ICCARM__)) && \ !defined(__TI_COMPILER_VERSION__) && \ (!defined(CS_PLATFORM) || CS_PLATFORM != CS_P_NXP_LPC) #include <sys/time.h> #endif #else #include <windows.h> #endif double cs_time(void) WEAK; double cs_time(void) { double now; #ifndef _WIN32 struct timeval tv; if (gettimeofday(&tv, NULL /* tz */) != 0) return 0; now = (double) tv.tv_sec + (((double) tv.tv_usec) / 1000000.0); #else SYSTEMTIME sysnow; FILETIME ftime; GetLocalTime(&sysnow); SystemTimeToFileTime(&sysnow, &ftime); /* * 1. VC 6.0 doesn't support conversion uint64 -> double, so, using int64 * This should not cause a problems in this (21th) century * 2. Windows FILETIME is a number of 100-nanosecond intervals since January * 1, 1601 while time_t is a number of _seconds_ since January 1, 1970 UTC, * thus, we need to convert to seconds and adjust amount (subtract 11644473600 * seconds) */ now = (double) (((int64_t) ftime.dwLowDateTime + ((int64_t) ftime.dwHighDateTime << 32)) / 10000000.0) - 11644473600; #endif /* _WIN32 */ return now; } double cs_timegm(const struct tm *tm) { /* Month-to-day offset for non-leap-years. */ static const int month_day[12] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334}; /* Most of the calculation is easy; leap years are the main difficulty. */ int month = tm->tm_mon % 12; int year = tm->tm_year + tm->tm_mon / 12; int year_for_leap; int64_t rt; if (month < 0) { /* Negative values % 12 are still negative. */ month += 12; --year; } /* This is the number of Februaries since 1900. */ year_for_leap = (month > 1) ? year + 1 : year; rt = tm->tm_sec /* Seconds */ + 60 * (tm->tm_min /* Minute = 60 seconds */ + 60 * (tm->tm_hour /* Hour = 60 minutes */ + 24 * (month_day[month] + tm->tm_mday - 1 /* Day = 24 hours */ + 365 * (year - 70) /* Year = 365 days */ + (year_for_leap - 69) / 4 /* Every 4 years is leap... */ - (year_for_leap - 1) / 100 /* Except centuries... */ + (year_for_leap + 299) / 400))); /* Except 400s. */ return rt < 0 ? -1 : (double) rt; } #ifdef MG_MODULE_LINES #line 1 "common/cs_endian.h" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CS_COMMON_CS_ENDIAN_H_ #define CS_COMMON_CS_ENDIAN_H_ #ifdef __cplusplus extern "C" { #endif /* * clang with std=-c99 uses __LITTLE_ENDIAN, by default * while for ex, RTOS gcc - LITTLE_ENDIAN, by default * it depends on __USE_BSD, but let's have everything */ #if !defined(BYTE_ORDER) && defined(__BYTE_ORDER) #define BYTE_ORDER __BYTE_ORDER #ifndef LITTLE_ENDIAN #define LITTLE_ENDIAN __LITTLE_ENDIAN #endif /* LITTLE_ENDIAN */ #ifndef BIG_ENDIAN #define BIG_ENDIAN __LITTLE_ENDIAN #endif /* BIG_ENDIAN */ #endif /* BYTE_ORDER */ #ifdef __cplusplus } #endif #endif /* CS_COMMON_CS_ENDIAN_H_ */ #ifdef MG_MODULE_LINES #line 1 "common/cs_md5.c" #endif /* * This code implements the MD5 message-digest algorithm. * The algorithm is due to Ron Rivest. This code was * written by Colin Plumb in 1993, no copyright is claimed. * This code is in the public domain; do with it what you wish. * * Equivalent code is available from RSA Data Security, Inc. * This code has been tested against that, and is equivalent, * except that you don't need to include two pages of legalese * with every copy. * * To compute the message digest of a chunk of bytes, declare an * MD5Context structure, pass it to MD5Init, call MD5Update as * needed on buffers full of bytes, and then call MD5Final, which * will fill a supplied 16-byte array with the digest. */ /* Amalgamated: #include "common/cs_md5.h" */ /* Amalgamated: #include "common/str_util.h" */ #if !defined(EXCLUDE_COMMON) #if !CS_DISABLE_MD5 /* Amalgamated: #include "common/cs_endian.h" */ static void byteReverse(unsigned char *buf, unsigned longs) { /* Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN */ #if BYTE_ORDER == BIG_ENDIAN do { uint32_t t = (uint32_t)((unsigned) buf[3] << 8 | buf[2]) << 16 | ((unsigned) buf[1] << 8 | buf[0]); *(uint32_t *) buf = t; buf += 4; } while (--longs); #else (void) buf; (void) longs; #endif } #define F1(x, y, z) (z ^ (x & (y ^ z))) #define F2(x, y, z) F1(z, x, y) #define F3(x, y, z) (x ^ y ^ z) #define F4(x, y, z) (y ^ (x | ~z)) #define MD5STEP(f, w, x, y, z, data, s) \ (w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x) /* * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious * initialization constants. */ void cs_md5_init(cs_md5_ctx *ctx) { ctx->buf[0] = 0x67452301; ctx->buf[1] = 0xefcdab89; ctx->buf[2] = 0x98badcfe; ctx->buf[3] = 0x10325476; ctx->bits[0] = 0; ctx->bits[1] = 0; } static void cs_md5_transform(uint32_t buf[4], uint32_t const in[16]) { register uint32_t a, b, c, d; a = buf[0]; b = buf[1]; c = buf[2]; d = buf[3]; MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); buf[0] += a; buf[1] += b; buf[2] += c; buf[3] += d; } void cs_md5_update(cs_md5_ctx *ctx, const unsigned char *buf, size_t len) { uint32_t t; t = ctx->bits[0]; if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) ctx->bits[1]++; ctx->bits[1] += (uint32_t) len >> 29; t = (t >> 3) & 0x3f; if (t) { unsigned char *p = (unsigned char *) ctx->in + t; t = 64 - t; if (len < t) { memcpy(p, buf, len); return; } memcpy(p, buf, t); byteReverse(ctx->in, 16); cs_md5_transform(ctx->buf, (uint32_t *) ctx->in); buf += t; len -= t; } while (len >= 64) { memcpy(ctx->in, buf, 64); byteReverse(ctx->in, 16); cs_md5_transform(ctx->buf, (uint32_t *) ctx->in); buf += 64; len -= 64; } memcpy(ctx->in, buf, len); } void cs_md5_final(unsigned char digest[16], cs_md5_ctx *ctx) { unsigned count; unsigned char *p; uint32_t *a; count = (ctx->bits[0] >> 3) & 0x3F; p = ctx->in + count; *p++ = 0x80; count = 64 - 1 - count; if (count < 8) { memset(p, 0, count); byteReverse(ctx->in, 16); cs_md5_transform(ctx->buf, (uint32_t *) ctx->in); memset(ctx->in, 0, 56); } else { memset(p, 0, count - 8); } byteReverse(ctx->in, 14); a = (uint32_t *) ctx->in; a[14] = ctx->bits[0]; a[15] = ctx->bits[1]; cs_md5_transform(ctx->buf, (uint32_t *) ctx->in); byteReverse((unsigned char *) ctx->buf, 4); memcpy(digest, ctx->buf, 16); memset((char *) ctx, 0, sizeof(*ctx)); } #endif /* CS_DISABLE_MD5 */ #endif /* EXCLUDE_COMMON */ #ifdef MG_MODULE_LINES #line 1 "common/cs_sha1.c" #endif /* Copyright(c) By Steve Reid <steve@edmweb.com> */ /* 100% Public Domain */ /* Amalgamated: #include "common/cs_sha1.h" */ #if !CS_DISABLE_SHA1 && !defined(EXCLUDE_COMMON) /* Amalgamated: #include "common/cs_endian.h" */ #define SHA1HANDSOFF #if defined(__sun) /* Amalgamated: #include "common/solarisfixes.h" */ #endif union char64long16 { unsigned char c[64]; uint32_t l[16]; }; #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) static uint32_t blk0(union char64long16 *block, int i) { /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */ #if BYTE_ORDER == LITTLE_ENDIAN block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) | (rol(block->l[i], 8) & 0x00FF00FF); #endif return block->l[i]; } /* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */ #undef blk #undef R0 #undef R1 #undef R2 #undef R3 #undef R4 #define blk(i) \ (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \ block->l[(i + 2) & 15] ^ block->l[i & 15], \ 1)) #define R0(v, w, x, y, z, i) \ z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \ w = rol(w, 30); #define R1(v, w, x, y, z, i) \ z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \ w = rol(w, 30); #define R2(v, w, x, y, z, i) \ z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \ w = rol(w, 30); #define R3(v, w, x, y, z, i) \ z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \ w = rol(w, 30); #define R4(v, w, x, y, z, i) \ z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \ w = rol(w, 30); void cs_sha1_transform(uint32_t state[5], const unsigned char buffer[64]) { uint32_t a, b, c, d, e; union char64long16 block[1]; memcpy(block, buffer, 64); a = state[0]; b = state[1]; c = state[2]; d = state[3]; e = state[4]; R0(a, b, c, d, e, 0); R0(e, a, b, c, d, 1); R0(d, e, a, b, c, 2); R0(c, d, e, a, b, 3); R0(b, c, d, e, a, 4); R0(a, b, c, d, e, 5); R0(e, a, b, c, d, 6); R0(d, e, a, b, c, 7); R0(c, d, e, a, b, 8); R0(b, c, d, e, a, 9); R0(a, b, c, d, e, 10); R0(e, a, b, c, d, 11); R0(d, e, a, b, c, 12); R0(c, d, e, a, b, 13); R0(b, c, d, e, a, 14); R0(a, b, c, d, e, 15); R1(e, a, b, c, d, 16); R1(d, e, a, b, c, 17); R1(c, d, e, a, b, 18); R1(b, c, d, e, a, 19); R2(a, b, c, d, e, 20); R2(e, a, b, c, d, 21); R2(d, e, a, b, c, 22); R2(c, d, e, a, b, 23); R2(b, c, d, e, a, 24); R2(a, b, c, d, e, 25); R2(e, a, b, c, d, 26); R2(d, e, a, b, c, 27); R2(c, d, e, a, b, 28); R2(b, c, d, e, a, 29); R2(a, b, c, d, e, 30); R2(e, a, b, c, d, 31); R2(d, e, a, b, c, 32); R2(c, d, e, a, b, 33); R2(b, c, d, e, a, 34); R2(a, b, c, d, e, 35); R2(e, a, b, c, d, 36); R2(d, e, a, b, c, 37); R2(c, d, e, a, b, 38); R2(b, c, d, e, a, 39); R3(a, b, c, d, e, 40); R3(e, a, b, c, d, 41); R3(d, e, a, b, c, 42); R3(c, d, e, a, b, 43); R3(b, c, d, e, a, 44); R3(a, b, c, d, e, 45); R3(e, a, b, c, d, 46); R3(d, e, a, b, c, 47); R3(c, d, e, a, b, 48); R3(b, c, d, e, a, 49); R3(a, b, c, d, e, 50); R3(e, a, b, c, d, 51); R3(d, e, a, b, c, 52); R3(c, d, e, a, b, 53); R3(b, c, d, e, a, 54); R3(a, b, c, d, e, 55); R3(e, a, b, c, d, 56); R3(d, e, a, b, c, 57); R3(c, d, e, a, b, 58); R3(b, c, d, e, a, 59); R4(a, b, c, d, e, 60); R4(e, a, b, c, d, 61); R4(d, e, a, b, c, 62); R4(c, d, e, a, b, 63); R4(b, c, d, e, a, 64); R4(a, b, c, d, e, 65); R4(e, a, b, c, d, 66); R4(d, e, a, b, c, 67); R4(c, d, e, a, b, 68); R4(b, c, d, e, a, 69); R4(a, b, c, d, e, 70); R4(e, a, b, c, d, 71); R4(d, e, a, b, c, 72); R4(c, d, e, a, b, 73); R4(b, c, d, e, a, 74); R4(a, b, c, d, e, 75); R4(e, a, b, c, d, 76); R4(d, e, a, b, c, 77); R4(c, d, e, a, b, 78); R4(b, c, d, e, a, 79); state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; /* Erase working structures. The order of operations is important, * used to ensure that compiler doesn't optimize those out. */ memset(block, 0, sizeof(block)); a = b = c = d = e = 0; (void) a; (void) b; (void) c; (void) d; (void) e; } void cs_sha1_init(cs_sha1_ctx *context) { context->state[0] = 0x67452301; context->state[1] = 0xEFCDAB89; context->state[2] = 0x98BADCFE; context->state[3] = 0x10325476; context->state[4] = 0xC3D2E1F0; context->count[0] = context->count[1] = 0; } void cs_sha1_update(cs_sha1_ctx *context, const unsigned char *data, uint32_t len) { uint32_t i, j; j = context->count[0]; if ((context->count[0] += len << 3) < j) context->count[1]++; context->count[1] += (len >> 29); j = (j >> 3) & 63; if ((j + len) > 63) { memcpy(&context->buffer[j], data, (i = 64 - j)); cs_sha1_transform(context->state, context->buffer); for (; i + 63 < len; i += 64) { cs_sha1_transform(context->state, &data[i]); } j = 0; } else i = 0; memcpy(&context->buffer[j], &data[i], len - i); } void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *context) { unsigned i; unsigned char finalcount[8], c; for (i = 0; i < 8; i++) { finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >> ((3 - (i & 3)) * 8)) & 255); } c = 0200; cs_sha1_update(context, &c, 1); while ((context->count[0] & 504) != 448) { c = 0000; cs_sha1_update(context, &c, 1); } cs_sha1_update(context, finalcount, 8); for (i = 0; i < 20; i++) { digest[i] = (unsigned char) ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255); } memset(context, '\0', sizeof(*context)); memset(&finalcount, '\0', sizeof(finalcount)); } void cs_hmac_sha1(const unsigned char *key, size_t keylen, const unsigned char *data, size_t datalen, unsigned char out[20]) { cs_sha1_ctx ctx; unsigned char buf1[64], buf2[64], tmp_key[20], i; if (keylen > sizeof(buf1)) { cs_sha1_init(&ctx); cs_sha1_update(&ctx, key, keylen); cs_sha1_final(tmp_key, &ctx); key = tmp_key; keylen = sizeof(tmp_key); } memset(buf1, 0, sizeof(buf1)); memset(buf2, 0, sizeof(buf2)); memcpy(buf1, key, keylen); memcpy(buf2, key, keylen); for (i = 0; i < sizeof(buf1); i++) { buf1[i] ^= 0x36; buf2[i] ^= 0x5c; } cs_sha1_init(&ctx); cs_sha1_update(&ctx, buf1, sizeof(buf1)); cs_sha1_update(&ctx, data, datalen); cs_sha1_final(out, &ctx); cs_sha1_init(&ctx); cs_sha1_update(&ctx, buf2, sizeof(buf2)); cs_sha1_update(&ctx, out, 20); cs_sha1_final(out, &ctx); } #endif /* EXCLUDE_COMMON */ #ifdef MG_MODULE_LINES #line 1 "common/mbuf.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef EXCLUDE_COMMON #include <assert.h> #include <string.h> /* Amalgamated: #include "common/mbuf.h" */ #ifndef MBUF_REALLOC #define MBUF_REALLOC realloc #endif #ifndef MBUF_FREE #define MBUF_FREE free #endif void mbuf_init(struct mbuf *mbuf, size_t initial_size) WEAK; void mbuf_init(struct mbuf *mbuf, size_t initial_size) { mbuf->len = mbuf->size = 0; mbuf->buf = NULL; mbuf_resize(mbuf, initial_size); } void mbuf_free(struct mbuf *mbuf) WEAK; void mbuf_free(struct mbuf *mbuf) { if (mbuf->buf != NULL) { MBUF_FREE(mbuf->buf); mbuf_init(mbuf, 0); } } void mbuf_resize(struct mbuf *a, size_t new_size) WEAK; void mbuf_resize(struct mbuf *a, size_t new_size) { if (new_size > a->size || (new_size < a->size && new_size >= a->len)) { char *buf = (char *) MBUF_REALLOC(a->buf, new_size); /* * In case realloc fails, there's not much we can do, except keep things as * they are. Note that NULL is a valid return value from realloc when * size == 0, but that is covered too. */ if (buf == NULL && new_size != 0) return; a->buf = buf; a->size = new_size; } } void mbuf_trim(struct mbuf *mbuf) WEAK; void mbuf_trim(struct mbuf *mbuf) { mbuf_resize(mbuf, mbuf->len); } size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t) WEAK; size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t len) { char *p = NULL; assert(a != NULL); assert(a->len <= a->size); assert(off <= a->len); /* check overflow */ if (~(size_t) 0 - (size_t) a->buf < len) return 0; if (a->len + len <= a->size) { memmove(a->buf + off + len, a->buf + off, a->len - off); if (buf != NULL) { memcpy(a->buf + off, buf, len); } a->len += len; } else { size_t min_size = (a->len + len); size_t new_size = (size_t)(min_size * MBUF_SIZE_MULTIPLIER); if (new_size - min_size > MBUF_SIZE_MAX_HEADROOM) { new_size = min_size + MBUF_SIZE_MAX_HEADROOM; } p = (char *) MBUF_REALLOC(a->buf, new_size); if (p == NULL && new_size != min_size) { new_size = min_size; p = (char *) MBUF_REALLOC(a->buf, new_size); } if (p != NULL) { a->buf = p; if (off != a->len) { memmove(a->buf + off + len, a->buf + off, a->len - off); } if (buf != NULL) memcpy(a->buf + off, buf, len); a->len += len; a->size = new_size; } else { len = 0; } } return len; } size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) WEAK; size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) { return mbuf_insert(a, a->len, buf, len); } size_t mbuf_append_and_free(struct mbuf *a, void *buf, size_t len) WEAK; size_t mbuf_append_and_free(struct mbuf *a, void *data, size_t len) { size_t ret; /* Optimization: if the buffer is currently empty, * take over the user-provided buffer. */ if (a->len == 0) { if (a->buf != NULL) free(a->buf); a->buf = (char *) data; a->len = a->size = len; return len; } ret = mbuf_insert(a, a->len, data, len); free(data); return ret; } void mbuf_remove(struct mbuf *mb, size_t n) WEAK; void mbuf_remove(struct mbuf *mb, size_t n) { if (n > 0 && n <= mb->len) { memmove(mb->buf, mb->buf + n, mb->len - n); mb->len -= n; } } void mbuf_clear(struct mbuf *mb) WEAK; void mbuf_clear(struct mbuf *mb) { mb->len = 0; } void mbuf_move(struct mbuf *from, struct mbuf *to) WEAK; void mbuf_move(struct mbuf *from, struct mbuf *to) { memcpy(to, from, sizeof(*to)); memset(from, 0, sizeof(*from)); } #endif /* EXCLUDE_COMMON */ #ifdef MG_MODULE_LINES #line 1 "common/mg_str.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Amalgamated: #include "common/mg_mem.h" */ /* Amalgamated: #include "common/mg_str.h" */ /* Amalgamated: #include "common/platform.h" */ #include <ctype.h> #include <stdlib.h> #include <string.h> int mg_ncasecmp(const char *s1, const char *s2, size_t len) WEAK; struct mg_str mg_mk_str(const char *s) WEAK; struct mg_str mg_mk_str(const char *s) { struct mg_str ret = {s, 0}; if (s != NULL) ret.len = strlen(s); return ret; } struct mg_str mg_mk_str_n(const char *s, size_t len) WEAK; struct mg_str mg_mk_str_n(const char *s, size_t len) { struct mg_str ret = {s, len}; return ret; } int mg_vcmp(const struct mg_str *str1, const char *str2) WEAK; int mg_vcmp(const struct mg_str *str1, const char *str2) { size_t n2 = strlen(str2), n1 = str1->len; int r = strncmp(str1->p, str2, (n1 < n2) ? n1 : n2); if (r == 0) { return n1 - n2; } return r; } int mg_vcasecmp(const struct mg_str *str1, const char *str2) WEAK; int mg_vcasecmp(const struct mg_str *str1, const char *str2) { size_t n2 = strlen(str2), n1 = str1->len; int r = mg_ncasecmp(str1->p, str2, (n1 < n2) ? n1 : n2); if (r == 0) { return n1 - n2; } return r; } static struct mg_str mg_strdup_common(const struct mg_str s, int nul_terminate) { struct mg_str r = {NULL, 0}; if (s.len > 0 && s.p != NULL) { char *sc = (char *) MG_MALLOC(s.len + (nul_terminate ? 1 : 0)); if (sc != NULL) { memcpy(sc, s.p, s.len); if (nul_terminate) sc[s.len] = '\0'; r.p = sc; r.len = s.len; } } return r; } struct mg_str mg_strdup(const struct mg_str s) WEAK; struct mg_str mg_strdup(const struct mg_str s) { return mg_strdup_common(s, 0 /* NUL-terminate */); } struct mg_str mg_strdup_nul(const struct mg_str s) WEAK; struct mg_str mg_strdup_nul(const struct mg_str s) { return mg_strdup_common(s, 1 /* NUL-terminate */); } const char *mg_strchr(const struct mg_str s, int c) WEAK; const char *mg_strchr(const struct mg_str s, int c) { size_t i; for (i = 0; i < s.len; i++) { if (s.p[i] == c) return &s.p[i]; } return NULL; } int mg_strcmp(const struct mg_str str1, const struct mg_str str2) WEAK; int mg_strcmp(const struct mg_str str1, const struct mg_str str2) { size_t i = 0; while (i < str1.len && i < str2.len) { if (str1.p[i] < str2.p[i]) return -1; if (str1.p[i] > str2.p[i]) return 1; i++; } if (i < str1.len) return 1; if (i < str2.len) return -1; return 0; } int mg_strncmp(const struct mg_str, const struct mg_str, size_t n) WEAK; int mg_strncmp(const struct mg_str str1, const struct mg_str str2, size_t n) { struct mg_str s1 = str1; struct mg_str s2 = str2; if (s1.len > n) { s1.len = n; } if (s2.len > n) { s2.len = n; } return mg_strcmp(s1, s2); } void mg_strfree(struct mg_str *s) WEAK; void mg_strfree(struct mg_str *s) { char *sp = (char *) s->p; s->p = NULL; s->len = 0; if (sp != NULL) free(sp); } const char *mg_strstr(const struct mg_str haystack, const struct mg_str needle) WEAK; const char *mg_strstr(const struct mg_str haystack, const struct mg_str needle) { size_t i; if (needle.len > haystack.len) return NULL; for (i = 0; i <= haystack.len - needle.len; i++) { if (memcmp(haystack.p + i, needle.p, needle.len) == 0) { return haystack.p + i; } } return NULL; } struct mg_str mg_strstrip(struct mg_str s) WEAK; struct mg_str mg_strstrip(struct mg_str s) { while (s.len > 0 && isspace((int) *s.p)) { s.p++; s.len--; } while (s.len > 0 && isspace((int) *(s.p + s.len - 1))) { s.len--; } return s; } int mg_str_starts_with(struct mg_str s, struct mg_str prefix) WEAK; int mg_str_starts_with(struct mg_str s, struct mg_str prefix) { const struct mg_str sp = MG_MK_STR_N(s.p, prefix.len); if (s.len < prefix.len) return 0; return (mg_strcmp(sp, prefix) == 0); } #ifdef MG_MODULE_LINES #line 1 "common/str_util.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef EXCLUDE_COMMON /* Amalgamated: #include "common/str_util.h" */ /* Amalgamated: #include "common/mg_mem.h" */ /* Amalgamated: #include "common/platform.h" */ #ifndef C_DISABLE_BUILTIN_SNPRINTF #define C_DISABLE_BUILTIN_SNPRINTF 0 #endif /* Amalgamated: #include "common/mg_mem.h" */ size_t c_strnlen(const char *s, size_t maxlen) WEAK; size_t c_strnlen(const char *s, size_t maxlen) { size_t l = 0; for (; l < maxlen && s[l] != '\0'; l++) { } return l; } #define C_SNPRINTF_APPEND_CHAR(ch) \ do { \ if (i < (int) buf_size) buf[i] = ch; \ i++; \ } while (0) #define C_SNPRINTF_FLAG_ZERO 1 #if C_DISABLE_BUILTIN_SNPRINTF int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) WEAK; int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) { return vsnprintf(buf, buf_size, fmt, ap); } #else static int c_itoa(char *buf, size_t buf_size, int64_t num, int base, int flags, int field_width) { char tmp[40]; int i = 0, k = 0, neg = 0; if (num < 0) { neg++; num = -num; } /* Print into temporary buffer - in reverse order */ do { int rem = num % base; if (rem < 10) { tmp[k++] = '0' + rem; } else { tmp[k++] = 'a' + (rem - 10); } num /= base; } while (num > 0); /* Zero padding */ if (flags && C_SNPRINTF_FLAG_ZERO) { while (k < field_width && k < (int) sizeof(tmp) - 1) { tmp[k++] = '0'; } } /* And sign */ if (neg) { tmp[k++] = '-'; } /* Now output */ while (--k >= 0) { C_SNPRINTF_APPEND_CHAR(tmp[k]); } return i; } int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) WEAK; int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) { int ch, i = 0, len_mod, flags, precision, field_width; while ((ch = *fmt++) != '\0') { if (ch != '%') { C_SNPRINTF_APPEND_CHAR(ch); } else { /* * Conversion specification: * zero or more flags (one of: # 0 - <space> + ') * an optional minimum field width (digits) * an optional precision (. followed by digits, or *) * an optional length modifier (one of: hh h l ll L q j z t) * conversion specifier (one of: d i o u x X e E f F g G a A c s p n) */ flags = field_width = precision = len_mod = 0; /* Flags. only zero-pad flag is supported. */ if (*fmt == '0') { flags |= C_SNPRINTF_FLAG_ZERO; } /* Field width */ while (*fmt >= '0' && *fmt <= '9') { field_width *= 10; field_width += *fmt++ - '0'; } /* Dynamic field width */ if (*fmt == '*') { field_width = va_arg(ap, int); fmt++; } /* Precision */ if (*fmt == '.') { fmt++; if (*fmt == '*') { precision = va_arg(ap, int); fmt++; } else { while (*fmt >= '0' && *fmt <= '9') { precision *= 10; precision += *fmt++ - '0'; } } } /* Length modifier */ switch (*fmt) { case 'h': case 'l': case 'L': case 'I': case 'q': case 'j': case 'z': case 't': len_mod = *fmt++; if (*fmt == 'h') { len_mod = 'H'; fmt++; } if (*fmt == 'l') { len_mod = 'q'; fmt++; } break; } ch = *fmt++; if (ch == 's') { const char *s = va_arg(ap, const char *); /* Always fetch parameter */ int j; int pad = field_width - (precision >= 0 ? c_strnlen(s, precision) : 0); for (j = 0; j < pad; j++) { C_SNPRINTF_APPEND_CHAR(' '); } /* `s` may be NULL in case of %.*s */ if (s != NULL) { /* Ignore negative and 0 precisions */ for (j = 0; (precision <= 0 || j < precision) && s[j] != '\0'; j++) { C_SNPRINTF_APPEND_CHAR(s[j]); } } } else if (ch == 'c') { ch = va_arg(ap, int); /* Always fetch parameter */ C_SNPRINTF_APPEND_CHAR(ch); } else if (ch == 'd' && len_mod == 0) { i += c_itoa(buf + i, buf_size - i, va_arg(ap, int), 10, flags, field_width); } else if (ch == 'd' && len_mod == 'l') { i += c_itoa(buf + i, buf_size - i, va_arg(ap, long), 10, flags, field_width); #ifdef SSIZE_MAX } else if (ch == 'd' && len_mod == 'z') { i += c_itoa(buf + i, buf_size - i, va_arg(ap, ssize_t), 10, flags, field_width); #endif } else if (ch == 'd' && len_mod == 'q') { i += c_itoa(buf + i, buf_size - i, va_arg(ap, int64_t), 10, flags, field_width); } else if ((ch == 'x' || ch == 'u') && len_mod == 0) { i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned), ch == 'x' ? 16 : 10, flags, field_width); } else if ((ch == 'x' || ch == 'u') && len_mod == 'l') { i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned long), ch == 'x' ? 16 : 10, flags, field_width); } else if ((ch == 'x' || ch == 'u') && len_mod == 'z') { i += c_itoa(buf + i, buf_size - i, va_arg(ap, size_t), ch == 'x' ? 16 : 10, flags, field_width); } else if (ch == 'p') { unsigned long num = (unsigned long) (uintptr_t) va_arg(ap, void *); C_SNPRINTF_APPEND_CHAR('0'); C_SNPRINTF_APPEND_CHAR('x'); i += c_itoa(buf + i, buf_size - i, num, 16, flags, 0); } else { #ifndef NO_LIBC /* * TODO(lsm): abort is not nice in a library, remove it * Also, ESP8266 SDK doesn't have it */ abort(); #endif } } } /* Zero-terminate the result */ if (buf_size > 0) { buf[i < (int) buf_size ? i : (int) buf_size - 1] = '\0'; } return i; } #endif int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) WEAK; int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) { int result; va_list ap; va_start(ap, fmt); result = c_vsnprintf(buf, buf_size, fmt, ap); va_end(ap); return result; } #ifdef _WIN32 int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) { int ret; char buf[MAX_PATH * 2], buf2[MAX_PATH * 2], *p; strncpy(buf, path, sizeof(buf)); buf[sizeof(buf) - 1] = '\0'; /* Trim trailing slashes. Leave backslash for paths like "X:\" */ p = buf + strlen(buf) - 1; while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0'; memset(wbuf, 0, wbuf_len * sizeof(wchar_t)); ret = MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len); /* * Convert back to Unicode. If doubly-converted string does not match the * original, something is fishy, reject. */ WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2), NULL, NULL); if (strcmp(buf, buf2) != 0) { wbuf[0] = L'\0'; ret = 0; } return ret; } #endif /* _WIN32 */ /* The simplest O(mn) algorithm. Better implementation are GPLed */ const char *c_strnstr(const char *s, const char *find, size_t slen) WEAK; const char *c_strnstr(const char *s, const char *find, size_t slen) { size_t find_length = strlen(find); size_t i; for (i = 0; i < slen; i++) { if (i + find_length > slen) { return NULL; } if (strncmp(&s[i], find, find_length) == 0) { return &s[i]; } } return NULL; } #if CS_ENABLE_STRDUP char *strdup(const char *src) WEAK; char *strdup(const char *src) { size_t len = strlen(src) + 1; char *ret = MG_MALLOC(len); if (ret != NULL) { strcpy(ret, src); } return ret; } #endif void cs_to_hex(char *to, const unsigned char *p, size_t len) WEAK; void cs_to_hex(char *to, const unsigned char *p, size_t len) { static const char *hex = "0123456789abcdef"; for (; len--; p++) { *to++ = hex[p[0] >> 4]; *to++ = hex[p[0] & 0x0f]; } *to = '\0'; } static int fourbit(int ch) { if (ch >= '0' && ch <= '9') { return ch - '0'; } else if (ch >= 'a' && ch <= 'f') { return ch - 'a' + 10; } else if (ch >= 'A' && ch <= 'F') { return ch - 'A' + 10; } return 0; } void cs_from_hex(char *to, const char *p, size_t len) WEAK; void cs_from_hex(char *to, const char *p, size_t len) { size_t i; for (i = 0; i < len; i += 2) { *to++ = (fourbit(p[i]) << 4) + fourbit(p[i + 1]); } *to = '\0'; } #if CS_ENABLE_TO64 int64_t cs_to64(const char *s) WEAK; int64_t cs_to64(const char *s) { int64_t result = 0; int64_t neg = 1; while (*s && isspace((unsigned char) *s)) s++; if (*s == '-') { neg = -1; s++; } while (isdigit((unsigned char) *s)) { result *= 10; result += (*s - '0'); s++; } return result * neg; } #endif static int str_util_lowercase(const char *s) { return tolower(*(const unsigned char *) s); } int mg_ncasecmp(const char *s1, const char *s2, size_t len) WEAK; int mg_ncasecmp(const char *s1, const char *s2, size_t len) { int diff = 0; if (len > 0) do { diff = str_util_lowercase(s1++) - str_util_lowercase(s2++); } while (diff == 0 && s1[-1] != '\0' && --len > 0); return diff; } int mg_casecmp(const char *s1, const char *s2) WEAK; int mg_casecmp(const char *s1, const char *s2) { return mg_ncasecmp(s1, s2, (size_t) ~0); } int mg_asprintf(char **buf, size_t size, const char *fmt, ...) WEAK; int mg_asprintf(char **buf, size_t size, const char *fmt, ...) { int ret; va_list ap; va_start(ap, fmt); ret = mg_avprintf(buf, size, fmt, ap); va_end(ap); return ret; } int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) WEAK; int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) { va_list ap_copy; int len; va_copy(ap_copy, ap); len = vsnprintf(*buf, size, fmt, ap_copy); va_end(ap_copy); if (len < 0) { /* eCos and Windows are not standard-compliant and return -1 when * the buffer is too small. Keep allocating larger buffers until we * succeed or out of memory. */ *buf = NULL; /* LCOV_EXCL_START */ while (len < 0) { MG_FREE(*buf); if (size == 0) { size = 5; } size *= 2; if ((*buf = (char *) MG_MALLOC(size)) == NULL) { len = -1; break; } va_copy(ap_copy, ap); len = vsnprintf(*buf, size - 1, fmt, ap_copy); va_end(ap_copy); } /* * Microsoft version of vsnprintf() is not always null-terminated, so put * the terminator manually */ (*buf)[len] = 0; /* LCOV_EXCL_STOP */ } else if (len >= (int) size) { /* Standard-compliant code path. Allocate a buffer that is large enough. */ if ((*buf = (char *) MG_MALLOC(len + 1)) == NULL) { len = -1; /* LCOV_EXCL_LINE */ } else { /* LCOV_EXCL_LINE */ va_copy(ap_copy, ap); len = vsnprintf(*buf, len + 1, fmt, ap_copy); va_end(ap_copy); } } return len; } const char *mg_next_comma_list_entry(const char *, struct mg_str *, struct mg_str *) WEAK; const char *mg_next_comma_list_entry(const char *list, struct mg_str *val, struct mg_str *eq_val) { struct mg_str ret = mg_next_comma_list_entry_n(mg_mk_str(list), val, eq_val); return ret.p; } struct mg_str mg_next_comma_list_entry_n(struct mg_str list, struct mg_str *val, struct mg_str *eq_val) WEAK; struct mg_str mg_next_comma_list_entry_n(struct mg_str list, struct mg_str *val, struct mg_str *eq_val) { if (list.len == 0) { /* End of the list */ list = mg_mk_str(NULL); } else { const char *chr = NULL; *val = list; if ((chr = mg_strchr(*val, ',')) != NULL) { /* Comma found. Store length and shift the list ptr */ val->len = chr - val->p; chr++; list.len -= (chr - list.p); list.p = chr; } else { /* This value is the last one */ list = mg_mk_str_n(list.p + list.len, 0); } if (eq_val != NULL) { /* Value has form "x=y", adjust pointers and lengths */ /* so that val points to "x", and eq_val points to "y". */ eq_val->len = 0; eq_val->p = (const char *) memchr(val->p, '=', val->len); if (eq_val->p != NULL) { eq_val->p++; /* Skip over '=' character */ eq_val->len = val->p + val->len - eq_val->p; val->len = (eq_val->p - val->p) - 1; } } } return list; } size_t mg_match_prefix_n(const struct mg_str, const struct mg_str) WEAK; size_t mg_match_prefix_n(const struct mg_str pattern, const struct mg_str str) { const char *or_str; size_t res = 0, len = 0, i = 0, j = 0; if ((or_str = (const char *) memchr(pattern.p, '|', pattern.len)) != NULL || (or_str = (const char *) memchr(pattern.p, ',', pattern.len)) != NULL) { struct mg_str pstr = {pattern.p, (size_t)(or_str - pattern.p)}; res = mg_match_prefix_n(pstr, str); if (res > 0) return res; pstr.p = or_str + 1; pstr.len = (pattern.p + pattern.len) - (or_str + 1); return mg_match_prefix_n(pstr, str); } for (; i < pattern.len && j < str.len; i++, j++) { if (pattern.p[i] == '?') { continue; } else if (pattern.p[i] == '*') { i++; if (i < pattern.len && pattern.p[i] == '*') { i++; len = str.len - j; } else { len = 0; while (j + len < str.len && str.p[j + len] != '/') len++; } if (i == pattern.len || (pattern.p[i] == '$' && i == pattern.len - 1)) return j + len; do { const struct mg_str pstr = {pattern.p + i, pattern.len - i}; const struct mg_str sstr = {str.p + j + len, str.len - j - len}; res = mg_match_prefix_n(pstr, sstr); } while (res == 0 && len != 0 && len-- > 0); return res == 0 ? 0 : j + res + len; } else if (str_util_lowercase(&pattern.p[i]) != str_util_lowercase(&str.p[j])) { break; } } if (i < pattern.len && pattern.p[i] == '$') { return j == str.len ? str.len : 0; } return i == pattern.len ? j : 0; } size_t mg_match_prefix(const char *, int, const char *) WEAK; size_t mg_match_prefix(const char *pattern, int pattern_len, const char *str) { const struct mg_str pstr = {pattern, (size_t) pattern_len}; struct mg_str s = {str, 0}; if (str != NULL) s.len = strlen(str); return mg_match_prefix_n(pstr, s); } #endif /* EXCLUDE_COMMON */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_net.c" #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved * * This software is dual-licensed: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. For the terms of this * license, see <http://www.gnu.org/licenses/>. * * You are free to use this software under the terms of the GNU General * Public License, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * Alternatively, you can license this software under a commercial * license, as set out in <https://www.cesanta.com/license>. */ /* Amalgamated: #include "common/cs_time.h" */ /* Amalgamated: #include "mg_dns.h" */ /* Amalgamated: #include "mg_internal.h" */ /* Amalgamated: #include "mg_resolv.h" */ /* Amalgamated: #include "mg_util.h" */ #define MG_MAX_HOST_LEN 200 #ifndef MG_TCP_IO_SIZE #define MG_TCP_IO_SIZE 1460 #endif #ifndef MG_UDP_IO_SIZE #define MG_UDP_IO_SIZE 1460 #endif #define MG_COPY_COMMON_CONNECTION_OPTIONS(dst, src) \ memcpy(dst, src, sizeof(*dst)); /* Which flags can be pre-set by the user at connection creation time. */ #define _MG_ALLOWED_CONNECT_FLAGS_MASK \ (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \ MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_ENABLE_BROADCAST) /* Which flags should be modifiable by user's callbacks. */ #define _MG_CALLBACK_MODIFIABLE_FLAGS_MASK \ (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \ MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_SEND_AND_CLOSE | \ MG_F_CLOSE_IMMEDIATELY | MG_F_IS_WEBSOCKET | MG_F_DELETE_CHUNK) #ifndef intptr_t #define intptr_t long #endif MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c) { DBG(("%p %p", mgr, c)); c->mgr = mgr; c->next = mgr->active_connections; mgr->active_connections = c; c->prev = NULL; if (c->next != NULL) c->next->prev = c; if (c->sock != INVALID_SOCKET) { c->iface->vtable->add_conn(c); } } MG_INTERNAL void mg_remove_conn(struct mg_connection *conn) { if (conn->prev == NULL) conn->mgr->active_connections = conn->next; if (conn->prev) conn->prev->next = conn->next; if (conn->next) conn->next->prev = conn->prev; conn->prev = conn->next = NULL; conn->iface->vtable->remove_conn(conn); } MG_INTERNAL void mg_call(struct mg_connection *nc, mg_event_handler_t ev_handler, void *user_data, int ev, void *ev_data) { if (ev_handler == NULL) { /* * If protocol handler is specified, call it. Otherwise, call user-specified * event handler. */ ev_handler = nc->proto_handler ? nc->proto_handler : nc->handler; } if (ev != MG_EV_POLL) { DBG(("%p %s ev=%d ev_data=%p flags=0x%lx rmbl=%d smbl=%d", nc, ev_handler == nc->handler ? "user" : "proto", ev, ev_data, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len)); } #if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP if (nc->mgr->hexdump_file != NULL && ev != MG_EV_POLL && ev != MG_EV_RECV && ev != MG_EV_SEND /* handled separately */) { mg_hexdump_connection(nc, nc->mgr->hexdump_file, NULL, 0, ev); } #endif if (ev_handler != NULL) { unsigned long flags_before = nc->flags; ev_handler(nc, ev, ev_data MG_UD_ARG(user_data)); /* Prevent user handler from fiddling with system flags. */ if (ev_handler == nc->handler && nc->flags != flags_before) { nc->flags = (flags_before & ~_MG_CALLBACK_MODIFIABLE_FLAGS_MASK) | (nc->flags & _MG_CALLBACK_MODIFIABLE_FLAGS_MASK); } } if (ev != MG_EV_POLL) nc->mgr->num_calls++; if (ev != MG_EV_POLL) { DBG(("%p after %s flags=0x%lx rmbl=%d smbl=%d", nc, ev_handler == nc->handler ? "user" : "proto", nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len)); } #if !MG_ENABLE_CALLBACK_USERDATA (void) user_data; #endif } MG_INTERNAL void mg_timer(struct mg_connection *c, double now) { if (c->ev_timer_time > 0 && now >= c->ev_timer_time) { double old_value = c->ev_timer_time; c->ev_timer_time = 0; mg_call(c, NULL, c->user_data, MG_EV_TIMER, &old_value); } } MG_INTERNAL size_t recv_avail_size(struct mg_connection *conn, size_t max) { size_t avail; if (conn->recv_mbuf_limit < conn->recv_mbuf.len) return 0; avail = conn->recv_mbuf_limit - conn->recv_mbuf.len; return avail > max ? max : avail; } static int mg_do_recv(struct mg_connection *nc); int mg_if_poll(struct mg_connection *nc, double now) { if (nc->flags & MG_F_CLOSE_IMMEDIATELY) { mg_close_conn(nc); return 0; } else if (nc->flags & MG_F_SEND_AND_CLOSE) { if (nc->send_mbuf.len == 0) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; mg_close_conn(nc); return 0; } } else if (nc->flags & MG_F_RECV_AND_CLOSE) { mg_close_conn(nc); return 0; } #if MG_ENABLE_SSL if ((nc->flags & (MG_F_SSL | MG_F_LISTENING | MG_F_CONNECTING)) == MG_F_SSL) { /* SSL library may have data to be delivered to the app in its buffers, * drain them. */ int recved = 0; do { if (nc->flags & (MG_F_WANT_READ | MG_F_WANT_WRITE)) break; if (recv_avail_size(nc, MG_TCP_IO_SIZE) <= 0) break; recved = mg_do_recv(nc); } while (recved > 0); } #endif /* MG_ENABLE_SSL */ mg_timer(nc, now); { time_t now_t = (time_t) now; mg_call(nc, NULL, nc->user_data, MG_EV_POLL, &now_t); } return 1; } void mg_destroy_conn(struct mg_connection *conn, int destroy_if) { if (conn->sock != INVALID_SOCKET) { /* Don't print timer-only conns */ LOG(LL_DEBUG, ("%p 0x%lx %d", conn, conn->flags, destroy_if)); } if (destroy_if) conn->iface->vtable->destroy_conn(conn); if (conn->proto_data != NULL && conn->proto_data_destructor != NULL) { conn->proto_data_destructor(conn->proto_data); } #if MG_ENABLE_SSL mg_ssl_if_conn_free(conn); #endif mbuf_free(&conn->recv_mbuf); mbuf_free(&conn->send_mbuf); memset(conn, 0, sizeof(*conn)); MG_FREE(conn); } void mg_close_conn(struct mg_connection *conn) { /* See if there's any remaining data to deliver. Skip if user completely * throttled the connection there will be no progress anyway. */ if (conn->sock != INVALID_SOCKET && mg_do_recv(conn) == -2) { /* Receive is throttled, wait. */ conn->flags |= MG_F_RECV_AND_CLOSE; return; } #if MG_ENABLE_SSL if (conn->flags & MG_F_SSL_HANDSHAKE_DONE) { mg_ssl_if_conn_close_notify(conn); } #endif /* * Clearly mark the connection as going away (if not already). * Some net_if impls (LwIP) need this for cleanly handling half-dead conns. */ conn->flags |= MG_F_CLOSE_IMMEDIATELY; mg_remove_conn(conn); conn->iface->vtable->destroy_conn(conn); mg_call(conn, NULL, conn->user_data, MG_EV_CLOSE, NULL); mg_destroy_conn(conn, 0 /* destroy_if */); } void mg_mgr_init(struct mg_mgr *m, void *user_data) { struct mg_mgr_init_opts opts; memset(&opts, 0, sizeof(opts)); mg_mgr_init_opt(m, user_data, opts); } void mg_mgr_init_opt(struct mg_mgr *m, void *user_data, struct mg_mgr_init_opts opts) { memset(m, 0, sizeof(*m)); #if MG_ENABLE_BROADCAST m->ctl[0] = m->ctl[1] = INVALID_SOCKET; #endif m->user_data = user_data; #ifdef _WIN32 { WSADATA data; WSAStartup(MAKEWORD(2, 2), &data); } #elif defined(__unix__) /* Ignore SIGPIPE signal, so if client cancels the request, it * won't kill the whole process. */ signal(SIGPIPE, SIG_IGN); #endif { int i; if (opts.num_ifaces == 0) { opts.num_ifaces = mg_num_ifaces; opts.ifaces = mg_ifaces; } if (opts.main_iface != NULL) { opts.ifaces[MG_MAIN_IFACE] = opts.main_iface; } m->num_ifaces = opts.num_ifaces; m->ifaces = (struct mg_iface **) MG_MALLOC(sizeof(*m->ifaces) * opts.num_ifaces); for (i = 0; i < opts.num_ifaces; i++) { m->ifaces[i] = mg_if_create_iface(opts.ifaces[i], m); m->ifaces[i]->vtable->init(m->ifaces[i]); } } if (opts.nameserver != NULL) { m->nameserver = strdup(opts.nameserver); } DBG(("==================================")); DBG(("init mgr=%p", m)); #if MG_ENABLE_SSL { static int init_done; if (!init_done) { mg_ssl_if_init(); init_done++; } } #endif } void mg_mgr_free(struct mg_mgr *m) { struct mg_connection *conn, *tmp_conn; DBG(("%p", m)); if (m == NULL) return; /* Do one last poll, see https://github.com/cesanta/mongoose/issues/286 */ mg_mgr_poll(m, 0); #if MG_ENABLE_BROADCAST if (m->ctl[0] != INVALID_SOCKET) closesocket(m->ctl[0]); if (m->ctl[1] != INVALID_SOCKET) closesocket(m->ctl[1]); m->ctl[0] = m->ctl[1] = INVALID_SOCKET; #endif for (conn = m->active_connections; conn != NULL; conn = tmp_conn) { tmp_conn = conn->next; conn->flags |= MG_F_CLOSE_IMMEDIATELY; mg_close_conn(conn); } { int i; for (i = 0; i < m->num_ifaces; i++) { m->ifaces[i]->vtable->free(m->ifaces[i]); MG_FREE(m->ifaces[i]); } MG_FREE(m->ifaces); } MG_FREE((char *) m->nameserver); } int mg_mgr_poll(struct mg_mgr *m, int timeout_ms) { int i, num_calls_before = m->num_calls; for (i = 0; i < m->num_ifaces; i++) { m->ifaces[i]->vtable->poll(m->ifaces[i], timeout_ms); } return (m->num_calls - num_calls_before); } int mg_vprintf(struct mg_connection *nc, const char *fmt, va_list ap) { char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem; int len; if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) { mg_send(nc, buf, len); } if (buf != mem && buf != NULL) { MG_FREE(buf); /* LCOV_EXCL_LINE */ } /* LCOV_EXCL_LINE */ return len; } int mg_printf(struct mg_connection *conn, const char *fmt, ...) { int len; va_list ap; va_start(ap, fmt); len = mg_vprintf(conn, fmt, ap); va_end(ap); return len; } #if MG_ENABLE_SYNC_RESOLVER /* TODO(lsm): use non-blocking resolver */ static int mg_resolve2(const char *host, struct in_addr *ina) { #if MG_ENABLE_GETADDRINFO int rv = 0; struct addrinfo hints, *servinfo, *p; struct sockaddr_in *h = NULL; memset(&hints, 0, sizeof hints); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; if ((rv = getaddrinfo(host, NULL, NULL, &servinfo)) != 0) { DBG(("getaddrinfo(%s) failed: %s", host, strerror(mg_get_errno()))); return 0; } for (p = servinfo; p != NULL; p = p->ai_next) { memcpy(&h, &p->ai_addr, sizeof(h)); memcpy(ina, &h->sin_addr, sizeof(*ina)); } freeaddrinfo(servinfo); return 1; #else struct hostent *he; if ((he = gethostbyname(host)) == NULL) { DBG(("gethostbyname(%s) failed: %s", host, strerror(mg_get_errno()))); } else { memcpy(ina, he->h_addr_list[0], sizeof(*ina)); return 1; } return 0; #endif /* MG_ENABLE_GETADDRINFO */ } int mg_resolve(const char *host, char *buf, size_t n) { struct in_addr ad; return mg_resolve2(host, &ad) ? snprintf(buf, n, "%s", inet_ntoa(ad)) : 0; } #endif /* MG_ENABLE_SYNC_RESOLVER */ MG_INTERNAL struct mg_connection *mg_create_connection_base( struct mg_mgr *mgr, mg_event_handler_t callback, struct mg_add_sock_opts opts) { struct mg_connection *conn; if ((conn = (struct mg_connection *) MG_CALLOC(1, sizeof(*conn))) != NULL) { conn->sock = INVALID_SOCKET; conn->handler = callback; conn->mgr = mgr; conn->last_io_time = (time_t) mg_time(); conn->iface = (opts.iface != NULL ? opts.iface : mgr->ifaces[MG_MAIN_IFACE]); conn->flags = opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK; conn->user_data = opts.user_data; /* * SIZE_MAX is defined as a long long constant in * system headers on some platforms and so it * doesn't compile with pedantic ansi flags. */ conn->recv_mbuf_limit = ~0; } else { MG_SET_PTRPTR(opts.error_string, "failed to create connection"); } return conn; } MG_INTERNAL struct mg_connection *mg_create_connection( struct mg_mgr *mgr, mg_event_handler_t callback, struct mg_add_sock_opts opts) { struct mg_connection *conn = mg_create_connection_base(mgr, callback, opts); if (conn != NULL && !conn->iface->vtable->create_conn(conn)) { MG_FREE(conn); conn = NULL; } if (conn == NULL) { MG_SET_PTRPTR(opts.error_string, "failed to init connection"); } return conn; } /* * Address format: [PROTO://][HOST]:PORT * * HOST could be IPv4/IPv6 address or a host name. * `host` is a destination buffer to hold parsed HOST part. Should be at least * MG_MAX_HOST_LEN bytes long. * `proto` is a returned socket type, either SOCK_STREAM or SOCK_DGRAM * * Return: * -1 on parse error * 0 if HOST needs DNS lookup * >0 length of the address string */ MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa, int *proto, char *host, size_t host_len) { unsigned int a, b, c, d, port = 0; int ch, len = 0; #if MG_ENABLE_IPV6 char buf[100]; #endif /* * MacOS needs that. If we do not zero it, subsequent bind() will fail. * Also, all-zeroes in the socket address means binding to all addresses * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */ memset(sa, 0, sizeof(*sa)); sa->sin.sin_family = AF_INET; *proto = SOCK_STREAM; if (strncmp(str, "udp://", 6) == 0) { str += 6; *proto = SOCK_DGRAM; } else if (strncmp(str, "tcp://", 6) == 0) { str += 6; } if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) { /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */ sa->sin.sin_addr.s_addr = htonl(((uint32_t) a << 24) | ((uint32_t) b << 16) | c << 8 | d); sa->sin.sin_port = htons((uint16_t) port); #if MG_ENABLE_IPV6 } else if (sscanf(str, "[%99[^]]]:%u%n", buf, &port, &len) == 2 && inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) { /* IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080 */ sa->sin6.sin6_family = AF_INET6; sa->sin.sin_port = htons((uint16_t) port); #endif #if MG_ENABLE_ASYNC_RESOLVER } else if (strlen(str) < host_len && sscanf(str, "%[^ :]:%u%n", host, &port, &len) == 2) { sa->sin.sin_port = htons((uint16_t) port); if (mg_resolve_from_hosts_file(host, sa) != 0) { /* * if resolving from hosts file failed and the host * we are trying to resolve is `localhost` - we should * try to resolve it using `gethostbyname` and do not try * to resolve it via DNS server if gethostbyname has failed too */ if (mg_ncasecmp(host, "localhost", 9) != 0) { return 0; } #if MG_ENABLE_SYNC_RESOLVER if (!mg_resolve2(host, &sa->sin.sin_addr)) { return -1; } #else return -1; #endif } #endif } else if (sscanf(str, ":%u%n", &port, &len) == 1 || sscanf(str, "%u%n", &port, &len) == 1) { /* If only port is specified, bind to IPv4, INADDR_ANY */ sa->sin.sin_port = htons((uint16_t) port); } else { return -1; } /* Required for MG_ENABLE_ASYNC_RESOLVER=0 */ (void) host; (void) host_len; ch = str[len]; /* Character that follows the address */ return port < 0xffffUL && (ch == '\0' || ch == ',' || isspace(ch)) ? len : -1; } #if MG_ENABLE_SSL MG_INTERNAL void mg_ssl_handshake(struct mg_connection *nc) { int err = 0; int server_side = (nc->listener != NULL); enum mg_ssl_if_result res; if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) return; res = mg_ssl_if_handshake(nc); if (res == MG_SSL_OK) { nc->flags |= MG_F_SSL_HANDSHAKE_DONE; nc->flags &= ~(MG_F_WANT_READ | MG_F_WANT_WRITE); if (server_side) { mg_call(nc, NULL, nc->user_data, MG_EV_ACCEPT, &nc->sa); } else { mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &err); } } else if (res == MG_SSL_WANT_READ) { nc->flags |= MG_F_WANT_READ; } else if (res == MG_SSL_WANT_WRITE) { nc->flags |= MG_F_WANT_WRITE; } else { if (!server_side) { err = res; mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &err); } nc->flags |= MG_F_CLOSE_IMMEDIATELY; } } #endif /* MG_ENABLE_SSL */ struct mg_connection *mg_if_accept_new_conn(struct mg_connection *lc) { struct mg_add_sock_opts opts; struct mg_connection *nc; memset(&opts, 0, sizeof(opts)); nc = mg_create_connection(lc->mgr, lc->handler, opts); if (nc == NULL) return NULL; nc->listener = lc; nc->proto_handler = lc->proto_handler; nc->user_data = lc->user_data; nc->recv_mbuf_limit = lc->recv_mbuf_limit; nc->iface = lc->iface; if (lc->flags & MG_F_SSL) nc->flags |= MG_F_SSL; mg_add_conn(nc->mgr, nc); LOG(LL_DEBUG, ("%p %p %d %d", lc, nc, nc->sock, (int) nc->flags)); return nc; } void mg_if_accept_tcp_cb(struct mg_connection *nc, union socket_address *sa, size_t sa_len) { LOG(LL_DEBUG, ("%p %s://%s:%hu", nc, (nc->flags & MG_F_UDP ? "udp" : "tcp"), inet_ntoa(sa->sin.sin_addr), ntohs(sa->sin.sin_port))); nc->sa = *sa; #if MG_ENABLE_SSL if (nc->listener->flags & MG_F_SSL) { nc->flags |= MG_F_SSL; if (mg_ssl_if_conn_accept(nc, nc->listener) == MG_SSL_OK) { mg_ssl_handshake(nc); } else { mg_close_conn(nc); } } else #endif { mg_call(nc, NULL, nc->user_data, MG_EV_ACCEPT, &nc->sa); } (void) sa_len; } void mg_send(struct mg_connection *nc, const void *buf, int len) { nc->last_io_time = (time_t) mg_time(); mbuf_append(&nc->send_mbuf, buf, len); } static int mg_recv_tcp(struct mg_connection *nc, char *buf, size_t len); static int mg_recv_udp(struct mg_connection *nc, char *buf, size_t len); static int mg_do_recv(struct mg_connection *nc) { int res = 0; char *buf = NULL; size_t len = (nc->flags & MG_F_UDP ? MG_UDP_IO_SIZE : MG_TCP_IO_SIZE); if ((nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_CONNECTING)) || ((nc->flags & MG_F_LISTENING) && !(nc->flags & MG_F_UDP))) { return -1; } do { len = recv_avail_size(nc, len); if (len == 0) { res = -2; break; } if (nc->recv_mbuf.size < nc->recv_mbuf.len + len) { mbuf_resize(&nc->recv_mbuf, nc->recv_mbuf.len + len); } buf = nc->recv_mbuf.buf + nc->recv_mbuf.len; len = nc->recv_mbuf.size - nc->recv_mbuf.len; if (nc->flags & MG_F_UDP) { res = mg_recv_udp(nc, buf, len); } else { res = mg_recv_tcp(nc, buf, len); } } while (res > 0 && !(nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_UDP))); return res; } void mg_if_can_recv_cb(struct mg_connection *nc) { mg_do_recv(nc); } static int mg_recv_tcp(struct mg_connection *nc, char *buf, size_t len) { int n = 0; #if MG_ENABLE_SSL if (nc->flags & MG_F_SSL) { if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) { n = mg_ssl_if_read(nc, buf, len); DBG(("%p <- %d bytes (SSL)", nc, n)); if (n < 0) { if (n == MG_SSL_WANT_READ) { nc->flags |= MG_F_WANT_READ; n = 0; } else { nc->flags |= MG_F_CLOSE_IMMEDIATELY; } } else if (n > 0) { nc->flags &= ~MG_F_WANT_READ; } } else { mg_ssl_handshake(nc); } } else #endif { n = nc->iface->vtable->tcp_recv(nc, buf, len); DBG(("%p <- %d bytes", nc, n)); } if (n > 0) { nc->recv_mbuf.len += n; nc->last_io_time = (time_t) mg_time(); #if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP if (nc->mgr && nc->mgr->hexdump_file != NULL) { mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, n, MG_EV_RECV); } #endif mbuf_trim(&nc->recv_mbuf); mg_call(nc, NULL, nc->user_data, MG_EV_RECV, &n); } else if (n < 0) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; } mbuf_trim(&nc->recv_mbuf); return n; } static int mg_recv_udp(struct mg_connection *nc, char *buf, size_t len) { int n = 0; struct mg_connection *lc = nc; union socket_address sa; size_t sa_len = sizeof(sa); n = nc->iface->vtable->udp_recv(lc, buf, len, &sa, &sa_len); if (n < 0) { lc->flags |= MG_F_CLOSE_IMMEDIATELY; goto out; } if (nc->flags & MG_F_LISTENING) { /* * Do we have an existing connection for this source? * This is very inefficient for long connection lists. */ lc = nc; for (nc = mg_next(lc->mgr, NULL); nc != NULL; nc = mg_next(lc->mgr, nc)) { if (memcmp(&nc->sa.sa, &sa.sa, sa_len) == 0 && nc->listener == lc) { break; } } if (nc == NULL) { struct mg_add_sock_opts opts; memset(&opts, 0, sizeof(opts)); /* Create fake connection w/out sock initialization */ nc = mg_create_connection_base(lc->mgr, lc->handler, opts); if (nc != NULL) { nc->sock = lc->sock; nc->listener = lc; nc->sa = sa; nc->proto_handler = lc->proto_handler; nc->user_data = lc->user_data; nc->recv_mbuf_limit = lc->recv_mbuf_limit; nc->flags = MG_F_UDP; /* * Long-lived UDP "connections" i.e. interactions that involve more * than one request and response are rare, most are transactional: * response is sent and the "connection" is closed. Or - should be. * But users (including ourselves) tend to forget about that part, * because UDP is connectionless and one does not think about * processing a UDP request as handling a connection that needs to be * closed. Thus, we begin with SEND_AND_CLOSE flag set, which should * be a reasonable default for most use cases, but it is possible to * turn it off the connection should be kept alive after processing. */ nc->flags |= MG_F_SEND_AND_CLOSE; mg_add_conn(lc->mgr, nc); mg_call(nc, NULL, nc->user_data, MG_EV_ACCEPT, &nc->sa); } } } if (nc != NULL) { DBG(("%p <- %d bytes from %s:%d", nc, n, inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port))); if (nc == lc) { nc->recv_mbuf.len += n; } else { mbuf_append(&nc->recv_mbuf, buf, n); } mbuf_trim(&lc->recv_mbuf); lc->last_io_time = nc->last_io_time = (time_t) mg_time(); #if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP if (nc->mgr && nc->mgr->hexdump_file != NULL) { mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, n, MG_EV_RECV); } #endif if (n != 0) { mg_call(nc, NULL, nc->user_data, MG_EV_RECV, &n); } } out: mbuf_free(&lc->recv_mbuf); return n; } void mg_if_can_send_cb(struct mg_connection *nc) { int n = 0; const char *buf = nc->send_mbuf.buf; size_t len = nc->send_mbuf.len; if (nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_CONNECTING)) { return; } if (!(nc->flags & MG_F_UDP)) { if (nc->flags & MG_F_LISTENING) return; if (len > MG_TCP_IO_SIZE) len = MG_TCP_IO_SIZE; } #if MG_ENABLE_SSL if (nc->flags & MG_F_SSL) { if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) { if (len > 0) { n = mg_ssl_if_write(nc, buf, len); DBG(("%p -> %d bytes (SSL)", nc, n)); } if (n < 0) { if (n == MG_SSL_WANT_WRITE) { nc->flags |= MG_F_WANT_WRITE; n = 0; } else { nc->flags |= MG_F_CLOSE_IMMEDIATELY; } } else { nc->flags &= ~MG_F_WANT_WRITE; } } else { mg_ssl_handshake(nc); } } else #endif if (len > 0) { if (nc->flags & MG_F_UDP) { n = nc->iface->vtable->udp_send(nc, buf, len); } else { n = nc->iface->vtable->tcp_send(nc, buf, len); } DBG(("%p -> %d bytes", nc, n)); } #if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP if (n > 0 && nc->mgr && nc->mgr->hexdump_file != NULL) { mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, n, MG_EV_SEND); } #endif if (n < 0) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; } else if (n > 0) { nc->last_io_time = (time_t) mg_time(); mbuf_remove(&nc->send_mbuf, n); mbuf_trim(&nc->send_mbuf); } if (n != 0) mg_call(nc, NULL, nc->user_data, MG_EV_SEND, &n); } /* * Schedules an async connect for a resolved address and proto. * Called from two places: `mg_connect_opt()` and from async resolver. * When called from the async resolver, it must trigger `MG_EV_CONNECT` event * with a failure flag to indicate connection failure. */ MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc, int proto, union socket_address *sa) { LOG(LL_DEBUG, ("%p %s://%s:%hu", nc, proto == SOCK_DGRAM ? "udp" : "tcp", inet_ntoa(sa->sin.sin_addr), ntohs(sa->sin.sin_port))); nc->flags |= MG_F_CONNECTING; if (proto == SOCK_DGRAM) { nc->iface->vtable->connect_udp(nc); } else { nc->iface->vtable->connect_tcp(nc, sa); } mg_add_conn(nc->mgr, nc); return nc; } void mg_if_connect_cb(struct mg_connection *nc, int err) { LOG(LL_DEBUG, ("%p %s://%s:%hu -> %d", nc, (nc->flags & MG_F_UDP ? "udp" : "tcp"), inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port), err)); nc->flags &= ~MG_F_CONNECTING; if (err != 0) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; } #if MG_ENABLE_SSL if (err == 0 && (nc->flags & MG_F_SSL)) { mg_ssl_handshake(nc); } else #endif { mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &err); } } #if MG_ENABLE_ASYNC_RESOLVER /* * Callback for the async resolver on mg_connect_opt() call. * Main task of this function is to trigger MG_EV_CONNECT event with * either failure (and dealloc the connection) * or success (and proceed with connect() */ static void resolve_cb(struct mg_dns_message *msg, void *data, enum mg_resolve_err e) { struct mg_connection *nc = (struct mg_connection *) data; int i; int failure = -1; nc->flags &= ~MG_F_RESOLVING; if (msg != NULL) { /* * Take the first DNS A answer and run... */ for (i = 0; i < msg->num_answers; i++) { if (msg->answers[i].rtype == MG_DNS_A_RECORD) { /* * Async resolver guarantees that there is at least one answer. * TODO(lsm): handle IPv6 answers too */ mg_dns_parse_record_data(msg, &msg->answers[i], &nc->sa.sin.sin_addr, 4); mg_do_connect(nc, nc->flags & MG_F_UDP ? SOCK_DGRAM : SOCK_STREAM, &nc->sa); return; } } } if (e == MG_RESOLVE_TIMEOUT) { double now = mg_time(); mg_call(nc, NULL, nc->user_data, MG_EV_TIMER, &now); } /* * If we get there was no MG_DNS_A_RECORD in the answer */ mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &failure); mg_call(nc, NULL, nc->user_data, MG_EV_CLOSE, NULL); mg_destroy_conn(nc, 1 /* destroy_if */); } #endif struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *address, MG_CB(mg_event_handler_t callback, void *user_data)) { struct mg_connect_opts opts; memset(&opts, 0, sizeof(opts)); return mg_connect_opt(mgr, address, MG_CB(callback, user_data), opts); } void mg_ev_handler_empty(struct mg_connection *c, int ev, void *ev_data MG_UD_ARG(void *user_data)) { (void) c; (void) ev; (void) ev_data; #if MG_ENABLE_CALLBACK_USERDATA (void) user_data; #endif } struct mg_connection *mg_connect_opt(struct mg_mgr *mgr, const char *address, MG_CB(mg_event_handler_t callback, void *user_data), struct mg_connect_opts opts) { struct mg_connection *nc = NULL; int proto, rc; struct mg_add_sock_opts add_sock_opts; char host[MG_MAX_HOST_LEN]; MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts); if (callback == NULL) callback = mg_ev_handler_empty; if ((nc = mg_create_connection(mgr, callback, add_sock_opts)) == NULL) { return NULL; } if ((rc = mg_parse_address(address, &nc->sa, &proto, host, sizeof(host))) < 0) { /* Address is malformed */ MG_SET_PTRPTR(opts.error_string, "cannot parse address"); mg_destroy_conn(nc, 1 /* destroy_if */); return NULL; } nc->flags |= opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK; nc->flags |= (proto == SOCK_DGRAM) ? MG_F_UDP : 0; #if MG_ENABLE_CALLBACK_USERDATA nc->user_data = user_data; #else nc->user_data = opts.user_data; #endif #if MG_ENABLE_SSL LOG(LL_DEBUG, ("%p %s %s,%s,%s", nc, address, (opts.ssl_cert ? opts.ssl_cert : "-"), (opts.ssl_key ? opts.ssl_key : "-"), (opts.ssl_ca_cert ? opts.ssl_ca_cert : "-"))); if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL || opts.ssl_psk_identity != NULL) { const char *err_msg = NULL; struct mg_ssl_if_conn_params params; if (nc->flags & MG_F_UDP) { MG_SET_PTRPTR(opts.error_string, "SSL for UDP is not supported"); mg_destroy_conn(nc, 1 /* destroy_if */); return NULL; } memset(&params, 0, sizeof(params)); params.cert = opts.ssl_cert; params.key = opts.ssl_key; params.ca_cert = opts.ssl_ca_cert; params.cipher_suites = opts.ssl_cipher_suites; params.psk_identity = opts.ssl_psk_identity; params.psk_key = opts.ssl_psk_key; if (opts.ssl_ca_cert != NULL) { if (opts.ssl_server_name != NULL) { if (strcmp(opts.ssl_server_name, "*") != 0) { params.server_name = opts.ssl_server_name; } } else if (rc == 0) { /* If it's a DNS name, use host. */ params.server_name = host; } } if (mg_ssl_if_conn_init(nc, &params, &err_msg) != MG_SSL_OK) { MG_SET_PTRPTR(opts.error_string, err_msg); mg_destroy_conn(nc, 1 /* destroy_if */); return NULL; } nc->flags |= MG_F_SSL; } #endif /* MG_ENABLE_SSL */ if (rc == 0) { #if MG_ENABLE_ASYNC_RESOLVER /* * DNS resolution is required for host. * mg_parse_address() fills port in nc->sa, which we pass to resolve_cb() */ struct mg_connection *dns_conn = NULL; struct mg_resolve_async_opts o; memset(&o, 0, sizeof(o)); o.dns_conn = &dns_conn; o.nameserver = opts.nameserver; if (mg_resolve_async_opt(nc->mgr, host, MG_DNS_A_RECORD, resolve_cb, nc, o) != 0) { MG_SET_PTRPTR(opts.error_string, "cannot schedule DNS lookup"); mg_destroy_conn(nc, 1 /* destroy_if */); return NULL; } nc->priv_2 = dns_conn; nc->flags |= MG_F_RESOLVING; return nc; #else MG_SET_PTRPTR(opts.error_string, "Resolver is disabled"); mg_destroy_conn(nc, 1 /* destroy_if */); return NULL; #endif } else { /* Address is parsed and resolved to IP. proceed with connect() */ return mg_do_connect(nc, proto, &nc->sa); } } struct mg_connection *mg_bind(struct mg_mgr *srv, const char *address, MG_CB(mg_event_handler_t event_handler, void *user_data)) { struct mg_bind_opts opts; memset(&opts, 0, sizeof(opts)); return mg_bind_opt(srv, address, MG_CB(event_handler, user_data), opts); } struct mg_connection *mg_bind_opt(struct mg_mgr *mgr, const char *address, MG_CB(mg_event_handler_t callback, void *user_data), struct mg_bind_opts opts) { union socket_address sa; struct mg_connection *nc = NULL; int proto, rc; struct mg_add_sock_opts add_sock_opts; char host[MG_MAX_HOST_LEN]; #if MG_ENABLE_CALLBACK_USERDATA opts.user_data = user_data; #endif if (callback == NULL) callback = mg_ev_handler_empty; MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts); if (mg_parse_address(address, &sa, &proto, host, sizeof(host)) <= 0) { MG_SET_PTRPTR(opts.error_string, "cannot parse address"); return NULL; } nc = mg_create_connection(mgr, callback, add_sock_opts); if (nc == NULL) { return NULL; } nc->sa = sa; nc->flags |= MG_F_LISTENING; if (proto == SOCK_DGRAM) nc->flags |= MG_F_UDP; #if MG_ENABLE_SSL DBG(("%p %s %s,%s,%s", nc, address, (opts.ssl_cert ? opts.ssl_cert : "-"), (opts.ssl_key ? opts.ssl_key : "-"), (opts.ssl_ca_cert ? opts.ssl_ca_cert : "-"))); if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL) { const char *err_msg = NULL; struct mg_ssl_if_conn_params params; if (nc->flags & MG_F_UDP) { MG_SET_PTRPTR(opts.error_string, "SSL for UDP is not supported"); mg_destroy_conn(nc, 1 /* destroy_if */); return NULL; } memset(&params, 0, sizeof(params)); params.cert = opts.ssl_cert; params.key = opts.ssl_key; params.ca_cert = opts.ssl_ca_cert; params.cipher_suites = opts.ssl_cipher_suites; if (mg_ssl_if_conn_init(nc, &params, &err_msg) != MG_SSL_OK) { MG_SET_PTRPTR(opts.error_string, err_msg); mg_destroy_conn(nc, 1 /* destroy_if */); return NULL; } nc->flags |= MG_F_SSL; } #endif /* MG_ENABLE_SSL */ if (nc->flags & MG_F_UDP) { rc = nc->iface->vtable->listen_udp(nc, &nc->sa); } else { rc = nc->iface->vtable->listen_tcp(nc, &nc->sa); } if (rc != 0) { DBG(("Failed to open listener: %d", rc)); MG_SET_PTRPTR(opts.error_string, "failed to open listener"); mg_destroy_conn(nc, 1 /* destroy_if */); return NULL; } mg_add_conn(nc->mgr, nc); return nc; } struct mg_connection *mg_next(struct mg_mgr *s, struct mg_connection *conn) { return conn == NULL ? s->active_connections : conn->next; } #if MG_ENABLE_BROADCAST void mg_broadcast(struct mg_mgr *mgr, mg_event_handler_t cb, void *data, size_t len) { struct ctl_msg ctl_msg; /* * Mongoose manager has a socketpair, `struct mg_mgr::ctl`, * where `mg_broadcast()` pushes the message. * `mg_mgr_poll()` wakes up, reads a message from the socket pair, and calls * specified callback for each connection. Thus the callback function executes * in event manager thread. */ if (mgr->ctl[0] != INVALID_SOCKET && data != NULL && len < sizeof(ctl_msg.message)) { size_t dummy; ctl_msg.callback = cb; memcpy(ctl_msg.message, data, len); dummy = MG_SEND_FUNC(mgr->ctl[0], (char *) &ctl_msg, offsetof(struct ctl_msg, message) + len, 0); dummy = MG_RECV_FUNC(mgr->ctl[0], (char *) &len, 1, 0); (void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */ } } #endif /* MG_ENABLE_BROADCAST */ static int isbyte(int n) { return n >= 0 && n <= 255; } static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) { int n, a, b, c, d, slash = 32, len = 0; if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 && slash < 33) { len = n; *net = ((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | d; *mask = slash ? 0xffffffffU << (32 - slash) : 0; } return len; } int mg_check_ip_acl(const char *acl, uint32_t remote_ip) { int allowed, flag; uint32_t net, mask; struct mg_str vec; /* If any ACL is set, deny by default */ allowed = (acl == NULL || *acl == '\0') ? '+' : '-'; while ((acl = mg_next_comma_list_entry(acl, &vec, NULL)) != NULL) { flag = vec.p[0]; if ((flag != '+' && flag != '-') || parse_net(&vec.p[1], &net, &mask) == 0) { return -1; } if (net == (remote_ip & mask)) { allowed = flag; } } DBG(("%08x %c", (unsigned int) remote_ip, allowed)); return allowed == '+'; } /* Move data from one connection to another */ void mg_forward(struct mg_connection *from, struct mg_connection *to) { mg_send(to, from->recv_mbuf.buf, from->recv_mbuf.len); mbuf_remove(&from->recv_mbuf, from->recv_mbuf.len); } double mg_set_timer(struct mg_connection *c, double timestamp) { double result = c->ev_timer_time; c->ev_timer_time = timestamp; /* * If this connection is resolving, it's not in the list of active * connections, so not processed yet. It has a DNS resolver connection * linked to it. Set up a timer for the DNS connection. */ DBG(("%p %p %d -> %lu", c, c->priv_2, (c->flags & MG_F_RESOLVING ? 1 : 0), (unsigned long) timestamp)); if ((c->flags & MG_F_RESOLVING) && c->priv_2 != NULL) { mg_set_timer((struct mg_connection *) c->priv_2, timestamp); } return result; } void mg_sock_set(struct mg_connection *nc, sock_t sock) { if (sock != INVALID_SOCKET) { nc->iface->vtable->sock_set(nc, sock); } } void mg_if_get_conn_addr(struct mg_connection *nc, int remote, union socket_address *sa) { nc->iface->vtable->get_conn_addr(nc, remote, sa); } struct mg_connection *mg_add_sock_opt(struct mg_mgr *s, sock_t sock, MG_CB(mg_event_handler_t callback, void *user_data), struct mg_add_sock_opts opts) { #if MG_ENABLE_CALLBACK_USERDATA opts.user_data = user_data; #endif struct mg_connection *nc = mg_create_connection_base(s, callback, opts); if (nc != NULL) { mg_sock_set(nc, sock); mg_add_conn(nc->mgr, nc); } return nc; } struct mg_connection *mg_add_sock(struct mg_mgr *s, sock_t sock, MG_CB(mg_event_handler_t callback, void *user_data)) { struct mg_add_sock_opts opts; memset(&opts, 0, sizeof(opts)); return mg_add_sock_opt(s, sock, MG_CB(callback, user_data), opts); } double mg_time(void) { return cs_time(); } #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_net_if_socket.h" #endif /* * Copyright (c) 2014-2016 Cesanta Software Limited * All rights reserved */ #ifndef CS_MONGOOSE_SRC_NET_IF_SOCKET_H_ #define CS_MONGOOSE_SRC_NET_IF_SOCKET_H_ /* Amalgamated: #include "mg_net_if.h" */ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #ifndef MG_ENABLE_NET_IF_SOCKET #define MG_ENABLE_NET_IF_SOCKET MG_NET_IF == MG_NET_IF_SOCKET #endif extern const struct mg_iface_vtable mg_socket_iface_vtable; #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* CS_MONGOOSE_SRC_NET_IF_SOCKET_H_ */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_net_if_socks.h" #endif /* * Copyright (c) 2014-2017 Cesanta Software Limited * All rights reserved */ #ifndef CS_MONGOOSE_SRC_NET_IF_SOCKS_H_ #define CS_MONGOOSE_SRC_NET_IF_SOCKS_H_ #if MG_ENABLE_SOCKS /* Amalgamated: #include "mg_net_if.h" */ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ extern const struct mg_iface_vtable mg_socks_iface_vtable; #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* MG_ENABLE_SOCKS */ #endif /* CS_MONGOOSE_SRC_NET_IF_SOCKS_H_ */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_net_if.c" #endif /* Amalgamated: #include "mg_net_if.h" */ /* Amalgamated: #include "mg_internal.h" */ /* Amalgamated: #include "mg_net_if_socket.h" */ extern const struct mg_iface_vtable mg_default_iface_vtable; const struct mg_iface_vtable *mg_ifaces[] = { &mg_default_iface_vtable, }; int mg_num_ifaces = (int) (sizeof(mg_ifaces) / sizeof(mg_ifaces[0])); struct mg_iface *mg_if_create_iface(const struct mg_iface_vtable *vtable, struct mg_mgr *mgr) { struct mg_iface *iface = (struct mg_iface *) MG_CALLOC(1, sizeof(*iface)); iface->mgr = mgr; iface->data = NULL; iface->vtable = vtable; return iface; } struct mg_iface *mg_find_iface(struct mg_mgr *mgr, const struct mg_iface_vtable *vtable, struct mg_iface *from) { int i = 0; if (from != NULL) { for (i = 0; i < mgr->num_ifaces; i++) { if (mgr->ifaces[i] == from) { i++; break; } } } for (; i < mgr->num_ifaces; i++) { if (mgr->ifaces[i]->vtable == vtable) { return mgr->ifaces[i]; } } return NULL; } double mg_mgr_min_timer(const struct mg_mgr *mgr) { double min_timer = 0; struct mg_connection *nc; for (nc = mgr->active_connections; nc != NULL; nc = nc->next) { if (nc->ev_timer_time <= 0) continue; if (min_timer == 0 || nc->ev_timer_time < min_timer) { min_timer = nc->ev_timer_time; } } return min_timer; } #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_net_if_null.c" #endif /* * Copyright (c) 2018 Cesanta Software Limited * All rights reserved * * This software is dual-licensed: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. For the terms of this * license, see <http://www.gnu.org/licenses/>. * * You are free to use this software under the terms of the GNU General * Public License, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * Alternatively, you can license this software under a commercial * license, as set out in <https://www.cesanta.com/license>. */ static void mg_null_if_connect_tcp(struct mg_connection *c, const union socket_address *sa) { c->flags |= MG_F_CLOSE_IMMEDIATELY; (void) sa; } static void mg_null_if_connect_udp(struct mg_connection *c) { c->flags |= MG_F_CLOSE_IMMEDIATELY; } static int mg_null_if_listen_tcp(struct mg_connection *c, union socket_address *sa) { (void) c; (void) sa; return -1; } static int mg_null_if_listen_udp(struct mg_connection *c, union socket_address *sa) { (void) c; (void) sa; return -1; } static int mg_null_if_tcp_send(struct mg_connection *c, const void *buf, size_t len) { (void) c; (void) buf; (void) len; return -1; } static int mg_null_if_udp_send(struct mg_connection *c, const void *buf, size_t len) { (void) c; (void) buf; (void) len; return -1; } int mg_null_if_tcp_recv(struct mg_connection *c, void *buf, size_t len) { (void) c; (void) buf; (void) len; return -1; } int mg_null_if_udp_recv(struct mg_connection *c, void *buf, size_t len, union socket_address *sa, size_t *sa_len) { (void) c; (void) buf; (void) len; (void) sa; (void) sa_len; return -1; } static int mg_null_if_create_conn(struct mg_connection *c) { (void) c; return 1; } static void mg_null_if_destroy_conn(struct mg_connection *c) { (void) c; } static void mg_null_if_sock_set(struct mg_connection *c, sock_t sock) { (void) c; (void) sock; } static void mg_null_if_init(struct mg_iface *iface) { (void) iface; } static void mg_null_if_free(struct mg_iface *iface) { (void) iface; } static void mg_null_if_add_conn(struct mg_connection *c) { c->sock = INVALID_SOCKET; c->flags |= MG_F_CLOSE_IMMEDIATELY; } static void mg_null_if_remove_conn(struct mg_connection *c) { (void) c; } static time_t mg_null_if_poll(struct mg_iface *iface, int timeout_ms) { struct mg_mgr *mgr = iface->mgr; struct mg_connection *nc, *tmp; double now = mg_time(); /* We basically just run timers and poll. */ for (nc = mgr->active_connections; nc != NULL; nc = tmp) { tmp = nc->next; mg_if_poll(nc, now); } (void) timeout_ms; return (time_t) now; } static void mg_null_if_get_conn_addr(struct mg_connection *c, int remote, union socket_address *sa) { (void) c; (void) remote; (void) sa; } #define MG_NULL_IFACE_VTABLE \ { \ mg_null_if_init, mg_null_if_free, mg_null_if_add_conn, \ mg_null_if_remove_conn, mg_null_if_poll, mg_null_if_listen_tcp, \ mg_null_if_listen_udp, mg_null_if_connect_tcp, mg_null_if_connect_udp, \ mg_null_if_tcp_send, mg_null_if_udp_send, mg_null_if_tcp_recv, \ mg_null_if_udp_recv, mg_null_if_create_conn, mg_null_if_destroy_conn, \ mg_null_if_sock_set, mg_null_if_get_conn_addr, \ } const struct mg_iface_vtable mg_null_iface_vtable = MG_NULL_IFACE_VTABLE; #if MG_NET_IF == MG_NET_IF_NULL const struct mg_iface_vtable mg_default_iface_vtable = MG_NULL_IFACE_VTABLE; #endif /* MG_NET_IF == MG_NET_IF_NULL */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_net_if_socket.c" #endif /* * Copyright (c) 2014-2016 Cesanta Software Limited * All rights reserved */ #if MG_ENABLE_NET_IF_SOCKET /* Amalgamated: #include "mg_net_if_socket.h" */ /* Amalgamated: #include "mg_internal.h" */ /* Amalgamated: #include "mg_util.h" */ static sock_t mg_open_listening_socket(union socket_address *sa, int type, int proto); void mg_set_non_blocking_mode(sock_t sock) { #ifdef _WIN32 unsigned long on = 1; ioctlsocket(sock, FIONBIO, &on); #else int flags = fcntl(sock, F_GETFL, 0); fcntl(sock, F_SETFL, flags | O_NONBLOCK); #endif } static int mg_is_error(void) { int err = mg_get_errno(); return err != EINPROGRESS && err != EWOULDBLOCK #ifndef WINCE && err != EAGAIN && err != EINTR #endif #ifdef _WIN32 && WSAGetLastError() != WSAEINTR && WSAGetLastError() != WSAEWOULDBLOCK #endif ; } void mg_socket_if_connect_tcp(struct mg_connection *nc, const union socket_address *sa) { int rc, proto = 0; nc->sock = socket(AF_INET, SOCK_STREAM, proto); if (nc->sock == INVALID_SOCKET) { nc->err = mg_get_errno() ? mg_get_errno() : 1; return; } #if !defined(MG_ESP8266) mg_set_non_blocking_mode(nc->sock); #endif rc = connect(nc->sock, &sa->sa, sizeof(sa->sin)); nc->err = rc < 0 && mg_is_error() ? mg_get_errno() : 0; DBG(("%p sock %d rc %d errno %d err %d", nc, nc->sock, rc, mg_get_errno(), nc->err)); } void mg_socket_if_connect_udp(struct mg_connection *nc) { nc->sock = socket(AF_INET, SOCK_DGRAM, 0); if (nc->sock == INVALID_SOCKET) { nc->err = mg_get_errno() ? mg_get_errno() : 1; return; } if (nc->flags & MG_F_ENABLE_BROADCAST) { int optval = 1; if (setsockopt(nc->sock, SOL_SOCKET, SO_BROADCAST, (const char *) &optval, sizeof(optval)) < 0) { nc->err = mg_get_errno() ? mg_get_errno() : 1; return; } } nc->err = 0; } int mg_socket_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) { int proto = 0; sock_t sock = mg_open_listening_socket(sa, SOCK_STREAM, proto); if (sock == INVALID_SOCKET) { return (mg_get_errno() ? mg_get_errno() : 1); } mg_sock_set(nc, sock); return 0; } static int mg_socket_if_listen_udp(struct mg_connection *nc, union socket_address *sa) { sock_t sock = mg_open_listening_socket(sa, SOCK_DGRAM, 0); if (sock == INVALID_SOCKET) return (mg_get_errno() ? mg_get_errno() : 1); mg_sock_set(nc, sock); return 0; } static int mg_socket_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) { int n = (int) MG_SEND_FUNC(nc->sock, buf, len, 0); if (n < 0 && !mg_is_error()) n = 0; return n; } static int mg_socket_if_udp_send(struct mg_connection *nc, const void *buf, size_t len) { int n = sendto(nc->sock, buf, len, 0, &nc->sa.sa, sizeof(nc->sa.sin)); if (n < 0 && !mg_is_error()) n = 0; return n; } static int mg_socket_if_tcp_recv(struct mg_connection *nc, void *buf, size_t len) { int n = (int) MG_RECV_FUNC(nc->sock, buf, len, 0); if (n == 0) { /* Orderly shutdown of the socket, try flushing output. */ nc->flags |= MG_F_SEND_AND_CLOSE; } else if (n < 0 && !mg_is_error()) { n = 0; } return n; } static int mg_socket_if_udp_recv(struct mg_connection *nc, void *buf, size_t len, union socket_address *sa, size_t *sa_len) { socklen_t sa_len_st = *sa_len; int n = recvfrom(nc->sock, buf, len, 0, &sa->sa, &sa_len_st); *sa_len = sa_len_st; if (n < 0 && !mg_is_error()) n = 0; return n; } int mg_socket_if_create_conn(struct mg_connection *nc) { (void) nc; return 1; } void mg_socket_if_destroy_conn(struct mg_connection *nc) { if (nc->sock == INVALID_SOCKET) return; if (!(nc->flags & MG_F_UDP)) { closesocket(nc->sock); } else { /* Only close outgoing UDP sockets or listeners. */ if (nc->listener == NULL) closesocket(nc->sock); } nc->sock = INVALID_SOCKET; } static int mg_accept_conn(struct mg_connection *lc) { struct mg_connection *nc; union socket_address sa; socklen_t sa_len = sizeof(sa); /* NOTE(lsm): on Windows, sock is always > FD_SETSIZE */ sock_t sock = accept(lc->sock, &sa.sa, &sa_len); if (sock == INVALID_SOCKET) { if (mg_is_error()) { DBG(("%p: failed to accept: %d", lc, mg_get_errno())); } return 0; } nc = mg_if_accept_new_conn(lc); if (nc == NULL) { closesocket(sock); return 0; } DBG(("%p conn from %s:%d", nc, inet_ntoa(sa.sin.sin_addr), ntohs(sa.sin.sin_port))); mg_sock_set(nc, sock); mg_if_accept_tcp_cb(nc, &sa, sa_len); return 1; } /* 'sa' must be an initialized address to bind to */ static sock_t mg_open_listening_socket(union socket_address *sa, int type, int proto) { socklen_t sa_len = (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6); sock_t sock = INVALID_SOCKET; #if !MG_LWIP int on = 1; #endif if ((sock = socket(sa->sa.sa_family, type, proto)) != INVALID_SOCKET && #if !MG_LWIP /* LWIP doesn't support either */ #if defined(_WIN32) && defined(SO_EXCLUSIVEADDRUSE) && !defined(WINCE) /* "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE" http://goo.gl/RmrFTm */ !setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (void *) &on, sizeof(on)) && #endif #if !defined(_WIN32) || !defined(SO_EXCLUSIVEADDRUSE) /* * SO_RESUSEADDR is not enabled on Windows because the semantics of * SO_REUSEADDR on UNIX and Windows is different. On Windows, * SO_REUSEADDR allows to bind a socket to a port without error even if * the port is already open by another program. This is not the behavior * SO_REUSEADDR was designed for, and leads to hard-to-track failure * scenarios. Therefore, SO_REUSEADDR was disabled on Windows unless * SO_EXCLUSIVEADDRUSE is supported and set on a socket. */ !setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof(on)) && #endif #endif /* !MG_LWIP */ !bind(sock, &sa->sa, sa_len) && (type == SOCK_DGRAM || listen(sock, SOMAXCONN) == 0)) { #if !MG_LWIP mg_set_non_blocking_mode(sock); /* In case port was set to 0, get the real port number */ (void) getsockname(sock, &sa->sa, &sa_len); #endif } else if (sock != INVALID_SOCKET) { closesocket(sock); sock = INVALID_SOCKET; } return sock; } #define _MG_F_FD_CAN_READ 1 #define _MG_F_FD_CAN_WRITE 1 << 1 #define _MG_F_FD_ERROR 1 << 2 void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) { int worth_logging = fd_flags != 0 || (nc->flags & (MG_F_WANT_READ | MG_F_WANT_WRITE)); if (worth_logging) { DBG(("%p fd=%d fd_flags=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->sock, fd_flags, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len)); } if (!mg_if_poll(nc, now)) return; if (nc->flags & MG_F_CONNECTING) { if (fd_flags != 0) { int err = 0; #if !defined(MG_ESP8266) if (!(nc->flags & MG_F_UDP)) { socklen_t len = sizeof(err); int ret = getsockopt(nc->sock, SOL_SOCKET, SO_ERROR, (char *) &err, &len); if (ret != 0) { err = 1; } else if (err == EAGAIN || err == EWOULDBLOCK) { err = 0; } } #else /* * On ESP8266 we use blocking connect. */ err = nc->err; #endif mg_if_connect_cb(nc, err); } else if (nc->err != 0) { mg_if_connect_cb(nc, nc->err); } } if (fd_flags & _MG_F_FD_CAN_READ) { if (nc->flags & MG_F_UDP) { mg_if_can_recv_cb(nc); } else { if (nc->flags & MG_F_LISTENING) { /* * We're not looping here, and accepting just one connection at * a time. The reason is that eCos does not respect non-blocking * flag on a listening socket and hangs in a loop. */ mg_accept_conn(nc); } else { mg_if_can_recv_cb(nc); } } } if (fd_flags & _MG_F_FD_CAN_WRITE) mg_if_can_send_cb(nc); if (worth_logging) { DBG(("%p after fd=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->sock, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len)); } } #if MG_ENABLE_BROADCAST static void mg_mgr_handle_ctl_sock(struct mg_mgr *mgr) { struct ctl_msg ctl_msg; int len = (int) MG_RECV_FUNC(mgr->ctl[1], (char *) &ctl_msg, sizeof(ctl_msg), 0); size_t dummy = MG_SEND_FUNC(mgr->ctl[1], ctl_msg.message, 1, 0); DBG(("read %d from ctl socket", len)); (void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */ if (len >= (int) sizeof(ctl_msg.callback) && ctl_msg.callback != NULL) { struct mg_connection *nc; for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) { ctl_msg.callback(nc, MG_EV_POLL, ctl_msg.message MG_UD_ARG(nc->user_data)); } } } #endif /* Associate a socket to a connection. */ void mg_socket_if_sock_set(struct mg_connection *nc, sock_t sock) { mg_set_non_blocking_mode(sock); mg_set_close_on_exec(sock); nc->sock = sock; DBG(("%p %d", nc, sock)); } void mg_socket_if_init(struct mg_iface *iface) { (void) iface; DBG(("%p using select()", iface->mgr)); #if MG_ENABLE_BROADCAST mg_socketpair(iface->mgr->ctl, SOCK_DGRAM); #endif } void mg_socket_if_free(struct mg_iface *iface) { (void) iface; } void mg_socket_if_add_conn(struct mg_connection *nc) { (void) nc; } void mg_socket_if_remove_conn(struct mg_connection *nc) { (void) nc; } void mg_add_to_set(sock_t sock, fd_set *set, sock_t *max_fd) { if (sock != INVALID_SOCKET #ifdef __unix__ && sock < (sock_t) FD_SETSIZE #endif ) { FD_SET(sock, set); if (*max_fd == INVALID_SOCKET || sock > *max_fd) { *max_fd = sock; } } } time_t mg_socket_if_poll(struct mg_iface *iface, int timeout_ms) { struct mg_mgr *mgr = iface->mgr; double now = mg_time(); double min_timer; struct mg_connection *nc, *tmp; struct timeval tv; fd_set read_set, write_set, err_set; sock_t max_fd = INVALID_SOCKET; int num_fds, num_ev, num_timers = 0; #ifdef __unix__ int try_dup = 1; #endif FD_ZERO(&read_set); FD_ZERO(&write_set); FD_ZERO(&err_set); #if MG_ENABLE_BROADCAST mg_add_to_set(mgr->ctl[1], &read_set, &max_fd); #endif /* * Note: it is ok to have connections with sock == INVALID_SOCKET in the list, * e.g. timer-only "connections". */ min_timer = 0; for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) { tmp = nc->next; if (nc->sock != INVALID_SOCKET) { num_fds++; #ifdef __unix__ /* A hack to make sure all our file descriptos fit into FD_SETSIZE. */ if (nc->sock >= (sock_t) FD_SETSIZE && try_dup) { int new_sock = dup(nc->sock); if (new_sock >= 0) { if (new_sock < (sock_t) FD_SETSIZE) { closesocket(nc->sock); DBG(("new sock %d -> %d", nc->sock, new_sock)); nc->sock = new_sock; } else { closesocket(new_sock); DBG(("new sock is still larger than FD_SETSIZE, disregard")); try_dup = 0; } } else { try_dup = 0; } } #endif if (nc->recv_mbuf.len < nc->recv_mbuf_limit && (!(nc->flags & MG_F_UDP) || nc->listener == NULL)) { mg_add_to_set(nc->sock, &read_set, &max_fd); } if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) || (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) { mg_add_to_set(nc->sock, &write_set, &max_fd); mg_add_to_set(nc->sock, &err_set, &max_fd); } } if (nc->ev_timer_time > 0) { if (num_timers == 0 || nc->ev_timer_time < min_timer) { min_timer = nc->ev_timer_time; } num_timers++; } } /* * If there is a timer to be fired earlier than the requested timeout, * adjust the timeout. */ if (num_timers > 0) { double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */; if (timer_timeout_ms < timeout_ms) { timeout_ms = (int) timer_timeout_ms; } } if (timeout_ms < 0) timeout_ms = 0; tv.tv_sec = timeout_ms / 1000; tv.tv_usec = (timeout_ms % 1000) * 1000; num_ev = select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv); now = mg_time(); #if 0 DBG(("select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev, num_fds, timeout_ms)); #endif #if MG_ENABLE_BROADCAST if (num_ev > 0 && mgr->ctl[1] != INVALID_SOCKET && FD_ISSET(mgr->ctl[1], &read_set)) { mg_mgr_handle_ctl_sock(mgr); } #endif for (nc = mgr->active_connections; nc != NULL; nc = tmp) { int fd_flags = 0; if (nc->sock != INVALID_SOCKET) { if (num_ev > 0) { fd_flags = (FD_ISSET(nc->sock, &read_set) && (!(nc->flags & MG_F_UDP) || nc->listener == NULL) ? _MG_F_FD_CAN_READ : 0) | (FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE : 0) | (FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0); } #if MG_LWIP /* With LWIP socket emulation layer, we don't get write events for UDP */ if ((nc->flags & MG_F_UDP) && nc->listener == NULL) { fd_flags |= _MG_F_FD_CAN_WRITE; } #endif } tmp = nc->next; mg_mgr_handle_conn(nc, fd_flags, now); } return (time_t) now; } #if MG_ENABLE_BROADCAST MG_INTERNAL void mg_socketpair_close(sock_t *sock) { while (1) { if (closesocket(*sock) == -1 && errno == EINTR) continue; break; } *sock = INVALID_SOCKET; } MG_INTERNAL sock_t mg_socketpair_accept(sock_t sock, union socket_address *sa, socklen_t sa_len) { sock_t rc; while (1) { if ((rc = accept(sock, &sa->sa, &sa_len)) == INVALID_SOCKET && errno == EINTR) continue; break; } return rc; } int mg_socketpair(sock_t sp[2], int sock_type) { union socket_address sa, sa2; sock_t sock; socklen_t len = sizeof(sa.sin); int ret = 0; sock = sp[0] = sp[1] = INVALID_SOCKET; (void) memset(&sa, 0, sizeof(sa)); sa.sin.sin_family = AF_INET; sa.sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */ sa2 = sa; if ((sock = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) { } else if (bind(sock, &sa.sa, len) != 0) { } else if (sock_type == SOCK_STREAM && listen(sock, 1) != 0) { } else if (getsockname(sock, &sa.sa, &len) != 0) { } else if ((sp[0] = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) { } else if (sock_type == SOCK_STREAM && connect(sp[0], &sa.sa, len) != 0) { } else if (sock_type == SOCK_DGRAM && (bind(sp[0], &sa2.sa, len) != 0 || getsockname(sp[0], &sa2.sa, &len) != 0 || connect(sp[0], &sa.sa, len) != 0 || connect(sock, &sa2.sa, len) != 0)) { } else if ((sp[1] = (sock_type == SOCK_DGRAM ? sock : mg_socketpair_accept( sock, &sa, len))) == INVALID_SOCKET) { } else { mg_set_close_on_exec(sp[0]); mg_set_close_on_exec(sp[1]); if (sock_type == SOCK_STREAM) mg_socketpair_close(&sock); ret = 1; } if (!ret) { if (sp[0] != INVALID_SOCKET) mg_socketpair_close(&sp[0]); if (sp[1] != INVALID_SOCKET) mg_socketpair_close(&sp[1]); if (sock != INVALID_SOCKET) mg_socketpair_close(&sock); } return ret; } #endif /* MG_ENABLE_BROADCAST */ static void mg_sock_get_addr(sock_t sock, int remote, union socket_address *sa) { socklen_t slen = sizeof(*sa); memset(sa, 0, slen); if (remote) { getpeername(sock, &sa->sa, &slen); } else { getsockname(sock, &sa->sa, &slen); } } void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags) { union socket_address sa; mg_sock_get_addr(sock, flags & MG_SOCK_STRINGIFY_REMOTE, &sa); mg_sock_addr_to_str(&sa, buf, len, flags); } void mg_socket_if_get_conn_addr(struct mg_connection *nc, int remote, union socket_address *sa) { if ((nc->flags & MG_F_UDP) && remote) { memcpy(sa, &nc->sa, sizeof(*sa)); return; } mg_sock_get_addr(nc->sock, remote, sa); } /* clang-format off */ #define MG_SOCKET_IFACE_VTABLE \ { \ mg_socket_if_init, \ mg_socket_if_free, \ mg_socket_if_add_conn, \ mg_socket_if_remove_conn, \ mg_socket_if_poll, \ mg_socket_if_listen_tcp, \ mg_socket_if_listen_udp, \ mg_socket_if_connect_tcp, \ mg_socket_if_connect_udp, \ mg_socket_if_tcp_send, \ mg_socket_if_udp_send, \ mg_socket_if_tcp_recv, \ mg_socket_if_udp_recv, \ mg_socket_if_create_conn, \ mg_socket_if_destroy_conn, \ mg_socket_if_sock_set, \ mg_socket_if_get_conn_addr, \ } /* clang-format on */ const struct mg_iface_vtable mg_socket_iface_vtable = MG_SOCKET_IFACE_VTABLE; #if MG_NET_IF == MG_NET_IF_SOCKET const struct mg_iface_vtable mg_default_iface_vtable = MG_SOCKET_IFACE_VTABLE; #endif #endif /* MG_ENABLE_NET_IF_SOCKET */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_net_if_socks.c" #endif /* * Copyright (c) 2014-2016 Cesanta Software Limited * All rights reserved */ #if MG_ENABLE_SOCKS struct socksdata { char *proxy_addr; /* HOST:PORT of the socks5 proxy server */ struct mg_connection *s; /* Respective connection to the server */ struct mg_connection *c; /* Connection to the client */ }; static void socks_if_disband(struct socksdata *d) { LOG(LL_DEBUG, ("disbanding proxy %p %p", d->c, d->s)); if (d->c) { d->c->flags |= MG_F_SEND_AND_CLOSE; d->c->user_data = NULL; d->c = NULL; } if (d->s) { d->s->flags |= MG_F_SEND_AND_CLOSE; d->s->user_data = NULL; d->s = NULL; } } static void socks_if_relay(struct mg_connection *s) { struct socksdata *d = (struct socksdata *) s->user_data; if (d == NULL || d->c == NULL || !(s->flags & MG_SOCKS_CONNECT_DONE) || d->s == NULL) { return; } if (s->recv_mbuf.len > 0) mg_if_can_recv_cb(d->c); if (d->c->send_mbuf.len > 0 && s->send_mbuf.len == 0) mg_if_can_send_cb(d->c); } static void socks_if_handler(struct mg_connection *c, int ev, void *ev_data) { struct socksdata *d = (struct socksdata *) c->user_data; if (d == NULL) return; if (ev == MG_EV_CONNECT) { int res = *(int *) ev_data; if (res == 0) { /* Send handshake to the proxy server */ unsigned char buf[] = {MG_SOCKS_VERSION, 1, MG_SOCKS_HANDSHAKE_NOAUTH}; mg_send(d->s, buf, sizeof(buf)); LOG(LL_DEBUG, ("Sent handshake to %s", d->proxy_addr)); } else { LOG(LL_ERROR, ("Cannot connect to %s: %d", d->proxy_addr, res)); d->c->flags |= MG_F_CLOSE_IMMEDIATELY; } } else if (ev == MG_EV_CLOSE) { socks_if_disband(d); } else if (ev == MG_EV_RECV) { /* Handle handshake reply */ if (!(c->flags & MG_SOCKS_HANDSHAKE_DONE)) { /* TODO(lsm): process IPv6 too */ unsigned char buf[10] = {MG_SOCKS_VERSION, MG_SOCKS_CMD_CONNECT, 0, MG_SOCKS_ADDR_IPV4}; if (c->recv_mbuf.len < 2) return; if ((unsigned char) c->recv_mbuf.buf[1] == MG_SOCKS_HANDSHAKE_FAILURE) { LOG(LL_ERROR, ("Server kicked us out")); socks_if_disband(d); return; } mbuf_remove(&c->recv_mbuf, 2); c->flags |= MG_SOCKS_HANDSHAKE_DONE; /* Send connect request */ memcpy(buf + 4, &d->c->sa.sin.sin_addr, 4); memcpy(buf + 8, &d->c->sa.sin.sin_port, 2); mg_send(c, buf, sizeof(buf)); LOG(LL_DEBUG, ("%p Sent connect request", c)); } /* Process connect request */ if ((c->flags & MG_SOCKS_HANDSHAKE_DONE) && !(c->flags & MG_SOCKS_CONNECT_DONE)) { if (c->recv_mbuf.len < 10) return; if (c->recv_mbuf.buf[1] != MG_SOCKS_SUCCESS) { LOG(LL_ERROR, ("Socks connection error: %d", c->recv_mbuf.buf[1])); socks_if_disband(d); return; } mbuf_remove(&c->recv_mbuf, 10); c->flags |= MG_SOCKS_CONNECT_DONE; LOG(LL_DEBUG, ("%p Connect done %p", c, d->c)); mg_if_connect_cb(d->c, 0); } socks_if_relay(c); } else if (ev == MG_EV_SEND || ev == MG_EV_POLL) { socks_if_relay(c); } } static void mg_socks_if_connect_tcp(struct mg_connection *c, const union socket_address *sa) { struct socksdata *d = (struct socksdata *) c->iface->data; d->c = c; d->s = mg_connect(c->mgr, d->proxy_addr, socks_if_handler); d->s->user_data = d; LOG(LL_DEBUG, ("%p %s %p %p", c, d->proxy_addr, d, d->s)); (void) sa; } static void mg_socks_if_connect_udp(struct mg_connection *c) { (void) c; } static int mg_socks_if_listen_tcp(struct mg_connection *c, union socket_address *sa) { (void) c; (void) sa; return 0; } static int mg_socks_if_listen_udp(struct mg_connection *c, union socket_address *sa) { (void) c; (void) sa; return -1; } static int mg_socks_if_tcp_send(struct mg_connection *c, const void *buf, size_t len) { int res; struct socksdata *d = (struct socksdata *) c->iface->data; if (d->s == NULL) return -1; res = (int) mbuf_append(&d->s->send_mbuf, buf, len); DBG(("%p -> %d -> %p", c, res, d->s)); return res; } static int mg_socks_if_udp_send(struct mg_connection *c, const void *buf, size_t len) { (void) c; (void) buf; (void) len; return -1; } int mg_socks_if_tcp_recv(struct mg_connection *c, void *buf, size_t len) { struct socksdata *d = (struct socksdata *) c->iface->data; if (d->s == NULL) return -1; if (len > d->s->recv_mbuf.len) len = d->s->recv_mbuf.len; if (len > 0) { memcpy(buf, d->s->recv_mbuf.buf, len); mbuf_remove(&d->s->recv_mbuf, len); } DBG(("%p <- %d <- %p", c, (int) len, d->s)); return len; } int mg_socks_if_udp_recv(struct mg_connection *c, void *buf, size_t len, union socket_address *sa, size_t *sa_len) { (void) c; (void) buf; (void) len; (void) sa; (void) sa_len; return -1; } static int mg_socks_if_create_conn(struct mg_connection *c) { (void) c; return 1; } static void mg_socks_if_destroy_conn(struct mg_connection *c) { c->iface->vtable->free(c->iface); MG_FREE(c->iface); c->iface = NULL; LOG(LL_DEBUG, ("%p", c)); } static void mg_socks_if_sock_set(struct mg_connection *c, sock_t sock) { (void) c; (void) sock; } static void mg_socks_if_init(struct mg_iface *iface) { (void) iface; } static void mg_socks_if_free(struct mg_iface *iface) { struct socksdata *d = (struct socksdata *) iface->data; LOG(LL_DEBUG, ("%p", iface)); if (d != NULL) { socks_if_disband(d); MG_FREE(d->proxy_addr); MG_FREE(d); iface->data = NULL; } } static void mg_socks_if_add_conn(struct mg_connection *c) { c->sock = INVALID_SOCKET; } static void mg_socks_if_remove_conn(struct mg_connection *c) { (void) c; } static time_t mg_socks_if_poll(struct mg_iface *iface, int timeout_ms) { LOG(LL_DEBUG, ("%p", iface)); (void) iface; (void) timeout_ms; return (time_t) cs_time(); } static void mg_socks_if_get_conn_addr(struct mg_connection *c, int remote, union socket_address *sa) { LOG(LL_DEBUG, ("%p", c)); (void) c; (void) remote; (void) sa; } const struct mg_iface_vtable mg_socks_iface_vtable = { mg_socks_if_init, mg_socks_if_free, mg_socks_if_add_conn, mg_socks_if_remove_conn, mg_socks_if_poll, mg_socks_if_listen_tcp, mg_socks_if_listen_udp, mg_socks_if_connect_tcp, mg_socks_if_connect_udp, mg_socks_if_tcp_send, mg_socks_if_udp_send, mg_socks_if_tcp_recv, mg_socks_if_udp_recv, mg_socks_if_create_conn, mg_socks_if_destroy_conn, mg_socks_if_sock_set, mg_socks_if_get_conn_addr, }; struct mg_iface *mg_socks_mk_iface(struct mg_mgr *mgr, const char *proxy_addr) { struct mg_iface *iface = mg_if_create_iface(&mg_socks_iface_vtable, mgr); iface->data = MG_CALLOC(1, sizeof(struct socksdata)); ((struct socksdata *) iface->data)->proxy_addr = strdup(proxy_addr); return iface; } #endif #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_ssl_if_openssl.c" #endif /* * Copyright (c) 2014-2016 Cesanta Software Limited * All rights reserved */ #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_OPENSSL #ifdef __APPLE__ #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif #include <openssl/ssl.h> #ifndef KR_VERSION #include <openssl/tls1.h> #endif struct mg_ssl_if_ctx { SSL *ssl; SSL_CTX *ssl_ctx; struct mbuf psk; size_t identity_len; }; void mg_ssl_if_init() { SSL_library_init(); } enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc, struct mg_connection *lc) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx)); struct mg_ssl_if_ctx *lc_ctx = (struct mg_ssl_if_ctx *) lc->ssl_if_data; nc->ssl_if_data = ctx; if (ctx == NULL || lc_ctx == NULL) return MG_SSL_ERROR; ctx->ssl_ctx = lc_ctx->ssl_ctx; if ((ctx->ssl = SSL_new(ctx->ssl_ctx)) == NULL) { return MG_SSL_ERROR; } return MG_SSL_OK; } static enum mg_ssl_if_result mg_use_cert(SSL_CTX *ctx, const char *cert, const char *key, const char **err_msg); static enum mg_ssl_if_result mg_use_ca_cert(SSL_CTX *ctx, const char *cert); static enum mg_ssl_if_result mg_set_cipher_list(SSL_CTX *ctx, const char *cl); static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx, const char *identity, const char *key_str); enum mg_ssl_if_result mg_ssl_if_conn_init( struct mg_connection *nc, const struct mg_ssl_if_conn_params *params, const char **err_msg) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx)); DBG(("%p %s,%s,%s", nc, (params->cert ? params->cert : ""), (params->key ? params->key : ""), (params->ca_cert ? params->ca_cert : ""))); if (ctx == NULL) { MG_SET_PTRPTR(err_msg, "Out of memory"); return MG_SSL_ERROR; } nc->ssl_if_data = ctx; if (nc->flags & MG_F_LISTENING) { ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method()); } else { ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()); } if (ctx->ssl_ctx == NULL) { MG_SET_PTRPTR(err_msg, "Failed to create SSL context"); return MG_SSL_ERROR; } #ifndef KR_VERSION /* Disable deprecated protocols. */ SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_SSLv2); SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_SSLv3); SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_TLSv1); #ifdef MG_SSL_OPENSSL_NO_COMPRESSION SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_COMPRESSION); #endif #ifdef MG_SSL_OPENSSL_CIPHER_SERVER_PREFERENCE SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE); #endif #else /* Krypton only supports TLSv1.2 anyway. */ #endif if (params->cert != NULL && mg_use_cert(ctx->ssl_ctx, params->cert, params->key, err_msg) != MG_SSL_OK) { return MG_SSL_ERROR; } if (params->ca_cert != NULL && mg_use_ca_cert(ctx->ssl_ctx, params->ca_cert) != MG_SSL_OK) { MG_SET_PTRPTR(err_msg, "Invalid SSL CA cert"); return MG_SSL_ERROR; } if (mg_set_cipher_list(ctx->ssl_ctx, params->cipher_suites) != MG_SSL_OK) { MG_SET_PTRPTR(err_msg, "Invalid cipher suite list"); return MG_SSL_ERROR; } mbuf_init(&ctx->psk, 0); if (mg_ssl_if_ossl_set_psk(ctx, params->psk_identity, params->psk_key) != MG_SSL_OK) { MG_SET_PTRPTR(err_msg, "Invalid PSK settings"); return MG_SSL_ERROR; } if (!(nc->flags & MG_F_LISTENING) && (ctx->ssl = SSL_new(ctx->ssl_ctx)) == NULL) { MG_SET_PTRPTR(err_msg, "Failed to create SSL session"); return MG_SSL_ERROR; } if (params->server_name != NULL) { #ifdef KR_VERSION SSL_CTX_kr_set_verify_name(ctx->ssl_ctx, params->server_name); #else SSL_set_tlsext_host_name(ctx->ssl, params->server_name); #endif } nc->flags |= MG_F_SSL; return MG_SSL_OK; } static enum mg_ssl_if_result mg_ssl_if_ssl_err(struct mg_connection *nc, int res) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; int err = SSL_get_error(ctx->ssl, res); if (err == SSL_ERROR_WANT_READ) return MG_SSL_WANT_READ; if (err == SSL_ERROR_WANT_WRITE) return MG_SSL_WANT_WRITE; DBG(("%p %p SSL error: %d %d", nc, ctx->ssl_ctx, res, err)); nc->err = err; return MG_SSL_ERROR; } enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; int server_side = (nc->listener != NULL); int res; /* If descriptor is not yet set, do it now. */ if (SSL_get_fd(ctx->ssl) < 0) { if (SSL_set_fd(ctx->ssl, nc->sock) != 1) return MG_SSL_ERROR; } res = server_side ? SSL_accept(ctx->ssl) : SSL_connect(ctx->ssl); if (res != 1) return mg_ssl_if_ssl_err(nc, res); return MG_SSL_OK; } int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t buf_size) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; int n = SSL_read(ctx->ssl, buf, buf_size); DBG(("%p %d -> %d", nc, (int) buf_size, n)); if (n < 0) return mg_ssl_if_ssl_err(nc, n); if (n == 0) nc->flags |= MG_F_CLOSE_IMMEDIATELY; return n; } int mg_ssl_if_write(struct mg_connection *nc, const void *data, size_t len) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; int n = SSL_write(ctx->ssl, data, len); DBG(("%p %d -> %d", nc, (int) len, n)); if (n <= 0) return mg_ssl_if_ssl_err(nc, n); return n; } void mg_ssl_if_conn_close_notify(struct mg_connection *nc) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; if (ctx == NULL) return; SSL_shutdown(ctx->ssl); } void mg_ssl_if_conn_free(struct mg_connection *nc) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; if (ctx == NULL) return; nc->ssl_if_data = NULL; if (ctx->ssl != NULL) SSL_free(ctx->ssl); if (ctx->ssl_ctx != NULL && nc->listener == NULL) SSL_CTX_free(ctx->ssl_ctx); mbuf_free(&ctx->psk); memset(ctx, 0, sizeof(*ctx)); MG_FREE(ctx); } /* * Cipher suite options used for TLS negotiation. * https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_configurations */ static const char mg_s_cipher_list[] = #if defined(MG_SSL_CRYPTO_MODERN) "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:" "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:" "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:" "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:" "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:" "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:" "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:" "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:" "!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK" #elif defined(MG_SSL_CRYPTO_OLD) "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:" "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:" "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:" "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:" "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:" "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:" "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:" "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:" "ECDHE-ECDSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:" "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:DES-CBC3-SHA:" "HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:" "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA" #else /* Default - intermediate. */ "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:" "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:" "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:" "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:" "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:" "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:" "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:" "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:" "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:" "DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:" "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA" #endif ; /* * Default DH params for PFS cipher negotiation. This is a 2048-bit group. * Will be used if none are provided by the user in the certificate file. */ #if !MG_DISABLE_PFS && !defined(KR_VERSION) static const char mg_s_default_dh_params[] = "\ -----BEGIN DH PARAMETERS-----\n\ MIIBCAKCAQEAlvbgD/qh9znWIlGFcV0zdltD7rq8FeShIqIhkQ0C7hYFThrBvF2E\n\ Z9bmgaP+sfQwGpVlv9mtaWjvERbu6mEG7JTkgmVUJrUt/wiRzwTaCXBqZkdUO8Tq\n\ +E6VOEQAilstG90ikN1Tfo+K6+X68XkRUIlgawBTKuvKVwBhuvlqTGerOtnXWnrt\n\ ym//hd3cd5PBYGBix0i7oR4xdghvfR2WLVu0LgdThTBb6XP7gLd19cQ1JuBtAajZ\n\ wMuPn7qlUkEFDIkAZy59/Hue/H2Q2vU/JsvVhHWCQBL4F1ofEAt50il6ZxR1QfFK\n\ 9VGKDC4oOgm9DlxwwBoC2FjqmvQlqVV3kwIBAg==\n\ -----END DH PARAMETERS-----\n"; #endif static enum mg_ssl_if_result mg_use_ca_cert(SSL_CTX *ctx, const char *cert) { if (cert == NULL || strcmp(cert, "*") == 0) { return MG_SSL_OK; } SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0); return SSL_CTX_load_verify_locations(ctx, cert, NULL) == 1 ? MG_SSL_OK : MG_SSL_ERROR; } static enum mg_ssl_if_result mg_use_cert(SSL_CTX *ctx, const char *cert, const char *key, const char **err_msg) { if (key == NULL) key = cert; if (cert == NULL || cert[0] == '\0' || key == NULL || key[0] == '\0') { return MG_SSL_OK; } else if (SSL_CTX_use_certificate_file(ctx, cert, 1) == 0) { MG_SET_PTRPTR(err_msg, "Invalid SSL cert"); return MG_SSL_ERROR; } else if (SSL_CTX_use_PrivateKey_file(ctx, key, 1) == 0) { MG_SET_PTRPTR(err_msg, "Invalid SSL key"); return MG_SSL_ERROR; } else if (SSL_CTX_use_certificate_chain_file(ctx, cert) == 0) { MG_SET_PTRPTR(err_msg, "Invalid CA bundle"); return MG_SSL_ERROR; } else { SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); #if !MG_DISABLE_PFS && !defined(KR_VERSION) BIO *bio = NULL; DH *dh = NULL; /* Try to read DH parameters from the cert/key file. */ bio = BIO_new_file(cert, "r"); if (bio != NULL) { dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL); BIO_free(bio); } /* * If there are no DH params in the file, fall back to hard-coded ones. * Not ideal, but better than nothing. */ if (dh == NULL) { bio = BIO_new_mem_buf((void *) mg_s_default_dh_params, -1); dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL); BIO_free(bio); } if (dh != NULL) { SSL_CTX_set_tmp_dh(ctx, dh); SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE); DH_free(dh); } #if OPENSSL_VERSION_NUMBER > 0x10002000L SSL_CTX_set_ecdh_auto(ctx, 1); #endif #endif } return MG_SSL_OK; } static enum mg_ssl_if_result mg_set_cipher_list(SSL_CTX *ctx, const char *cl) { return (SSL_CTX_set_cipher_list(ctx, cl ? cl : mg_s_cipher_list) == 1 ? MG_SSL_OK : MG_SSL_ERROR); } #if !defined(KR_VERSION) && !defined(LIBRESSL_VERSION_NUMBER) static unsigned int mg_ssl_if_ossl_psk_cb(SSL *ssl, const char *hint, char *identity, unsigned int max_identity_len, unsigned char *psk, unsigned int max_psk_len) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)); size_t key_len = ctx->psk.len - ctx->identity_len - 1; DBG(("hint: '%s'", (hint ? hint : ""))); if (ctx->identity_len + 1 > max_identity_len) { DBG(("identity too long")); return 0; } if (key_len > max_psk_len) { DBG(("key too long")); return 0; } memcpy(identity, ctx->psk.buf, ctx->identity_len + 1); memcpy(psk, ctx->psk.buf + ctx->identity_len + 1, key_len); (void) ssl; return key_len; } static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx, const char *identity, const char *key_str) { unsigned char key[32]; size_t key_len; size_t i = 0; if (identity == NULL && key_str == NULL) return MG_SSL_OK; if (identity == NULL || key_str == NULL) return MG_SSL_ERROR; key_len = strlen(key_str); if (key_len != 32 && key_len != 64) return MG_SSL_ERROR; memset(key, 0, sizeof(key)); key_len = 0; for (i = 0; key_str[i] != '\0'; i++) { unsigned char c; char hc = tolower((int) key_str[i]); if (hc >= '0' && hc <= '9') { c = hc - '0'; } else if (hc >= 'a' && hc <= 'f') { c = hc - 'a' + 0xa; } else { return MG_SSL_ERROR; } key_len = i / 2; key[key_len] <<= 4; key[key_len] |= c; } key_len++; DBG(("identity = '%s', key = (%u)", identity, (unsigned int) key_len)); ctx->identity_len = strlen(identity); mbuf_append(&ctx->psk, identity, ctx->identity_len + 1); mbuf_append(&ctx->psk, key, key_len); SSL_CTX_set_psk_client_callback(ctx->ssl_ctx, mg_ssl_if_ossl_psk_cb); SSL_CTX_set_app_data(ctx->ssl_ctx, ctx); return MG_SSL_OK; } #else static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx, const char *identity, const char *key_str) { (void) ctx; (void) identity; (void) key_str; /* Krypton / LibreSSL does not support PSK. */ return MG_SSL_ERROR; } #endif /* !defined(KR_VERSION) && !defined(LIBRESSL_VERSION_NUMBER) */ const char *mg_set_ssl(struct mg_connection *nc, const char *cert, const char *ca_cert) { const char *err_msg = NULL; struct mg_ssl_if_conn_params params; memset(&params, 0, sizeof(params)); params.cert = cert; params.ca_cert = ca_cert; if (mg_ssl_if_conn_init(nc, &params, &err_msg) != MG_SSL_OK) { return err_msg; } return NULL; } #endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_OPENSSL */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_ssl_if_mbedtls.c" #endif /* * Copyright (c) 2014-2016 Cesanta Software Limited * All rights reserved */ #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_MBEDTLS #include <mbedtls/debug.h> #include <mbedtls/ecp.h> #include <mbedtls/net.h> #include <mbedtls/platform.h> #include <mbedtls/ssl.h> #include <mbedtls/ssl_internal.h> #include <mbedtls/x509_crt.h> #include <mbedtls/version.h> static void mg_ssl_mbed_log(void *ctx, int level, const char *file, int line, const char *str) { enum cs_log_level cs_level; switch (level) { case 1: cs_level = LL_ERROR; break; case 2: cs_level = LL_INFO; break; case 3: cs_level = LL_DEBUG; break; default: cs_level = LL_VERBOSE_DEBUG; } /* mbedTLS passes strings with \n at the end, strip it. */ LOG(cs_level, ("%p %.*s", ctx, (int) (strlen(str) - 1), str)); (void) ctx; (void) str; (void) file; (void) line; (void) cs_level; } struct mg_ssl_if_ctx { mbedtls_ssl_config *conf; mbedtls_ssl_context *ssl; mbedtls_x509_crt *cert; mbedtls_pk_context *key; mbedtls_x509_crt *ca_cert; struct mbuf cipher_suites; size_t saved_len; }; /* Must be provided by the platform. ctx is struct mg_connection. */ extern int mg_ssl_if_mbed_random(void *ctx, unsigned char *buf, size_t len); void mg_ssl_if_init() { LOG(LL_INFO, ("%s", MBEDTLS_VERSION_STRING_FULL)); } enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc, struct mg_connection *lc) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx)); struct mg_ssl_if_ctx *lc_ctx = (struct mg_ssl_if_ctx *) lc->ssl_if_data; nc->ssl_if_data = ctx; if (ctx == NULL || lc_ctx == NULL) return MG_SSL_ERROR; ctx->ssl = (mbedtls_ssl_context *) MG_CALLOC(1, sizeof(*ctx->ssl)); if (mbedtls_ssl_setup(ctx->ssl, lc_ctx->conf) != 0) { return MG_SSL_ERROR; } return MG_SSL_OK; } static enum mg_ssl_if_result mg_use_cert(struct mg_ssl_if_ctx *ctx, const char *cert, const char *key, const char **err_msg); static enum mg_ssl_if_result mg_use_ca_cert(struct mg_ssl_if_ctx *ctx, const char *cert); static enum mg_ssl_if_result mg_set_cipher_list(struct mg_ssl_if_ctx *ctx, const char *ciphers); #ifdef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED static enum mg_ssl_if_result mg_ssl_if_mbed_set_psk(struct mg_ssl_if_ctx *ctx, const char *identity, const char *key); #endif enum mg_ssl_if_result mg_ssl_if_conn_init( struct mg_connection *nc, const struct mg_ssl_if_conn_params *params, const char **err_msg) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx)); DBG(("%p %s,%s,%s", nc, (params->cert ? params->cert : ""), (params->key ? params->key : ""), (params->ca_cert ? params->ca_cert : ""))); if (ctx == NULL) { MG_SET_PTRPTR(err_msg, "Out of memory"); return MG_SSL_ERROR; } nc->ssl_if_data = ctx; ctx->conf = (mbedtls_ssl_config *) MG_CALLOC(1, sizeof(*ctx->conf)); mbuf_init(&ctx->cipher_suites, 0); mbedtls_ssl_config_init(ctx->conf); mbedtls_ssl_conf_dbg(ctx->conf, mg_ssl_mbed_log, nc); if (mbedtls_ssl_config_defaults( ctx->conf, (nc->flags & MG_F_LISTENING ? MBEDTLS_SSL_IS_SERVER : MBEDTLS_SSL_IS_CLIENT), MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT) != 0) { MG_SET_PTRPTR(err_msg, "Failed to init SSL config"); return MG_SSL_ERROR; } /* TLS 1.2 and up */ mbedtls_ssl_conf_min_version(ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3); mbedtls_ssl_conf_rng(ctx->conf, mg_ssl_if_mbed_random, nc); if (params->cert != NULL && mg_use_cert(ctx, params->cert, params->key, err_msg) != MG_SSL_OK) { return MG_SSL_ERROR; } if (params->ca_cert != NULL && mg_use_ca_cert(ctx, params->ca_cert) != MG_SSL_OK) { MG_SET_PTRPTR(err_msg, "Invalid SSL CA cert"); return MG_SSL_ERROR; } if (mg_set_cipher_list(ctx, params->cipher_suites) != MG_SSL_OK) { MG_SET_PTRPTR(err_msg, "Invalid cipher suite list"); return MG_SSL_ERROR; } #ifdef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED if (mg_ssl_if_mbed_set_psk(ctx, params->psk_identity, params->psk_key) != MG_SSL_OK) { MG_SET_PTRPTR(err_msg, "Invalid PSK settings"); return MG_SSL_ERROR; } #endif if (!(nc->flags & MG_F_LISTENING)) { ctx->ssl = (mbedtls_ssl_context *) MG_CALLOC(1, sizeof(*ctx->ssl)); mbedtls_ssl_init(ctx->ssl); if (mbedtls_ssl_setup(ctx->ssl, ctx->conf) != 0) { MG_SET_PTRPTR(err_msg, "Failed to create SSL session"); return MG_SSL_ERROR; } if (params->server_name != NULL && mbedtls_ssl_set_hostname(ctx->ssl, params->server_name) != 0) { return MG_SSL_ERROR; } } #ifdef MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN if (mbedtls_ssl_conf_max_frag_len(ctx->conf, #if MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 512 MBEDTLS_SSL_MAX_FRAG_LEN_512 #elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 1024 MBEDTLS_SSL_MAX_FRAG_LEN_1024 #elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 2048 MBEDTLS_SSL_MAX_FRAG_LEN_2048 #elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 4096 MBEDTLS_SSL_MAX_FRAG_LEN_4096 #else #error Invalid MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN #endif ) != 0) { return MG_SSL_ERROR; } #endif nc->flags |= MG_F_SSL; return MG_SSL_OK; } static int mg_ssl_if_mbed_send(void *ctx, const unsigned char *buf, size_t len) { struct mg_connection *nc = (struct mg_connection *) ctx; int n = nc->iface->vtable->tcp_send(nc, buf, len); if (n > 0) return n; if (n == 0) return MBEDTLS_ERR_SSL_WANT_WRITE; return MBEDTLS_ERR_NET_SEND_FAILED; } static int mg_ssl_if_mbed_recv(void *ctx, unsigned char *buf, size_t len) { struct mg_connection *nc = (struct mg_connection *) ctx; int n = nc->iface->vtable->tcp_recv(nc, buf, len); if (n > 0) return n; if (n == 0) return MBEDTLS_ERR_SSL_WANT_READ; return MBEDTLS_ERR_NET_RECV_FAILED; } static enum mg_ssl_if_result mg_ssl_if_mbed_err(struct mg_connection *nc, int ret) { enum mg_ssl_if_result res = MG_SSL_OK; if (ret == MBEDTLS_ERR_SSL_WANT_READ) { res = MG_SSL_WANT_READ; } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { res = MG_SSL_WANT_WRITE; } else if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { LOG(LL_DEBUG, ("%p TLS connection closed by peer", nc)); nc->flags |= MG_F_CLOSE_IMMEDIATELY; res = MG_SSL_OK; } else { LOG(LL_ERROR, ("%p mbedTLS error: -0x%04x", nc, -ret)); nc->flags |= MG_F_CLOSE_IMMEDIATELY; res = MG_SSL_ERROR; } nc->err = ret; return res; } static void mg_ssl_if_mbed_free_certs_and_keys(struct mg_ssl_if_ctx *ctx) { if (ctx->cert != NULL) { mbedtls_x509_crt_free(ctx->cert); MG_FREE(ctx->cert); ctx->cert = NULL; mbedtls_pk_free(ctx->key); MG_FREE(ctx->key); ctx->key = NULL; } if (ctx->ca_cert != NULL) { mbedtls_ssl_conf_ca_chain(ctx->conf, NULL, NULL); #ifdef MBEDTLS_X509_CA_CHAIN_ON_DISK if (ctx->conf->ca_chain_file != NULL) { MG_FREE((void *) ctx->conf->ca_chain_file); ctx->conf->ca_chain_file = NULL; } #endif mbedtls_x509_crt_free(ctx->ca_cert); MG_FREE(ctx->ca_cert); ctx->ca_cert = NULL; } } enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; int err; /* If bio is not yet set, do it now. */ if (ctx->ssl->p_bio == NULL) { mbedtls_ssl_set_bio(ctx->ssl, nc, mg_ssl_if_mbed_send, mg_ssl_if_mbed_recv, NULL); } err = mbedtls_ssl_handshake(ctx->ssl); if (err != 0) return mg_ssl_if_mbed_err(nc, err); #ifdef MG_SSL_IF_MBEDTLS_FREE_CERTS /* * Free the peer certificate, we don't need it after handshake. * Note that this effectively disables renegotiation. */ mbedtls_x509_crt_free(ctx->ssl->session->peer_cert); mbedtls_free(ctx->ssl->session->peer_cert); ctx->ssl->session->peer_cert = NULL; /* On a client connection we can also free our own and CA certs. */ if (nc->listener == NULL) { if (ctx->conf->key_cert != NULL) { /* Note that this assumes one key_cert entry, which matches our init. */ MG_FREE(ctx->conf->key_cert); ctx->conf->key_cert = NULL; } mbedtls_ssl_conf_ca_chain(ctx->conf, NULL, NULL); mg_ssl_if_mbed_free_certs_and_keys(ctx); } #endif return MG_SSL_OK; } int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t len) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; int n = mbedtls_ssl_read(ctx->ssl, (unsigned char *) buf, len); DBG(("%p %d -> %d", nc, (int) len, n)); if (n < 0) return mg_ssl_if_mbed_err(nc, n); if (n == 0) nc->flags |= MG_F_CLOSE_IMMEDIATELY; return n; } int mg_ssl_if_write(struct mg_connection *nc, const void *buf, size_t len) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; /* Per mbedTLS docs, if write returns WANT_READ or WANT_WRITE, the operation * should be retried with the same data and length. * Here we assume that the data being pushed will remain the same but the * amount may grow between calls so we save the length that was used and * retry. The assumption being that the data itself won't change and won't * be removed. */ size_t l = len; if (ctx->saved_len > 0 && ctx->saved_len < l) l = ctx->saved_len; int n = mbedtls_ssl_write(ctx->ssl, (const unsigned char *) buf, l); DBG(("%p %d,%d,%d -> %d", nc, (int) len, (int) ctx->saved_len, (int) l, n)); if (n < 0) { if (n == MBEDTLS_ERR_SSL_WANT_READ || n == MBEDTLS_ERR_SSL_WANT_WRITE) { ctx->saved_len = len; } return mg_ssl_if_mbed_err(nc, n); } else if (n > 0) { ctx->saved_len = 0; } return n; } void mg_ssl_if_conn_close_notify(struct mg_connection *nc) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; if (ctx == NULL) return; mbedtls_ssl_close_notify(ctx->ssl); } void mg_ssl_if_conn_free(struct mg_connection *nc) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; if (ctx == NULL) return; nc->ssl_if_data = NULL; if (ctx->ssl != NULL) { mbedtls_ssl_free(ctx->ssl); MG_FREE(ctx->ssl); } mg_ssl_if_mbed_free_certs_and_keys(ctx); if (ctx->conf != NULL) { mbedtls_ssl_config_free(ctx->conf); MG_FREE(ctx->conf); } mbuf_free(&ctx->cipher_suites); memset(ctx, 0, sizeof(*ctx)); MG_FREE(ctx); } static enum mg_ssl_if_result mg_use_ca_cert(struct mg_ssl_if_ctx *ctx, const char *ca_cert) { if (ca_cert == NULL || strcmp(ca_cert, "*") == 0) { mbedtls_ssl_conf_authmode(ctx->conf, MBEDTLS_SSL_VERIFY_NONE); return MG_SSL_OK; } ctx->ca_cert = (mbedtls_x509_crt *) MG_CALLOC(1, sizeof(*ctx->ca_cert)); mbedtls_x509_crt_init(ctx->ca_cert); #ifdef MBEDTLS_X509_CA_CHAIN_ON_DISK ca_cert = strdup(ca_cert); mbedtls_ssl_conf_ca_chain_file(ctx->conf, ca_cert, NULL); #else if (mbedtls_x509_crt_parse_file(ctx->ca_cert, ca_cert) != 0) { return MG_SSL_ERROR; } mbedtls_ssl_conf_ca_chain(ctx->conf, ctx->ca_cert, NULL); #endif mbedtls_ssl_conf_authmode(ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED); return MG_SSL_OK; } static enum mg_ssl_if_result mg_use_cert(struct mg_ssl_if_ctx *ctx, const char *cert, const char *key, const char **err_msg) { if (key == NULL) key = cert; if (cert == NULL || cert[0] == '\0' || key == NULL || key[0] == '\0') { return MG_SSL_OK; } ctx->cert = (mbedtls_x509_crt *) MG_CALLOC(1, sizeof(*ctx->cert)); mbedtls_x509_crt_init(ctx->cert); ctx->key = (mbedtls_pk_context *) MG_CALLOC(1, sizeof(*ctx->key)); mbedtls_pk_init(ctx->key); if (mbedtls_x509_crt_parse_file(ctx->cert, cert) != 0) { MG_SET_PTRPTR(err_msg, "Invalid SSL cert"); return MG_SSL_ERROR; } if (mbedtls_pk_parse_keyfile(ctx->key, key, NULL) != 0) { MG_SET_PTRPTR(err_msg, "Invalid SSL key"); return MG_SSL_ERROR; } if (mbedtls_ssl_conf_own_cert(ctx->conf, ctx->cert, ctx->key) != 0) { MG_SET_PTRPTR(err_msg, "Invalid SSL key or cert"); return MG_SSL_ERROR; } return MG_SSL_OK; } static const int mg_s_cipher_list[] = { #if CS_PLATFORM != CS_P_ESP8266 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA, #else /* * ECDHE is way too slow on ESP8266 w/o cryptochip, this sometimes results * in WiFi STA deauths. Use weaker but faster cipher suites. Sad but true. * Disable DHE completely because it's just hopelessly slow. */ MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA, #endif /* CS_PLATFORM != CS_P_ESP8266 */ 0, }; /* * Ciphers can be specified as a colon-separated list of cipher suite names. * These can be found in * https://github.com/ARMmbed/mbedtls/blob/development/library/ssl_ciphersuites.c#L267 * E.g.: TLS-ECDHE-ECDSA-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-256-CCM */ static enum mg_ssl_if_result mg_set_cipher_list(struct mg_ssl_if_ctx *ctx, const char *ciphers) { if (ciphers != NULL) { int l, id; const char *s = ciphers, *e; char tmp[50]; while (s != NULL) { e = strchr(s, ':'); l = (e != NULL ? (e - s) : (int) strlen(s)); strncpy(tmp, s, l); tmp[l] = '\0'; id = mbedtls_ssl_get_ciphersuite_id(tmp); DBG(("%s -> %04x", tmp, id)); if (id != 0) { mbuf_append(&ctx->cipher_suites, &id, sizeof(id)); } s = (e != NULL ? e + 1 : NULL); } if (ctx->cipher_suites.len == 0) return MG_SSL_ERROR; id = 0; mbuf_append(&ctx->cipher_suites, &id, sizeof(id)); mbuf_trim(&ctx->cipher_suites); mbedtls_ssl_conf_ciphersuites(ctx->conf, (const int *) ctx->cipher_suites.buf); } else { mbedtls_ssl_conf_ciphersuites(ctx->conf, mg_s_cipher_list); } return MG_SSL_OK; } #ifdef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED static enum mg_ssl_if_result mg_ssl_if_mbed_set_psk(struct mg_ssl_if_ctx *ctx, const char *identity, const char *key_str) { unsigned char key[32]; size_t key_len; if (identity == NULL && key_str == NULL) return MG_SSL_OK; if (identity == NULL || key_str == NULL) return MG_SSL_ERROR; key_len = strlen(key_str); if (key_len != 32 && key_len != 64) return MG_SSL_ERROR; size_t i = 0; memset(key, 0, sizeof(key)); key_len = 0; for (i = 0; key_str[i] != '\0'; i++) { unsigned char c; char hc = tolower((int) key_str[i]); if (hc >= '0' && hc <= '9') { c = hc - '0'; } else if (hc >= 'a' && hc <= 'f') { c = hc - 'a' + 0xa; } else { return MG_SSL_ERROR; } key_len = i / 2; key[key_len] <<= 4; key[key_len] |= c; } key_len++; DBG(("identity = '%s', key = (%u)", identity, (unsigned int) key_len)); /* mbedTLS makes copies of psk and identity. */ if (mbedtls_ssl_conf_psk(ctx->conf, (const unsigned char *) key, key_len, (const unsigned char *) identity, strlen(identity)) != 0) { return MG_SSL_ERROR; } return MG_SSL_OK; } #endif const char *mg_set_ssl(struct mg_connection *nc, const char *cert, const char *ca_cert) { const char *err_msg = NULL; struct mg_ssl_if_conn_params params; memset(&params, 0, sizeof(params)); params.cert = cert; params.ca_cert = ca_cert; if (mg_ssl_if_conn_init(nc, &params, &err_msg) != MG_SSL_OK) { return err_msg; } return NULL; } /* Lazy RNG. Warning: it would be a bad idea to do this in production! */ #ifdef MG_SSL_MBED_DUMMY_RANDOM int mg_ssl_if_mbed_random(void *ctx, unsigned char *buf, size_t len) { (void) ctx; while (len--) *buf++ = rand(); return 0; } #endif #endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_MBEDTLS */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_uri.c" #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ /* Amalgamated: #include "mg_internal.h" */ /* Amalgamated: #include "mg_uri.h" */ /* * scan string until encountering one of `seps`, keeping track of component * boundaries in `res`. * * `p` will point to the char after the separator or it will be `end`. */ static void parse_uri_component(const char **p, const char *end, const char *seps, struct mg_str *res) { const char *q; res->p = *p; for (; *p < end; (*p)++) { for (q = seps; *q != '\0'; q++) { if (**p == *q) break; } if (*q != '\0') break; } res->len = (*p) - res->p; if (*p < end) (*p)++; } int mg_parse_uri(const struct mg_str uri, struct mg_str *scheme, struct mg_str *user_info, struct mg_str *host, unsigned int *port, struct mg_str *path, struct mg_str *query, struct mg_str *fragment) { struct mg_str rscheme = {0, 0}, ruser_info = {0, 0}, rhost = {0, 0}, rpath = {0, 0}, rquery = {0, 0}, rfragment = {0, 0}; unsigned int rport = 0; enum { P_START, P_SCHEME_OR_PORT, P_USER_INFO, P_HOST, P_PORT, P_REST } state = P_START; const char *p = uri.p, *end = p + uri.len; while (p < end) { switch (state) { case P_START: /* * expecting on of: * - `scheme://xxxx` * - `xxxx:port` * - `[a:b:c]:port` * - `xxxx/path` */ if (*p == '[') { state = P_HOST; break; } for (; p < end; p++) { if (*p == ':') { state = P_SCHEME_OR_PORT; break; } else if (*p == '/') { state = P_REST; break; } } if (state == P_START || state == P_REST) { rhost.p = uri.p; rhost.len = p - uri.p; } break; case P_SCHEME_OR_PORT: if (end - p >= 3 && strncmp(p, "://", 3) == 0) { rscheme.p = uri.p; rscheme.len = p - uri.p; state = P_USER_INFO; p += 3; } else { rhost.p = uri.p; rhost.len = p - uri.p; state = P_PORT; } break; case P_USER_INFO: ruser_info.p = p; for (; p < end; p++) { if (*p == '@' || *p == '[' || *p == '/') { break; } } if (p == end || *p == '/' || *p == '[') { /* backtrack and parse as host */ p = ruser_info.p; } ruser_info.len = p - ruser_info.p; state = P_HOST; break; case P_HOST: if (*p == '@') p++; rhost.p = p; if (*p == '[') { int found = 0; for (; !found && p < end; p++) { found = (*p == ']'); } if (!found) return -1; } else { for (; p < end; p++) { if (*p == ':' || *p == '/') break; } } rhost.len = p - rhost.p; if (p < end) { if (*p == ':') { state = P_PORT; break; } else if (*p == '/') { state = P_REST; break; } } break; case P_PORT: p++; for (; p < end; p++) { if (*p == '/') { state = P_REST; break; } rport *= 10; rport += *p - '0'; } break; case P_REST: /* `p` points to separator. `path` includes the separator */ parse_uri_component(&p, end, "?#", &rpath); if (p < end && *(p - 1) == '?') { parse_uri_component(&p, end, "#", &rquery); } parse_uri_component(&p, end, "", &rfragment); break; } } if (scheme != 0) *scheme = rscheme; if (user_info != 0) *user_info = ruser_info; if (host != 0) *host = rhost; if (port != 0) *port = rport; if (path != 0) *path = rpath; if (query != 0) *query = rquery; if (fragment != 0) *fragment = rfragment; return 0; } /* Normalize the URI path. Remove/resolve "." and "..". */ int mg_normalize_uri_path(const struct mg_str *in, struct mg_str *out) { const char *s = in->p, *se = s + in->len; char *cp = (char *) out->p, *d; if (in->len == 0 || *s != '/') { out->len = 0; return 0; } d = cp; while (s < se) { const char *next = s; struct mg_str component; parse_uri_component(&next, se, "/", &component); if (mg_vcmp(&component, ".") == 0) { /* Yum. */ } else if (mg_vcmp(&component, "..") == 0) { /* Backtrack to previous slash. */ if (d > cp + 1 && *(d - 1) == '/') d--; while (d > cp && *(d - 1) != '/') d--; } else { memmove(d, s, next - s); d += next - s; } s = next; } if (d == cp) *d++ = '/'; out->p = cp; out->len = d - cp; return 1; } int mg_assemble_uri(const struct mg_str *scheme, const struct mg_str *user_info, const struct mg_str *host, unsigned int port, const struct mg_str *path, const struct mg_str *query, const struct mg_str *fragment, int normalize_path, struct mg_str *uri) { int result = -1; struct mbuf out; mbuf_init(&out, 0); if (scheme != NULL && scheme->len > 0) { mbuf_append(&out, scheme->p, scheme->len); mbuf_append(&out, "://", 3); } if (user_info != NULL && user_info->len > 0) { mbuf_append(&out, user_info->p, user_info->len); mbuf_append(&out, "@", 1); } if (host != NULL && host->len > 0) { mbuf_append(&out, host->p, host->len); } if (port != 0) { char port_str[20]; int port_str_len = sprintf(port_str, ":%u", port); mbuf_append(&out, port_str, port_str_len); } if (path != NULL && path->len > 0) { if (normalize_path) { struct mg_str npath = mg_strdup(*path); if (npath.len != path->len) goto out; if (!mg_normalize_uri_path(path, &npath)) { free((void *) npath.p); goto out; } mbuf_append(&out, npath.p, npath.len); free((void *) npath.p); } else { mbuf_append(&out, path->p, path->len); } } else if (normalize_path) { mbuf_append(&out, "/", 1); } if (query != NULL && query->len > 0) { mbuf_append(&out, "?", 1); mbuf_append(&out, query->p, query->len); } if (fragment != NULL && fragment->len > 0) { mbuf_append(&out, "#", 1); mbuf_append(&out, fragment->p, fragment->len); } result = 0; out: if (result == 0) { uri->p = out.buf; uri->len = out.len; } else { mbuf_free(&out); uri->p = NULL; uri->len = 0; } return result; } #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_http.c" #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ #if MG_ENABLE_HTTP /* Amalgamated: #include "common/cs_md5.h" */ /* Amalgamated: #include "mg_internal.h" */ /* Amalgamated: #include "mg_util.h" */ /* altbuf {{{ */ /* * Alternate buffer: fills the client-provided buffer with data; and if it's * not large enough, allocates another buffer (via mbuf), similar to asprintf. */ struct altbuf { struct mbuf m; char *user_buf; size_t len; size_t user_buf_size; }; /* * Initializes altbuf; `buf`, `buf_size` is the client-provided buffer. */ MG_INTERNAL void altbuf_init(struct altbuf *ab, char *buf, size_t buf_size) { mbuf_init(&ab->m, 0); ab->user_buf = buf; ab->user_buf_size = buf_size; ab->len = 0; } /* * Appends a single char to the altbuf. */ MG_INTERNAL void altbuf_append(struct altbuf *ab, char c) { if (ab->len < ab->user_buf_size) { /* The data fits into the original buffer */ ab->user_buf[ab->len++] = c; } else { /* The data can't fit into the original buffer, so write it to mbuf. */ /* * First of all, see if that's the first byte which overflows the original * buffer: if so, copy the existing data from there to a newly allocated * mbuf. */ if (ab->len > 0 && ab->m.len == 0) { mbuf_append(&ab->m, ab->user_buf, ab->len); } mbuf_append(&ab->m, &c, 1); ab->len = ab->m.len; } } /* * Resets any data previously appended to altbuf. */ MG_INTERNAL void altbuf_reset(struct altbuf *ab) { mbuf_free(&ab->m); ab->len = 0; } /* * Returns whether the additional buffer was allocated (and thus the data * is in the mbuf, not the client-provided buffer) */ MG_INTERNAL int altbuf_reallocated(struct altbuf *ab) { return ab->len > ab->user_buf_size; } /* * Returns the actual buffer with data, either the client-provided or a newly * allocated one. If `trim` is non-zero, mbuf-backed buffer is trimmed first. */ MG_INTERNAL char *altbuf_get_buf(struct altbuf *ab, int trim) { if (altbuf_reallocated(ab)) { if (trim) { mbuf_trim(&ab->m); } return ab->m.buf; } else { return ab->user_buf; } } /* }}} */ static const char *mg_version_header = "Mongoose/" MG_VERSION; enum mg_http_proto_data_type { DATA_NONE, DATA_FILE, DATA_PUT }; struct mg_http_proto_data_file { FILE *fp; /* Opened file. */ int64_t cl; /* Content-Length. How many bytes to send. */ int64_t sent; /* How many bytes have been already sent. */ int keepalive; /* Keep connection open after sending. */ enum mg_http_proto_data_type type; }; #if MG_ENABLE_HTTP_CGI struct mg_http_proto_data_cgi { struct mg_connection *cgi_nc; }; #endif struct mg_http_proto_data_chuncked { int64_t body_len; /* How many bytes of chunked body was reassembled. */ }; struct mg_http_endpoint { struct mg_http_endpoint *next; struct mg_str uri_pattern; /* owned */ char *auth_domain; /* owned */ char *auth_file; /* owned */ mg_event_handler_t handler; #if MG_ENABLE_CALLBACK_USERDATA void *user_data; #endif }; enum mg_http_multipart_stream_state { MPS_BEGIN, MPS_WAITING_FOR_BOUNDARY, MPS_WAITING_FOR_CHUNK, MPS_GOT_BOUNDARY, MPS_FINALIZE, MPS_FINISHED }; struct mg_http_multipart_stream { const char *boundary; int boundary_len; const char *var_name; const char *file_name; void *user_data; enum mg_http_multipart_stream_state state; int processing_part; int data_avail; }; struct mg_reverse_proxy_data { struct mg_connection *linked_conn; }; struct mg_ws_proto_data { /* * Defragmented size of the frame so far. * * First byte of nc->recv_mbuf.buf is an op, the rest of the data is * defragmented data. */ size_t reass_len; }; struct mg_http_proto_data { #if MG_ENABLE_FILESYSTEM struct mg_http_proto_data_file file; #endif #if MG_ENABLE_HTTP_CGI struct mg_http_proto_data_cgi cgi; #endif #if MG_ENABLE_HTTP_STREAMING_MULTIPART struct mg_http_multipart_stream mp_stream; #endif #if MG_ENABLE_HTTP_WEBSOCKET struct mg_ws_proto_data ws_data; #endif struct mg_http_proto_data_chuncked chunk; struct mg_http_endpoint *endpoints; mg_event_handler_t endpoint_handler; struct mg_reverse_proxy_data reverse_proxy_data; size_t rcvd; /* How many bytes we have received. */ }; static void mg_http_proto_data_destructor(void *proto_data); struct mg_connection *mg_connect_http_base( struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), struct mg_connect_opts opts, const char *scheme1, const char *scheme2, const char *scheme_ssl1, const char *scheme_ssl2, const char *url, struct mg_str *path, struct mg_str *user_info, struct mg_str *host); MG_INTERNAL struct mg_http_proto_data *mg_http_create_proto_data( struct mg_connection *c) { /* If we have proto data from previous connection, flush it. */ if (c->proto_data != NULL) { void *pd = c->proto_data; c->proto_data = NULL; mg_http_proto_data_destructor(pd); } c->proto_data = MG_CALLOC(1, sizeof(struct mg_http_proto_data)); c->proto_data_destructor = mg_http_proto_data_destructor; return (struct mg_http_proto_data *) c->proto_data; } static struct mg_http_proto_data *mg_http_get_proto_data( struct mg_connection *c) { return (struct mg_http_proto_data *) c->proto_data; } #if MG_ENABLE_HTTP_STREAMING_MULTIPART static void mg_http_free_proto_data_mp_stream( struct mg_http_multipart_stream *mp) { MG_FREE((void *) mp->boundary); MG_FREE((void *) mp->var_name); MG_FREE((void *) mp->file_name); memset(mp, 0, sizeof(*mp)); } #endif #if MG_ENABLE_FILESYSTEM static void mg_http_free_proto_data_file(struct mg_http_proto_data_file *d) { if (d != NULL) { if (d->fp != NULL) { fclose(d->fp); } memset(d, 0, sizeof(struct mg_http_proto_data_file)); } } #endif static void mg_http_free_proto_data_endpoints(struct mg_http_endpoint **ep) { struct mg_http_endpoint *current = *ep; while (current != NULL) { struct mg_http_endpoint *tmp = current->next; MG_FREE((void *) current->uri_pattern.p); MG_FREE((void *) current->auth_domain); MG_FREE((void *) current->auth_file); MG_FREE(current); current = tmp; } ep = NULL; } static void mg_http_free_reverse_proxy_data(struct mg_reverse_proxy_data *rpd) { if (rpd->linked_conn != NULL) { /* * Connection has linked one, we have to unlink & close it * since _this_ connection is going to die and * it doesn't make sense to keep another one */ struct mg_http_proto_data *pd = mg_http_get_proto_data(rpd->linked_conn); if (pd->reverse_proxy_data.linked_conn != NULL) { pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE; pd->reverse_proxy_data.linked_conn = NULL; } rpd->linked_conn = NULL; } } static void mg_http_proto_data_destructor(void *proto_data) { struct mg_http_proto_data *pd = (struct mg_http_proto_data *) proto_data; #if MG_ENABLE_FILESYSTEM mg_http_free_proto_data_file(&pd->file); #endif #if MG_ENABLE_HTTP_CGI mg_http_free_proto_data_cgi(&pd->cgi); #endif #if MG_ENABLE_HTTP_STREAMING_MULTIPART mg_http_free_proto_data_mp_stream(&pd->mp_stream); #endif mg_http_free_proto_data_endpoints(&pd->endpoints); mg_http_free_reverse_proxy_data(&pd->reverse_proxy_data); MG_FREE(proto_data); } #if MG_ENABLE_FILESYSTEM #define MIME_ENTRY(_ext, _type) \ { _ext, sizeof(_ext) - 1, _type } static const struct { const char *extension; size_t ext_len; const char *mime_type; } mg_static_builtin_mime_types[] = { MIME_ENTRY("html", "text/html"), MIME_ENTRY("html", "text/html"), MIME_ENTRY("htm", "text/html"), MIME_ENTRY("shtm", "text/html"), MIME_ENTRY("shtml", "text/html"), MIME_ENTRY("css", "text/css"), MIME_ENTRY("js", "application/x-javascript"), MIME_ENTRY("ico", "image/x-icon"), MIME_ENTRY("gif", "image/gif"), MIME_ENTRY("jpg", "image/jpeg"), MIME_ENTRY("jpeg", "image/jpeg"), MIME_ENTRY("png", "image/png"), MIME_ENTRY("svg", "image/svg+xml"), MIME_ENTRY("txt", "text/plain"), MIME_ENTRY("torrent", "application/x-bittorrent"), MIME_ENTRY("wav", "audio/x-wav"), MIME_ENTRY("mp3", "audio/x-mp3"), MIME_ENTRY("mid", "audio/mid"), MIME_ENTRY("m3u", "audio/x-mpegurl"), MIME_ENTRY("ogg", "application/ogg"), MIME_ENTRY("ram", "audio/x-pn-realaudio"), MIME_ENTRY("xml", "text/xml"), MIME_ENTRY("ttf", "application/x-font-ttf"), MIME_ENTRY("json", "application/json"), MIME_ENTRY("xslt", "application/xml"), MIME_ENTRY("xsl", "application/xml"), MIME_ENTRY("ra", "audio/x-pn-realaudio"), MIME_ENTRY("doc", "application/msword"), MIME_ENTRY("exe", "application/octet-stream"), MIME_ENTRY("zip", "application/x-zip-compressed"), MIME_ENTRY("xls", "application/excel"), MIME_ENTRY("tgz", "application/x-tar-gz"), MIME_ENTRY("tar", "application/x-tar"), MIME_ENTRY("gz", "application/x-gunzip"), MIME_ENTRY("arj", "application/x-arj-compressed"), MIME_ENTRY("rar", "application/x-rar-compressed"), MIME_ENTRY("rtf", "application/rtf"), MIME_ENTRY("pdf", "application/pdf"), MIME_ENTRY("swf", "application/x-shockwave-flash"), MIME_ENTRY("mpg", "video/mpeg"), MIME_ENTRY("webm", "video/webm"), MIME_ENTRY("mpeg", "video/mpeg"), MIME_ENTRY("mov", "video/quicktime"), MIME_ENTRY("mp4", "video/mp4"), MIME_ENTRY("m4v", "video/x-m4v"), MIME_ENTRY("asf", "video/x-ms-asf"), MIME_ENTRY("avi", "video/x-msvideo"), MIME_ENTRY("bmp", "image/bmp"), {NULL, 0, NULL}}; static struct mg_str mg_get_mime_type(const char *path, const char *dflt, const struct mg_serve_http_opts *opts) { const char *ext, *overrides; size_t i, path_len; struct mg_str r, k, v; path_len = strlen(path); overrides = opts->custom_mime_types; while ((overrides = mg_next_comma_list_entry(overrides, &k, &v)) != NULL) { ext = path + (path_len - k.len); if (path_len > k.len && mg_vcasecmp(&k, ext) == 0) { return v; } } for (i = 0; mg_static_builtin_mime_types[i].extension != NULL; i++) { ext = path + (path_len - mg_static_builtin_mime_types[i].ext_len); if (path_len > mg_static_builtin_mime_types[i].ext_len && ext[-1] == '.' && mg_casecmp(ext, mg_static_builtin_mime_types[i].extension) == 0) { r.p = mg_static_builtin_mime_types[i].mime_type; r.len = strlen(r.p); return r; } } r.p = dflt; r.len = strlen(r.p); return r; } #endif /* * Check whether full request is buffered. Return: * -1 if request is malformed * 0 if request is not yet fully buffered * >0 actual request length, including last \r\n\r\n */ static int mg_http_get_request_len(const char *s, int buf_len) { const unsigned char *buf = (unsigned char *) s; int i; for (i = 0; i < buf_len; i++) { if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) { return -1; } else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') { return i + 2; } else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' && buf[i + 2] == '\n') { return i + 3; } } return 0; } static const char *mg_http_parse_headers(const char *s, const char *end, int len, struct http_message *req) { int i = 0; while (i < (int) ARRAY_SIZE(req->header_names) - 1) { struct mg_str *k = &req->header_names[i], *v = &req->header_values[i]; s = mg_skip(s, end, ": ", k); s = mg_skip(s, end, "\r\n", v); while (v->len > 0 && v->p[v->len - 1] == ' ') { v->len--; /* Trim trailing spaces in header value */ } /* * If header value is empty - skip it and go to next (if any). * NOTE: Do not add it to headers_values because such addition changes API * behaviour */ if (k->len != 0 && v->len == 0) { continue; } if (k->len == 0 || v->len == 0) { k->p = v->p = NULL; k->len = v->len = 0; break; } if (!mg_ncasecmp(k->p, "Content-Length", 14)) { req->body.len = (size_t) to64(v->p); req->message.len = len + req->body.len; } i++; } return s; } int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req) { const char *end, *qs; int len = mg_http_get_request_len(s, n); if (len <= 0) return len; memset(hm, 0, sizeof(*hm)); hm->message.p = s; hm->body.p = s + len; hm->message.len = hm->body.len = (size_t) ~0; end = s + len; /* Request is fully buffered. Skip leading whitespaces. */ while (s < end && isspace(*(unsigned char *) s)) s++; if (is_req) { /* Parse request line: method, URI, proto */ s = mg_skip(s, end, " ", &hm->method); s = mg_skip(s, end, " ", &hm->uri); s = mg_skip(s, end, "\r\n", &hm->proto); if (hm->uri.p <= hm->method.p || hm->proto.p <= hm->uri.p) return -1; /* If URI contains '?' character, initialize query_string */ if ((qs = (char *) memchr(hm->uri.p, '?', hm->uri.len)) != NULL) { hm->query_string.p = qs + 1; hm->query_string.len = &hm->uri.p[hm->uri.len] - (qs + 1); hm->uri.len = qs - hm->uri.p; } } else { s = mg_skip(s, end, " ", &hm->proto); if (end - s < 4 || s[3] != ' ') return -1; hm->resp_code = atoi(s); if (hm->resp_code < 100 || hm->resp_code >= 600) return -1; s += 4; s = mg_skip(s, end, "\r\n", &hm->resp_status_msg); } s = mg_http_parse_headers(s, end, len, hm); /* * mg_parse_http() is used to parse both HTTP requests and HTTP * responses. If HTTP response does not have Content-Length set, then * body is read until socket is closed, i.e. body.len is infinite (~0). * * For HTTP requests though, according to * http://tools.ietf.org/html/rfc7231#section-8.1.3, * only POST and PUT methods have defined body semantics. * Therefore, if Content-Length is not specified and methods are * not one of PUT or POST, set body length to 0. * * So, * if it is HTTP request, and Content-Length is not set, * and method is not (PUT or POST) then reset body length to zero. */ if (hm->body.len == (size_t) ~0 && is_req && mg_vcasecmp(&hm->method, "PUT") != 0 && mg_vcasecmp(&hm->method, "POST") != 0) { hm->body.len = 0; hm->message.len = len; } return len; } struct mg_str *mg_get_http_header(struct http_message *hm, const char *name) { size_t i, len = strlen(name); for (i = 0; hm->header_names[i].len > 0; i++) { struct mg_str *h = &hm->header_names[i], *v = &hm->header_values[i]; if (h->p != NULL && h->len == len && !mg_ncasecmp(h->p, name, len)) return v; } return NULL; } #if MG_ENABLE_FILESYSTEM static void mg_http_transfer_file_data(struct mg_connection *nc) { struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); char buf[MG_MAX_HTTP_SEND_MBUF]; size_t n = 0, to_read = 0, left = (size_t)(pd->file.cl - pd->file.sent); if (pd->file.type == DATA_FILE) { struct mbuf *io = &nc->send_mbuf; if (io->len >= MG_MAX_HTTP_SEND_MBUF) { to_read = 0; } else { to_read = MG_MAX_HTTP_SEND_MBUF - io->len; } if (to_read > left) { to_read = left; } if (to_read > 0) { n = mg_fread(buf, 1, to_read, pd->file.fp); if (n > 0) { mg_send(nc, buf, n); pd->file.sent += n; DBG(("%p sent %d (total %d)", nc, (int) n, (int) pd->file.sent)); } } else { /* Rate-limited */ } if (pd->file.sent >= pd->file.cl) { LOG(LL_DEBUG, ("%p done, %d bytes, ka %d", nc, (int) pd->file.sent, pd->file.keepalive)); if (!pd->file.keepalive) nc->flags |= MG_F_SEND_AND_CLOSE; mg_http_free_proto_data_file(&pd->file); } } else if (pd->file.type == DATA_PUT) { struct mbuf *io = &nc->recv_mbuf; size_t to_write = left <= 0 ? 0 : left < io->len ? (size_t) left : io->len; size_t n = mg_fwrite(io->buf, 1, to_write, pd->file.fp); if (n > 0) { mbuf_remove(io, n); pd->file.sent += n; } if (n == 0 || pd->file.sent >= pd->file.cl) { if (!pd->file.keepalive) nc->flags |= MG_F_SEND_AND_CLOSE; mg_http_free_proto_data_file(&pd->file); } } #if MG_ENABLE_HTTP_CGI else if (pd->cgi.cgi_nc != NULL) { /* This is POST data that needs to be forwarded to the CGI process */ if (pd->cgi.cgi_nc != NULL) { mg_forward(nc, pd->cgi.cgi_nc); } else { nc->flags |= MG_F_SEND_AND_CLOSE; } } #endif } #endif /* MG_ENABLE_FILESYSTEM */ /* * Parse chunked-encoded buffer. Return 0 if the buffer is not encoded, or * if it's incomplete. If the chunk is fully buffered, return total number of * bytes in a chunk, and store data in `data`, `data_len`. */ static size_t mg_http_parse_chunk(char *buf, size_t len, char **chunk_data, size_t *chunk_len) { unsigned char *s = (unsigned char *) buf; size_t n = 0; /* scanned chunk length */ size_t i = 0; /* index in s */ /* Scan chunk length. That should be a hexadecimal number. */ while (i < len && isxdigit(s[i])) { n *= 16; n += (s[i] >= '0' && s[i] <= '9') ? s[i] - '0' : tolower(s[i]) - 'a' + 10; i++; if (i > 6) { /* Chunk size is unreasonable. */ return 0; } } /* Skip new line */ if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') { return 0; } i += 2; /* Record where the data is */ *chunk_data = (char *) s + i; *chunk_len = n; /* Skip data */ i += n; /* Skip new line */ if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') { return 0; } return i + 2; } MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc, struct http_message *hm, char *buf, size_t blen) { struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); char *data; size_t i, n, data_len, body_len, zero_chunk_received = 0; /* Find out piece of received data that is not yet reassembled */ body_len = (size_t) pd->chunk.body_len; assert(blen >= body_len); /* Traverse all fully buffered chunks */ for (i = body_len; (n = mg_http_parse_chunk(buf + i, blen - i, &data, &data_len)) > 0; i += n) { /* Collapse chunk data to the rest of HTTP body */ memmove(buf + body_len, data, data_len); body_len += data_len; hm->body.len = body_len; if (data_len == 0) { zero_chunk_received = 1; i += n; break; } } if (i > body_len) { /* Shift unparsed content to the parsed body */ assert(i <= blen); memmove(buf + body_len, buf + i, blen - i); memset(buf + body_len + blen - i, 0, i - body_len); nc->recv_mbuf.len -= i - body_len; pd->chunk.body_len = body_len; /* Send MG_EV_HTTP_CHUNK event */ nc->flags &= ~MG_F_DELETE_CHUNK; mg_call(nc, nc->handler, nc->user_data, MG_EV_HTTP_CHUNK, hm); /* Delete processed data if user set MG_F_DELETE_CHUNK flag */ if (nc->flags & MG_F_DELETE_CHUNK) { memset(buf, 0, body_len); memmove(buf, buf + body_len, blen - i); nc->recv_mbuf.len -= body_len; hm->body.len = 0; pd->chunk.body_len = 0; } if (zero_chunk_received) { /* Total message size is len(body) + len(headers) */ hm->message.len = (size_t) pd->chunk.body_len + blen - i + (hm->body.p - hm->message.p); } } return body_len; } struct mg_http_endpoint *mg_http_get_endpoint_handler(struct mg_connection *nc, struct mg_str *uri_path) { struct mg_http_proto_data *pd; struct mg_http_endpoint *ret = NULL; int matched, matched_max = 0; struct mg_http_endpoint *ep; if (nc == NULL) return NULL; pd = mg_http_get_proto_data(nc); if (pd == NULL) return NULL; ep = pd->endpoints; while (ep != NULL) { if ((matched = mg_match_prefix_n(ep->uri_pattern, *uri_path)) > 0) { if (matched > matched_max) { /* Looking for the longest suitable handler */ ret = ep; matched_max = matched; } } ep = ep->next; } return ret; } #if MG_ENABLE_HTTP_STREAMING_MULTIPART static void mg_http_multipart_continue(struct mg_connection *nc); static void mg_http_multipart_begin(struct mg_connection *nc, struct http_message *hm, int req_len); #endif static void mg_http_call_endpoint_handler(struct mg_connection *nc, int ev, struct http_message *hm); static void deliver_chunk(struct mg_connection *c, struct http_message *hm, int req_len) { /* Incomplete message received. Send MG_EV_HTTP_CHUNK event */ hm->body.len = c->recv_mbuf.len - req_len; c->flags &= ~MG_F_DELETE_CHUNK; mg_call(c, c->handler, c->user_data, MG_EV_HTTP_CHUNK, hm); /* Delete processed data if user set MG_F_DELETE_CHUNK flag */ if (c->flags & MG_F_DELETE_CHUNK) c->recv_mbuf.len = req_len; } /* * lx106 compiler has a bug (TODO(mkm) report and insert tracking bug here) * If a big structure is declared in a big function, lx106 gcc will make it * even bigger (round up to 4k, from 700 bytes of actual size). */ #ifdef __xtensa__ static void mg_http_handler2(struct mg_connection *nc, int ev, void *ev_data MG_UD_ARG(void *user_data), struct http_message *hm) __attribute__((noinline)); void mg_http_handler(struct mg_connection *nc, int ev, void *ev_data MG_UD_ARG(void *user_data)) { struct http_message hm; mg_http_handler2(nc, ev, ev_data MG_UD_ARG(user_data), &hm); } static void mg_http_handler2(struct mg_connection *nc, int ev, void *ev_data MG_UD_ARG(void *user_data), struct http_message *hm) { #else /* !__XTENSA__ */ void mg_http_handler(struct mg_connection *nc, int ev, void *ev_data MG_UD_ARG(void *user_data)) { struct http_message shm, *hm = &shm; #endif /* __XTENSA__ */ struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); struct mbuf *io = &nc->recv_mbuf; int req_len; const int is_req = (nc->listener != NULL); #if MG_ENABLE_HTTP_WEBSOCKET struct mg_str *vec; #endif if (ev == MG_EV_CLOSE) { #if MG_ENABLE_HTTP_CGI /* Close associated CGI forwarder connection */ if (pd != NULL && pd->cgi.cgi_nc != NULL) { pd->cgi.cgi_nc->user_data = NULL; pd->cgi.cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY; } #endif #if MG_ENABLE_HTTP_STREAMING_MULTIPART if (pd != NULL && pd->mp_stream.boundary != NULL) { /* * Multipart message is in progress, but connection is closed. * Finish part and request with an error flag. */ struct mg_http_multipart_part mp; memset(&mp, 0, sizeof(mp)); mp.status = -1; mp.var_name = pd->mp_stream.var_name; mp.file_name = pd->mp_stream.file_name; mg_call(nc, (pd->endpoint_handler ? pd->endpoint_handler : nc->handler), nc->user_data, MG_EV_HTTP_PART_END, &mp); mp.var_name = NULL; mp.file_name = NULL; mg_call(nc, (pd->endpoint_handler ? pd->endpoint_handler : nc->handler), nc->user_data, MG_EV_HTTP_MULTIPART_REQUEST_END, &mp); } else #endif if (io->len > 0 && (req_len = mg_parse_http(io->buf, io->len, hm, is_req)) > 0) { /* * For HTTP messages without Content-Length, always send HTTP message * before MG_EV_CLOSE message. */ int ev2 = is_req ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY; hm->message.len = io->len; hm->body.len = io->buf + io->len - hm->body.p; deliver_chunk(nc, hm, req_len); mg_http_call_endpoint_handler(nc, ev2, hm); } if (pd != NULL && pd->endpoint_handler != NULL && pd->endpoint_handler != nc->handler) { mg_call(nc, pd->endpoint_handler, nc->user_data, ev, NULL); } } #if MG_ENABLE_FILESYSTEM if (pd != NULL && pd->file.fp != NULL) { mg_http_transfer_file_data(nc); } #endif mg_call(nc, nc->handler, nc->user_data, ev, ev_data); #if MG_ENABLE_HTTP_STREAMING_MULTIPART if (pd != NULL && pd->mp_stream.boundary != NULL && (ev == MG_EV_RECV || ev == MG_EV_POLL)) { if (ev == MG_EV_RECV) { pd->rcvd += *(int *) ev_data; mg_http_multipart_continue(nc); } else if (pd->mp_stream.data_avail) { /* Try re-delivering the data. */ mg_http_multipart_continue(nc); } return; } #endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */ if (ev == MG_EV_RECV) { struct mg_str *s; again: req_len = mg_parse_http(io->buf, io->len, hm, is_req); if (req_len > 0) { /* New request - new proto data */ pd = mg_http_create_proto_data(nc); pd->rcvd = io->len; } if (req_len > 0 && (s = mg_get_http_header(hm, "Transfer-Encoding")) != NULL && mg_vcasecmp(s, "chunked") == 0) { mg_handle_chunked(nc, hm, io->buf + req_len, io->len - req_len); } #if MG_ENABLE_HTTP_STREAMING_MULTIPART if (req_len > 0 && (s = mg_get_http_header(hm, "Content-Type")) != NULL && s->len >= 9 && strncmp(s->p, "multipart", 9) == 0) { mg_http_multipart_begin(nc, hm, req_len); mg_http_multipart_continue(nc); return; } #endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */ /* TODO(alashkin): refactor this ifelseifelseifelseifelse */ if ((req_len < 0 || (req_len == 0 && io->len >= MG_MAX_HTTP_REQUEST_SIZE))) { DBG(("invalid request")); nc->flags |= MG_F_CLOSE_IMMEDIATELY; } else if (req_len == 0) { /* Do nothing, request is not yet fully buffered */ } #if MG_ENABLE_HTTP_WEBSOCKET else if (nc->listener == NULL && (nc->flags & MG_F_IS_WEBSOCKET)) { /* We're websocket client, got handshake response from server. */ DBG(("%p WebSocket upgrade code %d", nc, hm->resp_code)); if (hm->resp_code == 101 && mg_get_http_header(hm, "Sec-WebSocket-Accept")) { /* TODO(lsm): check the validity of accept Sec-WebSocket-Accept */ mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_DONE, hm); mbuf_remove(io, req_len); nc->proto_handler = mg_ws_handler; mg_ws_handler(nc, MG_EV_RECV, ev_data MG_UD_ARG(user_data)); } else { mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_DONE, hm); nc->flags |= MG_F_CLOSE_IMMEDIATELY; mbuf_remove(io, req_len); } } else if (nc->listener != NULL && (vec = mg_get_http_header(hm, "Sec-WebSocket-Key")) != NULL) { struct mg_http_endpoint *ep; /* This is a websocket request. Switch protocol handlers. */ mbuf_remove(io, req_len); nc->proto_handler = mg_ws_handler; nc->flags |= MG_F_IS_WEBSOCKET; /* * If we have a handler set up with mg_register_http_endpoint(), * deliver subsequent websocket events to this handler after the * protocol switch. */ ep = mg_http_get_endpoint_handler(nc->listener, &hm->uri); if (ep != NULL) { nc->handler = ep->handler; #if MG_ENABLE_CALLBACK_USERDATA nc->user_data = ep->user_data; #endif } /* Send handshake */ mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_REQUEST, hm); if (!(nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_SEND_AND_CLOSE))) { if (nc->send_mbuf.len == 0) { mg_ws_handshake(nc, vec, hm); } mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_DONE, hm); mg_ws_handler(nc, MG_EV_RECV, ev_data MG_UD_ARG(user_data)); } } #endif /* MG_ENABLE_HTTP_WEBSOCKET */ else if (hm->message.len > pd->rcvd) { /* Not yet received all HTTP body, deliver MG_EV_HTTP_CHUNK */ deliver_chunk(nc, hm, req_len); if (nc->recv_mbuf_limit > 0 && nc->recv_mbuf.len >= nc->recv_mbuf_limit) { LOG(LL_ERROR, ("%p recv buffer (%lu bytes) exceeds the limit " "%lu bytes, and not drained, closing", nc, (unsigned long) nc->recv_mbuf.len, (unsigned long) nc->recv_mbuf_limit)); nc->flags |= MG_F_CLOSE_IMMEDIATELY; } } else { /* We did receive all HTTP body. */ int request_done = 1; int trigger_ev = nc->listener ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY; char addr[32]; mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT); DBG(("%p %s %.*s %.*s", nc, addr, (int) hm->method.len, hm->method.p, (int) hm->uri.len, hm->uri.p)); deliver_chunk(nc, hm, req_len); /* Whole HTTP message is fully buffered, call event handler */ mg_http_call_endpoint_handler(nc, trigger_ev, hm); mbuf_remove(io, hm->message.len); pd->rcvd -= hm->message.len; #if MG_ENABLE_FILESYSTEM /* We don't have a generic mechanism of communicating that we are done * responding to a request (should probably add one). But if we are * serving * a file, we are definitely not done. */ if (pd->file.fp != NULL) request_done = 0; #endif #if MG_ENABLE_HTTP_CGI /* If this is a CGI request, we are not done either. */ if (pd->cgi.cgi_nc != NULL) request_done = 0; #endif if (request_done && io->len > 0) goto again; } } } static size_t mg_get_line_len(const char *buf, size_t buf_len) { size_t len = 0; while (len < buf_len && buf[len] != '\n') len++; return len == buf_len ? 0 : len + 1; } #if MG_ENABLE_HTTP_STREAMING_MULTIPART static void mg_http_multipart_begin(struct mg_connection *nc, struct http_message *hm, int req_len) { struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); struct mg_str *ct; struct mbuf *io = &nc->recv_mbuf; char boundary_buf[100]; char *boundary = boundary_buf; int boundary_len; ct = mg_get_http_header(hm, "Content-Type"); if (ct == NULL) { /* We need more data - or it isn't multipart mesage */ goto exit_mp; } /* Content-type should start with "multipart" */ if (ct->len < 9 || strncmp(ct->p, "multipart", 9) != 0) { goto exit_mp; } boundary_len = mg_http_parse_header2(ct, "boundary", &boundary, sizeof(boundary_buf)); if (boundary_len == 0) { /* * Content type is multipart, but there is no boundary, * probably malformed request */ nc->flags = MG_F_CLOSE_IMMEDIATELY; DBG(("invalid request")); goto exit_mp; } /* If we reach this place - that is multipart request */ if (pd->mp_stream.boundary != NULL) { /* * Another streaming request was in progress, * looks like protocol error */ nc->flags |= MG_F_CLOSE_IMMEDIATELY; } else { struct mg_http_endpoint *ep = NULL; pd->mp_stream.state = MPS_BEGIN; pd->mp_stream.boundary = strdup(boundary); pd->mp_stream.boundary_len = strlen(boundary); pd->mp_stream.var_name = pd->mp_stream.file_name = NULL; pd->endpoint_handler = nc->handler; ep = mg_http_get_endpoint_handler(nc->listener, &hm->uri); if (ep != NULL) { pd->endpoint_handler = ep->handler; } mg_http_call_endpoint_handler(nc, MG_EV_HTTP_MULTIPART_REQUEST, hm); mbuf_remove(io, req_len); } exit_mp: if (boundary != boundary_buf) MG_FREE(boundary); } #define CONTENT_DISPOSITION "Content-Disposition: " static size_t mg_http_multipart_call_handler(struct mg_connection *c, int ev, const char *data, size_t data_len) { struct mg_http_multipart_part mp; struct mg_http_proto_data *pd = mg_http_get_proto_data(c); memset(&mp, 0, sizeof(mp)); mp.var_name = pd->mp_stream.var_name; mp.file_name = pd->mp_stream.file_name; mp.user_data = pd->mp_stream.user_data; mp.data.p = data; mp.data.len = data_len; mp.num_data_consumed = data_len; mg_call(c, pd->endpoint_handler, c->user_data, ev, &mp); pd->mp_stream.user_data = mp.user_data; pd->mp_stream.data_avail = (mp.num_data_consumed != data_len); return mp.num_data_consumed; } static int mg_http_multipart_finalize(struct mg_connection *c) { struct mg_http_proto_data *pd = mg_http_get_proto_data(c); mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_END, NULL, 0); MG_FREE((void *) pd->mp_stream.file_name); pd->mp_stream.file_name = NULL; MG_FREE((void *) pd->mp_stream.var_name); pd->mp_stream.var_name = NULL; mg_http_multipart_call_handler(c, MG_EV_HTTP_MULTIPART_REQUEST_END, NULL, 0); mg_http_free_proto_data_mp_stream(&pd->mp_stream); pd->mp_stream.state = MPS_FINISHED; return 1; } static int mg_http_multipart_wait_for_boundary(struct mg_connection *c) { const char *boundary; struct mbuf *io = &c->recv_mbuf; struct mg_http_proto_data *pd = mg_http_get_proto_data(c); if (pd->mp_stream.boundary == NULL) { pd->mp_stream.state = MPS_FINALIZE; DBG(("Invalid request: boundary not initialized")); return 0; } if ((int) io->len < pd->mp_stream.boundary_len + 2) { return 0; } boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len); if (boundary != NULL) { const char *boundary_end = (boundary + pd->mp_stream.boundary_len); if (io->len - (boundary_end - io->buf) < 4) { return 0; } if (strncmp(boundary_end, "--\r\n", 4) == 0) { pd->mp_stream.state = MPS_FINALIZE; mbuf_remove(io, (boundary_end - io->buf) + 4); } else { pd->mp_stream.state = MPS_GOT_BOUNDARY; } } else { return 0; } return 1; } static void mg_http_parse_header_internal(struct mg_str *hdr, const char *var_name, struct altbuf *ab); static int mg_http_multipart_process_boundary(struct mg_connection *c) { int data_size; const char *boundary, *block_begin; struct mbuf *io = &c->recv_mbuf; struct mg_http_proto_data *pd = mg_http_get_proto_data(c); struct altbuf ab_file_name, ab_var_name; int line_len; boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len); block_begin = boundary + pd->mp_stream.boundary_len + 2; data_size = io->len - (block_begin - io->buf); altbuf_init(&ab_file_name, NULL, 0); altbuf_init(&ab_var_name, NULL, 0); while (data_size > 0 && (line_len = mg_get_line_len(block_begin, data_size)) != 0) { if (line_len > (int) sizeof(CONTENT_DISPOSITION) && mg_ncasecmp(block_begin, CONTENT_DISPOSITION, sizeof(CONTENT_DISPOSITION) - 1) == 0) { struct mg_str header; header.p = block_begin + sizeof(CONTENT_DISPOSITION) - 1; header.len = line_len - sizeof(CONTENT_DISPOSITION) - 1; altbuf_reset(&ab_var_name); mg_http_parse_header_internal(&header, "name", &ab_var_name); altbuf_reset(&ab_file_name); mg_http_parse_header_internal(&header, "filename", &ab_file_name); block_begin += line_len; data_size -= line_len; continue; } if (line_len == 2 && mg_ncasecmp(block_begin, "\r\n", 2) == 0) { mbuf_remove(io, block_begin - io->buf + 2); if (pd->mp_stream.processing_part != 0) { mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_END, NULL, 0); } /* Reserve 2 bytes for "\r\n" in file_name and var_name */ altbuf_append(&ab_file_name, '\0'); altbuf_append(&ab_file_name, '\0'); altbuf_append(&ab_var_name, '\0'); altbuf_append(&ab_var_name, '\0'); MG_FREE((void *) pd->mp_stream.file_name); pd->mp_stream.file_name = altbuf_get_buf(&ab_file_name, 1 /* trim */); MG_FREE((void *) pd->mp_stream.var_name); pd->mp_stream.var_name = altbuf_get_buf(&ab_var_name, 1 /* trim */); mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_BEGIN, NULL, 0); pd->mp_stream.state = MPS_WAITING_FOR_CHUNK; pd->mp_stream.processing_part++; return 1; } block_begin += line_len; } pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY; altbuf_reset(&ab_var_name); altbuf_reset(&ab_file_name); return 0; } static int mg_http_multipart_continue_wait_for_chunk(struct mg_connection *c) { struct mg_http_proto_data *pd = mg_http_get_proto_data(c); struct mbuf *io = &c->recv_mbuf; const char *boundary; if ((int) io->len < pd->mp_stream.boundary_len + 6 /* \r\n, --, -- */) { return 0; } boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len); if (boundary == NULL) { int data_len = (io->len - (pd->mp_stream.boundary_len + 6)); if (data_len > 0) { size_t consumed = mg_http_multipart_call_handler( c, MG_EV_HTTP_PART_DATA, io->buf, (size_t) data_len); mbuf_remove(io, consumed); } return 0; } else if (boundary != NULL) { size_t data_len = ((size_t)(boundary - io->buf) - 4); size_t consumed = mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_DATA, io->buf, data_len); mbuf_remove(io, consumed); if (consumed == data_len) { mbuf_remove(io, 4); pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY; return 1; } else { return 0; } } else { return 0; } } static void mg_http_multipart_continue(struct mg_connection *c) { struct mg_http_proto_data *pd = mg_http_get_proto_data(c); while (1) { switch (pd->mp_stream.state) { case MPS_BEGIN: { pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY; break; } case MPS_WAITING_FOR_BOUNDARY: { if (mg_http_multipart_wait_for_boundary(c) == 0) { return; } break; } case MPS_GOT_BOUNDARY: { if (mg_http_multipart_process_boundary(c) == 0) { return; } break; } case MPS_WAITING_FOR_CHUNK: { if (mg_http_multipart_continue_wait_for_chunk(c) == 0) { return; } break; } case MPS_FINALIZE: { if (mg_http_multipart_finalize(c) == 0) { return; } break; } case MPS_FINISHED: { return; } } } } struct file_upload_state { char *lfn; size_t num_recd; FILE *fp; }; #endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */ void mg_set_protocol_http_websocket(struct mg_connection *nc) { nc->proto_handler = mg_http_handler; } const char *mg_status_message(int status_code) { switch (status_code) { case 206: return "Partial Content"; case 301: return "Moved"; case 302: return "Found"; case 400: return "Bad Request"; case 401: return "Unauthorized"; case 403: return "Forbidden"; case 404: return "Not Found"; case 416: return "Requested Range Not Satisfiable"; case 418: return "I'm a teapot"; case 500: return "Internal Server Error"; case 502: return "Bad Gateway"; case 503: return "Service Unavailable"; #if MG_ENABLE_EXTRA_ERRORS_DESC case 100: return "Continue"; case 101: return "Switching Protocols"; case 102: return "Processing"; case 200: return "OK"; case 201: return "Created"; case 202: return "Accepted"; case 203: return "Non-Authoritative Information"; case 204: return "No Content"; case 205: return "Reset Content"; case 207: return "Multi-Status"; case 208: return "Already Reported"; case 226: return "IM Used"; case 300: return "Multiple Choices"; case 303: return "See Other"; case 304: return "Not Modified"; case 305: return "Use Proxy"; case 306: return "Switch Proxy"; case 307: return "Temporary Redirect"; case 308: return "Permanent Redirect"; case 402: return "Payment Required"; case 405: return "Method Not Allowed"; case 406: return "Not Acceptable"; case 407: return "Proxy Authentication Required"; case 408: return "Request Timeout"; case 409: return "Conflict"; case 410: return "Gone"; case 411: return "Length Required"; case 412: return "Precondition Failed"; case 413: return "Payload Too Large"; case 414: return "URI Too Long"; case 415: return "Unsupported Media Type"; case 417: return "Expectation Failed"; case 422: return "Unprocessable Entity"; case 423: return "Locked"; case 424: return "Failed Dependency"; case 426: return "Upgrade Required"; case 428: return "Precondition Required"; case 429: return "Too Many Requests"; case 431: return "Request Header Fields Too Large"; case 451: return "Unavailable For Legal Reasons"; case 501: return "Not Implemented"; case 504: return "Gateway Timeout"; case 505: return "HTTP Version Not Supported"; case 506: return "Variant Also Negotiates"; case 507: return "Insufficient Storage"; case 508: return "Loop Detected"; case 510: return "Not Extended"; case 511: return "Network Authentication Required"; #endif /* MG_ENABLE_EXTRA_ERRORS_DESC */ default: return "OK"; } } void mg_send_response_line_s(struct mg_connection *nc, int status_code, const struct mg_str extra_headers) { mg_printf(nc, "HTTP/1.1 %d %s\r\n", status_code, mg_status_message(status_code)); #ifndef MG_HIDE_SERVER_INFO mg_printf(nc, "Server: %s\r\n", mg_version_header); #endif if (extra_headers.len > 0) { mg_printf(nc, "%.*s\r\n", (int) extra_headers.len, extra_headers.p); } } void mg_send_response_line(struct mg_connection *nc, int status_code, const char *extra_headers) { mg_send_response_line_s(nc, status_code, mg_mk_str(extra_headers)); } void mg_http_send_redirect(struct mg_connection *nc, int status_code, const struct mg_str location, const struct mg_str extra_headers) { char bbody[100], *pbody = bbody; int bl = mg_asprintf(&pbody, sizeof(bbody), "<p>Moved <a href='%.*s'>here</a>.\r\n", (int) location.len, location.p); char bhead[150], *phead = bhead; mg_asprintf(&phead, sizeof(bhead), "Location: %.*s\r\n" "Content-Type: text/html\r\n" "Content-Length: %d\r\n" "Cache-Control: no-cache\r\n" "%.*s%s", (int) location.len, location.p, bl, (int) extra_headers.len, extra_headers.p, (extra_headers.len > 0 ? "\r\n" : "")); mg_send_response_line(nc, status_code, phead); if (phead != bhead) MG_FREE(phead); mg_send(nc, pbody, bl); if (pbody != bbody) MG_FREE(pbody); } void mg_send_head(struct mg_connection *c, int status_code, int64_t content_length, const char *extra_headers) { mg_send_response_line(c, status_code, extra_headers); if (content_length < 0) { mg_printf(c, "%s", "Transfer-Encoding: chunked\r\n"); } else { mg_printf(c, "Content-Length: %" INT64_FMT "\r\n", content_length); } mg_send(c, "\r\n", 2); } void mg_http_send_error(struct mg_connection *nc, int code, const char *reason) { if (!reason) reason = mg_status_message(code); LOG(LL_DEBUG, ("%p %d %s", nc, code, reason)); mg_send_head(nc, code, strlen(reason), "Content-Type: text/plain\r\nConnection: close"); mg_send(nc, reason, strlen(reason)); nc->flags |= MG_F_SEND_AND_CLOSE; } #if MG_ENABLE_FILESYSTEM static void mg_http_construct_etag(char *buf, size_t buf_len, const cs_stat_t *st) { snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"", (unsigned long) st->st_mtime, (int64_t) st->st_size); } #ifndef WINCE static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) { strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t)); } #else /* Look wince_lib.c for WindowsCE implementation */ static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t); #endif static int mg_http_parse_range_header(const struct mg_str *header, int64_t *a, int64_t *b) { /* * There is no snscanf. Headers are not guaranteed to be NUL-terminated, * so we have this. Ugh. */ int result; char *p = (char *) MG_MALLOC(header->len + 1); if (p == NULL) return 0; memcpy(p, header->p, header->len); p[header->len] = '\0'; result = sscanf(p, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b); MG_FREE(p); return result; } void mg_http_serve_file(struct mg_connection *nc, struct http_message *hm, const char *path, const struct mg_str mime_type, const struct mg_str extra_headers) { struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); cs_stat_t st; LOG(LL_DEBUG, ("%p [%s] %.*s", nc, path, (int) mime_type.len, mime_type.p)); if (mg_stat(path, &st) != 0 || (pd->file.fp = mg_fopen(path, "rb")) == NULL) { int code, err = mg_get_errno(); switch (err) { case EACCES: code = 403; break; case ENOENT: code = 404; break; default: code = 500; }; mg_http_send_error(nc, code, "Open failed"); } else { char etag[50], current_time[50], last_modified[50], range[70]; time_t t = (time_t) mg_time(); int64_t r1 = 0, r2 = 0, cl = st.st_size; struct mg_str *range_hdr = mg_get_http_header(hm, "Range"); int n, status_code = 200; /* Handle Range header */ range[0] = '\0'; if (range_hdr != NULL && (n = mg_http_parse_range_header(range_hdr, &r1, &r2)) > 0 && r1 >= 0 && r2 >= 0) { /* If range is specified like "400-", set second limit to content len */ if (n == 1) { r2 = cl - 1; } if (r1 > r2 || r2 >= cl) { status_code = 416; cl = 0; snprintf(range, sizeof(range), "Content-Range: bytes */%" INT64_FMT "\r\n", (int64_t) st.st_size); } else { status_code = 206; cl = r2 - r1 + 1; snprintf(range, sizeof(range), "Content-Range: bytes %" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n", r1, r1 + cl - 1, (int64_t) st.st_size); #if _FILE_OFFSET_BITS == 64 || _POSIX_C_SOURCE >= 200112L || \ _XOPEN_SOURCE >= 600 fseeko(pd->file.fp, r1, SEEK_SET); #else fseek(pd->file.fp, (long) r1, SEEK_SET); #endif } } #if !MG_DISABLE_HTTP_KEEP_ALIVE { struct mg_str *conn_hdr = mg_get_http_header(hm, "Connection"); if (conn_hdr != NULL) { pd->file.keepalive = (mg_vcasecmp(conn_hdr, "keep-alive") == 0); } else { pd->file.keepalive = (mg_vcmp(&hm->proto, "HTTP/1.1") == 0); } } #endif mg_http_construct_etag(etag, sizeof(etag), &st); mg_gmt_time_string(current_time, sizeof(current_time), &t); mg_gmt_time_string(last_modified, sizeof(last_modified), &st.st_mtime); /* * Content length casted to size_t because: * 1) that's the maximum buffer size anyway * 2) ESP8266 RTOS SDK newlib vprintf cannot contain a 64bit arg at non-last * position * TODO(mkm): fix ESP8266 RTOS SDK */ mg_send_response_line_s(nc, status_code, extra_headers); mg_printf(nc, "Date: %s\r\n" "Last-Modified: %s\r\n" "Accept-Ranges: bytes\r\n" "Content-Type: %.*s\r\n" "Connection: %s\r\n" "Content-Length: %" SIZE_T_FMT "\r\n" "%sEtag: %s\r\n\r\n", current_time, last_modified, (int) mime_type.len, mime_type.p, (pd->file.keepalive ? "keep-alive" : "close"), (size_t) cl, range, etag); pd->file.cl = cl; pd->file.type = DATA_FILE; mg_http_transfer_file_data(nc); } } static void mg_http_serve_file2(struct mg_connection *nc, const char *path, struct http_message *hm, struct mg_serve_http_opts *opts) { #if MG_ENABLE_HTTP_SSI if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) > 0) { mg_handle_ssi_request(nc, hm, path, opts); return; } #endif mg_http_serve_file(nc, hm, path, mg_get_mime_type(path, "text/plain", opts), mg_mk_str(opts->extra_headers)); } #endif int mg_url_decode(const char *src, int src_len, char *dst, int dst_len, int is_form_url_encoded) { int i, j, a, b; #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W') for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) { if (src[i] == '%') { if (i < src_len - 2 && isxdigit(*(const unsigned char *) (src + i + 1)) && isxdigit(*(const unsigned char *) (src + i + 2))) { a = tolower(*(const unsigned char *) (src + i + 1)); b = tolower(*(const unsigned char *) (src + i + 2)); dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b)); i += 2; } else { return -1; } } else if (is_form_url_encoded && src[i] == '+') { dst[j] = ' '; } else { dst[j] = src[i]; } } dst[j] = '\0'; /* Null-terminate the destination */ return i >= src_len ? j : -1; } int mg_get_http_var(const struct mg_str *buf, const char *name, char *dst, size_t dst_len) { const char *p, *e, *s; size_t name_len; int len; /* * According to the documentation function returns negative * value in case of error. For debug purposes it returns: * -1 - src is wrong (NUUL) * -2 - dst is wrong (NULL) * -3 - failed to decode url or dst is to small * -4 - name does not exist */ if (dst == NULL || dst_len == 0) { len = -2; } else if (buf->p == NULL || name == NULL || buf->len == 0) { len = -1; dst[0] = '\0'; } else { name_len = strlen(name); e = buf->p + buf->len; len = -4; dst[0] = '\0'; for (p = buf->p; p + name_len < e; p++) { if ((p == buf->p || p[-1] == '&') && p[name_len] == '=' && !mg_ncasecmp(name, p, name_len)) { p += name_len + 1; s = (const char *) memchr(p, '&', (size_t)(e - p)); if (s == NULL) { s = e; } len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1); /* -1 means: failed to decode or dst is too small */ if (len == -1) { len = -3; } break; } } } return len; } void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len) { char chunk_size[50]; int n; n = snprintf(chunk_size, sizeof(chunk_size), "%lX\r\n", (unsigned long) len); mg_send(nc, chunk_size, n); mg_send(nc, buf, len); mg_send(nc, "\r\n", 2); } void mg_printf_http_chunk(struct mg_connection *nc, const char *fmt, ...) { char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem; int len; va_list ap; va_start(ap, fmt); len = mg_avprintf(&buf, sizeof(mem), fmt, ap); va_end(ap); if (len >= 0) { mg_send_http_chunk(nc, buf, len); } /* LCOV_EXCL_START */ if (buf != mem && buf != NULL) { MG_FREE(buf); } /* LCOV_EXCL_STOP */ } void mg_printf_html_escape(struct mg_connection *nc, const char *fmt, ...) { char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem; int i, j, len; va_list ap; va_start(ap, fmt); len = mg_avprintf(&buf, sizeof(mem), fmt, ap); va_end(ap); if (len >= 0) { for (i = j = 0; i < len; i++) { if (buf[i] == '<' || buf[i] == '>') { mg_send(nc, buf + j, i - j); mg_send(nc, buf[i] == '<' ? "&lt;" : "&gt;", 4); j = i + 1; } } mg_send(nc, buf + j, i - j); } /* LCOV_EXCL_START */ if (buf != mem && buf != NULL) { MG_FREE(buf); } /* LCOV_EXCL_STOP */ } static void mg_http_parse_header_internal(struct mg_str *hdr, const char *var_name, struct altbuf *ab) { int ch = ' ', ch1 = ',', ch2 = ';', n = strlen(var_name); const char *p, *end = hdr ? hdr->p + hdr->len : NULL, *s = NULL; /* Find where variable starts */ for (s = hdr->p; s != NULL && s + n < end; s++) { if ((s == hdr->p || s[-1] == ch || s[-1] == ch1 || s[-1] == ';') && s[n] == '=' && !strncmp(s, var_name, n)) break; } if (s != NULL && &s[n + 1] < end) { s += n + 1; if (*s == '"' || *s == '\'') { ch = ch1 = ch2 = *s++; } p = s; while (p < end && p[0] != ch && p[0] != ch1 && p[0] != ch2) { if (ch != ' ' && p[0] == '\\' && p[1] == ch) p++; altbuf_append(ab, *p++); } if (ch != ' ' && *p != ch) { altbuf_reset(ab); } } /* If there is some data, append a NUL. */ if (ab->len > 0) { altbuf_append(ab, '\0'); } } int mg_http_parse_header2(struct mg_str *hdr, const char *var_name, char **buf, size_t buf_size) { struct altbuf ab; altbuf_init(&ab, *buf, buf_size); if (hdr == NULL) return 0; if (*buf != NULL && buf_size > 0) *buf[0] = '\0'; mg_http_parse_header_internal(hdr, var_name, &ab); /* * Get a (trimmed) buffer, and return a len without a NUL byte which might * have been added. */ *buf = altbuf_get_buf(&ab, 1 /* trim */); return ab.len > 0 ? ab.len - 1 : 0; } int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf, size_t buf_size) { char *buf2 = buf; int len = mg_http_parse_header2(hdr, var_name, &buf2, buf_size); if (buf2 != buf) { /* Buffer was not enough and was reallocated: free it and just return 0 */ MG_FREE(buf2); return 0; } return len; } int mg_get_http_basic_auth(struct http_message *hm, char *user, size_t user_len, char *pass, size_t pass_len) { struct mg_str *hdr = mg_get_http_header(hm, "Authorization"); if (hdr == NULL) return -1; return mg_parse_http_basic_auth(hdr, user, user_len, pass, pass_len); } int mg_parse_http_basic_auth(struct mg_str *hdr, char *user, size_t user_len, char *pass, size_t pass_len) { char *buf = NULL; char fmt[64]; int res = 0; if (mg_strncmp(*hdr, mg_mk_str("Basic "), 6) != 0) return -1; buf = (char *) MG_MALLOC(hdr->len); cs_base64_decode((unsigned char *) hdr->p + 6, hdr->len, buf, NULL); /* e.g. "%123[^:]:%321[^\n]" */ snprintf(fmt, sizeof(fmt), "%%%" SIZE_T_FMT "[^:]:%%%" SIZE_T_FMT "[^\n]", user_len - 1, pass_len - 1); if (sscanf(buf, fmt, user, pass) == 0) { res = -1; } MG_FREE(buf); return res; } #if MG_ENABLE_FILESYSTEM static int mg_is_file_hidden(const char *path, const struct mg_serve_http_opts *opts, int exclude_specials) { const char *p1 = opts->per_directory_auth_file; const char *p2 = opts->hidden_file_pattern; /* Strip directory path from the file name */ const char *pdir = strrchr(path, DIRSEP); if (pdir != NULL) { path = pdir + 1; } return (exclude_specials && (!strcmp(path, ".") || !strcmp(path, ".."))) || (p1 != NULL && mg_match_prefix(p1, strlen(p1), path) == strlen(p1)) || (p2 != NULL && mg_match_prefix(p2, strlen(p2), path) > 0); } #if !MG_DISABLE_HTTP_DIGEST_AUTH #ifndef MG_EXT_MD5 void mg_hash_md5_v(size_t num_msgs, const uint8_t *msgs[], const size_t *msg_lens, uint8_t *digest) { size_t i; cs_md5_ctx md5_ctx; cs_md5_init(&md5_ctx); for (i = 0; i < num_msgs; i++) { cs_md5_update(&md5_ctx, msgs[i], msg_lens[i]); } cs_md5_final(digest, &md5_ctx); } #else extern void mg_hash_md5_v(size_t num_msgs, const uint8_t *msgs[], const size_t *msg_lens, uint8_t *digest); #endif void cs_md5(char buf[33], ...) { unsigned char hash[16]; const uint8_t *msgs[20], *p; size_t msg_lens[20]; size_t num_msgs = 0; va_list ap; va_start(ap, buf); while ((p = va_arg(ap, const unsigned char *) ) != NULL) { msgs[num_msgs] = p; msg_lens[num_msgs] = va_arg(ap, size_t); num_msgs++; } va_end(ap); mg_hash_md5_v(num_msgs, msgs, msg_lens, hash); cs_to_hex(buf, hash, sizeof(hash)); } static void mg_mkmd5resp(const char *method, size_t method_len, const char *uri, size_t uri_len, const char *ha1, size_t ha1_len, const char *nonce, size_t nonce_len, const char *nc, size_t nc_len, const char *cnonce, size_t cnonce_len, const char *qop, size_t qop_len, char *resp) { static const char colon[] = ":"; static const size_t one = 1; char ha2[33]; cs_md5(ha2, method, method_len, colon, one, uri, uri_len, NULL); cs_md5(resp, ha1, ha1_len, colon, one, nonce, nonce_len, colon, one, nc, nc_len, colon, one, cnonce, cnonce_len, colon, one, qop, qop_len, colon, one, ha2, sizeof(ha2) - 1, NULL); } int mg_http_create_digest_auth_header(char *buf, size_t buf_len, const char *method, const char *uri, const char *auth_domain, const char *user, const char *passwd, const char *nonce) { static const char colon[] = ":", qop[] = "auth"; static const size_t one = 1; char ha1[33], resp[33], cnonce[40]; snprintf(cnonce, sizeof(cnonce), "%lx", (unsigned long) mg_time()); cs_md5(ha1, user, (size_t) strlen(user), colon, one, auth_domain, (size_t) strlen(auth_domain), colon, one, passwd, (size_t) strlen(passwd), NULL); mg_mkmd5resp(method, strlen(method), uri, strlen(uri), ha1, sizeof(ha1) - 1, nonce, strlen(nonce), "1", one, cnonce, strlen(cnonce), qop, sizeof(qop) - 1, resp); return snprintf(buf, buf_len, "Authorization: Digest username=\"%s\"," "realm=\"%s\",uri=\"%s\",qop=%s,nc=1,cnonce=%s," "nonce=%s,response=%s\r\n", user, auth_domain, uri, qop, cnonce, nonce, resp); } /* * Check for authentication timeout. * Clients send time stamp encoded in nonce. Make sure it is not too old, * to prevent replay attacks. * Assumption: nonce is a hexadecimal number of seconds since 1970. */ static int mg_check_nonce(const char *nonce) { unsigned long now = (unsigned long) mg_time(); unsigned long val = (unsigned long) strtoul(nonce, NULL, 16); return (now >= val) && (now - val < 60 * 60); } int mg_http_check_digest_auth(struct http_message *hm, const char *auth_domain, FILE *fp) { int ret = 0; struct mg_str *hdr; char username_buf[50], cnonce_buf[64], response_buf[40], uri_buf[200], qop_buf[20], nc_buf[20], nonce_buf[16]; char *username = username_buf, *cnonce = cnonce_buf, *response = response_buf, *uri = uri_buf, *qop = qop_buf, *nc = nc_buf, *nonce = nonce_buf; /* Parse "Authorization:" header, fail fast on parse error */ if (hm == NULL || fp == NULL || (hdr = mg_get_http_header(hm, "Authorization")) == NULL || mg_http_parse_header2(hdr, "username", &username, sizeof(username_buf)) == 0 || mg_http_parse_header2(hdr, "cnonce", &cnonce, sizeof(cnonce_buf)) == 0 || mg_http_parse_header2(hdr, "response", &response, sizeof(response_buf)) == 0 || mg_http_parse_header2(hdr, "uri", &uri, sizeof(uri_buf)) == 0 || mg_http_parse_header2(hdr, "qop", &qop, sizeof(qop_buf)) == 0 || mg_http_parse_header2(hdr, "nc", &nc, sizeof(nc_buf)) == 0 || mg_http_parse_header2(hdr, "nonce", &nonce, sizeof(nonce_buf)) == 0 || mg_check_nonce(nonce) == 0) { ret = 0; goto clean; } /* NOTE(lsm): due to a bug in MSIE, we do not compare URIs */ ret = mg_check_digest_auth( hm->method, mg_mk_str_n( hm->uri.p, hm->uri.len + (hm->query_string.len ? hm->query_string.len + 1 : 0)), mg_mk_str(username), mg_mk_str(cnonce), mg_mk_str(response), mg_mk_str(qop), mg_mk_str(nc), mg_mk_str(nonce), mg_mk_str(auth_domain), fp); clean: if (username != username_buf) MG_FREE(username); if (cnonce != cnonce_buf) MG_FREE(cnonce); if (response != response_buf) MG_FREE(response); if (uri != uri_buf) MG_FREE(uri); if (qop != qop_buf) MG_FREE(qop); if (nc != nc_buf) MG_FREE(nc); if (nonce != nonce_buf) MG_FREE(nonce); return ret; } int mg_check_digest_auth(struct mg_str method, struct mg_str uri, struct mg_str username, struct mg_str cnonce, struct mg_str response, struct mg_str qop, struct mg_str nc, struct mg_str nonce, struct mg_str auth_domain, FILE *fp) { char buf[128], f_user[sizeof(buf)], f_ha1[sizeof(buf)], f_domain[sizeof(buf)]; char exp_resp[33]; /* * Read passwords file line by line. If should have htdigest format, * i.e. each line should be a colon-separated sequence: * USER_NAME:DOMAIN_NAME:HA1_HASH_OF_USER_DOMAIN_AND_PASSWORD */ while (fgets(buf, sizeof(buf), fp) != NULL) { if (sscanf(buf, "%[^:]:%[^:]:%s", f_user, f_domain, f_ha1) == 3 && mg_vcmp(&username, f_user) == 0 && mg_vcmp(&auth_domain, f_domain) == 0) { /* Username and domain matched, check the password */ mg_mkmd5resp(method.p, method.len, uri.p, uri.len, f_ha1, strlen(f_ha1), nonce.p, nonce.len, nc.p, nc.len, cnonce.p, cnonce.len, qop.p, qop.len, exp_resp); LOG(LL_DEBUG, ("%.*s %s %.*s %s", (int) username.len, username.p, f_domain, (int) response.len, response.p, exp_resp)); return mg_ncasecmp(response.p, exp_resp, strlen(exp_resp)) == 0; } } /* None of the entries in the passwords file matched - return failure */ return 0; } int mg_http_is_authorized(struct http_message *hm, struct mg_str path, const char *domain, const char *passwords_file, int flags) { char buf[MG_MAX_PATH]; const char *p; FILE *fp; int authorized = 1; if (domain != NULL && passwords_file != NULL) { if (flags & MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE) { fp = mg_fopen(passwords_file, "r"); } else if (flags & MG_AUTH_FLAG_IS_DIRECTORY) { snprintf(buf, sizeof(buf), "%.*s%c%s", (int) path.len, path.p, DIRSEP, passwords_file); fp = mg_fopen(buf, "r"); } else { p = strrchr(path.p, DIRSEP); if (p == NULL) p = path.p; snprintf(buf, sizeof(buf), "%.*s%c%s", (int) (p - path.p), path.p, DIRSEP, passwords_file); fp = mg_fopen(buf, "r"); } if (fp != NULL) { authorized = mg_http_check_digest_auth(hm, domain, fp); fclose(fp); } else if (!(flags & MG_AUTH_FLAG_ALLOW_MISSING_FILE)) { authorized = 0; } } LOG(LL_DEBUG, ("%.*s %s %x %d", (int) path.len, path.p, passwords_file ? passwords_file : "", flags, authorized)); return authorized; } #else int mg_http_is_authorized(struct http_message *hm, const struct mg_str path, const char *domain, const char *passwords_file, int flags) { (void) hm; (void) path; (void) domain; (void) passwords_file; (void) flags; return 1; } #endif #if MG_ENABLE_DIRECTORY_LISTING static void mg_escape(const char *src, char *dst, size_t dst_len) { size_t n = 0; while (*src != '\0' && n + 5 < dst_len) { unsigned char ch = *(unsigned char *) src++; if (ch == '<') { n += snprintf(dst + n, dst_len - n, "%s", "&lt;"); } else { dst[n++] = ch; } } dst[n] = '\0'; } static void mg_print_dir_entry(struct mg_connection *nc, const char *file_name, cs_stat_t *stp) { char size[64], mod[64], path[MG_MAX_PATH]; int64_t fsize = stp->st_size; int is_dir = S_ISDIR(stp->st_mode); const char *slash = is_dir ? "/" : ""; struct mg_str href; if (is_dir) { snprintf(size, sizeof(size), "%s", "[DIRECTORY]"); } else { /* * We use (double) cast below because MSVC 6 compiler cannot * convert unsigned __int64 to double. */ if (fsize < 1024) { snprintf(size, sizeof(size), "%d", (int) fsize); } else if (fsize < 0x100000) { snprintf(size, sizeof(size), "%.1fk", (double) fsize / 1024.0); } else if (fsize < 0x40000000) { snprintf(size, sizeof(size), "%.1fM", (double) fsize / 1048576); } else { snprintf(size, sizeof(size), "%.1fG", (double) fsize / 1073741824); } } strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&stp->st_mtime)); mg_escape(file_name, path, sizeof(path)); href = mg_url_encode(mg_mk_str(file_name)); mg_printf_http_chunk(nc, "<tr><td><a href=\"%s%s\">%s%s</a></td>" "<td>%s</td><td name=%" INT64_FMT ">%s</td></tr>\n", href.p, slash, path, slash, mod, is_dir ? -1 : fsize, size); free((void *) href.p); } static void mg_scan_directory(struct mg_connection *nc, const char *dir, const struct mg_serve_http_opts *opts, void (*func)(struct mg_connection *, const char *, cs_stat_t *)) { char path[MG_MAX_PATH + 1]; cs_stat_t st; struct dirent *dp; DIR *dirp; LOG(LL_DEBUG, ("%p [%s]", nc, dir)); if ((dirp = (opendir(dir))) != NULL) { while ((dp = readdir(dirp)) != NULL) { /* Do not show current dir and hidden files */ if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) { continue; } snprintf(path, sizeof(path), "%s/%s", dir, dp->d_name); if (mg_stat(path, &st) == 0) { func(nc, (const char *) dp->d_name, &st); } } closedir(dirp); } else { LOG(LL_DEBUG, ("%p opendir(%s) -> %d", nc, dir, mg_get_errno())); } } static void mg_send_directory_listing(struct mg_connection *nc, const char *dir, struct http_message *hm, struct mg_serve_http_opts *opts) { static const char *sort_js_code = "<script>function srt(tb, sc, so, d) {" "var tr = Array.prototype.slice.call(tb.rows, 0)," "tr = tr.sort(function (a, b) { var c1 = a.cells[sc], c2 = b.cells[sc]," "n1 = c1.getAttribute('name'), n2 = c2.getAttribute('name'), " "t1 = a.cells[2].getAttribute('name'), " "t2 = b.cells[2].getAttribute('name'); " "return so * (t1 < 0 && t2 >= 0 ? -1 : t2 < 0 && t1 >= 0 ? 1 : " "n1 ? parseInt(n2) - parseInt(n1) : " "c1.textContent.trim().localeCompare(c2.textContent.trim())); });"; static const char *sort_js_code2 = "for (var i = 0; i < tr.length; i++) tb.appendChild(tr[i]); " "if (!d) window.location.hash = ('sc=' + sc + '&so=' + so); " "};" "window.onload = function() {" "var tb = document.getElementById('tb');" "var m = /sc=([012]).so=(1|-1)/.exec(window.location.hash) || [0, 2, 1];" "var sc = m[1], so = m[2]; document.onclick = function(ev) { " "var c = ev.target.rel; if (c) {if (c == sc) so *= -1; srt(tb, c, so); " "sc = c; ev.preventDefault();}};" "srt(tb, sc, so, true);" "}" "</script>"; mg_send_response_line(nc, 200, opts->extra_headers); mg_printf(nc, "%s: %s\r\n%s: %s\r\n\r\n", "Transfer-Encoding", "chunked", "Content-Type", "text/html; charset=utf-8"); mg_printf_http_chunk( nc, "<html><head><title>Index of %.*s</title>%s%s" "<style>th,td {text-align: left; padding-right: 1em; " "font-family: monospace; }</style></head>\n" "<body><h1>Index of %.*s</h1>\n<table cellpadding=0><thead>" "<tr><th><a href=# rel=0>Name</a></th><th>" "<a href=# rel=1>Modified</a</th>" "<th><a href=# rel=2>Size</a></th></tr>" "<tr><td colspan=3><hr></td></tr>\n" "</thead>\n" "<tbody id=tb>", (int) hm->uri.len, hm->uri.p, sort_js_code, sort_js_code2, (int) hm->uri.len, hm->uri.p); mg_scan_directory(nc, dir, opts, mg_print_dir_entry); mg_printf_http_chunk(nc, "</tbody><tr><td colspan=3><hr></td></tr>\n" "</table>\n" "<address>%s</address>\n" "</body></html>", mg_version_header); mg_send_http_chunk(nc, "", 0); /* TODO(rojer): Remove when cesanta/dev/issues/197 is fixed. */ nc->flags |= MG_F_SEND_AND_CLOSE; } #endif /* MG_ENABLE_DIRECTORY_LISTING */ /* * Given a directory path, find one of the files specified in the * comma-separated list of index files `list`. * First found index file wins. If an index file is found, then gets * appended to the `path`, stat-ed, and result of `stat()` passed to `stp`. * If index file is not found, then `path` and `stp` remain unchanged. */ MG_INTERNAL void mg_find_index_file(const char *path, const char *list, char **index_file, cs_stat_t *stp) { struct mg_str vec; size_t path_len = strlen(path); int found = 0; *index_file = NULL; /* Traverse index files list. For each entry, append it to the given */ /* path and see if the file exists. If it exists, break the loop */ while ((list = mg_next_comma_list_entry(list, &vec, NULL)) != NULL) { cs_stat_t st; size_t len = path_len + 1 + vec.len + 1; *index_file = (char *) MG_REALLOC(*index_file, len); if (*index_file == NULL) break; snprintf(*index_file, len, "%s%c%.*s", path, DIRSEP, (int) vec.len, vec.p); /* Does it exist? Is it a file? */ if (mg_stat(*index_file, &st) == 0 && S_ISREG(st.st_mode)) { /* Yes it does, break the loop */ *stp = st; found = 1; break; } } if (!found) { MG_FREE(*index_file); *index_file = NULL; } LOG(LL_DEBUG, ("[%s] [%s]", path, (*index_file ? *index_file : ""))); } #if MG_ENABLE_HTTP_URL_REWRITES static int mg_http_send_port_based_redirect( struct mg_connection *c, struct http_message *hm, const struct mg_serve_http_opts *opts) { const char *rewrites = opts->url_rewrites; struct mg_str a, b; char local_port[20] = {'%'}; mg_conn_addr_to_str(c, local_port + 1, sizeof(local_port) - 1, MG_SOCK_STRINGIFY_PORT); while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) { if (mg_vcmp(&a, local_port) == 0) { mg_send_response_line(c, 301, NULL); mg_printf(c, "Content-Length: 0\r\nLocation: %.*s%.*s\r\n\r\n", (int) b.len, b.p, (int) (hm->proto.p - hm->uri.p - 1), hm->uri.p); return 1; } } return 0; } static void mg_reverse_proxy_handler(struct mg_connection *nc, int ev, void *ev_data MG_UD_ARG(void *user_data)) { struct http_message *hm = (struct http_message *) ev_data; struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); if (pd == NULL || pd->reverse_proxy_data.linked_conn == NULL) { DBG(("%p: upstream closed", nc)); return; } switch (ev) { case MG_EV_CONNECT: if (*(int *) ev_data != 0) { mg_http_send_error(pd->reverse_proxy_data.linked_conn, 502, NULL); } break; /* TODO(mkm): handle streaming */ case MG_EV_HTTP_REPLY: mg_send(pd->reverse_proxy_data.linked_conn, hm->message.p, hm->message.len); pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE; nc->flags |= MG_F_CLOSE_IMMEDIATELY; break; case MG_EV_CLOSE: pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE; break; } #if MG_ENABLE_CALLBACK_USERDATA (void) user_data; #endif } void mg_http_reverse_proxy(struct mg_connection *nc, const struct http_message *hm, struct mg_str mount, struct mg_str upstream) { struct mg_connection *be; char burl[256], *purl = burl; int i; const char *error; struct mg_connect_opts opts; struct mg_str path = MG_NULL_STR, user_info = MG_NULL_STR, host = MG_NULL_STR; memset(&opts, 0, sizeof(opts)); opts.error_string = &error; mg_asprintf(&purl, sizeof(burl), "%.*s%.*s", (int) upstream.len, upstream.p, (int) (hm->uri.len - mount.len), hm->uri.p + mount.len); be = mg_connect_http_base(nc->mgr, MG_CB(mg_reverse_proxy_handler, NULL), opts, "http", NULL, "https", NULL, purl, &path, &user_info, &host); LOG(LL_DEBUG, ("Proxying %.*s to %s (rule: %.*s)", (int) hm->uri.len, hm->uri.p, purl, (int) mount.len, mount.p)); if (be == NULL) { LOG(LL_ERROR, ("Error connecting to %s: %s", purl, error)); mg_http_send_error(nc, 502, NULL); goto cleanup; } /* link connections to each other, they must live and die together */ mg_http_get_proto_data(be)->reverse_proxy_data.linked_conn = nc; mg_http_get_proto_data(nc)->reverse_proxy_data.linked_conn = be; /* send request upstream */ mg_printf(be, "%.*s %.*s HTTP/1.1\r\n", (int) hm->method.len, hm->method.p, (int) path.len, path.p); mg_printf(be, "Host: %.*s\r\n", (int) host.len, host.p); for (i = 0; i < MG_MAX_HTTP_HEADERS && hm->header_names[i].len > 0; i++) { struct mg_str hn = hm->header_names[i]; struct mg_str hv = hm->header_values[i]; /* we rewrite the host header */ if (mg_vcasecmp(&hn, "Host") == 0) continue; /* * Don't pass chunked transfer encoding to the client because hm->body is * already dechunked when we arrive here. */ if (mg_vcasecmp(&hn, "Transfer-encoding") == 0 && mg_vcasecmp(&hv, "chunked") == 0) { mg_printf(be, "Content-Length: %" SIZE_T_FMT "\r\n", hm->body.len); continue; } /* We don't support proxying Expect: 100-continue. */ if (mg_vcasecmp(&hn, "Expect") == 0 && mg_vcasecmp(&hv, "100-continue") == 0) { continue; } mg_printf(be, "%.*s: %.*s\r\n", (int) hn.len, hn.p, (int) hv.len, hv.p); } mg_send(be, "\r\n", 2); mg_send(be, hm->body.p, hm->body.len); cleanup: if (purl != burl) MG_FREE(purl); } static int mg_http_handle_forwarding(struct mg_connection *nc, struct http_message *hm, const struct mg_serve_http_opts *opts) { const char *rewrites = opts->url_rewrites; struct mg_str a, b; struct mg_str p1 = MG_MK_STR("http://"), p2 = MG_MK_STR("https://"); while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) { if (mg_strncmp(a, hm->uri, a.len) == 0) { if (mg_strncmp(b, p1, p1.len) == 0 || mg_strncmp(b, p2, p2.len) == 0) { mg_http_reverse_proxy(nc, hm, a, b); return 1; } } } return 0; } #endif /* MG_ENABLE_FILESYSTEM */ MG_INTERNAL int mg_uri_to_local_path(struct http_message *hm, const struct mg_serve_http_opts *opts, char **local_path, struct mg_str *remainder) { int ok = 1; const char *cp = hm->uri.p, *cp_end = hm->uri.p + hm->uri.len; struct mg_str root = {NULL, 0}; const char *file_uri_start = cp; *local_path = NULL; remainder->p = NULL; remainder->len = 0; { /* 1. Determine which root to use. */ #if MG_ENABLE_HTTP_URL_REWRITES const char *rewrites = opts->url_rewrites; #else const char *rewrites = ""; #endif struct mg_str *hh = mg_get_http_header(hm, "Host"); struct mg_str a, b; /* Check rewrites first. */ while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) { if (a.len > 1 && a.p[0] == '@') { /* Host rewrite. */ if (hh != NULL && hh->len == a.len - 1 && mg_ncasecmp(a.p + 1, hh->p, a.len - 1) == 0) { root = b; break; } } else { /* Regular rewrite, URI=directory */ size_t match_len = mg_match_prefix_n(a, hm->uri); if (match_len > 0) { file_uri_start = hm->uri.p + match_len; if (*file_uri_start == '/' || file_uri_start == cp_end) { /* Match ended at component boundary, ok. */ } else if (*(file_uri_start - 1) == '/') { /* Pattern ends with '/', backtrack. */ file_uri_start--; } else { /* No match: must fall on the component boundary. */ continue; } root = b; break; } } } /* If no rewrite rules matched, use DAV or regular document root. */ if (root.p == NULL) { #if MG_ENABLE_HTTP_WEBDAV if (opts->dav_document_root != NULL && mg_is_dav_request(&hm->method)) { root.p = opts->dav_document_root; root.len = strlen(opts->dav_document_root); } else #endif { root.p = opts->document_root; root.len = strlen(opts->document_root); } } assert(root.p != NULL && root.len > 0); } { /* 2. Find where in the canonical URI path the local path ends. */ const char *u = file_uri_start + 1; char *lp = (char *) MG_MALLOC(root.len + hm->uri.len + 1); char *lp_end = lp + root.len + hm->uri.len + 1; char *p = lp, *ps; int exists = 1; if (lp == NULL) { ok = 0; goto out; } memcpy(p, root.p, root.len); p += root.len; if (*(p - 1) == DIRSEP) p--; *p = '\0'; ps = p; /* Chop off URI path components one by one and build local path. */ while (u <= cp_end) { const char *next = u; struct mg_str component; if (exists) { cs_stat_t st; exists = (mg_stat(lp, &st) == 0); if (exists && S_ISREG(st.st_mode)) { /* We found the terminal, the rest of the URI (if any) is path_info. */ if (*(u - 1) == '/') u--; break; } } if (u >= cp_end) break; parse_uri_component((const char **) &next, cp_end, "/", &component); if (component.len > 0) { int len; memmove(p + 1, component.p, component.len); len = mg_url_decode(p + 1, component.len, p + 1, lp_end - p - 1, 0); if (len <= 0) { ok = 0; break; } component.p = p + 1; component.len = len; if (mg_vcmp(&component, ".") == 0) { /* Yum. */ } else if (mg_vcmp(&component, "..") == 0) { while (p > ps && *p != DIRSEP) p--; *p = '\0'; } else { size_t i; #ifdef _WIN32 /* On Windows, make sure it's valid Unicode (no funny stuff). */ wchar_t buf[MG_MAX_PATH * 2]; if (to_wchar(component.p, buf, MG_MAX_PATH) == 0) { DBG(("[%.*s] smells funny", (int) component.len, component.p)); ok = 0; break; } #endif *p++ = DIRSEP; /* No NULs and DIRSEPs in the component (percent-encoded). */ for (i = 0; i < component.len; i++, p++) { if (*p == '\0' || *p == DIRSEP #ifdef _WIN32 /* On Windows, "/" is also accepted, so check for that too. */ || *p == '/' #endif ) { ok = 0; break; } } } } u = next; } if (ok) { *local_path = lp; if (u > cp_end) u = cp_end; remainder->p = u; remainder->len = cp_end - u; } else { MG_FREE(lp); } } out: LOG(LL_DEBUG, ("'%.*s' -> '%s' + '%.*s'", (int) hm->uri.len, hm->uri.p, *local_path ? *local_path : "", (int) remainder->len, remainder->p)); return ok; } static int mg_get_month_index(const char *s) { static const char *month_names[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; size_t i; for (i = 0; i < ARRAY_SIZE(month_names); i++) if (!strcmp(s, month_names[i])) return (int) i; return -1; } static int mg_num_leap_years(int year) { return year / 4 - year / 100 + year / 400; } /* Parse UTC date-time string, and return the corresponding time_t value. */ MG_INTERNAL time_t mg_parse_date_string(const char *datetime) { static const unsigned short days_before_month[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334}; char month_str[32]; int second, minute, hour, day, month, year, leap_days, days; time_t result = (time_t) 0; if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d", &day, month_str, &year, &hour, &minute, &second) == 6) || (sscanf(datetime, "%d %3s %d %d:%d:%d", &day, month_str, &year, &hour, &minute, &second) == 6) || (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d", &day, month_str, &year, &hour, &minute, &second) == 6) || (sscanf(datetime, "%d-%3s-%d %d:%d:%d", &day, month_str, &year, &hour, &minute, &second) == 6)) && year > 1970 && (month = mg_get_month_index(month_str)) != -1) { leap_days = mg_num_leap_years(year) - mg_num_leap_years(1970); year -= 1970; days = year * 365 + days_before_month[month] + (day - 1) + leap_days; result = days * 24 * 3600 + hour * 3600 + minute * 60 + second; } return result; } MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st) { struct mg_str *hdr; if ((hdr = mg_get_http_header(hm, "If-None-Match")) != NULL) { char etag[64]; mg_http_construct_etag(etag, sizeof(etag), st); return mg_vcasecmp(hdr, etag) == 0; } else if ((hdr = mg_get_http_header(hm, "If-Modified-Since")) != NULL) { return st->st_mtime <= mg_parse_date_string(hdr->p); } else { return 0; } } void mg_http_send_digest_auth_request(struct mg_connection *c, const char *domain) { mg_printf(c, "HTTP/1.1 401 Unauthorized\r\n" "WWW-Authenticate: Digest qop=\"auth\", " "realm=\"%s\", nonce=\"%lx\"\r\n" "Content-Length: 0\r\n\r\n", domain, (unsigned long) mg_time()); } static void mg_http_send_options(struct mg_connection *nc, struct mg_serve_http_opts *opts) { mg_send_response_line(nc, 200, opts->extra_headers); mg_printf(nc, "%s", "Allow: GET, POST, HEAD, CONNECT, OPTIONS" #if MG_ENABLE_HTTP_WEBDAV ", MKCOL, PUT, DELETE, PROPFIND, MOVE\r\nDAV: 1,2" #endif "\r\n\r\n"); nc->flags |= MG_F_SEND_AND_CLOSE; } static int mg_is_creation_request(const struct http_message *hm) { return mg_vcmp(&hm->method, "MKCOL") == 0 || mg_vcmp(&hm->method, "PUT") == 0; } MG_INTERNAL void mg_send_http_file(struct mg_connection *nc, char *path, const struct mg_str *path_info, struct http_message *hm, struct mg_serve_http_opts *opts) { int exists, is_directory, is_cgi; #if MG_ENABLE_HTTP_WEBDAV int is_dav = mg_is_dav_request(&hm->method); #else int is_dav = 0; #endif char *index_file = NULL; cs_stat_t st; exists = (mg_stat(path, &st) == 0); is_directory = exists && S_ISDIR(st.st_mode); if (is_directory) mg_find_index_file(path, opts->index_files, &index_file, &st); is_cgi = (mg_match_prefix(opts->cgi_file_pattern, strlen(opts->cgi_file_pattern), index_file ? index_file : path) > 0); LOG(LL_DEBUG, ("%p %.*s [%s] exists=%d is_dir=%d is_dav=%d is_cgi=%d index=%s", nc, (int) hm->method.len, hm->method.p, path, exists, is_directory, is_dav, is_cgi, index_file ? index_file : "")); if (is_directory && hm->uri.p[hm->uri.len - 1] != '/' && !is_dav) { mg_printf(nc, "HTTP/1.1 301 Moved\r\nLocation: %.*s/\r\n" "Content-Length: 0\r\n\r\n", (int) hm->uri.len, hm->uri.p); MG_FREE(index_file); return; } /* If we have path_info, the only way to handle it is CGI. */ if (path_info->len > 0 && !is_cgi) { mg_http_send_error(nc, 501, NULL); MG_FREE(index_file); return; } if (is_dav && opts->dav_document_root == NULL) { mg_http_send_error(nc, 501, NULL); } else if (!mg_http_is_authorized( hm, mg_mk_str(path), opts->auth_domain, opts->global_auth_file, ((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) | MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE | MG_AUTH_FLAG_ALLOW_MISSING_FILE)) || !mg_http_is_authorized( hm, mg_mk_str(path), opts->auth_domain, opts->per_directory_auth_file, ((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) | MG_AUTH_FLAG_ALLOW_MISSING_FILE))) { mg_http_send_digest_auth_request(nc, opts->auth_domain); } else if (is_cgi) { #if MG_ENABLE_HTTP_CGI mg_handle_cgi(nc, index_file ? index_file : path, path_info, hm, opts); #else mg_http_send_error(nc, 501, NULL); #endif /* MG_ENABLE_HTTP_CGI */ } else if ((!exists || mg_is_file_hidden(path, opts, 0 /* specials are ok */)) && !mg_is_creation_request(hm)) { mg_http_send_error(nc, 404, NULL); #if MG_ENABLE_HTTP_WEBDAV } else if (!mg_vcmp(&hm->method, "PROPFIND")) { mg_handle_propfind(nc, path, &st, hm, opts); #if !MG_DISABLE_DAV_AUTH } else if (is_dav && (opts->dav_auth_file == NULL || (strcmp(opts->dav_auth_file, "-") != 0 && !mg_http_is_authorized( hm, mg_mk_str(path), opts->auth_domain, opts->dav_auth_file, ((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) | MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE | MG_AUTH_FLAG_ALLOW_MISSING_FILE))))) { mg_http_send_digest_auth_request(nc, opts->auth_domain); #endif } else if (!mg_vcmp(&hm->method, "MKCOL")) { mg_handle_mkcol(nc, path, hm); } else if (!mg_vcmp(&hm->method, "DELETE")) { mg_handle_delete(nc, opts, path); } else if (!mg_vcmp(&hm->method, "PUT")) { mg_handle_put(nc, path, hm); } else if (!mg_vcmp(&hm->method, "MOVE")) { mg_handle_move(nc, opts, path, hm); #if MG_ENABLE_FAKE_DAVLOCK } else if (!mg_vcmp(&hm->method, "LOCK")) { mg_handle_lock(nc, path); #endif #endif /* MG_ENABLE_HTTP_WEBDAV */ } else if (!mg_vcmp(&hm->method, "OPTIONS")) { mg_http_send_options(nc, opts); } else if (is_directory && index_file == NULL) { #if MG_ENABLE_DIRECTORY_LISTING if (strcmp(opts->enable_directory_listing, "yes") == 0) { mg_send_directory_listing(nc, path, hm, opts); } else { mg_http_send_error(nc, 403, NULL); } #else mg_http_send_error(nc, 501, NULL); #endif } else if (mg_is_not_modified(hm, &st)) { mg_http_send_error(nc, 304, "Not Modified"); } else { mg_http_serve_file2(nc, index_file ? index_file : path, hm, opts); } MG_FREE(index_file); } void mg_serve_http(struct mg_connection *nc, struct http_message *hm, struct mg_serve_http_opts opts) { char *path = NULL; struct mg_str *hdr, path_info; uint32_t remote_ip = ntohl(*(uint32_t *) &nc->sa.sin.sin_addr); if (mg_check_ip_acl(opts.ip_acl, remote_ip) != 1) { /* Not allowed to connect */ mg_http_send_error(nc, 403, NULL); nc->flags |= MG_F_SEND_AND_CLOSE; return; } #if MG_ENABLE_HTTP_URL_REWRITES if (mg_http_handle_forwarding(nc, hm, &opts)) { return; } if (mg_http_send_port_based_redirect(nc, hm, &opts)) { return; } #endif if (opts.document_root == NULL) { opts.document_root = "."; } if (opts.per_directory_auth_file == NULL) { opts.per_directory_auth_file = ".htpasswd"; } if (opts.enable_directory_listing == NULL) { opts.enable_directory_listing = "yes"; } if (opts.cgi_file_pattern == NULL) { opts.cgi_file_pattern = "**.cgi$|**.php$"; } if (opts.ssi_pattern == NULL) { opts.ssi_pattern = "**.shtml$|**.shtm$"; } if (opts.index_files == NULL) { opts.index_files = "index.html,index.htm,index.shtml,index.cgi,index.php"; } /* Normalize path - resolve "." and ".." (in-place). */ if (!mg_normalize_uri_path(&hm->uri, &hm->uri)) { mg_http_send_error(nc, 400, NULL); return; } if (mg_uri_to_local_path(hm, &opts, &path, &path_info) == 0) { mg_http_send_error(nc, 404, NULL); return; } mg_send_http_file(nc, path, &path_info, hm, &opts); MG_FREE(path); path = NULL; /* Close connection for non-keep-alive requests */ if (mg_vcmp(&hm->proto, "HTTP/1.1") != 0 || ((hdr = mg_get_http_header(hm, "Connection")) != NULL && mg_vcmp(hdr, "keep-alive") != 0)) { #if 0 nc->flags |= MG_F_SEND_AND_CLOSE; #endif } } #if MG_ENABLE_HTTP_STREAMING_MULTIPART void mg_file_upload_handler(struct mg_connection *nc, int ev, void *ev_data, mg_fu_fname_fn local_name_fn MG_UD_ARG(void *user_data)) { switch (ev) { case MG_EV_HTTP_PART_BEGIN: { struct mg_http_multipart_part *mp = (struct mg_http_multipart_part *) ev_data; struct file_upload_state *fus; struct mg_str lfn = local_name_fn(nc, mg_mk_str(mp->file_name)); mp->user_data = NULL; if (lfn.p == NULL || lfn.len == 0) { LOG(LL_ERROR, ("%p Not allowed to upload %s", nc, mp->file_name)); mg_printf(nc, "HTTP/1.1 403 Not Allowed\r\n" "Content-Type: text/plain\r\n" "Connection: close\r\n\r\n" "Not allowed to upload %s\r\n", mp->file_name); nc->flags |= MG_F_SEND_AND_CLOSE; return; } fus = (struct file_upload_state *) MG_CALLOC(1, sizeof(*fus)); if (fus == NULL) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; return; } fus->lfn = (char *) MG_MALLOC(lfn.len + 1); memcpy(fus->lfn, lfn.p, lfn.len); fus->lfn[lfn.len] = '\0'; if (lfn.p != mp->file_name) MG_FREE((char *) lfn.p); LOG(LL_DEBUG, ("%p Receiving file %s -> %s", nc, mp->file_name, fus->lfn)); fus->fp = mg_fopen(fus->lfn, "wb"); if (fus->fp == NULL) { mg_printf(nc, "HTTP/1.1 500 Internal Server Error\r\n" "Content-Type: text/plain\r\n" "Connection: close\r\n\r\n"); LOG(LL_ERROR, ("Failed to open %s: %d\n", fus->lfn, mg_get_errno())); mg_printf(nc, "Failed to open %s: %d\n", fus->lfn, mg_get_errno()); /* Do not close the connection just yet, discard remainder of the data. * This is because at the time of writing some browsers (Chrome) fail to * render response before all the data is sent. */ } mp->user_data = (void *) fus; break; } case MG_EV_HTTP_PART_DATA: { struct mg_http_multipart_part *mp = (struct mg_http_multipart_part *) ev_data; struct file_upload_state *fus = (struct file_upload_state *) mp->user_data; if (fus == NULL || fus->fp == NULL) break; if (mg_fwrite(mp->data.p, 1, mp->data.len, fus->fp) != mp->data.len) { LOG(LL_ERROR, ("Failed to write to %s: %d, wrote %d", fus->lfn, mg_get_errno(), (int) fus->num_recd)); if (mg_get_errno() == ENOSPC #ifdef SPIFFS_ERR_FULL || mg_get_errno() == SPIFFS_ERR_FULL #endif ) { mg_printf(nc, "HTTP/1.1 413 Payload Too Large\r\n" "Content-Type: text/plain\r\n" "Connection: close\r\n\r\n"); mg_printf(nc, "Failed to write to %s: no space left; wrote %d\r\n", fus->lfn, (int) fus->num_recd); } else { mg_printf(nc, "HTTP/1.1 500 Internal Server Error\r\n" "Content-Type: text/plain\r\n" "Connection: close\r\n\r\n"); mg_printf(nc, "Failed to write to %s: %d, wrote %d", mp->file_name, mg_get_errno(), (int) fus->num_recd); } fclose(fus->fp); remove(fus->lfn); fus->fp = NULL; /* Do not close the connection just yet, discard remainder of the data. * This is because at the time of writing some browsers (Chrome) fail to * render response before all the data is sent. */ return; } fus->num_recd += mp->data.len; LOG(LL_DEBUG, ("%p rec'd %d bytes, %d total", nc, (int) mp->data.len, (int) fus->num_recd)); break; } case MG_EV_HTTP_PART_END: { struct mg_http_multipart_part *mp = (struct mg_http_multipart_part *) ev_data; struct file_upload_state *fus = (struct file_upload_state *) mp->user_data; if (fus == NULL) break; if (mp->status >= 0 && fus->fp != NULL) { LOG(LL_DEBUG, ("%p Uploaded %s (%s), %d bytes", nc, mp->file_name, fus->lfn, (int) fus->num_recd)); } else { LOG(LL_ERROR, ("Failed to store %s (%s)", mp->file_name, fus->lfn)); /* * mp->status < 0 means connection was terminated, so no reason to send * HTTP reply */ } if (fus->fp != NULL) fclose(fus->fp); MG_FREE(fus->lfn); MG_FREE(fus); mp->user_data = NULL; /* Don't close the connection yet, there may be more files to come. */ break; } case MG_EV_HTTP_MULTIPART_REQUEST_END: { mg_printf(nc, "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Connection: close\r\n\r\n" "Ok.\r\n"); nc->flags |= MG_F_SEND_AND_CLOSE; break; } } #if MG_ENABLE_CALLBACK_USERDATA (void) user_data; #endif } #endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */ #endif /* MG_ENABLE_FILESYSTEM */ struct mg_connection *mg_connect_http_base( struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), struct mg_connect_opts opts, const char *scheme1, const char *scheme2, const char *scheme_ssl1, const char *scheme_ssl2, const char *url, struct mg_str *path, struct mg_str *user_info, struct mg_str *host) { struct mg_connection *nc = NULL; unsigned int port_i = 0; int use_ssl = 0; struct mg_str scheme, query, fragment; char conn_addr_buf[2]; char *conn_addr = conn_addr_buf; if (mg_parse_uri(mg_mk_str(url), &scheme, user_info, host, &port_i, path, &query, &fragment) != 0) { MG_SET_PTRPTR(opts.error_string, "cannot parse url"); goto out; } /* If query is present, do not strip it. Pass to the caller. */ if (query.len > 0) path->len += query.len + 1; if (scheme.len == 0 || mg_vcmp(&scheme, scheme1) == 0 || (scheme2 != NULL && mg_vcmp(&scheme, scheme2) == 0)) { use_ssl = 0; if (port_i == 0) port_i = 80; } else if (mg_vcmp(&scheme, scheme_ssl1) == 0 || (scheme2 != NULL && mg_vcmp(&scheme, scheme_ssl2) == 0)) { use_ssl = 1; if (port_i == 0) port_i = 443; } else { goto out; } mg_asprintf(&conn_addr, sizeof(conn_addr_buf), "tcp://%.*s:%u", (int) host->len, host->p, port_i); if (conn_addr == NULL) goto out; LOG(LL_DEBUG, ("%s use_ssl? %d %s", url, use_ssl, conn_addr)); if (use_ssl) { #if MG_ENABLE_SSL /* * Schema requires SSL, but no SSL parameters were provided in opts. * In order to maintain backward compatibility, use a faux-SSL with no * verification. */ if (opts.ssl_ca_cert == NULL) { opts.ssl_ca_cert = "*"; } #else MG_SET_PTRPTR(opts.error_string, "ssl is disabled"); goto out; #endif } if ((nc = mg_connect_opt(mgr, conn_addr, MG_CB(ev_handler, user_data), opts)) != NULL) { mg_set_protocol_http_websocket(nc); } out: if (conn_addr != NULL && conn_addr != conn_addr_buf) MG_FREE(conn_addr); return nc; } struct mg_connection *mg_connect_http_opt( struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), struct mg_connect_opts opts, const char *url, const char *extra_headers, const char *post_data) { struct mg_str user = MG_NULL_STR, null_str = MG_NULL_STR; struct mg_str host = MG_NULL_STR, path = MG_NULL_STR; struct mbuf auth; struct mg_connection *nc = mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http", NULL, "https", NULL, url, &path, &user, &host); if (nc == NULL) { return NULL; } mbuf_init(&auth, 0); if (user.len > 0) { mg_basic_auth_header(user, null_str, &auth); } if (post_data == NULL) post_data = ""; if (extra_headers == NULL) extra_headers = ""; if (path.len == 0) path = mg_mk_str("/"); if (host.len == 0) host = mg_mk_str(""); mg_printf(nc, "%s %.*s HTTP/1.1\r\nHost: %.*s\r\nContent-Length: %" SIZE_T_FMT "\r\n%.*s%s\r\n%s", (post_data[0] == '\0' ? "GET" : "POST"), (int) path.len, path.p, (int) (path.p - host.p), host.p, strlen(post_data), (int) auth.len, (auth.buf == NULL ? "" : auth.buf), extra_headers, post_data); mbuf_free(&auth); return nc; } struct mg_connection *mg_connect_http( struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), const char *url, const char *extra_headers, const char *post_data) { struct mg_connect_opts opts; memset(&opts, 0, sizeof(opts)); return mg_connect_http_opt(mgr, MG_CB(ev_handler, user_data), opts, url, extra_headers, post_data); } size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name, size_t var_name_len, char *file_name, size_t file_name_len, const char **data, size_t *data_len) { static const char cd[] = "Content-Disposition: "; size_t hl, bl, n, ll, pos, cdl = sizeof(cd) - 1; int shl; if (buf == NULL || buf_len <= 0) return 0; if ((shl = mg_http_get_request_len(buf, buf_len)) <= 0) return 0; hl = shl; if (buf[0] != '-' || buf[1] != '-' || buf[2] == '\n') return 0; /* Get boundary length */ bl = mg_get_line_len(buf, buf_len); /* Loop through headers, fetch variable name and file name */ var_name[0] = file_name[0] = '\0'; for (n = bl; (ll = mg_get_line_len(buf + n, hl - n)) > 0; n += ll) { if (mg_ncasecmp(cd, buf + n, cdl) == 0) { struct mg_str header; header.p = buf + n + cdl; header.len = ll - (cdl + 2); { char *var_name2 = var_name; mg_http_parse_header2(&header, "name", &var_name2, var_name_len); /* TODO: handle reallocated buffer correctly */ if (var_name2 != var_name) { MG_FREE(var_name2); var_name[0] = '\0'; } } { char *file_name2 = file_name; mg_http_parse_header2(&header, "filename", &file_name2, file_name_len); /* TODO: handle reallocated buffer correctly */ if (file_name2 != file_name) { MG_FREE(file_name2); file_name[0] = '\0'; } } } } /* Scan through the body, search for terminating boundary */ for (pos = hl; pos + (bl - 2) < buf_len; pos++) { if (buf[pos] == '-' && !strncmp(buf, &buf[pos], bl - 2)) { if (data_len != NULL) *data_len = (pos - 2) - hl; if (data != NULL) *data = buf + hl; return pos; } } return 0; } void mg_register_http_endpoint_opt(struct mg_connection *nc, const char *uri_path, mg_event_handler_t handler, struct mg_http_endpoint_opts opts) { struct mg_http_proto_data *pd = NULL; struct mg_http_endpoint *new_ep = NULL; if (nc == NULL) return; new_ep = (struct mg_http_endpoint *) MG_CALLOC(1, sizeof(*new_ep)); if (new_ep == NULL) return; pd = mg_http_get_proto_data(nc); if (pd == NULL) pd = mg_http_create_proto_data(nc); new_ep->uri_pattern = mg_strdup(mg_mk_str(uri_path)); if (opts.auth_domain != NULL && opts.auth_file != NULL) { new_ep->auth_domain = strdup(opts.auth_domain); new_ep->auth_file = strdup(opts.auth_file); } new_ep->handler = handler; #if MG_ENABLE_CALLBACK_USERDATA new_ep->user_data = opts.user_data; #endif new_ep->next = pd->endpoints; pd->endpoints = new_ep; } static void mg_http_call_endpoint_handler(struct mg_connection *nc, int ev, struct http_message *hm) { struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); void *user_data = nc->user_data; if (ev == MG_EV_HTTP_REQUEST #if MG_ENABLE_HTTP_STREAMING_MULTIPART || ev == MG_EV_HTTP_MULTIPART_REQUEST #endif ) { struct mg_http_endpoint *ep = mg_http_get_endpoint_handler(nc->listener, &hm->uri); if (ep != NULL) { #if MG_ENABLE_FILESYSTEM && !MG_DISABLE_HTTP_DIGEST_AUTH if (!mg_http_is_authorized(hm, hm->uri, ep->auth_domain, ep->auth_file, MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE)) { mg_http_send_digest_auth_request(nc, ep->auth_domain); return; } #endif pd->endpoint_handler = ep->handler; #if MG_ENABLE_CALLBACK_USERDATA user_data = ep->user_data; #endif } } mg_call(nc, pd->endpoint_handler ? pd->endpoint_handler : nc->handler, user_data, ev, hm); } void mg_register_http_endpoint(struct mg_connection *nc, const char *uri_path, MG_CB(mg_event_handler_t handler, void *user_data)) { struct mg_http_endpoint_opts opts; memset(&opts, 0, sizeof(opts)); #if MG_ENABLE_CALLBACK_USERDATA opts.user_data = user_data; #endif mg_register_http_endpoint_opt(nc, uri_path, handler, opts); } #endif /* MG_ENABLE_HTTP */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_http_cgi.c" #endif /* * Copyright (c) 2014-2016 Cesanta Software Limited * All rights reserved */ #ifndef _WIN32 #include <signal.h> #endif #if MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI #ifndef MG_MAX_CGI_ENVIR_VARS #define MG_MAX_CGI_ENVIR_VARS 64 #endif #ifndef MG_ENV_EXPORT_TO_CGI #define MG_ENV_EXPORT_TO_CGI "MONGOOSE_CGI" #endif #define MG_F_HTTP_CGI_PARSE_HEADERS MG_F_USER_1 /* * This structure helps to create an environment for the spawned CGI program. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings, * last element must be NULL. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0 * strings must reside in a contiguous buffer. The end of the buffer is * marked by two '\0' characters. * We satisfy both worlds: we create an envp array (which is vars), all * entries are actually pointers inside buf. */ struct mg_cgi_env_block { struct mg_connection *nc; char buf[MG_CGI_ENVIRONMENT_SIZE]; /* Environment buffer */ const char *vars[MG_MAX_CGI_ENVIR_VARS]; /* char *envp[] */ int len; /* Space taken */ int nvars; /* Number of variables in envp[] */ }; #ifdef _WIN32 struct mg_threadparam { sock_t s; HANDLE hPipe; }; static int mg_wait_until_ready(sock_t sock, int for_read) { fd_set set; FD_ZERO(&set); FD_SET(sock, &set); return select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0) == 1; } static void *mg_push_to_stdin(void *arg) { struct mg_threadparam *tp = (struct mg_threadparam *) arg; int n, sent, stop = 0; DWORD k; char buf[BUFSIZ]; while (!stop && mg_wait_until_ready(tp->s, 1) && (n = recv(tp->s, buf, sizeof(buf), 0)) > 0) { if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue; for (sent = 0; !stop && sent < n; sent += k) { if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1; } } DBG(("%s", "FORWARED EVERYTHING TO CGI")); CloseHandle(tp->hPipe); MG_FREE(tp); return NULL; } static void *mg_pull_from_stdout(void *arg) { struct mg_threadparam *tp = (struct mg_threadparam *) arg; int k = 0, stop = 0; DWORD n, sent; char buf[BUFSIZ]; while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) { for (sent = 0; !stop && sent < n; sent += k) { if (mg_wait_until_ready(tp->s, 0) && (k = send(tp->s, buf + sent, n - sent, 0)) <= 0) stop = 1; } } DBG(("%s", "EOF FROM CGI")); CloseHandle(tp->hPipe); shutdown(tp->s, 2); // Without this, IO thread may get truncated data closesocket(tp->s); MG_FREE(tp); return NULL; } static void mg_spawn_stdio_thread(sock_t sock, HANDLE hPipe, void *(*func)(void *)) { struct mg_threadparam *tp = (struct mg_threadparam *) MG_MALLOC(sizeof(*tp)); if (tp != NULL) { tp->s = sock; tp->hPipe = hPipe; mg_start_thread(func, tp); } } static void mg_abs_path(const char *utf8_path, char *abs_path, size_t len) { wchar_t buf[MG_MAX_PATH], buf2[MG_MAX_PATH]; to_wchar(utf8_path, buf, ARRAY_SIZE(buf)); GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL); WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0); } static int mg_start_process(const char *interp, const char *cmd, const char *env, const char *envp[], const char *dir, sock_t sock) { STARTUPINFOW si; PROCESS_INFORMATION pi; HANDLE a[2], b[2], me = GetCurrentProcess(); wchar_t wcmd[MG_MAX_PATH], full_dir[MG_MAX_PATH]; char buf[MG_MAX_PATH], buf2[MG_MAX_PATH], buf5[MG_MAX_PATH], buf4[MG_MAX_PATH], cmdline[MG_MAX_PATH]; DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS; FILE *fp; memset(&si, 0, sizeof(si)); memset(&pi, 0, sizeof(pi)); si.cb = sizeof(si); si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; si.hStdError = GetStdHandle(STD_ERROR_HANDLE); CreatePipe(&a[0], &a[1], NULL, 0); CreatePipe(&b[0], &b[1], NULL, 0); DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags); DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags); if (interp == NULL && (fp = mg_fopen(cmd, "r")) != NULL) { buf[0] = buf[1] = '\0'; fgets(buf, sizeof(buf), fp); buf[sizeof(buf) - 1] = '\0'; if (buf[0] == '#' && buf[1] == '!') { interp = buf + 2; /* Trim leading spaces: https://github.com/cesanta/mongoose/issues/489 */ while (*interp != '\0' && isspace(*(unsigned char *) interp)) { interp++; } } fclose(fp); } snprintf(buf, sizeof(buf), "%s/%s", dir, cmd); mg_abs_path(buf, buf2, ARRAY_SIZE(buf2)); mg_abs_path(dir, buf5, ARRAY_SIZE(buf5)); to_wchar(dir, full_dir, ARRAY_SIZE(full_dir)); if (interp != NULL) { mg_abs_path(interp, buf4, ARRAY_SIZE(buf4)); snprintf(cmdline, sizeof(cmdline), "%s \"%s\"", buf4, buf2); } else { snprintf(cmdline, sizeof(cmdline), "\"%s\"", buf2); } to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd)); if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP, (void *) env, full_dir, &si, &pi) != 0) { mg_spawn_stdio_thread(sock, a[1], mg_push_to_stdin); mg_spawn_stdio_thread(sock, b[0], mg_pull_from_stdout); CloseHandle(si.hStdOutput); CloseHandle(si.hStdInput); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); } else { CloseHandle(a[1]); CloseHandle(b[0]); closesocket(sock); } DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess)); /* Not closing a[0] and b[1] because we've used DUPLICATE_CLOSE_SOURCE */ (void) envp; return (pi.hProcess != NULL); } #else static int mg_start_process(const char *interp, const char *cmd, const char *env, const char *envp[], const char *dir, sock_t sock) { char buf[500]; pid_t pid = fork(); (void) env; if (pid == 0) { /* * In Linux `chdir` declared with `warn_unused_result` attribute * To shutup compiler we have yo use result in some way */ int tmp = chdir(dir); (void) tmp; (void) dup2(sock, 0); (void) dup2(sock, 1); closesocket(sock); /* * After exec, all signal handlers are restored to their default values, * with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's * implementation, SIGCHLD's handler will leave unchanged after exec * if it was set to be ignored. Restore it to default action. */ signal(SIGCHLD, SIG_DFL); if (interp == NULL) { execle(cmd, cmd, (char *) 0, envp); /* (char *) 0 to squash warning */ } else { execle(interp, interp, cmd, (char *) 0, envp); } snprintf(buf, sizeof(buf), "Status: 500\r\n\r\n" "500 Server Error: %s%s%s: %s", interp == NULL ? "" : interp, interp == NULL ? "" : " ", cmd, strerror(errno)); send(1, buf, strlen(buf), 0); _exit(EXIT_FAILURE); /* exec call failed */ } return (pid != 0); } #endif /* _WIN32 */ /* * Append VARIABLE=VALUE\0 string to the buffer, and add a respective * pointer into the vars array. */ static char *mg_addenv(struct mg_cgi_env_block *block, const char *fmt, ...) { int n, space; char *added = block->buf + block->len; va_list ap; /* Calculate how much space is left in the buffer */ space = sizeof(block->buf) - (block->len + 2); if (space > 0) { /* Copy VARIABLE=VALUE\0 string into the free space */ va_start(ap, fmt); n = vsnprintf(added, (size_t) space, fmt, ap); va_end(ap); /* Make sure we do not overflow buffer and the envp array */ if (n > 0 && n + 1 < space && block->nvars < (int) ARRAY_SIZE(block->vars) - 2) { /* Append a pointer to the added string into the envp array */ block->vars[block->nvars++] = added; /* Bump up used length counter. Include \0 terminator */ block->len += n + 1; } } return added; } static void mg_addenv2(struct mg_cgi_env_block *blk, const char *name) { const char *s; if ((s = getenv(name)) != NULL) mg_addenv(blk, "%s=%s", name, s); } static void mg_prepare_cgi_environment(struct mg_connection *nc, const char *prog, const struct mg_str *path_info, const struct http_message *hm, const struct mg_serve_http_opts *opts, struct mg_cgi_env_block *blk) { const char *s; struct mg_str *h; char *p; size_t i; char buf[100]; size_t path_info_len = path_info != NULL ? path_info->len : 0; blk->len = blk->nvars = 0; blk->nc = nc; if ((s = getenv("SERVER_NAME")) != NULL) { mg_addenv(blk, "SERVER_NAME=%s", s); } else { mg_sock_to_str(nc->sock, buf, sizeof(buf), 3); mg_addenv(blk, "SERVER_NAME=%s", buf); } mg_addenv(blk, "SERVER_ROOT=%s", opts->document_root); mg_addenv(blk, "DOCUMENT_ROOT=%s", opts->document_root); mg_addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MG_VERSION); /* Prepare the environment block */ mg_addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1"); mg_addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1"); mg_addenv(blk, "%s", "REDIRECT_STATUS=200"); /* For PHP */ mg_addenv(blk, "REQUEST_METHOD=%.*s", (int) hm->method.len, hm->method.p); mg_addenv(blk, "REQUEST_URI=%.*s%s%.*s", (int) hm->uri.len, hm->uri.p, hm->query_string.len == 0 ? "" : "?", (int) hm->query_string.len, hm->query_string.p); mg_conn_addr_to_str(nc, buf, sizeof(buf), MG_SOCK_STRINGIFY_REMOTE | MG_SOCK_STRINGIFY_IP); mg_addenv(blk, "REMOTE_ADDR=%s", buf); mg_conn_addr_to_str(nc, buf, sizeof(buf), MG_SOCK_STRINGIFY_PORT); mg_addenv(blk, "SERVER_PORT=%s", buf); s = hm->uri.p + hm->uri.len - path_info_len - 1; if (*s == '/') { const char *base_name = strrchr(prog, DIRSEP); mg_addenv(blk, "SCRIPT_NAME=%.*s/%s", (int) (s - hm->uri.p), hm->uri.p, (base_name != NULL ? base_name + 1 : prog)); } else { mg_addenv(blk, "SCRIPT_NAME=%.*s", (int) (s - hm->uri.p + 1), hm->uri.p); } mg_addenv(blk, "SCRIPT_FILENAME=%s", prog); if (path_info != NULL && path_info->len > 0) { mg_addenv(blk, "PATH_INFO=%.*s", (int) path_info->len, path_info->p); /* Not really translated... */ mg_addenv(blk, "PATH_TRANSLATED=%.*s", (int) path_info->len, path_info->p); } #if MG_ENABLE_SSL mg_addenv(blk, "HTTPS=%s", (nc->flags & MG_F_SSL ? "on" : "off")); #else mg_addenv(blk, "HTTPS=off"); #endif if ((h = mg_get_http_header((struct http_message *) hm, "Content-Type")) != NULL) { mg_addenv(blk, "CONTENT_TYPE=%.*s", (int) h->len, h->p); } if (hm->query_string.len > 0) { mg_addenv(blk, "QUERY_STRING=%.*s", (int) hm->query_string.len, hm->query_string.p); } if ((h = mg_get_http_header((struct http_message *) hm, "Content-Length")) != NULL) { mg_addenv(blk, "CONTENT_LENGTH=%.*s", (int) h->len, h->p); } mg_addenv2(blk, "PATH"); mg_addenv2(blk, "TMP"); mg_addenv2(blk, "TEMP"); mg_addenv2(blk, "TMPDIR"); mg_addenv2(blk, "PERLLIB"); mg_addenv2(blk, MG_ENV_EXPORT_TO_CGI); #ifdef _WIN32 mg_addenv2(blk, "COMSPEC"); mg_addenv2(blk, "SYSTEMROOT"); mg_addenv2(blk, "SystemDrive"); mg_addenv2(blk, "ProgramFiles"); mg_addenv2(blk, "ProgramFiles(x86)"); mg_addenv2(blk, "CommonProgramFiles(x86)"); #else mg_addenv2(blk, "LD_LIBRARY_PATH"); #endif /* _WIN32 */ /* Add all headers as HTTP_* variables */ for (i = 0; hm->header_names[i].len > 0; i++) { p = mg_addenv(blk, "HTTP_%.*s=%.*s", (int) hm->header_names[i].len, hm->header_names[i].p, (int) hm->header_values[i].len, hm->header_values[i].p); /* Convert variable name into uppercase, and change - to _ */ for (; *p != '=' && *p != '\0'; p++) { if (*p == '-') *p = '_'; *p = (char) toupper(*(unsigned char *) p); } } blk->vars[blk->nvars++] = NULL; blk->buf[blk->len++] = '\0'; } static void mg_cgi_ev_handler(struct mg_connection *cgi_nc, int ev, void *ev_data MG_UD_ARG(void *user_data)) { #if !MG_ENABLE_CALLBACK_USERDATA void *user_data = cgi_nc->user_data; #endif struct mg_connection *nc = (struct mg_connection *) user_data; (void) ev_data; if (nc == NULL) { /* The corresponding network connection was closed. */ cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY; return; } switch (ev) { case MG_EV_RECV: /* * CGI script does not output reply line, like "HTTP/1.1 CODE XXXXX\n" * It outputs headers, then body. Headers might include "Status" * header, which changes CODE, and it might include "Location" header * which changes CODE to 302. * * Therefore we do not send the output from the CGI script to the user * until all CGI headers are received. * * Here we parse the output from the CGI script, and if all headers has * been received, send appropriate reply line, and forward all * received headers to the client. */ if (nc->flags & MG_F_HTTP_CGI_PARSE_HEADERS) { struct mbuf *io = &cgi_nc->recv_mbuf; int len = mg_http_get_request_len(io->buf, io->len); if (len == 0) break; if (len < 0 || io->len > MG_MAX_HTTP_REQUEST_SIZE) { cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY; mg_http_send_error(nc, 500, "Bad headers"); } else { struct http_message hm; struct mg_str *h; mg_http_parse_headers(io->buf, io->buf + io->len, io->len, &hm); if (mg_get_http_header(&hm, "Location") != NULL) { mg_printf(nc, "%s", "HTTP/1.1 302 Moved\r\n"); } else if ((h = mg_get_http_header(&hm, "Status")) != NULL) { mg_printf(nc, "HTTP/1.1 %.*s\r\n", (int) h->len, h->p); } else { mg_printf(nc, "%s", "HTTP/1.1 200 OK\r\n"); } } nc->flags &= ~MG_F_HTTP_CGI_PARSE_HEADERS; } if (!(nc->flags & MG_F_HTTP_CGI_PARSE_HEADERS)) { mg_forward(cgi_nc, nc); } break; case MG_EV_CLOSE: DBG(("%p CLOSE", cgi_nc)); mg_http_free_proto_data_cgi(&mg_http_get_proto_data(nc)->cgi); nc->flags |= MG_F_SEND_AND_CLOSE; break; } } MG_INTERNAL void mg_handle_cgi(struct mg_connection *nc, const char *prog, const struct mg_str *path_info, const struct http_message *hm, const struct mg_serve_http_opts *opts) { struct mg_cgi_env_block blk; char dir[MG_MAX_PATH]; const char *p; sock_t fds[2]; DBG(("%p [%s]", nc, prog)); mg_prepare_cgi_environment(nc, prog, path_info, hm, opts, &blk); /* * CGI must be executed in its own directory. 'dir' must point to the * directory containing executable program, 'p' must point to the * executable program name relative to 'dir'. */ if ((p = strrchr(prog, DIRSEP)) == NULL) { snprintf(dir, sizeof(dir), "%s", "."); } else { snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog); prog = p + 1; } if (!mg_socketpair(fds, SOCK_STREAM)) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; return; } #ifndef _WIN32 struct sigaction sa; sigemptyset(&sa.sa_mask); sa.sa_handler = SIG_IGN; sa.sa_flags = 0; sigaction(SIGCHLD, &sa, NULL); #endif if (mg_start_process(opts->cgi_interpreter, prog, blk.buf, blk.vars, dir, fds[1]) != 0) { struct mg_connection *cgi_nc = mg_add_sock(nc->mgr, fds[0], mg_cgi_ev_handler MG_UD_ARG(nc)); struct mg_http_proto_data *cgi_pd = mg_http_get_proto_data(nc); cgi_pd->cgi.cgi_nc = cgi_nc; #if !MG_ENABLE_CALLBACK_USERDATA cgi_pd->cgi.cgi_nc->user_data = nc; #endif nc->flags |= MG_F_HTTP_CGI_PARSE_HEADERS; /* Push POST data to the CGI */ if (hm->body.len > 0) { mg_send(cgi_pd->cgi.cgi_nc, hm->body.p, hm->body.len); } mbuf_remove(&nc->recv_mbuf, nc->recv_mbuf.len); } else { closesocket(fds[0]); mg_http_send_error(nc, 500, "CGI failure"); } #ifndef _WIN32 closesocket(fds[1]); /* On Windows, CGI stdio thread closes that socket */ #endif } MG_INTERNAL void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d) { if (d == NULL) return; if (d->cgi_nc != NULL) { d->cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY; d->cgi_nc->user_data = NULL; } memset(d, 0, sizeof(*d)); } #endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_http_ssi.c" #endif /* * Copyright (c) 2014-2016 Cesanta Software Limited * All rights reserved */ #if MG_ENABLE_HTTP && MG_ENABLE_HTTP_SSI && MG_ENABLE_FILESYSTEM static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm, const char *path, FILE *fp, int include_level, const struct mg_serve_http_opts *opts); static void mg_send_file_data(struct mg_connection *nc, FILE *fp) { char buf[BUFSIZ]; size_t n; while ((n = mg_fread(buf, 1, sizeof(buf), fp)) > 0) { mg_send(nc, buf, n); } } static void mg_do_ssi_include(struct mg_connection *nc, struct http_message *hm, const char *ssi, char *tag, int include_level, const struct mg_serve_http_opts *opts) { char file_name[MG_MAX_PATH], path[MG_MAX_PATH], *p; FILE *fp; /* * sscanf() is safe here, since send_ssi_file() also uses buffer * of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN. */ if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) { /* File name is relative to the webserver root */ snprintf(path, sizeof(path), "%s/%s", opts->document_root, file_name); } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) { /* * File name is relative to the webserver working directory * or it is absolute system path */ snprintf(path, sizeof(path), "%s", file_name); } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 || sscanf(tag, " \"%[^\"]\"", file_name) == 1) { /* File name is relative to the currect document */ snprintf(path, sizeof(path), "%s", ssi); if ((p = strrchr(path, DIRSEP)) != NULL) { p[1] = '\0'; } snprintf(path + strlen(path), sizeof(path) - strlen(path), "%s", file_name); } else { mg_printf(nc, "Bad SSI #include: [%s]", tag); return; } if ((fp = mg_fopen(path, "rb")) == NULL) { mg_printf(nc, "SSI include error: mg_fopen(%s): %s", path, strerror(mg_get_errno())); } else { mg_set_close_on_exec((sock_t) fileno(fp)); if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) > 0) { mg_send_ssi_file(nc, hm, path, fp, include_level + 1, opts); } else { mg_send_file_data(nc, fp); } fclose(fp); } } #if MG_ENABLE_HTTP_SSI_EXEC static void do_ssi_exec(struct mg_connection *nc, char *tag) { char cmd[BUFSIZ]; FILE *fp; if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) { mg_printf(nc, "Bad SSI #exec: [%s]", tag); } else if ((fp = popen(cmd, "r")) == NULL) { mg_printf(nc, "Cannot SSI #exec: [%s]: %s", cmd, strerror(mg_get_errno())); } else { mg_send_file_data(nc, fp); pclose(fp); } } #endif /* MG_ENABLE_HTTP_SSI_EXEC */ /* * SSI directive has the following format: * <!--#directive parameter=value parameter=value --> */ static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm, const char *path, FILE *fp, int include_level, const struct mg_serve_http_opts *opts) { static const struct mg_str btag = MG_MK_STR("<!--#"); static const struct mg_str d_include = MG_MK_STR("include"); static const struct mg_str d_call = MG_MK_STR("call"); #if MG_ENABLE_HTTP_SSI_EXEC static const struct mg_str d_exec = MG_MK_STR("exec"); #endif char buf[BUFSIZ], *p = buf + btag.len; /* p points to SSI directive */ int ch, len, in_ssi_tag; if (include_level > 10) { mg_printf(nc, "SSI #include level is too deep (%s)", path); return; } in_ssi_tag = len = 0; while ((ch = fgetc(fp)) != EOF) { if (in_ssi_tag && ch == '>' && buf[len - 1] == '-' && buf[len - 2] == '-') { size_t i = len - 2; in_ssi_tag = 0; /* Trim closing --> */ buf[i--] = '\0'; while (i > 0 && buf[i] == ' ') { buf[i--] = '\0'; } /* Handle known SSI directives */ if (strncmp(p, d_include.p, d_include.len) == 0) { mg_do_ssi_include(nc, hm, path, p + d_include.len + 1, include_level, opts); } else if (strncmp(p, d_call.p, d_call.len) == 0) { struct mg_ssi_call_ctx cctx; memset(&cctx, 0, sizeof(cctx)); cctx.req = hm; cctx.file = mg_mk_str(path); cctx.arg = mg_mk_str(p + d_call.len + 1); mg_call(nc, NULL, nc->user_data, MG_EV_SSI_CALL, (void *) cctx.arg.p); /* NUL added above */ mg_call(nc, NULL, nc->user_data, MG_EV_SSI_CALL_CTX, &cctx); #if MG_ENABLE_HTTP_SSI_EXEC } else if (strncmp(p, d_exec.p, d_exec.len) == 0) { do_ssi_exec(nc, p + d_exec.len + 1); #endif } else { /* Silently ignore unknown SSI directive. */ } len = 0; } else if (ch == '<') { in_ssi_tag = 1; if (len > 0) { mg_send(nc, buf, (size_t) len); } len = 0; buf[len++] = ch & 0xff; } else if (in_ssi_tag) { if (len == (int) btag.len && strncmp(buf, btag.p, btag.len) != 0) { /* Not an SSI tag */ in_ssi_tag = 0; } else if (len == (int) sizeof(buf) - 2) { mg_printf(nc, "%s: SSI tag is too large", path); len = 0; } buf[len++] = ch & 0xff; } else { buf[len++] = ch & 0xff; if (len == (int) sizeof(buf)) { mg_send(nc, buf, (size_t) len); len = 0; } } } /* Send the rest of buffered data */ if (len > 0) { mg_send(nc, buf, (size_t) len); } } MG_INTERNAL void mg_handle_ssi_request(struct mg_connection *nc, struct http_message *hm, const char *path, const struct mg_serve_http_opts *opts) { FILE *fp; struct mg_str mime_type; DBG(("%p %s", nc, path)); if ((fp = mg_fopen(path, "rb")) == NULL) { mg_http_send_error(nc, 404, NULL); } else { mg_set_close_on_exec((sock_t) fileno(fp)); mime_type = mg_get_mime_type(path, "text/plain", opts); mg_send_response_line(nc, 200, opts->extra_headers); mg_printf(nc, "Content-Type: %.*s\r\n" "Connection: close\r\n\r\n", (int) mime_type.len, mime_type.p); mg_send_ssi_file(nc, hm, path, fp, 0, opts); fclose(fp); nc->flags |= MG_F_SEND_AND_CLOSE; } } #endif /* MG_ENABLE_HTTP_SSI && MG_ENABLE_HTTP && MG_ENABLE_FILESYSTEM */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_http_webdav.c" #endif /* * Copyright (c) 2014-2016 Cesanta Software Limited * All rights reserved */ #if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV MG_INTERNAL int mg_is_dav_request(const struct mg_str *s) { static const char *methods[] = { "PUT", "DELETE", "MKCOL", "PROPFIND", "MOVE" #if MG_ENABLE_FAKE_DAVLOCK , "LOCK", "UNLOCK" #endif }; size_t i; for (i = 0; i < ARRAY_SIZE(methods); i++) { if (mg_vcmp(s, methods[i]) == 0) { return 1; } } return 0; } static int mg_mkdir(const char *path, uint32_t mode) { #ifndef _WIN32 return mkdir(path, mode); #else (void) mode; return _mkdir(path); #endif } static void mg_print_props(struct mg_connection *nc, const char *name, cs_stat_t *stp) { char mtime[64]; time_t t = stp->st_mtime; /* store in local variable for NDK compile */ struct mg_str name_esc = mg_url_encode(mg_mk_str(name)); mg_gmt_time_string(mtime, sizeof(mtime), &t); mg_printf(nc, "<d:response>" "<d:href>%s</d:href>" "<d:propstat>" "<d:prop>" "<d:resourcetype>%s</d:resourcetype>" "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>" "<d:getlastmodified>%s</d:getlastmodified>" "</d:prop>" "<d:status>HTTP/1.1 200 OK</d:status>" "</d:propstat>" "</d:response>\n", name_esc.p, S_ISDIR(stp->st_mode) ? "<d:collection/>" : "", (int64_t) stp->st_size, mtime); free((void *) name_esc.p); } MG_INTERNAL void mg_handle_propfind(struct mg_connection *nc, const char *path, cs_stat_t *stp, struct http_message *hm, struct mg_serve_http_opts *opts) { static const char header[] = "HTTP/1.1 207 Multi-Status\r\n" "Connection: close\r\n" "Content-Type: text/xml; charset=utf-8\r\n\r\n" "<?xml version=\"1.0\" encoding=\"utf-8\"?>" "<d:multistatus xmlns:d='DAV:'>\n"; static const char footer[] = "</d:multistatus>\n"; const struct mg_str *depth = mg_get_http_header(hm, "Depth"); /* Print properties for the requested resource itself */ if (S_ISDIR(stp->st_mode) && strcmp(opts->enable_directory_listing, "yes") != 0) { mg_printf(nc, "%s", "HTTP/1.1 403 Directory Listing Denied\r\n\r\n"); } else { char uri[MG_MAX_PATH]; mg_send(nc, header, sizeof(header) - 1); snprintf(uri, sizeof(uri), "%.*s", (int) hm->uri.len, hm->uri.p); mg_print_props(nc, uri, stp); if (S_ISDIR(stp->st_mode) && (depth == NULL || mg_vcmp(depth, "0") != 0)) { mg_scan_directory(nc, path, opts, mg_print_props); } mg_send(nc, footer, sizeof(footer) - 1); nc->flags |= MG_F_SEND_AND_CLOSE; } } #if MG_ENABLE_FAKE_DAVLOCK /* * Windows explorer (probably there are another WebDav clients like it) * requires LOCK support in webdav. W/out this, it still works, but fails * to save file: shows error message and offers "Save As". * "Save as" works, but this message is very annoying. * This is fake lock, which doesn't lock something, just returns LOCK token, * UNLOCK always answers "OK". * With this fake LOCK Windows Explorer looks happy and saves file. * NOTE: that is not DAV LOCK imlementation, it is just a way to shut up * Windows native DAV client. This is why FAKE LOCK is not enabed by default */ MG_INTERNAL void mg_handle_lock(struct mg_connection *nc, const char *path) { static const char *reply = "HTTP/1.1 207 Multi-Status\r\n" "Connection: close\r\n" "Content-Type: text/xml; charset=utf-8\r\n\r\n" "<?xml version=\"1.0\" encoding=\"utf-8\"?>" "<d:multistatus xmlns:d='DAV:'>\n" "<D:lockdiscovery>\n" "<D:activelock>\n" "<D:locktoken>\n" "<D:href>\n" "opaquelocktoken:%s%u" "</D:href>" "</D:locktoken>" "</D:activelock>\n" "</D:lockdiscovery>" "</d:multistatus>\n"; mg_printf(nc, reply, path, (unsigned int) mg_time()); nc->flags |= MG_F_SEND_AND_CLOSE; } #endif MG_INTERNAL void mg_handle_mkcol(struct mg_connection *nc, const char *path, struct http_message *hm) { int status_code = 500; if (hm->body.len != (size_t) ~0 && hm->body.len > 0) { status_code = 415; } else if (!mg_mkdir(path, 0755)) { status_code = 201; } else if (errno == EEXIST) { status_code = 405; } else if (errno == EACCES) { status_code = 403; } else if (errno == ENOENT) { status_code = 409; } else { status_code = 500; } mg_http_send_error(nc, status_code, NULL); } static int mg_remove_directory(const struct mg_serve_http_opts *opts, const char *dir) { char path[MG_MAX_PATH]; struct dirent *dp; cs_stat_t st; DIR *dirp; if ((dirp = opendir(dir)) == NULL) return 0; while ((dp = readdir(dirp)) != NULL) { if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) { continue; } snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name); mg_stat(path, &st); if (S_ISDIR(st.st_mode)) { mg_remove_directory(opts, path); } else { remove(path); } } closedir(dirp); rmdir(dir); return 1; } MG_INTERNAL void mg_handle_move(struct mg_connection *c, const struct mg_serve_http_opts *opts, const char *path, struct http_message *hm) { const struct mg_str *dest = mg_get_http_header(hm, "Destination"); if (dest == NULL) { mg_http_send_error(c, 411, NULL); } else { const char *p = (char *) memchr(dest->p, '/', dest->len); if (p != NULL && p[1] == '/' && (p = (char *) memchr(p + 2, '/', dest->p + dest->len - p)) != NULL) { char buf[MG_MAX_PATH]; snprintf(buf, sizeof(buf), "%s%.*s", opts->dav_document_root, (int) (dest->p + dest->len - p), p); if (rename(path, buf) == 0) { mg_http_send_error(c, 200, NULL); } else { mg_http_send_error(c, 418, NULL); } } else { mg_http_send_error(c, 500, NULL); } } } MG_INTERNAL void mg_handle_delete(struct mg_connection *nc, const struct mg_serve_http_opts *opts, const char *path) { cs_stat_t st; if (mg_stat(path, &st) != 0) { mg_http_send_error(nc, 404, NULL); } else if (S_ISDIR(st.st_mode)) { mg_remove_directory(opts, path); mg_http_send_error(nc, 204, NULL); } else if (remove(path) == 0) { mg_http_send_error(nc, 204, NULL); } else { mg_http_send_error(nc, 423, NULL); } } /* Return -1 on error, 1 on success. */ static int mg_create_itermediate_directories(const char *path) { const char *s; /* Create intermediate directories if they do not exist */ for (s = path + 1; *s != '\0'; s++) { if (*s == '/') { char buf[MG_MAX_PATH]; cs_stat_t st; snprintf(buf, sizeof(buf), "%.*s", (int) (s - path), path); buf[sizeof(buf) - 1] = '\0'; if (mg_stat(buf, &st) != 0 && mg_mkdir(buf, 0755) != 0) { return -1; } } } return 1; } MG_INTERNAL void mg_handle_put(struct mg_connection *nc, const char *path, struct http_message *hm) { struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); cs_stat_t st; const struct mg_str *cl_hdr = mg_get_http_header(hm, "Content-Length"); int rc, status_code = mg_stat(path, &st) == 0 ? 200 : 201; mg_http_free_proto_data_file(&pd->file); if ((rc = mg_create_itermediate_directories(path)) == 0) { mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code); } else if (rc == -1) { mg_http_send_error(nc, 500, NULL); } else if (cl_hdr == NULL) { mg_http_send_error(nc, 411, NULL); } else if ((pd->file.fp = mg_fopen(path, "w+b")) == NULL) { mg_http_send_error(nc, 500, NULL); } else { const struct mg_str *range_hdr = mg_get_http_header(hm, "Content-Range"); int64_t r1 = 0, r2 = 0; pd->file.type = DATA_PUT; mg_set_close_on_exec((sock_t) fileno(pd->file.fp)); pd->file.cl = to64(cl_hdr->p); if (range_hdr != NULL && mg_http_parse_range_header(range_hdr, &r1, &r2) > 0) { status_code = 206; fseeko(pd->file.fp, r1, SEEK_SET); pd->file.cl = r2 > r1 ? r2 - r1 + 1 : pd->file.cl - r1; } mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code); /* Remove HTTP request from the mbuf, leave only payload */ mbuf_remove(&nc->recv_mbuf, hm->message.len - hm->body.len); mg_http_transfer_file_data(nc); } } #endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_http_websocket.c" #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ #if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET /* Amalgamated: #include "common/cs_sha1.h" */ #ifndef MG_WEBSOCKET_PING_INTERVAL_SECONDS #define MG_WEBSOCKET_PING_INTERVAL_SECONDS 5 #endif #define FLAGS_MASK_FIN (1 << 7) #define FLAGS_MASK_OP 0x0f static int mg_is_ws_fragment(unsigned char flags) { return (flags & FLAGS_MASK_FIN) == 0 || (flags & FLAGS_MASK_OP) == WEBSOCKET_OP_CONTINUE; } static int mg_is_ws_first_fragment(unsigned char flags) { return (flags & FLAGS_MASK_FIN) == 0 && (flags & FLAGS_MASK_OP) != WEBSOCKET_OP_CONTINUE; } static int mg_is_ws_control_frame(unsigned char flags) { unsigned char op = (flags & FLAGS_MASK_OP); return op == WEBSOCKET_OP_CLOSE || op == WEBSOCKET_OP_PING || op == WEBSOCKET_OP_PONG; } static void mg_handle_incoming_websocket_frame(struct mg_connection *nc, struct websocket_message *wsm) { if (wsm->flags & 0x8) { mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_CONTROL_FRAME, wsm); } else { mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_FRAME, wsm); } } static struct mg_ws_proto_data *mg_ws_get_proto_data(struct mg_connection *nc) { struct mg_http_proto_data *htd = mg_http_get_proto_data(nc); return (htd != NULL ? &htd->ws_data : NULL); } /* * Sends a Close websocket frame with the given data, and closes the underlying * connection. If `len` is ~0, strlen(data) is used. */ static void mg_ws_close(struct mg_connection *nc, const void *data, size_t len) { if ((int) len == ~0) { len = strlen((const char *) data); } mg_send_websocket_frame(nc, WEBSOCKET_OP_CLOSE, data, len); nc->flags |= MG_F_SEND_AND_CLOSE; } static int mg_deliver_websocket_data(struct mg_connection *nc) { /* Using unsigned char *, cause of integer arithmetic below */ uint64_t i, data_len = 0, frame_len = 0, new_data_len = nc->recv_mbuf.len, len, mask_len = 0, header_len = 0; struct mg_ws_proto_data *wsd = mg_ws_get_proto_data(nc); unsigned char *new_data = (unsigned char *) nc->recv_mbuf.buf, *e = (unsigned char *) nc->recv_mbuf.buf + nc->recv_mbuf.len; uint8_t flags; int ok, reass; if (wsd->reass_len > 0) { /* * We already have some previously received data which we need to * reassemble and deliver to the client code when we get the final * fragment. * * NOTE: it doesn't mean that the current message must be a continuation: * it might be a control frame (Close, Ping or Pong), which should be * handled without breaking the fragmented message. */ size_t existing_len = wsd->reass_len; assert(new_data_len >= existing_len); new_data += existing_len; new_data_len -= existing_len; } flags = new_data[0]; reass = new_data_len > 0 && mg_is_ws_fragment(flags) && !(nc->flags & MG_F_WEBSOCKET_NO_DEFRAG); if (reass && mg_is_ws_control_frame(flags)) { /* * Control frames can't be fragmented, so if we encounter fragmented * control frame, close connection immediately. */ mg_ws_close(nc, "fragmented control frames are illegal", ~0); return 0; } else if (new_data_len > 0 && !reass && !mg_is_ws_control_frame(flags) && wsd->reass_len > 0) { /* * When in the middle of a fragmented message, only the continuations * and control frames are allowed. */ mg_ws_close(nc, "non-continuation in the middle of a fragmented message", ~0); return 0; } if (new_data_len >= 2) { len = new_data[1] & 0x7f; mask_len = new_data[1] & FLAGS_MASK_FIN ? 4 : 0; if (len < 126 && new_data_len >= mask_len) { data_len = len; header_len = 2 + mask_len; } else if (len == 126 && new_data_len >= 4 + mask_len) { header_len = 4 + mask_len; data_len = ntohs(*(uint16_t *) &new_data[2]); } else if (new_data_len >= 10 + mask_len) { header_len = 10 + mask_len; data_len = (((uint64_t) ntohl(*(uint32_t *) &new_data[2])) << 32) + ntohl(*(uint32_t *) &new_data[6]); } } frame_len = header_len + data_len; ok = (frame_len > 0 && frame_len <= new_data_len); /* Check for overflow */ if (frame_len < header_len || frame_len < data_len) { ok = 0; mg_ws_close(nc, "overflowed message", ~0); } if (ok) { size_t cleanup_len = 0; struct websocket_message wsm; wsm.size = (size_t) data_len; wsm.data = new_data + header_len; wsm.flags = flags; /* Apply mask if necessary */ if (mask_len > 0) { for (i = 0; i < data_len; i++) { new_data[i + header_len] ^= (new_data + header_len - mask_len)[i % 4]; } } if (reass) { /* This is a message fragment */ if (mg_is_ws_first_fragment(flags)) { /* * On the first fragmented frame, skip the first byte (op) and also * reset size to 1 (op), it'll be incremented with the data len below. */ new_data += 1; wsd->reass_len = 1 /* op */; } /* Append this frame to the reassembled buffer */ memmove(new_data, wsm.data, e - wsm.data); wsd->reass_len += wsm.size; nc->recv_mbuf.len -= wsm.data - new_data; if (flags & FLAGS_MASK_FIN) { /* On last fragmented frame - call user handler and remove data */ wsm.flags = FLAGS_MASK_FIN | nc->recv_mbuf.buf[0]; wsm.data = (unsigned char *) nc->recv_mbuf.buf + 1 /* op */; wsm.size = wsd->reass_len - 1 /* op */; cleanup_len = wsd->reass_len; wsd->reass_len = 0; /* Pass reassembled message to the client code. */ mg_handle_incoming_websocket_frame(nc, &wsm); mbuf_remove(&nc->recv_mbuf, cleanup_len); /* Cleanup frame */ } } else { /* * This is a complete message, not a fragment. It might happen in between * of a fragmented message (in this case, WebSocket protocol requires * current message to be a control frame). */ cleanup_len = (size_t) frame_len; /* First of all, check if we need to react on a control frame. */ switch (flags & FLAGS_MASK_OP) { case WEBSOCKET_OP_PING: mg_send_websocket_frame(nc, WEBSOCKET_OP_PONG, wsm.data, wsm.size); break; case WEBSOCKET_OP_CLOSE: mg_ws_close(nc, wsm.data, wsm.size); break; } /* Pass received message to the client code. */ mg_handle_incoming_websocket_frame(nc, &wsm); /* Cleanup frame */ memmove(nc->recv_mbuf.buf + wsd->reass_len, nc->recv_mbuf.buf + wsd->reass_len + cleanup_len, nc->recv_mbuf.len - wsd->reass_len - cleanup_len); nc->recv_mbuf.len -= cleanup_len; } } return ok; } struct ws_mask_ctx { size_t pos; /* zero means unmasked */ uint32_t mask; }; static uint32_t mg_ws_random_mask(void) { uint32_t mask; /* * The spec requires WS client to generate hard to * guess mask keys. From RFC6455, Section 5.3: * * The unpredictability of the masking key is essential to prevent * authors of malicious applications from selecting the bytes that appear on * the wire. * * Hence this feature is essential when the actual end user of this API * is untrusted code that wouldn't have access to a lower level net API * anyway (e.g. web browsers). Hence this feature is low prio for most * mongoose use cases and thus can be disabled, e.g. when porting to a platform * that lacks rand(). */ #if MG_DISABLE_WS_RANDOM_MASK mask = 0xefbeadde; /* generated with a random number generator, I swear */ #else if (sizeof(long) >= 4) { mask = (uint32_t) rand(); } else if (sizeof(long) == 2) { mask = (uint32_t) rand() << 16 | (uint32_t) rand(); } #endif return mask; } static void mg_send_ws_header(struct mg_connection *nc, int op, size_t len, struct ws_mask_ctx *ctx) { int header_len; unsigned char header[10]; header[0] = (op & WEBSOCKET_DONT_FIN ? 0x0 : FLAGS_MASK_FIN) | (op & FLAGS_MASK_OP); if (len < 126) { header[1] = (unsigned char) len; header_len = 2; } else if (len < 65535) { uint16_t tmp = htons((uint16_t) len); header[1] = 126; memcpy(&header[2], &tmp, sizeof(tmp)); header_len = 4; } else { uint32_t tmp; header[1] = 127; tmp = htonl((uint32_t)((uint64_t) len >> 32)); memcpy(&header[2], &tmp, sizeof(tmp)); tmp = htonl((uint32_t)(len & 0xffffffff)); memcpy(&header[6], &tmp, sizeof(tmp)); header_len = 10; } /* client connections enable masking */ if (nc->listener == NULL) { header[1] |= 1 << 7; /* set masking flag */ mg_send(nc, header, header_len); ctx->mask = mg_ws_random_mask(); mg_send(nc, &ctx->mask, sizeof(ctx->mask)); ctx->pos = nc->send_mbuf.len; } else { mg_send(nc, header, header_len); ctx->pos = 0; } } static void mg_ws_mask_frame(struct mbuf *mbuf, struct ws_mask_ctx *ctx) { size_t i; if (ctx->pos == 0) return; for (i = 0; i < (mbuf->len - ctx->pos); i++) { mbuf->buf[ctx->pos + i] ^= ((char *) &ctx->mask)[i % 4]; } } void mg_send_websocket_frame(struct mg_connection *nc, int op, const void *data, size_t len) { struct ws_mask_ctx ctx; DBG(("%p %d %d", nc, op, (int) len)); mg_send_ws_header(nc, op, len, &ctx); mg_send(nc, data, len); mg_ws_mask_frame(&nc->send_mbuf, &ctx); if (op == WEBSOCKET_OP_CLOSE) { nc->flags |= MG_F_SEND_AND_CLOSE; } } void mg_send_websocket_framev(struct mg_connection *nc, int op, const struct mg_str *strv, int strvcnt) { struct ws_mask_ctx ctx; int i; int len = 0; for (i = 0; i < strvcnt; i++) { len += strv[i].len; } mg_send_ws_header(nc, op, len, &ctx); for (i = 0; i < strvcnt; i++) { mg_send(nc, strv[i].p, strv[i].len); } mg_ws_mask_frame(&nc->send_mbuf, &ctx); if (op == WEBSOCKET_OP_CLOSE) { nc->flags |= MG_F_SEND_AND_CLOSE; } } void mg_printf_websocket_frame(struct mg_connection *nc, int op, const char *fmt, ...) { char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem; va_list ap; int len; va_start(ap, fmt); if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) { mg_send_websocket_frame(nc, op, buf, len); } va_end(ap); if (buf != mem && buf != NULL) { MG_FREE(buf); } } MG_INTERNAL void mg_ws_handler(struct mg_connection *nc, int ev, void *ev_data MG_UD_ARG(void *user_data)) { mg_call(nc, nc->handler, nc->user_data, ev, ev_data); switch (ev) { case MG_EV_RECV: do { } while (mg_deliver_websocket_data(nc)); break; case MG_EV_POLL: /* Ping idle websocket connections */ { time_t now = *(time_t *) ev_data; if (nc->flags & MG_F_IS_WEBSOCKET && now > nc->last_io_time + MG_WEBSOCKET_PING_INTERVAL_SECONDS) { mg_send_websocket_frame(nc, WEBSOCKET_OP_PING, "", 0); } } break; default: break; } #if MG_ENABLE_CALLBACK_USERDATA (void) user_data; #endif } #ifndef MG_EXT_SHA1 void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[], const size_t *msg_lens, uint8_t *digest) { size_t i; cs_sha1_ctx sha_ctx; cs_sha1_init(&sha_ctx); for (i = 0; i < num_msgs; i++) { cs_sha1_update(&sha_ctx, msgs[i], msg_lens[i]); } cs_sha1_final(digest, &sha_ctx); } #else extern void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[], const size_t *msg_lens, uint8_t *digest); #endif MG_INTERNAL void mg_ws_handshake(struct mg_connection *nc, const struct mg_str *key, struct http_message *hm) { static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; const uint8_t *msgs[2] = {(const uint8_t *) key->p, (const uint8_t *) magic}; const size_t msg_lens[2] = {key->len, 36}; unsigned char sha[20]; char b64_sha[30]; struct mg_str *s; mg_hash_sha1_v(2, msgs, msg_lens, sha); mg_base64_encode(sha, sizeof(sha), b64_sha); mg_printf(nc, "%s", "HTTP/1.1 101 Switching Protocols\r\n" "Upgrade: websocket\r\n" "Connection: Upgrade\r\n"); s = mg_get_http_header(hm, "Sec-WebSocket-Protocol"); if (s != NULL) { mg_printf(nc, "Sec-WebSocket-Protocol: %.*s\r\n", (int) s->len, s->p); } mg_printf(nc, "Sec-WebSocket-Accept: %s%s", b64_sha, "\r\n\r\n"); DBG(("%p %.*s %s", nc, (int) key->len, key->p, b64_sha)); } void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path, const char *host, const char *protocol, const char *extra_headers) { mg_send_websocket_handshake3(nc, path, host, protocol, extra_headers, NULL, NULL); } void mg_send_websocket_handshake3(struct mg_connection *nc, const char *path, const char *host, const char *protocol, const char *extra_headers, const char *user, const char *pass) { mg_send_websocket_handshake3v(nc, mg_mk_str(path), mg_mk_str(host), mg_mk_str(protocol), mg_mk_str(extra_headers), mg_mk_str(user), mg_mk_str(pass)); } void mg_send_websocket_handshake3v(struct mg_connection *nc, const struct mg_str path, const struct mg_str host, const struct mg_str protocol, const struct mg_str extra_headers, const struct mg_str user, const struct mg_str pass) { struct mbuf auth; char key[25]; uint32_t nonce[4]; nonce[0] = mg_ws_random_mask(); nonce[1] = mg_ws_random_mask(); nonce[2] = mg_ws_random_mask(); nonce[3] = mg_ws_random_mask(); mg_base64_encode((unsigned char *) &nonce, sizeof(nonce), key); mbuf_init(&auth, 0); if (user.len > 0) { mg_basic_auth_header(user, pass, &auth); } /* * NOTE: the (auth.buf == NULL ? "" : auth.buf) is because cc3200 libc is * broken: it doesn't like zero length to be passed to %.*s * i.e. sprintf("f%.*so", (int)0, NULL), yields `f\0o`. * because it handles NULL specially (and incorrectly). */ mg_printf(nc, "GET %.*s HTTP/1.1\r\n" "Upgrade: websocket\r\n" "Connection: Upgrade\r\n" "%.*s" "Sec-WebSocket-Version: 13\r\n" "Sec-WebSocket-Key: %s\r\n", (int) path.len, path.p, (int) auth.len, (auth.buf == NULL ? "" : auth.buf), key); /* TODO(mkm): take default hostname from http proto data if host == NULL */ if (host.len > 0) { int host_len = (int) (path.p - host.p); /* Account for possible :PORT */ mg_printf(nc, "Host: %.*s\r\n", host_len, host.p); } if (protocol.len > 0) { mg_printf(nc, "Sec-WebSocket-Protocol: %.*s\r\n", (int) protocol.len, protocol.p); } if (extra_headers.len > 0) { mg_printf(nc, "%.*s", (int) extra_headers.len, extra_headers.p); } mg_printf(nc, "\r\n"); nc->flags |= MG_F_IS_WEBSOCKET; mbuf_free(&auth); } void mg_send_websocket_handshake(struct mg_connection *nc, const char *path, const char *extra_headers) { struct mg_str null_str = MG_NULL_STR; mg_send_websocket_handshake3v( nc, mg_mk_str(path), null_str /* host */, null_str /* protocol */, mg_mk_str(extra_headers), null_str /* user */, null_str /* pass */); } struct mg_connection *mg_connect_ws_opt( struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), struct mg_connect_opts opts, const char *url, const char *protocol, const char *extra_headers) { struct mg_str null_str = MG_NULL_STR; struct mg_str host = MG_NULL_STR, path = MG_NULL_STR, user_info = MG_NULL_STR; struct mg_connection *nc = mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http", "ws", "https", "wss", url, &path, &user_info, &host); if (nc != NULL) { mg_send_websocket_handshake3v(nc, path, host, mg_mk_str(protocol), mg_mk_str(extra_headers), user_info, null_str); } return nc; } struct mg_connection *mg_connect_ws( struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), const char *url, const char *protocol, const char *extra_headers) { struct mg_connect_opts opts; memset(&opts, 0, sizeof(opts)); return mg_connect_ws_opt(mgr, MG_CB(ev_handler, user_data), opts, url, protocol, extra_headers); } #endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_util.c" #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ /* Amalgamated: #include "common/cs_base64.h" */ /* Amalgamated: #include "mg_internal.h" */ /* Amalgamated: #include "mg_util.h" */ /* For platforms with limited libc */ #ifndef MAX #define MAX(a, b) ((a) > (b) ? (a) : (b)) #endif const char *mg_skip(const char *s, const char *end, const char *delims, struct mg_str *v) { v->p = s; while (s < end && strchr(delims, *(unsigned char *) s) == NULL) s++; v->len = s - v->p; while (s < end && strchr(delims, *(unsigned char *) s) != NULL) s++; return s; } #if MG_ENABLE_FILESYSTEM && !defined(MG_USER_FILE_FUNCTIONS) int mg_stat(const char *path, cs_stat_t *st) { #ifdef _WIN32 wchar_t wpath[MG_MAX_PATH]; to_wchar(path, wpath, ARRAY_SIZE(wpath)); DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st))); return _wstati64(wpath, st); #else return stat(path, st); #endif } FILE *mg_fopen(const char *path, const char *mode) { #ifdef _WIN32 wchar_t wpath[MG_MAX_PATH], wmode[10]; to_wchar(path, wpath, ARRAY_SIZE(wpath)); to_wchar(mode, wmode, ARRAY_SIZE(wmode)); return _wfopen(wpath, wmode); #else return fopen(path, mode); #endif } int mg_open(const char *path, int flag, int mode) { /* LCOV_EXCL_LINE */ #if defined(_WIN32) && !defined(WINCE) wchar_t wpath[MG_MAX_PATH]; to_wchar(path, wpath, ARRAY_SIZE(wpath)); return _wopen(wpath, flag, mode); #else return open(path, flag, mode); /* LCOV_EXCL_LINE */ #endif } size_t mg_fread(void *ptr, size_t size, size_t count, FILE *f) { return fread(ptr, size, count, f); } size_t mg_fwrite(const void *ptr, size_t size, size_t count, FILE *f) { return fwrite(ptr, size, count, f); } #endif void mg_base64_encode(const unsigned char *src, int src_len, char *dst) { cs_base64_encode(src, src_len, dst); } int mg_base64_decode(const unsigned char *s, int len, char *dst) { return cs_base64_decode(s, len, dst, NULL); } #if MG_ENABLE_THREADS void *mg_start_thread(void *(*f)(void *), void *p) { #ifdef WINCE return (void *) CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) f, p, 0, NULL); #elif defined(_WIN32) return (void *) _beginthread((void(__cdecl *) (void *) ) f, 0, p); #else pthread_t thread_id = (pthread_t) 0; pthread_attr_t attr; (void) pthread_attr_init(&attr); (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); #if defined(MG_STACK_SIZE) && MG_STACK_SIZE > 1 (void) pthread_attr_setstacksize(&attr, MG_STACK_SIZE); #endif pthread_create(&thread_id, &attr, f, p); pthread_attr_destroy(&attr); return (void *) thread_id; #endif } #endif /* MG_ENABLE_THREADS */ /* Set close-on-exec bit for a given socket. */ void mg_set_close_on_exec(sock_t sock) { #if defined(_WIN32) && !defined(WINCE) (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0); #elif defined(__unix__) fcntl(sock, F_SETFD, FD_CLOEXEC); #else (void) sock; #endif } int mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len, int flags) { int is_v6; if (buf == NULL || len <= 0) return 0; memset(buf, 0, len); #if MG_ENABLE_IPV6 is_v6 = sa->sa.sa_family == AF_INET6; #else is_v6 = 0; #endif if (flags & MG_SOCK_STRINGIFY_IP) { #if MG_ENABLE_IPV6 const void *addr = NULL; char *start = buf; socklen_t capacity = len; if (!is_v6) { addr = &sa->sin.sin_addr; } else { addr = (void *) &sa->sin6.sin6_addr; if (flags & MG_SOCK_STRINGIFY_PORT) { *buf = '['; start++; capacity--; } } if (inet_ntop(sa->sa.sa_family, addr, start, capacity) == NULL) { goto cleanup; } #elif defined(_WIN32) || MG_LWIP || (MG_NET_IF == MG_NET_IF_PIC32) /* Only Windoze Vista (and newer) have inet_ntop() */ char *addr_str = inet_ntoa(sa->sin.sin_addr); if (addr_str != NULL) { strncpy(buf, inet_ntoa(sa->sin.sin_addr), len - 1); } else { goto cleanup; } #else if (inet_ntop(AF_INET, (void *) &sa->sin.sin_addr, buf, len) == NULL) { goto cleanup; } #endif } if (flags & MG_SOCK_STRINGIFY_PORT) { int port = ntohs(sa->sin.sin_port); if (flags & MG_SOCK_STRINGIFY_IP) { int buf_len = strlen(buf); snprintf(buf + buf_len, len - (buf_len + 1), "%s:%d", (is_v6 ? "]" : ""), port); } else { snprintf(buf, len, "%d", port); } } return strlen(buf); cleanup: *buf = '\0'; return 0; } int mg_conn_addr_to_str(struct mg_connection *nc, char *buf, size_t len, int flags) { union socket_address sa; memset(&sa, 0, sizeof(sa)); mg_if_get_conn_addr(nc, flags & MG_SOCK_STRINGIFY_REMOTE, &sa); return mg_sock_addr_to_str(&sa, buf, len, flags); } #if MG_ENABLE_HEXDUMP static int mg_hexdump_n(const void *buf, int len, char *dst, int dst_len, int offset) { const unsigned char *p = (const unsigned char *) buf; char ascii[17] = ""; int i, idx, n = 0; for (i = 0; i < len; i++) { idx = i % 16; if (idx == 0) { if (i > 0) n += snprintf(dst + n, MAX(dst_len - n, 0), " %s\n", ascii); n += snprintf(dst + n, MAX(dst_len - n, 0), "%04x ", i + offset); } if (dst_len - n < 0) { return n; } n += snprintf(dst + n, MAX(dst_len - n, 0), " %02x", p[i]); ascii[idx] = p[i] < 0x20 || p[i] > 0x7e ? '.' : p[i]; ascii[idx + 1] = '\0'; } while (i++ % 16) n += snprintf(dst + n, MAX(dst_len - n, 0), "%s", " "); n += snprintf(dst + n, MAX(dst_len - n, 0), " %s\n", ascii); return n; } int mg_hexdump(const void *buf, int len, char *dst, int dst_len) { return mg_hexdump_n(buf, len, dst, dst_len, 0); } void mg_hexdumpf(FILE *fp, const void *buf, int len) { char tmp[80]; int offset = 0, n; while (len > 0) { n = (len < 16 ? len : 16); mg_hexdump_n(((const char *) buf) + offset, n, tmp, sizeof(tmp), offset); fputs(tmp, fp); offset += n; len -= n; } } void mg_hexdump_connection(struct mg_connection *nc, const char *path, const void *buf, int num_bytes, int ev) { FILE *fp = NULL; char src[60], dst[60]; const char *tag = NULL; switch (ev) { case MG_EV_RECV: tag = "<-"; break; case MG_EV_SEND: tag = "->"; break; case MG_EV_ACCEPT: tag = "<A"; break; case MG_EV_CONNECT: tag = "C>"; break; case MG_EV_CLOSE: tag = "XX"; break; } if (tag == NULL) return; /* Don't log MG_EV_TIMER, etc */ if (strcmp(path, "-") == 0) { fp = stdout; } else if (strcmp(path, "--") == 0) { fp = stderr; #if MG_ENABLE_FILESYSTEM } else { fp = mg_fopen(path, "a"); #endif } if (fp == NULL) return; mg_conn_addr_to_str(nc, src, sizeof(src), MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT); mg_conn_addr_to_str(nc, dst, sizeof(dst), MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT | MG_SOCK_STRINGIFY_REMOTE); fprintf(fp, "%lu %p %s %s %s %d\n", (unsigned long) mg_time(), (void *) nc, src, tag, dst, (int) num_bytes); if (num_bytes > 0) { mg_hexdumpf(fp, buf, num_bytes); } if (fp != stdout && fp != stderr) fclose(fp); } #endif int mg_is_big_endian(void) { static const int n = 1; /* TODO(mkm) use compiletime check with 4-byte char literal */ return ((char *) &n)[0] == 0; } DO_NOT_WARN_UNUSED MG_INTERNAL int mg_get_errno(void) { #ifndef WINCE return errno; #else /* TODO(alashkin): translate error codes? */ return GetLastError(); #endif } void mg_mbuf_append_base64_putc(char ch, void *user_data) { struct mbuf *mbuf = (struct mbuf *) user_data; mbuf_append(mbuf, &ch, sizeof(ch)); } void mg_mbuf_append_base64(struct mbuf *mbuf, const void *data, size_t len) { struct cs_base64_ctx ctx; cs_base64_init(&ctx, mg_mbuf_append_base64_putc, mbuf); cs_base64_update(&ctx, (const char *) data, len); cs_base64_finish(&ctx); } void mg_basic_auth_header(const struct mg_str user, const struct mg_str pass, struct mbuf *buf) { const char *header_prefix = "Authorization: Basic "; const char *header_suffix = "\r\n"; struct cs_base64_ctx ctx; cs_base64_init(&ctx, mg_mbuf_append_base64_putc, buf); mbuf_append(buf, header_prefix, strlen(header_prefix)); cs_base64_update(&ctx, user.p, user.len); if (pass.len > 0) { cs_base64_update(&ctx, ":", 1); cs_base64_update(&ctx, pass.p, pass.len); } cs_base64_finish(&ctx); mbuf_append(buf, header_suffix, strlen(header_suffix)); } struct mg_str mg_url_encode_opt(const struct mg_str src, const struct mg_str safe, unsigned int flags) { const char *hex = (flags & MG_URL_ENCODE_F_UPPERCASE_HEX ? "0123456789ABCDEF" : "0123456789abcdef"); size_t i = 0; struct mbuf mb; mbuf_init(&mb, src.len); for (i = 0; i < src.len; i++) { const unsigned char c = *((const unsigned char *) src.p + i); if (isalnum(c) || mg_strchr(safe, c) != NULL) { mbuf_append(&mb, &c, 1); } else if (c == ' ' && (flags & MG_URL_ENCODE_F_SPACE_AS_PLUS)) { mbuf_append(&mb, "+", 1); } else { mbuf_append(&mb, "%", 1); mbuf_append(&mb, &hex[c >> 4], 1); mbuf_append(&mb, &hex[c & 15], 1); } } mbuf_append(&mb, "", 1); mbuf_trim(&mb); return mg_mk_str_n(mb.buf, mb.len - 1); } struct mg_str mg_url_encode(const struct mg_str src) { return mg_url_encode_opt(src, mg_mk_str("._-$,;~()/"), 0); } #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_mqtt.c" #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ #if MG_ENABLE_MQTT #include <string.h> /* Amalgamated: #include "mg_internal.h" */ /* Amalgamated: #include "mg_mqtt.h" */ static uint16_t getu16(const char *p) { const uint8_t *up = (const uint8_t *) p; return (up[0] << 8) + up[1]; } static const char *scanto(const char *p, struct mg_str *s) { s->len = getu16(p); s->p = p + 2; return s->p + s->len; } MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm) { uint8_t header; size_t len = 0, len_len = 0; const char *p, *end; unsigned char lc = 0; int cmd; if (io->len < 2) return MG_MQTT_ERROR_INCOMPLETE_MSG; header = io->buf[0]; cmd = header >> 4; /* decode mqtt variable length */ len = len_len = 0; p = io->buf + 1; while ((size_t)(p - io->buf) < io->len) { lc = *((const unsigned char *) p++); len += (lc & 0x7f) << 7 * len_len; len_len++; if (!(lc & 0x80)) break; if (len_len > 4) return MG_MQTT_ERROR_MALFORMED_MSG; } end = p + len; if (lc & 0x80 || len > (io->len - (p - io->buf))) { return MG_MQTT_ERROR_INCOMPLETE_MSG; } mm->cmd = cmd; mm->qos = MG_MQTT_GET_QOS(header); switch (cmd) { case MG_MQTT_CMD_CONNECT: { p = scanto(p, &mm->protocol_name); if (p > end - 4) return MG_MQTT_ERROR_MALFORMED_MSG; mm->protocol_version = *(uint8_t *) p++; mm->connect_flags = *(uint8_t *) p++; mm->keep_alive_timer = getu16(p); p += 2; if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; p = scanto(p, &mm->client_id); if (p > end) return MG_MQTT_ERROR_MALFORMED_MSG; if (mm->connect_flags & MG_MQTT_HAS_WILL) { if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; p = scanto(p, &mm->will_topic); } if (mm->connect_flags & MG_MQTT_HAS_WILL) { if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; p = scanto(p, &mm->will_message); } if (mm->connect_flags & MG_MQTT_HAS_USER_NAME) { if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; p = scanto(p, &mm->user_name); } if (mm->connect_flags & MG_MQTT_HAS_PASSWORD) { if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; p = scanto(p, &mm->password); } if (p != end) return MG_MQTT_ERROR_MALFORMED_MSG; LOG(LL_DEBUG, ("%d %2x %d proto [%.*s] client_id [%.*s] will_topic [%.*s] " "will_msg [%.*s] user_name [%.*s] password [%.*s]", (int) len, (int) mm->connect_flags, (int) mm->keep_alive_timer, (int) mm->protocol_name.len, mm->protocol_name.p, (int) mm->client_id.len, mm->client_id.p, (int) mm->will_topic.len, mm->will_topic.p, (int) mm->will_message.len, mm->will_message.p, (int) mm->user_name.len, mm->user_name.p, (int) mm->password.len, mm->password.p)); break; } case MG_MQTT_CMD_CONNACK: if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG; mm->connack_ret_code = p[1]; break; case MG_MQTT_CMD_PUBACK: case MG_MQTT_CMD_PUBREC: case MG_MQTT_CMD_PUBREL: case MG_MQTT_CMD_PUBCOMP: case MG_MQTT_CMD_SUBACK: mm->message_id = getu16(p); break; case MG_MQTT_CMD_PUBLISH: { p = scanto(p, &mm->topic); if (p > end) return MG_MQTT_ERROR_MALFORMED_MSG; if (mm->qos > 0) { if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG; mm->message_id = getu16(p); p += 2; } mm->payload.p = p; mm->payload.len = end - p; break; } case MG_MQTT_CMD_SUBSCRIBE: if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG; mm->message_id = getu16(p); p += 2; /* * topic expressions are left in the payload and can be parsed with * `mg_mqtt_next_subscribe_topic` */ mm->payload.p = p; mm->payload.len = end - p; break; default: /* Unhandled command */ break; } mm->len = end - io->buf; return mm->len; } static void mqtt_handler(struct mg_connection *nc, int ev, void *ev_data MG_UD_ARG(void *user_data)) { struct mbuf *io = &nc->recv_mbuf; struct mg_mqtt_message mm; memset(&mm, 0, sizeof(mm)); nc->handler(nc, ev, ev_data MG_UD_ARG(user_data)); switch (ev) { case MG_EV_ACCEPT: if (nc->proto_data == NULL) mg_set_protocol_mqtt(nc); break; case MG_EV_RECV: { /* There can be multiple messages in the buffer, process them all. */ while (1) { int len = parse_mqtt(io, &mm); if (len < 0) { if (len == MG_MQTT_ERROR_MALFORMED_MSG) { /* Protocol error. */ nc->flags |= MG_F_CLOSE_IMMEDIATELY; } else if (len == MG_MQTT_ERROR_INCOMPLETE_MSG) { /* Not fully buffered, let's check if we have a chance to get more * data later */ if (nc->recv_mbuf_limit > 0 && nc->recv_mbuf.len >= nc->recv_mbuf_limit) { LOG(LL_ERROR, ("%p recv buffer (%lu bytes) exceeds the limit " "%lu bytes, and not drained, closing", nc, (unsigned long) nc->recv_mbuf.len, (unsigned long) nc->recv_mbuf_limit)); nc->flags |= MG_F_CLOSE_IMMEDIATELY; } } else { /* Should never be here */ LOG(LL_ERROR, ("%p invalid len: %d, closing", nc, len)); nc->flags |= MG_F_CLOSE_IMMEDIATELY; } break; } nc->handler(nc, MG_MQTT_EVENT_BASE + mm.cmd, &mm MG_UD_ARG(user_data)); mbuf_remove(io, len); } break; } case MG_EV_POLL: { struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data; double now = mg_time(); if (pd->keep_alive > 0 && pd->last_control_time > 0 && (now - pd->last_control_time) > pd->keep_alive) { LOG(LL_DEBUG, ("Send PINGREQ")); mg_mqtt_ping(nc); } break; } } } static void mg_mqtt_proto_data_destructor(void *proto_data) { MG_FREE(proto_data); } static struct mg_str mg_mqtt_next_topic_component(struct mg_str *topic) { struct mg_str res = *topic; const char *c = mg_strchr(*topic, '/'); if (c != NULL) { res.len = (c - topic->p); topic->len -= (res.len + 1); topic->p += (res.len + 1); } else { topic->len = 0; } return res; } /* Refernce: https://mosquitto.org/man/mqtt-7.html */ int mg_mqtt_match_topic_expression(struct mg_str exp, struct mg_str topic) { struct mg_str ec, tc; if (exp.len == 0) return 0; while (1) { ec = mg_mqtt_next_topic_component(&exp); tc = mg_mqtt_next_topic_component(&topic); if (ec.len == 0) { if (tc.len != 0) return 0; if (exp.len == 0) break; continue; } if (mg_vcmp(&ec, "+") == 0) { if (tc.len == 0 && topic.len == 0) return 0; continue; } if (mg_vcmp(&ec, "#") == 0) { /* Must be the last component in the expression or it's invalid. */ return (exp.len == 0); } if (mg_strcmp(ec, tc) != 0) { return 0; } } return (tc.len == 0 && topic.len == 0); } int mg_mqtt_vmatch_topic_expression(const char *exp, struct mg_str topic) { return mg_mqtt_match_topic_expression(mg_mk_str(exp), topic); } void mg_set_protocol_mqtt(struct mg_connection *nc) { nc->proto_handler = mqtt_handler; nc->proto_data = MG_CALLOC(1, sizeof(struct mg_mqtt_proto_data)); nc->proto_data_destructor = mg_mqtt_proto_data_destructor; } static void mg_send_mqtt_header(struct mg_connection *nc, uint8_t cmd, uint8_t flags, size_t len) { struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data; uint8_t buf[1 + sizeof(size_t)]; uint8_t *vlen = &buf[1]; buf[0] = (cmd << 4) | flags; /* mqtt variable length encoding */ do { *vlen = len % 0x80; len /= 0x80; if (len > 0) *vlen |= 0x80; vlen++; } while (len > 0); mg_send(nc, buf, vlen - buf); pd->last_control_time = mg_time(); } void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id) { static struct mg_send_mqtt_handshake_opts opts; mg_send_mqtt_handshake_opt(nc, client_id, opts); } void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id, struct mg_send_mqtt_handshake_opts opts) { struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data; uint16_t id_len = 0, wt_len = 0, wm_len = 0, user_len = 0, pw_len = 0; uint16_t netbytes; size_t total_len; if (client_id != NULL) { id_len = strlen(client_id); } total_len = 7 + 1 + 2 + 2 + id_len; if (opts.user_name != NULL) { opts.flags |= MG_MQTT_HAS_USER_NAME; } if (opts.password != NULL) { opts.flags |= MG_MQTT_HAS_PASSWORD; } if (opts.will_topic != NULL && opts.will_message != NULL) { wt_len = strlen(opts.will_topic); wm_len = strlen(opts.will_message); opts.flags |= MG_MQTT_HAS_WILL; } if (opts.keep_alive == 0) { opts.keep_alive = 60; } if (opts.flags & MG_MQTT_HAS_WILL) { total_len += 2 + wt_len + 2 + wm_len; } if (opts.flags & MG_MQTT_HAS_USER_NAME) { user_len = strlen(opts.user_name); total_len += 2 + user_len; } if (opts.flags & MG_MQTT_HAS_PASSWORD) { pw_len = strlen(opts.password); total_len += 2 + pw_len; } mg_send_mqtt_header(nc, MG_MQTT_CMD_CONNECT, 0, total_len); mg_send(nc, "\00\04MQTT\04", 7); mg_send(nc, &opts.flags, 1); netbytes = htons(opts.keep_alive); mg_send(nc, &netbytes, 2); netbytes = htons(id_len); mg_send(nc, &netbytes, 2); mg_send(nc, client_id, id_len); if (opts.flags & MG_MQTT_HAS_WILL) { netbytes = htons(wt_len); mg_send(nc, &netbytes, 2); mg_send(nc, opts.will_topic, wt_len); netbytes = htons(wm_len); mg_send(nc, &netbytes, 2); mg_send(nc, opts.will_message, wm_len); } if (opts.flags & MG_MQTT_HAS_USER_NAME) { netbytes = htons(user_len); mg_send(nc, &netbytes, 2); mg_send(nc, opts.user_name, user_len); } if (opts.flags & MG_MQTT_HAS_PASSWORD) { netbytes = htons(pw_len); mg_send(nc, &netbytes, 2); mg_send(nc, opts.password, pw_len); } if (pd != NULL) { pd->keep_alive = opts.keep_alive; } } void mg_mqtt_publish(struct mg_connection *nc, const char *topic, uint16_t message_id, int flags, const void *data, size_t len) { uint16_t netbytes; uint16_t topic_len = strlen(topic); size_t total_len = 2 + topic_len + len; if (MG_MQTT_GET_QOS(flags) > 0) { total_len += 2; } mg_send_mqtt_header(nc, MG_MQTT_CMD_PUBLISH, flags, total_len); netbytes = htons(topic_len); mg_send(nc, &netbytes, 2); mg_send(nc, topic, topic_len); if (MG_MQTT_GET_QOS(flags) > 0) { netbytes = htons(message_id); mg_send(nc, &netbytes, 2); } mg_send(nc, data, len); } void mg_mqtt_subscribe(struct mg_connection *nc, const struct mg_mqtt_topic_expression *topics, size_t topics_len, uint16_t message_id) { uint16_t netbytes; size_t i; uint16_t topic_len; size_t total_len = 2; for (i = 0; i < topics_len; i++) { total_len += 2 + strlen(topics[i].topic) + 1; } mg_send_mqtt_header(nc, MG_MQTT_CMD_SUBSCRIBE, MG_MQTT_QOS(1), total_len); netbytes = htons(message_id); mg_send(nc, (char *) &netbytes, 2); for (i = 0; i < topics_len; i++) { topic_len = strlen(topics[i].topic); netbytes = htons(topic_len); mg_send(nc, &netbytes, 2); mg_send(nc, topics[i].topic, topic_len); mg_send(nc, &topics[i].qos, 1); } } int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg, struct mg_str *topic, uint8_t *qos, int pos) { unsigned char *buf = (unsigned char *) msg->payload.p + pos; int new_pos; if ((size_t) pos >= msg->payload.len) return -1; topic->len = buf[0] << 8 | buf[1]; topic->p = (char *) buf + 2; new_pos = pos + 2 + topic->len + 1; if ((size_t) new_pos > msg->payload.len) return -1; *qos = buf[2 + topic->len]; return new_pos; } void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics, size_t topics_len, uint16_t message_id) { uint16_t netbytes; size_t i; uint16_t topic_len; size_t total_len = 2; for (i = 0; i < topics_len; i++) { total_len += 2 + strlen(topics[i]); } mg_send_mqtt_header(nc, MG_MQTT_CMD_UNSUBSCRIBE, MG_MQTT_QOS(1), total_len); netbytes = htons(message_id); mg_send(nc, (char *) &netbytes, 2); for (i = 0; i < topics_len; i++) { topic_len = strlen(topics[i]); netbytes = htons(topic_len); mg_send(nc, &netbytes, 2); mg_send(nc, topics[i], topic_len); } } void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code) { uint8_t unused = 0; mg_send_mqtt_header(nc, MG_MQTT_CMD_CONNACK, 0, 2); mg_send(nc, &unused, 1); mg_send(nc, &return_code, 1); } /* * Sends a command which contains only a `message_id` and a QoS level of 1. * * Helper function. */ static void mg_send_mqtt_short_command(struct mg_connection *nc, uint8_t cmd, uint16_t message_id) { uint16_t netbytes; uint8_t flags = (cmd == MG_MQTT_CMD_PUBREL ? 2 : 0); mg_send_mqtt_header(nc, cmd, flags, 2 /* len */); netbytes = htons(message_id); mg_send(nc, &netbytes, 2); } void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id) { mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBACK, message_id); } void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id) { mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREC, message_id); } void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id) { mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREL, message_id); } void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id) { mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBCOMP, message_id); } void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len, uint16_t message_id) { size_t i; uint16_t netbytes; mg_send_mqtt_header(nc, MG_MQTT_CMD_SUBACK, MG_MQTT_QOS(1), 2 + qoss_len); netbytes = htons(message_id); mg_send(nc, &netbytes, 2); for (i = 0; i < qoss_len; i++) { mg_send(nc, &qoss[i], 1); } } void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id) { mg_send_mqtt_short_command(nc, MG_MQTT_CMD_UNSUBACK, message_id); } void mg_mqtt_ping(struct mg_connection *nc) { mg_send_mqtt_header(nc, MG_MQTT_CMD_PINGREQ, 0, 0); } void mg_mqtt_pong(struct mg_connection *nc) { mg_send_mqtt_header(nc, MG_MQTT_CMD_PINGRESP, 0, 0); } void mg_mqtt_disconnect(struct mg_connection *nc) { mg_send_mqtt_header(nc, MG_MQTT_CMD_DISCONNECT, 0, 0); } #endif /* MG_ENABLE_MQTT */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_mqtt_server.c" #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ /* Amalgamated: #include "mg_internal.h" */ /* Amalgamated: #include "mg_mqtt_server.h" */ #if MG_ENABLE_MQTT_BROKER static void mg_mqtt_session_init(struct mg_mqtt_broker *brk, struct mg_mqtt_session *s, struct mg_connection *nc) { s->brk = brk; s->subscriptions = NULL; s->num_subscriptions = 0; s->nc = nc; } static void mg_mqtt_add_session(struct mg_mqtt_session *s) { LIST_INSERT_HEAD(&s->brk->sessions, s, link); } static void mg_mqtt_remove_session(struct mg_mqtt_session *s) { LIST_REMOVE(s, link); } static void mg_mqtt_destroy_session(struct mg_mqtt_session *s) { size_t i; for (i = 0; i < s->num_subscriptions; i++) { MG_FREE((void *) s->subscriptions[i].topic); } MG_FREE(s->subscriptions); MG_FREE(s); } static void mg_mqtt_close_session(struct mg_mqtt_session *s) { mg_mqtt_remove_session(s); mg_mqtt_destroy_session(s); } void mg_mqtt_broker_init(struct mg_mqtt_broker *brk, void *user_data) { LIST_INIT(&brk->sessions); brk->user_data = user_data; } static void mg_mqtt_broker_handle_connect(struct mg_mqtt_broker *brk, struct mg_connection *nc) { struct mg_mqtt_session *s = (struct mg_mqtt_session *) MG_CALLOC(1, sizeof *s); if (s == NULL) { /* LCOV_EXCL_START */ mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE); return; /* LCOV_EXCL_STOP */ } /* TODO(mkm): check header (magic and version) */ mg_mqtt_session_init(brk, s, nc); nc->priv_2 = s; mg_mqtt_add_session(s); mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_ACCEPTED); } static void mg_mqtt_broker_handle_subscribe(struct mg_connection *nc, struct mg_mqtt_message *msg) { struct mg_mqtt_session *ss = (struct mg_mqtt_session *) nc->priv_2; uint8_t qoss[MG_MQTT_MAX_SESSION_SUBSCRIPTIONS]; size_t num_subs = 0; struct mg_str topic; uint8_t qos; int pos; struct mg_mqtt_topic_expression *te; for (pos = 0; (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;) { if (num_subs >= sizeof(MG_MQTT_MAX_SESSION_SUBSCRIPTIONS) || (ss->num_subscriptions + num_subs >= MG_MQTT_MAX_SESSION_SUBSCRIPTIONS)) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; return; } qoss[num_subs++] = qos; } if (num_subs > 0) { te = (struct mg_mqtt_topic_expression *) MG_REALLOC( ss->subscriptions, sizeof(*ss->subscriptions) * (ss->num_subscriptions + num_subs)); if (te == NULL) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; return; } ss->subscriptions = te; for (pos = 0; pos < (int) msg->payload.len && (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1; ss->num_subscriptions++) { te = &ss->subscriptions[ss->num_subscriptions]; te->topic = (char *) MG_MALLOC(topic.len + 1); te->qos = qos; memcpy((char *) te->topic, topic.p, topic.len); ((char *) te->topic)[topic.len] = '\0'; } } if (pos == (int) msg->payload.len) { mg_mqtt_suback(nc, qoss, num_subs, msg->message_id); } else { /* We did not fully parse the payload, something must be wrong. */ nc->flags |= MG_F_CLOSE_IMMEDIATELY; } } static void mg_mqtt_broker_handle_publish(struct mg_mqtt_broker *brk, struct mg_mqtt_message *msg) { struct mg_mqtt_session *s; size_t i; for (s = mg_mqtt_next(brk, NULL); s != NULL; s = mg_mqtt_next(brk, s)) { for (i = 0; i < s->num_subscriptions; i++) { if (mg_mqtt_vmatch_topic_expression(s->subscriptions[i].topic, msg->topic)) { char buf[100], *p = buf; mg_asprintf(&p, sizeof(buf), "%.*s", (int) msg->topic.len, msg->topic.p); if (p == NULL) { return; } mg_mqtt_publish(s->nc, p, 0, 0, msg->payload.p, msg->payload.len); if (p != buf) { MG_FREE(p); } break; } } } } void mg_mqtt_broker(struct mg_connection *nc, int ev, void *data) { struct mg_mqtt_message *msg = (struct mg_mqtt_message *) data; struct mg_mqtt_broker *brk; if (nc->listener) { brk = (struct mg_mqtt_broker *) nc->listener->priv_2; } else { brk = (struct mg_mqtt_broker *) nc->priv_2; } switch (ev) { case MG_EV_ACCEPT: if (nc->proto_data == NULL) mg_set_protocol_mqtt(nc); nc->priv_2 = NULL; /* Clear up the inherited pointer to broker */ break; case MG_EV_MQTT_CONNECT: if (nc->priv_2 == NULL) { mg_mqtt_broker_handle_connect(brk, nc); } else { /* Repeated CONNECT */ nc->flags |= MG_F_CLOSE_IMMEDIATELY; } break; case MG_EV_MQTT_SUBSCRIBE: if (nc->priv_2 != NULL) { mg_mqtt_broker_handle_subscribe(nc, msg); } else { /* Subscribe before CONNECT */ nc->flags |= MG_F_CLOSE_IMMEDIATELY; } break; case MG_EV_MQTT_PUBLISH: if (nc->priv_2 != NULL) { mg_mqtt_broker_handle_publish(brk, msg); } else { /* Publish before CONNECT */ nc->flags |= MG_F_CLOSE_IMMEDIATELY; } break; case MG_EV_CLOSE: if (nc->listener && nc->priv_2 != NULL) { mg_mqtt_close_session((struct mg_mqtt_session *) nc->priv_2); } break; } } struct mg_mqtt_session *mg_mqtt_next(struct mg_mqtt_broker *brk, struct mg_mqtt_session *s) { return s == NULL ? LIST_FIRST(&brk->sessions) : LIST_NEXT(s, link); } #endif /* MG_ENABLE_MQTT_BROKER */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_dns.c" #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ #if MG_ENABLE_DNS /* Amalgamated: #include "mg_internal.h" */ /* Amalgamated: #include "mg_dns.h" */ static int mg_dns_tid = 0xa0; struct mg_dns_header { uint16_t transaction_id; uint16_t flags; uint16_t num_questions; uint16_t num_answers; uint16_t num_authority_prs; uint16_t num_other_prs; }; struct mg_dns_resource_record *mg_dns_next_record( struct mg_dns_message *msg, int query, struct mg_dns_resource_record *prev) { struct mg_dns_resource_record *rr; for (rr = (prev == NULL ? msg->answers : prev + 1); rr - msg->answers < msg->num_answers; rr++) { if (rr->rtype == query) { return rr; } } return NULL; } int mg_dns_parse_record_data(struct mg_dns_message *msg, struct mg_dns_resource_record *rr, void *data, size_t data_len) { switch (rr->rtype) { case MG_DNS_A_RECORD: if (data_len < sizeof(struct in_addr)) { return -1; } if (rr->rdata.p + data_len > msg->pkt.p + msg->pkt.len) { return -1; } memcpy(data, rr->rdata.p, data_len); return 0; #if MG_ENABLE_IPV6 case MG_DNS_AAAA_RECORD: if (data_len < sizeof(struct in6_addr)) { return -1; /* LCOV_EXCL_LINE */ } memcpy(data, rr->rdata.p, data_len); return 0; #endif case MG_DNS_CNAME_RECORD: mg_dns_uncompress_name(msg, &rr->rdata, (char *) data, data_len); return 0; } return -1; } int mg_dns_insert_header(struct mbuf *io, size_t pos, struct mg_dns_message *msg) { struct mg_dns_header header; memset(&header, 0, sizeof(header)); header.transaction_id = msg->transaction_id; header.flags = htons(msg->flags); header.num_questions = htons(msg->num_questions); header.num_answers = htons(msg->num_answers); return mbuf_insert(io, pos, &header, sizeof(header)); } int mg_dns_copy_questions(struct mbuf *io, struct mg_dns_message *msg) { unsigned char *begin, *end; struct mg_dns_resource_record *last_q; if (msg->num_questions <= 0) return 0; begin = (unsigned char *) msg->pkt.p + sizeof(struct mg_dns_header); last_q = &msg->questions[msg->num_questions - 1]; end = (unsigned char *) last_q->name.p + last_q->name.len + 4; return mbuf_append(io, begin, end - begin); } int mg_dns_encode_name(struct mbuf *io, const char *name, size_t len) { const char *s; unsigned char n; size_t pos = io->len; do { if ((s = strchr(name, '.')) == NULL) { s = name + len; } if (s - name > 127) { return -1; /* TODO(mkm) cover */ } n = s - name; /* chunk length */ mbuf_append(io, &n, 1); /* send length */ mbuf_append(io, name, n); if (*s == '.') { n++; } name += n; len -= n; } while (*s != '\0'); mbuf_append(io, "\0", 1); /* Mark end of host name */ return io->len - pos; } int mg_dns_encode_record(struct mbuf *io, struct mg_dns_resource_record *rr, const char *name, size_t nlen, const void *rdata, size_t rlen) { size_t pos = io->len; uint16_t u16; uint32_t u32; if (rr->kind == MG_DNS_INVALID_RECORD) { return -1; /* LCOV_EXCL_LINE */ } if (mg_dns_encode_name(io, name, nlen) == -1) { return -1; } u16 = htons(rr->rtype); mbuf_append(io, &u16, 2); u16 = htons(rr->rclass); mbuf_append(io, &u16, 2); if (rr->kind == MG_DNS_ANSWER) { u32 = htonl(rr->ttl); mbuf_append(io, &u32, 4); if (rr->rtype == MG_DNS_CNAME_RECORD) { int clen; /* fill size after encoding */ size_t off = io->len; mbuf_append(io, &u16, 2); if ((clen = mg_dns_encode_name(io, (const char *) rdata, rlen)) == -1) { return -1; } u16 = clen; io->buf[off] = u16 >> 8; io->buf[off + 1] = u16 & 0xff; } else { u16 = htons((uint16_t) rlen); mbuf_append(io, &u16, 2); mbuf_append(io, rdata, rlen); } } return io->len - pos; } void mg_send_dns_query(struct mg_connection *nc, const char *name, int query_type) { struct mg_dns_message *msg = (struct mg_dns_message *) MG_CALLOC(1, sizeof(*msg)); struct mbuf pkt; struct mg_dns_resource_record *rr = &msg->questions[0]; DBG(("%s %d", name, query_type)); mbuf_init(&pkt, 64 /* Start small, it'll grow as needed. */); msg->transaction_id = ++mg_dns_tid; msg->flags = 0x100; msg->num_questions = 1; mg_dns_insert_header(&pkt, 0, msg); rr->rtype = query_type; rr->rclass = 1; /* Class: inet */ rr->kind = MG_DNS_QUESTION; if (mg_dns_encode_record(&pkt, rr, name, strlen(name), NULL, 0) == -1) { /* TODO(mkm): return an error code */ goto cleanup; /* LCOV_EXCL_LINE */ } /* TCP DNS requires messages to be prefixed with len */ if (!(nc->flags & MG_F_UDP)) { uint16_t len = htons((uint16_t) pkt.len); mbuf_insert(&pkt, 0, &len, 2); } mg_send(nc, pkt.buf, pkt.len); mbuf_free(&pkt); cleanup: MG_FREE(msg); } static unsigned char *mg_parse_dns_resource_record( unsigned char *data, unsigned char *end, struct mg_dns_resource_record *rr, int reply) { unsigned char *name = data; int chunk_len, data_len; while (data < end && (chunk_len = *data)) { if (((unsigned char *) data)[0] & 0xc0) { data += 1; break; } data += chunk_len + 1; } if (data > end - 5) { return NULL; } rr->name.p = (char *) name; rr->name.len = data - name + 1; data++; rr->rtype = data[0] << 8 | data[1]; data += 2; rr->rclass = data[0] << 8 | data[1]; data += 2; rr->kind = reply ? MG_DNS_ANSWER : MG_DNS_QUESTION; if (reply) { if (data >= end - 6) { return NULL; } rr->ttl = (uint32_t) data[0] << 24 | (uint32_t) data[1] << 16 | data[2] << 8 | data[3]; data += 4; data_len = *data << 8 | *(data + 1); data += 2; rr->rdata.p = (char *) data; rr->rdata.len = data_len; data += data_len; } return data; } int mg_parse_dns(const char *buf, int len, struct mg_dns_message *msg) { struct mg_dns_header *header = (struct mg_dns_header *) buf; unsigned char *data = (unsigned char *) buf + sizeof(*header); unsigned char *end = (unsigned char *) buf + len; int i; memset(msg, 0, sizeof(*msg)); msg->pkt.p = buf; msg->pkt.len = len; if (len < (int) sizeof(*header)) return -1; msg->transaction_id = header->transaction_id; msg->flags = ntohs(header->flags); msg->num_questions = ntohs(header->num_questions); if (msg->num_questions > (int) ARRAY_SIZE(msg->questions)) { msg->num_questions = (int) ARRAY_SIZE(msg->questions); } msg->num_answers = ntohs(header->num_answers); if (msg->num_answers > (int) ARRAY_SIZE(msg->answers)) { msg->num_answers = (int) ARRAY_SIZE(msg->answers); } for (i = 0; i < msg->num_questions; i++) { data = mg_parse_dns_resource_record(data, end, &msg->questions[i], 0); if (data == NULL) return -1; } for (i = 0; i < msg->num_answers; i++) { data = mg_parse_dns_resource_record(data, end, &msg->answers[i], 1); if (data == NULL) return -1; } return 0; } size_t mg_dns_uncompress_name(struct mg_dns_message *msg, struct mg_str *name, char *dst, int dst_len) { int chunk_len, num_ptrs = 0; char *old_dst = dst; const unsigned char *data = (unsigned char *) name->p; const unsigned char *end = (unsigned char *) msg->pkt.p + msg->pkt.len; if (data >= end) { return 0; } while ((chunk_len = *data++)) { int leeway = dst_len - (dst - old_dst); if (data >= end) { return 0; } if ((chunk_len & 0xc0) == 0xc0) { uint16_t off = (data[-1] & (~0xc0)) << 8 | data[0]; if (off >= msg->pkt.len) { return 0; } /* Basic circular loop avoidance: allow up to 16 pointer hops. */ if (++num_ptrs > 15) { return 0; } data = (unsigned char *) msg->pkt.p + off; continue; } if (chunk_len > 63) { return 0; } if (chunk_len > leeway) { chunk_len = leeway; } if (data + chunk_len >= end) { return 0; } memcpy(dst, data, chunk_len); data += chunk_len; dst += chunk_len; leeway -= chunk_len; if (leeway == 0) { return dst - old_dst; } *dst++ = '.'; } if (dst != old_dst) { *--dst = 0; } return dst - old_dst; } static void dns_handler(struct mg_connection *nc, int ev, void *ev_data MG_UD_ARG(void *user_data)) { struct mbuf *io = &nc->recv_mbuf; struct mg_dns_message msg; /* Pass low-level events to the user handler */ nc->handler(nc, ev, ev_data MG_UD_ARG(user_data)); switch (ev) { case MG_EV_RECV: if (!(nc->flags & MG_F_UDP)) { mbuf_remove(&nc->recv_mbuf, 2); } if (mg_parse_dns(nc->recv_mbuf.buf, nc->recv_mbuf.len, &msg) == -1) { /* reply + recursion allowed + format error */ memset(&msg, 0, sizeof(msg)); msg.flags = 0x8081; mg_dns_insert_header(io, 0, &msg); if (!(nc->flags & MG_F_UDP)) { uint16_t len = htons((uint16_t) io->len); mbuf_insert(io, 0, &len, 2); } mg_send(nc, io->buf, io->len); } else { /* Call user handler with parsed message */ nc->handler(nc, MG_DNS_MESSAGE, &msg MG_UD_ARG(user_data)); } mbuf_remove(io, io->len); break; } } void mg_set_protocol_dns(struct mg_connection *nc) { nc->proto_handler = dns_handler; } #endif /* MG_ENABLE_DNS */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_dns_server.c" #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ #if MG_ENABLE_DNS_SERVER /* Amalgamated: #include "mg_internal.h" */ /* Amalgamated: #include "dns-server.h" */ struct mg_dns_reply mg_dns_create_reply(struct mbuf *io, struct mg_dns_message *msg) { struct mg_dns_reply rep; rep.msg = msg; rep.io = io; rep.start = io->len; /* reply + recursion allowed */ msg->flags |= 0x8080; mg_dns_copy_questions(io, msg); msg->num_answers = 0; return rep; } void mg_dns_send_reply(struct mg_connection *nc, struct mg_dns_reply *r) { size_t sent = r->io->len - r->start; mg_dns_insert_header(r->io, r->start, r->msg); if (!(nc->flags & MG_F_UDP)) { uint16_t len = htons((uint16_t) sent); mbuf_insert(r->io, r->start, &len, 2); } if (&nc->send_mbuf != r->io) { mg_send(nc, r->io->buf + r->start, r->io->len - r->start); r->io->len = r->start; } } int mg_dns_reply_record(struct mg_dns_reply *reply, struct mg_dns_resource_record *question, const char *name, int rtype, int ttl, const void *rdata, size_t rdata_len) { struct mg_dns_message *msg = (struct mg_dns_message *) reply->msg; char rname[512]; struct mg_dns_resource_record *ans = &msg->answers[msg->num_answers]; if (msg->num_answers >= MG_MAX_DNS_ANSWERS) { return -1; /* LCOV_EXCL_LINE */ } if (name == NULL) { name = rname; rname[511] = 0; mg_dns_uncompress_name(msg, &question->name, rname, sizeof(rname) - 1); } *ans = *question; ans->kind = MG_DNS_ANSWER; ans->rtype = rtype; ans->ttl = ttl; if (mg_dns_encode_record(reply->io, ans, name, strlen(name), rdata, rdata_len) == -1) { return -1; /* LCOV_EXCL_LINE */ }; msg->num_answers++; return 0; } #endif /* MG_ENABLE_DNS_SERVER */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_resolv.c" #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ #if MG_ENABLE_ASYNC_RESOLVER /* Amalgamated: #include "mg_internal.h" */ /* Amalgamated: #include "mg_resolv.h" */ #ifndef MG_DEFAULT_NAMESERVER #define MG_DEFAULT_NAMESERVER "8.8.8.8" #endif struct mg_resolve_async_request { char name[1024]; int query; mg_resolve_callback_t callback; void *data; time_t timeout; int max_retries; enum mg_resolve_err err; /* state */ time_t last_time; int retries; }; /* * Find what nameserver to use. * * Return 0 if OK, -1 if error */ static int mg_get_ip_address_of_nameserver(char *name, size_t name_len) { int ret = -1; #ifdef _WIN32 int i; LONG err; HKEY hKey, hSub; wchar_t subkey[512], value[128], *key = L"SYSTEM\\ControlSet001\\Services\\Tcpip\\Parameters\\Interfaces"; if ((err = RegOpenKeyExW(HKEY_LOCAL_MACHINE, key, 0, KEY_READ, &hKey)) != ERROR_SUCCESS) { fprintf(stderr, "cannot open reg key %S: %ld\n", key, err); ret = -1; } else { for (ret = -1, i = 0; 1; i++) { DWORD subkey_size = sizeof(subkey), type, len = sizeof(value); if (RegEnumKeyExW(hKey, i, subkey, &subkey_size, NULL, NULL, NULL, NULL) != ERROR_SUCCESS) { break; } if (RegOpenKeyExW(hKey, subkey, 0, KEY_READ, &hSub) == ERROR_SUCCESS && ((RegQueryValueExW(hSub, L"NameServer", 0, &type, (void *) value, &len) == ERROR_SUCCESS && value[0] != '\0') || (RegQueryValueExW(hSub, L"DhcpNameServer", 0, &type, (void *) value, &len) == ERROR_SUCCESS && value[0] != '\0'))) { /* * See https://github.com/cesanta/mongoose/issues/176 * The value taken from the registry can be empty, a single * IP address, or multiple IP addresses separated by comma. * If it's empty, check the next interface. * If it's multiple IP addresses, take the first one. */ wchar_t *comma = wcschr(value, ','); if (comma != NULL) { *comma = '\0'; } /* %S will convert wchar_t -> char */ snprintf(name, name_len, "%S", value); ret = 0; RegCloseKey(hSub); break; } } RegCloseKey(hKey); } #elif MG_ENABLE_FILESYSTEM && defined(MG_RESOLV_CONF_FILE_NAME) FILE *fp; char line[512]; if ((fp = mg_fopen(MG_RESOLV_CONF_FILE_NAME, "r")) == NULL) { ret = -1; } else { /* Try to figure out what nameserver to use */ for (ret = -1; fgets(line, sizeof(line), fp) != NULL;) { unsigned int a, b, c, d; if (sscanf(line, "nameserver %u.%u.%u.%u", &a, &b, &c, &d) == 4) { snprintf(name, name_len, "%u.%u.%u.%u", a, b, c, d); ret = 0; break; } } (void) fclose(fp); } #else snprintf(name, name_len, "%s", MG_DEFAULT_NAMESERVER); #endif /* _WIN32 */ return ret; } int mg_resolve_from_hosts_file(const char *name, union socket_address *usa) { #if MG_ENABLE_FILESYSTEM && defined(MG_HOSTS_FILE_NAME) /* TODO(mkm) cache /etc/hosts */ FILE *fp; char line[1024]; char *p; char alias[256]; unsigned int a, b, c, d; int len = 0; if ((fp = mg_fopen(MG_HOSTS_FILE_NAME, "r")) == NULL) { return -1; } for (; fgets(line, sizeof(line), fp) != NULL;) { if (line[0] == '#') continue; if (sscanf(line, "%u.%u.%u.%u%n", &a, &b, &c, &d, &len) == 0) { /* TODO(mkm): handle ipv6 */ continue; } for (p = line + len; sscanf(p, "%s%n", alias, &len) == 1; p += len) { if (strcmp(alias, name) == 0) { usa->sin.sin_addr.s_addr = htonl(a << 24 | b << 16 | c << 8 | d); fclose(fp); return 0; } } } fclose(fp); #else (void) name; (void) usa; #endif return -1; } static void mg_resolve_async_eh(struct mg_connection *nc, int ev, void *data MG_UD_ARG(void *user_data)) { time_t now = (time_t) mg_time(); struct mg_resolve_async_request *req; struct mg_dns_message *msg; #if !MG_ENABLE_CALLBACK_USERDATA void *user_data = nc->user_data; #endif if (ev != MG_EV_POLL) { DBG(("ev=%d user_data=%p", ev, user_data)); } req = (struct mg_resolve_async_request *) user_data; if (req == NULL) { return; } switch (ev) { case MG_EV_POLL: if (req->retries > req->max_retries) { req->err = MG_RESOLVE_EXCEEDED_RETRY_COUNT; nc->flags |= MG_F_CLOSE_IMMEDIATELY; break; } if (nc->flags & MG_F_CONNECTING) break; /* fallthrough */ case MG_EV_CONNECT: if (req->retries == 0 || now - req->last_time >= req->timeout) { mg_send_dns_query(nc, req->name, req->query); req->last_time = now; req->retries++; } break; case MG_EV_RECV: msg = (struct mg_dns_message *) MG_MALLOC(sizeof(*msg)); if (mg_parse_dns(nc->recv_mbuf.buf, *(int *) data, msg) == 0 && msg->num_answers > 0) { req->callback(msg, req->data, MG_RESOLVE_OK); nc->user_data = NULL; MG_FREE(req); } else { req->err = MG_RESOLVE_NO_ANSWERS; } MG_FREE(msg); nc->flags |= MG_F_CLOSE_IMMEDIATELY; break; case MG_EV_SEND: /* * If a send error occurs, prevent closing of the connection by the core. * We will retry after timeout. */ nc->flags &= ~MG_F_CLOSE_IMMEDIATELY; mbuf_remove(&nc->send_mbuf, nc->send_mbuf.len); break; case MG_EV_TIMER: req->err = MG_RESOLVE_TIMEOUT; nc->flags |= MG_F_CLOSE_IMMEDIATELY; break; case MG_EV_CLOSE: /* If we got here with request still not done, fire an error callback. */ if (req != NULL) { char addr[32]; mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP); #ifdef MG_LOG_DNS_FAILURES LOG(LL_ERROR, ("Failed to resolve '%s', server %s", req->name, addr)); #endif req->callback(NULL, req->data, req->err); nc->user_data = NULL; MG_FREE(req); } break; } } int mg_resolve_async(struct mg_mgr *mgr, const char *name, int query, mg_resolve_callback_t cb, void *data) { struct mg_resolve_async_opts opts; memset(&opts, 0, sizeof(opts)); return mg_resolve_async_opt(mgr, name, query, cb, data, opts); } int mg_resolve_async_opt(struct mg_mgr *mgr, const char *name, int query, mg_resolve_callback_t cb, void *data, struct mg_resolve_async_opts opts) { struct mg_resolve_async_request *req; struct mg_connection *dns_nc; const char *nameserver = opts.nameserver; char dns_server_buff[17], nameserver_url[26]; if (nameserver == NULL) { nameserver = mgr->nameserver; } DBG(("%s %d %p", name, query, opts.dns_conn)); /* resolve with DNS */ req = (struct mg_resolve_async_request *) MG_CALLOC(1, sizeof(*req)); if (req == NULL) { return -1; } strncpy(req->name, name, sizeof(req->name)); req->name[sizeof(req->name) - 1] = '\0'; req->query = query; req->callback = cb; req->data = data; /* TODO(mkm): parse defaults out of resolve.conf */ req->max_retries = opts.max_retries ? opts.max_retries : 2; req->timeout = opts.timeout ? opts.timeout : 5; /* Lazily initialize dns server */ if (nameserver == NULL) { if (mg_get_ip_address_of_nameserver(dns_server_buff, sizeof(dns_server_buff)) != -1) { nameserver = dns_server_buff; } else { nameserver = MG_DEFAULT_NAMESERVER; } } snprintf(nameserver_url, sizeof(nameserver_url), "udp://%s:53", nameserver); dns_nc = mg_connect(mgr, nameserver_url, MG_CB(mg_resolve_async_eh, NULL)); if (dns_nc == NULL) { MG_FREE(req); return -1; } dns_nc->user_data = req; if (opts.dns_conn != NULL) { *opts.dns_conn = dns_nc; } return 0; } void mg_set_nameserver(struct mg_mgr *mgr, const char *nameserver) { MG_FREE((char *) mgr->nameserver); mgr->nameserver = NULL; if (nameserver != NULL) { mgr->nameserver = strdup(nameserver); } } #endif /* MG_ENABLE_ASYNC_RESOLVER */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_coap.c" #endif /* * Copyright (c) 2015 Cesanta Software Limited * All rights reserved * This software is dual-licensed: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. For the terms of this * license, see <http://www.gnu.org/licenses/>. * * You are free to use this software under the terms of the GNU General * Public License, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * Alternatively, you can license this software under a commercial * license, as set out in <https://www.cesanta.com/license>. */ /* Amalgamated: #include "mg_internal.h" */ /* Amalgamated: #include "mg_coap.h" */ #if MG_ENABLE_COAP void mg_coap_free_options(struct mg_coap_message *cm) { while (cm->options != NULL) { struct mg_coap_option *next = cm->options->next; MG_FREE(cm->options); cm->options = next; } } struct mg_coap_option *mg_coap_add_option(struct mg_coap_message *cm, uint32_t number, char *value, size_t len) { struct mg_coap_option *new_option = (struct mg_coap_option *) MG_CALLOC(1, sizeof(*new_option)); new_option->number = number; new_option->value.p = value; new_option->value.len = len; if (cm->options == NULL) { cm->options = cm->optiomg_tail = new_option; } else { /* * A very simple attention to help clients to compose options: * CoAP wants to see options ASC ordered. * Could be change by using sort in coap_compose */ if (cm->optiomg_tail->number <= new_option->number) { /* if option is already ordered just add it */ cm->optiomg_tail = cm->optiomg_tail->next = new_option; } else { /* looking for appropriate position */ struct mg_coap_option *current_opt = cm->options; struct mg_coap_option *prev_opt = 0; while (current_opt != NULL) { if (current_opt->number > new_option->number) { break; } prev_opt = current_opt; current_opt = current_opt->next; } if (prev_opt != NULL) { prev_opt->next = new_option; new_option->next = current_opt; } else { /* insert new_option to the beginning */ new_option->next = cm->options; cm->options = new_option; } } } return new_option; } /* * Fills CoAP header in mg_coap_message. * * Helper function. */ static char *coap_parse_header(char *ptr, struct mbuf *io, struct mg_coap_message *cm) { if (io->len < sizeof(uint32_t)) { cm->flags |= MG_COAP_NOT_ENOUGH_DATA; return NULL; } /* * Version (Ver): 2-bit unsigned integer. Indicates the CoAP version * number. Implementations of this specification MUST set this field * to 1 (01 binary). Other values are reserved for future versions. * Messages with unknown version numbers MUST be silently ignored. */ if (((uint8_t) *ptr >> 6) != 1) { cm->flags |= MG_COAP_IGNORE; return NULL; } /* * Type (T): 2-bit unsigned integer. Indicates if this message is of * type Confirmable (0), Non-confirmable (1), Acknowledgement (2), or * Reset (3). */ cm->msg_type = ((uint8_t) *ptr & 0x30) >> 4; cm->flags |= MG_COAP_MSG_TYPE_FIELD; /* * Token Length (TKL): 4-bit unsigned integer. Indicates the length of * the variable-length Token field (0-8 bytes). Lengths 9-15 are * reserved, MUST NOT be sent, and MUST be processed as a message * format error. */ cm->token.len = *ptr & 0x0F; if (cm->token.len > 8) { cm->flags |= MG_COAP_FORMAT_ERROR; return NULL; } ptr++; /* * Code: 8-bit unsigned integer, split into a 3-bit class (most * significant bits) and a 5-bit detail (least significant bits) */ cm->code_class = (uint8_t) *ptr >> 5; cm->code_detail = *ptr & 0x1F; cm->flags |= (MG_COAP_CODE_CLASS_FIELD | MG_COAP_CODE_DETAIL_FIELD); ptr++; /* Message ID: 16-bit unsigned integer in network byte order. */ cm->msg_id = (uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1); cm->flags |= MG_COAP_MSG_ID_FIELD; ptr += 2; return ptr; } /* * Fills token information in mg_coap_message. * * Helper function. */ static char *coap_get_token(char *ptr, struct mbuf *io, struct mg_coap_message *cm) { if (cm->token.len != 0) { if (ptr + cm->token.len > io->buf + io->len) { cm->flags |= MG_COAP_NOT_ENOUGH_DATA; return NULL; } else { cm->token.p = ptr; ptr += cm->token.len; cm->flags |= MG_COAP_TOKEN_FIELD; } } return ptr; } /* * Returns Option Delta or Length. * * Helper function. */ static int coap_get_ext_opt(char *ptr, struct mbuf *io, uint16_t *opt_info) { int ret = 0; if (*opt_info == 13) { /* * 13: An 8-bit unsigned integer follows the initial byte and * indicates the Option Delta/Length minus 13. */ if (ptr < io->buf + io->len) { *opt_info = (uint8_t) *ptr + 13; ret = sizeof(uint8_t); } else { ret = -1; /* LCOV_EXCL_LINE */ } } else if (*opt_info == 14) { /* * 14: A 16-bit unsigned integer in network byte order follows the * initial byte and indicates the Option Delta/Length minus 269. */ if (ptr + sizeof(uint8_t) < io->buf + io->len) { *opt_info = ((uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1)) + 269; ret = sizeof(uint16_t); } else { ret = -1; /* LCOV_EXCL_LINE */ } } return ret; } /* * Fills options in mg_coap_message. * * Helper function. * * General options format: * +---------------+---------------+ * | Option Delta | Option Length | 1 byte * +---------------+---------------+ * \ Option Delta (extended) \ 0-2 bytes * +-------------------------------+ * / Option Length (extended) \ 0-2 bytes * +-------------------------------+ * \ Option Value \ 0 or more bytes * +-------------------------------+ */ static char *coap_get_options(char *ptr, struct mbuf *io, struct mg_coap_message *cm) { uint16_t prev_opt = 0; if (ptr == io->buf + io->len) { /* end of packet, ok */ return NULL; } /* 0xFF is payload marker */ while (ptr < io->buf + io->len && (uint8_t) *ptr != 0xFF) { uint16_t option_delta, option_lenght; int optinfo_len; /* Option Delta: 4-bit unsigned integer */ option_delta = ((uint8_t) *ptr & 0xF0) >> 4; /* Option Length: 4-bit unsigned integer */ option_lenght = *ptr & 0x0F; if (option_delta == 15 || option_lenght == 15) { /* * 15: Reserved for future use. If the field is set to this value, * it MUST be processed as a message format error */ cm->flags |= MG_COAP_FORMAT_ERROR; break; } ptr++; /* check for extended option delta */ optinfo_len = coap_get_ext_opt(ptr, io, &option_delta); if (optinfo_len == -1) { cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */ break; /* LCOV_EXCL_LINE */ } ptr += optinfo_len; /* check or extended option lenght */ optinfo_len = coap_get_ext_opt(ptr, io, &option_lenght); if (optinfo_len == -1) { cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */ break; /* LCOV_EXCL_LINE */ } ptr += optinfo_len; /* * Instead of specifying the Option Number directly, the instances MUST * appear in order of their Option Numbers and a delta encoding is used * between them. */ option_delta += prev_opt; mg_coap_add_option(cm, option_delta, ptr, option_lenght); prev_opt = option_delta; if (ptr + option_lenght > io->buf + io->len) { cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */ break; /* LCOV_EXCL_LINE */ } ptr += option_lenght; } if ((cm->flags & MG_COAP_ERROR) != 0) { mg_coap_free_options(cm); return NULL; } cm->flags |= MG_COAP_OPTIOMG_FIELD; if (ptr == io->buf + io->len) { /* end of packet, ok */ return NULL; } ptr++; return ptr; } uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm) { char *ptr; memset(cm, 0, sizeof(*cm)); if ((ptr = coap_parse_header(io->buf, io, cm)) == NULL) { return cm->flags; } if ((ptr = coap_get_token(ptr, io, cm)) == NULL) { return cm->flags; } if ((ptr = coap_get_options(ptr, io, cm)) == NULL) { return cm->flags; } /* the rest is payload */ cm->payload.len = io->len - (ptr - io->buf); if (cm->payload.len != 0) { cm->payload.p = ptr; cm->flags |= MG_COAP_PAYLOAD_FIELD; } return cm->flags; } /* * Calculates extended size of given Opt Number/Length in coap message. * * Helper function. */ static size_t coap_get_ext_opt_size(uint32_t value) { int ret = 0; if (value >= 13 && value <= 0xFF + 13) { ret = sizeof(uint8_t); } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) { ret = sizeof(uint16_t); } return ret; } /* * Splits given Opt Number/Length into base and ext values. * * Helper function. */ static int coap_split_opt(uint32_t value, uint8_t *base, uint16_t *ext) { int ret = 0; if (value < 13) { *base = value; } else if (value >= 13 && value <= 0xFF + 13) { *base = 13; *ext = value - 13; ret = sizeof(uint8_t); } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) { *base = 14; *ext = value - 269; ret = sizeof(uint16_t); } return ret; } /* * Puts uint16_t (in network order) into given char stream. * * Helper function. */ static char *coap_add_uint16(char *ptr, uint16_t val) { *ptr = val >> 8; ptr++; *ptr = val & 0x00FF; ptr++; return ptr; } /* * Puts extended value of Opt Number/Length into given char stream. * * Helper function. */ static char *coap_add_opt_info(char *ptr, uint16_t val, size_t len) { if (len == sizeof(uint8_t)) { *ptr = (char) val; ptr++; } else if (len == sizeof(uint16_t)) { ptr = coap_add_uint16(ptr, val); } return ptr; } /* * Verifies given mg_coap_message and calculates message size for it. * * Helper function. */ static uint32_t coap_calculate_packet_size(struct mg_coap_message *cm, size_t *len) { struct mg_coap_option *opt; uint32_t prev_opt_number; *len = 4; /* header */ if (cm->msg_type > MG_COAP_MSG_MAX) { return MG_COAP_ERROR | MG_COAP_MSG_TYPE_FIELD; } if (cm->token.len > 8) { return MG_COAP_ERROR | MG_COAP_TOKEN_FIELD; } if (cm->code_class > 7) { return MG_COAP_ERROR | MG_COAP_CODE_CLASS_FIELD; } if (cm->code_detail > 31) { return MG_COAP_ERROR | MG_COAP_CODE_DETAIL_FIELD; } *len += cm->token.len; if (cm->payload.len != 0) { *len += cm->payload.len + 1; /* ... + 1; add payload marker */ } opt = cm->options; prev_opt_number = 0; while (opt != NULL) { *len += 1; /* basic delta/length */ *len += coap_get_ext_opt_size(opt->number - prev_opt_number); *len += coap_get_ext_opt_size((uint32_t) opt->value.len); /* * Current implementation performs check if * option_number > previous option_number and produces an error * TODO(alashkin): write design doc with limitations * May be resorting is more suitable solution. */ if ((opt->next != NULL && opt->number > opt->next->number) || opt->value.len > 0xFFFF + 269 || opt->number - prev_opt_number > 0xFFFF + 269) { return MG_COAP_ERROR | MG_COAP_OPTIOMG_FIELD; } *len += opt->value.len; prev_opt_number = opt->number; opt = opt->next; } return 0; } uint32_t mg_coap_compose(struct mg_coap_message *cm, struct mbuf *io) { struct mg_coap_option *opt; uint32_t res, prev_opt_number; size_t prev_io_len, packet_size; char *ptr; res = coap_calculate_packet_size(cm, &packet_size); if (res != 0) { return res; } /* saving previous lenght to handle non-empty mbuf */ prev_io_len = io->len; if (mbuf_append(io, NULL, packet_size) == 0) return MG_COAP_ERROR; ptr = io->buf + prev_io_len; /* * since cm is verified, it is possible to use bits shift operator * without additional zeroing of unused bits */ /* ver: 2 bits, msg_type: 2 bits, toklen: 4 bits */ *ptr = (1 << 6) | (cm->msg_type << 4) | (uint8_t)(cm->token.len); ptr++; /* code class: 3 bits, code detail: 5 bits */ *ptr = (cm->code_class << 5) | (cm->code_detail); ptr++; ptr = coap_add_uint16(ptr, cm->msg_id); if (cm->token.len != 0) { memcpy(ptr, cm->token.p, cm->token.len); ptr += cm->token.len; } opt = cm->options; prev_opt_number = 0; while (opt != NULL) { uint8_t delta_base = 0, length_base = 0; uint16_t delta_ext = 0, length_ext = 0; size_t opt_delta_len = coap_split_opt(opt->number - prev_opt_number, &delta_base, &delta_ext); size_t opt_lenght_len = coap_split_opt((uint32_t) opt->value.len, &length_base, &length_ext); *ptr = (delta_base << 4) | length_base; ptr++; ptr = coap_add_opt_info(ptr, delta_ext, opt_delta_len); ptr = coap_add_opt_info(ptr, length_ext, opt_lenght_len); if (opt->value.len != 0) { memcpy(ptr, opt->value.p, opt->value.len); ptr += opt->value.len; } prev_opt_number = opt->number; opt = opt->next; } if (cm->payload.len != 0) { *ptr = (char) -1; ptr++; memcpy(ptr, cm->payload.p, cm->payload.len); } return 0; } uint32_t mg_coap_send_message(struct mg_connection *nc, struct mg_coap_message *cm) { struct mbuf packet_out; uint32_t compose_res; mbuf_init(&packet_out, 0); compose_res = mg_coap_compose(cm, &packet_out); if (compose_res != 0) { return compose_res; /* LCOV_EXCL_LINE */ } mg_send(nc, packet_out.buf, (int) packet_out.len); mbuf_free(&packet_out); return 0; } uint32_t mg_coap_send_ack(struct mg_connection *nc, uint16_t msg_id) { struct mg_coap_message cm; memset(&cm, 0, sizeof(cm)); cm.msg_type = MG_COAP_MSG_ACK; cm.msg_id = msg_id; return mg_coap_send_message(nc, &cm); } static void coap_handler(struct mg_connection *nc, int ev, void *ev_data MG_UD_ARG(void *user_data)) { struct mbuf *io = &nc->recv_mbuf; struct mg_coap_message cm; uint32_t parse_res; memset(&cm, 0, sizeof(cm)); nc->handler(nc, ev, ev_data MG_UD_ARG(user_data)); switch (ev) { case MG_EV_RECV: parse_res = mg_coap_parse(io, &cm); if ((parse_res & MG_COAP_IGNORE) == 0) { if ((cm.flags & MG_COAP_NOT_ENOUGH_DATA) != 0) { /* * Since we support UDP only * MG_COAP_NOT_ENOUGH_DATA == MG_COAP_FORMAT_ERROR */ cm.flags |= MG_COAP_FORMAT_ERROR; /* LCOV_EXCL_LINE */ } /* LCOV_EXCL_LINE */ nc->handler(nc, MG_COAP_EVENT_BASE + cm.msg_type, &cm MG_UD_ARG(user_data)); } mg_coap_free_options(&cm); mbuf_remove(io, io->len); break; } } /* * Attach built-in CoAP event handler to the given connection. * * The user-defined event handler will receive following extra events: * * - MG_EV_COAP_CON * - MG_EV_COAP_NOC * - MG_EV_COAP_ACK * - MG_EV_COAP_RST */ int mg_set_protocol_coap(struct mg_connection *nc) { /* supports UDP only */ if ((nc->flags & MG_F_UDP) == 0) { return -1; } nc->proto_handler = coap_handler; return 0; } #endif /* MG_ENABLE_COAP */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_sntp.c" #endif /* * Copyright (c) 2016 Cesanta Software Limited * All rights reserved */ /* Amalgamated: #include "mg_internal.h" */ /* Amalgamated: #include "mg_sntp.h" */ /* Amalgamated: #include "mg_util.h" */ #if MG_ENABLE_SNTP #define SNTP_TIME_OFFSET 2208988800 #ifndef SNTP_TIMEOUT #define SNTP_TIMEOUT 10 #endif #ifndef SNTP_ATTEMPTS #define SNTP_ATTEMPTS 3 #endif static uint64_t mg_get_sec(uint64_t val) { return (val & 0xFFFFFFFF00000000) >> 32; } static uint64_t mg_get_usec(uint64_t val) { uint64_t tmp = (val & 0x00000000FFFFFFFF); tmp *= 1000000; tmp >>= 32; return tmp; } static void mg_ntp_to_tv(uint64_t val, struct timeval *tv) { uint64_t tmp; tmp = mg_get_sec(val); tmp -= SNTP_TIME_OFFSET; tv->tv_sec = tmp; tv->tv_usec = mg_get_usec(val); } static void mg_get_ntp_ts(const char *ntp, uint64_t *val) { uint32_t tmp; memcpy(&tmp, ntp, sizeof(tmp)); tmp = ntohl(tmp); *val = (uint64_t) tmp << 32; memcpy(&tmp, ntp + 4, sizeof(tmp)); tmp = ntohl(tmp); *val |= tmp; } void mg_sntp_send_request(struct mg_connection *c) { uint8_t buf[48] = {0}; /* * header - 8 bit: * LI (2 bit) - 3 (not in sync), VN (3 bit) - 4 (version), * mode (3 bit) - 3 (client) */ buf[0] = (3 << 6) | (4 << 3) | 3; /* * Next fields should be empty in client request * stratum, 8 bit * poll interval, 8 bit * rrecision, 8 bit * root delay, 32 bit * root dispersion, 32 bit * ref id, 32 bit * ref timestamp, 64 bit * originate Timestamp, 64 bit * receive Timestamp, 64 bit */ /* * convert time to sntp format (sntp starts from 00:00:00 01.01.1900) * according to rfc868 it is 2208988800L sec * this information is used to correct roundtrip delay * but if local clock is absolutely broken (and doesn't work even * as simple timer), it is better to disable it */ #ifndef MG_SNTP_NO_DELAY_CORRECTION uint32_t sec; sec = htonl((uint32_t)(mg_time() + SNTP_TIME_OFFSET)); memcpy(&buf[40], &sec, sizeof(sec)); #endif mg_send(c, buf, sizeof(buf)); } #ifndef MG_SNTP_NO_DELAY_CORRECTION static uint64_t mg_calculate_delay(uint64_t t1, uint64_t t2, uint64_t t3) { /* roundloop delay = (T4 - T1) - (T3 - T2) */ uint64_t d1 = ((mg_time() + SNTP_TIME_OFFSET) * 1000000) - (mg_get_sec(t1) * 1000000 + mg_get_usec(t1)); uint64_t d2 = (mg_get_sec(t3) * 1000000 + mg_get_usec(t3)) - (mg_get_sec(t2) * 1000000 + mg_get_usec(t2)); return (d1 > d2) ? d1 - d2 : 0; } #endif MG_INTERNAL int mg_sntp_parse_reply(const char *buf, int len, struct mg_sntp_message *msg) { uint8_t hdr; uint64_t trsm_ts_T3, delay = 0; int mode; struct timeval tv; if (len < 48) { return -1; } hdr = buf[0]; if ((hdr & 0x38) >> 3 != 4) { /* Wrong version */ return -1; } mode = hdr & 0x7; if (mode != 4 && mode != 5) { /* Not a server reply */ return -1; } memset(msg, 0, sizeof(*msg)); msg->kiss_of_death = (buf[1] == 0); /* Server asks to not send requests */ mg_get_ntp_ts(&buf[40], &trsm_ts_T3); #ifndef MG_SNTP_NO_DELAY_CORRECTION { uint64_t orig_ts_T1, recv_ts_T2; mg_get_ntp_ts(&buf[24], &orig_ts_T1); mg_get_ntp_ts(&buf[32], &recv_ts_T2); delay = mg_calculate_delay(orig_ts_T1, recv_ts_T2, trsm_ts_T3); } #endif mg_ntp_to_tv(trsm_ts_T3, &tv); msg->time = (double) tv.tv_sec + (((double) tv.tv_usec + delay) / 1000000.0); return 0; } static void mg_sntp_handler(struct mg_connection *c, int ev, void *ev_data MG_UD_ARG(void *user_data)) { struct mbuf *io = &c->recv_mbuf; struct mg_sntp_message msg; c->handler(c, ev, ev_data MG_UD_ARG(user_data)); switch (ev) { case MG_EV_RECV: { if (mg_sntp_parse_reply(io->buf, io->len, &msg) < 0) { DBG(("Invalid SNTP packet received (%d)", (int) io->len)); c->handler(c, MG_SNTP_MALFORMED_REPLY, NULL MG_UD_ARG(user_data)); } else { c->handler(c, MG_SNTP_REPLY, (void *) &msg MG_UD_ARG(user_data)); } mbuf_remove(io, io->len); break; } } } int mg_set_protocol_sntp(struct mg_connection *c) { if ((c->flags & MG_F_UDP) == 0) { return -1; } c->proto_handler = mg_sntp_handler; return 0; } struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr, MG_CB(mg_event_handler_t event_handler, void *user_data), const char *sntp_server_name) { struct mg_connection *c = NULL; char url[100], *p_url = url; const char *proto = "", *port = "", *tmp; /* If port is not specified, use default (123) */ tmp = strchr(sntp_server_name, ':'); if (tmp != NULL && *(tmp + 1) == '/') { tmp = strchr(tmp + 1, ':'); } if (tmp == NULL) { port = ":123"; } /* Add udp:// if needed */ if (strncmp(sntp_server_name, "udp://", 6) != 0) { proto = "udp://"; } mg_asprintf(&p_url, sizeof(url), "%s%s%s", proto, sntp_server_name, port); c = mg_connect(mgr, p_url, event_handler MG_UD_ARG(user_data)); if (c == NULL) { goto cleanup; } mg_set_protocol_sntp(c); cleanup: if (p_url != url) { MG_FREE(p_url); } return c; } struct sntp_data { mg_event_handler_t hander; int count; }; static void mg_sntp_util_ev_handler(struct mg_connection *c, int ev, void *ev_data MG_UD_ARG(void *user_data)) { #if !MG_ENABLE_CALLBACK_USERDATA void *user_data = c->user_data; #endif struct sntp_data *sd = (struct sntp_data *) user_data; switch (ev) { case MG_EV_CONNECT: if (*(int *) ev_data != 0) { mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL); break; } /* fallthrough */ case MG_EV_TIMER: if (sd->count <= SNTP_ATTEMPTS) { mg_sntp_send_request(c); mg_set_timer(c, mg_time() + 10); sd->count++; } else { mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL); c->flags |= MG_F_CLOSE_IMMEDIATELY; } break; case MG_SNTP_MALFORMED_REPLY: mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL); c->flags |= MG_F_CLOSE_IMMEDIATELY; break; case MG_SNTP_REPLY: mg_call(c, sd->hander, c->user_data, MG_SNTP_REPLY, ev_data); c->flags |= MG_F_CLOSE_IMMEDIATELY; break; case MG_EV_CLOSE: MG_FREE(user_data); c->user_data = NULL; break; } } struct mg_connection *mg_sntp_get_time(struct mg_mgr *mgr, mg_event_handler_t event_handler, const char *sntp_server_name) { struct mg_connection *c; struct sntp_data *sd = (struct sntp_data *) MG_CALLOC(1, sizeof(*sd)); if (sd == NULL) { return NULL; } c = mg_sntp_connect(mgr, MG_CB(mg_sntp_util_ev_handler, sd), sntp_server_name); if (c == NULL) { MG_FREE(sd); return NULL; } sd->hander = event_handler; #if !MG_ENABLE_CALLBACK_USERDATA c->user_data = sd; #endif return c; } #endif /* MG_ENABLE_SNTP */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_socks.c" #endif /* * Copyright (c) 2017 Cesanta Software Limited * All rights reserved */ #if MG_ENABLE_SOCKS /* Amalgamated: #include "mg_socks.h" */ /* Amalgamated: #include "mg_internal.h" */ /* * https://www.ietf.org/rfc/rfc1928.txt paragraph 3, handle client handshake * * +----+----------+----------+ * |VER | NMETHODS | METHODS | * +----+----------+----------+ * | 1 | 1 | 1 to 255 | * +----+----------+----------+ */ static void mg_socks5_handshake(struct mg_connection *c) { struct mbuf *r = &c->recv_mbuf; if (r->buf[0] != MG_SOCKS_VERSION) { c->flags |= MG_F_CLOSE_IMMEDIATELY; } else if (r->len > 2 && (size_t) r->buf[1] + 2 <= r->len) { /* https://www.ietf.org/rfc/rfc1928.txt paragraph 3 */ unsigned char reply[2] = {MG_SOCKS_VERSION, MG_SOCKS_HANDSHAKE_FAILURE}; int i; for (i = 2; i < r->buf[1] + 2; i++) { /* TODO(lsm): support other auth methods */ if (r->buf[i] == MG_SOCKS_HANDSHAKE_NOAUTH) reply[1] = r->buf[i]; } mbuf_remove(r, 2 + r->buf[1]); mg_send(c, reply, sizeof(reply)); c->flags |= MG_SOCKS_HANDSHAKE_DONE; /* Mark handshake done */ } } static void disband(struct mg_connection *c) { struct mg_connection *c2 = (struct mg_connection *) c->user_data; if (c2 != NULL) { c2->flags |= MG_F_SEND_AND_CLOSE; c2->user_data = NULL; } c->flags |= MG_F_SEND_AND_CLOSE; c->user_data = NULL; } static void relay_data(struct mg_connection *c) { struct mg_connection *c2 = (struct mg_connection *) c->user_data; if (c2 != NULL) { mg_send(c2, c->recv_mbuf.buf, c->recv_mbuf.len); mbuf_remove(&c->recv_mbuf, c->recv_mbuf.len); } else { c->flags |= MG_F_SEND_AND_CLOSE; } } static void serv_ev_handler(struct mg_connection *c, int ev, void *ev_data) { if (ev == MG_EV_CLOSE) { disband(c); } else if (ev == MG_EV_RECV) { relay_data(c); } else if (ev == MG_EV_CONNECT) { int res = *(int *) ev_data; if (res != 0) LOG(LL_ERROR, ("connect error: %d", res)); } } static void mg_socks5_connect(struct mg_connection *c, const char *addr) { struct mg_connection *serv = mg_connect(c->mgr, addr, serv_ev_handler); serv->user_data = c; c->user_data = serv; } /* * Request, https://www.ietf.org/rfc/rfc1928.txt paragraph 4 * * +----+-----+-------+------+----------+----------+ * |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT | * +----+-----+-------+------+----------+----------+ * | 1 | 1 | X'00' | 1 | Variable | 2 | * +----+-----+-------+------+----------+----------+ */ static void mg_socks5_handle_request(struct mg_connection *c) { struct mbuf *r = &c->recv_mbuf; unsigned char *p = (unsigned char *) r->buf; unsigned char addr_len = 4, reply = MG_SOCKS_SUCCESS; int ver, cmd, atyp; char addr[300]; if (r->len < 8) return; /* return if not fully buffered. min DST.ADDR is 2 */ ver = p[0]; cmd = p[1]; atyp = p[3]; /* TODO(lsm): support other commands */ if (ver != MG_SOCKS_VERSION || cmd != MG_SOCKS_CMD_CONNECT) { reply = MG_SOCKS_CMD_NOT_SUPPORTED; } else if (atyp == MG_SOCKS_ADDR_IPV4) { addr_len = 4; if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */ snprintf(addr, sizeof(addr), "%d.%d.%d.%d:%d", p[4], p[5], p[6], p[7], p[8] << 8 | p[9]); mg_socks5_connect(c, addr); } else if (atyp == MG_SOCKS_ADDR_IPV6) { addr_len = 16; if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */ snprintf(addr, sizeof(addr), "[%x:%x:%x:%x:%x:%x:%x:%x]:%d", p[4] << 8 | p[5], p[6] << 8 | p[7], p[8] << 8 | p[9], p[10] << 8 | p[11], p[12] << 8 | p[13], p[14] << 8 | p[15], p[16] << 8 | p[17], p[18] << 8 | p[19], p[20] << 8 | p[21]); mg_socks5_connect(c, addr); } else if (atyp == MG_SOCKS_ADDR_DOMAIN) { addr_len = p[4] + 1; if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */ snprintf(addr, sizeof(addr), "%.*s:%d", p[4], p + 5, p[4 + addr_len] << 8 | p[4 + addr_len + 1]); mg_socks5_connect(c, addr); } else { reply = MG_SOCKS_ADDR_NOT_SUPPORTED; } /* * Reply, https://www.ietf.org/rfc/rfc1928.txt paragraph 5 * * +----+-----+-------+------+----------+----------+ * |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT | * +----+-----+-------+------+----------+----------+ * | 1 | 1 | X'00' | 1 | Variable | 2 | * +----+-----+-------+------+----------+----------+ */ { unsigned char buf[] = {MG_SOCKS_VERSION, reply, 0}; mg_send(c, buf, sizeof(buf)); } mg_send(c, r->buf + 3, addr_len + 1 + 2); mbuf_remove(r, 6 + addr_len); /* Remove request from the input stream */ c->flags |= MG_SOCKS_CONNECT_DONE; /* Mark ourselves as connected */ } static void socks_handler(struct mg_connection *c, int ev, void *ev_data) { if (ev == MG_EV_RECV) { if (!(c->flags & MG_SOCKS_HANDSHAKE_DONE)) mg_socks5_handshake(c); if (c->flags & MG_SOCKS_HANDSHAKE_DONE && !(c->flags & MG_SOCKS_CONNECT_DONE)) { mg_socks5_handle_request(c); } if (c->flags & MG_SOCKS_CONNECT_DONE) relay_data(c); } else if (ev == MG_EV_CLOSE) { disband(c); } (void) ev_data; } void mg_set_protocol_socks(struct mg_connection *c) { c->proto_handler = socks_handler; } #endif #ifdef MG_MODULE_LINES #line 1 "common/platforms/cc3200/cc3200_libc.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if CS_PLATFORM == CS_P_CC3200 /* Amalgamated: #include "common/mg_mem.h" */ #include <stdio.h> #include <string.h> #ifndef __TI_COMPILER_VERSION__ #include <reent.h> #include <sys/stat.h> #include <sys/time.h> #include <unistd.h> #endif #include <inc/hw_types.h> #include <inc/hw_memmap.h> #include <driverlib/prcm.h> #include <driverlib/rom.h> #include <driverlib/rom_map.h> #include <driverlib/uart.h> #include <driverlib/utils.h> #define CONSOLE_UART UARTA0_BASE #ifdef __TI_COMPILER_VERSION__ int asprintf(char **strp, const char *fmt, ...) { va_list ap; int len; *strp = MG_MALLOC(BUFSIZ); if (*strp == NULL) return -1; va_start(ap, fmt); len = vsnprintf(*strp, BUFSIZ, fmt, ap); va_end(ap); if (len > 0) { *strp = MG_REALLOC(*strp, len + 1); if (*strp == NULL) return -1; } if (len >= BUFSIZ) { va_start(ap, fmt); len = vsnprintf(*strp, len + 1, fmt, ap); va_end(ap); } return len; } #if MG_TI_NO_HOST_INTERFACE time_t HOSTtime() { struct timeval tp; gettimeofday(&tp, NULL); return tp.tv_sec; } #endif #endif /* __TI_COMPILER_VERSION__ */ void fprint_str(FILE *fp, const char *str) { while (*str != '\0') { if (*str == '\n') MAP_UARTCharPut(CONSOLE_UART, '\r'); MAP_UARTCharPut(CONSOLE_UART, *str++); } } void _exit(int status) { fprint_str(stderr, "_exit\n"); /* cause an unaligned access exception, that will drop you into gdb */ *(int *) 1 = status; while (1) ; /* avoid gcc warning because stdlib abort() has noreturn attribute */ } void _not_implemented(const char *what) { fprint_str(stderr, what); fprint_str(stderr, " is not implemented\n"); _exit(42); } int _kill(int pid, int sig) { (void) pid; (void) sig; _not_implemented("_kill"); return -1; } int _getpid() { fprint_str(stderr, "_getpid is not implemented\n"); return 42; } int _isatty(int fd) { /* 0, 1 and 2 are TTYs. */ return fd < 2; } #endif /* CS_PLATFORM == CS_P_CC3200 */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/msp432/msp432_libc.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if CS_PLATFORM == CS_P_MSP432 #include <ti/sysbios/BIOS.h> #include <ti/sysbios/knl/Clock.h> int gettimeofday(struct timeval *tp, void *tzp) { uint32_t ticks = Clock_getTicks(); tp->tv_sec = ticks / 1000; tp->tv_usec = (ticks % 1000) * 1000; return 0; } #endif /* CS_PLATFORM == CS_P_MSP432 */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/nrf5/nrf5_libc.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if (CS_PLATFORM == CS_P_NRF51 || CS_PLATFORM == CS_P_NRF52) && \ defined(__ARMCC_VERSION) int gettimeofday(struct timeval *tp, void *tzp) { /* TODO */ tp->tv_sec = 0; tp->tv_usec = 0; return 0; } #endif #ifdef MG_MODULE_LINES #line 1 "common/platforms/simplelink/sl_fs_slfs.h" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_ #define CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_ #if defined(MG_FS_SLFS) #include <stdio.h> #ifndef __TI_COMPILER_VERSION__ #include <unistd.h> #include <sys/stat.h> #endif #define MAX_OPEN_SLFS_FILES 8 /* Indirect libc interface - same functions, different names. */ int fs_slfs_open(const char *pathname, int flags, mode_t mode); int fs_slfs_close(int fd); ssize_t fs_slfs_read(int fd, void *buf, size_t count); ssize_t fs_slfs_write(int fd, const void *buf, size_t count); int fs_slfs_stat(const char *pathname, struct stat *s); int fs_slfs_fstat(int fd, struct stat *s); off_t fs_slfs_lseek(int fd, off_t offset, int whence); int fs_slfs_unlink(const char *filename); int fs_slfs_rename(const char *from, const char *to); void fs_slfs_set_file_size(const char *name, size_t size); void fs_slfs_set_file_flags(const char *name, uint32_t flags, uint32_t *token); void fs_slfs_unset_file_flags(const char *name); #endif /* defined(MG_FS_SLFS) */ #endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_ */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/simplelink/sl_fs_slfs.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Standard libc interface to TI SimpleLink FS. */ #if defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS) /* Amalgamated: #include "common/platforms/simplelink/sl_fs_slfs.h" */ #include <errno.h> #if CS_PLATFORM == CS_P_CC3200 #include <inc/hw_types.h> #endif /* Amalgamated: #include "common/cs_dbg.h" */ /* Amalgamated: #include "common/mg_mem.h" */ #if SL_MAJOR_VERSION_NUM < 2 int slfs_open(const unsigned char *fname, uint32_t flags, uint32_t *token) { _i32 fh; _i32 r = sl_FsOpen(fname, flags, (unsigned long *) token, &fh); return (r < 0 ? r : fh); } #else /* SL_MAJOR_VERSION_NUM >= 2 */ int slfs_open(const unsigned char *fname, uint32_t flags, uint32_t *token) { return sl_FsOpen(fname, flags, (unsigned long *) token); } #endif /* From sl_fs.c */ int set_errno(int e); const char *drop_dir(const char *fname, bool *is_slfs); /* * With SLFS, you have to pre-declare max file size. Yes. Really. * 64K should be enough for everyone. Right? */ #ifndef FS_SLFS_MAX_FILE_SIZE #define FS_SLFS_MAX_FILE_SIZE (64 * 1024) #endif struct sl_file_open_info { char *name; size_t size; uint32_t flags; uint32_t *token; }; struct sl_fd_info { _i32 fh; _off_t pos; size_t size; }; static struct sl_fd_info s_sl_fds[MAX_OPEN_SLFS_FILES]; static struct sl_file_open_info s_sl_file_open_infos[MAX_OPEN_SLFS_FILES]; static struct sl_file_open_info *fs_slfs_find_foi(const char *name, bool create); static int sl_fs_to_errno(_i32 r) { DBG(("SL error: %d", (int) r)); switch (r) { case SL_FS_OK: return 0; case SL_ERROR_FS_FILE_NAME_EXIST: return EEXIST; case SL_ERROR_FS_WRONG_FILE_NAME: return EINVAL; case SL_ERROR_FS_NO_AVAILABLE_NV_INDEX: case SL_ERROR_FS_NOT_ENOUGH_STORAGE_SPACE: return ENOSPC; case SL_ERROR_FS_FAILED_TO_ALLOCATE_MEM: return ENOMEM; case SL_ERROR_FS_FILE_NOT_EXISTS: return ENOENT; case SL_ERROR_FS_NOT_SUPPORTED: return ENOTSUP; } return ENXIO; } int fs_slfs_open(const char *pathname, int flags, mode_t mode) { int fd; for (fd = 0; fd < MAX_OPEN_SLFS_FILES; fd++) { if (s_sl_fds[fd].fh <= 0) break; } if (fd >= MAX_OPEN_SLFS_FILES) return set_errno(ENOMEM); struct sl_fd_info *fi = &s_sl_fds[fd]; /* * Apply path manipulations again, in case we got here directly * (via TI libc's "add_device"). */ pathname = drop_dir(pathname, NULL); _u32 am = 0; fi->size = (size_t) -1; int rw = (flags & 3); size_t new_size = 0; struct sl_file_open_info *foi = fs_slfs_find_foi(pathname, false /* create */); if (foi != NULL) { LOG(LL_DEBUG, ("FOI for %s: %d 0x%x %p", pathname, (int) foi->size, (unsigned int) foi->flags, foi->token)); } if (rw == O_RDONLY) { SlFsFileInfo_t sl_fi; _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi); if (r == SL_FS_OK) { fi->size = SL_FI_FILE_SIZE(sl_fi); } am = SL_FS_READ; } else { if (!(flags & O_TRUNC) || (flags & O_APPEND)) { // FailFS files cannot be opened for append and will be truncated // when opened for write. return set_errno(ENOTSUP); } if (flags & O_CREAT) { if (foi->size > 0) { new_size = foi->size; } else { new_size = FS_SLFS_MAX_FILE_SIZE; } am = FS_MODE_OPEN_CREATE(new_size, 0); } else { am = SL_FS_WRITE; } #if SL_MAJOR_VERSION_NUM >= 2 am |= SL_FS_OVERWRITE; #endif } uint32_t *token = NULL; if (foi != NULL) { am |= foi->flags; token = foi->token; } fi->fh = slfs_open((_u8 *) pathname, am, token); LOG(LL_DEBUG, ("sl_FsOpen(%s, 0x%x, %p) sz %u = %d", pathname, (int) am, token, (unsigned int) new_size, (int) fi->fh)); int r; if (fi->fh >= 0) { fi->pos = 0; r = fd; } else { r = set_errno(sl_fs_to_errno(fi->fh)); } return r; } int fs_slfs_close(int fd) { struct sl_fd_info *fi = &s_sl_fds[fd]; if (fi->fh <= 0) return set_errno(EBADF); _i32 r = sl_FsClose(fi->fh, NULL, NULL, 0); LOG(LL_DEBUG, ("sl_FsClose(%d) = %d", (int) fi->fh, (int) r)); s_sl_fds[fd].fh = -1; return set_errno(sl_fs_to_errno(r)); } ssize_t fs_slfs_read(int fd, void *buf, size_t count) { struct sl_fd_info *fi = &s_sl_fds[fd]; if (fi->fh <= 0) return set_errno(EBADF); /* Simulate EOF. sl_FsRead @ file_size return SL_FS_ERR_OFFSET_OUT_OF_RANGE. */ if (fi->pos == fi->size) return 0; _i32 r = sl_FsRead(fi->fh, fi->pos, buf, count); DBG(("sl_FsRead(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count, (int) r)); if (r >= 0) { fi->pos += r; return r; } return set_errno(sl_fs_to_errno(r)); } ssize_t fs_slfs_write(int fd, const void *buf, size_t count) { struct sl_fd_info *fi = &s_sl_fds[fd]; if (fi->fh <= 0) return set_errno(EBADF); _i32 r = sl_FsWrite(fi->fh, fi->pos, (_u8 *) buf, count); DBG(("sl_FsWrite(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count, (int) r)); if (r >= 0) { fi->pos += r; return r; } return set_errno(sl_fs_to_errno(r)); } int fs_slfs_stat(const char *pathname, struct stat *s) { SlFsFileInfo_t sl_fi; /* * Apply path manipulations again, in case we got here directly * (via TI libc's "add_device"). */ pathname = drop_dir(pathname, NULL); _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi); if (r == SL_FS_OK) { s->st_mode = S_IFREG | 0666; s->st_nlink = 1; s->st_size = SL_FI_FILE_SIZE(sl_fi); return 0; } return set_errno(sl_fs_to_errno(r)); } int fs_slfs_fstat(int fd, struct stat *s) { struct sl_fd_info *fi = &s_sl_fds[fd]; if (fi->fh <= 0) return set_errno(EBADF); s->st_mode = 0666; s->st_mode = S_IFREG | 0666; s->st_nlink = 1; s->st_size = fi->size; return 0; } off_t fs_slfs_lseek(int fd, off_t offset, int whence) { if (s_sl_fds[fd].fh <= 0) return set_errno(EBADF); switch (whence) { case SEEK_SET: s_sl_fds[fd].pos = offset; break; case SEEK_CUR: s_sl_fds[fd].pos += offset; break; case SEEK_END: return set_errno(ENOTSUP); } return 0; } int fs_slfs_unlink(const char *pathname) { /* * Apply path manipulations again, in case we got here directly * (via TI libc's "add_device"). */ pathname = drop_dir(pathname, NULL); return set_errno(sl_fs_to_errno(sl_FsDel((const _u8 *) pathname, 0))); } int fs_slfs_rename(const char *from, const char *to) { return set_errno(ENOTSUP); } static struct sl_file_open_info *fs_slfs_find_foi(const char *name, bool create) { int i = 0; for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) { if (s_sl_file_open_infos[i].name != NULL && strcmp(drop_dir(s_sl_file_open_infos[i].name, NULL), name) == 0) { break; } } if (i != MAX_OPEN_SLFS_FILES) return &s_sl_file_open_infos[i]; if (!create) return NULL; for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) { if (s_sl_file_open_infos[i].name == NULL) break; } if (i == MAX_OPEN_SLFS_FILES) { i = 0; /* Evict a random slot. */ } if (s_sl_file_open_infos[i].name != NULL) { free(s_sl_file_open_infos[i].name); } s_sl_file_open_infos[i].name = strdup(name); return &s_sl_file_open_infos[i]; } void fs_slfs_set_file_size(const char *name, size_t size) { struct sl_file_open_info *foi = fs_slfs_find_foi(name, true /* create */); foi->size = size; } void fs_slfs_set_file_flags(const char *name, uint32_t flags, uint32_t *token) { struct sl_file_open_info *foi = fs_slfs_find_foi(name, true /* create */); foi->flags = flags; foi->token = token; } void fs_slfs_unset_file_flags(const char *name) { struct sl_file_open_info *foi = fs_slfs_find_foi(name, false /* create */); if (foi == NULL) return; free(foi->name); memset(foi, 0, sizeof(*foi)); } #endif /* defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS) */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/simplelink/sl_fs.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if MG_NET_IF == MG_NET_IF_SIMPLELINK && \ (defined(MG_FS_SLFS) || defined(MG_FS_SPIFFS)) int set_errno(int e) { errno = e; return (e == 0 ? 0 : -1); } const char *drop_dir(const char *fname, bool *is_slfs) { if (is_slfs != NULL) { *is_slfs = (strncmp(fname, "SL:", 3) == 0); if (*is_slfs) fname += 3; } /* Drop "./", if any */ if (fname[0] == '.' && fname[1] == '/') { fname += 2; } /* * Drop / if it is the only one in the path. * This allows use of /pretend/directories but serves /file.txt as normal. */ if (fname[0] == '/' && strchr(fname + 1, '/') == NULL) { fname++; } return fname; } #if !defined(MG_FS_NO_VFS) #include <errno.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef __TI_COMPILER_VERSION__ #include <file.h> #endif /* Amalgamated: #include "common/cs_dbg.h" */ /* Amalgamated: #include "common/platform.h" */ #ifdef CC3200_FS_SPIFFS /* Amalgamated: #include "cc3200_fs_spiffs.h" */ #endif #ifdef MG_FS_SLFS /* Amalgamated: #include "sl_fs_slfs.h" */ #endif #define NUM_SYS_FDS 3 #define SPIFFS_FD_BASE 10 #define SLFS_FD_BASE 100 #if !defined(MG_UART_CHAR_PUT) && !defined(MG_UART_WRITE) #if CS_PLATFORM == CS_P_CC3200 #include <inc/hw_types.h> #include <inc/hw_memmap.h> #include <driverlib/rom.h> #include <driverlib/rom_map.h> #include <driverlib/uart.h> #define MG_UART_CHAR_PUT(fd, c) MAP_UARTCharPut(UARTA0_BASE, c); #else #define MG_UART_WRITE(fd, buf, len) #endif /* CS_PLATFORM == CS_P_CC3200 */ #endif /* !MG_UART_CHAR_PUT */ enum fd_type { FD_INVALID, FD_SYS, #ifdef CC3200_FS_SPIFFS FD_SPIFFS, #endif #ifdef MG_FS_SLFS FD_SLFS #endif }; static int fd_type(int fd) { if (fd >= 0 && fd < NUM_SYS_FDS) return FD_SYS; #ifdef CC3200_FS_SPIFFS if (fd >= SPIFFS_FD_BASE && fd < SPIFFS_FD_BASE + MAX_OPEN_SPIFFS_FILES) { return FD_SPIFFS; } #endif #ifdef MG_FS_SLFS if (fd >= SLFS_FD_BASE && fd < SLFS_FD_BASE + MAX_OPEN_SLFS_FILES) { return FD_SLFS; } #endif return FD_INVALID; } #if MG_TI_NO_HOST_INTERFACE int open(const char *pathname, unsigned flags, int mode) { #else int _open(const char *pathname, int flags, mode_t mode) { #endif int fd = -1; bool is_sl; const char *fname = drop_dir(pathname, &is_sl); if (is_sl) { #ifdef MG_FS_SLFS fd = fs_slfs_open(fname, flags, mode); if (fd >= 0) fd += SLFS_FD_BASE; #endif } else { #ifdef CC3200_FS_SPIFFS fd = fs_spiffs_open(fname, flags, mode); if (fd >= 0) fd += SPIFFS_FD_BASE; #endif } LOG(LL_DEBUG, ("open(%s, 0x%x) = %d, fname = %s", pathname, flags, fd, fname)); return fd; } int _stat(const char *pathname, struct stat *st) { int res = -1; bool is_sl; const char *fname = drop_dir(pathname, &is_sl); memset(st, 0, sizeof(*st)); /* Simulate statting the root directory. */ if (fname[0] == '\0' || strcmp(fname, ".") == 0) { st->st_ino = 0; st->st_mode = S_IFDIR | 0777; st->st_nlink = 1; st->st_size = 0; return 0; } if (is_sl) { #ifdef MG_FS_SLFS res = fs_slfs_stat(fname, st); #endif } else { #ifdef CC3200_FS_SPIFFS res = fs_spiffs_stat(fname, st); #endif } LOG(LL_DEBUG, ("stat(%s) = %d; fname = %s", pathname, res, fname)); return res; } #if MG_TI_NO_HOST_INTERFACE int close(int fd) { #else int _close(int fd) { #endif int r = -1; switch (fd_type(fd)) { case FD_INVALID: r = set_errno(EBADF); break; case FD_SYS: r = set_errno(EACCES); break; #ifdef CC3200_FS_SPIFFS case FD_SPIFFS: r = fs_spiffs_close(fd - SPIFFS_FD_BASE); break; #endif #ifdef MG_FS_SLFS case FD_SLFS: r = fs_slfs_close(fd - SLFS_FD_BASE); break; #endif } DBG(("close(%d) = %d", fd, r)); return r; } #if MG_TI_NO_HOST_INTERFACE off_t lseek(int fd, off_t offset, int whence) { #else off_t _lseek(int fd, off_t offset, int whence) { #endif int r = -1; switch (fd_type(fd)) { case FD_INVALID: r = set_errno(EBADF); break; case FD_SYS: r = set_errno(ESPIPE); break; #ifdef CC3200_FS_SPIFFS case FD_SPIFFS: r = fs_spiffs_lseek(fd - SPIFFS_FD_BASE, offset, whence); break; #endif #ifdef MG_FS_SLFS case FD_SLFS: r = fs_slfs_lseek(fd - SLFS_FD_BASE, offset, whence); break; #endif } DBG(("lseek(%d, %d, %d) = %d", fd, (int) offset, whence, r)); return r; } int _fstat(int fd, struct stat *s) { int r = -1; memset(s, 0, sizeof(*s)); switch (fd_type(fd)) { case FD_INVALID: r = set_errno(EBADF); break; case FD_SYS: { /* Create barely passable stats for STD{IN,OUT,ERR}. */ memset(s, 0, sizeof(*s)); s->st_ino = fd; s->st_mode = S_IFCHR | 0666; r = 0; break; } #ifdef CC3200_FS_SPIFFS case FD_SPIFFS: r = fs_spiffs_fstat(fd - SPIFFS_FD_BASE, s); break; #endif #ifdef MG_FS_SLFS case FD_SLFS: r = fs_slfs_fstat(fd - SLFS_FD_BASE, s); break; #endif } DBG(("fstat(%d) = %d", fd, r)); return r; } #if MG_TI_NO_HOST_INTERFACE int read(int fd, char *buf, unsigned count) { #else ssize_t _read(int fd, void *buf, size_t count) { #endif int r = -1; switch (fd_type(fd)) { case FD_INVALID: r = set_errno(EBADF); break; case FD_SYS: { if (fd != 0) { r = set_errno(EACCES); break; } /* Should we allow reading from stdin = uart? */ r = set_errno(ENOTSUP); break; } #ifdef CC3200_FS_SPIFFS case FD_SPIFFS: r = fs_spiffs_read(fd - SPIFFS_FD_BASE, buf, count); break; #endif #ifdef MG_FS_SLFS case FD_SLFS: r = fs_slfs_read(fd - SLFS_FD_BASE, buf, count); break; #endif } DBG(("read(%d, %u) = %d", fd, count, r)); return r; } #if MG_TI_NO_HOST_INTERFACE int write(int fd, const char *buf, unsigned count) { #else ssize_t _write(int fd, const void *buf, size_t count) { #endif int r = -1; switch (fd_type(fd)) { case FD_INVALID: r = set_errno(EBADF); break; case FD_SYS: { if (fd == 0) { r = set_errno(EACCES); break; } #ifdef MG_UART_WRITE MG_UART_WRITE(fd, buf, count); #elif defined(MG_UART_CHAR_PUT) { size_t i; for (i = 0; i < count; i++) { const char c = ((const char *) buf)[i]; if (c == '\n') MG_UART_CHAR_PUT(fd, '\r'); MG_UART_CHAR_PUT(fd, c); } } #endif r = count; break; } #ifdef CC3200_FS_SPIFFS case FD_SPIFFS: r = fs_spiffs_write(fd - SPIFFS_FD_BASE, buf, count); break; #endif #ifdef MG_FS_SLFS case FD_SLFS: r = fs_slfs_write(fd - SLFS_FD_BASE, buf, count); break; #endif } return r; } /* * On Newlib we override rename directly too, because the default * implementation using _link and _unlink doesn't work for us. */ #if MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION) int rename(const char *frompath, const char *topath) { int r = -1; bool is_sl_from, is_sl_to; const char *from = drop_dir(frompath, &is_sl_from); const char *to = drop_dir(topath, &is_sl_to); if (is_sl_from || is_sl_to) { set_errno(ENOTSUP); } else { #ifdef CC3200_FS_SPIFFS r = fs_spiffs_rename(from, to); #endif } DBG(("rename(%s, %s) = %d", from, to, r)); return r; } #endif /* MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION) */ #if MG_TI_NO_HOST_INTERFACE int unlink(const char *pathname) { #else int _unlink(const char *pathname) { #endif int r = -1; bool is_sl; const char *fname = drop_dir(pathname, &is_sl); if (is_sl) { #ifdef MG_FS_SLFS r = fs_slfs_unlink(fname); #endif } else { #ifdef CC3200_FS_SPIFFS r = fs_spiffs_unlink(fname); #endif } DBG(("unlink(%s) = %d, fname = %s", pathname, r, fname)); return r; } #ifdef CC3200_FS_SPIFFS /* FailFS does not support listing files. */ DIR *opendir(const char *dir_name) { DIR *r = NULL; bool is_sl; drop_dir(dir_name, &is_sl); if (is_sl) { r = NULL; set_errno(ENOTSUP); } else { r = fs_spiffs_opendir(dir_name); } DBG(("opendir(%s) = %p", dir_name, r)); return r; } struct dirent *readdir(DIR *dir) { struct dirent *res = fs_spiffs_readdir(dir); DBG(("readdir(%p) = %p", dir, res)); return res; } int closedir(DIR *dir) { int res = fs_spiffs_closedir(dir); DBG(("closedir(%p) = %d", dir, res)); return res; } int rmdir(const char *path) { return fs_spiffs_rmdir(path); } int mkdir(const char *path, mode_t mode) { (void) path; (void) mode; /* for spiffs supports only root dir, which comes from mongoose as '.' */ return (strlen(path) == 1 && *path == '.') ? 0 : ENOTDIR; } #endif int sl_fs_init(void) { int ret = 1; #ifdef __TI_COMPILER_VERSION__ #ifdef MG_FS_SLFS #pragma diag_push #pragma diag_suppress 169 /* Nothing we can do about the prototype mismatch. \ */ ret = (add_device("SL", _MSA, fs_slfs_open, fs_slfs_close, fs_slfs_read, fs_slfs_write, fs_slfs_lseek, fs_slfs_unlink, fs_slfs_rename) == 0); #pragma diag_pop #endif #endif return ret; } #endif /* !defined(MG_FS_NO_VFS) */ #endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && (defined(MG_FS_SLFS) || \ defined(MG_FS_SPIFFS)) */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/simplelink/sl_socket.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if MG_NET_IF == MG_NET_IF_SIMPLELINK #include <errno.h> #include <stdio.h> /* Amalgamated: #include "common/platform.h" */ const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) { int res; struct in_addr *in = (struct in_addr *) src; if (af != AF_INET) { errno = ENOTSUP; return NULL; } res = snprintf(dst, size, "%lu.%lu.%lu.%lu", SL_IPV4_BYTE(in->s_addr, 0), SL_IPV4_BYTE(in->s_addr, 1), SL_IPV4_BYTE(in->s_addr, 2), SL_IPV4_BYTE(in->s_addr, 3)); return res > 0 ? dst : NULL; } char *inet_ntoa(struct in_addr n) { static char a[16]; return (char *) inet_ntop(AF_INET, &n, a, sizeof(a)); } int inet_pton(int af, const char *src, void *dst) { uint32_t a0, a1, a2, a3; uint8_t *db = (uint8_t *) dst; if (af != AF_INET) { errno = ENOTSUP; return 0; } if (sscanf(src, "%lu.%lu.%lu.%lu", &a0, &a1, &a2, &a3) != 4) { return 0; } *db = a3; *(db + 1) = a2; *(db + 2) = a1; *(db + 3) = a0; return 1; } #endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/simplelink/sl_mg_task.c" #endif #if MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI) /* Amalgamated: #include "mg_task.h" */ #include <oslib/osi.h> enum mg_q_msg_type { MG_Q_MSG_CB, }; struct mg_q_msg { enum mg_q_msg_type type; void (*cb)(struct mg_mgr *mgr, void *arg); void *arg; }; static OsiMsgQ_t s_mg_q; static void mg_task(void *arg); bool mg_start_task(int priority, int stack_size, mg_init_cb mg_init) { if (osi_MsgQCreate(&s_mg_q, "MG", sizeof(struct mg_q_msg), 16) != OSI_OK) { return false; } if (osi_TaskCreate(mg_task, (const signed char *) "MG", stack_size, (void *) mg_init, priority, NULL) != OSI_OK) { return false; } return true; } static void mg_task(void *arg) { struct mg_mgr mgr; mg_init_cb mg_init = (mg_init_cb) arg; mg_mgr_init(&mgr, NULL); mg_init(&mgr); while (1) { struct mg_q_msg msg; mg_mgr_poll(&mgr, 1); if (osi_MsgQRead(&s_mg_q, &msg, 1) != OSI_OK) continue; switch (msg.type) { case MG_Q_MSG_CB: { msg.cb(&mgr, msg.arg); } } } } void mg_run_in_task(void (*cb)(struct mg_mgr *mgr, void *arg), void *cb_arg) { struct mg_q_msg msg = {MG_Q_MSG_CB, cb, cb_arg}; osi_MsgQWrite(&s_mg_q, &msg, OSI_NO_WAIT); } #endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI) \ */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/simplelink/sl_net_if.h" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_ #define CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_ /* Amalgamated: #include "mongoose/src/net_if.h" */ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #ifndef MG_ENABLE_NET_IF_SIMPLELINK #define MG_ENABLE_NET_IF_SIMPLELINK MG_NET_IF == MG_NET_IF_SIMPLELINK #endif extern const struct mg_iface_vtable mg_simplelink_iface_vtable; #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_ */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/simplelink/sl_net_if.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Amalgamated: #include "common/platforms/simplelink/sl_net_if.h" */ #if MG_ENABLE_NET_IF_SIMPLELINK /* Amalgamated: #include "mongoose/src/internal.h" */ /* Amalgamated: #include "mongoose/src/util.h" */ #define MG_TCP_RECV_BUFFER_SIZE 1024 #define MG_UDP_RECV_BUFFER_SIZE 1500 static sock_t mg_open_listening_socket(struct mg_connection *nc, union socket_address *sa, int type, int proto); static void mg_set_non_blocking_mode(sock_t sock) { SlSockNonblocking_t opt; #if SL_MAJOR_VERSION_NUM < 2 opt.NonblockingEnabled = 1; #else opt.NonBlockingEnabled = 1; #endif sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &opt, sizeof(opt)); } static int mg_is_error(int n) { return (n < 0 && n != SL_ERROR_BSD_EALREADY && n != SL_ERROR_BSD_EAGAIN); } static void mg_sl_if_connect_tcp(struct mg_connection *nc, const union socket_address *sa) { int proto = 0; #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET; #endif sock_t sock = sl_Socket(AF_INET, SOCK_STREAM, proto); if (sock < 0) { nc->err = sock; goto out; } mg_sock_set(nc, sock); #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK nc->err = sl_set_ssl_opts(sock, nc); if (nc->err != 0) goto out; #endif nc->err = sl_Connect(sock, &sa->sa, sizeof(sa->sin)); out: DBG(("%p to %s:%d sock %d %d err %d", nc, inet_ntoa(sa->sin.sin_addr), ntohs(sa->sin.sin_port), nc->sock, proto, nc->err)); } static void mg_sl_if_connect_udp(struct mg_connection *nc) { sock_t sock = sl_Socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) { nc->err = sock; return; } mg_sock_set(nc, sock); nc->err = 0; } static int mg_sl_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) { int proto = 0; if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET; sock_t sock = mg_open_listening_socket(nc, sa, SOCK_STREAM, proto); if (sock < 0) return sock; mg_sock_set(nc, sock); return 0; } static int mg_sl_if_listen_udp(struct mg_connection *nc, union socket_address *sa) { sock_t sock = mg_open_listening_socket(nc, sa, SOCK_DGRAM, 0); if (sock == INVALID_SOCKET) return (errno ? errno : 1); mg_sock_set(nc, sock); return 0; } static int mg_sl_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) { int n = (int) sl_Send(nc->sock, buf, len, 0); if (n < 0 && !mg_is_error(n)) n = 0; return n; } static int mg_sl_if_udp_send(struct mg_connection *nc, const void *buf, size_t len) { int n = sl_SendTo(nc->sock, buf, len, 0, &nc->sa.sa, sizeof(nc->sa.sin)); if (n < 0 && !mg_is_error(n)) n = 0; return n; } static int mg_sl_if_tcp_recv(struct mg_connection *nc, void *buf, size_t len) { int n = sl_Recv(nc->sock, buf, len, 0); if (n == 0) { /* Orderly shutdown of the socket, try flushing output. */ nc->flags |= MG_F_SEND_AND_CLOSE; } else if (n < 0 && !mg_is_error(n)) { n = 0; } return n; } static int mg_sl_if_udp_recv(struct mg_connection *nc, void *buf, size_t len, union socket_address *sa, size_t *sa_len) { SlSocklen_t sa_len_t = *sa_len; int n = sl_RecvFrom(nc->sock, buf, MG_UDP_RECV_BUFFER_SIZE, 0, (SlSockAddr_t *) sa, &sa_len_t); *sa_len = sa_len_t; if (n < 0 && !mg_is_error(n)) n = 0; return n; } static int mg_sl_if_create_conn(struct mg_connection *nc) { (void) nc; return 1; } void mg_sl_if_destroy_conn(struct mg_connection *nc) { if (nc->sock == INVALID_SOCKET) return; /* For UDP, only close outgoing sockets or listeners. */ if (!(nc->flags & MG_F_UDP) || nc->listener == NULL) { sl_Close(nc->sock); } nc->sock = INVALID_SOCKET; } static int mg_accept_conn(struct mg_connection *lc) { struct mg_connection *nc; union socket_address sa; socklen_t sa_len = sizeof(sa); sock_t sock = sl_Accept(lc->sock, &sa.sa, &sa_len); if (sock < 0) { DBG(("%p: failed to accept: %d", lc, sock)); return 0; } nc = mg_if_accept_new_conn(lc); if (nc == NULL) { sl_Close(sock); return 0; } DBG(("%p conn from %s:%d", nc, inet_ntoa(sa.sin.sin_addr), ntohs(sa.sin.sin_port))); mg_sock_set(nc, sock); mg_if_accept_tcp_cb(nc, &sa, sa_len); return 1; } /* 'sa' must be an initialized address to bind to */ static sock_t mg_open_listening_socket(struct mg_connection *nc, union socket_address *sa, int type, int proto) { int r; socklen_t sa_len = (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6); sock_t sock = sl_Socket(sa->sa.sa_family, type, proto); if (sock < 0) return sock; #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK if ((r = sl_set_ssl_opts(sock, nc)) < 0) goto clean; #endif if ((r = sl_Bind(sock, &sa->sa, sa_len)) < 0) goto clean; if (type != SOCK_DGRAM) { if ((r = sl_Listen(sock, SOMAXCONN)) < 0) goto clean; } mg_set_non_blocking_mode(sock); clean: if (r < 0) { sl_Close(sock); sock = r; } return sock; } #define _MG_F_FD_CAN_READ 1 #define _MG_F_FD_CAN_WRITE 1 << 1 #define _MG_F_FD_ERROR 1 << 2 void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) { DBG(("%p fd=%d fd_flags=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->sock, fd_flags, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len)); if (!mg_if_poll(nc, now)) return; if (nc->flags & MG_F_CONNECTING) { if ((nc->flags & MG_F_UDP) || nc->err != SL_ERROR_BSD_EALREADY) { mg_if_connect_cb(nc, nc->err); } else { /* In SimpleLink, to get status of non-blocking connect() we need to wait * until socket is writable and repeat the call to sl_Connect again, * which will now return the real status. */ if (fd_flags & _MG_F_FD_CAN_WRITE) { nc->err = sl_Connect(nc->sock, &nc->sa.sa, sizeof(nc->sa.sin)); DBG(("%p conn res=%d", nc, nc->err)); if (nc->err == SL_ERROR_BSD_ESECSNOVERIFY || /* TODO(rojer): Provide API to set the date for verification. */ nc->err == SL_ERROR_BSD_ESECDATEERROR #if SL_MAJOR_VERSION_NUM >= 2 /* Per SWRU455, this error does not mean verification failed, * it only means that the cert used is not present in the trusted * root CA catalog. Which is perfectly fine. */ || nc->err == SL_ERROR_BSD_ESECUNKNOWNROOTCA #endif ) { nc->err = 0; } mg_if_connect_cb(nc, nc->err); } } /* Ignore read/write in further processing, we've handled it. */ fd_flags &= ~(_MG_F_FD_CAN_READ | _MG_F_FD_CAN_WRITE); } if (fd_flags & _MG_F_FD_CAN_READ) { if (nc->flags & MG_F_UDP) { mg_if_can_recv_cb(nc); } else { if (nc->flags & MG_F_LISTENING) { mg_accept_conn(nc); } else { mg_if_can_recv_cb(nc); } } } if (fd_flags & _MG_F_FD_CAN_WRITE) { mg_if_can_send_cb(nc); } DBG(("%p after fd=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->sock, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len)); } /* Associate a socket to a connection. */ void mg_sl_if_sock_set(struct mg_connection *nc, sock_t sock) { mg_set_non_blocking_mode(sock); nc->sock = sock; DBG(("%p %d", nc, sock)); } void mg_sl_if_init(struct mg_iface *iface) { (void) iface; DBG(("%p using sl_Select()", iface->mgr)); } void mg_sl_if_free(struct mg_iface *iface) { (void) iface; } void mg_sl_if_add_conn(struct mg_connection *nc) { (void) nc; } void mg_sl_if_remove_conn(struct mg_connection *nc) { (void) nc; } time_t mg_sl_if_poll(struct mg_iface *iface, int timeout_ms) { struct mg_mgr *mgr = iface->mgr; double now = mg_time(); double min_timer; struct mg_connection *nc, *tmp; struct SlTimeval_t tv; SlFdSet_t read_set, write_set, err_set; sock_t max_fd = INVALID_SOCKET; int num_fds, num_ev = 0, num_timers = 0; SL_SOCKET_FD_ZERO(&read_set); SL_SOCKET_FD_ZERO(&write_set); SL_SOCKET_FD_ZERO(&err_set); /* * Note: it is ok to have connections with sock == INVALID_SOCKET in the list, * e.g. timer-only "connections". */ min_timer = 0; for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) { tmp = nc->next; if (nc->sock != INVALID_SOCKET) { num_fds++; if (!(nc->flags & MG_F_WANT_WRITE) && nc->recv_mbuf.len < nc->recv_mbuf_limit && (!(nc->flags & MG_F_UDP) || nc->listener == NULL)) { SL_SOCKET_FD_SET(nc->sock, &read_set); if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock; } if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) || (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) { SL_SOCKET_FD_SET(nc->sock, &write_set); SL_SOCKET_FD_SET(nc->sock, &err_set); if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock; } } if (nc->ev_timer_time > 0) { if (num_timers == 0 || nc->ev_timer_time < min_timer) { min_timer = nc->ev_timer_time; } num_timers++; } } /* * If there is a timer to be fired earlier than the requested timeout, * adjust the timeout. */ if (num_timers > 0) { double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */; if (timer_timeout_ms < timeout_ms) { timeout_ms = timer_timeout_ms; } } if (timeout_ms < 0) timeout_ms = 0; tv.tv_sec = timeout_ms / 1000; tv.tv_usec = (timeout_ms % 1000) * 1000; if (num_fds > 0) { num_ev = sl_Select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv); } now = mg_time(); DBG(("sl_Select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev, num_fds, timeout_ms)); for (nc = mgr->active_connections; nc != NULL; nc = tmp) { int fd_flags = 0; if (nc->sock != INVALID_SOCKET) { if (num_ev > 0) { fd_flags = (SL_SOCKET_FD_ISSET(nc->sock, &read_set) && (!(nc->flags & MG_F_UDP) || nc->listener == NULL) ? _MG_F_FD_CAN_READ : 0) | (SL_SOCKET_FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE : 0) | (SL_SOCKET_FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0); } /* SimpleLink does not report UDP sockets as writable. */ if (nc->flags & MG_F_UDP && nc->send_mbuf.len > 0) { fd_flags |= _MG_F_FD_CAN_WRITE; } } tmp = nc->next; mg_mgr_handle_conn(nc, fd_flags, now); } return now; } void mg_sl_if_get_conn_addr(struct mg_connection *nc, int remote, union socket_address *sa) { /* SimpleLink does not provide a way to get socket's peer address after * accept or connect. Address should have been preserved in the connection, * so we do our best here by using it. */ if (remote) memcpy(sa, &nc->sa, sizeof(*sa)); } void sl_restart_cb(struct mg_mgr *mgr) { /* * SimpleLink has been restarted, meaning all sockets have been invalidated. * We try our best - we'll restart the listeners, but for outgoing * connections we have no option but to terminate. */ struct mg_connection *nc; for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) { if (nc->sock == INVALID_SOCKET) continue; /* Could be a timer */ if (nc->flags & MG_F_LISTENING) { DBG(("restarting %p %s:%d", nc, inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port))); int res = (nc->flags & MG_F_UDP ? mg_sl_if_listen_udp(nc, &nc->sa) : mg_sl_if_listen_tcp(nc, &nc->sa)); if (res == 0) continue; /* Well, we tried and failed. Fall through to closing. */ } nc->sock = INVALID_SOCKET; DBG(("terminating %p %s:%d", nc, inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port))); /* TODO(rojer): Outgoing UDP? */ nc->flags |= MG_F_CLOSE_IMMEDIATELY; } } /* clang-format off */ #define MG_SL_IFACE_VTABLE \ { \ mg_sl_if_init, \ mg_sl_if_free, \ mg_sl_if_add_conn, \ mg_sl_if_remove_conn, \ mg_sl_if_poll, \ mg_sl_if_listen_tcp, \ mg_sl_if_listen_udp, \ mg_sl_if_connect_tcp, \ mg_sl_if_connect_udp, \ mg_sl_if_tcp_send, \ mg_sl_if_udp_send, \ mg_sl_if_tcp_recv, \ mg_sl_if_udp_recv, \ mg_sl_if_create_conn, \ mg_sl_if_destroy_conn, \ mg_sl_if_sock_set, \ mg_sl_if_get_conn_addr, \ } /* clang-format on */ const struct mg_iface_vtable mg_simplelink_iface_vtable = MG_SL_IFACE_VTABLE; #if MG_NET_IF == MG_NET_IF_SIMPLELINK const struct mg_iface_vtable mg_default_iface_vtable = MG_SL_IFACE_VTABLE; #endif #endif /* MG_ENABLE_NET_IF_SIMPLELINK */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/simplelink/sl_ssl_if.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK /* Amalgamated: #include "common/mg_mem.h" */ #ifndef MG_SSL_IF_SIMPLELINK_SLFS_PREFIX #define MG_SSL_IF_SIMPLELINK_SLFS_PREFIX "SL:" #endif #define MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN \ (sizeof(MG_SSL_IF_SIMPLELINK_SLFS_PREFIX) - 1) struct mg_ssl_if_ctx { char *ssl_cert; char *ssl_key; char *ssl_ca_cert; char *ssl_server_name; }; void mg_ssl_if_init() { } enum mg_ssl_if_result mg_ssl_if_conn_init( struct mg_connection *nc, const struct mg_ssl_if_conn_params *params, const char **err_msg) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx)); if (ctx == NULL) { MG_SET_PTRPTR(err_msg, "Out of memory"); return MG_SSL_ERROR; } nc->ssl_if_data = ctx; if (params->cert != NULL || params->key != NULL) { if (params->cert != NULL && params->key != NULL) { ctx->ssl_cert = strdup(params->cert); ctx->ssl_key = strdup(params->key); } else { MG_SET_PTRPTR(err_msg, "Both cert and key are required."); return MG_SSL_ERROR; } } if (params->ca_cert != NULL && strcmp(params->ca_cert, "*") != 0) { ctx->ssl_ca_cert = strdup(params->ca_cert); } /* TODO(rojer): cipher_suites. */ if (params->server_name != NULL) { ctx->ssl_server_name = strdup(params->server_name); } return MG_SSL_OK; } enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc, struct mg_connection *lc) { /* SimpleLink does everything for us, nothing for us to do. */ (void) nc; (void) lc; return MG_SSL_OK; } enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) { /* SimpleLink has already performed the handshake, nothing to do. */ return MG_SSL_OK; } int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t len) { /* SimpelLink handles TLS, so this is just a pass-through. */ int n = nc->iface->vtable->tcp_recv(nc, buf, len); if (n == 0) nc->flags |= MG_F_WANT_READ; return n; } int mg_ssl_if_write(struct mg_connection *nc, const void *buf, size_t len) { /* SimpelLink handles TLS, so this is just a pass-through. */ return nc->iface->vtable->tcp_send(nc, buf, len); } void mg_ssl_if_conn_close_notify(struct mg_connection *nc) { /* Nothing to do */ (void) nc; } void mg_ssl_if_conn_free(struct mg_connection *nc) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; if (ctx == NULL) return; nc->ssl_if_data = NULL; MG_FREE(ctx->ssl_cert); MG_FREE(ctx->ssl_key); MG_FREE(ctx->ssl_ca_cert); MG_FREE(ctx->ssl_server_name); memset(ctx, 0, sizeof(*ctx)); MG_FREE(ctx); } bool pem_to_der(const char *pem_file, const char *der_file) { bool ret = false; FILE *pf = NULL, *df = NULL; bool writing = false; pf = fopen(pem_file, "r"); if (pf == NULL) goto clean; remove(der_file); fs_slfs_set_file_size(der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN, 2048); df = fopen(der_file, "w"); fs_slfs_unset_file_flags(der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN); if (df == NULL) goto clean; while (1) { char pem_buf[70]; char der_buf[48]; if (!fgets(pem_buf, sizeof(pem_buf), pf)) break; if (writing) { if (strstr(pem_buf, "-----END ") != NULL) { ret = true; break; } int l = 0; while (!isspace((unsigned int) pem_buf[l])) l++; int der_len = 0; cs_base64_decode((const unsigned char *) pem_buf, sizeof(pem_buf), der_buf, &der_len); if (der_len <= 0) break; if (fwrite(der_buf, 1, der_len, df) != der_len) break; } else if (strstr(pem_buf, "-----BEGIN ") != NULL) { writing = true; } } clean: if (pf != NULL) fclose(pf); if (df != NULL) { fclose(df); if (!ret) remove(der_file); } return ret; } #if MG_ENABLE_FILESYSTEM && defined(MG_FS_SLFS) /* If the file's extension is .pem, convert it to DER format and put on SLFS. */ static char *sl_pem2der(const char *pem_file) { const char *pem_ext = strstr(pem_file, ".pem"); if (pem_ext == NULL || *(pem_ext + 4) != '\0') { return strdup(pem_file); } char *der_file = NULL; /* DER file must be located on SLFS, add prefix. */ int l = mg_asprintf(&der_file, 0, MG_SSL_IF_SIMPLELINK_SLFS_PREFIX "%.*s.der", (int) (pem_ext - pem_file), pem_file); if (der_file == NULL) return NULL; bool result = false; cs_stat_t st; if (mg_stat(der_file, &st) != 0) { result = pem_to_der(pem_file, der_file); LOG(LL_DEBUG, ("%s -> %s = %d", pem_file, der_file, result)); } else { /* File exists, assume it's already been converted. */ result = true; } if (result) { /* Strip the SL: prefix we added since NWP does not expect it. */ memmove(der_file, der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN, l - 2 /* including \0 */); } else { MG_FREE(der_file); der_file = NULL; } return der_file; } #else static char *sl_pem2der(const char *pem_file) { return strdup(pem_file); } #endif int sl_set_ssl_opts(int sock, struct mg_connection *nc) { int err; const struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; DBG(("%p ssl ctx: %p", nc, ctx)); if (ctx == NULL) return 0; DBG(("%p %s,%s,%s,%s", nc, (ctx->ssl_cert ? ctx->ssl_cert : "-"), (ctx->ssl_key ? ctx->ssl_cert : "-"), (ctx->ssl_ca_cert ? ctx->ssl_ca_cert : "-"), (ctx->ssl_server_name ? ctx->ssl_server_name : "-"))); if (ctx->ssl_cert != NULL && ctx->ssl_key != NULL) { char *ssl_cert = sl_pem2der(ctx->ssl_cert), *ssl_key = NULL; if (ssl_cert != NULL) { err = sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME, ssl_cert, strlen(ssl_cert)); MG_FREE(ssl_cert); LOG(LL_DEBUG, ("CERTIFICATE_FILE_NAME %s -> %d", ssl_cert, err)); ssl_key = sl_pem2der(ctx->ssl_key); if (ssl_key != NULL) { err = sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME, ssl_key, strlen(ssl_key)); MG_FREE(ssl_key); LOG(LL_DEBUG, ("PRIVATE_KEY_FILE_NAME %s -> %d", ssl_key, err)); } else { err = -1; } } else { err = -1; } if (err != 0) return err; } if (ctx->ssl_ca_cert != NULL) { if (ctx->ssl_ca_cert[0] != '\0') { char *ssl_ca_cert = sl_pem2der(ctx->ssl_ca_cert); if (ssl_ca_cert != NULL) { err = sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_SECURE_FILES_CA_FILE_NAME, ssl_ca_cert, strlen(ssl_ca_cert)); LOG(LL_DEBUG, ("CA_FILE_NAME %s -> %d", ssl_ca_cert, err)); } else { err = -1; } MG_FREE(ssl_ca_cert); if (err != 0) return err; } } if (ctx->ssl_server_name != NULL) { err = sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_SECURE_DOMAIN_NAME_VERIFICATION, ctx->ssl_server_name, strlen(ctx->ssl_server_name)); DBG(("DOMAIN_NAME_VERIFICATION %s -> %d", ctx->ssl_server_name, err)); /* Domain name verificationw as added in a NWP service pack, older * versions return SL_ERROR_BSD_ENOPROTOOPT. There isn't much we can do * about it, * so we ignore the error. */ if (err != 0 && err != SL_ERROR_BSD_ENOPROTOOPT) return err; } return 0; } #endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/lwip/mg_lwip_net_if.h" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_ #define CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_ #ifndef MG_ENABLE_NET_IF_LWIP_LOW_LEVEL #define MG_ENABLE_NET_IF_LWIP_LOW_LEVEL MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL #endif #if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL #include <stdint.h> extern const struct mg_iface_vtable mg_lwip_iface_vtable; struct mg_lwip_conn_state { struct mg_connection *nc; struct mg_connection *lc; union { struct tcp_pcb *tcp; struct udp_pcb *udp; } pcb; err_t err; size_t num_sent; /* Number of acknowledged bytes to be reported to the core */ struct pbuf *rx_chain; /* Chain of incoming data segments. */ size_t rx_offset; /* Offset within the first pbuf (if partially consumed) */ /* Last SSL write size, for retries. */ int last_ssl_write_size; /* Whether MG_SIG_RECV is already pending for this connection */ int recv_pending; /* Whether the connection is about to close, just `rx_chain` needs to drain */ int draining_rx_chain; }; enum mg_sig_type { MG_SIG_CONNECT_RESULT = 1, MG_SIG_RECV = 2, MG_SIG_CLOSE_CONN = 3, MG_SIG_TOMBSTONE = 4, MG_SIG_ACCEPT = 5, }; void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc); /* To be implemented by the platform. */ void mg_lwip_mgr_schedule_poll(struct mg_mgr *mgr); #endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */ #endif /* CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_ */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/lwip/mg_lwip_net_if.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL /* Amalgamated: #include "common/mg_mem.h" */ #include <lwip/init.h> #include <lwip/pbuf.h> #include <lwip/tcp.h> #include <lwip/tcpip.h> #if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105 #include <lwip/priv/tcp_priv.h> /* For tcp_seg */ #include <lwip/priv/tcpip_priv.h> /* For tcpip_api_call */ #else #include <lwip/tcp_impl.h> #endif #include <lwip/udp.h> /* Amalgamated: #include "common/cs_dbg.h" */ /* * Newest versions of LWIP have ip_2_ip4, older have ipX_2_ip, * even older have nothing. */ #ifndef ip_2_ip4 #ifdef ipX_2_ip #define ip_2_ip4(addr) ipX_2_ip(addr) #else #define ip_2_ip4(addr) (addr) #endif #endif /* * Depending on whether Mongoose is compiled with ipv6 support, use right * lwip functions */ #if MG_ENABLE_IPV6 #define TCP_NEW tcp_new_ip6 #define TCP_BIND tcp_bind_ip6 #define UDP_BIND udp_bind_ip6 #define IPADDR_NTOA(x) ip6addr_ntoa((const ip6_addr_t *)(x)) #define SET_ADDR(dst, src) \ memcpy((dst)->sin6.sin6_addr.s6_addr, (src)->ip6.addr, \ sizeof((dst)->sin6.sin6_addr.s6_addr)) #else #define TCP_NEW tcp_new #define TCP_BIND tcp_bind #define UDP_BIND udp_bind #define IPADDR_NTOA ipaddr_ntoa #define SET_ADDR(dst, src) (dst)->sin.sin_addr.s_addr = ip_2_ip4(src)->addr #endif #if !NO_SYS #if LWIP_TCPIP_CORE_LOCKING /* With locking tcpip_api_call is just a function call wrapped in lock/unlock, * so we can get away with just casting. */ void mg_lwip_netif_run_on_tcpip(void (*fn)(void *), void *arg) { tcpip_api_call((tcpip_api_call_fn) fn, (struct tcpip_api_call_data *) arg); } #else static sys_sem_t s_tcpip_call_lock_sem = NULL; static sys_sem_t s_tcpip_call_sync_sem = NULL; struct mg_lwip_netif_tcpip_call_ctx { void (*fn)(void *); void *arg; }; static void xxx_tcpip(void *arg) { struct mg_lwip_netif_tcpip_call_ctx *ctx = (struct mg_lwip_netif_tcpip_call_ctx *) arg; ctx->fn(ctx->arg); sys_sem_signal(&s_tcpip_call_sync_sem); } void mg_lwip_netif_run_on_tcpip(void (*fn)(void *), void *arg) { struct mg_lwip_netif_tcpip_call_ctx ctx = {.fn = fn, .arg = arg}; sys_arch_sem_wait(&s_tcpip_call_lock_sem, 0); tcpip_send_msg_wait_sem(xxx_tcpip, &ctx, &s_tcpip_call_sync_sem); sys_sem_signal(&s_tcpip_call_lock_sem); } #endif #else #define mg_lwip_netif_run_on_tcpip(fn, arg) (fn)(arg) #endif void mg_lwip_if_init(struct mg_iface *iface); void mg_lwip_if_free(struct mg_iface *iface); void mg_lwip_if_add_conn(struct mg_connection *nc); void mg_lwip_if_remove_conn(struct mg_connection *nc); time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms); // If compiling for Mongoose OS. #ifdef MGOS extern void mgos_lock(); extern void mgos_unlock(); #else #define mgos_lock() #define mgos_unlock() #endif static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p); #if LWIP_TCP_KEEPALIVE void mg_lwip_set_keepalive_params(struct mg_connection *nc, int idle, int interval, int count) { if (nc->sock == INVALID_SOCKET || nc->flags & MG_F_UDP) { return; } struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; struct tcp_pcb *tpcb = cs->pcb.tcp; if (idle > 0 && interval > 0 && count > 0) { tpcb->keep_idle = idle * 1000; tpcb->keep_intvl = interval * 1000; tpcb->keep_cnt = count; tpcb->so_options |= SOF_KEEPALIVE; } else { tpcb->so_options &= ~SOF_KEEPALIVE; } } #elif !defined(MG_NO_LWIP_TCP_KEEPALIVE) #warning LWIP TCP keepalive is disabled. Please consider enabling it. #endif /* LWIP_TCP_KEEPALIVE */ static err_t mg_lwip_tcp_conn_cb(void *arg, struct tcp_pcb *tpcb, err_t err) { struct mg_connection *nc = (struct mg_connection *) arg; DBG(("%p connect to %s:%u = %d", nc, IPADDR_NTOA(ipX_2_ip(&tpcb->remote_ip)), tpcb->remote_port, err)); if (nc == NULL) { tcp_abort(tpcb); return ERR_ARG; } struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; cs->err = err; #if LWIP_TCP_KEEPALIVE if (err == 0) mg_lwip_set_keepalive_params(nc, 60, 10, 6); #endif mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc); return ERR_OK; } static void mg_lwip_tcp_error_cb(void *arg, err_t err) { struct mg_connection *nc = (struct mg_connection *) arg; DBG(("%p conn error %d", nc, err)); if (nc == NULL || (nc->flags & MG_F_CLOSE_IMMEDIATELY)) return; struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; cs->pcb.tcp = NULL; /* Has already been deallocated */ if (nc->flags & MG_F_CONNECTING) { cs->err = err; mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc); } else { mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc); } } static err_t mg_lwip_tcp_recv_cb(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err) { struct mg_connection *nc = (struct mg_connection *) arg; struct mg_lwip_conn_state *cs = (nc ? (struct mg_lwip_conn_state *) nc->sock : NULL); DBG(("%p %p %p %p %u %d", nc, cs, tpcb, p, (p != NULL ? p->tot_len : 0), err)); if (p == NULL) { if (nc != NULL && !(nc->flags & MG_F_CLOSE_IMMEDIATELY)) { if (cs->rx_chain != NULL) { /* * rx_chain still contains non-consumed data, don't close the * connection */ cs->draining_rx_chain = 1; } else { mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc); } } else { /* Tombstoned connection, do nothing. */ } return ERR_OK; } else if (nc == NULL) { tcp_abort(tpcb); return ERR_ARG; } /* * If we get a chain of more than one segment at once, we need to bump * refcount on the subsequent bufs to make them independent. */ if (p->next != NULL) { struct pbuf *q = p->next; for (; q != NULL; q = q->next) pbuf_ref(q); } mgos_lock(); if (cs->rx_chain == NULL) { cs->rx_offset = 0; } else if (pbuf_clen(cs->rx_chain) >= 4) { /* ESP SDK has a limited pool of 5 pbufs. We must not hog them all or RX * will be completely blocked. We already have at least 4 in the chain, * this one is the last, so we have to make a copy and release this one. */ struct pbuf *np = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM); if (np != NULL) { pbuf_copy(np, p); pbuf_free(p); p = np; } } mg_lwip_recv_common(nc, p); mgos_unlock(); (void) err; return ERR_OK; } static err_t mg_lwip_tcp_sent_cb(void *arg, struct tcp_pcb *tpcb, u16_t num_sent) { struct mg_connection *nc = (struct mg_connection *) arg; DBG(("%p %p %u %p %p", nc, tpcb, num_sent, tpcb->unsent, tpcb->unacked)); if (nc == NULL) return ERR_OK; if ((nc->flags & MG_F_SEND_AND_CLOSE) && !(nc->flags & MG_F_WANT_WRITE) && nc->send_mbuf.len == 0 && tpcb->unsent == NULL && tpcb->unacked == NULL) { mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc); } if (nc->send_mbuf.len > 0 || (nc->flags & MG_F_WANT_WRITE)) { mg_lwip_mgr_schedule_poll(nc->mgr); } (void) num_sent; return ERR_OK; } struct mg_lwip_if_connect_tcp_ctx { struct mg_connection *nc; const union socket_address *sa; }; static void mg_lwip_if_connect_tcp_tcpip(void *arg) { struct mg_lwip_if_connect_tcp_ctx *ctx = (struct mg_lwip_if_connect_tcp_ctx *) arg; struct mg_connection *nc = ctx->nc; const union socket_address *sa = ctx->sa; struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; struct tcp_pcb *tpcb = TCP_NEW(); cs->pcb.tcp = tpcb; ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr; u16_t port = ntohs(sa->sin.sin_port); tcp_arg(tpcb, nc); tcp_err(tpcb, mg_lwip_tcp_error_cb); tcp_sent(tpcb, mg_lwip_tcp_sent_cb); tcp_recv(tpcb, mg_lwip_tcp_recv_cb); cs->err = TCP_BIND(tpcb, IP_ADDR_ANY, 0 /* any port */); DBG(("%p tcp_bind = %d", nc, cs->err)); if (cs->err != ERR_OK) { mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc); return; } cs->err = tcp_connect(tpcb, ip, port, mg_lwip_tcp_conn_cb); DBG(("%p tcp_connect %p = %d", nc, tpcb, cs->err)); if (cs->err != ERR_OK) { mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc); return; } } void mg_lwip_if_connect_tcp(struct mg_connection *nc, const union socket_address *sa) { struct mg_lwip_if_connect_tcp_ctx ctx = {.nc = nc, .sa = sa}; mg_lwip_netif_run_on_tcpip(mg_lwip_if_connect_tcp_tcpip, &ctx); } /* * Lwip included in the SDKs for nRF5x chips has different type for the * callback of `udp_recv()` */ #if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105 static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, u16_t port) #else static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p, ip_addr_t *addr, u16_t port) #endif { struct mg_connection *nc = (struct mg_connection *) arg; DBG(("%p %s:%u %p %u %u", nc, IPADDR_NTOA(addr), port, p, p->ref, p->len)); /* Put address in a separate pbuf and tack it onto the packet. */ struct pbuf *sap = pbuf_alloc(PBUF_RAW, sizeof(union socket_address), PBUF_RAM); if (sap == NULL) { pbuf_free(p); return; } union socket_address *sa = (union socket_address *) sap->payload; #if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105 sa->sin.sin_addr.s_addr = ip_2_ip4(addr)->addr; #else sa->sin.sin_addr.s_addr = addr->addr; #endif sa->sin.sin_port = htons(port); /* Logic in the recv handler requires that there be exactly one data pbuf. */ p = pbuf_coalesce(p, PBUF_RAW); pbuf_chain(sap, p); mgos_lock(); mg_lwip_recv_common(nc, sap); mgos_unlock(); (void) pcb; } static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p) { struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; if (cs->rx_chain == NULL) { cs->rx_chain = p; } else { pbuf_chain(cs->rx_chain, p); } if (!cs->recv_pending) { cs->recv_pending = 1; mg_lwip_post_signal(MG_SIG_RECV, nc); } } static int mg_lwip_if_udp_recv(struct mg_connection *nc, void *buf, size_t len, union socket_address *sa, size_t *sa_len) { /* * For UDP, RX chain consists of interleaved address and packet bufs: * Address pbuf followed by exactly one data pbuf (recv_cb took care of that). */ int res = 0; struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; if (nc->sock == INVALID_SOCKET) return -1; mgos_lock(); if (cs->rx_chain != NULL) { struct pbuf *ap = cs->rx_chain; struct pbuf *dp = ap->next; cs->rx_chain = pbuf_dechain(dp); res = MIN(dp->len, len); pbuf_copy_partial(dp, buf, res, 0); pbuf_free(dp); pbuf_copy_partial(ap, sa, MIN(*sa_len, ap->len), 0); pbuf_free(ap); } mgos_unlock(); return res; } static void mg_lwip_if_connect_udp_tcpip(void *arg) { struct mg_connection *nc = (struct mg_connection *) arg; struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; struct udp_pcb *upcb = udp_new(); cs->err = UDP_BIND(upcb, IP_ADDR_ANY, 0 /* any port */); DBG(("%p udp_bind %p = %d", nc, upcb, cs->err)); if (cs->err == ERR_OK) { udp_recv(upcb, mg_lwip_udp_recv_cb, nc); cs->pcb.udp = upcb; } else { udp_remove(upcb); } mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc); } void mg_lwip_if_connect_udp(struct mg_connection *nc) { mg_lwip_netif_run_on_tcpip(mg_lwip_if_connect_udp_tcpip, nc); } static void tcp_close_tcpip(void *arg) { tcp_close((struct tcp_pcb *) arg); } void mg_lwip_handle_accept(struct mg_connection *nc) { struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; if (cs->pcb.tcp == NULL) return; union socket_address sa; struct tcp_pcb *tpcb = cs->pcb.tcp; SET_ADDR(&sa, &tpcb->remote_ip); sa.sin.sin_port = htons(tpcb->remote_port); mg_if_accept_tcp_cb(nc, &sa, sizeof(sa.sin)); } static err_t mg_lwip_accept_cb(void *arg, struct tcp_pcb *newtpcb, err_t err) { struct mg_connection *lc = (struct mg_connection *) arg, *nc; struct mg_lwip_conn_state *lcs, *cs; struct tcp_pcb_listen *lpcb; LOG(LL_DEBUG, ("%p conn %p from %s:%u", lc, newtpcb, IPADDR_NTOA(ipX_2_ip(&newtpcb->remote_ip)), newtpcb->remote_port)); if (lc == NULL) { tcp_abort(newtpcb); return ERR_ABRT; } lcs = (struct mg_lwip_conn_state *) lc->sock; lpcb = (struct tcp_pcb_listen *) lcs->pcb.tcp; #if TCP_LISTEN_BACKLOG tcp_accepted(lpcb); #endif nc = mg_if_accept_new_conn(lc); if (nc == NULL) { tcp_abort(newtpcb); return ERR_ABRT; } cs = (struct mg_lwip_conn_state *) nc->sock; cs->lc = lc; cs->pcb.tcp = newtpcb; /* We need to set up callbacks before returning because data may start * arriving immediately. */ tcp_arg(newtpcb, nc); tcp_err(newtpcb, mg_lwip_tcp_error_cb); tcp_sent(newtpcb, mg_lwip_tcp_sent_cb); tcp_recv(newtpcb, mg_lwip_tcp_recv_cb); #if LWIP_TCP_KEEPALIVE mg_lwip_set_keepalive_params(nc, 60, 10, 6); #endif mg_lwip_post_signal(MG_SIG_ACCEPT, nc); (void) err; (void) lpcb; return ERR_OK; } struct mg_lwip_if_listen_ctx { struct mg_connection *nc; union socket_address *sa; int ret; }; static void mg_lwip_if_listen_tcp_tcpip(void *arg) { struct mg_lwip_if_listen_ctx *ctx = (struct mg_lwip_if_listen_ctx *) arg; struct mg_connection *nc = ctx->nc; union socket_address *sa = ctx->sa; struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; struct tcp_pcb *tpcb = TCP_NEW(); ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr; u16_t port = ntohs(sa->sin.sin_port); cs->err = TCP_BIND(tpcb, ip, port); DBG(("%p tcp_bind(%s:%u) = %d", nc, IPADDR_NTOA(ip), port, cs->err)); if (cs->err != ERR_OK) { tcp_close(tpcb); ctx->ret = -1; return; } tcp_arg(tpcb, nc); tpcb = tcp_listen(tpcb); cs->pcb.tcp = tpcb; tcp_accept(tpcb, mg_lwip_accept_cb); ctx->ret = 0; } int mg_lwip_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) { struct mg_lwip_if_listen_ctx ctx = {.nc = nc, .sa = sa}; mg_lwip_netif_run_on_tcpip(mg_lwip_if_listen_tcp_tcpip, &ctx); return ctx.ret; } static void mg_lwip_if_listen_udp_tcpip(void *arg) { struct mg_lwip_if_listen_ctx *ctx = (struct mg_lwip_if_listen_ctx *) arg; struct mg_connection *nc = ctx->nc; union socket_address *sa = ctx->sa; struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; struct udp_pcb *upcb = udp_new(); ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr; u16_t port = ntohs(sa->sin.sin_port); cs->err = UDP_BIND(upcb, ip, port); DBG(("%p udb_bind(%s:%u) = %d", nc, IPADDR_NTOA(ip), port, cs->err)); if (cs->err != ERR_OK) { udp_remove(upcb); ctx->ret = -1; } else { udp_recv(upcb, mg_lwip_udp_recv_cb, nc); cs->pcb.udp = upcb; ctx->ret = 0; } } int mg_lwip_if_listen_udp(struct mg_connection *nc, union socket_address *sa) { struct mg_lwip_if_listen_ctx ctx = {.nc = nc, .sa = sa}; mg_lwip_netif_run_on_tcpip(mg_lwip_if_listen_udp_tcpip, &ctx); return ctx.ret; } struct mg_lwip_tcp_write_ctx { struct mg_connection *nc; const void *data; uint16_t len; int ret; }; static void tcp_output_tcpip(void *arg) { tcp_output((struct tcp_pcb *) arg); } static void mg_lwip_tcp_write_tcpip(void *arg) { struct mg_lwip_tcp_write_ctx *ctx = (struct mg_lwip_tcp_write_ctx *) arg; struct mg_connection *nc = ctx->nc; struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; struct tcp_pcb *tpcb = cs->pcb.tcp; size_t len = MIN(tpcb->mss, MIN(ctx->len, tpcb->snd_buf)); size_t unsent, unacked; if (len == 0) { DBG(("%p no buf avail %u %u %p %p", tpcb, tpcb->snd_buf, tpcb->snd_queuelen, tpcb->unsent, tpcb->unacked)); mg_lwip_netif_run_on_tcpip(tcp_output_tcpip, tpcb); ctx->ret = 0; return; } unsent = (tpcb->unsent != NULL ? tpcb->unsent->len : 0); unacked = (tpcb->unacked != NULL ? tpcb->unacked->len : 0); /* * On ESP8266 we only allow one TCP segment in flight at any given time. * This may increase latency and reduce efficiency of tcp windowing, * but memory is scarce and precious on that platform so we do this to * reduce footprint. */ #if CS_PLATFORM == CS_P_ESP8266 if (unacked > 0) { ctx->ret = 0; return; } len = MIN(len, (TCP_MSS - unsent)); #endif cs->err = tcp_write(tpcb, ctx->data, len, TCP_WRITE_FLAG_COPY); unsent = (tpcb->unsent != NULL ? tpcb->unsent->len : 0); unacked = (tpcb->unacked != NULL ? tpcb->unacked->len : 0); DBG(("%p tcp_write %u = %d, %u %u", tpcb, len, cs->err, unsent, unacked)); if (cs->err != ERR_OK) { /* * We ignore ERR_MEM because memory will be freed up when the data is sent * and we'll retry. */ ctx->ret = (cs->err == ERR_MEM ? 0 : -1); return; } ctx->ret = len; (void) unsent; (void) unacked; } int mg_lwip_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) { struct mg_lwip_tcp_write_ctx ctx = {.nc = nc, .data = buf, .len = len}; struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; if (nc->sock == INVALID_SOCKET) return -1; struct tcp_pcb *tpcb = cs->pcb.tcp; if (tpcb == NULL) return -1; if (tpcb->snd_buf <= 0) return 0; mg_lwip_netif_run_on_tcpip(mg_lwip_tcp_write_tcpip, &ctx); return ctx.ret; } struct udp_sendto_ctx { struct udp_pcb *upcb; struct pbuf *p; ip_addr_t *ip; uint16_t port; int ret; }; static void udp_sendto_tcpip(void *arg) { struct udp_sendto_ctx *ctx = (struct udp_sendto_ctx *) arg; ctx->ret = udp_sendto(ctx->upcb, ctx->p, ctx->ip, ctx->port); } static int mg_lwip_if_udp_send(struct mg_connection *nc, const void *data, size_t len) { struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; if (nc->sock == INVALID_SOCKET || cs->pcb.udp == NULL) return -1; struct udp_pcb *upcb = cs->pcb.udp; struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM); #if defined(LWIP_IPV4) && LWIP_IPV4 && defined(LWIP_IPV6) && LWIP_IPV6 ip_addr_t ip = {.u_addr.ip4.addr = nc->sa.sin.sin_addr.s_addr, .type = 0}; #else ip_addr_t ip = {.addr = nc->sa.sin.sin_addr.s_addr}; #endif u16_t port = ntohs(nc->sa.sin.sin_port); if (p == NULL) return 0; memcpy(p->payload, data, len); struct udp_sendto_ctx ctx = {.upcb = upcb, .p = p, .ip = &ip, .port = port}; mg_lwip_netif_run_on_tcpip(udp_sendto_tcpip, &ctx); cs->err = ctx.ret; pbuf_free(p); return (cs->err == ERR_OK ? (int) len : -2); } static int mg_lwip_if_can_send(struct mg_connection *nc, struct mg_lwip_conn_state *cs) { int can_send = 0; if (nc->send_mbuf.len > 0 || (nc->flags & MG_F_WANT_WRITE)) { /* We have stuff to send, but can we? */ if (nc->flags & MG_F_UDP) { /* UDP is always ready for sending. */ can_send = (cs->pcb.udp != NULL); } else { can_send = (cs->pcb.tcp != NULL && cs->pcb.tcp->snd_buf > 0); /* See comment above. */ #if CS_PLATFORM == CS_P_ESP8266 if (cs->pcb.tcp->unacked != NULL) can_send = 0; #endif } } return can_send; } struct tcp_recved_ctx { struct tcp_pcb *tpcb; size_t len; }; void tcp_recved_tcpip(void *arg) { struct tcp_recved_ctx *ctx = (struct tcp_recved_ctx *) arg; if (ctx->tpcb != NULL) tcp_recved(ctx->tpcb, ctx->len); } static int mg_lwip_if_tcp_recv(struct mg_connection *nc, void *buf, size_t len) { int res = 0; char *bufp = buf; struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; if (nc->sock == INVALID_SOCKET) return -1; mgos_lock(); while (cs->rx_chain != NULL && len > 0) { struct pbuf *seg = cs->rx_chain; size_t seg_len = (seg->len - cs->rx_offset); size_t copy_len = MIN(len, seg_len); pbuf_copy_partial(seg, bufp, copy_len, cs->rx_offset); len -= copy_len; res += copy_len; bufp += copy_len; cs->rx_offset += copy_len; if (cs->rx_offset == cs->rx_chain->len) { cs->rx_chain = pbuf_dechain(cs->rx_chain); pbuf_free(seg); cs->rx_offset = 0; } } mgos_unlock(); if (res > 0) { struct tcp_recved_ctx ctx = {.tpcb = cs->pcb.tcp, .len = res}; mg_lwip_netif_run_on_tcpip(tcp_recved_tcpip, &ctx); } return res; } int mg_lwip_if_create_conn(struct mg_connection *nc) { struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) MG_CALLOC(1, sizeof(*cs)); if (cs == NULL) return 0; cs->nc = nc; nc->sock = (intptr_t) cs; return 1; } static void udp_remove_tcpip(void *arg) { udp_remove((struct udp_pcb *) arg); } void mg_lwip_if_destroy_conn(struct mg_connection *nc) { if (nc->sock == INVALID_SOCKET) return; struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; if (!(nc->flags & MG_F_UDP)) { struct tcp_pcb *tpcb = cs->pcb.tcp; if (tpcb != NULL) { tcp_arg(tpcb, NULL); DBG(("%p tcp_close %p", nc, tpcb)); tcp_arg(tpcb, NULL); mg_lwip_netif_run_on_tcpip(tcp_close_tcpip, tpcb); } while (cs->rx_chain != NULL) { struct pbuf *seg = cs->rx_chain; cs->rx_chain = pbuf_dechain(cs->rx_chain); pbuf_free(seg); } memset(cs, 0, sizeof(*cs)); MG_FREE(cs); } else if (nc->listener == NULL) { /* Only close outgoing UDP pcb or listeners. */ struct udp_pcb *upcb = cs->pcb.udp; if (upcb != NULL) { DBG(("%p udp_remove %p", nc, upcb)); mg_lwip_netif_run_on_tcpip(udp_remove_tcpip, upcb); } memset(cs, 0, sizeof(*cs)); MG_FREE(cs); } nc->sock = INVALID_SOCKET; } void mg_lwip_if_get_conn_addr(struct mg_connection *nc, int remote, union socket_address *sa) { memset(sa, 0, sizeof(*sa)); if (nc == NULL || nc->sock == INVALID_SOCKET) return; struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; if (nc->flags & MG_F_UDP) { struct udp_pcb *upcb = cs->pcb.udp; if (remote) { memcpy(sa, &nc->sa, sizeof(*sa)); } else if (upcb != NULL) { sa->sin.sin_port = htons(upcb->local_port); SET_ADDR(sa, &upcb->local_ip); } } else { struct tcp_pcb *tpcb = cs->pcb.tcp; if (remote) { memcpy(sa, &nc->sa, sizeof(*sa)); } else if (tpcb != NULL) { sa->sin.sin_port = htons(tpcb->local_port); SET_ADDR(sa, &tpcb->local_ip); } } } void mg_lwip_if_sock_set(struct mg_connection *nc, sock_t sock) { nc->sock = sock; } /* clang-format off */ #define MG_LWIP_IFACE_VTABLE \ { \ mg_lwip_if_init, \ mg_lwip_if_free, \ mg_lwip_if_add_conn, \ mg_lwip_if_remove_conn, \ mg_lwip_if_poll, \ mg_lwip_if_listen_tcp, \ mg_lwip_if_listen_udp, \ mg_lwip_if_connect_tcp, \ mg_lwip_if_connect_udp, \ mg_lwip_if_tcp_send, \ mg_lwip_if_udp_send, \ mg_lwip_if_tcp_recv, \ mg_lwip_if_udp_recv, \ mg_lwip_if_create_conn, \ mg_lwip_if_destroy_conn, \ mg_lwip_if_sock_set, \ mg_lwip_if_get_conn_addr, \ } /* clang-format on */ const struct mg_iface_vtable mg_lwip_iface_vtable = MG_LWIP_IFACE_VTABLE; #if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL const struct mg_iface_vtable mg_default_iface_vtable = MG_LWIP_IFACE_VTABLE; #endif #endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/lwip/mg_lwip_ev_mgr.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL #ifndef MG_SIG_QUEUE_LEN #define MG_SIG_QUEUE_LEN 32 #endif struct mg_ev_mgr_lwip_signal { int sig; struct mg_connection *nc; }; struct mg_ev_mgr_lwip_data { struct mg_ev_mgr_lwip_signal sig_queue[MG_SIG_QUEUE_LEN]; int sig_queue_len; int start_index; }; void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc) { struct mg_ev_mgr_lwip_data *md = (struct mg_ev_mgr_lwip_data *) nc->iface->data; mgos_lock(); if (md->sig_queue_len >= MG_SIG_QUEUE_LEN) { mgos_unlock(); return; } int end_index = (md->start_index + md->sig_queue_len) % MG_SIG_QUEUE_LEN; md->sig_queue[end_index].sig = sig; md->sig_queue[end_index].nc = nc; md->sig_queue_len++; mg_lwip_mgr_schedule_poll(nc->mgr); mgos_unlock(); } void mg_ev_mgr_lwip_process_signals(struct mg_mgr *mgr) { struct mg_ev_mgr_lwip_data *md = (struct mg_ev_mgr_lwip_data *) mgr->ifaces[MG_MAIN_IFACE]->data; while (md->sig_queue_len > 0) { mgos_lock(); int i = md->start_index; int sig = md->sig_queue[i].sig; struct mg_connection *nc = md->sig_queue[i].nc; struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; md->start_index = (i + 1) % MG_SIG_QUEUE_LEN; md->sig_queue_len--; mgos_unlock(); if (nc->iface == NULL || nc->mgr == NULL) continue; switch (sig) { case MG_SIG_CONNECT_RESULT: { mg_if_connect_cb(nc, cs->err); break; } case MG_SIG_CLOSE_CONN: { mg_close_conn(nc); break; } case MG_SIG_RECV: { cs->recv_pending = 0; mg_if_can_recv_cb(nc); mbuf_trim(&nc->recv_mbuf); break; } case MG_SIG_TOMBSTONE: { break; } case MG_SIG_ACCEPT: { mg_lwip_handle_accept(nc); break; } } } } void mg_lwip_if_init(struct mg_iface *iface) { LOG(LL_INFO, ("Mongoose %s, LwIP %u.%u.%u", MG_VERSION, LWIP_VERSION_MAJOR, LWIP_VERSION_MINOR, LWIP_VERSION_REVISION)); iface->data = MG_CALLOC(1, sizeof(struct mg_ev_mgr_lwip_data)); #if !NO_SYS && !LWIP_TCPIP_CORE_LOCKING sys_sem_new(&s_tcpip_call_lock_sem, 1); sys_sem_new(&s_tcpip_call_sync_sem, 0); #endif } void mg_lwip_if_free(struct mg_iface *iface) { MG_FREE(iface->data); iface->data = NULL; } void mg_lwip_if_add_conn(struct mg_connection *nc) { (void) nc; } void mg_lwip_if_remove_conn(struct mg_connection *nc) { struct mg_ev_mgr_lwip_data *md = (struct mg_ev_mgr_lwip_data *) nc->iface->data; /* Walk the queue and null-out further signals for this conn. */ for (int i = 0; i < MG_SIG_QUEUE_LEN; i++) { if (md->sig_queue[i].nc == nc) { md->sig_queue[i].sig = MG_SIG_TOMBSTONE; } } } time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms) { struct mg_mgr *mgr = iface->mgr; int n = 0; double now = mg_time(); struct mg_connection *nc, *tmp; double min_timer = 0; int num_timers = 0; #if 0 DBG(("begin poll @%u", (unsigned int) (now * 1000))); #endif mg_ev_mgr_lwip_process_signals(mgr); for (nc = mgr->active_connections; nc != NULL; nc = tmp) { struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; tmp = nc->next; n++; if (!mg_if_poll(nc, now)) continue; if (nc->sock != INVALID_SOCKET && !(nc->flags & (MG_F_UDP | MG_F_LISTENING)) && cs->pcb.tcp != NULL && cs->pcb.tcp->unsent != NULL) { mg_lwip_netif_run_on_tcpip(tcp_output_tcpip, cs->pcb.tcp); } if (nc->ev_timer_time > 0) { if (num_timers == 0 || nc->ev_timer_time < min_timer) { min_timer = nc->ev_timer_time; } num_timers++; } if (nc->sock != INVALID_SOCKET) { if (mg_lwip_if_can_send(nc, cs)) { mg_if_can_send_cb(nc); mbuf_trim(&nc->send_mbuf); } if (cs->rx_chain != NULL) { mg_if_can_recv_cb(nc); } else if (cs->draining_rx_chain) { /* * If the connection is about to close, and rx_chain is finally empty, * send the MG_SIG_CLOSE_CONN signal */ mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc); } } } #if 0 DBG(("end poll @%u, %d conns, %d timers (min %u), next in %d ms", (unsigned int) (now * 1000), n, num_timers, (unsigned int) (min_timer * 1000), timeout_ms)); #endif (void) timeout_ms; return now; } #endif /* MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/wince/wince_libc.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef WINCE const char *strerror(int err) { /* * TODO(alashkin): there is no strerror on WinCE; * look for similar wce_xxxx function */ static char buf[10]; snprintf(buf, sizeof(buf), "%d", err); return buf; } int open(const char *filename, int oflag, int pmode) { /* * TODO(alashkin): mg_open function is not used in mongoose * but exists in documentation as utility function * Shall we delete it at all or implement for WinCE as well? */ DebugBreak(); return 0; /* for compiler */ } int _wstati64(const wchar_t *path, cs_stat_t *st) { DWORD fa = GetFileAttributesW(path); if (fa == INVALID_FILE_ATTRIBUTES) { return -1; } memset(st, 0, sizeof(*st)); if ((fa & FILE_ATTRIBUTE_DIRECTORY) == 0) { HANDLE h; FILETIME ftime; st->st_mode |= _S_IFREG; h = CreateFileW(path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (h == INVALID_HANDLE_VALUE) { return -1; } st->st_size = GetFileSize(h, NULL); GetFileTime(h, NULL, NULL, &ftime); st->st_mtime = (uint32_t)((((uint64_t) ftime.dwLowDateTime + ((uint64_t) ftime.dwHighDateTime << 32)) / 10000000.0) - 11644473600); CloseHandle(h); } else { st->st_mode |= _S_IFDIR; } return 0; } /* Windows CE doesn't have neither gmtime nor strftime */ static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) { FILETIME ft; SYSTEMTIME systime; if (t != NULL) { uint64_t filetime = (*t + 11644473600) * 10000000; ft.dwLowDateTime = filetime & 0xFFFFFFFF; ft.dwHighDateTime = (filetime & 0xFFFFFFFF00000000) >> 32; FileTimeToSystemTime(&ft, &systime); } else { GetSystemTime(&systime); } /* There is no PRIu16 in WinCE SDK */ snprintf(buf, buf_len, "%d.%d.%d %d:%d:%d GMT", (int) systime.wYear, (int) systime.wMonth, (int) systime.wDay, (int) systime.wHour, (int) systime.wMinute, (int) systime.wSecond); } #endif #ifdef MG_MODULE_LINES #line 1 "common/platforms/pic32/pic32_net_if.h" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CS_COMMON_PLATFORMS_PIC32_NET_IF_H_ #define CS_COMMON_PLATFORMS_PIC32_NET_IF_H_ /* Amalgamated: #include "mongoose/src/net_if.h" */ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #ifndef MG_ENABLE_NET_IF_PIC32 #define MG_ENABLE_NET_IF_PIC32 MG_NET_IF == MG_NET_IF_PIC32 #endif extern const struct mg_iface_vtable mg_pic32_iface_vtable; #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* CS_COMMON_PLATFORMS_PIC32_NET_IF_H_ */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/pic32/pic32_net_if.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if MG_ENABLE_NET_IF_PIC32 int mg_pic32_if_create_conn(struct mg_connection *nc) { (void) nc; return 1; } void mg_pic32_if_recved(struct mg_connection *nc, size_t len) { (void) nc; (void) len; } void mg_pic32_if_add_conn(struct mg_connection *nc) { (void) nc; } void mg_pic32_if_init(struct mg_iface *iface) { (void) iface; (void) mg_get_errno(); /* Shutup compiler */ } void mg_pic32_if_free(struct mg_iface *iface) { (void) iface; } void mg_pic32_if_remove_conn(struct mg_connection *nc) { (void) nc; } void mg_pic32_if_destroy_conn(struct mg_connection *nc) { if (nc->sock == INVALID_SOCKET) return; /* For UDP, only close outgoing sockets or listeners. */ if (!(nc->flags & MG_F_UDP)) { /* Close TCP */ TCPIP_TCP_Close((TCP_SOCKET) nc->sock); } else if (nc->listener == NULL) { /* Only close outgoing UDP or listeners. */ TCPIP_UDP_Close((UDP_SOCKET) nc->sock); } nc->sock = INVALID_SOCKET; } int mg_pic32_if_listen_udp(struct mg_connection *nc, union socket_address *sa) { nc->sock = TCPIP_UDP_ServerOpen( sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4 : IP_ADDRESS_TYPE_IPV6, ntohs(sa->sin.sin_port), sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin); if (nc->sock == INVALID_SOCKET) { return -1; } return 0; } void mg_pic32_if_udp_send(struct mg_connection *nc, const void *buf, size_t len) { mbuf_append(&nc->send_mbuf, buf, len); } void mg_pic32_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) { mbuf_append(&nc->send_mbuf, buf, len); } int mg_pic32_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) { nc->sock = TCPIP_TCP_ServerOpen( sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4 : IP_ADDRESS_TYPE_IPV6, ntohs(sa->sin.sin_port), sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin); memcpy(&nc->sa, sa, sizeof(*sa)); if (nc->sock == INVALID_SOCKET) { return -1; } return 0; } static int mg_accept_conn(struct mg_connection *lc) { struct mg_connection *nc; TCP_SOCKET_INFO si; union socket_address sa; nc = mg_if_accept_new_conn(lc); if (nc == NULL) { return 0; } nc->sock = lc->sock; nc->flags &= ~MG_F_LISTENING; if (!TCPIP_TCP_SocketInfoGet((TCP_SOCKET) nc->sock, &si)) { return 0; } if (si.addressType == IP_ADDRESS_TYPE_IPV4) { sa.sin.sin_family = AF_INET; sa.sin.sin_port = htons(si.remotePort); sa.sin.sin_addr.s_addr = si.remoteIPaddress.v4Add.Val; } else { /* TODO(alashkin): do something with _potential_ IPv6 */ memset(&sa, 0, sizeof(sa)); } mg_if_accept_tcp_cb(nc, (union socket_address *) &sa, sizeof(sa)); return mg_pic32_if_listen_tcp(lc, &lc->sa) >= 0; } char *inet_ntoa(struct in_addr in) { static char addr[17]; snprintf(addr, sizeof(addr), "%d.%d.%d.%d", (int) in.S_un.S_un_b.s_b1, (int) in.S_un.S_un_b.s_b2, (int) in.S_un.S_un_b.s_b3, (int) in.S_un.S_un_b.s_b4); return addr; } static void mg_handle_send(struct mg_connection *nc) { uint16_t bytes_written = 0; if (nc->flags & MG_F_UDP) { if (!TCPIP_UDP_RemoteBind( (UDP_SOCKET) nc->sock, nc->sa.sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4 : IP_ADDRESS_TYPE_IPV6, ntohs(nc->sa.sin.sin_port), (IP_MULTI_ADDRESS *) &nc->sa.sin)) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; return; } bytes_written = TCPIP_UDP_TxPutIsReady((UDP_SOCKET) nc->sock, 0); if (bytes_written >= nc->send_mbuf.len) { if (TCPIP_UDP_ArrayPut((UDP_SOCKET) nc->sock, (uint8_t *) nc->send_mbuf.buf, nc->send_mbuf.len) != nc->send_mbuf.len) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; bytes_written = 0; } } } else { bytes_written = TCPIP_TCP_FifoTxFreeGet((TCP_SOCKET) nc->sock); if (bytes_written != 0) { if (bytes_written > nc->send_mbuf.len) { bytes_written = nc->send_mbuf.len; } if (TCPIP_TCP_ArrayPut((TCP_SOCKET) nc->sock, (uint8_t *) nc->send_mbuf.buf, bytes_written) != bytes_written) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; bytes_written = 0; } } } mg_if_sent_cb(nc, bytes_written); } static void mg_handle_recv(struct mg_connection *nc) { uint16_t bytes_read = 0; uint8_t *buf = NULL; if (nc->flags & MG_F_UDP) { bytes_read = TCPIP_UDP_GetIsReady((UDP_SOCKET) nc->sock); if (bytes_read != 0 && (nc->recv_mbuf_limit == -1 || nc->recv_mbuf.len + bytes_read < nc->recv_mbuf_limit)) { buf = (uint8_t *) MG_MALLOC(bytes_read); if (TCPIP_UDP_ArrayGet((UDP_SOCKET) nc->sock, buf, bytes_read) != bytes_read) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; bytes_read = 0; MG_FREE(buf); } } } else { bytes_read = TCPIP_TCP_GetIsReady((TCP_SOCKET) nc->sock); if (bytes_read != 0) { if (nc->recv_mbuf_limit != -1 && nc->recv_mbuf_limit - nc->recv_mbuf.len > bytes_read) { bytes_read = nc->recv_mbuf_limit - nc->recv_mbuf.len; } buf = (uint8_t *) MG_MALLOC(bytes_read); if (TCPIP_TCP_ArrayGet((TCP_SOCKET) nc->sock, buf, bytes_read) != bytes_read) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; MG_FREE(buf); bytes_read = 0; } } } if (bytes_read != 0) { mg_if_recv_tcp_cb(nc, buf, bytes_read, 1 /* own */); } } time_t mg_pic32_if_poll(struct mg_iface *iface, int timeout_ms) { struct mg_mgr *mgr = iface->mgr; double now = mg_time(); struct mg_connection *nc, *tmp; for (nc = mgr->active_connections; nc != NULL; nc = tmp) { tmp = nc->next; if (nc->flags & MG_F_CONNECTING) { /* processing connections */ if (nc->flags & MG_F_UDP || TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) { mg_if_connect_cb(nc, 0); } } else if (nc->flags & MG_F_LISTENING) { if (TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) { /* accept new connections */ mg_accept_conn(nc); } } else { if (nc->send_mbuf.len != 0) { mg_handle_send(nc); } if (nc->recv_mbuf_limit == -1 || nc->recv_mbuf.len < nc->recv_mbuf_limit) { mg_handle_recv(nc); } } } for (nc = mgr->active_connections; nc != NULL; nc = tmp) { tmp = nc->next; if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) || (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) { mg_close_conn(nc); } } return now; } void mg_pic32_if_sock_set(struct mg_connection *nc, sock_t sock) { nc->sock = sock; } void mg_pic32_if_get_conn_addr(struct mg_connection *nc, int remote, union socket_address *sa) { /* TODO(alaskin): not implemented yet */ } void mg_pic32_if_connect_tcp(struct mg_connection *nc, const union socket_address *sa) { nc->sock = TCPIP_TCP_ClientOpen( sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4 : IP_ADDRESS_TYPE_IPV6, ntohs(sa->sin.sin_port), (IP_MULTI_ADDRESS *) &sa->sin); nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0; } void mg_pic32_if_connect_udp(struct mg_connection *nc) { nc->sock = TCPIP_UDP_ClientOpen(IP_ADDRESS_TYPE_ANY, 0, NULL); nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0; } /* clang-format off */ #define MG_PIC32_IFACE_VTABLE \ { \ mg_pic32_if_init, \ mg_pic32_if_free, \ mg_pic32_if_add_conn, \ mg_pic32_if_remove_conn, \ mg_pic32_if_poll, \ mg_pic32_if_listen_tcp, \ mg_pic32_if_listen_udp, \ mg_pic32_if_connect_tcp, \ mg_pic32_if_connect_udp, \ mg_pic32_if_tcp_send, \ mg_pic32_if_udp_send, \ mg_pic32_if_recved, \ mg_pic32_if_create_conn, \ mg_pic32_if_destroy_conn, \ mg_pic32_if_sock_set, \ mg_pic32_if_get_conn_addr, \ } /* clang-format on */ const struct mg_iface_vtable mg_pic32_iface_vtable = MG_PIC32_IFACE_VTABLE; #if MG_NET_IF == MG_NET_IF_PIC32 const struct mg_iface_vtable mg_default_iface_vtable = MG_PIC32_IFACE_VTABLE; #endif #endif /* MG_ENABLE_NET_IF_PIC32 */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/windows/windows_direct.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef _WIN32 int rmdir(const char *dirname) { return _rmdir(dirname); } unsigned int sleep(unsigned int seconds) { Sleep(seconds * 1000); return 0; } #endif /* _WIN32 */
null
#include "mongoose.h" #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_internal.h" #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ #ifndef CS_MONGOOSE_SRC_INTERNAL_H_ #define CS_MONGOOSE_SRC_INTERNAL_H_ /* Amalgamated: #include "common/mg_mem.h" */ #ifndef MBUF_REALLOC #define MBUF_REALLOC MG_REALLOC #endif #ifndef MBUF_FREE #define MBUF_FREE MG_FREE #endif #define MG_SET_PTRPTR(_ptr, _v) \ do { \ if (_ptr) *(_ptr) = _v; \ } while (0) #ifndef MG_INTERNAL #define MG_INTERNAL static #endif #ifdef PICOTCP #define NO_LIBC #define MG_DISABLE_PFS #endif /* Amalgamated: #include "common/cs_dbg.h" */ /* Amalgamated: #include "mg_http.h" */ /* Amalgamated: #include "mg_net.h" */ #ifndef MG_CTL_MSG_MESSAGE_SIZE #define MG_CTL_MSG_MESSAGE_SIZE 8192 #endif /* internals that need to be accessible in unit tests */ MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc, int proto, union socket_address *sa); MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa, int *proto, char *host, size_t host_len); MG_INTERNAL void mg_call(struct mg_connection *nc, mg_event_handler_t ev_handler, void *user_data, int ev, void *ev_data); void mg_forward(struct mg_connection *from, struct mg_connection *to); MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c); MG_INTERNAL void mg_remove_conn(struct mg_connection *c); MG_INTERNAL struct mg_connection *mg_create_connection( struct mg_mgr *mgr, mg_event_handler_t callback, struct mg_add_sock_opts opts); #ifdef _WIN32 /* Retur value is the same as for MultiByteToWideChar. */ int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len); #endif struct ctl_msg { mg_event_handler_t callback; char message[MG_CTL_MSG_MESSAGE_SIZE]; }; #if MG_ENABLE_MQTT struct mg_mqtt_message; #define MG_MQTT_ERROR_INCOMPLETE_MSG -1 #define MG_MQTT_ERROR_MALFORMED_MSG -2 MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm); #endif /* Forward declarations for testing. */ extern void *(*test_malloc)(size_t size); extern void *(*test_calloc)(size_t count, size_t size); #ifndef MIN #define MIN(a, b) ((a) < (b) ? (a) : (b)) #endif #if MG_ENABLE_HTTP struct mg_serve_http_opts; MG_INTERNAL struct mg_http_proto_data *mg_http_create_proto_data( struct mg_connection *c); /* * Reassemble the content of the buffer (buf, blen) which should be * in the HTTP chunked encoding, by collapsing data chunks to the * beginning of the buffer. * * If chunks get reassembled, modify hm->body to point to the reassembled * body and fire MG_EV_HTTP_CHUNK event. If handler sets MG_F_DELETE_CHUNK * in nc->flags, delete reassembled body from the mbuf. * * Return reassembled body size. */ MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc, struct http_message *hm, char *buf, size_t blen); #if MG_ENABLE_FILESYSTEM MG_INTERNAL int mg_uri_to_local_path(struct http_message *hm, const struct mg_serve_http_opts *opts, char **local_path, struct mg_str *remainder); MG_INTERNAL time_t mg_parse_date_string(const char *datetime); MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st); #endif #if MG_ENABLE_HTTP_CGI MG_INTERNAL void mg_handle_cgi(struct mg_connection *nc, const char *prog, const struct mg_str *path_info, const struct http_message *hm, const struct mg_serve_http_opts *opts); struct mg_http_proto_data_cgi; MG_INTERNAL void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d); #endif #if MG_ENABLE_HTTP_SSI MG_INTERNAL void mg_handle_ssi_request(struct mg_connection *nc, struct http_message *hm, const char *path, const struct mg_serve_http_opts *opts); #endif #if MG_ENABLE_HTTP_WEBDAV MG_INTERNAL int mg_is_dav_request(const struct mg_str *s); MG_INTERNAL void mg_handle_propfind(struct mg_connection *nc, const char *path, cs_stat_t *stp, struct http_message *hm, struct mg_serve_http_opts *opts); MG_INTERNAL void mg_handle_lock(struct mg_connection *nc, const char *path); MG_INTERNAL void mg_handle_mkcol(struct mg_connection *nc, const char *path, struct http_message *hm); MG_INTERNAL void mg_handle_move(struct mg_connection *c, const struct mg_serve_http_opts *opts, const char *path, struct http_message *hm); MG_INTERNAL void mg_handle_delete(struct mg_connection *nc, const struct mg_serve_http_opts *opts, const char *path); MG_INTERNAL void mg_handle_put(struct mg_connection *nc, const char *path, struct http_message *hm); #endif #if MG_ENABLE_HTTP_WEBSOCKET MG_INTERNAL void mg_ws_handler(struct mg_connection *nc, int ev, void *ev_data MG_UD_ARG(void *user_data)); MG_INTERNAL void mg_ws_handshake(struct mg_connection *nc, const struct mg_str *key, struct http_message *); #endif #endif /* MG_ENABLE_HTTP */ MG_INTERNAL int mg_get_errno(void); MG_INTERNAL void mg_close_conn(struct mg_connection *conn); #if MG_ENABLE_SNTP MG_INTERNAL int mg_sntp_parse_reply(const char *buf, int len, struct mg_sntp_message *msg); #endif #endif /* CS_MONGOOSE_SRC_INTERNAL_H_ */ #ifdef MG_MODULE_LINES #line 1 "common/mg_mem.h" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CS_COMMON_MG_MEM_H_ #define CS_COMMON_MG_MEM_H_ #ifdef __cplusplus extern "C" { #endif #ifndef MG_MALLOC #define MG_MALLOC malloc #endif #ifndef MG_CALLOC #define MG_CALLOC calloc #endif #ifndef MG_REALLOC #define MG_REALLOC realloc #endif #ifndef MG_FREE #define MG_FREE free #endif #ifdef __cplusplus } #endif #endif /* CS_COMMON_MG_MEM_H_ */ #ifdef MG_MODULE_LINES #line 1 "common/cs_base64.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef EXCLUDE_COMMON /* Amalgamated: #include "common/cs_base64.h" */ #include <string.h> /* Amalgamated: #include "common/cs_dbg.h" */ /* ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ */ #define NUM_UPPERCASES ('Z' - 'A' + 1) #define NUM_LETTERS (NUM_UPPERCASES * 2) #define NUM_DIGITS ('9' - '0' + 1) /* * Emit a base64 code char. * * Doesn't use memory, thus it's safe to use to safely dump memory in crashdumps */ static void cs_base64_emit_code(struct cs_base64_ctx *ctx, int v) { if (v < NUM_UPPERCASES) { ctx->b64_putc(v + 'A', ctx->user_data); } else if (v < (NUM_LETTERS)) { ctx->b64_putc(v - NUM_UPPERCASES + 'a', ctx->user_data); } else if (v < (NUM_LETTERS + NUM_DIGITS)) { ctx->b64_putc(v - NUM_LETTERS + '0', ctx->user_data); } else { ctx->b64_putc(v - NUM_LETTERS - NUM_DIGITS == 0 ? '+' : '/', ctx->user_data); } } static void cs_base64_emit_chunk(struct cs_base64_ctx *ctx) { int a, b, c; a = ctx->chunk[0]; b = ctx->chunk[1]; c = ctx->chunk[2]; cs_base64_emit_code(ctx, a >> 2); cs_base64_emit_code(ctx, ((a & 3) << 4) | (b >> 4)); if (ctx->chunk_size > 1) { cs_base64_emit_code(ctx, (b & 15) << 2 | (c >> 6)); } if (ctx->chunk_size > 2) { cs_base64_emit_code(ctx, c & 63); } } void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t b64_putc, void *user_data) { ctx->chunk_size = 0; ctx->b64_putc = b64_putc; ctx->user_data = user_data; } void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len) { const unsigned char *src = (const unsigned char *) str; size_t i; for (i = 0; i < len; i++) { ctx->chunk[ctx->chunk_size++] = src[i]; if (ctx->chunk_size == 3) { cs_base64_emit_chunk(ctx); ctx->chunk_size = 0; } } } void cs_base64_finish(struct cs_base64_ctx *ctx) { if (ctx->chunk_size > 0) { int i; memset(&ctx->chunk[ctx->chunk_size], 0, 3 - ctx->chunk_size); cs_base64_emit_chunk(ctx); for (i = 0; i < (3 - ctx->chunk_size); i++) { ctx->b64_putc('=', ctx->user_data); } } } #define BASE64_ENCODE_BODY \ static const char *b64 = \ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; \ int i, j, a, b, c; \ \ for (i = j = 0; i < src_len; i += 3) { \ a = src[i]; \ b = i + 1 >= src_len ? 0 : src[i + 1]; \ c = i + 2 >= src_len ? 0 : src[i + 2]; \ \ BASE64_OUT(b64[a >> 2]); \ BASE64_OUT(b64[((a & 3) << 4) | (b >> 4)]); \ if (i + 1 < src_len) { \ BASE64_OUT(b64[(b & 15) << 2 | (c >> 6)]); \ } \ if (i + 2 < src_len) { \ BASE64_OUT(b64[c & 63]); \ } \ } \ \ while (j % 4 != 0) { \ BASE64_OUT('='); \ } \ BASE64_FLUSH() #define BASE64_OUT(ch) \ do { \ dst[j++] = (ch); \ } while (0) #define BASE64_FLUSH() \ do { \ dst[j++] = '\0'; \ } while (0) void cs_base64_encode(const unsigned char *src, int src_len, char *dst) { BASE64_ENCODE_BODY; } #undef BASE64_OUT #undef BASE64_FLUSH #if CS_ENABLE_STDIO #define BASE64_OUT(ch) \ do { \ fprintf(f, "%c", (ch)); \ j++; \ } while (0) #define BASE64_FLUSH() void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len) { BASE64_ENCODE_BODY; } #undef BASE64_OUT #undef BASE64_FLUSH #endif /* CS_ENABLE_STDIO */ /* Convert one byte of encoded base64 input stream to 6-bit chunk */ static unsigned char from_b64(unsigned char ch) { /* Inverse lookup map */ static const unsigned char tab[128] = { 255, 255, 255, 255, 255, 255, 255, 255, /* 0 */ 255, 255, 255, 255, 255, 255, 255, 255, /* 8 */ 255, 255, 255, 255, 255, 255, 255, 255, /* 16 */ 255, 255, 255, 255, 255, 255, 255, 255, /* 24 */ 255, 255, 255, 255, 255, 255, 255, 255, /* 32 */ 255, 255, 255, 62, 255, 255, 255, 63, /* 40 */ 52, 53, 54, 55, 56, 57, 58, 59, /* 48 */ 60, 61, 255, 255, 255, 200, 255, 255, /* 56 '=' is 200, on index 61 */ 255, 0, 1, 2, 3, 4, 5, 6, /* 64 */ 7, 8, 9, 10, 11, 12, 13, 14, /* 72 */ 15, 16, 17, 18, 19, 20, 21, 22, /* 80 */ 23, 24, 25, 255, 255, 255, 255, 255, /* 88 */ 255, 26, 27, 28, 29, 30, 31, 32, /* 96 */ 33, 34, 35, 36, 37, 38, 39, 40, /* 104 */ 41, 42, 43, 44, 45, 46, 47, 48, /* 112 */ 49, 50, 51, 255, 255, 255, 255, 255, /* 120 */ }; return tab[ch & 127]; } int cs_base64_decode(const unsigned char *s, int len, char *dst, int *dec_len) { unsigned char a, b, c, d; int orig_len = len; char *orig_dst = dst; while (len >= 4 && (a = from_b64(s[0])) != 255 && (b = from_b64(s[1])) != 255 && (c = from_b64(s[2])) != 255 && (d = from_b64(s[3])) != 255) { s += 4; len -= 4; if (a == 200 || b == 200) break; /* '=' can't be there */ *dst++ = a << 2 | b >> 4; if (c == 200) break; *dst++ = b << 4 | c >> 2; if (d == 200) break; *dst++ = c << 6 | d; } *dst = 0; if (dec_len != NULL) *dec_len = (dst - orig_dst); return orig_len - len; } #endif /* EXCLUDE_COMMON */ #ifdef MG_MODULE_LINES #line 1 "common/cs_dbg.h" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CS_COMMON_CS_DBG_H_ #define CS_COMMON_CS_DBG_H_ /* Amalgamated: #include "common/platform.h" */ #if CS_ENABLE_STDIO #include <stdio.h> #endif #ifndef CS_ENABLE_DEBUG #define CS_ENABLE_DEBUG 0 #endif #ifndef CS_LOG_PREFIX_LEN #define CS_LOG_PREFIX_LEN 24 #endif #ifndef CS_LOG_ENABLE_TS_DIFF #define CS_LOG_ENABLE_TS_DIFF 0 #endif #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* * Log level; `LL_INFO` is the default. Use `cs_log_set_level()` to change it. */ enum cs_log_level { LL_NONE = -1, LL_ERROR = 0, LL_WARN = 1, LL_INFO = 2, LL_DEBUG = 3, LL_VERBOSE_DEBUG = 4, _LL_MIN = -2, _LL_MAX = 5, }; /* * Set max log level to print; messages with the level above the given one will * not be printed. */ void cs_log_set_level(enum cs_log_level level); /* * A comma-separated set of prefix=level. * prefix is matched against the log prefix exactly as printed, including line * number, but partial match is ok. Check stops on first matching entry. * If nothing matches, default level is used. * * Examples: * main.c:=4 - everything from main C at verbose debug level. * mongoose.c=1,mjs.c=1,=4 - everything at verbose debug except mg_* and mjs_* * */ void cs_log_set_file_level(const char *file_level); /* * Helper function which prints message prefix with the given `level`. * If message should be printed (according to the current log level * and filter), prints the prefix and returns 1, otherwise returns 0. * * Clients should typically just use `LOG()` macro. */ int cs_log_print_prefix(enum cs_log_level level, const char *fname, int line); extern enum cs_log_level cs_log_level; #if CS_ENABLE_STDIO /* * Set file to write logs into. If `NULL`, logs go to `stderr`. */ void cs_log_set_file(FILE *file); /* * Prints log to the current log file, appends "\n" in the end and flushes the * stream. */ void cs_log_printf(const char *fmt, ...) PRINTF_LIKE(1, 2); #if CS_ENABLE_STDIO /* * Format and print message `x` with the given level `l`. Example: * * ```c * LOG(LL_INFO, ("my info message: %d", 123)); * LOG(LL_DEBUG, ("my debug message: %d", 123)); * ``` */ #define LOG(l, x) \ do { \ if (cs_log_print_prefix(l, __FILE__, __LINE__)) { \ cs_log_printf x; \ } \ } while (0) #else #define LOG(l, x) ((void) l) #endif #ifndef CS_NDEBUG /* * Shortcut for `LOG(LL_VERBOSE_DEBUG, (...))` */ #define DBG(x) LOG(LL_VERBOSE_DEBUG, x) #else /* NDEBUG */ #define DBG(x) #endif #else /* CS_ENABLE_STDIO */ #define LOG(l, x) #define DBG(x) #endif #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* CS_COMMON_CS_DBG_H_ */ #ifdef MG_MODULE_LINES #line 1 "common/cs_dbg.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Amalgamated: #include "common/cs_dbg.h" */ #include <stdarg.h> #include <stdio.h> #include <string.h> /* Amalgamated: #include "common/cs_time.h" */ /* Amalgamated: #include "common/str_util.h" */ enum cs_log_level cs_log_level WEAK = #if CS_ENABLE_DEBUG LL_VERBOSE_DEBUG; #else LL_ERROR; #endif #if CS_ENABLE_STDIO static char *s_file_level = NULL; void cs_log_set_file_level(const char *file_level) WEAK; FILE *cs_log_file WEAK = NULL; #if CS_LOG_ENABLE_TS_DIFF double cs_log_ts WEAK; #endif enum cs_log_level cs_log_cur_msg_level WEAK = LL_NONE; void cs_log_set_file_level(const char *file_level) { char *fl = s_file_level; if (file_level != NULL) { s_file_level = strdup(file_level); } else { s_file_level = NULL; } free(fl); } int cs_log_print_prefix(enum cs_log_level level, const char *file, int ln) WEAK; int cs_log_print_prefix(enum cs_log_level level, const char *file, int ln) { char prefix[CS_LOG_PREFIX_LEN], *q; const char *p; size_t fl = 0, ll = 0, pl = 0; if (level > cs_log_level && s_file_level == NULL) return 0; p = file + strlen(file); while (p != file) { const char c = *(p - 1); if (c == '/' || c == '\\') break; p--; fl++; } ll = (ln < 10000 ? (ln < 1000 ? (ln < 100 ? (ln < 10 ? 1 : 2) : 3) : 4) : 5); if (fl > (sizeof(prefix) - ll - 2)) fl = (sizeof(prefix) - ll - 2); pl = fl + 1 + ll; memcpy(prefix, p, fl); q = prefix + pl; memset(q, ' ', sizeof(prefix) - pl); do { *(--q) = '0' + (ln % 10); ln /= 10; } while (ln > 0); *(--q) = ':'; if (s_file_level != NULL) { enum cs_log_level pll = cs_log_level; struct mg_str fl = mg_mk_str(s_file_level), ps = MG_MK_STR_N(prefix, pl); struct mg_str k, v; while ((fl = mg_next_comma_list_entry_n(fl, &k, &v)).p != NULL) { bool yes = !(!mg_str_starts_with(ps, k) || v.len == 0); if (!yes) continue; pll = (enum cs_log_level)(*v.p - '0'); break; } if (level > pll) return 0; } if (cs_log_file == NULL) cs_log_file = stderr; cs_log_cur_msg_level = level; fwrite(prefix, 1, sizeof(prefix), cs_log_file); #if CS_LOG_ENABLE_TS_DIFF { double now = cs_time(); fprintf(cs_log_file, "%7u ", (unsigned int) ((now - cs_log_ts) * 1000000)); cs_log_ts = now; } #endif return 1; } void cs_log_printf(const char *fmt, ...) WEAK; void cs_log_printf(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vfprintf(cs_log_file, fmt, ap); va_end(ap); fputc('\n', cs_log_file); fflush(cs_log_file); cs_log_cur_msg_level = LL_NONE; } void cs_log_set_file(FILE *file) WEAK; void cs_log_set_file(FILE *file) { cs_log_file = file; } #else void cs_log_set_file_level(const char *file_level) { (void) file_level; } #endif /* CS_ENABLE_STDIO */ void cs_log_set_level(enum cs_log_level level) WEAK; void cs_log_set_level(enum cs_log_level level) { cs_log_level = level; #if CS_LOG_ENABLE_TS_DIFF && CS_ENABLE_STDIO cs_log_ts = cs_time(); #endif } #ifdef MG_MODULE_LINES #line 1 "common/cs_dirent.h" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CS_COMMON_CS_DIRENT_H_ #define CS_COMMON_CS_DIRENT_H_ #include <limits.h> /* Amalgamated: #include "common/platform.h" */ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #ifdef CS_DEFINE_DIRENT typedef struct { int dummy; } DIR; struct dirent { int d_ino; #ifdef _WIN32 char d_name[MAX_PATH]; #else /* TODO(rojer): Use PATH_MAX but make sure it's sane on every platform */ char d_name[256]; #endif }; DIR *opendir(const char *dir_name); int closedir(DIR *dir); struct dirent *readdir(DIR *dir); #endif /* CS_DEFINE_DIRENT */ #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* CS_COMMON_CS_DIRENT_H_ */ #ifdef MG_MODULE_LINES #line 1 "common/cs_dirent.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef EXCLUDE_COMMON /* Amalgamated: #include "common/mg_mem.h" */ /* Amalgamated: #include "common/cs_dirent.h" */ /* * This file contains POSIX opendir/closedir/readdir API implementation * for systems which do not natively support it (e.g. Windows). */ #ifdef _WIN32 struct win32_dir { DIR d; HANDLE handle; WIN32_FIND_DATAW info; struct dirent result; }; DIR *opendir(const char *name) { struct win32_dir *dir = NULL; wchar_t wpath[MAX_PATH]; DWORD attrs; if (name == NULL) { SetLastError(ERROR_BAD_ARGUMENTS); } else if ((dir = (struct win32_dir *) MG_MALLOC(sizeof(*dir))) == NULL) { SetLastError(ERROR_NOT_ENOUGH_MEMORY); } else { to_wchar(name, wpath, ARRAY_SIZE(wpath)); attrs = GetFileAttributesW(wpath); if (attrs != 0xFFFFFFFF && (attrs & FILE_ATTRIBUTE_DIRECTORY)) { (void) wcscat(wpath, L"\\*"); dir->handle = FindFirstFileW(wpath, &dir->info); dir->result.d_name[0] = '\0'; } else { MG_FREE(dir); dir = NULL; } } return (DIR *) dir; } int closedir(DIR *d) { struct win32_dir *dir = (struct win32_dir *) d; int result = 0; if (dir != NULL) { if (dir->handle != INVALID_HANDLE_VALUE) result = FindClose(dir->handle) ? 0 : -1; MG_FREE(dir); } else { result = -1; SetLastError(ERROR_BAD_ARGUMENTS); } return result; } struct dirent *readdir(DIR *d) { struct win32_dir *dir = (struct win32_dir *) d; struct dirent *result = NULL; if (dir) { memset(&dir->result, 0, sizeof(dir->result)); if (dir->handle != INVALID_HANDLE_VALUE) { result = &dir->result; (void) WideCharToMultiByte(CP_UTF8, 0, dir->info.cFileName, -1, result->d_name, sizeof(result->d_name), NULL, NULL); if (!FindNextFileW(dir->handle, &dir->info)) { (void) FindClose(dir->handle); dir->handle = INVALID_HANDLE_VALUE; } } else { SetLastError(ERROR_FILE_NOT_FOUND); } } else { SetLastError(ERROR_BAD_ARGUMENTS); } return result; } #endif #endif /* EXCLUDE_COMMON */ /* ISO C requires a translation unit to contain at least one declaration */ typedef int cs_dirent_dummy; #ifdef MG_MODULE_LINES #line 1 "common/cs_time.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Amalgamated: #include "common/cs_time.h" */ #ifndef _WIN32 #include <stddef.h> /* * There is no sys/time.h on ARMCC. */ #if !(defined(__ARMCC_VERSION) || defined(__ICCARM__)) && \ !defined(__TI_COMPILER_VERSION__) && \ (!defined(CS_PLATFORM) || CS_PLATFORM != CS_P_NXP_LPC) #include <sys/time.h> #endif #else #include <windows.h> #endif double cs_time(void) WEAK; double cs_time(void) { double now; #ifndef _WIN32 struct timeval tv; if (gettimeofday(&tv, NULL /* tz */) != 0) return 0; now = (double) tv.tv_sec + (((double) tv.tv_usec) / 1000000.0); #else SYSTEMTIME sysnow; FILETIME ftime; GetLocalTime(&sysnow); SystemTimeToFileTime(&sysnow, &ftime); /* * 1. VC 6.0 doesn't support conversion uint64 -> double, so, using int64 * This should not cause a problems in this (21th) century * 2. Windows FILETIME is a number of 100-nanosecond intervals since January * 1, 1601 while time_t is a number of _seconds_ since January 1, 1970 UTC, * thus, we need to convert to seconds and adjust amount (subtract 11644473600 * seconds) */ now = (double) (((int64_t) ftime.dwLowDateTime + ((int64_t) ftime.dwHighDateTime << 32)) / 10000000.0) - 11644473600; #endif /* _WIN32 */ return now; } double cs_timegm(const struct tm *tm) { /* Month-to-day offset for non-leap-years. */ static const int month_day[12] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334}; /* Most of the calculation is easy; leap years are the main difficulty. */ int month = tm->tm_mon % 12; int year = tm->tm_year + tm->tm_mon / 12; int year_for_leap; int64_t rt; if (month < 0) { /* Negative values % 12 are still negative. */ month += 12; --year; } /* This is the number of Februaries since 1900. */ year_for_leap = (month > 1) ? year + 1 : year; rt = tm->tm_sec /* Seconds */ + 60 * (tm->tm_min /* Minute = 60 seconds */ + 60 * (tm->tm_hour /* Hour = 60 minutes */ + 24 * (month_day[month] + tm->tm_mday - 1 /* Day = 24 hours */ + 365 * (year - 70) /* Year = 365 days */ + (year_for_leap - 69) / 4 /* Every 4 years is leap... */ - (year_for_leap - 1) / 100 /* Except centuries... */ + (year_for_leap + 299) / 400))); /* Except 400s. */ return rt < 0 ? -1 : (double) rt; } #ifdef MG_MODULE_LINES #line 1 "common/cs_endian.h" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CS_COMMON_CS_ENDIAN_H_ #define CS_COMMON_CS_ENDIAN_H_ #ifdef __cplusplus extern "C" { #endif /* * clang with std=-c99 uses __LITTLE_ENDIAN, by default * while for ex, RTOS gcc - LITTLE_ENDIAN, by default * it depends on __USE_BSD, but let's have everything */ #if !defined(BYTE_ORDER) && defined(__BYTE_ORDER) #define BYTE_ORDER __BYTE_ORDER #ifndef LITTLE_ENDIAN #define LITTLE_ENDIAN __LITTLE_ENDIAN #endif /* LITTLE_ENDIAN */ #ifndef BIG_ENDIAN #define BIG_ENDIAN __LITTLE_ENDIAN #endif /* BIG_ENDIAN */ #endif /* BYTE_ORDER */ #ifdef __cplusplus } #endif #endif /* CS_COMMON_CS_ENDIAN_H_ */ #ifdef MG_MODULE_LINES #line 1 "common/cs_md5.c" #endif /* * This code implements the MD5 message-digest algorithm. * The algorithm is due to Ron Rivest. This code was * written by Colin Plumb in 1993, no copyright is claimed. * This code is in the public domain; do with it what you wish. * * Equivalent code is available from RSA Data Security, Inc. * This code has been tested against that, and is equivalent, * except that you don't need to include two pages of legalese * with every copy. * * To compute the message digest of a chunk of bytes, declare an * MD5Context structure, pass it to MD5Init, call MD5Update as * needed on buffers full of bytes, and then call MD5Final, which * will fill a supplied 16-byte array with the digest. */ /* Amalgamated: #include "common/cs_md5.h" */ /* Amalgamated: #include "common/str_util.h" */ #if !defined(EXCLUDE_COMMON) #if !CS_DISABLE_MD5 /* Amalgamated: #include "common/cs_endian.h" */ static void byteReverse(unsigned char *buf, unsigned longs) { /* Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN */ #if BYTE_ORDER == BIG_ENDIAN do { uint32_t t = (uint32_t)((unsigned) buf[3] << 8 | buf[2]) << 16 | ((unsigned) buf[1] << 8 | buf[0]); *(uint32_t *) buf = t; buf += 4; } while (--longs); #else (void) buf; (void) longs; #endif } #define F1(x, y, z) (z ^ (x & (y ^ z))) #define F2(x, y, z) F1(z, x, y) #define F3(x, y, z) (x ^ y ^ z) #define F4(x, y, z) (y ^ (x | ~z)) #define MD5STEP(f, w, x, y, z, data, s) \ (w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x) /* * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious * initialization constants. */ void cs_md5_init(cs_md5_ctx *ctx) { ctx->buf[0] = 0x67452301; ctx->buf[1] = 0xefcdab89; ctx->buf[2] = 0x98badcfe; ctx->buf[3] = 0x10325476; ctx->bits[0] = 0; ctx->bits[1] = 0; } static void cs_md5_transform(uint32_t buf[4], uint32_t const in[16]) { register uint32_t a, b, c, d; a = buf[0]; b = buf[1]; c = buf[2]; d = buf[3]; MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); buf[0] += a; buf[1] += b; buf[2] += c; buf[3] += d; } void cs_md5_update(cs_md5_ctx *ctx, const unsigned char *buf, size_t len) { uint32_t t; t = ctx->bits[0]; if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) ctx->bits[1]++; ctx->bits[1] += (uint32_t) len >> 29; t = (t >> 3) & 0x3f; if (t) { unsigned char *p = (unsigned char *) ctx->in + t; t = 64 - t; if (len < t) { memcpy(p, buf, len); return; } memcpy(p, buf, t); byteReverse(ctx->in, 16); cs_md5_transform(ctx->buf, (uint32_t *) ctx->in); buf += t; len -= t; } while (len >= 64) { memcpy(ctx->in, buf, 64); byteReverse(ctx->in, 16); cs_md5_transform(ctx->buf, (uint32_t *) ctx->in); buf += 64; len -= 64; } memcpy(ctx->in, buf, len); } void cs_md5_final(unsigned char digest[16], cs_md5_ctx *ctx) { unsigned count; unsigned char *p; uint32_t *a; count = (ctx->bits[0] >> 3) & 0x3F; p = ctx->in + count; *p++ = 0x80; count = 64 - 1 - count; if (count < 8) { memset(p, 0, count); byteReverse(ctx->in, 16); cs_md5_transform(ctx->buf, (uint32_t *) ctx->in); memset(ctx->in, 0, 56); } else { memset(p, 0, count - 8); } byteReverse(ctx->in, 14); a = (uint32_t *) ctx->in; a[14] = ctx->bits[0]; a[15] = ctx->bits[1]; cs_md5_transform(ctx->buf, (uint32_t *) ctx->in); byteReverse((unsigned char *) ctx->buf, 4); memcpy(digest, ctx->buf, 16); memset((char *) ctx, 0, sizeof(*ctx)); } #endif /* CS_DISABLE_MD5 */ #endif /* EXCLUDE_COMMON */ #ifdef MG_MODULE_LINES #line 1 "common/cs_sha1.c" #endif /* Copyright(c) By Steve Reid <steve@edmweb.com> */ /* 100% Public Domain */ /* Amalgamated: #include "common/cs_sha1.h" */ #if !CS_DISABLE_SHA1 && !defined(EXCLUDE_COMMON) /* Amalgamated: #include "common/cs_endian.h" */ #define SHA1HANDSOFF #if defined(__sun) /* Amalgamated: #include "common/solarisfixes.h" */ #endif union char64long16 { unsigned char c[64]; uint32_t l[16]; }; #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) static uint32_t blk0(union char64long16 *block, int i) { /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */ #if BYTE_ORDER == LITTLE_ENDIAN block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) | (rol(block->l[i], 8) & 0x00FF00FF); #endif return block->l[i]; } /* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */ #undef blk #undef R0 #undef R1 #undef R2 #undef R3 #undef R4 #define blk(i) \ (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \ block->l[(i + 2) & 15] ^ block->l[i & 15], \ 1)) #define R0(v, w, x, y, z, i) \ z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \ w = rol(w, 30); #define R1(v, w, x, y, z, i) \ z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \ w = rol(w, 30); #define R2(v, w, x, y, z, i) \ z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \ w = rol(w, 30); #define R3(v, w, x, y, z, i) \ z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \ w = rol(w, 30); #define R4(v, w, x, y, z, i) \ z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \ w = rol(w, 30); void cs_sha1_transform(uint32_t state[5], const unsigned char buffer[64]) { uint32_t a, b, c, d, e; union char64long16 block[1]; memcpy(block, buffer, 64); a = state[0]; b = state[1]; c = state[2]; d = state[3]; e = state[4]; R0(a, b, c, d, e, 0); R0(e, a, b, c, d, 1); R0(d, e, a, b, c, 2); R0(c, d, e, a, b, 3); R0(b, c, d, e, a, 4); R0(a, b, c, d, e, 5); R0(e, a, b, c, d, 6); R0(d, e, a, b, c, 7); R0(c, d, e, a, b, 8); R0(b, c, d, e, a, 9); R0(a, b, c, d, e, 10); R0(e, a, b, c, d, 11); R0(d, e, a, b, c, 12); R0(c, d, e, a, b, 13); R0(b, c, d, e, a, 14); R0(a, b, c, d, e, 15); R1(e, a, b, c, d, 16); R1(d, e, a, b, c, 17); R1(c, d, e, a, b, 18); R1(b, c, d, e, a, 19); R2(a, b, c, d, e, 20); R2(e, a, b, c, d, 21); R2(d, e, a, b, c, 22); R2(c, d, e, a, b, 23); R2(b, c, d, e, a, 24); R2(a, b, c, d, e, 25); R2(e, a, b, c, d, 26); R2(d, e, a, b, c, 27); R2(c, d, e, a, b, 28); R2(b, c, d, e, a, 29); R2(a, b, c, d, e, 30); R2(e, a, b, c, d, 31); R2(d, e, a, b, c, 32); R2(c, d, e, a, b, 33); R2(b, c, d, e, a, 34); R2(a, b, c, d, e, 35); R2(e, a, b, c, d, 36); R2(d, e, a, b, c, 37); R2(c, d, e, a, b, 38); R2(b, c, d, e, a, 39); R3(a, b, c, d, e, 40); R3(e, a, b, c, d, 41); R3(d, e, a, b, c, 42); R3(c, d, e, a, b, 43); R3(b, c, d, e, a, 44); R3(a, b, c, d, e, 45); R3(e, a, b, c, d, 46); R3(d, e, a, b, c, 47); R3(c, d, e, a, b, 48); R3(b, c, d, e, a, 49); R3(a, b, c, d, e, 50); R3(e, a, b, c, d, 51); R3(d, e, a, b, c, 52); R3(c, d, e, a, b, 53); R3(b, c, d, e, a, 54); R3(a, b, c, d, e, 55); R3(e, a, b, c, d, 56); R3(d, e, a, b, c, 57); R3(c, d, e, a, b, 58); R3(b, c, d, e, a, 59); R4(a, b, c, d, e, 60); R4(e, a, b, c, d, 61); R4(d, e, a, b, c, 62); R4(c, d, e, a, b, 63); R4(b, c, d, e, a, 64); R4(a, b, c, d, e, 65); R4(e, a, b, c, d, 66); R4(d, e, a, b, c, 67); R4(c, d, e, a, b, 68); R4(b, c, d, e, a, 69); R4(a, b, c, d, e, 70); R4(e, a, b, c, d, 71); R4(d, e, a, b, c, 72); R4(c, d, e, a, b, 73); R4(b, c, d, e, a, 74); R4(a, b, c, d, e, 75); R4(e, a, b, c, d, 76); R4(d, e, a, b, c, 77); R4(c, d, e, a, b, 78); R4(b, c, d, e, a, 79); state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; /* Erase working structures. The order of operations is important, * used to ensure that compiler doesn't optimize those out. */ memset(block, 0, sizeof(block)); a = b = c = d = e = 0; (void) a; (void) b; (void) c; (void) d; (void) e; } void cs_sha1_init(cs_sha1_ctx *context) { context->state[0] = 0x67452301; context->state[1] = 0xEFCDAB89; context->state[2] = 0x98BADCFE; context->state[3] = 0x10325476; context->state[4] = 0xC3D2E1F0; context->count[0] = context->count[1] = 0; } void cs_sha1_update(cs_sha1_ctx *context, const unsigned char *data, uint32_t len) { uint32_t i, j; j = context->count[0]; if ((context->count[0] += len << 3) < j) context->count[1]++; context->count[1] += (len >> 29); j = (j >> 3) & 63; if ((j + len) > 63) { memcpy(&context->buffer[j], data, (i = 64 - j)); cs_sha1_transform(context->state, context->buffer); for (; i + 63 < len; i += 64) { cs_sha1_transform(context->state, &data[i]); } j = 0; } else i = 0; memcpy(&context->buffer[j], &data[i], len - i); } void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *context) { unsigned i; unsigned char finalcount[8], c; for (i = 0; i < 8; i++) { finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >> ((3 - (i & 3)) * 8)) & 255); } c = 0200; cs_sha1_update(context, &c, 1); while ((context->count[0] & 504) != 448) { c = 0000; cs_sha1_update(context, &c, 1); } cs_sha1_update(context, finalcount, 8); for (i = 0; i < 20; i++) { digest[i] = (unsigned char) ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255); } memset(context, '\0', sizeof(*context)); memset(&finalcount, '\0', sizeof(finalcount)); } void cs_hmac_sha1(const unsigned char *key, size_t keylen, const unsigned char *data, size_t datalen, unsigned char out[20]) { cs_sha1_ctx ctx; unsigned char buf1[64], buf2[64], tmp_key[20], i; if (keylen > sizeof(buf1)) { cs_sha1_init(&ctx); cs_sha1_update(&ctx, key, keylen); cs_sha1_final(tmp_key, &ctx); key = tmp_key; keylen = sizeof(tmp_key); } memset(buf1, 0, sizeof(buf1)); memset(buf2, 0, sizeof(buf2)); memcpy(buf1, key, keylen); memcpy(buf2, key, keylen); for (i = 0; i < sizeof(buf1); i++) { buf1[i] ^= 0x36; buf2[i] ^= 0x5c; } cs_sha1_init(&ctx); cs_sha1_update(&ctx, buf1, sizeof(buf1)); cs_sha1_update(&ctx, data, datalen); cs_sha1_final(out, &ctx); cs_sha1_init(&ctx); cs_sha1_update(&ctx, buf2, sizeof(buf2)); cs_sha1_update(&ctx, out, 20); cs_sha1_final(out, &ctx); } #endif /* EXCLUDE_COMMON */ #ifdef MG_MODULE_LINES #line 1 "common/mbuf.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef EXCLUDE_COMMON #include <assert.h> #include <string.h> /* Amalgamated: #include "common/mbuf.h" */ #ifndef MBUF_REALLOC #define MBUF_REALLOC realloc #endif #ifndef MBUF_FREE #define MBUF_FREE free #endif void mbuf_init(struct mbuf *mbuf, size_t initial_size) WEAK; void mbuf_init(struct mbuf *mbuf, size_t initial_size) { mbuf->len = mbuf->size = 0; mbuf->buf = NULL; mbuf_resize(mbuf, initial_size); } void mbuf_free(struct mbuf *mbuf) WEAK; void mbuf_free(struct mbuf *mbuf) { if (mbuf->buf != NULL) { MBUF_FREE(mbuf->buf); mbuf_init(mbuf, 0); } } void mbuf_resize(struct mbuf *a, size_t new_size) WEAK; void mbuf_resize(struct mbuf *a, size_t new_size) { if (new_size > a->size || (new_size < a->size && new_size >= a->len)) { char *buf = (char *) MBUF_REALLOC(a->buf, new_size); /* * In case realloc fails, there's not much we can do, except keep things as * they are. Note that NULL is a valid return value from realloc when * size == 0, but that is covered too. */ if (buf == NULL && new_size != 0) return; a->buf = buf; a->size = new_size; } } void mbuf_trim(struct mbuf *mbuf) WEAK; void mbuf_trim(struct mbuf *mbuf) { mbuf_resize(mbuf, mbuf->len); } size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t) WEAK; size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t len) { char *p = NULL; assert(a != NULL); assert(a->len <= a->size); assert(off <= a->len); /* check overflow */ if (~(size_t) 0 - (size_t) a->buf < len) return 0; if (a->len + len <= a->size) { memmove(a->buf + off + len, a->buf + off, a->len - off); if (buf != NULL) { memcpy(a->buf + off, buf, len); } a->len += len; } else { size_t min_size = (a->len + len); size_t new_size = (size_t)(min_size * MBUF_SIZE_MULTIPLIER); if (new_size - min_size > MBUF_SIZE_MAX_HEADROOM) { new_size = min_size + MBUF_SIZE_MAX_HEADROOM; } p = (char *) MBUF_REALLOC(a->buf, new_size); if (p == NULL && new_size != min_size) { new_size = min_size; p = (char *) MBUF_REALLOC(a->buf, new_size); } if (p != NULL) { a->buf = p; if (off != a->len) { memmove(a->buf + off + len, a->buf + off, a->len - off); } if (buf != NULL) memcpy(a->buf + off, buf, len); a->len += len; a->size = new_size; } else { len = 0; } } return len; } size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) WEAK; size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) { return mbuf_insert(a, a->len, buf, len); } size_t mbuf_append_and_free(struct mbuf *a, void *buf, size_t len) WEAK; size_t mbuf_append_and_free(struct mbuf *a, void *data, size_t len) { size_t ret; /* Optimization: if the buffer is currently empty, * take over the user-provided buffer. */ if (a->len == 0) { if (a->buf != NULL) free(a->buf); a->buf = (char *) data; a->len = a->size = len; return len; } ret = mbuf_insert(a, a->len, data, len); free(data); return ret; } void mbuf_remove(struct mbuf *mb, size_t n) WEAK; void mbuf_remove(struct mbuf *mb, size_t n) { if (n > 0 && n <= mb->len) { memmove(mb->buf, mb->buf + n, mb->len - n); mb->len -= n; } } void mbuf_clear(struct mbuf *mb) WEAK; void mbuf_clear(struct mbuf *mb) { mb->len = 0; } void mbuf_move(struct mbuf *from, struct mbuf *to) WEAK; void mbuf_move(struct mbuf *from, struct mbuf *to) { memcpy(to, from, sizeof(*to)); memset(from, 0, sizeof(*from)); } #endif /* EXCLUDE_COMMON */ #ifdef MG_MODULE_LINES #line 1 "common/mg_str.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Amalgamated: #include "common/mg_mem.h" */ /* Amalgamated: #include "common/mg_str.h" */ /* Amalgamated: #include "common/platform.h" */ #include <ctype.h> #include <stdlib.h> #include <string.h> int mg_ncasecmp(const char *s1, const char *s2, size_t len) WEAK; struct mg_str mg_mk_str(const char *s) WEAK; struct mg_str mg_mk_str(const char *s) { struct mg_str ret = {s, 0}; if (s != NULL) ret.len = strlen(s); return ret; } struct mg_str mg_mk_str_n(const char *s, size_t len) WEAK; struct mg_str mg_mk_str_n(const char *s, size_t len) { struct mg_str ret = {s, len}; return ret; } int mg_vcmp(const struct mg_str *str1, const char *str2) WEAK; int mg_vcmp(const struct mg_str *str1, const char *str2) { size_t n2 = strlen(str2), n1 = str1->len; int r = strncmp(str1->p, str2, (n1 < n2) ? n1 : n2); if (r == 0) { return n1 - n2; } return r; } int mg_vcasecmp(const struct mg_str *str1, const char *str2) WEAK; int mg_vcasecmp(const struct mg_str *str1, const char *str2) { size_t n2 = strlen(str2), n1 = str1->len; int r = mg_ncasecmp(str1->p, str2, (n1 < n2) ? n1 : n2); if (r == 0) { return n1 - n2; } return r; } static struct mg_str mg_strdup_common(const struct mg_str s, int nul_terminate) { struct mg_str r = {NULL, 0}; if (s.len > 0 && s.p != NULL) { char *sc = (char *) MG_MALLOC(s.len + (nul_terminate ? 1 : 0)); if (sc != NULL) { memcpy(sc, s.p, s.len); if (nul_terminate) sc[s.len] = '\0'; r.p = sc; r.len = s.len; } } return r; } struct mg_str mg_strdup(const struct mg_str s) WEAK; struct mg_str mg_strdup(const struct mg_str s) { return mg_strdup_common(s, 0 /* NUL-terminate */); } struct mg_str mg_strdup_nul(const struct mg_str s) WEAK; struct mg_str mg_strdup_nul(const struct mg_str s) { return mg_strdup_common(s, 1 /* NUL-terminate */); } const char *mg_strchr(const struct mg_str s, int c) WEAK; const char *mg_strchr(const struct mg_str s, int c) { size_t i; for (i = 0; i < s.len; i++) { if (s.p[i] == c) return &s.p[i]; } return NULL; } int mg_strcmp(const struct mg_str str1, const struct mg_str str2) WEAK; int mg_strcmp(const struct mg_str str1, const struct mg_str str2) { size_t i = 0; while (i < str1.len && i < str2.len) { if (str1.p[i] < str2.p[i]) return -1; if (str1.p[i] > str2.p[i]) return 1; i++; } if (i < str1.len) return 1; if (i < str2.len) return -1; return 0; } int mg_strncmp(const struct mg_str, const struct mg_str, size_t n) WEAK; int mg_strncmp(const struct mg_str str1, const struct mg_str str2, size_t n) { struct mg_str s1 = str1; struct mg_str s2 = str2; if (s1.len > n) { s1.len = n; } if (s2.len > n) { s2.len = n; } return mg_strcmp(s1, s2); } void mg_strfree(struct mg_str *s) WEAK; void mg_strfree(struct mg_str *s) { char *sp = (char *) s->p; s->p = NULL; s->len = 0; if (sp != NULL) free(sp); } const char *mg_strstr(const struct mg_str haystack, const struct mg_str needle) WEAK; const char *mg_strstr(const struct mg_str haystack, const struct mg_str needle) { size_t i; if (needle.len > haystack.len) return NULL; for (i = 0; i <= haystack.len - needle.len; i++) { if (memcmp(haystack.p + i, needle.p, needle.len) == 0) { return haystack.p + i; } } return NULL; } struct mg_str mg_strstrip(struct mg_str s) WEAK; struct mg_str mg_strstrip(struct mg_str s) { while (s.len > 0 && isspace((int) *s.p)) { s.p++; s.len--; } while (s.len > 0 && isspace((int) *(s.p + s.len - 1))) { s.len--; } return s; } int mg_str_starts_with(struct mg_str s, struct mg_str prefix) WEAK; int mg_str_starts_with(struct mg_str s, struct mg_str prefix) { const struct mg_str sp = MG_MK_STR_N(s.p, prefix.len); if (s.len < prefix.len) return 0; return (mg_strcmp(sp, prefix) == 0); } #ifdef MG_MODULE_LINES #line 1 "common/str_util.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef EXCLUDE_COMMON /* Amalgamated: #include "common/str_util.h" */ /* Amalgamated: #include "common/mg_mem.h" */ /* Amalgamated: #include "common/platform.h" */ #ifndef C_DISABLE_BUILTIN_SNPRINTF #define C_DISABLE_BUILTIN_SNPRINTF 0 #endif /* Amalgamated: #include "common/mg_mem.h" */ size_t c_strnlen(const char *s, size_t maxlen) WEAK; size_t c_strnlen(const char *s, size_t maxlen) { size_t l = 0; for (; l < maxlen && s[l] != '\0'; l++) { } return l; } #define C_SNPRINTF_APPEND_CHAR(ch) \ do { \ if (i < (int) buf_size) buf[i] = ch; \ i++; \ } while (0) #define C_SNPRINTF_FLAG_ZERO 1 #if C_DISABLE_BUILTIN_SNPRINTF int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) WEAK; int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) { return vsnprintf(buf, buf_size, fmt, ap); } #else static int c_itoa(char *buf, size_t buf_size, int64_t num, int base, int flags, int field_width) { char tmp[40]; int i = 0, k = 0, neg = 0; if (num < 0) { neg++; num = -num; } /* Print into temporary buffer - in reverse order */ do { int rem = num % base; if (rem < 10) { tmp[k++] = '0' + rem; } else { tmp[k++] = 'a' + (rem - 10); } num /= base; } while (num > 0); /* Zero padding */ if (flags && C_SNPRINTF_FLAG_ZERO) { while (k < field_width && k < (int) sizeof(tmp) - 1) { tmp[k++] = '0'; } } /* And sign */ if (neg) { tmp[k++] = '-'; } /* Now output */ while (--k >= 0) { C_SNPRINTF_APPEND_CHAR(tmp[k]); } return i; } int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) WEAK; int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) { int ch, i = 0, len_mod, flags, precision, field_width; while ((ch = *fmt++) != '\0') { if (ch != '%') { C_SNPRINTF_APPEND_CHAR(ch); } else { /* * Conversion specification: * zero or more flags (one of: # 0 - <space> + ') * an optional minimum field width (digits) * an optional precision (. followed by digits, or *) * an optional length modifier (one of: hh h l ll L q j z t) * conversion specifier (one of: d i o u x X e E f F g G a A c s p n) */ flags = field_width = precision = len_mod = 0; /* Flags. only zero-pad flag is supported. */ if (*fmt == '0') { flags |= C_SNPRINTF_FLAG_ZERO; } /* Field width */ while (*fmt >= '0' && *fmt <= '9') { field_width *= 10; field_width += *fmt++ - '0'; } /* Dynamic field width */ if (*fmt == '*') { field_width = va_arg(ap, int); fmt++; } /* Precision */ if (*fmt == '.') { fmt++; if (*fmt == '*') { precision = va_arg(ap, int); fmt++; } else { while (*fmt >= '0' && *fmt <= '9') { precision *= 10; precision += *fmt++ - '0'; } } } /* Length modifier */ switch (*fmt) { case 'h': case 'l': case 'L': case 'I': case 'q': case 'j': case 'z': case 't': len_mod = *fmt++; if (*fmt == 'h') { len_mod = 'H'; fmt++; } if (*fmt == 'l') { len_mod = 'q'; fmt++; } break; } ch = *fmt++; if (ch == 's') { const char *s = va_arg(ap, const char *); /* Always fetch parameter */ int j; int pad = field_width - (precision >= 0 ? c_strnlen(s, precision) : 0); for (j = 0; j < pad; j++) { C_SNPRINTF_APPEND_CHAR(' '); } /* `s` may be NULL in case of %.*s */ if (s != NULL) { /* Ignore negative and 0 precisions */ for (j = 0; (precision <= 0 || j < precision) && s[j] != '\0'; j++) { C_SNPRINTF_APPEND_CHAR(s[j]); } } } else if (ch == 'c') { ch = va_arg(ap, int); /* Always fetch parameter */ C_SNPRINTF_APPEND_CHAR(ch); } else if (ch == 'd' && len_mod == 0) { i += c_itoa(buf + i, buf_size - i, va_arg(ap, int), 10, flags, field_width); } else if (ch == 'd' && len_mod == 'l') { i += c_itoa(buf + i, buf_size - i, va_arg(ap, long), 10, flags, field_width); #ifdef SSIZE_MAX } else if (ch == 'd' && len_mod == 'z') { i += c_itoa(buf + i, buf_size - i, va_arg(ap, ssize_t), 10, flags, field_width); #endif } else if (ch == 'd' && len_mod == 'q') { i += c_itoa(buf + i, buf_size - i, va_arg(ap, int64_t), 10, flags, field_width); } else if ((ch == 'x' || ch == 'u') && len_mod == 0) { i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned), ch == 'x' ? 16 : 10, flags, field_width); } else if ((ch == 'x' || ch == 'u') && len_mod == 'l') { i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned long), ch == 'x' ? 16 : 10, flags, field_width); } else if ((ch == 'x' || ch == 'u') && len_mod == 'z') { i += c_itoa(buf + i, buf_size - i, va_arg(ap, size_t), ch == 'x' ? 16 : 10, flags, field_width); } else if (ch == 'p') { unsigned long num = (unsigned long) (uintptr_t) va_arg(ap, void *); C_SNPRINTF_APPEND_CHAR('0'); C_SNPRINTF_APPEND_CHAR('x'); i += c_itoa(buf + i, buf_size - i, num, 16, flags, 0); } else { #ifndef NO_LIBC /* * TODO(lsm): abort is not nice in a library, remove it * Also, ESP8266 SDK doesn't have it */ abort(); #endif } } } /* Zero-terminate the result */ if (buf_size > 0) { buf[i < (int) buf_size ? i : (int) buf_size - 1] = '\0'; } return i; } #endif int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) WEAK; int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) { int result; va_list ap; va_start(ap, fmt); result = c_vsnprintf(buf, buf_size, fmt, ap); va_end(ap); return result; } #ifdef _WIN32 int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) { int ret; char buf[MAX_PATH * 2], buf2[MAX_PATH * 2], *p; strncpy(buf, path, sizeof(buf)); buf[sizeof(buf) - 1] = '\0'; /* Trim trailing slashes. Leave backslash for paths like "X:\" */ p = buf + strlen(buf) - 1; while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0'; memset(wbuf, 0, wbuf_len * sizeof(wchar_t)); ret = MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len); /* * Convert back to Unicode. If doubly-converted string does not match the * original, something is fishy, reject. */ WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2), NULL, NULL); if (strcmp(buf, buf2) != 0) { wbuf[0] = L'\0'; ret = 0; } return ret; } #endif /* _WIN32 */ /* The simplest O(mn) algorithm. Better implementation are GPLed */ const char *c_strnstr(const char *s, const char *find, size_t slen) WEAK; const char *c_strnstr(const char *s, const char *find, size_t slen) { size_t find_length = strlen(find); size_t i; for (i = 0; i < slen; i++) { if (i + find_length > slen) { return NULL; } if (strncmp(&s[i], find, find_length) == 0) { return &s[i]; } } return NULL; } #if CS_ENABLE_STRDUP char *strdup(const char *src) WEAK; char *strdup(const char *src) { size_t len = strlen(src) + 1; char *ret = MG_MALLOC(len); if (ret != NULL) { strcpy(ret, src); } return ret; } #endif void cs_to_hex(char *to, const unsigned char *p, size_t len) WEAK; void cs_to_hex(char *to, const unsigned char *p, size_t len) { static const char *hex = "0123456789abcdef"; for (; len--; p++) { *to++ = hex[p[0] >> 4]; *to++ = hex[p[0] & 0x0f]; } *to = '\0'; } static int fourbit(int ch) { if (ch >= '0' && ch <= '9') { return ch - '0'; } else if (ch >= 'a' && ch <= 'f') { return ch - 'a' + 10; } else if (ch >= 'A' && ch <= 'F') { return ch - 'A' + 10; } return 0; } void cs_from_hex(char *to, const char *p, size_t len) WEAK; void cs_from_hex(char *to, const char *p, size_t len) { size_t i; for (i = 0; i < len; i += 2) { *to++ = (fourbit(p[i]) << 4) + fourbit(p[i + 1]); } *to = '\0'; } #if CS_ENABLE_TO64 int64_t cs_to64(const char *s) WEAK; int64_t cs_to64(const char *s) { int64_t result = 0; int64_t neg = 1; while (*s && isspace((unsigned char) *s)) s++; if (*s == '-') { neg = -1; s++; } while (isdigit((unsigned char) *s)) { result *= 10; result += (*s - '0'); s++; } return result * neg; } #endif static int str_util_lowercase(const char *s) { return tolower(*(const unsigned char *) s); } int mg_ncasecmp(const char *s1, const char *s2, size_t len) WEAK; int mg_ncasecmp(const char *s1, const char *s2, size_t len) { int diff = 0; if (len > 0) do { diff = str_util_lowercase(s1++) - str_util_lowercase(s2++); } while (diff == 0 && s1[-1] != '\0' && --len > 0); return diff; } int mg_casecmp(const char *s1, const char *s2) WEAK; int mg_casecmp(const char *s1, const char *s2) { return mg_ncasecmp(s1, s2, (size_t) ~0); } int mg_asprintf(char **buf, size_t size, const char *fmt, ...) WEAK; int mg_asprintf(char **buf, size_t size, const char *fmt, ...) { int ret; va_list ap; va_start(ap, fmt); ret = mg_avprintf(buf, size, fmt, ap); va_end(ap); return ret; } int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) WEAK; int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) { va_list ap_copy; int len; va_copy(ap_copy, ap); len = vsnprintf(*buf, size, fmt, ap_copy); va_end(ap_copy); if (len < 0) { /* eCos and Windows are not standard-compliant and return -1 when * the buffer is too small. Keep allocating larger buffers until we * succeed or out of memory. */ *buf = NULL; /* LCOV_EXCL_START */ while (len < 0) { MG_FREE(*buf); if (size == 0) { size = 5; } size *= 2; if ((*buf = (char *) MG_MALLOC(size)) == NULL) { len = -1; break; } va_copy(ap_copy, ap); len = vsnprintf(*buf, size - 1, fmt, ap_copy); va_end(ap_copy); } /* * Microsoft version of vsnprintf() is not always null-terminated, so put * the terminator manually */ (*buf)[len] = 0; /* LCOV_EXCL_STOP */ } else if (len >= (int) size) { /* Standard-compliant code path. Allocate a buffer that is large enough. */ if ((*buf = (char *) MG_MALLOC(len + 1)) == NULL) { len = -1; /* LCOV_EXCL_LINE */ } else { /* LCOV_EXCL_LINE */ va_copy(ap_copy, ap); len = vsnprintf(*buf, len + 1, fmt, ap_copy); va_end(ap_copy); } } return len; } const char *mg_next_comma_list_entry(const char *, struct mg_str *, struct mg_str *) WEAK; const char *mg_next_comma_list_entry(const char *list, struct mg_str *val, struct mg_str *eq_val) { struct mg_str ret = mg_next_comma_list_entry_n(mg_mk_str(list), val, eq_val); return ret.p; } struct mg_str mg_next_comma_list_entry_n(struct mg_str list, struct mg_str *val, struct mg_str *eq_val) WEAK; struct mg_str mg_next_comma_list_entry_n(struct mg_str list, struct mg_str *val, struct mg_str *eq_val) { if (list.len == 0) { /* End of the list */ list = mg_mk_str(NULL); } else { const char *chr = NULL; *val = list; if ((chr = mg_strchr(*val, ',')) != NULL) { /* Comma found. Store length and shift the list ptr */ val->len = chr - val->p; chr++; list.len -= (chr - list.p); list.p = chr; } else { /* This value is the last one */ list = mg_mk_str_n(list.p + list.len, 0); } if (eq_val != NULL) { /* Value has form "x=y", adjust pointers and lengths */ /* so that val points to "x", and eq_val points to "y". */ eq_val->len = 0; eq_val->p = (const char *) memchr(val->p, '=', val->len); if (eq_val->p != NULL) { eq_val->p++; /* Skip over '=' character */ eq_val->len = val->p + val->len - eq_val->p; val->len = (eq_val->p - val->p) - 1; } } } return list; } size_t mg_match_prefix_n(const struct mg_str, const struct mg_str) WEAK; size_t mg_match_prefix_n(const struct mg_str pattern, const struct mg_str str) { const char *or_str; size_t res = 0, len = 0, i = 0, j = 0; if ((or_str = (const char *) memchr(pattern.p, '|', pattern.len)) != NULL || (or_str = (const char *) memchr(pattern.p, ',', pattern.len)) != NULL) { struct mg_str pstr = {pattern.p, (size_t)(or_str - pattern.p)}; res = mg_match_prefix_n(pstr, str); if (res > 0) return res; pstr.p = or_str + 1; pstr.len = (pattern.p + pattern.len) - (or_str + 1); return mg_match_prefix_n(pstr, str); } for (; i < pattern.len && j < str.len; i++, j++) { if (pattern.p[i] == '?') { continue; } else if (pattern.p[i] == '*') { i++; if (i < pattern.len && pattern.p[i] == '*') { i++; len = str.len - j; } else { len = 0; while (j + len < str.len && str.p[j + len] != '/') len++; } if (i == pattern.len || (pattern.p[i] == '$' && i == pattern.len - 1)) return j + len; do { const struct mg_str pstr = {pattern.p + i, pattern.len - i}; const struct mg_str sstr = {str.p + j + len, str.len - j - len}; res = mg_match_prefix_n(pstr, sstr); } while (res == 0 && len != 0 && len-- > 0); return res == 0 ? 0 : j + res + len; } else if (str_util_lowercase(&pattern.p[i]) != str_util_lowercase(&str.p[j])) { break; } } if (i < pattern.len && pattern.p[i] == '$') { return j == str.len ? str.len : 0; } return i == pattern.len ? j : 0; } size_t mg_match_prefix(const char *, int, const char *) WEAK; size_t mg_match_prefix(const char *pattern, int pattern_len, const char *str) { const struct mg_str pstr = {pattern, (size_t) pattern_len}; struct mg_str s = {str, 0}; if (str != NULL) s.len = strlen(str); return mg_match_prefix_n(pstr, s); } #endif /* EXCLUDE_COMMON */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_net.c" #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved * * This software is dual-licensed: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. For the terms of this * license, see <http://www.gnu.org/licenses/>. * * You are free to use this software under the terms of the GNU General * Public License, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * Alternatively, you can license this software under a commercial * license, as set out in <https://www.cesanta.com/license>. */ /* Amalgamated: #include "common/cs_time.h" */ /* Amalgamated: #include "mg_dns.h" */ /* Amalgamated: #include "mg_internal.h" */ /* Amalgamated: #include "mg_resolv.h" */ /* Amalgamated: #include "mg_util.h" */ #define MG_MAX_HOST_LEN 200 #ifndef MG_TCP_IO_SIZE #define MG_TCP_IO_SIZE 1460 #endif #ifndef MG_UDP_IO_SIZE #define MG_UDP_IO_SIZE 1460 #endif #define MG_COPY_COMMON_CONNECTION_OPTIONS(dst, src) \ memcpy(dst, src, sizeof(*dst)); /* Which flags can be pre-set by the user at connection creation time. */ #define _MG_ALLOWED_CONNECT_FLAGS_MASK \ (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \ MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_ENABLE_BROADCAST) /* Which flags should be modifiable by user's callbacks. */ #define _MG_CALLBACK_MODIFIABLE_FLAGS_MASK \ (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \ MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_SEND_AND_CLOSE | \ MG_F_CLOSE_IMMEDIATELY | MG_F_IS_WEBSOCKET | MG_F_DELETE_CHUNK) #ifndef intptr_t #define intptr_t long #endif MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c) { DBG(("%p %p", mgr, c)); c->mgr = mgr; c->next = mgr->active_connections; mgr->active_connections = c; c->prev = NULL; if (c->next != NULL) c->next->prev = c; if (c->sock != INVALID_SOCKET) { c->iface->vtable->add_conn(c); } } MG_INTERNAL void mg_remove_conn(struct mg_connection *conn) { if (conn->prev == NULL) conn->mgr->active_connections = conn->next; if (conn->prev) conn->prev->next = conn->next; if (conn->next) conn->next->prev = conn->prev; conn->prev = conn->next = NULL; conn->iface->vtable->remove_conn(conn); } MG_INTERNAL void mg_call(struct mg_connection *nc, mg_event_handler_t ev_handler, void *user_data, int ev, void *ev_data) { if (ev_handler == NULL) { /* * If protocol handler is specified, call it. Otherwise, call user-specified * event handler. */ ev_handler = nc->proto_handler ? nc->proto_handler : nc->handler; } if (ev != MG_EV_POLL) { DBG(("%p %s ev=%d ev_data=%p flags=0x%lx rmbl=%d smbl=%d", nc, ev_handler == nc->handler ? "user" : "proto", ev, ev_data, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len)); } #if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP if (nc->mgr->hexdump_file != NULL && ev != MG_EV_POLL && ev != MG_EV_RECV && ev != MG_EV_SEND /* handled separately */) { mg_hexdump_connection(nc, nc->mgr->hexdump_file, NULL, 0, ev); } #endif if (ev_handler != NULL) { unsigned long flags_before = nc->flags; ev_handler(nc, ev, ev_data MG_UD_ARG(user_data)); /* Prevent user handler from fiddling with system flags. */ if (ev_handler == nc->handler && nc->flags != flags_before) { nc->flags = (flags_before & ~_MG_CALLBACK_MODIFIABLE_FLAGS_MASK) | (nc->flags & _MG_CALLBACK_MODIFIABLE_FLAGS_MASK); } } if (ev != MG_EV_POLL) nc->mgr->num_calls++; if (ev != MG_EV_POLL) { DBG(("%p after %s flags=0x%lx rmbl=%d smbl=%d", nc, ev_handler == nc->handler ? "user" : "proto", nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len)); } #if !MG_ENABLE_CALLBACK_USERDATA (void) user_data; #endif } MG_INTERNAL void mg_timer(struct mg_connection *c, double now) { if (c->ev_timer_time > 0 && now >= c->ev_timer_time) { double old_value = c->ev_timer_time; c->ev_timer_time = 0; mg_call(c, NULL, c->user_data, MG_EV_TIMER, &old_value); } } MG_INTERNAL size_t recv_avail_size(struct mg_connection *conn, size_t max) { size_t avail; if (conn->recv_mbuf_limit < conn->recv_mbuf.len) return 0; avail = conn->recv_mbuf_limit - conn->recv_mbuf.len; return avail > max ? max : avail; } static int mg_do_recv(struct mg_connection *nc); int mg_if_poll(struct mg_connection *nc, double now) { if (nc->flags & MG_F_CLOSE_IMMEDIATELY) { mg_close_conn(nc); return 0; } else if (nc->flags & MG_F_SEND_AND_CLOSE) { if (nc->send_mbuf.len == 0) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; mg_close_conn(nc); return 0; } } else if (nc->flags & MG_F_RECV_AND_CLOSE) { mg_close_conn(nc); return 0; } #if MG_ENABLE_SSL if ((nc->flags & (MG_F_SSL | MG_F_LISTENING | MG_F_CONNECTING)) == MG_F_SSL) { /* SSL library may have data to be delivered to the app in its buffers, * drain them. */ int recved = 0; do { if (nc->flags & (MG_F_WANT_READ | MG_F_WANT_WRITE)) break; if (recv_avail_size(nc, MG_TCP_IO_SIZE) <= 0) break; recved = mg_do_recv(nc); } while (recved > 0); } #endif /* MG_ENABLE_SSL */ mg_timer(nc, now); { time_t now_t = (time_t) now; mg_call(nc, NULL, nc->user_data, MG_EV_POLL, &now_t); } return 1; } void mg_destroy_conn(struct mg_connection *conn, int destroy_if) { if (conn->sock != INVALID_SOCKET) { /* Don't print timer-only conns */ LOG(LL_DEBUG, ("%p 0x%lx %d", conn, conn->flags, destroy_if)); } if (destroy_if) conn->iface->vtable->destroy_conn(conn); if (conn->proto_data != NULL && conn->proto_data_destructor != NULL) { conn->proto_data_destructor(conn->proto_data); } #if MG_ENABLE_SSL mg_ssl_if_conn_free(conn); #endif mbuf_free(&conn->recv_mbuf); mbuf_free(&conn->send_mbuf); memset(conn, 0, sizeof(*conn)); MG_FREE(conn); } void mg_close_conn(struct mg_connection *conn) { /* See if there's any remaining data to deliver. Skip if user completely * throttled the connection there will be no progress anyway. */ if (conn->sock != INVALID_SOCKET && mg_do_recv(conn) == -2) { /* Receive is throttled, wait. */ conn->flags |= MG_F_RECV_AND_CLOSE; return; } #if MG_ENABLE_SSL if (conn->flags & MG_F_SSL_HANDSHAKE_DONE) { mg_ssl_if_conn_close_notify(conn); } #endif /* * Clearly mark the connection as going away (if not already). * Some net_if impls (LwIP) need this for cleanly handling half-dead conns. */ conn->flags |= MG_F_CLOSE_IMMEDIATELY; mg_remove_conn(conn); conn->iface->vtable->destroy_conn(conn); mg_call(conn, NULL, conn->user_data, MG_EV_CLOSE, NULL); mg_destroy_conn(conn, 0 /* destroy_if */); } void mg_mgr_init(struct mg_mgr *m, void *user_data) { struct mg_mgr_init_opts opts; memset(&opts, 0, sizeof(opts)); mg_mgr_init_opt(m, user_data, opts); } void mg_mgr_init_opt(struct mg_mgr *m, void *user_data, struct mg_mgr_init_opts opts) { memset(m, 0, sizeof(*m)); #if MG_ENABLE_BROADCAST m->ctl[0] = m->ctl[1] = INVALID_SOCKET; #endif m->user_data = user_data; #ifdef _WIN32 { WSADATA data; WSAStartup(MAKEWORD(2, 2), &data); } #elif defined(__unix__) /* Ignore SIGPIPE signal, so if client cancels the request, it * won't kill the whole process. */ signal(SIGPIPE, SIG_IGN); #endif { int i; if (opts.num_ifaces == 0) { opts.num_ifaces = mg_num_ifaces; opts.ifaces = mg_ifaces; } if (opts.main_iface != NULL) { opts.ifaces[MG_MAIN_IFACE] = opts.main_iface; } m->num_ifaces = opts.num_ifaces; m->ifaces = (struct mg_iface **) MG_MALLOC(sizeof(*m->ifaces) * opts.num_ifaces); for (i = 0; i < opts.num_ifaces; i++) { m->ifaces[i] = mg_if_create_iface(opts.ifaces[i], m); m->ifaces[i]->vtable->init(m->ifaces[i]); } } if (opts.nameserver != NULL) { m->nameserver = strdup(opts.nameserver); } DBG(("==================================")); DBG(("init mgr=%p", m)); #if MG_ENABLE_SSL { static int init_done; if (!init_done) { mg_ssl_if_init(); init_done++; } } #endif } void mg_mgr_free(struct mg_mgr *m) { struct mg_connection *conn, *tmp_conn; DBG(("%p", m)); if (m == NULL) return; /* Do one last poll, see https://github.com/cesanta/mongoose/issues/286 */ mg_mgr_poll(m, 0); #if MG_ENABLE_BROADCAST if (m->ctl[0] != INVALID_SOCKET) closesocket(m->ctl[0]); if (m->ctl[1] != INVALID_SOCKET) closesocket(m->ctl[1]); m->ctl[0] = m->ctl[1] = INVALID_SOCKET; #endif for (conn = m->active_connections; conn != NULL; conn = tmp_conn) { tmp_conn = conn->next; conn->flags |= MG_F_CLOSE_IMMEDIATELY; mg_close_conn(conn); } { int i; for (i = 0; i < m->num_ifaces; i++) { m->ifaces[i]->vtable->free(m->ifaces[i]); MG_FREE(m->ifaces[i]); } MG_FREE(m->ifaces); } MG_FREE((char *) m->nameserver); } int mg_mgr_poll(struct mg_mgr *m, int timeout_ms) { int i, num_calls_before = m->num_calls; for (i = 0; i < m->num_ifaces; i++) { m->ifaces[i]->vtable->poll(m->ifaces[i], timeout_ms); } return (m->num_calls - num_calls_before); } int mg_vprintf(struct mg_connection *nc, const char *fmt, va_list ap) { char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem; int len; if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) { mg_send(nc, buf, len); } if (buf != mem && buf != NULL) { MG_FREE(buf); /* LCOV_EXCL_LINE */ } /* LCOV_EXCL_LINE */ return len; } int mg_printf(struct mg_connection *conn, const char *fmt, ...) { int len; va_list ap; va_start(ap, fmt); len = mg_vprintf(conn, fmt, ap); va_end(ap); return len; } #if MG_ENABLE_SYNC_RESOLVER /* TODO(lsm): use non-blocking resolver */ static int mg_resolve2(const char *host, struct in_addr *ina) { #if MG_ENABLE_GETADDRINFO int rv = 0; struct addrinfo hints, *servinfo, *p; struct sockaddr_in *h = NULL; memset(&hints, 0, sizeof hints); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; if ((rv = getaddrinfo(host, NULL, NULL, &servinfo)) != 0) { DBG(("getaddrinfo(%s) failed: %s", host, strerror(mg_get_errno()))); return 0; } for (p = servinfo; p != NULL; p = p->ai_next) { memcpy(&h, &p->ai_addr, sizeof(h)); memcpy(ina, &h->sin_addr, sizeof(*ina)); } freeaddrinfo(servinfo); return 1; #else struct hostent *he; if ((he = gethostbyname(host)) == NULL) { DBG(("gethostbyname(%s) failed: %s", host, strerror(mg_get_errno()))); } else { memcpy(ina, he->h_addr_list[0], sizeof(*ina)); return 1; } return 0; #endif /* MG_ENABLE_GETADDRINFO */ } int mg_resolve(const char *host, char *buf, size_t n) { struct in_addr ad; return mg_resolve2(host, &ad) ? snprintf(buf, n, "%s", inet_ntoa(ad)) : 0; } #endif /* MG_ENABLE_SYNC_RESOLVER */ MG_INTERNAL struct mg_connection *mg_create_connection_base( struct mg_mgr *mgr, mg_event_handler_t callback, struct mg_add_sock_opts opts) { struct mg_connection *conn; if ((conn = (struct mg_connection *) MG_CALLOC(1, sizeof(*conn))) != NULL) { conn->sock = INVALID_SOCKET; conn->handler = callback; conn->mgr = mgr; conn->last_io_time = (time_t) mg_time(); conn->iface = (opts.iface != NULL ? opts.iface : mgr->ifaces[MG_MAIN_IFACE]); conn->flags = opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK; conn->user_data = opts.user_data; /* * SIZE_MAX is defined as a long long constant in * system headers on some platforms and so it * doesn't compile with pedantic ansi flags. */ conn->recv_mbuf_limit = ~0; } else { MG_SET_PTRPTR(opts.error_string, "failed to create connection"); } return conn; } MG_INTERNAL struct mg_connection *mg_create_connection( struct mg_mgr *mgr, mg_event_handler_t callback, struct mg_add_sock_opts opts) { struct mg_connection *conn = mg_create_connection_base(mgr, callback, opts); if (conn != NULL && !conn->iface->vtable->create_conn(conn)) { MG_FREE(conn); conn = NULL; } if (conn == NULL) { MG_SET_PTRPTR(opts.error_string, "failed to init connection"); } return conn; } /* * Address format: [PROTO://][HOST]:PORT * * HOST could be IPv4/IPv6 address or a host name. * `host` is a destination buffer to hold parsed HOST part. Should be at least * MG_MAX_HOST_LEN bytes long. * `proto` is a returned socket type, either SOCK_STREAM or SOCK_DGRAM * * Return: * -1 on parse error * 0 if HOST needs DNS lookup * >0 length of the address string */ MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa, int *proto, char *host, size_t host_len) { unsigned int a, b, c, d, port = 0; int ch, len = 0; #if MG_ENABLE_IPV6 char buf[100]; #endif /* * MacOS needs that. If we do not zero it, subsequent bind() will fail. * Also, all-zeroes in the socket address means binding to all addresses * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */ memset(sa, 0, sizeof(*sa)); sa->sin.sin_family = AF_INET; *proto = SOCK_STREAM; if (strncmp(str, "udp://", 6) == 0) { str += 6; *proto = SOCK_DGRAM; } else if (strncmp(str, "tcp://", 6) == 0) { str += 6; } if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) { /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */ sa->sin.sin_addr.s_addr = htonl(((uint32_t) a << 24) | ((uint32_t) b << 16) | c << 8 | d); sa->sin.sin_port = htons((uint16_t) port); #if MG_ENABLE_IPV6 } else if (sscanf(str, "[%99[^]]]:%u%n", buf, &port, &len) == 2 && inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) { /* IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080 */ sa->sin6.sin6_family = AF_INET6; sa->sin.sin_port = htons((uint16_t) port); #endif #if MG_ENABLE_ASYNC_RESOLVER } else if (strlen(str) < host_len && sscanf(str, "%[^ :]:%u%n", host, &port, &len) == 2) { sa->sin.sin_port = htons((uint16_t) port); if (mg_resolve_from_hosts_file(host, sa) != 0) { /* * if resolving from hosts file failed and the host * we are trying to resolve is `localhost` - we should * try to resolve it using `gethostbyname` and do not try * to resolve it via DNS server if gethostbyname has failed too */ if (mg_ncasecmp(host, "localhost", 9) != 0) { return 0; } #if MG_ENABLE_SYNC_RESOLVER if (!mg_resolve2(host, &sa->sin.sin_addr)) { return -1; } #else return -1; #endif } #endif } else if (sscanf(str, ":%u%n", &port, &len) == 1 || sscanf(str, "%u%n", &port, &len) == 1) { /* If only port is specified, bind to IPv4, INADDR_ANY */ sa->sin.sin_port = htons((uint16_t) port); } else { return -1; } /* Required for MG_ENABLE_ASYNC_RESOLVER=0 */ (void) host; (void) host_len; ch = str[len]; /* Character that follows the address */ return port < 0xffffUL && (ch == '\0' || ch == ',' || isspace(ch)) ? len : -1; } #if MG_ENABLE_SSL MG_INTERNAL void mg_ssl_handshake(struct mg_connection *nc) { int err = 0; int server_side = (nc->listener != NULL); enum mg_ssl_if_result res; if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) return; res = mg_ssl_if_handshake(nc); if (res == MG_SSL_OK) { nc->flags |= MG_F_SSL_HANDSHAKE_DONE; nc->flags &= ~(MG_F_WANT_READ | MG_F_WANT_WRITE); if (server_side) { mg_call(nc, NULL, nc->user_data, MG_EV_ACCEPT, &nc->sa); } else { mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &err); } } else if (res == MG_SSL_WANT_READ) { nc->flags |= MG_F_WANT_READ; } else if (res == MG_SSL_WANT_WRITE) { nc->flags |= MG_F_WANT_WRITE; } else { if (!server_side) { err = res; mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &err); } nc->flags |= MG_F_CLOSE_IMMEDIATELY; } } #endif /* MG_ENABLE_SSL */ struct mg_connection *mg_if_accept_new_conn(struct mg_connection *lc) { struct mg_add_sock_opts opts; struct mg_connection *nc; memset(&opts, 0, sizeof(opts)); nc = mg_create_connection(lc->mgr, lc->handler, opts); if (nc == NULL) return NULL; nc->listener = lc; nc->proto_handler = lc->proto_handler; nc->user_data = lc->user_data; nc->recv_mbuf_limit = lc->recv_mbuf_limit; nc->iface = lc->iface; if (lc->flags & MG_F_SSL) nc->flags |= MG_F_SSL; mg_add_conn(nc->mgr, nc); LOG(LL_DEBUG, ("%p %p %d %d", lc, nc, nc->sock, (int) nc->flags)); return nc; } void mg_if_accept_tcp_cb(struct mg_connection *nc, union socket_address *sa, size_t sa_len) { LOG(LL_DEBUG, ("%p %s://%s:%hu", nc, (nc->flags & MG_F_UDP ? "udp" : "tcp"), inet_ntoa(sa->sin.sin_addr), ntohs(sa->sin.sin_port))); nc->sa = *sa; #if MG_ENABLE_SSL if (nc->listener->flags & MG_F_SSL) { nc->flags |= MG_F_SSL; if (mg_ssl_if_conn_accept(nc, nc->listener) == MG_SSL_OK) { mg_ssl_handshake(nc); } else { mg_close_conn(nc); } } else #endif { mg_call(nc, NULL, nc->user_data, MG_EV_ACCEPT, &nc->sa); } (void) sa_len; } void mg_send(struct mg_connection *nc, const void *buf, int len) { nc->last_io_time = (time_t) mg_time(); mbuf_append(&nc->send_mbuf, buf, len); } static int mg_recv_tcp(struct mg_connection *nc, char *buf, size_t len); static int mg_recv_udp(struct mg_connection *nc, char *buf, size_t len); static int mg_do_recv(struct mg_connection *nc) { int res = 0; char *buf = NULL; size_t len = (nc->flags & MG_F_UDP ? MG_UDP_IO_SIZE : MG_TCP_IO_SIZE); if ((nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_CONNECTING)) || ((nc->flags & MG_F_LISTENING) && !(nc->flags & MG_F_UDP))) { return -1; } do { len = recv_avail_size(nc, len); if (len == 0) { res = -2; break; } if (nc->recv_mbuf.size < nc->recv_mbuf.len + len) { mbuf_resize(&nc->recv_mbuf, nc->recv_mbuf.len + len); } buf = nc->recv_mbuf.buf + nc->recv_mbuf.len; len = nc->recv_mbuf.size - nc->recv_mbuf.len; if (nc->flags & MG_F_UDP) { res = mg_recv_udp(nc, buf, len); } else { res = mg_recv_tcp(nc, buf, len); } } while (res > 0 && !(nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_UDP))); return res; } void mg_if_can_recv_cb(struct mg_connection *nc) { mg_do_recv(nc); } static int mg_recv_tcp(struct mg_connection *nc, char *buf, size_t len) { int n = 0; #if MG_ENABLE_SSL if (nc->flags & MG_F_SSL) { if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) { n = mg_ssl_if_read(nc, buf, len); DBG(("%p <- %d bytes (SSL)", nc, n)); if (n < 0) { if (n == MG_SSL_WANT_READ) { nc->flags |= MG_F_WANT_READ; n = 0; } else { nc->flags |= MG_F_CLOSE_IMMEDIATELY; } } else if (n > 0) { nc->flags &= ~MG_F_WANT_READ; } } else { mg_ssl_handshake(nc); } } else #endif { n = nc->iface->vtable->tcp_recv(nc, buf, len); DBG(("%p <- %d bytes", nc, n)); } if (n > 0) { nc->recv_mbuf.len += n; nc->last_io_time = (time_t) mg_time(); #if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP if (nc->mgr && nc->mgr->hexdump_file != NULL) { mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, n, MG_EV_RECV); } #endif mbuf_trim(&nc->recv_mbuf); mg_call(nc, NULL, nc->user_data, MG_EV_RECV, &n); } else if (n < 0) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; } mbuf_trim(&nc->recv_mbuf); return n; } static int mg_recv_udp(struct mg_connection *nc, char *buf, size_t len) { int n = 0; struct mg_connection *lc = nc; union socket_address sa; size_t sa_len = sizeof(sa); n = nc->iface->vtable->udp_recv(lc, buf, len, &sa, &sa_len); if (n < 0) { lc->flags |= MG_F_CLOSE_IMMEDIATELY; goto out; } if (nc->flags & MG_F_LISTENING) { /* * Do we have an existing connection for this source? * This is very inefficient for long connection lists. */ lc = nc; for (nc = mg_next(lc->mgr, NULL); nc != NULL; nc = mg_next(lc->mgr, nc)) { if (memcmp(&nc->sa.sa, &sa.sa, sa_len) == 0 && nc->listener == lc) { break; } } if (nc == NULL) { struct mg_add_sock_opts opts; memset(&opts, 0, sizeof(opts)); /* Create fake connection w/out sock initialization */ nc = mg_create_connection_base(lc->mgr, lc->handler, opts); if (nc != NULL) { nc->sock = lc->sock; nc->listener = lc; nc->sa = sa; nc->proto_handler = lc->proto_handler; nc->user_data = lc->user_data; nc->recv_mbuf_limit = lc->recv_mbuf_limit; nc->flags = MG_F_UDP; /* * Long-lived UDP "connections" i.e. interactions that involve more * than one request and response are rare, most are transactional: * response is sent and the "connection" is closed. Or - should be. * But users (including ourselves) tend to forget about that part, * because UDP is connectionless and one does not think about * processing a UDP request as handling a connection that needs to be * closed. Thus, we begin with SEND_AND_CLOSE flag set, which should * be a reasonable default for most use cases, but it is possible to * turn it off the connection should be kept alive after processing. */ nc->flags |= MG_F_SEND_AND_CLOSE; mg_add_conn(lc->mgr, nc); mg_call(nc, NULL, nc->user_data, MG_EV_ACCEPT, &nc->sa); } } } if (nc != NULL) { DBG(("%p <- %d bytes from %s:%d", nc, n, inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port))); if (nc == lc) { nc->recv_mbuf.len += n; } else { mbuf_append(&nc->recv_mbuf, buf, n); } mbuf_trim(&lc->recv_mbuf); lc->last_io_time = nc->last_io_time = (time_t) mg_time(); #if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP if (nc->mgr && nc->mgr->hexdump_file != NULL) { mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, n, MG_EV_RECV); } #endif if (n != 0) { mg_call(nc, NULL, nc->user_data, MG_EV_RECV, &n); } } out: mbuf_free(&lc->recv_mbuf); return n; } void mg_if_can_send_cb(struct mg_connection *nc) { int n = 0; const char *buf = nc->send_mbuf.buf; size_t len = nc->send_mbuf.len; if (nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_CONNECTING)) { return; } if (!(nc->flags & MG_F_UDP)) { if (nc->flags & MG_F_LISTENING) return; if (len > MG_TCP_IO_SIZE) len = MG_TCP_IO_SIZE; } #if MG_ENABLE_SSL if (nc->flags & MG_F_SSL) { if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) { if (len > 0) { n = mg_ssl_if_write(nc, buf, len); DBG(("%p -> %d bytes (SSL)", nc, n)); } if (n < 0) { if (n == MG_SSL_WANT_WRITE) { nc->flags |= MG_F_WANT_WRITE; n = 0; } else { nc->flags |= MG_F_CLOSE_IMMEDIATELY; } } else { nc->flags &= ~MG_F_WANT_WRITE; } } else { mg_ssl_handshake(nc); } } else #endif if (len > 0) { if (nc->flags & MG_F_UDP) { n = nc->iface->vtable->udp_send(nc, buf, len); } else { n = nc->iface->vtable->tcp_send(nc, buf, len); } DBG(("%p -> %d bytes", nc, n)); } #if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP if (n > 0 && nc->mgr && nc->mgr->hexdump_file != NULL) { mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, n, MG_EV_SEND); } #endif if (n < 0) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; } else if (n > 0) { nc->last_io_time = (time_t) mg_time(); mbuf_remove(&nc->send_mbuf, n); mbuf_trim(&nc->send_mbuf); } if (n != 0) mg_call(nc, NULL, nc->user_data, MG_EV_SEND, &n); } /* * Schedules an async connect for a resolved address and proto. * Called from two places: `mg_connect_opt()` and from async resolver. * When called from the async resolver, it must trigger `MG_EV_CONNECT` event * with a failure flag to indicate connection failure. */ MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc, int proto, union socket_address *sa) { LOG(LL_DEBUG, ("%p %s://%s:%hu", nc, proto == SOCK_DGRAM ? "udp" : "tcp", inet_ntoa(sa->sin.sin_addr), ntohs(sa->sin.sin_port))); nc->flags |= MG_F_CONNECTING; if (proto == SOCK_DGRAM) { nc->iface->vtable->connect_udp(nc); } else { nc->iface->vtable->connect_tcp(nc, sa); } mg_add_conn(nc->mgr, nc); return nc; } void mg_if_connect_cb(struct mg_connection *nc, int err) { LOG(LL_DEBUG, ("%p %s://%s:%hu -> %d", nc, (nc->flags & MG_F_UDP ? "udp" : "tcp"), inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port), err)); nc->flags &= ~MG_F_CONNECTING; if (err != 0) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; } #if MG_ENABLE_SSL if (err == 0 && (nc->flags & MG_F_SSL)) { mg_ssl_handshake(nc); } else #endif { mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &err); } } #if MG_ENABLE_ASYNC_RESOLVER /* * Callback for the async resolver on mg_connect_opt() call. * Main task of this function is to trigger MG_EV_CONNECT event with * either failure (and dealloc the connection) * or success (and proceed with connect() */ static void resolve_cb(struct mg_dns_message *msg, void *data, enum mg_resolve_err e) { struct mg_connection *nc = (struct mg_connection *) data; int i; int failure = -1; nc->flags &= ~MG_F_RESOLVING; if (msg != NULL) { /* * Take the first DNS A answer and run... */ for (i = 0; i < msg->num_answers; i++) { if (msg->answers[i].rtype == MG_DNS_A_RECORD) { /* * Async resolver guarantees that there is at least one answer. * TODO(lsm): handle IPv6 answers too */ mg_dns_parse_record_data(msg, &msg->answers[i], &nc->sa.sin.sin_addr, 4); mg_do_connect(nc, nc->flags & MG_F_UDP ? SOCK_DGRAM : SOCK_STREAM, &nc->sa); return; } } } if (e == MG_RESOLVE_TIMEOUT) { double now = mg_time(); mg_call(nc, NULL, nc->user_data, MG_EV_TIMER, &now); } /* * If we get there was no MG_DNS_A_RECORD in the answer */ mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &failure); mg_call(nc, NULL, nc->user_data, MG_EV_CLOSE, NULL); mg_destroy_conn(nc, 1 /* destroy_if */); } #endif struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *address, MG_CB(mg_event_handler_t callback, void *user_data)) { struct mg_connect_opts opts; memset(&opts, 0, sizeof(opts)); return mg_connect_opt(mgr, address, MG_CB(callback, user_data), opts); } void mg_ev_handler_empty(struct mg_connection *c, int ev, void *ev_data MG_UD_ARG(void *user_data)) { (void) c; (void) ev; (void) ev_data; #if MG_ENABLE_CALLBACK_USERDATA (void) user_data; #endif } struct mg_connection *mg_connect_opt(struct mg_mgr *mgr, const char *address, MG_CB(mg_event_handler_t callback, void *user_data), struct mg_connect_opts opts) { struct mg_connection *nc = NULL; int proto, rc; struct mg_add_sock_opts add_sock_opts; char host[MG_MAX_HOST_LEN]; MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts); if (callback == NULL) callback = mg_ev_handler_empty; if ((nc = mg_create_connection(mgr, callback, add_sock_opts)) == NULL) { return NULL; } if ((rc = mg_parse_address(address, &nc->sa, &proto, host, sizeof(host))) < 0) { /* Address is malformed */ MG_SET_PTRPTR(opts.error_string, "cannot parse address"); mg_destroy_conn(nc, 1 /* destroy_if */); return NULL; } nc->flags |= opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK; nc->flags |= (proto == SOCK_DGRAM) ? MG_F_UDP : 0; #if MG_ENABLE_CALLBACK_USERDATA nc->user_data = user_data; #else nc->user_data = opts.user_data; #endif #if MG_ENABLE_SSL LOG(LL_DEBUG, ("%p %s %s,%s,%s", nc, address, (opts.ssl_cert ? opts.ssl_cert : "-"), (opts.ssl_key ? opts.ssl_key : "-"), (opts.ssl_ca_cert ? opts.ssl_ca_cert : "-"))); if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL || opts.ssl_psk_identity != NULL) { const char *err_msg = NULL; struct mg_ssl_if_conn_params params; if (nc->flags & MG_F_UDP) { MG_SET_PTRPTR(opts.error_string, "SSL for UDP is not supported"); mg_destroy_conn(nc, 1 /* destroy_if */); return NULL; } memset(&params, 0, sizeof(params)); params.cert = opts.ssl_cert; params.key = opts.ssl_key; params.ca_cert = opts.ssl_ca_cert; params.cipher_suites = opts.ssl_cipher_suites; params.psk_identity = opts.ssl_psk_identity; params.psk_key = opts.ssl_psk_key; if (opts.ssl_ca_cert != NULL) { if (opts.ssl_server_name != NULL) { if (strcmp(opts.ssl_server_name, "*") != 0) { params.server_name = opts.ssl_server_name; } } else if (rc == 0) { /* If it's a DNS name, use host. */ params.server_name = host; } } if (mg_ssl_if_conn_init(nc, &params, &err_msg) != MG_SSL_OK) { MG_SET_PTRPTR(opts.error_string, err_msg); mg_destroy_conn(nc, 1 /* destroy_if */); return NULL; } nc->flags |= MG_F_SSL; } #endif /* MG_ENABLE_SSL */ if (rc == 0) { #if MG_ENABLE_ASYNC_RESOLVER /* * DNS resolution is required for host. * mg_parse_address() fills port in nc->sa, which we pass to resolve_cb() */ struct mg_connection *dns_conn = NULL; struct mg_resolve_async_opts o; memset(&o, 0, sizeof(o)); o.dns_conn = &dns_conn; o.nameserver = opts.nameserver; if (mg_resolve_async_opt(nc->mgr, host, MG_DNS_A_RECORD, resolve_cb, nc, o) != 0) { MG_SET_PTRPTR(opts.error_string, "cannot schedule DNS lookup"); mg_destroy_conn(nc, 1 /* destroy_if */); return NULL; } nc->priv_2 = dns_conn; nc->flags |= MG_F_RESOLVING; return nc; #else MG_SET_PTRPTR(opts.error_string, "Resolver is disabled"); mg_destroy_conn(nc, 1 /* destroy_if */); return NULL; #endif } else { /* Address is parsed and resolved to IP. proceed with connect() */ return mg_do_connect(nc, proto, &nc->sa); } } struct mg_connection *mg_bind(struct mg_mgr *srv, const char *address, MG_CB(mg_event_handler_t event_handler, void *user_data)) { struct mg_bind_opts opts; memset(&opts, 0, sizeof(opts)); return mg_bind_opt(srv, address, MG_CB(event_handler, user_data), opts); } struct mg_connection *mg_bind_opt(struct mg_mgr *mgr, const char *address, MG_CB(mg_event_handler_t callback, void *user_data), struct mg_bind_opts opts) { union socket_address sa; struct mg_connection *nc = NULL; int proto, rc; struct mg_add_sock_opts add_sock_opts; char host[MG_MAX_HOST_LEN]; #if MG_ENABLE_CALLBACK_USERDATA opts.user_data = user_data; #endif if (callback == NULL) callback = mg_ev_handler_empty; MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts); if (mg_parse_address(address, &sa, &proto, host, sizeof(host)) <= 0) { MG_SET_PTRPTR(opts.error_string, "cannot parse address"); return NULL; } nc = mg_create_connection(mgr, callback, add_sock_opts); if (nc == NULL) { return NULL; } nc->sa = sa; nc->flags |= MG_F_LISTENING; if (proto == SOCK_DGRAM) nc->flags |= MG_F_UDP; #if MG_ENABLE_SSL DBG(("%p %s %s,%s,%s", nc, address, (opts.ssl_cert ? opts.ssl_cert : "-"), (opts.ssl_key ? opts.ssl_key : "-"), (opts.ssl_ca_cert ? opts.ssl_ca_cert : "-"))); if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL) { const char *err_msg = NULL; struct mg_ssl_if_conn_params params; if (nc->flags & MG_F_UDP) { MG_SET_PTRPTR(opts.error_string, "SSL for UDP is not supported"); mg_destroy_conn(nc, 1 /* destroy_if */); return NULL; } memset(&params, 0, sizeof(params)); params.cert = opts.ssl_cert; params.key = opts.ssl_key; params.ca_cert = opts.ssl_ca_cert; params.cipher_suites = opts.ssl_cipher_suites; if (mg_ssl_if_conn_init(nc, &params, &err_msg) != MG_SSL_OK) { MG_SET_PTRPTR(opts.error_string, err_msg); mg_destroy_conn(nc, 1 /* destroy_if */); return NULL; } nc->flags |= MG_F_SSL; } #endif /* MG_ENABLE_SSL */ if (nc->flags & MG_F_UDP) { rc = nc->iface->vtable->listen_udp(nc, &nc->sa); } else { rc = nc->iface->vtable->listen_tcp(nc, &nc->sa); } if (rc != 0) { DBG(("Failed to open listener: %d", rc)); MG_SET_PTRPTR(opts.error_string, "failed to open listener"); mg_destroy_conn(nc, 1 /* destroy_if */); return NULL; } mg_add_conn(nc->mgr, nc); return nc; } struct mg_connection *mg_next(struct mg_mgr *s, struct mg_connection *conn) { return conn == NULL ? s->active_connections : conn->next; } #if MG_ENABLE_BROADCAST void mg_broadcast(struct mg_mgr *mgr, mg_event_handler_t cb, void *data, size_t len) { struct ctl_msg ctl_msg; /* * Mongoose manager has a socketpair, `struct mg_mgr::ctl`, * where `mg_broadcast()` pushes the message. * `mg_mgr_poll()` wakes up, reads a message from the socket pair, and calls * specified callback for each connection. Thus the callback function executes * in event manager thread. */ if (mgr->ctl[0] != INVALID_SOCKET && data != NULL && len < sizeof(ctl_msg.message)) { size_t dummy; ctl_msg.callback = cb; memcpy(ctl_msg.message, data, len); dummy = MG_SEND_FUNC(mgr->ctl[0], (char *) &ctl_msg, offsetof(struct ctl_msg, message) + len, 0); dummy = MG_RECV_FUNC(mgr->ctl[0], (char *) &len, 1, 0); (void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */ } } #endif /* MG_ENABLE_BROADCAST */ static int isbyte(int n) { return n >= 0 && n <= 255; } static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) { int n, a, b, c, d, slash = 32, len = 0; if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 && slash < 33) { len = n; *net = ((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | d; *mask = slash ? 0xffffffffU << (32 - slash) : 0; } return len; } int mg_check_ip_acl(const char *acl, uint32_t remote_ip) { int allowed, flag; uint32_t net, mask; struct mg_str vec; /* If any ACL is set, deny by default */ allowed = (acl == NULL || *acl == '\0') ? '+' : '-'; while ((acl = mg_next_comma_list_entry(acl, &vec, NULL)) != NULL) { flag = vec.p[0]; if ((flag != '+' && flag != '-') || parse_net(&vec.p[1], &net, &mask) == 0) { return -1; } if (net == (remote_ip & mask)) { allowed = flag; } } DBG(("%08x %c", (unsigned int) remote_ip, allowed)); return allowed == '+'; } /* Move data from one connection to another */ void mg_forward(struct mg_connection *from, struct mg_connection *to) { mg_send(to, from->recv_mbuf.buf, from->recv_mbuf.len); mbuf_remove(&from->recv_mbuf, from->recv_mbuf.len); } double mg_set_timer(struct mg_connection *c, double timestamp) { double result = c->ev_timer_time; c->ev_timer_time = timestamp; /* * If this connection is resolving, it's not in the list of active * connections, so not processed yet. It has a DNS resolver connection * linked to it. Set up a timer for the DNS connection. */ DBG(("%p %p %d -> %lu", c, c->priv_2, (c->flags & MG_F_RESOLVING ? 1 : 0), (unsigned long) timestamp)); if ((c->flags & MG_F_RESOLVING) && c->priv_2 != NULL) { mg_set_timer((struct mg_connection *) c->priv_2, timestamp); } return result; } void mg_sock_set(struct mg_connection *nc, sock_t sock) { if (sock != INVALID_SOCKET) { nc->iface->vtable->sock_set(nc, sock); } } void mg_if_get_conn_addr(struct mg_connection *nc, int remote, union socket_address *sa) { nc->iface->vtable->get_conn_addr(nc, remote, sa); } struct mg_connection *mg_add_sock_opt(struct mg_mgr *s, sock_t sock, MG_CB(mg_event_handler_t callback, void *user_data), struct mg_add_sock_opts opts) { #if MG_ENABLE_CALLBACK_USERDATA opts.user_data = user_data; #endif struct mg_connection *nc = mg_create_connection_base(s, callback, opts); if (nc != NULL) { mg_sock_set(nc, sock); mg_add_conn(nc->mgr, nc); } return nc; } struct mg_connection *mg_add_sock(struct mg_mgr *s, sock_t sock, MG_CB(mg_event_handler_t callback, void *user_data)) { struct mg_add_sock_opts opts; memset(&opts, 0, sizeof(opts)); return mg_add_sock_opt(s, sock, MG_CB(callback, user_data), opts); } double mg_time(void) { return cs_time(); } #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_net_if_socket.h" #endif /* * Copyright (c) 2014-2016 Cesanta Software Limited * All rights reserved */ #ifndef CS_MONGOOSE_SRC_NET_IF_SOCKET_H_ #define CS_MONGOOSE_SRC_NET_IF_SOCKET_H_ /* Amalgamated: #include "mg_net_if.h" */ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #ifndef MG_ENABLE_NET_IF_SOCKET #define MG_ENABLE_NET_IF_SOCKET MG_NET_IF == MG_NET_IF_SOCKET #endif extern const struct mg_iface_vtable mg_socket_iface_vtable; #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* CS_MONGOOSE_SRC_NET_IF_SOCKET_H_ */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_net_if_socks.h" #endif /* * Copyright (c) 2014-2017 Cesanta Software Limited * All rights reserved */ #ifndef CS_MONGOOSE_SRC_NET_IF_SOCKS_H_ #define CS_MONGOOSE_SRC_NET_IF_SOCKS_H_ #if MG_ENABLE_SOCKS /* Amalgamated: #include "mg_net_if.h" */ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ extern const struct mg_iface_vtable mg_socks_iface_vtable; #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* MG_ENABLE_SOCKS */ #endif /* CS_MONGOOSE_SRC_NET_IF_SOCKS_H_ */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_net_if.c" #endif /* Amalgamated: #include "mg_net_if.h" */ /* Amalgamated: #include "mg_internal.h" */ /* Amalgamated: #include "mg_net_if_socket.h" */ extern const struct mg_iface_vtable mg_default_iface_vtable; const struct mg_iface_vtable *mg_ifaces[] = { &mg_default_iface_vtable, }; int mg_num_ifaces = (int) (sizeof(mg_ifaces) / sizeof(mg_ifaces[0])); struct mg_iface *mg_if_create_iface(const struct mg_iface_vtable *vtable, struct mg_mgr *mgr) { struct mg_iface *iface = (struct mg_iface *) MG_CALLOC(1, sizeof(*iface)); iface->mgr = mgr; iface->data = NULL; iface->vtable = vtable; return iface; } struct mg_iface *mg_find_iface(struct mg_mgr *mgr, const struct mg_iface_vtable *vtable, struct mg_iface *from) { int i = 0; if (from != NULL) { for (i = 0; i < mgr->num_ifaces; i++) { if (mgr->ifaces[i] == from) { i++; break; } } } for (; i < mgr->num_ifaces; i++) { if (mgr->ifaces[i]->vtable == vtable) { return mgr->ifaces[i]; } } return NULL; } double mg_mgr_min_timer(const struct mg_mgr *mgr) { double min_timer = 0; struct mg_connection *nc; for (nc = mgr->active_connections; nc != NULL; nc = nc->next) { if (nc->ev_timer_time <= 0) continue; if (min_timer == 0 || nc->ev_timer_time < min_timer) { min_timer = nc->ev_timer_time; } } return min_timer; } #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_net_if_null.c" #endif /* * Copyright (c) 2018 Cesanta Software Limited * All rights reserved * * This software is dual-licensed: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. For the terms of this * license, see <http://www.gnu.org/licenses/>. * * You are free to use this software under the terms of the GNU General * Public License, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * Alternatively, you can license this software under a commercial * license, as set out in <https://www.cesanta.com/license>. */ static void mg_null_if_connect_tcp(struct mg_connection *c, const union socket_address *sa) { c->flags |= MG_F_CLOSE_IMMEDIATELY; (void) sa; } static void mg_null_if_connect_udp(struct mg_connection *c) { c->flags |= MG_F_CLOSE_IMMEDIATELY; } static int mg_null_if_listen_tcp(struct mg_connection *c, union socket_address *sa) { (void) c; (void) sa; return -1; } static int mg_null_if_listen_udp(struct mg_connection *c, union socket_address *sa) { (void) c; (void) sa; return -1; } static int mg_null_if_tcp_send(struct mg_connection *c, const void *buf, size_t len) { (void) c; (void) buf; (void) len; return -1; } static int mg_null_if_udp_send(struct mg_connection *c, const void *buf, size_t len) { (void) c; (void) buf; (void) len; return -1; } int mg_null_if_tcp_recv(struct mg_connection *c, void *buf, size_t len) { (void) c; (void) buf; (void) len; return -1; } int mg_null_if_udp_recv(struct mg_connection *c, void *buf, size_t len, union socket_address *sa, size_t *sa_len) { (void) c; (void) buf; (void) len; (void) sa; (void) sa_len; return -1; } static int mg_null_if_create_conn(struct mg_connection *c) { (void) c; return 1; } static void mg_null_if_destroy_conn(struct mg_connection *c) { (void) c; } static void mg_null_if_sock_set(struct mg_connection *c, sock_t sock) { (void) c; (void) sock; } static void mg_null_if_init(struct mg_iface *iface) { (void) iface; } static void mg_null_if_free(struct mg_iface *iface) { (void) iface; } static void mg_null_if_add_conn(struct mg_connection *c) { c->sock = INVALID_SOCKET; c->flags |= MG_F_CLOSE_IMMEDIATELY; } static void mg_null_if_remove_conn(struct mg_connection *c) { (void) c; } static time_t mg_null_if_poll(struct mg_iface *iface, int timeout_ms) { struct mg_mgr *mgr = iface->mgr; struct mg_connection *nc, *tmp; double now = mg_time(); /* We basically just run timers and poll. */ for (nc = mgr->active_connections; nc != NULL; nc = tmp) { tmp = nc->next; mg_if_poll(nc, now); } (void) timeout_ms; return (time_t) now; } static void mg_null_if_get_conn_addr(struct mg_connection *c, int remote, union socket_address *sa) { (void) c; (void) remote; (void) sa; } #define MG_NULL_IFACE_VTABLE \ { \ mg_null_if_init, mg_null_if_free, mg_null_if_add_conn, \ mg_null_if_remove_conn, mg_null_if_poll, mg_null_if_listen_tcp, \ mg_null_if_listen_udp, mg_null_if_connect_tcp, mg_null_if_connect_udp, \ mg_null_if_tcp_send, mg_null_if_udp_send, mg_null_if_tcp_recv, \ mg_null_if_udp_recv, mg_null_if_create_conn, mg_null_if_destroy_conn, \ mg_null_if_sock_set, mg_null_if_get_conn_addr, \ } const struct mg_iface_vtable mg_null_iface_vtable = MG_NULL_IFACE_VTABLE; #if MG_NET_IF == MG_NET_IF_NULL const struct mg_iface_vtable mg_default_iface_vtable = MG_NULL_IFACE_VTABLE; #endif /* MG_NET_IF == MG_NET_IF_NULL */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_net_if_socket.c" #endif /* * Copyright (c) 2014-2016 Cesanta Software Limited * All rights reserved */ #if MG_ENABLE_NET_IF_SOCKET /* Amalgamated: #include "mg_net_if_socket.h" */ /* Amalgamated: #include "mg_internal.h" */ /* Amalgamated: #include "mg_util.h" */ static sock_t mg_open_listening_socket(union socket_address *sa, int type, int proto); void mg_set_non_blocking_mode(sock_t sock) { #ifdef _WIN32 unsigned long on = 1; ioctlsocket(sock, FIONBIO, &on); #else int flags = fcntl(sock, F_GETFL, 0); fcntl(sock, F_SETFL, flags | O_NONBLOCK); #endif } static int mg_is_error(void) { int err = mg_get_errno(); return err != EINPROGRESS && err != EWOULDBLOCK #ifndef WINCE && err != EAGAIN && err != EINTR #endif #ifdef _WIN32 && WSAGetLastError() != WSAEINTR && WSAGetLastError() != WSAEWOULDBLOCK #endif ; } void mg_socket_if_connect_tcp(struct mg_connection *nc, const union socket_address *sa) { int rc, proto = 0; nc->sock = socket(AF_INET, SOCK_STREAM, proto); if (nc->sock == INVALID_SOCKET) { nc->err = mg_get_errno() ? mg_get_errno() : 1; return; } #if !defined(MG_ESP8266) mg_set_non_blocking_mode(nc->sock); #endif rc = connect(nc->sock, &sa->sa, sizeof(sa->sin)); nc->err = rc < 0 && mg_is_error() ? mg_get_errno() : 0; DBG(("%p sock %d rc %d errno %d err %d", nc, nc->sock, rc, mg_get_errno(), nc->err)); } void mg_socket_if_connect_udp(struct mg_connection *nc) { nc->sock = socket(AF_INET, SOCK_DGRAM, 0); if (nc->sock == INVALID_SOCKET) { nc->err = mg_get_errno() ? mg_get_errno() : 1; return; } if (nc->flags & MG_F_ENABLE_BROADCAST) { int optval = 1; if (setsockopt(nc->sock, SOL_SOCKET, SO_BROADCAST, (const char *) &optval, sizeof(optval)) < 0) { nc->err = mg_get_errno() ? mg_get_errno() : 1; return; } } nc->err = 0; } int mg_socket_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) { int proto = 0; sock_t sock = mg_open_listening_socket(sa, SOCK_STREAM, proto); if (sock == INVALID_SOCKET) { return (mg_get_errno() ? mg_get_errno() : 1); } mg_sock_set(nc, sock); return 0; } static int mg_socket_if_listen_udp(struct mg_connection *nc, union socket_address *sa) { sock_t sock = mg_open_listening_socket(sa, SOCK_DGRAM, 0); if (sock == INVALID_SOCKET) return (mg_get_errno() ? mg_get_errno() : 1); mg_sock_set(nc, sock); return 0; } static int mg_socket_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) { int n = (int) MG_SEND_FUNC(nc->sock, buf, len, 0); if (n < 0 && !mg_is_error()) n = 0; return n; } static int mg_socket_if_udp_send(struct mg_connection *nc, const void *buf, size_t len) { int n = sendto(nc->sock, buf, len, 0, &nc->sa.sa, sizeof(nc->sa.sin)); if (n < 0 && !mg_is_error()) n = 0; return n; } static int mg_socket_if_tcp_recv(struct mg_connection *nc, void *buf, size_t len) { int n = (int) MG_RECV_FUNC(nc->sock, buf, len, 0); if (n == 0) { /* Orderly shutdown of the socket, try flushing output. */ nc->flags |= MG_F_SEND_AND_CLOSE; } else if (n < 0 && !mg_is_error()) { n = 0; } return n; } static int mg_socket_if_udp_recv(struct mg_connection *nc, void *buf, size_t len, union socket_address *sa, size_t *sa_len) { socklen_t sa_len_st = *sa_len; int n = recvfrom(nc->sock, buf, len, 0, &sa->sa, &sa_len_st); *sa_len = sa_len_st; if (n < 0 && !mg_is_error()) n = 0; return n; } int mg_socket_if_create_conn(struct mg_connection *nc) { (void) nc; return 1; } void mg_socket_if_destroy_conn(struct mg_connection *nc) { if (nc->sock == INVALID_SOCKET) return; if (!(nc->flags & MG_F_UDP)) { closesocket(nc->sock); } else { /* Only close outgoing UDP sockets or listeners. */ if (nc->listener == NULL) closesocket(nc->sock); } nc->sock = INVALID_SOCKET; } static int mg_accept_conn(struct mg_connection *lc) { struct mg_connection *nc; union socket_address sa; socklen_t sa_len = sizeof(sa); /* NOTE(lsm): on Windows, sock is always > FD_SETSIZE */ sock_t sock = accept(lc->sock, &sa.sa, &sa_len); if (sock == INVALID_SOCKET) { if (mg_is_error()) { DBG(("%p: failed to accept: %d", lc, mg_get_errno())); } return 0; } nc = mg_if_accept_new_conn(lc); if (nc == NULL) { closesocket(sock); return 0; } DBG(("%p conn from %s:%d", nc, inet_ntoa(sa.sin.sin_addr), ntohs(sa.sin.sin_port))); mg_sock_set(nc, sock); mg_if_accept_tcp_cb(nc, &sa, sa_len); return 1; } /* 'sa' must be an initialized address to bind to */ static sock_t mg_open_listening_socket(union socket_address *sa, int type, int proto) { socklen_t sa_len = (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6); sock_t sock = INVALID_SOCKET; #if !MG_LWIP int on = 1; #endif if ((sock = socket(sa->sa.sa_family, type, proto)) != INVALID_SOCKET && #if !MG_LWIP /* LWIP doesn't support either */ #if defined(_WIN32) && defined(SO_EXCLUSIVEADDRUSE) && !defined(WINCE) /* "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE" http://goo.gl/RmrFTm */ !setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (void *) &on, sizeof(on)) && #endif #if !defined(_WIN32) || !defined(SO_EXCLUSIVEADDRUSE) /* * SO_RESUSEADDR is not enabled on Windows because the semantics of * SO_REUSEADDR on UNIX and Windows is different. On Windows, * SO_REUSEADDR allows to bind a socket to a port without error even if * the port is already open by another program. This is not the behavior * SO_REUSEADDR was designed for, and leads to hard-to-track failure * scenarios. Therefore, SO_REUSEADDR was disabled on Windows unless * SO_EXCLUSIVEADDRUSE is supported and set on a socket. */ !setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof(on)) && #endif #endif /* !MG_LWIP */ !bind(sock, &sa->sa, sa_len) && (type == SOCK_DGRAM || listen(sock, SOMAXCONN) == 0)) { #if !MG_LWIP mg_set_non_blocking_mode(sock); /* In case port was set to 0, get the real port number */ (void) getsockname(sock, &sa->sa, &sa_len); #endif } else if (sock != INVALID_SOCKET) { closesocket(sock); sock = INVALID_SOCKET; } return sock; } #define _MG_F_FD_CAN_READ 1 #define _MG_F_FD_CAN_WRITE 1 << 1 #define _MG_F_FD_ERROR 1 << 2 void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) { int worth_logging = fd_flags != 0 || (nc->flags & (MG_F_WANT_READ | MG_F_WANT_WRITE)); if (worth_logging) { DBG(("%p fd=%d fd_flags=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->sock, fd_flags, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len)); } if (!mg_if_poll(nc, now)) return; if (nc->flags & MG_F_CONNECTING) { if (fd_flags != 0) { int err = 0; #if !defined(MG_ESP8266) if (!(nc->flags & MG_F_UDP)) { socklen_t len = sizeof(err); int ret = getsockopt(nc->sock, SOL_SOCKET, SO_ERROR, (char *) &err, &len); if (ret != 0) { err = 1; } else if (err == EAGAIN || err == EWOULDBLOCK) { err = 0; } } #else /* * On ESP8266 we use blocking connect. */ err = nc->err; #endif mg_if_connect_cb(nc, err); } else if (nc->err != 0) { mg_if_connect_cb(nc, nc->err); } } if (fd_flags & _MG_F_FD_CAN_READ) { if (nc->flags & MG_F_UDP) { mg_if_can_recv_cb(nc); } else { if (nc->flags & MG_F_LISTENING) { /* * We're not looping here, and accepting just one connection at * a time. The reason is that eCos does not respect non-blocking * flag on a listening socket and hangs in a loop. */ mg_accept_conn(nc); } else { mg_if_can_recv_cb(nc); } } } if (fd_flags & _MG_F_FD_CAN_WRITE) mg_if_can_send_cb(nc); if (worth_logging) { DBG(("%p after fd=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->sock, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len)); } } #if MG_ENABLE_BROADCAST static void mg_mgr_handle_ctl_sock(struct mg_mgr *mgr) { struct ctl_msg ctl_msg; int len = (int) MG_RECV_FUNC(mgr->ctl[1], (char *) &ctl_msg, sizeof(ctl_msg), 0); size_t dummy = MG_SEND_FUNC(mgr->ctl[1], ctl_msg.message, 1, 0); DBG(("read %d from ctl socket", len)); (void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */ if (len >= (int) sizeof(ctl_msg.callback) && ctl_msg.callback != NULL) { struct mg_connection *nc; for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) { ctl_msg.callback(nc, MG_EV_POLL, ctl_msg.message MG_UD_ARG(nc->user_data)); } } } #endif /* Associate a socket to a connection. */ void mg_socket_if_sock_set(struct mg_connection *nc, sock_t sock) { mg_set_non_blocking_mode(sock); mg_set_close_on_exec(sock); nc->sock = sock; DBG(("%p %d", nc, sock)); } void mg_socket_if_init(struct mg_iface *iface) { (void) iface; DBG(("%p using select()", iface->mgr)); #if MG_ENABLE_BROADCAST mg_socketpair(iface->mgr->ctl, SOCK_DGRAM); #endif } void mg_socket_if_free(struct mg_iface *iface) { (void) iface; } void mg_socket_if_add_conn(struct mg_connection *nc) { (void) nc; } void mg_socket_if_remove_conn(struct mg_connection *nc) { (void) nc; } void mg_add_to_set(sock_t sock, fd_set *set, sock_t *max_fd) { if (sock != INVALID_SOCKET #ifdef __unix__ && sock < (sock_t) FD_SETSIZE #endif ) { FD_SET(sock, set); if (*max_fd == INVALID_SOCKET || sock > *max_fd) { *max_fd = sock; } } } time_t mg_socket_if_poll(struct mg_iface *iface, int timeout_ms) { struct mg_mgr *mgr = iface->mgr; double now = mg_time(); double min_timer; struct mg_connection *nc, *tmp; struct timeval tv; fd_set read_set, write_set, err_set; sock_t max_fd = INVALID_SOCKET; int num_fds, num_ev, num_timers = 0; #ifdef __unix__ int try_dup = 1; #endif FD_ZERO(&read_set); FD_ZERO(&write_set); FD_ZERO(&err_set); #if MG_ENABLE_BROADCAST mg_add_to_set(mgr->ctl[1], &read_set, &max_fd); #endif /* * Note: it is ok to have connections with sock == INVALID_SOCKET in the list, * e.g. timer-only "connections". */ min_timer = 0; for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) { tmp = nc->next; if (nc->sock != INVALID_SOCKET) { num_fds++; #ifdef __unix__ /* A hack to make sure all our file descriptos fit into FD_SETSIZE. */ if (nc->sock >= (sock_t) FD_SETSIZE && try_dup) { int new_sock = dup(nc->sock); if (new_sock >= 0) { if (new_sock < (sock_t) FD_SETSIZE) { closesocket(nc->sock); DBG(("new sock %d -> %d", nc->sock, new_sock)); nc->sock = new_sock; } else { closesocket(new_sock); DBG(("new sock is still larger than FD_SETSIZE, disregard")); try_dup = 0; } } else { try_dup = 0; } } #endif if (nc->recv_mbuf.len < nc->recv_mbuf_limit && (!(nc->flags & MG_F_UDP) || nc->listener == NULL)) { mg_add_to_set(nc->sock, &read_set, &max_fd); } if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) || (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) { mg_add_to_set(nc->sock, &write_set, &max_fd); mg_add_to_set(nc->sock, &err_set, &max_fd); } } if (nc->ev_timer_time > 0) { if (num_timers == 0 || nc->ev_timer_time < min_timer) { min_timer = nc->ev_timer_time; } num_timers++; } } /* * If there is a timer to be fired earlier than the requested timeout, * adjust the timeout. */ if (num_timers > 0) { double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */; if (timer_timeout_ms < timeout_ms) { timeout_ms = (int) timer_timeout_ms; } } if (timeout_ms < 0) timeout_ms = 0; tv.tv_sec = timeout_ms / 1000; tv.tv_usec = (timeout_ms % 1000) * 1000; num_ev = select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv); now = mg_time(); #if 0 DBG(("select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev, num_fds, timeout_ms)); #endif #if MG_ENABLE_BROADCAST if (num_ev > 0 && mgr->ctl[1] != INVALID_SOCKET && FD_ISSET(mgr->ctl[1], &read_set)) { mg_mgr_handle_ctl_sock(mgr); } #endif for (nc = mgr->active_connections; nc != NULL; nc = tmp) { int fd_flags = 0; if (nc->sock != INVALID_SOCKET) { if (num_ev > 0) { fd_flags = (FD_ISSET(nc->sock, &read_set) && (!(nc->flags & MG_F_UDP) || nc->listener == NULL) ? _MG_F_FD_CAN_READ : 0) | (FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE : 0) | (FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0); } #if MG_LWIP /* With LWIP socket emulation layer, we don't get write events for UDP */ if ((nc->flags & MG_F_UDP) && nc->listener == NULL) { fd_flags |= _MG_F_FD_CAN_WRITE; } #endif } tmp = nc->next; mg_mgr_handle_conn(nc, fd_flags, now); } return (time_t) now; } #if MG_ENABLE_BROADCAST MG_INTERNAL void mg_socketpair_close(sock_t *sock) { while (1) { if (closesocket(*sock) == -1 && errno == EINTR) continue; break; } *sock = INVALID_SOCKET; } MG_INTERNAL sock_t mg_socketpair_accept(sock_t sock, union socket_address *sa, socklen_t sa_len) { sock_t rc; while (1) { if ((rc = accept(sock, &sa->sa, &sa_len)) == INVALID_SOCKET && errno == EINTR) continue; break; } return rc; } int mg_socketpair(sock_t sp[2], int sock_type) { union socket_address sa, sa2; sock_t sock; socklen_t len = sizeof(sa.sin); int ret = 0; sock = sp[0] = sp[1] = INVALID_SOCKET; (void) memset(&sa, 0, sizeof(sa)); sa.sin.sin_family = AF_INET; sa.sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */ sa2 = sa; if ((sock = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) { } else if (bind(sock, &sa.sa, len) != 0) { } else if (sock_type == SOCK_STREAM && listen(sock, 1) != 0) { } else if (getsockname(sock, &sa.sa, &len) != 0) { } else if ((sp[0] = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) { } else if (sock_type == SOCK_STREAM && connect(sp[0], &sa.sa, len) != 0) { } else if (sock_type == SOCK_DGRAM && (bind(sp[0], &sa2.sa, len) != 0 || getsockname(sp[0], &sa2.sa, &len) != 0 || connect(sp[0], &sa.sa, len) != 0 || connect(sock, &sa2.sa, len) != 0)) { } else if ((sp[1] = (sock_type == SOCK_DGRAM ? sock : mg_socketpair_accept( sock, &sa, len))) == INVALID_SOCKET) { } else { mg_set_close_on_exec(sp[0]); mg_set_close_on_exec(sp[1]); if (sock_type == SOCK_STREAM) mg_socketpair_close(&sock); ret = 1; } if (!ret) { if (sp[0] != INVALID_SOCKET) mg_socketpair_close(&sp[0]); if (sp[1] != INVALID_SOCKET) mg_socketpair_close(&sp[1]); if (sock != INVALID_SOCKET) mg_socketpair_close(&sock); } return ret; } #endif /* MG_ENABLE_BROADCAST */ static void mg_sock_get_addr(sock_t sock, int remote, union socket_address *sa) { socklen_t slen = sizeof(*sa); memset(sa, 0, slen); if (remote) { getpeername(sock, &sa->sa, &slen); } else { getsockname(sock, &sa->sa, &slen); } } void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags) { union socket_address sa; mg_sock_get_addr(sock, flags & MG_SOCK_STRINGIFY_REMOTE, &sa); mg_sock_addr_to_str(&sa, buf, len, flags); } void mg_socket_if_get_conn_addr(struct mg_connection *nc, int remote, union socket_address *sa) { if ((nc->flags & MG_F_UDP) && remote) { memcpy(sa, &nc->sa, sizeof(*sa)); return; } mg_sock_get_addr(nc->sock, remote, sa); } /* clang-format off */ #define MG_SOCKET_IFACE_VTABLE \ { \ mg_socket_if_init, \ mg_socket_if_free, \ mg_socket_if_add_conn, \ mg_socket_if_remove_conn, \ mg_socket_if_poll, \ mg_socket_if_listen_tcp, \ mg_socket_if_listen_udp, \ mg_socket_if_connect_tcp, \ mg_socket_if_connect_udp, \ mg_socket_if_tcp_send, \ mg_socket_if_udp_send, \ mg_socket_if_tcp_recv, \ mg_socket_if_udp_recv, \ mg_socket_if_create_conn, \ mg_socket_if_destroy_conn, \ mg_socket_if_sock_set, \ mg_socket_if_get_conn_addr, \ } /* clang-format on */ const struct mg_iface_vtable mg_socket_iface_vtable = MG_SOCKET_IFACE_VTABLE; #if MG_NET_IF == MG_NET_IF_SOCKET const struct mg_iface_vtable mg_default_iface_vtable = MG_SOCKET_IFACE_VTABLE; #endif #endif /* MG_ENABLE_NET_IF_SOCKET */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_net_if_socks.c" #endif /* * Copyright (c) 2014-2016 Cesanta Software Limited * All rights reserved */ #if MG_ENABLE_SOCKS struct socksdata { char *proxy_addr; /* HOST:PORT of the socks5 proxy server */ struct mg_connection *s; /* Respective connection to the server */ struct mg_connection *c; /* Connection to the client */ }; static void socks_if_disband(struct socksdata *d) { LOG(LL_DEBUG, ("disbanding proxy %p %p", d->c, d->s)); if (d->c) { d->c->flags |= MG_F_SEND_AND_CLOSE; d->c->user_data = NULL; d->c = NULL; } if (d->s) { d->s->flags |= MG_F_SEND_AND_CLOSE; d->s->user_data = NULL; d->s = NULL; } } static void socks_if_relay(struct mg_connection *s) { struct socksdata *d = (struct socksdata *) s->user_data; if (d == NULL || d->c == NULL || !(s->flags & MG_SOCKS_CONNECT_DONE) || d->s == NULL) { return; } if (s->recv_mbuf.len > 0) mg_if_can_recv_cb(d->c); if (d->c->send_mbuf.len > 0 && s->send_mbuf.len == 0) mg_if_can_send_cb(d->c); } static void socks_if_handler(struct mg_connection *c, int ev, void *ev_data) { struct socksdata *d = (struct socksdata *) c->user_data; if (d == NULL) return; if (ev == MG_EV_CONNECT) { int res = *(int *) ev_data; if (res == 0) { /* Send handshake to the proxy server */ unsigned char buf[] = {MG_SOCKS_VERSION, 1, MG_SOCKS_HANDSHAKE_NOAUTH}; mg_send(d->s, buf, sizeof(buf)); LOG(LL_DEBUG, ("Sent handshake to %s", d->proxy_addr)); } else { LOG(LL_ERROR, ("Cannot connect to %s: %d", d->proxy_addr, res)); d->c->flags |= MG_F_CLOSE_IMMEDIATELY; } } else if (ev == MG_EV_CLOSE) { socks_if_disband(d); } else if (ev == MG_EV_RECV) { /* Handle handshake reply */ if (!(c->flags & MG_SOCKS_HANDSHAKE_DONE)) { /* TODO(lsm): process IPv6 too */ unsigned char buf[10] = {MG_SOCKS_VERSION, MG_SOCKS_CMD_CONNECT, 0, MG_SOCKS_ADDR_IPV4}; if (c->recv_mbuf.len < 2) return; if ((unsigned char) c->recv_mbuf.buf[1] == MG_SOCKS_HANDSHAKE_FAILURE) { LOG(LL_ERROR, ("Server kicked us out")); socks_if_disband(d); return; } mbuf_remove(&c->recv_mbuf, 2); c->flags |= MG_SOCKS_HANDSHAKE_DONE; /* Send connect request */ memcpy(buf + 4, &d->c->sa.sin.sin_addr, 4); memcpy(buf + 8, &d->c->sa.sin.sin_port, 2); mg_send(c, buf, sizeof(buf)); LOG(LL_DEBUG, ("%p Sent connect request", c)); } /* Process connect request */ if ((c->flags & MG_SOCKS_HANDSHAKE_DONE) && !(c->flags & MG_SOCKS_CONNECT_DONE)) { if (c->recv_mbuf.len < 10) return; if (c->recv_mbuf.buf[1] != MG_SOCKS_SUCCESS) { LOG(LL_ERROR, ("Socks connection error: %d", c->recv_mbuf.buf[1])); socks_if_disband(d); return; } mbuf_remove(&c->recv_mbuf, 10); c->flags |= MG_SOCKS_CONNECT_DONE; LOG(LL_DEBUG, ("%p Connect done %p", c, d->c)); mg_if_connect_cb(d->c, 0); } socks_if_relay(c); } else if (ev == MG_EV_SEND || ev == MG_EV_POLL) { socks_if_relay(c); } } static void mg_socks_if_connect_tcp(struct mg_connection *c, const union socket_address *sa) { struct socksdata *d = (struct socksdata *) c->iface->data; d->c = c; d->s = mg_connect(c->mgr, d->proxy_addr, socks_if_handler); d->s->user_data = d; LOG(LL_DEBUG, ("%p %s %p %p", c, d->proxy_addr, d, d->s)); (void) sa; } static void mg_socks_if_connect_udp(struct mg_connection *c) { (void) c; } static int mg_socks_if_listen_tcp(struct mg_connection *c, union socket_address *sa) { (void) c; (void) sa; return 0; } static int mg_socks_if_listen_udp(struct mg_connection *c, union socket_address *sa) { (void) c; (void) sa; return -1; } static int mg_socks_if_tcp_send(struct mg_connection *c, const void *buf, size_t len) { int res; struct socksdata *d = (struct socksdata *) c->iface->data; if (d->s == NULL) return -1; res = (int) mbuf_append(&d->s->send_mbuf, buf, len); DBG(("%p -> %d -> %p", c, res, d->s)); return res; } static int mg_socks_if_udp_send(struct mg_connection *c, const void *buf, size_t len) { (void) c; (void) buf; (void) len; return -1; } int mg_socks_if_tcp_recv(struct mg_connection *c, void *buf, size_t len) { struct socksdata *d = (struct socksdata *) c->iface->data; if (d->s == NULL) return -1; if (len > d->s->recv_mbuf.len) len = d->s->recv_mbuf.len; if (len > 0) { memcpy(buf, d->s->recv_mbuf.buf, len); mbuf_remove(&d->s->recv_mbuf, len); } DBG(("%p <- %d <- %p", c, (int) len, d->s)); return len; } int mg_socks_if_udp_recv(struct mg_connection *c, void *buf, size_t len, union socket_address *sa, size_t *sa_len) { (void) c; (void) buf; (void) len; (void) sa; (void) sa_len; return -1; } static int mg_socks_if_create_conn(struct mg_connection *c) { (void) c; return 1; } static void mg_socks_if_destroy_conn(struct mg_connection *c) { c->iface->vtable->free(c->iface); MG_FREE(c->iface); c->iface = NULL; LOG(LL_DEBUG, ("%p", c)); } static void mg_socks_if_sock_set(struct mg_connection *c, sock_t sock) { (void) c; (void) sock; } static void mg_socks_if_init(struct mg_iface *iface) { (void) iface; } static void mg_socks_if_free(struct mg_iface *iface) { struct socksdata *d = (struct socksdata *) iface->data; LOG(LL_DEBUG, ("%p", iface)); if (d != NULL) { socks_if_disband(d); MG_FREE(d->proxy_addr); MG_FREE(d); iface->data = NULL; } } static void mg_socks_if_add_conn(struct mg_connection *c) { c->sock = INVALID_SOCKET; } static void mg_socks_if_remove_conn(struct mg_connection *c) { (void) c; } static time_t mg_socks_if_poll(struct mg_iface *iface, int timeout_ms) { LOG(LL_DEBUG, ("%p", iface)); (void) iface; (void) timeout_ms; return (time_t) cs_time(); } static void mg_socks_if_get_conn_addr(struct mg_connection *c, int remote, union socket_address *sa) { LOG(LL_DEBUG, ("%p", c)); (void) c; (void) remote; (void) sa; } const struct mg_iface_vtable mg_socks_iface_vtable = { mg_socks_if_init, mg_socks_if_free, mg_socks_if_add_conn, mg_socks_if_remove_conn, mg_socks_if_poll, mg_socks_if_listen_tcp, mg_socks_if_listen_udp, mg_socks_if_connect_tcp, mg_socks_if_connect_udp, mg_socks_if_tcp_send, mg_socks_if_udp_send, mg_socks_if_tcp_recv, mg_socks_if_udp_recv, mg_socks_if_create_conn, mg_socks_if_destroy_conn, mg_socks_if_sock_set, mg_socks_if_get_conn_addr, }; struct mg_iface *mg_socks_mk_iface(struct mg_mgr *mgr, const char *proxy_addr) { struct mg_iface *iface = mg_if_create_iface(&mg_socks_iface_vtable, mgr); iface->data = MG_CALLOC(1, sizeof(struct socksdata)); ((struct socksdata *) iface->data)->proxy_addr = strdup(proxy_addr); return iface; } #endif #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_ssl_if_openssl.c" #endif /* * Copyright (c) 2014-2016 Cesanta Software Limited * All rights reserved */ #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_OPENSSL #ifdef __APPLE__ #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif #include <openssl/ssl.h> #ifndef KR_VERSION #include <openssl/tls1.h> #endif struct mg_ssl_if_ctx { SSL *ssl; SSL_CTX *ssl_ctx; struct mbuf psk; size_t identity_len; }; void mg_ssl_if_init() { SSL_library_init(); } enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc, struct mg_connection *lc) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx)); struct mg_ssl_if_ctx *lc_ctx = (struct mg_ssl_if_ctx *) lc->ssl_if_data; nc->ssl_if_data = ctx; if (ctx == NULL || lc_ctx == NULL) return MG_SSL_ERROR; ctx->ssl_ctx = lc_ctx->ssl_ctx; if ((ctx->ssl = SSL_new(ctx->ssl_ctx)) == NULL) { return MG_SSL_ERROR; } return MG_SSL_OK; } static enum mg_ssl_if_result mg_use_cert(SSL_CTX *ctx, const char *cert, const char *key, const char **err_msg); static enum mg_ssl_if_result mg_use_ca_cert(SSL_CTX *ctx, const char *cert); static enum mg_ssl_if_result mg_set_cipher_list(SSL_CTX *ctx, const char *cl); static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx, const char *identity, const char *key_str); enum mg_ssl_if_result mg_ssl_if_conn_init( struct mg_connection *nc, const struct mg_ssl_if_conn_params *params, const char **err_msg) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx)); DBG(("%p %s,%s,%s", nc, (params->cert ? params->cert : ""), (params->key ? params->key : ""), (params->ca_cert ? params->ca_cert : ""))); if (ctx == NULL) { MG_SET_PTRPTR(err_msg, "Out of memory"); return MG_SSL_ERROR; } nc->ssl_if_data = ctx; if (nc->flags & MG_F_LISTENING) { ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method()); } else { ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()); } if (ctx->ssl_ctx == NULL) { MG_SET_PTRPTR(err_msg, "Failed to create SSL context"); return MG_SSL_ERROR; } #ifndef KR_VERSION /* Disable deprecated protocols. */ SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_SSLv2); SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_SSLv3); SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_TLSv1); #ifdef MG_SSL_OPENSSL_NO_COMPRESSION SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_COMPRESSION); #endif #ifdef MG_SSL_OPENSSL_CIPHER_SERVER_PREFERENCE SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE); #endif #else /* Krypton only supports TLSv1.2 anyway. */ #endif if (params->cert != NULL && mg_use_cert(ctx->ssl_ctx, params->cert, params->key, err_msg) != MG_SSL_OK) { return MG_SSL_ERROR; } if (params->ca_cert != NULL && mg_use_ca_cert(ctx->ssl_ctx, params->ca_cert) != MG_SSL_OK) { MG_SET_PTRPTR(err_msg, "Invalid SSL CA cert"); return MG_SSL_ERROR; } if (mg_set_cipher_list(ctx->ssl_ctx, params->cipher_suites) != MG_SSL_OK) { MG_SET_PTRPTR(err_msg, "Invalid cipher suite list"); return MG_SSL_ERROR; } mbuf_init(&ctx->psk, 0); if (mg_ssl_if_ossl_set_psk(ctx, params->psk_identity, params->psk_key) != MG_SSL_OK) { MG_SET_PTRPTR(err_msg, "Invalid PSK settings"); return MG_SSL_ERROR; } if (!(nc->flags & MG_F_LISTENING) && (ctx->ssl = SSL_new(ctx->ssl_ctx)) == NULL) { MG_SET_PTRPTR(err_msg, "Failed to create SSL session"); return MG_SSL_ERROR; } if (params->server_name != NULL) { #ifdef KR_VERSION SSL_CTX_kr_set_verify_name(ctx->ssl_ctx, params->server_name); #else SSL_set_tlsext_host_name(ctx->ssl, params->server_name); #endif } nc->flags |= MG_F_SSL; return MG_SSL_OK; } static enum mg_ssl_if_result mg_ssl_if_ssl_err(struct mg_connection *nc, int res) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; int err = SSL_get_error(ctx->ssl, res); if (err == SSL_ERROR_WANT_READ) return MG_SSL_WANT_READ; if (err == SSL_ERROR_WANT_WRITE) return MG_SSL_WANT_WRITE; DBG(("%p %p SSL error: %d %d", nc, ctx->ssl_ctx, res, err)); nc->err = err; return MG_SSL_ERROR; } enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; int server_side = (nc->listener != NULL); int res; /* If descriptor is not yet set, do it now. */ if (SSL_get_fd(ctx->ssl) < 0) { if (SSL_set_fd(ctx->ssl, nc->sock) != 1) return MG_SSL_ERROR; } res = server_side ? SSL_accept(ctx->ssl) : SSL_connect(ctx->ssl); if (res != 1) return mg_ssl_if_ssl_err(nc, res); return MG_SSL_OK; } int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t buf_size) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; int n = SSL_read(ctx->ssl, buf, buf_size); DBG(("%p %d -> %d", nc, (int) buf_size, n)); if (n < 0) return mg_ssl_if_ssl_err(nc, n); if (n == 0) nc->flags |= MG_F_CLOSE_IMMEDIATELY; return n; } int mg_ssl_if_write(struct mg_connection *nc, const void *data, size_t len) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; int n = SSL_write(ctx->ssl, data, len); DBG(("%p %d -> %d", nc, (int) len, n)); if (n <= 0) return mg_ssl_if_ssl_err(nc, n); return n; } void mg_ssl_if_conn_close_notify(struct mg_connection *nc) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; if (ctx == NULL) return; SSL_shutdown(ctx->ssl); } void mg_ssl_if_conn_free(struct mg_connection *nc) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; if (ctx == NULL) return; nc->ssl_if_data = NULL; if (ctx->ssl != NULL) SSL_free(ctx->ssl); if (ctx->ssl_ctx != NULL && nc->listener == NULL) SSL_CTX_free(ctx->ssl_ctx); mbuf_free(&ctx->psk); memset(ctx, 0, sizeof(*ctx)); MG_FREE(ctx); } /* * Cipher suite options used for TLS negotiation. * https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_configurations */ static const char mg_s_cipher_list[] = #if defined(MG_SSL_CRYPTO_MODERN) "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:" "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:" "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:" "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:" "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:" "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:" "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:" "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:" "!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK" #elif defined(MG_SSL_CRYPTO_OLD) "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:" "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:" "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:" "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:" "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:" "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:" "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:" "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:" "ECDHE-ECDSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:" "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:DES-CBC3-SHA:" "HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:" "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA" #else /* Default - intermediate. */ "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:" "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:" "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:" "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:" "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:" "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:" "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:" "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:" "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:" "DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:" "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA" #endif ; /* * Default DH params for PFS cipher negotiation. This is a 2048-bit group. * Will be used if none are provided by the user in the certificate file. */ #if !MG_DISABLE_PFS && !defined(KR_VERSION) static const char mg_s_default_dh_params[] = "\ -----BEGIN DH PARAMETERS-----\n\ MIIBCAKCAQEAlvbgD/qh9znWIlGFcV0zdltD7rq8FeShIqIhkQ0C7hYFThrBvF2E\n\ Z9bmgaP+sfQwGpVlv9mtaWjvERbu6mEG7JTkgmVUJrUt/wiRzwTaCXBqZkdUO8Tq\n\ +E6VOEQAilstG90ikN1Tfo+K6+X68XkRUIlgawBTKuvKVwBhuvlqTGerOtnXWnrt\n\ ym//hd3cd5PBYGBix0i7oR4xdghvfR2WLVu0LgdThTBb6XP7gLd19cQ1JuBtAajZ\n\ wMuPn7qlUkEFDIkAZy59/Hue/H2Q2vU/JsvVhHWCQBL4F1ofEAt50il6ZxR1QfFK\n\ 9VGKDC4oOgm9DlxwwBoC2FjqmvQlqVV3kwIBAg==\n\ -----END DH PARAMETERS-----\n"; #endif static enum mg_ssl_if_result mg_use_ca_cert(SSL_CTX *ctx, const char *cert) { if (cert == NULL || strcmp(cert, "*") == 0) { return MG_SSL_OK; } SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0); return SSL_CTX_load_verify_locations(ctx, cert, NULL) == 1 ? MG_SSL_OK : MG_SSL_ERROR; } static enum mg_ssl_if_result mg_use_cert(SSL_CTX *ctx, const char *cert, const char *key, const char **err_msg) { if (key == NULL) key = cert; if (cert == NULL || cert[0] == '\0' || key == NULL || key[0] == '\0') { return MG_SSL_OK; } else if (SSL_CTX_use_certificate_file(ctx, cert, 1) == 0) { MG_SET_PTRPTR(err_msg, "Invalid SSL cert"); return MG_SSL_ERROR; } else if (SSL_CTX_use_PrivateKey_file(ctx, key, 1) == 0) { MG_SET_PTRPTR(err_msg, "Invalid SSL key"); return MG_SSL_ERROR; } else if (SSL_CTX_use_certificate_chain_file(ctx, cert) == 0) { MG_SET_PTRPTR(err_msg, "Invalid CA bundle"); return MG_SSL_ERROR; } else { SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); #if !MG_DISABLE_PFS && !defined(KR_VERSION) BIO *bio = NULL; DH *dh = NULL; /* Try to read DH parameters from the cert/key file. */ bio = BIO_new_file(cert, "r"); if (bio != NULL) { dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL); BIO_free(bio); } /* * If there are no DH params in the file, fall back to hard-coded ones. * Not ideal, but better than nothing. */ if (dh == NULL) { bio = BIO_new_mem_buf((void *) mg_s_default_dh_params, -1); dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL); BIO_free(bio); } if (dh != NULL) { SSL_CTX_set_tmp_dh(ctx, dh); SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE); DH_free(dh); } #if OPENSSL_VERSION_NUMBER > 0x10002000L SSL_CTX_set_ecdh_auto(ctx, 1); #endif #endif } return MG_SSL_OK; } static enum mg_ssl_if_result mg_set_cipher_list(SSL_CTX *ctx, const char *cl) { return (SSL_CTX_set_cipher_list(ctx, cl ? cl : mg_s_cipher_list) == 1 ? MG_SSL_OK : MG_SSL_ERROR); } #if !defined(KR_VERSION) && !defined(LIBRESSL_VERSION_NUMBER) static unsigned int mg_ssl_if_ossl_psk_cb(SSL *ssl, const char *hint, char *identity, unsigned int max_identity_len, unsigned char *psk, unsigned int max_psk_len) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)); size_t key_len = ctx->psk.len - ctx->identity_len - 1; DBG(("hint: '%s'", (hint ? hint : ""))); if (ctx->identity_len + 1 > max_identity_len) { DBG(("identity too long")); return 0; } if (key_len > max_psk_len) { DBG(("key too long")); return 0; } memcpy(identity, ctx->psk.buf, ctx->identity_len + 1); memcpy(psk, ctx->psk.buf + ctx->identity_len + 1, key_len); (void) ssl; return key_len; } static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx, const char *identity, const char *key_str) { unsigned char key[32]; size_t key_len; size_t i = 0; if (identity == NULL && key_str == NULL) return MG_SSL_OK; if (identity == NULL || key_str == NULL) return MG_SSL_ERROR; key_len = strlen(key_str); if (key_len != 32 && key_len != 64) return MG_SSL_ERROR; memset(key, 0, sizeof(key)); key_len = 0; for (i = 0; key_str[i] != '\0'; i++) { unsigned char c; char hc = tolower((int) key_str[i]); if (hc >= '0' && hc <= '9') { c = hc - '0'; } else if (hc >= 'a' && hc <= 'f') { c = hc - 'a' + 0xa; } else { return MG_SSL_ERROR; } key_len = i / 2; key[key_len] <<= 4; key[key_len] |= c; } key_len++; DBG(("identity = '%s', key = (%u)", identity, (unsigned int) key_len)); ctx->identity_len = strlen(identity); mbuf_append(&ctx->psk, identity, ctx->identity_len + 1); mbuf_append(&ctx->psk, key, key_len); SSL_CTX_set_psk_client_callback(ctx->ssl_ctx, mg_ssl_if_ossl_psk_cb); SSL_CTX_set_app_data(ctx->ssl_ctx, ctx); return MG_SSL_OK; } #else static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx, const char *identity, const char *key_str) { (void) ctx; (void) identity; (void) key_str; /* Krypton / LibreSSL does not support PSK. */ return MG_SSL_ERROR; } #endif /* !defined(KR_VERSION) && !defined(LIBRESSL_VERSION_NUMBER) */ const char *mg_set_ssl(struct mg_connection *nc, const char *cert, const char *ca_cert) { const char *err_msg = NULL; struct mg_ssl_if_conn_params params; memset(&params, 0, sizeof(params)); params.cert = cert; params.ca_cert = ca_cert; if (mg_ssl_if_conn_init(nc, &params, &err_msg) != MG_SSL_OK) { return err_msg; } return NULL; } #endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_OPENSSL */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_ssl_if_mbedtls.c" #endif /* * Copyright (c) 2014-2016 Cesanta Software Limited * All rights reserved */ #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_MBEDTLS #include <mbedtls/debug.h> #include <mbedtls/ecp.h> #include <mbedtls/net.h> #include <mbedtls/platform.h> #include <mbedtls/ssl.h> #include <mbedtls/ssl_internal.h> #include <mbedtls/x509_crt.h> #include <mbedtls/version.h> static void mg_ssl_mbed_log(void *ctx, int level, const char *file, int line, const char *str) { enum cs_log_level cs_level; switch (level) { case 1: cs_level = LL_ERROR; break; case 2: cs_level = LL_INFO; break; case 3: cs_level = LL_DEBUG; break; default: cs_level = LL_VERBOSE_DEBUG; } /* mbedTLS passes strings with \n at the end, strip it. */ LOG(cs_level, ("%p %.*s", ctx, (int) (strlen(str) - 1), str)); (void) ctx; (void) str; (void) file; (void) line; (void) cs_level; } struct mg_ssl_if_ctx { mbedtls_ssl_config *conf; mbedtls_ssl_context *ssl; mbedtls_x509_crt *cert; mbedtls_pk_context *key; mbedtls_x509_crt *ca_cert; struct mbuf cipher_suites; size_t saved_len; }; /* Must be provided by the platform. ctx is struct mg_connection. */ extern int mg_ssl_if_mbed_random(void *ctx, unsigned char *buf, size_t len); void mg_ssl_if_init() { LOG(LL_INFO, ("%s", MBEDTLS_VERSION_STRING_FULL)); } enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc, struct mg_connection *lc) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx)); struct mg_ssl_if_ctx *lc_ctx = (struct mg_ssl_if_ctx *) lc->ssl_if_data; nc->ssl_if_data = ctx; if (ctx == NULL || lc_ctx == NULL) return MG_SSL_ERROR; ctx->ssl = (mbedtls_ssl_context *) MG_CALLOC(1, sizeof(*ctx->ssl)); if (mbedtls_ssl_setup(ctx->ssl, lc_ctx->conf) != 0) { return MG_SSL_ERROR; } return MG_SSL_OK; } static enum mg_ssl_if_result mg_use_cert(struct mg_ssl_if_ctx *ctx, const char *cert, const char *key, const char **err_msg); static enum mg_ssl_if_result mg_use_ca_cert(struct mg_ssl_if_ctx *ctx, const char *cert); static enum mg_ssl_if_result mg_set_cipher_list(struct mg_ssl_if_ctx *ctx, const char *ciphers); #ifdef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED static enum mg_ssl_if_result mg_ssl_if_mbed_set_psk(struct mg_ssl_if_ctx *ctx, const char *identity, const char *key); #endif enum mg_ssl_if_result mg_ssl_if_conn_init( struct mg_connection *nc, const struct mg_ssl_if_conn_params *params, const char **err_msg) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx)); DBG(("%p %s,%s,%s", nc, (params->cert ? params->cert : ""), (params->key ? params->key : ""), (params->ca_cert ? params->ca_cert : ""))); if (ctx == NULL) { MG_SET_PTRPTR(err_msg, "Out of memory"); return MG_SSL_ERROR; } nc->ssl_if_data = ctx; ctx->conf = (mbedtls_ssl_config *) MG_CALLOC(1, sizeof(*ctx->conf)); mbuf_init(&ctx->cipher_suites, 0); mbedtls_ssl_config_init(ctx->conf); mbedtls_ssl_conf_dbg(ctx->conf, mg_ssl_mbed_log, nc); if (mbedtls_ssl_config_defaults( ctx->conf, (nc->flags & MG_F_LISTENING ? MBEDTLS_SSL_IS_SERVER : MBEDTLS_SSL_IS_CLIENT), MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT) != 0) { MG_SET_PTRPTR(err_msg, "Failed to init SSL config"); return MG_SSL_ERROR; } /* TLS 1.2 and up */ mbedtls_ssl_conf_min_version(ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3); mbedtls_ssl_conf_rng(ctx->conf, mg_ssl_if_mbed_random, nc); if (params->cert != NULL && mg_use_cert(ctx, params->cert, params->key, err_msg) != MG_SSL_OK) { return MG_SSL_ERROR; } if (params->ca_cert != NULL && mg_use_ca_cert(ctx, params->ca_cert) != MG_SSL_OK) { MG_SET_PTRPTR(err_msg, "Invalid SSL CA cert"); return MG_SSL_ERROR; } if (mg_set_cipher_list(ctx, params->cipher_suites) != MG_SSL_OK) { MG_SET_PTRPTR(err_msg, "Invalid cipher suite list"); return MG_SSL_ERROR; } #ifdef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED if (mg_ssl_if_mbed_set_psk(ctx, params->psk_identity, params->psk_key) != MG_SSL_OK) { MG_SET_PTRPTR(err_msg, "Invalid PSK settings"); return MG_SSL_ERROR; } #endif if (!(nc->flags & MG_F_LISTENING)) { ctx->ssl = (mbedtls_ssl_context *) MG_CALLOC(1, sizeof(*ctx->ssl)); mbedtls_ssl_init(ctx->ssl); if (mbedtls_ssl_setup(ctx->ssl, ctx->conf) != 0) { MG_SET_PTRPTR(err_msg, "Failed to create SSL session"); return MG_SSL_ERROR; } if (params->server_name != NULL && mbedtls_ssl_set_hostname(ctx->ssl, params->server_name) != 0) { return MG_SSL_ERROR; } } #ifdef MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN if (mbedtls_ssl_conf_max_frag_len(ctx->conf, #if MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 512 MBEDTLS_SSL_MAX_FRAG_LEN_512 #elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 1024 MBEDTLS_SSL_MAX_FRAG_LEN_1024 #elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 2048 MBEDTLS_SSL_MAX_FRAG_LEN_2048 #elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 4096 MBEDTLS_SSL_MAX_FRAG_LEN_4096 #else #error Invalid MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN #endif ) != 0) { return MG_SSL_ERROR; } #endif nc->flags |= MG_F_SSL; return MG_SSL_OK; } static int mg_ssl_if_mbed_send(void *ctx, const unsigned char *buf, size_t len) { struct mg_connection *nc = (struct mg_connection *) ctx; int n = nc->iface->vtable->tcp_send(nc, buf, len); if (n > 0) return n; if (n == 0) return MBEDTLS_ERR_SSL_WANT_WRITE; return MBEDTLS_ERR_NET_SEND_FAILED; } static int mg_ssl_if_mbed_recv(void *ctx, unsigned char *buf, size_t len) { struct mg_connection *nc = (struct mg_connection *) ctx; int n = nc->iface->vtable->tcp_recv(nc, buf, len); if (n > 0) return n; if (n == 0) return MBEDTLS_ERR_SSL_WANT_READ; return MBEDTLS_ERR_NET_RECV_FAILED; } static enum mg_ssl_if_result mg_ssl_if_mbed_err(struct mg_connection *nc, int ret) { enum mg_ssl_if_result res = MG_SSL_OK; if (ret == MBEDTLS_ERR_SSL_WANT_READ) { res = MG_SSL_WANT_READ; } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { res = MG_SSL_WANT_WRITE; } else if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { LOG(LL_DEBUG, ("%p TLS connection closed by peer", nc)); nc->flags |= MG_F_CLOSE_IMMEDIATELY; res = MG_SSL_OK; } else { LOG(LL_ERROR, ("%p mbedTLS error: -0x%04x", nc, -ret)); nc->flags |= MG_F_CLOSE_IMMEDIATELY; res = MG_SSL_ERROR; } nc->err = ret; return res; } static void mg_ssl_if_mbed_free_certs_and_keys(struct mg_ssl_if_ctx *ctx) { if (ctx->cert != NULL) { mbedtls_x509_crt_free(ctx->cert); MG_FREE(ctx->cert); ctx->cert = NULL; mbedtls_pk_free(ctx->key); MG_FREE(ctx->key); ctx->key = NULL; } if (ctx->ca_cert != NULL) { mbedtls_ssl_conf_ca_chain(ctx->conf, NULL, NULL); #ifdef MBEDTLS_X509_CA_CHAIN_ON_DISK if (ctx->conf->ca_chain_file != NULL) { MG_FREE((void *) ctx->conf->ca_chain_file); ctx->conf->ca_chain_file = NULL; } #endif mbedtls_x509_crt_free(ctx->ca_cert); MG_FREE(ctx->ca_cert); ctx->ca_cert = NULL; } } enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; int err; /* If bio is not yet set, do it now. */ if (ctx->ssl->p_bio == NULL) { mbedtls_ssl_set_bio(ctx->ssl, nc, mg_ssl_if_mbed_send, mg_ssl_if_mbed_recv, NULL); } err = mbedtls_ssl_handshake(ctx->ssl); if (err != 0) return mg_ssl_if_mbed_err(nc, err); #ifdef MG_SSL_IF_MBEDTLS_FREE_CERTS /* * Free the peer certificate, we don't need it after handshake. * Note that this effectively disables renegotiation. */ mbedtls_x509_crt_free(ctx->ssl->session->peer_cert); mbedtls_free(ctx->ssl->session->peer_cert); ctx->ssl->session->peer_cert = NULL; /* On a client connection we can also free our own and CA certs. */ if (nc->listener == NULL) { if (ctx->conf->key_cert != NULL) { /* Note that this assumes one key_cert entry, which matches our init. */ MG_FREE(ctx->conf->key_cert); ctx->conf->key_cert = NULL; } mbedtls_ssl_conf_ca_chain(ctx->conf, NULL, NULL); mg_ssl_if_mbed_free_certs_and_keys(ctx); } #endif return MG_SSL_OK; } int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t len) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; int n = mbedtls_ssl_read(ctx->ssl, (unsigned char *) buf, len); DBG(("%p %d -> %d", nc, (int) len, n)); if (n < 0) return mg_ssl_if_mbed_err(nc, n); if (n == 0) nc->flags |= MG_F_CLOSE_IMMEDIATELY; return n; } int mg_ssl_if_write(struct mg_connection *nc, const void *buf, size_t len) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; /* Per mbedTLS docs, if write returns WANT_READ or WANT_WRITE, the operation * should be retried with the same data and length. * Here we assume that the data being pushed will remain the same but the * amount may grow between calls so we save the length that was used and * retry. The assumption being that the data itself won't change and won't * be removed. */ size_t l = len; if (ctx->saved_len > 0 && ctx->saved_len < l) l = ctx->saved_len; int n = mbedtls_ssl_write(ctx->ssl, (const unsigned char *) buf, l); DBG(("%p %d,%d,%d -> %d", nc, (int) len, (int) ctx->saved_len, (int) l, n)); if (n < 0) { if (n == MBEDTLS_ERR_SSL_WANT_READ || n == MBEDTLS_ERR_SSL_WANT_WRITE) { ctx->saved_len = len; } return mg_ssl_if_mbed_err(nc, n); } else if (n > 0) { ctx->saved_len = 0; } return n; } void mg_ssl_if_conn_close_notify(struct mg_connection *nc) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; if (ctx == NULL) return; mbedtls_ssl_close_notify(ctx->ssl); } void mg_ssl_if_conn_free(struct mg_connection *nc) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; if (ctx == NULL) return; nc->ssl_if_data = NULL; if (ctx->ssl != NULL) { mbedtls_ssl_free(ctx->ssl); MG_FREE(ctx->ssl); } mg_ssl_if_mbed_free_certs_and_keys(ctx); if (ctx->conf != NULL) { mbedtls_ssl_config_free(ctx->conf); MG_FREE(ctx->conf); } mbuf_free(&ctx->cipher_suites); memset(ctx, 0, sizeof(*ctx)); MG_FREE(ctx); } static enum mg_ssl_if_result mg_use_ca_cert(struct mg_ssl_if_ctx *ctx, const char *ca_cert) { if (ca_cert == NULL || strcmp(ca_cert, "*") == 0) { mbedtls_ssl_conf_authmode(ctx->conf, MBEDTLS_SSL_VERIFY_NONE); return MG_SSL_OK; } ctx->ca_cert = (mbedtls_x509_crt *) MG_CALLOC(1, sizeof(*ctx->ca_cert)); mbedtls_x509_crt_init(ctx->ca_cert); #ifdef MBEDTLS_X509_CA_CHAIN_ON_DISK ca_cert = strdup(ca_cert); mbedtls_ssl_conf_ca_chain_file(ctx->conf, ca_cert, NULL); #else if (mbedtls_x509_crt_parse_file(ctx->ca_cert, ca_cert) != 0) { return MG_SSL_ERROR; } mbedtls_ssl_conf_ca_chain(ctx->conf, ctx->ca_cert, NULL); #endif mbedtls_ssl_conf_authmode(ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED); return MG_SSL_OK; } static enum mg_ssl_if_result mg_use_cert(struct mg_ssl_if_ctx *ctx, const char *cert, const char *key, const char **err_msg) { if (key == NULL) key = cert; if (cert == NULL || cert[0] == '\0' || key == NULL || key[0] == '\0') { return MG_SSL_OK; } ctx->cert = (mbedtls_x509_crt *) MG_CALLOC(1, sizeof(*ctx->cert)); mbedtls_x509_crt_init(ctx->cert); ctx->key = (mbedtls_pk_context *) MG_CALLOC(1, sizeof(*ctx->key)); mbedtls_pk_init(ctx->key); if (mbedtls_x509_crt_parse_file(ctx->cert, cert) != 0) { MG_SET_PTRPTR(err_msg, "Invalid SSL cert"); return MG_SSL_ERROR; } if (mbedtls_pk_parse_keyfile(ctx->key, key, NULL) != 0) { MG_SET_PTRPTR(err_msg, "Invalid SSL key"); return MG_SSL_ERROR; } if (mbedtls_ssl_conf_own_cert(ctx->conf, ctx->cert, ctx->key) != 0) { MG_SET_PTRPTR(err_msg, "Invalid SSL key or cert"); return MG_SSL_ERROR; } return MG_SSL_OK; } static const int mg_s_cipher_list[] = { #if CS_PLATFORM != CS_P_ESP8266 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA, #else /* * ECDHE is way too slow on ESP8266 w/o cryptochip, this sometimes results * in WiFi STA deauths. Use weaker but faster cipher suites. Sad but true. * Disable DHE completely because it's just hopelessly slow. */ MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA, #endif /* CS_PLATFORM != CS_P_ESP8266 */ 0, }; /* * Ciphers can be specified as a colon-separated list of cipher suite names. * These can be found in * https://github.com/ARMmbed/mbedtls/blob/development/library/ssl_ciphersuites.c#L267 * E.g.: TLS-ECDHE-ECDSA-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-256-CCM */ static enum mg_ssl_if_result mg_set_cipher_list(struct mg_ssl_if_ctx *ctx, const char *ciphers) { if (ciphers != NULL) { int l, id; const char *s = ciphers, *e; char tmp[50]; while (s != NULL) { e = strchr(s, ':'); l = (e != NULL ? (e - s) : (int) strlen(s)); strncpy(tmp, s, l); tmp[l] = '\0'; id = mbedtls_ssl_get_ciphersuite_id(tmp); DBG(("%s -> %04x", tmp, id)); if (id != 0) { mbuf_append(&ctx->cipher_suites, &id, sizeof(id)); } s = (e != NULL ? e + 1 : NULL); } if (ctx->cipher_suites.len == 0) return MG_SSL_ERROR; id = 0; mbuf_append(&ctx->cipher_suites, &id, sizeof(id)); mbuf_trim(&ctx->cipher_suites); mbedtls_ssl_conf_ciphersuites(ctx->conf, (const int *) ctx->cipher_suites.buf); } else { mbedtls_ssl_conf_ciphersuites(ctx->conf, mg_s_cipher_list); } return MG_SSL_OK; } #ifdef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED static enum mg_ssl_if_result mg_ssl_if_mbed_set_psk(struct mg_ssl_if_ctx *ctx, const char *identity, const char *key_str) { unsigned char key[32]; size_t key_len; if (identity == NULL && key_str == NULL) return MG_SSL_OK; if (identity == NULL || key_str == NULL) return MG_SSL_ERROR; key_len = strlen(key_str); if (key_len != 32 && key_len != 64) return MG_SSL_ERROR; size_t i = 0; memset(key, 0, sizeof(key)); key_len = 0; for (i = 0; key_str[i] != '\0'; i++) { unsigned char c; char hc = tolower((int) key_str[i]); if (hc >= '0' && hc <= '9') { c = hc - '0'; } else if (hc >= 'a' && hc <= 'f') { c = hc - 'a' + 0xa; } else { return MG_SSL_ERROR; } key_len = i / 2; key[key_len] <<= 4; key[key_len] |= c; } key_len++; DBG(("identity = '%s', key = (%u)", identity, (unsigned int) key_len)); /* mbedTLS makes copies of psk and identity. */ if (mbedtls_ssl_conf_psk(ctx->conf, (const unsigned char *) key, key_len, (const unsigned char *) identity, strlen(identity)) != 0) { return MG_SSL_ERROR; } return MG_SSL_OK; } #endif const char *mg_set_ssl(struct mg_connection *nc, const char *cert, const char *ca_cert) { const char *err_msg = NULL; struct mg_ssl_if_conn_params params; memset(&params, 0, sizeof(params)); params.cert = cert; params.ca_cert = ca_cert; if (mg_ssl_if_conn_init(nc, &params, &err_msg) != MG_SSL_OK) { return err_msg; } return NULL; } /* Lazy RNG. Warning: it would be a bad idea to do this in production! */ #ifdef MG_SSL_MBED_DUMMY_RANDOM int mg_ssl_if_mbed_random(void *ctx, unsigned char *buf, size_t len) { (void) ctx; while (len--) *buf++ = rand(); return 0; } #endif #endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_MBEDTLS */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_uri.c" #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ /* Amalgamated: #include "mg_internal.h" */ /* Amalgamated: #include "mg_uri.h" */ /* * scan string until encountering one of `seps`, keeping track of component * boundaries in `res`. * * `p` will point to the char after the separator or it will be `end`. */ static void parse_uri_component(const char **p, const char *end, const char *seps, struct mg_str *res) { const char *q; res->p = *p; for (; *p < end; (*p)++) { for (q = seps; *q != '\0'; q++) { if (**p == *q) break; } if (*q != '\0') break; } res->len = (*p) - res->p; if (*p < end) (*p)++; } int mg_parse_uri(const struct mg_str uri, struct mg_str *scheme, struct mg_str *user_info, struct mg_str *host, unsigned int *port, struct mg_str *path, struct mg_str *query, struct mg_str *fragment) { struct mg_str rscheme = {0, 0}, ruser_info = {0, 0}, rhost = {0, 0}, rpath = {0, 0}, rquery = {0, 0}, rfragment = {0, 0}; unsigned int rport = 0; enum { P_START, P_SCHEME_OR_PORT, P_USER_INFO, P_HOST, P_PORT, P_REST } state = P_START; const char *p = uri.p, *end = p + uri.len; while (p < end) { switch (state) { case P_START: /* * expecting on of: * - `scheme://xxxx` * - `xxxx:port` * - `[a:b:c]:port` * - `xxxx/path` */ if (*p == '[') { state = P_HOST; break; } for (; p < end; p++) { if (*p == ':') { state = P_SCHEME_OR_PORT; break; } else if (*p == '/') { state = P_REST; break; } } if (state == P_START || state == P_REST) { rhost.p = uri.p; rhost.len = p - uri.p; } break; case P_SCHEME_OR_PORT: if (end - p >= 3 && strncmp(p, "://", 3) == 0) { rscheme.p = uri.p; rscheme.len = p - uri.p; state = P_USER_INFO; p += 3; } else { rhost.p = uri.p; rhost.len = p - uri.p; state = P_PORT; } break; case P_USER_INFO: ruser_info.p = p; for (; p < end; p++) { if (*p == '@' || *p == '[' || *p == '/') { break; } } if (p == end || *p == '/' || *p == '[') { /* backtrack and parse as host */ p = ruser_info.p; } ruser_info.len = p - ruser_info.p; state = P_HOST; break; case P_HOST: if (*p == '@') p++; rhost.p = p; if (*p == '[') { int found = 0; for (; !found && p < end; p++) { found = (*p == ']'); } if (!found) return -1; } else { for (; p < end; p++) { if (*p == ':' || *p == '/') break; } } rhost.len = p - rhost.p; if (p < end) { if (*p == ':') { state = P_PORT; break; } else if (*p == '/') { state = P_REST; break; } } break; case P_PORT: p++; for (; p < end; p++) { if (*p == '/') { state = P_REST; break; } rport *= 10; rport += *p - '0'; } break; case P_REST: /* `p` points to separator. `path` includes the separator */ parse_uri_component(&p, end, "?#", &rpath); if (p < end && *(p - 1) == '?') { parse_uri_component(&p, end, "#", &rquery); } parse_uri_component(&p, end, "", &rfragment); break; } } if (scheme != 0) *scheme = rscheme; if (user_info != 0) *user_info = ruser_info; if (host != 0) *host = rhost; if (port != 0) *port = rport; if (path != 0) *path = rpath; if (query != 0) *query = rquery; if (fragment != 0) *fragment = rfragment; return 0; } /* Normalize the URI path. Remove/resolve "." and "..". */ int mg_normalize_uri_path(const struct mg_str *in, struct mg_str *out) { const char *s = in->p, *se = s + in->len; char *cp = (char *) out->p, *d; if (in->len == 0 || *s != '/') { out->len = 0; return 0; } d = cp; while (s < se) { const char *next = s; struct mg_str component; parse_uri_component(&next, se, "/", &component); if (mg_vcmp(&component, ".") == 0) { /* Yum. */ } else if (mg_vcmp(&component, "..") == 0) { /* Backtrack to previous slash. */ if (d > cp + 1 && *(d - 1) == '/') d--; while (d > cp && *(d - 1) != '/') d--; } else { memmove(d, s, next - s); d += next - s; } s = next; } if (d == cp) *d++ = '/'; out->p = cp; out->len = d - cp; return 1; } int mg_assemble_uri(const struct mg_str *scheme, const struct mg_str *user_info, const struct mg_str *host, unsigned int port, const struct mg_str *path, const struct mg_str *query, const struct mg_str *fragment, int normalize_path, struct mg_str *uri) { int result = -1; struct mbuf out; mbuf_init(&out, 0); if (scheme != NULL && scheme->len > 0) { mbuf_append(&out, scheme->p, scheme->len); mbuf_append(&out, "://", 3); } if (user_info != NULL && user_info->len > 0) { mbuf_append(&out, user_info->p, user_info->len); mbuf_append(&out, "@", 1); } if (host != NULL && host->len > 0) { mbuf_append(&out, host->p, host->len); } if (port != 0) { char port_str[20]; int port_str_len = sprintf(port_str, ":%u", port); mbuf_append(&out, port_str, port_str_len); } if (path != NULL && path->len > 0) { if (normalize_path) { struct mg_str npath = mg_strdup(*path); if (npath.len != path->len) goto out; if (!mg_normalize_uri_path(path, &npath)) { free((void *) npath.p); goto out; } mbuf_append(&out, npath.p, npath.len); free((void *) npath.p); } else { mbuf_append(&out, path->p, path->len); } } else if (normalize_path) { mbuf_append(&out, "/", 1); } if (query != NULL && query->len > 0) { mbuf_append(&out, "?", 1); mbuf_append(&out, query->p, query->len); } if (fragment != NULL && fragment->len > 0) { mbuf_append(&out, "#", 1); mbuf_append(&out, fragment->p, fragment->len); } result = 0; out: if (result == 0) { uri->p = out.buf; uri->len = out.len; } else { mbuf_free(&out); uri->p = NULL; uri->len = 0; } return result; } #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_http.c" #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ #if MG_ENABLE_HTTP /* Amalgamated: #include "common/cs_md5.h" */ /* Amalgamated: #include "mg_internal.h" */ /* Amalgamated: #include "mg_util.h" */ /* altbuf {{{ */ /* * Alternate buffer: fills the client-provided buffer with data; and if it's * not large enough, allocates another buffer (via mbuf), similar to asprintf. */ struct altbuf { struct mbuf m; char *user_buf; size_t len; size_t user_buf_size; }; /* * Initializes altbuf; `buf`, `buf_size` is the client-provided buffer. */ MG_INTERNAL void altbuf_init(struct altbuf *ab, char *buf, size_t buf_size) { mbuf_init(&ab->m, 0); ab->user_buf = buf; ab->user_buf_size = buf_size; ab->len = 0; } /* * Appends a single char to the altbuf. */ MG_INTERNAL void altbuf_append(struct altbuf *ab, char c) { if (ab->len < ab->user_buf_size) { /* The data fits into the original buffer */ ab->user_buf[ab->len++] = c; } else { /* The data can't fit into the original buffer, so write it to mbuf. */ /* * First of all, see if that's the first byte which overflows the original * buffer: if so, copy the existing data from there to a newly allocated * mbuf. */ if (ab->len > 0 && ab->m.len == 0) { mbuf_append(&ab->m, ab->user_buf, ab->len); } mbuf_append(&ab->m, &c, 1); ab->len = ab->m.len; } } /* * Resets any data previously appended to altbuf. */ MG_INTERNAL void altbuf_reset(struct altbuf *ab) { mbuf_free(&ab->m); ab->len = 0; } /* * Returns whether the additional buffer was allocated (and thus the data * is in the mbuf, not the client-provided buffer) */ MG_INTERNAL int altbuf_reallocated(struct altbuf *ab) { return ab->len > ab->user_buf_size; } /* * Returns the actual buffer with data, either the client-provided or a newly * allocated one. If `trim` is non-zero, mbuf-backed buffer is trimmed first. */ MG_INTERNAL char *altbuf_get_buf(struct altbuf *ab, int trim) { if (altbuf_reallocated(ab)) { if (trim) { mbuf_trim(&ab->m); } return ab->m.buf; } else { return ab->user_buf; } } /* }}} */ static const char *mg_version_header = "Mongoose/" MG_VERSION; enum mg_http_proto_data_type { DATA_NONE, DATA_FILE, DATA_PUT }; struct mg_http_proto_data_file { FILE *fp; /* Opened file. */ int64_t cl; /* Content-Length. How many bytes to send. */ int64_t sent; /* How many bytes have been already sent. */ int keepalive; /* Keep connection open after sending. */ enum mg_http_proto_data_type type; }; #if MG_ENABLE_HTTP_CGI struct mg_http_proto_data_cgi { struct mg_connection *cgi_nc; }; #endif struct mg_http_proto_data_chuncked { int64_t body_len; /* How many bytes of chunked body was reassembled. */ }; struct mg_http_endpoint { struct mg_http_endpoint *next; struct mg_str uri_pattern; /* owned */ char *auth_domain; /* owned */ char *auth_file; /* owned */ mg_event_handler_t handler; #if MG_ENABLE_CALLBACK_USERDATA void *user_data; #endif }; enum mg_http_multipart_stream_state { MPS_BEGIN, MPS_WAITING_FOR_BOUNDARY, MPS_WAITING_FOR_CHUNK, MPS_GOT_BOUNDARY, MPS_FINALIZE, MPS_FINISHED }; struct mg_http_multipart_stream { const char *boundary; int boundary_len; const char *var_name; const char *file_name; void *user_data; enum mg_http_multipart_stream_state state; int processing_part; int data_avail; }; struct mg_reverse_proxy_data { struct mg_connection *linked_conn; }; struct mg_ws_proto_data { /* * Defragmented size of the frame so far. * * First byte of nc->recv_mbuf.buf is an op, the rest of the data is * defragmented data. */ size_t reass_len; }; struct mg_http_proto_data { #if MG_ENABLE_FILESYSTEM struct mg_http_proto_data_file file; #endif #if MG_ENABLE_HTTP_CGI struct mg_http_proto_data_cgi cgi; #endif #if MG_ENABLE_HTTP_STREAMING_MULTIPART struct mg_http_multipart_stream mp_stream; #endif #if MG_ENABLE_HTTP_WEBSOCKET struct mg_ws_proto_data ws_data; #endif struct mg_http_proto_data_chuncked chunk; struct mg_http_endpoint *endpoints; mg_event_handler_t endpoint_handler; struct mg_reverse_proxy_data reverse_proxy_data; size_t rcvd; /* How many bytes we have received. */ }; static void mg_http_proto_data_destructor(void *proto_data); struct mg_connection *mg_connect_http_base( struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), struct mg_connect_opts opts, const char *scheme1, const char *scheme2, const char *scheme_ssl1, const char *scheme_ssl2, const char *url, struct mg_str *path, struct mg_str *user_info, struct mg_str *host); MG_INTERNAL struct mg_http_proto_data *mg_http_create_proto_data( struct mg_connection *c) { /* If we have proto data from previous connection, flush it. */ if (c->proto_data != NULL) { void *pd = c->proto_data; c->proto_data = NULL; mg_http_proto_data_destructor(pd); } c->proto_data = MG_CALLOC(1, sizeof(struct mg_http_proto_data)); c->proto_data_destructor = mg_http_proto_data_destructor; return (struct mg_http_proto_data *) c->proto_data; } static struct mg_http_proto_data *mg_http_get_proto_data( struct mg_connection *c) { return (struct mg_http_proto_data *) c->proto_data; } #if MG_ENABLE_HTTP_STREAMING_MULTIPART static void mg_http_free_proto_data_mp_stream( struct mg_http_multipart_stream *mp) { MG_FREE((void *) mp->boundary); MG_FREE((void *) mp->var_name); MG_FREE((void *) mp->file_name); memset(mp, 0, sizeof(*mp)); } #endif #if MG_ENABLE_FILESYSTEM static void mg_http_free_proto_data_file(struct mg_http_proto_data_file *d) { if (d != NULL) { if (d->fp != NULL) { fclose(d->fp); } memset(d, 0, sizeof(struct mg_http_proto_data_file)); } } #endif static void mg_http_free_proto_data_endpoints(struct mg_http_endpoint **ep) { struct mg_http_endpoint *current = *ep; while (current != NULL) { struct mg_http_endpoint *tmp = current->next; MG_FREE((void *) current->uri_pattern.p); MG_FREE((void *) current->auth_domain); MG_FREE((void *) current->auth_file); MG_FREE(current); current = tmp; } ep = NULL; } static void mg_http_free_reverse_proxy_data(struct mg_reverse_proxy_data *rpd) { if (rpd->linked_conn != NULL) { /* * Connection has linked one, we have to unlink & close it * since _this_ connection is going to die and * it doesn't make sense to keep another one */ struct mg_http_proto_data *pd = mg_http_get_proto_data(rpd->linked_conn); if (pd->reverse_proxy_data.linked_conn != NULL) { pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE; pd->reverse_proxy_data.linked_conn = NULL; } rpd->linked_conn = NULL; } } static void mg_http_proto_data_destructor(void *proto_data) { struct mg_http_proto_data *pd = (struct mg_http_proto_data *) proto_data; #if MG_ENABLE_FILESYSTEM mg_http_free_proto_data_file(&pd->file); #endif #if MG_ENABLE_HTTP_CGI mg_http_free_proto_data_cgi(&pd->cgi); #endif #if MG_ENABLE_HTTP_STREAMING_MULTIPART mg_http_free_proto_data_mp_stream(&pd->mp_stream); #endif mg_http_free_proto_data_endpoints(&pd->endpoints); mg_http_free_reverse_proxy_data(&pd->reverse_proxy_data); MG_FREE(proto_data); } #if MG_ENABLE_FILESYSTEM #define MIME_ENTRY(_ext, _type) \ { _ext, sizeof(_ext) - 1, _type } static const struct { const char *extension; size_t ext_len; const char *mime_type; } mg_static_builtin_mime_types[] = { MIME_ENTRY("html", "text/html"), MIME_ENTRY("html", "text/html"), MIME_ENTRY("htm", "text/html"), MIME_ENTRY("shtm", "text/html"), MIME_ENTRY("shtml", "text/html"), MIME_ENTRY("css", "text/css"), MIME_ENTRY("js", "application/x-javascript"), MIME_ENTRY("ico", "image/x-icon"), MIME_ENTRY("gif", "image/gif"), MIME_ENTRY("jpg", "image/jpeg"), MIME_ENTRY("jpeg", "image/jpeg"), MIME_ENTRY("png", "image/png"), MIME_ENTRY("svg", "image/svg+xml"), MIME_ENTRY("txt", "text/plain"), MIME_ENTRY("torrent", "application/x-bittorrent"), MIME_ENTRY("wav", "audio/x-wav"), MIME_ENTRY("mp3", "audio/x-mp3"), MIME_ENTRY("mid", "audio/mid"), MIME_ENTRY("m3u", "audio/x-mpegurl"), MIME_ENTRY("ogg", "application/ogg"), MIME_ENTRY("ram", "audio/x-pn-realaudio"), MIME_ENTRY("xml", "text/xml"), MIME_ENTRY("ttf", "application/x-font-ttf"), MIME_ENTRY("json", "application/json"), MIME_ENTRY("xslt", "application/xml"), MIME_ENTRY("xsl", "application/xml"), MIME_ENTRY("ra", "audio/x-pn-realaudio"), MIME_ENTRY("doc", "application/msword"), MIME_ENTRY("exe", "application/octet-stream"), MIME_ENTRY("zip", "application/x-zip-compressed"), MIME_ENTRY("xls", "application/excel"), MIME_ENTRY("tgz", "application/x-tar-gz"), MIME_ENTRY("tar", "application/x-tar"), MIME_ENTRY("gz", "application/x-gunzip"), MIME_ENTRY("arj", "application/x-arj-compressed"), MIME_ENTRY("rar", "application/x-rar-compressed"), MIME_ENTRY("rtf", "application/rtf"), MIME_ENTRY("pdf", "application/pdf"), MIME_ENTRY("swf", "application/x-shockwave-flash"), MIME_ENTRY("mpg", "video/mpeg"), MIME_ENTRY("webm", "video/webm"), MIME_ENTRY("mpeg", "video/mpeg"), MIME_ENTRY("mov", "video/quicktime"), MIME_ENTRY("mp4", "video/mp4"), MIME_ENTRY("m4v", "video/x-m4v"), MIME_ENTRY("asf", "video/x-ms-asf"), MIME_ENTRY("avi", "video/x-msvideo"), MIME_ENTRY("bmp", "image/bmp"), {NULL, 0, NULL}}; static struct mg_str mg_get_mime_type(const char *path, const char *dflt, const struct mg_serve_http_opts *opts) { const char *ext, *overrides; size_t i, path_len; struct mg_str r, k, v; path_len = strlen(path); overrides = opts->custom_mime_types; while ((overrides = mg_next_comma_list_entry(overrides, &k, &v)) != NULL) { ext = path + (path_len - k.len); if (path_len > k.len && mg_vcasecmp(&k, ext) == 0) { return v; } } for (i = 0; mg_static_builtin_mime_types[i].extension != NULL; i++) { ext = path + (path_len - mg_static_builtin_mime_types[i].ext_len); if (path_len > mg_static_builtin_mime_types[i].ext_len && ext[-1] == '.' && mg_casecmp(ext, mg_static_builtin_mime_types[i].extension) == 0) { r.p = mg_static_builtin_mime_types[i].mime_type; r.len = strlen(r.p); return r; } } r.p = dflt; r.len = strlen(r.p); return r; } #endif /* * Check whether full request is buffered. Return: * -1 if request is malformed * 0 if request is not yet fully buffered * >0 actual request length, including last \r\n\r\n */ static int mg_http_get_request_len(const char *s, int buf_len) { const unsigned char *buf = (unsigned char *) s; int i; for (i = 0; i < buf_len; i++) { if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) { return -1; } else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') { return i + 2; } else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' && buf[i + 2] == '\n') { return i + 3; } } return 0; } static const char *mg_http_parse_headers(const char *s, const char *end, int len, struct http_message *req) { int i = 0; while (i < (int) ARRAY_SIZE(req->header_names) - 1) { struct mg_str *k = &req->header_names[i], *v = &req->header_values[i]; s = mg_skip(s, end, ": ", k); s = mg_skip(s, end, "\r\n", v); while (v->len > 0 && v->p[v->len - 1] == ' ') { v->len--; /* Trim trailing spaces in header value */ } /* * If header value is empty - skip it and go to next (if any). * NOTE: Do not add it to headers_values because such addition changes API * behaviour */ if (k->len != 0 && v->len == 0) { continue; } if (k->len == 0 || v->len == 0) { k->p = v->p = NULL; k->len = v->len = 0; break; } if (!mg_ncasecmp(k->p, "Content-Length", 14)) { req->body.len = (size_t) to64(v->p); req->message.len = len + req->body.len; } i++; } return s; } int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req) { const char *end, *qs; int len = mg_http_get_request_len(s, n); if (len <= 0) return len; memset(hm, 0, sizeof(*hm)); hm->message.p = s; hm->body.p = s + len; hm->message.len = hm->body.len = (size_t) ~0; end = s + len; /* Request is fully buffered. Skip leading whitespaces. */ while (s < end && isspace(*(unsigned char *) s)) s++; if (is_req) { /* Parse request line: method, URI, proto */ s = mg_skip(s, end, " ", &hm->method); s = mg_skip(s, end, " ", &hm->uri); s = mg_skip(s, end, "\r\n", &hm->proto); if (hm->uri.p <= hm->method.p || hm->proto.p <= hm->uri.p) return -1; /* If URI contains '?' character, initialize query_string */ if ((qs = (char *) memchr(hm->uri.p, '?', hm->uri.len)) != NULL) { hm->query_string.p = qs + 1; hm->query_string.len = &hm->uri.p[hm->uri.len] - (qs + 1); hm->uri.len = qs - hm->uri.p; } } else { s = mg_skip(s, end, " ", &hm->proto); if (end - s < 4 || s[3] != ' ') return -1; hm->resp_code = atoi(s); if (hm->resp_code < 100 || hm->resp_code >= 600) return -1; s += 4; s = mg_skip(s, end, "\r\n", &hm->resp_status_msg); } s = mg_http_parse_headers(s, end, len, hm); /* * mg_parse_http() is used to parse both HTTP requests and HTTP * responses. If HTTP response does not have Content-Length set, then * body is read until socket is closed, i.e. body.len is infinite (~0). * * For HTTP requests though, according to * http://tools.ietf.org/html/rfc7231#section-8.1.3, * only POST and PUT methods have defined body semantics. * Therefore, if Content-Length is not specified and methods are * not one of PUT or POST, set body length to 0. * * So, * if it is HTTP request, and Content-Length is not set, * and method is not (PUT or POST) then reset body length to zero. */ if (hm->body.len == (size_t) ~0 && is_req && mg_vcasecmp(&hm->method, "PUT") != 0 && mg_vcasecmp(&hm->method, "POST") != 0) { hm->body.len = 0; hm->message.len = len; } return len; } struct mg_str *mg_get_http_header(struct http_message *hm, const char *name) { size_t i, len = strlen(name); for (i = 0; hm->header_names[i].len > 0; i++) { struct mg_str *h = &hm->header_names[i], *v = &hm->header_values[i]; if (h->p != NULL && h->len == len && !mg_ncasecmp(h->p, name, len)) return v; } return NULL; } #if MG_ENABLE_FILESYSTEM static void mg_http_transfer_file_data(struct mg_connection *nc) { struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); char buf[MG_MAX_HTTP_SEND_MBUF]; size_t n = 0, to_read = 0, left = (size_t)(pd->file.cl - pd->file.sent); if (pd->file.type == DATA_FILE) { struct mbuf *io = &nc->send_mbuf; if (io->len >= MG_MAX_HTTP_SEND_MBUF) { to_read = 0; } else { to_read = MG_MAX_HTTP_SEND_MBUF - io->len; } if (to_read > left) { to_read = left; } if (to_read > 0) { n = mg_fread(buf, 1, to_read, pd->file.fp); if (n > 0) { mg_send(nc, buf, n); pd->file.sent += n; DBG(("%p sent %d (total %d)", nc, (int) n, (int) pd->file.sent)); } } else { /* Rate-limited */ } if (pd->file.sent >= pd->file.cl) { LOG(LL_DEBUG, ("%p done, %d bytes, ka %d", nc, (int) pd->file.sent, pd->file.keepalive)); if (!pd->file.keepalive) nc->flags |= MG_F_SEND_AND_CLOSE; mg_http_free_proto_data_file(&pd->file); } } else if (pd->file.type == DATA_PUT) { struct mbuf *io = &nc->recv_mbuf; size_t to_write = left <= 0 ? 0 : left < io->len ? (size_t) left : io->len; size_t n = mg_fwrite(io->buf, 1, to_write, pd->file.fp); if (n > 0) { mbuf_remove(io, n); pd->file.sent += n; } if (n == 0 || pd->file.sent >= pd->file.cl) { if (!pd->file.keepalive) nc->flags |= MG_F_SEND_AND_CLOSE; mg_http_free_proto_data_file(&pd->file); } } #if MG_ENABLE_HTTP_CGI else if (pd->cgi.cgi_nc != NULL) { /* This is POST data that needs to be forwarded to the CGI process */ if (pd->cgi.cgi_nc != NULL) { mg_forward(nc, pd->cgi.cgi_nc); } else { nc->flags |= MG_F_SEND_AND_CLOSE; } } #endif } #endif /* MG_ENABLE_FILESYSTEM */ /* * Parse chunked-encoded buffer. Return 0 if the buffer is not encoded, or * if it's incomplete. If the chunk is fully buffered, return total number of * bytes in a chunk, and store data in `data`, `data_len`. */ static size_t mg_http_parse_chunk(char *buf, size_t len, char **chunk_data, size_t *chunk_len) { unsigned char *s = (unsigned char *) buf; size_t n = 0; /* scanned chunk length */ size_t i = 0; /* index in s */ /* Scan chunk length. That should be a hexadecimal number. */ while (i < len && isxdigit(s[i])) { n *= 16; n += (s[i] >= '0' && s[i] <= '9') ? s[i] - '0' : tolower(s[i]) - 'a' + 10; i++; if (i > 6) { /* Chunk size is unreasonable. */ return 0; } } /* Skip new line */ if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') { return 0; } i += 2; /* Record where the data is */ *chunk_data = (char *) s + i; *chunk_len = n; /* Skip data */ i += n; /* Skip new line */ if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') { return 0; } return i + 2; } MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc, struct http_message *hm, char *buf, size_t blen) { struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); char *data; size_t i, n, data_len, body_len, zero_chunk_received = 0; /* Find out piece of received data that is not yet reassembled */ body_len = (size_t) pd->chunk.body_len; assert(blen >= body_len); /* Traverse all fully buffered chunks */ for (i = body_len; (n = mg_http_parse_chunk(buf + i, blen - i, &data, &data_len)) > 0; i += n) { /* Collapse chunk data to the rest of HTTP body */ memmove(buf + body_len, data, data_len); body_len += data_len; hm->body.len = body_len; if (data_len == 0) { zero_chunk_received = 1; i += n; break; } } if (i > body_len) { /* Shift unparsed content to the parsed body */ assert(i <= blen); memmove(buf + body_len, buf + i, blen - i); memset(buf + body_len + blen - i, 0, i - body_len); nc->recv_mbuf.len -= i - body_len; pd->chunk.body_len = body_len; /* Send MG_EV_HTTP_CHUNK event */ nc->flags &= ~MG_F_DELETE_CHUNK; mg_call(nc, nc->handler, nc->user_data, MG_EV_HTTP_CHUNK, hm); /* Delete processed data if user set MG_F_DELETE_CHUNK flag */ if (nc->flags & MG_F_DELETE_CHUNK) { memset(buf, 0, body_len); memmove(buf, buf + body_len, blen - i); nc->recv_mbuf.len -= body_len; hm->body.len = 0; pd->chunk.body_len = 0; } if (zero_chunk_received) { /* Total message size is len(body) + len(headers) */ hm->message.len = (size_t) pd->chunk.body_len + blen - i + (hm->body.p - hm->message.p); } } return body_len; } struct mg_http_endpoint *mg_http_get_endpoint_handler(struct mg_connection *nc, struct mg_str *uri_path) { struct mg_http_proto_data *pd; struct mg_http_endpoint *ret = NULL; int matched, matched_max = 0; struct mg_http_endpoint *ep; if (nc == NULL) return NULL; pd = mg_http_get_proto_data(nc); if (pd == NULL) return NULL; ep = pd->endpoints; while (ep != NULL) { if ((matched = mg_match_prefix_n(ep->uri_pattern, *uri_path)) > 0) { if (matched > matched_max) { /* Looking for the longest suitable handler */ ret = ep; matched_max = matched; } } ep = ep->next; } return ret; } #if MG_ENABLE_HTTP_STREAMING_MULTIPART static void mg_http_multipart_continue(struct mg_connection *nc); static void mg_http_multipart_begin(struct mg_connection *nc, struct http_message *hm, int req_len); #endif static void mg_http_call_endpoint_handler(struct mg_connection *nc, int ev, struct http_message *hm); static void deliver_chunk(struct mg_connection *c, struct http_message *hm, int req_len) { /* Incomplete message received. Send MG_EV_HTTP_CHUNK event */ hm->body.len = c->recv_mbuf.len - req_len; c->flags &= ~MG_F_DELETE_CHUNK; mg_call(c, c->handler, c->user_data, MG_EV_HTTP_CHUNK, hm); /* Delete processed data if user set MG_F_DELETE_CHUNK flag */ if (c->flags & MG_F_DELETE_CHUNK) c->recv_mbuf.len = req_len; } /* * lx106 compiler has a bug (TODO(mkm) report and insert tracking bug here) * If a big structure is declared in a big function, lx106 gcc will make it * even bigger (round up to 4k, from 700 bytes of actual size). */ #ifdef __xtensa__ static void mg_http_handler2(struct mg_connection *nc, int ev, void *ev_data MG_UD_ARG(void *user_data), struct http_message *hm) __attribute__((noinline)); void mg_http_handler(struct mg_connection *nc, int ev, void *ev_data MG_UD_ARG(void *user_data)) { struct http_message hm; mg_http_handler2(nc, ev, ev_data MG_UD_ARG(user_data), &hm); } static void mg_http_handler2(struct mg_connection *nc, int ev, void *ev_data MG_UD_ARG(void *user_data), struct http_message *hm) { #else /* !__XTENSA__ */ void mg_http_handler(struct mg_connection *nc, int ev, void *ev_data MG_UD_ARG(void *user_data)) { struct http_message shm, *hm = &shm; #endif /* __XTENSA__ */ struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); struct mbuf *io = &nc->recv_mbuf; int req_len; const int is_req = (nc->listener != NULL); #if MG_ENABLE_HTTP_WEBSOCKET struct mg_str *vec; #endif if (ev == MG_EV_CLOSE) { #if MG_ENABLE_HTTP_CGI /* Close associated CGI forwarder connection */ if (pd != NULL && pd->cgi.cgi_nc != NULL) { pd->cgi.cgi_nc->user_data = NULL; pd->cgi.cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY; } #endif #if MG_ENABLE_HTTP_STREAMING_MULTIPART if (pd != NULL && pd->mp_stream.boundary != NULL) { /* * Multipart message is in progress, but connection is closed. * Finish part and request with an error flag. */ struct mg_http_multipart_part mp; memset(&mp, 0, sizeof(mp)); mp.status = -1; mp.var_name = pd->mp_stream.var_name; mp.file_name = pd->mp_stream.file_name; mg_call(nc, (pd->endpoint_handler ? pd->endpoint_handler : nc->handler), nc->user_data, MG_EV_HTTP_PART_END, &mp); mp.var_name = NULL; mp.file_name = NULL; mg_call(nc, (pd->endpoint_handler ? pd->endpoint_handler : nc->handler), nc->user_data, MG_EV_HTTP_MULTIPART_REQUEST_END, &mp); } else #endif if (io->len > 0 && (req_len = mg_parse_http(io->buf, io->len, hm, is_req)) > 0) { /* * For HTTP messages without Content-Length, always send HTTP message * before MG_EV_CLOSE message. */ int ev2 = is_req ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY; hm->message.len = io->len; hm->body.len = io->buf + io->len - hm->body.p; deliver_chunk(nc, hm, req_len); mg_http_call_endpoint_handler(nc, ev2, hm); } if (pd != NULL && pd->endpoint_handler != NULL && pd->endpoint_handler != nc->handler) { mg_call(nc, pd->endpoint_handler, nc->user_data, ev, NULL); } } #if MG_ENABLE_FILESYSTEM if (pd != NULL && pd->file.fp != NULL) { mg_http_transfer_file_data(nc); } #endif mg_call(nc, nc->handler, nc->user_data, ev, ev_data); #if MG_ENABLE_HTTP_STREAMING_MULTIPART if (pd != NULL && pd->mp_stream.boundary != NULL && (ev == MG_EV_RECV || ev == MG_EV_POLL)) { if (ev == MG_EV_RECV) { pd->rcvd += *(int *) ev_data; mg_http_multipart_continue(nc); } else if (pd->mp_stream.data_avail) { /* Try re-delivering the data. */ mg_http_multipart_continue(nc); } return; } #endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */ if (ev == MG_EV_RECV) { struct mg_str *s; again: req_len = mg_parse_http(io->buf, io->len, hm, is_req); if (req_len > 0) { /* New request - new proto data */ pd = mg_http_create_proto_data(nc); pd->rcvd = io->len; } if (req_len > 0 && (s = mg_get_http_header(hm, "Transfer-Encoding")) != NULL && mg_vcasecmp(s, "chunked") == 0) { mg_handle_chunked(nc, hm, io->buf + req_len, io->len - req_len); } #if MG_ENABLE_HTTP_STREAMING_MULTIPART if (req_len > 0 && (s = mg_get_http_header(hm, "Content-Type")) != NULL && s->len >= 9 && strncmp(s->p, "multipart", 9) == 0) { mg_http_multipart_begin(nc, hm, req_len); mg_http_multipart_continue(nc); return; } #endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */ /* TODO(alashkin): refactor this ifelseifelseifelseifelse */ if ((req_len < 0 || (req_len == 0 && io->len >= MG_MAX_HTTP_REQUEST_SIZE))) { DBG(("invalid request")); nc->flags |= MG_F_CLOSE_IMMEDIATELY; } else if (req_len == 0) { /* Do nothing, request is not yet fully buffered */ } #if MG_ENABLE_HTTP_WEBSOCKET else if (nc->listener == NULL && (nc->flags & MG_F_IS_WEBSOCKET)) { /* We're websocket client, got handshake response from server. */ DBG(("%p WebSocket upgrade code %d", nc, hm->resp_code)); if (hm->resp_code == 101 && mg_get_http_header(hm, "Sec-WebSocket-Accept")) { /* TODO(lsm): check the validity of accept Sec-WebSocket-Accept */ mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_DONE, hm); mbuf_remove(io, req_len); nc->proto_handler = mg_ws_handler; mg_ws_handler(nc, MG_EV_RECV, ev_data MG_UD_ARG(user_data)); } else { mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_DONE, hm); nc->flags |= MG_F_CLOSE_IMMEDIATELY; mbuf_remove(io, req_len); } } else if (nc->listener != NULL && (vec = mg_get_http_header(hm, "Sec-WebSocket-Key")) != NULL) { struct mg_http_endpoint *ep; /* This is a websocket request. Switch protocol handlers. */ mbuf_remove(io, req_len); nc->proto_handler = mg_ws_handler; nc->flags |= MG_F_IS_WEBSOCKET; /* * If we have a handler set up with mg_register_http_endpoint(), * deliver subsequent websocket events to this handler after the * protocol switch. */ ep = mg_http_get_endpoint_handler(nc->listener, &hm->uri); if (ep != NULL) { nc->handler = ep->handler; #if MG_ENABLE_CALLBACK_USERDATA nc->user_data = ep->user_data; #endif } /* Send handshake */ mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_REQUEST, hm); if (!(nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_SEND_AND_CLOSE))) { if (nc->send_mbuf.len == 0) { mg_ws_handshake(nc, vec, hm); } mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_DONE, hm); mg_ws_handler(nc, MG_EV_RECV, ev_data MG_UD_ARG(user_data)); } } #endif /* MG_ENABLE_HTTP_WEBSOCKET */ else if (hm->message.len > pd->rcvd) { /* Not yet received all HTTP body, deliver MG_EV_HTTP_CHUNK */ deliver_chunk(nc, hm, req_len); if (nc->recv_mbuf_limit > 0 && nc->recv_mbuf.len >= nc->recv_mbuf_limit) { LOG(LL_ERROR, ("%p recv buffer (%lu bytes) exceeds the limit " "%lu bytes, and not drained, closing", nc, (unsigned long) nc->recv_mbuf.len, (unsigned long) nc->recv_mbuf_limit)); nc->flags |= MG_F_CLOSE_IMMEDIATELY; } } else { /* We did receive all HTTP body. */ int request_done = 1; int trigger_ev = nc->listener ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY; char addr[32]; mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT); DBG(("%p %s %.*s %.*s", nc, addr, (int) hm->method.len, hm->method.p, (int) hm->uri.len, hm->uri.p)); deliver_chunk(nc, hm, req_len); /* Whole HTTP message is fully buffered, call event handler */ mg_http_call_endpoint_handler(nc, trigger_ev, hm); mbuf_remove(io, hm->message.len); pd->rcvd -= hm->message.len; #if MG_ENABLE_FILESYSTEM /* We don't have a generic mechanism of communicating that we are done * responding to a request (should probably add one). But if we are * serving * a file, we are definitely not done. */ if (pd->file.fp != NULL) request_done = 0; #endif #if MG_ENABLE_HTTP_CGI /* If this is a CGI request, we are not done either. */ if (pd->cgi.cgi_nc != NULL) request_done = 0; #endif if (request_done && io->len > 0) goto again; } } } static size_t mg_get_line_len(const char *buf, size_t buf_len) { size_t len = 0; while (len < buf_len && buf[len] != '\n') len++; return len == buf_len ? 0 : len + 1; } #if MG_ENABLE_HTTP_STREAMING_MULTIPART static void mg_http_multipart_begin(struct mg_connection *nc, struct http_message *hm, int req_len) { struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); struct mg_str *ct; struct mbuf *io = &nc->recv_mbuf; char boundary_buf[100]; char *boundary = boundary_buf; int boundary_len; ct = mg_get_http_header(hm, "Content-Type"); if (ct == NULL) { /* We need more data - or it isn't multipart mesage */ goto exit_mp; } /* Content-type should start with "multipart" */ if (ct->len < 9 || strncmp(ct->p, "multipart", 9) != 0) { goto exit_mp; } boundary_len = mg_http_parse_header2(ct, "boundary", &boundary, sizeof(boundary_buf)); if (boundary_len == 0) { /* * Content type is multipart, but there is no boundary, * probably malformed request */ nc->flags = MG_F_CLOSE_IMMEDIATELY; DBG(("invalid request")); goto exit_mp; } /* If we reach this place - that is multipart request */ if (pd->mp_stream.boundary != NULL) { /* * Another streaming request was in progress, * looks like protocol error */ nc->flags |= MG_F_CLOSE_IMMEDIATELY; } else { struct mg_http_endpoint *ep = NULL; pd->mp_stream.state = MPS_BEGIN; pd->mp_stream.boundary = strdup(boundary); pd->mp_stream.boundary_len = strlen(boundary); pd->mp_stream.var_name = pd->mp_stream.file_name = NULL; pd->endpoint_handler = nc->handler; ep = mg_http_get_endpoint_handler(nc->listener, &hm->uri); if (ep != NULL) { pd->endpoint_handler = ep->handler; } mg_http_call_endpoint_handler(nc, MG_EV_HTTP_MULTIPART_REQUEST, hm); mbuf_remove(io, req_len); } exit_mp: if (boundary != boundary_buf) MG_FREE(boundary); } #define CONTENT_DISPOSITION "Content-Disposition: " static size_t mg_http_multipart_call_handler(struct mg_connection *c, int ev, const char *data, size_t data_len) { struct mg_http_multipart_part mp; struct mg_http_proto_data *pd = mg_http_get_proto_data(c); memset(&mp, 0, sizeof(mp)); mp.var_name = pd->mp_stream.var_name; mp.file_name = pd->mp_stream.file_name; mp.user_data = pd->mp_stream.user_data; mp.data.p = data; mp.data.len = data_len; mp.num_data_consumed = data_len; mg_call(c, pd->endpoint_handler, c->user_data, ev, &mp); pd->mp_stream.user_data = mp.user_data; pd->mp_stream.data_avail = (mp.num_data_consumed != data_len); return mp.num_data_consumed; } static int mg_http_multipart_finalize(struct mg_connection *c) { struct mg_http_proto_data *pd = mg_http_get_proto_data(c); mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_END, NULL, 0); MG_FREE((void *) pd->mp_stream.file_name); pd->mp_stream.file_name = NULL; MG_FREE((void *) pd->mp_stream.var_name); pd->mp_stream.var_name = NULL; mg_http_multipart_call_handler(c, MG_EV_HTTP_MULTIPART_REQUEST_END, NULL, 0); mg_http_free_proto_data_mp_stream(&pd->mp_stream); pd->mp_stream.state = MPS_FINISHED; return 1; } static int mg_http_multipart_wait_for_boundary(struct mg_connection *c) { const char *boundary; struct mbuf *io = &c->recv_mbuf; struct mg_http_proto_data *pd = mg_http_get_proto_data(c); if (pd->mp_stream.boundary == NULL) { pd->mp_stream.state = MPS_FINALIZE; DBG(("Invalid request: boundary not initialized")); return 0; } if ((int) io->len < pd->mp_stream.boundary_len + 2) { return 0; } boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len); if (boundary != NULL) { const char *boundary_end = (boundary + pd->mp_stream.boundary_len); if (io->len - (boundary_end - io->buf) < 4) { return 0; } if (strncmp(boundary_end, "--\r\n", 4) == 0) { pd->mp_stream.state = MPS_FINALIZE; mbuf_remove(io, (boundary_end - io->buf) + 4); } else { pd->mp_stream.state = MPS_GOT_BOUNDARY; } } else { return 0; } return 1; } static void mg_http_parse_header_internal(struct mg_str *hdr, const char *var_name, struct altbuf *ab); static int mg_http_multipart_process_boundary(struct mg_connection *c) { int data_size; const char *boundary, *block_begin; struct mbuf *io = &c->recv_mbuf; struct mg_http_proto_data *pd = mg_http_get_proto_data(c); struct altbuf ab_file_name, ab_var_name; int line_len; boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len); block_begin = boundary + pd->mp_stream.boundary_len + 2; data_size = io->len - (block_begin - io->buf); altbuf_init(&ab_file_name, NULL, 0); altbuf_init(&ab_var_name, NULL, 0); while (data_size > 0 && (line_len = mg_get_line_len(block_begin, data_size)) != 0) { if (line_len > (int) sizeof(CONTENT_DISPOSITION) && mg_ncasecmp(block_begin, CONTENT_DISPOSITION, sizeof(CONTENT_DISPOSITION) - 1) == 0) { struct mg_str header; header.p = block_begin + sizeof(CONTENT_DISPOSITION) - 1; header.len = line_len - sizeof(CONTENT_DISPOSITION) - 1; altbuf_reset(&ab_var_name); mg_http_parse_header_internal(&header, "name", &ab_var_name); altbuf_reset(&ab_file_name); mg_http_parse_header_internal(&header, "filename", &ab_file_name); block_begin += line_len; data_size -= line_len; continue; } if (line_len == 2 && mg_ncasecmp(block_begin, "\r\n", 2) == 0) { mbuf_remove(io, block_begin - io->buf + 2); if (pd->mp_stream.processing_part != 0) { mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_END, NULL, 0); } /* Reserve 2 bytes for "\r\n" in file_name and var_name */ altbuf_append(&ab_file_name, '\0'); altbuf_append(&ab_file_name, '\0'); altbuf_append(&ab_var_name, '\0'); altbuf_append(&ab_var_name, '\0'); MG_FREE((void *) pd->mp_stream.file_name); pd->mp_stream.file_name = altbuf_get_buf(&ab_file_name, 1 /* trim */); MG_FREE((void *) pd->mp_stream.var_name); pd->mp_stream.var_name = altbuf_get_buf(&ab_var_name, 1 /* trim */); mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_BEGIN, NULL, 0); pd->mp_stream.state = MPS_WAITING_FOR_CHUNK; pd->mp_stream.processing_part++; return 1; } block_begin += line_len; } pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY; altbuf_reset(&ab_var_name); altbuf_reset(&ab_file_name); return 0; } static int mg_http_multipart_continue_wait_for_chunk(struct mg_connection *c) { struct mg_http_proto_data *pd = mg_http_get_proto_data(c); struct mbuf *io = &c->recv_mbuf; const char *boundary; if ((int) io->len < pd->mp_stream.boundary_len + 6 /* \r\n, --, -- */) { return 0; } boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len); if (boundary == NULL) { int data_len = (io->len - (pd->mp_stream.boundary_len + 6)); if (data_len > 0) { size_t consumed = mg_http_multipart_call_handler( c, MG_EV_HTTP_PART_DATA, io->buf, (size_t) data_len); mbuf_remove(io, consumed); } return 0; } else if (boundary != NULL) { size_t data_len = ((size_t)(boundary - io->buf) - 4); size_t consumed = mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_DATA, io->buf, data_len); mbuf_remove(io, consumed); if (consumed == data_len) { mbuf_remove(io, 4); pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY; return 1; } else { return 0; } } else { return 0; } } static void mg_http_multipart_continue(struct mg_connection *c) { struct mg_http_proto_data *pd = mg_http_get_proto_data(c); while (1) { switch (pd->mp_stream.state) { case MPS_BEGIN: { pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY; break; } case MPS_WAITING_FOR_BOUNDARY: { if (mg_http_multipart_wait_for_boundary(c) == 0) { return; } break; } case MPS_GOT_BOUNDARY: { if (mg_http_multipart_process_boundary(c) == 0) { return; } break; } case MPS_WAITING_FOR_CHUNK: { if (mg_http_multipart_continue_wait_for_chunk(c) == 0) { return; } break; } case MPS_FINALIZE: { if (mg_http_multipart_finalize(c) == 0) { return; } break; } case MPS_FINISHED: { return; } } } } struct file_upload_state { char *lfn; size_t num_recd; FILE *fp; }; #endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */ void mg_set_protocol_http_websocket(struct mg_connection *nc) { nc->proto_handler = mg_http_handler; } const char *mg_status_message(int status_code) { switch (status_code) { case 206: return "Partial Content"; case 301: return "Moved"; case 302: return "Found"; case 400: return "Bad Request"; case 401: return "Unauthorized"; case 403: return "Forbidden"; case 404: return "Not Found"; case 416: return "Requested Range Not Satisfiable"; case 418: return "I'm a teapot"; case 500: return "Internal Server Error"; case 502: return "Bad Gateway"; case 503: return "Service Unavailable"; #if MG_ENABLE_EXTRA_ERRORS_DESC case 100: return "Continue"; case 101: return "Switching Protocols"; case 102: return "Processing"; case 200: return "OK"; case 201: return "Created"; case 202: return "Accepted"; case 203: return "Non-Authoritative Information"; case 204: return "No Content"; case 205: return "Reset Content"; case 207: return "Multi-Status"; case 208: return "Already Reported"; case 226: return "IM Used"; case 300: return "Multiple Choices"; case 303: return "See Other"; case 304: return "Not Modified"; case 305: return "Use Proxy"; case 306: return "Switch Proxy"; case 307: return "Temporary Redirect"; case 308: return "Permanent Redirect"; case 402: return "Payment Required"; case 405: return "Method Not Allowed"; case 406: return "Not Acceptable"; case 407: return "Proxy Authentication Required"; case 408: return "Request Timeout"; case 409: return "Conflict"; case 410: return "Gone"; case 411: return "Length Required"; case 412: return "Precondition Failed"; case 413: return "Payload Too Large"; case 414: return "URI Too Long"; case 415: return "Unsupported Media Type"; case 417: return "Expectation Failed"; case 422: return "Unprocessable Entity"; case 423: return "Locked"; case 424: return "Failed Dependency"; case 426: return "Upgrade Required"; case 428: return "Precondition Required"; case 429: return "Too Many Requests"; case 431: return "Request Header Fields Too Large"; case 451: return "Unavailable For Legal Reasons"; case 501: return "Not Implemented"; case 504: return "Gateway Timeout"; case 505: return "HTTP Version Not Supported"; case 506: return "Variant Also Negotiates"; case 507: return "Insufficient Storage"; case 508: return "Loop Detected"; case 510: return "Not Extended"; case 511: return "Network Authentication Required"; #endif /* MG_ENABLE_EXTRA_ERRORS_DESC */ default: return "OK"; } } void mg_send_response_line_s(struct mg_connection *nc, int status_code, const struct mg_str extra_headers) { mg_printf(nc, "HTTP/1.1 %d %s\r\n", status_code, mg_status_message(status_code)); #ifndef MG_HIDE_SERVER_INFO mg_printf(nc, "Server: %s\r\n", mg_version_header); #endif if (extra_headers.len > 0) { mg_printf(nc, "%.*s\r\n", (int) extra_headers.len, extra_headers.p); } } void mg_send_response_line(struct mg_connection *nc, int status_code, const char *extra_headers) { mg_send_response_line_s(nc, status_code, mg_mk_str(extra_headers)); } void mg_http_send_redirect(struct mg_connection *nc, int status_code, const struct mg_str location, const struct mg_str extra_headers) { char bbody[100], *pbody = bbody; int bl = mg_asprintf(&pbody, sizeof(bbody), "<p>Moved <a href='%.*s'>here</a>.\r\n", (int) location.len, location.p); char bhead[150], *phead = bhead; mg_asprintf(&phead, sizeof(bhead), "Location: %.*s\r\n" "Content-Type: text/html\r\n" "Content-Length: %d\r\n" "Cache-Control: no-cache\r\n" "%.*s%s", (int) location.len, location.p, bl, (int) extra_headers.len, extra_headers.p, (extra_headers.len > 0 ? "\r\n" : "")); mg_send_response_line(nc, status_code, phead); if (phead != bhead) MG_FREE(phead); mg_send(nc, pbody, bl); if (pbody != bbody) MG_FREE(pbody); } void mg_send_head(struct mg_connection *c, int status_code, int64_t content_length, const char *extra_headers) { mg_send_response_line(c, status_code, extra_headers); if (content_length < 0) { mg_printf(c, "%s", "Transfer-Encoding: chunked\r\n"); } else { mg_printf(c, "Content-Length: %" INT64_FMT "\r\n", content_length); } mg_send(c, "\r\n", 2); } void mg_http_send_error(struct mg_connection *nc, int code, const char *reason) { if (!reason) reason = mg_status_message(code); LOG(LL_DEBUG, ("%p %d %s", nc, code, reason)); mg_send_head(nc, code, strlen(reason), "Content-Type: text/plain\r\nConnection: close"); mg_send(nc, reason, strlen(reason)); nc->flags |= MG_F_SEND_AND_CLOSE; } #if MG_ENABLE_FILESYSTEM static void mg_http_construct_etag(char *buf, size_t buf_len, const cs_stat_t *st) { snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"", (unsigned long) st->st_mtime, (int64_t) st->st_size); } #ifndef WINCE static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) { strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t)); } #else /* Look wince_lib.c for WindowsCE implementation */ static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t); #endif static int mg_http_parse_range_header(const struct mg_str *header, int64_t *a, int64_t *b) { /* * There is no snscanf. Headers are not guaranteed to be NUL-terminated, * so we have this. Ugh. */ int result; char *p = (char *) MG_MALLOC(header->len + 1); if (p == NULL) return 0; memcpy(p, header->p, header->len); p[header->len] = '\0'; result = sscanf(p, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b); MG_FREE(p); return result; } void mg_http_serve_file(struct mg_connection *nc, struct http_message *hm, const char *path, const struct mg_str mime_type, const struct mg_str extra_headers) { struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); cs_stat_t st; LOG(LL_DEBUG, ("%p [%s] %.*s", nc, path, (int) mime_type.len, mime_type.p)); if (mg_stat(path, &st) != 0 || (pd->file.fp = mg_fopen(path, "rb")) == NULL) { int code, err = mg_get_errno(); switch (err) { case EACCES: code = 403; break; case ENOENT: code = 404; break; default: code = 500; }; mg_http_send_error(nc, code, "Open failed"); } else { char etag[50], current_time[50], last_modified[50], range[70]; time_t t = (time_t) mg_time(); int64_t r1 = 0, r2 = 0, cl = st.st_size; struct mg_str *range_hdr = mg_get_http_header(hm, "Range"); int n, status_code = 200; /* Handle Range header */ range[0] = '\0'; if (range_hdr != NULL && (n = mg_http_parse_range_header(range_hdr, &r1, &r2)) > 0 && r1 >= 0 && r2 >= 0) { /* If range is specified like "400-", set second limit to content len */ if (n == 1) { r2 = cl - 1; } if (r1 > r2 || r2 >= cl) { status_code = 416; cl = 0; snprintf(range, sizeof(range), "Content-Range: bytes */%" INT64_FMT "\r\n", (int64_t) st.st_size); } else { status_code = 206; cl = r2 - r1 + 1; snprintf(range, sizeof(range), "Content-Range: bytes %" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n", r1, r1 + cl - 1, (int64_t) st.st_size); #if _FILE_OFFSET_BITS == 64 || _POSIX_C_SOURCE >= 200112L || \ _XOPEN_SOURCE >= 600 fseeko(pd->file.fp, r1, SEEK_SET); #else fseek(pd->file.fp, (long) r1, SEEK_SET); #endif } } #if !MG_DISABLE_HTTP_KEEP_ALIVE { struct mg_str *conn_hdr = mg_get_http_header(hm, "Connection"); if (conn_hdr != NULL) { pd->file.keepalive = (mg_vcasecmp(conn_hdr, "keep-alive") == 0); } else { pd->file.keepalive = (mg_vcmp(&hm->proto, "HTTP/1.1") == 0); } } #endif mg_http_construct_etag(etag, sizeof(etag), &st); mg_gmt_time_string(current_time, sizeof(current_time), &t); mg_gmt_time_string(last_modified, sizeof(last_modified), &st.st_mtime); /* * Content length casted to size_t because: * 1) that's the maximum buffer size anyway * 2) ESP8266 RTOS SDK newlib vprintf cannot contain a 64bit arg at non-last * position * TODO(mkm): fix ESP8266 RTOS SDK */ mg_send_response_line_s(nc, status_code, extra_headers); mg_printf(nc, "Date: %s\r\n" "Last-Modified: %s\r\n" "Accept-Ranges: bytes\r\n" "Content-Type: %.*s\r\n" "Connection: %s\r\n" "Content-Length: %" SIZE_T_FMT "\r\n" "%sEtag: %s\r\n\r\n", current_time, last_modified, (int) mime_type.len, mime_type.p, (pd->file.keepalive ? "keep-alive" : "close"), (size_t) cl, range, etag); pd->file.cl = cl; pd->file.type = DATA_FILE; mg_http_transfer_file_data(nc); } } static void mg_http_serve_file2(struct mg_connection *nc, const char *path, struct http_message *hm, struct mg_serve_http_opts *opts) { #if MG_ENABLE_HTTP_SSI if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) > 0) { mg_handle_ssi_request(nc, hm, path, opts); return; } #endif mg_http_serve_file(nc, hm, path, mg_get_mime_type(path, "text/plain", opts), mg_mk_str(opts->extra_headers)); } #endif int mg_url_decode(const char *src, int src_len, char *dst, int dst_len, int is_form_url_encoded) { int i, j, a, b; #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W') for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) { if (src[i] == '%') { if (i < src_len - 2 && isxdigit(*(const unsigned char *) (src + i + 1)) && isxdigit(*(const unsigned char *) (src + i + 2))) { a = tolower(*(const unsigned char *) (src + i + 1)); b = tolower(*(const unsigned char *) (src + i + 2)); dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b)); i += 2; } else { return -1; } } else if (is_form_url_encoded && src[i] == '+') { dst[j] = ' '; } else { dst[j] = src[i]; } } dst[j] = '\0'; /* Null-terminate the destination */ return i >= src_len ? j : -1; } int mg_get_http_var(const struct mg_str *buf, const char *name, char *dst, size_t dst_len) { const char *p, *e, *s; size_t name_len; int len; /* * According to the documentation function returns negative * value in case of error. For debug purposes it returns: * -1 - src is wrong (NUUL) * -2 - dst is wrong (NULL) * -3 - failed to decode url or dst is to small * -4 - name does not exist */ if (dst == NULL || dst_len == 0) { len = -2; } else if (buf->p == NULL || name == NULL || buf->len == 0) { len = -1; dst[0] = '\0'; } else { name_len = strlen(name); e = buf->p + buf->len; len = -4; dst[0] = '\0'; for (p = buf->p; p + name_len < e; p++) { if ((p == buf->p || p[-1] == '&') && p[name_len] == '=' && !mg_ncasecmp(name, p, name_len)) { p += name_len + 1; s = (const char *) memchr(p, '&', (size_t)(e - p)); if (s == NULL) { s = e; } len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1); /* -1 means: failed to decode or dst is too small */ if (len == -1) { len = -3; } break; } } } return len; } void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len) { char chunk_size[50]; int n; n = snprintf(chunk_size, sizeof(chunk_size), "%lX\r\n", (unsigned long) len); mg_send(nc, chunk_size, n); mg_send(nc, buf, len); mg_send(nc, "\r\n", 2); } void mg_printf_http_chunk(struct mg_connection *nc, const char *fmt, ...) { char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem; int len; va_list ap; va_start(ap, fmt); len = mg_avprintf(&buf, sizeof(mem), fmt, ap); va_end(ap); if (len >= 0) { mg_send_http_chunk(nc, buf, len); } /* LCOV_EXCL_START */ if (buf != mem && buf != NULL) { MG_FREE(buf); } /* LCOV_EXCL_STOP */ } void mg_printf_html_escape(struct mg_connection *nc, const char *fmt, ...) { char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem; int i, j, len; va_list ap; va_start(ap, fmt); len = mg_avprintf(&buf, sizeof(mem), fmt, ap); va_end(ap); if (len >= 0) { for (i = j = 0; i < len; i++) { if (buf[i] == '<' || buf[i] == '>') { mg_send(nc, buf + j, i - j); mg_send(nc, buf[i] == '<' ? "&lt;" : "&gt;", 4); j = i + 1; } } mg_send(nc, buf + j, i - j); } /* LCOV_EXCL_START */ if (buf != mem && buf != NULL) { MG_FREE(buf); } /* LCOV_EXCL_STOP */ } static void mg_http_parse_header_internal(struct mg_str *hdr, const char *var_name, struct altbuf *ab) { int ch = ' ', ch1 = ',', ch2 = ';', n = strlen(var_name); const char *p, *end = hdr ? hdr->p + hdr->len : NULL, *s = NULL; /* Find where variable starts */ for (s = hdr->p; s != NULL && s + n < end; s++) { if ((s == hdr->p || s[-1] == ch || s[-1] == ch1 || s[-1] == ';') && s[n] == '=' && !strncmp(s, var_name, n)) break; } if (s != NULL && &s[n + 1] < end) { s += n + 1; if (*s == '"' || *s == '\'') { ch = ch1 = ch2 = *s++; } p = s; while (p < end && p[0] != ch && p[0] != ch1 && p[0] != ch2) { if (ch != ' ' && p[0] == '\\' && p[1] == ch) p++; altbuf_append(ab, *p++); } if (ch != ' ' && *p != ch) { altbuf_reset(ab); } } /* If there is some data, append a NUL. */ if (ab->len > 0) { altbuf_append(ab, '\0'); } } int mg_http_parse_header2(struct mg_str *hdr, const char *var_name, char **buf, size_t buf_size) { struct altbuf ab; altbuf_init(&ab, *buf, buf_size); if (hdr == NULL) return 0; if (*buf != NULL && buf_size > 0) *buf[0] = '\0'; mg_http_parse_header_internal(hdr, var_name, &ab); /* * Get a (trimmed) buffer, and return a len without a NUL byte which might * have been added. */ *buf = altbuf_get_buf(&ab, 1 /* trim */); return ab.len > 0 ? ab.len - 1 : 0; } int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf, size_t buf_size) { char *buf2 = buf; int len = mg_http_parse_header2(hdr, var_name, &buf2, buf_size); if (buf2 != buf) { /* Buffer was not enough and was reallocated: free it and just return 0 */ MG_FREE(buf2); return 0; } return len; } int mg_get_http_basic_auth(struct http_message *hm, char *user, size_t user_len, char *pass, size_t pass_len) { struct mg_str *hdr = mg_get_http_header(hm, "Authorization"); if (hdr == NULL) return -1; return mg_parse_http_basic_auth(hdr, user, user_len, pass, pass_len); } int mg_parse_http_basic_auth(struct mg_str *hdr, char *user, size_t user_len, char *pass, size_t pass_len) { char *buf = NULL; char fmt[64]; int res = 0; if (mg_strncmp(*hdr, mg_mk_str("Basic "), 6) != 0) return -1; buf = (char *) MG_MALLOC(hdr->len); cs_base64_decode((unsigned char *) hdr->p + 6, hdr->len, buf, NULL); /* e.g. "%123[^:]:%321[^\n]" */ snprintf(fmt, sizeof(fmt), "%%%" SIZE_T_FMT "[^:]:%%%" SIZE_T_FMT "[^\n]", user_len - 1, pass_len - 1); if (sscanf(buf, fmt, user, pass) == 0) { res = -1; } MG_FREE(buf); return res; } #if MG_ENABLE_FILESYSTEM static int mg_is_file_hidden(const char *path, const struct mg_serve_http_opts *opts, int exclude_specials) { const char *p1 = opts->per_directory_auth_file; const char *p2 = opts->hidden_file_pattern; /* Strip directory path from the file name */ const char *pdir = strrchr(path, DIRSEP); if (pdir != NULL) { path = pdir + 1; } return (exclude_specials && (!strcmp(path, ".") || !strcmp(path, ".."))) || (p1 != NULL && mg_match_prefix(p1, strlen(p1), path) == strlen(p1)) || (p2 != NULL && mg_match_prefix(p2, strlen(p2), path) > 0); } #if !MG_DISABLE_HTTP_DIGEST_AUTH #ifndef MG_EXT_MD5 void mg_hash_md5_v(size_t num_msgs, const uint8_t *msgs[], const size_t *msg_lens, uint8_t *digest) { size_t i; cs_md5_ctx md5_ctx; cs_md5_init(&md5_ctx); for (i = 0; i < num_msgs; i++) { cs_md5_update(&md5_ctx, msgs[i], msg_lens[i]); } cs_md5_final(digest, &md5_ctx); } #else extern void mg_hash_md5_v(size_t num_msgs, const uint8_t *msgs[], const size_t *msg_lens, uint8_t *digest); #endif void cs_md5(char buf[33], ...) { unsigned char hash[16]; const uint8_t *msgs[20], *p; size_t msg_lens[20]; size_t num_msgs = 0; va_list ap; va_start(ap, buf); while ((p = va_arg(ap, const unsigned char *) ) != NULL) { msgs[num_msgs] = p; msg_lens[num_msgs] = va_arg(ap, size_t); num_msgs++; } va_end(ap); mg_hash_md5_v(num_msgs, msgs, msg_lens, hash); cs_to_hex(buf, hash, sizeof(hash)); } static void mg_mkmd5resp(const char *method, size_t method_len, const char *uri, size_t uri_len, const char *ha1, size_t ha1_len, const char *nonce, size_t nonce_len, const char *nc, size_t nc_len, const char *cnonce, size_t cnonce_len, const char *qop, size_t qop_len, char *resp) { static const char colon[] = ":"; static const size_t one = 1; char ha2[33]; cs_md5(ha2, method, method_len, colon, one, uri, uri_len, NULL); cs_md5(resp, ha1, ha1_len, colon, one, nonce, nonce_len, colon, one, nc, nc_len, colon, one, cnonce, cnonce_len, colon, one, qop, qop_len, colon, one, ha2, sizeof(ha2) - 1, NULL); } int mg_http_create_digest_auth_header(char *buf, size_t buf_len, const char *method, const char *uri, const char *auth_domain, const char *user, const char *passwd, const char *nonce) { static const char colon[] = ":", qop[] = "auth"; static const size_t one = 1; char ha1[33], resp[33], cnonce[40]; snprintf(cnonce, sizeof(cnonce), "%lx", (unsigned long) mg_time()); cs_md5(ha1, user, (size_t) strlen(user), colon, one, auth_domain, (size_t) strlen(auth_domain), colon, one, passwd, (size_t) strlen(passwd), NULL); mg_mkmd5resp(method, strlen(method), uri, strlen(uri), ha1, sizeof(ha1) - 1, nonce, strlen(nonce), "1", one, cnonce, strlen(cnonce), qop, sizeof(qop) - 1, resp); return snprintf(buf, buf_len, "Authorization: Digest username=\"%s\"," "realm=\"%s\",uri=\"%s\",qop=%s,nc=1,cnonce=%s," "nonce=%s,response=%s\r\n", user, auth_domain, uri, qop, cnonce, nonce, resp); } /* * Check for authentication timeout. * Clients send time stamp encoded in nonce. Make sure it is not too old, * to prevent replay attacks. * Assumption: nonce is a hexadecimal number of seconds since 1970. */ static int mg_check_nonce(const char *nonce) { unsigned long now = (unsigned long) mg_time(); unsigned long val = (unsigned long) strtoul(nonce, NULL, 16); return (now >= val) && (now - val < 60 * 60); } int mg_http_check_digest_auth(struct http_message *hm, const char *auth_domain, FILE *fp) { int ret = 0; struct mg_str *hdr; char username_buf[50], cnonce_buf[64], response_buf[40], uri_buf[200], qop_buf[20], nc_buf[20], nonce_buf[16]; char *username = username_buf, *cnonce = cnonce_buf, *response = response_buf, *uri = uri_buf, *qop = qop_buf, *nc = nc_buf, *nonce = nonce_buf; /* Parse "Authorization:" header, fail fast on parse error */ if (hm == NULL || fp == NULL || (hdr = mg_get_http_header(hm, "Authorization")) == NULL || mg_http_parse_header2(hdr, "username", &username, sizeof(username_buf)) == 0 || mg_http_parse_header2(hdr, "cnonce", &cnonce, sizeof(cnonce_buf)) == 0 || mg_http_parse_header2(hdr, "response", &response, sizeof(response_buf)) == 0 || mg_http_parse_header2(hdr, "uri", &uri, sizeof(uri_buf)) == 0 || mg_http_parse_header2(hdr, "qop", &qop, sizeof(qop_buf)) == 0 || mg_http_parse_header2(hdr, "nc", &nc, sizeof(nc_buf)) == 0 || mg_http_parse_header2(hdr, "nonce", &nonce, sizeof(nonce_buf)) == 0 || mg_check_nonce(nonce) == 0) { ret = 0; goto clean; } /* NOTE(lsm): due to a bug in MSIE, we do not compare URIs */ ret = mg_check_digest_auth( hm->method, mg_mk_str_n( hm->uri.p, hm->uri.len + (hm->query_string.len ? hm->query_string.len + 1 : 0)), mg_mk_str(username), mg_mk_str(cnonce), mg_mk_str(response), mg_mk_str(qop), mg_mk_str(nc), mg_mk_str(nonce), mg_mk_str(auth_domain), fp); clean: if (username != username_buf) MG_FREE(username); if (cnonce != cnonce_buf) MG_FREE(cnonce); if (response != response_buf) MG_FREE(response); if (uri != uri_buf) MG_FREE(uri); if (qop != qop_buf) MG_FREE(qop); if (nc != nc_buf) MG_FREE(nc); if (nonce != nonce_buf) MG_FREE(nonce); return ret; } int mg_check_digest_auth(struct mg_str method, struct mg_str uri, struct mg_str username, struct mg_str cnonce, struct mg_str response, struct mg_str qop, struct mg_str nc, struct mg_str nonce, struct mg_str auth_domain, FILE *fp) { char buf[128], f_user[sizeof(buf)], f_ha1[sizeof(buf)], f_domain[sizeof(buf)]; char exp_resp[33]; /* * Read passwords file line by line. If should have htdigest format, * i.e. each line should be a colon-separated sequence: * USER_NAME:DOMAIN_NAME:HA1_HASH_OF_USER_DOMAIN_AND_PASSWORD */ while (fgets(buf, sizeof(buf), fp) != NULL) { if (sscanf(buf, "%[^:]:%[^:]:%s", f_user, f_domain, f_ha1) == 3 && mg_vcmp(&username, f_user) == 0 && mg_vcmp(&auth_domain, f_domain) == 0) { /* Username and domain matched, check the password */ mg_mkmd5resp(method.p, method.len, uri.p, uri.len, f_ha1, strlen(f_ha1), nonce.p, nonce.len, nc.p, nc.len, cnonce.p, cnonce.len, qop.p, qop.len, exp_resp); LOG(LL_DEBUG, ("%.*s %s %.*s %s", (int) username.len, username.p, f_domain, (int) response.len, response.p, exp_resp)); return mg_ncasecmp(response.p, exp_resp, strlen(exp_resp)) == 0; } } /* None of the entries in the passwords file matched - return failure */ return 0; } int mg_http_is_authorized(struct http_message *hm, struct mg_str path, const char *domain, const char *passwords_file, int flags) { char buf[MG_MAX_PATH]; const char *p; FILE *fp; int authorized = 1; if (domain != NULL && passwords_file != NULL) { if (flags & MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE) { fp = mg_fopen(passwords_file, "r"); } else if (flags & MG_AUTH_FLAG_IS_DIRECTORY) { snprintf(buf, sizeof(buf), "%.*s%c%s", (int) path.len, path.p, DIRSEP, passwords_file); fp = mg_fopen(buf, "r"); } else { p = strrchr(path.p, DIRSEP); if (p == NULL) p = path.p; snprintf(buf, sizeof(buf), "%.*s%c%s", (int) (p - path.p), path.p, DIRSEP, passwords_file); fp = mg_fopen(buf, "r"); } if (fp != NULL) { authorized = mg_http_check_digest_auth(hm, domain, fp); fclose(fp); } else if (!(flags & MG_AUTH_FLAG_ALLOW_MISSING_FILE)) { authorized = 0; } } LOG(LL_DEBUG, ("%.*s %s %x %d", (int) path.len, path.p, passwords_file ? passwords_file : "", flags, authorized)); return authorized; } #else int mg_http_is_authorized(struct http_message *hm, const struct mg_str path, const char *domain, const char *passwords_file, int flags) { (void) hm; (void) path; (void) domain; (void) passwords_file; (void) flags; return 1; } #endif #if MG_ENABLE_DIRECTORY_LISTING static void mg_escape(const char *src, char *dst, size_t dst_len) { size_t n = 0; while (*src != '\0' && n + 5 < dst_len) { unsigned char ch = *(unsigned char *) src++; if (ch == '<') { n += snprintf(dst + n, dst_len - n, "%s", "&lt;"); } else { dst[n++] = ch; } } dst[n] = '\0'; } static void mg_print_dir_entry(struct mg_connection *nc, const char *file_name, cs_stat_t *stp) { char size[64], mod[64], path[MG_MAX_PATH]; int64_t fsize = stp->st_size; int is_dir = S_ISDIR(stp->st_mode); const char *slash = is_dir ? "/" : ""; struct mg_str href; if (is_dir) { snprintf(size, sizeof(size), "%s", "[DIRECTORY]"); } else { /* * We use (double) cast below because MSVC 6 compiler cannot * convert unsigned __int64 to double. */ if (fsize < 1024) { snprintf(size, sizeof(size), "%d", (int) fsize); } else if (fsize < 0x100000) { snprintf(size, sizeof(size), "%.1fk", (double) fsize / 1024.0); } else if (fsize < 0x40000000) { snprintf(size, sizeof(size), "%.1fM", (double) fsize / 1048576); } else { snprintf(size, sizeof(size), "%.1fG", (double) fsize / 1073741824); } } strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&stp->st_mtime)); mg_escape(file_name, path, sizeof(path)); href = mg_url_encode(mg_mk_str(file_name)); mg_printf_http_chunk(nc, "<tr><td><a href=\"%s%s\">%s%s</a></td>" "<td>%s</td><td name=%" INT64_FMT ">%s</td></tr>\n", href.p, slash, path, slash, mod, is_dir ? -1 : fsize, size); free((void *) href.p); } static void mg_scan_directory(struct mg_connection *nc, const char *dir, const struct mg_serve_http_opts *opts, void (*func)(struct mg_connection *, const char *, cs_stat_t *)) { char path[MG_MAX_PATH + 1]; cs_stat_t st; struct dirent *dp; DIR *dirp; LOG(LL_DEBUG, ("%p [%s]", nc, dir)); if ((dirp = (opendir(dir))) != NULL) { while ((dp = readdir(dirp)) != NULL) { /* Do not show current dir and hidden files */ if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) { continue; } snprintf(path, sizeof(path), "%s/%s", dir, dp->d_name); if (mg_stat(path, &st) == 0) { func(nc, (const char *) dp->d_name, &st); } } closedir(dirp); } else { LOG(LL_DEBUG, ("%p opendir(%s) -> %d", nc, dir, mg_get_errno())); } } static void mg_send_directory_listing(struct mg_connection *nc, const char *dir, struct http_message *hm, struct mg_serve_http_opts *opts) { static const char *sort_js_code = "<script>function srt(tb, sc, so, d) {" "var tr = Array.prototype.slice.call(tb.rows, 0)," "tr = tr.sort(function (a, b) { var c1 = a.cells[sc], c2 = b.cells[sc]," "n1 = c1.getAttribute('name'), n2 = c2.getAttribute('name'), " "t1 = a.cells[2].getAttribute('name'), " "t2 = b.cells[2].getAttribute('name'); " "return so * (t1 < 0 && t2 >= 0 ? -1 : t2 < 0 && t1 >= 0 ? 1 : " "n1 ? parseInt(n2) - parseInt(n1) : " "c1.textContent.trim().localeCompare(c2.textContent.trim())); });"; static const char *sort_js_code2 = "for (var i = 0; i < tr.length; i++) tb.appendChild(tr[i]); " "if (!d) window.location.hash = ('sc=' + sc + '&so=' + so); " "};" "window.onload = function() {" "var tb = document.getElementById('tb');" "var m = /sc=([012]).so=(1|-1)/.exec(window.location.hash) || [0, 2, 1];" "var sc = m[1], so = m[2]; document.onclick = function(ev) { " "var c = ev.target.rel; if (c) {if (c == sc) so *= -1; srt(tb, c, so); " "sc = c; ev.preventDefault();}};" "srt(tb, sc, so, true);" "}" "</script>"; mg_send_response_line(nc, 200, opts->extra_headers); mg_printf(nc, "%s: %s\r\n%s: %s\r\n\r\n", "Transfer-Encoding", "chunked", "Content-Type", "text/html; charset=utf-8"); mg_printf_http_chunk( nc, "<html><head><title>Index of %.*s</title>%s%s" "<style>th,td {text-align: left; padding-right: 1em; " "font-family: monospace; }</style></head>\n" "<body><h1>Index of %.*s</h1>\n<table cellpadding=0><thead>" "<tr><th><a href=# rel=0>Name</a></th><th>" "<a href=# rel=1>Modified</a</th>" "<th><a href=# rel=2>Size</a></th></tr>" "<tr><td colspan=3><hr></td></tr>\n" "</thead>\n" "<tbody id=tb>", (int) hm->uri.len, hm->uri.p, sort_js_code, sort_js_code2, (int) hm->uri.len, hm->uri.p); mg_scan_directory(nc, dir, opts, mg_print_dir_entry); mg_printf_http_chunk(nc, "</tbody><tr><td colspan=3><hr></td></tr>\n" "</table>\n" "<address>%s</address>\n" "</body></html>", mg_version_header); mg_send_http_chunk(nc, "", 0); /* TODO(rojer): Remove when cesanta/dev/issues/197 is fixed. */ nc->flags |= MG_F_SEND_AND_CLOSE; } #endif /* MG_ENABLE_DIRECTORY_LISTING */ /* * Given a directory path, find one of the files specified in the * comma-separated list of index files `list`. * First found index file wins. If an index file is found, then gets * appended to the `path`, stat-ed, and result of `stat()` passed to `stp`. * If index file is not found, then `path` and `stp` remain unchanged. */ MG_INTERNAL void mg_find_index_file(const char *path, const char *list, char **index_file, cs_stat_t *stp) { struct mg_str vec; size_t path_len = strlen(path); int found = 0; *index_file = NULL; /* Traverse index files list. For each entry, append it to the given */ /* path and see if the file exists. If it exists, break the loop */ while ((list = mg_next_comma_list_entry(list, &vec, NULL)) != NULL) { cs_stat_t st; size_t len = path_len + 1 + vec.len + 1; *index_file = (char *) MG_REALLOC(*index_file, len); if (*index_file == NULL) break; snprintf(*index_file, len, "%s%c%.*s", path, DIRSEP, (int) vec.len, vec.p); /* Does it exist? Is it a file? */ if (mg_stat(*index_file, &st) == 0 && S_ISREG(st.st_mode)) { /* Yes it does, break the loop */ *stp = st; found = 1; break; } } if (!found) { MG_FREE(*index_file); *index_file = NULL; } LOG(LL_DEBUG, ("[%s] [%s]", path, (*index_file ? *index_file : ""))); } #if MG_ENABLE_HTTP_URL_REWRITES static int mg_http_send_port_based_redirect( struct mg_connection *c, struct http_message *hm, const struct mg_serve_http_opts *opts) { const char *rewrites = opts->url_rewrites; struct mg_str a, b; char local_port[20] = {'%'}; mg_conn_addr_to_str(c, local_port + 1, sizeof(local_port) - 1, MG_SOCK_STRINGIFY_PORT); while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) { if (mg_vcmp(&a, local_port) == 0) { mg_send_response_line(c, 301, NULL); mg_printf(c, "Content-Length: 0\r\nLocation: %.*s%.*s\r\n\r\n", (int) b.len, b.p, (int) (hm->proto.p - hm->uri.p - 1), hm->uri.p); return 1; } } return 0; } static void mg_reverse_proxy_handler(struct mg_connection *nc, int ev, void *ev_data MG_UD_ARG(void *user_data)) { struct http_message *hm = (struct http_message *) ev_data; struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); if (pd == NULL || pd->reverse_proxy_data.linked_conn == NULL) { DBG(("%p: upstream closed", nc)); return; } switch (ev) { case MG_EV_CONNECT: if (*(int *) ev_data != 0) { mg_http_send_error(pd->reverse_proxy_data.linked_conn, 502, NULL); } break; /* TODO(mkm): handle streaming */ case MG_EV_HTTP_REPLY: mg_send(pd->reverse_proxy_data.linked_conn, hm->message.p, hm->message.len); pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE; nc->flags |= MG_F_CLOSE_IMMEDIATELY; break; case MG_EV_CLOSE: pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE; break; } #if MG_ENABLE_CALLBACK_USERDATA (void) user_data; #endif } void mg_http_reverse_proxy(struct mg_connection *nc, const struct http_message *hm, struct mg_str mount, struct mg_str upstream) { struct mg_connection *be; char burl[256], *purl = burl; int i; const char *error; struct mg_connect_opts opts; struct mg_str path = MG_NULL_STR, user_info = MG_NULL_STR, host = MG_NULL_STR; memset(&opts, 0, sizeof(opts)); opts.error_string = &error; mg_asprintf(&purl, sizeof(burl), "%.*s%.*s", (int) upstream.len, upstream.p, (int) (hm->uri.len - mount.len), hm->uri.p + mount.len); be = mg_connect_http_base(nc->mgr, MG_CB(mg_reverse_proxy_handler, NULL), opts, "http", NULL, "https", NULL, purl, &path, &user_info, &host); LOG(LL_DEBUG, ("Proxying %.*s to %s (rule: %.*s)", (int) hm->uri.len, hm->uri.p, purl, (int) mount.len, mount.p)); if (be == NULL) { LOG(LL_ERROR, ("Error connecting to %s: %s", purl, error)); mg_http_send_error(nc, 502, NULL); goto cleanup; } /* link connections to each other, they must live and die together */ mg_http_get_proto_data(be)->reverse_proxy_data.linked_conn = nc; mg_http_get_proto_data(nc)->reverse_proxy_data.linked_conn = be; /* send request upstream */ mg_printf(be, "%.*s %.*s HTTP/1.1\r\n", (int) hm->method.len, hm->method.p, (int) path.len, path.p); mg_printf(be, "Host: %.*s\r\n", (int) host.len, host.p); for (i = 0; i < MG_MAX_HTTP_HEADERS && hm->header_names[i].len > 0; i++) { struct mg_str hn = hm->header_names[i]; struct mg_str hv = hm->header_values[i]; /* we rewrite the host header */ if (mg_vcasecmp(&hn, "Host") == 0) continue; /* * Don't pass chunked transfer encoding to the client because hm->body is * already dechunked when we arrive here. */ if (mg_vcasecmp(&hn, "Transfer-encoding") == 0 && mg_vcasecmp(&hv, "chunked") == 0) { mg_printf(be, "Content-Length: %" SIZE_T_FMT "\r\n", hm->body.len); continue; } /* We don't support proxying Expect: 100-continue. */ if (mg_vcasecmp(&hn, "Expect") == 0 && mg_vcasecmp(&hv, "100-continue") == 0) { continue; } mg_printf(be, "%.*s: %.*s\r\n", (int) hn.len, hn.p, (int) hv.len, hv.p); } mg_send(be, "\r\n", 2); mg_send(be, hm->body.p, hm->body.len); cleanup: if (purl != burl) MG_FREE(purl); } static int mg_http_handle_forwarding(struct mg_connection *nc, struct http_message *hm, const struct mg_serve_http_opts *opts) { const char *rewrites = opts->url_rewrites; struct mg_str a, b; struct mg_str p1 = MG_MK_STR("http://"), p2 = MG_MK_STR("https://"); while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) { if (mg_strncmp(a, hm->uri, a.len) == 0) { if (mg_strncmp(b, p1, p1.len) == 0 || mg_strncmp(b, p2, p2.len) == 0) { mg_http_reverse_proxy(nc, hm, a, b); return 1; } } } return 0; } #endif /* MG_ENABLE_FILESYSTEM */ MG_INTERNAL int mg_uri_to_local_path(struct http_message *hm, const struct mg_serve_http_opts *opts, char **local_path, struct mg_str *remainder) { int ok = 1; const char *cp = hm->uri.p, *cp_end = hm->uri.p + hm->uri.len; struct mg_str root = {NULL, 0}; const char *file_uri_start = cp; *local_path = NULL; remainder->p = NULL; remainder->len = 0; { /* 1. Determine which root to use. */ #if MG_ENABLE_HTTP_URL_REWRITES const char *rewrites = opts->url_rewrites; #else const char *rewrites = ""; #endif struct mg_str *hh = mg_get_http_header(hm, "Host"); struct mg_str a, b; /* Check rewrites first. */ while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) { if (a.len > 1 && a.p[0] == '@') { /* Host rewrite. */ if (hh != NULL && hh->len == a.len - 1 && mg_ncasecmp(a.p + 1, hh->p, a.len - 1) == 0) { root = b; break; } } else { /* Regular rewrite, URI=directory */ size_t match_len = mg_match_prefix_n(a, hm->uri); if (match_len > 0) { file_uri_start = hm->uri.p + match_len; if (*file_uri_start == '/' || file_uri_start == cp_end) { /* Match ended at component boundary, ok. */ } else if (*(file_uri_start - 1) == '/') { /* Pattern ends with '/', backtrack. */ file_uri_start--; } else { /* No match: must fall on the component boundary. */ continue; } root = b; break; } } } /* If no rewrite rules matched, use DAV or regular document root. */ if (root.p == NULL) { #if MG_ENABLE_HTTP_WEBDAV if (opts->dav_document_root != NULL && mg_is_dav_request(&hm->method)) { root.p = opts->dav_document_root; root.len = strlen(opts->dav_document_root); } else #endif { root.p = opts->document_root; root.len = strlen(opts->document_root); } } assert(root.p != NULL && root.len > 0); } { /* 2. Find where in the canonical URI path the local path ends. */ const char *u = file_uri_start + 1; char *lp = (char *) MG_MALLOC(root.len + hm->uri.len + 1); char *lp_end = lp + root.len + hm->uri.len + 1; char *p = lp, *ps; int exists = 1; if (lp == NULL) { ok = 0; goto out; } memcpy(p, root.p, root.len); p += root.len; if (*(p - 1) == DIRSEP) p--; *p = '\0'; ps = p; /* Chop off URI path components one by one and build local path. */ while (u <= cp_end) { const char *next = u; struct mg_str component; if (exists) { cs_stat_t st; exists = (mg_stat(lp, &st) == 0); if (exists && S_ISREG(st.st_mode)) { /* We found the terminal, the rest of the URI (if any) is path_info. */ if (*(u - 1) == '/') u--; break; } } if (u >= cp_end) break; parse_uri_component((const char **) &next, cp_end, "/", &component); if (component.len > 0) { int len; memmove(p + 1, component.p, component.len); len = mg_url_decode(p + 1, component.len, p + 1, lp_end - p - 1, 0); if (len <= 0) { ok = 0; break; } component.p = p + 1; component.len = len; if (mg_vcmp(&component, ".") == 0) { /* Yum. */ } else if (mg_vcmp(&component, "..") == 0) { while (p > ps && *p != DIRSEP) p--; *p = '\0'; } else { size_t i; #ifdef _WIN32 /* On Windows, make sure it's valid Unicode (no funny stuff). */ wchar_t buf[MG_MAX_PATH * 2]; if (to_wchar(component.p, buf, MG_MAX_PATH) == 0) { DBG(("[%.*s] smells funny", (int) component.len, component.p)); ok = 0; break; } #endif *p++ = DIRSEP; /* No NULs and DIRSEPs in the component (percent-encoded). */ for (i = 0; i < component.len; i++, p++) { if (*p == '\0' || *p == DIRSEP #ifdef _WIN32 /* On Windows, "/" is also accepted, so check for that too. */ || *p == '/' #endif ) { ok = 0; break; } } } } u = next; } if (ok) { *local_path = lp; if (u > cp_end) u = cp_end; remainder->p = u; remainder->len = cp_end - u; } else { MG_FREE(lp); } } out: LOG(LL_DEBUG, ("'%.*s' -> '%s' + '%.*s'", (int) hm->uri.len, hm->uri.p, *local_path ? *local_path : "", (int) remainder->len, remainder->p)); return ok; } static int mg_get_month_index(const char *s) { static const char *month_names[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; size_t i; for (i = 0; i < ARRAY_SIZE(month_names); i++) if (!strcmp(s, month_names[i])) return (int) i; return -1; } static int mg_num_leap_years(int year) { return year / 4 - year / 100 + year / 400; } /* Parse UTC date-time string, and return the corresponding time_t value. */ MG_INTERNAL time_t mg_parse_date_string(const char *datetime) { static const unsigned short days_before_month[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334}; char month_str[32]; int second, minute, hour, day, month, year, leap_days, days; time_t result = (time_t) 0; if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d", &day, month_str, &year, &hour, &minute, &second) == 6) || (sscanf(datetime, "%d %3s %d %d:%d:%d", &day, month_str, &year, &hour, &minute, &second) == 6) || (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d", &day, month_str, &year, &hour, &minute, &second) == 6) || (sscanf(datetime, "%d-%3s-%d %d:%d:%d", &day, month_str, &year, &hour, &minute, &second) == 6)) && year > 1970 && (month = mg_get_month_index(month_str)) != -1) { leap_days = mg_num_leap_years(year) - mg_num_leap_years(1970); year -= 1970; days = year * 365 + days_before_month[month] + (day - 1) + leap_days; result = days * 24 * 3600 + hour * 3600 + minute * 60 + second; } return result; } MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st) { struct mg_str *hdr; if ((hdr = mg_get_http_header(hm, "If-None-Match")) != NULL) { char etag[64]; mg_http_construct_etag(etag, sizeof(etag), st); return mg_vcasecmp(hdr, etag) == 0; } else if ((hdr = mg_get_http_header(hm, "If-Modified-Since")) != NULL) { return st->st_mtime <= mg_parse_date_string(hdr->p); } else { return 0; } } void mg_http_send_digest_auth_request(struct mg_connection *c, const char *domain) { mg_printf(c, "HTTP/1.1 401 Unauthorized\r\n" "WWW-Authenticate: Digest qop=\"auth\", " "realm=\"%s\", nonce=\"%lx\"\r\n" "Content-Length: 0\r\n\r\n", domain, (unsigned long) mg_time()); } static void mg_http_send_options(struct mg_connection *nc, struct mg_serve_http_opts *opts) { mg_send_response_line(nc, 200, opts->extra_headers); mg_printf(nc, "%s", "Allow: GET, POST, HEAD, CONNECT, OPTIONS" #if MG_ENABLE_HTTP_WEBDAV ", MKCOL, PUT, DELETE, PROPFIND, MOVE\r\nDAV: 1,2" #endif "\r\n\r\n"); nc->flags |= MG_F_SEND_AND_CLOSE; } static int mg_is_creation_request(const struct http_message *hm) { return mg_vcmp(&hm->method, "MKCOL") == 0 || mg_vcmp(&hm->method, "PUT") == 0; } MG_INTERNAL void mg_send_http_file(struct mg_connection *nc, char *path, const struct mg_str *path_info, struct http_message *hm, struct mg_serve_http_opts *opts) { int exists, is_directory, is_cgi; #if MG_ENABLE_HTTP_WEBDAV int is_dav = mg_is_dav_request(&hm->method); #else int is_dav = 0; #endif char *index_file = NULL; cs_stat_t st; exists = (mg_stat(path, &st) == 0); is_directory = exists && S_ISDIR(st.st_mode); if (is_directory) mg_find_index_file(path, opts->index_files, &index_file, &st); is_cgi = (mg_match_prefix(opts->cgi_file_pattern, strlen(opts->cgi_file_pattern), index_file ? index_file : path) > 0); LOG(LL_DEBUG, ("%p %.*s [%s] exists=%d is_dir=%d is_dav=%d is_cgi=%d index=%s", nc, (int) hm->method.len, hm->method.p, path, exists, is_directory, is_dav, is_cgi, index_file ? index_file : "")); if (is_directory && hm->uri.p[hm->uri.len - 1] != '/' && !is_dav) { mg_printf(nc, "HTTP/1.1 301 Moved\r\nLocation: %.*s/\r\n" "Content-Length: 0\r\n\r\n", (int) hm->uri.len, hm->uri.p); MG_FREE(index_file); return; } /* If we have path_info, the only way to handle it is CGI. */ if (path_info->len > 0 && !is_cgi) { mg_http_send_error(nc, 501, NULL); MG_FREE(index_file); return; } if (is_dav && opts->dav_document_root == NULL) { mg_http_send_error(nc, 501, NULL); } else if (!mg_http_is_authorized( hm, mg_mk_str(path), opts->auth_domain, opts->global_auth_file, ((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) | MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE | MG_AUTH_FLAG_ALLOW_MISSING_FILE)) || !mg_http_is_authorized( hm, mg_mk_str(path), opts->auth_domain, opts->per_directory_auth_file, ((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) | MG_AUTH_FLAG_ALLOW_MISSING_FILE))) { mg_http_send_digest_auth_request(nc, opts->auth_domain); } else if (is_cgi) { #if MG_ENABLE_HTTP_CGI mg_handle_cgi(nc, index_file ? index_file : path, path_info, hm, opts); #else mg_http_send_error(nc, 501, NULL); #endif /* MG_ENABLE_HTTP_CGI */ } else if ((!exists || mg_is_file_hidden(path, opts, 0 /* specials are ok */)) && !mg_is_creation_request(hm)) { mg_http_send_error(nc, 404, NULL); #if MG_ENABLE_HTTP_WEBDAV } else if (!mg_vcmp(&hm->method, "PROPFIND")) { mg_handle_propfind(nc, path, &st, hm, opts); #if !MG_DISABLE_DAV_AUTH } else if (is_dav && (opts->dav_auth_file == NULL || (strcmp(opts->dav_auth_file, "-") != 0 && !mg_http_is_authorized( hm, mg_mk_str(path), opts->auth_domain, opts->dav_auth_file, ((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) | MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE | MG_AUTH_FLAG_ALLOW_MISSING_FILE))))) { mg_http_send_digest_auth_request(nc, opts->auth_domain); #endif } else if (!mg_vcmp(&hm->method, "MKCOL")) { mg_handle_mkcol(nc, path, hm); } else if (!mg_vcmp(&hm->method, "DELETE")) { mg_handle_delete(nc, opts, path); } else if (!mg_vcmp(&hm->method, "PUT")) { mg_handle_put(nc, path, hm); } else if (!mg_vcmp(&hm->method, "MOVE")) { mg_handle_move(nc, opts, path, hm); #if MG_ENABLE_FAKE_DAVLOCK } else if (!mg_vcmp(&hm->method, "LOCK")) { mg_handle_lock(nc, path); #endif #endif /* MG_ENABLE_HTTP_WEBDAV */ } else if (!mg_vcmp(&hm->method, "OPTIONS")) { mg_http_send_options(nc, opts); } else if (is_directory && index_file == NULL) { #if MG_ENABLE_DIRECTORY_LISTING if (strcmp(opts->enable_directory_listing, "yes") == 0) { mg_send_directory_listing(nc, path, hm, opts); } else { mg_http_send_error(nc, 403, NULL); } #else mg_http_send_error(nc, 501, NULL); #endif } else if (mg_is_not_modified(hm, &st)) { mg_http_send_error(nc, 304, "Not Modified"); } else { mg_http_serve_file2(nc, index_file ? index_file : path, hm, opts); } MG_FREE(index_file); } void mg_serve_http(struct mg_connection *nc, struct http_message *hm, struct mg_serve_http_opts opts) { char *path = NULL; struct mg_str *hdr, path_info; uint32_t remote_ip = ntohl(*(uint32_t *) &nc->sa.sin.sin_addr); if (mg_check_ip_acl(opts.ip_acl, remote_ip) != 1) { /* Not allowed to connect */ mg_http_send_error(nc, 403, NULL); nc->flags |= MG_F_SEND_AND_CLOSE; return; } #if MG_ENABLE_HTTP_URL_REWRITES if (mg_http_handle_forwarding(nc, hm, &opts)) { return; } if (mg_http_send_port_based_redirect(nc, hm, &opts)) { return; } #endif if (opts.document_root == NULL) { opts.document_root = "."; } if (opts.per_directory_auth_file == NULL) { opts.per_directory_auth_file = ".htpasswd"; } if (opts.enable_directory_listing == NULL) { opts.enable_directory_listing = "yes"; } if (opts.cgi_file_pattern == NULL) { opts.cgi_file_pattern = "**.cgi$|**.php$"; } if (opts.ssi_pattern == NULL) { opts.ssi_pattern = "**.shtml$|**.shtm$"; } if (opts.index_files == NULL) { opts.index_files = "index.html,index.htm,index.shtml,index.cgi,index.php"; } /* Normalize path - resolve "." and ".." (in-place). */ if (!mg_normalize_uri_path(&hm->uri, &hm->uri)) { mg_http_send_error(nc, 400, NULL); return; } if (mg_uri_to_local_path(hm, &opts, &path, &path_info) == 0) { mg_http_send_error(nc, 404, NULL); return; } mg_send_http_file(nc, path, &path_info, hm, &opts); MG_FREE(path); path = NULL; /* Close connection for non-keep-alive requests */ if (mg_vcmp(&hm->proto, "HTTP/1.1") != 0 || ((hdr = mg_get_http_header(hm, "Connection")) != NULL && mg_vcmp(hdr, "keep-alive") != 0)) { #if 0 nc->flags |= MG_F_SEND_AND_CLOSE; #endif } } #if MG_ENABLE_HTTP_STREAMING_MULTIPART void mg_file_upload_handler(struct mg_connection *nc, int ev, void *ev_data, mg_fu_fname_fn local_name_fn MG_UD_ARG(void *user_data)) { switch (ev) { case MG_EV_HTTP_PART_BEGIN: { struct mg_http_multipart_part *mp = (struct mg_http_multipart_part *) ev_data; struct file_upload_state *fus; struct mg_str lfn = local_name_fn(nc, mg_mk_str(mp->file_name)); mp->user_data = NULL; if (lfn.p == NULL || lfn.len == 0) { LOG(LL_ERROR, ("%p Not allowed to upload %s", nc, mp->file_name)); mg_printf(nc, "HTTP/1.1 403 Not Allowed\r\n" "Content-Type: text/plain\r\n" "Connection: close\r\n\r\n" "Not allowed to upload %s\r\n", mp->file_name); nc->flags |= MG_F_SEND_AND_CLOSE; return; } fus = (struct file_upload_state *) MG_CALLOC(1, sizeof(*fus)); if (fus == NULL) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; return; } fus->lfn = (char *) MG_MALLOC(lfn.len + 1); memcpy(fus->lfn, lfn.p, lfn.len); fus->lfn[lfn.len] = '\0'; if (lfn.p != mp->file_name) MG_FREE((char *) lfn.p); LOG(LL_DEBUG, ("%p Receiving file %s -> %s", nc, mp->file_name, fus->lfn)); fus->fp = mg_fopen(fus->lfn, "wb"); if (fus->fp == NULL) { mg_printf(nc, "HTTP/1.1 500 Internal Server Error\r\n" "Content-Type: text/plain\r\n" "Connection: close\r\n\r\n"); LOG(LL_ERROR, ("Failed to open %s: %d\n", fus->lfn, mg_get_errno())); mg_printf(nc, "Failed to open %s: %d\n", fus->lfn, mg_get_errno()); /* Do not close the connection just yet, discard remainder of the data. * This is because at the time of writing some browsers (Chrome) fail to * render response before all the data is sent. */ } mp->user_data = (void *) fus; break; } case MG_EV_HTTP_PART_DATA: { struct mg_http_multipart_part *mp = (struct mg_http_multipart_part *) ev_data; struct file_upload_state *fus = (struct file_upload_state *) mp->user_data; if (fus == NULL || fus->fp == NULL) break; if (mg_fwrite(mp->data.p, 1, mp->data.len, fus->fp) != mp->data.len) { LOG(LL_ERROR, ("Failed to write to %s: %d, wrote %d", fus->lfn, mg_get_errno(), (int) fus->num_recd)); if (mg_get_errno() == ENOSPC #ifdef SPIFFS_ERR_FULL || mg_get_errno() == SPIFFS_ERR_FULL #endif ) { mg_printf(nc, "HTTP/1.1 413 Payload Too Large\r\n" "Content-Type: text/plain\r\n" "Connection: close\r\n\r\n"); mg_printf(nc, "Failed to write to %s: no space left; wrote %d\r\n", fus->lfn, (int) fus->num_recd); } else { mg_printf(nc, "HTTP/1.1 500 Internal Server Error\r\n" "Content-Type: text/plain\r\n" "Connection: close\r\n\r\n"); mg_printf(nc, "Failed to write to %s: %d, wrote %d", mp->file_name, mg_get_errno(), (int) fus->num_recd); } fclose(fus->fp); remove(fus->lfn); fus->fp = NULL; /* Do not close the connection just yet, discard remainder of the data. * This is because at the time of writing some browsers (Chrome) fail to * render response before all the data is sent. */ return; } fus->num_recd += mp->data.len; LOG(LL_DEBUG, ("%p rec'd %d bytes, %d total", nc, (int) mp->data.len, (int) fus->num_recd)); break; } case MG_EV_HTTP_PART_END: { struct mg_http_multipart_part *mp = (struct mg_http_multipart_part *) ev_data; struct file_upload_state *fus = (struct file_upload_state *) mp->user_data; if (fus == NULL) break; if (mp->status >= 0 && fus->fp != NULL) { LOG(LL_DEBUG, ("%p Uploaded %s (%s), %d bytes", nc, mp->file_name, fus->lfn, (int) fus->num_recd)); } else { LOG(LL_ERROR, ("Failed to store %s (%s)", mp->file_name, fus->lfn)); /* * mp->status < 0 means connection was terminated, so no reason to send * HTTP reply */ } if (fus->fp != NULL) fclose(fus->fp); MG_FREE(fus->lfn); MG_FREE(fus); mp->user_data = NULL; /* Don't close the connection yet, there may be more files to come. */ break; } case MG_EV_HTTP_MULTIPART_REQUEST_END: { mg_printf(nc, "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Connection: close\r\n\r\n" "Ok.\r\n"); nc->flags |= MG_F_SEND_AND_CLOSE; break; } } #if MG_ENABLE_CALLBACK_USERDATA (void) user_data; #endif } #endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */ #endif /* MG_ENABLE_FILESYSTEM */ struct mg_connection *mg_connect_http_base( struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), struct mg_connect_opts opts, const char *scheme1, const char *scheme2, const char *scheme_ssl1, const char *scheme_ssl2, const char *url, struct mg_str *path, struct mg_str *user_info, struct mg_str *host) { struct mg_connection *nc = NULL; unsigned int port_i = 0; int use_ssl = 0; struct mg_str scheme, query, fragment; char conn_addr_buf[2]; char *conn_addr = conn_addr_buf; if (mg_parse_uri(mg_mk_str(url), &scheme, user_info, host, &port_i, path, &query, &fragment) != 0) { MG_SET_PTRPTR(opts.error_string, "cannot parse url"); goto out; } /* If query is present, do not strip it. Pass to the caller. */ if (query.len > 0) path->len += query.len + 1; if (scheme.len == 0 || mg_vcmp(&scheme, scheme1) == 0 || (scheme2 != NULL && mg_vcmp(&scheme, scheme2) == 0)) { use_ssl = 0; if (port_i == 0) port_i = 80; } else if (mg_vcmp(&scheme, scheme_ssl1) == 0 || (scheme2 != NULL && mg_vcmp(&scheme, scheme_ssl2) == 0)) { use_ssl = 1; if (port_i == 0) port_i = 443; } else { goto out; } mg_asprintf(&conn_addr, sizeof(conn_addr_buf), "tcp://%.*s:%u", (int) host->len, host->p, port_i); if (conn_addr == NULL) goto out; LOG(LL_DEBUG, ("%s use_ssl? %d %s", url, use_ssl, conn_addr)); if (use_ssl) { #if MG_ENABLE_SSL /* * Schema requires SSL, but no SSL parameters were provided in opts. * In order to maintain backward compatibility, use a faux-SSL with no * verification. */ if (opts.ssl_ca_cert == NULL) { opts.ssl_ca_cert = "*"; } #else MG_SET_PTRPTR(opts.error_string, "ssl is disabled"); goto out; #endif } if ((nc = mg_connect_opt(mgr, conn_addr, MG_CB(ev_handler, user_data), opts)) != NULL) { mg_set_protocol_http_websocket(nc); } out: if (conn_addr != NULL && conn_addr != conn_addr_buf) MG_FREE(conn_addr); return nc; } struct mg_connection *mg_connect_http_opt( struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), struct mg_connect_opts opts, const char *url, const char *extra_headers, const char *post_data) { struct mg_str user = MG_NULL_STR, null_str = MG_NULL_STR; struct mg_str host = MG_NULL_STR, path = MG_NULL_STR; struct mbuf auth; struct mg_connection *nc = mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http", NULL, "https", NULL, url, &path, &user, &host); if (nc == NULL) { return NULL; } mbuf_init(&auth, 0); if (user.len > 0) { mg_basic_auth_header(user, null_str, &auth); } if (post_data == NULL) post_data = ""; if (extra_headers == NULL) extra_headers = ""; if (path.len == 0) path = mg_mk_str("/"); if (host.len == 0) host = mg_mk_str(""); mg_printf(nc, "%s %.*s HTTP/1.1\r\nHost: %.*s\r\nContent-Length: %" SIZE_T_FMT "\r\n%.*s%s\r\n%s", (post_data[0] == '\0' ? "GET" : "POST"), (int) path.len, path.p, (int) (path.p - host.p), host.p, strlen(post_data), (int) auth.len, (auth.buf == NULL ? "" : auth.buf), extra_headers, post_data); mbuf_free(&auth); return nc; } struct mg_connection *mg_connect_http( struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), const char *url, const char *extra_headers, const char *post_data) { struct mg_connect_opts opts; memset(&opts, 0, sizeof(opts)); return mg_connect_http_opt(mgr, MG_CB(ev_handler, user_data), opts, url, extra_headers, post_data); } size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name, size_t var_name_len, char *file_name, size_t file_name_len, const char **data, size_t *data_len) { static const char cd[] = "Content-Disposition: "; size_t hl, bl, n, ll, pos, cdl = sizeof(cd) - 1; int shl; if (buf == NULL || buf_len <= 0) return 0; if ((shl = mg_http_get_request_len(buf, buf_len)) <= 0) return 0; hl = shl; if (buf[0] != '-' || buf[1] != '-' || buf[2] == '\n') return 0; /* Get boundary length */ bl = mg_get_line_len(buf, buf_len); /* Loop through headers, fetch variable name and file name */ var_name[0] = file_name[0] = '\0'; for (n = bl; (ll = mg_get_line_len(buf + n, hl - n)) > 0; n += ll) { if (mg_ncasecmp(cd, buf + n, cdl) == 0) { struct mg_str header; header.p = buf + n + cdl; header.len = ll - (cdl + 2); { char *var_name2 = var_name; mg_http_parse_header2(&header, "name", &var_name2, var_name_len); /* TODO: handle reallocated buffer correctly */ if (var_name2 != var_name) { MG_FREE(var_name2); var_name[0] = '\0'; } } { char *file_name2 = file_name; mg_http_parse_header2(&header, "filename", &file_name2, file_name_len); /* TODO: handle reallocated buffer correctly */ if (file_name2 != file_name) { MG_FREE(file_name2); file_name[0] = '\0'; } } } } /* Scan through the body, search for terminating boundary */ for (pos = hl; pos + (bl - 2) < buf_len; pos++) { if (buf[pos] == '-' && !strncmp(buf, &buf[pos], bl - 2)) { if (data_len != NULL) *data_len = (pos - 2) - hl; if (data != NULL) *data = buf + hl; return pos; } } return 0; } void mg_register_http_endpoint_opt(struct mg_connection *nc, const char *uri_path, mg_event_handler_t handler, struct mg_http_endpoint_opts opts) { struct mg_http_proto_data *pd = NULL; struct mg_http_endpoint *new_ep = NULL; if (nc == NULL) return; new_ep = (struct mg_http_endpoint *) MG_CALLOC(1, sizeof(*new_ep)); if (new_ep == NULL) return; pd = mg_http_get_proto_data(nc); if (pd == NULL) pd = mg_http_create_proto_data(nc); new_ep->uri_pattern = mg_strdup(mg_mk_str(uri_path)); if (opts.auth_domain != NULL && opts.auth_file != NULL) { new_ep->auth_domain = strdup(opts.auth_domain); new_ep->auth_file = strdup(opts.auth_file); } new_ep->handler = handler; #if MG_ENABLE_CALLBACK_USERDATA new_ep->user_data = opts.user_data; #endif new_ep->next = pd->endpoints; pd->endpoints = new_ep; } static void mg_http_call_endpoint_handler(struct mg_connection *nc, int ev, struct http_message *hm) { struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); void *user_data = nc->user_data; if (ev == MG_EV_HTTP_REQUEST #if MG_ENABLE_HTTP_STREAMING_MULTIPART || ev == MG_EV_HTTP_MULTIPART_REQUEST #endif ) { struct mg_http_endpoint *ep = mg_http_get_endpoint_handler(nc->listener, &hm->uri); if (ep != NULL) { #if MG_ENABLE_FILESYSTEM && !MG_DISABLE_HTTP_DIGEST_AUTH if (!mg_http_is_authorized(hm, hm->uri, ep->auth_domain, ep->auth_file, MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE)) { mg_http_send_digest_auth_request(nc, ep->auth_domain); return; } #endif pd->endpoint_handler = ep->handler; #if MG_ENABLE_CALLBACK_USERDATA user_data = ep->user_data; #endif } } mg_call(nc, pd->endpoint_handler ? pd->endpoint_handler : nc->handler, user_data, ev, hm); } void mg_register_http_endpoint(struct mg_connection *nc, const char *uri_path, MG_CB(mg_event_handler_t handler, void *user_data)) { struct mg_http_endpoint_opts opts; memset(&opts, 0, sizeof(opts)); #if MG_ENABLE_CALLBACK_USERDATA opts.user_data = user_data; #endif mg_register_http_endpoint_opt(nc, uri_path, handler, opts); } #endif /* MG_ENABLE_HTTP */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_http_cgi.c" #endif /* * Copyright (c) 2014-2016 Cesanta Software Limited * All rights reserved */ #ifndef _WIN32 #include <signal.h> #endif #if MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI #ifndef MG_MAX_CGI_ENVIR_VARS #define MG_MAX_CGI_ENVIR_VARS 64 #endif #ifndef MG_ENV_EXPORT_TO_CGI #define MG_ENV_EXPORT_TO_CGI "MONGOOSE_CGI" #endif #define MG_F_HTTP_CGI_PARSE_HEADERS MG_F_USER_1 /* * This structure helps to create an environment for the spawned CGI program. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings, * last element must be NULL. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0 * strings must reside in a contiguous buffer. The end of the buffer is * marked by two '\0' characters. * We satisfy both worlds: we create an envp array (which is vars), all * entries are actually pointers inside buf. */ struct mg_cgi_env_block { struct mg_connection *nc; char buf[MG_CGI_ENVIRONMENT_SIZE]; /* Environment buffer */ const char *vars[MG_MAX_CGI_ENVIR_VARS]; /* char *envp[] */ int len; /* Space taken */ int nvars; /* Number of variables in envp[] */ }; #ifdef _WIN32 struct mg_threadparam { sock_t s; HANDLE hPipe; }; static int mg_wait_until_ready(sock_t sock, int for_read) { fd_set set; FD_ZERO(&set); FD_SET(sock, &set); return select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0) == 1; } static void *mg_push_to_stdin(void *arg) { struct mg_threadparam *tp = (struct mg_threadparam *) arg; int n, sent, stop = 0; DWORD k; char buf[BUFSIZ]; while (!stop && mg_wait_until_ready(tp->s, 1) && (n = recv(tp->s, buf, sizeof(buf), 0)) > 0) { if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue; for (sent = 0; !stop && sent < n; sent += k) { if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1; } } DBG(("%s", "FORWARED EVERYTHING TO CGI")); CloseHandle(tp->hPipe); MG_FREE(tp); return NULL; } static void *mg_pull_from_stdout(void *arg) { struct mg_threadparam *tp = (struct mg_threadparam *) arg; int k = 0, stop = 0; DWORD n, sent; char buf[BUFSIZ]; while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) { for (sent = 0; !stop && sent < n; sent += k) { if (mg_wait_until_ready(tp->s, 0) && (k = send(tp->s, buf + sent, n - sent, 0)) <= 0) stop = 1; } } DBG(("%s", "EOF FROM CGI")); CloseHandle(tp->hPipe); shutdown(tp->s, 2); // Without this, IO thread may get truncated data closesocket(tp->s); MG_FREE(tp); return NULL; } static void mg_spawn_stdio_thread(sock_t sock, HANDLE hPipe, void *(*func)(void *)) { struct mg_threadparam *tp = (struct mg_threadparam *) MG_MALLOC(sizeof(*tp)); if (tp != NULL) { tp->s = sock; tp->hPipe = hPipe; mg_start_thread(func, tp); } } static void mg_abs_path(const char *utf8_path, char *abs_path, size_t len) { wchar_t buf[MG_MAX_PATH], buf2[MG_MAX_PATH]; to_wchar(utf8_path, buf, ARRAY_SIZE(buf)); GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL); WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0); } static int mg_start_process(const char *interp, const char *cmd, const char *env, const char *envp[], const char *dir, sock_t sock) { STARTUPINFOW si; PROCESS_INFORMATION pi; HANDLE a[2], b[2], me = GetCurrentProcess(); wchar_t wcmd[MG_MAX_PATH], full_dir[MG_MAX_PATH]; char buf[MG_MAX_PATH], buf2[MG_MAX_PATH], buf5[MG_MAX_PATH], buf4[MG_MAX_PATH], cmdline[MG_MAX_PATH]; DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS; FILE *fp; memset(&si, 0, sizeof(si)); memset(&pi, 0, sizeof(pi)); si.cb = sizeof(si); si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; si.hStdError = GetStdHandle(STD_ERROR_HANDLE); CreatePipe(&a[0], &a[1], NULL, 0); CreatePipe(&b[0], &b[1], NULL, 0); DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags); DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags); if (interp == NULL && (fp = mg_fopen(cmd, "r")) != NULL) { buf[0] = buf[1] = '\0'; fgets(buf, sizeof(buf), fp); buf[sizeof(buf) - 1] = '\0'; if (buf[0] == '#' && buf[1] == '!') { interp = buf + 2; /* Trim leading spaces: https://github.com/cesanta/mongoose/issues/489 */ while (*interp != '\0' && isspace(*(unsigned char *) interp)) { interp++; } } fclose(fp); } snprintf(buf, sizeof(buf), "%s/%s", dir, cmd); mg_abs_path(buf, buf2, ARRAY_SIZE(buf2)); mg_abs_path(dir, buf5, ARRAY_SIZE(buf5)); to_wchar(dir, full_dir, ARRAY_SIZE(full_dir)); if (interp != NULL) { mg_abs_path(interp, buf4, ARRAY_SIZE(buf4)); snprintf(cmdline, sizeof(cmdline), "%s \"%s\"", buf4, buf2); } else { snprintf(cmdline, sizeof(cmdline), "\"%s\"", buf2); } to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd)); if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP, (void *) env, full_dir, &si, &pi) != 0) { mg_spawn_stdio_thread(sock, a[1], mg_push_to_stdin); mg_spawn_stdio_thread(sock, b[0], mg_pull_from_stdout); CloseHandle(si.hStdOutput); CloseHandle(si.hStdInput); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); } else { CloseHandle(a[1]); CloseHandle(b[0]); closesocket(sock); } DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess)); /* Not closing a[0] and b[1] because we've used DUPLICATE_CLOSE_SOURCE */ (void) envp; return (pi.hProcess != NULL); } #else static int mg_start_process(const char *interp, const char *cmd, const char *env, const char *envp[], const char *dir, sock_t sock) { char buf[500]; pid_t pid = fork(); (void) env; if (pid == 0) { /* * In Linux `chdir` declared with `warn_unused_result` attribute * To shutup compiler we have yo use result in some way */ int tmp = chdir(dir); (void) tmp; (void) dup2(sock, 0); (void) dup2(sock, 1); closesocket(sock); /* * After exec, all signal handlers are restored to their default values, * with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's * implementation, SIGCHLD's handler will leave unchanged after exec * if it was set to be ignored. Restore it to default action. */ signal(SIGCHLD, SIG_DFL); if (interp == NULL) { execle(cmd, cmd, (char *) 0, envp); /* (char *) 0 to squash warning */ } else { execle(interp, interp, cmd, (char *) 0, envp); } snprintf(buf, sizeof(buf), "Status: 500\r\n\r\n" "500 Server Error: %s%s%s: %s", interp == NULL ? "" : interp, interp == NULL ? "" : " ", cmd, strerror(errno)); send(1, buf, strlen(buf), 0); _exit(EXIT_FAILURE); /* exec call failed */ } return (pid != 0); } #endif /* _WIN32 */ /* * Append VARIABLE=VALUE\0 string to the buffer, and add a respective * pointer into the vars array. */ static char *mg_addenv(struct mg_cgi_env_block *block, const char *fmt, ...) { int n, space; char *added = block->buf + block->len; va_list ap; /* Calculate how much space is left in the buffer */ space = sizeof(block->buf) - (block->len + 2); if (space > 0) { /* Copy VARIABLE=VALUE\0 string into the free space */ va_start(ap, fmt); n = vsnprintf(added, (size_t) space, fmt, ap); va_end(ap); /* Make sure we do not overflow buffer and the envp array */ if (n > 0 && n + 1 < space && block->nvars < (int) ARRAY_SIZE(block->vars) - 2) { /* Append a pointer to the added string into the envp array */ block->vars[block->nvars++] = added; /* Bump up used length counter. Include \0 terminator */ block->len += n + 1; } } return added; } static void mg_addenv2(struct mg_cgi_env_block *blk, const char *name) { const char *s; if ((s = getenv(name)) != NULL) mg_addenv(blk, "%s=%s", name, s); } static void mg_prepare_cgi_environment(struct mg_connection *nc, const char *prog, const struct mg_str *path_info, const struct http_message *hm, const struct mg_serve_http_opts *opts, struct mg_cgi_env_block *blk) { const char *s; struct mg_str *h; char *p; size_t i; char buf[100]; size_t path_info_len = path_info != NULL ? path_info->len : 0; blk->len = blk->nvars = 0; blk->nc = nc; if ((s = getenv("SERVER_NAME")) != NULL) { mg_addenv(blk, "SERVER_NAME=%s", s); } else { mg_sock_to_str(nc->sock, buf, sizeof(buf), 3); mg_addenv(blk, "SERVER_NAME=%s", buf); } mg_addenv(blk, "SERVER_ROOT=%s", opts->document_root); mg_addenv(blk, "DOCUMENT_ROOT=%s", opts->document_root); mg_addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MG_VERSION); /* Prepare the environment block */ mg_addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1"); mg_addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1"); mg_addenv(blk, "%s", "REDIRECT_STATUS=200"); /* For PHP */ mg_addenv(blk, "REQUEST_METHOD=%.*s", (int) hm->method.len, hm->method.p); mg_addenv(blk, "REQUEST_URI=%.*s%s%.*s", (int) hm->uri.len, hm->uri.p, hm->query_string.len == 0 ? "" : "?", (int) hm->query_string.len, hm->query_string.p); mg_conn_addr_to_str(nc, buf, sizeof(buf), MG_SOCK_STRINGIFY_REMOTE | MG_SOCK_STRINGIFY_IP); mg_addenv(blk, "REMOTE_ADDR=%s", buf); mg_conn_addr_to_str(nc, buf, sizeof(buf), MG_SOCK_STRINGIFY_PORT); mg_addenv(blk, "SERVER_PORT=%s", buf); s = hm->uri.p + hm->uri.len - path_info_len - 1; if (*s == '/') { const char *base_name = strrchr(prog, DIRSEP); mg_addenv(blk, "SCRIPT_NAME=%.*s/%s", (int) (s - hm->uri.p), hm->uri.p, (base_name != NULL ? base_name + 1 : prog)); } else { mg_addenv(blk, "SCRIPT_NAME=%.*s", (int) (s - hm->uri.p + 1), hm->uri.p); } mg_addenv(blk, "SCRIPT_FILENAME=%s", prog); if (path_info != NULL && path_info->len > 0) { mg_addenv(blk, "PATH_INFO=%.*s", (int) path_info->len, path_info->p); /* Not really translated... */ mg_addenv(blk, "PATH_TRANSLATED=%.*s", (int) path_info->len, path_info->p); } #if MG_ENABLE_SSL mg_addenv(blk, "HTTPS=%s", (nc->flags & MG_F_SSL ? "on" : "off")); #else mg_addenv(blk, "HTTPS=off"); #endif if ((h = mg_get_http_header((struct http_message *) hm, "Content-Type")) != NULL) { mg_addenv(blk, "CONTENT_TYPE=%.*s", (int) h->len, h->p); } if (hm->query_string.len > 0) { mg_addenv(blk, "QUERY_STRING=%.*s", (int) hm->query_string.len, hm->query_string.p); } if ((h = mg_get_http_header((struct http_message *) hm, "Content-Length")) != NULL) { mg_addenv(blk, "CONTENT_LENGTH=%.*s", (int) h->len, h->p); } mg_addenv2(blk, "PATH"); mg_addenv2(blk, "TMP"); mg_addenv2(blk, "TEMP"); mg_addenv2(blk, "TMPDIR"); mg_addenv2(blk, "PERLLIB"); mg_addenv2(blk, MG_ENV_EXPORT_TO_CGI); #ifdef _WIN32 mg_addenv2(blk, "COMSPEC"); mg_addenv2(blk, "SYSTEMROOT"); mg_addenv2(blk, "SystemDrive"); mg_addenv2(blk, "ProgramFiles"); mg_addenv2(blk, "ProgramFiles(x86)"); mg_addenv2(blk, "CommonProgramFiles(x86)"); #else mg_addenv2(blk, "LD_LIBRARY_PATH"); #endif /* _WIN32 */ /* Add all headers as HTTP_* variables */ for (i = 0; hm->header_names[i].len > 0; i++) { p = mg_addenv(blk, "HTTP_%.*s=%.*s", (int) hm->header_names[i].len, hm->header_names[i].p, (int) hm->header_values[i].len, hm->header_values[i].p); /* Convert variable name into uppercase, and change - to _ */ for (; *p != '=' && *p != '\0'; p++) { if (*p == '-') *p = '_'; *p = (char) toupper(*(unsigned char *) p); } } blk->vars[blk->nvars++] = NULL; blk->buf[blk->len++] = '\0'; } static void mg_cgi_ev_handler(struct mg_connection *cgi_nc, int ev, void *ev_data MG_UD_ARG(void *user_data)) { #if !MG_ENABLE_CALLBACK_USERDATA void *user_data = cgi_nc->user_data; #endif struct mg_connection *nc = (struct mg_connection *) user_data; (void) ev_data; if (nc == NULL) { /* The corresponding network connection was closed. */ cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY; return; } switch (ev) { case MG_EV_RECV: /* * CGI script does not output reply line, like "HTTP/1.1 CODE XXXXX\n" * It outputs headers, then body. Headers might include "Status" * header, which changes CODE, and it might include "Location" header * which changes CODE to 302. * * Therefore we do not send the output from the CGI script to the user * until all CGI headers are received. * * Here we parse the output from the CGI script, and if all headers has * been received, send appropriate reply line, and forward all * received headers to the client. */ if (nc->flags & MG_F_HTTP_CGI_PARSE_HEADERS) { struct mbuf *io = &cgi_nc->recv_mbuf; int len = mg_http_get_request_len(io->buf, io->len); if (len == 0) break; if (len < 0 || io->len > MG_MAX_HTTP_REQUEST_SIZE) { cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY; mg_http_send_error(nc, 500, "Bad headers"); } else { struct http_message hm; struct mg_str *h; mg_http_parse_headers(io->buf, io->buf + io->len, io->len, &hm); if (mg_get_http_header(&hm, "Location") != NULL) { mg_printf(nc, "%s", "HTTP/1.1 302 Moved\r\n"); } else if ((h = mg_get_http_header(&hm, "Status")) != NULL) { mg_printf(nc, "HTTP/1.1 %.*s\r\n", (int) h->len, h->p); } else { mg_printf(nc, "%s", "HTTP/1.1 200 OK\r\n"); } } nc->flags &= ~MG_F_HTTP_CGI_PARSE_HEADERS; } if (!(nc->flags & MG_F_HTTP_CGI_PARSE_HEADERS)) { mg_forward(cgi_nc, nc); } break; case MG_EV_CLOSE: DBG(("%p CLOSE", cgi_nc)); mg_http_free_proto_data_cgi(&mg_http_get_proto_data(nc)->cgi); nc->flags |= MG_F_SEND_AND_CLOSE; break; } } MG_INTERNAL void mg_handle_cgi(struct mg_connection *nc, const char *prog, const struct mg_str *path_info, const struct http_message *hm, const struct mg_serve_http_opts *opts) { struct mg_cgi_env_block blk; char dir[MG_MAX_PATH]; const char *p; sock_t fds[2]; DBG(("%p [%s]", nc, prog)); mg_prepare_cgi_environment(nc, prog, path_info, hm, opts, &blk); /* * CGI must be executed in its own directory. 'dir' must point to the * directory containing executable program, 'p' must point to the * executable program name relative to 'dir'. */ if ((p = strrchr(prog, DIRSEP)) == NULL) { snprintf(dir, sizeof(dir), "%s", "."); } else { snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog); prog = p + 1; } if (!mg_socketpair(fds, SOCK_STREAM)) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; return; } #ifndef _WIN32 struct sigaction sa; sigemptyset(&sa.sa_mask); sa.sa_handler = SIG_IGN; sa.sa_flags = 0; sigaction(SIGCHLD, &sa, NULL); #endif if (mg_start_process(opts->cgi_interpreter, prog, blk.buf, blk.vars, dir, fds[1]) != 0) { struct mg_connection *cgi_nc = mg_add_sock(nc->mgr, fds[0], mg_cgi_ev_handler MG_UD_ARG(nc)); struct mg_http_proto_data *cgi_pd = mg_http_get_proto_data(nc); cgi_pd->cgi.cgi_nc = cgi_nc; #if !MG_ENABLE_CALLBACK_USERDATA cgi_pd->cgi.cgi_nc->user_data = nc; #endif nc->flags |= MG_F_HTTP_CGI_PARSE_HEADERS; /* Push POST data to the CGI */ if (hm->body.len > 0) { mg_send(cgi_pd->cgi.cgi_nc, hm->body.p, hm->body.len); } mbuf_remove(&nc->recv_mbuf, nc->recv_mbuf.len); } else { closesocket(fds[0]); mg_http_send_error(nc, 500, "CGI failure"); } #ifndef _WIN32 closesocket(fds[1]); /* On Windows, CGI stdio thread closes that socket */ #endif } MG_INTERNAL void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d) { if (d == NULL) return; if (d->cgi_nc != NULL) { d->cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY; d->cgi_nc->user_data = NULL; } memset(d, 0, sizeof(*d)); } #endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_http_ssi.c" #endif /* * Copyright (c) 2014-2016 Cesanta Software Limited * All rights reserved */ #if MG_ENABLE_HTTP && MG_ENABLE_HTTP_SSI && MG_ENABLE_FILESYSTEM static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm, const char *path, FILE *fp, int include_level, const struct mg_serve_http_opts *opts); static void mg_send_file_data(struct mg_connection *nc, FILE *fp) { char buf[BUFSIZ]; size_t n; while ((n = mg_fread(buf, 1, sizeof(buf), fp)) > 0) { mg_send(nc, buf, n); } } static void mg_do_ssi_include(struct mg_connection *nc, struct http_message *hm, const char *ssi, char *tag, int include_level, const struct mg_serve_http_opts *opts) { char file_name[MG_MAX_PATH], path[MG_MAX_PATH], *p; FILE *fp; /* * sscanf() is safe here, since send_ssi_file() also uses buffer * of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN. */ if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) { /* File name is relative to the webserver root */ snprintf(path, sizeof(path), "%s/%s", opts->document_root, file_name); } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) { /* * File name is relative to the webserver working directory * or it is absolute system path */ snprintf(path, sizeof(path), "%s", file_name); } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 || sscanf(tag, " \"%[^\"]\"", file_name) == 1) { /* File name is relative to the currect document */ snprintf(path, sizeof(path), "%s", ssi); if ((p = strrchr(path, DIRSEP)) != NULL) { p[1] = '\0'; } snprintf(path + strlen(path), sizeof(path) - strlen(path), "%s", file_name); } else { mg_printf(nc, "Bad SSI #include: [%s]", tag); return; } if ((fp = mg_fopen(path, "rb")) == NULL) { mg_printf(nc, "SSI include error: mg_fopen(%s): %s", path, strerror(mg_get_errno())); } else { mg_set_close_on_exec((sock_t) fileno(fp)); if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) > 0) { mg_send_ssi_file(nc, hm, path, fp, include_level + 1, opts); } else { mg_send_file_data(nc, fp); } fclose(fp); } } #if MG_ENABLE_HTTP_SSI_EXEC static void do_ssi_exec(struct mg_connection *nc, char *tag) { char cmd[BUFSIZ]; FILE *fp; if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) { mg_printf(nc, "Bad SSI #exec: [%s]", tag); } else if ((fp = popen(cmd, "r")) == NULL) { mg_printf(nc, "Cannot SSI #exec: [%s]: %s", cmd, strerror(mg_get_errno())); } else { mg_send_file_data(nc, fp); pclose(fp); } } #endif /* MG_ENABLE_HTTP_SSI_EXEC */ /* * SSI directive has the following format: * <!--#directive parameter=value parameter=value --> */ static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm, const char *path, FILE *fp, int include_level, const struct mg_serve_http_opts *opts) { static const struct mg_str btag = MG_MK_STR("<!--#"); static const struct mg_str d_include = MG_MK_STR("include"); static const struct mg_str d_call = MG_MK_STR("call"); #if MG_ENABLE_HTTP_SSI_EXEC static const struct mg_str d_exec = MG_MK_STR("exec"); #endif char buf[BUFSIZ], *p = buf + btag.len; /* p points to SSI directive */ int ch, len, in_ssi_tag; if (include_level > 10) { mg_printf(nc, "SSI #include level is too deep (%s)", path); return; } in_ssi_tag = len = 0; while ((ch = fgetc(fp)) != EOF) { if (in_ssi_tag && ch == '>' && buf[len - 1] == '-' && buf[len - 2] == '-') { size_t i = len - 2; in_ssi_tag = 0; /* Trim closing --> */ buf[i--] = '\0'; while (i > 0 && buf[i] == ' ') { buf[i--] = '\0'; } /* Handle known SSI directives */ if (strncmp(p, d_include.p, d_include.len) == 0) { mg_do_ssi_include(nc, hm, path, p + d_include.len + 1, include_level, opts); } else if (strncmp(p, d_call.p, d_call.len) == 0) { struct mg_ssi_call_ctx cctx; memset(&cctx, 0, sizeof(cctx)); cctx.req = hm; cctx.file = mg_mk_str(path); cctx.arg = mg_mk_str(p + d_call.len + 1); mg_call(nc, NULL, nc->user_data, MG_EV_SSI_CALL, (void *) cctx.arg.p); /* NUL added above */ mg_call(nc, NULL, nc->user_data, MG_EV_SSI_CALL_CTX, &cctx); #if MG_ENABLE_HTTP_SSI_EXEC } else if (strncmp(p, d_exec.p, d_exec.len) == 0) { do_ssi_exec(nc, p + d_exec.len + 1); #endif } else { /* Silently ignore unknown SSI directive. */ } len = 0; } else if (ch == '<') { in_ssi_tag = 1; if (len > 0) { mg_send(nc, buf, (size_t) len); } len = 0; buf[len++] = ch & 0xff; } else if (in_ssi_tag) { if (len == (int) btag.len && strncmp(buf, btag.p, btag.len) != 0) { /* Not an SSI tag */ in_ssi_tag = 0; } else if (len == (int) sizeof(buf) - 2) { mg_printf(nc, "%s: SSI tag is too large", path); len = 0; } buf[len++] = ch & 0xff; } else { buf[len++] = ch & 0xff; if (len == (int) sizeof(buf)) { mg_send(nc, buf, (size_t) len); len = 0; } } } /* Send the rest of buffered data */ if (len > 0) { mg_send(nc, buf, (size_t) len); } } MG_INTERNAL void mg_handle_ssi_request(struct mg_connection *nc, struct http_message *hm, const char *path, const struct mg_serve_http_opts *opts) { FILE *fp; struct mg_str mime_type; DBG(("%p %s", nc, path)); if ((fp = mg_fopen(path, "rb")) == NULL) { mg_http_send_error(nc, 404, NULL); } else { mg_set_close_on_exec((sock_t) fileno(fp)); mime_type = mg_get_mime_type(path, "text/plain", opts); mg_send_response_line(nc, 200, opts->extra_headers); mg_printf(nc, "Content-Type: %.*s\r\n" "Connection: close\r\n\r\n", (int) mime_type.len, mime_type.p); mg_send_ssi_file(nc, hm, path, fp, 0, opts); fclose(fp); nc->flags |= MG_F_SEND_AND_CLOSE; } } #endif /* MG_ENABLE_HTTP_SSI && MG_ENABLE_HTTP && MG_ENABLE_FILESYSTEM */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_http_webdav.c" #endif /* * Copyright (c) 2014-2016 Cesanta Software Limited * All rights reserved */ #if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV MG_INTERNAL int mg_is_dav_request(const struct mg_str *s) { static const char *methods[] = { "PUT", "DELETE", "MKCOL", "PROPFIND", "MOVE" #if MG_ENABLE_FAKE_DAVLOCK , "LOCK", "UNLOCK" #endif }; size_t i; for (i = 0; i < ARRAY_SIZE(methods); i++) { if (mg_vcmp(s, methods[i]) == 0) { return 1; } } return 0; } static int mg_mkdir(const char *path, uint32_t mode) { #ifndef _WIN32 return mkdir(path, mode); #else (void) mode; return _mkdir(path); #endif } static void mg_print_props(struct mg_connection *nc, const char *name, cs_stat_t *stp) { char mtime[64]; time_t t = stp->st_mtime; /* store in local variable for NDK compile */ struct mg_str name_esc = mg_url_encode(mg_mk_str(name)); mg_gmt_time_string(mtime, sizeof(mtime), &t); mg_printf(nc, "<d:response>" "<d:href>%s</d:href>" "<d:propstat>" "<d:prop>" "<d:resourcetype>%s</d:resourcetype>" "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>" "<d:getlastmodified>%s</d:getlastmodified>" "</d:prop>" "<d:status>HTTP/1.1 200 OK</d:status>" "</d:propstat>" "</d:response>\n", name_esc.p, S_ISDIR(stp->st_mode) ? "<d:collection/>" : "", (int64_t) stp->st_size, mtime); free((void *) name_esc.p); } MG_INTERNAL void mg_handle_propfind(struct mg_connection *nc, const char *path, cs_stat_t *stp, struct http_message *hm, struct mg_serve_http_opts *opts) { static const char header[] = "HTTP/1.1 207 Multi-Status\r\n" "Connection: close\r\n" "Content-Type: text/xml; charset=utf-8\r\n\r\n" "<?xml version=\"1.0\" encoding=\"utf-8\"?>" "<d:multistatus xmlns:d='DAV:'>\n"; static const char footer[] = "</d:multistatus>\n"; const struct mg_str *depth = mg_get_http_header(hm, "Depth"); /* Print properties for the requested resource itself */ if (S_ISDIR(stp->st_mode) && strcmp(opts->enable_directory_listing, "yes") != 0) { mg_printf(nc, "%s", "HTTP/1.1 403 Directory Listing Denied\r\n\r\n"); } else { char uri[MG_MAX_PATH]; mg_send(nc, header, sizeof(header) - 1); snprintf(uri, sizeof(uri), "%.*s", (int) hm->uri.len, hm->uri.p); mg_print_props(nc, uri, stp); if (S_ISDIR(stp->st_mode) && (depth == NULL || mg_vcmp(depth, "0") != 0)) { mg_scan_directory(nc, path, opts, mg_print_props); } mg_send(nc, footer, sizeof(footer) - 1); nc->flags |= MG_F_SEND_AND_CLOSE; } } #if MG_ENABLE_FAKE_DAVLOCK /* * Windows explorer (probably there are another WebDav clients like it) * requires LOCK support in webdav. W/out this, it still works, but fails * to save file: shows error message and offers "Save As". * "Save as" works, but this message is very annoying. * This is fake lock, which doesn't lock something, just returns LOCK token, * UNLOCK always answers "OK". * With this fake LOCK Windows Explorer looks happy and saves file. * NOTE: that is not DAV LOCK imlementation, it is just a way to shut up * Windows native DAV client. This is why FAKE LOCK is not enabed by default */ MG_INTERNAL void mg_handle_lock(struct mg_connection *nc, const char *path) { static const char *reply = "HTTP/1.1 207 Multi-Status\r\n" "Connection: close\r\n" "Content-Type: text/xml; charset=utf-8\r\n\r\n" "<?xml version=\"1.0\" encoding=\"utf-8\"?>" "<d:multistatus xmlns:d='DAV:'>\n" "<D:lockdiscovery>\n" "<D:activelock>\n" "<D:locktoken>\n" "<D:href>\n" "opaquelocktoken:%s%u" "</D:href>" "</D:locktoken>" "</D:activelock>\n" "</D:lockdiscovery>" "</d:multistatus>\n"; mg_printf(nc, reply, path, (unsigned int) mg_time()); nc->flags |= MG_F_SEND_AND_CLOSE; } #endif MG_INTERNAL void mg_handle_mkcol(struct mg_connection *nc, const char *path, struct http_message *hm) { int status_code = 500; if (hm->body.len != (size_t) ~0 && hm->body.len > 0) { status_code = 415; } else if (!mg_mkdir(path, 0755)) { status_code = 201; } else if (errno == EEXIST) { status_code = 405; } else if (errno == EACCES) { status_code = 403; } else if (errno == ENOENT) { status_code = 409; } else { status_code = 500; } mg_http_send_error(nc, status_code, NULL); } static int mg_remove_directory(const struct mg_serve_http_opts *opts, const char *dir) { char path[MG_MAX_PATH]; struct dirent *dp; cs_stat_t st; DIR *dirp; if ((dirp = opendir(dir)) == NULL) return 0; while ((dp = readdir(dirp)) != NULL) { if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) { continue; } snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name); mg_stat(path, &st); if (S_ISDIR(st.st_mode)) { mg_remove_directory(opts, path); } else { remove(path); } } closedir(dirp); rmdir(dir); return 1; } MG_INTERNAL void mg_handle_move(struct mg_connection *c, const struct mg_serve_http_opts *opts, const char *path, struct http_message *hm) { const struct mg_str *dest = mg_get_http_header(hm, "Destination"); if (dest == NULL) { mg_http_send_error(c, 411, NULL); } else { const char *p = (char *) memchr(dest->p, '/', dest->len); if (p != NULL && p[1] == '/' && (p = (char *) memchr(p + 2, '/', dest->p + dest->len - p)) != NULL) { char buf[MG_MAX_PATH]; snprintf(buf, sizeof(buf), "%s%.*s", opts->dav_document_root, (int) (dest->p + dest->len - p), p); if (rename(path, buf) == 0) { mg_http_send_error(c, 200, NULL); } else { mg_http_send_error(c, 418, NULL); } } else { mg_http_send_error(c, 500, NULL); } } } MG_INTERNAL void mg_handle_delete(struct mg_connection *nc, const struct mg_serve_http_opts *opts, const char *path) { cs_stat_t st; if (mg_stat(path, &st) != 0) { mg_http_send_error(nc, 404, NULL); } else if (S_ISDIR(st.st_mode)) { mg_remove_directory(opts, path); mg_http_send_error(nc, 204, NULL); } else if (remove(path) == 0) { mg_http_send_error(nc, 204, NULL); } else { mg_http_send_error(nc, 423, NULL); } } /* Return -1 on error, 1 on success. */ static int mg_create_itermediate_directories(const char *path) { const char *s; /* Create intermediate directories if they do not exist */ for (s = path + 1; *s != '\0'; s++) { if (*s == '/') { char buf[MG_MAX_PATH]; cs_stat_t st; snprintf(buf, sizeof(buf), "%.*s", (int) (s - path), path); buf[sizeof(buf) - 1] = '\0'; if (mg_stat(buf, &st) != 0 && mg_mkdir(buf, 0755) != 0) { return -1; } } } return 1; } MG_INTERNAL void mg_handle_put(struct mg_connection *nc, const char *path, struct http_message *hm) { struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); cs_stat_t st; const struct mg_str *cl_hdr = mg_get_http_header(hm, "Content-Length"); int rc, status_code = mg_stat(path, &st) == 0 ? 200 : 201; mg_http_free_proto_data_file(&pd->file); if ((rc = mg_create_itermediate_directories(path)) == 0) { mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code); } else if (rc == -1) { mg_http_send_error(nc, 500, NULL); } else if (cl_hdr == NULL) { mg_http_send_error(nc, 411, NULL); } else if ((pd->file.fp = mg_fopen(path, "w+b")) == NULL) { mg_http_send_error(nc, 500, NULL); } else { const struct mg_str *range_hdr = mg_get_http_header(hm, "Content-Range"); int64_t r1 = 0, r2 = 0; pd->file.type = DATA_PUT; mg_set_close_on_exec((sock_t) fileno(pd->file.fp)); pd->file.cl = to64(cl_hdr->p); if (range_hdr != NULL && mg_http_parse_range_header(range_hdr, &r1, &r2) > 0) { status_code = 206; fseeko(pd->file.fp, r1, SEEK_SET); pd->file.cl = r2 > r1 ? r2 - r1 + 1 : pd->file.cl - r1; } mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code); /* Remove HTTP request from the mbuf, leave only payload */ mbuf_remove(&nc->recv_mbuf, hm->message.len - hm->body.len); mg_http_transfer_file_data(nc); } } #endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_http_websocket.c" #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ #if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET /* Amalgamated: #include "common/cs_sha1.h" */ #ifndef MG_WEBSOCKET_PING_INTERVAL_SECONDS #define MG_WEBSOCKET_PING_INTERVAL_SECONDS 5 #endif #define FLAGS_MASK_FIN (1 << 7) #define FLAGS_MASK_OP 0x0f static int mg_is_ws_fragment(unsigned char flags) { return (flags & FLAGS_MASK_FIN) == 0 || (flags & FLAGS_MASK_OP) == WEBSOCKET_OP_CONTINUE; } static int mg_is_ws_first_fragment(unsigned char flags) { return (flags & FLAGS_MASK_FIN) == 0 && (flags & FLAGS_MASK_OP) != WEBSOCKET_OP_CONTINUE; } static int mg_is_ws_control_frame(unsigned char flags) { unsigned char op = (flags & FLAGS_MASK_OP); return op == WEBSOCKET_OP_CLOSE || op == WEBSOCKET_OP_PING || op == WEBSOCKET_OP_PONG; } static void mg_handle_incoming_websocket_frame(struct mg_connection *nc, struct websocket_message *wsm) { if (wsm->flags & 0x8) { mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_CONTROL_FRAME, wsm); } else { mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_FRAME, wsm); } } static struct mg_ws_proto_data *mg_ws_get_proto_data(struct mg_connection *nc) { struct mg_http_proto_data *htd = mg_http_get_proto_data(nc); return (htd != NULL ? &htd->ws_data : NULL); } /* * Sends a Close websocket frame with the given data, and closes the underlying * connection. If `len` is ~0, strlen(data) is used. */ static void mg_ws_close(struct mg_connection *nc, const void *data, size_t len) { if ((int) len == ~0) { len = strlen((const char *) data); } mg_send_websocket_frame(nc, WEBSOCKET_OP_CLOSE, data, len); nc->flags |= MG_F_SEND_AND_CLOSE; } static int mg_deliver_websocket_data(struct mg_connection *nc) { /* Using unsigned char *, cause of integer arithmetic below */ uint64_t i, data_len = 0, frame_len = 0, new_data_len = nc->recv_mbuf.len, len, mask_len = 0, header_len = 0; struct mg_ws_proto_data *wsd = mg_ws_get_proto_data(nc); unsigned char *new_data = (unsigned char *) nc->recv_mbuf.buf, *e = (unsigned char *) nc->recv_mbuf.buf + nc->recv_mbuf.len; uint8_t flags; int ok, reass; if (wsd->reass_len > 0) { /* * We already have some previously received data which we need to * reassemble and deliver to the client code when we get the final * fragment. * * NOTE: it doesn't mean that the current message must be a continuation: * it might be a control frame (Close, Ping or Pong), which should be * handled without breaking the fragmented message. */ size_t existing_len = wsd->reass_len; assert(new_data_len >= existing_len); new_data += existing_len; new_data_len -= existing_len; } flags = new_data[0]; reass = new_data_len > 0 && mg_is_ws_fragment(flags) && !(nc->flags & MG_F_WEBSOCKET_NO_DEFRAG); if (reass && mg_is_ws_control_frame(flags)) { /* * Control frames can't be fragmented, so if we encounter fragmented * control frame, close connection immediately. */ mg_ws_close(nc, "fragmented control frames are illegal", ~0); return 0; } else if (new_data_len > 0 && !reass && !mg_is_ws_control_frame(flags) && wsd->reass_len > 0) { /* * When in the middle of a fragmented message, only the continuations * and control frames are allowed. */ mg_ws_close(nc, "non-continuation in the middle of a fragmented message", ~0); return 0; } if (new_data_len >= 2) { len = new_data[1] & 0x7f; mask_len = new_data[1] & FLAGS_MASK_FIN ? 4 : 0; if (len < 126 && new_data_len >= mask_len) { data_len = len; header_len = 2 + mask_len; } else if (len == 126 && new_data_len >= 4 + mask_len) { header_len = 4 + mask_len; data_len = ntohs(*(uint16_t *) &new_data[2]); } else if (new_data_len >= 10 + mask_len) { header_len = 10 + mask_len; data_len = (((uint64_t) ntohl(*(uint32_t *) &new_data[2])) << 32) + ntohl(*(uint32_t *) &new_data[6]); } } frame_len = header_len + data_len; ok = (frame_len > 0 && frame_len <= new_data_len); /* Check for overflow */ if (frame_len < header_len || frame_len < data_len) { ok = 0; mg_ws_close(nc, "overflowed message", ~0); } if (ok) { size_t cleanup_len = 0; struct websocket_message wsm; wsm.size = (size_t) data_len; wsm.data = new_data + header_len; wsm.flags = flags; /* Apply mask if necessary */ if (mask_len > 0) { for (i = 0; i < data_len; i++) { new_data[i + header_len] ^= (new_data + header_len - mask_len)[i % 4]; } } if (reass) { /* This is a message fragment */ if (mg_is_ws_first_fragment(flags)) { /* * On the first fragmented frame, skip the first byte (op) and also * reset size to 1 (op), it'll be incremented with the data len below. */ new_data += 1; wsd->reass_len = 1 /* op */; } /* Append this frame to the reassembled buffer */ memmove(new_data, wsm.data, e - wsm.data); wsd->reass_len += wsm.size; nc->recv_mbuf.len -= wsm.data - new_data; if (flags & FLAGS_MASK_FIN) { /* On last fragmented frame - call user handler and remove data */ wsm.flags = FLAGS_MASK_FIN | nc->recv_mbuf.buf[0]; wsm.data = (unsigned char *) nc->recv_mbuf.buf + 1 /* op */; wsm.size = wsd->reass_len - 1 /* op */; cleanup_len = wsd->reass_len; wsd->reass_len = 0; /* Pass reassembled message to the client code. */ mg_handle_incoming_websocket_frame(nc, &wsm); mbuf_remove(&nc->recv_mbuf, cleanup_len); /* Cleanup frame */ } } else { /* * This is a complete message, not a fragment. It might happen in between * of a fragmented message (in this case, WebSocket protocol requires * current message to be a control frame). */ cleanup_len = (size_t) frame_len; /* First of all, check if we need to react on a control frame. */ switch (flags & FLAGS_MASK_OP) { case WEBSOCKET_OP_PING: mg_send_websocket_frame(nc, WEBSOCKET_OP_PONG, wsm.data, wsm.size); break; case WEBSOCKET_OP_CLOSE: mg_ws_close(nc, wsm.data, wsm.size); break; } /* Pass received message to the client code. */ mg_handle_incoming_websocket_frame(nc, &wsm); /* Cleanup frame */ memmove(nc->recv_mbuf.buf + wsd->reass_len, nc->recv_mbuf.buf + wsd->reass_len + cleanup_len, nc->recv_mbuf.len - wsd->reass_len - cleanup_len); nc->recv_mbuf.len -= cleanup_len; } } return ok; } struct ws_mask_ctx { size_t pos; /* zero means unmasked */ uint32_t mask; }; static uint32_t mg_ws_random_mask(void) { uint32_t mask; /* * The spec requires WS client to generate hard to * guess mask keys. From RFC6455, Section 5.3: * * The unpredictability of the masking key is essential to prevent * authors of malicious applications from selecting the bytes that appear on * the wire. * * Hence this feature is essential when the actual end user of this API * is untrusted code that wouldn't have access to a lower level net API * anyway (e.g. web browsers). Hence this feature is low prio for most * mongoose use cases and thus can be disabled, e.g. when porting to a platform * that lacks rand(). */ #if MG_DISABLE_WS_RANDOM_MASK mask = 0xefbeadde; /* generated with a random number generator, I swear */ #else if (sizeof(long) >= 4) { mask = (uint32_t) rand(); } else if (sizeof(long) == 2) { mask = (uint32_t) rand() << 16 | (uint32_t) rand(); } #endif return mask; } static void mg_send_ws_header(struct mg_connection *nc, int op, size_t len, struct ws_mask_ctx *ctx) { int header_len; unsigned char header[10]; header[0] = (op & WEBSOCKET_DONT_FIN ? 0x0 : FLAGS_MASK_FIN) | (op & FLAGS_MASK_OP); if (len < 126) { header[1] = (unsigned char) len; header_len = 2; } else if (len < 65535) { uint16_t tmp = htons((uint16_t) len); header[1] = 126; memcpy(&header[2], &tmp, sizeof(tmp)); header_len = 4; } else { uint32_t tmp; header[1] = 127; tmp = htonl((uint32_t)((uint64_t) len >> 32)); memcpy(&header[2], &tmp, sizeof(tmp)); tmp = htonl((uint32_t)(len & 0xffffffff)); memcpy(&header[6], &tmp, sizeof(tmp)); header_len = 10; } /* client connections enable masking */ if (nc->listener == NULL) { header[1] |= 1 << 7; /* set masking flag */ mg_send(nc, header, header_len); ctx->mask = mg_ws_random_mask(); mg_send(nc, &ctx->mask, sizeof(ctx->mask)); ctx->pos = nc->send_mbuf.len; } else { mg_send(nc, header, header_len); ctx->pos = 0; } } static void mg_ws_mask_frame(struct mbuf *mbuf, struct ws_mask_ctx *ctx) { size_t i; if (ctx->pos == 0) return; for (i = 0; i < (mbuf->len - ctx->pos); i++) { mbuf->buf[ctx->pos + i] ^= ((char *) &ctx->mask)[i % 4]; } } void mg_send_websocket_frame(struct mg_connection *nc, int op, const void *data, size_t len) { struct ws_mask_ctx ctx; DBG(("%p %d %d", nc, op, (int) len)); mg_send_ws_header(nc, op, len, &ctx); mg_send(nc, data, len); mg_ws_mask_frame(&nc->send_mbuf, &ctx); if (op == WEBSOCKET_OP_CLOSE) { nc->flags |= MG_F_SEND_AND_CLOSE; } } void mg_send_websocket_framev(struct mg_connection *nc, int op, const struct mg_str *strv, int strvcnt) { struct ws_mask_ctx ctx; int i; int len = 0; for (i = 0; i < strvcnt; i++) { len += strv[i].len; } mg_send_ws_header(nc, op, len, &ctx); for (i = 0; i < strvcnt; i++) { mg_send(nc, strv[i].p, strv[i].len); } mg_ws_mask_frame(&nc->send_mbuf, &ctx); if (op == WEBSOCKET_OP_CLOSE) { nc->flags |= MG_F_SEND_AND_CLOSE; } } void mg_printf_websocket_frame(struct mg_connection *nc, int op, const char *fmt, ...) { char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem; va_list ap; int len; va_start(ap, fmt); if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) { mg_send_websocket_frame(nc, op, buf, len); } va_end(ap); if (buf != mem && buf != NULL) { MG_FREE(buf); } } MG_INTERNAL void mg_ws_handler(struct mg_connection *nc, int ev, void *ev_data MG_UD_ARG(void *user_data)) { mg_call(nc, nc->handler, nc->user_data, ev, ev_data); switch (ev) { case MG_EV_RECV: do { } while (mg_deliver_websocket_data(nc)); break; case MG_EV_POLL: /* Ping idle websocket connections */ { time_t now = *(time_t *) ev_data; if (nc->flags & MG_F_IS_WEBSOCKET && now > nc->last_io_time + MG_WEBSOCKET_PING_INTERVAL_SECONDS) { mg_send_websocket_frame(nc, WEBSOCKET_OP_PING, "", 0); } } break; default: break; } #if MG_ENABLE_CALLBACK_USERDATA (void) user_data; #endif } #ifndef MG_EXT_SHA1 void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[], const size_t *msg_lens, uint8_t *digest) { size_t i; cs_sha1_ctx sha_ctx; cs_sha1_init(&sha_ctx); for (i = 0; i < num_msgs; i++) { cs_sha1_update(&sha_ctx, msgs[i], msg_lens[i]); } cs_sha1_final(digest, &sha_ctx); } #else extern void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[], const size_t *msg_lens, uint8_t *digest); #endif MG_INTERNAL void mg_ws_handshake(struct mg_connection *nc, const struct mg_str *key, struct http_message *hm) { static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; const uint8_t *msgs[2] = {(const uint8_t *) key->p, (const uint8_t *) magic}; const size_t msg_lens[2] = {key->len, 36}; unsigned char sha[20]; char b64_sha[30]; struct mg_str *s; mg_hash_sha1_v(2, msgs, msg_lens, sha); mg_base64_encode(sha, sizeof(sha), b64_sha); mg_printf(nc, "%s", "HTTP/1.1 101 Switching Protocols\r\n" "Upgrade: websocket\r\n" "Connection: Upgrade\r\n"); s = mg_get_http_header(hm, "Sec-WebSocket-Protocol"); if (s != NULL) { mg_printf(nc, "Sec-WebSocket-Protocol: %.*s\r\n", (int) s->len, s->p); } mg_printf(nc, "Sec-WebSocket-Accept: %s%s", b64_sha, "\r\n\r\n"); DBG(("%p %.*s %s", nc, (int) key->len, key->p, b64_sha)); } void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path, const char *host, const char *protocol, const char *extra_headers) { mg_send_websocket_handshake3(nc, path, host, protocol, extra_headers, NULL, NULL); } void mg_send_websocket_handshake3(struct mg_connection *nc, const char *path, const char *host, const char *protocol, const char *extra_headers, const char *user, const char *pass) { mg_send_websocket_handshake3v(nc, mg_mk_str(path), mg_mk_str(host), mg_mk_str(protocol), mg_mk_str(extra_headers), mg_mk_str(user), mg_mk_str(pass)); } void mg_send_websocket_handshake3v(struct mg_connection *nc, const struct mg_str path, const struct mg_str host, const struct mg_str protocol, const struct mg_str extra_headers, const struct mg_str user, const struct mg_str pass) { struct mbuf auth; char key[25]; uint32_t nonce[4]; nonce[0] = mg_ws_random_mask(); nonce[1] = mg_ws_random_mask(); nonce[2] = mg_ws_random_mask(); nonce[3] = mg_ws_random_mask(); mg_base64_encode((unsigned char *) &nonce, sizeof(nonce), key); mbuf_init(&auth, 0); if (user.len > 0) { mg_basic_auth_header(user, pass, &auth); } /* * NOTE: the (auth.buf == NULL ? "" : auth.buf) is because cc3200 libc is * broken: it doesn't like zero length to be passed to %.*s * i.e. sprintf("f%.*so", (int)0, NULL), yields `f\0o`. * because it handles NULL specially (and incorrectly). */ mg_printf(nc, "GET %.*s HTTP/1.1\r\n" "Upgrade: websocket\r\n" "Connection: Upgrade\r\n" "%.*s" "Sec-WebSocket-Version: 13\r\n" "Sec-WebSocket-Key: %s\r\n", (int) path.len, path.p, (int) auth.len, (auth.buf == NULL ? "" : auth.buf), key); /* TODO(mkm): take default hostname from http proto data if host == NULL */ if (host.len > 0) { int host_len = (int) (path.p - host.p); /* Account for possible :PORT */ mg_printf(nc, "Host: %.*s\r\n", host_len, host.p); } if (protocol.len > 0) { mg_printf(nc, "Sec-WebSocket-Protocol: %.*s\r\n", (int) protocol.len, protocol.p); } if (extra_headers.len > 0) { mg_printf(nc, "%.*s", (int) extra_headers.len, extra_headers.p); } mg_printf(nc, "\r\n"); nc->flags |= MG_F_IS_WEBSOCKET; mbuf_free(&auth); } void mg_send_websocket_handshake(struct mg_connection *nc, const char *path, const char *extra_headers) { struct mg_str null_str = MG_NULL_STR; mg_send_websocket_handshake3v( nc, mg_mk_str(path), null_str /* host */, null_str /* protocol */, mg_mk_str(extra_headers), null_str /* user */, null_str /* pass */); } struct mg_connection *mg_connect_ws_opt( struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), struct mg_connect_opts opts, const char *url, const char *protocol, const char *extra_headers) { struct mg_str null_str = MG_NULL_STR; struct mg_str host = MG_NULL_STR, path = MG_NULL_STR, user_info = MG_NULL_STR; struct mg_connection *nc = mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http", "ws", "https", "wss", url, &path, &user_info, &host); if (nc != NULL) { mg_send_websocket_handshake3v(nc, path, host, mg_mk_str(protocol), mg_mk_str(extra_headers), user_info, null_str); } return nc; } struct mg_connection *mg_connect_ws( struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), const char *url, const char *protocol, const char *extra_headers) { struct mg_connect_opts opts; memset(&opts, 0, sizeof(opts)); return mg_connect_ws_opt(mgr, MG_CB(ev_handler, user_data), opts, url, protocol, extra_headers); } #endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_util.c" #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ /* Amalgamated: #include "common/cs_base64.h" */ /* Amalgamated: #include "mg_internal.h" */ /* Amalgamated: #include "mg_util.h" */ /* For platforms with limited libc */ #ifndef MAX #define MAX(a, b) ((a) > (b) ? (a) : (b)) #endif const char *mg_skip(const char *s, const char *end, const char *delims, struct mg_str *v) { v->p = s; while (s < end && strchr(delims, *(unsigned char *) s) == NULL) s++; v->len = s - v->p; while (s < end && strchr(delims, *(unsigned char *) s) != NULL) s++; return s; } #if MG_ENABLE_FILESYSTEM && !defined(MG_USER_FILE_FUNCTIONS) int mg_stat(const char *path, cs_stat_t *st) { #ifdef _WIN32 wchar_t wpath[MG_MAX_PATH]; to_wchar(path, wpath, ARRAY_SIZE(wpath)); DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st))); return _wstati64(wpath, st); #else return stat(path, st); #endif } FILE *mg_fopen(const char *path, const char *mode) { #ifdef _WIN32 wchar_t wpath[MG_MAX_PATH], wmode[10]; to_wchar(path, wpath, ARRAY_SIZE(wpath)); to_wchar(mode, wmode, ARRAY_SIZE(wmode)); return _wfopen(wpath, wmode); #else return fopen(path, mode); #endif } int mg_open(const char *path, int flag, int mode) { /* LCOV_EXCL_LINE */ #if defined(_WIN32) && !defined(WINCE) wchar_t wpath[MG_MAX_PATH]; to_wchar(path, wpath, ARRAY_SIZE(wpath)); return _wopen(wpath, flag, mode); #else return open(path, flag, mode); /* LCOV_EXCL_LINE */ #endif } size_t mg_fread(void *ptr, size_t size, size_t count, FILE *f) { return fread(ptr, size, count, f); } size_t mg_fwrite(const void *ptr, size_t size, size_t count, FILE *f) { return fwrite(ptr, size, count, f); } #endif void mg_base64_encode(const unsigned char *src, int src_len, char *dst) { cs_base64_encode(src, src_len, dst); } int mg_base64_decode(const unsigned char *s, int len, char *dst) { return cs_base64_decode(s, len, dst, NULL); } #if MG_ENABLE_THREADS void *mg_start_thread(void *(*f)(void *), void *p) { #ifdef WINCE return (void *) CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) f, p, 0, NULL); #elif defined(_WIN32) return (void *) _beginthread((void(__cdecl *) (void *) ) f, 0, p); #else pthread_t thread_id = (pthread_t) 0; pthread_attr_t attr; (void) pthread_attr_init(&attr); (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); #if defined(MG_STACK_SIZE) && MG_STACK_SIZE > 1 (void) pthread_attr_setstacksize(&attr, MG_STACK_SIZE); #endif pthread_create(&thread_id, &attr, f, p); pthread_attr_destroy(&attr); return (void *) thread_id; #endif } #endif /* MG_ENABLE_THREADS */ /* Set close-on-exec bit for a given socket. */ void mg_set_close_on_exec(sock_t sock) { #if defined(_WIN32) && !defined(WINCE) (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0); #elif defined(__unix__) fcntl(sock, F_SETFD, FD_CLOEXEC); #else (void) sock; #endif } int mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len, int flags) { int is_v6; if (buf == NULL || len <= 0) return 0; memset(buf, 0, len); #if MG_ENABLE_IPV6 is_v6 = sa->sa.sa_family == AF_INET6; #else is_v6 = 0; #endif if (flags & MG_SOCK_STRINGIFY_IP) { #if MG_ENABLE_IPV6 const void *addr = NULL; char *start = buf; socklen_t capacity = len; if (!is_v6) { addr = &sa->sin.sin_addr; } else { addr = (void *) &sa->sin6.sin6_addr; if (flags & MG_SOCK_STRINGIFY_PORT) { *buf = '['; start++; capacity--; } } if (inet_ntop(sa->sa.sa_family, addr, start, capacity) == NULL) { goto cleanup; } #elif defined(_WIN32) || MG_LWIP || (MG_NET_IF == MG_NET_IF_PIC32) /* Only Windoze Vista (and newer) have inet_ntop() */ char *addr_str = inet_ntoa(sa->sin.sin_addr); if (addr_str != NULL) { strncpy(buf, inet_ntoa(sa->sin.sin_addr), len - 1); } else { goto cleanup; } #else if (inet_ntop(AF_INET, (void *) &sa->sin.sin_addr, buf, len) == NULL) { goto cleanup; } #endif } if (flags & MG_SOCK_STRINGIFY_PORT) { int port = ntohs(sa->sin.sin_port); if (flags & MG_SOCK_STRINGIFY_IP) { int buf_len = strlen(buf); snprintf(buf + buf_len, len - (buf_len + 1), "%s:%d", (is_v6 ? "]" : ""), port); } else { snprintf(buf, len, "%d", port); } } return strlen(buf); cleanup: *buf = '\0'; return 0; } int mg_conn_addr_to_str(struct mg_connection *nc, char *buf, size_t len, int flags) { union socket_address sa; memset(&sa, 0, sizeof(sa)); mg_if_get_conn_addr(nc, flags & MG_SOCK_STRINGIFY_REMOTE, &sa); return mg_sock_addr_to_str(&sa, buf, len, flags); } #if MG_ENABLE_HEXDUMP static int mg_hexdump_n(const void *buf, int len, char *dst, int dst_len, int offset) { const unsigned char *p = (const unsigned char *) buf; char ascii[17] = ""; int i, idx, n = 0; for (i = 0; i < len; i++) { idx = i % 16; if (idx == 0) { if (i > 0) n += snprintf(dst + n, MAX(dst_len - n, 0), " %s\n", ascii); n += snprintf(dst + n, MAX(dst_len - n, 0), "%04x ", i + offset); } if (dst_len - n < 0) { return n; } n += snprintf(dst + n, MAX(dst_len - n, 0), " %02x", p[i]); ascii[idx] = p[i] < 0x20 || p[i] > 0x7e ? '.' : p[i]; ascii[idx + 1] = '\0'; } while (i++ % 16) n += snprintf(dst + n, MAX(dst_len - n, 0), "%s", " "); n += snprintf(dst + n, MAX(dst_len - n, 0), " %s\n", ascii); return n; } int mg_hexdump(const void *buf, int len, char *dst, int dst_len) { return mg_hexdump_n(buf, len, dst, dst_len, 0); } void mg_hexdumpf(FILE *fp, const void *buf, int len) { char tmp[80]; int offset = 0, n; while (len > 0) { n = (len < 16 ? len : 16); mg_hexdump_n(((const char *) buf) + offset, n, tmp, sizeof(tmp), offset); fputs(tmp, fp); offset += n; len -= n; } } void mg_hexdump_connection(struct mg_connection *nc, const char *path, const void *buf, int num_bytes, int ev) { FILE *fp = NULL; char src[60], dst[60]; const char *tag = NULL; switch (ev) { case MG_EV_RECV: tag = "<-"; break; case MG_EV_SEND: tag = "->"; break; case MG_EV_ACCEPT: tag = "<A"; break; case MG_EV_CONNECT: tag = "C>"; break; case MG_EV_CLOSE: tag = "XX"; break; } if (tag == NULL) return; /* Don't log MG_EV_TIMER, etc */ if (strcmp(path, "-") == 0) { fp = stdout; } else if (strcmp(path, "--") == 0) { fp = stderr; #if MG_ENABLE_FILESYSTEM } else { fp = mg_fopen(path, "a"); #endif } if (fp == NULL) return; mg_conn_addr_to_str(nc, src, sizeof(src), MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT); mg_conn_addr_to_str(nc, dst, sizeof(dst), MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT | MG_SOCK_STRINGIFY_REMOTE); fprintf(fp, "%lu %p %s %s %s %d\n", (unsigned long) mg_time(), (void *) nc, src, tag, dst, (int) num_bytes); if (num_bytes > 0) { mg_hexdumpf(fp, buf, num_bytes); } if (fp != stdout && fp != stderr) fclose(fp); } #endif int mg_is_big_endian(void) { static const int n = 1; /* TODO(mkm) use compiletime check with 4-byte char literal */ return ((char *) &n)[0] == 0; } DO_NOT_WARN_UNUSED MG_INTERNAL int mg_get_errno(void) { #ifndef WINCE return errno; #else /* TODO(alashkin): translate error codes? */ return GetLastError(); #endif } void mg_mbuf_append_base64_putc(char ch, void *user_data) { struct mbuf *mbuf = (struct mbuf *) user_data; mbuf_append(mbuf, &ch, sizeof(ch)); } void mg_mbuf_append_base64(struct mbuf *mbuf, const void *data, size_t len) { struct cs_base64_ctx ctx; cs_base64_init(&ctx, mg_mbuf_append_base64_putc, mbuf); cs_base64_update(&ctx, (const char *) data, len); cs_base64_finish(&ctx); } void mg_basic_auth_header(const struct mg_str user, const struct mg_str pass, struct mbuf *buf) { const char *header_prefix = "Authorization: Basic "; const char *header_suffix = "\r\n"; struct cs_base64_ctx ctx; cs_base64_init(&ctx, mg_mbuf_append_base64_putc, buf); mbuf_append(buf, header_prefix, strlen(header_prefix)); cs_base64_update(&ctx, user.p, user.len); if (pass.len > 0) { cs_base64_update(&ctx, ":", 1); cs_base64_update(&ctx, pass.p, pass.len); } cs_base64_finish(&ctx); mbuf_append(buf, header_suffix, strlen(header_suffix)); } struct mg_str mg_url_encode_opt(const struct mg_str src, const struct mg_str safe, unsigned int flags) { const char *hex = (flags & MG_URL_ENCODE_F_UPPERCASE_HEX ? "0123456789ABCDEF" : "0123456789abcdef"); size_t i = 0; struct mbuf mb; mbuf_init(&mb, src.len); for (i = 0; i < src.len; i++) { const unsigned char c = *((const unsigned char *) src.p + i); if (isalnum(c) || mg_strchr(safe, c) != NULL) { mbuf_append(&mb, &c, 1); } else if (c == ' ' && (flags & MG_URL_ENCODE_F_SPACE_AS_PLUS)) { mbuf_append(&mb, "+", 1); } else { mbuf_append(&mb, "%", 1); mbuf_append(&mb, &hex[c >> 4], 1); mbuf_append(&mb, &hex[c & 15], 1); } } mbuf_append(&mb, "", 1); mbuf_trim(&mb); return mg_mk_str_n(mb.buf, mb.len - 1); } struct mg_str mg_url_encode(const struct mg_str src) { return mg_url_encode_opt(src, mg_mk_str("._-$,;~()/"), 0); } #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_mqtt.c" #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ #if MG_ENABLE_MQTT #include <string.h> /* Amalgamated: #include "mg_internal.h" */ /* Amalgamated: #include "mg_mqtt.h" */ static uint16_t getu16(const char *p) { const uint8_t *up = (const uint8_t *) p; return (up[0] << 8) + up[1]; } static const char *scanto(const char *p, struct mg_str *s) { s->len = getu16(p); s->p = p + 2; return s->p + s->len; } MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm) { uint8_t header; size_t len = 0, len_len = 0; const char *p, *end, *eop = &io->buf[io->len]; unsigned char lc = 0; int cmd; if (io->len < 2) return MG_MQTT_ERROR_INCOMPLETE_MSG; header = io->buf[0]; cmd = header >> 4; /* decode mqtt variable length */ len = len_len = 0; p = io->buf + 1; while (p < eop) { lc = *((const unsigned char *) p++); len += (lc & 0x7f) << 7 * len_len; len_len++; if (!(lc & 0x80)) break; if (len_len > 4) return MG_MQTT_ERROR_MALFORMED_MSG; } end = p + len; if (lc & 0x80 || end > eop) return MG_MQTT_ERROR_INCOMPLETE_MSG; mm->cmd = cmd; mm->qos = MG_MQTT_GET_QOS(header); switch (cmd) { case MG_MQTT_CMD_CONNECT: { p = scanto(p, &mm->protocol_name); if (p > end - 4) return MG_MQTT_ERROR_MALFORMED_MSG; mm->protocol_version = *(uint8_t *) p++; mm->connect_flags = *(uint8_t *) p++; mm->keep_alive_timer = getu16(p); p += 2; if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; p = scanto(p, &mm->client_id); if (p > end) return MG_MQTT_ERROR_MALFORMED_MSG; if (mm->connect_flags & MG_MQTT_HAS_WILL) { if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; p = scanto(p, &mm->will_topic); } if (mm->connect_flags & MG_MQTT_HAS_WILL) { if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; p = scanto(p, &mm->will_message); } if (mm->connect_flags & MG_MQTT_HAS_USER_NAME) { if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; p = scanto(p, &mm->user_name); } if (mm->connect_flags & MG_MQTT_HAS_PASSWORD) { if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; p = scanto(p, &mm->password); } if (p != end) return MG_MQTT_ERROR_MALFORMED_MSG; LOG(LL_DEBUG, ("%d %2x %d proto [%.*s] client_id [%.*s] will_topic [%.*s] " "will_msg [%.*s] user_name [%.*s] password [%.*s]", (int) len, (int) mm->connect_flags, (int) mm->keep_alive_timer, (int) mm->protocol_name.len, mm->protocol_name.p, (int) mm->client_id.len, mm->client_id.p, (int) mm->will_topic.len, mm->will_topic.p, (int) mm->will_message.len, mm->will_message.p, (int) mm->user_name.len, mm->user_name.p, (int) mm->password.len, mm->password.p)); break; } case MG_MQTT_CMD_CONNACK: if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG; mm->connack_ret_code = p[1]; break; case MG_MQTT_CMD_PUBACK: case MG_MQTT_CMD_PUBREC: case MG_MQTT_CMD_PUBREL: case MG_MQTT_CMD_PUBCOMP: case MG_MQTT_CMD_SUBACK: if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG; mm->message_id = getu16(p); p += 2; break; case MG_MQTT_CMD_PUBLISH: { p = scanto(p, &mm->topic); if (p > end) return MG_MQTT_ERROR_MALFORMED_MSG; if (mm->qos > 0) { if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG; mm->message_id = getu16(p); p += 2; } mm->payload.p = p; mm->payload.len = end - p; break; } case MG_MQTT_CMD_SUBSCRIBE: if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG; mm->message_id = getu16(p); p += 2; /* * topic expressions are left in the payload and can be parsed with * `mg_mqtt_next_subscribe_topic` */ mm->payload.p = p; mm->payload.len = end - p; break; default: /* Unhandled command */ break; } mm->len = end - io->buf; return mm->len; } static void mqtt_handler(struct mg_connection *nc, int ev, void *ev_data MG_UD_ARG(void *user_data)) { struct mbuf *io = &nc->recv_mbuf; struct mg_mqtt_message mm; memset(&mm, 0, sizeof(mm)); nc->handler(nc, ev, ev_data MG_UD_ARG(user_data)); switch (ev) { case MG_EV_ACCEPT: if (nc->proto_data == NULL) mg_set_protocol_mqtt(nc); break; case MG_EV_RECV: { /* There can be multiple messages in the buffer, process them all. */ while (1) { int len = parse_mqtt(io, &mm); if (len < 0) { if (len == MG_MQTT_ERROR_MALFORMED_MSG) { /* Protocol error. */ nc->flags |= MG_F_CLOSE_IMMEDIATELY; } else if (len == MG_MQTT_ERROR_INCOMPLETE_MSG) { /* Not fully buffered, let's check if we have a chance to get more * data later */ if (nc->recv_mbuf_limit > 0 && nc->recv_mbuf.len >= nc->recv_mbuf_limit) { LOG(LL_ERROR, ("%p recv buffer (%lu bytes) exceeds the limit " "%lu bytes, and not drained, closing", nc, (unsigned long) nc->recv_mbuf.len, (unsigned long) nc->recv_mbuf_limit)); nc->flags |= MG_F_CLOSE_IMMEDIATELY; } } else { /* Should never be here */ LOG(LL_ERROR, ("%p invalid len: %d, closing", nc, len)); nc->flags |= MG_F_CLOSE_IMMEDIATELY; } break; } nc->handler(nc, MG_MQTT_EVENT_BASE + mm.cmd, &mm MG_UD_ARG(user_data)); mbuf_remove(io, len); } break; } case MG_EV_POLL: { struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data; double now = mg_time(); if (pd->keep_alive > 0 && pd->last_control_time > 0 && (now - pd->last_control_time) > pd->keep_alive) { LOG(LL_DEBUG, ("Send PINGREQ")); mg_mqtt_ping(nc); } break; } } } static void mg_mqtt_proto_data_destructor(void *proto_data) { MG_FREE(proto_data); } static struct mg_str mg_mqtt_next_topic_component(struct mg_str *topic) { struct mg_str res = *topic; const char *c = mg_strchr(*topic, '/'); if (c != NULL) { res.len = (c - topic->p); topic->len -= (res.len + 1); topic->p += (res.len + 1); } else { topic->len = 0; } return res; } /* Refernce: https://mosquitto.org/man/mqtt-7.html */ int mg_mqtt_match_topic_expression(struct mg_str exp, struct mg_str topic) { struct mg_str ec, tc; if (exp.len == 0) return 0; while (1) { ec = mg_mqtt_next_topic_component(&exp); tc = mg_mqtt_next_topic_component(&topic); if (ec.len == 0) { if (tc.len != 0) return 0; if (exp.len == 0) break; continue; } if (mg_vcmp(&ec, "+") == 0) { if (tc.len == 0 && topic.len == 0) return 0; continue; } if (mg_vcmp(&ec, "#") == 0) { /* Must be the last component in the expression or it's invalid. */ return (exp.len == 0); } if (mg_strcmp(ec, tc) != 0) { return 0; } } return (tc.len == 0 && topic.len == 0); } int mg_mqtt_vmatch_topic_expression(const char *exp, struct mg_str topic) { return mg_mqtt_match_topic_expression(mg_mk_str(exp), topic); } void mg_set_protocol_mqtt(struct mg_connection *nc) { nc->proto_handler = mqtt_handler; nc->proto_data = MG_CALLOC(1, sizeof(struct mg_mqtt_proto_data)); nc->proto_data_destructor = mg_mqtt_proto_data_destructor; } static void mg_send_mqtt_header(struct mg_connection *nc, uint8_t cmd, uint8_t flags, size_t len) { struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data; uint8_t buf[1 + sizeof(size_t)]; uint8_t *vlen = &buf[1]; buf[0] = (cmd << 4) | flags; /* mqtt variable length encoding */ do { *vlen = len % 0x80; len /= 0x80; if (len > 0) *vlen |= 0x80; vlen++; } while (len > 0); mg_send(nc, buf, vlen - buf); pd->last_control_time = mg_time(); } void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id) { static struct mg_send_mqtt_handshake_opts opts; mg_send_mqtt_handshake_opt(nc, client_id, opts); } void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id, struct mg_send_mqtt_handshake_opts opts) { struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data; uint16_t id_len = 0, wt_len = 0, wm_len = 0, user_len = 0, pw_len = 0; uint16_t netbytes; size_t total_len; if (client_id != NULL) { id_len = strlen(client_id); } total_len = 7 + 1 + 2 + 2 + id_len; if (opts.user_name != NULL) { opts.flags |= MG_MQTT_HAS_USER_NAME; } if (opts.password != NULL) { opts.flags |= MG_MQTT_HAS_PASSWORD; } if (opts.will_topic != NULL && opts.will_message != NULL) { wt_len = strlen(opts.will_topic); wm_len = strlen(opts.will_message); opts.flags |= MG_MQTT_HAS_WILL; } if (opts.keep_alive == 0) { opts.keep_alive = 60; } if (opts.flags & MG_MQTT_HAS_WILL) { total_len += 2 + wt_len + 2 + wm_len; } if (opts.flags & MG_MQTT_HAS_USER_NAME) { user_len = strlen(opts.user_name); total_len += 2 + user_len; } if (opts.flags & MG_MQTT_HAS_PASSWORD) { pw_len = strlen(opts.password); total_len += 2 + pw_len; } mg_send_mqtt_header(nc, MG_MQTT_CMD_CONNECT, 0, total_len); mg_send(nc, "\00\04MQTT\04", 7); mg_send(nc, &opts.flags, 1); netbytes = htons(opts.keep_alive); mg_send(nc, &netbytes, 2); netbytes = htons(id_len); mg_send(nc, &netbytes, 2); mg_send(nc, client_id, id_len); if (opts.flags & MG_MQTT_HAS_WILL) { netbytes = htons(wt_len); mg_send(nc, &netbytes, 2); mg_send(nc, opts.will_topic, wt_len); netbytes = htons(wm_len); mg_send(nc, &netbytes, 2); mg_send(nc, opts.will_message, wm_len); } if (opts.flags & MG_MQTT_HAS_USER_NAME) { netbytes = htons(user_len); mg_send(nc, &netbytes, 2); mg_send(nc, opts.user_name, user_len); } if (opts.flags & MG_MQTT_HAS_PASSWORD) { netbytes = htons(pw_len); mg_send(nc, &netbytes, 2); mg_send(nc, opts.password, pw_len); } if (pd != NULL) { pd->keep_alive = opts.keep_alive; } } void mg_mqtt_publish(struct mg_connection *nc, const char *topic, uint16_t message_id, int flags, const void *data, size_t len) { uint16_t netbytes; uint16_t topic_len = strlen(topic); size_t total_len = 2 + topic_len + len; if (MG_MQTT_GET_QOS(flags) > 0) { total_len += 2; } mg_send_mqtt_header(nc, MG_MQTT_CMD_PUBLISH, flags, total_len); netbytes = htons(topic_len); mg_send(nc, &netbytes, 2); mg_send(nc, topic, topic_len); if (MG_MQTT_GET_QOS(flags) > 0) { netbytes = htons(message_id); mg_send(nc, &netbytes, 2); } mg_send(nc, data, len); } void mg_mqtt_subscribe(struct mg_connection *nc, const struct mg_mqtt_topic_expression *topics, size_t topics_len, uint16_t message_id) { uint16_t netbytes; size_t i; uint16_t topic_len; size_t total_len = 2; for (i = 0; i < topics_len; i++) { total_len += 2 + strlen(topics[i].topic) + 1; } mg_send_mqtt_header(nc, MG_MQTT_CMD_SUBSCRIBE, MG_MQTT_QOS(1), total_len); netbytes = htons(message_id); mg_send(nc, (char *) &netbytes, 2); for (i = 0; i < topics_len; i++) { topic_len = strlen(topics[i].topic); netbytes = htons(topic_len); mg_send(nc, &netbytes, 2); mg_send(nc, topics[i].topic, topic_len); mg_send(nc, &topics[i].qos, 1); } } int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg, struct mg_str *topic, uint8_t *qos, int pos) { unsigned char *buf = (unsigned char *) msg->payload.p + pos; int new_pos; if ((size_t) pos >= msg->payload.len) return -1; topic->len = buf[0] << 8 | buf[1]; topic->p = (char *) buf + 2; new_pos = pos + 2 + topic->len + 1; if ((size_t) new_pos > msg->payload.len) return -1; *qos = buf[2 + topic->len]; return new_pos; } void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics, size_t topics_len, uint16_t message_id) { uint16_t netbytes; size_t i; uint16_t topic_len; size_t total_len = 2; for (i = 0; i < topics_len; i++) { total_len += 2 + strlen(topics[i]); } mg_send_mqtt_header(nc, MG_MQTT_CMD_UNSUBSCRIBE, MG_MQTT_QOS(1), total_len); netbytes = htons(message_id); mg_send(nc, (char *) &netbytes, 2); for (i = 0; i < topics_len; i++) { topic_len = strlen(topics[i]); netbytes = htons(topic_len); mg_send(nc, &netbytes, 2); mg_send(nc, topics[i], topic_len); } } void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code) { uint8_t unused = 0; mg_send_mqtt_header(nc, MG_MQTT_CMD_CONNACK, 0, 2); mg_send(nc, &unused, 1); mg_send(nc, &return_code, 1); } /* * Sends a command which contains only a `message_id` and a QoS level of 1. * * Helper function. */ static void mg_send_mqtt_short_command(struct mg_connection *nc, uint8_t cmd, uint16_t message_id) { uint16_t netbytes; uint8_t flags = (cmd == MG_MQTT_CMD_PUBREL ? 2 : 0); mg_send_mqtt_header(nc, cmd, flags, 2 /* len */); netbytes = htons(message_id); mg_send(nc, &netbytes, 2); } void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id) { mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBACK, message_id); } void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id) { mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREC, message_id); } void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id) { mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREL, message_id); } void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id) { mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBCOMP, message_id); } void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len, uint16_t message_id) { size_t i; uint16_t netbytes; mg_send_mqtt_header(nc, MG_MQTT_CMD_SUBACK, MG_MQTT_QOS(1), 2 + qoss_len); netbytes = htons(message_id); mg_send(nc, &netbytes, 2); for (i = 0; i < qoss_len; i++) { mg_send(nc, &qoss[i], 1); } } void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id) { mg_send_mqtt_short_command(nc, MG_MQTT_CMD_UNSUBACK, message_id); } void mg_mqtt_ping(struct mg_connection *nc) { mg_send_mqtt_header(nc, MG_MQTT_CMD_PINGREQ, 0, 0); } void mg_mqtt_pong(struct mg_connection *nc) { mg_send_mqtt_header(nc, MG_MQTT_CMD_PINGRESP, 0, 0); } void mg_mqtt_disconnect(struct mg_connection *nc) { mg_send_mqtt_header(nc, MG_MQTT_CMD_DISCONNECT, 0, 0); } #endif /* MG_ENABLE_MQTT */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_mqtt_server.c" #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ /* Amalgamated: #include "mg_internal.h" */ /* Amalgamated: #include "mg_mqtt_server.h" */ #if MG_ENABLE_MQTT_BROKER static void mg_mqtt_session_init(struct mg_mqtt_broker *brk, struct mg_mqtt_session *s, struct mg_connection *nc) { s->brk = brk; s->subscriptions = NULL; s->num_subscriptions = 0; s->nc = nc; } static void mg_mqtt_add_session(struct mg_mqtt_session *s) { LIST_INSERT_HEAD(&s->brk->sessions, s, link); } static void mg_mqtt_remove_session(struct mg_mqtt_session *s) { LIST_REMOVE(s, link); } static void mg_mqtt_destroy_session(struct mg_mqtt_session *s) { size_t i; for (i = 0; i < s->num_subscriptions; i++) { MG_FREE((void *) s->subscriptions[i].topic); } MG_FREE(s->subscriptions); MG_FREE(s); } static void mg_mqtt_close_session(struct mg_mqtt_session *s) { mg_mqtt_remove_session(s); mg_mqtt_destroy_session(s); } void mg_mqtt_broker_init(struct mg_mqtt_broker *brk, void *user_data) { LIST_INIT(&brk->sessions); brk->user_data = user_data; } static void mg_mqtt_broker_handle_connect(struct mg_mqtt_broker *brk, struct mg_connection *nc) { struct mg_mqtt_session *s = (struct mg_mqtt_session *) MG_CALLOC(1, sizeof *s); if (s == NULL) { /* LCOV_EXCL_START */ mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE); return; /* LCOV_EXCL_STOP */ } /* TODO(mkm): check header (magic and version) */ mg_mqtt_session_init(brk, s, nc); nc->priv_2 = s; mg_mqtt_add_session(s); mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_ACCEPTED); } static void mg_mqtt_broker_handle_subscribe(struct mg_connection *nc, struct mg_mqtt_message *msg) { struct mg_mqtt_session *ss = (struct mg_mqtt_session *) nc->priv_2; uint8_t qoss[MG_MQTT_MAX_SESSION_SUBSCRIPTIONS]; size_t num_subs = 0; struct mg_str topic; uint8_t qos; int pos; struct mg_mqtt_topic_expression *te; for (pos = 0; (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;) { if (num_subs >= sizeof(MG_MQTT_MAX_SESSION_SUBSCRIPTIONS) || (ss->num_subscriptions + num_subs >= MG_MQTT_MAX_SESSION_SUBSCRIPTIONS)) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; return; } qoss[num_subs++] = qos; } if (num_subs > 0) { te = (struct mg_mqtt_topic_expression *) MG_REALLOC( ss->subscriptions, sizeof(*ss->subscriptions) * (ss->num_subscriptions + num_subs)); if (te == NULL) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; return; } ss->subscriptions = te; for (pos = 0; pos < (int) msg->payload.len && (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1; ss->num_subscriptions++) { te = &ss->subscriptions[ss->num_subscriptions]; te->topic = (char *) MG_MALLOC(topic.len + 1); te->qos = qos; memcpy((char *) te->topic, topic.p, topic.len); ((char *) te->topic)[topic.len] = '\0'; } } if (pos == (int) msg->payload.len) { mg_mqtt_suback(nc, qoss, num_subs, msg->message_id); } else { /* We did not fully parse the payload, something must be wrong. */ nc->flags |= MG_F_CLOSE_IMMEDIATELY; } } static void mg_mqtt_broker_handle_publish(struct mg_mqtt_broker *brk, struct mg_mqtt_message *msg) { struct mg_mqtt_session *s; size_t i; for (s = mg_mqtt_next(brk, NULL); s != NULL; s = mg_mqtt_next(brk, s)) { for (i = 0; i < s->num_subscriptions; i++) { if (mg_mqtt_vmatch_topic_expression(s->subscriptions[i].topic, msg->topic)) { char buf[100], *p = buf; mg_asprintf(&p, sizeof(buf), "%.*s", (int) msg->topic.len, msg->topic.p); if (p == NULL) { return; } mg_mqtt_publish(s->nc, p, 0, 0, msg->payload.p, msg->payload.len); if (p != buf) { MG_FREE(p); } break; } } } } void mg_mqtt_broker(struct mg_connection *nc, int ev, void *data) { struct mg_mqtt_message *msg = (struct mg_mqtt_message *) data; struct mg_mqtt_broker *brk; if (nc->listener) { brk = (struct mg_mqtt_broker *) nc->listener->priv_2; } else { brk = (struct mg_mqtt_broker *) nc->priv_2; } switch (ev) { case MG_EV_ACCEPT: if (nc->proto_data == NULL) mg_set_protocol_mqtt(nc); nc->priv_2 = NULL; /* Clear up the inherited pointer to broker */ break; case MG_EV_MQTT_CONNECT: if (nc->priv_2 == NULL) { mg_mqtt_broker_handle_connect(brk, nc); } else { /* Repeated CONNECT */ nc->flags |= MG_F_CLOSE_IMMEDIATELY; } break; case MG_EV_MQTT_SUBSCRIBE: if (nc->priv_2 != NULL) { mg_mqtt_broker_handle_subscribe(nc, msg); } else { /* Subscribe before CONNECT */ nc->flags |= MG_F_CLOSE_IMMEDIATELY; } break; case MG_EV_MQTT_PUBLISH: if (nc->priv_2 != NULL) { mg_mqtt_broker_handle_publish(brk, msg); } else { /* Publish before CONNECT */ nc->flags |= MG_F_CLOSE_IMMEDIATELY; } break; case MG_EV_CLOSE: if (nc->listener && nc->priv_2 != NULL) { mg_mqtt_close_session((struct mg_mqtt_session *) nc->priv_2); } break; } } struct mg_mqtt_session *mg_mqtt_next(struct mg_mqtt_broker *brk, struct mg_mqtt_session *s) { return s == NULL ? LIST_FIRST(&brk->sessions) : LIST_NEXT(s, link); } #endif /* MG_ENABLE_MQTT_BROKER */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_dns.c" #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ #if MG_ENABLE_DNS /* Amalgamated: #include "mg_internal.h" */ /* Amalgamated: #include "mg_dns.h" */ static int mg_dns_tid = 0xa0; struct mg_dns_header { uint16_t transaction_id; uint16_t flags; uint16_t num_questions; uint16_t num_answers; uint16_t num_authority_prs; uint16_t num_other_prs; }; struct mg_dns_resource_record *mg_dns_next_record( struct mg_dns_message *msg, int query, struct mg_dns_resource_record *prev) { struct mg_dns_resource_record *rr; for (rr = (prev == NULL ? msg->answers : prev + 1); rr - msg->answers < msg->num_answers; rr++) { if (rr->rtype == query) { return rr; } } return NULL; } int mg_dns_parse_record_data(struct mg_dns_message *msg, struct mg_dns_resource_record *rr, void *data, size_t data_len) { switch (rr->rtype) { case MG_DNS_A_RECORD: if (data_len < sizeof(struct in_addr)) { return -1; } if (rr->rdata.p + data_len > msg->pkt.p + msg->pkt.len) { return -1; } memcpy(data, rr->rdata.p, data_len); return 0; #if MG_ENABLE_IPV6 case MG_DNS_AAAA_RECORD: if (data_len < sizeof(struct in6_addr)) { return -1; /* LCOV_EXCL_LINE */ } memcpy(data, rr->rdata.p, data_len); return 0; #endif case MG_DNS_CNAME_RECORD: mg_dns_uncompress_name(msg, &rr->rdata, (char *) data, data_len); return 0; } return -1; } int mg_dns_insert_header(struct mbuf *io, size_t pos, struct mg_dns_message *msg) { struct mg_dns_header header; memset(&header, 0, sizeof(header)); header.transaction_id = msg->transaction_id; header.flags = htons(msg->flags); header.num_questions = htons(msg->num_questions); header.num_answers = htons(msg->num_answers); return mbuf_insert(io, pos, &header, sizeof(header)); } int mg_dns_copy_questions(struct mbuf *io, struct mg_dns_message *msg) { unsigned char *begin, *end; struct mg_dns_resource_record *last_q; if (msg->num_questions <= 0) return 0; begin = (unsigned char *) msg->pkt.p + sizeof(struct mg_dns_header); last_q = &msg->questions[msg->num_questions - 1]; end = (unsigned char *) last_q->name.p + last_q->name.len + 4; return mbuf_append(io, begin, end - begin); } int mg_dns_encode_name(struct mbuf *io, const char *name, size_t len) { const char *s; unsigned char n; size_t pos = io->len; do { if ((s = strchr(name, '.')) == NULL) { s = name + len; } if (s - name > 127) { return -1; /* TODO(mkm) cover */ } n = s - name; /* chunk length */ mbuf_append(io, &n, 1); /* send length */ mbuf_append(io, name, n); if (*s == '.') { n++; } name += n; len -= n; } while (*s != '\0'); mbuf_append(io, "\0", 1); /* Mark end of host name */ return io->len - pos; } int mg_dns_encode_record(struct mbuf *io, struct mg_dns_resource_record *rr, const char *name, size_t nlen, const void *rdata, size_t rlen) { size_t pos = io->len; uint16_t u16; uint32_t u32; if (rr->kind == MG_DNS_INVALID_RECORD) { return -1; /* LCOV_EXCL_LINE */ } if (mg_dns_encode_name(io, name, nlen) == -1) { return -1; } u16 = htons(rr->rtype); mbuf_append(io, &u16, 2); u16 = htons(rr->rclass); mbuf_append(io, &u16, 2); if (rr->kind == MG_DNS_ANSWER) { u32 = htonl(rr->ttl); mbuf_append(io, &u32, 4); if (rr->rtype == MG_DNS_CNAME_RECORD) { int clen; /* fill size after encoding */ size_t off = io->len; mbuf_append(io, &u16, 2); if ((clen = mg_dns_encode_name(io, (const char *) rdata, rlen)) == -1) { return -1; } u16 = clen; io->buf[off] = u16 >> 8; io->buf[off + 1] = u16 & 0xff; } else { u16 = htons((uint16_t) rlen); mbuf_append(io, &u16, 2); mbuf_append(io, rdata, rlen); } } return io->len - pos; } void mg_send_dns_query(struct mg_connection *nc, const char *name, int query_type) { struct mg_dns_message *msg = (struct mg_dns_message *) MG_CALLOC(1, sizeof(*msg)); struct mbuf pkt; struct mg_dns_resource_record *rr = &msg->questions[0]; DBG(("%s %d", name, query_type)); mbuf_init(&pkt, 64 /* Start small, it'll grow as needed. */); msg->transaction_id = ++mg_dns_tid; msg->flags = 0x100; msg->num_questions = 1; mg_dns_insert_header(&pkt, 0, msg); rr->rtype = query_type; rr->rclass = 1; /* Class: inet */ rr->kind = MG_DNS_QUESTION; if (mg_dns_encode_record(&pkt, rr, name, strlen(name), NULL, 0) == -1) { /* TODO(mkm): return an error code */ goto cleanup; /* LCOV_EXCL_LINE */ } /* TCP DNS requires messages to be prefixed with len */ if (!(nc->flags & MG_F_UDP)) { uint16_t len = htons((uint16_t) pkt.len); mbuf_insert(&pkt, 0, &len, 2); } mg_send(nc, pkt.buf, pkt.len); mbuf_free(&pkt); cleanup: MG_FREE(msg); } static unsigned char *mg_parse_dns_resource_record( unsigned char *data, unsigned char *end, struct mg_dns_resource_record *rr, int reply) { unsigned char *name = data; int chunk_len, data_len; while (data < end && (chunk_len = *data)) { if (((unsigned char *) data)[0] & 0xc0) { data += 1; break; } data += chunk_len + 1; } if (data > end - 5) { return NULL; } rr->name.p = (char *) name; rr->name.len = data - name + 1; data++; rr->rtype = data[0] << 8 | data[1]; data += 2; rr->rclass = data[0] << 8 | data[1]; data += 2; rr->kind = reply ? MG_DNS_ANSWER : MG_DNS_QUESTION; if (reply) { if (data >= end - 6) { return NULL; } rr->ttl = (uint32_t) data[0] << 24 | (uint32_t) data[1] << 16 | data[2] << 8 | data[3]; data += 4; data_len = *data << 8 | *(data + 1); data += 2; rr->rdata.p = (char *) data; rr->rdata.len = data_len; data += data_len; } return data; } int mg_parse_dns(const char *buf, int len, struct mg_dns_message *msg) { struct mg_dns_header *header = (struct mg_dns_header *) buf; unsigned char *data = (unsigned char *) buf + sizeof(*header); unsigned char *end = (unsigned char *) buf + len; int i; memset(msg, 0, sizeof(*msg)); msg->pkt.p = buf; msg->pkt.len = len; if (len < (int) sizeof(*header)) return -1; msg->transaction_id = header->transaction_id; msg->flags = ntohs(header->flags); msg->num_questions = ntohs(header->num_questions); if (msg->num_questions > (int) ARRAY_SIZE(msg->questions)) { msg->num_questions = (int) ARRAY_SIZE(msg->questions); } msg->num_answers = ntohs(header->num_answers); if (msg->num_answers > (int) ARRAY_SIZE(msg->answers)) { msg->num_answers = (int) ARRAY_SIZE(msg->answers); } for (i = 0; i < msg->num_questions; i++) { data = mg_parse_dns_resource_record(data, end, &msg->questions[i], 0); if (data == NULL) return -1; } for (i = 0; i < msg->num_answers; i++) { data = mg_parse_dns_resource_record(data, end, &msg->answers[i], 1); if (data == NULL) return -1; } return 0; } size_t mg_dns_uncompress_name(struct mg_dns_message *msg, struct mg_str *name, char *dst, int dst_len) { int chunk_len, num_ptrs = 0; char *old_dst = dst; const unsigned char *data = (unsigned char *) name->p; const unsigned char *end = (unsigned char *) msg->pkt.p + msg->pkt.len; if (data >= end) { return 0; } while ((chunk_len = *data++)) { int leeway = dst_len - (dst - old_dst); if (data >= end) { return 0; } if ((chunk_len & 0xc0) == 0xc0) { uint16_t off = (data[-1] & (~0xc0)) << 8 | data[0]; if (off >= msg->pkt.len) { return 0; } /* Basic circular loop avoidance: allow up to 16 pointer hops. */ if (++num_ptrs > 15) { return 0; } data = (unsigned char *) msg->pkt.p + off; continue; } if (chunk_len > 63) { return 0; } if (chunk_len > leeway) { chunk_len = leeway; } if (data + chunk_len >= end) { return 0; } memcpy(dst, data, chunk_len); data += chunk_len; dst += chunk_len; leeway -= chunk_len; if (leeway == 0) { return dst - old_dst; } *dst++ = '.'; } if (dst != old_dst) { *--dst = 0; } return dst - old_dst; } static void dns_handler(struct mg_connection *nc, int ev, void *ev_data MG_UD_ARG(void *user_data)) { struct mbuf *io = &nc->recv_mbuf; struct mg_dns_message msg; /* Pass low-level events to the user handler */ nc->handler(nc, ev, ev_data MG_UD_ARG(user_data)); switch (ev) { case MG_EV_RECV: if (!(nc->flags & MG_F_UDP)) { mbuf_remove(&nc->recv_mbuf, 2); } if (mg_parse_dns(nc->recv_mbuf.buf, nc->recv_mbuf.len, &msg) == -1) { /* reply + recursion allowed + format error */ memset(&msg, 0, sizeof(msg)); msg.flags = 0x8081; mg_dns_insert_header(io, 0, &msg); if (!(nc->flags & MG_F_UDP)) { uint16_t len = htons((uint16_t) io->len); mbuf_insert(io, 0, &len, 2); } mg_send(nc, io->buf, io->len); } else { /* Call user handler with parsed message */ nc->handler(nc, MG_DNS_MESSAGE, &msg MG_UD_ARG(user_data)); } mbuf_remove(io, io->len); break; } } void mg_set_protocol_dns(struct mg_connection *nc) { nc->proto_handler = dns_handler; } #endif /* MG_ENABLE_DNS */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_dns_server.c" #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ #if MG_ENABLE_DNS_SERVER /* Amalgamated: #include "mg_internal.h" */ /* Amalgamated: #include "dns-server.h" */ struct mg_dns_reply mg_dns_create_reply(struct mbuf *io, struct mg_dns_message *msg) { struct mg_dns_reply rep; rep.msg = msg; rep.io = io; rep.start = io->len; /* reply + recursion allowed */ msg->flags |= 0x8080; mg_dns_copy_questions(io, msg); msg->num_answers = 0; return rep; } void mg_dns_send_reply(struct mg_connection *nc, struct mg_dns_reply *r) { size_t sent = r->io->len - r->start; mg_dns_insert_header(r->io, r->start, r->msg); if (!(nc->flags & MG_F_UDP)) { uint16_t len = htons((uint16_t) sent); mbuf_insert(r->io, r->start, &len, 2); } if (&nc->send_mbuf != r->io) { mg_send(nc, r->io->buf + r->start, r->io->len - r->start); r->io->len = r->start; } } int mg_dns_reply_record(struct mg_dns_reply *reply, struct mg_dns_resource_record *question, const char *name, int rtype, int ttl, const void *rdata, size_t rdata_len) { struct mg_dns_message *msg = (struct mg_dns_message *) reply->msg; char rname[512]; struct mg_dns_resource_record *ans = &msg->answers[msg->num_answers]; if (msg->num_answers >= MG_MAX_DNS_ANSWERS) { return -1; /* LCOV_EXCL_LINE */ } if (name == NULL) { name = rname; rname[511] = 0; mg_dns_uncompress_name(msg, &question->name, rname, sizeof(rname) - 1); } *ans = *question; ans->kind = MG_DNS_ANSWER; ans->rtype = rtype; ans->ttl = ttl; if (mg_dns_encode_record(reply->io, ans, name, strlen(name), rdata, rdata_len) == -1) { return -1; /* LCOV_EXCL_LINE */ }; msg->num_answers++; return 0; } #endif /* MG_ENABLE_DNS_SERVER */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_resolv.c" #endif /* * Copyright (c) 2014 Cesanta Software Limited * All rights reserved */ #if MG_ENABLE_ASYNC_RESOLVER /* Amalgamated: #include "mg_internal.h" */ /* Amalgamated: #include "mg_resolv.h" */ #ifndef MG_DEFAULT_NAMESERVER #define MG_DEFAULT_NAMESERVER "8.8.8.8" #endif struct mg_resolve_async_request { char name[1024]; int query; mg_resolve_callback_t callback; void *data; time_t timeout; int max_retries; enum mg_resolve_err err; /* state */ time_t last_time; int retries; }; /* * Find what nameserver to use. * * Return 0 if OK, -1 if error */ static int mg_get_ip_address_of_nameserver(char *name, size_t name_len) { int ret = -1; #ifdef _WIN32 int i; LONG err; HKEY hKey, hSub; wchar_t subkey[512], value[128], *key = L"SYSTEM\\ControlSet001\\Services\\Tcpip\\Parameters\\Interfaces"; if ((err = RegOpenKeyExW(HKEY_LOCAL_MACHINE, key, 0, KEY_READ, &hKey)) != ERROR_SUCCESS) { fprintf(stderr, "cannot open reg key %S: %ld\n", key, err); ret = -1; } else { for (ret = -1, i = 0; 1; i++) { DWORD subkey_size = sizeof(subkey), type, len = sizeof(value); if (RegEnumKeyExW(hKey, i, subkey, &subkey_size, NULL, NULL, NULL, NULL) != ERROR_SUCCESS) { break; } if (RegOpenKeyExW(hKey, subkey, 0, KEY_READ, &hSub) == ERROR_SUCCESS && ((RegQueryValueExW(hSub, L"NameServer", 0, &type, (void *) value, &len) == ERROR_SUCCESS && value[0] != '\0') || (RegQueryValueExW(hSub, L"DhcpNameServer", 0, &type, (void *) value, &len) == ERROR_SUCCESS && value[0] != '\0'))) { /* * See https://github.com/cesanta/mongoose/issues/176 * The value taken from the registry can be empty, a single * IP address, or multiple IP addresses separated by comma. * If it's empty, check the next interface. * If it's multiple IP addresses, take the first one. */ wchar_t *comma = wcschr(value, ','); if (comma != NULL) { *comma = '\0'; } /* %S will convert wchar_t -> char */ snprintf(name, name_len, "%S", value); ret = 0; RegCloseKey(hSub); break; } } RegCloseKey(hKey); } #elif MG_ENABLE_FILESYSTEM && defined(MG_RESOLV_CONF_FILE_NAME) FILE *fp; char line[512]; if ((fp = mg_fopen(MG_RESOLV_CONF_FILE_NAME, "r")) == NULL) { ret = -1; } else { /* Try to figure out what nameserver to use */ for (ret = -1; fgets(line, sizeof(line), fp) != NULL;) { unsigned int a, b, c, d; if (sscanf(line, "nameserver %u.%u.%u.%u", &a, &b, &c, &d) == 4) { snprintf(name, name_len, "%u.%u.%u.%u", a, b, c, d); ret = 0; break; } } (void) fclose(fp); } #else snprintf(name, name_len, "%s", MG_DEFAULT_NAMESERVER); #endif /* _WIN32 */ return ret; } int mg_resolve_from_hosts_file(const char *name, union socket_address *usa) { #if MG_ENABLE_FILESYSTEM && defined(MG_HOSTS_FILE_NAME) /* TODO(mkm) cache /etc/hosts */ FILE *fp; char line[1024]; char *p; char alias[256]; unsigned int a, b, c, d; int len = 0; if ((fp = mg_fopen(MG_HOSTS_FILE_NAME, "r")) == NULL) { return -1; } for (; fgets(line, sizeof(line), fp) != NULL;) { if (line[0] == '#') continue; if (sscanf(line, "%u.%u.%u.%u%n", &a, &b, &c, &d, &len) == 0) { /* TODO(mkm): handle ipv6 */ continue; } for (p = line + len; sscanf(p, "%s%n", alias, &len) == 1; p += len) { if (strcmp(alias, name) == 0) { usa->sin.sin_addr.s_addr = htonl(a << 24 | b << 16 | c << 8 | d); fclose(fp); return 0; } } } fclose(fp); #else (void) name; (void) usa; #endif return -1; } static void mg_resolve_async_eh(struct mg_connection *nc, int ev, void *data MG_UD_ARG(void *user_data)) { time_t now = (time_t) mg_time(); struct mg_resolve_async_request *req; struct mg_dns_message *msg; #if !MG_ENABLE_CALLBACK_USERDATA void *user_data = nc->user_data; #endif if (ev != MG_EV_POLL) { DBG(("ev=%d user_data=%p", ev, user_data)); } req = (struct mg_resolve_async_request *) user_data; if (req == NULL) { return; } switch (ev) { case MG_EV_POLL: if (req->retries > req->max_retries) { req->err = MG_RESOLVE_EXCEEDED_RETRY_COUNT; nc->flags |= MG_F_CLOSE_IMMEDIATELY; break; } if (nc->flags & MG_F_CONNECTING) break; /* fallthrough */ case MG_EV_CONNECT: if (req->retries == 0 || now - req->last_time >= req->timeout) { mg_send_dns_query(nc, req->name, req->query); req->last_time = now; req->retries++; } break; case MG_EV_RECV: msg = (struct mg_dns_message *) MG_MALLOC(sizeof(*msg)); if (mg_parse_dns(nc->recv_mbuf.buf, *(int *) data, msg) == 0 && msg->num_answers > 0) { req->callback(msg, req->data, MG_RESOLVE_OK); nc->user_data = NULL; MG_FREE(req); } else { req->err = MG_RESOLVE_NO_ANSWERS; } MG_FREE(msg); nc->flags |= MG_F_CLOSE_IMMEDIATELY; break; case MG_EV_SEND: /* * If a send error occurs, prevent closing of the connection by the core. * We will retry after timeout. */ nc->flags &= ~MG_F_CLOSE_IMMEDIATELY; mbuf_remove(&nc->send_mbuf, nc->send_mbuf.len); break; case MG_EV_TIMER: req->err = MG_RESOLVE_TIMEOUT; nc->flags |= MG_F_CLOSE_IMMEDIATELY; break; case MG_EV_CLOSE: /* If we got here with request still not done, fire an error callback. */ if (req != NULL) { char addr[32]; mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP); #ifdef MG_LOG_DNS_FAILURES LOG(LL_ERROR, ("Failed to resolve '%s', server %s", req->name, addr)); #endif req->callback(NULL, req->data, req->err); nc->user_data = NULL; MG_FREE(req); } break; } } int mg_resolve_async(struct mg_mgr *mgr, const char *name, int query, mg_resolve_callback_t cb, void *data) { struct mg_resolve_async_opts opts; memset(&opts, 0, sizeof(opts)); return mg_resolve_async_opt(mgr, name, query, cb, data, opts); } int mg_resolve_async_opt(struct mg_mgr *mgr, const char *name, int query, mg_resolve_callback_t cb, void *data, struct mg_resolve_async_opts opts) { struct mg_resolve_async_request *req; struct mg_connection *dns_nc; const char *nameserver = opts.nameserver; char dns_server_buff[17], nameserver_url[26]; if (nameserver == NULL) { nameserver = mgr->nameserver; } DBG(("%s %d %p", name, query, opts.dns_conn)); /* resolve with DNS */ req = (struct mg_resolve_async_request *) MG_CALLOC(1, sizeof(*req)); if (req == NULL) { return -1; } strncpy(req->name, name, sizeof(req->name)); req->name[sizeof(req->name) - 1] = '\0'; req->query = query; req->callback = cb; req->data = data; /* TODO(mkm): parse defaults out of resolve.conf */ req->max_retries = opts.max_retries ? opts.max_retries : 2; req->timeout = opts.timeout ? opts.timeout : 5; /* Lazily initialize dns server */ if (nameserver == NULL) { if (mg_get_ip_address_of_nameserver(dns_server_buff, sizeof(dns_server_buff)) != -1) { nameserver = dns_server_buff; } else { nameserver = MG_DEFAULT_NAMESERVER; } } snprintf(nameserver_url, sizeof(nameserver_url), "udp://%s:53", nameserver); dns_nc = mg_connect(mgr, nameserver_url, MG_CB(mg_resolve_async_eh, NULL)); if (dns_nc == NULL) { MG_FREE(req); return -1; } dns_nc->user_data = req; if (opts.dns_conn != NULL) { *opts.dns_conn = dns_nc; } return 0; } void mg_set_nameserver(struct mg_mgr *mgr, const char *nameserver) { MG_FREE((char *) mgr->nameserver); mgr->nameserver = NULL; if (nameserver != NULL) { mgr->nameserver = strdup(nameserver); } } #endif /* MG_ENABLE_ASYNC_RESOLVER */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_coap.c" #endif /* * Copyright (c) 2015 Cesanta Software Limited * All rights reserved * This software is dual-licensed: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. For the terms of this * license, see <http://www.gnu.org/licenses/>. * * You are free to use this software under the terms of the GNU General * Public License, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * Alternatively, you can license this software under a commercial * license, as set out in <https://www.cesanta.com/license>. */ /* Amalgamated: #include "mg_internal.h" */ /* Amalgamated: #include "mg_coap.h" */ #if MG_ENABLE_COAP void mg_coap_free_options(struct mg_coap_message *cm) { while (cm->options != NULL) { struct mg_coap_option *next = cm->options->next; MG_FREE(cm->options); cm->options = next; } } struct mg_coap_option *mg_coap_add_option(struct mg_coap_message *cm, uint32_t number, char *value, size_t len) { struct mg_coap_option *new_option = (struct mg_coap_option *) MG_CALLOC(1, sizeof(*new_option)); new_option->number = number; new_option->value.p = value; new_option->value.len = len; if (cm->options == NULL) { cm->options = cm->optiomg_tail = new_option; } else { /* * A very simple attention to help clients to compose options: * CoAP wants to see options ASC ordered. * Could be change by using sort in coap_compose */ if (cm->optiomg_tail->number <= new_option->number) { /* if option is already ordered just add it */ cm->optiomg_tail = cm->optiomg_tail->next = new_option; } else { /* looking for appropriate position */ struct mg_coap_option *current_opt = cm->options; struct mg_coap_option *prev_opt = 0; while (current_opt != NULL) { if (current_opt->number > new_option->number) { break; } prev_opt = current_opt; current_opt = current_opt->next; } if (prev_opt != NULL) { prev_opt->next = new_option; new_option->next = current_opt; } else { /* insert new_option to the beginning */ new_option->next = cm->options; cm->options = new_option; } } } return new_option; } /* * Fills CoAP header in mg_coap_message. * * Helper function. */ static char *coap_parse_header(char *ptr, struct mbuf *io, struct mg_coap_message *cm) { if (io->len < sizeof(uint32_t)) { cm->flags |= MG_COAP_NOT_ENOUGH_DATA; return NULL; } /* * Version (Ver): 2-bit unsigned integer. Indicates the CoAP version * number. Implementations of this specification MUST set this field * to 1 (01 binary). Other values are reserved for future versions. * Messages with unknown version numbers MUST be silently ignored. */ if (((uint8_t) *ptr >> 6) != 1) { cm->flags |= MG_COAP_IGNORE; return NULL; } /* * Type (T): 2-bit unsigned integer. Indicates if this message is of * type Confirmable (0), Non-confirmable (1), Acknowledgement (2), or * Reset (3). */ cm->msg_type = ((uint8_t) *ptr & 0x30) >> 4; cm->flags |= MG_COAP_MSG_TYPE_FIELD; /* * Token Length (TKL): 4-bit unsigned integer. Indicates the length of * the variable-length Token field (0-8 bytes). Lengths 9-15 are * reserved, MUST NOT be sent, and MUST be processed as a message * format error. */ cm->token.len = *ptr & 0x0F; if (cm->token.len > 8) { cm->flags |= MG_COAP_FORMAT_ERROR; return NULL; } ptr++; /* * Code: 8-bit unsigned integer, split into a 3-bit class (most * significant bits) and a 5-bit detail (least significant bits) */ cm->code_class = (uint8_t) *ptr >> 5; cm->code_detail = *ptr & 0x1F; cm->flags |= (MG_COAP_CODE_CLASS_FIELD | MG_COAP_CODE_DETAIL_FIELD); ptr++; /* Message ID: 16-bit unsigned integer in network byte order. */ cm->msg_id = (uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1); cm->flags |= MG_COAP_MSG_ID_FIELD; ptr += 2; return ptr; } /* * Fills token information in mg_coap_message. * * Helper function. */ static char *coap_get_token(char *ptr, struct mbuf *io, struct mg_coap_message *cm) { if (cm->token.len != 0) { if (ptr + cm->token.len > io->buf + io->len) { cm->flags |= MG_COAP_NOT_ENOUGH_DATA; return NULL; } else { cm->token.p = ptr; ptr += cm->token.len; cm->flags |= MG_COAP_TOKEN_FIELD; } } return ptr; } /* * Returns Option Delta or Length. * * Helper function. */ static int coap_get_ext_opt(char *ptr, struct mbuf *io, uint16_t *opt_info) { int ret = 0; if (*opt_info == 13) { /* * 13: An 8-bit unsigned integer follows the initial byte and * indicates the Option Delta/Length minus 13. */ if (ptr < io->buf + io->len) { *opt_info = (uint8_t) *ptr + 13; ret = sizeof(uint8_t); } else { ret = -1; /* LCOV_EXCL_LINE */ } } else if (*opt_info == 14) { /* * 14: A 16-bit unsigned integer in network byte order follows the * initial byte and indicates the Option Delta/Length minus 269. */ if (ptr + sizeof(uint8_t) < io->buf + io->len) { *opt_info = ((uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1)) + 269; ret = sizeof(uint16_t); } else { ret = -1; /* LCOV_EXCL_LINE */ } } return ret; } /* * Fills options in mg_coap_message. * * Helper function. * * General options format: * +---------------+---------------+ * | Option Delta | Option Length | 1 byte * +---------------+---------------+ * \ Option Delta (extended) \ 0-2 bytes * +-------------------------------+ * / Option Length (extended) \ 0-2 bytes * +-------------------------------+ * \ Option Value \ 0 or more bytes * +-------------------------------+ */ static char *coap_get_options(char *ptr, struct mbuf *io, struct mg_coap_message *cm) { uint16_t prev_opt = 0; if (ptr == io->buf + io->len) { /* end of packet, ok */ return NULL; } /* 0xFF is payload marker */ while (ptr < io->buf + io->len && (uint8_t) *ptr != 0xFF) { uint16_t option_delta, option_lenght; int optinfo_len; /* Option Delta: 4-bit unsigned integer */ option_delta = ((uint8_t) *ptr & 0xF0) >> 4; /* Option Length: 4-bit unsigned integer */ option_lenght = *ptr & 0x0F; if (option_delta == 15 || option_lenght == 15) { /* * 15: Reserved for future use. If the field is set to this value, * it MUST be processed as a message format error */ cm->flags |= MG_COAP_FORMAT_ERROR; break; } ptr++; /* check for extended option delta */ optinfo_len = coap_get_ext_opt(ptr, io, &option_delta); if (optinfo_len == -1) { cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */ break; /* LCOV_EXCL_LINE */ } ptr += optinfo_len; /* check or extended option lenght */ optinfo_len = coap_get_ext_opt(ptr, io, &option_lenght); if (optinfo_len == -1) { cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */ break; /* LCOV_EXCL_LINE */ } ptr += optinfo_len; /* * Instead of specifying the Option Number directly, the instances MUST * appear in order of their Option Numbers and a delta encoding is used * between them. */ option_delta += prev_opt; mg_coap_add_option(cm, option_delta, ptr, option_lenght); prev_opt = option_delta; if (ptr + option_lenght > io->buf + io->len) { cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */ break; /* LCOV_EXCL_LINE */ } ptr += option_lenght; } if ((cm->flags & MG_COAP_ERROR) != 0) { mg_coap_free_options(cm); return NULL; } cm->flags |= MG_COAP_OPTIOMG_FIELD; if (ptr == io->buf + io->len) { /* end of packet, ok */ return NULL; } ptr++; return ptr; } uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm) { char *ptr; memset(cm, 0, sizeof(*cm)); if ((ptr = coap_parse_header(io->buf, io, cm)) == NULL) { return cm->flags; } if ((ptr = coap_get_token(ptr, io, cm)) == NULL) { return cm->flags; } if ((ptr = coap_get_options(ptr, io, cm)) == NULL) { return cm->flags; } /* the rest is payload */ cm->payload.len = io->len - (ptr - io->buf); if (cm->payload.len != 0) { cm->payload.p = ptr; cm->flags |= MG_COAP_PAYLOAD_FIELD; } return cm->flags; } /* * Calculates extended size of given Opt Number/Length in coap message. * * Helper function. */ static size_t coap_get_ext_opt_size(uint32_t value) { int ret = 0; if (value >= 13 && value <= 0xFF + 13) { ret = sizeof(uint8_t); } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) { ret = sizeof(uint16_t); } return ret; } /* * Splits given Opt Number/Length into base and ext values. * * Helper function. */ static int coap_split_opt(uint32_t value, uint8_t *base, uint16_t *ext) { int ret = 0; if (value < 13) { *base = value; } else if (value >= 13 && value <= 0xFF + 13) { *base = 13; *ext = value - 13; ret = sizeof(uint8_t); } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) { *base = 14; *ext = value - 269; ret = sizeof(uint16_t); } return ret; } /* * Puts uint16_t (in network order) into given char stream. * * Helper function. */ static char *coap_add_uint16(char *ptr, uint16_t val) { *ptr = val >> 8; ptr++; *ptr = val & 0x00FF; ptr++; return ptr; } /* * Puts extended value of Opt Number/Length into given char stream. * * Helper function. */ static char *coap_add_opt_info(char *ptr, uint16_t val, size_t len) { if (len == sizeof(uint8_t)) { *ptr = (char) val; ptr++; } else if (len == sizeof(uint16_t)) { ptr = coap_add_uint16(ptr, val); } return ptr; } /* * Verifies given mg_coap_message and calculates message size for it. * * Helper function. */ static uint32_t coap_calculate_packet_size(struct mg_coap_message *cm, size_t *len) { struct mg_coap_option *opt; uint32_t prev_opt_number; *len = 4; /* header */ if (cm->msg_type > MG_COAP_MSG_MAX) { return MG_COAP_ERROR | MG_COAP_MSG_TYPE_FIELD; } if (cm->token.len > 8) { return MG_COAP_ERROR | MG_COAP_TOKEN_FIELD; } if (cm->code_class > 7) { return MG_COAP_ERROR | MG_COAP_CODE_CLASS_FIELD; } if (cm->code_detail > 31) { return MG_COAP_ERROR | MG_COAP_CODE_DETAIL_FIELD; } *len += cm->token.len; if (cm->payload.len != 0) { *len += cm->payload.len + 1; /* ... + 1; add payload marker */ } opt = cm->options; prev_opt_number = 0; while (opt != NULL) { *len += 1; /* basic delta/length */ *len += coap_get_ext_opt_size(opt->number - prev_opt_number); *len += coap_get_ext_opt_size((uint32_t) opt->value.len); /* * Current implementation performs check if * option_number > previous option_number and produces an error * TODO(alashkin): write design doc with limitations * May be resorting is more suitable solution. */ if ((opt->next != NULL && opt->number > opt->next->number) || opt->value.len > 0xFFFF + 269 || opt->number - prev_opt_number > 0xFFFF + 269) { return MG_COAP_ERROR | MG_COAP_OPTIOMG_FIELD; } *len += opt->value.len; prev_opt_number = opt->number; opt = opt->next; } return 0; } uint32_t mg_coap_compose(struct mg_coap_message *cm, struct mbuf *io) { struct mg_coap_option *opt; uint32_t res, prev_opt_number; size_t prev_io_len, packet_size; char *ptr; res = coap_calculate_packet_size(cm, &packet_size); if (res != 0) { return res; } /* saving previous lenght to handle non-empty mbuf */ prev_io_len = io->len; if (mbuf_append(io, NULL, packet_size) == 0) return MG_COAP_ERROR; ptr = io->buf + prev_io_len; /* * since cm is verified, it is possible to use bits shift operator * without additional zeroing of unused bits */ /* ver: 2 bits, msg_type: 2 bits, toklen: 4 bits */ *ptr = (1 << 6) | (cm->msg_type << 4) | (uint8_t)(cm->token.len); ptr++; /* code class: 3 bits, code detail: 5 bits */ *ptr = (cm->code_class << 5) | (cm->code_detail); ptr++; ptr = coap_add_uint16(ptr, cm->msg_id); if (cm->token.len != 0) { memcpy(ptr, cm->token.p, cm->token.len); ptr += cm->token.len; } opt = cm->options; prev_opt_number = 0; while (opt != NULL) { uint8_t delta_base = 0, length_base = 0; uint16_t delta_ext = 0, length_ext = 0; size_t opt_delta_len = coap_split_opt(opt->number - prev_opt_number, &delta_base, &delta_ext); size_t opt_lenght_len = coap_split_opt((uint32_t) opt->value.len, &length_base, &length_ext); *ptr = (delta_base << 4) | length_base; ptr++; ptr = coap_add_opt_info(ptr, delta_ext, opt_delta_len); ptr = coap_add_opt_info(ptr, length_ext, opt_lenght_len); if (opt->value.len != 0) { memcpy(ptr, opt->value.p, opt->value.len); ptr += opt->value.len; } prev_opt_number = opt->number; opt = opt->next; } if (cm->payload.len != 0) { *ptr = (char) -1; ptr++; memcpy(ptr, cm->payload.p, cm->payload.len); } return 0; } uint32_t mg_coap_send_message(struct mg_connection *nc, struct mg_coap_message *cm) { struct mbuf packet_out; uint32_t compose_res; mbuf_init(&packet_out, 0); compose_res = mg_coap_compose(cm, &packet_out); if (compose_res != 0) { return compose_res; /* LCOV_EXCL_LINE */ } mg_send(nc, packet_out.buf, (int) packet_out.len); mbuf_free(&packet_out); return 0; } uint32_t mg_coap_send_ack(struct mg_connection *nc, uint16_t msg_id) { struct mg_coap_message cm; memset(&cm, 0, sizeof(cm)); cm.msg_type = MG_COAP_MSG_ACK; cm.msg_id = msg_id; return mg_coap_send_message(nc, &cm); } static void coap_handler(struct mg_connection *nc, int ev, void *ev_data MG_UD_ARG(void *user_data)) { struct mbuf *io = &nc->recv_mbuf; struct mg_coap_message cm; uint32_t parse_res; memset(&cm, 0, sizeof(cm)); nc->handler(nc, ev, ev_data MG_UD_ARG(user_data)); switch (ev) { case MG_EV_RECV: parse_res = mg_coap_parse(io, &cm); if ((parse_res & MG_COAP_IGNORE) == 0) { if ((cm.flags & MG_COAP_NOT_ENOUGH_DATA) != 0) { /* * Since we support UDP only * MG_COAP_NOT_ENOUGH_DATA == MG_COAP_FORMAT_ERROR */ cm.flags |= MG_COAP_FORMAT_ERROR; /* LCOV_EXCL_LINE */ } /* LCOV_EXCL_LINE */ nc->handler(nc, MG_COAP_EVENT_BASE + cm.msg_type, &cm MG_UD_ARG(user_data)); } mg_coap_free_options(&cm); mbuf_remove(io, io->len); break; } } /* * Attach built-in CoAP event handler to the given connection. * * The user-defined event handler will receive following extra events: * * - MG_EV_COAP_CON * - MG_EV_COAP_NOC * - MG_EV_COAP_ACK * - MG_EV_COAP_RST */ int mg_set_protocol_coap(struct mg_connection *nc) { /* supports UDP only */ if ((nc->flags & MG_F_UDP) == 0) { return -1; } nc->proto_handler = coap_handler; return 0; } #endif /* MG_ENABLE_COAP */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_sntp.c" #endif /* * Copyright (c) 2016 Cesanta Software Limited * All rights reserved */ /* Amalgamated: #include "mg_internal.h" */ /* Amalgamated: #include "mg_sntp.h" */ /* Amalgamated: #include "mg_util.h" */ #if MG_ENABLE_SNTP #define SNTP_TIME_OFFSET 2208988800 #ifndef SNTP_TIMEOUT #define SNTP_TIMEOUT 10 #endif #ifndef SNTP_ATTEMPTS #define SNTP_ATTEMPTS 3 #endif static uint64_t mg_get_sec(uint64_t val) { return (val & 0xFFFFFFFF00000000) >> 32; } static uint64_t mg_get_usec(uint64_t val) { uint64_t tmp = (val & 0x00000000FFFFFFFF); tmp *= 1000000; tmp >>= 32; return tmp; } static void mg_ntp_to_tv(uint64_t val, struct timeval *tv) { uint64_t tmp; tmp = mg_get_sec(val); tmp -= SNTP_TIME_OFFSET; tv->tv_sec = tmp; tv->tv_usec = mg_get_usec(val); } static void mg_get_ntp_ts(const char *ntp, uint64_t *val) { uint32_t tmp; memcpy(&tmp, ntp, sizeof(tmp)); tmp = ntohl(tmp); *val = (uint64_t) tmp << 32; memcpy(&tmp, ntp + 4, sizeof(tmp)); tmp = ntohl(tmp); *val |= tmp; } void mg_sntp_send_request(struct mg_connection *c) { uint8_t buf[48] = {0}; /* * header - 8 bit: * LI (2 bit) - 3 (not in sync), VN (3 bit) - 4 (version), * mode (3 bit) - 3 (client) */ buf[0] = (3 << 6) | (4 << 3) | 3; /* * Next fields should be empty in client request * stratum, 8 bit * poll interval, 8 bit * rrecision, 8 bit * root delay, 32 bit * root dispersion, 32 bit * ref id, 32 bit * ref timestamp, 64 bit * originate Timestamp, 64 bit * receive Timestamp, 64 bit */ /* * convert time to sntp format (sntp starts from 00:00:00 01.01.1900) * according to rfc868 it is 2208988800L sec * this information is used to correct roundtrip delay * but if local clock is absolutely broken (and doesn't work even * as simple timer), it is better to disable it */ #ifndef MG_SNTP_NO_DELAY_CORRECTION uint32_t sec; sec = htonl((uint32_t)(mg_time() + SNTP_TIME_OFFSET)); memcpy(&buf[40], &sec, sizeof(sec)); #endif mg_send(c, buf, sizeof(buf)); } #ifndef MG_SNTP_NO_DELAY_CORRECTION static uint64_t mg_calculate_delay(uint64_t t1, uint64_t t2, uint64_t t3) { /* roundloop delay = (T4 - T1) - (T3 - T2) */ uint64_t d1 = ((mg_time() + SNTP_TIME_OFFSET) * 1000000) - (mg_get_sec(t1) * 1000000 + mg_get_usec(t1)); uint64_t d2 = (mg_get_sec(t3) * 1000000 + mg_get_usec(t3)) - (mg_get_sec(t2) * 1000000 + mg_get_usec(t2)); return (d1 > d2) ? d1 - d2 : 0; } #endif MG_INTERNAL int mg_sntp_parse_reply(const char *buf, int len, struct mg_sntp_message *msg) { uint8_t hdr; uint64_t trsm_ts_T3, delay = 0; int mode; struct timeval tv; if (len < 48) { return -1; } hdr = buf[0]; if ((hdr & 0x38) >> 3 != 4) { /* Wrong version */ return -1; } mode = hdr & 0x7; if (mode != 4 && mode != 5) { /* Not a server reply */ return -1; } memset(msg, 0, sizeof(*msg)); msg->kiss_of_death = (buf[1] == 0); /* Server asks to not send requests */ mg_get_ntp_ts(&buf[40], &trsm_ts_T3); #ifndef MG_SNTP_NO_DELAY_CORRECTION { uint64_t orig_ts_T1, recv_ts_T2; mg_get_ntp_ts(&buf[24], &orig_ts_T1); mg_get_ntp_ts(&buf[32], &recv_ts_T2); delay = mg_calculate_delay(orig_ts_T1, recv_ts_T2, trsm_ts_T3); } #endif mg_ntp_to_tv(trsm_ts_T3, &tv); msg->time = (double) tv.tv_sec + (((double) tv.tv_usec + delay) / 1000000.0); return 0; } static void mg_sntp_handler(struct mg_connection *c, int ev, void *ev_data MG_UD_ARG(void *user_data)) { struct mbuf *io = &c->recv_mbuf; struct mg_sntp_message msg; c->handler(c, ev, ev_data MG_UD_ARG(user_data)); switch (ev) { case MG_EV_RECV: { if (mg_sntp_parse_reply(io->buf, io->len, &msg) < 0) { DBG(("Invalid SNTP packet received (%d)", (int) io->len)); c->handler(c, MG_SNTP_MALFORMED_REPLY, NULL MG_UD_ARG(user_data)); } else { c->handler(c, MG_SNTP_REPLY, (void *) &msg MG_UD_ARG(user_data)); } mbuf_remove(io, io->len); break; } } } int mg_set_protocol_sntp(struct mg_connection *c) { if ((c->flags & MG_F_UDP) == 0) { return -1; } c->proto_handler = mg_sntp_handler; return 0; } struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr, MG_CB(mg_event_handler_t event_handler, void *user_data), const char *sntp_server_name) { struct mg_connection *c = NULL; char url[100], *p_url = url; const char *proto = "", *port = "", *tmp; /* If port is not specified, use default (123) */ tmp = strchr(sntp_server_name, ':'); if (tmp != NULL && *(tmp + 1) == '/') { tmp = strchr(tmp + 1, ':'); } if (tmp == NULL) { port = ":123"; } /* Add udp:// if needed */ if (strncmp(sntp_server_name, "udp://", 6) != 0) { proto = "udp://"; } mg_asprintf(&p_url, sizeof(url), "%s%s%s", proto, sntp_server_name, port); c = mg_connect(mgr, p_url, event_handler MG_UD_ARG(user_data)); if (c == NULL) { goto cleanup; } mg_set_protocol_sntp(c); cleanup: if (p_url != url) { MG_FREE(p_url); } return c; } struct sntp_data { mg_event_handler_t hander; int count; }; static void mg_sntp_util_ev_handler(struct mg_connection *c, int ev, void *ev_data MG_UD_ARG(void *user_data)) { #if !MG_ENABLE_CALLBACK_USERDATA void *user_data = c->user_data; #endif struct sntp_data *sd = (struct sntp_data *) user_data; switch (ev) { case MG_EV_CONNECT: if (*(int *) ev_data != 0) { mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL); break; } /* fallthrough */ case MG_EV_TIMER: if (sd->count <= SNTP_ATTEMPTS) { mg_sntp_send_request(c); mg_set_timer(c, mg_time() + 10); sd->count++; } else { mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL); c->flags |= MG_F_CLOSE_IMMEDIATELY; } break; case MG_SNTP_MALFORMED_REPLY: mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL); c->flags |= MG_F_CLOSE_IMMEDIATELY; break; case MG_SNTP_REPLY: mg_call(c, sd->hander, c->user_data, MG_SNTP_REPLY, ev_data); c->flags |= MG_F_CLOSE_IMMEDIATELY; break; case MG_EV_CLOSE: MG_FREE(user_data); c->user_data = NULL; break; } } struct mg_connection *mg_sntp_get_time(struct mg_mgr *mgr, mg_event_handler_t event_handler, const char *sntp_server_name) { struct mg_connection *c; struct sntp_data *sd = (struct sntp_data *) MG_CALLOC(1, sizeof(*sd)); if (sd == NULL) { return NULL; } c = mg_sntp_connect(mgr, MG_CB(mg_sntp_util_ev_handler, sd), sntp_server_name); if (c == NULL) { MG_FREE(sd); return NULL; } sd->hander = event_handler; #if !MG_ENABLE_CALLBACK_USERDATA c->user_data = sd; #endif return c; } #endif /* MG_ENABLE_SNTP */ #ifdef MG_MODULE_LINES #line 1 "mongoose/src/mg_socks.c" #endif /* * Copyright (c) 2017 Cesanta Software Limited * All rights reserved */ #if MG_ENABLE_SOCKS /* Amalgamated: #include "mg_socks.h" */ /* Amalgamated: #include "mg_internal.h" */ /* * https://www.ietf.org/rfc/rfc1928.txt paragraph 3, handle client handshake * * +----+----------+----------+ * |VER | NMETHODS | METHODS | * +----+----------+----------+ * | 1 | 1 | 1 to 255 | * +----+----------+----------+ */ static void mg_socks5_handshake(struct mg_connection *c) { struct mbuf *r = &c->recv_mbuf; if (r->buf[0] != MG_SOCKS_VERSION) { c->flags |= MG_F_CLOSE_IMMEDIATELY; } else if (r->len > 2 && (size_t) r->buf[1] + 2 <= r->len) { /* https://www.ietf.org/rfc/rfc1928.txt paragraph 3 */ unsigned char reply[2] = {MG_SOCKS_VERSION, MG_SOCKS_HANDSHAKE_FAILURE}; int i; for (i = 2; i < r->buf[1] + 2; i++) { /* TODO(lsm): support other auth methods */ if (r->buf[i] == MG_SOCKS_HANDSHAKE_NOAUTH) reply[1] = r->buf[i]; } mbuf_remove(r, 2 + r->buf[1]); mg_send(c, reply, sizeof(reply)); c->flags |= MG_SOCKS_HANDSHAKE_DONE; /* Mark handshake done */ } } static void disband(struct mg_connection *c) { struct mg_connection *c2 = (struct mg_connection *) c->user_data; if (c2 != NULL) { c2->flags |= MG_F_SEND_AND_CLOSE; c2->user_data = NULL; } c->flags |= MG_F_SEND_AND_CLOSE; c->user_data = NULL; } static void relay_data(struct mg_connection *c) { struct mg_connection *c2 = (struct mg_connection *) c->user_data; if (c2 != NULL) { mg_send(c2, c->recv_mbuf.buf, c->recv_mbuf.len); mbuf_remove(&c->recv_mbuf, c->recv_mbuf.len); } else { c->flags |= MG_F_SEND_AND_CLOSE; } } static void serv_ev_handler(struct mg_connection *c, int ev, void *ev_data) { if (ev == MG_EV_CLOSE) { disband(c); } else if (ev == MG_EV_RECV) { relay_data(c); } else if (ev == MG_EV_CONNECT) { int res = *(int *) ev_data; if (res != 0) LOG(LL_ERROR, ("connect error: %d", res)); } } static void mg_socks5_connect(struct mg_connection *c, const char *addr) { struct mg_connection *serv = mg_connect(c->mgr, addr, serv_ev_handler); serv->user_data = c; c->user_data = serv; } /* * Request, https://www.ietf.org/rfc/rfc1928.txt paragraph 4 * * +----+-----+-------+------+----------+----------+ * |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT | * +----+-----+-------+------+----------+----------+ * | 1 | 1 | X'00' | 1 | Variable | 2 | * +----+-----+-------+------+----------+----------+ */ static void mg_socks5_handle_request(struct mg_connection *c) { struct mbuf *r = &c->recv_mbuf; unsigned char *p = (unsigned char *) r->buf; unsigned char addr_len = 4, reply = MG_SOCKS_SUCCESS; int ver, cmd, atyp; char addr[300]; if (r->len < 8) return; /* return if not fully buffered. min DST.ADDR is 2 */ ver = p[0]; cmd = p[1]; atyp = p[3]; /* TODO(lsm): support other commands */ if (ver != MG_SOCKS_VERSION || cmd != MG_SOCKS_CMD_CONNECT) { reply = MG_SOCKS_CMD_NOT_SUPPORTED; } else if (atyp == MG_SOCKS_ADDR_IPV4) { addr_len = 4; if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */ snprintf(addr, sizeof(addr), "%d.%d.%d.%d:%d", p[4], p[5], p[6], p[7], p[8] << 8 | p[9]); mg_socks5_connect(c, addr); } else if (atyp == MG_SOCKS_ADDR_IPV6) { addr_len = 16; if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */ snprintf(addr, sizeof(addr), "[%x:%x:%x:%x:%x:%x:%x:%x]:%d", p[4] << 8 | p[5], p[6] << 8 | p[7], p[8] << 8 | p[9], p[10] << 8 | p[11], p[12] << 8 | p[13], p[14] << 8 | p[15], p[16] << 8 | p[17], p[18] << 8 | p[19], p[20] << 8 | p[21]); mg_socks5_connect(c, addr); } else if (atyp == MG_SOCKS_ADDR_DOMAIN) { addr_len = p[4] + 1; if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */ snprintf(addr, sizeof(addr), "%.*s:%d", p[4], p + 5, p[4 + addr_len] << 8 | p[4 + addr_len + 1]); mg_socks5_connect(c, addr); } else { reply = MG_SOCKS_ADDR_NOT_SUPPORTED; } /* * Reply, https://www.ietf.org/rfc/rfc1928.txt paragraph 5 * * +----+-----+-------+------+----------+----------+ * |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT | * +----+-----+-------+------+----------+----------+ * | 1 | 1 | X'00' | 1 | Variable | 2 | * +----+-----+-------+------+----------+----------+ */ { unsigned char buf[] = {MG_SOCKS_VERSION, reply, 0}; mg_send(c, buf, sizeof(buf)); } mg_send(c, r->buf + 3, addr_len + 1 + 2); mbuf_remove(r, 6 + addr_len); /* Remove request from the input stream */ c->flags |= MG_SOCKS_CONNECT_DONE; /* Mark ourselves as connected */ } static void socks_handler(struct mg_connection *c, int ev, void *ev_data) { if (ev == MG_EV_RECV) { if (!(c->flags & MG_SOCKS_HANDSHAKE_DONE)) mg_socks5_handshake(c); if (c->flags & MG_SOCKS_HANDSHAKE_DONE && !(c->flags & MG_SOCKS_CONNECT_DONE)) { mg_socks5_handle_request(c); } if (c->flags & MG_SOCKS_CONNECT_DONE) relay_data(c); } else if (ev == MG_EV_CLOSE) { disband(c); } (void) ev_data; } void mg_set_protocol_socks(struct mg_connection *c) { c->proto_handler = socks_handler; } #endif #ifdef MG_MODULE_LINES #line 1 "common/platforms/cc3200/cc3200_libc.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if CS_PLATFORM == CS_P_CC3200 /* Amalgamated: #include "common/mg_mem.h" */ #include <stdio.h> #include <string.h> #ifndef __TI_COMPILER_VERSION__ #include <reent.h> #include <sys/stat.h> #include <sys/time.h> #include <unistd.h> #endif #include <inc/hw_types.h> #include <inc/hw_memmap.h> #include <driverlib/prcm.h> #include <driverlib/rom.h> #include <driverlib/rom_map.h> #include <driverlib/uart.h> #include <driverlib/utils.h> #define CONSOLE_UART UARTA0_BASE #ifdef __TI_COMPILER_VERSION__ int asprintf(char **strp, const char *fmt, ...) { va_list ap; int len; *strp = MG_MALLOC(BUFSIZ); if (*strp == NULL) return -1; va_start(ap, fmt); len = vsnprintf(*strp, BUFSIZ, fmt, ap); va_end(ap); if (len > 0) { *strp = MG_REALLOC(*strp, len + 1); if (*strp == NULL) return -1; } if (len >= BUFSIZ) { va_start(ap, fmt); len = vsnprintf(*strp, len + 1, fmt, ap); va_end(ap); } return len; } #if MG_TI_NO_HOST_INTERFACE time_t HOSTtime() { struct timeval tp; gettimeofday(&tp, NULL); return tp.tv_sec; } #endif #endif /* __TI_COMPILER_VERSION__ */ void fprint_str(FILE *fp, const char *str) { while (*str != '\0') { if (*str == '\n') MAP_UARTCharPut(CONSOLE_UART, '\r'); MAP_UARTCharPut(CONSOLE_UART, *str++); } } void _exit(int status) { fprint_str(stderr, "_exit\n"); /* cause an unaligned access exception, that will drop you into gdb */ *(int *) 1 = status; while (1) ; /* avoid gcc warning because stdlib abort() has noreturn attribute */ } void _not_implemented(const char *what) { fprint_str(stderr, what); fprint_str(stderr, " is not implemented\n"); _exit(42); } int _kill(int pid, int sig) { (void) pid; (void) sig; _not_implemented("_kill"); return -1; } int _getpid() { fprint_str(stderr, "_getpid is not implemented\n"); return 42; } int _isatty(int fd) { /* 0, 1 and 2 are TTYs. */ return fd < 2; } #endif /* CS_PLATFORM == CS_P_CC3200 */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/msp432/msp432_libc.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if CS_PLATFORM == CS_P_MSP432 #include <ti/sysbios/BIOS.h> #include <ti/sysbios/knl/Clock.h> int gettimeofday(struct timeval *tp, void *tzp) { uint32_t ticks = Clock_getTicks(); tp->tv_sec = ticks / 1000; tp->tv_usec = (ticks % 1000) * 1000; return 0; } #endif /* CS_PLATFORM == CS_P_MSP432 */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/nrf5/nrf5_libc.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if (CS_PLATFORM == CS_P_NRF51 || CS_PLATFORM == CS_P_NRF52) && \ defined(__ARMCC_VERSION) int gettimeofday(struct timeval *tp, void *tzp) { /* TODO */ tp->tv_sec = 0; tp->tv_usec = 0; return 0; } #endif #ifdef MG_MODULE_LINES #line 1 "common/platforms/simplelink/sl_fs_slfs.h" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_ #define CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_ #if defined(MG_FS_SLFS) #include <stdio.h> #ifndef __TI_COMPILER_VERSION__ #include <unistd.h> #include <sys/stat.h> #endif #define MAX_OPEN_SLFS_FILES 8 /* Indirect libc interface - same functions, different names. */ int fs_slfs_open(const char *pathname, int flags, mode_t mode); int fs_slfs_close(int fd); ssize_t fs_slfs_read(int fd, void *buf, size_t count); ssize_t fs_slfs_write(int fd, const void *buf, size_t count); int fs_slfs_stat(const char *pathname, struct stat *s); int fs_slfs_fstat(int fd, struct stat *s); off_t fs_slfs_lseek(int fd, off_t offset, int whence); int fs_slfs_unlink(const char *filename); int fs_slfs_rename(const char *from, const char *to); void fs_slfs_set_file_size(const char *name, size_t size); void fs_slfs_set_file_flags(const char *name, uint32_t flags, uint32_t *token); void fs_slfs_unset_file_flags(const char *name); #endif /* defined(MG_FS_SLFS) */ #endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_ */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/simplelink/sl_fs_slfs.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Standard libc interface to TI SimpleLink FS. */ #if defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS) /* Amalgamated: #include "common/platforms/simplelink/sl_fs_slfs.h" */ #include <errno.h> #if CS_PLATFORM == CS_P_CC3200 #include <inc/hw_types.h> #endif /* Amalgamated: #include "common/cs_dbg.h" */ /* Amalgamated: #include "common/mg_mem.h" */ #if SL_MAJOR_VERSION_NUM < 2 int slfs_open(const unsigned char *fname, uint32_t flags, uint32_t *token) { _i32 fh; _i32 r = sl_FsOpen(fname, flags, (unsigned long *) token, &fh); return (r < 0 ? r : fh); } #else /* SL_MAJOR_VERSION_NUM >= 2 */ int slfs_open(const unsigned char *fname, uint32_t flags, uint32_t *token) { return sl_FsOpen(fname, flags, (unsigned long *) token); } #endif /* From sl_fs.c */ int set_errno(int e); const char *drop_dir(const char *fname, bool *is_slfs); /* * With SLFS, you have to pre-declare max file size. Yes. Really. * 64K should be enough for everyone. Right? */ #ifndef FS_SLFS_MAX_FILE_SIZE #define FS_SLFS_MAX_FILE_SIZE (64 * 1024) #endif struct sl_file_open_info { char *name; size_t size; uint32_t flags; uint32_t *token; }; struct sl_fd_info { _i32 fh; _off_t pos; size_t size; }; static struct sl_fd_info s_sl_fds[MAX_OPEN_SLFS_FILES]; static struct sl_file_open_info s_sl_file_open_infos[MAX_OPEN_SLFS_FILES]; static struct sl_file_open_info *fs_slfs_find_foi(const char *name, bool create); static int sl_fs_to_errno(_i32 r) { DBG(("SL error: %d", (int) r)); switch (r) { case SL_FS_OK: return 0; case SL_ERROR_FS_FILE_NAME_EXIST: return EEXIST; case SL_ERROR_FS_WRONG_FILE_NAME: return EINVAL; case SL_ERROR_FS_NO_AVAILABLE_NV_INDEX: case SL_ERROR_FS_NOT_ENOUGH_STORAGE_SPACE: return ENOSPC; case SL_ERROR_FS_FAILED_TO_ALLOCATE_MEM: return ENOMEM; case SL_ERROR_FS_FILE_NOT_EXISTS: return ENOENT; case SL_ERROR_FS_NOT_SUPPORTED: return ENOTSUP; } return ENXIO; } int fs_slfs_open(const char *pathname, int flags, mode_t mode) { int fd; for (fd = 0; fd < MAX_OPEN_SLFS_FILES; fd++) { if (s_sl_fds[fd].fh <= 0) break; } if (fd >= MAX_OPEN_SLFS_FILES) return set_errno(ENOMEM); struct sl_fd_info *fi = &s_sl_fds[fd]; /* * Apply path manipulations again, in case we got here directly * (via TI libc's "add_device"). */ pathname = drop_dir(pathname, NULL); _u32 am = 0; fi->size = (size_t) -1; int rw = (flags & 3); size_t new_size = 0; struct sl_file_open_info *foi = fs_slfs_find_foi(pathname, false /* create */); if (foi != NULL) { LOG(LL_DEBUG, ("FOI for %s: %d 0x%x %p", pathname, (int) foi->size, (unsigned int) foi->flags, foi->token)); } if (rw == O_RDONLY) { SlFsFileInfo_t sl_fi; _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi); if (r == SL_FS_OK) { fi->size = SL_FI_FILE_SIZE(sl_fi); } am = SL_FS_READ; } else { if (!(flags & O_TRUNC) || (flags & O_APPEND)) { // FailFS files cannot be opened for append and will be truncated // when opened for write. return set_errno(ENOTSUP); } if (flags & O_CREAT) { if (foi->size > 0) { new_size = foi->size; } else { new_size = FS_SLFS_MAX_FILE_SIZE; } am = FS_MODE_OPEN_CREATE(new_size, 0); } else { am = SL_FS_WRITE; } #if SL_MAJOR_VERSION_NUM >= 2 am |= SL_FS_OVERWRITE; #endif } uint32_t *token = NULL; if (foi != NULL) { am |= foi->flags; token = foi->token; } fi->fh = slfs_open((_u8 *) pathname, am, token); LOG(LL_DEBUG, ("sl_FsOpen(%s, 0x%x, %p) sz %u = %d", pathname, (int) am, token, (unsigned int) new_size, (int) fi->fh)); int r; if (fi->fh >= 0) { fi->pos = 0; r = fd; } else { r = set_errno(sl_fs_to_errno(fi->fh)); } return r; } int fs_slfs_close(int fd) { struct sl_fd_info *fi = &s_sl_fds[fd]; if (fi->fh <= 0) return set_errno(EBADF); _i32 r = sl_FsClose(fi->fh, NULL, NULL, 0); LOG(LL_DEBUG, ("sl_FsClose(%d) = %d", (int) fi->fh, (int) r)); s_sl_fds[fd].fh = -1; return set_errno(sl_fs_to_errno(r)); } ssize_t fs_slfs_read(int fd, void *buf, size_t count) { struct sl_fd_info *fi = &s_sl_fds[fd]; if (fi->fh <= 0) return set_errno(EBADF); /* Simulate EOF. sl_FsRead @ file_size return SL_FS_ERR_OFFSET_OUT_OF_RANGE. */ if (fi->pos == fi->size) return 0; _i32 r = sl_FsRead(fi->fh, fi->pos, buf, count); DBG(("sl_FsRead(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count, (int) r)); if (r >= 0) { fi->pos += r; return r; } return set_errno(sl_fs_to_errno(r)); } ssize_t fs_slfs_write(int fd, const void *buf, size_t count) { struct sl_fd_info *fi = &s_sl_fds[fd]; if (fi->fh <= 0) return set_errno(EBADF); _i32 r = sl_FsWrite(fi->fh, fi->pos, (_u8 *) buf, count); DBG(("sl_FsWrite(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count, (int) r)); if (r >= 0) { fi->pos += r; return r; } return set_errno(sl_fs_to_errno(r)); } int fs_slfs_stat(const char *pathname, struct stat *s) { SlFsFileInfo_t sl_fi; /* * Apply path manipulations again, in case we got here directly * (via TI libc's "add_device"). */ pathname = drop_dir(pathname, NULL); _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi); if (r == SL_FS_OK) { s->st_mode = S_IFREG | 0666; s->st_nlink = 1; s->st_size = SL_FI_FILE_SIZE(sl_fi); return 0; } return set_errno(sl_fs_to_errno(r)); } int fs_slfs_fstat(int fd, struct stat *s) { struct sl_fd_info *fi = &s_sl_fds[fd]; if (fi->fh <= 0) return set_errno(EBADF); s->st_mode = 0666; s->st_mode = S_IFREG | 0666; s->st_nlink = 1; s->st_size = fi->size; return 0; } off_t fs_slfs_lseek(int fd, off_t offset, int whence) { if (s_sl_fds[fd].fh <= 0) return set_errno(EBADF); switch (whence) { case SEEK_SET: s_sl_fds[fd].pos = offset; break; case SEEK_CUR: s_sl_fds[fd].pos += offset; break; case SEEK_END: return set_errno(ENOTSUP); } return 0; } int fs_slfs_unlink(const char *pathname) { /* * Apply path manipulations again, in case we got here directly * (via TI libc's "add_device"). */ pathname = drop_dir(pathname, NULL); return set_errno(sl_fs_to_errno(sl_FsDel((const _u8 *) pathname, 0))); } int fs_slfs_rename(const char *from, const char *to) { return set_errno(ENOTSUP); } static struct sl_file_open_info *fs_slfs_find_foi(const char *name, bool create) { int i = 0; for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) { if (s_sl_file_open_infos[i].name != NULL && strcmp(drop_dir(s_sl_file_open_infos[i].name, NULL), name) == 0) { break; } } if (i != MAX_OPEN_SLFS_FILES) return &s_sl_file_open_infos[i]; if (!create) return NULL; for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) { if (s_sl_file_open_infos[i].name == NULL) break; } if (i == MAX_OPEN_SLFS_FILES) { i = 0; /* Evict a random slot. */ } if (s_sl_file_open_infos[i].name != NULL) { free(s_sl_file_open_infos[i].name); } s_sl_file_open_infos[i].name = strdup(name); return &s_sl_file_open_infos[i]; } void fs_slfs_set_file_size(const char *name, size_t size) { struct sl_file_open_info *foi = fs_slfs_find_foi(name, true /* create */); foi->size = size; } void fs_slfs_set_file_flags(const char *name, uint32_t flags, uint32_t *token) { struct sl_file_open_info *foi = fs_slfs_find_foi(name, true /* create */); foi->flags = flags; foi->token = token; } void fs_slfs_unset_file_flags(const char *name) { struct sl_file_open_info *foi = fs_slfs_find_foi(name, false /* create */); if (foi == NULL) return; free(foi->name); memset(foi, 0, sizeof(*foi)); } #endif /* defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS) */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/simplelink/sl_fs.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if MG_NET_IF == MG_NET_IF_SIMPLELINK && \ (defined(MG_FS_SLFS) || defined(MG_FS_SPIFFS)) int set_errno(int e) { errno = e; return (e == 0 ? 0 : -1); } const char *drop_dir(const char *fname, bool *is_slfs) { if (is_slfs != NULL) { *is_slfs = (strncmp(fname, "SL:", 3) == 0); if (*is_slfs) fname += 3; } /* Drop "./", if any */ if (fname[0] == '.' && fname[1] == '/') { fname += 2; } /* * Drop / if it is the only one in the path. * This allows use of /pretend/directories but serves /file.txt as normal. */ if (fname[0] == '/' && strchr(fname + 1, '/') == NULL) { fname++; } return fname; } #if !defined(MG_FS_NO_VFS) #include <errno.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef __TI_COMPILER_VERSION__ #include <file.h> #endif /* Amalgamated: #include "common/cs_dbg.h" */ /* Amalgamated: #include "common/platform.h" */ #ifdef CC3200_FS_SPIFFS /* Amalgamated: #include "cc3200_fs_spiffs.h" */ #endif #ifdef MG_FS_SLFS /* Amalgamated: #include "sl_fs_slfs.h" */ #endif #define NUM_SYS_FDS 3 #define SPIFFS_FD_BASE 10 #define SLFS_FD_BASE 100 #if !defined(MG_UART_CHAR_PUT) && !defined(MG_UART_WRITE) #if CS_PLATFORM == CS_P_CC3200 #include <inc/hw_types.h> #include <inc/hw_memmap.h> #include <driverlib/rom.h> #include <driverlib/rom_map.h> #include <driverlib/uart.h> #define MG_UART_CHAR_PUT(fd, c) MAP_UARTCharPut(UARTA0_BASE, c); #else #define MG_UART_WRITE(fd, buf, len) #endif /* CS_PLATFORM == CS_P_CC3200 */ #endif /* !MG_UART_CHAR_PUT */ enum fd_type { FD_INVALID, FD_SYS, #ifdef CC3200_FS_SPIFFS FD_SPIFFS, #endif #ifdef MG_FS_SLFS FD_SLFS #endif }; static int fd_type(int fd) { if (fd >= 0 && fd < NUM_SYS_FDS) return FD_SYS; #ifdef CC3200_FS_SPIFFS if (fd >= SPIFFS_FD_BASE && fd < SPIFFS_FD_BASE + MAX_OPEN_SPIFFS_FILES) { return FD_SPIFFS; } #endif #ifdef MG_FS_SLFS if (fd >= SLFS_FD_BASE && fd < SLFS_FD_BASE + MAX_OPEN_SLFS_FILES) { return FD_SLFS; } #endif return FD_INVALID; } #if MG_TI_NO_HOST_INTERFACE int open(const char *pathname, unsigned flags, int mode) { #else int _open(const char *pathname, int flags, mode_t mode) { #endif int fd = -1; bool is_sl; const char *fname = drop_dir(pathname, &is_sl); if (is_sl) { #ifdef MG_FS_SLFS fd = fs_slfs_open(fname, flags, mode); if (fd >= 0) fd += SLFS_FD_BASE; #endif } else { #ifdef CC3200_FS_SPIFFS fd = fs_spiffs_open(fname, flags, mode); if (fd >= 0) fd += SPIFFS_FD_BASE; #endif } LOG(LL_DEBUG, ("open(%s, 0x%x) = %d, fname = %s", pathname, flags, fd, fname)); return fd; } int _stat(const char *pathname, struct stat *st) { int res = -1; bool is_sl; const char *fname = drop_dir(pathname, &is_sl); memset(st, 0, sizeof(*st)); /* Simulate statting the root directory. */ if (fname[0] == '\0' || strcmp(fname, ".") == 0) { st->st_ino = 0; st->st_mode = S_IFDIR | 0777; st->st_nlink = 1; st->st_size = 0; return 0; } if (is_sl) { #ifdef MG_FS_SLFS res = fs_slfs_stat(fname, st); #endif } else { #ifdef CC3200_FS_SPIFFS res = fs_spiffs_stat(fname, st); #endif } LOG(LL_DEBUG, ("stat(%s) = %d; fname = %s", pathname, res, fname)); return res; } #if MG_TI_NO_HOST_INTERFACE int close(int fd) { #else int _close(int fd) { #endif int r = -1; switch (fd_type(fd)) { case FD_INVALID: r = set_errno(EBADF); break; case FD_SYS: r = set_errno(EACCES); break; #ifdef CC3200_FS_SPIFFS case FD_SPIFFS: r = fs_spiffs_close(fd - SPIFFS_FD_BASE); break; #endif #ifdef MG_FS_SLFS case FD_SLFS: r = fs_slfs_close(fd - SLFS_FD_BASE); break; #endif } DBG(("close(%d) = %d", fd, r)); return r; } #if MG_TI_NO_HOST_INTERFACE off_t lseek(int fd, off_t offset, int whence) { #else off_t _lseek(int fd, off_t offset, int whence) { #endif int r = -1; switch (fd_type(fd)) { case FD_INVALID: r = set_errno(EBADF); break; case FD_SYS: r = set_errno(ESPIPE); break; #ifdef CC3200_FS_SPIFFS case FD_SPIFFS: r = fs_spiffs_lseek(fd - SPIFFS_FD_BASE, offset, whence); break; #endif #ifdef MG_FS_SLFS case FD_SLFS: r = fs_slfs_lseek(fd - SLFS_FD_BASE, offset, whence); break; #endif } DBG(("lseek(%d, %d, %d) = %d", fd, (int) offset, whence, r)); return r; } int _fstat(int fd, struct stat *s) { int r = -1; memset(s, 0, sizeof(*s)); switch (fd_type(fd)) { case FD_INVALID: r = set_errno(EBADF); break; case FD_SYS: { /* Create barely passable stats for STD{IN,OUT,ERR}. */ memset(s, 0, sizeof(*s)); s->st_ino = fd; s->st_mode = S_IFCHR | 0666; r = 0; break; } #ifdef CC3200_FS_SPIFFS case FD_SPIFFS: r = fs_spiffs_fstat(fd - SPIFFS_FD_BASE, s); break; #endif #ifdef MG_FS_SLFS case FD_SLFS: r = fs_slfs_fstat(fd - SLFS_FD_BASE, s); break; #endif } DBG(("fstat(%d) = %d", fd, r)); return r; } #if MG_TI_NO_HOST_INTERFACE int read(int fd, char *buf, unsigned count) { #else ssize_t _read(int fd, void *buf, size_t count) { #endif int r = -1; switch (fd_type(fd)) { case FD_INVALID: r = set_errno(EBADF); break; case FD_SYS: { if (fd != 0) { r = set_errno(EACCES); break; } /* Should we allow reading from stdin = uart? */ r = set_errno(ENOTSUP); break; } #ifdef CC3200_FS_SPIFFS case FD_SPIFFS: r = fs_spiffs_read(fd - SPIFFS_FD_BASE, buf, count); break; #endif #ifdef MG_FS_SLFS case FD_SLFS: r = fs_slfs_read(fd - SLFS_FD_BASE, buf, count); break; #endif } DBG(("read(%d, %u) = %d", fd, count, r)); return r; } #if MG_TI_NO_HOST_INTERFACE int write(int fd, const char *buf, unsigned count) { #else ssize_t _write(int fd, const void *buf, size_t count) { #endif int r = -1; switch (fd_type(fd)) { case FD_INVALID: r = set_errno(EBADF); break; case FD_SYS: { if (fd == 0) { r = set_errno(EACCES); break; } #ifdef MG_UART_WRITE MG_UART_WRITE(fd, buf, count); #elif defined(MG_UART_CHAR_PUT) { size_t i; for (i = 0; i < count; i++) { const char c = ((const char *) buf)[i]; if (c == '\n') MG_UART_CHAR_PUT(fd, '\r'); MG_UART_CHAR_PUT(fd, c); } } #endif r = count; break; } #ifdef CC3200_FS_SPIFFS case FD_SPIFFS: r = fs_spiffs_write(fd - SPIFFS_FD_BASE, buf, count); break; #endif #ifdef MG_FS_SLFS case FD_SLFS: r = fs_slfs_write(fd - SLFS_FD_BASE, buf, count); break; #endif } return r; } /* * On Newlib we override rename directly too, because the default * implementation using _link and _unlink doesn't work for us. */ #if MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION) int rename(const char *frompath, const char *topath) { int r = -1; bool is_sl_from, is_sl_to; const char *from = drop_dir(frompath, &is_sl_from); const char *to = drop_dir(topath, &is_sl_to); if (is_sl_from || is_sl_to) { set_errno(ENOTSUP); } else { #ifdef CC3200_FS_SPIFFS r = fs_spiffs_rename(from, to); #endif } DBG(("rename(%s, %s) = %d", from, to, r)); return r; } #endif /* MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION) */ #if MG_TI_NO_HOST_INTERFACE int unlink(const char *pathname) { #else int _unlink(const char *pathname) { #endif int r = -1; bool is_sl; const char *fname = drop_dir(pathname, &is_sl); if (is_sl) { #ifdef MG_FS_SLFS r = fs_slfs_unlink(fname); #endif } else { #ifdef CC3200_FS_SPIFFS r = fs_spiffs_unlink(fname); #endif } DBG(("unlink(%s) = %d, fname = %s", pathname, r, fname)); return r; } #ifdef CC3200_FS_SPIFFS /* FailFS does not support listing files. */ DIR *opendir(const char *dir_name) { DIR *r = NULL; bool is_sl; drop_dir(dir_name, &is_sl); if (is_sl) { r = NULL; set_errno(ENOTSUP); } else { r = fs_spiffs_opendir(dir_name); } DBG(("opendir(%s) = %p", dir_name, r)); return r; } struct dirent *readdir(DIR *dir) { struct dirent *res = fs_spiffs_readdir(dir); DBG(("readdir(%p) = %p", dir, res)); return res; } int closedir(DIR *dir) { int res = fs_spiffs_closedir(dir); DBG(("closedir(%p) = %d", dir, res)); return res; } int rmdir(const char *path) { return fs_spiffs_rmdir(path); } int mkdir(const char *path, mode_t mode) { (void) path; (void) mode; /* for spiffs supports only root dir, which comes from mongoose as '.' */ return (strlen(path) == 1 && *path == '.') ? 0 : ENOTDIR; } #endif int sl_fs_init(void) { int ret = 1; #ifdef __TI_COMPILER_VERSION__ #ifdef MG_FS_SLFS #pragma diag_push #pragma diag_suppress 169 /* Nothing we can do about the prototype mismatch. \ */ ret = (add_device("SL", _MSA, fs_slfs_open, fs_slfs_close, fs_slfs_read, fs_slfs_write, fs_slfs_lseek, fs_slfs_unlink, fs_slfs_rename) == 0); #pragma diag_pop #endif #endif return ret; } #endif /* !defined(MG_FS_NO_VFS) */ #endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && (defined(MG_FS_SLFS) || \ defined(MG_FS_SPIFFS)) */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/simplelink/sl_socket.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if MG_NET_IF == MG_NET_IF_SIMPLELINK #include <errno.h> #include <stdio.h> /* Amalgamated: #include "common/platform.h" */ const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) { int res; struct in_addr *in = (struct in_addr *) src; if (af != AF_INET) { errno = ENOTSUP; return NULL; } res = snprintf(dst, size, "%lu.%lu.%lu.%lu", SL_IPV4_BYTE(in->s_addr, 0), SL_IPV4_BYTE(in->s_addr, 1), SL_IPV4_BYTE(in->s_addr, 2), SL_IPV4_BYTE(in->s_addr, 3)); return res > 0 ? dst : NULL; } char *inet_ntoa(struct in_addr n) { static char a[16]; return (char *) inet_ntop(AF_INET, &n, a, sizeof(a)); } int inet_pton(int af, const char *src, void *dst) { uint32_t a0, a1, a2, a3; uint8_t *db = (uint8_t *) dst; if (af != AF_INET) { errno = ENOTSUP; return 0; } if (sscanf(src, "%lu.%lu.%lu.%lu", &a0, &a1, &a2, &a3) != 4) { return 0; } *db = a3; *(db + 1) = a2; *(db + 2) = a1; *(db + 3) = a0; return 1; } #endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/simplelink/sl_mg_task.c" #endif #if MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI) /* Amalgamated: #include "mg_task.h" */ #include <oslib/osi.h> enum mg_q_msg_type { MG_Q_MSG_CB, }; struct mg_q_msg { enum mg_q_msg_type type; void (*cb)(struct mg_mgr *mgr, void *arg); void *arg; }; static OsiMsgQ_t s_mg_q; static void mg_task(void *arg); bool mg_start_task(int priority, int stack_size, mg_init_cb mg_init) { if (osi_MsgQCreate(&s_mg_q, "MG", sizeof(struct mg_q_msg), 16) != OSI_OK) { return false; } if (osi_TaskCreate(mg_task, (const signed char *) "MG", stack_size, (void *) mg_init, priority, NULL) != OSI_OK) { return false; } return true; } static void mg_task(void *arg) { struct mg_mgr mgr; mg_init_cb mg_init = (mg_init_cb) arg; mg_mgr_init(&mgr, NULL); mg_init(&mgr); while (1) { struct mg_q_msg msg; mg_mgr_poll(&mgr, 1); if (osi_MsgQRead(&s_mg_q, &msg, 1) != OSI_OK) continue; switch (msg.type) { case MG_Q_MSG_CB: { msg.cb(&mgr, msg.arg); } } } } void mg_run_in_task(void (*cb)(struct mg_mgr *mgr, void *arg), void *cb_arg) { struct mg_q_msg msg = {MG_Q_MSG_CB, cb, cb_arg}; osi_MsgQWrite(&s_mg_q, &msg, OSI_NO_WAIT); } #endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI) \ */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/simplelink/sl_net_if.h" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_ #define CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_ /* Amalgamated: #include "mongoose/src/net_if.h" */ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #ifndef MG_ENABLE_NET_IF_SIMPLELINK #define MG_ENABLE_NET_IF_SIMPLELINK MG_NET_IF == MG_NET_IF_SIMPLELINK #endif extern const struct mg_iface_vtable mg_simplelink_iface_vtable; #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_ */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/simplelink/sl_net_if.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Amalgamated: #include "common/platforms/simplelink/sl_net_if.h" */ #if MG_ENABLE_NET_IF_SIMPLELINK /* Amalgamated: #include "mongoose/src/internal.h" */ /* Amalgamated: #include "mongoose/src/util.h" */ #define MG_TCP_RECV_BUFFER_SIZE 1024 #define MG_UDP_RECV_BUFFER_SIZE 1500 static sock_t mg_open_listening_socket(struct mg_connection *nc, union socket_address *sa, int type, int proto); static void mg_set_non_blocking_mode(sock_t sock) { SlSockNonblocking_t opt; #if SL_MAJOR_VERSION_NUM < 2 opt.NonblockingEnabled = 1; #else opt.NonBlockingEnabled = 1; #endif sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &opt, sizeof(opt)); } static int mg_is_error(int n) { return (n < 0 && n != SL_ERROR_BSD_EALREADY && n != SL_ERROR_BSD_EAGAIN); } static void mg_sl_if_connect_tcp(struct mg_connection *nc, const union socket_address *sa) { int proto = 0; #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET; #endif sock_t sock = sl_Socket(AF_INET, SOCK_STREAM, proto); if (sock < 0) { nc->err = sock; goto out; } mg_sock_set(nc, sock); #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK nc->err = sl_set_ssl_opts(sock, nc); if (nc->err != 0) goto out; #endif nc->err = sl_Connect(sock, &sa->sa, sizeof(sa->sin)); out: DBG(("%p to %s:%d sock %d %d err %d", nc, inet_ntoa(sa->sin.sin_addr), ntohs(sa->sin.sin_port), nc->sock, proto, nc->err)); } static void mg_sl_if_connect_udp(struct mg_connection *nc) { sock_t sock = sl_Socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) { nc->err = sock; return; } mg_sock_set(nc, sock); nc->err = 0; } static int mg_sl_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) { int proto = 0; if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET; sock_t sock = mg_open_listening_socket(nc, sa, SOCK_STREAM, proto); if (sock < 0) return sock; mg_sock_set(nc, sock); return 0; } static int mg_sl_if_listen_udp(struct mg_connection *nc, union socket_address *sa) { sock_t sock = mg_open_listening_socket(nc, sa, SOCK_DGRAM, 0); if (sock == INVALID_SOCKET) return (errno ? errno : 1); mg_sock_set(nc, sock); return 0; } static int mg_sl_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) { int n = (int) sl_Send(nc->sock, buf, len, 0); if (n < 0 && !mg_is_error(n)) n = 0; return n; } static int mg_sl_if_udp_send(struct mg_connection *nc, const void *buf, size_t len) { int n = sl_SendTo(nc->sock, buf, len, 0, &nc->sa.sa, sizeof(nc->sa.sin)); if (n < 0 && !mg_is_error(n)) n = 0; return n; } static int mg_sl_if_tcp_recv(struct mg_connection *nc, void *buf, size_t len) { int n = sl_Recv(nc->sock, buf, len, 0); if (n == 0) { /* Orderly shutdown of the socket, try flushing output. */ nc->flags |= MG_F_SEND_AND_CLOSE; } else if (n < 0 && !mg_is_error(n)) { n = 0; } return n; } static int mg_sl_if_udp_recv(struct mg_connection *nc, void *buf, size_t len, union socket_address *sa, size_t *sa_len) { SlSocklen_t sa_len_t = *sa_len; int n = sl_RecvFrom(nc->sock, buf, MG_UDP_RECV_BUFFER_SIZE, 0, (SlSockAddr_t *) sa, &sa_len_t); *sa_len = sa_len_t; if (n < 0 && !mg_is_error(n)) n = 0; return n; } static int mg_sl_if_create_conn(struct mg_connection *nc) { (void) nc; return 1; } void mg_sl_if_destroy_conn(struct mg_connection *nc) { if (nc->sock == INVALID_SOCKET) return; /* For UDP, only close outgoing sockets or listeners. */ if (!(nc->flags & MG_F_UDP) || nc->listener == NULL) { sl_Close(nc->sock); } nc->sock = INVALID_SOCKET; } static int mg_accept_conn(struct mg_connection *lc) { struct mg_connection *nc; union socket_address sa; socklen_t sa_len = sizeof(sa); sock_t sock = sl_Accept(lc->sock, &sa.sa, &sa_len); if (sock < 0) { DBG(("%p: failed to accept: %d", lc, sock)); return 0; } nc = mg_if_accept_new_conn(lc); if (nc == NULL) { sl_Close(sock); return 0; } DBG(("%p conn from %s:%d", nc, inet_ntoa(sa.sin.sin_addr), ntohs(sa.sin.sin_port))); mg_sock_set(nc, sock); mg_if_accept_tcp_cb(nc, &sa, sa_len); return 1; } /* 'sa' must be an initialized address to bind to */ static sock_t mg_open_listening_socket(struct mg_connection *nc, union socket_address *sa, int type, int proto) { int r; socklen_t sa_len = (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6); sock_t sock = sl_Socket(sa->sa.sa_family, type, proto); if (sock < 0) return sock; #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK if ((r = sl_set_ssl_opts(sock, nc)) < 0) goto clean; #endif if ((r = sl_Bind(sock, &sa->sa, sa_len)) < 0) goto clean; if (type != SOCK_DGRAM) { if ((r = sl_Listen(sock, SOMAXCONN)) < 0) goto clean; } mg_set_non_blocking_mode(sock); clean: if (r < 0) { sl_Close(sock); sock = r; } return sock; } #define _MG_F_FD_CAN_READ 1 #define _MG_F_FD_CAN_WRITE 1 << 1 #define _MG_F_FD_ERROR 1 << 2 void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) { DBG(("%p fd=%d fd_flags=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->sock, fd_flags, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len)); if (!mg_if_poll(nc, now)) return; if (nc->flags & MG_F_CONNECTING) { if ((nc->flags & MG_F_UDP) || nc->err != SL_ERROR_BSD_EALREADY) { mg_if_connect_cb(nc, nc->err); } else { /* In SimpleLink, to get status of non-blocking connect() we need to wait * until socket is writable and repeat the call to sl_Connect again, * which will now return the real status. */ if (fd_flags & _MG_F_FD_CAN_WRITE) { nc->err = sl_Connect(nc->sock, &nc->sa.sa, sizeof(nc->sa.sin)); DBG(("%p conn res=%d", nc, nc->err)); if (nc->err == SL_ERROR_BSD_ESECSNOVERIFY || /* TODO(rojer): Provide API to set the date for verification. */ nc->err == SL_ERROR_BSD_ESECDATEERROR #if SL_MAJOR_VERSION_NUM >= 2 /* Per SWRU455, this error does not mean verification failed, * it only means that the cert used is not present in the trusted * root CA catalog. Which is perfectly fine. */ || nc->err == SL_ERROR_BSD_ESECUNKNOWNROOTCA #endif ) { nc->err = 0; } mg_if_connect_cb(nc, nc->err); } } /* Ignore read/write in further processing, we've handled it. */ fd_flags &= ~(_MG_F_FD_CAN_READ | _MG_F_FD_CAN_WRITE); } if (fd_flags & _MG_F_FD_CAN_READ) { if (nc->flags & MG_F_UDP) { mg_if_can_recv_cb(nc); } else { if (nc->flags & MG_F_LISTENING) { mg_accept_conn(nc); } else { mg_if_can_recv_cb(nc); } } } if (fd_flags & _MG_F_FD_CAN_WRITE) { mg_if_can_send_cb(nc); } DBG(("%p after fd=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->sock, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len)); } /* Associate a socket to a connection. */ void mg_sl_if_sock_set(struct mg_connection *nc, sock_t sock) { mg_set_non_blocking_mode(sock); nc->sock = sock; DBG(("%p %d", nc, sock)); } void mg_sl_if_init(struct mg_iface *iface) { (void) iface; DBG(("%p using sl_Select()", iface->mgr)); } void mg_sl_if_free(struct mg_iface *iface) { (void) iface; } void mg_sl_if_add_conn(struct mg_connection *nc) { (void) nc; } void mg_sl_if_remove_conn(struct mg_connection *nc) { (void) nc; } time_t mg_sl_if_poll(struct mg_iface *iface, int timeout_ms) { struct mg_mgr *mgr = iface->mgr; double now = mg_time(); double min_timer; struct mg_connection *nc, *tmp; struct SlTimeval_t tv; SlFdSet_t read_set, write_set, err_set; sock_t max_fd = INVALID_SOCKET; int num_fds, num_ev = 0, num_timers = 0; SL_SOCKET_FD_ZERO(&read_set); SL_SOCKET_FD_ZERO(&write_set); SL_SOCKET_FD_ZERO(&err_set); /* * Note: it is ok to have connections with sock == INVALID_SOCKET in the list, * e.g. timer-only "connections". */ min_timer = 0; for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) { tmp = nc->next; if (nc->sock != INVALID_SOCKET) { num_fds++; if (!(nc->flags & MG_F_WANT_WRITE) && nc->recv_mbuf.len < nc->recv_mbuf_limit && (!(nc->flags & MG_F_UDP) || nc->listener == NULL)) { SL_SOCKET_FD_SET(nc->sock, &read_set); if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock; } if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) || (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) { SL_SOCKET_FD_SET(nc->sock, &write_set); SL_SOCKET_FD_SET(nc->sock, &err_set); if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock; } } if (nc->ev_timer_time > 0) { if (num_timers == 0 || nc->ev_timer_time < min_timer) { min_timer = nc->ev_timer_time; } num_timers++; } } /* * If there is a timer to be fired earlier than the requested timeout, * adjust the timeout. */ if (num_timers > 0) { double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */; if (timer_timeout_ms < timeout_ms) { timeout_ms = timer_timeout_ms; } } if (timeout_ms < 0) timeout_ms = 0; tv.tv_sec = timeout_ms / 1000; tv.tv_usec = (timeout_ms % 1000) * 1000; if (num_fds > 0) { num_ev = sl_Select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv); } now = mg_time(); DBG(("sl_Select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev, num_fds, timeout_ms)); for (nc = mgr->active_connections; nc != NULL; nc = tmp) { int fd_flags = 0; if (nc->sock != INVALID_SOCKET) { if (num_ev > 0) { fd_flags = (SL_SOCKET_FD_ISSET(nc->sock, &read_set) && (!(nc->flags & MG_F_UDP) || nc->listener == NULL) ? _MG_F_FD_CAN_READ : 0) | (SL_SOCKET_FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE : 0) | (SL_SOCKET_FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0); } /* SimpleLink does not report UDP sockets as writable. */ if (nc->flags & MG_F_UDP && nc->send_mbuf.len > 0) { fd_flags |= _MG_F_FD_CAN_WRITE; } } tmp = nc->next; mg_mgr_handle_conn(nc, fd_flags, now); } return now; } void mg_sl_if_get_conn_addr(struct mg_connection *nc, int remote, union socket_address *sa) { /* SimpleLink does not provide a way to get socket's peer address after * accept or connect. Address should have been preserved in the connection, * so we do our best here by using it. */ if (remote) memcpy(sa, &nc->sa, sizeof(*sa)); } void sl_restart_cb(struct mg_mgr *mgr) { /* * SimpleLink has been restarted, meaning all sockets have been invalidated. * We try our best - we'll restart the listeners, but for outgoing * connections we have no option but to terminate. */ struct mg_connection *nc; for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) { if (nc->sock == INVALID_SOCKET) continue; /* Could be a timer */ if (nc->flags & MG_F_LISTENING) { DBG(("restarting %p %s:%d", nc, inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port))); int res = (nc->flags & MG_F_UDP ? mg_sl_if_listen_udp(nc, &nc->sa) : mg_sl_if_listen_tcp(nc, &nc->sa)); if (res == 0) continue; /* Well, we tried and failed. Fall through to closing. */ } nc->sock = INVALID_SOCKET; DBG(("terminating %p %s:%d", nc, inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port))); /* TODO(rojer): Outgoing UDP? */ nc->flags |= MG_F_CLOSE_IMMEDIATELY; } } /* clang-format off */ #define MG_SL_IFACE_VTABLE \ { \ mg_sl_if_init, \ mg_sl_if_free, \ mg_sl_if_add_conn, \ mg_sl_if_remove_conn, \ mg_sl_if_poll, \ mg_sl_if_listen_tcp, \ mg_sl_if_listen_udp, \ mg_sl_if_connect_tcp, \ mg_sl_if_connect_udp, \ mg_sl_if_tcp_send, \ mg_sl_if_udp_send, \ mg_sl_if_tcp_recv, \ mg_sl_if_udp_recv, \ mg_sl_if_create_conn, \ mg_sl_if_destroy_conn, \ mg_sl_if_sock_set, \ mg_sl_if_get_conn_addr, \ } /* clang-format on */ const struct mg_iface_vtable mg_simplelink_iface_vtable = MG_SL_IFACE_VTABLE; #if MG_NET_IF == MG_NET_IF_SIMPLELINK const struct mg_iface_vtable mg_default_iface_vtable = MG_SL_IFACE_VTABLE; #endif #endif /* MG_ENABLE_NET_IF_SIMPLELINK */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/simplelink/sl_ssl_if.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK /* Amalgamated: #include "common/mg_mem.h" */ #ifndef MG_SSL_IF_SIMPLELINK_SLFS_PREFIX #define MG_SSL_IF_SIMPLELINK_SLFS_PREFIX "SL:" #endif #define MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN \ (sizeof(MG_SSL_IF_SIMPLELINK_SLFS_PREFIX) - 1) struct mg_ssl_if_ctx { char *ssl_cert; char *ssl_key; char *ssl_ca_cert; char *ssl_server_name; }; void mg_ssl_if_init() { } enum mg_ssl_if_result mg_ssl_if_conn_init( struct mg_connection *nc, const struct mg_ssl_if_conn_params *params, const char **err_msg) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx)); if (ctx == NULL) { MG_SET_PTRPTR(err_msg, "Out of memory"); return MG_SSL_ERROR; } nc->ssl_if_data = ctx; if (params->cert != NULL || params->key != NULL) { if (params->cert != NULL && params->key != NULL) { ctx->ssl_cert = strdup(params->cert); ctx->ssl_key = strdup(params->key); } else { MG_SET_PTRPTR(err_msg, "Both cert and key are required."); return MG_SSL_ERROR; } } if (params->ca_cert != NULL && strcmp(params->ca_cert, "*") != 0) { ctx->ssl_ca_cert = strdup(params->ca_cert); } /* TODO(rojer): cipher_suites. */ if (params->server_name != NULL) { ctx->ssl_server_name = strdup(params->server_name); } return MG_SSL_OK; } enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc, struct mg_connection *lc) { /* SimpleLink does everything for us, nothing for us to do. */ (void) nc; (void) lc; return MG_SSL_OK; } enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) { /* SimpleLink has already performed the handshake, nothing to do. */ return MG_SSL_OK; } int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t len) { /* SimpelLink handles TLS, so this is just a pass-through. */ int n = nc->iface->vtable->tcp_recv(nc, buf, len); if (n == 0) nc->flags |= MG_F_WANT_READ; return n; } int mg_ssl_if_write(struct mg_connection *nc, const void *buf, size_t len) { /* SimpelLink handles TLS, so this is just a pass-through. */ return nc->iface->vtable->tcp_send(nc, buf, len); } void mg_ssl_if_conn_close_notify(struct mg_connection *nc) { /* Nothing to do */ (void) nc; } void mg_ssl_if_conn_free(struct mg_connection *nc) { struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; if (ctx == NULL) return; nc->ssl_if_data = NULL; MG_FREE(ctx->ssl_cert); MG_FREE(ctx->ssl_key); MG_FREE(ctx->ssl_ca_cert); MG_FREE(ctx->ssl_server_name); memset(ctx, 0, sizeof(*ctx)); MG_FREE(ctx); } bool pem_to_der(const char *pem_file, const char *der_file) { bool ret = false; FILE *pf = NULL, *df = NULL; bool writing = false; pf = fopen(pem_file, "r"); if (pf == NULL) goto clean; remove(der_file); fs_slfs_set_file_size(der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN, 2048); df = fopen(der_file, "w"); fs_slfs_unset_file_flags(der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN); if (df == NULL) goto clean; while (1) { char pem_buf[70]; char der_buf[48]; if (!fgets(pem_buf, sizeof(pem_buf), pf)) break; if (writing) { if (strstr(pem_buf, "-----END ") != NULL) { ret = true; break; } int l = 0; while (!isspace((unsigned int) pem_buf[l])) l++; int der_len = 0; cs_base64_decode((const unsigned char *) pem_buf, sizeof(pem_buf), der_buf, &der_len); if (der_len <= 0) break; if (fwrite(der_buf, 1, der_len, df) != der_len) break; } else if (strstr(pem_buf, "-----BEGIN ") != NULL) { writing = true; } } clean: if (pf != NULL) fclose(pf); if (df != NULL) { fclose(df); if (!ret) remove(der_file); } return ret; } #if MG_ENABLE_FILESYSTEM && defined(MG_FS_SLFS) /* If the file's extension is .pem, convert it to DER format and put on SLFS. */ static char *sl_pem2der(const char *pem_file) { const char *pem_ext = strstr(pem_file, ".pem"); if (pem_ext == NULL || *(pem_ext + 4) != '\0') { return strdup(pem_file); } char *der_file = NULL; /* DER file must be located on SLFS, add prefix. */ int l = mg_asprintf(&der_file, 0, MG_SSL_IF_SIMPLELINK_SLFS_PREFIX "%.*s.der", (int) (pem_ext - pem_file), pem_file); if (der_file == NULL) return NULL; bool result = false; cs_stat_t st; if (mg_stat(der_file, &st) != 0) { result = pem_to_der(pem_file, der_file); LOG(LL_DEBUG, ("%s -> %s = %d", pem_file, der_file, result)); } else { /* File exists, assume it's already been converted. */ result = true; } if (result) { /* Strip the SL: prefix we added since NWP does not expect it. */ memmove(der_file, der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN, l - 2 /* including \0 */); } else { MG_FREE(der_file); der_file = NULL; } return der_file; } #else static char *sl_pem2der(const char *pem_file) { return strdup(pem_file); } #endif int sl_set_ssl_opts(int sock, struct mg_connection *nc) { int err; const struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; DBG(("%p ssl ctx: %p", nc, ctx)); if (ctx == NULL) return 0; DBG(("%p %s,%s,%s,%s", nc, (ctx->ssl_cert ? ctx->ssl_cert : "-"), (ctx->ssl_key ? ctx->ssl_cert : "-"), (ctx->ssl_ca_cert ? ctx->ssl_ca_cert : "-"), (ctx->ssl_server_name ? ctx->ssl_server_name : "-"))); if (ctx->ssl_cert != NULL && ctx->ssl_key != NULL) { char *ssl_cert = sl_pem2der(ctx->ssl_cert), *ssl_key = NULL; if (ssl_cert != NULL) { err = sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME, ssl_cert, strlen(ssl_cert)); MG_FREE(ssl_cert); LOG(LL_DEBUG, ("CERTIFICATE_FILE_NAME %s -> %d", ssl_cert, err)); ssl_key = sl_pem2der(ctx->ssl_key); if (ssl_key != NULL) { err = sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME, ssl_key, strlen(ssl_key)); MG_FREE(ssl_key); LOG(LL_DEBUG, ("PRIVATE_KEY_FILE_NAME %s -> %d", ssl_key, err)); } else { err = -1; } } else { err = -1; } if (err != 0) return err; } if (ctx->ssl_ca_cert != NULL) { if (ctx->ssl_ca_cert[0] != '\0') { char *ssl_ca_cert = sl_pem2der(ctx->ssl_ca_cert); if (ssl_ca_cert != NULL) { err = sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_SECURE_FILES_CA_FILE_NAME, ssl_ca_cert, strlen(ssl_ca_cert)); LOG(LL_DEBUG, ("CA_FILE_NAME %s -> %d", ssl_ca_cert, err)); } else { err = -1; } MG_FREE(ssl_ca_cert); if (err != 0) return err; } } if (ctx->ssl_server_name != NULL) { err = sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_SECURE_DOMAIN_NAME_VERIFICATION, ctx->ssl_server_name, strlen(ctx->ssl_server_name)); DBG(("DOMAIN_NAME_VERIFICATION %s -> %d", ctx->ssl_server_name, err)); /* Domain name verificationw as added in a NWP service pack, older * versions return SL_ERROR_BSD_ENOPROTOOPT. There isn't much we can do * about it, * so we ignore the error. */ if (err != 0 && err != SL_ERROR_BSD_ENOPROTOOPT) return err; } return 0; } #endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/lwip/mg_lwip_net_if.h" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_ #define CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_ #ifndef MG_ENABLE_NET_IF_LWIP_LOW_LEVEL #define MG_ENABLE_NET_IF_LWIP_LOW_LEVEL MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL #endif #if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL #include <stdint.h> extern const struct mg_iface_vtable mg_lwip_iface_vtable; struct mg_lwip_conn_state { struct mg_connection *nc; struct mg_connection *lc; union { struct tcp_pcb *tcp; struct udp_pcb *udp; } pcb; err_t err; size_t num_sent; /* Number of acknowledged bytes to be reported to the core */ struct pbuf *rx_chain; /* Chain of incoming data segments. */ size_t rx_offset; /* Offset within the first pbuf (if partially consumed) */ /* Last SSL write size, for retries. */ int last_ssl_write_size; /* Whether MG_SIG_RECV is already pending for this connection */ int recv_pending; /* Whether the connection is about to close, just `rx_chain` needs to drain */ int draining_rx_chain; }; enum mg_sig_type { MG_SIG_CONNECT_RESULT = 1, MG_SIG_RECV = 2, MG_SIG_CLOSE_CONN = 3, MG_SIG_TOMBSTONE = 4, MG_SIG_ACCEPT = 5, }; void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc); /* To be implemented by the platform. */ void mg_lwip_mgr_schedule_poll(struct mg_mgr *mgr); #endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */ #endif /* CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_ */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/lwip/mg_lwip_net_if.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL /* Amalgamated: #include "common/mg_mem.h" */ #include <lwip/init.h> #include <lwip/pbuf.h> #include <lwip/tcp.h> #include <lwip/tcpip.h> #if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105 #include <lwip/priv/tcp_priv.h> /* For tcp_seg */ #include <lwip/priv/tcpip_priv.h> /* For tcpip_api_call */ #else #include <lwip/tcp_impl.h> #endif #include <lwip/udp.h> /* Amalgamated: #include "common/cs_dbg.h" */ /* * Newest versions of LWIP have ip_2_ip4, older have ipX_2_ip, * even older have nothing. */ #ifndef ip_2_ip4 #ifdef ipX_2_ip #define ip_2_ip4(addr) ipX_2_ip(addr) #else #define ip_2_ip4(addr) (addr) #endif #endif /* * Depending on whether Mongoose is compiled with ipv6 support, use right * lwip functions */ #if MG_ENABLE_IPV6 #define TCP_NEW tcp_new_ip6 #define TCP_BIND tcp_bind_ip6 #define UDP_BIND udp_bind_ip6 #define IPADDR_NTOA(x) ip6addr_ntoa((const ip6_addr_t *)(x)) #define SET_ADDR(dst, src) \ memcpy((dst)->sin6.sin6_addr.s6_addr, (src)->ip6.addr, \ sizeof((dst)->sin6.sin6_addr.s6_addr)) #else #define TCP_NEW tcp_new #define TCP_BIND tcp_bind #define UDP_BIND udp_bind #define IPADDR_NTOA ipaddr_ntoa #define SET_ADDR(dst, src) (dst)->sin.sin_addr.s_addr = ip_2_ip4(src)->addr #endif #if !NO_SYS #if LWIP_TCPIP_CORE_LOCKING /* With locking tcpip_api_call is just a function call wrapped in lock/unlock, * so we can get away with just casting. */ void mg_lwip_netif_run_on_tcpip(void (*fn)(void *), void *arg) { tcpip_api_call((tcpip_api_call_fn) fn, (struct tcpip_api_call_data *) arg); } #else static sys_sem_t s_tcpip_call_lock_sem = NULL; static sys_sem_t s_tcpip_call_sync_sem = NULL; struct mg_lwip_netif_tcpip_call_ctx { void (*fn)(void *); void *arg; }; static void xxx_tcpip(void *arg) { struct mg_lwip_netif_tcpip_call_ctx *ctx = (struct mg_lwip_netif_tcpip_call_ctx *) arg; ctx->fn(ctx->arg); sys_sem_signal(&s_tcpip_call_sync_sem); } void mg_lwip_netif_run_on_tcpip(void (*fn)(void *), void *arg) { struct mg_lwip_netif_tcpip_call_ctx ctx = {.fn = fn, .arg = arg}; sys_arch_sem_wait(&s_tcpip_call_lock_sem, 0); tcpip_send_msg_wait_sem(xxx_tcpip, &ctx, &s_tcpip_call_sync_sem); sys_sem_signal(&s_tcpip_call_lock_sem); } #endif #else #define mg_lwip_netif_run_on_tcpip(fn, arg) (fn)(arg) #endif void mg_lwip_if_init(struct mg_iface *iface); void mg_lwip_if_free(struct mg_iface *iface); void mg_lwip_if_add_conn(struct mg_connection *nc); void mg_lwip_if_remove_conn(struct mg_connection *nc); time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms); // If compiling for Mongoose OS. #ifdef MGOS extern void mgos_lock(); extern void mgos_unlock(); #else #define mgos_lock() #define mgos_unlock() #endif static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p); #if LWIP_TCP_KEEPALIVE void mg_lwip_set_keepalive_params(struct mg_connection *nc, int idle, int interval, int count) { if (nc->sock == INVALID_SOCKET || nc->flags & MG_F_UDP) { return; } struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; struct tcp_pcb *tpcb = cs->pcb.tcp; if (idle > 0 && interval > 0 && count > 0) { tpcb->keep_idle = idle * 1000; tpcb->keep_intvl = interval * 1000; tpcb->keep_cnt = count; tpcb->so_options |= SOF_KEEPALIVE; } else { tpcb->so_options &= ~SOF_KEEPALIVE; } } #elif !defined(MG_NO_LWIP_TCP_KEEPALIVE) #warning LWIP TCP keepalive is disabled. Please consider enabling it. #endif /* LWIP_TCP_KEEPALIVE */ static err_t mg_lwip_tcp_conn_cb(void *arg, struct tcp_pcb *tpcb, err_t err) { struct mg_connection *nc = (struct mg_connection *) arg; DBG(("%p connect to %s:%u = %d", nc, IPADDR_NTOA(ipX_2_ip(&tpcb->remote_ip)), tpcb->remote_port, err)); if (nc == NULL) { tcp_abort(tpcb); return ERR_ARG; } struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; cs->err = err; #if LWIP_TCP_KEEPALIVE if (err == 0) mg_lwip_set_keepalive_params(nc, 60, 10, 6); #endif mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc); return ERR_OK; } static void mg_lwip_tcp_error_cb(void *arg, err_t err) { struct mg_connection *nc = (struct mg_connection *) arg; DBG(("%p conn error %d", nc, err)); if (nc == NULL || (nc->flags & MG_F_CLOSE_IMMEDIATELY)) return; struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; cs->pcb.tcp = NULL; /* Has already been deallocated */ if (nc->flags & MG_F_CONNECTING) { cs->err = err; mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc); } else { mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc); } } static err_t mg_lwip_tcp_recv_cb(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err) { struct mg_connection *nc = (struct mg_connection *) arg; struct mg_lwip_conn_state *cs = (nc ? (struct mg_lwip_conn_state *) nc->sock : NULL); DBG(("%p %p %p %p %u %d", nc, cs, tpcb, p, (p != NULL ? p->tot_len : 0), err)); if (p == NULL) { if (nc != NULL && !(nc->flags & MG_F_CLOSE_IMMEDIATELY)) { if (cs->rx_chain != NULL) { /* * rx_chain still contains non-consumed data, don't close the * connection */ cs->draining_rx_chain = 1; } else { mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc); } } else { /* Tombstoned connection, do nothing. */ } return ERR_OK; } else if (nc == NULL) { tcp_abort(tpcb); return ERR_ARG; } /* * If we get a chain of more than one segment at once, we need to bump * refcount on the subsequent bufs to make them independent. */ if (p->next != NULL) { struct pbuf *q = p->next; for (; q != NULL; q = q->next) pbuf_ref(q); } mgos_lock(); if (cs->rx_chain == NULL) { cs->rx_offset = 0; } else if (pbuf_clen(cs->rx_chain) >= 4) { /* ESP SDK has a limited pool of 5 pbufs. We must not hog them all or RX * will be completely blocked. We already have at least 4 in the chain, * this one is the last, so we have to make a copy and release this one. */ struct pbuf *np = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM); if (np != NULL) { pbuf_copy(np, p); pbuf_free(p); p = np; } } mg_lwip_recv_common(nc, p); mgos_unlock(); (void) err; return ERR_OK; } static err_t mg_lwip_tcp_sent_cb(void *arg, struct tcp_pcb *tpcb, u16_t num_sent) { struct mg_connection *nc = (struct mg_connection *) arg; DBG(("%p %p %u %p %p", nc, tpcb, num_sent, tpcb->unsent, tpcb->unacked)); if (nc == NULL) return ERR_OK; if ((nc->flags & MG_F_SEND_AND_CLOSE) && !(nc->flags & MG_F_WANT_WRITE) && nc->send_mbuf.len == 0 && tpcb->unsent == NULL && tpcb->unacked == NULL) { mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc); } if (nc->send_mbuf.len > 0 || (nc->flags & MG_F_WANT_WRITE)) { mg_lwip_mgr_schedule_poll(nc->mgr); } (void) num_sent; return ERR_OK; } struct mg_lwip_if_connect_tcp_ctx { struct mg_connection *nc; const union socket_address *sa; }; static void mg_lwip_if_connect_tcp_tcpip(void *arg) { struct mg_lwip_if_connect_tcp_ctx *ctx = (struct mg_lwip_if_connect_tcp_ctx *) arg; struct mg_connection *nc = ctx->nc; const union socket_address *sa = ctx->sa; struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; struct tcp_pcb *tpcb = TCP_NEW(); cs->pcb.tcp = tpcb; ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr; u16_t port = ntohs(sa->sin.sin_port); tcp_arg(tpcb, nc); tcp_err(tpcb, mg_lwip_tcp_error_cb); tcp_sent(tpcb, mg_lwip_tcp_sent_cb); tcp_recv(tpcb, mg_lwip_tcp_recv_cb); cs->err = TCP_BIND(tpcb, IP_ADDR_ANY, 0 /* any port */); DBG(("%p tcp_bind = %d", nc, cs->err)); if (cs->err != ERR_OK) { mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc); return; } cs->err = tcp_connect(tpcb, ip, port, mg_lwip_tcp_conn_cb); DBG(("%p tcp_connect %p = %d", nc, tpcb, cs->err)); if (cs->err != ERR_OK) { mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc); return; } } void mg_lwip_if_connect_tcp(struct mg_connection *nc, const union socket_address *sa) { struct mg_lwip_if_connect_tcp_ctx ctx = {.nc = nc, .sa = sa}; mg_lwip_netif_run_on_tcpip(mg_lwip_if_connect_tcp_tcpip, &ctx); } /* * Lwip included in the SDKs for nRF5x chips has different type for the * callback of `udp_recv()` */ #if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105 static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, u16_t port) #else static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p, ip_addr_t *addr, u16_t port) #endif { struct mg_connection *nc = (struct mg_connection *) arg; DBG(("%p %s:%u %p %u %u", nc, IPADDR_NTOA(addr), port, p, p->ref, p->len)); /* Put address in a separate pbuf and tack it onto the packet. */ struct pbuf *sap = pbuf_alloc(PBUF_RAW, sizeof(union socket_address), PBUF_RAM); if (sap == NULL) { pbuf_free(p); return; } union socket_address *sa = (union socket_address *) sap->payload; #if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105 sa->sin.sin_addr.s_addr = ip_2_ip4(addr)->addr; #else sa->sin.sin_addr.s_addr = addr->addr; #endif sa->sin.sin_port = htons(port); /* Logic in the recv handler requires that there be exactly one data pbuf. */ p = pbuf_coalesce(p, PBUF_RAW); pbuf_chain(sap, p); mgos_lock(); mg_lwip_recv_common(nc, sap); mgos_unlock(); (void) pcb; } static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p) { struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; if (cs->rx_chain == NULL) { cs->rx_chain = p; } else { pbuf_chain(cs->rx_chain, p); } if (!cs->recv_pending) { cs->recv_pending = 1; mg_lwip_post_signal(MG_SIG_RECV, nc); } } static int mg_lwip_if_udp_recv(struct mg_connection *nc, void *buf, size_t len, union socket_address *sa, size_t *sa_len) { /* * For UDP, RX chain consists of interleaved address and packet bufs: * Address pbuf followed by exactly one data pbuf (recv_cb took care of that). */ int res = 0; struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; if (nc->sock == INVALID_SOCKET) return -1; mgos_lock(); if (cs->rx_chain != NULL) { struct pbuf *ap = cs->rx_chain; struct pbuf *dp = ap->next; cs->rx_chain = pbuf_dechain(dp); res = MIN(dp->len, len); pbuf_copy_partial(dp, buf, res, 0); pbuf_free(dp); pbuf_copy_partial(ap, sa, MIN(*sa_len, ap->len), 0); pbuf_free(ap); } mgos_unlock(); return res; } static void mg_lwip_if_connect_udp_tcpip(void *arg) { struct mg_connection *nc = (struct mg_connection *) arg; struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; struct udp_pcb *upcb = udp_new(); cs->err = UDP_BIND(upcb, IP_ADDR_ANY, 0 /* any port */); DBG(("%p udp_bind %p = %d", nc, upcb, cs->err)); if (cs->err == ERR_OK) { udp_recv(upcb, mg_lwip_udp_recv_cb, nc); cs->pcb.udp = upcb; } else { udp_remove(upcb); } mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc); } void mg_lwip_if_connect_udp(struct mg_connection *nc) { mg_lwip_netif_run_on_tcpip(mg_lwip_if_connect_udp_tcpip, nc); } static void tcp_close_tcpip(void *arg) { tcp_close((struct tcp_pcb *) arg); } void mg_lwip_handle_accept(struct mg_connection *nc) { struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; if (cs->pcb.tcp == NULL) return; union socket_address sa; struct tcp_pcb *tpcb = cs->pcb.tcp; SET_ADDR(&sa, &tpcb->remote_ip); sa.sin.sin_port = htons(tpcb->remote_port); mg_if_accept_tcp_cb(nc, &sa, sizeof(sa.sin)); } static err_t mg_lwip_accept_cb(void *arg, struct tcp_pcb *newtpcb, err_t err) { struct mg_connection *lc = (struct mg_connection *) arg, *nc; struct mg_lwip_conn_state *lcs, *cs; struct tcp_pcb_listen *lpcb; LOG(LL_DEBUG, ("%p conn %p from %s:%u", lc, newtpcb, IPADDR_NTOA(ipX_2_ip(&newtpcb->remote_ip)), newtpcb->remote_port)); if (lc == NULL) { tcp_abort(newtpcb); return ERR_ABRT; } lcs = (struct mg_lwip_conn_state *) lc->sock; lpcb = (struct tcp_pcb_listen *) lcs->pcb.tcp; #if TCP_LISTEN_BACKLOG tcp_accepted(lpcb); #endif nc = mg_if_accept_new_conn(lc); if (nc == NULL) { tcp_abort(newtpcb); return ERR_ABRT; } cs = (struct mg_lwip_conn_state *) nc->sock; cs->lc = lc; cs->pcb.tcp = newtpcb; /* We need to set up callbacks before returning because data may start * arriving immediately. */ tcp_arg(newtpcb, nc); tcp_err(newtpcb, mg_lwip_tcp_error_cb); tcp_sent(newtpcb, mg_lwip_tcp_sent_cb); tcp_recv(newtpcb, mg_lwip_tcp_recv_cb); #if LWIP_TCP_KEEPALIVE mg_lwip_set_keepalive_params(nc, 60, 10, 6); #endif mg_lwip_post_signal(MG_SIG_ACCEPT, nc); (void) err; (void) lpcb; return ERR_OK; } struct mg_lwip_if_listen_ctx { struct mg_connection *nc; union socket_address *sa; int ret; }; static void mg_lwip_if_listen_tcp_tcpip(void *arg) { struct mg_lwip_if_listen_ctx *ctx = (struct mg_lwip_if_listen_ctx *) arg; struct mg_connection *nc = ctx->nc; union socket_address *sa = ctx->sa; struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; struct tcp_pcb *tpcb = TCP_NEW(); ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr; u16_t port = ntohs(sa->sin.sin_port); cs->err = TCP_BIND(tpcb, ip, port); DBG(("%p tcp_bind(%s:%u) = %d", nc, IPADDR_NTOA(ip), port, cs->err)); if (cs->err != ERR_OK) { tcp_close(tpcb); ctx->ret = -1; return; } tcp_arg(tpcb, nc); tpcb = tcp_listen(tpcb); cs->pcb.tcp = tpcb; tcp_accept(tpcb, mg_lwip_accept_cb); ctx->ret = 0; } int mg_lwip_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) { struct mg_lwip_if_listen_ctx ctx = {.nc = nc, .sa = sa}; mg_lwip_netif_run_on_tcpip(mg_lwip_if_listen_tcp_tcpip, &ctx); return ctx.ret; } static void mg_lwip_if_listen_udp_tcpip(void *arg) { struct mg_lwip_if_listen_ctx *ctx = (struct mg_lwip_if_listen_ctx *) arg; struct mg_connection *nc = ctx->nc; union socket_address *sa = ctx->sa; struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; struct udp_pcb *upcb = udp_new(); ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr; u16_t port = ntohs(sa->sin.sin_port); cs->err = UDP_BIND(upcb, ip, port); DBG(("%p udb_bind(%s:%u) = %d", nc, IPADDR_NTOA(ip), port, cs->err)); if (cs->err != ERR_OK) { udp_remove(upcb); ctx->ret = -1; } else { udp_recv(upcb, mg_lwip_udp_recv_cb, nc); cs->pcb.udp = upcb; ctx->ret = 0; } } int mg_lwip_if_listen_udp(struct mg_connection *nc, union socket_address *sa) { struct mg_lwip_if_listen_ctx ctx = {.nc = nc, .sa = sa}; mg_lwip_netif_run_on_tcpip(mg_lwip_if_listen_udp_tcpip, &ctx); return ctx.ret; } struct mg_lwip_tcp_write_ctx { struct mg_connection *nc; const void *data; uint16_t len; int ret; }; static void tcp_output_tcpip(void *arg) { tcp_output((struct tcp_pcb *) arg); } static void mg_lwip_tcp_write_tcpip(void *arg) { struct mg_lwip_tcp_write_ctx *ctx = (struct mg_lwip_tcp_write_ctx *) arg; struct mg_connection *nc = ctx->nc; struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; struct tcp_pcb *tpcb = cs->pcb.tcp; size_t len = MIN(tpcb->mss, MIN(ctx->len, tpcb->snd_buf)); size_t unsent, unacked; if (len == 0) { DBG(("%p no buf avail %u %u %p %p", tpcb, tpcb->snd_buf, tpcb->snd_queuelen, tpcb->unsent, tpcb->unacked)); mg_lwip_netif_run_on_tcpip(tcp_output_tcpip, tpcb); ctx->ret = 0; return; } unsent = (tpcb->unsent != NULL ? tpcb->unsent->len : 0); unacked = (tpcb->unacked != NULL ? tpcb->unacked->len : 0); /* * On ESP8266 we only allow one TCP segment in flight at any given time. * This may increase latency and reduce efficiency of tcp windowing, * but memory is scarce and precious on that platform so we do this to * reduce footprint. */ #if CS_PLATFORM == CS_P_ESP8266 if (unacked > 0) { ctx->ret = 0; return; } len = MIN(len, (TCP_MSS - unsent)); #endif cs->err = tcp_write(tpcb, ctx->data, len, TCP_WRITE_FLAG_COPY); unsent = (tpcb->unsent != NULL ? tpcb->unsent->len : 0); unacked = (tpcb->unacked != NULL ? tpcb->unacked->len : 0); DBG(("%p tcp_write %u = %d, %u %u", tpcb, len, cs->err, unsent, unacked)); if (cs->err != ERR_OK) { /* * We ignore ERR_MEM because memory will be freed up when the data is sent * and we'll retry. */ ctx->ret = (cs->err == ERR_MEM ? 0 : -1); return; } ctx->ret = len; (void) unsent; (void) unacked; } int mg_lwip_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) { struct mg_lwip_tcp_write_ctx ctx = {.nc = nc, .data = buf, .len = len}; struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; if (nc->sock == INVALID_SOCKET) return -1; struct tcp_pcb *tpcb = cs->pcb.tcp; if (tpcb == NULL) return -1; if (tpcb->snd_buf <= 0) return 0; mg_lwip_netif_run_on_tcpip(mg_lwip_tcp_write_tcpip, &ctx); return ctx.ret; } struct udp_sendto_ctx { struct udp_pcb *upcb; struct pbuf *p; ip_addr_t *ip; uint16_t port; int ret; }; static void udp_sendto_tcpip(void *arg) { struct udp_sendto_ctx *ctx = (struct udp_sendto_ctx *) arg; ctx->ret = udp_sendto(ctx->upcb, ctx->p, ctx->ip, ctx->port); } static int mg_lwip_if_udp_send(struct mg_connection *nc, const void *data, size_t len) { struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; if (nc->sock == INVALID_SOCKET || cs->pcb.udp == NULL) return -1; struct udp_pcb *upcb = cs->pcb.udp; struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM); #if defined(LWIP_IPV4) && LWIP_IPV4 && defined(LWIP_IPV6) && LWIP_IPV6 ip_addr_t ip = {.u_addr.ip4.addr = nc->sa.sin.sin_addr.s_addr, .type = 0}; #else ip_addr_t ip = {.addr = nc->sa.sin.sin_addr.s_addr}; #endif u16_t port = ntohs(nc->sa.sin.sin_port); if (p == NULL) return 0; memcpy(p->payload, data, len); struct udp_sendto_ctx ctx = {.upcb = upcb, .p = p, .ip = &ip, .port = port}; mg_lwip_netif_run_on_tcpip(udp_sendto_tcpip, &ctx); cs->err = ctx.ret; pbuf_free(p); return (cs->err == ERR_OK ? (int) len : -2); } static int mg_lwip_if_can_send(struct mg_connection *nc, struct mg_lwip_conn_state *cs) { int can_send = 0; if (nc->send_mbuf.len > 0 || (nc->flags & MG_F_WANT_WRITE)) { /* We have stuff to send, but can we? */ if (nc->flags & MG_F_UDP) { /* UDP is always ready for sending. */ can_send = (cs->pcb.udp != NULL); } else { can_send = (cs->pcb.tcp != NULL && cs->pcb.tcp->snd_buf > 0); /* See comment above. */ #if CS_PLATFORM == CS_P_ESP8266 if (cs->pcb.tcp->unacked != NULL) can_send = 0; #endif } } return can_send; } struct tcp_recved_ctx { struct tcp_pcb *tpcb; size_t len; }; void tcp_recved_tcpip(void *arg) { struct tcp_recved_ctx *ctx = (struct tcp_recved_ctx *) arg; if (ctx->tpcb != NULL) tcp_recved(ctx->tpcb, ctx->len); } static int mg_lwip_if_tcp_recv(struct mg_connection *nc, void *buf, size_t len) { int res = 0; char *bufp = buf; struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; if (nc->sock == INVALID_SOCKET) return -1; mgos_lock(); while (cs->rx_chain != NULL && len > 0) { struct pbuf *seg = cs->rx_chain; size_t seg_len = (seg->len - cs->rx_offset); size_t copy_len = MIN(len, seg_len); pbuf_copy_partial(seg, bufp, copy_len, cs->rx_offset); len -= copy_len; res += copy_len; bufp += copy_len; cs->rx_offset += copy_len; if (cs->rx_offset == cs->rx_chain->len) { cs->rx_chain = pbuf_dechain(cs->rx_chain); pbuf_free(seg); cs->rx_offset = 0; } } mgos_unlock(); if (res > 0) { struct tcp_recved_ctx ctx = {.tpcb = cs->pcb.tcp, .len = res}; mg_lwip_netif_run_on_tcpip(tcp_recved_tcpip, &ctx); } return res; } int mg_lwip_if_create_conn(struct mg_connection *nc) { struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) MG_CALLOC(1, sizeof(*cs)); if (cs == NULL) return 0; cs->nc = nc; nc->sock = (intptr_t) cs; return 1; } static void udp_remove_tcpip(void *arg) { udp_remove((struct udp_pcb *) arg); } void mg_lwip_if_destroy_conn(struct mg_connection *nc) { if (nc->sock == INVALID_SOCKET) return; struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; if (!(nc->flags & MG_F_UDP)) { struct tcp_pcb *tpcb = cs->pcb.tcp; if (tpcb != NULL) { tcp_arg(tpcb, NULL); DBG(("%p tcp_close %p", nc, tpcb)); tcp_arg(tpcb, NULL); mg_lwip_netif_run_on_tcpip(tcp_close_tcpip, tpcb); } while (cs->rx_chain != NULL) { struct pbuf *seg = cs->rx_chain; cs->rx_chain = pbuf_dechain(cs->rx_chain); pbuf_free(seg); } memset(cs, 0, sizeof(*cs)); MG_FREE(cs); } else if (nc->listener == NULL) { /* Only close outgoing UDP pcb or listeners. */ struct udp_pcb *upcb = cs->pcb.udp; if (upcb != NULL) { DBG(("%p udp_remove %p", nc, upcb)); mg_lwip_netif_run_on_tcpip(udp_remove_tcpip, upcb); } memset(cs, 0, sizeof(*cs)); MG_FREE(cs); } nc->sock = INVALID_SOCKET; } void mg_lwip_if_get_conn_addr(struct mg_connection *nc, int remote, union socket_address *sa) { memset(sa, 0, sizeof(*sa)); if (nc == NULL || nc->sock == INVALID_SOCKET) return; struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; if (nc->flags & MG_F_UDP) { struct udp_pcb *upcb = cs->pcb.udp; if (remote) { memcpy(sa, &nc->sa, sizeof(*sa)); } else if (upcb != NULL) { sa->sin.sin_port = htons(upcb->local_port); SET_ADDR(sa, &upcb->local_ip); } } else { struct tcp_pcb *tpcb = cs->pcb.tcp; if (remote) { memcpy(sa, &nc->sa, sizeof(*sa)); } else if (tpcb != NULL) { sa->sin.sin_port = htons(tpcb->local_port); SET_ADDR(sa, &tpcb->local_ip); } } } void mg_lwip_if_sock_set(struct mg_connection *nc, sock_t sock) { nc->sock = sock; } /* clang-format off */ #define MG_LWIP_IFACE_VTABLE \ { \ mg_lwip_if_init, \ mg_lwip_if_free, \ mg_lwip_if_add_conn, \ mg_lwip_if_remove_conn, \ mg_lwip_if_poll, \ mg_lwip_if_listen_tcp, \ mg_lwip_if_listen_udp, \ mg_lwip_if_connect_tcp, \ mg_lwip_if_connect_udp, \ mg_lwip_if_tcp_send, \ mg_lwip_if_udp_send, \ mg_lwip_if_tcp_recv, \ mg_lwip_if_udp_recv, \ mg_lwip_if_create_conn, \ mg_lwip_if_destroy_conn, \ mg_lwip_if_sock_set, \ mg_lwip_if_get_conn_addr, \ } /* clang-format on */ const struct mg_iface_vtable mg_lwip_iface_vtable = MG_LWIP_IFACE_VTABLE; #if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL const struct mg_iface_vtable mg_default_iface_vtable = MG_LWIP_IFACE_VTABLE; #endif #endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/lwip/mg_lwip_ev_mgr.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL #ifndef MG_SIG_QUEUE_LEN #define MG_SIG_QUEUE_LEN 32 #endif struct mg_ev_mgr_lwip_signal { int sig; struct mg_connection *nc; }; struct mg_ev_mgr_lwip_data { struct mg_ev_mgr_lwip_signal sig_queue[MG_SIG_QUEUE_LEN]; int sig_queue_len; int start_index; }; void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc) { struct mg_ev_mgr_lwip_data *md = (struct mg_ev_mgr_lwip_data *) nc->iface->data; mgos_lock(); if (md->sig_queue_len >= MG_SIG_QUEUE_LEN) { mgos_unlock(); return; } int end_index = (md->start_index + md->sig_queue_len) % MG_SIG_QUEUE_LEN; md->sig_queue[end_index].sig = sig; md->sig_queue[end_index].nc = nc; md->sig_queue_len++; mg_lwip_mgr_schedule_poll(nc->mgr); mgos_unlock(); } void mg_ev_mgr_lwip_process_signals(struct mg_mgr *mgr) { struct mg_ev_mgr_lwip_data *md = (struct mg_ev_mgr_lwip_data *) mgr->ifaces[MG_MAIN_IFACE]->data; while (md->sig_queue_len > 0) { mgos_lock(); int i = md->start_index; int sig = md->sig_queue[i].sig; struct mg_connection *nc = md->sig_queue[i].nc; struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; md->start_index = (i + 1) % MG_SIG_QUEUE_LEN; md->sig_queue_len--; mgos_unlock(); if (nc->iface == NULL || nc->mgr == NULL) continue; switch (sig) { case MG_SIG_CONNECT_RESULT: { mg_if_connect_cb(nc, cs->err); break; } case MG_SIG_CLOSE_CONN: { mg_close_conn(nc); break; } case MG_SIG_RECV: { cs->recv_pending = 0; mg_if_can_recv_cb(nc); mbuf_trim(&nc->recv_mbuf); break; } case MG_SIG_TOMBSTONE: { break; } case MG_SIG_ACCEPT: { mg_lwip_handle_accept(nc); break; } } } } void mg_lwip_if_init(struct mg_iface *iface) { LOG(LL_INFO, ("Mongoose %s, LwIP %u.%u.%u", MG_VERSION, LWIP_VERSION_MAJOR, LWIP_VERSION_MINOR, LWIP_VERSION_REVISION)); iface->data = MG_CALLOC(1, sizeof(struct mg_ev_mgr_lwip_data)); #if !NO_SYS && !LWIP_TCPIP_CORE_LOCKING sys_sem_new(&s_tcpip_call_lock_sem, 1); sys_sem_new(&s_tcpip_call_sync_sem, 0); #endif } void mg_lwip_if_free(struct mg_iface *iface) { MG_FREE(iface->data); iface->data = NULL; } void mg_lwip_if_add_conn(struct mg_connection *nc) { (void) nc; } void mg_lwip_if_remove_conn(struct mg_connection *nc) { struct mg_ev_mgr_lwip_data *md = (struct mg_ev_mgr_lwip_data *) nc->iface->data; /* Walk the queue and null-out further signals for this conn. */ for (int i = 0; i < MG_SIG_QUEUE_LEN; i++) { if (md->sig_queue[i].nc == nc) { md->sig_queue[i].sig = MG_SIG_TOMBSTONE; } } } time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms) { struct mg_mgr *mgr = iface->mgr; int n = 0; double now = mg_time(); struct mg_connection *nc, *tmp; double min_timer = 0; int num_timers = 0; #if 0 DBG(("begin poll @%u", (unsigned int) (now * 1000))); #endif mg_ev_mgr_lwip_process_signals(mgr); for (nc = mgr->active_connections; nc != NULL; nc = tmp) { struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; tmp = nc->next; n++; if (!mg_if_poll(nc, now)) continue; if (nc->sock != INVALID_SOCKET && !(nc->flags & (MG_F_UDP | MG_F_LISTENING)) && cs->pcb.tcp != NULL && cs->pcb.tcp->unsent != NULL) { mg_lwip_netif_run_on_tcpip(tcp_output_tcpip, cs->pcb.tcp); } if (nc->ev_timer_time > 0) { if (num_timers == 0 || nc->ev_timer_time < min_timer) { min_timer = nc->ev_timer_time; } num_timers++; } if (nc->sock != INVALID_SOCKET) { if (mg_lwip_if_can_send(nc, cs)) { mg_if_can_send_cb(nc); mbuf_trim(&nc->send_mbuf); } if (cs->rx_chain != NULL) { mg_if_can_recv_cb(nc); } else if (cs->draining_rx_chain) { /* * If the connection is about to close, and rx_chain is finally empty, * send the MG_SIG_CLOSE_CONN signal */ mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc); } } } #if 0 DBG(("end poll @%u, %d conns, %d timers (min %u), next in %d ms", (unsigned int) (now * 1000), n, num_timers, (unsigned int) (min_timer * 1000), timeout_ms)); #endif (void) timeout_ms; return now; } #endif /* MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/wince/wince_libc.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef WINCE const char *strerror(int err) { /* * TODO(alashkin): there is no strerror on WinCE; * look for similar wce_xxxx function */ static char buf[10]; snprintf(buf, sizeof(buf), "%d", err); return buf; } int open(const char *filename, int oflag, int pmode) { /* * TODO(alashkin): mg_open function is not used in mongoose * but exists in documentation as utility function * Shall we delete it at all or implement for WinCE as well? */ DebugBreak(); return 0; /* for compiler */ } int _wstati64(const wchar_t *path, cs_stat_t *st) { DWORD fa = GetFileAttributesW(path); if (fa == INVALID_FILE_ATTRIBUTES) { return -1; } memset(st, 0, sizeof(*st)); if ((fa & FILE_ATTRIBUTE_DIRECTORY) == 0) { HANDLE h; FILETIME ftime; st->st_mode |= _S_IFREG; h = CreateFileW(path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (h == INVALID_HANDLE_VALUE) { return -1; } st->st_size = GetFileSize(h, NULL); GetFileTime(h, NULL, NULL, &ftime); st->st_mtime = (uint32_t)((((uint64_t) ftime.dwLowDateTime + ((uint64_t) ftime.dwHighDateTime << 32)) / 10000000.0) - 11644473600); CloseHandle(h); } else { st->st_mode |= _S_IFDIR; } return 0; } /* Windows CE doesn't have neither gmtime nor strftime */ static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) { FILETIME ft; SYSTEMTIME systime; if (t != NULL) { uint64_t filetime = (*t + 11644473600) * 10000000; ft.dwLowDateTime = filetime & 0xFFFFFFFF; ft.dwHighDateTime = (filetime & 0xFFFFFFFF00000000) >> 32; FileTimeToSystemTime(&ft, &systime); } else { GetSystemTime(&systime); } /* There is no PRIu16 in WinCE SDK */ snprintf(buf, buf_len, "%d.%d.%d %d:%d:%d GMT", (int) systime.wYear, (int) systime.wMonth, (int) systime.wDay, (int) systime.wHour, (int) systime.wMinute, (int) systime.wSecond); } #endif #ifdef MG_MODULE_LINES #line 1 "common/platforms/pic32/pic32_net_if.h" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CS_COMMON_PLATFORMS_PIC32_NET_IF_H_ #define CS_COMMON_PLATFORMS_PIC32_NET_IF_H_ /* Amalgamated: #include "mongoose/src/net_if.h" */ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #ifndef MG_ENABLE_NET_IF_PIC32 #define MG_ENABLE_NET_IF_PIC32 MG_NET_IF == MG_NET_IF_PIC32 #endif extern const struct mg_iface_vtable mg_pic32_iface_vtable; #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* CS_COMMON_PLATFORMS_PIC32_NET_IF_H_ */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/pic32/pic32_net_if.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if MG_ENABLE_NET_IF_PIC32 int mg_pic32_if_create_conn(struct mg_connection *nc) { (void) nc; return 1; } void mg_pic32_if_recved(struct mg_connection *nc, size_t len) { (void) nc; (void) len; } void mg_pic32_if_add_conn(struct mg_connection *nc) { (void) nc; } void mg_pic32_if_init(struct mg_iface *iface) { (void) iface; (void) mg_get_errno(); /* Shutup compiler */ } void mg_pic32_if_free(struct mg_iface *iface) { (void) iface; } void mg_pic32_if_remove_conn(struct mg_connection *nc) { (void) nc; } void mg_pic32_if_destroy_conn(struct mg_connection *nc) { if (nc->sock == INVALID_SOCKET) return; /* For UDP, only close outgoing sockets or listeners. */ if (!(nc->flags & MG_F_UDP)) { /* Close TCP */ TCPIP_TCP_Close((TCP_SOCKET) nc->sock); } else if (nc->listener == NULL) { /* Only close outgoing UDP or listeners. */ TCPIP_UDP_Close((UDP_SOCKET) nc->sock); } nc->sock = INVALID_SOCKET; } int mg_pic32_if_listen_udp(struct mg_connection *nc, union socket_address *sa) { nc->sock = TCPIP_UDP_ServerOpen( sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4 : IP_ADDRESS_TYPE_IPV6, ntohs(sa->sin.sin_port), sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin); if (nc->sock == INVALID_SOCKET) { return -1; } return 0; } void mg_pic32_if_udp_send(struct mg_connection *nc, const void *buf, size_t len) { mbuf_append(&nc->send_mbuf, buf, len); } void mg_pic32_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) { mbuf_append(&nc->send_mbuf, buf, len); } int mg_pic32_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) { nc->sock = TCPIP_TCP_ServerOpen( sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4 : IP_ADDRESS_TYPE_IPV6, ntohs(sa->sin.sin_port), sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin); memcpy(&nc->sa, sa, sizeof(*sa)); if (nc->sock == INVALID_SOCKET) { return -1; } return 0; } static int mg_accept_conn(struct mg_connection *lc) { struct mg_connection *nc; TCP_SOCKET_INFO si; union socket_address sa; nc = mg_if_accept_new_conn(lc); if (nc == NULL) { return 0; } nc->sock = lc->sock; nc->flags &= ~MG_F_LISTENING; if (!TCPIP_TCP_SocketInfoGet((TCP_SOCKET) nc->sock, &si)) { return 0; } if (si.addressType == IP_ADDRESS_TYPE_IPV4) { sa.sin.sin_family = AF_INET; sa.sin.sin_port = htons(si.remotePort); sa.sin.sin_addr.s_addr = si.remoteIPaddress.v4Add.Val; } else { /* TODO(alashkin): do something with _potential_ IPv6 */ memset(&sa, 0, sizeof(sa)); } mg_if_accept_tcp_cb(nc, (union socket_address *) &sa, sizeof(sa)); return mg_pic32_if_listen_tcp(lc, &lc->sa) >= 0; } char *inet_ntoa(struct in_addr in) { static char addr[17]; snprintf(addr, sizeof(addr), "%d.%d.%d.%d", (int) in.S_un.S_un_b.s_b1, (int) in.S_un.S_un_b.s_b2, (int) in.S_un.S_un_b.s_b3, (int) in.S_un.S_un_b.s_b4); return addr; } static void mg_handle_send(struct mg_connection *nc) { uint16_t bytes_written = 0; if (nc->flags & MG_F_UDP) { if (!TCPIP_UDP_RemoteBind( (UDP_SOCKET) nc->sock, nc->sa.sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4 : IP_ADDRESS_TYPE_IPV6, ntohs(nc->sa.sin.sin_port), (IP_MULTI_ADDRESS *) &nc->sa.sin)) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; return; } bytes_written = TCPIP_UDP_TxPutIsReady((UDP_SOCKET) nc->sock, 0); if (bytes_written >= nc->send_mbuf.len) { if (TCPIP_UDP_ArrayPut((UDP_SOCKET) nc->sock, (uint8_t *) nc->send_mbuf.buf, nc->send_mbuf.len) != nc->send_mbuf.len) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; bytes_written = 0; } } } else { bytes_written = TCPIP_TCP_FifoTxFreeGet((TCP_SOCKET) nc->sock); if (bytes_written != 0) { if (bytes_written > nc->send_mbuf.len) { bytes_written = nc->send_mbuf.len; } if (TCPIP_TCP_ArrayPut((TCP_SOCKET) nc->sock, (uint8_t *) nc->send_mbuf.buf, bytes_written) != bytes_written) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; bytes_written = 0; } } } mg_if_sent_cb(nc, bytes_written); } static void mg_handle_recv(struct mg_connection *nc) { uint16_t bytes_read = 0; uint8_t *buf = NULL; if (nc->flags & MG_F_UDP) { bytes_read = TCPIP_UDP_GetIsReady((UDP_SOCKET) nc->sock); if (bytes_read != 0 && (nc->recv_mbuf_limit == -1 || nc->recv_mbuf.len + bytes_read < nc->recv_mbuf_limit)) { buf = (uint8_t *) MG_MALLOC(bytes_read); if (TCPIP_UDP_ArrayGet((UDP_SOCKET) nc->sock, buf, bytes_read) != bytes_read) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; bytes_read = 0; MG_FREE(buf); } } } else { bytes_read = TCPIP_TCP_GetIsReady((TCP_SOCKET) nc->sock); if (bytes_read != 0) { if (nc->recv_mbuf_limit != -1 && nc->recv_mbuf_limit - nc->recv_mbuf.len > bytes_read) { bytes_read = nc->recv_mbuf_limit - nc->recv_mbuf.len; } buf = (uint8_t *) MG_MALLOC(bytes_read); if (TCPIP_TCP_ArrayGet((TCP_SOCKET) nc->sock, buf, bytes_read) != bytes_read) { nc->flags |= MG_F_CLOSE_IMMEDIATELY; MG_FREE(buf); bytes_read = 0; } } } if (bytes_read != 0) { mg_if_recv_tcp_cb(nc, buf, bytes_read, 1 /* own */); } } time_t mg_pic32_if_poll(struct mg_iface *iface, int timeout_ms) { struct mg_mgr *mgr = iface->mgr; double now = mg_time(); struct mg_connection *nc, *tmp; for (nc = mgr->active_connections; nc != NULL; nc = tmp) { tmp = nc->next; if (nc->flags & MG_F_CONNECTING) { /* processing connections */ if (nc->flags & MG_F_UDP || TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) { mg_if_connect_cb(nc, 0); } } else if (nc->flags & MG_F_LISTENING) { if (TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) { /* accept new connections */ mg_accept_conn(nc); } } else { if (nc->send_mbuf.len != 0) { mg_handle_send(nc); } if (nc->recv_mbuf_limit == -1 || nc->recv_mbuf.len < nc->recv_mbuf_limit) { mg_handle_recv(nc); } } } for (nc = mgr->active_connections; nc != NULL; nc = tmp) { tmp = nc->next; if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) || (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) { mg_close_conn(nc); } } return now; } void mg_pic32_if_sock_set(struct mg_connection *nc, sock_t sock) { nc->sock = sock; } void mg_pic32_if_get_conn_addr(struct mg_connection *nc, int remote, union socket_address *sa) { /* TODO(alaskin): not implemented yet */ } void mg_pic32_if_connect_tcp(struct mg_connection *nc, const union socket_address *sa) { nc->sock = TCPIP_TCP_ClientOpen( sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4 : IP_ADDRESS_TYPE_IPV6, ntohs(sa->sin.sin_port), (IP_MULTI_ADDRESS *) &sa->sin); nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0; } void mg_pic32_if_connect_udp(struct mg_connection *nc) { nc->sock = TCPIP_UDP_ClientOpen(IP_ADDRESS_TYPE_ANY, 0, NULL); nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0; } /* clang-format off */ #define MG_PIC32_IFACE_VTABLE \ { \ mg_pic32_if_init, \ mg_pic32_if_free, \ mg_pic32_if_add_conn, \ mg_pic32_if_remove_conn, \ mg_pic32_if_poll, \ mg_pic32_if_listen_tcp, \ mg_pic32_if_listen_udp, \ mg_pic32_if_connect_tcp, \ mg_pic32_if_connect_udp, \ mg_pic32_if_tcp_send, \ mg_pic32_if_udp_send, \ mg_pic32_if_recved, \ mg_pic32_if_create_conn, \ mg_pic32_if_destroy_conn, \ mg_pic32_if_sock_set, \ mg_pic32_if_get_conn_addr, \ } /* clang-format on */ const struct mg_iface_vtable mg_pic32_iface_vtable = MG_PIC32_IFACE_VTABLE; #if MG_NET_IF == MG_NET_IF_PIC32 const struct mg_iface_vtable mg_default_iface_vtable = MG_PIC32_IFACE_VTABLE; #endif #endif /* MG_ENABLE_NET_IF_PIC32 */ #ifdef MG_MODULE_LINES #line 1 "common/platforms/windows/windows_direct.c" #endif /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef _WIN32 int rmdir(const char *dirname) { return _rmdir(dirname); } unsigned int sleep(unsigned int seconds) { Sleep(seconds * 1000); return 0; } #endif /* _WIN32 */
null
121
CWE-787
CVE-2019-13217
// Ogg Vorbis audio decoder - v1.16 - public domain // http://nothings.org/stb_vorbis/ // // Original version written by Sean Barrett in 2007. // // Originally sponsored by RAD Game Tools. Seeking implementation // sponsored by Phillip Bennefall, Marc Andersen, Aaron Baker, // Elias Software, Aras Pranckevicius, and Sean Barrett. // // LICENSE // // See end of file for license information. // // Limitations: // // - floor 0 not supported (used in old ogg vorbis files pre-2004) // - lossless sample-truncation at beginning ignored // - cannot concatenate multiple vorbis streams // - sample positions are 32-bit, limiting seekable 192Khz // files to around 6 hours (Ogg supports 64-bit) // // Feature contributors: // Dougall Johnson (sample-exact seeking) // // Bugfix/warning contributors: // Terje Mathisen Niklas Frykholm Andy Hill // Casey Muratori John Bolton Gargaj // Laurent Gomila Marc LeBlanc Ronny Chevalier // Bernhard Wodo Evan Balster alxprd@github // Tom Beaumont Ingo Leitgeb Nicolas Guillemot // Phillip Bennefall Rohit Thiago Goulart // manxorist@github saga musix github:infatum // Timur Gagiev // // Partial history: // 1.16 - 2019-03-04 - fix warnings // 1.15 - 2019-02-07 - explicit failure if Ogg Skeleton data is found // 1.14 - 2018-02-11 - delete bogus dealloca usage // 1.13 - 2018-01-29 - fix truncation of last frame (hopefully) // 1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files // 1.11 - 2017-07-23 - fix MinGW compilation // 1.10 - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory // 1.09 - 2016-04-04 - back out 'truncation of last frame' fix from previous version // 1.08 - 2016-04-02 - warnings; setup memory leaks; truncation of last frame // 1.07 - 2015-01-16 - fixes for crashes on invalid files; warning fixes; const // 1.06 - 2015-08-31 - full, correct support for seeking API (Dougall Johnson) // some crash fixes when out of memory or with corrupt files // fix some inappropriately signed shifts // 1.05 - 2015-04-19 - don't define __forceinline if it's redundant // 1.04 - 2014-08-27 - fix missing const-correct case in API // 1.03 - 2014-08-07 - warning fixes // 1.02 - 2014-07-09 - declare qsort comparison as explicitly _cdecl in Windows // 1.01 - 2014-06-18 - fix stb_vorbis_get_samples_float (interleaved was correct) // 1.0 - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in >2-channel; // (API change) report sample rate for decode-full-file funcs // // See end of file for full version history. ////////////////////////////////////////////////////////////////////////////// // // HEADER BEGINS HERE // #ifndef STB_VORBIS_INCLUDE_STB_VORBIS_H #define STB_VORBIS_INCLUDE_STB_VORBIS_H #if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO) #define STB_VORBIS_NO_STDIO 1 #endif #ifndef STB_VORBIS_NO_STDIO #include <stdio.h> #endif #ifdef __cplusplus extern "C" { #endif /////////// THREAD SAFETY // Individual stb_vorbis* handles are not thread-safe; you cannot decode from // them from multiple threads at the same time. However, you can have multiple // stb_vorbis* handles and decode from them independently in multiple thrads. /////////// MEMORY ALLOCATION // normally stb_vorbis uses malloc() to allocate memory at startup, // and alloca() to allocate temporary memory during a frame on the // stack. (Memory consumption will depend on the amount of setup // data in the file and how you set the compile flags for speed // vs. size. In my test files the maximal-size usage is ~150KB.) // // You can modify the wrapper functions in the source (setup_malloc, // setup_temp_malloc, temp_malloc) to change this behavior, or you // can use a simpler allocation model: you pass in a buffer from // which stb_vorbis will allocate _all_ its memory (including the // temp memory). "open" may fail with a VORBIS_outofmem if you // do not pass in enough data; there is no way to determine how // much you do need except to succeed (at which point you can // query get_info to find the exact amount required. yes I know // this is lame). // // If you pass in a non-NULL buffer of the type below, allocation // will occur from it as described above. Otherwise just pass NULL // to use malloc()/alloca() typedef struct { char *alloc_buffer; int alloc_buffer_length_in_bytes; } stb_vorbis_alloc; /////////// FUNCTIONS USEABLE WITH ALL INPUT MODES typedef struct stb_vorbis stb_vorbis; typedef struct { unsigned int sample_rate; int channels; unsigned int setup_memory_required; unsigned int setup_temp_memory_required; unsigned int temp_memory_required; int max_frame_size; } stb_vorbis_info; // get general information about the file extern stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f); // get the last error detected (clears it, too) extern int stb_vorbis_get_error(stb_vorbis *f); // close an ogg vorbis file and free all memory in use extern void stb_vorbis_close(stb_vorbis *f); // this function returns the offset (in samples) from the beginning of the // file that will be returned by the next decode, if it is known, or -1 // otherwise. after a flush_pushdata() call, this may take a while before // it becomes valid again. // NOT WORKING YET after a seek with PULLDATA API extern int stb_vorbis_get_sample_offset(stb_vorbis *f); // returns the current seek point within the file, or offset from the beginning // of the memory buffer. In pushdata mode it returns 0. extern unsigned int stb_vorbis_get_file_offset(stb_vorbis *f); /////////// PUSHDATA API #ifndef STB_VORBIS_NO_PUSHDATA_API // this API allows you to get blocks of data from any source and hand // them to stb_vorbis. you have to buffer them; stb_vorbis will tell // you how much it used, and you have to give it the rest next time; // and stb_vorbis may not have enough data to work with and you will // need to give it the same data again PLUS more. Note that the Vorbis // specification does not bound the size of an individual frame. extern stb_vorbis *stb_vorbis_open_pushdata( const unsigned char * datablock, int datablock_length_in_bytes, int *datablock_memory_consumed_in_bytes, int *error, const stb_vorbis_alloc *alloc_buffer); // create a vorbis decoder by passing in the initial data block containing // the ogg&vorbis headers (you don't need to do parse them, just provide // the first N bytes of the file--you're told if it's not enough, see below) // on success, returns an stb_vorbis *, does not set error, returns the amount of // data parsed/consumed on this call in *datablock_memory_consumed_in_bytes; // on failure, returns NULL on error and sets *error, does not change *datablock_memory_consumed // if returns NULL and *error is VORBIS_need_more_data, then the input block was // incomplete and you need to pass in a larger block from the start of the file extern int stb_vorbis_decode_frame_pushdata( stb_vorbis *f, const unsigned char *datablock, int datablock_length_in_bytes, int *channels, // place to write number of float * buffers float ***output, // place to write float ** array of float * buffers int *samples // place to write number of output samples ); // decode a frame of audio sample data if possible from the passed-in data block // // return value: number of bytes we used from datablock // // possible cases: // 0 bytes used, 0 samples output (need more data) // N bytes used, 0 samples output (resynching the stream, keep going) // N bytes used, M samples output (one frame of data) // note that after opening a file, you will ALWAYS get one N-bytes,0-sample // frame, because Vorbis always "discards" the first frame. // // Note that on resynch, stb_vorbis will rarely consume all of the buffer, // instead only datablock_length_in_bytes-3 or less. This is because it wants // to avoid missing parts of a page header if they cross a datablock boundary, // without writing state-machiney code to record a partial detection. // // The number of channels returned are stored in *channels (which can be // NULL--it is always the same as the number of channels reported by // get_info). *output will contain an array of float* buffers, one per // channel. In other words, (*output)[0][0] contains the first sample from // the first channel, and (*output)[1][0] contains the first sample from // the second channel. extern void stb_vorbis_flush_pushdata(stb_vorbis *f); // inform stb_vorbis that your next datablock will not be contiguous with // previous ones (e.g. you've seeked in the data); future attempts to decode // frames will cause stb_vorbis to resynchronize (as noted above), and // once it sees a valid Ogg page (typically 4-8KB, as large as 64KB), it // will begin decoding the _next_ frame. // // if you want to seek using pushdata, you need to seek in your file, then // call stb_vorbis_flush_pushdata(), then start calling decoding, then once // decoding is returning you data, call stb_vorbis_get_sample_offset, and // if you don't like the result, seek your file again and repeat. #endif ////////// PULLING INPUT API #ifndef STB_VORBIS_NO_PULLDATA_API // This API assumes stb_vorbis is allowed to pull data from a source-- // either a block of memory containing the _entire_ vorbis stream, or a // FILE * that you or it create, or possibly some other reading mechanism // if you go modify the source to replace the FILE * case with some kind // of callback to your code. (But if you don't support seeking, you may // just want to go ahead and use pushdata.) #if !defined(STB_VORBIS_NO_STDIO) && !defined(STB_VORBIS_NO_INTEGER_CONVERSION) extern int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output); #endif #if !defined(STB_VORBIS_NO_INTEGER_CONVERSION) extern int stb_vorbis_decode_memory(const unsigned char *mem, int len, int *channels, int *sample_rate, short **output); #endif // decode an entire file and output the data interleaved into a malloc()ed // buffer stored in *output. The return value is the number of samples // decoded, or -1 if the file could not be opened or was not an ogg vorbis file. // When you're done with it, just free() the pointer returned in *output. extern stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, int *error, const stb_vorbis_alloc *alloc_buffer); // create an ogg vorbis decoder from an ogg vorbis stream in memory (note // this must be the entire stream!). on failure, returns NULL and sets *error #ifndef STB_VORBIS_NO_STDIO extern stb_vorbis * stb_vorbis_open_filename(const char *filename, int *error, const stb_vorbis_alloc *alloc_buffer); // create an ogg vorbis decoder from a filename via fopen(). on failure, // returns NULL and sets *error (possibly to VORBIS_file_open_failure). extern stb_vorbis * stb_vorbis_open_file(FILE *f, int close_handle_on_close, int *error, const stb_vorbis_alloc *alloc_buffer); // create an ogg vorbis decoder from an open FILE *, looking for a stream at // the _current_ seek point (ftell). on failure, returns NULL and sets *error. // note that stb_vorbis must "own" this stream; if you seek it in between // calls to stb_vorbis, it will become confused. Moreover, if you attempt to // perform stb_vorbis_seek_*() operations on this file, it will assume it // owns the _entire_ rest of the file after the start point. Use the next // function, stb_vorbis_open_file_section(), to limit it. extern stb_vorbis * stb_vorbis_open_file_section(FILE *f, int close_handle_on_close, int *error, const stb_vorbis_alloc *alloc_buffer, unsigned int len); // create an ogg vorbis decoder from an open FILE *, looking for a stream at // the _current_ seek point (ftell); the stream will be of length 'len' bytes. // on failure, returns NULL and sets *error. note that stb_vorbis must "own" // this stream; if you seek it in between calls to stb_vorbis, it will become // confused. #endif extern int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number); extern int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number); // these functions seek in the Vorbis file to (approximately) 'sample_number'. // after calling seek_frame(), the next call to get_frame_*() will include // the specified sample. after calling stb_vorbis_seek(), the next call to // stb_vorbis_get_samples_* will start with the specified sample. If you // do not need to seek to EXACTLY the target sample when using get_samples_*, // you can also use seek_frame(). extern int stb_vorbis_seek_start(stb_vorbis *f); // this function is equivalent to stb_vorbis_seek(f,0) extern unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f); extern float stb_vorbis_stream_length_in_seconds(stb_vorbis *f); // these functions return the total length of the vorbis stream extern int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output); // decode the next frame and return the number of samples. the number of // channels returned are stored in *channels (which can be NULL--it is always // the same as the number of channels reported by get_info). *output will // contain an array of float* buffers, one per channel. These outputs will // be overwritten on the next call to stb_vorbis_get_frame_*. // // You generally should not intermix calls to stb_vorbis_get_frame_*() // and stb_vorbis_get_samples_*(), since the latter calls the former. #ifndef STB_VORBIS_NO_INTEGER_CONVERSION extern int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts); extern int stb_vorbis_get_frame_short (stb_vorbis *f, int num_c, short **buffer, int num_samples); #endif // decode the next frame and return the number of *samples* per channel. // Note that for interleaved data, you pass in the number of shorts (the // size of your array), but the return value is the number of samples per // channel, not the total number of samples. // // The data is coerced to the number of channels you request according to the // channel coercion rules (see below). You must pass in the size of your // buffer(s) so that stb_vorbis will not overwrite the end of the buffer. // The maximum buffer size needed can be gotten from get_info(); however, // the Vorbis I specification implies an absolute maximum of 4096 samples // per channel. // Channel coercion rules: // Let M be the number of channels requested, and N the number of channels present, // and Cn be the nth channel; let stereo L be the sum of all L and center channels, // and stereo R be the sum of all R and center channels (channel assignment from the // vorbis spec). // M N output // 1 k sum(Ck) for all k // 2 * stereo L, stereo R // k l k > l, the first l channels, then 0s // k l k <= l, the first k channels // Note that this is not _good_ surround etc. mixing at all! It's just so // you get something useful. extern int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats); extern int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples); // gets num_samples samples, not necessarily on a frame boundary--this requires // buffering so you have to supply the buffers. DOES NOT APPLY THE COERCION RULES. // Returns the number of samples stored per channel; it may be less than requested // at the end of the file. If there are no more samples in the file, returns 0. #ifndef STB_VORBIS_NO_INTEGER_CONVERSION extern int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts); extern int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int num_samples); #endif // gets num_samples samples, not necessarily on a frame boundary--this requires // buffering so you have to supply the buffers. Applies the coercion rules above // to produce 'channels' channels. Returns the number of samples stored per channel; // it may be less than requested at the end of the file. If there are no more // samples in the file, returns 0. #endif //////// ERROR CODES enum STBVorbisError { VORBIS__no_error, VORBIS_need_more_data=1, // not a real error VORBIS_invalid_api_mixing, // can't mix API modes VORBIS_outofmem, // not enough memory VORBIS_feature_not_supported, // uses floor 0 VORBIS_too_many_channels, // STB_VORBIS_MAX_CHANNELS is too small VORBIS_file_open_failure, // fopen() failed VORBIS_seek_without_length, // can't seek in unknown-length file VORBIS_unexpected_eof=10, // file is truncated? VORBIS_seek_invalid, // seek past EOF // decoding errors (corrupt/invalid stream) -- you probably // don't care about the exact details of these // vorbis errors: VORBIS_invalid_setup=20, VORBIS_invalid_stream, // ogg errors: VORBIS_missing_capture_pattern=30, VORBIS_invalid_stream_structure_version, VORBIS_continued_packet_flag_invalid, VORBIS_incorrect_stream_serial_number, VORBIS_invalid_first_page, VORBIS_bad_packet_type, VORBIS_cant_find_last_page, VORBIS_seek_failed, VORBIS_ogg_skeleton_not_supported }; #ifdef __cplusplus } #endif #endif // STB_VORBIS_INCLUDE_STB_VORBIS_H // // HEADER ENDS HERE // ////////////////////////////////////////////////////////////////////////////// #ifndef STB_VORBIS_HEADER_ONLY // global configuration settings (e.g. set these in the project/makefile), // or just set them in this file at the top (although ideally the first few // should be visible when the header file is compiled too, although it's not // crucial) // STB_VORBIS_NO_PUSHDATA_API // does not compile the code for the various stb_vorbis_*_pushdata() // functions // #define STB_VORBIS_NO_PUSHDATA_API // STB_VORBIS_NO_PULLDATA_API // does not compile the code for the non-pushdata APIs // #define STB_VORBIS_NO_PULLDATA_API // STB_VORBIS_NO_STDIO // does not compile the code for the APIs that use FILE *s internally // or externally (implied by STB_VORBIS_NO_PULLDATA_API) // #define STB_VORBIS_NO_STDIO // STB_VORBIS_NO_INTEGER_CONVERSION // does not compile the code for converting audio sample data from // float to integer (implied by STB_VORBIS_NO_PULLDATA_API) // #define STB_VORBIS_NO_INTEGER_CONVERSION // STB_VORBIS_NO_FAST_SCALED_FLOAT // does not use a fast float-to-int trick to accelerate float-to-int on // most platforms which requires endianness be defined correctly. //#define STB_VORBIS_NO_FAST_SCALED_FLOAT // STB_VORBIS_MAX_CHANNELS [number] // globally define this to the maximum number of channels you need. // The spec does not put a restriction on channels except that // the count is stored in a byte, so 255 is the hard limit. // Reducing this saves about 16 bytes per value, so using 16 saves // (255-16)*16 or around 4KB. Plus anything other memory usage // I forgot to account for. Can probably go as low as 8 (7.1 audio), // 6 (5.1 audio), or 2 (stereo only). #ifndef STB_VORBIS_MAX_CHANNELS #define STB_VORBIS_MAX_CHANNELS 16 // enough for anyone? #endif // STB_VORBIS_PUSHDATA_CRC_COUNT [number] // after a flush_pushdata(), stb_vorbis begins scanning for the // next valid page, without backtracking. when it finds something // that looks like a page, it streams through it and verifies its // CRC32. Should that validation fail, it keeps scanning. But it's // possible that _while_ streaming through to check the CRC32 of // one candidate page, it sees another candidate page. This #define // determines how many "overlapping" candidate pages it can search // at once. Note that "real" pages are typically ~4KB to ~8KB, whereas // garbage pages could be as big as 64KB, but probably average ~16KB. // So don't hose ourselves by scanning an apparent 64KB page and // missing a ton of real ones in the interim; so minimum of 2 #ifndef STB_VORBIS_PUSHDATA_CRC_COUNT #define STB_VORBIS_PUSHDATA_CRC_COUNT 4 #endif // STB_VORBIS_FAST_HUFFMAN_LENGTH [number] // sets the log size of the huffman-acceleration table. Maximum // supported value is 24. with larger numbers, more decodings are O(1), // but the table size is larger so worse cache missing, so you'll have // to probe (and try multiple ogg vorbis files) to find the sweet spot. #ifndef STB_VORBIS_FAST_HUFFMAN_LENGTH #define STB_VORBIS_FAST_HUFFMAN_LENGTH 10 #endif // STB_VORBIS_FAST_BINARY_LENGTH [number] // sets the log size of the binary-search acceleration table. this // is used in similar fashion to the fast-huffman size to set initial // parameters for the binary search // STB_VORBIS_FAST_HUFFMAN_INT // The fast huffman tables are much more efficient if they can be // stored as 16-bit results instead of 32-bit results. This restricts // the codebooks to having only 65535 possible outcomes, though. // (At least, accelerated by the huffman table.) #ifndef STB_VORBIS_FAST_HUFFMAN_INT #define STB_VORBIS_FAST_HUFFMAN_SHORT #endif // STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH // If the 'fast huffman' search doesn't succeed, then stb_vorbis falls // back on binary searching for the correct one. This requires storing // extra tables with the huffman codes in sorted order. Defining this // symbol trades off space for speed by forcing a linear search in the // non-fast case, except for "sparse" codebooks. // #define STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH // STB_VORBIS_DIVIDES_IN_RESIDUE // stb_vorbis precomputes the result of the scalar residue decoding // that would otherwise require a divide per chunk. you can trade off // space for time by defining this symbol. // #define STB_VORBIS_DIVIDES_IN_RESIDUE // STB_VORBIS_DIVIDES_IN_CODEBOOK // vorbis VQ codebooks can be encoded two ways: with every case explicitly // stored, or with all elements being chosen from a small range of values, // and all values possible in all elements. By default, stb_vorbis expands // this latter kind out to look like the former kind for ease of decoding, // because otherwise an integer divide-per-vector-element is required to // unpack the index. If you define STB_VORBIS_DIVIDES_IN_CODEBOOK, you can // trade off storage for speed. //#define STB_VORBIS_DIVIDES_IN_CODEBOOK #ifdef STB_VORBIS_CODEBOOK_SHORTS #error "STB_VORBIS_CODEBOOK_SHORTS is no longer supported as it produced incorrect results for some input formats" #endif // STB_VORBIS_DIVIDE_TABLE // this replaces small integer divides in the floor decode loop with // table lookups. made less than 1% difference, so disabled by default. // STB_VORBIS_NO_INLINE_DECODE // disables the inlining of the scalar codebook fast-huffman decode. // might save a little codespace; useful for debugging // #define STB_VORBIS_NO_INLINE_DECODE // STB_VORBIS_NO_DEFER_FLOOR // Normally we only decode the floor without synthesizing the actual // full curve. We can instead synthesize the curve immediately. This // requires more memory and is very likely slower, so I don't think // you'd ever want to do it except for debugging. // #define STB_VORBIS_NO_DEFER_FLOOR ////////////////////////////////////////////////////////////////////////////// #ifdef STB_VORBIS_NO_PULLDATA_API #define STB_VORBIS_NO_INTEGER_CONVERSION #define STB_VORBIS_NO_STDIO #endif #if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO) #define STB_VORBIS_NO_STDIO 1 #endif #ifndef STB_VORBIS_NO_INTEGER_CONVERSION #ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT // only need endianness for fast-float-to-int, which we don't // use for pushdata #ifndef STB_VORBIS_BIG_ENDIAN #define STB_VORBIS_ENDIAN 0 #else #define STB_VORBIS_ENDIAN 1 #endif #endif #endif #ifndef STB_VORBIS_NO_STDIO #include <stdio.h> #endif #ifndef STB_VORBIS_NO_CRT #include <stdlib.h> #include <string.h> #include <assert.h> #include <math.h> // find definition of alloca if it's not in stdlib.h: #if defined(_MSC_VER) || defined(__MINGW32__) #include <malloc.h> #endif #if defined(__linux__) || defined(__linux) || defined(__EMSCRIPTEN__) #include <alloca.h> #endif #else // STB_VORBIS_NO_CRT #define NULL 0 #define malloc(s) 0 #define free(s) ((void) 0) #define realloc(s) 0 #endif // STB_VORBIS_NO_CRT #include <limits.h> #ifdef __MINGW32__ // eff you mingw: // "fixed": // http://sourceforge.net/p/mingw-w64/mailman/message/32882927/ // "no that broke the build, reverted, who cares about C": // http://sourceforge.net/p/mingw-w64/mailman/message/32890381/ #ifdef __forceinline #undef __forceinline #endif #define __forceinline #define alloca __builtin_alloca #elif !defined(_MSC_VER) #if __GNUC__ #define __forceinline inline #else #define __forceinline #endif #endif #if STB_VORBIS_MAX_CHANNELS > 256 #error "Value of STB_VORBIS_MAX_CHANNELS outside of allowed range" #endif #if STB_VORBIS_FAST_HUFFMAN_LENGTH > 24 #error "Value of STB_VORBIS_FAST_HUFFMAN_LENGTH outside of allowed range" #endif #if 0 #include <crtdbg.h> #define CHECK(f) _CrtIsValidHeapPointer(f->channel_buffers[1]) #else #define CHECK(f) ((void) 0) #endif #define MAX_BLOCKSIZE_LOG 13 // from specification #define MAX_BLOCKSIZE (1 << MAX_BLOCKSIZE_LOG) typedef unsigned char uint8; typedef signed char int8; typedef unsigned short uint16; typedef signed short int16; typedef unsigned int uint32; typedef signed int int32; #ifndef TRUE #define TRUE 1 #define FALSE 0 #endif typedef float codetype; // @NOTE // // Some arrays below are tagged "//varies", which means it's actually // a variable-sized piece of data, but rather than malloc I assume it's // small enough it's better to just allocate it all together with the // main thing // // Most of the variables are specified with the smallest size I could pack // them into. It might give better performance to make them all full-sized // integers. It should be safe to freely rearrange the structures or change // the sizes larger--nothing relies on silently truncating etc., nor the // order of variables. #define FAST_HUFFMAN_TABLE_SIZE (1 << STB_VORBIS_FAST_HUFFMAN_LENGTH) #define FAST_HUFFMAN_TABLE_MASK (FAST_HUFFMAN_TABLE_SIZE - 1) typedef struct { int dimensions, entries; uint8 *codeword_lengths; float minimum_value; float delta_value; uint8 value_bits; uint8 lookup_type; uint8 sequence_p; uint8 sparse; uint32 lookup_values; codetype *multiplicands; uint32 *codewords; #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT int16 fast_huffman[FAST_HUFFMAN_TABLE_SIZE]; #else int32 fast_huffman[FAST_HUFFMAN_TABLE_SIZE]; #endif uint32 *sorted_codewords; int *sorted_values; int sorted_entries; } Codebook; typedef struct { uint8 order; uint16 rate; uint16 bark_map_size; uint8 amplitude_bits; uint8 amplitude_offset; uint8 number_of_books; uint8 book_list[16]; // varies } Floor0; typedef struct { uint8 partitions; uint8 partition_class_list[32]; // varies uint8 class_dimensions[16]; // varies uint8 class_subclasses[16]; // varies uint8 class_masterbooks[16]; // varies int16 subclass_books[16][8]; // varies uint16 Xlist[31*8+2]; // varies uint8 sorted_order[31*8+2]; uint8 neighbors[31*8+2][2]; uint8 floor1_multiplier; uint8 rangebits; int values; } Floor1; typedef union { Floor0 floor0; Floor1 floor1; } Floor; typedef struct { uint32 begin, end; uint32 part_size; uint8 classifications; uint8 classbook; uint8 **classdata; int16 (*residue_books)[8]; } Residue; typedef struct { uint8 magnitude; uint8 angle; uint8 mux; } MappingChannel; typedef struct { uint16 coupling_steps; MappingChannel *chan; uint8 submaps; uint8 submap_floor[15]; // varies uint8 submap_residue[15]; // varies } Mapping; typedef struct { uint8 blockflag; uint8 mapping; uint16 windowtype; uint16 transformtype; } Mode; typedef struct { uint32 goal_crc; // expected crc if match int bytes_left; // bytes left in packet uint32 crc_so_far; // running crc int bytes_done; // bytes processed in _current_ chunk uint32 sample_loc; // granule pos encoded in page } CRCscan; typedef struct { uint32 page_start, page_end; uint32 last_decoded_sample; } ProbedPage; struct stb_vorbis { // user-accessible info unsigned int sample_rate; int channels; unsigned int setup_memory_required; unsigned int temp_memory_required; unsigned int setup_temp_memory_required; // input config #ifndef STB_VORBIS_NO_STDIO FILE *f; uint32 f_start; int close_on_free; #endif uint8 *stream; uint8 *stream_start; uint8 *stream_end; uint32 stream_len; uint8 push_mode; uint32 first_audio_page_offset; ProbedPage p_first, p_last; // memory management stb_vorbis_alloc alloc; int setup_offset; int temp_offset; // run-time results int eof; enum STBVorbisError error; // user-useful data // header info int blocksize[2]; int blocksize_0, blocksize_1; int codebook_count; Codebook *codebooks; int floor_count; uint16 floor_types[64]; // varies Floor *floor_config; int residue_count; uint16 residue_types[64]; // varies Residue *residue_config; int mapping_count; Mapping *mapping; int mode_count; Mode mode_config[64]; // varies uint32 total_samples; // decode buffer float *channel_buffers[STB_VORBIS_MAX_CHANNELS]; float *outputs [STB_VORBIS_MAX_CHANNELS]; float *previous_window[STB_VORBIS_MAX_CHANNELS]; int previous_length; #ifndef STB_VORBIS_NO_DEFER_FLOOR int16 *finalY[STB_VORBIS_MAX_CHANNELS]; #else float *floor_buffers[STB_VORBIS_MAX_CHANNELS]; #endif uint32 current_loc; // sample location of next frame to decode int current_loc_valid; // per-blocksize precomputed data // twiddle factors float *A[2],*B[2],*C[2]; float *window[2]; uint16 *bit_reverse[2]; // current page/packet/segment streaming info uint32 serial; // stream serial number for verification int last_page; int segment_count; uint8 segments[255]; uint8 page_flag; uint8 bytes_in_seg; uint8 first_decode; int next_seg; int last_seg; // flag that we're on the last segment int last_seg_which; // what was the segment number of the last seg? uint32 acc; int valid_bits; int packet_bytes; int end_seg_with_known_loc; uint32 known_loc_for_packet; int discard_samples_deferred; uint32 samples_output; // push mode scanning int page_crc_tests; // only in push_mode: number of tests active; -1 if not searching #ifndef STB_VORBIS_NO_PUSHDATA_API CRCscan scan[STB_VORBIS_PUSHDATA_CRC_COUNT]; #endif // sample-access int channel_buffer_start; int channel_buffer_end; }; #if defined(STB_VORBIS_NO_PUSHDATA_API) #define IS_PUSH_MODE(f) FALSE #elif defined(STB_VORBIS_NO_PULLDATA_API) #define IS_PUSH_MODE(f) TRUE #else #define IS_PUSH_MODE(f) ((f)->push_mode) #endif typedef struct stb_vorbis vorb; static int error(vorb *f, enum STBVorbisError e) { f->error = e; if (!f->eof && e != VORBIS_need_more_data) { f->error=e; // breakpoint for debugging } return 0; } // these functions are used for allocating temporary memory // while decoding. if you can afford the stack space, use // alloca(); otherwise, provide a temp buffer and it will // allocate out of those. #define array_size_required(count,size) (count*(sizeof(void *)+(size))) #define temp_alloc(f,size) (f->alloc.alloc_buffer ? setup_temp_malloc(f,size) : alloca(size)) #define temp_free(f,p) 0 #define temp_alloc_save(f) ((f)->temp_offset) #define temp_alloc_restore(f,p) ((f)->temp_offset = (p)) #define temp_block_array(f,count,size) make_block_array(temp_alloc(f,array_size_required(count,size)), count, size) // given a sufficiently large block of memory, make an array of pointers to subblocks of it static void *make_block_array(void *mem, int count, int size) { int i; void ** p = (void **) mem; char *q = (char *) (p + count); for (i=0; i < count; ++i) { p[i] = q; q += size; } return p; } static void *setup_malloc(vorb *f, int sz) { sz = (sz+3) & ~3; f->setup_memory_required += sz; if (f->alloc.alloc_buffer) { void *p = (char *) f->alloc.alloc_buffer + f->setup_offset; if (f->setup_offset + sz > f->temp_offset) return NULL; f->setup_offset += sz; return p; } return sz ? malloc(sz) : NULL; } static void setup_free(vorb *f, void *p) { if (f->alloc.alloc_buffer) return; // do nothing; setup mem is a stack free(p); } static void *setup_temp_malloc(vorb *f, int sz) { sz = (sz+3) & ~3; if (f->alloc.alloc_buffer) { if (f->temp_offset - sz < f->setup_offset) return NULL; f->temp_offset -= sz; return (char *) f->alloc.alloc_buffer + f->temp_offset; } return malloc(sz); } static void setup_temp_free(vorb *f, void *p, int sz) { if (f->alloc.alloc_buffer) { f->temp_offset += (sz+3)&~3; return; } free(p); } #define CRC32_POLY 0x04c11db7 // from spec static uint32 crc_table[256]; static void crc32_init(void) { int i,j; uint32 s; for(i=0; i < 256; i++) { for (s=(uint32) i << 24, j=0; j < 8; ++j) s = (s << 1) ^ (s >= (1U<<31) ? CRC32_POLY : 0); crc_table[i] = s; } } static __forceinline uint32 crc32_update(uint32 crc, uint8 byte) { return (crc << 8) ^ crc_table[byte ^ (crc >> 24)]; } // used in setup, and for huffman that doesn't go fast path static unsigned int bit_reverse(unsigned int n) { n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1); n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2); n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4); n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8); return (n >> 16) | (n << 16); } static float square(float x) { return x*x; } // this is a weird definition of log2() for which log2(1) = 1, log2(2) = 2, log2(4) = 3 // as required by the specification. fast(?) implementation from stb.h // @OPTIMIZE: called multiple times per-packet with "constants"; move to setup static int ilog(int32 n) { static signed char log2_4[16] = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 }; if (n < 0) return 0; // signed n returns 0 // 2 compares if n < 16, 3 compares otherwise (4 if signed or n > 1<<29) if (n < (1 << 14)) if (n < (1 << 4)) return 0 + log2_4[n ]; else if (n < (1 << 9)) return 5 + log2_4[n >> 5]; else return 10 + log2_4[n >> 10]; else if (n < (1 << 24)) if (n < (1 << 19)) return 15 + log2_4[n >> 15]; else return 20 + log2_4[n >> 20]; else if (n < (1 << 29)) return 25 + log2_4[n >> 25]; else return 30 + log2_4[n >> 30]; } #ifndef M_PI #define M_PI 3.14159265358979323846264f // from CRC #endif // code length assigned to a value with no huffman encoding #define NO_CODE 255 /////////////////////// LEAF SETUP FUNCTIONS ////////////////////////// // // these functions are only called at setup, and only a few times // per file static float float32_unpack(uint32 x) { // from the specification uint32 mantissa = x & 0x1fffff; uint32 sign = x & 0x80000000; uint32 exp = (x & 0x7fe00000) >> 21; double res = sign ? -(double)mantissa : (double)mantissa; return (float) ldexp((float)res, exp-788); } // zlib & jpeg huffman tables assume that the output symbols // can either be arbitrarily arranged, or have monotonically // increasing frequencies--they rely on the lengths being sorted; // this makes for a very simple generation algorithm. // vorbis allows a huffman table with non-sorted lengths. This // requires a more sophisticated construction, since symbols in // order do not map to huffman codes "in order". static void add_entry(Codebook *c, uint32 huff_code, int symbol, int count, int len, uint32 *values) { if (!c->sparse) { c->codewords [symbol] = huff_code; } else { c->codewords [count] = huff_code; c->codeword_lengths[count] = len; values [count] = symbol; } } static int compute_codewords(Codebook *c, uint8 *len, int n, uint32 *values) { int i,k,m=0; uint32 available[32]; memset(available, 0, sizeof(available)); // find the first entry for (k=0; k < n; ++k) if (len[k] < NO_CODE) break; if (k == n) { assert(c->sorted_entries == 0); return TRUE; } // add to the list add_entry(c, 0, k, m++, len[k], values); // add all available leaves for (i=1; i <= len[k]; ++i) available[i] = 1U << (32-i); // note that the above code treats the first case specially, // but it's really the same as the following code, so they // could probably be combined (except the initial code is 0, // and I use 0 in available[] to mean 'empty') for (i=k+1; i < n; ++i) { uint32 res; int z = len[i], y; if (z == NO_CODE) continue; // find lowest available leaf (should always be earliest, // which is what the specification calls for) // note that this property, and the fact we can never have // more than one free leaf at a given level, isn't totally // trivial to prove, but it seems true and the assert never // fires, so! while (z > 0 && !available[z]) --z; if (z == 0) { return FALSE; } res = available[z]; assert(z >= 0 && z < 32); available[z] = 0; add_entry(c, bit_reverse(res), i, m++, len[i], values); // propagate availability up the tree if (z != len[i]) { assert(len[i] >= 0 && len[i] < 32); for (y=len[i]; y > z; --y) { assert(available[y] == 0); available[y] = res + (1 << (32-y)); } } } return TRUE; } // accelerated huffman table allows fast O(1) match of all symbols // of length <= STB_VORBIS_FAST_HUFFMAN_LENGTH static void compute_accelerated_huffman(Codebook *c) { int i, len; for (i=0; i < FAST_HUFFMAN_TABLE_SIZE; ++i) c->fast_huffman[i] = -1; len = c->sparse ? c->sorted_entries : c->entries; #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT if (len > 32767) len = 32767; // largest possible value we can encode! #endif for (i=0; i < len; ++i) { if (c->codeword_lengths[i] <= STB_VORBIS_FAST_HUFFMAN_LENGTH) { uint32 z = c->sparse ? bit_reverse(c->sorted_codewords[i]) : c->codewords[i]; // set table entries for all bit combinations in the higher bits while (z < FAST_HUFFMAN_TABLE_SIZE) { c->fast_huffman[z] = i; z += 1 << c->codeword_lengths[i]; } } } } #ifdef _MSC_VER #define STBV_CDECL __cdecl #else #define STBV_CDECL #endif static int STBV_CDECL uint32_compare(const void *p, const void *q) { uint32 x = * (uint32 *) p; uint32 y = * (uint32 *) q; return x < y ? -1 : x > y; } static int include_in_sort(Codebook *c, uint8 len) { if (c->sparse) { assert(len != NO_CODE); return TRUE; } if (len == NO_CODE) return FALSE; if (len > STB_VORBIS_FAST_HUFFMAN_LENGTH) return TRUE; return FALSE; } // if the fast table above doesn't work, we want to binary // search them... need to reverse the bits static void compute_sorted_huffman(Codebook *c, uint8 *lengths, uint32 *values) { int i, len; // build a list of all the entries // OPTIMIZATION: don't include the short ones, since they'll be caught by FAST_HUFFMAN. // this is kind of a frivolous optimization--I don't see any performance improvement, // but it's like 4 extra lines of code, so. if (!c->sparse) { int k = 0; for (i=0; i < c->entries; ++i) if (include_in_sort(c, lengths[i])) c->sorted_codewords[k++] = bit_reverse(c->codewords[i]); assert(k == c->sorted_entries); } else { for (i=0; i < c->sorted_entries; ++i) c->sorted_codewords[i] = bit_reverse(c->codewords[i]); } qsort(c->sorted_codewords, c->sorted_entries, sizeof(c->sorted_codewords[0]), uint32_compare); c->sorted_codewords[c->sorted_entries] = 0xffffffff; len = c->sparse ? c->sorted_entries : c->entries; // now we need to indicate how they correspond; we could either // #1: sort a different data structure that says who they correspond to // #2: for each sorted entry, search the original list to find who corresponds // #3: for each original entry, find the sorted entry // #1 requires extra storage, #2 is slow, #3 can use binary search! for (i=0; i < len; ++i) { int huff_len = c->sparse ? lengths[values[i]] : lengths[i]; if (include_in_sort(c,huff_len)) { uint32 code = bit_reverse(c->codewords[i]); int x=0, n=c->sorted_entries; while (n > 1) { // invariant: sc[x] <= code < sc[x+n] int m = x + (n >> 1); if (c->sorted_codewords[m] <= code) { x = m; n -= (n>>1); } else { n >>= 1; } } assert(c->sorted_codewords[x] == code); if (c->sparse) { c->sorted_values[x] = values[i]; c->codeword_lengths[x] = huff_len; } else { c->sorted_values[x] = i; } } } } // only run while parsing the header (3 times) static int vorbis_validate(uint8 *data) { static uint8 vorbis[6] = { 'v', 'o', 'r', 'b', 'i', 's' }; return memcmp(data, vorbis, 6) == 0; } // called from setup only, once per code book // (formula implied by specification) static int lookup1_values(int entries, int dim) { int r = (int) floor(exp((float) log((float) entries) / dim)); if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning; ++r; // floor() to avoid _ftol() when non-CRT assert(pow((float) r+1, dim) > entries); assert((int) floor(pow((float) r, dim)) <= entries); // (int),floor() as above return r; } // called twice per file static void compute_twiddle_factors(int n, float *A, float *B, float *C) { int n4 = n >> 2, n8 = n >> 3; int k,k2; for (k=k2=0; k < n4; ++k,k2+=2) { A[k2 ] = (float) cos(4*k*M_PI/n); A[k2+1] = (float) -sin(4*k*M_PI/n); B[k2 ] = (float) cos((k2+1)*M_PI/n/2) * 0.5f; B[k2+1] = (float) sin((k2+1)*M_PI/n/2) * 0.5f; } for (k=k2=0; k < n8; ++k,k2+=2) { C[k2 ] = (float) cos(2*(k2+1)*M_PI/n); C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n); } } static void compute_window(int n, float *window) { int n2 = n >> 1, i; for (i=0; i < n2; ++i) window[i] = (float) sin(0.5 * M_PI * square((float) sin((i - 0 + 0.5) / n2 * 0.5 * M_PI))); } static void compute_bitreverse(int n, uint16 *rev) { int ld = ilog(n) - 1; // ilog is off-by-one from normal definitions int i, n8 = n >> 3; for (i=0; i < n8; ++i) rev[i] = (bit_reverse(i) >> (32-ld+3)) << 2; } static int init_blocksize(vorb *f, int b, int n) { int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3; f->A[b] = (float *) setup_malloc(f, sizeof(float) * n2); f->B[b] = (float *) setup_malloc(f, sizeof(float) * n2); f->C[b] = (float *) setup_malloc(f, sizeof(float) * n4); if (!f->A[b] || !f->B[b] || !f->C[b]) return error(f, VORBIS_outofmem); compute_twiddle_factors(n, f->A[b], f->B[b], f->C[b]); f->window[b] = (float *) setup_malloc(f, sizeof(float) * n2); if (!f->window[b]) return error(f, VORBIS_outofmem); compute_window(n, f->window[b]); f->bit_reverse[b] = (uint16 *) setup_malloc(f, sizeof(uint16) * n8); if (!f->bit_reverse[b]) return error(f, VORBIS_outofmem); compute_bitreverse(n, f->bit_reverse[b]); return TRUE; } static void neighbors(uint16 *x, int n, int *plow, int *phigh) { int low = -1; int high = 65536; int i; for (i=0; i < n; ++i) { if (x[i] > low && x[i] < x[n]) { *plow = i; low = x[i]; } if (x[i] < high && x[i] > x[n]) { *phigh = i; high = x[i]; } } } // this has been repurposed so y is now the original index instead of y typedef struct { uint16 x,id; } stbv__floor_ordering; static int STBV_CDECL point_compare(const void *p, const void *q) { stbv__floor_ordering *a = (stbv__floor_ordering *) p; stbv__floor_ordering *b = (stbv__floor_ordering *) q; return a->x < b->x ? -1 : a->x > b->x; } // /////////////////////// END LEAF SETUP FUNCTIONS ////////////////////////// #if defined(STB_VORBIS_NO_STDIO) #define USE_MEMORY(z) TRUE #else #define USE_MEMORY(z) ((z)->stream) #endif static uint8 get8(vorb *z) { if (USE_MEMORY(z)) { if (z->stream >= z->stream_end) { z->eof = TRUE; return 0; } return *z->stream++; } #ifndef STB_VORBIS_NO_STDIO { int c = fgetc(z->f); if (c == EOF) { z->eof = TRUE; return 0; } return c; } #endif } static uint32 get32(vorb *f) { uint32 x; x = get8(f); x += get8(f) << 8; x += get8(f) << 16; x += (uint32) get8(f) << 24; return x; } static int getn(vorb *z, uint8 *data, int n) { if (USE_MEMORY(z)) { if (z->stream+n > z->stream_end) { z->eof = 1; return 0; } memcpy(data, z->stream, n); z->stream += n; return 1; } #ifndef STB_VORBIS_NO_STDIO if (fread(data, n, 1, z->f) == 1) return 1; else { z->eof = 1; return 0; } #endif } static void skip(vorb *z, int n) { if (USE_MEMORY(z)) { z->stream += n; if (z->stream >= z->stream_end) z->eof = 1; return; } #ifndef STB_VORBIS_NO_STDIO { long x = ftell(z->f); fseek(z->f, x+n, SEEK_SET); } #endif } static int set_file_offset(stb_vorbis *f, unsigned int loc) { #ifndef STB_VORBIS_NO_PUSHDATA_API if (f->push_mode) return 0; #endif f->eof = 0; if (USE_MEMORY(f)) { if (f->stream_start + loc >= f->stream_end || f->stream_start + loc < f->stream_start) { f->stream = f->stream_end; f->eof = 1; return 0; } else { f->stream = f->stream_start + loc; return 1; } } #ifndef STB_VORBIS_NO_STDIO if (loc + f->f_start < loc || loc >= 0x80000000) { loc = 0x7fffffff; f->eof = 1; } else { loc += f->f_start; } if (!fseek(f->f, loc, SEEK_SET)) return 1; f->eof = 1; fseek(f->f, f->f_start, SEEK_END); return 0; #endif } static uint8 ogg_page_header[4] = { 0x4f, 0x67, 0x67, 0x53 }; static int capture_pattern(vorb *f) { if (0x4f != get8(f)) return FALSE; if (0x67 != get8(f)) return FALSE; if (0x67 != get8(f)) return FALSE; if (0x53 != get8(f)) return FALSE; return TRUE; } #define PAGEFLAG_continued_packet 1 #define PAGEFLAG_first_page 2 #define PAGEFLAG_last_page 4 static int start_page_no_capturepattern(vorb *f) { uint32 loc0,loc1,n; // stream structure version if (0 != get8(f)) return error(f, VORBIS_invalid_stream_structure_version); // header flag f->page_flag = get8(f); // absolute granule position loc0 = get32(f); loc1 = get32(f); // @TODO: validate loc0,loc1 as valid positions? // stream serial number -- vorbis doesn't interleave, so discard get32(f); //if (f->serial != get32(f)) return error(f, VORBIS_incorrect_stream_serial_number); // page sequence number n = get32(f); f->last_page = n; // CRC32 get32(f); // page_segments f->segment_count = get8(f); if (!getn(f, f->segments, f->segment_count)) return error(f, VORBIS_unexpected_eof); // assume we _don't_ know any the sample position of any segments f->end_seg_with_known_loc = -2; if (loc0 != ~0U || loc1 != ~0U) { int i; // determine which packet is the last one that will complete for (i=f->segment_count-1; i >= 0; --i) if (f->segments[i] < 255) break; // 'i' is now the index of the _last_ segment of a packet that ends if (i >= 0) { f->end_seg_with_known_loc = i; f->known_loc_for_packet = loc0; } } if (f->first_decode) { int i,len; ProbedPage p; len = 0; for (i=0; i < f->segment_count; ++i) len += f->segments[i]; len += 27 + f->segment_count; p.page_start = f->first_audio_page_offset; p.page_end = p.page_start + len; p.last_decoded_sample = loc0; f->p_first = p; } f->next_seg = 0; return TRUE; } static int start_page(vorb *f) { if (!capture_pattern(f)) return error(f, VORBIS_missing_capture_pattern); return start_page_no_capturepattern(f); } static int start_packet(vorb *f) { while (f->next_seg == -1) { if (!start_page(f)) return FALSE; if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_continued_packet_flag_invalid); } f->last_seg = FALSE; f->valid_bits = 0; f->packet_bytes = 0; f->bytes_in_seg = 0; // f->next_seg is now valid return TRUE; } static int maybe_start_packet(vorb *f) { if (f->next_seg == -1) { int x = get8(f); if (f->eof) return FALSE; // EOF at page boundary is not an error! if (0x4f != x ) return error(f, VORBIS_missing_capture_pattern); if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern); if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern); if (0x53 != get8(f)) return error(f, VORBIS_missing_capture_pattern); if (!start_page_no_capturepattern(f)) return FALSE; if (f->page_flag & PAGEFLAG_continued_packet) { // set up enough state that we can read this packet if we want, // e.g. during recovery f->last_seg = FALSE; f->bytes_in_seg = 0; return error(f, VORBIS_continued_packet_flag_invalid); } } return start_packet(f); } static int next_segment(vorb *f) { int len; if (f->last_seg) return 0; if (f->next_seg == -1) { f->last_seg_which = f->segment_count-1; // in case start_page fails if (!start_page(f)) { f->last_seg = 1; return 0; } if (!(f->page_flag & PAGEFLAG_continued_packet)) return error(f, VORBIS_continued_packet_flag_invalid); } len = f->segments[f->next_seg++]; if (len < 255) { f->last_seg = TRUE; f->last_seg_which = f->next_seg-1; } if (f->next_seg >= f->segment_count) f->next_seg = -1; assert(f->bytes_in_seg == 0); f->bytes_in_seg = len; return len; } #define EOP (-1) #define INVALID_BITS (-1) static int get8_packet_raw(vorb *f) { if (!f->bytes_in_seg) { // CLANG! if (f->last_seg) return EOP; else if (!next_segment(f)) return EOP; } assert(f->bytes_in_seg > 0); --f->bytes_in_seg; ++f->packet_bytes; return get8(f); } static int get8_packet(vorb *f) { int x = get8_packet_raw(f); f->valid_bits = 0; return x; } static void flush_packet(vorb *f) { while (get8_packet_raw(f) != EOP); } // @OPTIMIZE: this is the secondary bit decoder, so it's probably not as important // as the huffman decoder? static uint32 get_bits(vorb *f, int n) { uint32 z; if (f->valid_bits < 0) return 0; if (f->valid_bits < n) { if (n > 24) { // the accumulator technique below would not work correctly in this case z = get_bits(f, 24); z += get_bits(f, n-24) << 24; return z; } if (f->valid_bits == 0) f->acc = 0; while (f->valid_bits < n) { int z = get8_packet_raw(f); if (z == EOP) { f->valid_bits = INVALID_BITS; return 0; } f->acc += z << f->valid_bits; f->valid_bits += 8; } } if (f->valid_bits < 0) return 0; z = f->acc & ((1 << n)-1); f->acc >>= n; f->valid_bits -= n; return z; } // @OPTIMIZE: primary accumulator for huffman // expand the buffer to as many bits as possible without reading off end of packet // it might be nice to allow f->valid_bits and f->acc to be stored in registers, // e.g. cache them locally and decode locally static __forceinline void prep_huffman(vorb *f) { if (f->valid_bits <= 24) { if (f->valid_bits == 0) f->acc = 0; do { int z; if (f->last_seg && !f->bytes_in_seg) return; z = get8_packet_raw(f); if (z == EOP) return; f->acc += (unsigned) z << f->valid_bits; f->valid_bits += 8; } while (f->valid_bits <= 24); } } enum { VORBIS_packet_id = 1, VORBIS_packet_comment = 3, VORBIS_packet_setup = 5 }; static int codebook_decode_scalar_raw(vorb *f, Codebook *c) { int i; prep_huffman(f); if (c->codewords == NULL && c->sorted_codewords == NULL) return -1; // cases to use binary search: sorted_codewords && !c->codewords // sorted_codewords && c->entries > 8 if (c->entries > 8 ? c->sorted_codewords!=NULL : !c->codewords) { // binary search uint32 code = bit_reverse(f->acc); int x=0, n=c->sorted_entries, len; while (n > 1) { // invariant: sc[x] <= code < sc[x+n] int m = x + (n >> 1); if (c->sorted_codewords[m] <= code) { x = m; n -= (n>>1); } else { n >>= 1; } } // x is now the sorted index if (!c->sparse) x = c->sorted_values[x]; // x is now sorted index if sparse, or symbol otherwise len = c->codeword_lengths[x]; if (f->valid_bits >= len) { f->acc >>= len; f->valid_bits -= len; return x; } f->valid_bits = 0; return -1; } // if small, linear search assert(!c->sparse); for (i=0; i < c->entries; ++i) { if (c->codeword_lengths[i] == NO_CODE) continue; if (c->codewords[i] == (f->acc & ((1 << c->codeword_lengths[i])-1))) { if (f->valid_bits >= c->codeword_lengths[i]) { f->acc >>= c->codeword_lengths[i]; f->valid_bits -= c->codeword_lengths[i]; return i; } f->valid_bits = 0; return -1; } } error(f, VORBIS_invalid_stream); f->valid_bits = 0; return -1; } #ifndef STB_VORBIS_NO_INLINE_DECODE #define DECODE_RAW(var, f,c) \ if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) \ prep_huffman(f); \ var = f->acc & FAST_HUFFMAN_TABLE_MASK; \ var = c->fast_huffman[var]; \ if (var >= 0) { \ int n = c->codeword_lengths[var]; \ f->acc >>= n; \ f->valid_bits -= n; \ if (f->valid_bits < 0) { f->valid_bits = 0; var = -1; } \ } else { \ var = codebook_decode_scalar_raw(f,c); \ } #else static int codebook_decode_scalar(vorb *f, Codebook *c) { int i; if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) prep_huffman(f); // fast huffman table lookup i = f->acc & FAST_HUFFMAN_TABLE_MASK; i = c->fast_huffman[i]; if (i >= 0) { f->acc >>= c->codeword_lengths[i]; f->valid_bits -= c->codeword_lengths[i]; if (f->valid_bits < 0) { f->valid_bits = 0; return -1; } return i; } return codebook_decode_scalar_raw(f,c); } #define DECODE_RAW(var,f,c) var = codebook_decode_scalar(f,c); #endif #define DECODE(var,f,c) \ DECODE_RAW(var,f,c) \ if (c->sparse) var = c->sorted_values[var]; #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK #define DECODE_VQ(var,f,c) DECODE_RAW(var,f,c) #else #define DECODE_VQ(var,f,c) DECODE(var,f,c) #endif // CODEBOOK_ELEMENT_FAST is an optimization for the CODEBOOK_FLOATS case // where we avoid one addition #define CODEBOOK_ELEMENT(c,off) (c->multiplicands[off]) #define CODEBOOK_ELEMENT_FAST(c,off) (c->multiplicands[off]) #define CODEBOOK_ELEMENT_BASE(c) (0) static int codebook_decode_start(vorb *f, Codebook *c) { int z = -1; // type 0 is only legal in a scalar context if (c->lookup_type == 0) error(f, VORBIS_invalid_stream); else { DECODE_VQ(z,f,c); if (c->sparse) assert(z < c->sorted_entries); if (z < 0) { // check for EOP if (!f->bytes_in_seg) if (f->last_seg) return z; error(f, VORBIS_invalid_stream); } } return z; } static int codebook_decode(vorb *f, Codebook *c, float *output, int len) { int i,z = codebook_decode_start(f,c); if (z < 0) return FALSE; if (len > c->dimensions) len = c->dimensions; #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { float last = CODEBOOK_ELEMENT_BASE(c); int div = 1; for (i=0; i < len; ++i) { int off = (z / div) % c->lookup_values; float val = CODEBOOK_ELEMENT_FAST(c,off) + last; output[i] += val; if (c->sequence_p) last = val + c->minimum_value; div *= c->lookup_values; } return TRUE; } #endif z *= c->dimensions; if (c->sequence_p) { float last = CODEBOOK_ELEMENT_BASE(c); for (i=0; i < len; ++i) { float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; output[i] += val; last = val + c->minimum_value; } } else { float last = CODEBOOK_ELEMENT_BASE(c); for (i=0; i < len; ++i) { output[i] += CODEBOOK_ELEMENT_FAST(c,z+i) + last; } } return TRUE; } static int codebook_decode_step(vorb *f, Codebook *c, float *output, int len, int step) { int i,z = codebook_decode_start(f,c); float last = CODEBOOK_ELEMENT_BASE(c); if (z < 0) return FALSE; if (len > c->dimensions) len = c->dimensions; #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { int div = 1; for (i=0; i < len; ++i) { int off = (z / div) % c->lookup_values; float val = CODEBOOK_ELEMENT_FAST(c,off) + last; output[i*step] += val; if (c->sequence_p) last = val; div *= c->lookup_values; } return TRUE; } #endif z *= c->dimensions; for (i=0; i < len; ++i) { float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; output[i*step] += val; if (c->sequence_p) last = val; } return TRUE; } static int codebook_decode_deinterleave_repeat(vorb *f, Codebook *c, float **outputs, int ch, int *c_inter_p, int *p_inter_p, int len, int total_decode) { int c_inter = *c_inter_p; int p_inter = *p_inter_p; int i,z, effective = c->dimensions; // type 0 is only legal in a scalar context if (c->lookup_type == 0) return error(f, VORBIS_invalid_stream); while (total_decode > 0) { float last = CODEBOOK_ELEMENT_BASE(c); DECODE_VQ(z,f,c); #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK assert(!c->sparse || z < c->sorted_entries); #endif if (z < 0) { if (!f->bytes_in_seg) if (f->last_seg) return FALSE; return error(f, VORBIS_invalid_stream); } // if this will take us off the end of the buffers, stop short! // we check by computing the length of the virtual interleaved // buffer (len*ch), our current offset within it (p_inter*ch)+(c_inter), // and the length we'll be using (effective) if (c_inter + p_inter*ch + effective > len * ch) { effective = len*ch - (p_inter*ch - c_inter); } #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { int div = 1; for (i=0; i < effective; ++i) { int off = (z / div) % c->lookup_values; float val = CODEBOOK_ELEMENT_FAST(c,off) + last; if (outputs[c_inter]) outputs[c_inter][p_inter] += val; if (++c_inter == ch) { c_inter = 0; ++p_inter; } if (c->sequence_p) last = val; div *= c->lookup_values; } } else #endif { z *= c->dimensions; if (c->sequence_p) { for (i=0; i < effective; ++i) { float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; if (outputs[c_inter]) outputs[c_inter][p_inter] += val; if (++c_inter == ch) { c_inter = 0; ++p_inter; } last = val; } } else { for (i=0; i < effective; ++i) { float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; if (outputs[c_inter]) outputs[c_inter][p_inter] += val; if (++c_inter == ch) { c_inter = 0; ++p_inter; } } } } total_decode -= effective; } *c_inter_p = c_inter; *p_inter_p = p_inter; return TRUE; } static int predict_point(int x, int x0, int x1, int y0, int y1) { int dy = y1 - y0; int adx = x1 - x0; // @OPTIMIZE: force int division to round in the right direction... is this necessary on x86? int err = abs(dy) * (x - x0); int off = err / adx; return dy < 0 ? y0 - off : y0 + off; } // the following table is block-copied from the specification static float inverse_db_table[256] = { 1.0649863e-07f, 1.1341951e-07f, 1.2079015e-07f, 1.2863978e-07f, 1.3699951e-07f, 1.4590251e-07f, 1.5538408e-07f, 1.6548181e-07f, 1.7623575e-07f, 1.8768855e-07f, 1.9988561e-07f, 2.1287530e-07f, 2.2670913e-07f, 2.4144197e-07f, 2.5713223e-07f, 2.7384213e-07f, 2.9163793e-07f, 3.1059021e-07f, 3.3077411e-07f, 3.5226968e-07f, 3.7516214e-07f, 3.9954229e-07f, 4.2550680e-07f, 4.5315863e-07f, 4.8260743e-07f, 5.1396998e-07f, 5.4737065e-07f, 5.8294187e-07f, 6.2082472e-07f, 6.6116941e-07f, 7.0413592e-07f, 7.4989464e-07f, 7.9862701e-07f, 8.5052630e-07f, 9.0579828e-07f, 9.6466216e-07f, 1.0273513e-06f, 1.0941144e-06f, 1.1652161e-06f, 1.2409384e-06f, 1.3215816e-06f, 1.4074654e-06f, 1.4989305e-06f, 1.5963394e-06f, 1.7000785e-06f, 1.8105592e-06f, 1.9282195e-06f, 2.0535261e-06f, 2.1869758e-06f, 2.3290978e-06f, 2.4804557e-06f, 2.6416497e-06f, 2.8133190e-06f, 2.9961443e-06f, 3.1908506e-06f, 3.3982101e-06f, 3.6190449e-06f, 3.8542308e-06f, 4.1047004e-06f, 4.3714470e-06f, 4.6555282e-06f, 4.9580707e-06f, 5.2802740e-06f, 5.6234160e-06f, 5.9888572e-06f, 6.3780469e-06f, 6.7925283e-06f, 7.2339451e-06f, 7.7040476e-06f, 8.2047000e-06f, 8.7378876e-06f, 9.3057248e-06f, 9.9104632e-06f, 1.0554501e-05f, 1.1240392e-05f, 1.1970856e-05f, 1.2748789e-05f, 1.3577278e-05f, 1.4459606e-05f, 1.5399272e-05f, 1.6400004e-05f, 1.7465768e-05f, 1.8600792e-05f, 1.9809576e-05f, 2.1096914e-05f, 2.2467911e-05f, 2.3928002e-05f, 2.5482978e-05f, 2.7139006e-05f, 2.8902651e-05f, 3.0780908e-05f, 3.2781225e-05f, 3.4911534e-05f, 3.7180282e-05f, 3.9596466e-05f, 4.2169667e-05f, 4.4910090e-05f, 4.7828601e-05f, 5.0936773e-05f, 5.4246931e-05f, 5.7772202e-05f, 6.1526565e-05f, 6.5524908e-05f, 6.9783085e-05f, 7.4317983e-05f, 7.9147585e-05f, 8.4291040e-05f, 8.9768747e-05f, 9.5602426e-05f, 0.00010181521f, 0.00010843174f, 0.00011547824f, 0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f, 0.00015820453f, 0.00016848555f, 0.00017943469f, 0.00019109536f, 0.00020351382f, 0.00021673929f, 0.00023082423f, 0.00024582449f, 0.00026179955f, 0.00027881276f, 0.00029693158f, 0.00031622787f, 0.00033677814f, 0.00035866388f, 0.00038197188f, 0.00040679456f, 0.00043323036f, 0.00046138411f, 0.00049136745f, 0.00052329927f, 0.00055730621f, 0.00059352311f, 0.00063209358f, 0.00067317058f, 0.00071691700f, 0.00076350630f, 0.00081312324f, 0.00086596457f, 0.00092223983f, 0.00098217216f, 0.0010459992f, 0.0011139742f, 0.0011863665f, 0.0012634633f, 0.0013455702f, 0.0014330129f, 0.0015261382f, 0.0016253153f, 0.0017309374f, 0.0018434235f, 0.0019632195f, 0.0020908006f, 0.0022266726f, 0.0023713743f, 0.0025254795f, 0.0026895994f, 0.0028643847f, 0.0030505286f, 0.0032487691f, 0.0034598925f, 0.0036847358f, 0.0039241906f, 0.0041792066f, 0.0044507950f, 0.0047400328f, 0.0050480668f, 0.0053761186f, 0.0057254891f, 0.0060975636f, 0.0064938176f, 0.0069158225f, 0.0073652516f, 0.0078438871f, 0.0083536271f, 0.0088964928f, 0.009474637f, 0.010090352f, 0.010746080f, 0.011444421f, 0.012188144f, 0.012980198f, 0.013823725f, 0.014722068f, 0.015678791f, 0.016697687f, 0.017782797f, 0.018938423f, 0.020169149f, 0.021479854f, 0.022875735f, 0.024362330f, 0.025945531f, 0.027631618f, 0.029427276f, 0.031339626f, 0.033376252f, 0.035545228f, 0.037855157f, 0.040315199f, 0.042935108f, 0.045725273f, 0.048696758f, 0.051861348f, 0.055231591f, 0.058820850f, 0.062643361f, 0.066714279f, 0.071049749f, 0.075666962f, 0.080584227f, 0.085821044f, 0.091398179f, 0.097337747f, 0.10366330f, 0.11039993f, 0.11757434f, 0.12521498f, 0.13335215f, 0.14201813f, 0.15124727f, 0.16107617f, 0.17154380f, 0.18269168f, 0.19456402f, 0.20720788f, 0.22067342f, 0.23501402f, 0.25028656f, 0.26655159f, 0.28387361f, 0.30232132f, 0.32196786f, 0.34289114f, 0.36517414f, 0.38890521f, 0.41417847f, 0.44109412f, 0.46975890f, 0.50028648f, 0.53279791f, 0.56742212f, 0.60429640f, 0.64356699f, 0.68538959f, 0.72993007f, 0.77736504f, 0.82788260f, 0.88168307f, 0.9389798f, 1.0f }; // @OPTIMIZE: if you want to replace this bresenham line-drawing routine, // note that you must produce bit-identical output to decode correctly; // this specific sequence of operations is specified in the spec (it's // drawing integer-quantized frequency-space lines that the encoder // expects to be exactly the same) // ... also, isn't the whole point of Bresenham's algorithm to NOT // have to divide in the setup? sigh. #ifndef STB_VORBIS_NO_DEFER_FLOOR #define LINE_OP(a,b) a *= b #else #define LINE_OP(a,b) a = b #endif #ifdef STB_VORBIS_DIVIDE_TABLE #define DIVTAB_NUMER 32 #define DIVTAB_DENOM 64 int8 integer_divide_table[DIVTAB_NUMER][DIVTAB_DENOM]; // 2KB #endif static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n) { int dy = y1 - y0; int adx = x1 - x0; int ady = abs(dy); int base; int x=x0,y=y0; int err = 0; int sy; #ifdef STB_VORBIS_DIVIDE_TABLE if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) { if (dy < 0) { base = -integer_divide_table[ady][adx]; sy = base-1; } else { base = integer_divide_table[ady][adx]; sy = base+1; } } else { base = dy / adx; if (dy < 0) sy = base - 1; else sy = base+1; } #else base = dy / adx; if (dy < 0) sy = base - 1; else sy = base+1; #endif ady -= abs(base) * adx; if (x1 > n) x1 = n; if (x < x1) { LINE_OP(output[x], inverse_db_table[y]); for (++x; x < x1; ++x) { err += ady; if (err >= adx) { err -= adx; y += sy; } else y += base; LINE_OP(output[x], inverse_db_table[y]); } } } static int residue_decode(vorb *f, Codebook *book, float *target, int offset, int n, int rtype) { int k; if (rtype == 0) { int step = n / book->dimensions; for (k=0; k < step; ++k) if (!codebook_decode_step(f, book, target+offset+k, n-offset-k, step)) return FALSE; } else { for (k=0; k < n; ) { if (!codebook_decode(f, book, target+offset, n-k)) return FALSE; k += book->dimensions; offset += book->dimensions; } } return TRUE; } // n is 1/2 of the blocksize -- // specification: "Correct per-vector decode length is [n]/2" static void decode_residue(vorb *f, float *residue_buffers[], int ch, int n, int rn, uint8 *do_not_decode) { int i,j,pass; Residue *r = f->residue_config + rn; int rtype = f->residue_types[rn]; int c = r->classbook; int classwords = f->codebooks[c].dimensions; unsigned int actual_size = rtype == 2 ? n*2 : n; unsigned int limit_r_begin = (r->begin < actual_size ? r->begin : actual_size); unsigned int limit_r_end = (r->end < actual_size ? r->end : actual_size); int n_read = limit_r_end - limit_r_begin; int part_read = n_read / r->part_size; int temp_alloc_point = temp_alloc_save(f); #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE uint8 ***part_classdata = (uint8 ***) temp_block_array(f,f->channels, part_read * sizeof(**part_classdata)); #else int **classifications = (int **) temp_block_array(f,f->channels, part_read * sizeof(**classifications)); #endif CHECK(f); for (i=0; i < ch; ++i) if (!do_not_decode[i]) memset(residue_buffers[i], 0, sizeof(float) * n); if (rtype == 2 && ch != 1) { for (j=0; j < ch; ++j) if (!do_not_decode[j]) break; if (j == ch) goto done; for (pass=0; pass < 8; ++pass) { int pcount = 0, class_set = 0; if (ch == 2) { while (pcount < part_read) { int z = r->begin + pcount*r->part_size; int c_inter = (z & 1), p_inter = z>>1; if (pass == 0) { Codebook *c = f->codebooks+r->classbook; int q; DECODE(q,f,c); if (q == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[0][class_set] = r->classdata[q]; #else for (i=classwords-1; i >= 0; --i) { classifications[0][i+pcount] = q % r->classifications; q /= r->classifications; } #endif } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { int z = r->begin + pcount*r->part_size; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[0][class_set][i]; #else int c = classifications[0][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { Codebook *book = f->codebooks + b; #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; #else // saves 1% if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; #endif } else { z += r->part_size; c_inter = z & 1; p_inter = z >> 1; } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } else if (ch == 1) { while (pcount < part_read) { int z = r->begin + pcount*r->part_size; int c_inter = 0, p_inter = z; if (pass == 0) { Codebook *c = f->codebooks+r->classbook; int q; DECODE(q,f,c); if (q == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[0][class_set] = r->classdata[q]; #else for (i=classwords-1; i >= 0; --i) { classifications[0][i+pcount] = q % r->classifications; q /= r->classifications; } #endif } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { int z = r->begin + pcount*r->part_size; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[0][class_set][i]; #else int c = classifications[0][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { Codebook *book = f->codebooks + b; if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; } else { z += r->part_size; c_inter = 0; p_inter = z; } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } else { while (pcount < part_read) { int z = r->begin + pcount*r->part_size; int c_inter = z % ch, p_inter = z/ch; if (pass == 0) { Codebook *c = f->codebooks+r->classbook; int q; DECODE(q,f,c); if (q == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[0][class_set] = r->classdata[q]; #else for (i=classwords-1; i >= 0; --i) { classifications[0][i+pcount] = q % r->classifications; q /= r->classifications; } #endif } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { int z = r->begin + pcount*r->part_size; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[0][class_set][i]; #else int c = classifications[0][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { Codebook *book = f->codebooks + b; if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; } else { z += r->part_size; c_inter = z % ch; p_inter = z / ch; } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } } goto done; } CHECK(f); for (pass=0; pass < 8; ++pass) { int pcount = 0, class_set=0; while (pcount < part_read) { if (pass == 0) { for (j=0; j < ch; ++j) { if (!do_not_decode[j]) { Codebook *c = f->codebooks+r->classbook; int temp; DECODE(temp,f,c); if (temp == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[j][class_set] = r->classdata[temp]; #else for (i=classwords-1; i >= 0; --i) { classifications[j][i+pcount] = temp % r->classifications; temp /= r->classifications; } #endif } } } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { for (j=0; j < ch; ++j) { if (!do_not_decode[j]) { #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[j][class_set][i]; #else int c = classifications[j][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { float *target = residue_buffers[j]; int offset = r->begin + pcount * r->part_size; int n = r->part_size; Codebook *book = f->codebooks + b; if (!residue_decode(f, book, target, offset, n, rtype)) goto done; } } } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } done: CHECK(f); #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE temp_free(f,part_classdata); #else temp_free(f,classifications); #endif temp_alloc_restore(f,temp_alloc_point); } #if 0 // slow way for debugging void inverse_mdct_slow(float *buffer, int n) { int i,j; int n2 = n >> 1; float *x = (float *) malloc(sizeof(*x) * n2); memcpy(x, buffer, sizeof(*x) * n2); for (i=0; i < n; ++i) { float acc = 0; for (j=0; j < n2; ++j) // formula from paper: //acc += n/4.0f * x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1)); // formula from wikipedia //acc += 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5)); // these are equivalent, except the formula from the paper inverts the multiplier! // however, what actually works is NO MULTIPLIER!?! //acc += 64 * 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5)); acc += x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1)); buffer[i] = acc; } free(x); } #elif 0 // same as above, but just barely able to run in real time on modern machines void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype) { float mcos[16384]; int i,j; int n2 = n >> 1, nmask = (n << 2) -1; float *x = (float *) malloc(sizeof(*x) * n2); memcpy(x, buffer, sizeof(*x) * n2); for (i=0; i < 4*n; ++i) mcos[i] = (float) cos(M_PI / 2 * i / n); for (i=0; i < n; ++i) { float acc = 0; for (j=0; j < n2; ++j) acc += x[j] * mcos[(2 * i + 1 + n2)*(2*j+1) & nmask]; buffer[i] = acc; } free(x); } #elif 0 // transform to use a slow dct-iv; this is STILL basically trivial, // but only requires half as many ops void dct_iv_slow(float *buffer, int n) { float mcos[16384]; float x[2048]; int i,j; int n2 = n >> 1, nmask = (n << 3) - 1; memcpy(x, buffer, sizeof(*x) * n); for (i=0; i < 8*n; ++i) mcos[i] = (float) cos(M_PI / 4 * i / n); for (i=0; i < n; ++i) { float acc = 0; for (j=0; j < n; ++j) acc += x[j] * mcos[((2 * i + 1)*(2*j+1)) & nmask]; buffer[i] = acc; } } void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype) { int i, n4 = n >> 2, n2 = n >> 1, n3_4 = n - n4; float temp[4096]; memcpy(temp, buffer, n2 * sizeof(float)); dct_iv_slow(temp, n2); // returns -c'-d, a-b' for (i=0; i < n4 ; ++i) buffer[i] = temp[i+n4]; // a-b' for ( ; i < n3_4; ++i) buffer[i] = -temp[n3_4 - i - 1]; // b-a', c+d' for ( ; i < n ; ++i) buffer[i] = -temp[i - n3_4]; // c'+d } #endif #ifndef LIBVORBIS_MDCT #define LIBVORBIS_MDCT 0 #endif #if LIBVORBIS_MDCT // directly call the vorbis MDCT using an interface documented // by Jeff Roberts... useful for performance comparison typedef struct { int n; int log2n; float *trig; int *bitrev; float scale; } mdct_lookup; extern void mdct_init(mdct_lookup *lookup, int n); extern void mdct_clear(mdct_lookup *l); extern void mdct_backward(mdct_lookup *init, float *in, float *out); mdct_lookup M1,M2; void inverse_mdct(float *buffer, int n, vorb *f, int blocktype) { mdct_lookup *M; if (M1.n == n) M = &M1; else if (M2.n == n) M = &M2; else if (M1.n == 0) { mdct_init(&M1, n); M = &M1; } else { if (M2.n) __asm int 3; mdct_init(&M2, n); M = &M2; } mdct_backward(M, buffer, buffer); } #endif // the following were split out into separate functions while optimizing; // they could be pushed back up but eh. __forceinline showed no change; // they're probably already being inlined. static void imdct_step3_iter0_loop(int n, float *e, int i_off, int k_off, float *A) { float *ee0 = e + i_off; float *ee2 = ee0 + k_off; int i; assert((n & 3) == 0); for (i=(n>>2); i > 0; --i) { float k00_20, k01_21; k00_20 = ee0[ 0] - ee2[ 0]; k01_21 = ee0[-1] - ee2[-1]; ee0[ 0] += ee2[ 0];//ee0[ 0] = ee0[ 0] + ee2[ 0]; ee0[-1] += ee2[-1];//ee0[-1] = ee0[-1] + ee2[-1]; ee2[ 0] = k00_20 * A[0] - k01_21 * A[1]; ee2[-1] = k01_21 * A[0] + k00_20 * A[1]; A += 8; k00_20 = ee0[-2] - ee2[-2]; k01_21 = ee0[-3] - ee2[-3]; ee0[-2] += ee2[-2];//ee0[-2] = ee0[-2] + ee2[-2]; ee0[-3] += ee2[-3];//ee0[-3] = ee0[-3] + ee2[-3]; ee2[-2] = k00_20 * A[0] - k01_21 * A[1]; ee2[-3] = k01_21 * A[0] + k00_20 * A[1]; A += 8; k00_20 = ee0[-4] - ee2[-4]; k01_21 = ee0[-5] - ee2[-5]; ee0[-4] += ee2[-4];//ee0[-4] = ee0[-4] + ee2[-4]; ee0[-5] += ee2[-5];//ee0[-5] = ee0[-5] + ee2[-5]; ee2[-4] = k00_20 * A[0] - k01_21 * A[1]; ee2[-5] = k01_21 * A[0] + k00_20 * A[1]; A += 8; k00_20 = ee0[-6] - ee2[-6]; k01_21 = ee0[-7] - ee2[-7]; ee0[-6] += ee2[-6];//ee0[-6] = ee0[-6] + ee2[-6]; ee0[-7] += ee2[-7];//ee0[-7] = ee0[-7] + ee2[-7]; ee2[-6] = k00_20 * A[0] - k01_21 * A[1]; ee2[-7] = k01_21 * A[0] + k00_20 * A[1]; A += 8; ee0 -= 8; ee2 -= 8; } } static void imdct_step3_inner_r_loop(int lim, float *e, int d0, int k_off, float *A, int k1) { int i; float k00_20, k01_21; float *e0 = e + d0; float *e2 = e0 + k_off; for (i=lim >> 2; i > 0; --i) { k00_20 = e0[-0] - e2[-0]; k01_21 = e0[-1] - e2[-1]; e0[-0] += e2[-0];//e0[-0] = e0[-0] + e2[-0]; e0[-1] += e2[-1];//e0[-1] = e0[-1] + e2[-1]; e2[-0] = (k00_20)*A[0] - (k01_21) * A[1]; e2[-1] = (k01_21)*A[0] + (k00_20) * A[1]; A += k1; k00_20 = e0[-2] - e2[-2]; k01_21 = e0[-3] - e2[-3]; e0[-2] += e2[-2];//e0[-2] = e0[-2] + e2[-2]; e0[-3] += e2[-3];//e0[-3] = e0[-3] + e2[-3]; e2[-2] = (k00_20)*A[0] - (k01_21) * A[1]; e2[-3] = (k01_21)*A[0] + (k00_20) * A[1]; A += k1; k00_20 = e0[-4] - e2[-4]; k01_21 = e0[-5] - e2[-5]; e0[-4] += e2[-4];//e0[-4] = e0[-4] + e2[-4]; e0[-5] += e2[-5];//e0[-5] = e0[-5] + e2[-5]; e2[-4] = (k00_20)*A[0] - (k01_21) * A[1]; e2[-5] = (k01_21)*A[0] + (k00_20) * A[1]; A += k1; k00_20 = e0[-6] - e2[-6]; k01_21 = e0[-7] - e2[-7]; e0[-6] += e2[-6];//e0[-6] = e0[-6] + e2[-6]; e0[-7] += e2[-7];//e0[-7] = e0[-7] + e2[-7]; e2[-6] = (k00_20)*A[0] - (k01_21) * A[1]; e2[-7] = (k01_21)*A[0] + (k00_20) * A[1]; e0 -= 8; e2 -= 8; A += k1; } } static void imdct_step3_inner_s_loop(int n, float *e, int i_off, int k_off, float *A, int a_off, int k0) { int i; float A0 = A[0]; float A1 = A[0+1]; float A2 = A[0+a_off]; float A3 = A[0+a_off+1]; float A4 = A[0+a_off*2+0]; float A5 = A[0+a_off*2+1]; float A6 = A[0+a_off*3+0]; float A7 = A[0+a_off*3+1]; float k00,k11; float *ee0 = e +i_off; float *ee2 = ee0+k_off; for (i=n; i > 0; --i) { k00 = ee0[ 0] - ee2[ 0]; k11 = ee0[-1] - ee2[-1]; ee0[ 0] = ee0[ 0] + ee2[ 0]; ee0[-1] = ee0[-1] + ee2[-1]; ee2[ 0] = (k00) * A0 - (k11) * A1; ee2[-1] = (k11) * A0 + (k00) * A1; k00 = ee0[-2] - ee2[-2]; k11 = ee0[-3] - ee2[-3]; ee0[-2] = ee0[-2] + ee2[-2]; ee0[-3] = ee0[-3] + ee2[-3]; ee2[-2] = (k00) * A2 - (k11) * A3; ee2[-3] = (k11) * A2 + (k00) * A3; k00 = ee0[-4] - ee2[-4]; k11 = ee0[-5] - ee2[-5]; ee0[-4] = ee0[-4] + ee2[-4]; ee0[-5] = ee0[-5] + ee2[-5]; ee2[-4] = (k00) * A4 - (k11) * A5; ee2[-5] = (k11) * A4 + (k00) * A5; k00 = ee0[-6] - ee2[-6]; k11 = ee0[-7] - ee2[-7]; ee0[-6] = ee0[-6] + ee2[-6]; ee0[-7] = ee0[-7] + ee2[-7]; ee2[-6] = (k00) * A6 - (k11) * A7; ee2[-7] = (k11) * A6 + (k00) * A7; ee0 -= k0; ee2 -= k0; } } static __forceinline void iter_54(float *z) { float k00,k11,k22,k33; float y0,y1,y2,y3; k00 = z[ 0] - z[-4]; y0 = z[ 0] + z[-4]; y2 = z[-2] + z[-6]; k22 = z[-2] - z[-6]; z[-0] = y0 + y2; // z0 + z4 + z2 + z6 z[-2] = y0 - y2; // z0 + z4 - z2 - z6 // done with y0,y2 k33 = z[-3] - z[-7]; z[-4] = k00 + k33; // z0 - z4 + z3 - z7 z[-6] = k00 - k33; // z0 - z4 - z3 + z7 // done with k33 k11 = z[-1] - z[-5]; y1 = z[-1] + z[-5]; y3 = z[-3] + z[-7]; z[-1] = y1 + y3; // z1 + z5 + z3 + z7 z[-3] = y1 - y3; // z1 + z5 - z3 - z7 z[-5] = k11 - k22; // z1 - z5 + z2 - z6 z[-7] = k11 + k22; // z1 - z5 - z2 + z6 } static void imdct_step3_inner_s_loop_ld654(int n, float *e, int i_off, float *A, int base_n) { int a_off = base_n >> 3; float A2 = A[0+a_off]; float *z = e + i_off; float *base = z - 16 * n; while (z > base) { float k00,k11; k00 = z[-0] - z[-8]; k11 = z[-1] - z[-9]; z[-0] = z[-0] + z[-8]; z[-1] = z[-1] + z[-9]; z[-8] = k00; z[-9] = k11 ; k00 = z[ -2] - z[-10]; k11 = z[ -3] - z[-11]; z[ -2] = z[ -2] + z[-10]; z[ -3] = z[ -3] + z[-11]; z[-10] = (k00+k11) * A2; z[-11] = (k11-k00) * A2; k00 = z[-12] - z[ -4]; // reverse to avoid a unary negation k11 = z[ -5] - z[-13]; z[ -4] = z[ -4] + z[-12]; z[ -5] = z[ -5] + z[-13]; z[-12] = k11; z[-13] = k00; k00 = z[-14] - z[ -6]; // reverse to avoid a unary negation k11 = z[ -7] - z[-15]; z[ -6] = z[ -6] + z[-14]; z[ -7] = z[ -7] + z[-15]; z[-14] = (k00+k11) * A2; z[-15] = (k00-k11) * A2; iter_54(z); iter_54(z-8); z -= 16; } } static void inverse_mdct(float *buffer, int n, vorb *f, int blocktype) { int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l; int ld; // @OPTIMIZE: reduce register pressure by using fewer variables? int save_point = temp_alloc_save(f); float *buf2 = (float *) temp_alloc(f, n2 * sizeof(*buf2)); float *u=NULL,*v=NULL; // twiddle factors float *A = f->A[blocktype]; // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio" // See notes about bugs in that paper in less-optimal implementation 'inverse_mdct_old' after this function. // kernel from paper // merged: // copy and reflect spectral data // step 0 // note that it turns out that the items added together during // this step are, in fact, being added to themselves (as reflected // by step 0). inexplicable inefficiency! this became obvious // once I combined the passes. // so there's a missing 'times 2' here (for adding X to itself). // this propagates through linearly to the end, where the numbers // are 1/2 too small, and need to be compensated for. { float *d,*e, *AA, *e_stop; d = &buf2[n2-2]; AA = A; e = &buffer[0]; e_stop = &buffer[n2]; while (e != e_stop) { d[1] = (e[0] * AA[0] - e[2]*AA[1]); d[0] = (e[0] * AA[1] + e[2]*AA[0]); d -= 2; AA += 2; e += 4; } e = &buffer[n2-3]; while (d >= buf2) { d[1] = (-e[2] * AA[0] - -e[0]*AA[1]); d[0] = (-e[2] * AA[1] + -e[0]*AA[0]); d -= 2; AA += 2; e -= 4; } } // now we use symbolic names for these, so that we can // possibly swap their meaning as we change which operations // are in place u = buffer; v = buf2; // step 2 (paper output is w, now u) // this could be in place, but the data ends up in the wrong // place... _somebody_'s got to swap it, so this is nominated { float *AA = &A[n2-8]; float *d0,*d1, *e0, *e1; e0 = &v[n4]; e1 = &v[0]; d0 = &u[n4]; d1 = &u[0]; while (AA >= A) { float v40_20, v41_21; v41_21 = e0[1] - e1[1]; v40_20 = e0[0] - e1[0]; d0[1] = e0[1] + e1[1]; d0[0] = e0[0] + e1[0]; d1[1] = v41_21*AA[4] - v40_20*AA[5]; d1[0] = v40_20*AA[4] + v41_21*AA[5]; v41_21 = e0[3] - e1[3]; v40_20 = e0[2] - e1[2]; d0[3] = e0[3] + e1[3]; d0[2] = e0[2] + e1[2]; d1[3] = v41_21*AA[0] - v40_20*AA[1]; d1[2] = v40_20*AA[0] + v41_21*AA[1]; AA -= 8; d0 += 4; d1 += 4; e0 += 4; e1 += 4; } } // step 3 ld = ilog(n) - 1; // ilog is off-by-one from normal definitions // optimized step 3: // the original step3 loop can be nested r inside s or s inside r; // it's written originally as s inside r, but this is dumb when r // iterates many times, and s few. So I have two copies of it and // switch between them halfway. // this is iteration 0 of step 3 imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*0, -(n >> 3), A); imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*1, -(n >> 3), A); // this is iteration 1 of step 3 imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*0, -(n >> 4), A, 16); imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*1, -(n >> 4), A, 16); imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*2, -(n >> 4), A, 16); imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*3, -(n >> 4), A, 16); l=2; for (; l < (ld-3)>>1; ++l) { int k0 = n >> (l+2), k0_2 = k0>>1; int lim = 1 << (l+1); int i; for (i=0; i < lim; ++i) imdct_step3_inner_r_loop(n >> (l+4), u, n2-1 - k0*i, -k0_2, A, 1 << (l+3)); } for (; l < ld-6; ++l) { int k0 = n >> (l+2), k1 = 1 << (l+3), k0_2 = k0>>1; int rlim = n >> (l+6), r; int lim = 1 << (l+1); int i_off; float *A0 = A; i_off = n2-1; for (r=rlim; r > 0; --r) { imdct_step3_inner_s_loop(lim, u, i_off, -k0_2, A0, k1, k0); A0 += k1*4; i_off -= 8; } } // iterations with count: // ld-6,-5,-4 all interleaved together // the big win comes from getting rid of needless flops // due to the constants on pass 5 & 4 being all 1 and 0; // combining them to be simultaneous to improve cache made little difference imdct_step3_inner_s_loop_ld654(n >> 5, u, n2-1, A, n); // output is u // step 4, 5, and 6 // cannot be in-place because of step 5 { uint16 *bitrev = f->bit_reverse[blocktype]; // weirdly, I'd have thought reading sequentially and writing // erratically would have been better than vice-versa, but in // fact that's not what my testing showed. (That is, with // j = bitreverse(i), do you read i and write j, or read j and write i.) float *d0 = &v[n4-4]; float *d1 = &v[n2-4]; while (d0 >= v) { int k4; k4 = bitrev[0]; d1[3] = u[k4+0]; d1[2] = u[k4+1]; d0[3] = u[k4+2]; d0[2] = u[k4+3]; k4 = bitrev[1]; d1[1] = u[k4+0]; d1[0] = u[k4+1]; d0[1] = u[k4+2]; d0[0] = u[k4+3]; d0 -= 4; d1 -= 4; bitrev += 2; } } // (paper output is u, now v) // data must be in buf2 assert(v == buf2); // step 7 (paper output is v, now v) // this is now in place { float *C = f->C[blocktype]; float *d, *e; d = v; e = v + n2 - 4; while (d < e) { float a02,a11,b0,b1,b2,b3; a02 = d[0] - e[2]; a11 = d[1] + e[3]; b0 = C[1]*a02 + C[0]*a11; b1 = C[1]*a11 - C[0]*a02; b2 = d[0] + e[ 2]; b3 = d[1] - e[ 3]; d[0] = b2 + b0; d[1] = b3 + b1; e[2] = b2 - b0; e[3] = b1 - b3; a02 = d[2] - e[0]; a11 = d[3] + e[1]; b0 = C[3]*a02 + C[2]*a11; b1 = C[3]*a11 - C[2]*a02; b2 = d[2] + e[ 0]; b3 = d[3] - e[ 1]; d[2] = b2 + b0; d[3] = b3 + b1; e[0] = b2 - b0; e[1] = b1 - b3; C += 4; d += 4; e -= 4; } } // data must be in buf2 // step 8+decode (paper output is X, now buffer) // this generates pairs of data a la 8 and pushes them directly through // the decode kernel (pushing rather than pulling) to avoid having // to make another pass later // this cannot POSSIBLY be in place, so we refer to the buffers directly { float *d0,*d1,*d2,*d3; float *B = f->B[blocktype] + n2 - 8; float *e = buf2 + n2 - 8; d0 = &buffer[0]; d1 = &buffer[n2-4]; d2 = &buffer[n2]; d3 = &buffer[n-4]; while (e >= v) { float p0,p1,p2,p3; p3 = e[6]*B[7] - e[7]*B[6]; p2 = -e[6]*B[6] - e[7]*B[7]; d0[0] = p3; d1[3] = - p3; d2[0] = p2; d3[3] = p2; p1 = e[4]*B[5] - e[5]*B[4]; p0 = -e[4]*B[4] - e[5]*B[5]; d0[1] = p1; d1[2] = - p1; d2[1] = p0; d3[2] = p0; p3 = e[2]*B[3] - e[3]*B[2]; p2 = -e[2]*B[2] - e[3]*B[3]; d0[2] = p3; d1[1] = - p3; d2[2] = p2; d3[1] = p2; p1 = e[0]*B[1] - e[1]*B[0]; p0 = -e[0]*B[0] - e[1]*B[1]; d0[3] = p1; d1[0] = - p1; d2[3] = p0; d3[0] = p0; B -= 8; e -= 8; d0 += 4; d2 += 4; d1 -= 4; d3 -= 4; } } temp_free(f,buf2); temp_alloc_restore(f,save_point); } #if 0 // this is the original version of the above code, if you want to optimize it from scratch void inverse_mdct_naive(float *buffer, int n) { float s; float A[1 << 12], B[1 << 12], C[1 << 11]; int i,k,k2,k4, n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l; int n3_4 = n - n4, ld; // how can they claim this only uses N words?! // oh, because they're only used sparsely, whoops float u[1 << 13], X[1 << 13], v[1 << 13], w[1 << 13]; // set up twiddle factors for (k=k2=0; k < n4; ++k,k2+=2) { A[k2 ] = (float) cos(4*k*M_PI/n); A[k2+1] = (float) -sin(4*k*M_PI/n); B[k2 ] = (float) cos((k2+1)*M_PI/n/2); B[k2+1] = (float) sin((k2+1)*M_PI/n/2); } for (k=k2=0; k < n8; ++k,k2+=2) { C[k2 ] = (float) cos(2*(k2+1)*M_PI/n); C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n); } // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio" // Note there are bugs in that pseudocode, presumably due to them attempting // to rename the arrays nicely rather than representing the way their actual // implementation bounces buffers back and forth. As a result, even in the // "some formulars corrected" version, a direct implementation fails. These // are noted below as "paper bug". // copy and reflect spectral data for (k=0; k < n2; ++k) u[k] = buffer[k]; for ( ; k < n ; ++k) u[k] = -buffer[n - k - 1]; // kernel from paper // step 1 for (k=k2=k4=0; k < n4; k+=1, k2+=2, k4+=4) { v[n-k4-1] = (u[k4] - u[n-k4-1]) * A[k2] - (u[k4+2] - u[n-k4-3])*A[k2+1]; v[n-k4-3] = (u[k4] - u[n-k4-1]) * A[k2+1] + (u[k4+2] - u[n-k4-3])*A[k2]; } // step 2 for (k=k4=0; k < n8; k+=1, k4+=4) { w[n2+3+k4] = v[n2+3+k4] + v[k4+3]; w[n2+1+k4] = v[n2+1+k4] + v[k4+1]; w[k4+3] = (v[n2+3+k4] - v[k4+3])*A[n2-4-k4] - (v[n2+1+k4]-v[k4+1])*A[n2-3-k4]; w[k4+1] = (v[n2+1+k4] - v[k4+1])*A[n2-4-k4] + (v[n2+3+k4]-v[k4+3])*A[n2-3-k4]; } // step 3 ld = ilog(n) - 1; // ilog is off-by-one from normal definitions for (l=0; l < ld-3; ++l) { int k0 = n >> (l+2), k1 = 1 << (l+3); int rlim = n >> (l+4), r4, r; int s2lim = 1 << (l+2), s2; for (r=r4=0; r < rlim; r4+=4,++r) { for (s2=0; s2 < s2lim; s2+=2) { u[n-1-k0*s2-r4] = w[n-1-k0*s2-r4] + w[n-1-k0*(s2+1)-r4]; u[n-3-k0*s2-r4] = w[n-3-k0*s2-r4] + w[n-3-k0*(s2+1)-r4]; u[n-1-k0*(s2+1)-r4] = (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1] - (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1+1]; u[n-3-k0*(s2+1)-r4] = (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1] + (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1+1]; } } if (l+1 < ld-3) { // paper bug: ping-ponging of u&w here is omitted memcpy(w, u, sizeof(u)); } } // step 4 for (i=0; i < n8; ++i) { int j = bit_reverse(i) >> (32-ld+3); assert(j < n8); if (i == j) { // paper bug: original code probably swapped in place; if copying, // need to directly copy in this case int i8 = i << 3; v[i8+1] = u[i8+1]; v[i8+3] = u[i8+3]; v[i8+5] = u[i8+5]; v[i8+7] = u[i8+7]; } else if (i < j) { int i8 = i << 3, j8 = j << 3; v[j8+1] = u[i8+1], v[i8+1] = u[j8 + 1]; v[j8+3] = u[i8+3], v[i8+3] = u[j8 + 3]; v[j8+5] = u[i8+5], v[i8+5] = u[j8 + 5]; v[j8+7] = u[i8+7], v[i8+7] = u[j8 + 7]; } } // step 5 for (k=0; k < n2; ++k) { w[k] = v[k*2+1]; } // step 6 for (k=k2=k4=0; k < n8; ++k, k2 += 2, k4 += 4) { u[n-1-k2] = w[k4]; u[n-2-k2] = w[k4+1]; u[n3_4 - 1 - k2] = w[k4+2]; u[n3_4 - 2 - k2] = w[k4+3]; } // step 7 for (k=k2=0; k < n8; ++k, k2 += 2) { v[n2 + k2 ] = ( u[n2 + k2] + u[n-2-k2] + C[k2+1]*(u[n2+k2]-u[n-2-k2]) + C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2; v[n-2 - k2] = ( u[n2 + k2] + u[n-2-k2] - C[k2+1]*(u[n2+k2]-u[n-2-k2]) - C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2; v[n2+1+ k2] = ( u[n2+1+k2] - u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2; v[n-1 - k2] = (-u[n2+1+k2] + u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2; } // step 8 for (k=k2=0; k < n4; ++k,k2 += 2) { X[k] = v[k2+n2]*B[k2 ] + v[k2+1+n2]*B[k2+1]; X[n2-1-k] = v[k2+n2]*B[k2+1] - v[k2+1+n2]*B[k2 ]; } // decode kernel to output // determined the following value experimentally // (by first figuring out what made inverse_mdct_slow work); then matching that here // (probably vorbis encoder premultiplies by n or n/2, to save it on the decoder?) s = 0.5; // theoretically would be n4 // [[[ note! the s value of 0.5 is compensated for by the B[] in the current code, // so it needs to use the "old" B values to behave correctly, or else // set s to 1.0 ]]] for (i=0; i < n4 ; ++i) buffer[i] = s * X[i+n4]; for ( ; i < n3_4; ++i) buffer[i] = -s * X[n3_4 - i - 1]; for ( ; i < n ; ++i) buffer[i] = -s * X[i - n3_4]; } #endif static float *get_window(vorb *f, int len) { len <<= 1; if (len == f->blocksize_0) return f->window[0]; if (len == f->blocksize_1) return f->window[1]; assert(0); return NULL; } #ifndef STB_VORBIS_NO_DEFER_FLOOR typedef int16 YTYPE; #else typedef int YTYPE; #endif static int do_floor(vorb *f, Mapping *map, int i, int n, float *target, YTYPE *finalY, uint8 *step2_flag) { int n2 = n >> 1; int s = map->chan[i].mux, floor; floor = map->submap_floor[s]; if (f->floor_types[floor] == 0) { return error(f, VORBIS_invalid_stream); } else { Floor1 *g = &f->floor_config[floor].floor1; int j,q; int lx = 0, ly = finalY[0] * g->floor1_multiplier; for (q=1; q < g->values; ++q) { j = g->sorted_order[q]; #ifndef STB_VORBIS_NO_DEFER_FLOOR if (finalY[j] >= 0) #else if (step2_flag[j]) #endif { int hy = finalY[j] * g->floor1_multiplier; int hx = g->Xlist[j]; if (lx != hx) draw_line(target, lx,ly, hx,hy, n2); CHECK(f); lx = hx, ly = hy; } } if (lx < n2) { // optimization of: draw_line(target, lx,ly, n,ly, n2); for (j=lx; j < n2; ++j) LINE_OP(target[j], inverse_db_table[ly]); CHECK(f); } } return TRUE; } // The meaning of "left" and "right" // // For a given frame: // we compute samples from 0..n // window_center is n/2 // we'll window and mix the samples from left_start to left_end with data from the previous frame // all of the samples from left_end to right_start can be output without mixing; however, // this interval is 0-length except when transitioning between short and long frames // all of the samples from right_start to right_end need to be mixed with the next frame, // which we don't have, so those get saved in a buffer // frame N's right_end-right_start, the number of samples to mix with the next frame, // has to be the same as frame N+1's left_end-left_start (which they are by // construction) static int vorbis_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode) { Mode *m; int i, n, prev, next, window_center; f->channel_buffer_start = f->channel_buffer_end = 0; retry: if (f->eof) return FALSE; if (!maybe_start_packet(f)) return FALSE; // check packet type if (get_bits(f,1) != 0) { if (IS_PUSH_MODE(f)) return error(f,VORBIS_bad_packet_type); while (EOP != get8_packet(f)); goto retry; } if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); i = get_bits(f, ilog(f->mode_count-1)); if (i == EOP) return FALSE; if (i >= f->mode_count) return FALSE; *mode = i; m = f->mode_config + i; if (m->blockflag) { n = f->blocksize_1; prev = get_bits(f,1); next = get_bits(f,1); } else { prev = next = 0; n = f->blocksize_0; } // WINDOWING window_center = n >> 1; if (m->blockflag && !prev) { *p_left_start = (n - f->blocksize_0) >> 2; *p_left_end = (n + f->blocksize_0) >> 2; } else { *p_left_start = 0; *p_left_end = window_center; } if (m->blockflag && !next) { *p_right_start = (n*3 - f->blocksize_0) >> 2; *p_right_end = (n*3 + f->blocksize_0) >> 2; } else { *p_right_start = window_center; *p_right_end = n; } return TRUE; } static int vorbis_decode_packet_rest(vorb *f, int *len, Mode *m, int left_start, int left_end, int right_start, int right_end, int *p_left) { Mapping *map; int i,j,k,n,n2; int zero_channel[256]; int really_zero_channel[256]; // WINDOWING n = f->blocksize[m->blockflag]; map = &f->mapping[m->mapping]; // FLOORS n2 = n >> 1; CHECK(f); for (i=0; i < f->channels; ++i) { int s = map->chan[i].mux, floor; zero_channel[i] = FALSE; floor = map->submap_floor[s]; if (f->floor_types[floor] == 0) { return error(f, VORBIS_invalid_stream); } else { Floor1 *g = &f->floor_config[floor].floor1; if (get_bits(f, 1)) { short *finalY; uint8 step2_flag[256]; static int range_list[4] = { 256, 128, 86, 64 }; int range = range_list[g->floor1_multiplier-1]; int offset = 2; finalY = f->finalY[i]; finalY[0] = get_bits(f, ilog(range)-1); finalY[1] = get_bits(f, ilog(range)-1); for (j=0; j < g->partitions; ++j) { int pclass = g->partition_class_list[j]; int cdim = g->class_dimensions[pclass]; int cbits = g->class_subclasses[pclass]; int csub = (1 << cbits)-1; int cval = 0; if (cbits) { Codebook *c = f->codebooks + g->class_masterbooks[pclass]; DECODE(cval,f,c); } for (k=0; k < cdim; ++k) { int book = g->subclass_books[pclass][cval & csub]; cval = cval >> cbits; if (book >= 0) { int temp; Codebook *c = f->codebooks + book; DECODE(temp,f,c); finalY[offset++] = temp; } else finalY[offset++] = 0; } } if (f->valid_bits == INVALID_BITS) goto error; // behavior according to spec step2_flag[0] = step2_flag[1] = 1; for (j=2; j < g->values; ++j) { int low, high, pred, highroom, lowroom, room, val; low = g->neighbors[j][0]; high = g->neighbors[j][1]; //neighbors(g->Xlist, j, &low, &high); pred = predict_point(g->Xlist[j], g->Xlist[low], g->Xlist[high], finalY[low], finalY[high]); val = finalY[j]; highroom = range - pred; lowroom = pred; if (highroom < lowroom) room = highroom * 2; else room = lowroom * 2; if (val) { step2_flag[low] = step2_flag[high] = 1; step2_flag[j] = 1; if (val >= room) if (highroom > lowroom) finalY[j] = val - lowroom + pred; else finalY[j] = pred - val + highroom - 1; else if (val & 1) finalY[j] = pred - ((val+1)>>1); else finalY[j] = pred + (val>>1); } else { step2_flag[j] = 0; finalY[j] = pred; } } #ifdef STB_VORBIS_NO_DEFER_FLOOR do_floor(f, map, i, n, f->floor_buffers[i], finalY, step2_flag); #else // defer final floor computation until _after_ residue for (j=0; j < g->values; ++j) { if (!step2_flag[j]) finalY[j] = -1; } #endif } else { error: zero_channel[i] = TRUE; } // So we just defer everything else to later // at this point we've decoded the floor into buffer } } CHECK(f); // at this point we've decoded all floors if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); // re-enable coupled channels if necessary memcpy(really_zero_channel, zero_channel, sizeof(really_zero_channel[0]) * f->channels); for (i=0; i < map->coupling_steps; ++i) if (!zero_channel[map->chan[i].magnitude] || !zero_channel[map->chan[i].angle]) { zero_channel[map->chan[i].magnitude] = zero_channel[map->chan[i].angle] = FALSE; } CHECK(f); // RESIDUE DECODE for (i=0; i < map->submaps; ++i) { float *residue_buffers[STB_VORBIS_MAX_CHANNELS]; int r; uint8 do_not_decode[256]; int ch = 0; for (j=0; j < f->channels; ++j) { if (map->chan[j].mux == i) { if (zero_channel[j]) { do_not_decode[ch] = TRUE; residue_buffers[ch] = NULL; } else { do_not_decode[ch] = FALSE; residue_buffers[ch] = f->channel_buffers[j]; } ++ch; } } r = map->submap_residue[i]; decode_residue(f, residue_buffers, ch, n2, r, do_not_decode); } if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); CHECK(f); // INVERSE COUPLING for (i = map->coupling_steps-1; i >= 0; --i) { int n2 = n >> 1; float *m = f->channel_buffers[map->chan[i].magnitude]; float *a = f->channel_buffers[map->chan[i].angle ]; for (j=0; j < n2; ++j) { float a2,m2; if (m[j] > 0) if (a[j] > 0) m2 = m[j], a2 = m[j] - a[j]; else a2 = m[j], m2 = m[j] + a[j]; else if (a[j] > 0) m2 = m[j], a2 = m[j] + a[j]; else a2 = m[j], m2 = m[j] - a[j]; m[j] = m2; a[j] = a2; } } CHECK(f); // finish decoding the floors #ifndef STB_VORBIS_NO_DEFER_FLOOR for (i=0; i < f->channels; ++i) { if (really_zero_channel[i]) { memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2); } else { do_floor(f, map, i, n, f->channel_buffers[i], f->finalY[i], NULL); } } #else for (i=0; i < f->channels; ++i) { if (really_zero_channel[i]) { memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2); } else { for (j=0; j < n2; ++j) f->channel_buffers[i][j] *= f->floor_buffers[i][j]; } } #endif // INVERSE MDCT CHECK(f); for (i=0; i < f->channels; ++i) inverse_mdct(f->channel_buffers[i], n, f, m->blockflag); CHECK(f); // this shouldn't be necessary, unless we exited on an error // and want to flush to get to the next packet flush_packet(f); if (f->first_decode) { // assume we start so first non-discarded sample is sample 0 // this isn't to spec, but spec would require us to read ahead // and decode the size of all current frames--could be done, // but presumably it's not a commonly used feature f->current_loc = -n2; // start of first frame is positioned for discard // we might have to discard samples "from" the next frame too, // if we're lapping a large block then a small at the start? f->discard_samples_deferred = n - right_end; f->current_loc_valid = TRUE; f->first_decode = FALSE; } else if (f->discard_samples_deferred) { if (f->discard_samples_deferred >= right_start - left_start) { f->discard_samples_deferred -= (right_start - left_start); left_start = right_start; *p_left = left_start; } else { left_start += f->discard_samples_deferred; *p_left = left_start; f->discard_samples_deferred = 0; } } else if (f->previous_length == 0 && f->current_loc_valid) { // we're recovering from a seek... that means we're going to discard // the samples from this packet even though we know our position from // the last page header, so we need to update the position based on // the discarded samples here // but wait, the code below is going to add this in itself even // on a discard, so we don't need to do it here... } // check if we have ogg information about the sample # for this packet if (f->last_seg_which == f->end_seg_with_known_loc) { // if we have a valid current loc, and this is final: if (f->current_loc_valid && (f->page_flag & PAGEFLAG_last_page)) { uint32 current_end = f->known_loc_for_packet; // then let's infer the size of the (probably) short final frame if (current_end < f->current_loc + (right_end-left_start)) { if (current_end < f->current_loc) { // negative truncation, that's impossible! *len = 0; } else { *len = current_end - f->current_loc; } *len += left_start; // this doesn't seem right, but has no ill effect on my test files if (*len > right_end) *len = right_end; // this should never happen f->current_loc += *len; return TRUE; } } // otherwise, just set our sample loc // guess that the ogg granule pos refers to the _middle_ of the // last frame? // set f->current_loc to the position of left_start f->current_loc = f->known_loc_for_packet - (n2-left_start); f->current_loc_valid = TRUE; } if (f->current_loc_valid) f->current_loc += (right_start - left_start); if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); *len = right_end; // ignore samples after the window goes to 0 CHECK(f); return TRUE; } static int vorbis_decode_packet(vorb *f, int *len, int *p_left, int *p_right) { int mode, left_end, right_end; if (!vorbis_decode_initial(f, p_left, &left_end, p_right, &right_end, &mode)) return 0; return vorbis_decode_packet_rest(f, len, f->mode_config + mode, *p_left, left_end, *p_right, right_end, p_left); } static int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right) { int prev,i,j; // we use right&left (the start of the right- and left-window sin()-regions) // to determine how much to return, rather than inferring from the rules // (same result, clearer code); 'left' indicates where our sin() window // starts, therefore where the previous window's right edge starts, and // therefore where to start mixing from the previous buffer. 'right' // indicates where our sin() ending-window starts, therefore that's where // we start saving, and where our returned-data ends. // mixin from previous window if (f->previous_length) { int i,j, n = f->previous_length; float *w = get_window(f, n); for (i=0; i < f->channels; ++i) { for (j=0; j < n; ++j) f->channel_buffers[i][left+j] = f->channel_buffers[i][left+j]*w[ j] + f->previous_window[i][ j]*w[n-1-j]; } } prev = f->previous_length; // last half of this data becomes previous window f->previous_length = len - right; // @OPTIMIZE: could avoid this copy by double-buffering the // output (flipping previous_window with channel_buffers), but // then previous_window would have to be 2x as large, and // channel_buffers couldn't be temp mem (although they're NOT // currently temp mem, they could be (unless we want to level // performance by spreading out the computation)) for (i=0; i < f->channels; ++i) for (j=0; right+j < len; ++j) f->previous_window[i][j] = f->channel_buffers[i][right+j]; if (!prev) // there was no previous packet, so this data isn't valid... // this isn't entirely true, only the would-have-overlapped data // isn't valid, but this seems to be what the spec requires return 0; // truncate a short frame if (len < right) right = len; f->samples_output += right-left; return right - left; } static int vorbis_pump_first_frame(stb_vorbis *f) { int len, right, left, res; res = vorbis_decode_packet(f, &len, &left, &right); if (res) vorbis_finish_frame(f, len, left, right); return res; } #ifndef STB_VORBIS_NO_PUSHDATA_API static int is_whole_packet_present(stb_vorbis *f, int end_page) { // make sure that we have the packet available before continuing... // this requires a full ogg parse, but we know we can fetch from f->stream // instead of coding this out explicitly, we could save the current read state, // read the next packet with get8() until end-of-packet, check f->eof, then // reset the state? but that would be slower, esp. since we'd have over 256 bytes // of state to restore (primarily the page segment table) int s = f->next_seg, first = TRUE; uint8 *p = f->stream; if (s != -1) { // if we're not starting the packet with a 'continue on next page' flag for (; s < f->segment_count; ++s) { p += f->segments[s]; if (f->segments[s] < 255) // stop at first short segment break; } // either this continues, or it ends it... if (end_page) if (s < f->segment_count-1) return error(f, VORBIS_invalid_stream); if (s == f->segment_count) s = -1; // set 'crosses page' flag if (p > f->stream_end) return error(f, VORBIS_need_more_data); first = FALSE; } for (; s == -1;) { uint8 *q; int n; // check that we have the page header ready if (p + 26 >= f->stream_end) return error(f, VORBIS_need_more_data); // validate the page if (memcmp(p, ogg_page_header, 4)) return error(f, VORBIS_invalid_stream); if (p[4] != 0) return error(f, VORBIS_invalid_stream); if (first) { // the first segment must NOT have 'continued_packet', later ones MUST if (f->previous_length) if ((p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream); // if no previous length, we're resynching, so we can come in on a continued-packet, // which we'll just drop } else { if (!(p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream); } n = p[26]; // segment counts q = p+27; // q points to segment table p = q + n; // advance past header // make sure we've read the segment table if (p > f->stream_end) return error(f, VORBIS_need_more_data); for (s=0; s < n; ++s) { p += q[s]; if (q[s] < 255) break; } if (end_page) if (s < n-1) return error(f, VORBIS_invalid_stream); if (s == n) s = -1; // set 'crosses page' flag if (p > f->stream_end) return error(f, VORBIS_need_more_data); first = FALSE; } return TRUE; } #endif // !STB_VORBIS_NO_PUSHDATA_API static int start_decoder(vorb *f) { uint8 header[6], x,y; int len,i,j,k, max_submaps = 0; int longest_floorlist=0; // first page, first packet if (!start_page(f)) return FALSE; // validate page flag if (!(f->page_flag & PAGEFLAG_first_page)) return error(f, VORBIS_invalid_first_page); if (f->page_flag & PAGEFLAG_last_page) return error(f, VORBIS_invalid_first_page); if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_invalid_first_page); // check for expected packet length if (f->segment_count != 1) return error(f, VORBIS_invalid_first_page); if (f->segments[0] != 30) { // check for the Ogg skeleton fishead identifying header to refine our error if (f->segments[0] == 64 && getn(f, header, 6) && header[0] == 'f' && header[1] == 'i' && header[2] == 's' && header[3] == 'h' && header[4] == 'e' && header[5] == 'a' && get8(f) == 'd' && get8(f) == '\0') return error(f, VORBIS_ogg_skeleton_not_supported); else return error(f, VORBIS_invalid_first_page); } // read packet // check packet header if (get8(f) != VORBIS_packet_id) return error(f, VORBIS_invalid_first_page); if (!getn(f, header, 6)) return error(f, VORBIS_unexpected_eof); if (!vorbis_validate(header)) return error(f, VORBIS_invalid_first_page); // vorbis_version if (get32(f) != 0) return error(f, VORBIS_invalid_first_page); f->channels = get8(f); if (!f->channels) return error(f, VORBIS_invalid_first_page); if (f->channels > STB_VORBIS_MAX_CHANNELS) return error(f, VORBIS_too_many_channels); f->sample_rate = get32(f); if (!f->sample_rate) return error(f, VORBIS_invalid_first_page); get32(f); // bitrate_maximum get32(f); // bitrate_nominal get32(f); // bitrate_minimum x = get8(f); { int log0,log1; log0 = x & 15; log1 = x >> 4; f->blocksize_0 = 1 << log0; f->blocksize_1 = 1 << log1; if (log0 < 6 || log0 > 13) return error(f, VORBIS_invalid_setup); if (log1 < 6 || log1 > 13) return error(f, VORBIS_invalid_setup); if (log0 > log1) return error(f, VORBIS_invalid_setup); } // framing_flag x = get8(f); if (!(x & 1)) return error(f, VORBIS_invalid_first_page); // second packet! if (!start_page(f)) return FALSE; if (!start_packet(f)) return FALSE; do { len = next_segment(f); skip(f, len); f->bytes_in_seg = 0; } while (len); // third packet! if (!start_packet(f)) return FALSE; #ifndef STB_VORBIS_NO_PUSHDATA_API if (IS_PUSH_MODE(f)) { if (!is_whole_packet_present(f, TRUE)) { // convert error in ogg header to write type if (f->error == VORBIS_invalid_stream) f->error = VORBIS_invalid_setup; return FALSE; } } #endif crc32_init(); // always init it, to avoid multithread race conditions if (get8_packet(f) != VORBIS_packet_setup) return error(f, VORBIS_invalid_setup); for (i=0; i < 6; ++i) header[i] = get8_packet(f); if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup); // codebooks f->codebook_count = get_bits(f,8) + 1; f->codebooks = (Codebook *) setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count); if (f->codebooks == NULL) return error(f, VORBIS_outofmem); memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count); for (i=0; i < f->codebook_count; ++i) { uint32 *values; int ordered, sorted_count; int total=0; uint8 *lengths; Codebook *c = f->codebooks+i; CHECK(f); x = get_bits(f, 8); if (x != 0x42) return error(f, VORBIS_invalid_setup); x = get_bits(f, 8); if (x != 0x43) return error(f, VORBIS_invalid_setup); x = get_bits(f, 8); if (x != 0x56) return error(f, VORBIS_invalid_setup); x = get_bits(f, 8); c->dimensions = (get_bits(f, 8)<<8) + x; x = get_bits(f, 8); y = get_bits(f, 8); c->entries = (get_bits(f, 8)<<16) + (y<<8) + x; ordered = get_bits(f,1); c->sparse = ordered ? 0 : get_bits(f,1); if (c->dimensions == 0 && c->entries != 0) return error(f, VORBIS_invalid_setup); if (c->sparse) lengths = (uint8 *) setup_temp_malloc(f, c->entries); else lengths = c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries); if (!lengths) return error(f, VORBIS_outofmem); if (ordered) { int current_entry = 0; int current_length = get_bits(f,5) + 1; while (current_entry < c->entries) { int limit = c->entries - current_entry; int n = get_bits(f, ilog(limit)); if (current_entry + n > (int) c->entries) { return error(f, VORBIS_invalid_setup); } memset(lengths + current_entry, current_length, n); current_entry += n; ++current_length; } } else { for (j=0; j < c->entries; ++j) { int present = c->sparse ? get_bits(f,1) : 1; if (present) { lengths[j] = get_bits(f, 5) + 1; ++total; if (lengths[j] == 32) return error(f, VORBIS_invalid_setup); } else { lengths[j] = NO_CODE; } } } if (c->sparse && total >= c->entries >> 2) { // convert sparse items to non-sparse! if (c->entries > (int) f->setup_temp_memory_required) f->setup_temp_memory_required = c->entries; c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries); if (c->codeword_lengths == NULL) return error(f, VORBIS_outofmem); memcpy(c->codeword_lengths, lengths, c->entries); setup_temp_free(f, lengths, c->entries); // note this is only safe if there have been no intervening temp mallocs! lengths = c->codeword_lengths; c->sparse = 0; } // compute the size of the sorted tables if (c->sparse) { sorted_count = total; } else { sorted_count = 0; #ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH for (j=0; j < c->entries; ++j) if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE) ++sorted_count; #endif } c->sorted_entries = sorted_count; values = NULL; CHECK(f); if (!c->sparse) { c->codewords = (uint32 *) setup_malloc(f, sizeof(c->codewords[0]) * c->entries); if (!c->codewords) return error(f, VORBIS_outofmem); } else { unsigned int size; if (c->sorted_entries) { c->codeword_lengths = (uint8 *) setup_malloc(f, c->sorted_entries); if (!c->codeword_lengths) return error(f, VORBIS_outofmem); c->codewords = (uint32 *) setup_temp_malloc(f, sizeof(*c->codewords) * c->sorted_entries); if (!c->codewords) return error(f, VORBIS_outofmem); values = (uint32 *) setup_temp_malloc(f, sizeof(*values) * c->sorted_entries); if (!values) return error(f, VORBIS_outofmem); } size = c->entries + (sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries; if (size > f->setup_temp_memory_required) f->setup_temp_memory_required = size; } if (!compute_codewords(c, lengths, c->entries, values)) { if (c->sparse) setup_temp_free(f, values, 0); return error(f, VORBIS_invalid_setup); } if (c->sorted_entries) { // allocate an extra slot for sentinels c->sorted_codewords = (uint32 *) setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries+1)); if (c->sorted_codewords == NULL) return error(f, VORBIS_outofmem); // allocate an extra slot at the front so that c->sorted_values[-1] is defined // so that we can catch that case without an extra if c->sorted_values = ( int *) setup_malloc(f, sizeof(*c->sorted_values ) * (c->sorted_entries+1)); if (c->sorted_values == NULL) return error(f, VORBIS_outofmem); ++c->sorted_values; c->sorted_values[-1] = -1; compute_sorted_huffman(c, lengths, values); } if (c->sparse) { setup_temp_free(f, values, sizeof(*values)*c->sorted_entries); setup_temp_free(f, c->codewords, sizeof(*c->codewords)*c->sorted_entries); setup_temp_free(f, lengths, c->entries); c->codewords = NULL; } compute_accelerated_huffman(c); CHECK(f); c->lookup_type = get_bits(f, 4); if (c->lookup_type > 2) return error(f, VORBIS_invalid_setup); if (c->lookup_type > 0) { uint16 *mults; c->minimum_value = float32_unpack(get_bits(f, 32)); c->delta_value = float32_unpack(get_bits(f, 32)); c->value_bits = get_bits(f, 4)+1; c->sequence_p = get_bits(f,1); if (c->lookup_type == 1) { c->lookup_values = lookup1_values(c->entries, c->dimensions); } else { c->lookup_values = c->entries * c->dimensions; } if (c->lookup_values == 0) return error(f, VORBIS_invalid_setup); mults = (uint16 *) setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values); if (mults == NULL) return error(f, VORBIS_outofmem); for (j=0; j < (int) c->lookup_values; ++j) { int q = get_bits(f, c->value_bits); if (q == EOP) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); } mults[j] = q; } #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { int len, sparse = c->sparse; float last=0; // pre-expand the lookup1-style multiplicands, to avoid a divide in the inner loop if (sparse) { if (c->sorted_entries == 0) goto skip; c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions); } else c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions); if (c->multiplicands == NULL) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); } len = sparse ? c->sorted_entries : c->entries; for (j=0; j < len; ++j) { unsigned int z = sparse ? c->sorted_values[j] : j; unsigned int div=1; for (k=0; k < c->dimensions; ++k) { int off = (z / div) % c->lookup_values; float val = mults[off]; val = mults[off]*c->delta_value + c->minimum_value + last; c->multiplicands[j*c->dimensions + k] = val; if (c->sequence_p) last = val; if (k+1 < c->dimensions) { if (div > UINT_MAX / (unsigned int) c->lookup_values) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); } div *= c->lookup_values; } } } c->lookup_type = 2; } else #endif { float last=0; CHECK(f); c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values); if (c->multiplicands == NULL) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); } for (j=0; j < (int) c->lookup_values; ++j) { float val = mults[j] * c->delta_value + c->minimum_value + last; c->multiplicands[j] = val; if (c->sequence_p) last = val; } } #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK skip:; #endif setup_temp_free(f, mults, sizeof(mults[0])*c->lookup_values); CHECK(f); } CHECK(f); } // time domain transfers (notused) x = get_bits(f, 6) + 1; for (i=0; i < x; ++i) { uint32 z = get_bits(f, 16); if (z != 0) return error(f, VORBIS_invalid_setup); } // Floors f->floor_count = get_bits(f, 6)+1; f->floor_config = (Floor *) setup_malloc(f, f->floor_count * sizeof(*f->floor_config)); if (f->floor_config == NULL) return error(f, VORBIS_outofmem); for (i=0; i < f->floor_count; ++i) { f->floor_types[i] = get_bits(f, 16); if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup); if (f->floor_types[i] == 0) { Floor0 *g = &f->floor_config[i].floor0; g->order = get_bits(f,8); g->rate = get_bits(f,16); g->bark_map_size = get_bits(f,16); g->amplitude_bits = get_bits(f,6); g->amplitude_offset = get_bits(f,8); g->number_of_books = get_bits(f,4) + 1; for (j=0; j < g->number_of_books; ++j) g->book_list[j] = get_bits(f,8); return error(f, VORBIS_feature_not_supported); } else { stbv__floor_ordering p[31*8+2]; Floor1 *g = &f->floor_config[i].floor1; int max_class = -1; g->partitions = get_bits(f, 5); for (j=0; j < g->partitions; ++j) { g->partition_class_list[j] = get_bits(f, 4); if (g->partition_class_list[j] > max_class) max_class = g->partition_class_list[j]; } for (j=0; j <= max_class; ++j) { g->class_dimensions[j] = get_bits(f, 3)+1; g->class_subclasses[j] = get_bits(f, 2); if (g->class_subclasses[j]) { g->class_masterbooks[j] = get_bits(f, 8); if (g->class_masterbooks[j] >= f->codebook_count) return error(f, VORBIS_invalid_setup); } for (k=0; k < 1 << g->class_subclasses[j]; ++k) { g->subclass_books[j][k] = get_bits(f,8)-1; if (g->subclass_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup); } } g->floor1_multiplier = get_bits(f,2)+1; g->rangebits = get_bits(f,4); g->Xlist[0] = 0; g->Xlist[1] = 1 << g->rangebits; g->values = 2; for (j=0; j < g->partitions; ++j) { int c = g->partition_class_list[j]; for (k=0; k < g->class_dimensions[c]; ++k) { g->Xlist[g->values] = get_bits(f, g->rangebits); ++g->values; } } // precompute the sorting for (j=0; j < g->values; ++j) { p[j].x = g->Xlist[j]; p[j].id = j; } qsort(p, g->values, sizeof(p[0]), point_compare); for (j=0; j < g->values; ++j) g->sorted_order[j] = (uint8) p[j].id; // precompute the neighbors for (j=2; j < g->values; ++j) { int low,hi; neighbors(g->Xlist, j, &low,&hi); g->neighbors[j][0] = low; g->neighbors[j][1] = hi; } if (g->values > longest_floorlist) longest_floorlist = g->values; } } // Residue f->residue_count = get_bits(f, 6)+1; f->residue_config = (Residue *) setup_malloc(f, f->residue_count * sizeof(f->residue_config[0])); if (f->residue_config == NULL) return error(f, VORBIS_outofmem); memset(f->residue_config, 0, f->residue_count * sizeof(f->residue_config[0])); for (i=0; i < f->residue_count; ++i) { uint8 residue_cascade[64]; Residue *r = f->residue_config+i; f->residue_types[i] = get_bits(f, 16); if (f->residue_types[i] > 2) return error(f, VORBIS_invalid_setup); r->begin = get_bits(f, 24); r->end = get_bits(f, 24); if (r->end < r->begin) return error(f, VORBIS_invalid_setup); r->part_size = get_bits(f,24)+1; r->classifications = get_bits(f,6)+1; r->classbook = get_bits(f,8); if (r->classbook >= f->codebook_count) return error(f, VORBIS_invalid_setup); for (j=0; j < r->classifications; ++j) { uint8 high_bits=0; uint8 low_bits=get_bits(f,3); if (get_bits(f,1)) high_bits = get_bits(f,5); residue_cascade[j] = high_bits*8 + low_bits; } r->residue_books = (short (*)[8]) setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications); if (r->residue_books == NULL) return error(f, VORBIS_outofmem); for (j=0; j < r->classifications; ++j) { for (k=0; k < 8; ++k) { if (residue_cascade[j] & (1 << k)) { r->residue_books[j][k] = get_bits(f, 8); if (r->residue_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup); } else { r->residue_books[j][k] = -1; } } } // precompute the classifications[] array to avoid inner-loop mod/divide // call it 'classdata' since we already have r->classifications r->classdata = (uint8 **) setup_malloc(f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries); if (!r->classdata) return error(f, VORBIS_outofmem); memset(r->classdata, 0, sizeof(*r->classdata) * f->codebooks[r->classbook].entries); for (j=0; j < f->codebooks[r->classbook].entries; ++j) { int classwords = f->codebooks[r->classbook].dimensions; int temp = j; r->classdata[j] = (uint8 *) setup_malloc(f, sizeof(r->classdata[j][0]) * classwords); if (r->classdata[j] == NULL) return error(f, VORBIS_outofmem); for (k=classwords-1; k >= 0; --k) { r->classdata[j][k] = temp % r->classifications; temp /= r->classifications; } } } f->mapping_count = get_bits(f,6)+1; f->mapping = (Mapping *) setup_malloc(f, f->mapping_count * sizeof(*f->mapping)); if (f->mapping == NULL) return error(f, VORBIS_outofmem); memset(f->mapping, 0, f->mapping_count * sizeof(*f->mapping)); for (i=0; i < f->mapping_count; ++i) { Mapping *m = f->mapping + i; int mapping_type = get_bits(f,16); if (mapping_type != 0) return error(f, VORBIS_invalid_setup); m->chan = (MappingChannel *) setup_malloc(f, f->channels * sizeof(*m->chan)); if (m->chan == NULL) return error(f, VORBIS_outofmem); if (get_bits(f,1)) m->submaps = get_bits(f,4)+1; else m->submaps = 1; if (m->submaps > max_submaps) max_submaps = m->submaps; if (get_bits(f,1)) { m->coupling_steps = get_bits(f,8)+1; for (k=0; k < m->coupling_steps; ++k) { m->chan[k].magnitude = get_bits(f, ilog(f->channels-1)); m->chan[k].angle = get_bits(f, ilog(f->channels-1)); if (m->chan[k].magnitude >= f->channels) return error(f, VORBIS_invalid_setup); if (m->chan[k].angle >= f->channels) return error(f, VORBIS_invalid_setup); if (m->chan[k].magnitude == m->chan[k].angle) return error(f, VORBIS_invalid_setup); } } else m->coupling_steps = 0; // reserved field if (get_bits(f,2)) return error(f, VORBIS_invalid_setup); if (m->submaps > 1) { for (j=0; j < f->channels; ++j) { m->chan[j].mux = get_bits(f, 4); if (m->chan[j].mux >= m->submaps) return error(f, VORBIS_invalid_setup); } } else // @SPECIFICATION: this case is missing from the spec for (j=0; j < f->channels; ++j) m->chan[j].mux = 0; for (j=0; j < m->submaps; ++j) { get_bits(f,8); // discard m->submap_floor[j] = get_bits(f,8); m->submap_residue[j] = get_bits(f,8); if (m->submap_floor[j] >= f->floor_count) return error(f, VORBIS_invalid_setup); if (m->submap_residue[j] >= f->residue_count) return error(f, VORBIS_invalid_setup); } } // Modes f->mode_count = get_bits(f, 6)+1; for (i=0; i < f->mode_count; ++i) { Mode *m = f->mode_config+i; m->blockflag = get_bits(f,1); m->windowtype = get_bits(f,16); m->transformtype = get_bits(f,16); m->mapping = get_bits(f,8); if (m->windowtype != 0) return error(f, VORBIS_invalid_setup); if (m->transformtype != 0) return error(f, VORBIS_invalid_setup); if (m->mapping >= f->mapping_count) return error(f, VORBIS_invalid_setup); } flush_packet(f); f->previous_length = 0; for (i=0; i < f->channels; ++i) { f->channel_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1); f->previous_window[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2); f->finalY[i] = (int16 *) setup_malloc(f, sizeof(int16) * longest_floorlist); if (f->channel_buffers[i] == NULL || f->previous_window[i] == NULL || f->finalY[i] == NULL) return error(f, VORBIS_outofmem); memset(f->channel_buffers[i], 0, sizeof(float) * f->blocksize_1); #ifdef STB_VORBIS_NO_DEFER_FLOOR f->floor_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2); if (f->floor_buffers[i] == NULL) return error(f, VORBIS_outofmem); #endif } if (!init_blocksize(f, 0, f->blocksize_0)) return FALSE; if (!init_blocksize(f, 1, f->blocksize_1)) return FALSE; f->blocksize[0] = f->blocksize_0; f->blocksize[1] = f->blocksize_1; #ifdef STB_VORBIS_DIVIDE_TABLE if (integer_divide_table[1][1]==0) for (i=0; i < DIVTAB_NUMER; ++i) for (j=1; j < DIVTAB_DENOM; ++j) integer_divide_table[i][j] = i / j; #endif // compute how much temporary memory is needed // 1. { uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1); uint32 classify_mem; int i,max_part_read=0; for (i=0; i < f->residue_count; ++i) { Residue *r = f->residue_config + i; unsigned int actual_size = f->blocksize_1 / 2; unsigned int limit_r_begin = r->begin < actual_size ? r->begin : actual_size; unsigned int limit_r_end = r->end < actual_size ? r->end : actual_size; int n_read = limit_r_end - limit_r_begin; int part_read = n_read / r->part_size; if (part_read > max_part_read) max_part_read = part_read; } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(uint8 *)); #else classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int *)); #endif // maximum reasonable partition size is f->blocksize_1 f->temp_memory_required = classify_mem; if (imdct_mem > f->temp_memory_required) f->temp_memory_required = imdct_mem; } f->first_decode = TRUE; if (f->alloc.alloc_buffer) { assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes); // check if there's enough temp memory so we don't error later if (f->setup_offset + sizeof(*f) + f->temp_memory_required > (unsigned) f->temp_offset) return error(f, VORBIS_outofmem); } f->first_audio_page_offset = stb_vorbis_get_file_offset(f); return TRUE; } static void vorbis_deinit(stb_vorbis *p) { int i,j; if (p->residue_config) { for (i=0; i < p->residue_count; ++i) { Residue *r = p->residue_config+i; if (r->classdata) { for (j=0; j < p->codebooks[r->classbook].entries; ++j) setup_free(p, r->classdata[j]); setup_free(p, r->classdata); } setup_free(p, r->residue_books); } } if (p->codebooks) { CHECK(p); for (i=0; i < p->codebook_count; ++i) { Codebook *c = p->codebooks + i; setup_free(p, c->codeword_lengths); setup_free(p, c->multiplicands); setup_free(p, c->codewords); setup_free(p, c->sorted_codewords); // c->sorted_values[-1] is the first entry in the array setup_free(p, c->sorted_values ? c->sorted_values-1 : NULL); } setup_free(p, p->codebooks); } setup_free(p, p->floor_config); setup_free(p, p->residue_config); if (p->mapping) { for (i=0; i < p->mapping_count; ++i) setup_free(p, p->mapping[i].chan); setup_free(p, p->mapping); } CHECK(p); for (i=0; i < p->channels && i < STB_VORBIS_MAX_CHANNELS; ++i) { setup_free(p, p->channel_buffers[i]); setup_free(p, p->previous_window[i]); #ifdef STB_VORBIS_NO_DEFER_FLOOR setup_free(p, p->floor_buffers[i]); #endif setup_free(p, p->finalY[i]); } for (i=0; i < 2; ++i) { setup_free(p, p->A[i]); setup_free(p, p->B[i]); setup_free(p, p->C[i]); setup_free(p, p->window[i]); setup_free(p, p->bit_reverse[i]); } #ifndef STB_VORBIS_NO_STDIO if (p->close_on_free) fclose(p->f); #endif } void stb_vorbis_close(stb_vorbis *p) { if (p == NULL) return; vorbis_deinit(p); setup_free(p,p); } static void vorbis_init(stb_vorbis *p, const stb_vorbis_alloc *z) { memset(p, 0, sizeof(*p)); // NULL out all malloc'd pointers to start if (z) { p->alloc = *z; p->alloc.alloc_buffer_length_in_bytes = (p->alloc.alloc_buffer_length_in_bytes+3) & ~3; p->temp_offset = p->alloc.alloc_buffer_length_in_bytes; } p->eof = 0; p->error = VORBIS__no_error; p->stream = NULL; p->codebooks = NULL; p->page_crc_tests = -1; #ifndef STB_VORBIS_NO_STDIO p->close_on_free = FALSE; p->f = NULL; #endif } int stb_vorbis_get_sample_offset(stb_vorbis *f) { if (f->current_loc_valid) return f->current_loc; else return -1; } stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f) { stb_vorbis_info d; d.channels = f->channels; d.sample_rate = f->sample_rate; d.setup_memory_required = f->setup_memory_required; d.setup_temp_memory_required = f->setup_temp_memory_required; d.temp_memory_required = f->temp_memory_required; d.max_frame_size = f->blocksize_1 >> 1; return d; } int stb_vorbis_get_error(stb_vorbis *f) { int e = f->error; f->error = VORBIS__no_error; return e; } static stb_vorbis * vorbis_alloc(stb_vorbis *f) { stb_vorbis *p = (stb_vorbis *) setup_malloc(f, sizeof(*p)); return p; } #ifndef STB_VORBIS_NO_PUSHDATA_API void stb_vorbis_flush_pushdata(stb_vorbis *f) { f->previous_length = 0; f->page_crc_tests = 0; f->discard_samples_deferred = 0; f->current_loc_valid = FALSE; f->first_decode = FALSE; f->samples_output = 0; f->channel_buffer_start = 0; f->channel_buffer_end = 0; } static int vorbis_search_for_page_pushdata(vorb *f, uint8 *data, int data_len) { int i,n; for (i=0; i < f->page_crc_tests; ++i) f->scan[i].bytes_done = 0; // if we have room for more scans, search for them first, because // they may cause us to stop early if their header is incomplete if (f->page_crc_tests < STB_VORBIS_PUSHDATA_CRC_COUNT) { if (data_len < 4) return 0; data_len -= 3; // need to look for 4-byte sequence, so don't miss // one that straddles a boundary for (i=0; i < data_len; ++i) { if (data[i] == 0x4f) { if (0==memcmp(data+i, ogg_page_header, 4)) { int j,len; uint32 crc; // make sure we have the whole page header if (i+26 >= data_len || i+27+data[i+26] >= data_len) { // only read up to this page start, so hopefully we'll // have the whole page header start next time data_len = i; break; } // ok, we have it all; compute the length of the page len = 27 + data[i+26]; for (j=0; j < data[i+26]; ++j) len += data[i+27+j]; // scan everything up to the embedded crc (which we must 0) crc = 0; for (j=0; j < 22; ++j) crc = crc32_update(crc, data[i+j]); // now process 4 0-bytes for ( ; j < 26; ++j) crc = crc32_update(crc, 0); // len is the total number of bytes we need to scan n = f->page_crc_tests++; f->scan[n].bytes_left = len-j; f->scan[n].crc_so_far = crc; f->scan[n].goal_crc = data[i+22] + (data[i+23] << 8) + (data[i+24]<<16) + (data[i+25]<<24); // if the last frame on a page is continued to the next, then // we can't recover the sample_loc immediately if (data[i+27+data[i+26]-1] == 255) f->scan[n].sample_loc = ~0; else f->scan[n].sample_loc = data[i+6] + (data[i+7] << 8) + (data[i+ 8]<<16) + (data[i+ 9]<<24); f->scan[n].bytes_done = i+j; if (f->page_crc_tests == STB_VORBIS_PUSHDATA_CRC_COUNT) break; // keep going if we still have room for more } } } } for (i=0; i < f->page_crc_tests;) { uint32 crc; int j; int n = f->scan[i].bytes_done; int m = f->scan[i].bytes_left; if (m > data_len - n) m = data_len - n; // m is the bytes to scan in the current chunk crc = f->scan[i].crc_so_far; for (j=0; j < m; ++j) crc = crc32_update(crc, data[n+j]); f->scan[i].bytes_left -= m; f->scan[i].crc_so_far = crc; if (f->scan[i].bytes_left == 0) { // does it match? if (f->scan[i].crc_so_far == f->scan[i].goal_crc) { // Houston, we have page data_len = n+m; // consumption amount is wherever that scan ended f->page_crc_tests = -1; // drop out of page scan mode f->previous_length = 0; // decode-but-don't-output one frame f->next_seg = -1; // start a new page f->current_loc = f->scan[i].sample_loc; // set the current sample location // to the amount we'd have decoded had we decoded this page f->current_loc_valid = f->current_loc != ~0U; return data_len; } // delete entry f->scan[i] = f->scan[--f->page_crc_tests]; } else { ++i; } } return data_len; } // return value: number of bytes we used int stb_vorbis_decode_frame_pushdata( stb_vorbis *f, // the file we're decoding const uint8 *data, int data_len, // the memory available for decoding int *channels, // place to write number of float * buffers float ***output, // place to write float ** array of float * buffers int *samples // place to write number of output samples ) { int i; int len,right,left; if (!IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); if (f->page_crc_tests >= 0) { *samples = 0; return vorbis_search_for_page_pushdata(f, (uint8 *) data, data_len); } f->stream = (uint8 *) data; f->stream_end = (uint8 *) data + data_len; f->error = VORBIS__no_error; // check that we have the entire packet in memory if (!is_whole_packet_present(f, FALSE)) { *samples = 0; return 0; } if (!vorbis_decode_packet(f, &len, &left, &right)) { // save the actual error we encountered enum STBVorbisError error = f->error; if (error == VORBIS_bad_packet_type) { // flush and resynch f->error = VORBIS__no_error; while (get8_packet(f) != EOP) if (f->eof) break; *samples = 0; return (int) (f->stream - data); } if (error == VORBIS_continued_packet_flag_invalid) { if (f->previous_length == 0) { // we may be resynching, in which case it's ok to hit one // of these; just discard the packet f->error = VORBIS__no_error; while (get8_packet(f) != EOP) if (f->eof) break; *samples = 0; return (int) (f->stream - data); } } // if we get an error while parsing, what to do? // well, it DEFINITELY won't work to continue from where we are! stb_vorbis_flush_pushdata(f); // restore the error that actually made us bail f->error = error; *samples = 0; return 1; } // success! len = vorbis_finish_frame(f, len, left, right); for (i=0; i < f->channels; ++i) f->outputs[i] = f->channel_buffers[i] + left; if (channels) *channels = f->channels; *samples = len; *output = f->outputs; return (int) (f->stream - data); } stb_vorbis *stb_vorbis_open_pushdata( const unsigned char *data, int data_len, // the memory available for decoding int *data_used, // only defined if result is not NULL int *error, const stb_vorbis_alloc *alloc) { stb_vorbis *f, p; vorbis_init(&p, alloc); p.stream = (uint8 *) data; p.stream_end = (uint8 *) data + data_len; p.push_mode = TRUE; if (!start_decoder(&p)) { if (p.eof) *error = VORBIS_need_more_data; else *error = p.error; return NULL; } f = vorbis_alloc(&p); if (f) { *f = p; *data_used = (int) (f->stream - data); *error = 0; return f; } else { vorbis_deinit(&p); return NULL; } } #endif // STB_VORBIS_NO_PUSHDATA_API unsigned int stb_vorbis_get_file_offset(stb_vorbis *f) { #ifndef STB_VORBIS_NO_PUSHDATA_API if (f->push_mode) return 0; #endif if (USE_MEMORY(f)) return (unsigned int) (f->stream - f->stream_start); #ifndef STB_VORBIS_NO_STDIO return (unsigned int) (ftell(f->f) - f->f_start); #endif } #ifndef STB_VORBIS_NO_PULLDATA_API // // DATA-PULLING API // static uint32 vorbis_find_page(stb_vorbis *f, uint32 *end, uint32 *last) { for(;;) { int n; if (f->eof) return 0; n = get8(f); if (n == 0x4f) { // page header candidate unsigned int retry_loc = stb_vorbis_get_file_offset(f); int i; // check if we're off the end of a file_section stream if (retry_loc - 25 > f->stream_len) return 0; // check the rest of the header for (i=1; i < 4; ++i) if (get8(f) != ogg_page_header[i]) break; if (f->eof) return 0; if (i == 4) { uint8 header[27]; uint32 i, crc, goal, len; for (i=0; i < 4; ++i) header[i] = ogg_page_header[i]; for (; i < 27; ++i) header[i] = get8(f); if (f->eof) return 0; if (header[4] != 0) goto invalid; goal = header[22] + (header[23] << 8) + (header[24]<<16) + (header[25]<<24); for (i=22; i < 26; ++i) header[i] = 0; crc = 0; for (i=0; i < 27; ++i) crc = crc32_update(crc, header[i]); len = 0; for (i=0; i < header[26]; ++i) { int s = get8(f); crc = crc32_update(crc, s); len += s; } if (len && f->eof) return 0; for (i=0; i < len; ++i) crc = crc32_update(crc, get8(f)); // finished parsing probable page if (crc == goal) { // we could now check that it's either got the last // page flag set, OR it's followed by the capture // pattern, but I guess TECHNICALLY you could have // a file with garbage between each ogg page and recover // from it automatically? So even though that paranoia // might decrease the chance of an invalid decode by // another 2^32, not worth it since it would hose those // invalid-but-useful files? if (end) *end = stb_vorbis_get_file_offset(f); if (last) { if (header[5] & 0x04) *last = 1; else *last = 0; } set_file_offset(f, retry_loc-1); return 1; } } invalid: // not a valid page, so rewind and look for next one set_file_offset(f, retry_loc); } } } #define SAMPLE_unknown 0xffffffff // seeking is implemented with a binary search, which narrows down the range to // 64K, before using a linear search (because finding the synchronization // pattern can be expensive, and the chance we'd find the end page again is // relatively high for small ranges) // // two initial interpolation-style probes are used at the start of the search // to try to bound either side of the binary search sensibly, while still // working in O(log n) time if they fail. static int get_seek_page_info(stb_vorbis *f, ProbedPage *z) { uint8 header[27], lacing[255]; int i,len; // record where the page starts z->page_start = stb_vorbis_get_file_offset(f); // parse the header getn(f, header, 27); if (header[0] != 'O' || header[1] != 'g' || header[2] != 'g' || header[3] != 'S') return 0; getn(f, lacing, header[26]); // determine the length of the payload len = 0; for (i=0; i < header[26]; ++i) len += lacing[i]; // this implies where the page ends z->page_end = z->page_start + 27 + header[26] + len; // read the last-decoded sample out of the data z->last_decoded_sample = header[6] + (header[7] << 8) + (header[8] << 16) + (header[9] << 24); // restore file state to where we were set_file_offset(f, z->page_start); return 1; } // rarely used function to seek back to the preceding page while finding the // start of a packet static int go_to_page_before(stb_vorbis *f, unsigned int limit_offset) { unsigned int previous_safe, end; // now we want to seek back 64K from the limit if (limit_offset >= 65536 && limit_offset-65536 >= f->first_audio_page_offset) previous_safe = limit_offset - 65536; else previous_safe = f->first_audio_page_offset; set_file_offset(f, previous_safe); while (vorbis_find_page(f, &end, NULL)) { if (end >= limit_offset && stb_vorbis_get_file_offset(f) < limit_offset) return 1; set_file_offset(f, end); } return 0; } // implements the search logic for finding a page and starting decoding. if // the function succeeds, current_loc_valid will be true and current_loc will // be less than or equal to the provided sample number (the closer the // better). static int seek_to_sample_coarse(stb_vorbis *f, uint32 sample_number) { ProbedPage left, right, mid; int i, start_seg_with_known_loc, end_pos, page_start; uint32 delta, stream_length, padding; double offset, bytes_per_sample; int probe = 0; // find the last page and validate the target sample stream_length = stb_vorbis_stream_length_in_samples(f); if (stream_length == 0) return error(f, VORBIS_seek_without_length); if (sample_number > stream_length) return error(f, VORBIS_seek_invalid); // this is the maximum difference between the window-center (which is the // actual granule position value), and the right-start (which the spec // indicates should be the granule position (give or take one)). padding = ((f->blocksize_1 - f->blocksize_0) >> 2); if (sample_number < padding) sample_number = 0; else sample_number -= padding; left = f->p_first; while (left.last_decoded_sample == ~0U) { // (untested) the first page does not have a 'last_decoded_sample' set_file_offset(f, left.page_end); if (!get_seek_page_info(f, &left)) goto error; } right = f->p_last; assert(right.last_decoded_sample != ~0U); // starting from the start is handled differently if (sample_number <= left.last_decoded_sample) { if (stb_vorbis_seek_start(f)) return 1; return 0; } while (left.page_end != right.page_start) { assert(left.page_end < right.page_start); // search range in bytes delta = right.page_start - left.page_end; if (delta <= 65536) { // there's only 64K left to search - handle it linearly set_file_offset(f, left.page_end); } else { if (probe < 2) { if (probe == 0) { // first probe (interpolate) double data_bytes = right.page_end - left.page_start; bytes_per_sample = data_bytes / right.last_decoded_sample; offset = left.page_start + bytes_per_sample * (sample_number - left.last_decoded_sample); } else { // second probe (try to bound the other side) double error = ((double) sample_number - mid.last_decoded_sample) * bytes_per_sample; if (error >= 0 && error < 8000) error = 8000; if (error < 0 && error > -8000) error = -8000; offset += error * 2; } // ensure the offset is valid if (offset < left.page_end) offset = left.page_end; if (offset > right.page_start - 65536) offset = right.page_start - 65536; set_file_offset(f, (unsigned int) offset); } else { // binary search for large ranges (offset by 32K to ensure // we don't hit the right page) set_file_offset(f, left.page_end + (delta / 2) - 32768); } if (!vorbis_find_page(f, NULL, NULL)) goto error; } for (;;) { if (!get_seek_page_info(f, &mid)) goto error; if (mid.last_decoded_sample != ~0U) break; // (untested) no frames end on this page set_file_offset(f, mid.page_end); assert(mid.page_start < right.page_start); } // if we've just found the last page again then we're in a tricky file, // and we're close enough. if (mid.page_start == right.page_start) break; if (sample_number < mid.last_decoded_sample) right = mid; else left = mid; ++probe; } // seek back to start of the last packet page_start = left.page_start; set_file_offset(f, page_start); if (!start_page(f)) return error(f, VORBIS_seek_failed); end_pos = f->end_seg_with_known_loc; assert(end_pos >= 0); for (;;) { for (i = end_pos; i > 0; --i) if (f->segments[i-1] != 255) break; start_seg_with_known_loc = i; if (start_seg_with_known_loc > 0 || !(f->page_flag & PAGEFLAG_continued_packet)) break; // (untested) the final packet begins on an earlier page if (!go_to_page_before(f, page_start)) goto error; page_start = stb_vorbis_get_file_offset(f); if (!start_page(f)) goto error; end_pos = f->segment_count - 1; } // prepare to start decoding f->current_loc_valid = FALSE; f->last_seg = FALSE; f->valid_bits = 0; f->packet_bytes = 0; f->bytes_in_seg = 0; f->previous_length = 0; f->next_seg = start_seg_with_known_loc; for (i = 0; i < start_seg_with_known_loc; i++) skip(f, f->segments[i]); // start decoding (optimizable - this frame is generally discarded) if (!vorbis_pump_first_frame(f)) return 0; if (f->current_loc > sample_number) return error(f, VORBIS_seek_failed); return 1; error: // try to restore the file to a valid state stb_vorbis_seek_start(f); return error(f, VORBIS_seek_failed); } // the same as vorbis_decode_initial, but without advancing static int peek_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode) { int bits_read, bytes_read; if (!vorbis_decode_initial(f, p_left_start, p_left_end, p_right_start, p_right_end, mode)) return 0; // either 1 or 2 bytes were read, figure out which so we can rewind bits_read = 1 + ilog(f->mode_count-1); if (f->mode_config[*mode].blockflag) bits_read += 2; bytes_read = (bits_read + 7) / 8; f->bytes_in_seg += bytes_read; f->packet_bytes -= bytes_read; skip(f, -bytes_read); if (f->next_seg == -1) f->next_seg = f->segment_count - 1; else f->next_seg--; f->valid_bits = 0; return 1; } int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number) { uint32 max_frame_samples; if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); // fast page-level search if (!seek_to_sample_coarse(f, sample_number)) return 0; assert(f->current_loc_valid); assert(f->current_loc <= sample_number); // linear search for the relevant packet max_frame_samples = (f->blocksize_1*3 - f->blocksize_0) >> 2; while (f->current_loc < sample_number) { int left_start, left_end, right_start, right_end, mode, frame_samples; if (!peek_decode_initial(f, &left_start, &left_end, &right_start, &right_end, &mode)) return error(f, VORBIS_seek_failed); // calculate the number of samples returned by the next frame frame_samples = right_start - left_start; if (f->current_loc + frame_samples > sample_number) { return 1; // the next frame will contain the sample } else if (f->current_loc + frame_samples + max_frame_samples > sample_number) { // there's a chance the frame after this could contain the sample vorbis_pump_first_frame(f); } else { // this frame is too early to be relevant f->current_loc += frame_samples; f->previous_length = 0; maybe_start_packet(f); flush_packet(f); } } // the next frame will start with the sample assert(f->current_loc == sample_number); return 1; } int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number) { if (!stb_vorbis_seek_frame(f, sample_number)) return 0; if (sample_number != f->current_loc) { int n; uint32 frame_start = f->current_loc; stb_vorbis_get_frame_float(f, &n, NULL); assert(sample_number > frame_start); assert(f->channel_buffer_start + (int) (sample_number-frame_start) <= f->channel_buffer_end); f->channel_buffer_start += (sample_number - frame_start); } return 1; } int stb_vorbis_seek_start(stb_vorbis *f) { if (IS_PUSH_MODE(f)) { return error(f, VORBIS_invalid_api_mixing); } set_file_offset(f, f->first_audio_page_offset); f->previous_length = 0; f->first_decode = TRUE; f->next_seg = -1; return vorbis_pump_first_frame(f); } unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f) { unsigned int restore_offset, previous_safe; unsigned int end, last_page_loc; if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); if (!f->total_samples) { unsigned int last; uint32 lo,hi; char header[6]; // first, store the current decode position so we can restore it restore_offset = stb_vorbis_get_file_offset(f); // now we want to seek back 64K from the end (the last page must // be at most a little less than 64K, but let's allow a little slop) if (f->stream_len >= 65536 && f->stream_len-65536 >= f->first_audio_page_offset) previous_safe = f->stream_len - 65536; else previous_safe = f->first_audio_page_offset; set_file_offset(f, previous_safe); // previous_safe is now our candidate 'earliest known place that seeking // to will lead to the final page' if (!vorbis_find_page(f, &end, &last)) { // if we can't find a page, we're hosed! f->error = VORBIS_cant_find_last_page; f->total_samples = 0xffffffff; goto done; } // check if there are more pages last_page_loc = stb_vorbis_get_file_offset(f); // stop when the last_page flag is set, not when we reach eof; // this allows us to stop short of a 'file_section' end without // explicitly checking the length of the section while (!last) { set_file_offset(f, end); if (!vorbis_find_page(f, &end, &last)) { // the last page we found didn't have the 'last page' flag // set. whoops! break; } previous_safe = last_page_loc+1; last_page_loc = stb_vorbis_get_file_offset(f); } set_file_offset(f, last_page_loc); // parse the header getn(f, (unsigned char *)header, 6); // extract the absolute granule position lo = get32(f); hi = get32(f); if (lo == 0xffffffff && hi == 0xffffffff) { f->error = VORBIS_cant_find_last_page; f->total_samples = SAMPLE_unknown; goto done; } if (hi) lo = 0xfffffffe; // saturate f->total_samples = lo; f->p_last.page_start = last_page_loc; f->p_last.page_end = end; f->p_last.last_decoded_sample = lo; done: set_file_offset(f, restore_offset); } return f->total_samples == SAMPLE_unknown ? 0 : f->total_samples; } float stb_vorbis_stream_length_in_seconds(stb_vorbis *f) { return stb_vorbis_stream_length_in_samples(f) / (float) f->sample_rate; } int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output) { int len, right,left,i; if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); if (!vorbis_decode_packet(f, &len, &left, &right)) { f->channel_buffer_start = f->channel_buffer_end = 0; return 0; } len = vorbis_finish_frame(f, len, left, right); for (i=0; i < f->channels; ++i) f->outputs[i] = f->channel_buffers[i] + left; f->channel_buffer_start = left; f->channel_buffer_end = left+len; if (channels) *channels = f->channels; if (output) *output = f->outputs; return len; } #ifndef STB_VORBIS_NO_STDIO stb_vorbis * stb_vorbis_open_file_section(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc, unsigned int length) { stb_vorbis *f, p; vorbis_init(&p, alloc); p.f = file; p.f_start = (uint32) ftell(file); p.stream_len = length; p.close_on_free = close_on_free; if (start_decoder(&p)) { f = vorbis_alloc(&p); if (f) { *f = p; vorbis_pump_first_frame(f); return f; } } if (error) *error = p.error; vorbis_deinit(&p); return NULL; } stb_vorbis * stb_vorbis_open_file(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc) { unsigned int len, start; start = (unsigned int) ftell(file); fseek(file, 0, SEEK_END); len = (unsigned int) (ftell(file) - start); fseek(file, start, SEEK_SET); return stb_vorbis_open_file_section(file, close_on_free, error, alloc, len); } stb_vorbis * stb_vorbis_open_filename(const char *filename, int *error, const stb_vorbis_alloc *alloc) { FILE *f; #if defined(_WIN32) && defined(__STDC_WANT_SECURE_LIB__) if (0 != fopen_s(&f, filename, "rb")) f = NULL; #else f = fopen(filename, "rb"); #endif if (f) return stb_vorbis_open_file(f, TRUE, error, alloc); if (error) *error = VORBIS_file_open_failure; return NULL; } #endif // STB_VORBIS_NO_STDIO stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, int *error, const stb_vorbis_alloc *alloc) { stb_vorbis *f, p; if (data == NULL) return NULL; vorbis_init(&p, alloc); p.stream = (uint8 *) data; p.stream_end = (uint8 *) data + len; p.stream_start = (uint8 *) p.stream; p.stream_len = len; p.push_mode = FALSE; if (start_decoder(&p)) { f = vorbis_alloc(&p); if (f) { *f = p; vorbis_pump_first_frame(f); if (error) *error = VORBIS__no_error; return f; } } if (error) *error = p.error; vorbis_deinit(&p); return NULL; } #ifndef STB_VORBIS_NO_INTEGER_CONVERSION #define PLAYBACK_MONO 1 #define PLAYBACK_LEFT 2 #define PLAYBACK_RIGHT 4 #define L (PLAYBACK_LEFT | PLAYBACK_MONO) #define C (PLAYBACK_LEFT | PLAYBACK_RIGHT | PLAYBACK_MONO) #define R (PLAYBACK_RIGHT | PLAYBACK_MONO) static int8 channel_position[7][6] = { { 0 }, { C }, { L, R }, { L, C, R }, { L, R, L, R }, { L, C, R, L, R }, { L, C, R, L, R, C }, }; #ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT typedef union { float f; int i; } float_conv; typedef char stb_vorbis_float_size_test[sizeof(float)==4 && sizeof(int) == 4]; #define FASTDEF(x) float_conv x // add (1<<23) to convert to int, then divide by 2^SHIFT, then add 0.5/2^SHIFT to round #define MAGIC(SHIFT) (1.5f * (1 << (23-SHIFT)) + 0.5f/(1 << SHIFT)) #define ADDEND(SHIFT) (((150-SHIFT) << 23) + (1 << 22)) #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) (temp.f = (x) + MAGIC(s), temp.i - ADDEND(s)) #define check_endianness() #else #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) ((int) ((x) * (1 << (s)))) #define check_endianness() #define FASTDEF(x) #endif static void copy_samples(short *dest, float *src, int len) { int i; check_endianness(); for (i=0; i < len; ++i) { FASTDEF(temp); int v = FAST_SCALED_FLOAT_TO_INT(temp, src[i],15); if ((unsigned int) (v + 32768) > 65535) v = v < 0 ? -32768 : 32767; dest[i] = v; } } static void compute_samples(int mask, short *output, int num_c, float **data, int d_offset, int len) { #define BUFFER_SIZE 32 float buffer[BUFFER_SIZE]; int i,j,o,n = BUFFER_SIZE; check_endianness(); for (o = 0; o < len; o += BUFFER_SIZE) { memset(buffer, 0, sizeof(buffer)); if (o + n > len) n = len - o; for (j=0; j < num_c; ++j) { if (channel_position[num_c][j] & mask) { for (i=0; i < n; ++i) buffer[i] += data[j][d_offset+o+i]; } } for (i=0; i < n; ++i) { FASTDEF(temp); int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15); if ((unsigned int) (v + 32768) > 65535) v = v < 0 ? -32768 : 32767; output[o+i] = v; } } } static void compute_stereo_samples(short *output, int num_c, float **data, int d_offset, int len) { #define BUFFER_SIZE 32 float buffer[BUFFER_SIZE]; int i,j,o,n = BUFFER_SIZE >> 1; // o is the offset in the source data check_endianness(); for (o = 0; o < len; o += BUFFER_SIZE >> 1) { // o2 is the offset in the output data int o2 = o << 1; memset(buffer, 0, sizeof(buffer)); if (o + n > len) n = len - o; for (j=0; j < num_c; ++j) { int m = channel_position[num_c][j] & (PLAYBACK_LEFT | PLAYBACK_RIGHT); if (m == (PLAYBACK_LEFT | PLAYBACK_RIGHT)) { for (i=0; i < n; ++i) { buffer[i*2+0] += data[j][d_offset+o+i]; buffer[i*2+1] += data[j][d_offset+o+i]; } } else if (m == PLAYBACK_LEFT) { for (i=0; i < n; ++i) { buffer[i*2+0] += data[j][d_offset+o+i]; } } else if (m == PLAYBACK_RIGHT) { for (i=0; i < n; ++i) { buffer[i*2+1] += data[j][d_offset+o+i]; } } } for (i=0; i < (n<<1); ++i) { FASTDEF(temp); int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15); if ((unsigned int) (v + 32768) > 65535) v = v < 0 ? -32768 : 32767; output[o2+i] = v; } } } static void convert_samples_short(int buf_c, short **buffer, int b_offset, int data_c, float **data, int d_offset, int samples) { int i; if (buf_c != data_c && buf_c <= 2 && data_c <= 6) { static int channel_selector[3][2] = { {0}, {PLAYBACK_MONO}, {PLAYBACK_LEFT, PLAYBACK_RIGHT} }; for (i=0; i < buf_c; ++i) compute_samples(channel_selector[buf_c][i], buffer[i]+b_offset, data_c, data, d_offset, samples); } else { int limit = buf_c < data_c ? buf_c : data_c; for (i=0; i < limit; ++i) copy_samples(buffer[i]+b_offset, data[i]+d_offset, samples); for ( ; i < buf_c; ++i) memset(buffer[i]+b_offset, 0, sizeof(short) * samples); } } int stb_vorbis_get_frame_short(stb_vorbis *f, int num_c, short **buffer, int num_samples) { float **output; int len = stb_vorbis_get_frame_float(f, NULL, &output); if (len > num_samples) len = num_samples; if (len) convert_samples_short(num_c, buffer, 0, f->channels, output, 0, len); return len; } static void convert_channels_short_interleaved(int buf_c, short *buffer, int data_c, float **data, int d_offset, int len) { int i; check_endianness(); if (buf_c != data_c && buf_c <= 2 && data_c <= 6) { assert(buf_c == 2); for (i=0; i < buf_c; ++i) compute_stereo_samples(buffer, data_c, data, d_offset, len); } else { int limit = buf_c < data_c ? buf_c : data_c; int j; for (j=0; j < len; ++j) { for (i=0; i < limit; ++i) { FASTDEF(temp); float f = data[i][d_offset+j]; int v = FAST_SCALED_FLOAT_TO_INT(temp, f,15);//data[i][d_offset+j],15); if ((unsigned int) (v + 32768) > 65535) v = v < 0 ? -32768 : 32767; *buffer++ = v; } for ( ; i < buf_c; ++i) *buffer++ = 0; } } } int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts) { float **output; int len; if (num_c == 1) return stb_vorbis_get_frame_short(f,num_c,&buffer, num_shorts); len = stb_vorbis_get_frame_float(f, NULL, &output); if (len) { if (len*num_c > num_shorts) len = num_shorts / num_c; convert_channels_short_interleaved(num_c, buffer, f->channels, output, 0, len); } return len; } int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts) { float **outputs; int len = num_shorts / channels; int n=0; int z = f->channels; if (z > channels) z = channels; while (n < len) { int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= len) k = len - n; if (k) convert_channels_short_interleaved(channels, buffer, f->channels, f->channel_buffers, f->channel_buffer_start, k); buffer += k*channels; n += k; f->channel_buffer_start += k; if (n == len) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int len) { float **outputs; int n=0; int z = f->channels; if (z > channels) z = channels; while (n < len) { int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= len) k = len - n; if (k) convert_samples_short(channels, buffer, n, f->channels, f->channel_buffers, f->channel_buffer_start, k); n += k; f->channel_buffer_start += k; if (n == len) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } #ifndef STB_VORBIS_NO_STDIO int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output) { int data_len, offset, total, limit, error; short *data; stb_vorbis *v = stb_vorbis_open_filename(filename, &error, NULL); if (v == NULL) return -1; limit = v->channels * 4096; *channels = v->channels; if (sample_rate) *sample_rate = v->sample_rate; offset = data_len = 0; total = limit; data = (short *) malloc(total * sizeof(*data)); if (data == NULL) { stb_vorbis_close(v); return -2; } for (;;) { int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset); if (n == 0) break; data_len += n; offset += n * v->channels; if (offset + limit > total) { short *data2; total *= 2; data2 = (short *) realloc(data, total * sizeof(*data)); if (data2 == NULL) { free(data); stb_vorbis_close(v); return -2; } data = data2; } } *output = data; stb_vorbis_close(v); return data_len; } #endif // NO_STDIO int stb_vorbis_decode_memory(const uint8 *mem, int len, int *channels, int *sample_rate, short **output) { int data_len, offset, total, limit, error; short *data; stb_vorbis *v = stb_vorbis_open_memory(mem, len, &error, NULL); if (v == NULL) return -1; limit = v->channels * 4096; *channels = v->channels; if (sample_rate) *sample_rate = v->sample_rate; offset = data_len = 0; total = limit; data = (short *) malloc(total * sizeof(*data)); if (data == NULL) { stb_vorbis_close(v); return -2; } for (;;) { int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset); if (n == 0) break; data_len += n; offset += n * v->channels; if (offset + limit > total) { short *data2; total *= 2; data2 = (short *) realloc(data, total * sizeof(*data)); if (data2 == NULL) { free(data); stb_vorbis_close(v); return -2; } data = data2; } } *output = data; stb_vorbis_close(v); return data_len; } #endif // STB_VORBIS_NO_INTEGER_CONVERSION int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats) { float **outputs; int len = num_floats / channels; int n=0; int z = f->channels; if (z > channels) z = channels; while (n < len) { int i,j; int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= len) k = len - n; for (j=0; j < k; ++j) { for (i=0; i < z; ++i) *buffer++ = f->channel_buffers[i][f->channel_buffer_start+j]; for ( ; i < channels; ++i) *buffer++ = 0; } n += k; f->channel_buffer_start += k; if (n == len) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples) { float **outputs; int n=0; int z = f->channels; if (z > channels) z = channels; while (n < num_samples) { int i; int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= num_samples) k = num_samples - n; if (k) { for (i=0; i < z; ++i) memcpy(buffer[i]+n, f->channel_buffers[i]+f->channel_buffer_start, sizeof(float)*k); for ( ; i < channels; ++i) memset(buffer[i]+n, 0, sizeof(float) * k); } n += k; f->channel_buffer_start += k; if (n == num_samples) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } #endif // STB_VORBIS_NO_PULLDATA_API /* Version history 1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files 1.11 - 2017-07-23 - fix MinGW compilation 1.10 - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory 1.09 - 2016-04-04 - back out 'avoid discarding last frame' fix from previous version 1.08 - 2016-04-02 - fixed multiple warnings; fix setup memory leaks; avoid discarding last frame of audio data 1.07 - 2015-01-16 - fixed some warnings, fix mingw, const-correct API some more crash fixes when out of memory or with corrupt files 1.06 - 2015-08-31 - full, correct support for seeking API (Dougall Johnson) some crash fixes when out of memory or with corrupt files 1.05 - 2015-04-19 - don't define __forceinline if it's redundant 1.04 - 2014-08-27 - fix missing const-correct case in API 1.03 - 2014-08-07 - Warning fixes 1.02 - 2014-07-09 - Declare qsort compare function _cdecl on windows 1.01 - 2014-06-18 - fix stb_vorbis_get_samples_float 1.0 - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in multichannel (API change) report sample rate for decode-full-file funcs 0.99996 - bracket #include <malloc.h> for macintosh compilation by Laurent Gomila 0.99995 - use union instead of pointer-cast for fast-float-to-int to avoid alias-optimization problem 0.99994 - change fast-float-to-int to work in single-precision FPU mode, remove endian-dependence 0.99993 - remove assert that fired on legal files with empty tables 0.99992 - rewind-to-start 0.99991 - bugfix to stb_vorbis_get_samples_short by Bernhard Wodo 0.9999 - (should have been 0.99990) fix no-CRT support, compiling as C++ 0.9998 - add a full-decode function with a memory source 0.9997 - fix a bug in the read-from-FILE case in 0.9996 addition 0.9996 - query length of vorbis stream in samples/seconds 0.9995 - bugfix to another optimization that only happened in certain files 0.9994 - bugfix to one of the optimizations that caused significant (but inaudible?) errors 0.9993 - performance improvements; runs in 99% to 104% of time of reference implementation 0.9992 - performance improvement of IMDCT; now performs close to reference implementation 0.9991 - performance improvement of IMDCT 0.999 - (should have been 0.9990) performance improvement of IMDCT 0.998 - no-CRT support from Casey Muratori 0.997 - bugfixes for bugs found by Terje Mathisen 0.996 - bugfix: fast-huffman decode initialized incorrectly for sparse codebooks; fixing gives 10% speedup - found by Terje Mathisen 0.995 - bugfix: fix to 'effective' overrun detection - found by Terje Mathisen 0.994 - bugfix: garbage decode on final VQ symbol of a non-multiple - found by Terje Mathisen 0.993 - bugfix: pushdata API required 1 extra byte for empty page (failed to consume final page if empty) - found by Terje Mathisen 0.992 - fixes for MinGW warning 0.991 - turn fast-float-conversion on by default 0.990 - fix push-mode seek recovery if you seek into the headers 0.98b - fix to bad release of 0.98 0.98 - fix push-mode seek recovery; robustify float-to-int and support non-fast mode 0.97 - builds under c++ (typecasting, don't use 'class' keyword) 0.96 - somehow MY 0.95 was right, but the web one was wrong, so here's my 0.95 rereleased as 0.96, fixes a typo in the clamping code 0.95 - clamping code for 16-bit functions 0.94 - not publically released 0.93 - fixed all-zero-floor case (was decoding garbage) 0.92 - fixed a memory leak 0.91 - conditional compiles to omit parts of the API and the infrastructure to support them: STB_VORBIS_NO_PULLDATA_API, STB_VORBIS_NO_PUSHDATA_API, STB_VORBIS_NO_STDIO, STB_VORBIS_NO_INTEGER_CONVERSION 0.90 - first public release */ #endif // STB_VORBIS_HEADER_ONLY /* ------------------------------------------------------------------------------ This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------ ALTERNATIVE A - MIT License Copyright (c) 2017 Sean Barrett Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ ALTERNATIVE B - Public Domain (www.unlicense.org) This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ */
null
// Ogg Vorbis audio decoder - v1.16 - public domain // http://nothings.org/stb_vorbis/ // // Original version written by Sean Barrett in 2007. // // Originally sponsored by RAD Game Tools. Seeking implementation // sponsored by Phillip Bennefall, Marc Andersen, Aaron Baker, // Elias Software, Aras Pranckevicius, and Sean Barrett. // // LICENSE // // See end of file for license information. // // Limitations: // // - floor 0 not supported (used in old ogg vorbis files pre-2004) // - lossless sample-truncation at beginning ignored // - cannot concatenate multiple vorbis streams // - sample positions are 32-bit, limiting seekable 192Khz // files to around 6 hours (Ogg supports 64-bit) // // Feature contributors: // Dougall Johnson (sample-exact seeking) // // Bugfix/warning contributors: // Terje Mathisen Niklas Frykholm Andy Hill // Casey Muratori John Bolton Gargaj // Laurent Gomila Marc LeBlanc Ronny Chevalier // Bernhard Wodo Evan Balster alxprd@github // Tom Beaumont Ingo Leitgeb Nicolas Guillemot // Phillip Bennefall Rohit Thiago Goulart // manxorist@github saga musix github:infatum // Timur Gagiev // // Partial history: // 1.17 - 2019-07-08 - fix CVE-2019-13217..CVE-2019-13223 (by ForAllSecure) // 1.16 - 2019-03-04 - fix warnings // 1.15 - 2019-02-07 - explicit failure if Ogg Skeleton data is found // 1.14 - 2018-02-11 - delete bogus dealloca usage // 1.13 - 2018-01-29 - fix truncation of last frame (hopefully) // 1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files // 1.11 - 2017-07-23 - fix MinGW compilation // 1.10 - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory // 1.09 - 2016-04-04 - back out 'truncation of last frame' fix from previous version // 1.08 - 2016-04-02 - warnings; setup memory leaks; truncation of last frame // 1.07 - 2015-01-16 - fixes for crashes on invalid files; warning fixes; const // 1.06 - 2015-08-31 - full, correct support for seeking API (Dougall Johnson) // some crash fixes when out of memory or with corrupt files // fix some inappropriately signed shifts // 1.05 - 2015-04-19 - don't define __forceinline if it's redundant // 1.04 - 2014-08-27 - fix missing const-correct case in API // 1.03 - 2014-08-07 - warning fixes // 1.02 - 2014-07-09 - declare qsort comparison as explicitly _cdecl in Windows // 1.01 - 2014-06-18 - fix stb_vorbis_get_samples_float (interleaved was correct) // 1.0 - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in >2-channel; // (API change) report sample rate for decode-full-file funcs // // See end of file for full version history. ////////////////////////////////////////////////////////////////////////////// // // HEADER BEGINS HERE // #ifndef STB_VORBIS_INCLUDE_STB_VORBIS_H #define STB_VORBIS_INCLUDE_STB_VORBIS_H #if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO) #define STB_VORBIS_NO_STDIO 1 #endif #ifndef STB_VORBIS_NO_STDIO #include <stdio.h> #endif #ifdef __cplusplus extern "C" { #endif /////////// THREAD SAFETY // Individual stb_vorbis* handles are not thread-safe; you cannot decode from // them from multiple threads at the same time. However, you can have multiple // stb_vorbis* handles and decode from them independently in multiple thrads. /////////// MEMORY ALLOCATION // normally stb_vorbis uses malloc() to allocate memory at startup, // and alloca() to allocate temporary memory during a frame on the // stack. (Memory consumption will depend on the amount of setup // data in the file and how you set the compile flags for speed // vs. size. In my test files the maximal-size usage is ~150KB.) // // You can modify the wrapper functions in the source (setup_malloc, // setup_temp_malloc, temp_malloc) to change this behavior, or you // can use a simpler allocation model: you pass in a buffer from // which stb_vorbis will allocate _all_ its memory (including the // temp memory). "open" may fail with a VORBIS_outofmem if you // do not pass in enough data; there is no way to determine how // much you do need except to succeed (at which point you can // query get_info to find the exact amount required. yes I know // this is lame). // // If you pass in a non-NULL buffer of the type below, allocation // will occur from it as described above. Otherwise just pass NULL // to use malloc()/alloca() typedef struct { char *alloc_buffer; int alloc_buffer_length_in_bytes; } stb_vorbis_alloc; /////////// FUNCTIONS USEABLE WITH ALL INPUT MODES typedef struct stb_vorbis stb_vorbis; typedef struct { unsigned int sample_rate; int channels; unsigned int setup_memory_required; unsigned int setup_temp_memory_required; unsigned int temp_memory_required; int max_frame_size; } stb_vorbis_info; // get general information about the file extern stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f); // get the last error detected (clears it, too) extern int stb_vorbis_get_error(stb_vorbis *f); // close an ogg vorbis file and free all memory in use extern void stb_vorbis_close(stb_vorbis *f); // this function returns the offset (in samples) from the beginning of the // file that will be returned by the next decode, if it is known, or -1 // otherwise. after a flush_pushdata() call, this may take a while before // it becomes valid again. // NOT WORKING YET after a seek with PULLDATA API extern int stb_vorbis_get_sample_offset(stb_vorbis *f); // returns the current seek point within the file, or offset from the beginning // of the memory buffer. In pushdata mode it returns 0. extern unsigned int stb_vorbis_get_file_offset(stb_vorbis *f); /////////// PUSHDATA API #ifndef STB_VORBIS_NO_PUSHDATA_API // this API allows you to get blocks of data from any source and hand // them to stb_vorbis. you have to buffer them; stb_vorbis will tell // you how much it used, and you have to give it the rest next time; // and stb_vorbis may not have enough data to work with and you will // need to give it the same data again PLUS more. Note that the Vorbis // specification does not bound the size of an individual frame. extern stb_vorbis *stb_vorbis_open_pushdata( const unsigned char * datablock, int datablock_length_in_bytes, int *datablock_memory_consumed_in_bytes, int *error, const stb_vorbis_alloc *alloc_buffer); // create a vorbis decoder by passing in the initial data block containing // the ogg&vorbis headers (you don't need to do parse them, just provide // the first N bytes of the file--you're told if it's not enough, see below) // on success, returns an stb_vorbis *, does not set error, returns the amount of // data parsed/consumed on this call in *datablock_memory_consumed_in_bytes; // on failure, returns NULL on error and sets *error, does not change *datablock_memory_consumed // if returns NULL and *error is VORBIS_need_more_data, then the input block was // incomplete and you need to pass in a larger block from the start of the file extern int stb_vorbis_decode_frame_pushdata( stb_vorbis *f, const unsigned char *datablock, int datablock_length_in_bytes, int *channels, // place to write number of float * buffers float ***output, // place to write float ** array of float * buffers int *samples // place to write number of output samples ); // decode a frame of audio sample data if possible from the passed-in data block // // return value: number of bytes we used from datablock // // possible cases: // 0 bytes used, 0 samples output (need more data) // N bytes used, 0 samples output (resynching the stream, keep going) // N bytes used, M samples output (one frame of data) // note that after opening a file, you will ALWAYS get one N-bytes,0-sample // frame, because Vorbis always "discards" the first frame. // // Note that on resynch, stb_vorbis will rarely consume all of the buffer, // instead only datablock_length_in_bytes-3 or less. This is because it wants // to avoid missing parts of a page header if they cross a datablock boundary, // without writing state-machiney code to record a partial detection. // // The number of channels returned are stored in *channels (which can be // NULL--it is always the same as the number of channels reported by // get_info). *output will contain an array of float* buffers, one per // channel. In other words, (*output)[0][0] contains the first sample from // the first channel, and (*output)[1][0] contains the first sample from // the second channel. extern void stb_vorbis_flush_pushdata(stb_vorbis *f); // inform stb_vorbis that your next datablock will not be contiguous with // previous ones (e.g. you've seeked in the data); future attempts to decode // frames will cause stb_vorbis to resynchronize (as noted above), and // once it sees a valid Ogg page (typically 4-8KB, as large as 64KB), it // will begin decoding the _next_ frame. // // if you want to seek using pushdata, you need to seek in your file, then // call stb_vorbis_flush_pushdata(), then start calling decoding, then once // decoding is returning you data, call stb_vorbis_get_sample_offset, and // if you don't like the result, seek your file again and repeat. #endif ////////// PULLING INPUT API #ifndef STB_VORBIS_NO_PULLDATA_API // This API assumes stb_vorbis is allowed to pull data from a source-- // either a block of memory containing the _entire_ vorbis stream, or a // FILE * that you or it create, or possibly some other reading mechanism // if you go modify the source to replace the FILE * case with some kind // of callback to your code. (But if you don't support seeking, you may // just want to go ahead and use pushdata.) #if !defined(STB_VORBIS_NO_STDIO) && !defined(STB_VORBIS_NO_INTEGER_CONVERSION) extern int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output); #endif #if !defined(STB_VORBIS_NO_INTEGER_CONVERSION) extern int stb_vorbis_decode_memory(const unsigned char *mem, int len, int *channels, int *sample_rate, short **output); #endif // decode an entire file and output the data interleaved into a malloc()ed // buffer stored in *output. The return value is the number of samples // decoded, or -1 if the file could not be opened or was not an ogg vorbis file. // When you're done with it, just free() the pointer returned in *output. extern stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, int *error, const stb_vorbis_alloc *alloc_buffer); // create an ogg vorbis decoder from an ogg vorbis stream in memory (note // this must be the entire stream!). on failure, returns NULL and sets *error #ifndef STB_VORBIS_NO_STDIO extern stb_vorbis * stb_vorbis_open_filename(const char *filename, int *error, const stb_vorbis_alloc *alloc_buffer); // create an ogg vorbis decoder from a filename via fopen(). on failure, // returns NULL and sets *error (possibly to VORBIS_file_open_failure). extern stb_vorbis * stb_vorbis_open_file(FILE *f, int close_handle_on_close, int *error, const stb_vorbis_alloc *alloc_buffer); // create an ogg vorbis decoder from an open FILE *, looking for a stream at // the _current_ seek point (ftell). on failure, returns NULL and sets *error. // note that stb_vorbis must "own" this stream; if you seek it in between // calls to stb_vorbis, it will become confused. Moreover, if you attempt to // perform stb_vorbis_seek_*() operations on this file, it will assume it // owns the _entire_ rest of the file after the start point. Use the next // function, stb_vorbis_open_file_section(), to limit it. extern stb_vorbis * stb_vorbis_open_file_section(FILE *f, int close_handle_on_close, int *error, const stb_vorbis_alloc *alloc_buffer, unsigned int len); // create an ogg vorbis decoder from an open FILE *, looking for a stream at // the _current_ seek point (ftell); the stream will be of length 'len' bytes. // on failure, returns NULL and sets *error. note that stb_vorbis must "own" // this stream; if you seek it in between calls to stb_vorbis, it will become // confused. #endif extern int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number); extern int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number); // these functions seek in the Vorbis file to (approximately) 'sample_number'. // after calling seek_frame(), the next call to get_frame_*() will include // the specified sample. after calling stb_vorbis_seek(), the next call to // stb_vorbis_get_samples_* will start with the specified sample. If you // do not need to seek to EXACTLY the target sample when using get_samples_*, // you can also use seek_frame(). extern int stb_vorbis_seek_start(stb_vorbis *f); // this function is equivalent to stb_vorbis_seek(f,0) extern unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f); extern float stb_vorbis_stream_length_in_seconds(stb_vorbis *f); // these functions return the total length of the vorbis stream extern int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output); // decode the next frame and return the number of samples. the number of // channels returned are stored in *channels (which can be NULL--it is always // the same as the number of channels reported by get_info). *output will // contain an array of float* buffers, one per channel. These outputs will // be overwritten on the next call to stb_vorbis_get_frame_*. // // You generally should not intermix calls to stb_vorbis_get_frame_*() // and stb_vorbis_get_samples_*(), since the latter calls the former. #ifndef STB_VORBIS_NO_INTEGER_CONVERSION extern int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts); extern int stb_vorbis_get_frame_short (stb_vorbis *f, int num_c, short **buffer, int num_samples); #endif // decode the next frame and return the number of *samples* per channel. // Note that for interleaved data, you pass in the number of shorts (the // size of your array), but the return value is the number of samples per // channel, not the total number of samples. // // The data is coerced to the number of channels you request according to the // channel coercion rules (see below). You must pass in the size of your // buffer(s) so that stb_vorbis will not overwrite the end of the buffer. // The maximum buffer size needed can be gotten from get_info(); however, // the Vorbis I specification implies an absolute maximum of 4096 samples // per channel. // Channel coercion rules: // Let M be the number of channels requested, and N the number of channels present, // and Cn be the nth channel; let stereo L be the sum of all L and center channels, // and stereo R be the sum of all R and center channels (channel assignment from the // vorbis spec). // M N output // 1 k sum(Ck) for all k // 2 * stereo L, stereo R // k l k > l, the first l channels, then 0s // k l k <= l, the first k channels // Note that this is not _good_ surround etc. mixing at all! It's just so // you get something useful. extern int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats); extern int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples); // gets num_samples samples, not necessarily on a frame boundary--this requires // buffering so you have to supply the buffers. DOES NOT APPLY THE COERCION RULES. // Returns the number of samples stored per channel; it may be less than requested // at the end of the file. If there are no more samples in the file, returns 0. #ifndef STB_VORBIS_NO_INTEGER_CONVERSION extern int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts); extern int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int num_samples); #endif // gets num_samples samples, not necessarily on a frame boundary--this requires // buffering so you have to supply the buffers. Applies the coercion rules above // to produce 'channels' channels. Returns the number of samples stored per channel; // it may be less than requested at the end of the file. If there are no more // samples in the file, returns 0. #endif //////// ERROR CODES enum STBVorbisError { VORBIS__no_error, VORBIS_need_more_data=1, // not a real error VORBIS_invalid_api_mixing, // can't mix API modes VORBIS_outofmem, // not enough memory VORBIS_feature_not_supported, // uses floor 0 VORBIS_too_many_channels, // STB_VORBIS_MAX_CHANNELS is too small VORBIS_file_open_failure, // fopen() failed VORBIS_seek_without_length, // can't seek in unknown-length file VORBIS_unexpected_eof=10, // file is truncated? VORBIS_seek_invalid, // seek past EOF // decoding errors (corrupt/invalid stream) -- you probably // don't care about the exact details of these // vorbis errors: VORBIS_invalid_setup=20, VORBIS_invalid_stream, // ogg errors: VORBIS_missing_capture_pattern=30, VORBIS_invalid_stream_structure_version, VORBIS_continued_packet_flag_invalid, VORBIS_incorrect_stream_serial_number, VORBIS_invalid_first_page, VORBIS_bad_packet_type, VORBIS_cant_find_last_page, VORBIS_seek_failed, VORBIS_ogg_skeleton_not_supported }; #ifdef __cplusplus } #endif #endif // STB_VORBIS_INCLUDE_STB_VORBIS_H // // HEADER ENDS HERE // ////////////////////////////////////////////////////////////////////////////// #ifndef STB_VORBIS_HEADER_ONLY // global configuration settings (e.g. set these in the project/makefile), // or just set them in this file at the top (although ideally the first few // should be visible when the header file is compiled too, although it's not // crucial) // STB_VORBIS_NO_PUSHDATA_API // does not compile the code for the various stb_vorbis_*_pushdata() // functions // #define STB_VORBIS_NO_PUSHDATA_API // STB_VORBIS_NO_PULLDATA_API // does not compile the code for the non-pushdata APIs // #define STB_VORBIS_NO_PULLDATA_API // STB_VORBIS_NO_STDIO // does not compile the code for the APIs that use FILE *s internally // or externally (implied by STB_VORBIS_NO_PULLDATA_API) // #define STB_VORBIS_NO_STDIO // STB_VORBIS_NO_INTEGER_CONVERSION // does not compile the code for converting audio sample data from // float to integer (implied by STB_VORBIS_NO_PULLDATA_API) // #define STB_VORBIS_NO_INTEGER_CONVERSION // STB_VORBIS_NO_FAST_SCALED_FLOAT // does not use a fast float-to-int trick to accelerate float-to-int on // most platforms which requires endianness be defined correctly. //#define STB_VORBIS_NO_FAST_SCALED_FLOAT // STB_VORBIS_MAX_CHANNELS [number] // globally define this to the maximum number of channels you need. // The spec does not put a restriction on channels except that // the count is stored in a byte, so 255 is the hard limit. // Reducing this saves about 16 bytes per value, so using 16 saves // (255-16)*16 or around 4KB. Plus anything other memory usage // I forgot to account for. Can probably go as low as 8 (7.1 audio), // 6 (5.1 audio), or 2 (stereo only). #ifndef STB_VORBIS_MAX_CHANNELS #define STB_VORBIS_MAX_CHANNELS 16 // enough for anyone? #endif // STB_VORBIS_PUSHDATA_CRC_COUNT [number] // after a flush_pushdata(), stb_vorbis begins scanning for the // next valid page, without backtracking. when it finds something // that looks like a page, it streams through it and verifies its // CRC32. Should that validation fail, it keeps scanning. But it's // possible that _while_ streaming through to check the CRC32 of // one candidate page, it sees another candidate page. This #define // determines how many "overlapping" candidate pages it can search // at once. Note that "real" pages are typically ~4KB to ~8KB, whereas // garbage pages could be as big as 64KB, but probably average ~16KB. // So don't hose ourselves by scanning an apparent 64KB page and // missing a ton of real ones in the interim; so minimum of 2 #ifndef STB_VORBIS_PUSHDATA_CRC_COUNT #define STB_VORBIS_PUSHDATA_CRC_COUNT 4 #endif // STB_VORBIS_FAST_HUFFMAN_LENGTH [number] // sets the log size of the huffman-acceleration table. Maximum // supported value is 24. with larger numbers, more decodings are O(1), // but the table size is larger so worse cache missing, so you'll have // to probe (and try multiple ogg vorbis files) to find the sweet spot. #ifndef STB_VORBIS_FAST_HUFFMAN_LENGTH #define STB_VORBIS_FAST_HUFFMAN_LENGTH 10 #endif // STB_VORBIS_FAST_BINARY_LENGTH [number] // sets the log size of the binary-search acceleration table. this // is used in similar fashion to the fast-huffman size to set initial // parameters for the binary search // STB_VORBIS_FAST_HUFFMAN_INT // The fast huffman tables are much more efficient if they can be // stored as 16-bit results instead of 32-bit results. This restricts // the codebooks to having only 65535 possible outcomes, though. // (At least, accelerated by the huffman table.) #ifndef STB_VORBIS_FAST_HUFFMAN_INT #define STB_VORBIS_FAST_HUFFMAN_SHORT #endif // STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH // If the 'fast huffman' search doesn't succeed, then stb_vorbis falls // back on binary searching for the correct one. This requires storing // extra tables with the huffman codes in sorted order. Defining this // symbol trades off space for speed by forcing a linear search in the // non-fast case, except for "sparse" codebooks. // #define STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH // STB_VORBIS_DIVIDES_IN_RESIDUE // stb_vorbis precomputes the result of the scalar residue decoding // that would otherwise require a divide per chunk. you can trade off // space for time by defining this symbol. // #define STB_VORBIS_DIVIDES_IN_RESIDUE // STB_VORBIS_DIVIDES_IN_CODEBOOK // vorbis VQ codebooks can be encoded two ways: with every case explicitly // stored, or with all elements being chosen from a small range of values, // and all values possible in all elements. By default, stb_vorbis expands // this latter kind out to look like the former kind for ease of decoding, // because otherwise an integer divide-per-vector-element is required to // unpack the index. If you define STB_VORBIS_DIVIDES_IN_CODEBOOK, you can // trade off storage for speed. //#define STB_VORBIS_DIVIDES_IN_CODEBOOK #ifdef STB_VORBIS_CODEBOOK_SHORTS #error "STB_VORBIS_CODEBOOK_SHORTS is no longer supported as it produced incorrect results for some input formats" #endif // STB_VORBIS_DIVIDE_TABLE // this replaces small integer divides in the floor decode loop with // table lookups. made less than 1% difference, so disabled by default. // STB_VORBIS_NO_INLINE_DECODE // disables the inlining of the scalar codebook fast-huffman decode. // might save a little codespace; useful for debugging // #define STB_VORBIS_NO_INLINE_DECODE // STB_VORBIS_NO_DEFER_FLOOR // Normally we only decode the floor without synthesizing the actual // full curve. We can instead synthesize the curve immediately. This // requires more memory and is very likely slower, so I don't think // you'd ever want to do it except for debugging. // #define STB_VORBIS_NO_DEFER_FLOOR ////////////////////////////////////////////////////////////////////////////// #ifdef STB_VORBIS_NO_PULLDATA_API #define STB_VORBIS_NO_INTEGER_CONVERSION #define STB_VORBIS_NO_STDIO #endif #if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO) #define STB_VORBIS_NO_STDIO 1 #endif #ifndef STB_VORBIS_NO_INTEGER_CONVERSION #ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT // only need endianness for fast-float-to-int, which we don't // use for pushdata #ifndef STB_VORBIS_BIG_ENDIAN #define STB_VORBIS_ENDIAN 0 #else #define STB_VORBIS_ENDIAN 1 #endif #endif #endif #ifndef STB_VORBIS_NO_STDIO #include <stdio.h> #endif #ifndef STB_VORBIS_NO_CRT #include <stdlib.h> #include <string.h> #include <assert.h> #include <math.h> // find definition of alloca if it's not in stdlib.h: #if defined(_MSC_VER) || defined(__MINGW32__) #include <malloc.h> #endif #if defined(__linux__) || defined(__linux) || defined(__EMSCRIPTEN__) #include <alloca.h> #endif #else // STB_VORBIS_NO_CRT #define NULL 0 #define malloc(s) 0 #define free(s) ((void) 0) #define realloc(s) 0 #endif // STB_VORBIS_NO_CRT #include <limits.h> #ifdef __MINGW32__ // eff you mingw: // "fixed": // http://sourceforge.net/p/mingw-w64/mailman/message/32882927/ // "no that broke the build, reverted, who cares about C": // http://sourceforge.net/p/mingw-w64/mailman/message/32890381/ #ifdef __forceinline #undef __forceinline #endif #define __forceinline #define alloca __builtin_alloca #elif !defined(_MSC_VER) #if __GNUC__ #define __forceinline inline #else #define __forceinline #endif #endif #if STB_VORBIS_MAX_CHANNELS > 256 #error "Value of STB_VORBIS_MAX_CHANNELS outside of allowed range" #endif #if STB_VORBIS_FAST_HUFFMAN_LENGTH > 24 #error "Value of STB_VORBIS_FAST_HUFFMAN_LENGTH outside of allowed range" #endif #if 0 #include <crtdbg.h> #define CHECK(f) _CrtIsValidHeapPointer(f->channel_buffers[1]) #else #define CHECK(f) ((void) 0) #endif #define MAX_BLOCKSIZE_LOG 13 // from specification #define MAX_BLOCKSIZE (1 << MAX_BLOCKSIZE_LOG) typedef unsigned char uint8; typedef signed char int8; typedef unsigned short uint16; typedef signed short int16; typedef unsigned int uint32; typedef signed int int32; #ifndef TRUE #define TRUE 1 #define FALSE 0 #endif typedef float codetype; // @NOTE // // Some arrays below are tagged "//varies", which means it's actually // a variable-sized piece of data, but rather than malloc I assume it's // small enough it's better to just allocate it all together with the // main thing // // Most of the variables are specified with the smallest size I could pack // them into. It might give better performance to make them all full-sized // integers. It should be safe to freely rearrange the structures or change // the sizes larger--nothing relies on silently truncating etc., nor the // order of variables. #define FAST_HUFFMAN_TABLE_SIZE (1 << STB_VORBIS_FAST_HUFFMAN_LENGTH) #define FAST_HUFFMAN_TABLE_MASK (FAST_HUFFMAN_TABLE_SIZE - 1) typedef struct { int dimensions, entries; uint8 *codeword_lengths; float minimum_value; float delta_value; uint8 value_bits; uint8 lookup_type; uint8 sequence_p; uint8 sparse; uint32 lookup_values; codetype *multiplicands; uint32 *codewords; #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT int16 fast_huffman[FAST_HUFFMAN_TABLE_SIZE]; #else int32 fast_huffman[FAST_HUFFMAN_TABLE_SIZE]; #endif uint32 *sorted_codewords; int *sorted_values; int sorted_entries; } Codebook; typedef struct { uint8 order; uint16 rate; uint16 bark_map_size; uint8 amplitude_bits; uint8 amplitude_offset; uint8 number_of_books; uint8 book_list[16]; // varies } Floor0; typedef struct { uint8 partitions; uint8 partition_class_list[32]; // varies uint8 class_dimensions[16]; // varies uint8 class_subclasses[16]; // varies uint8 class_masterbooks[16]; // varies int16 subclass_books[16][8]; // varies uint16 Xlist[31*8+2]; // varies uint8 sorted_order[31*8+2]; uint8 neighbors[31*8+2][2]; uint8 floor1_multiplier; uint8 rangebits; int values; } Floor1; typedef union { Floor0 floor0; Floor1 floor1; } Floor; typedef struct { uint32 begin, end; uint32 part_size; uint8 classifications; uint8 classbook; uint8 **classdata; int16 (*residue_books)[8]; } Residue; typedef struct { uint8 magnitude; uint8 angle; uint8 mux; } MappingChannel; typedef struct { uint16 coupling_steps; MappingChannel *chan; uint8 submaps; uint8 submap_floor[15]; // varies uint8 submap_residue[15]; // varies } Mapping; typedef struct { uint8 blockflag; uint8 mapping; uint16 windowtype; uint16 transformtype; } Mode; typedef struct { uint32 goal_crc; // expected crc if match int bytes_left; // bytes left in packet uint32 crc_so_far; // running crc int bytes_done; // bytes processed in _current_ chunk uint32 sample_loc; // granule pos encoded in page } CRCscan; typedef struct { uint32 page_start, page_end; uint32 last_decoded_sample; } ProbedPage; struct stb_vorbis { // user-accessible info unsigned int sample_rate; int channels; unsigned int setup_memory_required; unsigned int temp_memory_required; unsigned int setup_temp_memory_required; // input config #ifndef STB_VORBIS_NO_STDIO FILE *f; uint32 f_start; int close_on_free; #endif uint8 *stream; uint8 *stream_start; uint8 *stream_end; uint32 stream_len; uint8 push_mode; uint32 first_audio_page_offset; ProbedPage p_first, p_last; // memory management stb_vorbis_alloc alloc; int setup_offset; int temp_offset; // run-time results int eof; enum STBVorbisError error; // user-useful data // header info int blocksize[2]; int blocksize_0, blocksize_1; int codebook_count; Codebook *codebooks; int floor_count; uint16 floor_types[64]; // varies Floor *floor_config; int residue_count; uint16 residue_types[64]; // varies Residue *residue_config; int mapping_count; Mapping *mapping; int mode_count; Mode mode_config[64]; // varies uint32 total_samples; // decode buffer float *channel_buffers[STB_VORBIS_MAX_CHANNELS]; float *outputs [STB_VORBIS_MAX_CHANNELS]; float *previous_window[STB_VORBIS_MAX_CHANNELS]; int previous_length; #ifndef STB_VORBIS_NO_DEFER_FLOOR int16 *finalY[STB_VORBIS_MAX_CHANNELS]; #else float *floor_buffers[STB_VORBIS_MAX_CHANNELS]; #endif uint32 current_loc; // sample location of next frame to decode int current_loc_valid; // per-blocksize precomputed data // twiddle factors float *A[2],*B[2],*C[2]; float *window[2]; uint16 *bit_reverse[2]; // current page/packet/segment streaming info uint32 serial; // stream serial number for verification int last_page; int segment_count; uint8 segments[255]; uint8 page_flag; uint8 bytes_in_seg; uint8 first_decode; int next_seg; int last_seg; // flag that we're on the last segment int last_seg_which; // what was the segment number of the last seg? uint32 acc; int valid_bits; int packet_bytes; int end_seg_with_known_loc; uint32 known_loc_for_packet; int discard_samples_deferred; uint32 samples_output; // push mode scanning int page_crc_tests; // only in push_mode: number of tests active; -1 if not searching #ifndef STB_VORBIS_NO_PUSHDATA_API CRCscan scan[STB_VORBIS_PUSHDATA_CRC_COUNT]; #endif // sample-access int channel_buffer_start; int channel_buffer_end; }; #if defined(STB_VORBIS_NO_PUSHDATA_API) #define IS_PUSH_MODE(f) FALSE #elif defined(STB_VORBIS_NO_PULLDATA_API) #define IS_PUSH_MODE(f) TRUE #else #define IS_PUSH_MODE(f) ((f)->push_mode) #endif typedef struct stb_vorbis vorb; static int error(vorb *f, enum STBVorbisError e) { f->error = e; if (!f->eof && e != VORBIS_need_more_data) { f->error=e; // breakpoint for debugging } return 0; } // these functions are used for allocating temporary memory // while decoding. if you can afford the stack space, use // alloca(); otherwise, provide a temp buffer and it will // allocate out of those. #define array_size_required(count,size) (count*(sizeof(void *)+(size))) #define temp_alloc(f,size) (f->alloc.alloc_buffer ? setup_temp_malloc(f,size) : alloca(size)) #define temp_free(f,p) 0 #define temp_alloc_save(f) ((f)->temp_offset) #define temp_alloc_restore(f,p) ((f)->temp_offset = (p)) #define temp_block_array(f,count,size) make_block_array(temp_alloc(f,array_size_required(count,size)), count, size) // given a sufficiently large block of memory, make an array of pointers to subblocks of it static void *make_block_array(void *mem, int count, int size) { int i; void ** p = (void **) mem; char *q = (char *) (p + count); for (i=0; i < count; ++i) { p[i] = q; q += size; } return p; } static void *setup_malloc(vorb *f, int sz) { sz = (sz+3) & ~3; f->setup_memory_required += sz; if (f->alloc.alloc_buffer) { void *p = (char *) f->alloc.alloc_buffer + f->setup_offset; if (f->setup_offset + sz > f->temp_offset) return NULL; f->setup_offset += sz; return p; } return sz ? malloc(sz) : NULL; } static void setup_free(vorb *f, void *p) { if (f->alloc.alloc_buffer) return; // do nothing; setup mem is a stack free(p); } static void *setup_temp_malloc(vorb *f, int sz) { sz = (sz+3) & ~3; if (f->alloc.alloc_buffer) { if (f->temp_offset - sz < f->setup_offset) return NULL; f->temp_offset -= sz; return (char *) f->alloc.alloc_buffer + f->temp_offset; } return malloc(sz); } static void setup_temp_free(vorb *f, void *p, int sz) { if (f->alloc.alloc_buffer) { f->temp_offset += (sz+3)&~3; return; } free(p); } #define CRC32_POLY 0x04c11db7 // from spec static uint32 crc_table[256]; static void crc32_init(void) { int i,j; uint32 s; for(i=0; i < 256; i++) { for (s=(uint32) i << 24, j=0; j < 8; ++j) s = (s << 1) ^ (s >= (1U<<31) ? CRC32_POLY : 0); crc_table[i] = s; } } static __forceinline uint32 crc32_update(uint32 crc, uint8 byte) { return (crc << 8) ^ crc_table[byte ^ (crc >> 24)]; } // used in setup, and for huffman that doesn't go fast path static unsigned int bit_reverse(unsigned int n) { n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1); n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2); n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4); n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8); return (n >> 16) | (n << 16); } static float square(float x) { return x*x; } // this is a weird definition of log2() for which log2(1) = 1, log2(2) = 2, log2(4) = 3 // as required by the specification. fast(?) implementation from stb.h // @OPTIMIZE: called multiple times per-packet with "constants"; move to setup static int ilog(int32 n) { static signed char log2_4[16] = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 }; if (n < 0) return 0; // signed n returns 0 // 2 compares if n < 16, 3 compares otherwise (4 if signed or n > 1<<29) if (n < (1 << 14)) if (n < (1 << 4)) return 0 + log2_4[n ]; else if (n < (1 << 9)) return 5 + log2_4[n >> 5]; else return 10 + log2_4[n >> 10]; else if (n < (1 << 24)) if (n < (1 << 19)) return 15 + log2_4[n >> 15]; else return 20 + log2_4[n >> 20]; else if (n < (1 << 29)) return 25 + log2_4[n >> 25]; else return 30 + log2_4[n >> 30]; } #ifndef M_PI #define M_PI 3.14159265358979323846264f // from CRC #endif // code length assigned to a value with no huffman encoding #define NO_CODE 255 /////////////////////// LEAF SETUP FUNCTIONS ////////////////////////// // // these functions are only called at setup, and only a few times // per file static float float32_unpack(uint32 x) { // from the specification uint32 mantissa = x & 0x1fffff; uint32 sign = x & 0x80000000; uint32 exp = (x & 0x7fe00000) >> 21; double res = sign ? -(double)mantissa : (double)mantissa; return (float) ldexp((float)res, exp-788); } // zlib & jpeg huffman tables assume that the output symbols // can either be arbitrarily arranged, or have monotonically // increasing frequencies--they rely on the lengths being sorted; // this makes for a very simple generation algorithm. // vorbis allows a huffman table with non-sorted lengths. This // requires a more sophisticated construction, since symbols in // order do not map to huffman codes "in order". static void add_entry(Codebook *c, uint32 huff_code, int symbol, int count, int len, uint32 *values) { if (!c->sparse) { c->codewords [symbol] = huff_code; } else { c->codewords [count] = huff_code; c->codeword_lengths[count] = len; values [count] = symbol; } } static int compute_codewords(Codebook *c, uint8 *len, int n, uint32 *values) { int i,k,m=0; uint32 available[32]; memset(available, 0, sizeof(available)); // find the first entry for (k=0; k < n; ++k) if (len[k] < NO_CODE) break; if (k == n) { assert(c->sorted_entries == 0); return TRUE; } // add to the list add_entry(c, 0, k, m++, len[k], values); // add all available leaves for (i=1; i <= len[k]; ++i) available[i] = 1U << (32-i); // note that the above code treats the first case specially, // but it's really the same as the following code, so they // could probably be combined (except the initial code is 0, // and I use 0 in available[] to mean 'empty') for (i=k+1; i < n; ++i) { uint32 res; int z = len[i], y; if (z == NO_CODE) continue; // find lowest available leaf (should always be earliest, // which is what the specification calls for) // note that this property, and the fact we can never have // more than one free leaf at a given level, isn't totally // trivial to prove, but it seems true and the assert never // fires, so! while (z > 0 && !available[z]) --z; if (z == 0) { return FALSE; } res = available[z]; assert(z >= 0 && z < 32); available[z] = 0; add_entry(c, bit_reverse(res), i, m++, len[i], values); // propagate availability up the tree if (z != len[i]) { assert(len[i] >= 0 && len[i] < 32); for (y=len[i]; y > z; --y) { assert(available[y] == 0); available[y] = res + (1 << (32-y)); } } } return TRUE; } // accelerated huffman table allows fast O(1) match of all symbols // of length <= STB_VORBIS_FAST_HUFFMAN_LENGTH static void compute_accelerated_huffman(Codebook *c) { int i, len; for (i=0; i < FAST_HUFFMAN_TABLE_SIZE; ++i) c->fast_huffman[i] = -1; len = c->sparse ? c->sorted_entries : c->entries; #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT if (len > 32767) len = 32767; // largest possible value we can encode! #endif for (i=0; i < len; ++i) { if (c->codeword_lengths[i] <= STB_VORBIS_FAST_HUFFMAN_LENGTH) { uint32 z = c->sparse ? bit_reverse(c->sorted_codewords[i]) : c->codewords[i]; // set table entries for all bit combinations in the higher bits while (z < FAST_HUFFMAN_TABLE_SIZE) { c->fast_huffman[z] = i; z += 1 << c->codeword_lengths[i]; } } } } #ifdef _MSC_VER #define STBV_CDECL __cdecl #else #define STBV_CDECL #endif static int STBV_CDECL uint32_compare(const void *p, const void *q) { uint32 x = * (uint32 *) p; uint32 y = * (uint32 *) q; return x < y ? -1 : x > y; } static int include_in_sort(Codebook *c, uint8 len) { if (c->sparse) { assert(len != NO_CODE); return TRUE; } if (len == NO_CODE) return FALSE; if (len > STB_VORBIS_FAST_HUFFMAN_LENGTH) return TRUE; return FALSE; } // if the fast table above doesn't work, we want to binary // search them... need to reverse the bits static void compute_sorted_huffman(Codebook *c, uint8 *lengths, uint32 *values) { int i, len; // build a list of all the entries // OPTIMIZATION: don't include the short ones, since they'll be caught by FAST_HUFFMAN. // this is kind of a frivolous optimization--I don't see any performance improvement, // but it's like 4 extra lines of code, so. if (!c->sparse) { int k = 0; for (i=0; i < c->entries; ++i) if (include_in_sort(c, lengths[i])) c->sorted_codewords[k++] = bit_reverse(c->codewords[i]); assert(k == c->sorted_entries); } else { for (i=0; i < c->sorted_entries; ++i) c->sorted_codewords[i] = bit_reverse(c->codewords[i]); } qsort(c->sorted_codewords, c->sorted_entries, sizeof(c->sorted_codewords[0]), uint32_compare); c->sorted_codewords[c->sorted_entries] = 0xffffffff; len = c->sparse ? c->sorted_entries : c->entries; // now we need to indicate how they correspond; we could either // #1: sort a different data structure that says who they correspond to // #2: for each sorted entry, search the original list to find who corresponds // #3: for each original entry, find the sorted entry // #1 requires extra storage, #2 is slow, #3 can use binary search! for (i=0; i < len; ++i) { int huff_len = c->sparse ? lengths[values[i]] : lengths[i]; if (include_in_sort(c,huff_len)) { uint32 code = bit_reverse(c->codewords[i]); int x=0, n=c->sorted_entries; while (n > 1) { // invariant: sc[x] <= code < sc[x+n] int m = x + (n >> 1); if (c->sorted_codewords[m] <= code) { x = m; n -= (n>>1); } else { n >>= 1; } } assert(c->sorted_codewords[x] == code); if (c->sparse) { c->sorted_values[x] = values[i]; c->codeword_lengths[x] = huff_len; } else { c->sorted_values[x] = i; } } } } // only run while parsing the header (3 times) static int vorbis_validate(uint8 *data) { static uint8 vorbis[6] = { 'v', 'o', 'r', 'b', 'i', 's' }; return memcmp(data, vorbis, 6) == 0; } // called from setup only, once per code book // (formula implied by specification) static int lookup1_values(int entries, int dim) { int r = (int) floor(exp((float) log((float) entries) / dim)); if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning; ++r; // floor() to avoid _ftol() when non-CRT if (pow((float) r+1, dim) <= entries) return -1; if ((int) floor(pow((float) r, dim)) > entries) return -1; return r; } // called twice per file static void compute_twiddle_factors(int n, float *A, float *B, float *C) { int n4 = n >> 2, n8 = n >> 3; int k,k2; for (k=k2=0; k < n4; ++k,k2+=2) { A[k2 ] = (float) cos(4*k*M_PI/n); A[k2+1] = (float) -sin(4*k*M_PI/n); B[k2 ] = (float) cos((k2+1)*M_PI/n/2) * 0.5f; B[k2+1] = (float) sin((k2+1)*M_PI/n/2) * 0.5f; } for (k=k2=0; k < n8; ++k,k2+=2) { C[k2 ] = (float) cos(2*(k2+1)*M_PI/n); C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n); } } static void compute_window(int n, float *window) { int n2 = n >> 1, i; for (i=0; i < n2; ++i) window[i] = (float) sin(0.5 * M_PI * square((float) sin((i - 0 + 0.5) / n2 * 0.5 * M_PI))); } static void compute_bitreverse(int n, uint16 *rev) { int ld = ilog(n) - 1; // ilog is off-by-one from normal definitions int i, n8 = n >> 3; for (i=0; i < n8; ++i) rev[i] = (bit_reverse(i) >> (32-ld+3)) << 2; } static int init_blocksize(vorb *f, int b, int n) { int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3; f->A[b] = (float *) setup_malloc(f, sizeof(float) * n2); f->B[b] = (float *) setup_malloc(f, sizeof(float) * n2); f->C[b] = (float *) setup_malloc(f, sizeof(float) * n4); if (!f->A[b] || !f->B[b] || !f->C[b]) return error(f, VORBIS_outofmem); compute_twiddle_factors(n, f->A[b], f->B[b], f->C[b]); f->window[b] = (float *) setup_malloc(f, sizeof(float) * n2); if (!f->window[b]) return error(f, VORBIS_outofmem); compute_window(n, f->window[b]); f->bit_reverse[b] = (uint16 *) setup_malloc(f, sizeof(uint16) * n8); if (!f->bit_reverse[b]) return error(f, VORBIS_outofmem); compute_bitreverse(n, f->bit_reverse[b]); return TRUE; } static void neighbors(uint16 *x, int n, int *plow, int *phigh) { int low = -1; int high = 65536; int i; for (i=0; i < n; ++i) { if (x[i] > low && x[i] < x[n]) { *plow = i; low = x[i]; } if (x[i] < high && x[i] > x[n]) { *phigh = i; high = x[i]; } } } // this has been repurposed so y is now the original index instead of y typedef struct { uint16 x,id; } stbv__floor_ordering; static int STBV_CDECL point_compare(const void *p, const void *q) { stbv__floor_ordering *a = (stbv__floor_ordering *) p; stbv__floor_ordering *b = (stbv__floor_ordering *) q; return a->x < b->x ? -1 : a->x > b->x; } // /////////////////////// END LEAF SETUP FUNCTIONS ////////////////////////// #if defined(STB_VORBIS_NO_STDIO) #define USE_MEMORY(z) TRUE #else #define USE_MEMORY(z) ((z)->stream) #endif static uint8 get8(vorb *z) { if (USE_MEMORY(z)) { if (z->stream >= z->stream_end) { z->eof = TRUE; return 0; } return *z->stream++; } #ifndef STB_VORBIS_NO_STDIO { int c = fgetc(z->f); if (c == EOF) { z->eof = TRUE; return 0; } return c; } #endif } static uint32 get32(vorb *f) { uint32 x; x = get8(f); x += get8(f) << 8; x += get8(f) << 16; x += (uint32) get8(f) << 24; return x; } static int getn(vorb *z, uint8 *data, int n) { if (USE_MEMORY(z)) { if (z->stream+n > z->stream_end) { z->eof = 1; return 0; } memcpy(data, z->stream, n); z->stream += n; return 1; } #ifndef STB_VORBIS_NO_STDIO if (fread(data, n, 1, z->f) == 1) return 1; else { z->eof = 1; return 0; } #endif } static void skip(vorb *z, int n) { if (USE_MEMORY(z)) { z->stream += n; if (z->stream >= z->stream_end) z->eof = 1; return; } #ifndef STB_VORBIS_NO_STDIO { long x = ftell(z->f); fseek(z->f, x+n, SEEK_SET); } #endif } static int set_file_offset(stb_vorbis *f, unsigned int loc) { #ifndef STB_VORBIS_NO_PUSHDATA_API if (f->push_mode) return 0; #endif f->eof = 0; if (USE_MEMORY(f)) { if (f->stream_start + loc >= f->stream_end || f->stream_start + loc < f->stream_start) { f->stream = f->stream_end; f->eof = 1; return 0; } else { f->stream = f->stream_start + loc; return 1; } } #ifndef STB_VORBIS_NO_STDIO if (loc + f->f_start < loc || loc >= 0x80000000) { loc = 0x7fffffff; f->eof = 1; } else { loc += f->f_start; } if (!fseek(f->f, loc, SEEK_SET)) return 1; f->eof = 1; fseek(f->f, f->f_start, SEEK_END); return 0; #endif } static uint8 ogg_page_header[4] = { 0x4f, 0x67, 0x67, 0x53 }; static int capture_pattern(vorb *f) { if (0x4f != get8(f)) return FALSE; if (0x67 != get8(f)) return FALSE; if (0x67 != get8(f)) return FALSE; if (0x53 != get8(f)) return FALSE; return TRUE; } #define PAGEFLAG_continued_packet 1 #define PAGEFLAG_first_page 2 #define PAGEFLAG_last_page 4 static int start_page_no_capturepattern(vorb *f) { uint32 loc0,loc1,n; // stream structure version if (0 != get8(f)) return error(f, VORBIS_invalid_stream_structure_version); // header flag f->page_flag = get8(f); // absolute granule position loc0 = get32(f); loc1 = get32(f); // @TODO: validate loc0,loc1 as valid positions? // stream serial number -- vorbis doesn't interleave, so discard get32(f); //if (f->serial != get32(f)) return error(f, VORBIS_incorrect_stream_serial_number); // page sequence number n = get32(f); f->last_page = n; // CRC32 get32(f); // page_segments f->segment_count = get8(f); if (!getn(f, f->segments, f->segment_count)) return error(f, VORBIS_unexpected_eof); // assume we _don't_ know any the sample position of any segments f->end_seg_with_known_loc = -2; if (loc0 != ~0U || loc1 != ~0U) { int i; // determine which packet is the last one that will complete for (i=f->segment_count-1; i >= 0; --i) if (f->segments[i] < 255) break; // 'i' is now the index of the _last_ segment of a packet that ends if (i >= 0) { f->end_seg_with_known_loc = i; f->known_loc_for_packet = loc0; } } if (f->first_decode) { int i,len; ProbedPage p; len = 0; for (i=0; i < f->segment_count; ++i) len += f->segments[i]; len += 27 + f->segment_count; p.page_start = f->first_audio_page_offset; p.page_end = p.page_start + len; p.last_decoded_sample = loc0; f->p_first = p; } f->next_seg = 0; return TRUE; } static int start_page(vorb *f) { if (!capture_pattern(f)) return error(f, VORBIS_missing_capture_pattern); return start_page_no_capturepattern(f); } static int start_packet(vorb *f) { while (f->next_seg == -1) { if (!start_page(f)) return FALSE; if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_continued_packet_flag_invalid); } f->last_seg = FALSE; f->valid_bits = 0; f->packet_bytes = 0; f->bytes_in_seg = 0; // f->next_seg is now valid return TRUE; } static int maybe_start_packet(vorb *f) { if (f->next_seg == -1) { int x = get8(f); if (f->eof) return FALSE; // EOF at page boundary is not an error! if (0x4f != x ) return error(f, VORBIS_missing_capture_pattern); if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern); if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern); if (0x53 != get8(f)) return error(f, VORBIS_missing_capture_pattern); if (!start_page_no_capturepattern(f)) return FALSE; if (f->page_flag & PAGEFLAG_continued_packet) { // set up enough state that we can read this packet if we want, // e.g. during recovery f->last_seg = FALSE; f->bytes_in_seg = 0; return error(f, VORBIS_continued_packet_flag_invalid); } } return start_packet(f); } static int next_segment(vorb *f) { int len; if (f->last_seg) return 0; if (f->next_seg == -1) { f->last_seg_which = f->segment_count-1; // in case start_page fails if (!start_page(f)) { f->last_seg = 1; return 0; } if (!(f->page_flag & PAGEFLAG_continued_packet)) return error(f, VORBIS_continued_packet_flag_invalid); } len = f->segments[f->next_seg++]; if (len < 255) { f->last_seg = TRUE; f->last_seg_which = f->next_seg-1; } if (f->next_seg >= f->segment_count) f->next_seg = -1; assert(f->bytes_in_seg == 0); f->bytes_in_seg = len; return len; } #define EOP (-1) #define INVALID_BITS (-1) static int get8_packet_raw(vorb *f) { if (!f->bytes_in_seg) { // CLANG! if (f->last_seg) return EOP; else if (!next_segment(f)) return EOP; } assert(f->bytes_in_seg > 0); --f->bytes_in_seg; ++f->packet_bytes; return get8(f); } static int get8_packet(vorb *f) { int x = get8_packet_raw(f); f->valid_bits = 0; return x; } static void flush_packet(vorb *f) { while (get8_packet_raw(f) != EOP); } // @OPTIMIZE: this is the secondary bit decoder, so it's probably not as important // as the huffman decoder? static uint32 get_bits(vorb *f, int n) { uint32 z; if (f->valid_bits < 0) return 0; if (f->valid_bits < n) { if (n > 24) { // the accumulator technique below would not work correctly in this case z = get_bits(f, 24); z += get_bits(f, n-24) << 24; return z; } if (f->valid_bits == 0) f->acc = 0; while (f->valid_bits < n) { int z = get8_packet_raw(f); if (z == EOP) { f->valid_bits = INVALID_BITS; return 0; } f->acc += z << f->valid_bits; f->valid_bits += 8; } } if (f->valid_bits < 0) return 0; z = f->acc & ((1 << n)-1); f->acc >>= n; f->valid_bits -= n; return z; } // @OPTIMIZE: primary accumulator for huffman // expand the buffer to as many bits as possible without reading off end of packet // it might be nice to allow f->valid_bits and f->acc to be stored in registers, // e.g. cache them locally and decode locally static __forceinline void prep_huffman(vorb *f) { if (f->valid_bits <= 24) { if (f->valid_bits == 0) f->acc = 0; do { int z; if (f->last_seg && !f->bytes_in_seg) return; z = get8_packet_raw(f); if (z == EOP) return; f->acc += (unsigned) z << f->valid_bits; f->valid_bits += 8; } while (f->valid_bits <= 24); } } enum { VORBIS_packet_id = 1, VORBIS_packet_comment = 3, VORBIS_packet_setup = 5 }; static int codebook_decode_scalar_raw(vorb *f, Codebook *c) { int i; prep_huffman(f); if (c->codewords == NULL && c->sorted_codewords == NULL) return -1; // cases to use binary search: sorted_codewords && !c->codewords // sorted_codewords && c->entries > 8 if (c->entries > 8 ? c->sorted_codewords!=NULL : !c->codewords) { // binary search uint32 code = bit_reverse(f->acc); int x=0, n=c->sorted_entries, len; while (n > 1) { // invariant: sc[x] <= code < sc[x+n] int m = x + (n >> 1); if (c->sorted_codewords[m] <= code) { x = m; n -= (n>>1); } else { n >>= 1; } } // x is now the sorted index if (!c->sparse) x = c->sorted_values[x]; // x is now sorted index if sparse, or symbol otherwise len = c->codeword_lengths[x]; if (f->valid_bits >= len) { f->acc >>= len; f->valid_bits -= len; return x; } f->valid_bits = 0; return -1; } // if small, linear search assert(!c->sparse); for (i=0; i < c->entries; ++i) { if (c->codeword_lengths[i] == NO_CODE) continue; if (c->codewords[i] == (f->acc & ((1 << c->codeword_lengths[i])-1))) { if (f->valid_bits >= c->codeword_lengths[i]) { f->acc >>= c->codeword_lengths[i]; f->valid_bits -= c->codeword_lengths[i]; return i; } f->valid_bits = 0; return -1; } } error(f, VORBIS_invalid_stream); f->valid_bits = 0; return -1; } #ifndef STB_VORBIS_NO_INLINE_DECODE #define DECODE_RAW(var, f,c) \ if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) \ prep_huffman(f); \ var = f->acc & FAST_HUFFMAN_TABLE_MASK; \ var = c->fast_huffman[var]; \ if (var >= 0) { \ int n = c->codeword_lengths[var]; \ f->acc >>= n; \ f->valid_bits -= n; \ if (f->valid_bits < 0) { f->valid_bits = 0; var = -1; } \ } else { \ var = codebook_decode_scalar_raw(f,c); \ } #else static int codebook_decode_scalar(vorb *f, Codebook *c) { int i; if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) prep_huffman(f); // fast huffman table lookup i = f->acc & FAST_HUFFMAN_TABLE_MASK; i = c->fast_huffman[i]; if (i >= 0) { f->acc >>= c->codeword_lengths[i]; f->valid_bits -= c->codeword_lengths[i]; if (f->valid_bits < 0) { f->valid_bits = 0; return -1; } return i; } return codebook_decode_scalar_raw(f,c); } #define DECODE_RAW(var,f,c) var = codebook_decode_scalar(f,c); #endif #define DECODE(var,f,c) \ DECODE_RAW(var,f,c) \ if (c->sparse) var = c->sorted_values[var]; #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK #define DECODE_VQ(var,f,c) DECODE_RAW(var,f,c) #else #define DECODE_VQ(var,f,c) DECODE(var,f,c) #endif // CODEBOOK_ELEMENT_FAST is an optimization for the CODEBOOK_FLOATS case // where we avoid one addition #define CODEBOOK_ELEMENT(c,off) (c->multiplicands[off]) #define CODEBOOK_ELEMENT_FAST(c,off) (c->multiplicands[off]) #define CODEBOOK_ELEMENT_BASE(c) (0) static int codebook_decode_start(vorb *f, Codebook *c) { int z = -1; // type 0 is only legal in a scalar context if (c->lookup_type == 0) error(f, VORBIS_invalid_stream); else { DECODE_VQ(z,f,c); if (c->sparse) assert(z < c->sorted_entries); if (z < 0) { // check for EOP if (!f->bytes_in_seg) if (f->last_seg) return z; error(f, VORBIS_invalid_stream); } } return z; } static int codebook_decode(vorb *f, Codebook *c, float *output, int len) { int i,z = codebook_decode_start(f,c); if (z < 0) return FALSE; if (len > c->dimensions) len = c->dimensions; #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { float last = CODEBOOK_ELEMENT_BASE(c); int div = 1; for (i=0; i < len; ++i) { int off = (z / div) % c->lookup_values; float val = CODEBOOK_ELEMENT_FAST(c,off) + last; output[i] += val; if (c->sequence_p) last = val + c->minimum_value; div *= c->lookup_values; } return TRUE; } #endif z *= c->dimensions; if (c->sequence_p) { float last = CODEBOOK_ELEMENT_BASE(c); for (i=0; i < len; ++i) { float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; output[i] += val; last = val + c->minimum_value; } } else { float last = CODEBOOK_ELEMENT_BASE(c); for (i=0; i < len; ++i) { output[i] += CODEBOOK_ELEMENT_FAST(c,z+i) + last; } } return TRUE; } static int codebook_decode_step(vorb *f, Codebook *c, float *output, int len, int step) { int i,z = codebook_decode_start(f,c); float last = CODEBOOK_ELEMENT_BASE(c); if (z < 0) return FALSE; if (len > c->dimensions) len = c->dimensions; #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { int div = 1; for (i=0; i < len; ++i) { int off = (z / div) % c->lookup_values; float val = CODEBOOK_ELEMENT_FAST(c,off) + last; output[i*step] += val; if (c->sequence_p) last = val; div *= c->lookup_values; } return TRUE; } #endif z *= c->dimensions; for (i=0; i < len; ++i) { float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; output[i*step] += val; if (c->sequence_p) last = val; } return TRUE; } static int codebook_decode_deinterleave_repeat(vorb *f, Codebook *c, float **outputs, int ch, int *c_inter_p, int *p_inter_p, int len, int total_decode) { int c_inter = *c_inter_p; int p_inter = *p_inter_p; int i,z, effective = c->dimensions; // type 0 is only legal in a scalar context if (c->lookup_type == 0) return error(f, VORBIS_invalid_stream); while (total_decode > 0) { float last = CODEBOOK_ELEMENT_BASE(c); DECODE_VQ(z,f,c); #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK assert(!c->sparse || z < c->sorted_entries); #endif if (z < 0) { if (!f->bytes_in_seg) if (f->last_seg) return FALSE; return error(f, VORBIS_invalid_stream); } // if this will take us off the end of the buffers, stop short! // we check by computing the length of the virtual interleaved // buffer (len*ch), our current offset within it (p_inter*ch)+(c_inter), // and the length we'll be using (effective) if (c_inter + p_inter*ch + effective > len * ch) { effective = len*ch - (p_inter*ch - c_inter); } #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { int div = 1; for (i=0; i < effective; ++i) { int off = (z / div) % c->lookup_values; float val = CODEBOOK_ELEMENT_FAST(c,off) + last; if (outputs[c_inter]) outputs[c_inter][p_inter] += val; if (++c_inter == ch) { c_inter = 0; ++p_inter; } if (c->sequence_p) last = val; div *= c->lookup_values; } } else #endif { z *= c->dimensions; if (c->sequence_p) { for (i=0; i < effective; ++i) { float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; if (outputs[c_inter]) outputs[c_inter][p_inter] += val; if (++c_inter == ch) { c_inter = 0; ++p_inter; } last = val; } } else { for (i=0; i < effective; ++i) { float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; if (outputs[c_inter]) outputs[c_inter][p_inter] += val; if (++c_inter == ch) { c_inter = 0; ++p_inter; } } } } total_decode -= effective; } *c_inter_p = c_inter; *p_inter_p = p_inter; return TRUE; } static int predict_point(int x, int x0, int x1, int y0, int y1) { int dy = y1 - y0; int adx = x1 - x0; // @OPTIMIZE: force int division to round in the right direction... is this necessary on x86? int err = abs(dy) * (x - x0); int off = err / adx; return dy < 0 ? y0 - off : y0 + off; } // the following table is block-copied from the specification static float inverse_db_table[256] = { 1.0649863e-07f, 1.1341951e-07f, 1.2079015e-07f, 1.2863978e-07f, 1.3699951e-07f, 1.4590251e-07f, 1.5538408e-07f, 1.6548181e-07f, 1.7623575e-07f, 1.8768855e-07f, 1.9988561e-07f, 2.1287530e-07f, 2.2670913e-07f, 2.4144197e-07f, 2.5713223e-07f, 2.7384213e-07f, 2.9163793e-07f, 3.1059021e-07f, 3.3077411e-07f, 3.5226968e-07f, 3.7516214e-07f, 3.9954229e-07f, 4.2550680e-07f, 4.5315863e-07f, 4.8260743e-07f, 5.1396998e-07f, 5.4737065e-07f, 5.8294187e-07f, 6.2082472e-07f, 6.6116941e-07f, 7.0413592e-07f, 7.4989464e-07f, 7.9862701e-07f, 8.5052630e-07f, 9.0579828e-07f, 9.6466216e-07f, 1.0273513e-06f, 1.0941144e-06f, 1.1652161e-06f, 1.2409384e-06f, 1.3215816e-06f, 1.4074654e-06f, 1.4989305e-06f, 1.5963394e-06f, 1.7000785e-06f, 1.8105592e-06f, 1.9282195e-06f, 2.0535261e-06f, 2.1869758e-06f, 2.3290978e-06f, 2.4804557e-06f, 2.6416497e-06f, 2.8133190e-06f, 2.9961443e-06f, 3.1908506e-06f, 3.3982101e-06f, 3.6190449e-06f, 3.8542308e-06f, 4.1047004e-06f, 4.3714470e-06f, 4.6555282e-06f, 4.9580707e-06f, 5.2802740e-06f, 5.6234160e-06f, 5.9888572e-06f, 6.3780469e-06f, 6.7925283e-06f, 7.2339451e-06f, 7.7040476e-06f, 8.2047000e-06f, 8.7378876e-06f, 9.3057248e-06f, 9.9104632e-06f, 1.0554501e-05f, 1.1240392e-05f, 1.1970856e-05f, 1.2748789e-05f, 1.3577278e-05f, 1.4459606e-05f, 1.5399272e-05f, 1.6400004e-05f, 1.7465768e-05f, 1.8600792e-05f, 1.9809576e-05f, 2.1096914e-05f, 2.2467911e-05f, 2.3928002e-05f, 2.5482978e-05f, 2.7139006e-05f, 2.8902651e-05f, 3.0780908e-05f, 3.2781225e-05f, 3.4911534e-05f, 3.7180282e-05f, 3.9596466e-05f, 4.2169667e-05f, 4.4910090e-05f, 4.7828601e-05f, 5.0936773e-05f, 5.4246931e-05f, 5.7772202e-05f, 6.1526565e-05f, 6.5524908e-05f, 6.9783085e-05f, 7.4317983e-05f, 7.9147585e-05f, 8.4291040e-05f, 8.9768747e-05f, 9.5602426e-05f, 0.00010181521f, 0.00010843174f, 0.00011547824f, 0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f, 0.00015820453f, 0.00016848555f, 0.00017943469f, 0.00019109536f, 0.00020351382f, 0.00021673929f, 0.00023082423f, 0.00024582449f, 0.00026179955f, 0.00027881276f, 0.00029693158f, 0.00031622787f, 0.00033677814f, 0.00035866388f, 0.00038197188f, 0.00040679456f, 0.00043323036f, 0.00046138411f, 0.00049136745f, 0.00052329927f, 0.00055730621f, 0.00059352311f, 0.00063209358f, 0.00067317058f, 0.00071691700f, 0.00076350630f, 0.00081312324f, 0.00086596457f, 0.00092223983f, 0.00098217216f, 0.0010459992f, 0.0011139742f, 0.0011863665f, 0.0012634633f, 0.0013455702f, 0.0014330129f, 0.0015261382f, 0.0016253153f, 0.0017309374f, 0.0018434235f, 0.0019632195f, 0.0020908006f, 0.0022266726f, 0.0023713743f, 0.0025254795f, 0.0026895994f, 0.0028643847f, 0.0030505286f, 0.0032487691f, 0.0034598925f, 0.0036847358f, 0.0039241906f, 0.0041792066f, 0.0044507950f, 0.0047400328f, 0.0050480668f, 0.0053761186f, 0.0057254891f, 0.0060975636f, 0.0064938176f, 0.0069158225f, 0.0073652516f, 0.0078438871f, 0.0083536271f, 0.0088964928f, 0.009474637f, 0.010090352f, 0.010746080f, 0.011444421f, 0.012188144f, 0.012980198f, 0.013823725f, 0.014722068f, 0.015678791f, 0.016697687f, 0.017782797f, 0.018938423f, 0.020169149f, 0.021479854f, 0.022875735f, 0.024362330f, 0.025945531f, 0.027631618f, 0.029427276f, 0.031339626f, 0.033376252f, 0.035545228f, 0.037855157f, 0.040315199f, 0.042935108f, 0.045725273f, 0.048696758f, 0.051861348f, 0.055231591f, 0.058820850f, 0.062643361f, 0.066714279f, 0.071049749f, 0.075666962f, 0.080584227f, 0.085821044f, 0.091398179f, 0.097337747f, 0.10366330f, 0.11039993f, 0.11757434f, 0.12521498f, 0.13335215f, 0.14201813f, 0.15124727f, 0.16107617f, 0.17154380f, 0.18269168f, 0.19456402f, 0.20720788f, 0.22067342f, 0.23501402f, 0.25028656f, 0.26655159f, 0.28387361f, 0.30232132f, 0.32196786f, 0.34289114f, 0.36517414f, 0.38890521f, 0.41417847f, 0.44109412f, 0.46975890f, 0.50028648f, 0.53279791f, 0.56742212f, 0.60429640f, 0.64356699f, 0.68538959f, 0.72993007f, 0.77736504f, 0.82788260f, 0.88168307f, 0.9389798f, 1.0f }; // @OPTIMIZE: if you want to replace this bresenham line-drawing routine, // note that you must produce bit-identical output to decode correctly; // this specific sequence of operations is specified in the spec (it's // drawing integer-quantized frequency-space lines that the encoder // expects to be exactly the same) // ... also, isn't the whole point of Bresenham's algorithm to NOT // have to divide in the setup? sigh. #ifndef STB_VORBIS_NO_DEFER_FLOOR #define LINE_OP(a,b) a *= b #else #define LINE_OP(a,b) a = b #endif #ifdef STB_VORBIS_DIVIDE_TABLE #define DIVTAB_NUMER 32 #define DIVTAB_DENOM 64 int8 integer_divide_table[DIVTAB_NUMER][DIVTAB_DENOM]; // 2KB #endif static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n) { int dy = y1 - y0; int adx = x1 - x0; int ady = abs(dy); int base; int x=x0,y=y0; int err = 0; int sy; #ifdef STB_VORBIS_DIVIDE_TABLE if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) { if (dy < 0) { base = -integer_divide_table[ady][adx]; sy = base-1; } else { base = integer_divide_table[ady][adx]; sy = base+1; } } else { base = dy / adx; if (dy < 0) sy = base - 1; else sy = base+1; } #else base = dy / adx; if (dy < 0) sy = base - 1; else sy = base+1; #endif ady -= abs(base) * adx; if (x1 > n) x1 = n; if (x < x1) { LINE_OP(output[x], inverse_db_table[y&255]); for (++x; x < x1; ++x) { err += ady; if (err >= adx) { err -= adx; y += sy; } else y += base; LINE_OP(output[x], inverse_db_table[y&255]); } } } static int residue_decode(vorb *f, Codebook *book, float *target, int offset, int n, int rtype) { int k; if (rtype == 0) { int step = n / book->dimensions; for (k=0; k < step; ++k) if (!codebook_decode_step(f, book, target+offset+k, n-offset-k, step)) return FALSE; } else { for (k=0; k < n; ) { if (!codebook_decode(f, book, target+offset, n-k)) return FALSE; k += book->dimensions; offset += book->dimensions; } } return TRUE; } // n is 1/2 of the blocksize -- // specification: "Correct per-vector decode length is [n]/2" static void decode_residue(vorb *f, float *residue_buffers[], int ch, int n, int rn, uint8 *do_not_decode) { int i,j,pass; Residue *r = f->residue_config + rn; int rtype = f->residue_types[rn]; int c = r->classbook; int classwords = f->codebooks[c].dimensions; unsigned int actual_size = rtype == 2 ? n*2 : n; unsigned int limit_r_begin = (r->begin < actual_size ? r->begin : actual_size); unsigned int limit_r_end = (r->end < actual_size ? r->end : actual_size); int n_read = limit_r_end - limit_r_begin; int part_read = n_read / r->part_size; int temp_alloc_point = temp_alloc_save(f); #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE uint8 ***part_classdata = (uint8 ***) temp_block_array(f,f->channels, part_read * sizeof(**part_classdata)); #else int **classifications = (int **) temp_block_array(f,f->channels, part_read * sizeof(**classifications)); #endif CHECK(f); for (i=0; i < ch; ++i) if (!do_not_decode[i]) memset(residue_buffers[i], 0, sizeof(float) * n); if (rtype == 2 && ch != 1) { for (j=0; j < ch; ++j) if (!do_not_decode[j]) break; if (j == ch) goto done; for (pass=0; pass < 8; ++pass) { int pcount = 0, class_set = 0; if (ch == 2) { while (pcount < part_read) { int z = r->begin + pcount*r->part_size; int c_inter = (z & 1), p_inter = z>>1; if (pass == 0) { Codebook *c = f->codebooks+r->classbook; int q; DECODE(q,f,c); if (q == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[0][class_set] = r->classdata[q]; #else for (i=classwords-1; i >= 0; --i) { classifications[0][i+pcount] = q % r->classifications; q /= r->classifications; } #endif } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { int z = r->begin + pcount*r->part_size; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[0][class_set][i]; #else int c = classifications[0][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { Codebook *book = f->codebooks + b; #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; #else // saves 1% if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; #endif } else { z += r->part_size; c_inter = z & 1; p_inter = z >> 1; } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } else if (ch == 1) { while (pcount < part_read) { int z = r->begin + pcount*r->part_size; int c_inter = 0, p_inter = z; if (pass == 0) { Codebook *c = f->codebooks+r->classbook; int q; DECODE(q,f,c); if (q == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[0][class_set] = r->classdata[q]; #else for (i=classwords-1; i >= 0; --i) { classifications[0][i+pcount] = q % r->classifications; q /= r->classifications; } #endif } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { int z = r->begin + pcount*r->part_size; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[0][class_set][i]; #else int c = classifications[0][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { Codebook *book = f->codebooks + b; if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; } else { z += r->part_size; c_inter = 0; p_inter = z; } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } else { while (pcount < part_read) { int z = r->begin + pcount*r->part_size; int c_inter = z % ch, p_inter = z/ch; if (pass == 0) { Codebook *c = f->codebooks+r->classbook; int q; DECODE(q,f,c); if (q == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[0][class_set] = r->classdata[q]; #else for (i=classwords-1; i >= 0; --i) { classifications[0][i+pcount] = q % r->classifications; q /= r->classifications; } #endif } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { int z = r->begin + pcount*r->part_size; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[0][class_set][i]; #else int c = classifications[0][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { Codebook *book = f->codebooks + b; if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; } else { z += r->part_size; c_inter = z % ch; p_inter = z / ch; } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } } goto done; } CHECK(f); for (pass=0; pass < 8; ++pass) { int pcount = 0, class_set=0; while (pcount < part_read) { if (pass == 0) { for (j=0; j < ch; ++j) { if (!do_not_decode[j]) { Codebook *c = f->codebooks+r->classbook; int temp; DECODE(temp,f,c); if (temp == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[j][class_set] = r->classdata[temp]; #else for (i=classwords-1; i >= 0; --i) { classifications[j][i+pcount] = temp % r->classifications; temp /= r->classifications; } #endif } } } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { for (j=0; j < ch; ++j) { if (!do_not_decode[j]) { #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[j][class_set][i]; #else int c = classifications[j][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { float *target = residue_buffers[j]; int offset = r->begin + pcount * r->part_size; int n = r->part_size; Codebook *book = f->codebooks + b; if (!residue_decode(f, book, target, offset, n, rtype)) goto done; } } } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } done: CHECK(f); #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE temp_free(f,part_classdata); #else temp_free(f,classifications); #endif temp_alloc_restore(f,temp_alloc_point); } #if 0 // slow way for debugging void inverse_mdct_slow(float *buffer, int n) { int i,j; int n2 = n >> 1; float *x = (float *) malloc(sizeof(*x) * n2); memcpy(x, buffer, sizeof(*x) * n2); for (i=0; i < n; ++i) { float acc = 0; for (j=0; j < n2; ++j) // formula from paper: //acc += n/4.0f * x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1)); // formula from wikipedia //acc += 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5)); // these are equivalent, except the formula from the paper inverts the multiplier! // however, what actually works is NO MULTIPLIER!?! //acc += 64 * 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5)); acc += x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1)); buffer[i] = acc; } free(x); } #elif 0 // same as above, but just barely able to run in real time on modern machines void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype) { float mcos[16384]; int i,j; int n2 = n >> 1, nmask = (n << 2) -1; float *x = (float *) malloc(sizeof(*x) * n2); memcpy(x, buffer, sizeof(*x) * n2); for (i=0; i < 4*n; ++i) mcos[i] = (float) cos(M_PI / 2 * i / n); for (i=0; i < n; ++i) { float acc = 0; for (j=0; j < n2; ++j) acc += x[j] * mcos[(2 * i + 1 + n2)*(2*j+1) & nmask]; buffer[i] = acc; } free(x); } #elif 0 // transform to use a slow dct-iv; this is STILL basically trivial, // but only requires half as many ops void dct_iv_slow(float *buffer, int n) { float mcos[16384]; float x[2048]; int i,j; int n2 = n >> 1, nmask = (n << 3) - 1; memcpy(x, buffer, sizeof(*x) * n); for (i=0; i < 8*n; ++i) mcos[i] = (float) cos(M_PI / 4 * i / n); for (i=0; i < n; ++i) { float acc = 0; for (j=0; j < n; ++j) acc += x[j] * mcos[((2 * i + 1)*(2*j+1)) & nmask]; buffer[i] = acc; } } void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype) { int i, n4 = n >> 2, n2 = n >> 1, n3_4 = n - n4; float temp[4096]; memcpy(temp, buffer, n2 * sizeof(float)); dct_iv_slow(temp, n2); // returns -c'-d, a-b' for (i=0; i < n4 ; ++i) buffer[i] = temp[i+n4]; // a-b' for ( ; i < n3_4; ++i) buffer[i] = -temp[n3_4 - i - 1]; // b-a', c+d' for ( ; i < n ; ++i) buffer[i] = -temp[i - n3_4]; // c'+d } #endif #ifndef LIBVORBIS_MDCT #define LIBVORBIS_MDCT 0 #endif #if LIBVORBIS_MDCT // directly call the vorbis MDCT using an interface documented // by Jeff Roberts... useful for performance comparison typedef struct { int n; int log2n; float *trig; int *bitrev; float scale; } mdct_lookup; extern void mdct_init(mdct_lookup *lookup, int n); extern void mdct_clear(mdct_lookup *l); extern void mdct_backward(mdct_lookup *init, float *in, float *out); mdct_lookup M1,M2; void inverse_mdct(float *buffer, int n, vorb *f, int blocktype) { mdct_lookup *M; if (M1.n == n) M = &M1; else if (M2.n == n) M = &M2; else if (M1.n == 0) { mdct_init(&M1, n); M = &M1; } else { if (M2.n) __asm int 3; mdct_init(&M2, n); M = &M2; } mdct_backward(M, buffer, buffer); } #endif // the following were split out into separate functions while optimizing; // they could be pushed back up but eh. __forceinline showed no change; // they're probably already being inlined. static void imdct_step3_iter0_loop(int n, float *e, int i_off, int k_off, float *A) { float *ee0 = e + i_off; float *ee2 = ee0 + k_off; int i; assert((n & 3) == 0); for (i=(n>>2); i > 0; --i) { float k00_20, k01_21; k00_20 = ee0[ 0] - ee2[ 0]; k01_21 = ee0[-1] - ee2[-1]; ee0[ 0] += ee2[ 0];//ee0[ 0] = ee0[ 0] + ee2[ 0]; ee0[-1] += ee2[-1];//ee0[-1] = ee0[-1] + ee2[-1]; ee2[ 0] = k00_20 * A[0] - k01_21 * A[1]; ee2[-1] = k01_21 * A[0] + k00_20 * A[1]; A += 8; k00_20 = ee0[-2] - ee2[-2]; k01_21 = ee0[-3] - ee2[-3]; ee0[-2] += ee2[-2];//ee0[-2] = ee0[-2] + ee2[-2]; ee0[-3] += ee2[-3];//ee0[-3] = ee0[-3] + ee2[-3]; ee2[-2] = k00_20 * A[0] - k01_21 * A[1]; ee2[-3] = k01_21 * A[0] + k00_20 * A[1]; A += 8; k00_20 = ee0[-4] - ee2[-4]; k01_21 = ee0[-5] - ee2[-5]; ee0[-4] += ee2[-4];//ee0[-4] = ee0[-4] + ee2[-4]; ee0[-5] += ee2[-5];//ee0[-5] = ee0[-5] + ee2[-5]; ee2[-4] = k00_20 * A[0] - k01_21 * A[1]; ee2[-5] = k01_21 * A[0] + k00_20 * A[1]; A += 8; k00_20 = ee0[-6] - ee2[-6]; k01_21 = ee0[-7] - ee2[-7]; ee0[-6] += ee2[-6];//ee0[-6] = ee0[-6] + ee2[-6]; ee0[-7] += ee2[-7];//ee0[-7] = ee0[-7] + ee2[-7]; ee2[-6] = k00_20 * A[0] - k01_21 * A[1]; ee2[-7] = k01_21 * A[0] + k00_20 * A[1]; A += 8; ee0 -= 8; ee2 -= 8; } } static void imdct_step3_inner_r_loop(int lim, float *e, int d0, int k_off, float *A, int k1) { int i; float k00_20, k01_21; float *e0 = e + d0; float *e2 = e0 + k_off; for (i=lim >> 2; i > 0; --i) { k00_20 = e0[-0] - e2[-0]; k01_21 = e0[-1] - e2[-1]; e0[-0] += e2[-0];//e0[-0] = e0[-0] + e2[-0]; e0[-1] += e2[-1];//e0[-1] = e0[-1] + e2[-1]; e2[-0] = (k00_20)*A[0] - (k01_21) * A[1]; e2[-1] = (k01_21)*A[0] + (k00_20) * A[1]; A += k1; k00_20 = e0[-2] - e2[-2]; k01_21 = e0[-3] - e2[-3]; e0[-2] += e2[-2];//e0[-2] = e0[-2] + e2[-2]; e0[-3] += e2[-3];//e0[-3] = e0[-3] + e2[-3]; e2[-2] = (k00_20)*A[0] - (k01_21) * A[1]; e2[-3] = (k01_21)*A[0] + (k00_20) * A[1]; A += k1; k00_20 = e0[-4] - e2[-4]; k01_21 = e0[-5] - e2[-5]; e0[-4] += e2[-4];//e0[-4] = e0[-4] + e2[-4]; e0[-5] += e2[-5];//e0[-5] = e0[-5] + e2[-5]; e2[-4] = (k00_20)*A[0] - (k01_21) * A[1]; e2[-5] = (k01_21)*A[0] + (k00_20) * A[1]; A += k1; k00_20 = e0[-6] - e2[-6]; k01_21 = e0[-7] - e2[-7]; e0[-6] += e2[-6];//e0[-6] = e0[-6] + e2[-6]; e0[-7] += e2[-7];//e0[-7] = e0[-7] + e2[-7]; e2[-6] = (k00_20)*A[0] - (k01_21) * A[1]; e2[-7] = (k01_21)*A[0] + (k00_20) * A[1]; e0 -= 8; e2 -= 8; A += k1; } } static void imdct_step3_inner_s_loop(int n, float *e, int i_off, int k_off, float *A, int a_off, int k0) { int i; float A0 = A[0]; float A1 = A[0+1]; float A2 = A[0+a_off]; float A3 = A[0+a_off+1]; float A4 = A[0+a_off*2+0]; float A5 = A[0+a_off*2+1]; float A6 = A[0+a_off*3+0]; float A7 = A[0+a_off*3+1]; float k00,k11; float *ee0 = e +i_off; float *ee2 = ee0+k_off; for (i=n; i > 0; --i) { k00 = ee0[ 0] - ee2[ 0]; k11 = ee0[-1] - ee2[-1]; ee0[ 0] = ee0[ 0] + ee2[ 0]; ee0[-1] = ee0[-1] + ee2[-1]; ee2[ 0] = (k00) * A0 - (k11) * A1; ee2[-1] = (k11) * A0 + (k00) * A1; k00 = ee0[-2] - ee2[-2]; k11 = ee0[-3] - ee2[-3]; ee0[-2] = ee0[-2] + ee2[-2]; ee0[-3] = ee0[-3] + ee2[-3]; ee2[-2] = (k00) * A2 - (k11) * A3; ee2[-3] = (k11) * A2 + (k00) * A3; k00 = ee0[-4] - ee2[-4]; k11 = ee0[-5] - ee2[-5]; ee0[-4] = ee0[-4] + ee2[-4]; ee0[-5] = ee0[-5] + ee2[-5]; ee2[-4] = (k00) * A4 - (k11) * A5; ee2[-5] = (k11) * A4 + (k00) * A5; k00 = ee0[-6] - ee2[-6]; k11 = ee0[-7] - ee2[-7]; ee0[-6] = ee0[-6] + ee2[-6]; ee0[-7] = ee0[-7] + ee2[-7]; ee2[-6] = (k00) * A6 - (k11) * A7; ee2[-7] = (k11) * A6 + (k00) * A7; ee0 -= k0; ee2 -= k0; } } static __forceinline void iter_54(float *z) { float k00,k11,k22,k33; float y0,y1,y2,y3; k00 = z[ 0] - z[-4]; y0 = z[ 0] + z[-4]; y2 = z[-2] + z[-6]; k22 = z[-2] - z[-6]; z[-0] = y0 + y2; // z0 + z4 + z2 + z6 z[-2] = y0 - y2; // z0 + z4 - z2 - z6 // done with y0,y2 k33 = z[-3] - z[-7]; z[-4] = k00 + k33; // z0 - z4 + z3 - z7 z[-6] = k00 - k33; // z0 - z4 - z3 + z7 // done with k33 k11 = z[-1] - z[-5]; y1 = z[-1] + z[-5]; y3 = z[-3] + z[-7]; z[-1] = y1 + y3; // z1 + z5 + z3 + z7 z[-3] = y1 - y3; // z1 + z5 - z3 - z7 z[-5] = k11 - k22; // z1 - z5 + z2 - z6 z[-7] = k11 + k22; // z1 - z5 - z2 + z6 } static void imdct_step3_inner_s_loop_ld654(int n, float *e, int i_off, float *A, int base_n) { int a_off = base_n >> 3; float A2 = A[0+a_off]; float *z = e + i_off; float *base = z - 16 * n; while (z > base) { float k00,k11; k00 = z[-0] - z[-8]; k11 = z[-1] - z[-9]; z[-0] = z[-0] + z[-8]; z[-1] = z[-1] + z[-9]; z[-8] = k00; z[-9] = k11 ; k00 = z[ -2] - z[-10]; k11 = z[ -3] - z[-11]; z[ -2] = z[ -2] + z[-10]; z[ -3] = z[ -3] + z[-11]; z[-10] = (k00+k11) * A2; z[-11] = (k11-k00) * A2; k00 = z[-12] - z[ -4]; // reverse to avoid a unary negation k11 = z[ -5] - z[-13]; z[ -4] = z[ -4] + z[-12]; z[ -5] = z[ -5] + z[-13]; z[-12] = k11; z[-13] = k00; k00 = z[-14] - z[ -6]; // reverse to avoid a unary negation k11 = z[ -7] - z[-15]; z[ -6] = z[ -6] + z[-14]; z[ -7] = z[ -7] + z[-15]; z[-14] = (k00+k11) * A2; z[-15] = (k00-k11) * A2; iter_54(z); iter_54(z-8); z -= 16; } } static void inverse_mdct(float *buffer, int n, vorb *f, int blocktype) { int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l; int ld; // @OPTIMIZE: reduce register pressure by using fewer variables? int save_point = temp_alloc_save(f); float *buf2 = (float *) temp_alloc(f, n2 * sizeof(*buf2)); float *u=NULL,*v=NULL; // twiddle factors float *A = f->A[blocktype]; // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio" // See notes about bugs in that paper in less-optimal implementation 'inverse_mdct_old' after this function. // kernel from paper // merged: // copy and reflect spectral data // step 0 // note that it turns out that the items added together during // this step are, in fact, being added to themselves (as reflected // by step 0). inexplicable inefficiency! this became obvious // once I combined the passes. // so there's a missing 'times 2' here (for adding X to itself). // this propagates through linearly to the end, where the numbers // are 1/2 too small, and need to be compensated for. { float *d,*e, *AA, *e_stop; d = &buf2[n2-2]; AA = A; e = &buffer[0]; e_stop = &buffer[n2]; while (e != e_stop) { d[1] = (e[0] * AA[0] - e[2]*AA[1]); d[0] = (e[0] * AA[1] + e[2]*AA[0]); d -= 2; AA += 2; e += 4; } e = &buffer[n2-3]; while (d >= buf2) { d[1] = (-e[2] * AA[0] - -e[0]*AA[1]); d[0] = (-e[2] * AA[1] + -e[0]*AA[0]); d -= 2; AA += 2; e -= 4; } } // now we use symbolic names for these, so that we can // possibly swap their meaning as we change which operations // are in place u = buffer; v = buf2; // step 2 (paper output is w, now u) // this could be in place, but the data ends up in the wrong // place... _somebody_'s got to swap it, so this is nominated { float *AA = &A[n2-8]; float *d0,*d1, *e0, *e1; e0 = &v[n4]; e1 = &v[0]; d0 = &u[n4]; d1 = &u[0]; while (AA >= A) { float v40_20, v41_21; v41_21 = e0[1] - e1[1]; v40_20 = e0[0] - e1[0]; d0[1] = e0[1] + e1[1]; d0[0] = e0[0] + e1[0]; d1[1] = v41_21*AA[4] - v40_20*AA[5]; d1[0] = v40_20*AA[4] + v41_21*AA[5]; v41_21 = e0[3] - e1[3]; v40_20 = e0[2] - e1[2]; d0[3] = e0[3] + e1[3]; d0[2] = e0[2] + e1[2]; d1[3] = v41_21*AA[0] - v40_20*AA[1]; d1[2] = v40_20*AA[0] + v41_21*AA[1]; AA -= 8; d0 += 4; d1 += 4; e0 += 4; e1 += 4; } } // step 3 ld = ilog(n) - 1; // ilog is off-by-one from normal definitions // optimized step 3: // the original step3 loop can be nested r inside s or s inside r; // it's written originally as s inside r, but this is dumb when r // iterates many times, and s few. So I have two copies of it and // switch between them halfway. // this is iteration 0 of step 3 imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*0, -(n >> 3), A); imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*1, -(n >> 3), A); // this is iteration 1 of step 3 imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*0, -(n >> 4), A, 16); imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*1, -(n >> 4), A, 16); imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*2, -(n >> 4), A, 16); imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*3, -(n >> 4), A, 16); l=2; for (; l < (ld-3)>>1; ++l) { int k0 = n >> (l+2), k0_2 = k0>>1; int lim = 1 << (l+1); int i; for (i=0; i < lim; ++i) imdct_step3_inner_r_loop(n >> (l+4), u, n2-1 - k0*i, -k0_2, A, 1 << (l+3)); } for (; l < ld-6; ++l) { int k0 = n >> (l+2), k1 = 1 << (l+3), k0_2 = k0>>1; int rlim = n >> (l+6), r; int lim = 1 << (l+1); int i_off; float *A0 = A; i_off = n2-1; for (r=rlim; r > 0; --r) { imdct_step3_inner_s_loop(lim, u, i_off, -k0_2, A0, k1, k0); A0 += k1*4; i_off -= 8; } } // iterations with count: // ld-6,-5,-4 all interleaved together // the big win comes from getting rid of needless flops // due to the constants on pass 5 & 4 being all 1 and 0; // combining them to be simultaneous to improve cache made little difference imdct_step3_inner_s_loop_ld654(n >> 5, u, n2-1, A, n); // output is u // step 4, 5, and 6 // cannot be in-place because of step 5 { uint16 *bitrev = f->bit_reverse[blocktype]; // weirdly, I'd have thought reading sequentially and writing // erratically would have been better than vice-versa, but in // fact that's not what my testing showed. (That is, with // j = bitreverse(i), do you read i and write j, or read j and write i.) float *d0 = &v[n4-4]; float *d1 = &v[n2-4]; while (d0 >= v) { int k4; k4 = bitrev[0]; d1[3] = u[k4+0]; d1[2] = u[k4+1]; d0[3] = u[k4+2]; d0[2] = u[k4+3]; k4 = bitrev[1]; d1[1] = u[k4+0]; d1[0] = u[k4+1]; d0[1] = u[k4+2]; d0[0] = u[k4+3]; d0 -= 4; d1 -= 4; bitrev += 2; } } // (paper output is u, now v) // data must be in buf2 assert(v == buf2); // step 7 (paper output is v, now v) // this is now in place { float *C = f->C[blocktype]; float *d, *e; d = v; e = v + n2 - 4; while (d < e) { float a02,a11,b0,b1,b2,b3; a02 = d[0] - e[2]; a11 = d[1] + e[3]; b0 = C[1]*a02 + C[0]*a11; b1 = C[1]*a11 - C[0]*a02; b2 = d[0] + e[ 2]; b3 = d[1] - e[ 3]; d[0] = b2 + b0; d[1] = b3 + b1; e[2] = b2 - b0; e[3] = b1 - b3; a02 = d[2] - e[0]; a11 = d[3] + e[1]; b0 = C[3]*a02 + C[2]*a11; b1 = C[3]*a11 - C[2]*a02; b2 = d[2] + e[ 0]; b3 = d[3] - e[ 1]; d[2] = b2 + b0; d[3] = b3 + b1; e[0] = b2 - b0; e[1] = b1 - b3; C += 4; d += 4; e -= 4; } } // data must be in buf2 // step 8+decode (paper output is X, now buffer) // this generates pairs of data a la 8 and pushes them directly through // the decode kernel (pushing rather than pulling) to avoid having // to make another pass later // this cannot POSSIBLY be in place, so we refer to the buffers directly { float *d0,*d1,*d2,*d3; float *B = f->B[blocktype] + n2 - 8; float *e = buf2 + n2 - 8; d0 = &buffer[0]; d1 = &buffer[n2-4]; d2 = &buffer[n2]; d3 = &buffer[n-4]; while (e >= v) { float p0,p1,p2,p3; p3 = e[6]*B[7] - e[7]*B[6]; p2 = -e[6]*B[6] - e[7]*B[7]; d0[0] = p3; d1[3] = - p3; d2[0] = p2; d3[3] = p2; p1 = e[4]*B[5] - e[5]*B[4]; p0 = -e[4]*B[4] - e[5]*B[5]; d0[1] = p1; d1[2] = - p1; d2[1] = p0; d3[2] = p0; p3 = e[2]*B[3] - e[3]*B[2]; p2 = -e[2]*B[2] - e[3]*B[3]; d0[2] = p3; d1[1] = - p3; d2[2] = p2; d3[1] = p2; p1 = e[0]*B[1] - e[1]*B[0]; p0 = -e[0]*B[0] - e[1]*B[1]; d0[3] = p1; d1[0] = - p1; d2[3] = p0; d3[0] = p0; B -= 8; e -= 8; d0 += 4; d2 += 4; d1 -= 4; d3 -= 4; } } temp_free(f,buf2); temp_alloc_restore(f,save_point); } #if 0 // this is the original version of the above code, if you want to optimize it from scratch void inverse_mdct_naive(float *buffer, int n) { float s; float A[1 << 12], B[1 << 12], C[1 << 11]; int i,k,k2,k4, n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l; int n3_4 = n - n4, ld; // how can they claim this only uses N words?! // oh, because they're only used sparsely, whoops float u[1 << 13], X[1 << 13], v[1 << 13], w[1 << 13]; // set up twiddle factors for (k=k2=0; k < n4; ++k,k2+=2) { A[k2 ] = (float) cos(4*k*M_PI/n); A[k2+1] = (float) -sin(4*k*M_PI/n); B[k2 ] = (float) cos((k2+1)*M_PI/n/2); B[k2+1] = (float) sin((k2+1)*M_PI/n/2); } for (k=k2=0; k < n8; ++k,k2+=2) { C[k2 ] = (float) cos(2*(k2+1)*M_PI/n); C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n); } // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio" // Note there are bugs in that pseudocode, presumably due to them attempting // to rename the arrays nicely rather than representing the way their actual // implementation bounces buffers back and forth. As a result, even in the // "some formulars corrected" version, a direct implementation fails. These // are noted below as "paper bug". // copy and reflect spectral data for (k=0; k < n2; ++k) u[k] = buffer[k]; for ( ; k < n ; ++k) u[k] = -buffer[n - k - 1]; // kernel from paper // step 1 for (k=k2=k4=0; k < n4; k+=1, k2+=2, k4+=4) { v[n-k4-1] = (u[k4] - u[n-k4-1]) * A[k2] - (u[k4+2] - u[n-k4-3])*A[k2+1]; v[n-k4-3] = (u[k4] - u[n-k4-1]) * A[k2+1] + (u[k4+2] - u[n-k4-3])*A[k2]; } // step 2 for (k=k4=0; k < n8; k+=1, k4+=4) { w[n2+3+k4] = v[n2+3+k4] + v[k4+3]; w[n2+1+k4] = v[n2+1+k4] + v[k4+1]; w[k4+3] = (v[n2+3+k4] - v[k4+3])*A[n2-4-k4] - (v[n2+1+k4]-v[k4+1])*A[n2-3-k4]; w[k4+1] = (v[n2+1+k4] - v[k4+1])*A[n2-4-k4] + (v[n2+3+k4]-v[k4+3])*A[n2-3-k4]; } // step 3 ld = ilog(n) - 1; // ilog is off-by-one from normal definitions for (l=0; l < ld-3; ++l) { int k0 = n >> (l+2), k1 = 1 << (l+3); int rlim = n >> (l+4), r4, r; int s2lim = 1 << (l+2), s2; for (r=r4=0; r < rlim; r4+=4,++r) { for (s2=0; s2 < s2lim; s2+=2) { u[n-1-k0*s2-r4] = w[n-1-k0*s2-r4] + w[n-1-k0*(s2+1)-r4]; u[n-3-k0*s2-r4] = w[n-3-k0*s2-r4] + w[n-3-k0*(s2+1)-r4]; u[n-1-k0*(s2+1)-r4] = (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1] - (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1+1]; u[n-3-k0*(s2+1)-r4] = (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1] + (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1+1]; } } if (l+1 < ld-3) { // paper bug: ping-ponging of u&w here is omitted memcpy(w, u, sizeof(u)); } } // step 4 for (i=0; i < n8; ++i) { int j = bit_reverse(i) >> (32-ld+3); assert(j < n8); if (i == j) { // paper bug: original code probably swapped in place; if copying, // need to directly copy in this case int i8 = i << 3; v[i8+1] = u[i8+1]; v[i8+3] = u[i8+3]; v[i8+5] = u[i8+5]; v[i8+7] = u[i8+7]; } else if (i < j) { int i8 = i << 3, j8 = j << 3; v[j8+1] = u[i8+1], v[i8+1] = u[j8 + 1]; v[j8+3] = u[i8+3], v[i8+3] = u[j8 + 3]; v[j8+5] = u[i8+5], v[i8+5] = u[j8 + 5]; v[j8+7] = u[i8+7], v[i8+7] = u[j8 + 7]; } } // step 5 for (k=0; k < n2; ++k) { w[k] = v[k*2+1]; } // step 6 for (k=k2=k4=0; k < n8; ++k, k2 += 2, k4 += 4) { u[n-1-k2] = w[k4]; u[n-2-k2] = w[k4+1]; u[n3_4 - 1 - k2] = w[k4+2]; u[n3_4 - 2 - k2] = w[k4+3]; } // step 7 for (k=k2=0; k < n8; ++k, k2 += 2) { v[n2 + k2 ] = ( u[n2 + k2] + u[n-2-k2] + C[k2+1]*(u[n2+k2]-u[n-2-k2]) + C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2; v[n-2 - k2] = ( u[n2 + k2] + u[n-2-k2] - C[k2+1]*(u[n2+k2]-u[n-2-k2]) - C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2; v[n2+1+ k2] = ( u[n2+1+k2] - u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2; v[n-1 - k2] = (-u[n2+1+k2] + u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2; } // step 8 for (k=k2=0; k < n4; ++k,k2 += 2) { X[k] = v[k2+n2]*B[k2 ] + v[k2+1+n2]*B[k2+1]; X[n2-1-k] = v[k2+n2]*B[k2+1] - v[k2+1+n2]*B[k2 ]; } // decode kernel to output // determined the following value experimentally // (by first figuring out what made inverse_mdct_slow work); then matching that here // (probably vorbis encoder premultiplies by n or n/2, to save it on the decoder?) s = 0.5; // theoretically would be n4 // [[[ note! the s value of 0.5 is compensated for by the B[] in the current code, // so it needs to use the "old" B values to behave correctly, or else // set s to 1.0 ]]] for (i=0; i < n4 ; ++i) buffer[i] = s * X[i+n4]; for ( ; i < n3_4; ++i) buffer[i] = -s * X[n3_4 - i - 1]; for ( ; i < n ; ++i) buffer[i] = -s * X[i - n3_4]; } #endif static float *get_window(vorb *f, int len) { len <<= 1; if (len == f->blocksize_0) return f->window[0]; if (len == f->blocksize_1) return f->window[1]; return NULL; } #ifndef STB_VORBIS_NO_DEFER_FLOOR typedef int16 YTYPE; #else typedef int YTYPE; #endif static int do_floor(vorb *f, Mapping *map, int i, int n, float *target, YTYPE *finalY, uint8 *step2_flag) { int n2 = n >> 1; int s = map->chan[i].mux, floor; floor = map->submap_floor[s]; if (f->floor_types[floor] == 0) { return error(f, VORBIS_invalid_stream); } else { Floor1 *g = &f->floor_config[floor].floor1; int j,q; int lx = 0, ly = finalY[0] * g->floor1_multiplier; for (q=1; q < g->values; ++q) { j = g->sorted_order[q]; #ifndef STB_VORBIS_NO_DEFER_FLOOR if (finalY[j] >= 0) #else if (step2_flag[j]) #endif { int hy = finalY[j] * g->floor1_multiplier; int hx = g->Xlist[j]; if (lx != hx) draw_line(target, lx,ly, hx,hy, n2); CHECK(f); lx = hx, ly = hy; } } if (lx < n2) { // optimization of: draw_line(target, lx,ly, n,ly, n2); for (j=lx; j < n2; ++j) LINE_OP(target[j], inverse_db_table[ly]); CHECK(f); } } return TRUE; } // The meaning of "left" and "right" // // For a given frame: // we compute samples from 0..n // window_center is n/2 // we'll window and mix the samples from left_start to left_end with data from the previous frame // all of the samples from left_end to right_start can be output without mixing; however, // this interval is 0-length except when transitioning between short and long frames // all of the samples from right_start to right_end need to be mixed with the next frame, // which we don't have, so those get saved in a buffer // frame N's right_end-right_start, the number of samples to mix with the next frame, // has to be the same as frame N+1's left_end-left_start (which they are by // construction) static int vorbis_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode) { Mode *m; int i, n, prev, next, window_center; f->channel_buffer_start = f->channel_buffer_end = 0; retry: if (f->eof) return FALSE; if (!maybe_start_packet(f)) return FALSE; // check packet type if (get_bits(f,1) != 0) { if (IS_PUSH_MODE(f)) return error(f,VORBIS_bad_packet_type); while (EOP != get8_packet(f)); goto retry; } if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); i = get_bits(f, ilog(f->mode_count-1)); if (i == EOP) return FALSE; if (i >= f->mode_count) return FALSE; *mode = i; m = f->mode_config + i; if (m->blockflag) { n = f->blocksize_1; prev = get_bits(f,1); next = get_bits(f,1); } else { prev = next = 0; n = f->blocksize_0; } // WINDOWING window_center = n >> 1; if (m->blockflag && !prev) { *p_left_start = (n - f->blocksize_0) >> 2; *p_left_end = (n + f->blocksize_0) >> 2; } else { *p_left_start = 0; *p_left_end = window_center; } if (m->blockflag && !next) { *p_right_start = (n*3 - f->blocksize_0) >> 2; *p_right_end = (n*3 + f->blocksize_0) >> 2; } else { *p_right_start = window_center; *p_right_end = n; } return TRUE; } static int vorbis_decode_packet_rest(vorb *f, int *len, Mode *m, int left_start, int left_end, int right_start, int right_end, int *p_left) { Mapping *map; int i,j,k,n,n2; int zero_channel[256]; int really_zero_channel[256]; // WINDOWING n = f->blocksize[m->blockflag]; map = &f->mapping[m->mapping]; // FLOORS n2 = n >> 1; CHECK(f); for (i=0; i < f->channels; ++i) { int s = map->chan[i].mux, floor; zero_channel[i] = FALSE; floor = map->submap_floor[s]; if (f->floor_types[floor] == 0) { return error(f, VORBIS_invalid_stream); } else { Floor1 *g = &f->floor_config[floor].floor1; if (get_bits(f, 1)) { short *finalY; uint8 step2_flag[256]; static int range_list[4] = { 256, 128, 86, 64 }; int range = range_list[g->floor1_multiplier-1]; int offset = 2; finalY = f->finalY[i]; finalY[0] = get_bits(f, ilog(range)-1); finalY[1] = get_bits(f, ilog(range)-1); for (j=0; j < g->partitions; ++j) { int pclass = g->partition_class_list[j]; int cdim = g->class_dimensions[pclass]; int cbits = g->class_subclasses[pclass]; int csub = (1 << cbits)-1; int cval = 0; if (cbits) { Codebook *c = f->codebooks + g->class_masterbooks[pclass]; DECODE(cval,f,c); } for (k=0; k < cdim; ++k) { int book = g->subclass_books[pclass][cval & csub]; cval = cval >> cbits; if (book >= 0) { int temp; Codebook *c = f->codebooks + book; DECODE(temp,f,c); finalY[offset++] = temp; } else finalY[offset++] = 0; } } if (f->valid_bits == INVALID_BITS) goto error; // behavior according to spec step2_flag[0] = step2_flag[1] = 1; for (j=2; j < g->values; ++j) { int low, high, pred, highroom, lowroom, room, val; low = g->neighbors[j][0]; high = g->neighbors[j][1]; //neighbors(g->Xlist, j, &low, &high); pred = predict_point(g->Xlist[j], g->Xlist[low], g->Xlist[high], finalY[low], finalY[high]); val = finalY[j]; highroom = range - pred; lowroom = pred; if (highroom < lowroom) room = highroom * 2; else room = lowroom * 2; if (val) { step2_flag[low] = step2_flag[high] = 1; step2_flag[j] = 1; if (val >= room) if (highroom > lowroom) finalY[j] = val - lowroom + pred; else finalY[j] = pred - val + highroom - 1; else if (val & 1) finalY[j] = pred - ((val+1)>>1); else finalY[j] = pred + (val>>1); } else { step2_flag[j] = 0; finalY[j] = pred; } } #ifdef STB_VORBIS_NO_DEFER_FLOOR do_floor(f, map, i, n, f->floor_buffers[i], finalY, step2_flag); #else // defer final floor computation until _after_ residue for (j=0; j < g->values; ++j) { if (!step2_flag[j]) finalY[j] = -1; } #endif } else { error: zero_channel[i] = TRUE; } // So we just defer everything else to later // at this point we've decoded the floor into buffer } } CHECK(f); // at this point we've decoded all floors if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); // re-enable coupled channels if necessary memcpy(really_zero_channel, zero_channel, sizeof(really_zero_channel[0]) * f->channels); for (i=0; i < map->coupling_steps; ++i) if (!zero_channel[map->chan[i].magnitude] || !zero_channel[map->chan[i].angle]) { zero_channel[map->chan[i].magnitude] = zero_channel[map->chan[i].angle] = FALSE; } CHECK(f); // RESIDUE DECODE for (i=0; i < map->submaps; ++i) { float *residue_buffers[STB_VORBIS_MAX_CHANNELS]; int r; uint8 do_not_decode[256]; int ch = 0; for (j=0; j < f->channels; ++j) { if (map->chan[j].mux == i) { if (zero_channel[j]) { do_not_decode[ch] = TRUE; residue_buffers[ch] = NULL; } else { do_not_decode[ch] = FALSE; residue_buffers[ch] = f->channel_buffers[j]; } ++ch; } } r = map->submap_residue[i]; decode_residue(f, residue_buffers, ch, n2, r, do_not_decode); } if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); CHECK(f); // INVERSE COUPLING for (i = map->coupling_steps-1; i >= 0; --i) { int n2 = n >> 1; float *m = f->channel_buffers[map->chan[i].magnitude]; float *a = f->channel_buffers[map->chan[i].angle ]; for (j=0; j < n2; ++j) { float a2,m2; if (m[j] > 0) if (a[j] > 0) m2 = m[j], a2 = m[j] - a[j]; else a2 = m[j], m2 = m[j] + a[j]; else if (a[j] > 0) m2 = m[j], a2 = m[j] + a[j]; else a2 = m[j], m2 = m[j] - a[j]; m[j] = m2; a[j] = a2; } } CHECK(f); // finish decoding the floors #ifndef STB_VORBIS_NO_DEFER_FLOOR for (i=0; i < f->channels; ++i) { if (really_zero_channel[i]) { memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2); } else { do_floor(f, map, i, n, f->channel_buffers[i], f->finalY[i], NULL); } } #else for (i=0; i < f->channels; ++i) { if (really_zero_channel[i]) { memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2); } else { for (j=0; j < n2; ++j) f->channel_buffers[i][j] *= f->floor_buffers[i][j]; } } #endif // INVERSE MDCT CHECK(f); for (i=0; i < f->channels; ++i) inverse_mdct(f->channel_buffers[i], n, f, m->blockflag); CHECK(f); // this shouldn't be necessary, unless we exited on an error // and want to flush to get to the next packet flush_packet(f); if (f->first_decode) { // assume we start so first non-discarded sample is sample 0 // this isn't to spec, but spec would require us to read ahead // and decode the size of all current frames--could be done, // but presumably it's not a commonly used feature f->current_loc = -n2; // start of first frame is positioned for discard // we might have to discard samples "from" the next frame too, // if we're lapping a large block then a small at the start? f->discard_samples_deferred = n - right_end; f->current_loc_valid = TRUE; f->first_decode = FALSE; } else if (f->discard_samples_deferred) { if (f->discard_samples_deferred >= right_start - left_start) { f->discard_samples_deferred -= (right_start - left_start); left_start = right_start; *p_left = left_start; } else { left_start += f->discard_samples_deferred; *p_left = left_start; f->discard_samples_deferred = 0; } } else if (f->previous_length == 0 && f->current_loc_valid) { // we're recovering from a seek... that means we're going to discard // the samples from this packet even though we know our position from // the last page header, so we need to update the position based on // the discarded samples here // but wait, the code below is going to add this in itself even // on a discard, so we don't need to do it here... } // check if we have ogg information about the sample # for this packet if (f->last_seg_which == f->end_seg_with_known_loc) { // if we have a valid current loc, and this is final: if (f->current_loc_valid && (f->page_flag & PAGEFLAG_last_page)) { uint32 current_end = f->known_loc_for_packet; // then let's infer the size of the (probably) short final frame if (current_end < f->current_loc + (right_end-left_start)) { if (current_end < f->current_loc) { // negative truncation, that's impossible! *len = 0; } else { *len = current_end - f->current_loc; } *len += left_start; // this doesn't seem right, but has no ill effect on my test files if (*len > right_end) *len = right_end; // this should never happen f->current_loc += *len; return TRUE; } } // otherwise, just set our sample loc // guess that the ogg granule pos refers to the _middle_ of the // last frame? // set f->current_loc to the position of left_start f->current_loc = f->known_loc_for_packet - (n2-left_start); f->current_loc_valid = TRUE; } if (f->current_loc_valid) f->current_loc += (right_start - left_start); if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); *len = right_end; // ignore samples after the window goes to 0 CHECK(f); return TRUE; } static int vorbis_decode_packet(vorb *f, int *len, int *p_left, int *p_right) { int mode, left_end, right_end; if (!vorbis_decode_initial(f, p_left, &left_end, p_right, &right_end, &mode)) return 0; return vorbis_decode_packet_rest(f, len, f->mode_config + mode, *p_left, left_end, *p_right, right_end, p_left); } static int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right) { int prev,i,j; // we use right&left (the start of the right- and left-window sin()-regions) // to determine how much to return, rather than inferring from the rules // (same result, clearer code); 'left' indicates where our sin() window // starts, therefore where the previous window's right edge starts, and // therefore where to start mixing from the previous buffer. 'right' // indicates where our sin() ending-window starts, therefore that's where // we start saving, and where our returned-data ends. // mixin from previous window if (f->previous_length) { int i,j, n = f->previous_length; float *w = get_window(f, n); if (w == NULL) return 0; for (i=0; i < f->channels; ++i) { for (j=0; j < n; ++j) f->channel_buffers[i][left+j] = f->channel_buffers[i][left+j]*w[ j] + f->previous_window[i][ j]*w[n-1-j]; } } prev = f->previous_length; // last half of this data becomes previous window f->previous_length = len - right; // @OPTIMIZE: could avoid this copy by double-buffering the // output (flipping previous_window with channel_buffers), but // then previous_window would have to be 2x as large, and // channel_buffers couldn't be temp mem (although they're NOT // currently temp mem, they could be (unless we want to level // performance by spreading out the computation)) for (i=0; i < f->channels; ++i) for (j=0; right+j < len; ++j) f->previous_window[i][j] = f->channel_buffers[i][right+j]; if (!prev) // there was no previous packet, so this data isn't valid... // this isn't entirely true, only the would-have-overlapped data // isn't valid, but this seems to be what the spec requires return 0; // truncate a short frame if (len < right) right = len; f->samples_output += right-left; return right - left; } static int vorbis_pump_first_frame(stb_vorbis *f) { int len, right, left, res; res = vorbis_decode_packet(f, &len, &left, &right); if (res) vorbis_finish_frame(f, len, left, right); return res; } #ifndef STB_VORBIS_NO_PUSHDATA_API static int is_whole_packet_present(stb_vorbis *f, int end_page) { // make sure that we have the packet available before continuing... // this requires a full ogg parse, but we know we can fetch from f->stream // instead of coding this out explicitly, we could save the current read state, // read the next packet with get8() until end-of-packet, check f->eof, then // reset the state? but that would be slower, esp. since we'd have over 256 bytes // of state to restore (primarily the page segment table) int s = f->next_seg, first = TRUE; uint8 *p = f->stream; if (s != -1) { // if we're not starting the packet with a 'continue on next page' flag for (; s < f->segment_count; ++s) { p += f->segments[s]; if (f->segments[s] < 255) // stop at first short segment break; } // either this continues, or it ends it... if (end_page) if (s < f->segment_count-1) return error(f, VORBIS_invalid_stream); if (s == f->segment_count) s = -1; // set 'crosses page' flag if (p > f->stream_end) return error(f, VORBIS_need_more_data); first = FALSE; } for (; s == -1;) { uint8 *q; int n; // check that we have the page header ready if (p + 26 >= f->stream_end) return error(f, VORBIS_need_more_data); // validate the page if (memcmp(p, ogg_page_header, 4)) return error(f, VORBIS_invalid_stream); if (p[4] != 0) return error(f, VORBIS_invalid_stream); if (first) { // the first segment must NOT have 'continued_packet', later ones MUST if (f->previous_length) if ((p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream); // if no previous length, we're resynching, so we can come in on a continued-packet, // which we'll just drop } else { if (!(p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream); } n = p[26]; // segment counts q = p+27; // q points to segment table p = q + n; // advance past header // make sure we've read the segment table if (p > f->stream_end) return error(f, VORBIS_need_more_data); for (s=0; s < n; ++s) { p += q[s]; if (q[s] < 255) break; } if (end_page) if (s < n-1) return error(f, VORBIS_invalid_stream); if (s == n) s = -1; // set 'crosses page' flag if (p > f->stream_end) return error(f, VORBIS_need_more_data); first = FALSE; } return TRUE; } #endif // !STB_VORBIS_NO_PUSHDATA_API static int start_decoder(vorb *f) { uint8 header[6], x,y; int len,i,j,k, max_submaps = 0; int longest_floorlist=0; // first page, first packet if (!start_page(f)) return FALSE; // validate page flag if (!(f->page_flag & PAGEFLAG_first_page)) return error(f, VORBIS_invalid_first_page); if (f->page_flag & PAGEFLAG_last_page) return error(f, VORBIS_invalid_first_page); if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_invalid_first_page); // check for expected packet length if (f->segment_count != 1) return error(f, VORBIS_invalid_first_page); if (f->segments[0] != 30) { // check for the Ogg skeleton fishead identifying header to refine our error if (f->segments[0] == 64 && getn(f, header, 6) && header[0] == 'f' && header[1] == 'i' && header[2] == 's' && header[3] == 'h' && header[4] == 'e' && header[5] == 'a' && get8(f) == 'd' && get8(f) == '\0') return error(f, VORBIS_ogg_skeleton_not_supported); else return error(f, VORBIS_invalid_first_page); } // read packet // check packet header if (get8(f) != VORBIS_packet_id) return error(f, VORBIS_invalid_first_page); if (!getn(f, header, 6)) return error(f, VORBIS_unexpected_eof); if (!vorbis_validate(header)) return error(f, VORBIS_invalid_first_page); // vorbis_version if (get32(f) != 0) return error(f, VORBIS_invalid_first_page); f->channels = get8(f); if (!f->channels) return error(f, VORBIS_invalid_first_page); if (f->channels > STB_VORBIS_MAX_CHANNELS) return error(f, VORBIS_too_many_channels); f->sample_rate = get32(f); if (!f->sample_rate) return error(f, VORBIS_invalid_first_page); get32(f); // bitrate_maximum get32(f); // bitrate_nominal get32(f); // bitrate_minimum x = get8(f); { int log0,log1; log0 = x & 15; log1 = x >> 4; f->blocksize_0 = 1 << log0; f->blocksize_1 = 1 << log1; if (log0 < 6 || log0 > 13) return error(f, VORBIS_invalid_setup); if (log1 < 6 || log1 > 13) return error(f, VORBIS_invalid_setup); if (log0 > log1) return error(f, VORBIS_invalid_setup); } // framing_flag x = get8(f); if (!(x & 1)) return error(f, VORBIS_invalid_first_page); // second packet! if (!start_page(f)) return FALSE; if (!start_packet(f)) return FALSE; do { len = next_segment(f); skip(f, len); f->bytes_in_seg = 0; } while (len); // third packet! if (!start_packet(f)) return FALSE; #ifndef STB_VORBIS_NO_PUSHDATA_API if (IS_PUSH_MODE(f)) { if (!is_whole_packet_present(f, TRUE)) { // convert error in ogg header to write type if (f->error == VORBIS_invalid_stream) f->error = VORBIS_invalid_setup; return FALSE; } } #endif crc32_init(); // always init it, to avoid multithread race conditions if (get8_packet(f) != VORBIS_packet_setup) return error(f, VORBIS_invalid_setup); for (i=0; i < 6; ++i) header[i] = get8_packet(f); if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup); // codebooks f->codebook_count = get_bits(f,8) + 1; f->codebooks = (Codebook *) setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count); if (f->codebooks == NULL) return error(f, VORBIS_outofmem); memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count); for (i=0; i < f->codebook_count; ++i) { uint32 *values; int ordered, sorted_count; int total=0; uint8 *lengths; Codebook *c = f->codebooks+i; CHECK(f); x = get_bits(f, 8); if (x != 0x42) return error(f, VORBIS_invalid_setup); x = get_bits(f, 8); if (x != 0x43) return error(f, VORBIS_invalid_setup); x = get_bits(f, 8); if (x != 0x56) return error(f, VORBIS_invalid_setup); x = get_bits(f, 8); c->dimensions = (get_bits(f, 8)<<8) + x; x = get_bits(f, 8); y = get_bits(f, 8); c->entries = (get_bits(f, 8)<<16) + (y<<8) + x; ordered = get_bits(f,1); c->sparse = ordered ? 0 : get_bits(f,1); if (c->dimensions == 0 && c->entries != 0) return error(f, VORBIS_invalid_setup); if (c->sparse) lengths = (uint8 *) setup_temp_malloc(f, c->entries); else lengths = c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries); if (!lengths) return error(f, VORBIS_outofmem); if (ordered) { int current_entry = 0; int current_length = get_bits(f,5) + 1; while (current_entry < c->entries) { int limit = c->entries - current_entry; int n = get_bits(f, ilog(limit)); if (current_length >= 32) return error(f, VORBIS_invalid_setup); if (current_entry + n > (int) c->entries) { return error(f, VORBIS_invalid_setup); } memset(lengths + current_entry, current_length, n); current_entry += n; ++current_length; } } else { for (j=0; j < c->entries; ++j) { int present = c->sparse ? get_bits(f,1) : 1; if (present) { lengths[j] = get_bits(f, 5) + 1; ++total; if (lengths[j] == 32) return error(f, VORBIS_invalid_setup); } else { lengths[j] = NO_CODE; } } } if (c->sparse && total >= c->entries >> 2) { // convert sparse items to non-sparse! if (c->entries > (int) f->setup_temp_memory_required) f->setup_temp_memory_required = c->entries; c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries); if (c->codeword_lengths == NULL) return error(f, VORBIS_outofmem); memcpy(c->codeword_lengths, lengths, c->entries); setup_temp_free(f, lengths, c->entries); // note this is only safe if there have been no intervening temp mallocs! lengths = c->codeword_lengths; c->sparse = 0; } // compute the size of the sorted tables if (c->sparse) { sorted_count = total; } else { sorted_count = 0; #ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH for (j=0; j < c->entries; ++j) if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE) ++sorted_count; #endif } c->sorted_entries = sorted_count; values = NULL; CHECK(f); if (!c->sparse) { c->codewords = (uint32 *) setup_malloc(f, sizeof(c->codewords[0]) * c->entries); if (!c->codewords) return error(f, VORBIS_outofmem); } else { unsigned int size; if (c->sorted_entries) { c->codeword_lengths = (uint8 *) setup_malloc(f, c->sorted_entries); if (!c->codeword_lengths) return error(f, VORBIS_outofmem); c->codewords = (uint32 *) setup_temp_malloc(f, sizeof(*c->codewords) * c->sorted_entries); if (!c->codewords) return error(f, VORBIS_outofmem); values = (uint32 *) setup_temp_malloc(f, sizeof(*values) * c->sorted_entries); if (!values) return error(f, VORBIS_outofmem); } size = c->entries + (sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries; if (size > f->setup_temp_memory_required) f->setup_temp_memory_required = size; } if (!compute_codewords(c, lengths, c->entries, values)) { if (c->sparse) setup_temp_free(f, values, 0); return error(f, VORBIS_invalid_setup); } if (c->sorted_entries) { // allocate an extra slot for sentinels c->sorted_codewords = (uint32 *) setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries+1)); if (c->sorted_codewords == NULL) return error(f, VORBIS_outofmem); // allocate an extra slot at the front so that c->sorted_values[-1] is defined // so that we can catch that case without an extra if c->sorted_values = ( int *) setup_malloc(f, sizeof(*c->sorted_values ) * (c->sorted_entries+1)); if (c->sorted_values == NULL) return error(f, VORBIS_outofmem); ++c->sorted_values; c->sorted_values[-1] = -1; compute_sorted_huffman(c, lengths, values); } if (c->sparse) { setup_temp_free(f, values, sizeof(*values)*c->sorted_entries); setup_temp_free(f, c->codewords, sizeof(*c->codewords)*c->sorted_entries); setup_temp_free(f, lengths, c->entries); c->codewords = NULL; } compute_accelerated_huffman(c); CHECK(f); c->lookup_type = get_bits(f, 4); if (c->lookup_type > 2) return error(f, VORBIS_invalid_setup); if (c->lookup_type > 0) { uint16 *mults; c->minimum_value = float32_unpack(get_bits(f, 32)); c->delta_value = float32_unpack(get_bits(f, 32)); c->value_bits = get_bits(f, 4)+1; c->sequence_p = get_bits(f,1); if (c->lookup_type == 1) { int values = lookup1_values(c->entries, c->dimensions); if (values < 0) return error(f, VORBIS_invalid_setup); c->lookup_values = (uint32) values; } else { c->lookup_values = c->entries * c->dimensions; } if (c->lookup_values == 0) return error(f, VORBIS_invalid_setup); mults = (uint16 *) setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values); if (mults == NULL) return error(f, VORBIS_outofmem); for (j=0; j < (int) c->lookup_values; ++j) { int q = get_bits(f, c->value_bits); if (q == EOP) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); } mults[j] = q; } #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { int len, sparse = c->sparse; float last=0; // pre-expand the lookup1-style multiplicands, to avoid a divide in the inner loop if (sparse) { if (c->sorted_entries == 0) goto skip; c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions); } else c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions); if (c->multiplicands == NULL) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); } len = sparse ? c->sorted_entries : c->entries; for (j=0; j < len; ++j) { unsigned int z = sparse ? c->sorted_values[j] : j; unsigned int div=1; for (k=0; k < c->dimensions; ++k) { int off = (z / div) % c->lookup_values; float val = mults[off]; val = mults[off]*c->delta_value + c->minimum_value + last; c->multiplicands[j*c->dimensions + k] = val; if (c->sequence_p) last = val; if (k+1 < c->dimensions) { if (div > UINT_MAX / (unsigned int) c->lookup_values) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); } div *= c->lookup_values; } } } c->lookup_type = 2; } else #endif { float last=0; CHECK(f); c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values); if (c->multiplicands == NULL) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); } for (j=0; j < (int) c->lookup_values; ++j) { float val = mults[j] * c->delta_value + c->minimum_value + last; c->multiplicands[j] = val; if (c->sequence_p) last = val; } } #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK skip:; #endif setup_temp_free(f, mults, sizeof(mults[0])*c->lookup_values); CHECK(f); } CHECK(f); } // time domain transfers (notused) x = get_bits(f, 6) + 1; for (i=0; i < x; ++i) { uint32 z = get_bits(f, 16); if (z != 0) return error(f, VORBIS_invalid_setup); } // Floors f->floor_count = get_bits(f, 6)+1; f->floor_config = (Floor *) setup_malloc(f, f->floor_count * sizeof(*f->floor_config)); if (f->floor_config == NULL) return error(f, VORBIS_outofmem); for (i=0; i < f->floor_count; ++i) { f->floor_types[i] = get_bits(f, 16); if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup); if (f->floor_types[i] == 0) { Floor0 *g = &f->floor_config[i].floor0; g->order = get_bits(f,8); g->rate = get_bits(f,16); g->bark_map_size = get_bits(f,16); g->amplitude_bits = get_bits(f,6); g->amplitude_offset = get_bits(f,8); g->number_of_books = get_bits(f,4) + 1; for (j=0; j < g->number_of_books; ++j) g->book_list[j] = get_bits(f,8); return error(f, VORBIS_feature_not_supported); } else { stbv__floor_ordering p[31*8+2]; Floor1 *g = &f->floor_config[i].floor1; int max_class = -1; g->partitions = get_bits(f, 5); for (j=0; j < g->partitions; ++j) { g->partition_class_list[j] = get_bits(f, 4); if (g->partition_class_list[j] > max_class) max_class = g->partition_class_list[j]; } for (j=0; j <= max_class; ++j) { g->class_dimensions[j] = get_bits(f, 3)+1; g->class_subclasses[j] = get_bits(f, 2); if (g->class_subclasses[j]) { g->class_masterbooks[j] = get_bits(f, 8); if (g->class_masterbooks[j] >= f->codebook_count) return error(f, VORBIS_invalid_setup); } for (k=0; k < 1 << g->class_subclasses[j]; ++k) { g->subclass_books[j][k] = get_bits(f,8)-1; if (g->subclass_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup); } } g->floor1_multiplier = get_bits(f,2)+1; g->rangebits = get_bits(f,4); g->Xlist[0] = 0; g->Xlist[1] = 1 << g->rangebits; g->values = 2; for (j=0; j < g->partitions; ++j) { int c = g->partition_class_list[j]; for (k=0; k < g->class_dimensions[c]; ++k) { g->Xlist[g->values] = get_bits(f, g->rangebits); ++g->values; } } // precompute the sorting for (j=0; j < g->values; ++j) { p[j].x = g->Xlist[j]; p[j].id = j; } qsort(p, g->values, sizeof(p[0]), point_compare); for (j=0; j < g->values-1; ++j) if (p[j].x == p[j+1].x) return error(f, VORBIS_invalid_setup); for (j=0; j < g->values; ++j) g->sorted_order[j] = (uint8) p[j].id; // precompute the neighbors for (j=2; j < g->values; ++j) { int low,hi; neighbors(g->Xlist, j, &low,&hi); g->neighbors[j][0] = low; g->neighbors[j][1] = hi; } if (g->values > longest_floorlist) longest_floorlist = g->values; } } // Residue f->residue_count = get_bits(f, 6)+1; f->residue_config = (Residue *) setup_malloc(f, f->residue_count * sizeof(f->residue_config[0])); if (f->residue_config == NULL) return error(f, VORBIS_outofmem); memset(f->residue_config, 0, f->residue_count * sizeof(f->residue_config[0])); for (i=0; i < f->residue_count; ++i) { uint8 residue_cascade[64]; Residue *r = f->residue_config+i; f->residue_types[i] = get_bits(f, 16); if (f->residue_types[i] > 2) return error(f, VORBIS_invalid_setup); r->begin = get_bits(f, 24); r->end = get_bits(f, 24); if (r->end < r->begin) return error(f, VORBIS_invalid_setup); r->part_size = get_bits(f,24)+1; r->classifications = get_bits(f,6)+1; r->classbook = get_bits(f,8); if (r->classbook >= f->codebook_count) return error(f, VORBIS_invalid_setup); for (j=0; j < r->classifications; ++j) { uint8 high_bits=0; uint8 low_bits=get_bits(f,3); if (get_bits(f,1)) high_bits = get_bits(f,5); residue_cascade[j] = high_bits*8 + low_bits; } r->residue_books = (short (*)[8]) setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications); if (r->residue_books == NULL) return error(f, VORBIS_outofmem); for (j=0; j < r->classifications; ++j) { for (k=0; k < 8; ++k) { if (residue_cascade[j] & (1 << k)) { r->residue_books[j][k] = get_bits(f, 8); if (r->residue_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup); } else { r->residue_books[j][k] = -1; } } } // precompute the classifications[] array to avoid inner-loop mod/divide // call it 'classdata' since we already have r->classifications r->classdata = (uint8 **) setup_malloc(f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries); if (!r->classdata) return error(f, VORBIS_outofmem); memset(r->classdata, 0, sizeof(*r->classdata) * f->codebooks[r->classbook].entries); for (j=0; j < f->codebooks[r->classbook].entries; ++j) { int classwords = f->codebooks[r->classbook].dimensions; int temp = j; r->classdata[j] = (uint8 *) setup_malloc(f, sizeof(r->classdata[j][0]) * classwords); if (r->classdata[j] == NULL) return error(f, VORBIS_outofmem); for (k=classwords-1; k >= 0; --k) { r->classdata[j][k] = temp % r->classifications; temp /= r->classifications; } } } f->mapping_count = get_bits(f,6)+1; f->mapping = (Mapping *) setup_malloc(f, f->mapping_count * sizeof(*f->mapping)); if (f->mapping == NULL) return error(f, VORBIS_outofmem); memset(f->mapping, 0, f->mapping_count * sizeof(*f->mapping)); for (i=0; i < f->mapping_count; ++i) { Mapping *m = f->mapping + i; int mapping_type = get_bits(f,16); if (mapping_type != 0) return error(f, VORBIS_invalid_setup); m->chan = (MappingChannel *) setup_malloc(f, f->channels * sizeof(*m->chan)); if (m->chan == NULL) return error(f, VORBIS_outofmem); if (get_bits(f,1)) m->submaps = get_bits(f,4)+1; else m->submaps = 1; if (m->submaps > max_submaps) max_submaps = m->submaps; if (get_bits(f,1)) { m->coupling_steps = get_bits(f,8)+1; if (m->coupling_steps > f->channels) return error(f, VORBIS_invalid_setup); for (k=0; k < m->coupling_steps; ++k) { m->chan[k].magnitude = get_bits(f, ilog(f->channels-1)); m->chan[k].angle = get_bits(f, ilog(f->channels-1)); if (m->chan[k].magnitude >= f->channels) return error(f, VORBIS_invalid_setup); if (m->chan[k].angle >= f->channels) return error(f, VORBIS_invalid_setup); if (m->chan[k].magnitude == m->chan[k].angle) return error(f, VORBIS_invalid_setup); } } else m->coupling_steps = 0; // reserved field if (get_bits(f,2)) return error(f, VORBIS_invalid_setup); if (m->submaps > 1) { for (j=0; j < f->channels; ++j) { m->chan[j].mux = get_bits(f, 4); if (m->chan[j].mux >= m->submaps) return error(f, VORBIS_invalid_setup); } } else // @SPECIFICATION: this case is missing from the spec for (j=0; j < f->channels; ++j) m->chan[j].mux = 0; for (j=0; j < m->submaps; ++j) { get_bits(f,8); // discard m->submap_floor[j] = get_bits(f,8); m->submap_residue[j] = get_bits(f,8); if (m->submap_floor[j] >= f->floor_count) return error(f, VORBIS_invalid_setup); if (m->submap_residue[j] >= f->residue_count) return error(f, VORBIS_invalid_setup); } } // Modes f->mode_count = get_bits(f, 6)+1; for (i=0; i < f->mode_count; ++i) { Mode *m = f->mode_config+i; m->blockflag = get_bits(f,1); m->windowtype = get_bits(f,16); m->transformtype = get_bits(f,16); m->mapping = get_bits(f,8); if (m->windowtype != 0) return error(f, VORBIS_invalid_setup); if (m->transformtype != 0) return error(f, VORBIS_invalid_setup); if (m->mapping >= f->mapping_count) return error(f, VORBIS_invalid_setup); } flush_packet(f); f->previous_length = 0; for (i=0; i < f->channels; ++i) { f->channel_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1); f->previous_window[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2); f->finalY[i] = (int16 *) setup_malloc(f, sizeof(int16) * longest_floorlist); if (f->channel_buffers[i] == NULL || f->previous_window[i] == NULL || f->finalY[i] == NULL) return error(f, VORBIS_outofmem); memset(f->channel_buffers[i], 0, sizeof(float) * f->blocksize_1); #ifdef STB_VORBIS_NO_DEFER_FLOOR f->floor_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2); if (f->floor_buffers[i] == NULL) return error(f, VORBIS_outofmem); #endif } if (!init_blocksize(f, 0, f->blocksize_0)) return FALSE; if (!init_blocksize(f, 1, f->blocksize_1)) return FALSE; f->blocksize[0] = f->blocksize_0; f->blocksize[1] = f->blocksize_1; #ifdef STB_VORBIS_DIVIDE_TABLE if (integer_divide_table[1][1]==0) for (i=0; i < DIVTAB_NUMER; ++i) for (j=1; j < DIVTAB_DENOM; ++j) integer_divide_table[i][j] = i / j; #endif // compute how much temporary memory is needed // 1. { uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1); uint32 classify_mem; int i,max_part_read=0; for (i=0; i < f->residue_count; ++i) { Residue *r = f->residue_config + i; unsigned int actual_size = f->blocksize_1 / 2; unsigned int limit_r_begin = r->begin < actual_size ? r->begin : actual_size; unsigned int limit_r_end = r->end < actual_size ? r->end : actual_size; int n_read = limit_r_end - limit_r_begin; int part_read = n_read / r->part_size; if (part_read > max_part_read) max_part_read = part_read; } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(uint8 *)); #else classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int *)); #endif // maximum reasonable partition size is f->blocksize_1 f->temp_memory_required = classify_mem; if (imdct_mem > f->temp_memory_required) f->temp_memory_required = imdct_mem; } f->first_decode = TRUE; if (f->alloc.alloc_buffer) { assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes); // check if there's enough temp memory so we don't error later if (f->setup_offset + sizeof(*f) + f->temp_memory_required > (unsigned) f->temp_offset) return error(f, VORBIS_outofmem); } f->first_audio_page_offset = stb_vorbis_get_file_offset(f); return TRUE; } static void vorbis_deinit(stb_vorbis *p) { int i,j; if (p->residue_config) { for (i=0; i < p->residue_count; ++i) { Residue *r = p->residue_config+i; if (r->classdata) { for (j=0; j < p->codebooks[r->classbook].entries; ++j) setup_free(p, r->classdata[j]); setup_free(p, r->classdata); } setup_free(p, r->residue_books); } } if (p->codebooks) { CHECK(p); for (i=0; i < p->codebook_count; ++i) { Codebook *c = p->codebooks + i; setup_free(p, c->codeword_lengths); setup_free(p, c->multiplicands); setup_free(p, c->codewords); setup_free(p, c->sorted_codewords); // c->sorted_values[-1] is the first entry in the array setup_free(p, c->sorted_values ? c->sorted_values-1 : NULL); } setup_free(p, p->codebooks); } setup_free(p, p->floor_config); setup_free(p, p->residue_config); if (p->mapping) { for (i=0; i < p->mapping_count; ++i) setup_free(p, p->mapping[i].chan); setup_free(p, p->mapping); } CHECK(p); for (i=0; i < p->channels && i < STB_VORBIS_MAX_CHANNELS; ++i) { setup_free(p, p->channel_buffers[i]); setup_free(p, p->previous_window[i]); #ifdef STB_VORBIS_NO_DEFER_FLOOR setup_free(p, p->floor_buffers[i]); #endif setup_free(p, p->finalY[i]); } for (i=0; i < 2; ++i) { setup_free(p, p->A[i]); setup_free(p, p->B[i]); setup_free(p, p->C[i]); setup_free(p, p->window[i]); setup_free(p, p->bit_reverse[i]); } #ifndef STB_VORBIS_NO_STDIO if (p->close_on_free) fclose(p->f); #endif } void stb_vorbis_close(stb_vorbis *p) { if (p == NULL) return; vorbis_deinit(p); setup_free(p,p); } static void vorbis_init(stb_vorbis *p, const stb_vorbis_alloc *z) { memset(p, 0, sizeof(*p)); // NULL out all malloc'd pointers to start if (z) { p->alloc = *z; p->alloc.alloc_buffer_length_in_bytes = (p->alloc.alloc_buffer_length_in_bytes+3) & ~3; p->temp_offset = p->alloc.alloc_buffer_length_in_bytes; } p->eof = 0; p->error = VORBIS__no_error; p->stream = NULL; p->codebooks = NULL; p->page_crc_tests = -1; #ifndef STB_VORBIS_NO_STDIO p->close_on_free = FALSE; p->f = NULL; #endif } int stb_vorbis_get_sample_offset(stb_vorbis *f) { if (f->current_loc_valid) return f->current_loc; else return -1; } stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f) { stb_vorbis_info d; d.channels = f->channels; d.sample_rate = f->sample_rate; d.setup_memory_required = f->setup_memory_required; d.setup_temp_memory_required = f->setup_temp_memory_required; d.temp_memory_required = f->temp_memory_required; d.max_frame_size = f->blocksize_1 >> 1; return d; } int stb_vorbis_get_error(stb_vorbis *f) { int e = f->error; f->error = VORBIS__no_error; return e; } static stb_vorbis * vorbis_alloc(stb_vorbis *f) { stb_vorbis *p = (stb_vorbis *) setup_malloc(f, sizeof(*p)); return p; } #ifndef STB_VORBIS_NO_PUSHDATA_API void stb_vorbis_flush_pushdata(stb_vorbis *f) { f->previous_length = 0; f->page_crc_tests = 0; f->discard_samples_deferred = 0; f->current_loc_valid = FALSE; f->first_decode = FALSE; f->samples_output = 0; f->channel_buffer_start = 0; f->channel_buffer_end = 0; } static int vorbis_search_for_page_pushdata(vorb *f, uint8 *data, int data_len) { int i,n; for (i=0; i < f->page_crc_tests; ++i) f->scan[i].bytes_done = 0; // if we have room for more scans, search for them first, because // they may cause us to stop early if their header is incomplete if (f->page_crc_tests < STB_VORBIS_PUSHDATA_CRC_COUNT) { if (data_len < 4) return 0; data_len -= 3; // need to look for 4-byte sequence, so don't miss // one that straddles a boundary for (i=0; i < data_len; ++i) { if (data[i] == 0x4f) { if (0==memcmp(data+i, ogg_page_header, 4)) { int j,len; uint32 crc; // make sure we have the whole page header if (i+26 >= data_len || i+27+data[i+26] >= data_len) { // only read up to this page start, so hopefully we'll // have the whole page header start next time data_len = i; break; } // ok, we have it all; compute the length of the page len = 27 + data[i+26]; for (j=0; j < data[i+26]; ++j) len += data[i+27+j]; // scan everything up to the embedded crc (which we must 0) crc = 0; for (j=0; j < 22; ++j) crc = crc32_update(crc, data[i+j]); // now process 4 0-bytes for ( ; j < 26; ++j) crc = crc32_update(crc, 0); // len is the total number of bytes we need to scan n = f->page_crc_tests++; f->scan[n].bytes_left = len-j; f->scan[n].crc_so_far = crc; f->scan[n].goal_crc = data[i+22] + (data[i+23] << 8) + (data[i+24]<<16) + (data[i+25]<<24); // if the last frame on a page is continued to the next, then // we can't recover the sample_loc immediately if (data[i+27+data[i+26]-1] == 255) f->scan[n].sample_loc = ~0; else f->scan[n].sample_loc = data[i+6] + (data[i+7] << 8) + (data[i+ 8]<<16) + (data[i+ 9]<<24); f->scan[n].bytes_done = i+j; if (f->page_crc_tests == STB_VORBIS_PUSHDATA_CRC_COUNT) break; // keep going if we still have room for more } } } } for (i=0; i < f->page_crc_tests;) { uint32 crc; int j; int n = f->scan[i].bytes_done; int m = f->scan[i].bytes_left; if (m > data_len - n) m = data_len - n; // m is the bytes to scan in the current chunk crc = f->scan[i].crc_so_far; for (j=0; j < m; ++j) crc = crc32_update(crc, data[n+j]); f->scan[i].bytes_left -= m; f->scan[i].crc_so_far = crc; if (f->scan[i].bytes_left == 0) { // does it match? if (f->scan[i].crc_so_far == f->scan[i].goal_crc) { // Houston, we have page data_len = n+m; // consumption amount is wherever that scan ended f->page_crc_tests = -1; // drop out of page scan mode f->previous_length = 0; // decode-but-don't-output one frame f->next_seg = -1; // start a new page f->current_loc = f->scan[i].sample_loc; // set the current sample location // to the amount we'd have decoded had we decoded this page f->current_loc_valid = f->current_loc != ~0U; return data_len; } // delete entry f->scan[i] = f->scan[--f->page_crc_tests]; } else { ++i; } } return data_len; } // return value: number of bytes we used int stb_vorbis_decode_frame_pushdata( stb_vorbis *f, // the file we're decoding const uint8 *data, int data_len, // the memory available for decoding int *channels, // place to write number of float * buffers float ***output, // place to write float ** array of float * buffers int *samples // place to write number of output samples ) { int i; int len,right,left; if (!IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); if (f->page_crc_tests >= 0) { *samples = 0; return vorbis_search_for_page_pushdata(f, (uint8 *) data, data_len); } f->stream = (uint8 *) data; f->stream_end = (uint8 *) data + data_len; f->error = VORBIS__no_error; // check that we have the entire packet in memory if (!is_whole_packet_present(f, FALSE)) { *samples = 0; return 0; } if (!vorbis_decode_packet(f, &len, &left, &right)) { // save the actual error we encountered enum STBVorbisError error = f->error; if (error == VORBIS_bad_packet_type) { // flush and resynch f->error = VORBIS__no_error; while (get8_packet(f) != EOP) if (f->eof) break; *samples = 0; return (int) (f->stream - data); } if (error == VORBIS_continued_packet_flag_invalid) { if (f->previous_length == 0) { // we may be resynching, in which case it's ok to hit one // of these; just discard the packet f->error = VORBIS__no_error; while (get8_packet(f) != EOP) if (f->eof) break; *samples = 0; return (int) (f->stream - data); } } // if we get an error while parsing, what to do? // well, it DEFINITELY won't work to continue from where we are! stb_vorbis_flush_pushdata(f); // restore the error that actually made us bail f->error = error; *samples = 0; return 1; } // success! len = vorbis_finish_frame(f, len, left, right); for (i=0; i < f->channels; ++i) f->outputs[i] = f->channel_buffers[i] + left; if (channels) *channels = f->channels; *samples = len; *output = f->outputs; return (int) (f->stream - data); } stb_vorbis *stb_vorbis_open_pushdata( const unsigned char *data, int data_len, // the memory available for decoding int *data_used, // only defined if result is not NULL int *error, const stb_vorbis_alloc *alloc) { stb_vorbis *f, p; vorbis_init(&p, alloc); p.stream = (uint8 *) data; p.stream_end = (uint8 *) data + data_len; p.push_mode = TRUE; if (!start_decoder(&p)) { if (p.eof) *error = VORBIS_need_more_data; else *error = p.error; return NULL; } f = vorbis_alloc(&p); if (f) { *f = p; *data_used = (int) (f->stream - data); *error = 0; return f; } else { vorbis_deinit(&p); return NULL; } } #endif // STB_VORBIS_NO_PUSHDATA_API unsigned int stb_vorbis_get_file_offset(stb_vorbis *f) { #ifndef STB_VORBIS_NO_PUSHDATA_API if (f->push_mode) return 0; #endif if (USE_MEMORY(f)) return (unsigned int) (f->stream - f->stream_start); #ifndef STB_VORBIS_NO_STDIO return (unsigned int) (ftell(f->f) - f->f_start); #endif } #ifndef STB_VORBIS_NO_PULLDATA_API // // DATA-PULLING API // static uint32 vorbis_find_page(stb_vorbis *f, uint32 *end, uint32 *last) { for(;;) { int n; if (f->eof) return 0; n = get8(f); if (n == 0x4f) { // page header candidate unsigned int retry_loc = stb_vorbis_get_file_offset(f); int i; // check if we're off the end of a file_section stream if (retry_loc - 25 > f->stream_len) return 0; // check the rest of the header for (i=1; i < 4; ++i) if (get8(f) != ogg_page_header[i]) break; if (f->eof) return 0; if (i == 4) { uint8 header[27]; uint32 i, crc, goal, len; for (i=0; i < 4; ++i) header[i] = ogg_page_header[i]; for (; i < 27; ++i) header[i] = get8(f); if (f->eof) return 0; if (header[4] != 0) goto invalid; goal = header[22] + (header[23] << 8) + (header[24]<<16) + (header[25]<<24); for (i=22; i < 26; ++i) header[i] = 0; crc = 0; for (i=0; i < 27; ++i) crc = crc32_update(crc, header[i]); len = 0; for (i=0; i < header[26]; ++i) { int s = get8(f); crc = crc32_update(crc, s); len += s; } if (len && f->eof) return 0; for (i=0; i < len; ++i) crc = crc32_update(crc, get8(f)); // finished parsing probable page if (crc == goal) { // we could now check that it's either got the last // page flag set, OR it's followed by the capture // pattern, but I guess TECHNICALLY you could have // a file with garbage between each ogg page and recover // from it automatically? So even though that paranoia // might decrease the chance of an invalid decode by // another 2^32, not worth it since it would hose those // invalid-but-useful files? if (end) *end = stb_vorbis_get_file_offset(f); if (last) { if (header[5] & 0x04) *last = 1; else *last = 0; } set_file_offset(f, retry_loc-1); return 1; } } invalid: // not a valid page, so rewind and look for next one set_file_offset(f, retry_loc); } } } #define SAMPLE_unknown 0xffffffff // seeking is implemented with a binary search, which narrows down the range to // 64K, before using a linear search (because finding the synchronization // pattern can be expensive, and the chance we'd find the end page again is // relatively high for small ranges) // // two initial interpolation-style probes are used at the start of the search // to try to bound either side of the binary search sensibly, while still // working in O(log n) time if they fail. static int get_seek_page_info(stb_vorbis *f, ProbedPage *z) { uint8 header[27], lacing[255]; int i,len; // record where the page starts z->page_start = stb_vorbis_get_file_offset(f); // parse the header getn(f, header, 27); if (header[0] != 'O' || header[1] != 'g' || header[2] != 'g' || header[3] != 'S') return 0; getn(f, lacing, header[26]); // determine the length of the payload len = 0; for (i=0; i < header[26]; ++i) len += lacing[i]; // this implies where the page ends z->page_end = z->page_start + 27 + header[26] + len; // read the last-decoded sample out of the data z->last_decoded_sample = header[6] + (header[7] << 8) + (header[8] << 16) + (header[9] << 24); // restore file state to where we were set_file_offset(f, z->page_start); return 1; } // rarely used function to seek back to the preceding page while finding the // start of a packet static int go_to_page_before(stb_vorbis *f, unsigned int limit_offset) { unsigned int previous_safe, end; // now we want to seek back 64K from the limit if (limit_offset >= 65536 && limit_offset-65536 >= f->first_audio_page_offset) previous_safe = limit_offset - 65536; else previous_safe = f->first_audio_page_offset; set_file_offset(f, previous_safe); while (vorbis_find_page(f, &end, NULL)) { if (end >= limit_offset && stb_vorbis_get_file_offset(f) < limit_offset) return 1; set_file_offset(f, end); } return 0; } // implements the search logic for finding a page and starting decoding. if // the function succeeds, current_loc_valid will be true and current_loc will // be less than or equal to the provided sample number (the closer the // better). static int seek_to_sample_coarse(stb_vorbis *f, uint32 sample_number) { ProbedPage left, right, mid; int i, start_seg_with_known_loc, end_pos, page_start; uint32 delta, stream_length, padding; double offset, bytes_per_sample; int probe = 0; // find the last page and validate the target sample stream_length = stb_vorbis_stream_length_in_samples(f); if (stream_length == 0) return error(f, VORBIS_seek_without_length); if (sample_number > stream_length) return error(f, VORBIS_seek_invalid); // this is the maximum difference between the window-center (which is the // actual granule position value), and the right-start (which the spec // indicates should be the granule position (give or take one)). padding = ((f->blocksize_1 - f->blocksize_0) >> 2); if (sample_number < padding) sample_number = 0; else sample_number -= padding; left = f->p_first; while (left.last_decoded_sample == ~0U) { // (untested) the first page does not have a 'last_decoded_sample' set_file_offset(f, left.page_end); if (!get_seek_page_info(f, &left)) goto error; } right = f->p_last; assert(right.last_decoded_sample != ~0U); // starting from the start is handled differently if (sample_number <= left.last_decoded_sample) { if (stb_vorbis_seek_start(f)) return 1; return 0; } while (left.page_end != right.page_start) { assert(left.page_end < right.page_start); // search range in bytes delta = right.page_start - left.page_end; if (delta <= 65536) { // there's only 64K left to search - handle it linearly set_file_offset(f, left.page_end); } else { if (probe < 2) { if (probe == 0) { // first probe (interpolate) double data_bytes = right.page_end - left.page_start; bytes_per_sample = data_bytes / right.last_decoded_sample; offset = left.page_start + bytes_per_sample * (sample_number - left.last_decoded_sample); } else { // second probe (try to bound the other side) double error = ((double) sample_number - mid.last_decoded_sample) * bytes_per_sample; if (error >= 0 && error < 8000) error = 8000; if (error < 0 && error > -8000) error = -8000; offset += error * 2; } // ensure the offset is valid if (offset < left.page_end) offset = left.page_end; if (offset > right.page_start - 65536) offset = right.page_start - 65536; set_file_offset(f, (unsigned int) offset); } else { // binary search for large ranges (offset by 32K to ensure // we don't hit the right page) set_file_offset(f, left.page_end + (delta / 2) - 32768); } if (!vorbis_find_page(f, NULL, NULL)) goto error; } for (;;) { if (!get_seek_page_info(f, &mid)) goto error; if (mid.last_decoded_sample != ~0U) break; // (untested) no frames end on this page set_file_offset(f, mid.page_end); assert(mid.page_start < right.page_start); } // if we've just found the last page again then we're in a tricky file, // and we're close enough. if (mid.page_start == right.page_start) break; if (sample_number < mid.last_decoded_sample) right = mid; else left = mid; ++probe; } // seek back to start of the last packet page_start = left.page_start; set_file_offset(f, page_start); if (!start_page(f)) return error(f, VORBIS_seek_failed); end_pos = f->end_seg_with_known_loc; assert(end_pos >= 0); for (;;) { for (i = end_pos; i > 0; --i) if (f->segments[i-1] != 255) break; start_seg_with_known_loc = i; if (start_seg_with_known_loc > 0 || !(f->page_flag & PAGEFLAG_continued_packet)) break; // (untested) the final packet begins on an earlier page if (!go_to_page_before(f, page_start)) goto error; page_start = stb_vorbis_get_file_offset(f); if (!start_page(f)) goto error; end_pos = f->segment_count - 1; } // prepare to start decoding f->current_loc_valid = FALSE; f->last_seg = FALSE; f->valid_bits = 0; f->packet_bytes = 0; f->bytes_in_seg = 0; f->previous_length = 0; f->next_seg = start_seg_with_known_loc; for (i = 0; i < start_seg_with_known_loc; i++) skip(f, f->segments[i]); // start decoding (optimizable - this frame is generally discarded) if (!vorbis_pump_first_frame(f)) return 0; if (f->current_loc > sample_number) return error(f, VORBIS_seek_failed); return 1; error: // try to restore the file to a valid state stb_vorbis_seek_start(f); return error(f, VORBIS_seek_failed); } // the same as vorbis_decode_initial, but without advancing static int peek_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode) { int bits_read, bytes_read; if (!vorbis_decode_initial(f, p_left_start, p_left_end, p_right_start, p_right_end, mode)) return 0; // either 1 or 2 bytes were read, figure out which so we can rewind bits_read = 1 + ilog(f->mode_count-1); if (f->mode_config[*mode].blockflag) bits_read += 2; bytes_read = (bits_read + 7) / 8; f->bytes_in_seg += bytes_read; f->packet_bytes -= bytes_read; skip(f, -bytes_read); if (f->next_seg == -1) f->next_seg = f->segment_count - 1; else f->next_seg--; f->valid_bits = 0; return 1; } int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number) { uint32 max_frame_samples; if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); // fast page-level search if (!seek_to_sample_coarse(f, sample_number)) return 0; assert(f->current_loc_valid); assert(f->current_loc <= sample_number); // linear search for the relevant packet max_frame_samples = (f->blocksize_1*3 - f->blocksize_0) >> 2; while (f->current_loc < sample_number) { int left_start, left_end, right_start, right_end, mode, frame_samples; if (!peek_decode_initial(f, &left_start, &left_end, &right_start, &right_end, &mode)) return error(f, VORBIS_seek_failed); // calculate the number of samples returned by the next frame frame_samples = right_start - left_start; if (f->current_loc + frame_samples > sample_number) { return 1; // the next frame will contain the sample } else if (f->current_loc + frame_samples + max_frame_samples > sample_number) { // there's a chance the frame after this could contain the sample vorbis_pump_first_frame(f); } else { // this frame is too early to be relevant f->current_loc += frame_samples; f->previous_length = 0; maybe_start_packet(f); flush_packet(f); } } // the next frame will start with the sample assert(f->current_loc == sample_number); return 1; } int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number) { if (!stb_vorbis_seek_frame(f, sample_number)) return 0; if (sample_number != f->current_loc) { int n; uint32 frame_start = f->current_loc; stb_vorbis_get_frame_float(f, &n, NULL); assert(sample_number > frame_start); assert(f->channel_buffer_start + (int) (sample_number-frame_start) <= f->channel_buffer_end); f->channel_buffer_start += (sample_number - frame_start); } return 1; } int stb_vorbis_seek_start(stb_vorbis *f) { if (IS_PUSH_MODE(f)) { return error(f, VORBIS_invalid_api_mixing); } set_file_offset(f, f->first_audio_page_offset); f->previous_length = 0; f->first_decode = TRUE; f->next_seg = -1; return vorbis_pump_first_frame(f); } unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f) { unsigned int restore_offset, previous_safe; unsigned int end, last_page_loc; if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); if (!f->total_samples) { unsigned int last; uint32 lo,hi; char header[6]; // first, store the current decode position so we can restore it restore_offset = stb_vorbis_get_file_offset(f); // now we want to seek back 64K from the end (the last page must // be at most a little less than 64K, but let's allow a little slop) if (f->stream_len >= 65536 && f->stream_len-65536 >= f->first_audio_page_offset) previous_safe = f->stream_len - 65536; else previous_safe = f->first_audio_page_offset; set_file_offset(f, previous_safe); // previous_safe is now our candidate 'earliest known place that seeking // to will lead to the final page' if (!vorbis_find_page(f, &end, &last)) { // if we can't find a page, we're hosed! f->error = VORBIS_cant_find_last_page; f->total_samples = 0xffffffff; goto done; } // check if there are more pages last_page_loc = stb_vorbis_get_file_offset(f); // stop when the last_page flag is set, not when we reach eof; // this allows us to stop short of a 'file_section' end without // explicitly checking the length of the section while (!last) { set_file_offset(f, end); if (!vorbis_find_page(f, &end, &last)) { // the last page we found didn't have the 'last page' flag // set. whoops! break; } previous_safe = last_page_loc+1; last_page_loc = stb_vorbis_get_file_offset(f); } set_file_offset(f, last_page_loc); // parse the header getn(f, (unsigned char *)header, 6); // extract the absolute granule position lo = get32(f); hi = get32(f); if (lo == 0xffffffff && hi == 0xffffffff) { f->error = VORBIS_cant_find_last_page; f->total_samples = SAMPLE_unknown; goto done; } if (hi) lo = 0xfffffffe; // saturate f->total_samples = lo; f->p_last.page_start = last_page_loc; f->p_last.page_end = end; f->p_last.last_decoded_sample = lo; done: set_file_offset(f, restore_offset); } return f->total_samples == SAMPLE_unknown ? 0 : f->total_samples; } float stb_vorbis_stream_length_in_seconds(stb_vorbis *f) { return stb_vorbis_stream_length_in_samples(f) / (float) f->sample_rate; } int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output) { int len, right,left,i; if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); if (!vorbis_decode_packet(f, &len, &left, &right)) { f->channel_buffer_start = f->channel_buffer_end = 0; return 0; } len = vorbis_finish_frame(f, len, left, right); for (i=0; i < f->channels; ++i) f->outputs[i] = f->channel_buffers[i] + left; f->channel_buffer_start = left; f->channel_buffer_end = left+len; if (channels) *channels = f->channels; if (output) *output = f->outputs; return len; } #ifndef STB_VORBIS_NO_STDIO stb_vorbis * stb_vorbis_open_file_section(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc, unsigned int length) { stb_vorbis *f, p; vorbis_init(&p, alloc); p.f = file; p.f_start = (uint32) ftell(file); p.stream_len = length; p.close_on_free = close_on_free; if (start_decoder(&p)) { f = vorbis_alloc(&p); if (f) { *f = p; vorbis_pump_first_frame(f); return f; } } if (error) *error = p.error; vorbis_deinit(&p); return NULL; } stb_vorbis * stb_vorbis_open_file(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc) { unsigned int len, start; start = (unsigned int) ftell(file); fseek(file, 0, SEEK_END); len = (unsigned int) (ftell(file) - start); fseek(file, start, SEEK_SET); return stb_vorbis_open_file_section(file, close_on_free, error, alloc, len); } stb_vorbis * stb_vorbis_open_filename(const char *filename, int *error, const stb_vorbis_alloc *alloc) { FILE *f; #if defined(_WIN32) && defined(__STDC_WANT_SECURE_LIB__) if (0 != fopen_s(&f, filename, "rb")) f = NULL; #else f = fopen(filename, "rb"); #endif if (f) return stb_vorbis_open_file(f, TRUE, error, alloc); if (error) *error = VORBIS_file_open_failure; return NULL; } #endif // STB_VORBIS_NO_STDIO stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, int *error, const stb_vorbis_alloc *alloc) { stb_vorbis *f, p; if (data == NULL) return NULL; vorbis_init(&p, alloc); p.stream = (uint8 *) data; p.stream_end = (uint8 *) data + len; p.stream_start = (uint8 *) p.stream; p.stream_len = len; p.push_mode = FALSE; if (start_decoder(&p)) { f = vorbis_alloc(&p); if (f) { *f = p; vorbis_pump_first_frame(f); if (error) *error = VORBIS__no_error; return f; } } if (error) *error = p.error; vorbis_deinit(&p); return NULL; } #ifndef STB_VORBIS_NO_INTEGER_CONVERSION #define PLAYBACK_MONO 1 #define PLAYBACK_LEFT 2 #define PLAYBACK_RIGHT 4 #define L (PLAYBACK_LEFT | PLAYBACK_MONO) #define C (PLAYBACK_LEFT | PLAYBACK_RIGHT | PLAYBACK_MONO) #define R (PLAYBACK_RIGHT | PLAYBACK_MONO) static int8 channel_position[7][6] = { { 0 }, { C }, { L, R }, { L, C, R }, { L, R, L, R }, { L, C, R, L, R }, { L, C, R, L, R, C }, }; #ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT typedef union { float f; int i; } float_conv; typedef char stb_vorbis_float_size_test[sizeof(float)==4 && sizeof(int) == 4]; #define FASTDEF(x) float_conv x // add (1<<23) to convert to int, then divide by 2^SHIFT, then add 0.5/2^SHIFT to round #define MAGIC(SHIFT) (1.5f * (1 << (23-SHIFT)) + 0.5f/(1 << SHIFT)) #define ADDEND(SHIFT) (((150-SHIFT) << 23) + (1 << 22)) #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) (temp.f = (x) + MAGIC(s), temp.i - ADDEND(s)) #define check_endianness() #else #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) ((int) ((x) * (1 << (s)))) #define check_endianness() #define FASTDEF(x) #endif static void copy_samples(short *dest, float *src, int len) { int i; check_endianness(); for (i=0; i < len; ++i) { FASTDEF(temp); int v = FAST_SCALED_FLOAT_TO_INT(temp, src[i],15); if ((unsigned int) (v + 32768) > 65535) v = v < 0 ? -32768 : 32767; dest[i] = v; } } static void compute_samples(int mask, short *output, int num_c, float **data, int d_offset, int len) { #define BUFFER_SIZE 32 float buffer[BUFFER_SIZE]; int i,j,o,n = BUFFER_SIZE; check_endianness(); for (o = 0; o < len; o += BUFFER_SIZE) { memset(buffer, 0, sizeof(buffer)); if (o + n > len) n = len - o; for (j=0; j < num_c; ++j) { if (channel_position[num_c][j] & mask) { for (i=0; i < n; ++i) buffer[i] += data[j][d_offset+o+i]; } } for (i=0; i < n; ++i) { FASTDEF(temp); int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15); if ((unsigned int) (v + 32768) > 65535) v = v < 0 ? -32768 : 32767; output[o+i] = v; } } } static void compute_stereo_samples(short *output, int num_c, float **data, int d_offset, int len) { #define BUFFER_SIZE 32 float buffer[BUFFER_SIZE]; int i,j,o,n = BUFFER_SIZE >> 1; // o is the offset in the source data check_endianness(); for (o = 0; o < len; o += BUFFER_SIZE >> 1) { // o2 is the offset in the output data int o2 = o << 1; memset(buffer, 0, sizeof(buffer)); if (o + n > len) n = len - o; for (j=0; j < num_c; ++j) { int m = channel_position[num_c][j] & (PLAYBACK_LEFT | PLAYBACK_RIGHT); if (m == (PLAYBACK_LEFT | PLAYBACK_RIGHT)) { for (i=0; i < n; ++i) { buffer[i*2+0] += data[j][d_offset+o+i]; buffer[i*2+1] += data[j][d_offset+o+i]; } } else if (m == PLAYBACK_LEFT) { for (i=0; i < n; ++i) { buffer[i*2+0] += data[j][d_offset+o+i]; } } else if (m == PLAYBACK_RIGHT) { for (i=0; i < n; ++i) { buffer[i*2+1] += data[j][d_offset+o+i]; } } } for (i=0; i < (n<<1); ++i) { FASTDEF(temp); int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15); if ((unsigned int) (v + 32768) > 65535) v = v < 0 ? -32768 : 32767; output[o2+i] = v; } } } static void convert_samples_short(int buf_c, short **buffer, int b_offset, int data_c, float **data, int d_offset, int samples) { int i; if (buf_c != data_c && buf_c <= 2 && data_c <= 6) { static int channel_selector[3][2] = { {0}, {PLAYBACK_MONO}, {PLAYBACK_LEFT, PLAYBACK_RIGHT} }; for (i=0; i < buf_c; ++i) compute_samples(channel_selector[buf_c][i], buffer[i]+b_offset, data_c, data, d_offset, samples); } else { int limit = buf_c < data_c ? buf_c : data_c; for (i=0; i < limit; ++i) copy_samples(buffer[i]+b_offset, data[i]+d_offset, samples); for ( ; i < buf_c; ++i) memset(buffer[i]+b_offset, 0, sizeof(short) * samples); } } int stb_vorbis_get_frame_short(stb_vorbis *f, int num_c, short **buffer, int num_samples) { float **output; int len = stb_vorbis_get_frame_float(f, NULL, &output); if (len > num_samples) len = num_samples; if (len) convert_samples_short(num_c, buffer, 0, f->channels, output, 0, len); return len; } static void convert_channels_short_interleaved(int buf_c, short *buffer, int data_c, float **data, int d_offset, int len) { int i; check_endianness(); if (buf_c != data_c && buf_c <= 2 && data_c <= 6) { assert(buf_c == 2); for (i=0; i < buf_c; ++i) compute_stereo_samples(buffer, data_c, data, d_offset, len); } else { int limit = buf_c < data_c ? buf_c : data_c; int j; for (j=0; j < len; ++j) { for (i=0; i < limit; ++i) { FASTDEF(temp); float f = data[i][d_offset+j]; int v = FAST_SCALED_FLOAT_TO_INT(temp, f,15);//data[i][d_offset+j],15); if ((unsigned int) (v + 32768) > 65535) v = v < 0 ? -32768 : 32767; *buffer++ = v; } for ( ; i < buf_c; ++i) *buffer++ = 0; } } } int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts) { float **output; int len; if (num_c == 1) return stb_vorbis_get_frame_short(f,num_c,&buffer, num_shorts); len = stb_vorbis_get_frame_float(f, NULL, &output); if (len) { if (len*num_c > num_shorts) len = num_shorts / num_c; convert_channels_short_interleaved(num_c, buffer, f->channels, output, 0, len); } return len; } int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts) { float **outputs; int len = num_shorts / channels; int n=0; int z = f->channels; if (z > channels) z = channels; while (n < len) { int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= len) k = len - n; if (k) convert_channels_short_interleaved(channels, buffer, f->channels, f->channel_buffers, f->channel_buffer_start, k); buffer += k*channels; n += k; f->channel_buffer_start += k; if (n == len) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int len) { float **outputs; int n=0; int z = f->channels; if (z > channels) z = channels; while (n < len) { int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= len) k = len - n; if (k) convert_samples_short(channels, buffer, n, f->channels, f->channel_buffers, f->channel_buffer_start, k); n += k; f->channel_buffer_start += k; if (n == len) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } #ifndef STB_VORBIS_NO_STDIO int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output) { int data_len, offset, total, limit, error; short *data; stb_vorbis *v = stb_vorbis_open_filename(filename, &error, NULL); if (v == NULL) return -1; limit = v->channels * 4096; *channels = v->channels; if (sample_rate) *sample_rate = v->sample_rate; offset = data_len = 0; total = limit; data = (short *) malloc(total * sizeof(*data)); if (data == NULL) { stb_vorbis_close(v); return -2; } for (;;) { int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset); if (n == 0) break; data_len += n; offset += n * v->channels; if (offset + limit > total) { short *data2; total *= 2; data2 = (short *) realloc(data, total * sizeof(*data)); if (data2 == NULL) { free(data); stb_vorbis_close(v); return -2; } data = data2; } } *output = data; stb_vorbis_close(v); return data_len; } #endif // NO_STDIO int stb_vorbis_decode_memory(const uint8 *mem, int len, int *channels, int *sample_rate, short **output) { int data_len, offset, total, limit, error; short *data; stb_vorbis *v = stb_vorbis_open_memory(mem, len, &error, NULL); if (v == NULL) return -1; limit = v->channels * 4096; *channels = v->channels; if (sample_rate) *sample_rate = v->sample_rate; offset = data_len = 0; total = limit; data = (short *) malloc(total * sizeof(*data)); if (data == NULL) { stb_vorbis_close(v); return -2; } for (;;) { int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset); if (n == 0) break; data_len += n; offset += n * v->channels; if (offset + limit > total) { short *data2; total *= 2; data2 = (short *) realloc(data, total * sizeof(*data)); if (data2 == NULL) { free(data); stb_vorbis_close(v); return -2; } data = data2; } } *output = data; stb_vorbis_close(v); return data_len; } #endif // STB_VORBIS_NO_INTEGER_CONVERSION int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats) { float **outputs; int len = num_floats / channels; int n=0; int z = f->channels; if (z > channels) z = channels; while (n < len) { int i,j; int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= len) k = len - n; for (j=0; j < k; ++j) { for (i=0; i < z; ++i) *buffer++ = f->channel_buffers[i][f->channel_buffer_start+j]; for ( ; i < channels; ++i) *buffer++ = 0; } n += k; f->channel_buffer_start += k; if (n == len) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples) { float **outputs; int n=0; int z = f->channels; if (z > channels) z = channels; while (n < num_samples) { int i; int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= num_samples) k = num_samples - n; if (k) { for (i=0; i < z; ++i) memcpy(buffer[i]+n, f->channel_buffers[i]+f->channel_buffer_start, sizeof(float)*k); for ( ; i < channels; ++i) memset(buffer[i]+n, 0, sizeof(float) * k); } n += k; f->channel_buffer_start += k; if (n == num_samples) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } #endif // STB_VORBIS_NO_PULLDATA_API /* Version history 1.17 - 2019-07-08 - fix CVE-2019-13217, -13218, -13219, -13220, -13221, -13223, -13223 found with Mayhem by ForAllSecure 1.16 - 2019-03-04 - fix warnings 1.15 - 2019-02-07 - explicit failure if Ogg Skeleton data is found 1.14 - 2018-02-11 - delete bogus dealloca usage 1.13 - 2018-01-29 - fix truncation of last frame (hopefully) 1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files 1.11 - 2017-07-23 - fix MinGW compilation 1.10 - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory 1.09 - 2016-04-04 - back out 'avoid discarding last frame' fix from previous version 1.08 - 2016-04-02 - fixed multiple warnings; fix setup memory leaks; avoid discarding last frame of audio data 1.07 - 2015-01-16 - fixed some warnings, fix mingw, const-correct API some more crash fixes when out of memory or with corrupt files 1.06 - 2015-08-31 - full, correct support for seeking API (Dougall Johnson) some crash fixes when out of memory or with corrupt files 1.05 - 2015-04-19 - don't define __forceinline if it's redundant 1.04 - 2014-08-27 - fix missing const-correct case in API 1.03 - 2014-08-07 - Warning fixes 1.02 - 2014-07-09 - Declare qsort compare function _cdecl on windows 1.01 - 2014-06-18 - fix stb_vorbis_get_samples_float 1.0 - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in multichannel (API change) report sample rate for decode-full-file funcs 0.99996 - bracket #include <malloc.h> for macintosh compilation by Laurent Gomila 0.99995 - use union instead of pointer-cast for fast-float-to-int to avoid alias-optimization problem 0.99994 - change fast-float-to-int to work in single-precision FPU mode, remove endian-dependence 0.99993 - remove assert that fired on legal files with empty tables 0.99992 - rewind-to-start 0.99991 - bugfix to stb_vorbis_get_samples_short by Bernhard Wodo 0.9999 - (should have been 0.99990) fix no-CRT support, compiling as C++ 0.9998 - add a full-decode function with a memory source 0.9997 - fix a bug in the read-from-FILE case in 0.9996 addition 0.9996 - query length of vorbis stream in samples/seconds 0.9995 - bugfix to another optimization that only happened in certain files 0.9994 - bugfix to one of the optimizations that caused significant (but inaudible?) errors 0.9993 - performance improvements; runs in 99% to 104% of time of reference implementation 0.9992 - performance improvement of IMDCT; now performs close to reference implementation 0.9991 - performance improvement of IMDCT 0.999 - (should have been 0.9990) performance improvement of IMDCT 0.998 - no-CRT support from Casey Muratori 0.997 - bugfixes for bugs found by Terje Mathisen 0.996 - bugfix: fast-huffman decode initialized incorrectly for sparse codebooks; fixing gives 10% speedup - found by Terje Mathisen 0.995 - bugfix: fix to 'effective' overrun detection - found by Terje Mathisen 0.994 - bugfix: garbage decode on final VQ symbol of a non-multiple - found by Terje Mathisen 0.993 - bugfix: pushdata API required 1 extra byte for empty page (failed to consume final page if empty) - found by Terje Mathisen 0.992 - fixes for MinGW warning 0.991 - turn fast-float-conversion on by default 0.990 - fix push-mode seek recovery if you seek into the headers 0.98b - fix to bad release of 0.98 0.98 - fix push-mode seek recovery; robustify float-to-int and support non-fast mode 0.97 - builds under c++ (typecasting, don't use 'class' keyword) 0.96 - somehow MY 0.95 was right, but the web one was wrong, so here's my 0.95 rereleased as 0.96, fixes a typo in the clamping code 0.95 - clamping code for 16-bit functions 0.94 - not publically released 0.93 - fixed all-zero-floor case (was decoding garbage) 0.92 - fixed a memory leak 0.91 - conditional compiles to omit parts of the API and the infrastructure to support them: STB_VORBIS_NO_PULLDATA_API, STB_VORBIS_NO_PUSHDATA_API, STB_VORBIS_NO_STDIO, STB_VORBIS_NO_INTEGER_CONVERSION 0.90 - first public release */ #endif // STB_VORBIS_HEADER_ONLY /* ------------------------------------------------------------------------------ This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------ ALTERNATIVE A - MIT License Copyright (c) 2017 Sean Barrett Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ ALTERNATIVE B - Public Domain (www.unlicense.org) This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ */
null
122
CWE-787
CVE-2019-13221
// Ogg Vorbis audio decoder - v1.16 - public domain // http://nothings.org/stb_vorbis/ // // Original version written by Sean Barrett in 2007. // // Originally sponsored by RAD Game Tools. Seeking implementation // sponsored by Phillip Bennefall, Marc Andersen, Aaron Baker, // Elias Software, Aras Pranckevicius, and Sean Barrett. // // LICENSE // // See end of file for license information. // // Limitations: // // - floor 0 not supported (used in old ogg vorbis files pre-2004) // - lossless sample-truncation at beginning ignored // - cannot concatenate multiple vorbis streams // - sample positions are 32-bit, limiting seekable 192Khz // files to around 6 hours (Ogg supports 64-bit) // // Feature contributors: // Dougall Johnson (sample-exact seeking) // // Bugfix/warning contributors: // Terje Mathisen Niklas Frykholm Andy Hill // Casey Muratori John Bolton Gargaj // Laurent Gomila Marc LeBlanc Ronny Chevalier // Bernhard Wodo Evan Balster alxprd@github // Tom Beaumont Ingo Leitgeb Nicolas Guillemot // Phillip Bennefall Rohit Thiago Goulart // manxorist@github saga musix github:infatum // Timur Gagiev // // Partial history: // 1.16 - 2019-03-04 - fix warnings // 1.15 - 2019-02-07 - explicit failure if Ogg Skeleton data is found // 1.14 - 2018-02-11 - delete bogus dealloca usage // 1.13 - 2018-01-29 - fix truncation of last frame (hopefully) // 1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files // 1.11 - 2017-07-23 - fix MinGW compilation // 1.10 - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory // 1.09 - 2016-04-04 - back out 'truncation of last frame' fix from previous version // 1.08 - 2016-04-02 - warnings; setup memory leaks; truncation of last frame // 1.07 - 2015-01-16 - fixes for crashes on invalid files; warning fixes; const // 1.06 - 2015-08-31 - full, correct support for seeking API (Dougall Johnson) // some crash fixes when out of memory or with corrupt files // fix some inappropriately signed shifts // 1.05 - 2015-04-19 - don't define __forceinline if it's redundant // 1.04 - 2014-08-27 - fix missing const-correct case in API // 1.03 - 2014-08-07 - warning fixes // 1.02 - 2014-07-09 - declare qsort comparison as explicitly _cdecl in Windows // 1.01 - 2014-06-18 - fix stb_vorbis_get_samples_float (interleaved was correct) // 1.0 - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in >2-channel; // (API change) report sample rate for decode-full-file funcs // // See end of file for full version history. ////////////////////////////////////////////////////////////////////////////// // // HEADER BEGINS HERE // #ifndef STB_VORBIS_INCLUDE_STB_VORBIS_H #define STB_VORBIS_INCLUDE_STB_VORBIS_H #if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO) #define STB_VORBIS_NO_STDIO 1 #endif #ifndef STB_VORBIS_NO_STDIO #include <stdio.h> #endif #ifdef __cplusplus extern "C" { #endif /////////// THREAD SAFETY // Individual stb_vorbis* handles are not thread-safe; you cannot decode from // them from multiple threads at the same time. However, you can have multiple // stb_vorbis* handles and decode from them independently in multiple thrads. /////////// MEMORY ALLOCATION // normally stb_vorbis uses malloc() to allocate memory at startup, // and alloca() to allocate temporary memory during a frame on the // stack. (Memory consumption will depend on the amount of setup // data in the file and how you set the compile flags for speed // vs. size. In my test files the maximal-size usage is ~150KB.) // // You can modify the wrapper functions in the source (setup_malloc, // setup_temp_malloc, temp_malloc) to change this behavior, or you // can use a simpler allocation model: you pass in a buffer from // which stb_vorbis will allocate _all_ its memory (including the // temp memory). "open" may fail with a VORBIS_outofmem if you // do not pass in enough data; there is no way to determine how // much you do need except to succeed (at which point you can // query get_info to find the exact amount required. yes I know // this is lame). // // If you pass in a non-NULL buffer of the type below, allocation // will occur from it as described above. Otherwise just pass NULL // to use malloc()/alloca() typedef struct { char *alloc_buffer; int alloc_buffer_length_in_bytes; } stb_vorbis_alloc; /////////// FUNCTIONS USEABLE WITH ALL INPUT MODES typedef struct stb_vorbis stb_vorbis; typedef struct { unsigned int sample_rate; int channels; unsigned int setup_memory_required; unsigned int setup_temp_memory_required; unsigned int temp_memory_required; int max_frame_size; } stb_vorbis_info; // get general information about the file extern stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f); // get the last error detected (clears it, too) extern int stb_vorbis_get_error(stb_vorbis *f); // close an ogg vorbis file and free all memory in use extern void stb_vorbis_close(stb_vorbis *f); // this function returns the offset (in samples) from the beginning of the // file that will be returned by the next decode, if it is known, or -1 // otherwise. after a flush_pushdata() call, this may take a while before // it becomes valid again. // NOT WORKING YET after a seek with PULLDATA API extern int stb_vorbis_get_sample_offset(stb_vorbis *f); // returns the current seek point within the file, or offset from the beginning // of the memory buffer. In pushdata mode it returns 0. extern unsigned int stb_vorbis_get_file_offset(stb_vorbis *f); /////////// PUSHDATA API #ifndef STB_VORBIS_NO_PUSHDATA_API // this API allows you to get blocks of data from any source and hand // them to stb_vorbis. you have to buffer them; stb_vorbis will tell // you how much it used, and you have to give it the rest next time; // and stb_vorbis may not have enough data to work with and you will // need to give it the same data again PLUS more. Note that the Vorbis // specification does not bound the size of an individual frame. extern stb_vorbis *stb_vorbis_open_pushdata( const unsigned char * datablock, int datablock_length_in_bytes, int *datablock_memory_consumed_in_bytes, int *error, const stb_vorbis_alloc *alloc_buffer); // create a vorbis decoder by passing in the initial data block containing // the ogg&vorbis headers (you don't need to do parse them, just provide // the first N bytes of the file--you're told if it's not enough, see below) // on success, returns an stb_vorbis *, does not set error, returns the amount of // data parsed/consumed on this call in *datablock_memory_consumed_in_bytes; // on failure, returns NULL on error and sets *error, does not change *datablock_memory_consumed // if returns NULL and *error is VORBIS_need_more_data, then the input block was // incomplete and you need to pass in a larger block from the start of the file extern int stb_vorbis_decode_frame_pushdata( stb_vorbis *f, const unsigned char *datablock, int datablock_length_in_bytes, int *channels, // place to write number of float * buffers float ***output, // place to write float ** array of float * buffers int *samples // place to write number of output samples ); // decode a frame of audio sample data if possible from the passed-in data block // // return value: number of bytes we used from datablock // // possible cases: // 0 bytes used, 0 samples output (need more data) // N bytes used, 0 samples output (resynching the stream, keep going) // N bytes used, M samples output (one frame of data) // note that after opening a file, you will ALWAYS get one N-bytes,0-sample // frame, because Vorbis always "discards" the first frame. // // Note that on resynch, stb_vorbis will rarely consume all of the buffer, // instead only datablock_length_in_bytes-3 or less. This is because it wants // to avoid missing parts of a page header if they cross a datablock boundary, // without writing state-machiney code to record a partial detection. // // The number of channels returned are stored in *channels (which can be // NULL--it is always the same as the number of channels reported by // get_info). *output will contain an array of float* buffers, one per // channel. In other words, (*output)[0][0] contains the first sample from // the first channel, and (*output)[1][0] contains the first sample from // the second channel. extern void stb_vorbis_flush_pushdata(stb_vorbis *f); // inform stb_vorbis that your next datablock will not be contiguous with // previous ones (e.g. you've seeked in the data); future attempts to decode // frames will cause stb_vorbis to resynchronize (as noted above), and // once it sees a valid Ogg page (typically 4-8KB, as large as 64KB), it // will begin decoding the _next_ frame. // // if you want to seek using pushdata, you need to seek in your file, then // call stb_vorbis_flush_pushdata(), then start calling decoding, then once // decoding is returning you data, call stb_vorbis_get_sample_offset, and // if you don't like the result, seek your file again and repeat. #endif ////////// PULLING INPUT API #ifndef STB_VORBIS_NO_PULLDATA_API // This API assumes stb_vorbis is allowed to pull data from a source-- // either a block of memory containing the _entire_ vorbis stream, or a // FILE * that you or it create, or possibly some other reading mechanism // if you go modify the source to replace the FILE * case with some kind // of callback to your code. (But if you don't support seeking, you may // just want to go ahead and use pushdata.) #if !defined(STB_VORBIS_NO_STDIO) && !defined(STB_VORBIS_NO_INTEGER_CONVERSION) extern int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output); #endif #if !defined(STB_VORBIS_NO_INTEGER_CONVERSION) extern int stb_vorbis_decode_memory(const unsigned char *mem, int len, int *channels, int *sample_rate, short **output); #endif // decode an entire file and output the data interleaved into a malloc()ed // buffer stored in *output. The return value is the number of samples // decoded, or -1 if the file could not be opened or was not an ogg vorbis file. // When you're done with it, just free() the pointer returned in *output. extern stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, int *error, const stb_vorbis_alloc *alloc_buffer); // create an ogg vorbis decoder from an ogg vorbis stream in memory (note // this must be the entire stream!). on failure, returns NULL and sets *error #ifndef STB_VORBIS_NO_STDIO extern stb_vorbis * stb_vorbis_open_filename(const char *filename, int *error, const stb_vorbis_alloc *alloc_buffer); // create an ogg vorbis decoder from a filename via fopen(). on failure, // returns NULL and sets *error (possibly to VORBIS_file_open_failure). extern stb_vorbis * stb_vorbis_open_file(FILE *f, int close_handle_on_close, int *error, const stb_vorbis_alloc *alloc_buffer); // create an ogg vorbis decoder from an open FILE *, looking for a stream at // the _current_ seek point (ftell). on failure, returns NULL and sets *error. // note that stb_vorbis must "own" this stream; if you seek it in between // calls to stb_vorbis, it will become confused. Moreover, if you attempt to // perform stb_vorbis_seek_*() operations on this file, it will assume it // owns the _entire_ rest of the file after the start point. Use the next // function, stb_vorbis_open_file_section(), to limit it. extern stb_vorbis * stb_vorbis_open_file_section(FILE *f, int close_handle_on_close, int *error, const stb_vorbis_alloc *alloc_buffer, unsigned int len); // create an ogg vorbis decoder from an open FILE *, looking for a stream at // the _current_ seek point (ftell); the stream will be of length 'len' bytes. // on failure, returns NULL and sets *error. note that stb_vorbis must "own" // this stream; if you seek it in between calls to stb_vorbis, it will become // confused. #endif extern int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number); extern int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number); // these functions seek in the Vorbis file to (approximately) 'sample_number'. // after calling seek_frame(), the next call to get_frame_*() will include // the specified sample. after calling stb_vorbis_seek(), the next call to // stb_vorbis_get_samples_* will start with the specified sample. If you // do not need to seek to EXACTLY the target sample when using get_samples_*, // you can also use seek_frame(). extern int stb_vorbis_seek_start(stb_vorbis *f); // this function is equivalent to stb_vorbis_seek(f,0) extern unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f); extern float stb_vorbis_stream_length_in_seconds(stb_vorbis *f); // these functions return the total length of the vorbis stream extern int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output); // decode the next frame and return the number of samples. the number of // channels returned are stored in *channels (which can be NULL--it is always // the same as the number of channels reported by get_info). *output will // contain an array of float* buffers, one per channel. These outputs will // be overwritten on the next call to stb_vorbis_get_frame_*. // // You generally should not intermix calls to stb_vorbis_get_frame_*() // and stb_vorbis_get_samples_*(), since the latter calls the former. #ifndef STB_VORBIS_NO_INTEGER_CONVERSION extern int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts); extern int stb_vorbis_get_frame_short (stb_vorbis *f, int num_c, short **buffer, int num_samples); #endif // decode the next frame and return the number of *samples* per channel. // Note that for interleaved data, you pass in the number of shorts (the // size of your array), but the return value is the number of samples per // channel, not the total number of samples. // // The data is coerced to the number of channels you request according to the // channel coercion rules (see below). You must pass in the size of your // buffer(s) so that stb_vorbis will not overwrite the end of the buffer. // The maximum buffer size needed can be gotten from get_info(); however, // the Vorbis I specification implies an absolute maximum of 4096 samples // per channel. // Channel coercion rules: // Let M be the number of channels requested, and N the number of channels present, // and Cn be the nth channel; let stereo L be the sum of all L and center channels, // and stereo R be the sum of all R and center channels (channel assignment from the // vorbis spec). // M N output // 1 k sum(Ck) for all k // 2 * stereo L, stereo R // k l k > l, the first l channels, then 0s // k l k <= l, the first k channels // Note that this is not _good_ surround etc. mixing at all! It's just so // you get something useful. extern int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats); extern int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples); // gets num_samples samples, not necessarily on a frame boundary--this requires // buffering so you have to supply the buffers. DOES NOT APPLY THE COERCION RULES. // Returns the number of samples stored per channel; it may be less than requested // at the end of the file. If there are no more samples in the file, returns 0. #ifndef STB_VORBIS_NO_INTEGER_CONVERSION extern int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts); extern int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int num_samples); #endif // gets num_samples samples, not necessarily on a frame boundary--this requires // buffering so you have to supply the buffers. Applies the coercion rules above // to produce 'channels' channels. Returns the number of samples stored per channel; // it may be less than requested at the end of the file. If there are no more // samples in the file, returns 0. #endif //////// ERROR CODES enum STBVorbisError { VORBIS__no_error, VORBIS_need_more_data=1, // not a real error VORBIS_invalid_api_mixing, // can't mix API modes VORBIS_outofmem, // not enough memory VORBIS_feature_not_supported, // uses floor 0 VORBIS_too_many_channels, // STB_VORBIS_MAX_CHANNELS is too small VORBIS_file_open_failure, // fopen() failed VORBIS_seek_without_length, // can't seek in unknown-length file VORBIS_unexpected_eof=10, // file is truncated? VORBIS_seek_invalid, // seek past EOF // decoding errors (corrupt/invalid stream) -- you probably // don't care about the exact details of these // vorbis errors: VORBIS_invalid_setup=20, VORBIS_invalid_stream, // ogg errors: VORBIS_missing_capture_pattern=30, VORBIS_invalid_stream_structure_version, VORBIS_continued_packet_flag_invalid, VORBIS_incorrect_stream_serial_number, VORBIS_invalid_first_page, VORBIS_bad_packet_type, VORBIS_cant_find_last_page, VORBIS_seek_failed, VORBIS_ogg_skeleton_not_supported }; #ifdef __cplusplus } #endif #endif // STB_VORBIS_INCLUDE_STB_VORBIS_H // // HEADER ENDS HERE // ////////////////////////////////////////////////////////////////////////////// #ifndef STB_VORBIS_HEADER_ONLY // global configuration settings (e.g. set these in the project/makefile), // or just set them in this file at the top (although ideally the first few // should be visible when the header file is compiled too, although it's not // crucial) // STB_VORBIS_NO_PUSHDATA_API // does not compile the code for the various stb_vorbis_*_pushdata() // functions // #define STB_VORBIS_NO_PUSHDATA_API // STB_VORBIS_NO_PULLDATA_API // does not compile the code for the non-pushdata APIs // #define STB_VORBIS_NO_PULLDATA_API // STB_VORBIS_NO_STDIO // does not compile the code for the APIs that use FILE *s internally // or externally (implied by STB_VORBIS_NO_PULLDATA_API) // #define STB_VORBIS_NO_STDIO // STB_VORBIS_NO_INTEGER_CONVERSION // does not compile the code for converting audio sample data from // float to integer (implied by STB_VORBIS_NO_PULLDATA_API) // #define STB_VORBIS_NO_INTEGER_CONVERSION // STB_VORBIS_NO_FAST_SCALED_FLOAT // does not use a fast float-to-int trick to accelerate float-to-int on // most platforms which requires endianness be defined correctly. //#define STB_VORBIS_NO_FAST_SCALED_FLOAT // STB_VORBIS_MAX_CHANNELS [number] // globally define this to the maximum number of channels you need. // The spec does not put a restriction on channels except that // the count is stored in a byte, so 255 is the hard limit. // Reducing this saves about 16 bytes per value, so using 16 saves // (255-16)*16 or around 4KB. Plus anything other memory usage // I forgot to account for. Can probably go as low as 8 (7.1 audio), // 6 (5.1 audio), or 2 (stereo only). #ifndef STB_VORBIS_MAX_CHANNELS #define STB_VORBIS_MAX_CHANNELS 16 // enough for anyone? #endif // STB_VORBIS_PUSHDATA_CRC_COUNT [number] // after a flush_pushdata(), stb_vorbis begins scanning for the // next valid page, without backtracking. when it finds something // that looks like a page, it streams through it and verifies its // CRC32. Should that validation fail, it keeps scanning. But it's // possible that _while_ streaming through to check the CRC32 of // one candidate page, it sees another candidate page. This #define // determines how many "overlapping" candidate pages it can search // at once. Note that "real" pages are typically ~4KB to ~8KB, whereas // garbage pages could be as big as 64KB, but probably average ~16KB. // So don't hose ourselves by scanning an apparent 64KB page and // missing a ton of real ones in the interim; so minimum of 2 #ifndef STB_VORBIS_PUSHDATA_CRC_COUNT #define STB_VORBIS_PUSHDATA_CRC_COUNT 4 #endif // STB_VORBIS_FAST_HUFFMAN_LENGTH [number] // sets the log size of the huffman-acceleration table. Maximum // supported value is 24. with larger numbers, more decodings are O(1), // but the table size is larger so worse cache missing, so you'll have // to probe (and try multiple ogg vorbis files) to find the sweet spot. #ifndef STB_VORBIS_FAST_HUFFMAN_LENGTH #define STB_VORBIS_FAST_HUFFMAN_LENGTH 10 #endif // STB_VORBIS_FAST_BINARY_LENGTH [number] // sets the log size of the binary-search acceleration table. this // is used in similar fashion to the fast-huffman size to set initial // parameters for the binary search // STB_VORBIS_FAST_HUFFMAN_INT // The fast huffman tables are much more efficient if they can be // stored as 16-bit results instead of 32-bit results. This restricts // the codebooks to having only 65535 possible outcomes, though. // (At least, accelerated by the huffman table.) #ifndef STB_VORBIS_FAST_HUFFMAN_INT #define STB_VORBIS_FAST_HUFFMAN_SHORT #endif // STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH // If the 'fast huffman' search doesn't succeed, then stb_vorbis falls // back on binary searching for the correct one. This requires storing // extra tables with the huffman codes in sorted order. Defining this // symbol trades off space for speed by forcing a linear search in the // non-fast case, except for "sparse" codebooks. // #define STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH // STB_VORBIS_DIVIDES_IN_RESIDUE // stb_vorbis precomputes the result of the scalar residue decoding // that would otherwise require a divide per chunk. you can trade off // space for time by defining this symbol. // #define STB_VORBIS_DIVIDES_IN_RESIDUE // STB_VORBIS_DIVIDES_IN_CODEBOOK // vorbis VQ codebooks can be encoded two ways: with every case explicitly // stored, or with all elements being chosen from a small range of values, // and all values possible in all elements. By default, stb_vorbis expands // this latter kind out to look like the former kind for ease of decoding, // because otherwise an integer divide-per-vector-element is required to // unpack the index. If you define STB_VORBIS_DIVIDES_IN_CODEBOOK, you can // trade off storage for speed. //#define STB_VORBIS_DIVIDES_IN_CODEBOOK #ifdef STB_VORBIS_CODEBOOK_SHORTS #error "STB_VORBIS_CODEBOOK_SHORTS is no longer supported as it produced incorrect results for some input formats" #endif // STB_VORBIS_DIVIDE_TABLE // this replaces small integer divides in the floor decode loop with // table lookups. made less than 1% difference, so disabled by default. // STB_VORBIS_NO_INLINE_DECODE // disables the inlining of the scalar codebook fast-huffman decode. // might save a little codespace; useful for debugging // #define STB_VORBIS_NO_INLINE_DECODE // STB_VORBIS_NO_DEFER_FLOOR // Normally we only decode the floor without synthesizing the actual // full curve. We can instead synthesize the curve immediately. This // requires more memory and is very likely slower, so I don't think // you'd ever want to do it except for debugging. // #define STB_VORBIS_NO_DEFER_FLOOR ////////////////////////////////////////////////////////////////////////////// #ifdef STB_VORBIS_NO_PULLDATA_API #define STB_VORBIS_NO_INTEGER_CONVERSION #define STB_VORBIS_NO_STDIO #endif #if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO) #define STB_VORBIS_NO_STDIO 1 #endif #ifndef STB_VORBIS_NO_INTEGER_CONVERSION #ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT // only need endianness for fast-float-to-int, which we don't // use for pushdata #ifndef STB_VORBIS_BIG_ENDIAN #define STB_VORBIS_ENDIAN 0 #else #define STB_VORBIS_ENDIAN 1 #endif #endif #endif #ifndef STB_VORBIS_NO_STDIO #include <stdio.h> #endif #ifndef STB_VORBIS_NO_CRT #include <stdlib.h> #include <string.h> #include <assert.h> #include <math.h> // find definition of alloca if it's not in stdlib.h: #if defined(_MSC_VER) || defined(__MINGW32__) #include <malloc.h> #endif #if defined(__linux__) || defined(__linux) || defined(__EMSCRIPTEN__) #include <alloca.h> #endif #else // STB_VORBIS_NO_CRT #define NULL 0 #define malloc(s) 0 #define free(s) ((void) 0) #define realloc(s) 0 #endif // STB_VORBIS_NO_CRT #include <limits.h> #ifdef __MINGW32__ // eff you mingw: // "fixed": // http://sourceforge.net/p/mingw-w64/mailman/message/32882927/ // "no that broke the build, reverted, who cares about C": // http://sourceforge.net/p/mingw-w64/mailman/message/32890381/ #ifdef __forceinline #undef __forceinline #endif #define __forceinline #define alloca __builtin_alloca #elif !defined(_MSC_VER) #if __GNUC__ #define __forceinline inline #else #define __forceinline #endif #endif #if STB_VORBIS_MAX_CHANNELS > 256 #error "Value of STB_VORBIS_MAX_CHANNELS outside of allowed range" #endif #if STB_VORBIS_FAST_HUFFMAN_LENGTH > 24 #error "Value of STB_VORBIS_FAST_HUFFMAN_LENGTH outside of allowed range" #endif #if 0 #include <crtdbg.h> #define CHECK(f) _CrtIsValidHeapPointer(f->channel_buffers[1]) #else #define CHECK(f) ((void) 0) #endif #define MAX_BLOCKSIZE_LOG 13 // from specification #define MAX_BLOCKSIZE (1 << MAX_BLOCKSIZE_LOG) typedef unsigned char uint8; typedef signed char int8; typedef unsigned short uint16; typedef signed short int16; typedef unsigned int uint32; typedef signed int int32; #ifndef TRUE #define TRUE 1 #define FALSE 0 #endif typedef float codetype; // @NOTE // // Some arrays below are tagged "//varies", which means it's actually // a variable-sized piece of data, but rather than malloc I assume it's // small enough it's better to just allocate it all together with the // main thing // // Most of the variables are specified with the smallest size I could pack // them into. It might give better performance to make them all full-sized // integers. It should be safe to freely rearrange the structures or change // the sizes larger--nothing relies on silently truncating etc., nor the // order of variables. #define FAST_HUFFMAN_TABLE_SIZE (1 << STB_VORBIS_FAST_HUFFMAN_LENGTH) #define FAST_HUFFMAN_TABLE_MASK (FAST_HUFFMAN_TABLE_SIZE - 1) typedef struct { int dimensions, entries; uint8 *codeword_lengths; float minimum_value; float delta_value; uint8 value_bits; uint8 lookup_type; uint8 sequence_p; uint8 sparse; uint32 lookup_values; codetype *multiplicands; uint32 *codewords; #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT int16 fast_huffman[FAST_HUFFMAN_TABLE_SIZE]; #else int32 fast_huffman[FAST_HUFFMAN_TABLE_SIZE]; #endif uint32 *sorted_codewords; int *sorted_values; int sorted_entries; } Codebook; typedef struct { uint8 order; uint16 rate; uint16 bark_map_size; uint8 amplitude_bits; uint8 amplitude_offset; uint8 number_of_books; uint8 book_list[16]; // varies } Floor0; typedef struct { uint8 partitions; uint8 partition_class_list[32]; // varies uint8 class_dimensions[16]; // varies uint8 class_subclasses[16]; // varies uint8 class_masterbooks[16]; // varies int16 subclass_books[16][8]; // varies uint16 Xlist[31*8+2]; // varies uint8 sorted_order[31*8+2]; uint8 neighbors[31*8+2][2]; uint8 floor1_multiplier; uint8 rangebits; int values; } Floor1; typedef union { Floor0 floor0; Floor1 floor1; } Floor; typedef struct { uint32 begin, end; uint32 part_size; uint8 classifications; uint8 classbook; uint8 **classdata; int16 (*residue_books)[8]; } Residue; typedef struct { uint8 magnitude; uint8 angle; uint8 mux; } MappingChannel; typedef struct { uint16 coupling_steps; MappingChannel *chan; uint8 submaps; uint8 submap_floor[15]; // varies uint8 submap_residue[15]; // varies } Mapping; typedef struct { uint8 blockflag; uint8 mapping; uint16 windowtype; uint16 transformtype; } Mode; typedef struct { uint32 goal_crc; // expected crc if match int bytes_left; // bytes left in packet uint32 crc_so_far; // running crc int bytes_done; // bytes processed in _current_ chunk uint32 sample_loc; // granule pos encoded in page } CRCscan; typedef struct { uint32 page_start, page_end; uint32 last_decoded_sample; } ProbedPage; struct stb_vorbis { // user-accessible info unsigned int sample_rate; int channels; unsigned int setup_memory_required; unsigned int temp_memory_required; unsigned int setup_temp_memory_required; // input config #ifndef STB_VORBIS_NO_STDIO FILE *f; uint32 f_start; int close_on_free; #endif uint8 *stream; uint8 *stream_start; uint8 *stream_end; uint32 stream_len; uint8 push_mode; uint32 first_audio_page_offset; ProbedPage p_first, p_last; // memory management stb_vorbis_alloc alloc; int setup_offset; int temp_offset; // run-time results int eof; enum STBVorbisError error; // user-useful data // header info int blocksize[2]; int blocksize_0, blocksize_1; int codebook_count; Codebook *codebooks; int floor_count; uint16 floor_types[64]; // varies Floor *floor_config; int residue_count; uint16 residue_types[64]; // varies Residue *residue_config; int mapping_count; Mapping *mapping; int mode_count; Mode mode_config[64]; // varies uint32 total_samples; // decode buffer float *channel_buffers[STB_VORBIS_MAX_CHANNELS]; float *outputs [STB_VORBIS_MAX_CHANNELS]; float *previous_window[STB_VORBIS_MAX_CHANNELS]; int previous_length; #ifndef STB_VORBIS_NO_DEFER_FLOOR int16 *finalY[STB_VORBIS_MAX_CHANNELS]; #else float *floor_buffers[STB_VORBIS_MAX_CHANNELS]; #endif uint32 current_loc; // sample location of next frame to decode int current_loc_valid; // per-blocksize precomputed data // twiddle factors float *A[2],*B[2],*C[2]; float *window[2]; uint16 *bit_reverse[2]; // current page/packet/segment streaming info uint32 serial; // stream serial number for verification int last_page; int segment_count; uint8 segments[255]; uint8 page_flag; uint8 bytes_in_seg; uint8 first_decode; int next_seg; int last_seg; // flag that we're on the last segment int last_seg_which; // what was the segment number of the last seg? uint32 acc; int valid_bits; int packet_bytes; int end_seg_with_known_loc; uint32 known_loc_for_packet; int discard_samples_deferred; uint32 samples_output; // push mode scanning int page_crc_tests; // only in push_mode: number of tests active; -1 if not searching #ifndef STB_VORBIS_NO_PUSHDATA_API CRCscan scan[STB_VORBIS_PUSHDATA_CRC_COUNT]; #endif // sample-access int channel_buffer_start; int channel_buffer_end; }; #if defined(STB_VORBIS_NO_PUSHDATA_API) #define IS_PUSH_MODE(f) FALSE #elif defined(STB_VORBIS_NO_PULLDATA_API) #define IS_PUSH_MODE(f) TRUE #else #define IS_PUSH_MODE(f) ((f)->push_mode) #endif typedef struct stb_vorbis vorb; static int error(vorb *f, enum STBVorbisError e) { f->error = e; if (!f->eof && e != VORBIS_need_more_data) { f->error=e; // breakpoint for debugging } return 0; } // these functions are used for allocating temporary memory // while decoding. if you can afford the stack space, use // alloca(); otherwise, provide a temp buffer and it will // allocate out of those. #define array_size_required(count,size) (count*(sizeof(void *)+(size))) #define temp_alloc(f,size) (f->alloc.alloc_buffer ? setup_temp_malloc(f,size) : alloca(size)) #define temp_free(f,p) 0 #define temp_alloc_save(f) ((f)->temp_offset) #define temp_alloc_restore(f,p) ((f)->temp_offset = (p)) #define temp_block_array(f,count,size) make_block_array(temp_alloc(f,array_size_required(count,size)), count, size) // given a sufficiently large block of memory, make an array of pointers to subblocks of it static void *make_block_array(void *mem, int count, int size) { int i; void ** p = (void **) mem; char *q = (char *) (p + count); for (i=0; i < count; ++i) { p[i] = q; q += size; } return p; } static void *setup_malloc(vorb *f, int sz) { sz = (sz+3) & ~3; f->setup_memory_required += sz; if (f->alloc.alloc_buffer) { void *p = (char *) f->alloc.alloc_buffer + f->setup_offset; if (f->setup_offset + sz > f->temp_offset) return NULL; f->setup_offset += sz; return p; } return sz ? malloc(sz) : NULL; } static void setup_free(vorb *f, void *p) { if (f->alloc.alloc_buffer) return; // do nothing; setup mem is a stack free(p); } static void *setup_temp_malloc(vorb *f, int sz) { sz = (sz+3) & ~3; if (f->alloc.alloc_buffer) { if (f->temp_offset - sz < f->setup_offset) return NULL; f->temp_offset -= sz; return (char *) f->alloc.alloc_buffer + f->temp_offset; } return malloc(sz); } static void setup_temp_free(vorb *f, void *p, int sz) { if (f->alloc.alloc_buffer) { f->temp_offset += (sz+3)&~3; return; } free(p); } #define CRC32_POLY 0x04c11db7 // from spec static uint32 crc_table[256]; static void crc32_init(void) { int i,j; uint32 s; for(i=0; i < 256; i++) { for (s=(uint32) i << 24, j=0; j < 8; ++j) s = (s << 1) ^ (s >= (1U<<31) ? CRC32_POLY : 0); crc_table[i] = s; } } static __forceinline uint32 crc32_update(uint32 crc, uint8 byte) { return (crc << 8) ^ crc_table[byte ^ (crc >> 24)]; } // used in setup, and for huffman that doesn't go fast path static unsigned int bit_reverse(unsigned int n) { n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1); n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2); n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4); n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8); return (n >> 16) | (n << 16); } static float square(float x) { return x*x; } // this is a weird definition of log2() for which log2(1) = 1, log2(2) = 2, log2(4) = 3 // as required by the specification. fast(?) implementation from stb.h // @OPTIMIZE: called multiple times per-packet with "constants"; move to setup static int ilog(int32 n) { static signed char log2_4[16] = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 }; if (n < 0) return 0; // signed n returns 0 // 2 compares if n < 16, 3 compares otherwise (4 if signed or n > 1<<29) if (n < (1 << 14)) if (n < (1 << 4)) return 0 + log2_4[n ]; else if (n < (1 << 9)) return 5 + log2_4[n >> 5]; else return 10 + log2_4[n >> 10]; else if (n < (1 << 24)) if (n < (1 << 19)) return 15 + log2_4[n >> 15]; else return 20 + log2_4[n >> 20]; else if (n < (1 << 29)) return 25 + log2_4[n >> 25]; else return 30 + log2_4[n >> 30]; } #ifndef M_PI #define M_PI 3.14159265358979323846264f // from CRC #endif // code length assigned to a value with no huffman encoding #define NO_CODE 255 /////////////////////// LEAF SETUP FUNCTIONS ////////////////////////// // // these functions are only called at setup, and only a few times // per file static float float32_unpack(uint32 x) { // from the specification uint32 mantissa = x & 0x1fffff; uint32 sign = x & 0x80000000; uint32 exp = (x & 0x7fe00000) >> 21; double res = sign ? -(double)mantissa : (double)mantissa; return (float) ldexp((float)res, exp-788); } // zlib & jpeg huffman tables assume that the output symbols // can either be arbitrarily arranged, or have monotonically // increasing frequencies--they rely on the lengths being sorted; // this makes for a very simple generation algorithm. // vorbis allows a huffman table with non-sorted lengths. This // requires a more sophisticated construction, since symbols in // order do not map to huffman codes "in order". static void add_entry(Codebook *c, uint32 huff_code, int symbol, int count, int len, uint32 *values) { if (!c->sparse) { c->codewords [symbol] = huff_code; } else { c->codewords [count] = huff_code; c->codeword_lengths[count] = len; values [count] = symbol; } } static int compute_codewords(Codebook *c, uint8 *len, int n, uint32 *values) { int i,k,m=0; uint32 available[32]; memset(available, 0, sizeof(available)); // find the first entry for (k=0; k < n; ++k) if (len[k] < NO_CODE) break; if (k == n) { assert(c->sorted_entries == 0); return TRUE; } // add to the list add_entry(c, 0, k, m++, len[k], values); // add all available leaves for (i=1; i <= len[k]; ++i) available[i] = 1U << (32-i); // note that the above code treats the first case specially, // but it's really the same as the following code, so they // could probably be combined (except the initial code is 0, // and I use 0 in available[] to mean 'empty') for (i=k+1; i < n; ++i) { uint32 res; int z = len[i], y; if (z == NO_CODE) continue; // find lowest available leaf (should always be earliest, // which is what the specification calls for) // note that this property, and the fact we can never have // more than one free leaf at a given level, isn't totally // trivial to prove, but it seems true and the assert never // fires, so! while (z > 0 && !available[z]) --z; if (z == 0) { return FALSE; } res = available[z]; assert(z >= 0 && z < 32); available[z] = 0; add_entry(c, bit_reverse(res), i, m++, len[i], values); // propagate availability up the tree if (z != len[i]) { assert(len[i] >= 0 && len[i] < 32); for (y=len[i]; y > z; --y) { assert(available[y] == 0); available[y] = res + (1 << (32-y)); } } } return TRUE; } // accelerated huffman table allows fast O(1) match of all symbols // of length <= STB_VORBIS_FAST_HUFFMAN_LENGTH static void compute_accelerated_huffman(Codebook *c) { int i, len; for (i=0; i < FAST_HUFFMAN_TABLE_SIZE; ++i) c->fast_huffman[i] = -1; len = c->sparse ? c->sorted_entries : c->entries; #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT if (len > 32767) len = 32767; // largest possible value we can encode! #endif for (i=0; i < len; ++i) { if (c->codeword_lengths[i] <= STB_VORBIS_FAST_HUFFMAN_LENGTH) { uint32 z = c->sparse ? bit_reverse(c->sorted_codewords[i]) : c->codewords[i]; // set table entries for all bit combinations in the higher bits while (z < FAST_HUFFMAN_TABLE_SIZE) { c->fast_huffman[z] = i; z += 1 << c->codeword_lengths[i]; } } } } #ifdef _MSC_VER #define STBV_CDECL __cdecl #else #define STBV_CDECL #endif static int STBV_CDECL uint32_compare(const void *p, const void *q) { uint32 x = * (uint32 *) p; uint32 y = * (uint32 *) q; return x < y ? -1 : x > y; } static int include_in_sort(Codebook *c, uint8 len) { if (c->sparse) { assert(len != NO_CODE); return TRUE; } if (len == NO_CODE) return FALSE; if (len > STB_VORBIS_FAST_HUFFMAN_LENGTH) return TRUE; return FALSE; } // if the fast table above doesn't work, we want to binary // search them... need to reverse the bits static void compute_sorted_huffman(Codebook *c, uint8 *lengths, uint32 *values) { int i, len; // build a list of all the entries // OPTIMIZATION: don't include the short ones, since they'll be caught by FAST_HUFFMAN. // this is kind of a frivolous optimization--I don't see any performance improvement, // but it's like 4 extra lines of code, so. if (!c->sparse) { int k = 0; for (i=0; i < c->entries; ++i) if (include_in_sort(c, lengths[i])) c->sorted_codewords[k++] = bit_reverse(c->codewords[i]); assert(k == c->sorted_entries); } else { for (i=0; i < c->sorted_entries; ++i) c->sorted_codewords[i] = bit_reverse(c->codewords[i]); } qsort(c->sorted_codewords, c->sorted_entries, sizeof(c->sorted_codewords[0]), uint32_compare); c->sorted_codewords[c->sorted_entries] = 0xffffffff; len = c->sparse ? c->sorted_entries : c->entries; // now we need to indicate how they correspond; we could either // #1: sort a different data structure that says who they correspond to // #2: for each sorted entry, search the original list to find who corresponds // #3: for each original entry, find the sorted entry // #1 requires extra storage, #2 is slow, #3 can use binary search! for (i=0; i < len; ++i) { int huff_len = c->sparse ? lengths[values[i]] : lengths[i]; if (include_in_sort(c,huff_len)) { uint32 code = bit_reverse(c->codewords[i]); int x=0, n=c->sorted_entries; while (n > 1) { // invariant: sc[x] <= code < sc[x+n] int m = x + (n >> 1); if (c->sorted_codewords[m] <= code) { x = m; n -= (n>>1); } else { n >>= 1; } } assert(c->sorted_codewords[x] == code); if (c->sparse) { c->sorted_values[x] = values[i]; c->codeword_lengths[x] = huff_len; } else { c->sorted_values[x] = i; } } } } // only run while parsing the header (3 times) static int vorbis_validate(uint8 *data) { static uint8 vorbis[6] = { 'v', 'o', 'r', 'b', 'i', 's' }; return memcmp(data, vorbis, 6) == 0; } // called from setup only, once per code book // (formula implied by specification) static int lookup1_values(int entries, int dim) { int r = (int) floor(exp((float) log((float) entries) / dim)); if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning; ++r; // floor() to avoid _ftol() when non-CRT assert(pow((float) r+1, dim) > entries); assert((int) floor(pow((float) r, dim)) <= entries); // (int),floor() as above return r; } // called twice per file static void compute_twiddle_factors(int n, float *A, float *B, float *C) { int n4 = n >> 2, n8 = n >> 3; int k,k2; for (k=k2=0; k < n4; ++k,k2+=2) { A[k2 ] = (float) cos(4*k*M_PI/n); A[k2+1] = (float) -sin(4*k*M_PI/n); B[k2 ] = (float) cos((k2+1)*M_PI/n/2) * 0.5f; B[k2+1] = (float) sin((k2+1)*M_PI/n/2) * 0.5f; } for (k=k2=0; k < n8; ++k,k2+=2) { C[k2 ] = (float) cos(2*(k2+1)*M_PI/n); C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n); } } static void compute_window(int n, float *window) { int n2 = n >> 1, i; for (i=0; i < n2; ++i) window[i] = (float) sin(0.5 * M_PI * square((float) sin((i - 0 + 0.5) / n2 * 0.5 * M_PI))); } static void compute_bitreverse(int n, uint16 *rev) { int ld = ilog(n) - 1; // ilog is off-by-one from normal definitions int i, n8 = n >> 3; for (i=0; i < n8; ++i) rev[i] = (bit_reverse(i) >> (32-ld+3)) << 2; } static int init_blocksize(vorb *f, int b, int n) { int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3; f->A[b] = (float *) setup_malloc(f, sizeof(float) * n2); f->B[b] = (float *) setup_malloc(f, sizeof(float) * n2); f->C[b] = (float *) setup_malloc(f, sizeof(float) * n4); if (!f->A[b] || !f->B[b] || !f->C[b]) return error(f, VORBIS_outofmem); compute_twiddle_factors(n, f->A[b], f->B[b], f->C[b]); f->window[b] = (float *) setup_malloc(f, sizeof(float) * n2); if (!f->window[b]) return error(f, VORBIS_outofmem); compute_window(n, f->window[b]); f->bit_reverse[b] = (uint16 *) setup_malloc(f, sizeof(uint16) * n8); if (!f->bit_reverse[b]) return error(f, VORBIS_outofmem); compute_bitreverse(n, f->bit_reverse[b]); return TRUE; } static void neighbors(uint16 *x, int n, int *plow, int *phigh) { int low = -1; int high = 65536; int i; for (i=0; i < n; ++i) { if (x[i] > low && x[i] < x[n]) { *plow = i; low = x[i]; } if (x[i] < high && x[i] > x[n]) { *phigh = i; high = x[i]; } } } // this has been repurposed so y is now the original index instead of y typedef struct { uint16 x,id; } stbv__floor_ordering; static int STBV_CDECL point_compare(const void *p, const void *q) { stbv__floor_ordering *a = (stbv__floor_ordering *) p; stbv__floor_ordering *b = (stbv__floor_ordering *) q; return a->x < b->x ? -1 : a->x > b->x; } // /////////////////////// END LEAF SETUP FUNCTIONS ////////////////////////// #if defined(STB_VORBIS_NO_STDIO) #define USE_MEMORY(z) TRUE #else #define USE_MEMORY(z) ((z)->stream) #endif static uint8 get8(vorb *z) { if (USE_MEMORY(z)) { if (z->stream >= z->stream_end) { z->eof = TRUE; return 0; } return *z->stream++; } #ifndef STB_VORBIS_NO_STDIO { int c = fgetc(z->f); if (c == EOF) { z->eof = TRUE; return 0; } return c; } #endif } static uint32 get32(vorb *f) { uint32 x; x = get8(f); x += get8(f) << 8; x += get8(f) << 16; x += (uint32) get8(f) << 24; return x; } static int getn(vorb *z, uint8 *data, int n) { if (USE_MEMORY(z)) { if (z->stream+n > z->stream_end) { z->eof = 1; return 0; } memcpy(data, z->stream, n); z->stream += n; return 1; } #ifndef STB_VORBIS_NO_STDIO if (fread(data, n, 1, z->f) == 1) return 1; else { z->eof = 1; return 0; } #endif } static void skip(vorb *z, int n) { if (USE_MEMORY(z)) { z->stream += n; if (z->stream >= z->stream_end) z->eof = 1; return; } #ifndef STB_VORBIS_NO_STDIO { long x = ftell(z->f); fseek(z->f, x+n, SEEK_SET); } #endif } static int set_file_offset(stb_vorbis *f, unsigned int loc) { #ifndef STB_VORBIS_NO_PUSHDATA_API if (f->push_mode) return 0; #endif f->eof = 0; if (USE_MEMORY(f)) { if (f->stream_start + loc >= f->stream_end || f->stream_start + loc < f->stream_start) { f->stream = f->stream_end; f->eof = 1; return 0; } else { f->stream = f->stream_start + loc; return 1; } } #ifndef STB_VORBIS_NO_STDIO if (loc + f->f_start < loc || loc >= 0x80000000) { loc = 0x7fffffff; f->eof = 1; } else { loc += f->f_start; } if (!fseek(f->f, loc, SEEK_SET)) return 1; f->eof = 1; fseek(f->f, f->f_start, SEEK_END); return 0; #endif } static uint8 ogg_page_header[4] = { 0x4f, 0x67, 0x67, 0x53 }; static int capture_pattern(vorb *f) { if (0x4f != get8(f)) return FALSE; if (0x67 != get8(f)) return FALSE; if (0x67 != get8(f)) return FALSE; if (0x53 != get8(f)) return FALSE; return TRUE; } #define PAGEFLAG_continued_packet 1 #define PAGEFLAG_first_page 2 #define PAGEFLAG_last_page 4 static int start_page_no_capturepattern(vorb *f) { uint32 loc0,loc1,n; // stream structure version if (0 != get8(f)) return error(f, VORBIS_invalid_stream_structure_version); // header flag f->page_flag = get8(f); // absolute granule position loc0 = get32(f); loc1 = get32(f); // @TODO: validate loc0,loc1 as valid positions? // stream serial number -- vorbis doesn't interleave, so discard get32(f); //if (f->serial != get32(f)) return error(f, VORBIS_incorrect_stream_serial_number); // page sequence number n = get32(f); f->last_page = n; // CRC32 get32(f); // page_segments f->segment_count = get8(f); if (!getn(f, f->segments, f->segment_count)) return error(f, VORBIS_unexpected_eof); // assume we _don't_ know any the sample position of any segments f->end_seg_with_known_loc = -2; if (loc0 != ~0U || loc1 != ~0U) { int i; // determine which packet is the last one that will complete for (i=f->segment_count-1; i >= 0; --i) if (f->segments[i] < 255) break; // 'i' is now the index of the _last_ segment of a packet that ends if (i >= 0) { f->end_seg_with_known_loc = i; f->known_loc_for_packet = loc0; } } if (f->first_decode) { int i,len; ProbedPage p; len = 0; for (i=0; i < f->segment_count; ++i) len += f->segments[i]; len += 27 + f->segment_count; p.page_start = f->first_audio_page_offset; p.page_end = p.page_start + len; p.last_decoded_sample = loc0; f->p_first = p; } f->next_seg = 0; return TRUE; } static int start_page(vorb *f) { if (!capture_pattern(f)) return error(f, VORBIS_missing_capture_pattern); return start_page_no_capturepattern(f); } static int start_packet(vorb *f) { while (f->next_seg == -1) { if (!start_page(f)) return FALSE; if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_continued_packet_flag_invalid); } f->last_seg = FALSE; f->valid_bits = 0; f->packet_bytes = 0; f->bytes_in_seg = 0; // f->next_seg is now valid return TRUE; } static int maybe_start_packet(vorb *f) { if (f->next_seg == -1) { int x = get8(f); if (f->eof) return FALSE; // EOF at page boundary is not an error! if (0x4f != x ) return error(f, VORBIS_missing_capture_pattern); if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern); if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern); if (0x53 != get8(f)) return error(f, VORBIS_missing_capture_pattern); if (!start_page_no_capturepattern(f)) return FALSE; if (f->page_flag & PAGEFLAG_continued_packet) { // set up enough state that we can read this packet if we want, // e.g. during recovery f->last_seg = FALSE; f->bytes_in_seg = 0; return error(f, VORBIS_continued_packet_flag_invalid); } } return start_packet(f); } static int next_segment(vorb *f) { int len; if (f->last_seg) return 0; if (f->next_seg == -1) { f->last_seg_which = f->segment_count-1; // in case start_page fails if (!start_page(f)) { f->last_seg = 1; return 0; } if (!(f->page_flag & PAGEFLAG_continued_packet)) return error(f, VORBIS_continued_packet_flag_invalid); } len = f->segments[f->next_seg++]; if (len < 255) { f->last_seg = TRUE; f->last_seg_which = f->next_seg-1; } if (f->next_seg >= f->segment_count) f->next_seg = -1; assert(f->bytes_in_seg == 0); f->bytes_in_seg = len; return len; } #define EOP (-1) #define INVALID_BITS (-1) static int get8_packet_raw(vorb *f) { if (!f->bytes_in_seg) { // CLANG! if (f->last_seg) return EOP; else if (!next_segment(f)) return EOP; } assert(f->bytes_in_seg > 0); --f->bytes_in_seg; ++f->packet_bytes; return get8(f); } static int get8_packet(vorb *f) { int x = get8_packet_raw(f); f->valid_bits = 0; return x; } static void flush_packet(vorb *f) { while (get8_packet_raw(f) != EOP); } // @OPTIMIZE: this is the secondary bit decoder, so it's probably not as important // as the huffman decoder? static uint32 get_bits(vorb *f, int n) { uint32 z; if (f->valid_bits < 0) return 0; if (f->valid_bits < n) { if (n > 24) { // the accumulator technique below would not work correctly in this case z = get_bits(f, 24); z += get_bits(f, n-24) << 24; return z; } if (f->valid_bits == 0) f->acc = 0; while (f->valid_bits < n) { int z = get8_packet_raw(f); if (z == EOP) { f->valid_bits = INVALID_BITS; return 0; } f->acc += z << f->valid_bits; f->valid_bits += 8; } } if (f->valid_bits < 0) return 0; z = f->acc & ((1 << n)-1); f->acc >>= n; f->valid_bits -= n; return z; } // @OPTIMIZE: primary accumulator for huffman // expand the buffer to as many bits as possible without reading off end of packet // it might be nice to allow f->valid_bits and f->acc to be stored in registers, // e.g. cache them locally and decode locally static __forceinline void prep_huffman(vorb *f) { if (f->valid_bits <= 24) { if (f->valid_bits == 0) f->acc = 0; do { int z; if (f->last_seg && !f->bytes_in_seg) return; z = get8_packet_raw(f); if (z == EOP) return; f->acc += (unsigned) z << f->valid_bits; f->valid_bits += 8; } while (f->valid_bits <= 24); } } enum { VORBIS_packet_id = 1, VORBIS_packet_comment = 3, VORBIS_packet_setup = 5 }; static int codebook_decode_scalar_raw(vorb *f, Codebook *c) { int i; prep_huffman(f); if (c->codewords == NULL && c->sorted_codewords == NULL) return -1; // cases to use binary search: sorted_codewords && !c->codewords // sorted_codewords && c->entries > 8 if (c->entries > 8 ? c->sorted_codewords!=NULL : !c->codewords) { // binary search uint32 code = bit_reverse(f->acc); int x=0, n=c->sorted_entries, len; while (n > 1) { // invariant: sc[x] <= code < sc[x+n] int m = x + (n >> 1); if (c->sorted_codewords[m] <= code) { x = m; n -= (n>>1); } else { n >>= 1; } } // x is now the sorted index if (!c->sparse) x = c->sorted_values[x]; // x is now sorted index if sparse, or symbol otherwise len = c->codeword_lengths[x]; if (f->valid_bits >= len) { f->acc >>= len; f->valid_bits -= len; return x; } f->valid_bits = 0; return -1; } // if small, linear search assert(!c->sparse); for (i=0; i < c->entries; ++i) { if (c->codeword_lengths[i] == NO_CODE) continue; if (c->codewords[i] == (f->acc & ((1 << c->codeword_lengths[i])-1))) { if (f->valid_bits >= c->codeword_lengths[i]) { f->acc >>= c->codeword_lengths[i]; f->valid_bits -= c->codeword_lengths[i]; return i; } f->valid_bits = 0; return -1; } } error(f, VORBIS_invalid_stream); f->valid_bits = 0; return -1; } #ifndef STB_VORBIS_NO_INLINE_DECODE #define DECODE_RAW(var, f,c) \ if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) \ prep_huffman(f); \ var = f->acc & FAST_HUFFMAN_TABLE_MASK; \ var = c->fast_huffman[var]; \ if (var >= 0) { \ int n = c->codeword_lengths[var]; \ f->acc >>= n; \ f->valid_bits -= n; \ if (f->valid_bits < 0) { f->valid_bits = 0; var = -1; } \ } else { \ var = codebook_decode_scalar_raw(f,c); \ } #else static int codebook_decode_scalar(vorb *f, Codebook *c) { int i; if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) prep_huffman(f); // fast huffman table lookup i = f->acc & FAST_HUFFMAN_TABLE_MASK; i = c->fast_huffman[i]; if (i >= 0) { f->acc >>= c->codeword_lengths[i]; f->valid_bits -= c->codeword_lengths[i]; if (f->valid_bits < 0) { f->valid_bits = 0; return -1; } return i; } return codebook_decode_scalar_raw(f,c); } #define DECODE_RAW(var,f,c) var = codebook_decode_scalar(f,c); #endif #define DECODE(var,f,c) \ DECODE_RAW(var,f,c) \ if (c->sparse) var = c->sorted_values[var]; #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK #define DECODE_VQ(var,f,c) DECODE_RAW(var,f,c) #else #define DECODE_VQ(var,f,c) DECODE(var,f,c) #endif // CODEBOOK_ELEMENT_FAST is an optimization for the CODEBOOK_FLOATS case // where we avoid one addition #define CODEBOOK_ELEMENT(c,off) (c->multiplicands[off]) #define CODEBOOK_ELEMENT_FAST(c,off) (c->multiplicands[off]) #define CODEBOOK_ELEMENT_BASE(c) (0) static int codebook_decode_start(vorb *f, Codebook *c) { int z = -1; // type 0 is only legal in a scalar context if (c->lookup_type == 0) error(f, VORBIS_invalid_stream); else { DECODE_VQ(z,f,c); if (c->sparse) assert(z < c->sorted_entries); if (z < 0) { // check for EOP if (!f->bytes_in_seg) if (f->last_seg) return z; error(f, VORBIS_invalid_stream); } } return z; } static int codebook_decode(vorb *f, Codebook *c, float *output, int len) { int i,z = codebook_decode_start(f,c); if (z < 0) return FALSE; if (len > c->dimensions) len = c->dimensions; #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { float last = CODEBOOK_ELEMENT_BASE(c); int div = 1; for (i=0; i < len; ++i) { int off = (z / div) % c->lookup_values; float val = CODEBOOK_ELEMENT_FAST(c,off) + last; output[i] += val; if (c->sequence_p) last = val + c->minimum_value; div *= c->lookup_values; } return TRUE; } #endif z *= c->dimensions; if (c->sequence_p) { float last = CODEBOOK_ELEMENT_BASE(c); for (i=0; i < len; ++i) { float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; output[i] += val; last = val + c->minimum_value; } } else { float last = CODEBOOK_ELEMENT_BASE(c); for (i=0; i < len; ++i) { output[i] += CODEBOOK_ELEMENT_FAST(c,z+i) + last; } } return TRUE; } static int codebook_decode_step(vorb *f, Codebook *c, float *output, int len, int step) { int i,z = codebook_decode_start(f,c); float last = CODEBOOK_ELEMENT_BASE(c); if (z < 0) return FALSE; if (len > c->dimensions) len = c->dimensions; #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { int div = 1; for (i=0; i < len; ++i) { int off = (z / div) % c->lookup_values; float val = CODEBOOK_ELEMENT_FAST(c,off) + last; output[i*step] += val; if (c->sequence_p) last = val; div *= c->lookup_values; } return TRUE; } #endif z *= c->dimensions; for (i=0; i < len; ++i) { float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; output[i*step] += val; if (c->sequence_p) last = val; } return TRUE; } static int codebook_decode_deinterleave_repeat(vorb *f, Codebook *c, float **outputs, int ch, int *c_inter_p, int *p_inter_p, int len, int total_decode) { int c_inter = *c_inter_p; int p_inter = *p_inter_p; int i,z, effective = c->dimensions; // type 0 is only legal in a scalar context if (c->lookup_type == 0) return error(f, VORBIS_invalid_stream); while (total_decode > 0) { float last = CODEBOOK_ELEMENT_BASE(c); DECODE_VQ(z,f,c); #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK assert(!c->sparse || z < c->sorted_entries); #endif if (z < 0) { if (!f->bytes_in_seg) if (f->last_seg) return FALSE; return error(f, VORBIS_invalid_stream); } // if this will take us off the end of the buffers, stop short! // we check by computing the length of the virtual interleaved // buffer (len*ch), our current offset within it (p_inter*ch)+(c_inter), // and the length we'll be using (effective) if (c_inter + p_inter*ch + effective > len * ch) { effective = len*ch - (p_inter*ch - c_inter); } #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { int div = 1; for (i=0; i < effective; ++i) { int off = (z / div) % c->lookup_values; float val = CODEBOOK_ELEMENT_FAST(c,off) + last; if (outputs[c_inter]) outputs[c_inter][p_inter] += val; if (++c_inter == ch) { c_inter = 0; ++p_inter; } if (c->sequence_p) last = val; div *= c->lookup_values; } } else #endif { z *= c->dimensions; if (c->sequence_p) { for (i=0; i < effective; ++i) { float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; if (outputs[c_inter]) outputs[c_inter][p_inter] += val; if (++c_inter == ch) { c_inter = 0; ++p_inter; } last = val; } } else { for (i=0; i < effective; ++i) { float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; if (outputs[c_inter]) outputs[c_inter][p_inter] += val; if (++c_inter == ch) { c_inter = 0; ++p_inter; } } } } total_decode -= effective; } *c_inter_p = c_inter; *p_inter_p = p_inter; return TRUE; } static int predict_point(int x, int x0, int x1, int y0, int y1) { int dy = y1 - y0; int adx = x1 - x0; // @OPTIMIZE: force int division to round in the right direction... is this necessary on x86? int err = abs(dy) * (x - x0); int off = err / adx; return dy < 0 ? y0 - off : y0 + off; } // the following table is block-copied from the specification static float inverse_db_table[256] = { 1.0649863e-07f, 1.1341951e-07f, 1.2079015e-07f, 1.2863978e-07f, 1.3699951e-07f, 1.4590251e-07f, 1.5538408e-07f, 1.6548181e-07f, 1.7623575e-07f, 1.8768855e-07f, 1.9988561e-07f, 2.1287530e-07f, 2.2670913e-07f, 2.4144197e-07f, 2.5713223e-07f, 2.7384213e-07f, 2.9163793e-07f, 3.1059021e-07f, 3.3077411e-07f, 3.5226968e-07f, 3.7516214e-07f, 3.9954229e-07f, 4.2550680e-07f, 4.5315863e-07f, 4.8260743e-07f, 5.1396998e-07f, 5.4737065e-07f, 5.8294187e-07f, 6.2082472e-07f, 6.6116941e-07f, 7.0413592e-07f, 7.4989464e-07f, 7.9862701e-07f, 8.5052630e-07f, 9.0579828e-07f, 9.6466216e-07f, 1.0273513e-06f, 1.0941144e-06f, 1.1652161e-06f, 1.2409384e-06f, 1.3215816e-06f, 1.4074654e-06f, 1.4989305e-06f, 1.5963394e-06f, 1.7000785e-06f, 1.8105592e-06f, 1.9282195e-06f, 2.0535261e-06f, 2.1869758e-06f, 2.3290978e-06f, 2.4804557e-06f, 2.6416497e-06f, 2.8133190e-06f, 2.9961443e-06f, 3.1908506e-06f, 3.3982101e-06f, 3.6190449e-06f, 3.8542308e-06f, 4.1047004e-06f, 4.3714470e-06f, 4.6555282e-06f, 4.9580707e-06f, 5.2802740e-06f, 5.6234160e-06f, 5.9888572e-06f, 6.3780469e-06f, 6.7925283e-06f, 7.2339451e-06f, 7.7040476e-06f, 8.2047000e-06f, 8.7378876e-06f, 9.3057248e-06f, 9.9104632e-06f, 1.0554501e-05f, 1.1240392e-05f, 1.1970856e-05f, 1.2748789e-05f, 1.3577278e-05f, 1.4459606e-05f, 1.5399272e-05f, 1.6400004e-05f, 1.7465768e-05f, 1.8600792e-05f, 1.9809576e-05f, 2.1096914e-05f, 2.2467911e-05f, 2.3928002e-05f, 2.5482978e-05f, 2.7139006e-05f, 2.8902651e-05f, 3.0780908e-05f, 3.2781225e-05f, 3.4911534e-05f, 3.7180282e-05f, 3.9596466e-05f, 4.2169667e-05f, 4.4910090e-05f, 4.7828601e-05f, 5.0936773e-05f, 5.4246931e-05f, 5.7772202e-05f, 6.1526565e-05f, 6.5524908e-05f, 6.9783085e-05f, 7.4317983e-05f, 7.9147585e-05f, 8.4291040e-05f, 8.9768747e-05f, 9.5602426e-05f, 0.00010181521f, 0.00010843174f, 0.00011547824f, 0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f, 0.00015820453f, 0.00016848555f, 0.00017943469f, 0.00019109536f, 0.00020351382f, 0.00021673929f, 0.00023082423f, 0.00024582449f, 0.00026179955f, 0.00027881276f, 0.00029693158f, 0.00031622787f, 0.00033677814f, 0.00035866388f, 0.00038197188f, 0.00040679456f, 0.00043323036f, 0.00046138411f, 0.00049136745f, 0.00052329927f, 0.00055730621f, 0.00059352311f, 0.00063209358f, 0.00067317058f, 0.00071691700f, 0.00076350630f, 0.00081312324f, 0.00086596457f, 0.00092223983f, 0.00098217216f, 0.0010459992f, 0.0011139742f, 0.0011863665f, 0.0012634633f, 0.0013455702f, 0.0014330129f, 0.0015261382f, 0.0016253153f, 0.0017309374f, 0.0018434235f, 0.0019632195f, 0.0020908006f, 0.0022266726f, 0.0023713743f, 0.0025254795f, 0.0026895994f, 0.0028643847f, 0.0030505286f, 0.0032487691f, 0.0034598925f, 0.0036847358f, 0.0039241906f, 0.0041792066f, 0.0044507950f, 0.0047400328f, 0.0050480668f, 0.0053761186f, 0.0057254891f, 0.0060975636f, 0.0064938176f, 0.0069158225f, 0.0073652516f, 0.0078438871f, 0.0083536271f, 0.0088964928f, 0.009474637f, 0.010090352f, 0.010746080f, 0.011444421f, 0.012188144f, 0.012980198f, 0.013823725f, 0.014722068f, 0.015678791f, 0.016697687f, 0.017782797f, 0.018938423f, 0.020169149f, 0.021479854f, 0.022875735f, 0.024362330f, 0.025945531f, 0.027631618f, 0.029427276f, 0.031339626f, 0.033376252f, 0.035545228f, 0.037855157f, 0.040315199f, 0.042935108f, 0.045725273f, 0.048696758f, 0.051861348f, 0.055231591f, 0.058820850f, 0.062643361f, 0.066714279f, 0.071049749f, 0.075666962f, 0.080584227f, 0.085821044f, 0.091398179f, 0.097337747f, 0.10366330f, 0.11039993f, 0.11757434f, 0.12521498f, 0.13335215f, 0.14201813f, 0.15124727f, 0.16107617f, 0.17154380f, 0.18269168f, 0.19456402f, 0.20720788f, 0.22067342f, 0.23501402f, 0.25028656f, 0.26655159f, 0.28387361f, 0.30232132f, 0.32196786f, 0.34289114f, 0.36517414f, 0.38890521f, 0.41417847f, 0.44109412f, 0.46975890f, 0.50028648f, 0.53279791f, 0.56742212f, 0.60429640f, 0.64356699f, 0.68538959f, 0.72993007f, 0.77736504f, 0.82788260f, 0.88168307f, 0.9389798f, 1.0f }; // @OPTIMIZE: if you want to replace this bresenham line-drawing routine, // note that you must produce bit-identical output to decode correctly; // this specific sequence of operations is specified in the spec (it's // drawing integer-quantized frequency-space lines that the encoder // expects to be exactly the same) // ... also, isn't the whole point of Bresenham's algorithm to NOT // have to divide in the setup? sigh. #ifndef STB_VORBIS_NO_DEFER_FLOOR #define LINE_OP(a,b) a *= b #else #define LINE_OP(a,b) a = b #endif #ifdef STB_VORBIS_DIVIDE_TABLE #define DIVTAB_NUMER 32 #define DIVTAB_DENOM 64 int8 integer_divide_table[DIVTAB_NUMER][DIVTAB_DENOM]; // 2KB #endif static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n) { int dy = y1 - y0; int adx = x1 - x0; int ady = abs(dy); int base; int x=x0,y=y0; int err = 0; int sy; #ifdef STB_VORBIS_DIVIDE_TABLE if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) { if (dy < 0) { base = -integer_divide_table[ady][adx]; sy = base-1; } else { base = integer_divide_table[ady][adx]; sy = base+1; } } else { base = dy / adx; if (dy < 0) sy = base - 1; else sy = base+1; } #else base = dy / adx; if (dy < 0) sy = base - 1; else sy = base+1; #endif ady -= abs(base) * adx; if (x1 > n) x1 = n; if (x < x1) { LINE_OP(output[x], inverse_db_table[y]); for (++x; x < x1; ++x) { err += ady; if (err >= adx) { err -= adx; y += sy; } else y += base; LINE_OP(output[x], inverse_db_table[y]); } } } static int residue_decode(vorb *f, Codebook *book, float *target, int offset, int n, int rtype) { int k; if (rtype == 0) { int step = n / book->dimensions; for (k=0; k < step; ++k) if (!codebook_decode_step(f, book, target+offset+k, n-offset-k, step)) return FALSE; } else { for (k=0; k < n; ) { if (!codebook_decode(f, book, target+offset, n-k)) return FALSE; k += book->dimensions; offset += book->dimensions; } } return TRUE; } // n is 1/2 of the blocksize -- // specification: "Correct per-vector decode length is [n]/2" static void decode_residue(vorb *f, float *residue_buffers[], int ch, int n, int rn, uint8 *do_not_decode) { int i,j,pass; Residue *r = f->residue_config + rn; int rtype = f->residue_types[rn]; int c = r->classbook; int classwords = f->codebooks[c].dimensions; unsigned int actual_size = rtype == 2 ? n*2 : n; unsigned int limit_r_begin = (r->begin < actual_size ? r->begin : actual_size); unsigned int limit_r_end = (r->end < actual_size ? r->end : actual_size); int n_read = limit_r_end - limit_r_begin; int part_read = n_read / r->part_size; int temp_alloc_point = temp_alloc_save(f); #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE uint8 ***part_classdata = (uint8 ***) temp_block_array(f,f->channels, part_read * sizeof(**part_classdata)); #else int **classifications = (int **) temp_block_array(f,f->channels, part_read * sizeof(**classifications)); #endif CHECK(f); for (i=0; i < ch; ++i) if (!do_not_decode[i]) memset(residue_buffers[i], 0, sizeof(float) * n); if (rtype == 2 && ch != 1) { for (j=0; j < ch; ++j) if (!do_not_decode[j]) break; if (j == ch) goto done; for (pass=0; pass < 8; ++pass) { int pcount = 0, class_set = 0; if (ch == 2) { while (pcount < part_read) { int z = r->begin + pcount*r->part_size; int c_inter = (z & 1), p_inter = z>>1; if (pass == 0) { Codebook *c = f->codebooks+r->classbook; int q; DECODE(q,f,c); if (q == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[0][class_set] = r->classdata[q]; #else for (i=classwords-1; i >= 0; --i) { classifications[0][i+pcount] = q % r->classifications; q /= r->classifications; } #endif } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { int z = r->begin + pcount*r->part_size; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[0][class_set][i]; #else int c = classifications[0][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { Codebook *book = f->codebooks + b; #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; #else // saves 1% if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; #endif } else { z += r->part_size; c_inter = z & 1; p_inter = z >> 1; } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } else if (ch == 1) { while (pcount < part_read) { int z = r->begin + pcount*r->part_size; int c_inter = 0, p_inter = z; if (pass == 0) { Codebook *c = f->codebooks+r->classbook; int q; DECODE(q,f,c); if (q == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[0][class_set] = r->classdata[q]; #else for (i=classwords-1; i >= 0; --i) { classifications[0][i+pcount] = q % r->classifications; q /= r->classifications; } #endif } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { int z = r->begin + pcount*r->part_size; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[0][class_set][i]; #else int c = classifications[0][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { Codebook *book = f->codebooks + b; if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; } else { z += r->part_size; c_inter = 0; p_inter = z; } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } else { while (pcount < part_read) { int z = r->begin + pcount*r->part_size; int c_inter = z % ch, p_inter = z/ch; if (pass == 0) { Codebook *c = f->codebooks+r->classbook; int q; DECODE(q,f,c); if (q == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[0][class_set] = r->classdata[q]; #else for (i=classwords-1; i >= 0; --i) { classifications[0][i+pcount] = q % r->classifications; q /= r->classifications; } #endif } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { int z = r->begin + pcount*r->part_size; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[0][class_set][i]; #else int c = classifications[0][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { Codebook *book = f->codebooks + b; if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; } else { z += r->part_size; c_inter = z % ch; p_inter = z / ch; } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } } goto done; } CHECK(f); for (pass=0; pass < 8; ++pass) { int pcount = 0, class_set=0; while (pcount < part_read) { if (pass == 0) { for (j=0; j < ch; ++j) { if (!do_not_decode[j]) { Codebook *c = f->codebooks+r->classbook; int temp; DECODE(temp,f,c); if (temp == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[j][class_set] = r->classdata[temp]; #else for (i=classwords-1; i >= 0; --i) { classifications[j][i+pcount] = temp % r->classifications; temp /= r->classifications; } #endif } } } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { for (j=0; j < ch; ++j) { if (!do_not_decode[j]) { #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[j][class_set][i]; #else int c = classifications[j][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { float *target = residue_buffers[j]; int offset = r->begin + pcount * r->part_size; int n = r->part_size; Codebook *book = f->codebooks + b; if (!residue_decode(f, book, target, offset, n, rtype)) goto done; } } } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } done: CHECK(f); #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE temp_free(f,part_classdata); #else temp_free(f,classifications); #endif temp_alloc_restore(f,temp_alloc_point); } #if 0 // slow way for debugging void inverse_mdct_slow(float *buffer, int n) { int i,j; int n2 = n >> 1; float *x = (float *) malloc(sizeof(*x) * n2); memcpy(x, buffer, sizeof(*x) * n2); for (i=0; i < n; ++i) { float acc = 0; for (j=0; j < n2; ++j) // formula from paper: //acc += n/4.0f * x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1)); // formula from wikipedia //acc += 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5)); // these are equivalent, except the formula from the paper inverts the multiplier! // however, what actually works is NO MULTIPLIER!?! //acc += 64 * 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5)); acc += x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1)); buffer[i] = acc; } free(x); } #elif 0 // same as above, but just barely able to run in real time on modern machines void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype) { float mcos[16384]; int i,j; int n2 = n >> 1, nmask = (n << 2) -1; float *x = (float *) malloc(sizeof(*x) * n2); memcpy(x, buffer, sizeof(*x) * n2); for (i=0; i < 4*n; ++i) mcos[i] = (float) cos(M_PI / 2 * i / n); for (i=0; i < n; ++i) { float acc = 0; for (j=0; j < n2; ++j) acc += x[j] * mcos[(2 * i + 1 + n2)*(2*j+1) & nmask]; buffer[i] = acc; } free(x); } #elif 0 // transform to use a slow dct-iv; this is STILL basically trivial, // but only requires half as many ops void dct_iv_slow(float *buffer, int n) { float mcos[16384]; float x[2048]; int i,j; int n2 = n >> 1, nmask = (n << 3) - 1; memcpy(x, buffer, sizeof(*x) * n); for (i=0; i < 8*n; ++i) mcos[i] = (float) cos(M_PI / 4 * i / n); for (i=0; i < n; ++i) { float acc = 0; for (j=0; j < n; ++j) acc += x[j] * mcos[((2 * i + 1)*(2*j+1)) & nmask]; buffer[i] = acc; } } void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype) { int i, n4 = n >> 2, n2 = n >> 1, n3_4 = n - n4; float temp[4096]; memcpy(temp, buffer, n2 * sizeof(float)); dct_iv_slow(temp, n2); // returns -c'-d, a-b' for (i=0; i < n4 ; ++i) buffer[i] = temp[i+n4]; // a-b' for ( ; i < n3_4; ++i) buffer[i] = -temp[n3_4 - i - 1]; // b-a', c+d' for ( ; i < n ; ++i) buffer[i] = -temp[i - n3_4]; // c'+d } #endif #ifndef LIBVORBIS_MDCT #define LIBVORBIS_MDCT 0 #endif #if LIBVORBIS_MDCT // directly call the vorbis MDCT using an interface documented // by Jeff Roberts... useful for performance comparison typedef struct { int n; int log2n; float *trig; int *bitrev; float scale; } mdct_lookup; extern void mdct_init(mdct_lookup *lookup, int n); extern void mdct_clear(mdct_lookup *l); extern void mdct_backward(mdct_lookup *init, float *in, float *out); mdct_lookup M1,M2; void inverse_mdct(float *buffer, int n, vorb *f, int blocktype) { mdct_lookup *M; if (M1.n == n) M = &M1; else if (M2.n == n) M = &M2; else if (M1.n == 0) { mdct_init(&M1, n); M = &M1; } else { if (M2.n) __asm int 3; mdct_init(&M2, n); M = &M2; } mdct_backward(M, buffer, buffer); } #endif // the following were split out into separate functions while optimizing; // they could be pushed back up but eh. __forceinline showed no change; // they're probably already being inlined. static void imdct_step3_iter0_loop(int n, float *e, int i_off, int k_off, float *A) { float *ee0 = e + i_off; float *ee2 = ee0 + k_off; int i; assert((n & 3) == 0); for (i=(n>>2); i > 0; --i) { float k00_20, k01_21; k00_20 = ee0[ 0] - ee2[ 0]; k01_21 = ee0[-1] - ee2[-1]; ee0[ 0] += ee2[ 0];//ee0[ 0] = ee0[ 0] + ee2[ 0]; ee0[-1] += ee2[-1];//ee0[-1] = ee0[-1] + ee2[-1]; ee2[ 0] = k00_20 * A[0] - k01_21 * A[1]; ee2[-1] = k01_21 * A[0] + k00_20 * A[1]; A += 8; k00_20 = ee0[-2] - ee2[-2]; k01_21 = ee0[-3] - ee2[-3]; ee0[-2] += ee2[-2];//ee0[-2] = ee0[-2] + ee2[-2]; ee0[-3] += ee2[-3];//ee0[-3] = ee0[-3] + ee2[-3]; ee2[-2] = k00_20 * A[0] - k01_21 * A[1]; ee2[-3] = k01_21 * A[0] + k00_20 * A[1]; A += 8; k00_20 = ee0[-4] - ee2[-4]; k01_21 = ee0[-5] - ee2[-5]; ee0[-4] += ee2[-4];//ee0[-4] = ee0[-4] + ee2[-4]; ee0[-5] += ee2[-5];//ee0[-5] = ee0[-5] + ee2[-5]; ee2[-4] = k00_20 * A[0] - k01_21 * A[1]; ee2[-5] = k01_21 * A[0] + k00_20 * A[1]; A += 8; k00_20 = ee0[-6] - ee2[-6]; k01_21 = ee0[-7] - ee2[-7]; ee0[-6] += ee2[-6];//ee0[-6] = ee0[-6] + ee2[-6]; ee0[-7] += ee2[-7];//ee0[-7] = ee0[-7] + ee2[-7]; ee2[-6] = k00_20 * A[0] - k01_21 * A[1]; ee2[-7] = k01_21 * A[0] + k00_20 * A[1]; A += 8; ee0 -= 8; ee2 -= 8; } } static void imdct_step3_inner_r_loop(int lim, float *e, int d0, int k_off, float *A, int k1) { int i; float k00_20, k01_21; float *e0 = e + d0; float *e2 = e0 + k_off; for (i=lim >> 2; i > 0; --i) { k00_20 = e0[-0] - e2[-0]; k01_21 = e0[-1] - e2[-1]; e0[-0] += e2[-0];//e0[-0] = e0[-0] + e2[-0]; e0[-1] += e2[-1];//e0[-1] = e0[-1] + e2[-1]; e2[-0] = (k00_20)*A[0] - (k01_21) * A[1]; e2[-1] = (k01_21)*A[0] + (k00_20) * A[1]; A += k1; k00_20 = e0[-2] - e2[-2]; k01_21 = e0[-3] - e2[-3]; e0[-2] += e2[-2];//e0[-2] = e0[-2] + e2[-2]; e0[-3] += e2[-3];//e0[-3] = e0[-3] + e2[-3]; e2[-2] = (k00_20)*A[0] - (k01_21) * A[1]; e2[-3] = (k01_21)*A[0] + (k00_20) * A[1]; A += k1; k00_20 = e0[-4] - e2[-4]; k01_21 = e0[-5] - e2[-5]; e0[-4] += e2[-4];//e0[-4] = e0[-4] + e2[-4]; e0[-5] += e2[-5];//e0[-5] = e0[-5] + e2[-5]; e2[-4] = (k00_20)*A[0] - (k01_21) * A[1]; e2[-5] = (k01_21)*A[0] + (k00_20) * A[1]; A += k1; k00_20 = e0[-6] - e2[-6]; k01_21 = e0[-7] - e2[-7]; e0[-6] += e2[-6];//e0[-6] = e0[-6] + e2[-6]; e0[-7] += e2[-7];//e0[-7] = e0[-7] + e2[-7]; e2[-6] = (k00_20)*A[0] - (k01_21) * A[1]; e2[-7] = (k01_21)*A[0] + (k00_20) * A[1]; e0 -= 8; e2 -= 8; A += k1; } } static void imdct_step3_inner_s_loop(int n, float *e, int i_off, int k_off, float *A, int a_off, int k0) { int i; float A0 = A[0]; float A1 = A[0+1]; float A2 = A[0+a_off]; float A3 = A[0+a_off+1]; float A4 = A[0+a_off*2+0]; float A5 = A[0+a_off*2+1]; float A6 = A[0+a_off*3+0]; float A7 = A[0+a_off*3+1]; float k00,k11; float *ee0 = e +i_off; float *ee2 = ee0+k_off; for (i=n; i > 0; --i) { k00 = ee0[ 0] - ee2[ 0]; k11 = ee0[-1] - ee2[-1]; ee0[ 0] = ee0[ 0] + ee2[ 0]; ee0[-1] = ee0[-1] + ee2[-1]; ee2[ 0] = (k00) * A0 - (k11) * A1; ee2[-1] = (k11) * A0 + (k00) * A1; k00 = ee0[-2] - ee2[-2]; k11 = ee0[-3] - ee2[-3]; ee0[-2] = ee0[-2] + ee2[-2]; ee0[-3] = ee0[-3] + ee2[-3]; ee2[-2] = (k00) * A2 - (k11) * A3; ee2[-3] = (k11) * A2 + (k00) * A3; k00 = ee0[-4] - ee2[-4]; k11 = ee0[-5] - ee2[-5]; ee0[-4] = ee0[-4] + ee2[-4]; ee0[-5] = ee0[-5] + ee2[-5]; ee2[-4] = (k00) * A4 - (k11) * A5; ee2[-5] = (k11) * A4 + (k00) * A5; k00 = ee0[-6] - ee2[-6]; k11 = ee0[-7] - ee2[-7]; ee0[-6] = ee0[-6] + ee2[-6]; ee0[-7] = ee0[-7] + ee2[-7]; ee2[-6] = (k00) * A6 - (k11) * A7; ee2[-7] = (k11) * A6 + (k00) * A7; ee0 -= k0; ee2 -= k0; } } static __forceinline void iter_54(float *z) { float k00,k11,k22,k33; float y0,y1,y2,y3; k00 = z[ 0] - z[-4]; y0 = z[ 0] + z[-4]; y2 = z[-2] + z[-6]; k22 = z[-2] - z[-6]; z[-0] = y0 + y2; // z0 + z4 + z2 + z6 z[-2] = y0 - y2; // z0 + z4 - z2 - z6 // done with y0,y2 k33 = z[-3] - z[-7]; z[-4] = k00 + k33; // z0 - z4 + z3 - z7 z[-6] = k00 - k33; // z0 - z4 - z3 + z7 // done with k33 k11 = z[-1] - z[-5]; y1 = z[-1] + z[-5]; y3 = z[-3] + z[-7]; z[-1] = y1 + y3; // z1 + z5 + z3 + z7 z[-3] = y1 - y3; // z1 + z5 - z3 - z7 z[-5] = k11 - k22; // z1 - z5 + z2 - z6 z[-7] = k11 + k22; // z1 - z5 - z2 + z6 } static void imdct_step3_inner_s_loop_ld654(int n, float *e, int i_off, float *A, int base_n) { int a_off = base_n >> 3; float A2 = A[0+a_off]; float *z = e + i_off; float *base = z - 16 * n; while (z > base) { float k00,k11; k00 = z[-0] - z[-8]; k11 = z[-1] - z[-9]; z[-0] = z[-0] + z[-8]; z[-1] = z[-1] + z[-9]; z[-8] = k00; z[-9] = k11 ; k00 = z[ -2] - z[-10]; k11 = z[ -3] - z[-11]; z[ -2] = z[ -2] + z[-10]; z[ -3] = z[ -3] + z[-11]; z[-10] = (k00+k11) * A2; z[-11] = (k11-k00) * A2; k00 = z[-12] - z[ -4]; // reverse to avoid a unary negation k11 = z[ -5] - z[-13]; z[ -4] = z[ -4] + z[-12]; z[ -5] = z[ -5] + z[-13]; z[-12] = k11; z[-13] = k00; k00 = z[-14] - z[ -6]; // reverse to avoid a unary negation k11 = z[ -7] - z[-15]; z[ -6] = z[ -6] + z[-14]; z[ -7] = z[ -7] + z[-15]; z[-14] = (k00+k11) * A2; z[-15] = (k00-k11) * A2; iter_54(z); iter_54(z-8); z -= 16; } } static void inverse_mdct(float *buffer, int n, vorb *f, int blocktype) { int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l; int ld; // @OPTIMIZE: reduce register pressure by using fewer variables? int save_point = temp_alloc_save(f); float *buf2 = (float *) temp_alloc(f, n2 * sizeof(*buf2)); float *u=NULL,*v=NULL; // twiddle factors float *A = f->A[blocktype]; // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio" // See notes about bugs in that paper in less-optimal implementation 'inverse_mdct_old' after this function. // kernel from paper // merged: // copy and reflect spectral data // step 0 // note that it turns out that the items added together during // this step are, in fact, being added to themselves (as reflected // by step 0). inexplicable inefficiency! this became obvious // once I combined the passes. // so there's a missing 'times 2' here (for adding X to itself). // this propagates through linearly to the end, where the numbers // are 1/2 too small, and need to be compensated for. { float *d,*e, *AA, *e_stop; d = &buf2[n2-2]; AA = A; e = &buffer[0]; e_stop = &buffer[n2]; while (e != e_stop) { d[1] = (e[0] * AA[0] - e[2]*AA[1]); d[0] = (e[0] * AA[1] + e[2]*AA[0]); d -= 2; AA += 2; e += 4; } e = &buffer[n2-3]; while (d >= buf2) { d[1] = (-e[2] * AA[0] - -e[0]*AA[1]); d[0] = (-e[2] * AA[1] + -e[0]*AA[0]); d -= 2; AA += 2; e -= 4; } } // now we use symbolic names for these, so that we can // possibly swap their meaning as we change which operations // are in place u = buffer; v = buf2; // step 2 (paper output is w, now u) // this could be in place, but the data ends up in the wrong // place... _somebody_'s got to swap it, so this is nominated { float *AA = &A[n2-8]; float *d0,*d1, *e0, *e1; e0 = &v[n4]; e1 = &v[0]; d0 = &u[n4]; d1 = &u[0]; while (AA >= A) { float v40_20, v41_21; v41_21 = e0[1] - e1[1]; v40_20 = e0[0] - e1[0]; d0[1] = e0[1] + e1[1]; d0[0] = e0[0] + e1[0]; d1[1] = v41_21*AA[4] - v40_20*AA[5]; d1[0] = v40_20*AA[4] + v41_21*AA[5]; v41_21 = e0[3] - e1[3]; v40_20 = e0[2] - e1[2]; d0[3] = e0[3] + e1[3]; d0[2] = e0[2] + e1[2]; d1[3] = v41_21*AA[0] - v40_20*AA[1]; d1[2] = v40_20*AA[0] + v41_21*AA[1]; AA -= 8; d0 += 4; d1 += 4; e0 += 4; e1 += 4; } } // step 3 ld = ilog(n) - 1; // ilog is off-by-one from normal definitions // optimized step 3: // the original step3 loop can be nested r inside s or s inside r; // it's written originally as s inside r, but this is dumb when r // iterates many times, and s few. So I have two copies of it and // switch between them halfway. // this is iteration 0 of step 3 imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*0, -(n >> 3), A); imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*1, -(n >> 3), A); // this is iteration 1 of step 3 imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*0, -(n >> 4), A, 16); imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*1, -(n >> 4), A, 16); imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*2, -(n >> 4), A, 16); imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*3, -(n >> 4), A, 16); l=2; for (; l < (ld-3)>>1; ++l) { int k0 = n >> (l+2), k0_2 = k0>>1; int lim = 1 << (l+1); int i; for (i=0; i < lim; ++i) imdct_step3_inner_r_loop(n >> (l+4), u, n2-1 - k0*i, -k0_2, A, 1 << (l+3)); } for (; l < ld-6; ++l) { int k0 = n >> (l+2), k1 = 1 << (l+3), k0_2 = k0>>1; int rlim = n >> (l+6), r; int lim = 1 << (l+1); int i_off; float *A0 = A; i_off = n2-1; for (r=rlim; r > 0; --r) { imdct_step3_inner_s_loop(lim, u, i_off, -k0_2, A0, k1, k0); A0 += k1*4; i_off -= 8; } } // iterations with count: // ld-6,-5,-4 all interleaved together // the big win comes from getting rid of needless flops // due to the constants on pass 5 & 4 being all 1 and 0; // combining them to be simultaneous to improve cache made little difference imdct_step3_inner_s_loop_ld654(n >> 5, u, n2-1, A, n); // output is u // step 4, 5, and 6 // cannot be in-place because of step 5 { uint16 *bitrev = f->bit_reverse[blocktype]; // weirdly, I'd have thought reading sequentially and writing // erratically would have been better than vice-versa, but in // fact that's not what my testing showed. (That is, with // j = bitreverse(i), do you read i and write j, or read j and write i.) float *d0 = &v[n4-4]; float *d1 = &v[n2-4]; while (d0 >= v) { int k4; k4 = bitrev[0]; d1[3] = u[k4+0]; d1[2] = u[k4+1]; d0[3] = u[k4+2]; d0[2] = u[k4+3]; k4 = bitrev[1]; d1[1] = u[k4+0]; d1[0] = u[k4+1]; d0[1] = u[k4+2]; d0[0] = u[k4+3]; d0 -= 4; d1 -= 4; bitrev += 2; } } // (paper output is u, now v) // data must be in buf2 assert(v == buf2); // step 7 (paper output is v, now v) // this is now in place { float *C = f->C[blocktype]; float *d, *e; d = v; e = v + n2 - 4; while (d < e) { float a02,a11,b0,b1,b2,b3; a02 = d[0] - e[2]; a11 = d[1] + e[3]; b0 = C[1]*a02 + C[0]*a11; b1 = C[1]*a11 - C[0]*a02; b2 = d[0] + e[ 2]; b3 = d[1] - e[ 3]; d[0] = b2 + b0; d[1] = b3 + b1; e[2] = b2 - b0; e[3] = b1 - b3; a02 = d[2] - e[0]; a11 = d[3] + e[1]; b0 = C[3]*a02 + C[2]*a11; b1 = C[3]*a11 - C[2]*a02; b2 = d[2] + e[ 0]; b3 = d[3] - e[ 1]; d[2] = b2 + b0; d[3] = b3 + b1; e[0] = b2 - b0; e[1] = b1 - b3; C += 4; d += 4; e -= 4; } } // data must be in buf2 // step 8+decode (paper output is X, now buffer) // this generates pairs of data a la 8 and pushes them directly through // the decode kernel (pushing rather than pulling) to avoid having // to make another pass later // this cannot POSSIBLY be in place, so we refer to the buffers directly { float *d0,*d1,*d2,*d3; float *B = f->B[blocktype] + n2 - 8; float *e = buf2 + n2 - 8; d0 = &buffer[0]; d1 = &buffer[n2-4]; d2 = &buffer[n2]; d3 = &buffer[n-4]; while (e >= v) { float p0,p1,p2,p3; p3 = e[6]*B[7] - e[7]*B[6]; p2 = -e[6]*B[6] - e[7]*B[7]; d0[0] = p3; d1[3] = - p3; d2[0] = p2; d3[3] = p2; p1 = e[4]*B[5] - e[5]*B[4]; p0 = -e[4]*B[4] - e[5]*B[5]; d0[1] = p1; d1[2] = - p1; d2[1] = p0; d3[2] = p0; p3 = e[2]*B[3] - e[3]*B[2]; p2 = -e[2]*B[2] - e[3]*B[3]; d0[2] = p3; d1[1] = - p3; d2[2] = p2; d3[1] = p2; p1 = e[0]*B[1] - e[1]*B[0]; p0 = -e[0]*B[0] - e[1]*B[1]; d0[3] = p1; d1[0] = - p1; d2[3] = p0; d3[0] = p0; B -= 8; e -= 8; d0 += 4; d2 += 4; d1 -= 4; d3 -= 4; } } temp_free(f,buf2); temp_alloc_restore(f,save_point); } #if 0 // this is the original version of the above code, if you want to optimize it from scratch void inverse_mdct_naive(float *buffer, int n) { float s; float A[1 << 12], B[1 << 12], C[1 << 11]; int i,k,k2,k4, n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l; int n3_4 = n - n4, ld; // how can they claim this only uses N words?! // oh, because they're only used sparsely, whoops float u[1 << 13], X[1 << 13], v[1 << 13], w[1 << 13]; // set up twiddle factors for (k=k2=0; k < n4; ++k,k2+=2) { A[k2 ] = (float) cos(4*k*M_PI/n); A[k2+1] = (float) -sin(4*k*M_PI/n); B[k2 ] = (float) cos((k2+1)*M_PI/n/2); B[k2+1] = (float) sin((k2+1)*M_PI/n/2); } for (k=k2=0; k < n8; ++k,k2+=2) { C[k2 ] = (float) cos(2*(k2+1)*M_PI/n); C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n); } // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio" // Note there are bugs in that pseudocode, presumably due to them attempting // to rename the arrays nicely rather than representing the way their actual // implementation bounces buffers back and forth. As a result, even in the // "some formulars corrected" version, a direct implementation fails. These // are noted below as "paper bug". // copy and reflect spectral data for (k=0; k < n2; ++k) u[k] = buffer[k]; for ( ; k < n ; ++k) u[k] = -buffer[n - k - 1]; // kernel from paper // step 1 for (k=k2=k4=0; k < n4; k+=1, k2+=2, k4+=4) { v[n-k4-1] = (u[k4] - u[n-k4-1]) * A[k2] - (u[k4+2] - u[n-k4-3])*A[k2+1]; v[n-k4-3] = (u[k4] - u[n-k4-1]) * A[k2+1] + (u[k4+2] - u[n-k4-3])*A[k2]; } // step 2 for (k=k4=0; k < n8; k+=1, k4+=4) { w[n2+3+k4] = v[n2+3+k4] + v[k4+3]; w[n2+1+k4] = v[n2+1+k4] + v[k4+1]; w[k4+3] = (v[n2+3+k4] - v[k4+3])*A[n2-4-k4] - (v[n2+1+k4]-v[k4+1])*A[n2-3-k4]; w[k4+1] = (v[n2+1+k4] - v[k4+1])*A[n2-4-k4] + (v[n2+3+k4]-v[k4+3])*A[n2-3-k4]; } // step 3 ld = ilog(n) - 1; // ilog is off-by-one from normal definitions for (l=0; l < ld-3; ++l) { int k0 = n >> (l+2), k1 = 1 << (l+3); int rlim = n >> (l+4), r4, r; int s2lim = 1 << (l+2), s2; for (r=r4=0; r < rlim; r4+=4,++r) { for (s2=0; s2 < s2lim; s2+=2) { u[n-1-k0*s2-r4] = w[n-1-k0*s2-r4] + w[n-1-k0*(s2+1)-r4]; u[n-3-k0*s2-r4] = w[n-3-k0*s2-r4] + w[n-3-k0*(s2+1)-r4]; u[n-1-k0*(s2+1)-r4] = (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1] - (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1+1]; u[n-3-k0*(s2+1)-r4] = (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1] + (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1+1]; } } if (l+1 < ld-3) { // paper bug: ping-ponging of u&w here is omitted memcpy(w, u, sizeof(u)); } } // step 4 for (i=0; i < n8; ++i) { int j = bit_reverse(i) >> (32-ld+3); assert(j < n8); if (i == j) { // paper bug: original code probably swapped in place; if copying, // need to directly copy in this case int i8 = i << 3; v[i8+1] = u[i8+1]; v[i8+3] = u[i8+3]; v[i8+5] = u[i8+5]; v[i8+7] = u[i8+7]; } else if (i < j) { int i8 = i << 3, j8 = j << 3; v[j8+1] = u[i8+1], v[i8+1] = u[j8 + 1]; v[j8+3] = u[i8+3], v[i8+3] = u[j8 + 3]; v[j8+5] = u[i8+5], v[i8+5] = u[j8 + 5]; v[j8+7] = u[i8+7], v[i8+7] = u[j8 + 7]; } } // step 5 for (k=0; k < n2; ++k) { w[k] = v[k*2+1]; } // step 6 for (k=k2=k4=0; k < n8; ++k, k2 += 2, k4 += 4) { u[n-1-k2] = w[k4]; u[n-2-k2] = w[k4+1]; u[n3_4 - 1 - k2] = w[k4+2]; u[n3_4 - 2 - k2] = w[k4+3]; } // step 7 for (k=k2=0; k < n8; ++k, k2 += 2) { v[n2 + k2 ] = ( u[n2 + k2] + u[n-2-k2] + C[k2+1]*(u[n2+k2]-u[n-2-k2]) + C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2; v[n-2 - k2] = ( u[n2 + k2] + u[n-2-k2] - C[k2+1]*(u[n2+k2]-u[n-2-k2]) - C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2; v[n2+1+ k2] = ( u[n2+1+k2] - u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2; v[n-1 - k2] = (-u[n2+1+k2] + u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2; } // step 8 for (k=k2=0; k < n4; ++k,k2 += 2) { X[k] = v[k2+n2]*B[k2 ] + v[k2+1+n2]*B[k2+1]; X[n2-1-k] = v[k2+n2]*B[k2+1] - v[k2+1+n2]*B[k2 ]; } // decode kernel to output // determined the following value experimentally // (by first figuring out what made inverse_mdct_slow work); then matching that here // (probably vorbis encoder premultiplies by n or n/2, to save it on the decoder?) s = 0.5; // theoretically would be n4 // [[[ note! the s value of 0.5 is compensated for by the B[] in the current code, // so it needs to use the "old" B values to behave correctly, or else // set s to 1.0 ]]] for (i=0; i < n4 ; ++i) buffer[i] = s * X[i+n4]; for ( ; i < n3_4; ++i) buffer[i] = -s * X[n3_4 - i - 1]; for ( ; i < n ; ++i) buffer[i] = -s * X[i - n3_4]; } #endif static float *get_window(vorb *f, int len) { len <<= 1; if (len == f->blocksize_0) return f->window[0]; if (len == f->blocksize_1) return f->window[1]; assert(0); return NULL; } #ifndef STB_VORBIS_NO_DEFER_FLOOR typedef int16 YTYPE; #else typedef int YTYPE; #endif static int do_floor(vorb *f, Mapping *map, int i, int n, float *target, YTYPE *finalY, uint8 *step2_flag) { int n2 = n >> 1; int s = map->chan[i].mux, floor; floor = map->submap_floor[s]; if (f->floor_types[floor] == 0) { return error(f, VORBIS_invalid_stream); } else { Floor1 *g = &f->floor_config[floor].floor1; int j,q; int lx = 0, ly = finalY[0] * g->floor1_multiplier; for (q=1; q < g->values; ++q) { j = g->sorted_order[q]; #ifndef STB_VORBIS_NO_DEFER_FLOOR if (finalY[j] >= 0) #else if (step2_flag[j]) #endif { int hy = finalY[j] * g->floor1_multiplier; int hx = g->Xlist[j]; if (lx != hx) draw_line(target, lx,ly, hx,hy, n2); CHECK(f); lx = hx, ly = hy; } } if (lx < n2) { // optimization of: draw_line(target, lx,ly, n,ly, n2); for (j=lx; j < n2; ++j) LINE_OP(target[j], inverse_db_table[ly]); CHECK(f); } } return TRUE; } // The meaning of "left" and "right" // // For a given frame: // we compute samples from 0..n // window_center is n/2 // we'll window and mix the samples from left_start to left_end with data from the previous frame // all of the samples from left_end to right_start can be output without mixing; however, // this interval is 0-length except when transitioning between short and long frames // all of the samples from right_start to right_end need to be mixed with the next frame, // which we don't have, so those get saved in a buffer // frame N's right_end-right_start, the number of samples to mix with the next frame, // has to be the same as frame N+1's left_end-left_start (which they are by // construction) static int vorbis_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode) { Mode *m; int i, n, prev, next, window_center; f->channel_buffer_start = f->channel_buffer_end = 0; retry: if (f->eof) return FALSE; if (!maybe_start_packet(f)) return FALSE; // check packet type if (get_bits(f,1) != 0) { if (IS_PUSH_MODE(f)) return error(f,VORBIS_bad_packet_type); while (EOP != get8_packet(f)); goto retry; } if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); i = get_bits(f, ilog(f->mode_count-1)); if (i == EOP) return FALSE; if (i >= f->mode_count) return FALSE; *mode = i; m = f->mode_config + i; if (m->blockflag) { n = f->blocksize_1; prev = get_bits(f,1); next = get_bits(f,1); } else { prev = next = 0; n = f->blocksize_0; } // WINDOWING window_center = n >> 1; if (m->blockflag && !prev) { *p_left_start = (n - f->blocksize_0) >> 2; *p_left_end = (n + f->blocksize_0) >> 2; } else { *p_left_start = 0; *p_left_end = window_center; } if (m->blockflag && !next) { *p_right_start = (n*3 - f->blocksize_0) >> 2; *p_right_end = (n*3 + f->blocksize_0) >> 2; } else { *p_right_start = window_center; *p_right_end = n; } return TRUE; } static int vorbis_decode_packet_rest(vorb *f, int *len, Mode *m, int left_start, int left_end, int right_start, int right_end, int *p_left) { Mapping *map; int i,j,k,n,n2; int zero_channel[256]; int really_zero_channel[256]; // WINDOWING n = f->blocksize[m->blockflag]; map = &f->mapping[m->mapping]; // FLOORS n2 = n >> 1; CHECK(f); for (i=0; i < f->channels; ++i) { int s = map->chan[i].mux, floor; zero_channel[i] = FALSE; floor = map->submap_floor[s]; if (f->floor_types[floor] == 0) { return error(f, VORBIS_invalid_stream); } else { Floor1 *g = &f->floor_config[floor].floor1; if (get_bits(f, 1)) { short *finalY; uint8 step2_flag[256]; static int range_list[4] = { 256, 128, 86, 64 }; int range = range_list[g->floor1_multiplier-1]; int offset = 2; finalY = f->finalY[i]; finalY[0] = get_bits(f, ilog(range)-1); finalY[1] = get_bits(f, ilog(range)-1); for (j=0; j < g->partitions; ++j) { int pclass = g->partition_class_list[j]; int cdim = g->class_dimensions[pclass]; int cbits = g->class_subclasses[pclass]; int csub = (1 << cbits)-1; int cval = 0; if (cbits) { Codebook *c = f->codebooks + g->class_masterbooks[pclass]; DECODE(cval,f,c); } for (k=0; k < cdim; ++k) { int book = g->subclass_books[pclass][cval & csub]; cval = cval >> cbits; if (book >= 0) { int temp; Codebook *c = f->codebooks + book; DECODE(temp,f,c); finalY[offset++] = temp; } else finalY[offset++] = 0; } } if (f->valid_bits == INVALID_BITS) goto error; // behavior according to spec step2_flag[0] = step2_flag[1] = 1; for (j=2; j < g->values; ++j) { int low, high, pred, highroom, lowroom, room, val; low = g->neighbors[j][0]; high = g->neighbors[j][1]; //neighbors(g->Xlist, j, &low, &high); pred = predict_point(g->Xlist[j], g->Xlist[low], g->Xlist[high], finalY[low], finalY[high]); val = finalY[j]; highroom = range - pred; lowroom = pred; if (highroom < lowroom) room = highroom * 2; else room = lowroom * 2; if (val) { step2_flag[low] = step2_flag[high] = 1; step2_flag[j] = 1; if (val >= room) if (highroom > lowroom) finalY[j] = val - lowroom + pred; else finalY[j] = pred - val + highroom - 1; else if (val & 1) finalY[j] = pred - ((val+1)>>1); else finalY[j] = pred + (val>>1); } else { step2_flag[j] = 0; finalY[j] = pred; } } #ifdef STB_VORBIS_NO_DEFER_FLOOR do_floor(f, map, i, n, f->floor_buffers[i], finalY, step2_flag); #else // defer final floor computation until _after_ residue for (j=0; j < g->values; ++j) { if (!step2_flag[j]) finalY[j] = -1; } #endif } else { error: zero_channel[i] = TRUE; } // So we just defer everything else to later // at this point we've decoded the floor into buffer } } CHECK(f); // at this point we've decoded all floors if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); // re-enable coupled channels if necessary memcpy(really_zero_channel, zero_channel, sizeof(really_zero_channel[0]) * f->channels); for (i=0; i < map->coupling_steps; ++i) if (!zero_channel[map->chan[i].magnitude] || !zero_channel[map->chan[i].angle]) { zero_channel[map->chan[i].magnitude] = zero_channel[map->chan[i].angle] = FALSE; } CHECK(f); // RESIDUE DECODE for (i=0; i < map->submaps; ++i) { float *residue_buffers[STB_VORBIS_MAX_CHANNELS]; int r; uint8 do_not_decode[256]; int ch = 0; for (j=0; j < f->channels; ++j) { if (map->chan[j].mux == i) { if (zero_channel[j]) { do_not_decode[ch] = TRUE; residue_buffers[ch] = NULL; } else { do_not_decode[ch] = FALSE; residue_buffers[ch] = f->channel_buffers[j]; } ++ch; } } r = map->submap_residue[i]; decode_residue(f, residue_buffers, ch, n2, r, do_not_decode); } if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); CHECK(f); // INVERSE COUPLING for (i = map->coupling_steps-1; i >= 0; --i) { int n2 = n >> 1; float *m = f->channel_buffers[map->chan[i].magnitude]; float *a = f->channel_buffers[map->chan[i].angle ]; for (j=0; j < n2; ++j) { float a2,m2; if (m[j] > 0) if (a[j] > 0) m2 = m[j], a2 = m[j] - a[j]; else a2 = m[j], m2 = m[j] + a[j]; else if (a[j] > 0) m2 = m[j], a2 = m[j] + a[j]; else a2 = m[j], m2 = m[j] - a[j]; m[j] = m2; a[j] = a2; } } CHECK(f); // finish decoding the floors #ifndef STB_VORBIS_NO_DEFER_FLOOR for (i=0; i < f->channels; ++i) { if (really_zero_channel[i]) { memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2); } else { do_floor(f, map, i, n, f->channel_buffers[i], f->finalY[i], NULL); } } #else for (i=0; i < f->channels; ++i) { if (really_zero_channel[i]) { memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2); } else { for (j=0; j < n2; ++j) f->channel_buffers[i][j] *= f->floor_buffers[i][j]; } } #endif // INVERSE MDCT CHECK(f); for (i=0; i < f->channels; ++i) inverse_mdct(f->channel_buffers[i], n, f, m->blockflag); CHECK(f); // this shouldn't be necessary, unless we exited on an error // and want to flush to get to the next packet flush_packet(f); if (f->first_decode) { // assume we start so first non-discarded sample is sample 0 // this isn't to spec, but spec would require us to read ahead // and decode the size of all current frames--could be done, // but presumably it's not a commonly used feature f->current_loc = -n2; // start of first frame is positioned for discard // we might have to discard samples "from" the next frame too, // if we're lapping a large block then a small at the start? f->discard_samples_deferred = n - right_end; f->current_loc_valid = TRUE; f->first_decode = FALSE; } else if (f->discard_samples_deferred) { if (f->discard_samples_deferred >= right_start - left_start) { f->discard_samples_deferred -= (right_start - left_start); left_start = right_start; *p_left = left_start; } else { left_start += f->discard_samples_deferred; *p_left = left_start; f->discard_samples_deferred = 0; } } else if (f->previous_length == 0 && f->current_loc_valid) { // we're recovering from a seek... that means we're going to discard // the samples from this packet even though we know our position from // the last page header, so we need to update the position based on // the discarded samples here // but wait, the code below is going to add this in itself even // on a discard, so we don't need to do it here... } // check if we have ogg information about the sample # for this packet if (f->last_seg_which == f->end_seg_with_known_loc) { // if we have a valid current loc, and this is final: if (f->current_loc_valid && (f->page_flag & PAGEFLAG_last_page)) { uint32 current_end = f->known_loc_for_packet; // then let's infer the size of the (probably) short final frame if (current_end < f->current_loc + (right_end-left_start)) { if (current_end < f->current_loc) { // negative truncation, that's impossible! *len = 0; } else { *len = current_end - f->current_loc; } *len += left_start; // this doesn't seem right, but has no ill effect on my test files if (*len > right_end) *len = right_end; // this should never happen f->current_loc += *len; return TRUE; } } // otherwise, just set our sample loc // guess that the ogg granule pos refers to the _middle_ of the // last frame? // set f->current_loc to the position of left_start f->current_loc = f->known_loc_for_packet - (n2-left_start); f->current_loc_valid = TRUE; } if (f->current_loc_valid) f->current_loc += (right_start - left_start); if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); *len = right_end; // ignore samples after the window goes to 0 CHECK(f); return TRUE; } static int vorbis_decode_packet(vorb *f, int *len, int *p_left, int *p_right) { int mode, left_end, right_end; if (!vorbis_decode_initial(f, p_left, &left_end, p_right, &right_end, &mode)) return 0; return vorbis_decode_packet_rest(f, len, f->mode_config + mode, *p_left, left_end, *p_right, right_end, p_left); } static int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right) { int prev,i,j; // we use right&left (the start of the right- and left-window sin()-regions) // to determine how much to return, rather than inferring from the rules // (same result, clearer code); 'left' indicates where our sin() window // starts, therefore where the previous window's right edge starts, and // therefore where to start mixing from the previous buffer. 'right' // indicates where our sin() ending-window starts, therefore that's where // we start saving, and where our returned-data ends. // mixin from previous window if (f->previous_length) { int i,j, n = f->previous_length; float *w = get_window(f, n); for (i=0; i < f->channels; ++i) { for (j=0; j < n; ++j) f->channel_buffers[i][left+j] = f->channel_buffers[i][left+j]*w[ j] + f->previous_window[i][ j]*w[n-1-j]; } } prev = f->previous_length; // last half of this data becomes previous window f->previous_length = len - right; // @OPTIMIZE: could avoid this copy by double-buffering the // output (flipping previous_window with channel_buffers), but // then previous_window would have to be 2x as large, and // channel_buffers couldn't be temp mem (although they're NOT // currently temp mem, they could be (unless we want to level // performance by spreading out the computation)) for (i=0; i < f->channels; ++i) for (j=0; right+j < len; ++j) f->previous_window[i][j] = f->channel_buffers[i][right+j]; if (!prev) // there was no previous packet, so this data isn't valid... // this isn't entirely true, only the would-have-overlapped data // isn't valid, but this seems to be what the spec requires return 0; // truncate a short frame if (len < right) right = len; f->samples_output += right-left; return right - left; } static int vorbis_pump_first_frame(stb_vorbis *f) { int len, right, left, res; res = vorbis_decode_packet(f, &len, &left, &right); if (res) vorbis_finish_frame(f, len, left, right); return res; } #ifndef STB_VORBIS_NO_PUSHDATA_API static int is_whole_packet_present(stb_vorbis *f, int end_page) { // make sure that we have the packet available before continuing... // this requires a full ogg parse, but we know we can fetch from f->stream // instead of coding this out explicitly, we could save the current read state, // read the next packet with get8() until end-of-packet, check f->eof, then // reset the state? but that would be slower, esp. since we'd have over 256 bytes // of state to restore (primarily the page segment table) int s = f->next_seg, first = TRUE; uint8 *p = f->stream; if (s != -1) { // if we're not starting the packet with a 'continue on next page' flag for (; s < f->segment_count; ++s) { p += f->segments[s]; if (f->segments[s] < 255) // stop at first short segment break; } // either this continues, or it ends it... if (end_page) if (s < f->segment_count-1) return error(f, VORBIS_invalid_stream); if (s == f->segment_count) s = -1; // set 'crosses page' flag if (p > f->stream_end) return error(f, VORBIS_need_more_data); first = FALSE; } for (; s == -1;) { uint8 *q; int n; // check that we have the page header ready if (p + 26 >= f->stream_end) return error(f, VORBIS_need_more_data); // validate the page if (memcmp(p, ogg_page_header, 4)) return error(f, VORBIS_invalid_stream); if (p[4] != 0) return error(f, VORBIS_invalid_stream); if (first) { // the first segment must NOT have 'continued_packet', later ones MUST if (f->previous_length) if ((p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream); // if no previous length, we're resynching, so we can come in on a continued-packet, // which we'll just drop } else { if (!(p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream); } n = p[26]; // segment counts q = p+27; // q points to segment table p = q + n; // advance past header // make sure we've read the segment table if (p > f->stream_end) return error(f, VORBIS_need_more_data); for (s=0; s < n; ++s) { p += q[s]; if (q[s] < 255) break; } if (end_page) if (s < n-1) return error(f, VORBIS_invalid_stream); if (s == n) s = -1; // set 'crosses page' flag if (p > f->stream_end) return error(f, VORBIS_need_more_data); first = FALSE; } return TRUE; } #endif // !STB_VORBIS_NO_PUSHDATA_API static int start_decoder(vorb *f) { uint8 header[6], x,y; int len,i,j,k, max_submaps = 0; int longest_floorlist=0; // first page, first packet if (!start_page(f)) return FALSE; // validate page flag if (!(f->page_flag & PAGEFLAG_first_page)) return error(f, VORBIS_invalid_first_page); if (f->page_flag & PAGEFLAG_last_page) return error(f, VORBIS_invalid_first_page); if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_invalid_first_page); // check for expected packet length if (f->segment_count != 1) return error(f, VORBIS_invalid_first_page); if (f->segments[0] != 30) { // check for the Ogg skeleton fishead identifying header to refine our error if (f->segments[0] == 64 && getn(f, header, 6) && header[0] == 'f' && header[1] == 'i' && header[2] == 's' && header[3] == 'h' && header[4] == 'e' && header[5] == 'a' && get8(f) == 'd' && get8(f) == '\0') return error(f, VORBIS_ogg_skeleton_not_supported); else return error(f, VORBIS_invalid_first_page); } // read packet // check packet header if (get8(f) != VORBIS_packet_id) return error(f, VORBIS_invalid_first_page); if (!getn(f, header, 6)) return error(f, VORBIS_unexpected_eof); if (!vorbis_validate(header)) return error(f, VORBIS_invalid_first_page); // vorbis_version if (get32(f) != 0) return error(f, VORBIS_invalid_first_page); f->channels = get8(f); if (!f->channels) return error(f, VORBIS_invalid_first_page); if (f->channels > STB_VORBIS_MAX_CHANNELS) return error(f, VORBIS_too_many_channels); f->sample_rate = get32(f); if (!f->sample_rate) return error(f, VORBIS_invalid_first_page); get32(f); // bitrate_maximum get32(f); // bitrate_nominal get32(f); // bitrate_minimum x = get8(f); { int log0,log1; log0 = x & 15; log1 = x >> 4; f->blocksize_0 = 1 << log0; f->blocksize_1 = 1 << log1; if (log0 < 6 || log0 > 13) return error(f, VORBIS_invalid_setup); if (log1 < 6 || log1 > 13) return error(f, VORBIS_invalid_setup); if (log0 > log1) return error(f, VORBIS_invalid_setup); } // framing_flag x = get8(f); if (!(x & 1)) return error(f, VORBIS_invalid_first_page); // second packet! if (!start_page(f)) return FALSE; if (!start_packet(f)) return FALSE; do { len = next_segment(f); skip(f, len); f->bytes_in_seg = 0; } while (len); // third packet! if (!start_packet(f)) return FALSE; #ifndef STB_VORBIS_NO_PUSHDATA_API if (IS_PUSH_MODE(f)) { if (!is_whole_packet_present(f, TRUE)) { // convert error in ogg header to write type if (f->error == VORBIS_invalid_stream) f->error = VORBIS_invalid_setup; return FALSE; } } #endif crc32_init(); // always init it, to avoid multithread race conditions if (get8_packet(f) != VORBIS_packet_setup) return error(f, VORBIS_invalid_setup); for (i=0; i < 6; ++i) header[i] = get8_packet(f); if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup); // codebooks f->codebook_count = get_bits(f,8) + 1; f->codebooks = (Codebook *) setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count); if (f->codebooks == NULL) return error(f, VORBIS_outofmem); memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count); for (i=0; i < f->codebook_count; ++i) { uint32 *values; int ordered, sorted_count; int total=0; uint8 *lengths; Codebook *c = f->codebooks+i; CHECK(f); x = get_bits(f, 8); if (x != 0x42) return error(f, VORBIS_invalid_setup); x = get_bits(f, 8); if (x != 0x43) return error(f, VORBIS_invalid_setup); x = get_bits(f, 8); if (x != 0x56) return error(f, VORBIS_invalid_setup); x = get_bits(f, 8); c->dimensions = (get_bits(f, 8)<<8) + x; x = get_bits(f, 8); y = get_bits(f, 8); c->entries = (get_bits(f, 8)<<16) + (y<<8) + x; ordered = get_bits(f,1); c->sparse = ordered ? 0 : get_bits(f,1); if (c->dimensions == 0 && c->entries != 0) return error(f, VORBIS_invalid_setup); if (c->sparse) lengths = (uint8 *) setup_temp_malloc(f, c->entries); else lengths = c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries); if (!lengths) return error(f, VORBIS_outofmem); if (ordered) { int current_entry = 0; int current_length = get_bits(f,5) + 1; while (current_entry < c->entries) { int limit = c->entries - current_entry; int n = get_bits(f, ilog(limit)); if (current_entry + n > (int) c->entries) { return error(f, VORBIS_invalid_setup); } memset(lengths + current_entry, current_length, n); current_entry += n; ++current_length; } } else { for (j=0; j < c->entries; ++j) { int present = c->sparse ? get_bits(f,1) : 1; if (present) { lengths[j] = get_bits(f, 5) + 1; ++total; if (lengths[j] == 32) return error(f, VORBIS_invalid_setup); } else { lengths[j] = NO_CODE; } } } if (c->sparse && total >= c->entries >> 2) { // convert sparse items to non-sparse! if (c->entries > (int) f->setup_temp_memory_required) f->setup_temp_memory_required = c->entries; c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries); if (c->codeword_lengths == NULL) return error(f, VORBIS_outofmem); memcpy(c->codeword_lengths, lengths, c->entries); setup_temp_free(f, lengths, c->entries); // note this is only safe if there have been no intervening temp mallocs! lengths = c->codeword_lengths; c->sparse = 0; } // compute the size of the sorted tables if (c->sparse) { sorted_count = total; } else { sorted_count = 0; #ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH for (j=0; j < c->entries; ++j) if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE) ++sorted_count; #endif } c->sorted_entries = sorted_count; values = NULL; CHECK(f); if (!c->sparse) { c->codewords = (uint32 *) setup_malloc(f, sizeof(c->codewords[0]) * c->entries); if (!c->codewords) return error(f, VORBIS_outofmem); } else { unsigned int size; if (c->sorted_entries) { c->codeword_lengths = (uint8 *) setup_malloc(f, c->sorted_entries); if (!c->codeword_lengths) return error(f, VORBIS_outofmem); c->codewords = (uint32 *) setup_temp_malloc(f, sizeof(*c->codewords) * c->sorted_entries); if (!c->codewords) return error(f, VORBIS_outofmem); values = (uint32 *) setup_temp_malloc(f, sizeof(*values) * c->sorted_entries); if (!values) return error(f, VORBIS_outofmem); } size = c->entries + (sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries; if (size > f->setup_temp_memory_required) f->setup_temp_memory_required = size; } if (!compute_codewords(c, lengths, c->entries, values)) { if (c->sparse) setup_temp_free(f, values, 0); return error(f, VORBIS_invalid_setup); } if (c->sorted_entries) { // allocate an extra slot for sentinels c->sorted_codewords = (uint32 *) setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries+1)); if (c->sorted_codewords == NULL) return error(f, VORBIS_outofmem); // allocate an extra slot at the front so that c->sorted_values[-1] is defined // so that we can catch that case without an extra if c->sorted_values = ( int *) setup_malloc(f, sizeof(*c->sorted_values ) * (c->sorted_entries+1)); if (c->sorted_values == NULL) return error(f, VORBIS_outofmem); ++c->sorted_values; c->sorted_values[-1] = -1; compute_sorted_huffman(c, lengths, values); } if (c->sparse) { setup_temp_free(f, values, sizeof(*values)*c->sorted_entries); setup_temp_free(f, c->codewords, sizeof(*c->codewords)*c->sorted_entries); setup_temp_free(f, lengths, c->entries); c->codewords = NULL; } compute_accelerated_huffman(c); CHECK(f); c->lookup_type = get_bits(f, 4); if (c->lookup_type > 2) return error(f, VORBIS_invalid_setup); if (c->lookup_type > 0) { uint16 *mults; c->minimum_value = float32_unpack(get_bits(f, 32)); c->delta_value = float32_unpack(get_bits(f, 32)); c->value_bits = get_bits(f, 4)+1; c->sequence_p = get_bits(f,1); if (c->lookup_type == 1) { c->lookup_values = lookup1_values(c->entries, c->dimensions); } else { c->lookup_values = c->entries * c->dimensions; } if (c->lookup_values == 0) return error(f, VORBIS_invalid_setup); mults = (uint16 *) setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values); if (mults == NULL) return error(f, VORBIS_outofmem); for (j=0; j < (int) c->lookup_values; ++j) { int q = get_bits(f, c->value_bits); if (q == EOP) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); } mults[j] = q; } #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { int len, sparse = c->sparse; float last=0; // pre-expand the lookup1-style multiplicands, to avoid a divide in the inner loop if (sparse) { if (c->sorted_entries == 0) goto skip; c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions); } else c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions); if (c->multiplicands == NULL) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); } len = sparse ? c->sorted_entries : c->entries; for (j=0; j < len; ++j) { unsigned int z = sparse ? c->sorted_values[j] : j; unsigned int div=1; for (k=0; k < c->dimensions; ++k) { int off = (z / div) % c->lookup_values; float val = mults[off]; val = mults[off]*c->delta_value + c->minimum_value + last; c->multiplicands[j*c->dimensions + k] = val; if (c->sequence_p) last = val; if (k+1 < c->dimensions) { if (div > UINT_MAX / (unsigned int) c->lookup_values) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); } div *= c->lookup_values; } } } c->lookup_type = 2; } else #endif { float last=0; CHECK(f); c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values); if (c->multiplicands == NULL) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); } for (j=0; j < (int) c->lookup_values; ++j) { float val = mults[j] * c->delta_value + c->minimum_value + last; c->multiplicands[j] = val; if (c->sequence_p) last = val; } } #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK skip:; #endif setup_temp_free(f, mults, sizeof(mults[0])*c->lookup_values); CHECK(f); } CHECK(f); } // time domain transfers (notused) x = get_bits(f, 6) + 1; for (i=0; i < x; ++i) { uint32 z = get_bits(f, 16); if (z != 0) return error(f, VORBIS_invalid_setup); } // Floors f->floor_count = get_bits(f, 6)+1; f->floor_config = (Floor *) setup_malloc(f, f->floor_count * sizeof(*f->floor_config)); if (f->floor_config == NULL) return error(f, VORBIS_outofmem); for (i=0; i < f->floor_count; ++i) { f->floor_types[i] = get_bits(f, 16); if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup); if (f->floor_types[i] == 0) { Floor0 *g = &f->floor_config[i].floor0; g->order = get_bits(f,8); g->rate = get_bits(f,16); g->bark_map_size = get_bits(f,16); g->amplitude_bits = get_bits(f,6); g->amplitude_offset = get_bits(f,8); g->number_of_books = get_bits(f,4) + 1; for (j=0; j < g->number_of_books; ++j) g->book_list[j] = get_bits(f,8); return error(f, VORBIS_feature_not_supported); } else { stbv__floor_ordering p[31*8+2]; Floor1 *g = &f->floor_config[i].floor1; int max_class = -1; g->partitions = get_bits(f, 5); for (j=0; j < g->partitions; ++j) { g->partition_class_list[j] = get_bits(f, 4); if (g->partition_class_list[j] > max_class) max_class = g->partition_class_list[j]; } for (j=0; j <= max_class; ++j) { g->class_dimensions[j] = get_bits(f, 3)+1; g->class_subclasses[j] = get_bits(f, 2); if (g->class_subclasses[j]) { g->class_masterbooks[j] = get_bits(f, 8); if (g->class_masterbooks[j] >= f->codebook_count) return error(f, VORBIS_invalid_setup); } for (k=0; k < 1 << g->class_subclasses[j]; ++k) { g->subclass_books[j][k] = get_bits(f,8)-1; if (g->subclass_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup); } } g->floor1_multiplier = get_bits(f,2)+1; g->rangebits = get_bits(f,4); g->Xlist[0] = 0; g->Xlist[1] = 1 << g->rangebits; g->values = 2; for (j=0; j < g->partitions; ++j) { int c = g->partition_class_list[j]; for (k=0; k < g->class_dimensions[c]; ++k) { g->Xlist[g->values] = get_bits(f, g->rangebits); ++g->values; } } // precompute the sorting for (j=0; j < g->values; ++j) { p[j].x = g->Xlist[j]; p[j].id = j; } qsort(p, g->values, sizeof(p[0]), point_compare); for (j=0; j < g->values; ++j) g->sorted_order[j] = (uint8) p[j].id; // precompute the neighbors for (j=2; j < g->values; ++j) { int low,hi; neighbors(g->Xlist, j, &low,&hi); g->neighbors[j][0] = low; g->neighbors[j][1] = hi; } if (g->values > longest_floorlist) longest_floorlist = g->values; } } // Residue f->residue_count = get_bits(f, 6)+1; f->residue_config = (Residue *) setup_malloc(f, f->residue_count * sizeof(f->residue_config[0])); if (f->residue_config == NULL) return error(f, VORBIS_outofmem); memset(f->residue_config, 0, f->residue_count * sizeof(f->residue_config[0])); for (i=0; i < f->residue_count; ++i) { uint8 residue_cascade[64]; Residue *r = f->residue_config+i; f->residue_types[i] = get_bits(f, 16); if (f->residue_types[i] > 2) return error(f, VORBIS_invalid_setup); r->begin = get_bits(f, 24); r->end = get_bits(f, 24); if (r->end < r->begin) return error(f, VORBIS_invalid_setup); r->part_size = get_bits(f,24)+1; r->classifications = get_bits(f,6)+1; r->classbook = get_bits(f,8); if (r->classbook >= f->codebook_count) return error(f, VORBIS_invalid_setup); for (j=0; j < r->classifications; ++j) { uint8 high_bits=0; uint8 low_bits=get_bits(f,3); if (get_bits(f,1)) high_bits = get_bits(f,5); residue_cascade[j] = high_bits*8 + low_bits; } r->residue_books = (short (*)[8]) setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications); if (r->residue_books == NULL) return error(f, VORBIS_outofmem); for (j=0; j < r->classifications; ++j) { for (k=0; k < 8; ++k) { if (residue_cascade[j] & (1 << k)) { r->residue_books[j][k] = get_bits(f, 8); if (r->residue_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup); } else { r->residue_books[j][k] = -1; } } } // precompute the classifications[] array to avoid inner-loop mod/divide // call it 'classdata' since we already have r->classifications r->classdata = (uint8 **) setup_malloc(f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries); if (!r->classdata) return error(f, VORBIS_outofmem); memset(r->classdata, 0, sizeof(*r->classdata) * f->codebooks[r->classbook].entries); for (j=0; j < f->codebooks[r->classbook].entries; ++j) { int classwords = f->codebooks[r->classbook].dimensions; int temp = j; r->classdata[j] = (uint8 *) setup_malloc(f, sizeof(r->classdata[j][0]) * classwords); if (r->classdata[j] == NULL) return error(f, VORBIS_outofmem); for (k=classwords-1; k >= 0; --k) { r->classdata[j][k] = temp % r->classifications; temp /= r->classifications; } } } f->mapping_count = get_bits(f,6)+1; f->mapping = (Mapping *) setup_malloc(f, f->mapping_count * sizeof(*f->mapping)); if (f->mapping == NULL) return error(f, VORBIS_outofmem); memset(f->mapping, 0, f->mapping_count * sizeof(*f->mapping)); for (i=0; i < f->mapping_count; ++i) { Mapping *m = f->mapping + i; int mapping_type = get_bits(f,16); if (mapping_type != 0) return error(f, VORBIS_invalid_setup); m->chan = (MappingChannel *) setup_malloc(f, f->channels * sizeof(*m->chan)); if (m->chan == NULL) return error(f, VORBIS_outofmem); if (get_bits(f,1)) m->submaps = get_bits(f,4)+1; else m->submaps = 1; if (m->submaps > max_submaps) max_submaps = m->submaps; if (get_bits(f,1)) { m->coupling_steps = get_bits(f,8)+1; for (k=0; k < m->coupling_steps; ++k) { m->chan[k].magnitude = get_bits(f, ilog(f->channels-1)); m->chan[k].angle = get_bits(f, ilog(f->channels-1)); if (m->chan[k].magnitude >= f->channels) return error(f, VORBIS_invalid_setup); if (m->chan[k].angle >= f->channels) return error(f, VORBIS_invalid_setup); if (m->chan[k].magnitude == m->chan[k].angle) return error(f, VORBIS_invalid_setup); } } else m->coupling_steps = 0; // reserved field if (get_bits(f,2)) return error(f, VORBIS_invalid_setup); if (m->submaps > 1) { for (j=0; j < f->channels; ++j) { m->chan[j].mux = get_bits(f, 4); if (m->chan[j].mux >= m->submaps) return error(f, VORBIS_invalid_setup); } } else // @SPECIFICATION: this case is missing from the spec for (j=0; j < f->channels; ++j) m->chan[j].mux = 0; for (j=0; j < m->submaps; ++j) { get_bits(f,8); // discard m->submap_floor[j] = get_bits(f,8); m->submap_residue[j] = get_bits(f,8); if (m->submap_floor[j] >= f->floor_count) return error(f, VORBIS_invalid_setup); if (m->submap_residue[j] >= f->residue_count) return error(f, VORBIS_invalid_setup); } } // Modes f->mode_count = get_bits(f, 6)+1; for (i=0; i < f->mode_count; ++i) { Mode *m = f->mode_config+i; m->blockflag = get_bits(f,1); m->windowtype = get_bits(f,16); m->transformtype = get_bits(f,16); m->mapping = get_bits(f,8); if (m->windowtype != 0) return error(f, VORBIS_invalid_setup); if (m->transformtype != 0) return error(f, VORBIS_invalid_setup); if (m->mapping >= f->mapping_count) return error(f, VORBIS_invalid_setup); } flush_packet(f); f->previous_length = 0; for (i=0; i < f->channels; ++i) { f->channel_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1); f->previous_window[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2); f->finalY[i] = (int16 *) setup_malloc(f, sizeof(int16) * longest_floorlist); if (f->channel_buffers[i] == NULL || f->previous_window[i] == NULL || f->finalY[i] == NULL) return error(f, VORBIS_outofmem); memset(f->channel_buffers[i], 0, sizeof(float) * f->blocksize_1); #ifdef STB_VORBIS_NO_DEFER_FLOOR f->floor_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2); if (f->floor_buffers[i] == NULL) return error(f, VORBIS_outofmem); #endif } if (!init_blocksize(f, 0, f->blocksize_0)) return FALSE; if (!init_blocksize(f, 1, f->blocksize_1)) return FALSE; f->blocksize[0] = f->blocksize_0; f->blocksize[1] = f->blocksize_1; #ifdef STB_VORBIS_DIVIDE_TABLE if (integer_divide_table[1][1]==0) for (i=0; i < DIVTAB_NUMER; ++i) for (j=1; j < DIVTAB_DENOM; ++j) integer_divide_table[i][j] = i / j; #endif // compute how much temporary memory is needed // 1. { uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1); uint32 classify_mem; int i,max_part_read=0; for (i=0; i < f->residue_count; ++i) { Residue *r = f->residue_config + i; unsigned int actual_size = f->blocksize_1 / 2; unsigned int limit_r_begin = r->begin < actual_size ? r->begin : actual_size; unsigned int limit_r_end = r->end < actual_size ? r->end : actual_size; int n_read = limit_r_end - limit_r_begin; int part_read = n_read / r->part_size; if (part_read > max_part_read) max_part_read = part_read; } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(uint8 *)); #else classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int *)); #endif // maximum reasonable partition size is f->blocksize_1 f->temp_memory_required = classify_mem; if (imdct_mem > f->temp_memory_required) f->temp_memory_required = imdct_mem; } f->first_decode = TRUE; if (f->alloc.alloc_buffer) { assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes); // check if there's enough temp memory so we don't error later if (f->setup_offset + sizeof(*f) + f->temp_memory_required > (unsigned) f->temp_offset) return error(f, VORBIS_outofmem); } f->first_audio_page_offset = stb_vorbis_get_file_offset(f); return TRUE; } static void vorbis_deinit(stb_vorbis *p) { int i,j; if (p->residue_config) { for (i=0; i < p->residue_count; ++i) { Residue *r = p->residue_config+i; if (r->classdata) { for (j=0; j < p->codebooks[r->classbook].entries; ++j) setup_free(p, r->classdata[j]); setup_free(p, r->classdata); } setup_free(p, r->residue_books); } } if (p->codebooks) { CHECK(p); for (i=0; i < p->codebook_count; ++i) { Codebook *c = p->codebooks + i; setup_free(p, c->codeword_lengths); setup_free(p, c->multiplicands); setup_free(p, c->codewords); setup_free(p, c->sorted_codewords); // c->sorted_values[-1] is the first entry in the array setup_free(p, c->sorted_values ? c->sorted_values-1 : NULL); } setup_free(p, p->codebooks); } setup_free(p, p->floor_config); setup_free(p, p->residue_config); if (p->mapping) { for (i=0; i < p->mapping_count; ++i) setup_free(p, p->mapping[i].chan); setup_free(p, p->mapping); } CHECK(p); for (i=0; i < p->channels && i < STB_VORBIS_MAX_CHANNELS; ++i) { setup_free(p, p->channel_buffers[i]); setup_free(p, p->previous_window[i]); #ifdef STB_VORBIS_NO_DEFER_FLOOR setup_free(p, p->floor_buffers[i]); #endif setup_free(p, p->finalY[i]); } for (i=0; i < 2; ++i) { setup_free(p, p->A[i]); setup_free(p, p->B[i]); setup_free(p, p->C[i]); setup_free(p, p->window[i]); setup_free(p, p->bit_reverse[i]); } #ifndef STB_VORBIS_NO_STDIO if (p->close_on_free) fclose(p->f); #endif } void stb_vorbis_close(stb_vorbis *p) { if (p == NULL) return; vorbis_deinit(p); setup_free(p,p); } static void vorbis_init(stb_vorbis *p, const stb_vorbis_alloc *z) { memset(p, 0, sizeof(*p)); // NULL out all malloc'd pointers to start if (z) { p->alloc = *z; p->alloc.alloc_buffer_length_in_bytes = (p->alloc.alloc_buffer_length_in_bytes+3) & ~3; p->temp_offset = p->alloc.alloc_buffer_length_in_bytes; } p->eof = 0; p->error = VORBIS__no_error; p->stream = NULL; p->codebooks = NULL; p->page_crc_tests = -1; #ifndef STB_VORBIS_NO_STDIO p->close_on_free = FALSE; p->f = NULL; #endif } int stb_vorbis_get_sample_offset(stb_vorbis *f) { if (f->current_loc_valid) return f->current_loc; else return -1; } stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f) { stb_vorbis_info d; d.channels = f->channels; d.sample_rate = f->sample_rate; d.setup_memory_required = f->setup_memory_required; d.setup_temp_memory_required = f->setup_temp_memory_required; d.temp_memory_required = f->temp_memory_required; d.max_frame_size = f->blocksize_1 >> 1; return d; } int stb_vorbis_get_error(stb_vorbis *f) { int e = f->error; f->error = VORBIS__no_error; return e; } static stb_vorbis * vorbis_alloc(stb_vorbis *f) { stb_vorbis *p = (stb_vorbis *) setup_malloc(f, sizeof(*p)); return p; } #ifndef STB_VORBIS_NO_PUSHDATA_API void stb_vorbis_flush_pushdata(stb_vorbis *f) { f->previous_length = 0; f->page_crc_tests = 0; f->discard_samples_deferred = 0; f->current_loc_valid = FALSE; f->first_decode = FALSE; f->samples_output = 0; f->channel_buffer_start = 0; f->channel_buffer_end = 0; } static int vorbis_search_for_page_pushdata(vorb *f, uint8 *data, int data_len) { int i,n; for (i=0; i < f->page_crc_tests; ++i) f->scan[i].bytes_done = 0; // if we have room for more scans, search for them first, because // they may cause us to stop early if their header is incomplete if (f->page_crc_tests < STB_VORBIS_PUSHDATA_CRC_COUNT) { if (data_len < 4) return 0; data_len -= 3; // need to look for 4-byte sequence, so don't miss // one that straddles a boundary for (i=0; i < data_len; ++i) { if (data[i] == 0x4f) { if (0==memcmp(data+i, ogg_page_header, 4)) { int j,len; uint32 crc; // make sure we have the whole page header if (i+26 >= data_len || i+27+data[i+26] >= data_len) { // only read up to this page start, so hopefully we'll // have the whole page header start next time data_len = i; break; } // ok, we have it all; compute the length of the page len = 27 + data[i+26]; for (j=0; j < data[i+26]; ++j) len += data[i+27+j]; // scan everything up to the embedded crc (which we must 0) crc = 0; for (j=0; j < 22; ++j) crc = crc32_update(crc, data[i+j]); // now process 4 0-bytes for ( ; j < 26; ++j) crc = crc32_update(crc, 0); // len is the total number of bytes we need to scan n = f->page_crc_tests++; f->scan[n].bytes_left = len-j; f->scan[n].crc_so_far = crc; f->scan[n].goal_crc = data[i+22] + (data[i+23] << 8) + (data[i+24]<<16) + (data[i+25]<<24); // if the last frame on a page is continued to the next, then // we can't recover the sample_loc immediately if (data[i+27+data[i+26]-1] == 255) f->scan[n].sample_loc = ~0; else f->scan[n].sample_loc = data[i+6] + (data[i+7] << 8) + (data[i+ 8]<<16) + (data[i+ 9]<<24); f->scan[n].bytes_done = i+j; if (f->page_crc_tests == STB_VORBIS_PUSHDATA_CRC_COUNT) break; // keep going if we still have room for more } } } } for (i=0; i < f->page_crc_tests;) { uint32 crc; int j; int n = f->scan[i].bytes_done; int m = f->scan[i].bytes_left; if (m > data_len - n) m = data_len - n; // m is the bytes to scan in the current chunk crc = f->scan[i].crc_so_far; for (j=0; j < m; ++j) crc = crc32_update(crc, data[n+j]); f->scan[i].bytes_left -= m; f->scan[i].crc_so_far = crc; if (f->scan[i].bytes_left == 0) { // does it match? if (f->scan[i].crc_so_far == f->scan[i].goal_crc) { // Houston, we have page data_len = n+m; // consumption amount is wherever that scan ended f->page_crc_tests = -1; // drop out of page scan mode f->previous_length = 0; // decode-but-don't-output one frame f->next_seg = -1; // start a new page f->current_loc = f->scan[i].sample_loc; // set the current sample location // to the amount we'd have decoded had we decoded this page f->current_loc_valid = f->current_loc != ~0U; return data_len; } // delete entry f->scan[i] = f->scan[--f->page_crc_tests]; } else { ++i; } } return data_len; } // return value: number of bytes we used int stb_vorbis_decode_frame_pushdata( stb_vorbis *f, // the file we're decoding const uint8 *data, int data_len, // the memory available for decoding int *channels, // place to write number of float * buffers float ***output, // place to write float ** array of float * buffers int *samples // place to write number of output samples ) { int i; int len,right,left; if (!IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); if (f->page_crc_tests >= 0) { *samples = 0; return vorbis_search_for_page_pushdata(f, (uint8 *) data, data_len); } f->stream = (uint8 *) data; f->stream_end = (uint8 *) data + data_len; f->error = VORBIS__no_error; // check that we have the entire packet in memory if (!is_whole_packet_present(f, FALSE)) { *samples = 0; return 0; } if (!vorbis_decode_packet(f, &len, &left, &right)) { // save the actual error we encountered enum STBVorbisError error = f->error; if (error == VORBIS_bad_packet_type) { // flush and resynch f->error = VORBIS__no_error; while (get8_packet(f) != EOP) if (f->eof) break; *samples = 0; return (int) (f->stream - data); } if (error == VORBIS_continued_packet_flag_invalid) { if (f->previous_length == 0) { // we may be resynching, in which case it's ok to hit one // of these; just discard the packet f->error = VORBIS__no_error; while (get8_packet(f) != EOP) if (f->eof) break; *samples = 0; return (int) (f->stream - data); } } // if we get an error while parsing, what to do? // well, it DEFINITELY won't work to continue from where we are! stb_vorbis_flush_pushdata(f); // restore the error that actually made us bail f->error = error; *samples = 0; return 1; } // success! len = vorbis_finish_frame(f, len, left, right); for (i=0; i < f->channels; ++i) f->outputs[i] = f->channel_buffers[i] + left; if (channels) *channels = f->channels; *samples = len; *output = f->outputs; return (int) (f->stream - data); } stb_vorbis *stb_vorbis_open_pushdata( const unsigned char *data, int data_len, // the memory available for decoding int *data_used, // only defined if result is not NULL int *error, const stb_vorbis_alloc *alloc) { stb_vorbis *f, p; vorbis_init(&p, alloc); p.stream = (uint8 *) data; p.stream_end = (uint8 *) data + data_len; p.push_mode = TRUE; if (!start_decoder(&p)) { if (p.eof) *error = VORBIS_need_more_data; else *error = p.error; return NULL; } f = vorbis_alloc(&p); if (f) { *f = p; *data_used = (int) (f->stream - data); *error = 0; return f; } else { vorbis_deinit(&p); return NULL; } } #endif // STB_VORBIS_NO_PUSHDATA_API unsigned int stb_vorbis_get_file_offset(stb_vorbis *f) { #ifndef STB_VORBIS_NO_PUSHDATA_API if (f->push_mode) return 0; #endif if (USE_MEMORY(f)) return (unsigned int) (f->stream - f->stream_start); #ifndef STB_VORBIS_NO_STDIO return (unsigned int) (ftell(f->f) - f->f_start); #endif } #ifndef STB_VORBIS_NO_PULLDATA_API // // DATA-PULLING API // static uint32 vorbis_find_page(stb_vorbis *f, uint32 *end, uint32 *last) { for(;;) { int n; if (f->eof) return 0; n = get8(f); if (n == 0x4f) { // page header candidate unsigned int retry_loc = stb_vorbis_get_file_offset(f); int i; // check if we're off the end of a file_section stream if (retry_loc - 25 > f->stream_len) return 0; // check the rest of the header for (i=1; i < 4; ++i) if (get8(f) != ogg_page_header[i]) break; if (f->eof) return 0; if (i == 4) { uint8 header[27]; uint32 i, crc, goal, len; for (i=0; i < 4; ++i) header[i] = ogg_page_header[i]; for (; i < 27; ++i) header[i] = get8(f); if (f->eof) return 0; if (header[4] != 0) goto invalid; goal = header[22] + (header[23] << 8) + (header[24]<<16) + (header[25]<<24); for (i=22; i < 26; ++i) header[i] = 0; crc = 0; for (i=0; i < 27; ++i) crc = crc32_update(crc, header[i]); len = 0; for (i=0; i < header[26]; ++i) { int s = get8(f); crc = crc32_update(crc, s); len += s; } if (len && f->eof) return 0; for (i=0; i < len; ++i) crc = crc32_update(crc, get8(f)); // finished parsing probable page if (crc == goal) { // we could now check that it's either got the last // page flag set, OR it's followed by the capture // pattern, but I guess TECHNICALLY you could have // a file with garbage between each ogg page and recover // from it automatically? So even though that paranoia // might decrease the chance of an invalid decode by // another 2^32, not worth it since it would hose those // invalid-but-useful files? if (end) *end = stb_vorbis_get_file_offset(f); if (last) { if (header[5] & 0x04) *last = 1; else *last = 0; } set_file_offset(f, retry_loc-1); return 1; } } invalid: // not a valid page, so rewind and look for next one set_file_offset(f, retry_loc); } } } #define SAMPLE_unknown 0xffffffff // seeking is implemented with a binary search, which narrows down the range to // 64K, before using a linear search (because finding the synchronization // pattern can be expensive, and the chance we'd find the end page again is // relatively high for small ranges) // // two initial interpolation-style probes are used at the start of the search // to try to bound either side of the binary search sensibly, while still // working in O(log n) time if they fail. static int get_seek_page_info(stb_vorbis *f, ProbedPage *z) { uint8 header[27], lacing[255]; int i,len; // record where the page starts z->page_start = stb_vorbis_get_file_offset(f); // parse the header getn(f, header, 27); if (header[0] != 'O' || header[1] != 'g' || header[2] != 'g' || header[3] != 'S') return 0; getn(f, lacing, header[26]); // determine the length of the payload len = 0; for (i=0; i < header[26]; ++i) len += lacing[i]; // this implies where the page ends z->page_end = z->page_start + 27 + header[26] + len; // read the last-decoded sample out of the data z->last_decoded_sample = header[6] + (header[7] << 8) + (header[8] << 16) + (header[9] << 24); // restore file state to where we were set_file_offset(f, z->page_start); return 1; } // rarely used function to seek back to the preceding page while finding the // start of a packet static int go_to_page_before(stb_vorbis *f, unsigned int limit_offset) { unsigned int previous_safe, end; // now we want to seek back 64K from the limit if (limit_offset >= 65536 && limit_offset-65536 >= f->first_audio_page_offset) previous_safe = limit_offset - 65536; else previous_safe = f->first_audio_page_offset; set_file_offset(f, previous_safe); while (vorbis_find_page(f, &end, NULL)) { if (end >= limit_offset && stb_vorbis_get_file_offset(f) < limit_offset) return 1; set_file_offset(f, end); } return 0; } // implements the search logic for finding a page and starting decoding. if // the function succeeds, current_loc_valid will be true and current_loc will // be less than or equal to the provided sample number (the closer the // better). static int seek_to_sample_coarse(stb_vorbis *f, uint32 sample_number) { ProbedPage left, right, mid; int i, start_seg_with_known_loc, end_pos, page_start; uint32 delta, stream_length, padding; double offset, bytes_per_sample; int probe = 0; // find the last page and validate the target sample stream_length = stb_vorbis_stream_length_in_samples(f); if (stream_length == 0) return error(f, VORBIS_seek_without_length); if (sample_number > stream_length) return error(f, VORBIS_seek_invalid); // this is the maximum difference between the window-center (which is the // actual granule position value), and the right-start (which the spec // indicates should be the granule position (give or take one)). padding = ((f->blocksize_1 - f->blocksize_0) >> 2); if (sample_number < padding) sample_number = 0; else sample_number -= padding; left = f->p_first; while (left.last_decoded_sample == ~0U) { // (untested) the first page does not have a 'last_decoded_sample' set_file_offset(f, left.page_end); if (!get_seek_page_info(f, &left)) goto error; } right = f->p_last; assert(right.last_decoded_sample != ~0U); // starting from the start is handled differently if (sample_number <= left.last_decoded_sample) { if (stb_vorbis_seek_start(f)) return 1; return 0; } while (left.page_end != right.page_start) { assert(left.page_end < right.page_start); // search range in bytes delta = right.page_start - left.page_end; if (delta <= 65536) { // there's only 64K left to search - handle it linearly set_file_offset(f, left.page_end); } else { if (probe < 2) { if (probe == 0) { // first probe (interpolate) double data_bytes = right.page_end - left.page_start; bytes_per_sample = data_bytes / right.last_decoded_sample; offset = left.page_start + bytes_per_sample * (sample_number - left.last_decoded_sample); } else { // second probe (try to bound the other side) double error = ((double) sample_number - mid.last_decoded_sample) * bytes_per_sample; if (error >= 0 && error < 8000) error = 8000; if (error < 0 && error > -8000) error = -8000; offset += error * 2; } // ensure the offset is valid if (offset < left.page_end) offset = left.page_end; if (offset > right.page_start - 65536) offset = right.page_start - 65536; set_file_offset(f, (unsigned int) offset); } else { // binary search for large ranges (offset by 32K to ensure // we don't hit the right page) set_file_offset(f, left.page_end + (delta / 2) - 32768); } if (!vorbis_find_page(f, NULL, NULL)) goto error; } for (;;) { if (!get_seek_page_info(f, &mid)) goto error; if (mid.last_decoded_sample != ~0U) break; // (untested) no frames end on this page set_file_offset(f, mid.page_end); assert(mid.page_start < right.page_start); } // if we've just found the last page again then we're in a tricky file, // and we're close enough. if (mid.page_start == right.page_start) break; if (sample_number < mid.last_decoded_sample) right = mid; else left = mid; ++probe; } // seek back to start of the last packet page_start = left.page_start; set_file_offset(f, page_start); if (!start_page(f)) return error(f, VORBIS_seek_failed); end_pos = f->end_seg_with_known_loc; assert(end_pos >= 0); for (;;) { for (i = end_pos; i > 0; --i) if (f->segments[i-1] != 255) break; start_seg_with_known_loc = i; if (start_seg_with_known_loc > 0 || !(f->page_flag & PAGEFLAG_continued_packet)) break; // (untested) the final packet begins on an earlier page if (!go_to_page_before(f, page_start)) goto error; page_start = stb_vorbis_get_file_offset(f); if (!start_page(f)) goto error; end_pos = f->segment_count - 1; } // prepare to start decoding f->current_loc_valid = FALSE; f->last_seg = FALSE; f->valid_bits = 0; f->packet_bytes = 0; f->bytes_in_seg = 0; f->previous_length = 0; f->next_seg = start_seg_with_known_loc; for (i = 0; i < start_seg_with_known_loc; i++) skip(f, f->segments[i]); // start decoding (optimizable - this frame is generally discarded) if (!vorbis_pump_first_frame(f)) return 0; if (f->current_loc > sample_number) return error(f, VORBIS_seek_failed); return 1; error: // try to restore the file to a valid state stb_vorbis_seek_start(f); return error(f, VORBIS_seek_failed); } // the same as vorbis_decode_initial, but without advancing static int peek_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode) { int bits_read, bytes_read; if (!vorbis_decode_initial(f, p_left_start, p_left_end, p_right_start, p_right_end, mode)) return 0; // either 1 or 2 bytes were read, figure out which so we can rewind bits_read = 1 + ilog(f->mode_count-1); if (f->mode_config[*mode].blockflag) bits_read += 2; bytes_read = (bits_read + 7) / 8; f->bytes_in_seg += bytes_read; f->packet_bytes -= bytes_read; skip(f, -bytes_read); if (f->next_seg == -1) f->next_seg = f->segment_count - 1; else f->next_seg--; f->valid_bits = 0; return 1; } int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number) { uint32 max_frame_samples; if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); // fast page-level search if (!seek_to_sample_coarse(f, sample_number)) return 0; assert(f->current_loc_valid); assert(f->current_loc <= sample_number); // linear search for the relevant packet max_frame_samples = (f->blocksize_1*3 - f->blocksize_0) >> 2; while (f->current_loc < sample_number) { int left_start, left_end, right_start, right_end, mode, frame_samples; if (!peek_decode_initial(f, &left_start, &left_end, &right_start, &right_end, &mode)) return error(f, VORBIS_seek_failed); // calculate the number of samples returned by the next frame frame_samples = right_start - left_start; if (f->current_loc + frame_samples > sample_number) { return 1; // the next frame will contain the sample } else if (f->current_loc + frame_samples + max_frame_samples > sample_number) { // there's a chance the frame after this could contain the sample vorbis_pump_first_frame(f); } else { // this frame is too early to be relevant f->current_loc += frame_samples; f->previous_length = 0; maybe_start_packet(f); flush_packet(f); } } // the next frame will start with the sample assert(f->current_loc == sample_number); return 1; } int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number) { if (!stb_vorbis_seek_frame(f, sample_number)) return 0; if (sample_number != f->current_loc) { int n; uint32 frame_start = f->current_loc; stb_vorbis_get_frame_float(f, &n, NULL); assert(sample_number > frame_start); assert(f->channel_buffer_start + (int) (sample_number-frame_start) <= f->channel_buffer_end); f->channel_buffer_start += (sample_number - frame_start); } return 1; } int stb_vorbis_seek_start(stb_vorbis *f) { if (IS_PUSH_MODE(f)) { return error(f, VORBIS_invalid_api_mixing); } set_file_offset(f, f->first_audio_page_offset); f->previous_length = 0; f->first_decode = TRUE; f->next_seg = -1; return vorbis_pump_first_frame(f); } unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f) { unsigned int restore_offset, previous_safe; unsigned int end, last_page_loc; if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); if (!f->total_samples) { unsigned int last; uint32 lo,hi; char header[6]; // first, store the current decode position so we can restore it restore_offset = stb_vorbis_get_file_offset(f); // now we want to seek back 64K from the end (the last page must // be at most a little less than 64K, but let's allow a little slop) if (f->stream_len >= 65536 && f->stream_len-65536 >= f->first_audio_page_offset) previous_safe = f->stream_len - 65536; else previous_safe = f->first_audio_page_offset; set_file_offset(f, previous_safe); // previous_safe is now our candidate 'earliest known place that seeking // to will lead to the final page' if (!vorbis_find_page(f, &end, &last)) { // if we can't find a page, we're hosed! f->error = VORBIS_cant_find_last_page; f->total_samples = 0xffffffff; goto done; } // check if there are more pages last_page_loc = stb_vorbis_get_file_offset(f); // stop when the last_page flag is set, not when we reach eof; // this allows us to stop short of a 'file_section' end without // explicitly checking the length of the section while (!last) { set_file_offset(f, end); if (!vorbis_find_page(f, &end, &last)) { // the last page we found didn't have the 'last page' flag // set. whoops! break; } previous_safe = last_page_loc+1; last_page_loc = stb_vorbis_get_file_offset(f); } set_file_offset(f, last_page_loc); // parse the header getn(f, (unsigned char *)header, 6); // extract the absolute granule position lo = get32(f); hi = get32(f); if (lo == 0xffffffff && hi == 0xffffffff) { f->error = VORBIS_cant_find_last_page; f->total_samples = SAMPLE_unknown; goto done; } if (hi) lo = 0xfffffffe; // saturate f->total_samples = lo; f->p_last.page_start = last_page_loc; f->p_last.page_end = end; f->p_last.last_decoded_sample = lo; done: set_file_offset(f, restore_offset); } return f->total_samples == SAMPLE_unknown ? 0 : f->total_samples; } float stb_vorbis_stream_length_in_seconds(stb_vorbis *f) { return stb_vorbis_stream_length_in_samples(f) / (float) f->sample_rate; } int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output) { int len, right,left,i; if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); if (!vorbis_decode_packet(f, &len, &left, &right)) { f->channel_buffer_start = f->channel_buffer_end = 0; return 0; } len = vorbis_finish_frame(f, len, left, right); for (i=0; i < f->channels; ++i) f->outputs[i] = f->channel_buffers[i] + left; f->channel_buffer_start = left; f->channel_buffer_end = left+len; if (channels) *channels = f->channels; if (output) *output = f->outputs; return len; } #ifndef STB_VORBIS_NO_STDIO stb_vorbis * stb_vorbis_open_file_section(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc, unsigned int length) { stb_vorbis *f, p; vorbis_init(&p, alloc); p.f = file; p.f_start = (uint32) ftell(file); p.stream_len = length; p.close_on_free = close_on_free; if (start_decoder(&p)) { f = vorbis_alloc(&p); if (f) { *f = p; vorbis_pump_first_frame(f); return f; } } if (error) *error = p.error; vorbis_deinit(&p); return NULL; } stb_vorbis * stb_vorbis_open_file(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc) { unsigned int len, start; start = (unsigned int) ftell(file); fseek(file, 0, SEEK_END); len = (unsigned int) (ftell(file) - start); fseek(file, start, SEEK_SET); return stb_vorbis_open_file_section(file, close_on_free, error, alloc, len); } stb_vorbis * stb_vorbis_open_filename(const char *filename, int *error, const stb_vorbis_alloc *alloc) { FILE *f; #if defined(_WIN32) && defined(__STDC_WANT_SECURE_LIB__) if (0 != fopen_s(&f, filename, "rb")) f = NULL; #else f = fopen(filename, "rb"); #endif if (f) return stb_vorbis_open_file(f, TRUE, error, alloc); if (error) *error = VORBIS_file_open_failure; return NULL; } #endif // STB_VORBIS_NO_STDIO stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, int *error, const stb_vorbis_alloc *alloc) { stb_vorbis *f, p; if (data == NULL) return NULL; vorbis_init(&p, alloc); p.stream = (uint8 *) data; p.stream_end = (uint8 *) data + len; p.stream_start = (uint8 *) p.stream; p.stream_len = len; p.push_mode = FALSE; if (start_decoder(&p)) { f = vorbis_alloc(&p); if (f) { *f = p; vorbis_pump_first_frame(f); if (error) *error = VORBIS__no_error; return f; } } if (error) *error = p.error; vorbis_deinit(&p); return NULL; } #ifndef STB_VORBIS_NO_INTEGER_CONVERSION #define PLAYBACK_MONO 1 #define PLAYBACK_LEFT 2 #define PLAYBACK_RIGHT 4 #define L (PLAYBACK_LEFT | PLAYBACK_MONO) #define C (PLAYBACK_LEFT | PLAYBACK_RIGHT | PLAYBACK_MONO) #define R (PLAYBACK_RIGHT | PLAYBACK_MONO) static int8 channel_position[7][6] = { { 0 }, { C }, { L, R }, { L, C, R }, { L, R, L, R }, { L, C, R, L, R }, { L, C, R, L, R, C }, }; #ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT typedef union { float f; int i; } float_conv; typedef char stb_vorbis_float_size_test[sizeof(float)==4 && sizeof(int) == 4]; #define FASTDEF(x) float_conv x // add (1<<23) to convert to int, then divide by 2^SHIFT, then add 0.5/2^SHIFT to round #define MAGIC(SHIFT) (1.5f * (1 << (23-SHIFT)) + 0.5f/(1 << SHIFT)) #define ADDEND(SHIFT) (((150-SHIFT) << 23) + (1 << 22)) #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) (temp.f = (x) + MAGIC(s), temp.i - ADDEND(s)) #define check_endianness() #else #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) ((int) ((x) * (1 << (s)))) #define check_endianness() #define FASTDEF(x) #endif static void copy_samples(short *dest, float *src, int len) { int i; check_endianness(); for (i=0; i < len; ++i) { FASTDEF(temp); int v = FAST_SCALED_FLOAT_TO_INT(temp, src[i],15); if ((unsigned int) (v + 32768) > 65535) v = v < 0 ? -32768 : 32767; dest[i] = v; } } static void compute_samples(int mask, short *output, int num_c, float **data, int d_offset, int len) { #define BUFFER_SIZE 32 float buffer[BUFFER_SIZE]; int i,j,o,n = BUFFER_SIZE; check_endianness(); for (o = 0; o < len; o += BUFFER_SIZE) { memset(buffer, 0, sizeof(buffer)); if (o + n > len) n = len - o; for (j=0; j < num_c; ++j) { if (channel_position[num_c][j] & mask) { for (i=0; i < n; ++i) buffer[i] += data[j][d_offset+o+i]; } } for (i=0; i < n; ++i) { FASTDEF(temp); int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15); if ((unsigned int) (v + 32768) > 65535) v = v < 0 ? -32768 : 32767; output[o+i] = v; } } } static void compute_stereo_samples(short *output, int num_c, float **data, int d_offset, int len) { #define BUFFER_SIZE 32 float buffer[BUFFER_SIZE]; int i,j,o,n = BUFFER_SIZE >> 1; // o is the offset in the source data check_endianness(); for (o = 0; o < len; o += BUFFER_SIZE >> 1) { // o2 is the offset in the output data int o2 = o << 1; memset(buffer, 0, sizeof(buffer)); if (o + n > len) n = len - o; for (j=0; j < num_c; ++j) { int m = channel_position[num_c][j] & (PLAYBACK_LEFT | PLAYBACK_RIGHT); if (m == (PLAYBACK_LEFT | PLAYBACK_RIGHT)) { for (i=0; i < n; ++i) { buffer[i*2+0] += data[j][d_offset+o+i]; buffer[i*2+1] += data[j][d_offset+o+i]; } } else if (m == PLAYBACK_LEFT) { for (i=0; i < n; ++i) { buffer[i*2+0] += data[j][d_offset+o+i]; } } else if (m == PLAYBACK_RIGHT) { for (i=0; i < n; ++i) { buffer[i*2+1] += data[j][d_offset+o+i]; } } } for (i=0; i < (n<<1); ++i) { FASTDEF(temp); int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15); if ((unsigned int) (v + 32768) > 65535) v = v < 0 ? -32768 : 32767; output[o2+i] = v; } } } static void convert_samples_short(int buf_c, short **buffer, int b_offset, int data_c, float **data, int d_offset, int samples) { int i; if (buf_c != data_c && buf_c <= 2 && data_c <= 6) { static int channel_selector[3][2] = { {0}, {PLAYBACK_MONO}, {PLAYBACK_LEFT, PLAYBACK_RIGHT} }; for (i=0; i < buf_c; ++i) compute_samples(channel_selector[buf_c][i], buffer[i]+b_offset, data_c, data, d_offset, samples); } else { int limit = buf_c < data_c ? buf_c : data_c; for (i=0; i < limit; ++i) copy_samples(buffer[i]+b_offset, data[i]+d_offset, samples); for ( ; i < buf_c; ++i) memset(buffer[i]+b_offset, 0, sizeof(short) * samples); } } int stb_vorbis_get_frame_short(stb_vorbis *f, int num_c, short **buffer, int num_samples) { float **output; int len = stb_vorbis_get_frame_float(f, NULL, &output); if (len > num_samples) len = num_samples; if (len) convert_samples_short(num_c, buffer, 0, f->channels, output, 0, len); return len; } static void convert_channels_short_interleaved(int buf_c, short *buffer, int data_c, float **data, int d_offset, int len) { int i; check_endianness(); if (buf_c != data_c && buf_c <= 2 && data_c <= 6) { assert(buf_c == 2); for (i=0; i < buf_c; ++i) compute_stereo_samples(buffer, data_c, data, d_offset, len); } else { int limit = buf_c < data_c ? buf_c : data_c; int j; for (j=0; j < len; ++j) { for (i=0; i < limit; ++i) { FASTDEF(temp); float f = data[i][d_offset+j]; int v = FAST_SCALED_FLOAT_TO_INT(temp, f,15);//data[i][d_offset+j],15); if ((unsigned int) (v + 32768) > 65535) v = v < 0 ? -32768 : 32767; *buffer++ = v; } for ( ; i < buf_c; ++i) *buffer++ = 0; } } } int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts) { float **output; int len; if (num_c == 1) return stb_vorbis_get_frame_short(f,num_c,&buffer, num_shorts); len = stb_vorbis_get_frame_float(f, NULL, &output); if (len) { if (len*num_c > num_shorts) len = num_shorts / num_c; convert_channels_short_interleaved(num_c, buffer, f->channels, output, 0, len); } return len; } int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts) { float **outputs; int len = num_shorts / channels; int n=0; int z = f->channels; if (z > channels) z = channels; while (n < len) { int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= len) k = len - n; if (k) convert_channels_short_interleaved(channels, buffer, f->channels, f->channel_buffers, f->channel_buffer_start, k); buffer += k*channels; n += k; f->channel_buffer_start += k; if (n == len) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int len) { float **outputs; int n=0; int z = f->channels; if (z > channels) z = channels; while (n < len) { int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= len) k = len - n; if (k) convert_samples_short(channels, buffer, n, f->channels, f->channel_buffers, f->channel_buffer_start, k); n += k; f->channel_buffer_start += k; if (n == len) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } #ifndef STB_VORBIS_NO_STDIO int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output) { int data_len, offset, total, limit, error; short *data; stb_vorbis *v = stb_vorbis_open_filename(filename, &error, NULL); if (v == NULL) return -1; limit = v->channels * 4096; *channels = v->channels; if (sample_rate) *sample_rate = v->sample_rate; offset = data_len = 0; total = limit; data = (short *) malloc(total * sizeof(*data)); if (data == NULL) { stb_vorbis_close(v); return -2; } for (;;) { int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset); if (n == 0) break; data_len += n; offset += n * v->channels; if (offset + limit > total) { short *data2; total *= 2; data2 = (short *) realloc(data, total * sizeof(*data)); if (data2 == NULL) { free(data); stb_vorbis_close(v); return -2; } data = data2; } } *output = data; stb_vorbis_close(v); return data_len; } #endif // NO_STDIO int stb_vorbis_decode_memory(const uint8 *mem, int len, int *channels, int *sample_rate, short **output) { int data_len, offset, total, limit, error; short *data; stb_vorbis *v = stb_vorbis_open_memory(mem, len, &error, NULL); if (v == NULL) return -1; limit = v->channels * 4096; *channels = v->channels; if (sample_rate) *sample_rate = v->sample_rate; offset = data_len = 0; total = limit; data = (short *) malloc(total * sizeof(*data)); if (data == NULL) { stb_vorbis_close(v); return -2; } for (;;) { int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset); if (n == 0) break; data_len += n; offset += n * v->channels; if (offset + limit > total) { short *data2; total *= 2; data2 = (short *) realloc(data, total * sizeof(*data)); if (data2 == NULL) { free(data); stb_vorbis_close(v); return -2; } data = data2; } } *output = data; stb_vorbis_close(v); return data_len; } #endif // STB_VORBIS_NO_INTEGER_CONVERSION int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats) { float **outputs; int len = num_floats / channels; int n=0; int z = f->channels; if (z > channels) z = channels; while (n < len) { int i,j; int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= len) k = len - n; for (j=0; j < k; ++j) { for (i=0; i < z; ++i) *buffer++ = f->channel_buffers[i][f->channel_buffer_start+j]; for ( ; i < channels; ++i) *buffer++ = 0; } n += k; f->channel_buffer_start += k; if (n == len) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples) { float **outputs; int n=0; int z = f->channels; if (z > channels) z = channels; while (n < num_samples) { int i; int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= num_samples) k = num_samples - n; if (k) { for (i=0; i < z; ++i) memcpy(buffer[i]+n, f->channel_buffers[i]+f->channel_buffer_start, sizeof(float)*k); for ( ; i < channels; ++i) memset(buffer[i]+n, 0, sizeof(float) * k); } n += k; f->channel_buffer_start += k; if (n == num_samples) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } #endif // STB_VORBIS_NO_PULLDATA_API /* Version history 1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files 1.11 - 2017-07-23 - fix MinGW compilation 1.10 - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory 1.09 - 2016-04-04 - back out 'avoid discarding last frame' fix from previous version 1.08 - 2016-04-02 - fixed multiple warnings; fix setup memory leaks; avoid discarding last frame of audio data 1.07 - 2015-01-16 - fixed some warnings, fix mingw, const-correct API some more crash fixes when out of memory or with corrupt files 1.06 - 2015-08-31 - full, correct support for seeking API (Dougall Johnson) some crash fixes when out of memory or with corrupt files 1.05 - 2015-04-19 - don't define __forceinline if it's redundant 1.04 - 2014-08-27 - fix missing const-correct case in API 1.03 - 2014-08-07 - Warning fixes 1.02 - 2014-07-09 - Declare qsort compare function _cdecl on windows 1.01 - 2014-06-18 - fix stb_vorbis_get_samples_float 1.0 - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in multichannel (API change) report sample rate for decode-full-file funcs 0.99996 - bracket #include <malloc.h> for macintosh compilation by Laurent Gomila 0.99995 - use union instead of pointer-cast for fast-float-to-int to avoid alias-optimization problem 0.99994 - change fast-float-to-int to work in single-precision FPU mode, remove endian-dependence 0.99993 - remove assert that fired on legal files with empty tables 0.99992 - rewind-to-start 0.99991 - bugfix to stb_vorbis_get_samples_short by Bernhard Wodo 0.9999 - (should have been 0.99990) fix no-CRT support, compiling as C++ 0.9998 - add a full-decode function with a memory source 0.9997 - fix a bug in the read-from-FILE case in 0.9996 addition 0.9996 - query length of vorbis stream in samples/seconds 0.9995 - bugfix to another optimization that only happened in certain files 0.9994 - bugfix to one of the optimizations that caused significant (but inaudible?) errors 0.9993 - performance improvements; runs in 99% to 104% of time of reference implementation 0.9992 - performance improvement of IMDCT; now performs close to reference implementation 0.9991 - performance improvement of IMDCT 0.999 - (should have been 0.9990) performance improvement of IMDCT 0.998 - no-CRT support from Casey Muratori 0.997 - bugfixes for bugs found by Terje Mathisen 0.996 - bugfix: fast-huffman decode initialized incorrectly for sparse codebooks; fixing gives 10% speedup - found by Terje Mathisen 0.995 - bugfix: fix to 'effective' overrun detection - found by Terje Mathisen 0.994 - bugfix: garbage decode on final VQ symbol of a non-multiple - found by Terje Mathisen 0.993 - bugfix: pushdata API required 1 extra byte for empty page (failed to consume final page if empty) - found by Terje Mathisen 0.992 - fixes for MinGW warning 0.991 - turn fast-float-conversion on by default 0.990 - fix push-mode seek recovery if you seek into the headers 0.98b - fix to bad release of 0.98 0.98 - fix push-mode seek recovery; robustify float-to-int and support non-fast mode 0.97 - builds under c++ (typecasting, don't use 'class' keyword) 0.96 - somehow MY 0.95 was right, but the web one was wrong, so here's my 0.95 rereleased as 0.96, fixes a typo in the clamping code 0.95 - clamping code for 16-bit functions 0.94 - not publically released 0.93 - fixed all-zero-floor case (was decoding garbage) 0.92 - fixed a memory leak 0.91 - conditional compiles to omit parts of the API and the infrastructure to support them: STB_VORBIS_NO_PULLDATA_API, STB_VORBIS_NO_PUSHDATA_API, STB_VORBIS_NO_STDIO, STB_VORBIS_NO_INTEGER_CONVERSION 0.90 - first public release */ #endif // STB_VORBIS_HEADER_ONLY /* ------------------------------------------------------------------------------ This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------ ALTERNATIVE A - MIT License Copyright (c) 2017 Sean Barrett Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ ALTERNATIVE B - Public Domain (www.unlicense.org) This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ */
null
// Ogg Vorbis audio decoder - v1.16 - public domain // http://nothings.org/stb_vorbis/ // // Original version written by Sean Barrett in 2007. // // Originally sponsored by RAD Game Tools. Seeking implementation // sponsored by Phillip Bennefall, Marc Andersen, Aaron Baker, // Elias Software, Aras Pranckevicius, and Sean Barrett. // // LICENSE // // See end of file for license information. // // Limitations: // // - floor 0 not supported (used in old ogg vorbis files pre-2004) // - lossless sample-truncation at beginning ignored // - cannot concatenate multiple vorbis streams // - sample positions are 32-bit, limiting seekable 192Khz // files to around 6 hours (Ogg supports 64-bit) // // Feature contributors: // Dougall Johnson (sample-exact seeking) // // Bugfix/warning contributors: // Terje Mathisen Niklas Frykholm Andy Hill // Casey Muratori John Bolton Gargaj // Laurent Gomila Marc LeBlanc Ronny Chevalier // Bernhard Wodo Evan Balster alxprd@github // Tom Beaumont Ingo Leitgeb Nicolas Guillemot // Phillip Bennefall Rohit Thiago Goulart // manxorist@github saga musix github:infatum // Timur Gagiev // // Partial history: // 1.17 - 2019-07-08 - fix CVE-2019-13217..CVE-2019-13223 (by ForAllSecure) // 1.16 - 2019-03-04 - fix warnings // 1.15 - 2019-02-07 - explicit failure if Ogg Skeleton data is found // 1.14 - 2018-02-11 - delete bogus dealloca usage // 1.13 - 2018-01-29 - fix truncation of last frame (hopefully) // 1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files // 1.11 - 2017-07-23 - fix MinGW compilation // 1.10 - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory // 1.09 - 2016-04-04 - back out 'truncation of last frame' fix from previous version // 1.08 - 2016-04-02 - warnings; setup memory leaks; truncation of last frame // 1.07 - 2015-01-16 - fixes for crashes on invalid files; warning fixes; const // 1.06 - 2015-08-31 - full, correct support for seeking API (Dougall Johnson) // some crash fixes when out of memory or with corrupt files // fix some inappropriately signed shifts // 1.05 - 2015-04-19 - don't define __forceinline if it's redundant // 1.04 - 2014-08-27 - fix missing const-correct case in API // 1.03 - 2014-08-07 - warning fixes // 1.02 - 2014-07-09 - declare qsort comparison as explicitly _cdecl in Windows // 1.01 - 2014-06-18 - fix stb_vorbis_get_samples_float (interleaved was correct) // 1.0 - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in >2-channel; // (API change) report sample rate for decode-full-file funcs // // See end of file for full version history. ////////////////////////////////////////////////////////////////////////////// // // HEADER BEGINS HERE // #ifndef STB_VORBIS_INCLUDE_STB_VORBIS_H #define STB_VORBIS_INCLUDE_STB_VORBIS_H #if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO) #define STB_VORBIS_NO_STDIO 1 #endif #ifndef STB_VORBIS_NO_STDIO #include <stdio.h> #endif #ifdef __cplusplus extern "C" { #endif /////////// THREAD SAFETY // Individual stb_vorbis* handles are not thread-safe; you cannot decode from // them from multiple threads at the same time. However, you can have multiple // stb_vorbis* handles and decode from them independently in multiple thrads. /////////// MEMORY ALLOCATION // normally stb_vorbis uses malloc() to allocate memory at startup, // and alloca() to allocate temporary memory during a frame on the // stack. (Memory consumption will depend on the amount of setup // data in the file and how you set the compile flags for speed // vs. size. In my test files the maximal-size usage is ~150KB.) // // You can modify the wrapper functions in the source (setup_malloc, // setup_temp_malloc, temp_malloc) to change this behavior, or you // can use a simpler allocation model: you pass in a buffer from // which stb_vorbis will allocate _all_ its memory (including the // temp memory). "open" may fail with a VORBIS_outofmem if you // do not pass in enough data; there is no way to determine how // much you do need except to succeed (at which point you can // query get_info to find the exact amount required. yes I know // this is lame). // // If you pass in a non-NULL buffer of the type below, allocation // will occur from it as described above. Otherwise just pass NULL // to use malloc()/alloca() typedef struct { char *alloc_buffer; int alloc_buffer_length_in_bytes; } stb_vorbis_alloc; /////////// FUNCTIONS USEABLE WITH ALL INPUT MODES typedef struct stb_vorbis stb_vorbis; typedef struct { unsigned int sample_rate; int channels; unsigned int setup_memory_required; unsigned int setup_temp_memory_required; unsigned int temp_memory_required; int max_frame_size; } stb_vorbis_info; // get general information about the file extern stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f); // get the last error detected (clears it, too) extern int stb_vorbis_get_error(stb_vorbis *f); // close an ogg vorbis file and free all memory in use extern void stb_vorbis_close(stb_vorbis *f); // this function returns the offset (in samples) from the beginning of the // file that will be returned by the next decode, if it is known, or -1 // otherwise. after a flush_pushdata() call, this may take a while before // it becomes valid again. // NOT WORKING YET after a seek with PULLDATA API extern int stb_vorbis_get_sample_offset(stb_vorbis *f); // returns the current seek point within the file, or offset from the beginning // of the memory buffer. In pushdata mode it returns 0. extern unsigned int stb_vorbis_get_file_offset(stb_vorbis *f); /////////// PUSHDATA API #ifndef STB_VORBIS_NO_PUSHDATA_API // this API allows you to get blocks of data from any source and hand // them to stb_vorbis. you have to buffer them; stb_vorbis will tell // you how much it used, and you have to give it the rest next time; // and stb_vorbis may not have enough data to work with and you will // need to give it the same data again PLUS more. Note that the Vorbis // specification does not bound the size of an individual frame. extern stb_vorbis *stb_vorbis_open_pushdata( const unsigned char * datablock, int datablock_length_in_bytes, int *datablock_memory_consumed_in_bytes, int *error, const stb_vorbis_alloc *alloc_buffer); // create a vorbis decoder by passing in the initial data block containing // the ogg&vorbis headers (you don't need to do parse them, just provide // the first N bytes of the file--you're told if it's not enough, see below) // on success, returns an stb_vorbis *, does not set error, returns the amount of // data parsed/consumed on this call in *datablock_memory_consumed_in_bytes; // on failure, returns NULL on error and sets *error, does not change *datablock_memory_consumed // if returns NULL and *error is VORBIS_need_more_data, then the input block was // incomplete and you need to pass in a larger block from the start of the file extern int stb_vorbis_decode_frame_pushdata( stb_vorbis *f, const unsigned char *datablock, int datablock_length_in_bytes, int *channels, // place to write number of float * buffers float ***output, // place to write float ** array of float * buffers int *samples // place to write number of output samples ); // decode a frame of audio sample data if possible from the passed-in data block // // return value: number of bytes we used from datablock // // possible cases: // 0 bytes used, 0 samples output (need more data) // N bytes used, 0 samples output (resynching the stream, keep going) // N bytes used, M samples output (one frame of data) // note that after opening a file, you will ALWAYS get one N-bytes,0-sample // frame, because Vorbis always "discards" the first frame. // // Note that on resynch, stb_vorbis will rarely consume all of the buffer, // instead only datablock_length_in_bytes-3 or less. This is because it wants // to avoid missing parts of a page header if they cross a datablock boundary, // without writing state-machiney code to record a partial detection. // // The number of channels returned are stored in *channels (which can be // NULL--it is always the same as the number of channels reported by // get_info). *output will contain an array of float* buffers, one per // channel. In other words, (*output)[0][0] contains the first sample from // the first channel, and (*output)[1][0] contains the first sample from // the second channel. extern void stb_vorbis_flush_pushdata(stb_vorbis *f); // inform stb_vorbis that your next datablock will not be contiguous with // previous ones (e.g. you've seeked in the data); future attempts to decode // frames will cause stb_vorbis to resynchronize (as noted above), and // once it sees a valid Ogg page (typically 4-8KB, as large as 64KB), it // will begin decoding the _next_ frame. // // if you want to seek using pushdata, you need to seek in your file, then // call stb_vorbis_flush_pushdata(), then start calling decoding, then once // decoding is returning you data, call stb_vorbis_get_sample_offset, and // if you don't like the result, seek your file again and repeat. #endif ////////// PULLING INPUT API #ifndef STB_VORBIS_NO_PULLDATA_API // This API assumes stb_vorbis is allowed to pull data from a source-- // either a block of memory containing the _entire_ vorbis stream, or a // FILE * that you or it create, or possibly some other reading mechanism // if you go modify the source to replace the FILE * case with some kind // of callback to your code. (But if you don't support seeking, you may // just want to go ahead and use pushdata.) #if !defined(STB_VORBIS_NO_STDIO) && !defined(STB_VORBIS_NO_INTEGER_CONVERSION) extern int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output); #endif #if !defined(STB_VORBIS_NO_INTEGER_CONVERSION) extern int stb_vorbis_decode_memory(const unsigned char *mem, int len, int *channels, int *sample_rate, short **output); #endif // decode an entire file and output the data interleaved into a malloc()ed // buffer stored in *output. The return value is the number of samples // decoded, or -1 if the file could not be opened or was not an ogg vorbis file. // When you're done with it, just free() the pointer returned in *output. extern stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, int *error, const stb_vorbis_alloc *alloc_buffer); // create an ogg vorbis decoder from an ogg vorbis stream in memory (note // this must be the entire stream!). on failure, returns NULL and sets *error #ifndef STB_VORBIS_NO_STDIO extern stb_vorbis * stb_vorbis_open_filename(const char *filename, int *error, const stb_vorbis_alloc *alloc_buffer); // create an ogg vorbis decoder from a filename via fopen(). on failure, // returns NULL and sets *error (possibly to VORBIS_file_open_failure). extern stb_vorbis * stb_vorbis_open_file(FILE *f, int close_handle_on_close, int *error, const stb_vorbis_alloc *alloc_buffer); // create an ogg vorbis decoder from an open FILE *, looking for a stream at // the _current_ seek point (ftell). on failure, returns NULL and sets *error. // note that stb_vorbis must "own" this stream; if you seek it in between // calls to stb_vorbis, it will become confused. Moreover, if you attempt to // perform stb_vorbis_seek_*() operations on this file, it will assume it // owns the _entire_ rest of the file after the start point. Use the next // function, stb_vorbis_open_file_section(), to limit it. extern stb_vorbis * stb_vorbis_open_file_section(FILE *f, int close_handle_on_close, int *error, const stb_vorbis_alloc *alloc_buffer, unsigned int len); // create an ogg vorbis decoder from an open FILE *, looking for a stream at // the _current_ seek point (ftell); the stream will be of length 'len' bytes. // on failure, returns NULL and sets *error. note that stb_vorbis must "own" // this stream; if you seek it in between calls to stb_vorbis, it will become // confused. #endif extern int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number); extern int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number); // these functions seek in the Vorbis file to (approximately) 'sample_number'. // after calling seek_frame(), the next call to get_frame_*() will include // the specified sample. after calling stb_vorbis_seek(), the next call to // stb_vorbis_get_samples_* will start with the specified sample. If you // do not need to seek to EXACTLY the target sample when using get_samples_*, // you can also use seek_frame(). extern int stb_vorbis_seek_start(stb_vorbis *f); // this function is equivalent to stb_vorbis_seek(f,0) extern unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f); extern float stb_vorbis_stream_length_in_seconds(stb_vorbis *f); // these functions return the total length of the vorbis stream extern int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output); // decode the next frame and return the number of samples. the number of // channels returned are stored in *channels (which can be NULL--it is always // the same as the number of channels reported by get_info). *output will // contain an array of float* buffers, one per channel. These outputs will // be overwritten on the next call to stb_vorbis_get_frame_*. // // You generally should not intermix calls to stb_vorbis_get_frame_*() // and stb_vorbis_get_samples_*(), since the latter calls the former. #ifndef STB_VORBIS_NO_INTEGER_CONVERSION extern int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts); extern int stb_vorbis_get_frame_short (stb_vorbis *f, int num_c, short **buffer, int num_samples); #endif // decode the next frame and return the number of *samples* per channel. // Note that for interleaved data, you pass in the number of shorts (the // size of your array), but the return value is the number of samples per // channel, not the total number of samples. // // The data is coerced to the number of channels you request according to the // channel coercion rules (see below). You must pass in the size of your // buffer(s) so that stb_vorbis will not overwrite the end of the buffer. // The maximum buffer size needed can be gotten from get_info(); however, // the Vorbis I specification implies an absolute maximum of 4096 samples // per channel. // Channel coercion rules: // Let M be the number of channels requested, and N the number of channels present, // and Cn be the nth channel; let stereo L be the sum of all L and center channels, // and stereo R be the sum of all R and center channels (channel assignment from the // vorbis spec). // M N output // 1 k sum(Ck) for all k // 2 * stereo L, stereo R // k l k > l, the first l channels, then 0s // k l k <= l, the first k channels // Note that this is not _good_ surround etc. mixing at all! It's just so // you get something useful. extern int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats); extern int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples); // gets num_samples samples, not necessarily on a frame boundary--this requires // buffering so you have to supply the buffers. DOES NOT APPLY THE COERCION RULES. // Returns the number of samples stored per channel; it may be less than requested // at the end of the file. If there are no more samples in the file, returns 0. #ifndef STB_VORBIS_NO_INTEGER_CONVERSION extern int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts); extern int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int num_samples); #endif // gets num_samples samples, not necessarily on a frame boundary--this requires // buffering so you have to supply the buffers. Applies the coercion rules above // to produce 'channels' channels. Returns the number of samples stored per channel; // it may be less than requested at the end of the file. If there are no more // samples in the file, returns 0. #endif //////// ERROR CODES enum STBVorbisError { VORBIS__no_error, VORBIS_need_more_data=1, // not a real error VORBIS_invalid_api_mixing, // can't mix API modes VORBIS_outofmem, // not enough memory VORBIS_feature_not_supported, // uses floor 0 VORBIS_too_many_channels, // STB_VORBIS_MAX_CHANNELS is too small VORBIS_file_open_failure, // fopen() failed VORBIS_seek_without_length, // can't seek in unknown-length file VORBIS_unexpected_eof=10, // file is truncated? VORBIS_seek_invalid, // seek past EOF // decoding errors (corrupt/invalid stream) -- you probably // don't care about the exact details of these // vorbis errors: VORBIS_invalid_setup=20, VORBIS_invalid_stream, // ogg errors: VORBIS_missing_capture_pattern=30, VORBIS_invalid_stream_structure_version, VORBIS_continued_packet_flag_invalid, VORBIS_incorrect_stream_serial_number, VORBIS_invalid_first_page, VORBIS_bad_packet_type, VORBIS_cant_find_last_page, VORBIS_seek_failed, VORBIS_ogg_skeleton_not_supported }; #ifdef __cplusplus } #endif #endif // STB_VORBIS_INCLUDE_STB_VORBIS_H // // HEADER ENDS HERE // ////////////////////////////////////////////////////////////////////////////// #ifndef STB_VORBIS_HEADER_ONLY // global configuration settings (e.g. set these in the project/makefile), // or just set them in this file at the top (although ideally the first few // should be visible when the header file is compiled too, although it's not // crucial) // STB_VORBIS_NO_PUSHDATA_API // does not compile the code for the various stb_vorbis_*_pushdata() // functions // #define STB_VORBIS_NO_PUSHDATA_API // STB_VORBIS_NO_PULLDATA_API // does not compile the code for the non-pushdata APIs // #define STB_VORBIS_NO_PULLDATA_API // STB_VORBIS_NO_STDIO // does not compile the code for the APIs that use FILE *s internally // or externally (implied by STB_VORBIS_NO_PULLDATA_API) // #define STB_VORBIS_NO_STDIO // STB_VORBIS_NO_INTEGER_CONVERSION // does not compile the code for converting audio sample data from // float to integer (implied by STB_VORBIS_NO_PULLDATA_API) // #define STB_VORBIS_NO_INTEGER_CONVERSION // STB_VORBIS_NO_FAST_SCALED_FLOAT // does not use a fast float-to-int trick to accelerate float-to-int on // most platforms which requires endianness be defined correctly. //#define STB_VORBIS_NO_FAST_SCALED_FLOAT // STB_VORBIS_MAX_CHANNELS [number] // globally define this to the maximum number of channels you need. // The spec does not put a restriction on channels except that // the count is stored in a byte, so 255 is the hard limit. // Reducing this saves about 16 bytes per value, so using 16 saves // (255-16)*16 or around 4KB. Plus anything other memory usage // I forgot to account for. Can probably go as low as 8 (7.1 audio), // 6 (5.1 audio), or 2 (stereo only). #ifndef STB_VORBIS_MAX_CHANNELS #define STB_VORBIS_MAX_CHANNELS 16 // enough for anyone? #endif // STB_VORBIS_PUSHDATA_CRC_COUNT [number] // after a flush_pushdata(), stb_vorbis begins scanning for the // next valid page, without backtracking. when it finds something // that looks like a page, it streams through it and verifies its // CRC32. Should that validation fail, it keeps scanning. But it's // possible that _while_ streaming through to check the CRC32 of // one candidate page, it sees another candidate page. This #define // determines how many "overlapping" candidate pages it can search // at once. Note that "real" pages are typically ~4KB to ~8KB, whereas // garbage pages could be as big as 64KB, but probably average ~16KB. // So don't hose ourselves by scanning an apparent 64KB page and // missing a ton of real ones in the interim; so minimum of 2 #ifndef STB_VORBIS_PUSHDATA_CRC_COUNT #define STB_VORBIS_PUSHDATA_CRC_COUNT 4 #endif // STB_VORBIS_FAST_HUFFMAN_LENGTH [number] // sets the log size of the huffman-acceleration table. Maximum // supported value is 24. with larger numbers, more decodings are O(1), // but the table size is larger so worse cache missing, so you'll have // to probe (and try multiple ogg vorbis files) to find the sweet spot. #ifndef STB_VORBIS_FAST_HUFFMAN_LENGTH #define STB_VORBIS_FAST_HUFFMAN_LENGTH 10 #endif // STB_VORBIS_FAST_BINARY_LENGTH [number] // sets the log size of the binary-search acceleration table. this // is used in similar fashion to the fast-huffman size to set initial // parameters for the binary search // STB_VORBIS_FAST_HUFFMAN_INT // The fast huffman tables are much more efficient if they can be // stored as 16-bit results instead of 32-bit results. This restricts // the codebooks to having only 65535 possible outcomes, though. // (At least, accelerated by the huffman table.) #ifndef STB_VORBIS_FAST_HUFFMAN_INT #define STB_VORBIS_FAST_HUFFMAN_SHORT #endif // STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH // If the 'fast huffman' search doesn't succeed, then stb_vorbis falls // back on binary searching for the correct one. This requires storing // extra tables with the huffman codes in sorted order. Defining this // symbol trades off space for speed by forcing a linear search in the // non-fast case, except for "sparse" codebooks. // #define STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH // STB_VORBIS_DIVIDES_IN_RESIDUE // stb_vorbis precomputes the result of the scalar residue decoding // that would otherwise require a divide per chunk. you can trade off // space for time by defining this symbol. // #define STB_VORBIS_DIVIDES_IN_RESIDUE // STB_VORBIS_DIVIDES_IN_CODEBOOK // vorbis VQ codebooks can be encoded two ways: with every case explicitly // stored, or with all elements being chosen from a small range of values, // and all values possible in all elements. By default, stb_vorbis expands // this latter kind out to look like the former kind for ease of decoding, // because otherwise an integer divide-per-vector-element is required to // unpack the index. If you define STB_VORBIS_DIVIDES_IN_CODEBOOK, you can // trade off storage for speed. //#define STB_VORBIS_DIVIDES_IN_CODEBOOK #ifdef STB_VORBIS_CODEBOOK_SHORTS #error "STB_VORBIS_CODEBOOK_SHORTS is no longer supported as it produced incorrect results for some input formats" #endif // STB_VORBIS_DIVIDE_TABLE // this replaces small integer divides in the floor decode loop with // table lookups. made less than 1% difference, so disabled by default. // STB_VORBIS_NO_INLINE_DECODE // disables the inlining of the scalar codebook fast-huffman decode. // might save a little codespace; useful for debugging // #define STB_VORBIS_NO_INLINE_DECODE // STB_VORBIS_NO_DEFER_FLOOR // Normally we only decode the floor without synthesizing the actual // full curve. We can instead synthesize the curve immediately. This // requires more memory and is very likely slower, so I don't think // you'd ever want to do it except for debugging. // #define STB_VORBIS_NO_DEFER_FLOOR ////////////////////////////////////////////////////////////////////////////// #ifdef STB_VORBIS_NO_PULLDATA_API #define STB_VORBIS_NO_INTEGER_CONVERSION #define STB_VORBIS_NO_STDIO #endif #if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO) #define STB_VORBIS_NO_STDIO 1 #endif #ifndef STB_VORBIS_NO_INTEGER_CONVERSION #ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT // only need endianness for fast-float-to-int, which we don't // use for pushdata #ifndef STB_VORBIS_BIG_ENDIAN #define STB_VORBIS_ENDIAN 0 #else #define STB_VORBIS_ENDIAN 1 #endif #endif #endif #ifndef STB_VORBIS_NO_STDIO #include <stdio.h> #endif #ifndef STB_VORBIS_NO_CRT #include <stdlib.h> #include <string.h> #include <assert.h> #include <math.h> // find definition of alloca if it's not in stdlib.h: #if defined(_MSC_VER) || defined(__MINGW32__) #include <malloc.h> #endif #if defined(__linux__) || defined(__linux) || defined(__EMSCRIPTEN__) #include <alloca.h> #endif #else // STB_VORBIS_NO_CRT #define NULL 0 #define malloc(s) 0 #define free(s) ((void) 0) #define realloc(s) 0 #endif // STB_VORBIS_NO_CRT #include <limits.h> #ifdef __MINGW32__ // eff you mingw: // "fixed": // http://sourceforge.net/p/mingw-w64/mailman/message/32882927/ // "no that broke the build, reverted, who cares about C": // http://sourceforge.net/p/mingw-w64/mailman/message/32890381/ #ifdef __forceinline #undef __forceinline #endif #define __forceinline #define alloca __builtin_alloca #elif !defined(_MSC_VER) #if __GNUC__ #define __forceinline inline #else #define __forceinline #endif #endif #if STB_VORBIS_MAX_CHANNELS > 256 #error "Value of STB_VORBIS_MAX_CHANNELS outside of allowed range" #endif #if STB_VORBIS_FAST_HUFFMAN_LENGTH > 24 #error "Value of STB_VORBIS_FAST_HUFFMAN_LENGTH outside of allowed range" #endif #if 0 #include <crtdbg.h> #define CHECK(f) _CrtIsValidHeapPointer(f->channel_buffers[1]) #else #define CHECK(f) ((void) 0) #endif #define MAX_BLOCKSIZE_LOG 13 // from specification #define MAX_BLOCKSIZE (1 << MAX_BLOCKSIZE_LOG) typedef unsigned char uint8; typedef signed char int8; typedef unsigned short uint16; typedef signed short int16; typedef unsigned int uint32; typedef signed int int32; #ifndef TRUE #define TRUE 1 #define FALSE 0 #endif typedef float codetype; // @NOTE // // Some arrays below are tagged "//varies", which means it's actually // a variable-sized piece of data, but rather than malloc I assume it's // small enough it's better to just allocate it all together with the // main thing // // Most of the variables are specified with the smallest size I could pack // them into. It might give better performance to make them all full-sized // integers. It should be safe to freely rearrange the structures or change // the sizes larger--nothing relies on silently truncating etc., nor the // order of variables. #define FAST_HUFFMAN_TABLE_SIZE (1 << STB_VORBIS_FAST_HUFFMAN_LENGTH) #define FAST_HUFFMAN_TABLE_MASK (FAST_HUFFMAN_TABLE_SIZE - 1) typedef struct { int dimensions, entries; uint8 *codeword_lengths; float minimum_value; float delta_value; uint8 value_bits; uint8 lookup_type; uint8 sequence_p; uint8 sparse; uint32 lookup_values; codetype *multiplicands; uint32 *codewords; #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT int16 fast_huffman[FAST_HUFFMAN_TABLE_SIZE]; #else int32 fast_huffman[FAST_HUFFMAN_TABLE_SIZE]; #endif uint32 *sorted_codewords; int *sorted_values; int sorted_entries; } Codebook; typedef struct { uint8 order; uint16 rate; uint16 bark_map_size; uint8 amplitude_bits; uint8 amplitude_offset; uint8 number_of_books; uint8 book_list[16]; // varies } Floor0; typedef struct { uint8 partitions; uint8 partition_class_list[32]; // varies uint8 class_dimensions[16]; // varies uint8 class_subclasses[16]; // varies uint8 class_masterbooks[16]; // varies int16 subclass_books[16][8]; // varies uint16 Xlist[31*8+2]; // varies uint8 sorted_order[31*8+2]; uint8 neighbors[31*8+2][2]; uint8 floor1_multiplier; uint8 rangebits; int values; } Floor1; typedef union { Floor0 floor0; Floor1 floor1; } Floor; typedef struct { uint32 begin, end; uint32 part_size; uint8 classifications; uint8 classbook; uint8 **classdata; int16 (*residue_books)[8]; } Residue; typedef struct { uint8 magnitude; uint8 angle; uint8 mux; } MappingChannel; typedef struct { uint16 coupling_steps; MappingChannel *chan; uint8 submaps; uint8 submap_floor[15]; // varies uint8 submap_residue[15]; // varies } Mapping; typedef struct { uint8 blockflag; uint8 mapping; uint16 windowtype; uint16 transformtype; } Mode; typedef struct { uint32 goal_crc; // expected crc if match int bytes_left; // bytes left in packet uint32 crc_so_far; // running crc int bytes_done; // bytes processed in _current_ chunk uint32 sample_loc; // granule pos encoded in page } CRCscan; typedef struct { uint32 page_start, page_end; uint32 last_decoded_sample; } ProbedPage; struct stb_vorbis { // user-accessible info unsigned int sample_rate; int channels; unsigned int setup_memory_required; unsigned int temp_memory_required; unsigned int setup_temp_memory_required; // input config #ifndef STB_VORBIS_NO_STDIO FILE *f; uint32 f_start; int close_on_free; #endif uint8 *stream; uint8 *stream_start; uint8 *stream_end; uint32 stream_len; uint8 push_mode; uint32 first_audio_page_offset; ProbedPage p_first, p_last; // memory management stb_vorbis_alloc alloc; int setup_offset; int temp_offset; // run-time results int eof; enum STBVorbisError error; // user-useful data // header info int blocksize[2]; int blocksize_0, blocksize_1; int codebook_count; Codebook *codebooks; int floor_count; uint16 floor_types[64]; // varies Floor *floor_config; int residue_count; uint16 residue_types[64]; // varies Residue *residue_config; int mapping_count; Mapping *mapping; int mode_count; Mode mode_config[64]; // varies uint32 total_samples; // decode buffer float *channel_buffers[STB_VORBIS_MAX_CHANNELS]; float *outputs [STB_VORBIS_MAX_CHANNELS]; float *previous_window[STB_VORBIS_MAX_CHANNELS]; int previous_length; #ifndef STB_VORBIS_NO_DEFER_FLOOR int16 *finalY[STB_VORBIS_MAX_CHANNELS]; #else float *floor_buffers[STB_VORBIS_MAX_CHANNELS]; #endif uint32 current_loc; // sample location of next frame to decode int current_loc_valid; // per-blocksize precomputed data // twiddle factors float *A[2],*B[2],*C[2]; float *window[2]; uint16 *bit_reverse[2]; // current page/packet/segment streaming info uint32 serial; // stream serial number for verification int last_page; int segment_count; uint8 segments[255]; uint8 page_flag; uint8 bytes_in_seg; uint8 first_decode; int next_seg; int last_seg; // flag that we're on the last segment int last_seg_which; // what was the segment number of the last seg? uint32 acc; int valid_bits; int packet_bytes; int end_seg_with_known_loc; uint32 known_loc_for_packet; int discard_samples_deferred; uint32 samples_output; // push mode scanning int page_crc_tests; // only in push_mode: number of tests active; -1 if not searching #ifndef STB_VORBIS_NO_PUSHDATA_API CRCscan scan[STB_VORBIS_PUSHDATA_CRC_COUNT]; #endif // sample-access int channel_buffer_start; int channel_buffer_end; }; #if defined(STB_VORBIS_NO_PUSHDATA_API) #define IS_PUSH_MODE(f) FALSE #elif defined(STB_VORBIS_NO_PULLDATA_API) #define IS_PUSH_MODE(f) TRUE #else #define IS_PUSH_MODE(f) ((f)->push_mode) #endif typedef struct stb_vorbis vorb; static int error(vorb *f, enum STBVorbisError e) { f->error = e; if (!f->eof && e != VORBIS_need_more_data) { f->error=e; // breakpoint for debugging } return 0; } // these functions are used for allocating temporary memory // while decoding. if you can afford the stack space, use // alloca(); otherwise, provide a temp buffer and it will // allocate out of those. #define array_size_required(count,size) (count*(sizeof(void *)+(size))) #define temp_alloc(f,size) (f->alloc.alloc_buffer ? setup_temp_malloc(f,size) : alloca(size)) #define temp_free(f,p) 0 #define temp_alloc_save(f) ((f)->temp_offset) #define temp_alloc_restore(f,p) ((f)->temp_offset = (p)) #define temp_block_array(f,count,size) make_block_array(temp_alloc(f,array_size_required(count,size)), count, size) // given a sufficiently large block of memory, make an array of pointers to subblocks of it static void *make_block_array(void *mem, int count, int size) { int i; void ** p = (void **) mem; char *q = (char *) (p + count); for (i=0; i < count; ++i) { p[i] = q; q += size; } return p; } static void *setup_malloc(vorb *f, int sz) { sz = (sz+3) & ~3; f->setup_memory_required += sz; if (f->alloc.alloc_buffer) { void *p = (char *) f->alloc.alloc_buffer + f->setup_offset; if (f->setup_offset + sz > f->temp_offset) return NULL; f->setup_offset += sz; return p; } return sz ? malloc(sz) : NULL; } static void setup_free(vorb *f, void *p) { if (f->alloc.alloc_buffer) return; // do nothing; setup mem is a stack free(p); } static void *setup_temp_malloc(vorb *f, int sz) { sz = (sz+3) & ~3; if (f->alloc.alloc_buffer) { if (f->temp_offset - sz < f->setup_offset) return NULL; f->temp_offset -= sz; return (char *) f->alloc.alloc_buffer + f->temp_offset; } return malloc(sz); } static void setup_temp_free(vorb *f, void *p, int sz) { if (f->alloc.alloc_buffer) { f->temp_offset += (sz+3)&~3; return; } free(p); } #define CRC32_POLY 0x04c11db7 // from spec static uint32 crc_table[256]; static void crc32_init(void) { int i,j; uint32 s; for(i=0; i < 256; i++) { for (s=(uint32) i << 24, j=0; j < 8; ++j) s = (s << 1) ^ (s >= (1U<<31) ? CRC32_POLY : 0); crc_table[i] = s; } } static __forceinline uint32 crc32_update(uint32 crc, uint8 byte) { return (crc << 8) ^ crc_table[byte ^ (crc >> 24)]; } // used in setup, and for huffman that doesn't go fast path static unsigned int bit_reverse(unsigned int n) { n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1); n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2); n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4); n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8); return (n >> 16) | (n << 16); } static float square(float x) { return x*x; } // this is a weird definition of log2() for which log2(1) = 1, log2(2) = 2, log2(4) = 3 // as required by the specification. fast(?) implementation from stb.h // @OPTIMIZE: called multiple times per-packet with "constants"; move to setup static int ilog(int32 n) { static signed char log2_4[16] = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 }; if (n < 0) return 0; // signed n returns 0 // 2 compares if n < 16, 3 compares otherwise (4 if signed or n > 1<<29) if (n < (1 << 14)) if (n < (1 << 4)) return 0 + log2_4[n ]; else if (n < (1 << 9)) return 5 + log2_4[n >> 5]; else return 10 + log2_4[n >> 10]; else if (n < (1 << 24)) if (n < (1 << 19)) return 15 + log2_4[n >> 15]; else return 20 + log2_4[n >> 20]; else if (n < (1 << 29)) return 25 + log2_4[n >> 25]; else return 30 + log2_4[n >> 30]; } #ifndef M_PI #define M_PI 3.14159265358979323846264f // from CRC #endif // code length assigned to a value with no huffman encoding #define NO_CODE 255 /////////////////////// LEAF SETUP FUNCTIONS ////////////////////////// // // these functions are only called at setup, and only a few times // per file static float float32_unpack(uint32 x) { // from the specification uint32 mantissa = x & 0x1fffff; uint32 sign = x & 0x80000000; uint32 exp = (x & 0x7fe00000) >> 21; double res = sign ? -(double)mantissa : (double)mantissa; return (float) ldexp((float)res, exp-788); } // zlib & jpeg huffman tables assume that the output symbols // can either be arbitrarily arranged, or have monotonically // increasing frequencies--they rely on the lengths being sorted; // this makes for a very simple generation algorithm. // vorbis allows a huffman table with non-sorted lengths. This // requires a more sophisticated construction, since symbols in // order do not map to huffman codes "in order". static void add_entry(Codebook *c, uint32 huff_code, int symbol, int count, int len, uint32 *values) { if (!c->sparse) { c->codewords [symbol] = huff_code; } else { c->codewords [count] = huff_code; c->codeword_lengths[count] = len; values [count] = symbol; } } static int compute_codewords(Codebook *c, uint8 *len, int n, uint32 *values) { int i,k,m=0; uint32 available[32]; memset(available, 0, sizeof(available)); // find the first entry for (k=0; k < n; ++k) if (len[k] < NO_CODE) break; if (k == n) { assert(c->sorted_entries == 0); return TRUE; } // add to the list add_entry(c, 0, k, m++, len[k], values); // add all available leaves for (i=1; i <= len[k]; ++i) available[i] = 1U << (32-i); // note that the above code treats the first case specially, // but it's really the same as the following code, so they // could probably be combined (except the initial code is 0, // and I use 0 in available[] to mean 'empty') for (i=k+1; i < n; ++i) { uint32 res; int z = len[i], y; if (z == NO_CODE) continue; // find lowest available leaf (should always be earliest, // which is what the specification calls for) // note that this property, and the fact we can never have // more than one free leaf at a given level, isn't totally // trivial to prove, but it seems true and the assert never // fires, so! while (z > 0 && !available[z]) --z; if (z == 0) { return FALSE; } res = available[z]; assert(z >= 0 && z < 32); available[z] = 0; add_entry(c, bit_reverse(res), i, m++, len[i], values); // propagate availability up the tree if (z != len[i]) { assert(len[i] >= 0 && len[i] < 32); for (y=len[i]; y > z; --y) { assert(available[y] == 0); available[y] = res + (1 << (32-y)); } } } return TRUE; } // accelerated huffman table allows fast O(1) match of all symbols // of length <= STB_VORBIS_FAST_HUFFMAN_LENGTH static void compute_accelerated_huffman(Codebook *c) { int i, len; for (i=0; i < FAST_HUFFMAN_TABLE_SIZE; ++i) c->fast_huffman[i] = -1; len = c->sparse ? c->sorted_entries : c->entries; #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT if (len > 32767) len = 32767; // largest possible value we can encode! #endif for (i=0; i < len; ++i) { if (c->codeword_lengths[i] <= STB_VORBIS_FAST_HUFFMAN_LENGTH) { uint32 z = c->sparse ? bit_reverse(c->sorted_codewords[i]) : c->codewords[i]; // set table entries for all bit combinations in the higher bits while (z < FAST_HUFFMAN_TABLE_SIZE) { c->fast_huffman[z] = i; z += 1 << c->codeword_lengths[i]; } } } } #ifdef _MSC_VER #define STBV_CDECL __cdecl #else #define STBV_CDECL #endif static int STBV_CDECL uint32_compare(const void *p, const void *q) { uint32 x = * (uint32 *) p; uint32 y = * (uint32 *) q; return x < y ? -1 : x > y; } static int include_in_sort(Codebook *c, uint8 len) { if (c->sparse) { assert(len != NO_CODE); return TRUE; } if (len == NO_CODE) return FALSE; if (len > STB_VORBIS_FAST_HUFFMAN_LENGTH) return TRUE; return FALSE; } // if the fast table above doesn't work, we want to binary // search them... need to reverse the bits static void compute_sorted_huffman(Codebook *c, uint8 *lengths, uint32 *values) { int i, len; // build a list of all the entries // OPTIMIZATION: don't include the short ones, since they'll be caught by FAST_HUFFMAN. // this is kind of a frivolous optimization--I don't see any performance improvement, // but it's like 4 extra lines of code, so. if (!c->sparse) { int k = 0; for (i=0; i < c->entries; ++i) if (include_in_sort(c, lengths[i])) c->sorted_codewords[k++] = bit_reverse(c->codewords[i]); assert(k == c->sorted_entries); } else { for (i=0; i < c->sorted_entries; ++i) c->sorted_codewords[i] = bit_reverse(c->codewords[i]); } qsort(c->sorted_codewords, c->sorted_entries, sizeof(c->sorted_codewords[0]), uint32_compare); c->sorted_codewords[c->sorted_entries] = 0xffffffff; len = c->sparse ? c->sorted_entries : c->entries; // now we need to indicate how they correspond; we could either // #1: sort a different data structure that says who they correspond to // #2: for each sorted entry, search the original list to find who corresponds // #3: for each original entry, find the sorted entry // #1 requires extra storage, #2 is slow, #3 can use binary search! for (i=0; i < len; ++i) { int huff_len = c->sparse ? lengths[values[i]] : lengths[i]; if (include_in_sort(c,huff_len)) { uint32 code = bit_reverse(c->codewords[i]); int x=0, n=c->sorted_entries; while (n > 1) { // invariant: sc[x] <= code < sc[x+n] int m = x + (n >> 1); if (c->sorted_codewords[m] <= code) { x = m; n -= (n>>1); } else { n >>= 1; } } assert(c->sorted_codewords[x] == code); if (c->sparse) { c->sorted_values[x] = values[i]; c->codeword_lengths[x] = huff_len; } else { c->sorted_values[x] = i; } } } } // only run while parsing the header (3 times) static int vorbis_validate(uint8 *data) { static uint8 vorbis[6] = { 'v', 'o', 'r', 'b', 'i', 's' }; return memcmp(data, vorbis, 6) == 0; } // called from setup only, once per code book // (formula implied by specification) static int lookup1_values(int entries, int dim) { int r = (int) floor(exp((float) log((float) entries) / dim)); if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning; ++r; // floor() to avoid _ftol() when non-CRT if (pow((float) r+1, dim) <= entries) return -1; if ((int) floor(pow((float) r, dim)) > entries) return -1; return r; } // called twice per file static void compute_twiddle_factors(int n, float *A, float *B, float *C) { int n4 = n >> 2, n8 = n >> 3; int k,k2; for (k=k2=0; k < n4; ++k,k2+=2) { A[k2 ] = (float) cos(4*k*M_PI/n); A[k2+1] = (float) -sin(4*k*M_PI/n); B[k2 ] = (float) cos((k2+1)*M_PI/n/2) * 0.5f; B[k2+1] = (float) sin((k2+1)*M_PI/n/2) * 0.5f; } for (k=k2=0; k < n8; ++k,k2+=2) { C[k2 ] = (float) cos(2*(k2+1)*M_PI/n); C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n); } } static void compute_window(int n, float *window) { int n2 = n >> 1, i; for (i=0; i < n2; ++i) window[i] = (float) sin(0.5 * M_PI * square((float) sin((i - 0 + 0.5) / n2 * 0.5 * M_PI))); } static void compute_bitreverse(int n, uint16 *rev) { int ld = ilog(n) - 1; // ilog is off-by-one from normal definitions int i, n8 = n >> 3; for (i=0; i < n8; ++i) rev[i] = (bit_reverse(i) >> (32-ld+3)) << 2; } static int init_blocksize(vorb *f, int b, int n) { int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3; f->A[b] = (float *) setup_malloc(f, sizeof(float) * n2); f->B[b] = (float *) setup_malloc(f, sizeof(float) * n2); f->C[b] = (float *) setup_malloc(f, sizeof(float) * n4); if (!f->A[b] || !f->B[b] || !f->C[b]) return error(f, VORBIS_outofmem); compute_twiddle_factors(n, f->A[b], f->B[b], f->C[b]); f->window[b] = (float *) setup_malloc(f, sizeof(float) * n2); if (!f->window[b]) return error(f, VORBIS_outofmem); compute_window(n, f->window[b]); f->bit_reverse[b] = (uint16 *) setup_malloc(f, sizeof(uint16) * n8); if (!f->bit_reverse[b]) return error(f, VORBIS_outofmem); compute_bitreverse(n, f->bit_reverse[b]); return TRUE; } static void neighbors(uint16 *x, int n, int *plow, int *phigh) { int low = -1; int high = 65536; int i; for (i=0; i < n; ++i) { if (x[i] > low && x[i] < x[n]) { *plow = i; low = x[i]; } if (x[i] < high && x[i] > x[n]) { *phigh = i; high = x[i]; } } } // this has been repurposed so y is now the original index instead of y typedef struct { uint16 x,id; } stbv__floor_ordering; static int STBV_CDECL point_compare(const void *p, const void *q) { stbv__floor_ordering *a = (stbv__floor_ordering *) p; stbv__floor_ordering *b = (stbv__floor_ordering *) q; return a->x < b->x ? -1 : a->x > b->x; } // /////////////////////// END LEAF SETUP FUNCTIONS ////////////////////////// #if defined(STB_VORBIS_NO_STDIO) #define USE_MEMORY(z) TRUE #else #define USE_MEMORY(z) ((z)->stream) #endif static uint8 get8(vorb *z) { if (USE_MEMORY(z)) { if (z->stream >= z->stream_end) { z->eof = TRUE; return 0; } return *z->stream++; } #ifndef STB_VORBIS_NO_STDIO { int c = fgetc(z->f); if (c == EOF) { z->eof = TRUE; return 0; } return c; } #endif } static uint32 get32(vorb *f) { uint32 x; x = get8(f); x += get8(f) << 8; x += get8(f) << 16; x += (uint32) get8(f) << 24; return x; } static int getn(vorb *z, uint8 *data, int n) { if (USE_MEMORY(z)) { if (z->stream+n > z->stream_end) { z->eof = 1; return 0; } memcpy(data, z->stream, n); z->stream += n; return 1; } #ifndef STB_VORBIS_NO_STDIO if (fread(data, n, 1, z->f) == 1) return 1; else { z->eof = 1; return 0; } #endif } static void skip(vorb *z, int n) { if (USE_MEMORY(z)) { z->stream += n; if (z->stream >= z->stream_end) z->eof = 1; return; } #ifndef STB_VORBIS_NO_STDIO { long x = ftell(z->f); fseek(z->f, x+n, SEEK_SET); } #endif } static int set_file_offset(stb_vorbis *f, unsigned int loc) { #ifndef STB_VORBIS_NO_PUSHDATA_API if (f->push_mode) return 0; #endif f->eof = 0; if (USE_MEMORY(f)) { if (f->stream_start + loc >= f->stream_end || f->stream_start + loc < f->stream_start) { f->stream = f->stream_end; f->eof = 1; return 0; } else { f->stream = f->stream_start + loc; return 1; } } #ifndef STB_VORBIS_NO_STDIO if (loc + f->f_start < loc || loc >= 0x80000000) { loc = 0x7fffffff; f->eof = 1; } else { loc += f->f_start; } if (!fseek(f->f, loc, SEEK_SET)) return 1; f->eof = 1; fseek(f->f, f->f_start, SEEK_END); return 0; #endif } static uint8 ogg_page_header[4] = { 0x4f, 0x67, 0x67, 0x53 }; static int capture_pattern(vorb *f) { if (0x4f != get8(f)) return FALSE; if (0x67 != get8(f)) return FALSE; if (0x67 != get8(f)) return FALSE; if (0x53 != get8(f)) return FALSE; return TRUE; } #define PAGEFLAG_continued_packet 1 #define PAGEFLAG_first_page 2 #define PAGEFLAG_last_page 4 static int start_page_no_capturepattern(vorb *f) { uint32 loc0,loc1,n; // stream structure version if (0 != get8(f)) return error(f, VORBIS_invalid_stream_structure_version); // header flag f->page_flag = get8(f); // absolute granule position loc0 = get32(f); loc1 = get32(f); // @TODO: validate loc0,loc1 as valid positions? // stream serial number -- vorbis doesn't interleave, so discard get32(f); //if (f->serial != get32(f)) return error(f, VORBIS_incorrect_stream_serial_number); // page sequence number n = get32(f); f->last_page = n; // CRC32 get32(f); // page_segments f->segment_count = get8(f); if (!getn(f, f->segments, f->segment_count)) return error(f, VORBIS_unexpected_eof); // assume we _don't_ know any the sample position of any segments f->end_seg_with_known_loc = -2; if (loc0 != ~0U || loc1 != ~0U) { int i; // determine which packet is the last one that will complete for (i=f->segment_count-1; i >= 0; --i) if (f->segments[i] < 255) break; // 'i' is now the index of the _last_ segment of a packet that ends if (i >= 0) { f->end_seg_with_known_loc = i; f->known_loc_for_packet = loc0; } } if (f->first_decode) { int i,len; ProbedPage p; len = 0; for (i=0; i < f->segment_count; ++i) len += f->segments[i]; len += 27 + f->segment_count; p.page_start = f->first_audio_page_offset; p.page_end = p.page_start + len; p.last_decoded_sample = loc0; f->p_first = p; } f->next_seg = 0; return TRUE; } static int start_page(vorb *f) { if (!capture_pattern(f)) return error(f, VORBIS_missing_capture_pattern); return start_page_no_capturepattern(f); } static int start_packet(vorb *f) { while (f->next_seg == -1) { if (!start_page(f)) return FALSE; if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_continued_packet_flag_invalid); } f->last_seg = FALSE; f->valid_bits = 0; f->packet_bytes = 0; f->bytes_in_seg = 0; // f->next_seg is now valid return TRUE; } static int maybe_start_packet(vorb *f) { if (f->next_seg == -1) { int x = get8(f); if (f->eof) return FALSE; // EOF at page boundary is not an error! if (0x4f != x ) return error(f, VORBIS_missing_capture_pattern); if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern); if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern); if (0x53 != get8(f)) return error(f, VORBIS_missing_capture_pattern); if (!start_page_no_capturepattern(f)) return FALSE; if (f->page_flag & PAGEFLAG_continued_packet) { // set up enough state that we can read this packet if we want, // e.g. during recovery f->last_seg = FALSE; f->bytes_in_seg = 0; return error(f, VORBIS_continued_packet_flag_invalid); } } return start_packet(f); } static int next_segment(vorb *f) { int len; if (f->last_seg) return 0; if (f->next_seg == -1) { f->last_seg_which = f->segment_count-1; // in case start_page fails if (!start_page(f)) { f->last_seg = 1; return 0; } if (!(f->page_flag & PAGEFLAG_continued_packet)) return error(f, VORBIS_continued_packet_flag_invalid); } len = f->segments[f->next_seg++]; if (len < 255) { f->last_seg = TRUE; f->last_seg_which = f->next_seg-1; } if (f->next_seg >= f->segment_count) f->next_seg = -1; assert(f->bytes_in_seg == 0); f->bytes_in_seg = len; return len; } #define EOP (-1) #define INVALID_BITS (-1) static int get8_packet_raw(vorb *f) { if (!f->bytes_in_seg) { // CLANG! if (f->last_seg) return EOP; else if (!next_segment(f)) return EOP; } assert(f->bytes_in_seg > 0); --f->bytes_in_seg; ++f->packet_bytes; return get8(f); } static int get8_packet(vorb *f) { int x = get8_packet_raw(f); f->valid_bits = 0; return x; } static void flush_packet(vorb *f) { while (get8_packet_raw(f) != EOP); } // @OPTIMIZE: this is the secondary bit decoder, so it's probably not as important // as the huffman decoder? static uint32 get_bits(vorb *f, int n) { uint32 z; if (f->valid_bits < 0) return 0; if (f->valid_bits < n) { if (n > 24) { // the accumulator technique below would not work correctly in this case z = get_bits(f, 24); z += get_bits(f, n-24) << 24; return z; } if (f->valid_bits == 0) f->acc = 0; while (f->valid_bits < n) { int z = get8_packet_raw(f); if (z == EOP) { f->valid_bits = INVALID_BITS; return 0; } f->acc += z << f->valid_bits; f->valid_bits += 8; } } if (f->valid_bits < 0) return 0; z = f->acc & ((1 << n)-1); f->acc >>= n; f->valid_bits -= n; return z; } // @OPTIMIZE: primary accumulator for huffman // expand the buffer to as many bits as possible without reading off end of packet // it might be nice to allow f->valid_bits and f->acc to be stored in registers, // e.g. cache them locally and decode locally static __forceinline void prep_huffman(vorb *f) { if (f->valid_bits <= 24) { if (f->valid_bits == 0) f->acc = 0; do { int z; if (f->last_seg && !f->bytes_in_seg) return; z = get8_packet_raw(f); if (z == EOP) return; f->acc += (unsigned) z << f->valid_bits; f->valid_bits += 8; } while (f->valid_bits <= 24); } } enum { VORBIS_packet_id = 1, VORBIS_packet_comment = 3, VORBIS_packet_setup = 5 }; static int codebook_decode_scalar_raw(vorb *f, Codebook *c) { int i; prep_huffman(f); if (c->codewords == NULL && c->sorted_codewords == NULL) return -1; // cases to use binary search: sorted_codewords && !c->codewords // sorted_codewords && c->entries > 8 if (c->entries > 8 ? c->sorted_codewords!=NULL : !c->codewords) { // binary search uint32 code = bit_reverse(f->acc); int x=0, n=c->sorted_entries, len; while (n > 1) { // invariant: sc[x] <= code < sc[x+n] int m = x + (n >> 1); if (c->sorted_codewords[m] <= code) { x = m; n -= (n>>1); } else { n >>= 1; } } // x is now the sorted index if (!c->sparse) x = c->sorted_values[x]; // x is now sorted index if sparse, or symbol otherwise len = c->codeword_lengths[x]; if (f->valid_bits >= len) { f->acc >>= len; f->valid_bits -= len; return x; } f->valid_bits = 0; return -1; } // if small, linear search assert(!c->sparse); for (i=0; i < c->entries; ++i) { if (c->codeword_lengths[i] == NO_CODE) continue; if (c->codewords[i] == (f->acc & ((1 << c->codeword_lengths[i])-1))) { if (f->valid_bits >= c->codeword_lengths[i]) { f->acc >>= c->codeword_lengths[i]; f->valid_bits -= c->codeword_lengths[i]; return i; } f->valid_bits = 0; return -1; } } error(f, VORBIS_invalid_stream); f->valid_bits = 0; return -1; } #ifndef STB_VORBIS_NO_INLINE_DECODE #define DECODE_RAW(var, f,c) \ if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) \ prep_huffman(f); \ var = f->acc & FAST_HUFFMAN_TABLE_MASK; \ var = c->fast_huffman[var]; \ if (var >= 0) { \ int n = c->codeword_lengths[var]; \ f->acc >>= n; \ f->valid_bits -= n; \ if (f->valid_bits < 0) { f->valid_bits = 0; var = -1; } \ } else { \ var = codebook_decode_scalar_raw(f,c); \ } #else static int codebook_decode_scalar(vorb *f, Codebook *c) { int i; if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) prep_huffman(f); // fast huffman table lookup i = f->acc & FAST_HUFFMAN_TABLE_MASK; i = c->fast_huffman[i]; if (i >= 0) { f->acc >>= c->codeword_lengths[i]; f->valid_bits -= c->codeword_lengths[i]; if (f->valid_bits < 0) { f->valid_bits = 0; return -1; } return i; } return codebook_decode_scalar_raw(f,c); } #define DECODE_RAW(var,f,c) var = codebook_decode_scalar(f,c); #endif #define DECODE(var,f,c) \ DECODE_RAW(var,f,c) \ if (c->sparse) var = c->sorted_values[var]; #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK #define DECODE_VQ(var,f,c) DECODE_RAW(var,f,c) #else #define DECODE_VQ(var,f,c) DECODE(var,f,c) #endif // CODEBOOK_ELEMENT_FAST is an optimization for the CODEBOOK_FLOATS case // where we avoid one addition #define CODEBOOK_ELEMENT(c,off) (c->multiplicands[off]) #define CODEBOOK_ELEMENT_FAST(c,off) (c->multiplicands[off]) #define CODEBOOK_ELEMENT_BASE(c) (0) static int codebook_decode_start(vorb *f, Codebook *c) { int z = -1; // type 0 is only legal in a scalar context if (c->lookup_type == 0) error(f, VORBIS_invalid_stream); else { DECODE_VQ(z,f,c); if (c->sparse) assert(z < c->sorted_entries); if (z < 0) { // check for EOP if (!f->bytes_in_seg) if (f->last_seg) return z; error(f, VORBIS_invalid_stream); } } return z; } static int codebook_decode(vorb *f, Codebook *c, float *output, int len) { int i,z = codebook_decode_start(f,c); if (z < 0) return FALSE; if (len > c->dimensions) len = c->dimensions; #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { float last = CODEBOOK_ELEMENT_BASE(c); int div = 1; for (i=0; i < len; ++i) { int off = (z / div) % c->lookup_values; float val = CODEBOOK_ELEMENT_FAST(c,off) + last; output[i] += val; if (c->sequence_p) last = val + c->minimum_value; div *= c->lookup_values; } return TRUE; } #endif z *= c->dimensions; if (c->sequence_p) { float last = CODEBOOK_ELEMENT_BASE(c); for (i=0; i < len; ++i) { float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; output[i] += val; last = val + c->minimum_value; } } else { float last = CODEBOOK_ELEMENT_BASE(c); for (i=0; i < len; ++i) { output[i] += CODEBOOK_ELEMENT_FAST(c,z+i) + last; } } return TRUE; } static int codebook_decode_step(vorb *f, Codebook *c, float *output, int len, int step) { int i,z = codebook_decode_start(f,c); float last = CODEBOOK_ELEMENT_BASE(c); if (z < 0) return FALSE; if (len > c->dimensions) len = c->dimensions; #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { int div = 1; for (i=0; i < len; ++i) { int off = (z / div) % c->lookup_values; float val = CODEBOOK_ELEMENT_FAST(c,off) + last; output[i*step] += val; if (c->sequence_p) last = val; div *= c->lookup_values; } return TRUE; } #endif z *= c->dimensions; for (i=0; i < len; ++i) { float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; output[i*step] += val; if (c->sequence_p) last = val; } return TRUE; } static int codebook_decode_deinterleave_repeat(vorb *f, Codebook *c, float **outputs, int ch, int *c_inter_p, int *p_inter_p, int len, int total_decode) { int c_inter = *c_inter_p; int p_inter = *p_inter_p; int i,z, effective = c->dimensions; // type 0 is only legal in a scalar context if (c->lookup_type == 0) return error(f, VORBIS_invalid_stream); while (total_decode > 0) { float last = CODEBOOK_ELEMENT_BASE(c); DECODE_VQ(z,f,c); #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK assert(!c->sparse || z < c->sorted_entries); #endif if (z < 0) { if (!f->bytes_in_seg) if (f->last_seg) return FALSE; return error(f, VORBIS_invalid_stream); } // if this will take us off the end of the buffers, stop short! // we check by computing the length of the virtual interleaved // buffer (len*ch), our current offset within it (p_inter*ch)+(c_inter), // and the length we'll be using (effective) if (c_inter + p_inter*ch + effective > len * ch) { effective = len*ch - (p_inter*ch - c_inter); } #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { int div = 1; for (i=0; i < effective; ++i) { int off = (z / div) % c->lookup_values; float val = CODEBOOK_ELEMENT_FAST(c,off) + last; if (outputs[c_inter]) outputs[c_inter][p_inter] += val; if (++c_inter == ch) { c_inter = 0; ++p_inter; } if (c->sequence_p) last = val; div *= c->lookup_values; } } else #endif { z *= c->dimensions; if (c->sequence_p) { for (i=0; i < effective; ++i) { float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; if (outputs[c_inter]) outputs[c_inter][p_inter] += val; if (++c_inter == ch) { c_inter = 0; ++p_inter; } last = val; } } else { for (i=0; i < effective; ++i) { float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; if (outputs[c_inter]) outputs[c_inter][p_inter] += val; if (++c_inter == ch) { c_inter = 0; ++p_inter; } } } } total_decode -= effective; } *c_inter_p = c_inter; *p_inter_p = p_inter; return TRUE; } static int predict_point(int x, int x0, int x1, int y0, int y1) { int dy = y1 - y0; int adx = x1 - x0; // @OPTIMIZE: force int division to round in the right direction... is this necessary on x86? int err = abs(dy) * (x - x0); int off = err / adx; return dy < 0 ? y0 - off : y0 + off; } // the following table is block-copied from the specification static float inverse_db_table[256] = { 1.0649863e-07f, 1.1341951e-07f, 1.2079015e-07f, 1.2863978e-07f, 1.3699951e-07f, 1.4590251e-07f, 1.5538408e-07f, 1.6548181e-07f, 1.7623575e-07f, 1.8768855e-07f, 1.9988561e-07f, 2.1287530e-07f, 2.2670913e-07f, 2.4144197e-07f, 2.5713223e-07f, 2.7384213e-07f, 2.9163793e-07f, 3.1059021e-07f, 3.3077411e-07f, 3.5226968e-07f, 3.7516214e-07f, 3.9954229e-07f, 4.2550680e-07f, 4.5315863e-07f, 4.8260743e-07f, 5.1396998e-07f, 5.4737065e-07f, 5.8294187e-07f, 6.2082472e-07f, 6.6116941e-07f, 7.0413592e-07f, 7.4989464e-07f, 7.9862701e-07f, 8.5052630e-07f, 9.0579828e-07f, 9.6466216e-07f, 1.0273513e-06f, 1.0941144e-06f, 1.1652161e-06f, 1.2409384e-06f, 1.3215816e-06f, 1.4074654e-06f, 1.4989305e-06f, 1.5963394e-06f, 1.7000785e-06f, 1.8105592e-06f, 1.9282195e-06f, 2.0535261e-06f, 2.1869758e-06f, 2.3290978e-06f, 2.4804557e-06f, 2.6416497e-06f, 2.8133190e-06f, 2.9961443e-06f, 3.1908506e-06f, 3.3982101e-06f, 3.6190449e-06f, 3.8542308e-06f, 4.1047004e-06f, 4.3714470e-06f, 4.6555282e-06f, 4.9580707e-06f, 5.2802740e-06f, 5.6234160e-06f, 5.9888572e-06f, 6.3780469e-06f, 6.7925283e-06f, 7.2339451e-06f, 7.7040476e-06f, 8.2047000e-06f, 8.7378876e-06f, 9.3057248e-06f, 9.9104632e-06f, 1.0554501e-05f, 1.1240392e-05f, 1.1970856e-05f, 1.2748789e-05f, 1.3577278e-05f, 1.4459606e-05f, 1.5399272e-05f, 1.6400004e-05f, 1.7465768e-05f, 1.8600792e-05f, 1.9809576e-05f, 2.1096914e-05f, 2.2467911e-05f, 2.3928002e-05f, 2.5482978e-05f, 2.7139006e-05f, 2.8902651e-05f, 3.0780908e-05f, 3.2781225e-05f, 3.4911534e-05f, 3.7180282e-05f, 3.9596466e-05f, 4.2169667e-05f, 4.4910090e-05f, 4.7828601e-05f, 5.0936773e-05f, 5.4246931e-05f, 5.7772202e-05f, 6.1526565e-05f, 6.5524908e-05f, 6.9783085e-05f, 7.4317983e-05f, 7.9147585e-05f, 8.4291040e-05f, 8.9768747e-05f, 9.5602426e-05f, 0.00010181521f, 0.00010843174f, 0.00011547824f, 0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f, 0.00015820453f, 0.00016848555f, 0.00017943469f, 0.00019109536f, 0.00020351382f, 0.00021673929f, 0.00023082423f, 0.00024582449f, 0.00026179955f, 0.00027881276f, 0.00029693158f, 0.00031622787f, 0.00033677814f, 0.00035866388f, 0.00038197188f, 0.00040679456f, 0.00043323036f, 0.00046138411f, 0.00049136745f, 0.00052329927f, 0.00055730621f, 0.00059352311f, 0.00063209358f, 0.00067317058f, 0.00071691700f, 0.00076350630f, 0.00081312324f, 0.00086596457f, 0.00092223983f, 0.00098217216f, 0.0010459992f, 0.0011139742f, 0.0011863665f, 0.0012634633f, 0.0013455702f, 0.0014330129f, 0.0015261382f, 0.0016253153f, 0.0017309374f, 0.0018434235f, 0.0019632195f, 0.0020908006f, 0.0022266726f, 0.0023713743f, 0.0025254795f, 0.0026895994f, 0.0028643847f, 0.0030505286f, 0.0032487691f, 0.0034598925f, 0.0036847358f, 0.0039241906f, 0.0041792066f, 0.0044507950f, 0.0047400328f, 0.0050480668f, 0.0053761186f, 0.0057254891f, 0.0060975636f, 0.0064938176f, 0.0069158225f, 0.0073652516f, 0.0078438871f, 0.0083536271f, 0.0088964928f, 0.009474637f, 0.010090352f, 0.010746080f, 0.011444421f, 0.012188144f, 0.012980198f, 0.013823725f, 0.014722068f, 0.015678791f, 0.016697687f, 0.017782797f, 0.018938423f, 0.020169149f, 0.021479854f, 0.022875735f, 0.024362330f, 0.025945531f, 0.027631618f, 0.029427276f, 0.031339626f, 0.033376252f, 0.035545228f, 0.037855157f, 0.040315199f, 0.042935108f, 0.045725273f, 0.048696758f, 0.051861348f, 0.055231591f, 0.058820850f, 0.062643361f, 0.066714279f, 0.071049749f, 0.075666962f, 0.080584227f, 0.085821044f, 0.091398179f, 0.097337747f, 0.10366330f, 0.11039993f, 0.11757434f, 0.12521498f, 0.13335215f, 0.14201813f, 0.15124727f, 0.16107617f, 0.17154380f, 0.18269168f, 0.19456402f, 0.20720788f, 0.22067342f, 0.23501402f, 0.25028656f, 0.26655159f, 0.28387361f, 0.30232132f, 0.32196786f, 0.34289114f, 0.36517414f, 0.38890521f, 0.41417847f, 0.44109412f, 0.46975890f, 0.50028648f, 0.53279791f, 0.56742212f, 0.60429640f, 0.64356699f, 0.68538959f, 0.72993007f, 0.77736504f, 0.82788260f, 0.88168307f, 0.9389798f, 1.0f }; // @OPTIMIZE: if you want to replace this bresenham line-drawing routine, // note that you must produce bit-identical output to decode correctly; // this specific sequence of operations is specified in the spec (it's // drawing integer-quantized frequency-space lines that the encoder // expects to be exactly the same) // ... also, isn't the whole point of Bresenham's algorithm to NOT // have to divide in the setup? sigh. #ifndef STB_VORBIS_NO_DEFER_FLOOR #define LINE_OP(a,b) a *= b #else #define LINE_OP(a,b) a = b #endif #ifdef STB_VORBIS_DIVIDE_TABLE #define DIVTAB_NUMER 32 #define DIVTAB_DENOM 64 int8 integer_divide_table[DIVTAB_NUMER][DIVTAB_DENOM]; // 2KB #endif static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n) { int dy = y1 - y0; int adx = x1 - x0; int ady = abs(dy); int base; int x=x0,y=y0; int err = 0; int sy; #ifdef STB_VORBIS_DIVIDE_TABLE if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) { if (dy < 0) { base = -integer_divide_table[ady][adx]; sy = base-1; } else { base = integer_divide_table[ady][adx]; sy = base+1; } } else { base = dy / adx; if (dy < 0) sy = base - 1; else sy = base+1; } #else base = dy / adx; if (dy < 0) sy = base - 1; else sy = base+1; #endif ady -= abs(base) * adx; if (x1 > n) x1 = n; if (x < x1) { LINE_OP(output[x], inverse_db_table[y&255]); for (++x; x < x1; ++x) { err += ady; if (err >= adx) { err -= adx; y += sy; } else y += base; LINE_OP(output[x], inverse_db_table[y&255]); } } } static int residue_decode(vorb *f, Codebook *book, float *target, int offset, int n, int rtype) { int k; if (rtype == 0) { int step = n / book->dimensions; for (k=0; k < step; ++k) if (!codebook_decode_step(f, book, target+offset+k, n-offset-k, step)) return FALSE; } else { for (k=0; k < n; ) { if (!codebook_decode(f, book, target+offset, n-k)) return FALSE; k += book->dimensions; offset += book->dimensions; } } return TRUE; } // n is 1/2 of the blocksize -- // specification: "Correct per-vector decode length is [n]/2" static void decode_residue(vorb *f, float *residue_buffers[], int ch, int n, int rn, uint8 *do_not_decode) { int i,j,pass; Residue *r = f->residue_config + rn; int rtype = f->residue_types[rn]; int c = r->classbook; int classwords = f->codebooks[c].dimensions; unsigned int actual_size = rtype == 2 ? n*2 : n; unsigned int limit_r_begin = (r->begin < actual_size ? r->begin : actual_size); unsigned int limit_r_end = (r->end < actual_size ? r->end : actual_size); int n_read = limit_r_end - limit_r_begin; int part_read = n_read / r->part_size; int temp_alloc_point = temp_alloc_save(f); #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE uint8 ***part_classdata = (uint8 ***) temp_block_array(f,f->channels, part_read * sizeof(**part_classdata)); #else int **classifications = (int **) temp_block_array(f,f->channels, part_read * sizeof(**classifications)); #endif CHECK(f); for (i=0; i < ch; ++i) if (!do_not_decode[i]) memset(residue_buffers[i], 0, sizeof(float) * n); if (rtype == 2 && ch != 1) { for (j=0; j < ch; ++j) if (!do_not_decode[j]) break; if (j == ch) goto done; for (pass=0; pass < 8; ++pass) { int pcount = 0, class_set = 0; if (ch == 2) { while (pcount < part_read) { int z = r->begin + pcount*r->part_size; int c_inter = (z & 1), p_inter = z>>1; if (pass == 0) { Codebook *c = f->codebooks+r->classbook; int q; DECODE(q,f,c); if (q == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[0][class_set] = r->classdata[q]; #else for (i=classwords-1; i >= 0; --i) { classifications[0][i+pcount] = q % r->classifications; q /= r->classifications; } #endif } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { int z = r->begin + pcount*r->part_size; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[0][class_set][i]; #else int c = classifications[0][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { Codebook *book = f->codebooks + b; #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; #else // saves 1% if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; #endif } else { z += r->part_size; c_inter = z & 1; p_inter = z >> 1; } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } else if (ch == 1) { while (pcount < part_read) { int z = r->begin + pcount*r->part_size; int c_inter = 0, p_inter = z; if (pass == 0) { Codebook *c = f->codebooks+r->classbook; int q; DECODE(q,f,c); if (q == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[0][class_set] = r->classdata[q]; #else for (i=classwords-1; i >= 0; --i) { classifications[0][i+pcount] = q % r->classifications; q /= r->classifications; } #endif } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { int z = r->begin + pcount*r->part_size; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[0][class_set][i]; #else int c = classifications[0][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { Codebook *book = f->codebooks + b; if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; } else { z += r->part_size; c_inter = 0; p_inter = z; } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } else { while (pcount < part_read) { int z = r->begin + pcount*r->part_size; int c_inter = z % ch, p_inter = z/ch; if (pass == 0) { Codebook *c = f->codebooks+r->classbook; int q; DECODE(q,f,c); if (q == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[0][class_set] = r->classdata[q]; #else for (i=classwords-1; i >= 0; --i) { classifications[0][i+pcount] = q % r->classifications; q /= r->classifications; } #endif } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { int z = r->begin + pcount*r->part_size; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[0][class_set][i]; #else int c = classifications[0][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { Codebook *book = f->codebooks + b; if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; } else { z += r->part_size; c_inter = z % ch; p_inter = z / ch; } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } } goto done; } CHECK(f); for (pass=0; pass < 8; ++pass) { int pcount = 0, class_set=0; while (pcount < part_read) { if (pass == 0) { for (j=0; j < ch; ++j) { if (!do_not_decode[j]) { Codebook *c = f->codebooks+r->classbook; int temp; DECODE(temp,f,c); if (temp == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[j][class_set] = r->classdata[temp]; #else for (i=classwords-1; i >= 0; --i) { classifications[j][i+pcount] = temp % r->classifications; temp /= r->classifications; } #endif } } } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { for (j=0; j < ch; ++j) { if (!do_not_decode[j]) { #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[j][class_set][i]; #else int c = classifications[j][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { float *target = residue_buffers[j]; int offset = r->begin + pcount * r->part_size; int n = r->part_size; Codebook *book = f->codebooks + b; if (!residue_decode(f, book, target, offset, n, rtype)) goto done; } } } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } done: CHECK(f); #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE temp_free(f,part_classdata); #else temp_free(f,classifications); #endif temp_alloc_restore(f,temp_alloc_point); } #if 0 // slow way for debugging void inverse_mdct_slow(float *buffer, int n) { int i,j; int n2 = n >> 1; float *x = (float *) malloc(sizeof(*x) * n2); memcpy(x, buffer, sizeof(*x) * n2); for (i=0; i < n; ++i) { float acc = 0; for (j=0; j < n2; ++j) // formula from paper: //acc += n/4.0f * x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1)); // formula from wikipedia //acc += 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5)); // these are equivalent, except the formula from the paper inverts the multiplier! // however, what actually works is NO MULTIPLIER!?! //acc += 64 * 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5)); acc += x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1)); buffer[i] = acc; } free(x); } #elif 0 // same as above, but just barely able to run in real time on modern machines void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype) { float mcos[16384]; int i,j; int n2 = n >> 1, nmask = (n << 2) -1; float *x = (float *) malloc(sizeof(*x) * n2); memcpy(x, buffer, sizeof(*x) * n2); for (i=0; i < 4*n; ++i) mcos[i] = (float) cos(M_PI / 2 * i / n); for (i=0; i < n; ++i) { float acc = 0; for (j=0; j < n2; ++j) acc += x[j] * mcos[(2 * i + 1 + n2)*(2*j+1) & nmask]; buffer[i] = acc; } free(x); } #elif 0 // transform to use a slow dct-iv; this is STILL basically trivial, // but only requires half as many ops void dct_iv_slow(float *buffer, int n) { float mcos[16384]; float x[2048]; int i,j; int n2 = n >> 1, nmask = (n << 3) - 1; memcpy(x, buffer, sizeof(*x) * n); for (i=0; i < 8*n; ++i) mcos[i] = (float) cos(M_PI / 4 * i / n); for (i=0; i < n; ++i) { float acc = 0; for (j=0; j < n; ++j) acc += x[j] * mcos[((2 * i + 1)*(2*j+1)) & nmask]; buffer[i] = acc; } } void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype) { int i, n4 = n >> 2, n2 = n >> 1, n3_4 = n - n4; float temp[4096]; memcpy(temp, buffer, n2 * sizeof(float)); dct_iv_slow(temp, n2); // returns -c'-d, a-b' for (i=0; i < n4 ; ++i) buffer[i] = temp[i+n4]; // a-b' for ( ; i < n3_4; ++i) buffer[i] = -temp[n3_4 - i - 1]; // b-a', c+d' for ( ; i < n ; ++i) buffer[i] = -temp[i - n3_4]; // c'+d } #endif #ifndef LIBVORBIS_MDCT #define LIBVORBIS_MDCT 0 #endif #if LIBVORBIS_MDCT // directly call the vorbis MDCT using an interface documented // by Jeff Roberts... useful for performance comparison typedef struct { int n; int log2n; float *trig; int *bitrev; float scale; } mdct_lookup; extern void mdct_init(mdct_lookup *lookup, int n); extern void mdct_clear(mdct_lookup *l); extern void mdct_backward(mdct_lookup *init, float *in, float *out); mdct_lookup M1,M2; void inverse_mdct(float *buffer, int n, vorb *f, int blocktype) { mdct_lookup *M; if (M1.n == n) M = &M1; else if (M2.n == n) M = &M2; else if (M1.n == 0) { mdct_init(&M1, n); M = &M1; } else { if (M2.n) __asm int 3; mdct_init(&M2, n); M = &M2; } mdct_backward(M, buffer, buffer); } #endif // the following were split out into separate functions while optimizing; // they could be pushed back up but eh. __forceinline showed no change; // they're probably already being inlined. static void imdct_step3_iter0_loop(int n, float *e, int i_off, int k_off, float *A) { float *ee0 = e + i_off; float *ee2 = ee0 + k_off; int i; assert((n & 3) == 0); for (i=(n>>2); i > 0; --i) { float k00_20, k01_21; k00_20 = ee0[ 0] - ee2[ 0]; k01_21 = ee0[-1] - ee2[-1]; ee0[ 0] += ee2[ 0];//ee0[ 0] = ee0[ 0] + ee2[ 0]; ee0[-1] += ee2[-1];//ee0[-1] = ee0[-1] + ee2[-1]; ee2[ 0] = k00_20 * A[0] - k01_21 * A[1]; ee2[-1] = k01_21 * A[0] + k00_20 * A[1]; A += 8; k00_20 = ee0[-2] - ee2[-2]; k01_21 = ee0[-3] - ee2[-3]; ee0[-2] += ee2[-2];//ee0[-2] = ee0[-2] + ee2[-2]; ee0[-3] += ee2[-3];//ee0[-3] = ee0[-3] + ee2[-3]; ee2[-2] = k00_20 * A[0] - k01_21 * A[1]; ee2[-3] = k01_21 * A[0] + k00_20 * A[1]; A += 8; k00_20 = ee0[-4] - ee2[-4]; k01_21 = ee0[-5] - ee2[-5]; ee0[-4] += ee2[-4];//ee0[-4] = ee0[-4] + ee2[-4]; ee0[-5] += ee2[-5];//ee0[-5] = ee0[-5] + ee2[-5]; ee2[-4] = k00_20 * A[0] - k01_21 * A[1]; ee2[-5] = k01_21 * A[0] + k00_20 * A[1]; A += 8; k00_20 = ee0[-6] - ee2[-6]; k01_21 = ee0[-7] - ee2[-7]; ee0[-6] += ee2[-6];//ee0[-6] = ee0[-6] + ee2[-6]; ee0[-7] += ee2[-7];//ee0[-7] = ee0[-7] + ee2[-7]; ee2[-6] = k00_20 * A[0] - k01_21 * A[1]; ee2[-7] = k01_21 * A[0] + k00_20 * A[1]; A += 8; ee0 -= 8; ee2 -= 8; } } static void imdct_step3_inner_r_loop(int lim, float *e, int d0, int k_off, float *A, int k1) { int i; float k00_20, k01_21; float *e0 = e + d0; float *e2 = e0 + k_off; for (i=lim >> 2; i > 0; --i) { k00_20 = e0[-0] - e2[-0]; k01_21 = e0[-1] - e2[-1]; e0[-0] += e2[-0];//e0[-0] = e0[-0] + e2[-0]; e0[-1] += e2[-1];//e0[-1] = e0[-1] + e2[-1]; e2[-0] = (k00_20)*A[0] - (k01_21) * A[1]; e2[-1] = (k01_21)*A[0] + (k00_20) * A[1]; A += k1; k00_20 = e0[-2] - e2[-2]; k01_21 = e0[-3] - e2[-3]; e0[-2] += e2[-2];//e0[-2] = e0[-2] + e2[-2]; e0[-3] += e2[-3];//e0[-3] = e0[-3] + e2[-3]; e2[-2] = (k00_20)*A[0] - (k01_21) * A[1]; e2[-3] = (k01_21)*A[0] + (k00_20) * A[1]; A += k1; k00_20 = e0[-4] - e2[-4]; k01_21 = e0[-5] - e2[-5]; e0[-4] += e2[-4];//e0[-4] = e0[-4] + e2[-4]; e0[-5] += e2[-5];//e0[-5] = e0[-5] + e2[-5]; e2[-4] = (k00_20)*A[0] - (k01_21) * A[1]; e2[-5] = (k01_21)*A[0] + (k00_20) * A[1]; A += k1; k00_20 = e0[-6] - e2[-6]; k01_21 = e0[-7] - e2[-7]; e0[-6] += e2[-6];//e0[-6] = e0[-6] + e2[-6]; e0[-7] += e2[-7];//e0[-7] = e0[-7] + e2[-7]; e2[-6] = (k00_20)*A[0] - (k01_21) * A[1]; e2[-7] = (k01_21)*A[0] + (k00_20) * A[1]; e0 -= 8; e2 -= 8; A += k1; } } static void imdct_step3_inner_s_loop(int n, float *e, int i_off, int k_off, float *A, int a_off, int k0) { int i; float A0 = A[0]; float A1 = A[0+1]; float A2 = A[0+a_off]; float A3 = A[0+a_off+1]; float A4 = A[0+a_off*2+0]; float A5 = A[0+a_off*2+1]; float A6 = A[0+a_off*3+0]; float A7 = A[0+a_off*3+1]; float k00,k11; float *ee0 = e +i_off; float *ee2 = ee0+k_off; for (i=n; i > 0; --i) { k00 = ee0[ 0] - ee2[ 0]; k11 = ee0[-1] - ee2[-1]; ee0[ 0] = ee0[ 0] + ee2[ 0]; ee0[-1] = ee0[-1] + ee2[-1]; ee2[ 0] = (k00) * A0 - (k11) * A1; ee2[-1] = (k11) * A0 + (k00) * A1; k00 = ee0[-2] - ee2[-2]; k11 = ee0[-3] - ee2[-3]; ee0[-2] = ee0[-2] + ee2[-2]; ee0[-3] = ee0[-3] + ee2[-3]; ee2[-2] = (k00) * A2 - (k11) * A3; ee2[-3] = (k11) * A2 + (k00) * A3; k00 = ee0[-4] - ee2[-4]; k11 = ee0[-5] - ee2[-5]; ee0[-4] = ee0[-4] + ee2[-4]; ee0[-5] = ee0[-5] + ee2[-5]; ee2[-4] = (k00) * A4 - (k11) * A5; ee2[-5] = (k11) * A4 + (k00) * A5; k00 = ee0[-6] - ee2[-6]; k11 = ee0[-7] - ee2[-7]; ee0[-6] = ee0[-6] + ee2[-6]; ee0[-7] = ee0[-7] + ee2[-7]; ee2[-6] = (k00) * A6 - (k11) * A7; ee2[-7] = (k11) * A6 + (k00) * A7; ee0 -= k0; ee2 -= k0; } } static __forceinline void iter_54(float *z) { float k00,k11,k22,k33; float y0,y1,y2,y3; k00 = z[ 0] - z[-4]; y0 = z[ 0] + z[-4]; y2 = z[-2] + z[-6]; k22 = z[-2] - z[-6]; z[-0] = y0 + y2; // z0 + z4 + z2 + z6 z[-2] = y0 - y2; // z0 + z4 - z2 - z6 // done with y0,y2 k33 = z[-3] - z[-7]; z[-4] = k00 + k33; // z0 - z4 + z3 - z7 z[-6] = k00 - k33; // z0 - z4 - z3 + z7 // done with k33 k11 = z[-1] - z[-5]; y1 = z[-1] + z[-5]; y3 = z[-3] + z[-7]; z[-1] = y1 + y3; // z1 + z5 + z3 + z7 z[-3] = y1 - y3; // z1 + z5 - z3 - z7 z[-5] = k11 - k22; // z1 - z5 + z2 - z6 z[-7] = k11 + k22; // z1 - z5 - z2 + z6 } static void imdct_step3_inner_s_loop_ld654(int n, float *e, int i_off, float *A, int base_n) { int a_off = base_n >> 3; float A2 = A[0+a_off]; float *z = e + i_off; float *base = z - 16 * n; while (z > base) { float k00,k11; k00 = z[-0] - z[-8]; k11 = z[-1] - z[-9]; z[-0] = z[-0] + z[-8]; z[-1] = z[-1] + z[-9]; z[-8] = k00; z[-9] = k11 ; k00 = z[ -2] - z[-10]; k11 = z[ -3] - z[-11]; z[ -2] = z[ -2] + z[-10]; z[ -3] = z[ -3] + z[-11]; z[-10] = (k00+k11) * A2; z[-11] = (k11-k00) * A2; k00 = z[-12] - z[ -4]; // reverse to avoid a unary negation k11 = z[ -5] - z[-13]; z[ -4] = z[ -4] + z[-12]; z[ -5] = z[ -5] + z[-13]; z[-12] = k11; z[-13] = k00; k00 = z[-14] - z[ -6]; // reverse to avoid a unary negation k11 = z[ -7] - z[-15]; z[ -6] = z[ -6] + z[-14]; z[ -7] = z[ -7] + z[-15]; z[-14] = (k00+k11) * A2; z[-15] = (k00-k11) * A2; iter_54(z); iter_54(z-8); z -= 16; } } static void inverse_mdct(float *buffer, int n, vorb *f, int blocktype) { int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l; int ld; // @OPTIMIZE: reduce register pressure by using fewer variables? int save_point = temp_alloc_save(f); float *buf2 = (float *) temp_alloc(f, n2 * sizeof(*buf2)); float *u=NULL,*v=NULL; // twiddle factors float *A = f->A[blocktype]; // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio" // See notes about bugs in that paper in less-optimal implementation 'inverse_mdct_old' after this function. // kernel from paper // merged: // copy and reflect spectral data // step 0 // note that it turns out that the items added together during // this step are, in fact, being added to themselves (as reflected // by step 0). inexplicable inefficiency! this became obvious // once I combined the passes. // so there's a missing 'times 2' here (for adding X to itself). // this propagates through linearly to the end, where the numbers // are 1/2 too small, and need to be compensated for. { float *d,*e, *AA, *e_stop; d = &buf2[n2-2]; AA = A; e = &buffer[0]; e_stop = &buffer[n2]; while (e != e_stop) { d[1] = (e[0] * AA[0] - e[2]*AA[1]); d[0] = (e[0] * AA[1] + e[2]*AA[0]); d -= 2; AA += 2; e += 4; } e = &buffer[n2-3]; while (d >= buf2) { d[1] = (-e[2] * AA[0] - -e[0]*AA[1]); d[0] = (-e[2] * AA[1] + -e[0]*AA[0]); d -= 2; AA += 2; e -= 4; } } // now we use symbolic names for these, so that we can // possibly swap their meaning as we change which operations // are in place u = buffer; v = buf2; // step 2 (paper output is w, now u) // this could be in place, but the data ends up in the wrong // place... _somebody_'s got to swap it, so this is nominated { float *AA = &A[n2-8]; float *d0,*d1, *e0, *e1; e0 = &v[n4]; e1 = &v[0]; d0 = &u[n4]; d1 = &u[0]; while (AA >= A) { float v40_20, v41_21; v41_21 = e0[1] - e1[1]; v40_20 = e0[0] - e1[0]; d0[1] = e0[1] + e1[1]; d0[0] = e0[0] + e1[0]; d1[1] = v41_21*AA[4] - v40_20*AA[5]; d1[0] = v40_20*AA[4] + v41_21*AA[5]; v41_21 = e0[3] - e1[3]; v40_20 = e0[2] - e1[2]; d0[3] = e0[3] + e1[3]; d0[2] = e0[2] + e1[2]; d1[3] = v41_21*AA[0] - v40_20*AA[1]; d1[2] = v40_20*AA[0] + v41_21*AA[1]; AA -= 8; d0 += 4; d1 += 4; e0 += 4; e1 += 4; } } // step 3 ld = ilog(n) - 1; // ilog is off-by-one from normal definitions // optimized step 3: // the original step3 loop can be nested r inside s or s inside r; // it's written originally as s inside r, but this is dumb when r // iterates many times, and s few. So I have two copies of it and // switch between them halfway. // this is iteration 0 of step 3 imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*0, -(n >> 3), A); imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*1, -(n >> 3), A); // this is iteration 1 of step 3 imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*0, -(n >> 4), A, 16); imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*1, -(n >> 4), A, 16); imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*2, -(n >> 4), A, 16); imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*3, -(n >> 4), A, 16); l=2; for (; l < (ld-3)>>1; ++l) { int k0 = n >> (l+2), k0_2 = k0>>1; int lim = 1 << (l+1); int i; for (i=0; i < lim; ++i) imdct_step3_inner_r_loop(n >> (l+4), u, n2-1 - k0*i, -k0_2, A, 1 << (l+3)); } for (; l < ld-6; ++l) { int k0 = n >> (l+2), k1 = 1 << (l+3), k0_2 = k0>>1; int rlim = n >> (l+6), r; int lim = 1 << (l+1); int i_off; float *A0 = A; i_off = n2-1; for (r=rlim; r > 0; --r) { imdct_step3_inner_s_loop(lim, u, i_off, -k0_2, A0, k1, k0); A0 += k1*4; i_off -= 8; } } // iterations with count: // ld-6,-5,-4 all interleaved together // the big win comes from getting rid of needless flops // due to the constants on pass 5 & 4 being all 1 and 0; // combining them to be simultaneous to improve cache made little difference imdct_step3_inner_s_loop_ld654(n >> 5, u, n2-1, A, n); // output is u // step 4, 5, and 6 // cannot be in-place because of step 5 { uint16 *bitrev = f->bit_reverse[blocktype]; // weirdly, I'd have thought reading sequentially and writing // erratically would have been better than vice-versa, but in // fact that's not what my testing showed. (That is, with // j = bitreverse(i), do you read i and write j, or read j and write i.) float *d0 = &v[n4-4]; float *d1 = &v[n2-4]; while (d0 >= v) { int k4; k4 = bitrev[0]; d1[3] = u[k4+0]; d1[2] = u[k4+1]; d0[3] = u[k4+2]; d0[2] = u[k4+3]; k4 = bitrev[1]; d1[1] = u[k4+0]; d1[0] = u[k4+1]; d0[1] = u[k4+2]; d0[0] = u[k4+3]; d0 -= 4; d1 -= 4; bitrev += 2; } } // (paper output is u, now v) // data must be in buf2 assert(v == buf2); // step 7 (paper output is v, now v) // this is now in place { float *C = f->C[blocktype]; float *d, *e; d = v; e = v + n2 - 4; while (d < e) { float a02,a11,b0,b1,b2,b3; a02 = d[0] - e[2]; a11 = d[1] + e[3]; b0 = C[1]*a02 + C[0]*a11; b1 = C[1]*a11 - C[0]*a02; b2 = d[0] + e[ 2]; b3 = d[1] - e[ 3]; d[0] = b2 + b0; d[1] = b3 + b1; e[2] = b2 - b0; e[3] = b1 - b3; a02 = d[2] - e[0]; a11 = d[3] + e[1]; b0 = C[3]*a02 + C[2]*a11; b1 = C[3]*a11 - C[2]*a02; b2 = d[2] + e[ 0]; b3 = d[3] - e[ 1]; d[2] = b2 + b0; d[3] = b3 + b1; e[0] = b2 - b0; e[1] = b1 - b3; C += 4; d += 4; e -= 4; } } // data must be in buf2 // step 8+decode (paper output is X, now buffer) // this generates pairs of data a la 8 and pushes them directly through // the decode kernel (pushing rather than pulling) to avoid having // to make another pass later // this cannot POSSIBLY be in place, so we refer to the buffers directly { float *d0,*d1,*d2,*d3; float *B = f->B[blocktype] + n2 - 8; float *e = buf2 + n2 - 8; d0 = &buffer[0]; d1 = &buffer[n2-4]; d2 = &buffer[n2]; d3 = &buffer[n-4]; while (e >= v) { float p0,p1,p2,p3; p3 = e[6]*B[7] - e[7]*B[6]; p2 = -e[6]*B[6] - e[7]*B[7]; d0[0] = p3; d1[3] = - p3; d2[0] = p2; d3[3] = p2; p1 = e[4]*B[5] - e[5]*B[4]; p0 = -e[4]*B[4] - e[5]*B[5]; d0[1] = p1; d1[2] = - p1; d2[1] = p0; d3[2] = p0; p3 = e[2]*B[3] - e[3]*B[2]; p2 = -e[2]*B[2] - e[3]*B[3]; d0[2] = p3; d1[1] = - p3; d2[2] = p2; d3[1] = p2; p1 = e[0]*B[1] - e[1]*B[0]; p0 = -e[0]*B[0] - e[1]*B[1]; d0[3] = p1; d1[0] = - p1; d2[3] = p0; d3[0] = p0; B -= 8; e -= 8; d0 += 4; d2 += 4; d1 -= 4; d3 -= 4; } } temp_free(f,buf2); temp_alloc_restore(f,save_point); } #if 0 // this is the original version of the above code, if you want to optimize it from scratch void inverse_mdct_naive(float *buffer, int n) { float s; float A[1 << 12], B[1 << 12], C[1 << 11]; int i,k,k2,k4, n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l; int n3_4 = n - n4, ld; // how can they claim this only uses N words?! // oh, because they're only used sparsely, whoops float u[1 << 13], X[1 << 13], v[1 << 13], w[1 << 13]; // set up twiddle factors for (k=k2=0; k < n4; ++k,k2+=2) { A[k2 ] = (float) cos(4*k*M_PI/n); A[k2+1] = (float) -sin(4*k*M_PI/n); B[k2 ] = (float) cos((k2+1)*M_PI/n/2); B[k2+1] = (float) sin((k2+1)*M_PI/n/2); } for (k=k2=0; k < n8; ++k,k2+=2) { C[k2 ] = (float) cos(2*(k2+1)*M_PI/n); C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n); } // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio" // Note there are bugs in that pseudocode, presumably due to them attempting // to rename the arrays nicely rather than representing the way their actual // implementation bounces buffers back and forth. As a result, even in the // "some formulars corrected" version, a direct implementation fails. These // are noted below as "paper bug". // copy and reflect spectral data for (k=0; k < n2; ++k) u[k] = buffer[k]; for ( ; k < n ; ++k) u[k] = -buffer[n - k - 1]; // kernel from paper // step 1 for (k=k2=k4=0; k < n4; k+=1, k2+=2, k4+=4) { v[n-k4-1] = (u[k4] - u[n-k4-1]) * A[k2] - (u[k4+2] - u[n-k4-3])*A[k2+1]; v[n-k4-3] = (u[k4] - u[n-k4-1]) * A[k2+1] + (u[k4+2] - u[n-k4-3])*A[k2]; } // step 2 for (k=k4=0; k < n8; k+=1, k4+=4) { w[n2+3+k4] = v[n2+3+k4] + v[k4+3]; w[n2+1+k4] = v[n2+1+k4] + v[k4+1]; w[k4+3] = (v[n2+3+k4] - v[k4+3])*A[n2-4-k4] - (v[n2+1+k4]-v[k4+1])*A[n2-3-k4]; w[k4+1] = (v[n2+1+k4] - v[k4+1])*A[n2-4-k4] + (v[n2+3+k4]-v[k4+3])*A[n2-3-k4]; } // step 3 ld = ilog(n) - 1; // ilog is off-by-one from normal definitions for (l=0; l < ld-3; ++l) { int k0 = n >> (l+2), k1 = 1 << (l+3); int rlim = n >> (l+4), r4, r; int s2lim = 1 << (l+2), s2; for (r=r4=0; r < rlim; r4+=4,++r) { for (s2=0; s2 < s2lim; s2+=2) { u[n-1-k0*s2-r4] = w[n-1-k0*s2-r4] + w[n-1-k0*(s2+1)-r4]; u[n-3-k0*s2-r4] = w[n-3-k0*s2-r4] + w[n-3-k0*(s2+1)-r4]; u[n-1-k0*(s2+1)-r4] = (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1] - (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1+1]; u[n-3-k0*(s2+1)-r4] = (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1] + (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1+1]; } } if (l+1 < ld-3) { // paper bug: ping-ponging of u&w here is omitted memcpy(w, u, sizeof(u)); } } // step 4 for (i=0; i < n8; ++i) { int j = bit_reverse(i) >> (32-ld+3); assert(j < n8); if (i == j) { // paper bug: original code probably swapped in place; if copying, // need to directly copy in this case int i8 = i << 3; v[i8+1] = u[i8+1]; v[i8+3] = u[i8+3]; v[i8+5] = u[i8+5]; v[i8+7] = u[i8+7]; } else if (i < j) { int i8 = i << 3, j8 = j << 3; v[j8+1] = u[i8+1], v[i8+1] = u[j8 + 1]; v[j8+3] = u[i8+3], v[i8+3] = u[j8 + 3]; v[j8+5] = u[i8+5], v[i8+5] = u[j8 + 5]; v[j8+7] = u[i8+7], v[i8+7] = u[j8 + 7]; } } // step 5 for (k=0; k < n2; ++k) { w[k] = v[k*2+1]; } // step 6 for (k=k2=k4=0; k < n8; ++k, k2 += 2, k4 += 4) { u[n-1-k2] = w[k4]; u[n-2-k2] = w[k4+1]; u[n3_4 - 1 - k2] = w[k4+2]; u[n3_4 - 2 - k2] = w[k4+3]; } // step 7 for (k=k2=0; k < n8; ++k, k2 += 2) { v[n2 + k2 ] = ( u[n2 + k2] + u[n-2-k2] + C[k2+1]*(u[n2+k2]-u[n-2-k2]) + C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2; v[n-2 - k2] = ( u[n2 + k2] + u[n-2-k2] - C[k2+1]*(u[n2+k2]-u[n-2-k2]) - C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2; v[n2+1+ k2] = ( u[n2+1+k2] - u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2; v[n-1 - k2] = (-u[n2+1+k2] + u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2; } // step 8 for (k=k2=0; k < n4; ++k,k2 += 2) { X[k] = v[k2+n2]*B[k2 ] + v[k2+1+n2]*B[k2+1]; X[n2-1-k] = v[k2+n2]*B[k2+1] - v[k2+1+n2]*B[k2 ]; } // decode kernel to output // determined the following value experimentally // (by first figuring out what made inverse_mdct_slow work); then matching that here // (probably vorbis encoder premultiplies by n or n/2, to save it on the decoder?) s = 0.5; // theoretically would be n4 // [[[ note! the s value of 0.5 is compensated for by the B[] in the current code, // so it needs to use the "old" B values to behave correctly, or else // set s to 1.0 ]]] for (i=0; i < n4 ; ++i) buffer[i] = s * X[i+n4]; for ( ; i < n3_4; ++i) buffer[i] = -s * X[n3_4 - i - 1]; for ( ; i < n ; ++i) buffer[i] = -s * X[i - n3_4]; } #endif static float *get_window(vorb *f, int len) { len <<= 1; if (len == f->blocksize_0) return f->window[0]; if (len == f->blocksize_1) return f->window[1]; return NULL; } #ifndef STB_VORBIS_NO_DEFER_FLOOR typedef int16 YTYPE; #else typedef int YTYPE; #endif static int do_floor(vorb *f, Mapping *map, int i, int n, float *target, YTYPE *finalY, uint8 *step2_flag) { int n2 = n >> 1; int s = map->chan[i].mux, floor; floor = map->submap_floor[s]; if (f->floor_types[floor] == 0) { return error(f, VORBIS_invalid_stream); } else { Floor1 *g = &f->floor_config[floor].floor1; int j,q; int lx = 0, ly = finalY[0] * g->floor1_multiplier; for (q=1; q < g->values; ++q) { j = g->sorted_order[q]; #ifndef STB_VORBIS_NO_DEFER_FLOOR if (finalY[j] >= 0) #else if (step2_flag[j]) #endif { int hy = finalY[j] * g->floor1_multiplier; int hx = g->Xlist[j]; if (lx != hx) draw_line(target, lx,ly, hx,hy, n2); CHECK(f); lx = hx, ly = hy; } } if (lx < n2) { // optimization of: draw_line(target, lx,ly, n,ly, n2); for (j=lx; j < n2; ++j) LINE_OP(target[j], inverse_db_table[ly]); CHECK(f); } } return TRUE; } // The meaning of "left" and "right" // // For a given frame: // we compute samples from 0..n // window_center is n/2 // we'll window and mix the samples from left_start to left_end with data from the previous frame // all of the samples from left_end to right_start can be output without mixing; however, // this interval is 0-length except when transitioning between short and long frames // all of the samples from right_start to right_end need to be mixed with the next frame, // which we don't have, so those get saved in a buffer // frame N's right_end-right_start, the number of samples to mix with the next frame, // has to be the same as frame N+1's left_end-left_start (which they are by // construction) static int vorbis_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode) { Mode *m; int i, n, prev, next, window_center; f->channel_buffer_start = f->channel_buffer_end = 0; retry: if (f->eof) return FALSE; if (!maybe_start_packet(f)) return FALSE; // check packet type if (get_bits(f,1) != 0) { if (IS_PUSH_MODE(f)) return error(f,VORBIS_bad_packet_type); while (EOP != get8_packet(f)); goto retry; } if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); i = get_bits(f, ilog(f->mode_count-1)); if (i == EOP) return FALSE; if (i >= f->mode_count) return FALSE; *mode = i; m = f->mode_config + i; if (m->blockflag) { n = f->blocksize_1; prev = get_bits(f,1); next = get_bits(f,1); } else { prev = next = 0; n = f->blocksize_0; } // WINDOWING window_center = n >> 1; if (m->blockflag && !prev) { *p_left_start = (n - f->blocksize_0) >> 2; *p_left_end = (n + f->blocksize_0) >> 2; } else { *p_left_start = 0; *p_left_end = window_center; } if (m->blockflag && !next) { *p_right_start = (n*3 - f->blocksize_0) >> 2; *p_right_end = (n*3 + f->blocksize_0) >> 2; } else { *p_right_start = window_center; *p_right_end = n; } return TRUE; } static int vorbis_decode_packet_rest(vorb *f, int *len, Mode *m, int left_start, int left_end, int right_start, int right_end, int *p_left) { Mapping *map; int i,j,k,n,n2; int zero_channel[256]; int really_zero_channel[256]; // WINDOWING n = f->blocksize[m->blockflag]; map = &f->mapping[m->mapping]; // FLOORS n2 = n >> 1; CHECK(f); for (i=0; i < f->channels; ++i) { int s = map->chan[i].mux, floor; zero_channel[i] = FALSE; floor = map->submap_floor[s]; if (f->floor_types[floor] == 0) { return error(f, VORBIS_invalid_stream); } else { Floor1 *g = &f->floor_config[floor].floor1; if (get_bits(f, 1)) { short *finalY; uint8 step2_flag[256]; static int range_list[4] = { 256, 128, 86, 64 }; int range = range_list[g->floor1_multiplier-1]; int offset = 2; finalY = f->finalY[i]; finalY[0] = get_bits(f, ilog(range)-1); finalY[1] = get_bits(f, ilog(range)-1); for (j=0; j < g->partitions; ++j) { int pclass = g->partition_class_list[j]; int cdim = g->class_dimensions[pclass]; int cbits = g->class_subclasses[pclass]; int csub = (1 << cbits)-1; int cval = 0; if (cbits) { Codebook *c = f->codebooks + g->class_masterbooks[pclass]; DECODE(cval,f,c); } for (k=0; k < cdim; ++k) { int book = g->subclass_books[pclass][cval & csub]; cval = cval >> cbits; if (book >= 0) { int temp; Codebook *c = f->codebooks + book; DECODE(temp,f,c); finalY[offset++] = temp; } else finalY[offset++] = 0; } } if (f->valid_bits == INVALID_BITS) goto error; // behavior according to spec step2_flag[0] = step2_flag[1] = 1; for (j=2; j < g->values; ++j) { int low, high, pred, highroom, lowroom, room, val; low = g->neighbors[j][0]; high = g->neighbors[j][1]; //neighbors(g->Xlist, j, &low, &high); pred = predict_point(g->Xlist[j], g->Xlist[low], g->Xlist[high], finalY[low], finalY[high]); val = finalY[j]; highroom = range - pred; lowroom = pred; if (highroom < lowroom) room = highroom * 2; else room = lowroom * 2; if (val) { step2_flag[low] = step2_flag[high] = 1; step2_flag[j] = 1; if (val >= room) if (highroom > lowroom) finalY[j] = val - lowroom + pred; else finalY[j] = pred - val + highroom - 1; else if (val & 1) finalY[j] = pred - ((val+1)>>1); else finalY[j] = pred + (val>>1); } else { step2_flag[j] = 0; finalY[j] = pred; } } #ifdef STB_VORBIS_NO_DEFER_FLOOR do_floor(f, map, i, n, f->floor_buffers[i], finalY, step2_flag); #else // defer final floor computation until _after_ residue for (j=0; j < g->values; ++j) { if (!step2_flag[j]) finalY[j] = -1; } #endif } else { error: zero_channel[i] = TRUE; } // So we just defer everything else to later // at this point we've decoded the floor into buffer } } CHECK(f); // at this point we've decoded all floors if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); // re-enable coupled channels if necessary memcpy(really_zero_channel, zero_channel, sizeof(really_zero_channel[0]) * f->channels); for (i=0; i < map->coupling_steps; ++i) if (!zero_channel[map->chan[i].magnitude] || !zero_channel[map->chan[i].angle]) { zero_channel[map->chan[i].magnitude] = zero_channel[map->chan[i].angle] = FALSE; } CHECK(f); // RESIDUE DECODE for (i=0; i < map->submaps; ++i) { float *residue_buffers[STB_VORBIS_MAX_CHANNELS]; int r; uint8 do_not_decode[256]; int ch = 0; for (j=0; j < f->channels; ++j) { if (map->chan[j].mux == i) { if (zero_channel[j]) { do_not_decode[ch] = TRUE; residue_buffers[ch] = NULL; } else { do_not_decode[ch] = FALSE; residue_buffers[ch] = f->channel_buffers[j]; } ++ch; } } r = map->submap_residue[i]; decode_residue(f, residue_buffers, ch, n2, r, do_not_decode); } if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); CHECK(f); // INVERSE COUPLING for (i = map->coupling_steps-1; i >= 0; --i) { int n2 = n >> 1; float *m = f->channel_buffers[map->chan[i].magnitude]; float *a = f->channel_buffers[map->chan[i].angle ]; for (j=0; j < n2; ++j) { float a2,m2; if (m[j] > 0) if (a[j] > 0) m2 = m[j], a2 = m[j] - a[j]; else a2 = m[j], m2 = m[j] + a[j]; else if (a[j] > 0) m2 = m[j], a2 = m[j] + a[j]; else a2 = m[j], m2 = m[j] - a[j]; m[j] = m2; a[j] = a2; } } CHECK(f); // finish decoding the floors #ifndef STB_VORBIS_NO_DEFER_FLOOR for (i=0; i < f->channels; ++i) { if (really_zero_channel[i]) { memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2); } else { do_floor(f, map, i, n, f->channel_buffers[i], f->finalY[i], NULL); } } #else for (i=0; i < f->channels; ++i) { if (really_zero_channel[i]) { memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2); } else { for (j=0; j < n2; ++j) f->channel_buffers[i][j] *= f->floor_buffers[i][j]; } } #endif // INVERSE MDCT CHECK(f); for (i=0; i < f->channels; ++i) inverse_mdct(f->channel_buffers[i], n, f, m->blockflag); CHECK(f); // this shouldn't be necessary, unless we exited on an error // and want to flush to get to the next packet flush_packet(f); if (f->first_decode) { // assume we start so first non-discarded sample is sample 0 // this isn't to spec, but spec would require us to read ahead // and decode the size of all current frames--could be done, // but presumably it's not a commonly used feature f->current_loc = -n2; // start of first frame is positioned for discard // we might have to discard samples "from" the next frame too, // if we're lapping a large block then a small at the start? f->discard_samples_deferred = n - right_end; f->current_loc_valid = TRUE; f->first_decode = FALSE; } else if (f->discard_samples_deferred) { if (f->discard_samples_deferred >= right_start - left_start) { f->discard_samples_deferred -= (right_start - left_start); left_start = right_start; *p_left = left_start; } else { left_start += f->discard_samples_deferred; *p_left = left_start; f->discard_samples_deferred = 0; } } else if (f->previous_length == 0 && f->current_loc_valid) { // we're recovering from a seek... that means we're going to discard // the samples from this packet even though we know our position from // the last page header, so we need to update the position based on // the discarded samples here // but wait, the code below is going to add this in itself even // on a discard, so we don't need to do it here... } // check if we have ogg information about the sample # for this packet if (f->last_seg_which == f->end_seg_with_known_loc) { // if we have a valid current loc, and this is final: if (f->current_loc_valid && (f->page_flag & PAGEFLAG_last_page)) { uint32 current_end = f->known_loc_for_packet; // then let's infer the size of the (probably) short final frame if (current_end < f->current_loc + (right_end-left_start)) { if (current_end < f->current_loc) { // negative truncation, that's impossible! *len = 0; } else { *len = current_end - f->current_loc; } *len += left_start; // this doesn't seem right, but has no ill effect on my test files if (*len > right_end) *len = right_end; // this should never happen f->current_loc += *len; return TRUE; } } // otherwise, just set our sample loc // guess that the ogg granule pos refers to the _middle_ of the // last frame? // set f->current_loc to the position of left_start f->current_loc = f->known_loc_for_packet - (n2-left_start); f->current_loc_valid = TRUE; } if (f->current_loc_valid) f->current_loc += (right_start - left_start); if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); *len = right_end; // ignore samples after the window goes to 0 CHECK(f); return TRUE; } static int vorbis_decode_packet(vorb *f, int *len, int *p_left, int *p_right) { int mode, left_end, right_end; if (!vorbis_decode_initial(f, p_left, &left_end, p_right, &right_end, &mode)) return 0; return vorbis_decode_packet_rest(f, len, f->mode_config + mode, *p_left, left_end, *p_right, right_end, p_left); } static int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right) { int prev,i,j; // we use right&left (the start of the right- and left-window sin()-regions) // to determine how much to return, rather than inferring from the rules // (same result, clearer code); 'left' indicates where our sin() window // starts, therefore where the previous window's right edge starts, and // therefore where to start mixing from the previous buffer. 'right' // indicates where our sin() ending-window starts, therefore that's where // we start saving, and where our returned-data ends. // mixin from previous window if (f->previous_length) { int i,j, n = f->previous_length; float *w = get_window(f, n); if (w == NULL) return 0; for (i=0; i < f->channels; ++i) { for (j=0; j < n; ++j) f->channel_buffers[i][left+j] = f->channel_buffers[i][left+j]*w[ j] + f->previous_window[i][ j]*w[n-1-j]; } } prev = f->previous_length; // last half of this data becomes previous window f->previous_length = len - right; // @OPTIMIZE: could avoid this copy by double-buffering the // output (flipping previous_window with channel_buffers), but // then previous_window would have to be 2x as large, and // channel_buffers couldn't be temp mem (although they're NOT // currently temp mem, they could be (unless we want to level // performance by spreading out the computation)) for (i=0; i < f->channels; ++i) for (j=0; right+j < len; ++j) f->previous_window[i][j] = f->channel_buffers[i][right+j]; if (!prev) // there was no previous packet, so this data isn't valid... // this isn't entirely true, only the would-have-overlapped data // isn't valid, but this seems to be what the spec requires return 0; // truncate a short frame if (len < right) right = len; f->samples_output += right-left; return right - left; } static int vorbis_pump_first_frame(stb_vorbis *f) { int len, right, left, res; res = vorbis_decode_packet(f, &len, &left, &right); if (res) vorbis_finish_frame(f, len, left, right); return res; } #ifndef STB_VORBIS_NO_PUSHDATA_API static int is_whole_packet_present(stb_vorbis *f, int end_page) { // make sure that we have the packet available before continuing... // this requires a full ogg parse, but we know we can fetch from f->stream // instead of coding this out explicitly, we could save the current read state, // read the next packet with get8() until end-of-packet, check f->eof, then // reset the state? but that would be slower, esp. since we'd have over 256 bytes // of state to restore (primarily the page segment table) int s = f->next_seg, first = TRUE; uint8 *p = f->stream; if (s != -1) { // if we're not starting the packet with a 'continue on next page' flag for (; s < f->segment_count; ++s) { p += f->segments[s]; if (f->segments[s] < 255) // stop at first short segment break; } // either this continues, or it ends it... if (end_page) if (s < f->segment_count-1) return error(f, VORBIS_invalid_stream); if (s == f->segment_count) s = -1; // set 'crosses page' flag if (p > f->stream_end) return error(f, VORBIS_need_more_data); first = FALSE; } for (; s == -1;) { uint8 *q; int n; // check that we have the page header ready if (p + 26 >= f->stream_end) return error(f, VORBIS_need_more_data); // validate the page if (memcmp(p, ogg_page_header, 4)) return error(f, VORBIS_invalid_stream); if (p[4] != 0) return error(f, VORBIS_invalid_stream); if (first) { // the first segment must NOT have 'continued_packet', later ones MUST if (f->previous_length) if ((p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream); // if no previous length, we're resynching, so we can come in on a continued-packet, // which we'll just drop } else { if (!(p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream); } n = p[26]; // segment counts q = p+27; // q points to segment table p = q + n; // advance past header // make sure we've read the segment table if (p > f->stream_end) return error(f, VORBIS_need_more_data); for (s=0; s < n; ++s) { p += q[s]; if (q[s] < 255) break; } if (end_page) if (s < n-1) return error(f, VORBIS_invalid_stream); if (s == n) s = -1; // set 'crosses page' flag if (p > f->stream_end) return error(f, VORBIS_need_more_data); first = FALSE; } return TRUE; } #endif // !STB_VORBIS_NO_PUSHDATA_API static int start_decoder(vorb *f) { uint8 header[6], x,y; int len,i,j,k, max_submaps = 0; int longest_floorlist=0; // first page, first packet if (!start_page(f)) return FALSE; // validate page flag if (!(f->page_flag & PAGEFLAG_first_page)) return error(f, VORBIS_invalid_first_page); if (f->page_flag & PAGEFLAG_last_page) return error(f, VORBIS_invalid_first_page); if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_invalid_first_page); // check for expected packet length if (f->segment_count != 1) return error(f, VORBIS_invalid_first_page); if (f->segments[0] != 30) { // check for the Ogg skeleton fishead identifying header to refine our error if (f->segments[0] == 64 && getn(f, header, 6) && header[0] == 'f' && header[1] == 'i' && header[2] == 's' && header[3] == 'h' && header[4] == 'e' && header[5] == 'a' && get8(f) == 'd' && get8(f) == '\0') return error(f, VORBIS_ogg_skeleton_not_supported); else return error(f, VORBIS_invalid_first_page); } // read packet // check packet header if (get8(f) != VORBIS_packet_id) return error(f, VORBIS_invalid_first_page); if (!getn(f, header, 6)) return error(f, VORBIS_unexpected_eof); if (!vorbis_validate(header)) return error(f, VORBIS_invalid_first_page); // vorbis_version if (get32(f) != 0) return error(f, VORBIS_invalid_first_page); f->channels = get8(f); if (!f->channels) return error(f, VORBIS_invalid_first_page); if (f->channels > STB_VORBIS_MAX_CHANNELS) return error(f, VORBIS_too_many_channels); f->sample_rate = get32(f); if (!f->sample_rate) return error(f, VORBIS_invalid_first_page); get32(f); // bitrate_maximum get32(f); // bitrate_nominal get32(f); // bitrate_minimum x = get8(f); { int log0,log1; log0 = x & 15; log1 = x >> 4; f->blocksize_0 = 1 << log0; f->blocksize_1 = 1 << log1; if (log0 < 6 || log0 > 13) return error(f, VORBIS_invalid_setup); if (log1 < 6 || log1 > 13) return error(f, VORBIS_invalid_setup); if (log0 > log1) return error(f, VORBIS_invalid_setup); } // framing_flag x = get8(f); if (!(x & 1)) return error(f, VORBIS_invalid_first_page); // second packet! if (!start_page(f)) return FALSE; if (!start_packet(f)) return FALSE; do { len = next_segment(f); skip(f, len); f->bytes_in_seg = 0; } while (len); // third packet! if (!start_packet(f)) return FALSE; #ifndef STB_VORBIS_NO_PUSHDATA_API if (IS_PUSH_MODE(f)) { if (!is_whole_packet_present(f, TRUE)) { // convert error in ogg header to write type if (f->error == VORBIS_invalid_stream) f->error = VORBIS_invalid_setup; return FALSE; } } #endif crc32_init(); // always init it, to avoid multithread race conditions if (get8_packet(f) != VORBIS_packet_setup) return error(f, VORBIS_invalid_setup); for (i=0; i < 6; ++i) header[i] = get8_packet(f); if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup); // codebooks f->codebook_count = get_bits(f,8) + 1; f->codebooks = (Codebook *) setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count); if (f->codebooks == NULL) return error(f, VORBIS_outofmem); memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count); for (i=0; i < f->codebook_count; ++i) { uint32 *values; int ordered, sorted_count; int total=0; uint8 *lengths; Codebook *c = f->codebooks+i; CHECK(f); x = get_bits(f, 8); if (x != 0x42) return error(f, VORBIS_invalid_setup); x = get_bits(f, 8); if (x != 0x43) return error(f, VORBIS_invalid_setup); x = get_bits(f, 8); if (x != 0x56) return error(f, VORBIS_invalid_setup); x = get_bits(f, 8); c->dimensions = (get_bits(f, 8)<<8) + x; x = get_bits(f, 8); y = get_bits(f, 8); c->entries = (get_bits(f, 8)<<16) + (y<<8) + x; ordered = get_bits(f,1); c->sparse = ordered ? 0 : get_bits(f,1); if (c->dimensions == 0 && c->entries != 0) return error(f, VORBIS_invalid_setup); if (c->sparse) lengths = (uint8 *) setup_temp_malloc(f, c->entries); else lengths = c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries); if (!lengths) return error(f, VORBIS_outofmem); if (ordered) { int current_entry = 0; int current_length = get_bits(f,5) + 1; while (current_entry < c->entries) { int limit = c->entries - current_entry; int n = get_bits(f, ilog(limit)); if (current_length >= 32) return error(f, VORBIS_invalid_setup); if (current_entry + n > (int) c->entries) { return error(f, VORBIS_invalid_setup); } memset(lengths + current_entry, current_length, n); current_entry += n; ++current_length; } } else { for (j=0; j < c->entries; ++j) { int present = c->sparse ? get_bits(f,1) : 1; if (present) { lengths[j] = get_bits(f, 5) + 1; ++total; if (lengths[j] == 32) return error(f, VORBIS_invalid_setup); } else { lengths[j] = NO_CODE; } } } if (c->sparse && total >= c->entries >> 2) { // convert sparse items to non-sparse! if (c->entries > (int) f->setup_temp_memory_required) f->setup_temp_memory_required = c->entries; c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries); if (c->codeword_lengths == NULL) return error(f, VORBIS_outofmem); memcpy(c->codeword_lengths, lengths, c->entries); setup_temp_free(f, lengths, c->entries); // note this is only safe if there have been no intervening temp mallocs! lengths = c->codeword_lengths; c->sparse = 0; } // compute the size of the sorted tables if (c->sparse) { sorted_count = total; } else { sorted_count = 0; #ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH for (j=0; j < c->entries; ++j) if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE) ++sorted_count; #endif } c->sorted_entries = sorted_count; values = NULL; CHECK(f); if (!c->sparse) { c->codewords = (uint32 *) setup_malloc(f, sizeof(c->codewords[0]) * c->entries); if (!c->codewords) return error(f, VORBIS_outofmem); } else { unsigned int size; if (c->sorted_entries) { c->codeword_lengths = (uint8 *) setup_malloc(f, c->sorted_entries); if (!c->codeword_lengths) return error(f, VORBIS_outofmem); c->codewords = (uint32 *) setup_temp_malloc(f, sizeof(*c->codewords) * c->sorted_entries); if (!c->codewords) return error(f, VORBIS_outofmem); values = (uint32 *) setup_temp_malloc(f, sizeof(*values) * c->sorted_entries); if (!values) return error(f, VORBIS_outofmem); } size = c->entries + (sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries; if (size > f->setup_temp_memory_required) f->setup_temp_memory_required = size; } if (!compute_codewords(c, lengths, c->entries, values)) { if (c->sparse) setup_temp_free(f, values, 0); return error(f, VORBIS_invalid_setup); } if (c->sorted_entries) { // allocate an extra slot for sentinels c->sorted_codewords = (uint32 *) setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries+1)); if (c->sorted_codewords == NULL) return error(f, VORBIS_outofmem); // allocate an extra slot at the front so that c->sorted_values[-1] is defined // so that we can catch that case without an extra if c->sorted_values = ( int *) setup_malloc(f, sizeof(*c->sorted_values ) * (c->sorted_entries+1)); if (c->sorted_values == NULL) return error(f, VORBIS_outofmem); ++c->sorted_values; c->sorted_values[-1] = -1; compute_sorted_huffman(c, lengths, values); } if (c->sparse) { setup_temp_free(f, values, sizeof(*values)*c->sorted_entries); setup_temp_free(f, c->codewords, sizeof(*c->codewords)*c->sorted_entries); setup_temp_free(f, lengths, c->entries); c->codewords = NULL; } compute_accelerated_huffman(c); CHECK(f); c->lookup_type = get_bits(f, 4); if (c->lookup_type > 2) return error(f, VORBIS_invalid_setup); if (c->lookup_type > 0) { uint16 *mults; c->minimum_value = float32_unpack(get_bits(f, 32)); c->delta_value = float32_unpack(get_bits(f, 32)); c->value_bits = get_bits(f, 4)+1; c->sequence_p = get_bits(f,1); if (c->lookup_type == 1) { int values = lookup1_values(c->entries, c->dimensions); if (values < 0) return error(f, VORBIS_invalid_setup); c->lookup_values = (uint32) values; } else { c->lookup_values = c->entries * c->dimensions; } if (c->lookup_values == 0) return error(f, VORBIS_invalid_setup); mults = (uint16 *) setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values); if (mults == NULL) return error(f, VORBIS_outofmem); for (j=0; j < (int) c->lookup_values; ++j) { int q = get_bits(f, c->value_bits); if (q == EOP) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); } mults[j] = q; } #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { int len, sparse = c->sparse; float last=0; // pre-expand the lookup1-style multiplicands, to avoid a divide in the inner loop if (sparse) { if (c->sorted_entries == 0) goto skip; c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions); } else c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions); if (c->multiplicands == NULL) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); } len = sparse ? c->sorted_entries : c->entries; for (j=0; j < len; ++j) { unsigned int z = sparse ? c->sorted_values[j] : j; unsigned int div=1; for (k=0; k < c->dimensions; ++k) { int off = (z / div) % c->lookup_values; float val = mults[off]; val = mults[off]*c->delta_value + c->minimum_value + last; c->multiplicands[j*c->dimensions + k] = val; if (c->sequence_p) last = val; if (k+1 < c->dimensions) { if (div > UINT_MAX / (unsigned int) c->lookup_values) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); } div *= c->lookup_values; } } } c->lookup_type = 2; } else #endif { float last=0; CHECK(f); c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values); if (c->multiplicands == NULL) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); } for (j=0; j < (int) c->lookup_values; ++j) { float val = mults[j] * c->delta_value + c->minimum_value + last; c->multiplicands[j] = val; if (c->sequence_p) last = val; } } #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK skip:; #endif setup_temp_free(f, mults, sizeof(mults[0])*c->lookup_values); CHECK(f); } CHECK(f); } // time domain transfers (notused) x = get_bits(f, 6) + 1; for (i=0; i < x; ++i) { uint32 z = get_bits(f, 16); if (z != 0) return error(f, VORBIS_invalid_setup); } // Floors f->floor_count = get_bits(f, 6)+1; f->floor_config = (Floor *) setup_malloc(f, f->floor_count * sizeof(*f->floor_config)); if (f->floor_config == NULL) return error(f, VORBIS_outofmem); for (i=0; i < f->floor_count; ++i) { f->floor_types[i] = get_bits(f, 16); if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup); if (f->floor_types[i] == 0) { Floor0 *g = &f->floor_config[i].floor0; g->order = get_bits(f,8); g->rate = get_bits(f,16); g->bark_map_size = get_bits(f,16); g->amplitude_bits = get_bits(f,6); g->amplitude_offset = get_bits(f,8); g->number_of_books = get_bits(f,4) + 1; for (j=0; j < g->number_of_books; ++j) g->book_list[j] = get_bits(f,8); return error(f, VORBIS_feature_not_supported); } else { stbv__floor_ordering p[31*8+2]; Floor1 *g = &f->floor_config[i].floor1; int max_class = -1; g->partitions = get_bits(f, 5); for (j=0; j < g->partitions; ++j) { g->partition_class_list[j] = get_bits(f, 4); if (g->partition_class_list[j] > max_class) max_class = g->partition_class_list[j]; } for (j=0; j <= max_class; ++j) { g->class_dimensions[j] = get_bits(f, 3)+1; g->class_subclasses[j] = get_bits(f, 2); if (g->class_subclasses[j]) { g->class_masterbooks[j] = get_bits(f, 8); if (g->class_masterbooks[j] >= f->codebook_count) return error(f, VORBIS_invalid_setup); } for (k=0; k < 1 << g->class_subclasses[j]; ++k) { g->subclass_books[j][k] = get_bits(f,8)-1; if (g->subclass_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup); } } g->floor1_multiplier = get_bits(f,2)+1; g->rangebits = get_bits(f,4); g->Xlist[0] = 0; g->Xlist[1] = 1 << g->rangebits; g->values = 2; for (j=0; j < g->partitions; ++j) { int c = g->partition_class_list[j]; for (k=0; k < g->class_dimensions[c]; ++k) { g->Xlist[g->values] = get_bits(f, g->rangebits); ++g->values; } } // precompute the sorting for (j=0; j < g->values; ++j) { p[j].x = g->Xlist[j]; p[j].id = j; } qsort(p, g->values, sizeof(p[0]), point_compare); for (j=0; j < g->values-1; ++j) if (p[j].x == p[j+1].x) return error(f, VORBIS_invalid_setup); for (j=0; j < g->values; ++j) g->sorted_order[j] = (uint8) p[j].id; // precompute the neighbors for (j=2; j < g->values; ++j) { int low,hi; neighbors(g->Xlist, j, &low,&hi); g->neighbors[j][0] = low; g->neighbors[j][1] = hi; } if (g->values > longest_floorlist) longest_floorlist = g->values; } } // Residue f->residue_count = get_bits(f, 6)+1; f->residue_config = (Residue *) setup_malloc(f, f->residue_count * sizeof(f->residue_config[0])); if (f->residue_config == NULL) return error(f, VORBIS_outofmem); memset(f->residue_config, 0, f->residue_count * sizeof(f->residue_config[0])); for (i=0; i < f->residue_count; ++i) { uint8 residue_cascade[64]; Residue *r = f->residue_config+i; f->residue_types[i] = get_bits(f, 16); if (f->residue_types[i] > 2) return error(f, VORBIS_invalid_setup); r->begin = get_bits(f, 24); r->end = get_bits(f, 24); if (r->end < r->begin) return error(f, VORBIS_invalid_setup); r->part_size = get_bits(f,24)+1; r->classifications = get_bits(f,6)+1; r->classbook = get_bits(f,8); if (r->classbook >= f->codebook_count) return error(f, VORBIS_invalid_setup); for (j=0; j < r->classifications; ++j) { uint8 high_bits=0; uint8 low_bits=get_bits(f,3); if (get_bits(f,1)) high_bits = get_bits(f,5); residue_cascade[j] = high_bits*8 + low_bits; } r->residue_books = (short (*)[8]) setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications); if (r->residue_books == NULL) return error(f, VORBIS_outofmem); for (j=0; j < r->classifications; ++j) { for (k=0; k < 8; ++k) { if (residue_cascade[j] & (1 << k)) { r->residue_books[j][k] = get_bits(f, 8); if (r->residue_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup); } else { r->residue_books[j][k] = -1; } } } // precompute the classifications[] array to avoid inner-loop mod/divide // call it 'classdata' since we already have r->classifications r->classdata = (uint8 **) setup_malloc(f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries); if (!r->classdata) return error(f, VORBIS_outofmem); memset(r->classdata, 0, sizeof(*r->classdata) * f->codebooks[r->classbook].entries); for (j=0; j < f->codebooks[r->classbook].entries; ++j) { int classwords = f->codebooks[r->classbook].dimensions; int temp = j; r->classdata[j] = (uint8 *) setup_malloc(f, sizeof(r->classdata[j][0]) * classwords); if (r->classdata[j] == NULL) return error(f, VORBIS_outofmem); for (k=classwords-1; k >= 0; --k) { r->classdata[j][k] = temp % r->classifications; temp /= r->classifications; } } } f->mapping_count = get_bits(f,6)+1; f->mapping = (Mapping *) setup_malloc(f, f->mapping_count * sizeof(*f->mapping)); if (f->mapping == NULL) return error(f, VORBIS_outofmem); memset(f->mapping, 0, f->mapping_count * sizeof(*f->mapping)); for (i=0; i < f->mapping_count; ++i) { Mapping *m = f->mapping + i; int mapping_type = get_bits(f,16); if (mapping_type != 0) return error(f, VORBIS_invalid_setup); m->chan = (MappingChannel *) setup_malloc(f, f->channels * sizeof(*m->chan)); if (m->chan == NULL) return error(f, VORBIS_outofmem); if (get_bits(f,1)) m->submaps = get_bits(f,4)+1; else m->submaps = 1; if (m->submaps > max_submaps) max_submaps = m->submaps; if (get_bits(f,1)) { m->coupling_steps = get_bits(f,8)+1; if (m->coupling_steps > f->channels) return error(f, VORBIS_invalid_setup); for (k=0; k < m->coupling_steps; ++k) { m->chan[k].magnitude = get_bits(f, ilog(f->channels-1)); m->chan[k].angle = get_bits(f, ilog(f->channels-1)); if (m->chan[k].magnitude >= f->channels) return error(f, VORBIS_invalid_setup); if (m->chan[k].angle >= f->channels) return error(f, VORBIS_invalid_setup); if (m->chan[k].magnitude == m->chan[k].angle) return error(f, VORBIS_invalid_setup); } } else m->coupling_steps = 0; // reserved field if (get_bits(f,2)) return error(f, VORBIS_invalid_setup); if (m->submaps > 1) { for (j=0; j < f->channels; ++j) { m->chan[j].mux = get_bits(f, 4); if (m->chan[j].mux >= m->submaps) return error(f, VORBIS_invalid_setup); } } else // @SPECIFICATION: this case is missing from the spec for (j=0; j < f->channels; ++j) m->chan[j].mux = 0; for (j=0; j < m->submaps; ++j) { get_bits(f,8); // discard m->submap_floor[j] = get_bits(f,8); m->submap_residue[j] = get_bits(f,8); if (m->submap_floor[j] >= f->floor_count) return error(f, VORBIS_invalid_setup); if (m->submap_residue[j] >= f->residue_count) return error(f, VORBIS_invalid_setup); } } // Modes f->mode_count = get_bits(f, 6)+1; for (i=0; i < f->mode_count; ++i) { Mode *m = f->mode_config+i; m->blockflag = get_bits(f,1); m->windowtype = get_bits(f,16); m->transformtype = get_bits(f,16); m->mapping = get_bits(f,8); if (m->windowtype != 0) return error(f, VORBIS_invalid_setup); if (m->transformtype != 0) return error(f, VORBIS_invalid_setup); if (m->mapping >= f->mapping_count) return error(f, VORBIS_invalid_setup); } flush_packet(f); f->previous_length = 0; for (i=0; i < f->channels; ++i) { f->channel_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1); f->previous_window[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2); f->finalY[i] = (int16 *) setup_malloc(f, sizeof(int16) * longest_floorlist); if (f->channel_buffers[i] == NULL || f->previous_window[i] == NULL || f->finalY[i] == NULL) return error(f, VORBIS_outofmem); memset(f->channel_buffers[i], 0, sizeof(float) * f->blocksize_1); #ifdef STB_VORBIS_NO_DEFER_FLOOR f->floor_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2); if (f->floor_buffers[i] == NULL) return error(f, VORBIS_outofmem); #endif } if (!init_blocksize(f, 0, f->blocksize_0)) return FALSE; if (!init_blocksize(f, 1, f->blocksize_1)) return FALSE; f->blocksize[0] = f->blocksize_0; f->blocksize[1] = f->blocksize_1; #ifdef STB_VORBIS_DIVIDE_TABLE if (integer_divide_table[1][1]==0) for (i=0; i < DIVTAB_NUMER; ++i) for (j=1; j < DIVTAB_DENOM; ++j) integer_divide_table[i][j] = i / j; #endif // compute how much temporary memory is needed // 1. { uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1); uint32 classify_mem; int i,max_part_read=0; for (i=0; i < f->residue_count; ++i) { Residue *r = f->residue_config + i; unsigned int actual_size = f->blocksize_1 / 2; unsigned int limit_r_begin = r->begin < actual_size ? r->begin : actual_size; unsigned int limit_r_end = r->end < actual_size ? r->end : actual_size; int n_read = limit_r_end - limit_r_begin; int part_read = n_read / r->part_size; if (part_read > max_part_read) max_part_read = part_read; } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(uint8 *)); #else classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int *)); #endif // maximum reasonable partition size is f->blocksize_1 f->temp_memory_required = classify_mem; if (imdct_mem > f->temp_memory_required) f->temp_memory_required = imdct_mem; } f->first_decode = TRUE; if (f->alloc.alloc_buffer) { assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes); // check if there's enough temp memory so we don't error later if (f->setup_offset + sizeof(*f) + f->temp_memory_required > (unsigned) f->temp_offset) return error(f, VORBIS_outofmem); } f->first_audio_page_offset = stb_vorbis_get_file_offset(f); return TRUE; } static void vorbis_deinit(stb_vorbis *p) { int i,j; if (p->residue_config) { for (i=0; i < p->residue_count; ++i) { Residue *r = p->residue_config+i; if (r->classdata) { for (j=0; j < p->codebooks[r->classbook].entries; ++j) setup_free(p, r->classdata[j]); setup_free(p, r->classdata); } setup_free(p, r->residue_books); } } if (p->codebooks) { CHECK(p); for (i=0; i < p->codebook_count; ++i) { Codebook *c = p->codebooks + i; setup_free(p, c->codeword_lengths); setup_free(p, c->multiplicands); setup_free(p, c->codewords); setup_free(p, c->sorted_codewords); // c->sorted_values[-1] is the first entry in the array setup_free(p, c->sorted_values ? c->sorted_values-1 : NULL); } setup_free(p, p->codebooks); } setup_free(p, p->floor_config); setup_free(p, p->residue_config); if (p->mapping) { for (i=0; i < p->mapping_count; ++i) setup_free(p, p->mapping[i].chan); setup_free(p, p->mapping); } CHECK(p); for (i=0; i < p->channels && i < STB_VORBIS_MAX_CHANNELS; ++i) { setup_free(p, p->channel_buffers[i]); setup_free(p, p->previous_window[i]); #ifdef STB_VORBIS_NO_DEFER_FLOOR setup_free(p, p->floor_buffers[i]); #endif setup_free(p, p->finalY[i]); } for (i=0; i < 2; ++i) { setup_free(p, p->A[i]); setup_free(p, p->B[i]); setup_free(p, p->C[i]); setup_free(p, p->window[i]); setup_free(p, p->bit_reverse[i]); } #ifndef STB_VORBIS_NO_STDIO if (p->close_on_free) fclose(p->f); #endif } void stb_vorbis_close(stb_vorbis *p) { if (p == NULL) return; vorbis_deinit(p); setup_free(p,p); } static void vorbis_init(stb_vorbis *p, const stb_vorbis_alloc *z) { memset(p, 0, sizeof(*p)); // NULL out all malloc'd pointers to start if (z) { p->alloc = *z; p->alloc.alloc_buffer_length_in_bytes = (p->alloc.alloc_buffer_length_in_bytes+3) & ~3; p->temp_offset = p->alloc.alloc_buffer_length_in_bytes; } p->eof = 0; p->error = VORBIS__no_error; p->stream = NULL; p->codebooks = NULL; p->page_crc_tests = -1; #ifndef STB_VORBIS_NO_STDIO p->close_on_free = FALSE; p->f = NULL; #endif } int stb_vorbis_get_sample_offset(stb_vorbis *f) { if (f->current_loc_valid) return f->current_loc; else return -1; } stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f) { stb_vorbis_info d; d.channels = f->channels; d.sample_rate = f->sample_rate; d.setup_memory_required = f->setup_memory_required; d.setup_temp_memory_required = f->setup_temp_memory_required; d.temp_memory_required = f->temp_memory_required; d.max_frame_size = f->blocksize_1 >> 1; return d; } int stb_vorbis_get_error(stb_vorbis *f) { int e = f->error; f->error = VORBIS__no_error; return e; } static stb_vorbis * vorbis_alloc(stb_vorbis *f) { stb_vorbis *p = (stb_vorbis *) setup_malloc(f, sizeof(*p)); return p; } #ifndef STB_VORBIS_NO_PUSHDATA_API void stb_vorbis_flush_pushdata(stb_vorbis *f) { f->previous_length = 0; f->page_crc_tests = 0; f->discard_samples_deferred = 0; f->current_loc_valid = FALSE; f->first_decode = FALSE; f->samples_output = 0; f->channel_buffer_start = 0; f->channel_buffer_end = 0; } static int vorbis_search_for_page_pushdata(vorb *f, uint8 *data, int data_len) { int i,n; for (i=0; i < f->page_crc_tests; ++i) f->scan[i].bytes_done = 0; // if we have room for more scans, search for them first, because // they may cause us to stop early if their header is incomplete if (f->page_crc_tests < STB_VORBIS_PUSHDATA_CRC_COUNT) { if (data_len < 4) return 0; data_len -= 3; // need to look for 4-byte sequence, so don't miss // one that straddles a boundary for (i=0; i < data_len; ++i) { if (data[i] == 0x4f) { if (0==memcmp(data+i, ogg_page_header, 4)) { int j,len; uint32 crc; // make sure we have the whole page header if (i+26 >= data_len || i+27+data[i+26] >= data_len) { // only read up to this page start, so hopefully we'll // have the whole page header start next time data_len = i; break; } // ok, we have it all; compute the length of the page len = 27 + data[i+26]; for (j=0; j < data[i+26]; ++j) len += data[i+27+j]; // scan everything up to the embedded crc (which we must 0) crc = 0; for (j=0; j < 22; ++j) crc = crc32_update(crc, data[i+j]); // now process 4 0-bytes for ( ; j < 26; ++j) crc = crc32_update(crc, 0); // len is the total number of bytes we need to scan n = f->page_crc_tests++; f->scan[n].bytes_left = len-j; f->scan[n].crc_so_far = crc; f->scan[n].goal_crc = data[i+22] + (data[i+23] << 8) + (data[i+24]<<16) + (data[i+25]<<24); // if the last frame on a page is continued to the next, then // we can't recover the sample_loc immediately if (data[i+27+data[i+26]-1] == 255) f->scan[n].sample_loc = ~0; else f->scan[n].sample_loc = data[i+6] + (data[i+7] << 8) + (data[i+ 8]<<16) + (data[i+ 9]<<24); f->scan[n].bytes_done = i+j; if (f->page_crc_tests == STB_VORBIS_PUSHDATA_CRC_COUNT) break; // keep going if we still have room for more } } } } for (i=0; i < f->page_crc_tests;) { uint32 crc; int j; int n = f->scan[i].bytes_done; int m = f->scan[i].bytes_left; if (m > data_len - n) m = data_len - n; // m is the bytes to scan in the current chunk crc = f->scan[i].crc_so_far; for (j=0; j < m; ++j) crc = crc32_update(crc, data[n+j]); f->scan[i].bytes_left -= m; f->scan[i].crc_so_far = crc; if (f->scan[i].bytes_left == 0) { // does it match? if (f->scan[i].crc_so_far == f->scan[i].goal_crc) { // Houston, we have page data_len = n+m; // consumption amount is wherever that scan ended f->page_crc_tests = -1; // drop out of page scan mode f->previous_length = 0; // decode-but-don't-output one frame f->next_seg = -1; // start a new page f->current_loc = f->scan[i].sample_loc; // set the current sample location // to the amount we'd have decoded had we decoded this page f->current_loc_valid = f->current_loc != ~0U; return data_len; } // delete entry f->scan[i] = f->scan[--f->page_crc_tests]; } else { ++i; } } return data_len; } // return value: number of bytes we used int stb_vorbis_decode_frame_pushdata( stb_vorbis *f, // the file we're decoding const uint8 *data, int data_len, // the memory available for decoding int *channels, // place to write number of float * buffers float ***output, // place to write float ** array of float * buffers int *samples // place to write number of output samples ) { int i; int len,right,left; if (!IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); if (f->page_crc_tests >= 0) { *samples = 0; return vorbis_search_for_page_pushdata(f, (uint8 *) data, data_len); } f->stream = (uint8 *) data; f->stream_end = (uint8 *) data + data_len; f->error = VORBIS__no_error; // check that we have the entire packet in memory if (!is_whole_packet_present(f, FALSE)) { *samples = 0; return 0; } if (!vorbis_decode_packet(f, &len, &left, &right)) { // save the actual error we encountered enum STBVorbisError error = f->error; if (error == VORBIS_bad_packet_type) { // flush and resynch f->error = VORBIS__no_error; while (get8_packet(f) != EOP) if (f->eof) break; *samples = 0; return (int) (f->stream - data); } if (error == VORBIS_continued_packet_flag_invalid) { if (f->previous_length == 0) { // we may be resynching, in which case it's ok to hit one // of these; just discard the packet f->error = VORBIS__no_error; while (get8_packet(f) != EOP) if (f->eof) break; *samples = 0; return (int) (f->stream - data); } } // if we get an error while parsing, what to do? // well, it DEFINITELY won't work to continue from where we are! stb_vorbis_flush_pushdata(f); // restore the error that actually made us bail f->error = error; *samples = 0; return 1; } // success! len = vorbis_finish_frame(f, len, left, right); for (i=0; i < f->channels; ++i) f->outputs[i] = f->channel_buffers[i] + left; if (channels) *channels = f->channels; *samples = len; *output = f->outputs; return (int) (f->stream - data); } stb_vorbis *stb_vorbis_open_pushdata( const unsigned char *data, int data_len, // the memory available for decoding int *data_used, // only defined if result is not NULL int *error, const stb_vorbis_alloc *alloc) { stb_vorbis *f, p; vorbis_init(&p, alloc); p.stream = (uint8 *) data; p.stream_end = (uint8 *) data + data_len; p.push_mode = TRUE; if (!start_decoder(&p)) { if (p.eof) *error = VORBIS_need_more_data; else *error = p.error; return NULL; } f = vorbis_alloc(&p); if (f) { *f = p; *data_used = (int) (f->stream - data); *error = 0; return f; } else { vorbis_deinit(&p); return NULL; } } #endif // STB_VORBIS_NO_PUSHDATA_API unsigned int stb_vorbis_get_file_offset(stb_vorbis *f) { #ifndef STB_VORBIS_NO_PUSHDATA_API if (f->push_mode) return 0; #endif if (USE_MEMORY(f)) return (unsigned int) (f->stream - f->stream_start); #ifndef STB_VORBIS_NO_STDIO return (unsigned int) (ftell(f->f) - f->f_start); #endif } #ifndef STB_VORBIS_NO_PULLDATA_API // // DATA-PULLING API // static uint32 vorbis_find_page(stb_vorbis *f, uint32 *end, uint32 *last) { for(;;) { int n; if (f->eof) return 0; n = get8(f); if (n == 0x4f) { // page header candidate unsigned int retry_loc = stb_vorbis_get_file_offset(f); int i; // check if we're off the end of a file_section stream if (retry_loc - 25 > f->stream_len) return 0; // check the rest of the header for (i=1; i < 4; ++i) if (get8(f) != ogg_page_header[i]) break; if (f->eof) return 0; if (i == 4) { uint8 header[27]; uint32 i, crc, goal, len; for (i=0; i < 4; ++i) header[i] = ogg_page_header[i]; for (; i < 27; ++i) header[i] = get8(f); if (f->eof) return 0; if (header[4] != 0) goto invalid; goal = header[22] + (header[23] << 8) + (header[24]<<16) + (header[25]<<24); for (i=22; i < 26; ++i) header[i] = 0; crc = 0; for (i=0; i < 27; ++i) crc = crc32_update(crc, header[i]); len = 0; for (i=0; i < header[26]; ++i) { int s = get8(f); crc = crc32_update(crc, s); len += s; } if (len && f->eof) return 0; for (i=0; i < len; ++i) crc = crc32_update(crc, get8(f)); // finished parsing probable page if (crc == goal) { // we could now check that it's either got the last // page flag set, OR it's followed by the capture // pattern, but I guess TECHNICALLY you could have // a file with garbage between each ogg page and recover // from it automatically? So even though that paranoia // might decrease the chance of an invalid decode by // another 2^32, not worth it since it would hose those // invalid-but-useful files? if (end) *end = stb_vorbis_get_file_offset(f); if (last) { if (header[5] & 0x04) *last = 1; else *last = 0; } set_file_offset(f, retry_loc-1); return 1; } } invalid: // not a valid page, so rewind and look for next one set_file_offset(f, retry_loc); } } } #define SAMPLE_unknown 0xffffffff // seeking is implemented with a binary search, which narrows down the range to // 64K, before using a linear search (because finding the synchronization // pattern can be expensive, and the chance we'd find the end page again is // relatively high for small ranges) // // two initial interpolation-style probes are used at the start of the search // to try to bound either side of the binary search sensibly, while still // working in O(log n) time if they fail. static int get_seek_page_info(stb_vorbis *f, ProbedPage *z) { uint8 header[27], lacing[255]; int i,len; // record where the page starts z->page_start = stb_vorbis_get_file_offset(f); // parse the header getn(f, header, 27); if (header[0] != 'O' || header[1] != 'g' || header[2] != 'g' || header[3] != 'S') return 0; getn(f, lacing, header[26]); // determine the length of the payload len = 0; for (i=0; i < header[26]; ++i) len += lacing[i]; // this implies where the page ends z->page_end = z->page_start + 27 + header[26] + len; // read the last-decoded sample out of the data z->last_decoded_sample = header[6] + (header[7] << 8) + (header[8] << 16) + (header[9] << 24); // restore file state to where we were set_file_offset(f, z->page_start); return 1; } // rarely used function to seek back to the preceding page while finding the // start of a packet static int go_to_page_before(stb_vorbis *f, unsigned int limit_offset) { unsigned int previous_safe, end; // now we want to seek back 64K from the limit if (limit_offset >= 65536 && limit_offset-65536 >= f->first_audio_page_offset) previous_safe = limit_offset - 65536; else previous_safe = f->first_audio_page_offset; set_file_offset(f, previous_safe); while (vorbis_find_page(f, &end, NULL)) { if (end >= limit_offset && stb_vorbis_get_file_offset(f) < limit_offset) return 1; set_file_offset(f, end); } return 0; } // implements the search logic for finding a page and starting decoding. if // the function succeeds, current_loc_valid will be true and current_loc will // be less than or equal to the provided sample number (the closer the // better). static int seek_to_sample_coarse(stb_vorbis *f, uint32 sample_number) { ProbedPage left, right, mid; int i, start_seg_with_known_loc, end_pos, page_start; uint32 delta, stream_length, padding; double offset, bytes_per_sample; int probe = 0; // find the last page and validate the target sample stream_length = stb_vorbis_stream_length_in_samples(f); if (stream_length == 0) return error(f, VORBIS_seek_without_length); if (sample_number > stream_length) return error(f, VORBIS_seek_invalid); // this is the maximum difference between the window-center (which is the // actual granule position value), and the right-start (which the spec // indicates should be the granule position (give or take one)). padding = ((f->blocksize_1 - f->blocksize_0) >> 2); if (sample_number < padding) sample_number = 0; else sample_number -= padding; left = f->p_first; while (left.last_decoded_sample == ~0U) { // (untested) the first page does not have a 'last_decoded_sample' set_file_offset(f, left.page_end); if (!get_seek_page_info(f, &left)) goto error; } right = f->p_last; assert(right.last_decoded_sample != ~0U); // starting from the start is handled differently if (sample_number <= left.last_decoded_sample) { if (stb_vorbis_seek_start(f)) return 1; return 0; } while (left.page_end != right.page_start) { assert(left.page_end < right.page_start); // search range in bytes delta = right.page_start - left.page_end; if (delta <= 65536) { // there's only 64K left to search - handle it linearly set_file_offset(f, left.page_end); } else { if (probe < 2) { if (probe == 0) { // first probe (interpolate) double data_bytes = right.page_end - left.page_start; bytes_per_sample = data_bytes / right.last_decoded_sample; offset = left.page_start + bytes_per_sample * (sample_number - left.last_decoded_sample); } else { // second probe (try to bound the other side) double error = ((double) sample_number - mid.last_decoded_sample) * bytes_per_sample; if (error >= 0 && error < 8000) error = 8000; if (error < 0 && error > -8000) error = -8000; offset += error * 2; } // ensure the offset is valid if (offset < left.page_end) offset = left.page_end; if (offset > right.page_start - 65536) offset = right.page_start - 65536; set_file_offset(f, (unsigned int) offset); } else { // binary search for large ranges (offset by 32K to ensure // we don't hit the right page) set_file_offset(f, left.page_end + (delta / 2) - 32768); } if (!vorbis_find_page(f, NULL, NULL)) goto error; } for (;;) { if (!get_seek_page_info(f, &mid)) goto error; if (mid.last_decoded_sample != ~0U) break; // (untested) no frames end on this page set_file_offset(f, mid.page_end); assert(mid.page_start < right.page_start); } // if we've just found the last page again then we're in a tricky file, // and we're close enough. if (mid.page_start == right.page_start) break; if (sample_number < mid.last_decoded_sample) right = mid; else left = mid; ++probe; } // seek back to start of the last packet page_start = left.page_start; set_file_offset(f, page_start); if (!start_page(f)) return error(f, VORBIS_seek_failed); end_pos = f->end_seg_with_known_loc; assert(end_pos >= 0); for (;;) { for (i = end_pos; i > 0; --i) if (f->segments[i-1] != 255) break; start_seg_with_known_loc = i; if (start_seg_with_known_loc > 0 || !(f->page_flag & PAGEFLAG_continued_packet)) break; // (untested) the final packet begins on an earlier page if (!go_to_page_before(f, page_start)) goto error; page_start = stb_vorbis_get_file_offset(f); if (!start_page(f)) goto error; end_pos = f->segment_count - 1; } // prepare to start decoding f->current_loc_valid = FALSE; f->last_seg = FALSE; f->valid_bits = 0; f->packet_bytes = 0; f->bytes_in_seg = 0; f->previous_length = 0; f->next_seg = start_seg_with_known_loc; for (i = 0; i < start_seg_with_known_loc; i++) skip(f, f->segments[i]); // start decoding (optimizable - this frame is generally discarded) if (!vorbis_pump_first_frame(f)) return 0; if (f->current_loc > sample_number) return error(f, VORBIS_seek_failed); return 1; error: // try to restore the file to a valid state stb_vorbis_seek_start(f); return error(f, VORBIS_seek_failed); } // the same as vorbis_decode_initial, but without advancing static int peek_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode) { int bits_read, bytes_read; if (!vorbis_decode_initial(f, p_left_start, p_left_end, p_right_start, p_right_end, mode)) return 0; // either 1 or 2 bytes were read, figure out which so we can rewind bits_read = 1 + ilog(f->mode_count-1); if (f->mode_config[*mode].blockflag) bits_read += 2; bytes_read = (bits_read + 7) / 8; f->bytes_in_seg += bytes_read; f->packet_bytes -= bytes_read; skip(f, -bytes_read); if (f->next_seg == -1) f->next_seg = f->segment_count - 1; else f->next_seg--; f->valid_bits = 0; return 1; } int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number) { uint32 max_frame_samples; if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); // fast page-level search if (!seek_to_sample_coarse(f, sample_number)) return 0; assert(f->current_loc_valid); assert(f->current_loc <= sample_number); // linear search for the relevant packet max_frame_samples = (f->blocksize_1*3 - f->blocksize_0) >> 2; while (f->current_loc < sample_number) { int left_start, left_end, right_start, right_end, mode, frame_samples; if (!peek_decode_initial(f, &left_start, &left_end, &right_start, &right_end, &mode)) return error(f, VORBIS_seek_failed); // calculate the number of samples returned by the next frame frame_samples = right_start - left_start; if (f->current_loc + frame_samples > sample_number) { return 1; // the next frame will contain the sample } else if (f->current_loc + frame_samples + max_frame_samples > sample_number) { // there's a chance the frame after this could contain the sample vorbis_pump_first_frame(f); } else { // this frame is too early to be relevant f->current_loc += frame_samples; f->previous_length = 0; maybe_start_packet(f); flush_packet(f); } } // the next frame will start with the sample assert(f->current_loc == sample_number); return 1; } int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number) { if (!stb_vorbis_seek_frame(f, sample_number)) return 0; if (sample_number != f->current_loc) { int n; uint32 frame_start = f->current_loc; stb_vorbis_get_frame_float(f, &n, NULL); assert(sample_number > frame_start); assert(f->channel_buffer_start + (int) (sample_number-frame_start) <= f->channel_buffer_end); f->channel_buffer_start += (sample_number - frame_start); } return 1; } int stb_vorbis_seek_start(stb_vorbis *f) { if (IS_PUSH_MODE(f)) { return error(f, VORBIS_invalid_api_mixing); } set_file_offset(f, f->first_audio_page_offset); f->previous_length = 0; f->first_decode = TRUE; f->next_seg = -1; return vorbis_pump_first_frame(f); } unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f) { unsigned int restore_offset, previous_safe; unsigned int end, last_page_loc; if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); if (!f->total_samples) { unsigned int last; uint32 lo,hi; char header[6]; // first, store the current decode position so we can restore it restore_offset = stb_vorbis_get_file_offset(f); // now we want to seek back 64K from the end (the last page must // be at most a little less than 64K, but let's allow a little slop) if (f->stream_len >= 65536 && f->stream_len-65536 >= f->first_audio_page_offset) previous_safe = f->stream_len - 65536; else previous_safe = f->first_audio_page_offset; set_file_offset(f, previous_safe); // previous_safe is now our candidate 'earliest known place that seeking // to will lead to the final page' if (!vorbis_find_page(f, &end, &last)) { // if we can't find a page, we're hosed! f->error = VORBIS_cant_find_last_page; f->total_samples = 0xffffffff; goto done; } // check if there are more pages last_page_loc = stb_vorbis_get_file_offset(f); // stop when the last_page flag is set, not when we reach eof; // this allows us to stop short of a 'file_section' end without // explicitly checking the length of the section while (!last) { set_file_offset(f, end); if (!vorbis_find_page(f, &end, &last)) { // the last page we found didn't have the 'last page' flag // set. whoops! break; } previous_safe = last_page_loc+1; last_page_loc = stb_vorbis_get_file_offset(f); } set_file_offset(f, last_page_loc); // parse the header getn(f, (unsigned char *)header, 6); // extract the absolute granule position lo = get32(f); hi = get32(f); if (lo == 0xffffffff && hi == 0xffffffff) { f->error = VORBIS_cant_find_last_page; f->total_samples = SAMPLE_unknown; goto done; } if (hi) lo = 0xfffffffe; // saturate f->total_samples = lo; f->p_last.page_start = last_page_loc; f->p_last.page_end = end; f->p_last.last_decoded_sample = lo; done: set_file_offset(f, restore_offset); } return f->total_samples == SAMPLE_unknown ? 0 : f->total_samples; } float stb_vorbis_stream_length_in_seconds(stb_vorbis *f) { return stb_vorbis_stream_length_in_samples(f) / (float) f->sample_rate; } int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output) { int len, right,left,i; if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); if (!vorbis_decode_packet(f, &len, &left, &right)) { f->channel_buffer_start = f->channel_buffer_end = 0; return 0; } len = vorbis_finish_frame(f, len, left, right); for (i=0; i < f->channels; ++i) f->outputs[i] = f->channel_buffers[i] + left; f->channel_buffer_start = left; f->channel_buffer_end = left+len; if (channels) *channels = f->channels; if (output) *output = f->outputs; return len; } #ifndef STB_VORBIS_NO_STDIO stb_vorbis * stb_vorbis_open_file_section(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc, unsigned int length) { stb_vorbis *f, p; vorbis_init(&p, alloc); p.f = file; p.f_start = (uint32) ftell(file); p.stream_len = length; p.close_on_free = close_on_free; if (start_decoder(&p)) { f = vorbis_alloc(&p); if (f) { *f = p; vorbis_pump_first_frame(f); return f; } } if (error) *error = p.error; vorbis_deinit(&p); return NULL; } stb_vorbis * stb_vorbis_open_file(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc) { unsigned int len, start; start = (unsigned int) ftell(file); fseek(file, 0, SEEK_END); len = (unsigned int) (ftell(file) - start); fseek(file, start, SEEK_SET); return stb_vorbis_open_file_section(file, close_on_free, error, alloc, len); } stb_vorbis * stb_vorbis_open_filename(const char *filename, int *error, const stb_vorbis_alloc *alloc) { FILE *f; #if defined(_WIN32) && defined(__STDC_WANT_SECURE_LIB__) if (0 != fopen_s(&f, filename, "rb")) f = NULL; #else f = fopen(filename, "rb"); #endif if (f) return stb_vorbis_open_file(f, TRUE, error, alloc); if (error) *error = VORBIS_file_open_failure; return NULL; } #endif // STB_VORBIS_NO_STDIO stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, int *error, const stb_vorbis_alloc *alloc) { stb_vorbis *f, p; if (data == NULL) return NULL; vorbis_init(&p, alloc); p.stream = (uint8 *) data; p.stream_end = (uint8 *) data + len; p.stream_start = (uint8 *) p.stream; p.stream_len = len; p.push_mode = FALSE; if (start_decoder(&p)) { f = vorbis_alloc(&p); if (f) { *f = p; vorbis_pump_first_frame(f); if (error) *error = VORBIS__no_error; return f; } } if (error) *error = p.error; vorbis_deinit(&p); return NULL; } #ifndef STB_VORBIS_NO_INTEGER_CONVERSION #define PLAYBACK_MONO 1 #define PLAYBACK_LEFT 2 #define PLAYBACK_RIGHT 4 #define L (PLAYBACK_LEFT | PLAYBACK_MONO) #define C (PLAYBACK_LEFT | PLAYBACK_RIGHT | PLAYBACK_MONO) #define R (PLAYBACK_RIGHT | PLAYBACK_MONO) static int8 channel_position[7][6] = { { 0 }, { C }, { L, R }, { L, C, R }, { L, R, L, R }, { L, C, R, L, R }, { L, C, R, L, R, C }, }; #ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT typedef union { float f; int i; } float_conv; typedef char stb_vorbis_float_size_test[sizeof(float)==4 && sizeof(int) == 4]; #define FASTDEF(x) float_conv x // add (1<<23) to convert to int, then divide by 2^SHIFT, then add 0.5/2^SHIFT to round #define MAGIC(SHIFT) (1.5f * (1 << (23-SHIFT)) + 0.5f/(1 << SHIFT)) #define ADDEND(SHIFT) (((150-SHIFT) << 23) + (1 << 22)) #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) (temp.f = (x) + MAGIC(s), temp.i - ADDEND(s)) #define check_endianness() #else #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) ((int) ((x) * (1 << (s)))) #define check_endianness() #define FASTDEF(x) #endif static void copy_samples(short *dest, float *src, int len) { int i; check_endianness(); for (i=0; i < len; ++i) { FASTDEF(temp); int v = FAST_SCALED_FLOAT_TO_INT(temp, src[i],15); if ((unsigned int) (v + 32768) > 65535) v = v < 0 ? -32768 : 32767; dest[i] = v; } } static void compute_samples(int mask, short *output, int num_c, float **data, int d_offset, int len) { #define BUFFER_SIZE 32 float buffer[BUFFER_SIZE]; int i,j,o,n = BUFFER_SIZE; check_endianness(); for (o = 0; o < len; o += BUFFER_SIZE) { memset(buffer, 0, sizeof(buffer)); if (o + n > len) n = len - o; for (j=0; j < num_c; ++j) { if (channel_position[num_c][j] & mask) { for (i=0; i < n; ++i) buffer[i] += data[j][d_offset+o+i]; } } for (i=0; i < n; ++i) { FASTDEF(temp); int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15); if ((unsigned int) (v + 32768) > 65535) v = v < 0 ? -32768 : 32767; output[o+i] = v; } } } static void compute_stereo_samples(short *output, int num_c, float **data, int d_offset, int len) { #define BUFFER_SIZE 32 float buffer[BUFFER_SIZE]; int i,j,o,n = BUFFER_SIZE >> 1; // o is the offset in the source data check_endianness(); for (o = 0; o < len; o += BUFFER_SIZE >> 1) { // o2 is the offset in the output data int o2 = o << 1; memset(buffer, 0, sizeof(buffer)); if (o + n > len) n = len - o; for (j=0; j < num_c; ++j) { int m = channel_position[num_c][j] & (PLAYBACK_LEFT | PLAYBACK_RIGHT); if (m == (PLAYBACK_LEFT | PLAYBACK_RIGHT)) { for (i=0; i < n; ++i) { buffer[i*2+0] += data[j][d_offset+o+i]; buffer[i*2+1] += data[j][d_offset+o+i]; } } else if (m == PLAYBACK_LEFT) { for (i=0; i < n; ++i) { buffer[i*2+0] += data[j][d_offset+o+i]; } } else if (m == PLAYBACK_RIGHT) { for (i=0; i < n; ++i) { buffer[i*2+1] += data[j][d_offset+o+i]; } } } for (i=0; i < (n<<1); ++i) { FASTDEF(temp); int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15); if ((unsigned int) (v + 32768) > 65535) v = v < 0 ? -32768 : 32767; output[o2+i] = v; } } } static void convert_samples_short(int buf_c, short **buffer, int b_offset, int data_c, float **data, int d_offset, int samples) { int i; if (buf_c != data_c && buf_c <= 2 && data_c <= 6) { static int channel_selector[3][2] = { {0}, {PLAYBACK_MONO}, {PLAYBACK_LEFT, PLAYBACK_RIGHT} }; for (i=0; i < buf_c; ++i) compute_samples(channel_selector[buf_c][i], buffer[i]+b_offset, data_c, data, d_offset, samples); } else { int limit = buf_c < data_c ? buf_c : data_c; for (i=0; i < limit; ++i) copy_samples(buffer[i]+b_offset, data[i]+d_offset, samples); for ( ; i < buf_c; ++i) memset(buffer[i]+b_offset, 0, sizeof(short) * samples); } } int stb_vorbis_get_frame_short(stb_vorbis *f, int num_c, short **buffer, int num_samples) { float **output; int len = stb_vorbis_get_frame_float(f, NULL, &output); if (len > num_samples) len = num_samples; if (len) convert_samples_short(num_c, buffer, 0, f->channels, output, 0, len); return len; } static void convert_channels_short_interleaved(int buf_c, short *buffer, int data_c, float **data, int d_offset, int len) { int i; check_endianness(); if (buf_c != data_c && buf_c <= 2 && data_c <= 6) { assert(buf_c == 2); for (i=0; i < buf_c; ++i) compute_stereo_samples(buffer, data_c, data, d_offset, len); } else { int limit = buf_c < data_c ? buf_c : data_c; int j; for (j=0; j < len; ++j) { for (i=0; i < limit; ++i) { FASTDEF(temp); float f = data[i][d_offset+j]; int v = FAST_SCALED_FLOAT_TO_INT(temp, f,15);//data[i][d_offset+j],15); if ((unsigned int) (v + 32768) > 65535) v = v < 0 ? -32768 : 32767; *buffer++ = v; } for ( ; i < buf_c; ++i) *buffer++ = 0; } } } int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts) { float **output; int len; if (num_c == 1) return stb_vorbis_get_frame_short(f,num_c,&buffer, num_shorts); len = stb_vorbis_get_frame_float(f, NULL, &output); if (len) { if (len*num_c > num_shorts) len = num_shorts / num_c; convert_channels_short_interleaved(num_c, buffer, f->channels, output, 0, len); } return len; } int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts) { float **outputs; int len = num_shorts / channels; int n=0; int z = f->channels; if (z > channels) z = channels; while (n < len) { int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= len) k = len - n; if (k) convert_channels_short_interleaved(channels, buffer, f->channels, f->channel_buffers, f->channel_buffer_start, k); buffer += k*channels; n += k; f->channel_buffer_start += k; if (n == len) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int len) { float **outputs; int n=0; int z = f->channels; if (z > channels) z = channels; while (n < len) { int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= len) k = len - n; if (k) convert_samples_short(channels, buffer, n, f->channels, f->channel_buffers, f->channel_buffer_start, k); n += k; f->channel_buffer_start += k; if (n == len) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } #ifndef STB_VORBIS_NO_STDIO int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output) { int data_len, offset, total, limit, error; short *data; stb_vorbis *v = stb_vorbis_open_filename(filename, &error, NULL); if (v == NULL) return -1; limit = v->channels * 4096; *channels = v->channels; if (sample_rate) *sample_rate = v->sample_rate; offset = data_len = 0; total = limit; data = (short *) malloc(total * sizeof(*data)); if (data == NULL) { stb_vorbis_close(v); return -2; } for (;;) { int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset); if (n == 0) break; data_len += n; offset += n * v->channels; if (offset + limit > total) { short *data2; total *= 2; data2 = (short *) realloc(data, total * sizeof(*data)); if (data2 == NULL) { free(data); stb_vorbis_close(v); return -2; } data = data2; } } *output = data; stb_vorbis_close(v); return data_len; } #endif // NO_STDIO int stb_vorbis_decode_memory(const uint8 *mem, int len, int *channels, int *sample_rate, short **output) { int data_len, offset, total, limit, error; short *data; stb_vorbis *v = stb_vorbis_open_memory(mem, len, &error, NULL); if (v == NULL) return -1; limit = v->channels * 4096; *channels = v->channels; if (sample_rate) *sample_rate = v->sample_rate; offset = data_len = 0; total = limit; data = (short *) malloc(total * sizeof(*data)); if (data == NULL) { stb_vorbis_close(v); return -2; } for (;;) { int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset); if (n == 0) break; data_len += n; offset += n * v->channels; if (offset + limit > total) { short *data2; total *= 2; data2 = (short *) realloc(data, total * sizeof(*data)); if (data2 == NULL) { free(data); stb_vorbis_close(v); return -2; } data = data2; } } *output = data; stb_vorbis_close(v); return data_len; } #endif // STB_VORBIS_NO_INTEGER_CONVERSION int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats) { float **outputs; int len = num_floats / channels; int n=0; int z = f->channels; if (z > channels) z = channels; while (n < len) { int i,j; int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= len) k = len - n; for (j=0; j < k; ++j) { for (i=0; i < z; ++i) *buffer++ = f->channel_buffers[i][f->channel_buffer_start+j]; for ( ; i < channels; ++i) *buffer++ = 0; } n += k; f->channel_buffer_start += k; if (n == len) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples) { float **outputs; int n=0; int z = f->channels; if (z > channels) z = channels; while (n < num_samples) { int i; int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= num_samples) k = num_samples - n; if (k) { for (i=0; i < z; ++i) memcpy(buffer[i]+n, f->channel_buffers[i]+f->channel_buffer_start, sizeof(float)*k); for ( ; i < channels; ++i) memset(buffer[i]+n, 0, sizeof(float) * k); } n += k; f->channel_buffer_start += k; if (n == num_samples) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } #endif // STB_VORBIS_NO_PULLDATA_API /* Version history 1.17 - 2019-07-08 - fix CVE-2019-13217, -13218, -13219, -13220, -13221, -13223, -13223 found with Mayhem by ForAllSecure 1.16 - 2019-03-04 - fix warnings 1.15 - 2019-02-07 - explicit failure if Ogg Skeleton data is found 1.14 - 2018-02-11 - delete bogus dealloca usage 1.13 - 2018-01-29 - fix truncation of last frame (hopefully) 1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files 1.11 - 2017-07-23 - fix MinGW compilation 1.10 - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory 1.09 - 2016-04-04 - back out 'avoid discarding last frame' fix from previous version 1.08 - 2016-04-02 - fixed multiple warnings; fix setup memory leaks; avoid discarding last frame of audio data 1.07 - 2015-01-16 - fixed some warnings, fix mingw, const-correct API some more crash fixes when out of memory or with corrupt files 1.06 - 2015-08-31 - full, correct support for seeking API (Dougall Johnson) some crash fixes when out of memory or with corrupt files 1.05 - 2015-04-19 - don't define __forceinline if it's redundant 1.04 - 2014-08-27 - fix missing const-correct case in API 1.03 - 2014-08-07 - Warning fixes 1.02 - 2014-07-09 - Declare qsort compare function _cdecl on windows 1.01 - 2014-06-18 - fix stb_vorbis_get_samples_float 1.0 - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in multichannel (API change) report sample rate for decode-full-file funcs 0.99996 - bracket #include <malloc.h> for macintosh compilation by Laurent Gomila 0.99995 - use union instead of pointer-cast for fast-float-to-int to avoid alias-optimization problem 0.99994 - change fast-float-to-int to work in single-precision FPU mode, remove endian-dependence 0.99993 - remove assert that fired on legal files with empty tables 0.99992 - rewind-to-start 0.99991 - bugfix to stb_vorbis_get_samples_short by Bernhard Wodo 0.9999 - (should have been 0.99990) fix no-CRT support, compiling as C++ 0.9998 - add a full-decode function with a memory source 0.9997 - fix a bug in the read-from-FILE case in 0.9996 addition 0.9996 - query length of vorbis stream in samples/seconds 0.9995 - bugfix to another optimization that only happened in certain files 0.9994 - bugfix to one of the optimizations that caused significant (but inaudible?) errors 0.9993 - performance improvements; runs in 99% to 104% of time of reference implementation 0.9992 - performance improvement of IMDCT; now performs close to reference implementation 0.9991 - performance improvement of IMDCT 0.999 - (should have been 0.9990) performance improvement of IMDCT 0.998 - no-CRT support from Casey Muratori 0.997 - bugfixes for bugs found by Terje Mathisen 0.996 - bugfix: fast-huffman decode initialized incorrectly for sparse codebooks; fixing gives 10% speedup - found by Terje Mathisen 0.995 - bugfix: fix to 'effective' overrun detection - found by Terje Mathisen 0.994 - bugfix: garbage decode on final VQ symbol of a non-multiple - found by Terje Mathisen 0.993 - bugfix: pushdata API required 1 extra byte for empty page (failed to consume final page if empty) - found by Terje Mathisen 0.992 - fixes for MinGW warning 0.991 - turn fast-float-conversion on by default 0.990 - fix push-mode seek recovery if you seek into the headers 0.98b - fix to bad release of 0.98 0.98 - fix push-mode seek recovery; robustify float-to-int and support non-fast mode 0.97 - builds under c++ (typecasting, don't use 'class' keyword) 0.96 - somehow MY 0.95 was right, but the web one was wrong, so here's my 0.95 rereleased as 0.96, fixes a typo in the clamping code 0.95 - clamping code for 16-bit functions 0.94 - not publically released 0.93 - fixed all-zero-floor case (was decoding garbage) 0.92 - fixed a memory leak 0.91 - conditional compiles to omit parts of the API and the infrastructure to support them: STB_VORBIS_NO_PULLDATA_API, STB_VORBIS_NO_PUSHDATA_API, STB_VORBIS_NO_STDIO, STB_VORBIS_NO_INTEGER_CONVERSION 0.90 - first public release */ #endif // STB_VORBIS_HEADER_ONLY /* ------------------------------------------------------------------------------ This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------ ALTERNATIVE A - MIT License Copyright (c) 2017 Sean Barrett Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ ALTERNATIVE B - Public Domain (www.unlicense.org) This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ */
null
123
CWE-787
CVE-2019-13298
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % EEEEE N N H H AAA N N CCCC EEEEE % % E NN N H H A A NN N C E % % EEE N N N HHHHH AAAAA N N N C EEE % % E N NN H H A A N NN C E % % EEEEE N N H H A A N N CCCC EEEEE % % % % % % MagickCore Image Enhancement Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/accelerate-private.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite-private.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/fx.h" #include "MagickCore/gem.h" #include "MagickCore/gem-private.h" #include "MagickCore/geometry.h" #include "MagickCore/histogram.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resample.h" #include "MagickCore/resample-private.h" #include "MagickCore/resource_.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/threshold.h" #include "MagickCore/token.h" #include "MagickCore/xml-tree.h" #include "MagickCore/xml-tree-private.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A u t o G a m m a I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AutoGammaImage() extract the 'mean' from the image and adjust the image % to try make set its gamma appropriatally. % % The format of the AutoGammaImage method is: % % MagickBooleanType AutoGammaImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image to auto-level % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType AutoGammaImage(Image *image, ExceptionInfo *exception) { double gamma, log_mean, mean, sans; MagickStatusType status; register ssize_t i; log_mean=log(0.5); if (image->channel_mask == DefaultChannels) { /* Apply gamma correction equally across all given channels. */ (void) GetImageMean(image,&mean,&sans,exception); gamma=log(mean*QuantumScale)/log_mean; return(LevelImage(image,0.0,(double) QuantumRange,gamma,exception)); } /* Auto-gamma each channel separately. */ status=MagickTrue; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { ChannelType channel_mask; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; channel_mask=SetImageChannelMask(image,(ChannelType) (1UL << i)); status=GetImageMean(image,&mean,&sans,exception); gamma=log(mean*QuantumScale)/log_mean; status&=LevelImage(image,0.0,(double) QuantumRange,gamma,exception); (void) SetImageChannelMask(image,channel_mask); if (status == MagickFalse) break; } return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A u t o L e v e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AutoLevelImage() adjusts the levels of a particular image channel by % scaling the minimum and maximum values to the full quantum range. % % The format of the LevelImage method is: % % MagickBooleanType AutoLevelImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image to auto-level % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType AutoLevelImage(Image *image, ExceptionInfo *exception) { return(MinMaxStretchImage(image,0.0,0.0,1.0,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B r i g h t n e s s C o n t r a s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BrightnessContrastImage() changes the brightness and/or contrast of an % image. It converts the brightness and contrast parameters into slope and % intercept and calls a polynomical function to apply to the image. % % The format of the BrightnessContrastImage method is: % % MagickBooleanType BrightnessContrastImage(Image *image, % const double brightness,const double contrast,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o brightness: the brightness percent (-100 .. 100). % % o contrast: the contrast percent (-100 .. 100). % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType BrightnessContrastImage(Image *image, const double brightness,const double contrast,ExceptionInfo *exception) { #define BrightnessContastImageTag "BrightnessContast/Image" double alpha, coefficients[2], intercept, slope; MagickBooleanType status; /* Compute slope and intercept. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); alpha=contrast; slope=tan((double) (MagickPI*(alpha/100.0+1.0)/4.0)); if (slope < 0.0) slope=0.0; intercept=brightness/100.0+((100-brightness)/200.0)*(1.0-slope); coefficients[0]=slope; coefficients[1]=intercept; status=FunctionImage(image,PolynomialFunction,2,coefficients,exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C L A H E I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CLAHEImage() is a variant of adaptive histogram equalization in which the % contrast amplification is limited, so as to reduce this problem of noise % amplification. % % Adapted from implementation by Karel Zuiderveld, karel@cv.ruu.nl in % "Graphics Gems IV", Academic Press, 1994. % % The format of the CLAHEImage method is: % % MagickBooleanType CLAHEImage(Image *image,const size_t width, % const size_t height,const size_t number_bins,const double clip_limit, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width: the width of the tile divisions to use in horizontal direction. % % o height: the height of the tile divisions to use in vertical direction. % % o number_bins: number of bins for histogram ("dynamic range"). % % o clip_limit: contrast limit for localised changes in contrast. A limit % less than 1 results in standard non-contrast limited AHE. % % o exception: return any errors or warnings in this structure. % */ typedef struct _RangeInfo { unsigned short min, max; } RangeInfo; static void ClipCLAHEHistogram(const double clip_limit,const size_t number_bins, size_t *histogram) { #define NumberCLAHEGrays (65536) register ssize_t i; size_t cumulative_excess, previous_excess, step; ssize_t excess; /* Compute total number of excess pixels. */ cumulative_excess=0; for (i=0; i < (ssize_t) number_bins; i++) { excess=(ssize_t) histogram[i]-(ssize_t) clip_limit; if (excess > 0) cumulative_excess+=excess; } /* Clip histogram and redistribute excess pixels across all bins. */ step=cumulative_excess/number_bins; excess=(ssize_t) (clip_limit-step); for (i=0; i < (ssize_t) number_bins; i++) { if ((double) histogram[i] > clip_limit) histogram[i]=(size_t) clip_limit; else if ((ssize_t) histogram[i] > excess) { cumulative_excess-=histogram[i]-excess; histogram[i]=(size_t) clip_limit; } else { cumulative_excess-=step; histogram[i]+=step; } } /* Redistribute remaining excess. */ do { register size_t *p; size_t *q; previous_excess=cumulative_excess; p=histogram; q=histogram+number_bins; while ((cumulative_excess != 0) && (p < q)) { step=number_bins/cumulative_excess; if (step < 1) step=1; for (p=histogram; (p < q) && (cumulative_excess != 0); p+=step) if ((double) *p < clip_limit) { (*p)++; cumulative_excess--; } p++; } } while ((cumulative_excess != 0) && (cumulative_excess < previous_excess)); } static void GenerateCLAHEHistogram(const RectangleInfo *clahe_info, const RectangleInfo *tile_info,const size_t number_bins, const unsigned short *lut,const unsigned short *pixels,size_t *histogram) { register const unsigned short *p; register ssize_t i; /* Classify the pixels into a gray histogram. */ for (i=0; i < (ssize_t) number_bins; i++) histogram[i]=0L; p=pixels; for (i=0; i < (ssize_t) tile_info->height; i++) { const unsigned short *q; q=p+tile_info->width; while (p < q) histogram[lut[*p++]]++; q+=clahe_info->width; p=q-tile_info->width; } } static void InterpolateCLAHE(const RectangleInfo *clahe_info,const size_t *Q12, const size_t *Q22,const size_t *Q11,const size_t *Q21, const RectangleInfo *tile,const unsigned short *lut,unsigned short *pixels) { ssize_t y; unsigned short intensity; /* Bilinear interpolate four tiles to eliminate boundary artifacts. */ for (y=(ssize_t) tile->height; y > 0; y--) { register ssize_t x; for (x=(ssize_t) tile->width; x > 0; x--) { intensity=lut[*pixels]; *pixels++=(unsigned short ) (PerceptibleReciprocal((double) tile->width* tile->height)*(y*(x*Q12[intensity]+(tile->width-x)*Q22[intensity])+ (tile->height-y)*(x*Q11[intensity]+(tile->width-x)*Q21[intensity]))); } pixels+=(clahe_info->width-tile->width); } } static void GenerateCLAHELut(const RangeInfo *range_info, const size_t number_bins,unsigned short *lut) { ssize_t i; unsigned short delta; /* Scale input image [intensity min,max] to [0,number_bins-1]. */ delta=(unsigned short) ((range_info->max-range_info->min)/number_bins+1); for (i=(ssize_t) range_info->min; i <= (ssize_t) range_info->max; i++) lut[i]=(unsigned short) ((i-range_info->min)/delta); } static void MapCLAHEHistogram(const RangeInfo *range_info, const size_t number_bins,const size_t number_pixels,size_t *histogram) { double scale, sum; register ssize_t i; /* Rescale histogram to range [min-intensity .. max-intensity]. */ scale=(double) (range_info->max-range_info->min)/number_pixels; sum=0.0; for (i=0; i < (ssize_t) number_bins; i++) { sum+=histogram[i]; histogram[i]=(size_t) (range_info->min+scale*sum); if (histogram[i] > range_info->max) histogram[i]=range_info->max; } } static MagickBooleanType CLAHE(const RectangleInfo *clahe_info, const RectangleInfo *tile_info,const RangeInfo *range_info, const size_t number_bins,const double clip_limit,unsigned short *pixels) { MemoryInfo *tile_cache; register unsigned short *p; size_t limit, *tiles; ssize_t y; unsigned short lut[NumberCLAHEGrays]; /* Constrast limited adapted histogram equalization. */ if (clip_limit == 1.0) return(MagickTrue); tile_cache=AcquireVirtualMemory((size_t) clahe_info->x*clahe_info->y, number_bins*sizeof(*tiles)); if (tile_cache == (MemoryInfo *) NULL) return(MagickFalse); tiles=(size_t *) GetVirtualMemoryBlob(tile_cache); limit=(size_t) (clip_limit*(tile_info->width*tile_info->height)/number_bins); if (limit < 1UL) limit=1UL; /* Generate greylevel mappings for each tile. */ GenerateCLAHELut(range_info,number_bins,lut); p=pixels; for (y=0; y < (ssize_t) clahe_info->y; y++) { register ssize_t x; for (x=0; x < (ssize_t) clahe_info->x; x++) { size_t *histogram; histogram=tiles+(number_bins*(y*clahe_info->x+x)); GenerateCLAHEHistogram(clahe_info,tile_info,number_bins,lut,p,histogram); ClipCLAHEHistogram((double) limit,number_bins,histogram); MapCLAHEHistogram(range_info,number_bins,tile_info->width* tile_info->height,histogram); p+=tile_info->width; } p+=clahe_info->width*(tile_info->height-1); } /* Interpolate greylevel mappings to get CLAHE image. */ p=pixels; for (y=0; y <= (ssize_t) clahe_info->y; y++) { OffsetInfo offset; RectangleInfo tile; register ssize_t x; tile.height=tile_info->height; tile.y=y-1; offset.y=tile.y+1; if (y == 0) { /* Top row. */ tile.height=tile_info->height >> 1; tile.y=0; offset.y=0; } else if (y == (ssize_t) clahe_info->y) { /* Bottom row. */ tile.height=(tile_info->height+1) >> 1; tile.y=clahe_info->y-1; offset.y=tile.y; } for (x=0; x <= (ssize_t) clahe_info->x; x++) { tile.width=tile_info->width; tile.x=x-1; offset.x=tile.x+1; if (x == 0) { /* Left column. */ tile.width=tile_info->width >> 1; tile.x=0; offset.x=0; } else if (x == (ssize_t) clahe_info->x) { /* Right column. */ tile.width=(tile_info->width+1) >> 1; tile.x=clahe_info->x-1; offset.x=tile.x; } InterpolateCLAHE(clahe_info, tiles+(number_bins*(tile.y*clahe_info->x+tile.x)), /* Q12 */ tiles+(number_bins*(tile.y*clahe_info->x+offset.x)), /* Q22 */ tiles+(number_bins*(offset.y*clahe_info->x+tile.x)), /* Q11 */ tiles+(number_bins*(offset.y*clahe_info->x+offset.x)), /* Q21 */ &tile,lut,p); p+=tile.width; } p+=clahe_info->width*(tile.height-1); } tile_cache=RelinquishVirtualMemory(tile_cache); return(MagickTrue); } MagickExport MagickBooleanType CLAHEImage(Image *image,const size_t width, const size_t height,const size_t number_bins,const double clip_limit, ExceptionInfo *exception) { #define CLAHEImageTag "CLAHE/Image" CacheView *image_view; ColorspaceType colorspace; MagickBooleanType status; MagickOffsetType progress; MemoryInfo *pixel_cache; RangeInfo range_info; RectangleInfo clahe_info, tile_info; size_t n; ssize_t y; unsigned short *pixels; /* Configure CLAHE parameters. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); range_info.min=0; range_info.max=NumberCLAHEGrays-1; tile_info.width=width; if (tile_info.width == 0) tile_info.width=image->columns >> 3; tile_info.height=height; if (tile_info.height == 0) tile_info.height=image->rows >> 3; tile_info.x=0; if ((image->columns % tile_info.width) != 0) tile_info.x=(ssize_t) tile_info.width-(image->columns % tile_info.width); tile_info.y=0; if ((image->rows % tile_info.height) != 0) tile_info.y=(ssize_t) tile_info.height-(image->rows % tile_info.height); clahe_info.width=image->columns+tile_info.x; clahe_info.height=image->rows+tile_info.y; clahe_info.x=(ssize_t) clahe_info.width/tile_info.width; clahe_info.y=(ssize_t) clahe_info.height/tile_info.height; pixel_cache=AcquireVirtualMemory(clahe_info.width,clahe_info.height* sizeof(*pixels)); if (pixel_cache == (MemoryInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); pixels=(unsigned short *) GetVirtualMemoryBlob(pixel_cache); colorspace=image->colorspace; if (TransformImageColorspace(image,LabColorspace,exception) == MagickFalse) { pixel_cache=RelinquishVirtualMemory(pixel_cache); return(MagickFalse); } /* Initialize CLAHE pixels. */ image_view=AcquireVirtualCacheView(image,exception); progress=0; status=MagickTrue; n=0; for (y=0; y < (ssize_t) clahe_info.height; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-(tile_info.x >> 1),y- (tile_info.y >> 1),clahe_info.width,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) clahe_info.width; x++) { pixels[n++]=ScaleQuantumToShort(p[0]); p+=GetPixelChannels(image); } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,CLAHEImageTag,progress,2* GetPixelChannels(image)); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); status=CLAHE(&clahe_info,&tile_info,&range_info,number_bins == 0 ? (size_t) 128 : MagickMin(number_bins,256),clip_limit,pixels); if (status == MagickFalse) (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); /* Push CLAHE pixels to CLAHE image. */ image_view=AcquireAuthenticCacheView(image,exception); n=clahe_info.width*(tile_info.y >> 1); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } n+=tile_info.x >> 1; for (x=0; x < (ssize_t) image->columns; x++) { q[0]=ScaleShortToQuantum(pixels[n++]); q+=GetPixelChannels(image); } n+=(clahe_info.width-image->columns-(tile_info.x >> 1)); if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,CLAHEImageTag,progress,2* GetPixelChannels(image)); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); pixel_cache=RelinquishVirtualMemory(pixel_cache); if (TransformImageColorspace(image,colorspace,exception) == MagickFalse) status=MagickFalse; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l u t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClutImage() replaces each color value in the given image, by using it as an % index to lookup a replacement color value in a Color Look UP Table in the % form of an image. The values are extracted along a diagonal of the CLUT % image so either a horizontal or vertial gradient image can be used. % % Typically this is used to either re-color a gray-scale image according to a % color gradient in the CLUT image, or to perform a freeform histogram % (level) adjustment according to the (typically gray-scale) gradient in the % CLUT image. % % When the 'channel' mask includes the matte/alpha transparency channel but % one image has no such channel it is assumed that that image is a simple % gray-scale image that will effect the alpha channel values, either for % gray-scale coloring (with transparent or semi-transparent colors), or % a histogram adjustment of existing alpha channel values. If both images % have matte channels, direct and normal indexing is applied, which is rarely % used. % % The format of the ClutImage method is: % % MagickBooleanType ClutImage(Image *image,Image *clut_image, % const PixelInterpolateMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image, which is replaced by indexed CLUT values % % o clut_image: the color lookup table image for replacement color values. % % o method: the pixel interpolation method. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ClutImage(Image *image,const Image *clut_image, const PixelInterpolateMethod method,ExceptionInfo *exception) { #define ClutImageTag "Clut/Image" CacheView *clut_view, *image_view; MagickBooleanType status; MagickOffsetType progress; PixelInfo *clut_map; register ssize_t i; ssize_t adjust, y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(clut_image != (Image *) NULL); assert(clut_image->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if ((IsGrayColorspace(image->colorspace) != MagickFalse) && (IsGrayColorspace(clut_image->colorspace) == MagickFalse)) (void) SetImageColorspace(image,sRGBColorspace,exception); clut_map=(PixelInfo *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*clut_map)); if (clut_map == (PixelInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); /* Clut image. */ status=MagickTrue; progress=0; adjust=(ssize_t) (clut_image->interpolate == IntegerInterpolatePixel ? 0 : 1); clut_view=AcquireVirtualCacheView(clut_image,exception); for (i=0; i <= (ssize_t) MaxMap; i++) { GetPixelInfo(clut_image,clut_map+i); status=InterpolatePixelInfo(clut_image,clut_view,method, (double) i*(clut_image->columns-adjust)/MaxMap,(double) i* (clut_image->rows-adjust)/MaxMap,clut_map+i,exception); if (status == MagickFalse) break; } clut_view=DestroyCacheView(clut_view); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { PixelInfo pixel; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } GetPixelInfo(image,&pixel); for (x=0; x < (ssize_t) image->columns; x++) { PixelTrait traits; GetPixelInfoPixel(image,q,&pixel); traits=GetPixelChannelTraits(image,RedPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.red=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.red))].red; traits=GetPixelChannelTraits(image,GreenPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.green=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.green))].green; traits=GetPixelChannelTraits(image,BluePixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.blue=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.blue))].blue; traits=GetPixelChannelTraits(image,BlackPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.black=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.black))].black; traits=GetPixelChannelTraits(image,AlphaPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.alpha=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.alpha))].alpha; SetPixelViaPixelInfo(image,&pixel,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ClutImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); clut_map=(PixelInfo *) RelinquishMagickMemory(clut_map); if ((clut_image->alpha_trait != UndefinedPixelTrait) && ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)) (void) SetImageAlphaChannel(image,ActivateAlphaChannel,exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o l o r D e c i s i o n L i s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ColorDecisionListImage() accepts a lightweight Color Correction Collection % (CCC) file which solely contains one or more color corrections and applies % the correction to the image. Here is a sample CCC file: % % <ColorCorrectionCollection xmlns="urn:ASC:CDL:v1.2"> % <ColorCorrection id="cc03345"> % <SOPNode> % <Slope> 0.9 1.2 0.5 </Slope> % <Offset> 0.4 -0.5 0.6 </Offset> % <Power> 1.0 0.8 1.5 </Power> % </SOPNode> % <SATNode> % <Saturation> 0.85 </Saturation> % </SATNode> % </ColorCorrection> % </ColorCorrectionCollection> % % which includes the slop, offset, and power for each of the RGB channels % as well as the saturation. % % The format of the ColorDecisionListImage method is: % % MagickBooleanType ColorDecisionListImage(Image *image, % const char *color_correction_collection,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o color_correction_collection: the color correction collection in XML. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ColorDecisionListImage(Image *image, const char *color_correction_collection,ExceptionInfo *exception) { #define ColorDecisionListCorrectImageTag "ColorDecisionList/Image" typedef struct _Correction { double slope, offset, power; } Correction; typedef struct _ColorCorrection { Correction red, green, blue; double saturation; } ColorCorrection; CacheView *image_view; char token[MagickPathExtent]; ColorCorrection color_correction; const char *content, *p; MagickBooleanType status; MagickOffsetType progress; PixelInfo *cdl_map; register ssize_t i; ssize_t y; XMLTreeInfo *cc, *ccc, *sat, *sop; /* Allocate and initialize cdl maps. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (color_correction_collection == (const char *) NULL) return(MagickFalse); ccc=NewXMLTree((const char *) color_correction_collection,exception); if (ccc == (XMLTreeInfo *) NULL) return(MagickFalse); cc=GetXMLTreeChild(ccc,"ColorCorrection"); if (cc == (XMLTreeInfo *) NULL) { ccc=DestroyXMLTree(ccc); return(MagickFalse); } color_correction.red.slope=1.0; color_correction.red.offset=0.0; color_correction.red.power=1.0; color_correction.green.slope=1.0; color_correction.green.offset=0.0; color_correction.green.power=1.0; color_correction.blue.slope=1.0; color_correction.blue.offset=0.0; color_correction.blue.power=1.0; color_correction.saturation=0.0; sop=GetXMLTreeChild(cc,"SOPNode"); if (sop != (XMLTreeInfo *) NULL) { XMLTreeInfo *offset, *power, *slope; slope=GetXMLTreeChild(sop,"Slope"); if (slope != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(slope); p=(const char *) content; for (i=0; (*p != '\0') && (i < 3); i++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); switch (i) { case 0: { color_correction.red.slope=StringToDouble(token,(char **) NULL); break; } case 1: { color_correction.green.slope=StringToDouble(token, (char **) NULL); break; } case 2: { color_correction.blue.slope=StringToDouble(token, (char **) NULL); break; } } } } offset=GetXMLTreeChild(sop,"Offset"); if (offset != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(offset); p=(const char *) content; for (i=0; (*p != '\0') && (i < 3); i++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); switch (i) { case 0: { color_correction.red.offset=StringToDouble(token, (char **) NULL); break; } case 1: { color_correction.green.offset=StringToDouble(token, (char **) NULL); break; } case 2: { color_correction.blue.offset=StringToDouble(token, (char **) NULL); break; } } } } power=GetXMLTreeChild(sop,"Power"); if (power != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(power); p=(const char *) content; for (i=0; (*p != '\0') && (i < 3); i++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); switch (i) { case 0: { color_correction.red.power=StringToDouble(token,(char **) NULL); break; } case 1: { color_correction.green.power=StringToDouble(token, (char **) NULL); break; } case 2: { color_correction.blue.power=StringToDouble(token, (char **) NULL); break; } } } } } sat=GetXMLTreeChild(cc,"SATNode"); if (sat != (XMLTreeInfo *) NULL) { XMLTreeInfo *saturation; saturation=GetXMLTreeChild(sat,"Saturation"); if (saturation != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(saturation); p=(const char *) content; GetNextToken(p,&p,MagickPathExtent,token); color_correction.saturation=StringToDouble(token,(char **) NULL); } } ccc=DestroyXMLTree(ccc); if (image->debug != MagickFalse) { (void) LogMagickEvent(TransformEvent,GetMagickModule(), " Color Correction Collection:"); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.red.slope: %g",color_correction.red.slope); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.red.offset: %g",color_correction.red.offset); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.red.power: %g",color_correction.red.power); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.green.slope: %g",color_correction.green.slope); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.green.offset: %g",color_correction.green.offset); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.green.power: %g",color_correction.green.power); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.blue.slope: %g",color_correction.blue.slope); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.blue.offset: %g",color_correction.blue.offset); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.blue.power: %g",color_correction.blue.power); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.saturation: %g",color_correction.saturation); } cdl_map=(PixelInfo *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*cdl_map)); if (cdl_map == (PixelInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); for (i=0; i <= (ssize_t) MaxMap; i++) { cdl_map[i].red=(double) ScaleMapToQuantum((double) (MaxMap*(pow(color_correction.red.slope*i/MaxMap+ color_correction.red.offset,color_correction.red.power)))); cdl_map[i].green=(double) ScaleMapToQuantum((double) (MaxMap*(pow(color_correction.green.slope*i/MaxMap+ color_correction.green.offset,color_correction.green.power)))); cdl_map[i].blue=(double) ScaleMapToQuantum((double) (MaxMap*(pow(color_correction.blue.slope*i/MaxMap+ color_correction.blue.offset,color_correction.blue.power)))); } if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Apply transfer function to colormap. */ double luma; luma=0.21267f*image->colormap[i].red+0.71526*image->colormap[i].green+ 0.07217f*image->colormap[i].blue; image->colormap[i].red=luma+color_correction.saturation*cdl_map[ ScaleQuantumToMap(ClampToQuantum(image->colormap[i].red))].red-luma; image->colormap[i].green=luma+color_correction.saturation*cdl_map[ ScaleQuantumToMap(ClampToQuantum(image->colormap[i].green))].green-luma; image->colormap[i].blue=luma+color_correction.saturation*cdl_map[ ScaleQuantumToMap(ClampToQuantum(image->colormap[i].blue))].blue-luma; } /* Apply transfer function to image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double luma; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { luma=0.21267f*GetPixelRed(image,q)+0.71526*GetPixelGreen(image,q)+ 0.07217f*GetPixelBlue(image,q); SetPixelRed(image,ClampToQuantum(luma+color_correction.saturation* (cdl_map[ScaleQuantumToMap(GetPixelRed(image,q))].red-luma)),q); SetPixelGreen(image,ClampToQuantum(luma+color_correction.saturation* (cdl_map[ScaleQuantumToMap(GetPixelGreen(image,q))].green-luma)),q); SetPixelBlue(image,ClampToQuantum(luma+color_correction.saturation* (cdl_map[ScaleQuantumToMap(GetPixelBlue(image,q))].blue-luma)),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ColorDecisionListCorrectImageTag, progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); cdl_map=(PixelInfo *) RelinquishMagickMemory(cdl_map); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o n t r a s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ContrastImage() enhances the intensity differences between the lighter and % darker elements of the image. Set sharpen to a MagickTrue to increase the % image contrast otherwise the contrast is reduced. % % The format of the ContrastImage method is: % % MagickBooleanType ContrastImage(Image *image, % const MagickBooleanType sharpen,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o sharpen: Increase or decrease image contrast. % % o exception: return any errors or warnings in this structure. % */ static void Contrast(const int sign,double *red,double *green,double *blue) { double brightness, hue, saturation; /* Enhance contrast: dark color become darker, light color become lighter. */ assert(red != (double *) NULL); assert(green != (double *) NULL); assert(blue != (double *) NULL); hue=0.0; saturation=0.0; brightness=0.0; ConvertRGBToHSB(*red,*green,*blue,&hue,&saturation,&brightness); brightness+=0.5*sign*(0.5*(sin((double) (MagickPI*(brightness-0.5)))+1.0)- brightness); if (brightness > 1.0) brightness=1.0; else if (brightness < 0.0) brightness=0.0; ConvertHSBToRGB(hue,saturation,brightness,red,green,blue); } MagickExport MagickBooleanType ContrastImage(Image *image, const MagickBooleanType sharpen,ExceptionInfo *exception) { #define ContrastImageTag "Contrast/Image" CacheView *image_view; int sign; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateContrastImage(image,sharpen,exception) != MagickFalse) return(MagickTrue); #endif if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); sign=sharpen != MagickFalse ? 1 : -1; if (image->storage_class == PseudoClass) { /* Contrast enhance colormap. */ for (i=0; i < (ssize_t) image->colors; i++) { double blue, green, red; red=(double) image->colormap[i].red; green=(double) image->colormap[i].green; blue=(double) image->colormap[i].blue; Contrast(sign,&red,&green,&blue); image->colormap[i].red=(MagickRealType) red; image->colormap[i].green=(MagickRealType) green; image->colormap[i].blue=(MagickRealType) blue; } } /* Contrast enhance image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double blue, green, red; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { red=(double) GetPixelRed(image,q); green=(double) GetPixelGreen(image,q); blue=(double) GetPixelBlue(image,q); Contrast(sign,&red,&green,&blue); SetPixelRed(image,ClampToQuantum(red),q); SetPixelGreen(image,ClampToQuantum(green),q); SetPixelBlue(image,ClampToQuantum(blue),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ContrastImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o n t r a s t S t r e t c h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ContrastStretchImage() is a simple image enhancement technique that attempts % to improve the contrast in an image by 'stretching' the range of intensity % values it contains to span a desired range of values. It differs from the % more sophisticated histogram equalization in that it can only apply a % linear scaling function to the image pixel values. As a result the % 'enhancement' is less harsh. % % The format of the ContrastStretchImage method is: % % MagickBooleanType ContrastStretchImage(Image *image, % const char *levels,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_point: the black point. % % o white_point: the white point. % % o levels: Specify the levels where the black and white points have the % range of 0 to number-of-pixels (e.g. 1%, 10x90%, etc.). % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ContrastStretchImage(Image *image, const double black_point,const double white_point,ExceptionInfo *exception) { #define MaxRange(color) ((double) ScaleQuantumToMap((Quantum) (color))) #define ContrastStretchImageTag "ContrastStretch/Image" CacheView *image_view; double *black, *histogram, *stretch_map, *white; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate histogram and stretch map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageGray(image,exception) != MagickFalse) (void) SetImageColorspace(image,GRAYColorspace,exception); black=(double *) AcquireQuantumMemory(MaxPixelChannels,sizeof(*black)); white=(double *) AcquireQuantumMemory(MaxPixelChannels,sizeof(*white)); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels* sizeof(*histogram)); stretch_map=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels* sizeof(*stretch_map)); if ((black == (double *) NULL) || (white == (double *) NULL) || (histogram == (double *) NULL) || (stretch_map == (double *) NULL)) { if (stretch_map != (double *) NULL) stretch_map=(double *) RelinquishMagickMemory(stretch_map); if (histogram != (double *) NULL) histogram=(double *) RelinquishMagickMemory(histogram); if (white != (double *) NULL) white=(double *) RelinquishMagickMemory(white); if (black != (double *) NULL) black=(double *) RelinquishMagickMemory(black); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } /* Form histogram. */ status=MagickTrue; (void) memset(histogram,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double pixel; pixel=GetPixelIntensity(image,p); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { if (image->channel_mask != DefaultChannels) pixel=(double) p[i]; histogram[GetPixelChannels(image)*ScaleQuantumToMap( ClampToQuantum(pixel))+i]++; } p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Find the histogram boundaries by locating the black/white levels. */ for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; register ssize_t j; black[i]=0.0; white[i]=MaxRange(QuantumRange); intensity=0.0; for (j=0; j <= (ssize_t) MaxMap; j++) { intensity+=histogram[GetPixelChannels(image)*j+i]; if (intensity > black_point) break; } black[i]=(double) j; intensity=0.0; for (j=(ssize_t) MaxMap; j != 0; j--) { intensity+=histogram[GetPixelChannels(image)*j+i]; if (intensity > ((double) image->columns*image->rows-white_point)) break; } white[i]=(double) j; } histogram=(double *) RelinquishMagickMemory(histogram); /* Stretch the histogram to create the stretched image mapping. */ (void) memset(stretch_map,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*stretch_map)); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { register ssize_t j; for (j=0; j <= (ssize_t) MaxMap; j++) { double gamma; gamma=PerceptibleReciprocal(white[i]-black[i]); if (j < (ssize_t) black[i]) stretch_map[GetPixelChannels(image)*j+i]=0.0; else if (j > (ssize_t) white[i]) stretch_map[GetPixelChannels(image)*j+i]=(double) QuantumRange; else if (black[i] != white[i]) stretch_map[GetPixelChannels(image)*j+i]=(double) ScaleMapToQuantum( (double) (MaxMap*gamma*(j-black[i]))); } } if (image->storage_class == PseudoClass) { register ssize_t j; /* Stretch-contrast colormap. */ for (j=0; j < (ssize_t) image->colors; j++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,RedPixelChannel); image->colormap[j].red=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+i]; } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,GreenPixelChannel); image->colormap[j].green=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+i]; } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,BluePixelChannel); image->colormap[j].blue=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+i]; } if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,AlphaPixelChannel); image->colormap[j].alpha=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+i]; } } } /* Stretch-contrast image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if (black[j] == white[j]) continue; q[j]=ClampToQuantum(stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(q[j])+j]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ContrastStretchImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); stretch_map=(double *) RelinquishMagickMemory(stretch_map); white=(double *) RelinquishMagickMemory(white); black=(double *) RelinquishMagickMemory(black); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E n h a n c e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EnhanceImage() applies a digital filter that improves the quality of a % noisy image. % % The format of the EnhanceImage method is: % % Image *EnhanceImage(const Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *EnhanceImage(const Image *image,ExceptionInfo *exception) { #define EnhanceImageTag "Enhance/Image" #define EnhancePixel(weight) \ mean=QuantumScale*((double) GetPixelRed(image,r)+pixel.red)/2.0; \ distance=QuantumScale*((double) GetPixelRed(image,r)-pixel.red); \ distance_squared=(4.0+mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelGreen(image,r)+pixel.green)/2.0; \ distance=QuantumScale*((double) GetPixelGreen(image,r)-pixel.green); \ distance_squared+=(7.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelBlue(image,r)+pixel.blue)/2.0; \ distance=QuantumScale*((double) GetPixelBlue(image,r)-pixel.blue); \ distance_squared+=(5.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelBlack(image,r)+pixel.black)/2.0; \ distance=QuantumScale*((double) GetPixelBlack(image,r)-pixel.black); \ distance_squared+=(5.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelAlpha(image,r)+pixel.alpha)/2.0; \ distance=QuantumScale*((double) GetPixelAlpha(image,r)-pixel.alpha); \ distance_squared+=(5.0-mean)*distance*distance; \ if (distance_squared < 0.069) \ { \ aggregate.red+=(weight)*GetPixelRed(image,r); \ aggregate.green+=(weight)*GetPixelGreen(image,r); \ aggregate.blue+=(weight)*GetPixelBlue(image,r); \ aggregate.black+=(weight)*GetPixelBlack(image,r); \ aggregate.alpha+=(weight)*GetPixelAlpha(image,r); \ total_weight+=(weight); \ } \ r+=GetPixelChannels(image); CacheView *enhance_view, *image_view; Image *enhance_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Initialize enhanced image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); enhance_image=CloneImage(image,0,0,MagickTrue, exception); if (enhance_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(enhance_image,DirectClass,exception) == MagickFalse) { enhance_image=DestroyImage(enhance_image); return((Image *) NULL); } /* Enhance image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); enhance_view=AcquireAuthenticCacheView(enhance_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,enhance_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { PixelInfo pixel; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; ssize_t center; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-2,y-2,image->columns+4,5,exception); q=QueueCacheViewAuthenticPixels(enhance_view,0,y,enhance_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } center=(ssize_t) GetPixelChannels(image)*(2*(image->columns+4)+2); GetPixelInfo(image,&pixel); for (x=0; x < (ssize_t) image->columns; x++) { double distance, distance_squared, mean, total_weight; PixelInfo aggregate; register const Quantum *magick_restrict r; GetPixelInfo(image,&aggregate); total_weight=0.0; GetPixelInfoPixel(image,p+center,&pixel); r=p; EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0); EnhancePixel(8.0); EnhancePixel(5.0); r=p+GetPixelChannels(image)*(image->columns+4); EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0); EnhancePixel(20.0); EnhancePixel(8.0); r=p+2*GetPixelChannels(image)*(image->columns+4); EnhancePixel(10.0); EnhancePixel(40.0); EnhancePixel(80.0); EnhancePixel(40.0); EnhancePixel(10.0); r=p+3*GetPixelChannels(image)*(image->columns+4); EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0); EnhancePixel(20.0); EnhancePixel(8.0); r=p+4*GetPixelChannels(image)*(image->columns+4); EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0); EnhancePixel(8.0); EnhancePixel(5.0); if (total_weight > MagickEpsilon) { pixel.red=((aggregate.red+total_weight/2.0)/total_weight); pixel.green=((aggregate.green+total_weight/2.0)/total_weight); pixel.blue=((aggregate.blue+total_weight/2.0)/total_weight); pixel.black=((aggregate.black+total_weight/2.0)/total_weight); pixel.alpha=((aggregate.alpha+total_weight/2.0)/total_weight); } SetPixelViaPixelInfo(image,&pixel,q); p+=GetPixelChannels(image); q+=GetPixelChannels(enhance_image); } if (SyncCacheViewAuthenticPixels(enhance_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,EnhanceImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } enhance_view=DestroyCacheView(enhance_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) enhance_image=DestroyImage(enhance_image); return(enhance_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E q u a l i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EqualizeImage() applies a histogram equalization to the image. % % The format of the EqualizeImage method is: % % MagickBooleanType EqualizeImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType EqualizeImage(Image *image, ExceptionInfo *exception) { #define EqualizeImageTag "Equalize/Image" CacheView *image_view; double black[CompositePixelChannel+1], *equalize_map, *histogram, *map, white[CompositePixelChannel+1]; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate and initialize histogram arrays. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateEqualizeImage(image,exception) != MagickFalse) return(MagickTrue); #endif if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); equalize_map=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels* sizeof(*equalize_map)); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels* sizeof(*histogram)); map=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels*sizeof(*map)); if ((equalize_map == (double *) NULL) || (histogram == (double *) NULL) || (map == (double *) NULL)) { if (map != (double *) NULL) map=(double *) RelinquishMagickMemory(map); if (histogram != (double *) NULL) histogram=(double *) RelinquishMagickMemory(histogram); if (equalize_map != (double *) NULL) equalize_map=(double *) RelinquishMagickMemory(equalize_map); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } /* Form histogram. */ status=MagickTrue; (void) memset(histogram,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; intensity=(double) p[i]; if ((image->channel_mask & SyncChannels) != 0) intensity=GetPixelIntensity(image,p); histogram[GetPixelChannels(image)*ScaleQuantumToMap( ClampToQuantum(intensity))+i]++; } p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Integrate the histogram to get the equalization map. */ for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; register ssize_t j; intensity=0.0; for (j=0; j <= (ssize_t) MaxMap; j++) { intensity+=histogram[GetPixelChannels(image)*j+i]; map[GetPixelChannels(image)*j+i]=intensity; } } (void) memset(equalize_map,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*equalize_map)); (void) memset(black,0,sizeof(*black)); (void) memset(white,0,sizeof(*white)); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { register ssize_t j; black[i]=map[i]; white[i]=map[GetPixelChannels(image)*MaxMap+i]; if (black[i] != white[i]) for (j=0; j <= (ssize_t) MaxMap; j++) equalize_map[GetPixelChannels(image)*j+i]=(double) ScaleMapToQuantum((double) ((MaxMap*(map[ GetPixelChannels(image)*j+i]-black[i]))/(white[i]-black[i]))); } histogram=(double *) RelinquishMagickMemory(histogram); map=(double *) RelinquishMagickMemory(map); if (image->storage_class == PseudoClass) { register ssize_t j; /* Equalize colormap. */ for (j=0; j < (ssize_t) image->colors; j++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel = GetPixelChannelChannel(image, RedPixelChannel); if (black[channel] != white[channel]) image->colormap[j].red=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+ channel]; } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel = GetPixelChannelChannel(image, GreenPixelChannel); if (black[channel] != white[channel]) image->colormap[j].green=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+ channel]; } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel = GetPixelChannelChannel(image, BluePixelChannel); if (black[channel] != white[channel]) image->colormap[j].blue=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+ channel]; } if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel = GetPixelChannelChannel(image, AlphaPixelChannel); if (black[channel] != white[channel]) image->colormap[j].alpha=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+ channel]; } } } /* Equalize image. */ progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if (((traits & UpdatePixelTrait) == 0) || (black[j] == white[j])) continue; q[j]=ClampToQuantum(equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(q[j])+j]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,EqualizeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); equalize_map=(double *) RelinquishMagickMemory(equalize_map); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G a m m a I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GammaImage() gamma-corrects a particular image channel. The same % image viewed on different devices will have perceptual differences in the % way the image's intensities are represented on the screen. Specify % individual gamma levels for the red, green, and blue channels, or adjust % all three with the gamma parameter. Values typically range from 0.8 to 2.3. % % You can also reduce the influence of a particular channel with a gamma % value of 0. % % The format of the GammaImage method is: % % MagickBooleanType GammaImage(Image *image,const double gamma, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o level: the image gamma as a string (e.g. 1.6,1.2,1.0). % % o gamma: the image gamma. % */ static inline double gamma_pow(const double value,const double gamma) { return(value < 0.0 ? value : pow(value,gamma)); } MagickExport MagickBooleanType GammaImage(Image *image,const double gamma, ExceptionInfo *exception) { #define GammaImageTag "Gamma/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; Quantum *gamma_map; register ssize_t i; ssize_t y; /* Allocate and initialize gamma maps. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (gamma == 1.0) return(MagickTrue); gamma_map=(Quantum *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*gamma_map)); if (gamma_map == (Quantum *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); (void) memset(gamma_map,0,(MaxMap+1)*sizeof(*gamma_map)); if (gamma != 0.0) for (i=0; i <= (ssize_t) MaxMap; i++) gamma_map[i]=ScaleMapToQuantum((double) (MaxMap*pow((double) i/ MaxMap,1.0/gamma))); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Gamma-correct colormap. */ if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].red))]; if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].green))]; if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].blue))]; if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].alpha))]; } /* Gamma-correct image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=gamma_map[ScaleQuantumToMap(ClampToQuantum((MagickRealType) q[j]))]; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,GammaImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); gamma_map=(Quantum *) RelinquishMagickMemory(gamma_map); if (image->gamma != 0.0) image->gamma*=gamma; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G r a y s c a l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GrayscaleImage() converts the image to grayscale. % % The format of the GrayscaleImage method is: % % MagickBooleanType GrayscaleImage(Image *image, % const PixelIntensityMethod method ,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o method: the pixel intensity method. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GrayscaleImage(Image *image, const PixelIntensityMethod method,ExceptionInfo *exception) { #define GrayscaleImageTag "Grayscale/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateGrayscaleImage(image,method,exception) != MagickFalse) { image->intensity=method; image->type=GrayscaleType; if ((method == Rec601LuminancePixelIntensityMethod) || (method == Rec709LuminancePixelIntensityMethod)) return(SetImageColorspace(image,LinearGRAYColorspace,exception)); return(SetImageColorspace(image,GRAYColorspace,exception)); } #endif /* Grayscale image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType blue, green, red, intensity; red=(MagickRealType) GetPixelRed(image,q); green=(MagickRealType) GetPixelGreen(image,q); blue=(MagickRealType) GetPixelBlue(image,q); intensity=0.0; switch (method) { case AveragePixelIntensityMethod: { intensity=(red+green+blue)/3.0; break; } case BrightnessPixelIntensityMethod: { intensity=MagickMax(MagickMax(red,green),blue); break; } case LightnessPixelIntensityMethod: { intensity=(MagickMin(MagickMin(red,green),blue)+ MagickMax(MagickMax(red,green),blue))/2.0; break; } case MSPixelIntensityMethod: { intensity=(MagickRealType) (((double) red*red+green*green+ blue*blue)/3.0); break; } case Rec601LumaPixelIntensityMethod: { if (image->colorspace == RGBColorspace) { red=EncodePixelGamma(red); green=EncodePixelGamma(green); blue=EncodePixelGamma(blue); } intensity=0.298839*red+0.586811*green+0.114350*blue; break; } case Rec601LuminancePixelIntensityMethod: { if (image->colorspace == sRGBColorspace) { red=DecodePixelGamma(red); green=DecodePixelGamma(green); blue=DecodePixelGamma(blue); } intensity=0.298839*red+0.586811*green+0.114350*blue; break; } case Rec709LumaPixelIntensityMethod: default: { if (image->colorspace == RGBColorspace) { red=EncodePixelGamma(red); green=EncodePixelGamma(green); blue=EncodePixelGamma(blue); } intensity=0.212656*red+0.715158*green+0.072186*blue; break; } case Rec709LuminancePixelIntensityMethod: { if (image->colorspace == sRGBColorspace) { red=DecodePixelGamma(red); green=DecodePixelGamma(green); blue=DecodePixelGamma(blue); } intensity=0.212656*red+0.715158*green+0.072186*blue; break; } case RMSPixelIntensityMethod: { intensity=(MagickRealType) (sqrt((double) red*red+green*green+ blue*blue)/sqrt(3.0)); break; } } SetPixelGray(image,ClampToQuantum(intensity),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,GrayscaleImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); image->intensity=method; image->type=GrayscaleType; if ((method == Rec601LuminancePixelIntensityMethod) || (method == Rec709LuminancePixelIntensityMethod)) return(SetImageColorspace(image,LinearGRAYColorspace,exception)); return(SetImageColorspace(image,GRAYColorspace,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % H a l d C l u t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % HaldClutImage() applies a Hald color lookup table to the image. A Hald % color lookup table is a 3-dimensional color cube mapped to 2 dimensions. % Create it with the HALD coder. You can apply any color transformation to % the Hald image and then use this method to apply the transform to the % image. % % The format of the HaldClutImage method is: % % MagickBooleanType HaldClutImage(Image *image,Image *hald_image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image, which is replaced by indexed CLUT values % % o hald_image: the color lookup table image for replacement color values. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType HaldClutImage(Image *image, const Image *hald_image,ExceptionInfo *exception) { #define HaldClutImageTag "Clut/Image" typedef struct _HaldInfo { double x, y, z; } HaldInfo; CacheView *hald_view, *image_view; double width; MagickBooleanType status; MagickOffsetType progress; PixelInfo zero; size_t cube_size, length, level; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(hald_image != (Image *) NULL); assert(hald_image->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); /* Hald clut image. */ status=MagickTrue; progress=0; length=(size_t) MagickMin((MagickRealType) hald_image->columns, (MagickRealType) hald_image->rows); for (level=2; (level*level*level) < length; level++) ; level*=level; cube_size=level*level; width=(double) hald_image->columns; GetPixelInfo(hald_image,&zero); hald_view=AcquireVirtualCacheView(hald_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double offset; HaldInfo point; PixelInfo pixel, pixel1, pixel2, pixel3, pixel4; point.x=QuantumScale*(level-1.0)*GetPixelRed(image,q); point.y=QuantumScale*(level-1.0)*GetPixelGreen(image,q); point.z=QuantumScale*(level-1.0)*GetPixelBlue(image,q); offset=point.x+level*floor(point.y)+cube_size*floor(point.z); point.x-=floor(point.x); point.y-=floor(point.y); point.z-=floor(point.z); pixel1=zero; status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, fmod(offset,width),floor(offset/width),&pixel1,exception); if (status == MagickFalse) break; pixel2=zero; status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, fmod(offset+level,width),floor((offset+level)/width),&pixel2,exception); if (status == MagickFalse) break; pixel3=zero; CompositePixelInfoAreaBlend(&pixel1,pixel1.alpha,&pixel2,pixel2.alpha, point.y,&pixel3); offset+=cube_size; status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, fmod(offset,width),floor(offset/width),&pixel1,exception); if (status == MagickFalse) break; status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, fmod(offset+level,width),floor((offset+level)/width),&pixel2,exception); if (status == MagickFalse) break; pixel4=zero; CompositePixelInfoAreaBlend(&pixel1,pixel1.alpha,&pixel2,pixel2.alpha, point.y,&pixel4); pixel=zero; CompositePixelInfoAreaBlend(&pixel3,pixel3.alpha,&pixel4,pixel4.alpha, point.z,&pixel); if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) SetPixelRed(image,ClampToQuantum(pixel.red),q); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) SetPixelGreen(image,ClampToQuantum(pixel.green),q); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) SetPixelBlue(image,ClampToQuantum(pixel.blue),q); if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) && (image->colorspace == CMYKColorspace)) SetPixelBlack(image,ClampToQuantum(pixel.black),q); if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) && (image->alpha_trait != UndefinedPixelTrait)) SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,HaldClutImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } hald_view=DestroyCacheView(hald_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L e v e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LevelImage() adjusts the levels of a particular image channel by % scaling the colors falling between specified white and black points to % the full available quantum range. % % The parameters provided represent the black, and white points. The black % point specifies the darkest color in the image. Colors darker than the % black point are set to zero. White point specifies the lightest color in % the image. Colors brighter than the white point are set to the maximum % quantum value. % % If a '!' flag is given, map black and white colors to the given levels % rather than mapping those levels to black and white. See % LevelizeImage() below. % % Gamma specifies a gamma correction to apply to the image. % % The format of the LevelImage method is: % % MagickBooleanType LevelImage(Image *image,const double black_point, % const double white_point,const double gamma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_point: The level to map zero (black) to. % % o white_point: The level to map QuantumRange (white) to. % % o exception: return any errors or warnings in this structure. % */ static inline double LevelPixel(const double black_point, const double white_point,const double gamma,const double pixel) { double level_pixel, scale; scale=PerceptibleReciprocal(white_point-black_point); level_pixel=QuantumRange*gamma_pow(scale*((double) pixel-black_point), 1.0/gamma); return(level_pixel); } MagickExport MagickBooleanType LevelImage(Image *image,const double black_point, const double white_point,const double gamma,ExceptionInfo *exception) { #define LevelImageTag "Level/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate and initialize levels map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Level colormap. */ if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(double) ClampToQuantum(LevelPixel(black_point, white_point,gamma,image->colormap[i].red)); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(double) ClampToQuantum(LevelPixel(black_point, white_point,gamma,image->colormap[i].green)); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(double) ClampToQuantum(LevelPixel(black_point, white_point,gamma,image->colormap[i].blue)); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(double) ClampToQuantum(LevelPixel(black_point, white_point,gamma,image->colormap[i].alpha)); } /* Level image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=ClampToQuantum(LevelPixel(black_point,white_point,gamma, (double) q[j])); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,LevelImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); (void) ClampImage(image,exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L e v e l i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LevelizeImage() applies the reversed LevelImage() operation to just % the specific channels specified. It compresses the full range of color % values, so that they lie between the given black and white points. Gamma is % applied before the values are mapped. % % LevelizeImage() can be called with by using a +level command line % API option, or using a '!' on a -level or LevelImage() geometry string. % % It can be used to de-contrast a greyscale image to the exact levels % specified. Or by using specific levels for each channel of an image you % can convert a gray-scale image to any linear color gradient, according to % those levels. % % The format of the LevelizeImage method is: % % MagickBooleanType LevelizeImage(Image *image,const double black_point, % const double white_point,const double gamma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_point: The level to map zero (black) to. % % o white_point: The level to map QuantumRange (white) to. % % o gamma: adjust gamma by this factor before mapping values. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType LevelizeImage(Image *image, const double black_point,const double white_point,const double gamma, ExceptionInfo *exception) { #define LevelizeImageTag "Levelize/Image" #define LevelizeValue(x) ClampToQuantum(((MagickRealType) gamma_pow((double) \ (QuantumScale*(x)),gamma))*(white_point-black_point)+black_point) CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate and initialize levels map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Level colormap. */ if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(double) LevelizeValue(image->colormap[i].red); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(double) LevelizeValue( image->colormap[i].green); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(double) LevelizeValue(image->colormap[i].blue); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(double) LevelizeValue( image->colormap[i].alpha); } /* Level image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=LevelizeValue(q[j]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,LevelizeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L e v e l I m a g e C o l o r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LevelImageColors() maps the given color to "black" and "white" values, % linearly spreading out the colors, and level values on a channel by channel % bases, as per LevelImage(). The given colors allows you to specify % different level ranges for each of the color channels separately. % % If the boolean 'invert' is set true the image values will modifyed in the % reverse direction. That is any existing "black" and "white" colors in the % image will become the color values given, with all other values compressed % appropriatally. This effectivally maps a greyscale gradient into the given % color gradient. % % The format of the LevelImageColors method is: % % MagickBooleanType LevelImageColors(Image *image, % const PixelInfo *black_color,const PixelInfo *white_color, % const MagickBooleanType invert,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_color: The color to map black to/from % % o white_point: The color to map white to/from % % o invert: if true map the colors (levelize), rather than from (level) % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType LevelImageColors(Image *image, const PixelInfo *black_color,const PixelInfo *white_color, const MagickBooleanType invert,ExceptionInfo *exception) { ChannelType channel_mask; MagickStatusType status; /* Allocate and initialize levels map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((IsGrayColorspace(image->colorspace) != MagickFalse) && ((IsGrayColorspace(black_color->colorspace) == MagickFalse) || (IsGrayColorspace(white_color->colorspace) == MagickFalse))) (void) SetImageColorspace(image,sRGBColorspace,exception); status=MagickTrue; if (invert == MagickFalse) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,RedChannel); status&=LevelImage(image,black_color->red,white_color->red,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,GreenChannel); status&=LevelImage(image,black_color->green,white_color->green,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,BlueChannel); status&=LevelImage(image,black_color->blue,white_color->blue,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) && (image->colorspace == CMYKColorspace)) { channel_mask=SetImageChannelMask(image,BlackChannel); status&=LevelImage(image,black_color->black,white_color->black,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) && (image->alpha_trait != UndefinedPixelTrait)) { channel_mask=SetImageChannelMask(image,AlphaChannel); status&=LevelImage(image,black_color->alpha,white_color->alpha,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } } else { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,RedChannel); status&=LevelizeImage(image,black_color->red,white_color->red,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,GreenChannel); status&=LevelizeImage(image,black_color->green,white_color->green,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,BlueChannel); status&=LevelizeImage(image,black_color->blue,white_color->blue,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) && (image->colorspace == CMYKColorspace)) { channel_mask=SetImageChannelMask(image,BlackChannel); status&=LevelizeImage(image,black_color->black,white_color->black,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) && (image->alpha_trait != UndefinedPixelTrait)) { channel_mask=SetImageChannelMask(image,AlphaChannel); status&=LevelizeImage(image,black_color->alpha,white_color->alpha,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } } return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i n e a r S t r e t c h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LinearStretchImage() discards any pixels below the black point and above % the white point and levels the remaining pixels. % % The format of the LinearStretchImage method is: % % MagickBooleanType LinearStretchImage(Image *image, % const double black_point,const double white_point, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_point: the black point. % % o white_point: the white point. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType LinearStretchImage(Image *image, const double black_point,const double white_point,ExceptionInfo *exception) { #define LinearStretchImageTag "LinearStretch/Image" CacheView *image_view; double *histogram, intensity; MagickBooleanType status; ssize_t black, white, y; /* Allocate histogram and linear map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*histogram)); if (histogram == (double *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); /* Form histogram. */ (void) memset(histogram,0,(MaxMap+1)*sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { intensity=GetPixelIntensity(image,p); histogram[ScaleQuantumToMap(ClampToQuantum(intensity))]++; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Find the histogram boundaries by locating the black and white point levels. */ intensity=0.0; for (black=0; black < (ssize_t) MaxMap; black++) { intensity+=histogram[black]; if (intensity >= black_point) break; } intensity=0.0; for (white=(ssize_t) MaxMap; white != 0; white--) { intensity+=histogram[white]; if (intensity >= white_point) break; } histogram=(double *) RelinquishMagickMemory(histogram); status=LevelImage(image,(double) ScaleMapToQuantum((MagickRealType) black), (double) ScaleMapToQuantum((MagickRealType) white),1.0,exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o d u l a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ModulateImage() lets you control the brightness, saturation, and hue % of an image. Modulate represents the brightness, saturation, and hue % as one parameter (e.g. 90,150,100). If the image colorspace is HSL, the % modulation is lightness, saturation, and hue. For HWB, use blackness, % whiteness, and hue. And for HCL, use chrome, luma, and hue. % % The format of the ModulateImage method is: % % MagickBooleanType ModulateImage(Image *image,const char *modulate, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o modulate: Define the percent change in brightness, saturation, and hue. % % o exception: return any errors or warnings in this structure. % */ static inline void ModulateHCL(const double percent_hue, const double percent_chroma,const double percent_luma,double *red, double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToHCL(*red,*green,*blue,&hue,&chroma,&luma); hue+=fmod((percent_hue-100.0),200.0)/200.0; chroma*=0.01*percent_chroma; luma*=0.01*percent_luma; ConvertHCLToRGB(hue,chroma,luma,red,green,blue); } static inline void ModulateHCLp(const double percent_hue, const double percent_chroma,const double percent_luma,double *red, double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToHCLp(*red,*green,*blue,&hue,&chroma,&luma); hue+=fmod((percent_hue-100.0),200.0)/200.0; chroma*=0.01*percent_chroma; luma*=0.01*percent_luma; ConvertHCLpToRGB(hue,chroma,luma,red,green,blue); } static inline void ModulateHSB(const double percent_hue, const double percent_saturation,const double percent_brightness,double *red, double *green,double *blue) { double brightness, hue, saturation; /* Increase or decrease color brightness, saturation, or hue. */ ConvertRGBToHSB(*red,*green,*blue,&hue,&saturation,&brightness); hue+=fmod((percent_hue-100.0),200.0)/200.0; saturation*=0.01*percent_saturation; brightness*=0.01*percent_brightness; ConvertHSBToRGB(hue,saturation,brightness,red,green,blue); } static inline void ModulateHSI(const double percent_hue, const double percent_saturation,const double percent_intensity,double *red, double *green,double *blue) { double intensity, hue, saturation; /* Increase or decrease color intensity, saturation, or hue. */ ConvertRGBToHSI(*red,*green,*blue,&hue,&saturation,&intensity); hue+=fmod((percent_hue-100.0),200.0)/200.0; saturation*=0.01*percent_saturation; intensity*=0.01*percent_intensity; ConvertHSIToRGB(hue,saturation,intensity,red,green,blue); } static inline void ModulateHSL(const double percent_hue, const double percent_saturation,const double percent_lightness,double *red, double *green,double *blue) { double hue, lightness, saturation; /* Increase or decrease color lightness, saturation, or hue. */ ConvertRGBToHSL(*red,*green,*blue,&hue,&saturation,&lightness); hue+=fmod((percent_hue-100.0),200.0)/200.0; saturation*=0.01*percent_saturation; lightness*=0.01*percent_lightness; ConvertHSLToRGB(hue,saturation,lightness,red,green,blue); } static inline void ModulateHSV(const double percent_hue, const double percent_saturation,const double percent_value,double *red, double *green,double *blue) { double hue, saturation, value; /* Increase or decrease color value, saturation, or hue. */ ConvertRGBToHSV(*red,*green,*blue,&hue,&saturation,&value); hue+=fmod((percent_hue-100.0),200.0)/200.0; saturation*=0.01*percent_saturation; value*=0.01*percent_value; ConvertHSVToRGB(hue,saturation,value,red,green,blue); } static inline void ModulateHWB(const double percent_hue, const double percent_whiteness,const double percent_blackness,double *red, double *green,double *blue) { double blackness, hue, whiteness; /* Increase or decrease color blackness, whiteness, or hue. */ ConvertRGBToHWB(*red,*green,*blue,&hue,&whiteness,&blackness); hue+=fmod((percent_hue-100.0),200.0)/200.0; blackness*=0.01*percent_blackness; whiteness*=0.01*percent_whiteness; ConvertHWBToRGB(hue,whiteness,blackness,red,green,blue); } static inline void ModulateLCHab(const double percent_luma, const double percent_chroma,const double percent_hue,double *red, double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToLCHab(*red,*green,*blue,&luma,&chroma,&hue); luma*=0.01*percent_luma; chroma*=0.01*percent_chroma; hue+=fmod((percent_hue-100.0),200.0)/200.0; ConvertLCHabToRGB(luma,chroma,hue,red,green,blue); } static inline void ModulateLCHuv(const double percent_luma, const double percent_chroma,const double percent_hue,double *red, double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToLCHuv(*red,*green,*blue,&luma,&chroma,&hue); luma*=0.01*percent_luma; chroma*=0.01*percent_chroma; hue+=fmod((percent_hue-100.0),200.0)/200.0; ConvertLCHuvToRGB(luma,chroma,hue,red,green,blue); } MagickExport MagickBooleanType ModulateImage(Image *image,const char *modulate, ExceptionInfo *exception) { #define ModulateImageTag "Modulate/Image" CacheView *image_view; ColorspaceType colorspace; const char *artifact; double percent_brightness, percent_hue, percent_saturation; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; MagickStatusType flags; register ssize_t i; ssize_t y; /* Initialize modulate table. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (modulate == (char *) NULL) return(MagickFalse); if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); flags=ParseGeometry(modulate,&geometry_info); percent_brightness=geometry_info.rho; percent_saturation=geometry_info.sigma; if ((flags & SigmaValue) == 0) percent_saturation=100.0; percent_hue=geometry_info.xi; if ((flags & XiValue) == 0) percent_hue=100.0; colorspace=UndefinedColorspace; artifact=GetImageArtifact(image,"modulate:colorspace"); if (artifact != (const char *) NULL) colorspace=(ColorspaceType) ParseCommandOption(MagickColorspaceOptions, MagickFalse,artifact); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { double blue, green, red; /* Modulate image colormap. */ red=(double) image->colormap[i].red; green=(double) image->colormap[i].green; blue=(double) image->colormap[i].blue; switch (colorspace) { case HCLColorspace: { ModulateHCL(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HCLpColorspace: { ModulateHCLp(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSBColorspace: { ModulateHSB(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSIColorspace: { ModulateHSI(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSLColorspace: default: { ModulateHSL(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSVColorspace: { ModulateHSV(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HWBColorspace: { ModulateHWB(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case LCHColorspace: case LCHabColorspace: { ModulateLCHab(percent_brightness,percent_saturation,percent_hue, &red,&green,&blue); break; } case LCHuvColorspace: { ModulateLCHuv(percent_brightness,percent_saturation,percent_hue, &red,&green,&blue); break; } } image->colormap[i].red=red; image->colormap[i].green=green; image->colormap[i].blue=blue; } /* Modulate image. */ #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateModulateImage(image,percent_brightness,percent_hue, percent_saturation,colorspace,exception) != MagickFalse) return(MagickTrue); #endif status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double blue, green, red; red=(double) GetPixelRed(image,q); green=(double) GetPixelGreen(image,q); blue=(double) GetPixelBlue(image,q); switch (colorspace) { case HCLColorspace: { ModulateHCL(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HCLpColorspace: { ModulateHCLp(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSBColorspace: { ModulateHSB(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSLColorspace: default: { ModulateHSL(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSVColorspace: { ModulateHSV(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HWBColorspace: { ModulateHWB(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case LCHabColorspace: { ModulateLCHab(percent_brightness,percent_saturation,percent_hue, &red,&green,&blue); break; } case LCHColorspace: case LCHuvColorspace: { ModulateLCHuv(percent_brightness,percent_saturation,percent_hue, &red,&green,&blue); break; } } SetPixelRed(image,ClampToQuantum(red),q); SetPixelGreen(image,ClampToQuantum(green),q); SetPixelBlue(image,ClampToQuantum(blue),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ModulateImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N e g a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % NegateImage() negates the colors in the reference image. The grayscale % option means that only grayscale values within the image are negated. % % The format of the NegateImage method is: % % MagickBooleanType NegateImage(Image *image, % const MagickBooleanType grayscale,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o grayscale: If MagickTrue, only negate grayscale pixels within the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType NegateImage(Image *image, const MagickBooleanType grayscale,ExceptionInfo *exception) { #define NegateImageTag "Negate/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Negate colormap. */ if( grayscale != MagickFalse ) if ((image->colormap[i].red != image->colormap[i].green) || (image->colormap[i].green != image->colormap[i].blue)) continue; if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=QuantumRange-image->colormap[i].red; if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=QuantumRange-image->colormap[i].green; if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=QuantumRange-image->colormap[i].blue; } /* Negate image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); if( grayscale != MagickFalse ) { for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; if (IsPixelGray(image,q) != MagickFalse) { q+=GetPixelChannels(image); continue; } for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=QuantumRange-q[j]; } q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,NegateImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(MagickTrue); } /* Negate image. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=QuantumRange-q[j]; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,NegateImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N o r m a l i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % The NormalizeImage() method enhances the contrast of a color image by % mapping the darkest 2 percent of all pixel to black and the brightest % 1 percent to white. % % The format of the NormalizeImage method is: % % MagickBooleanType NormalizeImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType NormalizeImage(Image *image, ExceptionInfo *exception) { double black_point, white_point; black_point=(double) image->columns*image->rows*0.0015; white_point=(double) image->columns*image->rows*0.9995; return(ContrastStretchImage(image,black_point,white_point,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S i g m o i d a l C o n t r a s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SigmoidalContrastImage() adjusts the contrast of an image with a non-linear % sigmoidal contrast algorithm. Increase the contrast of the image using a % sigmoidal transfer function without saturating highlights or shadows. % Contrast indicates how much to increase the contrast (0 is none; 3 is % typical; 20 is pushing it); mid-point indicates where midtones fall in the % resultant image (0 is white; 50% is middle-gray; 100% is black). Set % sharpen to MagickTrue to increase the image contrast otherwise the contrast % is reduced. % % The format of the SigmoidalContrastImage method is: % % MagickBooleanType SigmoidalContrastImage(Image *image, % const MagickBooleanType sharpen,const char *levels, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o sharpen: Increase or decrease image contrast. % % o contrast: strength of the contrast, the larger the number the more % 'threshold-like' it becomes. % % o midpoint: midpoint of the function as a color value 0 to QuantumRange. % % o exception: return any errors or warnings in this structure. % */ /* ImageMagick 6 has a version of this function which uses LUTs. */ /* Sigmoidal function Sigmoidal with inflexion point moved to b and "slope constant" set to a. The first version, based on the hyperbolic tangent tanh, when combined with the scaling step, is an exact arithmetic clone of the the sigmoid function based on the logistic curve. The equivalence is based on the identity 1/(1+exp(-t)) = (1+tanh(t/2))/2 (http://de.wikipedia.org/wiki/Sigmoidfunktion) and the fact that the scaled sigmoidal derivation is invariant under affine transformations of the ordinate. The tanh version is almost certainly more accurate and cheaper. The 0.5 factor in the argument is to clone the legacy ImageMagick behavior. The reason for making the define depend on atanh even though it only uses tanh has to do with the construction of the inverse of the scaled sigmoidal. */ #if defined(MAGICKCORE_HAVE_ATANH) #define Sigmoidal(a,b,x) ( tanh((0.5*(a))*((x)-(b))) ) #else #define Sigmoidal(a,b,x) ( 1.0/(1.0+exp((a)*((b)-(x)))) ) #endif /* Scaled sigmoidal function: ( Sigmoidal(a,b,x) - Sigmoidal(a,b,0) ) / ( Sigmoidal(a,b,1) - Sigmoidal(a,b,0) ) See http://osdir.com/ml/video.image-magick.devel/2005-04/msg00006.html and http://www.cs.dartmouth.edu/farid/downloads/tutorials/fip.pdf. The limit of ScaledSigmoidal as a->0 is the identity, but a=0 gives a division by zero. This is fixed below by exiting immediately when contrast is small, leaving the image (or colormap) unmodified. This appears to be safe because the series expansion of the logistic sigmoidal function around x=b is 1/2-a*(b-x)/4+... so that the key denominator s(1)-s(0) is about a/4 (a/2 with tanh). */ #define ScaledSigmoidal(a,b,x) ( \ (Sigmoidal((a),(b),(x))-Sigmoidal((a),(b),0.0)) / \ (Sigmoidal((a),(b),1.0)-Sigmoidal((a),(b),0.0)) ) /* Inverse of ScaledSigmoidal, used for +sigmoidal-contrast. Because b may be 0 or 1, the argument of the hyperbolic tangent (resp. logistic sigmoidal) may be outside of the interval (-1,1) (resp. (0,1)), even when creating a LUT from in gamut values, hence the branching. In addition, HDRI may have out of gamut values. InverseScaledSigmoidal is not a two-sided inverse of ScaledSigmoidal: It is only a right inverse. This is unavoidable. */ static inline double InverseScaledSigmoidal(const double a,const double b, const double x) { const double sig0=Sigmoidal(a,b,0.0); const double sig1=Sigmoidal(a,b,1.0); const double argument=(sig1-sig0)*x+sig0; const double clamped= ( #if defined(MAGICKCORE_HAVE_ATANH) argument < -1+MagickEpsilon ? -1+MagickEpsilon : ( argument > 1-MagickEpsilon ? 1-MagickEpsilon : argument ) ); return(b+(2.0/a)*atanh(clamped)); #else argument < MagickEpsilon ? MagickEpsilon : ( argument > 1-MagickEpsilon ? 1-MagickEpsilon : argument ) ); return(b-log(1.0/clamped-1.0)/a); #endif } MagickExport MagickBooleanType SigmoidalContrastImage(Image *image, const MagickBooleanType sharpen,const double contrast,const double midpoint, ExceptionInfo *exception) { #define SigmoidalContrastImageTag "SigmoidalContrast/Image" #define ScaledSig(x) ( ClampToQuantum(QuantumRange* \ ScaledSigmoidal(contrast,QuantumScale*midpoint,QuantumScale*(x))) ) #define InverseScaledSig(x) ( ClampToQuantum(QuantumRange* \ InverseScaledSigmoidal(contrast,QuantumScale*midpoint,QuantumScale*(x))) ) CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Convenience macros. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); /* Side effect: may clamp values unless contrast<MagickEpsilon, in which case nothing is done. */ if (contrast < MagickEpsilon) return(MagickTrue); /* Sigmoidal-contrast enhance colormap. */ if (image->storage_class == PseudoClass) { register ssize_t i; if( sharpen != MagickFalse ) for (i=0; i < (ssize_t) image->colors; i++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(MagickRealType) ScaledSig( image->colormap[i].red); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(MagickRealType) ScaledSig( image->colormap[i].green); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(MagickRealType) ScaledSig( image->colormap[i].blue); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(MagickRealType) ScaledSig( image->colormap[i].alpha); } else for (i=0; i < (ssize_t) image->colors; i++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(MagickRealType) InverseScaledSig( image->colormap[i].red); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(MagickRealType) InverseScaledSig( image->colormap[i].green); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(MagickRealType) InverseScaledSig( image->colormap[i].blue); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(MagickRealType) InverseScaledSig( image->colormap[i].alpha); } } /* Sigmoidal-contrast enhance image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if( sharpen != MagickFalse ) q[i]=ScaledSig(q[i]); else q[i]=InverseScaledSig(q[i]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,SigmoidalContrastImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); }
null
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % EEEEE N N H H AAA N N CCCC EEEEE % % E NN N H H A A NN N C E % % EEE N N N HHHHH AAAAA N N N C EEE % % E N NN H H A A N NN C E % % EEEEE N N H H A A N N CCCC EEEEE % % % % % % MagickCore Image Enhancement Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/accelerate-private.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite-private.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/fx.h" #include "MagickCore/gem.h" #include "MagickCore/gem-private.h" #include "MagickCore/geometry.h" #include "MagickCore/histogram.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resample.h" #include "MagickCore/resample-private.h" #include "MagickCore/resource_.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/threshold.h" #include "MagickCore/token.h" #include "MagickCore/xml-tree.h" #include "MagickCore/xml-tree-private.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A u t o G a m m a I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AutoGammaImage() extract the 'mean' from the image and adjust the image % to try make set its gamma appropriatally. % % The format of the AutoGammaImage method is: % % MagickBooleanType AutoGammaImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image to auto-level % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType AutoGammaImage(Image *image, ExceptionInfo *exception) { double gamma, log_mean, mean, sans; MagickStatusType status; register ssize_t i; log_mean=log(0.5); if (image->channel_mask == DefaultChannels) { /* Apply gamma correction equally across all given channels. */ (void) GetImageMean(image,&mean,&sans,exception); gamma=log(mean*QuantumScale)/log_mean; return(LevelImage(image,0.0,(double) QuantumRange,gamma,exception)); } /* Auto-gamma each channel separately. */ status=MagickTrue; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { ChannelType channel_mask; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; channel_mask=SetImageChannelMask(image,(ChannelType) (1UL << i)); status=GetImageMean(image,&mean,&sans,exception); gamma=log(mean*QuantumScale)/log_mean; status&=LevelImage(image,0.0,(double) QuantumRange,gamma,exception); (void) SetImageChannelMask(image,channel_mask); if (status == MagickFalse) break; } return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A u t o L e v e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AutoLevelImage() adjusts the levels of a particular image channel by % scaling the minimum and maximum values to the full quantum range. % % The format of the LevelImage method is: % % MagickBooleanType AutoLevelImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image to auto-level % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType AutoLevelImage(Image *image, ExceptionInfo *exception) { return(MinMaxStretchImage(image,0.0,0.0,1.0,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B r i g h t n e s s C o n t r a s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BrightnessContrastImage() changes the brightness and/or contrast of an % image. It converts the brightness and contrast parameters into slope and % intercept and calls a polynomical function to apply to the image. % % The format of the BrightnessContrastImage method is: % % MagickBooleanType BrightnessContrastImage(Image *image, % const double brightness,const double contrast,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o brightness: the brightness percent (-100 .. 100). % % o contrast: the contrast percent (-100 .. 100). % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType BrightnessContrastImage(Image *image, const double brightness,const double contrast,ExceptionInfo *exception) { #define BrightnessContastImageTag "BrightnessContast/Image" double alpha, coefficients[2], intercept, slope; MagickBooleanType status; /* Compute slope and intercept. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); alpha=contrast; slope=tan((double) (MagickPI*(alpha/100.0+1.0)/4.0)); if (slope < 0.0) slope=0.0; intercept=brightness/100.0+((100-brightness)/200.0)*(1.0-slope); coefficients[0]=slope; coefficients[1]=intercept; status=FunctionImage(image,PolynomialFunction,2,coefficients,exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C L A H E I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CLAHEImage() is a variant of adaptive histogram equalization in which the % contrast amplification is limited, so as to reduce this problem of noise % amplification. % % Adapted from implementation by Karel Zuiderveld, karel@cv.ruu.nl in % "Graphics Gems IV", Academic Press, 1994. % % The format of the CLAHEImage method is: % % MagickBooleanType CLAHEImage(Image *image,const size_t width, % const size_t height,const size_t number_bins,const double clip_limit, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width: the width of the tile divisions to use in horizontal direction. % % o height: the height of the tile divisions to use in vertical direction. % % o number_bins: number of bins for histogram ("dynamic range"). % % o clip_limit: contrast limit for localised changes in contrast. A limit % less than 1 results in standard non-contrast limited AHE. % % o exception: return any errors or warnings in this structure. % */ typedef struct _RangeInfo { unsigned short min, max; } RangeInfo; static void ClipCLAHEHistogram(const double clip_limit,const size_t number_bins, size_t *histogram) { #define NumberCLAHEGrays (65536) register ssize_t i; size_t cumulative_excess, previous_excess, step; ssize_t excess; /* Compute total number of excess pixels. */ cumulative_excess=0; for (i=0; i < (ssize_t) number_bins; i++) { excess=(ssize_t) histogram[i]-(ssize_t) clip_limit; if (excess > 0) cumulative_excess+=excess; } /* Clip histogram and redistribute excess pixels across all bins. */ step=cumulative_excess/number_bins; excess=(ssize_t) (clip_limit-step); for (i=0; i < (ssize_t) number_bins; i++) { if ((double) histogram[i] > clip_limit) histogram[i]=(size_t) clip_limit; else if ((ssize_t) histogram[i] > excess) { cumulative_excess-=histogram[i]-excess; histogram[i]=(size_t) clip_limit; } else { cumulative_excess-=step; histogram[i]+=step; } } /* Redistribute remaining excess. */ do { register size_t *p; size_t *q; previous_excess=cumulative_excess; p=histogram; q=histogram+number_bins; while ((cumulative_excess != 0) && (p < q)) { step=number_bins/cumulative_excess; if (step < 1) step=1; for (p=histogram; (p < q) && (cumulative_excess != 0); p+=step) if ((double) *p < clip_limit) { (*p)++; cumulative_excess--; } p++; } } while ((cumulative_excess != 0) && (cumulative_excess < previous_excess)); } static void GenerateCLAHEHistogram(const RectangleInfo *clahe_info, const RectangleInfo *tile_info,const size_t number_bins, const unsigned short *lut,const unsigned short *pixels,size_t *histogram) { register const unsigned short *p; register ssize_t i; /* Classify the pixels into a gray histogram. */ for (i=0; i < (ssize_t) number_bins; i++) histogram[i]=0L; p=pixels; for (i=0; i < (ssize_t) tile_info->height; i++) { const unsigned short *q; q=p+tile_info->width; while (p < q) histogram[lut[*p++]]++; q+=clahe_info->width; p=q-tile_info->width; } } static void InterpolateCLAHE(const RectangleInfo *clahe_info,const size_t *Q12, const size_t *Q22,const size_t *Q11,const size_t *Q21, const RectangleInfo *tile,const unsigned short *lut,unsigned short *pixels) { ssize_t y; unsigned short intensity; /* Bilinear interpolate four tiles to eliminate boundary artifacts. */ for (y=(ssize_t) tile->height; y > 0; y--) { register ssize_t x; for (x=(ssize_t) tile->width; x > 0; x--) { intensity=lut[*pixels]; *pixels++=(unsigned short ) (PerceptibleReciprocal((double) tile->width* tile->height)*(y*(x*Q12[intensity]+(tile->width-x)*Q22[intensity])+ (tile->height-y)*(x*Q11[intensity]+(tile->width-x)*Q21[intensity]))); } pixels+=(clahe_info->width-tile->width); } } static void GenerateCLAHELut(const RangeInfo *range_info, const size_t number_bins,unsigned short *lut) { ssize_t i; unsigned short delta; /* Scale input image [intensity min,max] to [0,number_bins-1]. */ delta=(unsigned short) ((range_info->max-range_info->min)/number_bins+1); for (i=(ssize_t) range_info->min; i <= (ssize_t) range_info->max; i++) lut[i]=(unsigned short) ((i-range_info->min)/delta); } static void MapCLAHEHistogram(const RangeInfo *range_info, const size_t number_bins,const size_t number_pixels,size_t *histogram) { double scale, sum; register ssize_t i; /* Rescale histogram to range [min-intensity .. max-intensity]. */ scale=(double) (range_info->max-range_info->min)/number_pixels; sum=0.0; for (i=0; i < (ssize_t) number_bins; i++) { sum+=histogram[i]; histogram[i]=(size_t) (range_info->min+scale*sum); if (histogram[i] > range_info->max) histogram[i]=range_info->max; } } static MagickBooleanType CLAHE(const RectangleInfo *clahe_info, const RectangleInfo *tile_info,const RangeInfo *range_info, const size_t number_bins,const double clip_limit,unsigned short *pixels) { MemoryInfo *tile_cache; register unsigned short *p; size_t limit, *tiles; ssize_t y; unsigned short lut[NumberCLAHEGrays]; /* Constrast limited adapted histogram equalization. */ if (clip_limit == 1.0) return(MagickTrue); tile_cache=AcquireVirtualMemory((size_t) clahe_info->x*clahe_info->y, number_bins*sizeof(*tiles)); if (tile_cache == (MemoryInfo *) NULL) return(MagickFalse); tiles=(size_t *) GetVirtualMemoryBlob(tile_cache); limit=(size_t) (clip_limit*(tile_info->width*tile_info->height)/number_bins); if (limit < 1UL) limit=1UL; /* Generate greylevel mappings for each tile. */ GenerateCLAHELut(range_info,number_bins,lut); p=pixels; for (y=0; y < (ssize_t) clahe_info->y; y++) { register ssize_t x; for (x=0; x < (ssize_t) clahe_info->x; x++) { size_t *histogram; histogram=tiles+(number_bins*(y*clahe_info->x+x)); GenerateCLAHEHistogram(clahe_info,tile_info,number_bins,lut,p,histogram); ClipCLAHEHistogram((double) limit,number_bins,histogram); MapCLAHEHistogram(range_info,number_bins,tile_info->width* tile_info->height,histogram); p+=tile_info->width; } p+=clahe_info->width*(tile_info->height-1); } /* Interpolate greylevel mappings to get CLAHE image. */ p=pixels; for (y=0; y <= (ssize_t) clahe_info->y; y++) { OffsetInfo offset; RectangleInfo tile; register ssize_t x; tile.height=tile_info->height; tile.y=y-1; offset.y=tile.y+1; if (y == 0) { /* Top row. */ tile.height=tile_info->height >> 1; tile.y=0; offset.y=0; } else if (y == (ssize_t) clahe_info->y) { /* Bottom row. */ tile.height=(tile_info->height+1) >> 1; tile.y=clahe_info->y-1; offset.y=tile.y; } for (x=0; x <= (ssize_t) clahe_info->x; x++) { tile.width=tile_info->width; tile.x=x-1; offset.x=tile.x+1; if (x == 0) { /* Left column. */ tile.width=tile_info->width >> 1; tile.x=0; offset.x=0; } else if (x == (ssize_t) clahe_info->x) { /* Right column. */ tile.width=(tile_info->width+1) >> 1; tile.x=clahe_info->x-1; offset.x=tile.x; } InterpolateCLAHE(clahe_info, tiles+(number_bins*(tile.y*clahe_info->x+tile.x)), /* Q12 */ tiles+(number_bins*(tile.y*clahe_info->x+offset.x)), /* Q22 */ tiles+(number_bins*(offset.y*clahe_info->x+tile.x)), /* Q11 */ tiles+(number_bins*(offset.y*clahe_info->x+offset.x)), /* Q21 */ &tile,lut,p); p+=tile.width; } p+=clahe_info->width*(tile.height-1); } tile_cache=RelinquishVirtualMemory(tile_cache); return(MagickTrue); } MagickExport MagickBooleanType CLAHEImage(Image *image,const size_t width, const size_t height,const size_t number_bins,const double clip_limit, ExceptionInfo *exception) { #define CLAHEImageTag "CLAHE/Image" CacheView *image_view; ColorspaceType colorspace; MagickBooleanType status; MagickOffsetType progress; MemoryInfo *pixel_cache; RangeInfo range_info; RectangleInfo clahe_info, tile_info; size_t n; ssize_t y; unsigned short *pixels; /* Configure CLAHE parameters. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); range_info.min=0; range_info.max=NumberCLAHEGrays-1; tile_info.width=width; if (tile_info.width == 0) tile_info.width=image->columns >> 3; tile_info.height=height; if (tile_info.height == 0) tile_info.height=image->rows >> 3; tile_info.x=0; if ((image->columns % tile_info.width) != 0) tile_info.x=(ssize_t) tile_info.width-(image->columns % tile_info.width); tile_info.y=0; if ((image->rows % tile_info.height) != 0) tile_info.y=(ssize_t) tile_info.height-(image->rows % tile_info.height); clahe_info.width=image->columns+tile_info.x; clahe_info.height=image->rows+tile_info.y; clahe_info.x=(ssize_t) clahe_info.width/tile_info.width; clahe_info.y=(ssize_t) clahe_info.height/tile_info.height; pixel_cache=AcquireVirtualMemory(clahe_info.width,clahe_info.height* sizeof(*pixels)); if (pixel_cache == (MemoryInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); pixels=(unsigned short *) GetVirtualMemoryBlob(pixel_cache); colorspace=image->colorspace; if (TransformImageColorspace(image,LabColorspace,exception) == MagickFalse) { pixel_cache=RelinquishVirtualMemory(pixel_cache); return(MagickFalse); } /* Initialize CLAHE pixels. */ image_view=AcquireVirtualCacheView(image,exception); progress=0; status=MagickTrue; n=0; for (y=0; y < (ssize_t) clahe_info.height; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-(tile_info.x >> 1),y- (tile_info.y >> 1),clahe_info.width,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) clahe_info.width; x++) { pixels[n++]=ScaleQuantumToShort(p[0]); p+=GetPixelChannels(image); } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,CLAHEImageTag,progress,2* GetPixelChannels(image)); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); status=CLAHE(&clahe_info,&tile_info,&range_info,number_bins == 0 ? (size_t) 128 : MagickMin(number_bins,256),clip_limit,pixels); if (status == MagickFalse) (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); /* Push CLAHE pixels to CLAHE image. */ image_view=AcquireAuthenticCacheView(image,exception); n=clahe_info.width*(tile_info.y >> 1); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } n+=tile_info.x >> 1; for (x=0; x < (ssize_t) image->columns; x++) { q[0]=ScaleShortToQuantum(pixels[n++]); q+=GetPixelChannels(image); } n+=(clahe_info.width-image->columns-(tile_info.x >> 1)); if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,CLAHEImageTag,progress,2* GetPixelChannels(image)); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); pixel_cache=RelinquishVirtualMemory(pixel_cache); if (TransformImageColorspace(image,colorspace,exception) == MagickFalse) status=MagickFalse; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l u t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClutImage() replaces each color value in the given image, by using it as an % index to lookup a replacement color value in a Color Look UP Table in the % form of an image. The values are extracted along a diagonal of the CLUT % image so either a horizontal or vertial gradient image can be used. % % Typically this is used to either re-color a gray-scale image according to a % color gradient in the CLUT image, or to perform a freeform histogram % (level) adjustment according to the (typically gray-scale) gradient in the % CLUT image. % % When the 'channel' mask includes the matte/alpha transparency channel but % one image has no such channel it is assumed that that image is a simple % gray-scale image that will effect the alpha channel values, either for % gray-scale coloring (with transparent or semi-transparent colors), or % a histogram adjustment of existing alpha channel values. If both images % have matte channels, direct and normal indexing is applied, which is rarely % used. % % The format of the ClutImage method is: % % MagickBooleanType ClutImage(Image *image,Image *clut_image, % const PixelInterpolateMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image, which is replaced by indexed CLUT values % % o clut_image: the color lookup table image for replacement color values. % % o method: the pixel interpolation method. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ClutImage(Image *image,const Image *clut_image, const PixelInterpolateMethod method,ExceptionInfo *exception) { #define ClutImageTag "Clut/Image" CacheView *clut_view, *image_view; MagickBooleanType status; MagickOffsetType progress; PixelInfo *clut_map; register ssize_t i; ssize_t adjust, y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(clut_image != (Image *) NULL); assert(clut_image->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if ((IsGrayColorspace(image->colorspace) != MagickFalse) && (IsGrayColorspace(clut_image->colorspace) == MagickFalse)) (void) SetImageColorspace(image,sRGBColorspace,exception); clut_map=(PixelInfo *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*clut_map)); if (clut_map == (PixelInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); /* Clut image. */ status=MagickTrue; progress=0; adjust=(ssize_t) (clut_image->interpolate == IntegerInterpolatePixel ? 0 : 1); clut_view=AcquireVirtualCacheView(clut_image,exception); for (i=0; i <= (ssize_t) MaxMap; i++) { GetPixelInfo(clut_image,clut_map+i); status=InterpolatePixelInfo(clut_image,clut_view,method, (double) i*(clut_image->columns-adjust)/MaxMap,(double) i* (clut_image->rows-adjust)/MaxMap,clut_map+i,exception); if (status == MagickFalse) break; } clut_view=DestroyCacheView(clut_view); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { PixelInfo pixel; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } GetPixelInfo(image,&pixel); for (x=0; x < (ssize_t) image->columns; x++) { PixelTrait traits; GetPixelInfoPixel(image,q,&pixel); traits=GetPixelChannelTraits(image,RedPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.red=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.red))].red; traits=GetPixelChannelTraits(image,GreenPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.green=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.green))].green; traits=GetPixelChannelTraits(image,BluePixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.blue=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.blue))].blue; traits=GetPixelChannelTraits(image,BlackPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.black=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.black))].black; traits=GetPixelChannelTraits(image,AlphaPixelChannel); if ((traits & UpdatePixelTrait) != 0) pixel.alpha=clut_map[ScaleQuantumToMap(ClampToQuantum( pixel.alpha))].alpha; SetPixelViaPixelInfo(image,&pixel,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ClutImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); clut_map=(PixelInfo *) RelinquishMagickMemory(clut_map); if ((clut_image->alpha_trait != UndefinedPixelTrait) && ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)) (void) SetImageAlphaChannel(image,ActivateAlphaChannel,exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o l o r D e c i s i o n L i s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ColorDecisionListImage() accepts a lightweight Color Correction Collection % (CCC) file which solely contains one or more color corrections and applies % the correction to the image. Here is a sample CCC file: % % <ColorCorrectionCollection xmlns="urn:ASC:CDL:v1.2"> % <ColorCorrection id="cc03345"> % <SOPNode> % <Slope> 0.9 1.2 0.5 </Slope> % <Offset> 0.4 -0.5 0.6 </Offset> % <Power> 1.0 0.8 1.5 </Power> % </SOPNode> % <SATNode> % <Saturation> 0.85 </Saturation> % </SATNode> % </ColorCorrection> % </ColorCorrectionCollection> % % which includes the slop, offset, and power for each of the RGB channels % as well as the saturation. % % The format of the ColorDecisionListImage method is: % % MagickBooleanType ColorDecisionListImage(Image *image, % const char *color_correction_collection,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o color_correction_collection: the color correction collection in XML. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ColorDecisionListImage(Image *image, const char *color_correction_collection,ExceptionInfo *exception) { #define ColorDecisionListCorrectImageTag "ColorDecisionList/Image" typedef struct _Correction { double slope, offset, power; } Correction; typedef struct _ColorCorrection { Correction red, green, blue; double saturation; } ColorCorrection; CacheView *image_view; char token[MagickPathExtent]; ColorCorrection color_correction; const char *content, *p; MagickBooleanType status; MagickOffsetType progress; PixelInfo *cdl_map; register ssize_t i; ssize_t y; XMLTreeInfo *cc, *ccc, *sat, *sop; /* Allocate and initialize cdl maps. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (color_correction_collection == (const char *) NULL) return(MagickFalse); ccc=NewXMLTree((const char *) color_correction_collection,exception); if (ccc == (XMLTreeInfo *) NULL) return(MagickFalse); cc=GetXMLTreeChild(ccc,"ColorCorrection"); if (cc == (XMLTreeInfo *) NULL) { ccc=DestroyXMLTree(ccc); return(MagickFalse); } color_correction.red.slope=1.0; color_correction.red.offset=0.0; color_correction.red.power=1.0; color_correction.green.slope=1.0; color_correction.green.offset=0.0; color_correction.green.power=1.0; color_correction.blue.slope=1.0; color_correction.blue.offset=0.0; color_correction.blue.power=1.0; color_correction.saturation=0.0; sop=GetXMLTreeChild(cc,"SOPNode"); if (sop != (XMLTreeInfo *) NULL) { XMLTreeInfo *offset, *power, *slope; slope=GetXMLTreeChild(sop,"Slope"); if (slope != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(slope); p=(const char *) content; for (i=0; (*p != '\0') && (i < 3); i++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); switch (i) { case 0: { color_correction.red.slope=StringToDouble(token,(char **) NULL); break; } case 1: { color_correction.green.slope=StringToDouble(token, (char **) NULL); break; } case 2: { color_correction.blue.slope=StringToDouble(token, (char **) NULL); break; } } } } offset=GetXMLTreeChild(sop,"Offset"); if (offset != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(offset); p=(const char *) content; for (i=0; (*p != '\0') && (i < 3); i++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); switch (i) { case 0: { color_correction.red.offset=StringToDouble(token, (char **) NULL); break; } case 1: { color_correction.green.offset=StringToDouble(token, (char **) NULL); break; } case 2: { color_correction.blue.offset=StringToDouble(token, (char **) NULL); break; } } } } power=GetXMLTreeChild(sop,"Power"); if (power != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(power); p=(const char *) content; for (i=0; (*p != '\0') && (i < 3); i++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); switch (i) { case 0: { color_correction.red.power=StringToDouble(token,(char **) NULL); break; } case 1: { color_correction.green.power=StringToDouble(token, (char **) NULL); break; } case 2: { color_correction.blue.power=StringToDouble(token, (char **) NULL); break; } } } } } sat=GetXMLTreeChild(cc,"SATNode"); if (sat != (XMLTreeInfo *) NULL) { XMLTreeInfo *saturation; saturation=GetXMLTreeChild(sat,"Saturation"); if (saturation != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(saturation); p=(const char *) content; GetNextToken(p,&p,MagickPathExtent,token); color_correction.saturation=StringToDouble(token,(char **) NULL); } } ccc=DestroyXMLTree(ccc); if (image->debug != MagickFalse) { (void) LogMagickEvent(TransformEvent,GetMagickModule(), " Color Correction Collection:"); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.red.slope: %g",color_correction.red.slope); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.red.offset: %g",color_correction.red.offset); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.red.power: %g",color_correction.red.power); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.green.slope: %g",color_correction.green.slope); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.green.offset: %g",color_correction.green.offset); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.green.power: %g",color_correction.green.power); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.blue.slope: %g",color_correction.blue.slope); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.blue.offset: %g",color_correction.blue.offset); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.blue.power: %g",color_correction.blue.power); (void) LogMagickEvent(TransformEvent,GetMagickModule(), " color_correction.saturation: %g",color_correction.saturation); } cdl_map=(PixelInfo *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*cdl_map)); if (cdl_map == (PixelInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); for (i=0; i <= (ssize_t) MaxMap; i++) { cdl_map[i].red=(double) ScaleMapToQuantum((double) (MaxMap*(pow(color_correction.red.slope*i/MaxMap+ color_correction.red.offset,color_correction.red.power)))); cdl_map[i].green=(double) ScaleMapToQuantum((double) (MaxMap*(pow(color_correction.green.slope*i/MaxMap+ color_correction.green.offset,color_correction.green.power)))); cdl_map[i].blue=(double) ScaleMapToQuantum((double) (MaxMap*(pow(color_correction.blue.slope*i/MaxMap+ color_correction.blue.offset,color_correction.blue.power)))); } if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Apply transfer function to colormap. */ double luma; luma=0.21267f*image->colormap[i].red+0.71526*image->colormap[i].green+ 0.07217f*image->colormap[i].blue; image->colormap[i].red=luma+color_correction.saturation*cdl_map[ ScaleQuantumToMap(ClampToQuantum(image->colormap[i].red))].red-luma; image->colormap[i].green=luma+color_correction.saturation*cdl_map[ ScaleQuantumToMap(ClampToQuantum(image->colormap[i].green))].green-luma; image->colormap[i].blue=luma+color_correction.saturation*cdl_map[ ScaleQuantumToMap(ClampToQuantum(image->colormap[i].blue))].blue-luma; } /* Apply transfer function to image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double luma; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { luma=0.21267f*GetPixelRed(image,q)+0.71526*GetPixelGreen(image,q)+ 0.07217f*GetPixelBlue(image,q); SetPixelRed(image,ClampToQuantum(luma+color_correction.saturation* (cdl_map[ScaleQuantumToMap(GetPixelRed(image,q))].red-luma)),q); SetPixelGreen(image,ClampToQuantum(luma+color_correction.saturation* (cdl_map[ScaleQuantumToMap(GetPixelGreen(image,q))].green-luma)),q); SetPixelBlue(image,ClampToQuantum(luma+color_correction.saturation* (cdl_map[ScaleQuantumToMap(GetPixelBlue(image,q))].blue-luma)),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ColorDecisionListCorrectImageTag, progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); cdl_map=(PixelInfo *) RelinquishMagickMemory(cdl_map); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o n t r a s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ContrastImage() enhances the intensity differences between the lighter and % darker elements of the image. Set sharpen to a MagickTrue to increase the % image contrast otherwise the contrast is reduced. % % The format of the ContrastImage method is: % % MagickBooleanType ContrastImage(Image *image, % const MagickBooleanType sharpen,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o sharpen: Increase or decrease image contrast. % % o exception: return any errors or warnings in this structure. % */ static void Contrast(const int sign,double *red,double *green,double *blue) { double brightness, hue, saturation; /* Enhance contrast: dark color become darker, light color become lighter. */ assert(red != (double *) NULL); assert(green != (double *) NULL); assert(blue != (double *) NULL); hue=0.0; saturation=0.0; brightness=0.0; ConvertRGBToHSB(*red,*green,*blue,&hue,&saturation,&brightness); brightness+=0.5*sign*(0.5*(sin((double) (MagickPI*(brightness-0.5)))+1.0)- brightness); if (brightness > 1.0) brightness=1.0; else if (brightness < 0.0) brightness=0.0; ConvertHSBToRGB(hue,saturation,brightness,red,green,blue); } MagickExport MagickBooleanType ContrastImage(Image *image, const MagickBooleanType sharpen,ExceptionInfo *exception) { #define ContrastImageTag "Contrast/Image" CacheView *image_view; int sign; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateContrastImage(image,sharpen,exception) != MagickFalse) return(MagickTrue); #endif if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); sign=sharpen != MagickFalse ? 1 : -1; if (image->storage_class == PseudoClass) { /* Contrast enhance colormap. */ for (i=0; i < (ssize_t) image->colors; i++) { double blue, green, red; red=(double) image->colormap[i].red; green=(double) image->colormap[i].green; blue=(double) image->colormap[i].blue; Contrast(sign,&red,&green,&blue); image->colormap[i].red=(MagickRealType) red; image->colormap[i].green=(MagickRealType) green; image->colormap[i].blue=(MagickRealType) blue; } } /* Contrast enhance image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double blue, green, red; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { red=(double) GetPixelRed(image,q); green=(double) GetPixelGreen(image,q); blue=(double) GetPixelBlue(image,q); Contrast(sign,&red,&green,&blue); SetPixelRed(image,ClampToQuantum(red),q); SetPixelGreen(image,ClampToQuantum(green),q); SetPixelBlue(image,ClampToQuantum(blue),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ContrastImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o n t r a s t S t r e t c h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ContrastStretchImage() is a simple image enhancement technique that attempts % to improve the contrast in an image by 'stretching' the range of intensity % values it contains to span a desired range of values. It differs from the % more sophisticated histogram equalization in that it can only apply a % linear scaling function to the image pixel values. As a result the % 'enhancement' is less harsh. % % The format of the ContrastStretchImage method is: % % MagickBooleanType ContrastStretchImage(Image *image, % const char *levels,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_point: the black point. % % o white_point: the white point. % % o levels: Specify the levels where the black and white points have the % range of 0 to number-of-pixels (e.g. 1%, 10x90%, etc.). % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ContrastStretchImage(Image *image, const double black_point,const double white_point,ExceptionInfo *exception) { #define MaxRange(color) ((double) ScaleQuantumToMap((Quantum) (color))) #define ContrastStretchImageTag "ContrastStretch/Image" CacheView *image_view; double *black, *histogram, *stretch_map, *white; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate histogram and stretch map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageGray(image,exception) != MagickFalse) (void) SetImageColorspace(image,GRAYColorspace,exception); black=(double *) AcquireQuantumMemory(MaxPixelChannels,sizeof(*black)); white=(double *) AcquireQuantumMemory(MaxPixelChannels,sizeof(*white)); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels* sizeof(*histogram)); stretch_map=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels* sizeof(*stretch_map)); if ((black == (double *) NULL) || (white == (double *) NULL) || (histogram == (double *) NULL) || (stretch_map == (double *) NULL)) { if (stretch_map != (double *) NULL) stretch_map=(double *) RelinquishMagickMemory(stretch_map); if (histogram != (double *) NULL) histogram=(double *) RelinquishMagickMemory(histogram); if (white != (double *) NULL) white=(double *) RelinquishMagickMemory(white); if (black != (double *) NULL) black=(double *) RelinquishMagickMemory(black); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } /* Form histogram. */ status=MagickTrue; (void) memset(histogram,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double pixel; pixel=GetPixelIntensity(image,p); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { if (image->channel_mask != DefaultChannels) pixel=(double) p[i]; histogram[GetPixelChannels(image)*ScaleQuantumToMap( ClampToQuantum(pixel))+i]++; } p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Find the histogram boundaries by locating the black/white levels. */ for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; register ssize_t j; black[i]=0.0; white[i]=MaxRange(QuantumRange); intensity=0.0; for (j=0; j <= (ssize_t) MaxMap; j++) { intensity+=histogram[GetPixelChannels(image)*j+i]; if (intensity > black_point) break; } black[i]=(double) j; intensity=0.0; for (j=(ssize_t) MaxMap; j != 0; j--) { intensity+=histogram[GetPixelChannels(image)*j+i]; if (intensity > ((double) image->columns*image->rows-white_point)) break; } white[i]=(double) j; } histogram=(double *) RelinquishMagickMemory(histogram); /* Stretch the histogram to create the stretched image mapping. */ (void) memset(stretch_map,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*stretch_map)); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { register ssize_t j; for (j=0; j <= (ssize_t) MaxMap; j++) { double gamma; gamma=PerceptibleReciprocal(white[i]-black[i]); if (j < (ssize_t) black[i]) stretch_map[GetPixelChannels(image)*j+i]=0.0; else if (j > (ssize_t) white[i]) stretch_map[GetPixelChannels(image)*j+i]=(double) QuantumRange; else if (black[i] != white[i]) stretch_map[GetPixelChannels(image)*j+i]=(double) ScaleMapToQuantum( (double) (MaxMap*gamma*(j-black[i]))); } } if (image->storage_class == PseudoClass) { register ssize_t j; /* Stretch-contrast colormap. */ for (j=0; j < (ssize_t) image->colors; j++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,RedPixelChannel); image->colormap[j].red=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+i]; } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,GreenPixelChannel); image->colormap[j].green=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+i]; } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,BluePixelChannel); image->colormap[j].blue=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+i]; } if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,AlphaPixelChannel); image->colormap[j].alpha=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+i]; } } } /* Stretch-contrast image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if (black[j] == white[j]) continue; q[j]=ClampToQuantum(stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(q[j])+j]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ContrastStretchImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); stretch_map=(double *) RelinquishMagickMemory(stretch_map); white=(double *) RelinquishMagickMemory(white); black=(double *) RelinquishMagickMemory(black); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E n h a n c e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EnhanceImage() applies a digital filter that improves the quality of a % noisy image. % % The format of the EnhanceImage method is: % % Image *EnhanceImage(const Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *EnhanceImage(const Image *image,ExceptionInfo *exception) { #define EnhanceImageTag "Enhance/Image" #define EnhancePixel(weight) \ mean=QuantumScale*((double) GetPixelRed(image,r)+pixel.red)/2.0; \ distance=QuantumScale*((double) GetPixelRed(image,r)-pixel.red); \ distance_squared=(4.0+mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelGreen(image,r)+pixel.green)/2.0; \ distance=QuantumScale*((double) GetPixelGreen(image,r)-pixel.green); \ distance_squared+=(7.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelBlue(image,r)+pixel.blue)/2.0; \ distance=QuantumScale*((double) GetPixelBlue(image,r)-pixel.blue); \ distance_squared+=(5.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelBlack(image,r)+pixel.black)/2.0; \ distance=QuantumScale*((double) GetPixelBlack(image,r)-pixel.black); \ distance_squared+=(5.0-mean)*distance*distance; \ mean=QuantumScale*((double) GetPixelAlpha(image,r)+pixel.alpha)/2.0; \ distance=QuantumScale*((double) GetPixelAlpha(image,r)-pixel.alpha); \ distance_squared+=(5.0-mean)*distance*distance; \ if (distance_squared < 0.069) \ { \ aggregate.red+=(weight)*GetPixelRed(image,r); \ aggregate.green+=(weight)*GetPixelGreen(image,r); \ aggregate.blue+=(weight)*GetPixelBlue(image,r); \ aggregate.black+=(weight)*GetPixelBlack(image,r); \ aggregate.alpha+=(weight)*GetPixelAlpha(image,r); \ total_weight+=(weight); \ } \ r+=GetPixelChannels(image); CacheView *enhance_view, *image_view; Image *enhance_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Initialize enhanced image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); enhance_image=CloneImage(image,0,0,MagickTrue, exception); if (enhance_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(enhance_image,DirectClass,exception) == MagickFalse) { enhance_image=DestroyImage(enhance_image); return((Image *) NULL); } /* Enhance image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); enhance_view=AcquireAuthenticCacheView(enhance_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,enhance_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { PixelInfo pixel; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; ssize_t center; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-2,y-2,image->columns+4,5,exception); q=QueueCacheViewAuthenticPixels(enhance_view,0,y,enhance_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } center=(ssize_t) GetPixelChannels(image)*(2*(image->columns+4)+2); GetPixelInfo(image,&pixel); for (x=0; x < (ssize_t) image->columns; x++) { double distance, distance_squared, mean, total_weight; PixelInfo aggregate; register const Quantum *magick_restrict r; GetPixelInfo(image,&aggregate); total_weight=0.0; GetPixelInfoPixel(image,p+center,&pixel); r=p; EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0); EnhancePixel(8.0); EnhancePixel(5.0); r=p+GetPixelChannels(image)*(image->columns+4); EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0); EnhancePixel(20.0); EnhancePixel(8.0); r=p+2*GetPixelChannels(image)*(image->columns+4); EnhancePixel(10.0); EnhancePixel(40.0); EnhancePixel(80.0); EnhancePixel(40.0); EnhancePixel(10.0); r=p+3*GetPixelChannels(image)*(image->columns+4); EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0); EnhancePixel(20.0); EnhancePixel(8.0); r=p+4*GetPixelChannels(image)*(image->columns+4); EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0); EnhancePixel(8.0); EnhancePixel(5.0); if (total_weight > MagickEpsilon) { pixel.red=((aggregate.red+total_weight/2.0)/total_weight); pixel.green=((aggregate.green+total_weight/2.0)/total_weight); pixel.blue=((aggregate.blue+total_weight/2.0)/total_weight); pixel.black=((aggregate.black+total_weight/2.0)/total_weight); pixel.alpha=((aggregate.alpha+total_weight/2.0)/total_weight); } SetPixelViaPixelInfo(enhance_image,&pixel,q); p+=GetPixelChannels(image); q+=GetPixelChannels(enhance_image); } if (SyncCacheViewAuthenticPixels(enhance_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,EnhanceImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } enhance_view=DestroyCacheView(enhance_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) enhance_image=DestroyImage(enhance_image); return(enhance_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E q u a l i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EqualizeImage() applies a histogram equalization to the image. % % The format of the EqualizeImage method is: % % MagickBooleanType EqualizeImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType EqualizeImage(Image *image, ExceptionInfo *exception) { #define EqualizeImageTag "Equalize/Image" CacheView *image_view; double black[CompositePixelChannel+1], *equalize_map, *histogram, *map, white[CompositePixelChannel+1]; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate and initialize histogram arrays. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateEqualizeImage(image,exception) != MagickFalse) return(MagickTrue); #endif if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); equalize_map=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels* sizeof(*equalize_map)); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels* sizeof(*histogram)); map=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels*sizeof(*map)); if ((equalize_map == (double *) NULL) || (histogram == (double *) NULL) || (map == (double *) NULL)) { if (map != (double *) NULL) map=(double *) RelinquishMagickMemory(map); if (histogram != (double *) NULL) histogram=(double *) RelinquishMagickMemory(histogram); if (equalize_map != (double *) NULL) equalize_map=(double *) RelinquishMagickMemory(equalize_map); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } /* Form histogram. */ status=MagickTrue; (void) memset(histogram,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; intensity=(double) p[i]; if ((image->channel_mask & SyncChannels) != 0) intensity=GetPixelIntensity(image,p); histogram[GetPixelChannels(image)*ScaleQuantumToMap( ClampToQuantum(intensity))+i]++; } p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Integrate the histogram to get the equalization map. */ for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; register ssize_t j; intensity=0.0; for (j=0; j <= (ssize_t) MaxMap; j++) { intensity+=histogram[GetPixelChannels(image)*j+i]; map[GetPixelChannels(image)*j+i]=intensity; } } (void) memset(equalize_map,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*equalize_map)); (void) memset(black,0,sizeof(*black)); (void) memset(white,0,sizeof(*white)); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { register ssize_t j; black[i]=map[i]; white[i]=map[GetPixelChannels(image)*MaxMap+i]; if (black[i] != white[i]) for (j=0; j <= (ssize_t) MaxMap; j++) equalize_map[GetPixelChannels(image)*j+i]=(double) ScaleMapToQuantum((double) ((MaxMap*(map[ GetPixelChannels(image)*j+i]-black[i]))/(white[i]-black[i]))); } histogram=(double *) RelinquishMagickMemory(histogram); map=(double *) RelinquishMagickMemory(map); if (image->storage_class == PseudoClass) { register ssize_t j; /* Equalize colormap. */ for (j=0; j < (ssize_t) image->colors; j++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel = GetPixelChannelChannel(image, RedPixelChannel); if (black[channel] != white[channel]) image->colormap[j].red=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+ channel]; } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel = GetPixelChannelChannel(image, GreenPixelChannel); if (black[channel] != white[channel]) image->colormap[j].green=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+ channel]; } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel = GetPixelChannelChannel(image, BluePixelChannel); if (black[channel] != white[channel]) image->colormap[j].blue=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+ channel]; } if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel = GetPixelChannelChannel(image, AlphaPixelChannel); if (black[channel] != white[channel]) image->colormap[j].alpha=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+ channel]; } } } /* Equalize image. */ progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if (((traits & UpdatePixelTrait) == 0) || (black[j] == white[j])) continue; q[j]=ClampToQuantum(equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(q[j])+j]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,EqualizeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); equalize_map=(double *) RelinquishMagickMemory(equalize_map); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G a m m a I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GammaImage() gamma-corrects a particular image channel. The same % image viewed on different devices will have perceptual differences in the % way the image's intensities are represented on the screen. Specify % individual gamma levels for the red, green, and blue channels, or adjust % all three with the gamma parameter. Values typically range from 0.8 to 2.3. % % You can also reduce the influence of a particular channel with a gamma % value of 0. % % The format of the GammaImage method is: % % MagickBooleanType GammaImage(Image *image,const double gamma, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o level: the image gamma as a string (e.g. 1.6,1.2,1.0). % % o gamma: the image gamma. % */ static inline double gamma_pow(const double value,const double gamma) { return(value < 0.0 ? value : pow(value,gamma)); } MagickExport MagickBooleanType GammaImage(Image *image,const double gamma, ExceptionInfo *exception) { #define GammaImageTag "Gamma/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; Quantum *gamma_map; register ssize_t i; ssize_t y; /* Allocate and initialize gamma maps. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (gamma == 1.0) return(MagickTrue); gamma_map=(Quantum *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*gamma_map)); if (gamma_map == (Quantum *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); (void) memset(gamma_map,0,(MaxMap+1)*sizeof(*gamma_map)); if (gamma != 0.0) for (i=0; i <= (ssize_t) MaxMap; i++) gamma_map[i]=ScaleMapToQuantum((double) (MaxMap*pow((double) i/ MaxMap,1.0/gamma))); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Gamma-correct colormap. */ if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].red))]; if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].green))]; if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].blue))]; if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(double) gamma_map[ScaleQuantumToMap( ClampToQuantum(image->colormap[i].alpha))]; } /* Gamma-correct image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=gamma_map[ScaleQuantumToMap(ClampToQuantum((MagickRealType) q[j]))]; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,GammaImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); gamma_map=(Quantum *) RelinquishMagickMemory(gamma_map); if (image->gamma != 0.0) image->gamma*=gamma; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G r a y s c a l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GrayscaleImage() converts the image to grayscale. % % The format of the GrayscaleImage method is: % % MagickBooleanType GrayscaleImage(Image *image, % const PixelIntensityMethod method ,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o method: the pixel intensity method. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GrayscaleImage(Image *image, const PixelIntensityMethod method,ExceptionInfo *exception) { #define GrayscaleImageTag "Grayscale/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateGrayscaleImage(image,method,exception) != MagickFalse) { image->intensity=method; image->type=GrayscaleType; if ((method == Rec601LuminancePixelIntensityMethod) || (method == Rec709LuminancePixelIntensityMethod)) return(SetImageColorspace(image,LinearGRAYColorspace,exception)); return(SetImageColorspace(image,GRAYColorspace,exception)); } #endif /* Grayscale image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType blue, green, red, intensity; red=(MagickRealType) GetPixelRed(image,q); green=(MagickRealType) GetPixelGreen(image,q); blue=(MagickRealType) GetPixelBlue(image,q); intensity=0.0; switch (method) { case AveragePixelIntensityMethod: { intensity=(red+green+blue)/3.0; break; } case BrightnessPixelIntensityMethod: { intensity=MagickMax(MagickMax(red,green),blue); break; } case LightnessPixelIntensityMethod: { intensity=(MagickMin(MagickMin(red,green),blue)+ MagickMax(MagickMax(red,green),blue))/2.0; break; } case MSPixelIntensityMethod: { intensity=(MagickRealType) (((double) red*red+green*green+ blue*blue)/3.0); break; } case Rec601LumaPixelIntensityMethod: { if (image->colorspace == RGBColorspace) { red=EncodePixelGamma(red); green=EncodePixelGamma(green); blue=EncodePixelGamma(blue); } intensity=0.298839*red+0.586811*green+0.114350*blue; break; } case Rec601LuminancePixelIntensityMethod: { if (image->colorspace == sRGBColorspace) { red=DecodePixelGamma(red); green=DecodePixelGamma(green); blue=DecodePixelGamma(blue); } intensity=0.298839*red+0.586811*green+0.114350*blue; break; } case Rec709LumaPixelIntensityMethod: default: { if (image->colorspace == RGBColorspace) { red=EncodePixelGamma(red); green=EncodePixelGamma(green); blue=EncodePixelGamma(blue); } intensity=0.212656*red+0.715158*green+0.072186*blue; break; } case Rec709LuminancePixelIntensityMethod: { if (image->colorspace == sRGBColorspace) { red=DecodePixelGamma(red); green=DecodePixelGamma(green); blue=DecodePixelGamma(blue); } intensity=0.212656*red+0.715158*green+0.072186*blue; break; } case RMSPixelIntensityMethod: { intensity=(MagickRealType) (sqrt((double) red*red+green*green+ blue*blue)/sqrt(3.0)); break; } } SetPixelGray(image,ClampToQuantum(intensity),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,GrayscaleImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); image->intensity=method; image->type=GrayscaleType; if ((method == Rec601LuminancePixelIntensityMethod) || (method == Rec709LuminancePixelIntensityMethod)) return(SetImageColorspace(image,LinearGRAYColorspace,exception)); return(SetImageColorspace(image,GRAYColorspace,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % H a l d C l u t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % HaldClutImage() applies a Hald color lookup table to the image. A Hald % color lookup table is a 3-dimensional color cube mapped to 2 dimensions. % Create it with the HALD coder. You can apply any color transformation to % the Hald image and then use this method to apply the transform to the % image. % % The format of the HaldClutImage method is: % % MagickBooleanType HaldClutImage(Image *image,Image *hald_image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image, which is replaced by indexed CLUT values % % o hald_image: the color lookup table image for replacement color values. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType HaldClutImage(Image *image, const Image *hald_image,ExceptionInfo *exception) { #define HaldClutImageTag "Clut/Image" typedef struct _HaldInfo { double x, y, z; } HaldInfo; CacheView *hald_view, *image_view; double width; MagickBooleanType status; MagickOffsetType progress; PixelInfo zero; size_t cube_size, length, level; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(hald_image != (Image *) NULL); assert(hald_image->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); /* Hald clut image. */ status=MagickTrue; progress=0; length=(size_t) MagickMin((MagickRealType) hald_image->columns, (MagickRealType) hald_image->rows); for (level=2; (level*level*level) < length; level++) ; level*=level; cube_size=level*level; width=(double) hald_image->columns; GetPixelInfo(hald_image,&zero); hald_view=AcquireVirtualCacheView(hald_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double offset; HaldInfo point; PixelInfo pixel, pixel1, pixel2, pixel3, pixel4; point.x=QuantumScale*(level-1.0)*GetPixelRed(image,q); point.y=QuantumScale*(level-1.0)*GetPixelGreen(image,q); point.z=QuantumScale*(level-1.0)*GetPixelBlue(image,q); offset=point.x+level*floor(point.y)+cube_size*floor(point.z); point.x-=floor(point.x); point.y-=floor(point.y); point.z-=floor(point.z); pixel1=zero; status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, fmod(offset,width),floor(offset/width),&pixel1,exception); if (status == MagickFalse) break; pixel2=zero; status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, fmod(offset+level,width),floor((offset+level)/width),&pixel2,exception); if (status == MagickFalse) break; pixel3=zero; CompositePixelInfoAreaBlend(&pixel1,pixel1.alpha,&pixel2,pixel2.alpha, point.y,&pixel3); offset+=cube_size; status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, fmod(offset,width),floor(offset/width),&pixel1,exception); if (status == MagickFalse) break; status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, fmod(offset+level,width),floor((offset+level)/width),&pixel2,exception); if (status == MagickFalse) break; pixel4=zero; CompositePixelInfoAreaBlend(&pixel1,pixel1.alpha,&pixel2,pixel2.alpha, point.y,&pixel4); pixel=zero; CompositePixelInfoAreaBlend(&pixel3,pixel3.alpha,&pixel4,pixel4.alpha, point.z,&pixel); if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) SetPixelRed(image,ClampToQuantum(pixel.red),q); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) SetPixelGreen(image,ClampToQuantum(pixel.green),q); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) SetPixelBlue(image,ClampToQuantum(pixel.blue),q); if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) && (image->colorspace == CMYKColorspace)) SetPixelBlack(image,ClampToQuantum(pixel.black),q); if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) && (image->alpha_trait != UndefinedPixelTrait)) SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,HaldClutImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } hald_view=DestroyCacheView(hald_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L e v e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LevelImage() adjusts the levels of a particular image channel by % scaling the colors falling between specified white and black points to % the full available quantum range. % % The parameters provided represent the black, and white points. The black % point specifies the darkest color in the image. Colors darker than the % black point are set to zero. White point specifies the lightest color in % the image. Colors brighter than the white point are set to the maximum % quantum value. % % If a '!' flag is given, map black and white colors to the given levels % rather than mapping those levels to black and white. See % LevelizeImage() below. % % Gamma specifies a gamma correction to apply to the image. % % The format of the LevelImage method is: % % MagickBooleanType LevelImage(Image *image,const double black_point, % const double white_point,const double gamma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_point: The level to map zero (black) to. % % o white_point: The level to map QuantumRange (white) to. % % o exception: return any errors or warnings in this structure. % */ static inline double LevelPixel(const double black_point, const double white_point,const double gamma,const double pixel) { double level_pixel, scale; scale=PerceptibleReciprocal(white_point-black_point); level_pixel=QuantumRange*gamma_pow(scale*((double) pixel-black_point), 1.0/gamma); return(level_pixel); } MagickExport MagickBooleanType LevelImage(Image *image,const double black_point, const double white_point,const double gamma,ExceptionInfo *exception) { #define LevelImageTag "Level/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate and initialize levels map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Level colormap. */ if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(double) ClampToQuantum(LevelPixel(black_point, white_point,gamma,image->colormap[i].red)); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(double) ClampToQuantum(LevelPixel(black_point, white_point,gamma,image->colormap[i].green)); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(double) ClampToQuantum(LevelPixel(black_point, white_point,gamma,image->colormap[i].blue)); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(double) ClampToQuantum(LevelPixel(black_point, white_point,gamma,image->colormap[i].alpha)); } /* Level image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=ClampToQuantum(LevelPixel(black_point,white_point,gamma, (double) q[j])); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,LevelImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); (void) ClampImage(image,exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L e v e l i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LevelizeImage() applies the reversed LevelImage() operation to just % the specific channels specified. It compresses the full range of color % values, so that they lie between the given black and white points. Gamma is % applied before the values are mapped. % % LevelizeImage() can be called with by using a +level command line % API option, or using a '!' on a -level or LevelImage() geometry string. % % It can be used to de-contrast a greyscale image to the exact levels % specified. Or by using specific levels for each channel of an image you % can convert a gray-scale image to any linear color gradient, according to % those levels. % % The format of the LevelizeImage method is: % % MagickBooleanType LevelizeImage(Image *image,const double black_point, % const double white_point,const double gamma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_point: The level to map zero (black) to. % % o white_point: The level to map QuantumRange (white) to. % % o gamma: adjust gamma by this factor before mapping values. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType LevelizeImage(Image *image, const double black_point,const double white_point,const double gamma, ExceptionInfo *exception) { #define LevelizeImageTag "Levelize/Image" #define LevelizeValue(x) ClampToQuantum(((MagickRealType) gamma_pow((double) \ (QuantumScale*(x)),gamma))*(white_point-black_point)+black_point) CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate and initialize levels map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Level colormap. */ if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(double) LevelizeValue(image->colormap[i].red); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(double) LevelizeValue( image->colormap[i].green); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(double) LevelizeValue(image->colormap[i].blue); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(double) LevelizeValue( image->colormap[i].alpha); } /* Level image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=LevelizeValue(q[j]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,LevelizeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L e v e l I m a g e C o l o r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LevelImageColors() maps the given color to "black" and "white" values, % linearly spreading out the colors, and level values on a channel by channel % bases, as per LevelImage(). The given colors allows you to specify % different level ranges for each of the color channels separately. % % If the boolean 'invert' is set true the image values will modifyed in the % reverse direction. That is any existing "black" and "white" colors in the % image will become the color values given, with all other values compressed % appropriatally. This effectivally maps a greyscale gradient into the given % color gradient. % % The format of the LevelImageColors method is: % % MagickBooleanType LevelImageColors(Image *image, % const PixelInfo *black_color,const PixelInfo *white_color, % const MagickBooleanType invert,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_color: The color to map black to/from % % o white_point: The color to map white to/from % % o invert: if true map the colors (levelize), rather than from (level) % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType LevelImageColors(Image *image, const PixelInfo *black_color,const PixelInfo *white_color, const MagickBooleanType invert,ExceptionInfo *exception) { ChannelType channel_mask; MagickStatusType status; /* Allocate and initialize levels map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((IsGrayColorspace(image->colorspace) != MagickFalse) && ((IsGrayColorspace(black_color->colorspace) == MagickFalse) || (IsGrayColorspace(white_color->colorspace) == MagickFalse))) (void) SetImageColorspace(image,sRGBColorspace,exception); status=MagickTrue; if (invert == MagickFalse) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,RedChannel); status&=LevelImage(image,black_color->red,white_color->red,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,GreenChannel); status&=LevelImage(image,black_color->green,white_color->green,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,BlueChannel); status&=LevelImage(image,black_color->blue,white_color->blue,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) && (image->colorspace == CMYKColorspace)) { channel_mask=SetImageChannelMask(image,BlackChannel); status&=LevelImage(image,black_color->black,white_color->black,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) && (image->alpha_trait != UndefinedPixelTrait)) { channel_mask=SetImageChannelMask(image,AlphaChannel); status&=LevelImage(image,black_color->alpha,white_color->alpha,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } } else { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,RedChannel); status&=LevelizeImage(image,black_color->red,white_color->red,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,GreenChannel); status&=LevelizeImage(image,black_color->green,white_color->green,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { channel_mask=SetImageChannelMask(image,BlueChannel); status&=LevelizeImage(image,black_color->blue,white_color->blue,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) && (image->colorspace == CMYKColorspace)) { channel_mask=SetImageChannelMask(image,BlackChannel); status&=LevelizeImage(image,black_color->black,white_color->black,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) && (image->alpha_trait != UndefinedPixelTrait)) { channel_mask=SetImageChannelMask(image,AlphaChannel); status&=LevelizeImage(image,black_color->alpha,white_color->alpha,1.0, exception); (void) SetImageChannelMask(image,channel_mask); } } return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i n e a r S t r e t c h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LinearStretchImage() discards any pixels below the black point and above % the white point and levels the remaining pixels. % % The format of the LinearStretchImage method is: % % MagickBooleanType LinearStretchImage(Image *image, % const double black_point,const double white_point, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o black_point: the black point. % % o white_point: the white point. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType LinearStretchImage(Image *image, const double black_point,const double white_point,ExceptionInfo *exception) { #define LinearStretchImageTag "LinearStretch/Image" CacheView *image_view; double *histogram, intensity; MagickBooleanType status; ssize_t black, white, y; /* Allocate histogram and linear map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*histogram)); if (histogram == (double *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); /* Form histogram. */ (void) memset(histogram,0,(MaxMap+1)*sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { intensity=GetPixelIntensity(image,p); histogram[ScaleQuantumToMap(ClampToQuantum(intensity))]++; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Find the histogram boundaries by locating the black and white point levels. */ intensity=0.0; for (black=0; black < (ssize_t) MaxMap; black++) { intensity+=histogram[black]; if (intensity >= black_point) break; } intensity=0.0; for (white=(ssize_t) MaxMap; white != 0; white--) { intensity+=histogram[white]; if (intensity >= white_point) break; } histogram=(double *) RelinquishMagickMemory(histogram); status=LevelImage(image,(double) ScaleMapToQuantum((MagickRealType) black), (double) ScaleMapToQuantum((MagickRealType) white),1.0,exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o d u l a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ModulateImage() lets you control the brightness, saturation, and hue % of an image. Modulate represents the brightness, saturation, and hue % as one parameter (e.g. 90,150,100). If the image colorspace is HSL, the % modulation is lightness, saturation, and hue. For HWB, use blackness, % whiteness, and hue. And for HCL, use chrome, luma, and hue. % % The format of the ModulateImage method is: % % MagickBooleanType ModulateImage(Image *image,const char *modulate, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o modulate: Define the percent change in brightness, saturation, and hue. % % o exception: return any errors or warnings in this structure. % */ static inline void ModulateHCL(const double percent_hue, const double percent_chroma,const double percent_luma,double *red, double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToHCL(*red,*green,*blue,&hue,&chroma,&luma); hue+=fmod((percent_hue-100.0),200.0)/200.0; chroma*=0.01*percent_chroma; luma*=0.01*percent_luma; ConvertHCLToRGB(hue,chroma,luma,red,green,blue); } static inline void ModulateHCLp(const double percent_hue, const double percent_chroma,const double percent_luma,double *red, double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToHCLp(*red,*green,*blue,&hue,&chroma,&luma); hue+=fmod((percent_hue-100.0),200.0)/200.0; chroma*=0.01*percent_chroma; luma*=0.01*percent_luma; ConvertHCLpToRGB(hue,chroma,luma,red,green,blue); } static inline void ModulateHSB(const double percent_hue, const double percent_saturation,const double percent_brightness,double *red, double *green,double *blue) { double brightness, hue, saturation; /* Increase or decrease color brightness, saturation, or hue. */ ConvertRGBToHSB(*red,*green,*blue,&hue,&saturation,&brightness); hue+=fmod((percent_hue-100.0),200.0)/200.0; saturation*=0.01*percent_saturation; brightness*=0.01*percent_brightness; ConvertHSBToRGB(hue,saturation,brightness,red,green,blue); } static inline void ModulateHSI(const double percent_hue, const double percent_saturation,const double percent_intensity,double *red, double *green,double *blue) { double intensity, hue, saturation; /* Increase or decrease color intensity, saturation, or hue. */ ConvertRGBToHSI(*red,*green,*blue,&hue,&saturation,&intensity); hue+=fmod((percent_hue-100.0),200.0)/200.0; saturation*=0.01*percent_saturation; intensity*=0.01*percent_intensity; ConvertHSIToRGB(hue,saturation,intensity,red,green,blue); } static inline void ModulateHSL(const double percent_hue, const double percent_saturation,const double percent_lightness,double *red, double *green,double *blue) { double hue, lightness, saturation; /* Increase or decrease color lightness, saturation, or hue. */ ConvertRGBToHSL(*red,*green,*blue,&hue,&saturation,&lightness); hue+=fmod((percent_hue-100.0),200.0)/200.0; saturation*=0.01*percent_saturation; lightness*=0.01*percent_lightness; ConvertHSLToRGB(hue,saturation,lightness,red,green,blue); } static inline void ModulateHSV(const double percent_hue, const double percent_saturation,const double percent_value,double *red, double *green,double *blue) { double hue, saturation, value; /* Increase or decrease color value, saturation, or hue. */ ConvertRGBToHSV(*red,*green,*blue,&hue,&saturation,&value); hue+=fmod((percent_hue-100.0),200.0)/200.0; saturation*=0.01*percent_saturation; value*=0.01*percent_value; ConvertHSVToRGB(hue,saturation,value,red,green,blue); } static inline void ModulateHWB(const double percent_hue, const double percent_whiteness,const double percent_blackness,double *red, double *green,double *blue) { double blackness, hue, whiteness; /* Increase or decrease color blackness, whiteness, or hue. */ ConvertRGBToHWB(*red,*green,*blue,&hue,&whiteness,&blackness); hue+=fmod((percent_hue-100.0),200.0)/200.0; blackness*=0.01*percent_blackness; whiteness*=0.01*percent_whiteness; ConvertHWBToRGB(hue,whiteness,blackness,red,green,blue); } static inline void ModulateLCHab(const double percent_luma, const double percent_chroma,const double percent_hue,double *red, double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToLCHab(*red,*green,*blue,&luma,&chroma,&hue); luma*=0.01*percent_luma; chroma*=0.01*percent_chroma; hue+=fmod((percent_hue-100.0),200.0)/200.0; ConvertLCHabToRGB(luma,chroma,hue,red,green,blue); } static inline void ModulateLCHuv(const double percent_luma, const double percent_chroma,const double percent_hue,double *red, double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToLCHuv(*red,*green,*blue,&luma,&chroma,&hue); luma*=0.01*percent_luma; chroma*=0.01*percent_chroma; hue+=fmod((percent_hue-100.0),200.0)/200.0; ConvertLCHuvToRGB(luma,chroma,hue,red,green,blue); } MagickExport MagickBooleanType ModulateImage(Image *image,const char *modulate, ExceptionInfo *exception) { #define ModulateImageTag "Modulate/Image" CacheView *image_view; ColorspaceType colorspace; const char *artifact; double percent_brightness, percent_hue, percent_saturation; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; MagickStatusType flags; register ssize_t i; ssize_t y; /* Initialize modulate table. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (modulate == (char *) NULL) return(MagickFalse); if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); flags=ParseGeometry(modulate,&geometry_info); percent_brightness=geometry_info.rho; percent_saturation=geometry_info.sigma; if ((flags & SigmaValue) == 0) percent_saturation=100.0; percent_hue=geometry_info.xi; if ((flags & XiValue) == 0) percent_hue=100.0; colorspace=UndefinedColorspace; artifact=GetImageArtifact(image,"modulate:colorspace"); if (artifact != (const char *) NULL) colorspace=(ColorspaceType) ParseCommandOption(MagickColorspaceOptions, MagickFalse,artifact); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { double blue, green, red; /* Modulate image colormap. */ red=(double) image->colormap[i].red; green=(double) image->colormap[i].green; blue=(double) image->colormap[i].blue; switch (colorspace) { case HCLColorspace: { ModulateHCL(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HCLpColorspace: { ModulateHCLp(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSBColorspace: { ModulateHSB(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSIColorspace: { ModulateHSI(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSLColorspace: default: { ModulateHSL(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSVColorspace: { ModulateHSV(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HWBColorspace: { ModulateHWB(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case LCHColorspace: case LCHabColorspace: { ModulateLCHab(percent_brightness,percent_saturation,percent_hue, &red,&green,&blue); break; } case LCHuvColorspace: { ModulateLCHuv(percent_brightness,percent_saturation,percent_hue, &red,&green,&blue); break; } } image->colormap[i].red=red; image->colormap[i].green=green; image->colormap[i].blue=blue; } /* Modulate image. */ #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateModulateImage(image,percent_brightness,percent_hue, percent_saturation,colorspace,exception) != MagickFalse) return(MagickTrue); #endif status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double blue, green, red; red=(double) GetPixelRed(image,q); green=(double) GetPixelGreen(image,q); blue=(double) GetPixelBlue(image,q); switch (colorspace) { case HCLColorspace: { ModulateHCL(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HCLpColorspace: { ModulateHCLp(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSBColorspace: { ModulateHSB(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSLColorspace: default: { ModulateHSL(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HSVColorspace: { ModulateHSV(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case HWBColorspace: { ModulateHWB(percent_hue,percent_saturation,percent_brightness, &red,&green,&blue); break; } case LCHabColorspace: { ModulateLCHab(percent_brightness,percent_saturation,percent_hue, &red,&green,&blue); break; } case LCHColorspace: case LCHuvColorspace: { ModulateLCHuv(percent_brightness,percent_saturation,percent_hue, &red,&green,&blue); break; } } SetPixelRed(image,ClampToQuantum(red),q); SetPixelGreen(image,ClampToQuantum(green),q); SetPixelBlue(image,ClampToQuantum(blue),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ModulateImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N e g a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % NegateImage() negates the colors in the reference image. The grayscale % option means that only grayscale values within the image are negated. % % The format of the NegateImage method is: % % MagickBooleanType NegateImage(Image *image, % const MagickBooleanType grayscale,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o grayscale: If MagickTrue, only negate grayscale pixels within the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType NegateImage(Image *image, const MagickBooleanType grayscale,ExceptionInfo *exception) { #define NegateImageTag "Negate/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) for (i=0; i < (ssize_t) image->colors; i++) { /* Negate colormap. */ if( grayscale != MagickFalse ) if ((image->colormap[i].red != image->colormap[i].green) || (image->colormap[i].green != image->colormap[i].blue)) continue; if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=QuantumRange-image->colormap[i].red; if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=QuantumRange-image->colormap[i].green; if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=QuantumRange-image->colormap[i].blue; } /* Negate image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); if( grayscale != MagickFalse ) { for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; if (IsPixelGray(image,q) != MagickFalse) { q+=GetPixelChannels(image); continue; } for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=QuantumRange-q[j]; } q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,NegateImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(MagickTrue); } /* Negate image. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel = GetPixelChannelChannel(image,j); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=QuantumRange-q[j]; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,NegateImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N o r m a l i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % The NormalizeImage() method enhances the contrast of a color image by % mapping the darkest 2 percent of all pixel to black and the brightest % 1 percent to white. % % The format of the NormalizeImage method is: % % MagickBooleanType NormalizeImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType NormalizeImage(Image *image, ExceptionInfo *exception) { double black_point, white_point; black_point=(double) image->columns*image->rows*0.0015; white_point=(double) image->columns*image->rows*0.9995; return(ContrastStretchImage(image,black_point,white_point,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S i g m o i d a l C o n t r a s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SigmoidalContrastImage() adjusts the contrast of an image with a non-linear % sigmoidal contrast algorithm. Increase the contrast of the image using a % sigmoidal transfer function without saturating highlights or shadows. % Contrast indicates how much to increase the contrast (0 is none; 3 is % typical; 20 is pushing it); mid-point indicates where midtones fall in the % resultant image (0 is white; 50% is middle-gray; 100% is black). Set % sharpen to MagickTrue to increase the image contrast otherwise the contrast % is reduced. % % The format of the SigmoidalContrastImage method is: % % MagickBooleanType SigmoidalContrastImage(Image *image, % const MagickBooleanType sharpen,const char *levels, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o sharpen: Increase or decrease image contrast. % % o contrast: strength of the contrast, the larger the number the more % 'threshold-like' it becomes. % % o midpoint: midpoint of the function as a color value 0 to QuantumRange. % % o exception: return any errors or warnings in this structure. % */ /* ImageMagick 6 has a version of this function which uses LUTs. */ /* Sigmoidal function Sigmoidal with inflexion point moved to b and "slope constant" set to a. The first version, based on the hyperbolic tangent tanh, when combined with the scaling step, is an exact arithmetic clone of the the sigmoid function based on the logistic curve. The equivalence is based on the identity 1/(1+exp(-t)) = (1+tanh(t/2))/2 (http://de.wikipedia.org/wiki/Sigmoidfunktion) and the fact that the scaled sigmoidal derivation is invariant under affine transformations of the ordinate. The tanh version is almost certainly more accurate and cheaper. The 0.5 factor in the argument is to clone the legacy ImageMagick behavior. The reason for making the define depend on atanh even though it only uses tanh has to do with the construction of the inverse of the scaled sigmoidal. */ #if defined(MAGICKCORE_HAVE_ATANH) #define Sigmoidal(a,b,x) ( tanh((0.5*(a))*((x)-(b))) ) #else #define Sigmoidal(a,b,x) ( 1.0/(1.0+exp((a)*((b)-(x)))) ) #endif /* Scaled sigmoidal function: ( Sigmoidal(a,b,x) - Sigmoidal(a,b,0) ) / ( Sigmoidal(a,b,1) - Sigmoidal(a,b,0) ) See http://osdir.com/ml/video.image-magick.devel/2005-04/msg00006.html and http://www.cs.dartmouth.edu/farid/downloads/tutorials/fip.pdf. The limit of ScaledSigmoidal as a->0 is the identity, but a=0 gives a division by zero. This is fixed below by exiting immediately when contrast is small, leaving the image (or colormap) unmodified. This appears to be safe because the series expansion of the logistic sigmoidal function around x=b is 1/2-a*(b-x)/4+... so that the key denominator s(1)-s(0) is about a/4 (a/2 with tanh). */ #define ScaledSigmoidal(a,b,x) ( \ (Sigmoidal((a),(b),(x))-Sigmoidal((a),(b),0.0)) / \ (Sigmoidal((a),(b),1.0)-Sigmoidal((a),(b),0.0)) ) /* Inverse of ScaledSigmoidal, used for +sigmoidal-contrast. Because b may be 0 or 1, the argument of the hyperbolic tangent (resp. logistic sigmoidal) may be outside of the interval (-1,1) (resp. (0,1)), even when creating a LUT from in gamut values, hence the branching. In addition, HDRI may have out of gamut values. InverseScaledSigmoidal is not a two-sided inverse of ScaledSigmoidal: It is only a right inverse. This is unavoidable. */ static inline double InverseScaledSigmoidal(const double a,const double b, const double x) { const double sig0=Sigmoidal(a,b,0.0); const double sig1=Sigmoidal(a,b,1.0); const double argument=(sig1-sig0)*x+sig0; const double clamped= ( #if defined(MAGICKCORE_HAVE_ATANH) argument < -1+MagickEpsilon ? -1+MagickEpsilon : ( argument > 1-MagickEpsilon ? 1-MagickEpsilon : argument ) ); return(b+(2.0/a)*atanh(clamped)); #else argument < MagickEpsilon ? MagickEpsilon : ( argument > 1-MagickEpsilon ? 1-MagickEpsilon : argument ) ); return(b-log(1.0/clamped-1.0)/a); #endif } MagickExport MagickBooleanType SigmoidalContrastImage(Image *image, const MagickBooleanType sharpen,const double contrast,const double midpoint, ExceptionInfo *exception) { #define SigmoidalContrastImageTag "SigmoidalContrast/Image" #define ScaledSig(x) ( ClampToQuantum(QuantumRange* \ ScaledSigmoidal(contrast,QuantumScale*midpoint,QuantumScale*(x))) ) #define InverseScaledSig(x) ( ClampToQuantum(QuantumRange* \ InverseScaledSigmoidal(contrast,QuantumScale*midpoint,QuantumScale*(x))) ) CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Convenience macros. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); /* Side effect: may clamp values unless contrast<MagickEpsilon, in which case nothing is done. */ if (contrast < MagickEpsilon) return(MagickTrue); /* Sigmoidal-contrast enhance colormap. */ if (image->storage_class == PseudoClass) { register ssize_t i; if( sharpen != MagickFalse ) for (i=0; i < (ssize_t) image->colors; i++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(MagickRealType) ScaledSig( image->colormap[i].red); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(MagickRealType) ScaledSig( image->colormap[i].green); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(MagickRealType) ScaledSig( image->colormap[i].blue); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(MagickRealType) ScaledSig( image->colormap[i].alpha); } else for (i=0; i < (ssize_t) image->colors; i++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(MagickRealType) InverseScaledSig( image->colormap[i].red); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(MagickRealType) InverseScaledSig( image->colormap[i].green); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(MagickRealType) InverseScaledSig( image->colormap[i].blue); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(MagickRealType) InverseScaledSig( image->colormap[i].alpha); } } /* Sigmoidal-contrast enhance image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if( sharpen != MagickFalse ) q[i]=ScaledSig(q[i]); else q[i]=InverseScaledSig(q[i]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,SigmoidalContrastImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); }
null
124
CWE-787
CVE-2019-13300
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS TTTTT AAA TTTTT IIIII SSSSS TTTTT IIIII CCCC % % SS T A A T I SS T I C % % SSS T AAAAA T I SSS T I C % % SS T A A T I SS T I C % % SSSSS T A A T IIIII SSSSS T IIIII CCCC % % % % % % MagickCore Image Statistical Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/accelerate-private.h" #include "magick/animate.h" #include "magick/animate.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/cache-private.h" #include "magick/cache-view.h" #include "magick/client.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/composite.h" #include "magick/composite-private.h" #include "magick/compress.h" #include "magick/constitute.h" #include "magick/deprecate.h" #include "magick/display.h" #include "magick/draw.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/gem.h" #include "magick/geometry.h" #include "magick/list.h" #include "magick/image-private.h" #include "magick/magic.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/paint.h" #include "magick/pixel-private.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/quantize.h" #include "magick/random_.h" #include "magick/random-private.h" #include "magick/resource_.h" #include "magick/segment.h" #include "magick/semaphore.h" #include "magick/signature-private.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/thread-private.h" #include "magick/timer.h" #include "magick/utility.h" #include "magick/version.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E v a l u a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EvaluateImage() applies a value to the image with an arithmetic, relational, % or logical operator to an image. Use these operations to lighten or darken % an image, to increase or decrease contrast in an image, or to produce the % "negative" of an image. % % The format of the EvaluateImageChannel method is: % % MagickBooleanType EvaluateImage(Image *image, % const MagickEvaluateOperator op,const double value, % ExceptionInfo *exception) % MagickBooleanType EvaluateImages(Image *images, % const MagickEvaluateOperator op,const double value, % ExceptionInfo *exception) % MagickBooleanType EvaluateImageChannel(Image *image, % const ChannelType channel,const MagickEvaluateOperator op, % const double value,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o op: A channel op. % % o value: A value value. % % o exception: return any errors or warnings in this structure. % */ static MagickPixelPacket **DestroyPixelThreadSet(MagickPixelPacket **pixels) { register ssize_t i; assert(pixels != (MagickPixelPacket **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixels[i] != (MagickPixelPacket *) NULL) pixels[i]=(MagickPixelPacket *) RelinquishMagickMemory(pixels[i]); pixels=(MagickPixelPacket **) RelinquishMagickMemory(pixels); return(pixels); } static MagickPixelPacket **AcquirePixelThreadSet(const Image *image) { MagickPixelPacket **pixels; register ssize_t i, j; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(MagickPixelPacket **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (MagickPixelPacket **) NULL) return((MagickPixelPacket **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); for (i=0; i < (ssize_t) number_threads; i++) { pixels[i]=(MagickPixelPacket *) AcquireQuantumMemory(image->columns, sizeof(**pixels)); if (pixels[i] == (MagickPixelPacket *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) image->columns; j++) GetMagickPixelPacket(image,&pixels[i][j]); } return(pixels); } static inline double EvaluateMax(const double x,const double y) { if (x > y) return(x); return(y); } #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int IntensityCompare(const void *x,const void *y) { const MagickPixelPacket *color_1, *color_2; int intensity; color_1=(const MagickPixelPacket *) x; color_2=(const MagickPixelPacket *) y; intensity=(int) MagickPixelIntensity(color_2)-(int) MagickPixelIntensity(color_1); return(intensity); } #if defined(__cplusplus) || defined(c_plusplus) } #endif static MagickRealType ApplyEvaluateOperator(RandomInfo *random_info, const Quantum pixel,const MagickEvaluateOperator op, const MagickRealType value) { MagickRealType result; result=0.0; switch (op) { case UndefinedEvaluateOperator: break; case AbsEvaluateOperator: { result=(MagickRealType) fabs((double) (pixel+value)); break; } case AddEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case AddModulusEvaluateOperator: { /* This returns a 'floored modulus' of the addition which is a positive result. It differs from % or fmod() which returns a 'truncated modulus' result, where floor() is replaced by trunc() and could return a negative result (which is clipped). */ result=pixel+value; result-=(QuantumRange+1.0)*floor((double) result/(QuantumRange+1.0)); break; } case AndEvaluateOperator: { result=(MagickRealType) ((size_t) pixel & (size_t) (value+0.5)); break; } case CosineEvaluateOperator: { result=(MagickRealType) (QuantumRange*(0.5*cos((double) (2.0*MagickPI* QuantumScale*pixel*value))+0.5)); break; } case DivideEvaluateOperator: { result=pixel/(value == 0.0 ? 1.0 : value); break; } case ExponentialEvaluateOperator: { result=(MagickRealType) (QuantumRange*exp((double) (value*QuantumScale* pixel))); break; } case GaussianNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, GaussianNoise,value); break; } case ImpulseNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, ImpulseNoise,value); break; } case LaplacianNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, LaplacianNoise,value); break; } case LeftShiftEvaluateOperator: { result=(MagickRealType) ((size_t) pixel << (size_t) (value+0.5)); break; } case LogEvaluateOperator: { if ((QuantumScale*pixel) >= MagickEpsilon) result=(MagickRealType) (QuantumRange*log((double) (QuantumScale*value* pixel+1.0))/log((double) (value+1.0))); break; } case MaxEvaluateOperator: { result=(MagickRealType) EvaluateMax((double) pixel,value); break; } case MeanEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case MedianEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case MinEvaluateOperator: { result=(MagickRealType) MagickMin((double) pixel,value); break; } case MultiplicativeNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, MultiplicativeGaussianNoise,value); break; } case MultiplyEvaluateOperator: { result=(MagickRealType) (value*pixel); break; } case OrEvaluateOperator: { result=(MagickRealType) ((size_t) pixel | (size_t) (value+0.5)); break; } case PoissonNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, PoissonNoise,value); break; } case PowEvaluateOperator: { result=(MagickRealType) (QuantumRange*pow((double) (QuantumScale*pixel), (double) value)); break; } case RightShiftEvaluateOperator: { result=(MagickRealType) ((size_t) pixel >> (size_t) (value+0.5)); break; } case RootMeanSquareEvaluateOperator: { result=(MagickRealType) (pixel*pixel+value); break; } case SetEvaluateOperator: { result=value; break; } case SineEvaluateOperator: { result=(MagickRealType) (QuantumRange*(0.5*sin((double) (2.0*MagickPI* QuantumScale*pixel*value))+0.5)); break; } case SubtractEvaluateOperator: { result=(MagickRealType) (pixel-value); break; } case SumEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case ThresholdEvaluateOperator: { result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 : QuantumRange); break; } case ThresholdBlackEvaluateOperator: { result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 : pixel); break; } case ThresholdWhiteEvaluateOperator: { result=(MagickRealType) (((MagickRealType) pixel > value) ? QuantumRange : pixel); break; } case UniformNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, UniformNoise,value); break; } case XorEvaluateOperator: { result=(MagickRealType) ((size_t) pixel ^ (size_t) (value+0.5)); break; } } return(result); } static Image *AcquireImageCanvas(const Image *images,ExceptionInfo *exception) { const Image *p, *q; size_t columns, number_channels, rows; q=images; columns=images->columns; rows=images->rows; number_channels=0; for (p=images; p != (Image *) NULL; p=p->next) { size_t channels; channels=3; if (p->matte != MagickFalse) channels+=1; if (p->colorspace == CMYKColorspace) channels+=1; if (channels > number_channels) { number_channels=channels; q=p; } if (p->columns > columns) columns=p->columns; if (p->rows > rows) rows=p->rows; } return(CloneImage(q,columns,rows,MagickTrue,exception)); } MagickExport MagickBooleanType EvaluateImage(Image *image, const MagickEvaluateOperator op,const double value,ExceptionInfo *exception) { MagickBooleanType status; status=EvaluateImageChannel(image,CompositeChannels,op,value,exception); return(status); } MagickExport Image *EvaluateImages(const Image *images, const MagickEvaluateOperator op,ExceptionInfo *exception) { #define EvaluateImageTag "Evaluate/Image" CacheView *evaluate_view; Image *image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket **magick_restrict evaluate_pixels, zero; RandomInfo **magick_restrict random_info; size_t number_images; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImageCanvas(images,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImage(image); return((Image *) NULL); } evaluate_pixels=AcquirePixelThreadSet(images); if (evaluate_pixels == (MagickPixelPacket **) NULL) { image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return((Image *) NULL); } /* Evaluate image pixels. */ status=MagickTrue; progress=0; number_images=GetImageListLength(images); GetMagickPixelPacket(images,&zero); random_info=AcquireRandomInfoThreadSet(); evaluate_view=AcquireAuthenticCacheView(image,exception); if (op == MedianEvaluateOperator) { #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,images,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict evaluate_indexes; register MagickPixelPacket *evaluate_pixel; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } evaluate_indexes=GetCacheViewAuthenticIndexQueue(evaluate_view); evaluate_pixel=evaluate_pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) number_images; i++) evaluate_pixel[i]=zero; next=images; for (i=0; i < (ssize_t) number_images; i++) { register const IndexPacket *indexes; register const PixelPacket *p; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,x,y,1,1,exception); if (p == (const PixelPacket *) NULL) { image_view=DestroyCacheView(image_view); break; } indexes=GetCacheViewVirtualIndexQueue(image_view); evaluate_pixel[i].red=ApplyEvaluateOperator(random_info[id], GetPixelRed(p),op,evaluate_pixel[i].red); evaluate_pixel[i].green=ApplyEvaluateOperator(random_info[id], GetPixelGreen(p),op,evaluate_pixel[i].green); evaluate_pixel[i].blue=ApplyEvaluateOperator(random_info[id], GetPixelBlue(p),op,evaluate_pixel[i].blue); evaluate_pixel[i].opacity=ApplyEvaluateOperator(random_info[id], GetPixelAlpha(p),op,evaluate_pixel[i].opacity); if (image->colorspace == CMYKColorspace) evaluate_pixel[i].index=ApplyEvaluateOperator(random_info[id], *indexes,op,evaluate_pixel[i].index); image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } qsort((void *) evaluate_pixel,number_images,sizeof(*evaluate_pixel), IntensityCompare); SetPixelRed(q,ClampToQuantum(evaluate_pixel[i/2].red)); SetPixelGreen(q,ClampToQuantum(evaluate_pixel[i/2].green)); SetPixelBlue(q,ClampToQuantum(evaluate_pixel[i/2].blue)); SetPixelAlpha(q,ClampToQuantum(evaluate_pixel[i/2].opacity)); if (image->colorspace == CMYKColorspace) SetPixelIndex(evaluate_indexes+i,ClampToQuantum( evaluate_pixel[i/2].index)); q++; } if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,EvaluateImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } else { #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,images,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict evaluate_indexes; register ssize_t i, x; register MagickPixelPacket *evaluate_pixel; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } evaluate_indexes=GetCacheViewAuthenticIndexQueue(evaluate_view); evaluate_pixel=evaluate_pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) evaluate_pixel[x]=zero; next=images; for (i=0; i < (ssize_t) number_images; i++) { register const IndexPacket *indexes; register const PixelPacket *p; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1, exception); if (p == (const PixelPacket *) NULL) { image_view=DestroyCacheView(image_view); break; } indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { evaluate_pixel[x].red=ApplyEvaluateOperator(random_info[id], GetPixelRed(p),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].red); evaluate_pixel[x].green=ApplyEvaluateOperator(random_info[id], GetPixelGreen(p),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].green); evaluate_pixel[x].blue=ApplyEvaluateOperator(random_info[id], GetPixelBlue(p),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].blue); evaluate_pixel[x].opacity=ApplyEvaluateOperator(random_info[id], GetPixelAlpha(p),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].opacity); if (image->colorspace == CMYKColorspace) evaluate_pixel[x].index=ApplyEvaluateOperator(random_info[id], GetPixelIndex(indexes+x),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].index); p++; } image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } if (op == MeanEvaluateOperator) for (x=0; x < (ssize_t) image->columns; x++) { evaluate_pixel[x].red/=number_images; evaluate_pixel[x].green/=number_images; evaluate_pixel[x].blue/=number_images; evaluate_pixel[x].opacity/=number_images; evaluate_pixel[x].index/=number_images; } if (op == RootMeanSquareEvaluateOperator) for (x=0; x < (ssize_t) image->columns; x++) { evaluate_pixel[x].red=sqrt((double) evaluate_pixel[x].red/ number_images); evaluate_pixel[x].green=sqrt((double) evaluate_pixel[x].green/ number_images); evaluate_pixel[x].blue=sqrt((double) evaluate_pixel[x].blue/ number_images); evaluate_pixel[x].opacity=sqrt((double) evaluate_pixel[x].opacity/ number_images); evaluate_pixel[x].index=sqrt((double) evaluate_pixel[x].index/ number_images); } if (op == MultiplyEvaluateOperator) for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; for (j=0; j < (ssize_t) (number_images-1); j++) { evaluate_pixel[x].red*=(MagickRealType) QuantumScale; evaluate_pixel[x].green*=(MagickRealType) QuantumScale; evaluate_pixel[x].blue*=(MagickRealType) QuantumScale; evaluate_pixel[x].opacity*=(MagickRealType) QuantumScale; evaluate_pixel[x].index*=(MagickRealType) QuantumScale; } } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ClampToQuantum(evaluate_pixel[x].red)); SetPixelGreen(q,ClampToQuantum(evaluate_pixel[x].green)); SetPixelBlue(q,ClampToQuantum(evaluate_pixel[x].blue)); SetPixelAlpha(q,ClampToQuantum(evaluate_pixel[x].opacity)); if (image->colorspace == CMYKColorspace) SetPixelIndex(evaluate_indexes+x,ClampToQuantum( evaluate_pixel[x].index)); q++; } if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(images,EvaluateImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } evaluate_view=DestroyCacheView(evaluate_view); evaluate_pixels=DestroyPixelThreadSet(evaluate_pixels); random_info=DestroyRandomInfoThreadSet(random_info); if (status == MagickFalse) image=DestroyImage(image); return(image); } MagickExport MagickBooleanType EvaluateImageChannel(Image *image, const ChannelType channel,const MagickEvaluateOperator op,const double value, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); return(MagickFalse); } status=MagickTrue; progress=0; random_info=AcquireRandomInfoThreadSet(); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType result; if ((channel & RedChannel) != 0) { result=ApplyEvaluateOperator(random_info[id],GetPixelRed(q),op,value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelRed(q,ClampToQuantum(result)); } if ((channel & GreenChannel) != 0) { result=ApplyEvaluateOperator(random_info[id],GetPixelGreen(q),op, value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelGreen(q,ClampToQuantum(result)); } if ((channel & BlueChannel) != 0) { result=ApplyEvaluateOperator(random_info[id],GetPixelBlue(q),op, value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelBlue(q,ClampToQuantum(result)); } if ((channel & OpacityChannel) != 0) { if (image->matte == MagickFalse) { result=ApplyEvaluateOperator(random_info[id],GetPixelOpacity(q), op,value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelOpacity(q,ClampToQuantum(result)); } else { result=ApplyEvaluateOperator(random_info[id],GetPixelAlpha(q), op,value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelAlpha(q,ClampToQuantum(result)); } } if (((channel & IndexChannel) != 0) && (indexes != (IndexPacket *) NULL)) { result=ApplyEvaluateOperator(random_info[id],GetPixelIndex(indexes+x), op,value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelIndex(indexes+x,ClampToQuantum(result)); } q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,EvaluateImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F u n c t i o n I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FunctionImage() applies a value to the image with an arithmetic, relational, % or logical operator to an image. Use these operations to lighten or darken % an image, to increase or decrease contrast in an image, or to produce the % "negative" of an image. % % The format of the FunctionImageChannel method is: % % MagickBooleanType FunctionImage(Image *image, % const MagickFunction function,const ssize_t number_parameters, % const double *parameters,ExceptionInfo *exception) % MagickBooleanType FunctionImageChannel(Image *image, % const ChannelType channel,const MagickFunction function, % const ssize_t number_parameters,const double *argument, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o function: A channel function. % % o parameters: one or more parameters. % % o exception: return any errors or warnings in this structure. % */ static Quantum ApplyFunction(Quantum pixel,const MagickFunction function, const size_t number_parameters,const double *parameters, ExceptionInfo *exception) { MagickRealType result; register ssize_t i; (void) exception; result=0.0; switch (function) { case PolynomialFunction: { /* * Polynomial * Parameters: polynomial constants, highest to lowest order * For example: c0*x^3 + c1*x^2 + c2*x + c3 */ result=0.0; for (i=0; i < (ssize_t) number_parameters; i++) result=result*QuantumScale*pixel + parameters[i]; result*=QuantumRange; break; } case SinusoidFunction: { /* Sinusoid Function * Parameters: Freq, Phase, Ampl, bias */ double freq,phase,ampl,bias; freq = ( number_parameters >= 1 ) ? parameters[0] : 1.0; phase = ( number_parameters >= 2 ) ? parameters[1] : 0.0; ampl = ( number_parameters >= 3 ) ? parameters[2] : 0.5; bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5; result=(MagickRealType) (QuantumRange*(ampl*sin((double) (2.0*MagickPI* (freq*QuantumScale*pixel + phase/360.0) )) + bias ) ); break; } case ArcsinFunction: { /* Arcsin Function (peged at range limits for invalid results) * Parameters: Width, Center, Range, Bias */ double width,range,center,bias; width = ( number_parameters >= 1 ) ? parameters[0] : 1.0; center = ( number_parameters >= 2 ) ? parameters[1] : 0.5; range = ( number_parameters >= 3 ) ? parameters[2] : 1.0; bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5; result = 2.0/width*(QuantumScale*pixel - center); if ( result <= -1.0 ) result = bias - range/2.0; else if ( result >= 1.0 ) result = bias + range/2.0; else result=(MagickRealType) (range/MagickPI*asin((double) result)+bias); result *= QuantumRange; break; } case ArctanFunction: { /* Arctan Function * Parameters: Slope, Center, Range, Bias */ double slope,range,center,bias; slope = ( number_parameters >= 1 ) ? parameters[0] : 1.0; center = ( number_parameters >= 2 ) ? parameters[1] : 0.5; range = ( number_parameters >= 3 ) ? parameters[2] : 1.0; bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5; result=(MagickRealType) (MagickPI*slope*(QuantumScale*pixel-center)); result=(MagickRealType) (QuantumRange*(range/MagickPI*atan((double) result) + bias ) ); break; } case UndefinedFunction: break; } return(ClampToQuantum(result)); } MagickExport MagickBooleanType FunctionImage(Image *image, const MagickFunction function,const size_t number_parameters, const double *parameters,ExceptionInfo *exception) { MagickBooleanType status; status=FunctionImageChannel(image,CompositeChannels,function, number_parameters,parameters,exception); return(status); } MagickExport MagickBooleanType FunctionImageChannel(Image *image, const ChannelType channel,const MagickFunction function, const size_t number_parameters,const double *parameters, ExceptionInfo *exception) { #define FunctionImageTag "Function/Image " CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); return(MagickFalse); } #if defined(MAGICKCORE_OPENCL_SUPPORT) status=AccelerateFunctionImage(image,channel,function,number_parameters, parameters,exception); if (status != MagickFalse) return(status); #endif status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,ApplyFunction(GetPixelRed(q),function, number_parameters,parameters,exception)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ApplyFunction(GetPixelGreen(q),function, number_parameters,parameters,exception)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ApplyFunction(GetPixelBlue(q),function, number_parameters,parameters,exception)); if ((channel & OpacityChannel) != 0) { if (image->matte == MagickFalse) SetPixelOpacity(q,ApplyFunction(GetPixelOpacity(q),function, number_parameters,parameters,exception)); else SetPixelAlpha(q,ApplyFunction((Quantum) GetPixelAlpha(q),function, number_parameters,parameters,exception)); } if (((channel & IndexChannel) != 0) && (indexes != (IndexPacket *) NULL)) SetPixelIndex(indexes+x,ApplyFunction(GetPixelIndex(indexes+x),function, number_parameters,parameters,exception)); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,FunctionImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l E n t r o p y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelEntropy() returns the entropy of one or more image channels. % % The format of the GetImageChannelEntropy method is: % % MagickBooleanType GetImageChannelEntropy(const Image *image, % const ChannelType channel,double *entropy,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o entropy: the average entropy of the selected channels. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageEntropy(const Image *image, double *entropy,ExceptionInfo *exception) { MagickBooleanType status; status=GetImageChannelEntropy(image,CompositeChannels,entropy,exception); return(status); } MagickExport MagickBooleanType GetImageChannelEntropy(const Image *image, const ChannelType channel,double *entropy,ExceptionInfo *exception) { ChannelStatistics *channel_statistics; size_t channels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageChannelStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); channels=0; channel_statistics[CompositeChannels].entropy=0.0; if ((channel & RedChannel) != 0) { channel_statistics[CompositeChannels].entropy+= channel_statistics[RedChannel].entropy; channels++; } if ((channel & GreenChannel) != 0) { channel_statistics[CompositeChannels].entropy+= channel_statistics[GreenChannel].entropy; channels++; } if ((channel & BlueChannel) != 0) { channel_statistics[CompositeChannels].entropy+= channel_statistics[BlueChannel].entropy; channels++; } if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) { channel_statistics[CompositeChannels].entropy+= channel_statistics[OpacityChannel].entropy; channels++; } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { channel_statistics[CompositeChannels].entropy+= channel_statistics[BlackChannel].entropy; channels++; } channel_statistics[CompositeChannels].entropy/=channels; *entropy=channel_statistics[CompositeChannels].entropy; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e C h a n n e l E x t r e m a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelExtrema() returns the extrema of one or more image channels. % % The format of the GetImageChannelExtrema method is: % % MagickBooleanType GetImageChannelExtrema(const Image *image, % const ChannelType channel,size_t *minima,size_t *maxima, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o minima: the minimum value in the channel. % % o maxima: the maximum value in the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageExtrema(const Image *image, size_t *minima,size_t *maxima,ExceptionInfo *exception) { MagickBooleanType status; status=GetImageChannelExtrema(image,CompositeChannels,minima,maxima, exception); return(status); } MagickExport MagickBooleanType GetImageChannelExtrema(const Image *image, const ChannelType channel,size_t *minima,size_t *maxima, ExceptionInfo *exception) { double max, min; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=GetImageChannelRange(image,channel,&min,&max,exception); *minima=(size_t) ceil(min-0.5); *maxima=(size_t) floor(max+0.5); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l K u r t o s i s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelKurtosis() returns the kurtosis and skewness of one or more % image channels. % % The format of the GetImageChannelKurtosis method is: % % MagickBooleanType GetImageChannelKurtosis(const Image *image, % const ChannelType channel,double *kurtosis,double *skewness, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o kurtosis: the kurtosis of the channel. % % o skewness: the skewness of the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageKurtosis(const Image *image, double *kurtosis,double *skewness,ExceptionInfo *exception) { MagickBooleanType status; status=GetImageChannelKurtosis(image,CompositeChannels,kurtosis,skewness, exception); return(status); } MagickExport MagickBooleanType GetImageChannelKurtosis(const Image *image, const ChannelType channel,double *kurtosis,double *skewness, ExceptionInfo *exception) { double area, mean, standard_deviation, sum_squares, sum_cubes, sum_fourth_power; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); *kurtosis=0.0; *skewness=0.0; area=0.0; mean=0.0; standard_deviation=0.0; sum_squares=0.0; sum_cubes=0.0; sum_fourth_power=0.0; for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) { mean+=GetPixelRed(p); sum_squares+=(double) GetPixelRed(p)*GetPixelRed(p); sum_cubes+=(double) GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p); sum_fourth_power+=(double) GetPixelRed(p)*GetPixelRed(p)* GetPixelRed(p)*GetPixelRed(p); area++; } if ((channel & GreenChannel) != 0) { mean+=GetPixelGreen(p); sum_squares+=(double) GetPixelGreen(p)*GetPixelGreen(p); sum_cubes+=(double) GetPixelGreen(p)*GetPixelGreen(p)* GetPixelGreen(p); sum_fourth_power+=(double) GetPixelGreen(p)*GetPixelGreen(p)* GetPixelGreen(p)*GetPixelGreen(p); area++; } if ((channel & BlueChannel) != 0) { mean+=GetPixelBlue(p); sum_squares+=(double) GetPixelBlue(p)*GetPixelBlue(p); sum_cubes+=(double) GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p); sum_fourth_power+=(double) GetPixelBlue(p)*GetPixelBlue(p)* GetPixelBlue(p)*GetPixelBlue(p); area++; } if ((channel & OpacityChannel) != 0) { mean+=GetPixelAlpha(p); sum_squares+=(double) GetPixelOpacity(p)*GetPixelAlpha(p); sum_cubes+=(double) GetPixelOpacity(p)*GetPixelAlpha(p)* GetPixelAlpha(p); sum_fourth_power+=(double) GetPixelAlpha(p)*GetPixelAlpha(p)* GetPixelAlpha(p)*GetPixelAlpha(p); area++; } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { double index; index=(double) GetPixelIndex(indexes+x); mean+=index; sum_squares+=index*index; sum_cubes+=index*index*index; sum_fourth_power+=index*index*index*index; area++; } p++; } } if (y < (ssize_t) image->rows) return(MagickFalse); if (area != 0.0) { mean/=area; sum_squares/=area; sum_cubes/=area; sum_fourth_power/=area; } standard_deviation=sqrt(sum_squares-(mean*mean)); if (standard_deviation != 0.0) { *kurtosis=sum_fourth_power-4.0*mean*sum_cubes+6.0*mean*mean*sum_squares- 3.0*mean*mean*mean*mean; *kurtosis/=standard_deviation*standard_deviation*standard_deviation* standard_deviation; *kurtosis-=3.0; *skewness=sum_cubes-3.0*mean*sum_squares+2.0*mean*mean*mean; *skewness/=standard_deviation*standard_deviation*standard_deviation; } return(y == (ssize_t) image->rows ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l M e a n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelMean() returns the mean and standard deviation of one or more % image channels. % % The format of the GetImageChannelMean method is: % % MagickBooleanType GetImageChannelMean(const Image *image, % const ChannelType channel,double *mean,double *standard_deviation, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o mean: the average value in the channel. % % o standard_deviation: the standard deviation of the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageMean(const Image *image,double *mean, double *standard_deviation,ExceptionInfo *exception) { MagickBooleanType status; status=GetImageChannelMean(image,CompositeChannels,mean,standard_deviation, exception); return(status); } MagickExport MagickBooleanType GetImageChannelMean(const Image *image, const ChannelType channel,double *mean,double *standard_deviation, ExceptionInfo *exception) { ChannelStatistics *channel_statistics; size_t channels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageChannelStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); channels=0; channel_statistics[CompositeChannels].mean=0.0; channel_statistics[CompositeChannels].standard_deviation=0.0; if ((channel & RedChannel) != 0) { channel_statistics[CompositeChannels].mean+= channel_statistics[RedChannel].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[RedChannel].standard_deviation; channels++; } if ((channel & GreenChannel) != 0) { channel_statistics[CompositeChannels].mean+= channel_statistics[GreenChannel].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[GreenChannel].standard_deviation; channels++; } if ((channel & BlueChannel) != 0) { channel_statistics[CompositeChannels].mean+= channel_statistics[BlueChannel].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[BlueChannel].standard_deviation; channels++; } if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) { channel_statistics[CompositeChannels].mean+= (QuantumRange-channel_statistics[OpacityChannel].mean); channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[OpacityChannel].standard_deviation; channels++; } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { channel_statistics[CompositeChannels].mean+= channel_statistics[BlackChannel].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[CompositeChannels].standard_deviation; channels++; } channel_statistics[CompositeChannels].mean/=channels; channel_statistics[CompositeChannels].standard_deviation/=channels; *mean=channel_statistics[CompositeChannels].mean; *standard_deviation=channel_statistics[CompositeChannels].standard_deviation; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l M o m e n t s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelMoments() returns the normalized moments of one or more image % channels. % % The format of the GetImageChannelMoments method is: % % ChannelMoments *GetImageChannelMoments(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport ChannelMoments *GetImageChannelMoments(const Image *image, ExceptionInfo *exception) { #define MaxNumberImageMoments 8 ChannelMoments *channel_moments; double M00[CompositeChannels+1], M01[CompositeChannels+1], M02[CompositeChannels+1], M03[CompositeChannels+1], M10[CompositeChannels+1], M11[CompositeChannels+1], M12[CompositeChannels+1], M20[CompositeChannels+1], M21[CompositeChannels+1], M22[CompositeChannels+1], M30[CompositeChannels+1]; MagickPixelPacket pixel; PointInfo centroid[CompositeChannels+1]; ssize_t channel, channels, y; size_t length; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); length=CompositeChannels+1UL; channel_moments=(ChannelMoments *) AcquireQuantumMemory(length, sizeof(*channel_moments)); if (channel_moments == (ChannelMoments *) NULL) return(channel_moments); (void) memset(channel_moments,0,length*sizeof(*channel_moments)); (void) memset(centroid,0,sizeof(centroid)); (void) memset(M00,0,sizeof(M00)); (void) memset(M01,0,sizeof(M01)); (void) memset(M02,0,sizeof(M02)); (void) memset(M03,0,sizeof(M03)); (void) memset(M10,0,sizeof(M10)); (void) memset(M11,0,sizeof(M11)); (void) memset(M12,0,sizeof(M12)); (void) memset(M20,0,sizeof(M20)); (void) memset(M21,0,sizeof(M21)); (void) memset(M22,0,sizeof(M22)); (void) memset(M30,0,sizeof(M30)); GetMagickPixelPacket(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; /* Compute center of mass (centroid). */ p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,p,indexes+x,&pixel); M00[RedChannel]+=QuantumScale*pixel.red; M10[RedChannel]+=x*QuantumScale*pixel.red; M01[RedChannel]+=y*QuantumScale*pixel.red; M00[GreenChannel]+=QuantumScale*pixel.green; M10[GreenChannel]+=x*QuantumScale*pixel.green; M01[GreenChannel]+=y*QuantumScale*pixel.green; M00[BlueChannel]+=QuantumScale*pixel.blue; M10[BlueChannel]+=x*QuantumScale*pixel.blue; M01[BlueChannel]+=y*QuantumScale*pixel.blue; if (image->matte != MagickFalse) { M00[OpacityChannel]+=QuantumScale*pixel.opacity; M10[OpacityChannel]+=x*QuantumScale*pixel.opacity; M01[OpacityChannel]+=y*QuantumScale*pixel.opacity; } if (image->colorspace == CMYKColorspace) { M00[IndexChannel]+=QuantumScale*pixel.index; M10[IndexChannel]+=x*QuantumScale*pixel.index; M01[IndexChannel]+=y*QuantumScale*pixel.index; } p++; } } for (channel=0; channel <= CompositeChannels; channel++) { /* Compute center of mass (centroid). */ if (M00[channel] < MagickEpsilon) { M00[channel]+=MagickEpsilon; centroid[channel].x=(double) image->columns/2.0; centroid[channel].y=(double) image->rows/2.0; continue; } M00[channel]+=MagickEpsilon; centroid[channel].x=M10[channel]/M00[channel]; centroid[channel].y=M01[channel]/M00[channel]; } for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; /* Compute the image moments. */ p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,p,indexes+x,&pixel); M11[RedChannel]+=(x-centroid[RedChannel].x)*(y- centroid[RedChannel].y)*QuantumScale*pixel.red; M20[RedChannel]+=(x-centroid[RedChannel].x)*(x- centroid[RedChannel].x)*QuantumScale*pixel.red; M02[RedChannel]+=(y-centroid[RedChannel].y)*(y- centroid[RedChannel].y)*QuantumScale*pixel.red; M21[RedChannel]+=(x-centroid[RedChannel].x)*(x- centroid[RedChannel].x)*(y-centroid[RedChannel].y)*QuantumScale* pixel.red; M12[RedChannel]+=(x-centroid[RedChannel].x)*(y- centroid[RedChannel].y)*(y-centroid[RedChannel].y)*QuantumScale* pixel.red; M22[RedChannel]+=(x-centroid[RedChannel].x)*(x- centroid[RedChannel].x)*(y-centroid[RedChannel].y)*(y- centroid[RedChannel].y)*QuantumScale*pixel.red; M30[RedChannel]+=(x-centroid[RedChannel].x)*(x- centroid[RedChannel].x)*(x-centroid[RedChannel].x)*QuantumScale* pixel.red; M03[RedChannel]+=(y-centroid[RedChannel].y)*(y- centroid[RedChannel].y)*(y-centroid[RedChannel].y)*QuantumScale* pixel.red; M11[GreenChannel]+=(x-centroid[GreenChannel].x)*(y- centroid[GreenChannel].y)*QuantumScale*pixel.green; M20[GreenChannel]+=(x-centroid[GreenChannel].x)*(x- centroid[GreenChannel].x)*QuantumScale*pixel.green; M02[GreenChannel]+=(y-centroid[GreenChannel].y)*(y- centroid[GreenChannel].y)*QuantumScale*pixel.green; M21[GreenChannel]+=(x-centroid[GreenChannel].x)*(x- centroid[GreenChannel].x)*(y-centroid[GreenChannel].y)*QuantumScale* pixel.green; M12[GreenChannel]+=(x-centroid[GreenChannel].x)*(y- centroid[GreenChannel].y)*(y-centroid[GreenChannel].y)*QuantumScale* pixel.green; M22[GreenChannel]+=(x-centroid[GreenChannel].x)*(x- centroid[GreenChannel].x)*(y-centroid[GreenChannel].y)*(y- centroid[GreenChannel].y)*QuantumScale*pixel.green; M30[GreenChannel]+=(x-centroid[GreenChannel].x)*(x- centroid[GreenChannel].x)*(x-centroid[GreenChannel].x)*QuantumScale* pixel.green; M03[GreenChannel]+=(y-centroid[GreenChannel].y)*(y- centroid[GreenChannel].y)*(y-centroid[GreenChannel].y)*QuantumScale* pixel.green; M11[BlueChannel]+=(x-centroid[BlueChannel].x)*(y- centroid[BlueChannel].y)*QuantumScale*pixel.blue; M20[BlueChannel]+=(x-centroid[BlueChannel].x)*(x- centroid[BlueChannel].x)*QuantumScale*pixel.blue; M02[BlueChannel]+=(y-centroid[BlueChannel].y)*(y- centroid[BlueChannel].y)*QuantumScale*pixel.blue; M21[BlueChannel]+=(x-centroid[BlueChannel].x)*(x- centroid[BlueChannel].x)*(y-centroid[BlueChannel].y)*QuantumScale* pixel.blue; M12[BlueChannel]+=(x-centroid[BlueChannel].x)*(y- centroid[BlueChannel].y)*(y-centroid[BlueChannel].y)*QuantumScale* pixel.blue; M22[BlueChannel]+=(x-centroid[BlueChannel].x)*(x- centroid[BlueChannel].x)*(y-centroid[BlueChannel].y)*(y- centroid[BlueChannel].y)*QuantumScale*pixel.blue; M30[BlueChannel]+=(x-centroid[BlueChannel].x)*(x- centroid[BlueChannel].x)*(x-centroid[BlueChannel].x)*QuantumScale* pixel.blue; M03[BlueChannel]+=(y-centroid[BlueChannel].y)*(y- centroid[BlueChannel].y)*(y-centroid[BlueChannel].y)*QuantumScale* pixel.blue; if (image->matte != MagickFalse) { M11[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(y- centroid[OpacityChannel].y)*QuantumScale*pixel.opacity; M20[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x- centroid[OpacityChannel].x)*QuantumScale*pixel.opacity; M02[OpacityChannel]+=(y-centroid[OpacityChannel].y)*(y- centroid[OpacityChannel].y)*QuantumScale*pixel.opacity; M21[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x- centroid[OpacityChannel].x)*(y-centroid[OpacityChannel].y)* QuantumScale*pixel.opacity; M12[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(y- centroid[OpacityChannel].y)*(y-centroid[OpacityChannel].y)* QuantumScale*pixel.opacity; M22[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x- centroid[OpacityChannel].x)*(y-centroid[OpacityChannel].y)*(y- centroid[OpacityChannel].y)*QuantumScale*pixel.opacity; M30[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x- centroid[OpacityChannel].x)*(x-centroid[OpacityChannel].x)* QuantumScale*pixel.opacity; M03[OpacityChannel]+=(y-centroid[OpacityChannel].y)*(y- centroid[OpacityChannel].y)*(y-centroid[OpacityChannel].y)* QuantumScale*pixel.opacity; } if (image->colorspace == CMYKColorspace) { M11[IndexChannel]+=(x-centroid[IndexChannel].x)*(y- centroid[IndexChannel].y)*QuantumScale*pixel.index; M20[IndexChannel]+=(x-centroid[IndexChannel].x)*(x- centroid[IndexChannel].x)*QuantumScale*pixel.index; M02[IndexChannel]+=(y-centroid[IndexChannel].y)*(y- centroid[IndexChannel].y)*QuantumScale*pixel.index; M21[IndexChannel]+=(x-centroid[IndexChannel].x)*(x- centroid[IndexChannel].x)*(y-centroid[IndexChannel].y)* QuantumScale*pixel.index; M12[IndexChannel]+=(x-centroid[IndexChannel].x)*(y- centroid[IndexChannel].y)*(y-centroid[IndexChannel].y)* QuantumScale*pixel.index; M22[IndexChannel]+=(x-centroid[IndexChannel].x)*(x- centroid[IndexChannel].x)*(y-centroid[IndexChannel].y)*(y- centroid[IndexChannel].y)*QuantumScale*pixel.index; M30[IndexChannel]+=(x-centroid[IndexChannel].x)*(x- centroid[IndexChannel].x)*(x-centroid[IndexChannel].x)* QuantumScale*pixel.index; M03[IndexChannel]+=(y-centroid[IndexChannel].y)*(y- centroid[IndexChannel].y)*(y-centroid[IndexChannel].y)* QuantumScale*pixel.index; } p++; } } channels=3; M00[CompositeChannels]+=(M00[RedChannel]+M00[GreenChannel]+M00[BlueChannel]); M01[CompositeChannels]+=(M01[RedChannel]+M01[GreenChannel]+M01[BlueChannel]); M02[CompositeChannels]+=(M02[RedChannel]+M02[GreenChannel]+M02[BlueChannel]); M03[CompositeChannels]+=(M03[RedChannel]+M03[GreenChannel]+M03[BlueChannel]); M10[CompositeChannels]+=(M10[RedChannel]+M10[GreenChannel]+M10[BlueChannel]); M11[CompositeChannels]+=(M11[RedChannel]+M11[GreenChannel]+M11[BlueChannel]); M12[CompositeChannels]+=(M12[RedChannel]+M12[GreenChannel]+M12[BlueChannel]); M20[CompositeChannels]+=(M20[RedChannel]+M20[GreenChannel]+M20[BlueChannel]); M21[CompositeChannels]+=(M21[RedChannel]+M21[GreenChannel]+M21[BlueChannel]); M22[CompositeChannels]+=(M22[RedChannel]+M22[GreenChannel]+M22[BlueChannel]); M30[CompositeChannels]+=(M30[RedChannel]+M30[GreenChannel]+M30[BlueChannel]); if (image->matte != MagickFalse) { channels+=1; M00[CompositeChannels]+=M00[OpacityChannel]; M01[CompositeChannels]+=M01[OpacityChannel]; M02[CompositeChannels]+=M02[OpacityChannel]; M03[CompositeChannels]+=M03[OpacityChannel]; M10[CompositeChannels]+=M10[OpacityChannel]; M11[CompositeChannels]+=M11[OpacityChannel]; M12[CompositeChannels]+=M12[OpacityChannel]; M20[CompositeChannels]+=M20[OpacityChannel]; M21[CompositeChannels]+=M21[OpacityChannel]; M22[CompositeChannels]+=M22[OpacityChannel]; M30[CompositeChannels]+=M30[OpacityChannel]; } if (image->colorspace == CMYKColorspace) { channels+=1; M00[CompositeChannels]+=M00[IndexChannel]; M01[CompositeChannels]+=M01[IndexChannel]; M02[CompositeChannels]+=M02[IndexChannel]; M03[CompositeChannels]+=M03[IndexChannel]; M10[CompositeChannels]+=M10[IndexChannel]; M11[CompositeChannels]+=M11[IndexChannel]; M12[CompositeChannels]+=M12[IndexChannel]; M20[CompositeChannels]+=M20[IndexChannel]; M21[CompositeChannels]+=M21[IndexChannel]; M22[CompositeChannels]+=M22[IndexChannel]; M30[CompositeChannels]+=M30[IndexChannel]; } M00[CompositeChannels]/=(double) channels; M01[CompositeChannels]/=(double) channels; M02[CompositeChannels]/=(double) channels; M03[CompositeChannels]/=(double) channels; M10[CompositeChannels]/=(double) channels; M11[CompositeChannels]/=(double) channels; M12[CompositeChannels]/=(double) channels; M20[CompositeChannels]/=(double) channels; M21[CompositeChannels]/=(double) channels; M22[CompositeChannels]/=(double) channels; M30[CompositeChannels]/=(double) channels; for (channel=0; channel <= CompositeChannels; channel++) { /* Compute elliptical angle, major and minor axes, eccentricity, & intensity. */ channel_moments[channel].centroid=centroid[channel]; channel_moments[channel].ellipse_axis.x=sqrt((2.0/M00[channel])* ((M20[channel]+M02[channel])+sqrt(4.0*M11[channel]*M11[channel]+ (M20[channel]-M02[channel])*(M20[channel]-M02[channel])))); channel_moments[channel].ellipse_axis.y=sqrt((2.0/M00[channel])* ((M20[channel]+M02[channel])-sqrt(4.0*M11[channel]*M11[channel]+ (M20[channel]-M02[channel])*(M20[channel]-M02[channel])))); channel_moments[channel].ellipse_angle=RadiansToDegrees(0.5*atan(2.0* M11[channel]/(M20[channel]-M02[channel]+MagickEpsilon))); if (fabs(M11[channel]) < MagickEpsilon) { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=0.0; } else if (M11[channel] < 0.0) { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=180.0; } else { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=0.0; } channel_moments[channel].ellipse_eccentricity=sqrt(1.0-( channel_moments[channel].ellipse_axis.y/ (channel_moments[channel].ellipse_axis.x+MagickEpsilon))); channel_moments[channel].ellipse_intensity=M00[channel]/ (MagickPI*channel_moments[channel].ellipse_axis.x* channel_moments[channel].ellipse_axis.y+MagickEpsilon); } for (channel=0; channel <= CompositeChannels; channel++) { /* Normalize image moments. */ M10[channel]=0.0; M01[channel]=0.0; M11[channel]/=pow(M00[channel],1.0+(1.0+1.0)/2.0); M20[channel]/=pow(M00[channel],1.0+(2.0+0.0)/2.0); M02[channel]/=pow(M00[channel],1.0+(0.0+2.0)/2.0); M21[channel]/=pow(M00[channel],1.0+(2.0+1.0)/2.0); M12[channel]/=pow(M00[channel],1.0+(1.0+2.0)/2.0); M22[channel]/=pow(M00[channel],1.0+(2.0+2.0)/2.0); M30[channel]/=pow(M00[channel],1.0+(3.0+0.0)/2.0); M03[channel]/=pow(M00[channel],1.0+(0.0+3.0)/2.0); M00[channel]=1.0; } for (channel=0; channel <= CompositeChannels; channel++) { /* Compute Hu invariant moments. */ channel_moments[channel].I[0]=M20[channel]+M02[channel]; channel_moments[channel].I[1]=(M20[channel]-M02[channel])* (M20[channel]-M02[channel])+4.0*M11[channel]*M11[channel]; channel_moments[channel].I[2]=(M30[channel]-3.0*M12[channel])* (M30[channel]-3.0*M12[channel])+(3.0*M21[channel]-M03[channel])* (3.0*M21[channel]-M03[channel]); channel_moments[channel].I[3]=(M30[channel]+M12[channel])* (M30[channel]+M12[channel])+(M21[channel]+M03[channel])* (M21[channel]+M03[channel]); channel_moments[channel].I[4]=(M30[channel]-3.0*M12[channel])* (M30[channel]+M12[channel])*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])* (M21[channel]+M03[channel]))+(3.0*M21[channel]-M03[channel])* (M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M21[channel]+M03[channel])* (M21[channel]+M03[channel])); channel_moments[channel].I[5]=(M20[channel]-M02[channel])* ((M30[channel]+M12[channel])*(M30[channel]+M12[channel])- (M21[channel]+M03[channel])*(M21[channel]+M03[channel]))+ 4.0*M11[channel]*(M30[channel]+M12[channel])*(M21[channel]+M03[channel]); channel_moments[channel].I[6]=(3.0*M21[channel]-M03[channel])* (M30[channel]+M12[channel])*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])* (M21[channel]+M03[channel]))-(M30[channel]-3*M12[channel])* (M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M21[channel]+M03[channel])* (M21[channel]+M03[channel])); channel_moments[channel].I[7]=M11[channel]*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M03[channel]+M21[channel])* (M03[channel]+M21[channel]))-(M20[channel]-M02[channel])* (M30[channel]+M12[channel])*(M03[channel]+M21[channel]); } if (y < (ssize_t) image->rows) channel_moments=(ChannelMoments *) RelinquishMagickMemory(channel_moments); return(channel_moments); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l P e r c e p t u a l H a s h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelPerceptualHash() returns the perceptual hash of one or more % image channels. % % The format of the GetImageChannelPerceptualHash method is: % % ChannelPerceptualHash *GetImageChannelPerceptualHash(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static inline double MagickLog10(const double x) { #define Log10Epsilon (1.0e-11) if (fabs(x) < Log10Epsilon) return(log10(Log10Epsilon)); return(log10(fabs(x))); } MagickExport ChannelPerceptualHash *GetImageChannelPerceptualHash( const Image *image,ExceptionInfo *exception) { ChannelMoments *moments; ChannelPerceptualHash *perceptual_hash; Image *hash_image; MagickBooleanType status; register ssize_t i; ssize_t channel; /* Blur then transform to sRGB colorspace. */ hash_image=BlurImage(image,0.0,1.0,exception); if (hash_image == (Image *) NULL) return((ChannelPerceptualHash *) NULL); hash_image->depth=8; status=TransformImageColorspace(hash_image,sRGBColorspace); if (status == MagickFalse) return((ChannelPerceptualHash *) NULL); moments=GetImageChannelMoments(hash_image,exception); hash_image=DestroyImage(hash_image); if (moments == (ChannelMoments *) NULL) return((ChannelPerceptualHash *) NULL); perceptual_hash=(ChannelPerceptualHash *) AcquireQuantumMemory( CompositeChannels+1UL,sizeof(*perceptual_hash)); if (perceptual_hash == (ChannelPerceptualHash *) NULL) return((ChannelPerceptualHash *) NULL); for (channel=0; channel <= CompositeChannels; channel++) for (i=0; i < MaximumNumberOfImageMoments; i++) perceptual_hash[channel].P[i]=(-MagickLog10(moments[channel].I[i])); moments=(ChannelMoments *) RelinquishMagickMemory(moments); /* Blur then transform to HCLp colorspace. */ hash_image=BlurImage(image,0.0,1.0,exception); if (hash_image == (Image *) NULL) { perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory( perceptual_hash); return((ChannelPerceptualHash *) NULL); } hash_image->depth=8; status=TransformImageColorspace(hash_image,HCLpColorspace); if (status == MagickFalse) { perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory( perceptual_hash); return((ChannelPerceptualHash *) NULL); } moments=GetImageChannelMoments(hash_image,exception); hash_image=DestroyImage(hash_image); if (moments == (ChannelMoments *) NULL) { perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory( perceptual_hash); return((ChannelPerceptualHash *) NULL); } for (channel=0; channel <= CompositeChannels; channel++) for (i=0; i < MaximumNumberOfImageMoments; i++) perceptual_hash[channel].Q[i]=(-MagickLog10(moments[channel].I[i])); moments=(ChannelMoments *) RelinquishMagickMemory(moments); return(perceptual_hash); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l R a n g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelRange() returns the range of one or more image channels. % % The format of the GetImageChannelRange method is: % % MagickBooleanType GetImageChannelRange(const Image *image, % const ChannelType channel,double *minima,double *maxima, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o minima: the minimum value in the channel. % % o maxima: the maximum value in the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageRange(const Image *image, double *minima,double *maxima,ExceptionInfo *exception) { return(GetImageChannelRange(image,CompositeChannels,minima,maxima,exception)); } MagickExport MagickBooleanType GetImageChannelRange(const Image *image, const ChannelType channel,double *minima,double *maxima, ExceptionInfo *exception) { MagickPixelPacket pixel; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); *maxima=(-MagickMaximumValue); *minima=MagickMaximumValue; GetMagickPixelPacket(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,p,indexes+x,&pixel); if ((channel & RedChannel) != 0) { if (pixel.red < *minima) *minima=(double) pixel.red; if (pixel.red > *maxima) *maxima=(double) pixel.red; } if ((channel & GreenChannel) != 0) { if (pixel.green < *minima) *minima=(double) pixel.green; if (pixel.green > *maxima) *maxima=(double) pixel.green; } if ((channel & BlueChannel) != 0) { if (pixel.blue < *minima) *minima=(double) pixel.blue; if (pixel.blue > *maxima) *maxima=(double) pixel.blue; } if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) { if ((QuantumRange-pixel.opacity) < *minima) *minima=(double) (QuantumRange-pixel.opacity); if ((QuantumRange-pixel.opacity) > *maxima) *maxima=(double) (QuantumRange-pixel.opacity); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { if ((double) pixel.index < *minima) *minima=(double) pixel.index; if ((double) pixel.index > *maxima) *maxima=(double) pixel.index; } p++; } } return(y == (ssize_t) image->rows ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l S t a t i s t i c s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelStatistics() returns statistics for each channel in the % image. The statistics include the channel depth, its minima, maxima, mean, % standard deviation, kurtosis and skewness. You can access the red channel % mean, for example, like this: % % channel_statistics=GetImageChannelStatistics(image,exception); % red_mean=channel_statistics[RedChannel].mean; % % Use MagickRelinquishMemory() to free the statistics buffer. % % The format of the GetImageChannelStatistics method is: % % ChannelStatistics *GetImageChannelStatistics(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport ChannelStatistics *GetImageChannelStatistics(const Image *image, ExceptionInfo *exception) { ChannelStatistics *channel_statistics; double area, standard_deviation; MagickPixelPacket number_bins, *histogram; QuantumAny range; register ssize_t i; size_t channels, depth, length; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); length=CompositeChannels+1UL; channel_statistics=(ChannelStatistics *) AcquireQuantumMemory(length, sizeof(*channel_statistics)); histogram=(MagickPixelPacket *) AcquireQuantumMemory(MaxMap+1U, sizeof(*histogram)); if ((channel_statistics == (ChannelStatistics *) NULL) || (histogram == (MagickPixelPacket *) NULL)) { if (histogram != (MagickPixelPacket *) NULL) histogram=(MagickPixelPacket *) RelinquishMagickMemory(histogram); if (channel_statistics != (ChannelStatistics *) NULL) channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(channel_statistics); } (void) memset(channel_statistics,0,length* sizeof(*channel_statistics)); for (i=0; i <= (ssize_t) CompositeChannels; i++) { channel_statistics[i].depth=1; channel_statistics[i].maxima=(-MagickMaximumValue); channel_statistics[i].minima=MagickMaximumValue; } (void) memset(histogram,0,(MaxMap+1U)*sizeof(*histogram)); (void) memset(&number_bins,0,sizeof(number_bins)); for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; /* Compute pixel statistics. */ p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; ) { if (channel_statistics[RedChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[RedChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelRed(p),range) == MagickFalse) { channel_statistics[RedChannel].depth++; continue; } } if (channel_statistics[GreenChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[GreenChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelGreen(p),range) == MagickFalse) { channel_statistics[GreenChannel].depth++; continue; } } if (channel_statistics[BlueChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[BlueChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelBlue(p),range) == MagickFalse) { channel_statistics[BlueChannel].depth++; continue; } } if (image->matte != MagickFalse) { if (channel_statistics[OpacityChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[OpacityChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelAlpha(p),range) == MagickFalse) { channel_statistics[OpacityChannel].depth++; continue; } } } if (image->colorspace == CMYKColorspace) { if (channel_statistics[BlackChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[BlackChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelIndex(indexes+x),range) == MagickFalse) { channel_statistics[BlackChannel].depth++; continue; } } } if ((double) GetPixelRed(p) < channel_statistics[RedChannel].minima) channel_statistics[RedChannel].minima=(double) GetPixelRed(p); if ((double) GetPixelRed(p) > channel_statistics[RedChannel].maxima) channel_statistics[RedChannel].maxima=(double) GetPixelRed(p); channel_statistics[RedChannel].sum+=GetPixelRed(p); channel_statistics[RedChannel].sum_squared+=(double) GetPixelRed(p)* GetPixelRed(p); channel_statistics[RedChannel].sum_cubed+=(double) GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p); channel_statistics[RedChannel].sum_fourth_power+=(double) GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p); if ((double) GetPixelGreen(p) < channel_statistics[GreenChannel].minima) channel_statistics[GreenChannel].minima=(double) GetPixelGreen(p); if ((double) GetPixelGreen(p) > channel_statistics[GreenChannel].maxima) channel_statistics[GreenChannel].maxima=(double) GetPixelGreen(p); channel_statistics[GreenChannel].sum+=GetPixelGreen(p); channel_statistics[GreenChannel].sum_squared+=(double) GetPixelGreen(p)* GetPixelGreen(p); channel_statistics[GreenChannel].sum_cubed+=(double) GetPixelGreen(p)* GetPixelGreen(p)*GetPixelGreen(p); channel_statistics[GreenChannel].sum_fourth_power+=(double) GetPixelGreen(p)*GetPixelGreen(p)*GetPixelGreen(p)*GetPixelGreen(p); if ((double) GetPixelBlue(p) < channel_statistics[BlueChannel].minima) channel_statistics[BlueChannel].minima=(double) GetPixelBlue(p); if ((double) GetPixelBlue(p) > channel_statistics[BlueChannel].maxima) channel_statistics[BlueChannel].maxima=(double) GetPixelBlue(p); channel_statistics[BlueChannel].sum+=GetPixelBlue(p); channel_statistics[BlueChannel].sum_squared+=(double) GetPixelBlue(p)* GetPixelBlue(p); channel_statistics[BlueChannel].sum_cubed+=(double) GetPixelBlue(p)* GetPixelBlue(p)*GetPixelBlue(p); channel_statistics[BlueChannel].sum_fourth_power+=(double) GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p); histogram[ScaleQuantumToMap(GetPixelRed(p))].red++; histogram[ScaleQuantumToMap(GetPixelGreen(p))].green++; histogram[ScaleQuantumToMap(GetPixelBlue(p))].blue++; if (image->matte != MagickFalse) { if ((double) GetPixelAlpha(p) < channel_statistics[OpacityChannel].minima) channel_statistics[OpacityChannel].minima=(double) GetPixelAlpha(p); if ((double) GetPixelAlpha(p) > channel_statistics[OpacityChannel].maxima) channel_statistics[OpacityChannel].maxima=(double) GetPixelAlpha(p); channel_statistics[OpacityChannel].sum+=GetPixelAlpha(p); channel_statistics[OpacityChannel].sum_squared+=(double) GetPixelAlpha(p)*GetPixelAlpha(p); channel_statistics[OpacityChannel].sum_cubed+=(double) GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p); channel_statistics[OpacityChannel].sum_fourth_power+=(double) GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p); histogram[ScaleQuantumToMap(GetPixelAlpha(p))].opacity++; } if (image->colorspace == CMYKColorspace) { if ((double) GetPixelIndex(indexes+x) < channel_statistics[BlackChannel].minima) channel_statistics[BlackChannel].minima=(double) GetPixelIndex(indexes+x); if ((double) GetPixelIndex(indexes+x) > channel_statistics[BlackChannel].maxima) channel_statistics[BlackChannel].maxima=(double) GetPixelIndex(indexes+x); channel_statistics[BlackChannel].sum+=GetPixelIndex(indexes+x); channel_statistics[BlackChannel].sum_squared+=(double) GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x); channel_statistics[BlackChannel].sum_cubed+=(double) GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x)* GetPixelIndex(indexes+x); channel_statistics[BlackChannel].sum_fourth_power+=(double) GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x)* GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x); histogram[ScaleQuantumToMap(GetPixelIndex(indexes+x))].index++; } x++; p++; } } for (i=0; i < (ssize_t) CompositeChannels; i++) { double area, mean, standard_deviation; /* Normalize pixel statistics. */ area=PerceptibleReciprocal((double) image->columns*image->rows); mean=channel_statistics[i].sum*area; channel_statistics[i].sum=mean; channel_statistics[i].sum_squared*=area; channel_statistics[i].sum_cubed*=area; channel_statistics[i].sum_fourth_power*=area; channel_statistics[i].mean=mean; channel_statistics[i].variance=channel_statistics[i].sum_squared; standard_deviation=sqrt(channel_statistics[i].variance-(mean*mean)); area=PerceptibleReciprocal((double) image->columns*image->rows-1.0)* ((double) image->columns*image->rows); standard_deviation=sqrt(area*standard_deviation*standard_deviation); channel_statistics[i].standard_deviation=standard_deviation; } for (i=0; i < (ssize_t) (MaxMap+1U); i++) { if (histogram[i].red > 0.0) number_bins.red++; if (histogram[i].green > 0.0) number_bins.green++; if (histogram[i].blue > 0.0) number_bins.blue++; if ((image->matte != MagickFalse) && (histogram[i].opacity > 0.0)) number_bins.opacity++; if ((image->colorspace == CMYKColorspace) && (histogram[i].index > 0.0)) number_bins.index++; } area=PerceptibleReciprocal((double) image->columns*image->rows); for (i=0; i < (ssize_t) (MaxMap+1U); i++) { /* Compute pixel entropy. */ histogram[i].red*=area; channel_statistics[RedChannel].entropy+=-histogram[i].red* MagickLog10(histogram[i].red)* PerceptibleReciprocal(MagickLog10((double) number_bins.red)); histogram[i].green*=area; channel_statistics[GreenChannel].entropy+=-histogram[i].green* MagickLog10(histogram[i].green)* PerceptibleReciprocal(MagickLog10((double) number_bins.green)); histogram[i].blue*=area; channel_statistics[BlueChannel].entropy+=-histogram[i].blue* MagickLog10(histogram[i].blue)* PerceptibleReciprocal(MagickLog10((double) number_bins.blue)); if (image->matte != MagickFalse) { histogram[i].opacity*=area; channel_statistics[OpacityChannel].entropy+=-histogram[i].opacity* MagickLog10(histogram[i].opacity)* PerceptibleReciprocal(MagickLog10((double) number_bins.opacity)); } if (image->colorspace == CMYKColorspace) { histogram[i].index*=area; channel_statistics[IndexChannel].entropy+=-histogram[i].index* MagickLog10(histogram[i].index)* PerceptibleReciprocal(MagickLog10((double) number_bins.index)); } } /* Compute overall statistics. */ for (i=0; i < (ssize_t) CompositeChannels; i++) { channel_statistics[CompositeChannels].depth=(size_t) EvaluateMax((double) channel_statistics[CompositeChannels].depth,(double) channel_statistics[i].depth); channel_statistics[CompositeChannels].minima=MagickMin( channel_statistics[CompositeChannels].minima, channel_statistics[i].minima); channel_statistics[CompositeChannels].maxima=EvaluateMax( channel_statistics[CompositeChannels].maxima, channel_statistics[i].maxima); channel_statistics[CompositeChannels].sum+=channel_statistics[i].sum; channel_statistics[CompositeChannels].sum_squared+= channel_statistics[i].sum_squared; channel_statistics[CompositeChannels].sum_cubed+= channel_statistics[i].sum_cubed; channel_statistics[CompositeChannels].sum_fourth_power+= channel_statistics[i].sum_fourth_power; channel_statistics[CompositeChannels].mean+=channel_statistics[i].mean; channel_statistics[CompositeChannels].variance+= channel_statistics[i].variance-channel_statistics[i].mean* channel_statistics[i].mean; standard_deviation=sqrt(channel_statistics[i].variance- (channel_statistics[i].mean*channel_statistics[i].mean)); area=PerceptibleReciprocal((double) image->columns*image->rows-1.0)* ((double) image->columns*image->rows); standard_deviation=sqrt(area*standard_deviation*standard_deviation); channel_statistics[CompositeChannels].standard_deviation=standard_deviation; channel_statistics[CompositeChannels].entropy+= channel_statistics[i].entropy; } channels=3; if (image->matte != MagickFalse) channels++; if (image->colorspace == CMYKColorspace) channels++; channel_statistics[CompositeChannels].sum/=channels; channel_statistics[CompositeChannels].sum_squared/=channels; channel_statistics[CompositeChannels].sum_cubed/=channels; channel_statistics[CompositeChannels].sum_fourth_power/=channels; channel_statistics[CompositeChannels].mean/=channels; channel_statistics[CompositeChannels].kurtosis/=channels; channel_statistics[CompositeChannels].skewness/=channels; channel_statistics[CompositeChannels].entropy/=channels; i=CompositeChannels; area=PerceptibleReciprocal((double) channels*image->columns*image->rows); channel_statistics[i].variance=channel_statistics[i].sum_squared; channel_statistics[i].mean=channel_statistics[i].sum; standard_deviation=sqrt(channel_statistics[i].variance- (channel_statistics[i].mean*channel_statistics[i].mean)); standard_deviation=sqrt(PerceptibleReciprocal((double) channels* image->columns*image->rows-1.0)*channels*image->columns*image->rows* standard_deviation*standard_deviation); channel_statistics[i].standard_deviation=standard_deviation; for (i=0; i <= (ssize_t) CompositeChannels; i++) { /* Compute kurtosis & skewness statistics. */ standard_deviation=PerceptibleReciprocal( channel_statistics[i].standard_deviation); channel_statistics[i].skewness=(channel_statistics[i].sum_cubed-3.0* channel_statistics[i].mean*channel_statistics[i].sum_squared+2.0* channel_statistics[i].mean*channel_statistics[i].mean* channel_statistics[i].mean)*(standard_deviation*standard_deviation* standard_deviation); channel_statistics[i].kurtosis=(channel_statistics[i].sum_fourth_power-4.0* channel_statistics[i].mean*channel_statistics[i].sum_cubed+6.0* channel_statistics[i].mean*channel_statistics[i].mean* channel_statistics[i].sum_squared-3.0*channel_statistics[i].mean* channel_statistics[i].mean*1.0*channel_statistics[i].mean* channel_statistics[i].mean)*(standard_deviation*standard_deviation* standard_deviation*standard_deviation)-3.0; } channel_statistics[CompositeChannels].mean=0.0; channel_statistics[CompositeChannels].standard_deviation=0.0; for (i=0; i < (ssize_t) CompositeChannels; i++) { channel_statistics[CompositeChannels].mean+= channel_statistics[i].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[i].standard_deviation; } channel_statistics[CompositeChannels].mean/=(double) channels; channel_statistics[CompositeChannels].standard_deviation/=(double) channels; histogram=(MagickPixelPacket *) RelinquishMagickMemory(histogram); if (y < (ssize_t) image->rows) channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(channel_statistics); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o l y n o m i a l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PolynomialImage() returns a new image where each pixel is the sum of the % pixels in the image sequence after applying its corresponding terms % (coefficient and degree pairs). % % The format of the PolynomialImage method is: % % Image *PolynomialImage(const Image *images,const size_t number_terms, % const double *terms,ExceptionInfo *exception) % Image *PolynomialImageChannel(const Image *images, % const size_t number_terms,const ChannelType channel, % const double *terms,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o channel: the channel. % % o number_terms: the number of terms in the list. The actual list length % is 2 x number_terms + 1 (the constant). % % o terms: the list of polynomial coefficients and degree pairs and a % constant. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *PolynomialImage(const Image *images, const size_t number_terms,const double *terms,ExceptionInfo *exception) { Image *polynomial_image; polynomial_image=PolynomialImageChannel(images,DefaultChannels,number_terms, terms,exception); return(polynomial_image); } MagickExport Image *PolynomialImageChannel(const Image *images, const ChannelType channel,const size_t number_terms,const double *terms, ExceptionInfo *exception) { #define PolynomialImageTag "Polynomial/Image" CacheView *polynomial_view; Image *image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket **magick_restrict polynomial_pixels, zero; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImageCanvas(images,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImage(image); return((Image *) NULL); } polynomial_pixels=AcquirePixelThreadSet(images); if (polynomial_pixels == (MagickPixelPacket **) NULL) { image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return((Image *) NULL); } /* Polynomial image pixels. */ status=MagickTrue; progress=0; GetMagickPixelPacket(images,&zero); polynomial_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict polynomial_indexes; register MagickPixelPacket *polynomial_pixel; register PixelPacket *magick_restrict q; register ssize_t i, x; size_t number_images; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(polynomial_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } polynomial_indexes=GetCacheViewAuthenticIndexQueue(polynomial_view); polynomial_pixel=polynomial_pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) polynomial_pixel[x]=zero; next=images; number_images=GetImageListLength(images); for (i=0; i < (ssize_t) number_images; i++) { register const IndexPacket *indexes; register const PixelPacket *p; if (i >= (ssize_t) number_terms) break; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) { image_view=DestroyCacheView(image_view); break; } indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { double coefficient, degree; coefficient=terms[i << 1]; degree=terms[(i << 1)+1]; if ((channel & RedChannel) != 0) polynomial_pixel[x].red+=coefficient*pow(QuantumScale*p->red,degree); if ((channel & GreenChannel) != 0) polynomial_pixel[x].green+=coefficient*pow(QuantumScale*p->green, degree); if ((channel & BlueChannel) != 0) polynomial_pixel[x].blue+=coefficient*pow(QuantumScale*p->blue, degree); if ((channel & OpacityChannel) != 0) polynomial_pixel[x].opacity+=coefficient*pow(QuantumScale* (QuantumRange-p->opacity),degree); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) polynomial_pixel[x].index+=coefficient*pow(QuantumScale*indexes[x], degree); p++; } image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].red)); SetPixelGreen(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].green)); SetPixelBlue(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].blue)); if (image->matte == MagickFalse) SetPixelOpacity(q,ClampToQuantum(QuantumRange-QuantumRange* polynomial_pixel[x].opacity)); else SetPixelAlpha(q,ClampToQuantum(QuantumRange-QuantumRange* polynomial_pixel[x].opacity)); if (image->colorspace == CMYKColorspace) SetPixelIndex(polynomial_indexes+x,ClampToQuantum(QuantumRange* polynomial_pixel[x].index)); q++; } if (SyncCacheViewAuthenticPixels(polynomial_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(images,PolynomialImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } polynomial_view=DestroyCacheView(polynomial_view); polynomial_pixels=DestroyPixelThreadSet(polynomial_pixels); if (status == MagickFalse) image=DestroyImage(image); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t a t i s t i c I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % StatisticImage() makes each pixel the min / max / median / mode / etc. of % the neighborhood of the specified width and height. % % The format of the StatisticImage method is: % % Image *StatisticImage(const Image *image,const StatisticType type, % const size_t width,const size_t height,ExceptionInfo *exception) % Image *StatisticImageChannel(const Image *image, % const ChannelType channel,const StatisticType type, % const size_t width,const size_t height,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the image channel. % % o type: the statistic type (median, mode, etc.). % % o width: the width of the pixel neighborhood. % % o height: the height of the pixel neighborhood. % % o exception: return any errors or warnings in this structure. % */ #define ListChannels 5 typedef struct _ListNode { size_t next[9], count, signature; } ListNode; typedef struct _SkipList { ssize_t level; ListNode *nodes; } SkipList; typedef struct _PixelList { size_t length, seed, signature; SkipList lists[ListChannels]; } PixelList; static PixelList *DestroyPixelList(PixelList *pixel_list) { register ssize_t i; if (pixel_list == (PixelList *) NULL) return((PixelList *) NULL); for (i=0; i < ListChannels; i++) if (pixel_list->lists[i].nodes != (ListNode *) NULL) pixel_list->lists[i].nodes=(ListNode *) RelinquishAlignedMemory( pixel_list->lists[i].nodes); pixel_list=(PixelList *) RelinquishMagickMemory(pixel_list); return(pixel_list); } static PixelList **DestroyPixelListThreadSet(PixelList **pixel_list) { register ssize_t i; assert(pixel_list != (PixelList **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixel_list[i] != (PixelList *) NULL) pixel_list[i]=DestroyPixelList(pixel_list[i]); pixel_list=(PixelList **) RelinquishMagickMemory(pixel_list); return(pixel_list); } static PixelList *AcquirePixelList(const size_t width,const size_t height) { PixelList *pixel_list; register ssize_t i; pixel_list=(PixelList *) AcquireMagickMemory(sizeof(*pixel_list)); if (pixel_list == (PixelList *) NULL) return(pixel_list); (void) memset((void *) pixel_list,0,sizeof(*pixel_list)); pixel_list->length=width*height; for (i=0; i < ListChannels; i++) { pixel_list->lists[i].nodes=(ListNode *) AcquireAlignedMemory(65537UL, sizeof(*pixel_list->lists[i].nodes)); if (pixel_list->lists[i].nodes == (ListNode *) NULL) return(DestroyPixelList(pixel_list)); (void) memset(pixel_list->lists[i].nodes,0,65537UL* sizeof(*pixel_list->lists[i].nodes)); } pixel_list->signature=MagickCoreSignature; return(pixel_list); } static PixelList **AcquirePixelListThreadSet(const size_t width, const size_t height) { PixelList **pixel_list; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixel_list=(PixelList **) AcquireQuantumMemory(number_threads, sizeof(*pixel_list)); if (pixel_list == (PixelList **) NULL) return((PixelList **) NULL); (void) memset(pixel_list,0,number_threads*sizeof(*pixel_list)); for (i=0; i < (ssize_t) number_threads; i++) { pixel_list[i]=AcquirePixelList(width,height); if (pixel_list[i] == (PixelList *) NULL) return(DestroyPixelListThreadSet(pixel_list)); } return(pixel_list); } static void AddNodePixelList(PixelList *pixel_list,const ssize_t channel, const size_t color) { register SkipList *list; register ssize_t level; size_t search, update[9]; /* Initialize the node. */ list=pixel_list->lists+channel; list->nodes[color].signature=pixel_list->signature; list->nodes[color].count=1; /* Determine where it belongs in the list. */ search=65536UL; for (level=list->level; level >= 0; level--) { while (list->nodes[search].next[level] < color) search=list->nodes[search].next[level]; update[level]=search; } /* Generate a pseudo-random level for this node. */ for (level=0; ; level++) { pixel_list->seed=(pixel_list->seed*42893621L)+1L; if ((pixel_list->seed & 0x300) != 0x300) break; } if (level > 8) level=8; if (level > (list->level+2)) level=list->level+2; /* If we're raising the list's level, link back to the root node. */ while (level > list->level) { list->level++; update[list->level]=65536UL; } /* Link the node into the skip-list. */ do { list->nodes[color].next[level]=list->nodes[update[level]].next[level]; list->nodes[update[level]].next[level]=color; } while (level-- > 0); } static void GetMaximumPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color, maximum; ssize_t count; unsigned short channels[ListChannels]; /* Find the maximum value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; maximum=list->nodes[color].next[0]; do { color=list->nodes[color].next[0]; if (color > maximum) maximum=color; count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); channels[channel]=(unsigned short) maximum; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetMeanPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { MagickRealType sum; register SkipList *list; register ssize_t channel; size_t color; ssize_t count; unsigned short channels[ListChannels]; /* Find the mean value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; sum=0.0; do { color=list->nodes[color].next[0]; sum+=(MagickRealType) list->nodes[color].count*color; count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; channels[channel]=(unsigned short) sum; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetMedianPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color; ssize_t count; unsigned short channels[ListChannels]; /* Find the median value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; do { color=list->nodes[color].next[0]; count+=list->nodes[color].count; } while (count <= (ssize_t) (pixel_list->length >> 1)); channels[channel]=(unsigned short) color; } GetMagickPixelPacket((const Image *) NULL,pixel); pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetMinimumPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color, minimum; ssize_t count; unsigned short channels[ListChannels]; /* Find the minimum value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; count=0; color=65536UL; minimum=list->nodes[color].next[0]; do { color=list->nodes[color].next[0]; if (color < minimum) minimum=color; count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); channels[channel]=(unsigned short) minimum; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetModePixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color, max_count, mode; ssize_t count; unsigned short channels[5]; /* Make each pixel the 'predominant color' of the specified neighborhood. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; mode=color; max_count=list->nodes[mode].count; count=0; do { color=list->nodes[color].next[0]; if (list->nodes[color].count > max_count) { mode=color; max_count=list->nodes[mode].count; } count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); channels[channel]=(unsigned short) mode; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetNonpeakPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color, next, previous; ssize_t count; unsigned short channels[5]; /* Finds the non peak value for each of the colors. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; next=list->nodes[color].next[0]; count=0; do { previous=color; color=next; next=list->nodes[color].next[0]; count+=list->nodes[color].count; } while (count <= (ssize_t) (pixel_list->length >> 1)); if ((previous == 65536UL) && (next != 65536UL)) color=next; else if ((previous != 65536UL) && (next == 65536UL)) color=previous; channels[channel]=(unsigned short) color; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetRootMeanSquarePixelList(PixelList *pixel_list, MagickPixelPacket *pixel) { MagickRealType sum; register SkipList *list; register ssize_t channel; size_t color; ssize_t count; unsigned short channels[ListChannels]; /* Find the root mean square value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; sum=0.0; do { color=list->nodes[color].next[0]; sum+=(MagickRealType) (list->nodes[color].count*color*color); count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; channels[channel]=(unsigned short) sqrt(sum); } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetStandardDeviationPixelList(PixelList *pixel_list, MagickPixelPacket *pixel) { MagickRealType sum, sum_squared; register SkipList *list; register ssize_t channel; size_t color; ssize_t count; unsigned short channels[ListChannels]; /* Find the standard-deviation value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; sum=0.0; sum_squared=0.0; do { register ssize_t i; color=list->nodes[color].next[0]; sum+=(MagickRealType) list->nodes[color].count*color; for (i=0; i < (ssize_t) list->nodes[color].count; i++) sum_squared+=((MagickRealType) color)*((MagickRealType) color); count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; sum_squared/=pixel_list->length; channels[channel]=(unsigned short) sqrt(sum_squared-(sum*sum)); } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static inline void InsertPixelList(const Image *image,const PixelPacket *pixel, const IndexPacket *indexes,PixelList *pixel_list) { size_t signature; unsigned short index; index=ScaleQuantumToShort(GetPixelRed(pixel)); signature=pixel_list->lists[0].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[0].nodes[index].count++; else AddNodePixelList(pixel_list,0,index); index=ScaleQuantumToShort(GetPixelGreen(pixel)); signature=pixel_list->lists[1].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[1].nodes[index].count++; else AddNodePixelList(pixel_list,1,index); index=ScaleQuantumToShort(GetPixelBlue(pixel)); signature=pixel_list->lists[2].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[2].nodes[index].count++; else AddNodePixelList(pixel_list,2,index); index=ScaleQuantumToShort(GetPixelOpacity(pixel)); signature=pixel_list->lists[3].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[3].nodes[index].count++; else AddNodePixelList(pixel_list,3,index); if (image->colorspace == CMYKColorspace) index=ScaleQuantumToShort(GetPixelIndex(indexes)); signature=pixel_list->lists[4].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[4].nodes[index].count++; else AddNodePixelList(pixel_list,4,index); } static void ResetPixelList(PixelList *pixel_list) { int level; register ListNode *root; register SkipList *list; register ssize_t channel; /* Reset the skip-list. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; root=list->nodes+65536UL; list->level=0; for (level=0; level < 9; level++) root->next[level]=65536UL; } pixel_list->seed=pixel_list->signature++; } MagickExport Image *StatisticImage(const Image *image,const StatisticType type, const size_t width,const size_t height,ExceptionInfo *exception) { Image *statistic_image; statistic_image=StatisticImageChannel(image,DefaultChannels,type,width, height,exception); return(statistic_image); } MagickExport Image *StatisticImageChannel(const Image *image, const ChannelType channel,const StatisticType type,const size_t width, const size_t height,ExceptionInfo *exception) { #define StatisticImageTag "Statistic/Image" CacheView *image_view, *statistic_view; Image *statistic_image; MagickBooleanType status; MagickOffsetType progress; PixelList **magick_restrict pixel_list; size_t neighbor_height, neighbor_width; ssize_t y; /* Initialize statistics image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); statistic_image=CloneImage(image,0,0,MagickTrue,exception); if (statistic_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(statistic_image,DirectClass) == MagickFalse) { InheritException(exception,&statistic_image->exception); statistic_image=DestroyImage(statistic_image); return((Image *) NULL); } neighbor_width=width == 0 ? GetOptimalKernelWidth2D((double) width,0.5) : width; neighbor_height=height == 0 ? GetOptimalKernelWidth2D((double) height,0.5) : height; pixel_list=AcquirePixelListThreadSet(neighbor_width,neighbor_height); if (pixel_list == (PixelList **) NULL) { statistic_image=DestroyImage(statistic_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Make each pixel the min / max / median / mode / etc. of the neighborhood. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); statistic_view=AcquireAuthenticCacheView(statistic_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,statistic_image,statistic_image->rows,1) #endif for (y=0; y < (ssize_t) statistic_image->rows; y++) { const int id = GetOpenMPThreadId(); register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict statistic_indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) neighbor_width/2L),y- (ssize_t) (neighbor_height/2L),image->columns+neighbor_width, neighbor_height,exception); q=QueueCacheViewAuthenticPixels(statistic_view,0,y,statistic_image->columns, 1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); statistic_indexes=GetCacheViewAuthenticIndexQueue(statistic_view); for (x=0; x < (ssize_t) statistic_image->columns; x++) { MagickPixelPacket pixel; register const IndexPacket *magick_restrict s; register const PixelPacket *magick_restrict r; register ssize_t u, v; r=p; s=indexes+x; ResetPixelList(pixel_list[id]); for (v=0; v < (ssize_t) neighbor_height; v++) { for (u=0; u < (ssize_t) neighbor_width; u++) InsertPixelList(image,r+u,s+u,pixel_list[id]); r+=image->columns+neighbor_width; s+=image->columns+neighbor_width; } GetMagickPixelPacket(image,&pixel); SetMagickPixelPacket(image,p+neighbor_width*neighbor_height/2,indexes+x+ neighbor_width*neighbor_height/2,&pixel); switch (type) { case GradientStatistic: { MagickPixelPacket maximum, minimum; GetMinimumPixelList(pixel_list[id],&pixel); minimum=pixel; GetMaximumPixelList(pixel_list[id],&pixel); maximum=pixel; pixel.red=MagickAbsoluteValue(maximum.red-minimum.red); pixel.green=MagickAbsoluteValue(maximum.green-minimum.green); pixel.blue=MagickAbsoluteValue(maximum.blue-minimum.blue); pixel.opacity=MagickAbsoluteValue(maximum.opacity-minimum.opacity); if (image->colorspace == CMYKColorspace) pixel.index=MagickAbsoluteValue(maximum.index-minimum.index); break; } case MaximumStatistic: { GetMaximumPixelList(pixel_list[id],&pixel); break; } case MeanStatistic: { GetMeanPixelList(pixel_list[id],&pixel); break; } case MedianStatistic: default: { GetMedianPixelList(pixel_list[id],&pixel); break; } case MinimumStatistic: { GetMinimumPixelList(pixel_list[id],&pixel); break; } case ModeStatistic: { GetModePixelList(pixel_list[id],&pixel); break; } case NonpeakStatistic: { GetNonpeakPixelList(pixel_list[id],&pixel); break; } case RootMeanSquareStatistic: { GetRootMeanSquarePixelList(pixel_list[id],&pixel); break; } case StandardDeviationStatistic: { GetStandardDeviationPixelList(pixel_list[id],&pixel); break; } } if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(pixel.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(pixel.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(pixel.blue)); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,ClampToQuantum(pixel.opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(statistic_indexes+x,ClampToQuantum(pixel.index)); p++; q++; } if (SyncCacheViewAuthenticPixels(statistic_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,StatisticImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } statistic_view=DestroyCacheView(statistic_view); image_view=DestroyCacheView(image_view); pixel_list=DestroyPixelListThreadSet(pixel_list); if (status == MagickFalse) statistic_image=DestroyImage(statistic_image); return(statistic_image); }
null
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS TTTTT AAA TTTTT IIIII SSSSS TTTTT IIIII CCCC % % SS T A A T I SS T I C % % SSS T AAAAA T I SSS T I C % % SS T A A T I SS T I C % % SSSSS T A A T IIIII SSSSS T IIIII CCCC % % % % % % MagickCore Image Statistical Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/accelerate-private.h" #include "magick/animate.h" #include "magick/animate.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/cache-private.h" #include "magick/cache-view.h" #include "magick/client.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/composite.h" #include "magick/composite-private.h" #include "magick/compress.h" #include "magick/constitute.h" #include "magick/deprecate.h" #include "magick/display.h" #include "magick/draw.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/gem.h" #include "magick/geometry.h" #include "magick/list.h" #include "magick/image-private.h" #include "magick/magic.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/paint.h" #include "magick/pixel-private.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/quantize.h" #include "magick/random_.h" #include "magick/random-private.h" #include "magick/resource_.h" #include "magick/segment.h" #include "magick/semaphore.h" #include "magick/signature-private.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/thread-private.h" #include "magick/timer.h" #include "magick/utility.h" #include "magick/version.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E v a l u a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EvaluateImage() applies a value to the image with an arithmetic, relational, % or logical operator to an image. Use these operations to lighten or darken % an image, to increase or decrease contrast in an image, or to produce the % "negative" of an image. % % The format of the EvaluateImageChannel method is: % % MagickBooleanType EvaluateImage(Image *image, % const MagickEvaluateOperator op,const double value, % ExceptionInfo *exception) % MagickBooleanType EvaluateImages(Image *images, % const MagickEvaluateOperator op,const double value, % ExceptionInfo *exception) % MagickBooleanType EvaluateImageChannel(Image *image, % const ChannelType channel,const MagickEvaluateOperator op, % const double value,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o op: A channel op. % % o value: A value value. % % o exception: return any errors or warnings in this structure. % */ static MagickPixelPacket **DestroyPixelThreadSet(MagickPixelPacket **pixels) { register ssize_t i; assert(pixels != (MagickPixelPacket **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixels[i] != (MagickPixelPacket *) NULL) pixels[i]=(MagickPixelPacket *) RelinquishMagickMemory(pixels[i]); pixels=(MagickPixelPacket **) RelinquishMagickMemory(pixels); return(pixels); } static MagickPixelPacket **AcquirePixelThreadSet(const Image *images) { const Image *next; MagickPixelPacket **pixels; register ssize_t i, j; size_t columns, number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(MagickPixelPacket **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (MagickPixelPacket **) NULL) return((MagickPixelPacket **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); columns=images->columns; for (next=images; next != (Image *) NULL; next=next->next) columns=MagickMax(next->columns,columns); for (i=0; i < (ssize_t) number_threads; i++) { pixels[i]=(MagickPixelPacket *) AcquireQuantumMemory(columns, sizeof(**pixels)); if (pixels[i] == (MagickPixelPacket *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) columns; j++) GetMagickPixelPacket(images,&pixels[i][j]); } return(pixels); } static inline double EvaluateMax(const double x,const double y) { if (x > y) return(x); return(y); } #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int IntensityCompare(const void *x,const void *y) { const MagickPixelPacket *color_1, *color_2; int intensity; color_1=(const MagickPixelPacket *) x; color_2=(const MagickPixelPacket *) y; intensity=(int) MagickPixelIntensity(color_2)-(int) MagickPixelIntensity(color_1); return(intensity); } #if defined(__cplusplus) || defined(c_plusplus) } #endif static MagickRealType ApplyEvaluateOperator(RandomInfo *random_info, const Quantum pixel,const MagickEvaluateOperator op, const MagickRealType value) { MagickRealType result; result=0.0; switch (op) { case UndefinedEvaluateOperator: break; case AbsEvaluateOperator: { result=(MagickRealType) fabs((double) (pixel+value)); break; } case AddEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case AddModulusEvaluateOperator: { /* This returns a 'floored modulus' of the addition which is a positive result. It differs from % or fmod() which returns a 'truncated modulus' result, where floor() is replaced by trunc() and could return a negative result (which is clipped). */ result=pixel+value; result-=(QuantumRange+1.0)*floor((double) result/(QuantumRange+1.0)); break; } case AndEvaluateOperator: { result=(MagickRealType) ((size_t) pixel & (size_t) (value+0.5)); break; } case CosineEvaluateOperator: { result=(MagickRealType) (QuantumRange*(0.5*cos((double) (2.0*MagickPI* QuantumScale*pixel*value))+0.5)); break; } case DivideEvaluateOperator: { result=pixel/(value == 0.0 ? 1.0 : value); break; } case ExponentialEvaluateOperator: { result=(MagickRealType) (QuantumRange*exp((double) (value*QuantumScale* pixel))); break; } case GaussianNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, GaussianNoise,value); break; } case ImpulseNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, ImpulseNoise,value); break; } case LaplacianNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, LaplacianNoise,value); break; } case LeftShiftEvaluateOperator: { result=(MagickRealType) ((size_t) pixel << (size_t) (value+0.5)); break; } case LogEvaluateOperator: { if ((QuantumScale*pixel) >= MagickEpsilon) result=(MagickRealType) (QuantumRange*log((double) (QuantumScale*value* pixel+1.0))/log((double) (value+1.0))); break; } case MaxEvaluateOperator: { result=(MagickRealType) EvaluateMax((double) pixel,value); break; } case MeanEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case MedianEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case MinEvaluateOperator: { result=(MagickRealType) MagickMin((double) pixel,value); break; } case MultiplicativeNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, MultiplicativeGaussianNoise,value); break; } case MultiplyEvaluateOperator: { result=(MagickRealType) (value*pixel); break; } case OrEvaluateOperator: { result=(MagickRealType) ((size_t) pixel | (size_t) (value+0.5)); break; } case PoissonNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, PoissonNoise,value); break; } case PowEvaluateOperator: { result=(MagickRealType) (QuantumRange*pow((double) (QuantumScale*pixel), (double) value)); break; } case RightShiftEvaluateOperator: { result=(MagickRealType) ((size_t) pixel >> (size_t) (value+0.5)); break; } case RootMeanSquareEvaluateOperator: { result=(MagickRealType) (pixel*pixel+value); break; } case SetEvaluateOperator: { result=value; break; } case SineEvaluateOperator: { result=(MagickRealType) (QuantumRange*(0.5*sin((double) (2.0*MagickPI* QuantumScale*pixel*value))+0.5)); break; } case SubtractEvaluateOperator: { result=(MagickRealType) (pixel-value); break; } case SumEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case ThresholdEvaluateOperator: { result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 : QuantumRange); break; } case ThresholdBlackEvaluateOperator: { result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 : pixel); break; } case ThresholdWhiteEvaluateOperator: { result=(MagickRealType) (((MagickRealType) pixel > value) ? QuantumRange : pixel); break; } case UniformNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, UniformNoise,value); break; } case XorEvaluateOperator: { result=(MagickRealType) ((size_t) pixel ^ (size_t) (value+0.5)); break; } } return(result); } static Image *AcquireImageCanvas(const Image *images,ExceptionInfo *exception) { const Image *p, *q; size_t columns, number_channels, rows; q=images; columns=images->columns; rows=images->rows; number_channels=0; for (p=images; p != (Image *) NULL; p=p->next) { size_t channels; channels=3; if (p->matte != MagickFalse) channels+=1; if (p->colorspace == CMYKColorspace) channels+=1; if (channels > number_channels) { number_channels=channels; q=p; } if (p->columns > columns) columns=p->columns; if (p->rows > rows) rows=p->rows; } return(CloneImage(q,columns,rows,MagickTrue,exception)); } MagickExport MagickBooleanType EvaluateImage(Image *image, const MagickEvaluateOperator op,const double value,ExceptionInfo *exception) { MagickBooleanType status; status=EvaluateImageChannel(image,CompositeChannels,op,value,exception); return(status); } MagickExport Image *EvaluateImages(const Image *images, const MagickEvaluateOperator op,ExceptionInfo *exception) { #define EvaluateImageTag "Evaluate/Image" CacheView *evaluate_view; Image *image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket **magick_restrict evaluate_pixels, zero; RandomInfo **magick_restrict random_info; size_t number_images; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImageCanvas(images,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImage(image); return((Image *) NULL); } evaluate_pixels=AcquirePixelThreadSet(images); if (evaluate_pixels == (MagickPixelPacket **) NULL) { image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return((Image *) NULL); } /* Evaluate image pixels. */ status=MagickTrue; progress=0; number_images=GetImageListLength(images); GetMagickPixelPacket(images,&zero); random_info=AcquireRandomInfoThreadSet(); evaluate_view=AcquireAuthenticCacheView(image,exception); if (op == MedianEvaluateOperator) { #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,images,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict evaluate_indexes; register MagickPixelPacket *evaluate_pixel; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } evaluate_indexes=GetCacheViewAuthenticIndexQueue(evaluate_view); evaluate_pixel=evaluate_pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) number_images; i++) evaluate_pixel[i]=zero; next=images; for (i=0; i < (ssize_t) number_images; i++) { register const IndexPacket *indexes; register const PixelPacket *p; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,x,y,1,1,exception); if (p == (const PixelPacket *) NULL) { image_view=DestroyCacheView(image_view); break; } indexes=GetCacheViewVirtualIndexQueue(image_view); evaluate_pixel[i].red=ApplyEvaluateOperator(random_info[id], GetPixelRed(p),op,evaluate_pixel[i].red); evaluate_pixel[i].green=ApplyEvaluateOperator(random_info[id], GetPixelGreen(p),op,evaluate_pixel[i].green); evaluate_pixel[i].blue=ApplyEvaluateOperator(random_info[id], GetPixelBlue(p),op,evaluate_pixel[i].blue); evaluate_pixel[i].opacity=ApplyEvaluateOperator(random_info[id], GetPixelAlpha(p),op,evaluate_pixel[i].opacity); if (image->colorspace == CMYKColorspace) evaluate_pixel[i].index=ApplyEvaluateOperator(random_info[id], *indexes,op,evaluate_pixel[i].index); image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } qsort((void *) evaluate_pixel,number_images,sizeof(*evaluate_pixel), IntensityCompare); SetPixelRed(q,ClampToQuantum(evaluate_pixel[i/2].red)); SetPixelGreen(q,ClampToQuantum(evaluate_pixel[i/2].green)); SetPixelBlue(q,ClampToQuantum(evaluate_pixel[i/2].blue)); SetPixelAlpha(q,ClampToQuantum(evaluate_pixel[i/2].opacity)); if (image->colorspace == CMYKColorspace) SetPixelIndex(evaluate_indexes+i,ClampToQuantum( evaluate_pixel[i/2].index)); q++; } if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,EvaluateImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } else { #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,images,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict evaluate_indexes; register ssize_t i, x; register MagickPixelPacket *evaluate_pixel; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } evaluate_indexes=GetCacheViewAuthenticIndexQueue(evaluate_view); evaluate_pixel=evaluate_pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) evaluate_pixel[x]=zero; next=images; for (i=0; i < (ssize_t) number_images; i++) { register const IndexPacket *indexes; register const PixelPacket *p; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1, exception); if (p == (const PixelPacket *) NULL) { image_view=DestroyCacheView(image_view); break; } indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { evaluate_pixel[x].red=ApplyEvaluateOperator(random_info[id], GetPixelRed(p),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].red); evaluate_pixel[x].green=ApplyEvaluateOperator(random_info[id], GetPixelGreen(p),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].green); evaluate_pixel[x].blue=ApplyEvaluateOperator(random_info[id], GetPixelBlue(p),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].blue); evaluate_pixel[x].opacity=ApplyEvaluateOperator(random_info[id], GetPixelAlpha(p),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].opacity); if (image->colorspace == CMYKColorspace) evaluate_pixel[x].index=ApplyEvaluateOperator(random_info[id], GetPixelIndex(indexes+x),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].index); p++; } image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } if (op == MeanEvaluateOperator) for (x=0; x < (ssize_t) image->columns; x++) { evaluate_pixel[x].red/=number_images; evaluate_pixel[x].green/=number_images; evaluate_pixel[x].blue/=number_images; evaluate_pixel[x].opacity/=number_images; evaluate_pixel[x].index/=number_images; } if (op == RootMeanSquareEvaluateOperator) for (x=0; x < (ssize_t) image->columns; x++) { evaluate_pixel[x].red=sqrt((double) evaluate_pixel[x].red/ number_images); evaluate_pixel[x].green=sqrt((double) evaluate_pixel[x].green/ number_images); evaluate_pixel[x].blue=sqrt((double) evaluate_pixel[x].blue/ number_images); evaluate_pixel[x].opacity=sqrt((double) evaluate_pixel[x].opacity/ number_images); evaluate_pixel[x].index=sqrt((double) evaluate_pixel[x].index/ number_images); } if (op == MultiplyEvaluateOperator) for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; for (j=0; j < (ssize_t) (number_images-1); j++) { evaluate_pixel[x].red*=(MagickRealType) QuantumScale; evaluate_pixel[x].green*=(MagickRealType) QuantumScale; evaluate_pixel[x].blue*=(MagickRealType) QuantumScale; evaluate_pixel[x].opacity*=(MagickRealType) QuantumScale; evaluate_pixel[x].index*=(MagickRealType) QuantumScale; } } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ClampToQuantum(evaluate_pixel[x].red)); SetPixelGreen(q,ClampToQuantum(evaluate_pixel[x].green)); SetPixelBlue(q,ClampToQuantum(evaluate_pixel[x].blue)); SetPixelAlpha(q,ClampToQuantum(evaluate_pixel[x].opacity)); if (image->colorspace == CMYKColorspace) SetPixelIndex(evaluate_indexes+x,ClampToQuantum( evaluate_pixel[x].index)); q++; } if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(images,EvaluateImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } evaluate_view=DestroyCacheView(evaluate_view); evaluate_pixels=DestroyPixelThreadSet(evaluate_pixels); random_info=DestroyRandomInfoThreadSet(random_info); if (status == MagickFalse) image=DestroyImage(image); return(image); } MagickExport MagickBooleanType EvaluateImageChannel(Image *image, const ChannelType channel,const MagickEvaluateOperator op,const double value, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); return(MagickFalse); } status=MagickTrue; progress=0; random_info=AcquireRandomInfoThreadSet(); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType result; if ((channel & RedChannel) != 0) { result=ApplyEvaluateOperator(random_info[id],GetPixelRed(q),op,value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelRed(q,ClampToQuantum(result)); } if ((channel & GreenChannel) != 0) { result=ApplyEvaluateOperator(random_info[id],GetPixelGreen(q),op, value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelGreen(q,ClampToQuantum(result)); } if ((channel & BlueChannel) != 0) { result=ApplyEvaluateOperator(random_info[id],GetPixelBlue(q),op, value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelBlue(q,ClampToQuantum(result)); } if ((channel & OpacityChannel) != 0) { if (image->matte == MagickFalse) { result=ApplyEvaluateOperator(random_info[id],GetPixelOpacity(q), op,value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelOpacity(q,ClampToQuantum(result)); } else { result=ApplyEvaluateOperator(random_info[id],GetPixelAlpha(q), op,value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelAlpha(q,ClampToQuantum(result)); } } if (((channel & IndexChannel) != 0) && (indexes != (IndexPacket *) NULL)) { result=ApplyEvaluateOperator(random_info[id],GetPixelIndex(indexes+x), op,value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelIndex(indexes+x,ClampToQuantum(result)); } q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,EvaluateImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F u n c t i o n I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FunctionImage() applies a value to the image with an arithmetic, relational, % or logical operator to an image. Use these operations to lighten or darken % an image, to increase or decrease contrast in an image, or to produce the % "negative" of an image. % % The format of the FunctionImageChannel method is: % % MagickBooleanType FunctionImage(Image *image, % const MagickFunction function,const ssize_t number_parameters, % const double *parameters,ExceptionInfo *exception) % MagickBooleanType FunctionImageChannel(Image *image, % const ChannelType channel,const MagickFunction function, % const ssize_t number_parameters,const double *argument, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o function: A channel function. % % o parameters: one or more parameters. % % o exception: return any errors or warnings in this structure. % */ static Quantum ApplyFunction(Quantum pixel,const MagickFunction function, const size_t number_parameters,const double *parameters, ExceptionInfo *exception) { MagickRealType result; register ssize_t i; (void) exception; result=0.0; switch (function) { case PolynomialFunction: { /* * Polynomial * Parameters: polynomial constants, highest to lowest order * For example: c0*x^3 + c1*x^2 + c2*x + c3 */ result=0.0; for (i=0; i < (ssize_t) number_parameters; i++) result=result*QuantumScale*pixel + parameters[i]; result*=QuantumRange; break; } case SinusoidFunction: { /* Sinusoid Function * Parameters: Freq, Phase, Ampl, bias */ double freq,phase,ampl,bias; freq = ( number_parameters >= 1 ) ? parameters[0] : 1.0; phase = ( number_parameters >= 2 ) ? parameters[1] : 0.0; ampl = ( number_parameters >= 3 ) ? parameters[2] : 0.5; bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5; result=(MagickRealType) (QuantumRange*(ampl*sin((double) (2.0*MagickPI* (freq*QuantumScale*pixel + phase/360.0) )) + bias ) ); break; } case ArcsinFunction: { /* Arcsin Function (peged at range limits for invalid results) * Parameters: Width, Center, Range, Bias */ double width,range,center,bias; width = ( number_parameters >= 1 ) ? parameters[0] : 1.0; center = ( number_parameters >= 2 ) ? parameters[1] : 0.5; range = ( number_parameters >= 3 ) ? parameters[2] : 1.0; bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5; result = 2.0/width*(QuantumScale*pixel - center); if ( result <= -1.0 ) result = bias - range/2.0; else if ( result >= 1.0 ) result = bias + range/2.0; else result=(MagickRealType) (range/MagickPI*asin((double) result)+bias); result *= QuantumRange; break; } case ArctanFunction: { /* Arctan Function * Parameters: Slope, Center, Range, Bias */ double slope,range,center,bias; slope = ( number_parameters >= 1 ) ? parameters[0] : 1.0; center = ( number_parameters >= 2 ) ? parameters[1] : 0.5; range = ( number_parameters >= 3 ) ? parameters[2] : 1.0; bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5; result=(MagickRealType) (MagickPI*slope*(QuantumScale*pixel-center)); result=(MagickRealType) (QuantumRange*(range/MagickPI*atan((double) result) + bias ) ); break; } case UndefinedFunction: break; } return(ClampToQuantum(result)); } MagickExport MagickBooleanType FunctionImage(Image *image, const MagickFunction function,const size_t number_parameters, const double *parameters,ExceptionInfo *exception) { MagickBooleanType status; status=FunctionImageChannel(image,CompositeChannels,function, number_parameters,parameters,exception); return(status); } MagickExport MagickBooleanType FunctionImageChannel(Image *image, const ChannelType channel,const MagickFunction function, const size_t number_parameters,const double *parameters, ExceptionInfo *exception) { #define FunctionImageTag "Function/Image " CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); return(MagickFalse); } #if defined(MAGICKCORE_OPENCL_SUPPORT) status=AccelerateFunctionImage(image,channel,function,number_parameters, parameters,exception); if (status != MagickFalse) return(status); #endif status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,ApplyFunction(GetPixelRed(q),function, number_parameters,parameters,exception)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ApplyFunction(GetPixelGreen(q),function, number_parameters,parameters,exception)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ApplyFunction(GetPixelBlue(q),function, number_parameters,parameters,exception)); if ((channel & OpacityChannel) != 0) { if (image->matte == MagickFalse) SetPixelOpacity(q,ApplyFunction(GetPixelOpacity(q),function, number_parameters,parameters,exception)); else SetPixelAlpha(q,ApplyFunction((Quantum) GetPixelAlpha(q),function, number_parameters,parameters,exception)); } if (((channel & IndexChannel) != 0) && (indexes != (IndexPacket *) NULL)) SetPixelIndex(indexes+x,ApplyFunction(GetPixelIndex(indexes+x),function, number_parameters,parameters,exception)); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,FunctionImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l E n t r o p y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelEntropy() returns the entropy of one or more image channels. % % The format of the GetImageChannelEntropy method is: % % MagickBooleanType GetImageChannelEntropy(const Image *image, % const ChannelType channel,double *entropy,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o entropy: the average entropy of the selected channels. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageEntropy(const Image *image, double *entropy,ExceptionInfo *exception) { MagickBooleanType status; status=GetImageChannelEntropy(image,CompositeChannels,entropy,exception); return(status); } MagickExport MagickBooleanType GetImageChannelEntropy(const Image *image, const ChannelType channel,double *entropy,ExceptionInfo *exception) { ChannelStatistics *channel_statistics; size_t channels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageChannelStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); channels=0; channel_statistics[CompositeChannels].entropy=0.0; if ((channel & RedChannel) != 0) { channel_statistics[CompositeChannels].entropy+= channel_statistics[RedChannel].entropy; channels++; } if ((channel & GreenChannel) != 0) { channel_statistics[CompositeChannels].entropy+= channel_statistics[GreenChannel].entropy; channels++; } if ((channel & BlueChannel) != 0) { channel_statistics[CompositeChannels].entropy+= channel_statistics[BlueChannel].entropy; channels++; } if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) { channel_statistics[CompositeChannels].entropy+= channel_statistics[OpacityChannel].entropy; channels++; } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { channel_statistics[CompositeChannels].entropy+= channel_statistics[BlackChannel].entropy; channels++; } channel_statistics[CompositeChannels].entropy/=channels; *entropy=channel_statistics[CompositeChannels].entropy; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e C h a n n e l E x t r e m a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelExtrema() returns the extrema of one or more image channels. % % The format of the GetImageChannelExtrema method is: % % MagickBooleanType GetImageChannelExtrema(const Image *image, % const ChannelType channel,size_t *minima,size_t *maxima, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o minima: the minimum value in the channel. % % o maxima: the maximum value in the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageExtrema(const Image *image, size_t *minima,size_t *maxima,ExceptionInfo *exception) { MagickBooleanType status; status=GetImageChannelExtrema(image,CompositeChannels,minima,maxima, exception); return(status); } MagickExport MagickBooleanType GetImageChannelExtrema(const Image *image, const ChannelType channel,size_t *minima,size_t *maxima, ExceptionInfo *exception) { double max, min; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=GetImageChannelRange(image,channel,&min,&max,exception); *minima=(size_t) ceil(min-0.5); *maxima=(size_t) floor(max+0.5); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l K u r t o s i s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelKurtosis() returns the kurtosis and skewness of one or more % image channels. % % The format of the GetImageChannelKurtosis method is: % % MagickBooleanType GetImageChannelKurtosis(const Image *image, % const ChannelType channel,double *kurtosis,double *skewness, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o kurtosis: the kurtosis of the channel. % % o skewness: the skewness of the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageKurtosis(const Image *image, double *kurtosis,double *skewness,ExceptionInfo *exception) { MagickBooleanType status; status=GetImageChannelKurtosis(image,CompositeChannels,kurtosis,skewness, exception); return(status); } MagickExport MagickBooleanType GetImageChannelKurtosis(const Image *image, const ChannelType channel,double *kurtosis,double *skewness, ExceptionInfo *exception) { double area, mean, standard_deviation, sum_squares, sum_cubes, sum_fourth_power; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); *kurtosis=0.0; *skewness=0.0; area=0.0; mean=0.0; standard_deviation=0.0; sum_squares=0.0; sum_cubes=0.0; sum_fourth_power=0.0; for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) { mean+=GetPixelRed(p); sum_squares+=(double) GetPixelRed(p)*GetPixelRed(p); sum_cubes+=(double) GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p); sum_fourth_power+=(double) GetPixelRed(p)*GetPixelRed(p)* GetPixelRed(p)*GetPixelRed(p); area++; } if ((channel & GreenChannel) != 0) { mean+=GetPixelGreen(p); sum_squares+=(double) GetPixelGreen(p)*GetPixelGreen(p); sum_cubes+=(double) GetPixelGreen(p)*GetPixelGreen(p)* GetPixelGreen(p); sum_fourth_power+=(double) GetPixelGreen(p)*GetPixelGreen(p)* GetPixelGreen(p)*GetPixelGreen(p); area++; } if ((channel & BlueChannel) != 0) { mean+=GetPixelBlue(p); sum_squares+=(double) GetPixelBlue(p)*GetPixelBlue(p); sum_cubes+=(double) GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p); sum_fourth_power+=(double) GetPixelBlue(p)*GetPixelBlue(p)* GetPixelBlue(p)*GetPixelBlue(p); area++; } if ((channel & OpacityChannel) != 0) { mean+=GetPixelAlpha(p); sum_squares+=(double) GetPixelOpacity(p)*GetPixelAlpha(p); sum_cubes+=(double) GetPixelOpacity(p)*GetPixelAlpha(p)* GetPixelAlpha(p); sum_fourth_power+=(double) GetPixelAlpha(p)*GetPixelAlpha(p)* GetPixelAlpha(p)*GetPixelAlpha(p); area++; } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { double index; index=(double) GetPixelIndex(indexes+x); mean+=index; sum_squares+=index*index; sum_cubes+=index*index*index; sum_fourth_power+=index*index*index*index; area++; } p++; } } if (y < (ssize_t) image->rows) return(MagickFalse); if (area != 0.0) { mean/=area; sum_squares/=area; sum_cubes/=area; sum_fourth_power/=area; } standard_deviation=sqrt(sum_squares-(mean*mean)); if (standard_deviation != 0.0) { *kurtosis=sum_fourth_power-4.0*mean*sum_cubes+6.0*mean*mean*sum_squares- 3.0*mean*mean*mean*mean; *kurtosis/=standard_deviation*standard_deviation*standard_deviation* standard_deviation; *kurtosis-=3.0; *skewness=sum_cubes-3.0*mean*sum_squares+2.0*mean*mean*mean; *skewness/=standard_deviation*standard_deviation*standard_deviation; } return(y == (ssize_t) image->rows ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l M e a n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelMean() returns the mean and standard deviation of one or more % image channels. % % The format of the GetImageChannelMean method is: % % MagickBooleanType GetImageChannelMean(const Image *image, % const ChannelType channel,double *mean,double *standard_deviation, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o mean: the average value in the channel. % % o standard_deviation: the standard deviation of the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageMean(const Image *image,double *mean, double *standard_deviation,ExceptionInfo *exception) { MagickBooleanType status; status=GetImageChannelMean(image,CompositeChannels,mean,standard_deviation, exception); return(status); } MagickExport MagickBooleanType GetImageChannelMean(const Image *image, const ChannelType channel,double *mean,double *standard_deviation, ExceptionInfo *exception) { ChannelStatistics *channel_statistics; size_t channels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageChannelStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); channels=0; channel_statistics[CompositeChannels].mean=0.0; channel_statistics[CompositeChannels].standard_deviation=0.0; if ((channel & RedChannel) != 0) { channel_statistics[CompositeChannels].mean+= channel_statistics[RedChannel].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[RedChannel].standard_deviation; channels++; } if ((channel & GreenChannel) != 0) { channel_statistics[CompositeChannels].mean+= channel_statistics[GreenChannel].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[GreenChannel].standard_deviation; channels++; } if ((channel & BlueChannel) != 0) { channel_statistics[CompositeChannels].mean+= channel_statistics[BlueChannel].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[BlueChannel].standard_deviation; channels++; } if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) { channel_statistics[CompositeChannels].mean+= (QuantumRange-channel_statistics[OpacityChannel].mean); channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[OpacityChannel].standard_deviation; channels++; } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { channel_statistics[CompositeChannels].mean+= channel_statistics[BlackChannel].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[CompositeChannels].standard_deviation; channels++; } channel_statistics[CompositeChannels].mean/=channels; channel_statistics[CompositeChannels].standard_deviation/=channels; *mean=channel_statistics[CompositeChannels].mean; *standard_deviation=channel_statistics[CompositeChannels].standard_deviation; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l M o m e n t s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelMoments() returns the normalized moments of one or more image % channels. % % The format of the GetImageChannelMoments method is: % % ChannelMoments *GetImageChannelMoments(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport ChannelMoments *GetImageChannelMoments(const Image *image, ExceptionInfo *exception) { #define MaxNumberImageMoments 8 ChannelMoments *channel_moments; double M00[CompositeChannels+1], M01[CompositeChannels+1], M02[CompositeChannels+1], M03[CompositeChannels+1], M10[CompositeChannels+1], M11[CompositeChannels+1], M12[CompositeChannels+1], M20[CompositeChannels+1], M21[CompositeChannels+1], M22[CompositeChannels+1], M30[CompositeChannels+1]; MagickPixelPacket pixel; PointInfo centroid[CompositeChannels+1]; ssize_t channel, channels, y; size_t length; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); length=CompositeChannels+1UL; channel_moments=(ChannelMoments *) AcquireQuantumMemory(length, sizeof(*channel_moments)); if (channel_moments == (ChannelMoments *) NULL) return(channel_moments); (void) memset(channel_moments,0,length*sizeof(*channel_moments)); (void) memset(centroid,0,sizeof(centroid)); (void) memset(M00,0,sizeof(M00)); (void) memset(M01,0,sizeof(M01)); (void) memset(M02,0,sizeof(M02)); (void) memset(M03,0,sizeof(M03)); (void) memset(M10,0,sizeof(M10)); (void) memset(M11,0,sizeof(M11)); (void) memset(M12,0,sizeof(M12)); (void) memset(M20,0,sizeof(M20)); (void) memset(M21,0,sizeof(M21)); (void) memset(M22,0,sizeof(M22)); (void) memset(M30,0,sizeof(M30)); GetMagickPixelPacket(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; /* Compute center of mass (centroid). */ p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,p,indexes+x,&pixel); M00[RedChannel]+=QuantumScale*pixel.red; M10[RedChannel]+=x*QuantumScale*pixel.red; M01[RedChannel]+=y*QuantumScale*pixel.red; M00[GreenChannel]+=QuantumScale*pixel.green; M10[GreenChannel]+=x*QuantumScale*pixel.green; M01[GreenChannel]+=y*QuantumScale*pixel.green; M00[BlueChannel]+=QuantumScale*pixel.blue; M10[BlueChannel]+=x*QuantumScale*pixel.blue; M01[BlueChannel]+=y*QuantumScale*pixel.blue; if (image->matte != MagickFalse) { M00[OpacityChannel]+=QuantumScale*pixel.opacity; M10[OpacityChannel]+=x*QuantumScale*pixel.opacity; M01[OpacityChannel]+=y*QuantumScale*pixel.opacity; } if (image->colorspace == CMYKColorspace) { M00[IndexChannel]+=QuantumScale*pixel.index; M10[IndexChannel]+=x*QuantumScale*pixel.index; M01[IndexChannel]+=y*QuantumScale*pixel.index; } p++; } } for (channel=0; channel <= CompositeChannels; channel++) { /* Compute center of mass (centroid). */ if (M00[channel] < MagickEpsilon) { M00[channel]+=MagickEpsilon; centroid[channel].x=(double) image->columns/2.0; centroid[channel].y=(double) image->rows/2.0; continue; } M00[channel]+=MagickEpsilon; centroid[channel].x=M10[channel]/M00[channel]; centroid[channel].y=M01[channel]/M00[channel]; } for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; /* Compute the image moments. */ p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,p,indexes+x,&pixel); M11[RedChannel]+=(x-centroid[RedChannel].x)*(y- centroid[RedChannel].y)*QuantumScale*pixel.red; M20[RedChannel]+=(x-centroid[RedChannel].x)*(x- centroid[RedChannel].x)*QuantumScale*pixel.red; M02[RedChannel]+=(y-centroid[RedChannel].y)*(y- centroid[RedChannel].y)*QuantumScale*pixel.red; M21[RedChannel]+=(x-centroid[RedChannel].x)*(x- centroid[RedChannel].x)*(y-centroid[RedChannel].y)*QuantumScale* pixel.red; M12[RedChannel]+=(x-centroid[RedChannel].x)*(y- centroid[RedChannel].y)*(y-centroid[RedChannel].y)*QuantumScale* pixel.red; M22[RedChannel]+=(x-centroid[RedChannel].x)*(x- centroid[RedChannel].x)*(y-centroid[RedChannel].y)*(y- centroid[RedChannel].y)*QuantumScale*pixel.red; M30[RedChannel]+=(x-centroid[RedChannel].x)*(x- centroid[RedChannel].x)*(x-centroid[RedChannel].x)*QuantumScale* pixel.red; M03[RedChannel]+=(y-centroid[RedChannel].y)*(y- centroid[RedChannel].y)*(y-centroid[RedChannel].y)*QuantumScale* pixel.red; M11[GreenChannel]+=(x-centroid[GreenChannel].x)*(y- centroid[GreenChannel].y)*QuantumScale*pixel.green; M20[GreenChannel]+=(x-centroid[GreenChannel].x)*(x- centroid[GreenChannel].x)*QuantumScale*pixel.green; M02[GreenChannel]+=(y-centroid[GreenChannel].y)*(y- centroid[GreenChannel].y)*QuantumScale*pixel.green; M21[GreenChannel]+=(x-centroid[GreenChannel].x)*(x- centroid[GreenChannel].x)*(y-centroid[GreenChannel].y)*QuantumScale* pixel.green; M12[GreenChannel]+=(x-centroid[GreenChannel].x)*(y- centroid[GreenChannel].y)*(y-centroid[GreenChannel].y)*QuantumScale* pixel.green; M22[GreenChannel]+=(x-centroid[GreenChannel].x)*(x- centroid[GreenChannel].x)*(y-centroid[GreenChannel].y)*(y- centroid[GreenChannel].y)*QuantumScale*pixel.green; M30[GreenChannel]+=(x-centroid[GreenChannel].x)*(x- centroid[GreenChannel].x)*(x-centroid[GreenChannel].x)*QuantumScale* pixel.green; M03[GreenChannel]+=(y-centroid[GreenChannel].y)*(y- centroid[GreenChannel].y)*(y-centroid[GreenChannel].y)*QuantumScale* pixel.green; M11[BlueChannel]+=(x-centroid[BlueChannel].x)*(y- centroid[BlueChannel].y)*QuantumScale*pixel.blue; M20[BlueChannel]+=(x-centroid[BlueChannel].x)*(x- centroid[BlueChannel].x)*QuantumScale*pixel.blue; M02[BlueChannel]+=(y-centroid[BlueChannel].y)*(y- centroid[BlueChannel].y)*QuantumScale*pixel.blue; M21[BlueChannel]+=(x-centroid[BlueChannel].x)*(x- centroid[BlueChannel].x)*(y-centroid[BlueChannel].y)*QuantumScale* pixel.blue; M12[BlueChannel]+=(x-centroid[BlueChannel].x)*(y- centroid[BlueChannel].y)*(y-centroid[BlueChannel].y)*QuantumScale* pixel.blue; M22[BlueChannel]+=(x-centroid[BlueChannel].x)*(x- centroid[BlueChannel].x)*(y-centroid[BlueChannel].y)*(y- centroid[BlueChannel].y)*QuantumScale*pixel.blue; M30[BlueChannel]+=(x-centroid[BlueChannel].x)*(x- centroid[BlueChannel].x)*(x-centroid[BlueChannel].x)*QuantumScale* pixel.blue; M03[BlueChannel]+=(y-centroid[BlueChannel].y)*(y- centroid[BlueChannel].y)*(y-centroid[BlueChannel].y)*QuantumScale* pixel.blue; if (image->matte != MagickFalse) { M11[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(y- centroid[OpacityChannel].y)*QuantumScale*pixel.opacity; M20[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x- centroid[OpacityChannel].x)*QuantumScale*pixel.opacity; M02[OpacityChannel]+=(y-centroid[OpacityChannel].y)*(y- centroid[OpacityChannel].y)*QuantumScale*pixel.opacity; M21[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x- centroid[OpacityChannel].x)*(y-centroid[OpacityChannel].y)* QuantumScale*pixel.opacity; M12[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(y- centroid[OpacityChannel].y)*(y-centroid[OpacityChannel].y)* QuantumScale*pixel.opacity; M22[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x- centroid[OpacityChannel].x)*(y-centroid[OpacityChannel].y)*(y- centroid[OpacityChannel].y)*QuantumScale*pixel.opacity; M30[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x- centroid[OpacityChannel].x)*(x-centroid[OpacityChannel].x)* QuantumScale*pixel.opacity; M03[OpacityChannel]+=(y-centroid[OpacityChannel].y)*(y- centroid[OpacityChannel].y)*(y-centroid[OpacityChannel].y)* QuantumScale*pixel.opacity; } if (image->colorspace == CMYKColorspace) { M11[IndexChannel]+=(x-centroid[IndexChannel].x)*(y- centroid[IndexChannel].y)*QuantumScale*pixel.index; M20[IndexChannel]+=(x-centroid[IndexChannel].x)*(x- centroid[IndexChannel].x)*QuantumScale*pixel.index; M02[IndexChannel]+=(y-centroid[IndexChannel].y)*(y- centroid[IndexChannel].y)*QuantumScale*pixel.index; M21[IndexChannel]+=(x-centroid[IndexChannel].x)*(x- centroid[IndexChannel].x)*(y-centroid[IndexChannel].y)* QuantumScale*pixel.index; M12[IndexChannel]+=(x-centroid[IndexChannel].x)*(y- centroid[IndexChannel].y)*(y-centroid[IndexChannel].y)* QuantumScale*pixel.index; M22[IndexChannel]+=(x-centroid[IndexChannel].x)*(x- centroid[IndexChannel].x)*(y-centroid[IndexChannel].y)*(y- centroid[IndexChannel].y)*QuantumScale*pixel.index; M30[IndexChannel]+=(x-centroid[IndexChannel].x)*(x- centroid[IndexChannel].x)*(x-centroid[IndexChannel].x)* QuantumScale*pixel.index; M03[IndexChannel]+=(y-centroid[IndexChannel].y)*(y- centroid[IndexChannel].y)*(y-centroid[IndexChannel].y)* QuantumScale*pixel.index; } p++; } } channels=3; M00[CompositeChannels]+=(M00[RedChannel]+M00[GreenChannel]+M00[BlueChannel]); M01[CompositeChannels]+=(M01[RedChannel]+M01[GreenChannel]+M01[BlueChannel]); M02[CompositeChannels]+=(M02[RedChannel]+M02[GreenChannel]+M02[BlueChannel]); M03[CompositeChannels]+=(M03[RedChannel]+M03[GreenChannel]+M03[BlueChannel]); M10[CompositeChannels]+=(M10[RedChannel]+M10[GreenChannel]+M10[BlueChannel]); M11[CompositeChannels]+=(M11[RedChannel]+M11[GreenChannel]+M11[BlueChannel]); M12[CompositeChannels]+=(M12[RedChannel]+M12[GreenChannel]+M12[BlueChannel]); M20[CompositeChannels]+=(M20[RedChannel]+M20[GreenChannel]+M20[BlueChannel]); M21[CompositeChannels]+=(M21[RedChannel]+M21[GreenChannel]+M21[BlueChannel]); M22[CompositeChannels]+=(M22[RedChannel]+M22[GreenChannel]+M22[BlueChannel]); M30[CompositeChannels]+=(M30[RedChannel]+M30[GreenChannel]+M30[BlueChannel]); if (image->matte != MagickFalse) { channels+=1; M00[CompositeChannels]+=M00[OpacityChannel]; M01[CompositeChannels]+=M01[OpacityChannel]; M02[CompositeChannels]+=M02[OpacityChannel]; M03[CompositeChannels]+=M03[OpacityChannel]; M10[CompositeChannels]+=M10[OpacityChannel]; M11[CompositeChannels]+=M11[OpacityChannel]; M12[CompositeChannels]+=M12[OpacityChannel]; M20[CompositeChannels]+=M20[OpacityChannel]; M21[CompositeChannels]+=M21[OpacityChannel]; M22[CompositeChannels]+=M22[OpacityChannel]; M30[CompositeChannels]+=M30[OpacityChannel]; } if (image->colorspace == CMYKColorspace) { channels+=1; M00[CompositeChannels]+=M00[IndexChannel]; M01[CompositeChannels]+=M01[IndexChannel]; M02[CompositeChannels]+=M02[IndexChannel]; M03[CompositeChannels]+=M03[IndexChannel]; M10[CompositeChannels]+=M10[IndexChannel]; M11[CompositeChannels]+=M11[IndexChannel]; M12[CompositeChannels]+=M12[IndexChannel]; M20[CompositeChannels]+=M20[IndexChannel]; M21[CompositeChannels]+=M21[IndexChannel]; M22[CompositeChannels]+=M22[IndexChannel]; M30[CompositeChannels]+=M30[IndexChannel]; } M00[CompositeChannels]/=(double) channels; M01[CompositeChannels]/=(double) channels; M02[CompositeChannels]/=(double) channels; M03[CompositeChannels]/=(double) channels; M10[CompositeChannels]/=(double) channels; M11[CompositeChannels]/=(double) channels; M12[CompositeChannels]/=(double) channels; M20[CompositeChannels]/=(double) channels; M21[CompositeChannels]/=(double) channels; M22[CompositeChannels]/=(double) channels; M30[CompositeChannels]/=(double) channels; for (channel=0; channel <= CompositeChannels; channel++) { /* Compute elliptical angle, major and minor axes, eccentricity, & intensity. */ channel_moments[channel].centroid=centroid[channel]; channel_moments[channel].ellipse_axis.x=sqrt((2.0/M00[channel])* ((M20[channel]+M02[channel])+sqrt(4.0*M11[channel]*M11[channel]+ (M20[channel]-M02[channel])*(M20[channel]-M02[channel])))); channel_moments[channel].ellipse_axis.y=sqrt((2.0/M00[channel])* ((M20[channel]+M02[channel])-sqrt(4.0*M11[channel]*M11[channel]+ (M20[channel]-M02[channel])*(M20[channel]-M02[channel])))); channel_moments[channel].ellipse_angle=RadiansToDegrees(0.5*atan(2.0* M11[channel]/(M20[channel]-M02[channel]+MagickEpsilon))); if (fabs(M11[channel]) < MagickEpsilon) { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=0.0; } else if (M11[channel] < 0.0) { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=180.0; } else { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=0.0; } channel_moments[channel].ellipse_eccentricity=sqrt(1.0-( channel_moments[channel].ellipse_axis.y/ (channel_moments[channel].ellipse_axis.x+MagickEpsilon))); channel_moments[channel].ellipse_intensity=M00[channel]/ (MagickPI*channel_moments[channel].ellipse_axis.x* channel_moments[channel].ellipse_axis.y+MagickEpsilon); } for (channel=0; channel <= CompositeChannels; channel++) { /* Normalize image moments. */ M10[channel]=0.0; M01[channel]=0.0; M11[channel]/=pow(M00[channel],1.0+(1.0+1.0)/2.0); M20[channel]/=pow(M00[channel],1.0+(2.0+0.0)/2.0); M02[channel]/=pow(M00[channel],1.0+(0.0+2.0)/2.0); M21[channel]/=pow(M00[channel],1.0+(2.0+1.0)/2.0); M12[channel]/=pow(M00[channel],1.0+(1.0+2.0)/2.0); M22[channel]/=pow(M00[channel],1.0+(2.0+2.0)/2.0); M30[channel]/=pow(M00[channel],1.0+(3.0+0.0)/2.0); M03[channel]/=pow(M00[channel],1.0+(0.0+3.0)/2.0); M00[channel]=1.0; } for (channel=0; channel <= CompositeChannels; channel++) { /* Compute Hu invariant moments. */ channel_moments[channel].I[0]=M20[channel]+M02[channel]; channel_moments[channel].I[1]=(M20[channel]-M02[channel])* (M20[channel]-M02[channel])+4.0*M11[channel]*M11[channel]; channel_moments[channel].I[2]=(M30[channel]-3.0*M12[channel])* (M30[channel]-3.0*M12[channel])+(3.0*M21[channel]-M03[channel])* (3.0*M21[channel]-M03[channel]); channel_moments[channel].I[3]=(M30[channel]+M12[channel])* (M30[channel]+M12[channel])+(M21[channel]+M03[channel])* (M21[channel]+M03[channel]); channel_moments[channel].I[4]=(M30[channel]-3.0*M12[channel])* (M30[channel]+M12[channel])*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])* (M21[channel]+M03[channel]))+(3.0*M21[channel]-M03[channel])* (M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M21[channel]+M03[channel])* (M21[channel]+M03[channel])); channel_moments[channel].I[5]=(M20[channel]-M02[channel])* ((M30[channel]+M12[channel])*(M30[channel]+M12[channel])- (M21[channel]+M03[channel])*(M21[channel]+M03[channel]))+ 4.0*M11[channel]*(M30[channel]+M12[channel])*(M21[channel]+M03[channel]); channel_moments[channel].I[6]=(3.0*M21[channel]-M03[channel])* (M30[channel]+M12[channel])*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])* (M21[channel]+M03[channel]))-(M30[channel]-3*M12[channel])* (M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M21[channel]+M03[channel])* (M21[channel]+M03[channel])); channel_moments[channel].I[7]=M11[channel]*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M03[channel]+M21[channel])* (M03[channel]+M21[channel]))-(M20[channel]-M02[channel])* (M30[channel]+M12[channel])*(M03[channel]+M21[channel]); } if (y < (ssize_t) image->rows) channel_moments=(ChannelMoments *) RelinquishMagickMemory(channel_moments); return(channel_moments); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l P e r c e p t u a l H a s h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelPerceptualHash() returns the perceptual hash of one or more % image channels. % % The format of the GetImageChannelPerceptualHash method is: % % ChannelPerceptualHash *GetImageChannelPerceptualHash(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static inline double MagickLog10(const double x) { #define Log10Epsilon (1.0e-11) if (fabs(x) < Log10Epsilon) return(log10(Log10Epsilon)); return(log10(fabs(x))); } MagickExport ChannelPerceptualHash *GetImageChannelPerceptualHash( const Image *image,ExceptionInfo *exception) { ChannelMoments *moments; ChannelPerceptualHash *perceptual_hash; Image *hash_image; MagickBooleanType status; register ssize_t i; ssize_t channel; /* Blur then transform to sRGB colorspace. */ hash_image=BlurImage(image,0.0,1.0,exception); if (hash_image == (Image *) NULL) return((ChannelPerceptualHash *) NULL); hash_image->depth=8; status=TransformImageColorspace(hash_image,sRGBColorspace); if (status == MagickFalse) return((ChannelPerceptualHash *) NULL); moments=GetImageChannelMoments(hash_image,exception); hash_image=DestroyImage(hash_image); if (moments == (ChannelMoments *) NULL) return((ChannelPerceptualHash *) NULL); perceptual_hash=(ChannelPerceptualHash *) AcquireQuantumMemory( CompositeChannels+1UL,sizeof(*perceptual_hash)); if (perceptual_hash == (ChannelPerceptualHash *) NULL) return((ChannelPerceptualHash *) NULL); for (channel=0; channel <= CompositeChannels; channel++) for (i=0; i < MaximumNumberOfImageMoments; i++) perceptual_hash[channel].P[i]=(-MagickLog10(moments[channel].I[i])); moments=(ChannelMoments *) RelinquishMagickMemory(moments); /* Blur then transform to HCLp colorspace. */ hash_image=BlurImage(image,0.0,1.0,exception); if (hash_image == (Image *) NULL) { perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory( perceptual_hash); return((ChannelPerceptualHash *) NULL); } hash_image->depth=8; status=TransformImageColorspace(hash_image,HCLpColorspace); if (status == MagickFalse) { perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory( perceptual_hash); return((ChannelPerceptualHash *) NULL); } moments=GetImageChannelMoments(hash_image,exception); hash_image=DestroyImage(hash_image); if (moments == (ChannelMoments *) NULL) { perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory( perceptual_hash); return((ChannelPerceptualHash *) NULL); } for (channel=0; channel <= CompositeChannels; channel++) for (i=0; i < MaximumNumberOfImageMoments; i++) perceptual_hash[channel].Q[i]=(-MagickLog10(moments[channel].I[i])); moments=(ChannelMoments *) RelinquishMagickMemory(moments); return(perceptual_hash); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l R a n g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelRange() returns the range of one or more image channels. % % The format of the GetImageChannelRange method is: % % MagickBooleanType GetImageChannelRange(const Image *image, % const ChannelType channel,double *minima,double *maxima, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o minima: the minimum value in the channel. % % o maxima: the maximum value in the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageRange(const Image *image, double *minima,double *maxima,ExceptionInfo *exception) { return(GetImageChannelRange(image,CompositeChannels,minima,maxima,exception)); } MagickExport MagickBooleanType GetImageChannelRange(const Image *image, const ChannelType channel,double *minima,double *maxima, ExceptionInfo *exception) { MagickPixelPacket pixel; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); *maxima=(-MagickMaximumValue); *minima=MagickMaximumValue; GetMagickPixelPacket(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,p,indexes+x,&pixel); if ((channel & RedChannel) != 0) { if (pixel.red < *minima) *minima=(double) pixel.red; if (pixel.red > *maxima) *maxima=(double) pixel.red; } if ((channel & GreenChannel) != 0) { if (pixel.green < *minima) *minima=(double) pixel.green; if (pixel.green > *maxima) *maxima=(double) pixel.green; } if ((channel & BlueChannel) != 0) { if (pixel.blue < *minima) *minima=(double) pixel.blue; if (pixel.blue > *maxima) *maxima=(double) pixel.blue; } if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) { if ((QuantumRange-pixel.opacity) < *minima) *minima=(double) (QuantumRange-pixel.opacity); if ((QuantumRange-pixel.opacity) > *maxima) *maxima=(double) (QuantumRange-pixel.opacity); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { if ((double) pixel.index < *minima) *minima=(double) pixel.index; if ((double) pixel.index > *maxima) *maxima=(double) pixel.index; } p++; } } return(y == (ssize_t) image->rows ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l S t a t i s t i c s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelStatistics() returns statistics for each channel in the % image. The statistics include the channel depth, its minima, maxima, mean, % standard deviation, kurtosis and skewness. You can access the red channel % mean, for example, like this: % % channel_statistics=GetImageChannelStatistics(image,exception); % red_mean=channel_statistics[RedChannel].mean; % % Use MagickRelinquishMemory() to free the statistics buffer. % % The format of the GetImageChannelStatistics method is: % % ChannelStatistics *GetImageChannelStatistics(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport ChannelStatistics *GetImageChannelStatistics(const Image *image, ExceptionInfo *exception) { ChannelStatistics *channel_statistics; double area, standard_deviation; MagickPixelPacket number_bins, *histogram; QuantumAny range; register ssize_t i; size_t channels, depth, length; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); length=CompositeChannels+1UL; channel_statistics=(ChannelStatistics *) AcquireQuantumMemory(length, sizeof(*channel_statistics)); histogram=(MagickPixelPacket *) AcquireQuantumMemory(MaxMap+1U, sizeof(*histogram)); if ((channel_statistics == (ChannelStatistics *) NULL) || (histogram == (MagickPixelPacket *) NULL)) { if (histogram != (MagickPixelPacket *) NULL) histogram=(MagickPixelPacket *) RelinquishMagickMemory(histogram); if (channel_statistics != (ChannelStatistics *) NULL) channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(channel_statistics); } (void) memset(channel_statistics,0,length* sizeof(*channel_statistics)); for (i=0; i <= (ssize_t) CompositeChannels; i++) { channel_statistics[i].depth=1; channel_statistics[i].maxima=(-MagickMaximumValue); channel_statistics[i].minima=MagickMaximumValue; } (void) memset(histogram,0,(MaxMap+1U)*sizeof(*histogram)); (void) memset(&number_bins,0,sizeof(number_bins)); for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; /* Compute pixel statistics. */ p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; ) { if (channel_statistics[RedChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[RedChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelRed(p),range) == MagickFalse) { channel_statistics[RedChannel].depth++; continue; } } if (channel_statistics[GreenChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[GreenChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelGreen(p),range) == MagickFalse) { channel_statistics[GreenChannel].depth++; continue; } } if (channel_statistics[BlueChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[BlueChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelBlue(p),range) == MagickFalse) { channel_statistics[BlueChannel].depth++; continue; } } if (image->matte != MagickFalse) { if (channel_statistics[OpacityChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[OpacityChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelAlpha(p),range) == MagickFalse) { channel_statistics[OpacityChannel].depth++; continue; } } } if (image->colorspace == CMYKColorspace) { if (channel_statistics[BlackChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[BlackChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelIndex(indexes+x),range) == MagickFalse) { channel_statistics[BlackChannel].depth++; continue; } } } if ((double) GetPixelRed(p) < channel_statistics[RedChannel].minima) channel_statistics[RedChannel].minima=(double) GetPixelRed(p); if ((double) GetPixelRed(p) > channel_statistics[RedChannel].maxima) channel_statistics[RedChannel].maxima=(double) GetPixelRed(p); channel_statistics[RedChannel].sum+=GetPixelRed(p); channel_statistics[RedChannel].sum_squared+=(double) GetPixelRed(p)* GetPixelRed(p); channel_statistics[RedChannel].sum_cubed+=(double) GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p); channel_statistics[RedChannel].sum_fourth_power+=(double) GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p); if ((double) GetPixelGreen(p) < channel_statistics[GreenChannel].minima) channel_statistics[GreenChannel].minima=(double) GetPixelGreen(p); if ((double) GetPixelGreen(p) > channel_statistics[GreenChannel].maxima) channel_statistics[GreenChannel].maxima=(double) GetPixelGreen(p); channel_statistics[GreenChannel].sum+=GetPixelGreen(p); channel_statistics[GreenChannel].sum_squared+=(double) GetPixelGreen(p)* GetPixelGreen(p); channel_statistics[GreenChannel].sum_cubed+=(double) GetPixelGreen(p)* GetPixelGreen(p)*GetPixelGreen(p); channel_statistics[GreenChannel].sum_fourth_power+=(double) GetPixelGreen(p)*GetPixelGreen(p)*GetPixelGreen(p)*GetPixelGreen(p); if ((double) GetPixelBlue(p) < channel_statistics[BlueChannel].minima) channel_statistics[BlueChannel].minima=(double) GetPixelBlue(p); if ((double) GetPixelBlue(p) > channel_statistics[BlueChannel].maxima) channel_statistics[BlueChannel].maxima=(double) GetPixelBlue(p); channel_statistics[BlueChannel].sum+=GetPixelBlue(p); channel_statistics[BlueChannel].sum_squared+=(double) GetPixelBlue(p)* GetPixelBlue(p); channel_statistics[BlueChannel].sum_cubed+=(double) GetPixelBlue(p)* GetPixelBlue(p)*GetPixelBlue(p); channel_statistics[BlueChannel].sum_fourth_power+=(double) GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p); histogram[ScaleQuantumToMap(GetPixelRed(p))].red++; histogram[ScaleQuantumToMap(GetPixelGreen(p))].green++; histogram[ScaleQuantumToMap(GetPixelBlue(p))].blue++; if (image->matte != MagickFalse) { if ((double) GetPixelAlpha(p) < channel_statistics[OpacityChannel].minima) channel_statistics[OpacityChannel].minima=(double) GetPixelAlpha(p); if ((double) GetPixelAlpha(p) > channel_statistics[OpacityChannel].maxima) channel_statistics[OpacityChannel].maxima=(double) GetPixelAlpha(p); channel_statistics[OpacityChannel].sum+=GetPixelAlpha(p); channel_statistics[OpacityChannel].sum_squared+=(double) GetPixelAlpha(p)*GetPixelAlpha(p); channel_statistics[OpacityChannel].sum_cubed+=(double) GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p); channel_statistics[OpacityChannel].sum_fourth_power+=(double) GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p); histogram[ScaleQuantumToMap(GetPixelAlpha(p))].opacity++; } if (image->colorspace == CMYKColorspace) { if ((double) GetPixelIndex(indexes+x) < channel_statistics[BlackChannel].minima) channel_statistics[BlackChannel].minima=(double) GetPixelIndex(indexes+x); if ((double) GetPixelIndex(indexes+x) > channel_statistics[BlackChannel].maxima) channel_statistics[BlackChannel].maxima=(double) GetPixelIndex(indexes+x); channel_statistics[BlackChannel].sum+=GetPixelIndex(indexes+x); channel_statistics[BlackChannel].sum_squared+=(double) GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x); channel_statistics[BlackChannel].sum_cubed+=(double) GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x)* GetPixelIndex(indexes+x); channel_statistics[BlackChannel].sum_fourth_power+=(double) GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x)* GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x); histogram[ScaleQuantumToMap(GetPixelIndex(indexes+x))].index++; } x++; p++; } } for (i=0; i < (ssize_t) CompositeChannels; i++) { double area, mean, standard_deviation; /* Normalize pixel statistics. */ area=PerceptibleReciprocal((double) image->columns*image->rows); mean=channel_statistics[i].sum*area; channel_statistics[i].sum=mean; channel_statistics[i].sum_squared*=area; channel_statistics[i].sum_cubed*=area; channel_statistics[i].sum_fourth_power*=area; channel_statistics[i].mean=mean; channel_statistics[i].variance=channel_statistics[i].sum_squared; standard_deviation=sqrt(channel_statistics[i].variance-(mean*mean)); area=PerceptibleReciprocal((double) image->columns*image->rows-1.0)* ((double) image->columns*image->rows); standard_deviation=sqrt(area*standard_deviation*standard_deviation); channel_statistics[i].standard_deviation=standard_deviation; } for (i=0; i < (ssize_t) (MaxMap+1U); i++) { if (histogram[i].red > 0.0) number_bins.red++; if (histogram[i].green > 0.0) number_bins.green++; if (histogram[i].blue > 0.0) number_bins.blue++; if ((image->matte != MagickFalse) && (histogram[i].opacity > 0.0)) number_bins.opacity++; if ((image->colorspace == CMYKColorspace) && (histogram[i].index > 0.0)) number_bins.index++; } area=PerceptibleReciprocal((double) image->columns*image->rows); for (i=0; i < (ssize_t) (MaxMap+1U); i++) { /* Compute pixel entropy. */ histogram[i].red*=area; channel_statistics[RedChannel].entropy+=-histogram[i].red* MagickLog10(histogram[i].red)* PerceptibleReciprocal(MagickLog10((double) number_bins.red)); histogram[i].green*=area; channel_statistics[GreenChannel].entropy+=-histogram[i].green* MagickLog10(histogram[i].green)* PerceptibleReciprocal(MagickLog10((double) number_bins.green)); histogram[i].blue*=area; channel_statistics[BlueChannel].entropy+=-histogram[i].blue* MagickLog10(histogram[i].blue)* PerceptibleReciprocal(MagickLog10((double) number_bins.blue)); if (image->matte != MagickFalse) { histogram[i].opacity*=area; channel_statistics[OpacityChannel].entropy+=-histogram[i].opacity* MagickLog10(histogram[i].opacity)* PerceptibleReciprocal(MagickLog10((double) number_bins.opacity)); } if (image->colorspace == CMYKColorspace) { histogram[i].index*=area; channel_statistics[IndexChannel].entropy+=-histogram[i].index* MagickLog10(histogram[i].index)* PerceptibleReciprocal(MagickLog10((double) number_bins.index)); } } /* Compute overall statistics. */ for (i=0; i < (ssize_t) CompositeChannels; i++) { channel_statistics[CompositeChannels].depth=(size_t) EvaluateMax((double) channel_statistics[CompositeChannels].depth,(double) channel_statistics[i].depth); channel_statistics[CompositeChannels].minima=MagickMin( channel_statistics[CompositeChannels].minima, channel_statistics[i].minima); channel_statistics[CompositeChannels].maxima=EvaluateMax( channel_statistics[CompositeChannels].maxima, channel_statistics[i].maxima); channel_statistics[CompositeChannels].sum+=channel_statistics[i].sum; channel_statistics[CompositeChannels].sum_squared+= channel_statistics[i].sum_squared; channel_statistics[CompositeChannels].sum_cubed+= channel_statistics[i].sum_cubed; channel_statistics[CompositeChannels].sum_fourth_power+= channel_statistics[i].sum_fourth_power; channel_statistics[CompositeChannels].mean+=channel_statistics[i].mean; channel_statistics[CompositeChannels].variance+= channel_statistics[i].variance-channel_statistics[i].mean* channel_statistics[i].mean; standard_deviation=sqrt(channel_statistics[i].variance- (channel_statistics[i].mean*channel_statistics[i].mean)); area=PerceptibleReciprocal((double) image->columns*image->rows-1.0)* ((double) image->columns*image->rows); standard_deviation=sqrt(area*standard_deviation*standard_deviation); channel_statistics[CompositeChannels].standard_deviation=standard_deviation; channel_statistics[CompositeChannels].entropy+= channel_statistics[i].entropy; } channels=3; if (image->matte != MagickFalse) channels++; if (image->colorspace == CMYKColorspace) channels++; channel_statistics[CompositeChannels].sum/=channels; channel_statistics[CompositeChannels].sum_squared/=channels; channel_statistics[CompositeChannels].sum_cubed/=channels; channel_statistics[CompositeChannels].sum_fourth_power/=channels; channel_statistics[CompositeChannels].mean/=channels; channel_statistics[CompositeChannels].kurtosis/=channels; channel_statistics[CompositeChannels].skewness/=channels; channel_statistics[CompositeChannels].entropy/=channels; i=CompositeChannels; area=PerceptibleReciprocal((double) channels*image->columns*image->rows); channel_statistics[i].variance=channel_statistics[i].sum_squared; channel_statistics[i].mean=channel_statistics[i].sum; standard_deviation=sqrt(channel_statistics[i].variance- (channel_statistics[i].mean*channel_statistics[i].mean)); standard_deviation=sqrt(PerceptibleReciprocal((double) channels* image->columns*image->rows-1.0)*channels*image->columns*image->rows* standard_deviation*standard_deviation); channel_statistics[i].standard_deviation=standard_deviation; for (i=0; i <= (ssize_t) CompositeChannels; i++) { /* Compute kurtosis & skewness statistics. */ standard_deviation=PerceptibleReciprocal( channel_statistics[i].standard_deviation); channel_statistics[i].skewness=(channel_statistics[i].sum_cubed-3.0* channel_statistics[i].mean*channel_statistics[i].sum_squared+2.0* channel_statistics[i].mean*channel_statistics[i].mean* channel_statistics[i].mean)*(standard_deviation*standard_deviation* standard_deviation); channel_statistics[i].kurtosis=(channel_statistics[i].sum_fourth_power-4.0* channel_statistics[i].mean*channel_statistics[i].sum_cubed+6.0* channel_statistics[i].mean*channel_statistics[i].mean* channel_statistics[i].sum_squared-3.0*channel_statistics[i].mean* channel_statistics[i].mean*1.0*channel_statistics[i].mean* channel_statistics[i].mean)*(standard_deviation*standard_deviation* standard_deviation*standard_deviation)-3.0; } channel_statistics[CompositeChannels].mean=0.0; channel_statistics[CompositeChannels].standard_deviation=0.0; for (i=0; i < (ssize_t) CompositeChannels; i++) { channel_statistics[CompositeChannels].mean+= channel_statistics[i].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[i].standard_deviation; } channel_statistics[CompositeChannels].mean/=(double) channels; channel_statistics[CompositeChannels].standard_deviation/=(double) channels; histogram=(MagickPixelPacket *) RelinquishMagickMemory(histogram); if (y < (ssize_t) image->rows) channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(channel_statistics); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o l y n o m i a l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PolynomialImage() returns a new image where each pixel is the sum of the % pixels in the image sequence after applying its corresponding terms % (coefficient and degree pairs). % % The format of the PolynomialImage method is: % % Image *PolynomialImage(const Image *images,const size_t number_terms, % const double *terms,ExceptionInfo *exception) % Image *PolynomialImageChannel(const Image *images, % const size_t number_terms,const ChannelType channel, % const double *terms,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o channel: the channel. % % o number_terms: the number of terms in the list. The actual list length % is 2 x number_terms + 1 (the constant). % % o terms: the list of polynomial coefficients and degree pairs and a % constant. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *PolynomialImage(const Image *images, const size_t number_terms,const double *terms,ExceptionInfo *exception) { Image *polynomial_image; polynomial_image=PolynomialImageChannel(images,DefaultChannels,number_terms, terms,exception); return(polynomial_image); } MagickExport Image *PolynomialImageChannel(const Image *images, const ChannelType channel,const size_t number_terms,const double *terms, ExceptionInfo *exception) { #define PolynomialImageTag "Polynomial/Image" CacheView *polynomial_view; Image *image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket **magick_restrict polynomial_pixels, zero; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImageCanvas(images,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImage(image); return((Image *) NULL); } polynomial_pixels=AcquirePixelThreadSet(images); if (polynomial_pixels == (MagickPixelPacket **) NULL) { image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return((Image *) NULL); } /* Polynomial image pixels. */ status=MagickTrue; progress=0; GetMagickPixelPacket(images,&zero); polynomial_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict polynomial_indexes; register MagickPixelPacket *polynomial_pixel; register PixelPacket *magick_restrict q; register ssize_t i, x; size_t number_images; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(polynomial_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } polynomial_indexes=GetCacheViewAuthenticIndexQueue(polynomial_view); polynomial_pixel=polynomial_pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) polynomial_pixel[x]=zero; next=images; number_images=GetImageListLength(images); for (i=0; i < (ssize_t) number_images; i++) { register const IndexPacket *indexes; register const PixelPacket *p; if (i >= (ssize_t) number_terms) break; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) { image_view=DestroyCacheView(image_view); break; } indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { double coefficient, degree; coefficient=terms[i << 1]; degree=terms[(i << 1)+1]; if ((channel & RedChannel) != 0) polynomial_pixel[x].red+=coefficient*pow(QuantumScale*p->red,degree); if ((channel & GreenChannel) != 0) polynomial_pixel[x].green+=coefficient*pow(QuantumScale*p->green, degree); if ((channel & BlueChannel) != 0) polynomial_pixel[x].blue+=coefficient*pow(QuantumScale*p->blue, degree); if ((channel & OpacityChannel) != 0) polynomial_pixel[x].opacity+=coefficient*pow(QuantumScale* (QuantumRange-p->opacity),degree); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) polynomial_pixel[x].index+=coefficient*pow(QuantumScale*indexes[x], degree); p++; } image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].red)); SetPixelGreen(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].green)); SetPixelBlue(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].blue)); if (image->matte == MagickFalse) SetPixelOpacity(q,ClampToQuantum(QuantumRange-QuantumRange* polynomial_pixel[x].opacity)); else SetPixelAlpha(q,ClampToQuantum(QuantumRange-QuantumRange* polynomial_pixel[x].opacity)); if (image->colorspace == CMYKColorspace) SetPixelIndex(polynomial_indexes+x,ClampToQuantum(QuantumRange* polynomial_pixel[x].index)); q++; } if (SyncCacheViewAuthenticPixels(polynomial_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(images,PolynomialImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } polynomial_view=DestroyCacheView(polynomial_view); polynomial_pixels=DestroyPixelThreadSet(polynomial_pixels); if (status == MagickFalse) image=DestroyImage(image); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t a t i s t i c I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % StatisticImage() makes each pixel the min / max / median / mode / etc. of % the neighborhood of the specified width and height. % % The format of the StatisticImage method is: % % Image *StatisticImage(const Image *image,const StatisticType type, % const size_t width,const size_t height,ExceptionInfo *exception) % Image *StatisticImageChannel(const Image *image, % const ChannelType channel,const StatisticType type, % const size_t width,const size_t height,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the image channel. % % o type: the statistic type (median, mode, etc.). % % o width: the width of the pixel neighborhood. % % o height: the height of the pixel neighborhood. % % o exception: return any errors or warnings in this structure. % */ #define ListChannels 5 typedef struct _ListNode { size_t next[9], count, signature; } ListNode; typedef struct _SkipList { ssize_t level; ListNode *nodes; } SkipList; typedef struct _PixelList { size_t length, seed, signature; SkipList lists[ListChannels]; } PixelList; static PixelList *DestroyPixelList(PixelList *pixel_list) { register ssize_t i; if (pixel_list == (PixelList *) NULL) return((PixelList *) NULL); for (i=0; i < ListChannels; i++) if (pixel_list->lists[i].nodes != (ListNode *) NULL) pixel_list->lists[i].nodes=(ListNode *) RelinquishAlignedMemory( pixel_list->lists[i].nodes); pixel_list=(PixelList *) RelinquishMagickMemory(pixel_list); return(pixel_list); } static PixelList **DestroyPixelListThreadSet(PixelList **pixel_list) { register ssize_t i; assert(pixel_list != (PixelList **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixel_list[i] != (PixelList *) NULL) pixel_list[i]=DestroyPixelList(pixel_list[i]); pixel_list=(PixelList **) RelinquishMagickMemory(pixel_list); return(pixel_list); } static PixelList *AcquirePixelList(const size_t width,const size_t height) { PixelList *pixel_list; register ssize_t i; pixel_list=(PixelList *) AcquireMagickMemory(sizeof(*pixel_list)); if (pixel_list == (PixelList *) NULL) return(pixel_list); (void) memset((void *) pixel_list,0,sizeof(*pixel_list)); pixel_list->length=width*height; for (i=0; i < ListChannels; i++) { pixel_list->lists[i].nodes=(ListNode *) AcquireAlignedMemory(65537UL, sizeof(*pixel_list->lists[i].nodes)); if (pixel_list->lists[i].nodes == (ListNode *) NULL) return(DestroyPixelList(pixel_list)); (void) memset(pixel_list->lists[i].nodes,0,65537UL* sizeof(*pixel_list->lists[i].nodes)); } pixel_list->signature=MagickCoreSignature; return(pixel_list); } static PixelList **AcquirePixelListThreadSet(const size_t width, const size_t height) { PixelList **pixel_list; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixel_list=(PixelList **) AcquireQuantumMemory(number_threads, sizeof(*pixel_list)); if (pixel_list == (PixelList **) NULL) return((PixelList **) NULL); (void) memset(pixel_list,0,number_threads*sizeof(*pixel_list)); for (i=0; i < (ssize_t) number_threads; i++) { pixel_list[i]=AcquirePixelList(width,height); if (pixel_list[i] == (PixelList *) NULL) return(DestroyPixelListThreadSet(pixel_list)); } return(pixel_list); } static void AddNodePixelList(PixelList *pixel_list,const ssize_t channel, const size_t color) { register SkipList *list; register ssize_t level; size_t search, update[9]; /* Initialize the node. */ list=pixel_list->lists+channel; list->nodes[color].signature=pixel_list->signature; list->nodes[color].count=1; /* Determine where it belongs in the list. */ search=65536UL; for (level=list->level; level >= 0; level--) { while (list->nodes[search].next[level] < color) search=list->nodes[search].next[level]; update[level]=search; } /* Generate a pseudo-random level for this node. */ for (level=0; ; level++) { pixel_list->seed=(pixel_list->seed*42893621L)+1L; if ((pixel_list->seed & 0x300) != 0x300) break; } if (level > 8) level=8; if (level > (list->level+2)) level=list->level+2; /* If we're raising the list's level, link back to the root node. */ while (level > list->level) { list->level++; update[list->level]=65536UL; } /* Link the node into the skip-list. */ do { list->nodes[color].next[level]=list->nodes[update[level]].next[level]; list->nodes[update[level]].next[level]=color; } while (level-- > 0); } static void GetMaximumPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color, maximum; ssize_t count; unsigned short channels[ListChannels]; /* Find the maximum value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; maximum=list->nodes[color].next[0]; do { color=list->nodes[color].next[0]; if (color > maximum) maximum=color; count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); channels[channel]=(unsigned short) maximum; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetMeanPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { MagickRealType sum; register SkipList *list; register ssize_t channel; size_t color; ssize_t count; unsigned short channels[ListChannels]; /* Find the mean value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; sum=0.0; do { color=list->nodes[color].next[0]; sum+=(MagickRealType) list->nodes[color].count*color; count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; channels[channel]=(unsigned short) sum; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetMedianPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color; ssize_t count; unsigned short channels[ListChannels]; /* Find the median value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; do { color=list->nodes[color].next[0]; count+=list->nodes[color].count; } while (count <= (ssize_t) (pixel_list->length >> 1)); channels[channel]=(unsigned short) color; } GetMagickPixelPacket((const Image *) NULL,pixel); pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetMinimumPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color, minimum; ssize_t count; unsigned short channels[ListChannels]; /* Find the minimum value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; count=0; color=65536UL; minimum=list->nodes[color].next[0]; do { color=list->nodes[color].next[0]; if (color < minimum) minimum=color; count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); channels[channel]=(unsigned short) minimum; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetModePixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color, max_count, mode; ssize_t count; unsigned short channels[5]; /* Make each pixel the 'predominant color' of the specified neighborhood. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; mode=color; max_count=list->nodes[mode].count; count=0; do { color=list->nodes[color].next[0]; if (list->nodes[color].count > max_count) { mode=color; max_count=list->nodes[mode].count; } count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); channels[channel]=(unsigned short) mode; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetNonpeakPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color, next, previous; ssize_t count; unsigned short channels[5]; /* Finds the non peak value for each of the colors. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; next=list->nodes[color].next[0]; count=0; do { previous=color; color=next; next=list->nodes[color].next[0]; count+=list->nodes[color].count; } while (count <= (ssize_t) (pixel_list->length >> 1)); if ((previous == 65536UL) && (next != 65536UL)) color=next; else if ((previous != 65536UL) && (next == 65536UL)) color=previous; channels[channel]=(unsigned short) color; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetRootMeanSquarePixelList(PixelList *pixel_list, MagickPixelPacket *pixel) { MagickRealType sum; register SkipList *list; register ssize_t channel; size_t color; ssize_t count; unsigned short channels[ListChannels]; /* Find the root mean square value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; sum=0.0; do { color=list->nodes[color].next[0]; sum+=(MagickRealType) (list->nodes[color].count*color*color); count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; channels[channel]=(unsigned short) sqrt(sum); } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetStandardDeviationPixelList(PixelList *pixel_list, MagickPixelPacket *pixel) { MagickRealType sum, sum_squared; register SkipList *list; register ssize_t channel; size_t color; ssize_t count; unsigned short channels[ListChannels]; /* Find the standard-deviation value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; sum=0.0; sum_squared=0.0; do { register ssize_t i; color=list->nodes[color].next[0]; sum+=(MagickRealType) list->nodes[color].count*color; for (i=0; i < (ssize_t) list->nodes[color].count; i++) sum_squared+=((MagickRealType) color)*((MagickRealType) color); count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; sum_squared/=pixel_list->length; channels[channel]=(unsigned short) sqrt(sum_squared-(sum*sum)); } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static inline void InsertPixelList(const Image *image,const PixelPacket *pixel, const IndexPacket *indexes,PixelList *pixel_list) { size_t signature; unsigned short index; index=ScaleQuantumToShort(GetPixelRed(pixel)); signature=pixel_list->lists[0].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[0].nodes[index].count++; else AddNodePixelList(pixel_list,0,index); index=ScaleQuantumToShort(GetPixelGreen(pixel)); signature=pixel_list->lists[1].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[1].nodes[index].count++; else AddNodePixelList(pixel_list,1,index); index=ScaleQuantumToShort(GetPixelBlue(pixel)); signature=pixel_list->lists[2].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[2].nodes[index].count++; else AddNodePixelList(pixel_list,2,index); index=ScaleQuantumToShort(GetPixelOpacity(pixel)); signature=pixel_list->lists[3].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[3].nodes[index].count++; else AddNodePixelList(pixel_list,3,index); if (image->colorspace == CMYKColorspace) index=ScaleQuantumToShort(GetPixelIndex(indexes)); signature=pixel_list->lists[4].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[4].nodes[index].count++; else AddNodePixelList(pixel_list,4,index); } static void ResetPixelList(PixelList *pixel_list) { int level; register ListNode *root; register SkipList *list; register ssize_t channel; /* Reset the skip-list. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; root=list->nodes+65536UL; list->level=0; for (level=0; level < 9; level++) root->next[level]=65536UL; } pixel_list->seed=pixel_list->signature++; } MagickExport Image *StatisticImage(const Image *image,const StatisticType type, const size_t width,const size_t height,ExceptionInfo *exception) { Image *statistic_image; statistic_image=StatisticImageChannel(image,DefaultChannels,type,width, height,exception); return(statistic_image); } MagickExport Image *StatisticImageChannel(const Image *image, const ChannelType channel,const StatisticType type,const size_t width, const size_t height,ExceptionInfo *exception) { #define StatisticImageTag "Statistic/Image" CacheView *image_view, *statistic_view; Image *statistic_image; MagickBooleanType status; MagickOffsetType progress; PixelList **magick_restrict pixel_list; size_t neighbor_height, neighbor_width; ssize_t y; /* Initialize statistics image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); statistic_image=CloneImage(image,0,0,MagickTrue,exception); if (statistic_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(statistic_image,DirectClass) == MagickFalse) { InheritException(exception,&statistic_image->exception); statistic_image=DestroyImage(statistic_image); return((Image *) NULL); } neighbor_width=width == 0 ? GetOptimalKernelWidth2D((double) width,0.5) : width; neighbor_height=height == 0 ? GetOptimalKernelWidth2D((double) height,0.5) : height; pixel_list=AcquirePixelListThreadSet(neighbor_width,neighbor_height); if (pixel_list == (PixelList **) NULL) { statistic_image=DestroyImage(statistic_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Make each pixel the min / max / median / mode / etc. of the neighborhood. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); statistic_view=AcquireAuthenticCacheView(statistic_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,statistic_image,statistic_image->rows,1) #endif for (y=0; y < (ssize_t) statistic_image->rows; y++) { const int id = GetOpenMPThreadId(); register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict statistic_indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) neighbor_width/2L),y- (ssize_t) (neighbor_height/2L),image->columns+neighbor_width, neighbor_height,exception); q=QueueCacheViewAuthenticPixels(statistic_view,0,y,statistic_image->columns, 1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); statistic_indexes=GetCacheViewAuthenticIndexQueue(statistic_view); for (x=0; x < (ssize_t) statistic_image->columns; x++) { MagickPixelPacket pixel; register const IndexPacket *magick_restrict s; register const PixelPacket *magick_restrict r; register ssize_t u, v; r=p; s=indexes+x; ResetPixelList(pixel_list[id]); for (v=0; v < (ssize_t) neighbor_height; v++) { for (u=0; u < (ssize_t) neighbor_width; u++) InsertPixelList(image,r+u,s+u,pixel_list[id]); r+=image->columns+neighbor_width; s+=image->columns+neighbor_width; } GetMagickPixelPacket(image,&pixel); SetMagickPixelPacket(image,p+neighbor_width*neighbor_height/2,indexes+x+ neighbor_width*neighbor_height/2,&pixel); switch (type) { case GradientStatistic: { MagickPixelPacket maximum, minimum; GetMinimumPixelList(pixel_list[id],&pixel); minimum=pixel; GetMaximumPixelList(pixel_list[id],&pixel); maximum=pixel; pixel.red=MagickAbsoluteValue(maximum.red-minimum.red); pixel.green=MagickAbsoluteValue(maximum.green-minimum.green); pixel.blue=MagickAbsoluteValue(maximum.blue-minimum.blue); pixel.opacity=MagickAbsoluteValue(maximum.opacity-minimum.opacity); if (image->colorspace == CMYKColorspace) pixel.index=MagickAbsoluteValue(maximum.index-minimum.index); break; } case MaximumStatistic: { GetMaximumPixelList(pixel_list[id],&pixel); break; } case MeanStatistic: { GetMeanPixelList(pixel_list[id],&pixel); break; } case MedianStatistic: default: { GetMedianPixelList(pixel_list[id],&pixel); break; } case MinimumStatistic: { GetMinimumPixelList(pixel_list[id],&pixel); break; } case ModeStatistic: { GetModePixelList(pixel_list[id],&pixel); break; } case NonpeakStatistic: { GetNonpeakPixelList(pixel_list[id],&pixel); break; } case RootMeanSquareStatistic: { GetRootMeanSquarePixelList(pixel_list[id],&pixel); break; } case StandardDeviationStatistic: { GetStandardDeviationPixelList(pixel_list[id],&pixel); break; } } if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(pixel.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(pixel.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(pixel.blue)); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,ClampToQuantum(pixel.opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(statistic_indexes+x,ClampToQuantum(pixel.index)); p++; q++; } if (SyncCacheViewAuthenticPixels(statistic_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,StatisticImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } statistic_view=DestroyCacheView(statistic_view); image_view=DestroyCacheView(image_view); pixel_list=DestroyPixelListThreadSet(pixel_list); if (status == MagickFalse) statistic_image=DestroyImage(statistic_image); return(statistic_image); }
null
125
CWE-787
CVE-2019-13304
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP N N M M % % P P NN N MM MM % % PPPP N N N M M M % % P N NN M M % % P N N M M % % % % % % Read/Write PBMPlus Portable Anymap Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" /* Typedef declarations. */ typedef struct _CommentInfo { char *comment; size_t extent; } CommentInfo; /* Forward declarations. */ static MagickBooleanType WritePNMImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P N M % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPNM() returns MagickTrue if the image format type, identified by the % magick string, is PNM. % % The format of the IsPNM method is: % % MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o extent: Specifies the extent of the magick string. % */ static MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent) { if (extent < 2) return(MagickFalse); if ((*magick == (unsigned char) 'P') && ((magick[1] == '1') || (magick[1] == '2') || (magick[1] == '3') || (magick[1] == '4') || (magick[1] == '5') || (magick[1] == '6') || (magick[1] == '7') || (magick[1] == 'F') || (magick[1] == 'f'))) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPNMImage() reads a Portable Anymap image file and returns it. % It allocates the memory necessary for the new Image structure and returns % a pointer to the new image. % % The format of the ReadPNMImage method is: % % Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static int PNMComment(Image *image,CommentInfo *comment_info, ExceptionInfo *exception) { int c; register char *p; /* Read comment. */ p=comment_info->comment+strlen(comment_info->comment); for (c='#'; (c != EOF) && (c != (int) '\n') && (c != (int) '\r'); p++) { if ((size_t) (p-comment_info->comment+1) >= comment_info->extent) { comment_info->extent<<=1; comment_info->comment=(char *) ResizeQuantumMemory( comment_info->comment,comment_info->extent, sizeof(*comment_info->comment)); if (comment_info->comment == (char *) NULL) return(-1); p=comment_info->comment+strlen(comment_info->comment); } c=ReadBlobByte(image); if (c != EOF) { *p=(char) c; *(p+1)='\0'; } } return(c); } static unsigned int PNMInteger(Image *image,CommentInfo *comment_info, const unsigned int base,ExceptionInfo *exception) { int c; unsigned int value; /* Skip any leading whitespace. */ do { c=ReadBlobByte(image); if (c == EOF) return(0); if (c == (int) '#') c=PNMComment(image,comment_info,exception); } while ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r')); if (base == 2) return((unsigned int) (c-(int) '0')); /* Evaluate number. */ value=0; while (isdigit(c) != 0) { if (value <= (unsigned int) (INT_MAX/10)) { value*=10; if (value <= (unsigned int) (INT_MAX-(c-(int) '0'))) value+=c-(int) '0'; } c=ReadBlobByte(image); if (c == EOF) return(0); } if (c == (int) '#') c=PNMComment(image,comment_info,exception); return(value); } static Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define ThrowPNMException(exception,message) \ { \ if (comment_info.comment != (char *) NULL) \ comment_info.comment=DestroyString(comment_info.comment); \ ThrowReaderException((exception),(message)); \ } char format; CommentInfo comment_info; double quantum_scale; Image *image; MagickBooleanType status; QuantumAny max_value; QuantumInfo *quantum_info; QuantumType quantum_type; size_t depth, extent, packet_size; ssize_t count, row, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read PNM image. */ count=ReadBlob(image,1,(unsigned char *) &format); do { /* Initialize image structure. */ comment_info.comment=AcquireString(NULL); comment_info.extent=MagickPathExtent; if ((count != 1) || (format != 'P')) ThrowPNMException(CorruptImageError,"ImproperImageHeader"); max_value=1; quantum_type=RGBQuantum; quantum_scale=1.0; format=(char) ReadBlobByte(image); if (format != '7') { /* PBM, PGM, PPM, and PNM. */ image->columns=(size_t) PNMInteger(image,&comment_info,10,exception); image->rows=(size_t) PNMInteger(image,&comment_info,10,exception); if ((format == 'f') || (format == 'F')) { char scale[MagickPathExtent]; if (ReadBlobString(image,scale) != (char *) NULL) quantum_scale=StringToDouble(scale,(char **) NULL); } else { if ((format == '1') || (format == '4')) max_value=1; /* bitmap */ else max_value=(QuantumAny) PNMInteger(image,&comment_info,10, exception); } } else { char keyword[MagickPathExtent], value[MagickPathExtent]; int c; register char *p; /* PAM. */ for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); if (c == '#') { /* Comment. */ c=PNMComment(image,&comment_info,exception); c=ReadBlobByte(image); while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } p=keyword; do { if ((size_t) (p-keyword) < (MagickPathExtent-1)) *p++=c; c=ReadBlobByte(image); } while (isalnum(c)); *p='\0'; if (LocaleCompare(keyword,"endhdr") == 0) break; while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); p=value; while (isalnum(c) || (c == '_')) { if ((size_t) (p-value) < (MagickPathExtent-1)) *p++=c; c=ReadBlobByte(image); } *p='\0'; /* Assign a value to the specified keyword. */ if (LocaleCompare(keyword,"depth") == 0) packet_size=StringToUnsignedLong(value); (void) packet_size; if (LocaleCompare(keyword,"height") == 0) image->rows=StringToUnsignedLong(value); if (LocaleCompare(keyword,"maxval") == 0) max_value=StringToUnsignedLong(value); if (LocaleCompare(keyword,"TUPLTYPE") == 0) { if (LocaleCompare(value,"BLACKANDWHITE") == 0) { (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=GrayQuantum; } if (LocaleCompare(value,"BLACKANDWHITE_ALPHA") == 0) { (void) SetImageColorspace(image,GRAYColorspace,exception); image->alpha_trait=BlendPixelTrait; quantum_type=GrayAlphaQuantum; } if (LocaleCompare(value,"GRAYSCALE") == 0) { quantum_type=GrayQuantum; (void) SetImageColorspace(image,GRAYColorspace,exception); } if (LocaleCompare(value,"GRAYSCALE_ALPHA") == 0) { (void) SetImageColorspace(image,GRAYColorspace,exception); image->alpha_trait=BlendPixelTrait; quantum_type=GrayAlphaQuantum; } if (LocaleCompare(value,"RGB_ALPHA") == 0) { image->alpha_trait=BlendPixelTrait; quantum_type=RGBAQuantum; } if (LocaleCompare(value,"CMYK") == 0) { (void) SetImageColorspace(image,CMYKColorspace,exception); quantum_type=CMYKQuantum; } if (LocaleCompare(value,"CMYK_ALPHA") == 0) { (void) SetImageColorspace(image,CMYKColorspace,exception); image->alpha_trait=BlendPixelTrait; quantum_type=CMYKAQuantum; } } if (LocaleCompare(keyword,"width") == 0) image->columns=StringToUnsignedLong(value); } } if ((image->columns == 0) || (image->rows == 0)) ThrowPNMException(CorruptImageError,"NegativeOrZeroImageSize"); if ((max_value == 0) || (max_value > 4294967295UL)) ThrowPNMException(CorruptImageError,"ImproperImageHeader"); for (depth=1; GetQuantumRange(depth) < max_value; depth++) ; image->depth=depth; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((MagickSizeType) (image->columns*image->rows/8) > GetBlobSize(image)) ThrowPNMException(CorruptImageError,"InsufficientImageDataInFile"); status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { comment_info.comment=DestroyString(comment_info.comment); \ return(DestroyImageList(image)); } (void) ResetImagePixels(image,exception); /* Convert PNM pixels to runextent-encoded MIFF packets. */ row=0; y=0; switch (format) { case '1': { /* Convert PBM image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGray(image,PNMInteger(image,&comment_info,2,exception) == 0 ? QuantumRange : 0,q); if (EOFBlob(image) != MagickFalse) break; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } image->type=BilevelType; break; } case '2': { Quantum intensity; /* Convert PGM image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { intensity=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); if (EOFBlob(image) != MagickFalse) break; SetPixelGray(image,intensity,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } image->type=GrayscaleType; break; } case '3': { /* Convert PNM image to pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Quantum pixel; pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); if (EOFBlob(image) != MagickFalse) break; SetPixelRed(image,pixel,q); pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); SetPixelGreen(image,pixel,q); pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); SetPixelBlue(image,pixel,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } break; } case '4': { /* Convert PBM raw image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=GrayQuantum; if (image->storage_class == PseudoClass) quantum_type=IndexQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); SetQuantumMinIsWhite(quantum_info,MagickTrue); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register Quantum *magick_restrict q; ssize_t offset; size_t length; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (length != extent) break; sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case '5': { /* Convert PGM raw image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=GrayQuantum; extent=(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; ssize_t offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=pixels; switch (image->depth) { case 8: case 16: case 32: { (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q); q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q); q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q); q+=GetPixelChannels(image); } } break; } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case '6': { /* Convert PNM raster image to pixel packets. */ quantum_type=RGBQuantum; extent=3*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; ssize_t offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=pixels; switch (image->depth) { case 8: { for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleShortToQuantum(pixel),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleLongToQuantum(pixel),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } break; } default: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } } break; } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '7': { size_t channels; /* Convert PAM raster image to pixel packets. */ switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { channels=1; break; } case CMYKQuantum: case CMYKAQuantum: { channels=4; break; } default: { channels=3; break; } } if (image->alpha_trait != UndefinedPixelTrait) channels++; extent=channels*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; ssize_t offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=pixels; switch (image->depth) { case 8: case 16: case 32: { (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushCharPixel(p,&pixel); if (image->depth != 1) SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); else SetPixelAlpha(image,QuantumRange- ScaleAnyToQuantum(pixel,max_value),q); } q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } break; } case CMYKQuantum: case CMYKAQuantum: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushCharPixel(p,&pixel); SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushCharPixel(p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } break; } default: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushCharPixel(p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } break; } } } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case 'F': case 'f': { /* Convert PFM raster image to pixel packets. */ if (format == 'f') (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=format == 'f' ? GrayQuantum : RGBQuantum; image->endian=quantum_scale < 0.0 ? LSBEndian : MSBEndian; image->depth=32; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumDepth(image,quantum_info,32); if (status == MagickFalse) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); SetQuantumScale(quantum_info,(double) QuantumRange*fabs(quantum_scale)); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register Quantum *magick_restrict q; ssize_t offset; size_t length; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,(ssize_t) (image->rows-offset-1), image->columns,1,exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (length != extent) break; sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } default: ThrowPNMException(CorruptImageError,"ImproperImageHeader"); } if (*comment_info.comment != '\0') (void) SetImageProperty(image,"comment",comment_info.comment,exception); comment_info.comment=DestroyString(comment_info.comment); if (y < (ssize_t) image->rows) ThrowPNMException(CorruptImageError,"UnableToReadImageData"); if (EOFBlob(image) != MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"UnexpectedEndOfFile","`%s'",image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((format == '1') || (format == '2') || (format == '3')) do { /* Skip to end of line. */ count=ReadBlob(image,1,(unsigned char *) &format); if (count != 1) break; if (format == 'P') break; } while (format != '\n'); count=ReadBlob(image,1,(unsigned char *) &format); if ((count == 1) && (format == 'P')) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count == 1) && (format == 'P')); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPNMImage() adds properties for the PNM image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPNMImage method is: % % size_t RegisterPNMImage(void) % */ ModuleExport size_t RegisterPNMImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PNM","PAM","Common 2-dimensional bitmap format"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PBM", "Portable bitmap format (black and white)"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-bitmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PFM","Portable float format"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PGM","Portable graymap format (gray scale)"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-greymap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PNM","Portable anymap"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->magick=(IsImageFormatHandler *) IsPNM; entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PPM","Portable pixmap format (color)"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPNMImage() removes format registrations made by the % PNM module from the list of supported formats. % % The format of the UnregisterPNMImage method is: % % UnregisterPNMImage(void) % */ ModuleExport void UnregisterPNMImage(void) { (void) UnregisterMagickInfo("PAM"); (void) UnregisterMagickInfo("PBM"); (void) UnregisterMagickInfo("PGM"); (void) UnregisterMagickInfo("PNM"); (void) UnregisterMagickInfo("PPM"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePNMImage() writes an image to a file in the PNM rasterfile format. % % The format of the WritePNMImage method is: % % MagickBooleanType WritePNMImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { char buffer[MagickPathExtent], format, magick[MagickPathExtent]; const char *value; MagickBooleanType status; MagickOffsetType scene; Quantum index; QuantumAny pixel; QuantumInfo *quantum_info; QuantumType quantum_type; register unsigned char *q; size_t extent, imageListLength, packet_size; ssize_t count, y; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); scene=0; imageListLength=GetImageListLength(image); do { QuantumAny max_value; /* Write PNM file header. */ packet_size=3; quantum_type=RGBQuantum; (void) CopyMagickString(magick,image_info->magick,MagickPathExtent); max_value=GetQuantumRange(image->depth); switch (magick[1]) { case 'A': case 'a': { format='7'; break; } case 'B': case 'b': { format='4'; if (image_info->compression == NoCompression) format='1'; break; } case 'F': case 'f': { format='F'; if (SetImageGray(image,exception) != MagickFalse) format='f'; break; } case 'G': case 'g': { format='5'; if (image_info->compression == NoCompression) format='2'; break; } case 'N': case 'n': { if ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse)) { format='5'; if (image_info->compression == NoCompression) format='2'; if (SetImageMonochrome(image,exception) != MagickFalse) { format='4'; if (image_info->compression == NoCompression) format='1'; } break; } } default: { format='6'; if (image_info->compression == NoCompression) format='3'; break; } } (void) FormatLocaleString(buffer,MagickPathExtent,"P%c\n",format); (void) WriteBlobString(image,buffer); value=GetImageProperty(image,"comment",exception); if (value != (const char *) NULL) { register const char *p; /* Write comments to file. */ (void) WriteBlobByte(image,'#'); for (p=value; *p != '\0'; p++) { (void) WriteBlobByte(image,(unsigned char) *p); if ((*p == '\n') || (*p == '\r')) (void) WriteBlobByte(image,'#'); } (void) WriteBlobByte(image,'\n'); } if (format != '7') { (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g\n", (double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); } else { char type[MagickPathExtent]; /* PAM header. */ (void) FormatLocaleString(buffer,MagickPathExtent, "WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); quantum_type=GetQuantumType(image,exception); switch (quantum_type) { case CMYKQuantum: case CMYKAQuantum: { packet_size=4; (void) CopyMagickString(type,"CMYK",MagickPathExtent); break; } case GrayQuantum: case GrayAlphaQuantum: { packet_size=1; (void) CopyMagickString(type,"GRAYSCALE",MagickPathExtent); if (IdentifyImageMonochrome(image,exception) != MagickFalse) (void) CopyMagickString(type,"BLACKANDWHITE",MagickPathExtent); break; } default: { quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=RGBAQuantum; packet_size=3; (void) CopyMagickString(type,"RGB",MagickPathExtent); break; } } if (image->alpha_trait != UndefinedPixelTrait) { packet_size++; (void) ConcatenateMagickString(type,"_ALPHA",MagickPathExtent); } if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent, "DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, "TUPLTYPE %s\nENDHDR\n",type); (void) WriteBlobString(image,buffer); } /* Convert runextent encoded to PNM raster pixels. */ switch (format) { case '1': { unsigned char pixels[2048]; /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType,exception); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ? '0' : '1'); *q++=' '; if ((q-pixels+1) >= (ssize_t) sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '2': { unsigned char pixels[2048]; /* Convert image to a PGM image. */ if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { index=ClampToQuantum(GetPixelLuma(image,p)); if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,"%u ", ScaleQuantumToChar(index)); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u ",ScaleQuantumToShort(index)); else count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u ",ScaleQuantumToLong(index)); extent=(size_t) count; if ((q-pixels+extent+1) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } (void) strncpy((char *) q,buffer,extent); q+=extent; p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '3': { unsigned char pixels[2048]; /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToChar(GetPixelRed(image,p)), ScaleQuantumToChar(GetPixelGreen(image,p)), ScaleQuantumToChar(GetPixelBlue(image,p))); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToShort(GetPixelRed(image,p)), ScaleQuantumToShort(GetPixelGreen(image,p)), ScaleQuantumToShort(GetPixelBlue(image,p))); else count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToLong(GetPixelRed(image,p)), ScaleQuantumToLong(GetPixelGreen(image,p)), ScaleQuantumToLong(GetPixelBlue(image,p))); extent=(size_t) count; if ((q-pixels+extent+2) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } (void) strncpy((char *) q,buffer,extent); q+=extent; p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '4': { register unsigned char *pixels; /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType,exception); image->depth=1; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '5': { register unsigned char *pixels; /* Convert image to a PGM image. */ if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,GrayQuantum); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); else { if (image->depth == 8) pixel=ScaleQuantumToChar(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p), max_value); } q=PopCharPixel((unsigned char) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image, p)),max_value); else { if (image->depth == 16) pixel=ScaleQuantumToShort(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p), max_value); } q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,p)), max_value); else { if (image->depth == 16) pixel=ScaleQuantumToLong(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); } q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '6': { register unsigned char *pixels; /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '7': { register unsigned char *pixels; /* Convert image to a PAM. */ if (image->depth > 32) image->depth=32; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image, p)),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } case CMYKQuantum: case CMYKAQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case 'F': case 'f': { register unsigned char *pixels; (void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" : "1.0\n"); image->depth=32; quantum_type=format == 'f' ? GrayQuantum : RGBQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); for (y=(ssize_t) image->rows-1; y >= 0; y--) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); (void) WriteBlob(image,extent,pixels); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } } if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
null
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP N N M M % % P P NN N MM MM % % PPPP N N N M M M % % P N NN M M % % P N N M M % % % % % % Read/Write PBMPlus Portable Anymap Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" /* Typedef declarations. */ typedef struct _CommentInfo { char *comment; size_t extent; } CommentInfo; /* Forward declarations. */ static MagickBooleanType WritePNMImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P N M % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPNM() returns MagickTrue if the image format type, identified by the % magick string, is PNM. % % The format of the IsPNM method is: % % MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o extent: Specifies the extent of the magick string. % */ static MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent) { if (extent < 2) return(MagickFalse); if ((*magick == (unsigned char) 'P') && ((magick[1] == '1') || (magick[1] == '2') || (magick[1] == '3') || (magick[1] == '4') || (magick[1] == '5') || (magick[1] == '6') || (magick[1] == '7') || (magick[1] == 'F') || (magick[1] == 'f'))) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPNMImage() reads a Portable Anymap image file and returns it. % It allocates the memory necessary for the new Image structure and returns % a pointer to the new image. % % The format of the ReadPNMImage method is: % % Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static int PNMComment(Image *image,CommentInfo *comment_info, ExceptionInfo *exception) { int c; register char *p; /* Read comment. */ p=comment_info->comment+strlen(comment_info->comment); for (c='#'; (c != EOF) && (c != (int) '\n') && (c != (int) '\r'); p++) { if ((size_t) (p-comment_info->comment+1) >= comment_info->extent) { comment_info->extent<<=1; comment_info->comment=(char *) ResizeQuantumMemory( comment_info->comment,comment_info->extent, sizeof(*comment_info->comment)); if (comment_info->comment == (char *) NULL) return(-1); p=comment_info->comment+strlen(comment_info->comment); } c=ReadBlobByte(image); if (c != EOF) { *p=(char) c; *(p+1)='\0'; } } return(c); } static unsigned int PNMInteger(Image *image,CommentInfo *comment_info, const unsigned int base,ExceptionInfo *exception) { int c; unsigned int value; /* Skip any leading whitespace. */ do { c=ReadBlobByte(image); if (c == EOF) return(0); if (c == (int) '#') c=PNMComment(image,comment_info,exception); } while ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r')); if (base == 2) return((unsigned int) (c-(int) '0')); /* Evaluate number. */ value=0; while (isdigit(c) != 0) { if (value <= (unsigned int) (INT_MAX/10)) { value*=10; if (value <= (unsigned int) (INT_MAX-(c-(int) '0'))) value+=c-(int) '0'; } c=ReadBlobByte(image); if (c == EOF) return(0); } if (c == (int) '#') c=PNMComment(image,comment_info,exception); return(value); } static Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define ThrowPNMException(exception,message) \ { \ if (comment_info.comment != (char *) NULL) \ comment_info.comment=DestroyString(comment_info.comment); \ ThrowReaderException((exception),(message)); \ } char format; CommentInfo comment_info; double quantum_scale; Image *image; MagickBooleanType status; QuantumAny max_value; QuantumInfo *quantum_info; QuantumType quantum_type; size_t depth, extent, packet_size; ssize_t count, row, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read PNM image. */ count=ReadBlob(image,1,(unsigned char *) &format); do { /* Initialize image structure. */ comment_info.comment=AcquireString(NULL); comment_info.extent=MagickPathExtent; if ((count != 1) || (format != 'P')) ThrowPNMException(CorruptImageError,"ImproperImageHeader"); max_value=1; quantum_type=RGBQuantum; quantum_scale=1.0; format=(char) ReadBlobByte(image); if (format != '7') { /* PBM, PGM, PPM, and PNM. */ image->columns=(size_t) PNMInteger(image,&comment_info,10,exception); image->rows=(size_t) PNMInteger(image,&comment_info,10,exception); if ((format == 'f') || (format == 'F')) { char scale[MagickPathExtent]; if (ReadBlobString(image,scale) != (char *) NULL) quantum_scale=StringToDouble(scale,(char **) NULL); } else { if ((format == '1') || (format == '4')) max_value=1; /* bitmap */ else max_value=(QuantumAny) PNMInteger(image,&comment_info,10, exception); } } else { char keyword[MagickPathExtent], value[MagickPathExtent]; int c; register char *p; /* PAM. */ for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); if (c == '#') { /* Comment. */ c=PNMComment(image,&comment_info,exception); c=ReadBlobByte(image); while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } p=keyword; do { if ((size_t) (p-keyword) < (MagickPathExtent-1)) *p++=c; c=ReadBlobByte(image); } while (isalnum(c)); *p='\0'; if (LocaleCompare(keyword,"endhdr") == 0) break; while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); p=value; while (isalnum(c) || (c == '_')) { if ((size_t) (p-value) < (MagickPathExtent-1)) *p++=c; c=ReadBlobByte(image); } *p='\0'; /* Assign a value to the specified keyword. */ if (LocaleCompare(keyword,"depth") == 0) packet_size=StringToUnsignedLong(value); (void) packet_size; if (LocaleCompare(keyword,"height") == 0) image->rows=StringToUnsignedLong(value); if (LocaleCompare(keyword,"maxval") == 0) max_value=StringToUnsignedLong(value); if (LocaleCompare(keyword,"TUPLTYPE") == 0) { if (LocaleCompare(value,"BLACKANDWHITE") == 0) { (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=GrayQuantum; } if (LocaleCompare(value,"BLACKANDWHITE_ALPHA") == 0) { (void) SetImageColorspace(image,GRAYColorspace,exception); image->alpha_trait=BlendPixelTrait; quantum_type=GrayAlphaQuantum; } if (LocaleCompare(value,"GRAYSCALE") == 0) { quantum_type=GrayQuantum; (void) SetImageColorspace(image,GRAYColorspace,exception); } if (LocaleCompare(value,"GRAYSCALE_ALPHA") == 0) { (void) SetImageColorspace(image,GRAYColorspace,exception); image->alpha_trait=BlendPixelTrait; quantum_type=GrayAlphaQuantum; } if (LocaleCompare(value,"RGB_ALPHA") == 0) { image->alpha_trait=BlendPixelTrait; quantum_type=RGBAQuantum; } if (LocaleCompare(value,"CMYK") == 0) { (void) SetImageColorspace(image,CMYKColorspace,exception); quantum_type=CMYKQuantum; } if (LocaleCompare(value,"CMYK_ALPHA") == 0) { (void) SetImageColorspace(image,CMYKColorspace,exception); image->alpha_trait=BlendPixelTrait; quantum_type=CMYKAQuantum; } } if (LocaleCompare(keyword,"width") == 0) image->columns=StringToUnsignedLong(value); } } if ((image->columns == 0) || (image->rows == 0)) ThrowPNMException(CorruptImageError,"NegativeOrZeroImageSize"); if ((max_value == 0) || (max_value > 4294967295UL)) ThrowPNMException(CorruptImageError,"ImproperImageHeader"); for (depth=1; GetQuantumRange(depth) < max_value; depth++) ; image->depth=depth; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((MagickSizeType) (image->columns*image->rows/8) > GetBlobSize(image)) ThrowPNMException(CorruptImageError,"InsufficientImageDataInFile"); status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { comment_info.comment=DestroyString(comment_info.comment); \ return(DestroyImageList(image)); } (void) ResetImagePixels(image,exception); /* Convert PNM pixels to runextent-encoded MIFF packets. */ row=0; y=0; switch (format) { case '1': { /* Convert PBM image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGray(image,PNMInteger(image,&comment_info,2,exception) == 0 ? QuantumRange : 0,q); if (EOFBlob(image) != MagickFalse) break; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } image->type=BilevelType; break; } case '2': { Quantum intensity; /* Convert PGM image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { intensity=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); if (EOFBlob(image) != MagickFalse) break; SetPixelGray(image,intensity,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } image->type=GrayscaleType; break; } case '3': { /* Convert PNM image to pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Quantum pixel; pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); if (EOFBlob(image) != MagickFalse) break; SetPixelRed(image,pixel,q); pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); SetPixelGreen(image,pixel,q); pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); SetPixelBlue(image,pixel,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } break; } case '4': { /* Convert PBM raw image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=GrayQuantum; if (image->storage_class == PseudoClass) quantum_type=IndexQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); SetQuantumMinIsWhite(quantum_info,MagickTrue); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register Quantum *magick_restrict q; ssize_t offset; size_t length; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (length != extent) break; sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case '5': { /* Convert PGM raw image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=GrayQuantum; extent=(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; ssize_t offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=pixels; switch (image->depth) { case 8: case 16: case 32: { (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q); q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q); q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q); q+=GetPixelChannels(image); } } break; } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case '6': { /* Convert PNM raster image to pixel packets. */ quantum_type=RGBQuantum; extent=3*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; ssize_t offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=pixels; switch (image->depth) { case 8: { for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleShortToQuantum(pixel),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleLongToQuantum(pixel),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } break; } default: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } } break; } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '7': { size_t channels; /* Convert PAM raster image to pixel packets. */ switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { channels=1; break; } case CMYKQuantum: case CMYKAQuantum: { channels=4; break; } default: { channels=3; break; } } if (image->alpha_trait != UndefinedPixelTrait) channels++; extent=channels*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; ssize_t offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=pixels; switch (image->depth) { case 8: case 16: case 32: { (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushCharPixel(p,&pixel); if (image->depth != 1) SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); else SetPixelAlpha(image,QuantumRange- ScaleAnyToQuantum(pixel,max_value),q); } q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } break; } case CMYKQuantum: case CMYKAQuantum: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushCharPixel(p,&pixel); SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushCharPixel(p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } break; } default: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushCharPixel(p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } break; } } } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case 'F': case 'f': { /* Convert PFM raster image to pixel packets. */ if (format == 'f') (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=format == 'f' ? GrayQuantum : RGBQuantum; image->endian=quantum_scale < 0.0 ? LSBEndian : MSBEndian; image->depth=32; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumDepth(image,quantum_info,32); if (status == MagickFalse) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); SetQuantumScale(quantum_info,(double) QuantumRange*fabs(quantum_scale)); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register Quantum *magick_restrict q; ssize_t offset; size_t length; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,(ssize_t) (image->rows-offset-1), image->columns,1,exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (length != extent) break; sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } default: ThrowPNMException(CorruptImageError,"ImproperImageHeader"); } if (*comment_info.comment != '\0') (void) SetImageProperty(image,"comment",comment_info.comment,exception); comment_info.comment=DestroyString(comment_info.comment); if (y < (ssize_t) image->rows) ThrowPNMException(CorruptImageError,"UnableToReadImageData"); if (EOFBlob(image) != MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"UnexpectedEndOfFile","`%s'",image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((format == '1') || (format == '2') || (format == '3')) do { /* Skip to end of line. */ count=ReadBlob(image,1,(unsigned char *) &format); if (count != 1) break; if (format == 'P') break; } while (format != '\n'); count=ReadBlob(image,1,(unsigned char *) &format); if ((count == 1) && (format == 'P')) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count == 1) && (format == 'P')); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPNMImage() adds properties for the PNM image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPNMImage method is: % % size_t RegisterPNMImage(void) % */ ModuleExport size_t RegisterPNMImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PNM","PAM","Common 2-dimensional bitmap format"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PBM", "Portable bitmap format (black and white)"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-bitmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PFM","Portable float format"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PGM","Portable graymap format (gray scale)"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-greymap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PNM","Portable anymap"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->magick=(IsImageFormatHandler *) IsPNM; entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PPM","Portable pixmap format (color)"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPNMImage() removes format registrations made by the % PNM module from the list of supported formats. % % The format of the UnregisterPNMImage method is: % % UnregisterPNMImage(void) % */ ModuleExport void UnregisterPNMImage(void) { (void) UnregisterMagickInfo("PAM"); (void) UnregisterMagickInfo("PBM"); (void) UnregisterMagickInfo("PGM"); (void) UnregisterMagickInfo("PNM"); (void) UnregisterMagickInfo("PPM"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePNMImage() writes an image to a file in the PNM rasterfile format. % % The format of the WritePNMImage method is: % % MagickBooleanType WritePNMImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { char buffer[MagickPathExtent], format, magick[MagickPathExtent]; const char *value; MagickBooleanType status; MagickOffsetType scene; Quantum index; QuantumAny pixel; QuantumInfo *quantum_info; QuantumType quantum_type; register unsigned char *q; size_t extent, imageListLength, packet_size; ssize_t count, y; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); scene=0; imageListLength=GetImageListLength(image); do { QuantumAny max_value; /* Write PNM file header. */ packet_size=3; quantum_type=RGBQuantum; (void) CopyMagickString(magick,image_info->magick,MagickPathExtent); max_value=GetQuantumRange(image->depth); switch (magick[1]) { case 'A': case 'a': { format='7'; break; } case 'B': case 'b': { format='4'; if (image_info->compression == NoCompression) format='1'; break; } case 'F': case 'f': { format='F'; if (SetImageGray(image,exception) != MagickFalse) format='f'; break; } case 'G': case 'g': { format='5'; if (image_info->compression == NoCompression) format='2'; break; } case 'N': case 'n': { if ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse)) { format='5'; if (image_info->compression == NoCompression) format='2'; if (SetImageMonochrome(image,exception) != MagickFalse) { format='4'; if (image_info->compression == NoCompression) format='1'; } break; } } default: { format='6'; if (image_info->compression == NoCompression) format='3'; break; } } (void) FormatLocaleString(buffer,MagickPathExtent,"P%c\n",format); (void) WriteBlobString(image,buffer); value=GetImageProperty(image,"comment",exception); if (value != (const char *) NULL) { register const char *p; /* Write comments to file. */ (void) WriteBlobByte(image,'#'); for (p=value; *p != '\0'; p++) { (void) WriteBlobByte(image,(unsigned char) *p); if ((*p == '\n') || (*p == '\r')) (void) WriteBlobByte(image,'#'); } (void) WriteBlobByte(image,'\n'); } if (format != '7') { (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g\n", (double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); } else { char type[MagickPathExtent]; /* PAM header. */ (void) FormatLocaleString(buffer,MagickPathExtent, "WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); quantum_type=GetQuantumType(image,exception); switch (quantum_type) { case CMYKQuantum: case CMYKAQuantum: { packet_size=4; (void) CopyMagickString(type,"CMYK",MagickPathExtent); break; } case GrayQuantum: case GrayAlphaQuantum: { packet_size=1; (void) CopyMagickString(type,"GRAYSCALE",MagickPathExtent); if (IdentifyImageMonochrome(image,exception) != MagickFalse) (void) CopyMagickString(type,"BLACKANDWHITE",MagickPathExtent); break; } default: { quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=RGBAQuantum; packet_size=3; (void) CopyMagickString(type,"RGB",MagickPathExtent); break; } } if (image->alpha_trait != UndefinedPixelTrait) { packet_size++; (void) ConcatenateMagickString(type,"_ALPHA",MagickPathExtent); } if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent, "DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, "TUPLTYPE %s\nENDHDR\n",type); (void) WriteBlobString(image,buffer); } /* Convert runextent encoded to PNM raster pixels. */ switch (format) { case '1': { unsigned char pixels[2048]; /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType,exception); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ? '0' : '1'); if ((q-pixels+1) >= (ssize_t) sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } *q++=' '; p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '2': { unsigned char pixels[2048]; /* Convert image to a PGM image. */ if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { index=ClampToQuantum(GetPixelLuma(image,p)); if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,"%u ", ScaleQuantumToChar(index)); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u ",ScaleQuantumToShort(index)); else count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u ",ScaleQuantumToLong(index)); extent=(size_t) count; if ((q-pixels+extent+1) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } (void) strncpy((char *) q,buffer,extent); q+=extent; p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '3': { unsigned char pixels[2048]; /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToChar(GetPixelRed(image,p)), ScaleQuantumToChar(GetPixelGreen(image,p)), ScaleQuantumToChar(GetPixelBlue(image,p))); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToShort(GetPixelRed(image,p)), ScaleQuantumToShort(GetPixelGreen(image,p)), ScaleQuantumToShort(GetPixelBlue(image,p))); else count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToLong(GetPixelRed(image,p)), ScaleQuantumToLong(GetPixelGreen(image,p)), ScaleQuantumToLong(GetPixelBlue(image,p))); extent=(size_t) count; if ((q-pixels+extent+2) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } (void) strncpy((char *) q,buffer,extent); q+=extent; p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '4': { register unsigned char *pixels; /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType,exception); image->depth=1; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '5': { register unsigned char *pixels; /* Convert image to a PGM image. */ if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,GrayQuantum); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); else { if (image->depth == 8) pixel=ScaleQuantumToChar(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p), max_value); } q=PopCharPixel((unsigned char) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image, p)),max_value); else { if (image->depth == 16) pixel=ScaleQuantumToShort(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p), max_value); } q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,p)), max_value); else { if (image->depth == 16) pixel=ScaleQuantumToLong(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); } q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '6': { register unsigned char *pixels; /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '7': { register unsigned char *pixels; /* Convert image to a PAM. */ if (image->depth > 32) image->depth=32; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image, p)),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } case CMYKQuantum: case CMYKAQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case 'F': case 'f': { register unsigned char *pixels; (void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" : "1.0\n"); image->depth=32; quantum_type=format == 'f' ? GrayQuantum : RGBQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); for (y=(ssize_t) image->rows-1; y >= 0; y--) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); (void) WriteBlob(image,extent,pixels); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } } if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
null
126
CWE-787
CVE-2019-13305
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP N N M M % % P P NN N MM MM % % PPPP N N N M M M % % P N NN M M % % P N N M M % % % % % % Read/Write PBMPlus Portable Anymap Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" /* Typedef declarations. */ typedef struct _CommentInfo { char *comment; size_t extent; } CommentInfo; /* Forward declarations. */ static MagickBooleanType WritePNMImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P N M % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPNM() returns MagickTrue if the image format type, identified by the % magick string, is PNM. % % The format of the IsPNM method is: % % MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o extent: Specifies the extent of the magick string. % */ static MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent) { if (extent < 2) return(MagickFalse); if ((*magick == (unsigned char) 'P') && ((magick[1] == '1') || (magick[1] == '2') || (magick[1] == '3') || (magick[1] == '4') || (magick[1] == '5') || (magick[1] == '6') || (magick[1] == '7') || (magick[1] == 'F') || (magick[1] == 'f'))) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPNMImage() reads a Portable Anymap image file and returns it. % It allocates the memory necessary for the new Image structure and returns % a pointer to the new image. % % The format of the ReadPNMImage method is: % % Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static int PNMComment(Image *image,CommentInfo *comment_info, ExceptionInfo *exception) { int c; register char *p; /* Read comment. */ p=comment_info->comment+strlen(comment_info->comment); for (c='#'; (c != EOF) && (c != (int) '\n') && (c != (int) '\r'); p++) { if ((size_t) (p-comment_info->comment+1) >= comment_info->extent) { comment_info->extent<<=1; comment_info->comment=(char *) ResizeQuantumMemory( comment_info->comment,comment_info->extent, sizeof(*comment_info->comment)); if (comment_info->comment == (char *) NULL) return(-1); p=comment_info->comment+strlen(comment_info->comment); } c=ReadBlobByte(image); if (c != EOF) { *p=(char) c; *(p+1)='\0'; } } return(c); } static unsigned int PNMInteger(Image *image,CommentInfo *comment_info, const unsigned int base,ExceptionInfo *exception) { int c; unsigned int value; /* Skip any leading whitespace. */ do { c=ReadBlobByte(image); if (c == EOF) return(0); if (c == (int) '#') c=PNMComment(image,comment_info,exception); } while ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r')); if (base == 2) return((unsigned int) (c-(int) '0')); /* Evaluate number. */ value=0; while (isdigit(c) != 0) { if (value <= (unsigned int) (INT_MAX/10)) { value*=10; if (value <= (unsigned int) (INT_MAX-(c-(int) '0'))) value+=c-(int) '0'; } c=ReadBlobByte(image); if (c == EOF) return(0); } if (c == (int) '#') c=PNMComment(image,comment_info,exception); return(value); } static Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define ThrowPNMException(exception,message) \ { \ if (comment_info.comment != (char *) NULL) \ comment_info.comment=DestroyString(comment_info.comment); \ ThrowReaderException((exception),(message)); \ } char format; CommentInfo comment_info; double quantum_scale; Image *image; MagickBooleanType status; QuantumAny max_value; QuantumInfo *quantum_info; QuantumType quantum_type; size_t depth, extent, packet_size; ssize_t count, row, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read PNM image. */ count=ReadBlob(image,1,(unsigned char *) &format); do { /* Initialize image structure. */ comment_info.comment=AcquireString(NULL); comment_info.extent=MagickPathExtent; if ((count != 1) || (format != 'P')) ThrowPNMException(CorruptImageError,"ImproperImageHeader"); max_value=1; quantum_type=RGBQuantum; quantum_scale=1.0; format=(char) ReadBlobByte(image); if (format != '7') { /* PBM, PGM, PPM, and PNM. */ image->columns=(size_t) PNMInteger(image,&comment_info,10,exception); image->rows=(size_t) PNMInteger(image,&comment_info,10,exception); if ((format == 'f') || (format == 'F')) { char scale[MagickPathExtent]; if (ReadBlobString(image,scale) != (char *) NULL) quantum_scale=StringToDouble(scale,(char **) NULL); } else { if ((format == '1') || (format == '4')) max_value=1; /* bitmap */ else max_value=(QuantumAny) PNMInteger(image,&comment_info,10, exception); } } else { char keyword[MagickPathExtent], value[MagickPathExtent]; int c; register char *p; /* PAM. */ for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); if (c == '#') { /* Comment. */ c=PNMComment(image,&comment_info,exception); c=ReadBlobByte(image); while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } p=keyword; do { if ((size_t) (p-keyword) < (MagickPathExtent-1)) *p++=c; c=ReadBlobByte(image); } while (isalnum(c)); *p='\0'; if (LocaleCompare(keyword,"endhdr") == 0) break; while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); p=value; while (isalnum(c) || (c == '_')) { if ((size_t) (p-value) < (MagickPathExtent-1)) *p++=c; c=ReadBlobByte(image); } *p='\0'; /* Assign a value to the specified keyword. */ if (LocaleCompare(keyword,"depth") == 0) packet_size=StringToUnsignedLong(value); (void) packet_size; if (LocaleCompare(keyword,"height") == 0) image->rows=StringToUnsignedLong(value); if (LocaleCompare(keyword,"maxval") == 0) max_value=StringToUnsignedLong(value); if (LocaleCompare(keyword,"TUPLTYPE") == 0) { if (LocaleCompare(value,"BLACKANDWHITE") == 0) { (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=GrayQuantum; } if (LocaleCompare(value,"BLACKANDWHITE_ALPHA") == 0) { (void) SetImageColorspace(image,GRAYColorspace,exception); image->alpha_trait=BlendPixelTrait; quantum_type=GrayAlphaQuantum; } if (LocaleCompare(value,"GRAYSCALE") == 0) { quantum_type=GrayQuantum; (void) SetImageColorspace(image,GRAYColorspace,exception); } if (LocaleCompare(value,"GRAYSCALE_ALPHA") == 0) { (void) SetImageColorspace(image,GRAYColorspace,exception); image->alpha_trait=BlendPixelTrait; quantum_type=GrayAlphaQuantum; } if (LocaleCompare(value,"RGB_ALPHA") == 0) { image->alpha_trait=BlendPixelTrait; quantum_type=RGBAQuantum; } if (LocaleCompare(value,"CMYK") == 0) { (void) SetImageColorspace(image,CMYKColorspace,exception); quantum_type=CMYKQuantum; } if (LocaleCompare(value,"CMYK_ALPHA") == 0) { (void) SetImageColorspace(image,CMYKColorspace,exception); image->alpha_trait=BlendPixelTrait; quantum_type=CMYKAQuantum; } } if (LocaleCompare(keyword,"width") == 0) image->columns=StringToUnsignedLong(value); } } if ((image->columns == 0) || (image->rows == 0)) ThrowPNMException(CorruptImageError,"NegativeOrZeroImageSize"); if ((max_value == 0) || (max_value > 4294967295UL)) ThrowPNMException(CorruptImageError,"ImproperImageHeader"); for (depth=1; GetQuantumRange(depth) < max_value; depth++) ; image->depth=depth; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((MagickSizeType) (image->columns*image->rows/8) > GetBlobSize(image)) ThrowPNMException(CorruptImageError,"InsufficientImageDataInFile"); status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { comment_info.comment=DestroyString(comment_info.comment); \ return(DestroyImageList(image)); } (void) ResetImagePixels(image,exception); /* Convert PNM pixels to runextent-encoded MIFF packets. */ row=0; y=0; switch (format) { case '1': { /* Convert PBM image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGray(image,PNMInteger(image,&comment_info,2,exception) == 0 ? QuantumRange : 0,q); if (EOFBlob(image) != MagickFalse) break; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } image->type=BilevelType; break; } case '2': { Quantum intensity; /* Convert PGM image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { intensity=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); if (EOFBlob(image) != MagickFalse) break; SetPixelGray(image,intensity,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } image->type=GrayscaleType; break; } case '3': { /* Convert PNM image to pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Quantum pixel; pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); if (EOFBlob(image) != MagickFalse) break; SetPixelRed(image,pixel,q); pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); SetPixelGreen(image,pixel,q); pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); SetPixelBlue(image,pixel,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } break; } case '4': { /* Convert PBM raw image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=GrayQuantum; if (image->storage_class == PseudoClass) quantum_type=IndexQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); SetQuantumMinIsWhite(quantum_info,MagickTrue); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register Quantum *magick_restrict q; ssize_t offset; size_t length; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (length != extent) break; sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case '5': { /* Convert PGM raw image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=GrayQuantum; extent=(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; ssize_t offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=pixels; switch (image->depth) { case 8: case 16: case 32: { (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q); q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q); q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q); q+=GetPixelChannels(image); } } break; } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case '6': { /* Convert PNM raster image to pixel packets. */ quantum_type=RGBQuantum; extent=3*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; ssize_t offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=pixels; switch (image->depth) { case 8: { for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleShortToQuantum(pixel),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleLongToQuantum(pixel),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } break; } default: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } } break; } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '7': { size_t channels; /* Convert PAM raster image to pixel packets. */ switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { channels=1; break; } case CMYKQuantum: case CMYKAQuantum: { channels=4; break; } default: { channels=3; break; } } if (image->alpha_trait != UndefinedPixelTrait) channels++; extent=channels*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; ssize_t offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=pixels; switch (image->depth) { case 8: case 16: case 32: { (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushCharPixel(p,&pixel); if (image->depth != 1) SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); else SetPixelAlpha(image,QuantumRange- ScaleAnyToQuantum(pixel,max_value),q); } q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } break; } case CMYKQuantum: case CMYKAQuantum: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushCharPixel(p,&pixel); SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushCharPixel(p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } break; } default: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushCharPixel(p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } break; } } } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case 'F': case 'f': { /* Convert PFM raster image to pixel packets. */ if (format == 'f') (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=format == 'f' ? GrayQuantum : RGBQuantum; image->endian=quantum_scale < 0.0 ? LSBEndian : MSBEndian; image->depth=32; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumDepth(image,quantum_info,32); if (status == MagickFalse) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); SetQuantumScale(quantum_info,(double) QuantumRange*fabs(quantum_scale)); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register Quantum *magick_restrict q; ssize_t offset; size_t length; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,(ssize_t) (image->rows-offset-1), image->columns,1,exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (length != extent) break; sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } default: ThrowPNMException(CorruptImageError,"ImproperImageHeader"); } if (*comment_info.comment != '\0') (void) SetImageProperty(image,"comment",comment_info.comment,exception); comment_info.comment=DestroyString(comment_info.comment); if (y < (ssize_t) image->rows) ThrowPNMException(CorruptImageError,"UnableToReadImageData"); if (EOFBlob(image) != MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"UnexpectedEndOfFile","`%s'",image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((format == '1') || (format == '2') || (format == '3')) do { /* Skip to end of line. */ count=ReadBlob(image,1,(unsigned char *) &format); if (count != 1) break; if (format == 'P') break; } while (format != '\n'); count=ReadBlob(image,1,(unsigned char *) &format); if ((count == 1) && (format == 'P')) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count == 1) && (format == 'P')); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPNMImage() adds properties for the PNM image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPNMImage method is: % % size_t RegisterPNMImage(void) % */ ModuleExport size_t RegisterPNMImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PNM","PAM","Common 2-dimensional bitmap format"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PBM", "Portable bitmap format (black and white)"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-bitmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PFM","Portable float format"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PGM","Portable graymap format (gray scale)"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-greymap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PNM","Portable anymap"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->magick=(IsImageFormatHandler *) IsPNM; entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PPM","Portable pixmap format (color)"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPNMImage() removes format registrations made by the % PNM module from the list of supported formats. % % The format of the UnregisterPNMImage method is: % % UnregisterPNMImage(void) % */ ModuleExport void UnregisterPNMImage(void) { (void) UnregisterMagickInfo("PAM"); (void) UnregisterMagickInfo("PBM"); (void) UnregisterMagickInfo("PGM"); (void) UnregisterMagickInfo("PNM"); (void) UnregisterMagickInfo("PPM"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePNMImage() writes an image to a file in the PNM rasterfile format. % % The format of the WritePNMImage method is: % % MagickBooleanType WritePNMImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { char buffer[MagickPathExtent], format, magick[MagickPathExtent]; const char *value; MagickBooleanType status; MagickOffsetType scene; Quantum index; QuantumAny pixel; QuantumInfo *quantum_info; QuantumType quantum_type; register unsigned char *q; size_t extent, imageListLength, packet_size; ssize_t count, y; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); scene=0; imageListLength=GetImageListLength(image); do { QuantumAny max_value; /* Write PNM file header. */ packet_size=3; quantum_type=RGBQuantum; (void) CopyMagickString(magick,image_info->magick,MagickPathExtent); max_value=GetQuantumRange(image->depth); switch (magick[1]) { case 'A': case 'a': { format='7'; break; } case 'B': case 'b': { format='4'; if (image_info->compression == NoCompression) format='1'; break; } case 'F': case 'f': { format='F'; if (SetImageGray(image,exception) != MagickFalse) format='f'; break; } case 'G': case 'g': { format='5'; if (image_info->compression == NoCompression) format='2'; break; } case 'N': case 'n': { if ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse)) { format='5'; if (image_info->compression == NoCompression) format='2'; if (SetImageMonochrome(image,exception) != MagickFalse) { format='4'; if (image_info->compression == NoCompression) format='1'; } break; } } default: { format='6'; if (image_info->compression == NoCompression) format='3'; break; } } (void) FormatLocaleString(buffer,MagickPathExtent,"P%c\n",format); (void) WriteBlobString(image,buffer); value=GetImageProperty(image,"comment",exception); if (value != (const char *) NULL) { register const char *p; /* Write comments to file. */ (void) WriteBlobByte(image,'#'); for (p=value; *p != '\0'; p++) { (void) WriteBlobByte(image,(unsigned char) *p); if ((*p == '\n') || (*p == '\r')) (void) WriteBlobByte(image,'#'); } (void) WriteBlobByte(image,'\n'); } if (format != '7') { (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g\n", (double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); } else { char type[MagickPathExtent]; /* PAM header. */ (void) FormatLocaleString(buffer,MagickPathExtent, "WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); quantum_type=GetQuantumType(image,exception); switch (quantum_type) { case CMYKQuantum: case CMYKAQuantum: { packet_size=4; (void) CopyMagickString(type,"CMYK",MagickPathExtent); break; } case GrayQuantum: case GrayAlphaQuantum: { packet_size=1; (void) CopyMagickString(type,"GRAYSCALE",MagickPathExtent); if (IdentifyImageMonochrome(image,exception) != MagickFalse) (void) CopyMagickString(type,"BLACKANDWHITE",MagickPathExtent); break; } default: { quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=RGBAQuantum; packet_size=3; (void) CopyMagickString(type,"RGB",MagickPathExtent); break; } } if (image->alpha_trait != UndefinedPixelTrait) { packet_size++; (void) ConcatenateMagickString(type,"_ALPHA",MagickPathExtent); } if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent, "DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, "TUPLTYPE %s\nENDHDR\n",type); (void) WriteBlobString(image,buffer); } /* Convert runextent encoded to PNM raster pixels. */ switch (format) { case '1': { unsigned char pixels[2048]; /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType,exception); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ? '0' : '1'); *q++=' '; if ((q-pixels+1) >= (ssize_t) sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '2': { unsigned char pixels[2048]; /* Convert image to a PGM image. */ if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { index=ClampToQuantum(GetPixelLuma(image,p)); if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,"%u ", ScaleQuantumToChar(index)); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u ",ScaleQuantumToShort(index)); else count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u ",ScaleQuantumToLong(index)); extent=(size_t) count; (void) strncpy((char *) q,buffer,extent); q+=extent; if ((q-pixels+extent+2) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '3': { unsigned char pixels[2048]; /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToChar(GetPixelRed(image,p)), ScaleQuantumToChar(GetPixelGreen(image,p)), ScaleQuantumToChar(GetPixelBlue(image,p))); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToShort(GetPixelRed(image,p)), ScaleQuantumToShort(GetPixelGreen(image,p)), ScaleQuantumToShort(GetPixelBlue(image,p))); else count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToLong(GetPixelRed(image,p)), ScaleQuantumToLong(GetPixelGreen(image,p)), ScaleQuantumToLong(GetPixelBlue(image,p))); extent=(size_t) count; (void) strncpy((char *) q,buffer,extent); q+=extent; if ((q-pixels+extent+2) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '4': { register unsigned char *pixels; /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType,exception); image->depth=1; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '5': { register unsigned char *pixels; /* Convert image to a PGM image. */ if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,GrayQuantum); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); else { if (image->depth == 8) pixel=ScaleQuantumToChar(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p), max_value); } q=PopCharPixel((unsigned char) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image, p)),max_value); else { if (image->depth == 16) pixel=ScaleQuantumToShort(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p), max_value); } q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,p)), max_value); else { if (image->depth == 16) pixel=ScaleQuantumToLong(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); } q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '6': { register unsigned char *pixels; /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '7': { register unsigned char *pixels; /* Convert image to a PAM. */ if (image->depth > 32) image->depth=32; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image, p)),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } case CMYKQuantum: case CMYKAQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case 'F': case 'f': { register unsigned char *pixels; (void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" : "1.0\n"); image->depth=32; quantum_type=format == 'f' ? GrayQuantum : RGBQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); for (y=(ssize_t) image->rows-1; y >= 0; y--) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); (void) WriteBlob(image,extent,pixels); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } } if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
null
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP N N M M % % P P NN N MM MM % % PPPP N N N M M M % % P N NN M M % % P N N M M % % % % % % Read/Write PBMPlus Portable Anymap Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" /* Typedef declarations. */ typedef struct _CommentInfo { char *comment; size_t extent; } CommentInfo; /* Forward declarations. */ static MagickBooleanType WritePNMImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P N M % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPNM() returns MagickTrue if the image format type, identified by the % magick string, is PNM. % % The format of the IsPNM method is: % % MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o extent: Specifies the extent of the magick string. % */ static MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent) { if (extent < 2) return(MagickFalse); if ((*magick == (unsigned char) 'P') && ((magick[1] == '1') || (magick[1] == '2') || (magick[1] == '3') || (magick[1] == '4') || (magick[1] == '5') || (magick[1] == '6') || (magick[1] == '7') || (magick[1] == 'F') || (magick[1] == 'f'))) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPNMImage() reads a Portable Anymap image file and returns it. % It allocates the memory necessary for the new Image structure and returns % a pointer to the new image. % % The format of the ReadPNMImage method is: % % Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static int PNMComment(Image *image,CommentInfo *comment_info, ExceptionInfo *exception) { int c; register char *p; /* Read comment. */ p=comment_info->comment+strlen(comment_info->comment); for (c='#'; (c != EOF) && (c != (int) '\n') && (c != (int) '\r'); p++) { if ((size_t) (p-comment_info->comment+1) >= comment_info->extent) { comment_info->extent<<=1; comment_info->comment=(char *) ResizeQuantumMemory( comment_info->comment,comment_info->extent, sizeof(*comment_info->comment)); if (comment_info->comment == (char *) NULL) return(-1); p=comment_info->comment+strlen(comment_info->comment); } c=ReadBlobByte(image); if (c != EOF) { *p=(char) c; *(p+1)='\0'; } } return(c); } static unsigned int PNMInteger(Image *image,CommentInfo *comment_info, const unsigned int base,ExceptionInfo *exception) { int c; unsigned int value; /* Skip any leading whitespace. */ do { c=ReadBlobByte(image); if (c == EOF) return(0); if (c == (int) '#') c=PNMComment(image,comment_info,exception); } while ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r')); if (base == 2) return((unsigned int) (c-(int) '0')); /* Evaluate number. */ value=0; while (isdigit(c) != 0) { if (value <= (unsigned int) (INT_MAX/10)) { value*=10; if (value <= (unsigned int) (INT_MAX-(c-(int) '0'))) value+=c-(int) '0'; } c=ReadBlobByte(image); if (c == EOF) return(0); } if (c == (int) '#') c=PNMComment(image,comment_info,exception); return(value); } static Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define ThrowPNMException(exception,message) \ { \ if (comment_info.comment != (char *) NULL) \ comment_info.comment=DestroyString(comment_info.comment); \ ThrowReaderException((exception),(message)); \ } char format; CommentInfo comment_info; double quantum_scale; Image *image; MagickBooleanType status; QuantumAny max_value; QuantumInfo *quantum_info; QuantumType quantum_type; size_t depth, extent, packet_size; ssize_t count, row, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read PNM image. */ count=ReadBlob(image,1,(unsigned char *) &format); do { /* Initialize image structure. */ comment_info.comment=AcquireString(NULL); comment_info.extent=MagickPathExtent; if ((count != 1) || (format != 'P')) ThrowPNMException(CorruptImageError,"ImproperImageHeader"); max_value=1; quantum_type=RGBQuantum; quantum_scale=1.0; format=(char) ReadBlobByte(image); if (format != '7') { /* PBM, PGM, PPM, and PNM. */ image->columns=(size_t) PNMInteger(image,&comment_info,10,exception); image->rows=(size_t) PNMInteger(image,&comment_info,10,exception); if ((format == 'f') || (format == 'F')) { char scale[MagickPathExtent]; if (ReadBlobString(image,scale) != (char *) NULL) quantum_scale=StringToDouble(scale,(char **) NULL); } else { if ((format == '1') || (format == '4')) max_value=1; /* bitmap */ else max_value=(QuantumAny) PNMInteger(image,&comment_info,10, exception); } } else { char keyword[MagickPathExtent], value[MagickPathExtent]; int c; register char *p; /* PAM. */ for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); if (c == '#') { /* Comment. */ c=PNMComment(image,&comment_info,exception); c=ReadBlobByte(image); while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } p=keyword; do { if ((size_t) (p-keyword) < (MagickPathExtent-1)) *p++=c; c=ReadBlobByte(image); } while (isalnum(c)); *p='\0'; if (LocaleCompare(keyword,"endhdr") == 0) break; while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); p=value; while (isalnum(c) || (c == '_')) { if ((size_t) (p-value) < (MagickPathExtent-1)) *p++=c; c=ReadBlobByte(image); } *p='\0'; /* Assign a value to the specified keyword. */ if (LocaleCompare(keyword,"depth") == 0) packet_size=StringToUnsignedLong(value); (void) packet_size; if (LocaleCompare(keyword,"height") == 0) image->rows=StringToUnsignedLong(value); if (LocaleCompare(keyword,"maxval") == 0) max_value=StringToUnsignedLong(value); if (LocaleCompare(keyword,"TUPLTYPE") == 0) { if (LocaleCompare(value,"BLACKANDWHITE") == 0) { (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=GrayQuantum; } if (LocaleCompare(value,"BLACKANDWHITE_ALPHA") == 0) { (void) SetImageColorspace(image,GRAYColorspace,exception); image->alpha_trait=BlendPixelTrait; quantum_type=GrayAlphaQuantum; } if (LocaleCompare(value,"GRAYSCALE") == 0) { quantum_type=GrayQuantum; (void) SetImageColorspace(image,GRAYColorspace,exception); } if (LocaleCompare(value,"GRAYSCALE_ALPHA") == 0) { (void) SetImageColorspace(image,GRAYColorspace,exception); image->alpha_trait=BlendPixelTrait; quantum_type=GrayAlphaQuantum; } if (LocaleCompare(value,"RGB_ALPHA") == 0) { image->alpha_trait=BlendPixelTrait; quantum_type=RGBAQuantum; } if (LocaleCompare(value,"CMYK") == 0) { (void) SetImageColorspace(image,CMYKColorspace,exception); quantum_type=CMYKQuantum; } if (LocaleCompare(value,"CMYK_ALPHA") == 0) { (void) SetImageColorspace(image,CMYKColorspace,exception); image->alpha_trait=BlendPixelTrait; quantum_type=CMYKAQuantum; } } if (LocaleCompare(keyword,"width") == 0) image->columns=StringToUnsignedLong(value); } } if ((image->columns == 0) || (image->rows == 0)) ThrowPNMException(CorruptImageError,"NegativeOrZeroImageSize"); if ((max_value == 0) || (max_value > 4294967295UL)) ThrowPNMException(CorruptImageError,"ImproperImageHeader"); for (depth=1; GetQuantumRange(depth) < max_value; depth++) ; image->depth=depth; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((MagickSizeType) (image->columns*image->rows/8) > GetBlobSize(image)) ThrowPNMException(CorruptImageError,"InsufficientImageDataInFile"); status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { comment_info.comment=DestroyString(comment_info.comment); \ return(DestroyImageList(image)); } (void) ResetImagePixels(image,exception); /* Convert PNM pixels to runextent-encoded MIFF packets. */ row=0; y=0; switch (format) { case '1': { /* Convert PBM image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGray(image,PNMInteger(image,&comment_info,2,exception) == 0 ? QuantumRange : 0,q); if (EOFBlob(image) != MagickFalse) break; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } image->type=BilevelType; break; } case '2': { Quantum intensity; /* Convert PGM image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { intensity=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); if (EOFBlob(image) != MagickFalse) break; SetPixelGray(image,intensity,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } image->type=GrayscaleType; break; } case '3': { /* Convert PNM image to pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Quantum pixel; pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); if (EOFBlob(image) != MagickFalse) break; SetPixelRed(image,pixel,q); pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); SetPixelGreen(image,pixel,q); pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10, exception),max_value); SetPixelBlue(image,pixel,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } break; } case '4': { /* Convert PBM raw image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=GrayQuantum; if (image->storage_class == PseudoClass) quantum_type=IndexQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); SetQuantumMinIsWhite(quantum_info,MagickTrue); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register Quantum *magick_restrict q; ssize_t offset; size_t length; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (length != extent) break; sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case '5': { /* Convert PGM raw image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=GrayQuantum; extent=(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; ssize_t offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=pixels; switch (image->depth) { case 8: case 16: case 32: { (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q); q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q); q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value),q); q+=GetPixelChannels(image); } } break; } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case '6': { /* Convert PNM raster image to pixel packets. */ quantum_type=RGBQuantum; extent=3*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; ssize_t offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=pixels; switch (image->depth) { case 8: { for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } break; } case 16: { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleShortToQuantum(pixel),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleShortToQuantum(pixel),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } break; } case 32: { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleLongToQuantum(pixel),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleLongToQuantum(pixel),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } break; } default: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } } break; } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '7': { size_t channels; /* Convert PAM raster image to pixel packets. */ switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { channels=1; break; } case CMYKQuantum: case CMYKAQuantum: { channels=4; break; } default: { channels=3; break; } } if (image->alpha_trait != UndefinedPixelTrait) channels++; extent=channels*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; ssize_t offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; p=pixels; switch (image->depth) { case 8: case 16: case 32: { (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushCharPixel(p,&pixel); if (image->depth != 1) SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); else SetPixelAlpha(image,QuantumRange- ScaleAnyToQuantum(pixel,max_value),q); } q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGray(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } break; } case CMYKQuantum: case CMYKAQuantum: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushCharPixel(p,&pixel); SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushCharPixel(p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlack(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } break; } default: { if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushCharPixel(p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushCharPixel(p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushCharPixel(p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value),q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } else { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,max_value), q); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(image,ScaleAnyToQuantum(pixel,max_value), q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelAlpha(image,ScaleAnyToQuantum(pixel, max_value),q); } q+=GetPixelChannels(image); } } break; } } } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case 'F': case 'f': { /* Convert PFM raster image to pixel packets. */ if (format == 'f') (void) SetImageColorspace(image,GRAYColorspace,exception); quantum_type=format == 'f' ? GrayQuantum : RGBQuantum; image->endian=quantum_scale < 0.0 ? LSBEndian : MSBEndian; image->depth=32; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumDepth(image,quantum_info,32); if (status == MagickFalse) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); SetQuantumScale(quantum_info,(double) QuantumRange*fabs(quantum_scale)); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register Quantum *magick_restrict q; ssize_t offset; size_t length; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,(ssize_t) (image->rows-offset-1), image->columns,1,exception); if (q == (Quantum *) NULL) break; length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (length != extent) break; sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } default: ThrowPNMException(CorruptImageError,"ImproperImageHeader"); } if (*comment_info.comment != '\0') (void) SetImageProperty(image,"comment",comment_info.comment,exception); comment_info.comment=DestroyString(comment_info.comment); if (y < (ssize_t) image->rows) ThrowPNMException(CorruptImageError,"UnableToReadImageData"); if (EOFBlob(image) != MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"UnexpectedEndOfFile","`%s'",image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((format == '1') || (format == '2') || (format == '3')) do { /* Skip to end of line. */ count=ReadBlob(image,1,(unsigned char *) &format); if (count != 1) break; if (format == 'P') break; } while (format != '\n'); count=ReadBlob(image,1,(unsigned char *) &format); if ((count == 1) && (format == 'P')) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count == 1) && (format == 'P')); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPNMImage() adds properties for the PNM image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPNMImage method is: % % size_t RegisterPNMImage(void) % */ ModuleExport size_t RegisterPNMImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PNM","PAM","Common 2-dimensional bitmap format"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PBM", "Portable bitmap format (black and white)"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-bitmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PFM","Portable float format"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PGM","Portable graymap format (gray scale)"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-greymap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PNM","Portable anymap"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->magick=(IsImageFormatHandler *) IsPNM; entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PNM","PPM","Portable pixmap format (color)"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPNMImage() removes format registrations made by the % PNM module from the list of supported formats. % % The format of the UnregisterPNMImage method is: % % UnregisterPNMImage(void) % */ ModuleExport void UnregisterPNMImage(void) { (void) UnregisterMagickInfo("PAM"); (void) UnregisterMagickInfo("PBM"); (void) UnregisterMagickInfo("PGM"); (void) UnregisterMagickInfo("PNM"); (void) UnregisterMagickInfo("PPM"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePNMImage() writes an image to a file in the PNM rasterfile format. % % The format of the WritePNMImage method is: % % MagickBooleanType WritePNMImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { char buffer[MagickPathExtent], format, magick[MagickPathExtent]; const char *value; MagickBooleanType status; MagickOffsetType scene; Quantum index; QuantumAny pixel; QuantumInfo *quantum_info; QuantumType quantum_type; register unsigned char *q; size_t extent, imageListLength, packet_size; ssize_t count, y; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); scene=0; imageListLength=GetImageListLength(image); do { QuantumAny max_value; /* Write PNM file header. */ packet_size=3; quantum_type=RGBQuantum; (void) CopyMagickString(magick,image_info->magick,MagickPathExtent); max_value=GetQuantumRange(image->depth); switch (magick[1]) { case 'A': case 'a': { format='7'; break; } case 'B': case 'b': { format='4'; if (image_info->compression == NoCompression) format='1'; break; } case 'F': case 'f': { format='F'; if (SetImageGray(image,exception) != MagickFalse) format='f'; break; } case 'G': case 'g': { format='5'; if (image_info->compression == NoCompression) format='2'; break; } case 'N': case 'n': { if ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse)) { format='5'; if (image_info->compression == NoCompression) format='2'; if (SetImageMonochrome(image,exception) != MagickFalse) { format='4'; if (image_info->compression == NoCompression) format='1'; } break; } } default: { format='6'; if (image_info->compression == NoCompression) format='3'; break; } } (void) FormatLocaleString(buffer,MagickPathExtent,"P%c\n",format); (void) WriteBlobString(image,buffer); value=GetImageProperty(image,"comment",exception); if (value != (const char *) NULL) { register const char *p; /* Write comments to file. */ (void) WriteBlobByte(image,'#'); for (p=value; *p != '\0'; p++) { (void) WriteBlobByte(image,(unsigned char) *p); if ((*p == '\n') || (*p == '\r')) (void) WriteBlobByte(image,'#'); } (void) WriteBlobByte(image,'\n'); } if (format != '7') { (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g\n", (double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); } else { char type[MagickPathExtent]; /* PAM header. */ (void) FormatLocaleString(buffer,MagickPathExtent, "WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); quantum_type=GetQuantumType(image,exception); switch (quantum_type) { case CMYKQuantum: case CMYKAQuantum: { packet_size=4; (void) CopyMagickString(type,"CMYK",MagickPathExtent); break; } case GrayQuantum: case GrayAlphaQuantum: { packet_size=1; (void) CopyMagickString(type,"GRAYSCALE",MagickPathExtent); if (IdentifyImageMonochrome(image,exception) != MagickFalse) (void) CopyMagickString(type,"BLACKANDWHITE",MagickPathExtent); break; } default: { quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=RGBAQuantum; packet_size=3; (void) CopyMagickString(type,"RGB",MagickPathExtent); break; } } if (image->alpha_trait != UndefinedPixelTrait) { packet_size++; (void) ConcatenateMagickString(type,"_ALPHA",MagickPathExtent); } if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent, "DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, "TUPLTYPE %s\nENDHDR\n",type); (void) WriteBlobString(image,buffer); } /* Convert runextent encoded to PNM raster pixels. */ switch (format) { case '1': { unsigned char pixels[2048]; /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType,exception); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ? '0' : '1'); *q++=' '; if ((q-pixels+1) >= (ssize_t) sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '2': { unsigned char pixels[2048]; /* Convert image to a PGM image. */ if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { index=ClampToQuantum(GetPixelLuma(image,p)); if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,"%u ", ScaleQuantumToChar(index)); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u ",ScaleQuantumToShort(index)); else count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u ",ScaleQuantumToLong(index)); extent=(size_t) count; if ((q-pixels+extent+1) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } (void) strncpy((char *) q,buffer,extent); q+=extent; p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '3': { unsigned char pixels[2048]; /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToChar(GetPixelRed(image,p)), ScaleQuantumToChar(GetPixelGreen(image,p)), ScaleQuantumToChar(GetPixelBlue(image,p))); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToShort(GetPixelRed(image,p)), ScaleQuantumToShort(GetPixelGreen(image,p)), ScaleQuantumToShort(GetPixelBlue(image,p))); else count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToLong(GetPixelRed(image,p)), ScaleQuantumToLong(GetPixelGreen(image,p)), ScaleQuantumToLong(GetPixelBlue(image,p))); extent=(size_t) count; if ((q-pixels+extent+2) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } (void) strncpy((char *) q,buffer,extent); q+=extent; p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '4': { register unsigned char *pixels; /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType,exception); image->depth=1; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '5': { register unsigned char *pixels; /* Convert image to a PGM image. */ if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,GrayQuantum); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); else { if (image->depth == 8) pixel=ScaleQuantumToChar(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p), max_value); } q=PopCharPixel((unsigned char) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image, p)),max_value); else { if (image->depth == 16) pixel=ScaleQuantumToShort(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p), max_value); } q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,p)), max_value); else { if (image->depth == 16) pixel=ScaleQuantumToLong(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); } q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '6': { register unsigned char *pixels; /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '7': { register unsigned char *pixels; /* Convert image to a PAM. */ if (image->depth > 32) image->depth=32; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image, p)),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } case CMYKQuantum: case CMYKAQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case 'F': case 'f': { register unsigned char *pixels; (void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" : "1.0\n"); image->depth=32; quantum_type=format == 'f' ? GrayQuantum : RGBQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); for (y=(ssize_t) image->rows-1; y >= 0; y--) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); (void) WriteBlob(image,extent,pixels); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } } if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
null
127
CWE-787
CVE-2019-13306
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP N N M M % % P P NN N MM MM % % PPPP N N N M M M % % P N NN M M % % P N N M M % % % % % % Read/Write PBMPlus Portable Anymap Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/property.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/string-private.h" /* Typedef declarations. */ typedef struct _CommentInfo { char *comment; size_t extent; } CommentInfo; /* Forward declarations. */ static MagickBooleanType WritePNMImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P N M % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPNM() returns MagickTrue if the image format type, identified by the % magick string, is PNM. % % The format of the IsPNM method is: % % MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o extent: Specifies the extent of the magick string. % */ static MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent) { if (extent < 2) return(MagickFalse); if ((*magick == (unsigned char) 'P') && ((magick[1] == '1') || (magick[1] == '2') || (magick[1] == '3') || (magick[1] == '4') || (magick[1] == '5') || (magick[1] == '6') || (magick[1] == '7') || (magick[1] == 'F') || (magick[1] == 'f'))) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPNMImage() reads a Portable Anymap image file and returns it. % It allocates the memory necessary for the new Image structure and returns % a pointer to the new image. % % The format of the ReadPNMImage method is: % % Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static int PNMComment(Image *image,CommentInfo *comment_info) { int c; register char *p; /* Read comment. */ p=comment_info->comment+strlen(comment_info->comment); for (c='#'; (c != EOF) && (c != (int) '\n') && (c != (int) '\r'); p++) { if ((size_t) (p-comment_info->comment+1) >= comment_info->extent) { comment_info->extent<<=1; comment_info->comment=(char *) ResizeQuantumMemory( comment_info->comment,comment_info->extent, sizeof(*comment_info->comment)); if (comment_info->comment == (char *) NULL) return(-1); p=comment_info->comment+strlen(comment_info->comment); } c=ReadBlobByte(image); if (c != EOF) { *p=(char) c; *(p+1)='\0'; } } return(c); } static unsigned int PNMInteger(Image *image,CommentInfo *comment_info, const unsigned int base) { int c; unsigned int value; /* Skip any leading whitespace. */ do { c=ReadBlobByte(image); if (c == EOF) return(0); if (c == (int) '#') c=PNMComment(image,comment_info); } while ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r')); if (base == 2) return((unsigned int) (c-(int) '0')); /* Evaluate number. */ value=0; while (isdigit(c) != 0) { if (value <= (unsigned int) (INT_MAX/10)) { value*=10; if (value <= (unsigned int) (INT_MAX-(c-(int) '0'))) value+=c-(int) '0'; } c=ReadBlobByte(image); if (c == EOF) return(0); } if (c == (int) '#') c=PNMComment(image,comment_info); return(value); } static Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define ThrowPNMException(exception,message) \ { \ if (comment_info.comment != (char *) NULL) \ comment_info.comment=DestroyString(comment_info.comment); \ ThrowReaderException((exception),(message)); \ } char format; CommentInfo comment_info; double quantum_scale; Image *image; MagickBooleanType status; QuantumAny max_value; QuantumInfo *quantum_info; QuantumType quantum_type; size_t depth, extent, packet_size; ssize_t count, row, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read PNM image. */ count=ReadBlob(image,1,(unsigned char *) &format); do { /* Initialize image structure. */ comment_info.comment=AcquireString(NULL); comment_info.extent=MagickPathExtent; if ((count != 1) || (format != 'P')) ThrowPNMException(CorruptImageError,"ImproperImageHeader"); max_value=1; quantum_type=RGBQuantum; quantum_scale=1.0; format=(char) ReadBlobByte(image); if (format != '7') { /* PBM, PGM, PPM, and PNM. */ image->columns=PNMInteger(image,&comment_info,10); image->rows=PNMInteger(image,&comment_info,10); if ((format == 'f') || (format == 'F')) { char scale[MaxTextExtent]; if (ReadBlobString(image,scale) != (char *) NULL) quantum_scale=StringToDouble(scale,(char **) NULL); } else { if ((format == '1') || (format == '4')) max_value=1; /* bitmap */ else max_value=PNMInteger(image,&comment_info,10); } } else { char keyword[MaxTextExtent], value[MaxTextExtent]; int c; register char *p; /* PAM. */ for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); if (c == '#') { /* Comment. */ c=PNMComment(image,&comment_info); c=ReadBlobByte(image); while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } p=keyword; do { if ((size_t) (p-keyword) < (MaxTextExtent-1)) *p++=c; c=ReadBlobByte(image); } while (isalnum(c)); *p='\0'; if (LocaleCompare(keyword,"endhdr") == 0) break; while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); p=value; while (isalnum(c) || (c == '_')) { if ((size_t) (p-value) < (MaxTextExtent-1)) *p++=c; c=ReadBlobByte(image); } *p='\0'; /* Assign a value to the specified keyword. */ if (LocaleCompare(keyword,"depth") == 0) packet_size=StringToUnsignedLong(value); (void) packet_size; if (LocaleCompare(keyword,"height") == 0) image->rows=StringToUnsignedLong(value); if (LocaleCompare(keyword,"maxval") == 0) max_value=StringToUnsignedLong(value); if (LocaleCompare(keyword,"TUPLTYPE") == 0) { if (LocaleCompare(value,"BLACKANDWHITE") == 0) { (void) SetImageColorspace(image,GRAYColorspace); quantum_type=GrayQuantum; } if (LocaleCompare(value,"BLACKANDWHITE_ALPHA") == 0) { (void) SetImageColorspace(image,GRAYColorspace); image->matte=MagickTrue; quantum_type=GrayAlphaQuantum; } if (LocaleCompare(value,"GRAYSCALE") == 0) { (void) SetImageColorspace(image,GRAYColorspace); quantum_type=GrayQuantum; } if (LocaleCompare(value,"GRAYSCALE_ALPHA") == 0) { (void) SetImageColorspace(image,GRAYColorspace); image->matte=MagickTrue; quantum_type=GrayAlphaQuantum; } if (LocaleCompare(value,"RGB_ALPHA") == 0) { quantum_type=RGBAQuantum; image->matte=MagickTrue; } if (LocaleCompare(value,"CMYK") == 0) { (void) SetImageColorspace(image,CMYKColorspace); quantum_type=CMYKQuantum; } if (LocaleCompare(value,"CMYK_ALPHA") == 0) { (void) SetImageColorspace(image,CMYKColorspace); image->matte=MagickTrue; quantum_type=CMYKAQuantum; } } if (LocaleCompare(keyword,"width") == 0) image->columns=StringToUnsignedLong(value); } } if ((image->columns == 0) || (image->rows == 0)) ThrowPNMException(CorruptImageError,"NegativeOrZeroImageSize"); if ((max_value == 0) || (max_value > 4294967295U)) ThrowPNMException(CorruptImageError,"ImproperImageHeader"); for (depth=1; GetQuantumRange(depth) < max_value; depth++) ; image->depth=depth; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((MagickSizeType) (image->columns*image->rows/8) > GetBlobSize(image)) ThrowPNMException(CorruptImageError,"InsufficientImageDataInFile"); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } (void) ResetImagePixels(image,exception); /* Convert PNM pixels. */ row=0; switch (format) { case '1': { /* Convert PBM image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace); for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,PNMInteger(image,&comment_info,2) == 0 ? QuantumRange : 0); if (EOFBlob(image) != MagickFalse) break; SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } image->type=BilevelType; break; } case '2': { size_t intensity; /* Convert PGM image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace); for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { intensity=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10), max_value); if (EOFBlob(image) != MagickFalse) break; SetPixelRed(q,intensity); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } image->type=GrayscaleType; break; } case '3': { /* Convert PNM image to pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { QuantumAny pixel; pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10), max_value); if (EOFBlob(image) != MagickFalse) break; SetPixelRed(q,pixel); pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10), max_value); SetPixelGreen(q,pixel); pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10), max_value); SetPixelBlue(q,pixel); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } break; } case '4': { /* Convert PBM raw image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace); quantum_type=GrayQuantum; if (image->storage_class == PseudoClass) quantum_type=IndexQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); SetQuantumMinIsWhite(quantum_info,MagickTrue); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register PixelPacket *magick_restrict q; ssize_t count, offset; size_t length; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (length != extent) break; sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case '5': { /* Convert PGM raw image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace); quantum_type=GrayQuantum; extent=(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; ssize_t count, offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; p=pixels; switch (image->depth) { case 8: case 16: case 32: { (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { unsigned int pixel; if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); q++; } break; } if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); q++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); q++; } break; } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case '6': { /* Convert PNM raster image to pixel packets. */ quantum_type=RGBQuantum; extent=3*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; ssize_t count, offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; p=pixels; switch (image->depth) { case 8: { for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); q->opacity=OpaqueOpacity; q++; } break; } case 16: { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleShortToQuantum(pixel)); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(q,ScaleShortToQuantum(pixel)); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(q,ScaleShortToQuantum(pixel)); SetPixelOpacity(q,OpaqueOpacity); q++; } break; } case 32: { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleLongToQuantum(pixel)); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(q,ScaleLongToQuantum(pixel)); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(q,ScaleLongToQuantum(pixel)); SetPixelOpacity(q,OpaqueOpacity); q++; } break; } default: { unsigned int pixel; if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); p=PushCharPixel(p,&pixel); SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value)); p=PushCharPixel(p,&pixel); SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelOpacity(q,OpaqueOpacity); q++; } break; } if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value)); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelOpacity(q,OpaqueOpacity); q++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value)); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelOpacity(q,OpaqueOpacity); q++; } break; } break; } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '7': { register IndexPacket *indexes; size_t channels; /* Convert PAM raster image to pixel packets. */ switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { channels=1; break; } case CMYKQuantum: case CMYKAQuantum: { channels=4; break; } default: { channels=3; break; } } if (image->matte != MagickFalse) channels++; extent=channels*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register ssize_t x; register PixelPacket *magick_restrict q; ssize_t count, offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=pixels; switch (image->depth) { case 8: case 16: case 32: { (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { unsigned int pixel; if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { p=PushCharPixel(p,&pixel); if (image->depth != 1) SetPixelOpacity(q,ScaleAnyToQuantum(pixel, max_value)); else SetPixelOpacity(q,QuantumRange-ScaleAnyToQuantum( pixel,max_value)); } q++; } break; } if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelOpacity(q,ScaleAnyToQuantum(pixel, max_value)); } q++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelOpacity(q,ScaleAnyToQuantum(pixel,max_value)); } q++; } break; } case CMYKQuantum: case CMYKAQuantum: { unsigned int pixel; if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); p=PushCharPixel(p,&pixel); SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value)); p=PushCharPixel(p,&pixel); SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value)); p=PushCharPixel(p,&pixel); SetPixelIndex(indexes+x,ScaleAnyToQuantum(pixel, max_value)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { p=PushCharPixel(p,&pixel); SetPixelOpacity(q,ScaleAnyToQuantum(pixel, max_value)); } q++; } break; } if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value)); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value)); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelIndex(indexes+x,ScaleAnyToQuantum(pixel, max_value)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelOpacity(q,ScaleAnyToQuantum(pixel, max_value)); } q++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value)); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value)); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelIndex(indexes+x,ScaleAnyToQuantum(pixel,max_value)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelOpacity(q,ScaleAnyToQuantum(pixel,max_value)); } q++; } break; } default: { unsigned int pixel; if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); p=PushCharPixel(p,&pixel); SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value)); p=PushCharPixel(p,&pixel); SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { p=PushCharPixel(p,&pixel); SetPixelOpacity(q,ScaleAnyToQuantum(pixel, max_value)); } q++; } break; } if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value)); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelOpacity(q,ScaleAnyToQuantum(pixel, max_value)); } q++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value)); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelOpacity(q,ScaleAnyToQuantum(pixel,max_value)); } q++; } break; } } break; } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case 'F': case 'f': { /* Convert PFM raster image to pixel packets. */ if (format == 'f') (void) SetImageColorspace(image,GRAYColorspace); quantum_type=format == 'f' ? GrayQuantum : RGBQuantum; image->endian=quantum_scale < 0.0 ? LSBEndian : MSBEndian; image->depth=32; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumDepth(image,quantum_info,32); if (status == MagickFalse) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); SetQuantumScale(quantum_info,(MagickRealType) QuantumRange* fabs(quantum_scale)); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register PixelPacket *magick_restrict q; ssize_t count, offset; size_t length; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if ((size_t) count != extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,(ssize_t) (image->rows-offset-1), image->columns,1,exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (length != extent) break; sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } default: ThrowPNMException(CorruptImageError,"ImproperImageHeader"); } if (*comment_info.comment != '\0') (void) SetImageProperty(image,"comment",comment_info.comment); comment_info.comment=DestroyString(comment_info.comment); if (y < (ssize_t) image->rows) ThrowPNMException(CorruptImageError,"UnableToReadImageData"); if (EOFBlob(image) != MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"UnexpectedEndOfFile","`%s'",image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((format == '1') || (format == '2') || (format == '3')) do { /* Skip to end of line. */ count=ReadBlob(image,1,(unsigned char *) &format); if (count != 1) break; if (format == 'P') break; } while (format != '\n'); count=ReadBlob(image,1,(unsigned char *) &format); if ((count == 1) && (format == 'P')) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count == 1) && (format == 'P')); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPNMImage() adds properties for the PNM image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPNMImage method is: % % size_t RegisterPNMImage(void) % */ ModuleExport size_t RegisterPNMImage(void) { MagickInfo *entry; entry=SetMagickInfo("PAM"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->description=ConstantString("Common 2-dimensional bitmap format"); entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->module=ConstantString("PNM"); entry->seekable_stream=MagickTrue; (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PBM"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->description=ConstantString("Portable bitmap format (black and white)"); entry->mime_type=ConstantString("image/x-portable-bitmap"); entry->module=ConstantString("PNM"); entry->seekable_stream=MagickTrue; (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PFM"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->endian_support=MagickTrue; entry->description=ConstantString("Portable float format"); entry->module=ConstantString("PFM"); entry->seekable_stream=MagickTrue; (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PGM"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->description=ConstantString("Portable graymap format (gray scale)"); entry->mime_type=ConstantString("image/x-portable-greymap"); entry->module=ConstantString("PNM"); entry->seekable_stream=MagickTrue; (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNM"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->magick=(IsImageFormatHandler *) IsPNM; entry->description=ConstantString("Portable anymap"); entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->module=ConstantString("PNM"); entry->seekable_stream=MagickTrue; (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PPM"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->description=ConstantString("Portable pixmap format (color)"); entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->module=ConstantString("PNM"); entry->seekable_stream=MagickTrue; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPNMImage() removes format registrations made by the % PNM module from the list of supported formats. % % The format of the UnregisterPNMImage method is: % % UnregisterPNMImage(void) % */ ModuleExport void UnregisterPNMImage(void) { (void) UnregisterMagickInfo("PAM"); (void) UnregisterMagickInfo("PBM"); (void) UnregisterMagickInfo("PGM"); (void) UnregisterMagickInfo("PNM"); (void) UnregisterMagickInfo("PPM"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePNMImage() writes an image to a file in the PNM rasterfile format. % % The format of the WritePNMImage method is: % % MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image) { char buffer[MaxTextExtent], format, magick[MaxTextExtent]; const char *value; IndexPacket index; MagickBooleanType status; MagickOffsetType scene; QuantumAny pixel; QuantumInfo *quantum_info; QuantumType quantum_type; register unsigned char *pixels, *q; size_t extent, imageListLength, packet_size; ssize_t count, y; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); scene=0; imageListLength=GetImageListLength(image); do { QuantumAny max_value; /* Write PNM file header. */ max_value=GetQuantumRange(image->depth); packet_size=3; quantum_type=RGBQuantum; (void) CopyMagickString(magick,image_info->magick,MaxTextExtent); switch (magick[1]) { case 'A': case 'a': { format='7'; break; } case 'B': case 'b': { format='4'; if (image_info->compression == NoCompression) format='1'; break; } case 'F': case 'f': { format='F'; if (SetImageGray(image,&image->exception) != MagickFalse) format='f'; break; } case 'G': case 'g': { format='5'; if (image_info->compression == NoCompression) format='2'; break; } case 'N': case 'n': { if ((image_info->type != TrueColorType) && (SetImageGray(image,&image->exception) != MagickFalse)) { format='5'; if (image_info->compression == NoCompression) format='2'; if (SetImageMonochrome(image,&image->exception) != MagickFalse) { format='4'; if (image_info->compression == NoCompression) format='1'; } break; } } default: { format='6'; if (image_info->compression == NoCompression) format='3'; break; } } (void) FormatLocaleString(buffer,MaxTextExtent,"P%c\n",format); (void) WriteBlobString(image,buffer); value=GetImageProperty(image,"comment"); if (value != (const char *) NULL) { register const char *p; /* Write comments to file. */ (void) WriteBlobByte(image,'#'); for (p=value; *p != '\0'; p++) { (void) WriteBlobByte(image,(unsigned char) *p); if ((*p == '\n') || (*p == '\r')) (void) WriteBlobByte(image,'#'); } (void) WriteBlobByte(image,'\n'); } if (format != '7') { (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g\n", (double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); } else { char type[MaxTextExtent]; /* PAM header. */ (void) FormatLocaleString(buffer,MaxTextExtent, "WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); quantum_type=GetQuantumType(image,&image->exception); switch (quantum_type) { case CMYKQuantum: case CMYKAQuantum: { packet_size=4; (void) CopyMagickString(type,"CMYK",MaxTextExtent); break; } case GrayQuantum: case GrayAlphaQuantum: { packet_size=1; (void) CopyMagickString(type,"GRAYSCALE",MaxTextExtent); if (IdentifyImageMonochrome(image,&image->exception) != MagickFalse) (void) CopyMagickString(type,"BLACKANDWHITE",MaxTextExtent); break; } default: { quantum_type=RGBQuantum; if (image->matte != MagickFalse) quantum_type=RGBAQuantum; packet_size=3; (void) CopyMagickString(type,"RGB",MaxTextExtent); break; } } if (image->matte != MagickFalse) { packet_size++; (void) ConcatenateMagickString(type,"_ALPHA",MaxTextExtent); } if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MaxTextExtent, "DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"TUPLTYPE %s\nENDHDR\n", type); (void) WriteBlobString(image,buffer); } /* Convert to PNM raster pixels. */ switch (format) { case '1': { unsigned char pixels[2048]; /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ? '0' : '1'); *q++=' '; if ((q-pixels+1) >= (ssize_t) sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p++; } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '2': { unsigned char pixels[2048]; /* Convert image to a PGM image. */ if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { index=ClampToQuantum(GetPixelLuma(image,p)); if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ", ScaleQuantumToChar(index)); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ", ScaleQuantumToShort(index)); else count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ", ScaleQuantumToLong(index)); extent=(size_t) count; (void) strncpy((char *) q,buffer,extent); q+=extent; if ((q-pixels+extent+1) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p++; } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '3': { unsigned char pixels[2048]; /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace); if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent, "%u %u %u ",ScaleQuantumToChar(GetPixelRed(p)), ScaleQuantumToChar(GetPixelGreen(p)), ScaleQuantumToChar(GetPixelBlue(p))); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent, "%u %u %u ",ScaleQuantumToShort(GetPixelRed(p)), ScaleQuantumToShort(GetPixelGreen(p)), ScaleQuantumToShort(GetPixelBlue(p))); else count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent, "%u %u %u ",ScaleQuantumToLong(GetPixelRed(p)), ScaleQuantumToLong(GetPixelGreen(p)), ScaleQuantumToLong(GetPixelBlue(p))); extent=(size_t) count; (void) strncpy((char *) q,buffer,extent); q+=extent; if ((q-pixels+extent+1) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p++; } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '4': { /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType); image->depth=1; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; extent=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,pixels,&image->exception); count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '5': { /* Convert image to a PGM image. */ if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,GrayQuantum); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,pixels,&image->exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsGrayPixel(p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); else { if (image->depth == 8) pixel=ScaleQuantumToChar(GetPixelRed(p)); else pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); } q=PopCharPixel((unsigned char) pixel,q); p++; } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsGrayPixel(p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); else { if (image->depth == 16) pixel=ScaleQuantumToShort(GetPixelRed(p)); else pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); } q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p++; } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { if (IsGrayPixel(p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); else { if (image->depth == 32) pixel=ScaleQuantumToLong(GetPixelRed(p)); else pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); } q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p++; } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '6': { /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace); if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopCharPixel((unsigned char) pixel,q); p++; } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p++; } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopLongPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopLongPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopLongPixel(MSBEndian,(unsigned short) pixel,q); p++; } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '7': { /* Convert image to a PAM. */ if (image->depth > 32) image->depth=32; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); break; } default: { switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->matte != MagickFalse) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelOpacity(p),max_value); q=PopCharPixel((unsigned char) pixel,q); } p++; } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->matte != MagickFalse) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelOpacity(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->matte != MagickFalse) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelOpacity(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p++; } break; } case CMYKQuantum: case CMYKAQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopCharPixel((unsigned char) pixel,q); } p++; } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p++; } break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopCharPixel((unsigned char) pixel,q); } p++; } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p++; } break; } } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case 'F': case 'f': { (void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" : "1.0\n"); image->depth=32; quantum_type=format == 'f' ? GrayQuantum : RGBQuantum; quantum_info=AcquireQuantumInfo((const ImageInfo *) NULL,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); for (y=(ssize_t) image->rows-1; y >= 0; y--) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; extent=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); (void) WriteBlob(image,extent,pixels); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } } if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
null
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP N N M M % % P P NN N MM MM % % PPPP N N N M M M % % P N NN M M % % P N N M M % % % % % % Read/Write PBMPlus Portable Anymap Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/property.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/string-private.h" /* Typedef declarations. */ typedef struct _CommentInfo { char *comment; size_t extent; } CommentInfo; /* Forward declarations. */ static MagickBooleanType WritePNMImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P N M % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPNM() returns MagickTrue if the image format type, identified by the % magick string, is PNM. % % The format of the IsPNM method is: % % MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o extent: Specifies the extent of the magick string. % */ static MagickBooleanType IsPNM(const unsigned char *magick,const size_t extent) { if (extent < 2) return(MagickFalse); if ((*magick == (unsigned char) 'P') && ((magick[1] == '1') || (magick[1] == '2') || (magick[1] == '3') || (magick[1] == '4') || (magick[1] == '5') || (magick[1] == '6') || (magick[1] == '7') || (magick[1] == 'F') || (magick[1] == 'f'))) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPNMImage() reads a Portable Anymap image file and returns it. % It allocates the memory necessary for the new Image structure and returns % a pointer to the new image. % % The format of the ReadPNMImage method is: % % Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static int PNMComment(Image *image,CommentInfo *comment_info) { int c; register char *p; /* Read comment. */ p=comment_info->comment+strlen(comment_info->comment); for (c='#'; (c != EOF) && (c != (int) '\n') && (c != (int) '\r'); p++) { if ((size_t) (p-comment_info->comment+1) >= comment_info->extent) { comment_info->extent<<=1; comment_info->comment=(char *) ResizeQuantumMemory( comment_info->comment,comment_info->extent, sizeof(*comment_info->comment)); if (comment_info->comment == (char *) NULL) return(-1); p=comment_info->comment+strlen(comment_info->comment); } c=ReadBlobByte(image); if (c != EOF) { *p=(char) c; *(p+1)='\0'; } } return(c); } static unsigned int PNMInteger(Image *image,CommentInfo *comment_info, const unsigned int base) { int c; unsigned int value; /* Skip any leading whitespace. */ do { c=ReadBlobByte(image); if (c == EOF) return(0); if (c == (int) '#') c=PNMComment(image,comment_info); } while ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r')); if (base == 2) return((unsigned int) (c-(int) '0')); /* Evaluate number. */ value=0; while (isdigit(c) != 0) { if (value <= (unsigned int) (INT_MAX/10)) { value*=10; if (value <= (unsigned int) (INT_MAX-(c-(int) '0'))) value+=c-(int) '0'; } c=ReadBlobByte(image); if (c == EOF) return(0); } if (c == (int) '#') c=PNMComment(image,comment_info); return(value); } static Image *ReadPNMImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define ThrowPNMException(exception,message) \ { \ if (comment_info.comment != (char *) NULL) \ comment_info.comment=DestroyString(comment_info.comment); \ ThrowReaderException((exception),(message)); \ } char format; CommentInfo comment_info; double quantum_scale; Image *image; MagickBooleanType status; QuantumAny max_value; QuantumInfo *quantum_info; QuantumType quantum_type; size_t depth, extent, packet_size; ssize_t count, row, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read PNM image. */ count=ReadBlob(image,1,(unsigned char *) &format); do { /* Initialize image structure. */ comment_info.comment=AcquireString(NULL); comment_info.extent=MagickPathExtent; if ((count != 1) || (format != 'P')) ThrowPNMException(CorruptImageError,"ImproperImageHeader"); max_value=1; quantum_type=RGBQuantum; quantum_scale=1.0; format=(char) ReadBlobByte(image); if (format != '7') { /* PBM, PGM, PPM, and PNM. */ image->columns=PNMInteger(image,&comment_info,10); image->rows=PNMInteger(image,&comment_info,10); if ((format == 'f') || (format == 'F')) { char scale[MaxTextExtent]; if (ReadBlobString(image,scale) != (char *) NULL) quantum_scale=StringToDouble(scale,(char **) NULL); } else { if ((format == '1') || (format == '4')) max_value=1; /* bitmap */ else max_value=PNMInteger(image,&comment_info,10); } } else { char keyword[MaxTextExtent], value[MaxTextExtent]; int c; register char *p; /* PAM. */ for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); if (c == '#') { /* Comment. */ c=PNMComment(image,&comment_info); c=ReadBlobByte(image); while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } p=keyword; do { if ((size_t) (p-keyword) < (MaxTextExtent-1)) *p++=c; c=ReadBlobByte(image); } while (isalnum(c)); *p='\0'; if (LocaleCompare(keyword,"endhdr") == 0) break; while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); p=value; while (isalnum(c) || (c == '_')) { if ((size_t) (p-value) < (MaxTextExtent-1)) *p++=c; c=ReadBlobByte(image); } *p='\0'; /* Assign a value to the specified keyword. */ if (LocaleCompare(keyword,"depth") == 0) packet_size=StringToUnsignedLong(value); (void) packet_size; if (LocaleCompare(keyword,"height") == 0) image->rows=StringToUnsignedLong(value); if (LocaleCompare(keyword,"maxval") == 0) max_value=StringToUnsignedLong(value); if (LocaleCompare(keyword,"TUPLTYPE") == 0) { if (LocaleCompare(value,"BLACKANDWHITE") == 0) { (void) SetImageColorspace(image,GRAYColorspace); quantum_type=GrayQuantum; } if (LocaleCompare(value,"BLACKANDWHITE_ALPHA") == 0) { (void) SetImageColorspace(image,GRAYColorspace); image->matte=MagickTrue; quantum_type=GrayAlphaQuantum; } if (LocaleCompare(value,"GRAYSCALE") == 0) { (void) SetImageColorspace(image,GRAYColorspace); quantum_type=GrayQuantum; } if (LocaleCompare(value,"GRAYSCALE_ALPHA") == 0) { (void) SetImageColorspace(image,GRAYColorspace); image->matte=MagickTrue; quantum_type=GrayAlphaQuantum; } if (LocaleCompare(value,"RGB_ALPHA") == 0) { quantum_type=RGBAQuantum; image->matte=MagickTrue; } if (LocaleCompare(value,"CMYK") == 0) { (void) SetImageColorspace(image,CMYKColorspace); quantum_type=CMYKQuantum; } if (LocaleCompare(value,"CMYK_ALPHA") == 0) { (void) SetImageColorspace(image,CMYKColorspace); image->matte=MagickTrue; quantum_type=CMYKAQuantum; } } if (LocaleCompare(keyword,"width") == 0) image->columns=StringToUnsignedLong(value); } } if ((image->columns == 0) || (image->rows == 0)) ThrowPNMException(CorruptImageError,"NegativeOrZeroImageSize"); if ((max_value == 0) || (max_value > 4294967295U)) ThrowPNMException(CorruptImageError,"ImproperImageHeader"); for (depth=1; GetQuantumRange(depth) < max_value; depth++) ; image->depth=depth; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((MagickSizeType) (image->columns*image->rows/8) > GetBlobSize(image)) ThrowPNMException(CorruptImageError,"InsufficientImageDataInFile"); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } (void) ResetImagePixels(image,exception); /* Convert PNM pixels. */ row=0; switch (format) { case '1': { /* Convert PBM image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace); for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,PNMInteger(image,&comment_info,2) == 0 ? QuantumRange : 0); if (EOFBlob(image) != MagickFalse) break; SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } image->type=BilevelType; break; } case '2': { size_t intensity; /* Convert PGM image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace); for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { intensity=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10), max_value); if (EOFBlob(image) != MagickFalse) break; SetPixelRed(q,intensity); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } image->type=GrayscaleType; break; } case '3': { /* Convert PNM image to pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { QuantumAny pixel; pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10), max_value); if (EOFBlob(image) != MagickFalse) break; SetPixelRed(q,pixel); pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10), max_value); SetPixelGreen(q,pixel); pixel=ScaleAnyToQuantum(PNMInteger(image,&comment_info,10), max_value); SetPixelBlue(q,pixel); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) break; } break; } case '4': { /* Convert PBM raw image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace); quantum_type=GrayQuantum; if (image->storage_class == PseudoClass) quantum_type=IndexQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); SetQuantumMinIsWhite(quantum_info,MagickTrue); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register PixelPacket *magick_restrict q; ssize_t count, offset; size_t length; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (length != extent) break; sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case '5': { /* Convert PGM raw image to pixel packets. */ (void) SetImageColorspace(image,GRAYColorspace); quantum_type=GrayQuantum; extent=(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; ssize_t count, offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; p=pixels; switch (image->depth) { case 8: case 16: case 32: { (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { unsigned int pixel; if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); q++; } break; } if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); q++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); q++; } break; } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case '6': { /* Convert PNM raster image to pixel packets. */ quantum_type=RGBQuantum; extent=3*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; ssize_t count, offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; p=pixels; switch (image->depth) { case 8: { for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); q->opacity=OpaqueOpacity; q++; } break; } case 16: { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleShortToQuantum(pixel)); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(q,ScaleShortToQuantum(pixel)); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(q,ScaleShortToQuantum(pixel)); SetPixelOpacity(q,OpaqueOpacity); q++; } break; } case 32: { unsigned int pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleLongToQuantum(pixel)); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(q,ScaleLongToQuantum(pixel)); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(q,ScaleLongToQuantum(pixel)); SetPixelOpacity(q,OpaqueOpacity); q++; } break; } default: { unsigned int pixel; if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); p=PushCharPixel(p,&pixel); SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value)); p=PushCharPixel(p,&pixel); SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelOpacity(q,OpaqueOpacity); q++; } break; } if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value)); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelOpacity(q,OpaqueOpacity); q++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value)); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelOpacity(q,OpaqueOpacity); q++; } break; } break; } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '7': { register IndexPacket *indexes; size_t channels; /* Convert PAM raster image to pixel packets. */ switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { channels=1; break; } case CMYKQuantum: case CMYKAQuantum: { channels=4; break; } default: { channels=3; break; } } if (image->matte != MagickFalse) channels++; extent=channels*(image->depth <= 8 ? 1 : image->depth <= 16 ? 2 : 4)* image->columns; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register const unsigned char *magick_restrict p; register ssize_t x; register PixelPacket *magick_restrict q; ssize_t count, offset; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=pixels; switch (image->depth) { case 8: case 16: case 32: { (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { unsigned int pixel; if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { p=PushCharPixel(p,&pixel); if (image->depth != 1) SetPixelOpacity(q,ScaleAnyToQuantum(pixel, max_value)); else SetPixelOpacity(q,QuantumRange-ScaleAnyToQuantum( pixel,max_value)); } q++; } break; } if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelOpacity(q,ScaleAnyToQuantum(pixel, max_value)); } q++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelOpacity(q,ScaleAnyToQuantum(pixel,max_value)); } q++; } break; } case CMYKQuantum: case CMYKAQuantum: { unsigned int pixel; if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); p=PushCharPixel(p,&pixel); SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value)); p=PushCharPixel(p,&pixel); SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value)); p=PushCharPixel(p,&pixel); SetPixelIndex(indexes+x,ScaleAnyToQuantum(pixel, max_value)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { p=PushCharPixel(p,&pixel); SetPixelOpacity(q,ScaleAnyToQuantum(pixel, max_value)); } q++; } break; } if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value)); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value)); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelIndex(indexes+x,ScaleAnyToQuantum(pixel, max_value)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelOpacity(q,ScaleAnyToQuantum(pixel, max_value)); } q++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value)); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value)); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelIndex(indexes+x,ScaleAnyToQuantum(pixel,max_value)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelOpacity(q,ScaleAnyToQuantum(pixel,max_value)); } q++; } break; } default: { unsigned int pixel; if (image->depth <= 8) { unsigned char pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushCharPixel(p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); p=PushCharPixel(p,&pixel); SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value)); p=PushCharPixel(p,&pixel); SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { p=PushCharPixel(p,&pixel); SetPixelOpacity(q,ScaleAnyToQuantum(pixel, max_value)); } q++; } break; } if (image->depth <= 16) { unsigned short pixel; for (x=0; x < (ssize_t) image->columns; x++) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value)); p=PushShortPixel(MSBEndian,p,&pixel); SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { p=PushShortPixel(MSBEndian,p,&pixel); SetPixelOpacity(q,ScaleAnyToQuantum(pixel, max_value)); } q++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelRed(q,ScaleAnyToQuantum(pixel,max_value)); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelGreen(q,ScaleAnyToQuantum(pixel,max_value)); p=PushLongPixel(MSBEndian,p,&pixel); SetPixelBlue(q,ScaleAnyToQuantum(pixel,max_value)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) { p=PushLongPixel(MSBEndian,p,&pixel); SetPixelOpacity(q,ScaleAnyToQuantum(pixel,max_value)); } q++; } break; } } break; } } sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } case 'F': case 'f': { /* Convert PFM raster image to pixel packets. */ if (format == 'f') (void) SetImageColorspace(image,GRAYColorspace); quantum_type=format == 'f' ? GrayQuantum : RGBQuantum; image->endian=quantum_scale < 0.0 ? LSBEndian : MSBEndian; image->depth=32; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumDepth(image,quantum_info,32); if (status == MagickFalse) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowPNMException(ResourceLimitError,"MemoryAllocationFailed"); SetQuantumScale(quantum_info,(MagickRealType) QuantumRange* fabs(quantum_scale)); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { const unsigned char *pixels; MagickBooleanType sync; register PixelPacket *magick_restrict q; ssize_t count, offset; size_t length; pixels=(unsigned char *) ReadBlobStream(image,extent, GetQuantumPixels(quantum_info),&count); if ((size_t) count != extent) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (image->previous == (Image *) NULL)) { MagickBooleanType proceed; proceed=SetImageProgress(image,LoadImageTag,(MagickOffsetType) row,image->rows); if (proceed == MagickFalse) break; } offset=row++; q=QueueAuthenticPixels(image,0,(ssize_t) (image->rows-offset-1), image->columns,1,exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (length != extent) break; sync=SyncAuthenticPixels(image,exception); if (sync == MagickFalse) break; } quantum_info=DestroyQuantumInfo(quantum_info); SetQuantumImageType(image,quantum_type); break; } default: ThrowPNMException(CorruptImageError,"ImproperImageHeader"); } if (*comment_info.comment != '\0') (void) SetImageProperty(image,"comment",comment_info.comment); comment_info.comment=DestroyString(comment_info.comment); if (y < (ssize_t) image->rows) ThrowPNMException(CorruptImageError,"UnableToReadImageData"); if (EOFBlob(image) != MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"UnexpectedEndOfFile","`%s'",image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((format == '1') || (format == '2') || (format == '3')) do { /* Skip to end of line. */ count=ReadBlob(image,1,(unsigned char *) &format); if (count != 1) break; if (format == 'P') break; } while (format != '\n'); count=ReadBlob(image,1,(unsigned char *) &format); if ((count == 1) && (format == 'P')) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count == 1) && (format == 'P')); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPNMImage() adds properties for the PNM image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPNMImage method is: % % size_t RegisterPNMImage(void) % */ ModuleExport size_t RegisterPNMImage(void) { MagickInfo *entry; entry=SetMagickInfo("PAM"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->description=ConstantString("Common 2-dimensional bitmap format"); entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->module=ConstantString("PNM"); entry->seekable_stream=MagickTrue; (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PBM"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->description=ConstantString("Portable bitmap format (black and white)"); entry->mime_type=ConstantString("image/x-portable-bitmap"); entry->module=ConstantString("PNM"); entry->seekable_stream=MagickTrue; (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PFM"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->endian_support=MagickTrue; entry->description=ConstantString("Portable float format"); entry->module=ConstantString("PFM"); entry->seekable_stream=MagickTrue; (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PGM"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->description=ConstantString("Portable graymap format (gray scale)"); entry->mime_type=ConstantString("image/x-portable-greymap"); entry->module=ConstantString("PNM"); entry->seekable_stream=MagickTrue; (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PNM"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->magick=(IsImageFormatHandler *) IsPNM; entry->description=ConstantString("Portable anymap"); entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->module=ConstantString("PNM"); entry->seekable_stream=MagickTrue; (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PPM"); entry->decoder=(DecodeImageHandler *) ReadPNMImage; entry->encoder=(EncodeImageHandler *) WritePNMImage; entry->description=ConstantString("Portable pixmap format (color)"); entry->mime_type=ConstantString("image/x-portable-pixmap"); entry->module=ConstantString("PNM"); entry->seekable_stream=MagickTrue; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPNMImage() removes format registrations made by the % PNM module from the list of supported formats. % % The format of the UnregisterPNMImage method is: % % UnregisterPNMImage(void) % */ ModuleExport void UnregisterPNMImage(void) { (void) UnregisterMagickInfo("PAM"); (void) UnregisterMagickInfo("PBM"); (void) UnregisterMagickInfo("PGM"); (void) UnregisterMagickInfo("PNM"); (void) UnregisterMagickInfo("PPM"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P N M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePNMImage() writes an image to a file in the PNM rasterfile format. % % The format of the WritePNMImage method is: % % MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image) { char buffer[MaxTextExtent], format, magick[MaxTextExtent]; const char *value; IndexPacket index; MagickBooleanType status; MagickOffsetType scene; QuantumAny pixel; QuantumInfo *quantum_info; QuantumType quantum_type; register unsigned char *pixels, *q; size_t extent, imageListLength, packet_size; ssize_t count, y; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); scene=0; imageListLength=GetImageListLength(image); do { QuantumAny max_value; /* Write PNM file header. */ max_value=GetQuantumRange(image->depth); packet_size=3; quantum_type=RGBQuantum; (void) CopyMagickString(magick,image_info->magick,MaxTextExtent); switch (magick[1]) { case 'A': case 'a': { format='7'; break; } case 'B': case 'b': { format='4'; if (image_info->compression == NoCompression) format='1'; break; } case 'F': case 'f': { format='F'; if (SetImageGray(image,&image->exception) != MagickFalse) format='f'; break; } case 'G': case 'g': { format='5'; if (image_info->compression == NoCompression) format='2'; break; } case 'N': case 'n': { if ((image_info->type != TrueColorType) && (SetImageGray(image,&image->exception) != MagickFalse)) { format='5'; if (image_info->compression == NoCompression) format='2'; if (SetImageMonochrome(image,&image->exception) != MagickFalse) { format='4'; if (image_info->compression == NoCompression) format='1'; } break; } } default: { format='6'; if (image_info->compression == NoCompression) format='3'; break; } } (void) FormatLocaleString(buffer,MaxTextExtent,"P%c\n",format); (void) WriteBlobString(image,buffer); value=GetImageProperty(image,"comment"); if (value != (const char *) NULL) { register const char *p; /* Write comments to file. */ (void) WriteBlobByte(image,'#'); for (p=value; *p != '\0'; p++) { (void) WriteBlobByte(image,(unsigned char) *p); if ((*p == '\n') || (*p == '\r')) (void) WriteBlobByte(image,'#'); } (void) WriteBlobByte(image,'\n'); } if (format != '7') { (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g\n", (double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); } else { char type[MaxTextExtent]; /* PAM header. */ (void) FormatLocaleString(buffer,MaxTextExtent, "WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); quantum_type=GetQuantumType(image,&image->exception); switch (quantum_type) { case CMYKQuantum: case CMYKAQuantum: { packet_size=4; (void) CopyMagickString(type,"CMYK",MaxTextExtent); break; } case GrayQuantum: case GrayAlphaQuantum: { packet_size=1; (void) CopyMagickString(type,"GRAYSCALE",MaxTextExtent); if (IdentifyImageMonochrome(image,&image->exception) != MagickFalse) (void) CopyMagickString(type,"BLACKANDWHITE",MaxTextExtent); break; } default: { quantum_type=RGBQuantum; if (image->matte != MagickFalse) quantum_type=RGBAQuantum; packet_size=3; (void) CopyMagickString(type,"RGB",MaxTextExtent); break; } } if (image->matte != MagickFalse) { packet_size++; (void) ConcatenateMagickString(type,"_ALPHA",MaxTextExtent); } if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MaxTextExtent, "DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"TUPLTYPE %s\nENDHDR\n", type); (void) WriteBlobString(image,buffer); } /* Convert to PNM raster pixels. */ switch (format) { case '1': { unsigned char pixels[2048]; /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ? '0' : '1'); *q++=' '; if ((q-pixels+1) >= (ssize_t) sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p++; } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '2': { unsigned char pixels[2048]; /* Convert image to a PGM image. */ if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { index=ClampToQuantum(GetPixelLuma(image,p)); if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ", ScaleQuantumToChar(index)); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ", ScaleQuantumToShort(index)); else count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent,"%u ", ScaleQuantumToLong(index)); extent=(size_t) count; (void) strncpy((char *) q,buffer,extent); q+=extent; if ((q-pixels+extent+2) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p++; } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '3': { unsigned char pixels[2048]; /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace); if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent, "%u %u %u ",ScaleQuantumToChar(GetPixelRed(p)), ScaleQuantumToChar(GetPixelGreen(p)), ScaleQuantumToChar(GetPixelBlue(p))); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent, "%u %u %u ",ScaleQuantumToShort(GetPixelRed(p)), ScaleQuantumToShort(GetPixelGreen(p)), ScaleQuantumToShort(GetPixelBlue(p))); else count=(ssize_t) FormatLocaleString(buffer,MaxTextExtent, "%u %u %u ",ScaleQuantumToLong(GetPixelRed(p)), ScaleQuantumToLong(GetPixelGreen(p)), ScaleQuantumToLong(GetPixelBlue(p))); extent=(size_t) count; (void) strncpy((char *) q,buffer,extent); q+=extent; if ((q-pixels+extent+2) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p++; } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '4': { /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType); image->depth=1; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; extent=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,pixels,&image->exception); count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '5': { /* Convert image to a PGM image. */ if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,GrayQuantum); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GrayQuantum,pixels,&image->exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsGrayPixel(p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); else { if (image->depth == 8) pixel=ScaleQuantumToChar(GetPixelRed(p)); else pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); } q=PopCharPixel((unsigned char) pixel,q); p++; } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsGrayPixel(p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); else { if (image->depth == 16) pixel=ScaleQuantumToShort(GetPixelRed(p)); else pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); } q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p++; } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { if (IsGrayPixel(p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); else { if (image->depth == 32) pixel=ScaleQuantumToLong(GetPixelRed(p)); else pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); } q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p++; } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '6': { /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace); if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopCharPixel((unsigned char) pixel,q); p++; } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p++; } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopLongPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopLongPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopLongPixel(MSBEndian,(unsigned short) pixel,q); p++; } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '7': { /* Convert image to a PAM. */ if (image->depth > 32) image->depth=32; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); break; } default: { switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->matte != MagickFalse) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelOpacity(p),max_value); q=PopCharPixel((unsigned char) pixel,q); } p++; } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->matte != MagickFalse) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelOpacity(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum( GetPixelLuma(image,p)),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->matte != MagickFalse) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelOpacity(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p++; } break; } case CMYKQuantum: case CMYKAQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopCharPixel((unsigned char) pixel,q); } p++; } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelIndex(indexes+x),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p++; } break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopCharPixel((unsigned char) pixel,q); } p++; } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p++; } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->matte != MagickFalse) { pixel=ScaleQuantumToAny((Quantum) (QuantumRange- GetPixelOpacity(p)),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p++; } break; } } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case 'F': case 'f': { (void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" : "1.0\n"); image->depth=32; quantum_type=format == 'f' ? GrayQuantum : RGBQuantum; quantum_info=AcquireQuantumInfo((const ImageInfo *) NULL,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); for (y=(ssize_t) image->rows-1; y >= 0; y--) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; extent=ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->exception); (void) WriteBlob(image,extent,pixels); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } } if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
null
128
CWE-787
CVE-2019-13307
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS TTTTT AAA TTTTT IIIII SSSSS TTTTT IIIII CCCC % % SS T A A T I SS T I C % % SSS T AAAAA T I SSS T I C % % SS T A A T I SS T I C % % SSSSS T A A T IIIII SSSSS T IIIII CCCC % % % % % % MagickCore Image Statistical Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/accelerate-private.h" #include "magick/animate.h" #include "magick/animate.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/cache-private.h" #include "magick/cache-view.h" #include "magick/client.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/composite.h" #include "magick/composite-private.h" #include "magick/compress.h" #include "magick/constitute.h" #include "magick/deprecate.h" #include "magick/display.h" #include "magick/draw.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/gem.h" #include "magick/geometry.h" #include "magick/list.h" #include "magick/image-private.h" #include "magick/magic.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/paint.h" #include "magick/pixel-private.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/quantize.h" #include "magick/random_.h" #include "magick/random-private.h" #include "magick/resource_.h" #include "magick/segment.h" #include "magick/semaphore.h" #include "magick/signature-private.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/thread-private.h" #include "magick/timer.h" #include "magick/utility.h" #include "magick/version.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E v a l u a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EvaluateImage() applies a value to the image with an arithmetic, relational, % or logical operator to an image. Use these operations to lighten or darken % an image, to increase or decrease contrast in an image, or to produce the % "negative" of an image. % % The format of the EvaluateImageChannel method is: % % MagickBooleanType EvaluateImage(Image *image, % const MagickEvaluateOperator op,const double value, % ExceptionInfo *exception) % MagickBooleanType EvaluateImages(Image *images, % const MagickEvaluateOperator op,const double value, % ExceptionInfo *exception) % MagickBooleanType EvaluateImageChannel(Image *image, % const ChannelType channel,const MagickEvaluateOperator op, % const double value,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o op: A channel op. % % o value: A value value. % % o exception: return any errors or warnings in this structure. % */ static MagickPixelPacket **DestroyPixelThreadSet(MagickPixelPacket **pixels) { register ssize_t i; assert(pixels != (MagickPixelPacket **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixels[i] != (MagickPixelPacket *) NULL) pixels[i]=(MagickPixelPacket *) RelinquishMagickMemory(pixels[i]); pixels=(MagickPixelPacket **) RelinquishMagickMemory(pixels); return(pixels); } static MagickPixelPacket **AcquirePixelThreadSet(const Image *images) { const Image *next; MagickPixelPacket **pixels; register ssize_t i, j; size_t columns, number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(MagickPixelPacket **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (MagickPixelPacket **) NULL) return((MagickPixelPacket **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); columns=images->columns; for (next=images; next != (Image *) NULL; next=next->next) columns=MagickMax(next->columns,columns); for (i=0; i < (ssize_t) number_threads; i++) { pixels[i]=(MagickPixelPacket *) AcquireQuantumMemory(columns, sizeof(**pixels)); if (pixels[i] == (MagickPixelPacket *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) columns; j++) GetMagickPixelPacket(images,&pixels[i][j]); } return(pixels); } static inline double EvaluateMax(const double x,const double y) { if (x > y) return(x); return(y); } #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int IntensityCompare(const void *x,const void *y) { const MagickPixelPacket *color_1, *color_2; int intensity; color_1=(const MagickPixelPacket *) x; color_2=(const MagickPixelPacket *) y; intensity=(int) MagickPixelIntensity(color_2)-(int) MagickPixelIntensity(color_1); return(intensity); } #if defined(__cplusplus) || defined(c_plusplus) } #endif static MagickRealType ApplyEvaluateOperator(RandomInfo *random_info, const Quantum pixel,const MagickEvaluateOperator op, const MagickRealType value) { MagickRealType result; result=0.0; switch (op) { case UndefinedEvaluateOperator: break; case AbsEvaluateOperator: { result=(MagickRealType) fabs((double) (pixel+value)); break; } case AddEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case AddModulusEvaluateOperator: { /* This returns a 'floored modulus' of the addition which is a positive result. It differs from % or fmod() which returns a 'truncated modulus' result, where floor() is replaced by trunc() and could return a negative result (which is clipped). */ result=pixel+value; result-=(QuantumRange+1.0)*floor((double) result/(QuantumRange+1.0)); break; } case AndEvaluateOperator: { result=(MagickRealType) ((size_t) pixel & (size_t) (value+0.5)); break; } case CosineEvaluateOperator: { result=(MagickRealType) (QuantumRange*(0.5*cos((double) (2.0*MagickPI* QuantumScale*pixel*value))+0.5)); break; } case DivideEvaluateOperator: { result=pixel/(value == 0.0 ? 1.0 : value); break; } case ExponentialEvaluateOperator: { result=(MagickRealType) (QuantumRange*exp((double) (value*QuantumScale* pixel))); break; } case GaussianNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, GaussianNoise,value); break; } case ImpulseNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, ImpulseNoise,value); break; } case LaplacianNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, LaplacianNoise,value); break; } case LeftShiftEvaluateOperator: { result=(MagickRealType) ((size_t) pixel << (size_t) (value+0.5)); break; } case LogEvaluateOperator: { if ((QuantumScale*pixel) >= MagickEpsilon) result=(MagickRealType) (QuantumRange*log((double) (QuantumScale*value* pixel+1.0))/log((double) (value+1.0))); break; } case MaxEvaluateOperator: { result=(MagickRealType) EvaluateMax((double) pixel,value); break; } case MeanEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case MedianEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case MinEvaluateOperator: { result=(MagickRealType) MagickMin((double) pixel,value); break; } case MultiplicativeNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, MultiplicativeGaussianNoise,value); break; } case MultiplyEvaluateOperator: { result=(MagickRealType) (value*pixel); break; } case OrEvaluateOperator: { result=(MagickRealType) ((size_t) pixel | (size_t) (value+0.5)); break; } case PoissonNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, PoissonNoise,value); break; } case PowEvaluateOperator: { result=(MagickRealType) (QuantumRange*pow((double) (QuantumScale*pixel), (double) value)); break; } case RightShiftEvaluateOperator: { result=(MagickRealType) ((size_t) pixel >> (size_t) (value+0.5)); break; } case RootMeanSquareEvaluateOperator: { result=(MagickRealType) (pixel*pixel+value); break; } case SetEvaluateOperator: { result=value; break; } case SineEvaluateOperator: { result=(MagickRealType) (QuantumRange*(0.5*sin((double) (2.0*MagickPI* QuantumScale*pixel*value))+0.5)); break; } case SubtractEvaluateOperator: { result=(MagickRealType) (pixel-value); break; } case SumEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case ThresholdEvaluateOperator: { result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 : QuantumRange); break; } case ThresholdBlackEvaluateOperator: { result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 : pixel); break; } case ThresholdWhiteEvaluateOperator: { result=(MagickRealType) (((MagickRealType) pixel > value) ? QuantumRange : pixel); break; } case UniformNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, UniformNoise,value); break; } case XorEvaluateOperator: { result=(MagickRealType) ((size_t) pixel ^ (size_t) (value+0.5)); break; } } return(result); } static Image *AcquireImageCanvas(const Image *images,ExceptionInfo *exception) { const Image *p, *q; size_t columns, number_channels, rows; q=images; columns=images->columns; rows=images->rows; number_channels=0; for (p=images; p != (Image *) NULL; p=p->next) { size_t channels; channels=3; if (p->matte != MagickFalse) channels+=1; if (p->colorspace == CMYKColorspace) channels+=1; if (channels > number_channels) { number_channels=channels; q=p; } if (p->columns > columns) columns=p->columns; if (p->rows > rows) rows=p->rows; } return(CloneImage(q,columns,rows,MagickTrue,exception)); } MagickExport MagickBooleanType EvaluateImage(Image *image, const MagickEvaluateOperator op,const double value,ExceptionInfo *exception) { MagickBooleanType status; status=EvaluateImageChannel(image,CompositeChannels,op,value,exception); return(status); } MagickExport Image *EvaluateImages(const Image *images, const MagickEvaluateOperator op,ExceptionInfo *exception) { #define EvaluateImageTag "Evaluate/Image" CacheView *evaluate_view; Image *image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket **magick_restrict evaluate_pixels, zero; RandomInfo **magick_restrict random_info; size_t number_images; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImageCanvas(images,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImage(image); return((Image *) NULL); } evaluate_pixels=AcquirePixelThreadSet(images); if (evaluate_pixels == (MagickPixelPacket **) NULL) { image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return((Image *) NULL); } /* Evaluate image pixels. */ status=MagickTrue; progress=0; number_images=GetImageListLength(images); GetMagickPixelPacket(images,&zero); random_info=AcquireRandomInfoThreadSet(); evaluate_view=AcquireAuthenticCacheView(image,exception); if (op == MedianEvaluateOperator) { #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,images,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict evaluate_indexes; register MagickPixelPacket *evaluate_pixel; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } evaluate_indexes=GetCacheViewAuthenticIndexQueue(evaluate_view); evaluate_pixel=evaluate_pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) number_images; i++) evaluate_pixel[i]=zero; next=images; for (i=0; i < (ssize_t) number_images; i++) { register const IndexPacket *indexes; register const PixelPacket *p; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,x,y,1,1,exception); if (p == (const PixelPacket *) NULL) { image_view=DestroyCacheView(image_view); break; } indexes=GetCacheViewVirtualIndexQueue(image_view); evaluate_pixel[i].red=ApplyEvaluateOperator(random_info[id], GetPixelRed(p),op,evaluate_pixel[i].red); evaluate_pixel[i].green=ApplyEvaluateOperator(random_info[id], GetPixelGreen(p),op,evaluate_pixel[i].green); evaluate_pixel[i].blue=ApplyEvaluateOperator(random_info[id], GetPixelBlue(p),op,evaluate_pixel[i].blue); evaluate_pixel[i].opacity=ApplyEvaluateOperator(random_info[id], GetPixelAlpha(p),op,evaluate_pixel[i].opacity); if (image->colorspace == CMYKColorspace) evaluate_pixel[i].index=ApplyEvaluateOperator(random_info[id], *indexes,op,evaluate_pixel[i].index); image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } qsort((void *) evaluate_pixel,number_images,sizeof(*evaluate_pixel), IntensityCompare); SetPixelRed(q,ClampToQuantum(evaluate_pixel[i/2].red)); SetPixelGreen(q,ClampToQuantum(evaluate_pixel[i/2].green)); SetPixelBlue(q,ClampToQuantum(evaluate_pixel[i/2].blue)); SetPixelAlpha(q,ClampToQuantum(evaluate_pixel[i/2].opacity)); if (image->colorspace == CMYKColorspace) SetPixelIndex(evaluate_indexes+i,ClampToQuantum( evaluate_pixel[i/2].index)); q++; } if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,EvaluateImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } else { #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,images,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict evaluate_indexes; register ssize_t i, x; register MagickPixelPacket *evaluate_pixel; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } evaluate_indexes=GetCacheViewAuthenticIndexQueue(evaluate_view); evaluate_pixel=evaluate_pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) evaluate_pixel[x]=zero; next=images; for (i=0; i < (ssize_t) number_images; i++) { register const IndexPacket *indexes; register const PixelPacket *p; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1, exception); if (p == (const PixelPacket *) NULL) { image_view=DestroyCacheView(image_view); break; } indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { evaluate_pixel[x].red=ApplyEvaluateOperator(random_info[id], GetPixelRed(p),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].red); evaluate_pixel[x].green=ApplyEvaluateOperator(random_info[id], GetPixelGreen(p),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].green); evaluate_pixel[x].blue=ApplyEvaluateOperator(random_info[id], GetPixelBlue(p),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].blue); evaluate_pixel[x].opacity=ApplyEvaluateOperator(random_info[id], GetPixelAlpha(p),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].opacity); if (image->colorspace == CMYKColorspace) evaluate_pixel[x].index=ApplyEvaluateOperator(random_info[id], GetPixelIndex(indexes+x),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].index); p++; } image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } if (op == MeanEvaluateOperator) for (x=0; x < (ssize_t) image->columns; x++) { evaluate_pixel[x].red/=number_images; evaluate_pixel[x].green/=number_images; evaluate_pixel[x].blue/=number_images; evaluate_pixel[x].opacity/=number_images; evaluate_pixel[x].index/=number_images; } if (op == RootMeanSquareEvaluateOperator) for (x=0; x < (ssize_t) image->columns; x++) { evaluate_pixel[x].red=sqrt((double) evaluate_pixel[x].red/ number_images); evaluate_pixel[x].green=sqrt((double) evaluate_pixel[x].green/ number_images); evaluate_pixel[x].blue=sqrt((double) evaluate_pixel[x].blue/ number_images); evaluate_pixel[x].opacity=sqrt((double) evaluate_pixel[x].opacity/ number_images); evaluate_pixel[x].index=sqrt((double) evaluate_pixel[x].index/ number_images); } if (op == MultiplyEvaluateOperator) for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; for (j=0; j < (ssize_t) (number_images-1); j++) { evaluate_pixel[x].red*=(MagickRealType) QuantumScale; evaluate_pixel[x].green*=(MagickRealType) QuantumScale; evaluate_pixel[x].blue*=(MagickRealType) QuantumScale; evaluate_pixel[x].opacity*=(MagickRealType) QuantumScale; evaluate_pixel[x].index*=(MagickRealType) QuantumScale; } } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ClampToQuantum(evaluate_pixel[x].red)); SetPixelGreen(q,ClampToQuantum(evaluate_pixel[x].green)); SetPixelBlue(q,ClampToQuantum(evaluate_pixel[x].blue)); SetPixelAlpha(q,ClampToQuantum(evaluate_pixel[x].opacity)); if (image->colorspace == CMYKColorspace) SetPixelIndex(evaluate_indexes+x,ClampToQuantum( evaluate_pixel[x].index)); q++; } if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(images,EvaluateImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } evaluate_view=DestroyCacheView(evaluate_view); evaluate_pixels=DestroyPixelThreadSet(evaluate_pixels); random_info=DestroyRandomInfoThreadSet(random_info); if (status == MagickFalse) image=DestroyImage(image); return(image); } MagickExport MagickBooleanType EvaluateImageChannel(Image *image, const ChannelType channel,const MagickEvaluateOperator op,const double value, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); return(MagickFalse); } status=MagickTrue; progress=0; random_info=AcquireRandomInfoThreadSet(); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType result; if ((channel & RedChannel) != 0) { result=ApplyEvaluateOperator(random_info[id],GetPixelRed(q),op,value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelRed(q,ClampToQuantum(result)); } if ((channel & GreenChannel) != 0) { result=ApplyEvaluateOperator(random_info[id],GetPixelGreen(q),op, value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelGreen(q,ClampToQuantum(result)); } if ((channel & BlueChannel) != 0) { result=ApplyEvaluateOperator(random_info[id],GetPixelBlue(q),op, value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelBlue(q,ClampToQuantum(result)); } if ((channel & OpacityChannel) != 0) { if (image->matte == MagickFalse) { result=ApplyEvaluateOperator(random_info[id],GetPixelOpacity(q), op,value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelOpacity(q,ClampToQuantum(result)); } else { result=ApplyEvaluateOperator(random_info[id],GetPixelAlpha(q), op,value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelAlpha(q,ClampToQuantum(result)); } } if (((channel & IndexChannel) != 0) && (indexes != (IndexPacket *) NULL)) { result=ApplyEvaluateOperator(random_info[id],GetPixelIndex(indexes+x), op,value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelIndex(indexes+x,ClampToQuantum(result)); } q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,EvaluateImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F u n c t i o n I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FunctionImage() applies a value to the image with an arithmetic, relational, % or logical operator to an image. Use these operations to lighten or darken % an image, to increase or decrease contrast in an image, or to produce the % "negative" of an image. % % The format of the FunctionImageChannel method is: % % MagickBooleanType FunctionImage(Image *image, % const MagickFunction function,const ssize_t number_parameters, % const double *parameters,ExceptionInfo *exception) % MagickBooleanType FunctionImageChannel(Image *image, % const ChannelType channel,const MagickFunction function, % const ssize_t number_parameters,const double *argument, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o function: A channel function. % % o parameters: one or more parameters. % % o exception: return any errors or warnings in this structure. % */ static Quantum ApplyFunction(Quantum pixel,const MagickFunction function, const size_t number_parameters,const double *parameters, ExceptionInfo *exception) { MagickRealType result; register ssize_t i; (void) exception; result=0.0; switch (function) { case PolynomialFunction: { /* * Polynomial * Parameters: polynomial constants, highest to lowest order * For example: c0*x^3 + c1*x^2 + c2*x + c3 */ result=0.0; for (i=0; i < (ssize_t) number_parameters; i++) result=result*QuantumScale*pixel + parameters[i]; result*=QuantumRange; break; } case SinusoidFunction: { /* Sinusoid Function * Parameters: Freq, Phase, Ampl, bias */ double freq,phase,ampl,bias; freq = ( number_parameters >= 1 ) ? parameters[0] : 1.0; phase = ( number_parameters >= 2 ) ? parameters[1] : 0.0; ampl = ( number_parameters >= 3 ) ? parameters[2] : 0.5; bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5; result=(MagickRealType) (QuantumRange*(ampl*sin((double) (2.0*MagickPI* (freq*QuantumScale*pixel + phase/360.0) )) + bias ) ); break; } case ArcsinFunction: { /* Arcsin Function (peged at range limits for invalid results) * Parameters: Width, Center, Range, Bias */ double width,range,center,bias; width = ( number_parameters >= 1 ) ? parameters[0] : 1.0; center = ( number_parameters >= 2 ) ? parameters[1] : 0.5; range = ( number_parameters >= 3 ) ? parameters[2] : 1.0; bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5; result = 2.0/width*(QuantumScale*pixel - center); if ( result <= -1.0 ) result = bias - range/2.0; else if ( result >= 1.0 ) result = bias + range/2.0; else result=(MagickRealType) (range/MagickPI*asin((double) result)+bias); result *= QuantumRange; break; } case ArctanFunction: { /* Arctan Function * Parameters: Slope, Center, Range, Bias */ double slope,range,center,bias; slope = ( number_parameters >= 1 ) ? parameters[0] : 1.0; center = ( number_parameters >= 2 ) ? parameters[1] : 0.5; range = ( number_parameters >= 3 ) ? parameters[2] : 1.0; bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5; result=(MagickRealType) (MagickPI*slope*(QuantumScale*pixel-center)); result=(MagickRealType) (QuantumRange*(range/MagickPI*atan((double) result) + bias ) ); break; } case UndefinedFunction: break; } return(ClampToQuantum(result)); } MagickExport MagickBooleanType FunctionImage(Image *image, const MagickFunction function,const size_t number_parameters, const double *parameters,ExceptionInfo *exception) { MagickBooleanType status; status=FunctionImageChannel(image,CompositeChannels,function, number_parameters,parameters,exception); return(status); } MagickExport MagickBooleanType FunctionImageChannel(Image *image, const ChannelType channel,const MagickFunction function, const size_t number_parameters,const double *parameters, ExceptionInfo *exception) { #define FunctionImageTag "Function/Image " CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); return(MagickFalse); } #if defined(MAGICKCORE_OPENCL_SUPPORT) status=AccelerateFunctionImage(image,channel,function,number_parameters, parameters,exception); if (status != MagickFalse) return(status); #endif status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,ApplyFunction(GetPixelRed(q),function, number_parameters,parameters,exception)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ApplyFunction(GetPixelGreen(q),function, number_parameters,parameters,exception)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ApplyFunction(GetPixelBlue(q),function, number_parameters,parameters,exception)); if ((channel & OpacityChannel) != 0) { if (image->matte == MagickFalse) SetPixelOpacity(q,ApplyFunction(GetPixelOpacity(q),function, number_parameters,parameters,exception)); else SetPixelAlpha(q,ApplyFunction((Quantum) GetPixelAlpha(q),function, number_parameters,parameters,exception)); } if (((channel & IndexChannel) != 0) && (indexes != (IndexPacket *) NULL)) SetPixelIndex(indexes+x,ApplyFunction(GetPixelIndex(indexes+x),function, number_parameters,parameters,exception)); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,FunctionImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l E n t r o p y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelEntropy() returns the entropy of one or more image channels. % % The format of the GetImageChannelEntropy method is: % % MagickBooleanType GetImageChannelEntropy(const Image *image, % const ChannelType channel,double *entropy,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o entropy: the average entropy of the selected channels. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageEntropy(const Image *image, double *entropy,ExceptionInfo *exception) { MagickBooleanType status; status=GetImageChannelEntropy(image,CompositeChannels,entropy,exception); return(status); } MagickExport MagickBooleanType GetImageChannelEntropy(const Image *image, const ChannelType channel,double *entropy,ExceptionInfo *exception) { ChannelStatistics *channel_statistics; size_t channels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageChannelStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); channels=0; channel_statistics[CompositeChannels].entropy=0.0; if ((channel & RedChannel) != 0) { channel_statistics[CompositeChannels].entropy+= channel_statistics[RedChannel].entropy; channels++; } if ((channel & GreenChannel) != 0) { channel_statistics[CompositeChannels].entropy+= channel_statistics[GreenChannel].entropy; channels++; } if ((channel & BlueChannel) != 0) { channel_statistics[CompositeChannels].entropy+= channel_statistics[BlueChannel].entropy; channels++; } if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) { channel_statistics[CompositeChannels].entropy+= channel_statistics[OpacityChannel].entropy; channels++; } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { channel_statistics[CompositeChannels].entropy+= channel_statistics[BlackChannel].entropy; channels++; } channel_statistics[CompositeChannels].entropy/=channels; *entropy=channel_statistics[CompositeChannels].entropy; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e C h a n n e l E x t r e m a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelExtrema() returns the extrema of one or more image channels. % % The format of the GetImageChannelExtrema method is: % % MagickBooleanType GetImageChannelExtrema(const Image *image, % const ChannelType channel,size_t *minima,size_t *maxima, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o minima: the minimum value in the channel. % % o maxima: the maximum value in the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageExtrema(const Image *image, size_t *minima,size_t *maxima,ExceptionInfo *exception) { MagickBooleanType status; status=GetImageChannelExtrema(image,CompositeChannels,minima,maxima, exception); return(status); } MagickExport MagickBooleanType GetImageChannelExtrema(const Image *image, const ChannelType channel,size_t *minima,size_t *maxima, ExceptionInfo *exception) { double max, min; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=GetImageChannelRange(image,channel,&min,&max,exception); *minima=(size_t) ceil(min-0.5); *maxima=(size_t) floor(max+0.5); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l K u r t o s i s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelKurtosis() returns the kurtosis and skewness of one or more % image channels. % % The format of the GetImageChannelKurtosis method is: % % MagickBooleanType GetImageChannelKurtosis(const Image *image, % const ChannelType channel,double *kurtosis,double *skewness, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o kurtosis: the kurtosis of the channel. % % o skewness: the skewness of the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageKurtosis(const Image *image, double *kurtosis,double *skewness,ExceptionInfo *exception) { MagickBooleanType status; status=GetImageChannelKurtosis(image,CompositeChannels,kurtosis,skewness, exception); return(status); } MagickExport MagickBooleanType GetImageChannelKurtosis(const Image *image, const ChannelType channel,double *kurtosis,double *skewness, ExceptionInfo *exception) { double area, mean, standard_deviation, sum_squares, sum_cubes, sum_fourth_power; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); *kurtosis=0.0; *skewness=0.0; area=0.0; mean=0.0; standard_deviation=0.0; sum_squares=0.0; sum_cubes=0.0; sum_fourth_power=0.0; for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) { mean+=GetPixelRed(p); sum_squares+=(double) GetPixelRed(p)*GetPixelRed(p); sum_cubes+=(double) GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p); sum_fourth_power+=(double) GetPixelRed(p)*GetPixelRed(p)* GetPixelRed(p)*GetPixelRed(p); area++; } if ((channel & GreenChannel) != 0) { mean+=GetPixelGreen(p); sum_squares+=(double) GetPixelGreen(p)*GetPixelGreen(p); sum_cubes+=(double) GetPixelGreen(p)*GetPixelGreen(p)* GetPixelGreen(p); sum_fourth_power+=(double) GetPixelGreen(p)*GetPixelGreen(p)* GetPixelGreen(p)*GetPixelGreen(p); area++; } if ((channel & BlueChannel) != 0) { mean+=GetPixelBlue(p); sum_squares+=(double) GetPixelBlue(p)*GetPixelBlue(p); sum_cubes+=(double) GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p); sum_fourth_power+=(double) GetPixelBlue(p)*GetPixelBlue(p)* GetPixelBlue(p)*GetPixelBlue(p); area++; } if ((channel & OpacityChannel) != 0) { mean+=GetPixelAlpha(p); sum_squares+=(double) GetPixelOpacity(p)*GetPixelAlpha(p); sum_cubes+=(double) GetPixelOpacity(p)*GetPixelAlpha(p)* GetPixelAlpha(p); sum_fourth_power+=(double) GetPixelAlpha(p)*GetPixelAlpha(p)* GetPixelAlpha(p)*GetPixelAlpha(p); area++; } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { double index; index=(double) GetPixelIndex(indexes+x); mean+=index; sum_squares+=index*index; sum_cubes+=index*index*index; sum_fourth_power+=index*index*index*index; area++; } p++; } } if (y < (ssize_t) image->rows) return(MagickFalse); if (area != 0.0) { mean/=area; sum_squares/=area; sum_cubes/=area; sum_fourth_power/=area; } standard_deviation=sqrt(sum_squares-(mean*mean)); if (standard_deviation != 0.0) { *kurtosis=sum_fourth_power-4.0*mean*sum_cubes+6.0*mean*mean*sum_squares- 3.0*mean*mean*mean*mean; *kurtosis/=standard_deviation*standard_deviation*standard_deviation* standard_deviation; *kurtosis-=3.0; *skewness=sum_cubes-3.0*mean*sum_squares+2.0*mean*mean*mean; *skewness/=standard_deviation*standard_deviation*standard_deviation; } return(y == (ssize_t) image->rows ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l M e a n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelMean() returns the mean and standard deviation of one or more % image channels. % % The format of the GetImageChannelMean method is: % % MagickBooleanType GetImageChannelMean(const Image *image, % const ChannelType channel,double *mean,double *standard_deviation, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o mean: the average value in the channel. % % o standard_deviation: the standard deviation of the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageMean(const Image *image,double *mean, double *standard_deviation,ExceptionInfo *exception) { MagickBooleanType status; status=GetImageChannelMean(image,CompositeChannels,mean,standard_deviation, exception); return(status); } MagickExport MagickBooleanType GetImageChannelMean(const Image *image, const ChannelType channel,double *mean,double *standard_deviation, ExceptionInfo *exception) { ChannelStatistics *channel_statistics; size_t channels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageChannelStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); channels=0; channel_statistics[CompositeChannels].mean=0.0; channel_statistics[CompositeChannels].standard_deviation=0.0; if ((channel & RedChannel) != 0) { channel_statistics[CompositeChannels].mean+= channel_statistics[RedChannel].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[RedChannel].standard_deviation; channels++; } if ((channel & GreenChannel) != 0) { channel_statistics[CompositeChannels].mean+= channel_statistics[GreenChannel].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[GreenChannel].standard_deviation; channels++; } if ((channel & BlueChannel) != 0) { channel_statistics[CompositeChannels].mean+= channel_statistics[BlueChannel].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[BlueChannel].standard_deviation; channels++; } if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) { channel_statistics[CompositeChannels].mean+= (QuantumRange-channel_statistics[OpacityChannel].mean); channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[OpacityChannel].standard_deviation; channels++; } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { channel_statistics[CompositeChannels].mean+= channel_statistics[BlackChannel].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[CompositeChannels].standard_deviation; channels++; } channel_statistics[CompositeChannels].mean/=channels; channel_statistics[CompositeChannels].standard_deviation/=channels; *mean=channel_statistics[CompositeChannels].mean; *standard_deviation=channel_statistics[CompositeChannels].standard_deviation; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l M o m e n t s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelMoments() returns the normalized moments of one or more image % channels. % % The format of the GetImageChannelMoments method is: % % ChannelMoments *GetImageChannelMoments(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport ChannelMoments *GetImageChannelMoments(const Image *image, ExceptionInfo *exception) { #define MaxNumberImageMoments 8 ChannelMoments *channel_moments; double M00[CompositeChannels+1], M01[CompositeChannels+1], M02[CompositeChannels+1], M03[CompositeChannels+1], M10[CompositeChannels+1], M11[CompositeChannels+1], M12[CompositeChannels+1], M20[CompositeChannels+1], M21[CompositeChannels+1], M22[CompositeChannels+1], M30[CompositeChannels+1]; MagickPixelPacket pixel; PointInfo centroid[CompositeChannels+1]; ssize_t channel, channels, y; size_t length; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); length=CompositeChannels+1UL; channel_moments=(ChannelMoments *) AcquireQuantumMemory(length, sizeof(*channel_moments)); if (channel_moments == (ChannelMoments *) NULL) return(channel_moments); (void) memset(channel_moments,0,length*sizeof(*channel_moments)); (void) memset(centroid,0,sizeof(centroid)); (void) memset(M00,0,sizeof(M00)); (void) memset(M01,0,sizeof(M01)); (void) memset(M02,0,sizeof(M02)); (void) memset(M03,0,sizeof(M03)); (void) memset(M10,0,sizeof(M10)); (void) memset(M11,0,sizeof(M11)); (void) memset(M12,0,sizeof(M12)); (void) memset(M20,0,sizeof(M20)); (void) memset(M21,0,sizeof(M21)); (void) memset(M22,0,sizeof(M22)); (void) memset(M30,0,sizeof(M30)); GetMagickPixelPacket(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; /* Compute center of mass (centroid). */ p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,p,indexes+x,&pixel); M00[RedChannel]+=QuantumScale*pixel.red; M10[RedChannel]+=x*QuantumScale*pixel.red; M01[RedChannel]+=y*QuantumScale*pixel.red; M00[GreenChannel]+=QuantumScale*pixel.green; M10[GreenChannel]+=x*QuantumScale*pixel.green; M01[GreenChannel]+=y*QuantumScale*pixel.green; M00[BlueChannel]+=QuantumScale*pixel.blue; M10[BlueChannel]+=x*QuantumScale*pixel.blue; M01[BlueChannel]+=y*QuantumScale*pixel.blue; if (image->matte != MagickFalse) { M00[OpacityChannel]+=QuantumScale*pixel.opacity; M10[OpacityChannel]+=x*QuantumScale*pixel.opacity; M01[OpacityChannel]+=y*QuantumScale*pixel.opacity; } if (image->colorspace == CMYKColorspace) { M00[IndexChannel]+=QuantumScale*pixel.index; M10[IndexChannel]+=x*QuantumScale*pixel.index; M01[IndexChannel]+=y*QuantumScale*pixel.index; } p++; } } for (channel=0; channel <= CompositeChannels; channel++) { /* Compute center of mass (centroid). */ if (M00[channel] < MagickEpsilon) { M00[channel]+=MagickEpsilon; centroid[channel].x=(double) image->columns/2.0; centroid[channel].y=(double) image->rows/2.0; continue; } M00[channel]+=MagickEpsilon; centroid[channel].x=M10[channel]/M00[channel]; centroid[channel].y=M01[channel]/M00[channel]; } for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; /* Compute the image moments. */ p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,p,indexes+x,&pixel); M11[RedChannel]+=(x-centroid[RedChannel].x)*(y- centroid[RedChannel].y)*QuantumScale*pixel.red; M20[RedChannel]+=(x-centroid[RedChannel].x)*(x- centroid[RedChannel].x)*QuantumScale*pixel.red; M02[RedChannel]+=(y-centroid[RedChannel].y)*(y- centroid[RedChannel].y)*QuantumScale*pixel.red; M21[RedChannel]+=(x-centroid[RedChannel].x)*(x- centroid[RedChannel].x)*(y-centroid[RedChannel].y)*QuantumScale* pixel.red; M12[RedChannel]+=(x-centroid[RedChannel].x)*(y- centroid[RedChannel].y)*(y-centroid[RedChannel].y)*QuantumScale* pixel.red; M22[RedChannel]+=(x-centroid[RedChannel].x)*(x- centroid[RedChannel].x)*(y-centroid[RedChannel].y)*(y- centroid[RedChannel].y)*QuantumScale*pixel.red; M30[RedChannel]+=(x-centroid[RedChannel].x)*(x- centroid[RedChannel].x)*(x-centroid[RedChannel].x)*QuantumScale* pixel.red; M03[RedChannel]+=(y-centroid[RedChannel].y)*(y- centroid[RedChannel].y)*(y-centroid[RedChannel].y)*QuantumScale* pixel.red; M11[GreenChannel]+=(x-centroid[GreenChannel].x)*(y- centroid[GreenChannel].y)*QuantumScale*pixel.green; M20[GreenChannel]+=(x-centroid[GreenChannel].x)*(x- centroid[GreenChannel].x)*QuantumScale*pixel.green; M02[GreenChannel]+=(y-centroid[GreenChannel].y)*(y- centroid[GreenChannel].y)*QuantumScale*pixel.green; M21[GreenChannel]+=(x-centroid[GreenChannel].x)*(x- centroid[GreenChannel].x)*(y-centroid[GreenChannel].y)*QuantumScale* pixel.green; M12[GreenChannel]+=(x-centroid[GreenChannel].x)*(y- centroid[GreenChannel].y)*(y-centroid[GreenChannel].y)*QuantumScale* pixel.green; M22[GreenChannel]+=(x-centroid[GreenChannel].x)*(x- centroid[GreenChannel].x)*(y-centroid[GreenChannel].y)*(y- centroid[GreenChannel].y)*QuantumScale*pixel.green; M30[GreenChannel]+=(x-centroid[GreenChannel].x)*(x- centroid[GreenChannel].x)*(x-centroid[GreenChannel].x)*QuantumScale* pixel.green; M03[GreenChannel]+=(y-centroid[GreenChannel].y)*(y- centroid[GreenChannel].y)*(y-centroid[GreenChannel].y)*QuantumScale* pixel.green; M11[BlueChannel]+=(x-centroid[BlueChannel].x)*(y- centroid[BlueChannel].y)*QuantumScale*pixel.blue; M20[BlueChannel]+=(x-centroid[BlueChannel].x)*(x- centroid[BlueChannel].x)*QuantumScale*pixel.blue; M02[BlueChannel]+=(y-centroid[BlueChannel].y)*(y- centroid[BlueChannel].y)*QuantumScale*pixel.blue; M21[BlueChannel]+=(x-centroid[BlueChannel].x)*(x- centroid[BlueChannel].x)*(y-centroid[BlueChannel].y)*QuantumScale* pixel.blue; M12[BlueChannel]+=(x-centroid[BlueChannel].x)*(y- centroid[BlueChannel].y)*(y-centroid[BlueChannel].y)*QuantumScale* pixel.blue; M22[BlueChannel]+=(x-centroid[BlueChannel].x)*(x- centroid[BlueChannel].x)*(y-centroid[BlueChannel].y)*(y- centroid[BlueChannel].y)*QuantumScale*pixel.blue; M30[BlueChannel]+=(x-centroid[BlueChannel].x)*(x- centroid[BlueChannel].x)*(x-centroid[BlueChannel].x)*QuantumScale* pixel.blue; M03[BlueChannel]+=(y-centroid[BlueChannel].y)*(y- centroid[BlueChannel].y)*(y-centroid[BlueChannel].y)*QuantumScale* pixel.blue; if (image->matte != MagickFalse) { M11[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(y- centroid[OpacityChannel].y)*QuantumScale*pixel.opacity; M20[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x- centroid[OpacityChannel].x)*QuantumScale*pixel.opacity; M02[OpacityChannel]+=(y-centroid[OpacityChannel].y)*(y- centroid[OpacityChannel].y)*QuantumScale*pixel.opacity; M21[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x- centroid[OpacityChannel].x)*(y-centroid[OpacityChannel].y)* QuantumScale*pixel.opacity; M12[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(y- centroid[OpacityChannel].y)*(y-centroid[OpacityChannel].y)* QuantumScale*pixel.opacity; M22[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x- centroid[OpacityChannel].x)*(y-centroid[OpacityChannel].y)*(y- centroid[OpacityChannel].y)*QuantumScale*pixel.opacity; M30[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x- centroid[OpacityChannel].x)*(x-centroid[OpacityChannel].x)* QuantumScale*pixel.opacity; M03[OpacityChannel]+=(y-centroid[OpacityChannel].y)*(y- centroid[OpacityChannel].y)*(y-centroid[OpacityChannel].y)* QuantumScale*pixel.opacity; } if (image->colorspace == CMYKColorspace) { M11[IndexChannel]+=(x-centroid[IndexChannel].x)*(y- centroid[IndexChannel].y)*QuantumScale*pixel.index; M20[IndexChannel]+=(x-centroid[IndexChannel].x)*(x- centroid[IndexChannel].x)*QuantumScale*pixel.index; M02[IndexChannel]+=(y-centroid[IndexChannel].y)*(y- centroid[IndexChannel].y)*QuantumScale*pixel.index; M21[IndexChannel]+=(x-centroid[IndexChannel].x)*(x- centroid[IndexChannel].x)*(y-centroid[IndexChannel].y)* QuantumScale*pixel.index; M12[IndexChannel]+=(x-centroid[IndexChannel].x)*(y- centroid[IndexChannel].y)*(y-centroid[IndexChannel].y)* QuantumScale*pixel.index; M22[IndexChannel]+=(x-centroid[IndexChannel].x)*(x- centroid[IndexChannel].x)*(y-centroid[IndexChannel].y)*(y- centroid[IndexChannel].y)*QuantumScale*pixel.index; M30[IndexChannel]+=(x-centroid[IndexChannel].x)*(x- centroid[IndexChannel].x)*(x-centroid[IndexChannel].x)* QuantumScale*pixel.index; M03[IndexChannel]+=(y-centroid[IndexChannel].y)*(y- centroid[IndexChannel].y)*(y-centroid[IndexChannel].y)* QuantumScale*pixel.index; } p++; } } channels=3; M00[CompositeChannels]+=(M00[RedChannel]+M00[GreenChannel]+M00[BlueChannel]); M01[CompositeChannels]+=(M01[RedChannel]+M01[GreenChannel]+M01[BlueChannel]); M02[CompositeChannels]+=(M02[RedChannel]+M02[GreenChannel]+M02[BlueChannel]); M03[CompositeChannels]+=(M03[RedChannel]+M03[GreenChannel]+M03[BlueChannel]); M10[CompositeChannels]+=(M10[RedChannel]+M10[GreenChannel]+M10[BlueChannel]); M11[CompositeChannels]+=(M11[RedChannel]+M11[GreenChannel]+M11[BlueChannel]); M12[CompositeChannels]+=(M12[RedChannel]+M12[GreenChannel]+M12[BlueChannel]); M20[CompositeChannels]+=(M20[RedChannel]+M20[GreenChannel]+M20[BlueChannel]); M21[CompositeChannels]+=(M21[RedChannel]+M21[GreenChannel]+M21[BlueChannel]); M22[CompositeChannels]+=(M22[RedChannel]+M22[GreenChannel]+M22[BlueChannel]); M30[CompositeChannels]+=(M30[RedChannel]+M30[GreenChannel]+M30[BlueChannel]); if (image->matte != MagickFalse) { channels+=1; M00[CompositeChannels]+=M00[OpacityChannel]; M01[CompositeChannels]+=M01[OpacityChannel]; M02[CompositeChannels]+=M02[OpacityChannel]; M03[CompositeChannels]+=M03[OpacityChannel]; M10[CompositeChannels]+=M10[OpacityChannel]; M11[CompositeChannels]+=M11[OpacityChannel]; M12[CompositeChannels]+=M12[OpacityChannel]; M20[CompositeChannels]+=M20[OpacityChannel]; M21[CompositeChannels]+=M21[OpacityChannel]; M22[CompositeChannels]+=M22[OpacityChannel]; M30[CompositeChannels]+=M30[OpacityChannel]; } if (image->colorspace == CMYKColorspace) { channels+=1; M00[CompositeChannels]+=M00[IndexChannel]; M01[CompositeChannels]+=M01[IndexChannel]; M02[CompositeChannels]+=M02[IndexChannel]; M03[CompositeChannels]+=M03[IndexChannel]; M10[CompositeChannels]+=M10[IndexChannel]; M11[CompositeChannels]+=M11[IndexChannel]; M12[CompositeChannels]+=M12[IndexChannel]; M20[CompositeChannels]+=M20[IndexChannel]; M21[CompositeChannels]+=M21[IndexChannel]; M22[CompositeChannels]+=M22[IndexChannel]; M30[CompositeChannels]+=M30[IndexChannel]; } M00[CompositeChannels]/=(double) channels; M01[CompositeChannels]/=(double) channels; M02[CompositeChannels]/=(double) channels; M03[CompositeChannels]/=(double) channels; M10[CompositeChannels]/=(double) channels; M11[CompositeChannels]/=(double) channels; M12[CompositeChannels]/=(double) channels; M20[CompositeChannels]/=(double) channels; M21[CompositeChannels]/=(double) channels; M22[CompositeChannels]/=(double) channels; M30[CompositeChannels]/=(double) channels; for (channel=0; channel <= CompositeChannels; channel++) { /* Compute elliptical angle, major and minor axes, eccentricity, & intensity. */ channel_moments[channel].centroid=centroid[channel]; channel_moments[channel].ellipse_axis.x=sqrt((2.0/M00[channel])* ((M20[channel]+M02[channel])+sqrt(4.0*M11[channel]*M11[channel]+ (M20[channel]-M02[channel])*(M20[channel]-M02[channel])))); channel_moments[channel].ellipse_axis.y=sqrt((2.0/M00[channel])* ((M20[channel]+M02[channel])-sqrt(4.0*M11[channel]*M11[channel]+ (M20[channel]-M02[channel])*(M20[channel]-M02[channel])))); channel_moments[channel].ellipse_angle=RadiansToDegrees(0.5*atan(2.0* M11[channel]/(M20[channel]-M02[channel]+MagickEpsilon))); if (fabs(M11[channel]) < MagickEpsilon) { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=0.0; } else if (M11[channel] < 0.0) { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=180.0; } else { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=0.0; } channel_moments[channel].ellipse_eccentricity=sqrt(1.0-( channel_moments[channel].ellipse_axis.y/ (channel_moments[channel].ellipse_axis.x+MagickEpsilon))); channel_moments[channel].ellipse_intensity=M00[channel]/ (MagickPI*channel_moments[channel].ellipse_axis.x* channel_moments[channel].ellipse_axis.y+MagickEpsilon); } for (channel=0; channel <= CompositeChannels; channel++) { /* Normalize image moments. */ M10[channel]=0.0; M01[channel]=0.0; M11[channel]/=pow(M00[channel],1.0+(1.0+1.0)/2.0); M20[channel]/=pow(M00[channel],1.0+(2.0+0.0)/2.0); M02[channel]/=pow(M00[channel],1.0+(0.0+2.0)/2.0); M21[channel]/=pow(M00[channel],1.0+(2.0+1.0)/2.0); M12[channel]/=pow(M00[channel],1.0+(1.0+2.0)/2.0); M22[channel]/=pow(M00[channel],1.0+(2.0+2.0)/2.0); M30[channel]/=pow(M00[channel],1.0+(3.0+0.0)/2.0); M03[channel]/=pow(M00[channel],1.0+(0.0+3.0)/2.0); M00[channel]=1.0; } for (channel=0; channel <= CompositeChannels; channel++) { /* Compute Hu invariant moments. */ channel_moments[channel].I[0]=M20[channel]+M02[channel]; channel_moments[channel].I[1]=(M20[channel]-M02[channel])* (M20[channel]-M02[channel])+4.0*M11[channel]*M11[channel]; channel_moments[channel].I[2]=(M30[channel]-3.0*M12[channel])* (M30[channel]-3.0*M12[channel])+(3.0*M21[channel]-M03[channel])* (3.0*M21[channel]-M03[channel]); channel_moments[channel].I[3]=(M30[channel]+M12[channel])* (M30[channel]+M12[channel])+(M21[channel]+M03[channel])* (M21[channel]+M03[channel]); channel_moments[channel].I[4]=(M30[channel]-3.0*M12[channel])* (M30[channel]+M12[channel])*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])* (M21[channel]+M03[channel]))+(3.0*M21[channel]-M03[channel])* (M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M21[channel]+M03[channel])* (M21[channel]+M03[channel])); channel_moments[channel].I[5]=(M20[channel]-M02[channel])* ((M30[channel]+M12[channel])*(M30[channel]+M12[channel])- (M21[channel]+M03[channel])*(M21[channel]+M03[channel]))+ 4.0*M11[channel]*(M30[channel]+M12[channel])*(M21[channel]+M03[channel]); channel_moments[channel].I[6]=(3.0*M21[channel]-M03[channel])* (M30[channel]+M12[channel])*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])* (M21[channel]+M03[channel]))-(M30[channel]-3*M12[channel])* (M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M21[channel]+M03[channel])* (M21[channel]+M03[channel])); channel_moments[channel].I[7]=M11[channel]*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M03[channel]+M21[channel])* (M03[channel]+M21[channel]))-(M20[channel]-M02[channel])* (M30[channel]+M12[channel])*(M03[channel]+M21[channel]); } if (y < (ssize_t) image->rows) channel_moments=(ChannelMoments *) RelinquishMagickMemory(channel_moments); return(channel_moments); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l P e r c e p t u a l H a s h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelPerceptualHash() returns the perceptual hash of one or more % image channels. % % The format of the GetImageChannelPerceptualHash method is: % % ChannelPerceptualHash *GetImageChannelPerceptualHash(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static inline double MagickLog10(const double x) { #define Log10Epsilon (1.0e-11) if (fabs(x) < Log10Epsilon) return(log10(Log10Epsilon)); return(log10(fabs(x))); } MagickExport ChannelPerceptualHash *GetImageChannelPerceptualHash( const Image *image,ExceptionInfo *exception) { ChannelMoments *moments; ChannelPerceptualHash *perceptual_hash; Image *hash_image; MagickBooleanType status; register ssize_t i; ssize_t channel; /* Blur then transform to sRGB colorspace. */ hash_image=BlurImage(image,0.0,1.0,exception); if (hash_image == (Image *) NULL) return((ChannelPerceptualHash *) NULL); hash_image->depth=8; status=TransformImageColorspace(hash_image,sRGBColorspace); if (status == MagickFalse) return((ChannelPerceptualHash *) NULL); moments=GetImageChannelMoments(hash_image,exception); hash_image=DestroyImage(hash_image); if (moments == (ChannelMoments *) NULL) return((ChannelPerceptualHash *) NULL); perceptual_hash=(ChannelPerceptualHash *) AcquireQuantumMemory( CompositeChannels+1UL,sizeof(*perceptual_hash)); if (perceptual_hash == (ChannelPerceptualHash *) NULL) return((ChannelPerceptualHash *) NULL); for (channel=0; channel <= CompositeChannels; channel++) for (i=0; i < MaximumNumberOfImageMoments; i++) perceptual_hash[channel].P[i]=(-MagickLog10(moments[channel].I[i])); moments=(ChannelMoments *) RelinquishMagickMemory(moments); /* Blur then transform to HCLp colorspace. */ hash_image=BlurImage(image,0.0,1.0,exception); if (hash_image == (Image *) NULL) { perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory( perceptual_hash); return((ChannelPerceptualHash *) NULL); } hash_image->depth=8; status=TransformImageColorspace(hash_image,HCLpColorspace); if (status == MagickFalse) { perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory( perceptual_hash); return((ChannelPerceptualHash *) NULL); } moments=GetImageChannelMoments(hash_image,exception); hash_image=DestroyImage(hash_image); if (moments == (ChannelMoments *) NULL) { perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory( perceptual_hash); return((ChannelPerceptualHash *) NULL); } for (channel=0; channel <= CompositeChannels; channel++) for (i=0; i < MaximumNumberOfImageMoments; i++) perceptual_hash[channel].Q[i]=(-MagickLog10(moments[channel].I[i])); moments=(ChannelMoments *) RelinquishMagickMemory(moments); return(perceptual_hash); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l R a n g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelRange() returns the range of one or more image channels. % % The format of the GetImageChannelRange method is: % % MagickBooleanType GetImageChannelRange(const Image *image, % const ChannelType channel,double *minima,double *maxima, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o minima: the minimum value in the channel. % % o maxima: the maximum value in the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageRange(const Image *image, double *minima,double *maxima,ExceptionInfo *exception) { return(GetImageChannelRange(image,CompositeChannels,minima,maxima,exception)); } MagickExport MagickBooleanType GetImageChannelRange(const Image *image, const ChannelType channel,double *minima,double *maxima, ExceptionInfo *exception) { MagickPixelPacket pixel; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); *maxima=(-MagickMaximumValue); *minima=MagickMaximumValue; GetMagickPixelPacket(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,p,indexes+x,&pixel); if ((channel & RedChannel) != 0) { if (pixel.red < *minima) *minima=(double) pixel.red; if (pixel.red > *maxima) *maxima=(double) pixel.red; } if ((channel & GreenChannel) != 0) { if (pixel.green < *minima) *minima=(double) pixel.green; if (pixel.green > *maxima) *maxima=(double) pixel.green; } if ((channel & BlueChannel) != 0) { if (pixel.blue < *minima) *minima=(double) pixel.blue; if (pixel.blue > *maxima) *maxima=(double) pixel.blue; } if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) { if ((QuantumRange-pixel.opacity) < *minima) *minima=(double) (QuantumRange-pixel.opacity); if ((QuantumRange-pixel.opacity) > *maxima) *maxima=(double) (QuantumRange-pixel.opacity); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { if ((double) pixel.index < *minima) *minima=(double) pixel.index; if ((double) pixel.index > *maxima) *maxima=(double) pixel.index; } p++; } } return(y == (ssize_t) image->rows ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l S t a t i s t i c s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelStatistics() returns statistics for each channel in the % image. The statistics include the channel depth, its minima, maxima, mean, % standard deviation, kurtosis and skewness. You can access the red channel % mean, for example, like this: % % channel_statistics=GetImageChannelStatistics(image,exception); % red_mean=channel_statistics[RedChannel].mean; % % Use MagickRelinquishMemory() to free the statistics buffer. % % The format of the GetImageChannelStatistics method is: % % ChannelStatistics *GetImageChannelStatistics(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport ChannelStatistics *GetImageChannelStatistics(const Image *image, ExceptionInfo *exception) { ChannelStatistics *channel_statistics; double area, standard_deviation; MagickPixelPacket number_bins, *histogram; QuantumAny range; register ssize_t i; size_t channels, depth, length; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); length=CompositeChannels+1UL; channel_statistics=(ChannelStatistics *) AcquireQuantumMemory(length, sizeof(*channel_statistics)); histogram=(MagickPixelPacket *) AcquireQuantumMemory(MaxMap+1U, sizeof(*histogram)); if ((channel_statistics == (ChannelStatistics *) NULL) || (histogram == (MagickPixelPacket *) NULL)) { if (histogram != (MagickPixelPacket *) NULL) histogram=(MagickPixelPacket *) RelinquishMagickMemory(histogram); if (channel_statistics != (ChannelStatistics *) NULL) channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(channel_statistics); } (void) memset(channel_statistics,0,length* sizeof(*channel_statistics)); for (i=0; i <= (ssize_t) CompositeChannels; i++) { channel_statistics[i].depth=1; channel_statistics[i].maxima=(-MagickMaximumValue); channel_statistics[i].minima=MagickMaximumValue; } (void) memset(histogram,0,(MaxMap+1U)*sizeof(*histogram)); (void) memset(&number_bins,0,sizeof(number_bins)); for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; /* Compute pixel statistics. */ p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; ) { if (channel_statistics[RedChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[RedChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelRed(p),range) == MagickFalse) { channel_statistics[RedChannel].depth++; continue; } } if (channel_statistics[GreenChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[GreenChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelGreen(p),range) == MagickFalse) { channel_statistics[GreenChannel].depth++; continue; } } if (channel_statistics[BlueChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[BlueChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelBlue(p),range) == MagickFalse) { channel_statistics[BlueChannel].depth++; continue; } } if (image->matte != MagickFalse) { if (channel_statistics[OpacityChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[OpacityChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelAlpha(p),range) == MagickFalse) { channel_statistics[OpacityChannel].depth++; continue; } } } if (image->colorspace == CMYKColorspace) { if (channel_statistics[BlackChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[BlackChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelIndex(indexes+x),range) == MagickFalse) { channel_statistics[BlackChannel].depth++; continue; } } } if ((double) GetPixelRed(p) < channel_statistics[RedChannel].minima) channel_statistics[RedChannel].minima=(double) GetPixelRed(p); if ((double) GetPixelRed(p) > channel_statistics[RedChannel].maxima) channel_statistics[RedChannel].maxima=(double) GetPixelRed(p); channel_statistics[RedChannel].sum+=GetPixelRed(p); channel_statistics[RedChannel].sum_squared+=(double) GetPixelRed(p)* GetPixelRed(p); channel_statistics[RedChannel].sum_cubed+=(double) GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p); channel_statistics[RedChannel].sum_fourth_power+=(double) GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p); if ((double) GetPixelGreen(p) < channel_statistics[GreenChannel].minima) channel_statistics[GreenChannel].minima=(double) GetPixelGreen(p); if ((double) GetPixelGreen(p) > channel_statistics[GreenChannel].maxima) channel_statistics[GreenChannel].maxima=(double) GetPixelGreen(p); channel_statistics[GreenChannel].sum+=GetPixelGreen(p); channel_statistics[GreenChannel].sum_squared+=(double) GetPixelGreen(p)* GetPixelGreen(p); channel_statistics[GreenChannel].sum_cubed+=(double) GetPixelGreen(p)* GetPixelGreen(p)*GetPixelGreen(p); channel_statistics[GreenChannel].sum_fourth_power+=(double) GetPixelGreen(p)*GetPixelGreen(p)*GetPixelGreen(p)*GetPixelGreen(p); if ((double) GetPixelBlue(p) < channel_statistics[BlueChannel].minima) channel_statistics[BlueChannel].minima=(double) GetPixelBlue(p); if ((double) GetPixelBlue(p) > channel_statistics[BlueChannel].maxima) channel_statistics[BlueChannel].maxima=(double) GetPixelBlue(p); channel_statistics[BlueChannel].sum+=GetPixelBlue(p); channel_statistics[BlueChannel].sum_squared+=(double) GetPixelBlue(p)* GetPixelBlue(p); channel_statistics[BlueChannel].sum_cubed+=(double) GetPixelBlue(p)* GetPixelBlue(p)*GetPixelBlue(p); channel_statistics[BlueChannel].sum_fourth_power+=(double) GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p); histogram[ScaleQuantumToMap(GetPixelRed(p))].red++; histogram[ScaleQuantumToMap(GetPixelGreen(p))].green++; histogram[ScaleQuantumToMap(GetPixelBlue(p))].blue++; if (image->matte != MagickFalse) { if ((double) GetPixelAlpha(p) < channel_statistics[OpacityChannel].minima) channel_statistics[OpacityChannel].minima=(double) GetPixelAlpha(p); if ((double) GetPixelAlpha(p) > channel_statistics[OpacityChannel].maxima) channel_statistics[OpacityChannel].maxima=(double) GetPixelAlpha(p); channel_statistics[OpacityChannel].sum+=GetPixelAlpha(p); channel_statistics[OpacityChannel].sum_squared+=(double) GetPixelAlpha(p)*GetPixelAlpha(p); channel_statistics[OpacityChannel].sum_cubed+=(double) GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p); channel_statistics[OpacityChannel].sum_fourth_power+=(double) GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p); histogram[ScaleQuantumToMap(GetPixelAlpha(p))].opacity++; } if (image->colorspace == CMYKColorspace) { if ((double) GetPixelIndex(indexes+x) < channel_statistics[BlackChannel].minima) channel_statistics[BlackChannel].minima=(double) GetPixelIndex(indexes+x); if ((double) GetPixelIndex(indexes+x) > channel_statistics[BlackChannel].maxima) channel_statistics[BlackChannel].maxima=(double) GetPixelIndex(indexes+x); channel_statistics[BlackChannel].sum+=GetPixelIndex(indexes+x); channel_statistics[BlackChannel].sum_squared+=(double) GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x); channel_statistics[BlackChannel].sum_cubed+=(double) GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x)* GetPixelIndex(indexes+x); channel_statistics[BlackChannel].sum_fourth_power+=(double) GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x)* GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x); histogram[ScaleQuantumToMap(GetPixelIndex(indexes+x))].index++; } x++; p++; } } for (i=0; i < (ssize_t) CompositeChannels; i++) { double area, mean, standard_deviation; /* Normalize pixel statistics. */ area=PerceptibleReciprocal((double) image->columns*image->rows); mean=channel_statistics[i].sum*area; channel_statistics[i].sum=mean; channel_statistics[i].sum_squared*=area; channel_statistics[i].sum_cubed*=area; channel_statistics[i].sum_fourth_power*=area; channel_statistics[i].mean=mean; channel_statistics[i].variance=channel_statistics[i].sum_squared; standard_deviation=sqrt(channel_statistics[i].variance-(mean*mean)); area=PerceptibleReciprocal((double) image->columns*image->rows-1.0)* ((double) image->columns*image->rows); standard_deviation=sqrt(area*standard_deviation*standard_deviation); channel_statistics[i].standard_deviation=standard_deviation; } for (i=0; i < (ssize_t) (MaxMap+1U); i++) { if (histogram[i].red > 0.0) number_bins.red++; if (histogram[i].green > 0.0) number_bins.green++; if (histogram[i].blue > 0.0) number_bins.blue++; if ((image->matte != MagickFalse) && (histogram[i].opacity > 0.0)) number_bins.opacity++; if ((image->colorspace == CMYKColorspace) && (histogram[i].index > 0.0)) number_bins.index++; } area=PerceptibleReciprocal((double) image->columns*image->rows); for (i=0; i < (ssize_t) (MaxMap+1U); i++) { /* Compute pixel entropy. */ histogram[i].red*=area; channel_statistics[RedChannel].entropy+=-histogram[i].red* MagickLog10(histogram[i].red)* PerceptibleReciprocal(MagickLog10((double) number_bins.red)); histogram[i].green*=area; channel_statistics[GreenChannel].entropy+=-histogram[i].green* MagickLog10(histogram[i].green)* PerceptibleReciprocal(MagickLog10((double) number_bins.green)); histogram[i].blue*=area; channel_statistics[BlueChannel].entropy+=-histogram[i].blue* MagickLog10(histogram[i].blue)* PerceptibleReciprocal(MagickLog10((double) number_bins.blue)); if (image->matte != MagickFalse) { histogram[i].opacity*=area; channel_statistics[OpacityChannel].entropy+=-histogram[i].opacity* MagickLog10(histogram[i].opacity)* PerceptibleReciprocal(MagickLog10((double) number_bins.opacity)); } if (image->colorspace == CMYKColorspace) { histogram[i].index*=area; channel_statistics[IndexChannel].entropy+=-histogram[i].index* MagickLog10(histogram[i].index)* PerceptibleReciprocal(MagickLog10((double) number_bins.index)); } } /* Compute overall statistics. */ for (i=0; i < (ssize_t) CompositeChannels; i++) { channel_statistics[CompositeChannels].depth=(size_t) EvaluateMax((double) channel_statistics[CompositeChannels].depth,(double) channel_statistics[i].depth); channel_statistics[CompositeChannels].minima=MagickMin( channel_statistics[CompositeChannels].minima, channel_statistics[i].minima); channel_statistics[CompositeChannels].maxima=EvaluateMax( channel_statistics[CompositeChannels].maxima, channel_statistics[i].maxima); channel_statistics[CompositeChannels].sum+=channel_statistics[i].sum; channel_statistics[CompositeChannels].sum_squared+= channel_statistics[i].sum_squared; channel_statistics[CompositeChannels].sum_cubed+= channel_statistics[i].sum_cubed; channel_statistics[CompositeChannels].sum_fourth_power+= channel_statistics[i].sum_fourth_power; channel_statistics[CompositeChannels].mean+=channel_statistics[i].mean; channel_statistics[CompositeChannels].variance+= channel_statistics[i].variance-channel_statistics[i].mean* channel_statistics[i].mean; standard_deviation=sqrt(channel_statistics[i].variance- (channel_statistics[i].mean*channel_statistics[i].mean)); area=PerceptibleReciprocal((double) image->columns*image->rows-1.0)* ((double) image->columns*image->rows); standard_deviation=sqrt(area*standard_deviation*standard_deviation); channel_statistics[CompositeChannels].standard_deviation=standard_deviation; channel_statistics[CompositeChannels].entropy+= channel_statistics[i].entropy; } channels=3; if (image->matte != MagickFalse) channels++; if (image->colorspace == CMYKColorspace) channels++; channel_statistics[CompositeChannels].sum/=channels; channel_statistics[CompositeChannels].sum_squared/=channels; channel_statistics[CompositeChannels].sum_cubed/=channels; channel_statistics[CompositeChannels].sum_fourth_power/=channels; channel_statistics[CompositeChannels].mean/=channels; channel_statistics[CompositeChannels].kurtosis/=channels; channel_statistics[CompositeChannels].skewness/=channels; channel_statistics[CompositeChannels].entropy/=channels; i=CompositeChannels; area=PerceptibleReciprocal((double) channels*image->columns*image->rows); channel_statistics[i].variance=channel_statistics[i].sum_squared; channel_statistics[i].mean=channel_statistics[i].sum; standard_deviation=sqrt(channel_statistics[i].variance- (channel_statistics[i].mean*channel_statistics[i].mean)); standard_deviation=sqrt(PerceptibleReciprocal((double) channels* image->columns*image->rows-1.0)*channels*image->columns*image->rows* standard_deviation*standard_deviation); channel_statistics[i].standard_deviation=standard_deviation; for (i=0; i <= (ssize_t) CompositeChannels; i++) { /* Compute kurtosis & skewness statistics. */ standard_deviation=PerceptibleReciprocal( channel_statistics[i].standard_deviation); channel_statistics[i].skewness=(channel_statistics[i].sum_cubed-3.0* channel_statistics[i].mean*channel_statistics[i].sum_squared+2.0* channel_statistics[i].mean*channel_statistics[i].mean* channel_statistics[i].mean)*(standard_deviation*standard_deviation* standard_deviation); channel_statistics[i].kurtosis=(channel_statistics[i].sum_fourth_power-4.0* channel_statistics[i].mean*channel_statistics[i].sum_cubed+6.0* channel_statistics[i].mean*channel_statistics[i].mean* channel_statistics[i].sum_squared-3.0*channel_statistics[i].mean* channel_statistics[i].mean*1.0*channel_statistics[i].mean* channel_statistics[i].mean)*(standard_deviation*standard_deviation* standard_deviation*standard_deviation)-3.0; } channel_statistics[CompositeChannels].mean=0.0; channel_statistics[CompositeChannels].standard_deviation=0.0; for (i=0; i < (ssize_t) CompositeChannels; i++) { channel_statistics[CompositeChannels].mean+= channel_statistics[i].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[i].standard_deviation; } channel_statistics[CompositeChannels].mean/=(double) channels; channel_statistics[CompositeChannels].standard_deviation/=(double) channels; histogram=(MagickPixelPacket *) RelinquishMagickMemory(histogram); if (y < (ssize_t) image->rows) channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(channel_statistics); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o l y n o m i a l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PolynomialImage() returns a new image where each pixel is the sum of the % pixels in the image sequence after applying its corresponding terms % (coefficient and degree pairs). % % The format of the PolynomialImage method is: % % Image *PolynomialImage(const Image *images,const size_t number_terms, % const double *terms,ExceptionInfo *exception) % Image *PolynomialImageChannel(const Image *images, % const size_t number_terms,const ChannelType channel, % const double *terms,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o channel: the channel. % % o number_terms: the number of terms in the list. The actual list length % is 2 x number_terms + 1 (the constant). % % o terms: the list of polynomial coefficients and degree pairs and a % constant. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *PolynomialImage(const Image *images, const size_t number_terms,const double *terms,ExceptionInfo *exception) { Image *polynomial_image; polynomial_image=PolynomialImageChannel(images,DefaultChannels,number_terms, terms,exception); return(polynomial_image); } MagickExport Image *PolynomialImageChannel(const Image *images, const ChannelType channel,const size_t number_terms,const double *terms, ExceptionInfo *exception) { #define PolynomialImageTag "Polynomial/Image" CacheView *polynomial_view; Image *image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket **magick_restrict polynomial_pixels, zero; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImageCanvas(images,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImage(image); return((Image *) NULL); } polynomial_pixels=AcquirePixelThreadSet(images); if (polynomial_pixels == (MagickPixelPacket **) NULL) { image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return((Image *) NULL); } /* Polynomial image pixels. */ status=MagickTrue; progress=0; GetMagickPixelPacket(images,&zero); polynomial_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict polynomial_indexes; register MagickPixelPacket *polynomial_pixel; register PixelPacket *magick_restrict q; register ssize_t i, x; size_t number_images; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(polynomial_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } polynomial_indexes=GetCacheViewAuthenticIndexQueue(polynomial_view); polynomial_pixel=polynomial_pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) polynomial_pixel[x]=zero; next=images; number_images=GetImageListLength(images); for (i=0; i < (ssize_t) number_images; i++) { register const IndexPacket *indexes; register const PixelPacket *p; if (i >= (ssize_t) number_terms) break; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) { image_view=DestroyCacheView(image_view); break; } indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { double coefficient, degree; coefficient=terms[i << 1]; degree=terms[(i << 1)+1]; if ((channel & RedChannel) != 0) polynomial_pixel[x].red+=coefficient*pow(QuantumScale*p->red,degree); if ((channel & GreenChannel) != 0) polynomial_pixel[x].green+=coefficient*pow(QuantumScale*p->green, degree); if ((channel & BlueChannel) != 0) polynomial_pixel[x].blue+=coefficient*pow(QuantumScale*p->blue, degree); if ((channel & OpacityChannel) != 0) polynomial_pixel[x].opacity+=coefficient*pow(QuantumScale* (QuantumRange-p->opacity),degree); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) polynomial_pixel[x].index+=coefficient*pow(QuantumScale*indexes[x], degree); p++; } image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].red)); SetPixelGreen(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].green)); SetPixelBlue(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].blue)); if (image->matte == MagickFalse) SetPixelOpacity(q,ClampToQuantum(QuantumRange-QuantumRange* polynomial_pixel[x].opacity)); else SetPixelAlpha(q,ClampToQuantum(QuantumRange-QuantumRange* polynomial_pixel[x].opacity)); if (image->colorspace == CMYKColorspace) SetPixelIndex(polynomial_indexes+x,ClampToQuantum(QuantumRange* polynomial_pixel[x].index)); q++; } if (SyncCacheViewAuthenticPixels(polynomial_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(images,PolynomialImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } polynomial_view=DestroyCacheView(polynomial_view); polynomial_pixels=DestroyPixelThreadSet(polynomial_pixels); if (status == MagickFalse) image=DestroyImage(image); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t a t i s t i c I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % StatisticImage() makes each pixel the min / max / median / mode / etc. of % the neighborhood of the specified width and height. % % The format of the StatisticImage method is: % % Image *StatisticImage(const Image *image,const StatisticType type, % const size_t width,const size_t height,ExceptionInfo *exception) % Image *StatisticImageChannel(const Image *image, % const ChannelType channel,const StatisticType type, % const size_t width,const size_t height,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the image channel. % % o type: the statistic type (median, mode, etc.). % % o width: the width of the pixel neighborhood. % % o height: the height of the pixel neighborhood. % % o exception: return any errors or warnings in this structure. % */ #define ListChannels 5 typedef struct _ListNode { size_t next[9], count, signature; } ListNode; typedef struct _SkipList { ssize_t level; ListNode *nodes; } SkipList; typedef struct _PixelList { size_t length, seed, signature; SkipList lists[ListChannels]; } PixelList; static PixelList *DestroyPixelList(PixelList *pixel_list) { register ssize_t i; if (pixel_list == (PixelList *) NULL) return((PixelList *) NULL); for (i=0; i < ListChannels; i++) if (pixel_list->lists[i].nodes != (ListNode *) NULL) pixel_list->lists[i].nodes=(ListNode *) RelinquishAlignedMemory( pixel_list->lists[i].nodes); pixel_list=(PixelList *) RelinquishMagickMemory(pixel_list); return(pixel_list); } static PixelList **DestroyPixelListThreadSet(PixelList **pixel_list) { register ssize_t i; assert(pixel_list != (PixelList **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixel_list[i] != (PixelList *) NULL) pixel_list[i]=DestroyPixelList(pixel_list[i]); pixel_list=(PixelList **) RelinquishMagickMemory(pixel_list); return(pixel_list); } static PixelList *AcquirePixelList(const size_t width,const size_t height) { PixelList *pixel_list; register ssize_t i; pixel_list=(PixelList *) AcquireMagickMemory(sizeof(*pixel_list)); if (pixel_list == (PixelList *) NULL) return(pixel_list); (void) memset((void *) pixel_list,0,sizeof(*pixel_list)); pixel_list->length=width*height; for (i=0; i < ListChannels; i++) { pixel_list->lists[i].nodes=(ListNode *) AcquireAlignedMemory(65537UL, sizeof(*pixel_list->lists[i].nodes)); if (pixel_list->lists[i].nodes == (ListNode *) NULL) return(DestroyPixelList(pixel_list)); (void) memset(pixel_list->lists[i].nodes,0,65537UL* sizeof(*pixel_list->lists[i].nodes)); } pixel_list->signature=MagickCoreSignature; return(pixel_list); } static PixelList **AcquirePixelListThreadSet(const size_t width, const size_t height) { PixelList **pixel_list; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixel_list=(PixelList **) AcquireQuantumMemory(number_threads, sizeof(*pixel_list)); if (pixel_list == (PixelList **) NULL) return((PixelList **) NULL); (void) memset(pixel_list,0,number_threads*sizeof(*pixel_list)); for (i=0; i < (ssize_t) number_threads; i++) { pixel_list[i]=AcquirePixelList(width,height); if (pixel_list[i] == (PixelList *) NULL) return(DestroyPixelListThreadSet(pixel_list)); } return(pixel_list); } static void AddNodePixelList(PixelList *pixel_list,const ssize_t channel, const size_t color) { register SkipList *list; register ssize_t level; size_t search, update[9]; /* Initialize the node. */ list=pixel_list->lists+channel; list->nodes[color].signature=pixel_list->signature; list->nodes[color].count=1; /* Determine where it belongs in the list. */ search=65536UL; for (level=list->level; level >= 0; level--) { while (list->nodes[search].next[level] < color) search=list->nodes[search].next[level]; update[level]=search; } /* Generate a pseudo-random level for this node. */ for (level=0; ; level++) { pixel_list->seed=(pixel_list->seed*42893621L)+1L; if ((pixel_list->seed & 0x300) != 0x300) break; } if (level > 8) level=8; if (level > (list->level+2)) level=list->level+2; /* If we're raising the list's level, link back to the root node. */ while (level > list->level) { list->level++; update[list->level]=65536UL; } /* Link the node into the skip-list. */ do { list->nodes[color].next[level]=list->nodes[update[level]].next[level]; list->nodes[update[level]].next[level]=color; } while (level-- > 0); } static void GetMaximumPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color, maximum; ssize_t count; unsigned short channels[ListChannels]; /* Find the maximum value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; maximum=list->nodes[color].next[0]; do { color=list->nodes[color].next[0]; if (color > maximum) maximum=color; count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); channels[channel]=(unsigned short) maximum; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetMeanPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { MagickRealType sum; register SkipList *list; register ssize_t channel; size_t color; ssize_t count; unsigned short channels[ListChannels]; /* Find the mean value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; sum=0.0; do { color=list->nodes[color].next[0]; sum+=(MagickRealType) list->nodes[color].count*color; count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; channels[channel]=(unsigned short) sum; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetMedianPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color; ssize_t count; unsigned short channels[ListChannels]; /* Find the median value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; do { color=list->nodes[color].next[0]; count+=list->nodes[color].count; } while (count <= (ssize_t) (pixel_list->length >> 1)); channels[channel]=(unsigned short) color; } GetMagickPixelPacket((const Image *) NULL,pixel); pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetMinimumPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color, minimum; ssize_t count; unsigned short channels[ListChannels]; /* Find the minimum value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; count=0; color=65536UL; minimum=list->nodes[color].next[0]; do { color=list->nodes[color].next[0]; if (color < minimum) minimum=color; count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); channels[channel]=(unsigned short) minimum; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetModePixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color, max_count, mode; ssize_t count; unsigned short channels[5]; /* Make each pixel the 'predominant color' of the specified neighborhood. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; mode=color; max_count=list->nodes[mode].count; count=0; do { color=list->nodes[color].next[0]; if (list->nodes[color].count > max_count) { mode=color; max_count=list->nodes[mode].count; } count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); channels[channel]=(unsigned short) mode; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetNonpeakPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color, next, previous; ssize_t count; unsigned short channels[5]; /* Finds the non peak value for each of the colors. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; next=list->nodes[color].next[0]; count=0; do { previous=color; color=next; next=list->nodes[color].next[0]; count+=list->nodes[color].count; } while (count <= (ssize_t) (pixel_list->length >> 1)); if ((previous == 65536UL) && (next != 65536UL)) color=next; else if ((previous != 65536UL) && (next == 65536UL)) color=previous; channels[channel]=(unsigned short) color; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetRootMeanSquarePixelList(PixelList *pixel_list, MagickPixelPacket *pixel) { MagickRealType sum; register SkipList *list; register ssize_t channel; size_t color; ssize_t count; unsigned short channels[ListChannels]; /* Find the root mean square value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; sum=0.0; do { color=list->nodes[color].next[0]; sum+=(MagickRealType) (list->nodes[color].count*color*color); count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; channels[channel]=(unsigned short) sqrt(sum); } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetStandardDeviationPixelList(PixelList *pixel_list, MagickPixelPacket *pixel) { MagickRealType sum, sum_squared; register SkipList *list; register ssize_t channel; size_t color; ssize_t count; unsigned short channels[ListChannels]; /* Find the standard-deviation value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; sum=0.0; sum_squared=0.0; do { register ssize_t i; color=list->nodes[color].next[0]; sum+=(MagickRealType) list->nodes[color].count*color; for (i=0; i < (ssize_t) list->nodes[color].count; i++) sum_squared+=((MagickRealType) color)*((MagickRealType) color); count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; sum_squared/=pixel_list->length; channels[channel]=(unsigned short) sqrt(sum_squared-(sum*sum)); } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static inline void InsertPixelList(const Image *image,const PixelPacket *pixel, const IndexPacket *indexes,PixelList *pixel_list) { size_t signature; unsigned short index; index=ScaleQuantumToShort(GetPixelRed(pixel)); signature=pixel_list->lists[0].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[0].nodes[index].count++; else AddNodePixelList(pixel_list,0,index); index=ScaleQuantumToShort(GetPixelGreen(pixel)); signature=pixel_list->lists[1].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[1].nodes[index].count++; else AddNodePixelList(pixel_list,1,index); index=ScaleQuantumToShort(GetPixelBlue(pixel)); signature=pixel_list->lists[2].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[2].nodes[index].count++; else AddNodePixelList(pixel_list,2,index); index=ScaleQuantumToShort(GetPixelOpacity(pixel)); signature=pixel_list->lists[3].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[3].nodes[index].count++; else AddNodePixelList(pixel_list,3,index); if (image->colorspace == CMYKColorspace) index=ScaleQuantumToShort(GetPixelIndex(indexes)); signature=pixel_list->lists[4].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[4].nodes[index].count++; else AddNodePixelList(pixel_list,4,index); } static void ResetPixelList(PixelList *pixel_list) { int level; register ListNode *root; register SkipList *list; register ssize_t channel; /* Reset the skip-list. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; root=list->nodes+65536UL; list->level=0; for (level=0; level < 9; level++) root->next[level]=65536UL; } pixel_list->seed=pixel_list->signature++; } MagickExport Image *StatisticImage(const Image *image,const StatisticType type, const size_t width,const size_t height,ExceptionInfo *exception) { Image *statistic_image; statistic_image=StatisticImageChannel(image,DefaultChannels,type,width, height,exception); return(statistic_image); } MagickExport Image *StatisticImageChannel(const Image *image, const ChannelType channel,const StatisticType type,const size_t width, const size_t height,ExceptionInfo *exception) { #define StatisticImageTag "Statistic/Image" CacheView *image_view, *statistic_view; Image *statistic_image; MagickBooleanType status; MagickOffsetType progress; PixelList **magick_restrict pixel_list; size_t neighbor_height, neighbor_width; ssize_t y; /* Initialize statistics image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); statistic_image=CloneImage(image,0,0,MagickTrue,exception); if (statistic_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(statistic_image,DirectClass) == MagickFalse) { InheritException(exception,&statistic_image->exception); statistic_image=DestroyImage(statistic_image); return((Image *) NULL); } neighbor_width=width == 0 ? GetOptimalKernelWidth2D((double) width,0.5) : width; neighbor_height=height == 0 ? GetOptimalKernelWidth2D((double) height,0.5) : height; pixel_list=AcquirePixelListThreadSet(neighbor_width,neighbor_height); if (pixel_list == (PixelList **) NULL) { statistic_image=DestroyImage(statistic_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Make each pixel the min / max / median / mode / etc. of the neighborhood. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); statistic_view=AcquireAuthenticCacheView(statistic_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,statistic_image,statistic_image->rows,1) #endif for (y=0; y < (ssize_t) statistic_image->rows; y++) { const int id = GetOpenMPThreadId(); register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict statistic_indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) neighbor_width/2L),y- (ssize_t) (neighbor_height/2L),image->columns+neighbor_width, neighbor_height,exception); q=QueueCacheViewAuthenticPixels(statistic_view,0,y,statistic_image->columns, 1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); statistic_indexes=GetCacheViewAuthenticIndexQueue(statistic_view); for (x=0; x < (ssize_t) statistic_image->columns; x++) { MagickPixelPacket pixel; register const IndexPacket *magick_restrict s; register const PixelPacket *magick_restrict r; register ssize_t u, v; r=p; s=indexes+x; ResetPixelList(pixel_list[id]); for (v=0; v < (ssize_t) neighbor_height; v++) { for (u=0; u < (ssize_t) neighbor_width; u++) InsertPixelList(image,r+u,s+u,pixel_list[id]); r+=image->columns+neighbor_width; s+=image->columns+neighbor_width; } GetMagickPixelPacket(image,&pixel); SetMagickPixelPacket(image,p+neighbor_width*neighbor_height/2,indexes+x+ neighbor_width*neighbor_height/2,&pixel); switch (type) { case GradientStatistic: { MagickPixelPacket maximum, minimum; GetMinimumPixelList(pixel_list[id],&pixel); minimum=pixel; GetMaximumPixelList(pixel_list[id],&pixel); maximum=pixel; pixel.red=MagickAbsoluteValue(maximum.red-minimum.red); pixel.green=MagickAbsoluteValue(maximum.green-minimum.green); pixel.blue=MagickAbsoluteValue(maximum.blue-minimum.blue); pixel.opacity=MagickAbsoluteValue(maximum.opacity-minimum.opacity); if (image->colorspace == CMYKColorspace) pixel.index=MagickAbsoluteValue(maximum.index-minimum.index); break; } case MaximumStatistic: { GetMaximumPixelList(pixel_list[id],&pixel); break; } case MeanStatistic: { GetMeanPixelList(pixel_list[id],&pixel); break; } case MedianStatistic: default: { GetMedianPixelList(pixel_list[id],&pixel); break; } case MinimumStatistic: { GetMinimumPixelList(pixel_list[id],&pixel); break; } case ModeStatistic: { GetModePixelList(pixel_list[id],&pixel); break; } case NonpeakStatistic: { GetNonpeakPixelList(pixel_list[id],&pixel); break; } case RootMeanSquareStatistic: { GetRootMeanSquarePixelList(pixel_list[id],&pixel); break; } case StandardDeviationStatistic: { GetStandardDeviationPixelList(pixel_list[id],&pixel); break; } } if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(pixel.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(pixel.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(pixel.blue)); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,ClampToQuantum(pixel.opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(statistic_indexes+x,ClampToQuantum(pixel.index)); p++; q++; } if (SyncCacheViewAuthenticPixels(statistic_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,StatisticImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } statistic_view=DestroyCacheView(statistic_view); image_view=DestroyCacheView(image_view); pixel_list=DestroyPixelListThreadSet(pixel_list); if (status == MagickFalse) statistic_image=DestroyImage(statistic_image); return(statistic_image); }
null
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS TTTTT AAA TTTTT IIIII SSSSS TTTTT IIIII CCCC % % SS T A A T I SS T I C % % SSS T AAAAA T I SSS T I C % % SS T A A T I SS T I C % % SSSSS T A A T IIIII SSSSS T IIIII CCCC % % % % % % MagickCore Image Statistical Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/accelerate-private.h" #include "magick/animate.h" #include "magick/animate.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/cache-private.h" #include "magick/cache-view.h" #include "magick/client.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/composite.h" #include "magick/composite-private.h" #include "magick/compress.h" #include "magick/constitute.h" #include "magick/deprecate.h" #include "magick/display.h" #include "magick/draw.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/gem.h" #include "magick/geometry.h" #include "magick/list.h" #include "magick/image-private.h" #include "magick/magic.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/paint.h" #include "magick/pixel-private.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/quantize.h" #include "magick/random_.h" #include "magick/random-private.h" #include "magick/resource_.h" #include "magick/segment.h" #include "magick/semaphore.h" #include "magick/signature-private.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/thread-private.h" #include "magick/timer.h" #include "magick/utility.h" #include "magick/version.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E v a l u a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EvaluateImage() applies a value to the image with an arithmetic, relational, % or logical operator to an image. Use these operations to lighten or darken % an image, to increase or decrease contrast in an image, or to produce the % "negative" of an image. % % The format of the EvaluateImageChannel method is: % % MagickBooleanType EvaluateImage(Image *image, % const MagickEvaluateOperator op,const double value, % ExceptionInfo *exception) % MagickBooleanType EvaluateImages(Image *images, % const MagickEvaluateOperator op,const double value, % ExceptionInfo *exception) % MagickBooleanType EvaluateImageChannel(Image *image, % const ChannelType channel,const MagickEvaluateOperator op, % const double value,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o op: A channel op. % % o value: A value value. % % o exception: return any errors or warnings in this structure. % */ static MagickPixelPacket **DestroyPixelThreadSet(MagickPixelPacket **pixels) { register ssize_t i; assert(pixels != (MagickPixelPacket **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixels[i] != (MagickPixelPacket *) NULL) pixels[i]=(MagickPixelPacket *) RelinquishMagickMemory(pixels[i]); pixels=(MagickPixelPacket **) RelinquishMagickMemory(pixels); return(pixels); } static MagickPixelPacket **AcquirePixelThreadSet(const Image *images) { const Image *next; MagickPixelPacket **pixels; register ssize_t i, j; size_t columns, rows; rows=MagickMax(GetImageListLength(images), (size_t) GetMagickResourceLimit(ThreadResource)); pixels=(MagickPixelPacket **) AcquireQuantumMemory(rows,sizeof(*pixels)); if (pixels == (MagickPixelPacket **) NULL) return((MagickPixelPacket **) NULL); columns=images->columns; for (next=images; next != (Image *) NULL; next=next->next) columns=MagickMax(next->columns,columns); for (i=0; i < (ssize_t) rows; i++) { pixels[i]=(MagickPixelPacket *) AcquireQuantumMemory(columns, sizeof(**pixels)); if (pixels[i] == (MagickPixelPacket *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) columns; j++) GetMagickPixelPacket(images,&pixels[i][j]); } return(pixels); } static inline double EvaluateMax(const double x,const double y) { if (x > y) return(x); return(y); } #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int IntensityCompare(const void *x,const void *y) { const MagickPixelPacket *color_1, *color_2; int intensity; color_1=(const MagickPixelPacket *) x; color_2=(const MagickPixelPacket *) y; intensity=(int) MagickPixelIntensity(color_2)-(int) MagickPixelIntensity(color_1); return(intensity); } #if defined(__cplusplus) || defined(c_plusplus) } #endif static MagickRealType ApplyEvaluateOperator(RandomInfo *random_info, const Quantum pixel,const MagickEvaluateOperator op, const MagickRealType value) { MagickRealType result; result=0.0; switch (op) { case UndefinedEvaluateOperator: break; case AbsEvaluateOperator: { result=(MagickRealType) fabs((double) (pixel+value)); break; } case AddEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case AddModulusEvaluateOperator: { /* This returns a 'floored modulus' of the addition which is a positive result. It differs from % or fmod() which returns a 'truncated modulus' result, where floor() is replaced by trunc() and could return a negative result (which is clipped). */ result=pixel+value; result-=(QuantumRange+1.0)*floor((double) result/(QuantumRange+1.0)); break; } case AndEvaluateOperator: { result=(MagickRealType) ((size_t) pixel & (size_t) (value+0.5)); break; } case CosineEvaluateOperator: { result=(MagickRealType) (QuantumRange*(0.5*cos((double) (2.0*MagickPI* QuantumScale*pixel*value))+0.5)); break; } case DivideEvaluateOperator: { result=pixel/(value == 0.0 ? 1.0 : value); break; } case ExponentialEvaluateOperator: { result=(MagickRealType) (QuantumRange*exp((double) (value*QuantumScale* pixel))); break; } case GaussianNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, GaussianNoise,value); break; } case ImpulseNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, ImpulseNoise,value); break; } case LaplacianNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, LaplacianNoise,value); break; } case LeftShiftEvaluateOperator: { result=(MagickRealType) ((size_t) pixel << (size_t) (value+0.5)); break; } case LogEvaluateOperator: { if ((QuantumScale*pixel) >= MagickEpsilon) result=(MagickRealType) (QuantumRange*log((double) (QuantumScale*value* pixel+1.0))/log((double) (value+1.0))); break; } case MaxEvaluateOperator: { result=(MagickRealType) EvaluateMax((double) pixel,value); break; } case MeanEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case MedianEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case MinEvaluateOperator: { result=(MagickRealType) MagickMin((double) pixel,value); break; } case MultiplicativeNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, MultiplicativeGaussianNoise,value); break; } case MultiplyEvaluateOperator: { result=(MagickRealType) (value*pixel); break; } case OrEvaluateOperator: { result=(MagickRealType) ((size_t) pixel | (size_t) (value+0.5)); break; } case PoissonNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, PoissonNoise,value); break; } case PowEvaluateOperator: { result=(MagickRealType) (QuantumRange*pow((double) (QuantumScale*pixel), (double) value)); break; } case RightShiftEvaluateOperator: { result=(MagickRealType) ((size_t) pixel >> (size_t) (value+0.5)); break; } case RootMeanSquareEvaluateOperator: { result=(MagickRealType) (pixel*pixel+value); break; } case SetEvaluateOperator: { result=value; break; } case SineEvaluateOperator: { result=(MagickRealType) (QuantumRange*(0.5*sin((double) (2.0*MagickPI* QuantumScale*pixel*value))+0.5)); break; } case SubtractEvaluateOperator: { result=(MagickRealType) (pixel-value); break; } case SumEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case ThresholdEvaluateOperator: { result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 : QuantumRange); break; } case ThresholdBlackEvaluateOperator: { result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 : pixel); break; } case ThresholdWhiteEvaluateOperator: { result=(MagickRealType) (((MagickRealType) pixel > value) ? QuantumRange : pixel); break; } case UniformNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, UniformNoise,value); break; } case XorEvaluateOperator: { result=(MagickRealType) ((size_t) pixel ^ (size_t) (value+0.5)); break; } } return(result); } static Image *AcquireImageCanvas(const Image *images,ExceptionInfo *exception) { const Image *p, *q; size_t columns, number_channels, rows; q=images; columns=images->columns; rows=images->rows; number_channels=0; for (p=images; p != (Image *) NULL; p=p->next) { size_t channels; channels=3; if (p->matte != MagickFalse) channels+=1; if (p->colorspace == CMYKColorspace) channels+=1; if (channels > number_channels) { number_channels=channels; q=p; } if (p->columns > columns) columns=p->columns; if (p->rows > rows) rows=p->rows; } return(CloneImage(q,columns,rows,MagickTrue,exception)); } MagickExport MagickBooleanType EvaluateImage(Image *image, const MagickEvaluateOperator op,const double value,ExceptionInfo *exception) { MagickBooleanType status; status=EvaluateImageChannel(image,CompositeChannels,op,value,exception); return(status); } MagickExport Image *EvaluateImages(const Image *images, const MagickEvaluateOperator op,ExceptionInfo *exception) { #define EvaluateImageTag "Evaluate/Image" CacheView *evaluate_view; Image *image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket **magick_restrict evaluate_pixels, zero; RandomInfo **magick_restrict random_info; size_t number_images; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImageCanvas(images,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImage(image); return((Image *) NULL); } evaluate_pixels=AcquirePixelThreadSet(images); if (evaluate_pixels == (MagickPixelPacket **) NULL) { image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return((Image *) NULL); } /* Evaluate image pixels. */ status=MagickTrue; progress=0; number_images=GetImageListLength(images); GetMagickPixelPacket(images,&zero); random_info=AcquireRandomInfoThreadSet(); evaluate_view=AcquireAuthenticCacheView(image,exception); if (op == MedianEvaluateOperator) { #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,images,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict evaluate_indexes; register MagickPixelPacket *evaluate_pixel; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } evaluate_indexes=GetCacheViewAuthenticIndexQueue(evaluate_view); evaluate_pixel=evaluate_pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) number_images; i++) evaluate_pixel[i]=zero; next=images; for (i=0; i < (ssize_t) number_images; i++) { register const IndexPacket *indexes; register const PixelPacket *p; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,x,y,1,1,exception); if (p == (const PixelPacket *) NULL) { image_view=DestroyCacheView(image_view); break; } indexes=GetCacheViewVirtualIndexQueue(image_view); evaluate_pixel[i].red=ApplyEvaluateOperator(random_info[id], GetPixelRed(p),op,evaluate_pixel[i].red); evaluate_pixel[i].green=ApplyEvaluateOperator(random_info[id], GetPixelGreen(p),op,evaluate_pixel[i].green); evaluate_pixel[i].blue=ApplyEvaluateOperator(random_info[id], GetPixelBlue(p),op,evaluate_pixel[i].blue); evaluate_pixel[i].opacity=ApplyEvaluateOperator(random_info[id], GetPixelAlpha(p),op,evaluate_pixel[i].opacity); if (image->colorspace == CMYKColorspace) evaluate_pixel[i].index=ApplyEvaluateOperator(random_info[id], *indexes,op,evaluate_pixel[i].index); image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } qsort((void *) evaluate_pixel,number_images,sizeof(*evaluate_pixel), IntensityCompare); SetPixelRed(q,ClampToQuantum(evaluate_pixel[i/2].red)); SetPixelGreen(q,ClampToQuantum(evaluate_pixel[i/2].green)); SetPixelBlue(q,ClampToQuantum(evaluate_pixel[i/2].blue)); SetPixelAlpha(q,ClampToQuantum(evaluate_pixel[i/2].opacity)); if (image->colorspace == CMYKColorspace) SetPixelIndex(evaluate_indexes+i,ClampToQuantum( evaluate_pixel[i/2].index)); q++; } if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,EvaluateImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } else { #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,images,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict evaluate_indexes; register ssize_t i, x; register MagickPixelPacket *evaluate_pixel; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } evaluate_indexes=GetCacheViewAuthenticIndexQueue(evaluate_view); evaluate_pixel=evaluate_pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) evaluate_pixel[x]=zero; next=images; for (i=0; i < (ssize_t) number_images; i++) { register const IndexPacket *indexes; register const PixelPacket *p; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1, exception); if (p == (const PixelPacket *) NULL) { image_view=DestroyCacheView(image_view); break; } indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { evaluate_pixel[x].red=ApplyEvaluateOperator(random_info[id], GetPixelRed(p),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].red); evaluate_pixel[x].green=ApplyEvaluateOperator(random_info[id], GetPixelGreen(p),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].green); evaluate_pixel[x].blue=ApplyEvaluateOperator(random_info[id], GetPixelBlue(p),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].blue); evaluate_pixel[x].opacity=ApplyEvaluateOperator(random_info[id], GetPixelAlpha(p),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].opacity); if (image->colorspace == CMYKColorspace) evaluate_pixel[x].index=ApplyEvaluateOperator(random_info[id], GetPixelIndex(indexes+x),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].index); p++; } image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } if (op == MeanEvaluateOperator) for (x=0; x < (ssize_t) image->columns; x++) { evaluate_pixel[x].red/=number_images; evaluate_pixel[x].green/=number_images; evaluate_pixel[x].blue/=number_images; evaluate_pixel[x].opacity/=number_images; evaluate_pixel[x].index/=number_images; } if (op == RootMeanSquareEvaluateOperator) for (x=0; x < (ssize_t) image->columns; x++) { evaluate_pixel[x].red=sqrt((double) evaluate_pixel[x].red/ number_images); evaluate_pixel[x].green=sqrt((double) evaluate_pixel[x].green/ number_images); evaluate_pixel[x].blue=sqrt((double) evaluate_pixel[x].blue/ number_images); evaluate_pixel[x].opacity=sqrt((double) evaluate_pixel[x].opacity/ number_images); evaluate_pixel[x].index=sqrt((double) evaluate_pixel[x].index/ number_images); } if (op == MultiplyEvaluateOperator) for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; for (j=0; j < (ssize_t) (number_images-1); j++) { evaluate_pixel[x].red*=(MagickRealType) QuantumScale; evaluate_pixel[x].green*=(MagickRealType) QuantumScale; evaluate_pixel[x].blue*=(MagickRealType) QuantumScale; evaluate_pixel[x].opacity*=(MagickRealType) QuantumScale; evaluate_pixel[x].index*=(MagickRealType) QuantumScale; } } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ClampToQuantum(evaluate_pixel[x].red)); SetPixelGreen(q,ClampToQuantum(evaluate_pixel[x].green)); SetPixelBlue(q,ClampToQuantum(evaluate_pixel[x].blue)); SetPixelAlpha(q,ClampToQuantum(evaluate_pixel[x].opacity)); if (image->colorspace == CMYKColorspace) SetPixelIndex(evaluate_indexes+x,ClampToQuantum( evaluate_pixel[x].index)); q++; } if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(images,EvaluateImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } evaluate_view=DestroyCacheView(evaluate_view); evaluate_pixels=DestroyPixelThreadSet(evaluate_pixels); random_info=DestroyRandomInfoThreadSet(random_info); if (status == MagickFalse) image=DestroyImage(image); return(image); } MagickExport MagickBooleanType EvaluateImageChannel(Image *image, const ChannelType channel,const MagickEvaluateOperator op,const double value, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); return(MagickFalse); } status=MagickTrue; progress=0; random_info=AcquireRandomInfoThreadSet(); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType result; if ((channel & RedChannel) != 0) { result=ApplyEvaluateOperator(random_info[id],GetPixelRed(q),op,value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelRed(q,ClampToQuantum(result)); } if ((channel & GreenChannel) != 0) { result=ApplyEvaluateOperator(random_info[id],GetPixelGreen(q),op, value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelGreen(q,ClampToQuantum(result)); } if ((channel & BlueChannel) != 0) { result=ApplyEvaluateOperator(random_info[id],GetPixelBlue(q),op, value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelBlue(q,ClampToQuantum(result)); } if ((channel & OpacityChannel) != 0) { if (image->matte == MagickFalse) { result=ApplyEvaluateOperator(random_info[id],GetPixelOpacity(q), op,value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelOpacity(q,ClampToQuantum(result)); } else { result=ApplyEvaluateOperator(random_info[id],GetPixelAlpha(q), op,value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelAlpha(q,ClampToQuantum(result)); } } if (((channel & IndexChannel) != 0) && (indexes != (IndexPacket *) NULL)) { result=ApplyEvaluateOperator(random_info[id],GetPixelIndex(indexes+x), op,value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelIndex(indexes+x,ClampToQuantum(result)); } q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,EvaluateImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F u n c t i o n I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FunctionImage() applies a value to the image with an arithmetic, relational, % or logical operator to an image. Use these operations to lighten or darken % an image, to increase or decrease contrast in an image, or to produce the % "negative" of an image. % % The format of the FunctionImageChannel method is: % % MagickBooleanType FunctionImage(Image *image, % const MagickFunction function,const ssize_t number_parameters, % const double *parameters,ExceptionInfo *exception) % MagickBooleanType FunctionImageChannel(Image *image, % const ChannelType channel,const MagickFunction function, % const ssize_t number_parameters,const double *argument, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o function: A channel function. % % o parameters: one or more parameters. % % o exception: return any errors or warnings in this structure. % */ static Quantum ApplyFunction(Quantum pixel,const MagickFunction function, const size_t number_parameters,const double *parameters, ExceptionInfo *exception) { MagickRealType result; register ssize_t i; (void) exception; result=0.0; switch (function) { case PolynomialFunction: { /* * Polynomial * Parameters: polynomial constants, highest to lowest order * For example: c0*x^3 + c1*x^2 + c2*x + c3 */ result=0.0; for (i=0; i < (ssize_t) number_parameters; i++) result=result*QuantumScale*pixel + parameters[i]; result*=QuantumRange; break; } case SinusoidFunction: { /* Sinusoid Function * Parameters: Freq, Phase, Ampl, bias */ double freq,phase,ampl,bias; freq = ( number_parameters >= 1 ) ? parameters[0] : 1.0; phase = ( number_parameters >= 2 ) ? parameters[1] : 0.0; ampl = ( number_parameters >= 3 ) ? parameters[2] : 0.5; bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5; result=(MagickRealType) (QuantumRange*(ampl*sin((double) (2.0*MagickPI* (freq*QuantumScale*pixel + phase/360.0) )) + bias ) ); break; } case ArcsinFunction: { /* Arcsin Function (peged at range limits for invalid results) * Parameters: Width, Center, Range, Bias */ double width,range,center,bias; width = ( number_parameters >= 1 ) ? parameters[0] : 1.0; center = ( number_parameters >= 2 ) ? parameters[1] : 0.5; range = ( number_parameters >= 3 ) ? parameters[2] : 1.0; bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5; result = 2.0/width*(QuantumScale*pixel - center); if ( result <= -1.0 ) result = bias - range/2.0; else if ( result >= 1.0 ) result = bias + range/2.0; else result=(MagickRealType) (range/MagickPI*asin((double) result)+bias); result *= QuantumRange; break; } case ArctanFunction: { /* Arctan Function * Parameters: Slope, Center, Range, Bias */ double slope,range,center,bias; slope = ( number_parameters >= 1 ) ? parameters[0] : 1.0; center = ( number_parameters >= 2 ) ? parameters[1] : 0.5; range = ( number_parameters >= 3 ) ? parameters[2] : 1.0; bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5; result=(MagickRealType) (MagickPI*slope*(QuantumScale*pixel-center)); result=(MagickRealType) (QuantumRange*(range/MagickPI*atan((double) result) + bias ) ); break; } case UndefinedFunction: break; } return(ClampToQuantum(result)); } MagickExport MagickBooleanType FunctionImage(Image *image, const MagickFunction function,const size_t number_parameters, const double *parameters,ExceptionInfo *exception) { MagickBooleanType status; status=FunctionImageChannel(image,CompositeChannels,function, number_parameters,parameters,exception); return(status); } MagickExport MagickBooleanType FunctionImageChannel(Image *image, const ChannelType channel,const MagickFunction function, const size_t number_parameters,const double *parameters, ExceptionInfo *exception) { #define FunctionImageTag "Function/Image " CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); return(MagickFalse); } #if defined(MAGICKCORE_OPENCL_SUPPORT) status=AccelerateFunctionImage(image,channel,function,number_parameters, parameters,exception); if (status != MagickFalse) return(status); #endif status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,ApplyFunction(GetPixelRed(q),function, number_parameters,parameters,exception)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ApplyFunction(GetPixelGreen(q),function, number_parameters,parameters,exception)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ApplyFunction(GetPixelBlue(q),function, number_parameters,parameters,exception)); if ((channel & OpacityChannel) != 0) { if (image->matte == MagickFalse) SetPixelOpacity(q,ApplyFunction(GetPixelOpacity(q),function, number_parameters,parameters,exception)); else SetPixelAlpha(q,ApplyFunction((Quantum) GetPixelAlpha(q),function, number_parameters,parameters,exception)); } if (((channel & IndexChannel) != 0) && (indexes != (IndexPacket *) NULL)) SetPixelIndex(indexes+x,ApplyFunction(GetPixelIndex(indexes+x),function, number_parameters,parameters,exception)); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,FunctionImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l E n t r o p y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelEntropy() returns the entropy of one or more image channels. % % The format of the GetImageChannelEntropy method is: % % MagickBooleanType GetImageChannelEntropy(const Image *image, % const ChannelType channel,double *entropy,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o entropy: the average entropy of the selected channels. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageEntropy(const Image *image, double *entropy,ExceptionInfo *exception) { MagickBooleanType status; status=GetImageChannelEntropy(image,CompositeChannels,entropy,exception); return(status); } MagickExport MagickBooleanType GetImageChannelEntropy(const Image *image, const ChannelType channel,double *entropy,ExceptionInfo *exception) { ChannelStatistics *channel_statistics; size_t channels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageChannelStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); channels=0; channel_statistics[CompositeChannels].entropy=0.0; if ((channel & RedChannel) != 0) { channel_statistics[CompositeChannels].entropy+= channel_statistics[RedChannel].entropy; channels++; } if ((channel & GreenChannel) != 0) { channel_statistics[CompositeChannels].entropy+= channel_statistics[GreenChannel].entropy; channels++; } if ((channel & BlueChannel) != 0) { channel_statistics[CompositeChannels].entropy+= channel_statistics[BlueChannel].entropy; channels++; } if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) { channel_statistics[CompositeChannels].entropy+= channel_statistics[OpacityChannel].entropy; channels++; } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { channel_statistics[CompositeChannels].entropy+= channel_statistics[BlackChannel].entropy; channels++; } channel_statistics[CompositeChannels].entropy/=channels; *entropy=channel_statistics[CompositeChannels].entropy; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e C h a n n e l E x t r e m a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelExtrema() returns the extrema of one or more image channels. % % The format of the GetImageChannelExtrema method is: % % MagickBooleanType GetImageChannelExtrema(const Image *image, % const ChannelType channel,size_t *minima,size_t *maxima, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o minima: the minimum value in the channel. % % o maxima: the maximum value in the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageExtrema(const Image *image, size_t *minima,size_t *maxima,ExceptionInfo *exception) { MagickBooleanType status; status=GetImageChannelExtrema(image,CompositeChannels,minima,maxima, exception); return(status); } MagickExport MagickBooleanType GetImageChannelExtrema(const Image *image, const ChannelType channel,size_t *minima,size_t *maxima, ExceptionInfo *exception) { double max, min; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=GetImageChannelRange(image,channel,&min,&max,exception); *minima=(size_t) ceil(min-0.5); *maxima=(size_t) floor(max+0.5); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l K u r t o s i s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelKurtosis() returns the kurtosis and skewness of one or more % image channels. % % The format of the GetImageChannelKurtosis method is: % % MagickBooleanType GetImageChannelKurtosis(const Image *image, % const ChannelType channel,double *kurtosis,double *skewness, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o kurtosis: the kurtosis of the channel. % % o skewness: the skewness of the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageKurtosis(const Image *image, double *kurtosis,double *skewness,ExceptionInfo *exception) { MagickBooleanType status; status=GetImageChannelKurtosis(image,CompositeChannels,kurtosis,skewness, exception); return(status); } MagickExport MagickBooleanType GetImageChannelKurtosis(const Image *image, const ChannelType channel,double *kurtosis,double *skewness, ExceptionInfo *exception) { double area, mean, standard_deviation, sum_squares, sum_cubes, sum_fourth_power; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); *kurtosis=0.0; *skewness=0.0; area=0.0; mean=0.0; standard_deviation=0.0; sum_squares=0.0; sum_cubes=0.0; sum_fourth_power=0.0; for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) { mean+=GetPixelRed(p); sum_squares+=(double) GetPixelRed(p)*GetPixelRed(p); sum_cubes+=(double) GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p); sum_fourth_power+=(double) GetPixelRed(p)*GetPixelRed(p)* GetPixelRed(p)*GetPixelRed(p); area++; } if ((channel & GreenChannel) != 0) { mean+=GetPixelGreen(p); sum_squares+=(double) GetPixelGreen(p)*GetPixelGreen(p); sum_cubes+=(double) GetPixelGreen(p)*GetPixelGreen(p)* GetPixelGreen(p); sum_fourth_power+=(double) GetPixelGreen(p)*GetPixelGreen(p)* GetPixelGreen(p)*GetPixelGreen(p); area++; } if ((channel & BlueChannel) != 0) { mean+=GetPixelBlue(p); sum_squares+=(double) GetPixelBlue(p)*GetPixelBlue(p); sum_cubes+=(double) GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p); sum_fourth_power+=(double) GetPixelBlue(p)*GetPixelBlue(p)* GetPixelBlue(p)*GetPixelBlue(p); area++; } if ((channel & OpacityChannel) != 0) { mean+=GetPixelAlpha(p); sum_squares+=(double) GetPixelOpacity(p)*GetPixelAlpha(p); sum_cubes+=(double) GetPixelOpacity(p)*GetPixelAlpha(p)* GetPixelAlpha(p); sum_fourth_power+=(double) GetPixelAlpha(p)*GetPixelAlpha(p)* GetPixelAlpha(p)*GetPixelAlpha(p); area++; } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { double index; index=(double) GetPixelIndex(indexes+x); mean+=index; sum_squares+=index*index; sum_cubes+=index*index*index; sum_fourth_power+=index*index*index*index; area++; } p++; } } if (y < (ssize_t) image->rows) return(MagickFalse); if (area != 0.0) { mean/=area; sum_squares/=area; sum_cubes/=area; sum_fourth_power/=area; } standard_deviation=sqrt(sum_squares-(mean*mean)); if (standard_deviation != 0.0) { *kurtosis=sum_fourth_power-4.0*mean*sum_cubes+6.0*mean*mean*sum_squares- 3.0*mean*mean*mean*mean; *kurtosis/=standard_deviation*standard_deviation*standard_deviation* standard_deviation; *kurtosis-=3.0; *skewness=sum_cubes-3.0*mean*sum_squares+2.0*mean*mean*mean; *skewness/=standard_deviation*standard_deviation*standard_deviation; } return(y == (ssize_t) image->rows ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l M e a n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelMean() returns the mean and standard deviation of one or more % image channels. % % The format of the GetImageChannelMean method is: % % MagickBooleanType GetImageChannelMean(const Image *image, % const ChannelType channel,double *mean,double *standard_deviation, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o mean: the average value in the channel. % % o standard_deviation: the standard deviation of the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageMean(const Image *image,double *mean, double *standard_deviation,ExceptionInfo *exception) { MagickBooleanType status; status=GetImageChannelMean(image,CompositeChannels,mean,standard_deviation, exception); return(status); } MagickExport MagickBooleanType GetImageChannelMean(const Image *image, const ChannelType channel,double *mean,double *standard_deviation, ExceptionInfo *exception) { ChannelStatistics *channel_statistics; size_t channels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageChannelStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); channels=0; channel_statistics[CompositeChannels].mean=0.0; channel_statistics[CompositeChannels].standard_deviation=0.0; if ((channel & RedChannel) != 0) { channel_statistics[CompositeChannels].mean+= channel_statistics[RedChannel].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[RedChannel].standard_deviation; channels++; } if ((channel & GreenChannel) != 0) { channel_statistics[CompositeChannels].mean+= channel_statistics[GreenChannel].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[GreenChannel].standard_deviation; channels++; } if ((channel & BlueChannel) != 0) { channel_statistics[CompositeChannels].mean+= channel_statistics[BlueChannel].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[BlueChannel].standard_deviation; channels++; } if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) { channel_statistics[CompositeChannels].mean+= (QuantumRange-channel_statistics[OpacityChannel].mean); channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[OpacityChannel].standard_deviation; channels++; } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { channel_statistics[CompositeChannels].mean+= channel_statistics[BlackChannel].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[CompositeChannels].standard_deviation; channels++; } channel_statistics[CompositeChannels].mean/=channels; channel_statistics[CompositeChannels].standard_deviation/=channels; *mean=channel_statistics[CompositeChannels].mean; *standard_deviation=channel_statistics[CompositeChannels].standard_deviation; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l M o m e n t s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelMoments() returns the normalized moments of one or more image % channels. % % The format of the GetImageChannelMoments method is: % % ChannelMoments *GetImageChannelMoments(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport ChannelMoments *GetImageChannelMoments(const Image *image, ExceptionInfo *exception) { #define MaxNumberImageMoments 8 ChannelMoments *channel_moments; double M00[CompositeChannels+1], M01[CompositeChannels+1], M02[CompositeChannels+1], M03[CompositeChannels+1], M10[CompositeChannels+1], M11[CompositeChannels+1], M12[CompositeChannels+1], M20[CompositeChannels+1], M21[CompositeChannels+1], M22[CompositeChannels+1], M30[CompositeChannels+1]; MagickPixelPacket pixel; PointInfo centroid[CompositeChannels+1]; ssize_t channel, channels, y; size_t length; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); length=CompositeChannels+1UL; channel_moments=(ChannelMoments *) AcquireQuantumMemory(length, sizeof(*channel_moments)); if (channel_moments == (ChannelMoments *) NULL) return(channel_moments); (void) memset(channel_moments,0,length*sizeof(*channel_moments)); (void) memset(centroid,0,sizeof(centroid)); (void) memset(M00,0,sizeof(M00)); (void) memset(M01,0,sizeof(M01)); (void) memset(M02,0,sizeof(M02)); (void) memset(M03,0,sizeof(M03)); (void) memset(M10,0,sizeof(M10)); (void) memset(M11,0,sizeof(M11)); (void) memset(M12,0,sizeof(M12)); (void) memset(M20,0,sizeof(M20)); (void) memset(M21,0,sizeof(M21)); (void) memset(M22,0,sizeof(M22)); (void) memset(M30,0,sizeof(M30)); GetMagickPixelPacket(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; /* Compute center of mass (centroid). */ p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,p,indexes+x,&pixel); M00[RedChannel]+=QuantumScale*pixel.red; M10[RedChannel]+=x*QuantumScale*pixel.red; M01[RedChannel]+=y*QuantumScale*pixel.red; M00[GreenChannel]+=QuantumScale*pixel.green; M10[GreenChannel]+=x*QuantumScale*pixel.green; M01[GreenChannel]+=y*QuantumScale*pixel.green; M00[BlueChannel]+=QuantumScale*pixel.blue; M10[BlueChannel]+=x*QuantumScale*pixel.blue; M01[BlueChannel]+=y*QuantumScale*pixel.blue; if (image->matte != MagickFalse) { M00[OpacityChannel]+=QuantumScale*pixel.opacity; M10[OpacityChannel]+=x*QuantumScale*pixel.opacity; M01[OpacityChannel]+=y*QuantumScale*pixel.opacity; } if (image->colorspace == CMYKColorspace) { M00[IndexChannel]+=QuantumScale*pixel.index; M10[IndexChannel]+=x*QuantumScale*pixel.index; M01[IndexChannel]+=y*QuantumScale*pixel.index; } p++; } } for (channel=0; channel <= CompositeChannels; channel++) { /* Compute center of mass (centroid). */ if (M00[channel] < MagickEpsilon) { M00[channel]+=MagickEpsilon; centroid[channel].x=(double) image->columns/2.0; centroid[channel].y=(double) image->rows/2.0; continue; } M00[channel]+=MagickEpsilon; centroid[channel].x=M10[channel]/M00[channel]; centroid[channel].y=M01[channel]/M00[channel]; } for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; /* Compute the image moments. */ p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,p,indexes+x,&pixel); M11[RedChannel]+=(x-centroid[RedChannel].x)*(y- centroid[RedChannel].y)*QuantumScale*pixel.red; M20[RedChannel]+=(x-centroid[RedChannel].x)*(x- centroid[RedChannel].x)*QuantumScale*pixel.red; M02[RedChannel]+=(y-centroid[RedChannel].y)*(y- centroid[RedChannel].y)*QuantumScale*pixel.red; M21[RedChannel]+=(x-centroid[RedChannel].x)*(x- centroid[RedChannel].x)*(y-centroid[RedChannel].y)*QuantumScale* pixel.red; M12[RedChannel]+=(x-centroid[RedChannel].x)*(y- centroid[RedChannel].y)*(y-centroid[RedChannel].y)*QuantumScale* pixel.red; M22[RedChannel]+=(x-centroid[RedChannel].x)*(x- centroid[RedChannel].x)*(y-centroid[RedChannel].y)*(y- centroid[RedChannel].y)*QuantumScale*pixel.red; M30[RedChannel]+=(x-centroid[RedChannel].x)*(x- centroid[RedChannel].x)*(x-centroid[RedChannel].x)*QuantumScale* pixel.red; M03[RedChannel]+=(y-centroid[RedChannel].y)*(y- centroid[RedChannel].y)*(y-centroid[RedChannel].y)*QuantumScale* pixel.red; M11[GreenChannel]+=(x-centroid[GreenChannel].x)*(y- centroid[GreenChannel].y)*QuantumScale*pixel.green; M20[GreenChannel]+=(x-centroid[GreenChannel].x)*(x- centroid[GreenChannel].x)*QuantumScale*pixel.green; M02[GreenChannel]+=(y-centroid[GreenChannel].y)*(y- centroid[GreenChannel].y)*QuantumScale*pixel.green; M21[GreenChannel]+=(x-centroid[GreenChannel].x)*(x- centroid[GreenChannel].x)*(y-centroid[GreenChannel].y)*QuantumScale* pixel.green; M12[GreenChannel]+=(x-centroid[GreenChannel].x)*(y- centroid[GreenChannel].y)*(y-centroid[GreenChannel].y)*QuantumScale* pixel.green; M22[GreenChannel]+=(x-centroid[GreenChannel].x)*(x- centroid[GreenChannel].x)*(y-centroid[GreenChannel].y)*(y- centroid[GreenChannel].y)*QuantumScale*pixel.green; M30[GreenChannel]+=(x-centroid[GreenChannel].x)*(x- centroid[GreenChannel].x)*(x-centroid[GreenChannel].x)*QuantumScale* pixel.green; M03[GreenChannel]+=(y-centroid[GreenChannel].y)*(y- centroid[GreenChannel].y)*(y-centroid[GreenChannel].y)*QuantumScale* pixel.green; M11[BlueChannel]+=(x-centroid[BlueChannel].x)*(y- centroid[BlueChannel].y)*QuantumScale*pixel.blue; M20[BlueChannel]+=(x-centroid[BlueChannel].x)*(x- centroid[BlueChannel].x)*QuantumScale*pixel.blue; M02[BlueChannel]+=(y-centroid[BlueChannel].y)*(y- centroid[BlueChannel].y)*QuantumScale*pixel.blue; M21[BlueChannel]+=(x-centroid[BlueChannel].x)*(x- centroid[BlueChannel].x)*(y-centroid[BlueChannel].y)*QuantumScale* pixel.blue; M12[BlueChannel]+=(x-centroid[BlueChannel].x)*(y- centroid[BlueChannel].y)*(y-centroid[BlueChannel].y)*QuantumScale* pixel.blue; M22[BlueChannel]+=(x-centroid[BlueChannel].x)*(x- centroid[BlueChannel].x)*(y-centroid[BlueChannel].y)*(y- centroid[BlueChannel].y)*QuantumScale*pixel.blue; M30[BlueChannel]+=(x-centroid[BlueChannel].x)*(x- centroid[BlueChannel].x)*(x-centroid[BlueChannel].x)*QuantumScale* pixel.blue; M03[BlueChannel]+=(y-centroid[BlueChannel].y)*(y- centroid[BlueChannel].y)*(y-centroid[BlueChannel].y)*QuantumScale* pixel.blue; if (image->matte != MagickFalse) { M11[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(y- centroid[OpacityChannel].y)*QuantumScale*pixel.opacity; M20[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x- centroid[OpacityChannel].x)*QuantumScale*pixel.opacity; M02[OpacityChannel]+=(y-centroid[OpacityChannel].y)*(y- centroid[OpacityChannel].y)*QuantumScale*pixel.opacity; M21[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x- centroid[OpacityChannel].x)*(y-centroid[OpacityChannel].y)* QuantumScale*pixel.opacity; M12[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(y- centroid[OpacityChannel].y)*(y-centroid[OpacityChannel].y)* QuantumScale*pixel.opacity; M22[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x- centroid[OpacityChannel].x)*(y-centroid[OpacityChannel].y)*(y- centroid[OpacityChannel].y)*QuantumScale*pixel.opacity; M30[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x- centroid[OpacityChannel].x)*(x-centroid[OpacityChannel].x)* QuantumScale*pixel.opacity; M03[OpacityChannel]+=(y-centroid[OpacityChannel].y)*(y- centroid[OpacityChannel].y)*(y-centroid[OpacityChannel].y)* QuantumScale*pixel.opacity; } if (image->colorspace == CMYKColorspace) { M11[IndexChannel]+=(x-centroid[IndexChannel].x)*(y- centroid[IndexChannel].y)*QuantumScale*pixel.index; M20[IndexChannel]+=(x-centroid[IndexChannel].x)*(x- centroid[IndexChannel].x)*QuantumScale*pixel.index; M02[IndexChannel]+=(y-centroid[IndexChannel].y)*(y- centroid[IndexChannel].y)*QuantumScale*pixel.index; M21[IndexChannel]+=(x-centroid[IndexChannel].x)*(x- centroid[IndexChannel].x)*(y-centroid[IndexChannel].y)* QuantumScale*pixel.index; M12[IndexChannel]+=(x-centroid[IndexChannel].x)*(y- centroid[IndexChannel].y)*(y-centroid[IndexChannel].y)* QuantumScale*pixel.index; M22[IndexChannel]+=(x-centroid[IndexChannel].x)*(x- centroid[IndexChannel].x)*(y-centroid[IndexChannel].y)*(y- centroid[IndexChannel].y)*QuantumScale*pixel.index; M30[IndexChannel]+=(x-centroid[IndexChannel].x)*(x- centroid[IndexChannel].x)*(x-centroid[IndexChannel].x)* QuantumScale*pixel.index; M03[IndexChannel]+=(y-centroid[IndexChannel].y)*(y- centroid[IndexChannel].y)*(y-centroid[IndexChannel].y)* QuantumScale*pixel.index; } p++; } } channels=3; M00[CompositeChannels]+=(M00[RedChannel]+M00[GreenChannel]+M00[BlueChannel]); M01[CompositeChannels]+=(M01[RedChannel]+M01[GreenChannel]+M01[BlueChannel]); M02[CompositeChannels]+=(M02[RedChannel]+M02[GreenChannel]+M02[BlueChannel]); M03[CompositeChannels]+=(M03[RedChannel]+M03[GreenChannel]+M03[BlueChannel]); M10[CompositeChannels]+=(M10[RedChannel]+M10[GreenChannel]+M10[BlueChannel]); M11[CompositeChannels]+=(M11[RedChannel]+M11[GreenChannel]+M11[BlueChannel]); M12[CompositeChannels]+=(M12[RedChannel]+M12[GreenChannel]+M12[BlueChannel]); M20[CompositeChannels]+=(M20[RedChannel]+M20[GreenChannel]+M20[BlueChannel]); M21[CompositeChannels]+=(M21[RedChannel]+M21[GreenChannel]+M21[BlueChannel]); M22[CompositeChannels]+=(M22[RedChannel]+M22[GreenChannel]+M22[BlueChannel]); M30[CompositeChannels]+=(M30[RedChannel]+M30[GreenChannel]+M30[BlueChannel]); if (image->matte != MagickFalse) { channels+=1; M00[CompositeChannels]+=M00[OpacityChannel]; M01[CompositeChannels]+=M01[OpacityChannel]; M02[CompositeChannels]+=M02[OpacityChannel]; M03[CompositeChannels]+=M03[OpacityChannel]; M10[CompositeChannels]+=M10[OpacityChannel]; M11[CompositeChannels]+=M11[OpacityChannel]; M12[CompositeChannels]+=M12[OpacityChannel]; M20[CompositeChannels]+=M20[OpacityChannel]; M21[CompositeChannels]+=M21[OpacityChannel]; M22[CompositeChannels]+=M22[OpacityChannel]; M30[CompositeChannels]+=M30[OpacityChannel]; } if (image->colorspace == CMYKColorspace) { channels+=1; M00[CompositeChannels]+=M00[IndexChannel]; M01[CompositeChannels]+=M01[IndexChannel]; M02[CompositeChannels]+=M02[IndexChannel]; M03[CompositeChannels]+=M03[IndexChannel]; M10[CompositeChannels]+=M10[IndexChannel]; M11[CompositeChannels]+=M11[IndexChannel]; M12[CompositeChannels]+=M12[IndexChannel]; M20[CompositeChannels]+=M20[IndexChannel]; M21[CompositeChannels]+=M21[IndexChannel]; M22[CompositeChannels]+=M22[IndexChannel]; M30[CompositeChannels]+=M30[IndexChannel]; } M00[CompositeChannels]/=(double) channels; M01[CompositeChannels]/=(double) channels; M02[CompositeChannels]/=(double) channels; M03[CompositeChannels]/=(double) channels; M10[CompositeChannels]/=(double) channels; M11[CompositeChannels]/=(double) channels; M12[CompositeChannels]/=(double) channels; M20[CompositeChannels]/=(double) channels; M21[CompositeChannels]/=(double) channels; M22[CompositeChannels]/=(double) channels; M30[CompositeChannels]/=(double) channels; for (channel=0; channel <= CompositeChannels; channel++) { /* Compute elliptical angle, major and minor axes, eccentricity, & intensity. */ channel_moments[channel].centroid=centroid[channel]; channel_moments[channel].ellipse_axis.x=sqrt((2.0/M00[channel])* ((M20[channel]+M02[channel])+sqrt(4.0*M11[channel]*M11[channel]+ (M20[channel]-M02[channel])*(M20[channel]-M02[channel])))); channel_moments[channel].ellipse_axis.y=sqrt((2.0/M00[channel])* ((M20[channel]+M02[channel])-sqrt(4.0*M11[channel]*M11[channel]+ (M20[channel]-M02[channel])*(M20[channel]-M02[channel])))); channel_moments[channel].ellipse_angle=RadiansToDegrees(0.5*atan(2.0* M11[channel]/(M20[channel]-M02[channel]+MagickEpsilon))); if (fabs(M11[channel]) < MagickEpsilon) { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=0.0; } else if (M11[channel] < 0.0) { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=180.0; } else { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=0.0; } channel_moments[channel].ellipse_eccentricity=sqrt(1.0-( channel_moments[channel].ellipse_axis.y/ (channel_moments[channel].ellipse_axis.x+MagickEpsilon))); channel_moments[channel].ellipse_intensity=M00[channel]/ (MagickPI*channel_moments[channel].ellipse_axis.x* channel_moments[channel].ellipse_axis.y+MagickEpsilon); } for (channel=0; channel <= CompositeChannels; channel++) { /* Normalize image moments. */ M10[channel]=0.0; M01[channel]=0.0; M11[channel]/=pow(M00[channel],1.0+(1.0+1.0)/2.0); M20[channel]/=pow(M00[channel],1.0+(2.0+0.0)/2.0); M02[channel]/=pow(M00[channel],1.0+(0.0+2.0)/2.0); M21[channel]/=pow(M00[channel],1.0+(2.0+1.0)/2.0); M12[channel]/=pow(M00[channel],1.0+(1.0+2.0)/2.0); M22[channel]/=pow(M00[channel],1.0+(2.0+2.0)/2.0); M30[channel]/=pow(M00[channel],1.0+(3.0+0.0)/2.0); M03[channel]/=pow(M00[channel],1.0+(0.0+3.0)/2.0); M00[channel]=1.0; } for (channel=0; channel <= CompositeChannels; channel++) { /* Compute Hu invariant moments. */ channel_moments[channel].I[0]=M20[channel]+M02[channel]; channel_moments[channel].I[1]=(M20[channel]-M02[channel])* (M20[channel]-M02[channel])+4.0*M11[channel]*M11[channel]; channel_moments[channel].I[2]=(M30[channel]-3.0*M12[channel])* (M30[channel]-3.0*M12[channel])+(3.0*M21[channel]-M03[channel])* (3.0*M21[channel]-M03[channel]); channel_moments[channel].I[3]=(M30[channel]+M12[channel])* (M30[channel]+M12[channel])+(M21[channel]+M03[channel])* (M21[channel]+M03[channel]); channel_moments[channel].I[4]=(M30[channel]-3.0*M12[channel])* (M30[channel]+M12[channel])*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])* (M21[channel]+M03[channel]))+(3.0*M21[channel]-M03[channel])* (M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M21[channel]+M03[channel])* (M21[channel]+M03[channel])); channel_moments[channel].I[5]=(M20[channel]-M02[channel])* ((M30[channel]+M12[channel])*(M30[channel]+M12[channel])- (M21[channel]+M03[channel])*(M21[channel]+M03[channel]))+ 4.0*M11[channel]*(M30[channel]+M12[channel])*(M21[channel]+M03[channel]); channel_moments[channel].I[6]=(3.0*M21[channel]-M03[channel])* (M30[channel]+M12[channel])*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])* (M21[channel]+M03[channel]))-(M30[channel]-3*M12[channel])* (M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M21[channel]+M03[channel])* (M21[channel]+M03[channel])); channel_moments[channel].I[7]=M11[channel]*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M03[channel]+M21[channel])* (M03[channel]+M21[channel]))-(M20[channel]-M02[channel])* (M30[channel]+M12[channel])*(M03[channel]+M21[channel]); } if (y < (ssize_t) image->rows) channel_moments=(ChannelMoments *) RelinquishMagickMemory(channel_moments); return(channel_moments); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l P e r c e p t u a l H a s h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelPerceptualHash() returns the perceptual hash of one or more % image channels. % % The format of the GetImageChannelPerceptualHash method is: % % ChannelPerceptualHash *GetImageChannelPerceptualHash(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static inline double MagickLog10(const double x) { #define Log10Epsilon (1.0e-11) if (fabs(x) < Log10Epsilon) return(log10(Log10Epsilon)); return(log10(fabs(x))); } MagickExport ChannelPerceptualHash *GetImageChannelPerceptualHash( const Image *image,ExceptionInfo *exception) { ChannelMoments *moments; ChannelPerceptualHash *perceptual_hash; Image *hash_image; MagickBooleanType status; register ssize_t i; ssize_t channel; /* Blur then transform to sRGB colorspace. */ hash_image=BlurImage(image,0.0,1.0,exception); if (hash_image == (Image *) NULL) return((ChannelPerceptualHash *) NULL); hash_image->depth=8; status=TransformImageColorspace(hash_image,sRGBColorspace); if (status == MagickFalse) return((ChannelPerceptualHash *) NULL); moments=GetImageChannelMoments(hash_image,exception); hash_image=DestroyImage(hash_image); if (moments == (ChannelMoments *) NULL) return((ChannelPerceptualHash *) NULL); perceptual_hash=(ChannelPerceptualHash *) AcquireQuantumMemory( CompositeChannels+1UL,sizeof(*perceptual_hash)); if (perceptual_hash == (ChannelPerceptualHash *) NULL) return((ChannelPerceptualHash *) NULL); for (channel=0; channel <= CompositeChannels; channel++) for (i=0; i < MaximumNumberOfImageMoments; i++) perceptual_hash[channel].P[i]=(-MagickLog10(moments[channel].I[i])); moments=(ChannelMoments *) RelinquishMagickMemory(moments); /* Blur then transform to HCLp colorspace. */ hash_image=BlurImage(image,0.0,1.0,exception); if (hash_image == (Image *) NULL) { perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory( perceptual_hash); return((ChannelPerceptualHash *) NULL); } hash_image->depth=8; status=TransformImageColorspace(hash_image,HCLpColorspace); if (status == MagickFalse) { perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory( perceptual_hash); return((ChannelPerceptualHash *) NULL); } moments=GetImageChannelMoments(hash_image,exception); hash_image=DestroyImage(hash_image); if (moments == (ChannelMoments *) NULL) { perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory( perceptual_hash); return((ChannelPerceptualHash *) NULL); } for (channel=0; channel <= CompositeChannels; channel++) for (i=0; i < MaximumNumberOfImageMoments; i++) perceptual_hash[channel].Q[i]=(-MagickLog10(moments[channel].I[i])); moments=(ChannelMoments *) RelinquishMagickMemory(moments); return(perceptual_hash); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l R a n g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelRange() returns the range of one or more image channels. % % The format of the GetImageChannelRange method is: % % MagickBooleanType GetImageChannelRange(const Image *image, % const ChannelType channel,double *minima,double *maxima, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o minima: the minimum value in the channel. % % o maxima: the maximum value in the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageRange(const Image *image, double *minima,double *maxima,ExceptionInfo *exception) { return(GetImageChannelRange(image,CompositeChannels,minima,maxima,exception)); } MagickExport MagickBooleanType GetImageChannelRange(const Image *image, const ChannelType channel,double *minima,double *maxima, ExceptionInfo *exception) { MagickPixelPacket pixel; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); *maxima=(-MagickMaximumValue); *minima=MagickMaximumValue; GetMagickPixelPacket(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,p,indexes+x,&pixel); if ((channel & RedChannel) != 0) { if (pixel.red < *minima) *minima=(double) pixel.red; if (pixel.red > *maxima) *maxima=(double) pixel.red; } if ((channel & GreenChannel) != 0) { if (pixel.green < *minima) *minima=(double) pixel.green; if (pixel.green > *maxima) *maxima=(double) pixel.green; } if ((channel & BlueChannel) != 0) { if (pixel.blue < *minima) *minima=(double) pixel.blue; if (pixel.blue > *maxima) *maxima=(double) pixel.blue; } if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) { if ((QuantumRange-pixel.opacity) < *minima) *minima=(double) (QuantumRange-pixel.opacity); if ((QuantumRange-pixel.opacity) > *maxima) *maxima=(double) (QuantumRange-pixel.opacity); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { if ((double) pixel.index < *minima) *minima=(double) pixel.index; if ((double) pixel.index > *maxima) *maxima=(double) pixel.index; } p++; } } return(y == (ssize_t) image->rows ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l S t a t i s t i c s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelStatistics() returns statistics for each channel in the % image. The statistics include the channel depth, its minima, maxima, mean, % standard deviation, kurtosis and skewness. You can access the red channel % mean, for example, like this: % % channel_statistics=GetImageChannelStatistics(image,exception); % red_mean=channel_statistics[RedChannel].mean; % % Use MagickRelinquishMemory() to free the statistics buffer. % % The format of the GetImageChannelStatistics method is: % % ChannelStatistics *GetImageChannelStatistics(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport ChannelStatistics *GetImageChannelStatistics(const Image *image, ExceptionInfo *exception) { ChannelStatistics *channel_statistics; double area, standard_deviation; MagickPixelPacket number_bins, *histogram; QuantumAny range; register ssize_t i; size_t channels, depth, length; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); length=CompositeChannels+1UL; channel_statistics=(ChannelStatistics *) AcquireQuantumMemory(length, sizeof(*channel_statistics)); histogram=(MagickPixelPacket *) AcquireQuantumMemory(MaxMap+1U, sizeof(*histogram)); if ((channel_statistics == (ChannelStatistics *) NULL) || (histogram == (MagickPixelPacket *) NULL)) { if (histogram != (MagickPixelPacket *) NULL) histogram=(MagickPixelPacket *) RelinquishMagickMemory(histogram); if (channel_statistics != (ChannelStatistics *) NULL) channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(channel_statistics); } (void) memset(channel_statistics,0,length* sizeof(*channel_statistics)); for (i=0; i <= (ssize_t) CompositeChannels; i++) { channel_statistics[i].depth=1; channel_statistics[i].maxima=(-MagickMaximumValue); channel_statistics[i].minima=MagickMaximumValue; } (void) memset(histogram,0,(MaxMap+1U)*sizeof(*histogram)); (void) memset(&number_bins,0,sizeof(number_bins)); for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; /* Compute pixel statistics. */ p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; ) { if (channel_statistics[RedChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[RedChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelRed(p),range) == MagickFalse) { channel_statistics[RedChannel].depth++; continue; } } if (channel_statistics[GreenChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[GreenChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelGreen(p),range) == MagickFalse) { channel_statistics[GreenChannel].depth++; continue; } } if (channel_statistics[BlueChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[BlueChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelBlue(p),range) == MagickFalse) { channel_statistics[BlueChannel].depth++; continue; } } if (image->matte != MagickFalse) { if (channel_statistics[OpacityChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[OpacityChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelAlpha(p),range) == MagickFalse) { channel_statistics[OpacityChannel].depth++; continue; } } } if (image->colorspace == CMYKColorspace) { if (channel_statistics[BlackChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[BlackChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelIndex(indexes+x),range) == MagickFalse) { channel_statistics[BlackChannel].depth++; continue; } } } if ((double) GetPixelRed(p) < channel_statistics[RedChannel].minima) channel_statistics[RedChannel].minima=(double) GetPixelRed(p); if ((double) GetPixelRed(p) > channel_statistics[RedChannel].maxima) channel_statistics[RedChannel].maxima=(double) GetPixelRed(p); channel_statistics[RedChannel].sum+=GetPixelRed(p); channel_statistics[RedChannel].sum_squared+=(double) GetPixelRed(p)* GetPixelRed(p); channel_statistics[RedChannel].sum_cubed+=(double) GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p); channel_statistics[RedChannel].sum_fourth_power+=(double) GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p); if ((double) GetPixelGreen(p) < channel_statistics[GreenChannel].minima) channel_statistics[GreenChannel].minima=(double) GetPixelGreen(p); if ((double) GetPixelGreen(p) > channel_statistics[GreenChannel].maxima) channel_statistics[GreenChannel].maxima=(double) GetPixelGreen(p); channel_statistics[GreenChannel].sum+=GetPixelGreen(p); channel_statistics[GreenChannel].sum_squared+=(double) GetPixelGreen(p)* GetPixelGreen(p); channel_statistics[GreenChannel].sum_cubed+=(double) GetPixelGreen(p)* GetPixelGreen(p)*GetPixelGreen(p); channel_statistics[GreenChannel].sum_fourth_power+=(double) GetPixelGreen(p)*GetPixelGreen(p)*GetPixelGreen(p)*GetPixelGreen(p); if ((double) GetPixelBlue(p) < channel_statistics[BlueChannel].minima) channel_statistics[BlueChannel].minima=(double) GetPixelBlue(p); if ((double) GetPixelBlue(p) > channel_statistics[BlueChannel].maxima) channel_statistics[BlueChannel].maxima=(double) GetPixelBlue(p); channel_statistics[BlueChannel].sum+=GetPixelBlue(p); channel_statistics[BlueChannel].sum_squared+=(double) GetPixelBlue(p)* GetPixelBlue(p); channel_statistics[BlueChannel].sum_cubed+=(double) GetPixelBlue(p)* GetPixelBlue(p)*GetPixelBlue(p); channel_statistics[BlueChannel].sum_fourth_power+=(double) GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p); histogram[ScaleQuantumToMap(GetPixelRed(p))].red++; histogram[ScaleQuantumToMap(GetPixelGreen(p))].green++; histogram[ScaleQuantumToMap(GetPixelBlue(p))].blue++; if (image->matte != MagickFalse) { if ((double) GetPixelAlpha(p) < channel_statistics[OpacityChannel].minima) channel_statistics[OpacityChannel].minima=(double) GetPixelAlpha(p); if ((double) GetPixelAlpha(p) > channel_statistics[OpacityChannel].maxima) channel_statistics[OpacityChannel].maxima=(double) GetPixelAlpha(p); channel_statistics[OpacityChannel].sum+=GetPixelAlpha(p); channel_statistics[OpacityChannel].sum_squared+=(double) GetPixelAlpha(p)*GetPixelAlpha(p); channel_statistics[OpacityChannel].sum_cubed+=(double) GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p); channel_statistics[OpacityChannel].sum_fourth_power+=(double) GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p); histogram[ScaleQuantumToMap(GetPixelAlpha(p))].opacity++; } if (image->colorspace == CMYKColorspace) { if ((double) GetPixelIndex(indexes+x) < channel_statistics[BlackChannel].minima) channel_statistics[BlackChannel].minima=(double) GetPixelIndex(indexes+x); if ((double) GetPixelIndex(indexes+x) > channel_statistics[BlackChannel].maxima) channel_statistics[BlackChannel].maxima=(double) GetPixelIndex(indexes+x); channel_statistics[BlackChannel].sum+=GetPixelIndex(indexes+x); channel_statistics[BlackChannel].sum_squared+=(double) GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x); channel_statistics[BlackChannel].sum_cubed+=(double) GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x)* GetPixelIndex(indexes+x); channel_statistics[BlackChannel].sum_fourth_power+=(double) GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x)* GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x); histogram[ScaleQuantumToMap(GetPixelIndex(indexes+x))].index++; } x++; p++; } } for (i=0; i < (ssize_t) CompositeChannels; i++) { double area, mean, standard_deviation; /* Normalize pixel statistics. */ area=PerceptibleReciprocal((double) image->columns*image->rows); mean=channel_statistics[i].sum*area; channel_statistics[i].sum=mean; channel_statistics[i].sum_squared*=area; channel_statistics[i].sum_cubed*=area; channel_statistics[i].sum_fourth_power*=area; channel_statistics[i].mean=mean; channel_statistics[i].variance=channel_statistics[i].sum_squared; standard_deviation=sqrt(channel_statistics[i].variance-(mean*mean)); area=PerceptibleReciprocal((double) image->columns*image->rows-1.0)* ((double) image->columns*image->rows); standard_deviation=sqrt(area*standard_deviation*standard_deviation); channel_statistics[i].standard_deviation=standard_deviation; } for (i=0; i < (ssize_t) (MaxMap+1U); i++) { if (histogram[i].red > 0.0) number_bins.red++; if (histogram[i].green > 0.0) number_bins.green++; if (histogram[i].blue > 0.0) number_bins.blue++; if ((image->matte != MagickFalse) && (histogram[i].opacity > 0.0)) number_bins.opacity++; if ((image->colorspace == CMYKColorspace) && (histogram[i].index > 0.0)) number_bins.index++; } area=PerceptibleReciprocal((double) image->columns*image->rows); for (i=0; i < (ssize_t) (MaxMap+1U); i++) { /* Compute pixel entropy. */ histogram[i].red*=area; channel_statistics[RedChannel].entropy+=-histogram[i].red* MagickLog10(histogram[i].red)* PerceptibleReciprocal(MagickLog10((double) number_bins.red)); histogram[i].green*=area; channel_statistics[GreenChannel].entropy+=-histogram[i].green* MagickLog10(histogram[i].green)* PerceptibleReciprocal(MagickLog10((double) number_bins.green)); histogram[i].blue*=area; channel_statistics[BlueChannel].entropy+=-histogram[i].blue* MagickLog10(histogram[i].blue)* PerceptibleReciprocal(MagickLog10((double) number_bins.blue)); if (image->matte != MagickFalse) { histogram[i].opacity*=area; channel_statistics[OpacityChannel].entropy+=-histogram[i].opacity* MagickLog10(histogram[i].opacity)* PerceptibleReciprocal(MagickLog10((double) number_bins.opacity)); } if (image->colorspace == CMYKColorspace) { histogram[i].index*=area; channel_statistics[IndexChannel].entropy+=-histogram[i].index* MagickLog10(histogram[i].index)* PerceptibleReciprocal(MagickLog10((double) number_bins.index)); } } /* Compute overall statistics. */ for (i=0; i < (ssize_t) CompositeChannels; i++) { channel_statistics[CompositeChannels].depth=(size_t) EvaluateMax((double) channel_statistics[CompositeChannels].depth,(double) channel_statistics[i].depth); channel_statistics[CompositeChannels].minima=MagickMin( channel_statistics[CompositeChannels].minima, channel_statistics[i].minima); channel_statistics[CompositeChannels].maxima=EvaluateMax( channel_statistics[CompositeChannels].maxima, channel_statistics[i].maxima); channel_statistics[CompositeChannels].sum+=channel_statistics[i].sum; channel_statistics[CompositeChannels].sum_squared+= channel_statistics[i].sum_squared; channel_statistics[CompositeChannels].sum_cubed+= channel_statistics[i].sum_cubed; channel_statistics[CompositeChannels].sum_fourth_power+= channel_statistics[i].sum_fourth_power; channel_statistics[CompositeChannels].mean+=channel_statistics[i].mean; channel_statistics[CompositeChannels].variance+= channel_statistics[i].variance-channel_statistics[i].mean* channel_statistics[i].mean; standard_deviation=sqrt(channel_statistics[i].variance- (channel_statistics[i].mean*channel_statistics[i].mean)); area=PerceptibleReciprocal((double) image->columns*image->rows-1.0)* ((double) image->columns*image->rows); standard_deviation=sqrt(area*standard_deviation*standard_deviation); channel_statistics[CompositeChannels].standard_deviation=standard_deviation; channel_statistics[CompositeChannels].entropy+= channel_statistics[i].entropy; } channels=3; if (image->matte != MagickFalse) channels++; if (image->colorspace == CMYKColorspace) channels++; channel_statistics[CompositeChannels].sum/=channels; channel_statistics[CompositeChannels].sum_squared/=channels; channel_statistics[CompositeChannels].sum_cubed/=channels; channel_statistics[CompositeChannels].sum_fourth_power/=channels; channel_statistics[CompositeChannels].mean/=channels; channel_statistics[CompositeChannels].kurtosis/=channels; channel_statistics[CompositeChannels].skewness/=channels; channel_statistics[CompositeChannels].entropy/=channels; i=CompositeChannels; area=PerceptibleReciprocal((double) channels*image->columns*image->rows); channel_statistics[i].variance=channel_statistics[i].sum_squared; channel_statistics[i].mean=channel_statistics[i].sum; standard_deviation=sqrt(channel_statistics[i].variance- (channel_statistics[i].mean*channel_statistics[i].mean)); standard_deviation=sqrt(PerceptibleReciprocal((double) channels* image->columns*image->rows-1.0)*channels*image->columns*image->rows* standard_deviation*standard_deviation); channel_statistics[i].standard_deviation=standard_deviation; for (i=0; i <= (ssize_t) CompositeChannels; i++) { /* Compute kurtosis & skewness statistics. */ standard_deviation=PerceptibleReciprocal( channel_statistics[i].standard_deviation); channel_statistics[i].skewness=(channel_statistics[i].sum_cubed-3.0* channel_statistics[i].mean*channel_statistics[i].sum_squared+2.0* channel_statistics[i].mean*channel_statistics[i].mean* channel_statistics[i].mean)*(standard_deviation*standard_deviation* standard_deviation); channel_statistics[i].kurtosis=(channel_statistics[i].sum_fourth_power-4.0* channel_statistics[i].mean*channel_statistics[i].sum_cubed+6.0* channel_statistics[i].mean*channel_statistics[i].mean* channel_statistics[i].sum_squared-3.0*channel_statistics[i].mean* channel_statistics[i].mean*1.0*channel_statistics[i].mean* channel_statistics[i].mean)*(standard_deviation*standard_deviation* standard_deviation*standard_deviation)-3.0; } channel_statistics[CompositeChannels].mean=0.0; channel_statistics[CompositeChannels].standard_deviation=0.0; for (i=0; i < (ssize_t) CompositeChannels; i++) { channel_statistics[CompositeChannels].mean+= channel_statistics[i].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[i].standard_deviation; } channel_statistics[CompositeChannels].mean/=(double) channels; channel_statistics[CompositeChannels].standard_deviation/=(double) channels; histogram=(MagickPixelPacket *) RelinquishMagickMemory(histogram); if (y < (ssize_t) image->rows) channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(channel_statistics); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o l y n o m i a l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PolynomialImage() returns a new image where each pixel is the sum of the % pixels in the image sequence after applying its corresponding terms % (coefficient and degree pairs). % % The format of the PolynomialImage method is: % % Image *PolynomialImage(const Image *images,const size_t number_terms, % const double *terms,ExceptionInfo *exception) % Image *PolynomialImageChannel(const Image *images, % const size_t number_terms,const ChannelType channel, % const double *terms,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o channel: the channel. % % o number_terms: the number of terms in the list. The actual list length % is 2 x number_terms + 1 (the constant). % % o terms: the list of polynomial coefficients and degree pairs and a % constant. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *PolynomialImage(const Image *images, const size_t number_terms,const double *terms,ExceptionInfo *exception) { Image *polynomial_image; polynomial_image=PolynomialImageChannel(images,DefaultChannels,number_terms, terms,exception); return(polynomial_image); } MagickExport Image *PolynomialImageChannel(const Image *images, const ChannelType channel,const size_t number_terms,const double *terms, ExceptionInfo *exception) { #define PolynomialImageTag "Polynomial/Image" CacheView *polynomial_view; Image *image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket **magick_restrict polynomial_pixels, zero; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImageCanvas(images,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImage(image); return((Image *) NULL); } polynomial_pixels=AcquirePixelThreadSet(images); if (polynomial_pixels == (MagickPixelPacket **) NULL) { image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return((Image *) NULL); } /* Polynomial image pixels. */ status=MagickTrue; progress=0; GetMagickPixelPacket(images,&zero); polynomial_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict polynomial_indexes; register MagickPixelPacket *polynomial_pixel; register PixelPacket *magick_restrict q; register ssize_t i, x; size_t number_images; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(polynomial_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } polynomial_indexes=GetCacheViewAuthenticIndexQueue(polynomial_view); polynomial_pixel=polynomial_pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) polynomial_pixel[x]=zero; next=images; number_images=GetImageListLength(images); for (i=0; i < (ssize_t) number_images; i++) { register const IndexPacket *indexes; register const PixelPacket *p; if (i >= (ssize_t) number_terms) break; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) { image_view=DestroyCacheView(image_view); break; } indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { double coefficient, degree; coefficient=terms[i << 1]; degree=terms[(i << 1)+1]; if ((channel & RedChannel) != 0) polynomial_pixel[x].red+=coefficient*pow(QuantumScale*p->red,degree); if ((channel & GreenChannel) != 0) polynomial_pixel[x].green+=coefficient*pow(QuantumScale*p->green, degree); if ((channel & BlueChannel) != 0) polynomial_pixel[x].blue+=coefficient*pow(QuantumScale*p->blue, degree); if ((channel & OpacityChannel) != 0) polynomial_pixel[x].opacity+=coefficient*pow(QuantumScale* (QuantumRange-p->opacity),degree); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) polynomial_pixel[x].index+=coefficient*pow(QuantumScale*indexes[x], degree); p++; } image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].red)); SetPixelGreen(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].green)); SetPixelBlue(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].blue)); if (image->matte == MagickFalse) SetPixelOpacity(q,ClampToQuantum(QuantumRange-QuantumRange* polynomial_pixel[x].opacity)); else SetPixelAlpha(q,ClampToQuantum(QuantumRange-QuantumRange* polynomial_pixel[x].opacity)); if (image->colorspace == CMYKColorspace) SetPixelIndex(polynomial_indexes+x,ClampToQuantum(QuantumRange* polynomial_pixel[x].index)); q++; } if (SyncCacheViewAuthenticPixels(polynomial_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(images,PolynomialImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } polynomial_view=DestroyCacheView(polynomial_view); polynomial_pixels=DestroyPixelThreadSet(polynomial_pixels); if (status == MagickFalse) image=DestroyImage(image); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t a t i s t i c I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % StatisticImage() makes each pixel the min / max / median / mode / etc. of % the neighborhood of the specified width and height. % % The format of the StatisticImage method is: % % Image *StatisticImage(const Image *image,const StatisticType type, % const size_t width,const size_t height,ExceptionInfo *exception) % Image *StatisticImageChannel(const Image *image, % const ChannelType channel,const StatisticType type, % const size_t width,const size_t height,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the image channel. % % o type: the statistic type (median, mode, etc.). % % o width: the width of the pixel neighborhood. % % o height: the height of the pixel neighborhood. % % o exception: return any errors or warnings in this structure. % */ #define ListChannels 5 typedef struct _ListNode { size_t next[9], count, signature; } ListNode; typedef struct _SkipList { ssize_t level; ListNode *nodes; } SkipList; typedef struct _PixelList { size_t length, seed, signature; SkipList lists[ListChannels]; } PixelList; static PixelList *DestroyPixelList(PixelList *pixel_list) { register ssize_t i; if (pixel_list == (PixelList *) NULL) return((PixelList *) NULL); for (i=0; i < ListChannels; i++) if (pixel_list->lists[i].nodes != (ListNode *) NULL) pixel_list->lists[i].nodes=(ListNode *) RelinquishAlignedMemory( pixel_list->lists[i].nodes); pixel_list=(PixelList *) RelinquishMagickMemory(pixel_list); return(pixel_list); } static PixelList **DestroyPixelListThreadSet(PixelList **pixel_list) { register ssize_t i; assert(pixel_list != (PixelList **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixel_list[i] != (PixelList *) NULL) pixel_list[i]=DestroyPixelList(pixel_list[i]); pixel_list=(PixelList **) RelinquishMagickMemory(pixel_list); return(pixel_list); } static PixelList *AcquirePixelList(const size_t width,const size_t height) { PixelList *pixel_list; register ssize_t i; pixel_list=(PixelList *) AcquireMagickMemory(sizeof(*pixel_list)); if (pixel_list == (PixelList *) NULL) return(pixel_list); (void) memset((void *) pixel_list,0,sizeof(*pixel_list)); pixel_list->length=width*height; for (i=0; i < ListChannels; i++) { pixel_list->lists[i].nodes=(ListNode *) AcquireAlignedMemory(65537UL, sizeof(*pixel_list->lists[i].nodes)); if (pixel_list->lists[i].nodes == (ListNode *) NULL) return(DestroyPixelList(pixel_list)); (void) memset(pixel_list->lists[i].nodes,0,65537UL* sizeof(*pixel_list->lists[i].nodes)); } pixel_list->signature=MagickCoreSignature; return(pixel_list); } static PixelList **AcquirePixelListThreadSet(const size_t width, const size_t height) { PixelList **pixel_list; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixel_list=(PixelList **) AcquireQuantumMemory(number_threads, sizeof(*pixel_list)); if (pixel_list == (PixelList **) NULL) return((PixelList **) NULL); (void) memset(pixel_list,0,number_threads*sizeof(*pixel_list)); for (i=0; i < (ssize_t) number_threads; i++) { pixel_list[i]=AcquirePixelList(width,height); if (pixel_list[i] == (PixelList *) NULL) return(DestroyPixelListThreadSet(pixel_list)); } return(pixel_list); } static void AddNodePixelList(PixelList *pixel_list,const ssize_t channel, const size_t color) { register SkipList *list; register ssize_t level; size_t search, update[9]; /* Initialize the node. */ list=pixel_list->lists+channel; list->nodes[color].signature=pixel_list->signature; list->nodes[color].count=1; /* Determine where it belongs in the list. */ search=65536UL; for (level=list->level; level >= 0; level--) { while (list->nodes[search].next[level] < color) search=list->nodes[search].next[level]; update[level]=search; } /* Generate a pseudo-random level for this node. */ for (level=0; ; level++) { pixel_list->seed=(pixel_list->seed*42893621L)+1L; if ((pixel_list->seed & 0x300) != 0x300) break; } if (level > 8) level=8; if (level > (list->level+2)) level=list->level+2; /* If we're raising the list's level, link back to the root node. */ while (level > list->level) { list->level++; update[list->level]=65536UL; } /* Link the node into the skip-list. */ do { list->nodes[color].next[level]=list->nodes[update[level]].next[level]; list->nodes[update[level]].next[level]=color; } while (level-- > 0); } static void GetMaximumPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color, maximum; ssize_t count; unsigned short channels[ListChannels]; /* Find the maximum value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; maximum=list->nodes[color].next[0]; do { color=list->nodes[color].next[0]; if (color > maximum) maximum=color; count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); channels[channel]=(unsigned short) maximum; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetMeanPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { MagickRealType sum; register SkipList *list; register ssize_t channel; size_t color; ssize_t count; unsigned short channels[ListChannels]; /* Find the mean value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; sum=0.0; do { color=list->nodes[color].next[0]; sum+=(MagickRealType) list->nodes[color].count*color; count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; channels[channel]=(unsigned short) sum; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetMedianPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color; ssize_t count; unsigned short channels[ListChannels]; /* Find the median value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; do { color=list->nodes[color].next[0]; count+=list->nodes[color].count; } while (count <= (ssize_t) (pixel_list->length >> 1)); channels[channel]=(unsigned short) color; } GetMagickPixelPacket((const Image *) NULL,pixel); pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetMinimumPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color, minimum; ssize_t count; unsigned short channels[ListChannels]; /* Find the minimum value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; count=0; color=65536UL; minimum=list->nodes[color].next[0]; do { color=list->nodes[color].next[0]; if (color < minimum) minimum=color; count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); channels[channel]=(unsigned short) minimum; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetModePixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color, max_count, mode; ssize_t count; unsigned short channels[5]; /* Make each pixel the 'predominant color' of the specified neighborhood. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; mode=color; max_count=list->nodes[mode].count; count=0; do { color=list->nodes[color].next[0]; if (list->nodes[color].count > max_count) { mode=color; max_count=list->nodes[mode].count; } count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); channels[channel]=(unsigned short) mode; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetNonpeakPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color, next, previous; ssize_t count; unsigned short channels[5]; /* Finds the non peak value for each of the colors. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; next=list->nodes[color].next[0]; count=0; do { previous=color; color=next; next=list->nodes[color].next[0]; count+=list->nodes[color].count; } while (count <= (ssize_t) (pixel_list->length >> 1)); if ((previous == 65536UL) && (next != 65536UL)) color=next; else if ((previous != 65536UL) && (next == 65536UL)) color=previous; channels[channel]=(unsigned short) color; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetRootMeanSquarePixelList(PixelList *pixel_list, MagickPixelPacket *pixel) { MagickRealType sum; register SkipList *list; register ssize_t channel; size_t color; ssize_t count; unsigned short channels[ListChannels]; /* Find the root mean square value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; sum=0.0; do { color=list->nodes[color].next[0]; sum+=(MagickRealType) (list->nodes[color].count*color*color); count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; channels[channel]=(unsigned short) sqrt(sum); } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetStandardDeviationPixelList(PixelList *pixel_list, MagickPixelPacket *pixel) { MagickRealType sum, sum_squared; register SkipList *list; register ssize_t channel; size_t color; ssize_t count; unsigned short channels[ListChannels]; /* Find the standard-deviation value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; sum=0.0; sum_squared=0.0; do { register ssize_t i; color=list->nodes[color].next[0]; sum+=(MagickRealType) list->nodes[color].count*color; for (i=0; i < (ssize_t) list->nodes[color].count; i++) sum_squared+=((MagickRealType) color)*((MagickRealType) color); count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; sum_squared/=pixel_list->length; channels[channel]=(unsigned short) sqrt(sum_squared-(sum*sum)); } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static inline void InsertPixelList(const Image *image,const PixelPacket *pixel, const IndexPacket *indexes,PixelList *pixel_list) { size_t signature; unsigned short index; index=ScaleQuantumToShort(GetPixelRed(pixel)); signature=pixel_list->lists[0].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[0].nodes[index].count++; else AddNodePixelList(pixel_list,0,index); index=ScaleQuantumToShort(GetPixelGreen(pixel)); signature=pixel_list->lists[1].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[1].nodes[index].count++; else AddNodePixelList(pixel_list,1,index); index=ScaleQuantumToShort(GetPixelBlue(pixel)); signature=pixel_list->lists[2].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[2].nodes[index].count++; else AddNodePixelList(pixel_list,2,index); index=ScaleQuantumToShort(GetPixelOpacity(pixel)); signature=pixel_list->lists[3].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[3].nodes[index].count++; else AddNodePixelList(pixel_list,3,index); if (image->colorspace == CMYKColorspace) index=ScaleQuantumToShort(GetPixelIndex(indexes)); signature=pixel_list->lists[4].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[4].nodes[index].count++; else AddNodePixelList(pixel_list,4,index); } static void ResetPixelList(PixelList *pixel_list) { int level; register ListNode *root; register SkipList *list; register ssize_t channel; /* Reset the skip-list. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; root=list->nodes+65536UL; list->level=0; for (level=0; level < 9; level++) root->next[level]=65536UL; } pixel_list->seed=pixel_list->signature++; } MagickExport Image *StatisticImage(const Image *image,const StatisticType type, const size_t width,const size_t height,ExceptionInfo *exception) { Image *statistic_image; statistic_image=StatisticImageChannel(image,DefaultChannels,type,width, height,exception); return(statistic_image); } MagickExport Image *StatisticImageChannel(const Image *image, const ChannelType channel,const StatisticType type,const size_t width, const size_t height,ExceptionInfo *exception) { #define StatisticImageTag "Statistic/Image" CacheView *image_view, *statistic_view; Image *statistic_image; MagickBooleanType status; MagickOffsetType progress; PixelList **magick_restrict pixel_list; size_t neighbor_height, neighbor_width; ssize_t y; /* Initialize statistics image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); statistic_image=CloneImage(image,0,0,MagickTrue,exception); if (statistic_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(statistic_image,DirectClass) == MagickFalse) { InheritException(exception,&statistic_image->exception); statistic_image=DestroyImage(statistic_image); return((Image *) NULL); } neighbor_width=width == 0 ? GetOptimalKernelWidth2D((double) width,0.5) : width; neighbor_height=height == 0 ? GetOptimalKernelWidth2D((double) height,0.5) : height; pixel_list=AcquirePixelListThreadSet(neighbor_width,neighbor_height); if (pixel_list == (PixelList **) NULL) { statistic_image=DestroyImage(statistic_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Make each pixel the min / max / median / mode / etc. of the neighborhood. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); statistic_view=AcquireAuthenticCacheView(statistic_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,statistic_image,statistic_image->rows,1) #endif for (y=0; y < (ssize_t) statistic_image->rows; y++) { const int id = GetOpenMPThreadId(); register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict statistic_indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) neighbor_width/2L),y- (ssize_t) (neighbor_height/2L),image->columns+neighbor_width, neighbor_height,exception); q=QueueCacheViewAuthenticPixels(statistic_view,0,y,statistic_image->columns, 1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); statistic_indexes=GetCacheViewAuthenticIndexQueue(statistic_view); for (x=0; x < (ssize_t) statistic_image->columns; x++) { MagickPixelPacket pixel; register const IndexPacket *magick_restrict s; register const PixelPacket *magick_restrict r; register ssize_t u, v; r=p; s=indexes+x; ResetPixelList(pixel_list[id]); for (v=0; v < (ssize_t) neighbor_height; v++) { for (u=0; u < (ssize_t) neighbor_width; u++) InsertPixelList(image,r+u,s+u,pixel_list[id]); r+=image->columns+neighbor_width; s+=image->columns+neighbor_width; } GetMagickPixelPacket(image,&pixel); SetMagickPixelPacket(image,p+neighbor_width*neighbor_height/2,indexes+x+ neighbor_width*neighbor_height/2,&pixel); switch (type) { case GradientStatistic: { MagickPixelPacket maximum, minimum; GetMinimumPixelList(pixel_list[id],&pixel); minimum=pixel; GetMaximumPixelList(pixel_list[id],&pixel); maximum=pixel; pixel.red=MagickAbsoluteValue(maximum.red-minimum.red); pixel.green=MagickAbsoluteValue(maximum.green-minimum.green); pixel.blue=MagickAbsoluteValue(maximum.blue-minimum.blue); pixel.opacity=MagickAbsoluteValue(maximum.opacity-minimum.opacity); if (image->colorspace == CMYKColorspace) pixel.index=MagickAbsoluteValue(maximum.index-minimum.index); break; } case MaximumStatistic: { GetMaximumPixelList(pixel_list[id],&pixel); break; } case MeanStatistic: { GetMeanPixelList(pixel_list[id],&pixel); break; } case MedianStatistic: default: { GetMedianPixelList(pixel_list[id],&pixel); break; } case MinimumStatistic: { GetMinimumPixelList(pixel_list[id],&pixel); break; } case ModeStatistic: { GetModePixelList(pixel_list[id],&pixel); break; } case NonpeakStatistic: { GetNonpeakPixelList(pixel_list[id],&pixel); break; } case RootMeanSquareStatistic: { GetRootMeanSquarePixelList(pixel_list[id],&pixel); break; } case StandardDeviationStatistic: { GetStandardDeviationPixelList(pixel_list[id],&pixel); break; } } if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(pixel.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(pixel.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(pixel.blue)); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,ClampToQuantum(pixel.opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(statistic_indexes+x,ClampToQuantum(pixel.index)); p++; q++; } if (SyncCacheViewAuthenticPixels(statistic_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,StatisticImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } statistic_view=DestroyCacheView(statistic_view); image_view=DestroyCacheView(image_view); pixel_list=DestroyPixelListThreadSet(pixel_list); if (status == MagickFalse) statistic_image=DestroyImage(statistic_image); return(statistic_image); }
null
129
CWE-787
CVE-2019-13308
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % FFFFF OOO U U RRRR IIIII EEEEE RRRR % % F O O U U R R I E R R % % FFF O O U U RRRR I EEE RRRR % % F O O U U R R I E R R % % F OOO UUU R R IIIII EEEEE R R % % % % % % MagickCore Discrete Fourier Transform Methods % % % % Software Design % % Sean Burke % % Fred Weinhaus % % Cristy % % July 2009 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/cache.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/fourier.h" #include "magick/log.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/property.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #if defined(MAGICKCORE_FFTW_DELEGATE) #if defined(MAGICKCORE_HAVE_COMPLEX_H) #include <complex.h> #endif #include <fftw3.h> #if !defined(MAGICKCORE_HAVE_CABS) #define cabs(z) (sqrt(z[0]*z[0]+z[1]*z[1])) #endif #if !defined(MAGICKCORE_HAVE_CARG) #define carg(z) (atan2(cimag(z),creal(z))) #endif #if !defined(MAGICKCORE_HAVE_CIMAG) #define cimag(z) (z[1]) #endif #if !defined(MAGICKCORE_HAVE_CREAL) #define creal(z) (z[0]) #endif #endif /* Typedef declarations. */ typedef struct _FourierInfo { ChannelType channel; MagickBooleanType modulus; size_t width, height; ssize_t center; } FourierInfo; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p l e x I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ComplexImages() performs complex mathematics on an image sequence. % % The format of the ComplexImages method is: % % MagickBooleanType ComplexImages(Image *images,const ComplexOperator op, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o op: A complex operator. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op, ExceptionInfo *exception) { #define ComplexImageTag "Complex/Image" CacheView *Ai_view, *Ar_view, *Bi_view, *Br_view, *Ci_view, *Cr_view; const char *artifact; const Image *Ai_image, *Ar_image, *Bi_image, *Br_image; double snr; Image *Ci_image, *complex_images, *Cr_image, *image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (images->next == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",images->filename); return((Image *) NULL); } image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { image=DestroyImageList(image); return(image); } image->depth=32UL; complex_images=NewImageList(); AppendImageToList(&complex_images,image); image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) { complex_images=DestroyImageList(complex_images); return(complex_images); } AppendImageToList(&complex_images,image); /* Apply complex mathematics to image pixels. */ artifact=GetImageArtifact(image,"complex:snr"); snr=0.0; if (artifact != (const char *) NULL) snr=StringToDouble(artifact,(char **) NULL); Ar_image=images; Ai_image=images->next; Br_image=images; Bi_image=images->next; if ((images->next->next != (Image *) NULL) && (images->next->next->next != (Image *) NULL)) { Br_image=images->next->next; Bi_image=images->next->next->next; } Cr_image=complex_images; Ci_image=complex_images->next; Ar_view=AcquireVirtualCacheView(Ar_image,exception); Ai_view=AcquireVirtualCacheView(Ai_image,exception); Br_view=AcquireVirtualCacheView(Br_image,exception); Bi_view=AcquireVirtualCacheView(Bi_image,exception); Cr_view=AcquireAuthenticCacheView(Cr_image,exception); Ci_view=AcquireAuthenticCacheView(Ci_image,exception); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(images,complex_images,images->rows,1L) #endif for (y=0; y < (ssize_t) images->rows; y++) { register const PixelPacket *magick_restrict Ai, *magick_restrict Ar, *magick_restrict Bi, *magick_restrict Br; register PixelPacket *magick_restrict Ci, *magick_restrict Cr; register ssize_t x; if (status == MagickFalse) continue; Ar=GetCacheViewVirtualPixels(Ar_view,0,y, MagickMax(Ar_image->columns,Cr_image->columns),1,exception); Ai=GetCacheViewVirtualPixels(Ai_view,0,y, MagickMax(Ai_image->columns,Ci_image->columns),1,exception); Br=GetCacheViewVirtualPixels(Br_view,0,y, MagickMax(Br_image->columns,Cr_image->columns),1,exception); Bi=GetCacheViewVirtualPixels(Bi_view,0,y, MagickMax(Bi_image->columns,Ci_image->columns),1,exception); Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception); Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception); if ((Ar == (const PixelPacket *) NULL) || (Ai == (const PixelPacket *) NULL) || (Br == (const PixelPacket *) NULL) || (Bi == (const PixelPacket *) NULL) || (Cr == (PixelPacket *) NULL) || (Ci == (PixelPacket *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) images->columns; x++) { switch (op) { case AddComplexOperator: { Cr->red=Ar->red+Br->red; Ci->red=Ai->red+Bi->red; Cr->green=Ar->green+Br->green; Ci->green=Ai->green+Bi->green; Cr->blue=Ar->blue+Br->blue; Ci->blue=Ai->blue+Bi->blue; if (images->matte != MagickFalse) { Cr->opacity=Ar->opacity+Br->opacity; Ci->opacity=Ai->opacity+Bi->opacity; } break; } case ConjugateComplexOperator: default: { Cr->red=Ar->red; Ci->red=(-Bi->red); Cr->green=Ar->green; Ci->green=(-Bi->green); Cr->blue=Ar->blue; Ci->blue=(-Bi->blue); if (images->matte != MagickFalse) { Cr->opacity=Ar->opacity; Ci->opacity=(-Bi->opacity); } break; } case DivideComplexOperator: { double gamma; gamma=PerceptibleReciprocal(Br->red*Br->red+Bi->red*Bi->red+snr); Cr->red=gamma*(Ar->red*Br->red+Ai->red*Bi->red); Ci->red=gamma*(Ai->red*Br->red-Ar->red*Bi->red); gamma=PerceptibleReciprocal(Br->green*Br->green+Bi->green*Bi->green+ snr); Cr->green=gamma*(Ar->green*Br->green+Ai->green*Bi->green); Ci->green=gamma*(Ai->green*Br->green-Ar->green*Bi->green); gamma=PerceptibleReciprocal(Br->blue*Br->blue+Bi->blue*Bi->blue+snr); Cr->blue=gamma*(Ar->blue*Br->blue+Ai->blue*Bi->blue); Ci->blue=gamma*(Ai->blue*Br->blue-Ar->blue*Bi->blue); if (images->matte != MagickFalse) { gamma=PerceptibleReciprocal(Br->opacity*Br->opacity+Bi->opacity* Bi->opacity+snr); Cr->opacity=gamma*(Ar->opacity*Br->opacity+Ai->opacity* Bi->opacity); Ci->opacity=gamma*(Ai->opacity*Br->opacity-Ar->opacity* Bi->opacity); } break; } case MagnitudePhaseComplexOperator: { Cr->red=sqrt(Ar->red*Ar->red+Ai->red*Ai->red); Ci->red=atan2(Ai->red,Ar->red)/(2.0*MagickPI)+0.5; Cr->green=sqrt(Ar->green*Ar->green+Ai->green*Ai->green); Ci->green=atan2(Ai->green,Ar->green)/(2.0*MagickPI)+0.5; Cr->blue=sqrt(Ar->blue*Ar->blue+Ai->blue*Ai->blue); Ci->blue=atan2(Ai->blue,Ar->blue)/(2.0*MagickPI)+0.5; if (images->matte != MagickFalse) { Cr->opacity=sqrt(Ar->opacity*Ar->opacity+Ai->opacity*Ai->opacity); Ci->opacity=atan2(Ai->opacity,Ar->opacity)/(2.0*MagickPI)+0.5; } break; } case MultiplyComplexOperator: { Cr->red=QuantumScale*(Ar->red*Br->red-Ai->red*Bi->red); Ci->red=QuantumScale*(Ai->red*Br->red+Ar->red*Bi->red); Cr->green=QuantumScale*(Ar->green*Br->green-Ai->green*Bi->green); Ci->green=QuantumScale*(Ai->green*Br->green+Ar->green*Bi->green); Cr->blue=QuantumScale*(Ar->blue*Br->blue-Ai->blue*Bi->blue); Ci->blue=QuantumScale*(Ai->blue*Br->blue+Ar->blue*Bi->blue); if (images->matte != MagickFalse) { Cr->opacity=QuantumScale*(Ar->opacity*Br->opacity-Ai->opacity* Bi->opacity); Ci->opacity=QuantumScale*(Ai->opacity*Br->opacity+Ar->opacity* Bi->opacity); } break; } case RealImaginaryComplexOperator: { Cr->red=Ar->red*cos(2.0*MagickPI*(Ai->red-0.5)); Ci->red=Ar->red*sin(2.0*MagickPI*(Ai->red-0.5)); Cr->green=Ar->green*cos(2.0*MagickPI*(Ai->green-0.5)); Ci->green=Ar->green*sin(2.0*MagickPI*(Ai->green-0.5)); Cr->blue=Ar->blue*cos(2.0*MagickPI*(Ai->blue-0.5)); Ci->blue=Ar->blue*sin(2.0*MagickPI*(Ai->blue-0.5)); if (images->matte != MagickFalse) { Cr->opacity=Ar->opacity*cos(2.0*MagickPI*(Ai->opacity-0.5)); Ci->opacity=Ar->opacity*sin(2.0*MagickPI*(Ai->opacity-0.5)); } break; } case SubtractComplexOperator: { Cr->red=Ar->red-Br->red; Ci->red=Ai->red-Bi->red; Cr->green=Ar->green-Br->green; Ci->green=Ai->green-Bi->green; Cr->blue=Ar->blue-Br->blue; Ci->blue=Ai->blue-Bi->blue; if (images->matte != MagickFalse) { Cr->opacity=Ar->opacity-Br->opacity; Ci->opacity=Ai->opacity-Bi->opacity; } break; } } Ar++; Ai++; Br++; Bi++; Cr++; Ci++; } if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse) status=MagickFalse; if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows); if (proceed == MagickFalse) status=MagickFalse; } } Cr_view=DestroyCacheView(Cr_view); Ci_view=DestroyCacheView(Ci_view); Br_view=DestroyCacheView(Br_view); Bi_view=DestroyCacheView(Bi_view); Ar_view=DestroyCacheView(Ar_view); Ai_view=DestroyCacheView(Ai_view); if (status == MagickFalse) complex_images=DestroyImageList(complex_images); return(complex_images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F o r w a r d F o u r i e r T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ForwardFourierTransformImage() implements the discrete Fourier transform % (DFT) of the image either as a magnitude / phase or real / imaginary image % pair. % % The format of the ForwadFourierTransformImage method is: % % Image *ForwardFourierTransformImage(const Image *image, % const MagickBooleanType modulus,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o modulus: if true, return as transform as a magnitude / phase pair % otherwise a real / imaginary image pair. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FFTW_DELEGATE) static MagickBooleanType RollFourier(const size_t width,const size_t height, const ssize_t x_offset,const ssize_t y_offset,double *roll_pixels) { double *source_pixels; MemoryInfo *source_info; register ssize_t i, x; ssize_t u, v, y; /* Move zero frequency (DC, average color) from (0,0) to (width/2,height/2). */ source_info=AcquireVirtualMemory(width,height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) return(MagickFalse); source_pixels=(double *) GetVirtualMemoryBlob(source_info); i=0L; for (y=0L; y < (ssize_t) height; y++) { if (y_offset < 0L) v=((y+y_offset) < 0L) ? y+y_offset+(ssize_t) height : y+y_offset; else v=((y+y_offset) > ((ssize_t) height-1L)) ? y+y_offset-(ssize_t) height : y+y_offset; for (x=0L; x < (ssize_t) width; x++) { if (x_offset < 0L) u=((x+x_offset) < 0L) ? x+x_offset+(ssize_t) width : x+x_offset; else u=((x+x_offset) > ((ssize_t) width-1L)) ? x+x_offset-(ssize_t) width : x+x_offset; source_pixels[v*width+u]=roll_pixels[i++]; } } (void) memcpy(roll_pixels,source_pixels,height*width* sizeof(*source_pixels)); source_info=RelinquishVirtualMemory(source_info); return(MagickTrue); } static MagickBooleanType ForwardQuadrantSwap(const size_t width, const size_t height,double *source_pixels,double *forward_pixels) { MagickBooleanType status; register ssize_t x; ssize_t center, y; /* Swap quadrants. */ center=(ssize_t) (width/2L)+1L; status=RollFourier((size_t) center,height,0L,(ssize_t) height/2L, source_pixels); if (status == MagickFalse) return(MagickFalse); for (y=0L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[y*width+x+width/2L]=source_pixels[y*center+x]; for (y=1; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[(height-y)*width+width/2L-x-1L]= source_pixels[y*center+x+1L]; for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[width/2L-x-1L]=source_pixels[x+1L]; return(MagickTrue); } static void CorrectPhaseLHS(const size_t width,const size_t height, double *fourier_pixels) { register ssize_t x; ssize_t y; for (y=0L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) fourier_pixels[y*width+x]*=(-1.0); } static MagickBooleanType ForwardFourier(const FourierInfo *fourier_info, Image *image,double *magnitude,double *phase,ExceptionInfo *exception) { CacheView *magnitude_view, *phase_view; double *magnitude_pixels, *phase_pixels; Image *magnitude_image, *phase_image; MagickBooleanType status; MemoryInfo *magnitude_info, *phase_info; register IndexPacket *indexes; register PixelPacket *q; register ssize_t x; ssize_t i, y; magnitude_image=GetFirstImageInList(image); phase_image=GetNextImageInList(image); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",image->filename); return(MagickFalse); } /* Create "Fourier Transform" image from constituent arrays. */ magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*phase_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL)) { if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (magnitude_info != (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); (void) memset(magnitude_pixels,0,fourier_info->width* fourier_info->height*sizeof(*magnitude_pixels)); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); (void) memset(phase_pixels,0,fourier_info->width* fourier_info->height*sizeof(*phase_pixels)); status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height, magnitude,magnitude_pixels); if (status != MagickFalse) status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height,phase, phase_pixels); CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels); if (fourier_info->modulus != MagickFalse) { i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->width; x++) { phase_pixels[i]/=(2.0*MagickPI); phase_pixels[i]+=0.5; i++; } } magnitude_view=AcquireAuthenticCacheView(magnitude_image,exception); i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) { q=GetCacheViewAuthenticPixels(magnitude_view,0L,y,fourier_info->width,1UL, exception); if (q == (PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(magnitude_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { SetPixelRed(q,ClampToQuantum(QuantumRange*magnitude_pixels[i])); break; } case GreenChannel: { SetPixelGreen(q,ClampToQuantum(QuantumRange*magnitude_pixels[i])); break; } case BlueChannel: { SetPixelBlue(q,ClampToQuantum(QuantumRange*magnitude_pixels[i])); break; } case OpacityChannel: { SetPixelOpacity(q,ClampToQuantum(QuantumRange*magnitude_pixels[i])); break; } case IndexChannel: { SetPixelIndex(indexes+x,ClampToQuantum(QuantumRange* magnitude_pixels[i])); break; } case GrayChannels: { SetPixelGray(q,ClampToQuantum(QuantumRange*magnitude_pixels[i])); break; } } i++; q++; } status=SyncCacheViewAuthenticPixels(magnitude_view,exception); if (status == MagickFalse) break; } magnitude_view=DestroyCacheView(magnitude_view); i=0L; phase_view=AcquireAuthenticCacheView(phase_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { q=GetCacheViewAuthenticPixels(phase_view,0L,y,fourier_info->width,1UL, exception); if (q == (PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(phase_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { SetPixelRed(q,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } case GreenChannel: { SetPixelGreen(q,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } case BlueChannel: { SetPixelBlue(q,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } case OpacityChannel: { SetPixelOpacity(q,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } case IndexChannel: { SetPixelIndex(indexes+x,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } case GrayChannels: { SetPixelGray(q,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } } i++; q++; } status=SyncCacheViewAuthenticPixels(phase_view,exception); if (status == MagickFalse) break; } phase_view=DestroyCacheView(phase_view); phase_info=RelinquishVirtualMemory(phase_info); magnitude_info=RelinquishVirtualMemory(magnitude_info); return(status); } static MagickBooleanType ForwardFourierTransform(FourierInfo *fourier_info, const Image *image,double *magnitude_pixels,double *phase_pixels, ExceptionInfo *exception) { CacheView *image_view; const char *value; double *source_pixels; fftw_complex *forward_pixels; fftw_plan fftw_r2c_plan; MemoryInfo *forward_info, *source_info; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t i, x; ssize_t y; /* Generate the forward Fourier transform. */ source_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } source_pixels=(double *) GetVirtualMemoryBlob(source_info); memset(source_pixels,0,fourier_info->width*fourier_info->height* sizeof(*source_pixels)); i=0L; image_view=AcquireVirtualCacheView(image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(image_view,0L,y,fourier_info->width,1UL, exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { source_pixels[i]=QuantumScale*GetPixelRed(p); break; } case GreenChannel: { source_pixels[i]=QuantumScale*GetPixelGreen(p); break; } case BlueChannel: { source_pixels[i]=QuantumScale*GetPixelBlue(p); break; } case OpacityChannel: { source_pixels[i]=QuantumScale*GetPixelOpacity(p); break; } case IndexChannel: { source_pixels[i]=QuantumScale*GetPixelIndex(indexes+x); break; } case GrayChannels: { source_pixels[i]=QuantumScale*GetPixelGray(p); break; } } i++; p++; } } image_view=DestroyCacheView(image_view); forward_info=AcquireVirtualMemory((size_t) fourier_info->width, (fourier_info->height/2+1)*sizeof(*forward_pixels)); if (forward_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info); return(MagickFalse); } forward_pixels=(fftw_complex *) GetVirtualMemoryBlob(forward_info); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ForwardFourierTransform) #endif fftw_r2c_plan=fftw_plan_dft_r2c_2d(fourier_info->width,fourier_info->height, source_pixels,forward_pixels,FFTW_ESTIMATE); fftw_execute_dft_r2c(fftw_r2c_plan,source_pixels,forward_pixels); fftw_destroy_plan(fftw_r2c_plan); source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info); value=GetImageArtifact(image,"fourier:normalize"); if ((value == (const char *) NULL) || (LocaleCompare(value,"forward") == 0)) { double gamma; /* Normalize Fourier transform. */ i=0L; gamma=PerceptibleReciprocal((double) fourier_info->width* fourier_info->height); for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) forward_pixels[i]*=gamma; #else forward_pixels[i][0]*=gamma; forward_pixels[i][1]*=gamma; #endif i++; } } /* Generate magnitude and phase (or real and imaginary). */ i=0L; if (fourier_info->modulus != MagickFalse) for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { magnitude_pixels[i]=cabs(forward_pixels[i]); phase_pixels[i]=carg(forward_pixels[i]); i++; } else for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { magnitude_pixels[i]=creal(forward_pixels[i]); phase_pixels[i]=cimag(forward_pixels[i]); i++; } forward_info=(MemoryInfo *) RelinquishVirtualMemory(forward_info); return(MagickTrue); } static MagickBooleanType ForwardFourierTransformChannel(const Image *image, const ChannelType channel,const MagickBooleanType modulus, Image *fourier_image,ExceptionInfo *exception) { double *magnitude_pixels, *phase_pixels; FourierInfo fourier_info; MagickBooleanType status; MemoryInfo *magnitude_info, *phase_info; fourier_info.width=image->columns; fourier_info.height=image->rows; if ((image->columns != image->rows) || ((image->columns % 2) != 0) || ((image->rows % 2) != 0)) { size_t extent=image->columns < image->rows ? image->rows : image->columns; fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent; } fourier_info.height=fourier_info.width; fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L; fourier_info.channel=channel; fourier_info.modulus=modulus; magnitude_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*phase_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL)) { if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (magnitude_info == (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); status=ForwardFourierTransform(&fourier_info,image,magnitude_pixels, phase_pixels,exception); if (status != MagickFalse) status=ForwardFourier(&fourier_info,fourier_image,magnitude_pixels, phase_pixels,exception); phase_info=RelinquishVirtualMemory(phase_info); magnitude_info=RelinquishVirtualMemory(magnitude_info); return(status); } #endif MagickExport Image *ForwardFourierTransformImage(const Image *image, const MagickBooleanType modulus,ExceptionInfo *exception) { Image *fourier_image; fourier_image=NewImageList(); #if !defined(MAGICKCORE_FFTW_DELEGATE) (void) modulus; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)", image->filename); #else { Image *magnitude_image; size_t height, width; width=image->columns; height=image->rows; if ((image->columns != image->rows) || ((image->columns % 2) != 0) || ((image->rows % 2) != 0)) { size_t extent=image->columns < image->rows ? image->rows : image->columns; width=(extent & 0x01) == 1 ? extent+1UL : extent; } height=width; magnitude_image=CloneImage(image,width,height,MagickTrue,exception); if (magnitude_image != (Image *) NULL) { Image *phase_image; magnitude_image->storage_class=DirectClass; magnitude_image->depth=32UL; phase_image=CloneImage(image,width,height,MagickTrue,exception); if (phase_image == (Image *) NULL) magnitude_image=DestroyImage(magnitude_image); else { MagickBooleanType is_gray, status; phase_image->storage_class=DirectClass; phase_image->depth=32UL; AppendImageToList(&fourier_image,magnitude_image); AppendImageToList(&fourier_image,phase_image); status=MagickTrue; is_gray=IsGrayImage(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel sections #endif { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; if (is_gray != MagickFalse) thread_status=ForwardFourierTransformChannel(image, GrayChannels,modulus,fourier_image,exception); else thread_status=ForwardFourierTransformChannel(image,RedChannel, modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=ForwardFourierTransformChannel(image, GreenChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=ForwardFourierTransformChannel(image, BlueChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (image->matte != MagickFalse) thread_status=ForwardFourierTransformChannel(image, OpacityChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (image->colorspace == CMYKColorspace) thread_status=ForwardFourierTransformChannel(image, IndexChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } } if (status == MagickFalse) fourier_image=DestroyImageList(fourier_image); fftw_cleanup(); } } } #endif return(fourier_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n v e r s e F o u r i e r T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InverseFourierTransformImage() implements the inverse discrete Fourier % transform (DFT) of the image either as a magnitude / phase or real / % imaginary image pair. % % The format of the InverseFourierTransformImage method is: % % Image *InverseFourierTransformImage(const Image *magnitude_image, % const Image *phase_image,const MagickBooleanType modulus, % ExceptionInfo *exception) % % A description of each parameter follows: % % o magnitude_image: the magnitude or real image. % % o phase_image: the phase or imaginary image. % % o modulus: if true, return transform as a magnitude / phase pair % otherwise a real / imaginary image pair. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FFTW_DELEGATE) static MagickBooleanType InverseQuadrantSwap(const size_t width, const size_t height,const double *source,double *destination) { register ssize_t x; ssize_t center, y; /* Swap quadrants. */ center=(ssize_t) (width/2L)+1L; for (y=1L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L+1L); x++) destination[(height-y)*center-x+width/2L]=source[y*width+x]; for (y=0L; y < (ssize_t) height; y++) destination[y*center]=source[y*width+width/2L]; for (x=0L; x < center; x++) destination[x]=source[center-x-1L]; return(RollFourier(center,height,0L,(ssize_t) height/-2L,destination)); } static MagickBooleanType InverseFourier(FourierInfo *fourier_info, const Image *magnitude_image,const Image *phase_image, fftw_complex *fourier_pixels,ExceptionInfo *exception) { CacheView *magnitude_view, *phase_view; double *inverse_pixels, *magnitude_pixels, *phase_pixels; MagickBooleanType status; MemoryInfo *inverse_info, *magnitude_info, *phase_info; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t i, x; ssize_t y; /* Inverse Fourier - read image and break down into a double array. */ magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*phase_pixels)); inverse_info=AcquireVirtualMemory((size_t) fourier_info->width, (fourier_info->height/2+1)*sizeof(*inverse_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL) || (inverse_info == (MemoryInfo *) NULL)) { if (magnitude_info != (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (inverse_info != (MemoryInfo *) NULL) inverse_info=RelinquishVirtualMemory(inverse_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); inverse_pixels=(double *) GetVirtualMemoryBlob(inverse_info); i=0L; magnitude_view=AcquireVirtualCacheView(magnitude_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(magnitude_view,0L,y,fourier_info->width,1UL, exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(magnitude_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { magnitude_pixels[i]=QuantumScale*GetPixelRed(p); break; } case GreenChannel: { magnitude_pixels[i]=QuantumScale*GetPixelGreen(p); break; } case BlueChannel: { magnitude_pixels[i]=QuantumScale*GetPixelBlue(p); break; } case OpacityChannel: { magnitude_pixels[i]=QuantumScale*GetPixelOpacity(p); break; } case IndexChannel: { magnitude_pixels[i]=QuantumScale*GetPixelIndex(indexes+x); break; } case GrayChannels: { magnitude_pixels[i]=QuantumScale*GetPixelGray(p); break; } } i++; p++; } } magnitude_view=DestroyCacheView(magnitude_view); status=InverseQuadrantSwap(fourier_info->width,fourier_info->height, magnitude_pixels,inverse_pixels); (void) memcpy(magnitude_pixels,inverse_pixels,fourier_info->height* fourier_info->center*sizeof(*magnitude_pixels)); i=0L; phase_view=AcquireVirtualCacheView(phase_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(phase_view,0,y,fourier_info->width,1, exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(phase_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { phase_pixels[i]=QuantumScale*GetPixelRed(p); break; } case GreenChannel: { phase_pixels[i]=QuantumScale*GetPixelGreen(p); break; } case BlueChannel: { phase_pixels[i]=QuantumScale*GetPixelBlue(p); break; } case OpacityChannel: { phase_pixels[i]=QuantumScale*GetPixelOpacity(p); break; } case IndexChannel: { phase_pixels[i]=QuantumScale*GetPixelIndex(indexes+x); break; } case GrayChannels: { phase_pixels[i]=QuantumScale*GetPixelGray(p); break; } } i++; p++; } } if (fourier_info->modulus != MagickFalse) { i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->width; x++) { phase_pixels[i]-=0.5; phase_pixels[i]*=(2.0*MagickPI); i++; } } phase_view=DestroyCacheView(phase_view); CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels); if (status != MagickFalse) status=InverseQuadrantSwap(fourier_info->width,fourier_info->height, phase_pixels,inverse_pixels); (void) memcpy(phase_pixels,inverse_pixels,fourier_info->height* fourier_info->center*sizeof(*phase_pixels)); inverse_info=RelinquishVirtualMemory(inverse_info); /* Merge two sets. */ i=0L; if (fourier_info->modulus != MagickFalse) for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]=magnitude_pixels[i]*cos(phase_pixels[i])+I* magnitude_pixels[i]*sin(phase_pixels[i]); #else fourier_pixels[i][0]=magnitude_pixels[i]*cos(phase_pixels[i]); fourier_pixels[i][1]=magnitude_pixels[i]*sin(phase_pixels[i]); #endif i++; } else for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]=magnitude_pixels[i]+I*phase_pixels[i]; #else fourier_pixels[i][0]=magnitude_pixels[i]; fourier_pixels[i][1]=phase_pixels[i]; #endif i++; } magnitude_info=RelinquishVirtualMemory(magnitude_info); phase_info=RelinquishVirtualMemory(phase_info); return(status); } static MagickBooleanType InverseFourierTransform(FourierInfo *fourier_info, fftw_complex *fourier_pixels,Image *image,ExceptionInfo *exception) { CacheView *image_view; double *source_pixels; const char *value; fftw_plan fftw_c2r_plan; MemoryInfo *source_info; register IndexPacket *indexes; register PixelPacket *q; register ssize_t i, x; ssize_t y; source_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } source_pixels=(double *) GetVirtualMemoryBlob(source_info); value=GetImageArtifact(image,"fourier:normalize"); if (LocaleCompare(value,"inverse") == 0) { double gamma; /* Normalize inverse transform. */ i=0L; gamma=PerceptibleReciprocal((double) fourier_info->width* fourier_info->height); for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]*=gamma; #else fourier_pixels[i][0]*=gamma; fourier_pixels[i][1]*=gamma; #endif i++; } } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_InverseFourierTransform) #endif fftw_c2r_plan=fftw_plan_dft_c2r_2d(fourier_info->width,fourier_info->height, fourier_pixels,source_pixels,FFTW_ESTIMATE); fftw_execute_dft_c2r(fftw_c2r_plan,fourier_pixels,source_pixels); fftw_destroy_plan(fftw_c2r_plan); i=0L; image_view=AcquireAuthenticCacheView(image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { if (y >= (ssize_t) image->rows) break; q=GetCacheViewAuthenticPixels(image_view,0L,y,fourier_info->width > image->columns ? image->columns : fourier_info->width,1UL,exception); if (q == (PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { if (x < (ssize_t) image->columns) switch (fourier_info->channel) { case RedChannel: default: { SetPixelRed(q,ClampToQuantum(QuantumRange*source_pixels[i])); break; } case GreenChannel: { SetPixelGreen(q,ClampToQuantum(QuantumRange*source_pixels[i])); break; } case BlueChannel: { SetPixelBlue(q,ClampToQuantum(QuantumRange*source_pixels[i])); break; } case OpacityChannel: { SetPixelOpacity(q,ClampToQuantum(QuantumRange*source_pixels[i])); break; } case IndexChannel: { SetPixelIndex(indexes+x,ClampToQuantum(QuantumRange* source_pixels[i])); break; } case GrayChannels: { SetPixelGray(q,ClampToQuantum(QuantumRange*source_pixels[i])); break; } } i++; q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) break; } image_view=DestroyCacheView(image_view); source_info=RelinquishVirtualMemory(source_info); return(MagickTrue); } static MagickBooleanType InverseFourierTransformChannel( const Image *magnitude_image,const Image *phase_image, const ChannelType channel,const MagickBooleanType modulus, Image *fourier_image,ExceptionInfo *exception) { fftw_complex *inverse_pixels; FourierInfo fourier_info; MagickBooleanType status; MemoryInfo *inverse_info; fourier_info.width=magnitude_image->columns; fourier_info.height=magnitude_image->rows; if ((magnitude_image->columns != magnitude_image->rows) || ((magnitude_image->columns % 2) != 0) || ((magnitude_image->rows % 2) != 0)) { size_t extent=magnitude_image->columns < magnitude_image->rows ? magnitude_image->rows : magnitude_image->columns; fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent; } fourier_info.height=fourier_info.width; fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L; fourier_info.channel=channel; fourier_info.modulus=modulus; inverse_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*inverse_pixels)); if (inverse_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); return(MagickFalse); } inverse_pixels=(fftw_complex *) GetVirtualMemoryBlob(inverse_info); status=InverseFourier(&fourier_info,magnitude_image,phase_image, inverse_pixels,exception); if (status != MagickFalse) status=InverseFourierTransform(&fourier_info,inverse_pixels,fourier_image, exception); inverse_info=RelinquishVirtualMemory(inverse_info); return(status); } #endif MagickExport Image *InverseFourierTransformImage(const Image *magnitude_image, const Image *phase_image,const MagickBooleanType modulus, ExceptionInfo *exception) { Image *fourier_image; assert(magnitude_image != (Image *) NULL); assert(magnitude_image->signature == MagickCoreSignature); if (magnitude_image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", magnitude_image->filename); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",magnitude_image->filename); return((Image *) NULL); } #if !defined(MAGICKCORE_FFTW_DELEGATE) fourier_image=(Image *) NULL; (void) modulus; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)", magnitude_image->filename); #else { fourier_image=CloneImage(magnitude_image,magnitude_image->columns, magnitude_image->rows,MagickTrue,exception); if (fourier_image != (Image *) NULL) { MagickBooleanType is_gray, status; status=MagickTrue; is_gray=IsGrayImage(magnitude_image,exception); if (is_gray != MagickFalse) is_gray=IsGrayImage(phase_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel sections #endif { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; if (is_gray != MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,GrayChannels,modulus,fourier_image,exception); else thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,RedChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,GreenChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,BlueChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (magnitude_image->matte != MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,OpacityChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (magnitude_image->colorspace == CMYKColorspace) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,IndexChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } } if (status == MagickFalse) fourier_image=DestroyImage(fourier_image); } fftw_cleanup(); } #endif return(fourier_image); }
null
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % FFFFF OOO U U RRRR IIIII EEEEE RRRR % % F O O U U R R I E R R % % FFF O O U U RRRR I EEE RRRR % % F O O U U R R I E R R % % F OOO UUU R R IIIII EEEEE R R % % % % % % MagickCore Discrete Fourier Transform Methods % % % % Software Design % % Sean Burke % % Fred Weinhaus % % Cristy % % July 2009 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/cache.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/fourier.h" #include "magick/log.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/property.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #if defined(MAGICKCORE_FFTW_DELEGATE) #if defined(MAGICKCORE_HAVE_COMPLEX_H) #include <complex.h> #endif #include <fftw3.h> #if !defined(MAGICKCORE_HAVE_CABS) #define cabs(z) (sqrt(z[0]*z[0]+z[1]*z[1])) #endif #if !defined(MAGICKCORE_HAVE_CARG) #define carg(z) (atan2(cimag(z),creal(z))) #endif #if !defined(MAGICKCORE_HAVE_CIMAG) #define cimag(z) (z[1]) #endif #if !defined(MAGICKCORE_HAVE_CREAL) #define creal(z) (z[0]) #endif #endif /* Typedef declarations. */ typedef struct _FourierInfo { ChannelType channel; MagickBooleanType modulus; size_t width, height; ssize_t center; } FourierInfo; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p l e x I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ComplexImages() performs complex mathematics on an image sequence. % % The format of the ComplexImages method is: % % MagickBooleanType ComplexImages(Image *images,const ComplexOperator op, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o op: A complex operator. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op, ExceptionInfo *exception) { #define ComplexImageTag "Complex/Image" CacheView *Ai_view, *Ar_view, *Bi_view, *Br_view, *Ci_view, *Cr_view; const char *artifact; const Image *Ai_image, *Ar_image, *Bi_image, *Br_image; double snr; Image *Ci_image, *complex_images, *Cr_image, *image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (images->next == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",images->filename); return((Image *) NULL); } image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { image=DestroyImageList(image); return(image); } image->depth=32UL; complex_images=NewImageList(); AppendImageToList(&complex_images,image); image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) { complex_images=DestroyImageList(complex_images); return(complex_images); } AppendImageToList(&complex_images,image); /* Apply complex mathematics to image pixels. */ artifact=GetImageArtifact(image,"complex:snr"); snr=0.0; if (artifact != (const char *) NULL) snr=StringToDouble(artifact,(char **) NULL); Ar_image=images; Ai_image=images->next; Br_image=images; Bi_image=images->next; if ((images->next->next != (Image *) NULL) && (images->next->next->next != (Image *) NULL)) { Br_image=images->next->next; Bi_image=images->next->next->next; } Cr_image=complex_images; Ci_image=complex_images->next; Ar_view=AcquireVirtualCacheView(Ar_image,exception); Ai_view=AcquireVirtualCacheView(Ai_image,exception); Br_view=AcquireVirtualCacheView(Br_image,exception); Bi_view=AcquireVirtualCacheView(Bi_image,exception); Cr_view=AcquireAuthenticCacheView(Cr_image,exception); Ci_view=AcquireAuthenticCacheView(Ci_image,exception); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(Cr_image,complex_images,Cr_image->rows,1L) #endif for (y=0; y < (ssize_t) Cr_image->rows; y++) { register const PixelPacket *magick_restrict Ai, *magick_restrict Ar, *magick_restrict Bi, *magick_restrict Br; register PixelPacket *magick_restrict Ci, *magick_restrict Cr; register ssize_t x; if (status == MagickFalse) continue; Ar=GetCacheViewVirtualPixels(Ar_view,0,y,Cr_image->columns,1,exception); Ai=GetCacheViewVirtualPixels(Ai_view,0,y,Cr_image->columns,1,exception); Br=GetCacheViewVirtualPixels(Br_view,0,y,Cr_image->columns,1,exception); Bi=GetCacheViewVirtualPixels(Bi_view,0,y,Cr_image->columns,1,exception); Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception); Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception); if ((Ar == (const PixelPacket *) NULL) || (Ai == (const PixelPacket *) NULL) || (Br == (const PixelPacket *) NULL) || (Bi == (const PixelPacket *) NULL) || (Cr == (PixelPacket *) NULL) || (Ci == (PixelPacket *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) Cr_image->columns; x++) { switch (op) { case AddComplexOperator: { Cr->red=Ar->red+Br->red; Ci->red=Ai->red+Bi->red; Cr->green=Ar->green+Br->green; Ci->green=Ai->green+Bi->green; Cr->blue=Ar->blue+Br->blue; Ci->blue=Ai->blue+Bi->blue; if (images->matte != MagickFalse) { Cr->opacity=Ar->opacity+Br->opacity; Ci->opacity=Ai->opacity+Bi->opacity; } break; } case ConjugateComplexOperator: default: { Cr->red=Ar->red; Ci->red=(-Bi->red); Cr->green=Ar->green; Ci->green=(-Bi->green); Cr->blue=Ar->blue; Ci->blue=(-Bi->blue); if (images->matte != MagickFalse) { Cr->opacity=Ar->opacity; Ci->opacity=(-Bi->opacity); } break; } case DivideComplexOperator: { double gamma; gamma=PerceptibleReciprocal(Br->red*Br->red+Bi->red*Bi->red+snr); Cr->red=gamma*((double) Ar->red*Br->red+(double) Ai->red*Bi->red); Ci->red=gamma*((double) Ai->red*Br->red-(double) Ar->red*Bi->red); gamma=PerceptibleReciprocal((double) Br->green*Br->green+(double) Bi->green*Bi->green+snr); Cr->green=gamma*((double) Ar->green*Br->green+(double) Ai->green*Bi->green); Ci->green=gamma*((double) Ai->green*Br->green-(double) Ar->green*Bi->green); gamma=PerceptibleReciprocal((double) Br->blue*Br->blue+(double) Bi->blue*Bi->blue+snr); Cr->blue=gamma*((double) Ar->blue*Br->blue+(double) Ai->blue*Bi->blue); Ci->blue=gamma*((double) Ai->blue*Br->blue-(double) Ar->blue*Bi->blue); if (images->matte != MagickFalse) { gamma=PerceptibleReciprocal((double) Br->opacity*Br->opacity+ (double) Bi->opacity*Bi->opacity+snr); Cr->opacity=gamma*((double) Ar->opacity*Br->opacity+(double) Ai->opacity*Bi->opacity); Ci->opacity=gamma*((double) Ai->opacity*Br->opacity-(double) Ar->opacity*Bi->opacity); } break; } case MagnitudePhaseComplexOperator: { Cr->red=sqrt((double) Ar->red*Ar->red+(double) Ai->red*Ai->red); Ci->red=atan2((double) Ai->red,(double) Ar->red)/(2.0*MagickPI)+0.5; Cr->green=sqrt((double) Ar->green*Ar->green+(double) Ai->green*Ai->green); Ci->green=atan2((double) Ai->green,(double) Ar->green)/ (2.0*MagickPI)+0.5; Cr->blue=sqrt((double) Ar->blue*Ar->blue+(double) Ai->blue*Ai->blue); Ci->blue=atan2(Ai->blue,Ar->blue)/(2.0*MagickPI)+0.5; if (images->matte != MagickFalse) { Cr->opacity=sqrt((double) Ar->opacity*Ar->opacity+(double) Ai->opacity*Ai->opacity); Ci->opacity=atan2((double) Ai->opacity,(double) Ar->opacity)/ (2.0*MagickPI)+0.5; } break; } case MultiplyComplexOperator: { Cr->red=QuantumScale*((double) Ar->red*Br->red-(double) Ai->red*Bi->red); Ci->red=QuantumScale*((double) Ai->red*Br->red+(double) Ar->red*Bi->red); Cr->green=QuantumScale*((double) Ar->green*Br->green-(double) Ai->green*Bi->green); Ci->green=QuantumScale*((double) Ai->green*Br->green+(double) Ar->green*Bi->green); Cr->blue=QuantumScale*((double) Ar->blue*Br->blue-(double) Ai->blue*Bi->blue); Ci->blue=QuantumScale*((double) Ai->blue*Br->blue+(double) Ar->blue*Bi->blue); if (images->matte != MagickFalse) { Cr->opacity=QuantumScale*((double) Ar->opacity*Br->opacity- (double) Ai->opacity*Bi->opacity); Ci->opacity=QuantumScale*((double) Ai->opacity*Br->opacity+ (double) Ar->opacity*Bi->opacity); } break; } case RealImaginaryComplexOperator: { Cr->red=Ar->red*cos(2.0*MagickPI*(Ai->red-0.5)); Ci->red=Ar->red*sin(2.0*MagickPI*(Ai->red-0.5)); Cr->green=Ar->green*cos(2.0*MagickPI*(Ai->green-0.5)); Ci->green=Ar->green*sin(2.0*MagickPI*(Ai->green-0.5)); Cr->blue=Ar->blue*cos(2.0*MagickPI*(Ai->blue-0.5)); Ci->blue=Ar->blue*sin(2.0*MagickPI*(Ai->blue-0.5)); if (images->matte != MagickFalse) { Cr->opacity=Ar->opacity*cos(2.0*MagickPI*(Ai->opacity-0.5)); Ci->opacity=Ar->opacity*sin(2.0*MagickPI*(Ai->opacity-0.5)); } break; } case SubtractComplexOperator: { Cr->red=Ar->red-Br->red; Ci->red=Ai->red-Bi->red; Cr->green=Ar->green-Br->green; Ci->green=Ai->green-Bi->green; Cr->blue=Ar->blue-Br->blue; Ci->blue=Ai->blue-Bi->blue; if (Cr_image->matte != MagickFalse) { Cr->opacity=Ar->opacity-Br->opacity; Ci->opacity=Ai->opacity-Bi->opacity; } break; } } Ar++; Ai++; Br++; Bi++; Cr++; Ci++; } if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse) status=MagickFalse; if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows); if (proceed == MagickFalse) status=MagickFalse; } } Cr_view=DestroyCacheView(Cr_view); Ci_view=DestroyCacheView(Ci_view); Br_view=DestroyCacheView(Br_view); Bi_view=DestroyCacheView(Bi_view); Ar_view=DestroyCacheView(Ar_view); Ai_view=DestroyCacheView(Ai_view); if (status == MagickFalse) complex_images=DestroyImageList(complex_images); return(complex_images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F o r w a r d F o u r i e r T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ForwardFourierTransformImage() implements the discrete Fourier transform % (DFT) of the image either as a magnitude / phase or real / imaginary image % pair. % % The format of the ForwadFourierTransformImage method is: % % Image *ForwardFourierTransformImage(const Image *image, % const MagickBooleanType modulus,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o modulus: if true, return as transform as a magnitude / phase pair % otherwise a real / imaginary image pair. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FFTW_DELEGATE) static MagickBooleanType RollFourier(const size_t width,const size_t height, const ssize_t x_offset,const ssize_t y_offset,double *roll_pixels) { double *source_pixels; MemoryInfo *source_info; register ssize_t i, x; ssize_t u, v, y; /* Move zero frequency (DC, average color) from (0,0) to (width/2,height/2). */ source_info=AcquireVirtualMemory(width,height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) return(MagickFalse); source_pixels=(double *) GetVirtualMemoryBlob(source_info); i=0L; for (y=0L; y < (ssize_t) height; y++) { if (y_offset < 0L) v=((y+y_offset) < 0L) ? y+y_offset+(ssize_t) height : y+y_offset; else v=((y+y_offset) > ((ssize_t) height-1L)) ? y+y_offset-(ssize_t) height : y+y_offset; for (x=0L; x < (ssize_t) width; x++) { if (x_offset < 0L) u=((x+x_offset) < 0L) ? x+x_offset+(ssize_t) width : x+x_offset; else u=((x+x_offset) > ((ssize_t) width-1L)) ? x+x_offset-(ssize_t) width : x+x_offset; source_pixels[v*width+u]=roll_pixels[i++]; } } (void) memcpy(roll_pixels,source_pixels,height*width* sizeof(*source_pixels)); source_info=RelinquishVirtualMemory(source_info); return(MagickTrue); } static MagickBooleanType ForwardQuadrantSwap(const size_t width, const size_t height,double *source_pixels,double *forward_pixels) { MagickBooleanType status; register ssize_t x; ssize_t center, y; /* Swap quadrants. */ center=(ssize_t) (width/2L)+1L; status=RollFourier((size_t) center,height,0L,(ssize_t) height/2L, source_pixels); if (status == MagickFalse) return(MagickFalse); for (y=0L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[y*width+x+width/2L]=source_pixels[y*center+x]; for (y=1; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[(height-y)*width+width/2L-x-1L]= source_pixels[y*center+x+1L]; for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[width/2L-x-1L]=source_pixels[x+1L]; return(MagickTrue); } static void CorrectPhaseLHS(const size_t width,const size_t height, double *fourier_pixels) { register ssize_t x; ssize_t y; for (y=0L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) fourier_pixels[y*width+x]*=(-1.0); } static MagickBooleanType ForwardFourier(const FourierInfo *fourier_info, Image *image,double *magnitude,double *phase,ExceptionInfo *exception) { CacheView *magnitude_view, *phase_view; double *magnitude_pixels, *phase_pixels; Image *magnitude_image, *phase_image; MagickBooleanType status; MemoryInfo *magnitude_info, *phase_info; register IndexPacket *indexes; register PixelPacket *q; register ssize_t x; ssize_t i, y; magnitude_image=GetFirstImageInList(image); phase_image=GetNextImageInList(image); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",image->filename); return(MagickFalse); } /* Create "Fourier Transform" image from constituent arrays. */ magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*phase_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL)) { if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (magnitude_info != (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); (void) memset(magnitude_pixels,0,fourier_info->width* fourier_info->height*sizeof(*magnitude_pixels)); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); (void) memset(phase_pixels,0,fourier_info->width* fourier_info->height*sizeof(*phase_pixels)); status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height, magnitude,magnitude_pixels); if (status != MagickFalse) status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height,phase, phase_pixels); CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels); if (fourier_info->modulus != MagickFalse) { i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->width; x++) { phase_pixels[i]/=(2.0*MagickPI); phase_pixels[i]+=0.5; i++; } } magnitude_view=AcquireAuthenticCacheView(magnitude_image,exception); i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) { q=GetCacheViewAuthenticPixels(magnitude_view,0L,y,fourier_info->width,1UL, exception); if (q == (PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(magnitude_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { SetPixelRed(q,ClampToQuantum(QuantumRange*magnitude_pixels[i])); break; } case GreenChannel: { SetPixelGreen(q,ClampToQuantum(QuantumRange*magnitude_pixels[i])); break; } case BlueChannel: { SetPixelBlue(q,ClampToQuantum(QuantumRange*magnitude_pixels[i])); break; } case OpacityChannel: { SetPixelOpacity(q,ClampToQuantum(QuantumRange*magnitude_pixels[i])); break; } case IndexChannel: { SetPixelIndex(indexes+x,ClampToQuantum(QuantumRange* magnitude_pixels[i])); break; } case GrayChannels: { SetPixelGray(q,ClampToQuantum(QuantumRange*magnitude_pixels[i])); break; } } i++; q++; } status=SyncCacheViewAuthenticPixels(magnitude_view,exception); if (status == MagickFalse) break; } magnitude_view=DestroyCacheView(magnitude_view); i=0L; phase_view=AcquireAuthenticCacheView(phase_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { q=GetCacheViewAuthenticPixels(phase_view,0L,y,fourier_info->width,1UL, exception); if (q == (PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(phase_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { SetPixelRed(q,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } case GreenChannel: { SetPixelGreen(q,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } case BlueChannel: { SetPixelBlue(q,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } case OpacityChannel: { SetPixelOpacity(q,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } case IndexChannel: { SetPixelIndex(indexes+x,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } case GrayChannels: { SetPixelGray(q,ClampToQuantum(QuantumRange*phase_pixels[i])); break; } } i++; q++; } status=SyncCacheViewAuthenticPixels(phase_view,exception); if (status == MagickFalse) break; } phase_view=DestroyCacheView(phase_view); phase_info=RelinquishVirtualMemory(phase_info); magnitude_info=RelinquishVirtualMemory(magnitude_info); return(status); } static MagickBooleanType ForwardFourierTransform(FourierInfo *fourier_info, const Image *image,double *magnitude_pixels,double *phase_pixels, ExceptionInfo *exception) { CacheView *image_view; const char *value; double *source_pixels; fftw_complex *forward_pixels; fftw_plan fftw_r2c_plan; MemoryInfo *forward_info, *source_info; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t i, x; ssize_t y; /* Generate the forward Fourier transform. */ source_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } source_pixels=(double *) GetVirtualMemoryBlob(source_info); memset(source_pixels,0,fourier_info->width*fourier_info->height* sizeof(*source_pixels)); i=0L; image_view=AcquireVirtualCacheView(image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(image_view,0L,y,fourier_info->width,1UL, exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { source_pixels[i]=QuantumScale*GetPixelRed(p); break; } case GreenChannel: { source_pixels[i]=QuantumScale*GetPixelGreen(p); break; } case BlueChannel: { source_pixels[i]=QuantumScale*GetPixelBlue(p); break; } case OpacityChannel: { source_pixels[i]=QuantumScale*GetPixelOpacity(p); break; } case IndexChannel: { source_pixels[i]=QuantumScale*GetPixelIndex(indexes+x); break; } case GrayChannels: { source_pixels[i]=QuantumScale*GetPixelGray(p); break; } } i++; p++; } } image_view=DestroyCacheView(image_view); forward_info=AcquireVirtualMemory((size_t) fourier_info->width, (fourier_info->height/2+1)*sizeof(*forward_pixels)); if (forward_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info); return(MagickFalse); } forward_pixels=(fftw_complex *) GetVirtualMemoryBlob(forward_info); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ForwardFourierTransform) #endif fftw_r2c_plan=fftw_plan_dft_r2c_2d(fourier_info->width,fourier_info->height, source_pixels,forward_pixels,FFTW_ESTIMATE); fftw_execute_dft_r2c(fftw_r2c_plan,source_pixels,forward_pixels); fftw_destroy_plan(fftw_r2c_plan); source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info); value=GetImageArtifact(image,"fourier:normalize"); if ((value == (const char *) NULL) || (LocaleCompare(value,"forward") == 0)) { double gamma; /* Normalize Fourier transform. */ i=0L; gamma=PerceptibleReciprocal((double) fourier_info->width* fourier_info->height); for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) forward_pixels[i]*=gamma; #else forward_pixels[i][0]*=gamma; forward_pixels[i][1]*=gamma; #endif i++; } } /* Generate magnitude and phase (or real and imaginary). */ i=0L; if (fourier_info->modulus != MagickFalse) for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { magnitude_pixels[i]=cabs(forward_pixels[i]); phase_pixels[i]=carg(forward_pixels[i]); i++; } else for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { magnitude_pixels[i]=creal(forward_pixels[i]); phase_pixels[i]=cimag(forward_pixels[i]); i++; } forward_info=(MemoryInfo *) RelinquishVirtualMemory(forward_info); return(MagickTrue); } static MagickBooleanType ForwardFourierTransformChannel(const Image *image, const ChannelType channel,const MagickBooleanType modulus, Image *fourier_image,ExceptionInfo *exception) { double *magnitude_pixels, *phase_pixels; FourierInfo fourier_info; MagickBooleanType status; MemoryInfo *magnitude_info, *phase_info; fourier_info.width=image->columns; fourier_info.height=image->rows; if ((image->columns != image->rows) || ((image->columns % 2) != 0) || ((image->rows % 2) != 0)) { size_t extent=image->columns < image->rows ? image->rows : image->columns; fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent; } fourier_info.height=fourier_info.width; fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L; fourier_info.channel=channel; fourier_info.modulus=modulus; magnitude_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*phase_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL)) { if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (magnitude_info == (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); status=ForwardFourierTransform(&fourier_info,image,magnitude_pixels, phase_pixels,exception); if (status != MagickFalse) status=ForwardFourier(&fourier_info,fourier_image,magnitude_pixels, phase_pixels,exception); phase_info=RelinquishVirtualMemory(phase_info); magnitude_info=RelinquishVirtualMemory(magnitude_info); return(status); } #endif MagickExport Image *ForwardFourierTransformImage(const Image *image, const MagickBooleanType modulus,ExceptionInfo *exception) { Image *fourier_image; fourier_image=NewImageList(); #if !defined(MAGICKCORE_FFTW_DELEGATE) (void) modulus; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)", image->filename); #else { Image *magnitude_image; size_t height, width; width=image->columns; height=image->rows; if ((image->columns != image->rows) || ((image->columns % 2) != 0) || ((image->rows % 2) != 0)) { size_t extent=image->columns < image->rows ? image->rows : image->columns; width=(extent & 0x01) == 1 ? extent+1UL : extent; } height=width; magnitude_image=CloneImage(image,width,height,MagickTrue,exception); if (magnitude_image != (Image *) NULL) { Image *phase_image; magnitude_image->storage_class=DirectClass; magnitude_image->depth=32UL; phase_image=CloneImage(image,width,height,MagickTrue,exception); if (phase_image == (Image *) NULL) magnitude_image=DestroyImage(magnitude_image); else { MagickBooleanType is_gray, status; phase_image->storage_class=DirectClass; phase_image->depth=32UL; AppendImageToList(&fourier_image,magnitude_image); AppendImageToList(&fourier_image,phase_image); status=MagickTrue; is_gray=IsGrayImage(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel sections #endif { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; if (is_gray != MagickFalse) thread_status=ForwardFourierTransformChannel(image, GrayChannels,modulus,fourier_image,exception); else thread_status=ForwardFourierTransformChannel(image,RedChannel, modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=ForwardFourierTransformChannel(image, GreenChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=ForwardFourierTransformChannel(image, BlueChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (image->matte != MagickFalse) thread_status=ForwardFourierTransformChannel(image, OpacityChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (image->colorspace == CMYKColorspace) thread_status=ForwardFourierTransformChannel(image, IndexChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } } if (status == MagickFalse) fourier_image=DestroyImageList(fourier_image); fftw_cleanup(); } } } #endif return(fourier_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n v e r s e F o u r i e r T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InverseFourierTransformImage() implements the inverse discrete Fourier % transform (DFT) of the image either as a magnitude / phase or real / % imaginary image pair. % % The format of the InverseFourierTransformImage method is: % % Image *InverseFourierTransformImage(const Image *magnitude_image, % const Image *phase_image,const MagickBooleanType modulus, % ExceptionInfo *exception) % % A description of each parameter follows: % % o magnitude_image: the magnitude or real image. % % o phase_image: the phase or imaginary image. % % o modulus: if true, return transform as a magnitude / phase pair % otherwise a real / imaginary image pair. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FFTW_DELEGATE) static MagickBooleanType InverseQuadrantSwap(const size_t width, const size_t height,const double *source,double *destination) { register ssize_t x; ssize_t center, y; /* Swap quadrants. */ center=(ssize_t) (width/2L)+1L; for (y=1L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L+1L); x++) destination[(height-y)*center-x+width/2L]=source[y*width+x]; for (y=0L; y < (ssize_t) height; y++) destination[y*center]=source[y*width+width/2L]; for (x=0L; x < center; x++) destination[x]=source[center-x-1L]; return(RollFourier(center,height,0L,(ssize_t) height/-2L,destination)); } static MagickBooleanType InverseFourier(FourierInfo *fourier_info, const Image *magnitude_image,const Image *phase_image, fftw_complex *fourier_pixels,ExceptionInfo *exception) { CacheView *magnitude_view, *phase_view; double *inverse_pixels, *magnitude_pixels, *phase_pixels; MagickBooleanType status; MemoryInfo *inverse_info, *magnitude_info, *phase_info; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t i, x; ssize_t y; /* Inverse Fourier - read image and break down into a double array. */ magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*phase_pixels)); inverse_info=AcquireVirtualMemory((size_t) fourier_info->width, (fourier_info->height/2+1)*sizeof(*inverse_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL) || (inverse_info == (MemoryInfo *) NULL)) { if (magnitude_info != (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (inverse_info != (MemoryInfo *) NULL) inverse_info=RelinquishVirtualMemory(inverse_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); inverse_pixels=(double *) GetVirtualMemoryBlob(inverse_info); i=0L; magnitude_view=AcquireVirtualCacheView(magnitude_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(magnitude_view,0L,y,fourier_info->width,1UL, exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(magnitude_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { magnitude_pixels[i]=QuantumScale*GetPixelRed(p); break; } case GreenChannel: { magnitude_pixels[i]=QuantumScale*GetPixelGreen(p); break; } case BlueChannel: { magnitude_pixels[i]=QuantumScale*GetPixelBlue(p); break; } case OpacityChannel: { magnitude_pixels[i]=QuantumScale*GetPixelOpacity(p); break; } case IndexChannel: { magnitude_pixels[i]=QuantumScale*GetPixelIndex(indexes+x); break; } case GrayChannels: { magnitude_pixels[i]=QuantumScale*GetPixelGray(p); break; } } i++; p++; } } magnitude_view=DestroyCacheView(magnitude_view); status=InverseQuadrantSwap(fourier_info->width,fourier_info->height, magnitude_pixels,inverse_pixels); (void) memcpy(magnitude_pixels,inverse_pixels,fourier_info->height* fourier_info->center*sizeof(*magnitude_pixels)); i=0L; phase_view=AcquireVirtualCacheView(phase_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(phase_view,0,y,fourier_info->width,1, exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(phase_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedChannel: default: { phase_pixels[i]=QuantumScale*GetPixelRed(p); break; } case GreenChannel: { phase_pixels[i]=QuantumScale*GetPixelGreen(p); break; } case BlueChannel: { phase_pixels[i]=QuantumScale*GetPixelBlue(p); break; } case OpacityChannel: { phase_pixels[i]=QuantumScale*GetPixelOpacity(p); break; } case IndexChannel: { phase_pixels[i]=QuantumScale*GetPixelIndex(indexes+x); break; } case GrayChannels: { phase_pixels[i]=QuantumScale*GetPixelGray(p); break; } } i++; p++; } } if (fourier_info->modulus != MagickFalse) { i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->width; x++) { phase_pixels[i]-=0.5; phase_pixels[i]*=(2.0*MagickPI); i++; } } phase_view=DestroyCacheView(phase_view); CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels); if (status != MagickFalse) status=InverseQuadrantSwap(fourier_info->width,fourier_info->height, phase_pixels,inverse_pixels); (void) memcpy(phase_pixels,inverse_pixels,fourier_info->height* fourier_info->center*sizeof(*phase_pixels)); inverse_info=RelinquishVirtualMemory(inverse_info); /* Merge two sets. */ i=0L; if (fourier_info->modulus != MagickFalse) for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]=magnitude_pixels[i]*cos(phase_pixels[i])+I* magnitude_pixels[i]*sin(phase_pixels[i]); #else fourier_pixels[i][0]=magnitude_pixels[i]*cos(phase_pixels[i]); fourier_pixels[i][1]=magnitude_pixels[i]*sin(phase_pixels[i]); #endif i++; } else for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]=magnitude_pixels[i]+I*phase_pixels[i]; #else fourier_pixels[i][0]=magnitude_pixels[i]; fourier_pixels[i][1]=phase_pixels[i]; #endif i++; } magnitude_info=RelinquishVirtualMemory(magnitude_info); phase_info=RelinquishVirtualMemory(phase_info); return(status); } static MagickBooleanType InverseFourierTransform(FourierInfo *fourier_info, fftw_complex *fourier_pixels,Image *image,ExceptionInfo *exception) { CacheView *image_view; double *source_pixels; const char *value; fftw_plan fftw_c2r_plan; MemoryInfo *source_info; register IndexPacket *indexes; register PixelPacket *q; register ssize_t i, x; ssize_t y; source_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } source_pixels=(double *) GetVirtualMemoryBlob(source_info); value=GetImageArtifact(image,"fourier:normalize"); if (LocaleCompare(value,"inverse") == 0) { double gamma; /* Normalize inverse transform. */ i=0L; gamma=PerceptibleReciprocal((double) fourier_info->width* fourier_info->height); for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]*=gamma; #else fourier_pixels[i][0]*=gamma; fourier_pixels[i][1]*=gamma; #endif i++; } } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_InverseFourierTransform) #endif fftw_c2r_plan=fftw_plan_dft_c2r_2d(fourier_info->width,fourier_info->height, fourier_pixels,source_pixels,FFTW_ESTIMATE); fftw_execute_dft_c2r(fftw_c2r_plan,fourier_pixels,source_pixels); fftw_destroy_plan(fftw_c2r_plan); i=0L; image_view=AcquireAuthenticCacheView(image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { if (y >= (ssize_t) image->rows) break; q=GetCacheViewAuthenticPixels(image_view,0L,y,fourier_info->width > image->columns ? image->columns : fourier_info->width,1UL,exception); if (q == (PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0L; x < (ssize_t) fourier_info->width; x++) { if (x < (ssize_t) image->columns) switch (fourier_info->channel) { case RedChannel: default: { SetPixelRed(q,ClampToQuantum(QuantumRange*source_pixels[i])); break; } case GreenChannel: { SetPixelGreen(q,ClampToQuantum(QuantumRange*source_pixels[i])); break; } case BlueChannel: { SetPixelBlue(q,ClampToQuantum(QuantumRange*source_pixels[i])); break; } case OpacityChannel: { SetPixelOpacity(q,ClampToQuantum(QuantumRange*source_pixels[i])); break; } case IndexChannel: { SetPixelIndex(indexes+x,ClampToQuantum(QuantumRange* source_pixels[i])); break; } case GrayChannels: { SetPixelGray(q,ClampToQuantum(QuantumRange*source_pixels[i])); break; } } i++; q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) break; } image_view=DestroyCacheView(image_view); source_info=RelinquishVirtualMemory(source_info); return(MagickTrue); } static MagickBooleanType InverseFourierTransformChannel( const Image *magnitude_image,const Image *phase_image, const ChannelType channel,const MagickBooleanType modulus, Image *fourier_image,ExceptionInfo *exception) { fftw_complex *inverse_pixels; FourierInfo fourier_info; MagickBooleanType status; MemoryInfo *inverse_info; fourier_info.width=magnitude_image->columns; fourier_info.height=magnitude_image->rows; if ((magnitude_image->columns != magnitude_image->rows) || ((magnitude_image->columns % 2) != 0) || ((magnitude_image->rows % 2) != 0)) { size_t extent=magnitude_image->columns < magnitude_image->rows ? magnitude_image->rows : magnitude_image->columns; fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent; } fourier_info.height=fourier_info.width; fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L; fourier_info.channel=channel; fourier_info.modulus=modulus; inverse_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*inverse_pixels)); if (inverse_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); return(MagickFalse); } inverse_pixels=(fftw_complex *) GetVirtualMemoryBlob(inverse_info); status=InverseFourier(&fourier_info,magnitude_image,phase_image, inverse_pixels,exception); if (status != MagickFalse) status=InverseFourierTransform(&fourier_info,inverse_pixels,fourier_image, exception); inverse_info=RelinquishVirtualMemory(inverse_info); return(status); } #endif MagickExport Image *InverseFourierTransformImage(const Image *magnitude_image, const Image *phase_image,const MagickBooleanType modulus, ExceptionInfo *exception) { Image *fourier_image; assert(magnitude_image != (Image *) NULL); assert(magnitude_image->signature == MagickCoreSignature); if (magnitude_image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", magnitude_image->filename); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",magnitude_image->filename); return((Image *) NULL); } #if !defined(MAGICKCORE_FFTW_DELEGATE) fourier_image=(Image *) NULL; (void) modulus; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)", magnitude_image->filename); #else { fourier_image=CloneImage(magnitude_image,magnitude_image->columns, magnitude_image->rows,MagickTrue,exception); if (fourier_image != (Image *) NULL) { MagickBooleanType is_gray, status; status=MagickTrue; is_gray=IsGrayImage(magnitude_image,exception); if (is_gray != MagickFalse) is_gray=IsGrayImage(phase_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel sections #endif { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; if (is_gray != MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,GrayChannels,modulus,fourier_image,exception); else thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,RedChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,GreenChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,BlueChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (magnitude_image->matte != MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,OpacityChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (magnitude_image->colorspace == CMYKColorspace) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,IndexChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } } if (status == MagickFalse) fourier_image=DestroyImage(fourier_image); } fftw_cleanup(); } #endif return(fourier_image); }
null
130
CWE-787
CVE-2019-13568
/* # # File : CImg.h # ( C++ header file ) # # Description : The C++ Template Image Processing Toolkit. # This file is the main component of the CImg Library project. # ( http://cimg.eu ) # # Project manager : David Tschumperle. # ( http://tschumperle.users.greyc.fr/ ) # # A complete list of contributors is available in file 'README.txt' # distributed within the CImg package. # # Licenses : This file is 'dual-licensed', you have to choose one # of the two licenses below to apply. # # CeCILL-C # The CeCILL-C license is close to the GNU LGPL. # ( http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.html ) # # or CeCILL v2.1 # The CeCILL license is compatible with the GNU GPL. # ( http://www.cecill.info/licences/Licence_CeCILL_V2.1-en.html ) # # This software is governed either by the CeCILL or the CeCILL-C license # under French law and abiding by the rules of distribution of free software. # You can use, modify and or redistribute the software under the terms of # the CeCILL or CeCILL-C licenses as circulated by CEA, CNRS and INRIA # at the following URL: "http://www.cecill.info". # # As a counterpart to the access to the source code and rights to copy, # modify and redistribute granted by the license, users are provided only # with a limited warranty and the software's author, the holder of the # economic rights, and the successive licensors have only limited # liability. # # In this respect, the user's attention is drawn to the risks associated # with loading, using, modifying and/or developing or reproducing the # software by the user in light of its specific status of free software, # that may mean that it is complicated to manipulate, and that also # therefore means that it is reserved for developers and experienced # professionals having in-depth computer knowledge. Users are therefore # encouraged to load and test the software's suitability as regards their # requirements in conditions enabling the security of their systems and/or # data to be ensured and, more generally, to use and operate it in the # same conditions as regards security. # # The fact that you are presently reading this means that you have had # knowledge of the CeCILL and CeCILL-C licenses and that you accept its terms. # */ // Set version number of the library. #ifndef cimg_version #define cimg_version 270 /*----------------------------------------------------------- # # Test and possibly auto-set CImg configuration variables # and include required headers. # # If you find that the default configuration variables are # not adapted to your system, you can override their values # before including the header file "CImg.h" # (use the #define directive). # ------------------------------------------------------------*/ // Include standard C++ headers. // This is the minimal set of required headers to make CImg-based codes compile. #include <cstdio> #include <cstdlib> #include <cstdarg> #include <cstring> #include <cmath> #include <cfloat> #include <climits> #include <ctime> #include <exception> #include <algorithm> // Detect/configure OS variables. // // Define 'cimg_OS' to: '0' for an unknown OS (will try to minize library dependencies). // '1' for a Unix-like OS (Linux, Solaris, BSD, MacOSX, Irix, ...). // '2' for Microsoft Windows. // (auto-detection is performed if 'cimg_OS' is not set by the user). #ifndef cimg_OS #if defined(unix) || defined(__unix) || defined(__unix__) \ || defined(linux) || defined(__linux) || defined(__linux__) \ || defined(sun) || defined(__sun) \ || defined(BSD) || defined(__OpenBSD__) || defined(__NetBSD__) \ || defined(__FreeBSD__) || defined (__DragonFly__) \ || defined(sgi) || defined(__sgi) \ || defined(__MACOSX__) || defined(__APPLE__) \ || defined(__CYGWIN__) #define cimg_OS 1 #elif defined(_MSC_VER) || defined(WIN32) || defined(_WIN32) || defined(__WIN32__) \ || defined(WIN64) || defined(_WIN64) || defined(__WIN64__) #define cimg_OS 2 #else #define cimg_OS 0 #endif #elif !(cimg_OS==0 || cimg_OS==1 || cimg_OS==2) #error CImg Library: Invalid configuration variable 'cimg_OS'. #error (correct values are '0 = unknown OS', '1 = Unix-like OS', '2 = Microsoft Windows'). #endif #ifndef cimg_date #define cimg_date __DATE__ #endif #ifndef cimg_time #define cimg_time __TIME__ #endif // Disable silly warnings on some Microsoft VC++ compilers. #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4127) #pragma warning(disable:4244) #pragma warning(disable:4311) #pragma warning(disable:4312) #pragma warning(disable:4319) #pragma warning(disable:4512) #pragma warning(disable:4571) #pragma warning(disable:4640) #pragma warning(disable:4706) #pragma warning(disable:4710) #pragma warning(disable:4800) #pragma warning(disable:4804) #pragma warning(disable:4820) #pragma warning(disable:4996) #ifndef _CRT_SECURE_NO_DEPRECATE #define _CRT_SECURE_NO_DEPRECATE 1 #endif #ifndef _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS 1 #endif #ifndef _CRT_NONSTDC_NO_DEPRECATE #define _CRT_NONSTDC_NO_DEPRECATE 1 #endif #endif // Define correct string functions for each compiler and OS. #if cimg_OS==2 && defined(_MSC_VER) #define cimg_sscanf std::sscanf #define cimg_sprintf std::sprintf #define cimg_snprintf cimg::_snprintf #define cimg_vsnprintf cimg::_vsnprintf #else #include <stdio.h> #if defined(__MACOSX__) || defined(__APPLE__) #define cimg_sscanf cimg::_sscanf #define cimg_sprintf cimg::_sprintf #define cimg_snprintf cimg::_snprintf #define cimg_vsnprintf cimg::_vsnprintf #else #define cimg_sscanf std::sscanf #define cimg_sprintf std::sprintf #define cimg_snprintf snprintf #define cimg_vsnprintf vsnprintf #endif #endif // Include OS-specific headers. #if cimg_OS==1 #include <sys/types.h> #include <sys/time.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <fnmatch.h> #elif cimg_OS==2 #ifndef NOMINMAX #define NOMINMAX #endif #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #ifndef _WIN32_IE #define _WIN32_IE 0x0400 #endif #include <shlobj.h> #include <process.h> #include <io.h> #endif // Look for C++11 features. #ifndef cimg_use_cpp11 #if __cplusplus>201100 #define cimg_use_cpp11 1 #else #define cimg_use_cpp11 0 #endif #endif #if cimg_use_cpp11==1 #include <initializer_list> #include <utility> #endif // Convenient macro to define pragma #ifdef _MSC_VER #define cimg_pragma(x) __pragma(x) #else #define cimg_pragma(x) _Pragma(#x) #endif // Define own types 'cimg_long/ulong' and 'cimg_int64/uint64' to ensure portability. // ( constrained to 'sizeof(cimg_ulong/cimg_long) = sizeof(void*)' and 'sizeof(cimg_int64/cimg_uint64)=8' ). #if cimg_OS==2 #define cimg_uint64 unsigned __int64 #define cimg_int64 __int64 #define cimg_ulong UINT_PTR #define cimg_long INT_PTR #ifdef _MSC_VER #define cimg_fuint64 "%I64u" #define cimg_fint64 "%I64d" #else #define cimg_fuint64 "%llu" #define cimg_fint64 "%lld" #endif #else #if UINTPTR_MAX==0xffffffff || defined(__arm__) || defined(_M_ARM) || ((ULONG_MAX)==(UINT_MAX)) #define cimg_uint64 unsigned long long #define cimg_int64 long long #define cimg_fuint64 "%llu" #define cimg_fint64 "%lld" #else #define cimg_uint64 unsigned long #define cimg_int64 long #define cimg_fuint64 "%lu" #define cimg_fint64 "%ld" #endif #if defined(__arm__) || defined(_M_ARM) #define cimg_ulong unsigned long long #define cimg_long long long #else #define cimg_ulong unsigned long #define cimg_long long #endif #endif // Configure filename separator. // // Filename separator is set by default to '/', except for Windows where it is '\'. #ifndef cimg_file_separator #if cimg_OS==2 #define cimg_file_separator '\\' #else #define cimg_file_separator '/' #endif #endif // Configure verbosity of output messages. // // Define 'cimg_verbosity' to: '0' to hide library messages (quiet mode). // '1' to output library messages on the console. // '2' to output library messages on a basic dialog window (default behavior). // '3' to do as '1' + add extra warnings (may slow down the code!). // '4' to do as '2' + add extra warnings (may slow down the code!). // // Define 'cimg_strict_warnings' to replace warning messages by exception throwns. // // Define 'cimg_use_vt100' to allow output of color messages on VT100-compatible terminals. #ifndef cimg_verbosity #if cimg_OS==2 #define cimg_verbosity 2 #else #define cimg_verbosity 1 #endif #elif !(cimg_verbosity==0 || cimg_verbosity==1 || cimg_verbosity==2 || cimg_verbosity==3 || cimg_verbosity==4) #error CImg Library: Configuration variable 'cimg_verbosity' is badly defined. #error (should be { 0=quiet | 1=console | 2=dialog | 3=console+warnings | 4=dialog+warnings }). #endif // Configure OpenMP support. // (http://www.openmp.org) // // Define 'cimg_use_openmp' to enable OpenMP support (requires OpenMP 3.0+). // // OpenMP directives are used in many CImg functions to get // advantages of multi-core CPUs. #if !defined(cimg_use_openmp) #ifdef _OPENMP #define cimg_use_openmp 1 #else #define cimg_use_openmp 0 #endif #endif #if cimg_use_openmp!=0 #include <omp.h> #define cimg_pragma_openmp(p) cimg_pragma(omp p) #else #define cimg_pragma_openmp(p) #endif // Configure the 'abort' signal handler (does nothing by default). // A typical signal handler can be defined in your own source like this: // #define cimg_abort_test if (is_abort) throw CImgAbortException("") // // where 'is_abort' is a boolean variable defined somewhere in your code and reachable in the method. // 'cimg_abort_test2' does the same but is called more often (in inner loops). #if defined(cimg_abort_test) && cimg_use_openmp!=0 // Define abort macros to be used with OpenMP. #ifndef _cimg_abort_init_omp #define _cimg_abort_init_omp bool _cimg_abort_go_omp = true; cimg::unused(_cimg_abort_go_omp) #endif #ifndef _cimg_abort_try_omp #define _cimg_abort_try_omp if (_cimg_abort_go_omp) try #endif #ifndef _cimg_abort_catch_omp #define _cimg_abort_catch_omp catch (CImgAbortException&) { cimg_pragma(omp atomic) _cimg_abort_go_omp&=false; } #endif #ifdef cimg_abort_test2 #ifndef _cimg_abort_try_omp2 #define _cimg_abort_try_omp2 _cimg_abort_try_omp #endif #ifndef _cimg_abort_catch_omp2 #define _cimg_abort_catch_omp2 _cimg_abort_catch_omp #endif #ifndef _cimg_abort_catch_fill_omp #define _cimg_abort_catch_fill_omp \ catch (CImgException& e) { cimg_pragma(omp critical(abort)) CImg<charT>::string(e._message).move_to(is_error); \ cimg_pragma(omp atomic) _cimg_abort_go_omp&=false; } #endif #endif #endif #ifndef _cimg_abort_init_omp #define _cimg_abort_init_omp #endif #ifndef _cimg_abort_try_omp #define _cimg_abort_try_omp #endif #ifndef _cimg_abort_catch_omp #define _cimg_abort_catch_omp #endif #ifndef _cimg_abort_try_omp2 #define _cimg_abort_try_omp2 #endif #ifndef _cimg_abort_catch_omp2 #define _cimg_abort_catch_omp2 #endif #ifndef _cimg_abort_catch_fill_omp #define _cimg_abort_catch_fill_omp #endif #ifndef cimg_abort_init #define cimg_abort_init #endif #ifndef cimg_abort_test #define cimg_abort_test #endif #ifndef cimg_abort_test2 #define cimg_abort_test2 #endif // Configure display framework. // // Define 'cimg_display' to: '0' to disable display capabilities. // '1' to use the X-Window framework (X11). // '2' to use the Microsoft GDI32 framework. #ifndef cimg_display #if cimg_OS==0 #define cimg_display 0 #elif cimg_OS==1 #define cimg_display 1 #elif cimg_OS==2 #define cimg_display 2 #endif #elif !(cimg_display==0 || cimg_display==1 || cimg_display==2) #error CImg Library: Configuration variable 'cimg_display' is badly defined. #error (should be { 0=none | 1=X-Window (X11) | 2=Microsoft GDI32 }). #endif // Include display-specific headers. #if cimg_display==1 #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/keysym.h> #include <pthread.h> #ifdef cimg_use_xshm #include <sys/ipc.h> #include <sys/shm.h> #include <X11/extensions/XShm.h> #endif #ifdef cimg_use_xrandr #include <X11/extensions/Xrandr.h> #endif #endif #ifndef cimg_appname #define cimg_appname "CImg" #endif // Configure OpenCV support. // (http://opencv.willowgarage.com/wiki/) // // Define 'cimg_use_opencv' to enable OpenCV support. // // OpenCV library may be used to access images from cameras // (see method 'CImg<T>::load_camera()'). #ifdef cimg_use_opencv #ifdef True #undef True #define _cimg_redefine_True #endif #ifdef False #undef False #define _cimg_redefine_False #endif #ifdef Status #undef Status #define _cimg_redefine_Status #endif #include <cstddef> #include <opencv2/opencv.hpp> #if CV_MAJOR_VERSION>=3 #define _cimg_fourcc cv::VideoWriter::fourcc #define _cimg_cap_prop_frame_width cv::VideoCaptureProperties::CAP_PROP_FRAME_WIDTH #define _cimg_cap_prop_frame_height cv::VideoCaptureProperties::CAP_PROP_FRAME_HEIGHT #define _cimg_cap_prop_frame_count cv::VideoCaptureProperties::CAP_PROP_FRAME_COUNT #else #define _cimg_fourcc CV_FOURCC #define _cimg_cap_prop_frame_width CV_CAP_PROP_FRAME_WIDTH #define _cimg_cap_prop_frame_height CV_CAP_PROP_FRAME_HEIGHT #define _cimg_cap_prop_frame_count CV_CAP_PROP_FRAME_COUNT #endif #endif // Configure LibPNG support. // (http://www.libpng.org) // // Define 'cimg_use_png' to enable LibPNG support. // // PNG library may be used to get a native support of '.png' files. // (see methods 'CImg<T>::{load,save}_png()'. #ifdef cimg_use_png extern "C" { #include "png.h" } #endif // Configure LibJPEG support. // (http://en.wikipedia.org/wiki/Libjpeg) // // Define 'cimg_use_jpeg' to enable LibJPEG support. // // JPEG library may be used to get a native support of '.jpg' files. // (see methods 'CImg<T>::{load,save}_jpeg()'). #ifdef cimg_use_jpeg extern "C" { #include "jpeglib.h" #include "setjmp.h" } #endif // Configure LibTIFF support. // (http://www.libtiff.org) // // Define 'cimg_use_tiff' to enable LibTIFF support. // // TIFF library may be used to get a native support of '.tif' files. // (see methods 'CImg[List]<T>::{load,save}_tiff()'). #ifdef cimg_use_tiff extern "C" { #define uint64 uint64_hack_ #define int64 int64_hack_ #include "tiffio.h" #undef uint64 #undef int64 } #endif // Configure LibMINC2 support. // (http://en.wikibooks.org/wiki/MINC/Reference/MINC2.0_File_Format_Reference) // // Define 'cimg_use_minc2' to enable LibMINC2 support. // // MINC2 library may be used to get a native support of '.mnc' files. // (see methods 'CImg<T>::{load,save}_minc2()'). #ifdef cimg_use_minc2 #include "minc_io_simple_volume.h" #include "minc_1_simple.h" #include "minc_1_simple_rw.h" #endif // Configure Zlib support. // (http://www.zlib.net) // // Define 'cimg_use_zlib' to enable Zlib support. // // Zlib library may be used to allow compressed data in '.cimgz' files // (see methods 'CImg[List]<T>::{load,save}_cimg()'). #ifdef cimg_use_zlib extern "C" { #include "zlib.h" } #endif // Configure libcurl support. // (http://curl.haxx.se/libcurl/) // // Define 'cimg_use_curl' to enable libcurl support. // // Libcurl may be used to get a native support of file downloading from the network. // (see method 'cimg::load_network()'.) #ifdef cimg_use_curl #include "curl/curl.h" #endif // Configure Magick++ support. // (http://www.imagemagick.org/Magick++) // // Define 'cimg_use_magick' to enable Magick++ support. // // Magick++ library may be used to get a native support of various image file formats. // (see methods 'CImg<T>::{load,save}()'). #ifdef cimg_use_magick #include "Magick++.h" #endif // Configure FFTW3 support. // (http://www.fftw.org) // // Define 'cimg_use_fftw3' to enable libFFTW3 support. // // FFTW3 library may be used to efficiently compute the Fast Fourier Transform // of image data, without restriction on the image size. // (see method 'CImg[List]<T>::FFT()'). #ifdef cimg_use_fftw3 extern "C" { #include "fftw3.h" } #endif // Configure LibBoard support. // (http://libboard.sourceforge.net/) // // Define 'cimg_use_board' to enable Board support. // // Board library may be used to draw 3D objects in vector-graphics canvas // that can be saved as '.ps' or '.svg' files afterwards. // (see method 'CImg<T>::draw_object3d()'). #ifdef cimg_use_board #include "Board.h" #endif // Configure OpenEXR support. // (http://www.openexr.com/) // // Define 'cimg_use_openexr' to enable OpenEXR support. // // OpenEXR library may be used to get a native support of '.exr' files. // (see methods 'CImg<T>::{load,save}_exr()'). #ifdef cimg_use_openexr #include "ImfRgbaFile.h" #include "ImfInputFile.h" #include "ImfChannelList.h" #include "ImfMatrixAttribute.h" #include "ImfArray.h" #endif // Configure TinyEXR support. // (https://github.com/syoyo/tinyexr) // // Define 'cimg_use_tinyexr' to enable TinyEXR support. // // TinyEXR is a small, single header-only library to load and save OpenEXR(.exr) images. #ifdef cimg_use_tinyexr #ifndef TINYEXR_IMPLEMENTATION #define TINYEXR_IMPLEMENTATION #endif #include "tinyexr.h" #endif // Lapack configuration. // (http://www.netlib.org/lapack) // // Define 'cimg_use_lapack' to enable LAPACK support. // // Lapack library may be used in several CImg methods to speed up // matrix computations (eigenvalues, inverse, ...). #ifdef cimg_use_lapack extern "C" { extern void sgetrf_(int*, int*, float*, int*, int*, int*); extern void sgetri_(int*, float*, int*, int*, float*, int*, int*); extern void sgetrs_(char*, int*, int*, float*, int*, int*, float*, int*, int*); extern void sgesvd_(char*, char*, int*, int*, float*, int*, float*, float*, int*, float*, int*, float*, int*, int*); extern void ssyev_(char*, char*, int*, float*, int*, float*, float*, int*, int*); extern void dgetrf_(int*, int*, double*, int*, int*, int*); extern void dgetri_(int*, double*, int*, int*, double*, int*, int*); extern void dgetrs_(char*, int*, int*, double*, int*, int*, double*, int*, int*); extern void dgesvd_(char*, char*, int*, int*, double*, int*, double*, double*, int*, double*, int*, double*, int*, int*); extern void dsyev_(char*, char*, int*, double*, int*, double*, double*, int*, int*); extern void dgels_(char*, int*,int*,int*,double*,int*,double*,int*,double*,int*,int*); extern void sgels_(char*, int*,int*,int*,float*,int*,float*,int*,float*,int*,int*); } #endif // Check if min/max/PI macros are defined. // // CImg does not compile if macros 'min', 'max' or 'PI' are defined, // because it redefines functions min(), max() and const variable PI in the cimg:: namespace. // so it '#undef' these macros if necessary, and restore them to reasonable // values at the end of this file. #ifdef min #undef min #define _cimg_redefine_min #endif #ifdef max #undef max #define _cimg_redefine_max #endif #ifdef PI #undef PI #define _cimg_redefine_PI #endif // Define 'cimg_library' namespace suffix. // // You may want to add a suffix to the 'cimg_library' namespace, for instance if you need to work // with several versions of the library at the same time. #ifdef cimg_namespace_suffix #define __cimg_library_suffixed(s) cimg_library_##s #define _cimg_library_suffixed(s) __cimg_library_suffixed(s) #define cimg_library_suffixed _cimg_library_suffixed(cimg_namespace_suffix) #else #define cimg_library_suffixed cimg_library #endif /*------------------------------------------------------------------------------ # # Define user-friendly macros. # # These CImg macros are prefixed by 'cimg_' and can be used safely in your own # code. They are useful to parse command line options, or to write image loops. # ------------------------------------------------------------------------------*/ // Macros to define program usage, and retrieve command line arguments. #define cimg_usage(usage) cimg_library_suffixed::cimg::option((char*)0,argc,argv,(char*)0,usage,false) #define cimg_help(str) cimg_library_suffixed::cimg::option((char*)0,argc,argv,str,(char*)0) #define cimg_option(name,defaut,usage) cimg_library_suffixed::cimg::option(name,argc,argv,defaut,usage) // Macros to define and manipulate local neighborhoods. #define CImg_2x2(I,T) T I[4]; \ T& I##cc = I[0]; T& I##nc = I[1]; \ T& I##cn = I[2]; T& I##nn = I[3]; \ I##cc = I##nc = \ I##cn = I##nn = 0 #define CImg_3x3(I,T) T I[9]; \ T& I##pp = I[0]; T& I##cp = I[1]; T& I##np = I[2]; \ T& I##pc = I[3]; T& I##cc = I[4]; T& I##nc = I[5]; \ T& I##pn = I[6]; T& I##cn = I[7]; T& I##nn = I[8]; \ I##pp = I##cp = I##np = \ I##pc = I##cc = I##nc = \ I##pn = I##cn = I##nn = 0 #define CImg_4x4(I,T) T I[16]; \ T& I##pp = I[0]; T& I##cp = I[1]; T& I##np = I[2]; T& I##ap = I[3]; \ T& I##pc = I[4]; T& I##cc = I[5]; T& I##nc = I[6]; T& I##ac = I[7]; \ T& I##pn = I[8]; T& I##cn = I[9]; T& I##nn = I[10]; T& I##an = I[11]; \ T& I##pa = I[12]; T& I##ca = I[13]; T& I##na = I[14]; T& I##aa = I[15]; \ I##pp = I##cp = I##np = I##ap = \ I##pc = I##cc = I##nc = I##ac = \ I##pn = I##cn = I##nn = I##an = \ I##pa = I##ca = I##na = I##aa = 0 #define CImg_5x5(I,T) T I[25]; \ T& I##bb = I[0]; T& I##pb = I[1]; T& I##cb = I[2]; T& I##nb = I[3]; T& I##ab = I[4]; \ T& I##bp = I[5]; T& I##pp = I[6]; T& I##cp = I[7]; T& I##np = I[8]; T& I##ap = I[9]; \ T& I##bc = I[10]; T& I##pc = I[11]; T& I##cc = I[12]; T& I##nc = I[13]; T& I##ac = I[14]; \ T& I##bn = I[15]; T& I##pn = I[16]; T& I##cn = I[17]; T& I##nn = I[18]; T& I##an = I[19]; \ T& I##ba = I[20]; T& I##pa = I[21]; T& I##ca = I[22]; T& I##na = I[23]; T& I##aa = I[24]; \ I##bb = I##pb = I##cb = I##nb = I##ab = \ I##bp = I##pp = I##cp = I##np = I##ap = \ I##bc = I##pc = I##cc = I##nc = I##ac = \ I##bn = I##pn = I##cn = I##nn = I##an = \ I##ba = I##pa = I##ca = I##na = I##aa = 0 #define CImg_2x2x2(I,T) T I[8]; \ T& I##ccc = I[0]; T& I##ncc = I[1]; \ T& I##cnc = I[2]; T& I##nnc = I[3]; \ T& I##ccn = I[4]; T& I##ncn = I[5]; \ T& I##cnn = I[6]; T& I##nnn = I[7]; \ I##ccc = I##ncc = \ I##cnc = I##nnc = \ I##ccn = I##ncn = \ I##cnn = I##nnn = 0 #define CImg_3x3x3(I,T) T I[27]; \ T& I##ppp = I[0]; T& I##cpp = I[1]; T& I##npp = I[2]; \ T& I##pcp = I[3]; T& I##ccp = I[4]; T& I##ncp = I[5]; \ T& I##pnp = I[6]; T& I##cnp = I[7]; T& I##nnp = I[8]; \ T& I##ppc = I[9]; T& I##cpc = I[10]; T& I##npc = I[11]; \ T& I##pcc = I[12]; T& I##ccc = I[13]; T& I##ncc = I[14]; \ T& I##pnc = I[15]; T& I##cnc = I[16]; T& I##nnc = I[17]; \ T& I##ppn = I[18]; T& I##cpn = I[19]; T& I##npn = I[20]; \ T& I##pcn = I[21]; T& I##ccn = I[22]; T& I##ncn = I[23]; \ T& I##pnn = I[24]; T& I##cnn = I[25]; T& I##nnn = I[26]; \ I##ppp = I##cpp = I##npp = \ I##pcp = I##ccp = I##ncp = \ I##pnp = I##cnp = I##nnp = \ I##ppc = I##cpc = I##npc = \ I##pcc = I##ccc = I##ncc = \ I##pnc = I##cnc = I##nnc = \ I##ppn = I##cpn = I##npn = \ I##pcn = I##ccn = I##ncn = \ I##pnn = I##cnn = I##nnn = 0 #define cimg_get2x2(img,x,y,z,c,I,T) \ I[0] = (T)(img)(x,y,z,c), I[1] = (T)(img)(_n1##x,y,z,c), I[2] = (T)(img)(x,_n1##y,z,c), \ I[3] = (T)(img)(_n1##x,_n1##y,z,c) #define cimg_get3x3(img,x,y,z,c,I,T) \ I[0] = (T)(img)(_p1##x,_p1##y,z,c), I[1] = (T)(img)(x,_p1##y,z,c), I[2] = (T)(img)(_n1##x,_p1##y,z,c), \ I[3] = (T)(img)(_p1##x,y,z,c), I[4] = (T)(img)(x,y,z,c), I[5] = (T)(img)(_n1##x,y,z,c), \ I[6] = (T)(img)(_p1##x,_n1##y,z,c), I[7] = (T)(img)(x,_n1##y,z,c), I[8] = (T)(img)(_n1##x,_n1##y,z,c) #define cimg_get4x4(img,x,y,z,c,I,T) \ I[0] = (T)(img)(_p1##x,_p1##y,z,c), I[1] = (T)(img)(x,_p1##y,z,c), I[2] = (T)(img)(_n1##x,_p1##y,z,c), \ I[3] = (T)(img)(_n2##x,_p1##y,z,c), I[4] = (T)(img)(_p1##x,y,z,c), I[5] = (T)(img)(x,y,z,c), \ I[6] = (T)(img)(_n1##x,y,z,c), I[7] = (T)(img)(_n2##x,y,z,c), I[8] = (T)(img)(_p1##x,_n1##y,z,c), \ I[9] = (T)(img)(x,_n1##y,z,c), I[10] = (T)(img)(_n1##x,_n1##y,z,c), I[11] = (T)(img)(_n2##x,_n1##y,z,c), \ I[12] = (T)(img)(_p1##x,_n2##y,z,c), I[13] = (T)(img)(x,_n2##y,z,c), I[14] = (T)(img)(_n1##x,_n2##y,z,c), \ I[15] = (T)(img)(_n2##x,_n2##y,z,c) #define cimg_get5x5(img,x,y,z,c,I,T) \ I[0] = (T)(img)(_p2##x,_p2##y,z,c), I[1] = (T)(img)(_p1##x,_p2##y,z,c), I[2] = (T)(img)(x,_p2##y,z,c), \ I[3] = (T)(img)(_n1##x,_p2##y,z,c), I[4] = (T)(img)(_n2##x,_p2##y,z,c), I[5] = (T)(img)(_p2##x,_p1##y,z,c), \ I[6] = (T)(img)(_p1##x,_p1##y,z,c), I[7] = (T)(img)(x,_p1##y,z,c), I[8] = (T)(img)(_n1##x,_p1##y,z,c), \ I[9] = (T)(img)(_n2##x,_p1##y,z,c), I[10] = (T)(img)(_p2##x,y,z,c), I[11] = (T)(img)(_p1##x,y,z,c), \ I[12] = (T)(img)(x,y,z,c), I[13] = (T)(img)(_n1##x,y,z,c), I[14] = (T)(img)(_n2##x,y,z,c), \ I[15] = (T)(img)(_p2##x,_n1##y,z,c), I[16] = (T)(img)(_p1##x,_n1##y,z,c), I[17] = (T)(img)(x,_n1##y,z,c), \ I[18] = (T)(img)(_n1##x,_n1##y,z,c), I[19] = (T)(img)(_n2##x,_n1##y,z,c), I[20] = (T)(img)(_p2##x,_n2##y,z,c), \ I[21] = (T)(img)(_p1##x,_n2##y,z,c), I[22] = (T)(img)(x,_n2##y,z,c), I[23] = (T)(img)(_n1##x,_n2##y,z,c), \ I[24] = (T)(img)(_n2##x,_n2##y,z,c) #define cimg_get6x6(img,x,y,z,c,I,T) \ I[0] = (T)(img)(_p2##x,_p2##y,z,c), I[1] = (T)(img)(_p1##x,_p2##y,z,c), I[2] = (T)(img)(x,_p2##y,z,c), \ I[3] = (T)(img)(_n1##x,_p2##y,z,c), I[4] = (T)(img)(_n2##x,_p2##y,z,c), I[5] = (T)(img)(_n3##x,_p2##y,z,c), \ I[6] = (T)(img)(_p2##x,_p1##y,z,c), I[7] = (T)(img)(_p1##x,_p1##y,z,c), I[8] = (T)(img)(x,_p1##y,z,c), \ I[9] = (T)(img)(_n1##x,_p1##y,z,c), I[10] = (T)(img)(_n2##x,_p1##y,z,c), I[11] = (T)(img)(_n3##x,_p1##y,z,c), \ I[12] = (T)(img)(_p2##x,y,z,c), I[13] = (T)(img)(_p1##x,y,z,c), I[14] = (T)(img)(x,y,z,c), \ I[15] = (T)(img)(_n1##x,y,z,c), I[16] = (T)(img)(_n2##x,y,z,c), I[17] = (T)(img)(_n3##x,y,z,c), \ I[18] = (T)(img)(_p2##x,_n1##y,z,c), I[19] = (T)(img)(_p1##x,_n1##y,z,c), I[20] = (T)(img)(x,_n1##y,z,c), \ I[21] = (T)(img)(_n1##x,_n1##y,z,c), I[22] = (T)(img)(_n2##x,_n1##y,z,c), I[23] = (T)(img)(_n3##x,_n1##y,z,c), \ I[24] = (T)(img)(_p2##x,_n2##y,z,c), I[25] = (T)(img)(_p1##x,_n2##y,z,c), I[26] = (T)(img)(x,_n2##y,z,c), \ I[27] = (T)(img)(_n1##x,_n2##y,z,c), I[28] = (T)(img)(_n2##x,_n2##y,z,c), I[29] = (T)(img)(_n3##x,_n2##y,z,c), \ I[30] = (T)(img)(_p2##x,_n3##y,z,c), I[31] = (T)(img)(_p1##x,_n3##y,z,c), I[32] = (T)(img)(x,_n3##y,z,c), \ I[33] = (T)(img)(_n1##x,_n3##y,z,c), I[34] = (T)(img)(_n2##x,_n3##y,z,c), I[35] = (T)(img)(_n3##x,_n3##y,z,c) #define cimg_get7x7(img,x,y,z,c,I,T) \ I[0] = (T)(img)(_p3##x,_p3##y,z,c), I[1] = (T)(img)(_p2##x,_p3##y,z,c), I[2] = (T)(img)(_p1##x,_p3##y,z,c), \ I[3] = (T)(img)(x,_p3##y,z,c), I[4] = (T)(img)(_n1##x,_p3##y,z,c), I[5] = (T)(img)(_n2##x,_p3##y,z,c), \ I[6] = (T)(img)(_n3##x,_p3##y,z,c), I[7] = (T)(img)(_p3##x,_p2##y,z,c), I[8] = (T)(img)(_p2##x,_p2##y,z,c), \ I[9] = (T)(img)(_p1##x,_p2##y,z,c), I[10] = (T)(img)(x,_p2##y,z,c), I[11] = (T)(img)(_n1##x,_p2##y,z,c), \ I[12] = (T)(img)(_n2##x,_p2##y,z,c), I[13] = (T)(img)(_n3##x,_p2##y,z,c), I[14] = (T)(img)(_p3##x,_p1##y,z,c), \ I[15] = (T)(img)(_p2##x,_p1##y,z,c), I[16] = (T)(img)(_p1##x,_p1##y,z,c), I[17] = (T)(img)(x,_p1##y,z,c), \ I[18] = (T)(img)(_n1##x,_p1##y,z,c), I[19] = (T)(img)(_n2##x,_p1##y,z,c), I[20] = (T)(img)(_n3##x,_p1##y,z,c), \ I[21] = (T)(img)(_p3##x,y,z,c), I[22] = (T)(img)(_p2##x,y,z,c), I[23] = (T)(img)(_p1##x,y,z,c), \ I[24] = (T)(img)(x,y,z,c), I[25] = (T)(img)(_n1##x,y,z,c), I[26] = (T)(img)(_n2##x,y,z,c), \ I[27] = (T)(img)(_n3##x,y,z,c), I[28] = (T)(img)(_p3##x,_n1##y,z,c), I[29] = (T)(img)(_p2##x,_n1##y,z,c), \ I[30] = (T)(img)(_p1##x,_n1##y,z,c), I[31] = (T)(img)(x,_n1##y,z,c), I[32] = (T)(img)(_n1##x,_n1##y,z,c), \ I[33] = (T)(img)(_n2##x,_n1##y,z,c), I[34] = (T)(img)(_n3##x,_n1##y,z,c), I[35] = (T)(img)(_p3##x,_n2##y,z,c), \ I[36] = (T)(img)(_p2##x,_n2##y,z,c), I[37] = (T)(img)(_p1##x,_n2##y,z,c), I[38] = (T)(img)(x,_n2##y,z,c), \ I[39] = (T)(img)(_n1##x,_n2##y,z,c), I[40] = (T)(img)(_n2##x,_n2##y,z,c), I[41] = (T)(img)(_n3##x,_n2##y,z,c), \ I[42] = (T)(img)(_p3##x,_n3##y,z,c), I[43] = (T)(img)(_p2##x,_n3##y,z,c), I[44] = (T)(img)(_p1##x,_n3##y,z,c), \ I[45] = (T)(img)(x,_n3##y,z,c), I[46] = (T)(img)(_n1##x,_n3##y,z,c), I[47] = (T)(img)(_n2##x,_n3##y,z,c), \ I[48] = (T)(img)(_n3##x,_n3##y,z,c) #define cimg_get8x8(img,x,y,z,c,I,T) \ I[0] = (T)(img)(_p3##x,_p3##y,z,c), I[1] = (T)(img)(_p2##x,_p3##y,z,c), I[2] = (T)(img)(_p1##x,_p3##y,z,c), \ I[3] = (T)(img)(x,_p3##y,z,c), I[4] = (T)(img)(_n1##x,_p3##y,z,c), I[5] = (T)(img)(_n2##x,_p3##y,z,c), \ I[6] = (T)(img)(_n3##x,_p3##y,z,c), I[7] = (T)(img)(_n4##x,_p3##y,z,c), I[8] = (T)(img)(_p3##x,_p2##y,z,c), \ I[9] = (T)(img)(_p2##x,_p2##y,z,c), I[10] = (T)(img)(_p1##x,_p2##y,z,c), I[11] = (T)(img)(x,_p2##y,z,c), \ I[12] = (T)(img)(_n1##x,_p2##y,z,c), I[13] = (T)(img)(_n2##x,_p2##y,z,c), I[14] = (T)(img)(_n3##x,_p2##y,z,c), \ I[15] = (T)(img)(_n4##x,_p2##y,z,c), I[16] = (T)(img)(_p3##x,_p1##y,z,c), I[17] = (T)(img)(_p2##x,_p1##y,z,c), \ I[18] = (T)(img)(_p1##x,_p1##y,z,c), I[19] = (T)(img)(x,_p1##y,z,c), I[20] = (T)(img)(_n1##x,_p1##y,z,c), \ I[21] = (T)(img)(_n2##x,_p1##y,z,c), I[22] = (T)(img)(_n3##x,_p1##y,z,c), I[23] = (T)(img)(_n4##x,_p1##y,z,c), \ I[24] = (T)(img)(_p3##x,y,z,c), I[25] = (T)(img)(_p2##x,y,z,c), I[26] = (T)(img)(_p1##x,y,z,c), \ I[27] = (T)(img)(x,y,z,c), I[28] = (T)(img)(_n1##x,y,z,c), I[29] = (T)(img)(_n2##x,y,z,c), \ I[30] = (T)(img)(_n3##x,y,z,c), I[31] = (T)(img)(_n4##x,y,z,c), I[32] = (T)(img)(_p3##x,_n1##y,z,c), \ I[33] = (T)(img)(_p2##x,_n1##y,z,c), I[34] = (T)(img)(_p1##x,_n1##y,z,c), I[35] = (T)(img)(x,_n1##y,z,c), \ I[36] = (T)(img)(_n1##x,_n1##y,z,c), I[37] = (T)(img)(_n2##x,_n1##y,z,c), I[38] = (T)(img)(_n3##x,_n1##y,z,c), \ I[39] = (T)(img)(_n4##x,_n1##y,z,c), I[40] = (T)(img)(_p3##x,_n2##y,z,c), I[41] = (T)(img)(_p2##x,_n2##y,z,c), \ I[42] = (T)(img)(_p1##x,_n2##y,z,c), I[43] = (T)(img)(x,_n2##y,z,c), I[44] = (T)(img)(_n1##x,_n2##y,z,c), \ I[45] = (T)(img)(_n2##x,_n2##y,z,c), I[46] = (T)(img)(_n3##x,_n2##y,z,c), I[47] = (T)(img)(_n4##x,_n2##y,z,c), \ I[48] = (T)(img)(_p3##x,_n3##y,z,c), I[49] = (T)(img)(_p2##x,_n3##y,z,c), I[50] = (T)(img)(_p1##x,_n3##y,z,c), \ I[51] = (T)(img)(x,_n3##y,z,c), I[52] = (T)(img)(_n1##x,_n3##y,z,c), I[53] = (T)(img)(_n2##x,_n3##y,z,c), \ I[54] = (T)(img)(_n3##x,_n3##y,z,c), I[55] = (T)(img)(_n4##x,_n3##y,z,c), I[56] = (T)(img)(_p3##x,_n4##y,z,c), \ I[57] = (T)(img)(_p2##x,_n4##y,z,c), I[58] = (T)(img)(_p1##x,_n4##y,z,c), I[59] = (T)(img)(x,_n4##y,z,c), \ I[60] = (T)(img)(_n1##x,_n4##y,z,c), I[61] = (T)(img)(_n2##x,_n4##y,z,c), I[62] = (T)(img)(_n3##x,_n4##y,z,c), \ I[63] = (T)(img)(_n4##x,_n4##y,z,c); #define cimg_get9x9(img,x,y,z,c,I,T) \ I[0] = (T)(img)(_p4##x,_p4##y,z,c), I[1] = (T)(img)(_p3##x,_p4##y,z,c), I[2] = (T)(img)(_p2##x,_p4##y,z,c), \ I[3] = (T)(img)(_p1##x,_p4##y,z,c), I[4] = (T)(img)(x,_p4##y,z,c), I[5] = (T)(img)(_n1##x,_p4##y,z,c), \ I[6] = (T)(img)(_n2##x,_p4##y,z,c), I[7] = (T)(img)(_n3##x,_p4##y,z,c), I[8] = (T)(img)(_n4##x,_p4##y,z,c), \ I[9] = (T)(img)(_p4##x,_p3##y,z,c), I[10] = (T)(img)(_p3##x,_p3##y,z,c), I[11] = (T)(img)(_p2##x,_p3##y,z,c), \ I[12] = (T)(img)(_p1##x,_p3##y,z,c), I[13] = (T)(img)(x,_p3##y,z,c), I[14] = (T)(img)(_n1##x,_p3##y,z,c), \ I[15] = (T)(img)(_n2##x,_p3##y,z,c), I[16] = (T)(img)(_n3##x,_p3##y,z,c), I[17] = (T)(img)(_n4##x,_p3##y,z,c), \ I[18] = (T)(img)(_p4##x,_p2##y,z,c), I[19] = (T)(img)(_p3##x,_p2##y,z,c), I[20] = (T)(img)(_p2##x,_p2##y,z,c), \ I[21] = (T)(img)(_p1##x,_p2##y,z,c), I[22] = (T)(img)(x,_p2##y,z,c), I[23] = (T)(img)(_n1##x,_p2##y,z,c), \ I[24] = (T)(img)(_n2##x,_p2##y,z,c), I[25] = (T)(img)(_n3##x,_p2##y,z,c), I[26] = (T)(img)(_n4##x,_p2##y,z,c), \ I[27] = (T)(img)(_p4##x,_p1##y,z,c), I[28] = (T)(img)(_p3##x,_p1##y,z,c), I[29] = (T)(img)(_p2##x,_p1##y,z,c), \ I[30] = (T)(img)(_p1##x,_p1##y,z,c), I[31] = (T)(img)(x,_p1##y,z,c), I[32] = (T)(img)(_n1##x,_p1##y,z,c), \ I[33] = (T)(img)(_n2##x,_p1##y,z,c), I[34] = (T)(img)(_n3##x,_p1##y,z,c), I[35] = (T)(img)(_n4##x,_p1##y,z,c), \ I[36] = (T)(img)(_p4##x,y,z,c), I[37] = (T)(img)(_p3##x,y,z,c), I[38] = (T)(img)(_p2##x,y,z,c), \ I[39] = (T)(img)(_p1##x,y,z,c), I[40] = (T)(img)(x,y,z,c), I[41] = (T)(img)(_n1##x,y,z,c), \ I[42] = (T)(img)(_n2##x,y,z,c), I[43] = (T)(img)(_n3##x,y,z,c), I[44] = (T)(img)(_n4##x,y,z,c), \ I[45] = (T)(img)(_p4##x,_n1##y,z,c), I[46] = (T)(img)(_p3##x,_n1##y,z,c), I[47] = (T)(img)(_p2##x,_n1##y,z,c), \ I[48] = (T)(img)(_p1##x,_n1##y,z,c), I[49] = (T)(img)(x,_n1##y,z,c), I[50] = (T)(img)(_n1##x,_n1##y,z,c), \ I[51] = (T)(img)(_n2##x,_n1##y,z,c), I[52] = (T)(img)(_n3##x,_n1##y,z,c), I[53] = (T)(img)(_n4##x,_n1##y,z,c), \ I[54] = (T)(img)(_p4##x,_n2##y,z,c), I[55] = (T)(img)(_p3##x,_n2##y,z,c), I[56] = (T)(img)(_p2##x,_n2##y,z,c), \ I[57] = (T)(img)(_p1##x,_n2##y,z,c), I[58] = (T)(img)(x,_n2##y,z,c), I[59] = (T)(img)(_n1##x,_n2##y,z,c), \ I[60] = (T)(img)(_n2##x,_n2##y,z,c), I[61] = (T)(img)(_n3##x,_n2##y,z,c), I[62] = (T)(img)(_n4##x,_n2##y,z,c), \ I[63] = (T)(img)(_p4##x,_n3##y,z,c), I[64] = (T)(img)(_p3##x,_n3##y,z,c), I[65] = (T)(img)(_p2##x,_n3##y,z,c), \ I[66] = (T)(img)(_p1##x,_n3##y,z,c), I[67] = (T)(img)(x,_n3##y,z,c), I[68] = (T)(img)(_n1##x,_n3##y,z,c), \ I[69] = (T)(img)(_n2##x,_n3##y,z,c), I[70] = (T)(img)(_n3##x,_n3##y,z,c), I[71] = (T)(img)(_n4##x,_n3##y,z,c), \ I[72] = (T)(img)(_p4##x,_n4##y,z,c), I[73] = (T)(img)(_p3##x,_n4##y,z,c), I[74] = (T)(img)(_p2##x,_n4##y,z,c), \ I[75] = (T)(img)(_p1##x,_n4##y,z,c), I[76] = (T)(img)(x,_n4##y,z,c), I[77] = (T)(img)(_n1##x,_n4##y,z,c), \ I[78] = (T)(img)(_n2##x,_n4##y,z,c), I[79] = (T)(img)(_n3##x,_n4##y,z,c), I[80] = (T)(img)(_n4##x,_n4##y,z,c) #define cimg_get2x2x2(img,x,y,z,c,I,T) \ I[0] = (T)(img)(x,y,z,c), I[1] = (T)(img)(_n1##x,y,z,c), I[2] = (T)(img)(x,_n1##y,z,c), \ I[3] = (T)(img)(_n1##x,_n1##y,z,c), I[4] = (T)(img)(x,y,_n1##z,c), I[5] = (T)(img)(_n1##x,y,_n1##z,c), \ I[6] = (T)(img)(x,_n1##y,_n1##z,c), I[7] = (T)(img)(_n1##x,_n1##y,_n1##z,c) #define cimg_get3x3x3(img,x,y,z,c,I,T) \ I[0] = (T)(img)(_p1##x,_p1##y,_p1##z,c), I[1] = (T)(img)(x,_p1##y,_p1##z,c), \ I[2] = (T)(img)(_n1##x,_p1##y,_p1##z,c), I[3] = (T)(img)(_p1##x,y,_p1##z,c), I[4] = (T)(img)(x,y,_p1##z,c), \ I[5] = (T)(img)(_n1##x,y,_p1##z,c), I[6] = (T)(img)(_p1##x,_n1##y,_p1##z,c), I[7] = (T)(img)(x,_n1##y,_p1##z,c), \ I[8] = (T)(img)(_n1##x,_n1##y,_p1##z,c), I[9] = (T)(img)(_p1##x,_p1##y,z,c), I[10] = (T)(img)(x,_p1##y,z,c), \ I[11] = (T)(img)(_n1##x,_p1##y,z,c), I[12] = (T)(img)(_p1##x,y,z,c), I[13] = (T)(img)(x,y,z,c), \ I[14] = (T)(img)(_n1##x,y,z,c), I[15] = (T)(img)(_p1##x,_n1##y,z,c), I[16] = (T)(img)(x,_n1##y,z,c), \ I[17] = (T)(img)(_n1##x,_n1##y,z,c), I[18] = (T)(img)(_p1##x,_p1##y,_n1##z,c), I[19] = (T)(img)(x,_p1##y,_n1##z,c), \ I[20] = (T)(img)(_n1##x,_p1##y,_n1##z,c), I[21] = (T)(img)(_p1##x,y,_n1##z,c), I[22] = (T)(img)(x,y,_n1##z,c), \ I[23] = (T)(img)(_n1##x,y,_n1##z,c), I[24] = (T)(img)(_p1##x,_n1##y,_n1##z,c), I[25] = (T)(img)(x,_n1##y,_n1##z,c), \ I[26] = (T)(img)(_n1##x,_n1##y,_n1##z,c) // Macros to perform various image loops. // // These macros are simpler to use than loops with C++ iterators. #define cimg_for(img,ptrs,T_ptrs) \ for (T_ptrs *ptrs = (img)._data, *_max##ptrs = (img)._data + (img).size(); ptrs<_max##ptrs; ++ptrs) #define cimg_rof(img,ptrs,T_ptrs) for (T_ptrs *ptrs = (img)._data + (img).size() - 1; ptrs>=(img)._data; --ptrs) #define cimg_foroff(img,off) for (cimg_ulong off = 0, _max##off = (img).size(); off<_max##off; ++off) #define cimg_rofoff(img,off) for (cimg_long off = (cimg_long)((img).size() - 1); off>=0; --off) #define cimg_for1(bound,i) for (int i = 0; i<(int)(bound); ++i) #define cimg_forX(img,x) cimg_for1((img)._width,x) #define cimg_forY(img,y) cimg_for1((img)._height,y) #define cimg_forZ(img,z) cimg_for1((img)._depth,z) #define cimg_forC(img,c) cimg_for1((img)._spectrum,c) #define cimg_forXY(img,x,y) cimg_forY(img,y) cimg_forX(img,x) #define cimg_forXZ(img,x,z) cimg_forZ(img,z) cimg_forX(img,x) #define cimg_forYZ(img,y,z) cimg_forZ(img,z) cimg_forY(img,y) #define cimg_forXC(img,x,c) cimg_forC(img,c) cimg_forX(img,x) #define cimg_forYC(img,y,c) cimg_forC(img,c) cimg_forY(img,y) #define cimg_forZC(img,z,c) cimg_forC(img,c) cimg_forZ(img,z) #define cimg_forXYZ(img,x,y,z) cimg_forZ(img,z) cimg_forXY(img,x,y) #define cimg_forXYC(img,x,y,c) cimg_forC(img,c) cimg_forXY(img,x,y) #define cimg_forXZC(img,x,z,c) cimg_forC(img,c) cimg_forXZ(img,x,z) #define cimg_forYZC(img,y,z,c) cimg_forC(img,c) cimg_forYZ(img,y,z) #define cimg_forXYZC(img,x,y,z,c) cimg_forC(img,c) cimg_forXYZ(img,x,y,z) #define cimg_rof1(bound,i) for (int i = (int)(bound) - 1; i>=0; --i) #define cimg_rofX(img,x) cimg_rof1((img)._width,x) #define cimg_rofY(img,y) cimg_rof1((img)._height,y) #define cimg_rofZ(img,z) cimg_rof1((img)._depth,z) #define cimg_rofC(img,c) cimg_rof1((img)._spectrum,c) #define cimg_rofXY(img,x,y) cimg_rofY(img,y) cimg_rofX(img,x) #define cimg_rofXZ(img,x,z) cimg_rofZ(img,z) cimg_rofX(img,x) #define cimg_rofYZ(img,y,z) cimg_rofZ(img,z) cimg_rofY(img,y) #define cimg_rofXC(img,x,c) cimg_rofC(img,c) cimg_rofX(img,x) #define cimg_rofYC(img,y,c) cimg_rofC(img,c) cimg_rofY(img,y) #define cimg_rofZC(img,z,c) cimg_rofC(img,c) cimg_rofZ(img,z) #define cimg_rofXYZ(img,x,y,z) cimg_rofZ(img,z) cimg_rofXY(img,x,y) #define cimg_rofXYC(img,x,y,c) cimg_rofC(img,c) cimg_rofXY(img,x,y) #define cimg_rofXZC(img,x,z,c) cimg_rofC(img,c) cimg_rofXZ(img,x,z) #define cimg_rofYZC(img,y,z,c) cimg_rofC(img,c) cimg_rofYZ(img,y,z) #define cimg_rofXYZC(img,x,y,z,c) cimg_rofC(img,c) cimg_rofXYZ(img,x,y,z) #define cimg_for_in1(bound,i0,i1,i) \ for (int i = (int)(i0)<0?0:(int)(i0), _max##i = (int)(i1)<(int)(bound)?(int)(i1):(int)(bound) - 1; i<=_max##i; ++i) #define cimg_for_inX(img,x0,x1,x) cimg_for_in1((img)._width,x0,x1,x) #define cimg_for_inY(img,y0,y1,y) cimg_for_in1((img)._height,y0,y1,y) #define cimg_for_inZ(img,z0,z1,z) cimg_for_in1((img)._depth,z0,z1,z) #define cimg_for_inC(img,c0,c1,c) cimg_for_in1((img)._spectrum,c0,c1,c) #define cimg_for_inXY(img,x0,y0,x1,y1,x,y) cimg_for_inY(img,y0,y1,y) cimg_for_inX(img,x0,x1,x) #define cimg_for_inXZ(img,x0,z0,x1,z1,x,z) cimg_for_inZ(img,z0,z1,z) cimg_for_inX(img,x0,x1,x) #define cimg_for_inXC(img,x0,c0,x1,c1,x,c) cimg_for_inC(img,c0,c1,c) cimg_for_inX(img,x0,x1,x) #define cimg_for_inYZ(img,y0,z0,y1,z1,y,z) cimg_for_inZ(img,x0,z1,z) cimg_for_inY(img,y0,y1,y) #define cimg_for_inYC(img,y0,c0,y1,c1,y,c) cimg_for_inC(img,c0,c1,c) cimg_for_inY(img,y0,y1,y) #define cimg_for_inZC(img,z0,c0,z1,c1,z,c) cimg_for_inC(img,c0,c1,c) cimg_for_inZ(img,z0,z1,z) #define cimg_for_inXYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) cimg_for_inZ(img,z0,z1,z) cimg_for_inXY(img,x0,y0,x1,y1,x,y) #define cimg_for_inXYC(img,x0,y0,c0,x1,y1,c1,x,y,c) cimg_for_inC(img,c0,c1,c) cimg_for_inXY(img,x0,y0,x1,y1,x,y) #define cimg_for_inXZC(img,x0,z0,c0,x1,z1,c1,x,z,c) cimg_for_inC(img,c0,c1,c) cimg_for_inXZ(img,x0,z0,x1,z1,x,z) #define cimg_for_inYZC(img,y0,z0,c0,y1,z1,c1,y,z,c) cimg_for_inC(img,c0,c1,c) cimg_for_inYZ(img,y0,z0,y1,z1,y,z) #define cimg_for_inXYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) \ cimg_for_inC(img,c0,c1,c) cimg_for_inXYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for_insideX(img,x,n) cimg_for_inX(img,n,(img)._width - 1 - (n),x) #define cimg_for_insideY(img,y,n) cimg_for_inY(img,n,(img)._height - 1 - (n),y) #define cimg_for_insideZ(img,z,n) cimg_for_inZ(img,n,(img)._depth - 1 - (n),z) #define cimg_for_insideC(img,c,n) cimg_for_inC(img,n,(img)._spectrum - 1 - (n),c) #define cimg_for_insideXY(img,x,y,n) cimg_for_inXY(img,n,n,(img)._width - 1 - (n),(img)._height - 1 - (n),x,y) #define cimg_for_insideXYZ(img,x,y,z,n) \ cimg_for_inXYZ(img,n,n,n,(img)._width - 1 - (n),(img)._height - 1 - (n),(img)._depth - 1 - (n),x,y,z) #define cimg_for_insideXYZC(img,x,y,z,c,n) \ cimg_for_inXYZ(img,n,n,n,(img)._width - 1 - (n),(img)._height - 1 - (n),(img)._depth - 1 - (n),x,y,z) #define cimg_for_out1(boundi,i0,i1,i) \ for (int i = (int)(i0)>0?0:(int)(i1) + 1; i<(int)(boundi); ++i, i = i==(int)(i0)?(int)(i1) + 1:i) #define cimg_for_out2(boundi,boundj,i0,j0,i1,j1,i,j) \ for (int j = 0; j<(int)(boundj); ++j) \ for (int _n1j = (int)(j<(int)(j0) || j>(int)(j1)), i = _n1j?0:(int)(i0)>0?0:(int)(i1) + 1; i<(int)(boundi); \ ++i, i = _n1j?i:(i==(int)(i0)?(int)(i1) + 1:i)) #define cimg_for_out3(boundi,boundj,boundk,i0,j0,k0,i1,j1,k1,i,j,k) \ for (int k = 0; k<(int)(boundk); ++k) \ for (int _n1k = (int)(k<(int)(k0) || k>(int)(k1)), j = 0; j<(int)(boundj); ++j) \ for (int _n1j = (int)(j<(int)(j0) || j>(int)(j1)), i = _n1j || _n1k?0:(int)(i0)>0?0:(int)(i1) + 1; i<(int)(boundi); \ ++i, i = _n1j || _n1k?i:(i==(int)(i0)?(int)(i1) + 1:i)) #define cimg_for_out4(boundi,boundj,boundk,boundl,i0,j0,k0,l0,i1,j1,k1,l1,i,j,k,l) \ for (int l = 0; l<(int)(boundl); ++l) \ for (int _n1l = (int)(l<(int)(l0) || l>(int)(l1)), k = 0; k<(int)(boundk); ++k) \ for (int _n1k = (int)(k<(int)(k0) || k>(int)(k1)), j = 0; j<(int)(boundj); ++j) \ for (int _n1j = (int)(j<(int)(j0) || j>(int)(j1)), i = _n1j || _n1k || _n1l?0:(int)(i0)>0?0:(int)(i1) + 1; \ i<(int)(boundi); ++i, i = _n1j || _n1k || _n1l?i:(i==(int)(i0)?(int)(i1) + 1:i)) #define cimg_for_outX(img,x0,x1,x) cimg_for_out1((img)._width,x0,x1,x) #define cimg_for_outY(img,y0,y1,y) cimg_for_out1((img)._height,y0,y1,y) #define cimg_for_outZ(img,z0,z1,z) cimg_for_out1((img)._depth,z0,z1,z) #define cimg_for_outC(img,c0,c1,c) cimg_for_out1((img)._spectrum,c0,c1,c) #define cimg_for_outXY(img,x0,y0,x1,y1,x,y) cimg_for_out2((img)._width,(img)._height,x0,y0,x1,y1,x,y) #define cimg_for_outXZ(img,x0,z0,x1,z1,x,z) cimg_for_out2((img)._width,(img)._depth,x0,z0,x1,z1,x,z) #define cimg_for_outXC(img,x0,c0,x1,c1,x,c) cimg_for_out2((img)._width,(img)._spectrum,x0,c0,x1,c1,x,c) #define cimg_for_outYZ(img,y0,z0,y1,z1,y,z) cimg_for_out2((img)._height,(img)._depth,y0,z0,y1,z1,y,z) #define cimg_for_outYC(img,y0,c0,y1,c1,y,c) cimg_for_out2((img)._height,(img)._spectrum,y0,c0,y1,c1,y,c) #define cimg_for_outZC(img,z0,c0,z1,c1,z,c) cimg_for_out2((img)._depth,(img)._spectrum,z0,c0,z1,c1,z,c) #define cimg_for_outXYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) \ cimg_for_out3((img)._width,(img)._height,(img)._depth,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for_outXYC(img,x0,y0,c0,x1,y1,c1,x,y,c) \ cimg_for_out3((img)._width,(img)._height,(img)._spectrum,x0,y0,c0,x1,y1,c1,x,y,c) #define cimg_for_outXZC(img,x0,z0,c0,x1,z1,c1,x,z,c) \ cimg_for_out3((img)._width,(img)._depth,(img)._spectrum,x0,z0,c0,x1,z1,c1,x,z,c) #define cimg_for_outYZC(img,y0,z0,c0,y1,z1,c1,y,z,c) \ cimg_for_out3((img)._height,(img)._depth,(img)._spectrum,y0,z0,c0,y1,z1,c1,y,z,c) #define cimg_for_outXYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) \ cimg_for_out4((img)._width,(img)._height,(img)._depth,(img)._spectrum,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) #define cimg_for_borderX(img,x,n) cimg_for_outX(img,n,(img)._width - 1 - (n),x) #define cimg_for_borderY(img,y,n) cimg_for_outY(img,n,(img)._height - 1 - (n),y) #define cimg_for_borderZ(img,z,n) cimg_for_outZ(img,n,(img)._depth - 1 - (n),z) #define cimg_for_borderC(img,c,n) cimg_for_outC(img,n,(img)._spectrum - 1 - (n),c) #define cimg_for_borderXY(img,x,y,n) cimg_for_outXY(img,n,n,(img)._width - 1 - (n),(img)._height - 1 - (n),x,y) #define cimg_for_borderXYZ(img,x,y,z,n) \ cimg_for_outXYZ(img,n,n,n,(img)._width - 1 - (n),(img)._height - 1 - (n),(img)._depth - 1 - (n),x,y,z) #define cimg_for_borderXYZC(img,x,y,z,c,n) \ cimg_for_outXYZC(img,n,n,n,n,(img)._width - 1 - (n),(img)._height - 1 - (n), \ (img)._depth - 1 - (n),(img)._spectrum - 1 - (n),x,y,z,c) #define cimg_for_spiralXY(img,x,y) \ for (int x = 0, y = 0, _n1##x = 1, _n1##y = (img).width()*(img).height(); _n1##y; \ --_n1##y, _n1##x+=(_n1##x>>2) - ((!(_n1##x&3)?--y:((_n1##x&3)==1?(img)._width - 1 - ++x:\ ((_n1##x&3)==2?(img)._height - 1 - ++y:--x))))?0:1) #define cimg_for_lineXY(x,y,x0,y0,x1,y1) \ for (int x = (int)(x0), y = (int)(y0), _sx = 1, _sy = 1, _steep = 0, \ _dx=(x1)>(x0)?(int)(x1) - (int)(x0):(_sx=-1,(int)(x0) - (int)(x1)), \ _dy=(y1)>(y0)?(int)(y1) - (int)(y0):(_sy=-1,(int)(y0) - (int)(y1)), \ _counter = _dx, \ _err = _dx>_dy?(_dy>>1):((_steep=1),(_counter=_dy),(_dx>>1)); \ _counter>=0; \ --_counter, x+=_steep? \ (y+=_sy,(_err-=_dx)<0?_err+=_dy,_sx:0): \ (y+=(_err-=_dy)<0?_err+=_dx,_sy:0,_sx)) #define cimg_for2(bound,i) \ for (int i = 0, _n1##i = 1>=(bound)?(int)(bound) - 1:1; \ _n1##i<(int)(bound) || i==--_n1##i; \ ++i, ++_n1##i) #define cimg_for2X(img,x) cimg_for2((img)._width,x) #define cimg_for2Y(img,y) cimg_for2((img)._height,y) #define cimg_for2Z(img,z) cimg_for2((img)._depth,z) #define cimg_for2C(img,c) cimg_for2((img)._spectrum,c) #define cimg_for2XY(img,x,y) cimg_for2Y(img,y) cimg_for2X(img,x) #define cimg_for2XZ(img,x,z) cimg_for2Z(img,z) cimg_for2X(img,x) #define cimg_for2XC(img,x,c) cimg_for2C(img,c) cimg_for2X(img,x) #define cimg_for2YZ(img,y,z) cimg_for2Z(img,z) cimg_for2Y(img,y) #define cimg_for2YC(img,y,c) cimg_for2C(img,c) cimg_for2Y(img,y) #define cimg_for2ZC(img,z,c) cimg_for2C(img,c) cimg_for2Z(img,z) #define cimg_for2XYZ(img,x,y,z) cimg_for2Z(img,z) cimg_for2XY(img,x,y) #define cimg_for2XZC(img,x,z,c) cimg_for2C(img,c) cimg_for2XZ(img,x,z) #define cimg_for2YZC(img,y,z,c) cimg_for2C(img,c) cimg_for2YZ(img,y,z) #define cimg_for2XYZC(img,x,y,z,c) cimg_for2C(img,c) cimg_for2XYZ(img,x,y,z) #define cimg_for_in2(bound,i0,i1,i) \ for (int i = (int)(i0)<0?0:(int)(i0), \ _n1##i = i + 1>=(int)(bound)?(int)(bound) - 1:i + 1; \ i<=(int)(i1) && (_n1##i<(int)(bound) || i==--_n1##i); \ ++i, ++_n1##i) #define cimg_for_in2X(img,x0,x1,x) cimg_for_in2((img)._width,x0,x1,x) #define cimg_for_in2Y(img,y0,y1,y) cimg_for_in2((img)._height,y0,y1,y) #define cimg_for_in2Z(img,z0,z1,z) cimg_for_in2((img)._depth,z0,z1,z) #define cimg_for_in2C(img,c0,c1,c) cimg_for_in2((img)._spectrum,c0,c1,c) #define cimg_for_in2XY(img,x0,y0,x1,y1,x,y) cimg_for_in2Y(img,y0,y1,y) cimg_for_in2X(img,x0,x1,x) #define cimg_for_in2XZ(img,x0,z0,x1,z1,x,z) cimg_for_in2Z(img,z0,z1,z) cimg_for_in2X(img,x0,x1,x) #define cimg_for_in2XC(img,x0,c0,x1,c1,x,c) cimg_for_in2C(img,c0,c1,c) cimg_for_in2X(img,x0,x1,x) #define cimg_for_in2YZ(img,y0,z0,y1,z1,y,z) cimg_for_in2Z(img,z0,z1,z) cimg_for_in2Y(img,y0,y1,y) #define cimg_for_in2YC(img,y0,c0,y1,c1,y,c) cimg_for_in2C(img,c0,c1,c) cimg_for_in2Y(img,y0,y1,y) #define cimg_for_in2ZC(img,z0,c0,z1,c1,z,c) cimg_for_in2C(img,c0,c1,c) cimg_for_in2Z(img,z0,z1,z) #define cimg_for_in2XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) cimg_for_in2Z(img,z0,z1,z) cimg_for_in2XY(img,x0,y0,x1,y1,x,y) #define cimg_for_in2XZC(img,x0,z0,c0,x1,y1,c1,x,z,c) cimg_for_in2C(img,c0,c1,c) cimg_for_in2XZ(img,x0,y0,x1,y1,x,z) #define cimg_for_in2YZC(img,y0,z0,c0,y1,z1,c1,y,z,c) cimg_for_in2C(img,c0,c1,c) cimg_for_in2YZ(img,y0,z0,y1,z1,y,z) #define cimg_for_in2XYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) \ cimg_for_in2C(img,c0,c1,c) cimg_for_in2XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for3(bound,i) \ for (int i = 0, _p1##i = 0, \ _n1##i = 1>=(bound)?(int)(bound) - 1:1; \ _n1##i<(int)(bound) || i==--_n1##i; \ _p1##i = i++, ++_n1##i) #define cimg_for3X(img,x) cimg_for3((img)._width,x) #define cimg_for3Y(img,y) cimg_for3((img)._height,y) #define cimg_for3Z(img,z) cimg_for3((img)._depth,z) #define cimg_for3C(img,c) cimg_for3((img)._spectrum,c) #define cimg_for3XY(img,x,y) cimg_for3Y(img,y) cimg_for3X(img,x) #define cimg_for3XZ(img,x,z) cimg_for3Z(img,z) cimg_for3X(img,x) #define cimg_for3XC(img,x,c) cimg_for3C(img,c) cimg_for3X(img,x) #define cimg_for3YZ(img,y,z) cimg_for3Z(img,z) cimg_for3Y(img,y) #define cimg_for3YC(img,y,c) cimg_for3C(img,c) cimg_for3Y(img,y) #define cimg_for3ZC(img,z,c) cimg_for3C(img,c) cimg_for3Z(img,z) #define cimg_for3XYZ(img,x,y,z) cimg_for3Z(img,z) cimg_for3XY(img,x,y) #define cimg_for3XZC(img,x,z,c) cimg_for3C(img,c) cimg_for3XZ(img,x,z) #define cimg_for3YZC(img,y,z,c) cimg_for3C(img,c) cimg_for3YZ(img,y,z) #define cimg_for3XYZC(img,x,y,z,c) cimg_for3C(img,c) cimg_for3XYZ(img,x,y,z) #define cimg_for_in3(bound,i0,i1,i) \ for (int i = (int)(i0)<0?0:(int)(i0), \ _p1##i = i - 1<0?0:i - 1, \ _n1##i = i + 1>=(int)(bound)?(int)(bound) - 1:i + 1; \ i<=(int)(i1) && (_n1##i<(int)(bound) || i==--_n1##i); \ _p1##i = i++, ++_n1##i) #define cimg_for_in3X(img,x0,x1,x) cimg_for_in3((img)._width,x0,x1,x) #define cimg_for_in3Y(img,y0,y1,y) cimg_for_in3((img)._height,y0,y1,y) #define cimg_for_in3Z(img,z0,z1,z) cimg_for_in3((img)._depth,z0,z1,z) #define cimg_for_in3C(img,c0,c1,c) cimg_for_in3((img)._spectrum,c0,c1,c) #define cimg_for_in3XY(img,x0,y0,x1,y1,x,y) cimg_for_in3Y(img,y0,y1,y) cimg_for_in3X(img,x0,x1,x) #define cimg_for_in3XZ(img,x0,z0,x1,z1,x,z) cimg_for_in3Z(img,z0,z1,z) cimg_for_in3X(img,x0,x1,x) #define cimg_for_in3XC(img,x0,c0,x1,c1,x,c) cimg_for_in3C(img,c0,c1,c) cimg_for_in3X(img,x0,x1,x) #define cimg_for_in3YZ(img,y0,z0,y1,z1,y,z) cimg_for_in3Z(img,z0,z1,z) cimg_for_in3Y(img,y0,y1,y) #define cimg_for_in3YC(img,y0,c0,y1,c1,y,c) cimg_for_in3C(img,c0,c1,c) cimg_for_in3Y(img,y0,y1,y) #define cimg_for_in3ZC(img,z0,c0,z1,c1,z,c) cimg_for_in3C(img,c0,c1,c) cimg_for_in3Z(img,z0,z1,z) #define cimg_for_in3XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) cimg_for_in3Z(img,z0,z1,z) cimg_for_in3XY(img,x0,y0,x1,y1,x,y) #define cimg_for_in3XZC(img,x0,z0,c0,x1,y1,c1,x,z,c) cimg_for_in3C(img,c0,c1,c) cimg_for_in3XZ(img,x0,y0,x1,y1,x,z) #define cimg_for_in3YZC(img,y0,z0,c0,y1,z1,c1,y,z,c) cimg_for_in3C(img,c0,c1,c) cimg_for_in3YZ(img,y0,z0,y1,z1,y,z) #define cimg_for_in3XYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) \ cimg_for_in3C(img,c0,c1,c) cimg_for_in3XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for4(bound,i) \ for (int i = 0, _p1##i = 0, _n1##i = 1>=(bound)?(int)(bound) - 1:1, \ _n2##i = 2>=(bound)?(int)(bound) - 1:2; \ _n2##i<(int)(bound) || _n1##i==--_n2##i || i==(_n2##i = --_n1##i); \ _p1##i = i++, ++_n1##i, ++_n2##i) #define cimg_for4X(img,x) cimg_for4((img)._width,x) #define cimg_for4Y(img,y) cimg_for4((img)._height,y) #define cimg_for4Z(img,z) cimg_for4((img)._depth,z) #define cimg_for4C(img,c) cimg_for4((img)._spectrum,c) #define cimg_for4XY(img,x,y) cimg_for4Y(img,y) cimg_for4X(img,x) #define cimg_for4XZ(img,x,z) cimg_for4Z(img,z) cimg_for4X(img,x) #define cimg_for4XC(img,x,c) cimg_for4C(img,c) cimg_for4X(img,x) #define cimg_for4YZ(img,y,z) cimg_for4Z(img,z) cimg_for4Y(img,y) #define cimg_for4YC(img,y,c) cimg_for4C(img,c) cimg_for4Y(img,y) #define cimg_for4ZC(img,z,c) cimg_for4C(img,c) cimg_for4Z(img,z) #define cimg_for4XYZ(img,x,y,z) cimg_for4Z(img,z) cimg_for4XY(img,x,y) #define cimg_for4XZC(img,x,z,c) cimg_for4C(img,c) cimg_for4XZ(img,x,z) #define cimg_for4YZC(img,y,z,c) cimg_for4C(img,c) cimg_for4YZ(img,y,z) #define cimg_for4XYZC(img,x,y,z,c) cimg_for4C(img,c) cimg_for4XYZ(img,x,y,z) #define cimg_for_in4(bound,i0,i1,i) \ for (int i = (int)(i0)<0?0:(int)(i0), \ _p1##i = i - 1<0?0:i - 1, \ _n1##i = i + 1>=(int)(bound)?(int)(bound) - 1:i + 1, \ _n2##i = i + 2>=(int)(bound)?(int)(bound) - 1:i + 2; \ i<=(int)(i1) && (_n2##i<(int)(bound) || _n1##i==--_n2##i || i==(_n2##i = --_n1##i)); \ _p1##i = i++, ++_n1##i, ++_n2##i) #define cimg_for_in4X(img,x0,x1,x) cimg_for_in4((img)._width,x0,x1,x) #define cimg_for_in4Y(img,y0,y1,y) cimg_for_in4((img)._height,y0,y1,y) #define cimg_for_in4Z(img,z0,z1,z) cimg_for_in4((img)._depth,z0,z1,z) #define cimg_for_in4C(img,c0,c1,c) cimg_for_in4((img)._spectrum,c0,c1,c) #define cimg_for_in4XY(img,x0,y0,x1,y1,x,y) cimg_for_in4Y(img,y0,y1,y) cimg_for_in4X(img,x0,x1,x) #define cimg_for_in4XZ(img,x0,z0,x1,z1,x,z) cimg_for_in4Z(img,z0,z1,z) cimg_for_in4X(img,x0,x1,x) #define cimg_for_in4XC(img,x0,c0,x1,c1,x,c) cimg_for_in4C(img,c0,c1,c) cimg_for_in4X(img,x0,x1,x) #define cimg_for_in4YZ(img,y0,z0,y1,z1,y,z) cimg_for_in4Z(img,z0,z1,z) cimg_for_in4Y(img,y0,y1,y) #define cimg_for_in4YC(img,y0,c0,y1,c1,y,c) cimg_for_in4C(img,c0,c1,c) cimg_for_in4Y(img,y0,y1,y) #define cimg_for_in4ZC(img,z0,c0,z1,c1,z,c) cimg_for_in4C(img,c0,c1,c) cimg_for_in4Z(img,z0,z1,z) #define cimg_for_in4XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) cimg_for_in4Z(img,z0,z1,z) cimg_for_in4XY(img,x0,y0,x1,y1,x,y) #define cimg_for_in4XZC(img,x0,z0,c0,x1,y1,c1,x,z,c) cimg_for_in4C(img,c0,c1,c) cimg_for_in4XZ(img,x0,y0,x1,y1,x,z) #define cimg_for_in4YZC(img,y0,z0,c0,y1,z1,c1,y,z,c) cimg_for_in4C(img,c0,c1,c) cimg_for_in4YZ(img,y0,z0,y1,z1,y,z) #define cimg_for_in4XYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) \ cimg_for_in4C(img,c0,c1,c) cimg_for_in4XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for5(bound,i) \ for (int i = 0, _p2##i = 0, _p1##i = 0, \ _n1##i = 1>=(bound)?(int)(bound) - 1:1, \ _n2##i = 2>=(bound)?(int)(bound) - 1:2; \ _n2##i<(int)(bound) || _n1##i==--_n2##i || i==(_n2##i = --_n1##i); \ _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i) #define cimg_for5X(img,x) cimg_for5((img)._width,x) #define cimg_for5Y(img,y) cimg_for5((img)._height,y) #define cimg_for5Z(img,z) cimg_for5((img)._depth,z) #define cimg_for5C(img,c) cimg_for5((img)._spectrum,c) #define cimg_for5XY(img,x,y) cimg_for5Y(img,y) cimg_for5X(img,x) #define cimg_for5XZ(img,x,z) cimg_for5Z(img,z) cimg_for5X(img,x) #define cimg_for5XC(img,x,c) cimg_for5C(img,c) cimg_for5X(img,x) #define cimg_for5YZ(img,y,z) cimg_for5Z(img,z) cimg_for5Y(img,y) #define cimg_for5YC(img,y,c) cimg_for5C(img,c) cimg_for5Y(img,y) #define cimg_for5ZC(img,z,c) cimg_for5C(img,c) cimg_for5Z(img,z) #define cimg_for5XYZ(img,x,y,z) cimg_for5Z(img,z) cimg_for5XY(img,x,y) #define cimg_for5XZC(img,x,z,c) cimg_for5C(img,c) cimg_for5XZ(img,x,z) #define cimg_for5YZC(img,y,z,c) cimg_for5C(img,c) cimg_for5YZ(img,y,z) #define cimg_for5XYZC(img,x,y,z,c) cimg_for5C(img,c) cimg_for5XYZ(img,x,y,z) #define cimg_for_in5(bound,i0,i1,i) \ for (int i = (int)(i0)<0?0:(int)(i0), \ _p2##i = i - 2<0?0:i - 2, \ _p1##i = i - 1<0?0:i - 1, \ _n1##i = i + 1>=(int)(bound)?(int)(bound) - 1:i + 1, \ _n2##i = i + 2>=(int)(bound)?(int)(bound) - 1:i + 2; \ i<=(int)(i1) && (_n2##i<(int)(bound) || _n1##i==--_n2##i || i==(_n2##i = --_n1##i)); \ _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i) #define cimg_for_in5X(img,x0,x1,x) cimg_for_in5((img)._width,x0,x1,x) #define cimg_for_in5Y(img,y0,y1,y) cimg_for_in5((img)._height,y0,y1,y) #define cimg_for_in5Z(img,z0,z1,z) cimg_for_in5((img)._depth,z0,z1,z) #define cimg_for_in5C(img,c0,c1,c) cimg_for_in5((img)._spectrum,c0,c1,c) #define cimg_for_in5XY(img,x0,y0,x1,y1,x,y) cimg_for_in5Y(img,y0,y1,y) cimg_for_in5X(img,x0,x1,x) #define cimg_for_in5XZ(img,x0,z0,x1,z1,x,z) cimg_for_in5Z(img,z0,z1,z) cimg_for_in5X(img,x0,x1,x) #define cimg_for_in5XC(img,x0,c0,x1,c1,x,c) cimg_for_in5C(img,c0,c1,c) cimg_for_in5X(img,x0,x1,x) #define cimg_for_in5YZ(img,y0,z0,y1,z1,y,z) cimg_for_in5Z(img,z0,z1,z) cimg_for_in5Y(img,y0,y1,y) #define cimg_for_in5YC(img,y0,c0,y1,c1,y,c) cimg_for_in5C(img,c0,c1,c) cimg_for_in5Y(img,y0,y1,y) #define cimg_for_in5ZC(img,z0,c0,z1,c1,z,c) cimg_for_in5C(img,c0,c1,c) cimg_for_in5Z(img,z0,z1,z) #define cimg_for_in5XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) cimg_for_in5Z(img,z0,z1,z) cimg_for_in5XY(img,x0,y0,x1,y1,x,y) #define cimg_for_in5XZC(img,x0,z0,c0,x1,y1,c1,x,z,c) cimg_for_in5C(img,c0,c1,c) cimg_for_in5XZ(img,x0,y0,x1,y1,x,z) #define cimg_for_in5YZC(img,y0,z0,c0,y1,z1,c1,y,z,c) cimg_for_in5C(img,c0,c1,c) cimg_for_in5YZ(img,y0,z0,y1,z1,y,z) #define cimg_for_in5XYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) \ cimg_for_in5C(img,c0,c1,c) cimg_for_in5XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for6(bound,i) \ for (int i = 0, _p2##i = 0, _p1##i = 0, \ _n1##i = 1>=(bound)?(int)(bound) - 1:1, \ _n2##i = 2>=(bound)?(int)(bound) - 1:2, \ _n3##i = 3>=(bound)?(int)(bound) - 1:3; \ _n3##i<(int)(bound) || _n2##i==--_n3##i || _n1##i==--_n2##i || i==(_n3##i = _n2##i = --_n1##i); \ _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i, ++_n3##i) #define cimg_for6X(img,x) cimg_for6((img)._width,x) #define cimg_for6Y(img,y) cimg_for6((img)._height,y) #define cimg_for6Z(img,z) cimg_for6((img)._depth,z) #define cimg_for6C(img,c) cimg_for6((img)._spectrum,c) #define cimg_for6XY(img,x,y) cimg_for6Y(img,y) cimg_for6X(img,x) #define cimg_for6XZ(img,x,z) cimg_for6Z(img,z) cimg_for6X(img,x) #define cimg_for6XC(img,x,c) cimg_for6C(img,c) cimg_for6X(img,x) #define cimg_for6YZ(img,y,z) cimg_for6Z(img,z) cimg_for6Y(img,y) #define cimg_for6YC(img,y,c) cimg_for6C(img,c) cimg_for6Y(img,y) #define cimg_for6ZC(img,z,c) cimg_for6C(img,c) cimg_for6Z(img,z) #define cimg_for6XYZ(img,x,y,z) cimg_for6Z(img,z) cimg_for6XY(img,x,y) #define cimg_for6XZC(img,x,z,c) cimg_for6C(img,c) cimg_for6XZ(img,x,z) #define cimg_for6YZC(img,y,z,c) cimg_for6C(img,c) cimg_for6YZ(img,y,z) #define cimg_for6XYZC(img,x,y,z,c) cimg_for6C(img,c) cimg_for6XYZ(img,x,y,z) #define cimg_for_in6(bound,i0,i1,i) \ for (int i = (int)(i0)<0?0:(int)(i0), \ _p2##i = i - 2<0?0:i - 2, \ _p1##i = i - 1<0?0:i - 1, \ _n1##i = i + 1>=(int)(bound)?(int)(bound) - 1:i + 1, \ _n2##i = i + 2>=(int)(bound)?(int)(bound) - 1:i + 2, \ _n3##i = i + 3>=(int)(bound)?(int)(bound) - 1:i + 3; \ i<=(int)(i1) && \ (_n3##i<(int)(bound) || _n2##i==--_n3##i || _n1##i==--_n2##i || i==(_n3##i = _n2##i = --_n1##i)); \ _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i, ++_n3##i) #define cimg_for_in6X(img,x0,x1,x) cimg_for_in6((img)._width,x0,x1,x) #define cimg_for_in6Y(img,y0,y1,y) cimg_for_in6((img)._height,y0,y1,y) #define cimg_for_in6Z(img,z0,z1,z) cimg_for_in6((img)._depth,z0,z1,z) #define cimg_for_in6C(img,c0,c1,c) cimg_for_in6((img)._spectrum,c0,c1,c) #define cimg_for_in6XY(img,x0,y0,x1,y1,x,y) cimg_for_in6Y(img,y0,y1,y) cimg_for_in6X(img,x0,x1,x) #define cimg_for_in6XZ(img,x0,z0,x1,z1,x,z) cimg_for_in6Z(img,z0,z1,z) cimg_for_in6X(img,x0,x1,x) #define cimg_for_in6XC(img,x0,c0,x1,c1,x,c) cimg_for_in6C(img,c0,c1,c) cimg_for_in6X(img,x0,x1,x) #define cimg_for_in6YZ(img,y0,z0,y1,z1,y,z) cimg_for_in6Z(img,z0,z1,z) cimg_for_in6Y(img,y0,y1,y) #define cimg_for_in6YC(img,y0,c0,y1,c1,y,c) cimg_for_in6C(img,c0,c1,c) cimg_for_in6Y(img,y0,y1,y) #define cimg_for_in6ZC(img,z0,c0,z1,c1,z,c) cimg_for_in6C(img,c0,c1,c) cimg_for_in6Z(img,z0,z1,z) #define cimg_for_in6XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) cimg_for_in6Z(img,z0,z1,z) cimg_for_in6XY(img,x0,y0,x1,y1,x,y) #define cimg_for_in6XZC(img,x0,z0,c0,x1,y1,c1,x,z,c) cimg_for_in6C(img,c0,c1,c) cimg_for_in6XZ(img,x0,y0,x1,y1,x,z) #define cimg_for_in6YZC(img,y0,z0,c0,y1,z1,c1,y,z,c) cimg_for_in6C(img,c0,c1,c) cimg_for_in6YZ(img,y0,z0,y1,z1,y,z) #define cimg_for_in6XYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) \ cimg_for_in6C(img,c0,c1,c) cimg_for_in6XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for7(bound,i) \ for (int i = 0, _p3##i = 0, _p2##i = 0, _p1##i = 0, \ _n1##i = 1>=(bound)?(int)(bound) - 1:1, \ _n2##i = 2>=(bound)?(int)(bound) - 1:2, \ _n3##i = 3>=(bound)?(int)(bound) - 1:3; \ _n3##i<(int)(bound) || _n2##i==--_n3##i || _n1##i==--_n2##i || i==(_n3##i = _n2##i = --_n1##i); \ _p3##i = _p2##i, _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i, ++_n3##i) #define cimg_for7X(img,x) cimg_for7((img)._width,x) #define cimg_for7Y(img,y) cimg_for7((img)._height,y) #define cimg_for7Z(img,z) cimg_for7((img)._depth,z) #define cimg_for7C(img,c) cimg_for7((img)._spectrum,c) #define cimg_for7XY(img,x,y) cimg_for7Y(img,y) cimg_for7X(img,x) #define cimg_for7XZ(img,x,z) cimg_for7Z(img,z) cimg_for7X(img,x) #define cimg_for7XC(img,x,c) cimg_for7C(img,c) cimg_for7X(img,x) #define cimg_for7YZ(img,y,z) cimg_for7Z(img,z) cimg_for7Y(img,y) #define cimg_for7YC(img,y,c) cimg_for7C(img,c) cimg_for7Y(img,y) #define cimg_for7ZC(img,z,c) cimg_for7C(img,c) cimg_for7Z(img,z) #define cimg_for7XYZ(img,x,y,z) cimg_for7Z(img,z) cimg_for7XY(img,x,y) #define cimg_for7XZC(img,x,z,c) cimg_for7C(img,c) cimg_for7XZ(img,x,z) #define cimg_for7YZC(img,y,z,c) cimg_for7C(img,c) cimg_for7YZ(img,y,z) #define cimg_for7XYZC(img,x,y,z,c) cimg_for7C(img,c) cimg_for7XYZ(img,x,y,z) #define cimg_for_in7(bound,i0,i1,i) \ for (int i = (int)(i0)<0?0:(int)(i0), \ _p3##i = i - 3<0?0:i - 3, \ _p2##i = i - 2<0?0:i - 2, \ _p1##i = i - 1<0?0:i - 1, \ _n1##i = i + 1>=(int)(bound)?(int)(bound) - 1:i + 1, \ _n2##i = i + 2>=(int)(bound)?(int)(bound) - 1:i + 2, \ _n3##i = i + 3>=(int)(bound)?(int)(bound) - 1:i + 3; \ i<=(int)(i1) && \ (_n3##i<(int)(bound) || _n2##i==--_n3##i || _n1##i==--_n2##i || i==(_n3##i = _n2##i = --_n1##i)); \ _p3##i = _p2##i, _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i, ++_n3##i) #define cimg_for_in7X(img,x0,x1,x) cimg_for_in7((img)._width,x0,x1,x) #define cimg_for_in7Y(img,y0,y1,y) cimg_for_in7((img)._height,y0,y1,y) #define cimg_for_in7Z(img,z0,z1,z) cimg_for_in7((img)._depth,z0,z1,z) #define cimg_for_in7C(img,c0,c1,c) cimg_for_in7((img)._spectrum,c0,c1,c) #define cimg_for_in7XY(img,x0,y0,x1,y1,x,y) cimg_for_in7Y(img,y0,y1,y) cimg_for_in7X(img,x0,x1,x) #define cimg_for_in7XZ(img,x0,z0,x1,z1,x,z) cimg_for_in7Z(img,z0,z1,z) cimg_for_in7X(img,x0,x1,x) #define cimg_for_in7XC(img,x0,c0,x1,c1,x,c) cimg_for_in7C(img,c0,c1,c) cimg_for_in7X(img,x0,x1,x) #define cimg_for_in7YZ(img,y0,z0,y1,z1,y,z) cimg_for_in7Z(img,z0,z1,z) cimg_for_in7Y(img,y0,y1,y) #define cimg_for_in7YC(img,y0,c0,y1,c1,y,c) cimg_for_in7C(img,c0,c1,c) cimg_for_in7Y(img,y0,y1,y) #define cimg_for_in7ZC(img,z0,c0,z1,c1,z,c) cimg_for_in7C(img,c0,c1,c) cimg_for_in7Z(img,z0,z1,z) #define cimg_for_in7XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) cimg_for_in7Z(img,z0,z1,z) cimg_for_in7XY(img,x0,y0,x1,y1,x,y) #define cimg_for_in7XZC(img,x0,z0,c0,x1,y1,c1,x,z,c) cimg_for_in7C(img,c0,c1,c) cimg_for_in7XZ(img,x0,y0,x1,y1,x,z) #define cimg_for_in7YZC(img,y0,z0,c0,y1,z1,c1,y,z,c) cimg_for_in7C(img,c0,c1,c) cimg_for_in7YZ(img,y0,z0,y1,z1,y,z) #define cimg_for_in7XYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) \ cimg_for_in7C(img,c0,c1,c) cimg_for_in7XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for8(bound,i) \ for (int i = 0, _p3##i = 0, _p2##i = 0, _p1##i = 0, \ _n1##i = 1>=(bound)?(int)(bound) - 1:1, \ _n2##i = 2>=(bound)?(int)(bound) - 1:2, \ _n3##i = 3>=(bound)?(int)(bound) - 1:3, \ _n4##i = 4>=(bound)?(int)(bound) - 1:4; \ _n4##i<(int)(bound) || _n3##i==--_n4##i || _n2##i==--_n3##i || _n1##i==--_n2##i || \ i==(_n4##i = _n3##i = _n2##i = --_n1##i); \ _p3##i = _p2##i, _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i, ++_n3##i, ++_n4##i) #define cimg_for8X(img,x) cimg_for8((img)._width,x) #define cimg_for8Y(img,y) cimg_for8((img)._height,y) #define cimg_for8Z(img,z) cimg_for8((img)._depth,z) #define cimg_for8C(img,c) cimg_for8((img)._spectrum,c) #define cimg_for8XY(img,x,y) cimg_for8Y(img,y) cimg_for8X(img,x) #define cimg_for8XZ(img,x,z) cimg_for8Z(img,z) cimg_for8X(img,x) #define cimg_for8XC(img,x,c) cimg_for8C(img,c) cimg_for8X(img,x) #define cimg_for8YZ(img,y,z) cimg_for8Z(img,z) cimg_for8Y(img,y) #define cimg_for8YC(img,y,c) cimg_for8C(img,c) cimg_for8Y(img,y) #define cimg_for8ZC(img,z,c) cimg_for8C(img,c) cimg_for8Z(img,z) #define cimg_for8XYZ(img,x,y,z) cimg_for8Z(img,z) cimg_for8XY(img,x,y) #define cimg_for8XZC(img,x,z,c) cimg_for8C(img,c) cimg_for8XZ(img,x,z) #define cimg_for8YZC(img,y,z,c) cimg_for8C(img,c) cimg_for8YZ(img,y,z) #define cimg_for8XYZC(img,x,y,z,c) cimg_for8C(img,c) cimg_for8XYZ(img,x,y,z) #define cimg_for_in8(bound,i0,i1,i) \ for (int i = (int)(i0)<0?0:(int)(i0), \ _p3##i = i - 3<0?0:i - 3, \ _p2##i = i - 2<0?0:i - 2, \ _p1##i = i - 1<0?0:i - 1, \ _n1##i = i + 1>=(int)(bound)?(int)(bound) - 1:i + 1, \ _n2##i = i + 2>=(int)(bound)?(int)(bound) - 1:i + 2, \ _n3##i = i + 3>=(int)(bound)?(int)(bound) - 1:i + 3, \ _n4##i = i + 4>=(int)(bound)?(int)(bound) - 1:i + 4; \ i<=(int)(i1) && (_n4##i<(int)(bound) || _n3##i==--_n4##i || _n2##i==--_n3##i || _n1##i==--_n2##i || \ i==(_n4##i = _n3##i = _n2##i = --_n1##i)); \ _p3##i = _p2##i, _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i, ++_n3##i, ++_n4##i) #define cimg_for_in8X(img,x0,x1,x) cimg_for_in8((img)._width,x0,x1,x) #define cimg_for_in8Y(img,y0,y1,y) cimg_for_in8((img)._height,y0,y1,y) #define cimg_for_in8Z(img,z0,z1,z) cimg_for_in8((img)._depth,z0,z1,z) #define cimg_for_in8C(img,c0,c1,c) cimg_for_in8((img)._spectrum,c0,c1,c) #define cimg_for_in8XY(img,x0,y0,x1,y1,x,y) cimg_for_in8Y(img,y0,y1,y) cimg_for_in8X(img,x0,x1,x) #define cimg_for_in8XZ(img,x0,z0,x1,z1,x,z) cimg_for_in8Z(img,z0,z1,z) cimg_for_in8X(img,x0,x1,x) #define cimg_for_in8XC(img,x0,c0,x1,c1,x,c) cimg_for_in8C(img,c0,c1,c) cimg_for_in8X(img,x0,x1,x) #define cimg_for_in8YZ(img,y0,z0,y1,z1,y,z) cimg_for_in8Z(img,z0,z1,z) cimg_for_in8Y(img,y0,y1,y) #define cimg_for_in8YC(img,y0,c0,y1,c1,y,c) cimg_for_in8C(img,c0,c1,c) cimg_for_in8Y(img,y0,y1,y) #define cimg_for_in8ZC(img,z0,c0,z1,c1,z,c) cimg_for_in8C(img,c0,c1,c) cimg_for_in8Z(img,z0,z1,z) #define cimg_for_in8XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) cimg_for_in8Z(img,z0,z1,z) cimg_for_in8XY(img,x0,y0,x1,y1,x,y) #define cimg_for_in8XZC(img,x0,z0,c0,x1,y1,c1,x,z,c) cimg_for_in8C(img,c0,c1,c) cimg_for_in8XZ(img,x0,y0,x1,y1,x,z) #define cimg_for_in8YZC(img,y0,z0,c0,y1,z1,c1,y,z,c) cimg_for_in8C(img,c0,c1,c) cimg_for_in8YZ(img,y0,z0,y1,z1,y,z) #define cimg_for_in8XYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) \ cimg_for_in8C(img,c0,c1,c) cimg_for_in8XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for9(bound,i) \ for (int i = 0, _p4##i = 0, _p3##i = 0, _p2##i = 0, _p1##i = 0, \ _n1##i = 1>=(int)(bound)?(int)(bound) - 1:1, \ _n2##i = 2>=(int)(bound)?(int)(bound) - 1:2, \ _n3##i = 3>=(int)(bound)?(int)(bound) - 1:3, \ _n4##i = 4>=(int)(bound)?(int)(bound) - 1:4; \ _n4##i<(int)(bound) || _n3##i==--_n4##i || _n2##i==--_n3##i || _n1##i==--_n2##i || \ i==(_n4##i = _n3##i = _n2##i = --_n1##i); \ _p4##i = _p3##i, _p3##i = _p2##i, _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i, ++_n3##i, ++_n4##i) #define cimg_for9X(img,x) cimg_for9((img)._width,x) #define cimg_for9Y(img,y) cimg_for9((img)._height,y) #define cimg_for9Z(img,z) cimg_for9((img)._depth,z) #define cimg_for9C(img,c) cimg_for9((img)._spectrum,c) #define cimg_for9XY(img,x,y) cimg_for9Y(img,y) cimg_for9X(img,x) #define cimg_for9XZ(img,x,z) cimg_for9Z(img,z) cimg_for9X(img,x) #define cimg_for9XC(img,x,c) cimg_for9C(img,c) cimg_for9X(img,x) #define cimg_for9YZ(img,y,z) cimg_for9Z(img,z) cimg_for9Y(img,y) #define cimg_for9YC(img,y,c) cimg_for9C(img,c) cimg_for9Y(img,y) #define cimg_for9ZC(img,z,c) cimg_for9C(img,c) cimg_for9Z(img,z) #define cimg_for9XYZ(img,x,y,z) cimg_for9Z(img,z) cimg_for9XY(img,x,y) #define cimg_for9XZC(img,x,z,c) cimg_for9C(img,c) cimg_for9XZ(img,x,z) #define cimg_for9YZC(img,y,z,c) cimg_for9C(img,c) cimg_for9YZ(img,y,z) #define cimg_for9XYZC(img,x,y,z,c) cimg_for9C(img,c) cimg_for9XYZ(img,x,y,z) #define cimg_for_in9(bound,i0,i1,i) \ for (int i = (int)(i0)<0?0:(int)(i0), \ _p4##i = i - 4<0?0:i - 4, \ _p3##i = i - 3<0?0:i - 3, \ _p2##i = i - 2<0?0:i - 2, \ _p1##i = i - 1<0?0:i - 1, \ _n1##i = i + 1>=(int)(bound)?(int)(bound) - 1:i + 1, \ _n2##i = i + 2>=(int)(bound)?(int)(bound) - 1:i + 2, \ _n3##i = i + 3>=(int)(bound)?(int)(bound) - 1:i + 3, \ _n4##i = i + 4>=(int)(bound)?(int)(bound) - 1:i + 4; \ i<=(int)(i1) && (_n4##i<(int)(bound) || _n3##i==--_n4##i || _n2##i==--_n3##i || _n1##i==--_n2##i || \ i==(_n4##i = _n3##i = _n2##i = --_n1##i)); \ _p4##i = _p3##i, _p3##i = _p2##i, _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i, ++_n3##i, ++_n4##i) #define cimg_for_in9X(img,x0,x1,x) cimg_for_in9((img)._width,x0,x1,x) #define cimg_for_in9Y(img,y0,y1,y) cimg_for_in9((img)._height,y0,y1,y) #define cimg_for_in9Z(img,z0,z1,z) cimg_for_in9((img)._depth,z0,z1,z) #define cimg_for_in9C(img,c0,c1,c) cimg_for_in9((img)._spectrum,c0,c1,c) #define cimg_for_in9XY(img,x0,y0,x1,y1,x,y) cimg_for_in9Y(img,y0,y1,y) cimg_for_in9X(img,x0,x1,x) #define cimg_for_in9XZ(img,x0,z0,x1,z1,x,z) cimg_for_in9Z(img,z0,z1,z) cimg_for_in9X(img,x0,x1,x) #define cimg_for_in9XC(img,x0,c0,x1,c1,x,c) cimg_for_in9C(img,c0,c1,c) cimg_for_in9X(img,x0,x1,x) #define cimg_for_in9YZ(img,y0,z0,y1,z1,y,z) cimg_for_in9Z(img,z0,z1,z) cimg_for_in9Y(img,y0,y1,y) #define cimg_for_in9YC(img,y0,c0,y1,c1,y,c) cimg_for_in9C(img,c0,c1,c) cimg_for_in9Y(img,y0,y1,y) #define cimg_for_in9ZC(img,z0,c0,z1,c1,z,c) cimg_for_in9C(img,c0,c1,c) cimg_for_in9Z(img,z0,z1,z) #define cimg_for_in9XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) cimg_for_in9Z(img,z0,z1,z) cimg_for_in9XY(img,x0,y0,x1,y1,x,y) #define cimg_for_in9XZC(img,x0,z0,c0,x1,y1,c1,x,z,c) cimg_for_in9C(img,c0,c1,c) cimg_for_in9XZ(img,x0,y0,x1,y1,x,z) #define cimg_for_in9YZC(img,y0,z0,c0,y1,z1,c1,y,z,c) cimg_for_in9C(img,c0,c1,c) cimg_for_in9YZ(img,y0,z0,y1,z1,y,z) #define cimg_for_in9XYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) \ cimg_for_in9C(img,c0,c1,c) cimg_for_in9XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for2x2(img,x,y,z,c,I,T) \ cimg_for2((img)._height,y) for (int x = 0, \ _n1##x = (int)( \ (I[0] = (T)(img)(0,y,z,c)), \ (I[2] = (T)(img)(0,_n1##y,z,c)), \ 1>=(img)._width?(img).width() - 1:1); \ (_n1##x<(img).width() && ( \ (I[1] = (T)(img)(_n1##x,y,z,c)), \ (I[3] = (T)(img)(_n1##x,_n1##y,z,c)),1)) || \ x==--_n1##x; \ I[0] = I[1], \ I[2] = I[3], \ ++x, ++_n1##x) #define cimg_for_in2x2(img,x0,y0,x1,y1,x,y,z,c,I,T) \ cimg_for_in2((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)(x0), \ _n1##x = (int)( \ (I[0] = (T)(img)(x,y,z,c)), \ (I[2] = (T)(img)(x,_n1##y,z,c)), \ x + 1>=(int)(img)._width?(img).width() - 1:x + 1); \ x<=(int)(x1) && ((_n1##x<(img).width() && ( \ (I[1] = (T)(img)(_n1##x,y,z,c)), \ (I[3] = (T)(img)(_n1##x,_n1##y,z,c)),1)) || \ x==--_n1##x); \ I[0] = I[1], \ I[2] = I[3], \ ++x, ++_n1##x) #define cimg_for3x3(img,x,y,z,c,I,T) \ cimg_for3((img)._height,y) for (int x = 0, \ _p1##x = 0, \ _n1##x = (int)( \ (I[0] = I[1] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[3] = I[4] = (T)(img)(0,y,z,c)), \ (I[6] = I[7] = (T)(img)(0,_n1##y,z,c)), \ 1>=(img)._width?(img).width() - 1:1); \ (_n1##x<(img).width() && ( \ (I[2] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[5] = (T)(img)(_n1##x,y,z,c)), \ (I[8] = (T)(img)(_n1##x,_n1##y,z,c)),1)) || \ x==--_n1##x; \ I[0] = I[1], I[1] = I[2], \ I[3] = I[4], I[4] = I[5], \ I[6] = I[7], I[7] = I[8], \ _p1##x = x++, ++_n1##x) #define cimg_for_in3x3(img,x0,y0,x1,y1,x,y,z,c,I,T) \ cimg_for_in3((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)(x0), \ _p1##x = x - 1<0?0:x - 1, \ _n1##x = (int)( \ (I[0] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[3] = (T)(img)(_p1##x,y,z,c)), \ (I[6] = (T)(img)(_p1##x,_n1##y,z,c)), \ (I[1] = (T)(img)(x,_p1##y,z,c)), \ (I[4] = (T)(img)(x,y,z,c)), \ (I[7] = (T)(img)(x,_n1##y,z,c)), \ x + 1>=(int)(img)._width?(img).width() - 1:x + 1); \ x<=(int)(x1) && ((_n1##x<(img).width() && ( \ (I[2] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[5] = (T)(img)(_n1##x,y,z,c)), \ (I[8] = (T)(img)(_n1##x,_n1##y,z,c)),1)) || \ x==--_n1##x); \ I[0] = I[1], I[1] = I[2], \ I[3] = I[4], I[4] = I[5], \ I[6] = I[7], I[7] = I[8], \ _p1##x = x++, ++_n1##x) #define cimg_for4x4(img,x,y,z,c,I,T) \ cimg_for4((img)._height,y) for (int x = 0, \ _p1##x = 0, \ _n1##x = 1>=(img)._width?(img).width() - 1:1, \ _n2##x = (int)( \ (I[0] = I[1] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[4] = I[5] = (T)(img)(0,y,z,c)), \ (I[8] = I[9] = (T)(img)(0,_n1##y,z,c)), \ (I[12] = I[13] = (T)(img)(0,_n2##y,z,c)), \ (I[2] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[6] = (T)(img)(_n1##x,y,z,c)), \ (I[10] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[14] = (T)(img)(_n1##x,_n2##y,z,c)), \ 2>=(img)._width?(img).width() - 1:2); \ (_n2##x<(img).width() && ( \ (I[3] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[7] = (T)(img)(_n2##x,y,z,c)), \ (I[11] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[15] = (T)(img)(_n2##x,_n2##y,z,c)),1)) || \ _n1##x==--_n2##x || x==(_n2##x = --_n1##x); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], \ I[4] = I[5], I[5] = I[6], I[6] = I[7], \ I[8] = I[9], I[9] = I[10], I[10] = I[11], \ I[12] = I[13], I[13] = I[14], I[14] = I[15], \ _p1##x = x++, ++_n1##x, ++_n2##x) #define cimg_for_in4x4(img,x0,y0,x1,y1,x,y,z,c,I,T) \ cimg_for_in4((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)(x0), \ _p1##x = x - 1<0?0:x - 1, \ _n1##x = x + 1>=(int)(img)._width?(img).width() - 1:x + 1, \ _n2##x = (int)( \ (I[0] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[4] = (T)(img)(_p1##x,y,z,c)), \ (I[8] = (T)(img)(_p1##x,_n1##y,z,c)), \ (I[12] = (T)(img)(_p1##x,_n2##y,z,c)), \ (I[1] = (T)(img)(x,_p1##y,z,c)), \ (I[5] = (T)(img)(x,y,z,c)), \ (I[9] = (T)(img)(x,_n1##y,z,c)), \ (I[13] = (T)(img)(x,_n2##y,z,c)), \ (I[2] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[6] = (T)(img)(_n1##x,y,z,c)), \ (I[10] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[14] = (T)(img)(_n1##x,_n2##y,z,c)), \ x + 2>=(int)(img)._width?(img).width() - 1:x + 2); \ x<=(int)(x1) && ((_n2##x<(img).width() && ( \ (I[3] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[7] = (T)(img)(_n2##x,y,z,c)), \ (I[11] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[15] = (T)(img)(_n2##x,_n2##y,z,c)),1)) || \ _n1##x==--_n2##x || x==(_n2##x = --_n1##x)); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], \ I[4] = I[5], I[5] = I[6], I[6] = I[7], \ I[8] = I[9], I[9] = I[10], I[10] = I[11], \ I[12] = I[13], I[13] = I[14], I[14] = I[15], \ _p1##x = x++, ++_n1##x, ++_n2##x) #define cimg_for5x5(img,x,y,z,c,I,T) \ cimg_for5((img)._height,y) for (int x = 0, \ _p2##x = 0, _p1##x = 0, \ _n1##x = 1>=(img)._width?(img).width() - 1:1, \ _n2##x = (int)( \ (I[0] = I[1] = I[2] = (T)(img)(_p2##x,_p2##y,z,c)), \ (I[5] = I[6] = I[7] = (T)(img)(0,_p1##y,z,c)), \ (I[10] = I[11] = I[12] = (T)(img)(0,y,z,c)), \ (I[15] = I[16] = I[17] = (T)(img)(0,_n1##y,z,c)), \ (I[20] = I[21] = I[22] = (T)(img)(0,_n2##y,z,c)), \ (I[3] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[8] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[13] = (T)(img)(_n1##x,y,z,c)), \ (I[18] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[23] = (T)(img)(_n1##x,_n2##y,z,c)), \ 2>=(img)._width?(img).width() - 1:2); \ (_n2##x<(img).width() && ( \ (I[4] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[9] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[14] = (T)(img)(_n2##x,y,z,c)), \ (I[19] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[24] = (T)(img)(_n2##x,_n2##y,z,c)),1)) || \ _n1##x==--_n2##x || x==(_n2##x = --_n1##x); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], \ I[5] = I[6], I[6] = I[7], I[7] = I[8], I[8] = I[9], \ I[10] = I[11], I[11] = I[12], I[12] = I[13], I[13] = I[14], \ I[15] = I[16], I[16] = I[17], I[17] = I[18], I[18] = I[19], \ I[20] = I[21], I[21] = I[22], I[22] = I[23], I[23] = I[24], \ _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x) #define cimg_for_in5x5(img,x0,y0,x1,y1,x,y,z,c,I,T) \ cimg_for_in5((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)(x0), \ _p2##x = x - 2<0?0:x - 2, \ _p1##x = x - 1<0?0:x - 1, \ _n1##x = x + 1>=(int)(img)._width?(img).width() - 1:x + 1, \ _n2##x = (int)( \ (I[0] = (T)(img)(_p2##x,_p2##y,z,c)), \ (I[5] = (T)(img)(_p2##x,_p1##y,z,c)), \ (I[10] = (T)(img)(_p2##x,y,z,c)), \ (I[15] = (T)(img)(_p2##x,_n1##y,z,c)), \ (I[20] = (T)(img)(_p2##x,_n2##y,z,c)), \ (I[1] = (T)(img)(_p1##x,_p2##y,z,c)), \ (I[6] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[11] = (T)(img)(_p1##x,y,z,c)), \ (I[16] = (T)(img)(_p1##x,_n1##y,z,c)), \ (I[21] = (T)(img)(_p1##x,_n2##y,z,c)), \ (I[2] = (T)(img)(x,_p2##y,z,c)), \ (I[7] = (T)(img)(x,_p1##y,z,c)), \ (I[12] = (T)(img)(x,y,z,c)), \ (I[17] = (T)(img)(x,_n1##y,z,c)), \ (I[22] = (T)(img)(x,_n2##y,z,c)), \ (I[3] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[8] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[13] = (T)(img)(_n1##x,y,z,c)), \ (I[18] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[23] = (T)(img)(_n1##x,_n2##y,z,c)), \ x + 2>=(int)(img)._width?(img).width() - 1:x + 2); \ x<=(int)(x1) && ((_n2##x<(img).width() && ( \ (I[4] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[9] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[14] = (T)(img)(_n2##x,y,z,c)), \ (I[19] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[24] = (T)(img)(_n2##x,_n2##y,z,c)),1)) || \ _n1##x==--_n2##x || x==(_n2##x = --_n1##x)); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], \ I[5] = I[6], I[6] = I[7], I[7] = I[8], I[8] = I[9], \ I[10] = I[11], I[11] = I[12], I[12] = I[13], I[13] = I[14], \ I[15] = I[16], I[16] = I[17], I[17] = I[18], I[18] = I[19], \ I[20] = I[21], I[21] = I[22], I[22] = I[23], I[23] = I[24], \ _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x) #define cimg_for6x6(img,x,y,z,c,I,T) \ cimg_for6((img)._height,y) for (int x = 0, \ _p2##x = 0, _p1##x = 0, \ _n1##x = 1>=(img)._width?(img).width() - 1:1, \ _n2##x = 2>=(img)._width?(img).width() - 1:2, \ _n3##x = (int)( \ (I[0] = I[1] = I[2] = (T)(img)(_p2##x,_p2##y,z,c)), \ (I[6] = I[7] = I[8] = (T)(img)(0,_p1##y,z,c)), \ (I[12] = I[13] = I[14] = (T)(img)(0,y,z,c)), \ (I[18] = I[19] = I[20] = (T)(img)(0,_n1##y,z,c)), \ (I[24] = I[25] = I[26] = (T)(img)(0,_n2##y,z,c)), \ (I[30] = I[31] = I[32] = (T)(img)(0,_n3##y,z,c)), \ (I[3] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[9] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[15] = (T)(img)(_n1##x,y,z,c)), \ (I[21] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[27] = (T)(img)(_n1##x,_n2##y,z,c)), \ (I[33] = (T)(img)(_n1##x,_n3##y,z,c)), \ (I[4] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[10] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[16] = (T)(img)(_n2##x,y,z,c)), \ (I[22] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[28] = (T)(img)(_n2##x,_n2##y,z,c)), \ (I[34] = (T)(img)(_n2##x,_n3##y,z,c)), \ 3>=(img)._width?(img).width() - 1:3); \ (_n3##x<(img).width() && ( \ (I[5] = (T)(img)(_n3##x,_p2##y,z,c)), \ (I[11] = (T)(img)(_n3##x,_p1##y,z,c)), \ (I[17] = (T)(img)(_n3##x,y,z,c)), \ (I[23] = (T)(img)(_n3##x,_n1##y,z,c)), \ (I[29] = (T)(img)(_n3##x,_n2##y,z,c)), \ (I[35] = (T)(img)(_n3##x,_n3##y,z,c)),1)) || \ _n2##x==--_n3##x || _n1##x==--_n2##x || x==(_n3## x = _n2##x = --_n1##x); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], I[4] = I[5], \ I[6] = I[7], I[7] = I[8], I[8] = I[9], I[9] = I[10], I[10] = I[11], \ I[12] = I[13], I[13] = I[14], I[14] = I[15], I[15] = I[16], I[16] = I[17], \ I[18] = I[19], I[19] = I[20], I[20] = I[21], I[21] = I[22], I[22] = I[23], \ I[24] = I[25], I[25] = I[26], I[26] = I[27], I[27] = I[28], I[28] = I[29], \ I[30] = I[31], I[31] = I[32], I[32] = I[33], I[33] = I[34], I[34] = I[35], \ _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x, ++_n3##x) #define cimg_for_in6x6(img,x0,y0,x1,y1,x,y,z,c,I,T) \ cimg_for_in6((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)x0, \ _p2##x = x - 2<0?0:x - 2, \ _p1##x = x - 1<0?0:x - 1, \ _n1##x = x + 1>=(int)(img)._width?(img).width() - 1:x + 1, \ _n2##x = x + 2>=(int)(img)._width?(img).width() - 1:x + 2, \ _n3##x = (int)( \ (I[0] = (T)(img)(_p2##x,_p2##y,z,c)), \ (I[6] = (T)(img)(_p2##x,_p1##y,z,c)), \ (I[12] = (T)(img)(_p2##x,y,z,c)), \ (I[18] = (T)(img)(_p2##x,_n1##y,z,c)), \ (I[24] = (T)(img)(_p2##x,_n2##y,z,c)), \ (I[30] = (T)(img)(_p2##x,_n3##y,z,c)), \ (I[1] = (T)(img)(_p1##x,_p2##y,z,c)), \ (I[7] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[13] = (T)(img)(_p1##x,y,z,c)), \ (I[19] = (T)(img)(_p1##x,_n1##y,z,c)), \ (I[25] = (T)(img)(_p1##x,_n2##y,z,c)), \ (I[31] = (T)(img)(_p1##x,_n3##y,z,c)), \ (I[2] = (T)(img)(x,_p2##y,z,c)), \ (I[8] = (T)(img)(x,_p1##y,z,c)), \ (I[14] = (T)(img)(x,y,z,c)), \ (I[20] = (T)(img)(x,_n1##y,z,c)), \ (I[26] = (T)(img)(x,_n2##y,z,c)), \ (I[32] = (T)(img)(x,_n3##y,z,c)), \ (I[3] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[9] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[15] = (T)(img)(_n1##x,y,z,c)), \ (I[21] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[27] = (T)(img)(_n1##x,_n2##y,z,c)), \ (I[33] = (T)(img)(_n1##x,_n3##y,z,c)), \ (I[4] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[10] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[16] = (T)(img)(_n2##x,y,z,c)), \ (I[22] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[28] = (T)(img)(_n2##x,_n2##y,z,c)), \ (I[34] = (T)(img)(_n2##x,_n3##y,z,c)), \ x + 3>=(int)(img)._width?(img).width() - 1:x + 3); \ x<=(int)(x1) && ((_n3##x<(img).width() && ( \ (I[5] = (T)(img)(_n3##x,_p2##y,z,c)), \ (I[11] = (T)(img)(_n3##x,_p1##y,z,c)), \ (I[17] = (T)(img)(_n3##x,y,z,c)), \ (I[23] = (T)(img)(_n3##x,_n1##y,z,c)), \ (I[29] = (T)(img)(_n3##x,_n2##y,z,c)), \ (I[35] = (T)(img)(_n3##x,_n3##y,z,c)),1)) || \ _n2##x==--_n3##x || _n1##x==--_n2##x || x==(_n3## x = _n2##x = --_n1##x)); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], I[4] = I[5], \ I[6] = I[7], I[7] = I[8], I[8] = I[9], I[9] = I[10], I[10] = I[11], \ I[12] = I[13], I[13] = I[14], I[14] = I[15], I[15] = I[16], I[16] = I[17], \ I[18] = I[19], I[19] = I[20], I[20] = I[21], I[21] = I[22], I[22] = I[23], \ I[24] = I[25], I[25] = I[26], I[26] = I[27], I[27] = I[28], I[28] = I[29], \ I[30] = I[31], I[31] = I[32], I[32] = I[33], I[33] = I[34], I[34] = I[35], \ _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x, ++_n3##x) #define cimg_for7x7(img,x,y,z,c,I,T) \ cimg_for7((img)._height,y) for (int x = 0, \ _p3##x = 0, _p2##x = 0, _p1##x = 0, \ _n1##x = 1>=(img)._width?(img).width() - 1:1, \ _n2##x = 2>=(img)._width?(img).width() - 1:2, \ _n3##x = (int)( \ (I[0] = I[1] = I[2] = I[3] = (T)(img)(_p3##x,_p3##y,z,c)), \ (I[7] = I[8] = I[9] = I[10] = (T)(img)(0,_p2##y,z,c)), \ (I[14] = I[15] = I[16] = I[17] = (T)(img)(0,_p1##y,z,c)), \ (I[21] = I[22] = I[23] = I[24] = (T)(img)(0,y,z,c)), \ (I[28] = I[29] = I[30] = I[31] = (T)(img)(0,_n1##y,z,c)), \ (I[35] = I[36] = I[37] = I[38] = (T)(img)(0,_n2##y,z,c)), \ (I[42] = I[43] = I[44] = I[45] = (T)(img)(0,_n3##y,z,c)), \ (I[4] = (T)(img)(_n1##x,_p3##y,z,c)), \ (I[11] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[18] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[25] = (T)(img)(_n1##x,y,z,c)), \ (I[32] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[39] = (T)(img)(_n1##x,_n2##y,z,c)), \ (I[46] = (T)(img)(_n1##x,_n3##y,z,c)), \ (I[5] = (T)(img)(_n2##x,_p3##y,z,c)), \ (I[12] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[19] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[26] = (T)(img)(_n2##x,y,z,c)), \ (I[33] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[40] = (T)(img)(_n2##x,_n2##y,z,c)), \ (I[47] = (T)(img)(_n2##x,_n3##y,z,c)), \ 3>=(img)._width?(img).width() - 1:3); \ (_n3##x<(img).width() && ( \ (I[6] = (T)(img)(_n3##x,_p3##y,z,c)), \ (I[13] = (T)(img)(_n3##x,_p2##y,z,c)), \ (I[20] = (T)(img)(_n3##x,_p1##y,z,c)), \ (I[27] = (T)(img)(_n3##x,y,z,c)), \ (I[34] = (T)(img)(_n3##x,_n1##y,z,c)), \ (I[41] = (T)(img)(_n3##x,_n2##y,z,c)), \ (I[48] = (T)(img)(_n3##x,_n3##y,z,c)),1)) || \ _n2##x==--_n3##x || _n1##x==--_n2##x || x==(_n3##x = _n2##x = --_n1##x); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], I[4] = I[5], I[5] = I[6], \ I[7] = I[8], I[8] = I[9], I[9] = I[10], I[10] = I[11], I[11] = I[12], I[12] = I[13], \ I[14] = I[15], I[15] = I[16], I[16] = I[17], I[17] = I[18], I[18] = I[19], I[19] = I[20], \ I[21] = I[22], I[22] = I[23], I[23] = I[24], I[24] = I[25], I[25] = I[26], I[26] = I[27], \ I[28] = I[29], I[29] = I[30], I[30] = I[31], I[31] = I[32], I[32] = I[33], I[33] = I[34], \ I[35] = I[36], I[36] = I[37], I[37] = I[38], I[38] = I[39], I[39] = I[40], I[40] = I[41], \ I[42] = I[43], I[43] = I[44], I[44] = I[45], I[45] = I[46], I[46] = I[47], I[47] = I[48], \ _p3##x = _p2##x, _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x, ++_n3##x) #define cimg_for_in7x7(img,x0,y0,x1,y1,x,y,z,c,I,T) \ cimg_for_in7((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)(x0), \ _p3##x = x - 3<0?0:x - 3, \ _p2##x = x - 2<0?0:x - 2, \ _p1##x = x - 1<0?0:x - 1, \ _n1##x = x + 1>=(int)(img)._width?(img).width() - 1:x + 1, \ _n2##x = x + 2>=(int)(img)._width?(img).width() - 1:x + 2, \ _n3##x = (int)( \ (I[0] = (T)(img)(_p3##x,_p3##y,z,c)), \ (I[7] = (T)(img)(_p3##x,_p2##y,z,c)), \ (I[14] = (T)(img)(_p3##x,_p1##y,z,c)), \ (I[21] = (T)(img)(_p3##x,y,z,c)), \ (I[28] = (T)(img)(_p3##x,_n1##y,z,c)), \ (I[35] = (T)(img)(_p3##x,_n2##y,z,c)), \ (I[42] = (T)(img)(_p3##x,_n3##y,z,c)), \ (I[1] = (T)(img)(_p2##x,_p3##y,z,c)), \ (I[8] = (T)(img)(_p2##x,_p2##y,z,c)), \ (I[15] = (T)(img)(_p2##x,_p1##y,z,c)), \ (I[22] = (T)(img)(_p2##x,y,z,c)), \ (I[29] = (T)(img)(_p2##x,_n1##y,z,c)), \ (I[36] = (T)(img)(_p2##x,_n2##y,z,c)), \ (I[43] = (T)(img)(_p2##x,_n3##y,z,c)), \ (I[2] = (T)(img)(_p1##x,_p3##y,z,c)), \ (I[9] = (T)(img)(_p1##x,_p2##y,z,c)), \ (I[16] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[23] = (T)(img)(_p1##x,y,z,c)), \ (I[30] = (T)(img)(_p1##x,_n1##y,z,c)), \ (I[37] = (T)(img)(_p1##x,_n2##y,z,c)), \ (I[44] = (T)(img)(_p1##x,_n3##y,z,c)), \ (I[3] = (T)(img)(x,_p3##y,z,c)), \ (I[10] = (T)(img)(x,_p2##y,z,c)), \ (I[17] = (T)(img)(x,_p1##y,z,c)), \ (I[24] = (T)(img)(x,y,z,c)), \ (I[31] = (T)(img)(x,_n1##y,z,c)), \ (I[38] = (T)(img)(x,_n2##y,z,c)), \ (I[45] = (T)(img)(x,_n3##y,z,c)), \ (I[4] = (T)(img)(_n1##x,_p3##y,z,c)), \ (I[11] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[18] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[25] = (T)(img)(_n1##x,y,z,c)), \ (I[32] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[39] = (T)(img)(_n1##x,_n2##y,z,c)), \ (I[46] = (T)(img)(_n1##x,_n3##y,z,c)), \ (I[5] = (T)(img)(_n2##x,_p3##y,z,c)), \ (I[12] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[19] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[26] = (T)(img)(_n2##x,y,z,c)), \ (I[33] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[40] = (T)(img)(_n2##x,_n2##y,z,c)), \ (I[47] = (T)(img)(_n2##x,_n3##y,z,c)), \ x + 3>=(int)(img)._width?(img).width() - 1:x + 3); \ x<=(int)(x1) && ((_n3##x<(img).width() && ( \ (I[6] = (T)(img)(_n3##x,_p3##y,z,c)), \ (I[13] = (T)(img)(_n3##x,_p2##y,z,c)), \ (I[20] = (T)(img)(_n3##x,_p1##y,z,c)), \ (I[27] = (T)(img)(_n3##x,y,z,c)), \ (I[34] = (T)(img)(_n3##x,_n1##y,z,c)), \ (I[41] = (T)(img)(_n3##x,_n2##y,z,c)), \ (I[48] = (T)(img)(_n3##x,_n3##y,z,c)),1)) || \ _n2##x==--_n3##x || _n1##x==--_n2##x || x==(_n3##x = _n2##x = --_n1##x)); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], I[4] = I[5], I[5] = I[6], \ I[7] = I[8], I[8] = I[9], I[9] = I[10], I[10] = I[11], I[11] = I[12], I[12] = I[13], \ I[14] = I[15], I[15] = I[16], I[16] = I[17], I[17] = I[18], I[18] = I[19], I[19] = I[20], \ I[21] = I[22], I[22] = I[23], I[23] = I[24], I[24] = I[25], I[25] = I[26], I[26] = I[27], \ I[28] = I[29], I[29] = I[30], I[30] = I[31], I[31] = I[32], I[32] = I[33], I[33] = I[34], \ I[35] = I[36], I[36] = I[37], I[37] = I[38], I[38] = I[39], I[39] = I[40], I[40] = I[41], \ I[42] = I[43], I[43] = I[44], I[44] = I[45], I[45] = I[46], I[46] = I[47], I[47] = I[48], \ _p3##x = _p2##x, _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x, ++_n3##x) #define cimg_for8x8(img,x,y,z,c,I,T) \ cimg_for8((img)._height,y) for (int x = 0, \ _p3##x = 0, _p2##x = 0, _p1##x = 0, \ _n1##x = 1>=((img)._width)?(img).width() - 1:1, \ _n2##x = 2>=((img)._width)?(img).width() - 1:2, \ _n3##x = 3>=((img)._width)?(img).width() - 1:3, \ _n4##x = (int)( \ (I[0] = I[1] = I[2] = I[3] = (T)(img)(_p3##x,_p3##y,z,c)), \ (I[8] = I[9] = I[10] = I[11] = (T)(img)(0,_p2##y,z,c)), \ (I[16] = I[17] = I[18] = I[19] = (T)(img)(0,_p1##y,z,c)), \ (I[24] = I[25] = I[26] = I[27] = (T)(img)(0,y,z,c)), \ (I[32] = I[33] = I[34] = I[35] = (T)(img)(0,_n1##y,z,c)), \ (I[40] = I[41] = I[42] = I[43] = (T)(img)(0,_n2##y,z,c)), \ (I[48] = I[49] = I[50] = I[51] = (T)(img)(0,_n3##y,z,c)), \ (I[56] = I[57] = I[58] = I[59] = (T)(img)(0,_n4##y,z,c)), \ (I[4] = (T)(img)(_n1##x,_p3##y,z,c)), \ (I[12] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[20] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[28] = (T)(img)(_n1##x,y,z,c)), \ (I[36] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[44] = (T)(img)(_n1##x,_n2##y,z,c)), \ (I[52] = (T)(img)(_n1##x,_n3##y,z,c)), \ (I[60] = (T)(img)(_n1##x,_n4##y,z,c)), \ (I[5] = (T)(img)(_n2##x,_p3##y,z,c)), \ (I[13] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[21] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[29] = (T)(img)(_n2##x,y,z,c)), \ (I[37] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[45] = (T)(img)(_n2##x,_n2##y,z,c)), \ (I[53] = (T)(img)(_n2##x,_n3##y,z,c)), \ (I[61] = (T)(img)(_n2##x,_n4##y,z,c)), \ (I[6] = (T)(img)(_n3##x,_p3##y,z,c)), \ (I[14] = (T)(img)(_n3##x,_p2##y,z,c)), \ (I[22] = (T)(img)(_n3##x,_p1##y,z,c)), \ (I[30] = (T)(img)(_n3##x,y,z,c)), \ (I[38] = (T)(img)(_n3##x,_n1##y,z,c)), \ (I[46] = (T)(img)(_n3##x,_n2##y,z,c)), \ (I[54] = (T)(img)(_n3##x,_n3##y,z,c)), \ (I[62] = (T)(img)(_n3##x,_n4##y,z,c)), \ 4>=((img)._width)?(img).width() - 1:4); \ (_n4##x<(img).width() && ( \ (I[7] = (T)(img)(_n4##x,_p3##y,z,c)), \ (I[15] = (T)(img)(_n4##x,_p2##y,z,c)), \ (I[23] = (T)(img)(_n4##x,_p1##y,z,c)), \ (I[31] = (T)(img)(_n4##x,y,z,c)), \ (I[39] = (T)(img)(_n4##x,_n1##y,z,c)), \ (I[47] = (T)(img)(_n4##x,_n2##y,z,c)), \ (I[55] = (T)(img)(_n4##x,_n3##y,z,c)), \ (I[63] = (T)(img)(_n4##x,_n4##y,z,c)),1)) || \ _n3##x==--_n4##x || _n2##x==--_n3##x || _n1##x==--_n2##x || x==(_n4##x = _n3##x = _n2##x = --_n1##x); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], I[4] = I[5], I[5] = I[6], I[6] = I[7], \ I[8] = I[9], I[9] = I[10], I[10] = I[11], I[11] = I[12], I[12] = I[13], I[13] = I[14], I[14] = I[15], \ I[16] = I[17], I[17] = I[18], I[18] = I[19], I[19] = I[20], I[20] = I[21], I[21] = I[22], I[22] = I[23], \ I[24] = I[25], I[25] = I[26], I[26] = I[27], I[27] = I[28], I[28] = I[29], I[29] = I[30], I[30] = I[31], \ I[32] = I[33], I[33] = I[34], I[34] = I[35], I[35] = I[36], I[36] = I[37], I[37] = I[38], I[38] = I[39], \ I[40] = I[41], I[41] = I[42], I[42] = I[43], I[43] = I[44], I[44] = I[45], I[45] = I[46], I[46] = I[47], \ I[48] = I[49], I[49] = I[50], I[50] = I[51], I[51] = I[52], I[52] = I[53], I[53] = I[54], I[54] = I[55], \ I[56] = I[57], I[57] = I[58], I[58] = I[59], I[59] = I[60], I[60] = I[61], I[61] = I[62], I[62] = I[63], \ _p3##x = _p2##x, _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x, ++_n3##x, ++_n4##x) #define cimg_for_in8x8(img,x0,y0,x1,y1,x,y,z,c,I,T) \ cimg_for_in8((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)(x0), \ _p3##x = x - 3<0?0:x - 3, \ _p2##x = x - 2<0?0:x - 2, \ _p1##x = x - 1<0?0:x - 1, \ _n1##x = x + 1>=(img).width()?(img).width() - 1:x + 1, \ _n2##x = x + 2>=(img).width()?(img).width() - 1:x + 2, \ _n3##x = x + 3>=(img).width()?(img).width() - 1:x + 3, \ _n4##x = (int)( \ (I[0] = (T)(img)(_p3##x,_p3##y,z,c)), \ (I[8] = (T)(img)(_p3##x,_p2##y,z,c)), \ (I[16] = (T)(img)(_p3##x,_p1##y,z,c)), \ (I[24] = (T)(img)(_p3##x,y,z,c)), \ (I[32] = (T)(img)(_p3##x,_n1##y,z,c)), \ (I[40] = (T)(img)(_p3##x,_n2##y,z,c)), \ (I[48] = (T)(img)(_p3##x,_n3##y,z,c)), \ (I[56] = (T)(img)(_p3##x,_n4##y,z,c)), \ (I[1] = (T)(img)(_p2##x,_p3##y,z,c)), \ (I[9] = (T)(img)(_p2##x,_p2##y,z,c)), \ (I[17] = (T)(img)(_p2##x,_p1##y,z,c)), \ (I[25] = (T)(img)(_p2##x,y,z,c)), \ (I[33] = (T)(img)(_p2##x,_n1##y,z,c)), \ (I[41] = (T)(img)(_p2##x,_n2##y,z,c)), \ (I[49] = (T)(img)(_p2##x,_n3##y,z,c)), \ (I[57] = (T)(img)(_p2##x,_n4##y,z,c)), \ (I[2] = (T)(img)(_p1##x,_p3##y,z,c)), \ (I[10] = (T)(img)(_p1##x,_p2##y,z,c)), \ (I[18] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[26] = (T)(img)(_p1##x,y,z,c)), \ (I[34] = (T)(img)(_p1##x,_n1##y,z,c)), \ (I[42] = (T)(img)(_p1##x,_n2##y,z,c)), \ (I[50] = (T)(img)(_p1##x,_n3##y,z,c)), \ (I[58] = (T)(img)(_p1##x,_n4##y,z,c)), \ (I[3] = (T)(img)(x,_p3##y,z,c)), \ (I[11] = (T)(img)(x,_p2##y,z,c)), \ (I[19] = (T)(img)(x,_p1##y,z,c)), \ (I[27] = (T)(img)(x,y,z,c)), \ (I[35] = (T)(img)(x,_n1##y,z,c)), \ (I[43] = (T)(img)(x,_n2##y,z,c)), \ (I[51] = (T)(img)(x,_n3##y,z,c)), \ (I[59] = (T)(img)(x,_n4##y,z,c)), \ (I[4] = (T)(img)(_n1##x,_p3##y,z,c)), \ (I[12] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[20] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[28] = (T)(img)(_n1##x,y,z,c)), \ (I[36] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[44] = (T)(img)(_n1##x,_n2##y,z,c)), \ (I[52] = (T)(img)(_n1##x,_n3##y,z,c)), \ (I[60] = (T)(img)(_n1##x,_n4##y,z,c)), \ (I[5] = (T)(img)(_n2##x,_p3##y,z,c)), \ (I[13] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[21] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[29] = (T)(img)(_n2##x,y,z,c)), \ (I[37] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[45] = (T)(img)(_n2##x,_n2##y,z,c)), \ (I[53] = (T)(img)(_n2##x,_n3##y,z,c)), \ (I[61] = (T)(img)(_n2##x,_n4##y,z,c)), \ (I[6] = (T)(img)(_n3##x,_p3##y,z,c)), \ (I[14] = (T)(img)(_n3##x,_p2##y,z,c)), \ (I[22] = (T)(img)(_n3##x,_p1##y,z,c)), \ (I[30] = (T)(img)(_n3##x,y,z,c)), \ (I[38] = (T)(img)(_n3##x,_n1##y,z,c)), \ (I[46] = (T)(img)(_n3##x,_n2##y,z,c)), \ (I[54] = (T)(img)(_n3##x,_n3##y,z,c)), \ (I[62] = (T)(img)(_n3##x,_n4##y,z,c)), \ x + 4>=(img).width()?(img).width() - 1:x + 4); \ x<=(int)(x1) && ((_n4##x<(img).width() && ( \ (I[7] = (T)(img)(_n4##x,_p3##y,z,c)), \ (I[15] = (T)(img)(_n4##x,_p2##y,z,c)), \ (I[23] = (T)(img)(_n4##x,_p1##y,z,c)), \ (I[31] = (T)(img)(_n4##x,y,z,c)), \ (I[39] = (T)(img)(_n4##x,_n1##y,z,c)), \ (I[47] = (T)(img)(_n4##x,_n2##y,z,c)), \ (I[55] = (T)(img)(_n4##x,_n3##y,z,c)), \ (I[63] = (T)(img)(_n4##x,_n4##y,z,c)),1)) || \ _n3##x==--_n4##x || _n2##x==--_n3##x || _n1##x==--_n2##x || x==(_n4##x = _n3##x = _n2##x = --_n1##x)); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], I[4] = I[5], I[5] = I[6], I[6] = I[7], \ I[8] = I[9], I[9] = I[10], I[10] = I[11], I[11] = I[12], I[12] = I[13], I[13] = I[14], I[14] = I[15], \ I[16] = I[17], I[17] = I[18], I[18] = I[19], I[19] = I[20], I[20] = I[21], I[21] = I[22], I[22] = I[23], \ I[24] = I[25], I[25] = I[26], I[26] = I[27], I[27] = I[28], I[28] = I[29], I[29] = I[30], I[30] = I[31], \ I[32] = I[33], I[33] = I[34], I[34] = I[35], I[35] = I[36], I[36] = I[37], I[37] = I[38], I[38] = I[39], \ I[40] = I[41], I[41] = I[42], I[42] = I[43], I[43] = I[44], I[44] = I[45], I[45] = I[46], I[46] = I[47], \ I[48] = I[49], I[49] = I[50], I[50] = I[51], I[51] = I[52], I[52] = I[53], I[53] = I[54], I[54] = I[55], \ I[56] = I[57], I[57] = I[58], I[58] = I[59], I[59] = I[60], I[60] = I[61], I[61] = I[62], I[62] = I[63], \ _p3##x = _p2##x, _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x, ++_n3##x, ++_n4##x) #define cimg_for9x9(img,x,y,z,c,I,T) \ cimg_for9((img)._height,y) for (int x = 0, \ _p4##x = 0, _p3##x = 0, _p2##x = 0, _p1##x = 0, \ _n1##x = 1>=((img)._width)?(img).width() - 1:1, \ _n2##x = 2>=((img)._width)?(img).width() - 1:2, \ _n3##x = 3>=((img)._width)?(img).width() - 1:3, \ _n4##x = (int)( \ (I[0] = I[1] = I[2] = I[3] = I[4] = (T)(img)(_p4##x,_p4##y,z,c)), \ (I[9] = I[10] = I[11] = I[12] = I[13] = (T)(img)(0,_p3##y,z,c)), \ (I[18] = I[19] = I[20] = I[21] = I[22] = (T)(img)(0,_p2##y,z,c)), \ (I[27] = I[28] = I[29] = I[30] = I[31] = (T)(img)(0,_p1##y,z,c)), \ (I[36] = I[37] = I[38] = I[39] = I[40] = (T)(img)(0,y,z,c)), \ (I[45] = I[46] = I[47] = I[48] = I[49] = (T)(img)(0,_n1##y,z,c)), \ (I[54] = I[55] = I[56] = I[57] = I[58] = (T)(img)(0,_n2##y,z,c)), \ (I[63] = I[64] = I[65] = I[66] = I[67] = (T)(img)(0,_n3##y,z,c)), \ (I[72] = I[73] = I[74] = I[75] = I[76] = (T)(img)(0,_n4##y,z,c)), \ (I[5] = (T)(img)(_n1##x,_p4##y,z,c)), \ (I[14] = (T)(img)(_n1##x,_p3##y,z,c)), \ (I[23] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[32] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[41] = (T)(img)(_n1##x,y,z,c)), \ (I[50] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[59] = (T)(img)(_n1##x,_n2##y,z,c)), \ (I[68] = (T)(img)(_n1##x,_n3##y,z,c)), \ (I[77] = (T)(img)(_n1##x,_n4##y,z,c)), \ (I[6] = (T)(img)(_n2##x,_p4##y,z,c)), \ (I[15] = (T)(img)(_n2##x,_p3##y,z,c)), \ (I[24] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[33] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[42] = (T)(img)(_n2##x,y,z,c)), \ (I[51] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[60] = (T)(img)(_n2##x,_n2##y,z,c)), \ (I[69] = (T)(img)(_n2##x,_n3##y,z,c)), \ (I[78] = (T)(img)(_n2##x,_n4##y,z,c)), \ (I[7] = (T)(img)(_n3##x,_p4##y,z,c)), \ (I[16] = (T)(img)(_n3##x,_p3##y,z,c)), \ (I[25] = (T)(img)(_n3##x,_p2##y,z,c)), \ (I[34] = (T)(img)(_n3##x,_p1##y,z,c)), \ (I[43] = (T)(img)(_n3##x,y,z,c)), \ (I[52] = (T)(img)(_n3##x,_n1##y,z,c)), \ (I[61] = (T)(img)(_n3##x,_n2##y,z,c)), \ (I[70] = (T)(img)(_n3##x,_n3##y,z,c)), \ (I[79] = (T)(img)(_n3##x,_n4##y,z,c)), \ 4>=((img)._width)?(img).width() - 1:4); \ (_n4##x<(img).width() && ( \ (I[8] = (T)(img)(_n4##x,_p4##y,z,c)), \ (I[17] = (T)(img)(_n4##x,_p3##y,z,c)), \ (I[26] = (T)(img)(_n4##x,_p2##y,z,c)), \ (I[35] = (T)(img)(_n4##x,_p1##y,z,c)), \ (I[44] = (T)(img)(_n4##x,y,z,c)), \ (I[53] = (T)(img)(_n4##x,_n1##y,z,c)), \ (I[62] = (T)(img)(_n4##x,_n2##y,z,c)), \ (I[71] = (T)(img)(_n4##x,_n3##y,z,c)), \ (I[80] = (T)(img)(_n4##x,_n4##y,z,c)),1)) || \ _n3##x==--_n4##x || _n2##x==--_n3##x || _n1##x==--_n2##x || x==(_n4##x = _n3##x = _n2##x = --_n1##x); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], I[4] = I[5], I[5] = I[6], I[6] = I[7], I[7] = I[8], \ I[9] = I[10], I[10] = I[11], I[11] = I[12], I[12] = I[13], I[13] = I[14], I[14] = I[15], I[15] = I[16], \ I[16] = I[17], I[18] = I[19], I[19] = I[20], I[20] = I[21], I[21] = I[22], I[22] = I[23], I[23] = I[24], \ I[24] = I[25], I[25] = I[26], I[27] = I[28], I[28] = I[29], I[29] = I[30], I[30] = I[31], I[31] = I[32], \ I[32] = I[33], I[33] = I[34], I[34] = I[35], I[36] = I[37], I[37] = I[38], I[38] = I[39], I[39] = I[40], \ I[40] = I[41], I[41] = I[42], I[42] = I[43], I[43] = I[44], I[45] = I[46], I[46] = I[47], I[47] = I[48], \ I[48] = I[49], I[49] = I[50], I[50] = I[51], I[51] = I[52], I[52] = I[53], I[54] = I[55], I[55] = I[56], \ I[56] = I[57], I[57] = I[58], I[58] = I[59], I[59] = I[60], I[60] = I[61], I[61] = I[62], I[63] = I[64], \ I[64] = I[65], I[65] = I[66], I[66] = I[67], I[67] = I[68], I[68] = I[69], I[69] = I[70], I[70] = I[71], \ I[72] = I[73], I[73] = I[74], I[74] = I[75], I[75] = I[76], I[76] = I[77], I[77] = I[78], I[78] = I[79], \ I[79] = I[80], \ _p4##x = _p3##x, _p3##x = _p2##x, _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x, ++_n3##x, ++_n4##x) #define cimg_for_in9x9(img,x0,y0,x1,y1,x,y,z,c,I,T) \ cimg_for_in9((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)(x0), \ _p4##x = x - 4<0?0:x - 4, \ _p3##x = x - 3<0?0:x - 3, \ _p2##x = x - 2<0?0:x - 2, \ _p1##x = x - 1<0?0:x - 1, \ _n1##x = x + 1>=(img).width()?(img).width() - 1:x + 1, \ _n2##x = x + 2>=(img).width()?(img).width() - 1:x + 2, \ _n3##x = x + 3>=(img).width()?(img).width() - 1:x + 3, \ _n4##x = (int)( \ (I[0] = (T)(img)(_p4##x,_p4##y,z,c)), \ (I[9] = (T)(img)(_p4##x,_p3##y,z,c)), \ (I[18] = (T)(img)(_p4##x,_p2##y,z,c)), \ (I[27] = (T)(img)(_p4##x,_p1##y,z,c)), \ (I[36] = (T)(img)(_p4##x,y,z,c)), \ (I[45] = (T)(img)(_p4##x,_n1##y,z,c)), \ (I[54] = (T)(img)(_p4##x,_n2##y,z,c)), \ (I[63] = (T)(img)(_p4##x,_n3##y,z,c)), \ (I[72] = (T)(img)(_p4##x,_n4##y,z,c)), \ (I[1] = (T)(img)(_p3##x,_p4##y,z,c)), \ (I[10] = (T)(img)(_p3##x,_p3##y,z,c)), \ (I[19] = (T)(img)(_p3##x,_p2##y,z,c)), \ (I[28] = (T)(img)(_p3##x,_p1##y,z,c)), \ (I[37] = (T)(img)(_p3##x,y,z,c)), \ (I[46] = (T)(img)(_p3##x,_n1##y,z,c)), \ (I[55] = (T)(img)(_p3##x,_n2##y,z,c)), \ (I[64] = (T)(img)(_p3##x,_n3##y,z,c)), \ (I[73] = (T)(img)(_p3##x,_n4##y,z,c)), \ (I[2] = (T)(img)(_p2##x,_p4##y,z,c)), \ (I[11] = (T)(img)(_p2##x,_p3##y,z,c)), \ (I[20] = (T)(img)(_p2##x,_p2##y,z,c)), \ (I[29] = (T)(img)(_p2##x,_p1##y,z,c)), \ (I[38] = (T)(img)(_p2##x,y,z,c)), \ (I[47] = (T)(img)(_p2##x,_n1##y,z,c)), \ (I[56] = (T)(img)(_p2##x,_n2##y,z,c)), \ (I[65] = (T)(img)(_p2##x,_n3##y,z,c)), \ (I[74] = (T)(img)(_p2##x,_n4##y,z,c)), \ (I[3] = (T)(img)(_p1##x,_p4##y,z,c)), \ (I[12] = (T)(img)(_p1##x,_p3##y,z,c)), \ (I[21] = (T)(img)(_p1##x,_p2##y,z,c)), \ (I[30] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[39] = (T)(img)(_p1##x,y,z,c)), \ (I[48] = (T)(img)(_p1##x,_n1##y,z,c)), \ (I[57] = (T)(img)(_p1##x,_n2##y,z,c)), \ (I[66] = (T)(img)(_p1##x,_n3##y,z,c)), \ (I[75] = (T)(img)(_p1##x,_n4##y,z,c)), \ (I[4] = (T)(img)(x,_p4##y,z,c)), \ (I[13] = (T)(img)(x,_p3##y,z,c)), \ (I[22] = (T)(img)(x,_p2##y,z,c)), \ (I[31] = (T)(img)(x,_p1##y,z,c)), \ (I[40] = (T)(img)(x,y,z,c)), \ (I[49] = (T)(img)(x,_n1##y,z,c)), \ (I[58] = (T)(img)(x,_n2##y,z,c)), \ (I[67] = (T)(img)(x,_n3##y,z,c)), \ (I[76] = (T)(img)(x,_n4##y,z,c)), \ (I[5] = (T)(img)(_n1##x,_p4##y,z,c)), \ (I[14] = (T)(img)(_n1##x,_p3##y,z,c)), \ (I[23] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[32] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[41] = (T)(img)(_n1##x,y,z,c)), \ (I[50] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[59] = (T)(img)(_n1##x,_n2##y,z,c)), \ (I[68] = (T)(img)(_n1##x,_n3##y,z,c)), \ (I[77] = (T)(img)(_n1##x,_n4##y,z,c)), \ (I[6] = (T)(img)(_n2##x,_p4##y,z,c)), \ (I[15] = (T)(img)(_n2##x,_p3##y,z,c)), \ (I[24] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[33] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[42] = (T)(img)(_n2##x,y,z,c)), \ (I[51] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[60] = (T)(img)(_n2##x,_n2##y,z,c)), \ (I[69] = (T)(img)(_n2##x,_n3##y,z,c)), \ (I[78] = (T)(img)(_n2##x,_n4##y,z,c)), \ (I[7] = (T)(img)(_n3##x,_p4##y,z,c)), \ (I[16] = (T)(img)(_n3##x,_p3##y,z,c)), \ (I[25] = (T)(img)(_n3##x,_p2##y,z,c)), \ (I[34] = (T)(img)(_n3##x,_p1##y,z,c)), \ (I[43] = (T)(img)(_n3##x,y,z,c)), \ (I[52] = (T)(img)(_n3##x,_n1##y,z,c)), \ (I[61] = (T)(img)(_n3##x,_n2##y,z,c)), \ (I[70] = (T)(img)(_n3##x,_n3##y,z,c)), \ (I[79] = (T)(img)(_n3##x,_n4##y,z,c)), \ x + 4>=(img).width()?(img).width() - 1:x + 4); \ x<=(int)(x1) && ((_n4##x<(img).width() && ( \ (I[8] = (T)(img)(_n4##x,_p4##y,z,c)), \ (I[17] = (T)(img)(_n4##x,_p3##y,z,c)), \ (I[26] = (T)(img)(_n4##x,_p2##y,z,c)), \ (I[35] = (T)(img)(_n4##x,_p1##y,z,c)), \ (I[44] = (T)(img)(_n4##x,y,z,c)), \ (I[53] = (T)(img)(_n4##x,_n1##y,z,c)), \ (I[62] = (T)(img)(_n4##x,_n2##y,z,c)), \ (I[71] = (T)(img)(_n4##x,_n3##y,z,c)), \ (I[80] = (T)(img)(_n4##x,_n4##y,z,c)),1)) || \ _n3##x==--_n4##x || _n2##x==--_n3##x || _n1##x==--_n2##x || x==(_n4##x = _n3##x = _n2##x = --_n1##x)); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], I[4] = I[5], I[5] = I[6], I[6] = I[7], I[7] = I[8], \ I[9] = I[10], I[10] = I[11], I[11] = I[12], I[12] = I[13], I[13] = I[14], I[14] = I[15], I[15] = I[16], \ I[16] = I[17], I[18] = I[19], I[19] = I[20], I[20] = I[21], I[21] = I[22], I[22] = I[23], I[23] = I[24], \ I[24] = I[25], I[25] = I[26], I[27] = I[28], I[28] = I[29], I[29] = I[30], I[30] = I[31], I[31] = I[32], \ I[32] = I[33], I[33] = I[34], I[34] = I[35], I[36] = I[37], I[37] = I[38], I[38] = I[39], I[39] = I[40], \ I[40] = I[41], I[41] = I[42], I[42] = I[43], I[43] = I[44], I[45] = I[46], I[46] = I[47], I[47] = I[48], \ I[48] = I[49], I[49] = I[50], I[50] = I[51], I[51] = I[52], I[52] = I[53], I[54] = I[55], I[55] = I[56], \ I[56] = I[57], I[57] = I[58], I[58] = I[59], I[59] = I[60], I[60] = I[61], I[61] = I[62], I[63] = I[64], \ I[64] = I[65], I[65] = I[66], I[66] = I[67], I[67] = I[68], I[68] = I[69], I[69] = I[70], I[70] = I[71], \ I[72] = I[73], I[73] = I[74], I[74] = I[75], I[75] = I[76], I[76] = I[77], I[77] = I[78], I[78] = I[79], \ I[79] = I[80], \ _p4##x = _p3##x, _p3##x = _p2##x, _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x, ++_n3##x, ++_n4##x) #define cimg_for2x2x2(img,x,y,z,c,I,T) \ cimg_for2((img)._depth,z) cimg_for2((img)._height,y) for (int x = 0, \ _n1##x = (int)( \ (I[0] = (T)(img)(0,y,z,c)), \ (I[2] = (T)(img)(0,_n1##y,z,c)), \ (I[4] = (T)(img)(0,y,_n1##z,c)), \ (I[6] = (T)(img)(0,_n1##y,_n1##z,c)), \ 1>=(img)._width?(img).width() - 1:1); \ (_n1##x<(img).width() && ( \ (I[1] = (T)(img)(_n1##x,y,z,c)), \ (I[3] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[5] = (T)(img)(_n1##x,y,_n1##z,c)), \ (I[7] = (T)(img)(_n1##x,_n1##y,_n1##z,c)),1)) || \ x==--_n1##x; \ I[0] = I[1], I[2] = I[3], I[4] = I[5], I[6] = I[7], \ ++x, ++_n1##x) #define cimg_for_in2x2x2(img,x0,y0,z0,x1,y1,z1,x,y,z,c,I,T) \ cimg_for_in2((img)._depth,z0,z1,z) cimg_for_in2((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)(x0), \ _n1##x = (int)( \ (I[0] = (T)(img)(x,y,z,c)), \ (I[2] = (T)(img)(x,_n1##y,z,c)), \ (I[4] = (T)(img)(x,y,_n1##z,c)), \ (I[6] = (T)(img)(x,_n1##y,_n1##z,c)), \ x + 1>=(int)(img)._width?(img).width() - 1:x + 1); \ x<=(int)(x1) && ((_n1##x<(img).width() && ( \ (I[1] = (T)(img)(_n1##x,y,z,c)), \ (I[3] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[5] = (T)(img)(_n1##x,y,_n1##z,c)), \ (I[7] = (T)(img)(_n1##x,_n1##y,_n1##z,c)),1)) || \ x==--_n1##x); \ I[0] = I[1], I[2] = I[3], I[4] = I[5], I[6] = I[7], \ ++x, ++_n1##x) #define cimg_for3x3x3(img,x,y,z,c,I,T) \ cimg_for3((img)._depth,z) cimg_for3((img)._height,y) for (int x = 0, \ _p1##x = 0, \ _n1##x = (int)( \ (I[0] = I[1] = (T)(img)(_p1##x,_p1##y,_p1##z,c)), \ (I[3] = I[4] = (T)(img)(0,y,_p1##z,c)), \ (I[6] = I[7] = (T)(img)(0,_n1##y,_p1##z,c)), \ (I[9] = I[10] = (T)(img)(0,_p1##y,z,c)), \ (I[12] = I[13] = (T)(img)(0,y,z,c)), \ (I[15] = I[16] = (T)(img)(0,_n1##y,z,c)), \ (I[18] = I[19] = (T)(img)(0,_p1##y,_n1##z,c)), \ (I[21] = I[22] = (T)(img)(0,y,_n1##z,c)), \ (I[24] = I[25] = (T)(img)(0,_n1##y,_n1##z,c)), \ 1>=(img)._width?(img).width() - 1:1); \ (_n1##x<(img).width() && ( \ (I[2] = (T)(img)(_n1##x,_p1##y,_p1##z,c)), \ (I[5] = (T)(img)(_n1##x,y,_p1##z,c)), \ (I[8] = (T)(img)(_n1##x,_n1##y,_p1##z,c)), \ (I[11] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[14] = (T)(img)(_n1##x,y,z,c)), \ (I[17] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[20] = (T)(img)(_n1##x,_p1##y,_n1##z,c)), \ (I[23] = (T)(img)(_n1##x,y,_n1##z,c)), \ (I[26] = (T)(img)(_n1##x,_n1##y,_n1##z,c)),1)) || \ x==--_n1##x; \ I[0] = I[1], I[1] = I[2], I[3] = I[4], I[4] = I[5], I[6] = I[7], I[7] = I[8], \ I[9] = I[10], I[10] = I[11], I[12] = I[13], I[13] = I[14], I[15] = I[16], I[16] = I[17], \ I[18] = I[19], I[19] = I[20], I[21] = I[22], I[22] = I[23], I[24] = I[25], I[25] = I[26], \ _p1##x = x++, ++_n1##x) #define cimg_for_in3x3x3(img,x0,y0,z0,x1,y1,z1,x,y,z,c,I,T) \ cimg_for_in3((img)._depth,z0,z1,z) cimg_for_in3((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)(x0), \ _p1##x = x - 1<0?0:x - 1, \ _n1##x = (int)( \ (I[0] = (T)(img)(_p1##x,_p1##y,_p1##z,c)), \ (I[3] = (T)(img)(_p1##x,y,_p1##z,c)), \ (I[6] = (T)(img)(_p1##x,_n1##y,_p1##z,c)), \ (I[9] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[12] = (T)(img)(_p1##x,y,z,c)), \ (I[15] = (T)(img)(_p1##x,_n1##y,z,c)), \ (I[18] = (T)(img)(_p1##x,_p1##y,_n1##z,c)), \ (I[21] = (T)(img)(_p1##x,y,_n1##z,c)), \ (I[24] = (T)(img)(_p1##x,_n1##y,_n1##z,c)), \ (I[1] = (T)(img)(x,_p1##y,_p1##z,c)), \ (I[4] = (T)(img)(x,y,_p1##z,c)), \ (I[7] = (T)(img)(x,_n1##y,_p1##z,c)), \ (I[10] = (T)(img)(x,_p1##y,z,c)), \ (I[13] = (T)(img)(x,y,z,c)), \ (I[16] = (T)(img)(x,_n1##y,z,c)), \ (I[19] = (T)(img)(x,_p1##y,_n1##z,c)), \ (I[22] = (T)(img)(x,y,_n1##z,c)), \ (I[25] = (T)(img)(x,_n1##y,_n1##z,c)), \ x + 1>=(int)(img)._width?(img).width() - 1:x + 1); \ x<=(int)(x1) && ((_n1##x<(img).width() && ( \ (I[2] = (T)(img)(_n1##x,_p1##y,_p1##z,c)), \ (I[5] = (T)(img)(_n1##x,y,_p1##z,c)), \ (I[8] = (T)(img)(_n1##x,_n1##y,_p1##z,c)), \ (I[11] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[14] = (T)(img)(_n1##x,y,z,c)), \ (I[17] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[20] = (T)(img)(_n1##x,_p1##y,_n1##z,c)), \ (I[23] = (T)(img)(_n1##x,y,_n1##z,c)), \ (I[26] = (T)(img)(_n1##x,_n1##y,_n1##z,c)),1)) || \ x==--_n1##x); \ I[0] = I[1], I[1] = I[2], I[3] = I[4], I[4] = I[5], I[6] = I[7], I[7] = I[8], \ I[9] = I[10], I[10] = I[11], I[12] = I[13], I[13] = I[14], I[15] = I[16], I[16] = I[17], \ I[18] = I[19], I[19] = I[20], I[21] = I[22], I[22] = I[23], I[24] = I[25], I[25] = I[26], \ _p1##x = x++, ++_n1##x) #define cimglist_for(list,l) for (int l = 0; l<(int)(list)._width; ++l) #define cimglist_for_in(list,l0,l1,l) \ for (int l = (int)(l0)<0?0:(int)(l0), _max##l = (unsigned int)l1<(list)._width?(int)(l1):(int)(list)._width - 1; \ l<=_max##l; ++l) #define cimglist_apply(list,fn) cimglist_for(list,__##fn) (list)[__##fn].fn // Macros used to display error messages when exceptions are thrown. // You should not use these macros is your own code. #define _cimgdisplay_instance "[instance(%u,%u,%u,%c%s%c)] CImgDisplay::" #define cimgdisplay_instance _width,_height,_normalization,_title?'\"':'[',_title?_title:"untitled",_title?'\"':']' #define _cimg_instance "[instance(%u,%u,%u,%u,%p,%sshared)] CImg<%s>::" #define cimg_instance _width,_height,_depth,_spectrum,_data,_is_shared?"":"non-",pixel_type() #define _cimglist_instance "[instance(%u,%u,%p)] CImgList<%s>::" #define cimglist_instance _width,_allocated_width,_data,pixel_type() /*------------------------------------------------ # # # Define cimg_library:: namespace # # -------------------------------------------------*/ //! Contains <i>all classes and functions</i> of the \CImg library. /** This namespace is defined to avoid functions and class names collisions that could happen with the inclusion of other C++ header files. Anyway, it should not happen often and you should reasonnably start most of your \CImg-based programs with \code #include "CImg.h" using namespace cimg_library; \endcode to simplify the declaration of \CImg Library objects afterwards. **/ namespace cimg_library_suffixed { // Declare the four classes of the CImg Library. template<typename T=float> struct CImg; template<typename T=float> struct CImgList; struct CImgDisplay; struct CImgException; // Declare cimg:: namespace. // This is an uncomplete namespace definition here. It only contains some // necessary stuff to ensure a correct declaration order of the classes and functions // defined afterwards. namespace cimg { // Define Ascii sequences for colored terminal output. #ifdef cimg_use_vt100 static const char t_normal[] = { 0x1b, '[', '0', ';', '0', ';', '0', 'm', 0 }; static const char t_black[] = { 0x1b, '[', '0', ';', '3', '0', ';', '5', '9', 'm', 0 }; static const char t_red[] = { 0x1b, '[', '0', ';', '3', '1', ';', '5', '9', 'm', 0 }; static const char t_green[] = { 0x1b, '[', '0', ';', '3', '2', ';', '5', '9', 'm', 0 }; static const char t_yellow[] = { 0x1b, '[', '0', ';', '3', '3', ';', '5', '9', 'm', 0 }; static const char t_blue[] = { 0x1b, '[', '0', ';', '3', '4', ';', '5', '9', 'm', 0 }; static const char t_magenta[] = { 0x1b, '[', '0', ';', '3', '5', ';', '5', '9', 'm', 0 }; static const char t_cyan[] = { 0x1b, '[', '0', ';', '3', '6', ';', '5', '9', 'm', 0 }; static const char t_white[] = { 0x1b, '[', '0', ';', '3', '7', ';', '5', '9', 'm', 0 }; static const char t_bold[] = { 0x1b, '[', '1', 'm', 0 }; static const char t_underscore[] = { 0x1b, '[', '4', 'm', 0 }; #else static const char t_normal[] = { 0 }; static const char *const t_black = cimg::t_normal, *const t_red = cimg::t_normal, *const t_green = cimg::t_normal, *const t_yellow = cimg::t_normal, *const t_blue = cimg::t_normal, *const t_magenta = cimg::t_normal, *const t_cyan = cimg::t_normal, *const t_white = cimg::t_normal, *const t_bold = cimg::t_normal, *const t_underscore = cimg::t_normal; #endif inline std::FILE* output(std::FILE *file=0); inline void info(); //! Avoid warning messages due to unused parameters. Do nothing actually. template<typename T> inline void unused(const T&, ...) {} // [internal] Lock/unlock a mutex for managing concurrent threads. // 'lock_mode' can be { 0=unlock | 1=lock | 2=trylock }. // 'n' can be in [0,31] but mutex range [0,15] is reserved by CImg. inline int mutex(const unsigned int n, const int lock_mode=1); inline unsigned int& exception_mode(const unsigned int value, const bool is_set) { static unsigned int mode = cimg_verbosity; if (is_set) { cimg::mutex(0); mode = value<4?value:4; cimg::mutex(0,0); } return mode; } // Functions to return standard streams 'stdin', 'stdout' and 'stderr'. inline FILE* _stdin(const bool throw_exception=true); inline FILE* _stdout(const bool throw_exception=true); inline FILE* _stderr(const bool throw_exception=true); // Mandatory because Microsoft's _snprintf() and _vsnprintf() do not add the '\0' character // at the end of the string. #if cimg_OS==2 && defined(_MSC_VER) inline int _snprintf(char *const s, const size_t size, const char *const format, ...) { va_list ap; va_start(ap,format); const int result = _vsnprintf(s,size,format,ap); va_end(ap); return result; } inline int _vsnprintf(char *const s, const size_t size, const char *const format, va_list ap) { int result = -1; cimg::mutex(6); if (size) result = _vsnprintf_s(s,size,_TRUNCATE,format,ap); if (result==-1) result = _vscprintf(format,ap); cimg::mutex(6,0); return result; } // Mutex-protected version of sscanf, sprintf and snprintf. // Used only MacOSX, as it seems those functions are not re-entrant on MacOSX. #elif defined(__MACOSX__) || defined(__APPLE__) inline int _sscanf(const char *const s, const char *const format, ...) { cimg::mutex(6); va_list args; va_start(args,format); const int result = std::vsscanf(s,format,args); va_end(args); cimg::mutex(6,0); return result; } inline int _sprintf(char *const s, const char *const format, ...) { cimg::mutex(6); va_list args; va_start(args,format); const int result = std::vsprintf(s,format,args); va_end(args); cimg::mutex(6,0); return result; } inline int _snprintf(char *const s, const size_t n, const char *const format, ...) { cimg::mutex(6); va_list args; va_start(args,format); const int result = std::vsnprintf(s,n,format,args); va_end(args); cimg::mutex(6,0); return result; } inline int _vsnprintf(char *const s, const size_t size, const char* format, va_list ap) { cimg::mutex(6); const int result = std::vsnprintf(s,size,format,ap); cimg::mutex(6,0); return result; } #endif //! Set current \CImg exception mode. /** The way error messages are handled by \CImg can be changed dynamically, using this function. \param mode Desired exception mode. Possible values are: - \c 0: Hide library messages (quiet mode). - \c 1: Print library messages on the console. - \c 2: Display library messages on a dialog window. - \c 3: Do as \c 1 + add extra debug warnings (slow down the code!). - \c 4: Do as \c 2 + add extra debug warnings (slow down the code!). **/ inline unsigned int& exception_mode(const unsigned int mode) { return exception_mode(mode,true); } //! Return current \CImg exception mode. /** \note By default, return the value of configuration macro \c cimg_verbosity **/ inline unsigned int& exception_mode() { return exception_mode(0,false); } inline unsigned int openmp_mode(const unsigned int value, const bool is_set) { static unsigned int mode = 2; if (is_set) { cimg::mutex(0); mode = value<2?value:2; cimg::mutex(0,0); } return mode; } //! Set current \CImg openmp mode. /** The way openmp-based methods are handled by \CImg can be changed dynamically, using this function. \param mode Desired openmp mode. Possible values are: - \c 0: Never parallelize. - \c 1: Always parallelize. - \c 2: Adaptive parallelization mode (default behavior). **/ inline unsigned int openmp_mode(const unsigned int mode) { return openmp_mode(mode,true); } //! Return current \CImg openmp mode. inline unsigned int openmp_mode() { return openmp_mode(0,false); } #ifndef cimg_openmp_sizefactor #define cimg_openmp_sizefactor 1 #endif #define cimg_openmp_if(cond) if ((cimg::openmp_mode()==1 || (cimg::openmp_mode()>1 && (cond)))) #define cimg_openmp_if_size(size,min_size) cimg_openmp_if((size)>=(cimg_openmp_sizefactor)*(min_size)) #ifdef _MSC_VER // Disable 'collapse()' directive for MSVC (supports only OpenMP 2.0). #define cimg_openmp_collapse(k) #else #define cimg_openmp_collapse(k) collapse(k) #endif #if cimg_OS==2 // Disable parallelization of simple loops on Windows, due to noticed performance drop. #define cimg_openmp_for(instance,expr,min_size) cimg_rof((instance),ptr,T) *ptr = (T)(expr); #else #define cimg_openmp_for(instance,expr,min_size) \ cimg_pragma_openmp(parallel for cimg_openmp_if_size((instance).size(),min_size)) \ cimg_rof((instance),ptr,T) *ptr = (T)(expr); #endif // Display a simple dialog box, and wait for the user's response. inline int dialog(const char *const title, const char *const msg, const char *const button1_label="OK", const char *const button2_label=0, const char *const button3_label=0, const char *const button4_label=0, const char *const button5_label=0, const char *const button6_label=0, const bool centering=false); // Evaluate math expression. inline double eval(const char *const expression, const double x=0, const double y=0, const double z=0, const double c=0); } // namespace cimg { ... /*--------------------------------------- # # Define the CImgException structures # --------------------------------------*/ //! Instances of \c CImgException are thrown when errors are encountered in a \CImg function call. /** \par Overview CImgException is the base class of all exceptions thrown by \CImg (except \b CImgAbortException). CImgException is never thrown itself. Derived classes that specify the type of errord are thrown instead. These classes can be: - \b CImgAbortException: Thrown when a computationally-intensive function is aborted by an external signal. This is the only \c non-derived exception class. - \b CImgArgumentException: Thrown when one argument of a called \CImg function is invalid. This is probably one of the most thrown exception by \CImg. For instance, the following example throws a \c CImgArgumentException: \code CImg<float> img(100,100,1,3); // Define a 100x100 color image with float-valued pixels img.mirror('e'); // Try to mirror image along the (non-existing) 'e'-axis \endcode - \b CImgDisplayException: Thrown when something went wrong during the display of images in CImgDisplay instances. - \b CImgInstanceException: Thrown when an instance associated to a called \CImg method does not fit the function requirements. For instance, the following example throws a \c CImgInstanceException: \code const CImg<float> img; // Define an empty image const float value = img.at(0); // Try to read first pixel value (does not exist) \endcode - \b CImgIOException: Thrown when an error occured when trying to load or save image files. This happens when trying to read files that do not exist or with invalid formats. For instance, the following example throws a \c CImgIOException: \code const CImg<float> img("missing_file.jpg"); // Try to load a file that does not exist \endcode - \b CImgWarningException: Thrown only if configuration macro \c cimg_strict_warnings is set, and when a \CImg function has to display a warning message (see cimg::warn()). It is not recommended to throw CImgException instances by yourself, since they are expected to be thrown only by \CImg. When an error occurs in a library function call, \CImg may display error messages on the screen or on the standard output, depending on the current \CImg exception mode. The \CImg exception mode can be get and set by functions cimg::exception_mode() and cimg::exception_mode(unsigned int). \par Exceptions handling In all cases, when an error occurs in \CImg, an instance of the corresponding exception class is thrown. This may lead the program to break (this is the default behavior), but you can bypass this behavior by handling the exceptions by yourself, using a usual <tt>try { ... } catch () { ... }</tt> bloc, as in the following example: \code #define "CImg.h" using namespace cimg_library; int main() { cimg::exception_mode(0); // Enable quiet exception mode try { ... // Here, do what you want to stress CImg } catch (CImgException& e) { // You succeeded: something went wrong! std::fprintf(stderr,"CImg Library Error: %s",e.what()); // Display your custom error message ... // Do what you want now to save the ship! } } \endcode **/ struct CImgException : public std::exception { #define _cimg_exception_err(etype,disp_flag) \ std::va_list ap, ap2; \ va_start(ap,format); va_start(ap2,format); \ int size = cimg_vsnprintf(0,0,format,ap2); \ if (size++>=0) { \ delete[] _message; \ _message = new char[size]; \ cimg_vsnprintf(_message,size,format,ap); \ if (cimg::exception_mode()) { \ std::fprintf(cimg::output(),"\n%s[CImg] *** %s ***%s %s\n",cimg::t_red,etype,cimg::t_normal,_message); \ if (cimg_display && disp_flag && !(cimg::exception_mode()%2)) try { cimg::dialog(etype,_message,"Abort"); } \ catch (CImgException&) {} \ if (cimg::exception_mode()>=3) cimg_library_suffixed::cimg::info(); \ } \ } \ va_end(ap); va_end(ap2); \ char *_message; CImgException() { _message = new char[1]; *_message = 0; } CImgException(const char *const format, ...):_message(0) { _cimg_exception_err("CImgException",true); } CImgException(const CImgException& e):std::exception(e) { const size_t size = std::strlen(e._message); _message = new char[size + 1]; std::strncpy(_message,e._message,size); _message[size] = 0; } ~CImgException() throw() { delete[] _message; } CImgException& operator=(const CImgException& e) { const size_t size = std::strlen(e._message); _message = new char[size + 1]; std::strncpy(_message,e._message,size); _message[size] = 0; return *this; } //! Return a C-string containing the error message associated to the thrown exception. const char *what() const throw() { return _message; } }; // struct CImgException { ... // The CImgAbortException class is used to throw an exception when // a computationally-intensive function has been aborted by an external signal. struct CImgAbortException : public std::exception { char *_message; CImgAbortException() { _message = new char[1]; *_message = 0; } CImgAbortException(const char *const format, ...):_message(0) { _cimg_exception_err("CImgAbortException",true); } CImgAbortException(const CImgAbortException& e):std::exception(e) { const size_t size = std::strlen(e._message); _message = new char[size + 1]; std::strncpy(_message,e._message,size); _message[size] = 0; } ~CImgAbortException() throw() { delete[] _message; } CImgAbortException& operator=(const CImgAbortException& e) { const size_t size = std::strlen(e._message); _message = new char[size + 1]; std::strncpy(_message,e._message,size); _message[size] = 0; return *this; } //! Return a C-string containing the error message associated to the thrown exception. const char *what() const throw() { return _message; } }; // struct CImgAbortException { ... // The CImgArgumentException class is used to throw an exception related // to invalid arguments encountered in a library function call. struct CImgArgumentException : public CImgException { CImgArgumentException(const char *const format, ...) { _cimg_exception_err("CImgArgumentException",true); } }; // struct CImgArgumentException { ... // The CImgDisplayException class is used to throw an exception related // to display problems encountered in a library function call. struct CImgDisplayException : public CImgException { CImgDisplayException(const char *const format, ...) { _cimg_exception_err("CImgDisplayException",false); } }; // struct CImgDisplayException { ... // The CImgInstanceException class is used to throw an exception related // to an invalid instance encountered in a library function call. struct CImgInstanceException : public CImgException { CImgInstanceException(const char *const format, ...) { _cimg_exception_err("CImgInstanceException",true); } }; // struct CImgInstanceException { ... // The CImgIOException class is used to throw an exception related // to input/output file problems encountered in a library function call. struct CImgIOException : public CImgException { CImgIOException(const char *const format, ...) { _cimg_exception_err("CImgIOException",true); } }; // struct CImgIOException { ... // The CImgWarningException class is used to throw an exception for warnings // encountered in a library function call. struct CImgWarningException : public CImgException { CImgWarningException(const char *const format, ...) { _cimg_exception_err("CImgWarningException",false); } }; // struct CImgWarningException { ... /*------------------------------------- # # Define cimg:: namespace # -----------------------------------*/ //! Contains \a low-level functions and variables of the \CImg Library. /** Most of the functions and variables within this namespace are used by the \CImg library for low-level operations. You may use them to access specific const values or environment variables internally used by \CImg. \warning Never write <tt>using namespace cimg_library::cimg;</tt> in your source code. Lot of functions in the <tt>cimg:: namespace</tt> have the same names as standard C functions that may be defined in the global namespace <tt>::</tt>. **/ namespace cimg { // Define traits that will be used to determine the best data type to work in CImg functions. // template<typename T> struct type { static const char* string() { static const char* s[] = { "unknown", "unknown8", "unknown16", "unknown24", "unknown32", "unknown40", "unknown48", "unknown56", "unknown64", "unknown72", "unknown80", "unknown88", "unknown96", "unknown104", "unknown112", "unknown120", "unknown128" }; return s[(sizeof(T)<17)?sizeof(T):0]; } static bool is_float() { return false; } static bool is_inf(const T) { return false; } static bool is_nan(const T) { return false; } static T min() { return ~max(); } static T max() { return (T)1<<(8*sizeof(T) - 1); } static T inf() { return max(); } static T cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(T)val; } static const char* format() { return "%s"; } static const char* format_s() { return "%s"; } static const char* format(const T& val) { static const char *const s = "unknown"; cimg::unused(val); return s; } }; template<> struct type<bool> { static const char* string() { static const char *const s = "bool"; return s; } static bool is_float() { return false; } static bool is_inf(const bool) { return false; } static bool is_nan(const bool) { return false; } static bool min() { return false; } static bool max() { return true; } static bool inf() { return max(); } static bool is_inf() { return false; } static bool cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(bool)val; } static const char* format() { return "%s"; } static const char* format_s() { return "%s"; } static const char* format(const bool val) { static const char* s[] = { "false", "true" }; return s[val?1:0]; } }; template<> struct type<unsigned char> { static const char* string() { static const char *const s = "unsigned char"; return s; } static bool is_float() { return false; } static bool is_inf(const unsigned char) { return false; } static bool is_nan(const unsigned char) { return false; } static unsigned char min() { return 0; } static unsigned char max() { return (unsigned char)-1; } static unsigned char inf() { return max(); } static unsigned char cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(unsigned char)val; } static const char* format() { return "%u"; } static const char* format_s() { return "%u"; } static unsigned int format(const unsigned char val) { return (unsigned int)val; } }; #if defined(CHAR_MAX) && CHAR_MAX==255 template<> struct type<char> { static const char* string() { static const char *const s = "char"; return s; } static bool is_float() { return false; } static bool is_inf(const char) { return false; } static bool is_nan(const char) { return false; } static char min() { return 0; } static char max() { return (char)-1; } static char inf() { return max(); } static char cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(unsigned char)val; } static const char* format() { return "%u"; } static const char* format_s() { return "%u"; } static unsigned int format(const char val) { return (unsigned int)val; } }; #else template<> struct type<char> { static const char* string() { static const char *const s = "char"; return s; } static bool is_float() { return false; } static bool is_inf(const char) { return false; } static bool is_nan(const char) { return false; } static char min() { return ~max(); } static char max() { return (char)((unsigned char)-1>>1); } static char inf() { return max(); } static char cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(char)val; } static const char* format() { return "%d"; } static const char* format_s() { return "%d"; } static int format(const char val) { return (int)val; } }; #endif template<> struct type<signed char> { static const char* string() { static const char *const s = "signed char"; return s; } static bool is_float() { return false; } static bool is_inf(const signed char) { return false; } static bool is_nan(const signed char) { return false; } static signed char min() { return ~max(); } static signed char max() { return (signed char)((unsigned char)-1>>1); } static signed char inf() { return max(); } static signed char cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(signed char)val; } static const char* format() { return "%d"; } static const char* format_s() { return "%d"; } static int format(const signed char val) { return (int)val; } }; template<> struct type<unsigned short> { static const char* string() { static const char *const s = "unsigned short"; return s; } static bool is_float() { return false; } static bool is_inf(const unsigned short) { return false; } static bool is_nan(const unsigned short) { return false; } static unsigned short min() { return 0; } static unsigned short max() { return (unsigned short)-1; } static unsigned short inf() { return max(); } static unsigned short cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(unsigned short)val; } static const char* format() { return "%u"; } static const char* format_s() { return "%u"; } static unsigned int format(const unsigned short val) { return (unsigned int)val; } }; template<> struct type<short> { static const char* string() { static const char *const s = "short"; return s; } static bool is_float() { return false; } static bool is_inf(const short) { return false; } static bool is_nan(const short) { return false; } static short min() { return ~max(); } static short max() { return (short)((unsigned short)-1>>1); } static short inf() { return max(); } static short cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(short)val; } static const char* format() { return "%d"; } static const char* format_s() { return "%d"; } static int format(const short val) { return (int)val; } }; template<> struct type<unsigned int> { static const char* string() { static const char *const s = "unsigned int"; return s; } static bool is_float() { return false; } static bool is_inf(const unsigned int) { return false; } static bool is_nan(const unsigned int) { return false; } static unsigned int min() { return 0; } static unsigned int max() { return (unsigned int)-1; } static unsigned int inf() { return max(); } static unsigned int cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(unsigned int)val; } static const char* format() { return "%u"; } static const char* format_s() { return "%u"; } static unsigned int format(const unsigned int val) { return val; } }; template<> struct type<int> { static const char* string() { static const char *const s = "int"; return s; } static bool is_float() { return false; } static bool is_inf(const int) { return false; } static bool is_nan(const int) { return false; } static int min() { return ~max(); } static int max() { return (int)((unsigned int)-1>>1); } static int inf() { return max(); } static int cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(int)val; } static const char* format() { return "%d"; } static const char* format_s() { return "%d"; } static int format(const int val) { return val; } }; template<> struct type<cimg_uint64> { static const char* string() { static const char *const s = "unsigned int64"; return s; } static bool is_float() { return false; } static bool is_inf(const cimg_uint64) { return false; } static bool is_nan(const cimg_uint64) { return false; } static cimg_uint64 min() { return 0; } static cimg_uint64 max() { return (cimg_uint64)-1; } static cimg_uint64 inf() { return max(); } static cimg_uint64 cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(cimg_uint64)val; } static const char* format() { return cimg_fuint64; } static const char* format_s() { return cimg_fuint64; } static unsigned long format(const cimg_uint64 val) { return (unsigned long)val; } }; template<> struct type<cimg_int64> { static const char* string() { static const char *const s = "int64"; return s; } static bool is_float() { return false; } static bool is_inf(const cimg_int64) { return false; } static bool is_nan(const cimg_int64) { return false; } static cimg_int64 min() { return ~max(); } static cimg_int64 max() { return (cimg_int64)((cimg_uint64)-1>>1); } static cimg_int64 inf() { return max(); } static cimg_int64 cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(cimg_int64)val; } static const char* format() { return cimg_fint64; } static const char* format_s() { return cimg_fint64; } static long format(const long val) { return (long)val; } }; template<> struct type<double> { static const char* string() { static const char *const s = "double"; return s; } static bool is_float() { return true; } static bool is_inf(const double val) { #ifdef isinf return (bool)isinf(val); #else return !is_nan(val) && (val<cimg::type<double>::min() || val>cimg::type<double>::max()); #endif } static bool is_nan(const double val) { // Custom version that works with '-ffast-math' if (sizeof(double)==8) { cimg_uint64 u; std::memcpy(&u,&val,sizeof(double)); return ((unsigned int)(u>>32)&0x7fffffff) + ((unsigned int)u!=0)>0x7ff00000; } #ifdef isnan return (bool)isnan(val); #else return !(val==val); #endif } static double min() { return -DBL_MAX; } static double max() { return DBL_MAX; } static double inf() { #ifdef INFINITY return (double)INFINITY; #else return max()*max(); #endif } static double nan() { #ifdef NAN return (double)NAN; #else const double val_nan = -std::sqrt(-1.); return val_nan; #endif } static double cut(const double val) { return val; } static const char* format() { return "%.17g"; } static const char* format_s() { return "%g"; } static double format(const double val) { return val; } }; template<> struct type<float> { static const char* string() { static const char *const s = "float"; return s; } static bool is_float() { return true; } static bool is_inf(const float val) { #ifdef isinf return (bool)isinf(val); #else return !is_nan(val) && (val<cimg::type<float>::min() || val>cimg::type<float>::max()); #endif } static bool is_nan(const float val) { // Custom version that works with '-ffast-math' if (sizeof(float)==4) { unsigned int u; std::memcpy(&u,&val,sizeof(float)); return (u&0x7fffffff)>0x7f800000; } #ifdef isnan return (bool)isnan(val); #else return !(val==val); #endif } static float min() { return -FLT_MAX; } static float max() { return FLT_MAX; } static float inf() { return (float)cimg::type<double>::inf(); } static float nan() { return (float)cimg::type<double>::nan(); } static float cut(const double val) { return (float)val; } static float cut(const float val) { return (float)val; } static const char* format() { return "%.9g"; } static const char* format_s() { return "%g"; } static double format(const float val) { return (double)val; } }; template<> struct type<long double> { static const char* string() { static const char *const s = "long double"; return s; } static bool is_float() { return true; } static bool is_inf(const long double val) { #ifdef isinf return (bool)isinf(val); #else return !is_nan(val) && (val<cimg::type<long double>::min() || val>cimg::type<long double>::max()); #endif } static bool is_nan(const long double val) { #ifdef isnan return (bool)isnan(val); #else return !(val==val); #endif } static long double min() { return -LDBL_MAX; } static long double max() { return LDBL_MAX; } static long double inf() { return max()*max(); } static long double nan() { const long double val_nan = -std::sqrt(-1.L); return val_nan; } static long double cut(const long double val) { return val; } static const char* format() { return "%.17g"; } static const char* format_s() { return "%g"; } static double format(const long double val) { return (double)val; } }; #ifdef cimg_use_half template<> struct type<half> { static const char* string() { static const char *const s = "half"; return s; } static bool is_float() { return true; } static bool is_inf(const long double val) { #ifdef isinf return (bool)isinf(val); #else return !is_nan(val) && (val<cimg::type<half>::min() || val>cimg::type<half>::max()); #endif } static bool is_nan(const half val) { // Custom version that works with '-ffast-math' if (sizeof(half)==2) { short u; std::memcpy(&u,&val,sizeof(short)); return (bool)((u&0x7fff)>0x7c00); } return cimg::type<float>::is_nan((float)val); } static half min() { return (half)-65504; } static half max() { return (half)65504; } static half inf() { return max()*max(); } static half nan() { const half val_nan = (half)-std::sqrt(-1.); return val_nan; } static half cut(const double val) { return (half)val; } static const char* format() { return "%.9g"; } static const char* format_s() { return "%g"; } static double format(const half val) { return (double)val; } }; #endif template<typename T, typename t> struct superset { typedef T type; }; template<> struct superset<bool,unsigned char> { typedef unsigned char type; }; template<> struct superset<bool,char> { typedef char type; }; template<> struct superset<bool,signed char> { typedef signed char type; }; template<> struct superset<bool,unsigned short> { typedef unsigned short type; }; template<> struct superset<bool,short> { typedef short type; }; template<> struct superset<bool,unsigned int> { typedef unsigned int type; }; template<> struct superset<bool,int> { typedef int type; }; template<> struct superset<bool,cimg_uint64> { typedef cimg_uint64 type; }; template<> struct superset<bool,cimg_int64> { typedef cimg_int64 type; }; template<> struct superset<bool,float> { typedef float type; }; template<> struct superset<bool,double> { typedef double type; }; template<> struct superset<unsigned char,char> { typedef short type; }; template<> struct superset<unsigned char,signed char> { typedef short type; }; template<> struct superset<unsigned char,unsigned short> { typedef unsigned short type; }; template<> struct superset<unsigned char,short> { typedef short type; }; template<> struct superset<unsigned char,unsigned int> { typedef unsigned int type; }; template<> struct superset<unsigned char,int> { typedef int type; }; template<> struct superset<unsigned char,cimg_uint64> { typedef cimg_uint64 type; }; template<> struct superset<unsigned char,cimg_int64> { typedef cimg_int64 type; }; template<> struct superset<unsigned char,float> { typedef float type; }; template<> struct superset<unsigned char,double> { typedef double type; }; template<> struct superset<signed char,unsigned char> { typedef short type; }; template<> struct superset<signed char,char> { typedef short type; }; template<> struct superset<signed char,unsigned short> { typedef int type; }; template<> struct superset<signed char,short> { typedef short type; }; template<> struct superset<signed char,unsigned int> { typedef cimg_int64 type; }; template<> struct superset<signed char,int> { typedef int type; }; template<> struct superset<signed char,cimg_uint64> { typedef cimg_int64 type; }; template<> struct superset<signed char,cimg_int64> { typedef cimg_int64 type; }; template<> struct superset<signed char,float> { typedef float type; }; template<> struct superset<signed char,double> { typedef double type; }; template<> struct superset<char,unsigned char> { typedef short type; }; template<> struct superset<char,signed char> { typedef short type; }; template<> struct superset<char,unsigned short> { typedef int type; }; template<> struct superset<char,short> { typedef short type; }; template<> struct superset<char,unsigned int> { typedef cimg_int64 type; }; template<> struct superset<char,int> { typedef int type; }; template<> struct superset<char,cimg_uint64> { typedef cimg_int64 type; }; template<> struct superset<char,cimg_int64> { typedef cimg_int64 type; }; template<> struct superset<char,float> { typedef float type; }; template<> struct superset<char,double> { typedef double type; }; template<> struct superset<unsigned short,char> { typedef int type; }; template<> struct superset<unsigned short,signed char> { typedef int type; }; template<> struct superset<unsigned short,short> { typedef int type; }; template<> struct superset<unsigned short,unsigned int> { typedef unsigned int type; }; template<> struct superset<unsigned short,int> { typedef int type; }; template<> struct superset<unsigned short,cimg_uint64> { typedef cimg_uint64 type; }; template<> struct superset<unsigned short,cimg_int64> { typedef cimg_int64 type; }; template<> struct superset<unsigned short,float> { typedef float type; }; template<> struct superset<unsigned short,double> { typedef double type; }; template<> struct superset<short,unsigned short> { typedef int type; }; template<> struct superset<short,unsigned int> { typedef cimg_int64 type; }; template<> struct superset<short,int> { typedef int type; }; template<> struct superset<short,cimg_uint64> { typedef cimg_int64 type; }; template<> struct superset<short,cimg_int64> { typedef cimg_int64 type; }; template<> struct superset<short,float> { typedef float type; }; template<> struct superset<short,double> { typedef double type; }; template<> struct superset<unsigned int,char> { typedef cimg_int64 type; }; template<> struct superset<unsigned int,signed char> { typedef cimg_int64 type; }; template<> struct superset<unsigned int,short> { typedef cimg_int64 type; }; template<> struct superset<unsigned int,int> { typedef cimg_int64 type; }; template<> struct superset<unsigned int,cimg_uint64> { typedef cimg_uint64 type; }; template<> struct superset<unsigned int,cimg_int64> { typedef cimg_int64 type; }; template<> struct superset<unsigned int,float> { typedef float type; }; template<> struct superset<unsigned int,double> { typedef double type; }; template<> struct superset<int,unsigned int> { typedef cimg_int64 type; }; template<> struct superset<int,cimg_uint64> { typedef cimg_int64 type; }; template<> struct superset<int,cimg_int64> { typedef cimg_int64 type; }; template<> struct superset<int,float> { typedef float type; }; template<> struct superset<int,double> { typedef double type; }; template<> struct superset<cimg_uint64,char> { typedef cimg_int64 type; }; template<> struct superset<cimg_uint64,signed char> { typedef cimg_int64 type; }; template<> struct superset<cimg_uint64,short> { typedef cimg_int64 type; }; template<> struct superset<cimg_uint64,int> { typedef cimg_int64 type; }; template<> struct superset<cimg_uint64,cimg_int64> { typedef cimg_int64 type; }; template<> struct superset<cimg_uint64,float> { typedef double type; }; template<> struct superset<cimg_uint64,double> { typedef double type; }; template<> struct superset<cimg_int64,float> { typedef double type; }; template<> struct superset<cimg_int64,double> { typedef double type; }; template<> struct superset<float,double> { typedef double type; }; #ifdef cimg_use_half template<> struct superset<half,unsigned short> { typedef float type; }; template<> struct superset<half,short> { typedef float type; }; template<> struct superset<half,unsigned int> { typedef float type; }; template<> struct superset<half,int> { typedef float type; }; template<> struct superset<half,cimg_uint64> { typedef float type; }; template<> struct superset<half,cimg_int64> { typedef float type; }; template<> struct superset<half,float> { typedef float type; }; template<> struct superset<half,double> { typedef double type; }; #endif template<typename t1, typename t2, typename t3> struct superset2 { typedef typename superset<t1, typename superset<t2,t3>::type>::type type; }; template<typename t1, typename t2, typename t3, typename t4> struct superset3 { typedef typename superset<t1, typename superset2<t2,t3,t4>::type>::type type; }; template<typename t1, typename t2> struct last { typedef t2 type; }; #define _cimg_Tt typename cimg::superset<T,t>::type #define _cimg_Tfloat typename cimg::superset<T,float>::type #define _cimg_Ttfloat typename cimg::superset2<T,t,float>::type #define _cimg_Ttdouble typename cimg::superset2<T,t,double>::type // Define variables used internally by CImg. #if cimg_display==1 struct X11_info { unsigned int nb_wins; pthread_t *events_thread; pthread_cond_t wait_event; pthread_mutex_t wait_event_mutex; CImgDisplay **wins; Display *display; unsigned int nb_bits; bool is_blue_first; bool is_shm_enabled; bool byte_order; #ifdef cimg_use_xrandr XRRScreenSize *resolutions; Rotation curr_rotation; unsigned int curr_resolution; unsigned int nb_resolutions; #endif X11_info():nb_wins(0),events_thread(0),display(0), nb_bits(0),is_blue_first(false),is_shm_enabled(false),byte_order(false) { #ifdef __FreeBSD__ XInitThreads(); #endif wins = new CImgDisplay*[1024]; pthread_mutex_init(&wait_event_mutex,0); pthread_cond_init(&wait_event,0); #ifdef cimg_use_xrandr resolutions = 0; curr_rotation = 0; curr_resolution = nb_resolutions = 0; #endif } ~X11_info() { delete[] wins; /* if (events_thread) { pthread_cancel(*events_thread); delete events_thread; } if (display) { } // XCloseDisplay(display); } pthread_cond_destroy(&wait_event); pthread_mutex_unlock(&wait_event_mutex); pthread_mutex_destroy(&wait_event_mutex); */ } }; // struct X11_info { ... #if defined(cimg_module) X11_info& X11_attr(); #elif defined(cimg_main) X11_info& X11_attr() { static X11_info val; return val; } #else inline X11_info& X11_attr() { static X11_info val; return val; } #endif #elif cimg_display==2 struct Win32_info { HANDLE wait_event; Win32_info() { wait_event = CreateEvent(0,FALSE,FALSE,0); } }; // struct Win32_info { ... #if defined(cimg_module) Win32_info& Win32_attr(); #elif defined(cimg_main) Win32_info& Win32_attr() { static Win32_info val; return val; } #else inline Win32_info& Win32_attr() { static Win32_info val; return val; } #endif #endif #define cimg_lock_display() cimg::mutex(15) #define cimg_unlock_display() cimg::mutex(15,0) struct Mutex_info { #ifdef _PTHREAD_H pthread_mutex_t mutex[32]; Mutex_info() { for (unsigned int i = 0; i<32; ++i) pthread_mutex_init(&mutex[i],0); } void lock(const unsigned int n) { pthread_mutex_lock(&mutex[n]); } void unlock(const unsigned int n) { pthread_mutex_unlock(&mutex[n]); } int trylock(const unsigned int n) { return pthread_mutex_trylock(&mutex[n]); } #elif cimg_OS==2 HANDLE mutex[32]; Mutex_info() { for (unsigned int i = 0; i<32; ++i) mutex[i] = CreateMutex(0,FALSE,0); } void lock(const unsigned int n) { WaitForSingleObject(mutex[n],INFINITE); } void unlock(const unsigned int n) { ReleaseMutex(mutex[n]); } int trylock(const unsigned int) { return 0; } #else Mutex_info() {} void lock(const unsigned int) {} void unlock(const unsigned int) {} int trylock(const unsigned int) { return 0; } #endif }; // struct Mutex_info { ... #if defined(cimg_module) Mutex_info& Mutex_attr(); #elif defined(cimg_main) Mutex_info& Mutex_attr() { static Mutex_info val; return val; } #else inline Mutex_info& Mutex_attr() { static Mutex_info val; return val; } #endif #if defined(cimg_use_magick) struct Magick_info { Magick_info() { Magick::InitializeMagick(""); } }; // struct Magick_info { ... static Magick_info _Magick_info; #endif #if defined(cimg_use_fftw3) struct FFTW3_info { FFTW3_info() { fftw_init_threads(); } }; // struct FFTW3_info { ... static FFTW3_info _FFTW3_info; #endif #if cimg_display==1 // Define keycodes for X11-based graphical systems. const unsigned int keyESC = XK_Escape; const unsigned int keyF1 = XK_F1; const unsigned int keyF2 = XK_F2; const unsigned int keyF3 = XK_F3; const unsigned int keyF4 = XK_F4; const unsigned int keyF5 = XK_F5; const unsigned int keyF6 = XK_F6; const unsigned int keyF7 = XK_F7; const unsigned int keyF8 = XK_F8; const unsigned int keyF9 = XK_F9; const unsigned int keyF10 = XK_F10; const unsigned int keyF11 = XK_F11; const unsigned int keyF12 = XK_F12; const unsigned int keyPAUSE = XK_Pause; const unsigned int key1 = XK_1; const unsigned int key2 = XK_2; const unsigned int key3 = XK_3; const unsigned int key4 = XK_4; const unsigned int key5 = XK_5; const unsigned int key6 = XK_6; const unsigned int key7 = XK_7; const unsigned int key8 = XK_8; const unsigned int key9 = XK_9; const unsigned int key0 = XK_0; const unsigned int keyBACKSPACE = XK_BackSpace; const unsigned int keyINSERT = XK_Insert; const unsigned int keyHOME = XK_Home; const unsigned int keyPAGEUP = XK_Page_Up; const unsigned int keyTAB = XK_Tab; const unsigned int keyQ = XK_q; const unsigned int keyW = XK_w; const unsigned int keyE = XK_e; const unsigned int keyR = XK_r; const unsigned int keyT = XK_t; const unsigned int keyY = XK_y; const unsigned int keyU = XK_u; const unsigned int keyI = XK_i; const unsigned int keyO = XK_o; const unsigned int keyP = XK_p; const unsigned int keyDELETE = XK_Delete; const unsigned int keyEND = XK_End; const unsigned int keyPAGEDOWN = XK_Page_Down; const unsigned int keyCAPSLOCK = XK_Caps_Lock; const unsigned int keyA = XK_a; const unsigned int keyS = XK_s; const unsigned int keyD = XK_d; const unsigned int keyF = XK_f; const unsigned int keyG = XK_g; const unsigned int keyH = XK_h; const unsigned int keyJ = XK_j; const unsigned int keyK = XK_k; const unsigned int keyL = XK_l; const unsigned int keyENTER = XK_Return; const unsigned int keySHIFTLEFT = XK_Shift_L; const unsigned int keyZ = XK_z; const unsigned int keyX = XK_x; const unsigned int keyC = XK_c; const unsigned int keyV = XK_v; const unsigned int keyB = XK_b; const unsigned int keyN = XK_n; const unsigned int keyM = XK_m; const unsigned int keySHIFTRIGHT = XK_Shift_R; const unsigned int keyARROWUP = XK_Up; const unsigned int keyCTRLLEFT = XK_Control_L; const unsigned int keyAPPLEFT = XK_Super_L; const unsigned int keyALT = XK_Alt_L; const unsigned int keySPACE = XK_space; const unsigned int keyALTGR = XK_Alt_R; const unsigned int keyAPPRIGHT = XK_Super_R; const unsigned int keyMENU = XK_Menu; const unsigned int keyCTRLRIGHT = XK_Control_R; const unsigned int keyARROWLEFT = XK_Left; const unsigned int keyARROWDOWN = XK_Down; const unsigned int keyARROWRIGHT = XK_Right; const unsigned int keyPAD0 = XK_KP_0; const unsigned int keyPAD1 = XK_KP_1; const unsigned int keyPAD2 = XK_KP_2; const unsigned int keyPAD3 = XK_KP_3; const unsigned int keyPAD4 = XK_KP_4; const unsigned int keyPAD5 = XK_KP_5; const unsigned int keyPAD6 = XK_KP_6; const unsigned int keyPAD7 = XK_KP_7; const unsigned int keyPAD8 = XK_KP_8; const unsigned int keyPAD9 = XK_KP_9; const unsigned int keyPADADD = XK_KP_Add; const unsigned int keyPADSUB = XK_KP_Subtract; const unsigned int keyPADMUL = XK_KP_Multiply; const unsigned int keyPADDIV = XK_KP_Divide; #elif cimg_display==2 // Define keycodes for Windows. const unsigned int keyESC = VK_ESCAPE; const unsigned int keyF1 = VK_F1; const unsigned int keyF2 = VK_F2; const unsigned int keyF3 = VK_F3; const unsigned int keyF4 = VK_F4; const unsigned int keyF5 = VK_F5; const unsigned int keyF6 = VK_F6; const unsigned int keyF7 = VK_F7; const unsigned int keyF8 = VK_F8; const unsigned int keyF9 = VK_F9; const unsigned int keyF10 = VK_F10; const unsigned int keyF11 = VK_F11; const unsigned int keyF12 = VK_F12; const unsigned int keyPAUSE = VK_PAUSE; const unsigned int key1 = '1'; const unsigned int key2 = '2'; const unsigned int key3 = '3'; const unsigned int key4 = '4'; const unsigned int key5 = '5'; const unsigned int key6 = '6'; const unsigned int key7 = '7'; const unsigned int key8 = '8'; const unsigned int key9 = '9'; const unsigned int key0 = '0'; const unsigned int keyBACKSPACE = VK_BACK; const unsigned int keyINSERT = VK_INSERT; const unsigned int keyHOME = VK_HOME; const unsigned int keyPAGEUP = VK_PRIOR; const unsigned int keyTAB = VK_TAB; const unsigned int keyQ = 'Q'; const unsigned int keyW = 'W'; const unsigned int keyE = 'E'; const unsigned int keyR = 'R'; const unsigned int keyT = 'T'; const unsigned int keyY = 'Y'; const unsigned int keyU = 'U'; const unsigned int keyI = 'I'; const unsigned int keyO = 'O'; const unsigned int keyP = 'P'; const unsigned int keyDELETE = VK_DELETE; const unsigned int keyEND = VK_END; const unsigned int keyPAGEDOWN = VK_NEXT; const unsigned int keyCAPSLOCK = VK_CAPITAL; const unsigned int keyA = 'A'; const unsigned int keyS = 'S'; const unsigned int keyD = 'D'; const unsigned int keyF = 'F'; const unsigned int keyG = 'G'; const unsigned int keyH = 'H'; const unsigned int keyJ = 'J'; const unsigned int keyK = 'K'; const unsigned int keyL = 'L'; const unsigned int keyENTER = VK_RETURN; const unsigned int keySHIFTLEFT = VK_SHIFT; const unsigned int keyZ = 'Z'; const unsigned int keyX = 'X'; const unsigned int keyC = 'C'; const unsigned int keyV = 'V'; const unsigned int keyB = 'B'; const unsigned int keyN = 'N'; const unsigned int keyM = 'M'; const unsigned int keySHIFTRIGHT = VK_SHIFT; const unsigned int keyARROWUP = VK_UP; const unsigned int keyCTRLLEFT = VK_CONTROL; const unsigned int keyAPPLEFT = VK_LWIN; const unsigned int keyALT = VK_LMENU; const unsigned int keySPACE = VK_SPACE; const unsigned int keyALTGR = VK_CONTROL; const unsigned int keyAPPRIGHT = VK_RWIN; const unsigned int keyMENU = VK_APPS; const unsigned int keyCTRLRIGHT = VK_CONTROL; const unsigned int keyARROWLEFT = VK_LEFT; const unsigned int keyARROWDOWN = VK_DOWN; const unsigned int keyARROWRIGHT = VK_RIGHT; const unsigned int keyPAD0 = 0x60; const unsigned int keyPAD1 = 0x61; const unsigned int keyPAD2 = 0x62; const unsigned int keyPAD3 = 0x63; const unsigned int keyPAD4 = 0x64; const unsigned int keyPAD5 = 0x65; const unsigned int keyPAD6 = 0x66; const unsigned int keyPAD7 = 0x67; const unsigned int keyPAD8 = 0x68; const unsigned int keyPAD9 = 0x69; const unsigned int keyPADADD = VK_ADD; const unsigned int keyPADSUB = VK_SUBTRACT; const unsigned int keyPADMUL = VK_MULTIPLY; const unsigned int keyPADDIV = VK_DIVIDE; #else // Define random keycodes when no display is available. // (should rarely be used then!). const unsigned int keyESC = 1U; //!< Keycode for the \c ESC key (architecture-dependent) const unsigned int keyF1 = 2U; //!< Keycode for the \c F1 key (architecture-dependent) const unsigned int keyF2 = 3U; //!< Keycode for the \c F2 key (architecture-dependent) const unsigned int keyF3 = 4U; //!< Keycode for the \c F3 key (architecture-dependent) const unsigned int keyF4 = 5U; //!< Keycode for the \c F4 key (architecture-dependent) const unsigned int keyF5 = 6U; //!< Keycode for the \c F5 key (architecture-dependent) const unsigned int keyF6 = 7U; //!< Keycode for the \c F6 key (architecture-dependent) const unsigned int keyF7 = 8U; //!< Keycode for the \c F7 key (architecture-dependent) const unsigned int keyF8 = 9U; //!< Keycode for the \c F8 key (architecture-dependent) const unsigned int keyF9 = 10U; //!< Keycode for the \c F9 key (architecture-dependent) const unsigned int keyF10 = 11U; //!< Keycode for the \c F10 key (architecture-dependent) const unsigned int keyF11 = 12U; //!< Keycode for the \c F11 key (architecture-dependent) const unsigned int keyF12 = 13U; //!< Keycode for the \c F12 key (architecture-dependent) const unsigned int keyPAUSE = 14U; //!< Keycode for the \c PAUSE key (architecture-dependent) const unsigned int key1 = 15U; //!< Keycode for the \c 1 key (architecture-dependent) const unsigned int key2 = 16U; //!< Keycode for the \c 2 key (architecture-dependent) const unsigned int key3 = 17U; //!< Keycode for the \c 3 key (architecture-dependent) const unsigned int key4 = 18U; //!< Keycode for the \c 4 key (architecture-dependent) const unsigned int key5 = 19U; //!< Keycode for the \c 5 key (architecture-dependent) const unsigned int key6 = 20U; //!< Keycode for the \c 6 key (architecture-dependent) const unsigned int key7 = 21U; //!< Keycode for the \c 7 key (architecture-dependent) const unsigned int key8 = 22U; //!< Keycode for the \c 8 key (architecture-dependent) const unsigned int key9 = 23U; //!< Keycode for the \c 9 key (architecture-dependent) const unsigned int key0 = 24U; //!< Keycode for the \c 0 key (architecture-dependent) const unsigned int keyBACKSPACE = 25U; //!< Keycode for the \c BACKSPACE key (architecture-dependent) const unsigned int keyINSERT = 26U; //!< Keycode for the \c INSERT key (architecture-dependent) const unsigned int keyHOME = 27U; //!< Keycode for the \c HOME key (architecture-dependent) const unsigned int keyPAGEUP = 28U; //!< Keycode for the \c PAGEUP key (architecture-dependent) const unsigned int keyTAB = 29U; //!< Keycode for the \c TAB key (architecture-dependent) const unsigned int keyQ = 30U; //!< Keycode for the \c Q key (architecture-dependent) const unsigned int keyW = 31U; //!< Keycode for the \c W key (architecture-dependent) const unsigned int keyE = 32U; //!< Keycode for the \c E key (architecture-dependent) const unsigned int keyR = 33U; //!< Keycode for the \c R key (architecture-dependent) const unsigned int keyT = 34U; //!< Keycode for the \c T key (architecture-dependent) const unsigned int keyY = 35U; //!< Keycode for the \c Y key (architecture-dependent) const unsigned int keyU = 36U; //!< Keycode for the \c U key (architecture-dependent) const unsigned int keyI = 37U; //!< Keycode for the \c I key (architecture-dependent) const unsigned int keyO = 38U; //!< Keycode for the \c O key (architecture-dependent) const unsigned int keyP = 39U; //!< Keycode for the \c P key (architecture-dependent) const unsigned int keyDELETE = 40U; //!< Keycode for the \c DELETE key (architecture-dependent) const unsigned int keyEND = 41U; //!< Keycode for the \c END key (architecture-dependent) const unsigned int keyPAGEDOWN = 42U; //!< Keycode for the \c PAGEDOWN key (architecture-dependent) const unsigned int keyCAPSLOCK = 43U; //!< Keycode for the \c CAPSLOCK key (architecture-dependent) const unsigned int keyA = 44U; //!< Keycode for the \c A key (architecture-dependent) const unsigned int keyS = 45U; //!< Keycode for the \c S key (architecture-dependent) const unsigned int keyD = 46U; //!< Keycode for the \c D key (architecture-dependent) const unsigned int keyF = 47U; //!< Keycode for the \c F key (architecture-dependent) const unsigned int keyG = 48U; //!< Keycode for the \c G key (architecture-dependent) const unsigned int keyH = 49U; //!< Keycode for the \c H key (architecture-dependent) const unsigned int keyJ = 50U; //!< Keycode for the \c J key (architecture-dependent) const unsigned int keyK = 51U; //!< Keycode for the \c K key (architecture-dependent) const unsigned int keyL = 52U; //!< Keycode for the \c L key (architecture-dependent) const unsigned int keyENTER = 53U; //!< Keycode for the \c ENTER key (architecture-dependent) const unsigned int keySHIFTLEFT = 54U; //!< Keycode for the \c SHIFTLEFT key (architecture-dependent) const unsigned int keyZ = 55U; //!< Keycode for the \c Z key (architecture-dependent) const unsigned int keyX = 56U; //!< Keycode for the \c X key (architecture-dependent) const unsigned int keyC = 57U; //!< Keycode for the \c C key (architecture-dependent) const unsigned int keyV = 58U; //!< Keycode for the \c V key (architecture-dependent) const unsigned int keyB = 59U; //!< Keycode for the \c B key (architecture-dependent) const unsigned int keyN = 60U; //!< Keycode for the \c N key (architecture-dependent) const unsigned int keyM = 61U; //!< Keycode for the \c M key (architecture-dependent) const unsigned int keySHIFTRIGHT = 62U; //!< Keycode for the \c SHIFTRIGHT key (architecture-dependent) const unsigned int keyARROWUP = 63U; //!< Keycode for the \c ARROWUP key (architecture-dependent) const unsigned int keyCTRLLEFT = 64U; //!< Keycode for the \c CTRLLEFT key (architecture-dependent) const unsigned int keyAPPLEFT = 65U; //!< Keycode for the \c APPLEFT key (architecture-dependent) const unsigned int keyALT = 66U; //!< Keycode for the \c ALT key (architecture-dependent) const unsigned int keySPACE = 67U; //!< Keycode for the \c SPACE key (architecture-dependent) const unsigned int keyALTGR = 68U; //!< Keycode for the \c ALTGR key (architecture-dependent) const unsigned int keyAPPRIGHT = 69U; //!< Keycode for the \c APPRIGHT key (architecture-dependent) const unsigned int keyMENU = 70U; //!< Keycode for the \c MENU key (architecture-dependent) const unsigned int keyCTRLRIGHT = 71U; //!< Keycode for the \c CTRLRIGHT key (architecture-dependent) const unsigned int keyARROWLEFT = 72U; //!< Keycode for the \c ARROWLEFT key (architecture-dependent) const unsigned int keyARROWDOWN = 73U; //!< Keycode for the \c ARROWDOWN key (architecture-dependent) const unsigned int keyARROWRIGHT = 74U; //!< Keycode for the \c ARROWRIGHT key (architecture-dependent) const unsigned int keyPAD0 = 75U; //!< Keycode for the \c PAD0 key (architecture-dependent) const unsigned int keyPAD1 = 76U; //!< Keycode for the \c PAD1 key (architecture-dependent) const unsigned int keyPAD2 = 77U; //!< Keycode for the \c PAD2 key (architecture-dependent) const unsigned int keyPAD3 = 78U; //!< Keycode for the \c PAD3 key (architecture-dependent) const unsigned int keyPAD4 = 79U; //!< Keycode for the \c PAD4 key (architecture-dependent) const unsigned int keyPAD5 = 80U; //!< Keycode for the \c PAD5 key (architecture-dependent) const unsigned int keyPAD6 = 81U; //!< Keycode for the \c PAD6 key (architecture-dependent) const unsigned int keyPAD7 = 82U; //!< Keycode for the \c PAD7 key (architecture-dependent) const unsigned int keyPAD8 = 83U; //!< Keycode for the \c PAD8 key (architecture-dependent) const unsigned int keyPAD9 = 84U; //!< Keycode for the \c PAD9 key (architecture-dependent) const unsigned int keyPADADD = 85U; //!< Keycode for the \c PADADD key (architecture-dependent) const unsigned int keyPADSUB = 86U; //!< Keycode for the \c PADSUB key (architecture-dependent) const unsigned int keyPADMUL = 87U; //!< Keycode for the \c PADMUL key (architecture-dependent) const unsigned int keyPADDIV = 88U; //!< Keycode for the \c PADDDIV key (architecture-dependent) #endif const double PI = 3.14159265358979323846; //!< Value of the mathematical constant PI // Define a 10x13 binary font (small sans). static const char *const data_font_small[] = { " UwlwnwoyuwHwlwmwcwlwnw[xuwowlwmwoyuwRwlwnxcw Mw (wnwnwuwpwuypwuwoy" "ZwnwmwuwowuwmwnwnwuwowuwfwuxnwnwmwuwpwuypwuwZwnwnwtwpwtwow'y Hw cwnw >{ jw %xdxZwdw_wexfwYwkw 7yowoyFx=w " "ry qw %wuw !xnwkwnwoyuwfwuw[wkwnwcwowrwpwdwuwoxuwpwkwnwoyuwRwkwnwbwpwNyoyoyoyoy;wdwnxpxtxowG|!ydwnwuwowtwow" "pxswqxlwnxnxmwDwoyoxnyoymwp{oyq{pyoy>ypwqwpwp{oyqzo{q{pzrwrwowlwqwswpwnwqwsxswpypzoyqzozq}swrwrwqwtwswswtxsxswq" "ws}qwnwkwnydwew_wfwdwkwmwowkw(w0wmwmwGwtwdxQw swuwnwo{q{pynwp|rwtwtwqydwcwcwcwmwmxgwqwpwnzpwuwpzoyRzoyoyexnynwd" "z\\xnxgxrwsxrwsyswowmwmwmwmwmwmwo}ryp{q{q{q{nwmwnwmwozqxswpyoyoyoyoyeyuwswrwrwrwrwrwrwrwrwqwrwmwtwnwmwnwuwpwuyp" "wuwoyZwmwnwuwowuwmwqwkwuwowuwoxnwuxowmwnwuwpwuypwuwZwmwnwuwowuwnwowmwtw\\wuwuwqwswqwswqwswqwswEwqwtweypzr~qyIw " "rwswewnwuwowuwozswtwuwqwtwmwnwlwowuwuwowOxpxuxqwuwowswqwswoxpwlwjwqwswqwsw<wrwowrwuwqwrwqwswrwswpwmwmwrwswrwowl" "wqwtwownxsxsxswqwswqwswqwswrwswqwrwowpwrwrwqwtwswswswswqwswmwpwmwlwoxuxSw_wfwdwYwkw(w0wmwmwGwtwoxnwNw uwswpwuwp" "wmwmwswq{rwrwrwtwtwrwswfydwdyZwnwtwrwqwrwswowowdwrwqxuwSwrwfwuwnwlwnw[yuw[wowtwgwswqwswqwswewuwowuwowuwowuwowuw" "nwowuwowswqwmwmwmwjwmwnwmwowswrxswqwswqwswqwswqwswqwswrwrwqwswrwrwrwrwrwrwrwrwqwswqzpwtw #w DwPwtwtwswqwswuwuwu" "wswswuwswqwGwqxtwf{qzr~r{qzqwrwpxowtwrw rzcwnwuwq}rwuwqwtwuwqwtwmwnwlwnynwOwowswowkwmwpwuwpwmwjwpwswqwswowmwjwi" "wjxswsytwrwuwqwrwrwmwrwqwmwnwmwrwowlwqwuwnwnxsxswuwtwrwqwrwswrwqwswswqwjwpwrwqwswrwtwtwqwuwowuwmwowmwlwpxsx]ypz" "oyozpypzozqznwmwowtwnwqzuyrzoypzozqwuxoypzpwswrwrwrwtwtwswrwrwrwq{owmwmwQyuwqwtwmwoxnypzqxswowowswqwswqwtxr|rwt" "wtwqyp{q{qwswpwuwownwnwqwsxuwuxswrwrwtwtwswqwrwmwuwuwnwnwowtwpwuwuwewnzpwn{pwuwnwnxgwtxtwrwtwowtw_wuytwgynwmwlw" "gwswpyuw[wowtwqwtwpwtwpwtwowuwmwnwuwowuwowuwowuwowuwowuwqxuwpwlwmwmwmwjwmwnwmwowrwswuwtwrwqwswqwswqwswqwswqwrwt" "wqwswuwswrwrwrwrwrwrwrwpwuwpwswqwuwnyoyoyoyoyoyqyuyqyoyoyoyoymwqwjwmwnypzoyoyoyoyoynwnzqwswqwswqwswqwswrwrwqzqw" "rw^}s}swtwtwswtwtwswtwtwK}rwuwe{s~t~s}rwtwqwrwpxowtwrw qwawewtwpwuwpxuwpycwlwnynwOwowswowkwpypwtwpzpzmwoypwsw[y" "r}rymwrwtwtwtwrwuwq{qwmwrwq{q{rwm|owlwqxmwnwuwuwuwswuwtwrwqwrwswrwqwswswqylwpwrwqwswrwuwuwuwpwmwmwnwmwlwMwqwswq" "wmwswqwswpwnwswqwswowmwowuwmwqwswswswswqwswqwswqwswqxnwswpwnwswrwrwrwtwtwrwtwqwrwmwqxlwlx]xuxrwtyqwuwlwpwtwpwmw" "swqwtxpxowswrwqwswtwuxrwtwqwtwtwrwswrwswnwo{pwuwnxpwnwqwswtwtwswrwrwtwtwswuyuwswjwkwowpwrwowcwowuwnwnwswqxuxowo" "wtwhwuwrwrzpwtwq}jwuwtwuw_}qyoxfwswpyuwowdyoxowtwryuwqyuwqyuwmwnwuwowuwowuwowuwowuwowuwqwt{twl{q{q{q{nwmwnwmwpz" "twswuwtwrwqwswqwswqwswqwswqwqxpwtwtwswrwrwrwrwrwrwrwowowswqwuwkwmwmwmwmwmwowswswmwswqwswqwswqwswnwqwjwmwowswqws" "wqwswqwswqwswqwswqwswgwtxqwswqwswqwswqwswrwrwqwswrwrw^wtwtwswqwswuwuwuwswuwswswqwHwowuwf}t~s|r}swrwrwrwqwtwpwtw" "r~#zcwewtwoynwuxtwtwswgwlwowuwuwr}gyexowswowlwlwrwswlwqwswowowswpz^yayqwqwtwtwuwrwswrwrwrwmwrwqwmwnwsyswrwowlwq" "wuwnwnwuwuwuwswtwuwrwqwrzqwqwszmyowpwrwpwuwqwuwuwuwpwmwmwnwlwmwPzqwswqwmwswq{pwnwswqwswowmwoxlwqwswswswswqwswqw" "swqwswqwlxnwnwswqwtwqwuwuwuwqxowtwmwnwmwmwoytwiwtwtwswswpwtxqzpwswpxowswpwuwowuwpwswrwtwtwswtwtwrwtwqwtwtwrwswr" "wswnwowswqwswowownwqwswtwtwswrwqwuwuwrwuyuwt~pwq~pwq~pwcwowuwozpwswowewswiwuwrwiwtwjwjwuytw\\wRwswoxuwHwtwpwswq" "wtxqwswqxowswqwswqwswqwswqwswqwswrwtwpwlwmwmwmwjwmwnwmwowrwswtwuwrwqwswqwswqwswqwswqwqxpwtwtwswrwrwrwrwrwrwrwow" "owswqwtwozpzpzpzpzpzr~swm{q{q{q{nwqwjwmwowswqwswqwswqwswqwswqwswqwswr}rwuwuwqwswqwswqwswqwswqwtwpwswqwtw\\wuwuw" "qwswqwswqwswqwswJ}qxf}t~rzp{rwrwrwrwqwtwpwtwrw qwawg}owuwpwuwtwuwswuwfwlwmwmwPwnwswowmwkwr|mwqwswowowswmw^yo}oy" "qwqwszq{rwrwrwmwrwqwmwnwqwswrwowlwqwtwownwtwtwswtwuwrwqwrwnwqwswtwkwowpwrwpwuwqwuwuwuwqwuwnwnwmwlwmwQwswqwswqwm" "wswqwlwnwswqwswowmwowuwmwqwswswswswqwswqwswqwswqwjwownwswqwtwqwuwuwuwqxowtwnwmwmwmwpwtyhwtwtwswswpwswqwtwpwswqw" "mwswpwuwpwtwpwswrwtwtwswtwtwrwtwqwtwtwrwswrwswnwowswqwswpwnwnwqwsxuwuxswrwpyqwqwswjwkwqwuwuwrwrwqwuwuwewowuwnwn" "wswq{ownxuwiwtxtwrzpwtwkwjwuwtwuw\\wRwswnwuwSzpwtwowtxqwrwrwtxrxn{q{q{q{q{q{s{pwlwmwmwmwjwmwnwmwowrwswtwuwrwqws" "wqwswqwswqwswqwrwtwqwuwswswrwrwrwrwrwrwrwowozpwswqwswqwswqwswqwswqwswqwswswswowmwmwmwmwjwqwjwmwowswqwswqwswqwsw" "qwswqwswqwswgwuwuwqwswqwswqwswqwswqwtwpwswqwtw[yoyoyoyoyGwmwdwuwuwpxnxnyqwrwqwtwpwtwoxpw rwswSwuwmwuwpwuwtwuxsw" "ewlwcwPwnxuxownwnwswnwlwqwswowowswnwZygygwkwswrwrwqwswrwswpwmwmwrwswrwowlwqwswpwnwqwswsxqwswqwmwswrwswqwrwowpxt" "xowowswqwswowowlwlwmwQwswqwswqwmwswqwswpwnwswqwswowmwowtwnwqwswswswswqwswqwswqwswqwmwswpwnwswpxowswqwtwoxnwlwmw" "mw[xuxrwtxpwswqwtwpwswqwmwswpypwtwpwswrwtwtwsxuwuxrwtwqwtwtwrwswrwswnwnwuwpwswqwmwmwswq{rwrwowowswqwkwlwoypwtwo" "ydwowuwnwn{owmwlwgwrwfwtw^wrw6wswnwuwJwtwowtzswrwrwtzswmwswqwswqwswqwswqwswqwswswswowswqwmwmwmwjwmwnwmwowswrwsx" "qwswqwswqwswqwswqwswrwrwqwswrxtxrxtxrxtxrxtxowowmwswqwswqwswqwswqwswqwswqwswswtxowmwswqwswqwswqwswnwqwjwmwowswq" "wswqwswqwswqwswqwswqwswowoxtwqwswqwswqwswqwswpxowswpx Wwlwbwnxcwpwrwqzpwtwoxo|!ydwfwtwozpwsxszuxgxnxcwmwcwoxmyp" "{q{pymwpzoyowmypymwmwjwiwkwowrwrwqws{oyqzo{qwlzrwrwowlwqwrwq{rwqwswsxpypwlyqwrwqznwoznwowswrxsxpwp}qwkwnwPzqzoy" "ozpyowmzqwswowmwowswowqwswswswswpypzozqwlynxozpxowswrwrwpwn{owmwmwQxuxqzoxnyoypwswowpwrwqzpxuxq{qwtxq{qzpylwoyq" "}r{qwnyuypwpwrwownydwcwcwcwnzq{rwqwpwmwkwgzHz]}U|owuw@wqwswrytwqwqyqwqwswqwswqwswqwswqwswqwuwr{ryp{q{q{q{nwmwnw" "mwozqwsxpyoyoyoyoygwuypzpzpzpznwowmwuypzpzpzpzpzpzryuzryoyoyoyoymwqwjwmwnypwswpyoyoyoyoyfzozpzpzpzpwnzow \\w" "OwnwXw[w SwGz kx0x lxdx gw[w=wiw*wbyowoyGwKwowewawcwow YwOwoz Ewjwuwdw 7w 9w Iwnwlw \\w 0|*y[x=wiw," "xWw=wKwowewawcwow Yw hwVx 8w 9w Jxmwnxp" }; // Define a 26x32 font (normal sans). static const char *const data_font_normal[] = { " #{}~}a{|y~f{|y~}f{|}|x{}|j{|y}y{|y}g{}y~}|2y~|a{}~}f{}y~|" "gy}|yy}|i{}~}a{}~}f{}y~}gy}|yx}N{|}|x{}|hy~|ay~|fx~|g{}y~|y{}~j{|y~|yy~}5{}~}a{}~}f{}y~}gy~}yy~}e{|y~ " " 2{}~}c{|y~f{|y~}~}h{}w~y}~|j{}y~y{}y~h{}~y}y~|2y~|c{}~}f{" "}~y}~|hy~}yy~}hy~|c{|~}f{|~y}~|hy~}y{}y~O{}w~y}~|gy~|cy~|fy~|}~|i{|~y}y~}~}j{|y~|yy~}4{}~|c{}~}f{}~|}~}hy~}yy~}" "ey~| g{|}y~} J{}~|dy~|fy~y{}~|i{~}{|}y~}i{}y~y{}y" "~i{|~}x{~}2{|y~d{|~}f{|~}yy~hy~}yy~}gy~cy~f{|~}y{}~|iy~}y{}y~P{|~}{|}y~|ey~d{}~|fy~x{}~|j{}~y{|}~}i{|y}|yy}|3{}" "~|e{}~}f{}~|y{|~|iy}|yx}f{}~| fy~y}~} k{|y~| /{|y~| y{}" "~} Xy|e{|}|f{|}wy|5{|~|x{}~1{|}|ey|ey|wy|M{|}|e{|}|fy|wy| g{|}|3{|y~|_{}~}g{|y~2{}~|y{}~|5{|y~^y~}g{}y~N{|" "}|^{|}|g{|}| s{}~}_{|y~|gy~} Z{}~}_{|y~|gy~} )y}| -{|y~ Jy}|yy}| " "X{}y~ 4{|~}y{|~} P{| n{|y~`{|y~fx~}3{}~x{|~|4{}~}`{}~}g{|x~}N{}~}`{|y~|gx~| sy~|`y~|g{}x~| Z{}~}`y~}g{}" "x~|I{}y~ 1{|x~|oi| r{|~|O{|d{|y}|j{|y}|u{|y}|h{| \"{|}x~}|Ny~}g{|y~y{|~}g{|~}x{|~}i{|~l{|}y~}|s{|~}l{|}x~}|e" "{|y~by~g{}~}b{~} S{|y~i{|}x~}|i{|y}x~|i{|y}x~y}i{|y}w~}|d{}x~kq~|i{|}w~}|m{}o~k{|}x~y}h{|}x~}| B{|}w~}L{|x~j{|s" "~y}g{|}w~}|o{|s~y}|k{|o~n{|p~j{|}w~y}|o{|y~|ry~}k{|y~|e{|y~|j{|y~|t{|x~n{|y~|i{|x~}r{|x~}s{|x~|sy~}l{|}x~y}|l{|" "s~}|i{|}x~y}|m{|s~}|hy}w~y}|ok~}r{}y~r{|y~|r{}y~|p{}y~vy~}t{|x~sy~}ux~rx~q{}y~|r{}y~|r{|l~l{}v~hy~|c{|v~|f{|}|L" "{}~}M{}y~@{}~}O{|}w~R{}y~`{|y~d{|y~h{}y~`{|y~ ay}y~}h{}~}h{}y~y} Wy}x~}|O{|y}w~}| xx~} I{|}x~}f{|x~i{|o~m{|" "o~m{|y}x~}|f{}y~k{|m~}r{|y~|w{}y~vy~}n{|}x~y}|My}Iy}|J{}~| q{|}x~y}T{}y~r{}~}R{}w~}|j{|y~}yy~}O{|}w~} \\{|t~}h{" "|}y~}M{|}x~}|h{|}x~}|e{|y~L{|}t~|7y}y~}f{|}x~}Uy|y}|py}p{|n{|t{|}w~}r{|y~P{|x~e{|x~e{|x~e{|x~e{|x~f{}v~|jk~|o{|" "}w~}|m{|o~n{|o~n{|o~n{|o~j{|y~|e{|y~|e{|y~|e{|y~|k{|s~y}|m{|x~|sy~}l{|}x~y}|i{|}x~y}|i{|}x~y}|i{|}x~y}|i{|}x~y}" "|O{|}x~y}|y{|~}s{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|q{}y~|r{}y~|p{|y~|b{|}x~}|h{}~}b{|y~|g{}~|}~|h{|y~}|" "{}~iy~}yy~}i{}~|y{}~|3{}~}b{|~}fy~{}~|i{|y~|{|y~}iy~|ay~}g{}~}y~gy~}yy~}i{|y~}wy|j{|y~}y{}~hy~|b{}~}g{|~}|~}h{|" "}y~}{|~}j{}y~y{}y~|4y~|b{}~}g{|~}{y~h{}y~y{|y~|f{|y~|k{}y~by~}y{}y~ ev~o{}k~} r{}~O{|~e{}v~l{}v~w{}w~}j{}~ Y{}" "o~ S{|s~}Oy~}g{|y~y{|~}g{}~|x{}~|i{|~m{|y~y}y~|ty~l{}t~}f{|y~c{}~}fy~b{~} S{}~}j{}t~}kt~|j{}r~|l{|r~}f{|w~kq~|" "j{}s~|n{}p~}m{|r~|l{|s~| D{}s~|i{|y}y~y}|hw~|k{|p~|k{|q~}q{|p~}|m{|o~n{|p~l{|p~}q{|y~|ry~}k{|y~|e{|y~|j{|y~|u{|" "x~m{|y~|i{|w~|sw~}s{|w~sy~}n{}r~}m{|q~}l{}r~}n{|q~}k{|q~|pk~}r{}y~r{|y~|r{|y~}py~}v{}y~t{}x~|u{|y~|u{|y~}t{}y~|" "py~}s{|y~}q{|l~l{}w~}h{}~}c{|v~|gw~}L{}~|N{}y~@{}~}P{|u~R{}y~`{|y~d{|y~h{}y~`{|y~ e{}y~ {}w~}h{}~}h{}v~ Ys~}Q" "{|r~| yv~ K{}t~|hw~|j{|o~m{|o~n{}r~|h{}y~k{|m~}r{|y~|w{}y~vy~}p{}r~}O{}x~Jy~|K{}x~|/{~|f{}t~}Ty~|t{|y~|Ss~j{|y" "~}yy~}i{|}v~}|j{}~w}y~ v{|}v~}|k{|t~}i{|y~}x~N{}~}|}y~|i{|y}y|}~}fy~|N{|u~y}y~|8{|~y}~}g{|y~x}y~W{|w~}q{}~}s{}x" "~}q{|y~t{|}x|}~}s{}~|Pw~|fw~|fw~|fw~|fw~|fw~|j{|k~|q{|q~}o{|o~n{|o~n{|o~n{|o~j{|y~|e{|y~|e{|y~|e{|y~|k{|o~|o{|w" "~sy~}n{}r~}l{}r~}l{}r~}l{}r~}l{}r~}R{}r~}|y~|s{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|py~}s{|y~}o{|y~|cs~}h{" "}~}cy~|g{|~}yy~i{|y~}w~}iy~}yy~}hy~y}~}1y~|d{|y~f{}~|{|~}i{|y~|{|y~}i{|y~b{}~}g{|~}{|~}hy~}yy~}h{|y~y}y~}|k{|y~" "}y~}~}h{|y~c{|~}fy~y{|~|i{}~}v~|j{}y~y{}y~|4{|y~c{|~}fy~y{|~}i{}y~y{|y~|fy~|j{}y~by~}y{}y~ f{|y~{}~|p{|k~| r{~" "}Oy~}g{}u~}n{}t~y{}u~}l{}y~} \\{}m~ T{|x~}|{y|y~|Py~}g{|y~y{|~}gy~|xy~|i{|~my~|y{|y~u{}~}m{}y~}|y{|y}f{|y~d{|y" "~e{}~}hy|x{~}x{| Wy~|k{|y~}|{|}y~}lx~y}y~|jx~}x|}x~|m{|~}v|x~}gv~ky~s|j{}x~w|}~|nr|}y~|mx~}|{y|x~|mx~y|{|}y~| E" "y~}x|}x~k{}q~|k{|w~}k{|y~u|}x~l{}x~}v|}y~|r{|y~u|y}x~}n{|y~q|n{|y~r|m{}x~}v|}x~|r{|y~|ry~}k{|y~|e{|y~|j{|y~|v{|" "x~l{|y~|i{|w~}t{|w~}s{|w~}ty~}o{}x~}|{y|}x~n{|y~v|}x~|n{}x~}|{y|}x~o{|y~v|}x~}m{|x~}v|}~|pt|y~}u|q{}y~r{|y~|qx~" "q{|y~|v{|y~|u{}x~|u{}y~|t{}y~|v{|y~}o{|y~|tx~op|}y~}l{}~}e{|y~`{|y~|h{}v~}L{}~|O{}y~@{}~}Py~}|O{}y~`{|y~d{|y~h{" "}y~`{|y~ e{}y~ !{|y~}e{}~}e{|y~| [{}y~|x{}y~|jy}~y}|ix~|w{|}| w{}y~| M{}y~|y{|}y~i{|w~}ix~r|m{|y~q|p{|w~}x|}x" "~}l{|y}x~y}|n{|y~q|y~}r{|y~|w{}y~vy~}q{}x~}|{y|}x~Q{}v~Ky~|L{}v~|0{~|g{|y~}|y{|y}T{}y~t{}~}i{}~}h{}y~|x{|}P{}~y" "}x|y}~}k{|v{}~| x{}~y}x|y}~}Qy~x{|~}J{|y~cy~g{}~|Mt~y{}~|5{|~}gy~|x{}~}U{|~}r{|y~r{}y|~}qy~|ny~t{|~}P{|w~}g{|w~" "}g{|w~}g{|w~}g{|w~}fw~}j{}y~y|y~}r|q{}x~}v|}y~|p{|y~q|n{|y~q|n{|y~q|n{|y~q|j{|y~|e{|y~|e{|y~|e{|y~|k{|y~}u|}x~}" "p{|w~}ty~}o{}x~}|{y|}x~n{}x~}|{y|}x~n{}x~}|{y|}x~n{}x~}|{y|}x~n{}x~}|{y|}x~T{}x~}|{y|v~|r{}y~r{|y~|q{}y~r{|y~|q" "{}y~r{|y~|q{}y~r{|y~|p{|y~|tx~n{|y~|d{}y~|x{}y~|h{}~|e{}~|f{~}x{|~}j{|}xx}hy}|yy}|h{|}y~}/y~dy~|g{|~}x{|~|j{|y}" "|yy}|h{|~}d{|~}f{}~x{}~|iy}|yy}|iy|w~|h{}~y{|}~}f{|~}e{|~}f{}~|x{}~|j{}|y{|y}|i{|y}y{|y}2{|~}dy~f{}~|x{}~|j{|y}" "y{|y}|g{}~|i{}y~by}|y{|y}5{|}w~}|i{|}w~}|i{|}w~}|i{|}w~}|i{|}w~}|f{}~}{y|ny~}q{}y~ r{|~O{}x~|hs~|p{|s~y|s~|n{|w" "~} ^{}y~}| Ix~|u{}|Py~}g{|y~y{|~}gy~wy~k{|}v~y}|s{|y~w{}~|w{|y~ly~}_{|y~d{}~}dy~|iy~}y{~}{|y~|hy}| o{|y~jx~v{}" "y~l{|x{|y~|j{}|u{|x~d{}y~|i{}~|}y~ky~|d{|y~}]{}y~m{|y~|v{|y~}n{}y~|v{}y~ E{}u{}y~|n{|x~}|w{|}y~}|m{}y~}y~k{|y~|" "u{|y~}n{}y~}s{|~|r{|y~|t{|x~|o{|y~|e{|y~|f{}y~}r{}~|r{|y~|ry~}k{|y~|e{|y~|j{|y~|w{}y~}k{|y~|i{|y~}y~t{}~}y~}s{|" "v~ty~}p{}y~}t{}y~}o{|y~|v{|x~o{}y~}t{}y~}p{|y~|v{|x~mx~r{|iy~}k{}y~r{|y~|q{|y~|r{}y~u{|y~|uy~}~}u{}y~rx~vx~m{}y" "~u{}y~|e{|y~}k{}~}dy~|a{|y~|i{}y~|{}y~| y{}y~@{}~}Py~|N{}y~0{}y~`{|y~ e{}y~ !{|y~d{}~}dy~} [y~}v{}~}ju~}jy~| n" "{}y~ N{|y~|v{}~}j{}y~}y~i{|y~}e{|y~|gx~}t{}y~}o{|}q~|p{|y~|ry~}r{|y~|w{}y~vy~}r{}y~}t{}y~}S{}t~Ly~|M{}t~|1{~|g" "{}y~Ly~|v{|y~|i{}~}hy~}L{|y~|t{|y~|g{|~} {{|y~|t{|y~|T{|~|wy~f{}~|ay~ey|y~7{}t~y{}~|5{|~}h{|~}vy~U{|~}r{}~|p{|~" "}r{|~}my~ty~O{}y~}y~g{}y~}y~g{}y~}y~g{}y~}y~g{}y~}y~g{|y~}y~jy~}yy~}i{}y~}s{|~|p{|y~|e{|y~|e{|y~|e{|y~|a{|y~|e{" "|y~|e{|y~|e{|y~|k{|y~|t{|x~}q{|v~ty~}p{}y~}t{}y~}p{}y~}t{}y~}p{}y~}t{}y~}p{}y~}t{}y~}p{}y~}t{}y~}V{}y~}t{}x~q{}" "y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|o{}y~u{}y~|n{|y~|e{|y~|v{}~} A{|}|ey|e{}|wy|Py~}y|y~} ?{}~}h{}y~ p" "{}r~|l{}r~|l{}r~|l{}r~|l{}r~|h{}~}k{}y~qy~}1{|~}dy}P{}v~|is~|p{|r~}s~}nu~|h{|w}|k{|y}sy}|jx}|j{|y}t{|y}o{}y~| " "H{|y~|Gy~}g{|y~y{|~}h{|~}x{|~}l{}r~}s{|~}w{}~}w{}~|ly~}_{|y~dy~|d{}~}h{|y~|~y}~}|g{}~| o{}~}k{|y~|uy~}i{|y~|a{}" "y~|e{|y~}j{|~}{}y~ky~|dy~}]{|y~}m{}y~tx~ny~}u{|y~|,{|X{|X{|y~|o{}y~|q{}y~my~}|y~|l{|y~|ty~}o{|x~p{|r{|y~|s{|x~o" "{|y~|e{|y~|g{|x~p{|q{|y~|ry~}k{|y~|e{|y~|j{|y~|x{}y~}j{|y~|i{|y~|y~|uy~|y~}s{|y~|y~}uy~}q{|x~r{}y~|p{|y~|u{}y~|" "q{|x~r{}y~|q{|y~|u{}y~|ny~}_y~}k{}y~r{|y~|py~}s{|y~}ty~}v{|y~|y~uy~}r{|y~}x{}y~|ly~}w{|y~}e{|x~j{}~}d{}~}a{|y~|" "j{}y~|x{}y~| {{}y~@{}~}Py~|N{}y~0{}y~`{|y~ e{}y~ !{}y~d{}~}d{}~} \\{|y~u{}y~j{}x|}y~|kx~| o{|y~| O{}~}u{|y~jy" "~}|y~|i{|y~}f{|y~|h{}y~|rx~|q{|w~y}y~y}x~}q{|y~|ry~}r{|y~|w{}y~vy~}s{|x~r{}y~|U{}y~|y~}x~My~|N{}y~|y~|x~|2{~|gy" "~}g{|p{}m{}y~v{}~}h{}~}h{}~}L{~}xy|}y|x{}~l{|}u~ {{~}p{}~T{|~|wy~f{}~|b{}~}g{}w~|7{}t~y{}~|5{|~}h{}~|v{}~|V{|~}" "s{|~}o{|~}ry~n{|}~|u{}~}Oy~}|y~|hy~}|y~|hy~}|y~|hy~}|y~|hy~}|y~|hy~}|y~|l{}y~|yy~}j{|x~p{|p{|y~|e{|y~|e{|y~|e{|" "y~|a{|y~|e{|y~|e{|y~|e{|y~|k{|y~|rx~q{|y~|y~}uy~}q{|x~r{}y~|r{|x~r{}y~|r{|x~r{}y~|r{|x~r{}y~|r{|x~r{}y~|q{|}q{|" "}p{|x~s{}x~|r{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|ny~}w{|y~}m{|s~}|l{|y~u{|y~ 8{|w{|y~} _{} G{}y~ r{|" "x~|w{|}y~|o{|x~|w{|}y~|o{|x~|w{|}y~|o{|x~|w{|}y~|o{|x~|w{|}y~|i{}~|jy~|s{|y~|1y~}d{~|Q{|t~is~|p{}i~}os~j{|s~|m{" "|y~sy~|jw~j{|y~|u{}y~p{|y~| Gx~Fy~}g{|y~y{|~}h{}~}x{}~}m{|y~}{|~x{|}s{|~}w{}~}x{|~}ky~}_{|y~e{|y~c{|y~f{}x~}|e" "{}~| oy~|k{}y~t{}y~i{|y~|a{|y~|dy~|jy~|{}y~ky~|e{|y~|]{}y~|m{}y~ty~}o{|y~|ty~}/{|}~}Xy~}|[{|y~|p{}y~|o{}y~o{|y~" "|{y~}l{|y~|ty~}o{}y~|f{|y~|r{}y~|p{|y~|e{|y~|g{}y~|e{|y~|ry~}k{|y~|e{|y~|j{|y~|y{}y~}i{|y~|i{|y~|}~}v{|y~{y~}s{" "|y~|}y~uy~}q{}y~|qx~p{|y~|u{}y~|q{}y~|qx~q{|y~|u{}y~|o{|y~|_y~}k{}y~r{|y~|p{}y~s{}y~|t{}y~v{|~}{y~|w{|y~|q{}y~|" "{|y~}k{|y~|xx~dx~|j{}~}d{|y~a{|y~|k{}y~|v{}y~|9{|y}x~y}j{}y~y{}x~}|h{|}x~y}|j{}x~}|{}~}k{|}x~}|j{|s~|i{}x~}|{}~" "}n{}y~y{}x~}|h{|y~d{|y~h{}y~u{|y~}j{|y~m{}y~y{}x~}w{|}y~}|p{}y~y{}x~}|i{|}x~}|k{}y~y{}x~}|i{}x~}|{}~}k{}y~y{}x~" "k{|}w~y}|k{|r~l{}~}t{}~}oy~}s{}y~r{}~}v{}y~}v{}~}r{|y~|u{|y~|oy~}s{}y~n{}p~h{}y~d{}~}d{}~} t{}x~}|y{|~}n{|y~u{}" "~}e{}y~k{|w~y}|g{|}w~y}l{}y~y{}x~}|n{}~}|s{}y~iy~}i{}~}t{}~}p{|y~|r{}y~n{|y}y{}y~}lm~p{}y~x{|y~x{|y~|k{}w~}|j{|" "}q~|q{}n~ny~|ty~|l{|y~|{y~}h{|y~}g{|y~|hy~}q{|y~}qx~}y{}y~y{|x~|r{|y~|ry~}r{|y~|w{}y~vy~}s{}y~|qx~V{|y~|{y~y|y~" "}Ny~|O{|y~|{y~|{y~}Ny~}e{|}w~}|jy~}h{|y~r{}~}my~|x{|y~|h{}~}h{|y~}Ny}x{}u~|yy}n{}y~w}y~ y}y{}v~}|xy}T{~}x{|~}f{" "}~|c{|~}fx|y}|Q{}~}t{}~}ns~y{}~|5{|~}h{}~|v{}~|V{|~}sy~n{|~}s{}~|p{}x~}u{|y~f{|y~|h{|y~|{y~}i{|y~|{y~}i{|y~|{y~" "}i{|y~|{y~}i{|y~|{y~}i{|y~|{y~}ly~}xy~}j{}y~|d{|y~|e{|y~|e{|y~|e{|y~|a{|y~|e{|y~|e{|y~|e{|y~|k{|y~|r{|y~}r{|y~|" "}y~uy~}q{}y~|qx~r{}y~|qx~r{}y~|qx~r{}y~|qx~r{}y~|qx~qy~}s{|y~}q{}y~|t{}~}x~r{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|q{}" "y~r{|y~|n{|y~|xx~l{|q~}m{}y~w{|w~l{|y}x~y}i{|y}x~y}i{|y}x~y}i{|y}x~y}i{|y}x~y}i{|y}x~y}n{|y}x~y}w{|}x~}|l{|}x~y" "}|j{|}x~}|h{|}x~}|h{|}x~}|h{|}x~}|g{|y~d{|y~d{|y~d{|y~e{|}v~|l{}y~y{}x~}|i{|}x~}|h{|}x~}|h{|}x~}|h{|}x~}|h{|}x~" "}|g{|x~f{|}x~}|{}~|o{}~}t{}~}n{}~}t{}~}n{}~}t{}~}n{}~}t{}~}oy~}s{}y~n{}y~y{}x~}|my~}s{}y~;y~}xy~|y{|y~|py~}s{|y" "~|py~}s{|y~|py~}s{|y~|py~}s{|y~|j{}~|j{}y~sy~}1y~}d{|~Q{|s~}j{}t~o{|i~}p{}s~}kx~}y|}x~m{|y~sy~|k{|w~|jy~}uy~}py" "~} Fy~}Fy~}g{|y~y{|~}m{|k~}q{}y~y{|~n{|~}w{}~|xy~j{}y~|`{|y~e{}~}by~|g{|x~}d{}~| p{|y~jy~}t{}y~i{|y~|a{|y~|e{|" "y~|k{}~}y{}y~ky~|{|g{}y~\\x~l{|y~|v{|y~|o{|y~|tx~i{}y~d{}y~a{|}w~}Xv~}|^x~p{|y~l{}~}p{}y~y{|y~|m{|y~|ty~}ox~e{|" "y~|qy~}p{|y~|e{|y~|gx~d{|y~|ry~}k{|y~|e{|y~|j{|y~|{}y~}h{|y~|i{|y~y|y~v{}~}{y~}s{|y~|{y~}vy~}qx~p{}y~|q{|y~|u{|" "y~|qx~p{}y~|r{|y~|u{}y~|ny~}_y~}k{}y~r{|y~|p{|y~|ty~}s{}y~|w{}~|{}~|w{|y~|py~}{x~i{}y~y{}y~|e{}y~|i{}~}cy~|b{|y" "~|l{}y~|t{}y~|;{|r~|l{}y~|t~|j{}s~|m{|t~|}~}l{}s~|l{|s~|k{|t~|}~}n{}y~|t~|i{|y~d{|y~h{}y~v{}y~}i{|y~m{}y~|t~y{}" "u~}q{}y~|t~|l{|s~}l{}y~|t~|l{|t~|}~}k{}y~|v~l{|r~k{|s~}l{}~}t{}~}o{}y~sy~}r{|y~v{}x~vy~}q{}y~|w{|y~}n{}y~sy~}n{" "|p~h{}y~d{}~}d{}~} v{|t~|{}~|n{|y~u{}~}e{|y~|k{|t~|j{}s~|m{}y~|t~|o{}x~|ty~}ix~i{}~}t{}~}py~}q{|y~|p{|y~}{}v~|n" "m~p{}y~x{|y~x{|y~|ls~|l{|o~|q{}n~o{|y~|t{}~}l{}y~y{}y~|h{}y~}h{|y~|i{|y~|p{}y~r{}y~|x{}y~x{|x~r{|y~|ry~}r{|y~|w" "{}y~vy~}sx~p{}y~|p{}b{}|yy~|{|}b{}|hy~|i{|}s{}|ly|yy~|y{}My~}g{|r~k{|y~|gx~|}x~}|}y~|m{}y~xy~}g{}~}g{}x~|Q{|~|y" "y~}|yx|y{|~|p{|~}w{|y~gy|w{|<{|~|y{}~}x|y~|y{|~|U{}y~y}y~e{}~|d{|y~a{}~Q{}~}t{}~}n{}t~y{}~|5{|~}h{}~|v{}~|m{|v{" "|k{|~}t{}~|n{|~}t{|~}ox|}y~v{}~|f{|y~|h{}y~y{|y~|j{}y~y{|y~|j{}y~y{|y~|j{}y~y{|y~|j{}y~y{|y~|j{}y~y{}y~m{|y~|xy" "~}jx~c{|y~|e{|y~|e{|y~|e{|y~|a{|y~|e{|y~|e{|y~|e{|y~|k{|y~|qx~r{|y~|{y~}vy~}qx~p{}y~|sx~p{}y~|sx~p{}y~|sx~p{}y~" "|sx~p{}y~|r{|y~}u{|x~px~t{}~}{}y~|s{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|m{}y~y{}y~|l{|y~v|}x~}n{}y~x{}y~|" "k{|r~|l{|r~|l{|r~|l{|r~|l{|r~|l{|r~|q{|r~|{}s~n{}s~|l{}s~|k{}s~|k{}s~|k{}s~|i{|y~d{|y~d{|y~d{|y~g{|r~l{}y~|t~|l" "{|s~}k{|s~}k{|s~}k{|s~}k{|s~}h{|x~h{|q~|n{}~}t{}~}n{}~}t{}~}n{}~}t{}~}n{}~}t{}~}o{}y~sy~}n{}y~|t~|n{}y~sy~}<{}~" "}wy~|x{|y~q{}~}q{|y~q{}~}{~}w{|~y|y~q{}~}t{|~y|y~q{}~}q{|y~j{}~|j{|y~|u{|y~|<q|}y~w|p{|y}uy}Qq~}k{|u~}o{|i~|q{|" "q~}m{}y~uy~}n{|y~sy~|k{}w~|j{}y~v{|y~|q{|y~ H{}o~My~}fy|xy|m{|k~}q{}~}y{|~n{|y~wy~|y{}~|ix~_y|ey~|by~}i{|}~}~}" "y~}f{}~| p{|~}jy~}t{|y~|j{|y~|a{}y~f{|}y~}k{|y~x{}y~kt~}|ky~}{|w~}|e{|y~|kx~|x{|y~}n{|y~|tx~i{}y~d{}y~d{|}v~}|q" "k|p{|}w~}|a{}y~|p{}~|w{|}y~}|{y|xy~|qy~}xy~}m{|y~|u{|y~|p{|y~}e{|y~|qx~p{|y~|e{|y~|h{|y~}d{|y~|ry~}k{|y~|e{|y~|" "j{|y~|}y~}g{|y~|i{|y~|{y~|wy~|{y~}s{|y~|{}y~vy~}r{|y~}p{|y~|q{|y~|u{}y~|r{|y~}p{|y~|r{|y~|u{}y~mx~}`y~}k{}y~r{|" "y~|oy~}u{|y~|s{|y~|wy~|{|~}w{}y~o{|v~|hy~}|y~}e{}y~}h{}~}c{}~}b{|y~|m{}y~|r{|y~|<{|}y|x{|}y~l{}w~|y{|x~|lx~}|yy" "|}|mx~|y{|}x~}mx~y|y{|x~iy~|h{|x~|y{|}x~}n{}w~|y{|x~i{|y~d{|y~h{}y~w{}y~|h{|y~m{}w~|y{|y~}|~}|{|}y~|r{}w~|y{|x~" "lx~|y{|}y~}m{}w~|y{|x~|mx~|y{|}x~}k{}w~w|ly~}|xy|}i{}y~g{}~}t{}~}o{|y~|u{|y~|r{|y~|ww~vy~|px~wx~m{|y~|u{|y~|f{|" "y~}h{}y~d{}~}d{}~}6{|}x~|x{}x~|o{|y~}|{|}y~{y~m{|y~v{|y~|dy~|l{}~}x{|x~|l{}y~}|yy|}|m{}w~|y{|x~n{|}~}u{|y~|j{|x" "~|j{}~}t{}~}q{|y~|py~}q{|x~y|y~y|x~ny|y~}w|}y~}|p{}y~x{|y~x{|y~|mx~|y{|x~|n{|x~|x{}x~y|pu|y~}v|o{|y~s{}y~ly~}xy" "~}g{}y~|i{|y~|i{}y~o{}y~|sx~w{}y~w{}y~|s{|y~|ry~}r{|y~|w{}y~w{|y~}t{|y~}p{|y~|qy~}_y~|`{|y~|iy~|j{|y~}u{|y~|iy~" "|Jy~}h{|x~y|~|{|}k{|y~|fp~|ky~}{|y~f{}~}h{}~y}y~}|Sy}y{}~}qy}p{|~}w{|y~h{|~|x{}~<y}x{}~}x{|~}xy}T{|}y~}d{}~|e{|" "~}`{}~|R{}~}t{}~}n{}t~y{}~|5{|~}h{|~}vy~l{|~|xy}l{|~}u{|~}m{|~}ty~|k{}~|x{|~}e{|y~|hy~}xy~}jy~}xy~}jy~}xy~}jy~}" "xy~}jy~}xy~}jy~}xy~|n{}y~wy~}k{|y~}c{|y~|e{|y~|e{|y~|e{|y~|a{|y~|e{|y~|e{|y~|e{|y~|k{|y~|q{}y~r{|y~|{}y~vy~}r{|" "y~}p{|y~|t{|y~}p{|y~|t{|y~}p{|y~|t{|y~}p{|y~|t{|y~}p{|y~|q{|y~}w{|x~p{|y~}u{|~}y{|y~|s{}y~r{|y~|q{}y~r{|y~|q{}y" "~r{|y~|q{}y~r{|y~|ly~}|y~}k{|y~|ux~n{}y~y{|y~|j{|}y|x{|}y~l{|}y|x{|}y~l{|}y|x{|}y~l{|}y|x{|}y~l{|}y|x{|}y~l{|}y" "|x{|}y~q{|}y|x{|}v~|x{|y~}px~}|yy|}|mx~y|y{|x~lx~y|y{|x~lx~y|y{|x~lx~y|y{|x~i{|y~d{|y~d{|y~d{|y~gx~|x{|y~}m{}w~" "|y{|x~lx~|y{|}y~}lx~|y{|}y~}lx~|y{|}y~}lx~|y{|}y~}lx~|y{|}y~}i{|x~hx~|y{|}y~}m{}~}t{}~}n{}~}t{}~}n{}~}t{}~}n{}~" "}t{}~}o{|y~|u{|y~|n{}w~|y{|x~|o{|y~|u{|y~|={|y~vy~|w{}~|s{|y~o{}~|s{|y~{}y~}y{|y~}{}~|s{|y~t{|y~}{}~|s{|y~o{}~|" "ky~|iy~}u{}y~;k~}qw~u{~|R{}p~|k{}w~}mi~q{|o~|ny~|u{}y~n{|y~sy~|ky~}y~}j{|y~|w{}y~p{}~} Hx}y~t}|My~}M{|y~x{|~}l" "{}y~y{|~m{}~}y{}~}y{|~}i{|w~I{|y~|b{}y~j{}~}|{~}{|y~|h{}~| p{}~|jy~}t{|y~|j{|y~|b{|y~}j{}u~}jy~|x{}y~kr~}ly~y}t" "~}f{}y~i{}t~|ly~}u{|x~|j{}y~d{}y~f{}v~}|nk~}n{|}w~}|e{}y~|p{|~}w{|u~y}~x{|~}r{|y~|x{}y~m{|y~|xy|}y~}o{|y~|e{|y~" "|q{}y~p{|y~r|m{|y~s|o{|y~|d{|y~q|y~}k{|y~|e{|y~|j{|v~}f{|y~|i{|y~|{}~}x{|~}yy~}s{|y~|yy~}wy~}r{|y~|p{|y~}q{|y~|" "ux~q{|y~|p{|y~}r{|y~|v{|y~}m{|v~}y|ey~}k{}y~r{|y~|o{}y~u{}y~qy~}x{|y~y{|y~wy~}n{}x~}g{|v~e{|y~}g{}~}c{|y~b{|y~|" " o{}~}m{}x~ux~m{}y~|f{}y~u{}y~}n{}y~|uy~}jy~|h{}y~u{}y~}n{}x~v{|y~|j{|y~d{|y~h{}y~x{}y~|g{|y~m{}x~v{}x~|vy~}r{}" "x~v{|y~|n{}y~|v{}y~|n{}x~ux~n{}y~u{}y~}k{}x~h{|y~a{}y~g{}~}t{}~}ny~}u{}y~py~|x{|y~}~|x{|y~o{|y~}y{}y~|l{}~}u{}~" "}ex~g{}y~d{}~}d{}~}6y~y}y~|{}y~}y~}p{}y~vy~}y~m{|y~x{|}x~c{}~}m{|y~u{}y~l{}~}e{}x~v{|y~|n{|y~u{}~}i{}x~}j{}~}t{" "}~}q{}y~o{}y~q{}y~|{|y~y{|y~}my~|w{|y~|o{}y~x{|y~x{|y~|n{}y~ux~n{}y~u{}y~|iy~|j{|n~m{|y~|x{}y~f{}y~|j{|y~|i{}y~" "o{|y~|t{|y~}w{}y~w{|y~}s{|y~|ry~}qy~}w{}y~w{|y~|t{|y~|{r~y|y~}rx~|_y~|_{}y~|jy~|k{|x~s{}y~|jy~|Jx|h{}y~|y{~|h{|" "y~|f{|y~}|y{}y~|n{|u~{u~|j{}~}i{|~}y{|}y~}T{~|yy~p{|~p{|~}wx~i{|y~|y{}y~ok|X{~|x{}~}x{|~}x{|~?k~}m{}~}_y~|R{}~}" "t{}~}mt~y{}~|ix|J{|~}gy~|x{}~}l{|y~|y{}~}m{|~}uy~|u{|t{|~}u{}~}j{}~|xy~cy|h{|y~|x{}y~k{|y~|x{}y~k{|y~|x{}y~k{|y" "~|x{}y~k{|y~|x{}y~k{|y~|x{}y~ny~}wy~}r|t{|y~|c{|y~r|m{|y~r|m{|y~r|m{|y~r|i{|y~|e{|y~|e{|y~|e{|y~|k{|y~|q{}y~|s{" "|y~|yy~}wy~}r{|y~|p{|y~}t{|y~|p{|y~}t{|y~|p{|y~}t{|y~|p{|y~}t{|y~|p{|y~}p{|y~}y{|x~o{|y~|v{|y~wy~}s{}y~r{|y~|q{" "}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|l{|v~j{|y~|u{}y~|o{}y~y{|y~`{}~}d{}~}d{}~}d{}~}d{}~}d{}~}i{}x~u{|y~|r{}y~|f{}y~|" "uy~}n{}y~|uy~}n{}y~|uy~}n{}y~|uy~}j{|y~d{|y~d{|y~d{|y~h{}y~|v{|y~|n{}x~v{|y~|n{}y~|v{}y~|n{}y~|v{}y~|n{}y~|v{}y" "~|n{}y~|v{}y~|n{}y~|v{}y~|ix|i{}y~|w{|x~|n{}~}t{}~}n{}~}t{}~}n{}~}t{}~}n{}~}t{}~}n{}~}u{}~}m{}x~ux~n{}~}u{}~}<{" "|~}vy~|w{|~}s{|~}o{|~}s{|~}y{}y~}|y~}y{|~}s{|~}u{|y~}y{|~}s{|~}o{|~}ky~|i{}y~uy~};k~}q{|{y~|w{}~R{|n~o{}o~}|r{|" "k~}qm~|oy~|u{|y~n{|y~sy~|l{|y~|}y~iy~}wy~}p{}~} F{|y~|Fy~}M{}~}x{}~}l{|y~}y|~lu~xy~|xx}|q{|y~|x~ty|S{|y~a{}y~j" "{}|x{~}x{}|h{}~| py~j{|y~|t{|y~|j{|y~|bx~i{}v~}|k{}~}w{}y~k{}y|x{|x~}mw~}|y{|x~|gy~}h{}u~}l{}y~|v{}x~|jx|dx|i{|" "}w~}|kk~}l{|}v~}|i{}y~|o{}~|wy~}x{}x~wy~rx~w{|y~|n{|q~|n{|y~|e{|y~|q{}y~|q{|p~}n{|q~o{|y~|tu|q{|m~}k{|y~|e{|y~|" "j{|v~e{|y~|i{|y~|yy~xy~|yy~}s{|y~|y{}y~|xy~}r{|y~|oy~}q{|y~|w{|x~}q{|y~|oy~}r{|y~v|}y~}k{|}t~}gy~}k{}y~r{|y~|o{" "|y~}vy~}q{}y~x{|~}xy~|y{|y~|n{|x~e{}x~|ex~f{}~}by~|c{|y~| o{|y~m{}y~|u{|y~|ny~}ey~}u{|y~}ny~|t{}y~jy~|hy~}u{|y~" "}n{}y~|u{}~}j{|y~d{|y~h{}y~y{}y~|f{|y~m{}y~|v{|x~u{}y~r{}y~|u{}~}ny~}ty~}n{}y~|u{|y~|oy~}u{|y~}k{}y~|h{|y~a{}y~" "g{}~}t{}~}n{}y~uy~}p{}~}x{}~}|~}x{}~}n{|y~y|y~}k{|y~uy~|f{}y~f{}~}d{}~}d{}y~7{}~x{|y~|~}x{}~py~}v{}x~}m{|y~{|v~" "|i{}y~}|{}~}my~|ty~}m{}~}e{}y~|u{}~}my~|vy~|j{|y~}y~j{}~}t{}~}qx~o{|y~|ry~}y{|y~x{}y~my~|w{|y~|o{}y~x{|y~x{|y~|" "ny~|u{|y~|oy~}ty~}iy~|j{|n~mx~w{|y~|g{|y~}j{|y~|i{}y~o{|y~|t{|y~|w{}y~vy~}s{|y~|ry~}qx~w{}y~w{}y~|t{|y~|{r~|{y~" "}sx~|^y~|^{}y~|ky~|l{|x~q{}y~|ky~|5{|y~|x{~|h{|y~|f{}~}v{|~}mw}v~w}|j{}~}i{}~|w{|y~}U{~y{|y~p{|~ox~y}~}y~j{}y~|" "y{}y~nk~}Y{~w{}~}y{|}~|x{|~?k~}n{}y~v|ix}|}y~}Q{}~}t{}~}m{|u~y{}~|iy~}Ly|}~}y|i{|y~x}y~j{}y~|y{}y~n{|~}v{|~}v{|" "y~}u{|~}v{|y~y{}w~}wx|{|}y~x{}~|uy~}Wx~w{|y~|lx~w{|y~|lx~w{|y~|lx~w{|y~|lx~w{|y~|l{}y~w{|y~|p{}y~|wo~t{|y~|c{|p" "~}n{|p~}n{|p~}n{|p~}j{|y~|e{|y~|e{|y~|e{|y~|mq~u{}y~|s{|y~|y{}y~|xy~}r{|y~|oy~}t{|y~|oy~}t{|y~|oy~}t{|y~|oy~}t{" "|y~|oy~}o{|y~}|x~n{|y~|vy~|wy~}s{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|k{}x~|j{|y~|u{|y~|o{}y~y{|y~|a{|y~d{" "|y~d{|y~d{|y~d{|y~d{|y~i{|y~|t{}~}ry~}ey~|t{}y~ny~|t{}y~ny~|t{}y~ny~|t{}y~j{|y~d{|y~d{|y~d{|y~hy~}ty~}n{}y~|u{}" "~}ny~}ty~}ny~}ty~}ny~}ty~}ny~}ty~}ny~}ty~}Ty~}w{|~}y~}n{}~}t{}~}n{}~}t{}~}n{}~}t{}~}n{}~}t{}~}n{|y~uy~|m{}y~|u{" "|y~|o{|y~uy~|<{}~u|y~}w|{y~s{}~n|{y~s{}~|x{}w~}wy~s{}~|v{|y~}wy~s{}~|vy~}vy~ky~|i{|y~|w{|y~|4{|y~}i{}~}w{~}Rm~}" "qk~|r{}l~q{|m~|p{|y~sy~|o{|y~sy~|l{}y~{|y~|j{}y~x{|y~|p{}i~ V{|y~|F{}~}M{}~|x{}~|k{}v~}|m{|y}|x{}~}y{|v~}s{|y~" "|{|x~v{|y~S{}y~a{|y~e{~}jt|y~}u| w{|~}j{|y~|t{|y~|j{|y~|cx~|hw|}y~|m{|y~v{}y~cx~|nx~}ux~h{|y~|j{|y~}|{y|x~m{|x~" "|y{|}w~|={}w~}|E{|}v~|l{|y~|ny~w{}~}v{}y~wy~s{|y~|vy~}n{|q~}|o{|y~|e{|y~|q{}y~p{|p~}n{|q~o{|y~|u{|u~}r{|m~}k{|y" "~|e{|y~|j{|y~}x~f{|y~|i{|y~|y{}~|{|y~xy~}s{|y~|xy~}xy~}r{|y~|oy~}q{|q~}p{|y~|oy~}r{|r~}h{|y}u~|iy~}k{}y~r{|y~|n" "x~w{|y~|q{}y~x{}~|x{}~|y{|y~|nw~|ey~}e{}y~|f{}~}b{}~}c{|y~| v{|y}t~m{}y~sy~|o{|y~|f{|y~|ty~}o{|y~|t{|y~jy~|i{|y" "~|ty~}n{}y~t{}~}j{|y~d{|y~h{}y~{x~|e{|y~m{}y~ty~}u{|y~r{}y~t{}~}o{|y~|t{}y~n{}y~sy~|p{|y~|ty~}k{}y~g{|y~}b{}y~g" "{}~}t{}~}n{|y~|w{|y~o{|y~x{}~y|y~xy~}m{}w~}iy~|w{}y~f{}y~|g{|y~|d{}~}d{|y~}jy}y~}|t{|}X{~}w{|y~}v{~|r{|y~|v{|x~" "|m{|y~{|v~}|ku~|y~}n{|y~|t{}y~m{|y~}f{}y~t{}~}m{}y~w{}y~i{}y~{y~}k{}~}t{}~}qy~}ny~}s{|y~|y{|y~x{|y~my~|w{|y~|o{" "}y~x{|y~x{|y~|o{|y~sy~|p{|y~|t{}y~iy~|j{|y~s|}y~n{|y~}vy~}gx~|j{|y~|i{}y~o{|y~|t{|y~|w{}y~vy~}s{|y~|ry~}q{}y~|x" "{}y~x{|y~}s{|y~|{r|yy~}tx~}l|ly~|mk|x~|ly~|m{|x~o|x~|ly~|5{}y~w{~|j{}r~}ky~|uy~i{|x~}e{}~}i{}~}v{|y~V{|~y{|y~o{" "~|o{}x~|{y}k{}y~|y{}~}mk~}Z{|~w{}u~|v{~|@t|y~}t|n{}t~i{|}x~y}P{}~}t{}~}k{|}x~y{}~|iy~}Lt~|i{|}x~}h{|y~|y{}y~|rt" "~|yy~ux~}wt~|y{}~|{|~}y|}y~x{}v~}|y{|y~u{}y~}m{|y}i{|y~|vy~}m{|y~|vy~}m{|y~|vy~}m{|y~|vy~}m{|y~|vy~}ly~|vy~}py~" "}vo~t{|y~|c{|p~}n{|p~}n{|p~}n{|p~}j{|y~|e{|y~|e{|y~|e{|y~|m{}s~}u{}y~|s{|y~|xy~}xy~}r{|y~|oy~}t{|y~|oy~}t{|y~|o" "y~}t{|y~|oy~}t{|y~|oy~}n{|v~m{|y~|wy~|vy~}s{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|jy~}i{|y~|u{}y~|o{}y~xx~|" "i{|y}t~k{|y}t~k{|y}t~k{|y}t~k{|y}t~k{|y}t~p{|y}t~s{|y~s{|y~|f{|y~|t{|y~o{|y~|t{|y~o{|y~|t{|y~o{|y~|t{|y~j{|y~d{" "|y~d{|y~d{|y~i{|y~|t{}~}n{}y~t{}~}o{|y~|t{}y~o{|y~|t{}y~o{|y~|t{}y~o{|y~|t{}y~o{|y~|t{}y~pk~}q{|y~|w{~}{}y~n{}~" "}t{}~}n{}~}t{}~}n{}~}t{}~}n{}~}t{}~}my~|w{}y~l{}y~sy~|ny~|w{}y~;{}~|}p~{y~s{}~|}p~{y~s{}~|w{}x~vy~s{}~|w{|y~}vy" "~s{}~|vy~}vy~ky~|h{}~}w{}y~3y~}h{|y~x{|~|S{|l~r{}k~}qm~|p{}o~}o{|y~sy~|o{|y~sy~|ly~}yy~}j{|y~|y{|y~o{}i~ X{|y}" "y~u}K{}~}My~|xy~i{|}u~}i{|y~y{|y~|{|y~|t{}~}x{|x~w{|y~S{}y~a{|y~|f{~}jk~} x{}~}iy~}t{|y~|j{|y~|d{}y~|b{}y~|ny~|" "v{}y~c{|y~}nx~|u{}y~|ix~j{|y~|v{|y~}m{|t~y}y~|=x~}?{|x~}l{}y~m{~}wy~|v{|y~w{}~s{}y~u{}y~n{|y~|v{|}y~|p{|y~|e{|y" "~|q{}y~p{|y~|e{|y~|h{|y~|u{|u~}r{|y~|ry~}k{|y~|e{|y~|j{|y~|}x~g{|y~|i{|y~|y{|y~{}~}xy~}s{|y~|x{|y~|yy~}r{|y~|p{" "|y~}q{|s~}|o{|y~|p{|y~}r{|q~|ey|w~iy~}k{}y~r{|y~|n{|y~|x{}y~p{|y~|yy~|x{}~}y{}y~n{}v~ey~}f{}y~|e{}~}b{|~}c{|y~|" " w{}q~m{}y~sy~}o{|y~e{|y~s{}~}o{|n~jy~|i{|y~s{}~}n{}y~t{}~}j{|y~d{|y~h{}v~c{|y~m{}y~ty~|u{|y~r{}y~t{}~}o{|y~s{}" "y~n{}y~sy~}p{|y~s{}~}k{}y~f{}w~}|f{}y~g{}~}t{}~}m{}~}w{}~}o{|y~|yy~yy~xy~|lw~h{}y~wy~}g{}y~|i{}w~}c{}~}c{|w~}o{" "|s~}w|}~}X{~|vy~|vy}r{|y~tx~l{|y~w{|}x~|m{}y~x{}x~|n{|y~s{}y~l{|}v~j{}y~t{}~}m{|y~|xy~}j{|y~|{}y~k{}~}t{}~}qy~}" "vy~|vy~}s{|y~x{|y~x{|y~|ny~|w{|y~|o{}y~x{|y~x{|y~|o{|y~sy~}p{|y~s{}y~iy~|j{|y~s{}y~n{}y~u{}y~h{}y~|i{|y~|i{}y~|" "p{}y~s{|y~}w{}y~w{|y~}s{|y~|ry~}px~x{}y~x{}y~|s{|y~|p{|y~}u{}h~ly~|m{}h~ly~|mg~ly~|J{}~}i{}y~w{~|j{}r~}ky~ty~|i" "x~d{}~}i{}y~|vy~|W{|~y{|y~o{~|X{}y~xy~}^{|~}Z{|~w{}~}|}~}u{~|9{}~| v{}~}t{}~}hy~y{}~|iy~} s{|y~}y{}y~|st|y{}~|v" "{}~|~}wt|y{|~}sy~|wx|v{}~|vy}|~}m{|y~i{}y~u{}y~m{}y~u{}y~m{}y~u{}y~m{}y~u{}y~m{}y~u{}y~m{}y~u{}y~q{|y~|vy~}k{|y" "~|c{|y~|e{|y~|e{|y~|e{|y~|a{|y~|e{|y~|e{|y~|e{|y~|k{|y~|q{}y~|s{|y~|x{|y~|yy~}r{|y~|p{|y~}t{|y~|p{|y~}t{|y~|p{|" "y~}t{|y~|p{|y~}t{|y~|p{|y~}m{}x~|m{|y~|x{}~|v{|y~}s{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|jy~}i{|y~|ux~n{}y" "~x{|x~}k{}q~l{}q~l{}q~l{}q~l{}q~l{}q~q{}f~s{|y~e{|n~o{|n~o{|n~o{|n~j{|y~d{|y~d{|y~d{|y~i{|y~s{}y~n{}y~t{}~}o{|y" "~s{}y~o{|y~s{}y~o{|y~s{}y~o{|y~s{}y~o{|y~s{}y~pk~}q{|y~wy~y{}y~n{}~}t{}~}n{}~}t{}~}n{}~}t{}~}n{}~}t{}~}m{}y~wy~" "}l{}y~sy~}n{}y~wy~};{}~|}q~}{y~s{}~|}q~}{y~s{}~|x{|w~}wy~s{}~|x{|y~}uy~s{}~|vy~}vy~ky~g{|y~|xy~|4{}y~fy~|yy}R{|" "l~ri~po~|n{}p~n{|y~sy~|o{|y~sy~|m{|y~|y{}y~iy~}y{}~}o{}~} H{}r~}K{}~}N{|y~x{|y~f{|~}w~j{}~|y{}~}x{|y~ty~|w{|x~" "x{}~}S{}y~a{|y~|f{|ik~}T{}u~|Ly~|iy~}t{|y~|j{|y~|e{}y~|`y~}o{}~}u{}y~by~}nx~t{|y~|j{|y~}jy~}t{}y~k{}x~}|{}y~<v~" "}|hk|g{|}w~}l{}~}n{|~}wy~ty~wy~sy~}t|y~|o{|y~|t{}y~p{|y~}e{|y~|qx~p{|y~|e{|y~|h{|y~}py~}r{|y~|ry~}k{|y~|e{|y~|j" "{|y~|{}y~}h{|y~|i{|y~|xy~|y~|xy~}s{|y~|wy~}yy~}r{|y~}p{|y~|q{|y~w|k{|y~}p{|y~|r{|y~|w{}x~bx~|jy~}k{}y~r{|y~|my~" "}xy~}oy~}{|y~w{|y~yy~}o{|y~}{y~}fy~}g{|y~}d{}~}ay~c{|y~| x{}y~}|w{|y~m{}y~sy~}o{|y~e{}y~s{}~}o{|n~jy~|i{}y~s{}~" "}n{}y~t{}~}j{|y~d{|y~h{}w~}c{|y~m{}y~ty~|u{|y~r{}y~t{}~}o{}y~s{}y~n{}y~sy~}p{}y~s{}~}k{}y~e{|u~}h{}y~g{}~}t{}~}" "m{|y~wy~|ny~}{|~}y{}~|{|y~k{}y~}h{|y~|y{|y~|h{|y~}h{}w~|c{}~}c{|}x~}oy~}x|}r~|X{~|v{}~|v{~}r{}y~ty~}l{|y~t{}y~n" "{|y~|wx~|n{|y~s{}y~l{|u~j{}y~t{}~}ly~}y{|y~|j{}y~y{|y~|l{}~}t{}~}r{|y~}vy~|vy~}s{}y~x{|y~x{|y~|ny~|w{|y~|o{}y~x" "{|y~x{|y~|o{}y~sy~}p{|y~s{}y~iy~|j{|y~|t{}y~ny~}u{|y~|j{|y~}h{|y~|i{|y~}px~ry~}w{}y~w{}y~|s{|y~|ry~}p{|x~|{}y~y" "{}y~}r{|y~}p{|y~|u{|h~ly~|m{}h~ly~|m{}h~ly~|J{}~}i{}y~w{~|h{|y~|fy~|uy~mv}x~v}|Tx~|wy~U{~|yy~|q{|~or}ly~}xy~|^{" "|~}Y{~|x{}~}y{}~}w{|~8{}~| v{}~}t{}~}hy~y{}~| yr}h{}~}y{|y~|k{|~}v{|~y|~}ny~r{}~|p{|~}v{|~{|~}m{|y~iy~}t|y~|ny~" "}t|y~|ny~}t|y~|ny~}t|y~|ny~}t|y~|ny~}t|y~|r{}y~u|y~}k{|y~}c{|y~|e{|y~|e{|y~|e{|y~|a{|y~|e{|y~|e{|y~|e{|y~|k{|y~" "|q{}y~r{|y~|wy~}yy~}r{|y~}p{|y~|t{|y~}p{|y~|t{|y~}p{|y~|t{|y~}p{|y~|t{|y~}p{|y~|n{|w~}m{|y~}y{}~}u{|y~|s{}y~r{|" "y~|q{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|jy~}i{|y~|w{|x~}n{}y~v{}x~|n{}y~}|w{|y~m{}y~}|w{|y~m{}y~}|w{|y~m{}y~}|w{|y~" "m{}y~}|w{|y~m{}y~}|w{|y~r{}y~}|w{|n~s{|y~e{|n~o{|n~o{|n~o{|n~j{|y~d{|y~d{|y~d{|y~i{|y~s{}y~n{}y~t{}~}o{}y~s{}y~" "o{}y~s{}y~o{}y~s{}y~o{}y~s{}y~o{}y~s{}y~pk|p{}y~x{}~|y{}y~n{}~}t{}~}n{}~}t{}~}n{}~}t{}~}n{}~}t{}~}m{|y~|y{|y~|l" "{}y~sy~}n{|y~|y{|y~|;{|~}vy~|w{|~}s{|~}o{|~}s{|~}y{}y~}|y~}y{|~}s{|~}y{}y~}u{|~}s{|~}vy|v{|~}ky~fy~}y{}y~9k~}n{" "}y~y{~|R{}l~ri~p{|q~}lq~m{|y~sy~|o{|y~sy~|m{}y~x{|y~|j{}y~yy~}o{|y~ Ey~}E{|Qj~j{|~y{|y~}l{|~}xy~|wy~u{|y~|v{|x" "~{|y~R{}y~a{|y~K{}~|M{}u~|M{|y~hy~}t{}y~i{|y~|f{}y~|_{}y~o{}n~}ey~}n{}y~t{|y~|j{}y~|jy~}t{|y~|e{}y~;{|}v~}jk~}k" "{|}v~}j{}~}n{|~}wy~ty~wy~t{|o~}o{|y~|t{|y~|px~e{|y~|qy~}p{|y~|e{|y~|gx~py~}r{|y~|ry~}k{|y~|e{|y~|j{|y~|y{}y~}i{" "|y~|i{|y~|x{}w~wy~}s{|y~|w{|y~|{y~}qx~p{}y~|q{|y~|gx~p{}y~|r{|y~|v{|y~}c{|y~}jy~}k{}y~r{|y~|m{}y~y{}y~|o{}y~{|~" "}vy~{|y~|ox~y{|y~|gy~}h{|x~c{}~}a{}~|d{|y~| xy~|u{|y~m{}y~sy~}o{|y~e{|y~s{}~}o{|y~_y~|i{|y~s{}~}n{}y~t{}~}j{|y~" "d{|y~h{}y~|y~}d{|y~m{}y~ty~|u{|y~r{}y~t{}~}o{|y~s{}y~n{}y~sy~}p{|y~s{}~}k{}y~b{|}w~i{}y~g{}~}t{}~}ly~|y{}y~m{}~" "}{}~}y{|~}{}~}l{|w~|h{}~}y{}y~h{|y~}d{}y~|d{}~}d{|y~}|m{}t{|}x~}|V{~}w{|x~v{~|r{|y~ty~|l{|y~t{|y~|o{}y~v{}y~m{|" "y~s{}y~m{}y~}f{}y~t{}~}l{|y~y{}~}iy~|xy~}l{}~}t{}~}qy~}vy~}vy~}s{|y~x{|y~x{|y~|ny~|w{|y~|o{}y~x{|y~x{|y~|o{}y~s" "y~}p{|y~s{}y~iy~|j{|y~|ty~}o{|y~|ty~}k{|x~g{|y~|hx~q{|y~}r{}y~|x{}y~x{|x~r{|y~|ry~}o{}x~}x~}x~}px~p{}y~|t{}y~}]" "y~|^{|x~oy|yy~|y{|o{}y~|q{|x~oy|yy~|y{|M{}~}i{}y~w{~|h{|y~|f{}~}v{}~}n{|n~|S{}x~|{}~}Uy}y{}~}qy}p{|r~ky~}y{|y~}" "_{|~}Yy}x{}~}xy~|xy}8{}~| v{}~}t{}~}hy~y{}~| {{|r~iy~}y{|y~}jy~|w{|~|{|~}o{}~|s{|y~oy~v{|~|{|~}m{|y~j{|o~}o{|o~" "}o{|o~}o{|o~}o{|o~}o{|o~}s{|p~}jx~c{|y~|e{|y~|e{|y~|e{|y~|a{|y~|e{|y~|e{|y~|e{|y~|k{|y~|qx~r{|y~|w{|y~|{y~}qx~p" "{}y~|sx~p{}y~|sx~p{}y~|sx~p{}y~|sx~p{}y~|o{|x~|y~}my~}{}~}t{}y~|s{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|jy~" "}i{|q~}m{}y~u{|x~|oy~|u{|y~my~|u{|y~my~|u{|y~my~|u{|y~my~|u{|y~my~|u{|y~ry~|u{|y~h{|y~e{|y~d{|y~d{|y~d{|y~_{|y~" "d{|y~d{|y~d{|y~i{|y~s{}y~n{}y~t{}~}o{|y~s{}y~o{|y~s{}y~o{|y~s{}y~o{|y~s{}y~o{|y~s{}y~U{|y~y{}~|x{}y~n{}~}t{}~}n" "{}~}t{}~}n{}~}t{}~}n{}~}t{}~}l{}~}y{}y~k{}y~sy~}m{}~}y{}y~:{|y~vy~|w{}~|s{|y~o{}~|s{|y~{|y~}y{|y~}{}~|s{|y~{|y~" "}t{}~|s{|y~o{}~|ky~f{}y~yy~}9k~}n{|y~y|~Q{|u~|y}u~r{}t~y}s~o{|s~}k{|s~|m{|y~sy~|ny~sy~ly~}wy~}j{|y~y|y~|ny~| F" "x~ uj~j{|~x{}y~ly~wy~|wy~u{|y~|u{|x~}~}R{|y~a{}y~K{}~| r{}~}h{}y~t{}y~i{|y~|g{}y~|^{}y~o{}n~}ey~}n{}y~t{|y~|jy~" "}iy~}t{|y~|ey~}8{|}w~}|mk~}n{|}v~}|hx}m{~}wy~|v{|y~x{|~}t{}n~|p{|y~|t{|y~}p{}y~|f{|y~|r{}y~|p{|y~|e{|y~|g{}y~|q" "y~}r{|y~|ry~}k{|y~|e{|y~|j{|y~|x{}y~}j{|y~|i{|y~|x{|x~}wy~}s{|y~|vy~}{y~}q{}y~|qx~p{|y~|g{}y~|qx~q{|y~|u{}y~|d{" "|y~}jy~}k{|y~|s{}y~|m{|y~|{y~}n{}y~{}~}v{}~y|y~|p{}y~|x{}y~gy~}hx~|c{}~}a{|~}d{|y~| y{|y~t{}y~m{}y~sy~|o{|y~|f{" "|y~|ty~}o{|y~|`y~|i{|y~|ty~}n{}y~t{}~}j{|y~d{|y~h{}y~{|x~e{|y~m{}y~ty~|u{|y~r{}y~t{}~}o{|y~|t{}y~n{}y~sy~|p{|y~" "|ty~}k{}y~_{|y~}j{}y~g{}~}ty~}l{}y~yy~}m{|y~{y~|y{|y~{y~}m{|y~y}y~h{|y~yy~|hx~by~}d{}~}d{}y~7{}~|y{|~}|~}x{}~q{" "|y~|v{|y~}l{|y~t{|y~|o{}~}v{}~}m{|y~|t{}y~my~|e{}y~t{}~}ky~|{y~|j{}y~w{}y~l{}~}ty~}qy~}vy~}vy~}s{|y~|y{|y~x{}y~" "my~|w{|y~|o{|y~x{|y~x{|y~|o{}y~sy~|p{|y~|t{}~}iy~|iy~}ty~|o{}y~s{}y~|lx~|g{|y~|h{|y~}rx~px~|y{}y~y{|x~|r{|y~|ry" "~}n{|r~}o{}y~|qx~r{}y~}^y~|_{|x~o{|y~|{y~|{}~}o{}y~|s{|x~o{|y~|{y~|{}~}Ny~}i{}y~w{~|h{|y~|f{|y~}|{|}y~|h{}y~L{|" "v~}T{|~xy~}|yx|x{~|U{}y~y{|y~}`{|~}Y{|~x{}~}x{|y~x{~|8{}~| v{}~}ty~}hy~y{}~| `{|y~}y{|y~|j{}~}v{~}y{|~}p{|y~ry~" "|p{}~|v{~}y{|~}mx~j{}n~|p{}n~|p{}n~|p{}n~|p{}n~|p{}n~s{}p~}j{}y~|d{|y~|e{|y~|e{|y~|e{|y~|a{|y~|e{|y~|e{|y~|e{|y" "~|k{|y~|r{|y~}r{|y~|vy~}{y~}q{}y~|qx~r{}y~|qx~r{}y~|qx~r{}y~|qx~r{}y~|qx~o{|x~y{|y~}n{}y~}~}sx~r{|y~|s{}y~|q{|y" "~|s{}y~|q{|y~|s{}y~|q{|y~|s{}y~|jy~}i{|s~}|l{}y~sy~}p{|y~t{}y~n{|y~t{}y~n{|y~t{}y~n{|y~t{}y~n{|y~t{}y~n{|y~t{}y" "~s{|y~t{}y~|i{|y~|f{|y~|e{|y~|e{|y~|e{|y~|`{|y~d{|y~d{|y~d{|y~i{|y~|t{}y~n{}y~t{}~}o{|y~|t{}y~o{|y~|t{}y~o{|y~|" "t{}y~o{|y~|t{}y~o{|y~|t{}y~ix|j{|y~|}~}w{}y~n{}~}ty~}n{}~}ty~}n{}~}ty~}n{}~}ty~}l{|y~yy~|k{}y~sy~|m{|y~yy~|9{}~" "}wy~|x{|y~q{}~}q{|y~q{}~}{~}w{|~y|y~q{}~}{~}t{|y~q{}~}q{|y~k{|y~f{|y~y|y~|9x|}y~}q|m{}~x}P{}w~}{}{v~|r{|t~y|}u~" "|n{}u~}i{|u~}l{|y~sy~|ny~|u{|y~ly~|w{}y~iy~y}y~m{|y~| G{|y~| ry~|xy~|f{|~x{}y~m{}~|wy~|wy~ty~}t{|w~Q{|y~|b{}y~" "K{}~| ry~|h{|y~|uy~}i{|y~|h{}y~|]x~ns|x~y|e{|y~}n{|y~|u{}y~|k{|y~|iy~}t{}y~e{}y~4{|}w~}|U{|}v~}|Ty~w{}~}v{}y~xy" "~sy~}ry~}p{|y~|t{|y~}p{|x~p{|r{|y~|s{|x~o{|y~|e{|y~|g{|x~qy~}r{|y~|ry~}k{|y~|e{|y~|j{|y~|w{}y~}k{|y~|i{|y~|wx~|" "wy~}s{|y~|v{|y~|y~}q{|x~r{}y~|p{|y~|g{|y~}r{}y~|q{|y~|u{|y~}d{|y~}jy~}k{|y~}sx~ky~}|y~|n{|y~|y~|v{}~y}y~p{|y~}w" "{|y~}hy~}i{}y~|b{}~}a{|y~d{|y~| y{|y~tx~m{}y~|u{|y~|ny~}ey~}u{|y~}ny~}`y~|hy~}u{|y~}n{}y~t{}~}j{|y~d{|y~h{}y~y{" "|x~f{|y~m{}y~ty~|u{|y~r{}y~t{}~}ny~}ty~}n{}y~|u{|y~|oy~}u{|y~}k{}y~^{}~}j{|y~g{}y~u{|y~}l{|y~y|y~|ly~|y~wy~|y~|" "mx~yy~}hy~y|y~hx~a{}y~d{}~}d{}~}6u~y{}y~}y~|py~|v{}y~}l{|y~t{|y~|o{}~}vy~|ly~}ty~}n{|y~|e{}y~t{}~}k{}~y}y~iy~}v" "y~|m{}y~ty~}qx~w{|x~w{|y~|ry~}y{|y~x{}~}my~|w{|y~|o{|y~x{|y~x{|y~n{}y~|u{|y~|oy~}ty~}iy~|i{}y~u{|y~ny~}s{|y~}m{" "}y~|f{|y~|g{}y~|t{}y~|p{|w~y}y~y}x~}q{|y~|ry~}ly}x~y}|n{|x~r{}y~|q{}y~}_y~|`{|x~mx~|y~|}y~|n{}y~|u{|x~mx~|y~|}y" "~|Ny~}i{|y~|x{~|h{|y~|fp~|i{}y~d{}~}d{|x~|S{~}x{}u~|y{}~S{}y~xy~}a{|~}X{~}y{|~|w{}~|{}~7y| u{}y~ty~}hy~y{}~| a{" "|y~}y{|y~|j{|y~v{}~x{|~}p{}~|s{}~|p{|y~v{}~x{|~}n{}y~|jy~}ry~}py~}ry~}py~}ry~}py~}ry~}py~}ry~}py~}ry~}ty~}ty~}j" "{|x~p{|p{|y~|e{|y~|e{|y~|e{|y~|a{|y~|e{|y~|e{|y~|e{|y~|k{|y~|rx~q{|y~|v{|y~|y~}q{|x~r{}y~|r{|x~r{}y~|r{|x~r{}y~" "|r{|x~r{}y~|r{|x~r{}y~|p{|x~w{|y~}o{|w~s{}y~|r{|y~}sx~p{|y~}sx~p{|y~}sx~p{|y~}sx~iy~}i{|y~w|h{}y~s{}~}p{|y~tx~n" "{|y~tx~n{|y~tx~n{|y~tx~n{|y~tx~n{|y~tx~s{|y~tx~}hy~}ey~}dy~}dy~}dy~}`{|y~d{|y~d{|y~d{|y~hy~}ty~}n{}y~t{}~}ny~}t" "y~}ny~}ty~}ny~}ty~}ny~}ty~}ny~}ty~}j{|x~iy~}~}vy~}n{}y~u{|y~}n{}y~u{|y~}n{}y~u{|y~}n{}y~u{|y~}ky~y|y~j{}y~|u{|y" "~|ly~y|y~7y~}xy~|y{|y~|py~}s{|y~|py~}s{|y~|py~}s{|y~|py~}s{|y~|k{|y~ey~y}y~6{|y~}b{|x~|O{}y~}y{}{|}y~|p{|w~}{|}" "{}w~}l{}v~g{}w~}k{|y~sy~|n{}y~uy~}m{|y~v{|y~|j{}w~}l{}y~| Gx~|u{}|Px|O{|y~x{|y~j{|w{|~x{}~}n{|y~v{}~|x{|y~t{}y" "~}t{}x~Py~|by~}K{}~|dx|Jx|f{|y~fx~v{}y~h{|y~|i{}y~|f{|s{}y~}f{}y~l{|t{|x~l{}y~ux~j{}y~h{}y~|v{|x~f{|y~}hx|dx|a{" "}v~}Xv~}|bx|m{}~|x{|y~}x{|x~{|y~|t{|y~|r{}y~p{|y~|t{}y~|o{}y~}s{|~|r{|y~|t{|x~|o{|y~|e{|y~|f{}y~}ry~}r{|y~|ry~}" "k{|y~|e{|y~|j{|y~|v{}y~}l{|y~|i{|y~|oy~}s{|y~|uv~}p{}y~}t{}y~}o{|y~|f{}y~}t{}y~}p{|y~|t{}y~|o{}r{}y~|jy~}j{}y~|" "u{|y~}k{}y~}y~ly~}y~u{|w~}px~u{|y~|iy~}j{}y~}a{}~}`y~|e{|y~| y{|y~|v{}x~m{}x~ux~m{}y~|f{}y~u{}y~}n{}y~|ay~|h{}y" "~u{}y~}n{}y~t{}~}j{|y~d{|y~h{}y~x{|x~g{|y~m{}y~ty~|u{|y~r{}y~t{}~}n{}y~|v{}y~|n{}x~ux~n{}y~u{}y~}k{}y~^y~}j{|y~" "g{|y~|v{}y~}ky~y}y~kw~}w{}w~m{}y~|y{|y~}i{}~}y~}i{}y~|a{}y~d{}~}d{}~}5{}y~}w{|y~}|o{}y~w{|w~l{|y~}u{}y~n{}~}w{}" "y~k{}y~|v{}y~|my~|e{}y~t{}~}k{|w~}j{}y~u{}~}m{}y~|v{}y~}q{}y~|x{}~}~|x{}y~q{}y~|{|y~y{|y~|my~|w{|y~|ny~}y{|y~x{" "}y~n{}x~ux~n{}y~|v{}y~|iy~|i{|y~}vy~}o{|y~|rx~n{|y~}e{|y~|fx~|v{}y~}n{|}q~|p{|y~|ry~}j{}y~j{}y~}t{}y~}o{}~}_y~|" "`{|y~ks~|l{}~|u{|y~ks~|My~}hx~x{~|h{|y~|gx~|}x~}|}y~|j{}y~d{}~}c{|x~S{|~}xy|}y|x{}~|R{}~|x{}~a{|}|X{|~}p{}~| /{" "}y~|v{}y~}hy~y{}~| a{|~|x{}~|i{}~|vr~|s{|~}s{}~|o{}~|vr~|q{}y~}j{|y~|r{}y~q{|y~|r{}y~q{|y~|r{}y~q{|y~|r{}y~q{|y" "~|r{}y~q{|y~|r{}y~u{|y~|ty~}i{}y~}s{|~|p{|y~|e{|y~|e{|y~|e{|y~|a{|y~|e{|y~|e{|y~|e{|y~|k{|y~|t{|x~}q{|y~|uv~}p{" "}y~}t{}y~}p{}y~}t{}y~}p{}y~}t{}y~}p{}y~}t{}y~}p{}y~}t{}y~}p{|x~u{|y~}o{}y~}t{}y~}p{}y~|u{|y~}o{}y~|u{|y~}o{}y~|" "u{|y~}o{}y~|u{|y~}iy~}i{|y~|e{}y~sy~}p{|y~|v{}x~n{|y~|v{}x~n{|y~|v{}x~n{|y~|v{}x~n{|y~|v{}x~n{|y~|v{}x~s{|y~|v{" "}w~|i{}y~|f{}y~|e{}y~|e{}y~|e{}y~|a{|y~d{|y~d{|y~d{|y~h{}y~|v{}y~|n{}y~t{}~}n{}y~|v{}y~|n{}y~|v{}y~|n{}y~|v{}y~" "|n{}y~|v{}y~|n{}y~|v{}y~|j{|x~i{}y~}v{}y~|n{|y~|v{}y~}n{|y~|v{}y~}n{|y~|v{}y~}n{|y~|v{}y~}k{}~}y~}j{}x~ux~k{}~}" "y~}7{|y~}|{y|{|}y~|o{|y~}|w{|}y~|o{|y~}|w{|}y~|o{|y~}|w{|}y~|o{|y~}|w{|}y~|j{|y~e{|w~|6y~}`x~I{|~hx|y{|}yw|jw~|" "f{}x~j{|y~sy~|mx~w|x~l{}~}uy~}j{}w~|k{}y~}| I{|x~}|{y|y~|Py~}O{|~}x{|~}j{}~|y{|~{|}y~|n{}~|v{|y~x{}~}sx~}|y{|}" "u~Q{}~}by~|K{}~|d{}y~Jy~}f{}~}f{|y~}|{|}y~}kw|y~w|m{}y~}s|my~}w|}w~e{}y~ly~}w|}x~}l{|x~|y{|x~|jy~}h{|x~}|{y|x~|" "m{~}w|}y~}g{}y~d{}y~_{|}y~}Xy~}|_y~}m{|~}w{|u~y}w~|sx~q{|y~|q{|y~t|}y~}m{}x~}v|}y~|r{|y~u|y}x~}n{|y~q|n{|y~|e{}" "x~}v|}x~}r{|y~|ry~}k{|y~|e{|y~|j{|y~|u{}y~}m{|y~q|r{|y~|oy~}s{|y~|u{|w~}o{}x~}|{y|}x~n{|y~|e{}x~}|{y|}x~o{|y~|t" "{|y~}oy~}x|{y|x~}iy~}j{|x~}w|}x~j{|w~}l{}x~}tw~|q{}y~|t{}y~iy~}k{|x~o|l{}~}`{}~}e{|y~| xx~|y{|}w~m{}w~|y{|x~|lx" "~}|yy|}|mx~|y{|}x~}m{}y~}|x{|}~}jy~|h{|x~|y{|}x~}n{}y~t{}~}j{|y~d{|y~h{}y~w{|x~h{|y~m{}y~ty~|u{|y~r{}y~t{}~}mx~" "|y{|}y~}m{}w~|y{|x~|mx~|y{|}x~}k{}y~g{}~}|x{|}y~|j{|y~}gx~|y{|}x~}k{}w~}k{}x~}w{|x~}n{|y~|w{}y~|j{|w~|j{}y~|`{}" "y~d{}~}d{}~} w{|y~}|{|y~}y~}m{|x~}|y{|}y~}n{|~}x{|y~|jx~|y{|}y~}l{}y~}|x{|y}m{}y~t{}~}jw~|jy~}u{|y~|n{}x~}|{|}w" "~y|s{|x~|{|y~|~}|{}y~}px~y|y~|}y~}ly~|vy~}n{}y~|{|y~y{}y~|n{}w~|y{|x~|mx~|y{|}y~}h{}y~|i{}y~}y{|x~nx~q|}y~|ox~r" "|m{|y~|iw|x~}x{}y~}w|o{|y}x~y}|n{|y~|ry~}j{}y~i{}x~}|{y|}x~m{|^y~|_{|iu~|j{|s{|iu~|Ly~}h{|y~}|{~|{|}mx|y~}t|o{|" "y~r{}~}j{}y~d{}~}b{|y~|S{|~}r{}~|Py|w{}:{|~}r{}~|=k|!{}x~}|{|}w~y|jy~y{}~| ay|w{}h{|~}uv|}~}|ry~s{}~|o{|~}uv|}~" "}|q{|y~}ix~q{|y~|rx~q{|y~|rx~q{|y~|rx~q{|y~|rx~q{|y~|r{}y~q{|y~|vx~sy~}r|q{}x~}v|}y~|p{|y~q|n{|y~q|n{|y~q|n{|y~" "q|j{|y~|e{|y~|e{|y~|e{|y~|k{|y~}u|}x~}p{|y~|u{|w~}o{}x~}|{y|}x~n{}x~}|{y|}x~n{}x~}|{y|}x~n{}x~}|{y|}x~n{}x~}|{y" "|}x~ox~s{|y~}pv~}|{y|}x~o{|x~}w|}x~n{|x~}w|}x~n{|x~}w|}x~n{|x~}w|}x~hy~}i{|y~|e{}y~{x|y{|}y~|ox~|y{|}w~mx~|y{|}" "w~mx~|y{|}w~mx~|y{|}w~mx~|y{|}w~mx~|y{|}w~rx~|y{|}y~|}y~}|x{|}~}qx~}|yy|}|m{}y~}|x{|}~}m{}y~}|x{|}~}m{}y~}|x{|}" "~}m{}y~}|x{|}~}j{|y~d{|y~d{|y~d{|y~gx~|y{|}y~}m{}y~t{}~}mx~|y{|}y~}lx~|y{|}y~}lx~|y{|}y~}lx~|y{|}y~}lx~|y{|}y~}" "i{|x~i{|x~|y{|}y~}lx~|y{|}x~}mx~|y{|}x~}mx~|y{|}x~}mx~|y{|}x~}k{|w~|j{}w~|y{|x~|k{|w~|6{|q~|m{|q~|m{|q~|m{|q~|m" "{|q~|i{|y~dw~5{}~_{}~}I{}~c{}~d{|y~|dy~|j{|y~sy~|m{|s~|ly~}u{}~}j{|w~i{}m~ S{|s~}Oy~}O{}~|x{}~|j{}q~}n{|~}t{}y" "~}x~q{}s~}{|y~}R{|y~c{|y~J{}~|dx~Jy~}fy~|e{}t~}k{}q~}no~|nq~}d{}y~lq~|j{|s~|j{|y~|g{|r~|ls~}f{}y~dx~\\y|X{}|]y~" "}ly~|w{|}y~}|{}~}|r{|y~}py~}q{|p~}k{|q~}q{|p~}|m{|o~|o{|y~|d{|p~}q{|y~|ry~}k{|y~|e{|y~|j{|y~|t{}y~}n{|o~r{|y~|o" "y~}s{|y~|t{}x~}n{}r~}m{|y~|d{}r~}n{|y~|s{}y~|pp~}hy~}i{|r~}hw~|l{}x~}tw~|r{|y~}s{|y~}jy~}k{}l~|m{}~}`{|y~e{|y~|" " x{|t~}|y~m{}y~|t~|j{}s~|m{|t~|}~}l{}r~}jy~|g{|t~|}~}n{}y~t{}~}j{|y~d{|y~h{}y~v{|x~i{|y~m{}y~ty~|u{|y~r{}y~t{}~" "}m{|s~}l{}y~|t~|l{|t~|}~}k{}y~g{}r~}h{}u~k{|t~|}~}k{|w~|k{|x~|w{|x~|ny~}u{}y~iw~io~h{}y~d{}~}d{}~} v{}t~{}x~}o{" "|q~}ly~}y|y~}i{|s~}j{}s~}m{}y~t{}~}j{}x~j{}y~sy~}n{}~}t~}x~}r{|u~|{t~o{|q~ky~|vw~}ot~}x~}m{}y~|t~|l{|s~}g{|v~j{" "}t~|o{|k~}p{|o~|n{|y~|is~y{|t~}l{}y~k{|y~|ry~}j{}y~h{}r~}Ny~|Kw~|Lw~|Ky~}g{|r~n{|o~}n{|p{|i{}y~d{}~}ay~|R{|y~}y" "|{y|}y~| a{|y~}y|{y|}y~|<k~}\"{}~}t~}x~}jy~y{}~| Gy~o{|~}r{}~|ty~|ny~o{|~}q{|y~}i{|y~}py~}s{|y~}py~}s{|y~}py~}s" "{|y~}py~}s{|y~}py~}s{|y~}py~}w{|y~|so~}q{|q~}o{|o~|o{|o~|o{|o~|o{|o~|k{|y~|e{|y~|e{|y~|e{|y~|k{|o~|o{|y~|t{}x~}" "n{}r~}l{}r~}l{}r~}l{}r~}l{}r~}n{|~q{|~p{}~y|r~}m{|r~}l{|r~}l{|r~}l{|r~}gy~}i{|y~|e{}y~{}t~}n{|t~}|y~m{|t~}|y~m{" "|t~}|y~m{|t~}|y~m{|t~}|y~m{|t~}|y~r{|s~|y{}r~|p{}s~|l{}r~}l{}r~}l{}r~}l{}r~}j{|y~d{|y~d{|y~d{|y~fs~}l{}y~t{}~}m" "{|s~}k{|s~}k{|s~}k{|s~}k{|s~}Rq~}k{|t~|}~}m{|t~|}~}m{|t~|}~}m{|t~|}~}jw~i{}y~|t~|iw~3{|}w~}|i{|}w~}|i{|}w~}|i{|" "}w~}|i{|}w~}|g{|~}d{}y~} r{|~|Iy~|dy~|d{|}cy|i{|y}sy}|k{}w~}k{|y~|u{|y~ix~}gy}p~ Q{|}x~}|Ny~}Oy~wy~h{|y}v~}|my" "~r{|x~}o{|}w~}|x{}y~}Ry~|d{}~}J{}~|dy~}Jy~}g{|y~c{|}x~}|j{}q~}no~|m{|}w~y}|c{}y~l{|y}w~y}f{}w~}hx~dy}x~y}|k{|}w" "~}|e{}y~dy~} ry~}l{|y~c{}y~|p{}y~q{|r~}|h{|}w~}|o{|s~y}|k{|o~|o{|y~|b{|}w~y}|o{|y~|ry~}k{|y~|e{|y~|j{|y~|s{}y~}" "o{|o~r{|y~|oy~}s{|y~|t{|x~}l{|}x~y}|l{|y~|b{|}v~}m{|y~|ry~}o{|y}w~y}|gy~}g{|}w~}|g{|x~k{|x~|t{}x~qx~q{}y~|ky~}k" "{}l~|m{}~}_y~|f{|y~| v{}x~}|{|y~m{}y~{|}x~}|h{|}x~y}|j{}x~}|{}~}k{|}w~y}|iy~|e{}x~}|{}~}n{}y~t{}~}j{|y~d{|y~h{}" "y~u{|x~j{|y~m{}y~ty~|u{|y~r{}y~t{}~}k{|}x~}|k{}y~{|}x~}|i{}x~}|{}~}k{}y~f{|y}w~}|fy}w~j{|}x~}y{}~}jx~}ix~ux~|o{" "}y~t{|y~}j{|y~}io~h{}y~d{}~}d{}~} u{|}x~}|y{}y~}o{|y~|}w~}|k{|v~}f{|}x~}|h{|}w~y}|m{}y~t{}~}j{|y~|jy~}s{}y~n{}~" "}{}x~}y{}~}|q{|}y~}|x{}x~}l{}v~}|jy~|v{|}y~}n{}s~|l{}y~{|}x~}|i{|}x~}|e{|}x~i{|}x~}m{}j~p{|o~|n{|y~|is~y{|t~}l{" "}y~k{|y~|ry~}j{}y~f{|}x~y}|My~|Jy~|Jy~|Jy~}f{|}u~}n{|o~}O{}y~d{}~}h{}|w{}y~O{|}v~}| ]{|}v~}|:k~}\"{}~}{}x~}y{}~" "}|jy~y{}~| H{}~|o{|~|s{|~}t{|t~|t{}~|o{|~|q{}y~h{}y~|p{}y~s{}y~|p{}y~s{}y~|p{}y~s{}y~|p{}y~s{}y~|p{}y~s{}y~|p{}" "y~w{}y~ro~}o{|}w~}|m{|o~|o{|o~|o{|o~|o{|o~|k{|y~|e{|y~|e{|y~|e{|y~|k{|s~y}|m{|y~|t{|x~}l{|}x~y}|i{|}x~y}|i{|}x~" "y}|i{|}x~y}|i{|}x~y}|U{|~}x{|}x~y}|j{|}w~}|i{|}w~}|i{|}w~}|i{|}w~}|fy~}i{|y~|e{}y~{|}w~}|k{}x~}|{|y~k{}x~}|{|y~" "k{}x~}|{|y~k{}x~}|{|y~k{}x~}|{|y~k{}x~}|{|y~p{}x~}|v{|}w~y}|n{|}x~y}|j{|}w~y}|j{|}w~y}|j{|}w~y}|j{|}w~y}|i{|y~d" "{|y~d{|y~d{|y~e{|}x~}|k{}y~t{}~}k{|}x~}|h{|}x~}|h{|}x~}|h{|}x~}|h{|}x~}|R{}~|{|}x~}|i{|}x~}y{}~}l{|}x~}y{}~}l{|" "}x~}y{}~}l{|}x~}y{}~}j{|y~}i{}y~{|}x~}|h{|y~} e{|~} V{| .{|~ p{}~}dy~|1{|y~2{}~} U{|y~ ^{}~} ){|y~| {" "}y~} 6{}~}_{}~}f{|y~| -y~}6{|y~ A{}y~Z{}~} j{|y~I{}y~d{}~}d{}~} \\{|y~a{|}y|*{}~}j{|y~|O{}~}F{|y~K{|}y~y|j{}" "y~ Ry~}c{|~| r{}~}h{}t~|K{| U{| '{}~}^y~y{}~|O{|~| wy|cy}|st|sy|ay~} ^{|~| 9{| Y{|~| 8y| Q{|y~h{}" "y~`{|y~ d{|~} c{|~ oy~e{}~}0{}~}2y~| U{}~} ]{}y~|r{|y} 7{}y~ y{}y~| 7{}~}_{|y~f{|y~| .{|y~|6{|y~ " "A{}y~Z{}~} j{}~}I{|y~d{}~}dy~} \\{|y~ g{}~}j{|y~|O{}~}F{|y~J{|y~h{}y~ Ry~}b{~| r{}~}h{|y}x~}| ){}~}^y~y{" "}~|N{}~ 'y~} ]y~ p{~} g{}~}h{}y~`{}~} h{|}|{}~} c{|~ o{}~}fy~/{}~ c{}~ [{}y~}|v{|}y~} " " 7x~ x{}y~| 8{}v~M{|v~| .{}y~5{}~} A{}y~Z{}~} k{|y~|I{|y~}e{}~}e{|y~| \\{|y~ g{}~}j{|y~|O{}~}F{|y~J{|y~h{}y" "~ Ry~}b{~| r{}~} i{}~}*{}~| (x~uy| e{}~| q{}~ h{|y~|h{}y~a{|y~| h{|y~|y~| c{|~ ny~" "g{}~} M{|}q~| 9y|}y~| 1{}w~}M{|v~| 6y}|x{|}y~|6{|y~} A{}y~Z{}~} l{|x~G{}w~}h{}~}h{}w~} [{|y~ g{}~}j{" "|y~|O{}~}F{|y~J{|y~h{}y~ Ry~}b{~| r{}~} i{}~}-x}y~ '{}x~w|y~| e{}~| qy~ i{|x~g{}y~b{|x~ f" "{}w~ e{|y}w~}| 8{|w~} ({|n~} m{}s~}7{|w~ @{}y~Z{}~} nv~|F{|y}~}h{}~}h{}~y}| Z{|y~ g{}~}j{" "|y~|O{}~}F{|y~J{|y~h{}y~ Rx| W{}~} i{}~}-{}y~}| &{}s~| i{|~y}y~ t{|~y}y~ kv~|g{}y~dv~| ex" "} s{|y~}| '{|n~} m{|y}w~}|6{|y~} ?{}y~Z{}~} nx~}|-{}~} B{|y~ g{}~}j{|y~|O{}~}F{|y~J{|y~" "h{}y~ q{}~} -{|}x~}| f{}y~}| t{|x~}| kx~}|f{}y~dx~}| " " :{}~} I{" }; // Define a 52x64 font (large sans). static const char *const data_font_large[] = { " " " -{| " " [{|x}|Dw}|Pw}| @{}v~} C{|w}|Ew}|Pv}| xv|Ev|Pu| kv|Dw|P{|v} 6{|w}|E{|x}|P{" "|w}| pw}| " " G{|w~}F{}w~P{}v~}Q{}w~}|w{|x~X{|v~vv~|U{|r~| D{}w~F{}w~P{}u~S{|v~|wv~}V{}w~|G{|w~|Q{" "|u~|Sv~}w{}w~}\"{|}x~}|v{|x~W{}w~|F{}w~Q{|u~}Q{}x~}|v{|x~X{}w~}w{|v~ G{}w~F{}w~|Q{}u~Rv~|w{}w~}O{}w~ " " " " E{|w~|H{}w~P{}t~}Ss~}|y{}x~X{|v~vv~|V{|p~ Cw~}H{|w~|Q{|t~}T{|v~|wv~}U{}w~Gw~}Q{|s~|Tv~}w{}w~}#{|s~}|{|x~" "}V{}w~|H{}w~Ps~}St~}w{}y~}X{}w~}w{|v~ Fw~}H{|w~|Q{|t~}Sv~|w{}w~}P{|w~| " " D{|w~|J{|w~|Q{|x~}{w~|U" "{}l~}X{|v~vv~|Vw~}x{}x~} D{|w~|J{|w~|Q{|w~{}x~}U{|v~|wv~}T{}x~}Iw~}Pw~y|w~Tv~}w{}w~}#k~|U{}w~I{|w~|Q{}x~|{}x~|U" "{}r~|{|x~}X{}w~}w{|v~ Ew~|Iw~}Pw~|}x~}Tv~|w{}w~}Q{|w~| M{| " " q{}w~Jw~|Q{|x~}xw~Ux~}y{|}t~}W{|v~vv" "~|W{|x~|v{|x~| D{|w~|Kw~}Pw~x{}x~|V{|v~|wv~}S{}x~}K{}x~}P{}x~|y{|x~}Uv~}w{}w~}${|x~|y{|s~}S{}x~}K{|w~|Q{}x~}xw~" "Ux~}{|}r~W{}w~}w{|v~ E{|w~|K{}x~}Pw~|y{}x~|Uv~|w{}w~}Qw~| O{}v~} " " s{}x~}L{}x~|Pw~vw~W{|x~v{|}w~}" "V{|v~vv~|W{}y~}tx~} C{|w~L{}x~}P{}x~|w{}x~|W{|v~|wv~}R{}x~|M{}x~}P{}x~|w{|x~}Vv~}w{}w~}${|x~v{|}w~|Q{}x~}Lw~|Q{" "|x~}vw~W{|x~w{|t~|W{}w~}w{|v~ D{|w~L{|x~}P{}x~|w{}x~|Vv~|w{}w~}R{}x~} P{|r~| Y{}w~| " " A{}x~|N{}x~}P" "{}x~u{|x~}\"v|vv|V{}y~}t{}y~} B{}x~}N{|x~}P{}x~|u{}x~Vv|vv|P{}x~|O{|x~}P{}x~|u{|x~}Wv|uv| D{}x~|N{}x~|Q{|x~}tx~" "}X{|x~u{|}y~}|Vu|vv| C{|x~}N{|w~P{|x~|u{}x~Vv|vu|S{|x~} Op~| Zv~| " " ;v~ u{|v~ 6{|y}|N{|y}|P{|x}s{|x} I" "{}y~}t{}y~} Aw|Nw|Ow|sw| Qw|Nw|Pw|rx| 5{|x}N{|x}O{|y}|s{|y}| {{|y}| Dv|@v|Rv| C{}x~}x{|w~ Hu|@v|Rw| yv}@v}R" "{|w} lv|@v|Rv| 8v}@v}|S{|w} m{}w~| E{|y~x}| ;{|w~} " " vv~| J{}y~}t{}y~} e{}w~}B{|w~}Rv~| Dx~|v{|x~| H" "v~A{}w~|S{|w~} {{|w~}B{}w~|S{|v~| Ay|sx|Y{}w~|B{|w~}Rv~ 8{|w~}B{|w~}Rv~| o{|w~} ?y}~}| *x~ J{" "|y~| b{}x~|T{|x~} L{|q~} y{}q~| H{|w~} xw~} `{|w~| {{|}t~)w~}Cv~Lv~Tw~}Dv~ G" "{|x}w~}Tw~|U{|v~y}| 1{|y}v~y}| cv~y} p{|y}x~y}| {{v|vv| 3{}w~| I{|x~|v{|x~| " " %{| 5{|y}w~y}|U{}w~|Cv~R{}v~}Q{|}y~}|ux~|Y{|v~|wv~}W{|x~t{}y~} H{|w~}C{}w~|Ru~|S{}w~}w{|v~W{}w~|D{|w~}R" "t~S{|v~vv~|X{|v~}K{}w~}ux~X{}w~C{|w~}R{}v~}Q{|}y~}|ux~|Y{|v~vv~| J{|w~}D{|w~}R{}u~Rv~|w{}w~}N{|w~}Zw~}Hv~}w{}w~" "} N{|u~} ,{|y~} Ix|Tx|kw| Ru| 6{|y~|Yv|fx}|Zu| o{|w~Rw~|Hx| Xu| vt|Ns| =t| xt|Ot| [u| ds| kr|" " Qt| ut| ts| S{|q~} y{}q~| G{}w~| yw~} `{|w~|!{}q~)w~}Cv~Lv~Tw~}Dv~ I{|r~}Tw~|U{|r~} 5{|}o~| yr| " " ps~} t{|p~| kt| is| s{|y} r{|x}| rx}| bt| lu|S{|v~vv~|!{|y}w~y}| :{|l~|Qx| u{|y}w~}|Q{|x}w~y}|K{|w~| " " 9y|y}w~|O{|y}w~}|)y|x}dw~|hy|x}dw~|ly|x}y~y}|e{}x~| 6w~}x{}x~} us| lt|Nt|Nt|Nt|Nt| ut|p{}~| 9{|}o~|V{" "}w~D{}w~R{|t~|S{|u~}vx~|Y{|v~|wv~}W{}y~}t{|x~ G{|w~}E{|w~}R{}t~S{}w~}w{|v~V{}w~E{|w~}R{}t~}T{|v~vv~|W{|v~}s{|y}" "X{}u~}w{|x~Ww~}Dv~R{|t~|S{|u~}w{|x~X{|v~vv~| I{}w~|Ew~}R{|t~}Sv~|w{}w~}Nw~}Yw~}Hv~}w{}w~} O{|s~|cW} i{}y~|" "\"{|}L{|u~}|Z{|}v~}|p{}u~}V{|} /g| ({}r~}| v~}R{}x~}vw~}R{|x}|t{|x}|V{|y~|\\{|}t~|i{}x~|]{}q~}|O{}x~}Iw~|R{|" "w~Hx~ *{|w~V{|}s~}|Sy|y}v~}T{|}q~}|V{|y}p~}|L{|u~}\\{|g~}T{}q~y}|_{}c~}[{|}q~}|U{|}r~}| b{|}q~| w{}v~}X{}k~y" "}|R{|y}p~}|b{}m~x}y|W{}c~|`{}e~Y{|}o~}|a{}w~}hv~|Y{}w~}M{}w~}W{}w~}k{|u~}b{}w~}V{}t~|h{}t~|h{}u~}jv~^{|}p~}|Z{}" "m~y}|U{|}p~}|\\{}m~y}y|S{|}o~}y|bZ~g{|v~h{}w~}i{|v~|d{|v~|rv~|l{|v~}kv~|p{|v~|i{}v~g{}v~fv~}g\\~]{|q~}Uw~}I{}q~" "|P{|w}| w{}w~ yw~} `{|w~|\"o~)w~}Cv~Lv~Tw~}Dv~ J{|q~}Tw~|U{|q~} 7{}l~}\"y}p~y} sr~} v{}n~}R{}v~}V{" "}c~|_{}d~}^{|}p~}|R{|v~Y{}^~|iv~}r{|v~qv~}a{|}p~}| x{}x~} s{}w~ s{}w~| f{|}r~}|-{}w~|i{|v~({|q~}|W{|v~vv~|Ty|u" "}y|U{|}o~| ly|u}y|U{|l~|T{|}v~}| {|}p~|T{}p~}|N{|w~} yy|}m~} N{|r~|P{}q~|0{|y}t~|f{}x~}l{|y}t~|f{}x~}l{}p~}h{}" "x~}%{}v~}N{}v~}N{}v~}N{}v~}N{}v~}Q{|p~W{}\\~}b{|y}p~}|^{}c~|a{}c~|a{}c~|a{}c~|X{}w~}M{}w~}M{}w~}M{}w~}Z{|m~x}y|" "Z{}u~}jv~^{|}p~}|V{|}p~}|V{|}p~}|V{|}p~}|V{|}p~}|\"{|}q~y}t{}x~|i{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}g{}" "v~fv~}c{}w~}J{|l~}Vw~}F{}w~|R{}x~|w~Ss~}x{|x~X{|v~|wv~}W{}y~}t{|x~ F{|w~|Fw~}R{|x~y}x~}T{}w~}w{|v~U{}x~}Fw~}R{|" "w~{w~|U{|v~vv~|V{}v~|x{|}v~Y{|s~}x{}x~W{|w~}F{}w~Qw~|w~Ss~}x{|x~X{|v~vv~| H{}w~F{}w~Qw~|}x~|Tv~|w{}w~}O{}w~Xw~}" "Hv~}w{}w~} P{|q~c{}Y~} ix~!y~|N{}r~}\\{}r~}s{|q~|Y{|y~} 5{|}e~} *{}m~|\"v~}R{}x~}vw~}Rw~|tw~|V{|y~|]{}q" "~}k{|w~^{|l~|Q{}x~}J{}w~P{}x~}Ix~ *{}x~}W{}n~|Zy|}p~}W{|}k~}Z{}i~|Nt~}\\{|g~}V{}l~|`{}c~}\\{}l~|X{}n~} e{|l~" "|Ty|y}u~y}|Rt~X{}g~}V{|}j~}d{}g~}|Z{}c~|`{}e~\\{|}i~}|d{}w~}hv~|Y{}w~}M{}w~}W{}w~}l{|u~}a{}w~}V{}t~}i{|s~|h{}t~" "|kv~`{|k~}|\\{}i~}|Z{|k~}|^{}i~}|W{|h~}dZ~g{|v~h{}w~}hv~}d{}v~q{}w~}l{}u~kv~|o{}v~j{|v~|fv~}h{}v~f\\~]{|v~u}U{}" "w~Iu}v~|Qt~| w{}x~} {{w~} `{|w~|#{}o~)w~}Cv~Lv~Tw~}Dv~ Ov| s~x}|Tw~|U{|x}s~| 9{}j~}%{}j~| uq~| x{}l" "~}St~V{}c~|_{}d~}`{|}k~|T{|v~Y{}^~|iv~}r{|v~qv~}c{|k~}| {}v~} t{}w~ t{}u~| i{|l~-v~i{}w~|Xw}|R{|l~X{|v~vv~|W{|" "}o~}|X{|m~| p{|}o~}|X{|l~|U{}r~}!{|n~}U{}n~|Ow~} {{|}j~} N{|r~|R{|n~}1{|r~|g{|w~k{|r~|g{|w~k{}n~iw~$t~Nt~Nt~Nt" "~Nt~P{|r~V[~}d{|}j~}`{}c~|a{}c~|a{}c~|a{}c~|X{}w~}M{}w~}M{}w~}M{}w~}Z{|g~}|]{}t~|kv~`{|k~}|Z{|k~}|Z{|k~}|Z{|k~}" "|Z{|k~}|&{|k~}w{|w~|i{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}fv~}h{}v~b{}w~}K{}j~}W{|w~|H{|w~|R{|x~}{|x~}U{|" "x~}|w~}|{}x~X{|v~|wv~}W{|x~t{}y~} E{}w~G{}x~}Qw~|{}x~|U{}w~}w{|v~Tw~}H{}w~Q{}x~|{|x~}U{|v~vv~|U{}v~|}t~}Y{}x~|{" "}w~y|x~}V{|w~|H{|w~|R{}x~|{|x~}U{}x~}|w~}{|x~}X{|v~vv~| G{}x~}H{|w~|R{}x~|yw~Tv~|w{}w~}P{|w~|Xw~}Hv~}w{}w~} " "P{}w~y|w~|d{|Y~| j{|y~}\"{}x~Oo~}_{|o~}u{|o~}Zw~| 8{}b~} ,{|j~}#v~}R{}x~}vw~}Rw~sw~U{|y~|^{}o~}lw~|_{}k~|Q" "{}x~}Jw~|P{|w~|Jx~ *w~|Xk~|[m~}X{}h~}[{}h~}P{}t~}\\{|g~}X{|j~|`{}c~}^{|i~}[{|j~ gi~|X{|}l~}|V{}t~|Y{}e~|Y{}f" "~}f{}d~}\\{}c~|`{}e~]{}e~}|f{}w~}hv~|Y{}w~}M{}w~}W{}w~}m{|u~|`{}w~}V{}s~|j{}s~|h{}t~}kv~b{|g~}]{}g~}]{|g~}_{}g~" "}Y{}f~dZ~g{|v~h{}w~}h{}v~dv~}q{}w~}lt~|m{|v~mv~}kv~}e{|v~|j{|v~|f\\~]{|w~}O{|w~|D{|w~|Rr~| ww~} w~} `{|w~|${|v~" "}|#w~}Cv~Lv~Tw~}Dv~ Ov~ !{|v~}Nw~|O{|v~} :{|u~}|w{|}v~|'{}i~| r{|}v~} y{}v~}|x{|}v~}U{}t~|W{}c~|_{}d" "~}a{}g~|V{|v~Y{}^~|iv~}r{|v~qv~}e{|g~}\"{}t~} u{}w~ u{}s~| >y~}P{|k~-{|w~}k{|w~}Ww~|S{|k~X{|v~vv~|Y{|}k~}|Z{|y~" "}y|xy|}w~| s{|}k~}|Z{|l~|V{}p~}\"{|y~}|w{|}w~|V{|}|u{|v~P{}x~} {{}h~} N{|~y}y|}x~|S{|v~}|y{|}w~}2{|w~y}x~|g{}x" "~|k{|w~y}x~|g{}x~|kx}|w{|}w~}k{}x~}%{}t~|P{}t~|P{}t~|P{}t~|P{}t~|P{}t~}W{|[~}e{}f~}b{}c~|a{}c~|a{}c~|a{}c~|X{}w" "~}M{}w~}M{}w~}M{}w~}Z{|d~}|`{}t~}kv~b{|g~}]{|g~}]{|g~}]{|g~}]{|g~}){|g~|{|w~|h{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f" "{|v~h{}w~}f{|v~|j{|v~|b{}w~}L{|u~}|w{|}v~|W{|w~|Iw~}Qw~x{}x~|V{}y~}x{}s~|X{|v~|wv~}Vx~}v{|x~| D{}x~}I{}w~Q{}x~|" "xw~U{}w~}w{|v~T{|w~|J{|w~Q{|x~}x{|x~|V{|v~vv~|T{}q~}|Wx~|x{}s~T{|w~I{|w~|R{|x~}x{}x~|Vx~}x{}s~|X{|v~vv~| Fw~}J{" "|w~|R{|x~}x{|x~}Uv~|w{}w~}Q{|w~|Ww~}Hv~}w{}w~} Pw~}y{|x~}cY~ i{}y~|#{|w~}Qm~|`m~}w{|m~|\\{}v~| ;{}`~} -" "{|r~x}t~}$v~}R{}x~}vw~}S{|w~t{|x~}U{|y~|_{|w~}w{}w~|n{}x~}_{|t~w}u~|Q{}x~}K{}w~N{}x~}Jx~ +{|w~Xs~y}s~|\\m~}X{}" "f~\\{}g~}R{|s~}\\{|g~}Y{|i~|`{}c~|_{|s~w}s~}]{|s~x}s~ hr~}r~|[{|f~}Xs~}Y{}d~|\\{|c~}g{}b~|^{}c~|`{}e~_{|a~|g{" "}w~}hv~|Y{}w~}M{}w~}W{}w~}n{|u~|_{}w~}V{}s~}jr~|h{}s~|lv~c{|p~}q~}^{}f~}_{|p~}q~}`{}e~[{}q~}p~dZ~g{|v~h{}w~}h{|" "v~|f{|v~p{|v~m{|t~}m{}w~}m{|v~|m{}v~c{}v~jv~}e\\~]{|w~}Nw~}D{|w~|Sp~| ww~|!w~} `{|w~|${}w~}!w~}Cv~Lv~Tw~}Dv~ " " Ov~ !{}w~}Mw~|N{|v~ :{}v~|s{|v~V{|t}|V{|t~s}w~| p{|v~ {{|v~|t{|v~|Vs~}W{}c~|_{}d~}c{|d~|W{|v~Y{}^~|iv~" "}r{|v~qv~}f{|p~}q~}${}r~} v{}w~ v{}q~| ?y~}Ps~x}u~,v~k{}w~|Ww~|Su~}v|}w~X{|v~vv~|Z{}v~}y|wy|}v~}[{|}q{}x~} t{}" "v~}y|wy|}v~}&{}w~|x{|w~}#y|r{}x~}Kw~|R{|w~ {{}p~}v|x~} H{}x~|S{}w~t{}w~|3x|x{}x~|h{|x~}j{|}|x{}x~|h{|x~}`{|w~l{" "|w~$s~}Ps~}Ps~}Ps~}Ps~}Pr~W{}[~}g{|c~}c{}c~|a{}c~|a{}c~|a{}c~|X{}w~}M{}w~}M{}w~}M{}w~}Z{|b~}a{}s~|lv~c{|p~}q~}_" "{|p~}q~}_{|p~}q~}_{|p~}q~}_{|p~}q~}+{|p~}q~}w~|g{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}e{}v~jv~}a{}w~}Lu~r{" "|v~V{|w~J{}x~}Q{}x~|w{}x~Vx~|w{}u~}Vv|vv|U{}x~}x|}w~ Bw~|K{|w~|R{|x~}w{|x~}Vu|vv|S{|w~K{|w~|Qx~}v{}x~Uv|vv|T{|}" "t~}|Tx~|w{|u~|S{}x~}Jw~}Qw~vw~Vx~|w{}u~}Vv|vv| Dw~|Kw~|Qw~v{}x~|Vv|vv|Pw~|Vw~}Hv|uv| G{|t}|P{|t}|P{|t}|P{|t}|P{" "|t}|Lw~|xw~c{|[~} iy~}\"u~|S{|l~a{}l~|x{}l~]{}t~ ={|^~} .{|u~}|u{|}w~}$v~}R{}x~}vw~}S{}x~}t{}x~}Xy|y}y~y}x" "|cw~}u{}w~o{|w~^u~}t{|}y~|Q{}x~}Kw~|N{|w~|T{}sx~s{} 4{}x~}Y{}v~}|v{}u~\\m~}X{}v~y}|wy|s~]{}x~}x|v{|}t~}Sr~}\\{" "|v~k|Z{|t~}|v{|y}y~|`h|u~^t~|u{|}u~|^u~}|v{|}v~} iv~y|v{|t~]{|o~y}p~|[{|r~|Z{}w~}q|}s~]{|s~}|t{|}u~}g{}w~}r|y" "}q~}_{}w~}h|_{}w~}j|`{|s~}|s{|}t~|g{}w~}hv~|Y{}w~}M{}w~}W{}w~}o{}u~|^{}w~}V{}r~k{|r~|h{}r~lv~d{|t~}|uy|s~_{}w~}" "s|y}t~}a{|t~}|uy|s~a{}w~}s|y}s~]{}u~}|ty|}v~dn|}v~}n|g{|v~h{}w~}gv~}f{}w~}ov~|n{|t~}mv~|l{}v~|o{|v~|bv~}l{}v~dc" "|u~}]{|w~}N{}w~D{|w~|T{}o~| x{|w~!w~} `{|w~|${}w~ w~} >w~}Dv~ Ov~ !{}w~|Mw~|M{}w~ :v~|q{}w~|Xp~}X{}v~|p{|" "}| o{}w~| v~|r{|v~W{|r~|X{}v~}i|^{}w~}h|d{|s~}y|xy|}s~}[{|y}u~y}y|]{}w~}h|v~|iv~}r{|v~qv~}g{|t~}|uy|s~&{}p" "~} w{}w~ w{}o~| @y~}Q{}v~}|u{|}y~,{|w~}m{|w~}Vw~|T{|v~|s{|}~({|w~}|o{|}w~|P{}x~| w{|w~}|o{|}w~|(x~}tw~ rw~K{}x" "~|Rw~ {{}o~}w{|x~} H{}x~|T{|w~r{}x~}-{}x~|hw~|d{}x~|hw~|_{}x~|mw~|%{|r~|R{|r~|R{|r~|R{|r~|R{|r~|R{}r~|Y{|v~|y{|" "v~}h|h{|s~}|t{|}u~}c{}w~}h|`{}w~}h|`{}w~}h|`{}w~}h|W{}w~}M{}w~}M{}w~}M{}w~}Z{|v~r|x}q~b{}r~lv~d{|t~}|uy|s~a{|t~" "}|uy|s~a{|t~}|uy|s~a{|t~}|uy|s~a{|t~}|uy|s~-{|t~}|u{|}q~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}dv~}l{}v~`" "{}w~}M{|v~p{}w~|V{}x~}L{}x~}Q{|x~|ux~}Wx~|v{|w~} {{}q~| Aw~|Lw~|Qw~u{}x~| y{|x~}Lw~|Q{}x~tx~}#{|}r~}Rx~u{|}y~}|" "Q{}x~}L{}x~}Q{}x~|v{|x~}Wx~|v{}w~} j{|w~L{}x~}Q{}x~|u{}x~ x{}x~}Uw~} b{|}p~}|V{|}p~}|V{|}p~}|V{|}p~}|V{|}p~}|" "P{|w~|xx|av~|fv~| j{|y~|#{}t~Sk~|c{|k~}y{|k~}_{|s~} ?{}t~}y| u{|u~|p{}y~}$v~}R{}x~}vw~}Sw~|tw~|[{|}m~}|h{" "|w~sw~|p{}x~|_{}v~|q{|}|Q{}x~}L{}w~Lw~}U{}y~|ux~u{|y~}U{|x}| `w~|Z{|v~}s{|v~}]w~y}y|{}w~}X{}x~|p{|u~|^y}|n{|u~" "|U{}x~y}w~}\\{|w~}K{|u~}o{}|Mv~|_{}v~}q{|u~_{}v~}r{|v~| jy~}|qu~|_{}t~}y|s{|}t~}\\{}w~}w~}Z{}w~}o{|u~}_{|t~|n" "{|}x~}g{}w~}n{|}t~}`{}w~}L{}w~}P{|t~}m{|}w~|g{}w~}hv~|Y{}w~}M{}w~}W{}w~}p{}u~|]{}w~}V{}w~}w~|l{}r~|h{}r~|mv~e{|" "u~}|p{|t~`{}w~}q{|}u~|c{|u~}|p{|t~b{}w~}p{}u~|_{|u~|n{|}y~W{|v~|Z{|v~h{}w~}g{|v~fv~|o{}w~}n{}x~}w~mv~|kv~}ov~}a" "{|v~|n{|v~|M{}v~}\\{|w~}N{|w~|E{|w~|U{}v~}{|u~| x{|x~}\"w~} `{|w~|$v~ w~} >w~}Dv~ Ov~ !v~Lw~|M{}w~| <{|w~" "}p{|w~}Xn~|Zv~ _{|v~ !{|w~}p{}w~}X{}w~}w~}W{}v~|M{}w~}R{|t~|p{|t~|_{|}l~}|`{}w~}hv~|iv~}r{|v~qv~}h{|u~}|p{|" "t~({}n~} x{}w~ x{}m~| Ay~}R{|v~}p{}+{}w~|nv~Uw~|T{}w~| x{|w~|k{|w~|Q{|x~| x{|w~|k{|w~|*{|x~rx~|R{|w}Fw~Kw~|S{}" "x~| {|n~}w{|x~} H{}x~|T{}x~}qw~|.{}x~|i{}x~}c{}x~|i{}x~}^{}x~|n{}x~}${}w~}w~}R{}w~}w~}R{}w~}w~}R{}w~}w~}R{}w~}w" "~}Rv~|w~}Y{}w~}x{|v~U{|t~|n{|}x~}c{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~n{|}s~c{}r~|mv~e{|u~}|p{|" "t~c{|u~}|p{|t~c{|u~}|p{|t~c{|u~}|p{|t~c{|u~}|p{|t~/{|u~}|p{}t~}e{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}d{|v" "~|n{|v~|`{}w~}M{}w~}ow~}U{}x~|N{|w~Px~}t{|x~|Xx|sy| w{}s~| @{|w~M{}x~|Q{}x~|tw~ x{}x~}N{}x~|Q{|x~|t{|x~|&{}t~}v" "~} t{}x~|N{|x~}Q{|x~}t{}x~|Xx|sy| g{|x~}N{|x~}Q{|x~}sx~} {{|x~}Tw~} d{|j~|Z{|j~|Z{|j~|Z{|j~|Z{|j~|R{|w~Z{}w~}" "g{}w~} Ay|J{}y~#{|s~}Tk~}c{}j~|{}j~_q~| A{}u~} q{}v~|n{}~}$v~}R{}x~}vw~}Sw~t{|w~\\{|h~|i{}x~}s{}x~}q{|x~}^" "v~|C{}x~}Lw~}L{}w~V{|v~|wx~w{|v~|V{}w~ a{|w~Yv~}q{|v~|^{}y|u{}w~}Xy}|m{|u~M{|v~}V{|w~|}w~}\\{|w~}Ku~|?{|v~^u~o" "{}v~|a{|v~}p{}v~ j{~|nv~}`u~}|l{|}u~]v~{v~Z{}w~}mu~_u~}j{|y~}g{}w~}l{|}u~}a{}w~}L{}w~}Q{|u~}i{|}y~|g{}w~}hv~|" "Y{}w~}M{}w~}W{}w~}q{}u~|\\{}w~}V{}w~|w~}lw~|v~|h{}q~mv~f{|u~}m{|u~}a{}w~}o{}v~}d{|u~}m{|u~}c{}w~}o{|u~_{}v~|j{|" "W{|v~|Z{|v~h{}w~}fv~|h{}v~n{}w~}nw~|w~|o{|v~j{|v~}q{}v~_{}v~nv~}M{|u~[{|w~}Mw~}E{|w~|V{}v~}x{|u~| vw~} `{|w~|$" "w~} w~} >w~}Dv~ Ov~ !v~Lw~|M{}w~| <{}w~|ow~}Xm~|[v~ ^v~| \"v~|p{|v~Xv~{v~V{}v~|N{}w~}Ru~}l{}u~|b{|g~}" "|b{}w~}hv~|iv~}r{|v~qv~}i{|u~}m{|u~}*{}l~} y{}w~ y{}k~| By~}R{}v~ y{|w~}o{|w~}Uw~|T{}w~ x{|x~}g{}x~|R{|x~} y{|" "x~}g{}x~|+{}y~}r{}y~}R{}w~Fx~}M{|}w~ Mm~}w{|x~} H{}x~|Tw~p{}x~|.{}x~|j{|w~b{}x~|j{|w~]w~n{|w~#v~{v~Rv~{v~Rv~{v~" "Rv~{v~Rv~{v~S{|w~}{}w~|Zv~|x{|v~Uu~}j{|y~}c{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~k{}t~d{}q~mv~f{|" "u~}m{|u~}e{|u~}m{|u~}e{|u~}m{|u~}e{|u~}m{|u~}e{|u~}m{|u~}1{|u~}m{|u~}e{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w" "~}c{}v~nv~}_{}w~}Mv~n{}w~Tw}N{|x}P{|x}r{|x} F{|}x~}| ={|x}|O{|x}|Px}|s{|x}| xw|Nw|Pw|rw|'{|v~}|y{|v~} tw}Nw}P{|" "x}rx}| 6w|Nw|Ox|rw| Nw~} e{}h~}\\{}h~}\\{}h~}\\{}h~}\\{}h~}S{|w~Z{|v~gv~| Ay~}L{|y~}${|q~}V{|j~ci~}|i~|a{}p~|" "Oy|Uw|jw|Vu|Wv|kw|b{}v~} p{|v~|l{|}$v~}R{}x~}vw~}T{|x~}t{|x~}]{|g~|i{}x~|s{|w~qw~|^v~B{}x~}M{|w~|L{|w~}V{|}" "w~}xx~x{}w~}|U{}w~ a{}w~Z{|v~o{}w~}U{}w~}X{|j{}v~|M{}v~Vw~}{}w~}\\{|w~}L{|v~|>v~}_{|v~|nv~}a{}v~nv~| \\{}w~}" "b{|u~|h{|}v~|`{|w~}{}w~|[{}w~}m{|v~|a{}v~}gy}g{}w~}j{}u~|b{}w~}L{}w~}Q{}v~}f{|~|g{}w~}hv~|Y{}w~}M{}w~}W{}w~}r{}" "u~|[{}w~}V{}w~y|w~m{|w~{v~|h{}w~}v~|nv~f{}v~}ju~|b{}w~}nu~d{}v~}ju~|d{}w~}n{}v~|`v~}D{|v~|Z{|v~h{}w~}f{}w~}hv~}" "n{|v~o{|w~{}x~}o{}w~}i{}v~|s{|v~|^v~}p{}v~M{|u~|[{|w~}M{}x~}E{|w~|W{}v~|v{|u~| ww~} `{|w~|$w~} w~} >w~}Dv~ " "Ov~ !v~Lw~|M{|w~| <{}w~|ow~}Xy~}w|}t~[v~| _{}w~} #{|w~}n{}w~|Z{|w~}{}w~|Vu~|O{}w~}S{}v~}j{}u~c{}d~|c{}w~" "}hv~|iv~}r{|v~qv~}i{}v~}ju~|,{}v~y}w~|v~} {{}w~ {{}v~y}w~|u~| Cy~}R{}w~}R{|ey|_{}w~|pv~Tw~|T{}w~ y{|x~}e{}x~|\\" "{|}p~} {{|x~}e{}x~|,{}y~}r{}y~}R{}w~G{}x~|Rq~| N{|m~}w{|x~} H{}x~|U{|w~p{|x~}.{}x~|j{}x~|b{}x~|j{}x~|_{|w~|n{}" "x~|${|w~}{}w~|T{|w~}{}w~|T{|w~}{}w~|T{|w~}{}w~|T{|w~}{}w~|T{}w~|{|w~}[{|v~w{|v~V{}v~}gy}c{}w~}M{}w~}M{}w~}M{}w~" "}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~j{|u~}e{}w~}v~|nv~f{}v~}ju~|f{}v~}ju~|f{}v~}ju~|f{}v~}ju~|f{}v~}ju~|c{}d{}|d{}v~}" "k{}u~|f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}bv~}p{}v~^{}m~y}|Yv~o{|}w~ Py~}|u{|v~} 2w~} f{" "}u~}x|{x|}t~^{}u~}x|{x|}t~^{}u~}x|{x|}t~^{}u~}x|{x|}t~^{}u~}x|{x|}t~T{|w~Yv~|i{|v~ A{}x~}M{}y~|$o~|W{|j~ch~}i~}" "b{}n~T{|}t~y}|Zw~}kw~}X{}u~|X{}w~|m{}w~|d{|v~| ov~}j{|$v~}R{}x~}vw~}T{}x~}t{}x~}]u~}|{|y~|y{|y}x~|iw~|rw~r{" "}x~}]v~B{}x~}Mv~Jv~T{|}w~|{x~{|w~}|S{}w~ aw~}Z{}w~}o{|v~U{}w~}Ev~}M{|v~W{}w~y{}w~}\\{|w~}Lv~}>{|v~|_{|v~m{}w~}" "av~|n{|v~ 8{|y}6{|~|4{}v~c{|v~}d{|v~`{}w~|{|w~}[{}w~}lv~|b{|v~}e{|g{}w~}i{}u~b{}w~}L{}w~}R{|v~}dy|g{}w~}hv~|Y{}" "w~}M{}w~}W{}w~}s{}u~Y{}w~}V{}w~|{w~|nw~}{v~|h{}w~y|v~nv~g{|v~}i{|u~b{}w~}n{|v~|f{|v~}i{|u~d{}w~}n{|v~|a{|v~C{|v" "~|Z{|v~h{}w~}f{|v~|j{|v~|mv~|p{|w~{|x~}ov~|hv~}sv~}]{|v~|r{|v~|Mu~|Z{|w~}M{|w~E{|w~|X{}v~|t{|u~| xw~} `{|w~|$w" "~} w~} >w~}Dv~ Ov~ !w~}Lw~|M{|w~| <v~nw~}X{|s{}v~}\\{}v~| `{|v~ #{}w~|n{|w~}Z{}w~|{|w~}Uu~|P{}w~}T{|u" "~h{}v~}f{|r~y}v~}r~}d{}w~}hv~|iv~}r{|v~qv~}j{|v~}i{|u~-{}v~}{}w~{|v~} {}w~ {}v~}{}w~{|u~ Cy~}Rv~|S{}~}g{|y~|_v~" "q{}w~|Tw~|T{}w~| {{x~}t{|y}u~}|u{}x~^{}m~} {{x~}wq}y|s{}x~,{}y~}r{}y~}R{}w~H{|x~}Qs~} L{}m~}w{|x~} H{}x~|U{|x~" "}p{|x~}.{}x~|k{|x~}a{}x~|k{|w~cx}u~|n{|x~}#{}w~|{|w~}T{}w~|{|w~}T{}w~|{|w~}T{}w~|{|w~}T{}w~|{|w~}Tv~xv~[v~}w{|v" "~W{|v~}e{|c{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~i{|u~|f{}w~y|v~nv~g{|v~}i{|u~g{|v~}i{|u~g{|v~}i{" "|u~g{|v~}i{|u~g{|v~}i{|u~d{}y~f{}y~|f{|v~}k{|s~f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}b{|v~|r{|v~|^{}i~}|" "\\v~q{}t~| F{}v~| C{~| mw~} gu~}p{}u~|au~}p{}u~|au~}p{}u~|au~}p{}u~|au~}p{}u~|V{|w~Y{}w~}i{}w~} B{" "}w~}Mx~${}n~W{|k~}d{|U~}c{|m~}W{|n~}[w~}kw~}Xt~}X{|w~}mv~cv~| o{|v~| mv~}R{}x~}vw~}Tw~|tw~|^{}v~|x{|y~|u{|~" "|iw~|rw~s{|w~\\v~B{}x~}N{|w~}J{}w~|S{|n~|Q{}w~ b{|w~|Zv~|nv~|V{}w~}E{}w~}M{|v~X{|w~|y{}w~}\\{|w~}M{|v~={}v~^{|" "v~m{}w~}b{|v~lv~| <{|}x~}6{|x~}|7{}w~}cv~|b{|w~}b{|v~xv~[{}w~}l{}w~}bu~|P{}w~}h{}v~}c{}w~}L{}w~}Ru~M{}w~}hv~|Y{" "}w~}M{}w~}W{}w~}t{}u~X{}w~}V{}w~|{}x~}o{|w~|{v~|h{}w~|{v~}ov~gu~|h{}v~|c{}w~}mv~}fu~|h{}v~|e{}w~}mv~}a{|v~C{|v~" "|Z{|v~h{}w~}ev~}j{}v~l{}w~}p{}x~}{|w~ov~|h{|v~}u{}v~[{}v~rv~}M{}v~}Y{|w~}Lw~|F{|w~|Y{}v~|qu~| Kt|Uw~}uu|Mt|Ru|u" "{|w~|Wt|Ow~}Mu|Tw~}uu| Jw~}Dv~Tu|mv|Vu|Pt|Ku|Qu|Bv|Us|Rv~ !w~}Lw~|M{|w~| iv|Sv~o{|w~}N{}v~\\{|t~}|Is|Mu| u{}" "w~| Zt| Lv~|n{|v~[{|v~xv~Tu~P{}w~}T{}v~|gu~g{|t~}|y{|v~x{}t~}e{}w~}hv~|iv~}r{|v~qv~}ju~|h{}v~|/{}v~}y{}w~y{|v" "~}!{}w~!{}v~}y{}w~y{|u~ F{|}y~}x|V{|v~S{}x~}i{|w~|`{}w~|rw~}Sw~|T{|v~|!{}y~}u{|n~}v{}y~}a{|k~} {}y~}vn~}t{}y~}" "-{}y~}r{}y~}R{}w~I{|w~Pt~}| L{}m~}w{|x~} H{}x~|U{|x~}p{|w~.{}x~|kw~|a{}x~|kw~|ct~}lw~|${|v~xv~U{|v~xv~U{|v~xv~U" "{|v~xv~U{|v~xv~U{|w~}x{}w~|]{|v~v{|v~Wu~|L{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~h{|v~}f{}w~|{v~}o" "v~gu~|h{}v~|hu~|h{}v~|hu~|h{}v~|hu~|h{}v~|hu~|h{}v~|f{}w~h{}w~|gu~|l{|r~|g{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~" "h{}w~}a{}v~rv~}]{}g~}]w~}s{|r~|Xt|Nt|Nt|Nt|Nt|Nt|Xt|lu|Ut|Pt|Nt|Nt|Nt| 0{}v~|Pu|Pt|Nt|Nt|Nt|Nt| ut|t{}y~} nw" "~}uu| t{}w~}|wv|v{}v~b{}w~}|m{}v~b{}w~}|m{}v~b{}w~}|m{}v~b{}w~}|m{}v~V{|w~Xv~iv~| C{|v~M{|y~}%{}m~}Wk~}d{|U~}d" "{|k~}Y{}k~|]w~}kw~}Y{|s~X{|v~n{|w~}d{}w~} n{}w~} lv~}R{}x~}vw~}U{|w~t{|w~]v~|w{|y~|`w~|rw~s{}x~|\\v~|C{}x~}" "N{}w~|J{|w~}Q{|r~|O{}w~ b{}w~Z{|v~m{}w~}V{}w~}E{}w~}M{|v~Xw~}x{}w~}\\{|w~}M{}w~}=v~}^{|v~m{}w~}b{|v~lv~} ?{|}u" "~}6{|u~}|:{}w~}d{}w~|`{|w~}c{}w~|x{}w~}\\{}w~}l{}w~}c{|v~}O{}w~}gu~c{}w~}L{}w~}S{|v~}M{}w~}hv~|Y{}w~}M{}w~}W{}w" "~}uu~}W{}w~}V{}w~|{|w~|p{}w~yv~|h{}w~|{|v~ov~h{|v~}fu~c{}w~}mv~}g{|v~}fu~e{}w~}mv~}a{|v~C{|v~|Z{|v~h{}w~}e{}v~j" "v~|l{}w~}pw~|yw~|q{|v~f{}v~|w{|v~|Zv~}t{}v~M{}v~}X{|w~}L{}x~}F{|w~|Z{}v~|o{}v~| P{|}q~}|Xw~}w{}s~}|S{|}q~}|X{}s" "~}|x{|w~|Z{|}r~}|W{}k~}W{}s~}|x{|w~|`w~}w{|s~}|Rv~Lv~Tw~}n{|v~}Xv~_w~}w{}s~}r{|s~}cw~}w{|s~}|V{|}r~}|Yw~}w{}s~}" "|V{}s~}|x{|w~|Zw~}w{}t~|Y{}o~}|Z{}i~]{|w~|m{}w~|c{|v~iv~i{}w~|pu~ow~}hv~}m{|v~|d{|v~iv~`d~Uw~}Lw~|M{|w~| l{|s~" "}|u{}x~}av~o{|w~}M{}w~|\\{}q~}|P{}o~}|\\w~}w{|s~}|^x~y}hv~W{}w~}X{|w~|m{}w~|d{}w~}h{}w~}]{|y}w{|}x~}|]_~|dv~t{}" "w~t{|w~}[{|q~}|U{|y}i~}f{|`~b{|v~lv~|\\{}w~|x{}w~}U{|u~Q{}w~}U{|v~}f{|v~|ht~|w{|v~v{}u~}f{}w~}hv~|iv~}r{|v~qv~}" "k{|v~}fu~/{|w~}x{}w~x{|w~}I{|T{}w~S{|i{|\\w~}x{}w~x{|w~|!v~}O{|}p~}|Y{|v~T{|v~}k{|v~}_v~s{}w~|Sw~|Su~|#{|x~u{}l" "~ux~|bv~}y|v{|x~} !{|x~ul~|ux~|.{|x~|t{|x~|R{}w~J{|w~|L{|}x~}&{|w~|m{}w~|a{}m~}w{|x~} H{}x~|U{|x~}p{|w~.{}x~|l{" "}x~}`{}x~|l{}x~}br~|o{}x~}Qv~|S{}w~|x{}w~}V{}w~|x{}w~}V{}w~|x{}w~}V{}w~|x{}w~}V{}w~|x{}w~}V{}w~|x{|w~}]{}w~}v{|" "v~X{|v~}K{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~gu~|g{}w~|{|v~ov~h{|v~}fu~i{|v~}fu~i{|v~}fu~i{|v~}" "fu~i{|v~}fu~g{|u~j{}v~}h{|v~}l{|w~}v~}g{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}`v~}t{}v~\\{}f~}^w~}t{}v~}y|Y" "{|}q~}|U{|}q~}|U{|}q~}|U{|}q~}|U{|}q~}|U{|}q~}|_{|}q~}|r{|}r~}[{|}q~}|W{|}r~}|T{|}r~}|T{|}r~}|T{|}r~}|Qv~Lv~Lv~" "Lv~O{|y}w~}u~|\\w~}w{|s~}|V{|}r~}|T{|}r~}|T{|}r~}|T{|}r~}|T{|}r~}|Q{}u~Q{|}r~}|x{}x~}b{|w~|m{}w~|a{|w~|m{}w~|a{" "|w~|m{}w~|a{|w~|m{}w~|c{|v~iv~aw~}w{}s~}|^{|v~iv~ W{}w~}u{}w~u{}w~}d{}w~}j{}w~}d{}w~}j{}w~}d{}w~}j{}w~}d{}w~}j{" "}w~}W{}w~X{}w~}k{|v~ C{|v~|M{}y~|&{|k~}X{}l~|cU~}di~|[{}i~|^w~}kw~}Y{}s~|Xv~|o{}w~|dw~} mv~| lv~}R{}x~}vw~}" "^{}Z~f{|w~}v{|y~|`w~|rw~t{|x~}[{}w~}C{}x~}Nv~Hv~O{}v~}M{}w~ bw~}Z{}w~}m{|v~V{}w~}E{}w~}M{|v~Y{}w~w{}w~}\\{|w~}" "Mv~|>{|v~]{|v~m{}w~}b{|w~}l{}w~}W{|v}M{}v~D{}r~}6{|r~}|>{|v~|e{}w~|^{|w~|dv~w{|v~\\{}w~}lv~|c{}v~N{}w~}g{}v~|d{" "}w~}L{}w~}S{}v~L{}w~}hv~|Y{}w~}M{}w~}W{}w~}vu~}V{}w~}V{}w~|yw~}pw~}yv~|h{}w~|y{}w~}pv~h{}v~e{}v~|d{}w~}mv~}g{}v" "~e{}v~|f{}w~}mv~}a{|v~C{|v~|Z{|v~h{}w~}dv~|l{|v~k{|v~q{|w~x{}x~}q{}w~}e{}v~wv~}Y{|v~|v{|v~|N{|v~}W{|w~}L{|w~F{|" "w~|[{}v~l{}v~ S{|}k~|Zw~}y{|o~}V{|k~|\\{|o~}y{|w~|\\{|m~}X{}k~}Y{|o~}y{|w~|`w~}y{|o~}Sv~Lv~Tw~}o{|v~}Wv~_w~}y{|" "o~|v{|o~|ew~}y{|o~}Y{|}n~}|[w~}y{|o~}Y{|o~}y{|w~|Zw~}y{|r~|[{}j~[{}i~]{|w~|m{}w~|b{}w~|k{|w~}i{|w~}q{|u~|q{|w~|" "h{|v~|o{|v~}b{}w~|k{|w~}`d~Uw~}Lw~|M{|w~| n{|o~}vw~|av~o{}w~|M{|v~[{|o~}|U{}k~}]w~}y{|o~}_u~|k{|w~}Wu~X{|w~|m{" "}w~|dv~|h{|v~_{}x~}x{}s~}__~|dv~t{}w~t{|w~}\\{}n~}Y{|}e~}f{|`~b{|w~}l{}w~|\\v~w{|v~T{|u~R{}w~}U{}v~dv~}i{}u~u{|" "v~u{|u~|g{}w~}hv~|iv~}r{|v~qv~|k{}v~e{}v~|c{~}I{|y~}w{}w~w{|y~}I{}~|U{}w~T{}~|k{}~|\\y~}w{}w~w{|y~| v~}P{}k~Z{|" "v~S{|v~}x{|}v~}|y{|v~}^{|w~}u{|w~}Rw~|S{|u~}${}y~|v{}v~}|wy|}y~u{|y~}c{|x~}r{|x~}Q{|q{| W{}y~|uw~vy|v~u{|y~}-w~" "|v{|w~Q{}w~K{|w~|I{|w~'{|w~|m{}w~|a{}m~}w{|x~} H{}x~|U{|x~}p{|x~}]{|q{|X{}x~|m{|w~_{}x~|m{|w~]{|}w~}q{|w~Pv~|Sv" "~w{|v~Vv~w{|v~Vv~w{|v~Vv~w{|v~Vv~w{|v~W{|v~vv~^{|v~|v{|v~X{}v~J{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z" "{|v~g{|v~}g{}w~|y{}w~}pv~h{}v~e{}v~|j{}v~e{}v~|j{}v~e{}v~|j{}v~e{}v~|j{}v~e{}v~|g{|u~l{}v~}g{}v~kw~}{}v~g{|v~h{" "}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}`{|v~|v{|v~|\\{}w~}s|y}t~}_w~}u{|v~|Y{|}k~|Z{|}k~|Z{|}k~|Z{|}k~|Z{|}k~|Z{|" "}k~|d{|}k~|v{|m~}_{|k~|[{|m~}W{|m~}W{|m~}W{|m~}Rv~Lv~Lv~Lv~Q{|}l~\\w~}y{|o~}Y{|}n~}|X{|}n~}|X{|}n~}|X{|}n~}|X{|" "}n~}|S{}u~S{|}n~}{|x~}a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|b{}w~|k{|w~}aw~}y{|o~}^{}w~|k{|w~} X{|w~}" "t{}w~t{|w~}f{|w~}h{|w~}f{|w~}yy|p{|}y{|w~}f{|w~}ly|y{|w~}f{|w~}h{|w~}X{}x~}X{|v~kv~| Cv~|Lx~&{|i~|Y{|m~}bU~|e{}" "h~\\{|u~}|xy|}u~^w~}kw~}Yr~}X{}w~}ov~d{}w~ lv~| lv~}R{}x~}vw~}^{}Z~f{|w~|v{|y~|`w~|s{|w~tw~|[{|v~|D{}x~}Nw~" "}H{}w~|Q{|t~|N{}w~ c{|w~|Zv~|lv~|W{}w~}E{}w~}M{}w~}Z{|w~|w{}w~}\\{|w~}N{|v~={}w~}\\v~|nv~|b{}w~}l{}v~W{}v~M{}v" "~G{|}p~|6{|o~}@u~e{|w~|\\{}w~e{|w~}v{}w~|]{}w~}m{|v~|cv~}N{}w~}g{|v~}d{}w~}L{}w~}Sv~}L{}w~}hv~|Y{}w~}M{}w~}W{}w" "~}x{|u~}U{}w~}V{}w~|y{}w~q{|w~|yv~|h{}w~|y{|v~pv~hv~}e{|v~}d{}w~}mv~}gv~}e{|v~}f{}w~}mv~}a{|v~|D{|v~|Z{|v~h{}w~" "}d{}w~}l{}w~}jv~|r{|w~x{|x~}qv~|e{|v~}y{}v~W{}v~vv~}N{|u~V{|w~}Kw~|G{|w~|\\{}w~}j{}v~ T{}i~}[w~}{}m~}X{}j~|]{}m" "~}{|w~|]{}j~Y{}k~}Z{}m~}{|w~|`w~}{|l~Tv~Lv~Tw~}p{}v~}Vv~_w~}{|m~|x{|m~|fw~}{|m~}[{|j~|\\w~}{}m~}[{}m~}{|w~|Zw~}" "{|q~|\\{}i~[{}i~]{|w~|m{}w~|b{|w~}k{}w~|hw~}q{|u~}q{}w~|g{}v~ov~}a{|w~}k{}w~|`d~Uw~}Lw~|M{|w~| Gy|l{|Z{}m~}x{|w" "~`v~p{|v~Kv~Z{|m~|X{}j~}]w~}{|l~`t~|l{}w~|X{|u~}Y{|w~|m{}w~|e{}v~f{}w~}b{|v~}y{|q~}`_~|dv~t{}w~t{|w~}^{|k~}[{|c" "~}f{|`~b{}w~}l{}w~}]{|w~}vv~|T{|v~}S{}w~}Uv~}d{}v~j{|u~t{|v~t{|u~g{}w~}hv~|iv~}r{|v~r{|v~|kv~}e{|v~}dx~}I{|}v{}" "w~v{|}I{}x~|V{}w~U{}x~|m{}x~|\\{|v{}w~vy| {{v~}R{|i~Z{|v~R{|v~}|q~}|v~}\\v~u{}w~Qw~|R{|t~|'{|y~}v{}w~}p{|t{}y~|" "d{}x~|r{|x~}Ry}r{|~ X{|y~}tw~sw~|u{}y~|.{|w~}x|}w~|Q{}w~L{|w~|G{|x~}({|w~|m{}w~|a{}m~}w{|x~} H{}x~|U{|w~p{|x~}]" "{~|r{|}Y{}x~|mw~|_{}x~|m{}x~|[{|w~|r{}x~|Pv~|T{|w~}v{}w~|X{|w~}v{}w~|X{|w~}v{}w~|X{|w~}v{}w~|X{|w~}v{}w~|X{}w~}" "v{}w~}_{}w~}u{|v~Xv~}J{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~fu~g{}w~|y{|v~pv~hv~}e{|v~}jv~}e{|v~}" "jv~}e{|v~}jv~}e{|v~}jv~}e{|v~}f{|u~n{}v~}fv~}l{}x~}y{|v~|h{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}_{}v~vv~}[" "{}w~}q{|}u~|`w~}uv~W{}i~}[{}i~}[{}i~}[{}i~}[{}i~}[{}i~}e{}i~}x{}k~}a{}j~|\\{}j~Y{}j~Y{}j~Y{}j~Sv~Lv~Lv~Lv~R{}j~" "}]w~}{|m~}[{|j~|Z{|j~|Z{|j~|Z{|j~|Z{|j~|T{}u~T{|f~`{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|b{|w~}k{}w~|a" "w~}{}m~}_{|w~}k{}w~| Xw~}s{}w~s{}w~fw~}f{}w~fw~}y{|y~|r{|y~}y{}w~fw~}l{|y~}y{}w~fw~}f{}w~X{}x~}Wv~|m{|v~ C{}w~}" "[{|}|o{|y~|&g~|Y{}n~|b{}V~e{|g~}]v~}r{|v~}_w~}kw~}Z{|r~}X{|v~p{|w~}dw~} pw|v~l| {{v~}R{}x~}vw~}^{}Z~f{|w~|v" "{|y~|`{}x~}s{|x~}u{}x~}Y{}v~|E{}x~}O{|w~}H{}w~|S{|}r~}|P{}w~ c{|w~Yv~|lv~|W{}w~}Ev~|N{|v~|Zw~}v{}w~}\\{|w~}|}v" "~y}|X{}w~}>{|v~|\\{}w~}o{|v~a{}w~}l{}v~W{}v~M{}v~J{|}p~}|2{|}p~}|D{}v~|e{}x~}p{|}w~}|vx|uw~|f{}w~|v{|w~}]{}w~}m" "{}v~c{|v~|N{}w~}fv~}d{}w~}L{}w~}T{|v~|L{}w~}hv~|Y{}w~}M{}w~}W{}w~}y{|u~}T{}w~}V{}w~|y{|w~|r{}x~}xv~|h{}w~|x{}w~" "}qv~i{|v~|dv~}d{}w~}mv~}h{|v~|dv~}f{}w~}n{|v~|`u~D{|v~|Z{|v~h{}w~}d{|v~m{|v~|j{}w~}r{}x~}x{|w~qv~|d{}v~y|v~|Vv~" "}x{}v~Mu~|V{|w~}K{}x~}G{|w~|]{}w~}h{|v~ U{}u~v}s~}\\w~}|v~w}t~}Zr~v}v~|^{}t~w}v~}|w~|^{}t~v}t~Zv}v~s}[{}t~w}v~}" "|w~|`w~}|u~x}t~}Uv~Lv~Tw~}q{}v~|Uv~_w~}|v~x}s~y{|v~x}s~fw~}|u~x}t~}]{|s~x}s~|]w~}|v~w}t~}]{|t~w}v~}|w~|Zw~}|t~}" "x~|]{}t~u}u~[{|x}v~q}]{|w~|m{}w~|av~kv~g{}w~q{}t~qv~e{}v~q{}v~_v~|m{|v~_d~Uw~}Lw~|M{|w~| J{|}v~}r{}v~}|_{}u~w}u" "~|y{}x~}`v~q{|v~}K{}w~|\\{}w~}p~}Z{}s~w}u~}]w~}|u~x}t~}as~m{|v~W{}t~Y{|w~|m{}w~|ev~|f{|v~c{|u~}yn~a_~|dv~t{}w~t" "{|w~}_{|t~w}t~}]{|b~}f{|`~b{}w~|l{}w~}]{}w~|v{|w~}S{|v~}T{}w~}Uv~|d{|v~|k{}v~|t{|v~s{}v~|h{}w~}hv~|i{}w~}r{|v~r" "{|v~|l{|v~|dv~}ev~}C{}w~C{}v~|W{}w~V{}v~n{|v~|W{}w~ sv~}S{|s~}y~x}v~Z{|v~Q{|e~}[{|w~}w{|w~}Qw~|R{}r~|){}y~|w{|w" "~}g{|y~}dw~q{}x~}S{}~}s{}y~ X{}y~|tw~s{}x~}u{|y~}-{}p~}P{}w~M{|w~|F{|x~}({|w~|m{}w~|a{}m~}w{|x~} H{}x~|Tw~p{}x~" "|]y~}s{|y~Z{}x~|n{|x~}^{}x~|n{|w~Y{|x~}s{|x~}Ov~|T{}w~|v{|w~}X{}w~|v{|w~}X{}w~|v{|w~}X{}w~|v{|w~}X{}w~|v{|w~}Xv" "~u{|v~_v~|u{|v~Y{|v~|J{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~f{}v~g{}w~|x{}w~}qv~i{|v~|dv~}k{|v~|d" "v~}k{|v~|dv~}k{|v~|dv~}k{|v~|dv~}e{|u~p{}v~}f{|v~|m{}w~wv~}h{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}^v~}x{}v" "~Z{}w~}o{}v~}`w~}v{|w~|W{}u~v}s~}\\{}u~v}s~}\\{}u~v}s~}\\{}u~v}s~}\\{}u~v}s~}\\{}u~v}s~}f{}u~v}s~}{s~w}t~}cr~v}" "v~|]{}t~v}t~[{}t~v}t~[{}t~v}t~[{}t~v}t~Tv~Lv~Lv~Lv~S{}h~|^w~}|u~x}t~}]{|s~x}s~|\\{|s~x}s~|\\{|s~x}s~|\\{|s~x}s~" "|\\{|s~x}s~|U{}u~U{|s~x}q~|`{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|av~|m{|v~`w~}|v~w}t~}_v~|m{|v~ X{|w~" "r{}w~rw~}h{|w~dw~}h{|w~y{|w~|t{|w~}yw~}h{|w~l{|w~}yw~}h{|w~dw~}Y{}x~}W{}w~}m{}w~} Xg|}v~s|e{|}x~}o{}y~&{}f~Y{|o" "~}a{|V~f{|e~}_{|w~}p{|v~_w~}kw~}Z{}w~}v~Wv~|q{}w~}e{|w~ pc~} {{v~}R{|x}|v{|x}|^{}Z~f{|w~|v{|y~|`{|w~s{}x~}v" "{|w~Wu~|F{|x}|O{}w~|H{|w~}U{|}w~|x~|w~}|R{}w~ c{}x~}Yv~|lv~|W{}w~}F{|v~N{|v~}Z{}w~u{}w~}\\{|k~}Z{}w~}x{|}u~y}|" "L{}v~Zv~|pv~}a{|v~l{}v~|X{}v~M{}v~M{|}p~}|,{|}p~}|H{}v~|e{|w~q{|q~}y{}x~|v{|x~}fv~tv~]{}w~}n{}v~|c{|v~|N{}w~}f{" "}v~d{}w~}L{}w~}T{}v~|L{}w~}hv~|Y{}w~}M{}w~}W{}w~}{|u~}S{}w~}V{}w~|xw~}rw~|xv~|h{}w~|x{|v~|rv~i{|v~|d{}v~d{}w~}n" "{|v~|h{|v~|d{}v~f{}w~}n{}v~|`{}v~}|F{|v~|Z{|v~h{}w~}cv~|n{}v~i{}w~}rw~|ww~|s{|v~b{}q~}U{|v~|{|v~|N{}v~|U{|w~}K{" "|w~G{|w~|^{}w~}f{|v~ V{}y~}|r{|u~|]r~|u{|u~}\\{}u~}s{|}y~|_{|u~|u{|}s~|_{}v~}|t{}v~}Vw~}T{|u~|u{|}s~|`r~|u{|u~|" "Vv~Lv~Tw~}ru~|Tv~_r~|v{|}v~}{w~|u{}v~}gr~|u{|u~|^u~}|v{|}u~]r~|u{|u~|_{|u~|u{|}s~|Zr~}|v{|\\v~}|r{|}y~Wv~S{|w~|" "m{}w~|a{}w~|m{|w~}g{}w~|rs~qw~}dv~}s{|v~|_{}w~}m{}w~|Nu~Uw~}Lw~|M{|w~| K{}r~u{|r~}a{|v~}|v{}v~yw~|`v~r{|u~|K{|w" "~|]{}w~|xy|}t~}[u~}|s{|}~}]r~|u{|u~|ay|v~|n{}w~|X{|s~|Z{|w~|m{}w~|f{|v~dv~|e{|u~}|{|v~y|}v~}bx}u~q}u~x}|dv~t{}w" "~t{|w~}_u~|u{|u~|_{|u~}|v{|}t~v}f{|q}u~p}b{}w~|l{|v~]v~tv~R{}v~}U{}w~}V{|v~|cv~}l{|v~}s{|v~s{|v~}h{}w~}hv~|i{}v" "~r{|v~r{|v~|l{|v~|d{}v~fu~|C{}w~C{|u~|X{}w~W{}v~}m{}v~|X{}w~ sv~}T{|u~}|yy~}x{|}y~Z{|v~P{|g~}Y{}w~|xv~Pw~|T{|v~" "}u~}*x~v{}w~ex~dw~qw~}U{|x~}t{}x~ Xx~sw~s{}x~}tx~,{|r~|O{}w~N{|w~|Dw~({|w~|m{}w~|a{|m~}w{|x~} H{}x~|T{}x~}qw~|]" "x~}t{|x~|\\{}x~|nw~]{}x~|nw~|Xw~sw~|Ov~|Tv~tv~Xv~tv~Xv~tv~Xv~tv~Xv~tv~Y{|w~}tv~|a{|v~t{|v~Y{|v~|J{}w~}M{}w~}M{}" "w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~f{|v~|h{}w~|x{|v~|rv~i{|v~|d{}v~k{|v~|d{}v~k{|v~|d{}v~k{|v~|d{}v~k{|v~|d{" "}v~d{|u~r{}v~}e{|v~|n{}w~v{}v~h{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}^{|v~|{|v~|Z{}w~}nu~`w~}v{}w~V{}y~}|r" "{|u~|]{}y~}|r{|u~|]{}y~}|r{|u~|]{}y~}|r{|u~|]{}y~}|r{|u~|]{}y~}|r{|u~|g{}y~}|r{|o~}|u{|}v~}e{}u~}s{|}y~|^{}v~}|" "t{}v~}]{}v~}|t{}v~}]{}v~}|t{}v~}]{}v~}|t{}v~}Uv~Lv~Lv~Lv~T{}u~}|v{|}v~}^r~|u{|u~|^u~}|v{|}u~\\u~}|v{|}u~\\u~}|v" "{|}u~\\u~}|v{|}u~\\u~}|v{|}u~U{}u~Uu~}|u{}u~|_{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|a{}w~}m{}w~|`r~|u{" "|u~|`{}w~}m{}w~| Xw~|r{}w~r{|w~hw~|d{|w~hw~|yu~|v{|u~y{|w~hw~|m{|u~y{|w~hw~|d{|w~Y{}x~}Vv~mv~| XZ~}g{}t~oy~}'{}" "e~}Y{}p~_W~|fc~|`v~n{}w~|`w~}kw~}Zv~|}w~|X{}w~}qv~|e{}x~} q{|c~| {{v~} y{|x~}t{}x~}]{|w~}v{|y~|_w~|u{|w~|vw" "~|Wt~ p{}w~|H{|v~V{}w~}yx~y{}w~}S{}w~ cw~|Z{|v~k{}w~}W{}w~}Fv~}Qy|u~}Z{|w~|u{}w~}\\{|i~|\\v~|y{}p~}|Nv~}Z{|v~|" "s{|v~}`{|v~lu~|X{}v~M{}v~P{|}p~}|b{|Z~}b{|}p~}|L{}v~}d{}x~|r{|n~{}x~|uw~|h{}w~}t{}w~|^{}w~}q{|}u~}b{}v~M{}w~}f{" "}v~d{}w~}L{}w~}T{}v~K{}w~}hv~|Y{}w~}M{}w~}W{}w~}|u~}R{}w~}V{}w~|x{|w~s{}w~wv~|h{}w~|w{}w~}rv~i{}v~c{}v~d{}w~}n{" "}v~|h{}v~c{}v~f{}w~}o{|u~_{|t~}|H{|v~|Z{|v~h{}w~}c{}v~nv~}i{|v~s{|w~|w{}x~}s{}w~}b{|q~S{}v~|v~}N{}v~}T{|w~}K{|w" "~|H{|w~| s{}|m{}w~}]t~}q{}v~|^{}v~}ny|_u~q{}t~|`{|v~|q{|v~|Ww~}Tu~q{|t~|`t~}r{|v~}Vv~Lv~Tw~}t{|u~Rv~_t~}r{}v~}" "y~}r{}v~gt~}r{|v~}_{}v~|r{|v~}^s~q{}v~_{}v~|r{}t~|Zs~T{|w~}m{|Wv~S{|w~|m{}w~|a{|w~}mv~|g{|w~}s{|s~|s{|w~|d{|v~|" "u{|v~}]v~mv~N{}v~Tw~}Lw~|M{|w~| L{}p~w{|p~}bv~}s{}w~y|w~_v~wx|}t~}J{|w~}^{}w~r{}u~|]{|v~|Ot~}r{|v~}_{|v~nv~W{}s" "~}Z{|w~|m{}w~|f{}w~}d{}w~}eu~}x{|w~|x{}v~|`{|w~}q{|w~}`v~t{}w~t{|w~}`{}v~q{}v~_u~}r{|v~}V{|w~}Wv~|l{|v~^{}w~}t{" "}w~|R{}v~}V{}w~}V{|v~bv~}l{|v~|s{|v~r{}v~h{}w~}hv~|i{}v~r{|v~r{}v~k{}v~c{}v~gu~|B{}w~B{|u~|Y{}w~X{}v~}k{}v~|Y{}" "w~ sv~}Tu~|wy~}u{|Z{|v~O{|u~}|x{|}v~}_{|p~}y{|p~}Ww~|Tw~}y{|t~|,y~}vw~|e{}y~dw~|s{}w~}V{|w~}u{}w~ Xy~}sw~s{}x~}" "t{}y~*y}x~}|[m|}w~l|^{}w~C{|x~}({|w~|m{}w~|`m~}w{|x~} H{}x~|T{|w~|s{}x~}\\w~}u{|w~|]{}x~|o{}x~}]{}x~|o{}x~}Ww~t" "{}x~}Nv~|U{}w~}t{}w~|Z{}w~}t{}w~|Z{}w~}t{}w~|Z{}w~}t{}w~|Z{}w~}t{}w~|Z{}w~|t{|w~}av~}t{|v~Y{}v~I{}w~}M{}w~}M{}w" "~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~f{|v~|h{}w~|w{}w~}rv~i{}v~c{}v~k{}v~c{}v~k{}v~c{}v~k{}v~c{}v~k{}v~c{}v~c{|" "u~t{}v~}d{}v~n{|w~|v{|v~h{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}]{}v~|v~}Y{}w~}n{|v~|aw~}vv~V{}|m{}w~}]{}|m" "{}w~}]{}|m{}w~}]{}|m{}w~}]{}|m{}w~}]{}|m{}w~}g{}|m{}r~|q{|v~|g{}v~}ny|_{|v~|q{|v~|_{|v~|q{|v~|_{|v~|q{|v~|_{|v~" "|q{|v~|Vv~Lv~Lv~Lv~U{|v~}q{|v~|_t~}r{|v~}_{}v~|r{|v~}^{}v~|r{|v~}^{}v~|r{|v~}^{}v~|r{|v~}^{}v~|r{|v~}V{}u~V{}v~" "|r{|v~}_{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|`v~mv~_s~q{}v~_v~mv~ X{|w~q{}w~q{}x~|j{|w~b{}x~|j{|w~wu~" "|x{|u~|x{}x~|j{|w~m{|u~|x{}x~|j{|w~b{}x~|Z{}x~}V{}w~|o{|v~ WZ~}gx~}w~|q{}y~|({|c~}_v|{}r~u|d{}X~f{}b~|b{|w~}mw~" "}`w~}kw~}[{|v~{}w~}X{|w~}r{|v~d{}x~| q{}c~ yv~} y{}x~}t{}x~}\\v~}w{|y~|_{}w~|vw~}v{|x~}X{|r~ qv~Fv~X{}w~}|x" "x~x{|}w~}U{}w~ d{|w~Y{|v~k{}w~}W{}w~}G{}v~|Xm~}Y{}x~}t{}w~}\\{|h~}]v~y|l~}P{|v~|Y{|u~u|}v~}_{|v~|n{|u~|X{}v~M{" "}v~R{|o~}|`{|Z~}_{|}p~}|P{}v~}cw~r{|l~}x~|u{|x~|hv~|t{|v~^{}e~}a{}v~M{}w~}f{|v~|e{}d~|_{}g~|d{}v~K{}^~|Y{}w~}M{" "}w~}W{}p~|Q{}w~}V{}w~|ww~|tw~}wv~|h{}w~|vv~|sv~i{}v~c{|v~|e{}w~}o{|u~g{}v~c{|v~|g{}w~}p{|u~|^{}q~y}|M{|v~|Z{|v~" "h{}w~}c{|v~|p{|v~gv~|t{|w~v{|x~}sv~|a{|s~|Rq~}N{}v~}S{|w~}Jw~}H{|w~| bv~|^t~ov~}^v~}P{|v~|p{}u~|`v~|o{|v~Ww~}U" "{|v~o{}u~|`u~}p{|v~Vv~Lv~Tw~}u{|v~}Qv~_u~}pt~}pv~|hu~}p{|v~`{|v~|p{|v~|_t~ov~}a{|v~|p{}u~|Zt~S{}w~Gv~S{|w~|m{}w" "~|`v~|o{|v~ev~s{|x~y}x~}s{}w~|c{}v~uv~}\\{}w~|o{|w~}O{}v~|U{|w~}Lw~|M{|w~} M{|x~}x|}w~}xv~}x|}x~|d{}v~qw~y}x~}_" "v~x{}q~}I{|w~}_{|w~|q{|u~]{}w~|Nu~}p{|v~^{}w~|p{|w~}X{|q~Z{|w~|m{}w~|fv~|d{|v~f{|v~}w{}w~|wu~`{|w~}q{|w~}`v~t{}" "w~t{|w~}a{|v~ov~}a{|v~}p{}v~|W{|w~}Wv~}l|}v~^v~|t{|v~Q{}v~}W{}w~}V{|v~b{}w~}l{}v~r{|v~r{}v~|i{}w~}hv~|i{|v~|s{|" "v~r{}v~k{}v~xi~}y{|v~|iu~|A{}w~A{|u~|Z{}w~Y{}v~}i{}v~|Z{}w~ sv}|U{}v~|vy~}S{|v~O{|w~}s{|v~_{|o~|{o~}Ww~|U{}x~}v" "{}u~}.{|y~|w{|w~d{|y~|e{}w~t{}v~}W{|v~|v{}w~}cY|8{|y~|sw~sw~|t{|y~| `{|Z~}_{}x~}C{|w~}({|w~|m{}w~|`{|n~}w{|x~} " "H{}x~|Sv~|u{}w~|\\{}v~v{|v~|^{}x~|p{|w~\\{}x~|p{|w~W{|x~}u{|w~Mv}|Uv~|t{|v~Zv~|t{|v~Zv~|t{|v~Zv~|t{|v~Zv~|t{|v~" "Zv~rv~b{|v~s{|c~l{}v~I{}d~|`{}d~|`{}d~|`{}d~|W{}w~}M{}w~}M{}w~}M{}w~}Z{|v~ev~}h{}w~|vv~|sv~i{}v~c{|v~|l{}v~c{|v" "~|l{}v~c{|v~|l{}v~c{|v~|l{}v~c{|v~|c{|u~v{}v~}c{}v~o{|w~|u{|v~|i{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}\\q~" "}X{}w~}mv~}aw~}vv~Ev~|Mv~|Mv~|Mv~|Mv~|Mv~|Ws~|o{}w~}gv~}Ov~|o{|v~_v~|o{|v~_v~|o{|v~_v~|o{|v~Vv~Lv~Lv~Lv~Uv~}o{}" "w~}_u~}p{|v~`{|v~|p{|v~|`{|v~|p{|v~|`{|v~|p{|v~|`{|v~|p{|v~|`{|v~|p{|v~|Wt|W{|v~|q{}u~|`{|w~|m{}w~|a{|w~|m{}w~|" "a{|w~|m{}w~|a{|w~|m{}w~|`{}w~|o{|w~}_t~ov~}`{}w~|o{|w~} X{}x~}q{}w~q{|x~}j{}x~}b{|x~}j{}x~}vu~|yu~|w{|x~}j{}x~}" "mu~|w{|x~}j{}x~}b{|x~}Z{}x~}V{|v~o{}w~} WZ~}g{}|yw~}qx~'a~|c{|}t~}k~}|fY~}g{}`~b{|w~|m{}w~`w~}kw~}[{|w~}{|v~Wv~" "r{}w~}dw~| lv~| kv~| yw~|tw~|\\{}v~}|y{|y~|^v~}y|}v~uw~X{|p~ rv~Fv~Xw~|vx~v{|w~U{}w~ d{}x~}Y{|v~k{}w~}W{}w" "~}H{|v~}Wo~}|Y{|w~|t{}w~}\\{|v~x}|x}s~}^v~|j~}Q{}w~}V{}l~}]v~}n{}u~}X{}v~M{|v}U{|}p~}|]{|Z~}\\{}o~|S{}v~}c{|x~}" "rv~}|w{|}t~|tx~}i{|v~rv~|_{}h~}|_v~}M{}w~}f{|v~|e{}d~|_{}g~|dv~}K{}^~|Y{}w~}M{}w~}W{}q~|P{}w~}V{}w~|w{}w~u{|w~|" "wv~|h{}w~|v{}w~}sv~iv~}c{|v~|e{}w~}p{|u~|gv~}c{|v~|g{}w~}sy|}u~}\\{}m~}|Q{|v~|Z{|v~h{}w~}bv~}p{}w~}g{}w~}t{}x~}" "v{|w~sv~|`{}u~}Q{|r~|O{|u~R{|w~}J{}w~H{|w~| b{|w~}^u~|o{|v~_{}v~Ov~}nu~|a{}w~}m{}w~|Xw~}Uv~|nu~|`u~nv~|Wv~Lv~T" "w~}v{}v~}Pv~_u~o{}u~|p{}w~}hu~nv~|a{}w~}n{}w~}_u~|o{|v~a{}w~}nu~|Zu~|S{}w~Gv~S{|w~|m{}w~|`{}w~}o{}w~}e{}w~s{}x~" "}|w~sv~a{}v~w{}v~[{|w~}ov~|P{}v~|T{|w~}Lw~|M{|w~}:{|4x~|v{|w~}{}x~}u{}x~dv~}q{}s~|_v~x{}r~}S{|y}~y}|w{|w~}_w~}o" "{|v~}^{}w~Mu~nv~|_{|w~}pv~|X{}w~}v~|[{|w~|m{}w~|g{|v~bv~|g{}v~v{}w~v{|v~|a{|w~}q{|w~}`v~t{}w~t{|w~}a{}w~|o{|v~a" "{}v~nv~}W{|w~}W`~_{|v~rv~|Q{}v~|X{}w~}V{|v~b{}w~}lu~r{|v~r{|v~|i{}w~}hv~|hv~}s{|v~rv~}kv~}xi~}y{|v~|ju~|@{}w~@{" "|u~|[{}w~Z{}v~}g{}v~|[{}w~ Gv~}uy~}S{|v~Ow~}q{|w~|`{|n~}o~}Ww~|Uw~|t{}u~|0{|y~|w{|x~}d{|y~|e{|v~}w|t~}X{|v~|vv~" "}c{|Z~}8{|y~|sw~t{}w~s{|y~| `{|Z~}`{}x~}M{|~}|v{|}v~'{|w~|m{}w~|_{}o~}w{|x~}Vv}| s{}x~|S{|v~}|{y|}w~}Z{}v~|w{|v" "~}_{}x~|pw~|o{}w~m{}x~|p{}x~|vy|}w~y}|g{|w~|u{}x~|o{}w~3{|v~rv~|\\{|v~rv~|\\{|v~rv~|\\{|v~rv~|\\{|v~rv~|\\{}w~}" "r{}w~|c{}w~}s{|c~lv~}I{}d~|`{}d~|`{}d~|`{}d~|W{}w~}M{}w~}M{}w~}M{}w~}_{}i~}nv~}h{}w~|v{}w~}sv~iv~}c{|v~|lv~}c{|" "v~|lv~}c{|v~|lv~}c{|v~|lv~}c{|v~|b{|u~x{}v~}bv~}p{|w~}t{|v~|i{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}\\{|r~|" "X{}w~}mv~}aw~}v{}w~}F{|w~}M{|w~}M{|w~}M{|w~}M{|w~}M{|w~}W{|u~}m{}w~h{}v~O{}w~}m{}w~|a{}w~}m{}w~|a{}w~}m{}w~|a{}" "w~}m{}w~|Wv~Lv~Lv~Lv~V{}v~n{|v~_u~nv~|a{}w~}n{}w~}`{}w~}n{}w~}`{}w~}n{}w~}`{}w~}n{}w~}`{}w~}n{}w~},{}w~}q{}t~}`" "{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|`{|w~}ov~|_u~|o{|v~`{|w~}ov~| X{}x~|q{}w~q{|w~j{}x~|b{|w~j{}x~|u" "u~|u~|v{|w~j{}x~|nu~|v{|w~j{}x~|b{|w~Zw~}Uv~|q{|v~ VZ~}c{}w~r{|y~}({}`~d{}^~|h{|Z~g{|_~}c{}w~l{|w~`w~}kw~}[{}w~" "|yv~|X{}w~|sv~|dV~} 2v~| k{}w~| {{|w~t{|w~Zs~y}y~|^{|o~|v{}x~}rx|e{|v~y}u~n{|w~},{|v~Fv~|Y{|~}tx~t{}~|U{}w~ " " dw~|Y{|v~k{}w~}W{}w~}Hu~Vp~}|Y{|w~}s{}w~}\\{|~}|q{}t~|`{|q~}|xy|t~|Rv~|U{|}p~|[{}v~|ot~} V{|}p~}|Z{|Z~}Z{|}p~}" "|W{}v~|b{}x~|s{}w~|s{|u~|tw~i{}w~}r{}w~}_{}g~}|`v~}M{}w~}f{|v~|e{}d~|_{}g~|dv~}K{}^~|Y{}w~}M{}w~}W{}q~O{}w~}V{}" "w~|w{|w~|v{}w~vv~|h{}w~|uv~|tv~iv~}c{|v~|e{}w~}sy|s~fv~}c{|v~|g{}f~}Z{}k~}S{|v~|Z{|v~h{}w~}b{|v~pv~|g{}w~}tw~|u" "w~|u{|v~_{}u~O{}t~|O{|u~|R{|w~}J{|w~|I{|w~| aw~}^v~}m{}w~}`v~|P{|v~m{}v~|av~l{|w~}Xw~}V{|v~m{|v~|`v~}n{}w~|Wv~" "Lv~Tw~}w{}v~}Ov~_v~}o{|v~}o{|w~}hv~}n{}w~|av~|n{|v~|`u~mv~|bv~m{}v~|Zv~}R{}w~Gv~S{|w~|m{}w~|`{|v~ov~d{}w~|tw~|{" "w~|u{|w~}`v~}y{|v~|Z{}w~|q{|v~P{}v~|Sv~|Lw~|Lv~|W{|y}w~}|iy}5{|y~}sw~|x~}s{}y~|f{|v~|ps~^v~x{}q~}|W{|r~|y{|w~}`" "{}w~m{}v~^{}w~Mv~}n{}w~|^{}w~q{|v~Wv~y|w~}[{|w~|m{}w~|g{}v~b{}w~}h{|v~|v{}w~u{}w~}a{|w~}q{|w~}`v~t{}w~t{|w~}av~" "mv~|c{|v~|n{|v~W{|w~}W`~_{}w~}r{}w~}Q{|v~}X{}w~}V{|v~b{}w~}lv~}r{|v~r{|v~|i{}w~}hv~|h{}v~s{|v~s{|v~|kv~}xi~}y{|" "v~|ku~|?{}w~?{|u~|\\{}w~[{}v~}e{}v~|\\{}w~ H{}v~ty~}S{|v~P{|w~o{}w~_s|}r~s|Vw~|V{|w~r{|u~0{|y~v{}x~}d{|y~|d{}o~" "|x~}Y{}v~v{|v~|b{|Z~}8{|y~rw~u}v~|s{|y~| `{|Z~}a{}l~|X{|m~|'{|w~|m{}w~|^o~}w{|x~}W{|v~| xm~}W{|n~}X{|v~|vv~}e{}" "n~}v{}x~}o{|v~m{}x~|q{|w~w{|o~|t{|~}y|w{|}v~u{|x~}o{|v~3{}w~}r{}w~}\\{}w~}r{}w~}\\{}w~}r{}w~}\\{}w~}r{}w~}\\{}w" "~}r{}w~}\\v~|r{|w~}cv~|s{|c~lv~}I{}d~|`{}d~|`{}d~|`{}d~|W{}w~}M{}w~}M{}w~}M{}w~}_{}i~}nv~}h{}w~|uv~|tv~iv~}c{|v" "~|lv~}c{|v~|lv~}c{|v~|lv~}c{|v~|lv~}c{|v~|a{|u~|}v~}av~}pw~}s{|v~|i{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}[" "{}t~|W{}w~}mv~}aw~}v{}v~|Fw~}Lw~}Lw~}Lw~}Lw~}Lw~}Vu~l{|w~|iv~|Ov~l{|w~}av~l{|w~}av~l{|w~}av~l{|w~}Wv~Lv~Lv~Lv~V" "v~|mv~|`v~}n{}w~|av~|n{|v~|av~|n{|v~|av~|n{|v~|av~|n{|v~|av~|n{|v~|-v~|r{|x~}v~`{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{" "}w~|a{|w~|m{}w~|_{}w~|q{|v~^u~mv~|`{}w~|q{|v~ Ww~p{}w~pw~jw~yd|yw~jw~t{|p~|tw~jw~nu~|tw~jw~pv~}qw~Zw~|U{}w~}q{}" "w~} F{}w~}W{|w~|s{}y~|){|_~}f{}\\~|h{}\\~|g{}^~c{}w~l{|w~|aw~}kw~}[v~x{}w~}X{|w~}t{|v~cV~} 2v~| k{}w~| {{|x~" "}t{|x~}Z{|o~}y|`{|}r~|v{|w~t{}u~}|hv~}y{}u~o{|w~|,{|v~F{}w~|X{|sx~s{|T{}w~ e{|w~X{|v~k{}w~}W{}w~}Iu~|Vm~|[{}w~" "r{}w~}L{}u~`{|r~|s{|u~S{}v~V{|}m~}|\\u~p{}t~} Y{|}p~}|VY|W{|}p~}|[{|v~|aw~rw~}q{|v~|t{}x~iv~q{|v~_{}e~}av~}M{}w" "~}f{|v~|e{}d~|_{}g~|dv~}m{}n~|h{}^~|Y{}w~}M{}w~}W{}q~}P{}w~}V{}w~|vw~}vw~}vv~|h{}w~|u{}v~tv~iv~}bv~|e{}e~|fv~}b" "v~|g{}g~}X{|}k~}U{|v~|Z{|v~h{}w~}av~|r{|v~f{|v~u{|w~|u{}x~}u{}w~}`{|t~|O{}v~}Nu~|Q{|w~}Iw~}I{|w~| a{}w~^v~|m{|" "w~}a{|v~O{|w~}lv~|b{|w~}kv~Xw~}V{|w~}lv~|`v~|n{|w~}Wv~Lv~Tw~}x{}v~|Nv~_v~|nv~|nv~hv~|n{|w~}b{|v~lv~|`v~}m{|w~}c" "{|w~}m{|v~|Zv~|R{}w~|Hv~S{|w~|m{}w~|_{}w~|q{|w~}d{|w~}u{|w~y{}x~|u{|w~|`{|v~y|v~}Y{|w~}q{}w~|Q{|v~}S{}v~Kw~|L{}" "w~}Y{|p~}|n{|y~}5{}y~r{|t~qy~}f{}v~ot~}^v~x{}o~}Y{}p~|{|w~|`w~}lv~|_{|w~}Nv~|n{|w~}^{|w~|r{}w~|X{}w~}yv~[{|w~|m" "{}w~|gv~}b{}v~h{|v~u{}w~u{|v~a{|w~}q{|w~}`v~t{}w~t{|w~}b{|w~}m{|w~}c{|v~lv~|X{|w~}W`~_v~|r{|v~Qu~W{}w~}V{|v~b{}" "w~}lv~}r{|v~qv~|i{}w~}hv~|h{|v~|t{|v~s{}v~jv~}xi~}xv~|lu~[|]{}w~\\\\|u~|]{}w~\\{}v~}c|u~|]{}w~ H{}w~}ty~}X{}g~|" "[{}x~}nw~Vs~|Nw~|V{}x~}pv~}1{}y~v{}x~}d{|y~}c{}r~}{|x~}Z{}w~}v{|v~|a{|Z~}8{}y~rn~}q{|y~} `{|Z~}a{}l~|X{|o~}|&{|" "w~|m{}w~|]{}q~}w{|x~}W{|v~| xm~}V{|}q~|V{|v~|v{}w~}fm~}vw~o{|u~rm~}vw~|w{}n~|u{|m~|uw~|p{|u~3v~q{|v~\\v~q{|v~\\" "v~q{|v~\\v~q{|v~\\v~q{|v~]{|v~pv~|e{}w~}r{|c~lv~}I{}d~|`{}d~|`{}d~|`{}d~|W{}w~}M{}w~}M{}w~}M{}w~}_{}i~}nv~}h{}w" "~|u{}v~tv~iv~}bv~|lv~}bv~|lv~}bv~|lv~}bv~|lv~}bv~|`{|p~}`v~}q{}x~}qv~|i{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}" "w~}Z{}v~}V{}w~}mv~}aw~}uu~}G{}w~L{}w~L{}w~L{}w~L{}w~L{}w~V{}w~}kw~}j{|v~O{|w~}kv~b{|w~}kv~b{|w~}kv~b{|w~}kv~Wv~" "Lv~Lv~Lv~W{|v~l{}w~}`v~|n{|w~}b{|v~lv~|b{|v~lv~|b{|v~lv~|b{|v~lv~|b{|v~lv~|.{|v~r{|w~{}w~|a{|w~|m{}w~|a{|w~|m{}" "w~|a{|w~|m{}w~|a{|w~|m{}w~|_{|w~}q{}w~|^v~}m{|w~}`{|w~}q{}w~| Ww~yd~|{w~jw~yd~|{w~jw~s{|r~|sw~jw~ou~|sw~jw~pv~}" "qw~Zw~|U{|v~qv~| G{}w~}Uw~}sx~({}^~g{}Z~g]~}f{|_~|cw~}l{|w~|aw~}kw~}\\{|v~x{|v~Wv~t{}w~}cV~} 2v~| k{}w~| {{}" "x~}t{}x~}Y{|}m~}`{|}w~}|tw~|v{|q~}j{}v~w{}u~p{}w~|,{|w~}F{}w~|Ox~Z{|Z~} t{}x~}X{|v~k{}w~}W{}w~}J{}v~|Ut|}t~}]{" "|w~|r{}w~}K{}v~|a{|s~p{|v~}Tv~}W{}i~}]{}u~|t{|}s~} Z{|q~}| e{|}q~}\\v~}`x~}s{}w~ov~|t{}x~|k{|w~}p{}w~|`{}w~}p|}" "t~|cv~}M{}w~}f{|v~|e{}w~}i|^{}w~}l|cv~}m{}n~|h{}w~}h|v~|Y{}w~}M{}w~}W{}w~}u~}Q{}w~}V{}w~|v{}w~w{|w~uv~|h{}w~|tv" "~|uv~iv~}c{|v~|e{}f~|ev~}c{|v~|g{}i~}S{|}m~}V{|v~|Z{|v~h{}w~}a{}w~}rv~}ev~|v{|w~t{|w~uv~|`r~O{|v~|O{}v~}P{|w~}I" "{}w~I{|w~| a{}w~^v~|lv~a{}w~}O{}w~|lv~|b{|w~|k{}w~Xw~}V{}w~|lv~|`v~m{|w~}Wv~Lv~Tw~}yu~|Mv~_v~mv~mv~hv~m{|w~}b{" "}w~}l{}w~}`v~|m{|v~c{}w~|lv~|Zv~Q{}v~|Iv~S{|w~|m{}w~|_{|w~}q{}w~|cv~u{}x~}y{}x~}u{}w~^{}q~}Wv~qv~Q{|v~}Uy|}v~|K" "w~|L{|u~}|^{|k~}|s{|}x~}5y~}q{}v~|q{}y~f{}w~}o{}u~|^v~ty|}s~[{|u~y}v~y|w~|a{|w~}l{}w~}^{}w~|Ov~m{|w~}]w~}rv~Wv~" "|y{}w~}\\{|w~|m{}w~|gv~|b{|v~h{}w~}u{}w~tv~a{|w~}q{|w~}`v~t{}w~t{|w~}b{}w~|m{|v~c{}w~}l{}w~}X{|w~}W`~`{|w~}pv~|" "S{}v~|W{}w~}V{|v~bv~}lv~}r{|v~r{|v~|i{}w~}hv~|gu~t{|v~t{|v~}jv~}xh|y{|v~|mT~]{}w~]T~|^{}w~]{}U~|^{}w~ Hv~|ty~}X" "{}g~|[w~|nw~|W{}u~}Mw~|V{}w~ov~1{|y~v{}x~}d{|y~|ay}x~y}ww|[{}w~}v{|v~|`{|Z~}8{|y~ro~o{|y~| Q{}w~R{}l~|V{|y}v~y}" "|${|w~|m{}w~|\\{|}s~}w{|x~}W{|v~| xm~}T{|y}w~}|S{|v~|v{}w~}gm~}w{}x~}oy~y}x~rm~}w{}x~}v{}~}y|w{|v~u{|o~}t{}x~}o", "t~^v|V{|w~}p{}w~|^{|w~}p{}w~|^{|w~}p{}w~|^{|w~}p{}w~|^{|w~}p{}w~|^{}w~}p{}w~}ev~|r{|v~h|lv~}I{}w~}i|_{}w~}i|_{}" "w~}i|_{}w~}i|V{}w~}M{}w~}M{}w~}M{}w~}_v}u~r}nv~}h{}w~|tv~|uv~iv~}c{|v~|lv~}c{|v~|lv~}c{|v~|lv~}c{|v~|lv~}c{|v~|" "_{|r~}_v~}r{}w~q{|v~|i{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}Z{|v~|V{}w~}mv~}aw~}u{|t~|I{}w~L{}w~L{}w~L{}w~" "L{}w~L{}w~V{}w~|kv~j{}w~}O{|w~|k{}w~b{|w~|k{}w~b{|w~|k{}w~b{|w~|k{}w~Wv~Lv~Lv~Lv~W{}w~}l{|w~}`v~m{|w~}b{}w~}l{}" "w~}b{}w~}l{}w~}b{}w~}l{}w~}b{}w~}l{}w~}b{}w~}l{}w~}eY|f{}w~}rw~y{|w~}a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|" "m{}w~|^v~qv~]v~|m{|v~_v~qv~ Vw~yd~|{}x~|kw~yd~|{}x~|kw~r{|t~|r{}x~|kw~pu~|r{}x~|kw~pv~}q{}x~|[w~|T{}w~|s{|v~ G{" "}v~T{}w~t{|y~}(]~|i{|Y~}h{|_~}d{|a~}bw~}kw~|aw~}kw~}\\{}w~}wv~|Xv~|u{}w~|cV~} 2v~| k{}w~| {{w~|tw~|W{|}m~}T{" "}x~}v{|o~}l{|v~|v{}u~q{}w~+{|w~}F{}w~|Ox~Z{|Z~}+m| ww~|X{|v~k{}w~}W{}w~}K{}v~}K{|}v~}^w~}q{}w~}Ju~a{|t~|o{}v~U{" "|v~|X{}u~}|wy|u~}]t~}y|{y|}q~} Z{|t~}| _{|}t~}\\v~`{|x~}s{}x~}o{|w~|t{}x~|kv~|p{|w~}`{}w~}n{|u~cv~}M{}w~}f{|v~|" "e{}w~}L{}w~}Tv~}m{}n~|h{}w~}hv~|Y{}w~}M{}w~}W{}w~}|u~}R{}w~}V{}w~|v{|w~|x{}x~}uv~|h{}w~|t{|v~uv~iv~}c{|v~|e{}h~" "}cv~}c{|v~|g{}h~}Qy|y}p~W{|v~|Z{|v~h{}w~}a{|v~s{|v~|e{}w~}v{}x~}t{|w~uv~|a{}r~}P{|v~|P{}v~}O{|w~}I{|w~|J{|w~| " "n{|y}l~^v~kv~a{}w~|Ov~|l{}w~|b{}w~|k{}w~|Yw~}Vv~|l{}w~|`v~m{|w~}Wv~Lv~Tw~}|u~Kv~_v~mv~mv~hv~m{|w~}b{}w~|l{|v~`v" "~kv~c{}w~|l{}w~|Zv~Pu~}|Kv~S{|w~|m{}w~|^v~qv~b{}w~u{}x~|y{|w~uv~]{}r~V{}w~|s{|w~}R{|v~}X{|q~}Jw~|K{|q~}c{}g~}w|" "}u~}5y~}pw~}p{}y~fv~|o{}u~]v~p{|t~\\v~}w{|w~}w~|a{}w~|l{|w~}]{}w~}y|Rv~m{|w~}]{}w~s{}w~}X{}w~}x{|v~\\{|w~|m{}w~" "|h{|v~|b{|v~|i{}w~|u{}w~tv~|b{|w~}q{|w~}`v~t{}w~t{|w~}bv~kv~c{}w~|l{|w~}X{|w~}Wv~jv~`v~|p{}w~}T{}v~|V{}w~}V{|v~" "|cv~|lv~}r{|v~r{|v~|i{}w~}hv~|g{}v~}u{|v~tu~|jv~}c{|v~|n{|T~]{}w~]T~}^{}w~]T~}^{}w~ I{|v~sy~}X{}g~|[w~m{}x~|Vu~" "|#{|w~|p{|w~|2{|y~|w{|x~}d{|y~|3v~}v{}v~|Aw~}8{|y~|sw~x{|w~}p{|y~| Q{}w~ p{|w~|m{}w~|Y{|}v~}w{|x~}W{|v~| jv~}" "v{}v~|W{|w~o{}y~{}x~r{}n~}x{|w~uy|rw~|ty|t}|s{|w~o{}y~|}x~^{}w~|Wv~|p{|w~}^v~|p{|w~}^v~|p{|w~}^v~|p{|w~}^v~|p{|" "w~}^v~|p{|v~f{|v~q{|v~Yv~}I{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~ev~}h{}w~|t{|v~uv~iv~}c{|v~|lv~}" "c{|v~|lv~}c{|v~|lv~}c{|v~|lv~}c{|v~|^{|t~}^v~}s{}w~p{|v~|i{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}Z{|v~|V{}w" "~}n{|v~|aw~}t{}t~}W{|y}l~Y{|y}l~Y{|y}l~Y{|y}l~Y{|y}l~Y{|y}l~c{|y}l~j{}w~j{}w~|O{}w~|k{}w~|c{}w~|k{}w~|c{}w~|k{}" "w~|c{}w~|k{}w~|Xv~Lv~Lv~Lv~W{}w~|l{|v~`v~m{|w~}b{}w~|l{|v~b{}w~|l{|v~b{}w~|l{|v~b{}w~|l{|v~b{}w~|l{|v~f{|Z~}f{}" "w~|s{}x~|y{|w~}a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|^{}w~|s{|w~}]v~kv~_{}w~|s{|w~} Vw~yd~|{}x~|kw~yd" "~|{}x~|kw~qt~|r{}x~|kw~qu~|q{}x~|kw~pv~}q{}x~|[w~|T{|w~}s{}w~} H{|v~|T{|w~|u{}y~({|]~}i{}X~g{|`~b{}b~aw~}kw~}aw" "~}kw~}\\v~|w{}w~}X{}w~}uv~bw~}Z| 5x|v~}p| v{}w~| {|w~t{|w~S{|}n~|Vw~uv~|y{|}w~}m{}w~}t{}u~rw~}+{|w~}F{}w~|Ox" "~Z{|Z~},{|m~ x{|w~|X{|v~k{}w~}W{}w~}L{}v~}H{}v~}`{}w~p{}w~}J{}v~`t~n{|v~|V{}v~X{}v~}q{}v~}^{|j~|v~| Z{|t~| ]{|}" "u~}]{|w~}`{|x~|sw~|o{|w~|t{}x~|l{|v~nv~`{}w~}lv~}dv~}M{}w~}f{|v~|e{}w~}L{}w~}Tv~}m{}n~|h{}w~}hv~|Y{}w~}M{}w~}W{" "}w~}{|t~S{}w~}V{}w~|u{}x~}y{|w~|uv~|h{}w~|sv~|vv~iv~}c{|v~|e{}k~}|av~}c{|v~|g{}w~}t|y}u~}M{|}s~}X{|v~|Z{|v~h{}w" "~}`v~}t{}v~d{}w~}vw~|sw~|w{|v~a{|v~}v~|Q{|v~|Q{|u~N{|w~}Hw~|J{|w~| p{}h~|_v~k{}w~|bv~|Ov~k{}w~|bv~j}v~|Yw~}Vv~" "k{}w~|`w~}m{|w~}Wv~Lv~Tq~}Jv~_w~}mv~mv~hw~}m{|w~}bv~|l{|v~`v~kv~|dv~k{}w~|Zv~P{}r~}y|Pv~S{|w~|m{}w~|^{}w~|s{|w~" "}b{|w~|vw~|xw~|w{|w~}\\s~|Uv~sv~|Ru~W{|s~}|Iw~|I{|}t~}d{|u~}w|}g~}5{|y~|p{|x~|p{}y~fv~|o{|v~}]v~n{}v~|^{}w~|ts~" "`v~|l{|v~\\{}p~}Xw~}m{|w~}]{|w~|tv~|Xv~|wv~|]{|w~|m{}w~|h{|v~|q{}x~}q{|v~|iv~|u{}w~t{}w~|b{|w~}q{|w~}`v~t{}w~t{" "|w~}bv~kv~|dv~|l{|v~X{|w~}Wv~|l{|v~a{|v~nv~U{|v~}U{}w~}Uv~}d{|v~|l{}v~r{|v~r{|v~|i{}w~}hv~|fu~|v{|v~u{}v~}iv~}c" "{|v~|n{|T~]{}w~]T~}^{}w~]T~}^{}w~ rw|V{|w~}sy~}X{|w}u~q}Zw~m{}x~|V{}v~\"{|v~ow~|2{|y~|w{|w~d{|y~|4{}w~}v{|v~?w~" "}8{|y~|sw~vw~}q{|y~| Q{}w~ p{|w~|m{}w~|Ux~}w{|x~}W{|v~| i{}w~|v{|v~Ww~|p{|y~|{}x~`{}x~|j{|x~}bw~|p{|y~}{}x~^{" "}w~|X{|v~nv~_{|v~nv~_{|v~nv~_{|v~nv~_{|v~nv~_{|w~}nv~|g{}w~}q{|v~Yv~}I{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}" "M{}w~}Z{|v~ev~}h{}w~|sv~|vv~iv~}c{|v~|lv~}c{|v~|lv~}c{|v~|lv~}c{|v~|lv~}c{|v~|]{}u~|^v~}t{|w~|p{|v~|i{|v~h{}w~}" "f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}Z{|v~|V{}w~}n{}v~|aw~}s{|s~|[{}h~|\\{}h~|\\{}h~|\\{}h~|\\{}h~|\\{}h~|f{}h~j}v~" "jv~|Ov~j}v~|cv~j}v~|cv~j}v~|cv~j}v~|Xv~Lv~Lv~Lv~Wv~|l{|v~`w~}m{|w~}bv~|l{|v~bv~|l{|v~bv~|l{|v~bv~|l{|v~bv~|l{|v" "~f{|Z~}fv~|t{}x~|wv~a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|]v~sv~|]v~kv~|_v~sv~| Vw~yd~|{w~jw~yd~|{w~j" "w~rr~|sw~jw~ru~|pw~jw~pv~}qw~Zw~|Sv~sv~ H{|v~|Rw~}uy~}({|]~}i{}X~|g{}b~|a{}d~|aw~}kw~}aw~}kw~}]{|v~v{|v~X{|v~v{" "|w~}b{}x~} pf~ v{|w~ {{|w~t{|x~}P{|y~}r~W{}x~|v{}w~u{}w~mv~r{}u~t{|w~|+{|v~F{}w~|Ox~Z{|Z~},{|m~ x{}w~W{|v~k" "{}w~}W{}w~}M{}v~}F{}v~a{|w~|p{}w~}Iv~|au~}mv~}Vv~|Y{|v~}o{|v~|]{}m~|{v~| Z{|r~}| c{|}r~}]{|w~}`{|x~|sw~|nw~|t{}" "x~k{}w~}n{}w~}a{}w~}l{|v~|e{}v~M{}w~}f{}v~d{}w~}L{}w~}T{}v~mr|v~|h{}w~}hv~|Y{}w~}M{}w~}W{}w~}y{|t~T{}w~}V{}w~|u" "{|w~y{}w~tv~|h{}w~|s{|v~vv~i{}v~c{|v~|e{}w~}r|]{}v~c{|v~|g{}w~}q{}v~}K{|t~|Y{|v~|Z{|v~h{}w~}`{}v~tv~|d{|v~w{|w~" "|s{}x~}w{}w~}av~}{}v~Q{|v~|R{|u~M{|w~}H{}x~}J{|w~| r{|f~|_w~}k{}w~|bv~|Ov~k{}w~|b`~|Yw~}Vv~k{}w~|`w~}m{|w~}Wv~" "Lv~Tq~Iv~_w~}mv~mv~hw~}m{|w~}bv~jv~`v~k{}w~|dv~k{}w~|Zw~}O{}o~}|Sv~S{|w~|m{}w~|^{|w~}s{}w~|b{|w~}w{|w~w{}x~}w{|" "w~|\\{|u~}T{}w~|u{|w~}Ru~V{|s~}|Iw~|J{|}s~}d{|w~|s{|}k~|3y~}p{|x~}p{}y~fv~mv~|]v~m{}v~_{|w~}rt~`v~jv~Z{}r~}Xw~}" "m{|w~}\\w~}u{|w~}X{|w~}v{}w~}]{|w~|m{}w~|h{|v~|q{}x~}pv~|iv~t{}w~t{}w~|b{|w~}q{|w~}`v~t{}w~t{|w~}bv~k{}w~|dv~jv" "~X{|w~}W{}w~|l{|v~a{}w~}n{}w~}W{|u~T{}w~}U{}w~}d{}v~k{}v~|s{|v~r{}v~h{}w~}hv~|f{|u~|w{|v~v{}u~h{}v~c{|v~|n{|T~]" "{}w~]T~|^{}w~]{}U~}^{}w~ s{|w~V{|w~}sy~}S{|v~Pw~|nw~|V{|w~}!{}v~|q{}x~|1y~}vw~|e{}y~ci|]{}w~u{|w~|?w~}7y~}sw~v{" "|w~|r{}y~ P{}w~ p{|w~|m{}w~|Ux~}w{|x~}W{|v~| Fi|U{|w~|u{}w~X{}x~}p{|y~}y{}x~a{|w~i{|x~}c{}x~}p{|y~}y{}x~^{}w~|" "X{}w~}n{}w~}`{}w~}n{}w~}`{}w~}n{}w~}`{}w~}n{}w~}`{}w~}n{}w~}`{}w~|n{}w~}h{|v~p{|v~Y{}v~I{}w~}M{}w~}M{}w~}M{}w~}" "D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~f{|v~|h{}w~|s{|v~vv~i{}v~c{|v~|l{}v~c{|v~|l{}v~c{|v~|l{}v~c{|v~|l{}v~c{|v~|^{}s~|_" "{}v~u{|w~|o{|v~|i{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}Z{|v~|V{}w~}o{|u~`w~}q{}t~|^{|f~|^{|f~|^{|f~|^{|f~|" "^{|f~|^{|f~|h{|P~jv~|O`~|c`~|c`~|c`~|Xv~Lv~Lv~Lv~Wv~jv~`w~}m{|w~}bv~jv~bv~jv~bv~jv~bv~jv~bv~jv~f{|Z~}fv~|u{}x~}" "vv~a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|]{}w~|u{|w~}\\v~k{}w~|_{}w~|u{|w~} Uw~yq}w~r}yw~jw~yd|yw~jw~" "sp~|tw~jw~su~|ow~jw~pv~}qw~Zw~|S{}w~}u{|w~} Hv~|Q{}w~|w{|y~|({|\\~iW~|f{}d~|_e~|`w~}kw~}aw~}kw~|]{}w~}uv~Wv~|w{" "}w~|b{}x~} q{|g~| v{|w~({}Z~X{|y~|{|}u~}Y{|w~uw~|tw~}o{|w~}q{}u~u{}w~*{|v~F{}w~|*m|}w~l|,{|m~ xw~}W{|v~k{}w" "~}W{}w~}N{}v~}Dv~|bw~}o{}w~}Iv~|au~|m{}w~}W{|v~X{}v~m{}v~\\{|p~}xv~| Y{}p~}| i{|}p~}|]{}w~}`{|x~|sw~mw~|t{}x~kv" "~}n|}v~a{}w~}kv~}e{}v~M{}w~}f{}v~d{}w~}L{}w~}T{}v~dv~|h{}w~}hv~|Y{}w~}M{}w~}W{}w~}x{|t~U{}w~}V{}w~|tw~|{w~}tv~|" "h{}w~|rv~}wv~i{}v~c{}v~d{}w~}T{}v~c{}v~f{}w~}p{}v~|Ju~}Y{|v~|Z{|v~h{}w~}_v~|v{|v~bv~|x{|w~r{}w~wv~|b{}v~xv~}R{|" "v~|Ru~|M{|w~}H{|w~J{|w~| s{|q~t}v~|_w~}k{}w~|bv~Nv~k{}w~|b`~|Yw~}Vv~k{}w~|`w~}m{|w~}Wv~Lv~Tp~Jv~_w~}mv~mv~hw~}" "m{|w~}bv~jv~`w~}k{}w~|dv~k{}w~|Zw~}N{|m~|Uv~S{|w~|m{}w~|]v~t{|v~`v~w{}x~}w{|x~}w{}w~[{|u~|T{|w~}u{}w~|S{}v~|V{|" "x}t~}Jw~|K{|s~y}|d{|y~}n{|}p~}1y~}p{}w~p{}y~fv~mv~\\v~lv~|`{}w~|r{|v~}`v~jv~\\{|p~}Xw~}m{|w~}\\{}w~u{}w~|Xv~|v{" "|v~]{|w~|m{}w~|h{|v~p{}w~pv~}iv~t{}w~t{}w~|b{|w~}q{|w~}`v~t{}w~t{|w~}bw~}k{}w~|dv~jv~X{|w~}W{}w~|l{|w~}av~|n{|v" "~Wu~|T{}w~}U{}v~dv~}k{|v~}s{|v~s{|v~}h{}w~}hv~|e{}u~|x{|v~w{}u~|h{}v~c{}v~l{|u~}\\|]{}w~][|u~|]{}w~\\{}v~}c|u~}" "]{}w~ s{|w~V{|w~}sy~}S{|v~P{}x~}o{|w~`{|a~}+u~|rw~|1y~}v{}w~ex~d{|j~}]{}w~}v{|v~|@w~}7y~}sw~u{}w~rx~ P{}w~ p{|" "w~|m{}w~|Ux~}w{|x~} w{|j~}V{|v~|v{}w~}Xw~oy~}x{}x~aw~|i{|x~|cw~ox~x{}x~^{}w~|Xv~}n|}v~`v~}n|}v~`v~}n|}v~`v~}n|" "}v~`v~}n|}v~a{|b~h{}v~p|}v~Y{}v~I{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~f{|v~|h{}w~|rv~}wv~i{}v~c{" "}v~k{}v~c{}v~k{}v~c{}v~k{}v~c{}v~k{}v~c{}v~^{}q~|`{}v~v{|w~}n{}v~h{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}Z{" "|v~|V{}w~}p{|u~|`w~}p{|t~}`{|q~t}v~|_{|q~t}v~|_{|q~t}v~|_{|q~t}v~|_{|q~t}v~|_{|q~t}v~|i{|q~t}`~|kv~N`~|c`~|c`~|" "c`~|Xv~Lv~Lv~Lv~Wv~jv~`w~}m{|w~}bv~jv~bv~jv~bv~jv~bv~jv~bv~jv~f{|Z~}fv~u{|x~}uv~a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m" "{}w~|a{|w~|m{}w~|]{|w~}u{}w~|\\w~}k{}w~|_{|w~}u{}w~| U{}x~|q{}w~q{|w~j{}x~|b{|w~j{}x~|uu~|u~|v{|w~j{}x~|uu~|o{|" "w~j{}x~|qv}|r{|w~[{|w~|S{|v~uv~| TZ~}a{|w~}wx~'{|\\~iW~|ee~|^{|g~}_w~}kw~}aw~}kw~|]v~|u{}w~|X{}w~}wv~|b{|w~| " " r{}g~ u{|w~({}Z~X{|y~|w{}v~|Zw~|v{|w~s{|w~o{|w~}p{}u~vw~})v~Fv~| w{}w~ x{|m~ y{|w~|Vv~|lv~|W{}w~}O{}v~}C{}w~}" "c{|w~n|}w~}v|N{}w~}au~l{|v~Wv~}Xv~}m{|v~|[{|y}w~y}|x{|v~ V{|}p~}|XY|X{|}q~}|Z{}w~}`{|x~|sw~mw~|tw~l{|b~|b{}w~}k" "{}v~e{|v~|N{}w~}fv~}d{}w~}L{}w~}T{|v~|ev~|h{}w~}hv~|Y{}w~}M{}w~}W{}w~}w{|t~V{}w~}V{}w~|t{}w~|w~|tv~|h{}w~|r{|v~" "wv~i{|v~|d{}v~d{}w~}T{|v~|d{}v~f{}w~}o{}v~J{|u~Y{|v~|Z{|v~h{}w~}_{}w~}v{}w~}b{}w~}x{}x~}r{|w~wv~b{|v~|x{|v~|S{|" "v~|S{}v~|L{|w~}Gw~|K{|w~| t{|u~}|q{}w~|_v~k{}w~|bv~Nv~k{}w~|b`~|Yw~}Vv~k{}w~|`w~}m{|w~}Wv~Lv~Tw~}|u~Kv~_w~}mv~" "mv~hw~}m{|w~}bv~jv~`w~}k{}w~|dv~k{}w~|Zw~}L{|}o~}Vv~S{|w~|m{}w~|]{}w~}u{}w~}`{}w~|xw~|w{|w~wv~\\{|s~Sv~uv~S{}v~" "|O{}v~}Kw~|L{|v~}|_{|~|j{|y}x~y}|/x~q{|v~}qx~fv~m{}x~}\\v~l{}w~|`v~pv~}`v~jv~]n~}Xw~}m{|w~}\\{|w~|vv~X{|v~t{}w~" "|^{|w~|m{}w~|h{|v~p{}w~pv~|iv~t{}w~t{}w~|b{|w~}q{|w~}`v~t{}w~t{|w~}bw~}k{}w~|dv~jv~X{|w~}W{}w~}l{}w~}b{|v~lv~|Y" "{}v~|S{}w~}U{|v~}f{|v~|ju~|t{|v~s{}v~|h{}w~}hv~|dt~}y{|v~y{|t~|g{|v~|d{}v~k{|u~|?{}w~>u~|b{|v{}w~[{}v~|e{}v~}\\" "{}w~ s{|w~V{|w~}sy~}S{|v~P{|w~o{}x~}`{|a~}+{|u~}|u{|w~0{}y~v{|w~}g{|y~}d{|j~}\\{}v~|w{|v~}Aw~}7{}y~sw~tw~}t{|y~" "} P{}w~ p{|w~|m{}w~|Ux~}w{|x~} w{|j~}W{|v~|vv~}X{}x~|p{}y~|x{}x~b{}x~}hw~c{}x~}p{}y~|x{}x~^v~X{|b~|b{|b~|b{|b" "~|b{|b~|b{|b~|b{}b~}id~Y{|v~|J{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~f{}v~g{}w~|r{|v~wv~i{|v~|d{}v" "~k{|v~|d{}v~k{|v~|d{}v~k{|v~|d{}v~k{|v~|d{}v~_{}v~}u~|a{|v~|ww~}m{}v~h{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w" "~}Z{|v~|V{}w~}sy|s~_w~}n{}u~|b{|u~}|q{}w~|`{|u~}|q{}w~|`{|u~}|q{}w~|`{|u~}|q{}w~|`{|u~}|q{}w~|`{|u~}|q{}w~|j{|u" "~}|q{}a~|kv~N`~|c`~|c`~|c`~|Xv~Lv~Lv~Lv~Wv~jv~`w~}m{|w~}bv~jv~bv~jv~bv~jv~bv~jv~bv~jv~.v~v{|w~tv~a{|w~|m{}w~|a{" "|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|\\v~uv~[w~}k{}w~|^v~uv~ T{}x~}q{}w~q{|x~}j{}x~}b{|x~}j{}x~}vu~|{|u~|w{|x~}j{}" "x~}vu~|n{|x~}j{}x~}b{|x~}[{|w~Qv~|w{|v~ SZ~}`v~x{|y~}'{|]~}iW~|e{|g~}\\{}i~}^w~}kw~}aw~}l{|w~|^{|v~t{|w~}X{|v~x" "{|v~`w~} m{|v~ jw|({}Z~X{|y~|v{}w~}[{}x~}u{}x~}s{|w~o{}w~}o{}u~x{|w~|)v~Fv~ v{}w~ g{}w~Uv~|lv~|W{}w~}P{}v~" "}B{|v~c{|_~|O{}w~}a{}v~l{|v~X{|v~|Y{|v~|lv~|N{|v~ S{|}p~|[{|Z~}[{|}p~}|X{}w~}`{|x~|sw~|nw~|u{|x~}l{}b~}b{}w~}k{" "|v~e{|v~}N{}w~}g{|v~}d{}w~}L{}w~}T{|v~}ev~|h{}w~}hv~|Y{}w~}M{}w~}W{}w~}v{|t~W{}w~}V{}w~|t{|r~sv~|h{}w~|q{}w~}xv" "~i{|v~}dv~}d{}w~}T{|v~}dv~}f{}w~}nv~}J{}v~Y{|v~|Z{|v~|i{}w~}_{|v~vv~|b{}w~}xw~|qw~|y{|v~bv~}v{}v~S{|v~|T{}v~}K{" "|w~}G{}x~}K{|w~| tv~}n{}w~|_v~kv~|bv~|Ov~k{}w~|bv~Bw~}Vv~k{}w~|`w~}m{|w~}Wv~Lv~Tw~}{|u~|Mv~_w~}mv~mv~hw~}m{|w~" "}bv~|kv~`v~k{}w~|dv~k{}w~|Zw~}Iy|}q~Wv~S{|w~|m{}w~|]{|v~uv~_{|w~|xw~uw~|y{|w~}\\r~}T{|w~|w{}w~}T{}v~|M{|v~Kw~|L" "{}w~} O{}y~|rt~|s{|y~}fv~|nw~}\\v~l{|w~}`w~}p{}w~|`v~|kv~^u~}|Qw~}m{|w~}[w~}w{}w~}X{}w~|t{|w~}^{|w~|m{}w~|h{|v~" "pv~pv~|iv~t{}w~t{}w~|b{|w~}q{|w~}`v~t{}w~t{|w~}bv~k{}w~|dv~|l{|v~X{|w~}W{|w~}l{}w~|b{}w~}l{}w~}Z{|v~}R{}w~}T{}v" "~f{}v~i{|u~t{|v~t{|u~g{}w~}hv~|cr~}v~}s~}f{|v~}dv~}j{|u~|@{}w~?u~|b{}~|w{}w~vy~a{}v~|g{}v~}b{}~|w{}w~vy} {{}w~|" "W{|w~}sy~}S{|v~Ow~}q{|w~|`{|a~}){}u~}vw~}0{|y~}v{}w~}p{|t{}y~|d{|j~}[{|v~|vv~}Bw~}7{|y~}tw~t{|w~|u{}y~| P{}w~ " "p{|w~|m{}w~|Ux~}w{|x~} w{|j~}X{}v~v{|v~}X{|w~p{|y~|w{}x~bw~h{}x~|d{|w~p{|y~}w{}x~^v~X{}b~}b{}b~}b{}b~}b{}b~}b{" "}b~}b`~j{}d~Y{|v~}J{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~fv~}g{}w~|q{}w~}xv~i{|v~}dv~}k{|v~}dv~}k" "{|v~}dv~}k{|v~}dv~}k{|v~}dv~}`{}v~|{|u~|b{|v~}x{}x~}lv~}h{|v~|i{}w~}f{|v~|i{}w~}f{|v~|i{}w~}f{|v~|i{}w~}Z{|v~|V" "{}e~|_w~}m{|u~bv~}n{}w~|`v~}n{}w~|`v~}n{}w~|`v~}n{}w~|`v~}n{}w~|`v~}n{}w~|jv~}n{}w~Tv~|Ov~Lv~Lv~Lv~Av~Lv~Lv~Lv~" "Wv~|l{|v~`w~}m{|w~}bv~|kv~bv~|kv~bv~|kv~bv~|kv~bv~|kv~.v~vw~|u{|v~a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}" "w~|\\{|w~|w{}w~}[v~k{}w~|^{|w~|w{}w~} T{|w~q{}w~q{}x~|j{|w~b{}x~|j{|w~wu~|x{|u~|x{}x~|j{|w~wu~|m{}x~|j{|w~b{}x~" "|[{|w~Q{|w~}w{}w~} SZ~}`{}w~|y{}y~|'{|n~y}~|n~}i{}k~x}k~c{|i~}Z{}j~]w~}kw~}a{}w~l{|w~|^{}w~}sv~Wv~|y{}w~}`{}w~|" " mv~| o{}Z~X{|y~|v{|w~}\\{|w~t{}x~|rw~|p{}w~}n{}u~yw~}(v~|Gv~ v{}w~ gw~}U{}w~}m{|v~V{}w~}Q{}v~}A{|v~c{|_~" "|O{}w~}a{}v~l{|v~X{}v~X{|v~k{}w~}N{}w~} Q{|}p~}|^{|Z~}^{|}p~}|U{}w~}`{|x~}sw~|o{|w~|u{}x~|l`~b{}w~}k{|v~|eu~N{}" "w~}g{}v~|d{}w~}L{}w~}Su~ev~|h{}w~}hv~|Y{}w~}M{}w~}W{}w~}u{|t~X{}w~}V{}w~|ss~}sv~|h{}w~|q{|v~|yv~hu~e{|v~|d{}w~}" "Su~e{|v~|f{}w~}n{}v~|K{|v~|Z{|v~|Yv~|i{}w~}^v~|x{}v~a{|v~y{|w~|q{}x~}y{}w~}c{}v~tv~}T{|v~|U{|v~}J{|w~}G{|w~K{|w" "~| u{|v~m{}w~|_v~kv~a{}w~|O{}w~|l{}w~|bv~|Cw~}V{}w~|l{}w~|`w~}m{|w~}Wv~Lv~Tw~}y{|u~|Nv~_w~}mv~mv~hw~}m{|w~}bv~" "|l{|v~`v~kv~cv~|l{}w~|Zw~}D{|}u~}Xv~S{|w~|m{}w~|\\{}w~|w{|w~}^w~}y{|w~u{}x~}y{}w~|]{}q~|Tv~wv~|U{|v~}K{}w~|Lw~|" "Lv~ N{|x~s{}x~{w~|tx~|fv~|o{|v~\\v~l{|w~}a{|w~|p{}w~_{}w~|l{|v~_{}v~|Ow~}m{|w~}[{}w~|xv~X{|v~rv~|_{|w~|m{}w~|h{" "|v~|qv~pv~|iv~|u{}w~t{}w~|b{|w~}q{|w~}`v~t{}w~t{|w~|bv~kv~c{}w~|l{|v~X{|w~}Vv~l{}w~|bv~|l{|v~[{|v~}Q{}w~}T{|v~}" "h{|v~|hu~}u{|v~u{|u~|g{}w~}hv~|b{}f~|du~e{|v~|i{|u~|A{}w~@u~|b{}x~|x{}w~ww~a{}v~|i{}v~}b{}x~|x{}w~w{}y~} {}w~|W" "{|v~sy~}S{|v~O{|w~}s{}w~}^q|}v~q|'{}t~|{|w~}.x~u{}v~}|wy|}y~tx~/{|v~|v{}w~}Cw~}6x~tw~s{}w~ux~ O{}w~ p{|w~|m{}w" "~|Ux~}w{|x~} B{}w~}v{|v~|Ww~|q{|y~}v{}x~c{}x~|i{}x~}cw~|q{|y~}v{}x~_{|v~X`~b`~b`~b`~b`~c{|`~|kc~Xu~J{}w~}M{}w~" "}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~g{|v~}g{}w~|q{|v~|yv~hu~e{|v~|ju~e{|v~|ju~e{|v~|ju~e{|v~|ju~e{|v~|a{}" "v~|x{|u~|bu~y{}w~l{|v~|gv~|i{}w~}ev~|i{}w~}ev~|i{}w~}ev~|i{}w~}Z{|v~|V{}f~|^w~}l{|v~|d{|v~m{}w~|a{|v~m{}w~|a{|v" "~m{}w~|a{|v~m{}w~|a{|v~m{}w~|a{|v~m{}w~|k{|v~m{}w~T{}w~|Ov~|Mv~|Mv~|Mv~|Bv~Lv~Lv~Lv~W{}w~|l{|v~`w~}m{|w~}bv~|l{" "|v~bv~|l{|v~bv~|l{|v~bv~|l{|v~bv~|l{|v~.v~|x{}x~|t{|v~a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|[v~wv~|[v" "~kv~\\v~wv~| Sw~|r{}w~r{|w~hw~|d{|w~hw~|yu~|v{|u~y{|w~hw~|yu~|m{|w~hw~|d{|w~Z{|w~Pv~wv~| SZ~}_w~}yx~%n~{|~{|o~|" "i{|l~}|}|l~}b{}j~Xk~|]w~}kw~}a{}w~l{}w~]v~|s{}w~|X{}w~}yv~|_w~} mv~} g{}x~}t{}x~}O{|y~|uw~}\\{}x~|t{}x~|rw" "~|p{|w~}m{}u~}w~|({}w~|H{|w~} v{}w~ h{|w~|U{}w~}m{|v~V{}w~}R{}v~}@{|v~c{|_~|Ov~|a{|v~l{}w~}Xv~}X{|v~k{}w~}Nv~|" " N{|}p~}|a{|Z~}a{|}p~}|R{|w}|_x~}s{}x~}o{}w~|v{|w~l{}`~|c{}w~}k{|v~|e{}v~|O{}w~}gu~c{}w~}L{}w~}S{}v~|fv~|h{}w~}" "hv~|Y{}w~}M{}w~}W{}w~}t{|t~Y{}w~}V{}w~|s{}t~rv~|h{}w~|p{}w~}yv~h{}v~|f{}v~c{}w~}S{}v~|f{}v~e{}w~}mv~}K{|v~|Z{|v" "~|Yv~|iv~|^{}w~}xv~}`v~|{|w~p{}w~yv~|d{|v~|t{|v~|U{|v~|V{|u~I{|w~}Fw~|L{|w~| u{}w~|mv~|_v~|m{|v~a{}w~}O{}w~|lv" "~|b{}w~|Cw~}V{}w~|lv~|`w~}m{|w~}Wv~Lv~Tw~}x{|u~|Ov~_w~}mv~mv~hw~}m{|w~}b{}w~|l{|w~}`v~kv~c{}w~|lv~|Zw~}B{|u~Xv~" "S{|w~|m{}w~|\\{|w~}w{}w~|^v~y{}x~}u{|x~}y{}w~]{|v~|}v~T{}w~|y{|w~}U{|v~}J{|w~}Lw~|M{|w~} Mx~}v{|w~|{|w~|v{}x~e{" "}w~|o{}v~\\v~l{|w~}a{|w~|pw~}_{}w~|l{|w~}_v~Mw~}m{|w~}[{|w~}y{|w~}X{}w~|r{}w~}_{|w~|m{}w~|h{|v~|qv~|r{|v~|i{}w~" "|u{}w~tv~|b{|w~}q{|w~}`v~t{}w~t{}w~|bv~kv~c{}w~|l{|w~}X{|w~}Vv~lv~b{}v~jv~|\\u~P{}w~}S{}v~|iu~g{|t~|w{|v~v{}u~}" "f{}w~}hv~|a{}h~|c{}v~|f{}v~g{|u~|B{}w~Au~|b{}v~|y{}w~xu~a{}v~|k{}v~}b{}v~|y{}w~x{}w~}!{}w~|Vv~sy~}S{|v~O{|u~}y|" "{y|u~}T{|w~}Lw}|P{|}p~}-{|y~}u{}l~u{}y~|.{|v~|v{}w~}Dw~}6{|y~}uw~rw~}w{}y~| O{}w~ p{|w~|m{}w~|Ux~}w{|x~} C{}w" "~}v{|v~|W{}x~}px~u{}x~d{|w~i{}x~}c{}x~}px~u{}x~_{}w~}Y{}`~|d{}`~|d{}`~|d{}`~|d{}`~|d{}w~}j|}w~}l{|c~X{}v~|K{}w~" "}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~gu~|g{}w~|p{}w~}yv~h{}v~|f{}v~i{}v~|f{}v~i{}v~|f{}v~i{}v~|f{}v~" "i{}v~|f{}v~a{}v~|v{|u~|c{}v~|}w~|l{}v~fv~|iv~|ev~|iv~|ev~|iv~|ev~|iv~|Z{|v~|V{}h~}\\w~}k{}w~|d{}w~|mv~|a{}w~|mv" "~|a{}w~|mv~|a{}w~|mv~|a{}w~|mv~|a{}w~|mv~|k{}w~|mv~|U{}w~}O{}w~|M{}w~|M{}w~|M{}w~|Bv~Lv~Lv~Lv~W{}w~}l{}w~}`w~}m" "{|w~}b{}w~|l{|w~}b{}w~|l{|w~}b{}w~|l{|w~}b{}w~|l{|w~}b{}w~|l{|w~}.{}w~|y{}x~|s{|w~}a{|w~|m{}w~|a{|w~|m{}w~|a{|w" "~|m{}w~|a{|w~|m{}w~|[{}w~|y{|w~}Zv~kv~\\{}w~|y{|w~} R{|w~r{}w~rw~}h{|w~dw~}h{|w~y{|w~|t{|w~}yw~}h{|w~y{|w~|lw~}" "h{|w~dw~}Z{|w~P{}w~|y{|w~} Rs}v~g}|_{}w~{|y~}%{|p~|{|~yp~}g{}m~{}~{}m~|a{}l~|X{|m~}\\w~}kw~}a{|w~|mv~]v~r{}w~}X" "{|v~{|v~^{}w~} n{}v~ gw~|tw~|O{|y~|uw~}]{|x~}sw~|rw~|p{|v~l{}r~}'{|w~}H{|w~} v{}w~ h{|w~T{|v~m{}w~}V{}w~}" "S{}v~}?{|v~c{|_~|Ov~|`v~|m{}w~}Y{|v~W{|v~k{}w~}O{|v~ J{|}p~}|d{|Z~}d{|}p~}|-w~s{|w~ov~|v{}x~|lv~|j{|v~c{}w~}k{}" "v~cv~}O{}w~}h{}v~|c{}w~}L{}w~}Rv~}fv~|h{}w~}hv~|Y{}w~}M{}w~}W{}w~}rt~Z{}w~}V{}w~|ru~}rv~|h{}w~|p{|v~|{v~h{|v~}g" "{|v~}c{}w~}Rv~}g{|v~}e{}w~}m{|v~|L{|v~|Z{|v~|Y{}w~}j{|v~|^{|v~|{|v~_{}w~}{}x~}p{|w~yv~cv~}r{}v~U{|v~|W{|u~|I{|w" "~}F{}x~}L{|w~| u{}w~|n{|v~|_v~}m{}w~}a{|w~}O{|w~}m{|v~|b{}w~}Cw~}V{|w~}m{|v~|`w~}m{|w~}Wv~Lv~Tw~}vu~|Pv~_w~}mv" "~mv~hw~}m{|w~}b{|w~}l{}w~}`v~|m{|w~}c{|w~}lv~|Zw~}@v~|Yv~S{|w~}mv~|[v~wv~]{}w~|{w~|u{|w~yw~}]v~}y{}v~U{|w~}y{}w" "~|V{|v~}I{|w~}Lw~|M{|w~} M{|w~x}v~}x{}v~x}w~|e{}w~}ou~|]v~l{|w~|a{|w~p{}w~|_{|w~}l{}w~}`{|w~}Mw~}m{|w~}Zv~y{}w~" "|Y{|v~q{|v~_{|w~}m{}w~|gv~|r{|v~|r{|v~h{}w~}u{}w~tv~a{|w~}q{|w~}`v~t{}w~t{}w~|bv~|m{|w~}c{|w~}l{}w~}X{|w~}V{}w~" "|n{|w~}bv~}j{}v~]{}v~|P{}w~}Ru~j{}v~|f{|t~}|y{|v~x{|t~}e{}w~}hv~|`{|}l~}`v~}g{|v~}f{|u~|C{}w~Bu~|`u~|{}w~yu~|`{" "}v~|m{}v~}a{|u~|{}w~y{}v~}!{}w~|Vv~|ty~}S{|v~P{|g~}U{|w~}Lw~|N{|r~}+{}y~|u{|}o~}v{|y~}+v~}v{}v~Ew~}5{}y~|vw~r{|" "w~|y{|y~} N{}w~ p{|w~}m{}w~|Ux~}w{|x~} Dv~}v{}v~|W{|w~p{}y~|u{}x~dw~|j{}w~c{|w~p{}y~|u{}x~`{}v~|Yv~|j{|v~dv~|" "j{|v~dv~|j{|v~dv~|j{|v~dv~|j{|v~dv~|j{|v~l{}w~}n{|v~Wv~}K{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~h{" "|v~}f{}w~|p{|v~|{v~h{|v~}g{|v~}i{|v~}g{|v~}i{|v~}g{|v~}i{|v~}g{|v~}i{|v~}g{|v~}b{}v~|t{|u~|cq~|l{|v~}f{}w~}j{|v" "~|e{}w~}j{|v~|e{}w~}j{|v~|e{}w~}j{|v~|Z{|v~|V{}k~}|Zw~}k{}w~}d{}w~|n{|v~|a{}w~|n{|v~|a{}w~|n{|v~|a{}w~|n{|v~|a{" "}w~|n{|v~|a{}w~|n{|v~|k{}w~|n{|v~}U{|w~}O{}w~}M{}w~}M{}w~}M{}w~}Bv~Lv~Lv~Lv~W{|v~lv~|`w~}m{|w~}b{|w~}l{}w~}b{|w" "~}l{}w~}b{|w~}l{}w~}b{|w~}l{}w~}b{|w~}l{}w~}Xt|X{}w~}{}x~}r{}w~}a{|w~}mv~|a{|w~}mv~|a{|w~}mv~|a{|w~}mv~|[{|w~}y" "{}w~|Zv~|m{|w~}\\{|w~}y{}w~| Qw~}s{}w~s{}w~fw~}f{}w~fw~}y{|y~|r{|y~}y{}w~fw~}y{|y~|l{}w~fw~}f{}w~Y{|w~P{|v~y{}w" "~| Kv~}J{|w~|}y~|${}r~}y{}~y{|q~f{|n~|{}~yn~}_m~|V{|o~}[w~}kw~}`w~}n{|w~}^{|w~}r{|v~Wv~{}w~}]v~| o{|v~| hw" "~t{|w~N{|y~|uw~}]w~|s{}x~|rw~|ov~|l{}s~&{|w~}H{}w~| v{}w~ h{}x~}Sv~|nv~|V{}w~}T{}v~}>{}w~}Q{}w~}J{}v~_{}w~}mv~" "}Y{}w~}Vv~|lv~|Ov~} G{|}p~}|0{|}o~}*{}x~rw~}q{}v~|w{}w~l{|v~hv~|d{}w~}ku~c{}v~}P{}w~}i{}u~b{}w~}L{}w~}R{}v~|gv~" "|h{}w~}hv~|Y{}w~}M{}w~}W{}w~}qt~[{}w~}V{}w~|r{}v~|rv~|h{}w~|o{}w~}{v~g{}v~|hu~|c{}w~}R{}v~|hu~|e{}w~}lv~}L{}v~Y" "{|v~|Y{}v~j{}v~\\{}w~}{}w~}_{|v~{w~|ow~y|v~d{}v~pv~}V{|v~|Wu~|H{|w~}F{|w~L{|w~| u{}w~m{}v~|_u~mv~|a{|v~Nv~|n{}" "v~|b{|v~Cw~}Uv~|n{}v~|`w~}m{|w~}Wv~Lv~Tw~}uu~|Qv~_w~}mv~mv~hw~}m{|w~}b{|v~lv~|`v~}m{}w~}c{|v~m{|v~|Zw~}@{}w~|Yv" "~S{|w~}mv~|[{}w~|y{|w~}]{|w~}{w~sw~y|w~}^{}w~}wv~}U{}w~yv~Uv~}Gw~}Lw~|M{|w~| L{|q~}v{}q~|d{|w~}p{|u~|]v~l{}w~|a" "{|w~pv~^{|v~lv~|`{|w~|Mw~}m{|w~}Z{}w~y|v~X{}w~}pv~|`{|w~}mv~|gv~}r{|v~}r{}v~h{|v~u{}w~u{|w~}a{|w~}q{|w~}`{}w~|u" "{}w~tv~av~}m{}w~}c{|v~lv~|X{|w~}V{|w~}n{}w~|c{|v~i{|v~|_{}v~}O{}w~}R{|v~}l{}v~|d{|r~y}v~y}s~}d{}w~}hv~|]{|}s~y}" "|^{}v~|hu~|e{|v~}C{}w~C{}v~|^u~|}w~{}v~|^{}v~n{|v~}_{|u~|}w~{}v~} {}w~|V{}w~}ty~}S{|v~Q{}e~}V{|w~}Lw~|L{|t~*{|x" "~|t{|y}u~}|u{|x~|*{}w~|v{|v~Fw~}5{|x~|ww|qw|y{|x~| >{|w~}mv~|Ux~}w{|x~} Ev~}v{|v~U{}x~|q{|y~}t{}x~e{}x~}j{}w" "~b{}x~|q{|y~}t{}x~a{}v~}Y{|v~hv~|f{|v~hv~|f{|v~hv~|f{|v~hv~|f{|v~hv~|f{}v~hv~|n{|v~|n{|v~W{}v~}L{}w~}M{}w~}M{}w" "~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~i{|u~|f{}w~|o{}w~}{v~g{}v~|hu~|h{}v~|hu~|h{}v~|hu~|h{}v~|hu~|h{}v~|hu~|c{}" "v~|r{|u~|d{}s~|ku~|f{}v~j{}v~d{}v~j{}v~d{}v~j{}v~d{}v~j{}v~Y{|v~|V{}w~}r|Vw~}k{|w~|d{}w~m{}v~|a{}w~m{}v~|a{}w~m" "{}v~|a{}w~m{}v~|a{}w~m{}v~|a{}w~m{}v~|k{}w~m{}u~U{|v~O{|v~M{|v~M{|v~M{|v~Bv~Lv~Lv~Lv~Vv~|n{|v~_w~}m{|w~}b{|v~lv" "~|b{|v~lv~|b{|v~lv~|b{|v~lv~|b{|v~lv~|X{}u~X{|v~|x~}qv~|a{|w~}mv~|a{|w~}mv~|a{|w~}mv~|a{|w~}mv~|Z{}w~yv~Yv~}m{}" "w~}[{}w~yv~ P{|w~}t{}w~t{|w~}f{|w~}h{|w~}f{|w~}yy|p{|}y{|w~}f{|w~}yy|l{|w~}f{|w~}h{|w~}Y{|w~Ov~y|v~ K{}w~}Hw~}y" "~}\"{}t~}x{}~x{|s~d{|p~}y{}~y{|p~}]o~|T{}p~Zw~}kw~}`{}w~|o{}w~|^{}w~|qv~|X{}w~|v~|]{|v~| o{}v~j{} {|x~}t{|" "x~}N{|y~|v{}w~}^{}x~}r{}x~}rw~|o{}v~k{}u~|%v~Hv~ u{}w~ hw~|S{}v~o{}v~U{}w~}U{}v~}>{|v~}Q{}w~}Ju~_{|v~n{|v~|Z{|" "v~|Vv~}m{|v~|P{}v~ C{}o~}4{|o~}|({|x~}s{}w~}s{}u~|x{}w~|l{}w~}h{}w~}d{}w~}l{|v~}bu~|g{|}g{}w~}j{}u~|b{}w~}L{}w~" "}R{|u~|hv~|h{}w~}hv~|Y{}w~}M{}w~}W{}w~}pt~\\{}w~}V{}w~|r{|v}qv~|h{}w~|nv~|v~g{|u~|j{}v~}b{}w~}R{|u~i{}v~}d{}w~}" "l{|v~|M{}v~Y{|v~|Y{|v~|kv~}\\{|v~{v~|_{|v~|w~|o{}x~y}w~}e{|v~|p{|v~|W{|v~|X{}v~}G{|w~}F{|w~|M{|w~| u{}w~|nu~|_" "u~}o{}v~_v~}O{}w~}o{|u~|av~}Dw~}U{}w~}o{|u~|`w~}m{|w~}Wv~Lv~Tw~}t{}v~|Rv~_w~}mv~mv~hw~}m{|w~}av~|n{|v~_u~mv~|bv" "~|n{}v~|Zw~}@{}w~|Yv~Rv~n{}v~|[{|w~}y{}w~|\\w~}|x~}s{}x~y}w~|_{}v~v{|v~|V{|w~y}w~}Vu~Fw~}Lw~|M{|w~| K{|s~}t{}s~" "|bv~p{}u~}]v~|mv~`{|w~q{}w~}]v~}n{}v~_{|w~|Mw~}m{|w~}Yw~y}w~|Xv~o{|w~}`{|v~n{|v~|g{}v~r{}u~rv~}gv~|v{}w~uv~|a{|" "w~}q{|w~}`{|w~}u{}w~u{|v~au~mv~|bv~}n{}v~Vv~Uv~nv~b{}w~}hv~}`{|v~}N{}w~}Q{|v~}n{}v~}b{|c~}c{}w~}hv~|Z{|v~Z{|u~|" "j{}v~}c{|w~B{}w~B{}x~|\\u~}w~}v~|\\{}x~|m{}x~}]{|u~}w~}v~} {{v~|V{|v~|uy~}S{|v~R{}v~y|q~}|u~W{|w~}Lw~|J{}u~*{|x" "~|e{|x~|({}x~}u{|w~F{|x}|4{|x~|e{|x~| ={|v~n{|v~|Ux~}w{|x~} Ew~|u{|x~}U{|x~}p{}j~}iw~j{}w~b{|x~}p{}j~}f{}v~}" "X{}w~}h{}w~}f{}w~}h{}w~}f{}w~}h{}w~}f{}w~}h{}w~}f{}w~}h{}w~}fv~}h{}w~}n{}w~}m{|v~Vu~|g{|}c{}w~}M{}w~}M{}w~}M{}w" "~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~j{|u~}e{}w~|nv~|v~g{|u~|j{}v~}g{|u~|j{}v~}g{|u~|j{}v~}g{|u~|j{}v~}g{|u~|j{}v~}c{" "}v~|p{|u~|e{|t~}k{}v~}e{|v~|kv~}d{|v~|kv~}d{|v~|kv~}d{|v~|kv~}Y{|v~|V{}w~}Mw~}k{}w~|d{}w~|nu~|a{}w~|nu~|a{}w~|n" "u~|a{}w~|nu~|a{}w~|nu~|a{}w~|nu~|k{}w~|nt~|Uv~}Ov~}Mv~}Mv~}Mv~}Cv~Lv~Lv~Lv~V{}v~nv~}_w~}m{|w~}av~|n{|v~`v~|n{|v" "~`v~|n{|v~`v~|n{|v~`v~|n{|v~W{}u~Wr~q{|v~_v~n{}v~|`v~n{}v~|`v~n{}v~|`v~n{}v~|Z{|w~y}w~}Yu~mv~|[{|w~y}w~} O{}w~}" "u{}w~u{}w~}d{}w~}j{}w~}d{}w~}j{}w~}d{}w~}j{}w~}d{}w~}j{}w~}X{}w~O{|w~y}w~} L{}w~}G{}u~|!{|}x~}|w{}~v{}w~}b{|r~|" "x{}~w{}s~|\\{|q~}Rq~|Zw~}kw~}`{|v~p{|v~]v~p{}w~}X{|q~[{}v~} p{|v~}ly}$v}|\"{}x~}t{}x~}Yy}|s{|y~|w{|v~|_{|w~" "q{}x~}s{|w~n{|v~}l{|u~}%{}w~|Iw~} u{}w~L{}w~} tv}|P{|w~R{|v~|pv~}U{}w~}V{}v~}={}v~|Q{}w~}K{}v~|^v~|o{}v~Y{}v~U{" "}v~m{}v~P{|v~}U{|v}M{}w~}F{|}q~}6{|q~}|G{|w}|^w~ru~y|x{|}t~y|}v~|kv~|h{|v~d{}w~}m{|u~|b{|u~|i{|~}g{}w~}l{|}u~}a" "{}w~}L{}w~}Q{}u~|iv~|h{}w~}hv~|Y{}w~}M{}w~}W{}w~}ot~]{}w~}V{}w~|bv~|h{}w~|n{}q~f{}u~k{}u~a{}w~}Q{}u~k{|u~c{}w~}" "kv~}c{|}h{|v~}Y{|v~|X{}v~l{}v~|[v~}v~]v~}w~n{}r~|ev~}n{}v~W{|v~|Y{}v~}F{|w~}Ew~}M{|w~| u{}w~|o{}u~|_t~|q{|v~}_" "{|v~|P{|v~}pt~|a{|v~|Ew~}U{|v~|pt~|`w~}m{|w~}Wv~Lv~Tw~}s{}v~|Sv~_w~}mv~mv~hw~}m{|w~}a{}v~nv~}_u~}o{}v~a{}v~o{|u" "~|Zw~}@{}w~|Y{}w~|Sv~|p{|u~|Zv~{|v~[v~}x~}s{|r~_{|v~|u{}v~Uq~V{}v~|Fw~}Lw~|M{|w~| I{|y}~y}|r{|}x~}|`{}w~}qs~]u~" "n{|v~`{|w~r{|v~\\{|v~nv~}_{|w~}Mw~}m{|w~}Y{}r~X{}w~}nv~`{|v~|o{}v~|g{|v~|st~|t{|v~|g{}v~v{}w~v{|v~`{|w~}q{|w~}_" "v~|v{}w~uv~}au~}o{}v~a{|v~nv~}Vv~U{|w~}p{}w~}bv~|h{|v~`u~M{}w~}P{|u~|q{}v~}_{}g~}|b{}w~}hv~|Z{|v~Y{}u~k{}u~a{|y" "~A{}w~A{}~|Zl~|Z{}~|k{}~}[{|l~} yv~}Uv~}uy~}S{|v~S{}v~|x{|y}x~}|wu~X{|w~}Lw~|I{|v~}*{}x~|g{|x~}&{}y~}t{|x~ T{}x" "~|g{|x~} <{|v~|o{}v~|Ux~}w{|x~} Ex~|t{|y~}Tw~|p{}j~}j{}x~|k{}x~}aw~|p{}j~}g{}v~}Wv~|h{|v~fv~|h{|v~fv~|h{|v~f" "v~|h{|v~fv~|h{|v~g{|v~g{|v~|ov~|m{|v~V{|u~|i{|~}c{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~k{}t~d{}w~" "|n{}q~f{}u~k{}u~e{}u~k{}u~e{}u~k{}u~e{}u~k{}u~e{}u~k{}u~c{}v~|n{|u~|e{}u~|l{}u~c{}v~l{}v~|c{}v~l{}v~|c{}v~l{}v~" "|c{}v~l{}v~|Y{|v~|V{}w~}Mw~}kv~c{}w~|o{}u~|a{}w~|o{}u~|a{}w~|o{}u~|a{}w~|o{}u~|a{}w~|o{}u~|a{}w~|o{}u~|k{}w~|o{" "}s~U{|v~|P{|v~|N{|v~|N{|v~|N{|v~|Dv~Lv~Lv~Lv~Uv~}p{}v~^w~}m{|w~}a{}v~nv~}`{}v~nv~}`{}v~nv~}`{}v~nv~}`{}v~nv~}W{" "}u~W{}t~|qv~}_v~|p{|u~|`v~|p{|u~|`v~|p{|u~|`v~|p{|u~|Yq~Xu~}o{}v~Yq~ M{}w~}|w{}x~}v{}v~b{}w~}|m{}v~b{}w~}|m{}v~" "b{}w~}|m{}v~b{}w~}|m{}v~W{}x~}Nq~| M{|v~F{|u~ py~|V{|}y~y}|vy~|w{|y}y~y}Y{|s~}Q{|s~|Yw~}kw~}_{}v~|s{}v~|^{|w~}p" "{|v~X{|r~}Z{}u~} q{}v~}o{|y~}$v~}\"w~|tw~|Y{}y~}|u{|y~|x{|u~^{}x~|q{|w~s{}x~}mu~}n{|s~}&{|w~|J{|w~| u{}w~L{" "}v~ u{|v~|P{}x~}Q{}v~|r{}v~T{}w~}W{}v~}O{}|k{}v~}P{}w~}]{}|l{}u~]{|v~|q{}v~|Yv~}U{|v~}o{}v~}Q{|v~}T{}v~M{}v~C{|" "}t~}6{|t~}|D{}w~}^{}x~|s{|m~y}q~|k{|v~fv~|e{}w~}n{|u~}`{}u~|l{|}y~}g{}w~}n{|}t~}`{}w~}L{}w~}P{}u~}jv~|h{}w~}hv~" "|Y{}w~}M{}w~}W{}w~}nt~^{}w~}V{}w~|bv~|h{}w~|mq~e{}u~|n{}u~|a{}w~}P{}u~|n{}u~|c{}w~}k{|v~|d{|y~}k{|u~|Y{|v~|X{|u" "~n{|u~Z{}r~}]{}s~}n{|r~e{}v~lv~}X{|v~|Z{|u~E{|w~}E{}w~M{|w~| u{|v~p{|t~|_s~|s{|u~]u~|P{}v~}s{|s~|`u~|k{|Ww~}T{" "}v~}s{|s~|`w~}m{|w~}Wv~Lv~Tw~}r{}v~}Tv~_w~}mv~mv~hw~}m{|w~}`v~}p{}v~|_t~|q{|v~|`v~}q{|t~|Zw~}Q{|kv~|Y{}w~}S{}v~" "pt~|Z{}w~y}w~}[{}s~|rs~}_v~}s{}w~}V{}s~}W{}v~|Ew~}Lw~|M{|w~| r{|v~|s{}s~}^u~}ov~|_w~|s{}w~|[v~}pu~]v~|Nw~}m{|w" "~}Y{|s~}Xv~m{}w~|a{|u~p{|u~|fv~}t{}x~}x~}t{}v~ev~}w{}w~w{|v~}`{|w~}q{|w~}_{}v~|w{}w~v{}v~`t~|q{|v~|`v~}p{}v~U{}" "w~|Uv~|r{|v~b{|v~fv~|bu~|M{}w~}O{|u~}t{|u~}\\{|k~}|`{}w~}hv~|Z{|v~X{}u~|n{}u~|`{|@{}w~@{|Xn~|X{|i{|Y{|n~} xv~}U" "{|v~}vy~}S{|v~T{|v~|jv~}Y{|w~}Lw~|H{|v~|*{}x~}i{}x~}${}~}s{|y~ S{}x~}i{}x~} ;{|u~p{|u~|Ux~}w{|x~} Ey~|s{|~}T" "{}x~}o{}j~}k{|w~k{}x~}a{}x~}o{}j~}h{}v~}W{|v~fv~|h{|v~fv~|h{|v~fv~|h{|v~fv~|h{|v~fv~|h{}w~}f{}w~}p{|v~l{|v~U{}u" "~|l{|}y~}c{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~n{|}s~c{}w~|mq~e{}u~|n{}u~|d{}u~|n{}u~|d{}u~|n{}u" "~|d{}u~|n{}u~|d{}u~|n{}u~|d{}v~|l{|u~|et~|n{}u~|c{|u~n{|u~b{|u~n{|u~b{|u~n{|u~b{|u~n{|u~X{|v~|V{}w~}Mw~}x{|p{}v" "~c{|v~p{|t~|a{|v~p{|t~|a{|v~p{|t~|a{|v~p{|t~|a{|v~p{|t~|a{|v~p{|t~|k{|v~p{|q~j{|gu~|Pu~|k{|_u~|k{|_u~|k{|_u~|k{" "|Vv~Lv~Lv~Lv~U{|v~}r{}v~}^w~}m{|w~}`v~}p{}v~|_v~}p{}v~|_v~}p{}v~|_v~}p{}v~|_v~}p{}v~|W{}u~Vu~|q{}v~|_{}v~pt~|`{" "}v~pt~|`{}v~pt~|`{}v~pt~|Y{}s~}Xt~|q{|v~|Y{}s~} Lu~}p{}u~|au~}p{}u~|au~}p{}u~|au~}p{}u~|au~}p{}u~|W{}x~}N{}s~} " "M{|v~|Ev~} py~|Jy~|M{}t~O{|u~}Xw~}kw~}_{|t~}w|}u~}]{}w~}ov~|Xr~|Y{}t~}y| tt~|r{}x~}$v~}\"w~t{|w~X{}v~}y|y{|" "y~y|}t~|_{|x~}ow~}tw~|m{|t~|r{|}q~}&w~}J{}w~ t{}w~L{}v~ u{|v~|Pw~|Pu~|t{}v~|\\s|}w~}r|a{}v~}Nx~}|p{}t~O{}w~}]{}" "y~}|q{}t~|\\{}v~|s{}u~Y{|v~|T{}u~|r{}u~|_{~}|r{|}u~|T{}v~M{}v~@{|}w~}6{|w~}|A{}w~}^{|w~r{|o~}{}s~}iv~}f{}w~}e{}" "w~}q|y}s~|_{}t~|p{|}w~}g{}w~}r|y}q~}_{}w~}g|`{}w~}O{}t~}o{|}u~|h{}w~}hv~|Y{}w~}M{}w~}W{}w~}mt~_{}w~}h|i{}w~|bv~" "|h{}w~|m{}r~dt~}|r{|t~|`{}w~}Ot~}q{|t~}b{}w~}jv~}d{|w~}|p{|}u~}X{|v~|W{}u~|q{}u~|Z{|r~|]{|s~|mr~f{|v~|l{|v~|Y{|" "v~|[{|u~}b|^{|w~}E{|w~|N{|w~| tv~}r{}s~|_w~y}x~}|w{|}u~|]{|u~|p{|}|^t~y|x{|}w~}w~|`{|u~|n{|y~|Xw~}St~y|x{|}w~}" "w~|`w~}m{|w~}Wv~Lv~Tw~}q{}v~}Uv~_w~}mv~mv~hw~}m{|w~}`{}v~}r{}v~}^s~}s{|v~}_{}v~}s{|s~|Zw~}Qy~}|o{}w~}X{|v~}|U{|" "v~}s{|s~|Z{|q~Z{|s~qs~|`{}w~}qv~}Vs~|X{}v~|Dw~}Lw~|M{|w~| qu~|u{}w~|v~}_s~|s{|u~^{}w~t{}w~}Z{|v~}|t{|}v~|]{}v~" "|ny|^w~}m{|w~}Xs~|Y{}w~}m{|w~}a{|t~|s{}t~}f{}v~}v{|w~{w~|v{}v~}e{}v~}x{}w~x{}u~_{|w~}q{|w~}^u~}|y{}w~x{}u~}`s~}" "s{|v~}_{|v~}|t{|}v~|U{|v~}|W{|v~|t{|v~|bu~f|v~}c{}v~}h|_{}w~}Vs}t~}v{}t~s}`{|y}t~y}|]{}w~}hv~|Z{|v~Wt~}|r{|t~|#" "{}w~ vp~| {|p~} wv~}T{}v~}wy~}v{}~Z{|v~S{}x~|hx~}X{|w~}Lw~|G{}w~}){|w~|m{|w~|\"{|}q{} R{|w~|m{|w~| XY| ${|u~}r{" "|t~}Ux~}w{|x~} E{}qy|T{|w~c{}x~gw~|lw~}a{|w~c{}x~e{}v~}Vv~}f{}w~}hv~}f{}w~}hv~}f{}w~}hv~}f{}w~}hv~}f{}w~}hv~|f" "{|v~pv~}l{|v~}h|h{}t~|p{|}w~}c{}w~}g|a{}w~}g|a{}w~}g|a{}w~}g|X{}w~}M{}w~}M{}w~}M{}w~}Z{|v~r|x}q~b{}w~|m{}r~dt~}" "|r{|t~|bt~}|r{|t~|bt~}|r{|t~|bt~}|r{|t~|bt~}|r{|t~|d{|v~|j{|v~}f{}s~}|r{|t~|a{}u~|q{}u~|a{}u~|q{}u~|a{}u~|q{}u~" "|a{}u~|q{}u~|X{|v~|V{}w~}Mw~}xy~}y|wy|u~|bv~}r{}s~|`v~}r{}s~|`v~}r{}s~|`v~}r{}s~|`v~}r{}s~|`v~}r{}s~|jv~}r{}w~}" "|u~|o{|}y~g{|u~|p{|}|_{|u~|n{|y~|`{|u~|n{|y~|`{|u~|n{|y~|`{|u~|n{|y~|Wv~Lv~Lv~Lv~T{}u~}|x{|}u~}]w~}m{|w~}`{}v~}" "r{}v~}^{}v~}r{}v~}^{}v~}r{}v~}^{}v~}r{}v~}^{}v~}r{}v~}V{}u~V{|v~}r{}v~}^{|v~}s{|s~|`{|v~}s{|s~|`{|v~}s{|s~|`{|v" "~}s{|s~|Xs~|Xs~}s{|v~}Ws~| K{}u~}x|{x|}t~^{}u~}x|{x|}t~^{}u~}x|{x|}t~^{}u~}x|{x|}t~^{}u~}x|{x|}t~U{}x~}N{|s~| M" "{|w~|D{}w~| q{|y~}K{|y~}L{}v~|N{}v~Ww~}kw~}^{|j~}\\v~|o{}w~}X{}s~W{|^~} -s~}v|}v~}$v~}#{|w~t{|x~}X{}e~|^w~|o" "{|w~|v{}w~k{|s~}v|}t~y}v~}'{}w~Jw~} t{}w~L{}v~ u{|v~|Q{|w~O{|u~}w|}u~}\\{|e~|ab~`u~w}|x}r~|O{}w~}]{}v~w}|x}s~}Z" "t~}w|}t~X{}w~}S{|t~y}v|}t~}^v~y}y|y}s~|S{}v~M{}v~={|}~}6{|y~}|?{}w~}]w~}q{}r~|y{}u~}h{|v~|f{|v~e{}c~|]{}s~y}v|y" "}t~}g{}b~|^{}c~}`{}w~}N{}r~y}v|y}r~|h{}w~}hv~|Y{}w~}M{}w~}W{}w~}lt~`{}d~}i{}w~|bv~|h{}w~|lr~cr~}v|}s~}_{}w~}Ns~" "y}v|}s~}a{}w~}j{|v~|e{|s~}u|}r~W{|v~|Vs~}v|y}t~|Xs~}\\{|s~|m{}t~}fv~}j{}v~Y{|v~|[{}\\~}^{|w~}Dw~}N{|w~| t{}u~y" "|x{|}w~y}w~|_w~}{k~|[{|t~}|wy|}x~|^{|k~y|w~|_{|t~}|vy|y}w~|Xw~}S{|k~y|w~|`w~}m{|w~}Wv~Lv~Tw~}p{}v~}Vv~_w~}mv~mv" "~hw~}m{|w~}_{}u~}|x{|}u~}]w~y}w~y|yy|}u~|^{}u~}|x{|}w~}w~|Zw~}Qv~}y|v{|}u~|Wm~[{}u~}w|}v~}w~|Y{}s~}Yt~}q{}t~|a{" "}v~p{|v~|W{}t~W{}d~Uw~}Lw~|M{|w~| q{|u~}|y{|}v~{|s~br~}y|yy|}u~|^{|w~}v{}v~X{}u~}y|{y|}u~}\\{|t~}|vy|y}y~}^w~}" "m{|w~}X{}t~Xv~|lv~|b{|s~}v|}q~x}hu~}|{y|w~}{}w~}|{|}u~c{}u~}|}w~|}t~|_{|w~}q{|v~}_{|s~}v~}s~}_w~y}w~y|yy|}u~|^{" "}u~}y|{y|}u~}S{}r~}Z{}v~}|x{|}v~}b{|Z~c{}c~}_{}w~}Vk~v{}l~|^{|v~Y{}w~}hv~|Z{|v~Vr~}v|}s~|\"{}w~ ur~| y{|r~} vv~" "}St~}y|y~}{y|}x~`{}b~}a{}~|f{~}W{|w~}Lw~|G{|w~}({|v~}|s{|}v~| E{|v~}|s{|}v~| X{|Z~} ${|s~}y|{y|}q~}|}Xx~}w{|x~" "} l{}x~|c{}x~h{}x~}m{|w~|`{}x~|c{}x~f{|v~}V{|v~|f{|v~i{|v~|f{|v~i{|v~|f{|v~i{|v~|f{|v~i{|v~|f{|v~i{|v~dv~|r{|" "v~k{|b~g{}s~y}v|y}t~}c{}c~}a{}c~}a{}c~}a{}c~}X{}w~}M{}w~}M{}w~}M{}w~}Z{|b~}a{}w~|lr~cr~}v|}s~}`r~}v|}s~}`r~}v|}" "s~}`r~}v|}s~}`r~}v|}s~}b{|x~|h{|x~}f{}o~}v|}s~}_s~}v|y}t~|_s~}v|y}t~|_s~}v|y}t~|_s~}v|y}t~|W{|v~|V{}w~}Mw~}xk~}" "a{}u~y|x{|}w~y}w~|`{}u~y|x{|}w~y}w~|`{}u~y|x{|}w~y}w~|`{}u~y|x{|}w~y}w~|`{}u~y|x{|}w~y}w~|`{}u~y|x{|}w~y}w~|j{}" "u~y|x{|}u~y{|t~}|vy|}v~f{|t~}|wy|}x~|^{|t~}|vy|y}w~|_{|t~}|vy|y}w~|_{|t~}|vy|y}w~|_{|t~}|vy|y}w~|Wv~Lv~Lv~Lv~S{" "}j~}\\w~}m{|w~}_{}u~}|x{|}u~}\\{}u~}|x{|}u~}\\{}u~}|x{|}u~}\\{}u~}|x{|}u~}\\{}u~}|x{|}u~}U{}u~V{}t~}|x{|}u~}\\{" "}u~}w|}v~}w~|_{}u~}w|}v~}w~|_{}u~}w|}v~}w~|_{}u~}w|}v~}w~|X{}t~Ww~y}w~y|yy|}u~|W{}t~ I{}h~}\\{}h~}\\{}h~}\\{}h~" "}\\{}h~}T{}x~}Ms~ K{|y~}C{|w~ p{}x~K{}x~Kw~|L{}x~|Ww~}kw~}]{|l~}\\{|v~n{|w~}X{|s~U{}`~} -{|h~|$v~}#{}x~}t{}x" "~}X{|}g~|^{}x~}m{}w~}y|}v~|j{|g~}y{}v~}({|w~|L{|w~| t{}w~L{}v~ u{|v~|Q{}x~}N{}k~}[{|e~|ab~`e~|N{}w~}]{}g~}Y{|i~" "|Xv~|R{|g~}]i~|R{}v~M{}v~;y|5{|<{}w~}]{|w~|p{|v}|w{|x}|e{}v~dv~}f{}e~}|[{}d~|g{}d~}\\{}c~}`{}w~}M{}c~}|g{}w~}hv" "~|Y{}w~}M{}w~}W{}w~}kt~a{}d~}i{}w~|bv~|h{}w~|l{|s~b{}f~|^{}w~}M{}f~|`{}w~}iv~}e{|c~V{|v~|Uf~}W{}t~|[s~l{}t~|g{}" "v~hv~}Z{|v~|[{}\\~}^{|w~}D{}w~N{|w~| sj~{}w~|_w~}{|m~|Y{}i~|]{|m~|{|w~|^{|f~|Xw~}R{|m~|{}w~|`w~}m{|w~}Wv~Lv~Tw" "~}o{}v~}Wv~_w~}mv~mv~hw~}m{|w~}^h~\\w~}{k~|\\k~y|w~|Zw~}Qg~}V{|n~Zk~{}w~|Y{|s~|Y{}u~}q{|t~a{|v~|o{}v~W{|u~|W{}d" "~Uw~}Lw~|M{|w~| p{|l~|ys~be~}\\{}v~x}u~V{}j~}Z{|h~}^w~}m{|w~}X{|u~|Y{|w~}k{}w~}b{|w~}m~|s~h{|m~xm~|b{}g~|^{|w~" "}pr~a{|f~}^w~}{k~|\\{}j~}R{|r~}Y{}l~}a{}Z~}d{}c~}_{}w~}Vk~v{}l~|^{|v~Y{}w~}hv~|Z{|v~U{}f~|!{}w~ tt~| w{|t~} uv~" "}R{}i~`{}b~}`{|?{|w~}Lw~|Fw~}&{}t~w}t~} A{}t~w}t~} V{|Z~} ${|w~}m~|s~Xx~}w{|x~} m{|x~}b{}x~hw~lk~k{|x~}b{}x~" "fv~}U{}v~dv~}j{}v~dv~}j{}v~dv~}j{}v~dv~}j{}v~dv~}j{}w~}d{}w~}r{}w~}k{|b~f{}d~|c{}c~}a{}c~}a{}c~}a{}c~}X{}w~}M{}" "w~}M{}w~}M{}w~}Z{|d~}|`{}w~|l{|s~b{}f~|^{}f~|^{}f~|^{}f~|^{}f~|`{|~|f{|~}f{|w~|}f~|]f~}]f~}]f~}]f~}V{|v~|V{}w~}" "Mw~}xl~}_j~{}w~|_j~{}w~|_j~{}w~|_j~{}w~|_j~{}w~|_j~{}w~|ii~w{|f~e{}i~|]{|f~|^{|f~|^{|f~|^{|f~|Wv~Lv~Lv~Lv~R{}l~" "}[w~}m{|w~}^h~Zh~Zh~Zh~Zh~){|f~Zk~{}w~|^k~{}w~|^k~{}w~|^k~{}w~|X{|u~|Ww~}{k~|V{|u~| H{|j~|Z{|j~|Z{|j~|Z{|j~|Z{|" "j~|S{}x~}M{}u~} I{}Ax~} pw~|Lw~|L{|y~|Jy~|Vw~}kw~}[{}o~|[{}w~}mv~Wt~}T{|}b~} +{}l~}\"v~}#w~|tw~|U{|}l~}]{|w~" "ko~|h{|j~}|w{}u~({}w~L{}w~ s{}w~Lv~| u{|v~|Qw~}M{|m~}Z{|e~|ab~`g~}|M{}w~}]{}h~|W{|k~W{}v~P{|i~|\\k~}P{}v~Mv~| " "i{}w~}\\{}w~Jv~}d{}v~f{}g~}|X{|}h~}e{}g~}|Z{}c~}`{}w~}L{|}g~}|e{}w~}hv~|Y{}w~}M{}w~}W{}w~}jt~b{}d~}i{}w~|bv~|h{" "}w~|ks~a{|i~}\\{}w~}L{|i~}^{}w~}i{|v~|e{}f~}U{|v~|T{}i~|Ut~Z{}u~}l{|t~g{|v~|h{|v~|[{|v~|[{}\\~}^{|w~}D{|w~N{|w~" "| s{|l~|{}w~|_w~}x{}q~}|W{|j~|[{}p~|y{|w~|]{|g~|Xw~}P{}q~}|y{}w~|`w~}m{|w~}Wv~Lv~Tw~}n{|v~}Xv~_w~}mv~mv~hw~}m{" "|w~}]{}l~}[w~}{|m~|Zm~|{|w~|Zw~}Qh~|T{|o~Z{|m~|{}w~|Xs~X{}u~|pu~}av~}m{}w~}Wu~V{}d~Uw~}Lw~|M{|w~| o{|n~|w{}u~b" "f~}Z{}p~}T{}l~}X{|i~}^w~}m{|w~}Wu~Xv~|k{|v~b{|w~y|o~|{}t~g{|o~|x{|o~}`{}i~|]{|w~}p{}s~_{}j~}|]w~}{|m~|Z{}l~}P{|" "s~}X{}n~}`X~d{}c~}_{}w~}Vk~v{}l~|^{|v~Y{}w~}hv~|Z{|v~T{|i~} {{}w~ sv~| u{|v~} tv~}Q{}j~`{}b~}#{|w~}Lw~|G{|w~}${" "}m~} ={}m~} T{|Z~} ${|w~y|o~|{}t~Xx~}w{|x~} mw~|b{}x~i{}x~|lk~kw~|b{}x~g{|v~Tv~}d{}v~jv~}d{}v~jv~}d{}v~jv~}d" "{}v~jv~}d{}v~k{|v~|d{|v~rv~|k{|b~e{|}h~}a{}c~}a{}c~}a{}c~}a{}c~}X{}w~}M{}w~}M{}w~}M{}w~}Z{|g~}|]{}w~|ks~a{|i~}[" "{|i~}[{|i~}[{|i~}[{|i~}/{|w~|y{|i~}Z{}i~|[{}i~|[{}i~|[{}i~|U{|v~|V{}w~}Mw~}xm~|^{|l~|{}w~|_{|l~|{}w~|_{|l~|{}w~" "|_{|l~|{}w~|_{|l~|{}w~|_{|l~|{}w~|i{|l~}u{|g~d{|j~|\\{|g~|]{|g~|]{|g~|]{|g~|Wv~Lv~Lv~Lv~Q{|}p~}|Zw~}m{|w~}]{}l~" "}X{}l~}X{}l~}X{}l~}X{}l~}){|w~}l~}Y{|m~|{}w~|^{|m~|{}w~|^{|m~|{}w~|^{|m~|{}w~|Wu~Vw~}{|m~|Tu~ E{|}p~}|V{|}p~}|V" "{|}p~}|V{|}p~}|V{|}p~}|Qw~}Lu~| i{}y~| q{|w~}M{|w~}K{|}I{|}Uw~}kw~}Y{|y}w~y}|Yv~|m{}w~|X{}u~|Q{|}e~} *{|}p~" "}|!v~}#w~t{|w~Py|x}y~x}y|[w~|j{}r~|e{|n~}|t{}u~){|w~|N{|w~| s{}w~Lv~ t{|v~|R{|w~|L{|}p~|Y{|e~|ab~`y|}l~}|K{}w~}" "]{|}k~|S{}o~|Vv~}N{|m~}Z{}n~}|O{}v~Mv~ h{}w~}[v~L{|v~|d{|v~|g{}k~y}y|T{|}m~}|c{}m~x}y|W{}c~}`{}w~}J{|}k~}|c{}w" "~}hv~|Y{}w~}M{}w~}W{}w~}it~c{}d~}i{}w~|bv~|h{}w~|k{|t~_{|m~}|[{}w~}J{|l~|]{}w~}h{}w~}c{|}k~}|T{|v~R{|}m~|S{}v~}" "Z{|u~|kt~gv~}f{}v~[{|v~|[{}\\~}^{|w~}Cw~|O{|w~| q{}p~}x{}w~|_v}vy}w~y}|S{}m~}Xy}w~y}|w{|w}|[{|l~}|Vw~}N{|}w~y}" "|w{}w~|`v}lw}|Wv~Lv~Tv}m{|u}Yv}_w~}mv~mv~hw~}m{|w~}\\{|n~|Zw~}x{}q~}W{}q~}|y{|w~|Zw~}Q{|}l~}P{|y}s~X{}q~}x{}w~|" "X{}u~}X{|u~o{}v~|b{}w~}kv~}X{}w~}V{}d~Uv~Lw~|M{|w~| n{|}q~}u{|}w~bv~{}o~}|X{|r~|R{|}p~}|U{}l~}|^w~}m{|w~}W{}w~" "}Xw}|i{|w}b{|w~|{|q~|y{|t~f{|q~|v{|q~|^{|l~}[{|w~}os~]{|}o~}|[w~}x{}q~}W{|}p~}|M{|}v~}W{|p~|`{|X~|e{}c~}_{}w~}V" "k~v{}l~|^{|v~Y{}w~}hv~|Z{|v~R{|m~}| y{}w~ rx~| s{|x~} sv~}P{|}n~}|`{}b~}#{|w~}Lw~|Ty|pv~|\"y|}u~}y| 9y|}u~}y| " "R{|Z~} ${|w~|{|q~|y{|t~Xx~}w{|x~} y}| q{}x~}aw}j{|w~kk~l{}x~}aw}gv~}U{|v~|d{|v~|l{|v~|d{|v~|l{|v~|d{|v~|l{|v~|" "d{|v~|l{|v~|d{|v~|l{|v}bv}|t{}w~}j{|b~c{|}m~}|_{}c~}a{}c~}a{}c~}a{}c~}X{}w~}M{}w~}M{}w~}M{}w~}Z{|m~x}y|Z{}w~|k{" "|t~_{|m~}|X{|m~}|X{|m~}|X{|m~}|X{|m~}|.w~}v{|}n~}|X{|}m~|X{|}m~|X{|}m~|X{|}m~|S{|v~|V{}w~}Mv|wy|}u~y}|Z{}p~}x{}" "w~|]{}p~}x{}w~|]{}p~}x{}w~|]{}p~}x{}w~|]{}p~}x{}w~|]{}p~}x{}w~|g{}o~|r{|l~}|a{}m~}Y{|l~}|Y{|l~}|Y{|l~}|Y{|l~}|U" "v~Lv~Lv~Lv~O{|y}v~y}|Xw~}m{|w~}\\{|n~|V{|n~|V{|n~|V{|n~|V{|n~|(w~|{|n~|V{}q~}x{}w~|\\{}q~}x{}w~|\\{}q~}x{}w~|\\" "{}q~}x{}w~|W{}w~}Vw~}x{}q~}R{}w~} B{|t}|P{|t}|P{|t}|P{|t}|P{|t}|Nw~} 3{|~} ;f| '{|y}w~}y| 8{|y~|X{|x~}" "h{|}w~}|ay|y}w~y}| rw~}N{}w~ ?{|w~| D{}w~I{|y}w~y}|%b|\\{|x}u~y}|!y|y}u~y}y|O{|y}w~y}| {{y|}u~y}|Vy|y}v~}y| u{|" "w~| B{|v~| 1{|y}u~y}| o{|x}u~y}y| Fv~| 7y|y}v~y}| {{y|y}q~|#y|y}u~y}y| {{|y}v~y}y| a{|w~}C{}x~}O{|w~| oy}" "v~}|vv|!{|}t~y}|!{|y}t~y}|Sv|Av~\"v|Lv~ Rv|mv|mv|hv|lv|Z{|y}u~}|Xw~}v{|}w~y}|T{|}w~y}|w{|w~|Zv|Ny|y}u~y}| {{|y}" "w~}|uw|W{|u}|Wv}|o{|v}av|ju|Xv~| sv~Lw~|M{}w~| ly|}v~}|Uv~yy|}v~y}|S{|y}~y}|N{|y}v~y}|Qy|y}v~x}|[v|m{|w~}W{|w~" "|#{|w~|x{|}w~}|v{|}y~y}c{|y}x~y}ry}x~y}|Z{|y}s~}y|G{}w~}|Zy|v~}|Ww~}v{|}w~y}|T{|y}v~y}| x{|y}w~}| Ry|y}v~y}|" " Zy| rv~}M{|y}u~}|]`| Iw~|T{|y~}|u{|u~ 5{|w~|x{|}w~}|v{|}x~}Wx~}w{|x~} {}y~} r{|y}|Kw~|L{|y}|Hv~| E" "{|y}u~y}| qy|y}v~y}|Sy|y}v~y}|Sy|y}v~y}|Sy|y}v~y}|Sy|y}v~y}|+{|y~}r{|y}v~y}|R{|y}v~y}y|S{|y}v~y}y|S{|y}v~y" "}y|S{|y}v~y}y| oy}v~}|vv|Zy}v~}|vv|Zy}v~}|vv|Zy}v~}|vv|Zy}v~}|vv|Zy}v~}|vv|d{|}v~y}|n{|y}u~y}y|\\{|}t~y}|U{|y}" "t~y}|T{|y}t~y}|T{|y}t~y}|T{|y}t~y}|Rv|Lv|Lv|Lv|!v|lv|Z{|y}u~}|R{|y}u~}|R{|y}u~}|R{|y}u~}|R{|y}u~}|'{}x~|w{|y}u~" "}|S{|y}w~}|uw|Z{|y}w~}|uw|Z{|y}w~}|uw|Z{|y}w~}|uw|Vv~|Vw~}v{|}w~y}|Qv~| Mw~| K{|y~| e{|w~Nw~" "| ?{}w~ Cw~} .{}w~ @{|v~|d{}| Kv~| !u~| J{|w~}C{|w~O{|w~| 9w~} Iv~ bw~}9{|w~| X{|v~ rv" "~Lw~|M{}w~| <v~ S{|w~}W{|w~|#{|w~| j{}w~ s{}w~Uw~} )v~}Iy~} gw~|T{|u~y}s~| 5{|w~|Ax~}w{|x~} {" "{x~| 0{|v~ ?{}y~} R{|} 5x~| O{|y~} &{|v~Uw~}D{|v~ Lw~| K{|y~| d" "{}x~}P{}w~ >w~| D{|w~| .w~| ?{|v~}g{|x~| M{|v~ {|u~| K{|w~}Bw~|P{|w~| :{}w~} Iw~} bw~}9{" "|w~| X{}w~| r{}w~|Mw~|Mv~ ;v~ S{|w~}W{|w~|#{|w~| j{}w~ s{}w~Uw~} )v~}Iy~} gw~|T{|l~| 4{|w~" "|Ax~}w{|x~} {{}y~} /v~| ?x~| f{|x~ M{} %{}w~|Uw~}D{}w~| Lw~| K" "{|y~| d{|w~Pw~| ?{|w~ C{}w~ .{|w~ ={|u~}|l{|u~| N{}v~ {{|u~| L{|q~}H{}x~}V{}q~| :v~| Iw~}" " bw~}9{|w~| Xv~ q{}w~}Mw~|N{|v~ ;v~ S{|w~}W{|w~|#{|w~| j{}w~ s{}w~Uw~} )v~}Iy~} gw~|T{|}o~}| " " 3{|w~|Ax~}w{|x~} {{|x~| 0v~}m{} N{|x~ e{}y~} Rv~Tw~}Dv~ S{}x~x{|w~| " " K{|y~| c{}x~}R{}x~} >{|x~| Cw~} .{|x~| ;{}t~}|sy|}t~| N{|v~} y{|u~| M{|q~}H{|w~V" "{}q~| ;{}v~ I{|w~} bw~}9{|w~| Y{}w~} q{|v~}|Ow~|P{|}v~} ;v~ S{|w~}W{|w~|#{|w~| j{}w~ s{}w~Uw~} " " )v~}Iy~} gw~|Q{|y}v~y}| 1{|w~|Ax~}w{|x~} yx~| 0{}v~|p{|~} N{|x~| f{|x~ " " S{}w~}Tw~}E{}w~} S{}x~|y{|w~ J{|y~| bw~|Sw~| >{}y~} K{}y~} 9{|p~x}q~}| N{|u~" "| x{|u~ M{|q~} y{}q~| K{|}|p{|u~| I{}w~| bw~}9{|w~| Z{|v~ o{}q~}Tw~|U{|p~ :v~ S{|w~}W{|w~|#{|" "w~| j{}w~ s{}w~Uw~} )v~}Iy~} gw~| W{|w~|Aw|vx| y{|x~} 0{|u~|s{}x~} N{|x~| " " f{|x~| U{|v~Sw~}F{|v~ R{|x~}y{}w~ J{|y~| b{|x}|T{|x}| w{}g~}| Q" "x|y}u~} v{|u~ N{|p} yp}| K{|x~}y|wy|}u~} J{|}v~ aw~}9{|w~| \\{|}v~} nq~}Tw~|U{|q~| :v~ S{|w~}" "W{|w~|#{|w~| j{}w~ s{}w~Uw~} )v~}Iy~} gw~| W{|w~| :{|}w|}w~| /t~y}x|y}v~} U{|}|x{|w~| " " f{}x~| W{|}v~}Sw~}H{|}v~} Qq~| J{|y} *{|}l~}| O{}q" "~ tt| `{|i~} Lr~| aw~}9{|w~| `{}q~ l{}s~}Tw~|U{|s~}| 9v~ S{|w~}W{|w~|#{|w~| j{}w~ s{}w~Uw~" "} )v~}Iy~} gw~| W{|w~| :{|q~ .{|i~} U{|q~ ly}w|}w~| [{}q~Rw~}" "L{}q~ P{}r~ M{|y}u~y}y| L{}r~| R{|j~} Ks~} `w~}9{|w~| " " `{}r~| jy|v}|Tw~|U{|u}| 6v~ S{|w~}W{|w~|#{|w~| j{}w~ s{}w~Uw~} )v~}Iy}| gw~| W{|w~| :{|r~| " " -{|k~}| U{|r~} l{}r~} Z{}r~|Rw~}L{}r~| O{}t~ " " k{}t~} -{|`}| `{|}m~}| Jt~} _w~}9{|w~| `{}s~| :w~| cv~ S{|w~}W{|w~|#{|w~| j{}w~ s{}" "w~Uw~} )v~} d{|w~| 9y}w~y} ){}o~}| S{|}u~}| k{}r~ Y{}s~|Qw~" "}L{}s~| M{}w~} j{}w~}| +{}`~} ]{|x}v~y}| Gw~y} ]w~}9{|w~" "| `{}v~}| 8w~| cv~ S{|w~}W{|w~|#{|w~| j{}w~ s{}w~Uw~} g{|w~| 8{|}v~y}| Ly| " " g{|y}w~}| X{}v~}|Ow~}L{}v~}| Iy| " "l{}`~} Ww~| " " L{}`~} Ww}| " " r{" }; // Define a 104x128 binary font (huge sans). static const char *const data_font_huge[] = { " " " " " " " " " " " " " " " " " FY AY " "'Z ;W @Y @Y 'Z Y @Y (Z :Y ?Y (Z 0Y ?Y (Z >X " " " " " " " " " " )X AX '\\ )XAV 7YDY -] BY BY '[ +YEY 2X AY (\\ -YDY 'XAU 3Y AY (\\ )XAV 8YD" "Y LY AY (\\ ,YEY #Y " " " " " " " " (X CX '^ +[CU 6ZEY .` C" "X CY '] -ZEZ 2X CY (^ .ZEZ )[CU 2Y CY (] *[CU 7ZEZ LY CY (] -ZEZ %Y " " " " " " " " " " 'Y EY '^ ,^FV 6ZEY /b CX DX '_ .ZEZ 2Y DX '_ /ZEZ +_FV 1X CX (_ ,^FV 7ZEZ " " KX CX (_ .ZEZ &Y " " " " " " " " %Y GY '` .aHV 6ZEY 1e DY FX" " 'a /ZEZ 1Y FX '` /ZEZ +aHV 0X EX '` .aHV 7ZEZ JX EX (a /ZEZ &X " " " " " " " " " " #X GX 'XNX 0dKW 6ZEY 1f DY HX &WMX 0ZEZ 0X GX 'XMW 0ZEZ ,dLX /X GX 'WMX 0dLX 7ZEZ" " IX GX 'WMX 0ZEZ 'X :T " " " " " " " " ;X IX 'XLX 1o 5ZEY 2ZLY " " CX IX &WKW 0ZEZ /X HX (XLX 1ZEZ ,o .Y HX (WKX 1o 6ZEZ IY IY (WKW 0ZEZ (X <Z " " " " " " " " " " =X KX 'XJX 3WKd 5ZEY 3XGX CX JX 'WIW 1ZEZ .X JX (XJX 2ZEZ -WKd -X " "IX (WIW 2WKd 6ZEZ HX IX (WIW 1ZEZ )X =^ " " " " " " " " >X MX &WH" "W 3VHa 4ZEY 3WDW CX LX 'WGW 2ZEZ -X LX 'WHW 2ZEZ -VHa +X KX (XHW 3VHa 5ZEZ GX KX (WGW 2ZEZ )X " " ?b " " " " " " " " ?W MW &WFW 4VF^ 3ZEY 4WBV BW MX 'WEW 3ZEZ ,W M" "X 'WFW 3ZEZ -VF^ )X MX 'WFW 4VF^ 4ZEZ FX MX 'WFW 3ZEZ *X ?d " " " " " " " " " " ?W X 'WDW 5UC[ 2ZEY 4VAV AW X &WDW 4ZEZ +W NW 'WDW 4ZEZ -UC[ 'W MW 'WDW 5UC[ 3ZEZ " "EW MW 'WDW 4ZEZ +X ?f " " " " " " " " @X \"X 'WBW 6UAW 0ZEY 4V@V B" "X !W &WBV 4ZEZ +X !W 'WBW 5ZEZ .VAW $W W 'WBW 6UAW 1ZEZ DW W 'WBV 4ZEZ +W >f " " " " " " " " " " ?X #W 'W@W U?V AX #W &W@V NX #W &V@W 9W \"W 'W@V .W " "\"W 'W@V !W >XHX " " 3Y " " " " " " 6W $W &V>V U?V @W $W &W>V " " NW $X 'V>V 8W $X (W>V /X $W 'W>V #W >XFX " " 5Z " " " " ,Z " " GZ " " #U?V NY 7Z ,X CVCW MY " " 7Z ,X $Z 7Z ,X >Z 6Y ,X 4Z 7Y +W 7Y @Z " " " " +Z " " " " HY \"U?V " " MY 8Y ,Y CVBV LY 9Z ,Y #Z 9Z ,Z >Z 8Y ,Y 3Y 8Z ,Y 9Y " " ?Z " " *Y " " " " IY !U?V " " LY :Y ,[ $R>U ,V@V MZ :Y +Z #Y 9Y +Z ?R" ">U 8Y 9Y +Z %S?U HY :Z ,[ ;Y ?[ " " " " )Y " " 8U " " 9Y V@U JY <Y" " +[ 'XAU ,V@V LY ;Y +\\ #Y ;Y +\\ CXAU 7Y ;Z ,\\ )XAV HY ;Y +[ <Z " " ?U ;T $W /W " " 8e !f LY Y LX " " L] :Y <Y NX 0X >Y @Y /X 0Y K` .X " " ^ =ZEY @Y " " NVAV <P -X +Y =Y +] )[CU 7YDY 4V@V KY =" "Y +] ,YDY 5Y =Y *] .YDY 5[ M[CU 6Y <Y ,] *[CV 7YDY Y =Y +] ,YEZ !Y =Y FYDY 8X " " EU :T %W .X " " 9e !f KY !Y LY \"a :Y " "<Y NX 0X >Y E^ /X 0_ %f 1] 'c " " @ZEZ AY MV" "CW <R 4a .Y >X *^ +]DU 7ZEZ 5U>U JY ?Y *^ -YEZ 4Y " " ?Y *^ .ZEZ 5[ ]DU 5Y >Y +^ ,]DU 6ZEZ Y ?Y +_ .ZEZ \"Y <Y FYEZ :[ FU " " 7Y -T 7W#W <Y 9X -W DU KY HZ \"\\ 4Z M[ \"" "Y LZ +\\ 8] >Z G[ G\\ @e !f JX !Y " "LY %d :Y <Y NX 0X >Y Ha /X 0b *j L] D_ " " +g A[ LY 8Z -ZEZ \"Y 1o )V FX NZ FY " "%Y ,X NX*Z NW 3WEW H\\ #[ !Z \"[ \"[ \"[ G[7T 8g 0Y " "@Y +_ ,_FV 7ZEZ 5U>U IY @Y +` .YEZ 3X ?X *` /ZEZ 4[:P 8_FV 4X ?Y +` ._EU 6ZEZ NX @Y *_ .ZEZ #Y ;Y" " FYEZ ;] GU <b 1T :]'X @b >W ,X " " FV a \"d -g >d (d +b %b 4f Bg Ie \"e \"h " " Ge !f IX \"Y LY &e :Y <Y NX 0X >Y Jc /X 0c " " -n $g I` .j >a ;e HU .U +b Ac 2ZEZ 'b " " 5o -] Na (c KY .Y #_ 8Y!W'Y\"X.c$X 3XGX Mf -e +d " ",e ,e ,e \"e=V ;k 1Y BY +XNW .aGV 7ZEZ 5V@V HX AY +XNW .YEZ 3Y AY *WNW /ZEZ 4\\>T 9`GV 3" "X AY +XNW .`GV 6ZEZ NY AX *XNW /ZEZ $Y :Y FYEZ <_ IU (Q LZ 4Z2Z 1Q " " &g %Z +XCX MT <a)W Ah $X HX +X GV GX 3e )_ /j 4n L] ?y /i C~S =i 0g " " +g L\\ 8t (m Ks 2~R E} <o HZ(Z :Z \"Z 4Z,] LZ 2_'_(^-Z Ck :q 0k ?q *n J~d'Z(Z*Z LZ=Z.\\.Z7Z(Z([$Z'~^" " @e 3X Ff )\\ MY #Y LY (g :Y <Y NX 0X >Y Kd /X 0e 0p " " (m Lb 1m ,\\ 5~S E~R Ah 'Z :~]+[;Z;Z Ik LW DX DW /i ?Y(Y 4h 5ZEZ" " ,\\ ,h 7\\ -o .` $f -h NY No %_ %c @_\"X-_\"W0h&W .\\ $\\ \"\\ #\\ #\\ )g 5~a Lm D~S I~S " "H~R H~R 6Z !Z !Z \"Z :r 8^,Y Bk 2k 2k 2k 2k (kAX+Z(Z#Z(Z$Z(Z$Y'Y&[%[ MZ Im 1X CY *WMX /bHV 7ZEZ 5V@V G" "X CY *WLW /YEZ 2Y CY *WLW 0ZEZ 3[AW :bHV 3Y BX *WLW 0bHV 6ZEZ MY CX *XMX 0ZEZ $X 9Y FYEZ " " =a M~i 7U (Q N_ 9_8_ 3R )k 'Z +XCX +X@X 4T >e,X Cl &X IX *X GV " " GX 5i 0d 2p ;u !^ ?y 2o F~S @n 4j /l N\\ 8x .r Nx 7~R E} >t KZ(Z :Z \"Z 4Z-] KZ 2_'_(^-Z" " Ep =t 5o Au 1u N~d'Z(Z)Z MZ<Z/\\/Z5Z*['[&Z&~^ @e 3X Ff )] MY $Y LY )h :Y <Y NX 0X >Y " " Le /X 0e 1r +r c 3o -\\ 5~S E~R Dn *Z :~]+[;Z;Z Ko " " Y EX EY 2m @Y)Y 6l 7ZEZ 0e 2k >e 1o 0c 'j /i X !r (b 'g Eb\"W0c#X0i(W -" "\\ $] #\\ $] #\\ (f 6~b r F~S I~S H~R H~R 6Z !Z !Z \"Z :w =^,Y Ep 6p 7p 7o 7p ,oDY+Z(Z#Z(Z$Z(Z$Y'Y%Z%Z LZ Kp" " 1X DX *WKW /WMYJV 6ZEZ 5V@V GY EY *WKX 0YEZ 1Y EY *XKW 1ZEZ 2[EZ :WMZKV 1Y DX *WKX 1WLYKW 6ZEZ L" "Y EY *WKW 0ZEZ %X 8Y FYEZ >c M~h 7T (S !a <b:b 6S %| $o " ")Z +XCX +W?W 3T ?g.X Dp (X IX )X HV HY 6l 7i 5t <v #_ ?y 3p F~S Aq 8n 3p (Y $^ 9z 2v!{ :" "~R E} Az NZ(Z :Z \"Z 4Z.] JZ 2`)`(_.Z Gt ?w :s Cx 5x!~d'Z(Z)Z N[<Z/\\/Z5[,[%Z'[&~^ @e 2X Gf *_ MX $Y " "LY )h :Y <Y NX 0X >Y >X 8f /X 0f 3t -s c " " 4q /^ 6~S E~R Fr ,Z :~]+[;Z;Z Ms #[ FX F[ 4n @Y*Y 6m 7ZEZ 3k 5l Bk 4o 1f )k 0k #" "X #u (b (i Fb#X0c#W/k+X .^ %] $^ %] $^ (d 5~b\"v H~S I~S H~R H~R 6Z !Z !Z \"Z :{ A_-Y Gt :t ;t ;s ;t " " 0sGY*Z(Z#Z(Z$Z(Z$Y'Y$Z'[ LZ Ls 2X FX *WIW 1WJc 6ZEZ 4VBV EY FX *XJW 0YEZ 0X EX )WJW 1ZEZ 1[I^ <WJc 0" "X EX )WJW 2WJZNW 5ZEZ KX FY *WIW 1ZEZ &X 7Y FYEZ ?d M~h 8U )T #e ?d=e 8U " " *~Q &r *Z +XCX +W?W 3T @i/W Dq (X JX (X HV HX 7o <m 7x >x %_ ?y 5r F~S Ct :p" " 6s /e *^ 9| 6z#~ =~R E} B}!Z(Z :Z \"Z 4Z/\\ HZ 2`)`(_.Z Iw @y >w Ez 9z!~d'Z(Z)[ Z;Z0]/Z4Z,Z$[(Z%~^ " "@e 2X Gf +a MX %Y LY *i :Y <Y NX 0X >Y >Y 9f /X 0g 5v " " 0u d 6_K_ 0^ 6~S E~R Gu .Z :~]+[;Z;Z w &] GX G] 6U &o ?Y+Y 7X )n 7ZEZ " "6p 7m Eo 6o 2h *l 1l %X #v (b )k Gb$X/c$X/l,W -^ &_ %^ &_ %^ 'b 4~b$z J~S I~S H~R H~R 6Z !Z " "!Z \"Z :~ D_-Y Hw =v >w >w >w 4wIX)Z(Z#Z(Z$Z(Z$Y'Y$[)[ KZ Mt 1X HX )WHW 2VHb 6ZEZ 4WDW DX GX )WHW 1YE" "Z /X GX )WHW 2ZEZ 0[M` ;VHb /X GY *WHW 3VHb 5ZEZ JX GX )WHW 2ZEZ 'Y 7Y FYEZ ?e M~f " " 7U )U %g Bh@g :W .~T 't +Z +XCX ,X@X 3T Ak1X Er (X JX 'X IV HX 8q" " =m 7y ?y '` ?y 6s F~S Dv <r 8u 4m /_ 9~ :~%~Q ?~R E} D~Q\"Z(Z :Z \"Z 4Z0\\ GZ 2`*a(`/Z Jz Bz Az F{ " ";{!~d'Z(Z(Z Z;Z0^0Z3Z.[#[*Z$~^ @X %X :Y ,c MX &Y LY +^ .Y <Y NX 0X >Y >Y " " :] %X &] 5]C\\ 1v Nc 7\\D\\ 1_ 6~S E~R Iy 0Z :~]+[;Z;Z!y (_ H" "X H_ 7U 'p ?Y,Y 6X *o 7ZEZ 8t 9YH] Ht 9o 3i *XG[ 1VE[ &Y %x (b *[I[ Hb$W.c%X.VE[-X " " ._ &_ %_ '_ %_ '` 4~c%} L~S I~S H~R H~R 6Z !Z !Z \"Z :~Q F`.Y Jz @z Az Ay Az 7zKX(Z(Z#Z(Z$Z(Z$Y'Y#[*Z JZ Na" "J_ 2X IX )WGW 2VG` 5ZEZ 4XFX CX IX )WFW 2YEZ .X IX )WFW 3ZEZ /j 8VG` -X HX *WFW 4VG` 4ZEZ IX IX " ")WGW 2ZEZ 'X 6Y FYEZ ?XKX M~f 7T )W 'i DiAi ;X 1~V (w -Z " "+XCX ,X@X 3T AZI[2W Es (X KX &X IV HX 9s >m 7z @z )a ?y 7t F~R Dx >t 9v 8s 2` :~P <~Q&~S" " A~R E} E~T$Z(Z :Z \"Z 4Z2] FZ 2a+a(`/Z K| C{ C} H| =|!~d'Z(Z(Z!Z9Z1^1Z2[0[!Z+[$~^ @X $X ;Y -e MX 'Y " "LY +[ +Y <Y NX 0X >Y >Y :[ #X #Z 6\\?[ 2v F\\ " " 8Z@[ 2` 7~S E~R J{ 1Z :~]+[;Z;Z#} +` HX Ia 8U (q >Y-Y 6X +p 7ZEZ 9bMb ;U@Y JbMb :" "n 3ZIZ +T@Y 2R>Y 'X %y (XLV +ZEZ IXMW%X.YMW%W-R>Y.W -` '_ &` '_ &` '` 4~c'~R N~S I~S H~R H~R 6Z !Z " "!Z \"Z :~S Ha/Y K| B| C| D} D| 9|MX'Z(Z#Z(Z$Z(Z$Y'Y\"Z+[ JZ N]B\\ 2X JX *WEW 3UE_ 5ZEZ 3YJY AX JW )WE" "W 2YEZ -X KX (WFW 3ZEZ .f 5UE_ ,X JX )WFW 4VF_ 4ZEZ HX KX )WEW 3ZEZ (X 5Y FYEZ @YJW M~" "e 7U *X (j EkCk =Y 3~X )x -Z +XCX ,W?X 3T BYEY3X Ft (X KX %X JV " " IX 9u ?m 7{ A{ *a ?y 8u F~R Ez @v :v :w 4` :~Q >~S'~U C~R E} G~V$Z(Z :Z \"Z 4Z3] EZ 2a+a(a0Z M~P D" "| E~P I} ?}!~d'Z(Z'Z\"Z9Z1^1Z1Z0Z [,Z#~^ @X $X ;Y .g MW 'Y LY +Y )Y <Y NX 0X >Y " " >Y :Z \"X \"Z 7[=Z 3aE[ E[ 9Z>[ 3` 7~S E~R L~ 2Z :~]+[;Z;Z$" "~P -b IX Jc 9U )r >Y.Y 5X ,]DX 7ZEZ ;\\>\\ <R;X M]>\\ 0XDX ,R=Y MX (X %hEW (SG" "V ,YAY JSHW%W-SGW&X GX/W ,` (a '` (a '` (a 5~d(~S N~S I~S H~R H~R 6Z !Z !Z \"Z :~T Ia/Y L~P F~P F~P F~P F~P" " <~X&Z(Z#Z(Z$Z(Z$Y'Y\"[-[ IZ \\>Z 1X LX )VCW 4UD] 4ZEZ 2f ?X LX )WDW 3YEZ ,W KX )WDW 4ZEZ -b 2UD] *W" " KX )WDW 5UD] 3ZEZ GW LX (VCW 4ZEZ )X 4Y FYEZ @XIX M~d 7U *Y *l GmDl ?[ " " 6~Z *`C\\ -Z +XCX ,W?W 2T CYCY5X E]CZ (X LX $X JV IX 9]E^ @m 7aGb B^Ec ,b ?y " "9aF[ F~R E_C_ B_E^ ;]E_ ={ 7b ;~R @cBb'~V D~R E} HeBc$Z(Z :Z \"Z 4Z4] DZ 2b-b(a0Z NbCb E} GbCb J~ Aa" "B_!~d'Z(Z'Z#[9Z2_1Z0Z2[ N[.Z\"~^ @X $X ;Y /i MW (Y LY ,Y (Y <Y NX 0X >Y >Y " " :Y !X !Y 8[;Z 1\\ 0\\:U D[ ;Z<Z 4b 8~S E~R M~R 4Z :~]+[;Z;Z%bCb " "/d JX Ke :U )]BW =Y/Y 5X ,[?U 3Z8[ &W NZ7Z 2XBW EX LW )X %iEW KV -Y?Y @W&X" "!W&W EW0X -b )a (b )a 'a )a 5~d)dCb N~S I~S H~R H~R 6Z !Z !Z \"Z :~V Kb0Y MbCb HbCb HbCb HbCb HbCb >bCh%Z(Z" "#Z(Z$Z(Z$Y'Y![.Z HZ Z;Z 1X NX )WBV 5VBZ $e >W MX )WBW !X MX )WBW #` /UBZ (W MX )WBW 6UBZ " " 9X MW (WCW MX 3Y GXHW M~d 8U *[ +m HnFn A] 9~\\ +^=Y" " -Z +XCX -X@X 2U DXAX5W E\\=V (X LX #X .R@V?Q ,X :\\A\\ @m 7\\>_ CY<_ -c ?y :^=V F~Q E]>^ D]@] " " <Z@^ @~P 9b ;Z=d Aa;^'Z>j E~R E| Ha8^$Z(Z :Z \"Z 4Z5] CZ 2b-b(b1Z `<_ FZ@d I`=` K[@d C_:Z ~b&Z(Z'Z#Z8Z2`" "2Z0[4[ LZ/[\"~^ @X #X <Y 0\\N] NX )Y LY ,Y (Y ;X NX 0X >Y >Y ;Z " "!X !Y 8Z9Y 6d 4[5R CZ ;Y:Z 5b 8~R D~Q MbAb 8` =~]+[;Z;Z&`=` 1f KX Lg " " ;U *\\=T =Y0Y 4X ,Z;R 5Z3Y &W !Y3Y 3W@W EW LX *W %jEW KV -X=X @W'X W'X EX1W ,b " "*b (b )b )b )b 7ZH~R)a:] N~R H~R G~R H~R 6Z !Z !Z \"Z :Z>j Lb0Y N_<` J`<_ J`=` J`=` J`=` @`=e%Z(Z#Z(Z$Z(Z$Y'Y" " Z/[ HZ !Z9Y 0W X )WAW 6VAW \"d <W X (VAW X X (V@V &a .VAW &X NW (V@V 6UAW 6X X )WAW " " NW 2Y N\\ #[ \"\\ #\\ #[ MXHW L~b 7U +\\ ,n IoGp C_ ;~] ,]:X -Z " "+XCX -X@X 8c LX@X7X E[:T (X MX \"X /TAVAT .X :\\?\\ Am 7Y9] CT4] .c ?Y J]8S Z E\\;\\ E]=[ " " <W;\\ B~T ;b ;Z7_ C_5['Z7e GZ MZ '`3[$Z(Z :Z \"Z 4Z6] BZ 2b-b(b1Z!_8^ GZ;` K_9_ LZ:` D]5W 3Y 9Z(Z&Z$Z7Z3`3Z." "Z4Z JZ0Z \\ ?X #X <Y 1\\L] NX *Y LY ,Y (Y 8X >Y >Y ;Y X !Y " " 8Y8Y 6f 6Z2P BY <Z9Z 7c 7\\ Z (`;` >j BZ(Z+[;Z;Z'_9_ 3h LX Mi <" "U *[:R <Y2Z 4X -Z8P 6Y/X 'W #Y/Y 6W>V EW KW +W %kEW KV .X;W @W'W NW(X CW2X -c *c )b " "*c )c +c 7ZHZ 2_5[ NZ !Z Z !Z >Z !Z !Z \"Z :Z7d Mc1Y ^8_ K^8^ L_8^ L_9_ L^8_ B_9b$Z(Z#Z(Z$Z(Z$Y'Y [1[ GZ !Z" "8Y 0W !W (V?W I` :X !W (V?W X \"X (W@W *d EX !W (W@W 0X \"X (V?W !W 1Y #d ," "e +d +d ,e #XHW LZ#Z 7U +] -o KqHp C_ <c 2]7V -Z +XCX -W?X <l#X?X7W E[7R " "(X MX \"Y 0VCVCV .X :[<[ B\\IZ 7V5] DQ0] 0XNZ ?Y K\\4Q !Z E\\9\\ F\\;[ =U8[ DdAc =d <Z5^ " "E^1Y'Z3b HZ MZ (_/Y$Z(Z :Z \"Z 4Z7] AZ 2c/c(c2Z!]4] HZ9^ L^5^ MZ8^ E\\0T 3Y 9Z(Z&Z%Z6Z3`3Z-Z6[ J[2Z \\ >X #X " " <Y 2\\J] NW *Y LY ,X 'Y 8X >Y >Y ;Y X X 9Z7X 6g 7Y" " #Z =Y8Z 7d 7[ Z )_7_ Bp EZ(Z+[;Z;Z(^5^ 5j MX Nk =U +[7P <Z3Y 3X -Y " " MX+W 'V $X+X 7V=W FW KW ,W $kEW KV .X;X AW(X NW(W BW2W ,d +c *d +c *d +c 7ZHZ 3^0X NZ !" "Z Z !Z >Z !Z !Z \"Z :Z3a Nc1Y!^5] L]4] N^5^ N^5^ N^5] C^5_#Z(Z#Z(Z$Z(Z$Y'Y N[2Z FZ \"Z7Y /W #W (W>V H^" " 8X #W (W>V NW \"W (W>W .h EW \"X )W>W 0W #X (V=V \"W 0Y &j 1i 0j 1j 1i &X <Z#Y " " 7U +_ /p KrJr Ea >` .\\5U -Z +XCX -W?W =r'X>W8X EZ ;X NY !X 1XDVDX 2X " " &X ;[;[ BWDZ 7T2\\ \"\\ 1XMZ ?Y L\\ 2Z E[7[ G\\9[ >S5[ F`7` ?YNY <Z3\\ F]-W'Z0` IZ MZ )^+W$" "Z(Z :Z \"Z 4Z8] @Z 2YNX/XNY(c2Z\"]2] IZ7] N]2] MZ6] G\\-R 3Y 9Z(Z&[&Z6Z4XNW3Z-[8[ HZ3[ !\\ =X #X <Y 3\\H] N" "W +Y LY ,X 'Y 8X >Y >Y ;Y X Y :Y6Y 7i 9Y \"Y " " >Y6Y 7YNY 6[ !Z *^3] Dt GZ(Z+[;Z;Z)]2] 6l NX m >U +Z !Y4Z 3X -Y NW(W (W " " &X)X 8V<V +X DW LW ,W $lEW KV .W9W AW(W MW)X CW2W +YNY ,YNZ +YNY ,ZNY +YNY +YNY 9ZGZ 4^.W NZ !Z" " Z !Z >Z !Z !Z \"Z :Z1` d2Y\"]2] N]2] ]2]!^2]!]2] E]2]\"Z(Z#Z(Z$Z(Z$Y'Y MZ3[ FZ \"Z6X .V $W 'V<V GZ " " 5W $W 'V<V NW $W 'V<V 2m EW #W (V<V /W $W (W=W #W 0Y (n 6o 5n 5n 6n (X ;Z%Z " " 7U ,a 0q LrJr Fc A_ ,\\2S -Z +XCX .X@X ?u(W=X:X DY :X NX Y 2ZFVFZ 2X " "'X :Z9[ CR?Z 7R/\\ \"[ 1XMZ ?Y L[ 2[ F[5Z G[7Z >R4[ G^1^ AZNY <Z2[ G]*U'Z.^ IZ MZ )](U$Z(Z :Z \"Z" " 4Z9] ?Z 2YNX0YNY(d3Z#]0] JZ6\\ N\\/\\ NZ5\\ G[ <Y 9Z(Z%Z&Z6Z4XNX4Z,Z8Z FZ4Z [ <X \"X =Y 4\\F] #Y " "LY -Y 'Y 8X >Y >Y ;Y X Y :Y6Y 7j :Y \"Y " " >Y6Z 9YMY 5[ \"Z *]1] Hy IZ(Z+[;Z;Z)\\/\\ 8n X !o ?U ,[ Y5Y 2X -Y W&W )W 'W%W 9V" "<V +X DW LW )mEW KV /X9X BW)X MW)W BW3X ,YMY ,YMY ,ZNZ -YMY +YNZ -YMY 9ZGZ 5]*U NZ !Z Z !Z >Z " "!Z !Z \"Z :Z/_!d2Y#]0]!]0]\"]0\\!\\/\\\"]0] F\\0]#Z(Z#Z(Z$Z(Z$Y'Y M[5[ EZ \"Y5X +P " " %_K[ CY *r 9q 8r 9r 9q *X ;Z%Z >Q JT ,b 0q MsKs Ge " "C^ *[0R -Z +XCX .X@X @v)X=X:W CY :X Y NX 1[HVH[ 1X 'X ;Z7Z 0Z 7P,[ ![ 3XLZ ?Y M[" " 1Z EZ4[ I[5Z ?P1Z I^-] BYLY =Z1[ H\\(T'Z-^ JZ MZ *\\$S$Z(Z :Z \"Z 4Z:] >Z 2YMX1XMY(YNZ4Z$].\\ JZ5" "\\!\\-\\ Z4[ GZ ;Y 9Z(Z%Z'Z4Z5XNX5Z*Z:[ F[6Z [ ;X \"X =Y 5\\C[ #Y LY -Y 'Y 8X >Y " " >Y ;Y X Y :Y6Y 7k ;Y \"Z @Z5Y 9YLY 5[ #Z +\\.] J| KZ" "(Z+[;Z;Z*\\-\\ :p !X \"q @U ,Z NY6Y 1X -X W#V *W (W#W :U;V +X DW LW )mEW KV" " /X9X BW*X LW*X BW3W +YLY -YMY ,YLY -YMY ,YLY -YMZ ;ZFZ 5\\'S NZ !Z Z !Z >Z !Z !Z \"Z :Z-^\"e3Y#\\.]#].\\" "#\\-\\#\\-\\#\\-\\ H\\.]$Z(Z#Z(Z$Z(Z$Y'Y L[6Z DZ \"Y5Y /[G[ " " DY +u =u <u ;u =u ,X :Y&Z >S LU ,c 1q MtLt Hf E] )[.Q " " -Z +XCX .W?X Bx)X=X;X DZ :X X MY 0ZIVIZ /X 'X ;Z7[ 1Z AZ ![ 4XKZ ?Y MZ 0Z EZ3Z I[5Z " "Z J])\\ CYLY =Z1[ I\\%R'Z+] KZ MZ +\\\"R$Z(Z :Z \"Z 4Z;] =Z 2YMX1XMY(YNZ4Z$\\,\\ KZ4[\"\\+[ Z4\\ I[ ;Y 9Z(Z$Z" "(Z4Z5WLW5Z*[<[ DZ7[ !\\ ;X \"X =Y 6\\A[ $Y LY -Y 'Y 8X >Y >Y " " ;Y X Y :Y6Y 7l <Y !Y @Y4Z :YLY 4[ $Z ,\\,] M~Q MZ(Z+[;Z;Z+\\+\\ <r \"X" " #s AU ,Z MY7Y 1X -Y \"W!V :f (V!W ;U;V +X EX MW (mEW KV /W7W BW*W KW+X BW3X " " +YLY .YKY -YLY .YKY -YLY .ZLY ;ZFZ 6\\%R NZ !Z Z !Z >Z !Z !Z \"Z :Z,^#YNZ3Y$\\,\\#\\,\\$\\,\\%\\+\\%\\,\\ MP" " NP N\\-]$Z(Z#Z(Z$Z(Z$Y'Y KZ7[ Dq :Z4X /XC[ EY " " -x @x >x ?x @x -X :Z'Z ?U MU -e 2q MtLt Ig E[ 'Z,P -Z +XCX .W?W By)" "X<W;W CZ :X X MY .ZKVKZ -X (Y <Z5Z 1Z A[ !Z 4XKZ ?Y N[ 1Z DZ3Z IZ3Y NY K\\%[ EYKZ >Z0Z" " J\\#Q'Z*\\ KZ MZ +[ Q$Z(Z :Z \"Z 4Z<] <Z 2YMY3XLY(YMZ5Z%\\*\\ LZ4[\"[*\\!Z3[ IZ :Y 9Z(Z$Z)[4Z6XLW5Z)Z<Z BZ8Z" " !\\ :X !X >Y 7[>[ %Y LY -Y 'Y 8X >Y >Y ;Y X Y ;Y" "5Y 7UH_ <Z \"Z AY3Y ;YKZ 4[ %Z ,[*\\ N~S NZ(Z+[;Z;Z+[*\\ =\\NXM[ #X $\\MXN\\ " " BU ,Z *P DY8Y 0X -Y #W NV @k )V NV <V;V +X EW NY )nEW KV /W7W BW+X KW+W CY4X +YKZ /" "YKY .ZLZ /YKY .ZKY /YKY <ZEZ 7\\#Q NZ !Z Z !Z >Z !Z !Z \"Z :Z+]#YMZ4Y%\\*\\%\\*\\&\\*[%[)[%[*\\ R!R [-_%Z(Z#Z" "(Z$Z(Z$Y'Y K[9[ Ct =Y3X /U@[ \"Q EY .z B{ " "B{ Az B{ /X :Z'Y >V U -g 4r NvNu Ji *\\ 5X.X 6\\ 7Z1Z M[ '[ 8Z +XCX /X@X C`MTL_)W;" "W<X CY 9X !Y LX ,ZMVMZ +X (X ;Z5Z 1Z A[ !Z 5XJZ ?Y NZ 0Z DY2Z J[3Z )Q Q JZ M[!Z FYJY >Z0Z " "J[ 'Z)\\ LZ MZ ,\\ \"Z(Z :Z \"Z 4Z=] ;Z 2YLX3XLY(YMZ5Z%[([ LZ3[$\\)\\\"Z3[ IZ :Y 9Z(Z$Z)Z3Z6XLX6Z(Z>[ B[:Z !" "\\ 9X !X >Y 8[<[ &Y LY -Y 'Y 8X >Y >Y ;Y X Y ;Y5Y " "7RB] =\\ $Z BY2Y ;YJY 3[ &Z -[(\\!~U Z(Z+[;Z;Z,\\)\\ ?\\MXL[ $X %\\LXM\\ CU" " ,Y *Q\"R DY9Y 0X -Y #V=_?V Cm *V LV <U;V +X FX \"[ (nEW KV /W7W BW+W JW,X F[3W *YJY 0Z" "KZ /YJY /YKZ /YJY /YJY =ZEZ 7[!P NZ !Z Z !Z >Z !Z !Z \"Z :Z*]$YMZ4Y%[([%[(['\\)\\'\\)\\'\\)[!T#T\"\\-`&Z(Z#Z(" "Z$Z(Z$Y'Y J[:Z Bw @Y6[ .Q<[ #S GY /`Da E`C" "` DaD` C`Da E`C` 0X 9Y(Z ?X !U .h 4r NvNu Kk .c 9X.X 7^ 7Y1Y M[ &Z 7Z +XCX /X@X C\\" "ITFY)W;W=X BY 9X !X KY +YNVNZ *X (X ;Z4Z 2Z @Z !Z 6YJZ ?Y Z /Z DY2Z JZ1Y ,T T MZ N[ NZ HZJ" "Y >Z0Z K[ &Z(\\ MZ MZ ,[ !Z(Z :Z \"Z 4Z>] :Z 2YLX3XLY(YLZ6Z&['\\ MZ3[$['[\"Z2Z IZ :Y 9Z(Z#Z*Z2Z7XLX7Z'[@[ @Z;" "[ ![ 8X !X >Y 9[:[ 'Y LY -Y 'Y 8X >Y >Y ;Y X Y ;Y" "5Y %\\ =] %Y BY2Z =ZJY 3\\ 'Z .\\'[#cLZLb!Z(Z+[;Z;Z,['[ @\\LXK[ %X &\\KXL\\ " " DU -Z +S$T EY:Y /X -Z %V?fBU Eo +VEg=V =V<V +X GX *b &nEW KV /W7W BW,X JW,W Nb2X +ZJY " "0YIY /YJY 0YIY /YJZ 1YIY =ZEZ 8\\ NZ !Z Z !Z >Z !Z !Z \"Z :Z)\\$YLZ5Y&\\'['['\\(['['['['['[#V%V#[-a&Z(Z#Z(Z$" "Z(Z$Y'Y IZ;Z Ay BY9^ G[ %U HY 0]<^ G^=^ F" "^<] E]<^ G^=^ 1X 9Z)Z @Z \"U .i 5r NvNu Lm 2h ;X.X 7^ 7Y1Y N[ &[ 7Z +XCX /W?X D[GTC" "V)W;W=W AZ :X \"Y KY *j (X (X <Z3Z 2Z @Z !Z 6XIZ ?Y Z 0Z DZ2Z JZ1Z 0W V Y NZ KZ IYIZ ?Z0Z " "K[ &Z(\\ MZ MZ -[ Z(Z :Z \"Z 4Z?\\ 8Z 2YKX5XKY(YLZ6Z&[&[ MZ3[%[&\\#Z2[ JZ :Y 9Z(Z#Z+Z1Z7WJW7Z&Z@Z >Z<Z ![ 7X" " X ?Y :[8[ \"\\ 3YBZ \\ ,ZAY 4\\ &Y \"Z 0YAZ \"X >Y .Y3Y 3Z '\\ MZ )Z ;Z 2^ +Y ;Y " "X Y 6Y /Y5Y $[ =` G^ !Z IZ M\\ #Y2Z =YIZ 3\\ (Z .[%[%aIZI`\"Z(Z+[;Z;Z-[%[ B\\KXJ[" " &X '\\JXK\\ H\\ 1Z ,U&V EY;Y /X ,Z 'V@jDV Gp +UDj?V >V<V +X GW )` $nEW KV /W7W " "BW-X IW-X N`0W *YIZ 1YIY 0YHY 1YIY 0ZIY 1YIZ ?ZDZ 8[ MZ !Z Z !Z >Z !Z !Z \"Z :Z(\\%YLZ5Y&[&['[&[)\\&[)[%[)" "[&[$X'X%[-b&Z(Z#Z(Z$Z(Z$Y'Y I[=[ Az CY;` 5\\ $] $\\ \"\\ #\\ $] 8\\/[ 3\\ '\\ #\\ \"[ \"[ \"[ &Z &[ ![" " #\\ #[ ![ G[@W IYBZ J]8] I\\7\\ H]8] I]8] I\\7\\ 2X 8Y*Z @Z \"U .k 5q N~o Mm 4l =X" ".X 7^ 7Z3Z NZ %Z 6Z +XCX /W?W D[FT@S)W;W>X AZ :X \"Y JX (f &X )X ;Z3Z 2Z @Z !Z 7" "XHZ ?Y !Z /Z CY1Y JZ1Z 2Y Y $Z Z HY JYHY ?Z/Y L[ %Z'\\ NZ MZ -[ Z(Z :Z \"Z 4Z@\\ 7Z 2YKX5XKY(YKZ7Z'[" "$[ NZ2Z%[%[#Z2[ JZ :Y 9Z(Z#[,Z1Z8XJW7Z%ZB[ >[>Z !\\ 7X X ?Y ;[6[ (e 7YE` (e 3aEY 8c 2r 5`DX GYEa (X NX " "0X1Z 8Y FXD`9` YD` -c 9XD` /aEX :XD] 6g 7t BX0Y LY)Y+X6Z6X)Z/Z NX)Y I} 2Y X Y 9_>W KY5Y #[ =c h >XD` " "AT#X 5Y 6X0X LY'Y ?RCW ?~Y!X?X?X ;d 'r!~W KZ1Y =YHY 2\\ )Z /[$[%_GZG_#Z(Z+[;Z;Z-[%[ C\\JXI[ 'X (\\IXJ\\ " " (Y d 5Z -W(X FY<Y .X ,[ (UAmDV Iq ,VDl@U >V=W +X HX )^ ,Y1Y HnEW KV 0X7W BW-W HW.X M^/X )" "Y +YHY 2YHZ 1YHY 2ZHY 1YHY 2ZHY ?ZDZ 9[ LZ !Z Z !Z >Z !Z !Z \"Z :Z'[%YKZ6Y'\\%[)[$[*[%[)[%[)[%[%Y)Z&[.d'Z(Z#" "Z(Z$Z(Z$Y'Y H[>Z @{ DY=b ;f -f -f ,e -f -f Ae7c ;e /b )c *c *c 'Y NX NX X E[ >XD` -c )c *b *c )c '\\ &bDX L" "X0X GX0X GX0X GX0X KY)X KYE` ?Y*Y 8[4\\ K[3[ J\\4[ I[4\\ K[3[ 3X 8Z+Z AZ !U /m 6q N~o No 6o ?X.X 8_ " "6Y3Z Z $Z 6Z +XCX 0X@X DZET>Q)W;W>W ?Y :X \"X IY 'b $X )X ;Z2Y 2Z @Z !Z 8YHZ ?Y " "!Z 0[ CY1Y JZ1Z 5\\ \\ 'Z!Z FY LZHZ @Z/Y L[ %Z&[ NZ MZ .[ NZ(Z :Z \"Z 4ZA\\ 6Z 2YKX6YKY(YKZ7Z'[$[ NZ" "2Z&[#Z#Z2[ JZ :Y 9Z(Z\"Z,Z1Z8XJX8Z%[D[ <Z?[ \"\\ 6X X ?Y <[4[ -l :YGd ,k 9eGY :h 5r 8eGY GYGe +Y NX 0X3" "\\ 8Y FYGd=c!YGe 2h ;YGd 3eGX ;YG` 9m :t BY1Y LZ+Z+Y7[7Y*[1Z MY+Z J~ 2Y X Y <eAW KY5Y \"Z <f 'o CYFd D" "Y(Y 5Y 6Y1Y MY'Z CUE\\ B~Y!Y@X@Y =h 0z\"~W KY0Y >ZHY 1\\ *Z /[#['^EZE^$Z(Z+[;Z;Z.[#Z C[IXH[ (X ([HXI[ (" "Z $k 9Z .Y*Z FY=Y .X ,\\ *UAnCU J^CW -VCmAV ?W>V *X IX (a /Y1Y HnEW KV 0X7W BW.X HW.W La3X " "(Y ,ZHY 2YGY 2ZHZ 3YGY 1YHZ 3YGY @ZCZ 9[ LZ !Z Z !Z >Z !Z !Z \"Z :Z'\\&YJY6Y'[$[)[$[*[$[+[#[+[$[&[+\\([.e'Z(" "Z#Z(Z$Z(Z$Y'Y GZ?Z ?| EY>c >l 4l 3l 2l 3l 4l Gl=h @k 5h /h /h /h )Y Y NX Y E[ ?XFd 1g .h /h /h /h )\\ )hHX " "LY0X HY0X GX0X GX0Y LZ+Y KYGd AY*Y 9[EXD[ M[1[ L[1[ K[1[ M[1[ 4X 8Z+Y A[ !T /n 6q N~o q 8q @X.X 8` 7" "Y3Y Z $Z 5Z +XCX 0X@X DYDT EW;W?X ?Y :X #Y IY %^ \"X )X <Z1Z 3Z @Z !Z 8XGZ ?Y !Z" " 0Z BY2Z JY0Z 8_ _ *Z!Y DX LYFY @Z/Y M[ $Z&[ NZ MZ .[ NZ(Z :Z \"Z 4ZB\\ 5Z 2YJX7XJY(YJZ8Z([#[ NZ2Z&[" "#[$Z2[ JZ :Y 9Z(Z\"Z-Z/Z9XJX9Z#ZDZ :Z@Z \"\\ 5X NX @Y =[1Z 1q <YIh 0o =hHY <l 7r 9hIY GYHg ,Y NX 0X4\\ " "7Y FYIg@g#YHh 6l =YIh 7hHX ;YHa ;q <t BY1Y KY+Y*Y8\\8Y([3[ MY+Y I~ 2Y X Y =gCX KY6Z !Z <i -q CYHh F[*Y" " 5Z 7Y1Y NZ&Y EWG` D~Y!Y@X@Y >k 5}\"~W KY0Z ?YGZ 1[ *Z /Z\"[(]CZD^%Z(Z+[;Z;Z.[#[ CYHXGY 'X 'YGXHY 'Z &o" " ;Z /[,[ FZ?Y -X +\\ +UBoBU LZ>W -UBnAU >W@W *X JX 'c 1Y1Y HnEW KV /W7W BW.W GW/X Lc5W 'Y ," "YFY 4ZGY 2YFY 3YGZ 3YFY 3YGZ AZCZ 9Z KZ !Z Z !Z >Z !Z !Z \"Z :Z&[&YJZ7Y'[#[*Z\"Z+[#[+[#[+[#[&[-\\'[/YM[(Z(Z#" "Z(Z$Z(Z$Y'Y G[A[ ?} FY?] :p 8q 8q 7q 8q 8p LqAl Do 9l 3l 3l 3l +Y Y NX Y #i @XHh 5k 2l 3l 3k 2l +\\ +lKX KY0" "X HY0X GX0X GX0Y KY,Z KYIh CZ,Z :ZCXC[ [/[ N[.Z MZ.[ [/[ 5X 7Y,Z AZ !U /o 7p M~n s :s AX.X 8` 7Z4Y Y" " #Z 5Z +XCX 0W?X EYCT EW;W@X >Z ;X #Y HX #Z X *X ;Z1Z 3Z @Z !Z 9XFZ ?Y \"Z /Z " "BY2Z KZ0[ <b a -[\"Y BX MYFY @Z0Z M[ $Z%[ Z MZ .Z MZ(Z :Z \"Z 4ZD] 4Z 2YJX7XJY(YJZ8Z([\"[ Z2Z&Z\"[$Z2" "[ JZ :Y 9Z(Z!Z.Z/Z9WHW9Z\"ZF[ :[BZ \"\\ 4X NX @Y >[/Z 4t =YJj 3q >kJY >o 8r ;kJY GYJk .Y NX 0X5\\ 6Y FY" "JiBi$YJk 8o ?YJj 9kJX ;YJc <r <t BY1Y KZ-Z)X8\\8Y'Z4[ LZ,Y I~ 2Y X Y ?jDX KY6Y Z ;k 1r CYIj G]-Z 5Z 7" "Y1Y NZ&Z HYHb E~Y!Y@X@Y @n 8~P\"~W KY0Z ?YFY 0[ +Z 0[!Z)]BZB]&Z(Z+[;Z;Z.Z\"[ LQ GWGXFW HQ /X /Q*Q @WFXGW &Z" " (q ;Z .[BVB[ DY@Z -X *] .UC^EXBU LX<W .VBWC[AU ?WAW )X KX %c 2Y1Y HnEW KV /W7W BW/X GW/W J" "c7X 'Y ,YFY 4YFZ 3YFY 4YEY 3YFY 4ZFY AYBZ :[ KZ !Z Z !Z >Z !Z !Z \"Z :Z&[&YIZ8Y([\"[+[\"[,[\"Z+Z!Z,[\"[%[/\\" "&Z/YL[(Z(Z#Z(Z$Z(Z$Y'Y F[BZ >Z@d GY@\\ :t ;t <u ;t ;t ;t tDn Gr <o 6o 6o 6o ,Y Y NX Y &l @XIj 8o 5o 6n 6o 5o" " -\\ ,nLW JY0X HY0X GX0X GX0Y KY,Y JYJj CY,Y :ZBXBZ!Z+Z Z,Z Z,Z!Z+Z 6X 7Z-Z BZ U 0q 7o M~n s ;u BX." "X 9a 6Y5Z!Y \"Z 5Z +XCX C~d&YCT EW;W@W =[ <X #Y HY $Z X *X ;Z1Z 3Z @Z !Z :YFZ ?" "Y \"Z 0Z AZ3Z KZ0[ 5Z \"[ ?e d 0Z\"Y AY YEZ AZ0Z MZ #Z%[ Z MZ /[ MZ(Z :Z \"Z 4ZE] 3Z 2YJY9XIY(YIZ9Z(Z![ " "Z2Z'[!Z$Z2[ JZ :Y 9Z(Z!Z/[/Z:XHW9Z\"[H[ 8ZC[ \"[ 3X NX @Y ?[-Z 5v ?YKm 6r ?mKY ?q 9r <mKY GYKm /Y NX 0X" "6[ 4Y FYKkEl%YKm ;r @YKl ;mKX ;YKd >t <t BY1Y JY-Y(Y9]9Y&Z5Z JY-Y H~ 2Y X Y @lFX JY6Y NY 9k 4s CYJl H" "^.Y 4[ 8Y1Y NY$Y J[Ie G~Y!Y@X@Y Ap ;~R\"~W KY0Z @YEZ 0[ ,Z 0Z [*\\AZA\\&Z(Z+[;Z;Z/[![ NS GUFXEU HS 0X 0S,S @U" "EXFU %Z )r ;Z -[G^G[ CZAY ,X )] /UC[>TAU NX;W )P9P =UAWAYAU >XDX )X LX HY 3Y1Y HnEW KV /W7W " "AP9P 9W0X FW0X ?Y8W &Y -YEZ 5YEY 4ZFZ 5YEY 4ZEY 5YEY BZBZ :[ KZ !Z Z !Z >Z !Z !Z \"Z :Z%['YIZ8Y([!Z+Z![,Z![-" "[![-[!Z$[1\\&[/XJZ(Z(Z#Z(Z$Z(Z$Y'Y EZCZ =Z;` HYA[ 8u <u =v <v =u <u!uGr Js =r 9r 9r 9r .Y Y NX Y (o AXJl :q " "7q 9r 9q 7q .\\ -y IY0X HY0X GX0X GX0Y KZ-Y JYKl DY-Z ;ZAXAZ\"Y)Y!Z*Z\"Z*Z\"Y)Y 6X 7Z-Y BZ NT 0s 8o" " L~m!u =w CX.X 9b 7Y5Y Y \"Z 5Z +XCX C~d&YCT EX<WAX <Z <X #X GY &^ \"X *X ;Z0Y 3Z" " @Z !Y 9XEZ ?Y \"Z 0Z AZ3Y JZ/Z 5Z \"[ Ag g 4[\"X ?X YDY AZ0Z MZ #Z%[ Z MZ /[ MZ(Z :Z \"Z 4ZF] 2Z 2YIX9" "XIY(YIZ9Z(Z Z Z2Z'[![%Z2[ JZ :Y 9Z(Z!Z/Z.Z:XHX:Z!ZHZ 6ZDZ \"\\ 3X NY AY @Z*Z 6w @YLo 9t @oLY At :r =oLY " "GYLo 0Y NX 0X7[ 3Y FYLmGn&YLo =t AYLo >oLX ;YLe ?u <t BY1Y JY-Y(Y9]9X%[7Z IZ.Y H~ 2Y X Y AnGX JY7Z N" "Z 9k 6t CYKn I^/Z 5\\ 8Y1Y Z$Z L\\Jg H~Y!Y@X@Y Br =~S\"~W LZ/Y @YDY /[ -Z 0Z NZ+\\@Z@\\'Z(Z*Z;Z;Z/[![ U GSEXDS" " HU 1X 1U.U @SDXES $Z +t ;Z ,[JbJ[ AYBY +X (^ 2UCZ9QAU NW:W *Q:Q >VAW?XAU ?ZHY (X MX EX 4Y1Y HnE" "W KV /W7W AQ:Q :W0W EW1X <X:X &Y -YDY 6ZEZ 5YDY 6ZEZ 5YDY 5YEZ CZBZ :Z JZ !Z Z !Z >Z !Z !Z \"Z :Z%['YHZ" "9Y(Z Z+Z Z-[![-[![-Z [$[3\\%[0XI[)Z(Z#Z(Z$Z(Z$Y'Y E[E[ =Z9^ HYBZ 6v =v >w =w >v =v\"vIt Lt >t ;t ;t ;t /Y Y N" "X Y *r BXKn <s :t ;t ;s :t /\\ /{ IY0X HY0X GX0X GX0Y JY.Z JYLo FZ.Y :Y@X?Y$Y'Y#YIP5PIY\"Y.PIY$Y'Y 7X 6Z/Z" " CZ NU 1u 8m K~m\"w ?^C] CX.X 9b 7Z6Y X \"Z 4Z +XCX C~d&XBT EX=XAW ;[ =X $Y GY (" "b $X +X :Y/Z 4Z @Z \"Z :XDZ ?Y \"Y 0[ @Y4Z JZ/Z 5Z \"[ Dj j 8[\"X =X\"ZDY AZ0Z N[ #Z$[!Z MZ /Z L" "Z(Z :Z \"Z 4ZG] 1Z 2YIX:YIY(YHZ:Z)[ [!Z2Z'Z [%Z2[ J[ ;Y 9Z(Z Z0Z-Z;XHX;Z NZJ[ 6[FZ \"\\ 2X MX AY AZ(Z 7x" " AYMq ;u AqMY Bv ;r >qMY GYMp 0Y NX 0X8[ 2Y FYMoIp'YMq ?v BYMp ?qMX ;YMf ?u <t BY1Y JZ/Z(Y:^:Y$[9[ HY/Z H~ 2Y " " X Y BpHX JY7Z MY ;o 9u CYLp J_0Y 4\\ 8Y1Y Y#Z M]Jh I~Y!Y@X@Y Ct ?~T\"~W LZ/Y AZDY .[ .Z 1[ NZ+[?Z?['Z" "(Z*Z;Z;Z/Z NZ!W GQDXCQ HW 2X 2W0W @QCXDQ #Z ,u ;Z +[MfM[ ?YCY +X '_ 4UDZ'U W:W +R;R >U@W?XAU >j (X " " NX CX 5Y1Y HnEW KV /W7W AR;R ;W1X EW1W :X<X %Y .ZDY 6YCY 5YDZ 7YCY 5YDZ 7ZDY DZAZ ;[ JZ !Z Z !Z >Z " "!Z !Z \"Z :Z$Z'YHZ9Y)[ [-[ [.[ Z-Z NZ-Z [#[5\\$Z0XH[)Z(Z#Z(Z$Z(Z$Y'Y D[FZ <Z7] IYBY 5w >w ?x >x ?w >w#wKv Nu ?v" " =v =v =v 0Y Y NX Y +s BXLp >u <v =v =u <v 0\\ 0{ HY0X HY0X GX0X GX0Y JZ/Y IYMp EY.Y ;Y?X?Y%Y%Y$YJR7RIY$" "Y.RJY%Y%Y 8X 6Z/Y CZ MU 2v 8m K~m#y @[>\\ DX.X :c 7Z7Z!Y \"Z 4Z +XCX C~d&XBT DW=XB" "X :[ >X $Y FY +f &X +X ;Z/Z 4Z AZ !Z ;YDZ ?YFP -Z?Q BZ ?Z5Z JZ/Z 5Z \"[ Gj Ii ;[\"X1Q,W\"YCZ BZ1" "Z MZ \"Z$[!Z MZ /Z LZ(Z :Z \"Z 4ZH] 0Z 2YHX;XHY(YHZ:Z)Z N[!Z2Z([ NZ%Z2Z I[ ;Y 9Z(Z Z1Z,Z;XGW;Z N[L[ 4[H[ #\\" " 1X MX AY BZ&Z 8^Ga AYN[H_ <cI\\ B`I[MY CaH_ <r ?`H[NY GYNr 1Y NX 0X9[ 1Y FYNqJp'YMq @aJa CYN[H_ A`I[MX " ";YNg @`E[ <t BY1Y IY/Y&X:^:Y#Z:[ GY/Y G~ 2Y X Y JW5V B`M_JX IY8Z LY =r ;cL_ CYM^Na J`1Y 5^ 9Y1Y!Z\"Z ^K" "j J~Y!Y@X@Y D_I` A~U\"~W LY.Y AYCZ .[ /Z 1Z MZ,\\?Z?\\(Z(Z*Z;Z<[/Z NZ\"Y ;X ;Y 3X 3Y2Y 3X EZ -hM[ ;Z *~Q >" "YDY *X )b 6UDY%U V9W ,S<S >U@W>W@T =h 'X X AW 5Y1Y HnEW KV /X9X AS<S <W1W DW2X 9W<W $Y .YCZ 7Y" "CY 6YBY 7YCY 6ZCY 7YCZ EZAZ ;[ JZ !Z Z !Z >Z !Z !Z \"Z :Z$Z'YGZ:Y)[ NZ-[ [.Z N[.Z NZ.[ NZ\"[7\\$[1XFZ)Z(Z#Z(" "Z$Z(Z$Y'Y CZGZ ;Z6\\ IYCY 4^Ga ?^Ga @_Hb ?^Ga ?^Ga ?^Ga$^GaMaI`!bH\\ @aI` ?aI` ?aI` ?aI` 1Y Y NX Y ,u CXM^Nb" " @aKa >aJa ?aJa ?aKa =`Ja 1\\ 0`Ic GY0X HY0X GX0X GX0Y IY0Z IYN[H_ FZ0Z <Y>X>Y&X#X%YJT9TIY&Y.TJY&X#X 8X 5Y0" "Z CZ ;P4U 1w 9l J~m#z B[;[ EX.X :d 7Y7Y X )~Q #Z +XCX C~d&XBT DW=XCX 9\\ ?X $Y FY " "-j (X +X ;Z/Z 4Z AZ \"Z :XCZ ?YM_ 5ZE^ IZ >Y6Z IZ0[ 5Z \"[ Jj Ci ?\\\"X6\\2X#YBY BZ1Z MZ \"Z$[!Z " "MZ 0[ LZ(Z :Z \"Z 4ZI] /Z 2YHX;XHY(YGZ;Z)Z N[!Z3[([ NZ%Z2Z H[ <Y 9Z(Z NZ2Z,Z<XFW;Z MZLZ 2ZHZ #\\ 0X MX AY C" "Z$Z 9Y>^ BcB] >_?W C^CYNY C]A] 4Y /]Bc GYNYD^ 2Y NX 0X;\\ 0Y FYNXC\\KYD](YNYC] A]B^ DcB] C^CYNX ;YNZDQ A\\" ";V 5Y .Y1Y IY/Y&Y;_;Y\"Z;Z FZ0Y $[ 2Y X Y M];\\ F]E[JX IY9[ LY >ZKf =]=V CYNYC] K`2Z 5^ 9Y1Y!Z\"Z!^JZM^" " K~Y!Y@X@Y E]C^ CaHl\"~W LY.Z BYBY .\\ 0Z 1Z M[-[>Z>[(Z(Z*Z;Z<[0[ N[$[ <X <[ 4X 4[4[ 4X EZ ._KUHV ;Z )~ <Y" "EY *X *e 8UDY$T!W:X .U=T ?U?W>W@U =f &X !X @W 5Y1Y HnEW KV /X9X AT=T =W2X DW2W 8W=X $Y .YBY 8ZC" "Z 7YBY 8ZCZ 7YBY 8ZBY FZ@Z ;Z IZ !Z Z !Z >Z !Z !Z \"Z :Z$[(YGZ:Y)[ NZ-Z MZ.Z N[/[ N[/[ NZ![9\\#[2YFZ)Z(Z#Z(Z" "$Z(Z$Y'Y C[I[ ;Z5\\ JYCY 4X=^ @X=] @Y=] ?Y>^ @X=^ @X=^%X=l@\\\"_?W A]@\\ @]@\\ @^A\\ @^A\\ 1Y Y NX Y -w DXNY" "C] A^C^ ?^C^ A^B] @^C^ ?^C^ 2\\ 1^C_ FY0X HY0X GX0X GX0Y IY0Y HcB] FY0Y ;X=X=Y(Y#Y'YJV;VIX&X.VJY(Y#Y 9W 4Z1" "Z DZ =S4U 2y 9j I~l#{ BZ9Z EX.X :d 7Z8Y!Y *~R #Z +XCX C~d'YBT DX?XBW 7\\ @X $Y FY " "/ZNVNZ *X ,X :Z/Z 4Z AZ #Z :XBZ ?o 9ZGc MZ =Z8[ HY0\\ 6Z \"[ Li >j C\\\"X8aGVBW$ZBZ CZ2Z LZ \"Z#Z!" "Z MZ 0[ LZ(Z :Z \"Z 4ZJ] .Z 2YHX<YHY(YFY;Z)Z MZ!Z3[([ N[&Z3[ H] >Y 9Z(Z NZ2Z,Z<XFX<Z LZN[ 2[JZ \"[ /X LX B" "Y DZ\"Z :U7\\ Ca>\\ @^:T C\\?b D\\=\\ 5Y 0\\>a Ga?\\ 2Y NX 0X<\\ /Y Fa@\\MX@[(b@\\ B]?\\ Da?] D\\?a ;b 1Z6" "S 5Y .Y1Y IZ1Z&Y;_;X![=Z DY1Y #[ 2Y X Y `>` I\\B[KX IY:\\ LY ?ZDa ?\\7R Cb?\\ F[3Y 5_ 9Y1Y\"Z Y!]IYJ] L" "~Y!Y@X@Y F\\?\\ D^Ai\"~W LY.Z CZBZ .\\ 1Z 1Z LZ.[=Z>[(Z(Z*Z;Z<[0[ N[%\\ <X <\\ 5X 5\\4\\ 5X EZ /^IUFT ;Z (" "| ;YFY )X +h :TDY#U\"W:X /V?V ?U?W>XAU <c $X \"X ?X 6Y1Y HnEW KV .W9W @U>V ?W3X CW3X 8X>W #Y /Z" "BZ 9YAY 8ZBZ 9YAY 8ZBZ 9YAY FZ@Z ;Z IZ !Z Z !Z >Z !Z !Z \"Z :Z$[(YFZ;Y)Z MZ-Z MZ/[ MZ/[ N[/Z M[![;\\\"[3YE[*" "Z(Z#Z(Z$Z(Z$Y'Y B[JZ :Z4[ JYCX 3U8\\ @U8\\ AV8\\ @U7\\ AU7[ @U8\\%U8h=\\$]9T B\\=\\ B\\=\\ B\\=\\ B\\<[ 2Y Y " "NX Y .x Da?\\ C]?] A]?] B\\?] B]?] A]?] 3\\ 2]?] FY0X HY0X GX0X GX0Y IZ1Y Ha?] GY1Z <X<X<X(X!X'XJX=XJY(X.X" "JX(X!X 9W 4Z1Y >~d W5T 2{ 9i H~k$} DZ7Z FX.X :d 7Z9Z!X )~R #Z 0~d&XBT DX?XCX 6\\ " " =Y EY 0ZMVMZ +X ,X :Z/Z 4Z B[ %\\ :XBZ ?q ;YHg Z <Z:[ GZ1\\ 6Z \"[ i M~c Nj G\\!W9eIVBX%Y@Y CZ3[ M" "[ \"Z#Z!Z MZ 0Z KZ(Z :Z \"Z 4ZK] -Z 2YGX=XGY(YFZ<Z*[ MZ!Z3[(Z M[&Z3[ H^ ?Y 9Z(Z NZ3Z*Z=XFX=Z Kf 0[L[ #\\ /X " " LX BY JS4[ C`<\\ A\\5Q D[;` E[9Z 5Y 1\\<` G`<Z 2Y NX 0X=\\ .Y F_=[MV=[)`<[ D\\<\\ E`<[ E[;_ ;` 0Z3Q 5" "Y .Y1Y HY1Y%Y<`<Y [?[ DZ2Y $[ 1Y X Y !cBc J[?YLX HY<] JX @Y?_ @[ '`<[ EZ4Z 5` :Y1Y\"Z Z#\\GYI\\ EZ:Z IY@" "X@Y FZ;[ E]>\\ 0Z 6Y.Z CYAZ -\\ 2Z 1Z LZ.[=Z=[)Z(Z*Z;Z<Z/Z LZ&\\ ;X ;\\ 6X 6\\2\\ 6X EZ /\\GUCQ ;Z 'z 9YGY" " )X -ZN_ ;TDX\"U\"W;Y 0W@W ?T>W>X@T ;a #X #X =W 6Y1Y GmEW KV .X;X @W@W @W3W BW4X 6W?X #Y /Y@Y :" "ZAY 8Y@Y 9YAZ 9Y@Y 9YAZ GZ@Z ;Z IZ !Z Z !Z >Z !Z !Z \"Z :Z#Z(YFZ;Y)Z M[/[ MZ/[ MZ/Z LZ/Z M[ [=\\!Z3YD[*Z(Z#Z" "(Z$Z(Z$Y'Y AZKZ 9Z4[ JYDY 3R3[ AR3[ BS3Z @S4[ AS4[ AR3[&R3e:[&]6R C\\:[ D\\:[ D\\:[ D\\:[ 3Y Y NX Y /_B] E_<" "[ C[;[ B\\<\\ C\\<\\ C[;\\ C\\<\\ 3\\ 3\\<\\ FY0X HY0X GX0X GX0Y HY2Z H`<[ FY2Y ;X<X<X)X NX)YKZ?ZJX(X/ZKX)X" " NX ;X 3Y2Z >~d#Z6U 3} :h G~k%~P EY5Y FX.X ;ZNY 6Y9Z!X *~R \"Z 0~d&YCT CXAXBW 5] " " >Y EY 2ZKVKZ -X ,X :Z/Z 4Z BZ &] :XAZ ?s =YJk #[ ;[=[ FZ1\\ 6Z \"[ #j L~d Ki J\\!X:hKVAW%Y@Y CZ5\\ L" "[ \"Z#Z!Z MZ 0Z KZ(Z :Z \"Z 4ZL] ,Z 2YGX=XGY(YEZ=Z*[ M[\"Z4['Z LZ&Z4[ F` BY 9Z(Z MZ4Z*Z=XEW=Z Jd .ZLZ #\\ .X" " LX BY JQ1[ D_:[ B\\ ([9_ F[7Z 6Y 1[:_ G^9Z 3Y NX 0X>\\ -Y F^;b;Z)_:Z D[:\\ F_:[ G[9^ ;_ /Y EY .Y1Y " "HY2Z$Y=a=Y NZ@[ BY3Z %[ 0Y X Y \"eCd L[>YLX HY>^ IY AY=] @Z &_:Z DY4Y 5a :Y1Y\"Z Z$\\GYG\\ EY9Y IY@X@Y G" "Z9[ G\\;[ 0Y 5Y.Z DZ@Y ,\\ 3Z 1Z LZ.Z<Z=[)Z(Z*Z;Z<Z/Z LZ'\\ :X :\\ 7X 7\\0\\ 7X EZ 0\\FU -Z &x 8YHY (X -YK" "_ >UDX!T\"X<Y 1XAX ?T>W>X@U :] !X $X <W 6Y1Y GmEW KV .Y=X ?XAX AW4X BW4W 5W@X \"Y 0Z@Y :Y@Z 9Y@" "Y :Z@Y 9Y@Z ;Z@Y HZ?Z <[ IZ !Z Z !Z >Z !Z !Z \"Z :Z#Z(YEZ<Y*[ M[/[ M[0Z LZ/Z LZ/Z M[ N[?\\ Z3XBZ*Z(Z#Z(Z$Z(Z" "$Y'Y @ZM[ 9Z3[ KYDY 3P0Z AP0Z BQ0Z AQ0Z BP0Z AP0Z&P0b7Z'\\2P CZ7Z DZ7Z DZ7Z DZ7Z 3Y Y NX Y 0]<Z E^:Z D[9[ C[" ":\\ E\\:[ D[9[ C[:\\ 4\\ 3[9[ GY0X HY0X GX0X GX0Y HZ3Y G_:[ GY2Y <X;X;X*X NX)XJ[A\\JX*X/[JX*X NX ;X 3Z3Z " " >~d&^7U 4~ 9f E~i%~R GY4Y FX.X ;ZNZ 7Y9Y!X )~R \"Z NW?W BYCT CYBXCX 6_ ?Y EZ 5ZI" "VIZ /X ,X :Z.Y 4Z C[ )_ :YAZ ?t >YKn %Z 9\\A\\ EZ1\\ 6Z \"[ &j I~d Hi N\\ W:jLVAW&Z@Z DZ8^ KZ !Z#[\"Z " " MZ 0Z KZ(Z :Z \"Z 4ZM] +Z 2YGY?XFY(YEZ=Z*Z L[\"Z4['Z LZ&Z4[ Fc EY 9Z(Z MZ5Z)Z>XDW=Z Ic .[NZ #\\ -X KX CY " " )Z D^8[ D\\ '[8^ FZ5Z 7Y 2[8^ G]8Z 3Y NX 0X?[ +Y F]9`9Y)^9Z E[8[ F^8Z GZ8^ ;^ .Y EY .Y1Y GY3Y#Y=WNX=Y M" "ZAZ AY3Y %[ /Y X Y #gEf N[<YMX HYBb IY BY;] BZ %^8Z DY5Y 5b ;Y1Y#Z NZ$[FYF[ EY9Y IY@X@Y HZ8[ H\\9[ 1Y 5Y" ".Z DZ@Z ,\\ 4Z 2[ LZ.Z<Z<Z)Z(Z*[<Z<Z/Z LZ(\\ 9X 9\\ 8X 8\\.\\ 8X EZ 1\\EU -Z %^E] EhIg 6X .YI_ ?UEX T!W=" "Z 2YBY @U>W>W?U 7W <~d BX ;W 6Y1Y GmEW KV -X=X ?YBY BW4W AW5X 5W@W !Y 0Y?Z ;Y?Y :Z@Z ;Y?Y :Z?Y ;Y" "?Y HZ?Z <[ IZ !Z Z !Z >Z !Z !Z \"Z :Z#Z(YEZ<Y*[ LZ/[ M[0Z LZ/Z LZ0[ LZ M[A\\ NZ4XAZ*Z(Z#Z(Z$Z(Z$Y'Y @[NZ 8Z3" "[ KYDY AZ !Y Y Z !Z !Z 5`5Z([ %Z5Z FZ5Z FZ5Z FZ5Z 4Y Y NX Y 1\\:[ F]8Z F[7[ E[8[ E[8[ E[8[ E[8[ 4\\ 4[9\\" " GY0X HY0X GX0X GX0Y GY4Z G^8Z GZ4Z <X;X:W+X LX*WH[C\\IX*X0[HW+X LX <X 2Y4Z =~d(`7T 4~Q 9e E~i%~R GY3" "Y GX.X ;YMZ 7Z;Z!X *~R !Z X@X BZDT BXCYDX 6` ?Y DY 7[HVH[ 1X -X 9Z.Y 4Z D[ 7" "m 9X@Z ?v AZLp &Z 8^H_ DZ1\\ 6Z \"[ (i F~d Ei #\\ NW;lMV@W'Y>Y D~P JZ !Z#[\"~Q Dy Z K~] :Z \"Z 4ZN] *Z 2YFX?XF" "Y(YDZ>Z*Z L[\"Z5\\([ LZ&Z5\\ Eg JY 9Z(Z MZ5Z)Z>XDX>Z Ib ,f $\\ ,X KX CY (Y D]6Z D[ '[7^ GZ4Z 7Y 2Z6] " "G]7Z 4Y NX 0X@[ *Y F]8^8Z*]7Z FZ6[ G]6Z I[7] ;] -X DY .Y1Y GY3Y#Y=WNX=X L[CZ ?Y4Y &[ .X NX Y $iGh Z:XNX" " GYHg HY CY8\\ CY $]7Z DY6Y 4b ;Y1Y#Z MZ&[EYE[ FY9Y IY@X@Y HZ7[ I[7[ 2Y 5~V DY>Y +\\ 5Z 2Z KZ/[<Z<[*Z(Z)Z<Z<Z/" "ZIuIZ)\\ 8X 8\\ 9X 9\\,\\ 9X EZ 1[DU -Z $Z@[ EhJh 6X /YF_ ATDX U\"X?[ 3ZCZ @U>W>W?U K~d CX ;X " " 6Y1Y FlEW KV -Y?Y ?ZCZ CW5X AW5W 5XAX !Y 0Y>Y <Z?Z ;Y>Y <Z?Z ;Y>Y ;Y?Z JZ>~Q3[ I~Q G~Q F~Q G~Q 5Z !Z !Z " "\"Z :Z#Z(YDZ=Y*[ LZ/Z L[0Z L[0Z LZ0[ LZ L[C\\ N[5X@Z*Z(Z#Z(Z$Z(Z$Y'Y ?e 7Z3[ KYDY @Y Y !Z Y Y Y 4_4Y)[ %Z3" "Y GZ3Y FZ4Y FZ4Y 4Y Y NX Y 1[8Z F\\7Z F[7[ EZ6[ G[6[ G[6Z EZ6[ <Z9^ HY0X HY0X GX0X GX0Y GY4Y F]6Z GY4Y " " ;W:X:X,X LX+XG[E\\GW*W0[GX,X LX <X 2Z5Z =~d(`8U 4~R 9c D~h%~T HX2Y GX.X <ZLY 6Y;Z!X *~" "R !Z X@X BZDT BZGZCW 6b @Y DY 8ZFVFZ 2X -X 9Z.Y 4Z DZ 7l 8X?Z ?w BZMr ([ 7s C[3] 6Z \"[ +i C~d" " Cj '\\ NW;nNV@W(Z>Y D~ IZ !Z#[\"~Q Dy![ K~] :Z \"Z 4h )Z 2YFX@YFY(YDZ>Z*Z KZ\"Z5\\([ LZ&Z6\\ Ck Y 9Z(Z LZ6Z(" "Z?XDX?Z G` *d #[ +X KX CY 'Y E]6[ F[ &Z5] GY2Y 7Y 3Z4\\ G\\6Z 4Y NX 0XA[ )Y F\\7]6Y*\\5Y G[5Z G\\5Z I" "Z5\\ ;] -X DY .Y1Y GZ5Z#Y>XMW>Y K[E[ ?Y5Y &[ .Y NX Y $XIZHZIY!Z:XNX GYHf GY DY6[ CY $\\5Y CX6Y 5c ;Y1Y#" "Z MZ&[EYDZ FY9Y IY@X@Y IZ5Z IZ5Z 2Y 5~V EZ>Y *[ 5Z 2Z KZ/[<Z<[*Z(Z)Z<Z=[0[IuIZ*\\ 7X 7\\ :X :\\*\\ :X L[" "CU -Z %Z>Z EiKh 6X /XC^ BTDX U\"YA\\ 4ZCZ N~d &U>W?X>T K~d EY :W 5Y1Y EkEW KV ,YAY =ZCZ DW6X @W6" "X 5W@W 'Z>Y <Y=Y <Z>Z =Y=Y ;Y>Z =Z>Y JZ>~Q3Z H~Q G~Q F~Q G~Q 5Z !Z !Z \"Z :Z#[)YDZ=Y*[ LZ/Z KZ0Z L[1[ LZ0[ L" "Z K[E\\ M[6Y@Z*Z(Z#Z(Z$Z(Z$Y'Y >d 7Z2Z KYDY @Y Y Y NY Y !Y 4^3Z*Z $Z3Z HZ3Z HZ3Z HZ2Y 5Y Y NX Y 2[6Z G" "\\6Y FZ5[ G[5Z GZ5[ GZ5[ G[5Z =[:_ HY0X HY0X GX0X GX0Y GZ5Y F\\5Z GY5Z <X:X:X,W JW+XF[G\\FX,X1[FX,W JW <X " "2Z5Y <~d'UNY9U 5~T H[LaM[!~g&~V JY1X GX.X <ZLZ 7Y;Y X Z 3Z W?X AZET A\\M\\CX 7d " " BZ DY 8XDVDX 2X -X 9Z.Y 4Z E[ 7j 7Y?Z ?x CZNt )Z 5p @Z3] 6Z \"[ .i @~d @i *\\ MW<^Ib@W(Y=Z E| GZ !Z" "\"Z\"~Q Dy![ K~] :Z \"Z 4f 'Z 2YEXAXEY(YCZ?Z*Z KZ\"Z6\\'[ LZ&Z8] An $Y 9Z(Z LZ7Z'Z?XDX?Z F_ *c #\\ +X JX DY " " 'Y E\\4Z FZ %Z4\\ HZ1Y 8Y 3Z4\\ G[4Y 4Y NX 0XC\\ (Y F[6]6Y*[4Y GZ4[ H\\4Z JY4\\ ;\\ ,X DY .Y1Y FY5Y!Y?" "XMX?Y JZF[ >Z6Y &[ .Y NX Y %WEYJYEX#Z8a GYHe FY DX4[ DY $\\5Y CY8Z 5d <Y1Y$Z LZ'[DYD[ GY9Y IY@X@Y IY4Z J" "[5[ 3Y 6~W EY=Z *[ 6Z 2Z KZ/Z;Z<[*Z(Z)Z<Z=Z/[IuI[,\\ 6X 6\\ ;X ;\\(\\ ;X LZBU -Z %Y<Z FjMi 6X 0X@] CTD" "W NU!ZE^ 5ZCZ M~d &T=W@X=T K~d FY :X 5Y1Y EkEW 3Z CV +ZEZ ;ZCZ EW6W ?W7XA]\"XAX 'Y=Z =Y=Y <Y<Y =Y=" "Y <Z=Y =Y=Z KY=~Q3Z H~Q G~Q F~Q G~Q 5Z !Z !Z \"Z Ew5[)YCZ>Y*Z KZ/Z KZ0Z L[1[ L[1[ LZ J[G\\ L[7Y?Z*Z(Z#Z(Z$Z(Z$" "Y'Y >c 6Z2Z KYDY ?Y X NX NY Y Y 4\\1Y+[ %Z1Y HY1Y HY1Y HY1Y 5Y Y NX Y 3[5Z G[5Z HZ3Z GZ4[ HZ4Z HZ3Z GZ" "4[ >Z9` IY0X HY0X GX0X GX0Y FY6Z F\\4Z GY6Y ;W9X9W-X JX,WD[I\\DW,W1[DW-X JX =X 1Y6Z <~d'RKY:U 5~U J" "~T$~g'~X KY1X GX.X <YKZ 7Z<Y W NZ 3Y NW?W @\\GT @jCW 7f CZ DY 7VCVCV 1X .X " "8Z.Y 4Z F[ 6h 5X>Z ?y DgF` *Z 2k >Z4^ 6Z \"[ 1j >~d =i -[ LW=\\C_?W)Y<Y Ez EZ !Z\"Z\"~Q Dy![ K~] :Z \"Z 4e &Z" " 2YEXAXEY(YCZ?Z*Z KZ\"Z8^'[ L['Z:_ @p 'Y 9Z(Z KZ8Z'Z@XBW?Z F^ (b $\\ *X JX DY &X E[2Y FZ &Z3\\ HY0Y 8Y" " 3Y2[ G[4Y 4Y NX 0XD\\ 'Y F[5[5Y*[4Y HZ2Z H[3Z KZ3[ ;[ ,Y DY .Y1Y FY5Y!Y?WLX?Y J[GZ <Y7Z '[ -Y NX Z 'WC" "YKXBV#Z8` FYHc +YCY EY4[ DY $[4Z CX8Y 5e <Y1Y$Z KZ([DYCZ GY9Y IY@X@Y IY3Z KZ3Z 3Y 6~W EY<Y )[ 7Z 2Z KZ/Z;Z;Z*Z(" "Z)[=Z=Z/[IuI[-\\ 5X 5\\ <X <\\&\\ <X LZBU -Z &Y:Y FjNj 6X 0X?] EUEX NU!s 6ZCZ L~d &T=WAY=T K~d GX" " 9Y 5Y1Y DjEW 3Z CV *]M] 9ZCZ FW7X5X3W7WCc%XBX5Y JY<Y >Z=Z =Y<Y >Z=Z =Y<Y >Z=Z LZ=~Q3Z H~Q G~Q F~Q G~Q" " 5Z !Z !Z \"Z Ew5[)YCZ>Y*Z KZ/Z KZ0Z KZ1[ L[1Z KZ I[I\\ K[8Y>[+Z(Z#Z(Z$Z(Z$Y'Y =a 5Z2Z KYDY ?Y Y X MX Y Y" " 4\\1Y+Z $Y0Y IZ1Y IZ1Y IZ0X 5Y Y NX Y 3Z3Y GZ3Y HZ3Z HZ2Z IZ2Z IZ3Z GZ3Z >Z:a IY0X HY0X GX0X GX0Y FZ7Y E[" "3Z GY6Y ;W9X9W-W HW,WC[K\\CW,W2[CW-W HW =X 1Z7Z <~d NX:U 5~V M~X%~e&~Y LX0Y HX.X =ZJY 6Y=Z W " " NZ 3Y X@X ?]IT ?hCW 7h2X ;Y CY 7TAVAT 1X .X 8Z.Y 4Z G\\ 6g 5X=Z ?X?a EeB^ +Z /f ;[5" "^ 4i ;~d :i 1[ LW<Z?]?W*Z<Z Fx CZ !Z\"Z\"~Q Dy![ K~] :Z \"Z 4e &Z 2YEXBYEY(YBZ@Z*Z KZ\"Z9^&[ L['[Ad >r *Y " "9Z(Z KZ8Z'Z@XBX@Y D\\ &` $\\ )X JX DY &X E[2Z HZ %Z3\\ IZ/X 8Y 4Z2[ GZ3Y 4Y NX 0XE\\ &Y FZ4[5Y*[4Z IZ" "2Z H[2Y KY2[ ;[ +X DY .Y1Y FZ7Z!Y?WLX?X H[IZ ;Y7Y '[ ,Y NX NY *Q NV@WLW?U#Z8` FYHd .^FY EX2[ DX $[3Y CX8Y" " 5YMY <Y1Y$Z KZ(ZCYCZ GY9Y IY@X@Y JY2Z L[3Z 3Y 6~W FZ<Z )[ 8Z 2Z KZ/Z;Z;Z*Z(Z)[=Z>[/[IuI[.\\ 4X 4\\ =X =\\$\\" " =X MZAU -Z &X8Y G~W 6X 0W<\\ FUEX MT iNW 8[D[ K~d &T=WE\\<T K~d HX NQ<Y 4Y1Y CiEW 3Z CV )k 7" "ZC[ HW7W5Y3W8XFh>Q<YAW5Z KZ<Z ?Y;Y >Z<Z ?Y;Y >Z<Z ?Z<Y LZ=~Q3Z H~Q G~Q F~Q G~Q 5Z !Z !Z \"Z Ew5[)YBZ?Y*Z KZ/" "Z KZ0Z KZ1[ L[1Z KZ H[K\\ J[8X=[+Z(Z#Z(Z$Z(Z$Y'Y <` 5Z2Z KYDZ ?X Y Y NX NX NX 4[/Y,Z $Y/Y JY/Y JY/Y JY/Y " "6Y Y NX Y 3Z3Z HZ3Y IZ1Z IZ2Z IZ2Z JZ1Z IZ2Z ?Z:b IY0X HY0X GX0X GX0Y EY8Z E[2Y GZ8Z ;W9X9X.W HW-XB[M" "\\BW,W3[BX.W HW =X 0Y8Z ;~d NY;U 6~X!~[%~c&~Z LX0Y HX.X =ZJZ 7Y=Y N~l 4Z 3Y X@X ?`L" "T >eBX<U\"[M\\4Y ;Y CZ 7Q?V?Q 0X .X 8Y-Z 5Z H\\ 5j 9Y=Z ?T9_ Ec>] ,Z 1j <[7_ 7i 8~d 7i 5[ KW=Z=" "\\?W*Y:Y F{ FZ !Z\"Z\"~Q Dy![1j&~] :Z \"Z 4e &Z 2YDXCXDY(YBZ@Z*Z KZ\"Z<a&Z K['} <s ,Y 9Z(Z KZ9Z%ZAXBXAZ E] &_ $" "\\ (X JY EY &Y F[2Z HZ %Y1[ IY.Y 9Y 4Z1Z GZ3Z 5Y NX 0XF\\ %Y FZ4Z3Y+Z2Y IZ1Z I[2Z LY1Z ;[ +X DY .Y1Y " "EY7Y NX@XKW@Y G[K[ :Y8Y ([ ,Z NX NY /[(R NU?XNW=U%Z7_ EYHg 3bHY FY1Z DX $Z2Y CY:Y 5ZMZ =Y1Y$Z KZ)[CYBY GY9Y" " IY@X@Y JY1Y LZ1Z 4Y 6~W FY;Z *[ 7Z 2Z KZ/Z;Z;Z*Z(Z(Z=Z>[/[IuI[/\\ 3X 3\\ >X >\\\"\\ >X MZAU -Z 'X6X 5c " "%X 1X;\\ GUEX MT NgMW 9[D[ J~d &T=m;T K~d In 4TA[ 4Y1Y BhEW 3Z DX )i 5[D[ IX9W5Z3W8WFj?TA[BX5Z KY" ";Z @Z;Z ?Y:Y @Z;Z ?Z;Y ?Y;Z NZ<~Q3Z H~Q G~Q F~Q G~Q 5Z !Z !Z \"Z Ew5[)YAY?Y*Z KZ/Z KZ1[ KZ1[ L[1Z KZ G[M\\ IZ8" "X<[+Z(Z#Z(Z$Z(Z$Y'Y <_ 4Z2Z KYD[ @X NX Y NY X NX 3Z/Y-Z $Z/Y KZ/Y KZ/Y KZ/Y 6Y Y NX Y 4Z2Z HZ3Y IZ1Z I" "Z1Z JY1Z JZ1Z IZ1Z @Z;XNZ JY0X HY0X GX0X GX0Y EY8Y D[2Z GY8Y ;X9X8W.W HW-W@hAW-X4[@W.W:[:W =X 0Z9Z I" "[ 7Y<U 6~Y\"~^'~c'~\\ MX/X HX.X =YIZ 7Z>Y ~m 4Z 3Y W?X >g =cAW?]'[K\\5Y ;Y CZ %V M" "X /X 7Y-Z 5Z H[ 4l ;X<Z ?Q4^ Fb<] .[ 3o ?[7_ :i 5j 9[ JW=Y;[?W+Z:Y F~ IZ !Z\"Z\"~Q Dy![2l'~] :Z " "\"Z 4f 'Z 2YDXCXDY(YAZAZ*Z KZ\"~%Z K['| 9s .Y 9Z(Z JZ:Z%ZAXBXAZ E] %] #[ 'X IX EY &Y FZ0Y HY %Z1[ IY.Y" " 9Y 4Y0Z GZ2Y 5Y NX 0XG[ #Y FZ4Z3Y+Z2Y JZ0Z IZ0Y MZ1Z ;Z *Y EY .Y1Y EY8Z NYAXKXAY FZL[ 9Y9Y ([ +Y MX NZ 4b," "S U=`=U%Z6^ EYHi 6dIY FY1Z DY %Z2Y BX:Y 5ZLY =Y1Y%[ KZ)ZBYBZ HY9Y IY@X@Y JY1Z MZ1Z 4Y 6~W GZ:Y +\\ 7Z 2Z KZ/Z" ";Z;Z*Z(Z([>Z>Z.[IuI[0\\ 2X 2\\ ?X ?\\ \\ ?X MY@U 8y ;X6X 4a $X 1X9[ HUEX MT MeLW :[D[ I~d &T=l:T " "K~d Io 5m 3Y1Y AgEW 3Z Nl 2g 3[D[%lDX5Z>mDXFk@mAW5[ LZ:Y @Y:Z ?Y:Y @Z:Y ?Y:Z AZ:Y NZ<~Q3Z H~Q G~Q F~Q G" "~Q 5Z !Z !Z \"Z Ew5[)YAZ@Y*Z KZ/Z KZ1[ KZ1[ L[1Z K[ Gh HZ9X;[+Z(Z#Z(Z$Z(Z$Y'Y ;] 3Z2Z KYC[ AX NX Y NY Y X" " 3Y.Y-Z $Y.Y KY.Y KY.Y KY.Y 6Y Y NX Y 4Z1Y HY2Y IZ1Z IY0Z KZ0Z KZ1Z IY0Z @Y;XMZ JY0X HY0X GX0X GX0Y DY9Y D" "Z0Y GY9Z ;W8X8W.W HW-W?f?W.W4[?W.W:[:W =X 0Z9Y HZ 5X<U 6~Z$~`'~a&~\\ NY/X HX.X =YHY 7Z?Z ~m " " 4Z 3Y W?W <i >_@XAa*[I\\6Y ;Y CZ %V MX /X 7Y-Z 5Z I[ 3n >X;Z ] G`9\\ .Z 4s @[9` " " =i /i ;Z IV=Y9Z>V+Z:Z G~P JZ !Z\"Z\"~Q Dy!Z1l'~] :Z \"Z 4g (Z 2YDYEXCY(YAZAZ*Z KZ\"}$Z K['z 5r /Y 9Z(Z JZ;Z" "$ZAW@WAZ F_ %\\ $[ &X IX EY &Y FZ0Y IZ %Y/Z IY.Y 9Y 4Y0Z GY1Y 5Y NX 0XH[ \"Y FY3Z3Y+Z2Y JZ0Z IZ0Y MY0" "Z ;Z *Z FY .Y1Y DY9Y MYAWJXAY F[MZ 8Z:Y )[ +Z MX N[ 7g1U U<^;U&Z6^ EYHj 9gJY FX/Y CY &Z2Y BY<Z 6ZKZ >Y1Y%Z" " J[*ZBYBZ HY9Y IY@X@Y KY0Z MY/Y 4Y 6~W GZ:Z ,[ 6Z 2Z KZ/Z;Z;Z*Z(Z([>Z?[.ZHuI[1\\ 1X 1\\ @X @\\ M\\ @X NZ" "@U 8y ;W4X 5` #X 1X8Z HUEX MT LbJW ;ZC[ H~d &T=j8U L~d Io 5l 2Y1Y @fEW 3Z Nl 0c 0[CZ&lDW5[>mEXE\\N^" "AlAX6\\ LZ:Z AY9Y @Z:Z AY9Y @Z:Z AY9Z!Z;~Q3Z H~Q G~Q F~Q G~Q 5Z !Z !Z \"Z Ew5[)Y@ZAY*Z KZ/Z KZ1[ KZ1[ L[1Z K" "[ Ff GZ:X:[+Z(Z#Z(Z$Z(Z$Y'Y :\\ 3Z2Z KYC\\ BY X NX NY Y X 3Y-X-Y #Y-X KY-X KY-X KY-X 6Y Y NX Y 5Z0Y HY" "2Y IY/Y JZ0Z KZ0Z KY/Z KZ/Y AZ;WKY JY0X HY0X GX0X GX0Y DY:Z DZ0Y FY:Y :WK~KW.WK}KW-W>d>W.W5[>W.W:[:W =X /" "Y:Z IZ 4Y=T 6~[%~b'~_%~\\ NY/X HX.X >ZHY 6Y?Y N~m 4Z 3Y !X@X ;l @[>WBe,ZG\\7Y ;Y" " CZ %V ;~c LX 7Y-Z 5Z J\\ 2n @Y;Z N\\ G`8\\ /Z 5u A\\<b ?i *i ?Z IW=X8Z>V+Y8Y G~R LZ !Z\"Z\"~Q" " Dy![2l'~] :Z \"Z 4h )Z 2YCXEXCY(Y@ZBZ*Z KZ\"|#Z K['x 0q 1Y 9Z(Z IZ<Z$ZBX@XBY F` %[ $\\ &X IX EY &Y FZ" "0Z JZ %Y/Z JY,X 9Y 5Z0Z GY1Y 5Y NX 0XI[ !Y FY3Z3Y+Y1Y JZ/Y IZ0Y MY/Y ;Z *[ GY .Y1Y DY9Y MYBXIWBY Dg 7Y;Z *[ +" "[ MX M[ :l6W T:\\:U&Y5] DYHk :hKY GY/Z DZ 'Z2Y BY<Y 5ZKZ >Y1Y%Z IZ*YAYBZ HY9Y IY@X@Y KY/Y MY/Y 4Y 6~W GY9Z " "-[ 5Z 2[ LZ/Z;Z;Z*Z(Z'[?Z?[.[IuI[2~n BX B~n AX A~m AX NZ@U 8y <X4X 4_ #X 1X7Z IUEX MT J^HW <ZCZ F~d &T=" "g5T -X ,o 5k 1Y1Y >dEW 3Z Nl ._ ,ZCZ'lEX6\\>mEWDVCZBkAX6] LY8Y BZ9Z AY8Y BZ9Z AY8Y BZ9Z!Z;~Q3Z H~Q " "G~Q F~Q G~Q 5Z !Z !Z \"Z Ew5[)Y@ZAY*Z KZ/Z KZ1[ KZ1[ L[1Z KZ Ee FZ;Y:[+Z(Z#Z(Z$Z(Z$Y'Y :[ 2Z2Z KYB\\ CY X NX" " NY Y Y 4Y-Y.Y #Y-X KY-X KY-Y LY-Y 7Y Y NX Y 5Z0Z IY2Y JZ/Z KZ/Y KY/Z KY/Z KZ/Y#~d$Z<WJY JY0X HY0X GX0X G" "X0Y DZ;Y CZ0Y FY:Y :WK~KW/WJ}JW.W=b=W.W6[=W/W9[9W >X /Z;Z JZ 2X>U 6~\\'~c&~^$~Z MY/X HX.X >YGZ 7Z@Y " "N~m 4Z 3Y !X@X :n 'WBg.ZE\\8X :Y CZ %V <~e NX 6Y-Y 4Z K\\ #a AX:Z M\\ H_6[ 0Z" " 6aI` A]?c ?f $f ?Z IW>Y7Y>V,Z8Z HZ8` MZ !Z\"Z\"Z MZ 1[2l'Z(Z :Z \"Z 4ZN] *Z 2YCXFYCY(Y@ZBZ*Z KZ\"{\"Z " "K['v +o 2Y 9Z(Z IZ<Z#YBX@XCZ Fa %Z %\\ %X HX FY 6i FZ0Z JZ %Y/Z JY,X 9Y 5Z/Y GY1Y 5Y NX 0XK\\ Y FY3Z" "3Y+Y1Y JY.Y IY/Z NY/Y ;Z *\\ HY .Y1Y DZ;Z LXBXIWBY Ce 6Y;Y )[ -\\ LX L\\ >q:X !U:[9U&Y5] DY?d =jLX FY/Z C[ " ")Y1Y AX=Z 6ZIY >Y1Y%Z IZ*YAYAY HY9Y IY@X@Y KY/Y NZ/Z 5Y 5Y-Y HZ8Y .[ 4Z 1Z LZ/Z;Z;Z*Z(Z'[?Z@[-[ L[3~o BX B~o BX" " B~o BX NZ@U 8y <X4X 4^ \"X 1X6Y IUEX MT GW *ZCZ E~d &T=g5T -X ,o 5i /Y1Y <bEW 3Z Nl *W 'ZCZ(l", "EW6]>mFXDS?YBi?W5] CY 4Z8Y BY7Y BZ8Z CY7Y AY8Z CZ8Y!Y:Z <Z HZ !Z Z !Z >Z !Z !Z \"Z Ew5[)Y?ZBY*Z KZ/Z KZ1[ KZ" "1[ L[1Z KZ Dc E[=Y9[+Z(Z#Z(Z$Z(Z$Y'Y 9Z 2Z2Z KYB^ &i 0i 1i /i 0i 0i Ej-Y/Z $Z-Y MZ-Y MZ-Y LY-Y 7Y Y NX Y 5Y/" "Z IY1X JZ/Z KZ/Z LY.Y LZ/Z KZ/Z$~d$Z=WIZ KY0X HY0X GX0X GX0Y CY<Z CY/Z GZ<Z :WK~KW/WJ}JW.W<`<W.W7[<W/W9[9W " ">X .Y;Y JZ 1Y?U 6~\\(~e'~]\"~X LX.X HX.X >YFY 7ZAZ N~m 4Z 3Y !W?X 9p +XCi0ZC\\9X " " :Y CZ %V <~e NX 6Z.Y 4Z L\\ M^ CY:Z L[ H^4Z 0Z 7^A^ C_Ce ?c Mc @Z HW>X6Y>V,Y7Z HZ5^ NZ !Z\"" "Z\"Z MZ 1[2l'Z(Z :Z \"Z 4ZM] +Z 2YBXGXBY(Y?ZCZ*Z KZ\"z![ LZ&w 'k 3Y 9Z(Z IZ=Z\"ZCX@XCZ Gc &Z &\\ $X HX FY " " >q FY.Y JY $Y/Z JY,X 9Y 5Y.Y GY1Y 5Y NX 0XL\\ NY FY3Z3Y+Y1Y JY.Z JY/Z NY/Y ;Y (^ KY .Y1Y CY;Y KYCXIXCY " "Bc 4Y<Y *[ 2a KX La Du?Z !U9Z8T'Z5] DY9^ >\\IYMX FY/Z B\\ +Y1Y AY>Y 5ZIZ ?Y1Y%Z IZ*YAYAY HY9Y IY@X@Y KY/Y NZ" "/Z 5Y 5Y-Y HZ8Z 0\\ 4Z 1Z LZ/Z;Z;Z*Z(Z&[@Z@[-[ L[4~p BX B~o BX B~p CX NY?U 8y <W2W 3] \"X 1Y7Y IUEX MT " " JZCZ 8X &T=WIZ6T -X ,o 3e -Y1Y :`EW 3Z Nl (ZCZ)lFW5UNV>mFWCQ;XAe>X6UNW CY 4Y7Z DZ7Y BZ8Z CY7Z CZ7" "Y CY7Z#Z:Z <Z HZ !Z Z !Z >Z !Z !Z \"Z :Z#[)Y?ZBY*Z KZ/Z KZ0Z KZ1[ L[1Z KZ Ca D[>Y8[+Z(Z#Z(Z$Z(Z$Y'Y 9Z 2Z3[ " "KYA^ /q 9r 9q 7q 8q 9r Mq,Y/Z $Y,Y MY,Y MY,Y MZ-Y 7Y Y NX Y 5Y.Y IY1X JZ/Z KY.Z LY.Y LZ/Z KY.Z$~d$Y=XIZ KY0X" " HY0X GX0X GX0Y CY<Y BY/Z FY<Y 9WK~KW/WJ}JW.W;^;W.W8[;W/W9[9W >X .Y<Z K[ 1Y@U 6~](~f'~[ ~V KX.Y IX.X" " ?ZFY 6YAZ N~m 4Z 3Y !W?W 6p -WCk1ZB\\;Y :Y CZ %V <~e NX 6Z.Y 4Z M\\ J] EY9Z " " L[ H^4[ 2[ 8\\<\\ BbKi ?` Ha @Z HV=X5X>W-Y6Y HZ2\\ Z !Z\"Z\"Z MZ 1[2l'Z(Z :Z \"Z 4ZL] ,Z 2YBXGXBY(Y?Z" "CZ*Z KZ\"x N[ LZ&x #f 3Y 9Z(Z HZ>Z\"ZCW>WCZ Hd &Z &[ #X HX FY At FY.Y JY $Y/Z JY,Y :Y 5Y.Y GY1Y 5Y NX" " 0XM\\ MY FY3Y2Y+Y1Y JY.Z JY.Y Z/Y ;Y (b Y .Y1Y CY;Y KYCWHXCY Bb 3Y=Y *[ 6e JX Ke KzF^ !U9Y7T'Z4[ CY7] @[E" "XNX GZ.Y Ai 9Y1Y AY>Y 5YHZ ?Y1Y&[ IZ+ZAYAY HY9Y IY@X@Y KY/Y NZ.Y 5Y 5Y-Y IZ6Y 0[ 3Z 1Z LZ/Z;Z;Z*Z(Z&\\AZA[,[ L[" "4~p BX B~o BX C~q CX NY?U 8y <W2W 3\\ )Y6Y JUEX NU KZCZ 7X &T=WGY7T -X J^ *Y1Y 7]EW 3Z " " 8ZCZ 4X6UMV GX-X=^;W6UMW CY 4Y6Y DZ7Z CY6Y DZ7Z CY6Y DZ7Z#Z:Z <Z HZ !Z Z !Z >Z !Z !Z \"Z :Z#[)Y>ZCY*Z K" "Z/Z KZ0Z L[1[ L[1Z KZ B_ C[>X7[+Z(Z#Z(Z$Z(Z$Y'Y 9Z 2Z3[ KY@_ 5u <u <t :t <u <u!t,Y/Y #Y,Y MY,Y MY,Y MY,Y 7Y Y " " NX Y 6Z.Y IX0X JY-Y KY.Z MZ.Y LZ.Y KY.Z$~d$Y>XHZ KY0X HY0X GX0X GX0Y BY=Y BY.Y FY=Z 9WK~KW/WJ}JW.W:\\:W.W" "9[:W/W9[9W >X .Z=Y JZ /X@U 6~^*~g&~Y N~V KX.Y IX.X ?ZFZ 7ZBY L~l 4Z 3Y \"X@X 3n /X" "CZIZ2Z@\\<Y :Y BY %V <~e Y 6Z.Y 4Z N\\ G\\ FX8Z K[ I]2Z 2Z 8\\9[ BsNZ ?] B^ @Y GV=W4X>W.Z6" "Z IZ1[ Z !Z#[\"Z MZ 1[2l'Z(Z :Z \"Z 4ZK] -Z 2YBXHYBY(Y>ZDZ*Z KZ\"v L[ LZ&z !c 4Y 9Z(Z HZ>Z\"ZDX>XDY Ge 'Z '[ " "\"X GX GY Dw FY.Y JY %Z/Z J~W :Y 5Y.Y GY1Y 5Y NX 0XN\\ LY FY3Y2Y+Y1Y JY.Z JY.Y Z/Y ;Y 'e $Y .Y1Y CZ=Z" " KYDXGWDY @a 3Z>Y +[ 5d IX Ic L~d !U8X7T'Z4[ CY5\\ AZCa GY-Y @h 9Y1Y @X?Z 6ZGY ?Y1Y&[9X9Z+ZAYAZ IY9Y IY@X@Y " "KY/Z Y-Y 5Y 5Y.Z IZ6Z 2[ 2Z 1Z M[/Z;Z<[*Z(Z%[AZB\\,[ LZ3~p BX B~o BX C~q CX NY?U 8y <W2W 2[ (Y7Y ITDW " "NU M[CZ 6X &T=WFY8T -X EY1Y 1WEW 3Z 7ZC[ 6W6ULV HX+W JX7ULW CY 5Z6Z EY5Y DZ6Z EY5Y DZ6Z E" "Z6Y$Z9Z <Z HZ !Z Z !Z >Z !Z !Z \"Z :Z#[)Y>ZCY*Z KZ/Z KZ0Z L[1[ L[1[ LZ A] B[?X6Z*Z(Z#Z(Z$Z(Z$Y'Y 9Z 2Z3[ KY?" "_ 8w ?x ?w =w >w >w$~u/Y #~W M~W M~W M~W 7Y Y NX Y 6Z.Y IX0X JY-Y KY.Z MZ.Z MY-Y KY-Y$~d$Y?XFY KY0X HY0X GX0" "X GX0Y BY>Z BY.Y EY>Y 8WK~KW/WJ}JW.W;]:W.W:[9W/W9[9W >X -Y>Z KZ .YAU 6~^*~g%~W L~T JX.Y IX.X ?YEZ 7Z" "CZ L~k :y KY \"X@X 0m 1WCYEY3Y>\\=X 9Y BY %V <~e =l X 5Z.Y 4Z \\ E[ GY8Z JZ I]" "2Z 2Z 8[7[ BqMZ ?^ C^ @Y GV=W4X>V-Y5Z IZ0[!Z !Z#[\"Z MZ 1[2l'Z(Z :Z \"Z 4ZJ] .Z 2YAXIXAY(Y=YDZ*Z L[\"s" " I[ LZ&[Cc Na 5Y 9Z(Z HZ?Z YDX>XEZ Hg (Z (\\ \"X GX GY Fy FY.Y KZ %Z/Z J~W :Y 5Y.Y GY1Y 5Y NX 0e KY" " FY3Y2Y+Y1Y KZ.Z JY.Y Y.Y ;Y &h (Y .Y1Y BY=Y IXDXGWDY ?_ 1Y?Z ,[ 4b GX Ga L~c T6V6T'Z4[ CY4\\ CZ@_ GY-Y >f " "9Y1Y @Y@Y 5YFZ @Y1Y&Z8X9[,ZAYAZ IY9Y IY@X@Y KX.Z Y-Y 5Y 5Y.Z IY5Z 3[ 1Z 1Z M[/[<Z<[*Z(Z%\\BZC\\+[ LZ3~p BX B~o " "BX C~q CX DX 4Z?U -Z (W2W 2Z 'Z7X ITDX U MZCZ 5X &U>WEY9T -X EY1Y 1WEW 3Z 6ZCZ 7X7" "UKV HW*W KX6ULW CY 5Y5Z FZ5Z EY4Y FZ5Z EZ5Y EY5Z%Z9Z <Z HZ !Z Z !Z >Z !Z !Z \"Z :Z#Z(Y=ZDY*[ LZ/Z KZ0Z L[0Z " "LZ0[ LZ A] B[@X5Z*Z(Z#Z(Z$Z(Z$Y'Y 9Z 2Z4[ JY>` <y @y Ay ?y @y @y%~v/Y #~W M~W M~W M~W 7Y Y NX Y 6Z.Y IX0X JY" "-Y KY-Y MZ.Z MY-Y KY-Y$~d$Y?WEY KY0X HY0X GX0X GX0Y BZ?Y AY.Y EY>Y 8WK~KW/WJ}JW.W<_;W.W;[8W/W9[9W >X -Z?Z " " LZ -YBU 5~^*~h%~U J~R IX.Y IX.X @ZDY 6YCZ LW 'y JY \"W?X ,j 3WCYCY4Y=\\>X 9Y CZ" " %V <~e =l X 5Z.Y 4Z !\\ C[ IY7Z JZ I]2Z 3[ 9[5[ BoLZ ?a Ia @Y HW>X3W>V.Z4Y IZ/Z!Z !Z#[\"Z MZ 0" "Z Z'Z(Z :Z \"Z 4ZI] /Z 2YAXIXAY(Y=ZEZ*Z L[\"o DZ LZ&Z<^ M_ 5Y 9Z(Z GZ@Z ZEX>XEZ I[MZ (Z )\\ !X GX GY " "Gz FY.Y KZ %Y-Y J~W :Y 5Y.Y GY1Y 5Y NX 0c IY FY3Y2Y+Y1Y KZ.Z JY.Y Y.Y ;Y %j +Y .Y1Y BY=Y IYEXGXEY >] 0Y?Y ,[ " "3` EX E_ L\\Cx NT6V6T'Z4Z BY2Z CY>^ GY-Y ;c 9Y1Y @YAZ 6ZEY @Y1Y&Z8X9[,ZAYAZ IY9Y IY@X@Y KX.Z Y-Y 5Y 5Y.Z JZ" "4Y 4\\ 1Z 1[ NZ.[<Z<Z)Z(Z$\\CZD]*Z LZ3~p BX B~o BX C~q CX DX 4Z?U -Z (W2W 2Z 'Z7X ITDX U MYBY 4X &U>" "WDX:U -X EY1Y 1WEW 3Z 5YBY 7W6UKV IX*W KW6UKW CY 6Z4Y FZ5Z FZ4Z GZ4Y EY4Z GZ4Y%Y8Z <[ IZ !Z " " Z !Z >Z !Z !Z \"Z :Z#Z(Y=ZDY*[ LZ/Z L[0Z L[0Z LZ0[ LZ B_ BZAY5Z*Z(Z#Z(Z$Z(Z$Y'Y 9Z 2Z5\\ JY=` ?{ B{ Bz @z B{ " "B{'~x/Y #~W M~W M~W M~W 7Y Y NX Y 6Z.Y IX0X JY-Y LZ-Y MZ.Z MY-Y KY-Y$~d$Y@WDY KY0X HY0X GX0X GX0Y AY@Z AY.Y " "DY@Z 8WK~KW/WJ}JW.W=a<W.W<[7W/W9[9W >X ,Y?Y LZ +XBU 6~_+~i%~U I~P HX.Y IX.X @ZDZ 7YCY KX " " (y JY \"W?W (h 5XCXAX5Z<\\@Y 9Y CZ $T ;~e =l X 5Z/Z 4Z \"\\ AZ IX6Z JZ I\\1[ 4Z 8Z3Z AmKZ" " ?d d AZ HW>X3W>V.Z4Z JZ.Z\"[ \"Z#[\"Z MZ 0Z Z'Z(Z :Z \"Z 4ZH] 0Z 2YAYKX@Y(Y<ZFZ*[ M[\"Z /Z LZ&Z:\\ K" "^ 6Y 9Z(Z GZAZ NZEW<WEZ IZL[ )Z *\\ X FX HY H{ FY.Y KZ %Y-Y K~X :Y 5Y.Y GY1Y 5Y NX 0c IY FY3Y2Y+Y1Y" " KZ-Y JY.Y Y-X ;Y $l .Y .Y1Y AY?Y HYEWFXEX =\\ .Y@Y -[ 2b GX Ga LY=s LT6W7T'Z4Z BY2Z DY=^ GY-Z =d 9Y1Y ?XAY" " 5YDZ AY1Y&Z8X9[,ZAYAZ IY9Y IY@X@Y KX.Z Y-Y 5Y 5Y.Z JZ4Z 5[ 0Z 0Z NZ-Z<Z<Z)Z(Z#\\DZD\\)Z LZ3~p BX B~o BX B~p CX" " DX 4Z?U -Z (W2W 2Z &[9X IUEX T s AXAY 4X &U>WCX;U -X EY1Y 1WEW 3Z Is 0YAX 8W6UJV IW)W" " LX7UJW CY 6Z4Z GY3Y FZ4Z GY3Y FZ4Z GY3Z'Z8Z <[ IZ !Z Z !Z >Z !Z !Z \"Z :Z#Z(Y<ZEY*[ M[/[ M[0Z LZ/Z LZ/Z LZ " "Ca CZBY4Z*Z(Z#Z(Z$Z(Z$Y'Y 9Z 2Z5\\ JY<` A| C| C{ A{ C| C|(~y/Y #~W M~W M~W M~W 7Y Y NX Y 6Y-Z JX0X JY-Y LZ-Y" " MZ.Z MY-Y KY-Y$~d$YAWCY KY0X HY0X GX0X GX0Y AY@Y @Y.Y DY@Y 7WK~KW/XK}KX.W>c=W.W=[6W/X:[:X >X ,Y@Z M[ " "+YCT 5~`,~i$~S H~P HX.Y IX.X @YCZ 7ZDY KX )y HX #X@X (TNc 6WCX@X5Y:\\AX 8Y CZ :~e" " =l !X 4Z/Z 4Z #\\ @[ KY6Z IZ I[0Z 4Z 9Z2[ @jJZ ?f %g AZ HW>X3W>V.Y2Y JZ.Z\"[ \"Z#Z!Z MZ 0Z Z'Z(Z" " :Z \"Z 4ZG] 1Z 2Y@XKX@Y(Y<ZFZ*[ MZ!Z /Z LZ&Z8[ K] 6Y 9Z(Z FZBZ NZFX<XFY I[KZ )Z +\\ NX FX HY I| FY." "Y KZ %Y-Y K~X :Y 5Y.Y GY1Y 5Y NX 0d JY FY3Y2Y+Y1Y KZ-Y JY.Y Y-X ;Y #m 0Y .Y1Y AY?Y HYFXEWFY =\\ .YAY ,[ 2d I" "X Ic LW8n JU7W7T'Y2Y BY1Z EY<\\ FY-Z @g 9Y1Y ?YBY 6ZDZ AY1Y&Z8X8Z,Y@YAZ IY9Y IY@X@Y LY-Y Y-Y 5Y 5Y.Z JY3Z 6[" " /Z 0Z [-[=Z=[)Z(Z#]EZE\\(Z LZ2~o BX B~n AX A~n BX DX 4Z?U -Z (X4X H~W <\\:W HUDX!T s AZCZ 5X %T>WBX<U" " -X EY1Y 1WEW \"s 1ZCZ 9X7UIV JX)W LW7UIW CY 6Y2Y HZ3Z GY2Y HZ3Z GY2Y HZ3Z'Z8Z <[ IZ !Z Z !Z" " >Z !Z !Z \"Z :Z#Z(Y<ZEY)Z M[/[ M[0[ MZ/Z LZ/Z M[ Dc DZCY3Z*Z(Z#Z(Z$Z(Z$Y'Y 9Z 2Z6\\ IY:` D} D} D| B| D} D})~z" "/Y #~W M~W M~W M~W 7Y Y NX Y 6Y-Z JX0X JY-Y LZ-Y MY-Z MY-Y LZ-Y$~d%ZBXCY KY0X HY0X GX0X GX0Y @YAY @Y.Y DYAZ " " 7W8X8W.W HW-W?e>W.W>[5W.W:[:W =W +ZAY LZ *YDU 5~`,~i#~Q F} GX.Y IX.X AZBY 7ZEZ KX " ")y HX 6~e 9TJ_ 7XCX?X6Y9\\BX 8Y CZ KX Nl !X 4Z/Z 4Z $\\ >Z LY5Z IZ I[0Z 5Z 8Z1Z >fHY =h " " +i @Z HW>X3W?W/Z2Z KZ.[#[ \"Z#Z!Z MZ 0Z Z'Z(Z :Z \"Z 4ZF] 2Z 2Y@XLY@Y(Y;ZGZ*[ MZ!Z /Z M[&Z7[ K\\ 6Y 9Z(Z FZ" "BZ MYFX<XGZ J[IZ *Z +[ MX FX HY Jb>Y FY.Y KZ %Y-Y K~X :Y 5Y.Y GY1Y 5Y NX 0e KY FY3Y2Y+Y1Y KZ-Y JY.Y" " Y-X ;Y !m 2Y .Y1Y AZAZ GYGXEXGY >] .ZBY -[ 1e JX Ke LU4k IU8Y8T'Y2X AY0Y EX:[ FY-Z Ah 9Y1Y >XCZ 6YBY AY1Y&" "Z8X8Z,Y@YAZ IY9Y IY@X@Y LY-Y Y-Y 5Y 5Z/Y JZ2Z 8[ .Z 0[!Z,[=Z=[)Z(Z\"]FZG]'Z M[1] 1X 1\\ @X @\\ L\\ AX DX 4" "Z?U -Z (X4X H~W ;\\;W GTDX\"U s A[D[ 6X %T>WBX<T ,X EY1Y 1WEW \"s 2[D[ 9W7UHV KX(W MX7UI" "W CY 7Z2Z IZ3Z HZ2Z IZ3Z HZ2Z IZ3Z(Z7Z ;Z IZ !Z Z !Z >Z !Z !Z \"Z :Z$[(Y;ZFY)Z M[/[ MZ/[ MZ/Z M[/Z M[ Ee EZC" "X3[*Z(Z#Z(Z$Z(Z$Y(Z 9Z 2Z8^ IY9` Fb=Y Eb=Y Eb=X Cb>Y Eb=Y Eb=Y*b=~V/Y #~W M~W M~W M~W 7Y Y NX Y 6Y-Z JX0X JY" "-Y LZ-Y MY-Z MY-Y LZ-Y CZCXBY KY0X HY0X GX0X GX0Y @YBZ @Y.Y CYBY 6W8X8W.W HW-W@g@X.W?[4W.W:[:W =W *YBZ " " MZ (XDU 5~`,~i\"~ D{ FX.Y IX.X AZBZ 7YEY IX +y GX 6~e 9TG] 8WBW>X6Y8\\DY 8Y CZ " " KX Nl !X 4Z/Z 4Z %\\ =Z LX4Z IZ I[0Z 5Z 9Z0Z <bFY ;i 1i =Z HW>X3W?W/~S KZ-Z\"Z \"Z#Z!Z MZ 0[!Z" "'Z(Z :Z \"Z 4ZE] 3Z 2Y?XMX?Y(Y;ZGZ)Z MZ!Z /[ N[&Z6[ K\\ 7Y 9Z(Z FZCZ LZGX<XGZ JZH[ +Z ,\\ MX FY IY K" "]8Y FY.Y KZ %Y-Y K~X :Y 5Y.Y GY1Y 5Y NX 0f LY FY3Y2Y+Y1Y KZ-Y JY.Y Y-X ;Y Mk 3Y .Y1Y @YAY FYGWDXGY >^ .YCZ ." "[ )_ KX L_ ES/e FU8Z9T'Z3X AY0Y FY:[ FY-Z Cj 9Y1Y >XCY 6ZBZ BY1Y&Z8X9[,Y@YAZ IY9Y IY@X@Y LY-Y Y-Y 5Y 5Z/Y J" "Z2Z 9\\ .Z /Z!Z,\\>Z>[(Z(Z!]GZH^'[ N[0\\ 1X 2\\ ?X ?[ M\\ @X DX 4Z?U -Z 'W4W G~W :]>X GTDY#U s @[D[ 7" "X %U?WAX>U ,X EY1Y 1WEW \"s 3ZC[ 9X7UHV KW(W MX7UHW CY 7~S J~S H~S I~S I~S I~S)} ;Z IZ !Z Z" " !Z >Z !Z !Z \"Z :Z$[(Y;ZFY)Z MZ-Z MZ/[ N[/[ N[/Z MZ Eg F[EX2[*Z(Z#Z(Z$Z(Z$Y(Z 9Z 2Z9^ HY7_ G]8Y F^8Y F^8X D]8" "Y E]8Y F^8Y+^8~V/Y #~W M~W M~W M~W 7Y Y NX Y 6Y-Z JX0X JY-Y LZ-Y MY-Z MY-Y LZ-Y BYDXAY KY0X HY0X GX0X GX0Y" " @ZCY ?Y.Y CYBY 5W9X8W.W HW-WAiAW,WA[3W.W9Y9W >X *ZCZ 6~d IYET 4~`,~i!| By EX.Y IX.X AYAZ 7ZFY IX " " Z 3X 6~e 9TF\\ 9WBX=W7Z7\\EX 7Y CZ KX Nl \"X 3Z/Z 4Z &\\ ;Z M~Z %Z I[0Z 6[ 9Z/" "Y 8ZCZ 8i 6~d 5i ;Z HW>X3W?W0~T KZ-Z\"Z \"Z$[!Z MZ 0[!Z'Z(Z :Z \"Z 4ZD] 4Z 2Y?XMX?Y(Y:ZHZ)Z N[!Z /[ NZ%Z6[" " J[ 7Y 9Z(Y DZDZ LZGW:WGZ K[GZ +Z -\\ LX EX IY L\\6Y FY.Y KZ %Y-Y K~W 9Y 5Y.Y GY1Y 5Y NX 0XM\\ MY " "FY3Y2Y+Y1Y KZ.Z JY.Y Y-X ;Y Ji 4Y .Y1Y @YAY FYGWDXGX >` /YCY .[ $\\ LX M\\ AR+` CT9[:U'Z3X AY0Y FY9Z FY-Z " "D` .Y1Y >YEZ 6YAZ BY1Y&Z8X9[,ZAYAZ IY9Y IY@X@Y LY.Z Y-Y 5Y 5Z/Y KZ1Z 9[ -Z /Z\"[+[>Z>[(Z(Z ^IZJ_&[ NZ.\\ 2X 3" "\\ >X >[ \\ ?X DX 4Z?U -Z 'X6X G~W 9^@X GUDY$T Ns ?[CZ 8X %U?WAY?U ,X EY1Y 1WEW \"s 4" "ZCZ 7W7UGV LX)X MW7UGW CY 8~T J~T I~S J~T I~T K~T*~ ;Z IZ !Z Z !Z >Z !Z !Z \"Z :Z$[(Y:ZGY)[ NZ-Z N[.Z N[/[ N" "[/[ NZ Fi G[FX1Z)Z(Z#Z(Z$Z(Z$Z)Z 9Z 2Z<a HY5^ I[5Y F[5Y G\\5X E\\6Y F\\6Y F[5Y+[5~V/Y #~V L~V L~W M~W 7Y Y NX" " Y 6Y-Z JX0X JY-Y LZ-Y MZ.Z MY-Y KY-Y BYDW@Y KY0X HY0X GX0X GX0Y ?YDZ ?Y.Y BYDY 4W9X9X.W HW-XC\\L[BW,WB[" "3X.W HW >X )YCY 5~d IYFU 4~`,~i!{ @x EX.Y IX.X AY@Y 7ZGZ IX Z 3X 6~e 9TD[ ;XBX=X8" "Z6\\GY 7Y CY JX Nl \"X 2Y/Z 4Z '\\ :Z M~Z %Z I[0Z 6Z 8Z/Z \"Z 5i 9~d 8i 8Z HW>X3W?W0~U LZ-Z\"[ " "#Z$[!Z MZ /Z!Z'Z(Z :Z \"Z 4ZC] 5Z 2Y?XNY?Y(Y:ZHZ)[ [!Z .Z NZ%Z5[ K[ 7Y 9Z(Y DZDY KZHX:XHY K[EZ ,Z .\\ KX EX" " IY LZ4Y FY.Y KZ %Z.Y KZ <Y 5Y.Y GY1Y 5Y NX 0XL\\ NY FY3Y2Y+Y1Y KZ.Z JY.Y Y.Y ;Y Ff 5Y .Y1Y @ZCZ FY" "HXCWHY ?b /YDY /[ ![ MX M[ @Q%W ?T9\\;U'Z3X AY0Z GX8Z FY-Z E\\ )Y1Y =XEY 6Z@Y BY1Y&Z9Y9[,ZAYAZ IY9Y IY@X@Y " "LY.Z Y-Y 5Y 4Y/Y KZ0Z ;[ ,Z /[#Z*\\?Z?\\(Z(Z N`LZL`$Z NZ-\\ 3X 4\\ JPCXCP J[\"\\ >X DX 4Z?U -Z 'X6X G~W " "8^BX FUDY%U Ns =ZCZ 9X $U@W@X?T +X EY1Y 1WEW \"s 5ZCZ 7W7UFV LW(W MX8UFW CY 8~U K~T J~U K~" "T J~U K~T*~ ;[ JZ !Z Z !Z >Z !Z !Z \"Z :Z$Z'Y9YGY)[ [-[ [.Z N[.Z NZ.[ NZ G\\L[ GZGX0Z)Z(Z#Z(Z$Z(Y#Z)Z 9Z 2~ " "GY4] J[4Y G[4Y G[4X EZ4Y FZ4Y G[4Y,[4X 1Y #Y Y Y Y 9Y Y NX Y 6Y-Z JX0X JY-Y LZ-Y MZ.Z MY-Y KY-Y BYEW?Y" " KY0X HY0X GX0X GX0Y ?YDY >Y.Y BYDY 4W9X9W-X JX,WD\\J[CW,WC[2W-X JX >X )YDZ 5~d HXFU 4~_+~i z @w DX.Y" " IX.X BZ@Y 6YGZ IY Y @~e 9TCZ ;WAX=X8Y4\\HX 6Y CY JX Mj !X 2Y/Y 3Z (\\ 9Z" " M~Z %Z I[0Z 6Z 8Z/Z \"Z 2i <~d ;i 5Z HW>X3W@W/~U LZ-[#[ #Z$Z Z MZ /Z!Z'Z(Z :Z \"Z 4ZB] 6Z 2Y>a>Y(Y9ZIZ)[ " "Z Z .Z [%Z4Z JZ 7Y 9Z)Z DZEZ JYHX:XIZ KZD[ -Z /\\ JX EX IY MZ3Y FY.Y JY %Z/Z JY <Y 5Y.Y GY1Y 5Y NX" " 0XK\\ Y FY3Y2Y+Y1Y KZ.Z JY.Y Y.Y ;Y Bc 6Y .Y1Y ?YCY DYIXCXIY @c /YEY /[ NZ MX N[ *U;^=U&Z4Y AY/Y HY7X" " EY-Y E[ 'Y1Y =YFY 6Z@Z CY1Y&Z9Y9Z+ZAYAZ IY9Y IY@X@Y LZ/Z Y-Y 5Y 4Y0Z KZ0Z <[ +Z .Z$[)\\@Z@\\'Z(Z M~Q#Z [,\\ 4" "X 5\\ JRDXDR J[$\\ KQCXDQ #Y 4Z?U -Z &X8X F~W 7_EY EUDY&U Ns <ZCZ :X $U@W?XAU +X EY1Y 1WEW " " \"s 6ZCZ 7X8UEV MX)X MW7UFW DZ 8~U L~V K~U L~V K~U K~U+~ :Z JZ !Z Z !Z >Z !Z !Z \"Z :Z%['Y9ZHY(Z [-[ Z" "-[ Z-Z [-Z [ H\\J[ HZHY1[)Z(Z#Z(Z$Z(Y#Z)Z 9Z 2} FY2\\ KZ3Y GZ3Y GY3Y FZ3Y GZ3Y GZ3Y,Z3X 1Y #Y Y Y Y 9Y Y " "NX Y 6Y-Z JX0X JY-Y KY.Z MZ.Z MY-Y KY-Y BYFX?Y KY0X HY0X GX0X GX0Y >YEY >Y.Y BYEZ 4X:X9W,W JW+WE\\H[EX,X" "E[1W,W JW =X )ZEY 4~d HYHU 2~^+~i Nx >u CX.Y IX.X BY?Z 7ZHY GX Z A~e 9TCZ <XAW<" "X8Z4\\JY 6Z DY JX 4X 1Z0Y 3Z )\\ 8Z M~Z %Z I[0Z 7Z 7Z/Z \"Y /i >~d >i 2Z GV>X3W@W0~V LZ-[\"Z " "#Z%[ Z MZ /[\"Z'Z(Z :Z \"Z 4ZA] 7Z 2Y>a>Y(Y9ZIZ(Z Z Z .[![%Z4[ KZ 7Y 9Z)Z CZFZ JZIX:XIZ L[CZ -Z /[ IX DX J" "Y MY2Y FY.Y JY %Z/Z JY <Y 5Y.Y GY1Y 5Y NX 0XJ\\ !Y FY3Y2Y+Y1Y JY.Z JY.Y Z/Y ;Y ?a 7Y .Y1Y ?YCY DYIWBX" "IY @d /YFY 0[ LY MX NZ )U<VNW=U&Z4Y AY/Y HY8Y EZ.Y F[ &Y1Y =YGZ 7Z>Y CY1Y&Z9Y9Z+ZAYAY HY9Y IY@X@Y LZ/Y N" "Y-Y 5Y 4Y0Z LZ.Y =[ *Z .[%Z(]AZA]'Z(Z L~\"[![+\\ 5X 6\\ JTEXET J[&\\ KSDXES $Y 3Y?U -Z &Y:Y F~W 5_GX DU" "CZ9QAU DZCZ ;X $VAW?YBU +X EY1Y 1WEW DZCZ 6W7UEV NX)X MX8UEW DY 8~V L~V L~W M~V K~V M~V" ",~P :Z JZ !Z Z !Z >Z !Z !Z \"Z :Z%['Y8ZIY(Z Z+Z Z-[![-[![-[![ I\\H[ I[JY0[(Y(Z#Z(Z$Z)Z#Z)Z 9Z 2| EY1\\ LY2Y " "HZ2Y HZ3Y FY2Y GY2Y GY2Y-Z2X 1Y #Y Y Y Y 9Y Y NX Y 6Z.Y IX0X JY-Y KY.Z MZ.Z MY-Y KY.Z BYGX?Z KY1Y HY0X" " GX0X GX0Y >YFZ >Y.Y AYFY 2W:X:X,W JW+XG\\F[FW+XF[1X,W JW =X (YEY 4~d GXHU 2kNRMk*tNq Mv <s BX.Y IY/X" " BY>Y 7ZIZ GY !Z A~e 9TBY <W@W;W8Z3\\KX 5Z DY JX 4X 1Z1Z 3Z *\\ 7Z M~Z %" "Z HZ0Z 7Z 7Y.Z #Z ,i A~d Aj 0Z GV=W4X@W0~W MZ-[\"[ $Z%[ Z MZ /[\"Z'Z(Z :Z \"Z 4Z@] 8Z 2Y>`=Y(Y8ZJZ([\"[ Z " ".[!Z$Z3Z KZ 7Y 9Z)Z CZGZ IZIW8WIZ M[AZ .Z 0\\ IX DX JY MY2Y FY.Y JY $Y/Z JY <Y 5Z/Y GY1Y 5Y NX 0XI" "\\ \"Y FY3Y2Y+Y1Y JY.Z JY.Y NY/Y ;Y ;] 7Y .Y1Y >YEY CYIWBXIX @f 0YGZ 0[ LZ NX NY 'U>WMW?V&Z4Y AY/Y HY8Y" " EZ.Y FZ %Y1Y <XGY 6Z>Y CY1Y&[:Z:Z+ZAYAY HY9Y IY@X@Y LZ/Y NZ.Y 5Y 4Y0Y KZ.Z ?\\ *Z -['['\\AZB]&Z(Z K|![!Z)\\ 6" "X 7\\ JVFXFV J[(\\ KUEXFU %Y 3Y?U -Z %Y<Y /Z M`KY BUC[=SAU CZCZ <X #UAW>XCU *X EY1Y 1WEW" " F[CZ 6X8UDV NW)X MX8UDW DY 8~W N~W L~W M~V L~W M~W-~P :[ KZ !Z Z !Z >Z !Z !Z \"Z :Z%['Y8ZIY([\"[+[" "\"[,Z![-[!Z,[!Z I\\F[ J[KY/Z'Z)Z#Z)Z#Z)Z#Z)Z 9Z 2{ DY0[ MY1Y HY1Y HY2Y FY2Y HZ2Y HY1Y-Y2Y 1Z $Y Y Y Z :Y Y" " NX Y 6Z.Y IX0X JZ.Y KY.Z MZ.Y LZ.Y KY.Z BYHX>Z KY1Y HY1Y GX0X GX0Y =YGY =Y.Y AYFY 2X;X:W+X LX*WH\\D[HX" "*WG[0W+X LX =X (YFZ 4~d GYIU 2jLQLj*pNRNq Lt :q AX.Y IY0Y CZ>Y 6YIZ FX !Z A~e 9T" "BZ >W?W;W8Z2\\MY 4Y DY JX 4X 1Z1Z 3Z +\\ 6Z M~Z %Z HZ0Z 8[ 7Y.Z #Z )i D~d Ci -Z GV=W4XAW/~W M" "Z-[\"[ $Z&[ NZ MZ .Z\"Z'Z(Z :Z \"Z 4Z?] 9Z 2Y=_=Y(Y8ZJZ([\"[ Z -Z\"[$Z3[ L[ 8Y 9Z)Z BZHZ IZJX8XJY LZ@[ /Z 1\\" " HX DX JY NY1Y FZ0Z JY $Y/Z JY <Y 5Z0Z GY1Y 5Y NX 0XH\\ #Y FY3Y2Y+Y1Y JY.Y IY/Z NY/Y ;Y 9\\ 8Y .Y1" "Y >YEY BXJXAWJY A[N[ 1YGY 0[ JY NX NY 'V@WLX@U$Y5[ BY/Y HX7X DZ.Y FY $Y1Y <YIZ 6Y=Z DY1Y&[:Z:Z*YAYAY HY9" "Y IY@X@Y LZ/Y NZ/Z 5Y 3Y1Y KY-Z ?[ )Z -[([%]CZC]%Z(Z Jy M[#[(\\ 7X 8\\ JXGXGX J[*\\ KWFXGW &Y 3Y?U -Z %Z>Z " "/Z K_MZ BUC]BVBU A[D[ >X #VBW=XDU *X EY1Y 1WEW G[D[ 5W8UCV X*X LW8UCW EZ 8~W N~X M" "~W N~X M~W N~X.~Q :[ KZ !Z Z !Z >Z !Z !Z \"Z :Z&[&Y7ZJY([\"[+[\"[,[\"Z+[#[+Z\"[ J\\D[ JZKX/['Z*[#[*Z#Z)Z#Z)Z" " 9Z 2z CY/Z MY1Y HY2Z HY2Y GY1Y HY1Y HY1Y-Y2Z 2Z $Z !Z !Z !Z :Y Y NX Y 6Z.Y IX0X JZ/Z KY.Z LY.Y LZ/Z KY.Z " " BYHW=Z KY1Y GX1Y GX1Y GX0Y =YHZ =Y/Z @YHY 1X;X;X*W LW)XJ\\B[IX*XI[0X*W LW <X (ZGY 3~d GYJU 1iKQKi*pN" "RMo Jr 9q AX.Y HX0Y CZ>Z 7ZJY EY !Z 1X@X &TAY ?X?W;W8Z1\\NX 3Y DY JX 5Y 0" "Y1Z 3Z ,\\ 5Z M~Z %Z HZ0Z 8Z 6Y.Z #Z &i G~d Fi )X FV=X5XAW0~Y NZ-[!Z $Z&[ NZ MZ .[#Z'Z(Z :Z \"Z 4Z>] :Z 2" "Y=_=Y(Y7ZKZ'Z#[ NZ -[#[$Z2[ M[ 8Y 9Z)Z BZHZ HYJX8XKZ M[?Z /Z 2\\ GX CX KY NY1Y FZ0Z JZ %Y/Z JZ =Y 4" "Y0Z GY1Y 5Y NX 0XG\\ $Y FY3Y2Y+Y1Y JZ/Y IZ0Y MY/Y ;Y 8[ 8Y .Y1Y >ZGZ BYKXAXKY B[LZ 0YHY 1[ IY NX Z &VB" "XKXBV$Y5[ BY/Y HX8Y CY/Z GY #Y1Y <YIY 6Z<Y DY1Y%Z:Z:Z*YAYAY HY9Y IY@X@Y LZ/Y NZ/Z 5Y 3Y2Z LZ,Z A[ (Z ,[)[%^DZD^" "%Z(Z Iw L[#['\\ 8X 9\\ JZHXHZ J[,\\ KYGXHY 'Y 3Z@U -Z $[B[ .Z NW $j @UCpBU @[D[ ?X \"UBW=XEU )X " " EY1Y 1WEW H[D[ 5W8UBV W*X LX8UCW F[ 9~Y ~X N~Y ~X N~Y ~X.~Q 9[ LZ !Z Z !Z >Z !Z !Z \"Z :Z&[&" "Y7ZJY'[#Z)Z#[+[#[+[#[+[#[ K\\B[ K[MX.['Z*Z!Z*Z#Z)Z#Z)Z 9Z 2x AY.Z NY2Z HY2Z IY1Y GY1Y HY1Y HY2Z-X1Z 2Z $Z !Z !Z" " !Z :Y Y NX Y 5Y/Z IX0X JZ/Z KZ/Y KY.Y LZ/Z KZ/Y AYIW<Y IX1Y GX1Y GX1Y GY2Z =YHY <Z0Y ?YHY 0X<X;X*X N" "X)XJ[@[KX(XK[/X*X NX <X 'YHZ 3~d FXJU 0hKQKh(nMRMo Jq 7o @X.Y HX0X BY=Z 7ZKZ DY \"Z " " 1W?X &TAY ?W>W;W8Z0e 3Y EZ JX 5X /Z2Y 2Z -\\ 4Z M~Z %Z HZ0Z 8Z 6Z/Z $Z #j J~d Ii CW>X6Y" "BX0~Y NZ-[![ %Z'\\ NZ MZ -Z#Z'Z(Z :Z \"Z 4Z=] ;Z 2Y<]<Y(Y7ZKZ'[$[ NZ -[$[#Z1Z M[ 8Y 8Z*Z BZIZ GZKX8XKZ N[>[ 0" "Z 3\\ FX CX KY NY2Z FZ0Y IZ %Y/Z JZ =Y 4Y0Z GY1Y 5Y NX 0XF\\ %Y FY3Y2Y+Y1Y JZ/Y IZ0Y MY/Y ;Y 7Z 8Y" " .Y2Z =YGY AYKW@XKY BZJZ 1YIY 1[ HY NX Y %WEYIYFW#Y5[ BY/Y HX8Y CY/Z GY #Y1Y ;XIY 6Y;Z EY1Y%Z:Z:Z*ZBYBZ " "HY9Y IY@X@Y LZ/Y MY/Z 4Y 4Y2Y KZ,Z B[ 'Z +[+[#_FZF_$Z(Z Gt JZ$[%\\ 9X :\\ J\\IXI[ I\\/\\ K[HXI[ (Y 3Z@U -Z " "%^F^ /Z X \"f >VBnCU >[D[ @X \"VCW<XGV )X EY1Y 1WEW I[D[ 5X8UBV!W)X LW8UBW FZ 8~Y!~Z" " ~Y!~Z ~Y ~Y0~R 9[ LZ !Z Z !Z >Z !Z !Z \"Z :Z'[%Y6ZKY'[$[)[$[*[$[*[%[*[$[ K\\@[ Le.[&Z*Z!Z*Z\"Z*Z#Z*[ 9Z 2v " "?Y.Z NY2Z HX1Z IY1Y GY1Y HY2Z HX1Z.Y1Z 1Y #Y Y Y Y :Y Y NX Y 5Y/Z IX0X IY/Z KZ/Y KY/Z KY/Z KZ/Y 7\\ 7ZKW" ";Y IX1Y GX1Y GY2Y GY2Z <YIY <Z0Y ?YIZ 0X<X<X)X Y(XJY>YJX(XJY/X)X Y <X 'ZIZ 3~d FYKT /gJQJg(nMRLm Hp 6" "m ?X.Y HY1X CZ<Y 6YKZ DY \"Z 1W?W %TAY @X>W;W7Y/c 2Y EY IX 5X /Z3Z 2Z .\\" " 3Z M~Z &Z FY1Z 8[ 6Z/Z $Z i L~d Li @W>Y7YBW0Z*Y NZ-[![ %Z'[ MZ MZ -[$Z'Z(Z :Z \"Z 4Z<] <Z 2Y<]<Y(Y6ZL" "Z'[%[ MZ ,[%[#Z1[ N[ 8Y 8Z+[ AZJZ GZKW6WKZ NZ<[ 1Z 3[ EX CX KY NY2Z FZ0Y IZ %Z1[ IY =Y 4Z1Z GY1Y 5Y" " NX 0XE\\ &Y FY3Y2Y+Y1Y JZ0Z IZ0Y MZ1Z ;Y 6Y 8Y .Y2Z =YGY AYKW?WKX B[J[ 1YJY 2[ GY NX Y $ZL[H[JY#Y6\\ " "BY0Y GX8X BZ0Z GY #Y1Y ;YKZ 7Z:Y EY2Z%Z:Z:Z*ZBYBZ HY9Y IY@X@Y L[1Z MY/Y 3Y 4Z3Y LZ+Z C\\ 'Z +[,[!_GZG_#Z(Z Fq H" "[%[$\\ :X ;\\ H\\JXJ\\ H\\1\\ J\\IXJ\\ (Y 3Z@U -Z &x 0Z X c <UAmDV =[CZ AX !VDW<YHU (X E" "Y1Y 1WEW JZCZ 3W8UAV\"X*X LX9UAW G[ 9Z*Y!Z+Z Y*Y!Z+Z Y*Z\"Z+Z0Z3Z 8[ MZ !Z Z !Z >Z !Z !Z \"Z :Z(\\%" "Y6ZKY&[%[)\\&[)[%[)[%[)[%[ L\\>[ Ld.[&Z*Z!Z*Z\"Z+[\"Z+Z 8Z 2s <Y-Y NX1Z IY1Z IY2Z GY2Z HY2Z HX1Z.Y1Z 1Z $Y Y " "Z !Z ;Y Y NX Y 5Y/Z IX0X IY/Y JZ0Z KZ0Z KY/Y IY0Z 7\\ 6YLX<Z IX1Y GY2Y GY2Y GY2Z <YJZ <Z0Y >YJY .X=X=Y(" "X!X'YJW<WJX&XJW/Y(X!X ;X &YIY #[ LYLU .fJQJf&lLRLm Gn 4k >X.Y HY2Y CZ<Z 7YKY BY #[ " " 3X@X %TAY @W=W;W7Z0b 1Y EY IX 5X /Z3Z 2Z /\\ 2Z )Z JZ FZ2Z 8Z 5Z/Z %Z Ki :j >W=X8ZC" "W/Z*Z Z-Z N[ &Z(\\ MZ MZ -\\%Z'Z(Z :Z \"Z 4Z;] =Z 2Y<]<Y(Y6ZLZ&[&[ MZ ,\\'[\"Z0Z NZ 7Y 8Z+Z @ZJY FZLX6XLY N[;" "Z 1Z 4\\ EX BX LY NY2Z F[2Z HZ %Y1[ IZ >Y 4Z2[ GY1Y 5Y NX 0XD\\ 'Y FY3Y2Y+Y1Y IY0Z IZ1Z MZ1Z ;Y 6Y" " 8Y .Y2Z =ZIZ @XLX?WLY C[H[ 2YKZ 3[ EX NX Y $hFh\"Z7\\ BY0Y GX9Y BZ1Z FX \"Y1Y ;YKY 6Y9Y EY2Z%Z;[:Z*ZBYB" "Y GY9Y IY@XAZ L[1Y LZ1Z 3Y 3Y3Y LZ*Z D[ &Z *[-[ aJZJa\"Z(Z Cl F\\'[\"\\ ;X <\\ F\\KXK\\ F\\3\\ H\\JXK\\ 'Y " "2ZAU -Z 'z 1Z X Na ;V@jDV :ZCZ BX UDW;XIU 'X EY2Z 1WEW KZCZ 3X9U@V\"W*X LX9VAW H[ " "8Z*Z\"Y)Y!Z*Z\"Z*Y!Z*Z\"Z*Z1Z3Z 8[ MZ !Z Z !Z >Z !Z !Z \"Z :Z(\\%Y5ZLY&[&['[&[([&[)\\'\\)[&[ L\\<[ Mc.[$Z,[!" "[,[\"Z+Z!Z+Z 8Z 2n 7Y-Y NX1Z IY2[ IY2Z GY2Z HY2Z IY2[.Y2\\ 2Z $Z !Z !Z !Z ;Y Y NX Y 5Z0Y HX0X IZ1Z IY0Z KZ0" "Y JZ1Z IZ1Z 7\\ 6YMX;Z IY3Z GY2Y GY2Y GY2Z ;YKY ;Z1Z >YJY .Y>X=X'Y#Y&XIU:UJY&YJU.X'Y#Y ;X &YJZ #Z JXLU" " -dIQId%kKRKk El 2j >X.Y HY2Y CY;Z 7ZMZ BZ #Z 3X@X %TAX @W<W;W7Z/a 0Y FY IX " " 6X -Z4Z 2Z 0\\ 2[ )Z JZ FZ2Z 8Z 5Z/Z %Z Hi @j :V=Y9ZDX/Z*Z Z-Z N\\ 'Z)\\ LZ MZ ,[%Z'Z(Z :Z \"Z" " 4Z:] >Z 2Y;[;Y(Y5ZMZ&\\([ LZ +['[\"Z0[ Z 7Y 8[,Z ?YKZ EYLX6XLY [:[ 2Z 5\\ DX BX LY NY3[ F[2Z HZ %Y1" "[ IZ >Y 3Y2[ GY1Y 5Y NX 0XC\\ (Y FY3Y2Y+Y1Y IZ2Z H[2Z LY1Z ;Y 6Z 9Y .Y2Z <YIY ?YMX?XMY CZFZ 2YKY 3[ DY X " "Y #gEf!Z7\\ BY0Y GX9Y BZ1Z FX \"Y1Y :XLZ 7Z9Z FY2Z%Z;\\<[)ZCYCZ GY9Y IZAXAZ L[1Y LZ1Z 3Y 3Y4Y KZ*Z E[ %Z )[" "/[ MdNZNd!Z(Z Ag B['[!\\ <X =\\ D\\LXL\\ D[4\\ F\\KXL\\ &Z 3ZAU -Z (| 2Z X L^ 9V?fBU 8ZCZ CX V JV " " CY2Z 1WEW LZCZ 2W9V@V#X+X KW8U@W I[ 7Z*Z#Z)Z\"Z)Y#Z)Z\"Z)Y#Z)Z2Z2Z 7[ NZ !Z Z !Z >Z !Z" " !Z \"Z :Z)\\$Y5ZLY%[(\\'\\(['\\(['['['[(\\ M\\:[ Ma-[$Z,Z NZ,Z![,Z!Z,[ 8Z 2Z #Y-Y NX2[ IY2[ IY2Z GY3[ HX2[ IY2" "[.Y2\\ 2Z $Z !Z !Z Y ;Y Y NX Y 5Z1Z HX0X IZ1Z IZ1Z JZ2Z JZ1Z IZ1Z 7\\ 6c:Z IY3Z GY3Z GY3Z GY3[ ;YKY ;[2Z =" "YLY ,Y?X>Y&Y%Y%YIS8SJY$YJS.Y&Y%Y :X &ZKY #Z IYNU ,cISIb#jKRJi Cj 1i =X.Y GY4Y BY:Y 7ZMZ AZ " " $[,P )W?X %TBY AX<W;W7[/_ /Y FY IX 6X -Z5Z 1Z 1\\ 1Z (Z K[ EY2Z 9Z 4Z0[ &[ F" "j Ei 7W=Y;[EX/Z(Z!Z.[ M[!P'Z*] LZ MZ ,\\&Z'Z(Z :Z \"Z 4Z9] ?Z 2Y;[;Y(Y4YMZ%[)\\ LZ +\\)[!Z/Z Z 7Y 7Z-[ ?Z" "LZ EZMX6XMZ Z8[ 3Z 6\\ CX BX LY NY3[ F[2Y GZ %Z3\\ HZ ?Y 3Z4\\ GY1Y 5Y NX 0XB\\ )Y FY3Y2Y+Y1Y IZ2Z " "H[2Y KZ3[ ;Y 6Z 9Y .Z4[ <YIY ?YMW>XMY DZDZ 2YLY 3[ DY X Y \"eCd NY8^ CY0Y GX:Y @Z2Z FX \"Y1Y :YMY 6Y7Y " "FY2Z%[<\\<Z(ZCYCZ GY9Y HYAXAY K\\3Z KZ2Z 3Y 3Z5Y LZ)Z F[ $Z ([1[ K~U Z(Z ;[ <\\)[ N[ <X <Z B\\MXM\\ BZ3Z D\\L" "XM\\ %Z 3ZAU -Z )~ 3Z X J] 9V>a@V 7YBY CX NV LV BZ3Z 1WEW LYBY 2W8U?V#W+X KX9U" "?W J[ 7Z(Y#Z)Z#Z(Z$Z)Z\"Y(Z$Z(Y2Z2Z 7\\\"P NZ !Z Z !Z >Z !Z !Z \"Z :Z*\\#Y4ZMY%\\)[%[)\\&[)\\'\\)\\'\\)[ M\\8" "[ N`-[#Z,Z NZ,Z Z-[![-[ 8Z 2Z #Y-Y NX2[ IY2[ IY3[ GY3[ HY3[ HX2[.Y3^ 2Z $Z !Z !Z !Z <Y Y NX Y 4Z2Z HX0X HZ2" "Z IZ2Z IZ2Z IZ2Z IZ2Z 6\\ 5a:Z HY3Z GY3Z GY3Z GY3[ ;YLY :[2Y <YLY ,Y?X?Y$Y'Y#YIQ6QIY$YIQ.Y$Y'Y 9X %YLZ " "$Z HYNU +aHSH`!hJRIg Bi /g <X.Y GY4Y CZ:Y 6YMY @[ $Z-Q )W?W $TBY AW;W<X6Z.] .Y GY" " HX 6X -Z5Z 1Z 2\\ 0Z (Z L[ DZ4Z 8Z 4[1Z %Z Bj Ki 4W=Z=\\GY.Z(Z!Z.[ M\\#Q'Z+] KZ MZ +\\'Z" "'Z(Z :Z \"Z 4Z8] @Z 2Y:Y:Y(Y4ZNZ%\\*[ KZ *\\+\\!Z/[ \"[ 7Y 7Z-Z >ZMZ DZMW4WMZ![7Z 3Z 7\\ BX AX MY NY3" "[ F\\4Z FZ &Z3\\ HZ ?Y 3Z4\\ GY1Y 5Y NX 0X@[ *Y FY3Y2Y+Y1Y HZ3Z H\\4Z KZ3[ ;Y 5Y 9Y -Y4[ ;YKY >YNX=WNY D[D[ " "3YMY 3[ CY X Y !cAb MZ9^ CZ2Z GX:Y @Z3Z EX \"Y1Y :YMY 7Z7Y FZ4[$Z<\\<Z(ZCYCY FY9Y HYAXBZ K\\3Z KZ3Z 2Y 2" "Y6Z LZ(Z H\\ $Z (\\3[ I~R MZ(Z :Z ;\\+\\ MY ;X ;X @\\NXN\\ @X1X B\\MXN\\ $Z 2ZBU -Z *~Q 4Z X I] :W9U;V " " 5XAX CX MV NV AZ3Z 1WEW LXAX 2X8s+W,Y JW8t#\\ 7Z(Z%Z'Y#Z(Z$Y'Z$Z(Z$Z(Z4Z1Z 6[#Q NZ !" "Z Z !Z >Z !Z !Z \"Z :Z+]#Y4ZMY$[*\\%\\*[%\\+\\%\\+\\%\\+\\ N\\6[ N^-\\#[.[ N[.[ [.Z NZ-Z 7Z 2Z #Y-Y NY4\\ IY3" "\\ IY3[ GY3[ HY4\\ HX3\\.Y3^ 2Z $Z !Z !Z !Z <Y Y NX Y 4Z3Z GX0X HZ3Z GZ3Z IZ3[ IZ3Z GZ3Z 6\\ 5`9Z HY4[ GY4[" " GZ5[ GZ5\\ :YMY :\\4Z ;XMZ +Y@X@Y#Z)Z\"Y(Y\"Y(Y#Z)Z 9X %ZMZ %Z F_ )^GSG^ NfIRHe @g -e ;X.Y GZ6Z CY9" "Z 7ZNY ?[ %[/R *X@X $TBY BX;X=X6[.] /Y GY HX 7X +Z7Z 0Z 3\\ 0[ (Z L[ DZ4" "Z 9[ 3Z2[ &Z >i i 2W<Z?]HZ.Y'Z!Z/\\ L\\&S'Z,] JZ MZ *\\(Z'Z(Z :Z \"Z 4Z7] AZ 2Y JY(Y3e$\\,\\ KZ )\\-" "\\ Z.Z \"[ 7Y 7[/[ =ZNZ DZNX4XNY![6[ 4Z 7[ AX AX MY NY4\\ F\\4Z F[ &Z5] H[ @Y 2Z6] GY1Y 5Y NX 0X?[ +" "Y FY3Y2Y+Y1Y HZ4Z G\\4Z JZ5\\ ;Y 6Y 8Y -Y5\\ ;YKY =XNX=WNY E[B[ 3YNY 4[ BY X Y N_=_ LZ:_ CZ2Y FX;Y >Z4" "Z EY #Y1Y 9XNZ 7Y6Z GZ4[$Z=]=['ZDYDZ FY9Y HZBXBZ K]5Z J[5[ 2Y 2Z7Y L[(Z H[ #Z '\\5[ F~ LZ(Z :Z :\\-\\ KW :X :" "V >r >V/V @s #Z 2[CU -Z +[MeL[ 5Z X G\\ :W!V 3W@W 7V!W AZ4[ 1WEW LW@W 1W7s,X-" "Y JX8t$\\ 7Z'Z%Z'Z$Z'Y%Z'Z$Z'Y%Z'Z4Z1Z 6\\&S NZ !Z Z !Z >Z !Z !Z \"Z :Z,]\"Y3ZNY$\\,\\#\\,\\$\\,\\$\\-\\$\\," "\\ N\\4[ ]-\\![/Z LZ/[ N[/[ N[/[ 7Z 2Z #Y-Y NY4\\ HY5] IY4\\ GY4\\ HY4\\ HY4\\.Z5` 2Z $Z !Z !Z !Z =Y Y NX Y " "3Z4Z GX0X H[5[ GZ4Z GZ4Z H[5[ GZ4[ 6\\ 5_9[ HZ5[ GZ5[ FY5[ FY5\\ :YNZ :\\4Z ;YNY )YAXAZ\"Z+Z!Z*Y Y*Z\"Z+Z 8" "X $YMY %[ F^ '\\FSF\\ LcGRGc >f ,c :X.Y FZ7Y BY8Y 7e >[ %[1S -Y 'X@X ;Q:TCZ CX:X=X" "5[.] /Y HY HX NZ GZ 'X +[8Z 0Z 4\\ 0[ 'Z M\\ CZ6[ 9Z 2[3[ '[ 0Y Y ?f f BX DW=\\C_J[.Z&Z\"Z0\\ " "J\\(T'Z._ JZ MZ *])Z'Z(Z :Z \"Z 4Z6] BZ 2Y JY(Y3e#\\.\\ JZ )]/\\ NZ.[ NQ'[ 6Y 6[0[ =ZNZ CYNX4XNY!Z4[ 5Z 8[ @X" " AX MY NY5] F]6Z DZ &Z5] G[ AY 2[8^ GY1Y 5Y NX 0X>[ ,Y FY3Y2Y+Y1Y H[6[ G]6Z IZ5\\ ;Y 6Y 8Y -Z6\\ ;Z" "MZ =b=b EZ@Z 3d 5[ AY X Y L[:\\ IZ;` D[4Z FX<Z >Z5[ EY #Y1Y 9c 7Z5Y GZ5\\$[>^>['[EYE[ FY9Y HZBXCZ J]5Z " "IZ5Z 1Y 1Y8Z LZ&Z J[ \"Z &\\8] E| KZ(Z :Z :]/] JU 9X 9T <p <T-T >q \"Z 1ZCU -Z ,[JaI[ 6Z X F\\ :W#V 1" "V?V 7W#W @[5[ 1WEW LV?V 1X7s,W-Y JX7t%\\ 6Z&Z&Z'Z%Z&Z&Z'Z%Z&Z&Z&Y4Y0Z 5\\(T NZ !Z Z " "!Z >Z !Z !Z \"Z :Z.^!Y3e#\\.\\!\\.\\#].\\#]/]#\\.\\ N\\2[ ]/]![0[ L[0[ M[0[ N\\1[ 6Z 2Z #Y-Y NY5] HY5] IZ6] GY" "5] HY5] HY5]-Y5a 3[ %[ \"[ \"[ \"[ >Y Y NX Y 3Z5[ GX0X GZ5Z F[6[ G[6[ GZ5Z F[5Z 5\\ 4^9Z FY6\\ FY6\\ FY6\\ " "FY6] 9c 9]6Z :d )[CXBZ Z-Z NZ-[ [-Z Z-Z 7X $YNZ %Z D] $VCSDW G`FSG` ;d +c :X.Y F[9Z CZ8Y 6d =\\ " " '\\3T -Z (W?X ;S<TDZ BW8W=W4\\1` 0Y HY HX NZ GZ 'X *Z9Z /Z 5\\ 0\\ 'Z N\\ B[8[ 8Z" " 2\\5[ '[ /Z \"[ >d c @Z EW<_Ks-Z&Z\"Z1] J^,V'Z/_ IZ MZ )]*Z'Z(Z :Z \"Z 4Z5] CZ 2Y JY(Y2d#]0\\ IZ (]1] NZ-" "Z NS*\\ 6Y 6[1[ <e Bc4c\"[3Z 5Z 9\\ @X AX MY NZ6] F^8[ D[ &Z7^ G[ AY 1[:_ GY1Y 5Y NX 0X=[ -Y FY3Y2Y" "+Y1Y G[7Z F]7[ HZ7] ;Y 6Y 7Y .Z7] :YMY <a<a EZ>Z 4c 5[ @Y X Y HS3V FZ<a D\\5Z FX<Y =[7[ DZ $Y1Y 9c 7Y4" "Z H[6\\#Z?WNV>Z%ZEYF[ EY9Y GZCXD[ J^7Z H[7[ 1Y 1Z:Z KZ&Z K[ !Z %];] Bx IZ(Z :Z 9]1] HS 8X 8R :n :R+R <o !Z " "1[DU -Z -[F\\F[ 7Z X E\\ :W&W /U>U 6W%W ?[6\\ 1WEW LU>U 0W6s-X.X HW6t&\\ 5Z&Z'Z" "%Z&Z&Z'Z%Z&Z&Z&Z&Z6Z0Z 4],V NZ !Z Z !Z >Z !Z !Z \"Z :Z0`!Y2d\"\\0]!]0\\!]0\\!]1]!]1] \\0[ ]1] N[2\\ L\\2[ L\\" "2[ L[1[ 6Z 2Z #Y.Y MZ7^ HY6^ HY6] GZ6] HZ7^ HZ7^-Y6c 3[ %[ \"[ \"[ \"[ ?Y Y NX Y 3[7[ FX0X G[7[ E[7[ FZ7[ F" "[7[ E[7[ 5\\ 4]9[ FZ8] FZ8] FZ8] FZ7] 9c 9]7[ 9b '[DXD[ N[/Z LZ/[ M[0[ N[/Z 6X $d %Z C\\ ?S 2\\ETD" "\\ 9b )a 9X.Y E[<[ BY7Z 7c ;\\ '\\5U -Z (W?W :U>TE[ CX8X?X3\\3b 1Y IY GX NZ GZ (" "X )[;[ /Z 5[ %Q-\\ &Z BQ/] AZ9\\ 9Z 0[6\\ (\\ /Z \"[ ;a ` =Z EX<nNd,Z$Y\"Z2] H^.W'Z2a HZ MZ (^,Z'Z(Z :Z \"" "Z 4Z4] DZ 2Y JY(Y2d\"]3^ IZ ']3] MZ-[ U-] 6Y 5\\4\\ ;d Bb2b#[2[ 6Z :\\ ?X @X NY MZ8^ F^8Z B[ '[9_ F[," "P 7Y 1\\<` GY1Y 5Y NX 0X<[ .Y FY3Y2Y+Y1Y G[8[ F^9[ G[9^ ;Y *Q/Z 7Y -Z9^ :YMY <a;` F[>[ 4b 6[ ?Y X Y " "FZ=b E]7Z EX=Z <[9\\ D[ %Y1Y 8a 6Y3Y H\\8]#[@WNW@[%[FYG\\ EY9Y G[DXD[ J_9[ G[9[ /Y 1Z;Z LZ%Z L\\ !Z $]=\\ >t GZ" "(Z :Z 8]3] FQ 7X 7P 8l 8P)P :m Z 0[EU -Z .[?P?[ 8Z X D[ 9W(W -T<S 5X)X >\\8] 1WEW " " LS<T 0W5s-W.X HX6t'\\ 5Z$Y'Z%Z'[%Z(Z%Z&Z%Z(Z%Z6Z0Z 4^.W NZ !Z Z !Z >Z !Z !Z \"Z :Z2a Y2d\"^3] N]3^ ]3" "] N]3] N]3] \\.[!^3] M\\4\\ J\\4\\ K\\4\\ L\\4\\ 5Z 2Z #Y.Y MZ8_ HZ8_ HZ8^ FZ8^ HZ8_ HZ8_-Z8e-Q)\\ &\\-Q G\\-Q " "G\\-Q G\\-Q 5Y Y NX Y 2[9\\ FX0X F[9[ D\\9[ E[8[ E[9[ D\\9[ 4\\ 3[9[ EZ9^ FZ9^ FZ9^ F[9^ 9b 8^9[ 8b &[2[" " L\\3\\ K[2[ K[2[ L\\3\\ 6X #c &Z B\\ ?S /UATAT 4a '_ 8X.Y E\\>\\ BY6Y 7c :] (\\7V " "-Z )X@X :W@TF[ BW7X?X3]6e 1X IY GX NZ GZ (X ([=[ .Z 6[ $S1^ &Z BS3^ @\\<\\ 8Z 0]9] FR6] .Z \"[ 8^ " " ^ ;Z DW;lMc+Z$Z#Z4_ G_2Y'Z5c GZ MZ '^/\\'Z(Z :Z \"Z 4Z3] EZ 2Y JY(Y1c!^6^ HZ '^6^ LZ,Z X1] 5Y 5]6\\ :c Ab2a" "\"Z0[ 7Z ;\\ >X @X NY MZ:` F_:[ B\\3P D[;` E\\1S 7Y 0\\>a GY1Y 5Y NX 0X;\\ 0Y FY3Y2Y+Y1Y F[:[ E_;\\ " "F[;_ ;Y *S1Y 6Z .[;_ :e ;`;` G[<[ 5a 6[ >Y X Y F[?YNY F_:[ DX?Z :[;\\ B[ &Y1Y 8a 7Z3Y H]:^#\\BXNWA[#[" "GYH\\ DY9Y F\\FXF\\ I`;[ F\\;\\ /Z 2[=Z KZ$Z N\\ Z #^A] :n DZ(Z :Z 7]5] +X Mj (k NZ 0\\FUBP ;Z /[,[ " "9Z X CZ 8X+W *R;R 4X+X =]:^ 1WEW LR;R /X5s.W.X GW5t(\\ 4Z$Z(Z%Z'Z$Z(Z$Y'Z$Z(Z$Z" "8Z/Z 3_2Y NZ !Z Z !Z >Z !Z !Z \"Z :Z5c NY1c!^6^ L^6^ M^6^ M]5] M^6^ \\,[#a7^ K\\6] I\\6\\ J]6\\ J\\6] 5Z 2Z #" "Y/Z LZ:` H[:` H[:_ FZ:` GZ:` GZ:`-[:YN\\0S(\\4Q C\\0S F\\0S F\\0S F\\0S 5Y Y NX Y 1[:[ EX0X F\\;\\ C\\;[ C[:" "[ D\\;\\ C\\;\\ 4\\ 3[:\\ DZ;_ EZ;_ EZ;_ EZ;` 8a 8_;\\ 7a %\\6\\ J\\5\\ I\\6\\ I\\6\\ J\\5\\ 5X #c 'Z " "@[ @T JT _ %] 7X.Y D^D^ BZ6Y 6b 9_ *];X -Z )X@X :ZCTH] CX7YAX1^:h 2Y JY GX NZ" " GZ (X (\\?\\ .Z 7\\ $W7_ %Z BV8` ?\\>] 9[ /];] ET9] -Z \"[ 5[ [ 8Z DX;jLb*Z$Z#Z7a E`7\\'Z9f FZ MZ &`4^" "'Z(Z :Z \"Z 4Z2] FZ 2Y JY(Y1c _:_ GZ &_9^ KZ,[![6^ 4Y 4]9] 8b @a2a#[/Z 7Z ;[ =X @X NY M[<a Fa>\\ @]7R" " D\\=a E]4U 7Y /]Bc GY1Y 5Y NX 0X:\\ 1Y FY3Y2Y+Y1Y E\\>] E`=\\ E\\=` ;Y *U5[ 6[ /\\>a 9c :_:` GZ:Z 4` 6[ >Y " "X Y E[AYMZ G`<[ CX@Z 9\\=\\ A\\3Q EY1Y 7` 7Y2Z I^<_\"[BWMXC\\#]IYI\\ CY9Y F]GXG] Ia=\\ E\\=\\ .[ 2[?Z J" "Z$Z N[ NZ \"^C^ 7g @Z(Z :Z 7_9_ +X Lh &i MZ /]HUDR ;Z .Y*Y 8Z X BZ 8Y/X (Q:Q 2X/Y " " <^<` 2WEW LQ:Q .W MV(X/X GX NW\"\\ 3Z$Z)Z#Z(Z$Z)Z#Z(Z$Z)Z#Z8Z/Z 2`7\\ NZ !Z Z !Z >Z !Z !Z \"Z :" "Z9f MY0b _:_ J_:_ K_:_ L_9_ L_9^ N[*[$c:^ J^:^ H^:^ I^:] H]9] 4Z 2Z #YIP7[ L[<a G[<a G[=a F[<a G[<a G[<a,[=ZL\\" "4V'\\7S B\\4V E]5V E]5V E]5V 5Y Y NX Y 1\\=\\ DX0X E\\=\\ A\\=\\ C]>] C\\=\\ A\\=\\ 3\\ 2\\=\\ C[=` E[=` E[=" "` E[=a 8a 8`=\\ 6` #]:] H]9] G]:] G]:] H]9] 4W !a 'Z ?Z ?U KT N] $] 7X.Y Cv AZ6Z 7a 7a " " -_?Z -Z )W?X :^GTK_ CX5XAX0_>k 3Y JX FX NZ GZ )Y ']C] ?} I~S IZ=b %Z BZ>a =]B^ 8Z ._?^ DX" "@_ ,Z \"[ 3Y X 5Z CW:gJ`)Z\"Z$~T Cb=_'~W E~S FZ %b:a'Z(Z :Z \"Z 4Z1] G~Q)Y JY(Y0b N`>` FZ %a?` JZ+Z!^<a 4Y " "3_>_ 8b @a2a$[.[ 8Z <~` AX ?X Y L\\@c Fb@] ?^<U C]Ac D^9X 7Y /aI[NY GY1Y 5Y NX 0X9\\ 2Y FY3Y2Y+Y1Y E]" "@] Db@\\ C]Ab ;Y *X9\\ 5] 1\\Ac 9c :_:_ GZ9[ 5` 7[ =Y X Y E]DZM[ Hb@] BXB[ 8]A^ @]8T EY1Y 7_ 7Z1Y I`@" "b#]EXLXE\\!]JYK^ CY9Y E_JXJ_ HcA] C]A] ,] 4[B\\ K~c!~T FZ 3oDo A[ :Z(Z :Z 6a?a *X Kf $g LZ .^JUGU H~U" " JW(W 7Z X AY 7Z3Y &P9P 1Y3Y <~d 3`@b 2WEW LP9P .X MV(W/X GX MW#\\ 3Z\"Z*Z#Z)Z\"Z*" "Z#Z)[#Z*Z#Z9Z.~T+b=_ N~T J~T I~S I~S 7Z !Z !Z \"Z :~V KY0b N`>` H`>` I`>` Ja?a Ja?` LY(Y$f?` H_>_ F_>_ G_>_ H_>" "_ 3Z 2Z #YIS;[ K\\?c G\\?c G\\?b E\\@c F\\@c G\\?c,\\?[L^9Y'^<V B_:Y E_:Y E_:Y D^:Y 5Y Y NX Y 0]@] DX0X D]A]" " @]@] A]@] A]A^ A]@] 2\\ 2]@] B]Ab E]Ab D\\Ab D\\Ac 7_ 7b@\\ 5` \"_@_ F_?_ E_@_ E_@_ F_?_ 3W !a 'Z ?Z " " ?U KT M\\ #[ 6X.Y Bu AY5Z 7a 6f 2aE] -Z )W?W 9~ BW4YCY/bFp 3X KY FX NZ GZ " ")X %^G^ >} I~S I~ $Z B| ;^F_ 7Z -aEa Dv +Z \"[ 0V U 2Z CX9dI^'Z\"Z$~S AfGd'~U C~S FZ $gGg&Z(Z :Z \"Z 4Z0] H" "~Q)Y JY(Y0b McGd EZ $dGc IZ+[\"cEd 3Y 3cGc 7a ?`1a$Z,[ 9Z =~a AX ?X Y L^DZNY FYNZF_ =`CY B^EZNY CaB] 7" "Y .qMY GY1Y 5Y NX 0X8\\ 3Y FY3Y2Y+Y1Y D_F_ CYNYE_ B^EZNX ;Y *]A^ 4k >^G[NY 8a 9_9^ H[8[ 5^ 6~P 2Y X Y " " D^H[La NfH` AYD[ 6^E_ ?`?X EY1Y 7_ 7Y0Y IcFk(]HZLZI^ `Nk BY9Z E~Q GYNZE^ B_E_ ,e ;]G] J~c!~T FZ 3oDo @Z :Z(Z :" "Z 5dGd )X Jd \"e KZ -`MUKY H~U IU&U 6Z X AY 5Z7Z LZ7Z ;~d 3cFk 8WEW " " BW LV)X0X FW LW$\\ 2Z\"Z+[#Z)Z\"Z*Z\"Z*Z\"Z*Z\"Z:Z.~T*fGd N~T J~T I~S I~S 7Z !Z !Z \"Z :~U JY/a MdGc FcGd GcGd" " HdGd HdGc JW&W$kGc FbFb DbFb FcFb FcGc 3Z 2Z #YIWB] I^DZNY F]D[NY F]D[NX E^DZNY F^DZNY F^E[NY+]D]J`@]&`BY AaA]" " DaA] DaA] DaA] 5Y Y NX Y /_F_ CX0X D_E_ ?_F_ ?_F_ @_E_ ?_F_ 7aF_ @^FZMX D^FZMX D_GZMX D_G[NY 7_ 7YNYE_ 4^" " dLd CdMd BdLd CdLd DeMd 2X !` %X =Y ?U LV MZ !Y 5X.Y As AZ4Y 6` 5~] )x -Z " "*X@X 9} BX3YFZ-{L] 4Y LY FX NZ GZ )X $t >} I~S I} #Z B{ :v 7[ ,{ Cu *Z \"[ -S S 0Z BW8aG[%[\"Z$~R" " ?~S'~T B~S FZ #~V%Z(Z :Z \"Z 4Z/] I~Q)Y JY(Y/a L~ DZ #~ HZ*Z\"~R 2Y 2} 5` ?`0_$[+Z 9Z =~a AX ?X Y KsN" "Y FYNr ;u AqMY B{ 7Y -oLY GY1Y 5Y NX 0X7\\ 4Y FY3Y2Y+Y1Y Cv BYNr ArMX ;Y *y 2j >qMY 8a 8^9^ I[6Z 5^ 6~P 2Y X " " Y CpK` N} ?YF[ 5w =x EY1Y 6] 7Z0Z J~Y(nJm M{ AY9\\ F~ FYMq @w *d ;r J~d!~T FZ 3oDo @Z :Z(Z :Z 4~ 'X " " Ib c JZ ,u H~U HS$S 5Z X AY 4\\>\\ I]>\\ :~d 3~Y 8WEW CW KV)W0X FX LW" "$[ 2[\"Z+Z!Z*Z\"Z+Z!Z*Z!Z,Z!Z:Z.~T)~S N~T J~T I~S I~S 7Z !Z !Z \"Z :~T IY/a L~ D~ E~ F~ E~ HU$U$~X D| B| D} D} " "2Z 2Z #YIr HrMY FsMY FsMX DsNY ErMY FsMY+uH|%v @| C| C| C| 5Y Y NX Y .v BX0X Cw =w >v >w =w 8{ ?qMX CqMX C" "qMX CqMY 6] 6YNr 3^ My Ay @y @z Ay 1X _ $V <X ?V LV LX NW 4X.Y @p ?Z4Z 7_ 2~[ " " (v ,Z *X@X 9| AW1[K[+yJ] 5Y LX EX NZ GZ )X #r =} I~S I| \"Z Bz 8t 6Z *y Bt )Z \"[ *P P -Z BX" "6[DX\"Z Z%~Q <~P&~R @~S FZ \"~T$Z(Z :Z \"Z 4Z.] J~Q)Y JY(Y/a K| CZ !{ GZ*[#~Q 1Y 1{ 4_ =_0_%[*[ :Z =~a AX >X !" "Y JqMY FYMp 9t ApLY Az 7Y ,mKY GY1Y 5Y NX 0X6\\ 5Y FY3Y2Y+Y1Y Bt AYMp ?pLX ;Y *x 1j =oLY 8a 8]8^ IZ4Z 6" "] 5~P 2Y X Y CoI_ N} ?[K] 3u ;w EY1Y 6] 7Y.Y JvM_'mJm Ly @Y9b K| EYLp ?u (c :p I~e\"~T FZ 3oDo @Z :Z(Z" " :Z 2{ &X H` Ma IZ +t H~U GQ\"Q 4Z X AY 2aLb FaKa 8~d 3YNlN_ 8WEW " "DX KV*W0o-W KW%[ 1Z Z,Z!Z+Z Z,Z!Z+Z Z,Z!Z;Z-~T'~P M~T J~T I~S I~S 7Z !Z !Z \"Z :~R GY.` K| B| C{ B{ B{ FS\"S$YM" "{ Bz @z B{ B{ 1Z 2Z #YIq GqLY EqLY EqLX CqMY ErMY EqLY*sF{$u ?{ B{ B{ B{ 5Y Y NX Y -t AX0X Bu ;u <t <u ;u " "8{ >pLX CpLX CpLX BoLY 6] 6YMp 1] Lv >w =v =v >w 0X _ #T ;X ?W MV LW LV 4X.Y ?n >Y3Z 7_ 1~Z " " 't +Z *W?X 8y @X1j)vG] 5X MY EX NZ GZ *X !p <} I~S Iz Z By 6r 5Z )w As (Z \"[ " " 5Z AX HZ Z%~ 9|$~P >~S FZ ~P\"Z(Z :Z \"Z 4Z-] K~Q)Y JY(Y.` Jy AZ x EZ)Z#~P 0Y /x 3_ =_0_%Z([ ;Z =~a AX " ">X !Y JpLY FYLn 7s @nKY @y 7Y +kJY GY1Y 5Y NX 0X5\\ 6Y FY3Y2Y+Y1Y Ar @YLn =nKX ;Y *w /i <mKY 7_ 7]8] IZ" "3[ 6\\ 5~P 2Y X Y BmH_ N{ <k 0r 9v EY1Y 6] 8Z.Z KYNkM_&kHk Jw ?Y8a Jy CYKn =s &b 9n H~e\"~T FZ 3oDo @Z" " :Z(Z :Z 1y %X G^ K_ HZ *s H~U *Z X AY 1t Bs 6~d 3YNkM_ 8WEW DW " "JV+X0o.X KW%Z 0Z Z-Z NZ,Z Z-[ Z,Z Z-[ Z<Z-~T&| K~T J~T I~S I~S 7Z !Z !Z \"Z :~P EY.` Iy @y @y @y @y DQ Q$YKy @x" " >x ?x @y 0Z 2Z #YIp EoKY DoKY DoKX BoLY DpLY DoKY)qCy#t =y @y @y @y 5Y Y NX Y ,r @X0X As 9s :r :s 9s 7z <" "nKX BnKX BnKX BnKY 6] 6YLn 0\\ Jt ;s :t ;t ;s .X N] !R 9V >W NX LU KU 3X.Y >l =Y2Y 7_ /~X " " %p )Z *W?W 4u @X/i(tE] 6Y NX DX NZ GZ *X m :} I~S Iy NZ Bw 2o 5Z 'u @r 'Z \"Z " " 4Z AY J[ Z%} 6x\"} <~S FZ N| Z(Z :Z \"Z 4Z,] L~Q)Y JY(Y.` Hv @Z Mu DZ)[$~ /Y .u 0^ =^/_&['Z ;Z =~a AX >X" " !Y InKY FYKl 5r ?lJY >w 7Y )hIY GY1Y 5Y NX 0X4\\ 7Y FY3Y2Y+Y1Y @p ?YKl ;lJX ;Y *v -h ;kJY 7_ 7]7\\ J[2" "[ 7\\ 5~P 2Y X Y AkE] Nz :i .p 7u EY1Y 5[ 7Y,Y KYMiL_%iGj Hu >Y8a Hv BYJl :p $a 7k H~f\"~T FZ 3oDo @Z " ":Z(Z :Z /u #X F\\ I] GZ )r H~U *Z X AY /p >o 4~d 3YMiK^ 8WEW EX " "JV+W/o/X JW&Z 0[ Z-Z NZ-[ [.Z NZ,Z NZ.Z NZ=Z,~T$x I~T J~T I~S I~S 7Z !Z !Z \"Z :| BY-_ Hv <v =v =u =v BXHu =v" " <v =u <u .Z 2Z #YIo CmJY CmJY CmJX BnKY CmJY CmJY(oAx!r <x ?x ?x ?x 5Y Y NX Y +p ?X0X ?p 7p 7p 7p 7p 6WNp" " 9lJX AlJX AlJX AlJY 5[ 5YKl /\\ Hp 8q 7p 7p 8q -X N] NP 9V ?Y X KS IS 2X.Y <h <Z2Y 6^ -~V " " $n (Z +X@X 1o =W-f$pB] 6X NX DX Z FZ *X Nk 9} I~S Iw LZ Bv 0m 4Z %q >p %Z \"Z " " 4Z @X JZ MZ&{ 3u z 9~S FZ Lx MZ(Z :Z \"Z 4Z+] M~Q)Y JY(Y-_ Fr >Z Lr BZ(Z!y -Y -s /] <^.]&[&[ <Z =~a AX " " =X \"Y GjIY FYJj 2p =iIY =u 6Y 'dGY GY1Y 5Y NX 0X3\\ 8Y FY3Y2Y+Y1Y >m >YJj 8iIX ;Y *u *f :iIY 7_ 6\\7" "\\ K[0Z 6Z 4~P 2Y X Y ?hC\\ NYMm 8f +m 3s EY1Y 5[ 8Z,Y KYLgJ^$gEh Fs =Y8a Fr @YIi 7m !` 6i G~g#~T FZ 3o" "Do @Z :Z(Z :Z .s \"X EZ G[ FZ 'p H~U *Z X AY ,k :k 2~d 3YLgJ^ 8WEW " " EW IV,X/o/W IW&Z 0Z MZ/[ NZ-Z MZ.Z N[.Z MZ.Z MZ>Z,~T\"t G~T J~T I~S I~S 7Z !Z !Z \"Z :y ?Y-_ Fr 8r 9r :s :r " " AXEr :r 8r :s :s -Z 2Z #YIn AkIY BkIY BkIX @jIY BkIY BkIY'l=t Mq :t ;t ;t ;t 3Y Y NX Y *m =X0X >m 3m 5n 5m" " 3m 6XLm 7iHX @iHX @jIX @jIY 5[ 5YJj -Z El 3k 2l 3l 4l *X N\\ 5U ?Y Y KR HQ 1X.Y 9b 9Y1Z 7" "] )~S \"j &Z +X@X -h ;X+c!l?\\ 6X Y DX Z FZ +X Kh 8} I~S Fr JZ As ,i 3[ $n ;m " "#Z \"Y 3Z ?X KZ MZ&x -p Mu 4~S FZ Js JZ(Z :Z \"Z 4Z*] N~Q)Y JY(Y-_ Dn <Z Jn @Z([ Nt +Y +o ,\\ ;].]&Z$" "[ =Z =~a AX =X \"Y FhHY FYHf .m ;gHY ;p 3Y %`EY GY1Y 5Y NX 0X2\\ 9Y FY3Y2Y+Y1Y =j <YHf 5gHX ;Y (q &d 9" "fGY 6] 5[6\\ KZ.Z 7Z 4~P 2Y X Y >gB[ NYLj 5d (j 0q EY1Y 5Z 7Y+Z LYKdG]\"dBd Bo ;Y7` Dn >YHg 4i L^ 4e " "E~g#~T FZ 3oDo @Z :Z(Z :Z ,n NX DX EY EZ %m G~U *Z X BZ )e 4e /~d 3YKeH] 8" "WEW FW HV,W.o0X IW'Z /Z MZ/Z LZ.Z MZ/[ MZ.Z MZ/[ MZ>Y+~T p E~T J~T I~S I~S 7Z !Z !Z \"Z :u ;Y,^ Dn 4" "n 5n 6o 6n @XBm 5n 4n 6o 6o +Z 2Z #YIl =gGY AhGY AhGX ?hHY @hHY @gGY%i:o Hm 7p 6o 6p 7p 1Y Y NX Y (i ;X0X " "<i 0j 1j 1j 1j 5XIi 3fGX >fGX >fGX >fGY 4Y 4YHf +Z Bg /g .g -g /g (X M[ 5T ?Z !Z JP 'X.Y 5" "[ 6Y0Y 7] &~P Ne $Z +W?X '] 6W)a Mh<\\ 7Y !X CX Y EZ +X Id 6} I~S Cm HZ =l 'e " "1Z i 6h !Z #Z 3Z ?Y M[ M['s &k Jo .~S FZ Gm GZ(Z :Z \"Z 4Z)] ~Q)Y JY(Y,^ Bi 9Z Gl AZ'Z Jm (Y (i )\\ " ";].]'[#Z =Z =~a AX =X \"Y DdFY FYFb *h 6cFY 8j 0Y \"YAY GY1Y 5Y NX 0X1\\ :Y FY3Y2Y+Y1Y ;f :YFb 1cFX ;Y" " $k ` 7cFY 6] 5[5Z KZ-[ 8Y 3~P 2Y X Y ;b=X NYJe 0` $e +l BY1Y 4Y 7Y*Y LYIaE[ b@a >k 9Y6_ Ah ;YFc 0e " "FZ 2a D~i$~T FZ 3oDo @Z :Z(Z :Z )i LX CV CW DZ #h D~U *Z X -R9Z #[ *[ *~d 3" "YIaE\\ 8WEW GX HV-W-o0W HW'Z 0Z L[0Z LZ/[ LZ0Z LZ/[ LZ0Z LZ?Z+~T Lj B~T J~T I~S I~S 7Z !Z !Z \"Z :o " "5Y,^ Ai /h 0i 0i 0i >W?i 1j 0j 1j 1i (Z 2Z #YGh 9cEY ?dEY ?dEX =dFY >dFY >cEY#d5j Ch 1j 1j 1j 1j -Y Y NX Y" " &e 9X0X :e ,f -f -e ,f 4XFe 0cEX <bEX <bEX <bEY 4Y 4YFb )Z ?` (a '` '` (a %X 'T " " L{ K_ 0T 4X&[ Ga AX \"Y :Y EX G_ Ie #e !_ c /a EY " " EY Hc ?e FZ +b Ni )d Nc (X =Y #Y A^ J^ %a /] N" "c ;Y NX *` 7YD^ ,]CX 1c ^ /Y DY X Y 8] 1YF] *\\ N` %c DY 4Y *YG\\A" "X J\\;] 9e A^ =` 7YC] *_ G[ >a NU CZ N` 9X -T<[ " " LYG]BX 5WEW %U HW NX MX GZ (d +b (b )b )a )b 9V;a " ")c *c *c *c =a 4_ &^ %^ $^ &_ &_ :_/c <b +c *c *c *c 3_ K_ &` '` '_ &` 1WB_ *] $] $^ %^ NZ " "4YD^ 'Y 6Q HQ GQ FQ HQ LX &S DQ )T 4W Q :Q" " 9Y #X :Y EX ?Q 8R ?R @Q @R MQ =Y DY @R -Q <Z " " #R >RM] !R <R X <X #Y ;Q <Q GR !Q @Q 2Y MX #R 0Y=Q Q=X 'Q " " @Q *Z DY X Y ;Y <P AQ CQ ;Y 4Y *YAQ8P @Q0Q -Y 8X 7Y 3Y=Q LQ " " JQ 4Z IU 3X -W@[ KYAQ8P 1WEW $U IV MW LW FZ " " V KQ GR HQ GQ GQ 0T2Q HR GR HR HQ ,Q %Q GP GQ FQ GQ " "GP *P NQ ,V MQ GR HR HR #Q =Q FQ HR HQ FQ *V:Q LQ GQ GQ GQ GY 3Y=Q !Y " " 9X MT +X #X :Y EX " " 5X BZ 7Y 7] 8X <X #Y " " HY MX 0Y 'X MY CY X Y ;Y 8Y 4Y *Y 1Y E" "X 3Y CZ IU 3X -\\I_ KY 8WEW $V" " %Z NU 0R #V " " )T <Z 3Y =Y 8X " " MT +X $X 9X DX 6Y AZ NR " " =Z 6\\ 8X <X #Y HY MX 0Y '" "X NZ CY X X :Y 8Y 4Y *Y 1Y EX 3Y " " CZ IU 3X -q JY 8WEW #V &Z NV " " 0V (R " " <Y 2Y =Y 8X MT *X " "%X 9X EY 6X @[!T >Z 5\\ " " 9X ;X $Y HY NY 0Y 'X NY BY X !Y " ":Y 8Y 4Y *Y 1Y EX 3Y CZ IU 3X -p " " IY 8WEW #V &Z MV " " 0U 'P ;Y 2Y >Z 8X " " MT *X &X 9X DX " " 5X ?\\%W ?Z 4\\ :X ;X $Y " " IZ NY 0Y 'X NY BZ !X !Y :Y 8Y 4Y *Y 1Y EX 3Y " " CZ IU 3X -o HY 8WEW \"V " " 'Z LU 0V " " CZ 2Y >Y 7X " " MT )X 'X 9X DX 5W <\\(X ?" "Z 3\\ ;Y <X $Y IY MY 0Y 'X " " Z AY !X !Y :Y 8Y 4Y *Y 1Y EX 3Y CZ I" "U 3X -n GY 8WEW \"V '[3Q <V " " 0V DY 1Y " "?Z 7X MT )X (X 8W " " CX 6X ;],[ AZ 1\\ <e" " GX 2f JZ MY 0Y 'X Y @Z \"X \"Z :Y 8" "Y 4Y *Y 1Y EX 3Y CZ IU 3X ,k " " EY 8WEW !V 'Z4R <V " " 0V EZ 1Y ?Y ARGX " " MT (X )X 8W DX 5W " " 9^1^ AZ 0\\ =e GX 2f KZ LY" " 0Y 'X !Z @[ #X #Z 9Y 8Y 4Y *Y 1Y EX 3Y " " CZ IU 3X )f CY 8WEW !V '[7T " " ;V 1V " " EY 0Y ?Y FWGW " " LT 'W *X 8W CX 5W 8`7` A[ " " /\\ >e GX 2f KZ LY 0Y 'X !Y >" "\\ %X &] 9Y 8Y 4Y *Y 1Y EX 3Y CZ IU 3" "X $^ @Y 8WEW !V '\\:V ;V " " 1W GZ 0Y @Z " " FWHX LT 'X +W 7W " " V 5b?c A[ -\\ ?e !f " " <P2\\ MY /Y 'X \"Z >f /X 0g 9Y 8Y 4Y *Y " " 1Y EX 3Y CZ IU 3X 5Y " " NV &\\=X ;V " "1W GY /Y AZ EWHX " " LT &W ,X 7V V 3~T " " A] ,\\ @e !f <R5\\ LY /Y " "'X #Z =f /X 0f 8Y 8Y 4Y *Y 1Y EX 3Y " " CZ IU 3X 5Y NW '^B[ <W " " 1W " " HZ /Y AZ DWIX LT &X -" "W 6U NV 1~P B_ *\\ " " Ae !f <U:] LZ /Y 'X #Z <e /X 0e 7Y " " 8Y 4Y *Y 1Y EX 3Y CZ IU 3X " " 5Y X &aJ_ <W " " 2X IZ .Y BZ CWJY " " LT %X /X " " 7| Hf )\\ Be !f <X?_ N[ " " .Y 'X %[ :d /X 0e 7Y 8Y 4Y *Y 1Y EX 3Y " " CZ IU 3X 5Y -PDX %v " " JQDX ?QEY " " J[ .Y D\\ CXLY " " KT 7x Fe " " -_Me %b .Y 'X /e 9c /X 0c " "5Y 8Y 4Y *Y 1Y EX 3Y CZ IU 3X " " 5Y -d $u Je " " ?d $d -Y Ne Ad " " KT " " 5s Cd ,v %b -" "Y 'X 0e 6a /X 0b 4Y 8Y 4Y *Y 1Y EX 3Y " " CZ IU 3X 5Y -d #t Jd " " >d " " %e -Y Nd @c " " (m @c " " +u $b -Y 'X 0d 2^ /X 0_ 1Y 8Y 4Y *Y " " 1Y EX 3Y CZ IT 2X 5Y " "-c !q Hd >c " " $d ,Y Nd ?b " " %g =" "b *t #a ,Y 'X 0d " " ,X /X 0Y +Y 8Y 4Y *Y 1Y EX 3Y CZ '" "X 5Y -c Nm Fc " " =c $c +Y Nc " " >a " " M\\ 8a \"~Y 1" "r !` +Y 'X 0c 1X 1Y 8Y 4Y *Y 1Y EX 3Y " " CZ &W 5Y -b Lj " " Db <b " " #b *Y Nb <_ " " (_ " " ~Y 1q _ *Y 'X 0b 0X 1Y " " 8Y 4Y *Y 1Y EX 3Y CZ " " 3Y -` He A` " " :` !a )Y Na :] " " " " '] M~Y .l M] (Y 'X " " 0` .X 1Y 8Y 4Y *Y 1Y EX 3Y " " KY *Z B^ 9Z " " 5Z M` (Y N` " " 8Z " " %X H~Y " " *d I[ &Y 'X 0^ ,X 1Y 8Y 4Y *Y 1Y EX 3Y" " KY " " " " H^ &Y N] 3V " " " " B~Y #X CU !X &X /Y (X 1" "Y 7X 4X )X 0Y EX 2X " " KY " " HZ \"X MY " " " " J~Y " " 9X " " " " " " " " 3~Y " " 9X " " " " " " " " 3~Y " " 9X " " " " " " '" }; // Define a 40x38 'danger' color logo (used by cimg::dialog()). static const unsigned char logo40x38[4576] = { 177,200,200,200,3,123,123,0,36,200,200,200,1,123,123,0,2,255,255,0,1,189,189,189,1,0,0,0,34,200,200,200, 1,123,123,0,4,255,255,0,1,189,189,189,1,0,0,0,1,123,123,123,32,200,200,200,1,123,123,0,5,255,255,0,1,0,0, 0,2,123,123,123,30,200,200,200,1,123,123,0,6,255,255,0,1,189,189,189,1,0,0,0,2,123,123,123,29,200,200,200, 1,123,123,0,7,255,255,0,1,0,0,0,2,123,123,123,28,200,200,200,1,123,123,0,8,255,255,0,1,189,189,189,1,0,0,0, 2,123,123,123,27,200,200,200,1,123,123,0,9,255,255,0,1,0,0,0,2,123,123,123,26,200,200,200,1,123,123,0,10,255, 255,0,1,189,189,189,1,0,0,0,2,123,123,123,25,200,200,200,1,123,123,0,3,255,255,0,1,189,189,189,3,0,0,0,1,189, 189,189,3,255,255,0,1,0,0,0,2,123,123,123,24,200,200,200,1,123,123,0,4,255,255,0,5,0,0,0,3,255,255,0,1,189, 189,189,1,0,0,0,2,123,123,123,23,200,200,200,1,123,123,0,4,255,255,0,5,0,0,0,4,255,255,0,1,0,0,0,2,123,123,123, 22,200,200,200,1,123,123,0,5,255,255,0,5,0,0,0,4,255,255,0,1,189,189,189,1,0,0,0,2,123,123,123,21,200,200,200, 1,123,123,0,5,255,255,0,5,0,0,0,5,255,255,0,1,0,0,0,2,123,123,123,20,200,200,200,1,123,123,0,6,255,255,0,5,0,0, 0,5,255,255,0,1,189,189,189,1,0,0,0,2,123,123,123,19,200,200,200,1,123,123,0,6,255,255,0,1,123,123,0,3,0,0,0,1, 123,123,0,6,255,255,0,1,0,0,0,2,123,123,123,18,200,200,200,1,123,123,0,7,255,255,0,1,189,189,189,3,0,0,0,1,189, 189,189,6,255,255,0,1,189,189,189,1,0,0,0,2,123,123,123,17,200,200,200,1,123,123,0,8,255,255,0,3,0,0,0,8,255,255, 0,1,0,0,0,2,123,123,123,16,200,200,200,1,123,123,0,9,255,255,0,1,123,123,0,1,0,0,0,1,123,123,0,8,255,255,0,1,189, 189,189,1,0,0,0,2,123,123,123,15,200,200,200,1,123,123,0,9,255,255,0,1,189,189,189,1,0,0,0,1,189,189,189,9,255, 255,0,1,0,0,0,2,123,123,123,14,200,200,200,1,123,123,0,11,255,255,0,1,0,0,0,10,255,255,0,1,189,189,189,1,0,0,0,2, 123,123,123,13,200,200,200,1,123,123,0,23,255,255,0,1,0,0,0,2,123,123,123,12,200,200,200,1,123,123,0,11,255,255,0, 1,189,189,189,2,0,0,0,1,189,189,189,9,255,255,0,1,189,189,189,1,0,0,0,2,123,123,123,11,200,200,200,1,123,123,0,11, 255,255,0,4,0,0,0,10,255,255,0,1,0,0,0,2,123,123,123,10,200,200,200,1,123,123,0,12,255,255,0,4,0,0,0,10,255,255,0, 1,189,189,189,1,0,0,0,2,123,123,123,9,200,200,200,1,123,123,0,12,255,255,0,1,189,189,189,2,0,0,0,1,189,189,189,11, 255,255,0,1,0,0,0,2,123,123,123,9,200,200,200,1,123,123,0,27,255,255,0,1,0,0,0,3,123,123,123,8,200,200,200,1,123, 123,0,26,255,255,0,1,189,189,189,1,0,0,0,3,123,123,123,9,200,200,200,1,123,123,0,24,255,255,0,1,189,189,189,1,0,0, 0,4,123,123,123,10,200,200,200,1,123,123,0,24,0,0,0,5,123,123,123,12,200,200,200,27,123,123,123,14,200,200,200,25, 123,123,123,86,200,200,200,91,49,124,118,124,71,32,124,95,49,56,114,52,82,121,0 }; //! Get/set default output stream for the \CImg library messages. /** \param file Desired output stream. Set to \c 0 to get the currently used output stream only. \return Currently used output stream. **/ inline std::FILE* output(std::FILE *file) { cimg::mutex(1); static std::FILE *res = cimg::_stderr(); if (file) res = file; cimg::mutex(1,0); return res; } // Return number of available CPU cores. inline unsigned int nb_cpus() { unsigned int res = 1; #if cimg_OS==2 SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); res = (unsigned int)sysinfo.dwNumberOfProcessors; #elif cimg_OS == 1 res = (unsigned int)sysconf(_SC_NPROCESSORS_ONLN); #endif return res?res:1U; } // Lock/unlock mutex for CImg multi-thread programming. inline int mutex(const unsigned int n, const int lock_mode) { switch (lock_mode) { case 0 : cimg::Mutex_attr().unlock(n); return 0; case 1 : cimg::Mutex_attr().lock(n); return 0; default : return cimg::Mutex_attr().trylock(n); } } //! Display a warning message on the default output stream. /** \param format C-string containing the format of the message, as with <tt>std::printf()</tt>. \note If configuration macro \c cimg_strict_warnings is set, this function throws a \c CImgWarningException instead. \warning As the first argument is a format string, it is highly recommended to write \code cimg::warn("%s",warning_message); \endcode instead of \code cimg::warn(warning_message); \endcode if \c warning_message can be arbitrary, to prevent nasty memory access. **/ inline void warn(const char *const format, ...) { if (cimg::exception_mode()>=1) { char *const message = new char[16384]; std::va_list ap; va_start(ap,format); cimg_vsnprintf(message,16384,format,ap); va_end(ap); #ifdef cimg_strict_warnings throw CImgWarningException(message); #else std::fprintf(cimg::output(),"\n%s[CImg] *** Warning ***%s%s\n",cimg::t_red,cimg::t_normal,message); #endif delete[] message; } } // Execute an external system command. /** \param command C-string containing the command line to execute. \param module_name Module name. \return Status value of the executed command, whose meaning is OS-dependent. \note This function is similar to <tt>std::system()</tt> but it does not open an extra console windows on Windows-based systems. **/ inline int system(const char *const command, const char *const module_name=0, const bool is_verbose=false) { cimg::unused(module_name); #ifdef cimg_no_system_calls return -1; #else if (is_verbose) return std::system(command); #if cimg_OS==1 const unsigned int l = (unsigned int)std::strlen(command); if (l) { char *const ncommand = new char[l + 24]; std::memcpy(ncommand,command,l); std::strcpy(ncommand + l," >/dev/null 2>&1"); // Make command silent const int out_val = std::system(ncommand); delete[] ncommand; return out_val; } else return -1; #elif cimg_OS==2 PROCESS_INFORMATION pi; STARTUPINFO si; std::memset(&pi,0,sizeof(PROCESS_INFORMATION)); std::memset(&si,0,sizeof(STARTUPINFO)); GetStartupInfo(&si); si.cb = sizeof(si); si.wShowWindow = SW_HIDE; si.dwFlags |= SW_HIDE | STARTF_USESHOWWINDOW; const BOOL res = CreateProcess((LPCTSTR)module_name,(LPTSTR)command,0,0,FALSE,0,0,0,&si,&pi); if (res) { WaitForSingleObject(pi.hProcess,INFINITE); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); return 0; } else return std::system(command); #else return std::system(command); #endif #endif } //! Return a reference to a temporary variable of type T. template<typename T> inline T& temporary(const T&) { static T temp; return temp; } //! Exchange values of variables \c a and \c b. template<typename T> inline void swap(T& a, T& b) { T t = a; a = b; b = t; } //! Exchange values of variables (\c a1,\c a2) and (\c b1,\c b2). template<typename T1, typename T2> inline void swap(T1& a1, T1& b1, T2& a2, T2& b2) { cimg::swap(a1,b1); cimg::swap(a2,b2); } //! Exchange values of variables (\c a1,\c a2,\c a3) and (\c b1,\c b2,\c b3). template<typename T1, typename T2, typename T3> inline void swap(T1& a1, T1& b1, T2& a2, T2& b2, T3& a3, T3& b3) { cimg::swap(a1,b1,a2,b2); cimg::swap(a3,b3); } //! Exchange values of variables (\c a1,\c a2,...,\c a4) and (\c b1,\c b2,...,\c b4). template<typename T1, typename T2, typename T3, typename T4> inline void swap(T1& a1, T1& b1, T2& a2, T2& b2, T3& a3, T3& b3, T4& a4, T4& b4) { cimg::swap(a1,b1,a2,b2,a3,b3); cimg::swap(a4,b4); } //! Exchange values of variables (\c a1,\c a2,...,\c a5) and (\c b1,\c b2,...,\c b5). template<typename T1, typename T2, typename T3, typename T4, typename T5> inline void swap(T1& a1, T1& b1, T2& a2, T2& b2, T3& a3, T3& b3, T4& a4, T4& b4, T5& a5, T5& b5) { cimg::swap(a1,b1,a2,b2,a3,b3,a4,b4); cimg::swap(a5,b5); } //! Exchange values of variables (\c a1,\c a2,...,\c a6) and (\c b1,\c b2,...,\c b6). template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> inline void swap(T1& a1, T1& b1, T2& a2, T2& b2, T3& a3, T3& b3, T4& a4, T4& b4, T5& a5, T5& b5, T6& a6, T6& b6) { cimg::swap(a1,b1,a2,b2,a3,b3,a4,b4,a5,b5); cimg::swap(a6,b6); } //! Exchange values of variables (\c a1,\c a2,...,\c a7) and (\c b1,\c b2,...,\c b7). template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> inline void swap(T1& a1, T1& b1, T2& a2, T2& b2, T3& a3, T3& b3, T4& a4, T4& b4, T5& a5, T5& b5, T6& a6, T6& b6, T7& a7, T7& b7) { cimg::swap(a1,b1,a2,b2,a3,b3,a4,b4,a5,b5,a6,b6); cimg::swap(a7,b7); } //! Exchange values of variables (\c a1,\c a2,...,\c a8) and (\c b1,\c b2,...,\c b8). template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> inline void swap(T1& a1, T1& b1, T2& a2, T2& b2, T3& a3, T3& b3, T4& a4, T4& b4, T5& a5, T5& b5, T6& a6, T6& b6, T7& a7, T7& b7, T8& a8, T8& b8) { cimg::swap(a1,b1,a2,b2,a3,b3,a4,b4,a5,b5,a6,b6,a7,b7); cimg::swap(a8,b8); } //! Return the endianness of the current architecture. /** \return \c false for <i>Little Endian</i> or \c true for <i>Big Endian</i>. **/ inline bool endianness() { const int x = 1; return ((unsigned char*)&x)[0]?false:true; } //! Reverse endianness of all elements in a memory buffer. /** \param[in,out] buffer Memory buffer whose endianness must be reversed. \param size Number of buffer elements to reverse. **/ template<typename T> inline void invert_endianness(T* const buffer, const cimg_ulong size) { if (size) switch (sizeof(T)) { case 1 : break; case 2 : { for (unsigned short *ptr = (unsigned short*)buffer + size; ptr>(unsigned short*)buffer; ) { const unsigned short val = *(--ptr); *ptr = (unsigned short)((val>>8) | ((val<<8))); } } break; case 4 : { for (unsigned int *ptr = (unsigned int*)buffer + size; ptr>(unsigned int*)buffer; ) { const unsigned int val = *(--ptr); *ptr = (val>>24) | ((val>>8)&0xff00) | ((val<<8)&0xff0000) | (val<<24); } } break; case 8 : { const cimg_uint64 m0 = (cimg_uint64)0xff, m1 = m0<<8, m2 = m0<<16, m3 = m0<<24, m4 = m0<<32, m5 = m0<<40, m6 = m0<<48, m7 = m0<<56; for (cimg_uint64 *ptr = (cimg_uint64*)buffer + size; ptr>(cimg_uint64*)buffer; ) { const cimg_uint64 val = *(--ptr); *ptr = (((val&m7)>>56) | ((val&m6)>>40) | ((val&m5)>>24) | ((val&m4)>>8) | ((val&m3)<<8) |((val&m2)<<24) | ((val&m1)<<40) | ((val&m0)<<56)); } } break; default : { for (T* ptr = buffer + size; ptr>buffer; ) { unsigned char *pb = (unsigned char*)(--ptr), *pe = pb + sizeof(T); for (int i = 0; i<(int)sizeof(T)/2; ++i) swap(*(pb++),*(--pe)); } } } } //! Reverse endianness of a single variable. /** \param[in,out] a Variable to reverse. \return Reference to reversed variable. **/ template<typename T> inline T& invert_endianness(T& a) { invert_endianness(&a,1); return a; } // Conversion functions to get more precision when trying to store unsigned ints values as floats. inline unsigned int float2uint(const float f) { int tmp = 0; std::memcpy(&tmp,&f,sizeof(float)); if (tmp>=0) return (unsigned int)f; unsigned int u; // use memcpy instead of assignment to avoid undesired optimizations by C++-compiler. std::memcpy(&u,&f,sizeof(float)); return ((u)<<1)>>1; // set sign bit to 0 } inline float uint2float(const unsigned int u) { if (u<(1U<<19)) return (float)u; // Consider safe storage of unsigned int as floats until 19bits (i.e 524287) float f; const unsigned int v = u|(1U<<(8*sizeof(unsigned int)-1)); // set sign bit to 1 // use memcpy instead of simple assignment to avoid undesired optimizations by C++-compiler. std::memcpy(&f,&v,sizeof(float)); return f; } //! Return the value of a system timer, with a millisecond precision. /** \note The timer does not necessarily starts from \c 0. **/ inline cimg_ulong time() { #if cimg_OS==1 struct timeval st_time; gettimeofday(&st_time,0); return (cimg_ulong)(st_time.tv_usec/1000 + st_time.tv_sec*1000); #elif cimg_OS==2 SYSTEMTIME st_time; GetLocalTime(&st_time); return (cimg_ulong)(st_time.wMilliseconds + 1000*(st_time.wSecond + 60*(st_time.wMinute + 60*st_time.wHour))); #else return 0; #endif } // Implement a tic/toc mechanism to display elapsed time of algorithms. inline cimg_ulong tictoc(const bool is_tic); //! Start tic/toc timer for time measurement between code instructions. /** \return Current value of the timer (same value as time()). **/ inline cimg_ulong tic() { return cimg::tictoc(true); } //! End tic/toc timer and displays elapsed time from last call to tic(). /** \return Time elapsed (in ms) since last call to tic(). **/ inline cimg_ulong toc() { return cimg::tictoc(false); } //! Sleep for a given numbers of milliseconds. /** \param milliseconds Number of milliseconds to wait for. \note This function frees the CPU ressources during the sleeping time. It can be used to temporize your program properly, without wasting CPU time. **/ inline void sleep(const unsigned int milliseconds) { #if cimg_OS==1 struct timespec tv; tv.tv_sec = milliseconds/1000; tv.tv_nsec = (milliseconds%1000)*1000000; nanosleep(&tv,0); #elif cimg_OS==2 Sleep(milliseconds); #else cimg::unused(milliseconds); #endif } inline unsigned int wait(const unsigned int milliseconds, cimg_ulong *const p_timer) { if (!*p_timer) *p_timer = cimg::time(); const cimg_ulong current_time = cimg::time(); if (current_time>=*p_timer + milliseconds) { *p_timer = current_time; return 0; } const unsigned int time_diff = (unsigned int)(*p_timer + milliseconds - current_time); *p_timer = current_time + time_diff; cimg::sleep(time_diff); return time_diff; } //! Wait for a given number of milliseconds since the last call to wait(). /** \param milliseconds Number of milliseconds to wait for. \return Number of milliseconds elapsed since the last call to wait(). \note Same as sleep() with a waiting time computed with regard to the last call of wait(). It may be used to temporize your program properly, without wasting CPU time. **/ inline cimg_long wait(const unsigned int milliseconds) { cimg::mutex(3); static cimg_ulong timer = cimg::time(); cimg::mutex(3,0); return cimg::wait(milliseconds,&timer); } // Custom random number generator (allow re-entrance). inline cimg_ulong& rng() { // Used as a shared global number for rng static cimg_ulong rng = 0xB16B00B5U; return rng; } inline unsigned int _rand(cimg_ulong *const p_rng) { *p_rng = *p_rng*1103515245 + 12345U; return (unsigned int)*p_rng; } inline unsigned int _rand() { cimg::mutex(4); const unsigned int res = cimg::_rand(&cimg::rng()); cimg::mutex(4,0); return res; } inline void srand(cimg_ulong *const p_rng) { #if cimg_OS==1 *p_rng = cimg::time() + (cimg_ulong)getpid(); #elif cimg_OS==2 *p_rng = cimg::time() + (cimg_ulong)_getpid(); #endif } inline void srand() { cimg::mutex(4); cimg::srand(&cimg::rng()); cimg::mutex(4,0); } inline void srand(const cimg_ulong seed) { cimg::mutex(4); cimg::rng() = seed; cimg::mutex(4,0); } inline double rand(const double val_min, const double val_max, cimg_ulong *const p_rng) { const double val = cimg::_rand(p_rng)/(double)~0U; return val_min + (val_max - val_min)*val; } inline double rand(const double val_min, const double val_max) { cimg::mutex(4); const double res = cimg::rand(val_min,val_max,&cimg::rng()); cimg::mutex(4,0); return res; } inline double rand(const double val_max, cimg_ulong *const p_rng) { const double val = cimg::_rand(p_rng)/(double)~0U; return val_max*val; } inline double rand(const double val_max=1) { cimg::mutex(4); const double res = cimg::rand(val_max,&cimg::rng()); cimg::mutex(4,0); return res; } inline double grand(cimg_ulong *const p_rng) { double x1, w; do { const double x2 = cimg::rand(-1,1,p_rng); x1 = cimg::rand(-1,1,p_rng); w = x1*x1 + x2*x2; } while (w<=0 || w>=1.); return x1*std::sqrt((-2*std::log(w))/w); } inline double grand() { cimg::mutex(4); const double res = cimg::grand(&cimg::rng()); cimg::mutex(4,0); return res; } inline unsigned int prand(const double z, cimg_ulong *const p_rng) { if (z<=1.e-10) return 0; if (z>100) return (unsigned int)((std::sqrt(z) * cimg::grand(p_rng)) + z); unsigned int k = 0; const double y = std::exp(-z); for (double s = 1.; s>=y; ++k) s*=cimg::rand(1,p_rng); return k - 1; } inline unsigned int prand(const double z) { cimg::mutex(4); const unsigned int res = cimg::prand(z,&cimg::rng()); cimg::mutex(4,0); return res; } //! Cut (i.e. clamp) value in specified interval. template<typename T, typename t> inline T cut(const T& val, const t& val_min, const t& val_max) { return val<val_min?(T)val_min:val>val_max?(T)val_max:val; } //! Bitwise-rotate value on the left. template<typename T> inline T rol(const T& a, const unsigned int n=1) { return n?(T)((a<<n)|(a>>((sizeof(T)<<3) - n))):a; } inline float rol(const float a, const unsigned int n=1) { return (float)rol((int)a,n); } inline double rol(const double a, const unsigned int n=1) { return (double)rol((cimg_long)a,n); } inline double rol(const long double a, const unsigned int n=1) { return (double)rol((cimg_long)a,n); } #ifdef cimg_use_half inline half rol(const half a, const unsigned int n=1) { return (half)rol((int)a,n); } #endif //! Bitwise-rotate value on the right. template<typename T> inline T ror(const T& a, const unsigned int n=1) { return n?(T)((a>>n)|(a<<((sizeof(T)<<3) - n))):a; } inline float ror(const float a, const unsigned int n=1) { return (float)ror((int)a,n); } inline double ror(const double a, const unsigned int n=1) { return (double)ror((cimg_long)a,n); } inline double ror(const long double a, const unsigned int n=1) { return (double)ror((cimg_long)a,n); } #ifdef cimg_use_half inline half ror(const half a, const unsigned int n=1) { return (half)ror((int)a,n); } #endif //! Return absolute value of a value. template<typename T> inline T abs(const T& a) { return a>=0?a:-a; } inline bool abs(const bool a) { return a; } inline int abs(const unsigned char a) { return (int)a; } inline int abs(const unsigned short a) { return (int)a; } inline int abs(const unsigned int a) { return (int)a; } inline int abs(const int a) { return std::abs(a); } inline cimg_int64 abs(const cimg_uint64 a) { return (cimg_int64)a; } inline double abs(const double a) { return std::fabs(a); } inline float abs(const float a) { return (float)std::fabs((double)a); } //! Return hyperbolic arcosine of a value. inline double acosh(const double x) { #if cimg_use_cpp11==1 && !defined(_MSC_VER) return std::acosh(x); #else return std::log(x + std::sqrt(x*x - 1)); #endif } //! Return hyperbolic arcsine of a value. inline double asinh(const double x) { #if cimg_use_cpp11==1 && !defined(_MSC_VER) return std::asinh(x); #else return std::log(x + std::sqrt(x*x + 1)); #endif } //! Return hyperbolic arctangent of a value. inline double atanh(const double x) { #if cimg_use_cpp11==1 && !defined(_MSC_VER) return std::atanh(x); #else return 0.5*std::log((1. + x)/(1. - x)); #endif } //! Return the sinc of a given value. inline double sinc(const double x) { return x?std::sin(x)/x:1; } //! Return base-2 logarithm of a value. inline double log2(const double x) { #if cimg_use_cpp11==1 && !defined(_MSC_VER) return std::log2(x); #else const double base2 = std::log(2.); return std::log(x)/base2; #endif } //! Return square of a value. template<typename T> inline T sqr(const T& val) { return val*val; } //! Return cubic root of a value. template<typename T> inline double cbrt(const T& x) { #if cimg_use_cpp11==1 return std::cbrt(x); #else return x>=0?std::pow((double)x,1./3):-std::pow(-(double)x,1./3); #endif } template<typename T> inline T pow3(const T& val) { return val*val*val; } template<typename T> inline T pow4(const T& val) { return val*val*val*val; } //! Return the minimum between three values. template<typename t> inline t min(const t& a, const t& b, const t& c) { return std::min(std::min(a,b),c); } //! Return the minimum between four values. template<typename t> inline t min(const t& a, const t& b, const t& c, const t& d) { return std::min(std::min(a,b),std::min(c,d)); } //! Return the maximum between three values. template<typename t> inline t max(const t& a, const t& b, const t& c) { return std::max(std::max(a,b),c); } //! Return the maximum between four values. template<typename t> inline t max(const t& a, const t& b, const t& c, const t& d) { return std::max(std::max(a,b),std::max(c,d)); } //! Return the sign of a value. template<typename T> inline T sign(const T& x) { return (T)(cimg::type<T>::is_nan(x)?0:x<0?-1:x>0); } //! Return the nearest power of 2 higher than given value. template<typename T> inline cimg_ulong nearest_pow2(const T& x) { cimg_ulong i = 1; while (x>i) i<<=1; return i; } //! Return the modulo of a value. /** \param x Input value. \param m Modulo value. \note This modulo function accepts negative and floating-points modulo numbers, as well as variables of any type. **/ template<typename T> inline T mod(const T& x, const T& m) { const double dx = (double)x, dm = (double)m; return (T)(dx - dm * std::floor(dx / dm)); } inline int mod(const bool x, const bool m) { return m?(x?1:0):0; } inline int mod(const unsigned char x, const unsigned char m) { return x%m; } inline int mod(const char x, const char m) { #if defined(CHAR_MAX) && CHAR_MAX==255 return x%m; #else return x>=0?x%m:(x%m?m + x%m:0); #endif } inline int mod(const unsigned short x, const unsigned short m) { return x%m; } inline int mod(const short x, const short m) { return x>=0?x%m:(x%m?m + x%m:0); } inline int mod(const unsigned int x, const unsigned int m) { return (int)(x%m); } inline int mod(const int x, const int m) { return x>=0?x%m:(x%m?m + x%m:0); } inline cimg_int64 mod(const cimg_uint64 x, const cimg_uint64 m) { return x%m; } inline cimg_int64 mod(const cimg_int64 x, const cimg_int64 m) { return x>=0?x%m:(x%m?m + x%m:0); } //! Return the min-mod of two values. /** \note <i>minmod(\p a,\p b)</i> is defined to be: - <i>minmod(\p a,\p b) = min(\p a,\p b)</i>, if \p a and \p b have the same sign. - <i>minmod(\p a,\p b) = 0</i>, if \p a and \p b have different signs. **/ template<typename T> inline T minmod(const T& a, const T& b) { return a*b<=0?0:(a>0?(a<b?a:b):(a<b?b:a)); } template<typename T> inline T round(const T& x) { return (T)std::floor((_cimg_Tfloat)x + 0.5f); } template<typename T> inline int uiround(const T x) { return cimg::type<T>::is_float()?(int)(x + 0.5f):(int)x; } //! Return rounded value. /** \param x Value to be rounded. \param y Rounding precision. \param rounding_type Type of rounding operation (\c 0 = nearest, \c -1 = backward, \c 1 = forward). \return Rounded value, having the same type as input value \c x. **/ template<typename T> inline T round(const T& x, const double y, const int rounding_type=0) { if (y<=0) return x; if (y==1) switch (rounding_type) { case 0 : return cimg::round(x); case 1 : return (T)std::ceil((_cimg_Tfloat)x); default : return (T)std::floor((_cimg_Tfloat)x); } const double sx = (double)x/y, floor = std::floor(sx), delta = sx - floor; return (T)(y*(rounding_type<0?floor:rounding_type>0?std::ceil(sx):delta<0.5?floor:std::ceil(sx))); } // Code to compute fast median from 2,3,5,7,9,13,25 and 49 values. // (contribution by RawTherapee: http://rawtherapee.com/). template<typename T> inline T median(T val0, T val1) { return (val0 + val1)/2; } template<typename T> inline T median(T val0, T val1, T val2) { return std::max(std::min(val0,val1),std::min(val2,std::max(val0,val1))); } template<typename T> inline T median(T val0, T val1, T val2, T val3, T val4) { T tmp = std::min(val0,val1); val1 = std::max(val0,val1); val0 = tmp; tmp = std::min(val3,val4); val4 = std::max(val3,val4); val3 = std::max(val0,tmp); val1 = std::min(val1,val4); tmp = std::min(val1,val2); val2 = std::max(val1,val2); val1 = tmp; tmp = std::min(val2,val3); return std::max(val1,tmp); } template<typename T> inline T median(T val0, T val1, T val2, T val3, T val4, T val5, T val6) { T tmp = std::min(val0,val5); val5 = std::max(val0,val5); val0 = tmp; tmp = std::min(val0,val3); val3 = std::max(val0,val3); val0 = tmp; tmp = std::min(val1,val6); val6 = std::max(val1,val6); val1 = tmp; tmp = std::min(val2,val4); val4 = std::max(val2,val4); val2 = tmp; val1 = std::max(val0,val1); tmp = std::min(val3,val5); val5 = std::max(val3,val5); val3 = tmp; tmp = std::min(val2,val6); val6 = std::max(val2,val6); val3 = std::max(tmp,val3); val3 = std::min(val3,val6); tmp = std::min(val4,val5); val4 = std::max(val1,tmp); tmp = std::min(val1,tmp); val3 = std::max(tmp,val3); return std::min(val3,val4); } template<typename T> inline T median(T val0, T val1, T val2, T val3, T val4, T val5, T val6, T val7, T val8) { T tmp = std::min(val1,val2); val2 = std::max(val1,val2); val1 = tmp; tmp = std::min(val4,val5); val5 = std::max(val4,val5); val4 = tmp; tmp = std::min(val7,val8); val8 = std::max(val7,val8); val7 = tmp; tmp = std::min(val0,val1); val1 = std::max(val0,val1); val0 = tmp; tmp = std::min(val3,val4); val4 = std::max(val3,val4); val3 = tmp; tmp = std::min(val6,val7); val7 = std::max(val6,val7); val6 = tmp; tmp = std::min(val1,val2); val2 = std::max(val1,val2); val1 = tmp; tmp = std::min(val4,val5); val5 = std::max(val4,val5); val4 = tmp; tmp = std::min(val7,val8); val8 = std::max(val7,val8); val3 = std::max(val0,val3); val5 = std::min(val5,val8); val7 = std::max(val4,tmp); tmp = std::min(val4,tmp); val6 = std::max(val3,val6); val4 = std::max(val1,tmp); val2 = std::min(val2,val5); val4 = std::min(val4,val7); tmp = std::min(val4,val2); val2 = std::max(val4,val2); val4 = std::max(val6,tmp); return std::min(val4,val2); } template<typename T> inline T median(T val0, T val1, T val2, T val3, T val4, T val5, T val6, T val7, T val8, T val9, T val10, T val11, T val12) { T tmp = std::min(val1,val7); val7 = std::max(val1,val7); val1 = tmp; tmp = std::min(val9,val11); val11 = std::max(val9,val11); val9 = tmp; tmp = std::min(val3,val4); val4 = std::max(val3,val4); val3 = tmp; tmp = std::min(val5,val8); val8 = std::max(val5,val8); val5 = tmp; tmp = std::min(val0,val12); val12 = std::max(val0,val12); val0 = tmp; tmp = std::min(val2,val6); val6 = std::max(val2,val6); val2 = tmp; tmp = std::min(val0,val1); val1 = std::max(val0,val1); val0 = tmp; tmp = std::min(val2,val3); val3 = std::max(val2,val3); val2 = tmp; tmp = std::min(val4,val6); val6 = std::max(val4,val6); val4 = tmp; tmp = std::min(val8,val11); val11 = std::max(val8,val11); val8 = tmp; tmp = std::min(val7,val12); val12 = std::max(val7,val12); val7 = tmp; tmp = std::min(val5,val9); val9 = std::max(val5,val9); val5 = tmp; tmp = std::min(val0,val2); val2 = std::max(val0,val2); val0 = tmp; tmp = std::min(val3,val7); val7 = std::max(val3,val7); val3 = tmp; tmp = std::min(val10,val11); val11 = std::max(val10,val11); val10 = tmp; tmp = std::min(val1,val4); val4 = std::max(val1,val4); val1 = tmp; tmp = std::min(val6,val12); val12 = std::max(val6,val12); val6 = tmp; tmp = std::min(val7,val8); val8 = std::max(val7,val8); val7 = tmp; val11 = std::min(val11,val12); tmp = std::min(val4,val9); val9 = std::max(val4,val9); val4 = tmp; tmp = std::min(val6,val10); val10 = std::max(val6,val10); val6 = tmp; tmp = std::min(val3,val4); val4 = std::max(val3,val4); val3 = tmp; tmp = std::min(val5,val6); val6 = std::max(val5,val6); val5 = tmp; val8 = std::min(val8,val9); val10 = std::min(val10,val11); tmp = std::min(val1,val7); val7 = std::max(val1,val7); val1 = tmp; tmp = std::min(val2,val6); val6 = std::max(val2,val6); val2 = tmp; val3 = std::max(val1,val3); tmp = std::min(val4,val7); val7 = std::max(val4,val7); val4 = tmp; val8 = std::min(val8,val10); val5 = std::max(val0,val5); val5 = std::max(val2,val5); tmp = std::min(val6,val8); val8 = std::max(val6,val8); val5 = std::max(val3,val5); val7 = std::min(val7,val8); val6 = std::max(val4,tmp); tmp = std::min(val4,tmp); val5 = std::max(tmp,val5); val6 = std::min(val6,val7); return std::max(val5,val6); } template<typename T> inline T median(T val0, T val1, T val2, T val3, T val4, T val5, T val6, T val7, T val8, T val9, T val10, T val11, T val12, T val13, T val14, T val15, T val16, T val17, T val18, T val19, T val20, T val21, T val22, T val23, T val24) { T tmp = std::min(val0,val1); val1 = std::max(val0,val1); val0 = tmp; tmp = std::min(val3,val4); val4 = std::max(val3,val4); val3 = tmp; tmp = std::min(val2,val4); val4 = std::max(val2,val4); val2 = std::min(tmp,val3); val3 = std::max(tmp,val3); tmp = std::min(val6,val7); val7 = std::max(val6,val7); val6 = tmp; tmp = std::min(val5,val7); val7 = std::max(val5,val7); val5 = std::min(tmp,val6); val6 = std::max(tmp,val6); tmp = std::min(val9,val10); val10 = std::max(val9,val10); val9 = tmp; tmp = std::min(val8,val10); val10 = std::max(val8,val10); val8 = std::min(tmp,val9); val9 = std::max(tmp,val9); tmp = std::min(val12,val13); val13 = std::max(val12,val13); val12 = tmp; tmp = std::min(val11,val13); val13 = std::max(val11,val13); val11 = std::min(tmp,val12); val12 = std::max(tmp,val12); tmp = std::min(val15,val16); val16 = std::max(val15,val16); val15 = tmp; tmp = std::min(val14,val16); val16 = std::max(val14,val16); val14 = std::min(tmp,val15); val15 = std::max(tmp,val15); tmp = std::min(val18,val19); val19 = std::max(val18,val19); val18 = tmp; tmp = std::min(val17,val19); val19 = std::max(val17,val19); val17 = std::min(tmp,val18); val18 = std::max(tmp,val18); tmp = std::min(val21,val22); val22 = std::max(val21,val22); val21 = tmp; tmp = std::min(val20,val22); val22 = std::max(val20,val22); val20 = std::min(tmp,val21); val21 = std::max(tmp,val21); tmp = std::min(val23,val24); val24 = std::max(val23,val24); val23 = tmp; tmp = std::min(val2,val5); val5 = std::max(val2,val5); val2 = tmp; tmp = std::min(val3,val6); val6 = std::max(val3,val6); val3 = tmp; tmp = std::min(val0,val6); val6 = std::max(val0,val6); val0 = std::min(tmp,val3); val3 = std::max(tmp,val3); tmp = std::min(val4,val7); val7 = std::max(val4,val7); val4 = tmp; tmp = std::min(val1,val7); val7 = std::max(val1,val7); val1 = std::min(tmp,val4); val4 = std::max(tmp,val4); tmp = std::min(val11,val14); val14 = std::max(val11,val14); val11 = tmp; tmp = std::min(val8,val14); val14 = std::max(val8,val14); val8 = std::min(tmp,val11); val11 = std::max(tmp,val11); tmp = std::min(val12,val15); val15 = std::max(val12,val15); val12 = tmp; tmp = std::min(val9,val15); val15 = std::max(val9,val15); val9 = std::min(tmp,val12); val12 = std::max(tmp,val12); tmp = std::min(val13,val16); val16 = std::max(val13,val16); val13 = tmp; tmp = std::min(val10,val16); val16 = std::max(val10,val16); val10 = std::min(tmp,val13); val13 = std::max(tmp,val13); tmp = std::min(val20,val23); val23 = std::max(val20,val23); val20 = tmp; tmp = std::min(val17,val23); val23 = std::max(val17,val23); val17 = std::min(tmp,val20); val20 = std::max(tmp,val20); tmp = std::min(val21,val24); val24 = std::max(val21,val24); val21 = tmp; tmp = std::min(val18,val24); val24 = std::max(val18,val24); val18 = std::min(tmp,val21); val21 = std::max(tmp,val21); tmp = std::min(val19,val22); val22 = std::max(val19,val22); val19 = tmp; val17 = std::max(val8,val17); tmp = std::min(val9,val18); val18 = std::max(val9,val18); val9 = tmp; tmp = std::min(val0,val18); val18 = std::max(val0,val18); val9 = std::max(tmp,val9); tmp = std::min(val10,val19); val19 = std::max(val10,val19); val10 = tmp; tmp = std::min(val1,val19); val19 = std::max(val1,val19); val1 = std::min(tmp,val10); val10 = std::max(tmp,val10); tmp = std::min(val11,val20); val20 = std::max(val11,val20); val11 = tmp; tmp = std::min(val2,val20); val20 = std::max(val2,val20); val11 = std::max(tmp,val11); tmp = std::min(val12,val21); val21 = std::max(val12,val21); val12 = tmp; tmp = std::min(val3,val21); val21 = std::max(val3,val21); val3 = std::min(tmp,val12); val12 = std::max(tmp,val12); tmp = std::min(val13,val22); val22 = std::max(val13,val22); val4 = std::min(val4,val22); val13 = std::max(val4,tmp); tmp = std::min(val4,tmp); val4 = tmp; tmp = std::min(val14,val23); val23 = std::max(val14,val23); val14 = tmp; tmp = std::min(val5,val23); val23 = std::max(val5,val23); val5 = std::min(tmp,val14); val14 = std::max(tmp,val14); tmp = std::min(val15,val24); val24 = std::max(val15,val24); val15 = tmp; val6 = std::min(val6,val24); tmp = std::min(val6,val15); val15 = std::max(val6,val15); val6 = tmp; tmp = std::min(val7,val16); val7 = std::min(tmp,val19); tmp = std::min(val13,val21); val15 = std::min(val15,val23); tmp = std::min(val7,tmp); val7 = std::min(tmp,val15); val9 = std::max(val1,val9); val11 = std::max(val3,val11); val17 = std::max(val5,val17); val17 = std::max(val11,val17); val17 = std::max(val9,val17); tmp = std::min(val4,val10); val10 = std::max(val4,val10); val4 = tmp; tmp = std::min(val6,val12); val12 = std::max(val6,val12); val6 = tmp; tmp = std::min(val7,val14); val14 = std::max(val7,val14); val7 = tmp; tmp = std::min(val4,val6); val6 = std::max(val4,val6); val7 = std::max(tmp,val7); tmp = std::min(val12,val14); val14 = std::max(val12,val14); val12 = tmp; val10 = std::min(val10,val14); tmp = std::min(val6,val7); val7 = std::max(val6,val7); val6 = tmp; tmp = std::min(val10,val12); val12 = std::max(val10,val12); val10 = std::max(val6,tmp); tmp = std::min(val6,tmp); val17 = std::max(tmp,val17); tmp = std::min(val12,val17); val17 = std::max(val12,val17); val12 = tmp; val7 = std::min(val7,val17); tmp = std::min(val7,val10); val10 = std::max(val7,val10); val7 = tmp; tmp = std::min(val12,val18); val18 = std::max(val12,val18); val12 = std::max(val7,tmp); val10 = std::min(val10,val18); tmp = std::min(val12,val20); val20 = std::max(val12,val20); val12 = tmp; tmp = std::min(val10,val20); return std::max(tmp,val12); } template<typename T> inline T median(T val0, T val1, T val2, T val3, T val4, T val5, T val6, T val7, T val8, T val9, T val10, T val11, T val12, T val13, T val14, T val15, T val16, T val17, T val18, T val19, T val20, T val21, T val22, T val23, T val24, T val25, T val26, T val27, T val28, T val29, T val30, T val31, T val32, T val33, T val34, T val35, T val36, T val37, T val38, T val39, T val40, T val41, T val42, T val43, T val44, T val45, T val46, T val47, T val48) { T tmp = std::min(val0,val32); val32 = std::max(val0,val32); val0 = tmp; tmp = std::min(val1,val33); val33 = std::max(val1,val33); val1 = tmp; tmp = std::min(val2,val34); val34 = std::max(val2,val34); val2 = tmp; tmp = std::min(val3,val35); val35 = std::max(val3,val35); val3 = tmp; tmp = std::min(val4,val36); val36 = std::max(val4,val36); val4 = tmp; tmp = std::min(val5,val37); val37 = std::max(val5,val37); val5 = tmp; tmp = std::min(val6,val38); val38 = std::max(val6,val38); val6 = tmp; tmp = std::min(val7,val39); val39 = std::max(val7,val39); val7 = tmp; tmp = std::min(val8,val40); val40 = std::max(val8,val40); val8 = tmp; tmp = std::min(val9,val41); val41 = std::max(val9,val41); val9 = tmp; tmp = std::min(val10,val42); val42 = std::max(val10,val42); val10 = tmp; tmp = std::min(val11,val43); val43 = std::max(val11,val43); val11 = tmp; tmp = std::min(val12,val44); val44 = std::max(val12,val44); val12 = tmp; tmp = std::min(val13,val45); val45 = std::max(val13,val45); val13 = tmp; tmp = std::min(val14,val46); val46 = std::max(val14,val46); val14 = tmp; tmp = std::min(val15,val47); val47 = std::max(val15,val47); val15 = tmp; tmp = std::min(val16,val48); val48 = std::max(val16,val48); val16 = tmp; tmp = std::min(val0,val16); val16 = std::max(val0,val16); val0 = tmp; tmp = std::min(val1,val17); val17 = std::max(val1,val17); val1 = tmp; tmp = std::min(val2,val18); val18 = std::max(val2,val18); val2 = tmp; tmp = std::min(val3,val19); val19 = std::max(val3,val19); val3 = tmp; tmp = std::min(val4,val20); val20 = std::max(val4,val20); val4 = tmp; tmp = std::min(val5,val21); val21 = std::max(val5,val21); val5 = tmp; tmp = std::min(val6,val22); val22 = std::max(val6,val22); val6 = tmp; tmp = std::min(val7,val23); val23 = std::max(val7,val23); val7 = tmp; tmp = std::min(val8,val24); val24 = std::max(val8,val24); val8 = tmp; tmp = std::min(val9,val25); val25 = std::max(val9,val25); val9 = tmp; tmp = std::min(val10,val26); val26 = std::max(val10,val26); val10 = tmp; tmp = std::min(val11,val27); val27 = std::max(val11,val27); val11 = tmp; tmp = std::min(val12,val28); val28 = std::max(val12,val28); val12 = tmp; tmp = std::min(val13,val29); val29 = std::max(val13,val29); val13 = tmp; tmp = std::min(val14,val30); val30 = std::max(val14,val30); val14 = tmp; tmp = std::min(val15,val31); val31 = std::max(val15,val31); val15 = tmp; tmp = std::min(val32,val48); val48 = std::max(val32,val48); val32 = tmp; tmp = std::min(val16,val32); val32 = std::max(val16,val32); val16 = tmp; tmp = std::min(val17,val33); val33 = std::max(val17,val33); val17 = tmp; tmp = std::min(val18,val34); val34 = std::max(val18,val34); val18 = tmp; tmp = std::min(val19,val35); val35 = std::max(val19,val35); val19 = tmp; tmp = std::min(val20,val36); val36 = std::max(val20,val36); val20 = tmp; tmp = std::min(val21,val37); val37 = std::max(val21,val37); val21 = tmp; tmp = std::min(val22,val38); val38 = std::max(val22,val38); val22 = tmp; tmp = std::min(val23,val39); val39 = std::max(val23,val39); val23 = tmp; tmp = std::min(val24,val40); val40 = std::max(val24,val40); val24 = tmp; tmp = std::min(val25,val41); val41 = std::max(val25,val41); val25 = tmp; tmp = std::min(val26,val42); val42 = std::max(val26,val42); val26 = tmp; tmp = std::min(val27,val43); val43 = std::max(val27,val43); val27 = tmp; tmp = std::min(val28,val44); val44 = std::max(val28,val44); val28 = tmp; tmp = std::min(val29,val45); val45 = std::max(val29,val45); val29 = tmp; tmp = std::min(val30,val46); val46 = std::max(val30,val46); val30 = tmp; tmp = std::min(val31,val47); val47 = std::max(val31,val47); val31 = tmp; tmp = std::min(val0,val8); val8 = std::max(val0,val8); val0 = tmp; tmp = std::min(val1,val9); val9 = std::max(val1,val9); val1 = tmp; tmp = std::min(val2,val10); val10 = std::max(val2,val10); val2 = tmp; tmp = std::min(val3,val11); val11 = std::max(val3,val11); val3 = tmp; tmp = std::min(val4,val12); val12 = std::max(val4,val12); val4 = tmp; tmp = std::min(val5,val13); val13 = std::max(val5,val13); val5 = tmp; tmp = std::min(val6,val14); val14 = std::max(val6,val14); val6 = tmp; tmp = std::min(val7,val15); val15 = std::max(val7,val15); val7 = tmp; tmp = std::min(val16,val24); val24 = std::max(val16,val24); val16 = tmp; tmp = std::min(val17,val25); val25 = std::max(val17,val25); val17 = tmp; tmp = std::min(val18,val26); val26 = std::max(val18,val26); val18 = tmp; tmp = std::min(val19,val27); val27 = std::max(val19,val27); val19 = tmp; tmp = std::min(val20,val28); val28 = std::max(val20,val28); val20 = tmp; tmp = std::min(val21,val29); val29 = std::max(val21,val29); val21 = tmp; tmp = std::min(val22,val30); val30 = std::max(val22,val30); val22 = tmp; tmp = std::min(val23,val31); val31 = std::max(val23,val31); val23 = tmp; tmp = std::min(val32,val40); val40 = std::max(val32,val40); val32 = tmp; tmp = std::min(val33,val41); val41 = std::max(val33,val41); val33 = tmp; tmp = std::min(val34,val42); val42 = std::max(val34,val42); val34 = tmp; tmp = std::min(val35,val43); val43 = std::max(val35,val43); val35 = tmp; tmp = std::min(val36,val44); val44 = std::max(val36,val44); val36 = tmp; tmp = std::min(val37,val45); val45 = std::max(val37,val45); val37 = tmp; tmp = std::min(val38,val46); val46 = std::max(val38,val46); val38 = tmp; tmp = std::min(val39,val47); val47 = std::max(val39,val47); val39 = tmp; tmp = std::min(val8,val32); val32 = std::max(val8,val32); val8 = tmp; tmp = std::min(val9,val33); val33 = std::max(val9,val33); val9 = tmp; tmp = std::min(val10,val34); val34 = std::max(val10,val34); val10 = tmp; tmp = std::min(val11,val35); val35 = std::max(val11,val35); val11 = tmp; tmp = std::min(val12,val36); val36 = std::max(val12,val36); val12 = tmp; tmp = std::min(val13,val37); val37 = std::max(val13,val37); val13 = tmp; tmp = std::min(val14,val38); val38 = std::max(val14,val38); val14 = tmp; tmp = std::min(val15,val39); val39 = std::max(val15,val39); val15 = tmp; tmp = std::min(val24,val48); val48 = std::max(val24,val48); val24 = tmp; tmp = std::min(val8,val16); val16 = std::max(val8,val16); val8 = tmp; tmp = std::min(val9,val17); val17 = std::max(val9,val17); val9 = tmp; tmp = std::min(val10,val18); val18 = std::max(val10,val18); val10 = tmp; tmp = std::min(val11,val19); val19 = std::max(val11,val19); val11 = tmp; tmp = std::min(val12,val20); val20 = std::max(val12,val20); val12 = tmp; tmp = std::min(val13,val21); val21 = std::max(val13,val21); val13 = tmp; tmp = std::min(val14,val22); val22 = std::max(val14,val22); val14 = tmp; tmp = std::min(val15,val23); val23 = std::max(val15,val23); val15 = tmp; tmp = std::min(val24,val32); val32 = std::max(val24,val32); val24 = tmp; tmp = std::min(val25,val33); val33 = std::max(val25,val33); val25 = tmp; tmp = std::min(val26,val34); val34 = std::max(val26,val34); val26 = tmp; tmp = std::min(val27,val35); val35 = std::max(val27,val35); val27 = tmp; tmp = std::min(val28,val36); val36 = std::max(val28,val36); val28 = tmp; tmp = std::min(val29,val37); val37 = std::max(val29,val37); val29 = tmp; tmp = std::min(val30,val38); val38 = std::max(val30,val38); val30 = tmp; tmp = std::min(val31,val39); val39 = std::max(val31,val39); val31 = tmp; tmp = std::min(val40,val48); val48 = std::max(val40,val48); val40 = tmp; tmp = std::min(val0,val4); val4 = std::max(val0,val4); val0 = tmp; tmp = std::min(val1,val5); val5 = std::max(val1,val5); val1 = tmp; tmp = std::min(val2,val6); val6 = std::max(val2,val6); val2 = tmp; tmp = std::min(val3,val7); val7 = std::max(val3,val7); val3 = tmp; tmp = std::min(val8,val12); val12 = std::max(val8,val12); val8 = tmp; tmp = std::min(val9,val13); val13 = std::max(val9,val13); val9 = tmp; tmp = std::min(val10,val14); val14 = std::max(val10,val14); val10 = tmp; tmp = std::min(val11,val15); val15 = std::max(val11,val15); val11 = tmp; tmp = std::min(val16,val20); val20 = std::max(val16,val20); val16 = tmp; tmp = std::min(val17,val21); val21 = std::max(val17,val21); val17 = tmp; tmp = std::min(val18,val22); val22 = std::max(val18,val22); val18 = tmp; tmp = std::min(val19,val23); val23 = std::max(val19,val23); val19 = tmp; tmp = std::min(val24,val28); val28 = std::max(val24,val28); val24 = tmp; tmp = std::min(val25,val29); val29 = std::max(val25,val29); val25 = tmp; tmp = std::min(val26,val30); val30 = std::max(val26,val30); val26 = tmp; tmp = std::min(val27,val31); val31 = std::max(val27,val31); val27 = tmp; tmp = std::min(val32,val36); val36 = std::max(val32,val36); val32 = tmp; tmp = std::min(val33,val37); val37 = std::max(val33,val37); val33 = tmp; tmp = std::min(val34,val38); val38 = std::max(val34,val38); val34 = tmp; tmp = std::min(val35,val39); val39 = std::max(val35,val39); val35 = tmp; tmp = std::min(val40,val44); val44 = std::max(val40,val44); val40 = tmp; tmp = std::min(val41,val45); val45 = std::max(val41,val45); val41 = tmp; tmp = std::min(val42,val46); val46 = std::max(val42,val46); val42 = tmp; tmp = std::min(val43,val47); val47 = std::max(val43,val47); val43 = tmp; tmp = std::min(val4,val32); val32 = std::max(val4,val32); val4 = tmp; tmp = std::min(val5,val33); val33 = std::max(val5,val33); val5 = tmp; tmp = std::min(val6,val34); val34 = std::max(val6,val34); val6 = tmp; tmp = std::min(val7,val35); val35 = std::max(val7,val35); val7 = tmp; tmp = std::min(val12,val40); val40 = std::max(val12,val40); val12 = tmp; tmp = std::min(val13,val41); val41 = std::max(val13,val41); val13 = tmp; tmp = std::min(val14,val42); val42 = std::max(val14,val42); val14 = tmp; tmp = std::min(val15,val43); val43 = std::max(val15,val43); val15 = tmp; tmp = std::min(val20,val48); val48 = std::max(val20,val48); val20 = tmp; tmp = std::min(val4,val16); val16 = std::max(val4,val16); val4 = tmp; tmp = std::min(val5,val17); val17 = std::max(val5,val17); val5 = tmp; tmp = std::min(val6,val18); val18 = std::max(val6,val18); val6 = tmp; tmp = std::min(val7,val19); val19 = std::max(val7,val19); val7 = tmp; tmp = std::min(val12,val24); val24 = std::max(val12,val24); val12 = tmp; tmp = std::min(val13,val25); val25 = std::max(val13,val25); val13 = tmp; tmp = std::min(val14,val26); val26 = std::max(val14,val26); val14 = tmp; tmp = std::min(val15,val27); val27 = std::max(val15,val27); val15 = tmp; tmp = std::min(val20,val32); val32 = std::max(val20,val32); val20 = tmp; tmp = std::min(val21,val33); val33 = std::max(val21,val33); val21 = tmp; tmp = std::min(val22,val34); val34 = std::max(val22,val34); val22 = tmp; tmp = std::min(val23,val35); val35 = std::max(val23,val35); val23 = tmp; tmp = std::min(val28,val40); val40 = std::max(val28,val40); val28 = tmp; tmp = std::min(val29,val41); val41 = std::max(val29,val41); val29 = tmp; tmp = std::min(val30,val42); val42 = std::max(val30,val42); val30 = tmp; tmp = std::min(val31,val43); val43 = std::max(val31,val43); val31 = tmp; tmp = std::min(val36,val48); val48 = std::max(val36,val48); val36 = tmp; tmp = std::min(val4,val8); val8 = std::max(val4,val8); val4 = tmp; tmp = std::min(val5,val9); val9 = std::max(val5,val9); val5 = tmp; tmp = std::min(val6,val10); val10 = std::max(val6,val10); val6 = tmp; tmp = std::min(val7,val11); val11 = std::max(val7,val11); val7 = tmp; tmp = std::min(val12,val16); val16 = std::max(val12,val16); val12 = tmp; tmp = std::min(val13,val17); val17 = std::max(val13,val17); val13 = tmp; tmp = std::min(val14,val18); val18 = std::max(val14,val18); val14 = tmp; tmp = std::min(val15,val19); val19 = std::max(val15,val19); val15 = tmp; tmp = std::min(val20,val24); val24 = std::max(val20,val24); val20 = tmp; tmp = std::min(val21,val25); val25 = std::max(val21,val25); val21 = tmp; tmp = std::min(val22,val26); val26 = std::max(val22,val26); val22 = tmp; tmp = std::min(val23,val27); val27 = std::max(val23,val27); val23 = tmp; tmp = std::min(val28,val32); val32 = std::max(val28,val32); val28 = tmp; tmp = std::min(val29,val33); val33 = std::max(val29,val33); val29 = tmp; tmp = std::min(val30,val34); val34 = std::max(val30,val34); val30 = tmp; tmp = std::min(val31,val35); val35 = std::max(val31,val35); val31 = tmp; tmp = std::min(val36,val40); val40 = std::max(val36,val40); val36 = tmp; tmp = std::min(val37,val41); val41 = std::max(val37,val41); val37 = tmp; tmp = std::min(val38,val42); val42 = std::max(val38,val42); val38 = tmp; tmp = std::min(val39,val43); val43 = std::max(val39,val43); val39 = tmp; tmp = std::min(val44,val48); val48 = std::max(val44,val48); val44 = tmp; tmp = std::min(val0,val2); val2 = std::max(val0,val2); val0 = tmp; tmp = std::min(val1,val3); val3 = std::max(val1,val3); val1 = tmp; tmp = std::min(val4,val6); val6 = std::max(val4,val6); val4 = tmp; tmp = std::min(val5,val7); val7 = std::max(val5,val7); val5 = tmp; tmp = std::min(val8,val10); val10 = std::max(val8,val10); val8 = tmp; tmp = std::min(val9,val11); val11 = std::max(val9,val11); val9 = tmp; tmp = std::min(val12,val14); val14 = std::max(val12,val14); val12 = tmp; tmp = std::min(val13,val15); val15 = std::max(val13,val15); val13 = tmp; tmp = std::min(val16,val18); val18 = std::max(val16,val18); val16 = tmp; tmp = std::min(val17,val19); val19 = std::max(val17,val19); val17 = tmp; tmp = std::min(val20,val22); val22 = std::max(val20,val22); val20 = tmp; tmp = std::min(val21,val23); val23 = std::max(val21,val23); val21 = tmp; tmp = std::min(val24,val26); val26 = std::max(val24,val26); val24 = tmp; tmp = std::min(val25,val27); val27 = std::max(val25,val27); val25 = tmp; tmp = std::min(val28,val30); val30 = std::max(val28,val30); val28 = tmp; tmp = std::min(val29,val31); val31 = std::max(val29,val31); val29 = tmp; tmp = std::min(val32,val34); val34 = std::max(val32,val34); val32 = tmp; tmp = std::min(val33,val35); val35 = std::max(val33,val35); val33 = tmp; tmp = std::min(val36,val38); val38 = std::max(val36,val38); val36 = tmp; tmp = std::min(val37,val39); val39 = std::max(val37,val39); val37 = tmp; tmp = std::min(val40,val42); val42 = std::max(val40,val42); val40 = tmp; tmp = std::min(val41,val43); val43 = std::max(val41,val43); val41 = tmp; tmp = std::min(val44,val46); val46 = std::max(val44,val46); val44 = tmp; tmp = std::min(val45,val47); val47 = std::max(val45,val47); val45 = tmp; tmp = std::min(val2,val32); val32 = std::max(val2,val32); val2 = tmp; tmp = std::min(val3,val33); val33 = std::max(val3,val33); val3 = tmp; tmp = std::min(val6,val36); val36 = std::max(val6,val36); val6 = tmp; tmp = std::min(val7,val37); val37 = std::max(val7,val37); val7 = tmp; tmp = std::min(val10,val40); val40 = std::max(val10,val40); val10 = tmp; tmp = std::min(val11,val41); val41 = std::max(val11,val41); val11 = tmp; tmp = std::min(val14,val44); val44 = std::max(val14,val44); val14 = tmp; tmp = std::min(val15,val45); val45 = std::max(val15,val45); val15 = tmp; tmp = std::min(val18,val48); val48 = std::max(val18,val48); val18 = tmp; tmp = std::min(val2,val16); val16 = std::max(val2,val16); val2 = tmp; tmp = std::min(val3,val17); val17 = std::max(val3,val17); val3 = tmp; tmp = std::min(val6,val20); val20 = std::max(val6,val20); val6 = tmp; tmp = std::min(val7,val21); val21 = std::max(val7,val21); val7 = tmp; tmp = std::min(val10,val24); val24 = std::max(val10,val24); val10 = tmp; tmp = std::min(val11,val25); val25 = std::max(val11,val25); val11 = tmp; tmp = std::min(val14,val28); val28 = std::max(val14,val28); val14 = tmp; tmp = std::min(val15,val29); val29 = std::max(val15,val29); val15 = tmp; tmp = std::min(val18,val32); val32 = std::max(val18,val32); val18 = tmp; tmp = std::min(val19,val33); val33 = std::max(val19,val33); val19 = tmp; tmp = std::min(val22,val36); val36 = std::max(val22,val36); val22 = tmp; tmp = std::min(val23,val37); val37 = std::max(val23,val37); val23 = tmp; tmp = std::min(val26,val40); val40 = std::max(val26,val40); val26 = tmp; tmp = std::min(val27,val41); val41 = std::max(val27,val41); val27 = tmp; tmp = std::min(val30,val44); val44 = std::max(val30,val44); val30 = tmp; tmp = std::min(val31,val45); val45 = std::max(val31,val45); val31 = tmp; tmp = std::min(val34,val48); val48 = std::max(val34,val48); val34 = tmp; tmp = std::min(val2,val8); val8 = std::max(val2,val8); val2 = tmp; tmp = std::min(val3,val9); val9 = std::max(val3,val9); val3 = tmp; tmp = std::min(val6,val12); val12 = std::max(val6,val12); val6 = tmp; tmp = std::min(val7,val13); val13 = std::max(val7,val13); val7 = tmp; tmp = std::min(val10,val16); val16 = std::max(val10,val16); val10 = tmp; tmp = std::min(val11,val17); val17 = std::max(val11,val17); val11 = tmp; tmp = std::min(val14,val20); val20 = std::max(val14,val20); val14 = tmp; tmp = std::min(val15,val21); val21 = std::max(val15,val21); val15 = tmp; tmp = std::min(val18,val24); val24 = std::max(val18,val24); val18 = tmp; tmp = std::min(val19,val25); val25 = std::max(val19,val25); val19 = tmp; tmp = std::min(val22,val28); val28 = std::max(val22,val28); val22 = tmp; tmp = std::min(val23,val29); val29 = std::max(val23,val29); val23 = tmp; tmp = std::min(val26,val32); val32 = std::max(val26,val32); val26 = tmp; tmp = std::min(val27,val33); val33 = std::max(val27,val33); val27 = tmp; tmp = std::min(val30,val36); val36 = std::max(val30,val36); val30 = tmp; tmp = std::min(val31,val37); val37 = std::max(val31,val37); val31 = tmp; tmp = std::min(val34,val40); val40 = std::max(val34,val40); val34 = tmp; tmp = std::min(val35,val41); val41 = std::max(val35,val41); val35 = tmp; tmp = std::min(val38,val44); val44 = std::max(val38,val44); val38 = tmp; tmp = std::min(val39,val45); val45 = std::max(val39,val45); val39 = tmp; tmp = std::min(val42,val48); val48 = std::max(val42,val48); val42 = tmp; tmp = std::min(val2,val4); val4 = std::max(val2,val4); val2 = tmp; tmp = std::min(val3,val5); val5 = std::max(val3,val5); val3 = tmp; tmp = std::min(val6,val8); val8 = std::max(val6,val8); val6 = tmp; tmp = std::min(val7,val9); val9 = std::max(val7,val9); val7 = tmp; tmp = std::min(val10,val12); val12 = std::max(val10,val12); val10 = tmp; tmp = std::min(val11,val13); val13 = std::max(val11,val13); val11 = tmp; tmp = std::min(val14,val16); val16 = std::max(val14,val16); val14 = tmp; tmp = std::min(val15,val17); val17 = std::max(val15,val17); val15 = tmp; tmp = std::min(val18,val20); val20 = std::max(val18,val20); val18 = tmp; tmp = std::min(val19,val21); val21 = std::max(val19,val21); val19 = tmp; tmp = std::min(val22,val24); val24 = std::max(val22,val24); val22 = tmp; tmp = std::min(val23,val25); val25 = std::max(val23,val25); val23 = tmp; tmp = std::min(val26,val28); val28 = std::max(val26,val28); val26 = tmp; tmp = std::min(val27,val29); val29 = std::max(val27,val29); val27 = tmp; tmp = std::min(val30,val32); val32 = std::max(val30,val32); val30 = tmp; tmp = std::min(val31,val33); val33 = std::max(val31,val33); val31 = tmp; tmp = std::min(val34,val36); val36 = std::max(val34,val36); val34 = tmp; tmp = std::min(val35,val37); val37 = std::max(val35,val37); val35 = tmp; tmp = std::min(val38,val40); val40 = std::max(val38,val40); val38 = tmp; tmp = std::min(val39,val41); val41 = std::max(val39,val41); val39 = tmp; tmp = std::min(val42,val44); val44 = std::max(val42,val44); val42 = tmp; tmp = std::min(val43,val45); val45 = std::max(val43,val45); val43 = tmp; tmp = std::min(val46,val48); val48 = std::max(val46,val48); val46 = tmp; val1 = std::max(val0,val1); val3 = std::max(val2,val3); val5 = std::max(val4,val5); val7 = std::max(val6,val7); val9 = std::max(val8,val9); val11 = std::max(val10,val11); val13 = std::max(val12,val13); val15 = std::max(val14,val15); val17 = std::max(val16,val17); val19 = std::max(val18,val19); val21 = std::max(val20,val21); val23 = std::max(val22,val23); val24 = std::min(val24,val25); val26 = std::min(val26,val27); val28 = std::min(val28,val29); val30 = std::min(val30,val31); val32 = std::min(val32,val33); val34 = std::min(val34,val35); val36 = std::min(val36,val37); val38 = std::min(val38,val39); val40 = std::min(val40,val41); val42 = std::min(val42,val43); val44 = std::min(val44,val45); val46 = std::min(val46,val47); val32 = std::max(val1,val32); val34 = std::max(val3,val34); val36 = std::max(val5,val36); val38 = std::max(val7,val38); val9 = std::min(val9,val40); val11 = std::min(val11,val42); val13 = std::min(val13,val44); val15 = std::min(val15,val46); val17 = std::min(val17,val48); val24 = std::max(val9,val24); val26 = std::max(val11,val26); val28 = std::max(val13,val28); val30 = std::max(val15,val30); val17 = std::min(val17,val32); val19 = std::min(val19,val34); val21 = std::min(val21,val36); val23 = std::min(val23,val38); val24 = std::max(val17,val24); val26 = std::max(val19,val26); val21 = std::min(val21,val28); val23 = std::min(val23,val30); val24 = std::max(val21,val24); val23 = std::min(val23,val26); return std::max(val23,val24); } //! Return sqrt(x^2 + y^2). template<typename T> inline T hypot(const T x, const T y) { return std::sqrt(x*x + y*y); } template<typename T> inline T hypot(const T x, const T y, const T z) { return std::sqrt(x*x + y*y + z*z); } template<typename T> inline T _hypot(const T x, const T y) { // Slower but more precise version T nx = cimg::abs(x), ny = cimg::abs(y), t; if (nx<ny) { t = nx; nx = ny; } else t = ny; if (nx>0) { t/=nx; return nx*std::sqrt(1 + t*t); } return 0; } //! Return the factorial of n inline double factorial(const int n) { if (n<0) return cimg::type<double>::nan(); if (n<2) return 1; double res = 2; for (int i = 3; i<=n; ++i) res*=i; return res; } //! Return the number of permutations of k objects in a set of n objects. inline double permutations(const int k, const int n, const bool with_order) { if (n<0 || k<0) return cimg::type<double>::nan(); if (k>n) return 0; double res = 1; for (int i = n; i>=n - k + 1; --i) res*=i; return with_order?res:res/cimg::factorial(k); } inline double _fibonacci(int exp) { double base = (1 + std::sqrt(5.))/2, result = 1/std::sqrt(5.); while (exp) { if (exp&1) result*=base; exp>>=1; base*=base; } return result; } //! Calculate fibonacci number. // (Precise up to n = 78, less precise for n>78). inline double fibonacci(const int n) { if (n<0) return cimg::type<double>::nan(); if (n<3) return 1; if (n<11) { cimg_uint64 fn1 = 1, fn2 = 1, fn = 0; for (int i = 3; i<=n; ++i) { fn = fn1 + fn2; fn2 = fn1; fn1 = fn; } return (double)fn; } if (n<75) // precise up to n = 74, faster than the integer calculation above for n>10 return (double)((cimg_uint64)(_fibonacci(n) + 0.5)); if (n<94) { // precise up to n = 78, less precise for n>78 up to n = 93, overflows for n>93 cimg_uint64 fn1 = (cimg_uint64)1304969544928657ULL, fn2 = (cimg_uint64)806515533049393ULL, fn = 0; for (int i = 75; i<=n; ++i) { fn = fn1 + fn2; fn2 = fn1; fn1 = fn; } return (double)fn; } return _fibonacci(n); // Not precise, but better than the wrong overflowing calculation } //! Calculate greatest common divisor. inline long gcd(long a, long b) { while (a) { const long c = a; a = b%a; b = c; } return b; } //! Convert Ascii character to lower case. inline char lowercase(const char x) { return (char)((x<'A'||x>'Z')?x:x - 'A' + 'a'); } inline double lowercase(const double x) { return (double)((x<'A'||x>'Z')?x:x - 'A' + 'a'); } //! Convert C-string to lower case. inline void lowercase(char *const str) { if (str) for (char *ptr = str; *ptr; ++ptr) *ptr = lowercase(*ptr); } //! Convert Ascii character to upper case. inline char uppercase(const char x) { return (char)((x<'a'||x>'z')?x:x - 'a' + 'A'); } inline double uppercase(const double x) { return (double)((x<'a'||x>'z')?x:x - 'a' + 'A'); } //! Convert C-string to upper case. inline void uppercase(char *const str) { if (str) for (char *ptr = str; *ptr; ++ptr) *ptr = uppercase(*ptr); } //! Return \c true if input character is blank (space, tab, or non-printable character). inline bool is_blank(const char c) { return c>=0 && c<=' '; } //! Read value in a C-string. /** \param str C-string containing the float value to read. \return Read value. \note Same as <tt>std::atof()</tt> extended to manage the retrieval of fractions from C-strings, as in <em>"1/2"</em>. **/ inline double atof(const char *const str) { double x = 0, y = 1; return str && cimg_sscanf(str,"%lf/%lf",&x,&y)>0?x/y:0; } //! Compare the first \p l characters of two C-strings, ignoring the case. /** \param str1 C-string. \param str2 C-string. \param l Number of characters to compare. \return \c 0 if the two strings are equal, something else otherwise. \note This function has to be defined since it is not provided by all C++-compilers (not ANSI). **/ inline int strncasecmp(const char *const str1, const char *const str2, const int l) { if (!l) return 0; if (!str1) return str2?-1:0; const char *nstr1 = str1, *nstr2 = str2; int k, diff = 0; for (k = 0; k<l && !(diff = lowercase(*nstr1) - lowercase(*nstr2)); ++k) { ++nstr1; ++nstr2; } return k!=l?diff:0; } //! Compare two C-strings, ignoring the case. /** \param str1 C-string. \param str2 C-string. \return \c 0 if the two strings are equal, something else otherwise. \note This function has to be defined since it is not provided by all C++-compilers (not ANSI). **/ inline int strcasecmp(const char *const str1, const char *const str2) { if (!str1) return str2?-1:0; const int l1 = (int)std::strlen(str1), l2 = (int)std::strlen(str2); return cimg::strncasecmp(str1,str2,1 + (l1<l2?l1:l2)); } //! Ellipsize a string. /** \param str C-string. \param l Max number of characters. \param is_ending Tell if the dots are placed at the end or at the center of the ellipsized string. **/ inline char *strellipsize(char *const str, const unsigned int l=64, const bool is_ending=true) { if (!str) return str; const unsigned int nl = l<5?5:l, ls = (unsigned int)std::strlen(str); if (ls<=nl) return str; if (is_ending) std::strcpy(str + nl - 5,"(...)"); else { const unsigned int ll = (nl - 5)/2 + 1 - (nl%2), lr = nl - ll - 5; std::strcpy(str + ll,"(...)"); std::memmove(str + ll + 5,str + ls - lr,lr); } str[nl] = 0; return str; } //! Ellipsize a string. /** \param str C-string. \param res output C-string. \param l Max number of characters. \param is_ending Tell if the dots are placed at the end or at the center of the ellipsized string. **/ inline char *strellipsize(const char *const str, char *const res, const unsigned int l=64, const bool is_ending=true) { const unsigned int nl = l<5?5:l, ls = (unsigned int)std::strlen(str); if (ls<=nl) { std::strcpy(res,str); return res; } if (is_ending) { std::strncpy(res,str,nl - 5); std::strcpy(res + nl -5,"(...)"); } else { const unsigned int ll = (nl - 5)/2 + 1 - (nl%2), lr = nl - ll - 5; std::strncpy(res,str,ll); std::strcpy(res + ll,"(...)"); std::strncpy(res + ll + 5,str + ls - lr,lr); } res[nl] = 0; return res; } //! Remove delimiters on the start and/or end of a C-string. /** \param[in,out] str C-string to work with (modified at output). \param delimiter Delimiter character code to remove. \param is_symmetric Tells if the removal is done only if delimiters are symmetric (both at the beginning and the end of \c s). \param is_iterative Tells if the removal is done if several iterations are possible. \return \c true if delimiters have been removed, \c false otherwise. **/ inline bool strpare(char *const str, const char delimiter, const bool is_symmetric, const bool is_iterative) { if (!str) return false; const int l = (int)std::strlen(str); int p, q; if (is_symmetric) for (p = 0, q = l - 1; p<q && str[p]==delimiter && str[q]==delimiter; ) { --q; ++p; if (!is_iterative) break; } else { for (p = 0; p<l && str[p]==delimiter; ) { ++p; if (!is_iterative) break; } for (q = l - 1; q>p && str[q]==delimiter; ) { --q; if (!is_iterative) break; } } const int n = q - p + 1; if (n!=l) { std::memmove(str,str + p,(unsigned int)n); str[n] = 0; return true; } return false; } //! Remove white spaces on the start and/or end of a C-string. inline bool strpare(char *const str, const bool is_symmetric, const bool is_iterative) { if (!str) return false; const int l = (int)std::strlen(str); int p, q; if (is_symmetric) for (p = 0, q = l - 1; p<q && is_blank(str[p]) && is_blank(str[q]); ) { --q; ++p; if (!is_iterative) break; } else { for (p = 0; p<l && is_blank(str[p]); ) { ++p; if (!is_iterative) break; } for (q = l - 1; q>p && is_blank(str[q]); ) { --q; if (!is_iterative) break; } } const int n = q - p + 1; if (n!=l) { std::memmove(str,str + p,(unsigned int)n); str[n] = 0; return true; } return false; } //! Replace reserved characters (for Windows filename) by another character. /** \param[in,out] str C-string to work with (modified at output). \param[in] c Replacement character. **/ inline void strwindows_reserved(char *const str, const char c='_') { for (char *s = str; *s; ++s) { const char i = *s; if (i=='<' || i=='>' || i==':' || i=='\"' || i=='/' || i=='\\' || i=='|' || i=='?' || i=='*') *s = c; } } //! Replace escape sequences in C-strings by their binary Ascii values. /** \param[in,out] str C-string to work with (modified at output). **/ inline void strunescape(char *const str) { #define cimg_strunescape(ci,co) case ci : *nd = co; ++ns; break; unsigned int val = 0; for (char *ns = str, *nd = str; *ns || (bool)(*nd=0); ++nd) if (*ns=='\\') switch (*(++ns)) { cimg_strunescape('a','\a'); cimg_strunescape('b','\b'); cimg_strunescape('e',0x1B); cimg_strunescape('f','\f'); cimg_strunescape('n','\n'); cimg_strunescape('r','\r'); cimg_strunescape('t','\t'); cimg_strunescape('v','\v'); cimg_strunescape('\\','\\'); cimg_strunescape('\'','\''); cimg_strunescape('\"','\"'); cimg_strunescape('\?','\?'); case 0 : *nd = 0; break; case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : cimg_sscanf(ns,"%o",&val); while (*ns>='0' && *ns<='7') ++ns; *nd = (char)val; break; case 'x' : cimg_sscanf(++ns,"%x",&val); while ((*ns>='0' && *ns<='9') || (*ns>='a' && *ns<='f') || (*ns>='A' && *ns<='F')) ++ns; *nd = (char)val; break; default : *nd = *(ns++); } else *nd = *(ns++); } // Return a temporary string describing the size of a memory buffer. inline const char *strbuffersize(const cimg_ulong size); // Return string that identifies the running OS. inline const char *stros() { #if defined(linux) || defined(__linux) || defined(__linux__) static const char *const str = "Linux"; #elif defined(sun) || defined(__sun) static const char *const str = "Sun OS"; #elif defined(BSD) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__) || defined (__DragonFly__) static const char *const str = "BSD"; #elif defined(sgi) || defined(__sgi) static const char *const str = "Irix"; #elif defined(__MACOSX__) || defined(__APPLE__) static const char *const str = "Mac OS"; #elif defined(unix) || defined(__unix) || defined(__unix__) static const char *const str = "Generic Unix"; #elif defined(_MSC_VER) || defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || \ defined(WIN64) || defined(_WIN64) || defined(__WIN64__) static const char *const str = "Windows"; #else const char *const _str1 = std::getenv("OSTYPE"), *const _str2 = _str1?_str1:std::getenv("OS"), *const str = _str2?_str2:"Unknown OS"; #endif return str; } //! Return the basename of a filename. inline const char* basename(const char *const s, const char separator=cimg_file_separator) { const char *p = 0, *np = s; while (np>=s && (p=np)) np = std::strchr(np,separator) + 1; return p; } // Return a random filename. inline const char* filenamerand() { cimg::mutex(6); static char randomid[9]; for (unsigned int k = 0; k<8; ++k) { const int v = (int)cimg::rand(65535)%3; randomid[k] = (char)(v==0?('0' + ((int)cimg::rand(65535)%10)): (v==1?('a' + ((int)cimg::rand(65535)%26)): ('A' + ((int)cimg::rand(65535)%26)))); } cimg::mutex(6,0); return randomid; } // Convert filename as a Windows-style filename (short path name). inline void winformat_string(char *const str) { if (str && *str) { #if cimg_OS==2 char *const nstr = new char[MAX_PATH]; if (GetShortPathNameA(str,nstr,MAX_PATH)) std::strcpy(str,nstr); delete[] nstr; #endif } } // Open a file (similar to std:: fopen(), but with wide character support on Windows). inline std::FILE *std_fopen(const char *const path, const char *const mode); //! Open a file. /** \param path Path of the filename to open. \param mode C-string describing the opening mode. \return Opened file. \note Same as <tt>std::fopen()</tt> but throw a \c CImgIOException when the specified file cannot be opened, instead of returning \c 0. **/ inline std::FILE *fopen(const char *const path, const char *const mode) { if (!path) throw CImgArgumentException("cimg::fopen(): Specified file path is (null)."); if (!mode) throw CImgArgumentException("cimg::fopen(): File '%s', specified mode is (null).", path); std::FILE *res = 0; if (*path=='-' && (!path[1] || path[1]=='.')) { res = (*mode=='r')?cimg::_stdin():cimg::_stdout(); #if cimg_OS==2 if (*mode && mode[1]=='b') { // Force stdin/stdout to be in binary mode #ifdef __BORLANDC__ if (setmode(_fileno(res),0x8000)==-1) res = 0; #else if (_setmode(_fileno(res),0x8000)==-1) res = 0; #endif } #endif } else res = cimg::std_fopen(path,mode); if (!res) throw CImgIOException("cimg::fopen(): Failed to open file '%s' with mode '%s'.", path,mode); return res; } //! Close a file. /** \param file File to close. \return \c 0 if file has been closed properly, something else otherwise. \note Same as <tt>std::fclose()</tt> but display a warning message if the file has not been closed properly. **/ inline int fclose(std::FILE *file) { if (!file) { warn("cimg::fclose(): Specified file is (null)."); return 0; } if (file==cimg::_stdin(false) || file==cimg::_stdout(false)) return 0; const int errn = std::fclose(file); if (errn!=0) warn("cimg::fclose(): Error code %d returned during file closing.", errn); return errn; } //! Version of 'fseek()' that supports >=64bits offsets everywhere (for Windows). inline int fseek(FILE *stream, cimg_long offset, int origin) { #if defined(WIN64) || defined(_WIN64) || defined(__WIN64__) return _fseeki64(stream,(__int64)offset,origin); #else return std::fseek(stream,offset,origin); #endif } //! Version of 'ftell()' that supports >=64bits offsets everywhere (for Windows). inline cimg_long ftell(FILE *stream) { #if defined(WIN64) || defined(_WIN64) || defined(__WIN64__) return (cimg_long)_ftelli64(stream); #else return (cimg_long)std::ftell(stream); #endif } //! Check if a path is a directory. /** \param path Specified path to test. **/ inline bool is_directory(const char *const path) { if (!path || !*path) return false; #if cimg_OS==1 struct stat st_buf; return (!stat(path,&st_buf) && S_ISDIR(st_buf.st_mode)); #elif cimg_OS==2 const unsigned int res = (unsigned int)GetFileAttributesA(path); return res==INVALID_FILE_ATTRIBUTES?false:(res&16); #else return false; #endif } //! Check if a path is a file. /** \param path Specified path to test. **/ inline bool is_file(const char *const path) { if (!path || !*path) return false; std::FILE *const file = cimg::std_fopen(path,"rb"); if (!file) return false; cimg::fclose(file); return !is_directory(path); } //! Get file size. /** \param filename Specified filename to get size from. \return File size or '-1' if file does not exist. **/ inline cimg_int64 fsize(const char *const filename) { std::FILE *const file = cimg::std_fopen(filename,"rb"); if (!file) return (cimg_int64)-1; std::fseek(file,0,SEEK_END); const cimg_int64 siz = (cimg_int64)std::ftell(file); cimg::fclose(file); return siz; } //! Get last write time of a given file or directory (multiple-attributes version). /** \param path Specified path to get attributes from. \param[in,out] attr Type of requested time attributes. Can be { 0=year | 1=month | 2=day | 3=day of week | 4=hour | 5=minute | 6=second } Replaced by read attributes after return (or -1 if an error occured). \param nb_attr Number of attributes to read/write. \return Latest read attribute. **/ template<typename T> inline int fdate(const char *const path, T *attr, const unsigned int nb_attr) { #define _cimg_fdate_err() for (unsigned int i = 0; i<nb_attr; ++i) attr[i] = (T)-1 int res = -1; if (!path || !*path) { _cimg_fdate_err(); return -1; } cimg::mutex(6); #if cimg_OS==2 HANDLE file = CreateFileA(path,GENERIC_READ,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0); if (file!=INVALID_HANDLE_VALUE) { FILETIME _ft; SYSTEMTIME ft; if (GetFileTime(file,0,0,&_ft) && FileTimeToSystemTime(&_ft,&ft)) { for (unsigned int i = 0; i<nb_attr; ++i) { res = (int)(attr[i]==0?ft.wYear:attr[i]==1?ft.wMonth:attr[i]==2?ft.wDay: attr[i]==3?ft.wDayOfWeek:attr[i]==4?ft.wHour:attr[i]==5?ft.wMinute: attr[i]==6?ft.wSecond:-1); attr[i] = (T)res; } } else _cimg_fdate_err(); CloseHandle(file); } else _cimg_fdate_err(); #elif cimg_OS==1 struct stat st_buf; if (!stat(path,&st_buf)) { const time_t _ft = st_buf.st_mtime; const struct tm& ft = *std::localtime(&_ft); for (unsigned int i = 0; i<nb_attr; ++i) { res = (int)(attr[i]==0?ft.tm_year + 1900:attr[i]==1?ft.tm_mon + 1:attr[i]==2?ft.tm_mday: attr[i]==3?ft.tm_wday:attr[i]==4?ft.tm_hour:attr[i]==5?ft.tm_min: attr[i]==6?ft.tm_sec:-1); attr[i] = (T)res; } } else _cimg_fdate_err(); #endif cimg::mutex(6,0); return res; } //! Get last write time of a given file or directory (single-attribute version). /** \param path Specified path to get attributes from. \param attr Type of requested time attributes. Can be { 0=year | 1=month | 2=day | 3=day of week | 4=hour | 5=minute | 6=second } \return Specified attribute or -1 if an error occured. **/ inline int fdate(const char *const path, unsigned int attr) { int out = (int)attr; return fdate(path,&out,1); } //! Get current local time (multiple-attributes version). /** \param[in,out] attr Type of requested time attributes. Can be { 0=year | 1=month | 2=day | 3=day of week | 4=hour | 5=minute | 6=second } Replaced by read attributes after return (or -1 if an error occured). \param nb_attr Number of attributes to read/write. \return Latest read attribute. **/ template<typename T> inline int date(T *attr, const unsigned int nb_attr) { int res = -1; cimg::mutex(6); #if cimg_OS==2 SYSTEMTIME st; GetLocalTime(&st); for (unsigned int i = 0; i<nb_attr; ++i) { res = (int)(attr[i]==0?st.wYear:attr[i]==1?st.wMonth:attr[i]==2?st.wDay: attr[i]==3?st.wDayOfWeek:attr[i]==4?st.wHour:attr[i]==5?st.wMinute: attr[i]==6?st.wSecond:-1); attr[i] = (T)res; } #else time_t _st; std::time(&_st); struct tm *st = std::localtime(&_st); for (unsigned int i = 0; i<nb_attr; ++i) { res = (int)(attr[i]==0?st->tm_year + 1900:attr[i]==1?st->tm_mon + 1:attr[i]==2?st->tm_mday: attr[i]==3?st->tm_wday:attr[i]==4?st->tm_hour:attr[i]==5?st->tm_min: attr[i]==6?st->tm_sec:-1); attr[i] = (T)res; } #endif cimg::mutex(6,0); return res; } //! Get current local time (single-attribute version). /** \param attr Type of requested time attribute. Can be { 0=year | 1=month | 2=day | 3=day of week | 4=hour | 5=minute | 6=second } \return Specified attribute or -1 if an error occured. **/ inline int date(unsigned int attr) { int out = (int)attr; return date(&out,1); } // Get/set path to store temporary files. inline const char* temporary_path(const char *const user_path=0, const bool reinit_path=false); // Get/set path to the <i>Program Files/</i> directory (Windows only). #if cimg_OS==2 inline const char* programfiles_path(const char *const user_path=0, const bool reinit_path=false); #endif // Get/set path to the ImageMagick's \c convert binary. inline const char* imagemagick_path(const char *const user_path=0, const bool reinit_path=false); // Get/set path to the GraphicsMagick's \c gm binary. inline const char* graphicsmagick_path(const char *const user_path=0, const bool reinit_path=false); // Get/set path to the XMedcon's \c medcon binary. inline const char* medcon_path(const char *const user_path=0, const bool reinit_path=false); // Get/set path to the FFMPEG's \c ffmpeg binary. inline const char *ffmpeg_path(const char *const user_path=0, const bool reinit_path=false); // Get/set path to the \c gzip binary. inline const char *gzip_path(const char *const user_path=0, const bool reinit_path=false); // Get/set path to the \c gunzip binary. inline const char *gunzip_path(const char *const user_path=0, const bool reinit_path=false); // Get/set path to the \c dcraw binary. inline const char *dcraw_path(const char *const user_path=0, const bool reinit_path=false); // Get/set path to the \c wget binary. inline const char *wget_path(const char *const user_path=0, const bool reinit_path=false); // Get/set path to the \c curl binary. inline const char *curl_path(const char *const user_path=0, const bool reinit_path=false); //! Split filename into two C-strings \c body and \c extension. /** filename and body must not overlap! **/ inline const char *split_filename(const char *const filename, char *const body=0) { if (!filename) { if (body) *body = 0; return 0; } const char *p = 0; for (const char *np = filename; np>=filename && (p=np); np = std::strchr(np,'.') + 1) {} if (p==filename || std::strchr(p,'/') || std::strchr(p,'\\')) { if (body) std::strcpy(body,filename); return filename + std::strlen(filename); } const unsigned int l = (unsigned int)(p - filename - 1); if (body) { if (l) std::memcpy(body,filename,l); body[l] = 0; } return p; } //! Generate a numbered version of a filename. inline char* number_filename(const char *const filename, const int number, const unsigned int digits, char *const str) { if (!filename) { if (str) *str = 0; return 0; } char *const format = new char[1024], *const body = new char[1024]; const char *const ext = cimg::split_filename(filename,body); if (*ext) cimg_snprintf(format,1024,"%%s_%%.%ud.%%s",digits); else cimg_snprintf(format,1024,"%%s_%%.%ud",digits); cimg_sprintf(str,format,body,number,ext); delete[] format; delete[] body; return str; } //! Read data from file. /** \param[out] ptr Pointer to memory buffer that will contain the binary data read from file. \param nmemb Number of elements to read. \param stream File to read data from. \return Number of read elements. \note Same as <tt>std::fread()</tt> but may display warning message if all elements could not be read. **/ template<typename T> inline size_t fread(T *const ptr, const size_t nmemb, std::FILE *stream) { if (!ptr || !stream) throw CImgArgumentException("cimg::fread(): Invalid reading request of %u %s%s from file %p to buffer %p.", nmemb,cimg::type<T>::string(),nmemb>1?"s":"",stream,ptr); if (!nmemb) return 0; const size_t wlimitT = 63*1024*1024, wlimit = wlimitT/sizeof(T); size_t to_read = nmemb, al_read = 0, l_to_read = 0, l_al_read = 0; do { l_to_read = (to_read*sizeof(T))<wlimitT?to_read:wlimit; l_al_read = std::fread((void*)(ptr + al_read),sizeof(T),l_to_read,stream); al_read+=l_al_read; to_read-=l_al_read; } while (l_to_read==l_al_read && to_read>0); if (to_read>0) warn("cimg::fread(): Only %lu/%lu elements could be read from file.", (unsigned long)al_read,(unsigned long)nmemb); return al_read; } //! Write data to file. /** \param ptr Pointer to memory buffer containing the binary data to write on file. \param nmemb Number of elements to write. \param[out] stream File to write data on. \return Number of written elements. \note Similar to <tt>std::fwrite</tt> but may display warning messages if all elements could not be written. **/ template<typename T> inline size_t fwrite(const T *ptr, const size_t nmemb, std::FILE *stream) { if (!ptr || !stream) throw CImgArgumentException("cimg::fwrite(): Invalid writing request of %u %s%s from buffer %p to file %p.", nmemb,cimg::type<T>::string(),nmemb>1?"s":"",ptr,stream); if (!nmemb) return 0; const size_t wlimitT = 63*1024*1024, wlimit = wlimitT/sizeof(T); size_t to_write = nmemb, al_write = 0, l_to_write = 0, l_al_write = 0; do { l_to_write = (to_write*sizeof(T))<wlimitT?to_write:wlimit; l_al_write = std::fwrite((void*)(ptr + al_write),sizeof(T),l_to_write,stream); al_write+=l_al_write; to_write-=l_al_write; } while (l_to_write==l_al_write && to_write>0); if (to_write>0) warn("cimg::fwrite(): Only %lu/%lu elements could be written in file.", (unsigned long)al_write,(unsigned long)nmemb); return al_write; } //! Create an empty file. /** \param file Input file (can be \c 0 if \c filename is set). \param filename Filename, as a C-string (can be \c 0 if \c file is set). **/ inline void fempty(std::FILE *const file, const char *const filename) { if (!file && !filename) throw CImgArgumentException("cimg::fempty(): Specified filename is (null)."); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); if (!file) cimg::fclose(nfile); } // Try to guess format from an image file. inline const char *ftype(std::FILE *const file, const char *const filename); // Load file from network as a local temporary file. inline char *load_network(const char *const url, char *const filename_local, const unsigned int timeout=0, const bool try_fallback=false, const char *const referer=0); //! Return options specified on the command line. inline const char* option(const char *const name, const int argc, const char *const *const argv, const char *const defaut, const char *const usage, const bool reset_static) { static bool first = true, visu = false; if (reset_static) { first = true; return 0; } const char *res = 0; if (first) { first = false; visu = cimg::option("-h",argc,argv,(char*)0,(char*)0,false)!=0; visu |= cimg::option("-help",argc,argv,(char*)0,(char*)0,false)!=0; visu |= cimg::option("--help",argc,argv,(char*)0,(char*)0,false)!=0; } if (!name && visu) { if (usage) { std::fprintf(cimg::output(),"\n %s%s%s",cimg::t_red,cimg::basename(argv[0]),cimg::t_normal); std::fprintf(cimg::output(),": %s",usage); std::fprintf(cimg::output()," (%s, %s)\n\n",cimg_date,cimg_time); } if (defaut) std::fprintf(cimg::output(),"%s\n",defaut); } if (name) { if (argc>0) { int k = 0; while (k<argc && std::strcmp(argv[k],name)) ++k; res = (k++==argc?defaut:(k==argc?argv[--k]:argv[k])); } else res = defaut; if (visu && usage) std::fprintf(cimg::output()," %s%-16s%s %-24s %s%s%s\n", cimg::t_bold,name,cimg::t_normal,res?res:"0", cimg::t_green,usage,cimg::t_normal); } return res; } inline const char* option(const char *const name, const int argc, const char *const *const argv, const char *const defaut, const char *const usage=0) { return option(name,argc,argv,defaut,usage,false); } inline bool option(const char *const name, const int argc, const char *const *const argv, const bool defaut, const char *const usage=0) { const char *const s = cimg::option(name,argc,argv,(char*)0); const bool res = s?(cimg::strcasecmp(s,"false") && cimg::strcasecmp(s,"off") && cimg::strcasecmp(s,"0")):defaut; cimg::option(name,0,0,res?"true":"false",usage); return res; } inline int option(const char *const name, const int argc, const char *const *const argv, const int defaut, const char *const usage=0) { const char *const s = cimg::option(name,argc,argv,(char*)0); const int res = s?std::atoi(s):defaut; char *const tmp = new char[256]; cimg_snprintf(tmp,256,"%d",res); cimg::option(name,0,0,tmp,usage); delete[] tmp; return res; } inline char option(const char *const name, const int argc, const char *const *const argv, const char defaut, const char *const usage=0) { const char *const s = cimg::option(name,argc,argv,(char*)0); const char res = s?*s:defaut; char tmp[8]; *tmp = res; tmp[1] = 0; cimg::option(name,0,0,tmp,usage); return res; } inline float option(const char *const name, const int argc, const char *const *const argv, const float defaut, const char *const usage=0) { const char *const s = cimg::option(name,argc,argv,(char*)0); const float res = s?(float)cimg::atof(s):defaut; char *const tmp = new char[256]; cimg_snprintf(tmp,256,"%g",res); cimg::option(name,0,0,tmp,usage); delete[] tmp; return res; } inline double option(const char *const name, const int argc, const char *const *const argv, const double defaut, const char *const usage=0) { const char *const s = cimg::option(name,argc,argv,(char*)0); const double res = s?cimg::atof(s):defaut; char *const tmp = new char[256]; cimg_snprintf(tmp,256,"%g",res); cimg::option(name,0,0,tmp,usage); delete[] tmp; return res; } //! Print information about \CImg environement variables. /** \note Output is done on the default output stream. **/ inline void info() { std::fprintf(cimg::output(),"\n %s%sCImg Library %u.%u.%u%s, compiled %s ( %s ) with the following flags:\n\n", cimg::t_red,cimg::t_bold,cimg_version/100,(cimg_version/10)%10,cimg_version%10, cimg::t_normal,cimg_date,cimg_time); std::fprintf(cimg::output()," > Operating System: %s%-13s%s %s('cimg_OS'=%d)%s\n", cimg::t_bold, cimg_OS==1?"Unix":(cimg_OS==2?"Windows":"Unknow"), cimg::t_normal,cimg::t_green, cimg_OS, cimg::t_normal); std::fprintf(cimg::output()," > CPU endianness: %s%s Endian%s\n", cimg::t_bold, cimg::endianness()?"Big":"Little", cimg::t_normal); std::fprintf(cimg::output()," > Verbosity mode: %s%-13s%s %s('cimg_verbosity'=%d)%s\n", cimg::t_bold, cimg_verbosity==0?"Quiet": cimg_verbosity==1?"Console": cimg_verbosity==2?"Dialog": cimg_verbosity==3?"Console+Warnings":"Dialog+Warnings", cimg::t_normal,cimg::t_green, cimg_verbosity, cimg::t_normal); std::fprintf(cimg::output()," > Stricts warnings: %s%-13s%s %s('cimg_strict_warnings' %s)%s\n", cimg::t_bold, #ifdef cimg_strict_warnings "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); std::fprintf(cimg::output()," > Support for C++11: %s%-13s%s %s('cimg_use_cpp11'=%d)%s\n", cimg::t_bold, cimg_use_cpp11?"Yes":"No", cimg::t_normal,cimg::t_green, (int)cimg_use_cpp11, cimg::t_normal); std::fprintf(cimg::output()," > Using VT100 messages: %s%-13s%s %s('cimg_use_vt100' %s)%s\n", cimg::t_bold, #ifdef cimg_use_vt100 "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); std::fprintf(cimg::output()," > Display type: %s%-13s%s %s('cimg_display'=%d)%s\n", cimg::t_bold, cimg_display==0?"No display":cimg_display==1?"X11":cimg_display==2?"Windows GDI":"Unknown", cimg::t_normal,cimg::t_green, (int)cimg_display, cimg::t_normal); #if cimg_display==1 std::fprintf(cimg::output()," > Using XShm for X11: %s%-13s%s %s('cimg_use_xshm' %s)%s\n", cimg::t_bold, #ifdef cimg_use_xshm "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); std::fprintf(cimg::output()," > Using XRand for X11: %s%-13s%s %s('cimg_use_xrandr' %s)%s\n", cimg::t_bold, #ifdef cimg_use_xrandr "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); #endif std::fprintf(cimg::output()," > Using OpenMP: %s%-13s%s %s('cimg_use_openmp' %s)%s\n", cimg::t_bold, #if cimg_use_openmp!=0 "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); std::fprintf(cimg::output()," > Using PNG library: %s%-13s%s %s('cimg_use_png' %s)%s\n", cimg::t_bold, #ifdef cimg_use_png "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); std::fprintf(cimg::output()," > Using JPEG library: %s%-13s%s %s('cimg_use_jpeg' %s)%s\n", cimg::t_bold, #ifdef cimg_use_jpeg "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); std::fprintf(cimg::output()," > Using TIFF library: %s%-13s%s %s('cimg_use_tiff' %s)%s\n", cimg::t_bold, #ifdef cimg_use_tiff "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); std::fprintf(cimg::output()," > Using Magick++ library: %s%-13s%s %s('cimg_use_magick' %s)%s\n", cimg::t_bold, #ifdef cimg_use_magick "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); std::fprintf(cimg::output()," > Using FFTW3 library: %s%-13s%s %s('cimg_use_fftw3' %s)%s\n", cimg::t_bold, #ifdef cimg_use_fftw3 "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); std::fprintf(cimg::output()," > Using LAPACK library: %s%-13s%s %s('cimg_use_lapack' %s)%s\n", cimg::t_bold, #ifdef cimg_use_lapack "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); char *const tmp = new char[1024]; cimg_snprintf(tmp,1024,"\"%.1020s\"",cimg::imagemagick_path()); std::fprintf(cimg::output()," > Path of ImageMagick: %s%-13s%s\n", cimg::t_bold, tmp, cimg::t_normal); cimg_snprintf(tmp,1024,"\"%.1020s\"",cimg::graphicsmagick_path()); std::fprintf(cimg::output()," > Path of GraphicsMagick: %s%-13s%s\n", cimg::t_bold, tmp, cimg::t_normal); cimg_snprintf(tmp,1024,"\"%.1020s\"",cimg::medcon_path()); std::fprintf(cimg::output()," > Path of 'medcon': %s%-13s%s\n", cimg::t_bold, tmp, cimg::t_normal); cimg_snprintf(tmp,1024,"\"%.1020s\"",cimg::temporary_path()); std::fprintf(cimg::output()," > Temporary path: %s%-13s%s\n", cimg::t_bold, tmp, cimg::t_normal); std::fprintf(cimg::output(),"\n"); delete[] tmp; } // Declare LAPACK function signatures if LAPACK support is enabled. #ifdef cimg_use_lapack template<typename T> inline void getrf(int &N, T *lapA, int *IPIV, int &INFO) { dgetrf_(&N,&N,lapA,&N,IPIV,&INFO); } inline void getrf(int &N, float *lapA, int *IPIV, int &INFO) { sgetrf_(&N,&N,lapA,&N,IPIV,&INFO); } template<typename T> inline void getri(int &N, T *lapA, int *IPIV, T* WORK, int &LWORK, int &INFO) { dgetri_(&N,lapA,&N,IPIV,WORK,&LWORK,&INFO); } inline void getri(int &N, float *lapA, int *IPIV, float* WORK, int &LWORK, int &INFO) { sgetri_(&N,lapA,&N,IPIV,WORK,&LWORK,&INFO); } template<typename T> inline void gesvd(char &JOB, int &M, int &N, T *lapA, int &MN, T *lapS, T *lapU, T *lapV, T *WORK, int &LWORK, int &INFO) { dgesvd_(&JOB,&JOB,&M,&N,lapA,&MN,lapS,lapU,&M,lapV,&N,WORK,&LWORK,&INFO); } inline void gesvd(char &JOB, int &M, int &N, float *lapA, int &MN, float *lapS, float *lapU, float *lapV, float *WORK, int &LWORK, int &INFO) { sgesvd_(&JOB,&JOB,&M,&N,lapA,&MN,lapS,lapU,&M,lapV,&N,WORK,&LWORK,&INFO); } template<typename T> inline void getrs(char &TRANS, int &N, T *lapA, int *IPIV, T *lapB, int &INFO) { int one = 1; dgetrs_(&TRANS,&N,&one,lapA,&N,IPIV,lapB,&N,&INFO); } inline void getrs(char &TRANS, int &N, float *lapA, int *IPIV, float *lapB, int &INFO) { int one = 1; sgetrs_(&TRANS,&N,&one,lapA,&N,IPIV,lapB,&N,&INFO); } template<typename T> inline void syev(char &JOB, char &UPLO, int &N, T *lapA, T *lapW, T *WORK, int &LWORK, int &INFO) { dsyev_(&JOB,&UPLO,&N,lapA,&N,lapW,WORK,&LWORK,&INFO); } inline void syev(char &JOB, char &UPLO, int &N, float *lapA, float *lapW, float *WORK, int &LWORK, int &INFO) { ssyev_(&JOB,&UPLO,&N,lapA,&N,lapW,WORK,&LWORK,&INFO); } template<typename T> inline void sgels(char & TRANS, int &M, int &N, int &NRHS, T* lapA, int &LDA, T* lapB, int &LDB, T* WORK, int &LWORK, int &INFO){ dgels_(&TRANS, &M, &N, &NRHS, lapA, &LDA, lapB, &LDB, WORK, &LWORK, &INFO); } inline void sgels(char & TRANS, int &M, int &N, int &NRHS, float* lapA, int &LDA, float* lapB, int &LDB, float* WORK, int &LWORK, int &INFO){ sgels_(&TRANS, &M, &N, &NRHS, lapA, &LDA, lapB, &LDB, WORK, &LWORK, &INFO); } #endif } // namespace cimg { ... /*------------------------------------------------ # # # Definition of mathematical operators and # external functions. # # -------------------------------------------------*/ #define _cimg_create_ext_operators(typ) \ template<typename T> \ inline CImg<typename cimg::superset<T,typ>::type> operator+(const typ val, const CImg<T>& img) { \ return img + val; \ } \ template<typename T> \ inline CImg<typename cimg::superset<T,typ>::type> operator-(const typ val, const CImg<T>& img) { \ typedef typename cimg::superset<T,typ>::type Tt; \ return CImg<Tt>(img._width,img._height,img._depth,img._spectrum,val)-=img; \ } \ template<typename T> \ inline CImg<typename cimg::superset<T,typ>::type> operator*(const typ val, const CImg<T>& img) { \ return img*val; \ } \ template<typename T> \ inline CImg<typename cimg::superset<T,typ>::type> operator/(const typ val, const CImg<T>& img) { \ return val*img.get_invert(); \ } \ template<typename T> \ inline CImg<typename cimg::superset<T,typ>::type> operator&(const typ val, const CImg<T>& img) { \ return img & val; \ } \ template<typename T> \ inline CImg<typename cimg::superset<T,typ>::type> operator|(const typ val, const CImg<T>& img) { \ return img | val; \ } \ template<typename T> \ inline CImg<typename cimg::superset<T,typ>::type> operator^(const typ val, const CImg<T>& img) { \ return img ^ val; \ } \ template<typename T> \ inline bool operator==(const typ val, const CImg<T>& img) { \ return img == val; \ } \ template<typename T> \ inline bool operator!=(const typ val, const CImg<T>& img) { \ return img != val; \ } _cimg_create_ext_operators(bool) _cimg_create_ext_operators(unsigned char) _cimg_create_ext_operators(char) _cimg_create_ext_operators(signed char) _cimg_create_ext_operators(unsigned short) _cimg_create_ext_operators(short) _cimg_create_ext_operators(unsigned int) _cimg_create_ext_operators(int) _cimg_create_ext_operators(cimg_uint64) _cimg_create_ext_operators(cimg_int64) _cimg_create_ext_operators(float) _cimg_create_ext_operators(double) _cimg_create_ext_operators(long double) template<typename T> inline CImg<_cimg_Tfloat> operator+(const char *const expression, const CImg<T>& img) { return img + expression; } template<typename T> inline CImg<_cimg_Tfloat> operator-(const char *const expression, const CImg<T>& img) { return CImg<_cimg_Tfloat>(img,false).fill(expression,true)-=img; } template<typename T> inline CImg<_cimg_Tfloat> operator*(const char *const expression, const CImg<T>& img) { return img*expression; } template<typename T> inline CImg<_cimg_Tfloat> operator/(const char *const expression, const CImg<T>& img) { return expression*img.get_invert(); } template<typename T> inline CImg<T> operator&(const char *const expression, const CImg<T>& img) { return img & expression; } template<typename T> inline CImg<T> operator|(const char *const expression, const CImg<T>& img) { return img | expression; } template<typename T> inline CImg<T> operator^(const char *const expression, const CImg<T>& img) { return img ^ expression; } template<typename T> inline bool operator==(const char *const expression, const CImg<T>& img) { return img==expression; } template<typename T> inline bool operator!=(const char *const expression, const CImg<T>& img) { return img!=expression; } template<typename T> inline CImg<T> transpose(const CImg<T>& instance) { return instance.get_transpose(); } template<typename T> inline CImg<_cimg_Tfloat> invert(const CImg<T>& instance) { return instance.get_invert(); } template<typename T> inline CImg<_cimg_Tfloat> pseudoinvert(const CImg<T>& instance) { return instance.get_pseudoinvert(); } #define _cimg_create_ext_pointwise_function(name) \ template<typename T> \ inline CImg<_cimg_Tfloat> name(const CImg<T>& instance) { \ return instance.get_##name(); \ } _cimg_create_ext_pointwise_function(sqr) _cimg_create_ext_pointwise_function(sqrt) _cimg_create_ext_pointwise_function(exp) _cimg_create_ext_pointwise_function(log) _cimg_create_ext_pointwise_function(log2) _cimg_create_ext_pointwise_function(log10) _cimg_create_ext_pointwise_function(abs) _cimg_create_ext_pointwise_function(sign) _cimg_create_ext_pointwise_function(cos) _cimg_create_ext_pointwise_function(sin) _cimg_create_ext_pointwise_function(sinc) _cimg_create_ext_pointwise_function(tan) _cimg_create_ext_pointwise_function(acos) _cimg_create_ext_pointwise_function(asin) _cimg_create_ext_pointwise_function(atan) _cimg_create_ext_pointwise_function(cosh) _cimg_create_ext_pointwise_function(sinh) _cimg_create_ext_pointwise_function(tanh) _cimg_create_ext_pointwise_function(acosh) _cimg_create_ext_pointwise_function(asinh) _cimg_create_ext_pointwise_function(atanh) /*----------------------------------- # # Define the CImgDisplay structure # ----------------------------------*/ //! Allow the creation of windows, display images on them and manage user events (keyboard, mouse and windows events). /** CImgDisplay methods rely on a low-level graphic library to perform: it can be either \b X-Window (X11, for Unix-based systems) or \b GDI32 (for Windows-based systems). If both libraries are missing, CImgDisplay will not be able to display images on screen, and will enter a minimal mode where warning messages will be outputed each time the program is trying to call one of the CImgDisplay method. The configuration variable \c cimg_display tells about the graphic library used. It is set automatically by \CImg when one of these graphic libraries has been detected. But, you can override its value if necessary. Valid choices are: - 0: Disable display capabilities. - 1: Use \b X-Window (X11) library. - 2: Use \b GDI32 library. Remember to link your program against \b X11 or \b GDI32 libraries if you use CImgDisplay. **/ struct CImgDisplay { cimg_ulong _timer, _fps_frames, _fps_timer; unsigned int _width, _height, _normalization; float _fps_fps, _min, _max; bool _is_fullscreen; char *_title; unsigned int _window_width, _window_height, _button, *_keys, *_released_keys; int _window_x, _window_y, _mouse_x, _mouse_y, _wheel; bool _is_closed, _is_resized, _is_moved, _is_event, _is_keyESC, _is_keyF1, _is_keyF2, _is_keyF3, _is_keyF4, _is_keyF5, _is_keyF6, _is_keyF7, _is_keyF8, _is_keyF9, _is_keyF10, _is_keyF11, _is_keyF12, _is_keyPAUSE, _is_key1, _is_key2, _is_key3, _is_key4, _is_key5, _is_key6, _is_key7, _is_key8, _is_key9, _is_key0, _is_keyBACKSPACE, _is_keyINSERT, _is_keyHOME, _is_keyPAGEUP, _is_keyTAB, _is_keyQ, _is_keyW, _is_keyE, _is_keyR, _is_keyT, _is_keyY, _is_keyU, _is_keyI, _is_keyO, _is_keyP, _is_keyDELETE, _is_keyEND, _is_keyPAGEDOWN, _is_keyCAPSLOCK, _is_keyA, _is_keyS, _is_keyD, _is_keyF, _is_keyG, _is_keyH, _is_keyJ, _is_keyK, _is_keyL, _is_keyENTER, _is_keySHIFTLEFT, _is_keyZ, _is_keyX, _is_keyC, _is_keyV, _is_keyB, _is_keyN, _is_keyM, _is_keySHIFTRIGHT, _is_keyARROWUP, _is_keyCTRLLEFT, _is_keyAPPLEFT, _is_keyALT, _is_keySPACE, _is_keyALTGR, _is_keyAPPRIGHT, _is_keyMENU, _is_keyCTRLRIGHT, _is_keyARROWLEFT, _is_keyARROWDOWN, _is_keyARROWRIGHT, _is_keyPAD0, _is_keyPAD1, _is_keyPAD2, _is_keyPAD3, _is_keyPAD4, _is_keyPAD5, _is_keyPAD6, _is_keyPAD7, _is_keyPAD8, _is_keyPAD9, _is_keyPADADD, _is_keyPADSUB, _is_keyPADMUL, _is_keyPADDIV; //@} //--------------------------- // //! \name Plugins //@{ //--------------------------- #ifdef cimgdisplay_plugin #include cimgdisplay_plugin #endif #ifdef cimgdisplay_plugin1 #include cimgdisplay_plugin1 #endif #ifdef cimgdisplay_plugin2 #include cimgdisplay_plugin2 #endif #ifdef cimgdisplay_plugin3 #include cimgdisplay_plugin3 #endif #ifdef cimgdisplay_plugin4 #include cimgdisplay_plugin4 #endif #ifdef cimgdisplay_plugin5 #include cimgdisplay_plugin5 #endif #ifdef cimgdisplay_plugin6 #include cimgdisplay_plugin6 #endif #ifdef cimgdisplay_plugin7 #include cimgdisplay_plugin7 #endif #ifdef cimgdisplay_plugin8 #include cimgdisplay_plugin8 #endif //@} //-------------------------------------------------------- // //! \name Constructors / Destructor / Instance Management //@{ //-------------------------------------------------------- //! Destructor. /** \note If the associated window is visible on the screen, it is closed by the call to the destructor. **/ ~CImgDisplay() { assign(); delete[] _keys; delete[] _released_keys; } //! Construct an empty display. /** \note Constructing an empty CImgDisplay instance does not make a window appearing on the screen, until display of valid data is performed. \par Example \code CImgDisplay disp; // Does actually nothing ... disp.display(img); // Construct new window and display image in it \endcode **/ CImgDisplay(): _width(0),_height(0),_normalization(0), _min(0),_max(0), _is_fullscreen(false), _title(0), _window_width(0),_window_height(0),_button(0), _keys(new unsigned int[128]),_released_keys(new unsigned int[128]), _window_x(0),_window_y(0),_mouse_x(-1),_mouse_y(-1),_wheel(0), _is_closed(true),_is_resized(false),_is_moved(false),_is_event(false) { assign(); } //! Construct a display with specified dimensions. /** \param width Window width. \param height Window height. \param title Window title. \param normalization Normalization type (<tt>0</tt>=none, <tt>1</tt>=always, <tt>2</tt>=once, <tt>3</tt>=pixel type-dependent, see normalization()). \param is_fullscreen Tells if fullscreen mode is enabled. \param is_closed Tells if associated window is initially visible or not. \note A black background is initially displayed on the associated window. **/ CImgDisplay(const unsigned int width, const unsigned int height, const char *const title=0, const unsigned int normalization=3, const bool is_fullscreen=false, const bool is_closed=false): _width(0),_height(0),_normalization(0), _min(0),_max(0), _is_fullscreen(false), _title(0), _window_width(0),_window_height(0),_button(0), _keys(new unsigned int[128]),_released_keys(new unsigned int[128]), _window_x(0),_window_y(0),_mouse_x(-1),_mouse_y(-1),_wheel(0), _is_closed(true),_is_resized(false),_is_moved(false),_is_event(false) { assign(width,height,title,normalization,is_fullscreen,is_closed); } //! Construct a display from an image. /** \param img Image used as a model to create the window. \param title Window title. \param normalization Normalization type (<tt>0</tt>=none, <tt>1</tt>=always, <tt>2</tt>=once, <tt>3</tt>=pixel type-dependent, see normalization()). \param is_fullscreen Tells if fullscreen mode is enabled. \param is_closed Tells if associated window is initially visible or not. \note The pixels of the input image are initially displayed on the associated window. **/ template<typename T> explicit CImgDisplay(const CImg<T>& img, const char *const title=0, const unsigned int normalization=3, const bool is_fullscreen=false, const bool is_closed=false): _width(0),_height(0),_normalization(0), _min(0),_max(0), _is_fullscreen(false), _title(0), _window_width(0),_window_height(0),_button(0), _keys(new unsigned int[128]),_released_keys(new unsigned int[128]), _window_x(0),_window_y(0),_mouse_x(-1),_mouse_y(-1),_wheel(0), _is_closed(true),_is_resized(false),_is_moved(false),_is_event(false) { assign(img,title,normalization,is_fullscreen,is_closed); } //! Construct a display from an image list. /** \param list The images list to display. \param title Window title. \param normalization Normalization type (<tt>0</tt>=none, <tt>1</tt>=always, <tt>2</tt>=once, <tt>3</tt>=pixel type-dependent, see normalization()). \param is_fullscreen Tells if fullscreen mode is enabled. \param is_closed Tells if associated window is initially visible or not. \note All images of the list, appended along the X-axis, are initially displayed on the associated window. **/ template<typename T> explicit CImgDisplay(const CImgList<T>& list, const char *const title=0, const unsigned int normalization=3, const bool is_fullscreen=false, const bool is_closed=false): _width(0),_height(0),_normalization(0), _min(0),_max(0), _is_fullscreen(false), _title(0), _window_width(0),_window_height(0),_button(0), _keys(new unsigned int[128]),_released_keys(new unsigned int[128]), _window_x(0),_window_y(0),_mouse_x(-1),_mouse_y(-1),_wheel(0), _is_closed(true),_is_resized(false),_is_moved(false),_is_event(false) { assign(list,title,normalization,is_fullscreen,is_closed); } //! Construct a display as a copy of an existing one. /** \param disp Display instance to copy. \note The pixel buffer of the input window is initially displayed on the associated window. **/ CImgDisplay(const CImgDisplay& disp): _width(0),_height(0),_normalization(0), _min(0),_max(0), _is_fullscreen(false), _title(0), _window_width(0),_window_height(0),_button(0), _keys(new unsigned int[128]),_released_keys(new unsigned int[128]), _window_x(0),_window_y(0),_mouse_x(-1),_mouse_y(-1),_wheel(0), _is_closed(true),_is_resized(false),_is_moved(false),_is_event(false) { assign(disp); } //! Take a screenshot. /** \param[out] img Output screenshot. Can be empty on input **/ template<typename T> static void screenshot(CImg<T>& img) { return screenshot(0,0,cimg::type<int>::max(),cimg::type<int>::max(),img); } #if cimg_display==0 static void _no_display_exception() { throw CImgDisplayException("CImgDisplay(): No display available."); } //! Destructor - Empty constructor \inplace. /** \note Replace the current instance by an empty display. **/ CImgDisplay& assign() { return flush(); } //! Construct a display with specified dimensions \inplace. /** **/ CImgDisplay& assign(const unsigned int width, const unsigned int height, const char *const title=0, const unsigned int normalization=3, const bool is_fullscreen=false, const bool is_closed=false) { cimg::unused(width,height,title,normalization,is_fullscreen,is_closed); _no_display_exception(); return assign(); } //! Construct a display from an image \inplace. /** **/ template<typename T> CImgDisplay& assign(const CImg<T>& img, const char *const title=0, const unsigned int normalization=3, const bool is_fullscreen=false, const bool is_closed=false) { _no_display_exception(); return assign(img._width,img._height,title,normalization,is_fullscreen,is_closed); } //! Construct a display from an image list \inplace. /** **/ template<typename T> CImgDisplay& assign(const CImgList<T>& list, const char *const title=0, const unsigned int normalization=3, const bool is_fullscreen=false, const bool is_closed=false) { _no_display_exception(); return assign(list._width,list._width,title,normalization,is_fullscreen,is_closed); } //! Construct a display as a copy of another one \inplace. /** **/ CImgDisplay& assign(const CImgDisplay &disp) { _no_display_exception(); return assign(disp._width,disp._height); } #endif //! Return a reference to an empty display. /** \note Can be useful for writing function prototypes where one of the argument (of type CImgDisplay&) must have a default value. \par Example \code void foo(CImgDisplay& disp=CImgDisplay::empty()); \endcode **/ static CImgDisplay& empty() { static CImgDisplay _empty; return _empty.assign(); } //! Return a reference to an empty display \const. static const CImgDisplay& const_empty() { static const CImgDisplay _empty; return _empty; } #define cimg_fitscreen(dx,dy,dz) CImgDisplay::_fitscreen(dx,dy,dz,128,-85,false), \ CImgDisplay::_fitscreen(dx,dy,dz,128,-85,true) static unsigned int _fitscreen(const unsigned int dx, const unsigned int dy, const unsigned int dz, const int dmin, const int dmax, const bool return_y) { const int u = CImgDisplay::screen_width(), v = CImgDisplay::screen_height(); const float mw = dmin<0?cimg::round(u*-dmin/100.f):(float)dmin, mh = dmin<0?cimg::round(v*-dmin/100.f):(float)dmin, Mw = dmax<0?cimg::round(u*-dmax/100.f):(float)dmax, Mh = dmax<0?cimg::round(v*-dmax/100.f):(float)dmax; float w = (float)std::max(1U,dx), h = (float)std::max(1U,dy); if (dz>1) { w+=dz; h+=dz; } if (w<mw) { h = h*mw/w; w = mw; } if (h<mh) { w = w*mh/h; h = mh; } if (w>Mw) { h = h*Mw/w; w = Mw; } if (h>Mh) { w = w*Mh/h; h = Mh; } if (w<mw) w = mw; if (h<mh) h = mh; return std::max(1U,(unsigned int)cimg::round(return_y?h:w)); } //@} //------------------------------------------ // //! \name Overloaded Operators //@{ //------------------------------------------ //! Display image on associated window. /** \note <tt>disp = img</tt> is equivalent to <tt>disp.display(img)</tt>. **/ template<typename t> CImgDisplay& operator=(const CImg<t>& img) { return display(img); } //! Display list of images on associated window. /** \note <tt>disp = list</tt> is equivalent to <tt>disp.display(list)</tt>. **/ template<typename t> CImgDisplay& operator=(const CImgList<t>& list) { return display(list); } //! Construct a display as a copy of another one \inplace. /** \note Equivalent to assign(const CImgDisplay&). **/ CImgDisplay& operator=(const CImgDisplay& disp) { return assign(disp); } //! Return \c false if display is empty, \c true otherwise. /** \note <tt>if (disp) { ... }</tt> is equivalent to <tt>if (!disp.is_empty()) { ... }</tt>. **/ operator bool() const { return !is_empty(); } //@} //------------------------------------------ // //! \name Instance Checking //@{ //------------------------------------------ //! Return \c true if display is empty, \c false otherwise. /** **/ bool is_empty() const { return !(_width && _height); } //! Return \c true if display is closed (i.e. not visible on the screen), \c false otherwise. /** \note - When a user physically closes the associated window, the display is set to closed. - A closed display is not destroyed. Its associated window can be show again on the screen using show(). **/ bool is_closed() const { return _is_closed; } //! Return \c true if associated window has been resized on the screen, \c false otherwise. /** **/ bool is_resized() const { return _is_resized; } //! Return \c true if associated window has been moved on the screen, \c false otherwise. /** **/ bool is_moved() const { return _is_moved; } //! Return \c true if any event has occured on the associated window, \c false otherwise. /** **/ bool is_event() const { return _is_event; } //! Return \c true if current display is in fullscreen mode, \c false otherwise. /** **/ bool is_fullscreen() const { return _is_fullscreen; } //! Return \c true if any key is being pressed on the associated window, \c false otherwise. /** \note The methods below do the same only for specific keys. **/ bool is_key() const { return _is_keyESC || _is_keyF1 || _is_keyF2 || _is_keyF3 || _is_keyF4 || _is_keyF5 || _is_keyF6 || _is_keyF7 || _is_keyF8 || _is_keyF9 || _is_keyF10 || _is_keyF11 || _is_keyF12 || _is_keyPAUSE || _is_key1 || _is_key2 || _is_key3 || _is_key4 || _is_key5 || _is_key6 || _is_key7 || _is_key8 || _is_key9 || _is_key0 || _is_keyBACKSPACE || _is_keyINSERT || _is_keyHOME || _is_keyPAGEUP || _is_keyTAB || _is_keyQ || _is_keyW || _is_keyE || _is_keyR || _is_keyT || _is_keyY || _is_keyU || _is_keyI || _is_keyO || _is_keyP || _is_keyDELETE || _is_keyEND || _is_keyPAGEDOWN || _is_keyCAPSLOCK || _is_keyA || _is_keyS || _is_keyD || _is_keyF || _is_keyG || _is_keyH || _is_keyJ || _is_keyK || _is_keyL || _is_keyENTER || _is_keySHIFTLEFT || _is_keyZ || _is_keyX || _is_keyC || _is_keyV || _is_keyB || _is_keyN || _is_keyM || _is_keySHIFTRIGHT || _is_keyARROWUP || _is_keyCTRLLEFT || _is_keyAPPLEFT || _is_keyALT || _is_keySPACE || _is_keyALTGR || _is_keyAPPRIGHT || _is_keyMENU || _is_keyCTRLRIGHT || _is_keyARROWLEFT || _is_keyARROWDOWN || _is_keyARROWRIGHT || _is_keyPAD0 || _is_keyPAD1 || _is_keyPAD2 || _is_keyPAD3 || _is_keyPAD4 || _is_keyPAD5 || _is_keyPAD6 || _is_keyPAD7 || _is_keyPAD8 || _is_keyPAD9 || _is_keyPADADD || _is_keyPADSUB || _is_keyPADMUL || _is_keyPADDIV; } //! Return \c true if key specified by given keycode is being pressed on the associated window, \c false otherwise. /** \param keycode Keycode to test. \note Keycode constants are defined in the cimg namespace and are architecture-dependent. Use them to ensure your code stay portable (see cimg::keyESC). \par Example \code CImgDisplay disp(400,400); while (!disp.is_closed()) { if (disp.key(cimg::keyTAB)) { ... } // Equivalent to 'if (disp.is_keyTAB())' disp.wait(); } \endcode **/ bool is_key(const unsigned int keycode) const { #define _cimg_iskey_test(k) if (keycode==cimg::key##k) return _is_key##k; _cimg_iskey_test(ESC); _cimg_iskey_test(F1); _cimg_iskey_test(F2); _cimg_iskey_test(F3); _cimg_iskey_test(F4); _cimg_iskey_test(F5); _cimg_iskey_test(F6); _cimg_iskey_test(F7); _cimg_iskey_test(F8); _cimg_iskey_test(F9); _cimg_iskey_test(F10); _cimg_iskey_test(F11); _cimg_iskey_test(F12); _cimg_iskey_test(PAUSE); _cimg_iskey_test(1); _cimg_iskey_test(2); _cimg_iskey_test(3); _cimg_iskey_test(4); _cimg_iskey_test(5); _cimg_iskey_test(6); _cimg_iskey_test(7); _cimg_iskey_test(8); _cimg_iskey_test(9); _cimg_iskey_test(0); _cimg_iskey_test(BACKSPACE); _cimg_iskey_test(INSERT); _cimg_iskey_test(HOME); _cimg_iskey_test(PAGEUP); _cimg_iskey_test(TAB); _cimg_iskey_test(Q); _cimg_iskey_test(W); _cimg_iskey_test(E); _cimg_iskey_test(R); _cimg_iskey_test(T); _cimg_iskey_test(Y); _cimg_iskey_test(U); _cimg_iskey_test(I); _cimg_iskey_test(O); _cimg_iskey_test(P); _cimg_iskey_test(DELETE); _cimg_iskey_test(END); _cimg_iskey_test(PAGEDOWN); _cimg_iskey_test(CAPSLOCK); _cimg_iskey_test(A); _cimg_iskey_test(S); _cimg_iskey_test(D); _cimg_iskey_test(F); _cimg_iskey_test(G); _cimg_iskey_test(H); _cimg_iskey_test(J); _cimg_iskey_test(K); _cimg_iskey_test(L); _cimg_iskey_test(ENTER); _cimg_iskey_test(SHIFTLEFT); _cimg_iskey_test(Z); _cimg_iskey_test(X); _cimg_iskey_test(C); _cimg_iskey_test(V); _cimg_iskey_test(B); _cimg_iskey_test(N); _cimg_iskey_test(M); _cimg_iskey_test(SHIFTRIGHT); _cimg_iskey_test(ARROWUP); _cimg_iskey_test(CTRLLEFT); _cimg_iskey_test(APPLEFT); _cimg_iskey_test(ALT); _cimg_iskey_test(SPACE); _cimg_iskey_test(ALTGR); _cimg_iskey_test(APPRIGHT); _cimg_iskey_test(MENU); _cimg_iskey_test(CTRLRIGHT); _cimg_iskey_test(ARROWLEFT); _cimg_iskey_test(ARROWDOWN); _cimg_iskey_test(ARROWRIGHT); _cimg_iskey_test(PAD0); _cimg_iskey_test(PAD1); _cimg_iskey_test(PAD2); _cimg_iskey_test(PAD3); _cimg_iskey_test(PAD4); _cimg_iskey_test(PAD5); _cimg_iskey_test(PAD6); _cimg_iskey_test(PAD7); _cimg_iskey_test(PAD8); _cimg_iskey_test(PAD9); _cimg_iskey_test(PADADD); _cimg_iskey_test(PADSUB); _cimg_iskey_test(PADMUL); _cimg_iskey_test(PADDIV); return false; } //! Return \c true if key specified by given keycode is being pressed on the associated window, \c false otherwise. /** \param keycode C-string containing the keycode label of the key to test. \note Use it when the key you want to test can be dynamically set by the user. \par Example \code CImgDisplay disp(400,400); const char *const keycode = "TAB"; while (!disp.is_closed()) { if (disp.is_key(keycode)) { ... } // Equivalent to 'if (disp.is_keyTAB())' disp.wait(); } \endcode **/ bool& is_key(const char *const keycode) { static bool f = false; f = false; #define _cimg_iskey_test2(k) if (!cimg::strcasecmp(keycode,#k)) return _is_key##k; _cimg_iskey_test2(ESC); _cimg_iskey_test2(F1); _cimg_iskey_test2(F2); _cimg_iskey_test2(F3); _cimg_iskey_test2(F4); _cimg_iskey_test2(F5); _cimg_iskey_test2(F6); _cimg_iskey_test2(F7); _cimg_iskey_test2(F8); _cimg_iskey_test2(F9); _cimg_iskey_test2(F10); _cimg_iskey_test2(F11); _cimg_iskey_test2(F12); _cimg_iskey_test2(PAUSE); _cimg_iskey_test2(1); _cimg_iskey_test2(2); _cimg_iskey_test2(3); _cimg_iskey_test2(4); _cimg_iskey_test2(5); _cimg_iskey_test2(6); _cimg_iskey_test2(7); _cimg_iskey_test2(8); _cimg_iskey_test2(9); _cimg_iskey_test2(0); _cimg_iskey_test2(BACKSPACE); _cimg_iskey_test2(INSERT); _cimg_iskey_test2(HOME); _cimg_iskey_test2(PAGEUP); _cimg_iskey_test2(TAB); _cimg_iskey_test2(Q); _cimg_iskey_test2(W); _cimg_iskey_test2(E); _cimg_iskey_test2(R); _cimg_iskey_test2(T); _cimg_iskey_test2(Y); _cimg_iskey_test2(U); _cimg_iskey_test2(I); _cimg_iskey_test2(O); _cimg_iskey_test2(P); _cimg_iskey_test2(DELETE); _cimg_iskey_test2(END); _cimg_iskey_test2(PAGEDOWN); _cimg_iskey_test2(CAPSLOCK); _cimg_iskey_test2(A); _cimg_iskey_test2(S); _cimg_iskey_test2(D); _cimg_iskey_test2(F); _cimg_iskey_test2(G); _cimg_iskey_test2(H); _cimg_iskey_test2(J); _cimg_iskey_test2(K); _cimg_iskey_test2(L); _cimg_iskey_test2(ENTER); _cimg_iskey_test2(SHIFTLEFT); _cimg_iskey_test2(Z); _cimg_iskey_test2(X); _cimg_iskey_test2(C); _cimg_iskey_test2(V); _cimg_iskey_test2(B); _cimg_iskey_test2(N); _cimg_iskey_test2(M); _cimg_iskey_test2(SHIFTRIGHT); _cimg_iskey_test2(ARROWUP); _cimg_iskey_test2(CTRLLEFT); _cimg_iskey_test2(APPLEFT); _cimg_iskey_test2(ALT); _cimg_iskey_test2(SPACE); _cimg_iskey_test2(ALTGR); _cimg_iskey_test2(APPRIGHT); _cimg_iskey_test2(MENU); _cimg_iskey_test2(CTRLRIGHT); _cimg_iskey_test2(ARROWLEFT); _cimg_iskey_test2(ARROWDOWN); _cimg_iskey_test2(ARROWRIGHT); _cimg_iskey_test2(PAD0); _cimg_iskey_test2(PAD1); _cimg_iskey_test2(PAD2); _cimg_iskey_test2(PAD3); _cimg_iskey_test2(PAD4); _cimg_iskey_test2(PAD5); _cimg_iskey_test2(PAD6); _cimg_iskey_test2(PAD7); _cimg_iskey_test2(PAD8); _cimg_iskey_test2(PAD9); _cimg_iskey_test2(PADADD); _cimg_iskey_test2(PADSUB); _cimg_iskey_test2(PADMUL); _cimg_iskey_test2(PADDIV); return f; } //! Return \c true if specified key sequence has been typed on the associated window, \c false otherwise. /** \param keycodes_sequence Buffer of keycodes to test. \param length Number of keys in the \c keycodes_sequence buffer. \param remove_sequence Tells if the key sequence must be removed from the key history, if found. \note Keycode constants are defined in the cimg namespace and are architecture-dependent. Use them to ensure your code stay portable (see cimg::keyESC). \par Example \code CImgDisplay disp(400,400); const unsigned int key_seq[] = { cimg::keyCTRLLEFT, cimg::keyD }; while (!disp.is_closed()) { if (disp.is_key_sequence(key_seq,2)) { ... } // Test for the 'CTRL+D' keyboard event disp.wait(); } \endcode **/ bool is_key_sequence(const unsigned int *const keycodes_sequence, const unsigned int length, const bool remove_sequence=false) { if (keycodes_sequence && length) { const unsigned int *const ps_end = keycodes_sequence + length - 1, *const pk_end = (unsigned int*)_keys + 1 + 128 - length, k = *ps_end; for (unsigned int *pk = (unsigned int*)_keys; pk<pk_end; ) { if (*(pk++)==k) { bool res = true; const unsigned int *ps = ps_end, *pk2 = pk; for (unsigned int i = 1; i<length; ++i) res = (*(--ps)==*(pk2++)); if (res) { if (remove_sequence) std::memset((void*)(pk - 1),0,sizeof(unsigned int)*length); return true; } } } } return false; } #define _cimg_iskey_def(k) \ bool is_key##k() const { \ return _is_key##k; \ } //! Return \c true if the \c ESC key is being pressed on the associated window, \c false otherwise. /** \note Similar methods exist for all keys managed by \CImg (see cimg::keyESC). **/ _cimg_iskey_def(ESC); _cimg_iskey_def(F1); _cimg_iskey_def(F2); _cimg_iskey_def(F3); _cimg_iskey_def(F4); _cimg_iskey_def(F5); _cimg_iskey_def(F6); _cimg_iskey_def(F7); _cimg_iskey_def(F8); _cimg_iskey_def(F9); _cimg_iskey_def(F10); _cimg_iskey_def(F11); _cimg_iskey_def(F12); _cimg_iskey_def(PAUSE); _cimg_iskey_def(1); _cimg_iskey_def(2); _cimg_iskey_def(3); _cimg_iskey_def(4); _cimg_iskey_def(5); _cimg_iskey_def(6); _cimg_iskey_def(7); _cimg_iskey_def(8); _cimg_iskey_def(9); _cimg_iskey_def(0); _cimg_iskey_def(BACKSPACE); _cimg_iskey_def(INSERT); _cimg_iskey_def(HOME); _cimg_iskey_def(PAGEUP); _cimg_iskey_def(TAB); _cimg_iskey_def(Q); _cimg_iskey_def(W); _cimg_iskey_def(E); _cimg_iskey_def(R); _cimg_iskey_def(T); _cimg_iskey_def(Y); _cimg_iskey_def(U); _cimg_iskey_def(I); _cimg_iskey_def(O); _cimg_iskey_def(P); _cimg_iskey_def(DELETE); _cimg_iskey_def(END); _cimg_iskey_def(PAGEDOWN); _cimg_iskey_def(CAPSLOCK); _cimg_iskey_def(A); _cimg_iskey_def(S); _cimg_iskey_def(D); _cimg_iskey_def(F); _cimg_iskey_def(G); _cimg_iskey_def(H); _cimg_iskey_def(J); _cimg_iskey_def(K); _cimg_iskey_def(L); _cimg_iskey_def(ENTER); _cimg_iskey_def(SHIFTLEFT); _cimg_iskey_def(Z); _cimg_iskey_def(X); _cimg_iskey_def(C); _cimg_iskey_def(V); _cimg_iskey_def(B); _cimg_iskey_def(N); _cimg_iskey_def(M); _cimg_iskey_def(SHIFTRIGHT); _cimg_iskey_def(ARROWUP); _cimg_iskey_def(CTRLLEFT); _cimg_iskey_def(APPLEFT); _cimg_iskey_def(ALT); _cimg_iskey_def(SPACE); _cimg_iskey_def(ALTGR); _cimg_iskey_def(APPRIGHT); _cimg_iskey_def(MENU); _cimg_iskey_def(CTRLRIGHT); _cimg_iskey_def(ARROWLEFT); _cimg_iskey_def(ARROWDOWN); _cimg_iskey_def(ARROWRIGHT); _cimg_iskey_def(PAD0); _cimg_iskey_def(PAD1); _cimg_iskey_def(PAD2); _cimg_iskey_def(PAD3); _cimg_iskey_def(PAD4); _cimg_iskey_def(PAD5); _cimg_iskey_def(PAD6); _cimg_iskey_def(PAD7); _cimg_iskey_def(PAD8); _cimg_iskey_def(PAD9); _cimg_iskey_def(PADADD); _cimg_iskey_def(PADSUB); _cimg_iskey_def(PADMUL); _cimg_iskey_def(PADDIV); //@} //------------------------------------------ // //! \name Instance Characteristics //@{ //------------------------------------------ #if cimg_display==0 //! Return width of the screen (current resolution along the X-axis). /** **/ static int screen_width() { _no_display_exception(); return 0; } //! Return height of the screen (current resolution along the Y-axis). /** **/ static int screen_height() { _no_display_exception(); return 0; } #endif //! Return display width. /** \note The width of the display (i.e. the width of the pixel data buffer associated to the CImgDisplay instance) may be different from the actual width of the associated window. **/ int width() const { return (int)_width; } //! Return display height. /** \note The height of the display (i.e. the height of the pixel data buffer associated to the CImgDisplay instance) may be different from the actual height of the associated window. **/ int height() const { return (int)_height; } //! Return normalization type of the display. /** The normalization type tells about how the values of an input image are normalized by the CImgDisplay to be correctly displayed. The range of values for pixels displayed on screen is <tt>[0,255]</tt>. If the range of values of the data to display is different, a normalization may be required for displaying the data in a correct way. The normalization type can be one of: - \c 0: Value normalization is disabled. It is then assumed that all input data to be displayed by the CImgDisplay instance have values in range <tt>[0,255]</tt>. - \c 1: Value normalization is always performed (this is the default behavior). Before displaying an input image, its values will be (virtually) stretched in range <tt>[0,255]</tt>, so that the contrast of the displayed pixels will be maximum. Use this mode for images whose minimum and maximum values are not prescribed to known values (e.g. float-valued images). Note that when normalized versions of images are computed for display purposes, the actual values of these images are not modified. - \c 2: Value normalization is performed once (on the first image display), then the same normalization coefficients are kept for next displayed frames. - \c 3: Value normalization depends on the pixel type of the data to display. For integer pixel types, the normalization is done regarding the minimum/maximum values of the type (no normalization occurs then for <tt>unsigned char</tt>). For float-valued pixel types, the normalization is done regarding the minimum/maximum value of the image data instead. **/ unsigned int normalization() const { return _normalization; } //! Return title of the associated window as a C-string. /** \note Window title may be not visible, depending on the used window manager or if the current display is in fullscreen mode. **/ const char *title() const { return _title?_title:""; } //! Return width of the associated window. /** \note The width of the display (i.e. the width of the pixel data buffer associated to the CImgDisplay instance) may be different from the actual width of the associated window. **/ int window_width() const { return (int)_window_width; } //! Return height of the associated window. /** \note The height of the display (i.e. the height of the pixel data buffer associated to the CImgDisplay instance) may be different from the actual height of the associated window. **/ int window_height() const { return (int)_window_height; } //! Return X-coordinate of the associated window. /** \note The returned coordinate corresponds to the location of the upper-left corner of the associated window. **/ int window_x() const { return _window_x; } //! Return Y-coordinate of the associated window. /** \note The returned coordinate corresponds to the location of the upper-left corner of the associated window. **/ int window_y() const { return _window_y; } //! Return X-coordinate of the mouse pointer. /** \note - If the mouse pointer is outside window area, \c -1 is returned. - Otherwise, the returned value is in the range [0,width()-1]. **/ int mouse_x() const { return _mouse_x; } //! Return Y-coordinate of the mouse pointer. /** \note - If the mouse pointer is outside window area, \c -1 is returned. - Otherwise, the returned value is in the range [0,height()-1]. **/ int mouse_y() const { return _mouse_y; } //! Return current state of the mouse buttons. /** \note Three mouse buttons can be managed. If one button is pressed, its corresponding bit in the returned value is set: - bit \c 0 (value \c 0x1): State of the left mouse button. - bit \c 1 (value \c 0x2): State of the right mouse button. - bit \c 2 (value \c 0x4): State of the middle mouse button. Several bits can be activated if more than one button are pressed at the same time. \par Example \code CImgDisplay disp(400,400); while (!disp.is_closed()) { if (disp.button()&1) { // Left button clicked ... } if (disp.button()&2) { // Right button clicked ... } if (disp.button()&4) { // Middle button clicked ... } disp.wait(); } \endcode **/ unsigned int button() const { return _button; } //! Return current state of the mouse wheel. /** \note - The returned value can be positive or negative depending on whether the mouse wheel has been scrolled forward or backward. - Scrolling the wheel forward add \c 1 to the wheel value. - Scrolling the wheel backward substract \c 1 to the wheel value. - The returned value cumulates the number of forward of backward scrolls since the creation of the display, or since the last reset of the wheel value (using set_wheel()). It is strongly recommended to quickly reset the wheel counter when an action has been performed regarding the current wheel value. Otherwise, the returned wheel value may be for instance \c 0 despite the fact that many scrolls have been done (as many in forward as in backward directions). \par Example \code CImgDisplay disp(400,400); while (!disp.is_closed()) { if (disp.wheel()) { int counter = disp.wheel(); // Read the state of the mouse wheel ... // Do what you want with 'counter' disp.set_wheel(); // Reset the wheel value to 0 } disp.wait(); } \endcode **/ int wheel() const { return _wheel; } //! Return one entry from the pressed keys history. /** \param pos Index to read from the pressed keys history (index \c 0 corresponds to latest entry). \return Keycode of a pressed key or \c 0 for a released key. \note - Each CImgDisplay stores a history of the pressed keys in a buffer of size \c 128. When a new key is pressed, its keycode is stored in the pressed keys history. When a key is released, \c 0 is put instead. This means that up to the 64 last pressed keys may be read from the pressed keys history. When a new value is stored, the pressed keys history is shifted so that the latest entry is always stored at position \c 0. - Keycode constants are defined in the cimg namespace and are architecture-dependent. Use them to ensure your code stay portable (see cimg::keyESC). **/ unsigned int key(const unsigned int pos=0) const { return pos<128?_keys[pos]:0; } //! Return one entry from the released keys history. /** \param pos Index to read from the released keys history (index \c 0 corresponds to latest entry). \return Keycode of a released key or \c 0 for a pressed key. \note - Each CImgDisplay stores a history of the released keys in a buffer of size \c 128. When a new key is released, its keycode is stored in the pressed keys history. When a key is pressed, \c 0 is put instead. This means that up to the 64 last released keys may be read from the released keys history. When a new value is stored, the released keys history is shifted so that the latest entry is always stored at position \c 0. - Keycode constants are defined in the cimg namespace and are architecture-dependent. Use them to ensure your code stay portable (see cimg::keyESC). **/ unsigned int released_key(const unsigned int pos=0) const { return pos<128?_released_keys[pos]:0; } //! Return keycode corresponding to the specified string. /** \note Keycode constants are defined in the cimg namespace and are architecture-dependent. Use them to ensure your code stay portable (see cimg::keyESC). \par Example \code const unsigned int keyTAB = CImgDisplay::keycode("TAB"); // Return cimg::keyTAB \endcode **/ static unsigned int keycode(const char *const keycode) { #define _cimg_keycode(k) if (!cimg::strcasecmp(keycode,#k)) return cimg::key##k; _cimg_keycode(ESC); _cimg_keycode(F1); _cimg_keycode(F2); _cimg_keycode(F3); _cimg_keycode(F4); _cimg_keycode(F5); _cimg_keycode(F6); _cimg_keycode(F7); _cimg_keycode(F8); _cimg_keycode(F9); _cimg_keycode(F10); _cimg_keycode(F11); _cimg_keycode(F12); _cimg_keycode(PAUSE); _cimg_keycode(1); _cimg_keycode(2); _cimg_keycode(3); _cimg_keycode(4); _cimg_keycode(5); _cimg_keycode(6); _cimg_keycode(7); _cimg_keycode(8); _cimg_keycode(9); _cimg_keycode(0); _cimg_keycode(BACKSPACE); _cimg_keycode(INSERT); _cimg_keycode(HOME); _cimg_keycode(PAGEUP); _cimg_keycode(TAB); _cimg_keycode(Q); _cimg_keycode(W); _cimg_keycode(E); _cimg_keycode(R); _cimg_keycode(T); _cimg_keycode(Y); _cimg_keycode(U); _cimg_keycode(I); _cimg_keycode(O); _cimg_keycode(P); _cimg_keycode(DELETE); _cimg_keycode(END); _cimg_keycode(PAGEDOWN); _cimg_keycode(CAPSLOCK); _cimg_keycode(A); _cimg_keycode(S); _cimg_keycode(D); _cimg_keycode(F); _cimg_keycode(G); _cimg_keycode(H); _cimg_keycode(J); _cimg_keycode(K); _cimg_keycode(L); _cimg_keycode(ENTER); _cimg_keycode(SHIFTLEFT); _cimg_keycode(Z); _cimg_keycode(X); _cimg_keycode(C); _cimg_keycode(V); _cimg_keycode(B); _cimg_keycode(N); _cimg_keycode(M); _cimg_keycode(SHIFTRIGHT); _cimg_keycode(ARROWUP); _cimg_keycode(CTRLLEFT); _cimg_keycode(APPLEFT); _cimg_keycode(ALT); _cimg_keycode(SPACE); _cimg_keycode(ALTGR); _cimg_keycode(APPRIGHT); _cimg_keycode(MENU); _cimg_keycode(CTRLRIGHT); _cimg_keycode(ARROWLEFT); _cimg_keycode(ARROWDOWN); _cimg_keycode(ARROWRIGHT); _cimg_keycode(PAD0); _cimg_keycode(PAD1); _cimg_keycode(PAD2); _cimg_keycode(PAD3); _cimg_keycode(PAD4); _cimg_keycode(PAD5); _cimg_keycode(PAD6); _cimg_keycode(PAD7); _cimg_keycode(PAD8); _cimg_keycode(PAD9); _cimg_keycode(PADADD); _cimg_keycode(PADSUB); _cimg_keycode(PADMUL); _cimg_keycode(PADDIV); return 0; } //! Return the current refresh rate, in frames per second. /** \note Returns a significant value when the current instance is used to display successive frames. It measures the delay between successive calls to frames_per_second(). **/ float frames_per_second() { if (!_fps_timer) _fps_timer = cimg::time(); const float delta = (cimg::time() - _fps_timer)/1000.f; ++_fps_frames; if (delta>=1) { _fps_fps = _fps_frames/delta; _fps_frames = 0; _fps_timer = cimg::time(); } return _fps_fps; } // Move current display window so that its content stays inside the current screen. CImgDisplay& move_inside_screen() { if (is_empty()) return *this; const int x0 = window_x(), y0 = window_y(), x1 = x0 + window_width() - 1, y1 = y0 + window_height() - 1, sw = CImgDisplay::screen_width(), sh = CImgDisplay::screen_height(); if (x0<0 || y0<0 || x1>=sw || y1>=sh) move(std::max(0,std::min(x0,sw - x1 + x0)), std::max(0,std::min(y0,sh - y1 + y0))); return *this; } //@} //--------------------------------------- // //! \name Window Manipulation //@{ //--------------------------------------- #if cimg_display==0 //! Display image on associated window. /** \param img Input image to display. \note This method returns immediately. **/ template<typename T> CImgDisplay& display(const CImg<T>& img) { return assign(img); } #endif //! Display list of images on associated window. /** \param list List of images to display. \param axis Axis used to append the images along, for the visualization (can be \c x, \c y, \c z or \c c). \param align Relative position of aligned images when displaying lists with images of different sizes (\c 0 for upper-left, \c 0.5 for centering and \c 1 for lower-right). \note This method returns immediately. **/ template<typename T> CImgDisplay& display(const CImgList<T>& list, const char axis='x', const float align=0) { if (list._width==1) { const CImg<T>& img = list[0]; if (img._depth==1 && (img._spectrum==1 || img._spectrum>=3) && _normalization!=1) return display(img); } CImgList<typename CImg<T>::ucharT> visu(list._width); unsigned int dims = 0; cimglist_for(list,l) { const CImg<T>& img = list._data[l]; img._get_select(*this,_normalization,(img._width - 1)/2,(img._height - 1)/2, (img._depth - 1)/2).move_to(visu[l]); dims = std::max(dims,visu[l]._spectrum); } cimglist_for(list,l) if (visu[l]._spectrum<dims) visu[l].resize(-100,-100,-100,dims,1); visu.get_append(axis,align).display(*this); return *this; } #if cimg_display==0 //! Show (closed) associated window on the screen. /** \note - Force the associated window of a display to be visible on the screen, even if it has been closed before. - Using show() on a visible display does nothing. **/ CImgDisplay& show() { return assign(); } //! Close (visible) associated window and make it disappear from the screen. /** \note - A closed display only means the associated window is not visible anymore. This does not mean the display has been destroyed. Use show() to make the associated window reappear. - Using close() on a closed display does nothing. **/ CImgDisplay& close() { return assign(); } //! Move associated window to a new location. /** \param pos_x X-coordinate of the new window location. \param pos_y Y-coordinate of the new window location. \note Depending on the window manager behavior, this method may not succeed (no exceptions are thrown nevertheless). **/ CImgDisplay& move(const int pos_x, const int pos_y) { return assign(pos_x,pos_y); } #endif //! Resize display to the size of the associated window. /** \param force_redraw Tells if the previous window content must be updated and refreshed as well. \note - Calling this method ensures that width() and window_width() become equal, as well as height() and window_height(). - The associated window is also resized to specified dimensions. **/ CImgDisplay& resize(const bool force_redraw=true) { resize(window_width(),window_height(),force_redraw); return *this; } #if cimg_display==0 //! Resize display to the specified size. /** \param width Requested display width. \param height Requested display height. \param force_redraw Tells if the previous window content must be updated and refreshed as well. \note The associated window is also resized to specified dimensions. **/ CImgDisplay& resize(const int width, const int height, const bool force_redraw=true) { return assign(width,height,0,3,force_redraw); } #endif //! Resize display to the size of an input image. /** \param img Input image to take size from. \param force_redraw Tells if the previous window content must be resized and updated as well. \note - Calling this method ensures that width() and <tt>img.width()</tt> become equal, as well as height() and <tt>img.height()</tt>. - The associated window is also resized to specified dimensions. **/ template<typename T> CImgDisplay& resize(const CImg<T>& img, const bool force_redraw=true) { return resize(img._width,img._height,force_redraw); } //! Resize display to the size of another CImgDisplay instance. /** \param disp Input display to take size from. \param force_redraw Tells if the previous window content must be resized and updated as well. \note - Calling this method ensures that width() and <tt>disp.width()</tt> become equal, as well as height() and <tt>disp.height()</tt>. - The associated window is also resized to specified dimensions. **/ CImgDisplay& resize(const CImgDisplay& disp, const bool force_redraw=true) { return resize(disp.width(),disp.height(),force_redraw); } // [internal] Render pixel buffer with size (wd,hd) from source buffer of size (ws,hs). template<typename t, typename T> static void _render_resize(const T *ptrs, const unsigned int ws, const unsigned int hs, t *ptrd, const unsigned int wd, const unsigned int hd) { typedef typename cimg::last<T,cimg_ulong>::type ulongT; const ulongT one = (ulongT)1; CImg<ulongT> off_x(wd), off_y(hd + 1); if (wd==ws) off_x.fill(1); else { ulongT *poff_x = off_x._data, curr = 0; for (unsigned int x = 0; x<wd; ++x) { const ulongT old = curr; curr = (x + one)*ws/wd; *(poff_x++) = curr - old; } } if (hd==hs) off_y.fill(ws); else { ulongT *poff_y = off_y._data, curr = 0; for (unsigned int y = 0; y<hd; ++y) { const ulongT old = curr; curr = (y + one)*hs/hd; *(poff_y++) = ws*(curr - old); } *poff_y = 0; } ulongT *poff_y = off_y._data; for (unsigned int y = 0; y<hd; ) { const T *ptr = ptrs; ulongT *poff_x = off_x._data; for (unsigned int x = 0; x<wd; ++x) { *(ptrd++) = *ptr; ptr+=*(poff_x++); } ++y; ulongT dy = *(poff_y++); for ( ; !dy && y<hd; std::memcpy(ptrd,ptrd - wd,sizeof(t)*wd), ++y, ptrd+=wd, dy = *(poff_y++)) {} ptrs+=dy; } } //! Set normalization type. /** \param normalization New normalization mode. **/ CImgDisplay& set_normalization(const unsigned int normalization) { _normalization = normalization; _min = _max = 0; return *this; } #if cimg_display==0 //! Set title of the associated window. /** \param format C-string containing the format of the title, as with <tt>std::printf()</tt>. \warning As the first argument is a format string, it is highly recommended to write \code disp.set_title("%s",window_title); \endcode instead of \code disp.set_title(window_title); \endcode if \c window_title can be arbitrary, to prevent nasty memory access. **/ CImgDisplay& set_title(const char *const format, ...) { return assign(0,0,format); } #endif //! Enable or disable fullscreen mode. /** \param is_fullscreen Tells is the fullscreen mode must be activated or not. \param force_redraw Tells if the previous window content must be displayed as well. \note - When the fullscreen mode is enabled, the associated window fills the entire screen but the size of the current display is not modified. - The screen resolution may be switched to fit the associated window size and ensure it appears the largest as possible. For X-Window (X11) users, the configuration flag \c cimg_use_xrandr has to be set to allow the screen resolution change (requires the X11 extensions to be enabled). **/ CImgDisplay& set_fullscreen(const bool is_fullscreen, const bool force_redraw=true) { if (is_empty() || _is_fullscreen==is_fullscreen) return *this; return toggle_fullscreen(force_redraw); } #if cimg_display==0 //! Toggle fullscreen mode. /** \param force_redraw Tells if the previous window content must be displayed as well. \note Enable fullscreen mode if it was not enabled, and disable it otherwise. **/ CImgDisplay& toggle_fullscreen(const bool force_redraw=true) { return assign(_width,_height,0,3,force_redraw); } //! Show mouse pointer. /** \note Depending on the window manager behavior, this method may not succeed (no exceptions are thrown nevertheless). **/ CImgDisplay& show_mouse() { return assign(); } //! Hide mouse pointer. /** \note Depending on the window manager behavior, this method may not succeed (no exceptions are thrown nevertheless). **/ CImgDisplay& hide_mouse() { return assign(); } //! Move mouse pointer to a specified location. /** \note Depending on the window manager behavior, this method may not succeed (no exceptions are thrown nevertheless). **/ CImgDisplay& set_mouse(const int pos_x, const int pos_y) { return assign(pos_x,pos_y); } #endif //! Simulate a mouse button release event. /** \note All mouse buttons are considered released at the same time. **/ CImgDisplay& set_button() { _button = 0; _is_event = true; #if cimg_display==1 pthread_cond_broadcast(&cimg::X11_attr().wait_event); #elif cimg_display==2 SetEvent(cimg::Win32_attr().wait_event); #endif return *this; } //! Simulate a mouse button press or release event. /** \param button Buttons event code, where each button is associated to a single bit. \param is_pressed Tells if the mouse button is considered as pressed or released. **/ CImgDisplay& set_button(const unsigned int button, const bool is_pressed=true) { const unsigned int buttoncode = button==1U?1U:button==2U?2U:button==3U?4U:0U; if (is_pressed) _button |= buttoncode; else _button &= ~buttoncode; _is_event = buttoncode?true:false; if (buttoncode) { #if cimg_display==1 pthread_cond_broadcast(&cimg::X11_attr().wait_event); #elif cimg_display==2 SetEvent(cimg::Win32_attr().wait_event); #endif } return *this; } //! Flush all mouse wheel events. /** \note Make wheel() to return \c 0, if called afterwards. **/ CImgDisplay& set_wheel() { _wheel = 0; _is_event = true; #if cimg_display==1 pthread_cond_broadcast(&cimg::X11_attr().wait_event); #elif cimg_display==2 SetEvent(cimg::Win32_attr().wait_event); #endif return *this; } //! Simulate a wheel event. /** \param amplitude Amplitude of the wheel scrolling to simulate. \note Make wheel() to return \c amplitude, if called afterwards. **/ CImgDisplay& set_wheel(const int amplitude) { _wheel+=amplitude; _is_event = amplitude?true:false; if (amplitude) { #if cimg_display==1 pthread_cond_broadcast(&cimg::X11_attr().wait_event); #elif cimg_display==2 SetEvent(cimg::Win32_attr().wait_event); #endif } return *this; } //! Flush all key events. /** \note Make key() to return \c 0, if called afterwards. **/ CImgDisplay& set_key() { std::memset((void*)_keys,0,128*sizeof(unsigned int)); std::memset((void*)_released_keys,0,128*sizeof(unsigned int)); _is_keyESC = _is_keyF1 = _is_keyF2 = _is_keyF3 = _is_keyF4 = _is_keyF5 = _is_keyF6 = _is_keyF7 = _is_keyF8 = _is_keyF9 = _is_keyF10 = _is_keyF11 = _is_keyF12 = _is_keyPAUSE = _is_key1 = _is_key2 = _is_key3 = _is_key4 = _is_key5 = _is_key6 = _is_key7 = _is_key8 = _is_key9 = _is_key0 = _is_keyBACKSPACE = _is_keyINSERT = _is_keyHOME = _is_keyPAGEUP = _is_keyTAB = _is_keyQ = _is_keyW = _is_keyE = _is_keyR = _is_keyT = _is_keyY = _is_keyU = _is_keyI = _is_keyO = _is_keyP = _is_keyDELETE = _is_keyEND = _is_keyPAGEDOWN = _is_keyCAPSLOCK = _is_keyA = _is_keyS = _is_keyD = _is_keyF = _is_keyG = _is_keyH = _is_keyJ = _is_keyK = _is_keyL = _is_keyENTER = _is_keySHIFTLEFT = _is_keyZ = _is_keyX = _is_keyC = _is_keyV = _is_keyB = _is_keyN = _is_keyM = _is_keySHIFTRIGHT = _is_keyARROWUP = _is_keyCTRLLEFT = _is_keyAPPLEFT = _is_keyALT = _is_keySPACE = _is_keyALTGR = _is_keyAPPRIGHT = _is_keyMENU = _is_keyCTRLRIGHT = _is_keyARROWLEFT = _is_keyARROWDOWN = _is_keyARROWRIGHT = _is_keyPAD0 = _is_keyPAD1 = _is_keyPAD2 = _is_keyPAD3 = _is_keyPAD4 = _is_keyPAD5 = _is_keyPAD6 = _is_keyPAD7 = _is_keyPAD8 = _is_keyPAD9 = _is_keyPADADD = _is_keyPADSUB = _is_keyPADMUL = _is_keyPADDIV = false; _is_event = true; #if cimg_display==1 pthread_cond_broadcast(&cimg::X11_attr().wait_event); #elif cimg_display==2 SetEvent(cimg::Win32_attr().wait_event); #endif return *this; } //! Simulate a keyboard press/release event. /** \param keycode Keycode of the associated key. \param is_pressed Tells if the key is considered as pressed or released. \note Keycode constants are defined in the cimg namespace and are architecture-dependent. Use them to ensure your code stay portable (see cimg::keyESC). **/ CImgDisplay& set_key(const unsigned int keycode, const bool is_pressed=true) { #define _cimg_set_key(k) if (keycode==cimg::key##k) _is_key##k = is_pressed; _cimg_set_key(ESC); _cimg_set_key(F1); _cimg_set_key(F2); _cimg_set_key(F3); _cimg_set_key(F4); _cimg_set_key(F5); _cimg_set_key(F6); _cimg_set_key(F7); _cimg_set_key(F8); _cimg_set_key(F9); _cimg_set_key(F10); _cimg_set_key(F11); _cimg_set_key(F12); _cimg_set_key(PAUSE); _cimg_set_key(1); _cimg_set_key(2); _cimg_set_key(3); _cimg_set_key(4); _cimg_set_key(5); _cimg_set_key(6); _cimg_set_key(7); _cimg_set_key(8); _cimg_set_key(9); _cimg_set_key(0); _cimg_set_key(BACKSPACE); _cimg_set_key(INSERT); _cimg_set_key(HOME); _cimg_set_key(PAGEUP); _cimg_set_key(TAB); _cimg_set_key(Q); _cimg_set_key(W); _cimg_set_key(E); _cimg_set_key(R); _cimg_set_key(T); _cimg_set_key(Y); _cimg_set_key(U); _cimg_set_key(I); _cimg_set_key(O); _cimg_set_key(P); _cimg_set_key(DELETE); _cimg_set_key(END); _cimg_set_key(PAGEDOWN); _cimg_set_key(CAPSLOCK); _cimg_set_key(A); _cimg_set_key(S); _cimg_set_key(D); _cimg_set_key(F); _cimg_set_key(G); _cimg_set_key(H); _cimg_set_key(J); _cimg_set_key(K); _cimg_set_key(L); _cimg_set_key(ENTER); _cimg_set_key(SHIFTLEFT); _cimg_set_key(Z); _cimg_set_key(X); _cimg_set_key(C); _cimg_set_key(V); _cimg_set_key(B); _cimg_set_key(N); _cimg_set_key(M); _cimg_set_key(SHIFTRIGHT); _cimg_set_key(ARROWUP); _cimg_set_key(CTRLLEFT); _cimg_set_key(APPLEFT); _cimg_set_key(ALT); _cimg_set_key(SPACE); _cimg_set_key(ALTGR); _cimg_set_key(APPRIGHT); _cimg_set_key(MENU); _cimg_set_key(CTRLRIGHT); _cimg_set_key(ARROWLEFT); _cimg_set_key(ARROWDOWN); _cimg_set_key(ARROWRIGHT); _cimg_set_key(PAD0); _cimg_set_key(PAD1); _cimg_set_key(PAD2); _cimg_set_key(PAD3); _cimg_set_key(PAD4); _cimg_set_key(PAD5); _cimg_set_key(PAD6); _cimg_set_key(PAD7); _cimg_set_key(PAD8); _cimg_set_key(PAD9); _cimg_set_key(PADADD); _cimg_set_key(PADSUB); _cimg_set_key(PADMUL); _cimg_set_key(PADDIV); if (is_pressed) { if (*_keys) std::memmove((void*)(_keys + 1),(void*)_keys,127*sizeof(unsigned int)); *_keys = keycode; if (*_released_keys) { std::memmove((void*)(_released_keys + 1),(void*)_released_keys,127*sizeof(unsigned int)); *_released_keys = 0; } } else { if (*_keys) { std::memmove((void*)(_keys + 1),(void*)_keys,127*sizeof(unsigned int)); *_keys = 0; } if (*_released_keys) std::memmove((void*)(_released_keys + 1),(void*)_released_keys,127*sizeof(unsigned int)); *_released_keys = keycode; } _is_event = keycode?true:false; if (keycode) { #if cimg_display==1 pthread_cond_broadcast(&cimg::X11_attr().wait_event); #elif cimg_display==2 SetEvent(cimg::Win32_attr().wait_event); #endif } return *this; } //! Flush all display events. /** \note Remove all passed events from the current display. **/ CImgDisplay& flush() { set_key().set_button().set_wheel(); _is_resized = _is_moved = _is_event = false; _fps_timer = _fps_frames = _timer = 0; _fps_fps = 0; return *this; } //! Wait for any user event occuring on the current display. CImgDisplay& wait() { wait(*this); return *this; } //! Wait for a given number of milliseconds since the last call to wait(). /** \param milliseconds Number of milliseconds to wait for. \note Similar to cimg::wait(). **/ CImgDisplay& wait(const unsigned int milliseconds) { cimg::wait(milliseconds,&_timer); return *this; } //! Wait for any event occuring on the display \c disp1. static void wait(CImgDisplay& disp1) { disp1._is_event = false; while (!disp1._is_closed && !disp1._is_event) wait_all(); } //! Wait for any event occuring either on the display \c disp1 or \c disp2. static void wait(CImgDisplay& disp1, CImgDisplay& disp2) { disp1._is_event = disp2._is_event = false; while ((!disp1._is_closed || !disp2._is_closed) && !disp1._is_event && !disp2._is_event) wait_all(); } //! Wait for any event occuring either on the display \c disp1, \c disp2 or \c disp3. static void wait(CImgDisplay& disp1, CImgDisplay& disp2, CImgDisplay& disp3) { disp1._is_event = disp2._is_event = disp3._is_event = false; while ((!disp1._is_closed || !disp2._is_closed || !disp3._is_closed) && !disp1._is_event && !disp2._is_event && !disp3._is_event) wait_all(); } //! Wait for any event occuring either on the display \c disp1, \c disp2, \c disp3 or \c disp4. static void wait(CImgDisplay& disp1, CImgDisplay& disp2, CImgDisplay& disp3, CImgDisplay& disp4) { disp1._is_event = disp2._is_event = disp3._is_event = disp4._is_event = false; while ((!disp1._is_closed || !disp2._is_closed || !disp3._is_closed || !disp4._is_closed) && !disp1._is_event && !disp2._is_event && !disp3._is_event && !disp4._is_event) wait_all(); } //! Wait for any event occuring either on the display \c disp1, \c disp2, \c disp3, \c disp4 or \c disp5. static void wait(CImgDisplay& disp1, CImgDisplay& disp2, CImgDisplay& disp3, CImgDisplay& disp4, CImgDisplay& disp5) { disp1._is_event = disp2._is_event = disp3._is_event = disp4._is_event = disp5._is_event = false; while ((!disp1._is_closed || !disp2._is_closed || !disp3._is_closed || !disp4._is_closed || !disp5._is_closed) && !disp1._is_event && !disp2._is_event && !disp3._is_event && !disp4._is_event && !disp5._is_event) wait_all(); } //! Wait for any event occuring either on the display \c disp1, \c disp2, \c disp3, \c disp4, ... \c disp6. static void wait(CImgDisplay& disp1, CImgDisplay& disp2, CImgDisplay& disp3, CImgDisplay& disp4, CImgDisplay& disp5, CImgDisplay& disp6) { disp1._is_event = disp2._is_event = disp3._is_event = disp4._is_event = disp5._is_event = disp6._is_event = false; while ((!disp1._is_closed || !disp2._is_closed || !disp3._is_closed || !disp4._is_closed || !disp5._is_closed || !disp6._is_closed) && !disp1._is_event && !disp2._is_event && !disp3._is_event && !disp4._is_event && !disp5._is_event && !disp6._is_event) wait_all(); } //! Wait for any event occuring either on the display \c disp1, \c disp2, \c disp3, \c disp4, ... \c disp7. static void wait(CImgDisplay& disp1, CImgDisplay& disp2, CImgDisplay& disp3, CImgDisplay& disp4, CImgDisplay& disp5, CImgDisplay& disp6, CImgDisplay& disp7) { disp1._is_event = disp2._is_event = disp3._is_event = disp4._is_event = disp5._is_event = disp6._is_event = disp7._is_event = false; while ((!disp1._is_closed || !disp2._is_closed || !disp3._is_closed || !disp4._is_closed || !disp5._is_closed || !disp6._is_closed || !disp7._is_closed) && !disp1._is_event && !disp2._is_event && !disp3._is_event && !disp4._is_event && !disp5._is_event && !disp6._is_event && !disp7._is_event) wait_all(); } //! Wait for any event occuring either on the display \c disp1, \c disp2, \c disp3, \c disp4, ... \c disp8. static void wait(CImgDisplay& disp1, CImgDisplay& disp2, CImgDisplay& disp3, CImgDisplay& disp4, CImgDisplay& disp5, CImgDisplay& disp6, CImgDisplay& disp7, CImgDisplay& disp8) { disp1._is_event = disp2._is_event = disp3._is_event = disp4._is_event = disp5._is_event = disp6._is_event = disp7._is_event = disp8._is_event = false; while ((!disp1._is_closed || !disp2._is_closed || !disp3._is_closed || !disp4._is_closed || !disp5._is_closed || !disp6._is_closed || !disp7._is_closed || !disp8._is_closed) && !disp1._is_event && !disp2._is_event && !disp3._is_event && !disp4._is_event && !disp5._is_event && !disp6._is_event && !disp7._is_event && !disp8._is_event) wait_all(); } //! Wait for any event occuring either on the display \c disp1, \c disp2, \c disp3, \c disp4, ... \c disp9. static void wait(CImgDisplay& disp1, CImgDisplay& disp2, CImgDisplay& disp3, CImgDisplay& disp4, CImgDisplay& disp5, CImgDisplay& disp6, CImgDisplay& disp7, CImgDisplay& disp8, CImgDisplay& disp9) { disp1._is_event = disp2._is_event = disp3._is_event = disp4._is_event = disp5._is_event = disp6._is_event = disp7._is_event = disp8._is_event = disp9._is_event = false; while ((!disp1._is_closed || !disp2._is_closed || !disp3._is_closed || !disp4._is_closed || !disp5._is_closed || !disp6._is_closed || !disp7._is_closed || !disp8._is_closed || !disp9._is_closed) && !disp1._is_event && !disp2._is_event && !disp3._is_event && !disp4._is_event && !disp5._is_event && !disp6._is_event && !disp7._is_event && !disp8._is_event && !disp9._is_event) wait_all(); } //! Wait for any event occuring either on the display \c disp1, \c disp2, \c disp3, \c disp4, ... \c disp10. static void wait(CImgDisplay& disp1, CImgDisplay& disp2, CImgDisplay& disp3, CImgDisplay& disp4, CImgDisplay& disp5, CImgDisplay& disp6, CImgDisplay& disp7, CImgDisplay& disp8, CImgDisplay& disp9, CImgDisplay& disp10) { disp1._is_event = disp2._is_event = disp3._is_event = disp4._is_event = disp5._is_event = disp6._is_event = disp7._is_event = disp8._is_event = disp9._is_event = disp10._is_event = false; while ((!disp1._is_closed || !disp2._is_closed || !disp3._is_closed || !disp4._is_closed || !disp5._is_closed || !disp6._is_closed || !disp7._is_closed || !disp8._is_closed || !disp9._is_closed || !disp10._is_closed) && !disp1._is_event && !disp2._is_event && !disp3._is_event && !disp4._is_event && !disp5._is_event && !disp6._is_event && !disp7._is_event && !disp8._is_event && !disp9._is_event && !disp10._is_event) wait_all(); } #if cimg_display==0 //! Wait for any window event occuring in any opened CImgDisplay. static void wait_all() { return _no_display_exception(); } //! Render image into internal display buffer. /** \param img Input image data to render. \note - Convert image data representation into the internal display buffer (architecture-dependent structure). - The content of the associated window is not modified, until paint() is called. - Should not be used for common CImgDisplay uses, since display() is more useful. **/ template<typename T> CImgDisplay& render(const CImg<T>& img) { return assign(img); } //! Paint internal display buffer on associated window. /** \note - Update the content of the associated window with the internal display buffer, e.g. after a render() call. - Should not be used for common CImgDisplay uses, since display() is more useful. **/ CImgDisplay& paint() { return assign(); } //! Take a snapshot of the current screen content. /** \param x0 X-coordinate of the upper left corner. \param y0 Y-coordinate of the upper left corner. \param x1 X-coordinate of the lower right corner. \param y1 Y-coordinate of the lower right corner. \param[out] img Output screenshot. Can be empty on input **/ template<typename T> static void screenshot(const int x0, const int y0, const int x1, const int y1, CImg<T>& img) { cimg::unused(x0,y0,x1,y1,&img); _no_display_exception(); } //! Take a snapshot of the associated window content. /** \param[out] img Output snapshot. Can be empty on input. **/ template<typename T> const CImgDisplay& snapshot(CImg<T>& img) const { cimg::unused(img); _no_display_exception(); return *this; } #endif // X11-based implementation //-------------------------- #if cimg_display==1 Atom _wm_window_atom, _wm_protocol_atom; Window _window, _background_window; Colormap _colormap; XImage *_image; void *_data; #ifdef cimg_use_xshm XShmSegmentInfo *_shminfo; #endif static int screen_width() { Display *const dpy = cimg::X11_attr().display; int res = 0; if (!dpy) { Display *const _dpy = XOpenDisplay(0); if (!_dpy) throw CImgDisplayException("CImgDisplay::screen_width(): Failed to open X11 display."); res = DisplayWidth(_dpy,DefaultScreen(_dpy)); XCloseDisplay(_dpy); } else { #ifdef cimg_use_xrandr if (cimg::X11_attr().resolutions && cimg::X11_attr().curr_resolution) res = cimg::X11_attr().resolutions[cimg::X11_attr().curr_resolution].width; else res = DisplayWidth(dpy,DefaultScreen(dpy)); #else res = DisplayWidth(dpy,DefaultScreen(dpy)); #endif } return res; } static int screen_height() { Display *const dpy = cimg::X11_attr().display; int res = 0; if (!dpy) { Display *const _dpy = XOpenDisplay(0); if (!_dpy) throw CImgDisplayException("CImgDisplay::screen_height(): Failed to open X11 display."); res = DisplayHeight(_dpy,DefaultScreen(_dpy)); XCloseDisplay(_dpy); } else { #ifdef cimg_use_xrandr if (cimg::X11_attr().resolutions && cimg::X11_attr().curr_resolution) res = cimg::X11_attr().resolutions[cimg::X11_attr().curr_resolution].height; else res = DisplayHeight(dpy,DefaultScreen(dpy)); #else res = DisplayHeight(dpy,DefaultScreen(dpy)); #endif } return res; } static void wait_all() { if (!cimg::X11_attr().display) return; pthread_mutex_lock(&cimg::X11_attr().wait_event_mutex); pthread_cond_wait(&cimg::X11_attr().wait_event,&cimg::X11_attr().wait_event_mutex); pthread_mutex_unlock(&cimg::X11_attr().wait_event_mutex); } void _handle_events(const XEvent *const pevent) { Display *const dpy = cimg::X11_attr().display; XEvent event = *pevent; switch (event.type) { case ClientMessage : { if ((int)event.xclient.message_type==(int)_wm_protocol_atom && (int)event.xclient.data.l[0]==(int)_wm_window_atom) { XUnmapWindow(cimg::X11_attr().display,_window); _is_closed = _is_event = true; pthread_cond_broadcast(&cimg::X11_attr().wait_event); } } break; case ConfigureNotify : { while (XCheckWindowEvent(dpy,_window,StructureNotifyMask,&event)) {} const unsigned int nw = event.xconfigure.width, nh = event.xconfigure.height; const int nx = event.xconfigure.x, ny = event.xconfigure.y; if (nw && nh && (nw!=_window_width || nh!=_window_height)) { _window_width = nw; _window_height = nh; _mouse_x = _mouse_y = -1; XResizeWindow(dpy,_window,_window_width,_window_height); _is_resized = _is_event = true; pthread_cond_broadcast(&cimg::X11_attr().wait_event); } if (nx!=_window_x || ny!=_window_y) { _window_x = nx; _window_y = ny; _is_moved = _is_event = true; pthread_cond_broadcast(&cimg::X11_attr().wait_event); } } break; case Expose : { while (XCheckWindowEvent(dpy,_window,ExposureMask,&event)) {} _paint(false); if (_is_fullscreen) { XWindowAttributes attr; XGetWindowAttributes(dpy,_window,&attr); while (attr.map_state!=IsViewable) XSync(dpy,0); XSetInputFocus(dpy,_window,RevertToParent,CurrentTime); } } break; case ButtonPress : { do { _mouse_x = event.xmotion.x; _mouse_y = event.xmotion.y; if (_mouse_x<0 || _mouse_y<0 || _mouse_x>=width() || _mouse_y>=height()) _mouse_x = _mouse_y = -1; switch (event.xbutton.button) { case 1 : set_button(1); break; case 3 : set_button(2); break; case 2 : set_button(3); break; } } while (XCheckWindowEvent(dpy,_window,ButtonPressMask,&event)); } break; case ButtonRelease : { do { _mouse_x = event.xmotion.x; _mouse_y = event.xmotion.y; if (_mouse_x<0 || _mouse_y<0 || _mouse_x>=width() || _mouse_y>=height()) _mouse_x = _mouse_y = -1; switch (event.xbutton.button) { case 1 : set_button(1,false); break; case 3 : set_button(2,false); break; case 2 : set_button(3,false); break; case 4 : set_wheel(1); break; case 5 : set_wheel(-1); break; } } while (XCheckWindowEvent(dpy,_window,ButtonReleaseMask,&event)); } break; case KeyPress : { char tmp = 0; KeySym ksym; XLookupString(&event.xkey,&tmp,1,&ksym,0); set_key((unsigned int)ksym,true); } break; case KeyRelease : { char keys_return[32]; // Check that the key has been physically unpressed XQueryKeymap(dpy,keys_return); const unsigned int kc = event.xkey.keycode, kc1 = kc/8, kc2 = kc%8; const bool is_key_pressed = kc1>=32?false:(keys_return[kc1]>>kc2)&1; if (!is_key_pressed) { char tmp = 0; KeySym ksym; XLookupString(&event.xkey,&tmp,1,&ksym,0); set_key((unsigned int)ksym,false); } } break; case EnterNotify: { while (XCheckWindowEvent(dpy,_window,EnterWindowMask,&event)) {} _mouse_x = event.xmotion.x; _mouse_y = event.xmotion.y; if (_mouse_x<0 || _mouse_y<0 || _mouse_x>=width() || _mouse_y>=height()) _mouse_x = _mouse_y = -1; } break; case LeaveNotify : { while (XCheckWindowEvent(dpy,_window,LeaveWindowMask,&event)) {} _mouse_x = _mouse_y = -1; _is_event = true; pthread_cond_broadcast(&cimg::X11_attr().wait_event); } break; case MotionNotify : { while (XCheckWindowEvent(dpy,_window,PointerMotionMask,&event)) {} _mouse_x = event.xmotion.x; _mouse_y = event.xmotion.y; if (_mouse_x<0 || _mouse_y<0 || _mouse_x>=width() || _mouse_y>=height()) _mouse_x = _mouse_y = -1; _is_event = true; pthread_cond_broadcast(&cimg::X11_attr().wait_event); } break; } } static void* _events_thread(void *arg) { // Thread to manage events for all opened display windows Display *const dpy = cimg::X11_attr().display; XEvent event; pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED,0); pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,0); if (!arg) for ( ; ; ) { cimg_lock_display(); bool event_flag = XCheckTypedEvent(dpy,ClientMessage,&event); if (!event_flag) event_flag = XCheckMaskEvent(dpy, ExposureMask | StructureNotifyMask | ButtonPressMask | KeyPressMask | PointerMotionMask | EnterWindowMask | LeaveWindowMask | ButtonReleaseMask | KeyReleaseMask,&event); if (event_flag) for (unsigned int i = 0; i<cimg::X11_attr().nb_wins; ++i) if (!cimg::X11_attr().wins[i]->_is_closed && event.xany.window==cimg::X11_attr().wins[i]->_window) cimg::X11_attr().wins[i]->_handle_events(&event); cimg_unlock_display(); pthread_testcancel(); cimg::sleep(8); } return 0; } void _set_colormap(Colormap& cmap, const unsigned int dim) { XColor *const colormap = new XColor[256]; switch (dim) { case 1 : { // colormap for greyscale images for (unsigned int index = 0; index<256; ++index) { colormap[index].pixel = index; colormap[index].red = colormap[index].green = colormap[index].blue = (unsigned short)(index<<8); colormap[index].flags = DoRed | DoGreen | DoBlue; } } break; case 2 : { // colormap for RG images for (unsigned int index = 0, r = 8; r<256; r+=16) for (unsigned int g = 8; g<256; g+=16) { colormap[index].pixel = index; colormap[index].red = colormap[index].blue = (unsigned short)(r<<8); colormap[index].green = (unsigned short)(g<<8); colormap[index++].flags = DoRed | DoGreen | DoBlue; } } break; default : { // colormap for RGB images for (unsigned int index = 0, r = 16; r<256; r+=32) for (unsigned int g = 16; g<256; g+=32) for (unsigned int b = 32; b<256; b+=64) { colormap[index].pixel = index; colormap[index].red = (unsigned short)(r<<8); colormap[index].green = (unsigned short)(g<<8); colormap[index].blue = (unsigned short)(b<<8); colormap[index++].flags = DoRed | DoGreen | DoBlue; } } } XStoreColors(cimg::X11_attr().display,cmap,colormap,256); delete[] colormap; } void _map_window() { Display *const dpy = cimg::X11_attr().display; bool is_exposed = false, is_mapped = false; XWindowAttributes attr; XEvent event; XMapRaised(dpy,_window); do { // Wait for the window to be mapped XWindowEvent(dpy,_window,StructureNotifyMask | ExposureMask,&event); switch (event.type) { case MapNotify : is_mapped = true; break; case Expose : is_exposed = true; break; } } while (!is_exposed || !is_mapped); do { // Wait for the window to be visible XGetWindowAttributes(dpy,_window,&attr); if (attr.map_state!=IsViewable) { XSync(dpy,0); cimg::sleep(10); } } while (attr.map_state!=IsViewable); _window_x = attr.x; _window_y = attr.y; } void _paint(const bool wait_expose=true) { if (_is_closed || !_image) return; Display *const dpy = cimg::X11_attr().display; if (wait_expose) { // Send an expose event sticked to display window to force repaint XEvent event; event.xexpose.type = Expose; event.xexpose.serial = 0; event.xexpose.send_event = 1; event.xexpose.display = dpy; event.xexpose.window = _window; event.xexpose.x = 0; event.xexpose.y = 0; event.xexpose.width = width(); event.xexpose.height = height(); event.xexpose.count = 0; XSendEvent(dpy,_window,0,0,&event); } else { // Repaint directly (may be called from the expose event) GC gc = DefaultGC(dpy,DefaultScreen(dpy)); #ifdef cimg_use_xshm if (_shminfo) XShmPutImage(dpy,_window,gc,_image,0,0,0,0,_width,_height,1); else XPutImage(dpy,_window,gc,_image,0,0,0,0,_width,_height); #else XPutImage(dpy,_window,gc,_image,0,0,0,0,_width,_height); #endif } } template<typename T> void _resize(T pixel_type, const unsigned int ndimx, const unsigned int ndimy, const bool force_redraw) { Display *const dpy = cimg::X11_attr().display; cimg::unused(pixel_type); #ifdef cimg_use_xshm if (_shminfo) { XShmSegmentInfo *const nshminfo = new XShmSegmentInfo; XImage *const nimage = XShmCreateImage(dpy,DefaultVisual(dpy,DefaultScreen(dpy)), cimg::X11_attr().nb_bits,ZPixmap,0,nshminfo,ndimx,ndimy); if (!nimage) { delete nshminfo; return; } else { nshminfo->shmid = shmget(IPC_PRIVATE,ndimx*ndimy*sizeof(T),IPC_CREAT | 0777); if (nshminfo->shmid==-1) { XDestroyImage(nimage); delete nshminfo; return; } else { nshminfo->shmaddr = nimage->data = (char*)shmat(nshminfo->shmid,0,0); if (nshminfo->shmaddr==(char*)-1) { shmctl(nshminfo->shmid,IPC_RMID,0); XDestroyImage(nimage); delete nshminfo; return; } else { nshminfo->readOnly = 0; cimg::X11_attr().is_shm_enabled = true; XErrorHandler oldXErrorHandler = XSetErrorHandler(_assign_xshm); XShmAttach(dpy,nshminfo); XFlush(dpy); XSetErrorHandler(oldXErrorHandler); if (!cimg::X11_attr().is_shm_enabled) { shmdt(nshminfo->shmaddr); shmctl(nshminfo->shmid,IPC_RMID,0); XDestroyImage(nimage); delete nshminfo; return; } else { T *const ndata = (T*)nimage->data; if (force_redraw) _render_resize((T*)_data,_width,_height,ndata,ndimx,ndimy); else std::memset(ndata,0,sizeof(T)*ndimx*ndimy); XShmDetach(dpy,_shminfo); XDestroyImage(_image); shmdt(_shminfo->shmaddr); shmctl(_shminfo->shmid,IPC_RMID,0); delete _shminfo; _shminfo = nshminfo; _image = nimage; _data = (void*)ndata; } } } } } else #endif { T *ndata = (T*)std::malloc(ndimx*ndimy*sizeof(T)); if (force_redraw) _render_resize((T*)_data,_width,_height,ndata,ndimx,ndimy); else std::memset(ndata,0,sizeof(T)*ndimx*ndimy); _data = (void*)ndata; XDestroyImage(_image); _image = XCreateImage(dpy,DefaultVisual(dpy,DefaultScreen(dpy)), cimg::X11_attr().nb_bits,ZPixmap,0,(char*)_data,ndimx,ndimy,8,0); } } void _init_fullscreen() { if (!_is_fullscreen || _is_closed) return; Display *const dpy = cimg::X11_attr().display; _background_window = 0; #ifdef cimg_use_xrandr int foo; if (XRRQueryExtension(dpy,&foo,&foo)) { XRRRotations(dpy,DefaultScreen(dpy),&cimg::X11_attr().curr_rotation); if (!cimg::X11_attr().resolutions) { cimg::X11_attr().resolutions = XRRSizes(dpy,DefaultScreen(dpy),&foo); cimg::X11_attr().nb_resolutions = (unsigned int)foo; } if (cimg::X11_attr().resolutions) { cimg::X11_attr().curr_resolution = 0; for (unsigned int i = 0; i<cimg::X11_attr().nb_resolutions; ++i) { const unsigned int nw = (unsigned int)(cimg::X11_attr().resolutions[i].width), nh = (unsigned int)(cimg::X11_attr().resolutions[i].height); if (nw>=_width && nh>=_height && nw<=(unsigned int)(cimg::X11_attr().resolutions[cimg::X11_attr().curr_resolution].width) && nh<=(unsigned int)(cimg::X11_attr().resolutions[cimg::X11_attr().curr_resolution].height)) cimg::X11_attr().curr_resolution = i; } if (cimg::X11_attr().curr_resolution>0) { XRRScreenConfiguration *config = XRRGetScreenInfo(dpy,DefaultRootWindow(dpy)); XRRSetScreenConfig(dpy,config,DefaultRootWindow(dpy), cimg::X11_attr().curr_resolution,cimg::X11_attr().curr_rotation,CurrentTime); XRRFreeScreenConfigInfo(config); XSync(dpy,0); } } } if (!cimg::X11_attr().resolutions) cimg::warn(_cimgdisplay_instance "init_fullscreen(): Xrandr extension not supported by the X server.", cimgdisplay_instance); #endif const unsigned int sx = screen_width(), sy = screen_height(); if (sx==_width && sy==_height) return; XSetWindowAttributes winattr; winattr.override_redirect = 1; _background_window = XCreateWindow(dpy,DefaultRootWindow(dpy),0,0,sx,sy,0,0, InputOutput,CopyFromParent,CWOverrideRedirect,&winattr); const cimg_ulong buf_size = (cimg_ulong)sx*sy*(cimg::X11_attr().nb_bits==8?1: (cimg::X11_attr().nb_bits==16?2:4)); void *background_data = std::malloc(buf_size); std::memset(background_data,0,buf_size); XImage *background_image = XCreateImage(dpy,DefaultVisual(dpy,DefaultScreen(dpy)),cimg::X11_attr().nb_bits, ZPixmap,0,(char*)background_data,sx,sy,8,0); XEvent event; XSelectInput(dpy,_background_window,StructureNotifyMask); XMapRaised(dpy,_background_window); do XWindowEvent(dpy,_background_window,StructureNotifyMask,&event); while (event.type!=MapNotify); GC gc = DefaultGC(dpy,DefaultScreen(dpy)); #ifdef cimg_use_xshm if (_shminfo) XShmPutImage(dpy,_background_window,gc,background_image,0,0,0,0,sx,sy,0); else XPutImage(dpy,_background_window,gc,background_image,0,0,0,0,sx,sy); #else XPutImage(dpy,_background_window,gc,background_image,0,0,0,0,sx,sy); #endif XWindowAttributes attr; XGetWindowAttributes(dpy,_background_window,&attr); while (attr.map_state!=IsViewable) XSync(dpy,0); XDestroyImage(background_image); } void _desinit_fullscreen() { if (!_is_fullscreen) return; Display *const dpy = cimg::X11_attr().display; XUngrabKeyboard(dpy,CurrentTime); #ifdef cimg_use_xrandr if (cimg::X11_attr().resolutions && cimg::X11_attr().curr_resolution) { XRRScreenConfiguration *config = XRRGetScreenInfo(dpy,DefaultRootWindow(dpy)); XRRSetScreenConfig(dpy,config,DefaultRootWindow(dpy),0,cimg::X11_attr().curr_rotation,CurrentTime); XRRFreeScreenConfigInfo(config); XSync(dpy,0); cimg::X11_attr().curr_resolution = 0; } #endif if (_background_window) XDestroyWindow(dpy,_background_window); _background_window = 0; _is_fullscreen = false; } static int _assign_xshm(Display *dpy, XErrorEvent *error) { cimg::unused(dpy,error); cimg::X11_attr().is_shm_enabled = false; return 0; } void _assign(const unsigned int dimw, const unsigned int dimh, const char *const ptitle=0, const unsigned int normalization_type=3, const bool fullscreen_flag=false, const bool closed_flag=false) { cimg::mutex(14); // Allocate space for window title const char *const nptitle = ptitle?ptitle:""; const unsigned int s = (unsigned int)std::strlen(nptitle) + 1; char *const tmp_title = s?new char[s]:0; if (s) std::memcpy(tmp_title,nptitle,s*sizeof(char)); // Destroy previous display window if existing if (!is_empty()) assign(); // Open X11 display and retrieve graphical properties. Display* &dpy = cimg::X11_attr().display; if (!dpy) { dpy = XOpenDisplay(0); if (!dpy) throw CImgDisplayException(_cimgdisplay_instance "assign(): Failed to open X11 display.", cimgdisplay_instance); cimg::X11_attr().nb_bits = DefaultDepth(dpy,DefaultScreen(dpy)); if (cimg::X11_attr().nb_bits!=8 && cimg::X11_attr().nb_bits!=16 && cimg::X11_attr().nb_bits!=24 && cimg::X11_attr().nb_bits!=32) throw CImgDisplayException(_cimgdisplay_instance "assign(): Invalid %u bits screen mode detected " "(only 8, 16, 24 and 32 bits modes are managed).", cimgdisplay_instance, cimg::X11_attr().nb_bits); XVisualInfo vtemplate; vtemplate.visualid = XVisualIDFromVisual(DefaultVisual(dpy,DefaultScreen(dpy))); int nb_visuals; XVisualInfo *vinfo = XGetVisualInfo(dpy,VisualIDMask,&vtemplate,&nb_visuals); if (vinfo && vinfo->red_mask<vinfo->blue_mask) cimg::X11_attr().is_blue_first = true; cimg::X11_attr().byte_order = ImageByteOrder(dpy); XFree(vinfo); cimg_lock_display(); cimg::X11_attr().events_thread = new pthread_t; pthread_create(cimg::X11_attr().events_thread,0,_events_thread,0); } else cimg_lock_display(); // Set display variables. _width = std::min(dimw,(unsigned int)screen_width()); _height = std::min(dimh,(unsigned int)screen_height()); _normalization = normalization_type<4?normalization_type:3; _is_fullscreen = fullscreen_flag; _window_x = _window_y = 0; _is_closed = closed_flag; _title = tmp_title; flush(); // Create X11 window (and LUT, if 8bits display) if (_is_fullscreen) { if (!_is_closed) _init_fullscreen(); const unsigned int sx = screen_width(), sy = screen_height(); XSetWindowAttributes winattr; winattr.override_redirect = 1; _window = XCreateWindow(dpy,DefaultRootWindow(dpy),(sx - _width)/2,(sy - _height)/2,_width,_height,0,0, InputOutput,CopyFromParent,CWOverrideRedirect,&winattr); } else _window = XCreateSimpleWindow(dpy,DefaultRootWindow(dpy),0,0,_width,_height,0,0L,0L); XSelectInput(dpy,_window, ExposureMask | StructureNotifyMask | ButtonPressMask | KeyPressMask | PointerMotionMask | EnterWindowMask | LeaveWindowMask | ButtonReleaseMask | KeyReleaseMask); XStoreName(dpy,_window,_title?_title:" "); if (cimg::X11_attr().nb_bits==8) { _colormap = XCreateColormap(dpy,_window,DefaultVisual(dpy,DefaultScreen(dpy)),AllocAll); _set_colormap(_colormap,3); XSetWindowColormap(dpy,_window,_colormap); } static const char *const _window_class = cimg_appname; XClassHint *const window_class = XAllocClassHint(); window_class->res_name = (char*)_window_class; window_class->res_class = (char*)_window_class; XSetClassHint(dpy,_window,window_class); XFree(window_class); _window_width = _width; _window_height = _height; // Create XImage #ifdef cimg_use_xshm _shminfo = 0; if (XShmQueryExtension(dpy)) { _shminfo = new XShmSegmentInfo; _image = XShmCreateImage(dpy,DefaultVisual(dpy,DefaultScreen(dpy)),cimg::X11_attr().nb_bits, ZPixmap,0,_shminfo,_width,_height); if (!_image) { delete _shminfo; _shminfo = 0; } else { _shminfo->shmid = shmget(IPC_PRIVATE,_image->bytes_per_line*_image->height,IPC_CREAT|0777); if (_shminfo->shmid==-1) { XDestroyImage(_image); delete _shminfo; _shminfo = 0; } else { _shminfo->shmaddr = _image->data = (char*)(_data = shmat(_shminfo->shmid,0,0)); if (_shminfo->shmaddr==(char*)-1) { shmctl(_shminfo->shmid,IPC_RMID,0); XDestroyImage(_image); delete _shminfo; _shminfo = 0; } else { _shminfo->readOnly = 0; cimg::X11_attr().is_shm_enabled = true; XErrorHandler oldXErrorHandler = XSetErrorHandler(_assign_xshm); XShmAttach(dpy,_shminfo); XSync(dpy,0); XSetErrorHandler(oldXErrorHandler); if (!cimg::X11_attr().is_shm_enabled) { shmdt(_shminfo->shmaddr); shmctl(_shminfo->shmid,IPC_RMID,0); XDestroyImage(_image); delete _shminfo; _shminfo = 0; } } } } } if (!_shminfo) #endif { const cimg_ulong buf_size = (cimg_ulong)_width*_height*(cimg::X11_attr().nb_bits==8?1: (cimg::X11_attr().nb_bits==16?2:4)); _data = std::malloc(buf_size); _image = XCreateImage(dpy,DefaultVisual(dpy,DefaultScreen(dpy)),cimg::X11_attr().nb_bits, ZPixmap,0,(char*)_data,_width,_height,8,0); } _wm_window_atom = XInternAtom(dpy,"WM_DELETE_WINDOW",0); _wm_protocol_atom = XInternAtom(dpy,"WM_PROTOCOLS",0); XSetWMProtocols(dpy,_window,&_wm_window_atom,1); if (_is_fullscreen) XGrabKeyboard(dpy,_window,1,GrabModeAsync,GrabModeAsync,CurrentTime); cimg::X11_attr().wins[cimg::X11_attr().nb_wins++]=this; if (!_is_closed) _map_window(); else { _window_x = _window_y = cimg::type<int>::min(); } cimg_unlock_display(); cimg::mutex(14,0); } CImgDisplay& assign() { if (is_empty()) return flush(); Display *const dpy = cimg::X11_attr().display; cimg_lock_display(); // Remove display window from event thread list. unsigned int i; for (i = 0; i<cimg::X11_attr().nb_wins && cimg::X11_attr().wins[i]!=this; ++i) {} for ( ; i<cimg::X11_attr().nb_wins - 1; ++i) cimg::X11_attr().wins[i] = cimg::X11_attr().wins[i + 1]; --cimg::X11_attr().nb_wins; // Destroy window, image, colormap and title. if (_is_fullscreen && !_is_closed) _desinit_fullscreen(); XDestroyWindow(dpy,_window); _window = 0; #ifdef cimg_use_xshm if (_shminfo) { XShmDetach(dpy,_shminfo); XDestroyImage(_image); shmdt(_shminfo->shmaddr); shmctl(_shminfo->shmid,IPC_RMID,0); delete _shminfo; _shminfo = 0; } else #endif XDestroyImage(_image); _data = 0; _image = 0; if (cimg::X11_attr().nb_bits==8) XFreeColormap(dpy,_colormap); _colormap = 0; XSync(dpy,0); // Reset display variables. delete[] _title; _width = _height = _normalization = _window_width = _window_height = 0; _window_x = _window_y = 0; _is_fullscreen = false; _is_closed = true; _min = _max = 0; _title = 0; flush(); cimg_unlock_display(); return *this; } CImgDisplay& assign(const unsigned int dimw, const unsigned int dimh, const char *const title=0, const unsigned int normalization_type=3, const bool fullscreen_flag=false, const bool closed_flag=false) { if (!dimw || !dimh) return assign(); _assign(dimw,dimh,title,normalization_type,fullscreen_flag,closed_flag); _min = _max = 0; std::memset(_data,0,(cimg::X11_attr().nb_bits==8?sizeof(unsigned char): (cimg::X11_attr().nb_bits==16?sizeof(unsigned short):sizeof(unsigned int)))* (size_t)_width*_height); return paint(); } template<typename T> CImgDisplay& assign(const CImg<T>& img, const char *const title=0, const unsigned int normalization_type=3, const bool fullscreen_flag=false, const bool closed_flag=false) { if (!img) return assign(); CImg<T> tmp; const CImg<T>& nimg = (img._depth==1)?img:(tmp=img.get_projections2d((img._width - 1)/2, (img._height - 1)/2, (img._depth - 1)/2)); _assign(nimg._width,nimg._height,title,normalization_type,fullscreen_flag,closed_flag); if (_normalization==2) _min = (float)nimg.min_max(_max); return render(nimg).paint(); } template<typename T> CImgDisplay& assign(const CImgList<T>& list, const char *const title=0, const unsigned int normalization_type=3, const bool fullscreen_flag=false, const bool closed_flag=false) { if (!list) return assign(); CImg<T> tmp; const CImg<T> img = list>'x', &nimg = (img._depth==1)?img:(tmp=img.get_projections2d((img._width - 1)/2, (img._height - 1)/2, (img._depth - 1)/2)); _assign(nimg._width,nimg._height,title,normalization_type,fullscreen_flag,closed_flag); if (_normalization==2) _min = (float)nimg.min_max(_max); return render(nimg).paint(); } CImgDisplay& assign(const CImgDisplay& disp) { if (!disp) return assign(); _assign(disp._width,disp._height,disp._title,disp._normalization,disp._is_fullscreen,disp._is_closed); std::memcpy(_data,disp._data,(cimg::X11_attr().nb_bits==8?sizeof(unsigned char): cimg::X11_attr().nb_bits==16?sizeof(unsigned short): sizeof(unsigned int))*(size_t)_width*_height); return paint(); } CImgDisplay& resize(const int nwidth, const int nheight, const bool force_redraw=true) { if (!nwidth || !nheight || (is_empty() && (nwidth<0 || nheight<0))) return assign(); if (is_empty()) return assign(nwidth,nheight); Display *const dpy = cimg::X11_attr().display; const unsigned int tmpdimx = (nwidth>0)?nwidth:(-nwidth*width()/100), tmpdimy = (nheight>0)?nheight:(-nheight*height()/100), dimx = tmpdimx?tmpdimx:1, dimy = tmpdimy?tmpdimy:1; if (_width!=dimx || _height!=dimy || _window_width!=dimx || _window_height!=dimy) { show(); cimg_lock_display(); if (_window_width!=dimx || _window_height!=dimy) { XWindowAttributes attr; for (unsigned int i = 0; i<10; ++i) { XResizeWindow(dpy,_window,dimx,dimy); XGetWindowAttributes(dpy,_window,&attr); if (attr.width==(int)dimx && attr.height==(int)dimy) break; cimg::wait(5,&_timer); } } if (_width!=dimx || _height!=dimy) switch (cimg::X11_attr().nb_bits) { case 8 : { unsigned char pixel_type = 0; _resize(pixel_type,dimx,dimy,force_redraw); } break; case 16 : { unsigned short pixel_type = 0; _resize(pixel_type,dimx,dimy,force_redraw); } break; default : { unsigned int pixel_type = 0; _resize(pixel_type,dimx,dimy,force_redraw); } } _window_width = _width = dimx; _window_height = _height = dimy; cimg_unlock_display(); } _is_resized = false; if (_is_fullscreen) move((screen_width() - _width)/2,(screen_height() - _height)/2); if (force_redraw) return paint(); return *this; } CImgDisplay& toggle_fullscreen(const bool force_redraw=true) { if (is_empty()) return *this; if (force_redraw) { const cimg_ulong buf_size = (cimg_ulong)_width*_height* (cimg::X11_attr().nb_bits==8?1:(cimg::X11_attr().nb_bits==16?2:4)); void *image_data = std::malloc(buf_size); std::memcpy(image_data,_data,buf_size); assign(_width,_height,_title,_normalization,!_is_fullscreen,false); std::memcpy(_data,image_data,buf_size); std::free(image_data); return paint(); } return assign(_width,_height,_title,_normalization,!_is_fullscreen,false); } CImgDisplay& show() { if (is_empty() || !_is_closed) return *this; cimg_lock_display(); if (_is_fullscreen) _init_fullscreen(); _map_window(); _is_closed = false; cimg_unlock_display(); return paint(); } CImgDisplay& close() { if (is_empty() || _is_closed) return *this; Display *const dpy = cimg::X11_attr().display; cimg_lock_display(); if (_is_fullscreen) _desinit_fullscreen(); XUnmapWindow(dpy,_window); _window_x = _window_y = -1; _is_closed = true; cimg_unlock_display(); return *this; } CImgDisplay& move(const int posx, const int posy) { if (is_empty()) return *this; if (_window_x!=posx || _window_y!=posy) { show(); Display *const dpy = cimg::X11_attr().display; cimg_lock_display(); XMoveWindow(dpy,_window,posx,posy); _window_x = posx; _window_y = posy; cimg_unlock_display(); } _is_moved = false; return paint(); } CImgDisplay& show_mouse() { if (is_empty()) return *this; Display *const dpy = cimg::X11_attr().display; cimg_lock_display(); XUndefineCursor(dpy,_window); cimg_unlock_display(); return *this; } CImgDisplay& hide_mouse() { if (is_empty()) return *this; Display *const dpy = cimg::X11_attr().display; cimg_lock_display(); static const char pix_data[8] = { 0 }; XColor col; col.red = col.green = col.blue = 0; Pixmap pix = XCreateBitmapFromData(dpy,_window,pix_data,8,8); Cursor cur = XCreatePixmapCursor(dpy,pix,pix,&col,&col,0,0); XFreePixmap(dpy,pix); XDefineCursor(dpy,_window,cur); cimg_unlock_display(); return *this; } CImgDisplay& set_mouse(const int posx, const int posy) { if (is_empty() || _is_closed) return *this; Display *const dpy = cimg::X11_attr().display; cimg_lock_display(); XWarpPointer(dpy,0L,_window,0,0,0,0,posx,posy); _mouse_x = posx; _mouse_y = posy; _is_moved = false; XSync(dpy,0); cimg_unlock_display(); return *this; } CImgDisplay& set_title(const char *const format, ...) { if (is_empty()) return *this; char *const tmp = new char[1024]; va_list ap; va_start(ap, format); cimg_vsnprintf(tmp,1024,format,ap); va_end(ap); if (!std::strcmp(_title,tmp)) { delete[] tmp; return *this; } delete[] _title; const unsigned int s = (unsigned int)std::strlen(tmp) + 1; _title = new char[s]; std::memcpy(_title,tmp,s*sizeof(char)); Display *const dpy = cimg::X11_attr().display; cimg_lock_display(); XStoreName(dpy,_window,tmp); cimg_unlock_display(); delete[] tmp; return *this; } template<typename T> CImgDisplay& display(const CImg<T>& img) { if (!img) throw CImgArgumentException(_cimgdisplay_instance "display(): Empty specified image.", cimgdisplay_instance); if (is_empty()) return assign(img); return render(img).paint(false); } CImgDisplay& paint(const bool wait_expose=true) { if (is_empty()) return *this; cimg_lock_display(); _paint(wait_expose); cimg_unlock_display(); return *this; } template<typename T> CImgDisplay& render(const CImg<T>& img, const bool flag8=false) { if (!img) throw CImgArgumentException(_cimgdisplay_instance "render(): Empty specified image.", cimgdisplay_instance); if (is_empty()) return *this; if (img._depth!=1) return render(img.get_projections2d((img._width - 1)/2,(img._height - 1)/2, (img._depth - 1)/2)); if (cimg::X11_attr().nb_bits==8 && (img._width!=_width || img._height!=_height)) return render(img.get_resize(_width,_height,1,-100,1)); if (cimg::X11_attr().nb_bits==8 && !flag8 && img._spectrum==3) { static const CImg<typename CImg<T>::ucharT> default_colormap = CImg<typename CImg<T>::ucharT>::default_LUT256(); return render(img.get_index(default_colormap,1,false)); } const T *data1 = img._data, *data2 = (img._spectrum>1)?img.data(0,0,0,1):data1, *data3 = (img._spectrum>2)?img.data(0,0,0,2):data1; if (cimg::X11_attr().is_blue_first) cimg::swap(data1,data3); cimg_lock_display(); if (!_normalization || (_normalization==3 && cimg::type<T>::string()==cimg::type<unsigned char>::string())) { _min = _max = 0; switch (cimg::X11_attr().nb_bits) { case 8 : { // 256 colormap, no normalization _set_colormap(_colormap,img._spectrum); unsigned char *const ndata = (img._width==_width && img._height==_height)?(unsigned char*)_data: new unsigned char[(size_t)img._width*img._height], *ptrd = (unsigned char*)ndata; switch (img._spectrum) { case 1 : for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) (*ptrd++) = (unsigned char)*(data1++); break; case 2 : for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char R = (unsigned char)*(data1++), G = (unsigned char)*(data2++); (*ptrd++) = (R&0xf0) | (G>>4); } break; default : for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char R = (unsigned char)*(data1++), G = (unsigned char)*(data2++), B = (unsigned char)*(data3++); (*ptrd++) = (R&0xe0) | ((G>>5)<<2) | (B>>6); } } if (ndata!=_data) { _render_resize(ndata,img._width,img._height,(unsigned char*)_data,_width,_height); delete[] ndata; } } break; case 16 : { // 16 bits colors, no normalization unsigned short *const ndata = (img._width==_width && img._height==_height)?(unsigned short*)_data: new unsigned short[(size_t)img._width*img._height]; unsigned char *ptrd = (unsigned char*)ndata; const unsigned int M = 248; switch (img._spectrum) { case 1 : if (cimg::X11_attr().byte_order) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)*(data1++), G = val>>2; ptrd[0] = (val&M) | (G>>3); ptrd[1] = (G<<5) | (G>>1); ptrd+=2; } else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)*(data1++), G = val>>2; ptrd[0] = (G<<5) | (G>>1); ptrd[1] = (val&M) | (G>>3); ptrd+=2; } break; case 2 : if (cimg::X11_attr().byte_order) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char G = (unsigned char)*(data2++)>>2; ptrd[0] = ((unsigned char)*(data1++)&M) | (G>>3); ptrd[1] = (G<<5); ptrd+=2; } else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char G = (unsigned char)*(data2++)>>2; ptrd[0] = (G<<5); ptrd[1] = ((unsigned char)*(data1++)&M) | (G>>3); ptrd+=2; } break; default : if (cimg::X11_attr().byte_order) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char G = (unsigned char)*(data2++)>>2; ptrd[0] = ((unsigned char)*(data1++)&M) | (G>>3); ptrd[1] = (G<<5) | ((unsigned char)*(data3++)>>3); ptrd+=2; } else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char G = (unsigned char)*(data2++)>>2; ptrd[0] = (G<<5) | ((unsigned char)*(data3++)>>3); ptrd[1] = ((unsigned char)*(data1++)&M) | (G>>3); ptrd+=2; } } if (ndata!=_data) { _render_resize(ndata,img._width,img._height,(unsigned short*)_data,_width,_height); delete[] ndata; } } break; default : { // 24 bits colors, no normalization unsigned int *const ndata = (img._width==_width && img._height==_height)?(unsigned int*)_data: new unsigned int[(size_t)img._width*img._height]; if (sizeof(int)==4) { // 32 bits int uses optimized version unsigned int *ptrd = ndata; switch (img._spectrum) { case 1 : if (cimg::X11_attr().byte_order==cimg::endianness()) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)*(data1++); *(ptrd++) = (val<<16) | (val<<8) | val; } else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)*(data1++); *(ptrd++) = (val<<16) | (val<<8) | val; } break; case 2 : if (cimg::X11_attr().byte_order==cimg::endianness()) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) *(ptrd++) = ((unsigned char)*(data1++)<<16) | ((unsigned char)*(data2++)<<8); else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) *(ptrd++) = ((unsigned char)*(data2++)<<16) | ((unsigned char)*(data1++)<<8); break; default : if (cimg::X11_attr().byte_order==cimg::endianness()) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) *(ptrd++) = ((unsigned char)*(data1++)<<16) | ((unsigned char)*(data2++)<<8) | (unsigned char)*(data3++); else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) *(ptrd++) = ((unsigned char)*(data3++)<<24) | ((unsigned char)*(data2++)<<16) | ((unsigned char)*(data1++)<<8); } } else { unsigned char *ptrd = (unsigned char*)ndata; switch (img._spectrum) { case 1 : if (cimg::X11_attr().byte_order) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { ptrd[0] = 0; ptrd[1] = (unsigned char)*(data1++); ptrd[2] = 0; ptrd[3] = 0; ptrd+=4; } else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { ptrd[0] = 0; ptrd[1] = 0; ptrd[2] = (unsigned char)*(data1++); ptrd[3] = 0; ptrd+=4; } break; case 2 : if (cimg::X11_attr().byte_order) cimg::swap(data1,data2); for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { ptrd[0] = 0; ptrd[1] = (unsigned char)*(data2++); ptrd[2] = (unsigned char)*(data1++); ptrd[3] = 0; ptrd+=4; } break; default : if (cimg::X11_attr().byte_order) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { ptrd[0] = 0; ptrd[1] = (unsigned char)*(data1++); ptrd[2] = (unsigned char)*(data2++); ptrd[3] = (unsigned char)*(data3++); ptrd+=4; } else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { ptrd[0] = (unsigned char)*(data3++); ptrd[1] = (unsigned char)*(data2++); ptrd[2] = (unsigned char)*(data1++); ptrd[3] = 0; ptrd+=4; } } } if (ndata!=_data) { _render_resize(ndata,img._width,img._height,(unsigned int*)_data,_width,_height); delete[] ndata; } } } } else { if (_normalization==3) { if (cimg::type<T>::is_float()) _min = (float)img.min_max(_max); else { _min = (float)cimg::type<T>::min(); _max = (float)cimg::type<T>::max(); } } else if ((_min>_max) || _normalization==1) _min = (float)img.min_max(_max); const float delta = _max - _min, mm = 255/(delta?delta:1.f); switch (cimg::X11_attr().nb_bits) { case 8 : { // 256 colormap, with normalization _set_colormap(_colormap,img._spectrum); unsigned char *const ndata = (img._width==_width && img._height==_height)?(unsigned char*)_data: new unsigned char[(size_t)img._width*img._height]; unsigned char *ptrd = (unsigned char*)ndata; switch (img._spectrum) { case 1 : for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char R = (unsigned char)((*(data1++) - _min)*mm); *(ptrd++) = R; } break; case 2 : for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char R = (unsigned char)((*(data1++) - _min)*mm), G = (unsigned char)((*(data2++) - _min)*mm); (*ptrd++) = (R&0xf0) | (G>>4); } break; default : for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char R = (unsigned char)((*(data1++) - _min)*mm), G = (unsigned char)((*(data2++) - _min)*mm), B = (unsigned char)((*(data3++) - _min)*mm); *(ptrd++) = (R&0xe0) | ((G>>5)<<2) | (B>>6); } } if (ndata!=_data) { _render_resize(ndata,img._width,img._height,(unsigned char*)_data,_width,_height); delete[] ndata; } } break; case 16 : { // 16 bits colors, with normalization unsigned short *const ndata = (img._width==_width && img._height==_height)?(unsigned short*)_data: new unsigned short[(size_t)img._width*img._height]; unsigned char *ptrd = (unsigned char*)ndata; const unsigned int M = 248; switch (img._spectrum) { case 1 : if (cimg::X11_attr().byte_order) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)((*(data1++) - _min)*mm), G = val>>2; ptrd[0] = (val&M) | (G>>3); ptrd[1] = (G<<5) | (val>>3); ptrd+=2; } else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)((*(data1++) - _min)*mm), G = val>>2; ptrd[0] = (G<<5) | (val>>3); ptrd[1] = (val&M) | (G>>3); ptrd+=2; } break; case 2 : if (cimg::X11_attr().byte_order) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char G = (unsigned char)((*(data2++) - _min)*mm)>>2; ptrd[0] = ((unsigned char)((*(data1++) - _min)*mm)&M) | (G>>3); ptrd[1] = (G<<5); ptrd+=2; } else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char G = (unsigned char)((*(data2++) - _min)*mm)>>2; ptrd[0] = (G<<5); ptrd[1] = ((unsigned char)((*(data1++) - _min)*mm)&M) | (G>>3); ptrd+=2; } break; default : if (cimg::X11_attr().byte_order) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char G = (unsigned char)((*(data2++) - _min)*mm)>>2; ptrd[0] = ((unsigned char)((*(data1++) - _min)*mm)&M) | (G>>3); ptrd[1] = (G<<5) | ((unsigned char)((*(data3++) - _min)*mm)>>3); ptrd+=2; } else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char G = (unsigned char)((*(data2++) - _min)*mm)>>2; ptrd[0] = (G<<5) | ((unsigned char)((*(data3++) - _min)*mm)>>3); ptrd[1] = ((unsigned char)((*(data1++) - _min)*mm)&M) | (G>>3); ptrd+=2; } } if (ndata!=_data) { _render_resize(ndata,img._width,img._height,(unsigned short*)_data,_width,_height); delete[] ndata; } } break; default : { // 24 bits colors, with normalization unsigned int *const ndata = (img._width==_width && img._height==_height)?(unsigned int*)_data: new unsigned int[(size_t)img._width*img._height]; if (sizeof(int)==4) { // 32 bits int uses optimized version unsigned int *ptrd = ndata; switch (img._spectrum) { case 1 : if (cimg::X11_attr().byte_order==cimg::endianness()) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)((*(data1++) - _min)*mm); *(ptrd++) = (val<<16) | (val<<8) | val; } else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)((*(data1++) - _min)*mm); *(ptrd++) = (val<<24) | (val<<16) | (val<<8); } break; case 2 : if (cimg::X11_attr().byte_order==cimg::endianness()) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) *(ptrd++) = ((unsigned char)((*(data1++) - _min)*mm)<<16) | ((unsigned char)((*(data2++) - _min)*mm)<<8); else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) *(ptrd++) = ((unsigned char)((*(data2++) - _min)*mm)<<16) | ((unsigned char)((*(data1++) - _min)*mm)<<8); break; default : if (cimg::X11_attr().byte_order==cimg::endianness()) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) *(ptrd++) = ((unsigned char)((*(data1++) - _min)*mm)<<16) | ((unsigned char)((*(data2++) - _min)*mm)<<8) | (unsigned char)((*(data3++) - _min)*mm); else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) *(ptrd++) = ((unsigned char)((*(data3++) - _min)*mm)<<24) | ((unsigned char)((*(data2++) - _min)*mm)<<16) | ((unsigned char)((*(data1++) - _min)*mm)<<8); } } else { unsigned char *ptrd = (unsigned char*)ndata; switch (img._spectrum) { case 1 : if (cimg::X11_attr().byte_order) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)((*(data1++) - _min)*mm); ptrd[0] = 0; ptrd[1] = val; ptrd[2] = val; ptrd[3] = val; ptrd+=4; } else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)((*(data1++) - _min)*mm); ptrd[0] = val; ptrd[1] = val; ptrd[2] = val; ptrd[3] = 0; ptrd+=4; } break; case 2 : if (cimg::X11_attr().byte_order) cimg::swap(data1,data2); for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { ptrd[0] = 0; ptrd[1] = (unsigned char)((*(data2++) - _min)*mm); ptrd[2] = (unsigned char)((*(data1++) - _min)*mm); ptrd[3] = 0; ptrd+=4; } break; default : if (cimg::X11_attr().byte_order) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { ptrd[0] = 0; ptrd[1] = (unsigned char)((*(data1++) - _min)*mm); ptrd[2] = (unsigned char)((*(data2++) - _min)*mm); ptrd[3] = (unsigned char)((*(data3++) - _min)*mm); ptrd+=4; } else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { ptrd[0] = (unsigned char)((*(data3++) - _min)*mm); ptrd[1] = (unsigned char)((*(data2++) - _min)*mm); ptrd[2] = (unsigned char)((*(data1++) - _min)*mm); ptrd[3] = 0; ptrd+=4; } } } if (ndata!=_data) { _render_resize(ndata,img._width,img._height,(unsigned int*)_data,_width,_height); delete[] ndata; } } } } cimg_unlock_display(); return *this; } template<typename T> static void screenshot(const int x0, const int y0, const int x1, const int y1, CImg<T>& img) { img.assign(); Display *dpy = cimg::X11_attr().display; cimg_lock_display(); if (!dpy) { dpy = XOpenDisplay(0); if (!dpy) throw CImgDisplayException("CImgDisplay::screenshot(): Failed to open X11 display."); } Window root = DefaultRootWindow(dpy); XWindowAttributes gwa; XGetWindowAttributes(dpy,root,&gwa); const int width = gwa.width, height = gwa.height; int _x0 = x0, _y0 = y0, _x1 = x1, _y1 = y1; if (_x0>_x1) cimg::swap(_x0,_x1); if (_y0>_y1) cimg::swap(_y0,_y1); XImage *image = 0; if (_x1>=0 && _x0<width && _y1>=0 && _y0<height) { _x0 = std::max(_x0,0); _y0 = std::max(_y0,0); _x1 = std::min(_x1,width - 1); _y1 = std::min(_y1,height - 1); image = XGetImage(dpy,root,_x0,_y0,_x1 - _x0 + 1,_y1 - _y0 + 1,AllPlanes,ZPixmap); if (image) { const unsigned long red_mask = image->red_mask, green_mask = image->green_mask, blue_mask = image->blue_mask; img.assign(image->width,image->height,1,3); T *pR = img.data(0,0,0,0), *pG = img.data(0,0,0,1), *pB = img.data(0,0,0,2); cimg_forXY(img,x,y) { const unsigned long pixel = XGetPixel(image,x,y); *(pR++) = (T)((pixel & red_mask)>>16); *(pG++) = (T)((pixel & green_mask)>>8); *(pB++) = (T)(pixel & blue_mask); } XDestroyImage(image); } } if (!cimg::X11_attr().display) XCloseDisplay(dpy); cimg_unlock_display(); if (img.is_empty()) throw CImgDisplayException("CImgDisplay::screenshot(): Failed to take screenshot " "with coordinates (%d,%d)-(%d,%d).", x0,y0,x1,y1); } template<typename T> const CImgDisplay& snapshot(CImg<T>& img) const { if (is_empty()) { img.assign(); return *this; } const unsigned char *ptrs = (unsigned char*)_data; img.assign(_width,_height,1,3); T *data1 = img.data(0,0,0,0), *data2 = img.data(0,0,0,1), *data3 = img.data(0,0,0,2); if (cimg::X11_attr().is_blue_first) cimg::swap(data1,data3); switch (cimg::X11_attr().nb_bits) { case 8 : { for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char val = *(ptrs++); *(data1++) = (T)(val&0xe0); *(data2++) = (T)((val&0x1c)<<3); *(data3++) = (T)(val<<6); } } break; case 16 : { if (cimg::X11_attr().byte_order) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char val0 = ptrs[0], val1 = ptrs[1]; ptrs+=2; *(data1++) = (T)(val0&0xf8); *(data2++) = (T)((val0<<5) | ((val1&0xe0)>>5)); *(data3++) = (T)(val1<<3); } else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned short val0 = ptrs[0], val1 = ptrs[1]; ptrs+=2; *(data1++) = (T)(val1&0xf8); *(data2++) = (T)((val1<<5) | ((val0&0xe0)>>5)); *(data3++) = (T)(val0<<3); } } break; default : { if (cimg::X11_attr().byte_order) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { ++ptrs; *(data1++) = (T)ptrs[0]; *(data2++) = (T)ptrs[1]; *(data3++) = (T)ptrs[2]; ptrs+=3; } else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { *(data3++) = (T)ptrs[0]; *(data2++) = (T)ptrs[1]; *(data1++) = (T)ptrs[2]; ptrs+=3; ++ptrs; } } } return *this; } // Windows-based implementation. //------------------------------- #elif cimg_display==2 bool _is_mouse_tracked, _is_cursor_visible; HANDLE _thread, _is_created, _mutex; HWND _window, _background_window; CLIENTCREATESTRUCT _ccs; unsigned int *_data; DEVMODE _curr_mode; BITMAPINFO _bmi; HDC _hdc; static int screen_width() { DEVMODE mode; mode.dmSize = sizeof(DEVMODE); mode.dmDriverExtra = 0; EnumDisplaySettings(0,ENUM_CURRENT_SETTINGS,&mode); return (int)mode.dmPelsWidth; } static int screen_height() { DEVMODE mode; mode.dmSize = sizeof(DEVMODE); mode.dmDriverExtra = 0; EnumDisplaySettings(0,ENUM_CURRENT_SETTINGS,&mode); return (int)mode.dmPelsHeight; } static void wait_all() { WaitForSingleObject(cimg::Win32_attr().wait_event,INFINITE); } static LRESULT APIENTRY _handle_events(HWND window, UINT msg, WPARAM wParam, LPARAM lParam) { #ifdef _WIN64 CImgDisplay *const disp = (CImgDisplay*)GetWindowLongPtr(window,GWLP_USERDATA); #else CImgDisplay *const disp = (CImgDisplay*)GetWindowLong(window,GWL_USERDATA); #endif MSG st_msg; switch (msg) { case WM_CLOSE : disp->_mouse_x = disp->_mouse_y = -1; disp->_window_x = disp->_window_y = 0; disp->set_button().set_key(0).set_key(0,false)._is_closed = true; ReleaseMutex(disp->_mutex); ShowWindow(disp->_window,SW_HIDE); disp->_is_event = true; SetEvent(cimg::Win32_attr().wait_event); return 0; case WM_SIZE : { while (PeekMessage(&st_msg,window,WM_SIZE,WM_SIZE,PM_REMOVE)) {} WaitForSingleObject(disp->_mutex,INFINITE); const unsigned int nw = LOWORD(lParam),nh = HIWORD(lParam); if (nw && nh && (nw!=disp->_width || nh!=disp->_height)) { disp->_window_width = nw; disp->_window_height = nh; disp->_mouse_x = disp->_mouse_y = -1; disp->_is_resized = disp->_is_event = true; SetEvent(cimg::Win32_attr().wait_event); } ReleaseMutex(disp->_mutex); } break; case WM_MOVE : { while (PeekMessage(&st_msg,window,WM_SIZE,WM_SIZE,PM_REMOVE)) {} WaitForSingleObject(disp->_mutex,INFINITE); const int nx = (int)(short)(LOWORD(lParam)), ny = (int)(short)(HIWORD(lParam)); if (nx!=disp->_window_x || ny!=disp->_window_y) { disp->_window_x = nx; disp->_window_y = ny; disp->_is_moved = disp->_is_event = true; SetEvent(cimg::Win32_attr().wait_event); } ReleaseMutex(disp->_mutex); } break; case WM_PAINT : disp->paint(); cimg_lock_display(); if (disp->_is_cursor_visible) while (ShowCursor(TRUE)<0); else while (ShowCursor(FALSE)>=0); cimg_unlock_display(); break; case WM_ERASEBKGND : // return 0; break; case WM_KEYDOWN : disp->set_key((unsigned int)wParam); SetEvent(cimg::Win32_attr().wait_event); break; case WM_KEYUP : disp->set_key((unsigned int)wParam,false); SetEvent(cimg::Win32_attr().wait_event); break; case WM_MOUSEMOVE : { while (PeekMessage(&st_msg,window,WM_MOUSEMOVE,WM_MOUSEMOVE,PM_REMOVE)) {} disp->_mouse_x = LOWORD(lParam); disp->_mouse_y = HIWORD(lParam); #if (_WIN32_WINNT>=0x0400) && !defined(NOTRACKMOUSEEVENT) if (!disp->_is_mouse_tracked) { TRACKMOUSEEVENT tme; tme.cbSize = sizeof(TRACKMOUSEEVENT); tme.dwFlags = TME_LEAVE; tme.hwndTrack = disp->_window; if (TrackMouseEvent(&tme)) disp->_is_mouse_tracked = true; } #endif if (disp->_mouse_x<0 || disp->_mouse_y<0 || disp->_mouse_x>=disp->width() || disp->_mouse_y>=disp->height()) disp->_mouse_x = disp->_mouse_y = -1; disp->_is_event = true; SetEvent(cimg::Win32_attr().wait_event); cimg_lock_display(); if (disp->_is_cursor_visible) while (ShowCursor(TRUE)<0); else while (ShowCursor(FALSE)>=0); cimg_unlock_display(); } break; case WM_MOUSELEAVE : { disp->_mouse_x = disp->_mouse_y = -1; disp->_is_mouse_tracked = false; cimg_lock_display(); while (ShowCursor(TRUE)<0) {} cimg_unlock_display(); } break; case WM_LBUTTONDOWN : disp->set_button(1); SetEvent(cimg::Win32_attr().wait_event); break; case WM_RBUTTONDOWN : disp->set_button(2); SetEvent(cimg::Win32_attr().wait_event); break; case WM_MBUTTONDOWN : disp->set_button(3); SetEvent(cimg::Win32_attr().wait_event); break; case WM_LBUTTONUP : disp->set_button(1,false); SetEvent(cimg::Win32_attr().wait_event); break; case WM_RBUTTONUP : disp->set_button(2,false); SetEvent(cimg::Win32_attr().wait_event); break; case WM_MBUTTONUP : disp->set_button(3,false); SetEvent(cimg::Win32_attr().wait_event); break; case 0x020A : // WM_MOUSEWHEEL: disp->set_wheel((int)((short)HIWORD(wParam))/120); SetEvent(cimg::Win32_attr().wait_event); } return DefWindowProc(window,msg,wParam,lParam); } static DWORD WINAPI _events_thread(void* arg) { CImgDisplay *const disp = (CImgDisplay*)(((void**)arg)[0]); const char *const title = (const char*)(((void**)arg)[1]); MSG msg; delete[] (void**)arg; disp->_bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); disp->_bmi.bmiHeader.biWidth = disp->width(); disp->_bmi.bmiHeader.biHeight = -disp->height(); disp->_bmi.bmiHeader.biPlanes = 1; disp->_bmi.bmiHeader.biBitCount = 32; disp->_bmi.bmiHeader.biCompression = BI_RGB; disp->_bmi.bmiHeader.biSizeImage = 0; disp->_bmi.bmiHeader.biXPelsPerMeter = 1; disp->_bmi.bmiHeader.biYPelsPerMeter = 1; disp->_bmi.bmiHeader.biClrUsed = 0; disp->_bmi.bmiHeader.biClrImportant = 0; disp->_data = new unsigned int[(size_t)disp->_width*disp->_height]; if (!disp->_is_fullscreen) { // Normal window RECT rect; rect.left = rect.top = 0; rect.right = (LONG)disp->_width - 1; rect.bottom = (LONG)disp->_height - 1; AdjustWindowRect(&rect,WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX,false); const int border1 = (int)((rect.right - rect.left + 1 - disp->_width)/2), border2 = (int)(rect.bottom - rect.top + 1 - disp->_height - border1), ww = disp->_width + 2*border1, wh = disp->_height + border1 + border2, sw = CImgDisplay::screen_width(), sh = CImgDisplay::screen_height(); int wx = (int)cimg::round(cimg::rand(0,sw - ww -1)), wy = (int)cimg::round(cimg::rand(64,sh - wh - 65)); if (wx + ww>=sw) wx = sw - ww; if (wy + wh>=sh) wy = sh - wh; if (wx<0) wx = 0; if (wy<0) wy = 0; disp->_window = CreateWindowA("MDICLIENT",title?title:" ", WS_OVERLAPPEDWINDOW | (disp->_is_closed?0:WS_VISIBLE), wx,wy,ww,wh,0,0,0,&(disp->_ccs)); if (!disp->_is_closed) { GetWindowRect(disp->_window,&rect); disp->_window_x = rect.left + border1; disp->_window_y = rect.top + border2; } else disp->_window_x = disp->_window_y = 0; } else { // Fullscreen window const unsigned int sx = (unsigned int)screen_width(), sy = (unsigned int)screen_height(); disp->_window = CreateWindowA("MDICLIENT",title?title:" ", WS_POPUP | (disp->_is_closed?0:WS_VISIBLE), (sx - disp->_width)/2, (sy - disp->_height)/2, disp->_width,disp->_height,0,0,0,&(disp->_ccs)); disp->_window_x = disp->_window_y = 0; } SetForegroundWindow(disp->_window); disp->_hdc = GetDC(disp->_window); disp->_window_width = disp->_width; disp->_window_height = disp->_height; disp->flush(); #ifdef _WIN64 SetWindowLongPtr(disp->_window,GWLP_USERDATA,(LONG_PTR)disp); SetWindowLongPtr(disp->_window,GWLP_WNDPROC,(LONG_PTR)_handle_events); #else SetWindowLong(disp->_window,GWL_USERDATA,(LONG)disp); SetWindowLong(disp->_window,GWL_WNDPROC,(LONG)_handle_events); #endif SetEvent(disp->_is_created); while (GetMessage(&msg,0,0,0)) DispatchMessage(&msg); return 0; } CImgDisplay& _update_window_pos() { if (_is_closed) _window_x = _window_y = -1; else { RECT rect; rect.left = rect.top = 0; rect.right = (LONG)_width - 1; rect.bottom = (LONG)_height - 1; AdjustWindowRect(&rect,WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX,false); const int border1 = (int)((rect.right - rect.left + 1 - _width)/2), border2 = (int)(rect.bottom - rect.top + 1 - _height - border1); GetWindowRect(_window,&rect); _window_x = rect.left + border1; _window_y = rect.top + border2; } return *this; } void _init_fullscreen() { _background_window = 0; if (!_is_fullscreen || _is_closed) _curr_mode.dmSize = 0; else { DEVMODE mode; unsigned int imode = 0, ibest = 0, bestbpp = 0, bw = ~0U, bh = ~0U; for (mode.dmSize = sizeof(DEVMODE), mode.dmDriverExtra = 0; EnumDisplaySettings(0,imode,&mode); ++imode) { const unsigned int nw = mode.dmPelsWidth, nh = mode.dmPelsHeight; if (nw>=_width && nh>=_height && mode.dmBitsPerPel>=bestbpp && nw<=bw && nh<=bh) { bestbpp = mode.dmBitsPerPel; ibest = imode; bw = nw; bh = nh; } } if (bestbpp) { _curr_mode.dmSize = sizeof(DEVMODE); _curr_mode.dmDriverExtra = 0; EnumDisplaySettings(0,ENUM_CURRENT_SETTINGS,&_curr_mode); EnumDisplaySettings(0,ibest,&mode); ChangeDisplaySettings(&mode,0); } else _curr_mode.dmSize = 0; const unsigned int sx = (unsigned int)screen_width(), sy = (unsigned int)screen_height(); if (sx!=_width || sy!=_height) { CLIENTCREATESTRUCT background_ccs; _background_window = CreateWindowA("MDICLIENT","",WS_POPUP | WS_VISIBLE, 0,0,sx,sy,0,0,0,&background_ccs); SetForegroundWindow(_background_window); } } } void _desinit_fullscreen() { if (!_is_fullscreen) return; if (_background_window) DestroyWindow(_background_window); _background_window = 0; if (_curr_mode.dmSize) ChangeDisplaySettings(&_curr_mode,0); _is_fullscreen = false; } CImgDisplay& _assign(const unsigned int dimw, const unsigned int dimh, const char *const ptitle=0, const unsigned int normalization_type=3, const bool fullscreen_flag=false, const bool closed_flag=false) { // Allocate space for window title const char *const nptitle = ptitle?ptitle:""; const unsigned int s = (unsigned int)std::strlen(nptitle) + 1; char *const tmp_title = s?new char[s]:0; if (s) std::memcpy(tmp_title,nptitle,s*sizeof(char)); // Destroy previous window if existing if (!is_empty()) assign(); // Set display variables _width = std::min(dimw,(unsigned int)screen_width()); _height = std::min(dimh,(unsigned int)screen_height()); _normalization = normalization_type<4?normalization_type:3; _is_fullscreen = fullscreen_flag; _window_x = _window_y = 0; _is_closed = closed_flag; _is_cursor_visible = true; _is_mouse_tracked = false; _title = tmp_title; flush(); if (_is_fullscreen) _init_fullscreen(); // Create event thread void *const arg = (void*)(new void*[2]); ((void**)arg)[0] = (void*)this; ((void**)arg)[1] = (void*)_title; _mutex = CreateMutex(0,FALSE,0); _is_created = CreateEvent(0,FALSE,FALSE,0); _thread = CreateThread(0,0,_events_thread,arg,0,0); WaitForSingleObject(_is_created,INFINITE); return *this; } CImgDisplay& assign() { if (is_empty()) return flush(); DestroyWindow(_window); TerminateThread(_thread,0); delete[] _data; delete[] _title; _data = 0; _title = 0; if (_is_fullscreen) _desinit_fullscreen(); _width = _height = _normalization = _window_width = _window_height = 0; _window_x = _window_y = 0; _is_fullscreen = false; _is_closed = true; _min = _max = 0; _title = 0; flush(); return *this; } CImgDisplay& assign(const unsigned int dimw, const unsigned int dimh, const char *const title=0, const unsigned int normalization_type=3, const bool fullscreen_flag=false, const bool closed_flag=false) { if (!dimw || !dimh) return assign(); _assign(dimw,dimh,title,normalization_type,fullscreen_flag,closed_flag); _min = _max = 0; std::memset(_data,0,sizeof(unsigned int)*_width*_height); return paint(); } template<typename T> CImgDisplay& assign(const CImg<T>& img, const char *const title=0, const unsigned int normalization_type=3, const bool fullscreen_flag=false, const bool closed_flag=false) { if (!img) return assign(); CImg<T> tmp; const CImg<T>& nimg = (img._depth==1)?img:(tmp=img.get_projections2d((img._width - 1)/2, (img._height - 1)/2, (img._depth - 1)/2)); _assign(nimg._width,nimg._height,title,normalization_type,fullscreen_flag,closed_flag); if (_normalization==2) _min = (float)nimg.min_max(_max); return display(nimg); } template<typename T> CImgDisplay& assign(const CImgList<T>& list, const char *const title=0, const unsigned int normalization_type=3, const bool fullscreen_flag=false, const bool closed_flag=false) { if (!list) return assign(); CImg<T> tmp; const CImg<T> img = list>'x', &nimg = (img._depth==1)?img:(tmp=img.get_projections2d((img._width - 1)/2, (img._height - 1)/2, (img._depth - 1)/2)); _assign(nimg._width,nimg._height,title,normalization_type,fullscreen_flag,closed_flag); if (_normalization==2) _min = (float)nimg.min_max(_max); return display(nimg); } CImgDisplay& assign(const CImgDisplay& disp) { if (!disp) return assign(); _assign(disp._width,disp._height,disp._title,disp._normalization,disp._is_fullscreen,disp._is_closed); std::memcpy(_data,disp._data,sizeof(unsigned int)*_width*_height); return paint(); } CImgDisplay& resize(const int nwidth, const int nheight, const bool force_redraw=true) { if (!nwidth || !nheight || (is_empty() && (nwidth<0 || nheight<0))) return assign(); if (is_empty()) return assign(nwidth,nheight); const unsigned int tmpdimx = (nwidth>0)?nwidth:(-nwidth*_width/100), tmpdimy = (nheight>0)?nheight:(-nheight*_height/100), dimx = tmpdimx?tmpdimx:1, dimy = tmpdimy?tmpdimy:1; if (_width!=dimx || _height!=dimy || _window_width!=dimx || _window_height!=dimy) { if (_window_width!=dimx || _window_height!=dimy) { RECT rect; rect.left = rect.top = 0; rect.right = (LONG)dimx - 1; rect.bottom = (LONG)dimy - 1; AdjustWindowRect(&rect,WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX,false); const int cwidth = rect.right - rect.left + 1, cheight = rect.bottom - rect.top + 1; SetWindowPos(_window,0,0,0,cwidth,cheight,SWP_NOMOVE | SWP_NOZORDER | SWP_NOCOPYBITS); } if (_width!=dimx || _height!=dimy) { unsigned int *const ndata = new unsigned int[dimx*dimy]; if (force_redraw) _render_resize(_data,_width,_height,ndata,dimx,dimy); else std::memset(ndata,0x80,sizeof(unsigned int)*dimx*dimy); delete[] _data; _data = ndata; _bmi.bmiHeader.biWidth = (LONG)dimx; _bmi.bmiHeader.biHeight = -(int)dimy; _width = dimx; _height = dimy; } _window_width = dimx; _window_height = dimy; show(); } _is_resized = false; if (_is_fullscreen) move((screen_width() - width())/2,(screen_height() - height())/2); if (force_redraw) return paint(); return *this; } CImgDisplay& toggle_fullscreen(const bool force_redraw=true) { if (is_empty()) return *this; if (force_redraw) { const cimg_ulong buf_size = (cimg_ulong)_width*_height*4; void *odata = std::malloc(buf_size); if (odata) { std::memcpy(odata,_data,buf_size); assign(_width,_height,_title,_normalization,!_is_fullscreen,false); std::memcpy(_data,odata,buf_size); std::free(odata); } return paint(); } return assign(_width,_height,_title,_normalization,!_is_fullscreen,false); } CImgDisplay& show() { if (is_empty() || !_is_closed) return *this; _is_closed = false; if (_is_fullscreen) _init_fullscreen(); ShowWindow(_window,SW_SHOW); _update_window_pos(); return paint(); } CImgDisplay& close() { if (is_empty() || _is_closed) return *this; _is_closed = true; if (_is_fullscreen) _desinit_fullscreen(); ShowWindow(_window,SW_HIDE); _window_x = _window_y = 0; return *this; } CImgDisplay& move(const int posx, const int posy) { if (is_empty()) return *this; if (_window_x!=posx || _window_y!=posy) { if (!_is_fullscreen) { RECT rect; rect.left = rect.top = 0; rect.right = (LONG)_window_width - 1; rect.bottom = (LONG)_window_height - 1; AdjustWindowRect(&rect,WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX,false); const int border1 = (int)((rect.right - rect.left + 1 -_width)/2), border2 = (int)(rect.bottom - rect.top + 1 - _height - border1); SetWindowPos(_window,0,posx - border1,posy - border2,0,0,SWP_NOSIZE | SWP_NOZORDER); } else SetWindowPos(_window,0,posx,posy,0,0,SWP_NOSIZE | SWP_NOZORDER); _window_x = posx; _window_y = posy; show(); } _is_moved = false; return *this; } CImgDisplay& show_mouse() { if (is_empty()) return *this; _is_cursor_visible = true; return *this; } CImgDisplay& hide_mouse() { if (is_empty()) return *this; _is_cursor_visible = false; return *this; } CImgDisplay& set_mouse(const int posx, const int posy) { if (is_empty() || _is_closed || posx<0 || posy<0) return *this; _update_window_pos(); const int res = (int)SetCursorPos(_window_x + posx,_window_y + posy); if (res) { _mouse_x = posx; _mouse_y = posy; } return *this; } CImgDisplay& set_title(const char *const format, ...) { if (is_empty()) return *this; char *const tmp = new char[1024]; va_list ap; va_start(ap, format); cimg_vsnprintf(tmp,1024,format,ap); va_end(ap); if (!std::strcmp(_title,tmp)) { delete[] tmp; return *this; } delete[] _title; const unsigned int s = (unsigned int)std::strlen(tmp) + 1; _title = new char[s]; std::memcpy(_title,tmp,s*sizeof(char)); SetWindowTextA(_window, tmp); delete[] tmp; return *this; } template<typename T> CImgDisplay& display(const CImg<T>& img) { if (!img) throw CImgArgumentException(_cimgdisplay_instance "display(): Empty specified image.", cimgdisplay_instance); if (is_empty()) return assign(img); return render(img).paint(); } CImgDisplay& paint() { if (_is_closed) return *this; WaitForSingleObject(_mutex,INFINITE); SetDIBitsToDevice(_hdc,0,0,_width,_height,0,0,0,_height,_data,&_bmi,DIB_RGB_COLORS); ReleaseMutex(_mutex); return *this; } template<typename T> CImgDisplay& render(const CImg<T>& img) { if (!img) throw CImgArgumentException(_cimgdisplay_instance "render(): Empty specified image.", cimgdisplay_instance); if (is_empty()) return *this; if (img._depth!=1) return render(img.get_projections2d((img._width - 1)/2,(img._height - 1)/2, (img._depth - 1)/2)); const T *data1 = img._data, *data2 = (img._spectrum>=2)?img.data(0,0,0,1):data1, *data3 = (img._spectrum>=3)?img.data(0,0,0,2):data1; WaitForSingleObject(_mutex,INFINITE); unsigned int *const ndata = (img._width==_width && img._height==_height)?_data: new unsigned int[(size_t)img._width*img._height], *ptrd = ndata; if (!_normalization || (_normalization==3 && cimg::type<T>::string()==cimg::type<unsigned char>::string())) { _min = _max = 0; switch (img._spectrum) { case 1 : { for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)*(data1++); *(ptrd++) = (unsigned int)((val<<16) | (val<<8) | val); } } break; case 2 : { for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char R = (unsigned char)*(data1++), G = (unsigned char)*(data2++); *(ptrd++) = (unsigned int)((R<<16) | (G<<8)); } } break; default : { for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char R = (unsigned char)*(data1++), G = (unsigned char)*(data2++), B = (unsigned char)*(data3++); *(ptrd++) = (unsigned int)((R<<16) | (G<<8) | B); } } } } else { if (_normalization==3) { if (cimg::type<T>::is_float()) _min = (float)img.min_max(_max); else { _min = (float)cimg::type<T>::min(); _max = (float)cimg::type<T>::max(); } } else if ((_min>_max) || _normalization==1) _min = (float)img.min_max(_max); const float delta = _max - _min, mm = 255/(delta?delta:1.f); switch (img._spectrum) { case 1 : { for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)((*(data1++) - _min)*mm); *(ptrd++) = (unsigned int)((val<<16) | (val<<8) | val); } } break; case 2 : { for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char R = (unsigned char)((*(data1++) - _min)*mm), G = (unsigned char)((*(data2++) - _min)*mm); *(ptrd++) = (unsigned int)((R<<16) | (G<<8)); } } break; default : { for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char R = (unsigned char)((*(data1++) - _min)*mm), G = (unsigned char)((*(data2++) - _min)*mm), B = (unsigned char)((*(data3++) - _min)*mm); *(ptrd++) = (unsigned int)((R<<16) | (G<<8) | B); } } } } if (ndata!=_data) { _render_resize(ndata,img._width,img._height,_data,_width,_height); delete[] ndata; } ReleaseMutex(_mutex); return *this; } template<typename T> static void screenshot(const int x0, const int y0, const int x1, const int y1, CImg<T>& img) { img.assign(); HDC hScreen = GetDC(GetDesktopWindow()); if (hScreen) { const int width = GetDeviceCaps(hScreen,HORZRES), height = GetDeviceCaps(hScreen,VERTRES); int _x0 = x0, _y0 = y0, _x1 = x1, _y1 = y1; if (_x0>_x1) cimg::swap(_x0,_x1); if (_y0>_y1) cimg::swap(_y0,_y1); if (_x1>=0 && _x0<width && _y1>=0 && _y0<height) { _x0 = std::max(_x0,0); _y0 = std::max(_y0,0); _x1 = std::min(_x1,width - 1); _y1 = std::min(_y1,height - 1); const int bw = _x1 - _x0 + 1, bh = _y1 - _y0 + 1; HDC hdcMem = CreateCompatibleDC(hScreen); if (hdcMem) { HBITMAP hBitmap = CreateCompatibleBitmap(hScreen,bw,bh); if (hBitmap) { HGDIOBJ hOld = SelectObject(hdcMem,hBitmap); if (hOld && BitBlt(hdcMem,0,0,bw,bh,hScreen,_x0,_y0,SRCCOPY) && SelectObject(hdcMem,hOld)) { BITMAPINFOHEADER bmi; bmi.biSize = sizeof(BITMAPINFOHEADER); bmi.biWidth = bw; bmi.biHeight = -bh; bmi.biPlanes = 1; bmi.biBitCount = 32; bmi.biCompression = BI_RGB; bmi.biSizeImage = 0; bmi.biXPelsPerMeter = bmi.biYPelsPerMeter = 0; bmi.biClrUsed = bmi.biClrImportant = 0; unsigned char *buf = new unsigned char[4*bw*bh]; if (GetDIBits(hdcMem,hBitmap,0,bh,buf,(BITMAPINFO*)&bmi,DIB_RGB_COLORS)) { img.assign(bw,bh,1,3); const unsigned char *ptrs = buf; T *pR = img.data(0,0,0,0), *pG = img.data(0,0,0,1), *pB = img.data(0,0,0,2); cimg_forXY(img,x,y) { *(pR++) = (T)ptrs[2]; *(pG++) = (T)ptrs[1]; *(pB++) = (T)ptrs[0]; ptrs+=4; } } delete[] buf; } DeleteObject(hBitmap); } DeleteDC(hdcMem); } } ReleaseDC(GetDesktopWindow(),hScreen); } if (img.is_empty()) throw CImgDisplayException("CImgDisplay::screenshot(): Failed to take screenshot " "with coordinates (%d,%d)-(%d,%d).", x0,y0,x1,y1); } template<typename T> const CImgDisplay& snapshot(CImg<T>& img) const { if (is_empty()) { img.assign(); return *this; } const unsigned int *ptrs = _data; img.assign(_width,_height,1,3); T *data1 = img.data(0,0,0,0), *data2 = img.data(0,0,0,1), *data3 = img.data(0,0,0,2); for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned int val = *(ptrs++); *(data1++) = (T)(unsigned char)(val>>16); *(data2++) = (T)(unsigned char)((val>>8)&0xFF); *(data3++) = (T)(unsigned char)(val&0xFF); } return *this; } #endif //@} }; // struct CImgDisplay { ... /* #-------------------------------------- # # # # Definition of the CImg<T> structure # # # #-------------------------------------- */ //! Class representing an image (up to 4 dimensions wide), each pixel being of type \c T. /** This is the main class of the %CImg Library. It declares and constructs an image, allows access to its pixel values, and is able to perform various image operations. \par Image representation A %CImg image is defined as an instance of the container \c CImg<T>, which contains a regular grid of pixels, each pixel value being of type \c T. The image grid can have up to 4 dimensions: width, height, depth and number of channels. Usually, the three first dimensions are used to describe spatial coordinates <tt>(x,y,z)</tt>, while the number of channels is rather used as a vector-valued dimension (it may describe the R,G,B color channels for instance). If you need a fifth dimension, you can use image lists \c CImgList<T> rather than simple images \c CImg<T>. Thus, the \c CImg<T> class is able to represent volumetric images of vector-valued pixels, as well as images with less dimensions (1D scalar signal, 2D color images, ...). Most member functions of the class CImg<\c T> are designed to handle this maximum case of (3+1) dimensions. Concerning the pixel value type \c T: fully supported template types are the basic C++ types: <tt>unsigned char, char, short, unsigned int, int, unsigned long, long, float, double, ... </tt>. Typically, fast image display can be done using <tt>CImg<unsigned char></tt> images, while complex image processing algorithms may be rather coded using <tt>CImg<float></tt> or <tt>CImg<double></tt> images that have floating-point pixel values. The default value for the template T is \c float. Using your own template types may be possible. However, you will certainly have to define the complete set of arithmetic and logical operators for your class. \par Image structure The \c CImg<T> structure contains \e six fields: - \c _width defines the number of \a columns of the image (size along the X-axis). - \c _height defines the number of \a rows of the image (size along the Y-axis). - \c _depth defines the number of \a slices of the image (size along the Z-axis). - \c _spectrum defines the number of \a channels of the image (size along the C-axis). - \c _data defines a \a pointer to the \a pixel \a data (of type \c T). - \c _is_shared is a boolean that tells if the memory buffer \c data is shared with another image. You can access these fields publicly although it is recommended to use the dedicated functions width(), height(), depth(), spectrum() and ptr() to do so. Image dimensions are not limited to a specific range (as long as you got enough available memory). A value of \e 1 usually means that the corresponding dimension is \a flat. If one of the dimensions is \e 0, or if the data pointer is null, the image is considered as \e empty. Empty images should not contain any pixel data and thus, will not be processed by CImg member functions (a CImgInstanceException will be thrown instead). Pixel data are stored in memory, in a non interlaced mode (See \ref cimg_storage). \par Image declaration and construction Declaring an image can be done by using one of the several available constructors. Here is a list of the most used: - Construct images from arbitrary dimensions: - <tt>CImg<char> img;</tt> declares an empty image. - <tt>CImg<unsigned char> img(128,128);</tt> declares a 128x128 greyscale image with \c unsigned \c char pixel values. - <tt>CImg<double> img(3,3);</tt> declares a 3x3 matrix with \c double coefficients. - <tt>CImg<unsigned char> img(256,256,1,3);</tt> declares a 256x256x1x3 (color) image (colors are stored as an image with three channels). - <tt>CImg<double> img(128,128,128);</tt> declares a 128x128x128 volumetric and greyscale image (with \c double pixel values). - <tt>CImg<> img(128,128,128,3);</tt> declares a 128x128x128 volumetric color image (with \c float pixels, which is the default value of the template parameter \c T). - \b Note: images pixels are <b>not automatically initialized to 0</b>. You may use the function \c fill() to do it, or use the specific constructor taking 5 parameters like this: <tt>CImg<> img(128,128,128,3,0);</tt> declares a 128x128x128 volumetric color image with all pixel values to 0. - Construct images from filenames: - <tt>CImg<unsigned char> img("image.jpg");</tt> reads a JPEG color image from the file "image.jpg". - <tt>CImg<float> img("analyze.hdr");</tt> reads a volumetric image (ANALYZE7.5 format) from the file "analyze.hdr". - \b Note: You need to install <a href="http://www.imagemagick.org">ImageMagick</a> to be able to read common compressed image formats (JPG,PNG, ...) (See \ref cimg_files_io). - Construct images from C-style arrays: - <tt>CImg<int> img(data_buffer,256,256);</tt> constructs a 256x256 greyscale image from a \c int* buffer \c data_buffer (of size 256x256=65536). - <tt>CImg<unsigned char> img(data_buffer,256,256,1,3);</tt> constructs a 256x256 color image from a \c unsigned \c char* buffer \c data_buffer (where R,G,B channels follow each others). The complete list of constructors can be found <a href="#constructors">here</a>. \par Most useful functions The \c CImg<T> class contains a lot of functions that operates on images. Some of the most useful are: - operator()(): Read or write pixel values. - display(): displays the image in a new window. **/ template<typename T> struct CImg { unsigned int _width, _height, _depth, _spectrum; bool _is_shared; T *_data; //! Simple iterator type, to loop through each pixel value of an image instance. /** \note - The \c CImg<T>::iterator type is defined to be a <tt>T*</tt>. - You will seldom have to use iterators in %CImg, most classical operations being achieved (often in a faster way) using methods of \c CImg<T>. \par Example \code CImg<float> img("reference.jpg"); // Load image from file // Set all pixels to '0', with a CImg iterator. for (CImg<float>::iterator it = img.begin(), it<img.end(); ++it) *it = 0; img.fill(0); // Do the same with a built-in method \endcode **/ typedef T* iterator; //! Simple const iterator type, to loop through each pixel value of a \c const image instance. /** \note - The \c CImg<T>::const_iterator type is defined to be a \c const \c T*. - You will seldom have to use iterators in %CImg, most classical operations being achieved (often in a faster way) using methods of \c CImg<T>. \par Example \code const CImg<float> img("reference.jpg"); // Load image from file float sum = 0; // Compute sum of all pixel values, with a CImg iterator. for (CImg<float>::iterator it = img.begin(), it<img.end(); ++it) sum+=*it; const float sum2 = img.sum(); // Do the same with a built-in method \endcode **/ typedef const T* const_iterator; //! Pixel value type. /** Refer to the type of the pixel values of an image instance. \note - The \c CImg<T>::value_type type of a \c CImg<T> is defined to be a \c T. - \c CImg<T>::value_type is actually not used in %CImg methods. It has been mainly defined for compatibility with STL naming conventions. **/ typedef T value_type; // Define common types related to template type T. typedef typename cimg::superset<T,bool>::type Tbool; typedef typename cimg::superset<T,unsigned char>::type Tuchar; typedef typename cimg::superset<T,char>::type Tchar; typedef typename cimg::superset<T,unsigned short>::type Tushort; typedef typename cimg::superset<T,short>::type Tshort; typedef typename cimg::superset<T,unsigned int>::type Tuint; typedef typename cimg::superset<T,int>::type Tint; typedef typename cimg::superset<T,cimg_ulong>::type Tulong; typedef typename cimg::superset<T,cimg_long>::type Tlong; typedef typename cimg::superset<T,float>::type Tfloat; typedef typename cimg::superset<T,double>::type Tdouble; typedef typename cimg::last<T,bool>::type boolT; typedef typename cimg::last<T,unsigned char>::type ucharT; typedef typename cimg::last<T,char>::type charT; typedef typename cimg::last<T,unsigned short>::type ushortT; typedef typename cimg::last<T,short>::type shortT; typedef typename cimg::last<T,unsigned int>::type uintT; typedef typename cimg::last<T,int>::type intT; typedef typename cimg::last<T,cimg_ulong>::type ulongT; typedef typename cimg::last<T,cimg_long>::type longT; typedef typename cimg::last<T,cimg_uint64>::type uint64T; typedef typename cimg::last<T,cimg_int64>::type int64T; typedef typename cimg::last<T,float>::type floatT; typedef typename cimg::last<T,double>::type doubleT; //@} //--------------------------- // //! \name Plugins //@{ //--------------------------- #ifdef cimg_plugin #include cimg_plugin #endif #ifdef cimg_plugin1 #include cimg_plugin1 #endif #ifdef cimg_plugin2 #include cimg_plugin2 #endif #ifdef cimg_plugin3 #include cimg_plugin3 #endif #ifdef cimg_plugin4 #include cimg_plugin4 #endif #ifdef cimg_plugin5 #include cimg_plugin5 #endif #ifdef cimg_plugin6 #include cimg_plugin6 #endif #ifdef cimg_plugin7 #include cimg_plugin7 #endif #ifdef cimg_plugin8 #include cimg_plugin8 #endif //@} //--------------------------------------------------------- // //! \name Constructors / Destructor / Instance Management //@{ //--------------------------------------------------------- //! Destroy image. /** \note - The pixel buffer data() is deallocated if necessary, e.g. for non-empty and non-shared image instances. - Destroying an empty or shared image does nothing actually. \warning - When destroying a non-shared image, make sure that you will \e not operate on a remaining shared image that shares its buffer with the destroyed instance, in order to avoid further invalid memory access (to a deallocated buffer). **/ ~CImg() { if (!_is_shared) delete[] _data; } //! Construct empty image. /** \note - An empty image has no pixel data and all of its dimensions width(), height(), depth(), spectrum() are set to \c 0, as well as its pixel buffer pointer data(). - An empty image may be re-assigned afterwards, e.g. with the family of assign(unsigned int,unsigned int,unsigned int,unsigned int) methods, or by operator=(const CImg<t>&). In all cases, the type of pixels stays \c T. - An empty image is never shared. \par Example \code CImg<float> img1, img2; // Construct two empty images img1.assign(256,256,1,3); // Re-assign 'img1' to be a 256x256x1x3 (color) image img2 = img1.get_rand(0,255); // Re-assign 'img2' to be a random-valued version of 'img1' img2.assign(); // Re-assign 'img2' to be an empty image again \endcode **/ CImg():_width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) {} //! Construct image with specified size. /** \param size_x Image width(). \param size_y Image height(). \param size_z Image depth(). \param size_c Image spectrum() (number of channels). \note - It is able to create only \e non-shared images, and allocates thus a pixel buffer data() for each constructed image instance. - Setting one dimension \c size_x,\c size_y,\c size_z or \c size_c to \c 0 leads to the construction of an \e empty image. - A \c CImgInstanceException is thrown when the pixel buffer cannot be allocated (e.g. when requested size is too big for available memory). \warning - The allocated pixel buffer is \e not filled with a default value, and is likely to contain garbage values. In order to initialize pixel values during construction (e.g. with \c 0), use constructor CImg(unsigned int,unsigned int,unsigned int,unsigned int,T) instead. \par Example \code CImg<float> img1(256,256,1,3); // Construct a 256x256x1x3 (color) image, filled with garbage values CImg<float> img2(256,256,1,3,0); // Construct a 256x256x1x3 (color) image, filled with value '0' \endcode **/ explicit CImg(const unsigned int size_x, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1): _is_shared(false) { size_t siz = (size_t)size_x*size_y*size_z*size_c; if (siz) { _width = size_x; _height = size_y; _depth = size_z; _spectrum = size_c; try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*size_x*size_y*size_z*size_c), size_x,size_y,size_z,size_c); } } else { _width = _height = _depth = _spectrum = 0; _data = 0; } } //! Construct image with specified size and initialize pixel values. /** \param size_x Image width(). \param size_y Image height(). \param size_z Image depth(). \param size_c Image spectrum() (number of channels). \param value Initialization value. \note - Similar to CImg(unsigned int,unsigned int,unsigned int,unsigned int), but it also fills the pixel buffer with the specified \c value. \warning - It cannot be used to construct a vector-valued image and initialize it with \e vector-valued pixels (e.g. RGB vector, for color images). For this task, you may use fillC() after construction. **/ CImg(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const T& value): _is_shared(false) { const size_t siz = (size_t)size_x*size_y*size_z*size_c; if (siz) { _width = size_x; _height = size_y; _depth = size_z; _spectrum = size_c; try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*size_x*size_y*size_z*size_c), size_x,size_y,size_z,size_c); } fill(value); } else { _width = _height = _depth = _spectrum = 0; _data = 0; } } //! Construct image with specified size and initialize pixel values from a sequence of integers. /** Construct a new image instance of size \c size_x x \c size_y x \c size_z x \c size_c, with pixels of type \c T, and initialize pixel values from the specified sequence of integers \c value0,\c value1,\c ... \param size_x Image width(). \param size_y Image height(). \param size_z Image depth(). \param size_c Image spectrum() (number of channels). \param value0 First value of the initialization sequence (must be an \e integer). \param value1 Second value of the initialization sequence (must be an \e integer). \param ... \note - Similar to CImg(unsigned int,unsigned int,unsigned int,unsigned int), but it also fills the pixel buffer with a sequence of specified integer values. \warning - You must specify \e exactly \c size_x*\c size_y*\c size_z*\c size_c integers in the initialization sequence. Otherwise, the constructor may crash or fill your image pixels with garbage. \par Example \code const CImg<float> img(2,2,1,3, // Construct a 2x2 color (RGB) image 0,255,0,255, // Set the 4 values for the red component 0,0,255,255, // Set the 4 values for the green component 64,64,64,64); // Set the 4 values for the blue component img.resize(150,150).display(); \endcode \image html ref_constructor1.jpg **/ CImg(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const int value0, const int value1, ...): _width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { #define _CImg_stdarg(img,a0,a1,N,t) { \ size_t _siz = (size_t)N; \ if (_siz--) { \ va_list ap; \ va_start(ap,a1); \ T *ptrd = (img)._data; \ *(ptrd++) = (T)a0; \ if (_siz--) { \ *(ptrd++) = (T)a1; \ for ( ; _siz; --_siz) *(ptrd++) = (T)va_arg(ap,t); \ } \ va_end(ap); \ } \ } assign(size_x,size_y,size_z,size_c); _CImg_stdarg(*this,value0,value1,(size_t)size_x*size_y*size_z*size_c,int); } #if cimg_use_cpp11==1 //! Construct image with specified size and initialize pixel values from an initializer list of integers. /** Construct a new image instance of size \c size_x x \c size_y x \c size_z x \c size_c, with pixels of type \c T, and initialize pixel values from the specified initializer list of integers { \c value0,\c value1,\c ... } \param size_x Image width(). \param size_y Image height(). \param size_z Image depth(). \param size_c Image spectrum() (number of channels). \param { value0, value1, ... } Initialization list \param repeat_values Tells if the value filling process is repeated over the image. \note - Similar to CImg(unsigned int,unsigned int,unsigned int,unsigned int), but it also fills the pixel buffer with a sequence of specified integer values. \par Example \code const CImg<float> img(2,2,1,3, // Construct a 2x2 color (RGB) image { 0,255,0,255, // Set the 4 values for the red component 0,0,255,255, // Set the 4 values for the green component 64,64,64,64 }); // Set the 4 values for the blue component img.resize(150,150).display(); \endcode \image html ref_constructor1.jpg **/ template<typename t> CImg(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const std::initializer_list<t> values, const bool repeat_values=true): _width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { #define _cimg_constructor_cpp11(repeat_values) \ auto it = values.begin(); \ size_t siz = size(); \ if (repeat_values) for (T *ptrd = _data; siz--; ) { \ *(ptrd++) = (T)(*(it++)); if (it==values.end()) it = values.begin(); } \ else { siz = std::min(siz,values.size()); for (T *ptrd = _data; siz--; ) *(ptrd++) = (T)(*(it++)); } assign(size_x,size_y,size_z,size_c); _cimg_constructor_cpp11(repeat_values); } template<typename t> CImg(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, std::initializer_list<t> values, const bool repeat_values=true): _width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { assign(size_x,size_y,size_z); _cimg_constructor_cpp11(repeat_values); } template<typename t> CImg(const unsigned int size_x, const unsigned int size_y, std::initializer_list<t> values, const bool repeat_values=true): _width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { assign(size_x,size_y); _cimg_constructor_cpp11(repeat_values); } template<typename t> CImg(const unsigned int size_x, std::initializer_list<t> values, const bool repeat_values=true):_width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { assign(size_x); _cimg_constructor_cpp11(repeat_values); } //! Construct single channel 1D image with pixel values and width obtained from an initializer list of integers. /** Construct a new image instance of size \c width x \c 1 x \c 1 x \c 1, with pixels of type \c T, and initialize pixel values from the specified initializer list of integers { \c value0,\c value1,\c ... }. Image width is given by the size of the initializer list. \param { value0, value1, ... } Initialization list \note - Similar to CImg(unsigned int,unsigned int,unsigned int,unsigned int) with height=1, depth=1, and spectrum=1, but it also fills the pixel buffer with a sequence of specified integer values. \par Example \code const CImg<float> img = {10,20,30,20,10 }; // Construct a 5x1 image with one channel, and set its pixel values img.resize(150,150).display(); \endcode \image html ref_constructor1.jpg **/ template<typename t> CImg(const std::initializer_list<t> values): _width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { assign(values.size(),1,1,1); auto it = values.begin(); unsigned int siz = _width; for (T *ptrd = _data; siz--; ) *(ptrd++) = (T)(*(it++)); } template<typename t> CImg<T> & operator=(std::initializer_list<t> values) { _cimg_constructor_cpp11(siz>values.size()); return *this; } #endif //! Construct image with specified size and initialize pixel values from a sequence of doubles. /** Construct a new image instance of size \c size_x x \c size_y x \c size_z x \c size_c, with pixels of type \c T, and initialize pixel values from the specified sequence of doubles \c value0,\c value1,\c ... \param size_x Image width(). \param size_y Image height(). \param size_z Image depth(). \param size_c Image spectrum() (number of channels). \param value0 First value of the initialization sequence (must be a \e double). \param value1 Second value of the initialization sequence (must be a \e double). \param ... \note - Similar to CImg(unsigned int,unsigned int,unsigned int,unsigned int,int,int,...), but takes a sequence of double values instead of integers. \warning - You must specify \e exactly \c dx*\c dy*\c dz*\c dc doubles in the initialization sequence. Otherwise, the constructor may crash or fill your image with garbage. For instance, the code below will probably crash on most platforms: \code const CImg<float> img(2,2,1,1, 0.5,0.5,255,255); // FAIL: The two last arguments are 'int', not 'double'! \endcode **/ CImg(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const double value0, const double value1, ...): _width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { assign(size_x,size_y,size_z,size_c); _CImg_stdarg(*this,value0,value1,(size_t)size_x*size_y*size_z*size_c,double); } //! Construct image with specified size and initialize pixel values from a value string. /** Construct a new image instance of size \c size_x x \c size_y x \c size_z x \c size_c, with pixels of type \c T, and initializes pixel values from the specified string \c values. \param size_x Image width(). \param size_y Image height(). \param size_z Image depth(). \param size_c Image spectrum() (number of channels). \param values Value string describing the way pixel values are set. \param repeat_values Tells if the value filling process is repeated over the image. \note - Similar to CImg(unsigned int,unsigned int,unsigned int,unsigned int), but it also fills the pixel buffer with values described in the value string \c values. - Value string \c values may describe two different filling processes: - Either \c values is a sequences of values assigned to the image pixels, as in <tt>"1,2,3,7,8,2"</tt>. In this case, set \c repeat_values to \c true to periodically fill the image with the value sequence. - Either, \c values is a formula, as in <tt>"cos(x/10)*sin(y/20)"</tt>. In this case, parameter \c repeat_values is pointless. - For both cases, specifying \c repeat_values is mandatory. It disambiguates the possible overloading of constructor CImg(unsigned int,unsigned int,unsigned int,unsigned int,T) with \c T being a <tt>const char*</tt>. - A \c CImgArgumentException is thrown when an invalid value string \c values is specified. \par Example \code const CImg<float> img1(129,129,1,3,"0,64,128,192,255",true), // Construct image from a value sequence img2(129,129,1,3,"if(c==0,255*abs(cos(x/10)),1.8*y)",false); // Construct image from a formula (img1,img2).display(); \endcode \image html ref_constructor2.jpg **/ CImg(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const char *const values, const bool repeat_values):_is_shared(false) { const size_t siz = (size_t)size_x*size_y*size_z*size_c; if (siz) { _width = size_x; _height = size_y; _depth = size_z; _spectrum = size_c; try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*size_x*size_y*size_z*size_c), size_x,size_y,size_z,size_c); } fill(values,repeat_values); } else { _width = _height = _depth = _spectrum = 0; _data = 0; } } //! Construct image with specified size and initialize pixel values from a memory buffer. /** Construct a new image instance of size \c size_x x \c size_y x \c size_z x \c size_c, with pixels of type \c T, and initializes pixel values from the specified \c t* memory buffer. \param values Pointer to the input memory buffer. \param size_x Image width(). \param size_y Image height(). \param size_z Image depth(). \param size_c Image spectrum() (number of channels). \param is_shared Tells if input memory buffer must be shared by the current instance. \note - If \c is_shared is \c false, the image instance allocates its own pixel buffer, and values from the specified input buffer are copied to the instance buffer. If buffer types \c T and \c t are different, a regular static cast is performed during buffer copy. - Otherwise, the image instance does \e not allocate a new buffer, and uses the input memory buffer as its own pixel buffer. This case requires that types \c T and \c t are the same. Later, destroying such a shared image will not deallocate the pixel buffer, this task being obviously charged to the initial buffer allocator. - A \c CImgInstanceException is thrown when the pixel buffer cannot be allocated (e.g. when requested size is too big for available memory). \warning - You must take care when operating on a shared image, since it may have an invalid pixel buffer pointer data() (e.g. already deallocated). \par Example \code unsigned char tab[256*256] = { 0 }; CImg<unsigned char> img1(tab,256,256,1,1,false), // Construct new non-shared image from buffer 'tab' img2(tab,256,256,1,1,true); // Construct new shared-image from buffer 'tab' tab[1024] = 255; // Here, 'img2' is indirectly modified, but not 'img1' \endcode **/ template<typename t> CImg(const t *const values, const unsigned int size_x, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1, const bool is_shared=false):_is_shared(false) { if (is_shared) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgArgumentException(_cimg_instance "CImg(): Invalid construction request of a (%u,%u,%u,%u) shared instance " "from a (%s*) buffer (pixel types are different).", cimg_instance, size_x,size_y,size_z,size_c,CImg<t>::pixel_type()); } const size_t siz = (size_t)size_x*size_y*size_z*size_c; if (values && siz) { _width = size_x; _height = size_y; _depth = size_z; _spectrum = size_c; try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*size_x*size_y*size_z*size_c), size_x,size_y,size_z,size_c); } const t *ptrs = values; cimg_for(*this,ptrd,T) *ptrd = (T)*(ptrs++); } else { _width = _height = _depth = _spectrum = 0; _data = 0; } } //! Construct image with specified size and initialize pixel values from a memory buffer \specialization. CImg(const T *const values, const unsigned int size_x, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1, const bool is_shared=false) { const size_t siz = (size_t)size_x*size_y*size_z*size_c; if (values && siz) { _width = size_x; _height = size_y; _depth = size_z; _spectrum = size_c; _is_shared = is_shared; if (_is_shared) _data = const_cast<T*>(values); else { try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*size_x*size_y*size_z*size_c), size_x,size_y,size_z,size_c); } std::memcpy(_data,values,siz*sizeof(T)); } } else { _width = _height = _depth = _spectrum = 0; _is_shared = false; _data = 0; } } //! Construct image from reading an image file. /** Construct a new image instance with pixels of type \c T, and initialize pixel values with the data read from an image file. \param filename Filename, as a C-string. \note - Similar to CImg(unsigned int,unsigned int,unsigned int,unsigned int), but it reads the image dimensions and pixel values from the specified image file. - The recognition of the image file format by %CImg higly depends on the tools installed on your system and on the external libraries you used to link your code against. - Considered pixel type \c T should better fit the file format specification, or data loss may occur during file load (e.g. constructing a \c CImg<unsigned char> from a float-valued image file). - A \c CImgIOException is thrown when the specified \c filename cannot be read, or if the file format is not recognized. \par Example \code const CImg<float> img("reference.jpg"); img.display(); \endcode \image html ref_image.jpg **/ explicit CImg(const char *const filename):_width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { assign(filename); } //! Construct image copy. /** Construct a new image instance with pixels of type \c T, as a copy of an existing \c CImg<t> instance. \param img Input image to copy. \note - Constructed copy has the same size width() x height() x depth() x spectrum() and pixel values as the input image \c img. - If input image \c img is \e shared and if types \c T and \c t are the same, the constructed copy is also \e shared, and shares its pixel buffer with \c img. Modifying a pixel value in the constructed copy will thus also modifies it in the input image \c img. This behavior is needful to allow functions to return shared images. - Otherwise, the constructed copy allocates its own pixel buffer, and copies pixel values from the input image \c img into its buffer. The copied pixel values may be eventually statically casted if types \c T and \c t are different. - Constructing a copy from an image \c img when types \c t and \c T are the same is significantly faster than with different types. - A \c CImgInstanceException is thrown when the pixel buffer cannot be allocated (e.g. not enough available memory). **/ template<typename t> CImg(const CImg<t>& img):_is_shared(false) { const size_t siz = (size_t)img.size(); if (img._data && siz) { _width = img._width; _height = img._height; _depth = img._depth; _spectrum = img._spectrum; try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*img._width*img._height*img._depth*img._spectrum), img._width,img._height,img._depth,img._spectrum); } const t *ptrs = img._data; cimg_for(*this,ptrd,T) *ptrd = (T)*(ptrs++); } else { _width = _height = _depth = _spectrum = 0; _data = 0; } } //! Construct image copy \specialization. CImg(const CImg<T>& img) { const size_t siz = (size_t)img.size(); if (img._data && siz) { _width = img._width; _height = img._height; _depth = img._depth; _spectrum = img._spectrum; _is_shared = img._is_shared; if (_is_shared) _data = const_cast<T*>(img._data); else { try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*img._width*img._height*img._depth*img._spectrum), img._width,img._height,img._depth,img._spectrum); } std::memcpy(_data,img._data,siz*sizeof(T)); } } else { _width = _height = _depth = _spectrum = 0; _is_shared = false; _data = 0; } } //! Advanced copy constructor. /** Construct a new image instance with pixels of type \c T, as a copy of an existing \c CImg<t> instance, while forcing the shared state of the constructed copy. \param img Input image to copy. \param is_shared Tells about the shared state of the constructed copy. \note - Similar to CImg(const CImg<t>&), except that it allows to decide the shared state of the constructed image, which does not depend anymore on the shared state of the input image \c img: - If \c is_shared is \c true, the constructed copy will share its pixel buffer with the input image \c img. For that case, the pixel types \c T and \c t \e must be the same. - If \c is_shared is \c false, the constructed copy will allocate its own pixel buffer, whether the input image \c img is shared or not. - A \c CImgArgumentException is thrown when a shared copy is requested with different pixel types \c T and \c t. **/ template<typename t> CImg(const CImg<t>& img, const bool is_shared):_is_shared(false) { if (is_shared) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgArgumentException(_cimg_instance "CImg(): Invalid construction request of a shared instance from a " "CImg<%s> image (%u,%u,%u,%u,%p) (pixel types are different).", cimg_instance, CImg<t>::pixel_type(),img._width,img._height,img._depth,img._spectrum,img._data); } const size_t siz = (size_t)img.size(); if (img._data && siz) { _width = img._width; _height = img._height; _depth = img._depth; _spectrum = img._spectrum; try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*img._width*img._height*img._depth*img._spectrum), img._width,img._height,img._depth,img._spectrum); } const t *ptrs = img._data; cimg_for(*this,ptrd,T) *ptrd = (T)*(ptrs++); } else { _width = _height = _depth = _spectrum = 0; _data = 0; } } //! Advanced copy constructor \specialization. CImg(const CImg<T>& img, const bool is_shared) { const size_t siz = (size_t)img.size(); if (img._data && siz) { _width = img._width; _height = img._height; _depth = img._depth; _spectrum = img._spectrum; _is_shared = is_shared; if (_is_shared) _data = const_cast<T*>(img._data); else { try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*img._width*img._height*img._depth*img._spectrum), img._width,img._height,img._depth,img._spectrum); } std::memcpy(_data,img._data,siz*sizeof(T)); } } else { _width = _height = _depth = _spectrum = 0; _is_shared = false; _data = 0; } } //! Construct image with dimensions borrowed from another image. /** Construct a new image instance with pixels of type \c T, and size get from some dimensions of an existing \c CImg<t> instance. \param img Input image from which dimensions are borrowed. \param dimensions C-string describing the image size along the X,Y,Z and C-dimensions. \note - Similar to CImg(unsigned int,unsigned int,unsigned int,unsigned int), but it takes the image dimensions (\e not its pixel values) from an existing \c CImg<t> instance. - The allocated pixel buffer is \e not filled with a default value, and is likely to contain garbage values. In order to initialize pixel values (e.g. with \c 0), use constructor CImg(const CImg<t>&,const char*,T) instead. \par Example \code const CImg<float> img1(256,128,1,3), // 'img1' is a 256x128x1x3 image img2(img1,"xyzc"), // 'img2' is a 256x128x1x3 image img3(img1,"y,x,z,c"), // 'img3' is a 128x256x1x3 image img4(img1,"c,x,y,3",0), // 'img4' is a 3x128x256x3 image (with pixels initialized to '0') \endcode **/ template<typename t> CImg(const CImg<t>& img, const char *const dimensions): _width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { assign(img,dimensions); } //! Construct image with dimensions borrowed from another image and initialize pixel values. /** Construct a new image instance with pixels of type \c T, and size get from the dimensions of an existing \c CImg<t> instance, and set all pixel values to specified \c value. \param img Input image from which dimensions are borrowed. \param dimensions String describing the image size along the X,Y,Z and V-dimensions. \param value Value used for initialization. \note - Similar to CImg(const CImg<t>&,const char*), but it also fills the pixel buffer with the specified \c value. **/ template<typename t> CImg(const CImg<t>& img, const char *const dimensions, const T& value): _width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { assign(img,dimensions).fill(value); } //! Construct image from a display window. /** Construct a new image instance with pixels of type \c T, as a snapshot of an existing \c CImgDisplay instance. \param disp Input display window. \note - The width() and height() of the constructed image instance are the same as the specified \c CImgDisplay. - The depth() and spectrum() of the constructed image instance are respectively set to \c 1 and \c 3 (i.e. a 2D color image). - The image pixels are read as 8-bits RGB values. **/ explicit CImg(const CImgDisplay &disp):_width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { disp.snapshot(*this); } // Constructor and assignment operator for rvalue references (c++11). // This avoids an additional image copy for methods returning new images. Can save RAM for big images ! #if cimg_use_cpp11==1 CImg(CImg<T>&& img):_width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { swap(img); } CImg<T>& operator=(CImg<T>&& img) { if (_is_shared) return assign(img); return img.swap(*this); } #endif //! Construct empty image \inplace. /** In-place version of the default constructor CImg(). It simply resets the instance to an empty image. **/ CImg<T>& assign() { if (!_is_shared) delete[] _data; _width = _height = _depth = _spectrum = 0; _is_shared = false; _data = 0; return *this; } //! Construct image with specified size \inplace. /** In-place version of the constructor CImg(unsigned int,unsigned int,unsigned int,unsigned int). **/ CImg<T>& assign(const unsigned int size_x, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1) { const size_t siz = (size_t)size_x*size_y*size_z*size_c; if (!siz) return assign(); const size_t curr_siz = (size_t)size(); if (siz!=curr_siz) { if (_is_shared) throw CImgArgumentException(_cimg_instance "assign(): Invalid assignement request of shared instance from specified " "image (%u,%u,%u,%u).", cimg_instance, size_x,size_y,size_z,size_c); else { delete[] _data; try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "assign(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*size_x*size_y*size_z*size_c), size_x,size_y,size_z,size_c); } } } _width = size_x; _height = size_y; _depth = size_z; _spectrum = size_c; return *this; } //! Construct image with specified size and initialize pixel values \inplace. /** In-place version of the constructor CImg(unsigned int,unsigned int,unsigned int,unsigned int,T). **/ CImg<T>& assign(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const T& value) { return assign(size_x,size_y,size_z,size_c).fill(value); } //! Construct image with specified size and initialize pixel values from a sequence of integers \inplace. /** In-place version of the constructor CImg(unsigned int,unsigned int,unsigned int,unsigned int,int,int,...). **/ CImg<T>& assign(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const int value0, const int value1, ...) { assign(size_x,size_y,size_z,size_c); _CImg_stdarg(*this,value0,value1,(size_t)size_x*size_y*size_z*size_c,int); return *this; } //! Construct image with specified size and initialize pixel values from a sequence of doubles \inplace. /** In-place version of the constructor CImg(unsigned int,unsigned int,unsigned int,unsigned int,double,double,...). **/ CImg<T>& assign(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const double value0, const double value1, ...) { assign(size_x,size_y,size_z,size_c); _CImg_stdarg(*this,value0,value1,(size_t)size_x*size_y*size_z*size_c,double); return *this; } //! Construct image with specified size and initialize pixel values from a value string \inplace. /** In-place version of the constructor CImg(unsigned int,unsigned int,unsigned int,unsigned int,const char*,bool). **/ CImg<T>& assign(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const char *const values, const bool repeat_values) { return assign(size_x,size_y,size_z,size_c).fill(values,repeat_values); } //! Construct image with specified size and initialize pixel values from a memory buffer \inplace. /** In-place version of the constructor CImg(const t*,unsigned int,unsigned int,unsigned int,unsigned int). **/ template<typename t> CImg<T>& assign(const t *const values, const unsigned int size_x, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1) { const size_t siz = (size_t)size_x*size_y*size_z*size_c; if (!values || !siz) return assign(); assign(size_x,size_y,size_z,size_c); const t *ptrs = values; cimg_for(*this,ptrd,T) *ptrd = (T)*(ptrs++); return *this; } //! Construct image with specified size and initialize pixel values from a memory buffer \specialization. CImg<T>& assign(const T *const values, const unsigned int size_x, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1) { const size_t siz = (size_t)size_x*size_y*size_z*size_c; if (!values || !siz) return assign(); const size_t curr_siz = (size_t)size(); if (values==_data && siz==curr_siz) return assign(size_x,size_y,size_z,size_c); if (_is_shared || values + siz<_data || values>=_data + size()) { assign(size_x,size_y,size_z,size_c); if (_is_shared) std::memmove((void*)_data,(void*)values,siz*sizeof(T)); else std::memcpy((void*)_data,(void*)values,siz*sizeof(T)); } else { T *new_data = 0; try { new_data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "assign(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*size_x*size_y*size_z*size_c), size_x,size_y,size_z,size_c); } std::memcpy((void*)new_data,(void*)values,siz*sizeof(T)); delete[] _data; _data = new_data; _width = size_x; _height = size_y; _depth = size_z; _spectrum = size_c; } return *this; } //! Construct image with specified size and initialize pixel values from a memory buffer \overloading. template<typename t> CImg<T>& assign(const t *const values, const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const bool is_shared) { if (is_shared) throw CImgArgumentException(_cimg_instance "assign(): Invalid assignment request of shared instance from (%s*) buffer" "(pixel types are different).", cimg_instance, CImg<t>::pixel_type()); return assign(values,size_x,size_y,size_z,size_c); } //! Construct image with specified size and initialize pixel values from a memory buffer \overloading. CImg<T>& assign(const T *const values, const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const bool is_shared) { const size_t siz = (size_t)size_x*size_y*size_z*size_c; if (!values || !siz) return assign(); if (!is_shared) { if (_is_shared) assign(); assign(values,size_x,size_y,size_z,size_c); } else { if (!_is_shared) { if (values + siz<_data || values>=_data + size()) assign(); else cimg::warn(_cimg_instance "assign(): Shared image instance has overlapping memory.", cimg_instance); } _width = size_x; _height = size_y; _depth = size_z; _spectrum = size_c; _is_shared = true; _data = const_cast<T*>(values); } return *this; } //! Construct image from reading an image file \inplace. /** In-place version of the constructor CImg(const char*). **/ CImg<T>& assign(const char *const filename) { return load(filename); } //! Construct image copy \inplace. /** In-place version of the constructor CImg(const CImg<t>&). **/ template<typename t> CImg<T>& assign(const CImg<t>& img) { return assign(img._data,img._width,img._height,img._depth,img._spectrum); } //! In-place version of the advanced copy constructor. /** In-place version of the constructor CImg(const CImg<t>&,bool). **/ template<typename t> CImg<T>& assign(const CImg<t>& img, const bool is_shared) { return assign(img._data,img._width,img._height,img._depth,img._spectrum,is_shared); } //! Construct image with dimensions borrowed from another image \inplace. /** In-place version of the constructor CImg(const CImg<t>&,const char*). **/ template<typename t> CImg<T>& assign(const CImg<t>& img, const char *const dimensions) { if (!dimensions || !*dimensions) return assign(img._width,img._height,img._depth,img._spectrum); unsigned int siz[4] = { 0,1,1,1 }, k = 0; CImg<charT> item(256); for (const char *s = dimensions; *s && k<4; ++k) { if (cimg_sscanf(s,"%255[^0-9%xyzvwhdcXYZVWHDC]",item._data)>0) s+=std::strlen(item); if (*s) { unsigned int val = 0; char sep = 0; if (cimg_sscanf(s,"%u%c",&val,&sep)>0) { if (sep=='%') siz[k] = val*(k==0?_width:k==1?_height:k==2?_depth:_spectrum)/100; else siz[k] = val; while (*s>='0' && *s<='9') ++s; if (sep=='%') ++s; } else switch (cimg::lowercase(*s)) { case 'x' : case 'w' : siz[k] = img._width; ++s; break; case 'y' : case 'h' : siz[k] = img._height; ++s; break; case 'z' : case 'd' : siz[k] = img._depth; ++s; break; case 'c' : case 's' : siz[k] = img._spectrum; ++s; break; default : throw CImgArgumentException(_cimg_instance "assign(): Invalid character '%c' detected in specified dimension string '%s'.", cimg_instance, *s,dimensions); } } } return assign(siz[0],siz[1],siz[2],siz[3]); } //! Construct image with dimensions borrowed from another image and initialize pixel values \inplace. /** In-place version of the constructor CImg(const CImg<t>&,const char*,T). **/ template<typename t> CImg<T>& assign(const CImg<t>& img, const char *const dimensions, const T& value) { return assign(img,dimensions).fill(value); } //! Construct image from a display window \inplace. /** In-place version of the constructor CImg(const CImgDisplay&). **/ CImg<T>& assign(const CImgDisplay &disp) { disp.snapshot(*this); return *this; } //! Construct empty image \inplace. /** Equivalent to assign(). \note - It has been defined for compatibility with STL naming conventions. **/ CImg<T>& clear() { return assign(); } //! Transfer content of an image instance into another one. /** Transfer the dimensions and the pixel buffer content of an image instance into another one, and replace instance by an empty image. It avoids the copy of the pixel buffer when possible. \param img Destination image. \note - Pixel types \c T and \c t of source and destination images can be different, though the process is designed to be instantaneous when \c T and \c t are the same. \par Example \code CImg<float> src(256,256,1,3,0), // Construct a 256x256x1x3 (color) image filled with value '0' dest(16,16); // Construct a 16x16x1x1 (scalar) image src.move_to(dest); // Now, 'src' is empty and 'dest' is the 256x256x1x3 image \endcode **/ template<typename t> CImg<t>& move_to(CImg<t>& img) { img.assign(*this); assign(); return img; } //! Transfer content of an image instance into another one \specialization. CImg<T>& move_to(CImg<T>& img) { if (_is_shared || img._is_shared) img.assign(*this); else swap(img); assign(); return img; } //! Transfer content of an image instance into a new image in an image list. /** Transfer the dimensions and the pixel buffer content of an image instance into a newly inserted image at position \c pos in specified \c CImgList<t> instance. \param list Destination list. \param pos Position of the newly inserted image in the list. \note - When optional parameter \c pos is ommited, the image instance is transfered as a new image at the end of the specified \c list. - It is convenient to sequentially insert new images into image lists, with no additional copies of memory buffer. \par Example \code CImgList<float> list; // Construct an empty image list CImg<float> img("reference.jpg"); // Read image from filename img.move_to(list); // Transfer image content as a new item in the list (no buffer copy) \endcode **/ template<typename t> CImgList<t>& move_to(CImgList<t>& list, const unsigned int pos=~0U) { const unsigned int npos = pos>list._width?list._width:pos; move_to(list.insert(1,npos)[npos]); return list; } //! Swap fields of two image instances. /** \param img Image to swap fields with. \note - It can be used to interchange the content of two images in a very fast way. Can be convenient when dealing with algorithms requiring two swapping buffers. \par Example \code CImg<float> img1("lena.jpg"), img2("milla.jpg"); img1.swap(img2); // Now, 'img1' is 'milla' and 'img2' is 'lena' \endcode **/ CImg<T>& swap(CImg<T>& img) { cimg::swap(_width,img._width,_height,img._height,_depth,img._depth,_spectrum,img._spectrum); cimg::swap(_data,img._data); cimg::swap(_is_shared,img._is_shared); return img; } //! Return a reference to an empty image. /** \note This function is useful mainly to declare optional parameters having type \c CImg<T> in functions prototypes, e.g. \code void f(const int x=0, const int y=0, const CImg<float>& img=CImg<float>::empty()); \endcode **/ static CImg<T>& empty() { static CImg<T> _empty; return _empty.assign(); } //! Return a reference to an empty image \const. static const CImg<T>& const_empty() { static const CImg<T> _empty; return _empty; } //@} //------------------------------------------ // //! \name Overloaded Operators //@{ //------------------------------------------ //! Access to a pixel value. /** Return a reference to a located pixel value of the image instance, being possibly \e const, whether the image instance is \e const or not. This is the standard method to get/set pixel values in \c CImg<T> images. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note - Range of pixel coordinates start from <tt>(0,0,0,0)</tt> to <tt>(width() - 1,height() - 1,depth() - 1,spectrum() - 1)</tt>. - Due to the particular arrangement of the pixel buffers defined in %CImg, you can omit one coordinate if the corresponding dimension is equal to \c 1. For instance, pixels of a 2D image (depth() equal to \c 1) can be accessed by <tt>img(x,y,c)</tt> instead of <tt>img(x,y,0,c)</tt>. \warning - There is \e no boundary checking done in this operator, to make it as fast as possible. You \e must take care of out-of-bounds access by yourself, if necessary. For debuging purposes, you may want to define macro \c 'cimg_verbosity'>=3 to enable additional boundary checking operations in this operator. In that case, warning messages will be printed on the error output when accessing out-of-bounds pixels. \par Example \code CImg<float> img(100,100,1,3,0); // Construct a 100x100x1x3 (color) image with pixels set to '0' const float valR = img(10,10,0,0), // Read red value at coordinates (10,10) valG = img(10,10,0,1), // Read green value at coordinates (10,10) valB = img(10,10,2), // Read blue value at coordinates (10,10) (Z-coordinate can be omitted) avg = (valR + valG + valB)/3; // Compute average pixel value img(10,10,0) = img(10,10,1) = img(10,10,2) = avg; // Replace the color pixel (10,10) by the average grey value \endcode **/ #if cimg_verbosity>=3 T& operator()(const unsigned int x, const unsigned int y=0, const unsigned int z=0, const unsigned int c=0) { const ulongT off = (ulongT)offset(x,y,z,c); if (!_data || off>=size()) { cimg::warn(_cimg_instance "operator(): Invalid pixel request, at coordinates (%d,%d,%d,%d) [offset=%u].", cimg_instance, (int)x,(int)y,(int)z,(int)c,off); return *_data; } else return _data[off]; } //! Access to a pixel value \const. const T& operator()(const unsigned int x, const unsigned int y=0, const unsigned int z=0, const unsigned int c=0) const { return const_cast<CImg<T>*>(this)->operator()(x,y,z,c); } //! Access to a pixel value. /** \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param wh Precomputed offset, must be equal to <tt>width()*\ref height()</tt>. \param whd Precomputed offset, must be equal to <tt>width()*\ref height()*\ref depth()</tt>. \note - Similar to (but faster than) operator()(). It uses precomputed offsets to optimize memory access. You may use it to optimize the reading/writing of several pixel values in the same image (e.g. in a loop). **/ T& operator()(const unsigned int x, const unsigned int y, const unsigned int z, const unsigned int c, const ulongT wh, const ulongT whd=0) { cimg::unused(wh,whd); return (*this)(x,y,z,c); } //! Access to a pixel value \const. const T& operator()(const unsigned int x, const unsigned int y, const unsigned int z, const unsigned int c, const ulongT wh, const ulongT whd=0) const { cimg::unused(wh,whd); return (*this)(x,y,z,c); } #else T& operator()(const unsigned int x) { return _data[x]; } const T& operator()(const unsigned int x) const { return _data[x]; } T& operator()(const unsigned int x, const unsigned int y) { return _data[x + y*_width]; } const T& operator()(const unsigned int x, const unsigned int y) const { return _data[x + y*_width]; } T& operator()(const unsigned int x, const unsigned int y, const unsigned int z) { return _data[x + y*(ulongT)_width + z*(ulongT)_width*_height]; } const T& operator()(const unsigned int x, const unsigned int y, const unsigned int z) const { return _data[x + y*(ulongT)_width + z*(ulongT)_width*_height]; } T& operator()(const unsigned int x, const unsigned int y, const unsigned int z, const unsigned int c) { return _data[x + y*(ulongT)_width + z*(ulongT)_width*_height + c*(ulongT)_width*_height*_depth]; } const T& operator()(const unsigned int x, const unsigned int y, const unsigned int z, const unsigned int c) const { return _data[x + y*(ulongT)_width + z*(ulongT)_width*_height + c*(ulongT)_width*_height*_depth]; } T& operator()(const unsigned int x, const unsigned int y, const unsigned int z, const unsigned int, const ulongT wh) { return _data[x + y*_width + z*wh]; } const T& operator()(const unsigned int x, const unsigned int y, const unsigned int z, const unsigned int, const ulongT wh) const { return _data[x + y*_width + z*wh]; } T& operator()(const unsigned int x, const unsigned int y, const unsigned int z, const unsigned int c, const ulongT wh, const ulongT whd) { return _data[x + y*_width + z*wh + c*whd]; } const T& operator()(const unsigned int x, const unsigned int y, const unsigned int z, const unsigned int c, const ulongT wh, const ulongT whd) const { return _data[x + y*_width + z*wh + c*whd]; } #endif //! Implicitely cast an image into a \c T*. /** Implicitely cast a \c CImg<T> instance into a \c T* or \c const \c T* pointer, whether the image instance is \e const or not. The returned pointer points on the first value of the image pixel buffer. \note - It simply returns the pointer data() to the pixel buffer. - This implicit conversion is convenient to test the empty state of images (data() being \c 0 in this case), e.g. \code CImg<float> img1(100,100), img2; // 'img1' is a 100x100 image, 'img2' is an empty image if (img1) { // Test succeeds, 'img1' is not an empty image if (!img2) { // Test succeeds, 'img2' is an empty image std::printf("'img1' is not empty, 'img2' is empty."); } } \endcode - It also allows to use brackets to access pixel values, without need for a \c CImg<T>::operator[](), e.g. \code CImg<float> img(100,100); const float value = img[99]; // Access to value of the last pixel on the first row img[510] = 255; // Set pixel value at (10,5) \endcode **/ operator T*() { return _data; } //! Implicitely cast an image into a \c T* \const. operator const T*() const { return _data; } //! Assign a value to all image pixels. /** Assign specified \c value to each pixel value of the image instance. \param value Value that will be assigned to image pixels. \note - The image size is never modified. - The \c value may be casted to pixel type \c T if necessary. \par Example \code CImg<char> img(100,100); // Declare image (with garbage values) img = 0; // Set all pixel values to '0' img = 1.2; // Set all pixel values to '1' (cast of '1.2' as a 'char') \endcode **/ CImg<T>& operator=(const T& value) { return fill(value); } //! Assign pixels values from a specified expression. /** Initialize all pixel values from the specified string \c expression. \param expression Value string describing the way pixel values are set. \note - String parameter \c expression may describe different things: - If \c expression is a list of values (as in \c "1,2,3,8,3,2"), or a formula (as in \c "(x*y)%255"), the pixel values are set from specified \c expression and the image size is not modified. - If \c expression is a filename (as in \c "reference.jpg"), the corresponding image file is loaded and replace the image instance. The image size is modified if necessary. \par Example \code CImg<float> img1(100,100), img2(img1), img3(img1); // Declare 3 scalar images 100x100 with unitialized values img1 = "0,50,100,150,200,250,200,150,100,50"; // Set pixel values of 'img1' from a value sequence img2 = "10*((x*y)%25)"; // Set pixel values of 'img2' from a formula img3 = "reference.jpg"; // Set pixel values of 'img3' from a file (image size is modified) (img1,img2,img3).display(); \endcode \image html ref_operator_eq.jpg **/ CImg<T>& operator=(const char *const expression) { const unsigned int omode = cimg::exception_mode(); cimg::exception_mode(0); try { _fill(expression,true,1,0,0,"operator=",0); } catch (CImgException&) { cimg::exception_mode(omode); load(expression); } cimg::exception_mode(omode); return *this; } //! Copy an image into the current image instance. /** Similar to the in-place copy constructor assign(const CImg<t>&). **/ template<typename t> CImg<T>& operator=(const CImg<t>& img) { return assign(img); } //! Copy an image into the current image instance \specialization. CImg<T>& operator=(const CImg<T>& img) { return assign(img); } //! Copy the content of a display window to the current image instance. /** Similar to assign(const CImgDisplay&). **/ CImg<T>& operator=(const CImgDisplay& disp) { disp.snapshot(*this); return *this; } //! In-place addition operator. /** Add specified \c value to all pixels of an image instance. \param value Value to add. \note - Resulting pixel values are casted to fit the pixel type \c T. For instance, adding \c 0.2 to a \c CImg<char> is possible but does nothing indeed. - Overflow values are treated as with standard C++ numeric types. For instance, \code CImg<unsigned char> img(100,100,1,1,255); // Construct a 100x100 image with pixel values '255' img+=1; // Add '1' to each pixels -> Overflow // here all pixels of image 'img' are equal to '0'. \endcode - To prevent value overflow, you may want to consider pixel type \c T as \c float or \c double, and use cut() after addition. \par Example \code CImg<unsigned char> img1("reference.jpg"); // Load a 8-bits RGB image (values in [0,255]) CImg<float> img2(img1); // Construct a float-valued copy of 'img1' img2+=100; // Add '100' to pixel values -> goes out of [0,255] but no problems with floats img2.cut(0,255); // Cut values in [0,255] to fit the 'unsigned char' constraint img1 = img2; // Rewrite safe result in 'unsigned char' version 'img1' const CImg<unsigned char> img3 = (img1 + 100).cut(0,255); // Do the same in a more simple and elegant way (img1,img2,img3).display(); \endcode \image html ref_operator_plus.jpg **/ template<typename t> CImg<T>& operator+=(const t value) { if (is_empty()) return *this; cimg_openmp_for(*this,*ptr + value,524288); return *this; } //! In-place addition operator. /** Add values to image pixels, according to the specified string \c expression. \param expression Value string describing the way pixel values are added. \note - Similar to operator=(const char*), except that it adds values to the pixels of the current image instance, instead of assigning them. **/ CImg<T>& operator+=(const char *const expression) { return *this+=(+*this)._fill(expression,true,1,0,0,"operator+=",this); } //! In-place addition operator. /** Add values to image pixels, according to the values of the input image \c img. \param img Input image to add. \note - The size of the image instance is never modified. - It is not mandatory that input image \c img has the same size as the image instance. If less values are available in \c img, then the values are added periodically. For instance, adding one WxH scalar image (spectrum() equal to \c 1) to one WxH color image (spectrum() equal to \c 3) means each color channel will be incremented with the same values at the same locations. \par Example \code CImg<float> img1("reference.jpg"); // Load a RGB color image (img1.spectrum()==3) // Construct a scalar shading (img2.spectrum()==1). const CImg<float> img2(img1.width(),img.height(),1,1,"255*(x/w)^2"); img1+=img2; // Add shading to each channel of 'img1' img1.cut(0,255); // Prevent [0,255] overflow (img2,img1).display(); \endcode \image html ref_operator_plus1.jpg **/ template<typename t> CImg<T>& operator+=(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return *this+=+img; T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)(*ptrd + *(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)(*ptrd + *(ptrs++)); } return *this; } //! In-place increment operator (prefix). /** Add \c 1 to all image pixels, and return a reference to the current incremented image instance. \note - Writing \c ++img is equivalent to \c img+=1. **/ CImg<T>& operator++() { if (is_empty()) return *this; cimg_openmp_for(*this,*ptr + 1,524288); return *this; } //! In-place increment operator (postfix). /** Add \c 1 to all image pixels, and return a new copy of the initial (pre-incremented) image instance. \note - Use the prefixed version operator++() if you don't need a copy of the initial (pre-incremented) image instance, since a useless image copy may be expensive in terms of memory usage. **/ CImg<T> operator++(int) { const CImg<T> copy(*this,false); ++*this; return copy; } //! Return a non-shared copy of the image instance. /** \note - Use this operator to ensure you get a non-shared copy of an image instance with same pixel type \c T. Indeed, the usual copy constructor CImg<T>(const CImg<T>&) returns a shared copy of a shared input image, and it may be not desirable to work on a regular copy (e.g. for a resize operation) if you have no information about the shared state of the input image. - Writing \c (+img) is equivalent to \c CImg<T>(img,false). **/ CImg<T> operator+() const { return CImg<T>(*this,false); } //! Addition operator. /** Similar to operator+=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator+(const t value) const { return CImg<_cimg_Tt>(*this,false)+=value; } //! Addition operator. /** Similar to operator+=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ CImg<Tfloat> operator+(const char *const expression) const { return CImg<Tfloat>(*this,false)+=expression; } //! Addition operator. /** Similar to operator+=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator+(const CImg<t>& img) const { return CImg<_cimg_Tt>(*this,false)+=img; } //! In-place substraction operator. /** Similar to operator+=(const t), except that it performs a substraction instead of an addition. **/ template<typename t> CImg<T>& operator-=(const t value) { if (is_empty()) return *this; cimg_openmp_for(*this,*ptr - value,524288); return *this; } //! In-place substraction operator. /** Similar to operator+=(const char*), except that it performs a substraction instead of an addition. **/ CImg<T>& operator-=(const char *const expression) { return *this-=(+*this)._fill(expression,true,1,0,0,"operator-=",this); } //! In-place substraction operator. /** Similar to operator+=(const CImg<t>&), except that it performs a substraction instead of an addition. **/ template<typename t> CImg<T>& operator-=(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return *this-=+img; T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)(*ptrd - *(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)(*ptrd - *(ptrs++)); } return *this; } //! In-place decrement operator (prefix). /** Similar to operator++(), except that it performs a decrement instead of an increment. **/ CImg<T>& operator--() { if (is_empty()) return *this; cimg_openmp_for(*this,*ptr - 1,524288); return *this; } //! In-place decrement operator (postfix). /** Similar to operator++(int), except that it performs a decrement instead of an increment. **/ CImg<T> operator--(int) { const CImg<T> copy(*this,false); --*this; return copy; } //! Replace each pixel by its opposite value. /** \note - If the computed opposite values are out-of-range, they are treated as with standard C++ numeric types. For instance, the \c unsigned \c char opposite of \c 1 is \c 255. \par Example \code const CImg<unsigned char> img1("reference.jpg"), // Load a RGB color image img2 = -img1; // Compute its opposite (in 'unsigned char') (img1,img2).display(); \endcode \image html ref_operator_minus.jpg **/ CImg<T> operator-() const { return CImg<T>(_width,_height,_depth,_spectrum,(T)0)-=*this; } //! Substraction operator. /** Similar to operator-=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator-(const t value) const { return CImg<_cimg_Tt>(*this,false)-=value; } //! Substraction operator. /** Similar to operator-=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ CImg<Tfloat> operator-(const char *const expression) const { return CImg<Tfloat>(*this,false)-=expression; } //! Substraction operator. /** Similar to operator-=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator-(const CImg<t>& img) const { return CImg<_cimg_Tt>(*this,false)-=img; } //! In-place multiplication operator. /** Similar to operator+=(const t), except that it performs a multiplication instead of an addition. **/ template<typename t> CImg<T>& operator*=(const t value) { if (is_empty()) return *this; cimg_openmp_for(*this,*ptr * value,262144); return *this; } //! In-place multiplication operator. /** Similar to operator+=(const char*), except that it performs a multiplication instead of an addition. **/ CImg<T>& operator*=(const char *const expression) { return mul((+*this)._fill(expression,true,1,0,0,"operator*=",this)); } //! In-place multiplication operator. /** Replace the image instance by the matrix multiplication between the image instance and the specified matrix \c img. \param img Second operand of the matrix multiplication. \note - It does \e not compute a pointwise multiplication between two images. For this purpose, use mul(const CImg<t>&) instead. - The size of the image instance can be modified by this operator. \par Example \code CImg<float> A(2,2,1,1, 1,2,3,4); // Construct 2x2 matrix A = [1,2;3,4] const CImg<float> X(1,2,1,1, 1,2); // Construct 1x2 vector X = [1;2] A*=X; // Assign matrix multiplication A*X to 'A' // 'A' is now a 1x2 vector whose values are [5;11]. \endcode **/ template<typename t> CImg<T>& operator*=(const CImg<t>& img) { return ((*this)*img).move_to(*this); } //! Multiplication operator. /** Similar to operator*=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator*(const t value) const { return CImg<_cimg_Tt>(*this,false)*=value; } //! Multiplication operator. /** Similar to operator*=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ CImg<Tfloat> operator*(const char *const expression) const { return CImg<Tfloat>(*this,false)*=expression; } //! Multiplication operator. /** Similar to operator*=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator*(const CImg<t>& img) const { typedef _cimg_Ttdouble Ttdouble; typedef _cimg_Tt Tt; if (_width!=img._height || _depth!=1 || _spectrum!=1) throw CImgArgumentException(_cimg_instance "operator*(): Invalid multiplication of instance by specified " "matrix (%u,%u,%u,%u,%p)", cimg_instance, img._width,img._height,img._depth,img._spectrum,img._data); CImg<Tt> res(img._width,_height); // Check for common cases to optimize. if (img._width==1) { // Matrix * Vector if (_height==1) switch (_width) { // Vector^T * Vector case 1 : res[0] = (Tt)((Ttdouble)_data[0]*img[0]); return res; case 2 : res[0] = (Tt)((Ttdouble)_data[0]*img[0] + (Ttdouble)_data[1]*img[1]); return res; case 3 : res[0] = (Tt)((Ttdouble)_data[0]*img[0] + (Ttdouble)_data[1]*img[1] + (Ttdouble)_data[2]*img[2]); return res; case 4 : res[0] = (Tt)((Ttdouble)_data[0]*img[0] + (Ttdouble)_data[1]*img[1] + (Ttdouble)_data[2]*img[2] + (Ttdouble)_data[3]*img[3]); return res; default : { Ttdouble val = 0; cimg_forX(*this,i) val+=(Ttdouble)_data[i]*img[i]; res[0] = val; return res; } } else if (_height==_width) switch (_width) { // Square_matrix * Vector case 2 : // 2x2_matrix * Vector res[0] = (Tt)((Ttdouble)_data[0]*img[0] + (Ttdouble)_data[1]*img[1]); res[1] = (Tt)((Ttdouble)_data[2]*img[0] + (Ttdouble)_data[3]*img[1]); return res; case 3 : // 3x3_matrix * Vector res[0] = (Tt)((Ttdouble)_data[0]*img[0] + (Ttdouble)_data[1]*img[1] + (Ttdouble)_data[2]*img[2]); res[1] = (Tt)((Ttdouble)_data[3]*img[0] + (Ttdouble)_data[4]*img[1] + (Ttdouble)_data[5]*img[2]); res[2] = (Tt)((Ttdouble)_data[6]*img[0] + (Ttdouble)_data[7]*img[1] + (Ttdouble)_data[8]*img[2]); return res; case 4 : // 4x4_matrix * Vector res[0] = (Tt)((Ttdouble)_data[0]*img[0] + (Ttdouble)_data[1]*img[1] + (Ttdouble)_data[2]*img[2] + (Ttdouble)_data[3]*img[3]); res[1] = (Tt)((Ttdouble)_data[4]*img[0] + (Ttdouble)_data[5]*img[1] + (Ttdouble)_data[6]*img[2] + (Ttdouble)_data[7]*img[3]); res[2] = (Tt)((Ttdouble)_data[8]*img[0] + (Ttdouble)_data[9]*img[1] + (Ttdouble)_data[10]*img[2] + (Ttdouble)_data[11]*img[3]); res[3] = (Tt)((Ttdouble)_data[12]*img[0] + (Ttdouble)_data[13]*img[1] + (Ttdouble)_data[14]*img[2] + (Ttdouble)_data[15]*img[3]); return res; } } else if (_height==_width) { if (img._height==img._width) switch (_width) { // Square_matrix * Square_matrix case 2 : // 2x2_matrix * 2x2_matrix res[0] = (Tt)((Ttdouble)_data[0]*img[0] + (Ttdouble)_data[1]*img[2]); res[1] = (Tt)((Ttdouble)_data[0]*img[1] + (Ttdouble)_data[1]*img[3]); res[2] = (Tt)((Ttdouble)_data[2]*img[0] + (Ttdouble)_data[3]*img[2]); res[3] = (Tt)((Ttdouble)_data[2]*img[1] + (Ttdouble)_data[3]*img[3]); return res; case 3 : // 3x3_matrix * 3x3_matrix res[0] = (Tt)((Ttdouble)_data[0]*img[0] + (Ttdouble)_data[1]*img[3] + (Ttdouble)_data[2]*img[6]); res[1] = (Tt)((Ttdouble)_data[0]*img[1] + (Ttdouble)_data[1]*img[4] + (Ttdouble)_data[2]*img[7]); res[2] = (Tt)((Ttdouble)_data[0]*img[2] + (Ttdouble)_data[1]*img[5] + (Ttdouble)_data[2]*img[8]); res[3] = (Tt)((Ttdouble)_data[3]*img[0] + (Ttdouble)_data[4]*img[3] + (Ttdouble)_data[5]*img[6]); res[4] = (Tt)((Ttdouble)_data[3]*img[1] + (Ttdouble)_data[4]*img[4] + (Ttdouble)_data[5]*img[7]); res[5] = (Tt)((Ttdouble)_data[3]*img[2] + (Ttdouble)_data[4]*img[5] + (Ttdouble)_data[5]*img[8]); res[6] = (Tt)((Ttdouble)_data[6]*img[0] + (Ttdouble)_data[7]*img[3] + (Ttdouble)_data[8]*img[6]); res[7] = (Tt)((Ttdouble)_data[6]*img[1] + (Ttdouble)_data[7]*img[4] + (Ttdouble)_data[8]*img[7]); res[8] = (Tt)((Ttdouble)_data[6]*img[2] + (Ttdouble)_data[7]*img[5] + (Ttdouble)_data[8]*img[8]); return res; case 4 : // 4x4_matrix * 4x4_matrix res[0] = (Tt)((Ttdouble)_data[0]*img[0] + (Ttdouble)_data[1]*img[4] + (Ttdouble)_data[2]*img[8] + (Ttdouble)_data[3]*img[12]); res[1] = (Tt)((Ttdouble)_data[0]*img[1] + (Ttdouble)_data[1]*img[5] + (Ttdouble)_data[2]*img[9] + (Ttdouble)_data[3]*img[13]); res[2] = (Tt)((Ttdouble)_data[0]*img[2] + (Ttdouble)_data[1]*img[6] + (Ttdouble)_data[2]*img[10] + (Ttdouble)_data[3]*img[14]); res[3] = (Tt)((Ttdouble)_data[0]*img[3] + (Ttdouble)_data[1]*img[7] + (Ttdouble)_data[2]*img[11] + (Ttdouble)_data[3]*img[15]); res[4] = (Tt)((Ttdouble)_data[4]*img[0] + (Ttdouble)_data[5]*img[4] + (Ttdouble)_data[6]*img[8] + (Ttdouble)_data[7]*img[12]); res[5] = (Tt)((Ttdouble)_data[4]*img[1] + (Ttdouble)_data[5]*img[5] + (Ttdouble)_data[6]*img[9] + (Ttdouble)_data[7]*img[13]); res[6] = (Tt)((Ttdouble)_data[4]*img[2] + (Ttdouble)_data[5]*img[6] + (Ttdouble)_data[6]*img[10] + (Ttdouble)_data[7]*img[14]); res[7] = (Tt)((Ttdouble)_data[4]*img[3] + (Ttdouble)_data[5]*img[7] + (Ttdouble)_data[6]*img[11] + (Ttdouble)_data[7]*img[15]); res[8] = (Tt)((Ttdouble)_data[8]*img[0] + (Ttdouble)_data[9]*img[4] + (Ttdouble)_data[10]*img[8] + (Ttdouble)_data[11]*img[12]); res[9] = (Tt)((Ttdouble)_data[8]*img[1] + (Ttdouble)_data[9]*img[5] + (Ttdouble)_data[10]*img[9] + (Ttdouble)_data[11]*img[13]); res[10] = (Tt)((Ttdouble)_data[8]*img[2] + (Ttdouble)_data[9]*img[6] + (Ttdouble)_data[10]*img[10] + (Ttdouble)_data[11]*img[14]); res[11] = (Tt)((Ttdouble)_data[8]*img[3] + (Ttdouble)_data[9]*img[7] + (Ttdouble)_data[10]*img[11] + (Ttdouble)_data[11]*img[15]); res[12] = (Tt)((Ttdouble)_data[12]*img[0] + (Ttdouble)_data[13]*img[4] + (Ttdouble)_data[14]*img[8] + (Ttdouble)_data[15]*img[12]); res[13] = (Tt)((Ttdouble)_data[12]*img[1] + (Ttdouble)_data[13]*img[5] + (Ttdouble)_data[14]*img[9] + (Ttdouble)_data[15]*img[13]); res[14] = (Tt)((Ttdouble)_data[12]*img[2] + (Ttdouble)_data[13]*img[6] + (Ttdouble)_data[14]*img[10] + (Ttdouble)_data[15]*img[14]); res[15] = (Tt)((Ttdouble)_data[12]*img[3] + (Ttdouble)_data[13]*img[7] + (Ttdouble)_data[14]*img[11] + (Ttdouble)_data[15]*img[15]); return res; } else switch (_width) { // Square_matrix * Matrix case 2 : { // 2x2_matrix * Matrix const t *ps0 = img.data(), *ps1 = img.data(0,1); Tt *pd0 = res.data(), *pd1 = res.data(0,1); const Ttdouble a0 = (Ttdouble)_data[0], a1 = (Ttdouble)_data[1], a2 = (Ttdouble)_data[2], a3 = (Ttdouble)_data[3]; cimg_forX(img,i) { const Ttdouble x = (Ttdouble)*(ps0++), y = (Ttdouble)*(ps1++); *(pd0++) = (Tt)(a0*x + a1*y); *(pd1++) = (Tt)(a2*x + a3*y); } return res; } case 3 : { // 3x3_matrix * Matrix const t *ps0 = img.data(), *ps1 = img.data(0,1), *ps2 = img.data(0,2); Tt *pd0 = res.data(), *pd1 = res.data(0,1), *pd2 = res.data(0,2); const Ttdouble a0 = (Ttdouble)_data[0], a1 = (Ttdouble)_data[1], a2 = (Ttdouble)_data[2], a3 = (Ttdouble)_data[3], a4 = (Ttdouble)_data[4], a5 = (Ttdouble)_data[5], a6 = (Ttdouble)_data[6], a7 = (Ttdouble)_data[7], a8 = (Ttdouble)_data[8]; cimg_forX(img,i) { const Ttdouble x = (Ttdouble)*(ps0++), y = (Ttdouble)*(ps1++), z = (Ttdouble)*(ps2++); *(pd0++) = (Tt)(a0*x + a1*y + a2*z); *(pd1++) = (Tt)(a3*x + a4*y + a5*z); *(pd2++) = (Tt)(a6*x + a7*y + a8*z); } return res; } case 4 : { // 4x4_matrix * Matrix const t *ps0 = img.data(), *ps1 = img.data(0,1), *ps2 = img.data(0,2), *ps3 = img.data(0,3); Tt *pd0 = res.data(), *pd1 = res.data(0,1), *pd2 = res.data(0,2), *pd3 = res.data(0,3); const Ttdouble a0 = (Ttdouble)_data[0], a1 = (Ttdouble)_data[1], a2 = (Ttdouble)_data[2], a3 = (Ttdouble)_data[3], a4 = (Ttdouble)_data[4], a5 = (Ttdouble)_data[5], a6 = (Ttdouble)_data[6], a7 = (Ttdouble)_data[7], a8 = (Ttdouble)_data[8], a9 = (Ttdouble)_data[9], a10 = (Ttdouble)_data[10], a11 = (Ttdouble)_data[11], a12 = (Ttdouble)_data[12], a13 = (Ttdouble)_data[13], a14 = (Ttdouble)_data[14], a15 = (Ttdouble)_data[15]; cimg_forX(img,col) { const Ttdouble x = (Ttdouble)*(ps0++), y = (Ttdouble)*(ps1++), z = (Ttdouble)*(ps2++), c = (Ttdouble)*(ps3++); *(pd0++) = (Tt)(a0*x + a1*y + a2*z + a3*c); *(pd1++) = (Tt)(a4*x + a5*y + a6*z + a7*c); *(pd2++) = (Tt)(a8*x + a9*y + a10*z + a11*c); *(pd3++) = (Tt)(a12*x + a13*y + a14*z + a15*c); } return res; } } } // Fallback to generic version. #if cimg_use_openmp!=0 cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(size()>(cimg_openmp_sizefactor)*1024 && img.size()>(cimg_openmp_sizefactor)*1024)) cimg_forXY(res,i,j) { Ttdouble value = 0; cimg_forX(*this,k) value+=(*this)(k,j)*img(i,k); res(i,j) = (Tt)value; } #else Tt *ptrd = res._data; cimg_forXY(res,i,j) { Ttdouble value = 0; cimg_forX(*this,k) value+=(*this)(k,j)*img(i,k); *(ptrd++) = (Tt)value; } #endif return res; } //! In-place division operator. /** Similar to operator+=(const t), except that it performs a division instead of an addition. **/ template<typename t> CImg<T>& operator/=(const t value) { if (is_empty()) return *this; cimg_openmp_for(*this,*ptr / value,32768); return *this; } //! In-place division operator. /** Similar to operator+=(const char*), except that it performs a division instead of an addition. **/ CImg<T>& operator/=(const char *const expression) { return div((+*this)._fill(expression,true,1,0,0,"operator/=",this)); } //! In-place division operator. /** Replace the image instance by the (right) matrix division between the image instance and the specified matrix \c img. \param img Second operand of the matrix division. \note - It does \e not compute a pointwise division between two images. For this purpose, use div(const CImg<t>&) instead. - It returns the matrix operation \c A*inverse(img). - The size of the image instance can be modified by this operator. **/ template<typename t> CImg<T>& operator/=(const CImg<t>& img) { return (*this*img.get_invert()).move_to(*this); } //! Division operator. /** Similar to operator/=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator/(const t value) const { return CImg<_cimg_Tt>(*this,false)/=value; } //! Division operator. /** Similar to operator/=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ CImg<Tfloat> operator/(const char *const expression) const { return CImg<Tfloat>(*this,false)/=expression; } //! Division operator. /** Similar to operator/=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator/(const CImg<t>& img) const { return (*this)*img.get_invert(); } //! In-place modulo operator. /** Similar to operator+=(const t), except that it performs a modulo operation instead of an addition. **/ template<typename t> CImg<T>& operator%=(const t value) { if (is_empty()) return *this; cimg_openmp_for(*this,cimg::mod(*ptr,(T)value),16384); return *this; } //! In-place modulo operator. /** Similar to operator+=(const char*), except that it performs a modulo operation instead of an addition. **/ CImg<T>& operator%=(const char *const expression) { return *this%=(+*this)._fill(expression,true,1,0,0,"operator%=",this); } //! In-place modulo operator. /** Similar to operator+=(const CImg<t>&), except that it performs a modulo operation instead of an addition. **/ template<typename t> CImg<T>& operator%=(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return *this%=+img; T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = cimg::mod(*ptrd,(T)*(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = cimg::mod(*ptrd,(T)*(ptrs++)); } return *this; } //! Modulo operator. /** Similar to operator%=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator%(const t value) const { return CImg<_cimg_Tt>(*this,false)%=value; } //! Modulo operator. /** Similar to operator%=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ CImg<Tfloat> operator%(const char *const expression) const { return CImg<Tfloat>(*this,false)%=expression; } //! Modulo operator. /** Similar to operator%=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator%(const CImg<t>& img) const { return CImg<_cimg_Tt>(*this,false)%=img; } //! In-place bitwise AND operator. /** Similar to operator+=(const t), except that it performs a bitwise AND operation instead of an addition. **/ template<typename t> CImg<T>& operator&=(const t value) { if (is_empty()) return *this; cimg_openmp_for(*this,(ulongT)*ptr & (ulongT)value,32768); return *this; } //! In-place bitwise AND operator. /** Similar to operator+=(const char*), except that it performs a bitwise AND operation instead of an addition. **/ CImg<T>& operator&=(const char *const expression) { return *this&=(+*this)._fill(expression,true,1,0,0,"operator&=",this); } //! In-place bitwise AND operator. /** Similar to operator+=(const CImg<t>&), except that it performs a bitwise AND operation instead of an addition. **/ template<typename t> CImg<T>& operator&=(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return *this&=+img; T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)((ulongT)*ptrd & (ulongT)*(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)((ulongT)*ptrd & (ulongT)*(ptrs++)); } return *this; } //! Bitwise AND operator. /** Similar to operator&=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator&(const t value) const { return (+*this)&=value; } //! Bitwise AND operator. /** Similar to operator&=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ CImg<T> operator&(const char *const expression) const { return (+*this)&=expression; } //! Bitwise AND operator. /** Similar to operator&=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator&(const CImg<t>& img) const { return (+*this)&=img; } //! In-place bitwise OR operator. /** Similar to operator+=(const t), except that it performs a bitwise OR operation instead of an addition. **/ template<typename t> CImg<T>& operator|=(const t value) { if (is_empty()) return *this; cimg_openmp_for(*this,(ulongT)*ptr | (ulongT)value,32768); return *this; } //! In-place bitwise OR operator. /** Similar to operator+=(const char*), except that it performs a bitwise OR operation instead of an addition. **/ CImg<T>& operator|=(const char *const expression) { return *this|=(+*this)._fill(expression,true,1,0,0,"operator|=",this); } //! In-place bitwise OR operator. /** Similar to operator+=(const CImg<t>&), except that it performs a bitwise OR operation instead of an addition. **/ template<typename t> CImg<T>& operator|=(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return *this|=+img; T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)((ulongT)*ptrd | (ulongT)*(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)((ulongT)*ptrd | (ulongT)*(ptrs++)); } return *this; } //! Bitwise OR operator. /** Similar to operator|=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator|(const t value) const { return (+*this)|=value; } //! Bitwise OR operator. /** Similar to operator|=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ CImg<T> operator|(const char *const expression) const { return (+*this)|=expression; } //! Bitwise OR operator. /** Similar to operator|=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator|(const CImg<t>& img) const { return (+*this)|=img; } //! In-place bitwise XOR operator. /** Similar to operator+=(const t), except that it performs a bitwise XOR operation instead of an addition. \warning - It does \e not compute the \e power of pixel values. For this purpose, use pow(const t) instead. **/ template<typename t> CImg<T>& operator^=(const t value) { if (is_empty()) return *this; cimg_openmp_for(*this,(ulongT)*ptr ^ (ulongT)value,32768); return *this; } //! In-place bitwise XOR operator. /** Similar to operator+=(const char*), except that it performs a bitwise XOR operation instead of an addition. \warning - It does \e not compute the \e power of pixel values. For this purpose, use pow(const char*) instead. **/ CImg<T>& operator^=(const char *const expression) { return *this^=(+*this)._fill(expression,true,1,0,0,"operator^=",this); } //! In-place bitwise XOR operator. /** Similar to operator+=(const CImg<t>&), except that it performs a bitwise XOR operation instead of an addition. \warning - It does \e not compute the \e power of pixel values. For this purpose, use pow(const CImg<t>&) instead. **/ template<typename t> CImg<T>& operator^=(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return *this^=+img; T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)((ulongT)*ptrd ^ (ulongT)*(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)((ulongT)*ptrd ^ (ulongT)*(ptrs++)); } return *this; } //! Bitwise XOR operator. /** Similar to operator^=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator^(const t value) const { return (+*this)^=value; } //! Bitwise XOR operator. /** Similar to operator^=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ CImg<T> operator^(const char *const expression) const { return (+*this)^=expression; } //! Bitwise XOR operator. /** Similar to operator^=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator^(const CImg<t>& img) const { return (+*this)^=img; } //! In-place bitwise left shift operator. /** Similar to operator+=(const t), except that it performs a bitwise left shift instead of an addition. **/ template<typename t> CImg<T>& operator<<=(const t value) { if (is_empty()) return *this; cimg_openmp_for(*this,((longT)*ptr) << (int)value,65536); return *this; } //! In-place bitwise left shift operator. /** Similar to operator+=(const char*), except that it performs a bitwise left shift instead of an addition. **/ CImg<T>& operator<<=(const char *const expression) { return *this<<=(+*this)._fill(expression,true,1,0,0,"operator<<=",this); } //! In-place bitwise left shift operator. /** Similar to operator+=(const CImg<t>&), except that it performs a bitwise left shift instead of an addition. **/ template<typename t> CImg<T>& operator<<=(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return *this^=+img; T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)((longT)*ptrd << (int)*(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)((longT)*ptrd << (int)*(ptrs++)); } return *this; } //! Bitwise left shift operator. /** Similar to operator<<=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator<<(const t value) const { return (+*this)<<=value; } //! Bitwise left shift operator. /** Similar to operator<<=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ CImg<T> operator<<(const char *const expression) const { return (+*this)<<=expression; } //! Bitwise left shift operator. /** Similar to operator<<=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator<<(const CImg<t>& img) const { return (+*this)<<=img; } //! In-place bitwise right shift operator. /** Similar to operator+=(const t), except that it performs a bitwise right shift instead of an addition. **/ template<typename t> CImg<T>& operator>>=(const t value) { if (is_empty()) return *this; cimg_openmp_for(*this,((longT)*ptr) >> (int)value,65536); return *this; } //! In-place bitwise right shift operator. /** Similar to operator+=(const char*), except that it performs a bitwise right shift instead of an addition. **/ CImg<T>& operator>>=(const char *const expression) { return *this>>=(+*this)._fill(expression,true,1,0,0,"operator>>=",this); } //! In-place bitwise right shift operator. /** Similar to operator+=(const CImg<t>&), except that it performs a bitwise right shift instead of an addition. **/ template<typename t> CImg<T>& operator>>=(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return *this^=+img; T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)((longT)*ptrd >> (int)*(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)((longT)*ptrd >> (int)*(ptrs++)); } return *this; } //! Bitwise right shift operator. /** Similar to operator>>=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator>>(const t value) const { return (+*this)>>=value; } //! Bitwise right shift operator. /** Similar to operator>>=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ CImg<T> operator>>(const char *const expression) const { return (+*this)>>=expression; } //! Bitwise right shift operator. /** Similar to operator>>=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator>>(const CImg<t>& img) const { return (+*this)>>=img; } //! Bitwise inversion operator. /** Similar to operator-(), except that it compute the bitwise inverse instead of the opposite value. **/ CImg<T> operator~() const { CImg<T> res(_width,_height,_depth,_spectrum); const T *ptrs = _data; cimg_for(res,ptrd,T) { const ulongT value = (ulongT)*(ptrs++); *ptrd = (T)~value; } return res; } //! Test if all pixels of an image have the same value. /** Return \c true is all pixels of the image instance are equal to the specified \c value. \param value Reference value to compare with. **/ template<typename t> bool operator==(const t value) const { if (is_empty()) return false; typedef _cimg_Tt Tt; bool is_equal = true; for (T *ptrd = _data + size(); is_equal && ptrd>_data; is_equal = ((Tt)*(--ptrd)==(Tt)value)) {} return is_equal; } //! Test if all pixel values of an image follow a specified expression. /** Return \c true is all pixels of the image instance are equal to the specified \c expression. \param expression Value string describing the way pixel values are compared. **/ bool operator==(const char *const expression) const { return *this==(+*this)._fill(expression,true,1,0,0,"operator==",this); } //! Test if two images have the same size and values. /** Return \c true if the image instance and the input image \c img have the same dimensions and pixel values, and \c false otherwise. \param img Input image to compare with. \note - The pixel buffer pointers data() of the two compared images do not have to be the same for operator==() to return \c true. Only the dimensions and the pixel values matter. Thus, the comparison can be \c true even for different pixel types \c T and \c t. \par Example \code const CImg<float> img1(1,3,1,1, 0,1,2); // Construct a 1x3 vector [0;1;2] (with 'float' pixel values) const CImg<char> img2(1,3,1,1, 0,1,2); // Construct a 1x3 vector [0;1;2] (with 'char' pixel values) if (img1==img2) { // Test succeeds, image dimensions and values are the same std::printf("'img1' and 'img2' have same dimensions and values."); } \endcode **/ template<typename t> bool operator==(const CImg<t>& img) const { typedef _cimg_Tt Tt; const ulongT siz = size(); bool is_equal = true; if (siz!=img.size()) return false; t *ptrs = img._data + siz; for (T *ptrd = _data + siz; is_equal && ptrd>_data; is_equal = ((Tt)*(--ptrd)==(Tt)*(--ptrs))) {} return is_equal; } //! Test if pixels of an image are all different from a value. /** Return \c true is all pixels of the image instance are different than the specified \c value. \param value Reference value to compare with. **/ template<typename t> bool operator!=(const t value) const { return !((*this)==value); } //! Test if all pixel values of an image are different from a specified expression. /** Return \c true is all pixels of the image instance are different to the specified \c expression. \param expression Value string describing the way pixel values are compared. **/ bool operator!=(const char *const expression) const { return !((*this)==expression); } //! Test if two images have different sizes or values. /** Return \c true if the image instance and the input image \c img have different dimensions or pixel values, and \c false otherwise. \param img Input image to compare with. \note - Writing \c img1!=img2 is equivalent to \c !(img1==img2). **/ template<typename t> bool operator!=(const CImg<t>& img) const { return !((*this)==img); } //! Construct an image list from two images. /** Return a new list of image (\c CImgList instance) containing exactly two elements: - A copy of the image instance, at position [\c 0]. - A copy of the specified image \c img, at position [\c 1]. \param img Input image that will be the second image of the resulting list. \note - The family of operator,() is convenient to easily create list of images, but it is also \e quite \e slow in practice (see warning below). - Constructed lists contain no shared images. If image instance or input image \c img are shared, they are inserted as new non-shared copies in the resulting list. - The pixel type of the returned list may be a superset of the initial pixel type \c T, if necessary. \warning - Pipelining operator,() \c N times will perform \c N copies of the entire content of a (growing) image list. This may become very expensive in terms of speed and used memory. You should avoid using this technique to build a new CImgList instance from several images, if you are seeking for performance. Fast insertions of images in an image list are possible with CImgList<T>::insert(const CImg<t>&,unsigned int,bool) or move_to(CImgList<t>&,unsigned int). \par Example \code const CImg<float> img1("reference.jpg"), img2 = img1.get_mirror('x'), img3 = img2.get_blur(5); const CImgList<float> list = (img1,img2); // Create list of two elements from 'img1' and 'img2' (list,img3).display(); // Display image list containing copies of 'img1','img2' and 'img3' \endcode \image html ref_operator_comma.jpg **/ template<typename t> CImgList<_cimg_Tt> operator,(const CImg<t>& img) const { return CImgList<_cimg_Tt>(*this,img); } //! Construct an image list from image instance and an input image list. /** Return a new list of images (\c CImgList instance) containing exactly \c list.size() \c + \c 1 elements: - A copy of the image instance, at position [\c 0]. - A copy of the specified image list \c list, from positions [\c 1] to [\c list.size()]. \param list Input image list that will be appended to the image instance. \note - Similar to operator,(const CImg<t>&) const, except that it takes an image list as an argument. **/ template<typename t> CImgList<_cimg_Tt> operator,(const CImgList<t>& list) const { return CImgList<_cimg_Tt>(list,false).insert(*this,0); } //! Split image along specified axis. /** Return a new list of images (\c CImgList instance) containing the splitted components of the instance image along the specified axis. \param axis Splitting axis (can be '\c x','\c y','\c z' or '\c c') \note - Similar to get_split(char,int) const, with default second argument. \par Example \code const CImg<unsigned char> img("reference.jpg"); // Load a RGB color image const CImgList<unsigned char> list = (img<'c'); // Get a list of its three R,G,B channels (img,list).display(); \endcode \image html ref_operator_less.jpg **/ CImgList<T> operator<(const char axis) const { return get_split(axis); } //@} //------------------------------------- // //! \name Instance Characteristics //@{ //------------------------------------- //! Return the type of image pixel values as a C string. /** Return a \c char* string containing the usual type name of the image pixel values (i.e. a stringified version of the template parameter \c T). \note - The returned string may contain spaces (as in \c "unsigned char"). - If the pixel type \c T does not correspond to a registered type, the string <tt>"unknown"</tt> is returned. **/ static const char* pixel_type() { return cimg::type<T>::string(); } //! Return the number of image columns. /** Return the image width, i.e. the image dimension along the X-axis. \note - The width() of an empty image is equal to \c 0. - width() is typically equal to \c 1 when considering images as \e vectors for matrix calculations. - width() returns an \c int, although the image width is internally stored as an \c unsigned \c int. Using an \c int is safer and prevents arithmetic traps possibly encountered when doing calculations involving \c unsigned \c int variables. Access to the initial \c unsigned \c int variable is possible (though not recommended) by <tt>(*this)._width</tt>. **/ int width() const { return (int)_width; } //! Return the number of image rows. /** Return the image height, i.e. the image dimension along the Y-axis. \note - The height() of an empty image is equal to \c 0. - height() returns an \c int, although the image height is internally stored as an \c unsigned \c int. Using an \c int is safer and prevents arithmetic traps possibly encountered when doing calculations involving \c unsigned \c int variables. Access to the initial \c unsigned \c int variable is possible (though not recommended) by <tt>(*this)._height</tt>. **/ int height() const { return (int)_height; } //! Return the number of image slices. /** Return the image depth, i.e. the image dimension along the Z-axis. \note - The depth() of an empty image is equal to \c 0. - depth() is typically equal to \c 1 when considering usual 2D images. When depth()\c > \c 1, the image is said to be \e volumetric. - depth() returns an \c int, although the image depth is internally stored as an \c unsigned \c int. Using an \c int is safer and prevents arithmetic traps possibly encountered when doing calculations involving \c unsigned \c int variables. Access to the initial \c unsigned \c int variable is possible (though not recommended) by <tt>(*this)._depth</tt>. **/ int depth() const { return (int)_depth; } //! Return the number of image channels. /** Return the number of image channels, i.e. the image dimension along the C-axis. \note - The spectrum() of an empty image is equal to \c 0. - spectrum() is typically equal to \c 1 when considering scalar-valued images, to \c 3 for RGB-coded color images, and to \c 4 for RGBA-coded color images (with alpha-channel). The number of channels of an image instance is not limited. The meaning of the pixel values is not linked up to the number of channels (e.g. a 4-channel image may indifferently stands for a RGBA or CMYK color image). - spectrum() returns an \c int, although the image spectrum is internally stored as an \c unsigned \c int. Using an \c int is safer and prevents arithmetic traps possibly encountered when doing calculations involving \c unsigned \c int variables. Access to the initial \c unsigned \c int variable is possible (though not recommended) by <tt>(*this)._spectrum</tt>. **/ int spectrum() const { return (int)_spectrum; } //! Return the total number of pixel values. /** Return <tt>width()*\ref height()*\ref depth()*\ref spectrum()</tt>, i.e. the total number of values of type \c T in the pixel buffer of the image instance. \note - The size() of an empty image is equal to \c 0. - The allocated memory size for a pixel buffer of a non-shared \c CImg<T> instance is equal to <tt>size()*sizeof(T)</tt>. \par Example \code const CImg<float> img(100,100,1,3); // Construct new 100x100 color image if (img.size()==30000) // Test succeeds std::printf("Pixel buffer uses %lu bytes", img.size()*sizeof(float)); \endcode **/ ulongT size() const { return (ulongT)_width*_height*_depth*_spectrum; } //! Return a pointer to the first pixel value. /** Return a \c T*, or a \c const \c T* pointer to the first value in the pixel buffer of the image instance, whether the instance is \c const or not. \note - The data() of an empty image is equal to \c 0 (null pointer). - The allocated pixel buffer for the image instance starts from \c data() and goes to <tt>data()+\ref size() - 1</tt> (included). - To get the pointer to one particular location of the pixel buffer, use data(unsigned int,unsigned int,unsigned int,unsigned int) instead. **/ T* data() { return _data; } //! Return a pointer to the first pixel value \const. const T* data() const { return _data; } //! Return a pointer to a located pixel value. /** Return a \c T*, or a \c const \c T* pointer to the value located at (\c x,\c y,\c z,\c c) in the pixel buffer of the image instance, whether the instance is \c const or not. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note - Writing \c img.data(x,y,z,c) is equivalent to <tt>&(img(x,y,z,c))</tt>. Thus, this method has the same properties as operator()(unsigned int,unsigned int,unsigned int,unsigned int). **/ #if cimg_verbosity>=3 T *data(const unsigned int x, const unsigned int y=0, const unsigned int z=0, const unsigned int c=0) { const ulongT off = (ulongT)offset(x,y,z,c); if (off>=size()) cimg::warn(_cimg_instance "data(): Invalid pointer request, at coordinates (%u,%u,%u,%u) [offset=%u].", cimg_instance, x,y,z,c,off); return _data + off; } //! Return a pointer to a located pixel value \const. const T* data(const unsigned int x, const unsigned int y=0, const unsigned int z=0, const unsigned int c=0) const { return const_cast<CImg<T>*>(this)->data(x,y,z,c); } #else T* data(const unsigned int x, const unsigned int y=0, const unsigned int z=0, const unsigned int c=0) { return _data + x + (ulongT)y*_width + (ulongT)z*_width*_height + (ulongT)c*_width*_height*_depth; } const T* data(const unsigned int x, const unsigned int y=0, const unsigned int z=0, const unsigned int c=0) const { return _data + x + (ulongT)y*_width + (ulongT)z*_width*_height + (ulongT)c*_width*_height*_depth; } #endif //! Return the offset to a located pixel value, with respect to the beginning of the pixel buffer. /** \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note - Writing \c img.data(x,y,z,c) is equivalent to <tt>&(img(x,y,z,c)) - img.data()</tt>. Thus, this method has the same properties as operator()(unsigned int,unsigned int,unsigned int,unsigned int). \par Example \code const CImg<float> img(100,100,1,3); // Define a 100x100 RGB-color image const long off = img.offset(10,10,0,2); // Get the offset of the blue value of the pixel located at (10,10) const float val = img[off]; // Get the blue value of this pixel \endcode **/ longT offset(const int x, const int y=0, const int z=0, const int c=0) const { return x + (longT)y*_width + (longT)z*_width*_height + (longT)c*_width*_height*_depth; } //! Return a CImg<T>::iterator pointing to the first pixel value. /** \note - Equivalent to data(). - It has been mainly defined for compatibility with STL naming conventions. **/ iterator begin() { return _data; } //! Return a CImg<T>::iterator pointing to the first value of the pixel buffer \const. const_iterator begin() const { return _data; } //! Return a CImg<T>::iterator pointing next to the last pixel value. /** \note - Writing \c img.end() is equivalent to <tt>img.data() + img.size()</tt>. - It has been mainly defined for compatibility with STL naming conventions. \warning - The returned iterator actually points to a value located \e outside the acceptable bounds of the pixel buffer. Trying to read or write the content of the returned iterator will probably result in a crash. Use it mainly as a strict upper bound for a CImg<T>::iterator. \par Example \code CImg<float> img(100,100,1,3); // Define a 100x100 RGB color image // 'img.end()' used below as an upper bound for the iterator. for (CImg<float>::iterator it = img.begin(); it<img.end(); ++it) *it = 0; \endcode **/ iterator end() { return _data + size(); } //! Return a CImg<T>::iterator pointing next to the last pixel value \const. const_iterator end() const { return _data + size(); } //! Return a reference to the first pixel value. /** \note - Writing \c img.front() is equivalent to <tt>img[0]</tt>, or <tt>img(0,0,0,0)</tt>. - It has been mainly defined for compatibility with STL naming conventions. **/ T& front() { return *_data; } //! Return a reference to the first pixel value \const. const T& front() const { return *_data; } //! Return a reference to the last pixel value. /** \note - Writing \c img.back() is equivalent to <tt>img[img.size() - 1]</tt>, or <tt>img(img.width() - 1,img.height() - 1,img.depth() - 1,img.spectrum() - 1)</tt>. - It has been mainly defined for compatibility with STL naming conventions. **/ T& back() { return *(_data + size() - 1); } //! Return a reference to the last pixel value \const. const T& back() const { return *(_data + size() - 1); } //! Access to a pixel value at a specified offset, using Dirichlet boundary conditions. /** Return a reference to the pixel value of the image instance located at a specified \c offset, or to a specified default value in case of out-of-bounds access. \param offset Offset to the desired pixel value. \param out_value Default value returned if \c offset is outside image bounds. \note - Writing \c img.at(offset,out_value) is similar to <tt>img[offset]</tt>, except that if \c offset is outside bounds (e.g. \c offset<0 or \c offset>=img.size()), a reference to a value \c out_value is safely returned instead. - Due to the additional boundary checking operation, this method is slower than operator()(). Use it when you are \e not sure about the validity of the specified pixel offset. **/ T& at(const int offset, const T& out_value) { return (offset<0 || offset>=(int)size())?(cimg::temporary(out_value)=out_value):(*this)[offset]; } //! Access to a pixel value at a specified offset, using Dirichlet boundary conditions \const. T at(const int offset, const T& out_value) const { return (offset<0 || offset>=(int)size())?out_value:(*this)[offset]; } //! Access to a pixel value at a specified offset, using Neumann boundary conditions. /** Return a reference to the pixel value of the image instance located at a specified \c offset, or to the nearest pixel location in the image instance in case of out-of-bounds access. \param offset Offset to the desired pixel value. \note - Similar to at(int,const T), except that an out-of-bounds access returns the value of the nearest pixel in the image instance, regarding the specified offset, i.e. - If \c offset<0, then \c img[0] is returned. - If \c offset>=img.size(), then \c img[img.size() - 1] is returned. - Due to the additional boundary checking operation, this method is slower than operator()(). Use it when you are \e not sure about the validity of the specified pixel offset. - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _at(int). **/ T& at(const int offset) { if (is_empty()) throw CImgInstanceException(_cimg_instance "at(): Empty instance.", cimg_instance); return _at(offset); } T& _at(const int offset) { const unsigned int siz = (unsigned int)size(); return (*this)[offset<0?0:(unsigned int)offset>=siz?siz - 1:offset]; } //! Access to a pixel value at a specified offset, using Neumann boundary conditions \const. const T& at(const int offset) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "at(): Empty instance.", cimg_instance); return _at(offset); } const T& _at(const int offset) const { const unsigned int siz = (unsigned int)size(); return (*this)[offset<0?0:(unsigned int)offset>=siz?siz - 1:offset]; } //! Access to a pixel value, using Dirichlet boundary conditions for the X-coordinate. /** Return a reference to the pixel value of the image instance located at (\c x,\c y,\c z,\c c), or to a specified default value in case of out-of-bounds access along the X-axis. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param out_value Default value returned if \c (\c x,\c y,\c z,\c c) is outside image bounds. \note - Similar to operator()(), except that an out-of-bounds access along the X-axis returns the specified value \c out_value. - Due to the additional boundary checking operation, this method is slower than operator()(). Use it when you are \e not sure about the validity of the specified pixel coordinates. \warning - There is \e no boundary checking performed for the Y,Z and C-coordinates, so they must be inside image bounds. **/ T& atX(const int x, const int y, const int z, const int c, const T& out_value) { return (x<0 || x>=width())?(cimg::temporary(out_value)=out_value):(*this)(x,y,z,c); } //! Access to a pixel value, using Dirichlet boundary conditions for the X-coordinate \const. T atX(const int x, const int y, const int z, const int c, const T& out_value) const { return (x<0 || x>=width())?out_value:(*this)(x,y,z,c); } //! Access to a pixel value, using Neumann boundary conditions for the X-coordinate. /** Return a reference to the pixel value of the image instance located at (\c x,\c y,\c z,\c c), or to the nearest pixel location in the image instance in case of out-of-bounds access along the X-axis. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note - Similar to at(int,int,int,int,const T), except that an out-of-bounds access returns the value of the nearest pixel in the image instance, regarding the specified X-coordinate. - Due to the additional boundary checking operation, this method is slower than operator()(). Use it when you are \e not sure about the validity of the specified pixel coordinates. - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _at(int,int,int,int). \warning - There is \e no boundary checking performed for the Y,Z and C-coordinates, so they must be inside image bounds. **/ T& atX(const int x, const int y=0, const int z=0, const int c=0) { if (is_empty()) throw CImgInstanceException(_cimg_instance "atX(): Empty instance.", cimg_instance); return _atX(x,y,z,c); } T& _atX(const int x, const int y=0, const int z=0, const int c=0) { return (*this)(x<0?0:(x>=width()?width() - 1:x),y,z,c); } //! Access to a pixel value, using Neumann boundary conditions for the X-coordinate \const. const T& atX(const int x, const int y=0, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "atX(): Empty instance.", cimg_instance); return _atX(x,y,z,c); } const T& _atX(const int x, const int y=0, const int z=0, const int c=0) const { return (*this)(x<0?0:(x>=width()?width() - 1:x),y,z,c); } //! Access to a pixel value, using Dirichlet boundary conditions for the X and Y-coordinates. /** Similar to atX(int,int,int,int,const T), except that boundary checking is performed both on X and Y-coordinates. **/ T& atXY(const int x, const int y, const int z, const int c, const T& out_value) { return (x<0 || y<0 || x>=width() || y>=height())?(cimg::temporary(out_value)=out_value):(*this)(x,y,z,c); } //! Access to a pixel value, using Dirichlet boundary conditions for the X and Y coordinates \const. T atXY(const int x, const int y, const int z, const int c, const T& out_value) const { return (x<0 || y<0 || x>=width() || y>=height())?out_value:(*this)(x,y,z,c); } //! Access to a pixel value, using Neumann boundary conditions for the X and Y-coordinates. /** Similar to atX(int,int,int,int), except that boundary checking is performed both on X and Y-coordinates. \note - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _atXY(int,int,int,int). **/ T& atXY(const int x, const int y, const int z=0, const int c=0) { if (is_empty()) throw CImgInstanceException(_cimg_instance "atXY(): Empty instance.", cimg_instance); return _atXY(x,y,z,c); } T& _atXY(const int x, const int y, const int z=0, const int c=0) { return (*this)(cimg::cut(x,0,width() - 1), cimg::cut(y,0,height() - 1),z,c); } //! Access to a pixel value, using Neumann boundary conditions for the X and Y-coordinates \const. const T& atXY(const int x, const int y, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "atXY(): Empty instance.", cimg_instance); return _atXY(x,y,z,c); } const T& _atXY(const int x, const int y, const int z=0, const int c=0) const { return (*this)(cimg::cut(x,0,width() - 1), cimg::cut(y,0,height() - 1),z,c); } //! Access to a pixel value, using Dirichlet boundary conditions for the X,Y and Z-coordinates. /** Similar to atX(int,int,int,int,const T), except that boundary checking is performed both on X,Y and Z-coordinates. **/ T& atXYZ(const int x, const int y, const int z, const int c, const T& out_value) { return (x<0 || y<0 || z<0 || x>=width() || y>=height() || z>=depth())? (cimg::temporary(out_value)=out_value):(*this)(x,y,z,c); } //! Access to a pixel value, using Dirichlet boundary conditions for the X,Y and Z-coordinates \const. T atXYZ(const int x, const int y, const int z, const int c, const T& out_value) const { return (x<0 || y<0 || z<0 || x>=width() || y>=height() || z>=depth())?out_value:(*this)(x,y,z,c); } //! Access to a pixel value, using Neumann boundary conditions for the X,Y and Z-coordinates. /** Similar to atX(int,int,int,int), except that boundary checking is performed both on X,Y and Z-coordinates. \note - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _atXYZ(int,int,int,int). **/ T& atXYZ(const int x, const int y, const int z, const int c=0) { if (is_empty()) throw CImgInstanceException(_cimg_instance "atXYZ(): Empty instance.", cimg_instance); return _atXYZ(x,y,z,c); } T& _atXYZ(const int x, const int y, const int z, const int c=0) { return (*this)(cimg::cut(x,0,width() - 1), cimg::cut(y,0,height() - 1), cimg::cut(z,0,depth() - 1),c); } //! Access to a pixel value, using Neumann boundary conditions for the X,Y and Z-coordinates \const. const T& atXYZ(const int x, const int y, const int z, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "atXYZ(): Empty instance.", cimg_instance); return _atXYZ(x,y,z,c); } const T& _atXYZ(const int x, const int y, const int z, const int c=0) const { return (*this)(cimg::cut(x,0,width() - 1), cimg::cut(y,0,height() - 1), cimg::cut(z,0,depth() - 1),c); } //! Access to a pixel value, using Dirichlet boundary conditions. /** Similar to atX(int,int,int,int,const T), except that boundary checking is performed on all X,Y,Z and C-coordinates. **/ T& atXYZC(const int x, const int y, const int z, const int c, const T& out_value) { return (x<0 || y<0 || z<0 || c<0 || x>=width() || y>=height() || z>=depth() || c>=spectrum())? (cimg::temporary(out_value)=out_value):(*this)(x,y,z,c); } //! Access to a pixel value, using Dirichlet boundary conditions \const. T atXYZC(const int x, const int y, const int z, const int c, const T& out_value) const { return (x<0 || y<0 || z<0 || c<0 || x>=width() || y>=height() || z>=depth() || c>=spectrum())?out_value: (*this)(x,y,z,c); } //! Access to a pixel value, using Neumann boundary conditions. /** Similar to atX(int,int,int,int), except that boundary checking is performed on all X,Y,Z and C-coordinates. \note - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _atXYZC(int,int,int,int). **/ T& atXYZC(const int x, const int y, const int z, const int c) { if (is_empty()) throw CImgInstanceException(_cimg_instance "atXYZC(): Empty instance.", cimg_instance); return _atXYZC(x,y,z,c); } T& _atXYZC(const int x, const int y, const int z, const int c) { return (*this)(cimg::cut(x,0,width() - 1), cimg::cut(y,0,height() - 1), cimg::cut(z,0,depth() - 1), cimg::cut(c,0,spectrum() - 1)); } //! Access to a pixel value, using Neumann boundary conditions \const. const T& atXYZC(const int x, const int y, const int z, const int c) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "atXYZC(): Empty instance.", cimg_instance); return _atXYZC(x,y,z,c); } const T& _atXYZC(const int x, const int y, const int z, const int c) const { return (*this)(cimg::cut(x,0,width() - 1), cimg::cut(y,0,height() - 1), cimg::cut(z,0,depth() - 1), cimg::cut(c,0,spectrum() - 1)); } //! Return pixel value, using linear interpolation and Dirichlet boundary conditions for the X-coordinate. /** Return a linearly-interpolated pixel value of the image instance located at (\c fx,\c y,\c z,\c c), or a specified default value in case of out-of-bounds access along the X-axis. \param fx X-coordinate of the pixel value (float-valued). \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param out_value Default value returned if \c (\c fx,\c y,\c z,\c c) is outside image bounds. \note - Similar to atX(int,int,int,int,const T), except that the returned pixel value is approximated by a linear interpolation along the X-axis, if corresponding coordinates are not integers. - The type of the returned pixel value is extended to \c float, if the pixel type \c T is not float-valued. \warning - There is \e no boundary checking performed for the Y,Z and C-coordinates, so they must be inside image bounds. **/ Tfloat linear_atX(const float fx, const int y, const int z, const int c, const T& out_value) const { const int x = (int)fx - (fx>=0?0:1), nx = x + 1; const float dx = fx - x; const Tfloat Ic = (Tfloat)atX(x,y,z,c,out_value), In = (Tfloat)atXY(nx,y,z,c,out_value); return Ic + dx*(In - Ic); } //! Return pixel value, using linear interpolation and Neumann boundary conditions for the X-coordinate. /** Return a linearly-interpolated pixel value of the image instance located at (\c fx,\c y,\c z,\c c), or the value of the nearest pixel location in the image instance in case of out-of-bounds access along the X-axis. \param fx X-coordinate of the pixel value (float-valued). \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note - Similar to linear_atX(float,int,int,int,const T) const, except that an out-of-bounds access returns the value of the nearest pixel in the image instance, regarding the specified X-coordinate. - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _linear_atX(float,int,int,int). \warning - There is \e no boundary checking performed for the Y,Z and C-coordinates, so they must be inside image bounds. **/ Tfloat linear_atX(const float fx, const int y=0, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "linear_atX(): Empty instance.", cimg_instance); return _linear_atX(fx,y,z,c); } Tfloat _linear_atX(const float fx, const int y=0, const int z=0, const int c=0) const { const float nfx = cimg::cut(fx,0,width() - 1); const unsigned int x = (unsigned int)nfx; const float dx = nfx - x; const unsigned int nx = dx>0?x + 1:x; const Tfloat Ic = (Tfloat)(*this)(x,y,z,c), In = (Tfloat)(*this)(nx,y,z,c); return Ic + dx*(In - Ic); } //! Return pixel value, using linear interpolation and periodic boundary conditions for the X-coordinate. Tfloat linear_atX_p(const float fx, const int y=0, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "linear_atX_p(): Empty instance.", cimg_instance); return _linear_atX_p(fx,y,z,c); } Tfloat _linear_atX_p(const float fx, const int y=0, const int z=0, const int c=0) const { const float nfx = cimg::mod(fx,(float)_width); const unsigned int x = (unsigned int)nfx; const float dx = nfx - x; const unsigned int nx = cimg::mod(x + 1,_width); const Tfloat Ic = (Tfloat)(*this)(x,y,z,c), In = (Tfloat)(*this)(nx,y,z,c); return Ic + dx*(In - Ic); } //! Return pixel value, using linear interpolation and Dirichlet boundary conditions for the X and Y-coordinates. /** Similar to linear_atX(float,int,int,int,const T) const, except that the linear interpolation and the boundary checking are achieved both for X and Y-coordinates. **/ Tfloat linear_atXY(const float fx, const float fy, const int z, const int c, const T& out_value) const { const int x = (int)fx - (fx>=0?0:1), nx = x + 1, y = (int)fy - (fy>=0?0:1), ny = y + 1; const float dx = fx - x, dy = fy - y; const Tfloat Icc = (Tfloat)atXY(x,y,z,c,out_value), Inc = (Tfloat)atXY(nx,y,z,c,out_value), Icn = (Tfloat)atXY(x,ny,z,c,out_value), Inn = (Tfloat)atXY(nx,ny,z,c,out_value); return Icc + dx*(Inc - Icc + dy*(Icc + Inn - Icn - Inc)) + dy*(Icn - Icc); } //! Return pixel value, using linear interpolation and Neumann boundary conditions for the X and Y-coordinates. /** Similar to linear_atX(float,int,int,int) const, except that the linear interpolation and the boundary checking are achieved both for X and Y-coordinates. \note - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _linear_atXY(float,float,int,int). **/ Tfloat linear_atXY(const float fx, const float fy, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "linear_atXY(): Empty instance.", cimg_instance); return _linear_atXY(fx,fy,z,c); } Tfloat _linear_atXY(const float fx, const float fy, const int z=0, const int c=0) const { const float nfx = cimg::cut(fx,0,width() - 1), nfy = cimg::cut(fy,0,height() - 1); const unsigned int x = (unsigned int)nfx, y = (unsigned int)nfy; const float dx = nfx - x, dy = nfy - y; const unsigned int nx = dx>0?x + 1:x, ny = dy>0?y + 1:y; const Tfloat Icc = (Tfloat)(*this)(x,y,z,c), Inc = (Tfloat)(*this)(nx,y,z,c), Icn = (Tfloat)(*this)(x,ny,z,c), Inn = (Tfloat)(*this)(nx,ny,z,c); return Icc + dx*(Inc - Icc + dy*(Icc + Inn - Icn - Inc)) + dy*(Icn - Icc); } //! Return pixel value, using linear interpolation and periodic boundary conditions for the X and Y-coordinates. Tfloat linear_atXY_p(const float fx, const float fy, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "linear_atXY_p(): Empty instance.", cimg_instance); return _linear_atXY_p(fx,fy,z,c); } Tfloat _linear_atXY_p(const float fx, const float fy, const int z=0, const int c=0) const { const float nfx = cimg::mod(fx,(float)_width), nfy = cimg::mod(fy,(float)_height); const unsigned int x = (unsigned int)nfx, y = (unsigned int)nfy; const float dx = nfx - x, dy = nfy - y; const unsigned int nx = cimg::mod(x + 1,_width), ny = cimg::mod(y + 1,_height); const Tfloat Icc = (Tfloat)(*this)(x,y,z,c), Inc = (Tfloat)(*this)(nx,y,z,c), Icn = (Tfloat)(*this)(x,ny,z,c), Inn = (Tfloat)(*this)(nx,ny,z,c); return Icc + dx*(Inc - Icc + dy*(Icc + Inn - Icn - Inc)) + dy*(Icn - Icc); } //! Return pixel value, using linear interpolation and Dirichlet boundary conditions for the X,Y and Z-coordinates. /** Similar to linear_atX(float,int,int,int,const T) const, except that the linear interpolation and the boundary checking are achieved both for X,Y and Z-coordinates. **/ Tfloat linear_atXYZ(const float fx, const float fy, const float fz, const int c, const T& out_value) const { const int x = (int)fx - (fx>=0?0:1), nx = x + 1, y = (int)fy - (fy>=0?0:1), ny = y + 1, z = (int)fz - (fz>=0?0:1), nz = z + 1; const float dx = fx - x, dy = fy - y, dz = fz - z; const Tfloat Iccc = (Tfloat)atXYZ(x,y,z,c,out_value), Incc = (Tfloat)atXYZ(nx,y,z,c,out_value), Icnc = (Tfloat)atXYZ(x,ny,z,c,out_value), Innc = (Tfloat)atXYZ(nx,ny,z,c,out_value), Iccn = (Tfloat)atXYZ(x,y,nz,c,out_value), Incn = (Tfloat)atXYZ(nx,y,nz,c,out_value), Icnn = (Tfloat)atXYZ(x,ny,nz,c,out_value), Innn = (Tfloat)atXYZ(nx,ny,nz,c,out_value); return Iccc + dx*(Incc - Iccc + dy*(Iccc + Innc - Icnc - Incc + dz*(Iccn + Innn + Icnc + Incc - Icnn - Incn - Iccc - Innc)) + dz*(Iccc + Incn - Iccn - Incc)) + dy*(Icnc - Iccc + dz*(Iccc + Icnn - Iccn - Icnc)) + dz*(Iccn - Iccc); } //! Return pixel value, using linear interpolation and Neumann boundary conditions for the X,Y and Z-coordinates. /** Similar to linear_atX(float,int,int,int) const, except that the linear interpolation and the boundary checking are achieved both for X,Y and Z-coordinates. \note - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _linear_atXYZ(float,float,float,int). **/ Tfloat linear_atXYZ(const float fx, const float fy=0, const float fz=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "linear_atXYZ(): Empty instance.", cimg_instance); return _linear_atXYZ(fx,fy,fz,c); } Tfloat _linear_atXYZ(const float fx, const float fy=0, const float fz=0, const int c=0) const { const float nfx = cimg::cut(fx,0,width() - 1), nfy = cimg::cut(fy,0,height() - 1), nfz = cimg::cut(fz,0,depth() - 1); const unsigned int x = (unsigned int)nfx, y = (unsigned int)nfy, z = (unsigned int)nfz; const float dx = nfx - x, dy = nfy - y, dz = nfz - z; const unsigned int nx = dx>0?x + 1:x, ny = dy>0?y + 1:y, nz = dz>0?z + 1:z; const Tfloat Iccc = (Tfloat)(*this)(x,y,z,c), Incc = (Tfloat)(*this)(nx,y,z,c), Icnc = (Tfloat)(*this)(x,ny,z,c), Innc = (Tfloat)(*this)(nx,ny,z,c), Iccn = (Tfloat)(*this)(x,y,nz,c), Incn = (Tfloat)(*this)(nx,y,nz,c), Icnn = (Tfloat)(*this)(x,ny,nz,c), Innn = (Tfloat)(*this)(nx,ny,nz,c); return Iccc + dx*(Incc - Iccc + dy*(Iccc + Innc - Icnc - Incc + dz*(Iccn + Innn + Icnc + Incc - Icnn - Incn - Iccc - Innc)) + dz*(Iccc + Incn - Iccn - Incc)) + dy*(Icnc - Iccc + dz*(Iccc + Icnn - Iccn - Icnc)) + dz*(Iccn - Iccc); } //! Return pixel value, using linear interpolation and periodic boundary conditions for the X,Y and Z-coordinates. Tfloat linear_atXYZ_p(const float fx, const float fy=0, const float fz=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "linear_atXYZ_p(): Empty instance.", cimg_instance); return _linear_atXYZ_p(fx,fy,fz,c); } Tfloat _linear_atXYZ_p(const float fx, const float fy=0, const float fz=0, const int c=0) const { const float nfx = cimg::mod(fx,(float)_width), nfy = cimg::mod(fy,(float)_height), nfz = cimg::mod(fz,(float)_depth); const unsigned int x = (unsigned int)nfx, y = (unsigned int)nfy, z = (unsigned int)nfz; const float dx = nfx - x, dy = nfy - y, dz = nfz - z; const unsigned int nx = cimg::mod(x + 1,_width), ny = cimg::mod(y + 1,_height), nz = cimg::mod(z + 1,_depth); const Tfloat Iccc = (Tfloat)(*this)(x,y,z,c), Incc = (Tfloat)(*this)(nx,y,z,c), Icnc = (Tfloat)(*this)(x,ny,z,c), Innc = (Tfloat)(*this)(nx,ny,z,c), Iccn = (Tfloat)(*this)(x,y,nz,c), Incn = (Tfloat)(*this)(nx,y,nz,c), Icnn = (Tfloat)(*this)(x,ny,nz,c), Innn = (Tfloat)(*this)(nx,ny,nz,c); return Iccc + dx*(Incc - Iccc + dy*(Iccc + Innc - Icnc - Incc + dz*(Iccn + Innn + Icnc + Incc - Icnn - Incn - Iccc - Innc)) + dz*(Iccc + Incn - Iccn - Incc)) + dy*(Icnc - Iccc + dz*(Iccc + Icnn - Iccn - Icnc)) + dz*(Iccn - Iccc); } //! Return pixel value, using linear interpolation and Dirichlet boundary conditions for all X,Y,Z,C-coordinates. /** Similar to linear_atX(float,int,int,int,const T) const, except that the linear interpolation and the boundary checking are achieved for all X,Y,Z and C-coordinates. **/ Tfloat linear_atXYZC(const float fx, const float fy, const float fz, const float fc, const T& out_value) const { const int x = (int)fx - (fx>=0?0:1), nx = x + 1, y = (int)fy - (fy>=0?0:1), ny = y + 1, z = (int)fz - (fz>=0?0:1), nz = z + 1, c = (int)fc - (fc>=0?0:1), nc = c + 1; const float dx = fx - x, dy = fy - y, dz = fz - z, dc = fc - c; const Tfloat Icccc = (Tfloat)atXYZC(x,y,z,c,out_value), Inccc = (Tfloat)atXYZC(nx,y,z,c,out_value), Icncc = (Tfloat)atXYZC(x,ny,z,c,out_value), Inncc = (Tfloat)atXYZC(nx,ny,z,c,out_value), Iccnc = (Tfloat)atXYZC(x,y,nz,c,out_value), Incnc = (Tfloat)atXYZC(nx,y,nz,c,out_value), Icnnc = (Tfloat)atXYZC(x,ny,nz,c,out_value), Innnc = (Tfloat)atXYZC(nx,ny,nz,c,out_value), Icccn = (Tfloat)atXYZC(x,y,z,nc,out_value), Inccn = (Tfloat)atXYZC(nx,y,z,nc,out_value), Icncn = (Tfloat)atXYZC(x,ny,z,nc,out_value), Inncn = (Tfloat)atXYZC(nx,ny,z,nc,out_value), Iccnn = (Tfloat)atXYZC(x,y,nz,nc,out_value), Incnn = (Tfloat)atXYZC(nx,y,nz,nc,out_value), Icnnn = (Tfloat)atXYZC(x,ny,nz,nc,out_value), Innnn = (Tfloat)atXYZC(nx,ny,nz,nc,out_value); return Icccc + dx*(Inccc - Icccc + dy*(Icccc + Inncc - Icncc - Inccc + dz*(Iccnc + Innnc + Icncc + Inccc - Icnnc - Incnc - Icccc - Inncc + dc*(Iccnn + Innnn + Icncn + Inccn + Icnnc + Incnc + Icccc + Inncc - Icnnn - Incnn - Icccn - Inncn - Iccnc - Innnc - Icncc - Inccc)) + dc*(Icccn + Inncn + Icncc + Inccc - Icncn - Inccn - Icccc - Inncc)) + dz*(Icccc + Incnc - Iccnc - Inccc + dc*(Icccn + Incnn + Iccnc + Inccc - Iccnn - Inccn - Icccc - Incnc)) + dc*(Icccc + Inccn - Inccc - Icccn)) + dy*(Icncc - Icccc + dz*(Icccc + Icnnc - Iccnc - Icncc + dc*(Icccn + Icnnn + Iccnc + Icncc - Iccnn - Icncn - Icccc - Icnnc)) + dc*(Icccc + Icncn - Icncc - Icccn)) + dz*(Iccnc - Icccc + dc*(Icccc + Iccnn - Iccnc - Icccn)) + dc*(Icccn -Icccc); } //! Return pixel value, using linear interpolation and Neumann boundary conditions for all X,Y,Z and C-coordinates. /** Similar to linear_atX(float,int,int,int) const, except that the linear interpolation and the boundary checking are achieved for all X,Y,Z and C-coordinates. \note - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _linear_atXYZC(float,float,float,float). **/ Tfloat linear_atXYZC(const float fx, const float fy=0, const float fz=0, const float fc=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "linear_atXYZC(): Empty instance.", cimg_instance); return _linear_atXYZC(fx,fy,fz,fc); } Tfloat _linear_atXYZC(const float fx, const float fy=0, const float fz=0, const float fc=0) const { const float nfx = cimg::cut(fx,0,width() - 1), nfy = cimg::cut(fy,0,height() - 1), nfz = cimg::cut(fz,0,depth() - 1), nfc = cimg::cut(fc,0,spectrum() - 1); const unsigned int x = (unsigned int)nfx, y = (unsigned int)nfy, z = (unsigned int)nfz, c = (unsigned int)nfc; const float dx = nfx - x, dy = nfy - y, dz = nfz - z, dc = nfc - c; const unsigned int nx = dx>0?x + 1:x, ny = dy>0?y + 1:y, nz = dz>0?z + 1:z, nc = dc>0?c + 1:c; const Tfloat Icccc = (Tfloat)(*this)(x,y,z,c), Inccc = (Tfloat)(*this)(nx,y,z,c), Icncc = (Tfloat)(*this)(x,ny,z,c), Inncc = (Tfloat)(*this)(nx,ny,z,c), Iccnc = (Tfloat)(*this)(x,y,nz,c), Incnc = (Tfloat)(*this)(nx,y,nz,c), Icnnc = (Tfloat)(*this)(x,ny,nz,c), Innnc = (Tfloat)(*this)(nx,ny,nz,c), Icccn = (Tfloat)(*this)(x,y,z,nc), Inccn = (Tfloat)(*this)(nx,y,z,nc), Icncn = (Tfloat)(*this)(x,ny,z,nc), Inncn = (Tfloat)(*this)(nx,ny,z,nc), Iccnn = (Tfloat)(*this)(x,y,nz,nc), Incnn = (Tfloat)(*this)(nx,y,nz,nc), Icnnn = (Tfloat)(*this)(x,ny,nz,nc), Innnn = (Tfloat)(*this)(nx,ny,nz,nc); return Icccc + dx*(Inccc - Icccc + dy*(Icccc + Inncc - Icncc - Inccc + dz*(Iccnc + Innnc + Icncc + Inccc - Icnnc - Incnc - Icccc - Inncc + dc*(Iccnn + Innnn + Icncn + Inccn + Icnnc + Incnc + Icccc + Inncc - Icnnn - Incnn - Icccn - Inncn - Iccnc - Innnc - Icncc - Inccc)) + dc*(Icccn + Inncn + Icncc + Inccc - Icncn - Inccn - Icccc - Inncc)) + dz*(Icccc + Incnc - Iccnc - Inccc + dc*(Icccn + Incnn + Iccnc + Inccc - Iccnn - Inccn - Icccc - Incnc)) + dc*(Icccc + Inccn - Inccc - Icccn)) + dy*(Icncc - Icccc + dz*(Icccc + Icnnc - Iccnc - Icncc + dc*(Icccn + Icnnn + Iccnc + Icncc - Iccnn - Icncn - Icccc - Icnnc)) + dc*(Icccc + Icncn - Icncc - Icccn)) + dz*(Iccnc - Icccc + dc*(Icccc + Iccnn - Iccnc - Icccn)) + dc*(Icccn - Icccc); } //! Return pixel value, using linear interpolation and periodic boundary conditions for all X,Y,Z and C-coordinates. Tfloat linear_atXYZC_p(const float fx, const float fy=0, const float fz=0, const float fc=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "linear_atXYZC_p(): Empty instance.", cimg_instance); return _linear_atXYZC_p(fx,fy,fz,fc); } Tfloat _linear_atXYZC_p(const float fx, const float fy=0, const float fz=0, const float fc=0) const { const float nfx = cimg::mod(fx,(float)_width), nfy = cimg::mod(fy,(float)_height), nfz = cimg::mod(fz,(float)_depth), nfc = cimg::mod(fc,(float)_spectrum); const unsigned int x = (unsigned int)nfx, y = (unsigned int)nfy, z = (unsigned int)nfz, c = (unsigned int)nfc; const float dx = nfx - x, dy = nfy - y, dz = nfz - z, dc = nfc - c; const unsigned int nx = cimg::mod(x + 1,_width), ny = cimg::mod(y + 1,_height), nz = cimg::mod(z + 1,_depth), nc = cimg::mod(c + 1,_spectrum); const Tfloat Icccc = (Tfloat)(*this)(x,y,z,c), Inccc = (Tfloat)(*this)(nx,y,z,c), Icncc = (Tfloat)(*this)(x,ny,z,c), Inncc = (Tfloat)(*this)(nx,ny,z,c), Iccnc = (Tfloat)(*this)(x,y,nz,c), Incnc = (Tfloat)(*this)(nx,y,nz,c), Icnnc = (Tfloat)(*this)(x,ny,nz,c), Innnc = (Tfloat)(*this)(nx,ny,nz,c), Icccn = (Tfloat)(*this)(x,y,z,nc), Inccn = (Tfloat)(*this)(nx,y,z,nc), Icncn = (Tfloat)(*this)(x,ny,z,nc), Inncn = (Tfloat)(*this)(nx,ny,z,nc), Iccnn = (Tfloat)(*this)(x,y,nz,nc), Incnn = (Tfloat)(*this)(nx,y,nz,nc), Icnnn = (Tfloat)(*this)(x,ny,nz,nc), Innnn = (Tfloat)(*this)(nx,ny,nz,nc); return Icccc + dx*(Inccc - Icccc + dy*(Icccc + Inncc - Icncc - Inccc + dz*(Iccnc + Innnc + Icncc + Inccc - Icnnc - Incnc - Icccc - Inncc + dc*(Iccnn + Innnn + Icncn + Inccn + Icnnc + Incnc + Icccc + Inncc - Icnnn - Incnn - Icccn - Inncn - Iccnc - Innnc - Icncc - Inccc)) + dc*(Icccn + Inncn + Icncc + Inccc - Icncn - Inccn - Icccc - Inncc)) + dz*(Icccc + Incnc - Iccnc - Inccc + dc*(Icccn + Incnn + Iccnc + Inccc - Iccnn - Inccn - Icccc - Incnc)) + dc*(Icccc + Inccn - Inccc - Icccn)) + dy*(Icncc - Icccc + dz*(Icccc + Icnnc - Iccnc - Icncc + dc*(Icccn + Icnnn + Iccnc + Icncc - Iccnn - Icncn - Icccc - Icnnc)) + dc*(Icccc + Icncn - Icncc - Icccn)) + dz*(Iccnc - Icccc + dc*(Icccc + Iccnn - Iccnc - Icccn)) + dc*(Icccn - Icccc); } //! Return pixel value, using cubic interpolation and Dirichlet boundary conditions for the X-coordinate. /** Return a cubicly-interpolated pixel value of the image instance located at (\c fx,\c y,\c z,\c c), or a specified default value in case of out-of-bounds access along the X-axis. The cubic interpolation uses Hermite splines. \param fx d X-coordinate of the pixel value (float-valued). \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param out_value Default value returned if \c (\c fx,\c y,\c z,\c c) is outside image bounds. \note - Similar to linear_atX(float,int,int,int,const T) const, except that the returned pixel value is approximated by a \e cubic interpolation along the X-axis. - The type of the returned pixel value is extended to \c float, if the pixel type \c T is not float-valued. \warning - There is \e no boundary checking performed for the Y,Z and C-coordinates, so they must be inside image bounds. **/ Tfloat cubic_atX(const float fx, const int y, const int z, const int c, const T& out_value) const { const int x = (int)fx - (fx>=0?0:1), px = x - 1, nx = x + 1, ax = x + 2; const float dx = fx - x; const Tfloat Ip = (Tfloat)atX(px,y,z,c,out_value), Ic = (Tfloat)atX(x,y,z,c,out_value), In = (Tfloat)atX(nx,y,z,c,out_value), Ia = (Tfloat)atX(ax,y,z,c,out_value); return Ic + 0.5f*(dx*(-Ip + In) + dx*dx*(2*Ip - 5*Ic + 4*In - Ia) + dx*dx*dx*(-Ip + 3*Ic - 3*In + Ia)); } //! Return clamped pixel value, using cubic interpolation and Dirichlet boundary conditions for the X-coordinate. /** Similar to cubic_atX(float,int,int,int,const T) const, except that the return value is clamped to stay in the min/max range of the datatype \c T. **/ T cubic_atX_c(const float fx, const int y, const int z, const int c, const T& out_value) const { return cimg::type<T>::cut(cubic_atX(fx,y,z,c,out_value)); } //! Return pixel value, using cubic interpolation and Neumann boundary conditions for the X-coordinate. /** Return a cubicly-interpolated pixel value of the image instance located at (\c fx,\c y,\c z,\c c), or the value of the nearest pixel location in the image instance in case of out-of-bounds access along the X-axis. The cubic interpolation uses Hermite splines. \param fx X-coordinate of the pixel value (float-valued). \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note - Similar to cubic_atX(float,int,int,int,const T) const, except that the returned pixel value is approximated by a cubic interpolation along the X-axis. - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _cubic_atX(float,int,int,int). \warning - There is \e no boundary checking performed for the Y,Z and C-coordinates, so they must be inside image bounds. **/ Tfloat cubic_atX(const float fx, const int y=0, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "cubic_atX(): Empty instance.", cimg_instance); return _cubic_atX(fx,y,z,c); } Tfloat _cubic_atX(const float fx, const int y=0, const int z=0, const int c=0) const { const float nfx = cimg::type<float>::is_nan(fx)?0:cimg::cut(fx,0,width() - 1); const int x = (int)nfx; const float dx = nfx - x; const int px = x - 1<0?0:x - 1, nx = dx>0?x + 1:x, ax = x + 2>=width()?width() - 1:x + 2; const Tfloat Ip = (Tfloat)(*this)(px,y,z,c), Ic = (Tfloat)(*this)(x,y,z,c), In = (Tfloat)(*this)(nx,y,z,c), Ia = (Tfloat)(*this)(ax,y,z,c); return Ic + 0.5f*(dx*(-Ip + In) + dx*dx*(2*Ip - 5*Ic + 4*In - Ia) + dx*dx*dx*(-Ip + 3*Ic - 3*In + Ia)); } //! Return clamped pixel value, using cubic interpolation and Neumann boundary conditions for the X-coordinate. /** Similar to cubic_atX(float,int,int,int) const, except that the return value is clamped to stay in the min/max range of the datatype \c T. **/ T cubic_atX_c(const float fx, const int y, const int z, const int c) const { return cimg::type<T>::cut(cubic_atX(fx,y,z,c)); } T _cubic_atX_c(const float fx, const int y, const int z, const int c) const { return cimg::type<T>::cut(_cubic_atX(fx,y,z,c)); } //! Return pixel value, using cubic interpolation and periodic boundary conditions for the X-coordinate. Tfloat cubic_atX_p(const float fx, const int y=0, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "cubic_atX_p(): Empty instance.", cimg_instance); return _cubic_atX_p(fx,y,z,c); } Tfloat _cubic_atX_p(const float fx, const int y=0, const int z=0, const int c=0) const { const float nfx = cimg::type<float>::is_nan(fx)?0:cimg::mod(fx,(float)_width); const int x = (int)nfx; const float dx = nfx - x; const int px = cimg::mod(x - 1,width()), nx = cimg::mod(x + 1,width()), ax = cimg::mod(x + 2,width()); const Tfloat Ip = (Tfloat)(*this)(px,y,z,c), Ic = (Tfloat)(*this)(x,y,z,c), In = (Tfloat)(*this)(nx,y,z,c), Ia = (Tfloat)(*this)(ax,y,z,c); return Ic + 0.5f*(dx*(-Ip + In) + dx*dx*(2*Ip - 5*Ic + 4*In - Ia) + dx*dx*dx*(-Ip + 3*Ic - 3*In + Ia)); } T cubic_atX_pc(const float fx, const int y, const int z, const int c) const { return cimg::type<T>::cut(cubic_atX_p(fx,y,z,c)); } T _cubic_atX_pc(const float fx, const int y, const int z, const int c) const { return cimg::type<T>::cut(_cubic_atX_p(fx,y,z,c)); } //! Return pixel value, using cubic interpolation and Dirichlet boundary conditions for the X and Y-coordinates. /** Similar to cubic_atX(float,int,int,int,const T) const, except that the cubic interpolation and boundary checking are achieved both for X and Y-coordinates. **/ Tfloat cubic_atXY(const float fx, const float fy, const int z, const int c, const T& out_value) const { const int x = (int)fx - (fx>=0?0:1), px = x - 1, nx = x + 1, ax = x + 2, y = (int)fy - (fy>=0?0:1), py = y - 1, ny = y + 1, ay = y + 2; const float dx = fx - x, dy = fy - y; const Tfloat Ipp = (Tfloat)atXY(px,py,z,c,out_value), Icp = (Tfloat)atXY(x,py,z,c,out_value), Inp = (Tfloat)atXY(nx,py,z,c,out_value), Iap = (Tfloat)atXY(ax,py,z,c,out_value), Ip = Icp + 0.5f*(dx*(-Ipp + Inp) + dx*dx*(2*Ipp - 5*Icp + 4*Inp - Iap) + dx*dx*dx*(-Ipp + 3*Icp - 3*Inp + Iap)), Ipc = (Tfloat)atXY(px,y,z,c,out_value), Icc = (Tfloat)atXY(x, y,z,c,out_value), Inc = (Tfloat)atXY(nx,y,z,c,out_value), Iac = (Tfloat)atXY(ax,y,z,c,out_value), Ic = Icc + 0.5f*(dx*(-Ipc + Inc) + dx*dx*(2*Ipc - 5*Icc + 4*Inc - Iac) + dx*dx*dx*(-Ipc + 3*Icc - 3*Inc + Iac)), Ipn = (Tfloat)atXY(px,ny,z,c,out_value), Icn = (Tfloat)atXY(x,ny,z,c,out_value), Inn = (Tfloat)atXY(nx,ny,z,c,out_value), Ian = (Tfloat)atXY(ax,ny,z,c,out_value), In = Icn + 0.5f*(dx*(-Ipn + Inn) + dx*dx*(2*Ipn - 5*Icn + 4*Inn - Ian) + dx*dx*dx*(-Ipn + 3*Icn - 3*Inn + Ian)), Ipa = (Tfloat)atXY(px,ay,z,c,out_value), Ica = (Tfloat)atXY(x,ay,z,c,out_value), Ina = (Tfloat)atXY(nx,ay,z,c,out_value), Iaa = (Tfloat)atXY(ax,ay,z,c,out_value), Ia = Ica + 0.5f*(dx*(-Ipa + Ina) + dx*dx*(2*Ipa - 5*Ica + 4*Ina - Iaa) + dx*dx*dx*(-Ipa + 3*Ica - 3*Ina + Iaa)); return Ic + 0.5f*(dy*(-Ip + In) + dy*dy*(2*Ip - 5*Ic + 4*In - Ia) + dy*dy*dy*(-Ip + 3*Ic - 3*In + Ia)); } //! Return clamped pixel value, using cubic interpolation and Dirichlet boundary conditions for the X,Y-coordinates. /** Similar to cubic_atXY(float,float,int,int,const T) const, except that the return value is clamped to stay in the min/max range of the datatype \c T. **/ T cubic_atXY_c(const float fx, const float fy, const int z, const int c, const T& out_value) const { return cimg::type<T>::cut(cubic_atXY(fx,fy,z,c,out_value)); } //! Return pixel value, using cubic interpolation and Neumann boundary conditions for the X and Y-coordinates. /** Similar to cubic_atX(float,int,int,int) const, except that the cubic interpolation and boundary checking are achieved for both X and Y-coordinates. \note - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _cubic_atXY(float,float,int,int). **/ Tfloat cubic_atXY(const float fx, const float fy, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "cubic_atXY(): Empty instance.", cimg_instance); return _cubic_atXY(fx,fy,z,c); } Tfloat _cubic_atXY(const float fx, const float fy, const int z=0, const int c=0) const { const float nfx = cimg::type<float>::is_nan(fx)?0:cimg::cut(fx,0,width() - 1), nfy = cimg::type<float>::is_nan(fy)?0:cimg::cut(fy,0,height() - 1); const int x = (int)nfx, y = (int)nfy; const float dx = nfx - x, dy = nfy - y; const int px = x - 1<0?0:x - 1, nx = dx<=0?x:x + 1, ax = x + 2>=width()?width() - 1:x + 2, py = y - 1<0?0:y - 1, ny = dy<=0?y:y + 1, ay = y + 2>=height()?height() - 1:y + 2; const Tfloat Ipp = (Tfloat)(*this)(px,py,z,c), Icp = (Tfloat)(*this)(x,py,z,c), Inp = (Tfloat)(*this)(nx,py,z,c), Iap = (Tfloat)(*this)(ax,py,z,c), Ip = Icp + 0.5f*(dx*(-Ipp + Inp) + dx*dx*(2*Ipp - 5*Icp + 4*Inp - Iap) + dx*dx*dx*(-Ipp + 3*Icp - 3*Inp + Iap)), Ipc = (Tfloat)(*this)(px,y,z,c), Icc = (Tfloat)(*this)(x, y,z,c), Inc = (Tfloat)(*this)(nx,y,z,c), Iac = (Tfloat)(*this)(ax,y,z,c), Ic = Icc + 0.5f*(dx*(-Ipc + Inc) + dx*dx*(2*Ipc - 5*Icc + 4*Inc - Iac) + dx*dx*dx*(-Ipc + 3*Icc - 3*Inc + Iac)), Ipn = (Tfloat)(*this)(px,ny,z,c), Icn = (Tfloat)(*this)(x,ny,z,c), Inn = (Tfloat)(*this)(nx,ny,z,c), Ian = (Tfloat)(*this)(ax,ny,z,c), In = Icn + 0.5f*(dx*(-Ipn + Inn) + dx*dx*(2*Ipn - 5*Icn + 4*Inn - Ian) + dx*dx*dx*(-Ipn + 3*Icn - 3*Inn + Ian)), Ipa = (Tfloat)(*this)(px,ay,z,c), Ica = (Tfloat)(*this)(x,ay,z,c), Ina = (Tfloat)(*this)(nx,ay,z,c), Iaa = (Tfloat)(*this)(ax,ay,z,c), Ia = Ica + 0.5f*(dx*(-Ipa + Ina) + dx*dx*(2*Ipa - 5*Ica + 4*Ina - Iaa) + dx*dx*dx*(-Ipa + 3*Ica - 3*Ina + Iaa)); return Ic + 0.5f*(dy*(-Ip + In) + dy*dy*(2*Ip - 5*Ic + 4*In - Ia) + dy*dy*dy*(-Ip + 3*Ic - 3*In + Ia)); } //! Return clamped pixel value, using cubic interpolation and Neumann boundary conditions for the X,Y-coordinates. /** Similar to cubic_atXY(float,float,int,int) const, except that the return value is clamped to stay in the min/max range of the datatype \c T. **/ T cubic_atXY_c(const float fx, const float fy, const int z, const int c) const { return cimg::type<T>::cut(cubic_atXY(fx,fy,z,c)); } T _cubic_atXY_c(const float fx, const float fy, const int z, const int c) const { return cimg::type<T>::cut(_cubic_atXY(fx,fy,z,c)); } //! Return pixel value, using cubic interpolation and mirror boundary conditions for the X and Y-coordinates. Tfloat cubic_atXY_p(const float fx, const float fy, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "cubic_atXY_p(): Empty instance.", cimg_instance); return _cubic_atXY_p(fx,fy,z,c); } Tfloat _cubic_atXY_p(const float fx, const float fy, const int z=0, const int c=0) const { const float nfx = cimg::type<float>::is_nan(fx)?0:cimg::mod(fx,(float)_width), nfy = cimg::type<float>::is_nan(fy)?0:cimg::mod(fy,(float)_height); const int x = (int)nfx, y = (int)nfy; const float dx = nfx - x, dy = nfy - y; const int px = cimg::mod(x - 1,width()), nx = cimg::mod(x + 1,width()), ax = cimg::mod(x + 2,width()), py = cimg::mod(y - 1,height()), ny = cimg::mod(y + 1,height()), ay = cimg::mod(y + 2,height()); const Tfloat Ipp = (Tfloat)(*this)(px,py,z,c), Icp = (Tfloat)(*this)(x,py,z,c), Inp = (Tfloat)(*this)(nx,py,z,c), Iap = (Tfloat)(*this)(ax,py,z,c), Ip = Icp + 0.5f*(dx*(-Ipp + Inp) + dx*dx*(2*Ipp - 5*Icp + 4*Inp - Iap) + dx*dx*dx*(-Ipp + 3*Icp - 3*Inp + Iap)), Ipc = (Tfloat)(*this)(px,y,z,c), Icc = (Tfloat)(*this)(x, y,z,c), Inc = (Tfloat)(*this)(nx,y,z,c), Iac = (Tfloat)(*this)(ax,y,z,c), Ic = Icc + 0.5f*(dx*(-Ipc + Inc) + dx*dx*(2*Ipc - 5*Icc + 4*Inc - Iac) + dx*dx*dx*(-Ipc + 3*Icc - 3*Inc + Iac)), Ipn = (Tfloat)(*this)(px,ny,z,c), Icn = (Tfloat)(*this)(x,ny,z,c), Inn = (Tfloat)(*this)(nx,ny,z,c), Ian = (Tfloat)(*this)(ax,ny,z,c), In = Icn + 0.5f*(dx*(-Ipn + Inn) + dx*dx*(2*Ipn - 5*Icn + 4*Inn - Ian) + dx*dx*dx*(-Ipn + 3*Icn - 3*Inn + Ian)), Ipa = (Tfloat)(*this)(px,ay,z,c), Ica = (Tfloat)(*this)(x,ay,z,c), Ina = (Tfloat)(*this)(nx,ay,z,c), Iaa = (Tfloat)(*this)(ax,ay,z,c), Ia = Ica + 0.5f*(dx*(-Ipa + Ina) + dx*dx*(2*Ipa - 5*Ica + 4*Ina - Iaa) + dx*dx*dx*(-Ipa + 3*Ica - 3*Ina + Iaa)); return Ic + 0.5f*(dy*(-Ip + In) + dy*dy*(2*Ip - 5*Ic + 4*In - Ia) + dy*dy*dy*(-Ip + 3*Ic - 3*In + Ia)); } T cubic_atXY_pc(const float fx, const float fy, const int z, const int c) const { return cimg::type<T>::cut(cubic_atXY_p(fx,fy,z,c)); } T _cubic_atXY_pc(const float fx, const float fy, const int z, const int c) const { return cimg::type<T>::cut(_cubic_atXY_p(fx,fy,z,c)); } //! Return pixel value, using cubic interpolation and Dirichlet boundary conditions for the X,Y and Z-coordinates. /** Similar to cubic_atX(float,int,int,int,const T) const, except that the cubic interpolation and boundary checking are achieved both for X,Y and Z-coordinates. **/ Tfloat cubic_atXYZ(const float fx, const float fy, const float fz, const int c, const T& out_value) const { const int x = (int)fx - (fx>=0?0:1), px = x - 1, nx = x + 1, ax = x + 2, y = (int)fy - (fy>=0?0:1), py = y - 1, ny = y + 1, ay = y + 2, z = (int)fz - (fz>=0?0:1), pz = z - 1, nz = z + 1, az = z + 2; const float dx = fx - x, dy = fy - y, dz = fz - z; const Tfloat Ippp = (Tfloat)atXYZ(px,py,pz,c,out_value), Icpp = (Tfloat)atXYZ(x,py,pz,c,out_value), Inpp = (Tfloat)atXYZ(nx,py,pz,c,out_value), Iapp = (Tfloat)atXYZ(ax,py,pz,c,out_value), Ipp = Icpp + 0.5f*(dx*(-Ippp + Inpp) + dx*dx*(2*Ippp - 5*Icpp + 4*Inpp - Iapp) + dx*dx*dx*(-Ippp + 3*Icpp - 3*Inpp + Iapp)), Ipcp = (Tfloat)atXYZ(px,y,pz,c,out_value), Iccp = (Tfloat)atXYZ(x, y,pz,c,out_value), Incp = (Tfloat)atXYZ(nx,y,pz,c,out_value), Iacp = (Tfloat)atXYZ(ax,y,pz,c,out_value), Icp = Iccp + 0.5f*(dx*(-Ipcp + Incp) + dx*dx*(2*Ipcp - 5*Iccp + 4*Incp - Iacp) + dx*dx*dx*(-Ipcp + 3*Iccp - 3*Incp + Iacp)), Ipnp = (Tfloat)atXYZ(px,ny,pz,c,out_value), Icnp = (Tfloat)atXYZ(x,ny,pz,c,out_value), Innp = (Tfloat)atXYZ(nx,ny,pz,c,out_value), Ianp = (Tfloat)atXYZ(ax,ny,pz,c,out_value), Inp = Icnp + 0.5f*(dx*(-Ipnp + Innp) + dx*dx*(2*Ipnp - 5*Icnp + 4*Innp - Ianp) + dx*dx*dx*(-Ipnp + 3*Icnp - 3*Innp + Ianp)), Ipap = (Tfloat)atXYZ(px,ay,pz,c,out_value), Icap = (Tfloat)atXYZ(x,ay,pz,c,out_value), Inap = (Tfloat)atXYZ(nx,ay,pz,c,out_value), Iaap = (Tfloat)atXYZ(ax,ay,pz,c,out_value), Iap = Icap + 0.5f*(dx*(-Ipap + Inap) + dx*dx*(2*Ipap - 5*Icap + 4*Inap - Iaap) + dx*dx*dx*(-Ipap + 3*Icap - 3*Inap + Iaap)), Ip = Icp + 0.5f*(dy*(-Ipp + Inp) + dy*dy*(2*Ipp - 5*Icp + 4*Inp - Iap) + dy*dy*dy*(-Ipp + 3*Icp - 3*Inp + Iap)), Ippc = (Tfloat)atXYZ(px,py,z,c,out_value), Icpc = (Tfloat)atXYZ(x,py,z,c,out_value), Inpc = (Tfloat)atXYZ(nx,py,z,c,out_value), Iapc = (Tfloat)atXYZ(ax,py,z,c,out_value), Ipc = Icpc + 0.5f*(dx*(-Ippc + Inpc) + dx*dx*(2*Ippc - 5*Icpc + 4*Inpc - Iapc) + dx*dx*dx*(-Ippc + 3*Icpc - 3*Inpc + Iapc)), Ipcc = (Tfloat)atXYZ(px,y,z,c,out_value), Iccc = (Tfloat)atXYZ(x, y,z,c,out_value), Incc = (Tfloat)atXYZ(nx,y,z,c,out_value), Iacc = (Tfloat)atXYZ(ax,y,z,c,out_value), Icc = Iccc + 0.5f*(dx*(-Ipcc + Incc) + dx*dx*(2*Ipcc - 5*Iccc + 4*Incc - Iacc) + dx*dx*dx*(-Ipcc + 3*Iccc - 3*Incc + Iacc)), Ipnc = (Tfloat)atXYZ(px,ny,z,c,out_value), Icnc = (Tfloat)atXYZ(x,ny,z,c,out_value), Innc = (Tfloat)atXYZ(nx,ny,z,c,out_value), Ianc = (Tfloat)atXYZ(ax,ny,z,c,out_value), Inc = Icnc + 0.5f*(dx*(-Ipnc + Innc) + dx*dx*(2*Ipnc - 5*Icnc + 4*Innc - Ianc) + dx*dx*dx*(-Ipnc + 3*Icnc - 3*Innc + Ianc)), Ipac = (Tfloat)atXYZ(px,ay,z,c,out_value), Icac = (Tfloat)atXYZ(x,ay,z,c,out_value), Inac = (Tfloat)atXYZ(nx,ay,z,c,out_value), Iaac = (Tfloat)atXYZ(ax,ay,z,c,out_value), Iac = Icac + 0.5f*(dx*(-Ipac + Inac) + dx*dx*(2*Ipac - 5*Icac + 4*Inac - Iaac) + dx*dx*dx*(-Ipac + 3*Icac - 3*Inac + Iaac)), Ic = Icc + 0.5f*(dy*(-Ipc + Inc) + dy*dy*(2*Ipc - 5*Icc + 4*Inc - Iac) + dy*dy*dy*(-Ipc + 3*Icc - 3*Inc + Iac)), Ippn = (Tfloat)atXYZ(px,py,nz,c,out_value), Icpn = (Tfloat)atXYZ(x,py,nz,c,out_value), Inpn = (Tfloat)atXYZ(nx,py,nz,c,out_value), Iapn = (Tfloat)atXYZ(ax,py,nz,c,out_value), Ipn = Icpn + 0.5f*(dx*(-Ippn + Inpn) + dx*dx*(2*Ippn - 5*Icpn + 4*Inpn - Iapn) + dx*dx*dx*(-Ippn + 3*Icpn - 3*Inpn + Iapn)), Ipcn = (Tfloat)atXYZ(px,y,nz,c,out_value), Iccn = (Tfloat)atXYZ(x, y,nz,c,out_value), Incn = (Tfloat)atXYZ(nx,y,nz,c,out_value), Iacn = (Tfloat)atXYZ(ax,y,nz,c,out_value), Icn = Iccn + 0.5f*(dx*(-Ipcn + Incn) + dx*dx*(2*Ipcn - 5*Iccn + 4*Incn - Iacn) + dx*dx*dx*(-Ipcn + 3*Iccn - 3*Incn + Iacn)), Ipnn = (Tfloat)atXYZ(px,ny,nz,c,out_value), Icnn = (Tfloat)atXYZ(x,ny,nz,c,out_value), Innn = (Tfloat)atXYZ(nx,ny,nz,c,out_value), Iann = (Tfloat)atXYZ(ax,ny,nz,c,out_value), Inn = Icnn + 0.5f*(dx*(-Ipnn + Innn) + dx*dx*(2*Ipnn - 5*Icnn + 4*Innn - Iann) + dx*dx*dx*(-Ipnn + 3*Icnn - 3*Innn + Iann)), Ipan = (Tfloat)atXYZ(px,ay,nz,c,out_value), Ican = (Tfloat)atXYZ(x,ay,nz,c,out_value), Inan = (Tfloat)atXYZ(nx,ay,nz,c,out_value), Iaan = (Tfloat)atXYZ(ax,ay,nz,c,out_value), Ian = Ican + 0.5f*(dx*(-Ipan + Inan) + dx*dx*(2*Ipan - 5*Ican + 4*Inan - Iaan) + dx*dx*dx*(-Ipan + 3*Ican - 3*Inan + Iaan)), In = Icn + 0.5f*(dy*(-Ipn + Inn) + dy*dy*(2*Ipn - 5*Icn + 4*Inn - Ian) + dy*dy*dy*(-Ipn + 3*Icn - 3*Inn + Ian)), Ippa = (Tfloat)atXYZ(px,py,az,c,out_value), Icpa = (Tfloat)atXYZ(x,py,az,c,out_value), Inpa = (Tfloat)atXYZ(nx,py,az,c,out_value), Iapa = (Tfloat)atXYZ(ax,py,az,c,out_value), Ipa = Icpa + 0.5f*(dx*(-Ippa + Inpa) + dx*dx*(2*Ippa - 5*Icpa + 4*Inpa - Iapa) + dx*dx*dx*(-Ippa + 3*Icpa - 3*Inpa + Iapa)), Ipca = (Tfloat)atXYZ(px,y,az,c,out_value), Icca = (Tfloat)atXYZ(x, y,az,c,out_value), Inca = (Tfloat)atXYZ(nx,y,az,c,out_value), Iaca = (Tfloat)atXYZ(ax,y,az,c,out_value), Ica = Icca + 0.5f*(dx*(-Ipca + Inca) + dx*dx*(2*Ipca - 5*Icca + 4*Inca - Iaca) + dx*dx*dx*(-Ipca + 3*Icca - 3*Inca + Iaca)), Ipna = (Tfloat)atXYZ(px,ny,az,c,out_value), Icna = (Tfloat)atXYZ(x,ny,az,c,out_value), Inna = (Tfloat)atXYZ(nx,ny,az,c,out_value), Iana = (Tfloat)atXYZ(ax,ny,az,c,out_value), Ina = Icna + 0.5f*(dx*(-Ipna + Inna) + dx*dx*(2*Ipna - 5*Icna + 4*Inna - Iana) + dx*dx*dx*(-Ipna + 3*Icna - 3*Inna + Iana)), Ipaa = (Tfloat)atXYZ(px,ay,az,c,out_value), Icaa = (Tfloat)atXYZ(x,ay,az,c,out_value), Inaa = (Tfloat)atXYZ(nx,ay,az,c,out_value), Iaaa = (Tfloat)atXYZ(ax,ay,az,c,out_value), Iaa = Icaa + 0.5f*(dx*(-Ipaa + Inaa) + dx*dx*(2*Ipaa - 5*Icaa + 4*Inaa - Iaaa) + dx*dx*dx*(-Ipaa + 3*Icaa - 3*Inaa + Iaaa)), Ia = Ica + 0.5f*(dy*(-Ipa + Ina) + dy*dy*(2*Ipa - 5*Ica + 4*Ina - Iaa) + dy*dy*dy*(-Ipa + 3*Ica - 3*Ina + Iaa)); return Ic + 0.5f*(dz*(-Ip + In) + dz*dz*(2*Ip - 5*Ic + 4*In - Ia) + dz*dz*dz*(-Ip + 3*Ic - 3*In + Ia)); } //! Return clamped pixel value, using cubic interpolation and Dirichlet boundary conditions for the XYZ-coordinates. /** Similar to cubic_atXYZ(float,float,float,int,const T) const, except that the return value is clamped to stay in the min/max range of the datatype \c T. **/ T cubic_atXYZ_c(const float fx, const float fy, const float fz, const int c, const T& out_value) const { return cimg::type<T>::cut(cubic_atXYZ(fx,fy,fz,c,out_value)); } //! Return pixel value, using cubic interpolation and Neumann boundary conditions for the X,Y and Z-coordinates. /** Similar to cubic_atX(float,int,int,int) const, except that the cubic interpolation and boundary checking are achieved both for X,Y and Z-coordinates. \note - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _cubic_atXYZ(float,float,float,int). **/ Tfloat cubic_atXYZ(const float fx, const float fy, const float fz, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "cubic_atXYZ(): Empty instance.", cimg_instance); return _cubic_atXYZ(fx,fy,fz,c); } Tfloat _cubic_atXYZ(const float fx, const float fy, const float fz, const int c=0) const { const float nfx = cimg::type<float>::is_nan(fx)?0:cimg::cut(fx,0,width() - 1), nfy = cimg::type<float>::is_nan(fy)?0:cimg::cut(fy,0,height() - 1), nfz = cimg::type<float>::is_nan(fz)?0:cimg::cut(fz,0,depth() - 1); const int x = (int)nfx, y = (int)nfy, z = (int)nfz; const float dx = nfx - x, dy = nfy - y, dz = nfz - z; const int px = x - 1<0?0:x - 1, nx = dx>0?x + 1:x, ax = x + 2>=width()?width() - 1:x + 2, py = y - 1<0?0:y - 1, ny = dy>0?y + 1:y, ay = y + 2>=height()?height() - 1:y + 2, pz = z - 1<0?0:z - 1, nz = dz>0?z + 1:z, az = z + 2>=depth()?depth() - 1:z + 2; const Tfloat Ippp = (Tfloat)(*this)(px,py,pz,c), Icpp = (Tfloat)(*this)(x,py,pz,c), Inpp = (Tfloat)(*this)(nx,py,pz,c), Iapp = (Tfloat)(*this)(ax,py,pz,c), Ipp = Icpp + 0.5f*(dx*(-Ippp + Inpp) + dx*dx*(2*Ippp - 5*Icpp + 4*Inpp - Iapp) + dx*dx*dx*(-Ippp + 3*Icpp - 3*Inpp + Iapp)), Ipcp = (Tfloat)(*this)(px,y,pz,c), Iccp = (Tfloat)(*this)(x, y,pz,c), Incp = (Tfloat)(*this)(nx,y,pz,c), Iacp = (Tfloat)(*this)(ax,y,pz,c), Icp = Iccp + 0.5f*(dx*(-Ipcp + Incp) + dx*dx*(2*Ipcp - 5*Iccp + 4*Incp - Iacp) + dx*dx*dx*(-Ipcp + 3*Iccp - 3*Incp + Iacp)), Ipnp = (Tfloat)(*this)(px,ny,pz,c), Icnp = (Tfloat)(*this)(x,ny,pz,c), Innp = (Tfloat)(*this)(nx,ny,pz,c), Ianp = (Tfloat)(*this)(ax,ny,pz,c), Inp = Icnp + 0.5f*(dx*(-Ipnp + Innp) + dx*dx*(2*Ipnp - 5*Icnp + 4*Innp - Ianp) + dx*dx*dx*(-Ipnp + 3*Icnp - 3*Innp + Ianp)), Ipap = (Tfloat)(*this)(px,ay,pz,c), Icap = (Tfloat)(*this)(x,ay,pz,c), Inap = (Tfloat)(*this)(nx,ay,pz,c), Iaap = (Tfloat)(*this)(ax,ay,pz,c), Iap = Icap + 0.5f*(dx*(-Ipap + Inap) + dx*dx*(2*Ipap - 5*Icap + 4*Inap - Iaap) + dx*dx*dx*(-Ipap + 3*Icap - 3*Inap + Iaap)), Ip = Icp + 0.5f*(dy*(-Ipp + Inp) + dy*dy*(2*Ipp - 5*Icp + 4*Inp - Iap) + dy*dy*dy*(-Ipp + 3*Icp - 3*Inp + Iap)), Ippc = (Tfloat)(*this)(px,py,z,c), Icpc = (Tfloat)(*this)(x,py,z,c), Inpc = (Tfloat)(*this)(nx,py,z,c), Iapc = (Tfloat)(*this)(ax,py,z,c), Ipc = Icpc + 0.5f*(dx*(-Ippc + Inpc) + dx*dx*(2*Ippc - 5*Icpc + 4*Inpc - Iapc) + dx*dx*dx*(-Ippc + 3*Icpc - 3*Inpc + Iapc)), Ipcc = (Tfloat)(*this)(px,y,z,c), Iccc = (Tfloat)(*this)(x, y,z,c), Incc = (Tfloat)(*this)(nx,y,z,c), Iacc = (Tfloat)(*this)(ax,y,z,c), Icc = Iccc + 0.5f*(dx*(-Ipcc + Incc) + dx*dx*(2*Ipcc - 5*Iccc + 4*Incc - Iacc) + dx*dx*dx*(-Ipcc + 3*Iccc - 3*Incc + Iacc)), Ipnc = (Tfloat)(*this)(px,ny,z,c), Icnc = (Tfloat)(*this)(x,ny,z,c), Innc = (Tfloat)(*this)(nx,ny,z,c), Ianc = (Tfloat)(*this)(ax,ny,z,c), Inc = Icnc + 0.5f*(dx*(-Ipnc + Innc) + dx*dx*(2*Ipnc - 5*Icnc + 4*Innc - Ianc) + dx*dx*dx*(-Ipnc + 3*Icnc - 3*Innc + Ianc)), Ipac = (Tfloat)(*this)(px,ay,z,c), Icac = (Tfloat)(*this)(x,ay,z,c), Inac = (Tfloat)(*this)(nx,ay,z,c), Iaac = (Tfloat)(*this)(ax,ay,z,c), Iac = Icac + 0.5f*(dx*(-Ipac + Inac) + dx*dx*(2*Ipac - 5*Icac + 4*Inac - Iaac) + dx*dx*dx*(-Ipac + 3*Icac - 3*Inac + Iaac)), Ic = Icc + 0.5f*(dy*(-Ipc + Inc) + dy*dy*(2*Ipc - 5*Icc + 4*Inc - Iac) + dy*dy*dy*(-Ipc + 3*Icc - 3*Inc + Iac)), Ippn = (Tfloat)(*this)(px,py,nz,c), Icpn = (Tfloat)(*this)(x,py,nz,c), Inpn = (Tfloat)(*this)(nx,py,nz,c), Iapn = (Tfloat)(*this)(ax,py,nz,c), Ipn = Icpn + 0.5f*(dx*(-Ippn + Inpn) + dx*dx*(2*Ippn - 5*Icpn + 4*Inpn - Iapn) + dx*dx*dx*(-Ippn + 3*Icpn - 3*Inpn + Iapn)), Ipcn = (Tfloat)(*this)(px,y,nz,c), Iccn = (Tfloat)(*this)(x, y,nz,c), Incn = (Tfloat)(*this)(nx,y,nz,c), Iacn = (Tfloat)(*this)(ax,y,nz,c), Icn = Iccn + 0.5f*(dx*(-Ipcn + Incn) + dx*dx*(2*Ipcn - 5*Iccn + 4*Incn - Iacn) + dx*dx*dx*(-Ipcn + 3*Iccn - 3*Incn + Iacn)), Ipnn = (Tfloat)(*this)(px,ny,nz,c), Icnn = (Tfloat)(*this)(x,ny,nz,c), Innn = (Tfloat)(*this)(nx,ny,nz,c), Iann = (Tfloat)(*this)(ax,ny,nz,c), Inn = Icnn + 0.5f*(dx*(-Ipnn + Innn) + dx*dx*(2*Ipnn - 5*Icnn + 4*Innn - Iann) + dx*dx*dx*(-Ipnn + 3*Icnn - 3*Innn + Iann)), Ipan = (Tfloat)(*this)(px,ay,nz,c), Ican = (Tfloat)(*this)(x,ay,nz,c), Inan = (Tfloat)(*this)(nx,ay,nz,c), Iaan = (Tfloat)(*this)(ax,ay,nz,c), Ian = Ican + 0.5f*(dx*(-Ipan + Inan) + dx*dx*(2*Ipan - 5*Ican + 4*Inan - Iaan) + dx*dx*dx*(-Ipan + 3*Ican - 3*Inan + Iaan)), In = Icn + 0.5f*(dy*(-Ipn + Inn) + dy*dy*(2*Ipn - 5*Icn + 4*Inn - Ian) + dy*dy*dy*(-Ipn + 3*Icn - 3*Inn + Ian)), Ippa = (Tfloat)(*this)(px,py,az,c), Icpa = (Tfloat)(*this)(x,py,az,c), Inpa = (Tfloat)(*this)(nx,py,az,c), Iapa = (Tfloat)(*this)(ax,py,az,c), Ipa = Icpa + 0.5f*(dx*(-Ippa + Inpa) + dx*dx*(2*Ippa - 5*Icpa + 4*Inpa - Iapa) + dx*dx*dx*(-Ippa + 3*Icpa - 3*Inpa + Iapa)), Ipca = (Tfloat)(*this)(px,y,az,c), Icca = (Tfloat)(*this)(x, y,az,c), Inca = (Tfloat)(*this)(nx,y,az,c), Iaca = (Tfloat)(*this)(ax,y,az,c), Ica = Icca + 0.5f*(dx*(-Ipca + Inca) + dx*dx*(2*Ipca - 5*Icca + 4*Inca - Iaca) + dx*dx*dx*(-Ipca + 3*Icca - 3*Inca + Iaca)), Ipna = (Tfloat)(*this)(px,ny,az,c), Icna = (Tfloat)(*this)(x,ny,az,c), Inna = (Tfloat)(*this)(nx,ny,az,c), Iana = (Tfloat)(*this)(ax,ny,az,c), Ina = Icna + 0.5f*(dx*(-Ipna + Inna) + dx*dx*(2*Ipna - 5*Icna + 4*Inna - Iana) + dx*dx*dx*(-Ipna + 3*Icna - 3*Inna + Iana)), Ipaa = (Tfloat)(*this)(px,ay,az,c), Icaa = (Tfloat)(*this)(x,ay,az,c), Inaa = (Tfloat)(*this)(nx,ay,az,c), Iaaa = (Tfloat)(*this)(ax,ay,az,c), Iaa = Icaa + 0.5f*(dx*(-Ipaa + Inaa) + dx*dx*(2*Ipaa - 5*Icaa + 4*Inaa - Iaaa) + dx*dx*dx*(-Ipaa + 3*Icaa - 3*Inaa + Iaaa)), Ia = Ica + 0.5f*(dy*(-Ipa + Ina) + dy*dy*(2*Ipa - 5*Ica + 4*Ina - Iaa) + dy*dy*dy*(-Ipa + 3*Ica - 3*Ina + Iaa)); return Ic + 0.5f*(dz*(-Ip + In) + dz*dz*(2*Ip - 5*Ic + 4*In - Ia) + dz*dz*dz*(-Ip + 3*Ic - 3*In + Ia)); } //! Return clamped pixel value, using cubic interpolation and Neumann boundary conditions for the XYZ-coordinates. /** Similar to cubic_atXYZ(float,float,float,int) const, except that the return value is clamped to stay in the min/max range of the datatype \c T. **/ T cubic_atXYZ_c(const float fx, const float fy, const float fz, const int c) const { return cimg::type<T>::cut(cubic_atXYZ(fx,fy,fz,c)); } T _cubic_atXYZ_c(const float fx, const float fy, const float fz, const int c) const { return cimg::type<T>::cut(_cubic_atXYZ(fx,fy,fz,c)); } //! Return pixel value, using cubic interpolation and Neumann boundary conditions for the X,Y and Z-coordinates. /** Similar to cubic_atX(float,int,int,int) const, except that the cubic interpolation and boundary checking are achieved both for X,Y and Z-coordinates. \note - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _cubic_atXYZ(float,float,float,int). **/ Tfloat cubic_atXYZ_p(const float fx, const float fy, const float fz, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "cubic_atXYZ_p(): Empty instance.", cimg_instance); return _cubic_atXYZ_p(fx,fy,fz,c); } Tfloat _cubic_atXYZ_p(const float fx, const float fy, const float fz, const int c=0) const { const float nfx = cimg::type<float>::is_nan(fx)?0:cimg::mod(fx,(float)_width), nfy = cimg::type<float>::is_nan(fy)?0:cimg::mod(fy,(float)_height), nfz = cimg::type<float>::is_nan(fz)?0:cimg::mod(fz,(float)_depth); const int x = (int)nfx, y = (int)nfy, z = (int)nfz; const float dx = nfx - x, dy = nfy - y, dz = nfz - z; const int px = cimg::mod(x - 1,width()), nx = cimg::mod(x + 1,width()), ax = cimg::mod(x + 2,width()), py = cimg::mod(y - 1,height()), ny = cimg::mod(y + 1,height()), ay = cimg::mod(y + 2,height()), pz = cimg::mod(z - 1,depth()), nz = cimg::mod(z + 1,depth()), az = cimg::mod(z + 2,depth()); const Tfloat Ippp = (Tfloat)(*this)(px,py,pz,c), Icpp = (Tfloat)(*this)(x,py,pz,c), Inpp = (Tfloat)(*this)(nx,py,pz,c), Iapp = (Tfloat)(*this)(ax,py,pz,c), Ipp = Icpp + 0.5f*(dx*(-Ippp + Inpp) + dx*dx*(2*Ippp - 5*Icpp + 4*Inpp - Iapp) + dx*dx*dx*(-Ippp + 3*Icpp - 3*Inpp + Iapp)), Ipcp = (Tfloat)(*this)(px,y,pz,c), Iccp = (Tfloat)(*this)(x, y,pz,c), Incp = (Tfloat)(*this)(nx,y,pz,c), Iacp = (Tfloat)(*this)(ax,y,pz,c), Icp = Iccp + 0.5f*(dx*(-Ipcp + Incp) + dx*dx*(2*Ipcp - 5*Iccp + 4*Incp - Iacp) + dx*dx*dx*(-Ipcp + 3*Iccp - 3*Incp + Iacp)), Ipnp = (Tfloat)(*this)(px,ny,pz,c), Icnp = (Tfloat)(*this)(x,ny,pz,c), Innp = (Tfloat)(*this)(nx,ny,pz,c), Ianp = (Tfloat)(*this)(ax,ny,pz,c), Inp = Icnp + 0.5f*(dx*(-Ipnp + Innp) + dx*dx*(2*Ipnp - 5*Icnp + 4*Innp - Ianp) + dx*dx*dx*(-Ipnp + 3*Icnp - 3*Innp + Ianp)), Ipap = (Tfloat)(*this)(px,ay,pz,c), Icap = (Tfloat)(*this)(x,ay,pz,c), Inap = (Tfloat)(*this)(nx,ay,pz,c), Iaap = (Tfloat)(*this)(ax,ay,pz,c), Iap = Icap + 0.5f*(dx*(-Ipap + Inap) + dx*dx*(2*Ipap - 5*Icap + 4*Inap - Iaap) + dx*dx*dx*(-Ipap + 3*Icap - 3*Inap + Iaap)), Ip = Icp + 0.5f*(dy*(-Ipp + Inp) + dy*dy*(2*Ipp - 5*Icp + 4*Inp - Iap) + dy*dy*dy*(-Ipp + 3*Icp - 3*Inp + Iap)), Ippc = (Tfloat)(*this)(px,py,z,c), Icpc = (Tfloat)(*this)(x,py,z,c), Inpc = (Tfloat)(*this)(nx,py,z,c), Iapc = (Tfloat)(*this)(ax,py,z,c), Ipc = Icpc + 0.5f*(dx*(-Ippc + Inpc) + dx*dx*(2*Ippc - 5*Icpc + 4*Inpc - Iapc) + dx*dx*dx*(-Ippc + 3*Icpc - 3*Inpc + Iapc)), Ipcc = (Tfloat)(*this)(px,y,z,c), Iccc = (Tfloat)(*this)(x, y,z,c), Incc = (Tfloat)(*this)(nx,y,z,c), Iacc = (Tfloat)(*this)(ax,y,z,c), Icc = Iccc + 0.5f*(dx*(-Ipcc + Incc) + dx*dx*(2*Ipcc - 5*Iccc + 4*Incc - Iacc) + dx*dx*dx*(-Ipcc + 3*Iccc - 3*Incc + Iacc)), Ipnc = (Tfloat)(*this)(px,ny,z,c), Icnc = (Tfloat)(*this)(x,ny,z,c), Innc = (Tfloat)(*this)(nx,ny,z,c), Ianc = (Tfloat)(*this)(ax,ny,z,c), Inc = Icnc + 0.5f*(dx*(-Ipnc + Innc) + dx*dx*(2*Ipnc - 5*Icnc + 4*Innc - Ianc) + dx*dx*dx*(-Ipnc + 3*Icnc - 3*Innc + Ianc)), Ipac = (Tfloat)(*this)(px,ay,z,c), Icac = (Tfloat)(*this)(x,ay,z,c), Inac = (Tfloat)(*this)(nx,ay,z,c), Iaac = (Tfloat)(*this)(ax,ay,z,c), Iac = Icac + 0.5f*(dx*(-Ipac + Inac) + dx*dx*(2*Ipac - 5*Icac + 4*Inac - Iaac) + dx*dx*dx*(-Ipac + 3*Icac - 3*Inac + Iaac)), Ic = Icc + 0.5f*(dy*(-Ipc + Inc) + dy*dy*(2*Ipc - 5*Icc + 4*Inc - Iac) + dy*dy*dy*(-Ipc + 3*Icc - 3*Inc + Iac)), Ippn = (Tfloat)(*this)(px,py,nz,c), Icpn = (Tfloat)(*this)(x,py,nz,c), Inpn = (Tfloat)(*this)(nx,py,nz,c), Iapn = (Tfloat)(*this)(ax,py,nz,c), Ipn = Icpn + 0.5f*(dx*(-Ippn + Inpn) + dx*dx*(2*Ippn - 5*Icpn + 4*Inpn - Iapn) + dx*dx*dx*(-Ippn + 3*Icpn - 3*Inpn + Iapn)), Ipcn = (Tfloat)(*this)(px,y,nz,c), Iccn = (Tfloat)(*this)(x, y,nz,c), Incn = (Tfloat)(*this)(nx,y,nz,c), Iacn = (Tfloat)(*this)(ax,y,nz,c), Icn = Iccn + 0.5f*(dx*(-Ipcn + Incn) + dx*dx*(2*Ipcn - 5*Iccn + 4*Incn - Iacn) + dx*dx*dx*(-Ipcn + 3*Iccn - 3*Incn + Iacn)), Ipnn = (Tfloat)(*this)(px,ny,nz,c), Icnn = (Tfloat)(*this)(x,ny,nz,c), Innn = (Tfloat)(*this)(nx,ny,nz,c), Iann = (Tfloat)(*this)(ax,ny,nz,c), Inn = Icnn + 0.5f*(dx*(-Ipnn + Innn) + dx*dx*(2*Ipnn - 5*Icnn + 4*Innn - Iann) + dx*dx*dx*(-Ipnn + 3*Icnn - 3*Innn + Iann)), Ipan = (Tfloat)(*this)(px,ay,nz,c), Ican = (Tfloat)(*this)(x,ay,nz,c), Inan = (Tfloat)(*this)(nx,ay,nz,c), Iaan = (Tfloat)(*this)(ax,ay,nz,c), Ian = Ican + 0.5f*(dx*(-Ipan + Inan) + dx*dx*(2*Ipan - 5*Ican + 4*Inan - Iaan) + dx*dx*dx*(-Ipan + 3*Ican - 3*Inan + Iaan)), In = Icn + 0.5f*(dy*(-Ipn + Inn) + dy*dy*(2*Ipn - 5*Icn + 4*Inn - Ian) + dy*dy*dy*(-Ipn + 3*Icn - 3*Inn + Ian)), Ippa = (Tfloat)(*this)(px,py,az,c), Icpa = (Tfloat)(*this)(x,py,az,c), Inpa = (Tfloat)(*this)(nx,py,az,c), Iapa = (Tfloat)(*this)(ax,py,az,c), Ipa = Icpa + 0.5f*(dx*(-Ippa + Inpa) + dx*dx*(2*Ippa - 5*Icpa + 4*Inpa - Iapa) + dx*dx*dx*(-Ippa + 3*Icpa - 3*Inpa + Iapa)), Ipca = (Tfloat)(*this)(px,y,az,c), Icca = (Tfloat)(*this)(x, y,az,c), Inca = (Tfloat)(*this)(nx,y,az,c), Iaca = (Tfloat)(*this)(ax,y,az,c), Ica = Icca + 0.5f*(dx*(-Ipca + Inca) + dx*dx*(2*Ipca - 5*Icca + 4*Inca - Iaca) + dx*dx*dx*(-Ipca + 3*Icca - 3*Inca + Iaca)), Ipna = (Tfloat)(*this)(px,ny,az,c), Icna = (Tfloat)(*this)(x,ny,az,c), Inna = (Tfloat)(*this)(nx,ny,az,c), Iana = (Tfloat)(*this)(ax,ny,az,c), Ina = Icna + 0.5f*(dx*(-Ipna + Inna) + dx*dx*(2*Ipna - 5*Icna + 4*Inna - Iana) + dx*dx*dx*(-Ipna + 3*Icna - 3*Inna + Iana)), Ipaa = (Tfloat)(*this)(px,ay,az,c), Icaa = (Tfloat)(*this)(x,ay,az,c), Inaa = (Tfloat)(*this)(nx,ay,az,c), Iaaa = (Tfloat)(*this)(ax,ay,az,c), Iaa = Icaa + 0.5f*(dx*(-Ipaa + Inaa) + dx*dx*(2*Ipaa - 5*Icaa + 4*Inaa - Iaaa) + dx*dx*dx*(-Ipaa + 3*Icaa - 3*Inaa + Iaaa)), Ia = Ica + 0.5f*(dy*(-Ipa + Ina) + dy*dy*(2*Ipa - 5*Ica + 4*Ina - Iaa) + dy*dy*dy*(-Ipa + 3*Ica - 3*Ina + Iaa)); return Ic + 0.5f*(dz*(-Ip + In) + dz*dz*(2*Ip - 5*Ic + 4*In - Ia) + dz*dz*dz*(-Ip + 3*Ic - 3*In + Ia)); } T cubic_atXYZ_pc(const float fx, const float fy, const float fz, const int c) const { return cimg::type<T>::cut(cubic_atXYZ_p(fx,fy,fz,c)); } T _cubic_atXYZ_pc(const float fx, const float fy, const float fz, const int c) const { return cimg::type<T>::cut(_cubic_atXYZ_p(fx,fy,fz,c)); } //! Set pixel value, using linear interpolation for the X-coordinates. /** Set pixel value at specified coordinates (\c fx,\c y,\c z,\c c) in the image instance, in a way that the value is spread amongst several neighbors if the pixel coordinates are float-valued. \param value Pixel value to set. \param fx X-coordinate of the pixel value (float-valued). \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param is_added Tells if the pixel value is added to (\c true), or simply replace (\c false) the current image pixel(s). \return A reference to the current image instance. \note - Calling this method with out-of-bounds coordinates does nothing. **/ CImg<T>& set_linear_atX(const T& value, const float fx, const int y=0, const int z=0, const int c=0, const bool is_added=false) { const int x = (int)fx - (fx>=0?0:1), nx = x + 1; const float dx = fx - x; if (y>=0 && y<height() && z>=0 && z<depth() && c>=0 && c<spectrum()) { if (x>=0 && x<width()) { const float w1 = 1 - dx, w2 = is_added?1:(1 - w1); (*this)(x,y,z,c) = (T)(w1*value + w2*(*this)(x,y,z,c)); } if (nx>=0 && nx<width()) { const float w1 = dx, w2 = is_added?1:(1 - w1); (*this)(nx,y,z,c) = (T)(w1*value + w2*(*this)(nx,y,z,c)); } } return *this; } //! Set pixel value, using linear interpolation for the X and Y-coordinates. /** Similar to set_linear_atX(const T&,float,int,int,int,bool), except that the linear interpolation is achieved both for X and Y-coordinates. **/ CImg<T>& set_linear_atXY(const T& value, const float fx, const float fy=0, const int z=0, const int c=0, const bool is_added=false) { const int x = (int)fx - (fx>=0?0:1), nx = x + 1, y = (int)fy - (fy>=0?0:1), ny = y + 1; const float dx = fx - x, dy = fy - y; if (z>=0 && z<depth() && c>=0 && c<spectrum()) { if (y>=0 && y<height()) { if (x>=0 && x<width()) { const float w1 = (1 - dx)*(1 - dy), w2 = is_added?1:(1 - w1); (*this)(x,y,z,c) = (T)(w1*value + w2*(*this)(x,y,z,c)); } if (nx>=0 && nx<width()) { const float w1 = dx*(1 - dy), w2 = is_added?1:(1 - w1); (*this)(nx,y,z,c) = (T)(w1*value + w2*(*this)(nx,y,z,c)); } } if (ny>=0 && ny<height()) { if (x>=0 && x<width()) { const float w1 = (1 - dx)*dy, w2 = is_added?1:(1 - w1); (*this)(x,ny,z,c) = (T)(w1*value + w2*(*this)(x,ny,z,c)); } if (nx>=0 && nx<width()) { const float w1 = dx*dy, w2 = is_added?1:(1 - w1); (*this)(nx,ny,z,c) = (T)(w1*value + w2*(*this)(nx,ny,z,c)); } } } return *this; } //! Set pixel value, using linear interpolation for the X,Y and Z-coordinates. /** Similar to set_linear_atXY(const T&,float,float,int,int,bool), except that the linear interpolation is achieved both for X,Y and Z-coordinates. **/ CImg<T>& set_linear_atXYZ(const T& value, const float fx, const float fy=0, const float fz=0, const int c=0, const bool is_added=false) { const int x = (int)fx - (fx>=0?0:1), nx = x + 1, y = (int)fy - (fy>=0?0:1), ny = y + 1, z = (int)fz - (fz>=0?0:1), nz = z + 1; const float dx = fx - x, dy = fy - y, dz = fz - z; if (c>=0 && c<spectrum()) { if (z>=0 && z<depth()) { if (y>=0 && y<height()) { if (x>=0 && x<width()) { const float w1 = (1 - dx)*(1 - dy)*(1 - dz), w2 = is_added?1:(1 - w1); (*this)(x,y,z,c) = (T)(w1*value + w2*(*this)(x,y,z,c)); } if (nx>=0 && nx<width()) { const float w1 = dx*(1 - dy)*(1 - dz), w2 = is_added?1:(1 - w1); (*this)(nx,y,z,c) = (T)(w1*value + w2*(*this)(nx,y,z,c)); } } if (ny>=0 && ny<height()) { if (x>=0 && x<width()) { const float w1 = (1 - dx)*dy*(1 - dz), w2 = is_added?1:(1 - w1); (*this)(x,ny,z,c) = (T)(w1*value + w2*(*this)(x,ny,z,c)); } if (nx>=0 && nx<width()) { const float w1 = dx*dy*(1 - dz), w2 = is_added?1:(1 - w1); (*this)(nx,ny,z,c) = (T)(w1*value + w2*(*this)(nx,ny,z,c)); } } } if (nz>=0 && nz<depth()) { if (y>=0 && y<height()) { if (x>=0 && x<width()) { const float w1 = (1 - dx)*(1 - dy)*dz, w2 = is_added?1:(1 - w1); (*this)(x,y,nz,c) = (T)(w1*value + w2*(*this)(x,y,nz,c)); } if (nx>=0 && nx<width()) { const float w1 = dx*(1 - dy)*dz, w2 = is_added?1:(1 - w1); (*this)(nx,y,nz,c) = (T)(w1*value + w2*(*this)(nx,y,nz,c)); } } if (ny>=0 && ny<height()) { if (x>=0 && x<width()) { const float w1 = (1 - dx)*dy*dz, w2 = is_added?1:(1 - w1); (*this)(x,ny,nz,c) = (T)(w1*value + w2*(*this)(x,ny,nz,c)); } if (nx>=0 && nx<width()) { const float w1 = dx*dy*dz, w2 = is_added?1:(1 - w1); (*this)(nx,ny,nz,c) = (T)(w1*value + w2*(*this)(nx,ny,nz,c)); } } } } return *this; } //! Return a C-string containing a list of all values of the image instance. /** Return a new \c CImg<char> image whose buffer data() is a \c char* string describing the list of all pixel values of the image instance (written in base 10), separated by specified \c separator character. \param separator A \c char character which specifies the separator between values in the returned C-string. \param max_size Maximum size of the returned image (or \c 0 if no limits are set). \param format For float/double-values, tell the printf format used to generate the Ascii representation of the numbers (or \c 0 for default representation). \note - The returned image is never empty. - For an empty image instance, the returned string is <tt>""</tt>. - If \c max_size is equal to \c 0, there are no limits on the size of the returned string. - Otherwise, if the maximum number of string characters is exceeded, the value string is cut off and terminated by character \c '\0'. In that case, the returned image size is <tt>max_size + 1</tt>. **/ CImg<charT> value_string(const char separator=',', const unsigned int max_size=0, const char *const format=0) const { if (is_empty() || max_size==1) return CImg<charT>(1,1,1,1,0); CImgList<charT> items; CImg<charT> s_item(256); *s_item = 0; const T *ptrs = _data; unsigned int string_size = 0; const char *const _format = format?format:cimg::type<T>::format(); for (ulongT off = 0, siz = size(); off<siz && (!max_size || string_size<max_size); ++off) { const unsigned int printed_size = 1U + cimg_snprintf(s_item,s_item._width,_format, cimg::type<T>::format(*(ptrs++))); CImg<charT> item(s_item._data,printed_size); item[printed_size - 1] = separator; item.move_to(items); if (max_size) string_size+=printed_size; } CImg<charT> res; (items>'x').move_to(res); if (max_size && res._width>=max_size) res.crop(0,max_size - 1); res.back() = 0; return res; } //@} //------------------------------------- // //! \name Instance Checking //@{ //------------------------------------- //! Test shared state of the pixel buffer. /** Return \c true if image instance has a shared memory buffer, and \c false otherwise. \note - A shared image do not own his pixel buffer data() and will not deallocate it on destruction. - Most of the time, a \c CImg<T> image instance will \e not be shared. - A shared image can only be obtained by a limited set of constructors and methods (see list below). **/ bool is_shared() const { return _is_shared; } //! Test if image instance is empty. /** Return \c true, if image instance is empty, i.e. does \e not contain any pixel values, has dimensions \c 0 x \c 0 x \c 0 x \c 0 and a pixel buffer pointer set to \c 0 (null pointer), and \c false otherwise. **/ bool is_empty() const { return !(_data && _width && _height && _depth && _spectrum); } //! Test if image instance contains a 'inf' value. /** Return \c true, if image instance contains a 'inf' value, and \c false otherwise. **/ bool is_inf() const { if (cimg::type<T>::is_float()) cimg_for(*this,p,T) if (cimg::type<T>::is_inf((float)*p)) return true; return false; } //! Test if image instance contains a NaN value. /** Return \c true, if image instance contains a NaN value, and \c false otherwise. **/ bool is_nan() const { if (cimg::type<T>::is_float()) cimg_for(*this,p,T) if (cimg::type<T>::is_nan((float)*p)) return true; return false; } //! Test if image width is equal to specified value. bool is_sameX(const unsigned int size_x) const { return _width==size_x; } //! Test if image width is equal to specified value. template<typename t> bool is_sameX(const CImg<t>& img) const { return is_sameX(img._width); } //! Test if image width is equal to specified value. bool is_sameX(const CImgDisplay& disp) const { return is_sameX(disp._width); } //! Test if image height is equal to specified value. bool is_sameY(const unsigned int size_y) const { return _height==size_y; } //! Test if image height is equal to specified value. template<typename t> bool is_sameY(const CImg<t>& img) const { return is_sameY(img._height); } //! Test if image height is equal to specified value. bool is_sameY(const CImgDisplay& disp) const { return is_sameY(disp._height); } //! Test if image depth is equal to specified value. bool is_sameZ(const unsigned int size_z) const { return _depth==size_z; } //! Test if image depth is equal to specified value. template<typename t> bool is_sameZ(const CImg<t>& img) const { return is_sameZ(img._depth); } //! Test if image spectrum is equal to specified value. bool is_sameC(const unsigned int size_c) const { return _spectrum==size_c; } //! Test if image spectrum is equal to specified value. template<typename t> bool is_sameC(const CImg<t>& img) const { return is_sameC(img._spectrum); } //! Test if image width and height are equal to specified values. /** Test if is_sameX(unsigned int) const and is_sameY(unsigned int) const are both verified. **/ bool is_sameXY(const unsigned int size_x, const unsigned int size_y) const { return _width==size_x && _height==size_y; } //! Test if image width and height are the same as that of another image. /** Test if is_sameX(const CImg<t>&) const and is_sameY(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameXY(const CImg<t>& img) const { return is_sameXY(img._width,img._height); } //! Test if image width and height are the same as that of an existing display window. /** Test if is_sameX(const CImgDisplay&) const and is_sameY(const CImgDisplay&) const are both verified. **/ bool is_sameXY(const CImgDisplay& disp) const { return is_sameXY(disp._width,disp._height); } //! Test if image width and depth are equal to specified values. /** Test if is_sameX(unsigned int) const and is_sameZ(unsigned int) const are both verified. **/ bool is_sameXZ(const unsigned int size_x, const unsigned int size_z) const { return _width==size_x && _depth==size_z; } //! Test if image width and depth are the same as that of another image. /** Test if is_sameX(const CImg<t>&) const and is_sameZ(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameXZ(const CImg<t>& img) const { return is_sameXZ(img._width,img._depth); } //! Test if image width and spectrum are equal to specified values. /** Test if is_sameX(unsigned int) const and is_sameC(unsigned int) const are both verified. **/ bool is_sameXC(const unsigned int size_x, const unsigned int size_c) const { return _width==size_x && _spectrum==size_c; } //! Test if image width and spectrum are the same as that of another image. /** Test if is_sameX(const CImg<t>&) const and is_sameC(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameXC(const CImg<t>& img) const { return is_sameXC(img._width,img._spectrum); } //! Test if image height and depth are equal to specified values. /** Test if is_sameY(unsigned int) const and is_sameZ(unsigned int) const are both verified. **/ bool is_sameYZ(const unsigned int size_y, const unsigned int size_z) const { return _height==size_y && _depth==size_z; } //! Test if image height and depth are the same as that of another image. /** Test if is_sameY(const CImg<t>&) const and is_sameZ(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameYZ(const CImg<t>& img) const { return is_sameYZ(img._height,img._depth); } //! Test if image height and spectrum are equal to specified values. /** Test if is_sameY(unsigned int) const and is_sameC(unsigned int) const are both verified. **/ bool is_sameYC(const unsigned int size_y, const unsigned int size_c) const { return _height==size_y && _spectrum==size_c; } //! Test if image height and spectrum are the same as that of another image. /** Test if is_sameY(const CImg<t>&) const and is_sameC(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameYC(const CImg<t>& img) const { return is_sameYC(img._height,img._spectrum); } //! Test if image depth and spectrum are equal to specified values. /** Test if is_sameZ(unsigned int) const and is_sameC(unsigned int) const are both verified. **/ bool is_sameZC(const unsigned int size_z, const unsigned int size_c) const { return _depth==size_z && _spectrum==size_c; } //! Test if image depth and spectrum are the same as that of another image. /** Test if is_sameZ(const CImg<t>&) const and is_sameC(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameZC(const CImg<t>& img) const { return is_sameZC(img._depth,img._spectrum); } //! Test if image width, height and depth are equal to specified values. /** Test if is_sameXY(unsigned int,unsigned int) const and is_sameZ(unsigned int) const are both verified. **/ bool is_sameXYZ(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z) const { return is_sameXY(size_x,size_y) && _depth==size_z; } //! Test if image width, height and depth are the same as that of another image. /** Test if is_sameXY(const CImg<t>&) const and is_sameZ(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameXYZ(const CImg<t>& img) const { return is_sameXYZ(img._width,img._height,img._depth); } //! Test if image width, height and spectrum are equal to specified values. /** Test if is_sameXY(unsigned int,unsigned int) const and is_sameC(unsigned int) const are both verified. **/ bool is_sameXYC(const unsigned int size_x, const unsigned int size_y, const unsigned int size_c) const { return is_sameXY(size_x,size_y) && _spectrum==size_c; } //! Test if image width, height and spectrum are the same as that of another image. /** Test if is_sameXY(const CImg<t>&) const and is_sameC(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameXYC(const CImg<t>& img) const { return is_sameXYC(img._width,img._height,img._spectrum); } //! Test if image width, depth and spectrum are equal to specified values. /** Test if is_sameXZ(unsigned int,unsigned int) const and is_sameC(unsigned int) const are both verified. **/ bool is_sameXZC(const unsigned int size_x, const unsigned int size_z, const unsigned int size_c) const { return is_sameXZ(size_x,size_z) && _spectrum==size_c; } //! Test if image width, depth and spectrum are the same as that of another image. /** Test if is_sameXZ(const CImg<t>&) const and is_sameC(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameXZC(const CImg<t>& img) const { return is_sameXZC(img._width,img._depth,img._spectrum); } //! Test if image height, depth and spectrum are equal to specified values. /** Test if is_sameYZ(unsigned int,unsigned int) const and is_sameC(unsigned int) const are both verified. **/ bool is_sameYZC(const unsigned int size_y, const unsigned int size_z, const unsigned int size_c) const { return is_sameYZ(size_y,size_z) && _spectrum==size_c; } //! Test if image height, depth and spectrum are the same as that of another image. /** Test if is_sameYZ(const CImg<t>&) const and is_sameC(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameYZC(const CImg<t>& img) const { return is_sameYZC(img._height,img._depth,img._spectrum); } //! Test if image width, height, depth and spectrum are equal to specified values. /** Test if is_sameXYZ(unsigned int,unsigned int,unsigned int) const and is_sameC(unsigned int) const are both verified. **/ bool is_sameXYZC(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c) const { return is_sameXYZ(size_x,size_y,size_z) && _spectrum==size_c; } //! Test if image width, height, depth and spectrum are the same as that of another image. /** Test if is_sameXYZ(const CImg<t>&) const and is_sameC(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameXYZC(const CImg<t>& img) const { return is_sameXYZC(img._width,img._height,img._depth,img._spectrum); } //! Test if specified coordinates are inside image bounds. /** Return \c true if pixel located at (\c x,\c y,\c z,\c c) is inside bounds of the image instance, and \c false otherwise. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note - Return \c true only if all these conditions are verified: - The image instance is \e not empty. - <tt>0<=x<=\ref width() - 1</tt>. - <tt>0<=y<=\ref height() - 1</tt>. - <tt>0<=z<=\ref depth() - 1</tt>. - <tt>0<=c<=\ref spectrum() - 1</tt>. **/ bool containsXYZC(const int x, const int y=0, const int z=0, const int c=0) const { return !is_empty() && x>=0 && x<width() && y>=0 && y<height() && z>=0 && z<depth() && c>=0 && c<spectrum(); } //! Test if pixel value is inside image bounds and get its X,Y,Z and C-coordinates. /** Return \c true, if specified reference refers to a pixel value inside bounds of the image instance, and \c false otherwise. \param pixel Reference to pixel value to test. \param[out] x X-coordinate of the pixel value, if test succeeds. \param[out] y Y-coordinate of the pixel value, if test succeeds. \param[out] z Z-coordinate of the pixel value, if test succeeds. \param[out] c C-coordinate of the pixel value, if test succeeds. \note - Useful to convert an offset to a buffer value into pixel value coordinates: \code const CImg<float> img(100,100,1,3); // Construct a 100x100 RGB color image const unsigned long offset = 1249; // Offset to the pixel (49,12,0,0) unsigned int x,y,z,c; if (img.contains(img[offset],x,y,z,c)) { // Convert offset to (x,y,z,c) coordinates std::printf("Offset %u refers to pixel located at (%u,%u,%u,%u).\n", offset,x,y,z,c); } \endcode **/ template<typename t> bool contains(const T& pixel, t& x, t& y, t& z, t& c) const { const ulongT wh = (ulongT)_width*_height, whd = wh*_depth, siz = whd*_spectrum; const T *const ppixel = &pixel; if (is_empty() || ppixel<_data || ppixel>=_data + siz) return false; ulongT off = (ulongT)(ppixel - _data); const ulongT nc = off/whd; off%=whd; const ulongT nz = off/wh; off%=wh; const ulongT ny = off/_width, nx = off%_width; x = (t)nx; y = (t)ny; z = (t)nz; c = (t)nc; return true; } //! Test if pixel value is inside image bounds and get its X,Y and Z-coordinates. /** Similar to contains(const T&,t&,t&,t&,t&) const, except that only the X,Y and Z-coordinates are set. **/ template<typename t> bool contains(const T& pixel, t& x, t& y, t& z) const { const ulongT wh = (ulongT)_width*_height, whd = wh*_depth, siz = whd*_spectrum; const T *const ppixel = &pixel; if (is_empty() || ppixel<_data || ppixel>=_data + siz) return false; ulongT off = ((ulongT)(ppixel - _data))%whd; const ulongT nz = off/wh; off%=wh; const ulongT ny = off/_width, nx = off%_width; x = (t)nx; y = (t)ny; z = (t)nz; return true; } //! Test if pixel value is inside image bounds and get its X and Y-coordinates. /** Similar to contains(const T&,t&,t&,t&,t&) const, except that only the X and Y-coordinates are set. **/ template<typename t> bool contains(const T& pixel, t& x, t& y) const { const ulongT wh = (ulongT)_width*_height, siz = wh*_depth*_spectrum; const T *const ppixel = &pixel; if (is_empty() || ppixel<_data || ppixel>=_data + siz) return false; ulongT off = ((unsigned int)(ppixel - _data))%wh; const ulongT ny = off/_width, nx = off%_width; x = (t)nx; y = (t)ny; return true; } //! Test if pixel value is inside image bounds and get its X-coordinate. /** Similar to contains(const T&,t&,t&,t&,t&) const, except that only the X-coordinate is set. **/ template<typename t> bool contains(const T& pixel, t& x) const { const T *const ppixel = &pixel; if (is_empty() || ppixel<_data || ppixel>=_data + size()) return false; x = (t)(((ulongT)(ppixel - _data))%_width); return true; } //! Test if pixel value is inside image bounds. /** Similar to contains(const T&,t&,t&,t&,t&) const, except that no pixel coordinates are set. **/ bool contains(const T& pixel) const { const T *const ppixel = &pixel; return !is_empty() && ppixel>=_data && ppixel<_data + size(); } //! Test if pixel buffers of instance and input images overlap. /** Return \c true, if pixel buffers attached to image instance and input image \c img overlap, and \c false otherwise. \param img Input image to compare with. \note - Buffer overlapping may happen when manipulating \e shared images. - If two image buffers overlap, operating on one of the image will probably modify the other one. - Most of the time, \c CImg<T> instances are \e non-shared and do not overlap between each others. \par Example \code const CImg<float> img1("reference.jpg"), // Load RGB-color image img2 = img1.get_shared_channel(1); // Get shared version of the green channel if (img1.is_overlapped(img2)) { // Test succeeds, 'img1' and 'img2' overlaps std::printf("Buffers overlap!\n"); } \endcode **/ template<typename t> bool is_overlapped(const CImg<t>& img) const { const ulongT csiz = size(), isiz = img.size(); return !((void*)(_data + csiz)<=(void*)img._data || (void*)_data>=(void*)(img._data + isiz)); } //! Test if the set {\c *this,\c primitives,\c colors,\c opacities} defines a valid 3D object. /** Return \c true is the 3D object represented by the set {\c *this,\c primitives,\c colors,\c opacities} defines a valid 3D object, and \c false otherwise. The vertex coordinates are defined by the instance image. \param primitives List of primitives of the 3D object. \param colors List of colors of the 3D object. \param opacities List (or image) of opacities of the 3D object. \param full_check Tells if full checking of the 3D object must be performed. \param[out] error_message C-string to contain the error message, if the test does not succeed. \note - Set \c full_checking to \c false to speed-up the 3D object checking. In this case, only the size of each 3D object component is checked. - Size of the string \c error_message should be at least 128-bytes long, to be able to contain the error message. **/ template<typename tp, typename tc, typename to> bool is_object3d(const CImgList<tp>& primitives, const CImgList<tc>& colors, const to& opacities, const bool full_check=true, char *const error_message=0) const { if (error_message) *error_message = 0; // Check consistency for the particular case of an empty 3D object. if (is_empty()) { if (primitives || colors || opacities) { if (error_message) cimg_sprintf(error_message, "3D object (%u,%u) defines no vertices but %u primitives, " "%u colors and %lu opacities", _width,primitives._width,primitives._width, colors._width,(unsigned long)opacities.size()); return false; } return true; } // Check consistency of vertices. if (_height!=3 || _depth>1 || _spectrum>1) { // Check vertices dimensions if (error_message) cimg_sprintf(error_message, "3D object (%u,%u) has invalid vertex dimensions (%u,%u,%u,%u)", _width,primitives._width,_width,_height,_depth,_spectrum); return false; } if (colors._width>primitives._width + 1) { if (error_message) cimg_sprintf(error_message, "3D object (%u,%u) defines %u colors", _width,primitives._width,colors._width); return false; } if (opacities.size()>primitives._width) { if (error_message) cimg_sprintf(error_message, "3D object (%u,%u) defines %lu opacities", _width,primitives._width,(unsigned long)opacities.size()); return false; } if (!full_check) return true; // Check consistency of primitives. cimglist_for(primitives,l) { const CImg<tp>& primitive = primitives[l]; const unsigned int psiz = (unsigned int)primitive.size(); switch (psiz) { case 1 : { // Point const unsigned int i0 = (unsigned int)primitive(0); if (i0>=_width) { if (error_message) cimg_sprintf(error_message, "3D object (%u,%u) refers to invalid vertex index %u in " "point primitive [%u]", _width,primitives._width,i0,l); return false; } } break; case 5 : { // Sphere const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1); if (i0>=_width || i1>=_width) { if (error_message) cimg_sprintf(error_message, "3D object (%u,%u) refers to invalid vertex indices (%u,%u) in " "sphere primitive [%u]", _width,primitives._width,i0,i1,l); return false; } } break; case 2 : case 6 : { // Segment const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1); if (i0>=_width || i1>=_width) { if (error_message) cimg_sprintf(error_message, "3D object (%u,%u) refers to invalid vertex indices (%u,%u) in " "segment primitive [%u]", _width,primitives._width,i0,i1,l); return false; } } break; case 3 : case 9 : { // Triangle const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1), i2 = (unsigned int)primitive(2); if (i0>=_width || i1>=_width || i2>=_width) { if (error_message) cimg_sprintf(error_message, "3D object (%u,%u) refers to invalid vertex indices (%u,%u,%u) in " "triangle primitive [%u]", _width,primitives._width,i0,i1,i2,l); return false; } } break; case 4 : case 12 : { // Quadrangle const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1), i2 = (unsigned int)primitive(2), i3 = (unsigned int)primitive(3); if (i0>=_width || i1>=_width || i2>=_width || i3>=_width) { if (error_message) cimg_sprintf(error_message, "3D object (%u,%u) refers to invalid vertex indices (%u,%u,%u,%u) in " "quadrangle primitive [%u]", _width,primitives._width,i0,i1,i2,i3,l); return false; } } break; default : if (error_message) cimg_sprintf(error_message, "3D object (%u,%u) defines an invalid primitive [%u] of size %u", _width,primitives._width,l,(unsigned int)psiz); return false; } } // Check consistency of colors. cimglist_for(colors,c) { const CImg<tc>& color = colors[c]; if (!color) { if (error_message) cimg_sprintf(error_message, "3D object (%u,%u) defines no color for primitive [%u]", _width,primitives._width,c); return false; } } // Check consistency of light texture. if (colors._width>primitives._width) { const CImg<tc> &light = colors.back(); if (!light || light._depth>1) { if (error_message) cimg_sprintf(error_message, "3D object (%u,%u) defines an invalid light texture (%u,%u,%u,%u)", _width,primitives._width,light._width, light._height,light._depth,light._spectrum); return false; } } return true; } //! Test if image instance represents a valid serialization of a 3D object. /** Return \c true if the image instance represents a valid serialization of a 3D object, and \c false otherwise. \param full_check Tells if full checking of the instance must be performed. \param[out] error_message C-string to contain the error message, if the test does not succeed. \note - Set \c full_check to \c false to speed-up the 3D object checking. In this case, only the size of each 3D object component is checked. - Size of the string \c error_message should be at least 128-bytes long, to be able to contain the error message. **/ bool is_CImg3d(const bool full_check=true, char *const error_message=0) const { if (error_message) *error_message = 0; // Check instance dimension and header. if (_width!=1 || _height<8 || _depth!=1 || _spectrum!=1) { if (error_message) cimg_sprintf(error_message, "CImg3d has invalid dimensions (%u,%u,%u,%u)", _width,_height,_depth,_spectrum); return false; } const T *ptrs = _data, *const ptre = end(); if (!_is_CImg3d(*(ptrs++),'C') || !_is_CImg3d(*(ptrs++),'I') || !_is_CImg3d(*(ptrs++),'m') || !_is_CImg3d(*(ptrs++),'g') || !_is_CImg3d(*(ptrs++),'3') || !_is_CImg3d(*(ptrs++),'d')) { if (error_message) cimg_sprintf(error_message, "CImg3d header not found"); return false; } const unsigned int nb_points = cimg::float2uint((float)*(ptrs++)), nb_primitives = cimg::float2uint((float)*(ptrs++)); // Check consistency of number of vertices / primitives. if (!full_check) { const ulongT minimal_size = 8UL + 3*nb_points + 6*nb_primitives; if (_data + minimal_size>ptre) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) has only %lu values, while at least %lu values were expected", nb_points,nb_primitives,(unsigned long)size(),(unsigned long)minimal_size); return false; } } // Check consistency of vertex data. if (!nb_points) { if (nb_primitives) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) defines no vertices but %u primitives", nb_points,nb_primitives,nb_primitives); return false; } if (ptrs!=ptre) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) is an empty object but contains %u value%s " "more than expected", nb_points,nb_primitives,(unsigned int)(ptre - ptrs),(ptre - ptrs)>1?"s":""); return false; } return true; } if (ptrs + 3*nb_points>ptre) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) defines only %u vertices data", nb_points,nb_primitives,(unsigned int)(ptre - ptrs)/3); return false; } ptrs+=3*nb_points; // Check consistency of primitive data. if (ptrs==ptre) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) defines %u vertices but no primitive", nb_points,nb_primitives,nb_points); return false; } if (!full_check) return true; for (unsigned int p = 0; p<nb_primitives; ++p) { const unsigned int nb_inds = (unsigned int)*(ptrs++); switch (nb_inds) { case 1 : { // Point const unsigned int i0 = cimg::float2uint((float)*(ptrs++)); if (i0>=nb_points) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) refers to invalid vertex index %u in point primitive [%u]", nb_points,nb_primitives,i0,p); return false; } } break; case 5 : { // Sphere const unsigned int i0 = cimg::float2uint((float)*(ptrs++)), i1 = cimg::float2uint((float)*(ptrs++)); ptrs+=3; if (i0>=nb_points || i1>=nb_points) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) refers to invalid vertex indices (%u,%u) in " "sphere primitive [%u]", nb_points,nb_primitives,i0,i1,p); return false; } } break; case 2 : case 6 : { // Segment const unsigned int i0 = cimg::float2uint((float)*(ptrs++)), i1 = cimg::float2uint((float)*(ptrs++)); if (nb_inds==6) ptrs+=4; if (i0>=nb_points || i1>=nb_points) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) refers to invalid vertex indices (%u,%u) in " "segment primitive [%u]", nb_points,nb_primitives,i0,i1,p); return false; } } break; case 3 : case 9 : { // Triangle const unsigned int i0 = cimg::float2uint((float)*(ptrs++)), i1 = cimg::float2uint((float)*(ptrs++)), i2 = cimg::float2uint((float)*(ptrs++)); if (nb_inds==9) ptrs+=6; if (i0>=nb_points || i1>=nb_points || i2>=nb_points) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) refers to invalid vertex indices (%u,%u,%u) in " "triangle primitive [%u]", nb_points,nb_primitives,i0,i1,i2,p); return false; } } break; case 4 : case 12 : { // Quadrangle const unsigned int i0 = cimg::float2uint((float)*(ptrs++)), i1 = cimg::float2uint((float)*(ptrs++)), i2 = cimg::float2uint((float)*(ptrs++)), i3 = cimg::float2uint((float)*(ptrs++)); if (nb_inds==12) ptrs+=8; if (i0>=nb_points || i1>=nb_points || i2>=nb_points || i3>=nb_points) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) refers to invalid vertex indices (%u,%u,%u,%u) in " "quadrangle primitive [%u]", nb_points,nb_primitives,i0,i1,i2,i3,p); return false; } } break; default : if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) defines an invalid primitive [%u] of size %u", nb_points,nb_primitives,p,nb_inds); return false; } if (ptrs>ptre) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) has incomplete primitive data for primitive [%u], " "%u values missing", nb_points,nb_primitives,p,(unsigned int)(ptrs - ptre)); return false; } } // Check consistency of color data. if (ptrs==ptre) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) defines no color/texture data", nb_points,nb_primitives); return false; } for (unsigned int c = 0; c<nb_primitives; ++c) { if (*(ptrs++)!=(T)-128) ptrs+=2; else if ((ptrs+=3)<ptre) { const unsigned int w = (unsigned int)*(ptrs - 3), h = (unsigned int)*(ptrs - 2), s = (unsigned int)*(ptrs - 1); if (!h && !s) { if (w>=c) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) refers to invalid shared sprite/texture index %u " "for primitive [%u]", nb_points,nb_primitives,w,c); return false; } } else ptrs+=w*h*s; } if (ptrs>ptre) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) has incomplete color/texture data for primitive [%u], " "%u values missing", nb_points,nb_primitives,c,(unsigned int)(ptrs - ptre)); return false; } } // Check consistency of opacity data. if (ptrs==ptre) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) defines no opacity data", nb_points,nb_primitives); return false; } for (unsigned int o = 0; o<nb_primitives; ++o) { if (*(ptrs++)==(T)-128 && (ptrs+=3)<ptre) { const unsigned int w = (unsigned int)*(ptrs - 3), h = (unsigned int)*(ptrs - 2), s = (unsigned int)*(ptrs - 1); if (!h && !s) { if (w>=o) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) refers to invalid shared opacity index %u " "for primitive [%u]", nb_points,nb_primitives,w,o); return false; } } else ptrs+=w*h*s; } if (ptrs>ptre) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) has incomplete opacity data for primitive [%u]", nb_points,nb_primitives,o); return false; } } // Check end of data. if (ptrs<ptre) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) contains %u value%s more than expected", nb_points,nb_primitives,(unsigned int)(ptre - ptrs),(ptre - ptrs)>1?"s":""); return false; } return true; } static bool _is_CImg3d(const T val, const char c) { return val>=(T)c && val<(T)(c + 1); } //@} //------------------------------------- // //! \name Mathematical Functions //@{ //------------------------------------- // Define the math formula parser/compiler and expression evaluator. struct _cimg_math_parser { CImg<doubleT> mem; CImg<intT> memtype; CImgList<ulongT> _code, &code, code_begin, code_end; CImg<ulongT> opcode; const CImg<ulongT> *p_code_end, *p_code; const CImg<ulongT> *const p_break; CImg<charT> expr, pexpr; const CImg<T>& imgin; const CImgList<T>& listin; CImg<T> &imgout; CImgList<T>& listout; CImg<doubleT> _img_stats, &img_stats, constcache_vals; CImgList<doubleT> _list_stats, &list_stats, _list_median, &list_median; CImg<uintT> mem_img_stats, constcache_inds; CImg<uintT> level, variable_pos, reserved_label; CImgList<charT> variable_def, macro_def, macro_body; CImgList<boolT> macro_body_is_string; char *user_macro; unsigned int mempos, mem_img_median, debug_indent, result_dim, break_type, constcache_size; bool is_parallelizable, is_fill, need_input_copy; double *result; ulongT rng; const char *const calling_function, *s_op, *ss_op; typedef double (*mp_func)(_cimg_math_parser&); #define _cimg_mp_is_constant(arg) (memtype[arg]==1) // Is constant value? #define _cimg_mp_is_scalar(arg) (memtype[arg]<2) // Is scalar value? #define _cimg_mp_is_comp(arg) (!memtype[arg]) // Is computation value? #define _cimg_mp_is_variable(arg) (memtype[arg]==-1) // Is scalar variable? #define _cimg_mp_is_vector(arg) (memtype[arg]>1) // Is vector? #define _cimg_mp_size(arg) (_cimg_mp_is_scalar(arg)?0U:(unsigned int)memtype[arg] - 1) // Size (0=scalar, N>0=vectorN) #define _cimg_mp_calling_function calling_function_s()._data #define _cimg_mp_op(s) s_op = s; ss_op = ss #define _cimg_mp_check_type(arg,n_arg,mode,N) check_type(arg,n_arg,mode,N,ss,se,saved_char) #define _cimg_mp_check_constant(arg,n_arg,mode) check_constant(arg,n_arg,mode,ss,se,saved_char) #define _cimg_mp_check_matrix_square(arg,n_arg) check_matrix_square(arg,n_arg,ss,se,saved_char) #define _cimg_mp_check_list(is_out) check_list(is_out,ss,se,saved_char) #define _cimg_mp_defunc(mp) (*(mp_func)(*(mp).opcode))(mp) #define _cimg_mp_return(x) { *se = saved_char; s_op = previous_s_op; ss_op = previous_ss_op; return x; } #define _cimg_mp_return_nan() _cimg_mp_return(_cimg_mp_slot_nan) #define _cimg_mp_constant(val) _cimg_mp_return(constant((double)(val))) #define _cimg_mp_scalar0(op) _cimg_mp_return(scalar0(op)) #define _cimg_mp_scalar1(op,i1) _cimg_mp_return(scalar1(op,i1)) #define _cimg_mp_scalar2(op,i1,i2) _cimg_mp_return(scalar2(op,i1,i2)) #define _cimg_mp_scalar3(op,i1,i2,i3) _cimg_mp_return(scalar3(op,i1,i2,i3)) #define _cimg_mp_scalar4(op,i1,i2,i3,i4) _cimg_mp_return(scalar4(op,i1,i2,i3,i4)) #define _cimg_mp_scalar5(op,i1,i2,i3,i4,i5) _cimg_mp_return(scalar5(op,i1,i2,i3,i4,i5)) #define _cimg_mp_scalar6(op,i1,i2,i3,i4,i5,i6) _cimg_mp_return(scalar6(op,i1,i2,i3,i4,i5,i6)) #define _cimg_mp_scalar7(op,i1,i2,i3,i4,i5,i6,i7) _cimg_mp_return(scalar7(op,i1,i2,i3,i4,i5,i6,i7)) #define _cimg_mp_vector1_v(op,i1) _cimg_mp_return(vector1_v(op,i1)) #define _cimg_mp_vector2_sv(op,i1,i2) _cimg_mp_return(vector2_sv(op,i1,i2)) #define _cimg_mp_vector2_vs(op,i1,i2) _cimg_mp_return(vector2_vs(op,i1,i2)) #define _cimg_mp_vector2_vv(op,i1,i2) _cimg_mp_return(vector2_vv(op,i1,i2)) #define _cimg_mp_vector3_vss(op,i1,i2,i3) _cimg_mp_return(vector3_vss(op,i1,i2,i3)) // Constructors / Destructors. ~_cimg_math_parser() { cimg::srand(rng); } _cimg_math_parser(const char *const expression, const char *const funcname=0, const CImg<T>& img_input=CImg<T>::const_empty(), CImg<T> *const img_output=0, const CImgList<T> *const list_inputs=0, CImgList<T> *const list_outputs=0, const bool _is_fill=false): code(_code),p_break((CImg<ulongT>*)(cimg_ulong)-2), imgin(img_input),listin(list_inputs?*list_inputs:CImgList<T>::const_empty()), imgout(img_output?*img_output:CImg<T>::empty()),listout(list_outputs?*list_outputs:CImgList<T>::empty()), img_stats(_img_stats),list_stats(_list_stats),list_median(_list_median),user_macro(0), mem_img_median(~0U),debug_indent(0),result_dim(0),break_type(0),constcache_size(0), is_parallelizable(true),is_fill(_is_fill),need_input_copy(false), rng((cimg::_rand(),cimg::rng())),calling_function(funcname?funcname:"cimg_math_parser") { #if cimg_use_openmp!=0 rng+=omp_get_thread_num(); #endif if (!expression || !*expression) throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: Empty expression.", pixel_type(),_cimg_mp_calling_function); const char *_expression = expression; while (*_expression && (cimg::is_blank(*_expression) || *_expression==';')) ++_expression; CImg<charT>::string(_expression).move_to(expr); char *ps = &expr.back() - 1; while (ps>expr._data && (cimg::is_blank(*ps) || *ps==';')) --ps; *(++ps) = 0; expr._width = (unsigned int)(ps - expr._data + 1); // Ease the retrieval of previous non-space characters afterwards. pexpr.assign(expr._width); char c, *pe = pexpr._data; for (ps = expr._data, c = ' '; *ps; ++ps) { if (!cimg::is_blank(*ps)) c = *ps; else *ps = ' '; *(pe++) = c; } *pe = 0; level = get_level(expr); // Init constant values. #define _cimg_mp_interpolation (reserved_label[29]!=~0U?reserved_label[29]:0) #define _cimg_mp_boundary (reserved_label[30]!=~0U?reserved_label[30]:0) #define _cimg_mp_slot_nan 29 #define _cimg_mp_slot_x 30 #define _cimg_mp_slot_y 31 #define _cimg_mp_slot_z 32 #define _cimg_mp_slot_c 33 mem.assign(96); for (unsigned int i = 0; i<=10; ++i) mem[i] = (double)i; // mem[0-10] = 0...10 for (unsigned int i = 1; i<=5; ++i) mem[i + 10] = -(double)i; // mem[11-15] = -1...-5 mem[16] = 0.5; mem[17] = 0; // thread_id mem[18] = (double)imgin._width; // w mem[19] = (double)imgin._height; // h mem[20] = (double)imgin._depth; // d mem[21] = (double)imgin._spectrum; // s mem[22] = (double)imgin._is_shared; // r mem[23] = (double)imgin._width*imgin._height; // wh mem[24] = (double)imgin._width*imgin._height*imgin._depth; // whd mem[25] = (double)imgin._width*imgin._height*imgin._depth*imgin._spectrum; // whds mem[26] = (double)listin._width; // l mem[27] = std::exp(1.); // e mem[28] = cimg::PI; // pi mem[_cimg_mp_slot_nan] = cimg::type<double>::nan(); // nan // Set value property : // { -2 = other | -1 = variable | 0 = computation value | // 1 = compile-time constant | N>1 = constant ptr to vector[N-1] }. memtype.assign(mem._width,1,1,1,0); for (unsigned int i = 0; i<_cimg_mp_slot_x; ++i) memtype[i] = 1; memtype[17] = 0; memtype[_cimg_mp_slot_x] = memtype[_cimg_mp_slot_y] = memtype[_cimg_mp_slot_z] = memtype[_cimg_mp_slot_c] = -2; mempos = _cimg_mp_slot_c + 1; variable_pos.assign(8); reserved_label.assign(128,1,1,1,~0U); // reserved_label[4-28] are used to store these two-char variables: // [0] = wh, [1] = whd, [2] = whds, [3] = pi, [4] = im, [5] = iM, [6] = ia, [7] = iv, // [8] = is, [9] = ip, [10] = ic, [11] = xm, [12] = ym, [13] = zm, [14] = cm, [15] = xM, // [16] = yM, [17] = zM, [18]=cM, [19]=i0...[28]=i9, [29] = interpolation, [30] = boundary // Compile expression into a serie of opcodes. s_op = ""; ss_op = expr._data; const unsigned int ind_result = compile(expr._data,expr._data + expr._width - 1,0,0,false); if (!_cimg_mp_is_constant(ind_result)) { if (_cimg_mp_is_vector(ind_result)) CImg<doubleT>(&mem[ind_result] + 1,_cimg_mp_size(ind_result),1,1,1,true). fill(cimg::type<double>::nan()); else mem[ind_result] = cimg::type<double>::nan(); } // Free resources used for compiling expression and prepare evaluation. result_dim = _cimg_mp_size(ind_result); if (mem._width>=256 && mem._width - mempos>=mem._width/2) mem.resize(mempos,1,1,1,-1); result = mem._data + ind_result; memtype.assign(); constcache_vals.assign(); constcache_inds.assign(); level.assign(); variable_pos.assign(); reserved_label.assign(); expr.assign(); pexpr.assign(); opcode.assign(); opcode._is_shared = true; // Execute begin() bloc if any specified. if (code_begin) { mem[_cimg_mp_slot_x] = mem[_cimg_mp_slot_y] = mem[_cimg_mp_slot_z] = mem[_cimg_mp_slot_c] = 0; p_code_end = code_begin.end(); for (p_code = code_begin; p_code<p_code_end; ++p_code) { opcode._data = p_code->_data; const ulongT target = opcode[1]; mem[target] = _cimg_mp_defunc(*this); } } p_code_end = code.end(); } _cimg_math_parser(): code(_code),p_code_end(0),p_break((CImg<ulongT>*)(cimg_ulong)-2), imgin(CImg<T>::const_empty()),listin(CImgList<T>::const_empty()), imgout(CImg<T>::empty()),listout(CImgList<T>::empty()), img_stats(_img_stats),list_stats(_list_stats),list_median(_list_median),debug_indent(0), result_dim(0),break_type(0),constcache_size(0),is_parallelizable(true),is_fill(false),need_input_copy(false), rng(0),calling_function(0) { mem.assign(1 + _cimg_mp_slot_c,1,1,1,0); // Allow to skip 'is_empty?' test in operator()() result = mem._data; } _cimg_math_parser(const _cimg_math_parser& mp): mem(mp.mem),code(mp.code),p_code_end(mp.p_code_end),p_break(mp.p_break), imgin(mp.imgin),listin(mp.listin),imgout(mp.imgout),listout(mp.listout),img_stats(mp.img_stats), list_stats(mp.list_stats),list_median(mp.list_median),debug_indent(0),result_dim(mp.result_dim), break_type(0),constcache_size(0),is_parallelizable(mp.is_parallelizable),is_fill(mp.is_fill), need_input_copy(mp.need_input_copy), result(mem._data + (mp.result - mp.mem._data)), rng((cimg::_rand(),cimg::rng())),calling_function(0) { #if cimg_use_openmp!=0 mem[17] = omp_get_thread_num(); rng+=omp_get_thread_num(); #endif opcode.assign(); opcode._is_shared = true; } // Count parentheses/brackets level of each character of the expression. CImg<uintT> get_level(CImg<charT>& _expr) const { bool is_escaped = false, next_is_escaped = false; unsigned int mode = 0, next_mode = 0; // { 0=normal | 1=char-string | 2=vector-string CImg<uintT> res(_expr._width - 1); unsigned int *pd = res._data; int _level = 0; for (const char *ps = _expr._data; *ps && _level>=0; ++ps) { if (!is_escaped && !next_is_escaped && *ps=='\\') next_is_escaped = true; if (!is_escaped && *ps=='\'') { // Non-escaped character if (!mode && ps>_expr._data && *(ps - 1)=='[') next_mode = mode = 2; // Start vector-string else if (mode==2 && *(ps + 1)==']') next_mode = !mode; // End vector-string else if (mode<2) next_mode = mode?(mode = 0):1; // Start/end char-string } *(pd++) = (unsigned int)(mode>=1 || is_escaped?_level + (mode==1): *ps=='(' || *ps=='['?_level++: *ps==')' || *ps==']'?--_level: _level); mode = next_mode; is_escaped = next_is_escaped; next_is_escaped = false; } if (mode) { cimg::strellipsize(_expr,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: Unterminated string literal, in expression '%s'.", pixel_type(),_cimg_mp_calling_function, _expr._data); } if (_level) { cimg::strellipsize(_expr,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: Unbalanced parentheses/brackets, in expression '%s'.", pixel_type(),_cimg_mp_calling_function, _expr._data); } return res; } // Tell for each character of an expression if it is inside a string or not. CImg<boolT> is_inside_string(CImg<charT>& _expr) const { bool is_escaped = false, next_is_escaped = false; unsigned int mode = 0, next_mode = 0; // { 0=normal | 1=char-string | 2=vector-string CImg<boolT> res = CImg<charT>::string(_expr); bool *pd = res._data; for (const char *ps = _expr._data; *ps; ++ps) { if (!next_is_escaped && *ps=='\\') next_is_escaped = true; if (!is_escaped && *ps=='\'') { // Non-escaped character if (!mode && ps>_expr._data && *(ps - 1)=='[') next_mode = mode = 2; // Start vector-string else if (mode==2 && *(ps + 1)==']') next_mode = !mode; // End vector-string else if (mode<2) next_mode = mode?(mode = 0):1; // Start/end char-string } *(pd++) = mode>=1 || is_escaped; mode = next_mode; is_escaped = next_is_escaped; next_is_escaped = false; } return res; } // Compilation procedure. unsigned int compile(char *ss, char *se, const unsigned int depth, unsigned int *const p_ref, const bool is_single) { if (depth>256) { cimg::strellipsize(expr,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: Call stack overflow (infinite recursion?), " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function, (ss - 4)>expr._data?"...":"", (ss - 4)>expr._data?ss - 4:expr._data, se<&expr.back()?"...":""); } char c1, c2, c3, c4; // Simplify expression when possible. do { c2 = 0; if (ss<se) { while (*ss && (cimg::is_blank(*ss) || *ss==';')) ++ss; while (se>ss && (cimg::is_blank(c1 = *(se - 1)) || c1==';')) --se; } while (*ss=='(' && *(se - 1)==')' && std::strchr(ss,')')==se - 1) { ++ss; --se; c2 = 1; } } while (c2 && ss<se); if (se<=ss || !*ss) { cimg::strellipsize(expr,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s%s Missing %s, in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op,*s_op?":":"", *s_op=='F'?"argument":"item", (ss_op - 4)>expr._data?"...":"", (ss_op - 4)>expr._data?ss_op - 4:expr._data, ss_op + std::strlen(ss_op)<&expr.back()?"...":""); } const char *const previous_s_op = s_op, *const previous_ss_op = ss_op; const unsigned int depth1 = depth + 1; unsigned int pos, p1, p2, p3, arg1, arg2, arg3, arg4, arg5, arg6; char *const se1 = se - 1, *const se2 = se - 2, *const se3 = se - 3, *const ss1 = ss + 1, *const ss2 = ss + 2, *const ss3 = ss + 3, *const ss4 = ss + 4, *const ss5 = ss + 5, *const ss6 = ss + 6, *const ss7 = ss + 7, *const ss8 = ss + 8, *s, *ps, *ns, *s0, *s1, *s2, *s3, sep = 0, end = 0; double val = 0, val1, val2; mp_func op; // 'p_ref' is a 'unsigned int[7]' used to return a reference to an image or vector value // linked to the returned memory slot (reference that cannot be determined at compile time). // p_ref[0] can be { 0 = scalar (unlinked) | 1 = vector value | 2 = image value (offset) | // 3 = image value (coordinates) | 4 = image value as a vector (offsets) | // 5 = image value as a vector (coordinates) }. // Depending on p_ref[0], the remaining p_ref[k] have the following meaning: // When p_ref[0]==0, p_ref is actually unlinked. // When p_ref[0]==1, p_ref = [ 1, vector_ind, offset ]. // When p_ref[0]==2, p_ref = [ 2, image_ind (or ~0U), is_relative, offset ]. // When p_ref[0]==3, p_ref = [ 3, image_ind (or ~0U), is_relative, x, y, z, c ]. // When p_ref[0]==4, p_ref = [ 4, image_ind (or ~0U), is_relative, offset ]. // When p_ref[0]==5, p_ref = [ 5, image_ind (or ~0U), is_relative, x, y, z ]. if (p_ref) { *p_ref = 0; p_ref[1] = p_ref[2] = p_ref[3] = p_ref[4] = p_ref[5] = p_ref[6] = ~0U; } const char saved_char = *se; *se = 0; const unsigned int clevel = level[ss - expr._data], clevel1 = clevel + 1; bool is_sth, is_relative; CImg<uintT> ref; CImg<charT> variable_name; CImgList<ulongT> l_opcode; // Look for a single value or a pre-defined variable. int nb = 0; s = ss + (*ss=='+' || *ss=='-'?1:0); if (*s=='i' || *s=='I' || *s=='n' || *s=='N') { // Particular cases : +/-NaN and +/-Inf is_sth = *ss=='-'; if (!cimg::strcasecmp(s,"inf")) { val = cimg::type<double>::inf(); nb = 1; } else if (!cimg::strcasecmp(s,"nan")) { val = cimg::type<double>::nan(); nb = 1; } if (nb==1 && is_sth) val = -val; } else if (*s=='0' && (s[1]=='x' || s[1]=='X')) { // Hexadecimal number is_sth = *ss=='-'; if (cimg_sscanf(s + 2,"%x%c",&arg1,&sep)==1) { nb = 1; val = (double)arg1; if (is_sth) val = -val; } } if (!nb) nb = cimg_sscanf(ss,"%lf%c%c",&val,&(sep=0),&(end=0)); if (nb==1) _cimg_mp_constant(val); if (nb==2 && sep=='%') _cimg_mp_constant(val/100); if (ss1==se) switch (*ss) { // One-char reserved variable case 'c' : _cimg_mp_return(reserved_label[(int)'c']!=~0U?reserved_label[(int)'c']:_cimg_mp_slot_c); case 'd' : _cimg_mp_return(reserved_label[(int)'d']!=~0U?reserved_label[(int)'d']:20); case 'e' : _cimg_mp_return(reserved_label[(int)'e']!=~0U?reserved_label[(int)'e']:27); case 'h' : _cimg_mp_return(reserved_label[(int)'h']!=~0U?reserved_label[(int)'h']:19); case 'l' : _cimg_mp_return(reserved_label[(int)'l']!=~0U?reserved_label[(int)'l']:26); case 'r' : _cimg_mp_return(reserved_label[(int)'r']!=~0U?reserved_label[(int)'r']:22); case 's' : _cimg_mp_return(reserved_label[(int)'s']!=~0U?reserved_label[(int)'s']:21); case 't' : _cimg_mp_return(reserved_label[(int)'t']!=~0U?reserved_label[(int)'t']:17); case 'w' : _cimg_mp_return(reserved_label[(int)'w']!=~0U?reserved_label[(int)'w']:18); case 'x' : _cimg_mp_return(reserved_label[(int)'x']!=~0U?reserved_label[(int)'x']:_cimg_mp_slot_x); case 'y' : _cimg_mp_return(reserved_label[(int)'y']!=~0U?reserved_label[(int)'y']:_cimg_mp_slot_y); case 'z' : _cimg_mp_return(reserved_label[(int)'z']!=~0U?reserved_label[(int)'z']:_cimg_mp_slot_z); case 'u' : if (reserved_label[(int)'u']!=~0U) _cimg_mp_return(reserved_label[(int)'u']); _cimg_mp_scalar2(mp_u,0,1); case 'g' : if (reserved_label[(int)'g']!=~0U) _cimg_mp_return(reserved_label[(int)'g']); _cimg_mp_scalar0(mp_g); case 'i' : if (reserved_label[(int)'i']!=~0U) _cimg_mp_return(reserved_label[(int)'i']); _cimg_mp_scalar0(mp_i); case 'I' : _cimg_mp_op("Variable 'I'"); if (reserved_label[(int)'I']!=~0U) _cimg_mp_return(reserved_label[(int)'I']); if (!imgin._spectrum) _cimg_mp_return(0); need_input_copy = true; pos = vector(imgin._spectrum); CImg<ulongT>::vector((ulongT)mp_Joff,pos,0,0,imgin._spectrum).move_to(code); _cimg_mp_return(pos); case 'R' : if (reserved_label[(int)'R']!=~0U) _cimg_mp_return(reserved_label[(int)'R']); need_input_copy = true; _cimg_mp_scalar6(mp_ixyzc,_cimg_mp_slot_x,_cimg_mp_slot_y,_cimg_mp_slot_z,0,0,0); case 'G' : if (reserved_label[(int)'G']!=~0U) _cimg_mp_return(reserved_label[(int)'G']); need_input_copy = true; _cimg_mp_scalar6(mp_ixyzc,_cimg_mp_slot_x,_cimg_mp_slot_y,_cimg_mp_slot_z,1,0,0); case 'B' : if (reserved_label[(int)'B']!=~0U) _cimg_mp_return(reserved_label[(int)'B']); need_input_copy = true; _cimg_mp_scalar6(mp_ixyzc,_cimg_mp_slot_x,_cimg_mp_slot_y,_cimg_mp_slot_z,2,0,0); case 'A' : if (reserved_label[(int)'A']!=~0U) _cimg_mp_return(reserved_label[(int)'A']); need_input_copy = true; _cimg_mp_scalar6(mp_ixyzc,_cimg_mp_slot_x,_cimg_mp_slot_y,_cimg_mp_slot_z,3,0,0); } else if (ss2==se) { // Two-chars reserved variable arg1 = arg2 = ~0U; if (*ss=='w' && *ss1=='h') // wh _cimg_mp_return(reserved_label[0]!=~0U?reserved_label[0]:23); if (*ss=='p' && *ss1=='i') // pi _cimg_mp_return(reserved_label[3]!=~0U?reserved_label[3]:28); if (*ss=='i') { if (*ss1>='0' && *ss1<='9') { // i0...i9 pos = 19 + *ss1 - '0'; if (reserved_label[pos]!=~0U) _cimg_mp_return(reserved_label[pos]); need_input_copy = true; _cimg_mp_scalar6(mp_ixyzc,_cimg_mp_slot_x,_cimg_mp_slot_y,_cimg_mp_slot_z,pos - 19,0,0); } switch (*ss1) { case 'm' : arg1 = 4; arg2 = 0; break; // im case 'M' : arg1 = 5; arg2 = 1; break; // iM case 'a' : arg1 = 6; arg2 = 2; break; // ia case 'v' : arg1 = 7; arg2 = 3; break; // iv case 's' : arg1 = 8; arg2 = 12; break; // is case 'p' : arg1 = 9; arg2 = 13; break; // ip case 'c' : // ic if (reserved_label[10]!=~0U) _cimg_mp_return(reserved_label[10]); if (mem_img_median==~0U) mem_img_median = imgin?constant(imgin.median()):0; _cimg_mp_return(mem_img_median); break; } } else if (*ss1=='m') switch (*ss) { case 'x' : arg1 = 11; arg2 = 4; break; // xm case 'y' : arg1 = 12; arg2 = 5; break; // ym case 'z' : arg1 = 13; arg2 = 6; break; // zm case 'c' : arg1 = 14; arg2 = 7; break; // cm } else if (*ss1=='M') switch (*ss) { case 'x' : arg1 = 15; arg2 = 8; break; // xM case 'y' : arg1 = 16; arg2 = 9; break; // yM case 'z' : arg1 = 17; arg2 = 10; break; // zM case 'c' : arg1 = 18; arg2 = 11; break; // cM } if (arg1!=~0U) { if (reserved_label[arg1]!=~0U) _cimg_mp_return(reserved_label[arg1]); if (!img_stats) { img_stats.assign(1,14,1,1,0).fill(imgin.get_stats(),false); mem_img_stats.assign(1,14,1,1,~0U); } if (mem_img_stats[arg2]==~0U) mem_img_stats[arg2] = constant(img_stats[arg2]); _cimg_mp_return(mem_img_stats[arg2]); } } else if (ss3==se) { // Three-chars reserved variable if (*ss=='w' && *ss1=='h' && *ss2=='d') // whd _cimg_mp_return(reserved_label[1]!=~0U?reserved_label[1]:24); } else if (ss4==se) { // Four-chars reserved variable if (*ss=='w' && *ss1=='h' && *ss2=='d' && *ss3=='s') // whds _cimg_mp_return(reserved_label[2]!=~0U?reserved_label[2]:25); } pos = ~0U; is_sth = false; for (s0 = ss, s = ss1; s<se1; ++s) if (*s==';' && level[s - expr._data]==clevel) { // Separator ';' arg1 = code_end._width; arg2 = compile(s0,s++,depth,0,is_single); if (code_end._width==arg1) pos = arg2; // makes 'end()' return void is_sth = true; while (*s && (cimg::is_blank(*s) || *s==';')) ++s; s0 = s; } if (is_sth) { arg1 = code_end._width; arg2 = compile(s0,se,depth,p_ref,is_single); if (code_end._width==arg1) pos = arg2; // makes 'end()' return void _cimg_mp_return(pos); } // Declare / assign variable, vector value or image value. for (s = ss1, ps = ss, ns = ss2; s<se1; ++s, ++ps, ++ns) if (*s=='=' && *ns!='=' && *ps!='=' && *ps!='>' && *ps!='<' && *ps!='!' && *ps!='+' && *ps!='-' && *ps!='*' && *ps!='/' && *ps!='%' && *ps!='>' && *ps!='<' && *ps!='&' && *ps!='|' && *ps!='^' && level[s - expr._data]==clevel) { variable_name.assign(ss,(unsigned int)(s + 1 - ss)).back() = 0; cimg::strpare(variable_name,false,true); const unsigned int l_variable_name = (unsigned int)std::strlen(variable_name); char *const ve1 = ss + l_variable_name - 1; _cimg_mp_op("Operator '='"); // Assign image value (direct). if (l_variable_name>2 && (*ss=='i' || *ss=='j' || *ss=='I' || *ss=='J') && (*ss1=='(' || *ss1=='[') && (reserved_label[(int)*ss]==~0U || *ss1=='(' || !_cimg_mp_is_vector(reserved_label[(int)*ss]))) { is_relative = *ss=='j' || *ss=='J'; if (*ss1=='[' && *ve1==']') { // i/j/I/J[_#ind,offset] = value if (!is_single) is_parallelizable = false; if (*ss2=='#') { // Index specified s0 = ss3; while (s0<ve1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; p1 = compile(ss3,s0++,depth1,0,is_single); _cimg_mp_check_list(true); } else { p1 = ~0U; s0 = ss2; } arg1 = compile(s0,ve1,depth1,0,is_single); // Offset _cimg_mp_check_type(arg1,0,1,0); arg2 = compile(s + 1,se,depth1,0,is_single); // Value to assign if (_cimg_mp_is_vector(arg2)) { p2 = ~0U; // 'p2' must be the dimension of the vector-valued operand if any if (p1==~0U) p2 = imgin._spectrum; else if (_cimg_mp_is_constant(p1)) { p3 = (unsigned int)cimg::mod((int)mem[p1],listin.width()); p2 = listin[p3]._spectrum; } if (!p2) _cimg_mp_return(0); } else p2 = 0; _cimg_mp_check_type(arg2,2,*ss>='i'?1:3,p2); if (p_ref) { *p_ref = _cimg_mp_is_vector(arg2)?4:2; p_ref[1] = p1; p_ref[2] = (unsigned int)is_relative; p_ref[3] = arg1; if (_cimg_mp_is_vector(arg2)) set_variable_vector(arg2); // Prevent from being used in further optimization else if (_cimg_mp_is_comp(arg2)) memtype[arg2] = -2; if (p1!=~0U && _cimg_mp_is_comp(p1)) memtype[p1] = -2; if (_cimg_mp_is_comp(arg1)) memtype[arg1] = -2; } if (p1!=~0U) { if (!listout) _cimg_mp_return(arg2); if (*ss>='i') CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_joff:mp_list_set_ioff), arg2,p1,arg1).move_to(code); else if (_cimg_mp_is_scalar(arg2)) CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_Joff_s:mp_list_set_Ioff_s), arg2,p1,arg1).move_to(code); else CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_Joff_v:mp_list_set_Ioff_v), arg2,p1,arg1,_cimg_mp_size(arg2)).move_to(code); } else { if (!imgout) _cimg_mp_return(arg2); if (*ss>='i') CImg<ulongT>::vector((ulongT)(is_relative?mp_set_joff:mp_set_ioff), arg2,arg1).move_to(code); else if (_cimg_mp_is_scalar(arg2)) CImg<ulongT>::vector((ulongT)(is_relative?mp_set_Joff_s:mp_set_Ioff_s), arg2,arg1).move_to(code); else CImg<ulongT>::vector((ulongT)(is_relative?mp_set_Joff_v:mp_set_Ioff_v), arg2,arg1,_cimg_mp_size(arg2)).move_to(code); } _cimg_mp_return(arg2); } if (*ss1=='(' && *ve1==')') { // i/j/I/J(_#ind,_x,_y,_z,_c) = value if (!is_single) is_parallelizable = false; if (*ss2=='#') { // Index specified s0 = ss3; while (s0<ve1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; p1 = compile(ss3,s0++,depth1,0,is_single); _cimg_mp_check_list(true); } else { p1 = ~0U; s0 = ss2; } arg1 = is_relative?0U:(unsigned int)_cimg_mp_slot_x; arg2 = is_relative?0U:(unsigned int)_cimg_mp_slot_y; arg3 = is_relative?0U:(unsigned int)_cimg_mp_slot_z; arg4 = is_relative?0U:(unsigned int)_cimg_mp_slot_c; arg5 = compile(s + 1,se,depth1,0,is_single); // Value to assign if (s0<ve1) { // X or [ X,_Y,_Z,_C ] s1 = s0; while (s1<ve1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(s0,s1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) { // Coordinates specified as a vector p2 = _cimg_mp_size(arg1); // Vector size ++arg1; if (p2>1) { arg2 = arg1 + 1; if (p2>2) { arg3 = arg2 + 1; if (p2>3) arg4 = arg3 + 1; } } } else if (s1<ve1) { // Y s2 = ++s1; while (s2<ve1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(s1,s2,depth1,0,is_single); if (s2<ve1) { // Z s3 = ++s2; while (s3<ve1 && (*s3!=',' || level[s3 - expr._data]!=clevel1)) ++s3; arg3 = compile(s2,s3,depth1,0,is_single); if (s3<ve1) arg4 = compile(++s3,ve1,depth1,0,is_single); // C } } } if (_cimg_mp_is_vector(arg5)) { p2 = ~0U; // 'p2' must be the dimension of the vector-valued operand if any if (p1==~0U) p2 = imgin._spectrum; else if (_cimg_mp_is_constant(p1)) { p3 = (unsigned int)cimg::mod((int)mem[p1],listin.width()); p2 = listin[p3]._spectrum; } if (!p2) _cimg_mp_return(0); } else p2 = 0; _cimg_mp_check_type(arg5,2,*ss>='i'?1:3,p2); if (p_ref) { *p_ref = _cimg_mp_is_vector(arg5)?5:3; p_ref[1] = p1; p_ref[2] = (unsigned int)is_relative; p_ref[3] = arg1; p_ref[4] = arg2; p_ref[5] = arg3; p_ref[6] = arg4; if (_cimg_mp_is_vector(arg5)) set_variable_vector(arg5); // Prevent from being used in further optimization else if (_cimg_mp_is_comp(arg5)) memtype[arg5] = -2; if (p1!=~0U && _cimg_mp_is_comp(p1)) memtype[p1] = -2; if (_cimg_mp_is_comp(arg1)) memtype[arg1] = -2; if (_cimg_mp_is_comp(arg2)) memtype[arg2] = -2; if (_cimg_mp_is_comp(arg3)) memtype[arg3] = -2; if (_cimg_mp_is_comp(arg4)) memtype[arg4] = -2; } if (p1!=~0U) { if (!listout) _cimg_mp_return(arg5); if (*ss>='i') CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_jxyzc:mp_list_set_ixyzc), arg5,p1,arg1,arg2,arg3,arg4).move_to(code); else if (_cimg_mp_is_scalar(arg5)) CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_Jxyz_s:mp_list_set_Ixyz_s), arg5,p1,arg1,arg2,arg3).move_to(code); else CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_Jxyz_v:mp_list_set_Ixyz_v), arg5,p1,arg1,arg2,arg3,_cimg_mp_size(arg5)).move_to(code); } else { if (!imgout) _cimg_mp_return(arg5); if (*ss>='i') CImg<ulongT>::vector((ulongT)(is_relative?mp_set_jxyzc:mp_set_ixyzc), arg5,arg1,arg2,arg3,arg4).move_to(code); else if (_cimg_mp_is_scalar(arg5)) CImg<ulongT>::vector((ulongT)(is_relative?mp_set_Jxyz_s:mp_set_Ixyz_s), arg5,arg1,arg2,arg3).move_to(code); else CImg<ulongT>::vector((ulongT)(is_relative?mp_set_Jxyz_v:mp_set_Ixyz_v), arg5,arg1,arg2,arg3,_cimg_mp_size(arg5)).move_to(code); } _cimg_mp_return(arg5); } } // Assign vector value (direct). if (l_variable_name>3 && *ve1==']' && *ss!='[') { s0 = ve1; while (s0>ss && (*s0!='[' || level[s0 - expr._data]!=clevel)) --s0; is_sth = true; // is_valid_variable_name? if (*ss>='0' && *ss<='9') is_sth = false; else for (ns = ss; ns<s0; ++ns) if (!is_varchar(*ns)) { is_sth = false; break; } if (is_sth && s0>ss) { variable_name[s0 - ss] = 0; // Remove brackets in variable name arg1 = ~0U; // Vector slot arg2 = compile(++s0,ve1,depth1,0,is_single); // Index arg3 = compile(s + 1,se,depth1,0,is_single); // Value to assign _cimg_mp_check_type(arg3,2,1,0); if (variable_name[1]) { // Multi-char variable cimglist_for(variable_def,i) if (!std::strcmp(variable_name,variable_def[i])) { arg1 = variable_pos[i]; break; } } else arg1 = reserved_label[(int)*variable_name]; // Single-char variable if (arg1==~0U) compile(ss,s0 - 1,depth1,0,is_single); // Variable does not exist -> error else { // Variable already exists if (_cimg_mp_is_scalar(arg1)) compile(ss,s,depth1,0,is_single); // Variable is not a vector -> error if (_cimg_mp_is_constant(arg2)) { // Constant index -> return corresponding variable slot directly nb = (int)mem[arg2]; if (nb>=0 && nb<(int)_cimg_mp_size(arg1)) { arg1+=nb + 1; CImg<ulongT>::vector((ulongT)mp_copy,arg1,arg3).move_to(code); _cimg_mp_return(arg1); } compile(ss,s,depth1,0,is_single); // Out-of-bounds reference -> error } // Case of non-constant index -> return assigned value + linked reference if (p_ref) { *p_ref = 1; p_ref[1] = arg1; p_ref[2] = arg2; if (_cimg_mp_is_comp(arg3)) memtype[arg3] = -2; // Prevent from being used in further optimization if (_cimg_mp_is_comp(arg2)) memtype[arg2] = -2; } CImg<ulongT>::vector((ulongT)mp_vector_set_off,arg3,arg1,(ulongT)_cimg_mp_size(arg1), arg2,arg3). move_to(code); _cimg_mp_return(arg3); } } } // Assign user-defined macro. if (l_variable_name>2 && *ve1==')' && *ss!='(') { s0 = ve1; while (s0>ss && *s0!='(') --s0; is_sth = std::strncmp(variable_name,"debug(",6) && std::strncmp(variable_name,"print(",6); // is_valid_function_name? if (*ss>='0' && *ss<='9') is_sth = false; else for (ns = ss; ns<s0; ++ns) if (!is_varchar(*ns)) { is_sth = false; break; } if (is_sth && s0>ss) { // Looks like a valid function declaration s0 = variable_name._data + (s0 - ss); *s0 = 0; s1 = variable_name._data + l_variable_name - 1; // Pointer to closing parenthesis CImg<charT>(variable_name._data,(unsigned int)(s0 - variable_name._data + 1)).move_to(macro_def,0); ++s; while (*s && cimg::is_blank(*s)) ++s; CImg<charT>(s,(unsigned int)(se - s + 1)).move_to(macro_body,0); p1 = 1; // Index of current parsed argument for (s = s0 + 1; s<=s1; ++p1, s = ns + 1) { // Parse function arguments if (p1>24) { *se = saved_char; cimg::strellipsize(variable_name,64); s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Too much specified arguments (>24) in macro " "definition '%s()', in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, variable_name._data, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } while (*s && cimg::is_blank(*s)) ++s; if (*s==')' && p1==1) break; // Function has no arguments s2 = s; // Start of the argument name is_sth = true; // is_valid_argument_name? if (*s>='0' && *s<='9') is_sth = false; else for (ns = s; ns<s1 && *ns!=',' && !cimg::is_blank(*ns); ++ns) if (!is_varchar(*ns)) { is_sth = false; break; } s3 = ns; // End of the argument name while (*ns && cimg::is_blank(*ns)) ++ns; if (!is_sth || s2==s3 || (*ns!=',' && ns!=s1)) { *se = saved_char; cimg::strellipsize(variable_name,64); s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: %s name specified for argument %u when defining " "macro '%s()', in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, is_sth?"Empty":"Invalid",p1, variable_name._data, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } if (ns==s1 || *ns==',') { // New argument found *s3 = 0; p2 = (unsigned int)(s3 - s2); // Argument length for (ps = std::strstr(macro_body[0],s2); ps; ps = std::strstr(ps,s2)) { // Replace by arg number if (!((ps>macro_body[0]._data && is_varchar(*(ps - 1))) || (ps + p2<macro_body[0].end() && is_varchar(*(ps + p2))))) { if (ps>macro_body[0]._data && *(ps - 1)=='#') { // Remove pre-number sign *(ps - 1) = (char)p1; if (ps + p2<macro_body[0].end() && *(ps + p2)=='#') { // Has pre & post number signs std::memmove(ps,ps + p2 + 1,macro_body[0].end() - ps - p2 - 1); macro_body[0]._width-=p2 + 1; } else { // Has pre number sign only std::memmove(ps,ps + p2,macro_body[0].end() - ps - p2); macro_body[0]._width-=p2; } } else if (ps + p2<macro_body[0].end() && *(ps + p2)=='#') { // Remove post-number sign *(ps++) = (char)p1; std::memmove(ps,ps + p2,macro_body[0].end() - ps - p2); macro_body[0]._width-=p2; } else { // Not near a number sign if (p2<3) { ps-=(ulongT)macro_body[0]._data; macro_body[0].resize(macro_body[0]._width - p2 + 3,1,1,1,0); ps+=(ulongT)macro_body[0]._data; } else macro_body[0]._width-=p2 - 3; std::memmove(ps + 3,ps + p2,macro_body[0].end() - ps - 3); *(ps++) = '('; *(ps++) = (char)p1; *(ps++) = ')'; } } else ++ps; } } } // Store number of arguments. macro_def[0].resize(macro_def[0]._width + 1,1,1,1,0).back() = (char)(p1 - 1); // Detect parts of function body inside a string. is_inside_string(macro_body[0]).move_to(macro_body_is_string,0); _cimg_mp_return_nan(); } } // Check if the variable name could be valid. If not, this is probably an lvalue assignment. is_sth = true; // is_valid_variable_name? const bool is_const = l_variable_name>6 && !std::strncmp(variable_name,"const ",6); s0 = variable_name._data; if (is_const) { s0+=6; while (cimg::is_blank(*s0)) ++s0; variable_name.resize(variable_name.end() - s0,1,1,1,0,0,1); } if (*variable_name>='0' && *variable_name<='9') is_sth = false; else for (ns = variable_name._data; *ns; ++ns) if (!is_varchar(*ns)) { is_sth = false; break; } // Assign variable (direct). if (is_sth) { arg3 = variable_name[1]?~0U:*variable_name; // One-char variable if (variable_name[1] && !variable_name[2]) { // Two-chars variable c1 = variable_name[0]; c2 = variable_name[1]; if (c1=='w' && c2=='h') arg3 = 0; // wh else if (c1=='p' && c2=='i') arg3 = 3; // pi else if (c1=='i') { if (c2>='0' && c2<='9') arg3 = 19 + c2 - '0'; // i0...i9 else if (c2=='m') arg3 = 4; // im else if (c2=='M') arg3 = 5; // iM else if (c2=='a') arg3 = 6; // ia else if (c2=='v') arg3 = 7; // iv else if (c2=='s') arg3 = 8; // is else if (c2=='p') arg3 = 9; // ip else if (c2=='c') arg3 = 10; // ic } else if (c2=='m') { if (c1=='x') arg3 = 11; // xm else if (c1=='y') arg3 = 12; // ym else if (c1=='z') arg3 = 13; // zm else if (c1=='c') arg3 = 14; // cm } else if (c2=='M') { if (c1=='x') arg3 = 15; // xM else if (c1=='y') arg3 = 16; // yM else if (c1=='z') arg3 = 17; // zM else if (c1=='c') arg3 = 18; // cM } } else if (variable_name[1] && variable_name[2] && !variable_name[3]) { // Three-chars variable c1 = variable_name[0]; c2 = variable_name[1]; c3 = variable_name[2]; if (c1=='w' && c2=='h' && c3=='d') arg3 = 1; // whd } else if (variable_name[1] && variable_name[2] && variable_name[3] && !variable_name[4]) { // Four-chars variable c1 = variable_name[0]; c2 = variable_name[1]; c3 = variable_name[2]; c4 = variable_name[3]; if (c1=='w' && c2=='h' && c3=='d' && c4=='s') arg3 = 2; // whds } else if (!std::strcmp(variable_name,"interpolation")) arg3 = 29; // interpolation else if (!std::strcmp(variable_name,"boundary")) arg3 = 30; // boundary arg1 = ~0U; arg2 = compile(s + 1,se,depth1,0,is_single); if (is_const) _cimg_mp_check_constant(arg2,2,0); if (arg3!=~0U) // One-char variable, or variable in reserved_labels arg1 = reserved_label[arg3]; else // Multi-char variable name : check for existing variable with same name cimglist_for(variable_def,i) if (!std::strcmp(variable_name,variable_def[i])) { arg1 = variable_pos[i]; break; } if (arg1==~0U) { // Create new variable if (_cimg_mp_is_vector(arg2)) { // Vector variable arg1 = is_comp_vector(arg2)?arg2:vector_copy(arg2); set_variable_vector(arg1); } else { // Scalar variable if (is_const) arg1 = arg2; else { arg1 = _cimg_mp_is_comp(arg2)?arg2:scalar1(mp_copy,arg2); memtype[arg1] = -1; } } if (arg3!=~0U) reserved_label[arg3] = arg1; else { if (variable_def._width>=variable_pos._width) variable_pos.resize(-200,1,1,1,0); variable_pos[variable_def._width] = arg1; variable_name.move_to(variable_def); } } else { // Variable already exists -> assign a new value if (is_const || _cimg_mp_is_constant(arg1)) { *se = saved_char; cimg::strellipsize(variable_name,64); s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Invalid assignment of %sconst variable '%s'%s, " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, _cimg_mp_is_constant(arg1)?"already-defined ":"non-", variable_name._data, !_cimg_mp_is_constant(arg1) && is_const?" as a new const variable":"", s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } _cimg_mp_check_type(arg2,2,_cimg_mp_is_vector(arg1)?3:1,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg1)) { // Vector if (_cimg_mp_is_vector(arg2)) // From vector CImg<ulongT>::vector((ulongT)mp_vector_copy,arg1,arg2,(ulongT)_cimg_mp_size(arg1)). move_to(code); else // From scalar CImg<ulongT>::vector((ulongT)mp_vector_init,arg1,1,(ulongT)_cimg_mp_size(arg1),arg2). move_to(code); } else // Scalar CImg<ulongT>::vector((ulongT)mp_copy,arg1,arg2).move_to(code); } _cimg_mp_return(arg1); } // Assign lvalue (variable name was not valid for a direct assignment). arg1 = ~0U; is_sth = (bool)std::strchr(variable_name,'?'); // Contains_ternary_operator? if (is_sth) break; // Do nothing and make ternary operator prioritary over assignment if (l_variable_name>2 && (std::strchr(variable_name,'(') || std::strchr(variable_name,'['))) { ref.assign(7); arg1 = compile(ss,s,depth1,ref,is_single); // Lvalue slot arg2 = compile(s + 1,se,depth1,0,is_single); // Value to assign if (*ref==1) { // Vector value (scalar): V[k] = scalar _cimg_mp_check_type(arg2,2,1,0); arg3 = ref[1]; // Vector slot arg4 = ref[2]; // Index if (p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); CImg<ulongT>::vector((ulongT)mp_vector_set_off,arg2,arg3,(ulongT)_cimg_mp_size(arg3),arg4,arg2). move_to(code); _cimg_mp_return(arg2); } if (*ref==2) { // Image value (scalar): i/j[_#ind,off] = scalar if (!is_single) is_parallelizable = false; _cimg_mp_check_type(arg2,2,1,0); p1 = ref[1]; // Index is_relative = (bool)ref[2]; arg3 = ref[3]; // Offset if (p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); if (p1!=~0U) { if (!listout) _cimg_mp_return(arg2); CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_joff:mp_list_set_ioff), arg2,p1,arg3).move_to(code); } else { if (!imgout) _cimg_mp_return(arg2); CImg<ulongT>::vector((ulongT)(is_relative?mp_set_joff:mp_set_ioff), arg2,arg3).move_to(code); } _cimg_mp_return(arg2); } if (*ref==3) { // Image value (scalar): i/j(_#ind,_x,_y,_z,_c) = scalar if (!is_single) is_parallelizable = false; _cimg_mp_check_type(arg2,2,1,0); p1 = ref[1]; // Index is_relative = (bool)ref[2]; arg3 = ref[3]; // X arg4 = ref[4]; // Y arg5 = ref[5]; // Z arg6 = ref[6]; // C if (p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); if (p1!=~0U) { if (!listout) _cimg_mp_return(arg2); CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_jxyzc:mp_list_set_ixyzc), arg2,p1,arg3,arg4,arg5,arg6).move_to(code); } else { if (!imgout) _cimg_mp_return(arg2); CImg<ulongT>::vector((ulongT)(is_relative?mp_set_jxyzc:mp_set_ixyzc), arg2,arg3,arg4,arg5,arg6).move_to(code); } _cimg_mp_return(arg2); } if (*ref==4) { // Image value (vector): I/J[_#ind,off] = value if (!is_single) is_parallelizable = false; _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); p1 = ref[1]; // Index is_relative = (bool)ref[2]; arg3 = ref[3]; // Offset if (p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); if (p1!=~0U) { if (!listout) _cimg_mp_return(arg2); if (_cimg_mp_is_scalar(arg2)) CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_Joff_s:mp_list_set_Ioff_s), arg2,p1,arg3).move_to(code); else CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_Joff_v:mp_list_set_Ioff_v), arg2,p1,arg3,_cimg_mp_size(arg2)).move_to(code); } else { if (!imgout) _cimg_mp_return(arg2); if (_cimg_mp_is_scalar(arg2)) CImg<ulongT>::vector((ulongT)(is_relative?mp_set_Joff_s:mp_set_Ioff_s), arg2,arg3).move_to(code); else CImg<ulongT>::vector((ulongT)(is_relative?mp_set_Joff_v:mp_set_Ioff_v), arg2,arg3,_cimg_mp_size(arg2)).move_to(code); } _cimg_mp_return(arg2); } if (*ref==5) { // Image value (vector): I/J(_#ind,_x,_y,_z,_c) = value if (!is_single) is_parallelizable = false; _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); p1 = ref[1]; // Index is_relative = (bool)ref[2]; arg3 = ref[3]; // X arg4 = ref[4]; // Y arg5 = ref[5]; // Z if (p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); if (p1!=~0U) { if (!listout) _cimg_mp_return(arg2); if (_cimg_mp_is_scalar(arg2)) CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_Jxyz_s:mp_list_set_Ixyz_s), arg2,p1,arg3,arg4,arg5).move_to(code); else CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_Jxyz_v:mp_list_set_Ixyz_v), arg2,p1,arg3,arg4,arg5,_cimg_mp_size(arg2)).move_to(code); } else { if (!imgout) _cimg_mp_return(arg2); if (_cimg_mp_is_scalar(arg2)) CImg<ulongT>::vector((ulongT)(is_relative?mp_set_Jxyz_s:mp_set_Ixyz_s), arg2,arg3,arg4,arg5).move_to(code); else CImg<ulongT>::vector((ulongT)(is_relative?mp_set_Jxyz_v:mp_set_Ixyz_v), arg2,arg3,arg4,arg5,_cimg_mp_size(arg2)).move_to(code); } _cimg_mp_return(arg2); } if (_cimg_mp_is_vector(arg1)) { // Vector variable: V = value _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg2)) // From vector CImg<ulongT>::vector((ulongT)mp_vector_copy,arg1,arg2,(ulongT)_cimg_mp_size(arg1)). move_to(code); else // From scalar CImg<ulongT>::vector((ulongT)mp_vector_init,arg1,1,(ulongT)_cimg_mp_size(arg1),arg2). move_to(code); _cimg_mp_return(arg1); } if (_cimg_mp_is_variable(arg1)) { // Scalar variable: s = scalar _cimg_mp_check_type(arg2,2,1,0); CImg<ulongT>::vector((ulongT)mp_copy,arg1,arg2).move_to(code); _cimg_mp_return(arg1); } } // No assignment expressions match -> error *se = saved_char; cimg::strellipsize(variable_name,64); s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Invalid %slvalue '%s', " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, arg1!=~0U && _cimg_mp_is_constant(arg1)?"const ":"", variable_name._data, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } // Apply unary/binary/ternary operators. The operator precedences should be the same as in C++. for (s = se2, ps = se3, ns = ps - 1; s>ss1; --s, --ps, --ns) // Here, ns = ps - 1 if (*s=='=' && (*ps=='*' || *ps=='/' || *ps=='^') && *ns==*ps && level[s - expr._data]==clevel) { // Self-operators for complex numbers only (**=,//=,^^=) _cimg_mp_op(*ps=='*'?"Operator '**='":*ps=='/'?"Operator '//='":"Operator '^^='"); ref.assign(7); arg1 = compile(ss,ns,depth1,ref,is_single); // Vector slot arg2 = compile(s + 1,se,depth1,0,is_single); // Right operand _cimg_mp_check_type(arg1,1,2,2); _cimg_mp_check_type(arg2,2,3,2); if (_cimg_mp_is_vector(arg2)) { // Complex **= complex if (*ps=='*') CImg<ulongT>::vector((ulongT)mp_complex_mul,arg1,arg1,arg2).move_to(code); else if (*ps=='/') CImg<ulongT>::vector((ulongT)mp_complex_div_vv,arg1,arg1,arg2).move_to(code); else CImg<ulongT>::vector((ulongT)mp_complex_pow_vv,arg1,arg1,arg2).move_to(code); } else { // Complex **= scalar if (*ps=='*') { if (arg2==1) _cimg_mp_return(arg1); self_vector_s(arg1,mp_self_mul,arg2); } else if (*ps=='/') { if (arg2==1) _cimg_mp_return(arg1); self_vector_s(arg1,mp_self_div,arg2); } else { if (arg2==1) _cimg_mp_return(arg1); CImg<ulongT>::vector((ulongT)mp_complex_pow_vs,arg1,arg1,arg2).move_to(code); } } // Write computed value back in image if necessary. if (*ref==4) { // Image value (vector): I/J[_#ind,off] **= value if (!is_single) is_parallelizable = false; p1 = ref[1]; // Index is_relative = (bool)ref[2]; arg3 = ref[3]; // Offset if (p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); if (p1!=~0U) { if (!listout) _cimg_mp_return(arg1); CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_Joff_v:mp_list_set_Ioff_v), arg1,p1,arg3,_cimg_mp_size(arg1)).move_to(code); } else { if (!imgout) _cimg_mp_return(arg1); CImg<ulongT>::vector((ulongT)(is_relative?mp_set_Joff_v:mp_set_Ioff_v), arg1,arg3,_cimg_mp_size(arg1)).move_to(code); } } else if (*ref==5) { // Image value (vector): I/J(_#ind,_x,_y,_z,_c) **= value if (!is_single) is_parallelizable = false; p1 = ref[1]; // Index is_relative = (bool)ref[2]; arg3 = ref[3]; // X arg4 = ref[4]; // Y arg5 = ref[5]; // Z if (p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); if (p1!=~0U) { if (!listout) _cimg_mp_return(arg1); CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_Jxyz_v:mp_list_set_Ixyz_v), arg1,p1,arg3,arg4,arg5,_cimg_mp_size(arg1)).move_to(code); } else { if (!imgout) _cimg_mp_return(arg1); CImg<ulongT>::vector((ulongT)(is_relative?mp_set_Jxyz_v:mp_set_Ixyz_v), arg1,arg3,arg4,arg5,_cimg_mp_size(arg1)).move_to(code); } } _cimg_mp_return(arg1); } for (s = se2, ps = se3, ns = ps - 1; s>ss1; --s, --ps, --ns) // Here, ns = ps - 1 if (*s=='=' && (*ps=='+' || *ps=='-' || *ps=='*' || *ps=='/' || *ps=='%' || *ps=='&' || *ps=='^' || *ps=='|' || (*ps=='>' && *ns=='>') || (*ps=='<' && *ns=='<')) && level[s - expr._data]==clevel) { // Self-operators (+=,-=,*=,/=,%=,>>=,<<=,&=,^=,|=) switch (*ps) { case '+' : op = mp_self_add; _cimg_mp_op("Operator '+='"); break; case '-' : op = mp_self_sub; _cimg_mp_op("Operator '-='"); break; case '*' : op = mp_self_mul; _cimg_mp_op("Operator '*='"); break; case '/' : op = mp_self_div; _cimg_mp_op("Operator '/='"); break; case '%' : op = mp_self_modulo; _cimg_mp_op("Operator '%='"); break; case '<' : op = mp_self_bitwise_left_shift; _cimg_mp_op("Operator '<<='"); break; case '>' : op = mp_self_bitwise_right_shift; _cimg_mp_op("Operator '>>='"); break; case '&' : op = mp_self_bitwise_and; _cimg_mp_op("Operator '&='"); break; case '|' : op = mp_self_bitwise_or; _cimg_mp_op("Operator '|='"); break; default : op = mp_self_pow; _cimg_mp_op("Operator '^='"); break; } s1 = *ps=='>' || *ps=='<'?ns:ps; ref.assign(7); arg1 = compile(ss,s1,depth1,ref,is_single); // Variable slot arg2 = compile(s + 1,se,depth1,0,is_single); // Value to apply // Check for particular case to be simplified. if ((op==mp_self_add || op==mp_self_sub) && !arg2) _cimg_mp_return(arg1); if ((op==mp_self_mul || op==mp_self_div) && arg2==1) _cimg_mp_return(arg1); // Apply operator on a copy to prevent modifying a constant or a variable. if (*ref && (_cimg_mp_is_constant(arg1) || _cimg_mp_is_vector(arg1) || _cimg_mp_is_variable(arg1))) { if (_cimg_mp_is_vector(arg1)) arg1 = vector_copy(arg1); else arg1 = scalar1(mp_copy,arg1); } if (*ref==1) { // Vector value (scalar): V[k] += scalar _cimg_mp_check_type(arg2,2,1,0); arg3 = ref[1]; // Vector slot arg4 = ref[2]; // Index if (p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); CImg<ulongT>::vector((ulongT)op,arg1,arg2).move_to(code); CImg<ulongT>::vector((ulongT)mp_vector_set_off,arg1,arg3,(ulongT)_cimg_mp_size(arg3),arg4,arg1). move_to(code); _cimg_mp_return(arg1); } if (*ref==2) { // Image value (scalar): i/j[_#ind,off] += scalar if (!is_single) is_parallelizable = false; _cimg_mp_check_type(arg2,2,1,0); p1 = ref[1]; // Index is_relative = (bool)ref[2]; arg3 = ref[3]; // Offset if (p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); CImg<ulongT>::vector((ulongT)op,arg1,arg2).move_to(code); if (p1!=~0U) { if (!listout) _cimg_mp_return(arg1); CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_joff:mp_list_set_ioff), arg1,p1,arg3).move_to(code); } else { if (!imgout) _cimg_mp_return(arg1); CImg<ulongT>::vector((ulongT)(is_relative?mp_set_joff:mp_set_ioff), arg1,arg3).move_to(code); } _cimg_mp_return(arg1); } if (*ref==3) { // Image value (scalar): i/j(_#ind,_x,_y,_z,_c) += scalar if (!is_single) is_parallelizable = false; _cimg_mp_check_type(arg2,2,1,0); p1 = ref[1]; // Index is_relative = (bool)ref[2]; arg3 = ref[3]; // X arg4 = ref[4]; // Y arg5 = ref[5]; // Z arg6 = ref[6]; // C if (p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); CImg<ulongT>::vector((ulongT)op,arg1,arg2).move_to(code); if (p1!=~0U) { if (!listout) _cimg_mp_return(arg1); CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_jxyzc:mp_list_set_ixyzc), arg1,p1,arg3,arg4,arg5,arg6).move_to(code); } else { if (!imgout) _cimg_mp_return(arg1); CImg<ulongT>::vector((ulongT)(is_relative?mp_set_jxyzc:mp_set_ixyzc), arg1,arg3,arg4,arg5,arg6).move_to(code); } _cimg_mp_return(arg1); } if (*ref==4) { // Image value (vector): I/J[_#ind,off] += value if (!is_single) is_parallelizable = false; _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); p1 = ref[1]; // Index is_relative = (bool)ref[2]; arg3 = ref[3]; // Offset if (p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); if (_cimg_mp_is_scalar(arg2)) self_vector_s(arg1,op,arg2); else self_vector_v(arg1,op,arg2); if (p1!=~0U) { if (!listout) _cimg_mp_return(arg1); CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_Joff_v:mp_list_set_Ioff_v), arg1,p1,arg3,_cimg_mp_size(arg1)).move_to(code); } else { if (!imgout) _cimg_mp_return(arg1); CImg<ulongT>::vector((ulongT)(is_relative?mp_set_Joff_v:mp_set_Ioff_v), arg1,arg3,_cimg_mp_size(arg1)).move_to(code); } _cimg_mp_return(arg1); } if (*ref==5) { // Image value (vector): I/J(_#ind,_x,_y,_z,_c) += value if (!is_single) is_parallelizable = false; _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); p1 = ref[1]; // Index is_relative = (bool)ref[2]; arg3 = ref[3]; // X arg4 = ref[4]; // Y arg5 = ref[5]; // Z if (p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); if (_cimg_mp_is_scalar(arg2)) self_vector_s(arg1,op,arg2); else self_vector_v(arg1,op,arg2); if (p1!=~0U) { if (!listout) _cimg_mp_return(arg1); CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_Jxyz_v:mp_list_set_Ixyz_v), arg1,p1,arg3,arg4,arg5,_cimg_mp_size(arg1)).move_to(code); } else { if (!imgout) _cimg_mp_return(arg1); CImg<ulongT>::vector((ulongT)(is_relative?mp_set_Jxyz_v:mp_set_Ixyz_v), arg1,arg3,arg4,arg5,_cimg_mp_size(arg1)).move_to(code); } _cimg_mp_return(arg1); } if (_cimg_mp_is_vector(arg1)) { // Vector variable: V += value _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg2)) self_vector_v(arg1,op,arg2); // Vector += vector else self_vector_s(arg1,op,arg2); // Vector += scalar _cimg_mp_return(arg1); } if (_cimg_mp_is_variable(arg1)) { // Scalar variable: s += scalar _cimg_mp_check_type(arg2,2,1,0); CImg<ulongT>::vector((ulongT)op,arg1,arg2).move_to(code); _cimg_mp_return(arg1); } variable_name.assign(ss,(unsigned int)(s - ss)).back() = 0; cimg::strpare(variable_name,false,true); *se = saved_char; s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Invalid %slvalue '%s', " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, _cimg_mp_is_constant(arg1)?"const ":"", variable_name._data, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } for (s = ss1; s<se1; ++s) if (*s=='?' && level[s - expr._data]==clevel) { // Ternary operator 'cond?expr1:expr2' _cimg_mp_op("Operator '?:'"); s1 = s + 1; while (s1<se1 && (*s1!=':' || level[s1 - expr._data]!=clevel)) ++s1; arg1 = compile(ss,s,depth1,0,is_single); _cimg_mp_check_type(arg1,1,1,0); if (_cimg_mp_is_constant(arg1)) { if ((bool)mem[arg1]) return compile(s + 1,*s1!=':'?se:s1,depth1,0,is_single); else return *s1!=':'?0:compile(++s1,se,depth1,0,is_single); } p2 = code._width; arg2 = compile(s + 1,*s1!=':'?se:s1,depth1,0,is_single); p3 = code._width; arg3 = *s1==':'?compile(++s1,se,depth1,0,is_single): _cimg_mp_is_vector(arg2)?vector(_cimg_mp_size(arg2),0):0; _cimg_mp_check_type(arg3,3,_cimg_mp_is_vector(arg2)?2:1,_cimg_mp_size(arg2)); arg4 = _cimg_mp_size(arg2); if (arg4) pos = vector(arg4); else pos = scalar(); CImg<ulongT>::vector((ulongT)mp_if,pos,arg1,arg2,arg3, p3 - p2,code._width - p3,arg4).move_to(code,p2); _cimg_mp_return(pos); } for (s = se3, ns = se2; s>ss; --s, --ns) if (*s=='|' && *ns=='|' && level[s - expr._data]==clevel) { // Logical or ('||') _cimg_mp_op("Operator '||'"); arg1 = compile(ss,s,depth1,0,is_single); _cimg_mp_check_type(arg1,1,1,0); if (arg1>0 && arg1<=16) _cimg_mp_return(1); p2 = code._width; arg2 = compile(s + 2,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,1,0); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(mem[arg1] || mem[arg2]); if (!arg1) _cimg_mp_return(arg2); pos = scalar(); CImg<ulongT>::vector((ulongT)mp_logical_or,pos,arg1,arg2,code._width - p2). move_to(code,p2); _cimg_mp_return(pos); } for (s = se3, ns = se2; s>ss; --s, --ns) if (*s=='&' && *ns=='&' && level[s - expr._data]==clevel) { // Logical and ('&&') _cimg_mp_op("Operator '&&'"); arg1 = compile(ss,s,depth1,0,is_single); _cimg_mp_check_type(arg1,1,1,0); if (!arg1) _cimg_mp_return(0); p2 = code._width; arg2 = compile(s + 2,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,1,0); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(mem[arg1] && mem[arg2]); if (arg1>0 && arg1<=16) _cimg_mp_return(arg2); pos = scalar(); CImg<ulongT>::vector((ulongT)mp_logical_and,pos,arg1,arg2,code._width - p2). move_to(code,p2); _cimg_mp_return(pos); } for (s = se2; s>ss; --s) if (*s=='|' && level[s - expr._data]==clevel) { // Bitwise or ('|') _cimg_mp_op("Operator '|'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 1,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_bitwise_or,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) { if (!arg2) _cimg_mp_return(arg1); _cimg_mp_vector2_vs(mp_bitwise_or,arg1,arg2); } if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) { if (!arg1) _cimg_mp_return(arg2); _cimg_mp_vector2_sv(mp_bitwise_or,arg1,arg2); } if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant((longT)mem[arg1] | (longT)mem[arg2]); if (!arg2) _cimg_mp_return(arg1); if (!arg1) _cimg_mp_return(arg2); _cimg_mp_scalar2(mp_bitwise_or,arg1,arg2); } for (s = se2; s>ss; --s) if (*s=='&' && level[s - expr._data]==clevel) { // Bitwise and ('&') _cimg_mp_op("Operator '&'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 1,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_bitwise_and,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_bitwise_and,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_bitwise_and,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant((longT)mem[arg1] & (longT)mem[arg2]); if (!arg1 || !arg2) _cimg_mp_return(0); _cimg_mp_scalar2(mp_bitwise_and,arg1,arg2); } for (s = se3, ns = se2; s>ss; --s, --ns) if (*s=='!' && *ns=='=' && level[s - expr._data]==clevel) { // Not equal to ('!=') _cimg_mp_op("Operator '!='"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 2,se,depth1,0,is_single); if (arg1==arg2) _cimg_mp_return(0); p1 = _cimg_mp_size(arg1); p2 = _cimg_mp_size(arg2); if (p1 || p2) { if (p1 && p2 && p1!=p2) _cimg_mp_return(1); pos = scalar(); CImg<ulongT>::vector((ulongT)mp_vector_neq,pos,arg1,p1,arg2,p2,11,1).move_to(code); _cimg_mp_return(pos); } if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(mem[arg1]!=mem[arg2]); _cimg_mp_scalar2(mp_neq,arg1,arg2); } for (s = se3, ns = se2; s>ss; --s, --ns) if (*s=='=' && *ns=='=' && level[s - expr._data]==clevel) { // Equal to ('==') _cimg_mp_op("Operator '=='"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 2,se,depth1,0,is_single); if (arg1==arg2) _cimg_mp_return(1); p1 = _cimg_mp_size(arg1); p2 = _cimg_mp_size(arg2); if (p1 || p2) { if (p1 && p2 && p1!=p2) _cimg_mp_return(0); pos = scalar(); CImg<ulongT>::vector((ulongT)mp_vector_eq,pos,arg1,p1,arg2,p2,11,1).move_to(code); _cimg_mp_return(pos); } if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(mem[arg1]==mem[arg2]); _cimg_mp_scalar2(mp_eq,arg1,arg2); } for (s = se3, ns = se2; s>ss; --s, --ns) if (*s=='<' && *ns=='=' && level[s - expr._data]==clevel) { // Less or equal than ('<=') _cimg_mp_op("Operator '<='"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 2,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_lte,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_lte,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_lte,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(mem[arg1]<=mem[arg2]); if (arg1==arg2) _cimg_mp_return(1); _cimg_mp_scalar2(mp_lte,arg1,arg2); } for (s = se3, ns = se2; s>ss; --s, --ns) if (*s=='>' && *ns=='=' && level[s - expr._data]==clevel) { // Greater or equal than ('>=') _cimg_mp_op("Operator '>='"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 2,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_gte,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_gte,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_gte,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(mem[arg1]>=mem[arg2]); if (arg1==arg2) _cimg_mp_return(1); _cimg_mp_scalar2(mp_gte,arg1,arg2); } for (s = se2, ns = se1, ps = se3; s>ss; --s, --ns, --ps) if (*s=='<' && *ns!='<' && *ps!='<' && level[s - expr._data]==clevel) { // Less than ('<') _cimg_mp_op("Operator '<'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 1,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_lt,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_lt,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_lt,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(mem[arg1]<mem[arg2]); if (arg1==arg2) _cimg_mp_return(0); _cimg_mp_scalar2(mp_lt,arg1,arg2); } for (s = se2, ns = se1, ps = se3; s>ss; --s, --ns, --ps) if (*s=='>' && *ns!='>' && *ps!='>' && level[s - expr._data]==clevel) { // Greather than ('>') _cimg_mp_op("Operator '>'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 1,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_gt,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_gt,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_gt,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(mem[arg1]>mem[arg2]); if (arg1==arg2) _cimg_mp_return(0); _cimg_mp_scalar2(mp_gt,arg1,arg2); } for (s = se3, ns = se2; s>ss; --s, --ns) if (*s=='<' && *ns=='<' && level[s - expr._data]==clevel) { // Left bit shift ('<<') _cimg_mp_op("Operator '<<'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 2,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_bitwise_left_shift,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) { if (!arg2) _cimg_mp_return(arg1); _cimg_mp_vector2_vs(mp_bitwise_left_shift,arg1,arg2); } if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_bitwise_left_shift,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant((longT)mem[arg1]<<(unsigned int)mem[arg2]); if (!arg1) _cimg_mp_return(0); if (!arg2) _cimg_mp_return(arg1); _cimg_mp_scalar2(mp_bitwise_left_shift,arg1,arg2); } for (s = se3, ns = se2; s>ss; --s, --ns) if (*s=='>' && *ns=='>' && level[s - expr._data]==clevel) { // Right bit shift ('>>') _cimg_mp_op("Operator '>>'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 2,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_bitwise_right_shift,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) { if (!arg2) _cimg_mp_return(arg1); _cimg_mp_vector2_vs(mp_bitwise_right_shift,arg1,arg2); } if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_bitwise_right_shift,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant((longT)mem[arg1]>>(unsigned int)mem[arg2]); if (!arg1) _cimg_mp_return(0); if (!arg2) _cimg_mp_return(arg1); _cimg_mp_scalar2(mp_bitwise_right_shift,arg1,arg2); } for (ns = se1, s = se2, ps = pexpr._data + (se3 - expr._data); s>ss; --ns, --s, --ps) if (*s=='+' && (*ns!='+' || ns!=se1) && *ps!='-' && *ps!='+' && *ps!='*' && *ps!='/' && *ps!='%' && *ps!='&' && *ps!='|' && *ps!='^' && *ps!='!' && *ps!='~' && *ps!='#' && (*ps!='e' || !(ps - pexpr._data>ss - expr._data && (*(ps - 1)=='.' || (*(ps - 1)>='0' && *(ps - 1)<='9')))) && level[s - expr._data]==clevel) { // Addition ('+') _cimg_mp_op("Operator '+'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 1,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (!arg2) _cimg_mp_return(arg1); if (!arg1) _cimg_mp_return(arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_add,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_add,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_add,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(mem[arg1] + mem[arg2]); if (code) { // Try to spot linear case 'a*b + c' CImg<ulongT> &pop = code.back(); if (pop[0]==(ulongT)mp_mul && _cimg_mp_is_comp(pop[1]) && (pop[1]==arg1 || pop[1]==arg2)) { arg3 = (unsigned int)pop[1]; arg4 = (unsigned int)pop[2]; arg5 = (unsigned int)pop[3]; code.remove(); CImg<ulongT>::vector((ulongT)mp_linear_add,arg3,arg4,arg5,arg3==arg2?arg1:arg2).move_to(code); _cimg_mp_return(arg3); } } if (arg2==1) _cimg_mp_scalar1(mp_increment,arg1); if (arg1==1) _cimg_mp_scalar1(mp_increment,arg2); _cimg_mp_scalar2(mp_add,arg1,arg2); } for (ns = se1, s = se2, ps = pexpr._data + (se3 - expr._data); s>ss; --ns, --s, --ps) if (*s=='-' && (*ns!='-' || ns!=se1) && *ps!='-' && *ps!='+' && *ps!='*' && *ps!='/' && *ps!='%' && *ps!='&' && *ps!='|' && *ps!='^' && *ps!='!' && *ps!='~' && *ps!='#' && (*ps!='e' || !(ps - pexpr._data>ss - expr._data && (*(ps - 1)=='.' || (*(ps - 1)>='0' && *(ps - 1)<='9')))) && level[s - expr._data]==clevel) { // Subtraction ('-') _cimg_mp_op("Operator '-'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 1,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (!arg2) _cimg_mp_return(arg1); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_sub,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_sub,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) { if (!arg1) _cimg_mp_vector1_v(mp_minus,arg2); _cimg_mp_vector2_sv(mp_sub,arg1,arg2); } if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(mem[arg1] - mem[arg2]); if (!arg1) _cimg_mp_scalar1(mp_minus,arg2); if (code) { // Try to spot linear cases 'a*b - c' and 'c - a*b' CImg<ulongT> &pop = code.back(); if (pop[0]==(ulongT)mp_mul && _cimg_mp_is_comp(pop[1]) && (pop[1]==arg1 || pop[1]==arg2)) { arg3 = (unsigned int)pop[1]; arg4 = (unsigned int)pop[2]; arg5 = (unsigned int)pop[3]; code.remove(); CImg<ulongT>::vector((ulongT)(arg3==arg1?mp_linear_sub_left:mp_linear_sub_right), arg3,arg4,arg5,arg3==arg1?arg2:arg1).move_to(code); _cimg_mp_return(arg3); } } if (arg2==1) _cimg_mp_scalar1(mp_decrement,arg1); _cimg_mp_scalar2(mp_sub,arg1,arg2); } for (s = se3, ns = se2; s>ss; --s, --ns) if (*s=='*' && *ns=='*' && level[s - expr._data]==clevel) { // Complex multiplication ('**') _cimg_mp_op("Operator '**'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 2,se,depth1,0,is_single); _cimg_mp_check_type(arg1,1,3,2); _cimg_mp_check_type(arg2,2,3,2); if (arg2==1) _cimg_mp_return(arg1); if (arg1==1) _cimg_mp_return(arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) { pos = vector(2); CImg<ulongT>::vector((ulongT)mp_complex_mul,pos,arg1,arg2).move_to(code); _cimg_mp_return(pos); } if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_mul,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_mul,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(mem[arg1]*mem[arg2]); if (!arg1 || !arg2) _cimg_mp_return(0); _cimg_mp_scalar2(mp_mul,arg1,arg2); } for (s = se3, ns = se2; s>ss; --s, --ns) if (*s=='/' && *ns=='/' && level[s - expr._data]==clevel) { // Complex division ('//') _cimg_mp_op("Operator '//'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 2,se,depth1,0,is_single); _cimg_mp_check_type(arg1,1,3,2); _cimg_mp_check_type(arg2,2,3,2); if (arg2==1) _cimg_mp_return(arg1); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) { pos = vector(2); CImg<ulongT>::vector((ulongT)mp_complex_div_vv,pos,arg1,arg2).move_to(code); _cimg_mp_return(pos); } if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_div,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) { pos = vector(2); CImg<ulongT>::vector((ulongT)mp_complex_div_sv,pos,arg1,arg2).move_to(code); _cimg_mp_return(pos); } if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(mem[arg1]/mem[arg2]); if (!arg1) _cimg_mp_return(0); _cimg_mp_scalar2(mp_div,arg1,arg2); } for (s = se2; s>ss; --s) if (*s=='*' && level[s - expr._data]==clevel) { // Multiplication ('*') _cimg_mp_op("Operator '*'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 1,se,depth1,0,is_single); p2 = _cimg_mp_size(arg2); if (p2>0 && _cimg_mp_size(arg1)==p2*p2) { // Particular case of matrix multiplication pos = vector(p2); CImg<ulongT>::vector((ulongT)mp_matrix_mul,pos,arg1,arg2,p2,p2,1).move_to(code); _cimg_mp_return(pos); } _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (arg2==1) _cimg_mp_return(arg1); if (arg1==1) _cimg_mp_return(arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_mul,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_mul,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_mul,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(mem[arg1]*mem[arg2]); if (code) { // Try to spot double multiplication 'a*b*c' CImg<ulongT> &pop = code.back(); if (pop[0]==(ulongT)mp_mul && _cimg_mp_is_comp(pop[1]) && (pop[1]==arg1 || pop[1]==arg2)) { arg3 = (unsigned int)pop[1]; arg4 = (unsigned int)pop[2]; arg5 = (unsigned int)pop[3]; code.remove(); CImg<ulongT>::vector((ulongT)mp_mul2,arg3,arg4,arg5,arg3==arg2?arg1:arg2).move_to(code); _cimg_mp_return(arg3); } } if (!arg1 || !arg2) _cimg_mp_return(0); _cimg_mp_scalar2(mp_mul,arg1,arg2); } for (s = se2; s>ss; --s) if (*s=='/' && level[s - expr._data]==clevel) { // Division ('/') _cimg_mp_op("Operator '/'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 1,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (arg2==1) _cimg_mp_return(arg1); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_div,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_div,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_div,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(mem[arg1]/mem[arg2]); if (!arg1) _cimg_mp_return(0); _cimg_mp_scalar2(mp_div,arg1,arg2); } for (s = se2, ns = se1; s>ss; --s, --ns) if (*s=='%' && *ns!='^' && level[s - expr._data]==clevel) { // Modulo ('%') _cimg_mp_op("Operator '%'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 1,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_modulo,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_modulo,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_modulo,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(cimg::mod(mem[arg1],mem[arg2])); _cimg_mp_scalar2(mp_modulo,arg1,arg2); } if (se1>ss) { if (*ss=='+' && (*ss1!='+' || (ss2<se && *ss2>='0' && *ss2<='9'))) { // Unary plus ('+') _cimg_mp_op("Operator '+'"); _cimg_mp_return(compile(ss1,se,depth1,0,is_single)); } if (*ss=='-' && (*ss1!='-' || (ss2<se && *ss2>='0' && *ss2<='9'))) { // Unary minus ('-') _cimg_mp_op("Operator '-'"); arg1 = compile(ss1,se,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_minus,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(-mem[arg1]); _cimg_mp_scalar1(mp_minus,arg1); } if (*ss=='!') { // Logical not ('!') _cimg_mp_op("Operator '!'"); if (*ss1=='!') { // '!!expr' optimized as 'bool(expr)' arg1 = compile(ss2,se,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_bool,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant((bool)mem[arg1]); _cimg_mp_scalar1(mp_bool,arg1); } arg1 = compile(ss1,se,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_logical_not,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(!mem[arg1]); _cimg_mp_scalar1(mp_logical_not,arg1); } if (*ss=='~') { // Bitwise not ('~') _cimg_mp_op("Operator '~'"); arg1 = compile(ss1,se,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_bitwise_not,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(~(unsigned int)mem[arg1]); _cimg_mp_scalar1(mp_bitwise_not,arg1); } } for (s = se3, ns = se2; s>ss; --s, --ns) if (*s=='^' && *ns=='^' && level[s - expr._data]==clevel) { // Complex power ('^^') _cimg_mp_op("Operator '^^'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 2,se,depth1,0,is_single); _cimg_mp_check_type(arg1,1,3,2); _cimg_mp_check_type(arg2,2,3,2); if (arg2==1) _cimg_mp_return(arg1); pos = vector(2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) { CImg<ulongT>::vector((ulongT)mp_complex_pow_vv,pos,arg1,arg2).move_to(code); _cimg_mp_return(pos); } if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) { CImg<ulongT>::vector((ulongT)mp_complex_pow_vs,pos,arg1,arg2).move_to(code); _cimg_mp_return(pos); } if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) { CImg<ulongT>::vector((ulongT)mp_complex_pow_sv,pos,arg1,arg2).move_to(code); _cimg_mp_return(pos); } CImg<ulongT>::vector((ulongT)mp_complex_pow_ss,pos,arg1,arg2).move_to(code); _cimg_mp_return(pos); } for (s = se2; s>ss; --s) if (*s=='^' && level[s - expr._data]==clevel) { // Power ('^') _cimg_mp_op("Operator '^'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 1,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (arg2==1) _cimg_mp_return(arg1); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_pow,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_pow,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_pow,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(std::pow(mem[arg1],mem[arg2])); switch (arg2) { case 0 : _cimg_mp_return(1); case 2 : _cimg_mp_scalar1(mp_sqr,arg1); case 3 : _cimg_mp_scalar1(mp_pow3,arg1); case 4 : _cimg_mp_scalar1(mp_pow4,arg1); default : if (_cimg_mp_is_constant(arg2)) { if (mem[arg2]==0.5) { _cimg_mp_scalar1(mp_sqrt,arg1); } else if (mem[arg2]==0.25) { _cimg_mp_scalar1(mp_pow0_25,arg1); } } _cimg_mp_scalar2(mp_pow,arg1,arg2); } } // Percentage computation. if (*se1=='%') { arg1 = compile(ss,se1,depth1,0,is_single); arg2 = _cimg_mp_is_constant(arg1)?0:constant(100); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector2_vs(mp_div,arg1,arg2); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(mem[arg1]/100); _cimg_mp_scalar2(mp_div,arg1,arg2); } is_sth = ss1<se1 && (*ss=='+' || *ss=='-') && *ss1==*ss; // is pre-? if (is_sth || (se2>ss && (*se1=='+' || *se1=='-') && *se2==*se1)) { // Pre/post-decrement and increment if ((is_sth && *ss=='+') || (!is_sth && *se1=='+')) { _cimg_mp_op("Operator '++'"); op = mp_self_increment; } else { _cimg_mp_op("Operator '--'"); op = mp_self_decrement; } ref.assign(7); arg1 = is_sth?compile(ss2,se,depth1,ref,is_single): compile(ss,se2,depth1,ref,is_single); // Variable slot // Apply operator on a copy to prevent modifying a constant or a variable. if (*ref && (_cimg_mp_is_constant(arg1) || _cimg_mp_is_vector(arg1) || _cimg_mp_is_variable(arg1))) { if (_cimg_mp_is_vector(arg1)) arg1 = vector_copy(arg1); else arg1 = scalar1(mp_copy,arg1); } if (is_sth) pos = arg1; // Determine return index, depending on pre/post action else { if (_cimg_mp_is_vector(arg1)) pos = vector_copy(arg1); else pos = scalar1(mp_copy,arg1); } if (*ref==1) { // Vector value (scalar): V[k]++ arg3 = ref[1]; // Vector slot arg4 = ref[2]; // Index if (is_sth && p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); CImg<ulongT>::vector((ulongT)op,arg1,1).move_to(code); CImg<ulongT>::vector((ulongT)mp_vector_set_off,arg1,arg3,(ulongT)_cimg_mp_size(arg3),arg4,arg1). move_to(code); _cimg_mp_return(pos); } if (*ref==2) { // Image value (scalar): i/j[_#ind,off]++ if (!is_single) is_parallelizable = false; p1 = ref[1]; // Index is_relative = (bool)ref[2]; arg3 = ref[3]; // Offset if (is_sth && p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); CImg<ulongT>::vector((ulongT)op,arg1).move_to(code); if (p1!=~0U) { if (!listout) _cimg_mp_return(pos); CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_joff:mp_list_set_ioff), arg1,p1,arg3).move_to(code); } else { if (!imgout) _cimg_mp_return(pos); CImg<ulongT>::vector((ulongT)(is_relative?mp_set_joff:mp_set_ioff), arg1,arg3).move_to(code); } _cimg_mp_return(pos); } if (*ref==3) { // Image value (scalar): i/j(_#ind,_x,_y,_z,_c)++ if (!is_single) is_parallelizable = false; p1 = ref[1]; // Index is_relative = (bool)ref[2]; arg3 = ref[3]; // X arg4 = ref[4]; // Y arg5 = ref[5]; // Z arg6 = ref[6]; // C if (is_sth && p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); CImg<ulongT>::vector((ulongT)op,arg1).move_to(code); if (p1!=~0U) { if (!listout) _cimg_mp_return(pos); CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_jxyzc:mp_list_set_ixyzc), arg1,p1,arg3,arg4,arg5,arg6).move_to(code); } else { if (!imgout) _cimg_mp_return(pos); CImg<ulongT>::vector((ulongT)(is_relative?mp_set_jxyzc:mp_set_ixyzc), arg1,arg3,arg4,arg5,arg6).move_to(code); } _cimg_mp_return(pos); } if (*ref==4) { // Image value (vector): I/J[_#ind,off]++ if (!is_single) is_parallelizable = false; p1 = ref[1]; // Index is_relative = (bool)ref[2]; arg3 = ref[3]; // Offset if (is_sth && p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); self_vector_s(arg1,op==mp_self_increment?mp_self_add:mp_self_sub,1); if (p1!=~0U) { if (!listout) _cimg_mp_return(pos); CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_Joff_v:mp_list_set_Ioff_v), arg1,p1,arg3,_cimg_mp_size(arg1)).move_to(code); } else { if (!imgout) _cimg_mp_return(pos); CImg<ulongT>::vector((ulongT)(is_relative?mp_set_Joff_v:mp_set_Ioff_v), arg1,arg3,_cimg_mp_size(arg1)).move_to(code); } _cimg_mp_return(pos); } if (*ref==5) { // Image value (vector): I/J(_#ind,_x,_y,_z,_c)++ if (!is_single) is_parallelizable = false; p1 = ref[1]; // Index is_relative = (bool)ref[2]; arg3 = ref[3]; // X arg4 = ref[4]; // Y arg5 = ref[5]; // Z if (is_sth && p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); self_vector_s(arg1,op==mp_self_increment?mp_self_add:mp_self_sub,1); if (p1!=~0U) { if (!listout) _cimg_mp_return(pos); CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_Jxyz_v:mp_list_set_Ixyz_v), arg1,p1,arg3,arg4,arg5,_cimg_mp_size(arg1)).move_to(code); } else { if (!imgout) _cimg_mp_return(pos); CImg<ulongT>::vector((ulongT)(is_relative?mp_set_Jxyz_v:mp_set_Ixyz_v), arg1,arg3,arg4,arg5,_cimg_mp_size(arg1)).move_to(code); } _cimg_mp_return(pos); } if (_cimg_mp_is_vector(arg1)) { // Vector variable: V++ self_vector_s(arg1,op==mp_self_increment?mp_self_add:mp_self_sub,1); _cimg_mp_return(pos); } if (_cimg_mp_is_variable(arg1)) { // Scalar variable: s++ CImg<ulongT>::vector((ulongT)op,arg1).move_to(code); _cimg_mp_return(pos); } if (is_sth) variable_name.assign(ss2,(unsigned int)(se - ss1)); else variable_name.assign(ss,(unsigned int)(se1 - ss)); variable_name.back() = 0; cimg::strpare(variable_name,false,true); *se = saved_char; cimg::strellipsize(variable_name,64); s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Invalid %slvalue '%s', " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, _cimg_mp_is_constant(arg1)?"const ":"", variable_name._data, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } // Array-like access to vectors and image values 'i/j/I/J[_#ind,offset,_boundary]' and 'vector[offset]'. if (*se1==']' && *ss!='[') { _cimg_mp_op("Value accessor '[]'"); is_relative = *ss=='j' || *ss=='J'; s0 = s1 = std::strchr(ss,'['); if (s0) { do { --s1; } while (cimg::is_blank(*s1)); cimg::swap(*s0,*++s1); } if ((*ss=='I' || *ss=='J') && *ss1=='[' && (reserved_label[(int)*ss]==~0U || !_cimg_mp_is_vector(reserved_label[(int)*ss]))) { // Image value as a vector if (*ss2=='#') { // Index specified s0 = ss3; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; p1 = compile(ss3,s0++,depth1,0,is_single); _cimg_mp_check_list(false); } else { p1 = ~0U; s0 = ss2; } s1 = s0; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; p2 = 1 + (p1!=~0U); arg1 = compile(s0,s1,depth1,0,is_single); // Offset _cimg_mp_check_type(arg1,p2,1,0); arg2 = ~0U; if (s1<se1) { arg2 = compile(++s1,se1,depth1,0,is_single); // Boundary _cimg_mp_check_type(arg2,p2 + 1,1,0); } if (p_ref && arg2==~0U) { *p_ref = 4; p_ref[1] = p1; p_ref[2] = (unsigned int)is_relative; p_ref[3] = arg1; if (p1!=~0U && _cimg_mp_is_comp(p1)) memtype[p1] = -2; // Prevent from being used in further optimization if (_cimg_mp_is_comp(arg1)) memtype[arg1] = -2; } p2 = ~0U; // 'p2' must be the dimension of the vector-valued operand if any if (p1==~0U) p2 = imgin._spectrum; else if (_cimg_mp_is_constant(p1)) { p3 = (unsigned int)cimg::mod((int)mem[p1],listin.width()); p2 = listin[p3]._spectrum; } if (!p2) _cimg_mp_return(0); pos = vector(p2); if (p1!=~0U) { CImg<ulongT>::vector((ulongT)(is_relative?mp_list_Joff:mp_list_Ioff), pos,p1,arg1,arg2==~0U?_cimg_mp_boundary:arg2,p2).move_to(code); } else { need_input_copy = true; CImg<ulongT>::vector((ulongT)(is_relative?mp_Joff:mp_Ioff), pos,arg1,arg2==~0U?_cimg_mp_boundary:arg2,p2).move_to(code); } _cimg_mp_return(pos); } if ((*ss=='i' || *ss=='j') && *ss1=='[' && (reserved_label[(int)*ss]==~0U || !_cimg_mp_is_vector(reserved_label[(int)*ss]))) { // Image value as a scalar if (*ss2=='#') { // Index specified s0 = ss3; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; p1 = compile(ss3,s0++,depth1,0,is_single); } else { p1 = ~0U; s0 = ss2; } s1 = s0; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(s0,s1,depth1,0,is_single); // Offset arg2 = s1<se1?compile(++s1,se1,depth1,0,is_single):~0U; // Boundary if (p_ref && arg2==~0U) { *p_ref = 2; p_ref[1] = p1; p_ref[2] = (unsigned int)is_relative; p_ref[3] = arg1; if (p1!=~0U && _cimg_mp_is_comp(p1)) memtype[p1] = -2; // Prevent from being used in further optimization if (_cimg_mp_is_comp(arg1)) memtype[arg1] = -2; } if (p1!=~0U) { if (!listin) _cimg_mp_return(0); pos = scalar3(is_relative?mp_list_joff:mp_list_ioff,p1,arg1,arg2==~0U?_cimg_mp_boundary:arg2); } else { if (!imgin) _cimg_mp_return(0); need_input_copy = true; pos = scalar2(is_relative?mp_joff:mp_ioff,arg1,arg2==~0U?_cimg_mp_boundary:arg2); } memtype[pos] = -2; // Prevent from being used in further optimization _cimg_mp_return(pos); } s0 = se1; while (s0>ss && (*s0!='[' || level[s0 - expr._data]!=clevel)) --s0; if (s0>ss) { // Vector value arg1 = compile(ss,s0,depth1,0,is_single); if (_cimg_mp_is_scalar(arg1)) { variable_name.assign(ss,(unsigned int)(s0 - ss + 1)).back() = 0; *se = saved_char; cimg::strellipsize(variable_name,64); s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Array brackets used on non-vector variable '%s', " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, variable_name._data, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } s1 = s0 + 1; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; if (s1<se1) { // Two or three arguments -> sub-vector extraction p1 = _cimg_mp_size(arg1); arg2 = compile(++s0,s1,depth1,0,is_single); // Starting index s0 = ++s1; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; arg3 = compile(s1,s0,depth1,0,is_single); // Length arg4 = s0<se1?compile(++s0,se1,depth1,0,is_single):1; // Step _cimg_mp_check_constant(arg3,2,3); arg3 = (unsigned int)mem[arg3]; pos = vector(arg3); CImg<ulongT>::vector((ulongT)mp_vector_crop,pos,arg1,p1,arg2,arg3,arg4).move_to(code); _cimg_mp_return(pos); } // One argument -> vector value reference arg2 = compile(++s0,se1,depth1,0,is_single); if (_cimg_mp_is_constant(arg2)) { // Constant index nb = (int)mem[arg2]; if (nb>=0 && nb<(int)_cimg_mp_size(arg1)) _cimg_mp_return(arg1 + 1 + nb); variable_name.assign(ss,(unsigned int)(s0 - ss)).back() = 0; *se = saved_char; cimg::strellipsize(variable_name,64); s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: Out-of-bounds reference '%s[%d]' " "(vector '%s' has dimension %u), " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function, variable_name._data,nb, variable_name._data,_cimg_mp_size(arg1), s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } if (p_ref) { *p_ref = 1; p_ref[1] = arg1; p_ref[2] = arg2; if (_cimg_mp_is_comp(arg2)) memtype[arg2] = -2; // Prevent from being used in further optimization } pos = scalar3(mp_vector_off,arg1,_cimg_mp_size(arg1),arg2); memtype[pos] = -2; // Prevent from being used in further optimization _cimg_mp_return(pos); } } // Look for a function call, an access to image value, or a parenthesis. if (*se1==')') { if (*ss=='(') _cimg_mp_return(compile(ss1,se1,depth1,p_ref,is_single)); // Simple parentheses _cimg_mp_op("Value accessor '()'"); is_relative = *ss=='j' || *ss=='J'; s0 = s1 = std::strchr(ss,'('); if (s0) { do { --s1; } while (cimg::is_blank(*s1)); cimg::swap(*s0,*++s1); } // I/J(_#ind,_x,_y,_z,_interpolation,_boundary_conditions) if ((*ss=='I' || *ss=='J') && *ss1=='(') { // Image value as scalar if (*ss2=='#') { // Index specified s0 = ss3; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; p1 = compile(ss3,s0++,depth1,0,is_single); _cimg_mp_check_list(false); } else { p1 = ~0U; s0 = ss2; } arg1 = is_relative?0U:(unsigned int)_cimg_mp_slot_x; arg2 = is_relative?0U:(unsigned int)_cimg_mp_slot_y; arg3 = is_relative?0U:(unsigned int)_cimg_mp_slot_z; arg4 = arg5 = ~0U; if (s0<se1) { s1 = s0; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(s0,s1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) { // Coordinates specified as a vector p2 = _cimg_mp_size(arg1); ++arg1; if (p2>1) { arg2 = arg1 + 1; if (p2>2) arg3 = arg2 + 1; } if (s1<se1) { s2 = ++s1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg4 = compile(s1,s2,depth1,0,is_single); arg5 = s2<se1?compile(++s2,se1,depth1,0,is_single):~0U; } } else if (s1<se1) { s2 = ++s1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(s1,s2,depth1,0,is_single); if (s2<se1) { s3 = ++s2; while (s3<se1 && (*s3!=',' || level[s3 - expr._data]!=clevel1)) ++s3; arg3 = compile(s2,s3,depth1,0,is_single); if (s3<se1) { s2 = ++s3; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg4 = compile(s3,s2,depth1,0,is_single); arg5 = s2<se1?compile(++s2,se1,depth1,0,is_single):~0U; } } } } if (p_ref && arg4==~0U && arg5==~0U) { *p_ref = 5; p_ref[1] = p1; p_ref[2] = (unsigned int)is_relative; p_ref[3] = arg1; p_ref[4] = arg2; p_ref[5] = arg3; if (p1!=~0U && _cimg_mp_is_comp(p1)) memtype[p1] = -2; // Prevent from being used in further optimization if (_cimg_mp_is_comp(arg1)) memtype[arg1] = -2; if (_cimg_mp_is_comp(arg2)) memtype[arg2] = -2; if (_cimg_mp_is_comp(arg3)) memtype[arg3] = -2; } p2 = ~0U; // 'p2' must be the dimension of the vector-valued operand if any if (p1==~0U) p2 = imgin._spectrum; else if (_cimg_mp_is_constant(p1)) { p3 = (unsigned int)cimg::mod((int)mem[p1],listin.width()); p2 = listin[p3]._spectrum; } if (!p2) _cimg_mp_return(0); pos = vector(p2); if (p1!=~0U) CImg<ulongT>::vector((ulongT)(is_relative?mp_list_Jxyz:mp_list_Ixyz), pos,p1,arg1,arg2,arg3, arg4==~0U?_cimg_mp_interpolation:arg4, arg5==~0U?_cimg_mp_boundary:arg5,p2).move_to(code); else { need_input_copy = true; CImg<ulongT>::vector((ulongT)(is_relative?mp_Jxyz:mp_Ixyz), pos,arg1,arg2,arg3, arg4==~0U?_cimg_mp_interpolation:arg4, arg5==~0U?_cimg_mp_boundary:arg5,p2).move_to(code); } _cimg_mp_return(pos); } // i/j(_#ind,_x,_y,_z,_c,_interpolation,_boundary_conditions) if ((*ss=='i' || *ss=='j') && *ss1=='(') { // Image value as scalar if (*ss2=='#') { // Index specified s0 = ss3; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; p1 = compile(ss3,s0++,depth1,0,is_single); } else { p1 = ~0U; s0 = ss2; } arg1 = is_relative?0U:(unsigned int)_cimg_mp_slot_x; arg2 = is_relative?0U:(unsigned int)_cimg_mp_slot_y; arg3 = is_relative?0U:(unsigned int)_cimg_mp_slot_z; arg4 = is_relative?0U:(unsigned int)_cimg_mp_slot_c; arg5 = arg6 = ~0U; if (s0<se1) { s1 = s0; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(s0,s1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) { // Coordinates specified as a vector p2 = _cimg_mp_size(arg1); ++arg1; if (p2>1) { arg2 = arg1 + 1; if (p2>2) { arg3 = arg2 + 1; if (p2>3) arg4 = arg3 + 1; } } if (s1<se1) { s2 = ++s1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg5 = compile(s1,s2,depth1,0,is_single); arg6 = s2<se1?compile(++s2,se1,depth1,0,is_single):~0U; } } else if (s1<se1) { s2 = ++s1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(s1,s2,depth1,0,is_single); if (s2<se1) { s3 = ++s2; while (s3<se1 && (*s3!=',' || level[s3 - expr._data]!=clevel1)) ++s3; arg3 = compile(s2,s3,depth1,0,is_single); if (s3<se1) { s2 = ++s3; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg4 = compile(s3,s2,depth1,0,is_single); if (s2<se1) { s3 = ++s2; while (s3<se1 && (*s3!=',' || level[s3 - expr._data]!=clevel1)) ++s3; arg5 = compile(s2,s3,depth1,0,is_single); arg6 = s3<se1?compile(++s3,se1,depth1,0,is_single):~0U; } } } } } if (p_ref && arg5==~0U && arg6==~0U) { *p_ref = 3; p_ref[1] = p1; p_ref[2] = (unsigned int)is_relative; p_ref[3] = arg1; p_ref[4] = arg2; p_ref[5] = arg3; p_ref[6] = arg4; if (p1!=~0U && _cimg_mp_is_comp(p1)) memtype[p1] = -2; // Prevent from being used in further optimization if (_cimg_mp_is_comp(arg1)) memtype[arg1] = -2; if (_cimg_mp_is_comp(arg2)) memtype[arg2] = -2; if (_cimg_mp_is_comp(arg3)) memtype[arg3] = -2; if (_cimg_mp_is_comp(arg4)) memtype[arg4] = -2; } if (p1!=~0U) { if (!listin) _cimg_mp_return(0); pos = scalar7(is_relative?mp_list_jxyzc:mp_list_ixyzc, p1,arg1,arg2,arg3,arg4, arg5==~0U?_cimg_mp_interpolation:arg5, arg6==~0U?_cimg_mp_boundary:arg6); } else { if (!imgin) _cimg_mp_return(0); need_input_copy = true; pos = scalar6(is_relative?mp_jxyzc:mp_ixyzc, arg1,arg2,arg3,arg4, arg5==~0U?_cimg_mp_interpolation:arg5, arg6==~0U?_cimg_mp_boundary:arg6); } memtype[pos] = -2; // Prevent from being used in further optimization _cimg_mp_return(pos); } // Mathematical functions. switch (*ss) { case '_' : if (*ss1=='(') // Skip arguments _cimg_mp_return_nan(); break; case 'a' : if (!std::strncmp(ss,"abs(",4)) { // Absolute value _cimg_mp_op("Function 'abs()'"); arg1 = compile(ss4,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_abs,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(cimg::abs(mem[arg1])); _cimg_mp_scalar1(mp_abs,arg1); } if (!std::strncmp(ss,"acos(",5)) { // Arccos _cimg_mp_op("Function 'acos()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_acos,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::acos(mem[arg1])); _cimg_mp_scalar1(mp_acos,arg1); } if (!std::strncmp(ss,"acosh(",6)) { // Hyperbolic arccosine _cimg_mp_op("Function 'acosh()'"); arg1 = compile(ss6,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_acosh,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(cimg::acosh(mem[arg1])); _cimg_mp_scalar1(mp_acosh,arg1); } if (!std::strncmp(ss,"asinh(",6)) { // Hyperbolic arcsine _cimg_mp_op("Function 'asinh()'"); arg1 = compile(ss6,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_asinh,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(cimg::asinh(mem[arg1])); _cimg_mp_scalar1(mp_asinh,arg1); } if (!std::strncmp(ss,"atanh(",6)) { // Hyperbolic arctangent _cimg_mp_op("Function 'atanh()'"); arg1 = compile(ss6,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_atanh,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(cimg::atanh(mem[arg1])); _cimg_mp_scalar1(mp_atanh,arg1); } if (!std::strncmp(ss,"arg(",4)) { // Nth argument _cimg_mp_op("Function 'arg()'"); s1 = ss4; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss4,s1,depth1,0,is_single); _cimg_mp_check_type(arg1,1,1,0); s2 = ++s1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(s1,s2,depth1,0,is_single); p2 = _cimg_mp_size(arg2); p3 = 3; CImg<ulongT>::vector((ulongT)mp_arg,0,0,p2,arg1,arg2).move_to(l_opcode); for (s = ++s2; s<se; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; arg3 = compile(s,ns,depth1,0,is_single); _cimg_mp_check_type(arg3,p3,p2?2:1,p2); CImg<ulongT>::vector(arg3).move_to(l_opcode); ++p3; s = ns; } (l_opcode>'y').move_to(opcode); opcode[2] = opcode._height; if (_cimg_mp_is_constant(arg1)) { p3-=1; // Number of args arg1 = (unsigned int)(mem[arg1]<0?mem[arg1] + p3:mem[arg1]); if (arg1<p3) _cimg_mp_return(opcode[4 + arg1]); if (p2) { pos = vector(p2); std::memset(&mem[pos] + 1,0,p2*sizeof(double)); _cimg_mp_return(pos); } else _cimg_mp_return(0); } pos = opcode[1] = p2?vector(p2):scalar(); opcode.move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"asin(",5)) { // Arcsin _cimg_mp_op("Function 'asin()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_asin,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::asin(mem[arg1])); _cimg_mp_scalar1(mp_asin,arg1); } if (!std::strncmp(ss,"atan(",5)) { // Arctan _cimg_mp_op("Function 'atan()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_atan,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::atan(mem[arg1])); _cimg_mp_scalar1(mp_atan,arg1); } if (!std::strncmp(ss,"atan2(",6)) { // Arctan2 _cimg_mp_op("Function 'atan2()'"); s1 = ss6; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss6,s1,depth1,0,is_single); arg2 = compile(++s1,se1,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_atan2,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_atan2,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_atan2,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(std::atan2(mem[arg1],mem[arg2])); _cimg_mp_scalar2(mp_atan2,arg1,arg2); } break; case 'b' : if (!std::strncmp(ss,"break(",6)) { // Complex absolute value if (pexpr[se2 - expr._data]=='(') { // no arguments? CImg<ulongT>::vector((ulongT)mp_break,_cimg_mp_slot_nan).move_to(code); _cimg_mp_return_nan(); } } if (!std::strncmp(ss,"breakpoint(",11)) { // Break point (for abort test) _cimg_mp_op("Function 'breakpoint()'"); if (pexpr[se2 - expr._data]=='(') { // no arguments? CImg<ulongT>::vector((ulongT)mp_breakpoint,_cimg_mp_slot_nan).move_to(code); _cimg_mp_return_nan(); } } if (!std::strncmp(ss,"bool(",5)) { // Boolean cast _cimg_mp_op("Function 'bool()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_bool,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant((bool)mem[arg1]); _cimg_mp_scalar1(mp_bool,arg1); } if (!std::strncmp(ss,"begin(",6)) { // Begin _cimg_mp_op("Function 'begin()'"); code.swap(code_begin); arg1 = compile(ss6,se1,depth1,p_ref,true); code.swap(code_begin); _cimg_mp_return(arg1); } break; case 'c' : if (!std::strncmp(ss,"cabs(",5)) { // Complex absolute value _cimg_mp_op("Function 'cabs()'"); arg1 = compile(ss5,se1,depth1,0,is_single); _cimg_mp_check_type(arg1,0,2,2); _cimg_mp_scalar2(mp_complex_abs,arg1 + 1,arg1 + 2); } if (!std::strncmp(ss,"carg(",5)) { // Complex argument _cimg_mp_op("Function 'carg()'"); arg1 = compile(ss5,se1,depth1,0,is_single); _cimg_mp_check_type(arg1,0,2,2); _cimg_mp_scalar2(mp_atan2,arg1 + 2,arg1 + 1); } if (!std::strncmp(ss,"cats(",5)) { // Concatenate strings _cimg_mp_op("Function 'cats()'"); CImg<ulongT>::vector((ulongT)mp_cats,0,0,0).move_to(l_opcode); arg1 = 0; for (s = ss5; s<se; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; arg1 = compile(s,ns,depth1,0,is_single); CImg<ulongT>::vector(arg1,_cimg_mp_size(arg1)).move_to(l_opcode); s = ns; } _cimg_mp_check_constant(arg1,1,3); // Last argument = output vector size l_opcode.remove(); (l_opcode>'y').move_to(opcode); p1 = (unsigned int)mem[arg1]; pos = vector(p1); opcode[1] = pos; opcode[2] = p1; opcode[3] = opcode._height; opcode.move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"cbrt(",5)) { // Cubic root _cimg_mp_op("Function 'cbrt()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_cbrt,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(cimg::cbrt(mem[arg1])); _cimg_mp_scalar1(mp_cbrt,arg1); } if (!std::strncmp(ss,"cconj(",6)) { // Complex conjugate _cimg_mp_op("Function 'cconj()'"); arg1 = compile(ss6,se1,depth1,0,is_single); _cimg_mp_check_type(arg1,0,2,2); pos = vector(2); CImg<ulongT>::vector((ulongT)mp_complex_conj,pos,arg1).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"ceil(",5)) { // Ceil _cimg_mp_op("Function 'ceil()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_ceil,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::ceil(mem[arg1])); _cimg_mp_scalar1(mp_ceil,arg1); } if (!std::strncmp(ss,"cexp(",5)) { // Complex exponential _cimg_mp_op("Function 'cexp()'"); arg1 = compile(ss5,se1,depth1,0,is_single); _cimg_mp_check_type(arg1,0,2,2); pos = vector(2); CImg<ulongT>::vector((ulongT)mp_complex_exp,pos,arg1).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"clog(",5)) { // Complex logarithm _cimg_mp_op("Function 'clog()'"); arg1 = compile(ss5,se1,depth1,0,is_single); _cimg_mp_check_type(arg1,0,2,2); pos = vector(2); CImg<ulongT>::vector((ulongT)mp_complex_log,pos,arg1).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"continue(",9)) { // Complex absolute value if (pexpr[se2 - expr._data]=='(') { // no arguments? CImg<ulongT>::vector((ulongT)mp_continue,_cimg_mp_slot_nan).move_to(code); _cimg_mp_return_nan(); } } if (!std::strncmp(ss,"copy(",5)) { // Memory copy _cimg_mp_op("Function 'copy()'"); ref.assign(14); s1 = ss5; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = p1 = compile(ss5,s1,depth1,ref,is_single); s2 = ++s1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(s1,s2,depth1,ref._data + 7,is_single); arg3 = arg4 = arg5 = ~0U; arg6 = 1; if (s2<se1) { s3 = ++s2; while (s3<se1 && (*s3!=',' || level[s3 - expr._data]!=clevel1)) ++s3; arg3 = compile(s2,s3,depth1,0,is_single); if (s3<se1) { s1 = ++s3; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg4 = compile(s3,s1,depth1,0,is_single); if (s1<se1) { s2 = ++s1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg5 = compile(s1,s2,depth1,0,is_single); arg6 = s2<se1?compile(++s2,se1,depth1,0,is_single):1; } } } if (_cimg_mp_is_vector(arg1)) { if (!ref[0]) ++arg1; else if (ref[0]>=4 && arg4==~0U) arg4 = scalar1(mp_image_whd,ref[1]); } if (_cimg_mp_is_vector(arg2)) { if (arg3==~0U) arg3 = constant(_cimg_mp_size(arg2)); if (!ref[7]) ++arg2; if (ref[7]>=4 && arg5==~0U) arg5 = scalar1(mp_image_whd,ref[8]); } if (arg3==~0U) arg3 = 1; if (arg4==~0U) arg4 = 1; if (arg5==~0U) arg5 = 1; _cimg_mp_check_type(arg3,3,1,0); _cimg_mp_check_type(arg4,4,1,0); _cimg_mp_check_type(arg5,5,1,0); _cimg_mp_check_type(arg6,5,1,0); CImg<ulongT>(1,22).move_to(code); code.back().get_shared_rows(0,7).fill((ulongT)mp_memcopy,p1,arg1,arg2,arg3,arg4,arg5,arg6); code.back().get_shared_rows(8,21).fill(ref); _cimg_mp_return(p1); } if (!std::strncmp(ss,"cos(",4)) { // Cosine _cimg_mp_op("Function 'cos()'"); arg1 = compile(ss4,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_cos,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::cos(mem[arg1])); _cimg_mp_scalar1(mp_cos,arg1); } if (!std::strncmp(ss,"cosh(",5)) { // Hyperbolic cosine _cimg_mp_op("Function 'cosh()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_cosh,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::cosh(mem[arg1])); _cimg_mp_scalar1(mp_cosh,arg1); } if (!std::strncmp(ss,"critical(",9)) { // Critical section (single thread at a time) _cimg_mp_op("Function 'critical()'"); p1 = code._width; arg1 = compile(ss + 9,se1,depth1,p_ref,true); CImg<ulongT>::vector((ulongT)mp_critical,arg1,code._width - p1).move_to(code,p1); _cimg_mp_return(arg1); } if (!std::strncmp(ss,"crop(",5)) { // Image crop _cimg_mp_op("Function 'crop()'"); if (*ss5=='#') { // Index specified s0 = ss6; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; p1 = compile(ss6,s0++,depth1,0,is_single); _cimg_mp_check_list(false); } else { p1 = ~0U; s0 = ss5; need_input_copy = true; } pos = 0; is_sth = false; // Coordinates specified as a vector? if (s0<se1) for (s = s0; s<se; ++s, ++pos) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; arg1 = compile(s,ns,depth1,0,is_single); if (!pos && _cimg_mp_is_vector(arg1)) { // Coordinates specified as a vector opcode = CImg<ulongT>::sequence(_cimg_mp_size(arg1),arg1 + 1, arg1 + (ulongT)_cimg_mp_size(arg1)); opcode.resize(1,std::min(opcode._height,4U),1,1,0).move_to(l_opcode); is_sth = true; } else { _cimg_mp_check_type(arg1,pos + 1,1,0); CImg<ulongT>::vector(arg1).move_to(l_opcode); } s = ns; } (l_opcode>'y').move_to(opcode); arg1 = 0; arg2 = (p1!=~0U); switch (opcode._height) { case 0 : case 1 : CImg<ulongT>::vector(0,0,0,0,~0U,~0U,~0U,~0U,0).move_to(opcode); break; case 2 : CImg<ulongT>::vector(*opcode,0,0,0,opcode[1],~0U,~0U,~0U,_cimg_mp_boundary).move_to(opcode); arg1 = arg2 + 2; break; case 3 : CImg<ulongT>::vector(*opcode,0,0,0,opcode[1],~0U,~0U,~0U,opcode[2]).move_to(opcode); arg1 = arg2 + 2; break; case 4 : CImg<ulongT>::vector(*opcode,opcode[1],0,0,opcode[2],opcode[3],~0U,~0U,_cimg_mp_boundary). move_to(opcode); arg1 = arg2 + (is_sth?2:3); break; case 5 : CImg<ulongT>::vector(*opcode,opcode[1],0,0,opcode[2],opcode[3],~0U,~0U,opcode[4]). move_to(opcode); arg1 = arg2 + (is_sth?2:3); break; case 6 : CImg<ulongT>::vector(*opcode,opcode[1],opcode[2],0,opcode[3],opcode[4],opcode[5],~0U, _cimg_mp_boundary).move_to(opcode); arg1 = arg2 + (is_sth?2:4); break; case 7 : CImg<ulongT>::vector(*opcode,opcode[1],opcode[2],0,opcode[3],opcode[4],opcode[5],~0U, opcode[6]).move_to(opcode); arg1 = arg2 + (is_sth?2:4); break; case 8 : CImg<ulongT>::vector(*opcode,opcode[1],opcode[2],opcode[3],opcode[4],opcode[5],opcode[6], opcode[7],_cimg_mp_boundary).move_to(opcode); arg1 = arg2 + (is_sth?2:5); break; case 9 : arg1 = arg2 + (is_sth?2:5); break; default : // Error -> too much arguments *se = saved_char; s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Too much arguments specified, " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } _cimg_mp_check_type((unsigned int)*opcode,arg2 + 1,1,0); _cimg_mp_check_type((unsigned int)opcode[1],arg2 + 1 + (is_sth?0:1),1,0); _cimg_mp_check_type((unsigned int)opcode[2],arg2 + 1 + (is_sth?0:2),1,0); _cimg_mp_check_type((unsigned int)opcode[3],arg2 + 1 + (is_sth?0:3),1,0); if (opcode[4]!=(ulongT)~0U) { _cimg_mp_check_constant((unsigned int)opcode[4],arg1,3); opcode[4] = (ulongT)mem[opcode[4]]; } if (opcode[5]!=(ulongT)~0U) { _cimg_mp_check_constant((unsigned int)opcode[5],arg1 + 1,3); opcode[5] = (ulongT)mem[opcode[5]]; } if (opcode[6]!=(ulongT)~0U) { _cimg_mp_check_constant((unsigned int)opcode[6],arg1 + 2,3); opcode[6] = (ulongT)mem[opcode[6]]; } if (opcode[7]!=(ulongT)~0U) { _cimg_mp_check_constant((unsigned int)opcode[7],arg1 + 3,3); opcode[7] = (ulongT)mem[opcode[7]]; } _cimg_mp_check_type((unsigned int)opcode[8],arg1 + 4,1,0); if (opcode[4]==(ulongT)~0U || opcode[5]==(ulongT)~0U || opcode[6]==(ulongT)~0U || opcode[7]==(ulongT)~0U) { if (p1!=~0U) { _cimg_mp_check_constant(p1,1,1); p1 = (unsigned int)cimg::mod((int)mem[p1],listin.width()); } const CImg<T> &img = p1!=~0U?listin[p1]:imgin; if (!img) { *se = saved_char; s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Cannot crop empty image when " "some xyzc-coordinates are unspecified, in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } if (opcode[4]==(ulongT)~0U) opcode[4] = (ulongT)img._width; if (opcode[5]==(ulongT)~0U) opcode[5] = (ulongT)img._height; if (opcode[6]==(ulongT)~0U) opcode[6] = (ulongT)img._depth; if (opcode[7]==(ulongT)~0U) opcode[7] = (ulongT)img._spectrum; } pos = vector((unsigned int)(opcode[4]*opcode[5]*opcode[6]*opcode[7])); CImg<ulongT>::vector((ulongT)mp_crop, pos,p1, *opcode,opcode[1],opcode[2],opcode[3], opcode[4],opcode[5],opcode[6],opcode[7], opcode[8]).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"cross(",6)) { // Cross product _cimg_mp_op("Function 'cross()'"); s1 = ss6; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss6,s1,depth1,0,is_single); arg2 = compile(++s1,se1,depth1,0,is_single); _cimg_mp_check_type(arg1,1,2,3); _cimg_mp_check_type(arg2,2,2,3); pos = vector(3); CImg<ulongT>::vector((ulongT)mp_cross,pos,arg1,arg2).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"cut(",4)) { // Cut _cimg_mp_op("Function 'cut()'"); s1 = ss4; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss4,s1,depth1,0,is_single); s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(++s1,s2,depth1,0,is_single); arg3 = compile(++s2,se1,depth1,0,is_single); _cimg_mp_check_type(arg2,2,1,0); _cimg_mp_check_type(arg3,3,1,0); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector3_vss(mp_cut,arg1,arg2,arg3); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2) && _cimg_mp_is_constant(arg3)) { val = mem[arg1]; val1 = mem[arg2]; val2 = mem[arg3]; _cimg_mp_constant(val<val1?val1:val>val2?val2:val); } _cimg_mp_scalar3(mp_cut,arg1,arg2,arg3); } /* if (!std::strncmp(ss,"convolve(",9) || !std::strncmp(ss,"correlate(",10)) { // Convolve & Correlate is_sth = *ss2=='n'; // is_convolve? _cimg_mp_op(is_sth?"Function 'convolve()'":"Function 'correlate()'"); s0 = ss + (is_sth?9:10); s1 = s0; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(s0,s1,depth1,0,is_single); s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(++s1,s2,depth1,0,is_single); arg3 = _cimg_mp_boundary; arg4 = 0; if (s2<se1) { s1 = s2 + 1; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg3 = compile(++s2,s1,depth1,0,is_single); arg4 = s1<se1?compile(++s1,se1,depth1,0,is_single):0; } _cimg_mp_check_type(arg1,1,2,0); _cimg_mp_check_type(arg2,2,2,0); _cimg_mp_check_type(arg3,3,1,0); _cimg_mp_check_type(arg4,4,1,0); p1 = _cimg_mp_size(arg1); p2 = _cimg_mp_size(arg2); pos = vector(p1); CImg<ulongT>::vector((ulongT)is_convolve?mp_matrix_convolve:mp_matrix_correlate,pos, arg1,arg2,arg4,p1,p2).move_to(code); _cimg_mp_return(pos); } */ break; case 'd' : if (*ss1=='(') { // Image depth _cimg_mp_op("Function 'd()'"); if (*ss2=='#') { // Index specified p1 = compile(ss3,se1,depth1,0,is_single); _cimg_mp_check_list(false); } else { if (ss2!=se1) break; p1 = ~0U; } pos = scalar(); CImg<ulongT>::vector((ulongT)mp_image_d,pos,p1).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"date(",5)) { // Current date or file date _cimg_mp_op("Function 'date()'"); s1 = ss5; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = ss5!=se1?compile(ss5,s1,depth1,0,is_single):~0U; arg2 = s1<se1?compile(++s1,se1,depth1,0,is_single):~0U; if (arg2!=~0U) _cimg_mp_check_type(arg2,1,2,0); pos = arg1==~0U || _cimg_mp_is_vector(arg1)?vector(arg1==~0U?7:_cimg_mp_size(arg1)):scalar(); CImg<ulongT>::vector((ulongT)mp_date,pos,_cimg_mp_size(pos), arg1,arg1==~0U?~0U:_cimg_mp_size(arg1), arg2,arg2==~0U?~0U:_cimg_mp_size(arg2)).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"debug(",6)) { // Print debug info _cimg_mp_op("Function 'debug()'"); p1 = code._width; arg1 = compile(ss6,se1,depth1,p_ref,is_single); *se1 = 0; variable_name.assign(CImg<charT>::string(ss6,true,true).unroll('y'),true); cimg::strpare(variable_name,false,true); ((CImg<ulongT>::vector((ulongT)mp_debug,arg1,0,code._width - p1), variable_name)>'y').move_to(opcode); opcode[2] = opcode._height; opcode.move_to(code,p1); *se1 = ')'; _cimg_mp_return(arg1); } if (!std::strncmp(ss,"display(",8)) { // Display memory, vector or image _cimg_mp_op("Function 'display()'"); if (pexpr[se2 - expr._data]=='(') { // no arguments? CImg<ulongT>::vector((ulongT)mp_display_memory,_cimg_mp_slot_nan).move_to(code); _cimg_mp_return_nan(); } if (*ss8!='#') { // Vector s1 = ss8; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss8,s1,depth1,0,is_single); arg2 = 0; arg3 = arg4 = arg5 = 1; if (s1<se1) { s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(s1 + 1,s2,depth1,0,is_single); if (s2<se1) { s3 = ++s2; while (s3<se1 && (*s3!=',' || level[s3 - expr._data]!=clevel1)) ++s3; arg3 = compile(s2,s3,depth1,0,is_single); if (s3<se1) { s2 = ++s3; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg4 = compile(s3,s2,depth1,0,is_single); arg5 = s2<se1?compile(++s2,se1,depth1,0,is_single):0; } } } _cimg_mp_check_type(arg2,2,1,0); _cimg_mp_check_type(arg3,3,1,0); _cimg_mp_check_type(arg4,4,1,0); _cimg_mp_check_type(arg5,5,1,0); c1 = *s1; *s1 = 0; variable_name.assign(CImg<charT>::string(ss8,true,true).unroll('y'),true); cimg::strpare(variable_name,false,true); if (_cimg_mp_is_vector(arg1)) ((CImg<ulongT>::vector((ulongT)mp_vector_print,arg1,0,(ulongT)_cimg_mp_size(arg1),0), variable_name)>'y').move_to(opcode); else ((CImg<ulongT>::vector((ulongT)mp_print,arg1,0,0), variable_name)>'y').move_to(opcode); opcode[2] = opcode._height; opcode.move_to(code); ((CImg<ulongT>::vector((ulongT)mp_display,arg1,0,(ulongT)_cimg_mp_size(arg1), arg2,arg3,arg4,arg5), variable_name)>'y').move_to(opcode); opcode[2] = opcode._height; opcode.move_to(code); *s1 = c1; _cimg_mp_return(arg1); } else { // Image p1 = compile(ss8 + 1,se1,depth1,0,is_single); _cimg_mp_check_list(true); CImg<ulongT>::vector((ulongT)mp_image_display,_cimg_mp_slot_nan,p1).move_to(code); _cimg_mp_return_nan(); } } if (!std::strncmp(ss,"det(",4)) { // Matrix determinant _cimg_mp_op("Function 'det()'"); arg1 = compile(ss4,se1,depth1,0,is_single); _cimg_mp_check_matrix_square(arg1,1); p1 = (unsigned int)cimg::round(std::sqrt((float)_cimg_mp_size(arg1))); _cimg_mp_scalar2(mp_det,arg1,p1); } if (!std::strncmp(ss,"diag(",5)) { // Diagonal matrix _cimg_mp_op("Function 'diag()'"); CImg<ulongT>::vector((ulongT)mp_diag,0,0).move_to(l_opcode); for (s = ss5; s<se; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; arg2 = compile(s,ns,depth1,0,is_single); if (_cimg_mp_is_vector(arg2)) CImg<ulongT>::sequence(_cimg_mp_size(arg2),arg2 + 1, arg2 + (ulongT)_cimg_mp_size(arg2)). move_to(l_opcode); else CImg<ulongT>::vector(arg2).move_to(l_opcode); s = ns; } (l_opcode>'y').move_to(opcode); arg1 = opcode._height - 3; pos = vector(arg1*arg1); opcode[1] = pos; opcode[2] = opcode._height; opcode.move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"dot(",4)) { // Dot product _cimg_mp_op("Function 'dot()'"); s1 = ss4; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss4,s1,depth1,0,is_single); arg2 = compile(++s1,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) { _cimg_mp_check_type(arg2,2,2,_cimg_mp_size(arg1)); _cimg_mp_scalar3(mp_dot,arg1,arg2,_cimg_mp_size(arg1)); } _cimg_mp_check_type(arg2,2,1,0); _cimg_mp_scalar2(mp_mul,arg1,arg2); } if (!std::strncmp(ss,"do(",3)) { // Do..while _cimg_mp_op("Function 'do()'"); s0 = *ss2=='('?ss3:ss8; s1 = s0; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = code._width; arg6 = mempos; p1 = compile(s0,s1,depth1,0,is_single); // Body arg2 = code._width; p2 = s1<se1?compile(++s1,se1,depth1,0,is_single):p1; // Condition _cimg_mp_check_type(p2,2,1,0); CImg<ulongT>::vector((ulongT)mp_do,p1,p2,arg2 - arg1,code._width - arg2,_cimg_mp_size(p1), p1>=arg6 && !_cimg_mp_is_constant(p1), p2>=arg6 && !_cimg_mp_is_constant(p2)).move_to(code,arg1); _cimg_mp_return(p1); } if (!std::strncmp(ss,"draw(",5)) { // Draw image if (!is_single) is_parallelizable = false; _cimg_mp_op("Function 'draw()'"); if (*ss5=='#') { // Index specified s0 = ss6; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; p1 = compile(ss6,s0++,depth1,0,is_single); _cimg_mp_check_list(true); } else { p1 = ~0U; s0 = ss5; } s1 = s0; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(s0,s1,depth1,0,is_single); arg2 = is_relative?0U:(unsigned int)_cimg_mp_slot_x; arg3 = is_relative?0U:(unsigned int)_cimg_mp_slot_y; arg4 = is_relative?0U:(unsigned int)_cimg_mp_slot_z; arg5 = is_relative?0U:(unsigned int)_cimg_mp_slot_c; s0 = se1; if (s1<se1) { s0 = s1 + 1; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; arg2 = compile(++s1,s0,depth1,0,is_single); if (_cimg_mp_is_vector(arg2)) { // Coordinates specified as a vector p2 = _cimg_mp_size(arg2); ++arg2; if (p2>1) { arg3 = arg2 + 1; if (p2>2) { arg4 = arg3 + 1; if (p2>3) arg5 = arg4 + 1; } } ++s0; is_sth = true; } else { if (s0<se1) { is_sth = p1!=~0U; s1 = s0 + 1; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg3 = compile(++s0,s1,depth1,0,is_single); _cimg_mp_check_type(arg3,is_sth?4:3,1,0); if (s1<se1) { s0 = s1 + 1; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; arg4 = compile(++s1,s0,depth1,0,is_single); _cimg_mp_check_type(arg4,is_sth?5:4,1,0); if (s0<se1) { s1 = s0 + 1; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg5 = compile(++s0,s1,depth1,0,is_single); _cimg_mp_check_type(arg5,is_sth?6:5,1,0); s0 = ++s1; } } } is_sth = false; } } l_opcode.assign(); // Don't use 'opcode': it can be modified by further calls to 'compile()'! CImg<ulongT>::vector((ulongT)mp_draw,arg1,(ulongT)_cimg_mp_size(arg1),p1,arg2,arg3,arg4,arg5, 0,0,0,0,1,(ulongT)~0U,0,1).move_to(l_opcode); arg2 = arg3 = arg4 = arg5 = ~0U; p2 = p1!=~0U?0:1; if (s0<se1) { s1 = s0; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg2 = compile(s0,s1,depth1,0,is_single); _cimg_mp_check_type(arg2,p2 + (is_sth?3:6),1,0); if (s1<se1) { s0 = s1 + 1; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; arg3 = compile(++s1,s0,depth1,0,is_single); _cimg_mp_check_type(arg3,p2 + (is_sth?4:7),1,0); if (s0<se1) { s1 = s0 + 1; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg4 = compile(++s0,s1,depth1,0,is_single); _cimg_mp_check_type(arg4,p2 + (is_sth?5:8),1,0); if (s1<se1) { s0 = s1 + 1; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; arg5 = compile(++s1,s0,depth1,0,is_single); _cimg_mp_check_type(arg5,p2 + (is_sth?6:9),1,0); } } } } if (s0<s1) s0 = s1; l_opcode(0,8) = (ulongT)arg2; l_opcode(0,9) = (ulongT)arg3; l_opcode(0,10) = (ulongT)arg4; l_opcode(0,11) = (ulongT)arg5; if (s0<se1) { s1 = s0 + 1; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg6 = compile(++s0,s1,depth1,0,is_single); _cimg_mp_check_type(arg6,0,1,0); l_opcode(0,12) = arg6; if (s1<se1) { s0 = s1 + 1; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; p2 = compile(++s1,s0,depth1,0,is_single); _cimg_mp_check_type(p2,0,2,0); l_opcode(0,13) = p2; l_opcode(0,14) = _cimg_mp_size(p2); p3 = s0<se1?compile(++s0,se1,depth1,0,is_single):1; _cimg_mp_check_type(p3,0,1,0); l_opcode(0,15) = p3; } } l_opcode[0].move_to(code); _cimg_mp_return(arg1); } break; case 'e' : if (!std::strncmp(ss,"echo(",5)) { // Echo _cimg_mp_op("Function 'echo()'"); CImg<ulongT>::vector((ulongT)mp_echo,_cimg_mp_slot_nan,0).move_to(l_opcode); for (s = ss5; s<se; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; arg1 = compile(s,ns,depth1,0,is_single); CImg<ulongT>::vector(arg1,_cimg_mp_size(arg1)).move_to(l_opcode); s = ns; } (l_opcode>'y').move_to(opcode); opcode[2] = opcode._height; opcode.move_to(code); _cimg_mp_return_nan(); } if (!std::strncmp(ss,"eig(",4)) { // Matrix eigenvalues/eigenvector _cimg_mp_op("Function 'eig()'"); arg1 = compile(ss4,se1,depth1,0,is_single); _cimg_mp_check_matrix_square(arg1,1); p1 = (unsigned int)cimg::round(std::sqrt((float)_cimg_mp_size(arg1))); pos = vector((p1 + 1)*p1); CImg<ulongT>::vector((ulongT)mp_matrix_eig,pos,arg1,p1).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"end(",4)) { // End _cimg_mp_op("Function 'end()'"); code.swap(code_end); compile(ss4,se1,depth1,p_ref,true); code.swap(code_end); _cimg_mp_return_nan(); } if (!std::strncmp(ss,"ellipse(",8)) { // Ellipse/circle drawing if (!is_single) is_parallelizable = false; _cimg_mp_op("Function 'ellipse()'"); if (*ss8=='#') { // Index specified s0 = ss + 9; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; p1 = compile(ss + 9,s0++,depth1,0,is_single); _cimg_mp_check_list(true); } else { p1 = ~0U; s0 = ss8; } if (s0==se1) compile(s0,se1,depth1,0,is_single); // 'missing' argument error CImg<ulongT>::vector((ulongT)mp_ellipse,_cimg_mp_slot_nan,0,p1).move_to(l_opcode); for (s = s0; s<se; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; arg2 = compile(s,ns,depth1,0,is_single); if (_cimg_mp_is_vector(arg2)) CImg<ulongT>::sequence(_cimg_mp_size(arg2),arg2 + 1, arg2 + (ulongT)_cimg_mp_size(arg2)). move_to(l_opcode); else CImg<ulongT>::vector(arg2).move_to(l_opcode); s = ns; } (l_opcode>'y').move_to(opcode); opcode[2] = opcode._height; opcode.move_to(code); _cimg_mp_return_nan(); } if (!std::strncmp(ss,"ext(",4)) { // Extern _cimg_mp_op("Function 'ext()'"); if (!is_single) is_parallelizable = false; CImg<ulongT>::vector((ulongT)mp_ext,0,0).move_to(l_opcode); pos = 1; for (s = ss4; s<se; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; arg1 = compile(s,ns,depth1,0,is_single); CImg<ulongT>::vector(arg1,_cimg_mp_size(arg1)).move_to(l_opcode); s = ns; } (l_opcode>'y').move_to(opcode); pos = scalar(); opcode[1] = pos; opcode[2] = opcode._height; opcode.move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"exp(",4)) { // Exponential _cimg_mp_op("Function 'exp()'"); arg1 = compile(ss4,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_exp,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::exp(mem[arg1])); _cimg_mp_scalar1(mp_exp,arg1); } if (!std::strncmp(ss,"eye(",4)) { // Identity matrix _cimg_mp_op("Function 'eye()'"); arg1 = compile(ss4,se1,depth1,0,is_single); _cimg_mp_check_constant(arg1,1,3); p1 = (unsigned int)mem[arg1]; pos = vector(p1*p1); CImg<ulongT>::vector((ulongT)mp_eye,pos,p1).move_to(code); _cimg_mp_return(pos); } break; case 'f' : if (!std::strncmp(ss,"fact(",5)) { // Factorial _cimg_mp_op("Function 'fact()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_factorial,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(cimg::factorial((int)mem[arg1])); _cimg_mp_scalar1(mp_factorial,arg1); } if (!std::strncmp(ss,"fibo(",5)) { // Fibonacci _cimg_mp_op("Function 'fibo()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_fibonacci,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(cimg::fibonacci((int)mem[arg1])); _cimg_mp_scalar1(mp_fibonacci,arg1); } if (!std::strncmp(ss,"find(",5)) { // Find _cimg_mp_op("Function 'find()'"); // First argument: data to look at. s0 = ss5; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; if (*ss5=='#') { // Index specified p1 = compile(ss6,s0,depth1,0,is_single); _cimg_mp_check_list(false); arg1 = ~0U; } else { // Vector specified arg1 = compile(ss5,s0,depth1,0,is_single); _cimg_mp_check_type(arg1,1,2,0); p1 = ~0U; } // Second argument: data to find. s1 = ++s0; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg2 = compile(s0,s1,depth1,0,is_single); // Third and fourth arguments: search direction and starting index. arg3 = 1; arg4 = _cimg_mp_slot_nan; if (s1<se1) { s0 = s1 + 1; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; arg3 = compile(++s1,s0,depth1,0,is_single); _cimg_mp_check_type(arg3,3,1,0); if (s0<se1) { arg4 = compile(++s0,se1,depth1,0,is_single); _cimg_mp_check_type(arg4,4,1,0); } } if (p1!=~0U) { if (_cimg_mp_is_vector(arg2)) _cimg_mp_scalar5(mp_list_find_seq,p1,arg2,_cimg_mp_size(arg2),arg3,arg4); _cimg_mp_scalar4(mp_list_find,p1,arg2,arg3,arg4); } if (_cimg_mp_is_vector(arg2)) _cimg_mp_scalar6(mp_find_seq,arg1,_cimg_mp_size(arg1),arg2,_cimg_mp_size(arg2),arg3,arg4); _cimg_mp_scalar5(mp_find,arg1,_cimg_mp_size(arg1),arg2,arg3,arg4); } if (*ss1=='o' && *ss2=='r' && *ss3=='(') { // For loop _cimg_mp_op("Function 'for()'"); s1 = ss4; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; s3 = s2 + 1; while (s3<se1 && (*s3!=',' || level[s3 - expr._data]!=clevel1)) ++s3; arg1 = code._width; p1 = compile(ss4,s1,depth1,0,is_single); // Init arg2 = code._width; p2 = compile(++s1,s2,depth1,0,is_single); // Cond arg3 = code._width; arg6 = mempos; if (s3<se1) { // Body + post p3 = compile(s3 + 1,se1,depth1,0,is_single); // Body arg4 = code._width; pos = compile(++s2,s3,depth1,0,is_single); // Post } else { p3 = compile(++s2,se1,depth1,0,is_single); // Body only arg4 = pos = code._width; } _cimg_mp_check_type(p2,2,1,0); arg5 = _cimg_mp_size(pos); CImg<ulongT>::vector((ulongT)mp_for,p3,(ulongT)_cimg_mp_size(p3),p2,arg2 - arg1,arg3 - arg2, arg4 - arg3,code._width - arg4, p3>=arg6 && !_cimg_mp_is_constant(p3), p2>=arg6 && !_cimg_mp_is_constant(p2)).move_to(code,arg1); _cimg_mp_return(p3); } if (!std::strncmp(ss,"floor(",6)) { // Floor _cimg_mp_op("Function 'floor()'"); arg1 = compile(ss6,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_floor,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::floor(mem[arg1])); _cimg_mp_scalar1(mp_floor,arg1); } if (!std::strncmp(ss,"fsize(",6)) { // File size _cimg_mp_op("Function 'fsize()'"); arg1 = compile(ss6,se1,depth1,0,is_single); _cimg_mp_check_type(arg1,1,2,0); pos = scalar(); CImg<ulongT>::vector((ulongT)mp_fsize,pos,arg1,(ulongT)_cimg_mp_size(arg1)).move_to(code); _cimg_mp_return(pos); } break; case 'g' : if (!std::strncmp(ss,"gauss(",6)) { // Gaussian function _cimg_mp_op("Function 'gauss()'"); s1 = ss6; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss6,s1,depth1,0,is_single); arg2 = arg3 = 1; if (s1<se1) { s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(++s1,s2,depth1,0,is_single); arg3 = s2<se1?compile(++s2,se1,depth1,0,is_single):1; } _cimg_mp_check_type(arg2,2,1,0); _cimg_mp_check_type(arg3,3,1,0); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector3_vss(mp_gauss,arg1,arg2,arg3); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2) && _cimg_mp_is_constant(arg3)) { val1 = mem[arg1]; val2 = mem[arg2]; _cimg_mp_constant(std::exp(-val1*val1/(2*val2*val2))/(mem[arg3]?std::sqrt(2*val2*val2*cimg::PI):1)); } _cimg_mp_scalar3(mp_gauss,arg1,arg2,arg3); } if (!std::strncmp(ss,"gcd(",4)) { // Gcd _cimg_mp_op("Function 'gcd()'"); s1 = ss4; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss4,s1,depth1,0,is_single); arg2 = compile(++s1,se1,depth1,0,is_single); _cimg_mp_check_type(arg1,1,1,0); _cimg_mp_check_type(arg2,2,1,0); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(cimg::gcd((long)mem[arg1],(long)mem[arg2])); _cimg_mp_scalar2(mp_gcd,arg1,arg2); } break; case 'h' : if (*ss1=='(') { // Image height _cimg_mp_op("Function 'h()'"); if (*ss2=='#') { // Index specified p1 = compile(ss3,se1,depth1,0,is_single); _cimg_mp_check_list(false); } else { if (ss2!=se1) break; p1 = ~0U; } pos = scalar(); CImg<ulongT>::vector((ulongT)mp_image_h,pos,p1).move_to(code); _cimg_mp_return(pos); } break; case 'i' : if (*ss1=='c' && *ss2=='(') { // Image median _cimg_mp_op("Function 'ic()'"); if (*ss3=='#') { // Index specified p1 = compile(ss4,se1,depth1,0,is_single); _cimg_mp_check_list(false); } else { if (ss3!=se1) break; p1 = ~0U; } pos = scalar(); CImg<ulongT>::vector((ulongT)mp_image_median,pos,p1).move_to(code); _cimg_mp_return(pos); } if (*ss1=='f' && *ss2=='(') { // If..then[..else.] _cimg_mp_op("Function 'if()'"); s1 = ss3; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg1 = compile(ss3,s1,depth1,0,is_single); _cimg_mp_check_type(arg1,1,1,0); if (_cimg_mp_is_constant(arg1)) { if ((bool)mem[arg1]) return compile(++s1,s2,depth1,0,is_single); else return s2<se1?compile(++s2,se1,depth1,0,is_single):0; } p2 = code._width; arg2 = compile(++s1,s2,depth1,0,is_single); p3 = code._width; arg3 = s2<se1?compile(++s2,se1,depth1,0,is_single): _cimg_mp_is_vector(arg2)?vector(_cimg_mp_size(arg2),0):0; _cimg_mp_check_type(arg3,3,_cimg_mp_is_vector(arg2)?2:1,_cimg_mp_size(arg2)); arg4 = _cimg_mp_size(arg2); if (arg4) pos = vector(arg4); else pos = scalar(); CImg<ulongT>::vector((ulongT)mp_if,pos,arg1,arg2,arg3, p3 - p2,code._width - p3,arg4).move_to(code,p2); _cimg_mp_return(pos); } if (!std::strncmp(ss,"int(",4)) { // Integer cast _cimg_mp_op("Function 'int()'"); arg1 = compile(ss4,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_int,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant((longT)mem[arg1]); _cimg_mp_scalar1(mp_int,arg1); } if (!std::strncmp(ss,"inv(",4)) { // Matrix/scalar inversion _cimg_mp_op("Function 'inv()'"); arg1 = compile(ss4,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) { _cimg_mp_check_matrix_square(arg1,1); p1 = (unsigned int)cimg::round(std::sqrt((float)_cimg_mp_size(arg1))); pos = vector(p1*p1); CImg<ulongT>::vector((ulongT)mp_matrix_inv,pos,arg1,p1).move_to(code); _cimg_mp_return(pos); } if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(1/mem[arg1]); _cimg_mp_scalar2(mp_div,1,arg1); } if (*ss1=='s') { // Family of 'is_?()' functions if (!std::strncmp(ss,"isbool(",7)) { // Is boolean? _cimg_mp_op("Function 'isbool()'"); if (ss7==se1) _cimg_mp_return(0); try { arg1 = compile(ss7,se1,depth1,0,is_single); } catch(CImgException&) { _cimg_mp_return(0); } if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_isbool,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_return(mem[arg1]==0. || mem[arg1]==1.); _cimg_mp_scalar1(mp_isbool,arg1); } if (!std::strncmp(ss,"isdir(",6)) { // Is directory? _cimg_mp_op("Function 'isdir()'"); arg1 = compile(ss6,se1,depth1,0,is_single); if (_cimg_mp_is_scalar(arg1)) _cimg_mp_return(0); pos = scalar(); CImg<ulongT>::vector((ulongT)mp_isdir,pos,arg1,(ulongT)_cimg_mp_size(arg1)).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"isfile(",7)) { // Is file? _cimg_mp_op("Function 'isfile()'"); arg1 = compile(ss7,se1,depth1,0,is_single); if (_cimg_mp_is_scalar(arg1)) _cimg_mp_return(0); pos = scalar(); CImg<ulongT>::vector((ulongT)mp_isfile,pos,arg1,(ulongT)_cimg_mp_size(arg1)).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"isin(",5)) { // Is in sequence/vector? if (ss5>=se1) _cimg_mp_return(0); _cimg_mp_op("Function 'isin()'"); pos = scalar(); CImg<ulongT>::vector((ulongT)mp_isin,pos,0).move_to(l_opcode); for (s = ss5; s<se; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; arg1 = compile(s,ns,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) CImg<ulongT>::sequence(_cimg_mp_size(arg1),arg1 + 1, arg1 + (ulongT)_cimg_mp_size(arg1)). move_to(l_opcode); else CImg<ulongT>::vector(arg1).move_to(l_opcode); s = ns; } (l_opcode>'y').move_to(opcode); opcode[2] = opcode._height; opcode.move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"isinf(",6)) { // Is infinite? _cimg_mp_op("Function 'isinf()'"); if (ss6==se1) _cimg_mp_return(0); arg1 = compile(ss6,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_isinf,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_return((unsigned int)cimg::type<double>::is_inf(mem[arg1])); _cimg_mp_scalar1(mp_isinf,arg1); } if (!std::strncmp(ss,"isint(",6)) { // Is integer? _cimg_mp_op("Function 'isint()'"); if (ss6==se1) _cimg_mp_return(0); try { arg1 = compile(ss6,se1,depth1,0,is_single); } catch(CImgException&) { _cimg_mp_return(0); } if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_isint,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_return((unsigned int)(cimg::mod(mem[arg1],1.)==0)); _cimg_mp_scalar1(mp_isint,arg1); } if (!std::strncmp(ss,"isnan(",6)) { // Is NaN? _cimg_mp_op("Function 'isnan()'"); if (ss6==se1) _cimg_mp_return(0); arg1 = compile(ss6,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_isnan,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_return((unsigned int)cimg::type<double>::is_nan(mem[arg1])); _cimg_mp_scalar1(mp_isnan,arg1); } if (!std::strncmp(ss,"isnum(",6)) { // Is number? _cimg_mp_op("Function 'isnum()'"); val = 0; if (cimg_sscanf(ss6,"%lf%c%c",&val,&sep,&end)==2 && sep==')') _cimg_mp_return(1); _cimg_mp_return(0); } if (!std::strncmp(ss,"isexpr(",7)) { // Is valid expression? _cimg_mp_op("Function 'isexpr()'"); if (ss7==se1) _cimg_mp_return(0); try { arg1 = compile(ss7,se1,depth1,0,is_single); } catch (CImgException&) { _cimg_mp_return(0); } _cimg_mp_return(1); } } break; case 'l' : if (*ss1=='(') { // Size of image list _cimg_mp_op("Function 'l()'"); if (ss2!=se1) break; _cimg_mp_scalar0(mp_list_l); } if (!std::strncmp(ss,"log(",4)) { // Natural logarithm _cimg_mp_op("Function 'log()'"); arg1 = compile(ss4,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_log,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::log(mem[arg1])); _cimg_mp_scalar1(mp_log,arg1); } if (!std::strncmp(ss,"log2(",5)) { // Base-2 logarithm _cimg_mp_op("Function 'log2()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_log2,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(cimg::log2(mem[arg1])); _cimg_mp_scalar1(mp_log2,arg1); } if (!std::strncmp(ss,"log10(",6)) { // Base-10 logarithm _cimg_mp_op("Function 'log10()'"); arg1 = compile(ss6,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_log10,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::log10(mem[arg1])); _cimg_mp_scalar1(mp_log10,arg1); } if (!std::strncmp(ss,"lowercase(",10)) { // Lower case _cimg_mp_op("Function 'lowercase()'"); arg1 = compile(ss + 10,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_lowercase,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(cimg::lowercase(mem[arg1])); _cimg_mp_scalar1(mp_lowercase,arg1); } break; case 'm' : if (!std::strncmp(ss,"mul(",4)) { // Matrix multiplication _cimg_mp_op("Function 'mul()'"); s1 = ss4; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss4,s1,depth1,0,is_single); s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(++s1,s2,depth1,0,is_single); arg3 = s2<se1?compile(++s2,se1,depth1,0,is_single):1; _cimg_mp_check_type(arg1,1,2,0); _cimg_mp_check_type(arg2,2,2,0); _cimg_mp_check_constant(arg3,3,3); p1 = _cimg_mp_size(arg1); p2 = _cimg_mp_size(arg2); p3 = (unsigned int)mem[arg3]; arg5 = p2/p3; arg4 = p1/arg5; if (arg4*arg5!=p1 || arg5*p3!=p2) { *se = saved_char; s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Types of first and second arguments ('%s' and '%s') " "do not match with third argument 'nb_colsB=%u', " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, s_type(arg1)._data,s_type(arg2)._data,p3, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } pos = vector(arg4*p3); CImg<ulongT>::vector((ulongT)mp_matrix_mul,pos,arg1,arg2,arg4,arg5,p3).move_to(code); _cimg_mp_return(pos); } break; case 'n' : if (!std::strncmp(ss,"narg(",5)) { // Number of arguments _cimg_mp_op("Function 'narg()'"); if (ss5>=se1) _cimg_mp_return(0); arg1 = 0; for (s = ss5; s<se; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; ++arg1; s = ns; } _cimg_mp_constant(arg1); } if ((cimg_sscanf(ss,"norm%u%c",&(arg1=~0U),&sep)==2 && sep=='(') || !std::strncmp(ss,"norminf(",8) || !std::strncmp(ss,"norm(",5) || (!std::strncmp(ss,"norm",4) && ss5<se1 && (s=std::strchr(ss5,'('))!=0)) { // Lp norm _cimg_mp_op("Function 'normP()'"); if (*ss4=='(') { arg1 = 2; s = ss5; } else if (*ss4=='i' && *ss5=='n' && *ss6=='f' && *ss7=='(') { arg1 = ~0U; s = ss8; } else if (arg1==~0U) { arg1 = compile(ss4,s++,depth1,0,is_single); _cimg_mp_check_constant(arg1,0,2); arg1 = (unsigned int)mem[arg1]; } else s = std::strchr(ss4,'(') + 1; pos = scalar(); switch (arg1) { case 0 : CImg<ulongT>::vector((ulongT)mp_norm0,pos,0).move_to(l_opcode); break; case 1 : CImg<ulongT>::vector((ulongT)mp_norm1,pos,0).move_to(l_opcode); break; case 2 : CImg<ulongT>::vector((ulongT)mp_norm2,pos,0).move_to(l_opcode); break; case ~0U : CImg<ulongT>::vector((ulongT)mp_norminf,pos,0).move_to(l_opcode); break; default : CImg<ulongT>::vector((ulongT)mp_normp,pos,0,(ulongT)(arg1==~0U?-1:(int)arg1)). move_to(l_opcode); } for ( ; s<se; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; arg2 = compile(s,ns,depth1,0,is_single); if (_cimg_mp_is_vector(arg2)) CImg<ulongT>::sequence(_cimg_mp_size(arg2),arg2 + 1, arg2 + (ulongT)_cimg_mp_size(arg2)). move_to(l_opcode); else CImg<ulongT>::vector(arg2).move_to(l_opcode); s = ns; } (l_opcode>'y').move_to(opcode); if (arg1>0 && opcode._height==4) // Special case with one argument and p>=1 _cimg_mp_scalar1(mp_abs,opcode[3]); opcode[2] = opcode._height; opcode.move_to(code); _cimg_mp_return(pos); } break; case 'p' : if (!std::strncmp(ss,"permut(",7)) { // Number of permutations _cimg_mp_op("Function 'permut()'"); s1 = ss7; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg1 = compile(ss7,s1,depth1,0,is_single); arg2 = compile(++s1,s2,depth1,0,is_single); arg3 = compile(++s2,se1,depth1,0,is_single); _cimg_mp_check_type(arg1,1,1,0); _cimg_mp_check_type(arg2,2,1,0); _cimg_mp_check_type(arg3,3,1,0); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2) && _cimg_mp_is_constant(arg3)) _cimg_mp_constant(cimg::permutations((int)mem[arg1],(int)mem[arg2],(bool)mem[arg3])); _cimg_mp_scalar3(mp_permutations,arg1,arg2,arg3); } if (!std::strncmp(ss,"polygon(",8)) { // Polygon/line drawing if (!is_single) is_parallelizable = false; _cimg_mp_op("Function 'polygon()'"); if (*ss8=='#') { // Index specified s0 = ss + 9; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; p1 = compile(ss + 9,s0++,depth1,0,is_single); _cimg_mp_check_list(true); } else { p1 = ~0U; s0 = ss8; } if (s0==se1) compile(s0,se1,depth1,0,is_single); // 'missing' argument error CImg<ulongT>::vector((ulongT)mp_polygon,_cimg_mp_slot_nan,0,p1).move_to(l_opcode); for (s = s0; s<se; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; arg2 = compile(s,ns,depth1,0,is_single); if (_cimg_mp_is_vector(arg2)) CImg<ulongT>::sequence(_cimg_mp_size(arg2),arg2 + 1, arg2 + (ulongT)_cimg_mp_size(arg2)). move_to(l_opcode); else CImg<ulongT>::vector(arg2).move_to(l_opcode); s = ns; } (l_opcode>'y').move_to(opcode); opcode[2] = opcode._height; opcode.move_to(code); _cimg_mp_return_nan(); } if (!std::strncmp(ss,"print(",6) || !std::strncmp(ss,"prints(",7)) { // Print expressions is_sth = ss[5]=='s'; // is prints() _cimg_mp_op(is_sth?"Function 'prints()'":"Function 'print()'"); s0 = is_sth?ss7:ss6; if (*s0!='#' || is_sth) { // Regular expression for (s = s0; s<se; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; pos = compile(s,ns,depth1,p_ref,is_single); c1 = *ns; *ns = 0; variable_name.assign(CImg<charT>::string(s,true,true).unroll('y'),true); cimg::strpare(variable_name,false,true); if (_cimg_mp_is_vector(pos)) // Vector ((CImg<ulongT>::vector((ulongT)mp_vector_print,pos,0,(ulongT)_cimg_mp_size(pos),is_sth?1:0), variable_name)>'y').move_to(opcode); else // Scalar ((CImg<ulongT>::vector((ulongT)mp_print,pos,0,is_sth?1:0), variable_name)>'y').move_to(opcode); opcode[2] = opcode._height; opcode.move_to(code); *ns = c1; s = ns; } _cimg_mp_return(pos); } else { // Image p1 = compile(ss7,se1,depth1,0,is_single); _cimg_mp_check_list(true); CImg<ulongT>::vector((ulongT)mp_image_print,_cimg_mp_slot_nan,p1).move_to(code); _cimg_mp_return_nan(); } } if (!std::strncmp(ss,"pseudoinv(",10)) { // Matrix/scalar pseudo-inversion _cimg_mp_op("Function 'pseudoinv()'"); s1 = ss + 10; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss + 10,s1,depth1,0,is_single); arg2 = s1<se1?compile(++s1,se1,depth1,0,is_single):1; _cimg_mp_check_type(arg1,1,2,0); _cimg_mp_check_constant(arg2,2,3); p1 = _cimg_mp_size(arg1); p2 = (unsigned int)mem[arg2]; p3 = p1/p2; if (p3*p2!=p1) { *se = saved_char; s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Type of first argument ('%s') " "does not match with second argument 'nb_colsA=%u', " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, s_type(arg1)._data,p2, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } pos = vector(p1); CImg<ulongT>::vector((ulongT)mp_matrix_pseudoinv,pos,arg1,p2,p3).move_to(code); _cimg_mp_return(pos); } break; case 'r' : if (!std::strncmp(ss,"resize(",7)) { // Vector or image resize _cimg_mp_op("Function 'resize()'"); if (*ss7!='#') { // Vector s1 = ss7; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss7,s1,depth1,0,is_single); s2 = ++s1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(s1,s2,depth1,0,is_single); arg3 = 1; arg4 = 0; if (s2<se1) { s1 = ++s2; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg3 = compile(s2,s1,depth1,0,is_single); arg4 = s1<se1?compile(++s1,se1,depth1,0,is_single):0; } _cimg_mp_check_constant(arg2,2,3); arg2 = (unsigned int)mem[arg2]; _cimg_mp_check_type(arg3,3,1,0); _cimg_mp_check_type(arg4,4,1,0); pos = vector(arg2); CImg<ulongT>::vector((ulongT)mp_vector_resize,pos,arg2,arg1,(ulongT)_cimg_mp_size(arg1), arg3,arg4).move_to(code); _cimg_mp_return(pos); } else { // Image if (!is_single) is_parallelizable = false; s0 = ss8; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; p1 = compile(ss8,s0++,depth1,0,is_single); _cimg_mp_check_list(true); l_opcode.assign(); // Don't use 'opcode': it can be modified by further calls to 'compile()'! CImg<ulongT>::vector((ulongT)mp_image_resize,_cimg_mp_slot_nan,p1,~0U,~0U,~0U,~0U,1,0,0,0,0,0). move_to(l_opcode); pos = 0; for (s = s0; s<se && pos<10; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; arg1 = compile(s,ns,depth1,0,is_single); _cimg_mp_check_type(arg1,pos + 2,1,0); l_opcode(0,pos + 3) = arg1; s = ns; ++pos; } if (pos<1 || pos>10) { *se = saved_char; s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: %s arguments, in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, pos<1?"Missing":"Too much", s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } l_opcode[0].move_to(code); _cimg_mp_return_nan(); } } if (!std::strncmp(ss,"reverse(",8)) { // Vector reverse _cimg_mp_op("Function 'reverse()'"); arg1 = compile(ss8,se1,depth1,0,is_single); if (!_cimg_mp_is_vector(arg1)) _cimg_mp_return(arg1); p1 = _cimg_mp_size(arg1); pos = vector(p1); CImg<ulongT>::vector((ulongT)mp_vector_reverse,pos,arg1,p1).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"rol(",4) || !std::strncmp(ss,"ror(",4)) { // Bitwise rotation _cimg_mp_op(ss[2]=='l'?"Function 'rol()'":"Function 'ror()'"); s1 = ss4; while (s1<se1 && (*s1!=',' || level[s1-expr._data]!=clevel1)) ++s1; arg1 = compile(ss4,s1,depth1,0,is_single); arg2 = s1<se1?compile(++s1,se1,depth1,0,is_single):1; _cimg_mp_check_type(arg2,2,1,0); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector2_vs(*ss2=='l'?mp_rol:mp_ror,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(*ss2=='l'?cimg::rol(mem[arg1],(unsigned int)mem[arg2]): cimg::ror(mem[arg1],(unsigned int)mem[arg2])); _cimg_mp_scalar2(*ss2=='l'?mp_rol:mp_ror,arg1,arg2); } if (!std::strncmp(ss,"rot(",4)) { // 2D/3D rotation matrix _cimg_mp_op("Function 'rot()'"); s1 = ss4; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss4,s1,depth1,0,is_single); if (s1<se1) { // 3D rotation _cimg_mp_check_type(arg1,1,3,3); is_sth = false; // Is coordinates as vector? if (_cimg_mp_is_vector(arg1)) { // Coordinates specified as a vector is_sth = true; p2 = _cimg_mp_size(arg1); ++arg1; arg2 = arg3 = 0; if (p2>1) { arg2 = arg1 + 1; if (p2>2) arg3 = arg2 + 1; } arg4 = compile(++s1,se1,depth1,0,is_single); } else { s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(++s1,s2,depth1,0,is_single); s3 = s2 + 1; while (s3<se1 && (*s3!=',' || level[s3 - expr._data]!=clevel1)) ++s3; arg3 = compile(++s2,s3,depth1,0,is_single); arg4 = compile(++s3,se1,depth1,0,is_single); _cimg_mp_check_type(arg2,2,1,0); _cimg_mp_check_type(arg3,3,1,0); } _cimg_mp_check_type(arg4,is_sth?2:4,1,0); pos = vector(9); CImg<ulongT>::vector((ulongT)mp_rot3d,pos,arg1,arg2,arg3,arg4).move_to(code); } else { // 2D rotation _cimg_mp_check_type(arg1,1,1,0); pos = vector(4); CImg<ulongT>::vector((ulongT)mp_rot2d,pos,arg1).move_to(code); } _cimg_mp_return(pos); } if (!std::strncmp(ss,"round(",6)) { // Value rounding _cimg_mp_op("Function 'round()'"); s1 = ss6; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss6,s1,depth1,0,is_single); arg2 = 1; arg3 = 0; if (s1<se1) { s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(++s1,s2,depth1,0,is_single); arg3 = s2<se1?compile(++s2,se1,depth1,0,is_single):0; } _cimg_mp_check_type(arg2,2,1,0); _cimg_mp_check_type(arg3,3,1,0); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector3_vss(mp_round,arg1,arg2,arg3); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2) && _cimg_mp_is_constant(arg3)) _cimg_mp_constant(cimg::round(mem[arg1],mem[arg2],(int)mem[arg3])); _cimg_mp_scalar3(mp_round,arg1,arg2,arg3); } break; case 's' : if (*ss1=='(') { // Image spectrum _cimg_mp_op("Function 's()'"); if (*ss2=='#') { // Index specified p1 = compile(ss3,se1,depth1,0,is_single); _cimg_mp_check_list(false); } else { if (ss2!=se1) break; p1 = ~0U; } pos = scalar(); CImg<ulongT>::vector((ulongT)mp_image_s,pos,p1).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"same(",5)) { // Test if operands have the same values _cimg_mp_op("Function 'same()'"); s1 = ss5; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss5,s1,depth1,0,is_single); s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(++s1,s2,depth1,0,is_single); arg3 = 11; arg4 = 1; if (s2<se1) { s3 = s2 + 1; while (s3<se1 && (*s3!=',' || level[s3 - expr._data]!=clevel1)) ++s3; arg3 = compile(++s2,s3,depth1,0,is_single); _cimg_mp_check_type(arg3,3,1,0); arg4 = s3<se1?compile(++s3,se1,depth1,0,is_single):1; } p1 = _cimg_mp_size(arg1); p2 = _cimg_mp_size(arg2); _cimg_mp_scalar6(mp_vector_eq,arg1,p1,arg2,p2,arg3,arg4); } if (!std::strncmp(ss,"shift(",6)) { // Shift vector _cimg_mp_op("Function 'shift()'"); s1 = ss6; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss6,s1,depth1,0,is_single); arg2 = 1; arg3 = 0; if (s1<se1) { s0 = ++s1; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; arg2 = compile(s1,s0,depth1,0,is_single); arg3 = s0<se1?compile(++s0,se1,depth1,0,is_single):0; } _cimg_mp_check_type(arg1,1,2,0); _cimg_mp_check_type(arg2,2,1,0); _cimg_mp_check_type(arg3,3,1,0); p1 = _cimg_mp_size(arg1); pos = vector(p1); CImg<ulongT>::vector((ulongT)mp_shift,pos,arg1,p1,arg2,arg3).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"sign(",5)) { // Sign _cimg_mp_op("Function 'sign()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_sign,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(cimg::sign(mem[arg1])); _cimg_mp_scalar1(mp_sign,arg1); } if (!std::strncmp(ss,"sin(",4)) { // Sine _cimg_mp_op("Function 'sin()'"); arg1 = compile(ss4,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_sin,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::sin(mem[arg1])); _cimg_mp_scalar1(mp_sin,arg1); } if (!std::strncmp(ss,"sinc(",5)) { // Sine cardinal _cimg_mp_op("Function 'sinc()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_sinc,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(cimg::sinc(mem[arg1])); _cimg_mp_scalar1(mp_sinc,arg1); } if (!std::strncmp(ss,"sinh(",5)) { // Hyperbolic sine _cimg_mp_op("Function 'sinh()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_sinh,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::sinh(mem[arg1])); _cimg_mp_scalar1(mp_sinh,arg1); } if (!std::strncmp(ss,"size(",5)) { // Vector size _cimg_mp_op("Function 'size()'"); arg1 = compile(ss5,se1,depth1,0,is_single); _cimg_mp_constant(_cimg_mp_is_scalar(arg1)?0:_cimg_mp_size(arg1)); } if (!std::strncmp(ss,"solve(",6)) { // Solve linear system _cimg_mp_op("Function 'solve()'"); s1 = ss6; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss6,s1,depth1,0,is_single); s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(++s1,s2,depth1,0,is_single); arg3 = s2<se1?compile(++s2,se1,depth1,0,is_single):1; _cimg_mp_check_type(arg1,1,2,0); _cimg_mp_check_type(arg2,2,2,0); _cimg_mp_check_constant(arg3,3,3); p1 = _cimg_mp_size(arg1); p2 = _cimg_mp_size(arg2); p3 = (unsigned int)mem[arg3]; arg5 = p2/p3; arg4 = p1/arg5; if (arg4*arg5!=p1 || arg5*p3!=p2) { *se = saved_char; s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Types of first and second arguments ('%s' and '%s') " "do not match with third argument 'nb_colsB=%u', " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, s_type(arg1)._data,s_type(arg2)._data,p3, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } pos = vector(arg4*p3); CImg<ulongT>::vector((ulongT)mp_solve,pos,arg1,arg2,arg4,arg5,p3).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"sort(",5)) { // Sort vector _cimg_mp_op("Function 'sort()'"); if (*ss5!='#') { // Vector s1 = ss5; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss5,s1,depth1,0,is_single); arg2 = arg3 = 1; if (s1<se1) { s0 = ++s1; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; arg2 = compile(s1,s0,depth1,0,is_single); arg3 = s0<se1?compile(++s0,se1,depth1,0,is_single):1; } _cimg_mp_check_type(arg1,1,2,0); _cimg_mp_check_type(arg2,2,1,0); _cimg_mp_check_constant(arg3,3,3); arg3 = (unsigned int)mem[arg3]; p1 = _cimg_mp_size(arg1); if (p1%arg3) { *se = saved_char; s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Invalid specified chunk size (%u) for first argument " "('%s'), in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, arg3,s_type(arg1)._data, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } pos = vector(p1); CImg<ulongT>::vector((ulongT)mp_sort,pos,arg1,p1,arg2,arg3).move_to(code); _cimg_mp_return(pos); } else { // Image s1 = ss6; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; p1 = compile(ss6,s1,depth1,0,is_single); arg1 = 1; arg2 = constant(-1.); if (s1<se1) { s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg1 = compile(++s1,s2,depth1,0,is_single); if (s2<se1) arg2 = compile(++s2,se1,depth1,0,is_single); } _cimg_mp_check_type(arg1,2,1,0); _cimg_mp_check_type(arg2,3,1,0); _cimg_mp_check_list(true); CImg<ulongT>::vector((ulongT)mp_image_sort,_cimg_mp_slot_nan,p1,arg1,arg2).move_to(code); _cimg_mp_return_nan(); } } if (!std::strncmp(ss,"sqr(",4)) { // Square _cimg_mp_op("Function 'sqr()'"); arg1 = compile(ss4,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_sqr,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(cimg::sqr(mem[arg1])); _cimg_mp_scalar1(mp_sqr,arg1); } if (!std::strncmp(ss,"sqrt(",5)) { // Square root _cimg_mp_op("Function 'sqrt()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_sqrt,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::sqrt(mem[arg1])); _cimg_mp_scalar1(mp_sqrt,arg1); } if (!std::strncmp(ss,"srand(",6)) { // Set RNG seed _cimg_mp_op("Function 'srand()'"); arg1 = ss6<se1?compile(ss6,se1,depth1,0,is_single):~0U; if (arg1!=~0U) { _cimg_mp_check_type(arg1,1,1,0); _cimg_mp_scalar1(mp_srand,arg1); } _cimg_mp_scalar0(mp_srand0); } if (!std::strncmp(ss,"stats(",6)) { // Image statistics _cimg_mp_op("Function 'stats()'"); if (*ss6=='#') { // Index specified p1 = compile(ss7,se1,depth1,0,is_single); _cimg_mp_check_list(false); } else { if (ss6!=se1) break; p1 = ~0U; } pos = vector(14); CImg<ulongT>::vector((ulongT)mp_image_stats,pos,p1).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"stov(",5)) { // String to double _cimg_mp_op("Function 'stov()'"); s1 = ss5; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss5,s1,depth1,0,is_single); arg2 = arg3 = 0; if (s1<se1) { s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(++s1,s2,depth1,0,is_single); arg3 = s2<se1?compile(++s2,se1,depth1,0,is_single):0; } _cimg_mp_check_type(arg2,2,1,0); _cimg_mp_check_type(arg3,3,1,0); p1 = _cimg_mp_size(arg1); pos = scalar(); CImg<ulongT>::vector((ulongT)mp_stov,pos,arg1,p1,arg2,arg3).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"svd(",4)) { // Matrix SVD _cimg_mp_op("Function 'svd()'"); s1 = ss4; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss4,s1,depth1,0,is_single); arg2 = s1<se1?compile(++s1,se1,depth1,0,is_single):1; _cimg_mp_check_type(arg1,1,2,0); _cimg_mp_check_constant(arg2,2,3); p1 = _cimg_mp_size(arg1); p2 = (unsigned int)mem[arg2]; p3 = p1/p2; if (p3*p2!=p1) { *se = saved_char; s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Type of first argument ('%s') " "does not match with second argument 'nb_colsA=%u', " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, s_type(arg1)._data,p2, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } pos = vector(p1 + p2 + p2*p2); CImg<ulongT>::vector((ulongT)mp_matrix_svd,pos,arg1,p2,p3).move_to(code); _cimg_mp_return(pos); } break; case 't' : if (!std::strncmp(ss,"tan(",4)) { // Tangent _cimg_mp_op("Function 'tan()'"); arg1 = compile(ss4,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_tan,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::tan(mem[arg1])); _cimg_mp_scalar1(mp_tan,arg1); } if (!std::strncmp(ss,"tanh(",5)) { // Hyperbolic tangent _cimg_mp_op("Function 'tanh()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_tanh,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::tanh(mem[arg1])); _cimg_mp_scalar1(mp_tanh,arg1); } if (!std::strncmp(ss,"trace(",6)) { // Matrix trace _cimg_mp_op("Function 'trace()'"); arg1 = compile(ss6,se1,depth1,0,is_single); _cimg_mp_check_matrix_square(arg1,1); p1 = (unsigned int)cimg::round(std::sqrt((float)_cimg_mp_size(arg1))); _cimg_mp_scalar2(mp_trace,arg1,p1); } if (!std::strncmp(ss,"transp(",7)) { // Matrix transpose _cimg_mp_op("Function 'transp()'"); s1 = ss7; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss7,s1,depth1,0,is_single); arg2 = compile(++s1,se1,depth1,0,is_single); _cimg_mp_check_type(arg1,1,2,0); _cimg_mp_check_constant(arg2,2,3); p1 = _cimg_mp_size(arg1); p2 = (unsigned int)mem[arg2]; p3 = p1/p2; if (p2*p3!=p1) { *se = saved_char; s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Size of first argument ('%s') does not match " "second argument 'nb_cols=%u', in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, s_type(arg1)._data,p2, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } pos = vector(p3*p2); CImg<ulongT>::vector((ulongT)mp_transp,pos,arg1,p2,p3).move_to(code); _cimg_mp_return(pos); } break; case 'u' : if (*ss1=='(') { // Random value with uniform distribution _cimg_mp_op("Function 'u()'"); if (*ss2==')') _cimg_mp_scalar2(mp_u,0,1); s1 = ss2; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss2,s1,depth1,0,is_single); if (s1<se1) arg2 = compile(++s1,se1,depth1,0,is_single); else { arg2 = arg1; arg1 = 0; } _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_u,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_u,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_u,arg1,arg2); _cimg_mp_scalar2(mp_u,arg1,arg2); } if (!std::strncmp(ss,"unref(",6)) { // Un-reference variable _cimg_mp_op("Function 'unref()'"); arg1 = ~0U; for (s0 = ss6; s0<se1; s0 = s1) { if (s0>ss6 && *s0==',') ++s0; s1 = s0; while (s1<se1 && *s1!=',') ++s1; c1 = *s1; if (s1>s0) { *s1 = 0; arg2 = arg3 = ~0U; if (s0[0]=='w' && s0[1]=='h' && !s0[2]) arg1 = reserved_label[arg3 = 0]; else if (s0[0]=='w' && s0[1]=='h' && s0[2]=='d' && !s0[3]) arg1 = reserved_label[arg3 = 1]; else if (s0[0]=='w' && s0[1]=='h' && s0[2]=='d' && s0[3]=='s' && !s0[4]) arg1 = reserved_label[arg3 = 2]; else if (s0[0]=='p' && s0[1]=='i' && !s0[2]) arg1 = reserved_label[arg3 = 3]; else if (s0[0]=='i' && s0[1]=='m' && !s0[2]) arg1 = reserved_label[arg3 = 4]; else if (s0[0]=='i' && s0[1]=='M' && !s0[2]) arg1 = reserved_label[arg3 = 5]; else if (s0[0]=='i' && s0[1]=='a' && !s0[2]) arg1 = reserved_label[arg3 = 6]; else if (s0[0]=='i' && s0[1]=='v' && !s0[2]) arg1 = reserved_label[arg3 = 7]; else if (s0[0]=='i' && s0[1]=='s' && !s0[2]) arg1 = reserved_label[arg3 = 8]; else if (s0[0]=='i' && s0[1]=='p' && !s0[2]) arg1 = reserved_label[arg3 = 9]; else if (s0[0]=='i' && s0[1]=='c' && !s0[2]) arg1 = reserved_label[arg3 = 10]; else if (s0[0]=='x' && s0[1]=='m' && !s0[2]) arg1 = reserved_label[arg3 = 11]; else if (s0[0]=='y' && s0[1]=='m' && !s0[2]) arg1 = reserved_label[arg3 = 12]; else if (s0[0]=='z' && s0[1]=='m' && !s0[2]) arg1 = reserved_label[arg3 = 13]; else if (s0[0]=='c' && s0[1]=='m' && !s0[2]) arg1 = reserved_label[arg3 = 14]; else if (s0[0]=='x' && s0[1]=='M' && !s0[2]) arg1 = reserved_label[arg3 = 15]; else if (s0[0]=='y' && s0[1]=='M' && !s0[2]) arg1 = reserved_label[arg3 = 16]; else if (s0[0]=='z' && s0[1]=='M' && !s0[2]) arg1 = reserved_label[arg3 = 17]; else if (s0[0]=='c' && s0[1]=='M' && !s0[2]) arg1 = reserved_label[arg3 = 18]; else if (s0[0]=='i' && s0[1]>='0' && s0[1]<='9' && !s0[2]) arg1 = reserved_label[arg3 = 19 + s0[1] - '0']; else if (!std::strcmp(s0,"interpolation")) arg1 = reserved_label[arg3 = 29]; else if (!std::strcmp(s0,"boundary")) arg1 = reserved_label[arg3 = 30]; else if (s0[1]) { // Multi-char variable cimglist_for(variable_def,i) if (!std::strcmp(s0,variable_def[i])) { arg1 = variable_pos[i]; arg2 = i; break; } } else arg1 = reserved_label[arg3 = *s0]; // Single-char variable if (arg1!=~0U) { if (arg2==~0U) { if (arg3!=~0U) reserved_label[arg3] = ~0U; } else { variable_def.remove(arg2); if (arg2<variable_pos._width - 1) std::memmove(variable_pos._data + arg2,variable_pos._data + arg2 + 1, sizeof(uintT)*(variable_pos._width - arg2 - 1)); --variable_pos._width; } } *s1 = c1; } else compile(s0,s1,depth1,0,is_single); // Will throw a 'missing argument' exception } _cimg_mp_return(arg1!=~0U?arg1:_cimg_mp_slot_nan); // Return value of last specified variable } if (!std::strncmp(ss,"uppercase(",10)) { // Upper case _cimg_mp_op("Function 'uppercase()'"); arg1 = compile(ss + 10,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_uppercase,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(cimg::uppercase(mem[arg1])); _cimg_mp_scalar1(mp_uppercase,arg1); } break; case 'v' : if ((cimg_sscanf(ss,"vector%u%c",&(arg1=~0U),&sep)==2 && sep=='(' && arg1>0) || !std::strncmp(ss,"vector(",7) || (!std::strncmp(ss,"vector",6) && ss7<se1 && (s=std::strchr(ss7,'('))!=0)) { // Vector _cimg_mp_op("Function 'vector()'"); arg2 = 0; // Number of specified values if (arg1==~0U && *ss6!='(') { arg1 = compile(ss6,s++,depth1,0,is_single); _cimg_mp_check_constant(arg1,0,3); arg1 = (unsigned int)mem[arg1]; } else s = std::strchr(ss6,'(') + 1; if (arg1==~0U && *s=='#') { // Number of elements specified as first argument with '#' s0 = ++s; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; arg1 = compile(s,s0++,depth1,0,is_single); _cimg_mp_check_constant(arg1,1,3); arg1 = (unsigned int)mem[arg1]; s = s0; } if (s<se1 || arg1==~0U) for ( ; s<se; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; arg3 = compile(s,ns,depth1,0,is_single); if (_cimg_mp_is_vector(arg3)) { arg4 = _cimg_mp_size(arg3); CImg<ulongT>::sequence(arg4,arg3 + 1,arg3 + arg4).move_to(l_opcode); arg2+=arg4; } else { CImg<ulongT>::vector(arg3).move_to(l_opcode); ++arg2; } s = ns; } if (arg1==~0U) arg1 = arg2; if (!arg1) _cimg_mp_return(0); pos = vector(arg1); l_opcode.insert(CImg<ulongT>::vector((ulongT)mp_vector_init,pos,0,arg1),0); (l_opcode>'y').move_to(opcode); opcode[2] = opcode._height; opcode.move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"vtos(",5)) { // Double(s) to string _cimg_mp_op("Function 'vtos()'"); s1 = ss5; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss5,s1,depth1,0,is_single); arg2 = 0; arg3 = ~0U; if (s1<se1) { s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(++s1,s2,depth1,0,is_single); arg3 = s2<se1?compile(++s2,se1,depth1,0,is_single):~0U; } _cimg_mp_check_type(arg2,2,1,0); if (arg3==~0U) { // Auto-guess best output vector size p1 = _cimg_mp_size(arg1); p1 = p1?22*p1 - 1:18; } else { _cimg_mp_check_constant(arg3,3,3); p1 = (unsigned int)mem[arg3]; } pos = vector(p1); CImg<ulongT>::vector((ulongT)mp_vtos,pos,p1,arg1,_cimg_mp_size(arg1),arg2).move_to(code); _cimg_mp_return(pos); } break; case 'w' : if (*ss1=='(') { // Image width _cimg_mp_op("Function 'w()'"); if (*ss2=='#') { // Index specified p1 = compile(ss3,se1,depth1,0,is_single); _cimg_mp_check_list(false); } else { if (ss2!=se1) break; p1 = ~0U; } pos = scalar(); CImg<ulongT>::vector((ulongT)mp_image_w,pos,p1).move_to(code); _cimg_mp_return(pos); } if (*ss1=='h' && *ss2=='(') { // Image width*height _cimg_mp_op("Function 'wh()'"); if (*ss3=='#') { // Index specified p1 = compile(ss4,se1,depth1,0,is_single); _cimg_mp_check_list(false); } else { if (ss3!=se1) break; p1 = ~0U; } pos = scalar(); CImg<ulongT>::vector((ulongT)mp_image_wh,pos,p1).move_to(code); _cimg_mp_return(pos); } if (*ss1=='h' && *ss2=='d' && *ss3=='(') { // Image width*height*depth _cimg_mp_op("Function 'whd()'"); if (*ss4=='#') { // Index specified p1 = compile(ss5,se1,depth1,0,is_single); _cimg_mp_check_list(false); } else { if (ss4!=se1) break; p1 = ~0U; } pos = scalar(); CImg<ulongT>::vector((ulongT)mp_image_whd,pos,p1).move_to(code); _cimg_mp_return(pos); } if (*ss1=='h' && *ss2=='d' && *ss3=='s' && *ss4=='(') { // Image width*height*depth*spectrum _cimg_mp_op("Function 'whds()'"); if (*ss5=='#') { // Index specified p1 = compile(ss6,se1,depth1,0,is_single); _cimg_mp_check_list(false); } else { if (ss5!=se1) break; p1 = ~0U; } pos = scalar(); CImg<ulongT>::vector((ulongT)mp_image_whds,pos,p1).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"while(",6)) { // While...do _cimg_mp_op("Function 'while()'"); s0 = *ss5=='('?ss6:ss8; s1 = s0; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; p1 = code._width; arg1 = compile(s0,s1,depth1,0,is_single); p2 = code._width; arg6 = mempos; pos = compile(++s1,se1,depth1,0,is_single); _cimg_mp_check_type(arg1,1,1,0); arg2 = _cimg_mp_size(pos); CImg<ulongT>::vector((ulongT)mp_while,pos,arg1,p2 - p1,code._width - p2,arg2, pos>=arg6 && !_cimg_mp_is_constant(pos), arg1>=arg6 && !_cimg_mp_is_constant(arg1)).move_to(code,p1); _cimg_mp_return(pos); } break; case 'x' : if (!std::strncmp(ss,"xor(",4)) { // Xor _cimg_mp_op("Function 'xor()'"); s1 = ss4; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss4,s1,depth1,0,is_single); arg2 = compile(++s1,se1,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_bitwise_xor,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_bitwise_xor,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_bitwise_xor,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant((longT)mem[arg1] ^ (longT)mem[arg2]); _cimg_mp_scalar2(mp_bitwise_xor,arg1,arg2); } break; } if (!std::strncmp(ss,"min(",4) || !std::strncmp(ss,"max(",4) || !std::strncmp(ss,"med(",4) || !std::strncmp(ss,"kth(",4) || !std::strncmp(ss,"sum(",4) || !std::strncmp(ss,"avg(",4) || !std::strncmp(ss,"std(",4) || !std::strncmp(ss,"var(",4) || !std::strncmp(ss,"prod(",5) || !std::strncmp(ss,"argmin(",7) || !std::strncmp(ss,"argmax(",7) || !std::strncmp(ss,"argkth(",7)) { // Multi-argument functions _cimg_mp_op(*ss=='a'?(ss[1]=='v'?"Function 'avg()'": ss[3]=='k'?"Function 'argkth()'": ss[4]=='i'?"Function 'argmin()'": "Function 'argmax()'"): *ss=='s'?(ss[1]=='u'?"Function 'sum()'":"Function 'std()'"): *ss=='k'?"Function 'kth()'": *ss=='p'?"Function 'prod()'": *ss=='v'?"Function 'var()'": ss[1]=='i'?"Function 'min()'": ss[1]=='a'?"Function 'max()'":"Function 'med()'"); op = *ss=='a'?(ss[1]=='v'?mp_avg:ss[3]=='k'?mp_argkth:ss[4]=='i'?mp_argmin:mp_argmax): *ss=='s'?(ss[1]=='u'?mp_sum:mp_std): *ss=='k'?mp_kth: *ss=='p'?mp_prod: *ss=='v'?mp_var: ss[1]=='i'?mp_min: ss[1]=='a'?mp_max: ss[2]=='a'?mp_avg: mp_median; is_sth = true; // Tell if all arguments are constant pos = scalar(); CImg<ulongT>::vector((ulongT)op,pos,0).move_to(l_opcode); for (s = std::strchr(ss,'(') + 1; s<se; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; arg2 = compile(s,ns,depth1,0,is_single); if (_cimg_mp_is_vector(arg2)) CImg<ulongT>::sequence(_cimg_mp_size(arg2),arg2 + 1, arg2 + (ulongT)_cimg_mp_size(arg2)). move_to(l_opcode); else CImg<ulongT>::vector(arg2).move_to(l_opcode); is_sth&=_cimg_mp_is_constant(arg2); s = ns; } (l_opcode>'y').move_to(opcode); opcode[2] = opcode._height; if (is_sth) _cimg_mp_constant(op(*this)); opcode.move_to(code); _cimg_mp_return(pos); } // No corresponding built-in function -> Look for a user-defined macro call. s0 = strchr(ss,'('); if (s0) { variable_name.assign(ss,(unsigned int)(s0 - ss + 1)).back() = 0; // Count number of specified arguments. p1 = 0; for (s = s0 + 1; s<=se1; ++p1, s = ns + 1) { while (*s && cimg::is_blank(*s)) ++s; if (*s==')' && !p1) break; ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; } arg3 = 0; // Number of possible name matches cimglist_for(macro_def,l) if (!std::strcmp(macro_def[l],variable_name) && ++arg3 && macro_def[l].back()==(char)p1) { p2 = (unsigned int)macro_def[l].back(); // Number of required arguments CImg<charT> _expr = macro_body[l]; // Expression to be substituted p1 = 1; // Index of current parsed argument for (s = s0 + 1; s<=se1; ++p1, s = ns + 1) { // Parse function arguments while (*s && cimg::is_blank(*s)) ++s; if (*s==')' && p1==1) break; // Function has no arguments if (p1>p2) { ++p1; break; } ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; variable_name.assign(s,(unsigned int)(ns - s + 1)).back() = 0; // Argument to write arg2 = 0; cimg_forX(_expr,k) { if (_expr[k]==(char)p1) { // Perform argument substitution arg1 = _expr._width; _expr.resize(arg1 + variable_name._width - 2,1,1,1,0); std::memmove(_expr._data + k + variable_name._width - 1,_expr._data + k + 1,arg1 - k - 1); std::memcpy(_expr._data + k,variable_name,variable_name._width - 1); k+=variable_name._width - 2; } ++arg2; } } // Recompute 'pexpr' and 'level' for evaluating substituted expression. CImg<charT> _pexpr(_expr._width); ns = _pexpr._data; for (ps = _expr._data, c1 = ' '; *ps; ++ps) { if (!cimg::is_blank(*ps)) c1 = *ps; *(ns++) = c1; } *ns = 0; CImg<uintT> _level = get_level(_expr); expr.swap(_expr); pexpr.swap(_pexpr); level.swap(_level); s0 = user_macro; user_macro = macro_def[l]; pos = compile(expr._data,expr._data + expr._width - 1,depth1,p_ref,is_single); user_macro = s0; level.swap(_level); pexpr.swap(_pexpr); expr.swap(_expr); _cimg_mp_return(pos); } if (arg3) { // Macro name matched but number of arguments does not CImg<uintT> sig_nargs(arg3); arg1 = 0; cimglist_for(macro_def,l) if (!std::strcmp(macro_def[l],variable_name)) sig_nargs[arg1++] = (unsigned int)macro_def[l].back(); *se = saved_char; cimg::strellipsize(variable_name,64); s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); if (sig_nargs._width>1) { sig_nargs.sort(); arg1 = sig_nargs.back(); --sig_nargs._width; throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: Function '%s()': Number of specified arguments (%u) " "does not match macro declaration (defined for %s or %u arguments), " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,variable_name._data, p1,sig_nargs.value_string()._data,arg1, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } else throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: Function '%s()': Number of specified arguments (%u) " "does not match macro declaration (defined for %u argument%s), " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,variable_name._data, p1,*sig_nargs,*sig_nargs!=1?"s":"", s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } } } // if (se1==')') // Char / string initializer. if (*se1=='\'' && ((se1>ss && *ss=='\'') || (se1>ss1 && *ss=='_' && *ss1=='\''))) { if (*ss=='_') { _cimg_mp_op("Char initializer"); s1 = ss2; } else { _cimg_mp_op("String initializer"); s1 = ss1; } arg1 = (unsigned int)(se1 - s1); // Original string length if (arg1) { CImg<charT>(s1,arg1 + 1).move_to(variable_name).back() = 0; cimg::strunescape(variable_name); arg1 = (unsigned int)std::strlen(variable_name); } if (!arg1) _cimg_mp_return(0); // Empty string -> 0 if (*ss=='_') { if (arg1==1) _cimg_mp_constant(*variable_name); *se = saved_char; cimg::strellipsize(variable_name,64); s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Literal %s contains more than one character, " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, ss1, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } pos = vector(arg1); CImg<ulongT>::vector((ulongT)mp_string_init,pos,arg1).move_to(l_opcode); CImg<ulongT>(1,arg1/sizeof(ulongT) + (arg1%sizeof(ulongT)?1:0)).move_to(l_opcode); std::memcpy((char*)l_opcode[1]._data,variable_name,arg1); (l_opcode>'y').move_to(code); _cimg_mp_return(pos); } // Vector initializer [ ... ]. if (*ss=='[' && *se1==']') { _cimg_mp_op("Vector initializer"); s1 = ss1; while (s1<se2 && cimg::is_blank(*s1)) ++s1; s2 = se2; while (s2>s1 && cimg::is_blank(*s2)) --s2; if (s2>s1 && *s1=='\'' && *s2=='\'') { // Vector values provided as a string arg1 = (unsigned int)(s2 - s1 - 1); // Original string length if (arg1) { CImg<charT>(s1 + 1,arg1 + 1).move_to(variable_name).back() = 0; cimg::strunescape(variable_name); arg1 = (unsigned int)std::strlen(variable_name); } if (!arg1) _cimg_mp_return(0); // Empty string -> 0 pos = vector(arg1); CImg<ulongT>::vector((ulongT)mp_string_init,pos,arg1).move_to(l_opcode); CImg<ulongT>(1,arg1/sizeof(ulongT) + (arg1%sizeof(ulongT)?1:0)).move_to(l_opcode); std::memcpy((char*)l_opcode[1]._data,variable_name,arg1); (l_opcode>'y').move_to(code); } else { // Vector values provided as list of items arg1 = 0; // Number of specified values if (*ss1!=']') for (s = ss1; s<se; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=']' || level[ns - expr._data]!=clevel)) ++ns; arg2 = compile(s,ns,depth1,0,is_single); if (_cimg_mp_is_vector(arg2)) { arg3 = _cimg_mp_size(arg2); CImg<ulongT>::sequence(arg3,arg2 + 1,arg2 + arg3).move_to(l_opcode); arg1+=arg3; } else { CImg<ulongT>::vector(arg2).move_to(l_opcode); ++arg1; } s = ns; } if (!arg1) _cimg_mp_return(0); pos = vector(arg1); l_opcode.insert(CImg<ulongT>::vector((ulongT)mp_vector_init,pos,0,arg1),0); (l_opcode>'y').move_to(opcode); opcode[2] = opcode._height; opcode.move_to(code); } _cimg_mp_return(pos); } // Variables related to the input list of images. if (*ss1=='#' && ss2<se) { arg1 = compile(ss2,se,depth1,0,is_single); p1 = (unsigned int)(listin._width && _cimg_mp_is_constant(arg1)?cimg::mod((int)mem[arg1],listin.width()):~0U); switch (*ss) { case 'w' : // w#ind if (!listin) _cimg_mp_return(0); if (p1!=~0U) _cimg_mp_constant(listin[p1]._width); _cimg_mp_scalar1(mp_list_width,arg1); case 'h' : // h#ind if (!listin) _cimg_mp_return(0); if (p1!=~0U) _cimg_mp_constant(listin[p1]._height); _cimg_mp_scalar1(mp_list_height,arg1); case 'd' : // d#ind if (!listin) _cimg_mp_return(0); if (p1!=~0U) _cimg_mp_constant(listin[p1]._depth); _cimg_mp_scalar1(mp_list_depth,arg1); case 'r' : // r#ind if (!listin) _cimg_mp_return(0); if (p1!=~0U) _cimg_mp_constant(listin[p1]._is_shared); _cimg_mp_scalar1(mp_list_is_shared,arg1); case 's' : // s#ind if (!listin) _cimg_mp_return(0); if (p1!=~0U) _cimg_mp_constant(listin[p1]._spectrum); _cimg_mp_scalar1(mp_list_spectrum,arg1); case 'i' : // i#ind if (!listin) _cimg_mp_return(0); _cimg_mp_scalar7(mp_list_ixyzc,arg1,_cimg_mp_slot_x,_cimg_mp_slot_y,_cimg_mp_slot_z,_cimg_mp_slot_c, 0,_cimg_mp_boundary); case 'I' : // I#ind p2 = p1!=~0U?listin[p1]._spectrum:listin._width?~0U:0; if (!p2) _cimg_mp_return(0); pos = vector(p2); CImg<ulongT>::vector((ulongT)mp_list_Joff,pos,p1,0,0,p2).move_to(code); _cimg_mp_return(pos); case 'R' : // R#ind if (!listin) _cimg_mp_return(0); _cimg_mp_scalar7(mp_list_ixyzc,arg1,_cimg_mp_slot_x,_cimg_mp_slot_y,_cimg_mp_slot_z,0, 0,_cimg_mp_boundary); case 'G' : // G#ind if (!listin) _cimg_mp_return(0); _cimg_mp_scalar7(mp_list_ixyzc,arg1,_cimg_mp_slot_x,_cimg_mp_slot_y,_cimg_mp_slot_z,1, 0,_cimg_mp_boundary); case 'B' : // B#ind if (!listin) _cimg_mp_return(0); _cimg_mp_scalar7(mp_list_ixyzc,arg1,_cimg_mp_slot_x,_cimg_mp_slot_y,_cimg_mp_slot_z,2, 0,_cimg_mp_boundary); case 'A' : // A#ind if (!listin) _cimg_mp_return(0); _cimg_mp_scalar7(mp_list_ixyzc,arg1,_cimg_mp_slot_x,_cimg_mp_slot_y,_cimg_mp_slot_z,3, 0,_cimg_mp_boundary); } } if (*ss1 && *ss2=='#' && ss3<se) { arg1 = compile(ss3,se,depth1,0,is_single); p1 = (unsigned int)(listin._width && _cimg_mp_is_constant(arg1)?cimg::mod((int)mem[arg1],listin.width()):~0U); if (*ss=='w' && *ss1=='h') { // wh#ind if (!listin) _cimg_mp_return(0); if (p1!=~0U) _cimg_mp_constant(listin[p1]._width*listin[p1]._height); _cimg_mp_scalar1(mp_list_wh,arg1); } arg2 = ~0U; if (*ss=='i') { if (*ss1=='c') { // ic#ind if (!listin) _cimg_mp_return(0); if (_cimg_mp_is_constant(arg1)) { if (!list_median) list_median.assign(listin._width); if (!list_median[p1]) CImg<doubleT>::vector(listin[p1].median()).move_to(list_median[p1]); _cimg_mp_constant(*list_median[p1]); } _cimg_mp_scalar1(mp_list_median,arg1); } if (*ss1>='0' && *ss1<='9') { // i0#ind...i9#ind if (!listin) _cimg_mp_return(0); _cimg_mp_scalar7(mp_list_ixyzc,arg1,_cimg_mp_slot_x,_cimg_mp_slot_y,_cimg_mp_slot_z,*ss1 - '0', 0,_cimg_mp_boundary); } switch (*ss1) { case 'm' : arg2 = 0; break; // im#ind case 'M' : arg2 = 1; break; // iM#ind case 'a' : arg2 = 2; break; // ia#ind case 'v' : arg2 = 3; break; // iv#ind case 's' : arg2 = 12; break; // is#ind case 'p' : arg2 = 13; break; // ip#ind } } else if (*ss1=='m') switch (*ss) { case 'x' : arg2 = 4; break; // xm#ind case 'y' : arg2 = 5; break; // ym#ind case 'z' : arg2 = 6; break; // zm#ind case 'c' : arg2 = 7; break; // cm#ind } else if (*ss1=='M') switch (*ss) { case 'x' : arg2 = 8; break; // xM#ind case 'y' : arg2 = 9; break; // yM#ind case 'z' : arg2 = 10; break; // zM#ind case 'c' : arg2 = 11; break; // cM#ind } if (arg2!=~0U) { if (!listin) _cimg_mp_return(0); if (_cimg_mp_is_constant(arg1)) { if (!list_stats) list_stats.assign(listin._width); if (!list_stats[p1]) list_stats[p1].assign(1,14,1,1,0).fill(listin[p1].get_stats(),false); _cimg_mp_constant(list_stats(p1,arg2)); } _cimg_mp_scalar2(mp_list_stats,arg1,arg2); } } if (*ss=='w' && *ss1=='h' && *ss2=='d' && *ss3=='#' && ss4<se) { // whd#ind arg1 = compile(ss4,se,depth1,0,is_single); if (!listin) _cimg_mp_return(0); p1 = (unsigned int)(_cimg_mp_is_constant(arg1)?cimg::mod((int)mem[arg1],listin.width()):~0U); if (p1!=~0U) _cimg_mp_constant(listin[p1]._width*listin[p1]._height*listin[p1]._depth); _cimg_mp_scalar1(mp_list_whd,arg1); } if (*ss=='w' && *ss1=='h' && *ss2=='d' && *ss3=='s' && *ss4=='#' && ss5<se) { // whds#ind arg1 = compile(ss5,se,depth1,0,is_single); if (!listin) _cimg_mp_return(0); p1 = (unsigned int)(_cimg_mp_is_constant(arg1)?cimg::mod((int)mem[arg1],listin.width()):~0U); if (p1!=~0U) _cimg_mp_constant(listin[p1]._width*listin[p1]._height*listin[p1]._depth*listin[p1]._spectrum); _cimg_mp_scalar1(mp_list_whds,arg1); } if (!std::strcmp(ss,"interpolation")) _cimg_mp_return(_cimg_mp_interpolation); // interpolation if (!std::strcmp(ss,"boundary")) _cimg_mp_return(_cimg_mp_boundary); // boundary // No known item found, assuming this is an already initialized variable. variable_name.assign(ss,(unsigned int)(se - ss + 1)).back() = 0; if (variable_name[1]) { // Multi-char variable cimglist_for(variable_def,i) if (!std::strcmp(variable_name,variable_def[i])) _cimg_mp_return(variable_pos[i]); } else if (reserved_label[(int)*variable_name]!=~0U) // Single-char variable _cimg_mp_return(reserved_label[(int)*variable_name]); // Reached an unknown item -> error. is_sth = true; // is_valid_variable_name if (*variable_name>='0' && *variable_name<='9') is_sth = false; else for (ns = variable_name._data; *ns; ++ns) if (!is_varchar(*ns)) { is_sth = false; break; } *se = saved_char; c1 = *se1; cimg::strellipsize(variable_name,64); s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); if (is_sth) throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: Undefined variable '%s' in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function, variable_name._data, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); s1 = std::strchr(ss,'('); s_op = s1 && c1==')'?"function call":"item"; throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: Unrecognized %s '%s' in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function, s_op,variable_name._data, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } // Evaluation procedure. double operator()(const double x, const double y, const double z, const double c) { mem[_cimg_mp_slot_x] = x; mem[_cimg_mp_slot_y] = y; mem[_cimg_mp_slot_z] = z; mem[_cimg_mp_slot_c] = c; for (p_code = code; p_code<p_code_end; ++p_code) { opcode._data = p_code->_data; const ulongT target = opcode[1]; mem[target] = _cimg_mp_defunc(*this); } return *result; } // Evaluation procedure (return output values in vector 'output'). template<typename t> void operator()(const double x, const double y, const double z, const double c, t *const output) { mem[_cimg_mp_slot_x] = x; mem[_cimg_mp_slot_y] = y; mem[_cimg_mp_slot_z] = z; mem[_cimg_mp_slot_c] = c; for (p_code = code; p_code<p_code_end; ++p_code) { opcode._data = p_code->_data; const ulongT target = opcode[1]; mem[target] = _cimg_mp_defunc(*this); } if (result_dim) { const double *ptrs = result + 1; t *ptrd = output; for (unsigned int k = 0; k<result_dim; ++k) *(ptrd++) = (t)*(ptrs++); } else *output = (t)*result; } // Evaluation procedure for the end() blocks. void end() { if (code_end.is_empty()) return; if (imgin) { mem[_cimg_mp_slot_x] = imgin._width - 1.; mem[_cimg_mp_slot_y] = imgin._height - 1.; mem[_cimg_mp_slot_z] = imgin._depth - 1.; mem[_cimg_mp_slot_c] = imgin._spectrum - 1.; } else mem[_cimg_mp_slot_x] = mem[_cimg_mp_slot_y] = mem[_cimg_mp_slot_z] = mem[_cimg_mp_slot_c] = 0; p_code_end = code_end.end(); for (p_code = code_end; p_code<p_code_end; ++p_code) { opcode._data = p_code->_data; const ulongT target = opcode[1]; mem[target] = _cimg_mp_defunc(*this); } } // Return type of a memory element as a string. CImg<charT> s_type(const unsigned int arg) const { CImg<charT> res; if (_cimg_mp_is_vector(arg)) { // Vector CImg<charT>::string("vectorXXXXXXXXXXXXXXXX").move_to(res); cimg_sprintf(res._data + 6,"%u",_cimg_mp_size(arg)); } else CImg<charT>::string("scalar").move_to(res); return res; } // Insert constant value in memory. unsigned int constant(const double val) { // Search for built-in constant. if (cimg::type<double>::is_nan(val)) return _cimg_mp_slot_nan; if (val==(double)(int)val) { if (val>=0 && val<=10) return (unsigned int)val; if (val<0 && val>=-5) return (unsigned int)(10 - val); } if (val==0.5) return 16; // Search for constant already requested before (in const cache). unsigned int ind = ~0U; if (constcache_size<1024) { if (!constcache_size) { constcache_vals.assign(16,1,1,1,0); constcache_inds.assign(16,1,1,1,0); *constcache_vals = val; constcache_size = 1; ind = 0; } else { // Dichotomic search const double val_beg = *constcache_vals, val_end = constcache_vals[constcache_size - 1]; if (val_beg>=val) ind = 0; else if (val_end==val) ind = constcache_size - 1; else if (val_end<val) ind = constcache_size; else { unsigned int i0 = 1, i1 = constcache_size - 2; while (i0<=i1) { const unsigned int mid = (i0 + i1)/2; if (constcache_vals[mid]==val) { i0 = mid; break; } else if (constcache_vals[mid]<val) i0 = mid + 1; else i1 = mid - 1; } ind = i0; } if (ind>=constcache_size || constcache_vals[ind]!=val) { ++constcache_size; if (constcache_size>constcache_vals._width) { constcache_vals.resize(-200,1,1,1,0); constcache_inds.resize(-200,1,1,1,0); } const int l = constcache_size - (int)ind - 1; if (l>0) { std::memmove(&constcache_vals[ind + 1],&constcache_vals[ind],l*sizeof(double)); std::memmove(&constcache_inds[ind + 1],&constcache_inds[ind],l*sizeof(unsigned int)); } constcache_vals[ind] = val; constcache_inds[ind] = 0; } } if (constcache_inds[ind]) return constcache_inds[ind]; } // Insert new constant in memory if necessary. if (mempos>=mem._width) { mem.resize(-200,1,1,1,0); memtype.resize(-200,1,1,1,0); } const unsigned int pos = mempos++; mem[pos] = val; memtype[pos] = 1; // Set constant property if (ind!=~0U) constcache_inds[ind] = pos; return pos; } // Insert code instructions for processing scalars. unsigned int scalar() { // Insert new scalar in memory if (mempos>=mem._width) { mem.resize(-200,1,1,1,0); memtype.resize(mem._width,1,1,1,0); } return mempos++; } unsigned int scalar0(const mp_func op) { const unsigned int pos = scalar(); CImg<ulongT>::vector((ulongT)op,pos).move_to(code); return pos; } unsigned int scalar1(const mp_func op, const unsigned int arg1) { const unsigned int pos = arg1!=~0U && arg1>_cimg_mp_slot_c && _cimg_mp_is_comp(arg1) && op!=mp_copy?arg1:scalar(); CImg<ulongT>::vector((ulongT)op,pos,arg1).move_to(code); return pos; } unsigned int scalar2(const mp_func op, const unsigned int arg1, const unsigned int arg2) { const unsigned int pos = arg1!=~0U && arg1>_cimg_mp_slot_c && _cimg_mp_is_comp(arg1)?arg1: arg2!=~0U && arg2>_cimg_mp_slot_c && _cimg_mp_is_comp(arg2)?arg2:scalar(); CImg<ulongT>::vector((ulongT)op,pos,arg1,arg2).move_to(code); return pos; } unsigned int scalar3(const mp_func op, const unsigned int arg1, const unsigned int arg2, const unsigned int arg3) { const unsigned int pos = arg1!=~0U && arg1>_cimg_mp_slot_c && _cimg_mp_is_comp(arg1)?arg1: arg2!=~0U && arg2>_cimg_mp_slot_c && _cimg_mp_is_comp(arg2)?arg2: arg3!=~0U && arg3>_cimg_mp_slot_c && _cimg_mp_is_comp(arg3)?arg3:scalar(); CImg<ulongT>::vector((ulongT)op,pos,arg1,arg2,arg3).move_to(code); return pos; } unsigned int scalar4(const mp_func op, const unsigned int arg1, const unsigned int arg2, const unsigned int arg3, const unsigned int arg4) { const unsigned int pos = arg1!=~0U && arg1>_cimg_mp_slot_c && _cimg_mp_is_comp(arg1)?arg1: arg2!=~0U && arg2>_cimg_mp_slot_c && _cimg_mp_is_comp(arg2)?arg2: arg3!=~0U && arg3>_cimg_mp_slot_c && _cimg_mp_is_comp(arg3)?arg3: arg4!=~0U && arg4>_cimg_mp_slot_c && _cimg_mp_is_comp(arg4)?arg4:scalar(); CImg<ulongT>::vector((ulongT)op,pos,arg1,arg2,arg3,arg4).move_to(code); return pos; } unsigned int scalar5(const mp_func op, const unsigned int arg1, const unsigned int arg2, const unsigned int arg3, const unsigned int arg4, const unsigned int arg5) { const unsigned int pos = arg1!=~0U && arg1>_cimg_mp_slot_c && _cimg_mp_is_comp(arg1)?arg1: arg2!=~0U && arg2>_cimg_mp_slot_c && _cimg_mp_is_comp(arg2)?arg2: arg3!=~0U && arg3>_cimg_mp_slot_c && _cimg_mp_is_comp(arg3)?arg3: arg4!=~0U && arg4>_cimg_mp_slot_c && _cimg_mp_is_comp(arg4)?arg4: arg5!=~0U && arg5>_cimg_mp_slot_c && _cimg_mp_is_comp(arg5)?arg5:scalar(); CImg<ulongT>::vector((ulongT)op,pos,arg1,arg2,arg3,arg4,arg5).move_to(code); return pos; } unsigned int scalar6(const mp_func op, const unsigned int arg1, const unsigned int arg2, const unsigned int arg3, const unsigned int arg4, const unsigned int arg5, const unsigned int arg6) { const unsigned int pos = arg1!=~0U && arg1>_cimg_mp_slot_c && _cimg_mp_is_comp(arg1)?arg1: arg2!=~0U && arg2>_cimg_mp_slot_c && _cimg_mp_is_comp(arg2)?arg2: arg3!=~0U && arg3>_cimg_mp_slot_c && _cimg_mp_is_comp(arg3)?arg3: arg4!=~0U && arg4>_cimg_mp_slot_c && _cimg_mp_is_comp(arg4)?arg4: arg5!=~0U && arg5>_cimg_mp_slot_c && _cimg_mp_is_comp(arg5)?arg5: arg6!=~0U && arg6>_cimg_mp_slot_c && _cimg_mp_is_comp(arg6)?arg6:scalar(); CImg<ulongT>::vector((ulongT)op,pos,arg1,arg2,arg3,arg4,arg5,arg6).move_to(code); return pos; } unsigned int scalar7(const mp_func op, const unsigned int arg1, const unsigned int arg2, const unsigned int arg3, const unsigned int arg4, const unsigned int arg5, const unsigned int arg6, const unsigned int arg7) { const unsigned int pos = arg1!=~0U && arg1>_cimg_mp_slot_c && _cimg_mp_is_comp(arg1)?arg1: arg2!=~0U && arg2>_cimg_mp_slot_c && _cimg_mp_is_comp(arg2)?arg2: arg3!=~0U && arg3>_cimg_mp_slot_c && _cimg_mp_is_comp(arg3)?arg3: arg4!=~0U && arg4>_cimg_mp_slot_c && _cimg_mp_is_comp(arg4)?arg4: arg5!=~0U && arg5>_cimg_mp_slot_c && _cimg_mp_is_comp(arg5)?arg5: arg6!=~0U && arg6>_cimg_mp_slot_c && _cimg_mp_is_comp(arg6)?arg6: arg7!=~0U && arg7>_cimg_mp_slot_c && _cimg_mp_is_comp(arg7)?arg7:scalar(); CImg<ulongT>::vector((ulongT)op,pos,arg1,arg2,arg3,arg4,arg5,arg6,arg7).move_to(code); return pos; } // Return a string that defines the calling function + the user-defined function scope. CImg<charT> calling_function_s() const { CImg<charT> res; const unsigned int l1 = calling_function?(unsigned int)std::strlen(calling_function):0U, l2 = user_macro?(unsigned int)std::strlen(user_macro):0U; if (l2) { res.assign(l1 + l2 + 48); cimg_snprintf(res,res._width,"%s(): When substituting function '%s()'",calling_function,user_macro); } else { res.assign(l1 + l2 + 4); cimg_snprintf(res,res._width,"%s()",calling_function); } return res; } // Return true if specified argument can be a part of an allowed variable name. bool is_varchar(const char c) const { return (c>='a' && c<='z') || (c>='A' && c<='Z') || (c>='0' && c<='9') || c=='_'; } // Insert code instructions for processing vectors. bool is_comp_vector(const unsigned int arg) const { unsigned int siz = _cimg_mp_size(arg); if (siz>8) return false; const int *ptr = memtype.data(arg + 1); bool is_tmp = true; while (siz-->0) if (*(ptr++)) { is_tmp = false; break; } return is_tmp; } void set_variable_vector(const unsigned int arg) { unsigned int siz = _cimg_mp_size(arg); int *ptr = memtype.data(arg + 1); while (siz-->0) *(ptr++) = -1; } unsigned int vector(const unsigned int siz) { // Insert new vector of specified size in memory if (mempos + siz>=mem._width) { mem.resize(2*mem._width + siz,1,1,1,0); memtype.resize(mem._width,1,1,1,0); } const unsigned int pos = mempos++; mem[pos] = cimg::type<double>::nan(); memtype[pos] = siz + 1; mempos+=siz; return pos; } unsigned int vector(const unsigned int siz, const double value) { // Insert new initialized vector const unsigned int pos = vector(siz); double *ptr = &mem[pos] + 1; for (unsigned int i = 0; i<siz; ++i) *(ptr++) = value; return pos; } unsigned int vector_copy(const unsigned int arg) { // Insert new copy of specified vector in memory const unsigned int siz = _cimg_mp_size(arg), pos = vector(siz); CImg<ulongT>::vector((ulongT)mp_vector_copy,pos,arg,siz).move_to(code); return pos; } void self_vector_s(const unsigned int pos, const mp_func op, const unsigned int arg1) { const unsigned int siz = _cimg_mp_size(pos); if (siz>24) CImg<ulongT>::vector((ulongT)mp_self_map_vector_s,pos,siz,(ulongT)op,arg1).move_to(code); else { code.insert(siz); for (unsigned int k = 1; k<=siz; ++k) CImg<ulongT>::vector((ulongT)op,pos + k,arg1).move_to(code[code._width - 1 - siz + k]); } } void self_vector_v(const unsigned int pos, const mp_func op, const unsigned int arg1) { const unsigned int siz = _cimg_mp_size(pos); if (siz>24) CImg<ulongT>::vector((ulongT)mp_self_map_vector_v,pos,siz,(ulongT)op,arg1).move_to(code); else { code.insert(siz); for (unsigned int k = 1; k<=siz; ++k) CImg<ulongT>::vector((ulongT)op,pos + k,arg1 + k).move_to(code[code._width - 1 - siz + k]); } } unsigned int vector1_v(const mp_func op, const unsigned int arg1) { const unsigned int siz = _cimg_mp_size(arg1), pos = is_comp_vector(arg1)?arg1:vector(siz); if (siz>24) CImg<ulongT>::vector((ulongT)mp_vector_map_v,pos,siz,(ulongT)op,arg1).move_to(code); else { code.insert(siz); for (unsigned int k = 1; k<=siz; ++k) CImg<ulongT>::vector((ulongT)op,pos + k,arg1 + k).move_to(code[code._width - 1 - siz + k]); } return pos; } unsigned int vector2_vv(const mp_func op, const unsigned int arg1, const unsigned int arg2) { const unsigned int siz = _cimg_mp_size(arg1), pos = is_comp_vector(arg1)?arg1:is_comp_vector(arg2)?arg2:vector(siz); if (siz>24) CImg<ulongT>::vector((ulongT)mp_vector_map_vv,pos,siz,(ulongT)op,arg1,arg2).move_to(code); else { code.insert(siz); for (unsigned int k = 1; k<=siz; ++k) CImg<ulongT>::vector((ulongT)op,pos + k,arg1 + k,arg2 + k).move_to(code[code._width - 1 - siz + k]); } return pos; } unsigned int vector2_vs(const mp_func op, const unsigned int arg1, const unsigned int arg2) { const unsigned int siz = _cimg_mp_size(arg1), pos = is_comp_vector(arg1)?arg1:vector(siz); if (siz>24) CImg<ulongT>::vector((ulongT)mp_vector_map_vs,pos,siz,(ulongT)op,arg1,arg2).move_to(code); else { code.insert(siz); for (unsigned int k = 1; k<=siz; ++k) CImg<ulongT>::vector((ulongT)op,pos + k,arg1 + k,arg2).move_to(code[code._width - 1 - siz + k]); } return pos; } unsigned int vector2_sv(const mp_func op, const unsigned int arg1, const unsigned int arg2) { const unsigned int siz = _cimg_mp_size(arg2), pos = is_comp_vector(arg2)?arg2:vector(siz); if (siz>24) CImg<ulongT>::vector((ulongT)mp_vector_map_sv,pos,siz,(ulongT)op,arg1,arg2).move_to(code); else { code.insert(siz); for (unsigned int k = 1; k<=siz; ++k) CImg<ulongT>::vector((ulongT)op,pos + k,arg1,arg2 + k).move_to(code[code._width - 1 - siz + k]); } return pos; } unsigned int vector3_vss(const mp_func op, const unsigned int arg1, const unsigned int arg2, const unsigned int arg3) { const unsigned int siz = _cimg_mp_size(arg1), pos = is_comp_vector(arg1)?arg1:vector(siz); if (siz>24) CImg<ulongT>::vector((ulongT)mp_vector_map_vss,pos,siz,(ulongT)op,arg1,arg2,arg3).move_to(code); else { code.insert(siz); for (unsigned int k = 1; k<=siz; ++k) CImg<ulongT>::vector((ulongT)op,pos + k,arg1 + k,arg2,arg3).move_to(code[code._width - 1 - siz + k]); } return pos; } // Check if a memory slot is a positive integer constant scalar value. // 'mode' can be: // { 0=constant | 1=integer constant | 2=positive integer constant | 3=strictly-positive integer constant } void check_constant(const unsigned int arg, const unsigned int n_arg, const unsigned int mode, char *const ss, char *const se, const char saved_char) { _cimg_mp_check_type(arg,n_arg,1,0); if (!(_cimg_mp_is_constant(arg) && (!mode || (double)(int)mem[arg]==mem[arg]) && (mode<2 || mem[arg]>=(mode==3)))) { const char *s_arg = !n_arg?"":n_arg==1?"First ":n_arg==2?"Second ":n_arg==3?"Third ": n_arg==4?"Fourth ":n_arg==5?"Fifth ":n_arg==6?"Sixth ":n_arg==7?"Seventh ":n_arg==8?"Eighth ": n_arg==9?"Ninth ":"One of the "; *se = saved_char; char *const s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s%s %s%s (of type '%s') is not a%s constant, " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op,*s_op?":":"", s_arg,*s_arg?"argument":"Argument",s_type(arg)._data, !mode?"":mode==1?"n integer": mode==2?" positive integer":" strictly positive integer", s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } } // Check a matrix is square. void check_matrix_square(const unsigned int arg, const unsigned int n_arg, char *const ss, char *const se, const char saved_char) { _cimg_mp_check_type(arg,n_arg,2,0); const unsigned int siz = _cimg_mp_size(arg), n = (unsigned int)cimg::round(std::sqrt((float)siz)); if (n*n!=siz) { const char *s_arg; if (*s_op!='F') s_arg = !n_arg?"":n_arg==1?"Left-hand ":"Right-hand "; else s_arg = !n_arg?"":n_arg==1?"First ":n_arg==2?"Second ":n_arg==3?"Third ":"One "; *se = saved_char; char *const s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s%s %s%s (of type '%s') " "cannot be considered as a square matrix, in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op,*s_op?":":"", s_arg,*s_op=='F'?(*s_arg?"argument":"Argument"):(*s_arg?"operand":"Operand"), s_type(arg)._data, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } } // Check type compatibility for one argument. // Bits of 'mode' tells what types are allowed: // { 1 = scalar | 2 = vectorN }. // If 'N' is not zero, it also restricts the vectors to be of size N only. void check_type(const unsigned int arg, const unsigned int n_arg, const unsigned int mode, const unsigned int N, char *const ss, char *const se, const char saved_char) { const bool is_scalar = _cimg_mp_is_scalar(arg), is_vector = _cimg_mp_is_vector(arg) && (!N || _cimg_mp_size(arg)==N); bool cond = false; if (mode&1) cond|=is_scalar; if (mode&2) cond|=is_vector; if (!cond) { const char *s_arg; if (*s_op!='F') s_arg = !n_arg?"":n_arg==1?"Left-hand ":"Right-hand "; else s_arg = !n_arg?"":n_arg==1?"First ":n_arg==2?"Second ":n_arg==3?"Third ": n_arg==4?"Fourth ":n_arg==5?"Fifth ":n_arg==6?"Sixth ":n_arg==7?"Seventh ":n_arg==8?"Eighth": n_arg==9?"Ninth":"One of the "; CImg<charT> sb_type(32); if (mode==1) cimg_snprintf(sb_type,sb_type._width,"'scalar'"); else if (mode==2) { if (N) cimg_snprintf(sb_type,sb_type._width,"'vector%u'",N); else cimg_snprintf(sb_type,sb_type._width,"'vector'"); } else { if (N) cimg_snprintf(sb_type,sb_type._width,"'scalar' or 'vector%u'",N); else cimg_snprintf(sb_type,sb_type._width,"'scalar' or 'vector'"); } *se = saved_char; char *const s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s%s %s%s has invalid type '%s' (should be %s), " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op,*s_op?":":"", s_arg,*s_op=='F'?(*s_arg?"argument":"Argument"):(*s_arg?"operand":"Operand"), s_type(arg)._data,sb_type._data, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } } // Check that listin or listout are not empty. void check_list(const bool is_out, char *const ss, char *const se, const char saved_char) { if ((!is_out && !listin) || (is_out && !listout)) { *se = saved_char; char *const s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s%s Invalid call with an empty image list, " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op,*s_op?":":"", s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } } // Evaluation functions, known by the parser. // Defining these functions 'static' ensures that sizeof(mp_func)==sizeof(ulongT), // so we can store pointers to them directly in the opcode vectors. #ifdef _mp_arg #undef _mp_arg #endif #define _mp_arg(x) mp.mem[mp.opcode[x]] static double mp_abs(_cimg_math_parser& mp) { return cimg::abs(_mp_arg(2)); } static double mp_add(_cimg_math_parser& mp) { return _mp_arg(2) + _mp_arg(3); } static double mp_acos(_cimg_math_parser& mp) { return std::acos(_mp_arg(2)); } static double mp_acosh(_cimg_math_parser& mp) { return cimg::acosh(_mp_arg(2)); } static double mp_asinh(_cimg_math_parser& mp) { return cimg::asinh(_mp_arg(2)); } static double mp_atanh(_cimg_math_parser& mp) { return cimg::atanh(_mp_arg(2)); } static double mp_arg(_cimg_math_parser& mp) { const int _ind = (int)_mp_arg(4); const unsigned int nb_args = (unsigned int)mp.opcode[2] - 4, ind = _ind<0?_ind + nb_args:(unsigned int)_ind, siz = (unsigned int)mp.opcode[3]; if (siz>0) { if (ind>=nb_args) std::memset(&_mp_arg(1) + 1,0,siz*sizeof(double)); else std::memcpy(&_mp_arg(1) + 1,&_mp_arg(ind + 4) + 1,siz*sizeof(double)); return cimg::type<double>::nan(); } if (ind>=nb_args) return 0; return _mp_arg(ind + 4); } static double mp_argkth(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; const double val = mp_kth(mp); for (unsigned int i = 4; i<i_end; ++i) if (val==_mp_arg(i)) return i - 3.; return 1; } static double mp_argmin(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; double val = _mp_arg(3); unsigned int argval = 0; for (unsigned int i = 4; i<i_end; ++i) { const double _val = _mp_arg(i); if (_val<val) { val = _val; argval = i - 3; } } return (double)argval; } static double mp_argmax(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; double val = _mp_arg(3); unsigned int argval = 0; for (unsigned int i = 4; i<i_end; ++i) { const double _val = _mp_arg(i); if (_val>val) { val = _val; argval = i - 3; } } return (double)argval; } static double mp_asin(_cimg_math_parser& mp) { return std::asin(_mp_arg(2)); } static double mp_atan(_cimg_math_parser& mp) { return std::atan(_mp_arg(2)); } static double mp_atan2(_cimg_math_parser& mp) { return std::atan2(_mp_arg(2),_mp_arg(3)); } static double mp_avg(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; double val = _mp_arg(3); for (unsigned int i = 4; i<i_end; ++i) val+=_mp_arg(i); return val/(i_end - 3); } static double mp_bitwise_and(_cimg_math_parser& mp) { return (double)((longT)_mp_arg(2) & (longT)_mp_arg(3)); } static double mp_bitwise_left_shift(_cimg_math_parser& mp) { return (double)((longT)_mp_arg(2)<<(unsigned int)_mp_arg(3)); } static double mp_bitwise_not(_cimg_math_parser& mp) { // Limit result to 32bits such that it can be entirely represented as a 'double'. return (double)~(unsigned int)_mp_arg(2); } static double mp_bitwise_or(_cimg_math_parser& mp) { return (double)((longT)_mp_arg(2) | (longT)_mp_arg(3)); } static double mp_bitwise_right_shift(_cimg_math_parser& mp) { return (double)((longT)_mp_arg(2)>>(unsigned int)_mp_arg(3)); } static double mp_bitwise_xor(_cimg_math_parser& mp) { return (double)((longT)_mp_arg(2) ^ (longT)_mp_arg(3)); } static double mp_bool(_cimg_math_parser& mp) { return (double)(bool)_mp_arg(2); } static double mp_break(_cimg_math_parser& mp) { mp.break_type = 1; mp.p_code = mp.p_break - 1; return cimg::type<double>::nan(); } static double mp_breakpoint(_cimg_math_parser& mp) { cimg_abort_init; cimg_abort_test; cimg::unused(mp); return cimg::type<double>::nan(); } static double mp_cats(_cimg_math_parser& mp) { const double *ptrd = &_mp_arg(1) + 1; const unsigned int sizd = (unsigned int)mp.opcode[2], nb_args = (unsigned int)(mp.opcode[3] - 4)/2; CImgList<charT> _str; for (unsigned int n = 0; n<nb_args; ++n) { const unsigned int siz = (unsigned int)mp.opcode[5 + 2*n]; if (siz) { // Vector argument const double *ptrs = &_mp_arg(4 + 2*n) + 1; unsigned int l = 0; while (l<siz && ptrs[l]) ++l; CImg<doubleT>(ptrs,l,1,1,1,true).move_to(_str); } else CImg<charT>::vector((char)_mp_arg(4 + 2*n)).move_to(_str); // Scalar argument } CImg(1,1,1,1,0).move_to(_str); const CImg<charT> str = _str>'x'; const unsigned int l = std::min(str._width,sizd); CImg<doubleT>(ptrd,l,1,1,1,true) = str.get_shared_points(0,l - 1); return cimg::type<double>::nan(); } static double mp_cbrt(_cimg_math_parser& mp) { return cimg::cbrt(_mp_arg(2)); } static double mp_ceil(_cimg_math_parser& mp) { return std::ceil(_mp_arg(2)); } static double mp_complex_abs(_cimg_math_parser& mp) { return cimg::_hypot(_mp_arg(2),_mp_arg(3)); } static double mp_complex_conj(_cimg_math_parser& mp) { const double *ptrs = &_mp_arg(2) + 1; double *ptrd = &_mp_arg(1) + 1; *(ptrd++) = *(ptrs++); *ptrd = -*(ptrs); return cimg::type<double>::nan(); } static double mp_complex_div_sv(_cimg_math_parser& mp) { const double *ptr2 = &_mp_arg(3) + 1, r1 = _mp_arg(2), r2 = *(ptr2++), i2 = *ptr2; double *ptrd = &_mp_arg(1) + 1; const double denom = r2*r2 + i2*i2; *(ptrd++) = r1*r2/denom; *ptrd = -r1*i2/denom; return cimg::type<double>::nan(); } static double mp_complex_div_vv(_cimg_math_parser& mp) { const double *ptr1 = &_mp_arg(2) + 1, *ptr2 = &_mp_arg(3) + 1, r1 = *(ptr1++), i1 = *ptr1, r2 = *(ptr2++), i2 = *ptr2; double *ptrd = &_mp_arg(1) + 1; const double denom = r2*r2 + i2*i2; *(ptrd++) = (r1*r2 + i1*i2)/denom; *ptrd = (r2*i1 - r1*i2)/denom; return cimg::type<double>::nan(); } static double mp_complex_exp(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const double *ptrs = &_mp_arg(2) + 1, r = *(ptrs++), i = *(ptrs), er = std::exp(r); *(ptrd++) = er*std::cos(i); *(ptrd++) = er*std::sin(i); return cimg::type<double>::nan(); } static double mp_complex_log(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const double *ptrs = &_mp_arg(2) + 1, r = *(ptrs++), i = *(ptrs); *(ptrd++) = 0.5*std::log(r*r + i*i); *(ptrd++) = std::atan2(i,r); return cimg::type<double>::nan(); } static double mp_complex_mul(_cimg_math_parser& mp) { const double *ptr1 = &_mp_arg(2) + 1, *ptr2 = &_mp_arg(3) + 1, r1 = *(ptr1++), i1 = *ptr1, r2 = *(ptr2++), i2 = *ptr2; double *ptrd = &_mp_arg(1) + 1; *(ptrd++) = r1*r2 - i1*i2; *(ptrd++) = r1*i2 + r2*i1; return cimg::type<double>::nan(); } static void _mp_complex_pow(const double r1, const double i1, const double r2, const double i2, double *ptrd) { double ro, io; if (cimg::abs(i2)<1e-15) { // Exponent is real if (cimg::abs(r1)<1e-15 && cimg::abs(i1)<1e-15) { if (cimg::abs(r2)<1e-15) { ro = 1; io = 0; } else ro = io = 0; } else { const double mod1_2 = r1*r1 + i1*i1, phi1 = std::atan2(i1,r1), modo = std::pow(mod1_2,0.5*r2), phio = r2*phi1; ro = modo*std::cos(phio); io = modo*std::sin(phio); } } else { // Exponent is complex if (cimg::abs(r1)<1e-15 && cimg::abs(i1)<1e-15) ro = io = 0; const double mod1_2 = r1*r1 + i1*i1, phi1 = std::atan2(i1,r1), modo = std::pow(mod1_2,0.5*r2)*std::exp(-i2*phi1), phio = r2*phi1 + 0.5*i2*std::log(mod1_2); ro = modo*std::cos(phio); io = modo*std::sin(phio); } *(ptrd++) = ro; *ptrd = io; } static double mp_complex_pow_ss(_cimg_math_parser& mp) { const double val1 = _mp_arg(2), val2 = _mp_arg(3); double *ptrd = &_mp_arg(1) + 1; _mp_complex_pow(val1,0,val2,0,ptrd); return cimg::type<double>::nan(); } static double mp_complex_pow_sv(_cimg_math_parser& mp) { const double val1 = _mp_arg(2), *ptr2 = &_mp_arg(3) + 1; double *ptrd = &_mp_arg(1) + 1; _mp_complex_pow(val1,0,ptr2[0],ptr2[1],ptrd); return cimg::type<double>::nan(); } static double mp_complex_pow_vs(_cimg_math_parser& mp) { const double *ptr1 = &_mp_arg(2) + 1, val2 = _mp_arg(3); double *ptrd = &_mp_arg(1) + 1; _mp_complex_pow(ptr1[0],ptr1[1],val2,0,ptrd); return cimg::type<double>::nan(); } static double mp_complex_pow_vv(_cimg_math_parser& mp) { const double *ptr1 = &_mp_arg(2) + 1, *ptr2 = &_mp_arg(3) + 1; double *ptrd = &_mp_arg(1) + 1; _mp_complex_pow(ptr1[0],ptr1[1],ptr2[0],ptr2[1],ptrd); return cimg::type<double>::nan(); } static double mp_continue(_cimg_math_parser& mp) { mp.break_type = 2; mp.p_code = mp.p_break - 1; return cimg::type<double>::nan(); } static double mp_cos(_cimg_math_parser& mp) { return std::cos(_mp_arg(2)); } static double mp_cosh(_cimg_math_parser& mp) { return std::cosh(_mp_arg(2)); } static double mp_critical(_cimg_math_parser& mp) { const double res = _mp_arg(1); cimg_pragma_openmp(critical(mp_critical)) { for (const CImg<ulongT> *const p_end = ++mp.p_code + mp.opcode[2]; mp.p_code<p_end; ++mp.p_code) { // Evaluate body mp.opcode._data = mp.p_code->_data; const ulongT target = mp.opcode[1]; mp.mem[target] = _cimg_mp_defunc(mp); } } --mp.p_code; return res; } static double mp_crop(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const int x = (int)_mp_arg(3), y = (int)_mp_arg(4), z = (int)_mp_arg(5), c = (int)_mp_arg(6); const unsigned int dx = (unsigned int)mp.opcode[7], dy = (unsigned int)mp.opcode[8], dz = (unsigned int)mp.opcode[9], dc = (unsigned int)mp.opcode[10]; const unsigned int boundary_conditions = (unsigned int)_mp_arg(11); unsigned int ind = (unsigned int)mp.opcode[2]; if (ind!=~0U) ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); const CImg<T> &img = ind==~0U?mp.imgin:mp.listin[ind]; if (!img) std::memset(ptrd,0,dx*dy*dz*dc*sizeof(double)); else CImg<doubleT>(ptrd,dx,dy,dz,dc,true) = img.get_crop(x,y,z,c, x + dx - 1,y + dy - 1, z + dz - 1,c + dc - 1, boundary_conditions); return cimg::type<double>::nan(); } static double mp_cross(_cimg_math_parser& mp) { CImg<doubleT> vout(&_mp_arg(1) + 1,1,3,1,1,true), v1(&_mp_arg(2) + 1,1,3,1,1,true), v2(&_mp_arg(3) + 1,1,3,1,1,true); (vout = v1).cross(v2); return cimg::type<double>::nan(); } static double mp_cut(_cimg_math_parser& mp) { double val = _mp_arg(2), cmin = _mp_arg(3), cmax = _mp_arg(4); return val<cmin?cmin:val>cmax?cmax:val; } static double mp_date(_cimg_math_parser& mp) { const unsigned int siz_out = (unsigned int)mp.opcode[2], siz_arg1 = (unsigned int)mp.opcode[4], siz_arg2 = (unsigned int)mp.opcode[6]; double *ptr_out = &_mp_arg(1) + (siz_out?1:0); const double *ptr_arg1 = siz_arg1==~0U?0:&_mp_arg(3) + (siz_arg1?1:0), *ptr_arg2 = siz_arg2==~0U?0:&_mp_arg(5) + 1; if (!ptr_arg2) { // No filename specified if (!siz_arg1) return cimg::date((unsigned int)*ptr_arg1); if (siz_arg1==~0U) for (unsigned int k = 0; k<siz_out; ++k) ptr_out[k] = k; else for (unsigned int k = 0; k<siz_out; ++k) ptr_out[k] = ptr_arg1[k]; cimg::date(ptr_out,siz_out); return cimg::type<double>::nan(); } // Filename specified. CImg<charT> ss(siz_arg2 + 1); cimg_forX(ss,i) ss[i] = (char)ptr_arg2[i]; ss.back() = 0; if (!siz_arg1) return cimg::fdate(ss,(unsigned int)*ptr_arg1); for (unsigned int k = 0; k<siz_out; ++k) ptr_out[k] = ptr_arg1[k]; cimg::fdate(ss,ptr_out,siz_out); return cimg::type<double>::nan(); } static double mp_debug(_cimg_math_parser& mp) { CImg<charT> expr(mp.opcode[2] - 4); { const ulongT *ptrs = mp.opcode._data + 4; cimg_for(expr,ptrd,char) *ptrd = (char)*(ptrs++); } cimg::strellipsize(expr); const ulongT g_target = mp.opcode[1]; #if cimg_use_openmp==0 const unsigned int n_thread = 0; #else const unsigned int n_thread = omp_get_thread_num(); #endif cimg_pragma_openmp(critical(mp_debug)) { std::fprintf(cimg::output(), "\n[" cimg_appname "_math_parser] %p[thread #%u]:%*c" "Start debugging expression '%s', code length %u -> mem[%u] (memsize: %u)", (void*)&mp,n_thread,mp.debug_indent,' ', expr._data,(unsigned int)mp.opcode[3],(unsigned int)g_target,mp.mem._width); std::fflush(cimg::output()); mp.debug_indent+=3; } const CImg<ulongT> *const p_end = (++mp.p_code) + mp.opcode[3]; CImg<ulongT> _op; for ( ; mp.p_code<p_end; ++mp.p_code) { const CImg<ulongT> &op = *mp.p_code; mp.opcode._data = op._data; _op.assign(1,op._height - 1); const ulongT *ptrs = op._data + 1; for (ulongT *ptrd = _op._data, *const ptrde = _op._data + _op._height; ptrd<ptrde; ++ptrd) *ptrd = *(ptrs++); const ulongT target = mp.opcode[1]; mp.mem[target] = _cimg_mp_defunc(mp); cimg_pragma_openmp(critical(mp_debug)) { std::fprintf(cimg::output(), "\n[" cimg_appname "_math_parser] %p[thread #%u]:%*c" "Opcode %p = [ %p,%s ] -> mem[%u] = %g", (void*)&mp,n_thread,mp.debug_indent,' ', (void*)mp.opcode._data,(void*)*mp.opcode,_op.value_string().data(), (unsigned int)target,mp.mem[target]); std::fflush(cimg::output()); } } cimg_pragma_openmp(critical(mp_debug)) { mp.debug_indent-=3; std::fprintf(cimg::output(), "\n[" cimg_appname "_math_parser] %p[thread #%u]:%*c" "End debugging expression '%s' -> mem[%u] = %g (memsize: %u)", (void*)&mp,n_thread,mp.debug_indent,' ', expr._data,(unsigned int)g_target,mp.mem[g_target],mp.mem._width); std::fflush(cimg::output()); } --mp.p_code; return mp.mem[g_target]; } static double mp_decrement(_cimg_math_parser& mp) { return _mp_arg(2) - 1; } static double mp_det(_cimg_math_parser& mp) { const double *ptrs = &_mp_arg(2) + 1; const unsigned int k = (unsigned int)mp.opcode[3]; return CImg<doubleT>(ptrs,k,k,1,1,true).det(); } static double mp_diag(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2], siz = mp.opcode[2] - 3; double *ptrd = &_mp_arg(1) + 1; std::memset(ptrd,0,siz*siz*sizeof(double)); for (unsigned int i = 3; i<i_end; ++i) { *(ptrd++) = _mp_arg(i); ptrd+=siz; } return cimg::type<double>::nan(); } static double mp_display_memory(_cimg_math_parser& mp) { cimg::unused(mp); std::fputc('\n',cimg::output()); mp.mem.display("[" cimg_appname "_math_parser] Memory snapshot"); return cimg::type<double>::nan(); } static double mp_display(_cimg_math_parser& mp) { const unsigned int _siz = (unsigned int)mp.opcode[3], siz = _siz?_siz:1; const double *const ptr = &_mp_arg(1) + (_siz?1:0); const int w = (int)_mp_arg(4), h = (int)_mp_arg(5), d = (int)_mp_arg(6), s = (int)_mp_arg(7); CImg<doubleT> img; if (w>0 && h>0 && d>0 && s>0) { if ((unsigned int)w*h*d*s<=siz) img.assign(ptr,w,h,d,s,true); else img.assign(ptr,siz).resize(w,h,d,s,-1); } else img.assign(ptr,1,siz,1,1,true); CImg<charT> expr(mp.opcode[2] - 8); const ulongT *ptrs = mp.opcode._data + 8; cimg_for(expr,ptrd,char) *ptrd = (char)*(ptrs++); ((CImg<charT>::string("[" cimg_appname "_math_parser] ",false,true),expr)>'x').move_to(expr); cimg::strellipsize(expr); std::fputc('\n',cimg::output()); img.display(expr._data); return cimg::type<double>::nan(); } static double mp_div(_cimg_math_parser& mp) { return _mp_arg(2)/_mp_arg(3); } static double mp_dot(_cimg_math_parser& mp) { const unsigned int siz = (unsigned int)mp.opcode[4]; return CImg<doubleT>(&_mp_arg(2) + 1,1,siz,1,1,true). dot(CImg<doubleT>(&_mp_arg(3) + 1,1,siz,1,1,true)); } static double mp_do(_cimg_math_parser& mp) { const ulongT mem_body = mp.opcode[1], mem_cond = mp.opcode[2]; const CImg<ulongT> *const p_body = ++mp.p_code, *const p_cond = p_body + mp.opcode[3], *const p_end = p_cond + mp.opcode[4]; const unsigned int vsiz = (unsigned int)mp.opcode[5]; if (mp.opcode[6]) { // Set default value for result and condition if necessary if (vsiz) CImg<doubleT>(&mp.mem[mem_body] + 1,vsiz,1,1,1,true).fill(cimg::type<double>::nan()); else mp.mem[mem_body] = cimg::type<double>::nan(); } if (mp.opcode[7]) mp.mem[mem_cond] = 0; const unsigned int _break_type = mp.break_type; mp.break_type = 0; do { for (mp.p_code = p_body; mp.p_code<p_cond; ++mp.p_code) { // Evaluate body mp.opcode._data = mp.p_code->_data; const ulongT target = mp.opcode[1]; mp.mem[target] = _cimg_mp_defunc(mp); } if (mp.break_type==1) break; else if (mp.break_type==2) mp.break_type = 0; for (mp.p_code = p_cond; mp.p_code<p_end; ++mp.p_code) { // Evaluate condition mp.opcode._data = mp.p_code->_data; const ulongT target = mp.opcode[1]; mp.mem[target] = _cimg_mp_defunc(mp); } if (mp.break_type==1) break; else if (mp.break_type==2) mp.break_type = 0; } while (mp.mem[mem_cond]); mp.break_type = _break_type; mp.p_code = p_end - 1; return mp.mem[mem_body]; } static double mp_draw(_cimg_math_parser& mp) { const int x = (int)_mp_arg(4), y = (int)_mp_arg(5), z = (int)_mp_arg(6), c = (int)_mp_arg(7); unsigned int ind = (unsigned int)mp.opcode[3]; if (ind!=~0U) ind = (unsigned int)cimg::mod((int)_mp_arg(3),mp.listin.width()); CImg<T> &img = ind==~0U?mp.imgout:mp.listout[ind]; unsigned int dx = (unsigned int)mp.opcode[8], dy = (unsigned int)mp.opcode[9], dz = (unsigned int)mp.opcode[10], dc = (unsigned int)mp.opcode[11]; dx = dx==~0U?img._width:(unsigned int)_mp_arg(8); dy = dy==~0U?img._height:(unsigned int)_mp_arg(9); dz = dz==~0U?img._depth:(unsigned int)_mp_arg(10); dc = dc==~0U?img._spectrum:(unsigned int)_mp_arg(11); const ulongT sizS = mp.opcode[2]; if (sizS<(ulongT)dx*dy*dz*dc) throw CImgArgumentException("[" cimg_appname "_math_parser] CImg<%s>: Function 'draw()': " "Sprite dimension (%lu values) and specified sprite geometry (%u,%u,%u,%u) " "(%lu values) do not match.", mp.imgin.pixel_type(),sizS,dx,dy,dz,dc,(ulongT)dx*dy*dz*dc); CImg<doubleT> S(&_mp_arg(1) + 1,dx,dy,dz,dc,true); const float opacity = (float)_mp_arg(12); if (img._data) { if (mp.opcode[13]!=~0U) { // Opacity mask specified const ulongT sizM = mp.opcode[14]; if (sizM<(ulongT)dx*dy*dz) throw CImgArgumentException("[" cimg_appname "_math_parser] CImg<%s>: Function 'draw()': " "Mask dimension (%lu values) and specified sprite geometry (%u,%u,%u,%u) " "(%lu values) do not match.", mp.imgin.pixel_type(),sizS,dx,dy,dz,dc,(ulongT)dx*dy*dz*dc); const CImg<doubleT> M(&_mp_arg(13) + 1,dx,dy,dz,(unsigned int)(sizM/(dx*dy*dz)),true); img.draw_image(x,y,z,c,S,M,opacity,(float)_mp_arg(15)); } else img.draw_image(x,y,z,c,S,opacity); } return cimg::type<double>::nan(); } static double mp_echo(_cimg_math_parser& mp) { const unsigned int nb_args = (unsigned int)(mp.opcode[2] - 3)/2; CImgList<charT> _str; CImg<charT> it; for (unsigned int n = 0; n<nb_args; ++n) { const unsigned int siz = (unsigned int)mp.opcode[4 + 2*n]; if (siz) { // Vector argument -> string const double *ptr = &_mp_arg(3 + 2*n) + 1; unsigned int l = 0; while (l<siz && ptr[l]) ++l; CImg<doubleT>(ptr,l,1,1,1,true).move_to(_str); } else { // Scalar argument -> number it.assign(256); cimg_snprintf(it,it._width,"%.17g",_mp_arg(3 + 2*n)); CImg<charT>::string(it,false,true).move_to(_str); } } CImg(1,1,1,1,0).move_to(_str); const CImg<charT> str = _str>'x'; std::fprintf(cimg::output(),"\n%s",str._data); return cimg::type<double>::nan(); } static double mp_ellipse(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; unsigned int ind = (unsigned int)mp.opcode[3]; if (ind!=~0U) ind = (unsigned int)cimg::mod((int)_mp_arg(3),mp.listin.width()); CImg<T> &img = ind==~0U?mp.imgout:mp.listout[ind]; CImg<T> color(img._spectrum,1,1,1,0); bool is_invalid_arguments = false, is_outlined = false; float r1 = 0, r2 = 0, angle = 0, opacity = 1; unsigned int i = 4, pattern = ~0U; int x0 = 0, y0 = 0; if (i>=i_end) is_invalid_arguments = true; else { x0 = (int)cimg::round(_mp_arg(i++)); if (i>=i_end) is_invalid_arguments = true; else { y0 = (int)cimg::round(_mp_arg(i++)); if (i>=i_end) is_invalid_arguments = true; else { r1 = (float)_mp_arg(i++); if (i>=i_end) r2 = r1; else { r2 = (float)_mp_arg(i++); if (i<i_end) { angle = (float)_mp_arg(i++); if (i<i_end) { opacity = (float)_mp_arg(i++); if (r1<0 && r2<0) { pattern = (unsigned int)_mp_arg(i++); is_outlined = true; r1 = -r1; r2 = -r2; } if (i<i_end) { cimg_forX(color,k) if (i<i_end) color[k] = (T)_mp_arg(i++); else { color.resize(k,1,1,1,-1); break; } color.resize(img._spectrum,1,1,1,0,2); } } } } } } } if (!is_invalid_arguments) { if (is_outlined) img.draw_ellipse(x0,y0,r1,r2,angle,color._data,opacity,pattern); else img.draw_ellipse(x0,y0,r1,r2,angle,color._data,opacity); } else { CImg<doubleT> args(i_end - 4); cimg_forX(args,k) args[k] = _mp_arg(4 + k); if (ind==~0U) throw CImgArgumentException("[" cimg_appname "_math_parser] CImg<%s>: Function 'ellipse()': " "Invalid arguments '%s'. ", mp.imgin.pixel_type(),args.value_string()._data); else throw CImgArgumentException("[" cimg_appname "_math_parser] CImg<%s>: Function 'ellipse()': " "Invalid arguments '#%u%s%s'. ", mp.imgin.pixel_type(),ind,args._width?",":"",args.value_string()._data); } return cimg::type<double>::nan(); } static double mp_eq(_cimg_math_parser& mp) { return (double)(_mp_arg(2)==_mp_arg(3)); } static double mp_ext(_cimg_math_parser& mp) { const unsigned int nb_args = (unsigned int)(mp.opcode[2] - 3)/2; CImgList<charT> _str; CImg<charT> it; for (unsigned int n = 0; n<nb_args; ++n) { const unsigned int siz = (unsigned int)mp.opcode[4 + 2*n]; if (siz) { // Vector argument -> string const double *ptr = &_mp_arg(3 + 2*n) + 1; unsigned int l = 0; while (l<siz && ptr[l]) ++l; CImg<doubleT>(ptr,l,1,1,1,true).move_to(_str); } else { // Scalar argument -> number it.assign(256); cimg_snprintf(it,it._width,"%.17g",_mp_arg(3 + 2*n)); CImg<charT>::string(it,false,true).move_to(_str); } } CImg(1,1,1,1,0).move_to(_str); CImg<charT> str = _str>'x'; #ifdef cimg_mp_ext_function cimg_mp_ext_function(str); #endif return cimg::type<double>::nan(); } static double mp_exp(_cimg_math_parser& mp) { return std::exp(_mp_arg(2)); } static double mp_eye(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const unsigned int k = (unsigned int)mp.opcode[2]; CImg<doubleT>(ptrd,k,k,1,1,true).identity_matrix(); return cimg::type<double>::nan(); } static double mp_factorial(_cimg_math_parser& mp) { return cimg::factorial((int)_mp_arg(2)); } static double mp_fibonacci(_cimg_math_parser& mp) { return cimg::fibonacci((int)_mp_arg(2)); } static double mp_find(_cimg_math_parser& mp) { const bool is_forward = (bool)_mp_arg(5); const ulongT siz = (ulongT)mp.opcode[3]; longT ind = (longT)(mp.opcode[6]!=_cimg_mp_slot_nan?_mp_arg(6):is_forward?0:siz - 1); if (ind<0 || ind>=(longT)siz) return -1.; const double *const ptrb = &_mp_arg(2) + 1, *const ptre = ptrb + siz, val = _mp_arg(4), *ptr = ptrb + ind; // Forward search if (is_forward) { while (ptr<ptre && *ptr!=val) ++ptr; return ptr==ptre?-1.:(double)(ptr - ptrb); } // Backward search. while (ptr>=ptrb && *ptr!=val) --ptr; return ptr<ptrb?-1.:(double)(ptr - ptrb); } static double mp_find_seq(_cimg_math_parser& mp) { const bool is_forward = (bool)_mp_arg(6); const ulongT siz1 = (ulongT)mp.opcode[3], siz2 = (ulongT)mp.opcode[5]; longT ind = (longT)(mp.opcode[7]!=_cimg_mp_slot_nan?_mp_arg(7):is_forward?0:siz1 - 1); if (ind<0 || ind>=(longT)siz1) return -1.; const double *const ptr1b = &_mp_arg(2) + 1, *const ptr1e = ptr1b + siz1, *const ptr2b = &_mp_arg(4) + 1, *const ptr2e = ptr2b + siz2, *ptr1 = ptr1b + ind, *p1 = 0, *p2 = 0; // Forward search. if (is_forward) { do { while (ptr1<ptr1e && *ptr1!=*ptr2b) ++ptr1; if (ptr1>=ptr1e) return -1.; p1 = ptr1 + 1; p2 = ptr2b + 1; while (p1<ptr1e && p2<ptr2e && *p1==*p2) { ++p1; ++p2; } } while (p2<ptr2e && ++ptr1<ptr1e); return p2<ptr2e?-1.:(double)(ptr1 - ptr1b); } // Backward search. do { while (ptr1>=ptr1b && *ptr1!=*ptr2b) --ptr1; if (ptr1<ptr1b) return -1.; p1 = ptr1 + 1; p2 = ptr2b + 1; while (p1<ptr1e && p2<ptr2e && *p1==*p2) { ++p1; ++p2; } } while (p2<ptr2e && --ptr1>=ptr1b); return p2<ptr2e?-1.:(double)(ptr1 - ptr1b); } static double mp_floor(_cimg_math_parser& mp) { return std::floor(_mp_arg(2)); } static double mp_for(_cimg_math_parser& mp) { const ulongT mem_body = mp.opcode[1], mem_cond = mp.opcode[3]; const CImg<ulongT> *const p_init = ++mp.p_code, *const p_cond = p_init + mp.opcode[4], *const p_body = p_cond + mp.opcode[5], *const p_post = p_body + mp.opcode[6], *const p_end = p_post + mp.opcode[7]; const unsigned int vsiz = (unsigned int)mp.opcode[2]; bool is_cond = false; if (mp.opcode[8]) { // Set default value for result and condition if necessary if (vsiz) CImg<doubleT>(&mp.mem[mem_body] + 1,vsiz,1,1,1,true).fill(cimg::type<double>::nan()); else mp.mem[mem_body] = cimg::type<double>::nan(); } if (mp.opcode[9]) mp.mem[mem_cond] = 0; const unsigned int _break_type = mp.break_type; mp.break_type = 0; for (mp.p_code = p_init; mp.p_code<p_cond; ++mp.p_code) { // Evaluate init mp.opcode._data = mp.p_code->_data; const ulongT target = mp.opcode[1]; mp.mem[target] = _cimg_mp_defunc(mp); } if (!mp.break_type) do { for (mp.p_code = p_cond; mp.p_code<p_body; ++mp.p_code) { // Evaluate condition mp.opcode._data = mp.p_code->_data; const ulongT target = mp.opcode[1]; mp.mem[target] = _cimg_mp_defunc(mp); } if (mp.break_type==1) break; is_cond = (bool)mp.mem[mem_cond]; if (is_cond && !mp.break_type) { for (mp.p_code = p_body; mp.p_code<p_post; ++mp.p_code) { // Evaluate body mp.opcode._data = mp.p_code->_data; const ulongT target = mp.opcode[1]; mp.mem[target] = _cimg_mp_defunc(mp); } if (mp.break_type==1) break; else if (mp.break_type==2) mp.break_type = 0; for (mp.p_code = p_post; mp.p_code<p_end; ++mp.p_code) { // Evaluate post-code mp.opcode._data = mp.p_code->_data; const ulongT target = mp.opcode[1]; mp.mem[target] = _cimg_mp_defunc(mp); } if (mp.break_type==1) break; else if (mp.break_type==2) mp.break_type = 0; } } while (is_cond); mp.break_type = _break_type; mp.p_code = p_end - 1; return mp.mem[mem_body]; } static double mp_fsize(_cimg_math_parser& mp) { const double *ptrs = &_mp_arg(2) + 1; const ulongT siz = (ulongT)mp.opcode[3]; CImg<charT> ss(siz + 1); cimg_forX(ss,i) ss[i] = (char)ptrs[i]; ss.back() = 0; return (double)cimg::fsize(ss); } static double mp_g(_cimg_math_parser& mp) { cimg::unused(mp); return cimg::grand(&mp.rng); } static double mp_gauss(_cimg_math_parser& mp) { const double x = _mp_arg(2), s = _mp_arg(3); return std::exp(-x*x/(2*s*s))/(_mp_arg(4)?std::sqrt(2*s*s*cimg::PI):1); } static double mp_gcd(_cimg_math_parser& mp) { return cimg::gcd((long)_mp_arg(2),(long)_mp_arg(3)); } static double mp_gt(_cimg_math_parser& mp) { return (double)(_mp_arg(2)>_mp_arg(3)); } static double mp_gte(_cimg_math_parser& mp) { return (double)(_mp_arg(2)>=_mp_arg(3)); } static double mp_i(_cimg_math_parser& mp) { return (double)mp.imgin.atXYZC((int)mp.mem[_cimg_mp_slot_x],(int)mp.mem[_cimg_mp_slot_y], (int)mp.mem[_cimg_mp_slot_z],(int)mp.mem[_cimg_mp_slot_c],(T)0); } static double mp_if(_cimg_math_parser& mp) { const bool is_cond = (bool)_mp_arg(2); const ulongT mem_left = mp.opcode[3], mem_right = mp.opcode[4]; const CImg<ulongT> *const p_right = ++mp.p_code + mp.opcode[5], *const p_end = p_right + mp.opcode[6]; const unsigned int vtarget = (unsigned int)mp.opcode[1], vsiz = (unsigned int)mp.opcode[7]; if (is_cond) for ( ; mp.p_code<p_right; ++mp.p_code) { mp.opcode._data = mp.p_code->_data; const ulongT target = mp.opcode[1]; mp.mem[target] = _cimg_mp_defunc(mp); } else for (mp.p_code = p_right; mp.p_code<p_end; ++mp.p_code) { mp.opcode._data = mp.p_code->_data; const ulongT target = mp.opcode[1]; mp.mem[target] = _cimg_mp_defunc(mp); } if (mp.p_code==mp.p_break) --mp.p_code; else mp.p_code = p_end - 1; if (vsiz) std::memcpy(&mp.mem[vtarget] + 1,&mp.mem[is_cond?mem_left:mem_right] + 1,sizeof(double)*vsiz); return mp.mem[is_cond?mem_left:mem_right]; } static double mp_image_d(_cimg_math_parser& mp) { unsigned int ind = (unsigned int)mp.opcode[2]; if (ind!=~0U) ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); const CImg<T> &img = ind==~0U?mp.imgout:mp.listout[ind]; return (double)img.depth(); } static double mp_image_display(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listout.width()); cimg::mutex(6); CImg<T> &img = mp.listout[ind]; CImg<charT> title(256); std::fputc('\n',cimg::output()); cimg_snprintf(title,title._width,"[ Image #%u ]",ind); img.display(title); cimg::mutex(6,0); return cimg::type<double>::nan(); } static double mp_image_h(_cimg_math_parser& mp) { unsigned int ind = (unsigned int)mp.opcode[2]; if (ind!=~0U) ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); const CImg<T> &img = ind==~0U?mp.imgout:mp.listout[ind]; return (double)img.height(); } static double mp_image_median(_cimg_math_parser& mp) { unsigned int ind = (unsigned int)mp.opcode[2]; if (ind!=~0U) ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); const CImg<T> &img = ind==~0U?mp.imgout:mp.listout[ind]; return (double)img.median(); } static double mp_image_print(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listout.width()); cimg::mutex(6); CImg<T> &img = mp.listout[ind]; CImg<charT> title(256); std::fputc('\n',cimg::output()); cimg_snprintf(title,title._width,"[ Image #%u ]",ind); img.print(title); cimg::mutex(6,0); return cimg::type<double>::nan(); } static double mp_image_resize(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listout.width()); cimg::mutex(6); CImg<T> &img = mp.listout[ind]; const double _w = mp.opcode[3]==~0U?-100:_mp_arg(3), _h = mp.opcode[4]==~0U?-100:_mp_arg(4), _d = mp.opcode[5]==~0U?-100:_mp_arg(5), _s = mp.opcode[6]==~0U?-100:_mp_arg(6); const unsigned int w = (unsigned int)(_w>=0?_w:-_w*img.width()/100), h = (unsigned int)(_h>=0?_h:-_h*img.height()/100), d = (unsigned int)(_d>=0?_d:-_d*img.depth()/100), s = (unsigned int)(_s>=0?_s:-_s*img.spectrum()/100), interp = (int)_mp_arg(7); if (mp.is_fill && img._data==mp.imgout._data) { cimg::mutex(6,0); throw CImgArgumentException("[" cimg_appname "_math_parser] CImg<%s>: Function 'resize()': " "Cannot both fill and resize image (%u,%u,%u,%u) " "to new dimensions (%u,%u,%u,%u).", img.pixel_type(),img._width,img._height,img._depth,img._spectrum,w,h,d,s); } const unsigned int boundary = (int)_mp_arg(8); const float cx = (float)_mp_arg(9), cy = (float)_mp_arg(10), cz = (float)_mp_arg(11), cc = (float)_mp_arg(12); img.resize(w,h,d,s,interp,boundary,cx,cy,cz,cc); cimg::mutex(6,0); return cimg::type<double>::nan(); } static double mp_image_s(_cimg_math_parser& mp) { unsigned int ind = (unsigned int)mp.opcode[2]; if (ind!=~0U) ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); const CImg<T> &img = ind==~0U?mp.imgout:mp.listout[ind]; return (double)img.spectrum(); } static double mp_image_sort(_cimg_math_parser& mp) { const bool is_increasing = (bool)_mp_arg(3); const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listout.width()), axis = (unsigned int)_mp_arg(4); cimg::mutex(6); CImg<T> &img = mp.listout[ind]; img.sort(is_increasing, axis==0 || axis=='x'?'x': axis==1 || axis=='y'?'y': axis==2 || axis=='z'?'z': axis==3 || axis=='c'?'c':0); cimg::mutex(6,0); return cimg::type<double>::nan(); } static double mp_image_stats(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; unsigned int ind = (unsigned int)mp.opcode[2]; if (ind==~0U) CImg<doubleT>(ptrd,14,1,1,1,true) = mp.imgout.get_stats(); else { ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); CImg<doubleT>(ptrd,14,1,1,1,true) = mp.listout[ind].get_stats(); } return cimg::type<double>::nan(); } static double mp_image_w(_cimg_math_parser& mp) { unsigned int ind = (unsigned int)mp.opcode[2]; if (ind!=~0U) ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); const CImg<T> &img = ind==~0U?mp.imgout:mp.listout[ind]; return (double)img.width(); } static double mp_image_wh(_cimg_math_parser& mp) { unsigned int ind = (unsigned int)mp.opcode[2]; if (ind!=~0U) ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); const CImg<T> &img = ind==~0U?mp.imgout:mp.listout[ind]; return (double)img.width()*img.height(); } static double mp_image_whd(_cimg_math_parser& mp) { unsigned int ind = (unsigned int)mp.opcode[2]; if (ind!=~0U) ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); const CImg<T> &img = ind==~0U?mp.imgout:mp.listout[ind]; return (double)img.width()*img.height()*img.depth(); } static double mp_image_whds(_cimg_math_parser& mp) { unsigned int ind = (unsigned int)mp.opcode[2]; if (ind!=~0U) ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); const CImg<T> &img = ind==~0U?mp.imgout:mp.listout[ind]; return (double)img.width()*img.height()*img.depth()*img.spectrum(); } static double mp_increment(_cimg_math_parser& mp) { return _mp_arg(2) + 1; } static double mp_int(_cimg_math_parser& mp) { return (double)(longT)_mp_arg(2); } static double mp_ioff(_cimg_math_parser& mp) { const unsigned int boundary_conditions = (unsigned int)_mp_arg(3); const CImg<T> &img = mp.imgin; const longT off = (longT)_mp_arg(2), whds = (longT)img.size(); if (off>=0 && off<whds) return (double)img[off]; if (img._data) switch (boundary_conditions) { case 3 : { // Mirror const longT whds2 = 2*whds, moff = cimg::mod(off,whds2); return (double)img[moff<whds?moff:whds2 - moff - 1]; } case 2 : // Periodic return (double)img[cimg::mod(off,whds)]; case 1 : // Neumann return (double)img[off<0?0:whds - 1]; default : // Dirichlet return 0; } return 0; } static double mp_isbool(_cimg_math_parser& mp) { const double val = _mp_arg(2); return (double)(val==0. || val==1.); } static double mp_isdir(_cimg_math_parser& mp) { const double *ptrs = &_mp_arg(2) + 1; const ulongT siz = (ulongT)mp.opcode[3]; CImg<charT> ss(siz + 1); cimg_forX(ss,i) ss[i] = (char)ptrs[i]; ss.back() = 0; return (double)cimg::is_directory(ss); } static double mp_isin(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; const double val = _mp_arg(3); for (unsigned int i = 4; i<i_end; ++i) if (val==_mp_arg(i)) return 1.; return 0.; } static double mp_isinf(_cimg_math_parser& mp) { return (double)cimg::type<double>::is_inf(_mp_arg(2)); } static double mp_isint(_cimg_math_parser& mp) { return (double)(cimg::mod(_mp_arg(2),1.)==0); } static double mp_isfile(_cimg_math_parser& mp) { const double *ptrs = &_mp_arg(2) + 1; const ulongT siz = (ulongT)mp.opcode[3]; CImg<charT> ss(siz + 1); cimg_forX(ss,i) ss[i] = (char)ptrs[i]; ss.back() = 0; return (double)cimg::is_file(ss); } static double mp_isnan(_cimg_math_parser& mp) { return (double)cimg::type<double>::is_nan(_mp_arg(2)); } static double mp_ixyzc(_cimg_math_parser& mp) { const unsigned int interpolation = (unsigned int)_mp_arg(6), boundary_conditions = (unsigned int)_mp_arg(7); const CImg<T> &img = mp.imgin; const double x = _mp_arg(2), y = _mp_arg(3), z = _mp_arg(4), c = _mp_arg(5); switch (interpolation) { case 2 : // Cubic interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), s2 = 2.f*img.spectrum(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), mc = cimg::mod((float)c,s2); return (double)img._cubic_atXYZ(mx<img.width()?mx:w2 - mx - 1, my<img.height()?my:h2 - my - 1, mz<img.depth()?mz:d2 - mz - 1, (int)(mc<img.spectrum()?mc:s2 - mc - 1)); } case 2 : // Periodic return (double)img._cubic_atXYZ_p((float)x,(float)y,(float)z, (int)cimg::mod(c,(double)img._spectrum)); case 1 : // Neumann return (double)img._cubic_atXYZ((float)x,(float)y,(float)z, (int)(c<0?0:c>=img._spectrum?img._spectrum - 1:c)); default : // Dirichlet if (c<0 || c>=img._spectrum) return (T)0; return (double)img.cubic_atXYZ((float)x,(float)y,(float)z,(int)c,(T)0); } case 1 : // Linear interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), s2 = 2.f*img.spectrum(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), mc = cimg::mod((float)c,s2); return (double)img._linear_atXYZ(mx<img.width()?mx:w2 - mx - 1, my<img.height()?my:h2 - my - 1, mz<img.depth()?mz:d2 - mz - 1, (int)(mc<img.spectrum()?mc:s2 - mc - 1)); } case 2 : // Periodic return (double)img._linear_atXYZ_p((float)x,(float)y,(float)z, (int)cimg::mod(c,(double)img._spectrum)); case 1 : // Neumann return (double)img._linear_atXYZ((float)x,(float)y,(float)z, (int)(c<0?0:c>=img._spectrum?img._spectrum - 1:c)); default : // Dirichlet if (c<0 || c>=img._spectrum) return (T)0; return (double)img.linear_atXYZ((float)x,(float)y,(float)z,(int)c,(T)0); } default : // Nearest neighbor interpolation switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*img.width(), h2 = 2*img.height(), d2 = 2*img.depth(), s2 = 2*img.spectrum(), mx = cimg::mod((int)x,w2), my = cimg::mod((int)y,h2), mz = cimg::mod((int)z,d2), mc = cimg::mod((int)c,s2); return (double)img(mx<img.width()?mx:w2 - mx - 1, my<img.height()?my:h2 - my - 1, mz<img.depth()?mz:d2 - mz - 1, mc<img.spectrum()?mc:s2 - mc - 1); } case 2 : // Periodic return (double)img((int)cimg::mod(x,(double)img._width), (int)cimg::mod(y,(double)img._height), (int)cimg::mod(z,(double)img._depth), (int)cimg::mod(c,(double)img._spectrum)); case 1 : // Neumann return (double)img._atXYZC((int)x,(int)y,(int)z,(int)c); default : // Dirichlet return (double)img.atXYZC((int)x,(int)y,(int)z,(int)c,(T)0); } } } static double mp_joff(_cimg_math_parser& mp) { const unsigned int boundary_conditions = (unsigned int)_mp_arg(3); const int ox = (int)mp.mem[_cimg_mp_slot_x], oy = (int)mp.mem[_cimg_mp_slot_y], oz = (int)mp.mem[_cimg_mp_slot_z], oc = (int)mp.mem[_cimg_mp_slot_c]; const CImg<T> &img = mp.imgin; const longT off = img.offset(ox,oy,oz,oc) + (longT)_mp_arg(2), whds = (longT)img.size(); if (off>=0 && off<whds) return (double)img[off]; if (img._data) switch (boundary_conditions) { case 3 : { // Mirror const longT whds2 = 2*whds, moff = cimg::mod(off,whds2); return (double)img[moff<whds?moff:whds2 - moff - 1]; } case 2 : // Periodic return (double)img[cimg::mod(off,whds)]; case 1 : // Neumann return (double)img[off<0?0:whds - 1]; default : // Dirichlet return 0; } return 0; } static double mp_jxyzc(_cimg_math_parser& mp) { const unsigned int interpolation = (unsigned int)_mp_arg(6), boundary_conditions = (unsigned int)_mp_arg(7); const CImg<T> &img = mp.imgin; const double ox = mp.mem[_cimg_mp_slot_x], oy = mp.mem[_cimg_mp_slot_y], oz = mp.mem[_cimg_mp_slot_z], oc = mp.mem[_cimg_mp_slot_c], x = ox + _mp_arg(2), y = oy + _mp_arg(3), z = oz + _mp_arg(4), c = oc + _mp_arg(5); switch (interpolation) { case 2 : // Cubic interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), s2 = 2.f*img.spectrum(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), mc = cimg::mod((float)c,s2); return (double)img._cubic_atXYZ(mx<img.width()?mx:w2 - mx - 1, my<img.height()?my:h2 - my - 1, mz<img.depth()?mz:d2 - mz - 1, (int)(mc<img.spectrum()?mc:s2 - mc - 1)); } case 2 : // Periodic return (double)img._cubic_atXYZ_p((float)x,(float)y,(float)z, (int)cimg::mod(c,(double)img._spectrum)); case 1 : // Neumann return (double)img._cubic_atXYZ((float)x,(float)y,(float)z, (int)(c<0?0:c>=img._spectrum?img._spectrum - 1:c)); default : // Dirichlet if (c<0 || c>=img._spectrum) return (T)0; return (double)img.cubic_atXYZ((float)x,(float)y,(float)z,(int)c,(T)0); } case 1 : // Linear interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), s2 = 2.f*img.spectrum(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), mc = cimg::mod((float)c,s2); return (double)img._linear_atXYZ(mx<img.width()?mx:w2 - mx - 1, my<img.height()?my:h2 - my - 1, mz<img.depth()?mz:d2 - mz - 1, (int)(mc<img.spectrum()?mc:s2 - mc - 1)); } case 2 : // Periodic return (double)img._linear_atXYZ_p((float)x,(float)y,(float)z, (int)cimg::mod(c,(double)img._spectrum)); case 1 : // Neumann return (double)img._linear_atXYZ((float)x,(float)y,(float)z, (int)(c<0?0:c>=img._spectrum?img._spectrum - 1:c)); default : // Dirichlet if (c<0 || c>=img._spectrum) return (T)0; return (double)img.linear_atXYZ((float)x,(float)y,(float)z,(int)c,(T)0); } default : // Nearest neighbor interpolation switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*img.width(), h2 = 2*img.height(), d2 = 2*img.depth(), s2 = 2*img.spectrum(), mx = cimg::mod((int)x,w2), my = cimg::mod((int)y,h2), mz = cimg::mod((int)z,d2), mc = cimg::mod((int)c,s2); return (double)img(mx<img.width()?mx:w2 - mx - 1, my<img.height()?my:h2 - my - 1, mz<img.depth()?mz:d2 - mz - 1, mc<img.spectrum()?mc:s2 - mc - 1); } case 2 : // Periodic return (double)img((int)cimg::mod(x,(double)img._width), (int)cimg::mod(y,(double)img._height), (int)cimg::mod(z,(double)img._depth), (int)cimg::mod(c,(double)img._spectrum)); case 1 : // Neumann return (double)img._atXYZC((int)x,(int)y,(int)z,(int)c); default : // Dirichlet return (double)img.atXYZC((int)x,(int)y,(int)z,(int)c,(T)0); } } } static double mp_kth(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; CImg<doubleT> vals(i_end - 4); double *p = vals.data(); for (unsigned int i = 4; i<i_end; ++i) *(p++) = _mp_arg(i); int ind = (int)cimg::round(_mp_arg(3)); if (ind<0) ind+=vals.width() + 1; ind = std::max(1,std::min(vals.width(),ind)); return vals.kth_smallest(ind - 1); } static double mp_linear_add(_cimg_math_parser& mp) { return _mp_arg(2)*_mp_arg(3) + _mp_arg(4); } static double mp_linear_sub_left(_cimg_math_parser& mp) { return _mp_arg(2)*_mp_arg(3) - _mp_arg(4); } static double mp_linear_sub_right(_cimg_math_parser& mp) { return _mp_arg(4) - _mp_arg(2)*_mp_arg(3); } static double mp_list_depth(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); return (double)mp.listin[ind]._depth; } static double mp_list_find(_cimg_math_parser& mp) { const unsigned int indi = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); const CImg<T> &img = mp.listin[indi]; const bool is_forward = (bool)_mp_arg(4); const ulongT siz = (ulongT)img.size(); longT ind = (longT)(mp.opcode[5]!=_cimg_mp_slot_nan?_mp_arg(5):is_forward?0:siz - 1); if (ind<0 || ind>=(longT)siz) return -1.; const T *const ptrb = img.data(), *const ptre = img.end(), *ptr = ptrb + ind; const double val = _mp_arg(3); // Forward search if (is_forward) { while (ptr<ptre && (double)*ptr!=val) ++ptr; return ptr==ptre?-1.:(double)(ptr - ptrb); } // Backward search. while (ptr>=ptrb && (double)*ptr!=val) --ptr; return ptr<ptrb?-1.:(double)(ptr - ptrb); } static double mp_list_find_seq(_cimg_math_parser& mp) { const unsigned int indi = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); const CImg<T> &img = mp.listin[indi]; const bool is_forward = (bool)_mp_arg(5); const ulongT siz1 = (ulongT)img.size(), siz2 = (ulongT)mp.opcode[4]; longT ind = (longT)(mp.opcode[6]!=_cimg_mp_slot_nan?_mp_arg(6):is_forward?0:siz1 - 1); if (ind<0 || ind>=(longT)siz1) return -1.; const T *const ptr1b = img.data(), *const ptr1e = ptr1b + siz1, *ptr1 = ptr1b + ind, *p1 = 0; const double *const ptr2b = &_mp_arg(3) + 1, *const ptr2e = ptr2b + siz2, *p2 = 0; // Forward search. if (is_forward) { do { while (ptr1<ptr1e && *ptr1!=*ptr2b) ++ptr1; if (ptr1>=ptr1e) return -1.; p1 = ptr1 + 1; p2 = ptr2b + 1; while (p1<ptr1e && p2<ptr2e && *p1==*p2) { ++p1; ++p2; } } while (p2<ptr2e && ++ptr1<ptr1e); return p2<ptr2e?-1.:(double)(ptr1 - ptr1b); } // Backward search. do { while (ptr1>=ptr1b && *ptr1!=*ptr2b) --ptr1; if (ptr1<ptr1b) return -1.; p1 = ptr1 + 1; p2 = ptr2b + 1; while (p1<ptr1e && p2<ptr2e && *p1==*p2) { ++p1; ++p2; } } while (p2<ptr2e && --ptr1>=ptr1b); return p2<ptr2e?-1.:(double)(ptr1 - ptr1b); } static double mp_list_height(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); return (double)mp.listin[ind]._height; } static double mp_list_ioff(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()), boundary_conditions = (unsigned int)_mp_arg(4); const CImg<T> &img = mp.listin[ind]; const longT off = (longT)_mp_arg(3), whds = (longT)img.size(); if (off>=0 && off<whds) return (double)img[off]; if (img._data) switch (boundary_conditions) { case 3 : { // Mirror const longT whds2 = 2*whds, moff = cimg::mod(off,whds2); return (double)img[moff<whds?moff:whds2 - moff - 1]; } case 2 : // Periodic return (double)img[cimg::mod(off,whds)]; case 1 : // Neumann return (double)img[off<0?0:whds - 1]; default : // Dirichlet return 0; } return 0; } static double mp_list_is_shared(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); return (double)mp.listin[ind]._is_shared; } static double mp_list_ixyzc(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()), interpolation = (unsigned int)_mp_arg(7), boundary_conditions = (unsigned int)_mp_arg(8); const CImg<T> &img = mp.listin[ind]; const double x = _mp_arg(3), y = _mp_arg(4), z = _mp_arg(5), c = _mp_arg(6); switch (interpolation) { case 2 : // Cubic interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), s2 = 2.f*img.spectrum(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), mc = cimg::mod((float)c,s2); return (double)img._cubic_atXYZ(mx<img.width()?mx:w2 - mx - 1, my<img.height()?my:h2 - my - 1, mz<img.depth()?mz:d2 - mz - 1, (int)(mc<img.spectrum()?mc:s2 - mc - 1)); } case 2 : // Periodic return (double)img._cubic_atXYZ_p((float)x,(float)y,(float)z, (int)cimg::mod(c,(double)img._spectrum)); case 1 : // Neumann return (double)img._cubic_atXYZ((float)x,(float)y,(float)z, (int)(c<0?0:c>=img._spectrum?img._spectrum - 1:c)); default : // Dirichlet if (c<0 || c>=img._spectrum) return (T)0; return (double)img.cubic_atXYZ((float)x,(float)y,(float)z,(int)c,(T)0); } case 1 : // Linear interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), s2 = 2.f*img.spectrum(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), mc = cimg::mod((float)c,s2); return (double)img._linear_atXYZ(mx<img.width()?mx:w2 - mx - 1, my<img.height()?my:h2 - my - 1, mz<img.depth()?mz:d2 - mz - 1, (int)(mc<img.spectrum()?mc:s2 - mc - 1)); } case 2 : // Periodic return (double)img._linear_atXYZ_p((float)x,(float)y,(float)z, (int)cimg::mod(c,(double)img._spectrum)); case 1 : // Neumann return (double)img._linear_atXYZ((float)x,(float)y,(float)z, (int)(c<0?0:c>=img._spectrum?img._spectrum - 1:c)); default : // Dirichlet if (c<0 || c>=img._spectrum) return (T)0; return (double)img.linear_atXYZ((float)x,(float)y,(float)z,(int)c,(T)0); } default : // Nearest neighbor interpolation switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*img.width(), h2 = 2*img.height(), d2 = 2*img.depth(), s2 = 2*img.spectrum(), mx = cimg::mod((int)x,w2), my = cimg::mod((int)y,h2), mz = cimg::mod((int)z,d2), mc = cimg::mod((int)c,s2); return (double)img(mx<img.width()?mx:w2 - mx - 1, my<img.height()?my:h2 - my - 1, mz<img.depth()?mz:d2 - mz - 1, mc<img.spectrum()?mc:s2 - mc - 1); } case 2 : // Periodic return (double)img((int)cimg::mod(x,(double)img._width), (int)cimg::mod(y,(double)img._height), (int)cimg::mod(z,(double)img._depth), (int)cimg::mod(c,(double)img._spectrum)); case 1 : // Neumann return (double)img._atXYZC((int)x,(int)y,(int)z,(int)c); default : // Dirichlet return (double)img.atXYZC((int)x,(int)y,(int)z,(int)c,(T)0); } } } static double mp_list_joff(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()), boundary_conditions = (unsigned int)_mp_arg(4); const int ox = (int)mp.mem[_cimg_mp_slot_x], oy = (int)mp.mem[_cimg_mp_slot_y], oz = (int)mp.mem[_cimg_mp_slot_z], oc = (int)mp.mem[_cimg_mp_slot_c]; const CImg<T> &img = mp.listin[ind]; const longT off = img.offset(ox,oy,oz,oc) + (longT)_mp_arg(3), whds = (longT)img.size(); if (off>=0 && off<whds) return (double)img[off]; if (img._data) switch (boundary_conditions) { case 3 : { // Mirror const longT whds2 = 2*whds, moff = cimg::mod(off,whds2); return (double)img[moff<whds?moff:whds2 - moff - 1]; } case 2 : // Periodic return (double)img[cimg::mod(off,whds)]; case 1 : // Neumann return (double)img[off<0?0:whds - 1]; default : // Dirichlet return 0; } return 0; } static double mp_list_jxyzc(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()), interpolation = (unsigned int)_mp_arg(7), boundary_conditions = (unsigned int)_mp_arg(8); const CImg<T> &img = mp.listin[ind]; const double ox = mp.mem[_cimg_mp_slot_x], oy = mp.mem[_cimg_mp_slot_y], oz = mp.mem[_cimg_mp_slot_z], oc = mp.mem[_cimg_mp_slot_c], x = ox + _mp_arg(3), y = oy + _mp_arg(4), z = oz + _mp_arg(5), c = oc + _mp_arg(6); switch (interpolation) { case 2 : // Cubic interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), s2 = 2.f*img.spectrum(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), mc = cimg::mod((float)c,s2); return (double)img._cubic_atXYZ(mx<img.width()?mx:w2 - mx - 1, my<img.height()?my:h2 - my - 1, mz<img.depth()?mz:d2 - mz - 1, (int)(mc<img.spectrum()?mc:s2 - mc - 1)); } case 2 : // Periodic return (double)img._cubic_atXYZ_p((float)x,(float)y,(float)z, (int)cimg::mod(c,(double)img._spectrum)); case 1 : // Neumann return (double)img._cubic_atXYZ((float)x,(float)y,(float)z, (int)(c<0?0:c>=img._spectrum?img._spectrum - 1:c)); default : // Dirichlet if (c<0 || c>=img._spectrum) return (T)0; return (double)img.cubic_atXYZ((float)x,(float)y,(float)z,(int)c,(T)0); } case 1 : // Linear interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), s2 = 2.f*img.spectrum(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), mc = cimg::mod((float)c,s2); return (double)img._linear_atXYZ(mx<img.width()?mx:w2 - mx - 1, my<img.height()?my:h2 - my - 1, mz<img.depth()?mz:d2 - mz - 1, (int)(mc<img.spectrum()?mc:s2 - mc - 1)); } case 2 : // Periodic return (double)img._linear_atXYZ_p((float)x,(float)y,(float)z, (int)cimg::mod(c,(double)img._spectrum)); case 1 : // Neumann return (double)img._linear_atXYZ((float)x,(float)y,(float)z, (int)(c<0?0:c>=img._spectrum?img._spectrum - 1:c)); default : // Dirichlet if (c<0 || c>=img._spectrum) return (T)0; return (double)img.linear_atXYZ((float)x,(float)y,(float)z,(int)c,(T)0); } default : // Nearest neighbor interpolation switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*img.width(), h2 = 2*img.height(), d2 = 2*img.depth(), s2 = 2*img.spectrum(), mx = cimg::mod((int)x,w2), my = cimg::mod((int)y,h2), mz = cimg::mod((int)z,d2), mc = cimg::mod((int)c,s2); return (double)img(mx<img.width()?mx:w2 - mx - 1, my<img.height()?my:h2 - my - 1, mz<img.depth()?mz:d2 - mz - 1, mc<img.spectrum()?mc:s2 - mc - 1); } case 2 : // Periodic return (double)img((int)cimg::mod(x,(double)img._width), (int)cimg::mod(y,(double)img._height), (int)cimg::mod(z,(double)img._depth), (int)cimg::mod(c,(double)img._spectrum)); case 1 : // Neumann return (double)img._atXYZC((int)x,(int)y,(int)z,(int)c); default : // Dirichlet return (double)img.atXYZC((int)x,(int)y,(int)z,(int)c,(T)0); } } } static double mp_list_l(_cimg_math_parser& mp) { return (double)mp.listout.width(); } static double mp_list_median(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); if (!mp.list_median) mp.list_median.assign(mp.listin._width); if (!mp.list_median[ind]) CImg<doubleT>::vector(mp.listin[ind].median()).move_to(mp.list_median[ind]); return *mp.list_median[ind]; } static double mp_list_set_ioff(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); CImg<T> &img = mp.listout[ind]; const longT off = (longT)_mp_arg(3), whds = (longT)img.size(); const double val = _mp_arg(1); if (off>=0 && off<whds) img[off] = (T)val; return val; } static double mp_list_set_ixyzc(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); CImg<T> &img = mp.listout[ind]; const int x = (int)_mp_arg(3), y = (int)_mp_arg(4), z = (int)_mp_arg(5), c = (int)_mp_arg(6); const double val = _mp_arg(1); if (x>=0 && x<img.width() && y>=0 && y<img.height() && z>=0 && z<img.depth() && c>=0 && c<img.spectrum()) img(x,y,z,c) = (T)val; return val; } static double mp_list_set_joff(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); CImg<T> &img = mp.listout[ind]; const int ox = (int)mp.mem[_cimg_mp_slot_x], oy = (int)mp.mem[_cimg_mp_slot_y], oz = (int)mp.mem[_cimg_mp_slot_z], oc = (int)mp.mem[_cimg_mp_slot_c]; const longT off = img.offset(ox,oy,oz,oc) + (longT)_mp_arg(3), whds = (longT)img.size(); const double val = _mp_arg(1); if (off>=0 && off<whds) img[off] = (T)val; return val; } static double mp_list_set_jxyzc(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); CImg<T> &img = mp.listout[ind]; const double ox = mp.mem[_cimg_mp_slot_x], oy = mp.mem[_cimg_mp_slot_y], oz = mp.mem[_cimg_mp_slot_z], oc = mp.mem[_cimg_mp_slot_c]; const int x = (int)(ox + _mp_arg(3)), y = (int)(oy + _mp_arg(4)), z = (int)(oz + _mp_arg(5)), c = (int)(oc + _mp_arg(6)); const double val = _mp_arg(1); if (x>=0 && x<img.width() && y>=0 && y<img.height() && z>=0 && z<img.depth() && c>=0 && c<img.spectrum()) img(x,y,z,c) = (T)val; return val; } static double mp_list_set_Ioff_s(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); CImg<T> &img = mp.listout[ind]; const longT off = (longT)_mp_arg(3), whd = (longT)img.width()*img.height()*img.depth(); const T val = (T)_mp_arg(1); if (off>=0 && off<whd) { T *ptrd = &img[off]; cimg_forC(img,c) { *ptrd = val; ptrd+=whd; } } return _mp_arg(1); } static double mp_list_set_Ioff_v(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); CImg<T> &img = mp.listout[ind]; const longT off = (longT)_mp_arg(3), whd = (longT)img.width()*img.height()*img.depth(); const double *ptrs = &_mp_arg(1) + 1; if (off>=0 && off<whd) { const unsigned int vsiz = (unsigned int)mp.opcode[4]; T *ptrd = &img[off]; cimg_for_inC(img,0,vsiz - 1,c) { *ptrd = (T)*(ptrs++); ptrd+=whd; } } return cimg::type<double>::nan(); } static double mp_list_set_Ixyz_s(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); CImg<T> &img = mp.listout[ind]; const int x = (int)_mp_arg(3), y = (int)_mp_arg(4), z = (int)_mp_arg(5); const T val = (T)_mp_arg(1); if (x>=0 && x<img.width() && y>=0 && y<img.height() && z>=0 && z<img.depth()) { T *ptrd = &img(x,y,z); const ulongT whd = (ulongT)img._width*img._height*img._depth; cimg_forC(img,c) { *ptrd = val; ptrd+=whd; } } return _mp_arg(1); } static double mp_list_set_Ixyz_v(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); CImg<T> &img = mp.listout[ind]; const int x = (int)_mp_arg(3), y = (int)_mp_arg(4), z = (int)_mp_arg(5); const double *ptrs = &_mp_arg(1) + 1; if (x>=0 && x<img.width() && y>=0 && y<img.height() && z>=0 && z<img.depth()) { const unsigned int vsiz = (unsigned int)mp.opcode[6]; T *ptrd = &img(x,y,z); const ulongT whd = (ulongT)img._width*img._height*img._depth; cimg_for_inC(img,0,vsiz - 1,c) { *ptrd = (T)*(ptrs++); ptrd+=whd; } } return cimg::type<double>::nan(); } static double mp_list_set_Joff_s(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); CImg<T> &img = mp.listout[ind]; const int ox = (int)mp.mem[_cimg_mp_slot_x], oy = (int)mp.mem[_cimg_mp_slot_y], oz = (int)mp.mem[_cimg_mp_slot_z], oc = (int)mp.mem[_cimg_mp_slot_c]; const longT off = img.offset(ox,oy,oz,oc) + (longT)_mp_arg(3), whd = (longT)img.width()*img.height()*img.depth(); const T val = (T)_mp_arg(1); if (off>=0 && off<whd) { T *ptrd = &img[off]; cimg_forC(img,c) { *ptrd = val; ptrd+=whd; } } return _mp_arg(1); } static double mp_list_set_Joff_v(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); CImg<T> &img = mp.listout[ind]; const int ox = (int)mp.mem[_cimg_mp_slot_x], oy = (int)mp.mem[_cimg_mp_slot_y], oz = (int)mp.mem[_cimg_mp_slot_z], oc = (int)mp.mem[_cimg_mp_slot_c]; const longT off = img.offset(ox,oy,oz,oc) + (longT)_mp_arg(3), whd = (longT)img.width()*img.height()*img.depth(); const double *ptrs = &_mp_arg(1) + 1; if (off>=0 && off<whd) { const unsigned int vsiz = (unsigned int)mp.opcode[4]; T *ptrd = &img[off]; cimg_for_inC(img,0,vsiz - 1,c) { *ptrd = (T)*(ptrs++); ptrd+=whd; } } return cimg::type<double>::nan(); } static double mp_list_set_Jxyz_s(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); CImg<T> &img = mp.listout[ind]; const double ox = mp.mem[_cimg_mp_slot_x], oy = mp.mem[_cimg_mp_slot_y], oz = mp.mem[_cimg_mp_slot_z]; const int x = (int)(ox + _mp_arg(3)), y = (int)(oy + _mp_arg(4)), z = (int)(oz + _mp_arg(5)); const T val = (T)_mp_arg(1); if (x>=0 && x<img.width() && y>=0 && y<img.height() && z>=0 && z<img.depth()) { T *ptrd = &img(x,y,z); const ulongT whd = (ulongT)img._width*img._height*img._depth; cimg_forC(img,c) { *ptrd = val; ptrd+=whd; } } return _mp_arg(1); } static double mp_list_set_Jxyz_v(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); CImg<T> &img = mp.listout[ind]; const double ox = mp.mem[_cimg_mp_slot_x], oy = mp.mem[_cimg_mp_slot_y], oz = mp.mem[_cimg_mp_slot_z]; const int x = (int)(ox + _mp_arg(3)), y = (int)(oy + _mp_arg(4)), z = (int)(oz + _mp_arg(5)); const double *ptrs = &_mp_arg(1) + 1; if (x>=0 && x<img.width() && y>=0 && y<img.height() && z>=0 && z<img.depth()) { const unsigned int vsiz = (unsigned int)mp.opcode[6]; T *ptrd = &img(x,y,z); const ulongT whd = (ulongT)img._width*img._height*img._depth; cimg_for_inC(img,0,vsiz - 1,c) { *ptrd = (T)*(ptrs++); ptrd+=whd; } } return cimg::type<double>::nan(); } static double mp_list_spectrum(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); return (double)mp.listin[ind]._spectrum; } static double mp_list_stats(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()), k = (unsigned int)mp.opcode[3]; if (!mp.list_stats) mp.list_stats.assign(mp.listin._width); if (!mp.list_stats[ind]) mp.list_stats[ind].assign(1,14,1,1,0).fill(mp.listin[ind].get_stats(),false); return mp.list_stats(ind,k); } static double mp_list_wh(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); return (double)mp.listin[ind]._width*mp.listin[ind]._height; } static double mp_list_whd(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); return (double)mp.listin[ind]._width*mp.listin[ind]._height*mp.listin[ind]._depth; } static double mp_list_whds(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); return (double)mp.listin[ind]._width*mp.listin[ind]._height*mp.listin[ind]._depth*mp.listin[ind]._spectrum; } static double mp_list_width(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); return (double)mp.listin[ind]._width; } static double mp_list_Ioff(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()), boundary_conditions = (unsigned int)_mp_arg(4), vsiz = (unsigned int)mp.opcode[5]; const CImg<T> &img = mp.listin[ind]; const longT off = (longT)_mp_arg(3), whd = (longT)img.width()*img.height()*img.depth(); const T *ptrs; if (off>=0 && off<whd) { ptrs = &img[off]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); } if (img._data) switch (boundary_conditions) { case 3 : { // Mirror const longT whd2 = 2*whd, moff = cimg::mod(off,whd2); ptrs = &img[moff<whd?moff:whd2 - moff - 1]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); } case 2 : // Periodic ptrs = &img[cimg::mod(off,whd)]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); case 1 : // Neumann ptrs = off<0?&img[0]:&img[whd - 1]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); default : // Dirichlet std::memset(ptrd,0,vsiz*sizeof(double)); return cimg::type<double>::nan(); } std::memset(ptrd,0,vsiz*sizeof(double)); return cimg::type<double>::nan(); } static double mp_list_Ixyz(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()), interpolation = (unsigned int)_mp_arg(6), boundary_conditions = (unsigned int)_mp_arg(7), vsiz = (unsigned int)mp.opcode[8]; const CImg<T> &img = mp.listin[ind]; const double x = _mp_arg(3), y = _mp_arg(4), z = _mp_arg(5); const ulongT whd = (ulongT)img._width*img._height*img._depth; const T *ptrs; switch (interpolation) { case 2 : // Cubic interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), cx = mx<img.width()?mx:w2 - mx - 1, cy = my<img.height()?my:h2 - my - 1, cz = mz<img.depth()?mz:d2 - mz - 1; cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._cubic_atXYZ(cx,cy,cz,c); } break; case 2 : // Periodic cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._cubic_atXYZ_p((float)x,(float)y,(float)z,c); break; case 1 : // Neumann cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._cubic_atXYZ((float)x,(float)y,(float)z,c); break; default : // Dirichlet cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img.cubic_atXYZ((float)x,(float)y,(float)z,c,(T)0); } break; case 1 : // Linear interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), cx = mx<img.width()?mx:w2 - mx - 1, cy = my<img.height()?my:h2 - my - 1, cz = mz<img.depth()?mz:d2 - mz - 1; cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._linear_atXYZ(cx,cy,cz,c); } break; case 2 : // Periodic cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._linear_atXYZ_p((float)x,(float)y,(float)z,c); break; case 1 : // Neumann cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._linear_atXYZ((float)x,(float)y,(float)z,c); break; default : // Dirichlet cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img.linear_atXYZ((float)x,(float)y,(float)z,c,(T)0); } break; default : // Nearest neighbor interpolation switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*img.width(), h2 = 2*img.height(), d2 = 2*img.depth(), mx = cimg::mod((int)x,w2), my = cimg::mod((int)y,h2), mz = cimg::mod((int)z,d2), cx = mx<img.width()?mx:w2 - mx - 1, cy = my<img.height()?my:h2 - my - 1, cz = mz<img.depth()?mz:d2 - mz - 1; ptrs = &img(cx,cy,cz); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } break; case 2 : { // Periodic const int cx = (int)cimg::mod(x,(double)img._width), cy = (int)cimg::mod(y,(double)img._height), cz = (int)cimg::mod(z,(double)img._depth); ptrs = &img(cx,cy,cz); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } break; case 1 : { // Neumann ptrs = &img._atXYZ((int)x,(int)y,(int)z); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } break; default : // Dirichlet if (img.containsXYZC((int)x,(int)y,(int)z)) { ptrs = &img((int)x,(int)y,(int)z); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } else std::memset(ptrd,0,vsiz*sizeof(double)); } } return cimg::type<double>::nan(); } static double mp_list_Joff(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()), boundary_conditions = (unsigned int)_mp_arg(4), vsiz = (unsigned int)mp.opcode[5]; const int ox = (int)mp.mem[_cimg_mp_slot_x], oy = (int)mp.mem[_cimg_mp_slot_y], oz = (int)mp.mem[_cimg_mp_slot_z]; const CImg<T> &img = mp.listin[ind]; const longT off = img.offset(ox,oy,oz) + (longT)_mp_arg(3), whd = (longT)img.width()*img.height()*img.depth(); const T *ptrs; if (off>=0 && off<whd) { ptrs = &img[off]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); } if (img._data) switch (boundary_conditions) { case 3 : { // Mirror const longT whd2 = 2*whd, moff = cimg::mod(off,whd2); ptrs = &img[moff<whd?moff:whd2 - moff - 1]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); } case 2 : // Periodic ptrs = &img[cimg::mod(off,whd)]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); case 1 : // Neumann ptrs = off<0?&img[0]:&img[whd - 1]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); default : // Dirichlet std::memset(ptrd,0,vsiz*sizeof(double)); return cimg::type<double>::nan(); } std::memset(ptrd,0,vsiz*sizeof(double)); return cimg::type<double>::nan(); } static double mp_list_Jxyz(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()), interpolation = (unsigned int)_mp_arg(6), boundary_conditions = (unsigned int)_mp_arg(7), vsiz = (unsigned int)mp.opcode[8]; const CImg<T> &img = mp.listin[ind]; const double ox = mp.mem[_cimg_mp_slot_x], oy = mp.mem[_cimg_mp_slot_y], oz = mp.mem[_cimg_mp_slot_z], x = ox + _mp_arg(3), y = oy + _mp_arg(4), z = oz + _mp_arg(5); const ulongT whd = (ulongT)img._width*img._height*img._depth; const T *ptrs; switch (interpolation) { case 2 : // Cubic interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), cx = mx<img.width()?mx:w2 - mx - 1, cy = my<img.height()?my:h2 - my - 1, cz = mz<img.depth()?mz:d2 - mz - 1; cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._cubic_atXYZ(cx,cy,cz,c); } break; case 2 : // Periodic cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._cubic_atXYZ_p((float)x,(float)y,(float)z,c); break; case 1 : // Neumann cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._cubic_atXYZ((float)x,(float)y,(float)z,c); break; default : // Dirichlet cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img.cubic_atXYZ((float)x,(float)y,(float)z,c,(T)0); } break; case 1 : // Linear interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), cx = mx<img.width()?mx:w2 - mx - 1, cy = my<img.height()?my:h2 - my - 1, cz = mz<img.depth()?mz:d2 - mz - 1; cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._linear_atXYZ(cx,cy,cz,c); } break; case 2 : // Periodic cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._linear_atXYZ_p((float)x,(float)y,(float)z,c); break; case 1 : // Neumann cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._linear_atXYZ((float)x,(float)y,(float)z,c); break; default : // Dirichlet cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img.linear_atXYZ((float)x,(float)y,(float)z,c,(T)0); } break; case 0 : // Nearest neighbor interpolation switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*img.width(), h2 = 2*img.height(), d2 = 2*img.depth(), mx = cimg::mod((int)x,w2), my = cimg::mod((int)y,h2), mz = cimg::mod((int)z,d2), cx = mx<img.width()?mx:w2 - mx - 1, cy = my<img.height()?my:h2 - my - 1, cz = mz<img.depth()?mz:d2 - mz - 1; ptrs = &img(cx,cy,cz); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } break; case 2 : { // Periodic const int cx = (int)cimg::mod(x,(double)img._width), cy = (int)cimg::mod(y,(double)img._height), cz = (int)cimg::mod(z,(double)img._depth); ptrs = &img(cx,cy,cz); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } break; case 1 : { // Neumann ptrs = &img._atXYZ((int)x,(int)y,(int)z); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } break; default : // Dirichlet if (img.containsXYZC((int)x,(int)y,(int)z)) { ptrs = &img((int)x,(int)y,(int)z); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } else std::memset(ptrd,0,vsiz*sizeof(double)); } } return cimg::type<double>::nan(); } static double mp_log(_cimg_math_parser& mp) { return std::log(_mp_arg(2)); } static double mp_log10(_cimg_math_parser& mp) { return std::log10(_mp_arg(2)); } static double mp_log2(_cimg_math_parser& mp) { return cimg::log2(_mp_arg(2)); } static double mp_logical_and(_cimg_math_parser& mp) { const bool val_left = (bool)_mp_arg(2); const CImg<ulongT> *const p_end = ++mp.p_code + mp.opcode[4]; if (!val_left) { mp.p_code = p_end - 1; return 0; } const ulongT mem_right = mp.opcode[3]; for ( ; mp.p_code<p_end; ++mp.p_code) { mp.opcode._data = mp.p_code->_data; const ulongT target = mp.opcode[1]; mp.mem[target] = _cimg_mp_defunc(mp); } --mp.p_code; return (double)(bool)mp.mem[mem_right]; } static double mp_logical_not(_cimg_math_parser& mp) { return (double)!_mp_arg(2); } static double mp_logical_or(_cimg_math_parser& mp) { const bool val_left = (bool)_mp_arg(2); const CImg<ulongT> *const p_end = ++mp.p_code + mp.opcode[4]; if (val_left) { mp.p_code = p_end - 1; return 1; } const ulongT mem_right = mp.opcode[3]; for ( ; mp.p_code<p_end; ++mp.p_code) { mp.opcode._data = mp.p_code->_data; const ulongT target = mp.opcode[1]; mp.mem[target] = _cimg_mp_defunc(mp); } --mp.p_code; return (double)(bool)mp.mem[mem_right]; } static double mp_lowercase(_cimg_math_parser& mp) { return cimg::lowercase(_mp_arg(2)); } static double mp_lt(_cimg_math_parser& mp) { return (double)(_mp_arg(2)<_mp_arg(3)); } static double mp_lte(_cimg_math_parser& mp) { return (double)(_mp_arg(2)<=_mp_arg(3)); } static double mp_matrix_eig(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const double *ptr1 = &_mp_arg(2) + 1; const unsigned int k = (unsigned int)mp.opcode[3]; CImg<doubleT> val, vec; CImg<doubleT>(ptr1,k,k,1,1,true).symmetric_eigen(val,vec); CImg<doubleT>(ptrd,1,k,1,1,true) = val; CImg<doubleT>(ptrd + k,k,k,1,1,true) = vec.get_transpose(); return cimg::type<double>::nan(); } static double mp_matrix_inv(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const double *ptr1 = &_mp_arg(2) + 1; const unsigned int k = (unsigned int)mp.opcode[3]; CImg<doubleT>(ptrd,k,k,1,1,true) = CImg<doubleT>(ptr1,k,k,1,1,true).get_invert(); return cimg::type<double>::nan(); } static double mp_matrix_mul(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const double *ptr1 = &_mp_arg(2) + 1, *ptr2 = &_mp_arg(3) + 1; const unsigned int k = (unsigned int)mp.opcode[4], l = (unsigned int)mp.opcode[5], m = (unsigned int)mp.opcode[6]; CImg<doubleT>(ptrd,m,k,1,1,true) = CImg<doubleT>(ptr1,l,k,1,1,true)*CImg<doubleT>(ptr2,m,l,1,1,true); return cimg::type<double>::nan(); } static double mp_matrix_pseudoinv(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const double *ptr1 = &_mp_arg(2) + 1; const unsigned int k = (unsigned int)mp.opcode[3], l = (unsigned int)mp.opcode[4]; CImg<doubleT>(ptrd,l,k,1,1,true) = CImg<doubleT>(ptr1,k,l,1,1,true).get_pseudoinvert(); return cimg::type<double>::nan(); } static double mp_matrix_svd(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const double *ptr1 = &_mp_arg(2) + 1; const unsigned int k = (unsigned int)mp.opcode[3], l = (unsigned int)mp.opcode[4]; CImg<doubleT> U, S, V; CImg<doubleT>(ptr1,k,l,1,1,true).SVD(U,S,V); CImg<doubleT>(ptrd,1,k,1,1,true) = S; CImg<doubleT>(ptrd + k,k,l,1,1,true) = U; CImg<doubleT>(ptrd + k + k*l,k,k,1,1,true) = V; return cimg::type<double>::nan(); } static double mp_max(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; double val = _mp_arg(3); for (unsigned int i = 4; i<i_end; ++i) val = std::max(val,_mp_arg(i)); return val; } static double* _mp_memcopy_double(_cimg_math_parser& mp, const unsigned int ind, const ulongT *const p_ref, const longT siz, const long inc) { const longT off = *p_ref?p_ref[1] + (longT)mp.mem[(longT)p_ref[2]] + 1:ind, eoff = off + (siz - 1)*inc; if (off<0 || eoff>=mp.mem.width()) throw CImgArgumentException("[" cimg_appname "_math_parser] CImg<%s>: Function 'copy()': " "Out-of-bounds variable pointer " "(length: %ld, increment: %ld, offset start: %ld, " "offset end: %ld, offset max: %u).", mp.imgin.pixel_type(),siz,inc,off,eoff,mp.mem._width - 1); return &mp.mem[off]; } static float* _mp_memcopy_float(_cimg_math_parser& mp, const ulongT *const p_ref, const longT siz, const long inc, const bool is_out) { const unsigned ind = (unsigned int)p_ref[1]; const CImg<T> &img = is_out? (ind==~0U?mp.imgout:mp.listout[cimg::mod((int)mp.mem[ind],mp.listout.width())]): (ind==~0U?mp.imgin:mp.listin[cimg::mod((int)mp.mem[ind],mp.listin.width())]); const bool is_relative = (bool)p_ref[2]; int ox, oy, oz, oc; longT off = 0; if (is_relative) { ox = (int)mp.mem[_cimg_mp_slot_x]; oy = (int)mp.mem[_cimg_mp_slot_y]; oz = (int)mp.mem[_cimg_mp_slot_z]; oc = (int)mp.mem[_cimg_mp_slot_c]; off = img.offset(ox,oy,oz,oc); } if ((*p_ref)%2) { const int x = (int)mp.mem[p_ref[3]], y = (int)mp.mem[p_ref[4]], z = (int)mp.mem[p_ref[5]], c = *p_ref==5?0:(int)mp.mem[p_ref[6]]; off+=img.offset(x,y,z,c); } else off+=(longT)mp.mem[p_ref[3]]; const longT eoff = off + (siz - 1)*inc; if (off<0 || eoff>=(longT)img.size()) throw CImgArgumentException("[" cimg_appname "_math_parser] CImg<%s>: Function 'copy()': " "Out-of-bounds image pointer " "(length: %ld, increment: %ld, offset start: %ld, " "offset end: %ld, offset max: %lu).", mp.imgin.pixel_type(),siz,inc,off,eoff,img.size() - 1); return (float*)&img[off]; } static double mp_memcopy(_cimg_math_parser& mp) { longT siz = (longT)_mp_arg(4); const longT inc_d = (longT)_mp_arg(5), inc_s = (longT)_mp_arg(6); const float _opacity = (float)_mp_arg(7), opacity = (float)cimg::abs(_opacity), omopacity = 1 - std::max(_opacity,0.f); if (siz>0) { const bool is_doubled = mp.opcode[8]<=1, is_doubles = mp.opcode[15]<=1; if (is_doubled && is_doubles) { // (double*) <- (double*) double *ptrd = _mp_memcopy_double(mp,(unsigned int)mp.opcode[2],&mp.opcode[8],siz,inc_d); const double *ptrs = _mp_memcopy_double(mp,(unsigned int)mp.opcode[3],&mp.opcode[15],siz,inc_s); if (inc_d==1 && inc_s==1 && _opacity>=1) { if (ptrs + siz - 1<ptrd || ptrs>ptrd + siz - 1) std::memcpy(ptrd,ptrs,siz*sizeof(double)); else std::memmove(ptrd,ptrs,siz*sizeof(double)); } else { if (ptrs + (siz - 1)*inc_s<ptrd || ptrs>ptrd + (siz - 1)*inc_d) { if (_opacity>=1) while (siz-->0) { *ptrd = *ptrs; ptrd+=inc_d; ptrs+=inc_s; } else while (siz-->0) { *ptrd = omopacity**ptrd + opacity**ptrs; ptrd+=inc_d; ptrs+=inc_s; } } else { // Overlapping buffers CImg<doubleT> buf((unsigned int)siz); cimg_for(buf,ptr,double) { *ptr = *ptrs; ptrs+=inc_s; } ptrs = buf; if (_opacity>=1) while (siz-->0) { *ptrd = *(ptrs++); ptrd+=inc_d; } else while (siz-->0) { *ptrd = omopacity**ptrd + opacity**(ptrs++); ptrd+=inc_d; } } } } else if (is_doubled && !is_doubles) { // (double*) <- (float*) double *ptrd = _mp_memcopy_double(mp,(unsigned int)mp.opcode[2],&mp.opcode[8],siz,inc_d); const float *ptrs = _mp_memcopy_float(mp,&mp.opcode[15],siz,inc_s,false); if (_opacity>=1) while (siz-->0) { *ptrd = *ptrs; ptrd+=inc_d; ptrs+=inc_s; } else while (siz-->0) { *ptrd = omopacity**ptrd + _opacity**ptrs; ptrd+=inc_d; ptrs+=inc_s; } } else if (!is_doubled && is_doubles) { // (float*) <- (double*) float *ptrd = _mp_memcopy_float(mp,&mp.opcode[8],siz,inc_d,true); const double *ptrs = _mp_memcopy_double(mp,(unsigned int)mp.opcode[3],&mp.opcode[15],siz,inc_s); if (_opacity>=1) while (siz-->0) { *ptrd = (float)*ptrs; ptrd+=inc_d; ptrs+=inc_s; } else while (siz-->0) { *ptrd = (float)(omopacity**ptrd + opacity**ptrs); ptrd+=inc_d; ptrs+=inc_s; } } else { // (float*) <- (float*) float *ptrd = _mp_memcopy_float(mp,&mp.opcode[8],siz,inc_d,true); const float *ptrs = _mp_memcopy_float(mp,&mp.opcode[15],siz,inc_s,false); if (inc_d==1 && inc_s==1 && _opacity>=1) { if (ptrs + siz - 1<ptrd || ptrs>ptrd + siz - 1) std::memcpy(ptrd,ptrs,siz*sizeof(float)); else std::memmove(ptrd,ptrs,siz*sizeof(float)); } else { if (ptrs + (siz - 1)*inc_s<ptrd || ptrs>ptrd + (siz - 1)*inc_d) { if (_opacity>=1) while (siz-->0) { *ptrd = *ptrs; ptrd+=inc_d; ptrs+=inc_s; } else while (siz-->0) { *ptrd = omopacity**ptrd + opacity**ptrs; ptrd+=inc_d; ptrs+=inc_s; } } else { // Overlapping buffers CImg<floatT> buf((unsigned int)siz); cimg_for(buf,ptr,float) { *ptr = *ptrs; ptrs+=inc_s; } ptrs = buf; if (_opacity>=1) while (siz-->0) { *ptrd = *(ptrs++); ptrd+=inc_d; } else while (siz-->0) { *ptrd = omopacity**ptrd + opacity**(ptrs++); ptrd+=inc_d; } } } } } return _mp_arg(1); } static double mp_min(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; double val = _mp_arg(3); for (unsigned int i = 4; i<i_end; ++i) val = std::min(val,_mp_arg(i)); return val; } static double mp_minus(_cimg_math_parser& mp) { return -_mp_arg(2); } static double mp_median(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; switch (i_end - 3) { case 1 : return _mp_arg(3); case 2 : return cimg::median(_mp_arg(3),_mp_arg(4)); case 3 : return cimg::median(_mp_arg(3),_mp_arg(4),_mp_arg(5)); case 5 : return cimg::median(_mp_arg(3),_mp_arg(4),_mp_arg(5),_mp_arg(6),_mp_arg(7)); case 7 : return cimg::median(_mp_arg(3),_mp_arg(4),_mp_arg(5),_mp_arg(6),_mp_arg(7),_mp_arg(8),_mp_arg(9)); case 9 : return cimg::median(_mp_arg(3),_mp_arg(4),_mp_arg(5),_mp_arg(6),_mp_arg(7),_mp_arg(8),_mp_arg(9), _mp_arg(10),_mp_arg(11)); case 13 : return cimg::median(_mp_arg(3),_mp_arg(4),_mp_arg(5),_mp_arg(6),_mp_arg(7),_mp_arg(8),_mp_arg(9), _mp_arg(10),_mp_arg(11),_mp_arg(12),_mp_arg(13),_mp_arg(14),_mp_arg(15)); } CImg<doubleT> vals(i_end - 3); double *p = vals.data(); for (unsigned int i = 3; i<i_end; ++i) *(p++) = _mp_arg(i); return vals.median(); } static double mp_modulo(_cimg_math_parser& mp) { return cimg::mod(_mp_arg(2),_mp_arg(3)); } static double mp_mul(_cimg_math_parser& mp) { return _mp_arg(2)*_mp_arg(3); } static double mp_mul2(_cimg_math_parser& mp) { return _mp_arg(2)*_mp_arg(3)*_mp_arg(4); } static double mp_neq(_cimg_math_parser& mp) { return (double)(_mp_arg(2)!=_mp_arg(3)); } static double mp_norm0(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; switch (i_end - 3) { case 1 : return _mp_arg(3)!=0; case 2 : return (_mp_arg(3)!=0) + (_mp_arg(4)!=0); } double res = 0; for (unsigned int i = 3; i<i_end; ++i) res+=_mp_arg(i)==0?0:1; return res; } static double mp_norm1(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; switch (i_end - 3) { case 1 : return cimg::abs(_mp_arg(3)); case 2 : return cimg::abs(_mp_arg(3)) + cimg::abs(_mp_arg(4)); } double res = 0; for (unsigned int i = 3; i<i_end; ++i) res+=cimg::abs(_mp_arg(i)); return res; } static double mp_norm2(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; switch (i_end - 3) { case 1 : return cimg::abs(_mp_arg(3)); case 2 : return cimg::_hypot(_mp_arg(3),_mp_arg(4)); } double res = 0; for (unsigned int i = 3; i<i_end; ++i) res+=cimg::sqr(_mp_arg(i)); return std::sqrt(res); } static double mp_norminf(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; switch (i_end - 3) { case 1 : return cimg::abs(_mp_arg(3)); case 2 : return std::max(cimg::abs(_mp_arg(3)),cimg::abs(_mp_arg(4))); } double res = 0; for (unsigned int i = 3; i<i_end; ++i) { const double val = cimg::abs(_mp_arg(i)); if (val>res) res = val; } return res; } static double mp_normp(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; if (i_end==4) return cimg::abs(_mp_arg(3)); const double p = (double)mp.opcode[3]; double res = 0; for (unsigned int i = 4; i<i_end; ++i) res+=std::pow(cimg::abs(_mp_arg(i)),p); res = std::pow(res,1/p); return res>0?res:0.; } static double mp_permutations(_cimg_math_parser& mp) { return cimg::permutations((int)_mp_arg(2),(int)_mp_arg(3),(bool)_mp_arg(4)); } static double mp_polygon(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; unsigned int ind = (unsigned int)mp.opcode[3]; if (ind!=~0U) ind = (unsigned int)cimg::mod((int)_mp_arg(3),mp.listin.width()); CImg<T> &img = ind==~0U?mp.imgout:mp.listout[ind]; bool is_invalid_arguments = i_end<=4, is_outlined = false; if (!is_invalid_arguments) { int nbv = (int)_mp_arg(4); if (!nbv) is_invalid_arguments = true; else { if (nbv<0) { nbv = -nbv; is_outlined = true; } CImg<intT> points(nbv,2,1,1,0); CImg<T> color(img._spectrum,1,1,1,0); float opacity = 1; unsigned int i = 5, pattern=~0U; cimg_foroff(points,k) if (i<i_end) points(k/2,k%2) = (int)cimg::round(_mp_arg(i++)); else { is_invalid_arguments = true; break; } if (!is_invalid_arguments) { if (i<i_end) opacity = (float)_mp_arg(i++); if (is_outlined && i<i_end) pattern = (unsigned int)_mp_arg(i++); cimg_forX(color,k) if (i<i_end) color[k] = (T)_mp_arg(i++); else { color.resize(k,1,1,1,-1); break; } color.resize(img._spectrum,1,1,1,0,2); if (is_outlined) img.draw_polygon(points,color._data,opacity,pattern); else img.draw_polygon(points,color._data,opacity); } } } if (is_invalid_arguments) { CImg<doubleT> args(i_end - 4); cimg_forX(args,k) args[k] = _mp_arg(4 + k); if (ind==~0U) throw CImgArgumentException("[" cimg_appname "_math_parser] CImg<%s>: Function 'polygon()': " "Invalid arguments '%s'. ", mp.imgin.pixel_type(),args.value_string()._data); else throw CImgArgumentException("[" cimg_appname "_math_parser] CImg<%s>: Function 'polygon()': " "Invalid arguments '#%u%s%s'. ", mp.imgin.pixel_type(),ind,args._width?",":"",args.value_string()._data); } return cimg::type<double>::nan(); } static double mp_pow(_cimg_math_parser& mp) { const double v = _mp_arg(2), p = _mp_arg(3); return std::pow(v,p); } static double mp_pow0_25(_cimg_math_parser& mp) { const double val = _mp_arg(2); return std::sqrt(std::sqrt(val)); } static double mp_pow3(_cimg_math_parser& mp) { const double val = _mp_arg(2); return val*val*val; } static double mp_pow4(_cimg_math_parser& mp) { const double val = _mp_arg(2); return val*val*val*val; } static double mp_print(_cimg_math_parser& mp) { const double val = _mp_arg(1); const bool print_char = (bool)mp.opcode[3]; cimg_pragma_openmp(critical(mp_print)) { CImg<charT> _expr(mp.opcode[2] - 4); const ulongT *ptrs = mp.opcode._data + 4; cimg_for(_expr,ptrd,char) *ptrd = (char)*(ptrs++); cimg::strellipsize(_expr); cimg::mutex(6); if (print_char) std::fprintf(cimg::output(),"\n[" cimg_appname "_math_parser] %s = %g = '%c'",_expr._data,val,(int)val); else std::fprintf(cimg::output(),"\n[" cimg_appname "_math_parser] %s = %g",_expr._data,val); std::fflush(cimg::output()); cimg::mutex(6,0); } return val; } static double mp_prod(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; double val = _mp_arg(3); for (unsigned int i = 4; i<i_end; ++i) val*=_mp_arg(i); return val; } static double mp_copy(_cimg_math_parser& mp) { return _mp_arg(2); } static double mp_rol(_cimg_math_parser& mp) { return cimg::rol(_mp_arg(2),(unsigned int)_mp_arg(3)); } static double mp_ror(_cimg_math_parser& mp) { return cimg::ror(_mp_arg(2),(unsigned int)_mp_arg(3)); } static double mp_rot2d(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const float theta = (float)_mp_arg(2)*cimg::PI/180, ca = std::cos(theta), sa = std::sin(theta); *(ptrd++) = ca; *(ptrd++) = -sa; *(ptrd++) = sa; *ptrd = ca; return cimg::type<double>::nan(); } static double mp_rot3d(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const float x = (float)_mp_arg(2), y = (float)_mp_arg(3), z = (float)_mp_arg(4), theta = (float)_mp_arg(5); CImg<doubleT>(ptrd,3,3,1,1,true) = CImg<doubleT>::rotation_matrix(x,y,z,theta); return cimg::type<double>::nan(); } static double mp_round(_cimg_math_parser& mp) { return cimg::round(_mp_arg(2),_mp_arg(3),(int)_mp_arg(4)); } static double mp_self_add(_cimg_math_parser& mp) { return _mp_arg(1)+=_mp_arg(2); } static double mp_self_bitwise_and(_cimg_math_parser& mp) { double &val = _mp_arg(1); return val = (double)((longT)val & (longT)_mp_arg(2)); } static double mp_self_bitwise_left_shift(_cimg_math_parser& mp) { double &val = _mp_arg(1); return val = (double)((longT)val<<(unsigned int)_mp_arg(2)); } static double mp_self_bitwise_or(_cimg_math_parser& mp) { double &val = _mp_arg(1); return val = (double)((longT)val | (longT)_mp_arg(2)); } static double mp_self_bitwise_right_shift(_cimg_math_parser& mp) { double &val = _mp_arg(1); return val = (double)((longT)val>>(unsigned int)_mp_arg(2)); } static double mp_self_decrement(_cimg_math_parser& mp) { return --_mp_arg(1); } static double mp_self_increment(_cimg_math_parser& mp) { return ++_mp_arg(1); } static double mp_self_map_vector_s(_cimg_math_parser& mp) { // Vector += scalar unsigned int ptrd = (unsigned int)mp.opcode[1] + 1, siz = (unsigned int)mp.opcode[2]; mp_func op = (mp_func)mp.opcode[3]; CImg<ulongT> l_opcode(1,3); l_opcode[2] = mp.opcode[4]; // Scalar argument l_opcode.swap(mp.opcode); ulongT &target = mp.opcode[1]; while (siz-->0) { target = ptrd++; (*op)(mp); } l_opcode.swap(mp.opcode); return cimg::type<double>::nan(); } static double mp_self_map_vector_v(_cimg_math_parser& mp) { // Vector += vector unsigned int ptrd = (unsigned int)mp.opcode[1] + 1, siz = (unsigned int)mp.opcode[2], ptrs = (unsigned int)mp.opcode[4] + 1; mp_func op = (mp_func)mp.opcode[3]; CImg<ulongT> l_opcode(1,4); l_opcode.swap(mp.opcode); ulongT &target = mp.opcode[1], &argument = mp.opcode[2]; while (siz-->0) { target = ptrd++; argument = ptrs++; (*op)(mp); } l_opcode.swap(mp.opcode); return cimg::type<double>::nan(); } static double mp_self_mul(_cimg_math_parser& mp) { return _mp_arg(1)*=_mp_arg(2); } static double mp_self_div(_cimg_math_parser& mp) { return _mp_arg(1)/=_mp_arg(2); } static double mp_self_modulo(_cimg_math_parser& mp) { double &val = _mp_arg(1); return val = cimg::mod(val,_mp_arg(2)); } static double mp_self_pow(_cimg_math_parser& mp) { double &val = _mp_arg(1); return val = std::pow(val,_mp_arg(2)); } static double mp_self_sub(_cimg_math_parser& mp) { return _mp_arg(1)-=_mp_arg(2); } static double mp_set_ioff(_cimg_math_parser& mp) { CImg<T> &img = mp.imgout; const longT off = (longT)_mp_arg(2), whds = (longT)img.size(); const double val = _mp_arg(1); if (off>=0 && off<whds) img[off] = (T)val; return val; } static double mp_set_ixyzc(_cimg_math_parser& mp) { CImg<T> &img = mp.imgout; const int x = (int)_mp_arg(2), y = (int)_mp_arg(3), z = (int)_mp_arg(4), c = (int)_mp_arg(5); const double val = _mp_arg(1); if (x>=0 && x<img.width() && y>=0 && y<img.height() && z>=0 && z<img.depth() && c>=0 && c<img.spectrum()) img(x,y,z,c) = (T)val; return val; } static double mp_set_joff(_cimg_math_parser& mp) { CImg<T> &img = mp.imgout; const int ox = (int)mp.mem[_cimg_mp_slot_x], oy = (int)mp.mem[_cimg_mp_slot_y], oz = (int)mp.mem[_cimg_mp_slot_z], oc = (int)mp.mem[_cimg_mp_slot_c]; const longT off = img.offset(ox,oy,oz,oc) + (longT)_mp_arg(2), whds = (longT)img.size(); const double val = _mp_arg(1); if (off>=0 && off<whds) img[off] = (T)val; return val; } static double mp_set_jxyzc(_cimg_math_parser& mp) { CImg<T> &img = mp.imgout; const double ox = mp.mem[_cimg_mp_slot_x], oy = mp.mem[_cimg_mp_slot_y], oz = mp.mem[_cimg_mp_slot_z], oc = mp.mem[_cimg_mp_slot_c]; const int x = (int)(ox + _mp_arg(2)), y = (int)(oy + _mp_arg(3)), z = (int)(oz + _mp_arg(4)), c = (int)(oc + _mp_arg(5)); const double val = _mp_arg(1); if (x>=0 && x<img.width() && y>=0 && y<img.height() && z>=0 && z<img.depth() && c>=0 && c<img.spectrum()) img(x,y,z,c) = (T)val; return val; } static double mp_set_Ioff_s(_cimg_math_parser& mp) { CImg<T> &img = mp.imgout; const longT off = (longT)_mp_arg(2), whd = (longT)img.width()*img.height()*img.depth(); const T val = (T)_mp_arg(1); if (off>=0 && off<whd) { T *ptrd = &img[off]; cimg_forC(img,c) { *ptrd = val; ptrd+=whd; } } return _mp_arg(1); } static double mp_set_Ioff_v(_cimg_math_parser& mp) { CImg<T> &img = mp.imgout; const longT off = (longT)_mp_arg(2), whd = (longT)img.width()*img.height()*img.depth(); const double *ptrs = &_mp_arg(1) + 1; if (off>=0 && off<whd) { const unsigned int vsiz = (unsigned int)mp.opcode[3]; T *ptrd = &img[off]; cimg_for_inC(img,0,vsiz - 1,c) { *ptrd = (T)*(ptrs++); ptrd+=whd; } } return cimg::type<double>::nan(); } static double mp_set_Ixyz_s(_cimg_math_parser& mp) { CImg<T> &img = mp.imgout; const int x = (int)_mp_arg(2), y = (int)_mp_arg(3), z = (int)_mp_arg(4); const T val = (T)_mp_arg(1); if (x>=0 && x<img.width() && y>=0 && y<img.height() && z>=0 && z<img.depth()) { T *ptrd = &img(x,y,z); const ulongT whd = (ulongT)img._width*img._height*img._depth; cimg_forC(img,c) { *ptrd = val; ptrd+=whd; } } return _mp_arg(1); } static double mp_set_Ixyz_v(_cimg_math_parser& mp) { CImg<T> &img = mp.imgout; const int x = (int)_mp_arg(2), y = (int)_mp_arg(3), z = (int)_mp_arg(4); const double *ptrs = &_mp_arg(1) + 1; if (x>=0 && x<img.width() && y>=0 && y<img.height() && z>=0 && z<img.depth()) { const unsigned int vsiz = (unsigned int)mp.opcode[5]; T *ptrd = &img(x,y,z); const ulongT whd = (ulongT)img._width*img._height*img._depth; cimg_for_inC(img,0,vsiz - 1,c) { *ptrd = (T)*(ptrs++); ptrd+=whd; } } return cimg::type<double>::nan(); } static double mp_set_Joff_s(_cimg_math_parser& mp) { CImg<T> &img = mp.imgout; const int ox = (int)mp.mem[_cimg_mp_slot_x], oy = (int)mp.mem[_cimg_mp_slot_y], oz = (int)mp.mem[_cimg_mp_slot_z], oc = (int)mp.mem[_cimg_mp_slot_c]; const longT off = img.offset(ox,oy,oz,oc) + (longT)_mp_arg(2), whd = (longT)img.width()*img.height()*img.depth(); const T val = (T)_mp_arg(1); if (off>=0 && off<whd) { T *ptrd = &img[off]; cimg_forC(img,c) { *ptrd = val; ptrd+=whd; } } return _mp_arg(1); } static double mp_set_Joff_v(_cimg_math_parser& mp) { CImg<T> &img = mp.imgout; const int ox = (int)mp.mem[_cimg_mp_slot_x], oy = (int)mp.mem[_cimg_mp_slot_y], oz = (int)mp.mem[_cimg_mp_slot_z], oc = (int)mp.mem[_cimg_mp_slot_c]; const longT off = img.offset(ox,oy,oz,oc) + (longT)_mp_arg(2), whd = (longT)img.width()*img.height()*img.depth(); const double *ptrs = &_mp_arg(1) + 1; if (off>=0 && off<whd) { const unsigned int vsiz = (unsigned int)mp.opcode[3]; T *ptrd = &img[off]; cimg_for_inC(img,0,vsiz - 1,c) { *ptrd = (T)*(ptrs++); ptrd+=whd; } } return cimg::type<double>::nan(); } static double mp_set_Jxyz_s(_cimg_math_parser& mp) { CImg<T> &img = mp.imgout; const double ox = mp.mem[_cimg_mp_slot_x], oy = mp.mem[_cimg_mp_slot_y], oz = mp.mem[_cimg_mp_slot_z]; const int x = (int)(ox + _mp_arg(2)), y = (int)(oy + _mp_arg(3)), z = (int)(oz + _mp_arg(4)); const T val = (T)_mp_arg(1); if (x>=0 && x<img.width() && y>=0 && y<img.height() && z>=0 && z<img.depth()) { T *ptrd = &img(x,y,z); const ulongT whd = (ulongT)img._width*img._height*img._depth; cimg_forC(img,c) { *ptrd = val; ptrd+=whd; } } return _mp_arg(1); } static double mp_set_Jxyz_v(_cimg_math_parser& mp) { CImg<T> &img = mp.imgout; const double ox = mp.mem[_cimg_mp_slot_x], oy = mp.mem[_cimg_mp_slot_y], oz = mp.mem[_cimg_mp_slot_z]; const int x = (int)(ox + _mp_arg(2)), y = (int)(oy + _mp_arg(3)), z = (int)(oz + _mp_arg(4)); const double *ptrs = &_mp_arg(1) + 1; if (x>=0 && x<img.width() && y>=0 && y<img.height() && z>=0 && z<img.depth()) { const unsigned int vsiz = (unsigned int)mp.opcode[5]; T *ptrd = &img(x,y,z); const ulongT whd = (ulongT)img._width*img._height*img._depth; cimg_for_inC(img,0,vsiz - 1,c) { *ptrd = (T)*(ptrs++); ptrd+=whd; } } return cimg::type<double>::nan(); } static double mp_shift(_cimg_math_parser& mp) { double *const ptrd = &_mp_arg(1) + 1; const double *const ptrs = &_mp_arg(2) + 1; const unsigned int siz = (unsigned int)mp.opcode[3]; const int shift = (int)_mp_arg(4), boundary_conditions = (int)_mp_arg(5); CImg<doubleT>(ptrd,siz,1,1,1,true) = CImg<doubleT>(ptrs,siz,1,1,1,true).shift(shift,0,0,0,boundary_conditions); return cimg::type<double>::nan(); } static double mp_sign(_cimg_math_parser& mp) { return cimg::sign(_mp_arg(2)); } static double mp_sin(_cimg_math_parser& mp) { return std::sin(_mp_arg(2)); } static double mp_sinc(_cimg_math_parser& mp) { return cimg::sinc(_mp_arg(2)); } static double mp_sinh(_cimg_math_parser& mp) { return std::sinh(_mp_arg(2)); } static double mp_solve(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const double *ptr1 = &_mp_arg(2) + 1, *ptr2 = &_mp_arg(3) + 1; const unsigned int k = (unsigned int)mp.opcode[4], l = (unsigned int)mp.opcode[5], m = (unsigned int)mp.opcode[6]; CImg<doubleT>(ptrd,m,k,1,1,true) = CImg<doubleT>(ptr2,m,l,1,1,true).get_solve(CImg<doubleT>(ptr1,k,l,1,1,true)); return cimg::type<double>::nan(); } static double mp_sort(_cimg_math_parser& mp) { double *const ptrd = &_mp_arg(1) + 1; const double *const ptrs = &_mp_arg(2) + 1; const unsigned int siz = (unsigned int)mp.opcode[3], chunk_siz = (unsigned int)mp.opcode[5]; const bool is_increasing = (bool)_mp_arg(4); CImg<doubleT>(ptrd,chunk_siz,siz/chunk_siz,1,1,true) = CImg<doubleT>(ptrs,chunk_siz,siz/chunk_siz,1,1,true). get_sort(is_increasing,chunk_siz>1?'y':0); return cimg::type<double>::nan(); } static double mp_sqr(_cimg_math_parser& mp) { return cimg::sqr(_mp_arg(2)); } static double mp_sqrt(_cimg_math_parser& mp) { return std::sqrt(_mp_arg(2)); } static double mp_srand(_cimg_math_parser& mp) { mp.rng = (ulongT)_mp_arg(2); return cimg::type<double>::nan(); } static double mp_srand0(_cimg_math_parser& mp) { cimg::srand(&mp.rng); #if cimg_use_openmp!=0 mp.rng+=omp_get_thread_num(); #endif return cimg::type<double>::nan(); } static double mp_std(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; CImg<doubleT> vals(i_end - 3); double *p = vals.data(); for (unsigned int i = 3; i<i_end; ++i) *(p++) = _mp_arg(i); return std::sqrt(vals.variance()); } static double mp_string_init(_cimg_math_parser& mp) { const char *ptrs = (char*)&mp.opcode[3]; unsigned int ptrd = (unsigned int)mp.opcode[1] + 1, siz = (unsigned int)mp.opcode[2]; while (siz-->0) mp.mem[ptrd++] = (double)*(ptrs++); return cimg::type<double>::nan(); } static double mp_stov(_cimg_math_parser& mp) { const double *ptrs = &_mp_arg(2); const ulongT siz = (ulongT)mp.opcode[3]; longT ind = (longT)_mp_arg(4); const bool is_strict = (bool)_mp_arg(5); double val = cimg::type<double>::nan(); if (ind<0 || ind>=(longT)siz) return val; if (!siz) return *ptrs>='0' && *ptrs<='9'?*ptrs - '0':val; CImg<charT> ss(siz + 1 - ind); ptrs+=1 + ind; cimg_forX(ss,i) ss[i] = (char)ptrs[i]; ss.back() = 0; const char *s = ss._data; while (*s && *s<=32) ++s; const bool is_negative = *s=='-'; if (is_negative || *s=='+') ++s; int err = 0; char sep; if (*s=='0' && (s[1]=='x' || s[1]=='X') && s[2]>32) { // Hexadecimal number unsigned int ival; err = cimg_sscanf(s + 2,"%x%c",&ival,&sep); if (err>0) val = (double)ival; } else if (*s>32) { // Decimal number err = cimg_sscanf(s,"%lf%c",&val,&sep); #if cimg_OS==2 // Check for +/-NaN and +/-inf as Microsoft's sscanf() version is not able // to read those particular values. if (!err && (*s=='i' || *s=='I' || *s=='n' || *s=='N')) { if (!cimg::strncasecmp(s,"inf",3)) { val = cimg::type<double>::inf(); err = 1 + (s[3]!=0); } else if (!cimg::strncasecmp(s,"nan",3)) { val = cimg::type<double>::nan(); err = 1 + (s[3]!=0); } } #endif } if (err<=0 || (is_strict && err!=1)) return cimg::type<double>::nan(); if (is_negative) val = -val; return val; } static double mp_sub(_cimg_math_parser& mp) { return _mp_arg(2) - _mp_arg(3); } static double mp_sum(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; double val = _mp_arg(3); for (unsigned int i = 4; i<i_end; ++i) val+=_mp_arg(i); return val; } static double mp_tan(_cimg_math_parser& mp) { return std::tan(_mp_arg(2)); } static double mp_tanh(_cimg_math_parser& mp) { return std::tanh(_mp_arg(2)); } static double mp_trace(_cimg_math_parser& mp) { const double *ptrs = &_mp_arg(2) + 1; const unsigned int k = (unsigned int)mp.opcode[3]; return CImg<doubleT>(ptrs,k,k,1,1,true).trace(); } static double mp_transp(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const double *ptrs = &_mp_arg(2) + 1; const unsigned int k = (unsigned int)mp.opcode[3], l = (unsigned int)mp.opcode[4]; CImg<doubleT>(ptrd,l,k,1,1,true) = CImg<doubleT>(ptrs,k,l,1,1,true).get_transpose(); return cimg::type<double>::nan(); } static double mp_u(_cimg_math_parser& mp) { return cimg::rand(_mp_arg(2),_mp_arg(3),&mp.rng); } static double mp_uppercase(_cimg_math_parser& mp) { return cimg::uppercase(_mp_arg(2)); } static double mp_var(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; CImg<doubleT> vals(i_end - 3); double *p = vals.data(); for (unsigned int i = 3; i<i_end; ++i) *(p++) = _mp_arg(i); return vals.variance(); } static double mp_vector_copy(_cimg_math_parser& mp) { std::memcpy(&_mp_arg(1) + 1,&_mp_arg(2) + 1,sizeof(double)*mp.opcode[3]); return cimg::type<double>::nan(); } static double mp_vector_crop(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const double *ptrs = &_mp_arg(2) + 1; const longT length = (longT)mp.opcode[3], start = (longT)_mp_arg(4), sublength = (longT)mp.opcode[5], step = (longT)_mp_arg(6); if (start<0 || start + step*(sublength-1)>=length) throw CImgArgumentException("[" cimg_appname "_math_parser] CImg<%s>: Value accessor '[]': " "Out-of-bounds sub-vector request " "(length: %ld, start: %ld, sub-length: %ld, step: %ld).", mp.imgin.pixel_type(),length,start,sublength,step); ptrs+=start; if (step==1) std::memcpy(ptrd,ptrs,sublength*sizeof(double)); else for (longT k = 0; k<sublength; ++k) { *(ptrd++) = *ptrs; ptrs+=step; } return cimg::type<double>::nan(); } static double mp_vector_init(_cimg_math_parser& mp) { unsigned int ptrs = 4U, ptrd = (unsigned int)mp.opcode[1] + 1, siz = (unsigned int)mp.opcode[3]; switch (mp.opcode[2] - 4) { case 0 : std::memset(mp.mem._data + ptrd,0,siz*sizeof(double)); break; // 0 values given case 1 : { const double val = _mp_arg(ptrs); while (siz-->0) mp.mem[ptrd++] = val; } break; default : while (siz-->0) { mp.mem[ptrd++] = _mp_arg(ptrs++); if (ptrs>=mp.opcode[2]) ptrs = 4U; } } return cimg::type<double>::nan(); } static double mp_vector_eq(_cimg_math_parser& mp) { const double *ptr1 = &_mp_arg(2) + 1, *ptr2 = &_mp_arg(4) + 1; unsigned int p1 = (unsigned int)mp.opcode[3], p2 = (unsigned int)mp.opcode[5], n; const int N = (int)_mp_arg(6); const bool case_sensitive = (bool)_mp_arg(7); bool still_equal = true; double value; if (!N) return true; // Compare all values. if (N<0) { if (p1>0 && p2>0) { // Vector == vector if (p1!=p2) return false; if (case_sensitive) while (still_equal && p1--) still_equal = *(ptr1++)==*(ptr2++); else while (still_equal && p1--) still_equal = cimg::lowercase(*(ptr1++))==cimg::lowercase(*(ptr2++)); return still_equal; } else if (p1>0 && !p2) { // Vector == scalar value = _mp_arg(4); if (!case_sensitive) value = cimg::lowercase(value); while (still_equal && p1--) still_equal = *(ptr1++)==value; return still_equal; } else if (!p1 && p2>0) { // Scalar == vector value = _mp_arg(2); if (!case_sensitive) value = cimg::lowercase(value); while (still_equal && p2--) still_equal = *(ptr2++)==value; return still_equal; } else { // Scalar == scalar if (case_sensitive) return _mp_arg(2)==_mp_arg(4); else return cimg::lowercase(_mp_arg(2))==cimg::lowercase(_mp_arg(4)); } } // Compare only first N values. if (p1>0 && p2>0) { // Vector == vector n = cimg::min((unsigned int)N,p1,p2); if (case_sensitive) while (still_equal && n--) still_equal = *(ptr1++)==(*ptr2++); else while (still_equal && n--) still_equal = cimg::lowercase(*(ptr1++))==cimg::lowercase(*(ptr2++)); return still_equal; } else if (p1>0 && !p2) { // Vector == scalar n = std::min((unsigned int)N,p1); value = _mp_arg(4); if (!case_sensitive) value = cimg::lowercase(value); while (still_equal && n--) still_equal = *(ptr1++)==value; return still_equal; } else if (!p1 && p2>0) { // Scalar == vector n = std::min((unsigned int)N,p2); value = _mp_arg(2); if (!case_sensitive) value = cimg::lowercase(value); while (still_equal && n--) still_equal = *(ptr2++)==value; return still_equal; } // Scalar == scalar if (case_sensitive) return _mp_arg(2)==_mp_arg(4); return cimg::lowercase(_mp_arg(2))==cimg::lowercase(_mp_arg(4)); } static double mp_vector_off(_cimg_math_parser& mp) { const unsigned int ptr = (unsigned int)mp.opcode[2] + 1, siz = (unsigned int)mp.opcode[3]; const int off = (int)_mp_arg(4); return off>=0 && off<(int)siz?mp.mem[ptr + off]:cimg::type<double>::nan(); } static double mp_vector_map_sv(_cimg_math_parser& mp) { // Operator(scalar,vector) unsigned int siz = (unsigned int)mp.opcode[2], ptrs = (unsigned int)mp.opcode[5] + 1; double *ptrd = &_mp_arg(1) + 1; mp_func op = (mp_func)mp.opcode[3]; CImg<ulongT> l_opcode(4); l_opcode[2] = mp.opcode[4]; // Scalar argument1 l_opcode.swap(mp.opcode); ulongT &argument2 = mp.opcode[3]; while (siz-->0) { argument2 = ptrs++; *(ptrd++) = (*op)(mp); } l_opcode.swap(mp.opcode); return cimg::type<double>::nan(); } static double mp_vector_map_v(_cimg_math_parser& mp) { // Operator(vector) unsigned int siz = (unsigned int)mp.opcode[2], ptrs = (unsigned int)mp.opcode[4] + 1; double *ptrd = &_mp_arg(1) + 1; mp_func op = (mp_func)mp.opcode[3]; CImg<ulongT> l_opcode(1,3); l_opcode.swap(mp.opcode); ulongT &argument = mp.opcode[2]; while (siz-->0) { argument = ptrs++; *(ptrd++) = (*op)(mp); } l_opcode.swap(mp.opcode); return cimg::type<double>::nan(); } static double mp_vector_map_vs(_cimg_math_parser& mp) { // Operator(vector,scalar) unsigned int siz = (unsigned int)mp.opcode[2], ptrs = (unsigned int)mp.opcode[4] + 1; double *ptrd = &_mp_arg(1) + 1; mp_func op = (mp_func)mp.opcode[3]; CImg<ulongT> l_opcode(1,4); l_opcode[3] = mp.opcode[5]; // Scalar argument2 l_opcode.swap(mp.opcode); ulongT &argument1 = mp.opcode[2]; while (siz-->0) { argument1 = ptrs++; *(ptrd++) = (*op)(mp); } l_opcode.swap(mp.opcode); return cimg::type<double>::nan(); } static double mp_vector_map_vss(_cimg_math_parser& mp) { // Operator(vector,scalar,scalar) unsigned int siz = (unsigned int)mp.opcode[2], ptrs = (unsigned int)mp.opcode[4] + 1; double *ptrd = &_mp_arg(1) + 1; mp_func op = (mp_func)mp.opcode[3]; CImg<ulongT> l_opcode(1,5); l_opcode[3] = mp.opcode[5]; // Scalar argument2 l_opcode[4] = mp.opcode[6]; // Scalar argument3 l_opcode.swap(mp.opcode); ulongT &argument1 = mp.opcode[2]; while (siz-->0) { argument1 = ptrs++; *(ptrd++) = (*op)(mp); } l_opcode.swap(mp.opcode); return cimg::type<double>::nan(); } static double mp_vector_map_vv(_cimg_math_parser& mp) { // Operator(vector,vector) unsigned int siz = (unsigned int)mp.opcode[2], ptrs1 = (unsigned int)mp.opcode[4] + 1, ptrs2 = (unsigned int)mp.opcode[5] + 1; double *ptrd = &_mp_arg(1) + 1; mp_func op = (mp_func)mp.opcode[3]; CImg<ulongT> l_opcode(1,4); l_opcode.swap(mp.opcode); ulongT &argument1 = mp.opcode[2], &argument2 = mp.opcode[3]; while (siz-->0) { argument1 = ptrs1++; argument2 = ptrs2++; *(ptrd++) = (*op)(mp); } l_opcode.swap(mp.opcode); return cimg::type<double>::nan(); } static double mp_vector_neq(_cimg_math_parser& mp) { return !mp_vector_eq(mp); } static double mp_vector_print(_cimg_math_parser& mp) { const bool print_string = (bool)mp.opcode[4]; cimg_pragma_openmp(critical(mp_vector_print)) { CImg<charT> _expr(mp.opcode[2] - 5); const ulongT *ptrs = mp.opcode._data + 5; cimg_for(_expr,ptrd,char) *ptrd = (char)*(ptrs++); cimg::strellipsize(_expr); unsigned int ptr = (unsigned int)mp.opcode[1] + 1, siz0 = (unsigned int)mp.opcode[3], siz = siz0; cimg::mutex(6); std::fprintf(cimg::output(),"\n[" cimg_appname "_math_parser] %s = [ ",_expr._data); unsigned int count = 0; while (siz-->0) { if (count>=64 && siz>=64) { std::fprintf(cimg::output(),"...,"); ptr = (unsigned int)mp.opcode[1] + 1 + siz0 - 64; siz = 64; } else std::fprintf(cimg::output(),"%g%s",mp.mem[ptr++],siz?",":""); ++count; } if (print_string) { CImg<charT> str(siz0 + 1); ptr = (unsigned int)mp.opcode[1] + 1; for (unsigned int k = 0; k<siz0; ++k) str[k] = (char)mp.mem[ptr++]; str[siz0] = 0; cimg::strellipsize(str,1024,false); std::fprintf(cimg::output()," ] = '%s' (size: %u)",str._data,siz0); } else std::fprintf(cimg::output()," ] (size: %u)",siz0); std::fflush(cimg::output()); cimg::mutex(6,0); } return cimg::type<double>::nan(); } static double mp_vector_resize(_cimg_math_parser& mp) { double *const ptrd = &_mp_arg(1) + 1; const unsigned int p1 = (unsigned int)mp.opcode[2], p2 = (unsigned int)mp.opcode[4]; const int interpolation = (int)_mp_arg(5), boundary_conditions = (int)_mp_arg(6); if (p2) { // Resize vector const double *const ptrs = &_mp_arg(3) + 1; CImg<doubleT>(ptrd,p1,1,1,1,true) = CImg<doubleT>(ptrs,p2,1,1,1,true). get_resize(p1,1,1,1,interpolation,boundary_conditions); } else { // Resize scalar const double value = _mp_arg(3); CImg<doubleT>(ptrd,p1,1,1,1,true) = CImg<doubleT>(1,1,1,1,value).resize(p1,1,1,1,interpolation, boundary_conditions); } return cimg::type<double>::nan(); } static double mp_vector_reverse(_cimg_math_parser& mp) { double *const ptrd = &_mp_arg(1) + 1; const double *const ptrs = &_mp_arg(2) + 1; const unsigned int p1 = (unsigned int)mp.opcode[3]; CImg<doubleT>(ptrd,p1,1,1,1,true) = CImg<doubleT>(ptrs,p1,1,1,1,true).get_mirror('x'); return cimg::type<double>::nan(); } static double mp_vector_set_off(_cimg_math_parser& mp) { const unsigned int ptr = (unsigned int)mp.opcode[2] + 1, siz = (unsigned int)mp.opcode[3]; const int off = (int)_mp_arg(4); if (off>=0 && off<(int)siz) mp.mem[ptr + off] = _mp_arg(5); return _mp_arg(5); } static double mp_vtos(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const unsigned int sizd = (unsigned int)mp.opcode[2], sizs = (unsigned int)mp.opcode[4]; const int nb_digits = (int)_mp_arg(5); CImg<charT> format(8); switch (nb_digits) { case -1 : std::strcpy(format,"%g"); break; case 0 : std::strcpy(format,"%.17g"); break; default : cimg_snprintf(format,format._width,"%%.%dg",nb_digits); } CImg<charT> str; if (sizs) { // Vector expression const double *ptrs = &_mp_arg(3) + 1; CImg<doubleT>(ptrs,sizs,1,1,1,true).value_string(',',sizd + 1,format).move_to(str); } else { // Scalar expression str.assign(sizd + 1); cimg_snprintf(str,sizd + 1,format,_mp_arg(3)); } const unsigned int l = std::min(sizd,(unsigned int)std::strlen(str) + 1); CImg<doubleT>(ptrd,l,1,1,1,true) = str.get_shared_points(0,l - 1); return cimg::type<double>::nan(); } static double mp_while(_cimg_math_parser& mp) { const ulongT mem_body = mp.opcode[1], mem_cond = mp.opcode[2]; const CImg<ulongT> *const p_cond = ++mp.p_code, *const p_body = p_cond + mp.opcode[3], *const p_end = p_body + mp.opcode[4]; const unsigned int vsiz = (unsigned int)mp.opcode[5]; bool is_cond = false; if (mp.opcode[6]) { // Set default value for result and condition if necessary if (vsiz) CImg<doubleT>(&mp.mem[mem_body] + 1,vsiz,1,1,1,true).fill(cimg::type<double>::nan()); else mp.mem[mem_body] = cimg::type<double>::nan(); } if (mp.opcode[7]) mp.mem[mem_cond] = 0; const unsigned int _break_type = mp.break_type; mp.break_type = 0; do { for (mp.p_code = p_cond; mp.p_code<p_body; ++mp.p_code) { // Evaluate condition mp.opcode._data = mp.p_code->_data; const ulongT target = mp.opcode[1]; mp.mem[target] = _cimg_mp_defunc(mp); } if (mp.break_type==1) break; is_cond = (bool)mp.mem[mem_cond]; if (is_cond && !mp.break_type) // Evaluate body for (mp.p_code = p_body; mp.p_code<p_end; ++mp.p_code) { mp.opcode._data = mp.p_code->_data; const ulongT target = mp.opcode[1]; mp.mem[target] = _cimg_mp_defunc(mp); } if (mp.break_type==1) break; else if (mp.break_type==2) mp.break_type = 0; } while (is_cond); mp.break_type = _break_type; mp.p_code = p_end - 1; return mp.mem[mem_body]; } static double mp_Ioff(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const unsigned int boundary_conditions = (unsigned int)_mp_arg(3), vsiz = (unsigned int)mp.opcode[4]; const CImg<T> &img = mp.imgin; const longT off = (longT)_mp_arg(2), whd = (longT)img.width()*img.height()*img.depth(); const T *ptrs; if (off>=0 && off<whd) { ptrs = &img[off]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); } if (img._data) switch (boundary_conditions) { case 3 : { // Mirror const longT whd2 = 2*whd, moff = cimg::mod(off,whd2); ptrs = &img[moff<whd?moff:whd2 - moff - 1]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); } case 2 : // Periodic ptrs = &img[cimg::mod(off,whd)]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); case 1 : // Neumann ptrs = off<0?&img[0]:&img[whd - 1]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); default : // Dirichlet std::memset(ptrd,0,vsiz*sizeof(double)); return cimg::type<double>::nan(); } std::memset(ptrd,0,vsiz*sizeof(double)); return cimg::type<double>::nan(); } static double mp_Ixyz(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const unsigned int interpolation = (unsigned int)_mp_arg(5), boundary_conditions = (unsigned int)_mp_arg(6), vsiz = (unsigned int)mp.opcode[7]; const CImg<T> &img = mp.imgin; const double x = _mp_arg(2), y = _mp_arg(3), z = _mp_arg(4); const ulongT whd = (ulongT)img._width*img._height*img._depth; const T *ptrs; switch (interpolation) { case 2 : // Cubic interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), cx = mx<img.width()?mx:w2 - mx - 1, cy = my<img.height()?my:h2 - my - 1, cz = mz<img.depth()?mz:d2 - mz - 1; cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._cubic_atXYZ(cx,cy,cz,c); } break; case 2 : // Periodic cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._cubic_atXYZ_p((float)x,(float)y,(float)z,c); break; case 1 : // Neumann cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._cubic_atXYZ((float)x,(float)y,(float)z,c); break; default : // Dirichlet cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img.cubic_atXYZ((float)x,(float)y,(float)z,c,(T)0); } break; case 1 : // Linear interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), cx = mx<img.width()?mx:w2 - mx - 1, cy = my<img.height()?my:h2 - my - 1, cz = mz<img.depth()?mz:d2 - mz - 1; cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._linear_atXYZ(cx,cy,cz,c); } break; case 2 : // Periodic cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._linear_atXYZ_p((float)x,(float)y,(float)z,c); break; case 1 : // Neumann cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._linear_atXYZ((float)x,(float)y,(float)z,c); break; default : // Dirichlet cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img.linear_atXYZ((float)x,(float)y,(float)z,c,(T)0); } break; default : // Nearest neighbor interpolation switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*img.width(), h2 = 2*img.height(), d2 = 2*img.depth(), mx = cimg::mod((int)x,w2), my = cimg::mod((int)y,h2), mz = cimg::mod((int)z,d2), cx = mx<img.width()?mx:w2 - mx - 1, cy = my<img.height()?my:h2 - my - 1, cz = mz<img.depth()?mz:d2 - mz - 1; ptrs = &img(cx,cy,cz); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } break; case 2 : { // Periodic const int cx = (int)cimg::mod(x,(double)img._width), cy = (int)cimg::mod(y,(double)img._height), cz = (int)cimg::mod(z,(double)img._depth); ptrs = &img(cx,cy,cz); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } break; case 1 : { // Neumann ptrs = &img._atXYZ((int)x,(int)y,(int)z); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } break; default : // Dirichlet if (img.containsXYZC((int)x,(int)y,(int)z)) { ptrs = &img((int)x,(int)y,(int)z); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } else std::memset(ptrd,0,vsiz*sizeof(double)); } } return cimg::type<double>::nan(); } static double mp_Joff(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const unsigned int boundary_conditions = (unsigned int)_mp_arg(3), vsiz = (unsigned int)mp.opcode[4]; const CImg<T> &img = mp.imgin; const int ox = (int)mp.mem[_cimg_mp_slot_x], oy = (int)mp.mem[_cimg_mp_slot_y], oz = (int)mp.mem[_cimg_mp_slot_z]; const longT off = img.offset(ox,oy,oz) + (longT)_mp_arg(2), whd = (longT)img.width()*img.height()*img.depth(); const T *ptrs; if (off>=0 && off<whd) { ptrs = &img[off]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); } if (img._data) switch (boundary_conditions) { case 3 : { // Mirror const longT whd2 = 2*whd, moff = cimg::mod(off,whd2); ptrs = &img[moff<whd?moff:whd2 - moff - 1]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); } case 2 : // Periodic ptrs = &img[cimg::mod(off,whd)]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); case 1 : // Neumann ptrs = off<0?&img[0]:&img[whd - 1]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); default : // Dirichlet std::memset(ptrd,0,vsiz*sizeof(double)); return cimg::type<double>::nan(); } std::memset(ptrd,0,vsiz*sizeof(double)); return cimg::type<double>::nan(); } static double mp_Jxyz(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const unsigned int interpolation = (unsigned int)_mp_arg(5), boundary_conditions = (unsigned int)_mp_arg(6), vsiz = (unsigned int)mp.opcode[7]; const CImg<T> &img = mp.imgin; const double ox = mp.mem[_cimg_mp_slot_x], oy = mp.mem[_cimg_mp_slot_y], oz = mp.mem[_cimg_mp_slot_z], x = ox + _mp_arg(2), y = oy + _mp_arg(3), z = oz + _mp_arg(4); const ulongT whd = (ulongT)img._width*img._height*img._depth; const T *ptrs; switch (interpolation) { case 2 : // Cubic interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), cx = mx<img.width()?mx:w2 - mx - 1, cy = my<img.height()?my:h2 - my - 1, cz = mz<img.depth()?mz:d2 - mz - 1; cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._cubic_atXYZ(cx,cy,cz,c); } break; case 2 : // Periodic cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._cubic_atXYZ_p((float)x,(float)y,(float)z,c); break; case 1 : // Neumann cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._cubic_atXYZ((float)x,(float)y,(float)z,c); break; default : // Dirichlet cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img.cubic_atXYZ((float)x,(float)y,(float)z,c,(T)0); } break; case 1 : // Linear interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), cx = mx<img.width()?mx:w2 - mx - 1, cy = my<img.height()?my:h2 - my - 1, cz = mz<img.depth()?mz:d2 - mz - 1; cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._linear_atXYZ(cx,cy,cz,c); } break; case 2 : // Periodic cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._linear_atXYZ_p((float)x,(float)y,(float)z,c); break; case 1 : // Neumann cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._linear_atXYZ((float)x,(float)y,(float)z,c); break; default : // Dirichlet cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img.linear_atXYZ((float)x,(float)y,(float)z,c,(T)0); } break; default : // Nearest neighbor interpolation switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*img.width(), h2 = 2*img.height(), d2 = 2*img.depth(), mx = cimg::mod((int)x,w2), my = cimg::mod((int)y,h2), mz = cimg::mod((int)z,d2), cx = mx<img.width()?mx:w2 - mx - 1, cy = my<img.height()?my:h2 - my - 1, cz = mz<img.depth()?mz:d2 - mz - 1; ptrs = &img(cx,cy,cz); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } break; case 2 : { // Periodic const int cx = (int)cimg::mod(x,(double)img._width), cy = (int)cimg::mod(y,(double)img._height), cz = (int)cimg::mod(z,(double)img._depth); ptrs = &img(cx,cy,cz); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } break; case 1 : { // Neumann ptrs = &img._atXYZ((int)x,(int)y,(int)z); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } break; default : // Dirichlet if (img.containsXYZC((int)x,(int)y,(int)z)) { ptrs = &img((int)x,(int)y,(int)z); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } else std::memset(ptrd,0,vsiz*sizeof(double)); } } return cimg::type<double>::nan(); } #undef _mp_arg }; // struct _cimg_math_parser {} #define _cimg_create_pointwise_functions(name,func,min_size) \ CImg<T>& name() { \ if (is_empty()) return *this; \ cimg_openmp_for(*this,func((double)*ptr),min_size); \ return *this; \ } \ CImg<Tfloat> get_##name() const { \ return CImg<Tfloat>(*this,false).name(); \ } //! Compute the square value of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its square value \f$I_{(x,y,z,c)}^2\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. \par Example \code const CImg<float> img("reference.jpg"); (img,img.get_sqr().normalize(0,255)).display(); \endcode \image html ref_sqr.jpg **/ _cimg_create_pointwise_functions(sqr,cimg::sqr,524288) //! Compute the square root of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its square root \f$\sqrt{I_{(x,y,z,c)}}\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. \par Example \code const CImg<float> img("reference.jpg"); (img,img.get_sqrt().normalize(0,255)).display(); \endcode \image html ref_sqrt.jpg **/ _cimg_create_pointwise_functions(sqrt,std::sqrt,8192) //! Compute the exponential of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its exponential \f$e^{I_{(x,y,z,c)}}\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(exp,std::exp,4096) //! Compute the logarithm of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its logarithm \f$\mathrm{log}_{e}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(log,std::log,262144) //! Compute the base-2 logarithm of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its base-2 logarithm \f$\mathrm{log}_{2}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(log2,cimg::log2,4096) //! Compute the base-10 logarithm of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its base-10 logarithm \f$\mathrm{log}_{10}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(log10,std::log10,4096) //! Compute the absolute value of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its absolute value \f$|I_{(x,y,z,c)}|\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(abs,cimg::abs,524288) //! Compute the sign of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its sign \f$\mathrm{sign}(I_{(x,y,z,c)})\f$. \note - The sign is set to: - \c 1 if pixel value is strictly positive. - \c -1 if pixel value is strictly negative. - \c 0 if pixel value is equal to \c 0. - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(sign,cimg::sign,32768) //! Compute the cosine of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its cosine \f$\cos(I_{(x,y,z,c)})\f$. \note - Pixel values are regarded as being in \e radian. - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(cos,std::cos,8192) //! Compute the sine of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its sine \f$\sin(I_{(x,y,z,c)})\f$. \note - Pixel values are regarded as being in \e radian. - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(sin,std::sin,8192) //! Compute the sinc of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its sinc \f$\mathrm{sinc}(I_{(x,y,z,c)})\f$. \note - Pixel values are regarded as being exin \e radian. - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(sinc,cimg::sinc,2048) //! Compute the tangent of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its tangent \f$\tan(I_{(x,y,z,c)})\f$. \note - Pixel values are regarded as being exin \e radian. - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(tan,std::tan,2048) //! Compute the hyperbolic cosine of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its hyperbolic cosine \f$\mathrm{cosh}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(cosh,std::cosh,2048) //! Compute the hyperbolic sine of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its hyperbolic sine \f$\mathrm{sinh}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(sinh,std::sinh,2048) //! Compute the hyperbolic tangent of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its hyperbolic tangent \f$\mathrm{tanh}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(tanh,std::tanh,2048) //! Compute the arccosine of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its arccosine \f$\mathrm{acos}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(acos,std::acos,8192) //! Compute the arcsine of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its arcsine \f$\mathrm{asin}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(asin,std::asin,8192) //! Compute the arctangent of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its arctangent \f$\mathrm{atan}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(atan,std::atan,8192) //! Compute the arctangent2 of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its arctangent2 \f$\mathrm{atan2}(I_{(x,y,z,c)})\f$. \param img Image whose pixel values specify the second argument of the \c atan2() function. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. \par Example \code const CImg<float> img_x(100,100,1,1,"x-w/2",false), // Define an horizontal centered gradient, from '-width/2' to 'width/2' img_y(100,100,1,1,"y-h/2",false), // Define a vertical centered gradient, from '-height/2' to 'height/2' img_atan2 = img_y.get_atan2(img_x); // Compute atan2(y,x) for each pixel value (img_x,img_y,img_atan2).display(); \endcode **/ template<typename t> CImg<T>& atan2(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return atan2(+img); T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)std::atan2((double)*ptrd,(double)*(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)std::atan2((double)*ptrd,(double)*(ptrs++)); } return *this; } //! Compute the arctangent2 of each pixel value \newinstance. template<typename t> CImg<Tfloat> get_atan2(const CImg<t>& img) const { return CImg<Tfloat>(*this,false).atan2(img); } //! Compute the hyperbolic arccosine of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its arccosineh \f$\mathrm{acosh}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(acosh,cimg::acosh,8192) //! Compute the hyperbolic arcsine of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its hyperbolic arcsine \f$\mathrm{asinh}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(asinh,cimg::asinh,8192) //! Compute the hyperbolic arctangent of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its hyperbolic arctangent \f$\mathrm{atanh}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(atanh,cimg::atanh,8192) //! In-place pointwise multiplication. /** Compute the pointwise multiplication between the image instance and the specified input image \c img. \param img Input image, as the second operand of the multiplication. \note - Similar to operator+=(const CImg<t>&), except that it performs a pointwise multiplication instead of an addition. - It does \e not perform a \e matrix multiplication. For this purpose, use operator*=(const CImg<t>&) instead. \par Example \code CImg<float> img("reference.jpg"), shade(img.width,img.height(),1,1,"-(x-w/2)^2-(y-h/2)^2",false); shade.normalize(0,1); (img,shade,img.get_mul(shade)).display(); \endcode **/ template<typename t> CImg<T>& mul(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return mul(+img); T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)(*ptrd * *(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)(*ptrd * *(ptrs++)); } return *this; } //! In-place pointwise multiplication \newinstance. template<typename t> CImg<_cimg_Tt> get_mul(const CImg<t>& img) const { return CImg<_cimg_Tt>(*this,false).mul(img); } //! In-place pointwise division. /** Similar to mul(const CImg<t>&), except that it performs a pointwise division instead of a multiplication. **/ template<typename t> CImg<T>& div(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return div(+img); T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)(*ptrd / *(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)(*ptrd / *(ptrs++)); } return *this; } //! In-place pointwise division \newinstance. template<typename t> CImg<_cimg_Tt> get_div(const CImg<t>& img) const { return CImg<_cimg_Tt>(*this,false).div(img); } //! Raise each pixel value to a specified power. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its power \f$I_{(x,y,z,c)}^p\f$. \param p Exponent value. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. \par Example \code const CImg<float> img0("reference.jpg"), // Load reference color image img1 = (img0/255).pow(1.8)*=255, // Compute gamma correction, with gamma = 1.8 img2 = (img0/255).pow(0.5)*=255; // Compute gamma correction, with gamma = 0.5 (img0,img1,img2).display(); \endcode **/ CImg<T>& pow(const double p) { if (is_empty()) return *this; if (p==-4) { cimg_openmp_for(*this,1/(Tfloat)cimg::pow4(*ptr),32768); return *this; } if (p==-3) { cimg_openmp_for(*this,1/(Tfloat)cimg::pow3(*ptr),32768); return *this; } if (p==-2) { cimg_openmp_for(*this,1/(Tfloat)cimg::sqr(*ptr),32768); return *this; } if (p==-1) { cimg_openmp_for(*this,1/(Tfloat)*ptr,32768); return *this; } if (p==-0.5) { cimg_openmp_for(*this,1/std::sqrt((Tfloat)*ptr),8192); return *this; } if (p==0) return fill((T)1); if (p==0.5) return sqrt(); if (p==1) return *this; if (p==2) return sqr(); if (p==3) { cimg_openmp_for(*this,cimg::pow3(*ptr),262144); return *this; } if (p==4) { cimg_openmp_for(*this,cimg::pow4(*ptr),131072); return *this; } cimg_openmp_for(*this,std::pow((Tfloat)*ptr,(Tfloat)p),1024); return *this; } //! Raise each pixel value to a specified power \newinstance. CImg<Tfloat> get_pow(const double p) const { return CImg<Tfloat>(*this,false).pow(p); } //! Raise each pixel value to a power, specified from an expression. /** Similar to operator+=(const char*), except it performs a pointwise exponentiation instead of an addition. **/ CImg<T>& pow(const char *const expression) { return pow((+*this)._fill(expression,true,1,0,0,"pow",this)); } //! Raise each pixel value to a power, specified from an expression \newinstance. CImg<Tfloat> get_pow(const char *const expression) const { return CImg<Tfloat>(*this,false).pow(expression); } //! Raise each pixel value to a power, pointwisely specified from another image. /** Similar to operator+=(const CImg<t>& img), except that it performs an exponentiation instead of an addition. **/ template<typename t> CImg<T>& pow(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return pow(+img); T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)std::pow((double)*ptrd,(double)(*(ptrs++))); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)std::pow((double)*ptrd,(double)(*(ptrs++))); } return *this; } //! Raise each pixel value to a power, pointwisely specified from another image \newinstance. template<typename t> CImg<Tfloat> get_pow(const CImg<t>& img) const { return CImg<Tfloat>(*this,false).pow(img); } //! Compute the bitwise left rotation of each pixel value. /** Similar to operator<<=(unsigned int), except that it performs a left rotation instead of a left shift. **/ CImg<T>& rol(const unsigned int n=1) { if (is_empty()) return *this; cimg_openmp_for(*this,cimg::rol(*ptr,n),32768); return *this; } //! Compute the bitwise left rotation of each pixel value \newinstance. CImg<T> get_rol(const unsigned int n=1) const { return (+*this).rol(n); } //! Compute the bitwise left rotation of each pixel value. /** Similar to operator<<=(const char*), except that it performs a left rotation instead of a left shift. **/ CImg<T>& rol(const char *const expression) { return rol((+*this)._fill(expression,true,1,0,0,"rol",this)); } //! Compute the bitwise left rotation of each pixel value \newinstance. CImg<T> get_rol(const char *const expression) const { return (+*this).rol(expression); } //! Compute the bitwise left rotation of each pixel value. /** Similar to operator<<=(const CImg<t>&), except that it performs a left rotation instead of a left shift. **/ template<typename t> CImg<T>& rol(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return rol(+img); T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)cimg::rol(*ptrd,(unsigned int)(*(ptrs++))); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)cimg::rol(*ptrd,(unsigned int)(*(ptrs++))); } return *this; } //! Compute the bitwise left rotation of each pixel value \newinstance. template<typename t> CImg<T> get_rol(const CImg<t>& img) const { return (+*this).rol(img); } //! Compute the bitwise right rotation of each pixel value. /** Similar to operator>>=(unsigned int), except that it performs a right rotation instead of a right shift. **/ CImg<T>& ror(const unsigned int n=1) { if (is_empty()) return *this; cimg_openmp_for(*this,cimg::ror(*ptr,n),32768); return *this; } //! Compute the bitwise right rotation of each pixel value \newinstance. CImg<T> get_ror(const unsigned int n=1) const { return (+*this).ror(n); } //! Compute the bitwise right rotation of each pixel value. /** Similar to operator>>=(const char*), except that it performs a right rotation instead of a right shift. **/ CImg<T>& ror(const char *const expression) { return ror((+*this)._fill(expression,true,1,0,0,"ror",this)); } //! Compute the bitwise right rotation of each pixel value \newinstance. CImg<T> get_ror(const char *const expression) const { return (+*this).ror(expression); } //! Compute the bitwise right rotation of each pixel value. /** Similar to operator>>=(const CImg<t>&), except that it performs a right rotation instead of a right shift. **/ template<typename t> CImg<T>& ror(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return ror(+img); T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)cimg::ror(*ptrd,(unsigned int)(*(ptrs++))); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)cimg::ror(*ptrd,(unsigned int)(*(ptrs++))); } return *this; } //! Compute the bitwise right rotation of each pixel value \newinstance. template<typename t> CImg<T> get_ror(const CImg<t>& img) const { return (+*this).ror(img); } //! Pointwise min operator between instance image and a value. /** \param val Value used as the reference argument of the min operator. \note Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by \f$\mathrm{min}(I_{(x,y,z,c)},\mathrm{val})\f$. **/ CImg<T>& min(const T& value) { if (is_empty()) return *this; cimg_openmp_for(*this,std::min(*ptr,value),65536); return *this; } //! Pointwise min operator between instance image and a value \newinstance. CImg<T> get_min(const T& value) const { return (+*this).min(value); } //! Pointwise min operator between two images. /** \param img Image used as the reference argument of the min operator. \note Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by \f$\mathrm{min}(I_{(x,y,z,c)},\mathrm{img}_{(x,y,z,c)})\f$. **/ template<typename t> CImg<T>& min(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return min(+img); T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = std::min((T)*(ptrs++),*ptrd); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = std::min((T)*(ptrs++),*ptrd); } return *this; } //! Pointwise min operator between two images \newinstance. template<typename t> CImg<_cimg_Tt> get_min(const CImg<t>& img) const { return CImg<_cimg_Tt>(*this,false).min(img); } //! Pointwise min operator between an image and an expression. /** \param expression Math formula as a C-string. \note Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by \f$\mathrm{min}(I_{(x,y,z,c)},\mathrm{expr}_{(x,y,z,c)})\f$. **/ CImg<T>& min(const char *const expression) { return min((+*this)._fill(expression,true,1,0,0,"min",this)); } //! Pointwise min operator between an image and an expression \newinstance. CImg<Tfloat> get_min(const char *const expression) const { return CImg<Tfloat>(*this,false).min(expression); } //! Pointwise max operator between instance image and a value. /** \param val Value used as the reference argument of the max operator. \note Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by \f$\mathrm{max}(I_{(x,y,z,c)},\mathrm{val})\f$. **/ CImg<T>& max(const T& value) { if (is_empty()) return *this; cimg_openmp_for(*this,std::max(*ptr,value),65536); return *this; } //! Pointwise max operator between instance image and a value \newinstance. CImg<T> get_max(const T& value) const { return (+*this).max(value); } //! Pointwise max operator between two images. /** \param img Image used as the reference argument of the max operator. \note Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by \f$\mathrm{max}(I_{(x,y,z,c)},\mathrm{img}_{(x,y,z,c)})\f$. **/ template<typename t> CImg<T>& max(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return max(+img); T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = std::max((T)*(ptrs++),*ptrd); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = std::max((T)*(ptrs++),*ptrd); } return *this; } //! Pointwise max operator between two images \newinstance. template<typename t> CImg<_cimg_Tt> get_max(const CImg<t>& img) const { return CImg<_cimg_Tt>(*this,false).max(img); } //! Pointwise max operator between an image and an expression. /** \param expression Math formula as a C-string. \note Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by \f$\mathrm{max}(I_{(x,y,z,c)},\mathrm{expr}_{(x,y,z,c)})\f$. **/ CImg<T>& max(const char *const expression) { return max((+*this)._fill(expression,true,1,0,0,"max",this)); } //! Pointwise max operator between an image and an expression \newinstance. CImg<Tfloat> get_max(const char *const expression) const { return CImg<Tfloat>(*this,false).max(expression); } //! Return a reference to the minimum pixel value. /** **/ T& min() { if (is_empty()) throw CImgInstanceException(_cimg_instance "min(): Empty instance.", cimg_instance); T *ptr_min = _data; T min_value = *ptr_min; cimg_for(*this,ptrs,T) if (*ptrs<min_value) min_value = *(ptr_min=ptrs); return *ptr_min; } //! Return a reference to the minimum pixel value \const. const T& min() const { if (is_empty()) throw CImgInstanceException(_cimg_instance "min(): Empty instance.", cimg_instance); const T *ptr_min = _data; T min_value = *ptr_min; cimg_for(*this,ptrs,T) if (*ptrs<min_value) min_value = *(ptr_min=ptrs); return *ptr_min; } //! Return a reference to the maximum pixel value. /** **/ T& max() { if (is_empty()) throw CImgInstanceException(_cimg_instance "max(): Empty instance.", cimg_instance); T *ptr_max = _data; T max_value = *ptr_max; cimg_for(*this,ptrs,T) if (*ptrs>max_value) max_value = *(ptr_max=ptrs); return *ptr_max; } //! Return a reference to the maximum pixel value \const. const T& max() const { if (is_empty()) throw CImgInstanceException(_cimg_instance "max(): Empty instance.", cimg_instance); const T *ptr_max = _data; T max_value = *ptr_max; cimg_for(*this,ptrs,T) if (*ptrs>max_value) max_value = *(ptr_max=ptrs); return *ptr_max; } //! Return a reference to the minimum pixel value as well as the maximum pixel value. /** \param[out] max_val Maximum pixel value. **/ template<typename t> T& min_max(t& max_val) { if (is_empty()) throw CImgInstanceException(_cimg_instance "min_max(): Empty instance.", cimg_instance); T *ptr_min = _data; T min_value = *ptr_min, max_value = min_value; cimg_for(*this,ptrs,T) { const T val = *ptrs; if (val<min_value) { min_value = val; ptr_min = ptrs; } if (val>max_value) max_value = val; } max_val = (t)max_value; return *ptr_min; } //! Return a reference to the minimum pixel value as well as the maximum pixel value \const. template<typename t> const T& min_max(t& max_val) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "min_max(): Empty instance.", cimg_instance); const T *ptr_min = _data; T min_value = *ptr_min, max_value = min_value; cimg_for(*this,ptrs,T) { const T val = *ptrs; if (val<min_value) { min_value = val; ptr_min = ptrs; } if (val>max_value) max_value = val; } max_val = (t)max_value; return *ptr_min; } //! Return a reference to the maximum pixel value as well as the minimum pixel value. /** \param[out] min_val Minimum pixel value. **/ template<typename t> T& max_min(t& min_val) { if (is_empty()) throw CImgInstanceException(_cimg_instance "max_min(): Empty instance.", cimg_instance); T *ptr_max = _data; T max_value = *ptr_max, min_value = max_value; cimg_for(*this,ptrs,T) { const T val = *ptrs; if (val>max_value) { max_value = val; ptr_max = ptrs; } if (val<min_value) min_value = val; } min_val = (t)min_value; return *ptr_max; } //! Return a reference to the maximum pixel value as well as the minimum pixel value \const. template<typename t> const T& max_min(t& min_val) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "max_min(): Empty instance.", cimg_instance); const T *ptr_max = _data; T max_value = *ptr_max, min_value = max_value; cimg_for(*this,ptrs,T) { const T val = *ptrs; if (val>max_value) { max_value = val; ptr_max = ptrs; } if (val<min_value) min_value = val; } min_val = (t)min_value; return *ptr_max; } //! Return the kth smallest pixel value. /** \param k Rank of the search smallest element. **/ T kth_smallest(const ulongT k) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "kth_smallest(): Empty instance.", cimg_instance); CImg<T> arr(*this,false); ulongT l = 0, ir = size() - 1; for ( ; ; ) { if (ir<=l + 1) { if (ir==l + 1 && arr[ir]<arr[l]) cimg::swap(arr[l],arr[ir]); return arr[k]; } else { const ulongT mid = (l + ir)>>1; cimg::swap(arr[mid],arr[l + 1]); if (arr[l]>arr[ir]) cimg::swap(arr[l],arr[ir]); if (arr[l + 1]>arr[ir]) cimg::swap(arr[l + 1],arr[ir]); if (arr[l]>arr[l + 1]) cimg::swap(arr[l],arr[l + 1]); ulongT i = l + 1, j = ir; const T pivot = arr[l + 1]; for ( ; ; ) { do ++i; while (arr[i]<pivot); do --j; while (arr[j]>pivot); if (j<i) break; cimg::swap(arr[i],arr[j]); } arr[l + 1] = arr[j]; arr[j] = pivot; if (j>=k) ir = j - 1; if (j<=k) l = i; } } } //! Return the median pixel value. /** **/ T median() const { if (is_empty()) throw CImgInstanceException(_cimg_instance "median(): Empty instance.", cimg_instance); const ulongT s = size(); switch (s) { case 1 : return _data[0]; case 2 : return cimg::median(_data[0],_data[1]); case 3 : return cimg::median(_data[0],_data[1],_data[2]); case 5 : return cimg::median(_data[0],_data[1],_data[2],_data[3],_data[4]); case 7 : return cimg::median(_data[0],_data[1],_data[2],_data[3],_data[4],_data[5],_data[6]); case 9 : return cimg::median(_data[0],_data[1],_data[2],_data[3],_data[4],_data[5],_data[6],_data[7],_data[8]); case 13 : return cimg::median(_data[0],_data[1],_data[2],_data[3],_data[4],_data[5],_data[6],_data[7],_data[8], _data[9],_data[10],_data[11],_data[12]); } const T res = kth_smallest(s>>1); return (s%2)?res:(T)((res + kth_smallest((s>>1) - 1))/2); } //! Return the product of all the pixel values. /** **/ double product() const { if (is_empty()) return 0; double res = 1; cimg_for(*this,ptrs,T) res*=(double)*ptrs; return res; } //! Return the sum of all the pixel values. /** **/ double sum() const { double res = 0; cimg_for(*this,ptrs,T) res+=(double)*ptrs; return res; } //! Return the average pixel value. /** **/ double mean() const { double res = 0; cimg_for(*this,ptrs,T) res+=(double)*ptrs; return res/size(); } //! Return the variance of the pixel values. /** \param variance_method Method used to estimate the variance. Can be: - \c 0: Second moment, computed as \f$1/N \sum\limits_{k=1}^{N} (x_k - \bar x)^2 = 1/N \left( \sum\limits_{k=1}^N x_k^2 - \left( \sum\limits_{k=1}^N x_k \right)^2 / N \right)\f$ with \f$ \bar x = 1/N \sum\limits_{k=1}^N x_k \f$. - \c 1: Best unbiased estimator, computed as \f$\frac{1}{N - 1} \sum\limits_{k=1}^{N} (x_k - \bar x)^2 \f$. - \c 2: Least median of squares. - \c 3: Least trimmed of squares. **/ double variance(const unsigned int variance_method=1) const { double foo; return variance_mean(variance_method,foo); } //! Return the variance as well as the average of the pixel values. /** \param variance_method Method used to estimate the variance (see variance(const unsigned int) const). \param[out] mean Average pixel value. **/ template<typename t> double variance_mean(const unsigned int variance_method, t& mean) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "variance_mean(): Empty instance.", cimg_instance); double variance = 0, average = 0; const ulongT siz = size(); switch (variance_method) { case 0 : { // Least mean square (standard definition) double S = 0, S2 = 0; cimg_for(*this,ptrs,T) { const double val = (double)*ptrs; S+=val; S2+=val*val; } variance = (S2 - S*S/siz)/siz; average = S; } break; case 1 : { // Least mean square (robust definition) double S = 0, S2 = 0; cimg_for(*this,ptrs,T) { const double val = (double)*ptrs; S+=val; S2+=val*val; } variance = siz>1?(S2 - S*S/siz)/(siz - 1):0; average = S; } break; case 2 : { // Least Median of Squares (MAD) CImg<Tfloat> buf(*this,false); buf.sort(); const ulongT siz2 = siz>>1; const double med_i = (double)buf[siz2]; cimg_for(buf,ptrs,Tfloat) { const double val = (double)*ptrs; *ptrs = (Tfloat)cimg::abs(val - med_i); average+=val; } buf.sort(); const double sig = (double)(1.4828*buf[siz2]); variance = sig*sig; } break; default : { // Least trimmed of Squares CImg<Tfloat> buf(*this,false); const ulongT siz2 = siz>>1; cimg_for(buf,ptrs,Tfloat) { const double val = (double)*ptrs; (*ptrs)=(Tfloat)((*ptrs)*val); average+=val; } buf.sort(); double a = 0; const Tfloat *ptrs = buf._data; for (ulongT j = 0; j<siz2; ++j) a+=(double)*(ptrs++); const double sig = (double)(2.6477*std::sqrt(a/siz2)); variance = sig*sig; } } mean = (t)(average/siz); return variance>0?variance:0; } //! Return estimated variance of the noise. /** \param variance_method Method used to compute the variance (see variance(const unsigned int) const). \note Because of structures such as edges in images it is recommanded to use a robust variance estimation. The variance of the noise is estimated by computing the variance of the Laplacian \f$(\Delta I)^2 \f$ scaled by a factor \f$c\f$ insuring \f$ c E[(\Delta I)^2]= \sigma^2\f$ where \f$\sigma\f$ is the noise variance. **/ double variance_noise(const unsigned int variance_method=2) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "variance_noise(): Empty instance.", cimg_instance); const ulongT siz = size(); if (!siz || !_data) return 0; if (variance_method>1) { // Compute a scaled version of the Laplacian CImg<Tdouble> tmp(*this,false); if (_depth==1) { const double cste = 1./std::sqrt(20.); // Depends on how the Laplacian is computed cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height>=(cimg_openmp_sizefactor)*262144 && _spectrum>=2)) cimg_forC(*this,c) { CImg_3x3(I,T); cimg_for3x3(*this,x,y,0,c,I,T) { tmp(x,y,c) = cste*((double)Inc + (double)Ipc + (double)Icn + (double)Icp - 4*(double)Icc); } } } else { const double cste = 1./std::sqrt(42.); // Depends on how the Laplacian is computed cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height*_depth>=(cimg_openmp_sizefactor)*262144 && _spectrum>=2)) cimg_forC(*this,c) { CImg_3x3x3(I,T); cimg_for3x3x3(*this,x,y,z,c,I,T) { tmp(x,y,z,c) = cste*( (double)Incc + (double)Ipcc + (double)Icnc + (double)Icpc + (double)Iccn + (double)Iccp - 6*(double)Iccc); } } } return tmp.variance(variance_method); } // Version that doesn't need intermediate images. double variance = 0, S = 0, S2 = 0; if (_depth==1) { const double cste = 1./std::sqrt(20.); CImg_3x3(I,T); cimg_forC(*this,c) cimg_for3x3(*this,x,y,0,c,I,T) { const double val = cste*((double)Inc + (double)Ipc + (double)Icn + (double)Icp - 4*(double)Icc); S+=val; S2+=val*val; } } else { const double cste = 1./std::sqrt(42.); CImg_3x3x3(I,T); cimg_forC(*this,c) cimg_for3x3x3(*this,x,y,z,c,I,T) { const double val = cste * ((double)Incc + (double)Ipcc + (double)Icnc + (double)Icpc + (double)Iccn + (double)Iccp - 6*(double)Iccc); S+=val; S2+=val*val; } } if (variance_method) variance = siz>1?(S2 - S*S/siz)/(siz - 1):0; else variance = (S2 - S*S/siz)/siz; return variance>0?variance:0; } //! Compute the MSE (Mean-Squared Error) between two images. /** \param img Image used as the second argument of the MSE operator. **/ template<typename t> double MSE(const CImg<t>& img) const { if (img.size()!=size()) throw CImgArgumentException(_cimg_instance "MSE(): Instance and specified image (%u,%u,%u,%u,%p) have different dimensions.", cimg_instance, img._width,img._height,img._depth,img._spectrum,img._data); double vMSE = 0; const t* ptr2 = img._data; cimg_for(*this,ptr1,T) { const double diff = (double)*ptr1 - (double)*(ptr2++); vMSE+=diff*diff; } const ulongT siz = img.size(); if (siz) vMSE/=siz; return vMSE; } //! Compute the PSNR (Peak Signal-to-Noise Ratio) between two images. /** \param img Image used as the second argument of the PSNR operator. \param max_value Maximum theoretical value of the signal. **/ template<typename t> double PSNR(const CImg<t>& img, const double max_value=255) const { const double vMSE = (double)std::sqrt(MSE(img)); return (vMSE!=0)?(double)(20*std::log10(max_value/vMSE)):(double)(cimg::type<double>::max()); } //! Evaluate math formula. /** \param expression Math formula, as a C-string. \param x Value of the pre-defined variable \c x. \param y Value of the pre-defined variable \c y. \param z Value of the pre-defined variable \c z. \param c Value of the pre-defined variable \c c. \param list_inputs A list of input images attached to the specified math formula. \param[out] list_outputs A pointer to a list of output images attached to the specified math formula. **/ double eval(const char *const expression, const double x=0, const double y=0, const double z=0, const double c=0, const CImgList<T> *const list_inputs=0, CImgList<T> *const list_outputs=0) { return _eval(this,expression,x,y,z,c,list_inputs,list_outputs); } //! Evaluate math formula \const. double eval(const char *const expression, const double x=0, const double y=0, const double z=0, const double c=0, const CImgList<T> *const list_inputs=0, CImgList<T> *const list_outputs=0) const { return _eval(0,expression,x,y,z,c,list_inputs,list_outputs); } double _eval(CImg<T> *const img_output, const char *const expression, const double x, const double y, const double z, const double c, const CImgList<T> *const list_inputs, CImgList<T> *const list_outputs) const { if (!expression || !*expression) return 0; if (!expression[1]) switch (*expression) { // Single-char optimization case 'w' : return (double)_width; case 'h' : return (double)_height; case 'd' : return (double)_depth; case 's' : return (double)_spectrum; case 'r' : return (double)_is_shared; } _cimg_math_parser mp(expression + (*expression=='>' || *expression=='<' || *expression=='*' || *expression==':'),"eval", *this,img_output,list_inputs,list_outputs,false); const double val = mp(x,y,z,c); mp.end(); return val; } //! Evaluate math formula. /** \param[out] output Contains values of output vector returned by the evaluated expression (or is empty if the returned type is scalar). \param expression Math formula, as a C-string. \param x Value of the pre-defined variable \c x. \param y Value of the pre-defined variable \c y. \param z Value of the pre-defined variable \c z. \param c Value of the pre-defined variable \c c. \param list_inputs A list of input images attached to the specified math formula. \param[out] list_outputs A pointer to a list of output images attached to the specified math formula. **/ template<typename t> void eval(CImg<t> &output, const char *const expression, const double x=0, const double y=0, const double z=0, const double c=0, const CImgList<T> *const list_inputs=0, CImgList<T> *const list_outputs=0) { _eval(output,this,expression,x,y,z,c,list_inputs,list_outputs); } //! Evaluate math formula \const. template<typename t> void eval(CImg<t>& output, const char *const expression, const double x=0, const double y=0, const double z=0, const double c=0, const CImgList<T> *const list_inputs=0, CImgList<T> *const list_outputs=0) const { _eval(output,0,expression,x,y,z,c,list_inputs,list_outputs); } template<typename t> void _eval(CImg<t>& output, CImg<T> *const img_output, const char *const expression, const double x, const double y, const double z, const double c, const CImgList<T> *const list_inputs, CImgList<T> *const list_outputs) const { if (!expression || !*expression) { output.assign(1); *output = 0; } if (!expression[1]) switch (*expression) { // Single-char optimization case 'w' : output.assign(1); *output = (t)_width; break; case 'h' : output.assign(1); *output = (t)_height; break; case 'd' : output.assign(1); *output = (t)_depth; break; case 's' : output.assign(1); *output = (t)_spectrum; break; case 'r' : output.assign(1); *output = (t)_is_shared; break; } _cimg_math_parser mp(expression + (*expression=='>' || *expression=='<' || *expression=='*' || *expression==':'),"eval", *this,img_output,list_inputs,list_outputs,false); output.assign(1,std::max(1U,mp.result_dim)); mp(x,y,z,c,output._data); mp.end(); } //! Evaluate math formula on a set of variables. /** \param expression Math formula, as a C-string. \param xyzc Set of values (x,y,z,c) used for the evaluation. \param list_inputs A list of input images attached to the specified math formula. \param[out] list_outputs A pointer to a list of output images attached to the specified math formula. **/ template<typename t> CImg<doubleT> eval(const char *const expression, const CImg<t>& xyzc, const CImgList<T> *const list_inputs=0, CImgList<T> *const list_outputs=0) { return _eval(this,expression,xyzc,list_inputs,list_outputs); } //! Evaluate math formula on a set of variables \const. template<typename t> CImg<doubleT> eval(const char *const expression, const CImg<t>& xyzc, const CImgList<T> *const list_inputs=0, CImgList<T> *const list_outputs=0) const { return _eval(0,expression,xyzc,list_inputs,list_outputs); } template<typename t> CImg<doubleT> _eval(CImg<T> *const output, const char *const expression, const CImg<t>& xyzc, const CImgList<T> *const list_inputs=0, CImgList<T> *const list_outputs=0) const { CImg<doubleT> res(1,xyzc.size()/4); if (!expression || !*expression) return res.fill(0); _cimg_math_parser mp(expression,"eval",*this,output,list_inputs,list_outputs,false); #if cimg_use_openmp!=0 cimg_pragma_openmp(parallel if (res._height>=512)) { _cimg_math_parser _mp = omp_get_thread_num()?mp:_cimg_math_parser(), &lmp = omp_get_thread_num()?_mp:mp; cimg_pragma_openmp(for) for (int i = 0; i<res.height(); ++i) { const unsigned int i4 = 4*i; const double x = (double)xyzc[i4], y = (double)xyzc[i4 + 1], z = (double)xyzc[i4 + 2], c = (double)xyzc[i4 + 3]; res[i] = lmp(x,y,z,c); } } #else const t *ps = xyzc._data; cimg_for(res,pd,double) { const double x = (double)*(ps++), y = (double)*(ps++), z = (double)*(ps++), c = (double)*(ps++); *pd = mp(x,y,z,c); } #endif mp.end(); return res; } //! Compute statistics vector from the pixel values. /* \param variance_method Method used to compute the variance (see variance(const unsigned int) const). \return Statistics vector as <tt>[min, max, mean, variance, xmin, ymin, zmin, cmin, xmax, ymax, zmax, cmax, sum, product]</tt>. **/ CImg<Tdouble> get_stats(const unsigned int variance_method=1) const { if (is_empty()) return CImg<doubleT>(); const ulongT siz = size(); const longT off_end = (longT)siz; double S = 0, S2 = 0, P = 1; longT offm = 0, offM = 0; T m = *_data, M = m; cimg_pragma_openmp(parallel reduction(+:S,S2) reduction(*:P) cimg_openmp_if_size(siz,131072)) { longT loffm = 0, loffM = 0; T lm = *_data, lM = lm; cimg_pragma_openmp(for) for (longT off = 0; off<off_end; ++off) { const T val = _data[off]; const double _val = (double)val; if (val<lm) { lm = val; loffm = off; } if (val>lM) { lM = val; loffM = off; } S+=_val; S2+=_val*_val; P*=_val; } cimg_pragma_openmp(critical(get_stats)) { if (lm<m || (lm==m && loffm<offm)) { m = lm; offm = loffm; } if (lM>M || (lM==M && loffM<offM)) { M = lM; offM = loffM; } } } const double mean_value = S/siz, _variance_value = variance_method==0?(S2 - S*S/siz)/siz: (variance_method==1?(siz>1?(S2 - S*S/siz)/(siz - 1):0): variance(variance_method)), variance_value = _variance_value>0?_variance_value:0; int xm = 0, ym = 0, zm = 0, cm = 0, xM = 0, yM = 0, zM = 0, cM = 0; contains(_data[offm],xm,ym,zm,cm); contains(_data[offM],xM,yM,zM,cM); return CImg<Tdouble>(1,14).fill((double)m,(double)M,mean_value,variance_value, (double)xm,(double)ym,(double)zm,(double)cm, (double)xM,(double)yM,(double)zM,(double)cM, S,P); } //! Compute statistics vector from the pixel values \inplace. CImg<T>& stats(const unsigned int variance_method=1) { return get_stats(variance_method).move_to(*this); } //@} //------------------------------------- // //! \name Vector / Matrix Operations //@{ //------------------------------------- //! Compute norm of the image, viewed as a matrix. /** \param magnitude_type Norm type. Can be: - \c -1: Linf-norm - \c 0: L0-norm - \c 1: L1-norm - \c 2: L2-norm **/ double magnitude(const int magnitude_type=2) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "magnitude(): Empty instance.", cimg_instance); double res = 0; switch (magnitude_type) { case -1 : { cimg_for(*this,ptrs,T) { const double val = (double)cimg::abs(*ptrs); if (val>res) res = val; } } break; case 1 : { cimg_for(*this,ptrs,T) res+=(double)cimg::abs(*ptrs); } break; default : { cimg_for(*this,ptrs,T) res+=(double)cimg::sqr(*ptrs); res = (double)std::sqrt(res); } } return res; } //! Compute the trace of the image, viewed as a matrix. /** **/ double trace() const { if (is_empty()) throw CImgInstanceException(_cimg_instance "trace(): Empty instance.", cimg_instance); double res = 0; cimg_forX(*this,k) res+=(double)(*this)(k,k); return res; } //! Compute the determinant of the image, viewed as a matrix. /** **/ double det() const { if (is_empty() || _width!=_height || _depth!=1 || _spectrum!=1) throw CImgInstanceException(_cimg_instance "det(): Instance is not a square matrix.", cimg_instance); switch (_width) { case 1 : return (double)((*this)(0,0)); case 2 : return (double)((*this)(0,0))*(double)((*this)(1,1)) - (double)((*this)(0,1))*(double)((*this)(1,0)); case 3 : { const double a = (double)_data[0], d = (double)_data[1], g = (double)_data[2], b = (double)_data[3], e = (double)_data[4], h = (double)_data[5], c = (double)_data[6], f = (double)_data[7], i = (double)_data[8]; return i*a*e - a*h*f - i*b*d + b*g*f + c*d*h - c*g*e; } default : { CImg<Tfloat> lu(*this,false); CImg<uintT> indx; bool d; lu._LU(indx,d); double res = d?(double)1:(double)-1; cimg_forX(lu,i) res*=lu(i,i); return res; } } } //! Compute the dot product between instance and argument, viewed as matrices. /** \param img Image used as a second argument of the dot product. **/ template<typename t> double dot(const CImg<t>& img) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "dot(): Empty instance.", cimg_instance); if (!img) throw CImgArgumentException(_cimg_instance "dot(): Empty specified image.", cimg_instance); const ulongT nb = std::min(size(),img.size()); double res = 0; for (ulongT off = 0; off<nb; ++off) res+=(double)_data[off]*(double)img[off]; return res; } //! Get vector-valued pixel located at specified position. /** \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. **/ CImg<T> get_vector_at(const unsigned int x, const unsigned int y=0, const unsigned int z=0) const { CImg<T> res; if (res._height!=_spectrum) res.assign(1,_spectrum); const ulongT whd = (ulongT)_width*_height*_depth; const T *ptrs = data(x,y,z); T *ptrd = res._data; cimg_forC(*this,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return res; } //! Get (square) matrix-valued pixel located at specified position. /** \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \note - The spectrum() of the image must be a square. **/ CImg<T> get_matrix_at(const unsigned int x=0, const unsigned int y=0, const unsigned int z=0) const { const int n = (int)cimg::round(std::sqrt((double)_spectrum)); const T *ptrs = data(x,y,z,0); const ulongT whd = (ulongT)_width*_height*_depth; CImg<T> res(n,n); T *ptrd = res._data; cimg_forC(*this,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return res; } //! Get tensor-valued pixel located at specified position. /** \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. **/ CImg<T> get_tensor_at(const unsigned int x, const unsigned int y=0, const unsigned int z=0) const { const T *ptrs = data(x,y,z,0); const ulongT whd = (ulongT)_width*_height*_depth; if (_spectrum==6) return tensor(*ptrs,*(ptrs + whd),*(ptrs + 2*whd),*(ptrs + 3*whd),*(ptrs + 4*whd),*(ptrs + 5*whd)); if (_spectrum==3) return tensor(*ptrs,*(ptrs + whd),*(ptrs + 2*whd)); return tensor(*ptrs); } //! Set vector-valued pixel at specified position. /** \param vec Vector to put on the instance image. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. **/ template<typename t> CImg<T>& set_vector_at(const CImg<t>& vec, const unsigned int x, const unsigned int y=0, const unsigned int z=0) { if (x<_width && y<_height && z<_depth) { const t *ptrs = vec._data; const ulongT whd = (ulongT)_width*_height*_depth; T *ptrd = data(x,y,z); for (unsigned int k = std::min((unsigned int)vec.size(),_spectrum); k; --k) { *ptrd = (T)*(ptrs++); ptrd+=whd; } } return *this; } //! Set (square) matrix-valued pixel at specified position. /** \param mat Matrix to put on the instance image. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. **/ template<typename t> CImg<T>& set_matrix_at(const CImg<t>& mat, const unsigned int x=0, const unsigned int y=0, const unsigned int z=0) { return set_vector_at(mat,x,y,z); } //! Set tensor-valued pixel at specified position. /** \param ten Tensor to put on the instance image. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. **/ template<typename t> CImg<T>& set_tensor_at(const CImg<t>& ten, const unsigned int x=0, const unsigned int y=0, const unsigned int z=0) { T *ptrd = data(x,y,z,0); const ulongT siz = (ulongT)_width*_height*_depth; if (ten._height==2) { *ptrd = (T)ten[0]; ptrd+=siz; *ptrd = (T)ten[1]; ptrd+=siz; *ptrd = (T)ten[3]; } else { *ptrd = (T)ten[0]; ptrd+=siz; *ptrd = (T)ten[1]; ptrd+=siz; *ptrd = (T)ten[2]; ptrd+=siz; *ptrd = (T)ten[4]; ptrd+=siz; *ptrd = (T)ten[5]; ptrd+=siz; *ptrd = (T)ten[8]; } return *this; } //! Unroll pixel values along axis \c y. /** \note Equivalent to \code unroll('y'); \endcode. **/ CImg<T>& vector() { return unroll('y'); } //! Unroll pixel values along axis \c y \newinstance. CImg<T> get_vector() const { return get_unroll('y'); } //! Resize image to become a scalar square matrix. /** **/ CImg<T>& matrix() { const ulongT siz = size(); switch (siz) { case 1 : break; case 4 : _width = _height = 2; break; case 9 : _width = _height = 3; break; case 16 : _width = _height = 4; break; case 25 : _width = _height = 5; break; case 36 : _width = _height = 6; break; case 49 : _width = _height = 7; break; case 64 : _width = _height = 8; break; case 81 : _width = _height = 9; break; case 100 : _width = _height = 10; break; default : { ulongT i = 11, i2 = i*i; while (i2<siz) { i2+=2*i + 1; ++i; } if (i2==siz) _width = _height = i; else throw CImgInstanceException(_cimg_instance "matrix(): Invalid instance size %u (should be a square integer).", cimg_instance, siz); } } return *this; } //! Resize image to become a scalar square matrix \newinstance. CImg<T> get_matrix() const { return (+*this).matrix(); } //! Resize image to become a symmetric tensor. /** **/ CImg<T>& tensor() { return get_tensor().move_to(*this); } //! Resize image to become a symmetric tensor \newinstance. CImg<T> get_tensor() const { CImg<T> res; const ulongT siz = size(); switch (siz) { case 1 : break; case 3 : res.assign(2,2); res(0,0) = (*this)(0); res(1,0) = res(0,1) = (*this)(1); res(1,1) = (*this)(2); break; case 6 : res.assign(3,3); res(0,0) = (*this)(0); res(1,0) = res(0,1) = (*this)(1); res(2,0) = res(0,2) = (*this)(2); res(1,1) = (*this)(3); res(2,1) = res(1,2) = (*this)(4); res(2,2) = (*this)(5); break; default : throw CImgInstanceException(_cimg_instance "tensor(): Invalid instance size (does not define a 1x1, 2x2 or 3x3 tensor).", cimg_instance); } return res; } //! Resize image to become a diagonal matrix. /** \note Transform the image as a diagonal matrix so that each of its initial value becomes a diagonal coefficient. **/ CImg<T>& diagonal() { return get_diagonal().move_to(*this); } //! Resize image to become a diagonal matrix \newinstance. CImg<T> get_diagonal() const { if (is_empty()) return *this; const unsigned int siz = (unsigned int)size(); CImg<T> res(siz,siz,1,1,0); cimg_foroff(*this,off) res((unsigned int)off,(unsigned int)off) = (*this)[off]; return res; } //! Replace the image by an identity matrix. /** \note If the instance image is not square, it is resized to a square matrix using its maximum dimension as a reference. **/ CImg<T>& identity_matrix() { return identity_matrix(std::max(_width,_height)).move_to(*this); } //! Replace the image by an identity matrix \newinstance. CImg<T> get_identity_matrix() const { return identity_matrix(std::max(_width,_height)); } //! Fill image with a linear sequence of values. /** \param a0 Starting value of the sequence. \param a1 Ending value of the sequence. **/ CImg<T>& sequence(const T& a0, const T& a1) { if (is_empty()) return *this; const ulongT siz = size() - 1; T* ptr = _data; if (siz) { const double delta = (double)a1 - (double)a0; cimg_foroff(*this,l) *(ptr++) = (T)(a0 + delta*l/siz); } else *ptr = a0; return *this; } //! Fill image with a linear sequence of values \newinstance. CImg<T> get_sequence(const T& a0, const T& a1) const { return (+*this).sequence(a0,a1); } //! Transpose the image, viewed as a matrix. /** \note Equivalent to \code permute_axes("yxzc"); \endcode. **/ CImg<T>& transpose() { if (_width==1) { _width = _height; _height = 1; return *this; } if (_height==1) { _height = _width; _width = 1; return *this; } if (_width==_height) { cimg_forYZC(*this,y,z,c) for (int x = y; x<width(); ++x) cimg::swap((*this)(x,y,z,c),(*this)(y,x,z,c)); return *this; } return get_transpose().move_to(*this); } //! Transpose the image, viewed as a matrix \newinstance. CImg<T> get_transpose() const { return get_permute_axes("yxzc"); } //! Compute the cross product between two \c 1x3 images, viewed as 3D vectors. /** \param img Image used as the second argument of the cross product. \note The first argument of the cross product is \c *this. **/ template<typename t> CImg<T>& cross(const CImg<t>& img) { if (_width!=1 || _height<3 || img._width!=1 || img._height<3) throw CImgInstanceException(_cimg_instance "cross(): Instance and/or specified image (%u,%u,%u,%u,%p) are not 3D vectors.", cimg_instance, img._width,img._height,img._depth,img._spectrum,img._data); const T x = (*this)[0], y = (*this)[1], z = (*this)[2]; (*this)[0] = (T)(y*img[2] - z*img[1]); (*this)[1] = (T)(z*img[0] - x*img[2]); (*this)[2] = (T)(x*img[1] - y*img[0]); return *this; } //! Compute the cross product between two \c 1x3 images, viewed as 3D vectors \newinstance. template<typename t> CImg<_cimg_Tt> get_cross(const CImg<t>& img) const { return CImg<_cimg_Tt>(*this).cross(img); } //! Invert the instance image, viewed as a matrix. /** \param use_LU Choose the inverting algorithm. Can be: - \c true: LU-based matrix inversion. - \c false: SVD-based matrix inversion. **/ CImg<T>& invert(const bool use_LU=true) { if (_width!=_height || _depth!=1 || _spectrum!=1) throw CImgInstanceException(_cimg_instance "invert(): Instance is not a square matrix.", cimg_instance); const double dete = _width>3?-1.:det(); if (dete!=0. && _width==2) { const double a = _data[0], c = _data[1], b = _data[2], d = _data[3]; _data[0] = (T)(d/dete); _data[1] = (T)(-c/dete); _data[2] = (T)(-b/dete); _data[3] = (T)(a/dete); } else if (dete!=0. && _width==3) { const double a = _data[0], d = _data[1], g = _data[2], b = _data[3], e = _data[4], h = _data[5], c = _data[6], f = _data[7], i = _data[8]; _data[0] = (T)((i*e - f*h)/dete), _data[1] = (T)((g*f - i*d)/dete), _data[2] = (T)((d*h - g*e)/dete); _data[3] = (T)((h*c - i*b)/dete), _data[4] = (T)((i*a - c*g)/dete), _data[5] = (T)((g*b - a*h)/dete); _data[6] = (T)((b*f - e*c)/dete), _data[7] = (T)((d*c - a*f)/dete), _data[8] = (T)((a*e - d*b)/dete); } else { #ifdef cimg_use_lapack int INFO = (int)use_LU, N = _width, LWORK = 4*N, *const IPIV = new int[N]; Tfloat *const lapA = new Tfloat[N*N], *const WORK = new Tfloat[LWORK]; cimg_forXY(*this,k,l) lapA[k*N + l] = (Tfloat)((*this)(k,l)); cimg::getrf(N,lapA,IPIV,INFO); if (INFO) cimg::warn(_cimg_instance "invert(): LAPACK function dgetrf_() returned error code %d.", cimg_instance, INFO); else { cimg::getri(N,lapA,IPIV,WORK,LWORK,INFO); if (INFO) cimg::warn(_cimg_instance "invert(): LAPACK function dgetri_() returned error code %d.", cimg_instance, INFO); } if (!INFO) cimg_forXY(*this,k,l) (*this)(k,l) = (T)(lapA[k*N + l]); else fill(0); delete[] IPIV; delete[] lapA; delete[] WORK; #else if (use_LU) { // LU-based inverse computation CImg<Tfloat> A(*this,false), indx, col(1,_width); bool d; A._LU(indx,d); cimg_forX(*this,j) { col.fill(0); col(j) = 1; col._solve(A,indx); cimg_forX(*this,i) (*this)(j,i) = (T)col(i); } } else { // SVD-based inverse computation CImg<Tfloat> U(_width,_width), S(1,_width), V(_width,_width); SVD(U,S,V,false); U.transpose(); cimg_forY(S,k) if (S[k]!=0) S[k]=1/S[k]; S.diagonal(); *this = V*S*U; } #endif } return *this; } //! Invert the instance image, viewed as a matrix \newinstance. CImg<Tfloat> get_invert(const bool use_LU=true) const { return CImg<Tfloat>(*this,false).invert(use_LU); } //! Compute the Moore-Penrose pseudo-inverse of the instance image, viewed as a matrix. /** **/ CImg<T>& pseudoinvert() { return get_pseudoinvert().move_to(*this); } //! Compute the Moore-Penrose pseudo-inverse of the instance image, viewed as a matrix \newinstance. CImg<Tfloat> get_pseudoinvert() const { CImg<Tfloat> U, S, V; SVD(U,S,V); const Tfloat tolerance = (sizeof(Tfloat)<=4?5.96e-8f:1.11e-16f)*std::max(_width,_height)*S.max(); cimg_forX(V,x) { const Tfloat s = S(x), invs = s>tolerance?1/s:0; cimg_forY(V,y) V(x,y)*=invs; } return V*U.transpose(); } //! Solve a system of linear equations. /** \param A Matrix of the linear system. \note Solve \c AX = B where \c B=*this. **/ template<typename t> CImg<T>& solve(const CImg<t>& A) { if (_depth!=1 || _spectrum!=1 || _height!=A._height || A._depth!=1 || A._spectrum!=1) throw CImgArgumentException(_cimg_instance "solve(): Instance and specified matrix (%u,%u,%u,%u,%p) have " "incompatible dimensions.", cimg_instance, A._width,A._height,A._depth,A._spectrum,A._data); typedef _cimg_Ttfloat Ttfloat; if (A.size()==1) return (*this)/=A[0]; if (A._width==2 && A._height==2 && _height==2) { const double a = (double)A[0], b = (double)A[1], c = (double)A[2], d = (double)A[3], fa = std::fabs(a), fb = std::fabs(b), fc = std::fabs(c), fd = std::fabs(d), det = a*d - b*c, fM = cimg::max(fa,fb,fc,fd); if (fM==fa) cimg_forX(*this,k) { const double u = (double)(*this)(k,0), v = (double)(*this)(k,1), y = (a*v - c*u)/det; (*this)(k,0) = (T)((u - b*y)/a); (*this)(k,1) = (T)y; } else if (fM==fc) cimg_forX(*this,k) { const double u = (double)(*this)(k,0), v = (double)(*this)(k,1), y = (a*v - c*u)/det; (*this)(k,0) = (T)((v - d*y)/c); (*this)(k,1) = (T)y; } else if (fM==fb) cimg_forX(*this,k) { const double u = (double)(*this)(k,0), v = (double)(*this)(k,1), x = (d*u - b*v)/det; (*this)(k,0) = (T)x; (*this)(k,1) = (T)((u - a*x)/b); } else cimg_forX(*this,k) { const double u = (double)(*this)(k,0), v = (double)(*this)(k,1), x = (d*u - b*v)/det; (*this)(k,0) = (T)x; (*this)(k,1) = (T)((v - c*x)/d); } return *this; } if (_width!=1) { // Process column-by-column CImg<T> res(_width,A._width); cimg_forX(*this,i) res.draw_image(i,get_column(i).solve(A)); return res.move_to(*this); } if (A._width==A._height) { // Square linear system #ifdef cimg_use_lapack char TRANS = 'N'; int INFO, N = _height, LWORK = 4*N, *const IPIV = new int[N]; Ttfloat *const lapA = new Ttfloat[N*N], *const lapB = new Ttfloat[N], *const WORK = new Ttfloat[LWORK]; cimg_forXY(A,k,l) lapA[k*N + l] = (Ttfloat)(A(k,l)); cimg_forY(*this,i) lapB[i] = (Ttfloat)((*this)(i)); cimg::getrf(N,lapA,IPIV,INFO); if (INFO) cimg::warn(_cimg_instance "solve(): LAPACK library function dgetrf_() returned error code %d.", cimg_instance, INFO); if (!INFO) { cimg::getrs(TRANS,N,lapA,IPIV,lapB,INFO); if (INFO) cimg::warn(_cimg_instance "solve(): LAPACK library function dgetrs_() returned error code %d.", cimg_instance, INFO); } if (!INFO) cimg_forY(*this,i) (*this)(i) = (T)(lapB[i]); else fill(0); delete[] IPIV; delete[] lapA; delete[] lapB; delete[] WORK; #else CImg<Ttfloat> lu(A,false); CImg<Ttfloat> indx; bool d; lu._LU(indx,d); _solve(lu,indx); #endif } else { // Least-square solution for non-square systems #ifdef cimg_use_lapack char TRANS = 'N'; int INFO, N = A._width, M = A._height, LWORK = -1, LDA = M, LDB = M, NRHS = _width; Ttfloat WORK_QUERY; Ttfloat * const lapA = new Ttfloat[M*N], * const lapB = new Ttfloat[M*NRHS]; cimg::sgels(TRANS, M, N, NRHS, lapA, LDA, lapB, LDB, &WORK_QUERY, LWORK, INFO); LWORK = (int) WORK_QUERY; Ttfloat *const WORK = new Ttfloat[LWORK]; cimg_forXY(A,k,l) lapA[k*M + l] = (Ttfloat)(A(k,l)); cimg_forXY(*this,k,l) lapB[k*M + l] = (Ttfloat)((*this)(k,l)); cimg::sgels(TRANS, M, N, NRHS, lapA, LDA, lapB, LDB, WORK, LWORK, INFO); if (INFO != 0) cimg::warn(_cimg_instance "solve(): LAPACK library function sgels() returned error code %d.", cimg_instance, INFO); assign(NRHS, N); if (!INFO) cimg_forXY(*this,k,l) (*this)(k,l) = (T)lapB[k*M + l]; else assign(A.get_pseudoinvert()*(*this)); delete[] lapA; delete[] lapB; delete[] WORK; #else assign(A.get_pseudoinvert()*(*this)); #endif } return *this; } //! Solve a system of linear equations \newinstance. template<typename t> CImg<_cimg_Ttfloat> get_solve(const CImg<t>& A) const { typedef _cimg_Ttfloat Ttfloat; return CImg<Ttfloat>(*this,false).solve(A); } template<typename t, typename ti> CImg<T>& _solve(const CImg<t>& A, const CImg<ti>& indx) { typedef _cimg_Ttfloat Ttfloat; const int N = (int)size(); int ii = -1; Ttfloat sum; for (int i = 0; i<N; ++i) { const int ip = (int)indx[i]; sum = (*this)(ip); (*this)(ip) = (*this)(i); if (ii>=0) for (int j = ii; j<=i - 1; ++j) sum-=A(j,i)*(*this)(j); else if (sum!=0) ii = i; (*this)(i) = (T)sum; } for (int i = N - 1; i>=0; --i) { sum = (*this)(i); for (int j = i + 1; j<N; ++j) sum-=A(j,i)*(*this)(j); (*this)(i) = (T)(sum/A(i,i)); } return *this; } //! Solve a tridiagonal system of linear equations. /** \param A Coefficients of the tridiagonal system. A is a tridiagonal matrix A = [ b0,c0,0,...; a1,b1,c1,0,... ; ... ; ...,0,aN,bN ], stored as a 3 columns matrix \note Solve AX=B where \c B=*this, using the Thomas algorithm. **/ template<typename t> CImg<T>& solve_tridiagonal(const CImg<t>& A) { const unsigned int siz = (unsigned int)size(); if (A._width!=3 || A._height!=siz) throw CImgArgumentException(_cimg_instance "solve_tridiagonal(): Instance and tridiagonal matrix " "(%u,%u,%u,%u,%p) have incompatible dimensions.", cimg_instance, A._width,A._height,A._depth,A._spectrum,A._data); typedef _cimg_Ttfloat Ttfloat; const Ttfloat epsilon = 1e-4f; CImg<Ttfloat> B = A.get_column(1), V(*this,false); for (int i = 1; i<(int)siz; ++i) { const Ttfloat m = A(0,i)/(B[i - 1]?B[i - 1]:epsilon); B[i] -= m*A(2,i - 1); V[i] -= m*V[i - 1]; } (*this)[siz - 1] = (T)(V[siz - 1]/(B[siz - 1]?B[siz - 1]:epsilon)); for (int i = (int)siz - 2; i>=0; --i) (*this)[i] = (T)((V[i] - A(2,i)*(*this)[i + 1])/(B[i]?B[i]:epsilon)); return *this; } //! Solve a tridiagonal system of linear equations \newinstance. template<typename t> CImg<_cimg_Ttfloat> get_solve_tridiagonal(const CImg<t>& A) const { return CImg<_cimg_Ttfloat>(*this,false).solve_tridiagonal(A); } //! Compute eigenvalues and eigenvectors of the instance image, viewed as a matrix. /** \param[out] val Vector of the estimated eigenvalues, in decreasing order. \param[out] vec Matrix of the estimated eigenvectors, sorted by columns. **/ template<typename t> const CImg<T>& eigen(CImg<t>& val, CImg<t> &vec) const { if (is_empty()) { val.assign(); vec.assign(); } else { if (_width!=_height || _depth>1 || _spectrum>1) throw CImgInstanceException(_cimg_instance "eigen(): Instance is not a square matrix.", cimg_instance); if (val.size()<(ulongT)_width) val.assign(1,_width); if (vec.size()<(ulongT)_width*_width) vec.assign(_width,_width); switch (_width) { case 1 : { val[0] = (t)(*this)[0]; vec[0] = (t)1; } break; case 2 : { const double a = (*this)[0], b = (*this)[1], c = (*this)[2], d = (*this)[3], e = a + d; double f = e*e - 4*(a*d - b*c); if (f<0) cimg::warn(_cimg_instance "eigen(): Complex eigenvalues found.", cimg_instance); f = std::sqrt(f); const double l1 = 0.5*(e - f), l2 = 0.5*(e + f), b2 = b*b, norm1 = std::sqrt(cimg::sqr(l2 - a) + b2), norm2 = std::sqrt(cimg::sqr(l1 - a) + b2); val[0] = (t)l2; val[1] = (t)l1; if (norm1>0) { vec(0,0) = (t)(b/norm1); vec(0,1) = (t)((l2 - a)/norm1); } else { vec(0,0) = 1; vec(0,1) = 0; } if (norm2>0) { vec(1,0) = (t)(b/norm2); vec(1,1) = (t)((l1 - a)/norm2); } else { vec(1,0) = 1; vec(1,1) = 0; } } break; default : throw CImgInstanceException(_cimg_instance "eigen(): Eigenvalues computation of general matrices is limited " "to 2x2 matrices.", cimg_instance); } } return *this; } //! Compute eigenvalues and eigenvectors of the instance image, viewed as a matrix. /** \return A list of two images <tt>[val; vec]</tt>, whose meaning is similar as in eigen(CImg<t>&,CImg<t>&) const. **/ CImgList<Tfloat> get_eigen() const { CImgList<Tfloat> res(2); eigen(res[0],res[1]); return res; } //! Compute eigenvalues and eigenvectors of the instance image, viewed as a symmetric matrix. /** \param[out] val Vector of the estimated eigenvalues, in decreasing order. \param[out] vec Matrix of the estimated eigenvectors, sorted by columns. **/ template<typename t> const CImg<T>& symmetric_eigen(CImg<t>& val, CImg<t>& vec) const { if (is_empty()) { val.assign(); vec.assign(); return *this; } if (_width!=_height || _depth>1 || _spectrum>1) throw CImgInstanceException(_cimg_instance "eigen(): Instance is not a square matrix.", cimg_instance); val.assign(1,_width); vec.assign(_width,_width); if (_width==1) { val[0] = cimg::abs((*this)[0]); vec[0] = 1; return *this; } if (_width==2) { const double a = (*this)[0], b = (*this)[1], c = (*this)[2], d = (*this)[3], e = a + d, f = std::sqrt(std::max(e*e - 4*(a*d - b*c),0.0)), l1 = 0.5*(e - f), l2 = 0.5*(e + f), n = std::sqrt(cimg::sqr(l2 - a) + b*b); val[0] = (t)l2; val[1] = (t)l1; if (n>0) { vec[0] = (t)(b/n); vec[2] = (t)((l2 - a)/n); } else { vec[0] = 1; vec[2] = 0; } vec[1] = -vec[2]; vec[3] = vec[0]; return *this; } #ifdef cimg_use_lapack char JOB = 'V', UPLO = 'U'; int N = _width, LWORK = 4*N, INFO; Tfloat *const lapA = new Tfloat[N*N], *const lapW = new Tfloat[N], *const WORK = new Tfloat[LWORK]; cimg_forXY(*this,k,l) lapA[k*N + l] = (Tfloat)((*this)(k,l)); cimg::syev(JOB,UPLO,N,lapA,lapW,WORK,LWORK,INFO); if (INFO) cimg::warn(_cimg_instance "symmetric_eigen(): LAPACK library function dsyev_() returned error code %d.", cimg_instance, INFO); if (!INFO) { cimg_forY(val,i) val(i) = (T)lapW[N - 1 -i]; cimg_forXY(vec,k,l) vec(k,l) = (T)(lapA[(N - 1 - k)*N + l]); } else { val.fill(0); vec.fill(0); } delete[] lapA; delete[] lapW; delete[] WORK; #else CImg<t> V(_width,_width); Tfloat M = 0, m = (Tfloat)min_max(M), maxabs = cimg::max((Tfloat)1,cimg::abs(m),cimg::abs(M)); (CImg<Tfloat>(*this,false)/=maxabs).SVD(vec,val,V,false); if (maxabs!=1) val*=maxabs; bool is_ambiguous = false; float eig = 0; cimg_forY(val,p) { // Check for ambiguous cases if (val[p]>eig) eig = (float)val[p]; t scal = 0; cimg_forY(vec,y) scal+=vec(p,y)*V(p,y); if (cimg::abs(scal)<0.9f) is_ambiguous = true; if (scal<0) val[p] = -val[p]; } if (is_ambiguous) { ++(eig*=2); SVD(vec,val,V,false,40,eig); val-=eig; } CImg<intT> permutations; // Sort eigenvalues in decreasing order CImg<t> tmp(_width); val.sort(permutations,false); cimg_forY(vec,k) { cimg_forY(permutations,y) tmp(y) = vec(permutations(y),k); std::memcpy(vec.data(0,k),tmp._data,sizeof(t)*_width); } #endif return *this; } //! Compute eigenvalues and eigenvectors of the instance image, viewed as a symmetric matrix. /** \return A list of two images <tt>[val; vec]</tt>, whose meaning are similar as in symmetric_eigen(CImg<t>&,CImg<t>&) const. **/ CImgList<Tfloat> get_symmetric_eigen() const { CImgList<Tfloat> res(2); symmetric_eigen(res[0],res[1]); return res; } //! Sort pixel values and get sorting permutations. /** \param[out] permutations Permutation map used for the sorting. \param is_increasing Tells if pixel values are sorted in an increasing (\c true) or decreasing (\c false) way. **/ template<typename t> CImg<T>& sort(CImg<t>& permutations, const bool is_increasing=true) { permutations.assign(_width,_height,_depth,_spectrum); if (is_empty()) return *this; cimg_foroff(permutations,off) permutations[off] = (t)off; return _quicksort(0,size() - 1,permutations,is_increasing,true); } //! Sort pixel values and get sorting permutations \newinstance. template<typename t> CImg<T> get_sort(CImg<t>& permutations, const bool is_increasing=true) const { return (+*this).sort(permutations,is_increasing); } //! Sort pixel values. /** \param is_increasing Tells if pixel values are sorted in an increasing (\c true) or decreasing (\c false) way. \param axis Tells if the value sorting must be done along a specific axis. Can be: - \c 0: All pixel values are sorted, independently on their initial position. - \c 'x': Image columns are sorted, according to the first value in each column. - \c 'y': Image rows are sorted, according to the first value in each row. - \c 'z': Image slices are sorted, according to the first value in each slice. - \c 'c': Image channels are sorted, according to the first value in each channel. **/ CImg<T>& sort(const bool is_increasing=true, const char axis=0) { if (is_empty()) return *this; CImg<uintT> perm; switch (cimg::lowercase(axis)) { case 0 : _quicksort(0,size() - 1,perm,is_increasing,false); break; case 'x' : { perm.assign(_width); get_crop(0,0,0,0,_width - 1,0,0,0).sort(perm,is_increasing); CImg<T> img(*this,false); cimg_forXYZC(*this,x,y,z,c) (*this)(x,y,z,c) = img(perm[x],y,z,c); } break; case 'y' : { perm.assign(_height); get_crop(0,0,0,0,0,_height - 1,0,0).sort(perm,is_increasing); CImg<T> img(*this,false); cimg_forXYZC(*this,x,y,z,c) (*this)(x,y,z,c) = img(x,perm[y],z,c); } break; case 'z' : { perm.assign(_depth); get_crop(0,0,0,0,0,0,_depth - 1,0).sort(perm,is_increasing); CImg<T> img(*this,false); cimg_forXYZC(*this,x,y,z,c) (*this)(x,y,z,c) = img(x,y,perm[z],c); } break; case 'c' : { perm.assign(_spectrum); get_crop(0,0,0,0,0,0,0,_spectrum - 1).sort(perm,is_increasing); CImg<T> img(*this,false); cimg_forXYZC(*this,x,y,z,c) (*this)(x,y,z,c) = img(x,y,z,perm[c]); } break; default : throw CImgArgumentException(_cimg_instance "sort(): Invalid specified axis '%c' " "(should be { x | y | z | c }).", cimg_instance,axis); } return *this; } //! Sort pixel values \newinstance. CImg<T> get_sort(const bool is_increasing=true, const char axis=0) const { return (+*this).sort(is_increasing,axis); } template<typename t> CImg<T>& _quicksort(const long indm, const long indM, CImg<t>& permutations, const bool is_increasing, const bool is_permutations) { if (indm<indM) { const long mid = (indm + indM)/2; if (is_increasing) { if ((*this)[indm]>(*this)[mid]) { cimg::swap((*this)[indm],(*this)[mid]); if (is_permutations) cimg::swap(permutations[indm],permutations[mid]); } if ((*this)[mid]>(*this)[indM]) { cimg::swap((*this)[indM],(*this)[mid]); if (is_permutations) cimg::swap(permutations[indM],permutations[mid]); } if ((*this)[indm]>(*this)[mid]) { cimg::swap((*this)[indm],(*this)[mid]); if (is_permutations) cimg::swap(permutations[indm],permutations[mid]); } } else { if ((*this)[indm]<(*this)[mid]) { cimg::swap((*this)[indm],(*this)[mid]); if (is_permutations) cimg::swap(permutations[indm],permutations[mid]); } if ((*this)[mid]<(*this)[indM]) { cimg::swap((*this)[indM],(*this)[mid]); if (is_permutations) cimg::swap(permutations[indM],permutations[mid]); } if ((*this)[indm]<(*this)[mid]) { cimg::swap((*this)[indm],(*this)[mid]); if (is_permutations) cimg::swap(permutations[indm],permutations[mid]); } } if (indM - indm>=3) { const T pivot = (*this)[mid]; long i = indm, j = indM; if (is_increasing) { do { while ((*this)[i]<pivot) ++i; while ((*this)[j]>pivot) --j; if (i<=j) { if (is_permutations) cimg::swap(permutations[i],permutations[j]); cimg::swap((*this)[i++],(*this)[j--]); } } while (i<=j); } else { do { while ((*this)[i]>pivot) ++i; while ((*this)[j]<pivot) --j; if (i<=j) { if (is_permutations) cimg::swap(permutations[i],permutations[j]); cimg::swap((*this)[i++],(*this)[j--]); } } while (i<=j); } if (indm<j) _quicksort(indm,j,permutations,is_increasing,is_permutations); if (i<indM) _quicksort(i,indM,permutations,is_increasing,is_permutations); } } return *this; } //! Compute the SVD of the instance image, viewed as a general matrix. /** Compute the SVD decomposition \c *this=U*S*V' where \c U and \c V are orthogonal matrices and \c S is a diagonal matrix. \c V' denotes the matrix transpose of \c V. \param[out] U First matrix of the SVD product. \param[out] S Coefficients of the second (diagonal) matrix of the SVD product. These coefficients are stored as a vector. \param[out] V Third matrix of the SVD product. \param sorting Tells if the diagonal coefficients are sorted (in decreasing order). \param max_iteration Maximum number of iterations considered for the algorithm convergence. \param lambda Epsilon used for the algorithm convergence. \note The instance matrix can be computed from \c U,\c S and \c V by \code const CImg<> A; // Input matrix (assumed to contain some values) CImg<> U,S,V; A.SVD(U,S,V) \endcode **/ template<typename t> const CImg<T>& SVD(CImg<t>& U, CImg<t>& S, CImg<t>& V, const bool sorting=true, const unsigned int max_iteration=40, const float lambda=0) const { typedef _cimg_Ttfloat Ttfloat; if (is_empty()) { U.assign(); S.assign(); V.assign(); } else { U = *this; if (lambda!=0) { const unsigned int delta = std::min(U._width,U._height); for (unsigned int i = 0; i<delta; ++i) U(i,i) = (t)(U(i,i) + lambda); } if (S.size()<_width) S.assign(1,_width); if (V._width<_width || V._height<_height) V.assign(_width,_width); CImg<t> rv1(_width); Ttfloat anorm = 0, c, f, g = 0, h, s, scale = 0; int l = 0, nm = 0; cimg_forX(U,i) { l = i + 1; rv1[i] = scale*g; g = s = scale = 0; if (i<height()) { for (int k = i; k<height(); ++k) scale+=cimg::abs(U(i,k)); if (scale) { for (int k = i; k<height(); ++k) { U(i,k)/=scale; s+=U(i,k)*U(i,k); } f = U(i,i); g = (Ttfloat)((f>=0?-1:1)*std::sqrt(s)); h=f*g-s; U(i,i) = f-g; for (int j = l; j<width(); ++j) { s = 0; for (int k=i; k<height(); ++k) s+=U(i,k)*U(j,k); f = s/h; for (int k = i; k<height(); ++k) U(j,k)+=f*U(i,k); } for (int k = i; k<height(); ++k) U(i,k)*=scale; } } S[i]=scale*g; g = s = scale = 0; if (i<height() && i!=width() - 1) { for (int k = l; k<width(); ++k) scale+=cimg::abs(U(k,i)); if (scale) { for (int k = l; k<width(); ++k) { U(k,i)/= scale; s+=U(k,i)*U(k,i); } f = U(l,i); g = (Ttfloat)((f>=0?-1:1)*std::sqrt(s)); h = f*g-s; U(l,i) = f-g; for (int k = l; k<width(); ++k) rv1[k]=U(k,i)/h; for (int j = l; j<height(); ++j) { s = 0; for (int k = l; k<width(); ++k) s+=U(k,j)*U(k,i); for (int k = l; k<width(); ++k) U(k,j)+=s*rv1[k]; } for (int k = l; k<width(); ++k) U(k,i)*=scale; } } anorm = (Ttfloat)std::max((float)anorm,(float)(cimg::abs(S[i]) + cimg::abs(rv1[i]))); } for (int i = width() - 1; i>=0; --i) { if (i<width()-1) { if (g) { for (int j = l; j<width(); ++j) V(i,j) =(U(j,i)/U(l,i))/g; for (int j = l; j<width(); ++j) { s = 0; for (int k = l; k<width(); ++k) s+=U(k,i)*V(j,k); for (int k = l; k<width(); ++k) V(j,k)+=s*V(i,k); } } for (int j = l; j<width(); ++j) V(j,i) = V(i,j) = (t)0.; } V(i,i) = (t)1.; g = rv1[i]; l = i; } for (int i = std::min(width(),height()) - 1; i>=0; --i) { l = i + 1; g = S[i]; for (int j = l; j<width(); ++j) U(j,i) = 0; if (g) { g = 1/g; for (int j = l; j<width(); ++j) { s = 0; for (int k = l; k<height(); ++k) s+=U(i,k)*U(j,k); f = (s/U(i,i))*g; for (int k = i; k<height(); ++k) U(j,k)+=f*U(i,k); } for (int j = i; j<height(); ++j) U(i,j)*= g; } else for (int j = i; j<height(); ++j) U(i,j) = 0; ++U(i,i); } for (int k = width() - 1; k>=0; --k) { for (unsigned int its = 0; its<max_iteration; ++its) { bool flag = true; for (l = k; l>=1; --l) { nm = l - 1; if ((cimg::abs(rv1[l]) + anorm)==anorm) { flag = false; break; } if ((cimg::abs(S[nm]) + anorm)==anorm) break; } if (flag) { c = 0; s = 1; for (int i = l; i<=k; ++i) { f = s*rv1[i]; rv1[i] = c*rv1[i]; if ((cimg::abs(f) + anorm)==anorm) break; g = S[i]; h = cimg::_hypot(f,g); S[i] = h; h = 1/h; c = g*h; s = -f*h; cimg_forY(U,j) { const t y = U(nm,j), z = U(i,j); U(nm,j) = y*c + z*s; U(i,j) = z*c - y*s; } } } const t z = S[k]; if (l==k) { if (z<0) { S[k] = -z; cimg_forX(U,j) V(k,j) = -V(k,j); } break; } nm = k - 1; t x = S[l], y = S[nm]; g = rv1[nm]; h = rv1[k]; f = ((y - z)*(y + z)+(g - h)*(g + h))/std::max((Ttfloat)1e-25,(Ttfloat)2*h*y); g = cimg::_hypot(f,(Ttfloat)1); f = ((x - z)*(x + z)+h*((y/(f + (f>=0?g:-g))) - h))/std::max((Ttfloat)1e-25,(Ttfloat)x); c = s = 1; for (int j = l; j<=nm; ++j) { const int i = j + 1; g = rv1[i]; h = s*g; g = c*g; t y1 = S[i]; t z1 = cimg::_hypot(f,h); rv1[j] = z1; c = f/std::max((Ttfloat)1e-25,(Ttfloat)z1); s = h/std::max((Ttfloat)1e-25,(Ttfloat)z1); f = x*c + g*s; g = g*c - x*s; h = y1*s; y1*=c; cimg_forX(U,jj) { const t x2 = V(j,jj), z2 = V(i,jj); V(j,jj) = x2*c + z2*s; V(i,jj) = z2*c - x2*s; } z1 = cimg::_hypot(f,h); S[j] = z1; if (z1) { z1 = 1/std::max((Ttfloat)1e-25,(Ttfloat)z1); c = f*z1; s = h*z1; } f = c*g + s*y1; x = c*y1 - s*g; cimg_forY(U,jj) { const t y2 = U(j,jj), z2 = U(i,jj); U(j,jj) = y2*c + z2*s; U(i,jj) = z2*c - y2*s; } } rv1[l] = 0; rv1[k] = f; S[k] = x; } } if (sorting) { CImg<intT> permutations; CImg<t> tmp(_width); S.sort(permutations,false); cimg_forY(U,k) { cimg_forY(permutations,y) tmp(y) = U(permutations(y),k); std::memcpy(U.data(0,k),tmp._data,sizeof(t)*_width); } cimg_forY(V,k) { cimg_forY(permutations,y) tmp(y) = V(permutations(y),k); std::memcpy(V.data(0,k),tmp._data,sizeof(t)*_width); } } } return *this; } //! Compute the SVD of the instance image, viewed as a general matrix. /** \return A list of three images <tt>[U; S; V]</tt>, whose meaning is similar as in SVD(CImg<t>&,CImg<t>&,CImg<t>&,bool,unsigned int,float) const. **/ CImgList<Tfloat> get_SVD(const bool sorting=true, const unsigned int max_iteration=40, const float lambda=0) const { CImgList<Tfloat> res(3); SVD(res[0],res[1],res[2],sorting,max_iteration,lambda); return res; } // [internal] Compute the LU decomposition of a permuted matrix. template<typename t> CImg<T>& _LU(CImg<t>& indx, bool& d) { const int N = width(); int imax = 0; CImg<Tfloat> vv(N); indx.assign(N); d = true; bool return0 = false; cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height>=512)) cimg_forX(*this,i) { Tfloat vmax = 0; cimg_forX(*this,j) { const Tfloat tmp = cimg::abs((*this)(j,i)); if (tmp>vmax) vmax = tmp; } if (vmax==0) return0 = true; else vv[i] = 1/vmax; } if (return0) { indx.fill(0); return fill(0); } cimg_forX(*this,j) { for (int i = 0; i<j; ++i) { Tfloat sum = (*this)(j,i); for (int k = 0; k<i; ++k) sum-=(*this)(k,i)*(*this)(j,k); (*this)(j,i) = (T)sum; } Tfloat vmax = 0; for (int i = j; i<width(); ++i) { Tfloat sum = (*this)(j,i); for (int k = 0; k<j; ++k) sum-=(*this)(k,i)*(*this)(j,k); (*this)(j,i) = (T)sum; const Tfloat tmp = vv[i]*cimg::abs(sum); if (tmp>=vmax) { vmax = tmp; imax = i; } } if (j!=imax) { cimg_forX(*this,k) cimg::swap((*this)(k,imax),(*this)(k,j)); d = !d; vv[imax] = vv[j]; } indx[j] = (t)imax; if ((*this)(j,j)==0) (*this)(j,j) = (T)1e-20; if (j<N) { const Tfloat tmp = 1/(Tfloat)(*this)(j,j); for (int i = j + 1; i<N; ++i) (*this)(j,i) = (T)((*this)(j,i)*tmp); } } return *this; } //! Compute minimal path in a graph, using the Dijkstra algorithm. /** \param distance An object having operator()(unsigned int i, unsigned int j) which returns distance between two nodes (i,j). \param nb_nodes Number of graph nodes. \param starting_node Index of the starting node. \param ending_node Index of the ending node (set to ~0U to ignore ending node). \param previous_node Array that gives the previous node index in the path to the starting node (optional parameter). \return Array of distances of each node to the starting node. **/ template<typename tf, typename t> static CImg<T> dijkstra(const tf& distance, const unsigned int nb_nodes, const unsigned int starting_node, const unsigned int ending_node, CImg<t>& previous_node) { if (starting_node>=nb_nodes) throw CImgArgumentException("CImg<%s>::dijkstra(): Specified index of starting node %u is higher " "than number of nodes %u.", pixel_type(),starting_node,nb_nodes); CImg<T> dist(1,nb_nodes,1,1,cimg::type<T>::max()); dist(starting_node) = 0; previous_node.assign(1,nb_nodes,1,1,(t)-1); previous_node(starting_node) = (t)starting_node; CImg<uintT> Q(nb_nodes); cimg_forX(Q,u) Q(u) = (unsigned int)u; cimg::swap(Q(starting_node),Q(0)); unsigned int sizeQ = nb_nodes; while (sizeQ) { // Update neighbors from minimal vertex const unsigned int umin = Q(0); if (umin==ending_node) sizeQ = 0; else { const T dmin = dist(umin); const T infty = cimg::type<T>::max(); for (unsigned int q = 1; q<sizeQ; ++q) { const unsigned int v = Q(q); const T d = (T)distance(v,umin); if (d<infty) { const T alt = dmin + d; if (alt<dist(v)) { dist(v) = alt; previous_node(v) = (t)umin; const T distpos = dist(Q(q)); for (unsigned int pos = q, par = 0; pos && distpos<dist(Q(par=(pos + 1)/2 - 1)); pos=par) cimg::swap(Q(pos),Q(par)); } } } // Remove minimal vertex from queue Q(0) = Q(--sizeQ); const T distpos = dist(Q(0)); for (unsigned int pos = 0, left = 0, right = 0; ((right=2*(pos + 1),(left=right - 1))<sizeQ && distpos>dist(Q(left))) || (right<sizeQ && distpos>dist(Q(right)));) { if (right<sizeQ) { if (dist(Q(left))<dist(Q(right))) { cimg::swap(Q(pos),Q(left)); pos = left; } else { cimg::swap(Q(pos),Q(right)); pos = right; } } else { cimg::swap(Q(pos),Q(left)); pos = left; } } } } return dist; } //! Return minimal path in a graph, using the Dijkstra algorithm. template<typename tf, typename t> static CImg<T> dijkstra(const tf& distance, const unsigned int nb_nodes, const unsigned int starting_node, const unsigned int ending_node=~0U) { CImg<uintT> foo; return dijkstra(distance,nb_nodes,starting_node,ending_node,foo); } //! Return minimal path in a graph, using the Dijkstra algorithm. /** \param starting_node Index of the starting node. \param ending_node Index of the ending node. \param previous_node Array that gives the previous node index in the path to the starting node (optional parameter). \return Array of distances of each node to the starting node. \note image instance corresponds to the adjacency matrix of the graph. **/ template<typename t> CImg<T>& dijkstra(const unsigned int starting_node, const unsigned int ending_node, CImg<t>& previous_node) { return get_dijkstra(starting_node,ending_node,previous_node).move_to(*this); } //! Return minimal path in a graph, using the Dijkstra algorithm \newinstance. template<typename t> CImg<T> get_dijkstra(const unsigned int starting_node, const unsigned int ending_node, CImg<t>& previous_node) const { if (_width!=_height || _depth!=1 || _spectrum!=1) throw CImgInstanceException(_cimg_instance "dijkstra(): Instance is not a graph adjacency matrix.", cimg_instance); return dijkstra(*this,_width,starting_node,ending_node,previous_node); } //! Return minimal path in a graph, using the Dijkstra algorithm. CImg<T>& dijkstra(const unsigned int starting_node, const unsigned int ending_node=~0U) { return get_dijkstra(starting_node,ending_node).move_to(*this); } //! Return minimal path in a graph, using the Dijkstra algorithm \newinstance. CImg<Tfloat> get_dijkstra(const unsigned int starting_node, const unsigned int ending_node=~0U) const { CImg<uintT> foo; return get_dijkstra(starting_node,ending_node,foo); } //! Return an image containing the Ascii codes of the specified string. /** \param str input C-string to encode as an image. \param is_last_zero Tells if the ending \c '0' character appear in the resulting image. \param is_shared Return result that shares its buffer with \p str. **/ static CImg<T> string(const char *const str, const bool is_last_zero=true, const bool is_shared=false) { if (!str) return CImg<T>(); return CImg<T>(str,(unsigned int)std::strlen(str) + (is_last_zero?1:0),1,1,1,is_shared); } //! Return a \c 1x1 image containing specified value. /** \param a0 First vector value. **/ static CImg<T> vector(const T& a0) { CImg<T> r(1,1); r[0] = a0; return r; } //! Return a \c 1x2 image containing specified values. /** \param a0 First vector value. \param a1 Second vector value. **/ static CImg<T> vector(const T& a0, const T& a1) { CImg<T> r(1,2); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; return r; } //! Return a \c 1x3 image containing specified values. /** \param a0 First vector value. \param a1 Second vector value. \param a2 Third vector value. **/ static CImg<T> vector(const T& a0, const T& a1, const T& a2) { CImg<T> r(1,3); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; return r; } //! Return a \c 1x4 image containing specified values. /** \param a0 First vector value. \param a1 Second vector value. \param a2 Third vector value. \param a3 Fourth vector value. **/ static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3) { CImg<T> r(1,4); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; return r; } //! Return a \c 1x5 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4) { CImg<T> r(1,5); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; return r; } //! Return a \c 1x6 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5) { CImg<T> r(1,6); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; return r; } //! Return a \c 1x7 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6) { CImg<T> r(1,7); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; return r; } //! Return a \c 1x8 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7) { CImg<T> r(1,8); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; return r; } //! Return a \c 1x9 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8) { CImg<T> r(1,9); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; return r; } //! Return a \c 1x10 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8, const T& a9) { CImg<T> r(1,10); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; *(ptr++) = a9; return r; } //! Return a \c 1x11 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8, const T& a9, const T& a10) { CImg<T> r(1,11); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; *(ptr++) = a9; *(ptr++) = a10; return r; } //! Return a \c 1x12 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8, const T& a9, const T& a10, const T& a11) { CImg<T> r(1,12); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; *(ptr++) = a9; *(ptr++) = a10; *(ptr++) = a11; return r; } //! Return a \c 1x13 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8, const T& a9, const T& a10, const T& a11, const T& a12) { CImg<T> r(1,13); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; *(ptr++) = a9; *(ptr++) = a10; *(ptr++) = a11; *(ptr++) = a12; return r; } //! Return a \c 1x14 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8, const T& a9, const T& a10, const T& a11, const T& a12, const T& a13) { CImg<T> r(1,14); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; *(ptr++) = a9; *(ptr++) = a10; *(ptr++) = a11; *(ptr++) = a12; *(ptr++) = a13; return r; } //! Return a \c 1x15 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8, const T& a9, const T& a10, const T& a11, const T& a12, const T& a13, const T& a14) { CImg<T> r(1,15); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; *(ptr++) = a9; *(ptr++) = a10; *(ptr++) = a11; *(ptr++) = a12; *(ptr++) = a13; *(ptr++) = a14; return r; } //! Return a \c 1x16 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8, const T& a9, const T& a10, const T& a11, const T& a12, const T& a13, const T& a14, const T& a15) { CImg<T> r(1,16); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; *(ptr++) = a9; *(ptr++) = a10; *(ptr++) = a11; *(ptr++) = a12; *(ptr++) = a13; *(ptr++) = a14; *(ptr++) = a15; return r; } //! Return a 1x1 matrix containing specified coefficients. /** \param a0 First matrix value. \note Equivalent to vector(const T&). **/ static CImg<T> matrix(const T& a0) { return vector(a0); } //! Return a 2x2 matrix containing specified coefficients. /** \param a0 First matrix value. \param a1 Second matrix value. \param a2 Third matrix value. \param a3 Fourth matrix value. **/ static CImg<T> matrix(const T& a0, const T& a1, const T& a2, const T& a3) { CImg<T> r(2,2); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; return r; } //! Return a 3x3 matrix containing specified coefficients. /** \param a0 First matrix value. \param a1 Second matrix value. \param a2 Third matrix value. \param a3 Fourth matrix value. \param a4 Fifth matrix value. \param a5 Sixth matrix value. \param a6 Seventh matrix value. \param a7 Eighth matrix value. \param a8 Nineth matrix value. **/ static CImg<T> matrix(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8) { CImg<T> r(3,3); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; return r; } //! Return a 4x4 matrix containing specified coefficients. static CImg<T> matrix(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8, const T& a9, const T& a10, const T& a11, const T& a12, const T& a13, const T& a14, const T& a15) { CImg<T> r(4,4); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; *(ptr++) = a9; *(ptr++) = a10; *(ptr++) = a11; *(ptr++) = a12; *(ptr++) = a13; *(ptr++) = a14; *(ptr++) = a15; return r; } //! Return a 5x5 matrix containing specified coefficients. static CImg<T> matrix(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8, const T& a9, const T& a10, const T& a11, const T& a12, const T& a13, const T& a14, const T& a15, const T& a16, const T& a17, const T& a18, const T& a19, const T& a20, const T& a21, const T& a22, const T& a23, const T& a24) { CImg<T> r(5,5); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; *(ptr++) = a9; *(ptr++) = a10; *(ptr++) = a11; *(ptr++) = a12; *(ptr++) = a13; *(ptr++) = a14; *(ptr++) = a15; *(ptr++) = a16; *(ptr++) = a17; *(ptr++) = a18; *(ptr++) = a19; *(ptr++) = a20; *(ptr++) = a21; *(ptr++) = a22; *(ptr++) = a23; *(ptr++) = a24; return r; } //! Return a 1x1 symmetric matrix containing specified coefficients. /** \param a0 First matrix value. \note Equivalent to vector(const T&). **/ static CImg<T> tensor(const T& a0) { return matrix(a0); } //! Return a 2x2 symmetric matrix tensor containing specified coefficients. static CImg<T> tensor(const T& a0, const T& a1, const T& a2) { return matrix(a0,a1,a1,a2); } //! Return a 3x3 symmetric matrix containing specified coefficients. static CImg<T> tensor(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5) { return matrix(a0,a1,a2,a1,a3,a4,a2,a4,a5); } //! Return a 1x1 diagonal matrix containing specified coefficients. static CImg<T> diagonal(const T& a0) { return matrix(a0); } //! Return a 2x2 diagonal matrix containing specified coefficients. static CImg<T> diagonal(const T& a0, const T& a1) { return matrix(a0,0,0,a1); } //! Return a 3x3 diagonal matrix containing specified coefficients. static CImg<T> diagonal(const T& a0, const T& a1, const T& a2) { return matrix(a0,0,0,0,a1,0,0,0,a2); } //! Return a 4x4 diagonal matrix containing specified coefficients. static CImg<T> diagonal(const T& a0, const T& a1, const T& a2, const T& a3) { return matrix(a0,0,0,0,0,a1,0,0,0,0,a2,0,0,0,0,a3); } //! Return a 5x5 diagonal matrix containing specified coefficients. static CImg<T> diagonal(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4) { return matrix(a0,0,0,0,0,0,a1,0,0,0,0,0,a2,0,0,0,0,0,a3,0,0,0,0,0,a4); } //! Return a NxN identity matrix. /** \param N Dimension of the matrix. **/ static CImg<T> identity_matrix(const unsigned int N) { CImg<T> res(N,N,1,1,0); cimg_forX(res,x) res(x,x) = 1; return res; } //! Return a N-numbered sequence vector from \p a0 to \p a1. /** \param N Size of the resulting vector. \param a0 Starting value of the sequence. \param a1 Ending value of the sequence. **/ static CImg<T> sequence(const unsigned int N, const T& a0, const T& a1) { if (N) return CImg<T>(1,N).sequence(a0,a1); return CImg<T>(); } //! Return a 3x3 rotation matrix from an { axis + angle } or a quaternion. /** \param x X-coordinate of the rotation axis, or first quaternion coordinate. \param y Y-coordinate of the rotation axis, or second quaternion coordinate. \param z Z-coordinate of the rotation axis, or third quaternion coordinate. \param w Angle of the rotation axis (in degree), or fourth quaternion coordinate. \param is_quaternion Tell is the four arguments denotes a set { axis + angle } or a quaternion (x,y,z,w). **/ static CImg<T> rotation_matrix(const float x, const float y, const float z, const float w, const bool is_quaternion=false) { double X, Y, Z, W, N; if (is_quaternion) { N = std::sqrt((double)x*x + (double)y*y + (double)z*z + (double)w*w); if (N>0) { X = x/N; Y = y/N; Z = z/N; W = w/N; } else { X = Y = Z = 0; W = 1; } return CImg<T>::matrix((T)(X*X + Y*Y - Z*Z - W*W),(T)(2*Y*Z - 2*X*W),(T)(2*X*Z + 2*Y*W), (T)(2*X*W + 2*Y*Z),(T)(X*X - Y*Y + Z*Z - W*W),(T)(2*Z*W - 2*X*Y), (T)(2*Y*W - 2*X*Z),(T)(2*X*Y + 2*Z*W),(T)(X*X - Y*Y - Z*Z + W*W)); } N = cimg::hypot((double)x,(double)y,(double)z); if (N>0) { X = x/N; Y = y/N; Z = z/N; } else { X = Y = 0; Z = 1; } const double ang = w*cimg::PI/180, c = std::cos(ang), omc = 1 - c, s = std::sin(ang); return CImg<T>::matrix((T)(X*X*omc + c),(T)(X*Y*omc - Z*s),(T)(X*Z*omc + Y*s), (T)(X*Y*omc + Z*s),(T)(Y*Y*omc + c),(T)(Y*Z*omc - X*s), (T)(X*Z*omc - Y*s),(T)(Y*Z*omc + X*s),(T)(Z*Z*omc + c)); } //@} //----------------------------------- // //! \name Value Manipulation //@{ //----------------------------------- //! Fill all pixel values with specified value. /** \param val Fill value. **/ CImg<T>& fill(const T& val) { if (is_empty()) return *this; if (val && sizeof(T)!=1) cimg_for(*this,ptrd,T) *ptrd = val; else std::memset(_data,(int)(ulongT)val,sizeof(T)*size()); // Double cast to allow val to be (void*) return *this; } //! Fill all pixel values with specified value \newinstance. CImg<T> get_fill(const T& val) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val); } //! Fill sequentially all pixel values with specified values. /** \param val0 First fill value. \param val1 Second fill value. **/ CImg<T>& fill(const T& val0, const T& val1) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 1; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; } if (ptrd!=ptre + 1) *(ptrd++) = val0; return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T& val0, const T& val1, const T& val2) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 2; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; } ptre+=2; switch (ptre - ptrd) { case 2 : *(--ptre) = val1; // fallthrough case 1 : *(--ptre) = val0; // fallthrough } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1, const T& val2) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T& val0, const T& val1, const T& val2, const T& val3) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 3; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; } ptre+=3; switch (ptre - ptrd) { case 3 : *(--ptre) = val2; // fallthrough case 2 : *(--ptre) = val1; // fallthrough case 1 : *(--ptre) = val0; // fallthrough } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1, const T& val2, const T& val3) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 4; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; } ptre+=4; switch (ptre - ptrd) { case 4 : *(--ptre) = val3; // fallthrough case 3 : *(--ptre) = val2; // fallthrough case 2 : *(--ptre) = val1; // fallthrough case 1 : *(--ptre) = val0; // fallthrough } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 5; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; } ptre+=5; switch (ptre - ptrd) { case 5 : *(--ptre) = val4; // fallthrough case 4 : *(--ptre) = val3; // fallthrough case 3 : *(--ptre) = val2; // fallthrough case 2 : *(--ptre) = val1; // fallthrough case 1 : *(--ptre) = val0; // fallthrough } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 6; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; } ptre+=6; switch (ptre - ptrd) { case 6 : *(--ptre) = val5; // fallthrough case 5 : *(--ptre) = val4; // fallthrough case 4 : *(--ptre) = val3; // fallthrough case 3 : *(--ptre) = val2; // fallthrough case 2 : *(--ptre) = val1; // fallthrough case 1 : *(--ptre) = val0; // fallthrough } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 7; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; *(ptrd++) = val7; } ptre+=7; switch (ptre - ptrd) { case 7 : *(--ptre) = val6; // fallthrough case 6 : *(--ptre) = val5; // fallthrough case 5 : *(--ptre) = val4; // fallthrough case 4 : *(--ptre) = val3; // fallthrough case 3 : *(--ptre) = val2; // fallthrough case 2 : *(--ptre) = val1; // fallthrough case 1 : *(--ptre) = val0; // fallthrough } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6,val7); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 8; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; *(ptrd++) = val7; *(ptrd++) = val8; } ptre+=8; switch (ptre - ptrd) { case 8 : *(--ptre) = val7; // fallthrough case 7 : *(--ptre) = val6; // fallthrough case 6 : *(--ptre) = val5; // fallthrough case 5 : *(--ptre) = val4; // fallthrough case 4 : *(--ptre) = val3; // fallthrough case 3 : *(--ptre) = val2; // fallthrough case 2 : *(--ptre) = val1; // fallthrough case 1 : *(--ptre) = val0; // fallthrough } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6,val7,val8); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8, const T& val9) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 9; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; *(ptrd++) = val7; *(ptrd++) = val8; *(ptrd++) = val9; } ptre+=9; switch (ptre - ptrd) { case 9 : *(--ptre) = val8; // fallthrough case 8 : *(--ptre) = val7; // fallthrough case 7 : *(--ptre) = val6; // fallthrough case 6 : *(--ptre) = val5; // fallthrough case 5 : *(--ptre) = val4; // fallthrough case 4 : *(--ptre) = val3; // fallthrough case 3 : *(--ptre) = val2; // fallthrough case 2 : *(--ptre) = val1; // fallthrough case 1 : *(--ptre) = val0; // fallthrough } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8, const T& val9) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6,val7,val8,val9); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8, const T& val9, const T& val10) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 10; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; *(ptrd++) = val7; *(ptrd++) = val8; *(ptrd++) = val9; *(ptrd++) = val10; } ptre+=10; switch (ptre - ptrd) { case 10 : *(--ptre) = val9; // fallthrough case 9 : *(--ptre) = val8; // fallthrough case 8 : *(--ptre) = val7; // fallthrough case 7 : *(--ptre) = val6; // fallthrough case 6 : *(--ptre) = val5; // fallthrough case 5 : *(--ptre) = val4; // fallthrough case 4 : *(--ptre) = val3; // fallthrough case 3 : *(--ptre) = val2; // fallthrough case 2 : *(--ptre) = val1; // fallthrough case 1 : *(--ptre) = val0; // fallthrough } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8, const T& val9, const T& val10) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6,val7,val8,val9,val10); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8, const T& val9, const T& val10, const T& val11) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 11; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; *(ptrd++) = val7; *(ptrd++) = val8; *(ptrd++) = val9; *(ptrd++) = val10; *(ptrd++) = val11; } ptre+=11; switch (ptre - ptrd) { case 11 : *(--ptre) = val10; // fallthrough case 10 : *(--ptre) = val9; // fallthrough case 9 : *(--ptre) = val8; // fallthrough case 8 : *(--ptre) = val7; // fallthrough case 7 : *(--ptre) = val6; // fallthrough case 6 : *(--ptre) = val5; // fallthrough case 5 : *(--ptre) = val4; // fallthrough case 4 : *(--ptre) = val3; // fallthrough case 3 : *(--ptre) = val2; // fallthrough case 2 : *(--ptre) = val1; // fallthrough case 1 : *(--ptre) = val0; // fallthrough } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8, const T& val9, const T& val10, const T& val11) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6,val7,val8,val9,val10, val11); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8, const T& val9, const T& val10, const T& val11, const T& val12) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 12; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; *(ptrd++) = val7; *(ptrd++) = val8; *(ptrd++) = val9; *(ptrd++) = val10; *(ptrd++) = val11; *(ptrd++) = val12; } ptre+=12; switch (ptre - ptrd) { case 12 : *(--ptre) = val11; // fallthrough case 11 : *(--ptre) = val10; // fallthrough case 10 : *(--ptre) = val9; // fallthrough case 9 : *(--ptre) = val8; // fallthrough case 8 : *(--ptre) = val7; // fallthrough case 7 : *(--ptre) = val6; // fallthrough case 6 : *(--ptre) = val5; // fallthrough case 5 : *(--ptre) = val4; // fallthrough case 4 : *(--ptre) = val3; // fallthrough case 3 : *(--ptre) = val2; // fallthrough case 2 : *(--ptre) = val1; // fallthrough case 1 : *(--ptre) = val0; // fallthrough } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8, const T& val9, const T& val10, const T& val11, const T& val12) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6,val7,val8,val9,val10, val11,val12); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8, const T& val9, const T& val10, const T& val11, const T& val12, const T& val13) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 13; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; *(ptrd++) = val7; *(ptrd++) = val8; *(ptrd++) = val9; *(ptrd++) = val10; *(ptrd++) = val11; *(ptrd++) = val12; *(ptrd++) = val13; } ptre+=13; switch (ptre - ptrd) { case 13 : *(--ptre) = val12; // fallthrough case 12 : *(--ptre) = val11; // fallthrough case 11 : *(--ptre) = val10; // fallthrough case 10 : *(--ptre) = val9; // fallthrough case 9 : *(--ptre) = val8; // fallthrough case 8 : *(--ptre) = val7; // fallthrough case 7 : *(--ptre) = val6; // fallthrough case 6 : *(--ptre) = val5; // fallthrough case 5 : *(--ptre) = val4; // fallthrough case 4 : *(--ptre) = val3; // fallthrough case 3 : *(--ptre) = val2; // fallthrough case 2 : *(--ptre) = val1; // fallthrough case 1 : *(--ptre) = val0; // fallthrough } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8, const T& val9, const T& val10, const T& val11, const T& val12, const T& val13) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6,val7,val8,val9,val10, val11,val12,val13); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8, const T& val9, const T& val10, const T& val11, const T& val12, const T& val13, const T& val14) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 14; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; *(ptrd++) = val7; *(ptrd++) = val8; *(ptrd++) = val9; *(ptrd++) = val10; *(ptrd++) = val11; *(ptrd++) = val12; *(ptrd++) = val13; *(ptrd++) = val14; } ptre+=14; switch (ptre - ptrd) { case 14 : *(--ptre) = val13; // fallthrough case 13 : *(--ptre) = val12; // fallthrough case 12 : *(--ptre) = val11; // fallthrough case 11 : *(--ptre) = val10; // fallthrough case 10 : *(--ptre) = val9; // fallthrough case 9 : *(--ptre) = val8; // fallthrough case 8 : *(--ptre) = val7; // fallthrough case 7 : *(--ptre) = val6; // fallthrough case 6 : *(--ptre) = val5; // fallthrough case 5 : *(--ptre) = val4; // fallthrough case 4 : *(--ptre) = val3; // fallthrough case 3 : *(--ptre) = val2; // fallthrough case 2 : *(--ptre) = val1; // fallthrough case 1 : *(--ptre) = val0; // fallthrough } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8, const T& val9, const T& val10, const T& val11, const T& val12, const T& val13, const T& val14) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6,val7,val8,val9,val10, val11,val12,val13,val14); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8, const T& val9, const T& val10, const T& val11, const T& val12, const T& val13, const T& val14, const T& val15) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 15; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; *(ptrd++) = val7; *(ptrd++) = val8; *(ptrd++) = val9; *(ptrd++) = val10; *(ptrd++) = val11; *(ptrd++) = val12; *(ptrd++) = val13; *(ptrd++) = val14; *(ptrd++) = val15; } ptre+=15; switch (ptre - ptrd) { case 15 : *(--ptre) = val14; // fallthrough case 14 : *(--ptre) = val13; // fallthrough case 13 : *(--ptre) = val12; // fallthrough case 12 : *(--ptre) = val11; // fallthrough case 11 : *(--ptre) = val10; // fallthrough case 10 : *(--ptre) = val9; // fallthrough case 9 : *(--ptre) = val8; // fallthrough case 8 : *(--ptre) = val7; // fallthrough case 7 : *(--ptre) = val6; // fallthrough case 6 : *(--ptre) = val5; // fallthrough case 5 : *(--ptre) = val4; // fallthrough case 4 : *(--ptre) = val3; // fallthrough case 3 : *(--ptre) = val2; // fallthrough case 2 : *(--ptre) = val1; // fallthrough case 1 : *(--ptre) = val0; // fallthrough } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8, const T& val9, const T& val10, const T& val11, const T& val12, const T& val13, const T& val14, const T& val15) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6,val7,val8,val9,val10, val11,val12,val13,val14,val15); } //! Fill sequentially pixel values according to a given expression. /** \param expression C-string describing a math formula, or a sequence of values. \param repeat_values In case a list of values is provided, tells if this list must be repeated for the filling. \param allow_formula Tells that mathematical formulas are authorized for the filling. \param list_inputs In case of a mathematical expression, attach a list of images to the specified expression. \param[out] list_outputs In case of a math expression, list of images atatched to the specified expression. **/ CImg<T>& fill(const char *const expression, const bool repeat_values, const bool allow_formula=true, const CImgList<T> *const list_inputs=0, CImgList<T> *const list_outputs=0) { return _fill(expression,repeat_values,allow_formula?1:0,list_inputs,list_outputs,"fill",0); } // 'formula_mode' = { 0 = does not allow formula | 1 = allow formula | // 2 = allow formula but do not fill image values }. CImg<T>& _fill(const char *const expression, const bool repeat_values, const unsigned int formula_mode, const CImgList<T> *const list_inputs, CImgList<T> *const list_outputs, const char *const calling_function, const CImg<T> *provides_copy) { if (is_empty() || !expression || !*expression) return *this; const unsigned int omode = cimg::exception_mode(); cimg::exception_mode(0); CImg<charT> is_error; bool is_value_sequence = false; cimg_abort_init; if (formula_mode) { // Try to pre-detect regular value sequence to avoid exception thrown by _cimg_math_parser. double value; char sep; const int err = cimg_sscanf(expression,"%lf %c",&value,&sep); if (err==1 || (err==2 && sep==',')) { if (err==1) return fill((T)value); else is_value_sequence = true; } // Try to fill values according to a formula. _cimg_abort_init_omp; if (!is_value_sequence) try { CImg<T> base = provides_copy?provides_copy->get_shared():get_shared(); _cimg_math_parser mp(expression + (*expression=='>' || *expression=='<' || *expression=='*' || *expression==':'), calling_function,base,this,list_inputs,list_outputs,true); if (!provides_copy && expression && *expression!='>' && *expression!='<' && *expression!=':' && mp.need_input_copy) base.assign().assign(*this,false); // Needs input copy bool do_in_parallel = false; #if cimg_use_openmp!=0 cimg_openmp_if(*expression=='*' || *expression==':' || (mp.is_parallelizable && _width>=(cimg_openmp_sizefactor)*320 && _height*_depth*_spectrum>=2)) do_in_parallel = true; #endif if (mp.result_dim) { // Vector-valued expression const unsigned int N = std::min(mp.result_dim,_spectrum); const ulongT whd = (ulongT)_width*_height*_depth; T *ptrd = *expression=='<'?_data + _width*_height*_depth - 1:_data; if (*expression=='<') { CImg<doubleT> res(1,mp.result_dim); cimg_rofYZ(*this,y,z) { cimg_abort_test; if (formula_mode==2) cimg_rofX(*this,x) mp(x,y,z,0); else cimg_rofX(*this,x) { mp(x,y,z,0,res._data); const double *ptrs = res._data; T *_ptrd = ptrd--; for (unsigned int n = N; n>0; --n) { *_ptrd = (T)(*ptrs++); _ptrd+=whd; } } } } else if (*expression=='>' || !do_in_parallel) { CImg<doubleT> res(1,mp.result_dim); cimg_forYZ(*this,y,z) { cimg_abort_test; if (formula_mode==2) cimg_forX(*this,x) mp(x,y,z,0); else cimg_forX(*this,x) { mp(x,y,z,0,res._data); const double *ptrs = res._data; T *_ptrd = ptrd++; for (unsigned int n = N; n>0; --n) { *_ptrd = (T)(*ptrs++); _ptrd+=whd; } } } } else { #if cimg_use_openmp!=0 cimg_pragma_openmp(parallel) { _cimg_math_parser _mp = omp_get_thread_num()?mp:_cimg_math_parser(), &lmp = omp_get_thread_num()?_mp:mp; lmp.is_fill = true; cimg_pragma_openmp(for cimg_openmp_collapse(2)) cimg_forYZ(*this,y,z) _cimg_abort_try_omp { cimg_abort_test; if (formula_mode==2) cimg_forX(*this,x) lmp(x,y,z,0); else { CImg<doubleT> res(1,lmp.result_dim); T *__ptrd = data(0,y,z,0); cimg_forX(*this,x) { lmp(x,y,z,0,res._data); const double *ptrs = res._data; T *_ptrd = __ptrd++; for (unsigned int n = N; n>0; --n) { *_ptrd = (T)(*ptrs++); _ptrd+=whd; } } } } _cimg_abort_catch_omp _cimg_abort_catch_fill_omp } #endif } } else { // Scalar-valued expression T *ptrd = *expression=='<'?end() - 1:_data; if (*expression=='<') { if (formula_mode==2) cimg_rofYZC(*this,y,z,c) { cimg_abort_test; cimg_rofX(*this,x) mp(x,y,z,c); } else cimg_rofYZC(*this,y,z,c) { cimg_abort_test; cimg_rofX(*this,x) *(ptrd--) = (T)mp(x,y,z,c); } } else if (*expression=='>' || !do_in_parallel) { if (formula_mode==2) cimg_forYZC(*this,y,z,c) { cimg_abort_test; cimg_forX(*this,x) mp(x,y,z,c); } else cimg_forYZC(*this,y,z,c) { cimg_abort_test; cimg_forX(*this,x) *(ptrd++) = (T)mp(x,y,z,c); } } else { #if cimg_use_openmp!=0 cimg_pragma_openmp(parallel) { _cimg_math_parser _mp = omp_get_thread_num()?mp:_cimg_math_parser(), &lmp = omp_get_thread_num()?_mp:mp; lmp.is_fill = true; cimg_pragma_openmp(for cimg_openmp_collapse(3)) cimg_forYZC(*this,y,z,c) _cimg_abort_try_omp { cimg_abort_test; if (formula_mode==2) cimg_forX(*this,x) lmp(x,y,z,c); else { T *_ptrd = data(0,y,z,c); cimg_forX(*this,x) *(_ptrd++) = (T)lmp(x,y,z,c); } } _cimg_abort_catch_omp _cimg_abort_catch_fill_omp } #endif } } mp.end(); } catch (CImgException& e) { CImg<charT>::string(e._message).move_to(is_error); } } // Try to fill values according to a value sequence. if (!formula_mode || is_value_sequence || is_error) { CImg<charT> item(256); char sep = 0; const char *nexpression = expression; ulongT nb = 0; const ulongT siz = size(); T *ptrd = _data; for (double val = 0; *nexpression && nb<siz; ++nb) { sep = 0; const int err = cimg_sscanf(nexpression,"%255[ \n\t0-9.eEinfa+-]%c",item._data,&sep); if (err>0 && cimg_sscanf(item,"%lf",&val)==1 && (sep==',' || sep==';' || err==1)) { nexpression+=std::strlen(item) + (err>1); *(ptrd++) = (T)val; } else break; } cimg::exception_mode(omode); if (nb<siz && (sep || *nexpression)) { if (is_error) throw CImgArgumentException("%s",is_error._data); else throw CImgArgumentException(_cimg_instance "%s(): Invalid sequence of filling values '%s'.", cimg_instance,calling_function,expression); } if (repeat_values && nb && nb<siz) for (T *ptrs = _data, *const ptre = _data + siz; ptrd<ptre; ++ptrs) *(ptrd++) = *ptrs; } cimg::exception_mode(omode); cimg_abort_test; return *this; } //! Fill sequentially pixel values according to a given expression \newinstance. CImg<T> get_fill(const char *const expression, const bool repeat_values, const bool allow_formula=true, const CImgList<T> *const list_inputs=0, CImgList<T> *const list_outputs=0) const { return (+*this).fill(expression,repeat_values,allow_formula?1:0,list_inputs,list_outputs); } //! Fill sequentially pixel values according to the values found in another image. /** \param values Image containing the values used for the filling. \param repeat_values In case there are less values than necessary in \c values, tells if these values must be repeated for the filling. **/ template<typename t> CImg<T>& fill(const CImg<t>& values, const bool repeat_values=true) { if (is_empty() || !values) return *this; T *ptrd = _data, *ptre = ptrd + size(); for (t *ptrs = values._data, *ptrs_end = ptrs + values.size(); ptrs<ptrs_end && ptrd<ptre; ++ptrs) *(ptrd++) = (T)*ptrs; if (repeat_values && ptrd<ptre) for (T *ptrs = _data; ptrd<ptre; ++ptrs) *(ptrd++) = *ptrs; return *this; } //! Fill sequentially pixel values according to the values found in another image \newinstance. template<typename t> CImg<T> get_fill(const CImg<t>& values, const bool repeat_values=true) const { return repeat_values?CImg<T>(_width,_height,_depth,_spectrum).fill(values,repeat_values): (+*this).fill(values,repeat_values); } //! Fill pixel values along the X-axis at a specified pixel position. /** \param y Y-coordinate of the filled column. \param z Z-coordinate of the filled column. \param c C-coordinate of the filled column. \param a0 First fill value. **/ CImg<T>& fillX(const unsigned int y, const unsigned int z, const unsigned int c, const int a0, ...) { #define _cimg_fill1(x,y,z,c,off,siz,t) { \ va_list ap; va_start(ap,a0); T *ptrd = data(x,y,z,c); *ptrd = (T)a0; \ for (unsigned int k = 1; k<siz; ++k) { ptrd+=off; *ptrd = (T)va_arg(ap,t); } \ va_end(ap); } if (y<_height && z<_depth && c<_spectrum) _cimg_fill1(0,y,z,c,1,_width,int); return *this; } //! Fill pixel values along the X-axis at a specified pixel position \overloading. CImg<T>& fillX(const unsigned int y, const unsigned int z, const unsigned int c, const double a0, ...) { if (y<_height && z<_depth && c<_spectrum) _cimg_fill1(0,y,z,c,1,_width,double); return *this; } //! Fill pixel values along the Y-axis at a specified pixel position. /** \param x X-coordinate of the filled row. \param z Z-coordinate of the filled row. \param c C-coordinate of the filled row. \param a0 First fill value. **/ CImg<T>& fillY(const unsigned int x, const unsigned int z, const unsigned int c, const int a0, ...) { if (x<_width && z<_depth && c<_spectrum) _cimg_fill1(x,0,z,c,_width,_height,int); return *this; } //! Fill pixel values along the Y-axis at a specified pixel position \overloading. CImg<T>& fillY(const unsigned int x, const unsigned int z, const unsigned int c, const double a0, ...) { if (x<_width && z<_depth && c<_spectrum) _cimg_fill1(x,0,z,c,_width,_height,double); return *this; } //! Fill pixel values along the Z-axis at a specified pixel position. /** \param x X-coordinate of the filled slice. \param y Y-coordinate of the filled slice. \param c C-coordinate of the filled slice. \param a0 First fill value. **/ CImg<T>& fillZ(const unsigned int x, const unsigned int y, const unsigned int c, const int a0, ...) { const ulongT wh = (ulongT)_width*_height; if (x<_width && y<_height && c<_spectrum) _cimg_fill1(x,y,0,c,wh,_depth,int); return *this; } //! Fill pixel values along the Z-axis at a specified pixel position \overloading. CImg<T>& fillZ(const unsigned int x, const unsigned int y, const unsigned int c, const double a0, ...) { const ulongT wh = (ulongT)_width*_height; if (x<_width && y<_height && c<_spectrum) _cimg_fill1(x,y,0,c,wh,_depth,double); return *this; } //! Fill pixel values along the C-axis at a specified pixel position. /** \param x X-coordinate of the filled channel. \param y Y-coordinate of the filled channel. \param z Z-coordinate of the filled channel. \param a0 First filling value. **/ CImg<T>& fillC(const unsigned int x, const unsigned int y, const unsigned int z, const int a0, ...) { const ulongT whd = (ulongT)_width*_height*_depth; if (x<_width && y<_height && z<_depth) _cimg_fill1(x,y,z,0,whd,_spectrum,int); return *this; } //! Fill pixel values along the C-axis at a specified pixel position \overloading. CImg<T>& fillC(const unsigned int x, const unsigned int y, const unsigned int z, const double a0, ...) { const ulongT whd = (ulongT)_width*_height*_depth; if (x<_width && y<_height && z<_depth) _cimg_fill1(x,y,z,0,whd,_spectrum,double); return *this; } //! Discard specified sequence of values in the image buffer, along a specific axis. /** \param values Sequence of values to discard. \param axis Axis along which the values are discarded. If set to \c 0 (default value) the method does it for all the buffer values and returns a one-column vector. \note Discarded values will change the image geometry, so the resulting image is returned as a one-column vector. **/ template<typename t> CImg<T>& discard(const CImg<t>& values, const char axis=0) { if (is_empty() || !values) return *this; return get_discard(values,axis).move_to(*this); } template<typename t> CImg<T> get_discard(const CImg<t>& values, const char axis=0) const { CImg<T> res; if (!values) return +*this; if (is_empty()) return res; const ulongT vsiz = values.size(); const char _axis = cimg::lowercase(axis); ulongT j = 0; unsigned int k = 0; int i0 = 0; res.assign(width(),height(),depth(),spectrum()); switch (_axis) { case 'x' : { cimg_forX(*this,i) { if ((*this)(i)!=(T)values[j]) { if (j) --i; res.draw_image(k,get_columns(i0,i)); k+=i - i0 + 1; i0 = i + 1; j = 0; } else { ++j; if (j>=vsiz) { j = 0; i0 = i + 1; } } } if (i0<width()) { res.draw_image(k,get_columns(i0,width() - 1)); k+=width() - i0; } res.resize(k,-100,-100,-100,0); } break; case 'y' : { cimg_forY(*this,i) { if ((*this)(0,i)!=(T)values[j]) { if (j) --i; res.draw_image(0,k,get_rows(i0,i)); k+=i - i0 + 1; i0 = i + 1; j = 0; } else { ++j; if (j>=vsiz) { j = 0; i0 = i + 1; } } } if (i0<height()) { res.draw_image(0,k,get_rows(i0,height() - 1)); k+=height() - i0; } res.resize(-100,k,-100,-100,0); } break; case 'z' : { cimg_forZ(*this,i) { if ((*this)(0,0,i)!=(T)values[j]) { if (j) --i; res.draw_image(0,0,k,get_slices(i0,i)); k+=i - i0 + 1; i0 = i + 1; j = 0; } else { ++j; if (j>=vsiz) { j = 0; i0 = i + 1; } } } if (i0<depth()) { res.draw_image(0,0,k,get_slices(i0,height() - 1)); k+=depth() - i0; } res.resize(-100,-100,k,-100,0); } break; case 'c' : { cimg_forC(*this,i) { if ((*this)(0,0,0,i)!=(T)values[j]) { if (j) --i; res.draw_image(0,0,0,k,get_channels(i0,i)); k+=i - i0 + 1; i0 = i + 1; j = 0; } else { ++j; if (j>=vsiz) { j = 0; i0 = i + 1; } } } if (i0<spectrum()) { res.draw_image(0,0,k,get_channels(i0,height() - 1)); k+=spectrum() - i0; } res.resize(-100,-100,-100,k,0); } break; default : { res.unroll('y'); cimg_foroff(*this,i) { if ((*this)[i]!=(T)values[j]) { if (j) --i; std::memcpy(res._data + k,_data + i0,(i - i0 + 1)*sizeof(T)); k+=i - i0 + 1; i0 = (int)i + 1; j = 0; } else { ++j; if (j>=vsiz) { j = 0; i0 = (int)i + 1; }} } const ulongT siz = size(); if ((ulongT)i0<siz) { std::memcpy(res._data + k,_data + i0,(siz - i0)*sizeof(T)); k+=siz - i0; } res.resize(1,k,1,1,0); } } return res; } //! Discard neighboring duplicates in the image buffer, along the specified axis. CImg<T>& discard(const char axis=0) { return get_discard(axis).move_to(*this); } //! Discard neighboring duplicates in the image buffer, along the specified axis \newinstance. CImg<T> get_discard(const char axis=0) const { CImg<T> res; if (is_empty()) return res; const char _axis = cimg::lowercase(axis); T current = *_data?(T)0:(T)1; int j = 0; res.assign(width(),height(),depth(),spectrum()); switch (_axis) { case 'x' : { cimg_forX(*this,i) if ((*this)(i)!=current) { res.draw_image(j++,get_column(i)); current = (*this)(i); } res.resize(j,-100,-100,-100,0); } break; case 'y' : { cimg_forY(*this,i) if ((*this)(0,i)!=current) { res.draw_image(0,j++,get_row(i)); current = (*this)(0,i); } res.resize(-100,j,-100,-100,0); } break; case 'z' : { cimg_forZ(*this,i) if ((*this)(0,0,i)!=current) { res.draw_image(0,0,j++,get_slice(i)); current = (*this)(0,0,i); } res.resize(-100,-100,j,-100,0); } break; case 'c' : { cimg_forC(*this,i) if ((*this)(0,0,0,i)!=current) { res.draw_image(0,0,0,j++,get_channel(i)); current = (*this)(0,0,0,i); } res.resize(-100,-100,-100,j,0); } break; default : { res.unroll('y'); cimg_foroff(*this,i) if ((*this)[i]!=current) res[j++] = current = (*this)[i]; res.resize(-100,j,-100,-100,0); } } return res; } //! Invert endianness of all pixel values. /** **/ CImg<T>& invert_endianness() { cimg::invert_endianness(_data,size()); return *this; } //! Invert endianness of all pixel values \newinstance. CImg<T> get_invert_endianness() const { return (+*this).invert_endianness(); } //! Fill image with random values in specified range. /** \param val_min Minimal authorized random value. \param val_max Maximal authorized random value. \note Random variables are uniformely distributed in [val_min,val_max]. **/ CImg<T>& rand(const T& val_min, const T& val_max) { const float delta = (float)val_max - (float)val_min + (cimg::type<T>::is_float()?0:1); if (cimg::type<T>::is_float()) cimg_pragma_openmp(parallel cimg_openmp_if_size(size(),524288)) { ulongT rng = (cimg::_rand(),cimg::rng()); #if cimg_use_openmp!=0 rng+=omp_get_thread_num(); #endif cimg_pragma_openmp(for) cimg_rofoff(*this,off) _data[off] = (T)(val_min + delta*cimg::rand(1,&rng)); cimg::srand(rng); } else cimg_pragma_openmp(parallel cimg_openmp_if_size(size(),524288)) { ulongT rng = (cimg::_rand(),cimg::rng()); #if cimg_use_openmp!=0 rng+=omp_get_thread_num(); #endif cimg_pragma_openmp(for) cimg_rofoff(*this,off) _data[off] = std::min(val_max,(T)(val_min + delta*cimg::rand(1,&rng))); cimg::srand(rng); } return *this; } //! Fill image with random values in specified range \newinstance. CImg<T> get_rand(const T& val_min, const T& val_max) const { return (+*this).rand(val_min,val_max); } //! Round pixel values. /** \param y Rounding precision. \param rounding_type Rounding type. Can be: - \c -1: Backward. - \c 0: Nearest. - \c 1: Forward. **/ CImg<T>& round(const double y=1, const int rounding_type=0) { if (y>0) cimg_openmp_for(*this,cimg::round(*ptr,y,rounding_type),8192); return *this; } //! Round pixel values \newinstance. CImg<T> get_round(const double y=1, const unsigned int rounding_type=0) const { return (+*this).round(y,rounding_type); } //! Add random noise to pixel values. /** \param sigma Amplitude of the random additive noise. If \p sigma<0, it stands for a percentage of the global value range. \param noise_type Type of additive noise (can be \p 0=gaussian, \p 1=uniform, \p 2=Salt and Pepper, \p 3=Poisson or \p 4=Rician). \return A reference to the modified image instance. \note - For Poisson noise (\p noise_type=3), parameter \p sigma is ignored, as Poisson noise only depends on the image value itself. - Function \p CImg<T>::get_noise() is also defined. It returns a non-shared modified copy of the image instance. \par Example \code const CImg<float> img("reference.jpg"), res = img.get_noise(40); (img,res.normalize(0,255)).display(); \endcode \image html ref_noise.jpg **/ CImg<T>& noise(const double sigma, const unsigned int noise_type=0) { if (is_empty()) return *this; const Tfloat vmin = (Tfloat)cimg::type<T>::min(), vmax = (Tfloat)cimg::type<T>::max(); Tfloat nsigma = (Tfloat)sigma, m = 0, M = 0; if (nsigma==0 && noise_type!=3) return *this; if (nsigma<0 || noise_type==2) m = (Tfloat)min_max(M); if (nsigma<0) nsigma = (Tfloat)(-nsigma*(M-m)/100.); switch (noise_type) { case 0 : { // Gaussian noise cimg_pragma_openmp(parallel cimg_openmp_if_size(size(),131072)) { ulongT rng = (cimg::_rand(),cimg::rng()); #if cimg_use_openmp!=0 rng+=omp_get_thread_num(); #endif cimg_pragma_openmp(for) cimg_rofoff(*this,off) { Tfloat val = (Tfloat)(_data[off] + nsigma*cimg::grand(&rng)); if (val>vmax) val = vmax; if (val<vmin) val = vmin; _data[off] = (T)val; } cimg::srand(rng); } } break; case 1 : { // Uniform noise cimg_pragma_openmp(parallel cimg_openmp_if_size(size(),131072)) { ulongT rng = (cimg::_rand(),cimg::rng()); #if cimg_use_openmp!=0 rng+=omp_get_thread_num(); #endif cimg_pragma_openmp(for) cimg_rofoff(*this,off) { Tfloat val = (Tfloat)(_data[off] + nsigma*cimg::rand(-1,1,&rng)); if (val>vmax) val = vmax; if (val<vmin) val = vmin; _data[off] = (T)val; } cimg::srand(rng); } } break; case 2 : { // Salt & Pepper noise if (nsigma<0) nsigma = -nsigma; if (M==m) { if (cimg::type<T>::is_float()) { --m; ++M; } else { m = (Tfloat)cimg::type<T>::min(); M = (Tfloat)cimg::type<T>::max(); } } cimg_pragma_openmp(parallel cimg_openmp_if_size(size(),131072)) { ulongT rng = (cimg::_rand(),cimg::rng()); #if cimg_use_openmp!=0 rng+=omp_get_thread_num(); #endif cimg_pragma_openmp(for) cimg_rofoff(*this,off) if (cimg::rand(100,&rng)<nsigma) _data[off] = (T)(cimg::rand(1,&rng)<0.5?M:m); cimg::srand(rng); } } break; case 3 : { // Poisson Noise cimg_pragma_openmp(parallel cimg_openmp_if_size(size(),131072)) { ulongT rng = (cimg::_rand(),cimg::rng()); #if cimg_use_openmp!=0 rng+=omp_get_thread_num(); #endif cimg_pragma_openmp(for) cimg_rofoff(*this,off) _data[off] = (T)cimg::prand(_data[off],&rng); cimg::srand(rng); } } break; case 4 : { // Rice noise const Tfloat sqrt2 = (Tfloat)std::sqrt(2.); cimg_pragma_openmp(parallel cimg_openmp_if_size(size(),131072)) { ulongT rng = (cimg::_rand(),cimg::rng()); #if cimg_use_openmp!=0 rng+=omp_get_thread_num(); #endif cimg_pragma_openmp(for) cimg_rofoff(*this,off) { const Tfloat val0 = (Tfloat)_data[off]/sqrt2, re = (Tfloat)(val0 + nsigma*cimg::grand(&rng)), im = (Tfloat)(val0 + nsigma*cimg::grand(&rng)); Tfloat val = cimg::hypot(re,im); if (val>vmax) val = vmax; if (val<vmin) val = vmin; _data[off] = (T)val; } cimg::srand(rng); } } break; default : throw CImgArgumentException(_cimg_instance "noise(): Invalid specified noise type %d " "(should be { 0=gaussian | 1=uniform | 2=salt&Pepper | 3=poisson }).", cimg_instance, noise_type); } return *this; } //! Add random noise to pixel values \newinstance. CImg<T> get_noise(const double sigma, const unsigned int noise_type=0) const { return (+*this).noise(sigma,noise_type); } //! Linearly normalize pixel values. /** \param min_value Minimum desired value of the resulting image. \param max_value Maximum desired value of the resulting image. \par Example \code const CImg<float> img("reference.jpg"), res = img.get_normalize(160,220); (img,res).display(); \endcode \image html ref_normalize2.jpg **/ CImg<T>& normalize(const T& min_value, const T& max_value) { if (is_empty()) return *this; const T a = min_value<max_value?min_value:max_value, b = min_value<max_value?max_value:min_value; T m, M = max_min(m); const Tfloat fm = (Tfloat)m, fM = (Tfloat)M; if (m==M) return fill(min_value); if (m!=a || M!=b) cimg_rof(*this,ptrd,T) *ptrd = (T)((*ptrd - fm)/(fM - fm)*(b - a) + a); return *this; } //! Linearly normalize pixel values \newinstance. CImg<Tfloat> get_normalize(const T& min_value, const T& max_value) const { return CImg<Tfloat>(*this,false).normalize((Tfloat)min_value,(Tfloat)max_value); } //! Normalize multi-valued pixels of the image instance, with respect to their L2-norm. /** \par Example \code const CImg<float> img("reference.jpg"), res = img.get_normalize(); (img,res.normalize(0,255)).display(); \endcode \image html ref_normalize.jpg **/ CImg<T>& normalize() { const ulongT whd = (ulongT)_width*_height*_depth; cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*512 && _height*_depth>=16)) cimg_forYZ(*this,y,z) { T *ptrd = data(0,y,z,0); cimg_forX(*this,x) { const T *ptrs = ptrd; float n = 0; cimg_forC(*this,c) { n+=cimg::sqr((float)*ptrs); ptrs+=whd; } n = (float)std::sqrt(n); T *_ptrd = ptrd++; if (n>0) cimg_forC(*this,c) { *_ptrd = (T)(*_ptrd/n); _ptrd+=whd; } else cimg_forC(*this,c) { *_ptrd = (T)0; _ptrd+=whd; } } } return *this; } //! Normalize multi-valued pixels of the image instance, with respect to their L2-norm \newinstance. CImg<Tfloat> get_normalize() const { return CImg<Tfloat>(*this,false).normalize(); } //! Compute Lp-norm of each multi-valued pixel of the image instance. /** \param norm_type Type of computed vector norm (can be \p -1=Linf, or \p greater or equal than 0). \par Example \code const CImg<float> img("reference.jpg"), res = img.get_norm(); (img,res.normalize(0,255)).display(); \endcode \image html ref_norm.jpg **/ CImg<T>& norm(const int norm_type=2) { if (_spectrum==1 && norm_type) return abs(); return get_norm(norm_type).move_to(*this); } //! Compute L2-norm of each multi-valued pixel of the image instance \newinstance. CImg<Tfloat> get_norm(const int norm_type=2) const { if (is_empty()) return *this; if (_spectrum==1 && norm_type) return get_abs(); const ulongT whd = (ulongT)_width*_height*_depth; CImg<Tfloat> res(_width,_height,_depth); switch (norm_type) { case -1 : { // Linf-norm cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*512 && _height*_depth>=16)) cimg_forYZ(*this,y,z) { const ulongT off = (ulongT)offset(0,y,z); const T *ptrs = _data + off; Tfloat *ptrd = res._data + off; cimg_forX(*this,x) { Tfloat n = 0; const T *_ptrs = ptrs++; cimg_forC(*this,c) { const Tfloat val = (Tfloat)cimg::abs(*_ptrs); if (val>n) n = val; _ptrs+=whd; } *(ptrd++) = n; } } } break; case 0 : { // L0-norm cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*512 && _height*_depth>=16)) cimg_forYZ(*this,y,z) { const ulongT off = (ulongT)offset(0,y,z); const T *ptrs = _data + off; Tfloat *ptrd = res._data + off; cimg_forX(*this,x) { unsigned int n = 0; const T *_ptrs = ptrs++; cimg_forC(*this,c) { n+=*_ptrs==0?0:1; _ptrs+=whd; } *(ptrd++) = (Tfloat)n; } } } break; case 1 : { // L1-norm cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*512 && _height*_depth>=16)) cimg_forYZ(*this,y,z) { const ulongT off = (ulongT)offset(0,y,z); const T *ptrs = _data + off; Tfloat *ptrd = res._data + off; cimg_forX(*this,x) { Tfloat n = 0; const T *_ptrs = ptrs++; cimg_forC(*this,c) { n+=cimg::abs(*_ptrs); _ptrs+=whd; } *(ptrd++) = n; } } } break; case 2 : { // L2-norm cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*512 && _height*_depth>=16)) cimg_forYZ(*this,y,z) { const ulongT off = (ulongT)offset(0,y,z); const T *ptrs = _data + off; Tfloat *ptrd = res._data + off; cimg_forX(*this,x) { Tfloat n = 0; const T *_ptrs = ptrs++; cimg_forC(*this,c) { n+=cimg::sqr((Tfloat)*_ptrs); _ptrs+=whd; } *(ptrd++) = (Tfloat)std::sqrt((Tfloat)n); } } } break; default : { // Linf-norm cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*512 && _height*_depth>=16)) cimg_forYZ(*this,y,z) { const ulongT off = (ulongT)offset(0,y,z); const T *ptrs = _data + off; Tfloat *ptrd = res._data + off; cimg_forX(*this,x) { Tfloat n = 0; const T *_ptrs = ptrs++; cimg_forC(*this,c) { n+=std::pow(cimg::abs((Tfloat)*_ptrs),(Tfloat)norm_type); _ptrs+=whd; } *(ptrd++) = (Tfloat)std::pow((Tfloat)n,1/(Tfloat)norm_type); } } } } return res; } //! Cut pixel values in specified range. /** \param min_value Minimum desired value of the resulting image. \param max_value Maximum desired value of the resulting image. \par Example \code const CImg<float> img("reference.jpg"), res = img.get_cut(160,220); (img,res).display(); \endcode \image html ref_cut.jpg **/ CImg<T>& cut(const T& min_value, const T& max_value) { if (is_empty()) return *this; const T a = min_value<max_value?min_value:max_value, b = min_value<max_value?max_value:min_value; cimg_openmp_for(*this,cimg::cut(*ptr,a,b),32768); return *this; } //! Cut pixel values in specified range \newinstance. CImg<T> get_cut(const T& min_value, const T& max_value) const { return (+*this).cut(min_value,max_value); } //! Uniformly quantize pixel values. /** \param nb_levels Number of quantization levels. \param keep_range Tells if resulting values keep the same range as the original ones. \par Example \code const CImg<float> img("reference.jpg"), res = img.get_quantize(4); (img,res).display(); \endcode \image html ref_quantize.jpg **/ CImg<T>& quantize(const unsigned int nb_levels, const bool keep_range=true) { if (!nb_levels) throw CImgArgumentException(_cimg_instance "quantize(): Invalid quantization request with 0 values.", cimg_instance); if (is_empty()) return *this; Tfloat m, M = (Tfloat)max_min(m), range = M - m; if (range>0) { if (keep_range) cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),32768)) cimg_rofoff(*this,off) { const unsigned int val = (unsigned int)((_data[off] - m)*nb_levels/range); _data[off] = (T)(m + std::min(val,nb_levels - 1)*range/nb_levels); } else cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),32768)) cimg_rofoff(*this,off) { const unsigned int val = (unsigned int)((_data[off] - m)*nb_levels/range); _data[off] = (T)std::min(val,nb_levels - 1); } } return *this; } //! Uniformly quantize pixel values \newinstance. CImg<T> get_quantize(const unsigned int n, const bool keep_range=true) const { return (+*this).quantize(n,keep_range); } //! Threshold pixel values. /** \param value Threshold value \param soft_threshold Tells if soft thresholding must be applied (instead of hard one). \param strict_threshold Tells if threshold value is strict. \par Example \code const CImg<float> img("reference.jpg"), res = img.get_threshold(128); (img,res.normalize(0,255)).display(); \endcode \image html ref_threshold.jpg **/ CImg<T>& threshold(const T& value, const bool soft_threshold=false, const bool strict_threshold=false) { if (is_empty()) return *this; if (strict_threshold) { if (soft_threshold) cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),32768)) cimg_rofoff(*this,off) { const T v = _data[off]; _data[off] = v>value?(T)(v-value):v<-(float)value?(T)(v + value):(T)0; } else cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),65536)) cimg_rofoff(*this,off) _data[off] = _data[off]>value?(T)1:(T)0; } else { if (soft_threshold) cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),32768)) cimg_rofoff(*this,off) { const T v = _data[off]; _data[off] = v>=value?(T)(v-value):v<=-(float)value?(T)(v + value):(T)0; } else cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),65536)) cimg_rofoff(*this,off) _data[off] = _data[off]>=value?(T)1:(T)0; } return *this; } //! Threshold pixel values \newinstance. CImg<T> get_threshold(const T& value, const bool soft_threshold=false, const bool strict_threshold=false) const { return (+*this).threshold(value,soft_threshold,strict_threshold); } //! Compute the histogram of pixel values. /** \param nb_levels Number of desired histogram levels. \param min_value Minimum pixel value considered for the histogram computation. All pixel values lower than \p min_value will not be counted. \param max_value Maximum pixel value considered for the histogram computation. All pixel values higher than \p max_value will not be counted. \note - The histogram H of an image I is the 1D function where H(x) counts the number of occurrences of the value x in the image I. - The resulting histogram is always defined in 1D. Histograms of multi-valued images are not multi-dimensional. \par Example \code const CImg<float> img = CImg<float>("reference.jpg").histogram(256); img.display_graph(0,3); \endcode \image html ref_histogram.jpg **/ CImg<T>& histogram(const unsigned int nb_levels, const T& min_value, const T& max_value) { return get_histogram(nb_levels,min_value,max_value).move_to(*this); } //! Compute the histogram of pixel values \overloading. CImg<T>& histogram(const unsigned int nb_levels) { return get_histogram(nb_levels).move_to(*this); } //! Compute the histogram of pixel values \newinstance. CImg<ulongT> get_histogram(const unsigned int nb_levels, const T& min_value, const T& max_value) const { if (!nb_levels || is_empty()) return CImg<ulongT>(); const double vmin = (double)(min_value<max_value?min_value:max_value), vmax = (double)(min_value<max_value?max_value:min_value); CImg<ulongT> res(nb_levels,1,1,1,0); cimg_rof(*this,ptrs,T) { const T val = *ptrs; if (val>=vmin && val<=vmax) ++res[val==vmax?nb_levels - 1:(unsigned int)((val - vmin)*nb_levels/(vmax - vmin))]; } return res; } //! Compute the histogram of pixel values \newinstance. CImg<ulongT> get_histogram(const unsigned int nb_levels) const { if (!nb_levels || is_empty()) return CImg<ulongT>(); T vmax = 0, vmin = min_max(vmax); return get_histogram(nb_levels,vmin,vmax); } //! Equalize histogram of pixel values. /** \param nb_levels Number of histogram levels used for the equalization. \param min_value Minimum pixel value considered for the histogram computation. All pixel values lower than \p min_value will not be counted. \param max_value Maximum pixel value considered for the histogram computation. All pixel values higher than \p max_value will not be counted. \par Example \code const CImg<float> img("reference.jpg"), res = img.get_equalize(256); (img,res).display(); \endcode \image html ref_equalize.jpg **/ CImg<T>& equalize(const unsigned int nb_levels, const T& min_value, const T& max_value) { if (!nb_levels || is_empty()) return *this; const T vmin = min_value<max_value?min_value:max_value, vmax = min_value<max_value?max_value:min_value; CImg<ulongT> hist = get_histogram(nb_levels,vmin,vmax); ulongT cumul = 0; cimg_forX(hist,pos) { cumul+=hist[pos]; hist[pos] = cumul; } if (!cumul) cumul = 1; cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),1048576)) cimg_rofoff(*this,off) { const int pos = (int)((_data[off] - vmin)*(nb_levels - 1.)/(vmax - vmin)); if (pos>=0 && pos<(int)nb_levels) _data[off] = (T)(vmin + (vmax - vmin)*hist[pos]/cumul); } return *this; } //! Equalize histogram of pixel values \overloading. CImg<T>& equalize(const unsigned int nb_levels) { if (!nb_levels || is_empty()) return *this; T vmax = 0, vmin = min_max(vmax); return equalize(nb_levels,vmin,vmax); } //! Equalize histogram of pixel values \newinstance. CImg<T> get_equalize(const unsigned int nblevels, const T& val_min, const T& val_max) const { return (+*this).equalize(nblevels,val_min,val_max); } //! Equalize histogram of pixel values \newinstance. CImg<T> get_equalize(const unsigned int nblevels) const { return (+*this).equalize(nblevels); } //! Index multi-valued pixels regarding to a specified colormap. /** \param colormap Multi-valued colormap used as the basis for multi-valued pixel indexing. \param dithering Level of dithering (0=disable, 1=standard level). \param map_indexes Tell if the values of the resulting image are the colormap indices or the colormap vectors. \note - \p img.index(colormap,dithering,1) is equivalent to <tt>img.index(colormap,dithering,0).map(colormap)</tt>. \par Example \code const CImg<float> img("reference.jpg"), colormap(3,1,1,3, 0,128,255, 0,128,255, 0,128,255); const CImg<float> res = img.get_index(colormap,1,true); (img,res).display(); \endcode \image html ref_index.jpg **/ template<typename t> CImg<T>& index(const CImg<t>& colormap, const float dithering=1, const bool map_indexes=false) { return get_index(colormap,dithering,map_indexes).move_to(*this); } //! Index multi-valued pixels regarding to a specified colormap \newinstance. template<typename t> CImg<typename CImg<t>::Tuint> get_index(const CImg<t>& colormap, const float dithering=1, const bool map_indexes=true) const { if (colormap._spectrum!=_spectrum) throw CImgArgumentException(_cimg_instance "index(): Instance and specified colormap (%u,%u,%u,%u,%p) " "have incompatible dimensions.", cimg_instance, colormap._width,colormap._height,colormap._depth,colormap._spectrum,colormap._data); typedef typename CImg<t>::Tuint tuint; if (is_empty()) return CImg<tuint>(); const ulongT whd = (ulongT)_width*_height*_depth, pwhd = (ulongT)colormap._width*colormap._height*colormap._depth; CImg<tuint> res(_width,_height,_depth,map_indexes?_spectrum:1); if (dithering>0) { // Dithered versions tuint *ptrd = res._data; const float ndithering = cimg::cut(dithering,0,1)/16; Tfloat valm = 0, valM = (Tfloat)max_min(valm); if (valm==valM && valm>=0 && valM<=255) { valm = 0; valM = 255; } CImg<Tfloat> cache = get_crop(-1,0,0,0,_width,1,0,_spectrum - 1); Tfloat *cache_current = cache.data(1,0,0,0), *cache_next = cache.data(1,1,0,0); const ulongT cwhd = (ulongT)cache._width*cache._height*cache._depth; switch (_spectrum) { case 1 : { // Optimized for scalars cimg_forYZ(*this,y,z) { if (y<height() - 2) { Tfloat *ptrc0 = cache_next; const T *ptrs0 = data(0,y + 1,z,0); cimg_forX(*this,x) *(ptrc0++) = (Tfloat)*(ptrs0++); } Tfloat *ptrs0 = cache_current, *ptrsn0 = cache_next; cimg_forX(*this,x) { const Tfloat _val0 = (Tfloat)*ptrs0, val0 = _val0<valm?valm:_val0>valM?valM:_val0; Tfloat distmin = cimg::type<Tfloat>::max(); const t *ptrmin0 = colormap._data; for (const t *ptrp0 = colormap._data, *ptrp_end = ptrp0 + pwhd; ptrp0<ptrp_end; ) { const Tfloat pval0 = (Tfloat)*(ptrp0++) - val0, dist = pval0*pval0; if (dist<distmin) { ptrmin0 = ptrp0 - 1; distmin = dist; } } const Tfloat err0 = ((*(ptrs0++)=val0) - (Tfloat)*ptrmin0)*ndithering; *ptrs0+=7*err0; *(ptrsn0 - 1)+=3*err0; *(ptrsn0++)+=5*err0; *ptrsn0+=err0; if (map_indexes) *(ptrd++) = (tuint)*ptrmin0; else *(ptrd++) = (tuint)(ptrmin0 - colormap._data); } cimg::swap(cache_current,cache_next); } } break; case 2 : { // Optimized for 2D vectors tuint *ptrd1 = ptrd + whd; cimg_forYZ(*this,y,z) { if (y<height() - 2) { Tfloat *ptrc0 = cache_next, *ptrc1 = ptrc0 + cwhd; const T *ptrs0 = data(0,y + 1,z,0), *ptrs1 = ptrs0 + whd; cimg_forX(*this,x) { *(ptrc0++) = (Tfloat)*(ptrs0++); *(ptrc1++) = (Tfloat)*(ptrs1++); } } Tfloat *ptrs0 = cache_current, *ptrs1 = ptrs0 + cwhd, *ptrsn0 = cache_next, *ptrsn1 = ptrsn0 + cwhd; cimg_forX(*this,x) { const Tfloat _val0 = (Tfloat)*ptrs0, val0 = _val0<valm?valm:_val0>valM?valM:_val0, _val1 = (Tfloat)*ptrs1, val1 = _val1<valm?valm:_val1>valM?valM:_val1; Tfloat distmin = cimg::type<Tfloat>::max(); const t *ptrmin0 = colormap._data; for (const t *ptrp0 = colormap._data, *ptrp1 = ptrp0 + pwhd, *ptrp_end = ptrp1; ptrp0<ptrp_end; ) { const Tfloat pval0 = (Tfloat)*(ptrp0++) - val0, pval1 = (Tfloat)*(ptrp1++) - val1, dist = pval0*pval0 + pval1*pval1; if (dist<distmin) { ptrmin0 = ptrp0 - 1; distmin = dist; } } const t *const ptrmin1 = ptrmin0 + pwhd; const Tfloat err0 = ((*(ptrs0++)=val0) - (Tfloat)*ptrmin0)*ndithering, err1 = ((*(ptrs1++)=val1) - (Tfloat)*ptrmin1)*ndithering; *ptrs0+=7*err0; *ptrs1+=7*err1; *(ptrsn0 - 1)+=3*err0; *(ptrsn1 - 1)+=3*err1; *(ptrsn0++)+=5*err0; *(ptrsn1++)+=5*err1; *ptrsn0+=err0; *ptrsn1+=err1; if (map_indexes) { *(ptrd++) = (tuint)*ptrmin0; *(ptrd1++) = (tuint)*ptrmin1; } else *(ptrd++) = (tuint)(ptrmin0 - colormap._data); } cimg::swap(cache_current,cache_next); } } break; case 3 : { // Optimized for 3D vectors (colors) tuint *ptrd1 = ptrd + whd, *ptrd2 = ptrd1 + whd; cimg_forYZ(*this,y,z) { if (y<height() - 2) { Tfloat *ptrc0 = cache_next, *ptrc1 = ptrc0 + cwhd, *ptrc2 = ptrc1 + cwhd; const T *ptrs0 = data(0,y + 1,z,0), *ptrs1 = ptrs0 + whd, *ptrs2 = ptrs1 + whd; cimg_forX(*this,x) { *(ptrc0++) = (Tfloat)*(ptrs0++); *(ptrc1++) = (Tfloat)*(ptrs1++); *(ptrc2++) = (Tfloat)*(ptrs2++); } } Tfloat *ptrs0 = cache_current, *ptrs1 = ptrs0 + cwhd, *ptrs2 = ptrs1 + cwhd, *ptrsn0 = cache_next, *ptrsn1 = ptrsn0 + cwhd, *ptrsn2 = ptrsn1 + cwhd; cimg_forX(*this,x) { const Tfloat _val0 = (Tfloat)*ptrs0, val0 = _val0<valm?valm:_val0>valM?valM:_val0, _val1 = (Tfloat)*ptrs1, val1 = _val1<valm?valm:_val1>valM?valM:_val1, _val2 = (Tfloat)*ptrs2, val2 = _val2<valm?valm:_val2>valM?valM:_val2; Tfloat distmin = cimg::type<Tfloat>::max(); const t *ptrmin0 = colormap._data; for (const t *ptrp0 = colormap._data, *ptrp1 = ptrp0 + pwhd, *ptrp2 = ptrp1 + pwhd, *ptrp_end = ptrp1; ptrp0<ptrp_end; ) { const Tfloat pval0 = (Tfloat)*(ptrp0++) - val0, pval1 = (Tfloat)*(ptrp1++) - val1, pval2 = (Tfloat)*(ptrp2++) - val2, dist = pval0*pval0 + pval1*pval1 + pval2*pval2; if (dist<distmin) { ptrmin0 = ptrp0 - 1; distmin = dist; } } const t *const ptrmin1 = ptrmin0 + pwhd, *const ptrmin2 = ptrmin1 + pwhd; const Tfloat err0 = ((*(ptrs0++)=val0) - (Tfloat)*ptrmin0)*ndithering, err1 = ((*(ptrs1++)=val1) - (Tfloat)*ptrmin1)*ndithering, err2 = ((*(ptrs2++)=val2) - (Tfloat)*ptrmin2)*ndithering; *ptrs0+=7*err0; *ptrs1+=7*err1; *ptrs2+=7*err2; *(ptrsn0 - 1)+=3*err0; *(ptrsn1 - 1)+=3*err1; *(ptrsn2 - 1)+=3*err2; *(ptrsn0++)+=5*err0; *(ptrsn1++)+=5*err1; *(ptrsn2++)+=5*err2; *ptrsn0+=err0; *ptrsn1+=err1; *ptrsn2+=err2; if (map_indexes) { *(ptrd++) = (tuint)*ptrmin0; *(ptrd1++) = (tuint)*ptrmin1; *(ptrd2++) = (tuint)*ptrmin2; } else *(ptrd++) = (tuint)(ptrmin0 - colormap._data); } cimg::swap(cache_current,cache_next); } } break; default : // Generic version cimg_forYZ(*this,y,z) { if (y<height() - 2) { Tfloat *ptrc = cache_next; cimg_forC(*this,c) { Tfloat *_ptrc = ptrc; const T *_ptrs = data(0,y + 1,z,c); cimg_forX(*this,x) *(_ptrc++) = (Tfloat)*(_ptrs++); ptrc+=cwhd; } } Tfloat *ptrs = cache_current, *ptrsn = cache_next; cimg_forX(*this,x) { Tfloat distmin = cimg::type<Tfloat>::max(); const t *ptrmin = colormap._data; for (const t *ptrp = colormap._data, *ptrp_end = ptrp + pwhd; ptrp<ptrp_end; ++ptrp) { Tfloat dist = 0; Tfloat *_ptrs = ptrs; const t *_ptrp = ptrp; cimg_forC(*this,c) { const Tfloat _val = *_ptrs, val = _val<valm?valm:_val>valM?valM:_val; dist+=cimg::sqr((*_ptrs=val) - (Tfloat)*_ptrp); _ptrs+=cwhd; _ptrp+=pwhd; } if (dist<distmin) { ptrmin = ptrp; distmin = dist; } } const t *_ptrmin = ptrmin; Tfloat *_ptrs = ptrs++, *_ptrsn = (ptrsn++) - 1; cimg_forC(*this,c) { const Tfloat err = (*(_ptrs++) - (Tfloat)*_ptrmin)*ndithering; *_ptrs+=7*err; *(_ptrsn++)+=3*err; *(_ptrsn++)+=5*err; *_ptrsn+=err; _ptrmin+=pwhd; _ptrs+=cwhd - 1; _ptrsn+=cwhd - 2; } if (map_indexes) { tuint *_ptrd = ptrd++; cimg_forC(*this,c) { *_ptrd = (tuint)*ptrmin; _ptrd+=whd; ptrmin+=pwhd; } } else *(ptrd++) = (tuint)(ptrmin - colormap._data); } cimg::swap(cache_current,cache_next); } } } else { // Non-dithered versions switch (_spectrum) { case 1 : { // Optimized for scalars cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*64 && _height*_depth>=16 && pwhd>=16)) cimg_forYZ(*this,y,z) { tuint *ptrd = res.data(0,y,z); for (const T *ptrs0 = data(0,y,z), *ptrs_end = ptrs0 + _width; ptrs0<ptrs_end; ) { const Tfloat val0 = (Tfloat)*(ptrs0++); Tfloat distmin = cimg::type<Tfloat>::max(); const t *ptrmin0 = colormap._data; for (const t *ptrp0 = colormap._data, *ptrp_end = ptrp0 + pwhd; ptrp0<ptrp_end; ) { const Tfloat pval0 = (Tfloat)*(ptrp0++) - val0, dist = pval0*pval0; if (dist<distmin) { ptrmin0 = ptrp0 - 1; distmin = dist; } } if (map_indexes) *(ptrd++) = (tuint)*ptrmin0; else *(ptrd++) = (tuint)(ptrmin0 - colormap._data); } } } break; case 2 : { // Optimized for 2D vectors cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*64 && _height*_depth>=16 && pwhd>=16)) cimg_forYZ(*this,y,z) { tuint *ptrd = res.data(0,y,z), *ptrd1 = ptrd + whd; for (const T *ptrs0 = data(0,y,z), *ptrs1 = ptrs0 + whd, *ptrs_end = ptrs0 + _width; ptrs0<ptrs_end; ) { const Tfloat val0 = (Tfloat)*(ptrs0++), val1 = (Tfloat)*(ptrs1++); Tfloat distmin = cimg::type<Tfloat>::max(); const t *ptrmin0 = colormap._data; for (const t *ptrp0 = colormap._data, *ptrp1 = ptrp0 + pwhd, *ptrp_end = ptrp1; ptrp0<ptrp_end; ) { const Tfloat pval0 = (Tfloat)*(ptrp0++) - val0, pval1 = (Tfloat)*(ptrp1++) - val1, dist = pval0*pval0 + pval1*pval1; if (dist<distmin) { ptrmin0 = ptrp0 - 1; distmin = dist; } } if (map_indexes) { *(ptrd++) = (tuint)*ptrmin0; *(ptrd1++) = (tuint)*(ptrmin0 + pwhd); } else *(ptrd++) = (tuint)(ptrmin0 - colormap._data); } } } break; case 3 : { // Optimized for 3D vectors (colors) cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*64 && _height*_depth>=16 && pwhd>=16)) cimg_forYZ(*this,y,z) { tuint *ptrd = res.data(0,y,z), *ptrd1 = ptrd + whd, *ptrd2 = ptrd1 + whd; for (const T *ptrs0 = data(0,y,z), *ptrs1 = ptrs0 + whd, *ptrs2 = ptrs1 + whd, *ptrs_end = ptrs0 + _width; ptrs0<ptrs_end; ) { const Tfloat val0 = (Tfloat)*(ptrs0++), val1 = (Tfloat)*(ptrs1++), val2 = (Tfloat)*(ptrs2++); Tfloat distmin = cimg::type<Tfloat>::max(); const t *ptrmin0 = colormap._data; for (const t *ptrp0 = colormap._data, *ptrp1 = ptrp0 + pwhd, *ptrp2 = ptrp1 + pwhd, *ptrp_end = ptrp1; ptrp0<ptrp_end; ) { const Tfloat pval0 = (Tfloat)*(ptrp0++) - val0, pval1 = (Tfloat)*(ptrp1++) - val1, pval2 = (Tfloat)*(ptrp2++) - val2, dist = pval0*pval0 + pval1*pval1 + pval2*pval2; if (dist<distmin) { ptrmin0 = ptrp0 - 1; distmin = dist; } } if (map_indexes) { *(ptrd++) = (tuint)*ptrmin0; *(ptrd1++) = (tuint)*(ptrmin0 + pwhd); *(ptrd2++) = (tuint)*(ptrmin0 + 2*pwhd); } else *(ptrd++) = (tuint)(ptrmin0 - colormap._data); } } } break; default : // Generic version cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*64 && _height*_depth>=16 && pwhd>=16)) cimg_forYZ(*this,y,z) { tuint *ptrd = res.data(0,y,z); for (const T *ptrs = data(0,y,z), *ptrs_end = ptrs + _width; ptrs<ptrs_end; ++ptrs) { Tfloat distmin = cimg::type<Tfloat>::max(); const t *ptrmin = colormap._data; for (const t *ptrp = colormap._data, *ptrp_end = ptrp + pwhd; ptrp<ptrp_end; ++ptrp) { Tfloat dist = 0; const T *_ptrs = ptrs; const t *_ptrp = ptrp; cimg_forC(*this,c) { dist+=cimg::sqr((Tfloat)*_ptrs - (Tfloat)*_ptrp); _ptrs+=whd; _ptrp+=pwhd; } if (dist<distmin) { ptrmin = ptrp; distmin = dist; } } if (map_indexes) { tuint *_ptrd = ptrd++; cimg_forC(*this,c) { *_ptrd = (tuint)*ptrmin; _ptrd+=whd; ptrmin+=pwhd; } } else *(ptrd++) = (tuint)(ptrmin - colormap._data); } } } } return res; } //! Map predefined colormap on the scalar (indexed) image instance. /** \param colormap Multi-valued colormap used for mapping the indexes. \param boundary_conditions The border condition type { 0=dirichlet | 1=neumann | 2=periodic | 3=mirror }. \par Example \code const CImg<float> img("reference.jpg"), colormap1(3,1,1,3, 0,128,255, 0,128,255, 0,128,255), colormap2(3,1,1,3, 255,0,0, 0,255,0, 0,0,255), res = img.get_index(colormap1,0).map(colormap2); (img,res).display(); \endcode \image html ref_map.jpg **/ template<typename t> CImg<T>& map(const CImg<t>& colormap, const unsigned int boundary_conditions=0) { return get_map(colormap,boundary_conditions).move_to(*this); } //! Map predefined colormap on the scalar (indexed) image instance \newinstance. template<typename t> CImg<t> get_map(const CImg<t>& colormap, const unsigned int boundary_conditions=0) const { const ulongT whd = (ulongT)_width*_height*_depth, siz = size(), cwhd = (ulongT)colormap._width*colormap._height*colormap._depth, cwhd2 = 2*cwhd; CImg<t> res(_width,_height,_depth,_spectrum*colormap._spectrum); switch (colormap._spectrum) { case 1 : { // Optimized for scalars switch (boundary_conditions) { case 3 : // Mirror cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)siz; ++off) { const ulongT ind = ((ulongT)_data[off])%cwhd2; res[off] = colormap[ind<cwhd?ind:cwhd2 - ind - 1]; } break; case 2 : // Periodic cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)siz; ++off) { const ulongT ind = (ulongT)_data[off]; res[off] = colormap[ind%cwhd]; } break; case 1 : // Neumann cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)siz; ++off) { const longT ind = (longT)_data[off]; res[off] = colormap[cimg::cut(ind,(longT)0,(longT)cwhd - 1)]; } break; default : // Dirichlet cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)siz; ++off) { const ulongT ind = (ulongT)_data[off]; res[off] = ind<cwhd?colormap[ind]:(t)0; } } } break; case 2 : { // Optimized for 2D vectors const t *const ptrp0 = colormap._data, *const ptrp1 = ptrp0 + cwhd; switch (boundary_conditions) { case 3 : // Mirror cimg_forC(*this,c) { t *const ptrd0 = res.data(0,0,0,2*c), *const ptrd1 = ptrd0 + whd; const T *const ptrs = data(0,0,0,c); cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)whd; ++off) { const ulongT _ind = ((ulongT)ptrs[off])%cwhd2, ind = _ind<cwhd?_ind:cwhd2 - _ind - 1; ptrd0[off] = ptrp0[ind]; ptrd1[off] = ptrp1[ind]; } } break; case 2 : // Periodic cimg_forC(*this,c) { t *const ptrd0 = res.data(0,0,0,2*c), *const ptrd1 = ptrd0 + whd; const T *const ptrs = data(0,0,0,c); cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)whd; ++off) { const ulongT ind = ((ulongT)ptrs[off])%cwhd; ptrd0[off] = ptrp0[ind]; ptrd1[off] = ptrp1[ind]; } } break; case 1 : // Neumann cimg_forC(*this,c) { t *const ptrd0 = res.data(0,0,0,2*c), *const ptrd1 = ptrd0 + whd; const T *const ptrs = data(0,0,0,c); cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)whd; ++off) { const longT ind = cimg::cut((longT)ptrs[off],(longT)0,(longT)cwhd - 1); ptrd0[off] = ptrp0[ind]; ptrd1[off] = ptrp1[ind]; } } break; default : // Dirichlet cimg_forC(*this,c) { t *const ptrd0 = res.data(0,0,0,2*c), *const ptrd1 = ptrd0 + whd; const T *const ptrs = data(0,0,0,c); cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)whd; ++off) { const ulongT ind = (ulongT)ptrs[off]; if (ind<cwhd) { ptrd0[off] = ptrp0[ind]; ptrd1[off] = ptrp1[ind]; } else ptrd0[off] = ptrd1[off] = (t)0; } } } } break; case 3 : { // Optimized for 3D vectors (colors) const t *const ptrp0 = colormap._data, *ptrp1 = ptrp0 + cwhd, *ptrp2 = ptrp0 + 2*cwhd; switch (boundary_conditions) { case 3 : // Mirror cimg_forC(*this,c) { t *const ptrd0 = res.data(0,0,0,3*c), *const ptrd1 = ptrd0 + whd, *const ptrd2 = ptrd1 + whd; const T *const ptrs = data(0,0,0,c); cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)whd; ++off) { const ulongT _ind = ((ulongT)ptrs[off])%cwhd2, ind = _ind<cwhd?_ind:cwhd2 - _ind - 1; ptrd0[off] = ptrp0[ind]; ptrd1[off] = ptrp1[ind]; ptrd2[off] = ptrp2[ind]; } } break; case 2 : // Periodic cimg_forC(*this,c) { t *const ptrd0 = res.data(0,0,0,3*c), *const ptrd1 = ptrd0 + whd, *const ptrd2 = ptrd1 + whd; const T *const ptrs = data(0,0,0,c); cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)whd; ++off) { const ulongT ind = ((ulongT)ptrs[off])%cwhd; ptrd0[off] = ptrp0[ind]; ptrd1[off] = ptrp1[ind]; ptrd2[off] = ptrp2[ind]; } } break; case 1 : // Neumann cimg_forC(*this,c) { t *const ptrd0 = res.data(0,0,0,3*c), *const ptrd1 = ptrd0 + whd, *const ptrd2 = ptrd1 + whd; const T *const ptrs = data(0,0,0,c); cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)whd; ++off) { const longT ind = cimg::cut((longT)ptrs[off],(longT)0,(longT)cwhd - 1); ptrd0[off] = ptrp0[ind]; ptrd1[off] = ptrp1[ind]; ptrd2[off] = ptrp2[ind]; } } break; default : // Dirichlet cimg_forC(*this,c) { t *const ptrd0 = res.data(0,0,0,3*c), *const ptrd1 = ptrd0 + whd, *const ptrd2 = ptrd1 + whd; const T *const ptrs = data(0,0,0,c); cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)whd; ++off) { const ulongT ind = (ulongT)ptrs[off]; if (ind<cwhd) { ptrd0[off] = ptrp0[ind]; ptrd1[off] = ptrp1[ind]; ptrd2[off] = ptrp2[ind]; } else ptrd0[off] = ptrd1[off] = ptrd2[off] = (t)0; } } } } break; default : { // Generic version switch (boundary_conditions) { case 3 : // Mirror cimg_forC(*this,c) { t *const ptrd = res.data(0,0,0,colormap._spectrum*c); const T *const ptrs = data(0,0,0,c); cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)whd; ++off) { const ulongT _ind = ((ulongT)ptrs[off])%cwhd, ind = _ind<cwhd?_ind:cwhd2 - _ind - 1; t *const _ptrd = ptrd + off; const t *const ptrp = &colormap[ind]; cimg_forC(colormap,k) _ptrd[k*whd] = ptrp[k*cwhd]; } } break; case 2 : // Periodic cimg_forC(*this,c) { t *const ptrd = res.data(0,0,0,colormap._spectrum*c); const T *const ptrs = data(0,0,0,c); cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)whd; ++off) { const ulongT ind = ((ulongT)ptrs[off])%cwhd; t *const _ptrd = ptrd + off; const t *const ptrp = &colormap[ind]; cimg_forC(colormap,k) _ptrd[k*whd] = ptrp[k*cwhd]; } } break; case 1 : // Neumann cimg_forC(*this,c) { t *const ptrd = res.data(0,0,0,colormap._spectrum*c); const T *const ptrs = data(0,0,0,c); cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)whd; ++off) { const longT ind = cimg::cut((longT)ptrs[off],(longT)0,(longT)cwhd - 1); t *const _ptrd = ptrd + off; const t *const ptrp = &colormap[ind]; cimg_forC(colormap,k) _ptrd[k*whd] = ptrp[k*cwhd]; } } break; default : // Dirichlet cimg_forC(*this,c) { t *const ptrd = res.data(0,0,0,colormap._spectrum*c); const T *const ptrs = data(0,0,0,c); cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)whd; ++off) { const ulongT ind = (ulongT)ptrs[off]; t *const _ptrd = ptrd + off; if (ind<cwhd) { const t *const ptrp = &colormap[ind]; cimg_forC(colormap,k) _ptrd[k*whd] = ptrp[k*cwhd]; } else cimg_forC(colormap,k) _ptrd[k*whd] = (t)0; } } } } } return res; } //! Label connected components. /** \param is_high_connectivity Boolean that choose between 4(false)- or 8(true)-connectivity in 2D case, and between 6(false)- or 26(true)-connectivity in 3D case. \param tolerance Tolerance used to determine if two neighboring pixels belong to the same region. \note The algorithm of connected components computation has been primarily done by A. Meijster, according to the publication: 'W.H. Hesselink, A. Meijster, C. Bron, "Concurrent Determination of Connected Components.", In: Science of Computer Programming 41 (2001), pp. 173--194'. The submitted code has then been modified to fit CImg coding style and constraints. **/ CImg<T>& label(const bool is_high_connectivity=false, const Tfloat tolerance=0) { return get_label(is_high_connectivity,tolerance).move_to(*this); } //! Label connected components \newinstance. CImg<ulongT> get_label(const bool is_high_connectivity=false, const Tfloat tolerance=0) const { if (is_empty()) return CImg<ulongT>(); // Create neighborhood tables. int dx[13], dy[13], dz[13], nb = 0; dx[nb] = 1; dy[nb] = 0; dz[nb++] = 0; dx[nb] = 0; dy[nb] = 1; dz[nb++] = 0; if (is_high_connectivity) { dx[nb] = 1; dy[nb] = 1; dz[nb++] = 0; dx[nb] = 1; dy[nb] = -1; dz[nb++] = 0; } if (_depth>1) { // 3D version dx[nb] = 0; dy[nb] = 0; dz[nb++]=1; if (is_high_connectivity) { dx[nb] = 1; dy[nb] = 1; dz[nb++] = -1; dx[nb] = 1; dy[nb] = 0; dz[nb++] = -1; dx[nb] = 1; dy[nb] = -1; dz[nb++] = -1; dx[nb] = 0; dy[nb] = 1; dz[nb++] = -1; dx[nb] = 0; dy[nb] = 1; dz[nb++] = 1; dx[nb] = 1; dy[nb] = -1; dz[nb++] = 1; dx[nb] = 1; dy[nb] = 0; dz[nb++] = 1; dx[nb] = 1; dy[nb] = 1; dz[nb++] = 1; } } return _label(nb,dx,dy,dz,tolerance); } //! Label connected components \overloading. /** \param connectivity_mask Mask of the neighboring pixels. \param tolerance Tolerance used to determine if two neighboring pixels belong to the same region. **/ template<typename t> CImg<T>& label(const CImg<t>& connectivity_mask, const Tfloat tolerance=0) { return get_label(connectivity_mask,tolerance).move_to(*this); } //! Label connected components \newinstance. template<typename t> CImg<ulongT> get_label(const CImg<t>& connectivity_mask, const Tfloat tolerance=0) const { int nb = 0; cimg_for(connectivity_mask,ptr,t) if (*ptr) ++nb; CImg<intT> dx(nb,1,1,1,0), dy(nb,1,1,1,0), dz(nb,1,1,1,0); nb = 0; cimg_forXYZ(connectivity_mask,x,y,z) if ((x || y || z) && connectivity_mask(x,y,z)) { dx[nb] = x; dy[nb] = y; dz[nb++] = z; } return _label(nb,dx,dy,dz,tolerance); } CImg<ulongT> _label(const unsigned int nb, const int *const dx, const int *const dy, const int *const dz, const Tfloat tolerance) const { CImg<ulongT> res(_width,_height,_depth,_spectrum); cimg_forC(*this,c) { CImg<ulongT> _res = res.get_shared_channel(c); // Init label numbers. ulongT *ptr = _res.data(); cimg_foroff(_res,p) *(ptr++) = p; // For each neighbour-direction, label. for (unsigned int n = 0; n<nb; ++n) { const int _dx = dx[n], _dy = dy[n], _dz = dz[n]; if (_dx || _dy || _dz) { const int x0 = _dx<0?-_dx:0, x1 = _dx<0?width():width() - _dx, y0 = _dy<0?-_dy:0, y1 = _dy<0?height():height() - _dy, z0 = _dz<0?-_dz:0, z1 = _dz<0?depth():depth() - _dz; const longT wh = (longT)width()*height(), whd = (longT)width()*height()*depth(), offset = _dz*wh + _dy*width() + _dx; for (longT z = z0, nz = z0 + _dz, pz = z0*wh; z<z1; ++z, ++nz, pz+=wh) { for (longT y = y0, ny = y0 + _dy, py = y0*width() + pz; y<y1; ++y, ++ny, py+=width()) { for (longT x = x0, nx = x0 + _dx, p = x0 + py; x<x1; ++x, ++nx, ++p) { if (cimg::abs((Tfloat)(*this)(x,y,z,c,wh,whd) - (Tfloat)(*this)(nx,ny,nz,c,wh,whd))<=tolerance) { const longT q = p + offset; ulongT xk, yk; for (xk = (ulongT)(p<q?q:p), yk = (ulongT)(p<q?p:q); xk!=yk && _res[xk]!=xk; ) { xk = _res[xk]; if (xk<yk) cimg::swap(xk,yk); } if (xk!=yk) _res[xk] = (ulongT)yk; for (ulongT _p = (ulongT)p; _p!=yk; ) { const ulongT h = _res[_p]; _res[_p] = (ulongT)yk; _p = h; } for (ulongT _q = (ulongT)q; _q!=yk; ) { const ulongT h = _res[_q]; _res[_q] = (ulongT)yk; _q = h; } } } } } } } // Resolve equivalences. ulongT counter = 0; ptr = _res.data(); cimg_foroff(_res,p) { *ptr = *ptr==p?counter++:_res[*ptr]; ++ptr; } } return res; } // [internal] Replace possibly malicious characters for commands to be called by system() by their escaped version. CImg<T>& _system_strescape() { #define cimg_system_strescape(c,s) case c : if (p!=ptrs) CImg<T>(ptrs,(unsigned int)(p-ptrs),1,1,1,false).\ move_to(list); \ CImg<T>(s,(unsigned int)std::strlen(s),1,1,1,false).move_to(list); ptrs = p + 1; break CImgList<T> list; const T *ptrs = _data; cimg_for(*this,p,T) switch ((int)*p) { cimg_system_strescape('\\',"\\\\"); cimg_system_strescape('\"',"\\\""); cimg_system_strescape('!',"\"\\!\""); cimg_system_strescape('`',"\\`"); cimg_system_strescape('$',"\\$"); } if (ptrs<end()) CImg<T>(ptrs,(unsigned int)(end()-ptrs),1,1,1,false).move_to(list); return (list>'x').move_to(*this); } //@} //--------------------------------- // //! \name Color Base Management //@{ //--------------------------------- //! Return colormap \e "default", containing 256 colors entries in RGB. /** \return The following \c 256x1x1x3 colormap is returned: \image html ref_colormap_default.jpg **/ static const CImg<Tuchar>& default_LUT256() { static CImg<Tuchar> colormap; cimg::mutex(8); if (!colormap) { colormap.assign(1,256,1,3); for (unsigned int index = 0, r = 16; r<256; r+=32) for (unsigned int g = 16; g<256; g+=32) for (unsigned int b = 32; b<256; b+=64) { colormap(0,index,0) = (Tuchar)r; colormap(0,index,1) = (Tuchar)g; colormap(0,index++,2) = (Tuchar)b; } } cimg::mutex(8,0); return colormap; } //! Return colormap \e "HSV", containing 256 colors entries in RGB. /** \return The following \c 256x1x1x3 colormap is returned: \image html ref_colormap_hsv.jpg **/ static const CImg<Tuchar>& HSV_LUT256() { static CImg<Tuchar> colormap; cimg::mutex(8); if (!colormap) { CImg<Tint> tmp(1,256,1,3,1); tmp.get_shared_channel(0).sequence(0,359); colormap = tmp.HSVtoRGB(); } cimg::mutex(8,0); return colormap; } //! Return colormap \e "lines", containing 256 colors entries in RGB. /** \return The following \c 256x1x1x3 colormap is returned: \image html ref_colormap_lines.jpg **/ static const CImg<Tuchar>& lines_LUT256() { static const unsigned char pal[] = { 0,255,255,0,0,28,125,125,235,210,186,182,36,0,125,255, 53,32,255,210,89,186,65,45,125,210,210,97,130,194,0,125, 206,53,190,89,255,146,20,190,154,73,255,36,130,215,0,138, 101,210,61,194,206,0,77,45,255,154,174,0,190,239,89,125, 16,36,158,223,117,0,97,69,223,255,40,239,0,0,255,0, 97,170,93,255,138,40,117,210,0,170,53,158,186,255,0,121, 227,121,186,40,20,190,89,255,77,57,130,142,255,73,186,85, 210,8,32,166,243,130,210,40,255,45,61,142,223,49,121,255, 20,162,158,73,89,255,53,138,210,190,57,235,36,73,255,49, 210,0,210,85,57,97,255,121,85,174,40,255,162,178,0,121, 166,125,53,146,166,255,97,121,65,89,235,231,12,170,36,190, 85,255,166,97,198,77,20,146,109,166,255,28,40,202,121,81, 247,0,210,255,49,0,65,255,36,166,93,77,255,85,251,0, 170,178,0,182,255,0,162,16,154,142,162,223,223,0,0,81, 215,4,215,162,215,125,77,206,121,36,125,231,101,16,255,121, 0,57,190,215,65,125,89,142,255,101,73,53,146,223,125,125, 0,255,0,255,0,206,93,138,49,255,0,202,154,85,45,219, 251,53,0,255,40,130,219,158,16,117,186,130,202,49,65,239, 89,202,49,28,247,134,150,0,255,117,202,4,215,81,186,57, 202,89,73,210,40,93,45,251,206,28,223,142,40,134,162,125, 32,247,97,170,0,255,57,134,73,247,162,0,251,40,142,142, 8,166,206,81,154,194,93,89,125,243,28,109,227,0,190,65, 194,186,0,255,53,45,109,186,186,0,255,130,49,170,69,210, 154,0,109,227,45,255,125,105,81,81,255,0,219,134,170,85, 146,28,170,89,223,97,8,210,255,158,49,40,125,174,174,125, 0,227,166,28,219,130,0,93,239,0,85,255,81,178,125,49, 89,255,53,206,73,113,146,255,0,150,36,219,162,0,210,125, 69,134,255,85,40,89,235,49,215,121,0,206,36,223,174,69, 40,182,178,130,69,45,255,210,85,77,215,0,231,146,0,194, 125,174,0,255,40,89,121,206,57,0,206,170,231,150,81,0, 125,255,4,174,4,190,121,255,4,166,109,130,49,239,170,93, 16,174,210,0,255,16,105,158,93,255,0,125,0,255,158,85, 0,255,0,0,255,170,166,61,121,28,198,215,45,243,61,97, 255,53,81,130,109,255,8,117,235,121,40,178,174,0,182,49, 162,121,255,69,206,0,219,125,0,101,255,239,121,32,210,130, 36,231,32,125,81,142,215,158,4,178,255,0,40,251,125,125, 219,89,130,0,166,255,24,65,194,125,255,125,77,125,93,125, 202,24,138,174,178,32,255,85,194,40,85,36,174,174,125,210, 85,255,53,16,93,206,40,130,170,202,93,255,0,24,117,255, 97,113,105,81,255,186,194,57,69,206,57,53,223,190,4,255, 85,97,130,255,85,0,125,223,85,219,0,215,146,77,40,239, 89,36,142,154,227,0,255,85,162,0,162,0,235,178,45,166, 0,247,255,20,69,210,89,142,53,255,40,146,166,255,69,0, 174,154,142,130,162,0,215,255,0,89,40,255,166,61,146,69, 162,40,255,32,121,255,117,178,0,186,206,0,57,215,215,81, 158,77,166,210,77,89,210,0,24,202,150,186,0,255,20,97, 57,170,235,251,16,73,142,251,93,0,202,0,255,121,219,4, 73,219,8,162,206,16,219,93,117,0,255,8,130,174,223,45 }; static const CImg<Tuchar> colormap(pal,1,256,1,3,false); return colormap; } //! Return colormap \e "hot", containing 256 colors entries in RGB. /** \return The following \c 256x1x1x3 colormap is returned: \image html ref_colormap_hot.jpg **/ static const CImg<Tuchar>& hot_LUT256() { static CImg<Tuchar> colormap; cimg::mutex(8); if (!colormap) { colormap.assign(1,4,1,3,(T)0); colormap[1] = colormap[2] = colormap[3] = colormap[6] = colormap[7] = colormap[11] = 255; colormap.resize(1,256,1,3,3); } cimg::mutex(8,0); return colormap; } //! Return colormap \e "cool", containing 256 colors entries in RGB. /** \return The following \c 256x1x1x3 colormap is returned: \image html ref_colormap_cool.jpg **/ static const CImg<Tuchar>& cool_LUT256() { static CImg<Tuchar> colormap; cimg::mutex(8); if (!colormap) colormap.assign(1,2,1,3).fill((T)0,(T)255,(T)255,(T)0,(T)255,(T)255).resize(1,256,1,3,3); cimg::mutex(8,0); return colormap; } //! Return colormap \e "jet", containing 256 colors entries in RGB. /** \return The following \c 256x1x1x3 colormap is returned: \image html ref_colormap_jet.jpg **/ static const CImg<Tuchar>& jet_LUT256() { static CImg<Tuchar> colormap; cimg::mutex(8); if (!colormap) { colormap.assign(1,4,1,3,(T)0); colormap[2] = colormap[3] = colormap[5] = colormap[6] = colormap[8] = colormap[9] = 255; colormap.resize(1,256,1,3,3); } cimg::mutex(8,0); return colormap; } //! Return colormap \e "flag", containing 256 colors entries in RGB. /** \return The following \c 256x1x1x3 colormap is returned: \image html ref_colormap_flag.jpg **/ static const CImg<Tuchar>& flag_LUT256() { static CImg<Tuchar> colormap; cimg::mutex(8); if (!colormap) { colormap.assign(1,4,1,3,(T)0); colormap[0] = colormap[1] = colormap[5] = colormap[9] = colormap[10] = 255; colormap.resize(1,256,1,3,0,2); } cimg::mutex(8,0); return colormap; } //! Return colormap \e "cube", containing 256 colors entries in RGB. /** \return The following \c 256x1x1x3 colormap is returned: \image html ref_colormap_cube.jpg **/ static const CImg<Tuchar>& cube_LUT256() { static CImg<Tuchar> colormap; cimg::mutex(8); if (!colormap) { colormap.assign(1,8,1,3,(T)0); colormap[1] = colormap[3] = colormap[5] = colormap[7] = colormap[10] = colormap[11] = colormap[12] = colormap[13] = colormap[20] = colormap[21] = colormap[22] = colormap[23] = 255; colormap.resize(1,256,1,3,3); } cimg::mutex(8,0); return colormap; } //! Convert pixel values from sRGB to RGB color spaces. CImg<T>& sRGBtoRGB() { if (is_empty()) return *this; cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),32)) cimg_rofoff(*this,off) { const Tfloat sval = (Tfloat)_data[off]/255, val = (Tfloat)(sval<=0.04045f?sval/12.92f:std::pow((sval + 0.055f)/(1.055f),2.4f)); _data[off] = (T)cimg::cut(val*255,0,255); } return *this; } //! Convert pixel values from sRGB to RGB color spaces \newinstance. CImg<Tfloat> get_sRGBtoRGB() const { return CImg<Tfloat>(*this,false).sRGBtoRGB(); } //! Convert pixel values from RGB to sRGB color spaces. CImg<T>& RGBtosRGB() { if (is_empty()) return *this; cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),32)) cimg_rofoff(*this,off) { const Tfloat val = (Tfloat)_data[off]/255, sval = (Tfloat)(val<=0.0031308f?val*12.92f:1.055f*std::pow(val,0.416667f) - 0.055f); _data[off] = (T)cimg::cut(sval*255,0,255); } return *this; } //! Convert pixel values from RGB to sRGB color spaces \newinstance. CImg<Tfloat> get_RGBtosRGB() const { return CImg<Tfloat>(*this,false).RGBtosRGB(); } //! Convert pixel values from RGB to HSI color spaces. CImg<T>& RGBtoHSI() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "RGBtoHSI(): Instance is not a RGB image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,256)) for (longT N = 0; N<whd; ++N) { const Tfloat R = (Tfloat)p1[N], G = (Tfloat)p2[N], B = (Tfloat)p3[N], m = cimg::min(R,G,B), M = cimg::max(R,G,B), C = M - m, sum = R + G + B, H = 60*(C==0?0:M==R?cimg::mod((G - B)/C,(Tfloat)6):M==G?(B - R)/C + 2:(R - G)/C + 4), S = sum<=0?0:1 - 3*m/sum, I = sum/(3*255); p1[N] = (T)H; p2[N] = (T)S; p3[N] = (T)I; } return *this; } //! Convert pixel values from RGB to HSI color spaces \newinstance. CImg<Tfloat> get_RGBtoHSI() const { return CImg<Tfloat>(*this,false).RGBtoHSI(); } //! Convert pixel values from HSI to RGB color spaces. CImg<T>& HSItoRGB() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "HSItoRGB(): Instance is not a HSI image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,256)) for (longT N = 0; N<whd; ++N) { const Tfloat H = cimg::mod((Tfloat)p1[N]/60,(Tfloat)6), S = (Tfloat)p2[N], I = (Tfloat)p3[N], Z = 1 - cimg::abs(cimg::mod(H,(Tfloat)2) - 1), C = I*S/(1 + Z), X = C*Z, m = I*(1 - S)/3; Tfloat R, G, B; switch ((int)H) { case 0 : R = C; G = X; B = 0; break; case 1 : R = X; G = C; B = 0; break; case 2 : R = 0; G = C; B = X; break; case 3 : R = 0; G = X; B = C; break; case 4 : R = X; G = 0; B = C; break; default : R = C; G = 0; B = X; } p1[N] = (T)((R + m)*3*255); p2[N] = (T)((G + m)*3*255); p3[N] = (T)((B + m)*3*255); } return *this; } //! Convert pixel values from HSI to RGB color spaces \newinstance. CImg<Tfloat> get_HSItoRGB() const { return CImg< Tuchar>(*this,false).HSItoRGB(); } //! Convert pixel values from RGB to HSL color spaces. CImg<T>& RGBtoHSL() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "RGBtoHSL(): Instance is not a RGB image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,256)) for (longT N = 0; N<whd; ++N) { const Tfloat R = (Tfloat)p1[N], G = (Tfloat)p2[N], B = (Tfloat)p3[N], m = cimg::min(R,G,B), M = cimg::max(R,G,B), C = M - m, H = 60*(C==0?0:M==R?cimg::mod((G - B)/C,(Tfloat)6):M==G?(B - R)/C + 2:(R - G)/C + 4), L = 0.5f*(m + M)/255, S = L==1 || L==0?0:C/(1 - cimg::abs(2*L - 1))/255; p1[N] = (T)H; p2[N] = (T)S; p3[N] = (T)L; } return *this; } //! Convert pixel values from RGB to HSL color spaces \newinstance. CImg<Tfloat> get_RGBtoHSL() const { return CImg<Tfloat>(*this,false).RGBtoHSL(); } //! Convert pixel values from HSL to RGB color spaces. CImg<T>& HSLtoRGB() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "HSLtoRGB(): Instance is not a HSL image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,256)) for (longT N = 0; N<whd; ++N) { const Tfloat H = cimg::mod((Tfloat)p1[N]/60,(Tfloat)6), S = (Tfloat)p2[N], L = (Tfloat)p3[N], C = (1 - cimg::abs(2*L - 1))*S, X = C*(1 - cimg::abs(cimg::mod(H,(Tfloat)2) - 1)), m = L - C/2; Tfloat R, G, B; switch ((int)H) { case 0 : R = C; G = X; B = 0; break; case 1 : R = X; G = C; B = 0; break; case 2 : R = 0; G = C; B = X; break; case 3 : R = 0; G = X; B = C; break; case 4 : R = X; G = 0; B = C; break; default : R = C; G = 0; B = X; } p1[N] = (T)((R + m)*255); p2[N] = (T)((G + m)*255); p3[N] = (T)((B + m)*255); } return *this; } //! Convert pixel values from HSL to RGB color spaces \newinstance. CImg<Tuchar> get_HSLtoRGB() const { return CImg<Tuchar>(*this,false).HSLtoRGB(); } //! Convert pixel values from RGB to HSV color spaces. CImg<T>& RGBtoHSV() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "RGBtoHSV(): Instance is not a RGB image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,256)) for (longT N = 0; N<whd; ++N) { const Tfloat R = (Tfloat)p1[N], G = (Tfloat)p2[N], B = (Tfloat)p3[N], M = cimg::max(R,G,B), C = M - cimg::min(R,G,B), H = 60*(C==0?0:M==R?cimg::mod((G-B)/C,(Tfloat)6):M==G?(B - R)/C + 2:(R - G)/C + 4), S = M<=0?0:C/M; p1[N] = (T)H; p2[N] = (T)S; p3[N] = (T)(M/255); } return *this; } //! Convert pixel values from RGB to HSV color spaces \newinstance. CImg<Tfloat> get_RGBtoHSV() const { return CImg<Tfloat>(*this,false).RGBtoHSV(); } //! Convert pixel values from HSV to RGB color spaces. CImg<T>& HSVtoRGB() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "HSVtoRGB(): Instance is not a HSV image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,256)) for (longT N = 0; N<whd; ++N) { Tfloat H = cimg::mod((Tfloat)p1[N]/60,(Tfloat)6), S = (Tfloat)p2[N], V = (Tfloat)p3[N], C = V*S, X = C*(1 - cimg::abs(cimg::mod(H,(Tfloat)2) - 1)), m = V - C; Tfloat R, G, B; switch ((int)H) { case 0 : R = C; G = X; B = 0; break; case 1 : R = X; G = C; B = 0; break; case 2 : R = 0; G = C; B = X; break; case 3 : R = 0; G = X; B = C; break; case 4 : R = X; G = 0; B = C; break; default : R = C; G = 0; B = X; } p1[N] = (T)((R + m)*255); p2[N] = (T)((G + m)*255); p3[N] = (T)((B + m)*255); } return *this; } //! Convert pixel values from HSV to RGB color spaces \newinstance. CImg<Tuchar> get_HSVtoRGB() const { return CImg<Tuchar>(*this,false).HSVtoRGB(); } //! Convert pixel values from RGB to YCbCr color spaces. CImg<T>& RGBtoYCbCr() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "RGBtoYCbCr(): Instance is not a RGB image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,512)) for (longT N = 0; N<whd; ++N) { const Tfloat R = (Tfloat)p1[N], G = (Tfloat)p2[N], B = (Tfloat)p3[N], Y = (66*R + 129*G + 25*B + 128)/256 + 16, Cb = (-38*R - 74*G + 112*B + 128)/256 + 128, Cr = (112*R - 94*G - 18*B + 128)/256 + 128; p1[N] = (T)cimg::cut(Y,0,255), p2[N] = (T)cimg::cut(Cb,0,255), p3[N] = (T)cimg::cut(Cr,0,255); } return *this; } //! Convert pixel values from RGB to YCbCr color spaces \newinstance. CImg<Tuchar> get_RGBtoYCbCr() const { return CImg<Tuchar>(*this,false).RGBtoYCbCr(); } //! Convert pixel values from RGB to YCbCr color spaces. CImg<T>& YCbCrtoRGB() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "YCbCrtoRGB(): Instance is not a YCbCr image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,512)) for (longT N = 0; N<whd; ++N) { const Tfloat Y = (Tfloat)p1[N] - 16, Cb = (Tfloat)p2[N] - 128, Cr = (Tfloat)p3[N] - 128, R = (298*Y + 409*Cr + 128)/256, G = (298*Y - 100*Cb - 208*Cr + 128)/256, B = (298*Y + 516*Cb + 128)/256; p1[N] = (T)cimg::cut(R,0,255), p2[N] = (T)cimg::cut(G,0,255), p3[N] = (T)cimg::cut(B,0,255); } return *this; } //! Convert pixel values from RGB to YCbCr color spaces \newinstance. CImg<Tuchar> get_YCbCrtoRGB() const { return CImg<Tuchar>(*this,false).YCbCrtoRGB(); } //! Convert pixel values from RGB to YUV color spaces. CImg<T>& RGBtoYUV() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "RGBtoYUV(): Instance is not a RGB image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,16384)) for (longT N = 0; N<whd; ++N) { const Tfloat R = (Tfloat)p1[N]/255, G = (Tfloat)p2[N]/255, B = (Tfloat)p3[N]/255, Y = 0.299f*R + 0.587f*G + 0.114f*B; p1[N] = (T)Y; p2[N] = (T)(0.492f*(B - Y)); p3[N] = (T)(0.877*(R - Y)); } return *this; } //! Convert pixel values from RGB to YUV color spaces \newinstance. CImg<Tfloat> get_RGBtoYUV() const { return CImg<Tfloat>(*this,false).RGBtoYUV(); } //! Convert pixel values from YUV to RGB color spaces. CImg<T>& YUVtoRGB() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "YUVtoRGB(): Instance is not a YUV image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,16384)) for (longT N = 0; N<whd; ++N) { const Tfloat Y = (Tfloat)p1[N], U = (Tfloat)p2[N], V = (Tfloat)p3[N], R = (Y + 1.140f*V)*255, G = (Y - 0.395f*U - 0.581f*V)*255, B = (Y + 2.032f*U)*255; p1[N] = (T)cimg::cut(R,0,255), p2[N] = (T)cimg::cut(G,0,255), p3[N] = (T)cimg::cut(B,0,255); } return *this; } //! Convert pixel values from YUV to RGB color spaces \newinstance. CImg<Tuchar> get_YUVtoRGB() const { return CImg< Tuchar>(*this,false).YUVtoRGB(); } //! Convert pixel values from RGB to CMY color spaces. CImg<T>& RGBtoCMY() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "RGBtoCMY(): Instance is not a RGB image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,2048)) for (longT N = 0; N<whd; ++N) { const Tfloat R = (Tfloat)p1[N], G = (Tfloat)p2[N], B = (Tfloat)p3[N], C = 255 - R, M = 255 - G, Y = 255 - B; p1[N] = (T)cimg::cut(C,0,255), p2[N] = (T)cimg::cut(M,0,255), p3[N] = (T)cimg::cut(Y,0,255); } return *this; } //! Convert pixel values from RGB to CMY color spaces \newinstance. CImg<Tuchar> get_RGBtoCMY() const { return CImg<Tfloat>(*this,false).RGBtoCMY(); } //! Convert pixel values from CMY to RGB color spaces. CImg<T>& CMYtoRGB() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "CMYtoRGB(): Instance is not a CMY image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,2048)) for (longT N = 0; N<whd; ++N) { const Tfloat C = (Tfloat)p1[N], M = (Tfloat)p2[N], Y = (Tfloat)p3[N], R = 255 - C, G = 255 - M, B = 255 - Y; p1[N] = (T)cimg::cut(R,0,255), p2[N] = (T)cimg::cut(G,0,255), p3[N] = (T)cimg::cut(B,0,255); } return *this; } //! Convert pixel values from CMY to RGB color spaces \newinstance. CImg<Tuchar> get_CMYtoRGB() const { return CImg<Tuchar>(*this,false).CMYtoRGB(); } //! Convert pixel values from CMY to CMYK color spaces. CImg<T>& CMYtoCMYK() { return get_CMYtoCMYK().move_to(*this); } //! Convert pixel values from CMY to CMYK color spaces \newinstance. CImg<Tuchar> get_CMYtoCMYK() const { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "CMYtoCMYK(): Instance is not a CMY image.", cimg_instance); CImg<Tfloat> res(_width,_height,_depth,4); const T *ps1 = data(0,0,0,0), *ps2 = data(0,0,0,1), *ps3 = data(0,0,0,2); Tfloat *pd1 = res.data(0,0,0,0), *pd2 = res.data(0,0,0,1), *pd3 = res.data(0,0,0,2), *pd4 = res.data(0,0,0,3); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,1024)) for (longT N = 0; N<whd; ++N) { Tfloat C = (Tfloat)ps1[N], M = (Tfloat)ps2[N], Y = (Tfloat)ps3[N], K = cimg::min(C,M,Y); if (K>=255) C = M = Y = 0; else { const Tfloat K1 = 255 - K; C = 255*(C - K)/K1; M = 255*(M - K)/K1; Y = 255*(Y - K)/K1; } pd1[N] = (Tfloat)cimg::cut(C,0,255), pd2[N] = (Tfloat)cimg::cut(M,0,255), pd3[N] = (Tfloat)cimg::cut(Y,0,255), pd4[N] = (Tfloat)cimg::cut(K,0,255); } return res; } //! Convert pixel values from CMYK to CMY color spaces. CImg<T>& CMYKtoCMY() { return get_CMYKtoCMY().move_to(*this); } //! Convert pixel values from CMYK to CMY color spaces \newinstance. CImg<Tfloat> get_CMYKtoCMY() const { if (_spectrum!=4) throw CImgInstanceException(_cimg_instance "CMYKtoCMY(): Instance is not a CMYK image.", cimg_instance); CImg<Tfloat> res(_width,_height,_depth,3); const T *ps1 = data(0,0,0,0), *ps2 = data(0,0,0,1), *ps3 = data(0,0,0,2), *ps4 = data(0,0,0,3); Tfloat *pd1 = res.data(0,0,0,0), *pd2 = res.data(0,0,0,1), *pd3 = res.data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,1024)) for (longT N = 0; N<whd; ++N) { const Tfloat C = (Tfloat)ps1[N], M = (Tfloat)ps2[N], Y = (Tfloat)ps3[N], K = (Tfloat)ps4[N], K1 = 1 - K/255, nC = C*K1 + K, nM = M*K1 + K, nY = Y*K1 + K; pd1[N] = (Tfloat)cimg::cut(nC,0,255), pd2[N] = (Tfloat)cimg::cut(nM,0,255), pd3[N] = (Tfloat)cimg::cut(nY,0,255); } return res; } //! Convert pixel values from RGB to XYZ color spaces. /** \param use_D65 Tell to use the D65 illuminant (D50 otherwise). **/ CImg<T>& RGBtoXYZ(const bool use_D65=true) { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "RGBtoXYZ(): Instance is not a RGB image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,2048)) for (longT N = 0; N<whd; ++N) { const Tfloat R = (Tfloat)p1[N]/255, G = (Tfloat)p2[N]/255, B = (Tfloat)p3[N]/255; if (use_D65) { // D65 p1[N] = (T)(0.4124564*R + 0.3575761*G + 0.1804375*B); p2[N] = (T)(0.2126729*R + 0.7151522*G + 0.0721750*B); p3[N] = (T)(0.0193339*R + 0.1191920*G + 0.9503041*B); } else { // D50 p1[N] = (T)(0.43603516*R + 0.38511658*G + 0.14305115*B); p2[N] = (T)(0.22248840*R + 0.71690369*G + 0.06060791*B); p3[N] = (T)(0.01391602*R + 0.09706116*G + 0.71392822*B); } } return *this; } //! Convert pixel values from RGB to XYZ color spaces \newinstance. CImg<Tfloat> get_RGBtoXYZ(const bool use_D65=true) const { return CImg<Tfloat>(*this,false).RGBtoXYZ(use_D65); } //! Convert pixel values from XYZ to RGB color spaces. /** \param use_D65 Tell to use the D65 illuminant (D50 otherwise). **/ CImg<T>& XYZtoRGB(const bool use_D65=true) { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "XYZtoRGB(): Instance is not a XYZ image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,2048)) for (longT N = 0; N<whd; ++N) { const Tfloat X = (Tfloat)p1[N]*255, Y = (Tfloat)p2[N]*255, Z = (Tfloat)p3[N]*255; if (use_D65) { p1[N] = (T)cimg::cut(3.2404542*X - 1.5371385*Y - 0.4985314*Z,0,255); p2[N] = (T)cimg::cut(-0.9692660*X + 1.8760108*Y + 0.0415560*Z,0,255); p3[N] = (T)cimg::cut(0.0556434*X - 0.2040259*Y + 1.0572252*Z,0,255); } else { p1[N] = (T)cimg::cut(3.134274799724*X - 1.617275708956*Y - 0.490724283042*Z,0,255); p2[N] = (T)cimg::cut(-0.978795575994*X + 1.916161689117*Y + 0.033453331711*Z,0,255); p3[N] = (T)cimg::cut(0.071976988401*X - 0.228984974402*Y + 1.405718224383*Z,0,255); } } return *this; } //! Convert pixel values from XYZ to RGB color spaces \newinstance. CImg<Tuchar> get_XYZtoRGB(const bool use_D65=true) const { return CImg<Tuchar>(*this,false).XYZtoRGB(use_D65); } //! Convert pixel values from XYZ to Lab color spaces. CImg<T>& XYZtoLab(const bool use_D65=true) { #define _cimg_Labf(x) (24389*(x)>216?cimg::cbrt(x):(24389*(x)/27 + 16)/116) if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "XYZtoLab(): Instance is not a XYZ image.", cimg_instance); const CImg<Tfloat> white = CImg<Tfloat>(1,1,1,3,255).RGBtoXYZ(use_D65); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,128)) for (longT N = 0; N<whd; ++N) { const Tfloat X = (Tfloat)(p1[N]/white[0]), Y = (Tfloat)(p2[N]/white[1]), Z = (Tfloat)(p3[N]/white[2]), fX = (Tfloat)_cimg_Labf(X), fY = (Tfloat)_cimg_Labf(Y), fZ = (Tfloat)_cimg_Labf(Z); p1[N] = (T)cimg::cut(116*fY - 16,0,100); p2[N] = (T)(500*(fX - fY)); p3[N] = (T)(200*(fY - fZ)); } return *this; } //! Convert pixel values from XYZ to Lab color spaces \newinstance. CImg<Tfloat> get_XYZtoLab(const bool use_D65=true) const { return CImg<Tfloat>(*this,false).XYZtoLab(use_D65); } //! Convert pixel values from Lab to XYZ color spaces. CImg<T>& LabtoXYZ(const bool use_D65=true) { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "LabtoXYZ(): Instance is not a Lab image.", cimg_instance); const CImg<Tfloat> white = CImg<Tfloat>(1,1,1,3,255).RGBtoXYZ(use_D65); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,128)) for (longT N = 0; N<whd; ++N) { const Tfloat L = (Tfloat)p1[N], a = (Tfloat)p2[N], b = (Tfloat)p3[N], cY = (L + 16)/116, cZ = cY - b/200, cX = a/500 + cY, X = (Tfloat)(24389*cX>216?cX*cX*cX:(116*cX - 16)*27/24389), Y = (Tfloat)(27*L>216?cY*cY*cY:27*L/24389), Z = (Tfloat)(24389*cZ>216?cZ*cZ*cZ:(116*cZ - 16)*27/24389); p1[N] = (T)(X*white[0]); p2[N] = (T)(Y*white[1]); p3[N] = (T)(Z*white[2]); } return *this; } //! Convert pixel values from Lab to XYZ color spaces \newinstance. CImg<Tfloat> get_LabtoXYZ(const bool use_D65=true) const { return CImg<Tfloat>(*this,false).LabtoXYZ(use_D65); } //! Convert pixel values from XYZ to xyY color spaces. CImg<T>& XYZtoxyY() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "XYZtoxyY(): Instance is not a XYZ image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,4096)) for (longT N = 0; N<whd; ++N) { const Tfloat X = (Tfloat)p1[N], Y = (Tfloat)p2[N], Z = (Tfloat)p3[N], sum = X + Y + Z, nsum = sum>0?sum:1; p1[N] = (T)(X/nsum); p2[N] = (T)(Y/nsum); p3[N] = (T)Y; } return *this; } //! Convert pixel values from XYZ to xyY color spaces \newinstance. CImg<Tfloat> get_XYZtoxyY() const { return CImg<Tfloat>(*this,false).XYZtoxyY(); } //! Convert pixel values from xyY pixels to XYZ color spaces. CImg<T>& xyYtoXYZ() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "xyYtoXYZ(): Instance is not a xyY image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,4096)) for (longT N = 0; N<whd; ++N) { const Tfloat px = (Tfloat)p1[N], py = (Tfloat)p2[N], Y = (Tfloat)p3[N], ny = py>0?py:1; p1[N] = (T)(px*Y/ny); p2[N] = (T)Y; p3[N] = (T)((1 - px - py)*Y/ny); } return *this; } //! Convert pixel values from xyY pixels to XYZ color spaces \newinstance. CImg<Tfloat> get_xyYtoXYZ() const { return CImg<Tfloat>(*this,false).xyYtoXYZ(); } //! Convert pixel values from RGB to Lab color spaces. CImg<T>& RGBtoLab(const bool use_D65=true) { return RGBtoXYZ(use_D65).XYZtoLab(use_D65); } //! Convert pixel values from RGB to Lab color spaces \newinstance. CImg<Tfloat> get_RGBtoLab(const bool use_D65=true) const { return CImg<Tfloat>(*this,false).RGBtoLab(use_D65); } //! Convert pixel values from Lab to RGB color spaces. CImg<T>& LabtoRGB(const bool use_D65=true) { return LabtoXYZ().XYZtoRGB(use_D65); } //! Convert pixel values from Lab to RGB color spaces \newinstance. CImg<Tuchar> get_LabtoRGB(const bool use_D65=true) const { return CImg<Tuchar>(*this,false).LabtoRGB(use_D65); } //! Convert pixel values from RGB to xyY color spaces. CImg<T>& RGBtoxyY(const bool use_D65=true) { return RGBtoXYZ(use_D65).XYZtoxyY(); } //! Convert pixel values from RGB to xyY color spaces \newinstance. CImg<Tfloat> get_RGBtoxyY(const bool use_D65=true) const { return CImg<Tfloat>(*this,false).RGBtoxyY(use_D65); } //! Convert pixel values from xyY to RGB color spaces. CImg<T>& xyYtoRGB(const bool use_D65=true) { return xyYtoXYZ().XYZtoRGB(use_D65); } //! Convert pixel values from xyY to RGB color spaces \newinstance. CImg<Tuchar> get_xyYtoRGB(const bool use_D65=true) const { return CImg<Tuchar>(*this,false).xyYtoRGB(use_D65); } //! Convert pixel values from RGB to CMYK color spaces. CImg<T>& RGBtoCMYK() { return RGBtoCMY().CMYtoCMYK(); } //! Convert pixel values from RGB to CMYK color spaces \newinstance. CImg<Tfloat> get_RGBtoCMYK() const { return CImg<Tfloat>(*this,false).RGBtoCMYK(); } //! Convert pixel values from CMYK to RGB color spaces. CImg<T>& CMYKtoRGB() { return CMYKtoCMY().CMYtoRGB(); } //! Convert pixel values from CMYK to RGB color spaces \newinstance. CImg<Tuchar> get_CMYKtoRGB() const { return CImg<Tuchar>(*this,false).CMYKtoRGB(); } //@} //------------------------------------------ // //! \name Geometric / Spatial Manipulation //@{ //------------------------------------------ static float _cimg_lanczos(const float x) { if (x<=-2 || x>=2) return 0; const float a = (float)cimg::PI*x, b = 0.5f*a; return (float)(x?std::sin(a)*std::sin(b)/(a*b):1); } //! Resize image to new dimensions. /** \param size_x Number of columns (new size along the X-axis). \param size_y Number of rows (new size along the Y-axis). \param size_z Number of slices (new size along the Z-axis). \param size_c Number of vector-channels (new size along the C-axis). \param interpolation_type Method of interpolation: - -1 = no interpolation: raw memory resizing. - 0 = no interpolation: additional space is filled according to \p boundary_conditions. - 1 = nearest-neighbor interpolation. - 2 = moving average interpolation. - 3 = linear interpolation. - 4 = grid interpolation. - 5 = cubic interpolation. - 6 = lanczos interpolation. \param boundary_conditions Type of boundary conditions used if necessary. \param centering_x Set centering type (only if \p interpolation_type=0). \param centering_y Set centering type (only if \p interpolation_type=0). \param centering_z Set centering type (only if \p interpolation_type=0). \param centering_c Set centering type (only if \p interpolation_type=0). \note If pd[x,y,z,v]<0, it corresponds to a percentage of the original size (the default value is -100). **/ CImg<T>& resize(const int size_x, const int size_y=-100, const int size_z=-100, const int size_c=-100, const int interpolation_type=1, const unsigned int boundary_conditions=0, const float centering_x = 0, const float centering_y = 0, const float centering_z = 0, const float centering_c = 0) { if (!size_x || !size_y || !size_z || !size_c) return assign(); const unsigned int _sx = (unsigned int)(size_x<0?-size_x*width()/100:size_x), _sy = (unsigned int)(size_y<0?-size_y*height()/100:size_y), _sz = (unsigned int)(size_z<0?-size_z*depth()/100:size_z), _sc = (unsigned int)(size_c<0?-size_c*spectrum()/100:size_c), sx = _sx?_sx:1, sy = _sy?_sy:1, sz = _sz?_sz:1, sc = _sc?_sc:1; if (sx==_width && sy==_height && sz==_depth && sc==_spectrum) return *this; if (is_empty()) return assign(sx,sy,sz,sc,(T)0); if (interpolation_type==-1 && sx*sy*sz*sc==size()) { _width = sx; _height = sy; _depth = sz; _spectrum = sc; return *this; } return get_resize(sx,sy,sz,sc,interpolation_type,boundary_conditions, centering_x,centering_y,centering_z,centering_c).move_to(*this); } //! Resize image to new dimensions \newinstance. CImg<T> get_resize(const int size_x, const int size_y = -100, const int size_z = -100, const int size_c = -100, const int interpolation_type=1, const unsigned int boundary_conditions=0, const float centering_x = 0, const float centering_y = 0, const float centering_z = 0, const float centering_c = 0) const { if (centering_x<0 || centering_x>1 || centering_y<0 || centering_y>1 || centering_z<0 || centering_z>1 || centering_c<0 || centering_c>1) throw CImgArgumentException(_cimg_instance "resize(): Specified centering arguments (%g,%g,%g,%g) are outside range [0,1].", cimg_instance, centering_x,centering_y,centering_z,centering_c); if (!size_x || !size_y || !size_z || !size_c) return CImg<T>(); const unsigned int sx = std::max(1U,(unsigned int)(size_x>=0?size_x:-size_x*width()/100)), sy = std::max(1U,(unsigned int)(size_y>=0?size_y:-size_y*height()/100)), sz = std::max(1U,(unsigned int)(size_z>=0?size_z:-size_z*depth()/100)), sc = std::max(1U,(unsigned int)(size_c>=0?size_c:-size_c*spectrum()/100)); if (sx==_width && sy==_height && sz==_depth && sc==_spectrum) return +*this; if (is_empty()) return CImg<T>(sx,sy,sz,sc,(T)0); CImg<T> res; switch (interpolation_type) { // Raw resizing. // case -1 : std::memcpy(res.assign(sx,sy,sz,sc,(T)0)._data,_data,sizeof(T)*std::min(size(),(ulongT)sx*sy*sz*sc)); break; // No interpolation. // case 0 : { const int xc = (int)(centering_x*((int)sx - width())), yc = (int)(centering_y*((int)sy - height())), zc = (int)(centering_z*((int)sz - depth())), cc = (int)(centering_c*((int)sc - spectrum())); switch (boundary_conditions) { case 3 : { // Mirror res.assign(sx,sy,sz,sc); const int w2 = 2*width(), h2 = 2*height(), d2 = 2*depth(), s2 = 2*spectrum(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),65536)) cimg_forXYZC(res,x,y,z,c) { const int mx = cimg::mod(x - xc,w2), my = cimg::mod(y - yc,h2), mz = cimg::mod(z - zc,d2), mc = cimg::mod(c - cc,s2); res(x,y,z,c) = (*this)(mx<width()?mx:w2 - mx - 1, my<height()?my:h2 - my - 1, mz<depth()?mz:d2 - mz - 1, mc<spectrum()?mc:s2 - mc - 1); } } break; case 2 : { // Periodic res.assign(sx,sy,sz,sc); const int x0 = ((int)xc%width()) - width(), y0 = ((int)yc%height()) - height(), z0 = ((int)zc%depth()) - depth(), c0 = ((int)cc%spectrum()) - spectrum(), dx = width(), dy = height(), dz = depth(), dc = spectrum(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),65536)) for (int c = c0; c<(int)sc; c+=dc) for (int z = z0; z<(int)sz; z+=dz) for (int y = y0; y<(int)sy; y+=dy) for (int x = x0; x<(int)sx; x+=dx) res.draw_image(x,y,z,c,*this); } break; case 1 : { // Neumann res.assign(sx,sy,sz,sc).draw_image(xc,yc,zc,cc,*this); CImg<T> sprite; if (xc>0) { // X-backward res.get_crop(xc,yc,zc,cc,xc,yc + height() - 1,zc + depth() - 1,cc + spectrum() - 1).move_to(sprite); for (int x = xc - 1; x>=0; --x) res.draw_image(x,yc,zc,cc,sprite); } if (xc + width()<(int)sx) { // X-forward res.get_crop(xc + width() - 1,yc,zc,cc,xc + width() - 1,yc + height() - 1, zc + depth() - 1,cc + spectrum() - 1).move_to(sprite); for (int x = xc + width(); x<(int)sx; ++x) res.draw_image(x,yc,zc,cc,sprite); } if (yc>0) { // Y-backward res.get_crop(0,yc,zc,cc,sx - 1,yc,zc + depth() - 1,cc + spectrum() - 1).move_to(sprite); for (int y = yc - 1; y>=0; --y) res.draw_image(0,y,zc,cc,sprite); } if (yc + height()<(int)sy) { // Y-forward res.get_crop(0,yc + height() - 1,zc,cc,sx - 1,yc + height() - 1, zc + depth() - 1,cc + spectrum() - 1).move_to(sprite); for (int y = yc + height(); y<(int)sy; ++y) res.draw_image(0,y,zc,cc,sprite); } if (zc>0) { // Z-backward res.get_crop(0,0,zc,cc,sx - 1,sy - 1,zc,cc + spectrum() - 1).move_to(sprite); for (int z = zc - 1; z>=0; --z) res.draw_image(0,0,z,cc,sprite); } if (zc + depth()<(int)sz) { // Z-forward res.get_crop(0,0,zc +depth() - 1,cc,sx - 1,sy - 1,zc + depth() - 1,cc + spectrum() - 1).move_to(sprite); for (int z = zc + depth(); z<(int)sz; ++z) res.draw_image(0,0,z,cc,sprite); } if (cc>0) { // C-backward res.get_crop(0,0,0,cc,sx - 1,sy - 1,sz - 1,cc).move_to(sprite); for (int c = cc - 1; c>=0; --c) res.draw_image(0,0,0,c,sprite); } if (cc + spectrum()<(int)sc) { // C-forward res.get_crop(0,0,0,cc + spectrum() - 1,sx - 1,sy - 1,sz - 1,cc + spectrum() - 1).move_to(sprite); for (int c = cc + spectrum(); c<(int)sc; ++c) res.draw_image(0,0,0,c,sprite); } } break; default : // Dirichlet res.assign(sx,sy,sz,sc,(T)0).draw_image(xc,yc,zc,cc,*this); } break; } break; // Nearest neighbor interpolation. // case 1 : { res.assign(sx,sy,sz,sc); CImg<ulongT> off_x(sx), off_y(sy + 1), off_z(sz + 1), off_c(sc + 1); const ulongT wh = (ulongT)_width*_height, whd = (ulongT)_width*_height*_depth, sxy = (ulongT)sx*sy, sxyz = (ulongT)sx*sy*sz, one = (ulongT)1; if (sx==_width) off_x.fill(1); else { ulongT *poff_x = off_x._data, curr = 0; cimg_forX(res,x) { const ulongT old = curr; curr = (x + one)*_width/sx; *(poff_x++) = curr - old; } } if (sy==_height) off_y.fill(_width); else { ulongT *poff_y = off_y._data, curr = 0; cimg_forY(res,y) { const ulongT old = curr; curr = (y + one)*_height/sy; *(poff_y++) = _width*(curr - old); } *poff_y = 0; } if (sz==_depth) off_z.fill(wh); else { ulongT *poff_z = off_z._data, curr = 0; cimg_forZ(res,z) { const ulongT old = curr; curr = (z + one)*_depth/sz; *(poff_z++) = wh*(curr - old); } *poff_z = 0; } if (sc==_spectrum) off_c.fill(whd); else { ulongT *poff_c = off_c._data, curr = 0; cimg_forC(res,c) { const ulongT old = curr; curr = (c + one)*_spectrum/sc; *(poff_c++) = whd*(curr - old); } *poff_c = 0; } T *ptrd = res._data; const T* ptrc = _data; const ulongT *poff_c = off_c._data; for (unsigned int c = 0; c<sc; ) { const T *ptrz = ptrc; const ulongT *poff_z = off_z._data; for (unsigned int z = 0; z<sz; ) { const T *ptry = ptrz; const ulongT *poff_y = off_y._data; for (unsigned int y = 0; y<sy; ) { const T *ptrx = ptry; const ulongT *poff_x = off_x._data; cimg_forX(res,x) { *(ptrd++) = *ptrx; ptrx+=*(poff_x++); } ++y; ulongT dy = *(poff_y++); for ( ; !dy && y<dy; std::memcpy(ptrd,ptrd - sx,sizeof(T)*sx), ++y, ptrd+=sx, dy = *(poff_y++)) {} ptry+=dy; } ++z; ulongT dz = *(poff_z++); for ( ; !dz && z<dz; std::memcpy(ptrd,ptrd - sxy,sizeof(T)*sxy), ++z, ptrd+=sxy, dz = *(poff_z++)) {} ptrz+=dz; } ++c; ulongT dc = *(poff_c++); for ( ; !dc && c<dc; std::memcpy(ptrd,ptrd - sxyz,sizeof(T)*sxyz), ++c, ptrd+=sxyz, dc = *(poff_c++)) {} ptrc+=dc; } } break; // Moving average. // case 2 : { bool instance_first = true; if (sx!=_width) { CImg<Tfloat> tmp(sx,_height,_depth,_spectrum,0); for (unsigned int a = _width*sx, b = _width, c = sx, s = 0, t = 0; a; ) { const unsigned int d = std::min(b,c); a-=d; b-=d; c-=d; cimg_forYZC(tmp,y,z,v) tmp(t,y,z,v)+=(Tfloat)(*this)(s,y,z,v)*d; if (!b) { cimg_forYZC(tmp,y,z,v) tmp(t,y,z,v)/=_width; ++t; b = _width; } if (!c) { ++s; c = sx; } } tmp.move_to(res); instance_first = false; } if (sy!=_height) { CImg<Tfloat> tmp(sx,sy,_depth,_spectrum,0); for (unsigned int a = _height*sy, b = _height, c = sy, s = 0, t = 0; a; ) { const unsigned int d = std::min(b,c); a-=d; b-=d; c-=d; if (instance_first) cimg_forXZC(tmp,x,z,v) tmp(x,t,z,v)+=(Tfloat)(*this)(x,s,z,v)*d; else cimg_forXZC(tmp,x,z,v) tmp(x,t,z,v)+=(Tfloat)res(x,s,z,v)*d; if (!b) { cimg_forXZC(tmp,x,z,v) tmp(x,t,z,v)/=_height; ++t; b = _height; } if (!c) { ++s; c = sy; } } tmp.move_to(res); instance_first = false; } if (sz!=_depth) { CImg<Tfloat> tmp(sx,sy,sz,_spectrum,0); for (unsigned int a = _depth*sz, b = _depth, c = sz, s = 0, t = 0; a; ) { const unsigned int d = std::min(b,c); a-=d; b-=d; c-=d; if (instance_first) cimg_forXYC(tmp,x,y,v) tmp(x,y,t,v)+=(Tfloat)(*this)(x,y,s,v)*d; else cimg_forXYC(tmp,x,y,v) tmp(x,y,t,v)+=(Tfloat)res(x,y,s,v)*d; if (!b) { cimg_forXYC(tmp,x,y,v) tmp(x,y,t,v)/=_depth; ++t; b = _depth; } if (!c) { ++s; c = sz; } } tmp.move_to(res); instance_first = false; } if (sc!=_spectrum) { CImg<Tfloat> tmp(sx,sy,sz,sc,0); for (unsigned int a = _spectrum*sc, b = _spectrum, c = sc, s = 0, t = 0; a; ) { const unsigned int d = std::min(b,c); a-=d; b-=d; c-=d; if (instance_first) cimg_forXYZ(tmp,x,y,z) tmp(x,y,z,t)+=(Tfloat)(*this)(x,y,z,s)*d; else cimg_forXYZ(tmp,x,y,z) tmp(x,y,z,t)+=(Tfloat)res(x,y,z,s)*d; if (!b) { cimg_forXYZ(tmp,x,y,z) tmp(x,y,z,t)/=_spectrum; ++t; b = _spectrum; } if (!c) { ++s; c = sc; } } tmp.move_to(res); instance_first = false; } } break; // Linear interpolation. // case 3 : { CImg<uintT> off(cimg::max(sx,sy,sz,sc)); CImg<doubleT> foff(off._width); CImg<T> resx, resy, resz, resc; double curr, old; if (sx!=_width) { if (_width==1) get_resize(sx,_height,_depth,_spectrum,1).move_to(resx); else if (_width>sx) get_resize(sx,_height,_depth,_spectrum,2).move_to(resx); else { const double fx = (!boundary_conditions && sx>_width)?(sx>1?(_width - 1.)/(sx - 1):0): (double)_width/sx; resx.assign(sx,_height,_depth,_spectrum); curr = old = 0; { unsigned int *poff = off._data; double *pfoff = foff._data; cimg_forX(resx,x) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr = std::min(width() - 1.,curr + fx); *(poff++) = (unsigned int)curr - (unsigned int)old; } } cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(resx.size(),65536)) cimg_forYZC(resx,y,z,c) { const T *ptrs = data(0,y,z,c), *const ptrsmax = ptrs + _width - 1; T *ptrd = resx.data(0,y,z,c); const unsigned int *poff = off._data; const double *pfoff = foff._data; cimg_forX(resx,x) { const double alpha = *(pfoff++); const T val1 = *ptrs, val2 = ptrs<ptrsmax?*(ptrs + 1):val1; *(ptrd++) = (T)((1 - alpha)*val1 + alpha*val2); ptrs+=*(poff++); } } } } else resx.assign(*this,true); if (sy!=_height) { if (_height==1) resx.get_resize(sx,sy,_depth,_spectrum,1).move_to(resy); else { if (_height>sy) resx.get_resize(sx,sy,_depth,_spectrum,2).move_to(resy); else { const double fy = (!boundary_conditions && sy>_height)?(sy>1?(_height - 1.)/(sy - 1):0): (double)_height/sy; resy.assign(sx,sy,_depth,_spectrum); curr = old = 0; { unsigned int *poff = off._data; double *pfoff = foff._data; cimg_forY(resy,y) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr = std::min(height() - 1.,curr + fy); *(poff++) = sx*((unsigned int)curr - (unsigned int)old); } } cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(resy.size(),65536)) cimg_forXZC(resy,x,z,c) { const T *ptrs = resx.data(x,0,z,c), *const ptrsmax = ptrs + (_height - 1)*sx; T *ptrd = resy.data(x,0,z,c); const unsigned int *poff = off._data; const double *pfoff = foff._data; cimg_forY(resy,y) { const double alpha = *(pfoff++); const T val1 = *ptrs, val2 = ptrs<ptrsmax?*(ptrs + sx):val1; *ptrd = (T)((1 - alpha)*val1 + alpha*val2); ptrd+=sx; ptrs+=*(poff++); } } } } resx.assign(); } else resy.assign(resx,true); if (sz!=_depth) { if (_depth==1) resy.get_resize(sx,sy,sz,_spectrum,1).move_to(resz); else { if (_depth>sz) resy.get_resize(sx,sy,sz,_spectrum,2).move_to(resz); else { const double fz = (!boundary_conditions && sz>_depth)?(sz>1?(_depth - 1.)/(sz - 1):0): (double)_depth/sz; const unsigned int sxy = sx*sy; resz.assign(sx,sy,sz,_spectrum); curr = old = 0; { unsigned int *poff = off._data; double *pfoff = foff._data; cimg_forZ(resz,z) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr = std::min(depth() - 1.,curr + fz); *(poff++) = sxy*((unsigned int)curr - (unsigned int)old); } } cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(resz.size(),65536)) cimg_forXYC(resz,x,y,c) { const T *ptrs = resy.data(x,y,0,c), *const ptrsmax = ptrs + (_depth - 1)*sxy; T *ptrd = resz.data(x,y,0,c); const unsigned int *poff = off._data; const double *pfoff = foff._data; cimg_forZ(resz,z) { const double alpha = *(pfoff++); const T val1 = *ptrs, val2 = ptrs<ptrsmax?*(ptrs + sxy):val1; *ptrd = (T)((1 - alpha)*val1 + alpha*val2); ptrd+=sxy; ptrs+=*(poff++); } } } } resy.assign(); } else resz.assign(resy,true); if (sc!=_spectrum) { if (_spectrum==1) resz.get_resize(sx,sy,sz,sc,1).move_to(resc); else { if (_spectrum>sc) resz.get_resize(sx,sy,sz,sc,2).move_to(resc); else { const double fc = (!boundary_conditions && sc>_spectrum)?(sc>1?(_spectrum - 1.)/(sc - 1):0): (double)_spectrum/sc; const unsigned int sxyz = sx*sy*sz; resc.assign(sx,sy,sz,sc); curr = old = 0; { unsigned int *poff = off._data; double *pfoff = foff._data; cimg_forC(resc,c) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr = std::min(spectrum() - 1.,curr + fc); *(poff++) = sxyz*((unsigned int)curr - (unsigned int)old); } } cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(resc.size(),65536)) cimg_forXYZ(resc,x,y,z) { const T *ptrs = resz.data(x,y,z,0), *const ptrsmax = ptrs + (_spectrum - 1)*sxyz; T *ptrd = resc.data(x,y,z,0); const unsigned int *poff = off._data; const double *pfoff = foff._data; cimg_forC(resc,c) { const double alpha = *(pfoff++); const T val1 = *ptrs, val2 = ptrs<ptrsmax?*(ptrs + sxyz):val1; *ptrd = (T)((1 - alpha)*val1 + alpha*val2); ptrd+=sxyz; ptrs+=*(poff++); } } } } resz.assign(); } else resc.assign(resz,true); return resc._is_shared?(resz._is_shared?(resy._is_shared?(resx._is_shared?(+(*this)):resx):resy):resz):resc; } break; // Grid interpolation. // case 4 : { CImg<T> resx, resy, resz, resc; if (sx!=_width) { if (sx<_width) get_resize(sx,_height,_depth,_spectrum,1).move_to(resx); else { resx.assign(sx,_height,_depth,_spectrum,(T)0); const int dx = (int)(2*sx), dy = 2*width(); int err = (int)(dy + centering_x*(sx*dy/width() - dy)), xs = 0; cimg_forX(resx,x) if ((err-=dy)<=0) { cimg_forYZC(resx,y,z,c) resx(x,y,z,c) = (*this)(xs,y,z,c); ++xs; err+=dx; } } } else resx.assign(*this,true); if (sy!=_height) { if (sy<_height) resx.get_resize(sx,sy,_depth,_spectrum,1).move_to(resy); else { resy.assign(sx,sy,_depth,_spectrum,(T)0); const int dx = (int)(2*sy), dy = 2*height(); int err = (int)(dy + centering_y*(sy*dy/height() - dy)), ys = 0; cimg_forY(resy,y) if ((err-=dy)<=0) { cimg_forXZC(resy,x,z,c) resy(x,y,z,c) = resx(x,ys,z,c); ++ys; err+=dx; } } resx.assign(); } else resy.assign(resx,true); if (sz!=_depth) { if (sz<_depth) resy.get_resize(sx,sy,sz,_spectrum,1).move_to(resz); else { resz.assign(sx,sy,sz,_spectrum,(T)0); const int dx = (int)(2*sz), dy = 2*depth(); int err = (int)(dy + centering_z*(sz*dy/depth() - dy)), zs = 0; cimg_forZ(resz,z) if ((err-=dy)<=0) { cimg_forXYC(resz,x,y,c) resz(x,y,z,c) = resy(x,y,zs,c); ++zs; err+=dx; } } resy.assign(); } else resz.assign(resy,true); if (sc!=_spectrum) { if (sc<_spectrum) resz.get_resize(sx,sy,sz,sc,1).move_to(resc); else { resc.assign(sx,sy,sz,sc,(T)0); const int dx = (int)(2*sc), dy = 2*spectrum(); int err = (int)(dy + centering_c*(sc*dy/spectrum() - dy)), cs = 0; cimg_forC(resc,c) if ((err-=dy)<=0) { cimg_forXYZ(resc,x,y,z) resc(x,y,z,c) = resz(x,y,z,cs); ++cs; err+=dx; } } resz.assign(); } else resc.assign(resz,true); return resc._is_shared?(resz._is_shared?(resy._is_shared?(resx._is_shared?(+(*this)):resx):resy):resz):resc; } break; // Cubic interpolation. // case 5 : { const Tfloat vmin = (Tfloat)cimg::type<T>::min(), vmax = (Tfloat)cimg::type<T>::max(); CImg<uintT> off(cimg::max(sx,sy,sz,sc)); CImg<doubleT> foff(off._width); CImg<T> resx, resy, resz, resc; double curr, old; if (sx!=_width) { if (_width==1) get_resize(sx,_height,_depth,_spectrum,1).move_to(resx); else { if (_width>sx) get_resize(sx,_height,_depth,_spectrum,2).move_to(resx); else { const double fx = (!boundary_conditions && sx>_width)?(sx>1?(_width - 1.)/(sx - 1):0): (double)_width/sx; resx.assign(sx,_height,_depth,_spectrum); curr = old = 0; { unsigned int *poff = off._data; double *pfoff = foff._data; cimg_forX(resx,x) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr = std::min(width() - 1.,curr + fx); *(poff++) = (unsigned int)curr - (unsigned int)old; } } cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(resx.size(),65536)) cimg_forYZC(resx,y,z,c) { const T *const ptrs0 = data(0,y,z,c), *ptrs = ptrs0, *const ptrsmax = ptrs + (_width - 2); T *ptrd = resx.data(0,y,z,c); const unsigned int *poff = off._data; const double *pfoff = foff._data; cimg_forX(resx,x) { const double t = *(pfoff++), val1 = (double)*ptrs, val0 = ptrs>ptrs0?(double)*(ptrs - 1):val1, val2 = ptrs<=ptrsmax?(double)*(ptrs + 1):val1, val3 = ptrs<ptrsmax?(double)*(ptrs + 2):val2, val = val1 + 0.5f*(t*(-val0 + val2) + t*t*(2*val0 - 5*val1 + 4*val2 - val3) + t*t*t*(-val0 + 3*val1 - 3*val2 + val3)); *(ptrd++) = (T)(val<vmin?vmin:val>vmax?vmax:val); ptrs+=*(poff++); } } } } } else resx.assign(*this,true); if (sy!=_height) { if (_height==1) resx.get_resize(sx,sy,_depth,_spectrum,1).move_to(resy); else { if (_height>sy) resx.get_resize(sx,sy,_depth,_spectrum,2).move_to(resy); else { const double fy = (!boundary_conditions && sy>_height)?(sy>1?(_height - 1.)/(sy - 1):0): (double)_height/sy; resy.assign(sx,sy,_depth,_spectrum); curr = old = 0; { unsigned int *poff = off._data; double *pfoff = foff._data; cimg_forY(resy,y) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr = std::min(height() - 1.,curr + fy); *(poff++) = sx*((unsigned int)curr - (unsigned int)old); } } cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(resy.size(),65536)) cimg_forXZC(resy,x,z,c) { const T *const ptrs0 = resx.data(x,0,z,c), *ptrs = ptrs0, *const ptrsmax = ptrs + (_height - 2)*sx; T *ptrd = resy.data(x,0,z,c); const unsigned int *poff = off._data; const double *pfoff = foff._data; cimg_forY(resy,y) { const double t = *(pfoff++), val1 = (double)*ptrs, val0 = ptrs>ptrs0?(double)*(ptrs - sx):val1, val2 = ptrs<=ptrsmax?(double)*(ptrs + sx):val1, val3 = ptrs<ptrsmax?(double)*(ptrs + 2*sx):val2, val = val1 + 0.5f*(t*(-val0 + val2) + t*t*(2*val0 - 5*val1 + 4*val2 - val3) + t*t*t*(-val0 + 3*val1 - 3*val2 + val3)); *ptrd = (T)(val<vmin?vmin:val>vmax?vmax:val); ptrd+=sx; ptrs+=*(poff++); } } } } resx.assign(); } else resy.assign(resx,true); if (sz!=_depth) { if (_depth==1) resy.get_resize(sx,sy,sz,_spectrum,1).move_to(resz); else { if (_depth>sz) resy.get_resize(sx,sy,sz,_spectrum,2).move_to(resz); else { const double fz = (!boundary_conditions && sz>_depth)?(sz>1?(_depth - 1.)/(sz - 1):0): (double)_depth/sz; const unsigned int sxy = sx*sy; resz.assign(sx,sy,sz,_spectrum); curr = old = 0; { unsigned int *poff = off._data; double *pfoff = foff._data; cimg_forZ(resz,z) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr = std::min(depth() - 1.,curr + fz); *(poff++) = sxy*((unsigned int)curr - (unsigned int)old); } } cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(resz.size(),65536)) cimg_forXYC(resz,x,y,c) { const T *const ptrs0 = resy.data(x,y,0,c), *ptrs = ptrs0, *const ptrsmax = ptrs + (_depth - 2)*sxy; T *ptrd = resz.data(x,y,0,c); const unsigned int *poff = off._data; const double *pfoff = foff._data; cimg_forZ(resz,z) { const double t = *(pfoff++), val1 = (double)*ptrs, val0 = ptrs>ptrs0?(double)*(ptrs - sxy):val1, val2 = ptrs<=ptrsmax?(double)*(ptrs + sxy):val1, val3 = ptrs<ptrsmax?(double)*(ptrs + 2*sxy):val2, val = val1 + 0.5f*(t*(-val0 + val2) + t*t*(2*val0 - 5*val1 + 4*val2 - val3) + t*t*t*(-val0 + 3*val1 - 3*val2 + val3)); *ptrd = (T)(val<vmin?vmin:val>vmax?vmax:val); ptrd+=sxy; ptrs+=*(poff++); } } } } resy.assign(); } else resz.assign(resy,true); if (sc!=_spectrum) { if (_spectrum==1) resz.get_resize(sx,sy,sz,sc,1).move_to(resc); else { if (_spectrum>sc) resz.get_resize(sx,sy,sz,sc,2).move_to(resc); else { const double fc = (!boundary_conditions && sc>_spectrum)?(sc>1?(_spectrum - 1.)/(sc - 1):0): (double)_spectrum/sc; const unsigned int sxyz = sx*sy*sz; resc.assign(sx,sy,sz,sc); curr = old = 0; { unsigned int *poff = off._data; double *pfoff = foff._data; cimg_forC(resc,c) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr = std::min(spectrum() - 1.,curr + fc); *(poff++) = sxyz*((unsigned int)curr - (unsigned int)old); } } cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(resc.size(),65536)) cimg_forXYZ(resc,x,y,z) { const T *const ptrs0 = resz.data(x,y,z,0), *ptrs = ptrs0, *const ptrsmax = ptrs + (_spectrum - 2)*sxyz; T *ptrd = resc.data(x,y,z,0); const unsigned int *poff = off._data; const double *pfoff = foff._data; cimg_forC(resc,c) { const double t = *(pfoff++), val1 = (double)*ptrs, val0 = ptrs>ptrs0?(double)*(ptrs - sxyz):val1, val2 = ptrs<=ptrsmax?(double)*(ptrs + sxyz):val1, val3 = ptrs<ptrsmax?(double)*(ptrs + 2*sxyz):val2, val = val1 + 0.5f*(t*(-val0 + val2) + t*t*(2*val0 - 5*val1 + 4*val2 - val3) + t*t*t*(-val0 + 3*val1 - 3*val2 + val3)); *ptrd = (T)(val<vmin?vmin:val>vmax?vmax:val); ptrd+=sxyz; ptrs+=*(poff++); } } } } resz.assign(); } else resc.assign(resz,true); return resc._is_shared?(resz._is_shared?(resy._is_shared?(resx._is_shared?(+(*this)):resx):resy):resz):resc; } break; // Lanczos interpolation. // case 6 : { const double vmin = (double)cimg::type<T>::min(), vmax = (double)cimg::type<T>::max(); CImg<uintT> off(cimg::max(sx,sy,sz,sc)); CImg<doubleT> foff(off._width); CImg<T> resx, resy, resz, resc; double curr, old; if (sx!=_width) { if (_width==1) get_resize(sx,_height,_depth,_spectrum,1).move_to(resx); else { if (_width>sx) get_resize(sx,_height,_depth,_spectrum,2).move_to(resx); else { const double fx = (!boundary_conditions && sx>_width)?(sx>1?(_width - 1.)/(sx - 1):0): (double)_width/sx; resx.assign(sx,_height,_depth,_spectrum); curr = old = 0; { unsigned int *poff = off._data; double *pfoff = foff._data; cimg_forX(resx,x) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr = std::min(width() - 1.,curr + fx); *(poff++) = (unsigned int)curr - (unsigned int)old; } } cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(resx.size(),65536)) cimg_forYZC(resx,y,z,c) { const T *const ptrs0 = data(0,y,z,c), *ptrs = ptrs0, *const ptrsmin = ptrs0 + 1, *const ptrsmax = ptrs0 + (_width - 2); T *ptrd = resx.data(0,y,z,c); const unsigned int *poff = off._data; const double *pfoff = foff._data; cimg_forX(resx,x) { const double t = *(pfoff++), w0 = _cimg_lanczos(t + 2), w1 = _cimg_lanczos(t + 1), w2 = _cimg_lanczos(t), w3 = _cimg_lanczos(t - 1), w4 = _cimg_lanczos(t - 2), val2 = (double)*ptrs, val1 = ptrs>=ptrsmin?(double)*(ptrs - 1):val2, val0 = ptrs>ptrsmin?(double)*(ptrs - 2):val1, val3 = ptrs<=ptrsmax?(double)*(ptrs + 1):val2, val4 = ptrs<ptrsmax?(double)*(ptrs + 2):val3, val = (val0*w0 + val1*w1 + val2*w2 + val3*w3 + val4*w4)/(w1 + w2 + w3 + w4); *(ptrd++) = (T)(val<vmin?vmin:val>vmax?vmax:val); ptrs+=*(poff++); } } } } } else resx.assign(*this,true); if (sy!=_height) { if (_height==1) resx.get_resize(sx,sy,_depth,_spectrum,1).move_to(resy); else { if (_height>sy) resx.get_resize(sx,sy,_depth,_spectrum,2).move_to(resy); else { const double fy = (!boundary_conditions && sy>_height)?(sy>1?(_height - 1.)/(sy - 1):0): (double)_height/sy; resy.assign(sx,sy,_depth,_spectrum); curr = old = 0; { unsigned int *poff = off._data; double *pfoff = foff._data; cimg_forY(resy,y) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr = std::min(height() - 1.,curr + fy); *(poff++) = sx*((unsigned int)curr - (unsigned int)old); } } cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(resy.size(),65536)) cimg_forXZC(resy,x,z,c) { const T *const ptrs0 = resx.data(x,0,z,c), *ptrs = ptrs0, *const ptrsmin = ptrs0 + sx, *const ptrsmax = ptrs0 + (_height - 2)*sx; T *ptrd = resy.data(x,0,z,c); const unsigned int *poff = off._data; const double *pfoff = foff._data; cimg_forY(resy,y) { const double t = *(pfoff++), w0 = _cimg_lanczos(t + 2), w1 = _cimg_lanczos(t + 1), w2 = _cimg_lanczos(t), w3 = _cimg_lanczos(t - 1), w4 = _cimg_lanczos(t - 2), val2 = (double)*ptrs, val1 = ptrs>=ptrsmin?(double)*(ptrs - sx):val2, val0 = ptrs>ptrsmin?(double)*(ptrs - 2*sx):val1, val3 = ptrs<=ptrsmax?(double)*(ptrs + sx):val2, val4 = ptrs<ptrsmax?(double)*(ptrs + 2*sx):val3, val = (val0*w0 + val1*w1 + val2*w2 + val3*w3 + val4*w4)/(w1 + w2 + w3 + w4); *ptrd = (T)(val<vmin?vmin:val>vmax?vmax:val); ptrd+=sx; ptrs+=*(poff++); } } } } resx.assign(); } else resy.assign(resx,true); if (sz!=_depth) { if (_depth==1) resy.get_resize(sx,sy,sz,_spectrum,1).move_to(resz); else { if (_depth>sz) resy.get_resize(sx,sy,sz,_spectrum,2).move_to(resz); else { const double fz = (!boundary_conditions && sz>_depth)?(sz>1?(_depth - 1.)/(sz - 1):0): (double)_depth/sz; const unsigned int sxy = sx*sy; resz.assign(sx,sy,sz,_spectrum); curr = old = 0; { unsigned int *poff = off._data; double *pfoff = foff._data; cimg_forZ(resz,z) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr = std::min(depth() - 1.,curr + fz); *(poff++) = sxy*((unsigned int)curr - (unsigned int)old); } } cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(resz.size(),65536)) cimg_forXYC(resz,x,y,c) { const T *const ptrs0 = resy.data(x,y,0,c), *ptrs = ptrs0, *const ptrsmin = ptrs0 + sxy, *const ptrsmax = ptrs0 + (_depth - 2)*sxy; T *ptrd = resz.data(x,y,0,c); const unsigned int *poff = off._data; const double *pfoff = foff._data; cimg_forZ(resz,z) { const double t = *(pfoff++), w0 = _cimg_lanczos(t + 2), w1 = _cimg_lanczos(t + 1), w2 = _cimg_lanczos(t), w3 = _cimg_lanczos(t - 1), w4 = _cimg_lanczos(t - 2), val2 = (double)*ptrs, val1 = ptrs>=ptrsmin?(double)*(ptrs - sxy):val2, val0 = ptrs>ptrsmin?(double)*(ptrs - 2*sxy):val1, val3 = ptrs<=ptrsmax?(double)*(ptrs + sxy):val2, val4 = ptrs<ptrsmax?(double)*(ptrs + 2*sxy):val3, val = (val0*w0 + val1*w1 + val2*w2 + val3*w3 + val4*w4)/(w1 + w2 + w3 + w4); *ptrd = (T)(val<vmin?vmin:val>vmax?vmax:val); ptrd+=sxy; ptrs+=*(poff++); } } } } resy.assign(); } else resz.assign(resy,true); if (sc!=_spectrum) { if (_spectrum==1) resz.get_resize(sx,sy,sz,sc,1).move_to(resc); else { if (_spectrum>sc) resz.get_resize(sx,sy,sz,sc,2).move_to(resc); else { const double fc = (!boundary_conditions && sc>_spectrum)?(sc>1?(_spectrum - 1.)/(sc - 1):0): (double)_spectrum/sc; const unsigned int sxyz = sx*sy*sz; resc.assign(sx,sy,sz,sc); curr = old = 0; { unsigned int *poff = off._data; double *pfoff = foff._data; cimg_forC(resc,c) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr = std::min(spectrum() - 1.,curr + fc); *(poff++) = sxyz*((unsigned int)curr - (unsigned int)old); } } cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(resc.size(),65536)) cimg_forXYZ(resc,x,y,z) { const T *const ptrs0 = resz.data(x,y,z,0), *ptrs = ptrs0, *const ptrsmin = ptrs0 + sxyz, *const ptrsmax = ptrs + (_spectrum - 2)*sxyz; T *ptrd = resc.data(x,y,z,0); const unsigned int *poff = off._data; const double *pfoff = foff._data; cimg_forC(resc,c) { const double t = *(pfoff++), w0 = _cimg_lanczos(t + 2), w1 = _cimg_lanczos(t + 1), w2 = _cimg_lanczos(t), w3 = _cimg_lanczos(t - 1), w4 = _cimg_lanczos(t - 2), val2 = (double)*ptrs, val1 = ptrs>=ptrsmin?(double)*(ptrs - sxyz):val2, val0 = ptrs>ptrsmin?(double)*(ptrs - 2*sxyz):val1, val3 = ptrs<=ptrsmax?(double)*(ptrs + sxyz):val2, val4 = ptrs<ptrsmax?(double)*(ptrs + 2*sxyz):val3, val = (val0*w0 + val1*w1 + val2*w2 + val3*w3 + val4*w4)/(w1 + w2 + w3 + w4); *ptrd = (T)(val<vmin?vmin:val>vmax?vmax:val); ptrd+=sxyz; ptrs+=*(poff++); } } } } resz.assign(); } else resc.assign(resz,true); return resc._is_shared?(resz._is_shared?(resy._is_shared?(resx._is_shared?(+(*this)):resx):resy):resz):resc; } break; // Unknow interpolation. // default : throw CImgArgumentException(_cimg_instance "resize(): Invalid specified interpolation %d " "(should be { -1=raw | 0=none | 1=nearest | 2=average | 3=linear | 4=grid | " "5=cubic | 6=lanczos }).", cimg_instance, interpolation_type); } return res; } //! Resize image to dimensions of another image. /** \param src Reference image used for dimensions. \param interpolation_type Interpolation method. \param boundary_conditions Boundary conditions. \param centering_x Set centering type (only if \p interpolation_type=0). \param centering_y Set centering type (only if \p interpolation_type=0). \param centering_z Set centering type (only if \p interpolation_type=0). \param centering_c Set centering type (only if \p interpolation_type=0). **/ template<typename t> CImg<T>& resize(const CImg<t>& src, const int interpolation_type=1, const unsigned int boundary_conditions=0, const float centering_x = 0, const float centering_y = 0, const float centering_z = 0, const float centering_c = 0) { return resize(src._width,src._height,src._depth,src._spectrum,interpolation_type,boundary_conditions, centering_x,centering_y,centering_z,centering_c); } //! Resize image to dimensions of another image \newinstance. template<typename t> CImg<T> get_resize(const CImg<t>& src, const int interpolation_type=1, const unsigned int boundary_conditions=0, const float centering_x = 0, const float centering_y = 0, const float centering_z = 0, const float centering_c = 0) const { return get_resize(src._width,src._height,src._depth,src._spectrum,interpolation_type,boundary_conditions, centering_x,centering_y,centering_z,centering_c); } //! Resize image to dimensions of a display window. /** \param disp Reference display window used for dimensions. \param interpolation_type Interpolation method. \param boundary_conditions Boundary conditions. \param centering_x Set centering type (only if \p interpolation_type=0). \param centering_y Set centering type (only if \p interpolation_type=0). \param centering_z Set centering type (only if \p interpolation_type=0). \param centering_c Set centering type (only if \p interpolation_type=0). **/ CImg<T>& resize(const CImgDisplay& disp, const int interpolation_type=1, const unsigned int boundary_conditions=0, const float centering_x = 0, const float centering_y = 0, const float centering_z = 0, const float centering_c = 0) { return resize(disp.width(),disp.height(),_depth,_spectrum,interpolation_type,boundary_conditions, centering_x,centering_y,centering_z,centering_c); } //! Resize image to dimensions of a display window \newinstance. CImg<T> get_resize(const CImgDisplay& disp, const int interpolation_type=1, const unsigned int boundary_conditions=0, const float centering_x = 0, const float centering_y = 0, const float centering_z = 0, const float centering_c = 0) const { return get_resize(disp.width(),disp.height(),_depth,_spectrum,interpolation_type,boundary_conditions, centering_x,centering_y,centering_z,centering_c); } //! Resize image to half-size along XY axes, using an optimized filter. CImg<T>& resize_halfXY() { return get_resize_halfXY().move_to(*this); } //! Resize image to half-size along XY axes, using an optimized filter \newinstance. CImg<T> get_resize_halfXY() const { if (is_empty()) return *this; static const Tfloat kernel[9] = { 0.07842776544f, 0.1231940459f, 0.07842776544f, 0.1231940459f, 0.1935127547f, 0.1231940459f, 0.07842776544f, 0.1231940459f, 0.07842776544f }; CImg<T> I(9), res(_width/2,_height/2,_depth,_spectrum); T *ptrd = res._data; cimg_forZC(*this,z,c) cimg_for3x3(*this,x,y,z,c,I,T) if (x%2 && y%2) *(ptrd++) = (T) (I[0]*kernel[0] + I[1]*kernel[1] + I[2]*kernel[2] + I[3]*kernel[3] + I[4]*kernel[4] + I[5]*kernel[5] + I[6]*kernel[6] + I[7]*kernel[7] + I[8]*kernel[8]); return res; } //! Resize image to double-size, using the Scale2X algorithm. /** \note Use anisotropic upscaling algorithm <a href="http://scale2x.sourceforge.net/algorithm.html">described here</a>. **/ CImg<T>& resize_doubleXY() { return get_resize_doubleXY().move_to(*this); } //! Resize image to double-size, using the Scale2X algorithm \newinstance. CImg<T> get_resize_doubleXY() const { #define _cimg_gs2x_for3(bound,i) \ for (int i = 0, _p1##i = 0, \ _n1##i = 1>=(bound)?(int)(bound) - 1:1; \ _n1##i<(int)(bound) || i==--_n1##i; \ _p1##i = i++, ++_n1##i, ptrd1+=(res)._width, ptrd2+=(res)._width) #define _cimg_gs2x_for3x3(img,x,y,z,c,I,T) \ _cimg_gs2x_for3((img)._height,y) for (int x = 0, \ _p1##x = 0, \ _n1##x = (int)( \ (I[1] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[3] = I[4] = (T)(img)(0,y,z,c)), \ (I[7] = (T)(img)(0,_n1##y,z,c)), \ 1>=(img)._width?(img).width() - 1:1); \ (_n1##x<(img).width() && ( \ (I[2] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[5] = (T)(img)(_n1##x,y,z,c)), \ (I[8] = (T)(img)(_n1##x,_n1##y,z,c)),1)) || \ x==--_n1##x; \ I[1] = I[2], \ I[3] = I[4], I[4] = I[5], \ I[7] = I[8], \ _p1##x = x++, ++_n1##x) if (is_empty()) return *this; CImg<T> res(_width<<1,_height<<1,_depth,_spectrum); CImg_3x3(I,T); cimg_forZC(*this,z,c) { T *ptrd1 = res.data(0,0,z,c), *ptrd2 = ptrd1 + res._width; _cimg_gs2x_for3x3(*this,x,y,z,c,I,T) { if (Icp!=Icn && Ipc!=Inc) { *(ptrd1++) = Ipc==Icp?Ipc:Icc; *(ptrd1++) = Icp==Inc?Inc:Icc; *(ptrd2++) = Ipc==Icn?Ipc:Icc; *(ptrd2++) = Icn==Inc?Inc:Icc; } else { *(ptrd1++) = Icc; *(ptrd1++) = Icc; *(ptrd2++) = Icc; *(ptrd2++) = Icc; } } } return res; } //! Resize image to triple-size, using the Scale3X algorithm. /** \note Use anisotropic upscaling algorithm <a href="http://scale2x.sourceforge.net/algorithm.html">described here</a>. **/ CImg<T>& resize_tripleXY() { return get_resize_tripleXY().move_to(*this); } //! Resize image to triple-size, using the Scale3X algorithm \newinstance. CImg<T> get_resize_tripleXY() const { #define _cimg_gs3x_for3(bound,i) \ for (int i = 0, _p1##i = 0, \ _n1##i = 1>=(bound)?(int)(bound) - 1:1; \ _n1##i<(int)(bound) || i==--_n1##i; \ _p1##i = i++, ++_n1##i, ptrd1+=2*(res)._width, ptrd2+=2*(res)._width, ptrd3+=2*(res)._width) #define _cimg_gs3x_for3x3(img,x,y,z,c,I,T) \ _cimg_gs3x_for3((img)._height,y) for (int x = 0, \ _p1##x = 0, \ _n1##x = (int)( \ (I[0] = I[1] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[3] = I[4] = (T)(img)(0,y,z,c)), \ (I[6] = I[7] = (T)(img)(0,_n1##y,z,c)), \ 1>=(img)._width?(img).width() - 1:1); \ (_n1##x<(img).width() && ( \ (I[2] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[5] = (T)(img)(_n1##x,y,z,c)), \ (I[8] = (T)(img)(_n1##x,_n1##y,z,c)),1)) || \ x==--_n1##x; \ I[0] = I[1], I[1] = I[2], \ I[3] = I[4], I[4] = I[5], \ I[6] = I[7], I[7] = I[8], \ _p1##x = x++, ++_n1##x) if (is_empty()) return *this; CImg<T> res(3*_width,3*_height,_depth,_spectrum); CImg_3x3(I,T); cimg_forZC(*this,z,c) { T *ptrd1 = res.data(0,0,z,c), *ptrd2 = ptrd1 + res._width, *ptrd3 = ptrd2 + res._width; _cimg_gs3x_for3x3(*this,x,y,z,c,I,T) { if (Icp != Icn && Ipc != Inc) { *(ptrd1++) = Ipc==Icp?Ipc:Icc; *(ptrd1++) = (Ipc==Icp && Icc!=Inp) || (Icp==Inc && Icc!=Ipp)?Icp:Icc; *(ptrd1++) = Icp==Inc?Inc:Icc; *(ptrd2++) = (Ipc==Icp && Icc!=Ipn) || (Ipc==Icn && Icc!=Ipp)?Ipc:Icc; *(ptrd2++) = Icc; *(ptrd2++) = (Icp==Inc && Icc!=Inn) || (Icn==Inc && Icc!=Inp)?Inc:Icc; *(ptrd3++) = Ipc==Icn?Ipc:Icc; *(ptrd3++) = (Ipc==Icn && Icc!=Inn) || (Icn==Inc && Icc!=Ipn)?Icn:Icc; *(ptrd3++) = Icn==Inc?Inc:Icc; } else { *(ptrd1++) = Icc; *(ptrd1++) = Icc; *(ptrd1++) = Icc; *(ptrd2++) = Icc; *(ptrd2++) = Icc; *(ptrd2++) = Icc; *(ptrd3++) = Icc; *(ptrd3++) = Icc; *(ptrd3++) = Icc; } } } return res; } //! Mirror image content along specified axis. /** \param axis Mirror axis **/ CImg<T>& mirror(const char axis) { if (is_empty()) return *this; T *pf, *pb, *buf = 0; switch (cimg::lowercase(axis)) { case 'x' : { pf = _data; pb = data(_width - 1); const unsigned int width2 = _width/2; for (unsigned int yzv = 0; yzv<_height*_depth*_spectrum; ++yzv) { for (unsigned int x = 0; x<width2; ++x) { const T val = *pf; *(pf++) = *pb; *(pb--) = val; } pf+=_width - width2; pb+=_width + width2; } } break; case 'y' : { buf = new T[_width]; pf = _data; pb = data(0,_height - 1); const unsigned int height2 = _height/2; for (unsigned int zv = 0; zv<_depth*_spectrum; ++zv) { for (unsigned int y = 0; y<height2; ++y) { std::memcpy(buf,pf,_width*sizeof(T)); std::memcpy(pf,pb,_width*sizeof(T)); std::memcpy(pb,buf,_width*sizeof(T)); pf+=_width; pb-=_width; } pf+=(ulongT)_width*(_height - height2); pb+=(ulongT)_width*(_height + height2); } } break; case 'z' : { buf = new T[(ulongT)_width*_height]; pf = _data; pb = data(0,0,_depth - 1); const unsigned int depth2 = _depth/2; cimg_forC(*this,c) { for (unsigned int z = 0; z<depth2; ++z) { std::memcpy(buf,pf,_width*_height*sizeof(T)); std::memcpy(pf,pb,_width*_height*sizeof(T)); std::memcpy(pb,buf,_width*_height*sizeof(T)); pf+=(ulongT)_width*_height; pb-=(ulongT)_width*_height; } pf+=(ulongT)_width*_height*(_depth - depth2); pb+=(ulongT)_width*_height*(_depth + depth2); } } break; case 'c' : { buf = new T[(ulongT)_width*_height*_depth]; pf = _data; pb = data(0,0,0,_spectrum - 1); const unsigned int _spectrum2 = _spectrum/2; for (unsigned int v = 0; v<_spectrum2; ++v) { std::memcpy(buf,pf,_width*_height*_depth*sizeof(T)); std::memcpy(pf,pb,_width*_height*_depth*sizeof(T)); std::memcpy(pb,buf,_width*_height*_depth*sizeof(T)); pf+=(ulongT)_width*_height*_depth; pb-=(ulongT)_width*_height*_depth; } } break; default : throw CImgArgumentException(_cimg_instance "mirror(): Invalid specified axis '%c'.", cimg_instance, axis); } delete[] buf; return *this; } //! Mirror image content along specified axis \newinstance. CImg<T> get_mirror(const char axis) const { return (+*this).mirror(axis); } //! Mirror image content along specified axes. /** \param axes Mirror axes, as a C-string. \note \c axes may contains multiple characters, e.g. \c "xyz" **/ CImg<T>& mirror(const char *const axes) { for (const char *s = axes; *s; ++s) mirror(*s); return *this; } //! Mirror image content along specified axes \newinstance. CImg<T> get_mirror(const char *const axes) const { return (+*this).mirror(axes); } //! Shift image content. /** \param delta_x Amount of displacement along the X-axis. \param delta_y Amount of displacement along the Y-axis. \param delta_z Amount of displacement along the Z-axis. \param delta_c Amount of displacement along the C-axis. \param boundary_conditions Border condition. Can be { 0=dirichlet | 1=neumann | 2=periodic | 3=mirror }. **/ CImg<T>& shift(const int delta_x, const int delta_y=0, const int delta_z=0, const int delta_c=0, const unsigned int boundary_conditions=0) { if (is_empty()) return *this; if (boundary_conditions==3) return get_crop(-delta_x,-delta_y,-delta_z,-delta_c, width() - delta_x - 1, height() - delta_y - 1, depth() - delta_z - 1, spectrum() - delta_c - 1,3).move_to(*this); if (delta_x) // Shift along X-axis switch (boundary_conditions) { case 2 : { // Periodic const int ml = cimg::mod(-delta_x,width()), ndelta_x = (ml<=width()/2)?ml:(ml-width()); if (!ndelta_x) return *this; CImg<T> buf(cimg::abs(ndelta_x)); if (ndelta_x>0) cimg_forYZC(*this,y,z,c) { std::memcpy(buf,data(0,y,z,c),ndelta_x*sizeof(T)); std::memmove(data(0,y,z,c),data(ndelta_x,y,z,c),(_width-ndelta_x)*sizeof(T)); std::memcpy(data(_width-ndelta_x,y,z,c),buf,ndelta_x*sizeof(T)); } else cimg_forYZC(*this,y,z,c) { std::memcpy(buf,data(_width + ndelta_x,y,z,c),-ndelta_x*sizeof(T)); std::memmove(data(-ndelta_x,y,z,c),data(0,y,z,c),(_width + ndelta_x)*sizeof(T)); std::memcpy(data(0,y,z,c),buf,-ndelta_x*sizeof(T)); } } break; case 1 : // Neumann if (delta_x<0) { const int ndelta_x = (-delta_x>=width())?width() - 1:-delta_x; if (!ndelta_x) return *this; cimg_forYZC(*this,y,z,c) { std::memmove(data(0,y,z,c),data(ndelta_x,y,z,c),(_width-ndelta_x)*sizeof(T)); T *ptrd = data(_width - 1,y,z,c); const T val = *ptrd; for (int l = 0; l<ndelta_x - 1; ++l) *(--ptrd) = val; } } else { const int ndelta_x = (delta_x>=width())?width() - 1:delta_x; if (!ndelta_x) return *this; cimg_forYZC(*this,y,z,c) { std::memmove(data(ndelta_x,y,z,c),data(0,y,z,c),(_width-ndelta_x)*sizeof(T)); T *ptrd = data(0,y,z,c); const T val = *ptrd; for (int l = 0; l<ndelta_x - 1; ++l) *(++ptrd) = val; } } break; default : // Dirichlet if (delta_x<=-width() || delta_x>=width()) return fill((T)0); if (delta_x<0) cimg_forYZC(*this,y,z,c) { std::memmove(data(0,y,z,c),data(-delta_x,y,z,c),(_width + delta_x)*sizeof(T)); std::memset(data(_width + delta_x,y,z,c),0,-delta_x*sizeof(T)); } else cimg_forYZC(*this,y,z,c) { std::memmove(data(delta_x,y,z,c),data(0,y,z,c),(_width-delta_x)*sizeof(T)); std::memset(data(0,y,z,c),0,delta_x*sizeof(T)); } } if (delta_y) // Shift along Y-axis switch (boundary_conditions) { case 2 : { // Periodic const int ml = cimg::mod(-delta_y,height()), ndelta_y = (ml<=height()/2)?ml:(ml-height()); if (!ndelta_y) return *this; CImg<T> buf(width(),cimg::abs(ndelta_y)); if (ndelta_y>0) cimg_forZC(*this,z,c) { std::memcpy(buf,data(0,0,z,c),_width*ndelta_y*sizeof(T)); std::memmove(data(0,0,z,c),data(0,ndelta_y,z,c),_width*(_height-ndelta_y)*sizeof(T)); std::memcpy(data(0,_height-ndelta_y,z,c),buf,_width*ndelta_y*sizeof(T)); } else cimg_forZC(*this,z,c) { std::memcpy(buf,data(0,_height + ndelta_y,z,c),-ndelta_y*_width*sizeof(T)); std::memmove(data(0,-ndelta_y,z,c),data(0,0,z,c),_width*(_height + ndelta_y)*sizeof(T)); std::memcpy(data(0,0,z,c),buf,-ndelta_y*_width*sizeof(T)); } } break; case 1 : // Neumann if (delta_y<0) { const int ndelta_y = (-delta_y>=height())?height() - 1:-delta_y; if (!ndelta_y) return *this; cimg_forZC(*this,z,c) { std::memmove(data(0,0,z,c),data(0,ndelta_y,z,c),_width*(_height-ndelta_y)*sizeof(T)); T *ptrd = data(0,_height-ndelta_y,z,c), *ptrs = data(0,_height - 1,z,c); for (int l = 0; l<ndelta_y - 1; ++l) { std::memcpy(ptrd,ptrs,_width*sizeof(T)); ptrd+=_width; } } } else { const int ndelta_y = (delta_y>=height())?height() - 1:delta_y; if (!ndelta_y) return *this; cimg_forZC(*this,z,c) { std::memmove(data(0,ndelta_y,z,c),data(0,0,z,c),_width*(_height-ndelta_y)*sizeof(T)); T *ptrd = data(0,1,z,c), *ptrs = data(0,0,z,c); for (int l = 0; l<ndelta_y - 1; ++l) { std::memcpy(ptrd,ptrs,_width*sizeof(T)); ptrd+=_width; } } } break; default : // Dirichlet if (delta_y<=-height() || delta_y>=height()) return fill((T)0); if (delta_y<0) cimg_forZC(*this,z,c) { std::memmove(data(0,0,z,c),data(0,-delta_y,z,c),_width*(_height + delta_y)*sizeof(T)); std::memset(data(0,_height + delta_y,z,c),0,-delta_y*_width*sizeof(T)); } else cimg_forZC(*this,z,c) { std::memmove(data(0,delta_y,z,c),data(0,0,z,c),_width*(_height-delta_y)*sizeof(T)); std::memset(data(0,0,z,c),0,delta_y*_width*sizeof(T)); } } if (delta_z) // Shift along Z-axis switch (boundary_conditions) { case 2 : { // Periodic const int ml = cimg::mod(-delta_z,depth()), ndelta_z = (ml<=depth()/2)?ml:(ml-depth()); if (!ndelta_z) return *this; CImg<T> buf(width(),height(),cimg::abs(ndelta_z)); if (ndelta_z>0) cimg_forC(*this,c) { std::memcpy(buf,data(0,0,0,c),_width*_height*ndelta_z*sizeof(T)); std::memmove(data(0,0,0,c),data(0,0,ndelta_z,c),_width*_height*(_depth-ndelta_z)*sizeof(T)); std::memcpy(data(0,0,_depth-ndelta_z,c),buf,_width*_height*ndelta_z*sizeof(T)); } else cimg_forC(*this,c) { std::memcpy(buf,data(0,0,_depth + ndelta_z,c),-ndelta_z*_width*_height*sizeof(T)); std::memmove(data(0,0,-ndelta_z,c),data(0,0,0,c),_width*_height*(_depth + ndelta_z)*sizeof(T)); std::memcpy(data(0,0,0,c),buf,-ndelta_z*_width*_height*sizeof(T)); } } break; case 1 : // Neumann if (delta_z<0) { const int ndelta_z = (-delta_z>=depth())?depth() - 1:-delta_z; if (!ndelta_z) return *this; cimg_forC(*this,c) { std::memmove(data(0,0,0,c),data(0,0,ndelta_z,c),_width*_height*(_depth-ndelta_z)*sizeof(T)); T *ptrd = data(0,0,_depth-ndelta_z,c), *ptrs = data(0,0,_depth - 1,c); for (int l = 0; l<ndelta_z - 1; ++l) { std::memcpy(ptrd,ptrs,_width*_height*sizeof(T)); ptrd+=(ulongT)_width*_height; } } } else { const int ndelta_z = (delta_z>=depth())?depth() - 1:delta_z; if (!ndelta_z) return *this; cimg_forC(*this,c) { std::memmove(data(0,0,ndelta_z,c),data(0,0,0,c),_width*_height*(_depth-ndelta_z)*sizeof(T)); T *ptrd = data(0,0,1,c), *ptrs = data(0,0,0,c); for (int l = 0; l<ndelta_z - 1; ++l) { std::memcpy(ptrd,ptrs,_width*_height*sizeof(T)); ptrd+=(ulongT)_width*_height; } } } break; default : // Dirichlet if (delta_z<=-depth() || delta_z>=depth()) return fill((T)0); if (delta_z<0) cimg_forC(*this,c) { std::memmove(data(0,0,0,c),data(0,0,-delta_z,c),_width*_height*(_depth + delta_z)*sizeof(T)); std::memset(data(0,0,_depth + delta_z,c),0,_width*_height*(-delta_z)*sizeof(T)); } else cimg_forC(*this,c) { std::memmove(data(0,0,delta_z,c),data(0,0,0,c),_width*_height*(_depth-delta_z)*sizeof(T)); std::memset(data(0,0,0,c),0,delta_z*_width*_height*sizeof(T)); } } if (delta_c) // Shift along C-axis switch (boundary_conditions) { case 2 : { // Periodic const int ml = cimg::mod(-delta_c,spectrum()), ndelta_c = (ml<=spectrum()/2)?ml:(ml-spectrum()); if (!ndelta_c) return *this; CImg<T> buf(width(),height(),depth(),cimg::abs(ndelta_c)); if (ndelta_c>0) { std::memcpy(buf,_data,_width*_height*_depth*ndelta_c*sizeof(T)); std::memmove(_data,data(0,0,0,ndelta_c),_width*_height*_depth*(_spectrum-ndelta_c)*sizeof(T)); std::memcpy(data(0,0,0,_spectrum-ndelta_c),buf,_width*_height*_depth*ndelta_c*sizeof(T)); } else { std::memcpy(buf,data(0,0,0,_spectrum + ndelta_c),-ndelta_c*_width*_height*_depth*sizeof(T)); std::memmove(data(0,0,0,-ndelta_c),_data,_width*_height*_depth*(_spectrum + ndelta_c)*sizeof(T)); std::memcpy(_data,buf,-ndelta_c*_width*_height*_depth*sizeof(T)); } } break; case 1 : // Neumann if (delta_c<0) { const int ndelta_c = (-delta_c>=spectrum())?spectrum() - 1:-delta_c; if (!ndelta_c) return *this; std::memmove(_data,data(0,0,0,ndelta_c),_width*_height*_depth*(_spectrum-ndelta_c)*sizeof(T)); T *ptrd = data(0,0,0,_spectrum-ndelta_c), *ptrs = data(0,0,0,_spectrum - 1); for (int l = 0; l<ndelta_c - 1; ++l) { std::memcpy(ptrd,ptrs,_width*_height*_depth*sizeof(T)); ptrd+=(ulongT)_width*_height*_depth; } } else { const int ndelta_c = (delta_c>=spectrum())?spectrum() - 1:delta_c; if (!ndelta_c) return *this; std::memmove(data(0,0,0,ndelta_c),_data,_width*_height*_depth*(_spectrum-ndelta_c)*sizeof(T)); T *ptrd = data(0,0,0,1); for (int l = 0; l<ndelta_c - 1; ++l) { std::memcpy(ptrd,_data,_width*_height*_depth*sizeof(T)); ptrd+=(ulongT)_width*_height*_depth; } } break; default : // Dirichlet if (delta_c<=-spectrum() || delta_c>=spectrum()) return fill((T)0); if (delta_c<0) { std::memmove(_data,data(0,0,0,-delta_c),_width*_height*_depth*(_spectrum + delta_c)*sizeof(T)); std::memset(data(0,0,0,_spectrum + delta_c),0,_width*_height*_depth*(-delta_c)*sizeof(T)); } else { std::memmove(data(0,0,0,delta_c),_data,_width*_height*_depth*(_spectrum-delta_c)*sizeof(T)); std::memset(_data,0,delta_c*_width*_height*_depth*sizeof(T)); } } return *this; } //! Shift image content \newinstance. CImg<T> get_shift(const int delta_x, const int delta_y=0, const int delta_z=0, const int delta_c=0, const unsigned int boundary_conditions=0) const { return (+*this).shift(delta_x,delta_y,delta_z,delta_c,boundary_conditions); } //! Permute axes order. /** \param order Axes permutations, as a C-string of 4 characters. This function permutes image content regarding the specified axes permutation. **/ CImg<T>& permute_axes(const char *const order) { return get_permute_axes(order).move_to(*this); } //! Permute axes order \newinstance. CImg<T> get_permute_axes(const char *const order) const { const T foo = (T)0; return _permute_axes(order,foo); } template<typename t> CImg<t> _permute_axes(const char *const order, const t&) const { if (is_empty() || !order) return CImg<t>(*this,false); CImg<t> res; const T* ptrs = _data; unsigned char s_code[4] = { 0,1,2,3 }, n_code[4] = { 0 }; for (unsigned int l = 0; order[l]; ++l) { int c = cimg::lowercase(order[l]); if (c!='x' && c!='y' && c!='z' && c!='c') { *s_code = 4; break; } else { ++n_code[c%=4]; s_code[l] = c; } } if (*order && *s_code<4 && *n_code<=1 && n_code[1]<=1 && n_code[2]<=1 && n_code[3]<=1) { const unsigned int code = (s_code[0]<<12) | (s_code[1]<<8) | (s_code[2]<<4) | (s_code[3]); ulongT wh, whd; switch (code) { case 0x0123 : // xyzc return +*this; case 0x0132 : // xycz res.assign(_width,_height,_spectrum,_depth); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(x,y,c,z,wh,whd) = (t)*(ptrs++); break; case 0x0213 : // xzyc res.assign(_width,_depth,_height,_spectrum); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(x,z,y,c,wh,whd) = (t)*(ptrs++); break; case 0x0231 : // xzcy res.assign(_width,_depth,_spectrum,_height); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(x,z,c,y,wh,whd) = (t)*(ptrs++); break; case 0x0312 : // xcyz res.assign(_width,_spectrum,_height,_depth); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(x,c,y,z,wh,whd) = (t)*(ptrs++); break; case 0x0321 : // xczy res.assign(_width,_spectrum,_depth,_height); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(x,c,z,y,wh,whd) = (t)*(ptrs++); break; case 0x1023 : // yxzc res.assign(_height,_width,_depth,_spectrum); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(y,x,z,c,wh,whd) = (t)*(ptrs++); break; case 0x1032 : // yxcz res.assign(_height,_width,_spectrum,_depth); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(y,x,c,z,wh,whd) = (t)*(ptrs++); break; case 0x1203 : // yzxc res.assign(_height,_depth,_width,_spectrum); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(y,z,x,c,wh,whd) = (t)*(ptrs++); break; case 0x1230 : // yzcx res.assign(_height,_depth,_spectrum,_width); switch (_width) { case 1 : { t *ptr_r = res.data(0,0,0,0); for (unsigned int siz = _height*_depth*_spectrum; siz; --siz) { *(ptr_r++) = (t)*(ptrs++); } } break; case 2 : { t *ptr_r = res.data(0,0,0,0), *ptr_g = res.data(0,0,0,1); for (unsigned int siz = _height*_depth*_spectrum; siz; --siz) { *(ptr_r++) = (t)ptrs[0]; *(ptr_g++) = (t)ptrs[1]; ptrs+=2; } } break; case 3 : { // Optimization for the classical conversion from interleaved RGB to planar RGB t *ptr_r = res.data(0,0,0,0), *ptr_g = res.data(0,0,0,1), *ptr_b = res.data(0,0,0,2); for (unsigned int siz = _height*_depth*_spectrum; siz; --siz) { *(ptr_r++) = (t)ptrs[0]; *(ptr_g++) = (t)ptrs[1]; *(ptr_b++) = (t)ptrs[2]; ptrs+=3; } } break; case 4 : { // Optimization for the classical conversion from interleaved RGBA to planar RGBA t *ptr_r = res.data(0,0,0,0), *ptr_g = res.data(0,0,0,1), *ptr_b = res.data(0,0,0,2), *ptr_a = res.data(0,0,0,3); for (unsigned int siz = _height*_depth*_spectrum; siz; --siz) { *(ptr_r++) = (t)ptrs[0]; *(ptr_g++) = (t)ptrs[1]; *(ptr_b++) = (t)ptrs[2]; *(ptr_a++) = (t)ptrs[3]; ptrs+=4; } } break; default : { wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(y,z,c,x,wh,whd) = *(ptrs++); return res; } } break; case 0x1302 : // ycxz res.assign(_height,_spectrum,_width,_depth); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(y,c,x,z,wh,whd) = (t)*(ptrs++); break; case 0x1320 : // yczx res.assign(_height,_spectrum,_depth,_width); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(y,c,z,x,wh,whd) = (t)*(ptrs++); break; case 0x2013 : // zxyc res.assign(_depth,_width,_height,_spectrum); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(z,x,y,c,wh,whd) = (t)*(ptrs++); break; case 0x2031 : // zxcy res.assign(_depth,_width,_spectrum,_height); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(z,x,c,y,wh,whd) = (t)*(ptrs++); break; case 0x2103 : // zyxc res.assign(_depth,_height,_width,_spectrum); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(z,y,x,c,wh,whd) = (t)*(ptrs++); break; case 0x2130 : // zycx res.assign(_depth,_height,_spectrum,_width); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(z,y,c,x,wh,whd) = (t)*(ptrs++); break; case 0x2301 : // zcxy res.assign(_depth,_spectrum,_width,_height); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(z,c,x,y,wh,whd) = (t)*(ptrs++); break; case 0x2310 : // zcyx res.assign(_depth,_spectrum,_height,_width); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(z,c,y,x,wh,whd) = (t)*(ptrs++); break; case 0x3012 : // cxyz res.assign(_spectrum,_width,_height,_depth); switch (_spectrum) { case 1 : { const T *ptr_r = data(0,0,0,0); t *ptrd = res._data; for (ulongT siz = (ulongT)_width*_height*_depth; siz; --siz) *(ptrd++) = (t)*(ptr_r++); } break; case 2 : { const T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1); t *ptrd = res._data; for (ulongT siz = (ulongT)_width*_height*_depth; siz; --siz) { ptrd[0] = (t)*(ptr_r++); ptrd[1] = (t)*(ptr_g++); ptrd+=2; } } break; case 3 : { // Optimization for the classical conversion from planar RGB to interleaved RGB const T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2); t *ptrd = res._data; for (ulongT siz = (ulongT)_width*_height*_depth; siz; --siz) { ptrd[0] = (t)*(ptr_r++); ptrd[1] = (t)*(ptr_g++); ptrd[2] = (t)*(ptr_b++); ptrd+=3; } } break; case 4 : { // Optimization for the classical conversion from planar RGBA to interleaved RGBA const T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2), *ptr_a = data(0,0,0,3); t *ptrd = res._data; for (ulongT siz = (ulongT)_width*_height*_depth; siz; --siz) { ptrd[0] = (t)*(ptr_r++); ptrd[1] = (t)*(ptr_g++); ptrd[2] = (t)*(ptr_b++); ptrd[3] = (t)*(ptr_a++); ptrd+=4; } } break; default : { wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(c,x,y,z,wh,whd) = (t)*(ptrs++); } } break; case 0x3021 : // cxzy res.assign(_spectrum,_width,_depth,_height); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(c,x,z,y,wh,whd) = (t)*(ptrs++); break; case 0x3102 : // cyxz res.assign(_spectrum,_height,_width,_depth); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(c,y,x,z,wh,whd) = (t)*(ptrs++); break; case 0x3120 : // cyzx res.assign(_spectrum,_height,_depth,_width); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(c,y,z,x,wh,whd) = (t)*(ptrs++); break; case 0x3201 : // czxy res.assign(_spectrum,_depth,_width,_height); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(c,z,x,y,wh,whd) = (t)*(ptrs++); break; case 0x3210 : // czyx res.assign(_spectrum,_depth,_height,_width); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(c,z,y,x,wh,whd) = (t)*(ptrs++); break; } } if (!res) throw CImgArgumentException(_cimg_instance "permute_axes(): Invalid specified permutation '%s'.", cimg_instance, order); return res; } //! Unroll pixel values along specified axis. /** \param axis Unroll axis (can be \c 'x', \c 'y', \c 'z' or c 'c'). **/ CImg<T>& unroll(const char axis) { const unsigned int siz = (unsigned int)size(); if (siz) switch (cimg::lowercase(axis)) { case 'x' : _width = siz; _height = _depth = _spectrum = 1; break; case 'y' : _height = siz; _width = _depth = _spectrum = 1; break; case 'z' : _depth = siz; _width = _height = _spectrum = 1; break; default : _spectrum = siz; _width = _height = _depth = 1; } return *this; } //! Unroll pixel values along specified axis \newinstance. CImg<T> get_unroll(const char axis) const { return (+*this).unroll(axis); } //! Rotate image with arbitrary angle. /** \param angle Rotation angle, in degrees. \param interpolation Type of interpolation. Can be <tt>{ 0=nearest | 1=linear | 2=cubic }</tt>. \param boundary_conditions Boundary conditions. Can be <tt>{ 0=dirichlet | 1=neumann | 2=periodic | 3=mirror }</tt>. \note The size of the image is modified. **/ CImg<T>& rotate(const float angle, const unsigned int interpolation=1, const unsigned int boundary_conditions=0) { const float nangle = cimg::mod(angle,360.f); if (nangle==0.f) return *this; return get_rotate(nangle,interpolation,boundary_conditions).move_to(*this); } //! Rotate image with arbitrary angle \newinstance. CImg<T> get_rotate(const float angle, const unsigned int interpolation=1, const unsigned int boundary_conditions=0) const { if (is_empty()) return *this; CImg<T> res; const float nangle = cimg::mod(angle,360.f); if (boundary_conditions!=1 && cimg::mod(nangle,90.f)==0) { // Optimized version for orthogonal angles const int wm1 = width() - 1, hm1 = height() - 1; const int iangle = (int)nangle/90; switch (iangle) { case 1 : { // 90 deg res.assign(_height,_width,_depth,_spectrum); T *ptrd = res._data; cimg_forXYZC(res,x,y,z,c) *(ptrd++) = (*this)(y,hm1 - x,z,c); } break; case 2 : { // 180 deg res.assign(_width,_height,_depth,_spectrum); T *ptrd = res._data; cimg_forXYZC(res,x,y,z,c) *(ptrd++) = (*this)(wm1 - x,hm1 - y,z,c); } break; case 3 : { // 270 deg res.assign(_height,_width,_depth,_spectrum); T *ptrd = res._data; cimg_forXYZC(res,x,y,z,c) *(ptrd++) = (*this)(wm1 - y,x,z,c); } break; default : // 0 deg return *this; } } else { // Generic angle const float rad = (float)(nangle*cimg::PI/180.), ca = (float)std::cos(rad), sa = (float)std::sin(rad), ux = cimg::abs((_width - 1)*ca), uy = cimg::abs((_width - 1)*sa), vx = cimg::abs((_height - 1)*sa), vy = cimg::abs((_height - 1)*ca), w2 = 0.5f*(_width - 1), h2 = 0.5f*(_height - 1); res.assign((int)cimg::round(1 + ux + vx),(int)cimg::round(1 + uy + vy),_depth,_spectrum); const float rw2 = 0.5f*(res._width - 1), rh2 = 0.5f*(res._height - 1); _rotate(res,nangle,interpolation,boundary_conditions,w2,h2,rw2,rh2); } return res; } //! Rotate image with arbitrary angle, around a center point. /** \param angle Rotation angle, in degrees. \param cx X-coordinate of the rotation center. \param cy Y-coordinate of the rotation center. \param interpolation Type of interpolation, <tt>{ 0=nearest | 1=linear | 2=cubic | 3=mirror }</tt>. \param boundary_conditions Boundary conditions, <tt>{ 0=dirichlet | 1=neumann | 2=periodic | 3=mirror }</tt>. **/ CImg<T>& rotate(const float angle, const float cx, const float cy, const unsigned int interpolation, const unsigned int boundary_conditions=0) { return get_rotate(angle,cx,cy,interpolation,boundary_conditions).move_to(*this); } //! Rotate image with arbitrary angle, around a center point \newinstance. CImg<T> get_rotate(const float angle, const float cx, const float cy, const unsigned int interpolation, const unsigned int boundary_conditions=0) const { if (is_empty()) return *this; CImg<T> res(_width,_height,_depth,_spectrum); _rotate(res,angle,interpolation,boundary_conditions,cx,cy,cx,cy); return res; } // [internal] Perform 2D rotation with arbitrary angle. void _rotate(CImg<T>& res, const float angle, const unsigned int interpolation, const unsigned int boundary_conditions, const float w2, const float h2, const float rw2, const float rh2) const { const float rad = (float)(angle*cimg::PI/180.), ca = (float)std::cos(rad), sa = (float)std::sin(rad); switch (boundary_conditions) { case 3 : { // Mirror switch (interpolation) { case 2 : { // Cubic interpolation const float ww = 2.f*width(), hh = 2.f*height(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZC(res,x,y,z,c) { const float xc = x - rw2, yc = y - rh2, mx = cimg::mod(w2 + xc*ca + yc*sa,ww), my = cimg::mod(h2 - xc*sa + yc*ca,hh); res(x,y,z,c) = _cubic_atXY_c(mx<width()?mx:ww - mx - 1,my<height()?my:hh - my - 1,z,c); } } break; case 1 : { // Linear interpolation const float ww = 2.f*width(), hh = 2.f*height(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZC(res,x,y,z,c) { const float xc = x - rw2, yc = y - rh2, mx = cimg::mod(w2 + xc*ca + yc*sa,ww), my = cimg::mod(h2 - xc*sa + yc*ca,hh); res(x,y,z,c) = (T)_linear_atXY(mx<width()?mx:ww - mx - 1,my<height()?my:hh - my - 1,z,c); } } break; default : { // Nearest-neighbor interpolation const int ww = 2*width(), hh = 2*height(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZC(res,x,y,z,c) { const float xc = x - rw2, yc = y - rh2, mx = cimg::mod((int)cimg::round(w2 + xc*ca + yc*sa),ww), my = cimg::mod((int)cimg::round(h2 - xc*sa + yc*ca),hh); res(x,y,z,c) = (*this)(mx<width()?mx:ww - mx - 1,my<height()?my:hh - my - 1,z,c); } } } } break; case 2 : // Periodic switch (interpolation) { case 2 : { // Cubic interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZC(res,x,y,z,c) { const float xc = x - rw2, yc = y - rh2; res(x,y,z,c) = _cubic_atXY_pc(w2 + xc*ca + yc*sa,h2 - xc*sa + yc*ca,z,c); } } break; case 1 : { // Linear interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZC(res,x,y,z,c) { const float xc = x - rw2, yc = y - rh2; res(x,y,z,c) = (T)_linear_atXY_p(w2 + xc*ca + yc*sa,h2 - xc*sa + yc*ca,z,c); } } break; default : { // Nearest-neighbor interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZC(res,x,y,z,c) { const float xc = x - rw2, yc = y - rh2; res(x,y,z,c) = (*this)(cimg::mod((int)cimg::round(w2 + xc*ca + yc*sa),(float)width()), cimg::mod((int)cimg::round(h2 - xc*sa + yc*ca),(float)height()),z,c); } } } break; case 1 : // Neumann switch (interpolation) { case 2 : { // Cubic interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZC(res,x,y,z,c) { const float xc = x - rw2, yc = y - rh2; res(x,y,z,c) = _cubic_atXY_c(w2 + xc*ca + yc*sa,h2 - xc*sa + yc*ca,z,c); } } break; case 1 : { // Linear interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZC(res,x,y,z,c) { const float xc = x - rw2, yc = y - rh2; res(x,y,z,c) = (T)_linear_atXY(w2 + xc*ca + yc*sa,h2 - xc*sa + yc*ca,z,c); } } break; default : { // Nearest-neighbor interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZC(res,x,y,z,c) { const float xc = x - rw2, yc = y - rh2; res(x,y,z,c) = _atXY((int)cimg::round(w2 + xc*ca + yc*sa), (int)cimg::round(h2 - xc*sa + yc*ca),z,c); } } } break; default : // Dirichlet switch (interpolation) { case 2 : { // Cubic interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZC(res,x,y,z,c) { const float xc = x - rw2, yc = y - rh2; res(x,y,z,c) = cubic_atXY_c(w2 + xc*ca + yc*sa,h2 - xc*sa + yc*ca,z,c,(T)0); } } break; case 1 : { // Linear interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZC(res,x,y,z,c) { const float xc = x - rw2, yc = y - rh2; res(x,y,z,c) = (T)linear_atXY(w2 + xc*ca + yc*sa,h2 - xc*sa + yc*ca,z,c,(T)0); } } break; default : { // Nearest-neighbor interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZC(res,x,y,z,c) { const float xc = x - rw2, yc = y - rh2; res(x,y,z,c) = atXY((int)cimg::round(w2 + xc*ca + yc*sa), (int)cimg::round(h2 - xc*sa + yc*ca),z,c,(T)0); } } } } } //! Rotate volumetric image with arbitrary angle and axis. /** \param u X-coordinate of the 3D rotation axis. \param v Y-coordinate of the 3D rotation axis. \param w Z-coordinate of the 3D rotation axis. \param angle Rotation angle, in degrees. \param interpolation Type of interpolation. Can be <tt>{ 0=nearest | 1=linear | 2=cubic }</tt>. \param boundary_conditions Boundary conditions. Can be <tt>{ 0=dirichlet | 1=neumann | 2=periodic | 3=mirror }</tt>. \note Most of the time, size of the image is modified. **/ CImg<T> rotate(const float u, const float v, const float w, const float angle, const unsigned int interpolation, const unsigned int boundary_conditions) { const float nangle = cimg::mod(angle,360.f); if (nangle==0.f) return *this; return get_rotate(u,v,w,nangle,interpolation,boundary_conditions).move_to(*this); } //! Rotate volumetric image with arbitrary angle and axis \newinstance. CImg<T> get_rotate(const float u, const float v, const float w, const float angle, const unsigned int interpolation, const unsigned int boundary_conditions) const { if (is_empty()) return *this; CImg<T> res; const float w1 = _width - 1, h1 = _height - 1, d1 = _depth -1, w2 = 0.5f*w1, h2 = 0.5f*h1, d2 = 0.5f*d1; CImg<floatT> R = CImg<floatT>::rotation_matrix(u,v,w,angle); const CImg<Tfloat> X = R*CImg<Tfloat>(8,3,1,1, 0.f,w1,w1,0.f,0.f,w1,w1,0.f, 0.f,0.f,h1,h1,0.f,0.f,h1,h1, 0.f,0.f,0.f,0.f,d1,d1,d1,d1); float xm, xM = X.get_shared_row(0).max_min(xm), ym, yM = X.get_shared_row(1).max_min(ym), zm, zM = X.get_shared_row(2).max_min(zm); const int dx = (int)cimg::round(xM - xm), dy = (int)cimg::round(yM - ym), dz = (int)cimg::round(zM - zm); R.transpose(); res.assign(1 + dx,1 + dy,1 + dz,_spectrum); const float rw2 = 0.5f*dx, rh2 = 0.5f*dy, rd2 = 0.5f*dz; _rotate(res,R,interpolation,boundary_conditions,w2,h2,d2,rw2,rh2,rd2); return res; } //! Rotate volumetric image with arbitrary angle and axis, around a center point. /** \param u X-coordinate of the 3D rotation axis. \param v Y-coordinate of the 3D rotation axis. \param w Z-coordinate of the 3D rotation axis. \param angle Rotation angle, in degrees. \param cx X-coordinate of the rotation center. \param cy Y-coordinate of the rotation center. \param cz Z-coordinate of the rotation center. \param interpolation Type of interpolation. Can be <tt>{ 0=nearest | 1=linear | 2=cubic | 3=mirror }</tt>. \param boundary_conditions Boundary conditions. Can be <tt>{ 0=dirichlet | 1=neumann | 2=periodic }</tt>. \note Most of the time, size of the image is modified. **/ CImg<T> rotate(const float u, const float v, const float w, const float angle, const float cx, const float cy, const float cz, const unsigned int interpolation=1, const unsigned int boundary_conditions=0) { const float nangle = cimg::mod(angle,360.f); if (nangle==0.f) return *this; return get_rotate(u,v,w,nangle,cx,cy,cz,interpolation,boundary_conditions).move_to(*this); } //! Rotate volumetric image with arbitrary angle and axis, around a center point \newinstance. CImg<T> get_rotate(const float u, const float v, const float w, const float angle, const float cx, const float cy, const float cz, const unsigned int interpolation=1, const unsigned int boundary_conditions=0) const { if (is_empty()) return *this; CImg<T> res(_width,_height,_depth,_spectrum); CImg<floatT> R = CImg<floatT>::rotation_matrix(u,v,w,-angle); _rotate(res,R,interpolation,boundary_conditions,cx,cy,cz,cx,cy,cz); return res; } // [internal] Perform 3D rotation with arbitrary axis and angle. void _rotate(CImg<T>& res, const CImg<Tfloat>& R, const unsigned int interpolation, const unsigned int boundary_conditions, const float w2, const float h2, const float d2, const float rw2, const float rh2, const float rd2) const { switch (boundary_conditions) { case 3 : // Mirror switch (interpolation) { case 2 : { // Cubic interpolation const float ww = 2.f*width(), hh = 2.f*height(), dd = 2.f*depth(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZ(res,x,y,z) { const float xc = x - rw2, yc = y - rh2, zc = z - rd2, X = cimg::mod((float)(w2 + R(0,0)*xc + R(1,0)*yc + R(2,0)*zc),ww), Y = cimg::mod((float)(h2 + R(0,1)*xc + R(1,1)*yc + R(2,1)*zc),hh), Z = cimg::mod((float)(d2 + R(0,2)*xc + R(1,2)*yc + R(2,2)*zc),dd); cimg_forC(res,c) res(x,y,z,c) = _cubic_atXYZ_c(X<width()?X:ww - X - 1, Y<height()?Y:hh - Y - 1, Z<depth()?Z:dd - Z - z,c); } } break; case 1 : { // Linear interpolation const float ww = 2.f*width(), hh = 2.f*height(), dd = 2.f*depth(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZ(res,x,y,z) { const float xc = x - rw2, yc = y - rh2, zc = z - rd2, X = cimg::mod((float)(w2 + R(0,0)*xc + R(1,0)*yc + R(2,0)*zc),ww), Y = cimg::mod((float)(h2 + R(0,1)*xc + R(1,1)*yc + R(2,1)*zc),hh), Z = cimg::mod((float)(d2 + R(0,2)*xc + R(1,2)*yc + R(2,2)*zc),dd); cimg_forC(res,c) res(x,y,z,c) = (T)_linear_atXYZ(X<width()?X:ww - X - 1, Y<height()?Y:hh - Y - 1, Z<depth()?Z:dd - Z - 1,c); } } break; default : { // Nearest-neighbor interpolation const int ww = 2*width(), hh = 2*height(), dd = 2*depth(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZ(res,x,y,z) { const float xc = x - rw2, yc = y - rh2, zc = z - rd2; const int X = cimg::mod((int)cimg::round(w2 + R(0,0)*xc + R(1,0)*yc + R(2,0)*zc),ww), Y = cimg::mod((int)cimg::round(h2 + R(0,1)*xc + R(1,1)*yc + R(2,1)*zc),hh), Z = cimg::mod((int)cimg::round(d2 + R(0,2)*xc + R(1,2)*yc + R(2,2)*zc),dd); cimg_forC(res,c) res(x,y,z,c) = (*this)(X<width()?X:ww - X - 1, Y<height()?Y:hh - Y - 1, Z<depth()?Z:dd - Z - 1,c); } } } break; case 2 : // Periodic switch (interpolation) { case 2 : { // Cubic interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZ(res,x,y,z) { const float xc = x - rw2, yc = y - rh2, zc = z - rd2, X = w2 + R(0,0)*xc + R(1,0)*yc + R(2,0)*zc, Y = h2 + R(0,1)*xc + R(1,1)*yc + R(2,1)*zc, Z = d2 + R(0,2)*xc + R(1,2)*yc + R(2,2)*zc; cimg_forC(res,c) res(x,y,z,c) = _cubic_atXYZ_pc(X,Y,Z,c); } } break; case 1 : { // Linear interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZ(res,x,y,z) { const float xc = x - rw2, yc = y - rh2, zc = z - rd2, X = w2 + R(0,0)*xc + R(1,0)*yc + R(2,0)*zc, Y = h2 + R(0,1)*xc + R(1,1)*yc + R(2,1)*zc, Z = d2 + R(0,2)*xc + R(1,2)*yc + R(2,2)*zc; cimg_forC(res,c) res(x,y,z,c) = (T)_linear_atXYZ_p(X,Y,Z,c); } } break; default : { // Nearest-neighbor interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZ(res,x,y,z) { const float xc = x - rw2, yc = y - rh2, zc = z - rd2; const int X = cimg::mod((int)cimg::round(w2 + R(0,0)*xc + R(1,0)*yc + R(2,0)*zc),width()), Y = cimg::mod((int)cimg::round(h2 + R(0,1)*xc + R(1,1)*yc + R(2,1)*zc),height()), Z = cimg::mod((int)cimg::round(d2 + R(0,2)*xc + R(1,2)*yc + R(2,2)*zc),depth()); cimg_forC(res,c) res(x,y,z,c) = (*this)(X,Y,Z,c); } } } break; case 1 : // Neumann switch (interpolation) { case 2 : { // Cubic interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZ(res,x,y,z) { const float xc = x - rw2, yc = y - rh2, zc = z - rd2, X = w2 + R(0,0)*xc + R(1,0)*yc + R(2,0)*zc, Y = h2 + R(0,1)*xc + R(1,1)*yc + R(2,1)*zc, Z = d2 + R(0,2)*xc + R(1,2)*yc + R(2,2)*zc; cimg_forC(res,c) res(x,y,z,c) = _cubic_atXYZ_c(X,Y,Z,c); } } break; case 1 : { // Linear interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZ(res,x,y,z) { const float xc = x - rw2, yc = y - rh2, zc = z - rd2, X = w2 + R(0,0)*xc + R(1,0)*yc + R(2,0)*zc, Y = h2 + R(0,1)*xc + R(1,1)*yc + R(2,1)*zc, Z = d2 + R(0,2)*xc + R(1,2)*yc + R(2,2)*zc; cimg_forC(res,c) res(x,y,z,c) = _linear_atXYZ(X,Y,Z,c); } } break; default : { // Nearest-neighbor interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZ(res,x,y,z) { const float xc = x - rw2, yc = y - rh2, zc = z - rd2; const int X = (int)cimg::round(w2 + R(0,0)*xc + R(1,0)*yc + R(2,0)*zc), Y = (int)cimg::round(h2 + R(0,1)*xc + R(1,1)*yc + R(2,1)*zc), Z = (int)cimg::round(d2 + R(0,2)*xc + R(1,2)*yc + R(2,2)*zc); cimg_forC(res,c) res(x,y,z,c) = _atXYZ(X,Y,Z,c); } } } break; default : // Dirichlet switch (interpolation) { case 2 : { // Cubic interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZ(res,x,y,z) { const float xc = x - rw2, yc = y - rh2, zc = z - rd2, X = w2 + R(0,0)*xc + R(1,0)*yc + R(2,0)*zc, Y = h2 + R(0,1)*xc + R(1,1)*yc + R(2,1)*zc, Z = d2 + R(0,2)*xc + R(1,2)*yc + R(2,2)*zc; cimg_forC(res,c) res(x,y,z,c) = cubic_atXYZ_c(X,Y,Z,c,(T)0); } } break; case 1 : { // Linear interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZ(res,x,y,z) { const float xc = x - rw2, yc = y - rh2, zc = z - rd2, X = w2 + R(0,0)*xc + R(1,0)*yc + R(2,0)*zc, Y = h2 + R(0,1)*xc + R(1,1)*yc + R(2,1)*zc, Z = d2 + R(0,2)*xc + R(1,2)*yc + R(2,2)*zc; cimg_forC(res,c) res(x,y,z,c) = linear_atXYZ(X,Y,Z,c,(T)0); } } break; default : { // Nearest-neighbor interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZ(res,x,y,z) { const float xc = x - rw2, yc = y - rh2, zc = z - rd2; const int X = (int)cimg::round(w2 + R(0,0)*xc + R(1,0)*yc + R(2,0)*zc), Y = (int)cimg::round(h2 + R(0,1)*xc + R(1,1)*yc + R(2,1)*zc), Z = (int)cimg::round(d2 + R(0,2)*xc + R(1,2)*yc + R(2,2)*zc); cimg_forC(res,c) res(x,y,z,c) = atXYZ(X,Y,Z,c,(T)0); } } } break; } } //! Warp image content by a warping field. /** \param warp Warping field. \param mode Can be { 0=backward-absolute | 1=backward-relative | 2=forward-absolute | 3=foward-relative } \param interpolation Can be <tt>{ 0=nearest | 1=linear | 2=cubic }</tt>. \param boundary_conditions Boundary conditions <tt>{ 0=dirichlet | 1=neumann | 2=periodic | 3=mirror }</tt>. **/ template<typename t> CImg<T>& warp(const CImg<t>& p_warp, const unsigned int mode=0, const unsigned int interpolation=1, const unsigned int boundary_conditions=0) { return get_warp(p_warp,mode,interpolation,boundary_conditions).move_to(*this); } //! Warp image content by a warping field \newinstance template<typename t> CImg<T> get_warp(const CImg<t>& p_warp, const unsigned int mode=0, const unsigned int interpolation=1, const unsigned int boundary_conditions=0) const { if (is_empty() || !p_warp) return *this; if (mode && !is_sameXYZ(p_warp)) throw CImgArgumentException(_cimg_instance "warp(): Instance and specified relative warping field (%u,%u,%u,%u,%p) " "have different XYZ dimensions.", cimg_instance, p_warp._width,p_warp._height,p_warp._depth,p_warp._spectrum,p_warp._data); CImg<T> res(p_warp._width,p_warp._height,p_warp._depth,_spectrum); if (p_warp._spectrum==1) { // 1D warping if (mode>=3) { // Forward-relative warp res.fill((T)0); if (interpolation>=1) // Linear interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); const T *ptrs = data(0,y,z,c); cimg_forX(res,x) res.set_linear_atX(*(ptrs++),x + (float)*(ptrs0++),y,z,c); } else // Nearest-neighbor interpolation cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); const T *ptrs = data(0,y,z,c); cimg_forX(res,x) { const int X = x + (int)cimg::round(*(ptrs0++)); if (X>=0 && X<width()) res(X,y,z,c) = *(ptrs++); } } } else if (mode==2) { // Forward-absolute warp res.fill((T)0); if (interpolation>=1) // Linear interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); const T *ptrs = data(0,y,z,c); cimg_forX(res,x) res.set_linear_atX(*(ptrs++),(float)*(ptrs0++),y,z,c); } else // Nearest-neighbor interpolation cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); const T *ptrs = data(0,y,z,c); cimg_forX(res,x) { const int X = (int)cimg::round(*(ptrs0++)); if (X>=0 && X<width()) res(X,y,z,c) = *(ptrs++); } } } else if (mode==1) { // Backward-relative warp if (interpolation==2) // Cubic interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*width(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const float mx = cimg::mod(x - (float)*(ptrs0++),w2); *(ptrd++) = _cubic_atX_c(mx<width()?mx:w2 - mx - 1,y,z,c); } } } break; case 2 : // Periodic cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _cubic_atX_pc(x - (float)*(ptrs0++),y,z,c); } break; case 1 : // Neumann cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _cubic_atX_c(x - (float)*(ptrs0++),y,z,c); } break; default : // Dirichlet cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = cubic_atX_c(x - (float)*(ptrs0++),y,z,c,(T)0); } } else if (interpolation==1) // Linear interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*width(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const float mx = cimg::mod(x - (float)*(ptrs0++),w2); *(ptrd++) = (T)_linear_atX(mx<width()?mx:w2 - mx - 1,y,z,c); } } } break; case 2 : // Periodic cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)_linear_atX_p(x - (float)*(ptrs0++),y,z,c); } break; case 1 : // Neumann cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)_linear_atX(x - (float)*(ptrs0++),y,z,c); } break; default : // Dirichlet cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)linear_atX(x - (float)*(ptrs0++),y,z,c,(T)0); } } else // Nearest-neighbor interpolation switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*width(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const int mx = cimg::mod(x - (int)cimg::round(*(ptrs0++)),w2); *(ptrd++) = (*this)(mx<width()?mx:w2 - mx - 1,y,z,c); } } } break; case 2 : // Periodic cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (*this)(cimg::mod(x - (int)cimg::round(*(ptrs0++)),width()),y,z,c); } break; case 1 : // Neumann cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _atX(x - (int)cimg::round(*(ptrs0++)),y,z,c); } break; default : // Dirichlet cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = atX(x - (int)cimg::round(*(ptrs0++)),y,z,c,(T)0); } } } else { // Backward-absolute warp if (interpolation==2) // Cubic interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*width(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const float mx = cimg::mod((float)*(ptrs0++),w2); *(ptrd++) = _cubic_atX_c(mx<width()?mx:w2 - mx - 1,0,0,c); } } } break; case 2 : // Periodic cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _cubic_atX_pc((float)*(ptrs0++),0,0,c); } break; case 1 : // Neumann cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _cubic_atX_c((float)*(ptrs0++),0,0,c); } break; default : // Dirichlet cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = cubic_atX_c((float)*(ptrs0++),0,0,c,(T)0); } } else if (interpolation==1) // Linear interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*width(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const float mx = cimg::mod((float)*(ptrs0++),w2); *(ptrd++) = (T)_linear_atX(mx<width()?mx:w2 - mx - 1,0,0,c); } } } break; case 2 : // Periodic cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)_linear_atX_p((float)*(ptrs0++),0,0,c); } break; case 1 : // Neumann cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)_linear_atX((float)*(ptrs0++),0,0,c); } break; default : // Dirichlet cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)linear_atX((float)*(ptrs0++),0,0,c,(T)0); } } else // Nearest-neighbor interpolation switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*width(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const int mx = cimg::mod((int)cimg::round(*(ptrs0++)),w2); *(ptrd++) = (*this)(mx<width()?mx:w2 - mx - 1,0,0,c); } } } break; case 2 : // Periodic cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (*this)(cimg::mod((int)cimg::round(*(ptrs0++)),width()),0,0,c); } break; case 1 : // Neumann cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _atX((int)cimg::round(*(ptrs0++)),0,0,c); } break; default : // Dirichlet cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = atX((int)cimg::round(*(ptrs0++)),0,0,c,(T)0); } } } } else if (p_warp._spectrum==2) { // 2D warping if (mode>=3) { // Forward-relative warp res.fill((T)0); if (interpolation>=1) // Linear interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); const T *ptrs = data(0,y,z,c); cimg_forX(res,x) res.set_linear_atXY(*(ptrs++),x + (float)*(ptrs0++),y + (float)*(ptrs1++),z,c); } else // Nearest-neighbor interpolation cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); const T *ptrs = data(0,y,z,c); cimg_forX(res,x) { const int X = x + (int)cimg::round(*(ptrs0++)), Y = y + (int)cimg::round(*(ptrs1++)); if (X>=0 && X<width() && Y>=0 && Y<height()) res(X,Y,z,c) = *(ptrs++); } } } else if (mode==2) { // Forward-absolute warp res.fill((T)0); if (interpolation>=1) // Linear interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); const T *ptrs = data(0,y,z,c); cimg_forX(res,x) res.set_linear_atXY(*(ptrs++),(float)*(ptrs0++),(float)*(ptrs1++),z,c); } else // Nearest-neighbor interpolation cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); const T *ptrs = data(0,y,z,c); cimg_forX(res,x) { const int X = (int)cimg::round(*(ptrs0++)), Y = (int)cimg::round(*(ptrs1++)); if (X>=0 && X<width() && Y>=0 && Y<height()) res(X,Y,z,c) = *(ptrs++); } } } else if (mode==1) { // Backward-relative warp if (interpolation==2) // Cubic interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*width(), h2 = 2.f*height(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const float mx = cimg::mod(x - (float)*(ptrs0++),w2), my = cimg::mod(y - (float)*(ptrs1++),h2); *(ptrd++) = _cubic_atXY_c(mx<width()?mx:w2 - mx - 1,my<height()?my:h2 - my - 1,z,c); } } } break; case 2 : // Periodic cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _cubic_atXY_pc(x - (float)*(ptrs0++),y - (float)*(ptrs1++),z,c); } break; case 1 : // Neumann cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _cubic_atXY_c(x - (float)*(ptrs0++),y - (float)*(ptrs1++),z,c); } break; default : // Dirichlet cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = cubic_atXY_c(x - (float)*(ptrs0++),y - (float)*(ptrs1++),z,c,(T)0); } } else if (interpolation==1) // Linear interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*width(), h2 = 2.f*height(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const float mx = cimg::mod(x - (float)*(ptrs0++),w2), my = cimg::mod(y - (float)*(ptrs1++),h2); *(ptrd++) = (T)_linear_atXY(mx<width()?mx:w2 - mx - 1,my<height()?my:h2 - my - 1,z,c); } } } break; case 2 : // Periodic cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)_linear_atXY_p(x - (float)*(ptrs0++),y - (float)*(ptrs1++),z,c); } break; case 1 : // Neumann cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)_linear_atXY(x - (float)*(ptrs0++),y - (float)*(ptrs1++),z,c); } break; default : // Dirichlet cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)linear_atXY(x - (float)*(ptrs0++),y - (float)*(ptrs1++),z,c,(T)0); } } else // Nearest-neighbor interpolation switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*width(), h2 = 2*height(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const int mx = cimg::mod(x - (int)cimg::round(*(ptrs0++)),w2), my = cimg::mod(y - (int)cimg::round(*(ptrs1++)),h2); *(ptrd++) = (*this)(mx<width()?mx:w2 - mx - 1,my<height()?my:h2 - my - 1,z,c); } } } break; case 2 : // Periodic cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (*this)(cimg::mod(x - (int)cimg::round(*(ptrs0++)),width()), cimg::mod(y - (int)cimg::round(*(ptrs1++)),height()),z,c); } break; case 1 : // Neumann cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _atXY(x - (int)cimg::round(*(ptrs0++)), y - (int)cimg::round(*(ptrs1++)),z,c); } break; default : // Dirichlet cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = atXY(x - (int)cimg::round(*(ptrs0++)), y - (int)cimg::round(*(ptrs1++)),z,c,(T)0); } } } else { // Backward-absolute warp if (interpolation==2) // Cubic interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*width(), h2 = 2.f*height(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const float mx = cimg::mod((float)*(ptrs0++),w2), my = cimg::mod((float)*(ptrs1++),h2); *(ptrd++) = _cubic_atXY_c(mx<width()?mx:w2 - mx - 1,my<height()?my:h2 - my - 1,0,c); } } } break; case 2 : // Periodic cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _cubic_atXY_pc((float)*(ptrs0++),(float)*(ptrs1++),0,c); } break; case 1 : // Neumann cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _cubic_atXY_c((float)*(ptrs0++),(float)*(ptrs1++),0,c); } break; default : // Dirichlet cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = cubic_atXY_c((float)*(ptrs0++),(float)*(ptrs1++),0,c,(T)0); } } else if (interpolation==1) // Linear interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*width(), h2 = 2.f*height(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const float mx = cimg::mod((float)*(ptrs0++),w2), my = cimg::mod((float)*(ptrs1++),h2); *(ptrd++) = (T)_linear_atXY(mx<width()?mx:w2 - mx - 1,my<height()?my:h2 - my - 1,0,c); } } } break; case 2 : // Periodic cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)_linear_atXY_p((float)*(ptrs0++),(float)*(ptrs1++),0,c); } break; case 1 : // Neumann cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)_linear_atXY((float)*(ptrs0++),(float)*(ptrs1++),0,c); } break; default : // Dirichlet cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)linear_atXY((float)*(ptrs0++),(float)*(ptrs1++),0,c,(T)0); } } else // Nearest-neighbor interpolation switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*width(), h2 = 2*height(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const int mx = cimg::mod((int)cimg::round(*(ptrs0++)),w2), my = cimg::mod((int)cimg::round(*(ptrs1++)),h2); *(ptrd++) = (*this)(mx<width()?mx:w2 - mx - 1,my<height()?my:h2 - my - 1,0,c); } } } break; case 2 : // Periodic cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (*this)(cimg::mod((int)cimg::round(*(ptrs0++)),width()), cimg::mod((int)cimg::round(*(ptrs1++)),height()),0,c); } break; case 1 : // Neumann cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _atXY((int)cimg::round(*(ptrs0++)), (int)cimg::round(*(ptrs1++)),0,c); } break; default : // Dirichlet cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = atXY((int)cimg::round(*(ptrs0++)), (int)cimg::round(*(ptrs1++)),0,c,(T)0); } } } } else { // 3D warping if (mode>=3) { // Forward-relative warp res.fill((T)0); if (interpolation>=1) // Linear interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); const T *ptrs = data(0,y,z,c); cimg_forX(res,x) res.set_linear_atXYZ(*(ptrs++),x + (float)*(ptrs0++),y + (float)*(ptrs1++), z + (float)*(ptrs2++),c); } else // Nearest-neighbor interpolation cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); const T *ptrs = data(0,y,z,c); cimg_forX(res,x) { const int X = x + (int)cimg::round(*(ptrs0++)), Y = y + (int)cimg::round(*(ptrs1++)), Z = z + (int)cimg::round(*(ptrs2++)); if (X>=0 && X<width() && Y>=0 && Y<height() && Z>=0 && Z<depth()) res(X,Y,Z,c) = *(ptrs++); } } } else if (mode==2) { // Forward-absolute warp res.fill((T)0); if (interpolation>=1) // Linear interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); const T *ptrs = data(0,y,z,c); cimg_forX(res,x) res.set_linear_atXYZ(*(ptrs++),(float)*(ptrs0++),(float)*(ptrs1++),(float)*(ptrs2++),c); } else // Nearest-neighbor interpolation cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); const T *ptrs = data(0,y,z,c); cimg_forX(res,x) { const int X = (int)cimg::round(*(ptrs0++)), Y = (int)cimg::round(*(ptrs1++)), Z = (int)cimg::round(*(ptrs2++)); if (X>=0 && X<width() && Y>=0 && Y<height() && Z>=0 && Z<depth()) res(X,Y,Z,c) = *(ptrs++); } } } else if (mode==1) { // Backward-relative warp if (interpolation==2) // Cubic interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*width(), h2 = 2.f*height(), d2 = 2.f*depth(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const float mx = cimg::mod(x - (float)*(ptrs0++),w2), my = cimg::mod(y - (float)*(ptrs1++),h2), mz = cimg::mod(z - (float)*(ptrs2++),d2); *(ptrd++) = _cubic_atXYZ_c(mx<width()?mx:w2 - mx - 1, my<height()?my:h2 - my - 1, mz<depth()?mz:d2 - mz - 1,c); } } } break; case 2 : // Periodic cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _cubic_atXYZ_pc(x - (float)*(ptrs0++),y - (float)*(ptrs1++),z - (float)*(ptrs2++),c); } break; case 1 : // Neumann cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _cubic_atXYZ_c(x - (float)*(ptrs0++),y - (float)*(ptrs1++),z - (float)*(ptrs2++),c); } break; default : // Dirichlet cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = cubic_atXYZ_c(x - (float)*(ptrs0++),y - (float)*(ptrs1++),z - (float)*(ptrs2++),c,(T)0); } } else if (interpolation==1) // Linear interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*width(), h2 = 2.f*height(), d2 = 2.f*depth(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const float mx = cimg::mod(x - (float)*(ptrs0++),w2), my = cimg::mod(y - (float)*(ptrs1++),h2), mz = cimg::mod(z - (float)*(ptrs2++),d2); *(ptrd++) = (T)_linear_atXYZ(mx<width()?mx:w2 - mx - 1, my<height()?my:h2 - my - 1, mz<depth()?mz:d2 - mz - 1,c); } } } break; case 2 : // Periodic cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)_linear_atXYZ_p(x - (float)*(ptrs0++),y - (float)*(ptrs1++), z - (float)*(ptrs2++),c); } break; case 1 : // Neumann cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)_linear_atXYZ(x - (float)*(ptrs0++),y - (float)*(ptrs1++),z - (float)*(ptrs2++),c); } break; default : // Dirichlet cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)linear_atXYZ(x - (float)*(ptrs0++),y - (float)*(ptrs1++),z - (float)*(ptrs2++),c,(T)0); } } else // Nearest neighbor interpolation switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*width(), h2 = 2*height(), d2 = 2*depth(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const int mx = cimg::mod(x - (int)cimg::round(*(ptrs0++)),w2), my = cimg::mod(y - (int)cimg::round(*(ptrs1++)),h2), mz = cimg::mod(z - (int)cimg::round(*(ptrs2++)),d2); *(ptrd++) = (*this)(mx<width()?mx:w2 - mx - 1, my<height()?my:h2 - my - 1, mz<depth()?mz:d2 - mz - 1,c); } } } break; case 2 : // Periodic cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (*this)(cimg::mod(x - (int)cimg::round(*(ptrs0++)),width()), cimg::mod(y - (int)cimg::round(*(ptrs1++)),height()), cimg::mod(z - (int)cimg::round(*(ptrs2++)),depth()),c); } break; case 1 : // Neumann cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _atXYZ(x - (int)cimg::round(*(ptrs0++)), y - (int)cimg::round(*(ptrs1++)), z - (int)cimg::round(*(ptrs2++)),c); } break; default : // Dirichlet cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = atXYZ(x - (int)cimg::round(*(ptrs0++)), y - (int)cimg::round(*(ptrs1++)), z - (int)cimg::round(*(ptrs2++)),c,(T)0); } } } else { // Backward-absolute warp if (interpolation==2) // Cubic interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*width(), h2 = 2.f*height(), d2 = 2.f*depth(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const float mx = cimg::mod((float)*(ptrs0++),w2), my = cimg::mod((float)*(ptrs1++),h2), mz = cimg::mod((float)*(ptrs2++),d2); *(ptrd++) = _cubic_atXYZ_c(mx<width()?mx:w2 - mx - 1, my<height()?my:h2 - my - 1, mz<depth()?mz:d2 - mz - 1,c); } } } break; case 2 : // Periodic cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _cubic_atXYZ_pc((float)*(ptrs0++),(float)*(ptrs1++),(float)*(ptrs2++),c); } break; case 1 : // Neumann cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _cubic_atXYZ_c((float)*(ptrs0++),(float)*(ptrs1++),(float)*(ptrs2++),c); } break; default : // Dirichlet cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = cubic_atXYZ_c((float)*(ptrs0++),(float)*(ptrs1++),(float)*(ptrs2++), c,(T)0); } } else if (interpolation==1) // Linear interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*width(), h2 = 2.f*height(), d2 = 2.f*depth(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const float mx = cimg::mod((float)*(ptrs0++),w2), my = cimg::mod((float)*(ptrs1++),h2), mz = cimg::mod((float)*(ptrs2++),d2); *(ptrd++) = (T)_linear_atXYZ(mx<width()?mx:w2 - mx - 1, my<height()?my:h2 - my - 1, mz<depth()?mz:d2 - mz - 1,c); } } } break; case 2 :// Periodic cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)_linear_atXYZ_p((float)*(ptrs0++),(float)*(ptrs1++), (float)*(ptrs2++),c); } break; case 1 : // Neumann cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)_linear_atXYZ((float)*(ptrs0++),(float)*(ptrs1++),(float)*(ptrs2++),c); } break; default : // Dirichlet cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)linear_atXYZ((float)*(ptrs0++),(float)*(ptrs1++),(float)*(ptrs2++), c,(T)0); } } else // Nearest-neighbor interpolation switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*width(), h2 = 2*height(), d2 = 2*depth(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const int mx = cimg::mod((int)cimg::round(*(ptrs0++)),w2), my = cimg::mod((int)cimg::round(*(ptrs1++)),h2), mz = cimg::mod((int)cimg::round(*(ptrs2++)),d2); *(ptrd++) = (*this)(mx<width()?mx:w2 - mx - 1, my<height()?my:h2 - my - 1, mz<depth()?mz:d2 - mz - 1,c); } } } break; case 2 : // Periodic cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (*this)(cimg::mod((int)cimg::round(*(ptrs0++)),width()), cimg::mod((int)cimg::round(*(ptrs1++)),height()), cimg::mod((int)cimg::round(*(ptrs2++)),depth()),c); } break; case 1 : // Neumann cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _atXYZ((int)cimg::round(*(ptrs0++)), (int)cimg::round(*(ptrs1++)), (int)cimg::round(*(ptrs2++)),c); } break; default : // Dirichlet cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = atXYZ((int)cimg::round(*(ptrs0++)), (int)cimg::round(*(ptrs1++)), (int)cimg::round(*(ptrs2++)),c,(T)0); } } } } return res; } //! Generate a 2D representation of a 3D image, with XY,XZ and YZ views. /** \param x0 X-coordinate of the projection point. \param y0 Y-coordinate of the projection point. \param z0 Z-coordinate of the projection point. **/ CImg<T> get_projections2d(const unsigned int x0, const unsigned int y0, const unsigned int z0) const { if (is_empty() || _depth<2) return +*this; const unsigned int _x0 = (x0>=_width)?_width - 1:x0, _y0 = (y0>=_height)?_height - 1:y0, _z0 = (z0>=_depth)?_depth - 1:z0; const CImg<T> img_xy = get_crop(0,0,_z0,0,_width - 1,_height - 1,_z0,_spectrum - 1), img_zy = get_crop(_x0,0,0,0,_x0,_height - 1,_depth - 1,_spectrum - 1).permute_axes("xzyc"). resize(_depth,_height,1,-100,-1), img_xz = get_crop(0,_y0,0,0,_width - 1,_y0,_depth - 1,_spectrum - 1).resize(_width,_depth,1,-100,-1); return CImg<T>(_width + _depth,_height + _depth,1,_spectrum,cimg::min(img_xy.min(),img_zy.min(),img_xz.min())). draw_image(0,0,img_xy).draw_image(img_xy._width,0,img_zy). draw_image(0,img_xy._height,img_xz); } //! Construct a 2D representation of a 3D image, with XY,XZ and YZ views \inplace. CImg<T>& projections2d(const unsigned int x0, const unsigned int y0, const unsigned int z0) { if (_depth<2) return *this; return get_projections2d(x0,y0,z0).move_to(*this); } //! Crop image region. /** \param x0 = X-coordinate of the upper-left crop rectangle corner. \param y0 = Y-coordinate of the upper-left crop rectangle corner. \param z0 = Z-coordinate of the upper-left crop rectangle corner. \param c0 = C-coordinate of the upper-left crop rectangle corner. \param x1 = X-coordinate of the lower-right crop rectangle corner. \param y1 = Y-coordinate of the lower-right crop rectangle corner. \param z1 = Z-coordinate of the lower-right crop rectangle corner. \param c1 = C-coordinate of the lower-right crop rectangle corner. \param boundary_conditions = Can be { 0=dirichlet | 1=neumann | 2=periodic | 3=mirror }. **/ CImg<T>& crop(const int x0, const int y0, const int z0, const int c0, const int x1, const int y1, const int z1, const int c1, const unsigned int boundary_conditions=0) { return get_crop(x0,y0,z0,c0,x1,y1,z1,c1,boundary_conditions).move_to(*this); } //! Crop image region \newinstance. CImg<T> get_crop(const int x0, const int y0, const int z0, const int c0, const int x1, const int y1, const int z1, const int c1, const unsigned int boundary_conditions=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "crop(): Empty instance.", cimg_instance); const int nx0 = x0<x1?x0:x1, nx1 = x0^x1^nx0, ny0 = y0<y1?y0:y1, ny1 = y0^y1^ny0, nz0 = z0<z1?z0:z1, nz1 = z0^z1^nz0, nc0 = c0<c1?c0:c1, nc1 = c0^c1^nc0; CImg<T> res(1U + nx1 - nx0,1U + ny1 - ny0,1U + nz1 - nz0,1U + nc1 - nc0); if (nx0<0 || nx1>=width() || ny0<0 || ny1>=height() || nz0<0 || nz1>=depth() || nc0<0 || nc1>=spectrum()) switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*width(), h2 = 2*height(), d2 = 2*depth(), s2 = 2*spectrum(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*16 && _height*_depth*_spectrum>=4)) cimg_forXYZC(res,x,y,z,c) { const int mx = cimg::mod(nx0 + x,w2), my = cimg::mod(ny0 + y,h2), mz = cimg::mod(nz0 + z,d2), mc = cimg::mod(nc0 + c,s2); res(x,y,z,c) = (*this)(mx<width()?mx:w2 - mx - 1, my<height()?my:h2 - my - 1, mz<depth()?mz:d2 - mz - 1, mc<spectrum()?mc:s2 - mc - 1); } } break; case 2 : { // Periodic cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*16 && _height*_depth*_spectrum>=4)) cimg_forXYZC(res,x,y,z,c) { res(x,y,z,c) = (*this)(cimg::mod(nx0 + x,width()),cimg::mod(ny0 + y,height()), cimg::mod(nz0 + z,depth()),cimg::mod(nc0 + c,spectrum())); } } break; case 1 : // Neumann cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*16 && _height*_depth*_spectrum>=4)) cimg_forXYZC(res,x,y,z,c) res(x,y,z,c) = _atXYZC(nx0 + x,ny0 + y,nz0 + z,nc0 + c); break; default : // Dirichlet res.fill((T)0).draw_image(-nx0,-ny0,-nz0,-nc0,*this); } else res.draw_image(-nx0,-ny0,-nz0,-nc0,*this); return res; } //! Crop image region \overloading. CImg<T>& crop(const int x0, const int y0, const int z0, const int x1, const int y1, const int z1, const unsigned int boundary_conditions=0) { return crop(x0,y0,z0,0,x1,y1,z1,_spectrum - 1,boundary_conditions); } //! Crop image region \newinstance. CImg<T> get_crop(const int x0, const int y0, const int z0, const int x1, const int y1, const int z1, const unsigned int boundary_conditions=0) const { return get_crop(x0,y0,z0,0,x1,y1,z1,_spectrum - 1,boundary_conditions); } //! Crop image region \overloading. CImg<T>& crop(const int x0, const int y0, const int x1, const int y1, const unsigned int boundary_conditions=0) { return crop(x0,y0,0,0,x1,y1,_depth - 1,_spectrum - 1,boundary_conditions); } //! Crop image region \newinstance. CImg<T> get_crop(const int x0, const int y0, const int x1, const int y1, const unsigned int boundary_conditions=0) const { return get_crop(x0,y0,0,0,x1,y1,_depth - 1,_spectrum - 1,boundary_conditions); } //! Crop image region \overloading. CImg<T>& crop(const int x0, const int x1, const unsigned int boundary_conditions=0) { return crop(x0,0,0,0,x1,_height - 1,_depth - 1,_spectrum - 1,boundary_conditions); } //! Crop image region \newinstance. CImg<T> get_crop(const int x0, const int x1, const unsigned int boundary_conditions=0) const { return get_crop(x0,0,0,0,x1,_height - 1,_depth - 1,_spectrum - 1,boundary_conditions); } //! Autocrop image region, regarding the specified background value. CImg<T>& autocrop(const T& value, const char *const axes="czyx") { if (is_empty()) return *this; for (const char *s = axes; *s; ++s) { const char axis = cimg::lowercase(*s); const CImg<intT> coords = _autocrop(value,axis); if (coords[0]==-1 && coords[1]==-1) return assign(); // Image has only 'value' pixels else switch (axis) { case 'x' : { const int x0 = coords[0], x1 = coords[1]; if (x0>=0 && x1>=0) crop(x0,x1); } break; case 'y' : { const int y0 = coords[0], y1 = coords[1]; if (y0>=0 && y1>=0) crop(0,y0,_width - 1,y1); } break; case 'z' : { const int z0 = coords[0], z1 = coords[1]; if (z0>=0 && z1>=0) crop(0,0,z0,_width - 1,_height - 1,z1); } break; default : { const int c0 = coords[0], c1 = coords[1]; if (c0>=0 && c1>=0) crop(0,0,0,c0,_width - 1,_height - 1,_depth - 1,c1); } } } return *this; } //! Autocrop image region, regarding the specified background value \newinstance. CImg<T> get_autocrop(const T& value, const char *const axes="czyx") const { return (+*this).autocrop(value,axes); } //! Autocrop image region, regarding the specified background color. /** \param color Color used for the crop. If \c 0, color is guessed. \param axes Axes used for the crop. **/ CImg<T>& autocrop(const T *const color=0, const char *const axes="zyx") { if (is_empty()) return *this; if (!color) { // Guess color const CImg<T> col1 = get_vector_at(0,0,0); const unsigned int w = _width, h = _height, d = _depth, s = _spectrum; autocrop(col1,axes); if (_width==w && _height==h && _depth==d && _spectrum==s) { const CImg<T> col2 = get_vector_at(w - 1,h - 1,d - 1); autocrop(col2,axes); } return *this; } for (const char *s = axes; *s; ++s) { const char axis = cimg::lowercase(*s); switch (axis) { case 'x' : { int x0 = width(), x1 = -1; cimg_forC(*this,c) { const CImg<intT> coords = get_shared_channel(c)._autocrop(color[c],'x'); const int nx0 = coords[0], nx1 = coords[1]; if (nx0>=0 && nx1>=0) { x0 = std::min(x0,nx0); x1 = std::max(x1,nx1); } } if (x0==width() && x1==-1) return assign(); else crop(x0,x1); } break; case 'y' : { int y0 = height(), y1 = -1; cimg_forC(*this,c) { const CImg<intT> coords = get_shared_channel(c)._autocrop(color[c],'y'); const int ny0 = coords[0], ny1 = coords[1]; if (ny0>=0 && ny1>=0) { y0 = std::min(y0,ny0); y1 = std::max(y1,ny1); } } if (y0==height() && y1==-1) return assign(); else crop(0,y0,_width - 1,y1); } break; default : { int z0 = depth(), z1 = -1; cimg_forC(*this,c) { const CImg<intT> coords = get_shared_channel(c)._autocrop(color[c],'z'); const int nz0 = coords[0], nz1 = coords[1]; if (nz0>=0 && nz1>=0) { z0 = std::min(z0,nz0); z1 = std::max(z1,nz1); } } if (z0==depth() && z1==-1) return assign(); else crop(0,0,z0,_width - 1,_height - 1,z1); } } } return *this; } //! Autocrop image region, regarding the specified background color \newinstance. CImg<T> get_autocrop(const T *const color=0, const char *const axes="zyx") const { return (+*this).autocrop(color,axes); } CImg<intT> _autocrop(const T& value, const char axis) const { CImg<intT> res; switch (cimg::lowercase(axis)) { case 'x' : { int x0 = -1, x1 = -1; cimg_forX(*this,x) cimg_forYZC(*this,y,z,c) if ((*this)(x,y,z,c)!=value) { x0 = x; x = width(); y = height(); z = depth(); c = spectrum(); } if (x0>=0) { for (int x = width() - 1; x>=0; --x) cimg_forYZC(*this,y,z,c) if ((*this)(x,y,z,c)!=value) { x1 = x; x = 0; y = height(); z = depth(); c = spectrum(); } } res = CImg<intT>::vector(x0,x1); } break; case 'y' : { int y0 = -1, y1 = -1; cimg_forY(*this,y) cimg_forXZC(*this,x,z,c) if ((*this)(x,y,z,c)!=value) { y0 = y; x = width(); y = height(); z = depth(); c = spectrum(); } if (y0>=0) { for (int y = height() - 1; y>=0; --y) cimg_forXZC(*this,x,z,c) if ((*this)(x,y,z,c)!=value) { y1 = y; x = width(); y = 0; z = depth(); c = spectrum(); } } res = CImg<intT>::vector(y0,y1); } break; case 'z' : { int z0 = -1, z1 = -1; cimg_forZ(*this,z) cimg_forXYC(*this,x,y,c) if ((*this)(x,y,z,c)!=value) { z0 = z; x = width(); y = height(); z = depth(); c = spectrum(); } if (z0>=0) { for (int z = depth() - 1; z>=0; --z) cimg_forXYC(*this,x,y,c) if ((*this)(x,y,z,c)!=value) { z1 = z; x = width(); y = height(); z = 0; c = spectrum(); } } res = CImg<intT>::vector(z0,z1); } break; default : { int c0 = -1, c1 = -1; cimg_forC(*this,c) cimg_forXYZ(*this,x,y,z) if ((*this)(x,y,z,c)!=value) { c0 = c; x = width(); y = height(); z = depth(); c = spectrum(); } if (c0>=0) { for (int c = spectrum() - 1; c>=0; --c) cimg_forXYZ(*this,x,y,z) if ((*this)(x,y,z,c)!=value) { c1 = c; x = width(); y = height(); z = depth(); c = 0; } } res = CImg<intT>::vector(c0,c1); } } return res; } //! Return specified image column. /** \param x0 Image column. **/ CImg<T> get_column(const int x0) const { return get_columns(x0,x0); } //! Return specified image column \inplace. CImg<T>& column(const int x0) { return columns(x0,x0); } //! Return specified range of image columns. /** \param x0 Starting image column. \param x1 Ending image column. **/ CImg<T>& columns(const int x0, const int x1) { return get_columns(x0,x1).move_to(*this); } //! Return specified range of image columns \inplace. CImg<T> get_columns(const int x0, const int x1) const { return get_crop(x0,0,0,0,x1,height() - 1,depth() - 1,spectrum() - 1); } //! Return specified image row. CImg<T> get_row(const int y0) const { return get_rows(y0,y0); } //! Return specified image row \inplace. /** \param y0 Image row. **/ CImg<T>& row(const int y0) { return rows(y0,y0); } //! Return specified range of image rows. /** \param y0 Starting image row. \param y1 Ending image row. **/ CImg<T> get_rows(const int y0, const int y1) const { return get_crop(0,y0,0,0,width() - 1,y1,depth() - 1,spectrum() - 1); } //! Return specified range of image rows \inplace. CImg<T>& rows(const int y0, const int y1) { return get_rows(y0,y1).move_to(*this); } //! Return specified image slice. /** \param z0 Image slice. **/ CImg<T> get_slice(const int z0) const { return get_slices(z0,z0); } //! Return specified image slice \inplace. CImg<T>& slice(const int z0) { return slices(z0,z0); } //! Return specified range of image slices. /** \param z0 Starting image slice. \param z1 Ending image slice. **/ CImg<T> get_slices(const int z0, const int z1) const { return get_crop(0,0,z0,0,width() - 1,height() - 1,z1,spectrum() - 1); } //! Return specified range of image slices \inplace. CImg<T>& slices(const int z0, const int z1) { return get_slices(z0,z1).move_to(*this); } //! Return specified image channel. /** \param c0 Image channel. **/ CImg<T> get_channel(const int c0) const { return get_channels(c0,c0); } //! Return specified image channel \inplace. CImg<T>& channel(const int c0) { return channels(c0,c0); } //! Return specified range of image channels. /** \param c0 Starting image channel. \param c1 Ending image channel. **/ CImg<T> get_channels(const int c0, const int c1) const { return get_crop(0,0,0,c0,width() - 1,height() - 1,depth() - 1,c1); } //! Return specified range of image channels \inplace. CImg<T>& channels(const int c0, const int c1) { return get_channels(c0,c1).move_to(*this); } //! Return stream line of a 2D or 3D vector field. CImg<floatT> get_streamline(const float x, const float y, const float z, const float L=256, const float dl=0.1f, const unsigned int interpolation_type=2, const bool is_backward_tracking=false, const bool is_oriented_only=false) const { if (_spectrum!=2 && _spectrum!=3) throw CImgInstanceException(_cimg_instance "streamline(): Instance is not a 2D or 3D vector field.", cimg_instance); if (_spectrum==2) { if (is_oriented_only) { typename CImg<T>::_functor4d_streamline2d_oriented func(*this); return streamline(func,x,y,z,L,dl,interpolation_type,is_backward_tracking,true, 0,0,0,_width - 1.f,_height - 1.f,0.f); } else { typename CImg<T>::_functor4d_streamline2d_directed func(*this); return streamline(func,x,y,z,L,dl,interpolation_type,is_backward_tracking,false, 0,0,0,_width - 1.f,_height - 1.f,0.f); } } if (is_oriented_only) { typename CImg<T>::_functor4d_streamline3d_oriented func(*this); return streamline(func,x,y,z,L,dl,interpolation_type,is_backward_tracking,true, 0,0,0,_width - 1.f,_height - 1.f,_depth - 1.f); } typename CImg<T>::_functor4d_streamline3d_directed func(*this); return streamline(func,x,y,z,L,dl,interpolation_type,is_backward_tracking,false, 0,0,0,_width - 1.f,_height - 1.f,_depth - 1.f); } //! Return stream line of a 3D vector field. /** \param func Vector field function. \param x X-coordinate of the starting point of the streamline. \param y Y-coordinate of the starting point of the streamline. \param z Z-coordinate of the starting point of the streamline. \param L Streamline length. \param dl Streamline length increment. \param interpolation_type Type of interpolation. Can be <tt>{ 0=nearest int | 1=linear | 2=2nd-order RK | 3=4th-order RK. }</tt>. \param is_backward_tracking Tells if the streamline is estimated forward or backward. \param is_oriented_only Tells if the direction of the vectors must be ignored. \param x0 X-coordinate of the first bounding-box vertex. \param y0 Y-coordinate of the first bounding-box vertex. \param z0 Z-coordinate of the first bounding-box vertex. \param x1 X-coordinate of the second bounding-box vertex. \param y1 Y-coordinate of the second bounding-box vertex. \param z1 Z-coordinate of the second bounding-box vertex. **/ template<typename tfunc> static CImg<floatT> streamline(const tfunc& func, const float x, const float y, const float z, const float L=256, const float dl=0.1f, const unsigned int interpolation_type=2, const bool is_backward_tracking=false, const bool is_oriented_only=false, const float x0=0, const float y0=0, const float z0=0, const float x1=0, const float y1=0, const float z1=0) { if (dl<=0) throw CImgArgumentException("CImg<%s>::streamline(): Invalid specified integration length %g " "(should be >0).", pixel_type(), dl); const bool is_bounded = (x0!=x1 || y0!=y1 || z0!=z1); if (L<=0 || (is_bounded && (x<x0 || x>x1 || y<y0 || y>y1 || z<z0 || z>z1))) return CImg<floatT>(); const unsigned int size_L = (unsigned int)cimg::round(L/dl + 1); CImg<floatT> coordinates(size_L,3); const float dl2 = dl/2; float *ptr_x = coordinates.data(0,0), *ptr_y = coordinates.data(0,1), *ptr_z = coordinates.data(0,2), pu = (float)(dl*func(x,y,z,0)), pv = (float)(dl*func(x,y,z,1)), pw = (float)(dl*func(x,y,z,2)), X = x, Y = y, Z = z; switch (interpolation_type) { case 0 : { // Nearest integer interpolation cimg_forX(coordinates,l) { *(ptr_x++) = X; *(ptr_y++) = Y; *(ptr_z++) = Z; const int xi = (int)(X>0?X + 0.5f:X - 0.5f), yi = (int)(Y>0?Y + 0.5f:Y - 0.5f), zi = (int)(Z>0?Z + 0.5f:Z - 0.5f); float u = (float)(dl*func((float)xi,(float)yi,(float)zi,0)), v = (float)(dl*func((float)xi,(float)yi,(float)zi,1)), w = (float)(dl*func((float)xi,(float)yi,(float)zi,2)); if (is_oriented_only && u*pu + v*pv + w*pw<0) { u = -u; v = -v; w = -w; } if (is_backward_tracking) { X-=(pu=u); Y-=(pv=v); Z-=(pw=w); } else { X+=(pu=u); Y+=(pv=v); Z+=(pw=w); } if (is_bounded && (X<x0 || X>x1 || Y<y0 || Y>y1 || Z<z0 || Z>z1)) break; } } break; case 1 : { // First-order interpolation cimg_forX(coordinates,l) { *(ptr_x++) = X; *(ptr_y++) = Y; *(ptr_z++) = Z; float u = (float)(dl*func(X,Y,Z,0)), v = (float)(dl*func(X,Y,Z,1)), w = (float)(dl*func(X,Y,Z,2)); if (is_oriented_only && u*pu + v*pv + w*pw<0) { u = -u; v = -v; w = -w; } if (is_backward_tracking) { X-=(pu=u); Y-=(pv=v); Z-=(pw=w); } else { X+=(pu=u); Y+=(pv=v); Z+=(pw=w); } if (is_bounded && (X<x0 || X>x1 || Y<y0 || Y>y1 || Z<z0 || Z>z1)) break; } } break; case 2 : { // Second order interpolation cimg_forX(coordinates,l) { *(ptr_x++) = X; *(ptr_y++) = Y; *(ptr_z++) = Z; float u0 = (float)(dl2*func(X,Y,Z,0)), v0 = (float)(dl2*func(X,Y,Z,1)), w0 = (float)(dl2*func(X,Y,Z,2)); if (is_oriented_only && u0*pu + v0*pv + w0*pw<0) { u0 = -u0; v0 = -v0; w0 = -w0; } float u = (float)(dl*func(X + u0,Y + v0,Z + w0,0)), v = (float)(dl*func(X + u0,Y + v0,Z + w0,1)), w = (float)(dl*func(X + u0,Y + v0,Z + w0,2)); if (is_oriented_only && u*pu + v*pv + w*pw<0) { u = -u; v = -v; w = -w; } if (is_backward_tracking) { X-=(pu=u); Y-=(pv=v); Z-=(pw=w); } else { X+=(pu=u); Y+=(pv=v); Z+=(pw=w); } if (is_bounded && (X<x0 || X>x1 || Y<y0 || Y>y1 || Z<z0 || Z>z1)) break; } } break; default : { // Fourth order interpolation cimg_forX(coordinates,k) { *(ptr_x++) = X; *(ptr_y++) = Y; *(ptr_z++) = Z; float u0 = (float)(dl2*func(X,Y,Z,0)), v0 = (float)(dl2*func(X,Y,Z,1)), w0 = (float)(dl2*func(X,Y,Z,2)); if (is_oriented_only && u0*pu + v0*pv + w0*pw<0) { u0 = -u0; v0 = -v0; w0 = -w0; } float u1 = (float)(dl2*func(X + u0,Y + v0,Z + w0,0)), v1 = (float)(dl2*func(X + u0,Y + v0,Z + w0,1)), w1 = (float)(dl2*func(X + u0,Y + v0,Z + w0,2)); if (is_oriented_only && u1*pu + v1*pv + w1*pw<0) { u1 = -u1; v1 = -v1; w1 = -w1; } float u2 = (float)(dl2*func(X + u1,Y + v1,Z + w1,0)), v2 = (float)(dl2*func(X + u1,Y + v1,Z + w1,1)), w2 = (float)(dl2*func(X + u1,Y + v1,Z + w1,2)); if (is_oriented_only && u2*pu + v2*pv + w2*pw<0) { u2 = -u2; v2 = -v2; w2 = -w2; } float u3 = (float)(dl2*func(X + u2,Y + v2,Z + w2,0)), v3 = (float)(dl2*func(X + u2,Y + v2,Z + w2,1)), w3 = (float)(dl2*func(X + u2,Y + v2,Z + w2,2)); if (is_oriented_only && u2*pu + v2*pv + w2*pw<0) { u3 = -u3; v3 = -v3; w3 = -w3; } const float u = (u0 + u3)/3 + (u1 + u2)/1.5f, v = (v0 + v3)/3 + (v1 + v2)/1.5f, w = (w0 + w3)/3 + (w1 + w2)/1.5f; if (is_backward_tracking) { X-=(pu=u); Y-=(pv=v); Z-=(pw=w); } else { X+=(pu=u); Y+=(pv=v); Z+=(pw=w); } if (is_bounded && (X<x0 || X>x1 || Y<y0 || Y>y1 || Z<z0 || Z>z1)) break; } } } if (ptr_x!=coordinates.data(0,1)) coordinates.resize((int)(ptr_x-coordinates.data()),3,1,1,0); return coordinates; } //! Return stream line of a 3D vector field \overloading. static CImg<floatT> streamline(const char *const expression, const float x, const float y, const float z, const float L=256, const float dl=0.1f, const unsigned int interpolation_type=2, const bool is_backward_tracking=true, const bool is_oriented_only=false, const float x0=0, const float y0=0, const float z0=0, const float x1=0, const float y1=0, const float z1=0) { _functor4d_streamline_expr func(expression); return streamline(func,x,y,z,L,dl,interpolation_type,is_backward_tracking,is_oriented_only,x0,y0,z0,x1,y1,z1); } struct _functor4d_streamline2d_directed { const CImg<T>& ref; _functor4d_streamline2d_directed(const CImg<T>& pref):ref(pref) {} float operator()(const float x, const float y, const float z, const unsigned int c) const { return c<2?(float)ref._linear_atXY(x,y,(int)z,c):0; } }; struct _functor4d_streamline3d_directed { const CImg<T>& ref; _functor4d_streamline3d_directed(const CImg<T>& pref):ref(pref) {} float operator()(const float x, const float y, const float z, const unsigned int c) const { return (float)ref._linear_atXYZ(x,y,z,c); } }; struct _functor4d_streamline2d_oriented { const CImg<T>& ref; CImg<floatT> *pI; _functor4d_streamline2d_oriented(const CImg<T>& pref):ref(pref),pI(0) { pI = new CImg<floatT>(2,2,1,2); } ~_functor4d_streamline2d_oriented() { delete pI; } float operator()(const float x, const float y, const float z, const unsigned int c) const { #define _cimg_vecalign2d(i,j) \ if (I(i,j,0)*I(0,0,0) + I(i,j,1)*I(0,0,1)<0) { I(i,j,0) = -I(i,j,0); I(i,j,1) = -I(i,j,1); } int xi = (int)x - (x>=0?0:1), nxi = xi + 1, yi = (int)y - (y>=0?0:1), nyi = yi + 1, zi = (int)z; const float dx = x - xi, dy = y - yi; if (c==0) { CImg<floatT>& I = *pI; if (xi<0) xi = 0; if (nxi<0) nxi = 0; if (xi>=ref.width()) xi = ref.width() - 1; if (nxi>=ref.width()) nxi = ref.width() - 1; if (yi<0) yi = 0; if (nyi<0) nyi = 0; if (yi>=ref.height()) yi = ref.height() - 1; if (nyi>=ref.height()) nyi = ref.height() - 1; I(0,0,0) = (float)ref(xi,yi,zi,0); I(0,0,1) = (float)ref(xi,yi,zi,1); I(1,0,0) = (float)ref(nxi,yi,zi,0); I(1,0,1) = (float)ref(nxi,yi,zi,1); I(1,1,0) = (float)ref(nxi,nyi,zi,0); I(1,1,1) = (float)ref(nxi,nyi,zi,1); I(0,1,0) = (float)ref(xi,nyi,zi,0); I(0,1,1) = (float)ref(xi,nyi,zi,1); _cimg_vecalign2d(1,0); _cimg_vecalign2d(1,1); _cimg_vecalign2d(0,1); } return c<2?(float)pI->_linear_atXY(dx,dy,0,c):0; } }; struct _functor4d_streamline3d_oriented { const CImg<T>& ref; CImg<floatT> *pI; _functor4d_streamline3d_oriented(const CImg<T>& pref):ref(pref),pI(0) { pI = new CImg<floatT>(2,2,2,3); } ~_functor4d_streamline3d_oriented() { delete pI; } float operator()(const float x, const float y, const float z, const unsigned int c) const { #define _cimg_vecalign3d(i,j,k) if (I(i,j,k,0)*I(0,0,0,0) + I(i,j,k,1)*I(0,0,0,1) + I(i,j,k,2)*I(0,0,0,2)<0) { \ I(i,j,k,0) = -I(i,j,k,0); I(i,j,k,1) = -I(i,j,k,1); I(i,j,k,2) = -I(i,j,k,2); } int xi = (int)x - (x>=0?0:1), nxi = xi + 1, yi = (int)y - (y>=0?0:1), nyi = yi + 1, zi = (int)z - (z>=0?0:1), nzi = zi + 1; const float dx = x - xi, dy = y - yi, dz = z - zi; if (c==0) { CImg<floatT>& I = *pI; if (xi<0) xi = 0; if (nxi<0) nxi = 0; if (xi>=ref.width()) xi = ref.width() - 1; if (nxi>=ref.width()) nxi = ref.width() - 1; if (yi<0) yi = 0; if (nyi<0) nyi = 0; if (yi>=ref.height()) yi = ref.height() - 1; if (nyi>=ref.height()) nyi = ref.height() - 1; if (zi<0) zi = 0; if (nzi<0) nzi = 0; if (zi>=ref.depth()) zi = ref.depth() - 1; if (nzi>=ref.depth()) nzi = ref.depth() - 1; I(0,0,0,0) = (float)ref(xi,yi,zi,0); I(0,0,0,1) = (float)ref(xi,yi,zi,1); I(0,0,0,2) = (float)ref(xi,yi,zi,2); I(1,0,0,0) = (float)ref(nxi,yi,zi,0); I(1,0,0,1) = (float)ref(nxi,yi,zi,1); I(1,0,0,2) = (float)ref(nxi,yi,zi,2); I(1,1,0,0) = (float)ref(nxi,nyi,zi,0); I(1,1,0,1) = (float)ref(nxi,nyi,zi,1); I(1,1,0,2) = (float)ref(nxi,nyi,zi,2); I(0,1,0,0) = (float)ref(xi,nyi,zi,0); I(0,1,0,1) = (float)ref(xi,nyi,zi,1); I(0,1,0,2) = (float)ref(xi,nyi,zi,2); I(0,0,1,0) = (float)ref(xi,yi,nzi,0); I(0,0,1,1) = (float)ref(xi,yi,nzi,1); I(0,0,1,2) = (float)ref(xi,yi,nzi,2); I(1,0,1,0) = (float)ref(nxi,yi,nzi,0); I(1,0,1,1) = (float)ref(nxi,yi,nzi,1); I(1,0,1,2) = (float)ref(nxi,yi,nzi,2); I(1,1,1,0) = (float)ref(nxi,nyi,nzi,0); I(1,1,1,1) = (float)ref(nxi,nyi,nzi,1); I(1,1,1,2) = (float)ref(nxi,nyi,nzi,2); I(0,1,1,0) = (float)ref(xi,nyi,nzi,0); I(0,1,1,1) = (float)ref(xi,nyi,nzi,1); I(0,1,1,2) = (float)ref(xi,nyi,nzi,2); _cimg_vecalign3d(1,0,0); _cimg_vecalign3d(1,1,0); _cimg_vecalign3d(0,1,0); _cimg_vecalign3d(0,0,1); _cimg_vecalign3d(1,0,1); _cimg_vecalign3d(1,1,1); _cimg_vecalign3d(0,1,1); } return (float)pI->_linear_atXYZ(dx,dy,dz,c); } }; struct _functor4d_streamline_expr { _cimg_math_parser *mp; ~_functor4d_streamline_expr() { mp->end(); delete mp; } _functor4d_streamline_expr(const char *const expr):mp(0) { mp = new _cimg_math_parser(expr,"streamline",CImg<T>::const_empty(),0); } float operator()(const float x, const float y, const float z, const unsigned int c) const { return (float)(*mp)(x,y,z,c); } }; //! Return a shared-memory image referencing a range of pixels of the image instance. /** \param x0 X-coordinate of the starting pixel. \param x1 X-coordinate of the ending pixel. \param y0 Y-coordinate. \param z0 Z-coordinate. \param c0 C-coordinate. **/ CImg<T> get_shared_points(const unsigned int x0, const unsigned int x1, const unsigned int y0=0, const unsigned int z0=0, const unsigned int c0=0) { const unsigned int beg = (unsigned int)offset(x0,y0,z0,c0), end = (unsigned int)offset(x1,y0,z0,c0); if (beg>end || beg>=size() || end>=size()) throw CImgArgumentException(_cimg_instance "get_shared_points(): Invalid request of a shared-memory subset (%u->%u,%u,%u,%u).", cimg_instance, x0,x1,y0,z0,c0); return CImg<T>(_data + beg,x1 - x0 + 1,1,1,1,true); } //! Return a shared-memory image referencing a range of pixels of the image instance \const. const CImg<T> get_shared_points(const unsigned int x0, const unsigned int x1, const unsigned int y0=0, const unsigned int z0=0, const unsigned int c0=0) const { const unsigned int beg = (unsigned int)offset(x0,y0,z0,c0), end = (unsigned int)offset(x1,y0,z0,c0); if (beg>end || beg>=size() || end>=size()) throw CImgArgumentException(_cimg_instance "get_shared_points(): Invalid request of a shared-memory subset (%u->%u,%u,%u,%u).", cimg_instance, x0,x1,y0,z0,c0); return CImg<T>(_data + beg,x1 - x0 + 1,1,1,1,true); } //! Return a shared-memory image referencing a range of rows of the image instance. /** \param y0 Y-coordinate of the starting row. \param y1 Y-coordinate of the ending row. \param z0 Z-coordinate. \param c0 C-coordinate. **/ CImg<T> get_shared_rows(const unsigned int y0, const unsigned int y1, const unsigned int z0=0, const unsigned int c0=0) { const unsigned int beg = (unsigned int)offset(0,y0,z0,c0), end = (unsigned int)offset(0,y1,z0,c0); if (beg>end || beg>=size() || end>=size()) throw CImgArgumentException(_cimg_instance "get_shared_rows(): Invalid request of a shared-memory subset " "(0->%u,%u->%u,%u,%u).", cimg_instance, _width - 1,y0,y1,z0,c0); return CImg<T>(_data + beg,_width,y1 - y0 + 1,1,1,true); } //! Return a shared-memory image referencing a range of rows of the image instance \const. const CImg<T> get_shared_rows(const unsigned int y0, const unsigned int y1, const unsigned int z0=0, const unsigned int c0=0) const { const unsigned int beg = (unsigned int)offset(0,y0,z0,c0), end = (unsigned int)offset(0,y1,z0,c0); if (beg>end || beg>=size() || end>=size()) throw CImgArgumentException(_cimg_instance "get_shared_rows(): Invalid request of a shared-memory subset " "(0->%u,%u->%u,%u,%u).", cimg_instance, _width - 1,y0,y1,z0,c0); return CImg<T>(_data + beg,_width,y1 - y0 + 1,1,1,true); } //! Return a shared-memory image referencing one row of the image instance. /** \param y0 Y-coordinate. \param z0 Z-coordinate. \param c0 C-coordinate. **/ CImg<T> get_shared_row(const unsigned int y0, const unsigned int z0=0, const unsigned int c0=0) { return get_shared_rows(y0,y0,z0,c0); } //! Return a shared-memory image referencing one row of the image instance \const. const CImg<T> get_shared_row(const unsigned int y0, const unsigned int z0=0, const unsigned int c0=0) const { return get_shared_rows(y0,y0,z0,c0); } //! Return a shared memory image referencing a range of slices of the image instance. /** \param z0 Z-coordinate of the starting slice. \param z1 Z-coordinate of the ending slice. \param c0 C-coordinate. **/ CImg<T> get_shared_slices(const unsigned int z0, const unsigned int z1, const unsigned int c0=0) { const unsigned int beg = (unsigned int)offset(0,0,z0,c0), end = (unsigned int)offset(0,0,z1,c0); if (beg>end || beg>=size() || end>=size()) throw CImgArgumentException(_cimg_instance "get_shared_slices(): Invalid request of a shared-memory subset " "(0->%u,0->%u,%u->%u,%u).", cimg_instance, _width - 1,_height - 1,z0,z1,c0); return CImg<T>(_data + beg,_width,_height,z1 - z0 + 1,1,true); } //! Return a shared memory image referencing a range of slices of the image instance \const. const CImg<T> get_shared_slices(const unsigned int z0, const unsigned int z1, const unsigned int c0=0) const { const unsigned int beg = (unsigned int)offset(0,0,z0,c0), end = (unsigned int)offset(0,0,z1,c0); if (beg>end || beg>=size() || end>=size()) throw CImgArgumentException(_cimg_instance "get_shared_slices(): Invalid request of a shared-memory subset " "(0->%u,0->%u,%u->%u,%u).", cimg_instance, _width - 1,_height - 1,z0,z1,c0); return CImg<T>(_data + beg,_width,_height,z1 - z0 + 1,1,true); } //! Return a shared-memory image referencing one slice of the image instance. /** \param z0 Z-coordinate. \param c0 C-coordinate. **/ CImg<T> get_shared_slice(const unsigned int z0, const unsigned int c0=0) { return get_shared_slices(z0,z0,c0); } //! Return a shared-memory image referencing one slice of the image instance \const. const CImg<T> get_shared_slice(const unsigned int z0, const unsigned int c0=0) const { return get_shared_slices(z0,z0,c0); } //! Return a shared-memory image referencing a range of channels of the image instance. /** \param c0 C-coordinate of the starting channel. \param c1 C-coordinate of the ending channel. **/ CImg<T> get_shared_channels(const unsigned int c0, const unsigned int c1) { const unsigned int beg = (unsigned int)offset(0,0,0,c0), end = (unsigned int)offset(0,0,0,c1); if (beg>end || beg>=size() || end>=size()) throw CImgArgumentException(_cimg_instance "get_shared_channels(): Invalid request of a shared-memory subset " "(0->%u,0->%u,0->%u,%u->%u).", cimg_instance, _width - 1,_height - 1,_depth - 1,c0,c1); return CImg<T>(_data + beg,_width,_height,_depth,c1 - c0 + 1,true); } //! Return a shared-memory image referencing a range of channels of the image instance \const. const CImg<T> get_shared_channels(const unsigned int c0, const unsigned int c1) const { const unsigned int beg = (unsigned int)offset(0,0,0,c0), end = (unsigned int)offset(0,0,0,c1); if (beg>end || beg>=size() || end>=size()) throw CImgArgumentException(_cimg_instance "get_shared_channels(): Invalid request of a shared-memory subset " "(0->%u,0->%u,0->%u,%u->%u).", cimg_instance, _width - 1,_height - 1,_depth - 1,c0,c1); return CImg<T>(_data + beg,_width,_height,_depth,c1 - c0 + 1,true); } //! Return a shared-memory image referencing one channel of the image instance. /** \param c0 C-coordinate. **/ CImg<T> get_shared_channel(const unsigned int c0) { return get_shared_channels(c0,c0); } //! Return a shared-memory image referencing one channel of the image instance \const. const CImg<T> get_shared_channel(const unsigned int c0) const { return get_shared_channels(c0,c0); } //! Return a shared-memory version of the image instance. CImg<T> get_shared() { return CImg<T>(_data,_width,_height,_depth,_spectrum,true); } //! Return a shared-memory version of the image instance \const. const CImg<T> get_shared() const { return CImg<T>(_data,_width,_height,_depth,_spectrum,true); } //! Split image into a list along specified axis. /** \param axis Splitting axis. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param nb Number of splitted parts. \note - If \c nb==0, instance image is splitted into blocs of egal values along the specified axis. - If \c nb<=0, instance image is splitted into blocs of -\c nb pixel wide. - If \c nb>0, instance image is splitted into \c nb blocs. **/ CImgList<T> get_split(const char axis, const int nb=-1) const { CImgList<T> res; if (is_empty()) return res; const char _axis = cimg::lowercase(axis); if (nb<0) { // Split by bloc size const unsigned int dp = (unsigned int)(nb?-nb:1); switch (_axis) { case 'x': { if (_width>dp) { res.assign(_width/dp + (_width%dp?1:0),1,1); const unsigned int pe = _width - dp; cimg_pragma_openmp(parallel for cimg_openmp_if(res._width>=(cimg_openmp_sizefactor)*128 && _height*_depth*_spectrum>=128)) for (int p = 0; p<(int)pe; p+=dp) get_crop(p,0,0,0,p + dp - 1,_height - 1,_depth - 1,_spectrum - 1).move_to(res[p/dp]); get_crop((res._width - 1)*dp,0,0,0,_width - 1,_height - 1,_depth - 1,_spectrum - 1).move_to(res.back()); } else res.assign(*this); } break; case 'y': { if (_height>dp) { res.assign(_height/dp + (_height%dp?1:0),1,1); const unsigned int pe = _height - dp; cimg_pragma_openmp(parallel for cimg_openmp_if(res._width>=(cimg_openmp_sizefactor)*128 && _width*_depth*_spectrum>=128)) for (int p = 0; p<(int)pe; p+=dp) get_crop(0,p,0,0,_width - 1,p + dp - 1,_depth - 1,_spectrum - 1).move_to(res[p/dp]); get_crop(0,(res._width - 1)*dp,0,0,_width - 1,_height - 1,_depth - 1,_spectrum - 1).move_to(res.back()); } else res.assign(*this); } break; case 'z': { if (_depth>dp) { res.assign(_depth/dp + (_depth%dp?1:0),1,1); const unsigned int pe = _depth - dp; cimg_pragma_openmp(parallel for cimg_openmp_if(res._width>=(cimg_openmp_sizefactor)*128 && _width*_height*_spectrum>=128)) for (int p = 0; p<(int)pe; p+=dp) get_crop(0,0,p,0,_width - 1,_height - 1,p + dp - 1,_spectrum - 1).move_to(res[p/dp]); get_crop(0,0,(res._width - 1)*dp,0,_width - 1,_height - 1,_depth - 1,_spectrum - 1).move_to(res.back()); } else res.assign(*this); } break; case 'c' : { if (_spectrum>dp) { res.assign(_spectrum/dp + (_spectrum%dp?1:0),1,1); const unsigned int pe = _spectrum - dp; cimg_pragma_openmp(parallel for cimg_openmp_if(res._width>=(cimg_openmp_sizefactor)*128 && _width*_height*_depth>=128)) for (int p = 0; p<(int)pe; p+=dp) get_crop(0,0,0,p,_width - 1,_height - 1,_depth - 1,p + dp - 1).move_to(res[p/dp]); get_crop(0,0,0,(res._width - 1)*dp,_width - 1,_height - 1,_depth - 1,_spectrum - 1).move_to(res.back()); } else res.assign(*this); } } } else if (nb>0) { // Split by number of (non-homogeneous) blocs const unsigned int siz = _axis=='x'?_width:_axis=='y'?_height:_axis=='z'?_depth:_axis=='c'?_spectrum:0; if ((unsigned int)nb>siz) throw CImgArgumentException(_cimg_instance "get_split(): Instance cannot be split along %c-axis into %u blocs.", cimg_instance, axis,nb); if (nb==1) res.assign(*this); else { int err = (int)siz; unsigned int _p = 0; switch (_axis) { case 'x' : { cimg_forX(*this,p) if ((err-=nb)<=0) { get_crop(_p,0,0,0,p,_height - 1,_depth - 1,_spectrum - 1).move_to(res); err+=(int)siz; _p = p + 1U; } } break; case 'y' : { cimg_forY(*this,p) if ((err-=nb)<=0) { get_crop(0,_p,0,0,_width - 1,p,_depth - 1,_spectrum - 1).move_to(res); err+=(int)siz; _p = p + 1U; } } break; case 'z' : { cimg_forZ(*this,p) if ((err-=nb)<=0) { get_crop(0,0,_p,0,_width - 1,_height - 1,p,_spectrum - 1).move_to(res); err+=(int)siz; _p = p + 1U; } } break; case 'c' : { cimg_forC(*this,p) if ((err-=nb)<=0) { get_crop(0,0,0,_p,_width - 1,_height - 1,_depth - 1,p).move_to(res); err+=(int)siz; _p = p + 1U; } } } } } else { // Split by egal values according to specified axis T current = *_data; switch (_axis) { case 'x' : { int i0 = 0; cimg_forX(*this,i) if ((*this)(i)!=current) { get_columns(i0,i - 1).move_to(res); i0 = i; current = (*this)(i); } get_columns(i0,width() - 1).move_to(res); } break; case 'y' : { int i0 = 0; cimg_forY(*this,i) if ((*this)(0,i)!=current) { get_rows(i0,i - 1).move_to(res); i0 = i; current = (*this)(0,i); } get_rows(i0,height() - 1).move_to(res); } break; case 'z' : { int i0 = 0; cimg_forZ(*this,i) if ((*this)(0,0,i)!=current) { get_slices(i0,i - 1).move_to(res); i0 = i; current = (*this)(0,0,i); } get_slices(i0,depth() - 1).move_to(res); } break; case 'c' : { int i0 = 0; cimg_forC(*this,i) if ((*this)(0,0,0,i)!=current) { get_channels(i0,i - 1).move_to(res); i0 = i; current = (*this)(0,0,0,i); } get_channels(i0,spectrum() - 1).move_to(res); } break; default : { longT i0 = 0; cimg_foroff(*this,i) if ((*this)[i]!=current) { CImg<T>(_data + i0,1,(unsigned int)(i - i0)).move_to(res); i0 = (longT)i; current = (*this)[i]; } CImg<T>(_data + i0,1,(unsigned int)(size() - i0)).move_to(res); } } } return res; } //! Split image into a list of sub-images, according to a specified splitting value sequence and optionally axis. /** \param values Splitting value sequence. \param axis Axis along which the splitting is performed. Can be '0' to ignore axis. \param keep_values Tells if the splitting sequence must be kept in the splitted blocs. **/ template<typename t> CImgList<T> get_split(const CImg<t>& values, const char axis=0, const bool keep_values=true) const { typedef _cimg_Tt Tt; CImgList<T> res; if (is_empty()) return res; const ulongT vsiz = values.size(); const char _axis = cimg::lowercase(axis); if (!vsiz) return CImgList<T>(*this); if (vsiz==1) { // Split according to a single value const T value = (T)*values; switch (_axis) { case 'x' : { unsigned int i0 = 0, i = 0; do { while (i<_width && (*this)(i)==value) ++i; if (i>i0) { if (keep_values) get_columns(i0,i - 1).move_to(res); i0 = i; } while (i<_width && (*this)(i)!=value) ++i; if (i>i0) { get_columns(i0,i - 1).move_to(res); i0 = i; } } while (i<_width); } break; case 'y' : { unsigned int i0 = 0, i = 0; do { while (i<_height && (*this)(0,i)==value) ++i; if (i>i0) { if (keep_values) get_rows(i0,i - 1).move_to(res); i0 = i; } while (i<_height && (*this)(0,i)!=value) ++i; if (i>i0) { get_rows(i0,i - 1).move_to(res); i0 = i; } } while (i<_height); } break; case 'z' : { unsigned int i0 = 0, i = 0; do { while (i<_depth && (*this)(0,0,i)==value) ++i; if (i>i0) { if (keep_values) get_slices(i0,i - 1).move_to(res); i0 = i; } while (i<_depth && (*this)(0,0,i)!=value) ++i; if (i>i0) { get_slices(i0,i - 1).move_to(res); i0 = i; } } while (i<_depth); } break; case 'c' : { unsigned int i0 = 0, i = 0; do { while (i<_spectrum && (*this)(0,0,0,i)==value) ++i; if (i>i0) { if (keep_values) get_channels(i0,i - 1).move_to(res); i0 = i; } while (i<_spectrum && (*this)(0,0,0,i)!=value) ++i; if (i>i0) { get_channels(i0,i - 1).move_to(res); i0 = i; } } while (i<_spectrum); } break; default : { const ulongT siz = size(); ulongT i0 = 0, i = 0; do { while (i<siz && (*this)[i]==value) ++i; if (i>i0) { if (keep_values) CImg<T>(_data + i0,1,(unsigned int)(i - i0)).move_to(res); i0 = i; } while (i<siz && (*this)[i]!=value) ++i; if (i>i0) { CImg<T>(_data + i0,1,(unsigned int)(i - i0)).move_to(res); i0 = i; } } while (i<siz); } } } else { // Split according to multiple values ulongT j = 0; switch (_axis) { case 'x' : { unsigned int i0 = 0, i1 = 0, i = 0; do { if ((Tt)(*this)(i)==(Tt)*values) { i1 = i; j = 0; while (i<_width && (Tt)(*this)(i)==(Tt)values[j]) { ++i; if (++j>=vsiz) j = 0; } i-=j; if (i>i1) { if (i1>i0) get_columns(i0,i1 - 1).move_to(res); if (keep_values) get_columns(i1,i - 1).move_to(res); i0 = i; } else ++i; } else ++i; } while (i<_width); if (i0<_width) get_columns(i0,width() - 1).move_to(res); } break; case 'y' : { unsigned int i0 = 0, i1 = 0, i = 0; do { if ((Tt)(*this)(0,i)==(Tt)*values) { i1 = i; j = 0; while (i<_height && (Tt)(*this)(0,i)==(Tt)values[j]) { ++i; if (++j>=vsiz) j = 0; } i-=j; if (i>i1) { if (i1>i0) get_rows(i0,i1 - 1).move_to(res); if (keep_values) get_rows(i1,i - 1).move_to(res); i0 = i; } else ++i; } else ++i; } while (i<_height); if (i0<_height) get_rows(i0,height() - 1).move_to(res); } break; case 'z' : { unsigned int i0 = 0, i1 = 0, i = 0; do { if ((Tt)(*this)(0,0,i)==(Tt)*values) { i1 = i; j = 0; while (i<_depth && (Tt)(*this)(0,0,i)==(Tt)values[j]) { ++i; if (++j>=vsiz) j = 0; } i-=j; if (i>i1) { if (i1>i0) get_slices(i0,i1 - 1).move_to(res); if (keep_values) get_slices(i1,i - 1).move_to(res); i0 = i; } else ++i; } else ++i; } while (i<_depth); if (i0<_depth) get_slices(i0,depth() - 1).move_to(res); } break; case 'c' : { unsigned int i0 = 0, i1 = 0, i = 0; do { if ((Tt)(*this)(0,0,0,i)==(Tt)*values) { i1 = i; j = 0; while (i<_spectrum && (Tt)(*this)(0,0,0,i)==(Tt)values[j]) { ++i; if (++j>=vsiz) j = 0; } i-=j; if (i>i1) { if (i1>i0) get_channels(i0,i1 - 1).move_to(res); if (keep_values) get_channels(i1,i - 1).move_to(res); i0 = i; } else ++i; } else ++i; } while (i<_spectrum); if (i0<_spectrum) get_channels(i0,spectrum() - 1).move_to(res); } break; default : { ulongT i0 = 0, i1 = 0, i = 0; const ulongT siz = size(); do { if ((Tt)(*this)[i]==(Tt)*values) { i1 = i; j = 0; while (i<siz && (Tt)(*this)[i]==(Tt)values[j]) { ++i; if (++j>=vsiz) j = 0; } i-=j; if (i>i1) { if (i1>i0) CImg<T>(_data + i0,1,(unsigned int)(i1 - i0)).move_to(res); if (keep_values) CImg<T>(_data + i1,1,(unsigned int)(i - i1)).move_to(res); i0 = i; } else ++i; } else ++i; } while (i<siz); if (i0<siz) CImg<T>(_data + i0,1,(unsigned int)(siz - i0)).move_to(res); } break; } } return res; } //! Append two images along specified axis. /** \param img Image to append with instance image. \param axis Appending axis. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param align Append alignment in \c [0,1]. **/ template<typename t> CImg<T>& append(const CImg<t>& img, const char axis='x', const float align=0) { if (is_empty()) return assign(img,false); if (!img) return *this; return CImgList<T>(*this,true).insert(img).get_append(axis,align).move_to(*this); } //! Append two images along specified axis \specialization. CImg<T>& append(const CImg<T>& img, const char axis='x', const float align=0) { if (is_empty()) return assign(img,false); if (!img) return *this; return CImgList<T>(*this,img,true).get_append(axis,align).move_to(*this); } //! Append two images along specified axis \const. template<typename t> CImg<_cimg_Tt> get_append(const CImg<T>& img, const char axis='x', const float align=0) const { if (is_empty()) return +img; if (!img) return +*this; return CImgList<_cimg_Tt>(*this,true).insert(img).get_append(axis,align); } //! Append two images along specified axis \specialization. CImg<T> get_append(const CImg<T>& img, const char axis='x', const float align=0) const { if (is_empty()) return +img; if (!img) return +*this; return CImgList<T>(*this,img,true).get_append(axis,align); } //@} //--------------------------------------- // //! \name Filtering / Transforms //@{ //--------------------------------------- //! Correlate image by a kernel. /** \param kernel = the correlation kernel. \param boundary_conditions boundary conditions can be (false=dirichlet, true=neumann) \param is_normalized = enable local normalization. \param dilation = dilation \note - The correlation of the image instance \p *this by the kernel \p kernel is defined to be: res(x,y,z) = sum_{i,j,k} (*this)(x + i,y + j,z + k)*kernel(i,j,k). **/ template<typename t> CImg<T>& correlate(const CImg<t>& kernel, const bool boundary_conditions=true, const bool is_normalized=false, const int dilation=1) { if (is_empty() || !kernel) return *this; return get_correlate(kernel,boundary_conditions,is_normalized,dilation).move_to(*this); } template<typename t> CImg<_cimg_Ttfloat> get_correlate(const CImg<t>& kernel, const bool boundary_conditions=true, const bool is_normalized=false, const int dilation=1) const { return _correlate(kernel,boundary_conditions,is_normalized,dilation,false); } //! Correlate image by a kernel \newinstance. template<typename t> CImg<_cimg_Ttfloat> _correlate(const CImg<t>& kernel, const bool boundary_conditions, const bool is_normalized, /* const int x0, const int y0, const int z0, const int x1, const int y1, const int z1, const int xstep, const int ystep, const int zstep, */ const int dilation, const bool is_convolution) const { if (is_empty() || !kernel || dilation<0) return *this; typedef _cimg_Ttfloat Ttfloat; CImg<Ttfloat> res; const ulongT res_whd = (ulongT)_width*_height*_depth, res_size = res_whd*std::max(_spectrum,kernel._spectrum); const bool is_inner_parallel = _width*_height*_depth>=(cimg_openmp_sizefactor)*32768, is_outer_parallel = res_size>=(cimg_openmp_sizefactor)*32768; _cimg_abort_init_omp; cimg_abort_init; if (kernel._width==kernel._height && ((kernel._depth==1 && kernel._width<=5) || (kernel._depth==kernel._width && kernel._width<=3))) { // Special optimization done for 2x2, 3x3, 4x4, 5x5, 6x6, 2x2x2 and 3x3x3 kernel. if (!boundary_conditions && res_whd<=3000*3000) { // Dirichlet boundaries // For relatively small images, adding a zero border then use optimized NxN convolution loops is faster. res = (kernel._depth==1?get_crop(-1,-1,_width,_height):get_crop(-1,-1,-1,_width,_height,_depth)). _correlate(kernel,true,is_normalized,dilation,is_convolution); if (kernel._depth==1) res.crop(1,1,res._width - 2,res._height - 2); else res.crop(1,1,1,res._width - 2,res._height - 2,res._depth - 2); } else { // Neumann boundaries res.assign(_width,_height,_depth,std::max(_spectrum,kernel._spectrum)); cimg::unused(is_inner_parallel,is_outer_parallel); CImg<t> _kernel; if (is_convolution) { // Add empty column/row/slice to shift kernel center in case of convolution const int dw = !(kernel.width()%2), dh = !(kernel.height()%2), dd = !(kernel.depth()%2); if (dw || dh || dd) kernel.get_resize(kernel.width() + dw,kernel.height() + dh,kernel.depth() + dd,-100,0,0). move_to(_kernel); } if (!_kernel) _kernel = kernel.get_shared(); switch (_kernel._depth) { case 3 : { // 3x3x3 kernel cimg_forC(res,c) { cimg_abort_test; const CImg<T> I = get_shared_channel(c%_spectrum); const CImg<t> K = _kernel.get_shared_channel(c%kernel._spectrum); CImg<T> _res = res.get_shared_channel(c); if (is_normalized) { const Ttfloat M = (Ttfloat)K.magnitude(2), M2 = M*M; cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(_res.size(),16384)) cimg_forXYZ(res,x,y,z) { const int px = x>dilation?x - dilation:x, nx = x + dilation<res.width()?x + dilation:x, py = y>dilation?y - dilation:y, ny = y + dilation<res.height()?y + dilation:y, pz = z>dilation?z - dilation:z, nz = z + dilation<res.depth()?z + dilation:z; const Ttfloat N = M2*(cimg::sqr(I(px,py,pz)) + cimg::sqr(I(x,py,pz)) + cimg::sqr(I(nx,py,pz)) + cimg::sqr(I(px,y,pz)) + cimg::sqr(I(x,y,pz)) + cimg::sqr(I(nx,y,pz)) + cimg::sqr(I(px,ny,pz)) + cimg::sqr(I(x,ny,pz)) + cimg::sqr(I(nx,ny,pz)) + cimg::sqr(I(px,py,z)) + cimg::sqr(I(x,py,z)) + cimg::sqr(I(nx,py,z)) + cimg::sqr(I(px,y,z)) + cimg::sqr(I(x,y,z)) + cimg::sqr(I(nx,y,z)) + cimg::sqr(I(px,ny,z)) + cimg::sqr(I(x,ny,z)) + cimg::sqr(I(nx,ny,z)) + cimg::sqr(I(px,py,nz)) + cimg::sqr(I(x,py,nz)) + cimg::sqr(I(nx,py,nz)) + cimg::sqr(I(px,y,nz)) + cimg::sqr(I(x,y,nz)) + cimg::sqr(I(nx,y,nz)) + cimg::sqr(I(px,ny,nz)) + cimg::sqr(I(x,ny,nz)) + cimg::sqr(I(nx,ny,nz))); _res(x,y,z) = (Ttfloat)(N?(K[0]*I(px,py,pz) + K[1]*I(x,py,pz) + K[2]*I(nx,py,pz) + K[3]*I(px,y,pz) + K[4]*I(x,y,pz) + K[5]*I(nx,y,pz) + K[6]*I(px,ny,pz) + K[7]*I(x,ny,pz) + K[8]*I(nx,ny,pz) + K[9]*I(px,py,z) + K[10]*I(x,py,z) + K[11]*I(nx,py,z) + K[12]*I(px,y,z) + K[13]*I(x,y,z) + K[14]*I(nx,y,z) + K[15]*I(px,ny,z) + K[16]*I(x,ny,z) + K[17]*I(nx,ny,z) + K[18]*I(px,py,nz) + K[19]*I(x,py,nz) + K[20]*I(nx,py,nz) + K[21]*I(px,y,nz) + K[22]*I(x,y,nz) + K[23]*I(nx,y,nz) + K[24]*I(px,ny,nz) + K[25]*I(x,ny,nz) + K[26]*I(nx,ny,nz))/std::sqrt(N):0); } } else { cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(_res.size(),16384)) cimg_forXYZ(res,x,y,z) { const int px = x>dilation?x - dilation:x, nx = x + dilation<res.width()?x + dilation:x, py = y>dilation?y - dilation:y, ny = y + dilation<res.height()?y + dilation:y, pz = z>dilation?z - dilation:z, nz = z + dilation<res.depth()?z + dilation:z; _res(x,y,z) = (Ttfloat)(K[0]*I(px,py,pz) + K[1]*I(x,py,pz) + K[2]*I(nx,py,pz) + K[3]*I(px,y,pz) + K[4]*I(x,y,pz) + K[5]*I(nx,y,pz) + K[6]*I(px,ny,pz) + K[7]*I(x,ny,pz) + K[8]*I(nx,ny,pz) + K[9]*I(px,py,z) + K[10]*I(x,py,z) + K[11]*I(nx,py,z) + K[12]*I(px,y,z) + K[13]*I(x,y,z) + K[14]*I(nx,y,z) + K[15]*I(px,ny,z) + K[16]*I(x,ny,z) + K[17]*I(nx,ny,z) + K[18]*I(px,py,nz) + K[19]*I(x,py,nz) + K[20]*I(nx,py,nz) + K[21]*I(px,y,nz) + K[22]*I(x,y,nz) + K[23]*I(nx,y,nz) + K[24]*I(px,ny,nz) + K[25]*I(x,ny,nz) + K[26]*I(nx,ny,nz)); } } } } break; case 2 : { // 2x2x2 kernel cimg_forC(res,c) { cimg_abort_test; const CImg<T> I = get_shared_channel(c%_spectrum); const CImg<t> K = _kernel.get_shared_channel(c%kernel._spectrum); CImg<T> _res = res.get_shared_channel(c); if (is_normalized) { const Ttfloat M = (Ttfloat)K.magnitude(2), M2 = M*M; cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(_res.size(),16384)) cimg_forXYZ(res,x,y,z) { const int nx = x + 1<res.width()?x + 1:x, ny = y + 1<res.height()?y + 1:y, nz = z + 1<res.depth()?z + 1:z; const Ttfloat N = M2*(cimg::sqr(I(x,y,z)) + cimg::sqr(I(nx,y,z)) + cimg::sqr(I(x,ny,z)) + cimg::sqr(I(nx,ny,z)) + cimg::sqr(I(x,y,nz)) + cimg::sqr(I(nx,y,nz)) + cimg::sqr(I(x,ny,nz)) + cimg::sqr(I(nx,ny,nz))); _res(x,y,z) = (Ttfloat)(N?(K[0]*I(x,y,z) + K[1]*I(nx,y,z) + K[2]*I(x,ny,z) + K[3]*I(nx,ny,z) + K[4]*I(x,y,nz) + K[5]*I(nx,y,nz) + K[6]*I(x,ny,nz) + K[7]*I(nx,ny,nz))/std::sqrt(N):0); } } else { cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(_res.size(),16384)) cimg_forXYZ(res,x,y,z) { const int nx = x + 1<res.width()?x + 1:x, ny = y + 1<res.height()?y + 1:y, nz = z + 1<res.depth()?z + 1:z; _res(x,y,z) = (Ttfloat)(K[0]*I(x,y,z) + K[1]*I(nx,y,z) + K[2]*I(x,ny,z) + K[3]*I(nx,ny,z) + K[4]*I(x,y,nz) + K[5]*I(nx,y,nz) + K[6]*I(x,ny,nz) + K[7]*I(nx,ny,nz)); } } } } break; default : case 1 : switch (_kernel._width) { case 5 : { // 5x5 kernel cimg_forC(res,c) { cimg_abort_test; const CImg<T> I = get_shared_channel(c%_spectrum); const CImg<t> K = _kernel.get_shared_channel(c%kernel._spectrum); CImg<T> _res = res.get_shared_channel(c); if (is_normalized) { const Ttfloat M = (Ttfloat)K.magnitude(2), M2 = M*M; cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(_res.size(),16384)) cimg_forXYZ(res,x,y,z) { const int px = x>dilation?x - dilation:x, nx = x + dilation<res.width()?x + dilation:x, bx = px>dilation?px - dilation:px, ax = nx + dilation<res.width()?nx + dilation:nx, py = y>dilation?y - dilation:y, ny = y + dilation<res.height()?y + dilation:y, by = py>dilation?py - dilation:py, ay = ny + dilation<res.height()?ny + dilation:ny; const Ttfloat N = M2*(cimg::sqr(I(bx,by,z)) + cimg::sqr(I(px,by,z)) + cimg::sqr(I(x,by,z)) + cimg::sqr(I(nx,by,z)) + cimg::sqr(I(ax,by,z)) + cimg::sqr(I(bx,py,z)) + cimg::sqr(I(px,py,z)) + cimg::sqr(I(x,py,z)) + cimg::sqr(I(nx,py,z)) + cimg::sqr(I(ax,py,z)) + cimg::sqr(I(bx,y,z)) + cimg::sqr(I(px,y,z)) + cimg::sqr(I(x,y,z)) + cimg::sqr(I(nx,y,z)) + cimg::sqr(I(ax,y,z)) + cimg::sqr(I(bx,ny,z)) + cimg::sqr(I(px,ny,z)) + cimg::sqr(I(x,ny,z)) + cimg::sqr(I(nx,ny,z)) + cimg::sqr(I(ax,ny,z)) + cimg::sqr(I(bx,ay,z)) + cimg::sqr(I(px,ay,z)) + cimg::sqr(I(x,ay,z)) + cimg::sqr(I(nx,ay,z)) + cimg::sqr(I(ax,ay,z))); _res(x,y,z) = (Ttfloat)(N?(K[0]*I(bx,by,z) + K[1]*I(px,by,z) + K[2]*I(x,by,z) + K[3]*I(nx,by,z) + K[4]*I(ax,by,z) + K[5]*I(bx,py,z) + K[6]*I(px,py,z) + K[7]*I(x,py,z) + K[8]*I(nx,py,z) + K[9]*I(ax,py,z) + K[10]*I(bx,y,z) + K[11]*I(px,y,z) + K[12]*I(x,y,z) + K[13]*I(nx,y,z) + K[14]*I(ax,y,z) + K[15]*I(bx,ny,z) + K[16]*I(px,ny,z) + K[17]*I(x,ny,z) + K[18]*I(nx,ny,z) + K[19]*I(ax,ny,z) + K[20]*I(bx,ay,z) + K[21]*I(px,ay,z) + K[22]*I(x,ay,z) + K[23]*I(nx,ay,z) + K[24]*I(ax,ay,z))/std::sqrt(N):0); } } else { cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(_res.size(),16384)) cimg_forXYZ(res,x,y,z) { const int px = x>dilation?x - dilation:x, nx = x + dilation<res.width()?x + dilation:x, bx = px>dilation?px - dilation:px, ax = nx + dilation<res.width()?nx + dilation:nx, py = y>dilation?y - dilation:y, ny = y + dilation<res.height()?y + dilation:y, by = py>dilation?py - dilation:py, ay = ny + dilation<res.height()?ny + dilation:ny; _res(x,y,z) = (Ttfloat)(K[0]*I(bx,by,z) + K[1]*I(px,by,z) + K[2]*I(x,by,z) + K[3]*I(nx,by,z) + K[4]*I(ax,by,z) + K[5]*I(bx,py,z) + K[6]*I(px,py,z) + K[7]*I(x,py,z) + K[8]*I(nx,py,z) + K[9]*I(ax,py,z) + K[10]*I(bx,y,z) + K[11]*I(px,y,z) + K[12]*I(x,y,z) + K[13]*I(nx,y,z) + K[14]*I(ax,y,z) + K[15]*I(bx,ny,z) + K[16]*I(px,ny,z) + K[17]*I(x,ny,z) + K[18]*I(nx,ny,z) + K[19]*I(ax,ny,z) + K[20]*I(bx,ay,z) + K[21]*I(px,ay,z) + K[22]*I(x,ay,z) + K[23]*I(nx,ay,z) + K[24]*I(ax,ay,z)); } } } } break; case 4 : { // 4x4 kernel cimg_forC(res,c) { cimg_abort_test; const CImg<T> I = get_shared_channel(c%_spectrum); const CImg<t> K = _kernel.get_shared_channel(c%kernel._spectrum); CImg<T> _res = res.get_shared_channel(c); if (is_normalized) { const Ttfloat M = (Ttfloat)K.magnitude(2), M2 = M*M; cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(_res.size(),16384)) cimg_forXYZ(res,x,y,z) { const int px = x>dilation?x - dilation:x, nx = x + dilation<res.width()?x + dilation:x, ax = nx + dilation<res.width()?nx + dilation:nx, py = y>dilation?y - dilation:y, ny = y + dilation<res.height()?y + dilation:y, ay = ny + dilation<res.height()?ny + dilation:ny; const Ttfloat N = M2*(cimg::sqr(I(px,py,z)) + cimg::sqr(I(x,py,z)) + cimg::sqr(I(nx,py,z)) + cimg::sqr(I(ax,py,z)) + cimg::sqr(I(px,y,z)) + cimg::sqr(I(x,y,z)) + cimg::sqr(I(nx,y,z)) + cimg::sqr(I(ax,y,z)) + cimg::sqr(I(px,ny,z)) + cimg::sqr(I(x,ny,z)) + cimg::sqr(I(nx,ny,z)) + cimg::sqr(I(ax,ny,z)) + cimg::sqr(I(px,ay,z)) + cimg::sqr(I(x,ay,z)) + cimg::sqr(I(nx,ay,z)) + cimg::sqr(I(ax,ay,z))); _res(x,y,z) = (Ttfloat)(N?(K[0]*I(px,py,z) + K[1]*I(x,py,z) + K[2]*I(nx,py,z) + K[3]*I(ax,py,z) + K[4]*I(px,y,z) + K[5]*I(x,y,z) + K[6]*I(nx,y,z) + K[7]*I(ax,y,z) + K[8]*I(px,ny,z) + K[9]*I(x,ny,z) + K[10]*I(nx,ny,z) + K[11]*I(ax,ny,z) + K[12]*I(px,ay,z) + K[13]*I(x,ay,z) + K[14]*I(nx,ay,z) + K[15]*I(ax,ay,z))/std::sqrt(N):0); } } else { cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(_res.size(),16384)) cimg_forXYZ(res,x,y,z) { const int px = x>dilation?x - dilation:x, nx = x + dilation<res.width()?x + dilation:x, ax = nx + dilation<res.width()?nx + dilation:nx, py = y>dilation?y - dilation:y, ny = y + dilation<res.height()?y + dilation:y, ay = ny + dilation<res.height()?ny + dilation:ny; _res(x,y,z) = (Ttfloat)(K[0]*I(px,py,z) + K[1]*I(x,py,z) + K[2]*I(nx,py,z) + K[3]*I(ax,py,z) + K[4]*I(px,y,z) + K[5]*I(x,y,z) + K[6]*I(nx,y,z) + K[7]*I(ax,y,z) + K[8]*I(px,ny,z) + K[9]*I(x,ny,z) + K[10]*I(nx,ny,z) + K[11]*I(ax,ny,z) + K[12]*I(px,ay,z) + K[13]*I(x,ay,z) + K[14]*I(nx,ay,z) + K[15]*I(ax,ay,z)); } } } } break; case 3 : { // 3x3 kernel cimg_forC(res,c) { cimg_abort_test; const CImg<T> I = get_shared_channel(c%_spectrum); const CImg<t> K = _kernel.get_shared_channel(c%kernel._spectrum); CImg<T> _res = res.get_shared_channel(c); if (is_normalized) { const Ttfloat M = (Ttfloat)K.magnitude(2), M2 = M*M; cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(_res.size(),16384)) cimg_forXYZ(res,x,y,z) { const int px = x>dilation?x - dilation:x, nx = x + dilation<res.width()?x + dilation:x, py = y>dilation?y - dilation:y, ny = y + dilation<res.height()?y + dilation:y; const Ttfloat N = M2*(cimg::sqr(I(px,py,z)) + cimg::sqr(I(x,py,z)) + cimg::sqr(I(nx,py,z)) + cimg::sqr(I(px,y,z)) + cimg::sqr(I(x,y,z)) + cimg::sqr(I(nx,y,z)) + cimg::sqr(I(px,ny,z)) + cimg::sqr(I(x,ny,z)) + cimg::sqr(I(nx,ny,z))); _res(x,y,z) = (Ttfloat)(N?(K[0]*I(px,py,z) + K[1]*I(x,py,z) + K[2]*I(nx,py,z) + K[3]*I(px,y,z) + K[4]*I(x,y,z) + K[5]*I(nx,y,z) + K[6]*I(px,ny,z) + K[7]*I(x,ny,z) + K[8]*I(nx,ny,z))/std::sqrt(N):0); } } else { cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(_res.size(),16384)) cimg_forXYZ(res,x,y,z) { const int px = x>dilation?x - dilation:x, nx = x + dilation<res.width()?x + dilation:x, py = y>dilation?y - dilation:y, ny = y + dilation<res.height()?y + dilation:y; _res(x,y,z) = (Ttfloat)(K[0]*I(px,py,z) + K[1]*I(x,py,z) + K[2]*I(nx,py,z) + K[3]*I(px,y,z) + K[4]*I(x,y,z) + K[5]*I(nx,y,z) + K[6]*I(px,ny,z) + K[7]*I(x,ny,z) + K[8]*I(nx,ny,z)); } } } } break; case 2 : { // 2x2 kernel cimg_forC(res,c) { cimg_abort_test; const CImg<T> I = get_shared_channel(c%_spectrum); const CImg<t> K = _kernel.get_shared_channel(c%kernel._spectrum); CImg<T> _res = res.get_shared_channel(c); if (is_normalized) { const Ttfloat M = (Ttfloat)K.magnitude(2), M2 = M*M; cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(_res.size(),16384)) cimg_forXYZ(res,x,y,z) { const int nx = x + 1<res.width()?x + 1:x, ny = y + 1<res.height()?y + 1:y; const Ttfloat N = M2*(cimg::sqr(I(x,y,z)) + cimg::sqr(I(nx,y,z)) + cimg::sqr(I(x,ny,z)) + cimg::sqr(I(nx,ny,z))); _res(x,y,z) = (Ttfloat)(N?(K[0]*I(x,y,z) + K[1]*I(nx,y,z) + K[2]*I(x,ny,z) + K[3]*I(nx,ny,z))/std::sqrt(N):0); } } else { cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(_res.size(),16384)) cimg_forXYZ(res,x,y,z) { const int nx = x + 1<res.width()?x + 1:x, ny = y + 1<res.height()?y + 1:y; _res(x,y,z) = (Ttfloat)(K[0]*I(x,y,z) + K[1]*I(nx,y,z) + K[2]*I(x,ny,z) + K[3]*I(nx,ny,z)); } } } } break; default : case 1 : // 1x1 kernel if (is_normalized) res.fill(1); else cimg_forC(res,c) { cimg_abort_test; const CImg<T> img = get_shared_channel(c%_spectrum); res.get_shared_channel(c).assign(img)*=_kernel(0,0,0,c%kernel._spectrum); } break; } } } } else { // Generic version for other kernels and boundary conditions res.assign(_width,_height,_depth,std::max(_spectrum,kernel._spectrum)); int mx2 = kernel.width()/2, my2 = kernel.height()/2, mz2 = kernel.depth()/2, mx1 = kernel.width() - mx2 - 1, my1 = kernel.height() - my2 - 1, mz1 = kernel.depth() - mz2 - 1; if (is_convolution) cimg::swap(mx1,mx2,my1,my2,mz1,mz2); // Shift kernel center in case of convolution const int mxs = dilation*mx1, mys = dilation*my1, mzs = dilation*mz1, mxe = width() - dilation*mx2, mye = height() - dilation*my2, mze = depth() - dilation*mz2; cimg_pragma_openmp(parallel for cimg_openmp_if(!is_inner_parallel && is_outer_parallel)) cimg_forC(res,c) _cimg_abort_try_omp { cimg_abort_test; const CImg<T> img = get_shared_channel(c%_spectrum); const CImg<t> K = kernel.get_shared_channel(c%kernel._spectrum); if (is_normalized) { // Normalized correlation const Ttfloat M = (Ttfloat)K.magnitude(2), M2 = M*M; cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(is_inner_parallel)) for (int z = mzs; z<mze; ++z) for (int y = mys; y<mye; ++y) for (int x = mxs; x<mxe; ++x) _cimg_abort_try_omp2 { cimg_abort_test2; Ttfloat val = 0, N = 0; for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const Ttfloat _val = (Ttfloat)img(x + dilation*xm,y + dilation*ym,z + dilation*zm); val+=_val*K(mx1 + xm,my1 + ym,mz1 + zm); N+=_val*_val; } N*=M2; res(x,y,z,c) = (Ttfloat)(N?val/std::sqrt(N):0); } _cimg_abort_catch_omp2 if (boundary_conditions) cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(is_inner_parallel)) cimg_forYZ(res,y,z) _cimg_abort_try_omp2 { cimg_abort_test2; for (int x = 0; x<width(); (y<mys || y>=mye || z<mzs || z>=mze)?++x:((x<mxs - 1 || x>=mxe)?++x:(x=mxe))) { Ttfloat val = 0, N = 0; for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const Ttfloat _val = (Ttfloat)img._atXYZ(x + dilation*xm,y + dilation*ym,z + dilation*zm); val+=_val*K(mx1 + xm,my1 + ym,mz1 + zm); N+=_val*_val; } N*=M2; res(x,y,z,c) = (Ttfloat)(N?val/std::sqrt(N):0); } } _cimg_abort_catch_omp2 else cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(is_inner_parallel)) cimg_forYZ(res,y,z) _cimg_abort_try_omp2 { cimg_abort_test2; for (int x = 0; x<width(); (y<mys || y>=mye || z<mzs || z>=mze)?++x:((x<mxs - 1 || x>=mxe)?++x:(x=mxe))) { Ttfloat val = 0, N = 0; for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const Ttfloat _val = (Ttfloat)img.atXYZ(x + dilation*xm,y + dilation*ym,z + dilation*zm,0,(T)0); val+=_val*K(mx1 + xm,my1 + ym,mz1 + zm); N+=_val*_val; } N*=M2; res(x,y,z,c) = (Ttfloat)(N?val/std::sqrt(N):0); } } _cimg_abort_catch_omp2 } else { // Classical correlation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(is_inner_parallel)) for (int z = mzs; z<mze; ++z) for (int y = mys; y<mye; ++y) for (int x = mxs; x<mxe; ++x) _cimg_abort_try_omp2 { cimg_abort_test2; Ttfloat val = 0; for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) val+=img(x + dilation*xm,y + dilation*ym,z + dilation*zm)*K(mx1 + xm,my1 + ym,mz1 + zm); res(x,y,z,c) = (Ttfloat)val; } _cimg_abort_catch_omp2 if (boundary_conditions) cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(is_inner_parallel)) cimg_forYZ(res,y,z) _cimg_abort_try_omp2 { cimg_abort_test2; for (int x = 0; x<width(); (y<mys || y>=mye || z<mzs || z>=mze)?++x:((x<mxs - 1 || x>=mxe)?++x:(x=mxe))) { Ttfloat val = 0; for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) val+=img._atXYZ(x + dilation*xm,y + dilation*ym,z + dilation*zm)*K(mx1 + xm,my1 + ym,mz1 + zm); res(x,y,z,c) = (Ttfloat)val; } } _cimg_abort_catch_omp2 else cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(is_inner_parallel)) cimg_forYZ(res,y,z) _cimg_abort_try_omp2 { cimg_abort_test2; for (int x = 0; x<width(); (y<mys || y>=mye || z<mzs || z>=mze)?++x:((x<mxs - 1 || x>=mxe)?++x:(x=mxe))) { Ttfloat val = 0; for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) val+=img.atXYZ(x + dilation*xm,y + dilation*ym,z + dilation*zm,0,(T)0)* K(mx1 + xm,my1 + ym,mz1 + zm); res(x,y,z,c) = (Ttfloat)val; } } _cimg_abort_catch_omp2 } } _cimg_abort_catch_omp } cimg_abort_test; return res; } //! Convolve image by a kernel. /** \param kernel = the correlation kernel. \param boundary_conditions boundary conditions can be (false=dirichlet, true=neumann) \param is_normalized = enable local normalization. \param dilation = dilation \note - The result \p res of the convolution of an image \p img by a kernel \p kernel is defined to be: res(x,y,z) = sum_{i,j,k} img(x-i,y-j,z-k)*kernel(i,j,k) **/ template<typename t> CImg<T>& convolve(const CImg<t>& kernel, const bool boundary_conditions=true, const bool is_normalized=false, const int dilation=1) { if (is_empty() || !kernel) return *this; return get_convolve(kernel,boundary_conditions,is_normalized,dilation).move_to(*this); } //! Convolve image by a kernel \newinstance. template<typename t> CImg<_cimg_Ttfloat> get_convolve(const CImg<t>& kernel, const bool boundary_conditions=true, const bool is_normalized=false, const int dilation=1) const { return _correlate(CImg<t>(kernel._data,kernel.size()/kernel._spectrum,1,1,kernel._spectrum,true). get_mirror('x').resize(kernel,-1),boundary_conditions,is_normalized,dilation,true); } //! Cumulate image values, optionally along specified axis. /** \param axis Cumulation axis. Set it to 0 to cumulate all values globally without taking axes into account. **/ CImg<T>& cumulate(const char axis=0) { switch (cimg::lowercase(axis)) { case 'x' : cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*512 && _height*_depth*_spectrum>=16)) cimg_forYZC(*this,y,z,c) { T *ptrd = data(0,y,z,c); Tlong cumul = (Tlong)0; cimg_forX(*this,x) { cumul+=(Tlong)*ptrd; *(ptrd++) = (T)cumul; } } break; case 'y' : { const ulongT w = (ulongT)_width; cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_height>=(cimg_openmp_sizefactor)*512 && _width*_depth*_spectrum>=16)) cimg_forXZC(*this,x,z,c) { T *ptrd = data(x,0,z,c); Tlong cumul = (Tlong)0; cimg_forY(*this,y) { cumul+=(Tlong)*ptrd; *ptrd = (T)cumul; ptrd+=w; } } } break; case 'z' : { const ulongT wh = (ulongT)_width*_height; cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_depth>=(cimg_openmp_sizefactor)*512 && _width*_depth*_spectrum>=16)) cimg_forXYC(*this,x,y,c) { T *ptrd = data(x,y,0,c); Tlong cumul = (Tlong)0; cimg_forZ(*this,z) { cumul+=(Tlong)*ptrd; *ptrd = (T)cumul; ptrd+=wh; } } } break; case 'c' : { const ulongT whd = (ulongT)_width*_height*_depth; cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_spectrum>=(cimg_openmp_sizefactor)*512 && _width*_height*_depth>=16)) cimg_forXYZ(*this,x,y,z) { T *ptrd = data(x,y,z,0); Tlong cumul = (Tlong)0; cimg_forC(*this,c) { cumul+=(Tlong)*ptrd; *ptrd = (T)cumul; ptrd+=whd; } } } break; default : { // Global cumulation Tlong cumul = (Tlong)0; cimg_for(*this,ptrd,T) { cumul+=(Tlong)*ptrd; *ptrd = (T)cumul; } } } return *this; } //! Cumulate image values, optionally along specified axis \newinstance. CImg<Tlong> get_cumulate(const char axis=0) const { return CImg<Tlong>(*this,false).cumulate(axis); } //! Cumulate image values, along specified axes. /** \param axes Cumulation axes, as a C-string. \note \c axes may contains multiple characters, e.g. \c "xyz" **/ CImg<T>& cumulate(const char *const axes) { for (const char *s = axes; *s; ++s) cumulate(*s); return *this; } //! Cumulate image values, along specified axes \newinstance. CImg<Tlong> get_cumulate(const char *const axes) const { return CImg<Tlong>(*this,false).cumulate(axes); } //! Erode image by a structuring element. /** \param kernel Structuring element. \param boundary_conditions Boundary conditions. \param is_real Do the erosion in real (a.k.a 'non-flat') mode (\c true) rather than binary mode (\c false). **/ template<typename t> CImg<T>& erode(const CImg<t>& kernel, const bool boundary_conditions=true, const bool is_real=false) { if (is_empty() || !kernel) return *this; return get_erode(kernel,boundary_conditions,is_real).move_to(*this); } //! Erode image by a structuring element \newinstance. template<typename t> CImg<_cimg_Tt> get_erode(const CImg<t>& kernel, const bool boundary_conditions=true, const bool is_real=false) const { if (is_empty() || !kernel) return *this; if (!is_real && kernel==0) return CImg<T>(width(),height(),depth(),spectrum(),0); typedef _cimg_Tt Tt; CImg<Tt> res(_width,_height,_depth,std::max(_spectrum,kernel._spectrum)); const int mx2 = kernel.width()/2, my2 = kernel.height()/2, mz2 = kernel.depth()/2, mx1 = kernel.width() - mx2 - 1, my1 = kernel.height() - my2 - 1, mz1 = kernel.depth() - mz2 - 1, mxe = width() - mx2, mye = height() - my2, mze = depth() - mz2; const bool is_inner_parallel = _width*_height*_depth>=(cimg_openmp_sizefactor)*32768, is_outer_parallel = res.size()>=(cimg_openmp_sizefactor)*32768; cimg::unused(is_inner_parallel,is_outer_parallel); _cimg_abort_init_omp; cimg_abort_init; cimg_pragma_openmp(parallel for cimg_openmp_if(!is_inner_parallel && is_outer_parallel)) cimg_forC(res,c) _cimg_abort_try_omp { cimg_abort_test; const CImg<T> img = get_shared_channel(c%_spectrum); const CImg<t> K = kernel.get_shared_channel(c%kernel._spectrum); if (is_real) { // Real erosion cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(is_inner_parallel)) for (int z = mz1; z<mze; ++z) for (int y = my1; y<mye; ++y) for (int x = mx1; x<mxe; ++x) _cimg_abort_try_omp2 { cimg_abort_test2; Tt min_val = cimg::type<Tt>::max(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const t mval = K(mx1 + xm,my1 + ym,mz1 + zm); const Tt cval = (Tt)(img(x + xm,y + ym,z + zm) - mval); if (cval<min_val) min_val = cval; } res(x,y,z,c) = min_val; } _cimg_abort_catch_omp2 if (boundary_conditions) cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(is_inner_parallel)) cimg_forYZ(res,y,z) _cimg_abort_try_omp2 { cimg_abort_test2; for (int x = 0; x<width(); (y<my1 || y>=mye || z<mz1 || z>=mze)?++x:((x<mx1 - 1 || x>=mxe)?++x:(x=mxe))) { Tt min_val = cimg::type<Tt>::max(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const t mval = K(mx1 + xm,my1 + ym,mz1 + zm); const Tt cval = (Tt)(img._atXYZ(x + xm,y + ym,z + zm) - mval); if (cval<min_val) min_val = cval; } res(x,y,z,c) = min_val; } } _cimg_abort_catch_omp2 else cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(is_inner_parallel)) cimg_forYZ(res,y,z) _cimg_abort_try_omp2 { cimg_abort_test2; for (int x = 0; x<width(); (y<my1 || y>=mye || z<mz1 || z>=mze)?++x:((x<mx1 - 1 || x>=mxe)?++x:(x=mxe))) { Tt min_val = cimg::type<Tt>::max(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const t mval = K(mx1 + xm,my1 + ym,mz1 + zm); const Tt cval = (Tt)(img.atXYZ(x + xm,y + ym,z + zm,0,(T)0) - mval); if (cval<min_val) min_val = cval; } res(x,y,z,c) = min_val; } } _cimg_abort_catch_omp2 } else { // Binary erosion cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(is_inner_parallel)) for (int z = mz1; z<mze; ++z) for (int y = my1; y<mye; ++y) for (int x = mx1; x<mxe; ++x) _cimg_abort_try_omp2 { cimg_abort_test2; Tt min_val = cimg::type<Tt>::max(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) if (K(mx1 + xm,my1 + ym,mz1 + zm)) { const Tt cval = (Tt)img(x + xm,y + ym,z + zm); if (cval<min_val) min_val = cval; } res(x,y,z,c) = min_val; } _cimg_abort_catch_omp2 if (boundary_conditions) cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(is_inner_parallel)) cimg_forYZ(res,y,z) _cimg_abort_try_omp2 { cimg_abort_test2; for (int x = 0; x<width(); (y<my1 || y>=mye || z<mz1 || z>=mze)?++x:((x<mx1 - 1 || x>=mxe)?++x:(x=mxe))) { Tt min_val = cimg::type<Tt>::max(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) if (K(mx1 + xm,my1 + ym,mz1 + zm)) { const Tt cval = (Tt)img._atXYZ(x + xm,y + ym,z + zm); if (cval<min_val) min_val = cval; } res(x,y,z,c) = min_val; } } _cimg_abort_catch_omp2 else cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(is_inner_parallel)) cimg_forYZ(res,y,z) _cimg_abort_try_omp2 { cimg_abort_test2; for (int x = 0; x<width(); (y<my1 || y>=mye || z<mz1 || z>=mze)?++x:((x<mx1 - 1 || x>=mxe)?++x:(x=mxe))) { Tt min_val = cimg::type<Tt>::max(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) if (K(mx1 + xm,my1 + ym,mz1 + zm)) { const Tt cval = (Tt)img.atXYZ(x + xm,y + ym,z + zm,0,(T)0); if (cval<min_val) min_val = cval; } res(x,y,z,c) = min_val; } } _cimg_abort_catch_omp2 } } _cimg_abort_catch_omp cimg_abort_test; return res; } //! Erode image by a rectangular structuring element of specified size. /** \param sx Width of the structuring element. \param sy Height of the structuring element. \param sz Depth of the structuring element. **/ CImg<T>& erode(const unsigned int sx, const unsigned int sy, const unsigned int sz=1) { if (is_empty() || (sx==1 && sy==1 && sz==1)) return *this; if (sx>1 && _width>1) { // Along X-axis const int L = width(), off = 1, s = (int)sx, _s2 = s/2 + 1, _s1 = s - _s2, s1 = _s1>L?L:_s1, s2 = _s2>L?L:_s2; CImg<T> buf(L); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) firstprivate(buf) if (size()>524288)) cimg_forYZC(*this,y,z,c) { T *const ptrdb = buf._data, *ptrd = buf._data, *const ptrde = buf._data + L - 1; const T *const ptrsb = data(0,y,z,c), *ptrs = ptrsb, *const ptrse = ptrs + L*off - off; T cur = *ptrs; ptrs+=off; bool is_first = true; for (int p = s2 - 1; p>0 && ptrs<=ptrse; --p) { const T val = *ptrs; ptrs+=off; if (val<=cur) { cur = val; is_first = false; }} *(ptrd++) = cur; if (ptrs>=ptrse) { T *pd = data(0,y,z,c); cur = std::min(cur,*ptrse); cimg_forX(buf,k) { *pd = cur; pd+=off; } } else { for (int p = s1; p>0 && ptrd<=ptrde; --p) { const T val = *ptrs; if (ptrs<ptrse) ptrs+=off; if (val<=cur) { cur = val; is_first = false; } *(ptrd++) = cur; } for (int p = L - s - 1; p>0; --p) { const T val = *ptrs; ptrs+=off; if (is_first) { const T *nptrs = ptrs - off; cur = val; for (int q = s - 2; q>0; --q) { nptrs-=off; const T nval = *nptrs; if (nval<cur) cur = nval; } nptrs-=off; const T nval = *nptrs; if (nval<cur) { cur = nval; is_first = true; } else is_first = false; } else { if (val<=cur) cur = val; else if (cur==*(ptrs-s*off)) is_first = true; } *(ptrd++) = cur; } ptrd = ptrde; ptrs = ptrse; cur = *ptrs; ptrs-=off; for (int p = s1; p>0 && ptrs>=ptrsb; --p) { const T val = *ptrs; ptrs-=off; if (val<cur) cur = val; } *(ptrd--) = cur; for (int p = s2 - 1; p>0 && ptrd>=ptrdb; --p) { const T val = *ptrs; if (ptrs>ptrsb) ptrs-=off; if (val<cur) cur = val; *(ptrd--) = cur; } T *pd = data(0,y,z,c); cimg_for(buf,ps,T) { *pd = *ps; pd+=off; } } } } if (sy>1 && _height>1) { // Along Y-axis const int L = height(), off = width(), s = (int)sy, _s2 = s/2 + 1, _s1 = s - _s2, s1 = _s1>L?L:_s1, s2 = _s2>L?L:_s2; CImg<T> buf(L); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) firstprivate(buf) if (size()>524288)) cimg_forXZC(*this,x,z,c) { T *const ptrdb = buf._data, *ptrd = ptrdb, *const ptrde = buf._data + L - 1; const T *const ptrsb = data(x,0,z,c), *ptrs = ptrsb, *const ptrse = ptrs + L*off - off; T cur = *ptrs; ptrs+=off; bool is_first = true; for (int p = s2 - 1; p>0 && ptrs<=ptrse; --p) { const T val = *ptrs; ptrs+=off; if (val<=cur) { cur = val; is_first = false; } } *(ptrd++) = cur; if (ptrs>=ptrse) { T *pd = data(x,0,z,c); cur = std::min(cur,*ptrse); cimg_forX(buf,k) { *pd = cur; pd+=off; } } else { for (int p = s1; p>0 && ptrd<=ptrde; --p) { const T val = *ptrs; if (ptrs<ptrse) ptrs+=off; if (val<=cur) { cur = val; is_first = false; } *(ptrd++) = cur; } for (int p = L - s - 1; p>0; --p) { const T val = *ptrs; ptrs+=off; if (is_first) { const T *nptrs = ptrs - off; cur = val; for (int q = s - 2; q>0; --q) { nptrs-=off; const T nval = *nptrs; if (nval<cur) cur = nval; } nptrs-=off; const T nval = *nptrs; if (nval<cur) { cur = nval; is_first = true; } else is_first = false; } else { if (val<=cur) cur = val; else if (cur==*(ptrs-s*off)) is_first = true; } *(ptrd++) = cur; } ptrd = ptrde; ptrs = ptrse; cur = *ptrs; ptrs-=off; for (int p = s1; p>0 && ptrs>=ptrsb; --p) { const T val = *ptrs; ptrs-=off; if (val<cur) cur = val; } *(ptrd--) = cur; for (int p = s2 - 1; p>0 && ptrd>=ptrdb; --p) { const T val = *ptrs; if (ptrs>ptrsb) ptrs-=off; if (val<cur) cur = val; *(ptrd--) = cur; } T *pd = data(x,0,z,c); cimg_for(buf,ps,T) { *pd = *ps; pd+=off; } } } } if (sz>1 && _depth>1) { // Along Z-axis const int L = depth(), off = width()*height(), s = (int)sz, _s2 = s/2 + 1, _s1 = s - _s2, s1 = _s1>L?L:_s1, s2 = _s2>L?L:_s2; CImg<T> buf(L); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) firstprivate(buf) if (size()>524288)) cimg_forXYC(*this,x,y,c) { T *const ptrdb = buf._data, *ptrd = ptrdb, *const ptrde = buf._data + L - 1; const T *const ptrsb = data(x,y,0,c), *ptrs = ptrsb, *const ptrse = ptrs + L*off - off; T cur = *ptrs; ptrs+=off; bool is_first = true; for (int p = s2 - 1; p>0 && ptrs<=ptrse; --p) { const T val = *ptrs; ptrs+=off; if (val<=cur) { cur = val; is_first = false; } } *(ptrd++) = cur; if (ptrs>=ptrse) { T *pd = data(x,y,0,c); cur = std::min(cur,*ptrse); cimg_forX(buf,k) { *pd = cur; pd+=off; } } else { for (int p = s1; p>0 && ptrd<=ptrde; --p) { const T val = *ptrs; if (ptrs<ptrse) ptrs+=off; if (val<=cur) { cur = val; is_first = false; } *(ptrd++) = cur; } for (int p = L - s - 1; p>0; --p) { const T val = *ptrs; ptrs+=off; if (is_first) { const T *nptrs = ptrs - off; cur = val; for (int q = s - 2; q>0; --q) { nptrs-=off; const T nval = *nptrs; if (nval<cur) cur = nval; } nptrs-=off; const T nval = *nptrs; if (nval<cur) { cur = nval; is_first = true; } else is_first = false; } else { if (val<=cur) cur = val; else if (cur==*(ptrs-s*off)) is_first = true; } *(ptrd++) = cur; } ptrd = ptrde; ptrs = ptrse; cur = *ptrs; ptrs-=off; for (int p = s1; p>0 && ptrs>=ptrsb; --p) { const T val = *ptrs; ptrs-=off; if (val<cur) cur = val; } *(ptrd--) = cur; for (int p = s2 - 1; p>0 && ptrd>=ptrdb; --p) { const T val = *ptrs; if (ptrs>ptrsb) ptrs-=off; if (val<cur) cur = val; *(ptrd--) = cur; } T *pd = data(x,y,0,c); cimg_for(buf,ps,T) { *pd = *ps; pd+=off; } } } } return *this; } //! Erode image by a rectangular structuring element of specified size \newinstance. CImg<T> get_erode(const unsigned int sx, const unsigned int sy, const unsigned int sz=1) const { return (+*this).erode(sx,sy,sz); } //! Erode the image by a square structuring element of specified size. /** \param s Size of the structuring element. **/ CImg<T>& erode(const unsigned int s) { return erode(s,s,s); } //! Erode the image by a square structuring element of specified size \newinstance. CImg<T> get_erode(const unsigned int s) const { return (+*this).erode(s); } //! Dilate image by a structuring element. /** \param kernel Structuring element. \param boundary_conditions Boundary conditions. \param is_real Do the dilation in real (a.k.a 'non-flat') mode (\c true) rather than binary mode (\c false). **/ template<typename t> CImg<T>& dilate(const CImg<t>& kernel, const bool boundary_conditions=true, const bool is_real=false) { if (is_empty() || !kernel) return *this; return get_dilate(kernel,boundary_conditions,is_real).move_to(*this); } //! Dilate image by a structuring element \newinstance. template<typename t> CImg<_cimg_Tt> get_dilate(const CImg<t>& kernel, const bool boundary_conditions=true, const bool is_real=false) const { if (is_empty() || !kernel || (!is_real && kernel==0)) return *this; typedef _cimg_Tt Tt; CImg<Tt> res(_width,_height,_depth,std::max(_spectrum,kernel._spectrum)); const int mx1 = kernel.width()/2, my1 = kernel.height()/2, mz1 = kernel.depth()/2, mx2 = kernel.width() - mx1 - 1, my2 = kernel.height() - my1 - 1, mz2 = kernel.depth() - mz1 - 1, mxe = width() - mx2, mye = height() - my2, mze = depth() - mz2; const bool is_inner_parallel = _width*_height*_depth>=(cimg_openmp_sizefactor)*32768, is_outer_parallel = res.size()>=(cimg_openmp_sizefactor)*32768; cimg::unused(is_inner_parallel,is_outer_parallel); _cimg_abort_init_omp; cimg_abort_init; cimg_pragma_openmp(parallel for cimg_openmp_if(!is_inner_parallel && is_outer_parallel)) cimg_forC(res,c) _cimg_abort_try_omp { cimg_abort_test; const CImg<T> img = get_shared_channel(c%_spectrum); const CImg<t> K = kernel.get_shared_channel(c%kernel._spectrum); if (is_real) { // Real dilation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(is_inner_parallel)) for (int z = mz1; z<mze; ++z) for (int y = my1; y<mye; ++y) for (int x = mx1; x<mxe; ++x) _cimg_abort_try_omp2 { cimg_abort_test2; Tt max_val = cimg::type<Tt>::min(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const t mval = K(mx2 - xm,my2 - ym,mz2 - zm); const Tt cval = (Tt)(img(x + xm,y + ym,z + zm) + mval); if (cval>max_val) max_val = cval; } res(x,y,z,c) = max_val; } _cimg_abort_catch_omp2 if (boundary_conditions) cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(is_inner_parallel)) cimg_forYZ(res,y,z) _cimg_abort_try_omp2 { cimg_abort_test2; for (int x = 0; x<width(); (y<my1 || y>=mye || z<mz1 || z>=mze)?++x:((x<mx1 - 1 || x>=mxe)?++x:(x=mxe))) { Tt max_val = cimg::type<Tt>::min(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const t mval = K(mx2 - xm,my2 - ym,mz2 - zm); const Tt cval = (Tt)(img._atXYZ(x + xm,y + ym,z + zm) + mval); if (cval>max_val) max_val = cval; } res(x,y,z,c) = max_val; } } _cimg_abort_catch_omp2 else cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(is_inner_parallel)) cimg_forYZ(*this,y,z) _cimg_abort_try_omp2 { cimg_abort_test2; for (int x = 0; x<width(); (y<my1 || y>=mye || z<mz1 || z>=mze)?++x:((x<mx1 - 1 || x>=mxe)?++x:(x=mxe))) { Tt max_val = cimg::type<Tt>::min(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const t mval = K(mx2 - xm,my2 - ym,mz2 - zm); const Tt cval = (Tt)(img.atXYZ(x + xm,y + ym,z + zm,0,(T)0) + mval); if (cval>max_val) max_val = cval; } res(x,y,z,c) = max_val; } } _cimg_abort_catch_omp2 } else { // Binary dilation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(is_inner_parallel)) for (int z = mz1; z<mze; ++z) for (int y = my1; y<mye; ++y) for (int x = mx1; x<mxe; ++x) _cimg_abort_try_omp2 { cimg_abort_test2; Tt max_val = cimg::type<Tt>::min(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) if (K(mx2 - xm,my2 - ym,mz2 - zm)) { const Tt cval = (Tt)img(x + xm,y + ym,z + zm); if (cval>max_val) max_val = cval; } res(x,y,z,c) = max_val; } _cimg_abort_catch_omp2 if (boundary_conditions) cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(is_inner_parallel)) cimg_forYZ(res,y,z) _cimg_abort_try_omp2 { cimg_abort_test2; for (int x = 0; x<width(); (y<my1 || y>=mye || z<mz1 || z>=mze)?++x:((x<mx1 - 1 || x>=mxe)?++x:(x=mxe))) { Tt max_val = cimg::type<Tt>::min(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) if (K(mx2 - xm,my2 - ym,mz2 - zm)) { const Tt cval = (Tt)img._atXYZ(x + xm,y + ym,z + zm); if (cval>max_val) max_val = cval; } res(x,y,z,c) = max_val; } } _cimg_abort_catch_omp2 else cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(is_inner_parallel)) cimg_forYZ(res,y,z) _cimg_abort_try_omp2 { cimg_abort_test2; for (int x = 0; x<width(); (y<my1 || y>=mye || z<mz1 || z>=mze)?++x:((x<mx1 - 1 || x>=mxe)?++x:(x=mxe))) { Tt max_val = cimg::type<Tt>::min(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) if (K(mx2 - xm,my2 - ym,mz2 - zm)) { const Tt cval = (Tt)img.atXYZ(x + xm,y + ym,z + zm,0,(T)0); if (cval>max_val) max_val = cval; } res(x,y,z,c) = max_val; } } _cimg_abort_catch_omp2 } } _cimg_abort_catch_omp cimg_abort_test; return res; } //! Dilate image by a rectangular structuring element of specified size. /** \param sx Width of the structuring element. \param sy Height of the structuring element. \param sz Depth of the structuring element. **/ CImg<T>& dilate(const unsigned int sx, const unsigned int sy, const unsigned int sz=1) { if (is_empty() || (sx==1 && sy==1 && sz==1)) return *this; if (sx>1 && _width>1) { // Along X-axis const int L = width(), off = 1, s = (int)sx, _s1 = s/2, _s2 = s - _s1, s1 = _s1>L?L:_s1, s2 = _s2>L?L:_s2; CImg<T> buf(L); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) firstprivate(buf) if (size()>524288)) cimg_forYZC(*this,y,z,c) { T *const ptrdb = buf._data, *ptrd = ptrdb, *const ptrde = buf._data + L - 1; const T *const ptrsb = data(0,y,z,c), *ptrs = ptrsb, *const ptrse = ptrs + L*off - off; T cur = *ptrs; ptrs+=off; bool is_first = true; for (int p = s2 - 1; p>0 && ptrs<=ptrse; --p) { const T val = *ptrs; ptrs+=off; if (val>=cur) { cur = val; is_first = false; } } *(ptrd++) = cur; if (ptrs>=ptrse) { T *pd = data(0,y,z,c); cur = std::max(cur,*ptrse); cimg_forX(buf,k) { *pd = cur; pd+=off; } } else { for (int p = s1; p>0 && ptrd<=ptrde; --p) { const T val = *ptrs; if (ptrs<ptrse) ptrs+=off; if (val>=cur) { cur = val; is_first = false; } *(ptrd++) = cur; } for (int p = L - s - 1; p>0; --p) { const T val = *ptrs; ptrs+=off; if (is_first) { const T *nptrs = ptrs - off; cur = val; for (int q = s - 2; q>0; --q) { nptrs-=off; const T nval = *nptrs; if (nval>cur) cur = nval; } nptrs-=off; const T nval = *nptrs; if (nval>cur) { cur = nval; is_first = true; } else is_first = false; } else { if (val>=cur) cur = val; else if (cur==*(ptrs-s*off)) is_first = true; } *(ptrd++) = cur; } ptrd = ptrde; ptrs = ptrse; cur = *ptrs; ptrs-=off; for (int p = s1; p>0 && ptrs>=ptrsb; --p) { const T val = *ptrs; ptrs-=off; if (val>cur) cur = val; } *(ptrd--) = cur; for (int p = s2 - 1; p>0 && ptrd>=ptrdb; --p) { const T val = *ptrs; if (ptrs>ptrsb) ptrs-=off; if (val>cur) cur = val; *(ptrd--) = cur; } T *pd = data(0,y,z,c); cimg_for(buf,ps,T) { *pd = *ps; pd+=off; } } } } if (sy>1 && _height>1) { // Along Y-axis const int L = height(), off = width(), s = (int)sy, _s1 = s/2, _s2 = s - _s1, s1 = _s1>L?L:_s1, s2 = _s2>L?L:_s2; CImg<T> buf(L); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) firstprivate(buf) if (size()>524288)) cimg_forXZC(*this,x,z,c) { T *const ptrdb = buf._data, *ptrd = ptrdb, *const ptrde = buf._data + L - 1; const T *const ptrsb = data(x,0,z,c), *ptrs = ptrsb, *const ptrse = ptrs + L*off - off; T cur = *ptrs; ptrs+=off; bool is_first = true; for (int p = s2 - 1; p>0 && ptrs<=ptrse; --p) { const T val = *ptrs; ptrs+=off; if (val>=cur) { cur = val; is_first = false; } } *(ptrd++) = cur; if (ptrs>=ptrse) { T *pd = data(x,0,z,c); cur = std::max(cur,*ptrse); cimg_forX(buf,k) { *pd = cur; pd+=off; } } else { for (int p = s1; p>0 && ptrd<=ptrde; --p) { const T val = *ptrs; if (ptrs<ptrse) ptrs+=off; if (val>=cur) { cur = val; is_first = false; } *(ptrd++) = cur; } for (int p = L - s - 1; p>0; --p) { const T val = *ptrs; ptrs+=off; if (is_first) { const T *nptrs = ptrs - off; cur = val; for (int q = s - 2; q>0; --q) { nptrs-=off; const T nval = *nptrs; if (nval>cur) cur = nval; } nptrs-=off; const T nval = *nptrs; if (nval>cur) { cur = nval; is_first = true; } else is_first = false; } else { if (val>=cur) cur = val; else if (cur==*(ptrs-s*off)) is_first = true; } *(ptrd++) = cur; } ptrd = ptrde; ptrs = ptrse; cur = *ptrs; ptrs-=off; for (int p = s1; p>0 && ptrs>=ptrsb; --p) { const T val = *ptrs; ptrs-=off; if (val>cur) cur = val; } *(ptrd--) = cur; for (int p = s2 - 1; p>0 && ptrd>=ptrdb; --p) { const T val = *ptrs; if (ptrs>ptrsb) ptrs-=off; if (val>cur) cur = val; *(ptrd--) = cur; } T *pd = data(x,0,z,c); cimg_for(buf,ps,T) { *pd = *ps; pd+=off; } } } } if (sz>1 && _depth>1) { // Along Z-axis const int L = depth(), off = width()*height(), s = (int)sz, _s1 = s/2, _s2 = s - _s1, s1 = _s1>L?L:_s1, s2 = _s2>L?L:_s2; CImg<T> buf(L); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) firstprivate(buf) if (size()>524288)) cimg_forXYC(*this,x,y,c) { T *const ptrdb = buf._data, *ptrd = ptrdb, *const ptrde = buf._data + L - 1; const T *const ptrsb = data(x,y,0,c), *ptrs = ptrsb, *const ptrse = ptrs + L*off - off; T cur = *ptrs; ptrs+=off; bool is_first = true; for (int p = s2 - 1; p>0 && ptrs<=ptrse; --p) { const T val = *ptrs; ptrs+=off; if (val>=cur) { cur = val; is_first = false; } } *(ptrd++) = cur; if (ptrs>=ptrse) { T *pd = data(x,y,0,c); cur = std::max(cur,*ptrse); cimg_forX(buf,k) { *pd = cur; pd+=off; } } else { for (int p = s1; p>0 && ptrd<=ptrde; --p) { const T val = *ptrs; if (ptrs<ptrse) ptrs+=off; if (val>=cur) { cur = val; is_first = false; } *(ptrd++) = cur; } for (int p = L - s - 1; p>0; --p) { const T val = *ptrs; ptrs+=off; if (is_first) { const T *nptrs = ptrs - off; cur = val; for (int q = s - 2; q>0; --q) { nptrs-=off; const T nval = *nptrs; if (nval>cur) cur = nval; } nptrs-=off; const T nval = *nptrs; if (nval>cur) { cur = nval; is_first = true; } else is_first = false; } else { if (val>=cur) cur = val; else if (cur==*(ptrs-s*off)) is_first = true; } *(ptrd++) = cur; } ptrd = ptrde; ptrs = ptrse; cur = *ptrs; ptrs-=off; for (int p = s1; p>0 && ptrs>=ptrsb; --p) { const T val = *ptrs; ptrs-=off; if (val>cur) cur = val; } *(ptrd--) = cur; for (int p = s2 - 1; p>0 && ptrd>=ptrdb; --p) { const T val = *ptrs; if (ptrs>ptrsb) ptrs-=off; if (val>cur) cur = val; *(ptrd--) = cur; } T *pd = data(x,y,0,c); cimg_for(buf,ps,T) { *pd = *ps; pd+=off; } } } } return *this; } //! Dilate image by a rectangular structuring element of specified size \newinstance. CImg<T> get_dilate(const unsigned int sx, const unsigned int sy, const unsigned int sz=1) const { return (+*this).dilate(sx,sy,sz); } //! Dilate image by a square structuring element of specified size. /** \param s Size of the structuring element. **/ CImg<T>& dilate(const unsigned int s) { return dilate(s,s,s); } //! Dilate image by a square structuring element of specified size \newinstance. CImg<T> get_dilate(const unsigned int s) const { return (+*this).dilate(s); } //! Compute watershed transform. /** \param priority Priority map. \param is_high_connectivity Boolean that choose between 4(false)- or 8(true)-connectivity in 2D case, and between 6(false)- or 26(true)-connectivity in 3D case. \note Non-zero values of the instance instance are propagated to zero-valued ones according to specified the priority map. **/ template<typename t> CImg<T>& watershed(const CImg<t>& priority, const bool is_high_connectivity=false) { #define _cimg_watershed_init(cond,X,Y,Z) \ if (cond && !(*this)(X,Y,Z)) Q._priority_queue_insert(labels,sizeQ,priority(X,Y,Z),X,Y,Z,nb_seeds) #define _cimg_watershed_propagate(cond,X,Y,Z) \ if (cond) { \ if ((*this)(X,Y,Z)) { \ ns = labels(X,Y,Z) - 1; xs = seeds(ns,0); ys = seeds(ns,1); zs = seeds(ns,2); \ d = cimg::sqr((float)x - xs) + cimg::sqr((float)y - ys) + cimg::sqr((float)z - zs); \ if (d<dmin) { dmin = d; nmin = ns; nlabel = (*this)(xs,ys,zs); } \ } else Q._priority_queue_insert(labels,sizeQ,priority(X,Y,Z),X,Y,Z,n); \ } if (is_empty()) return *this; if (!is_sameXYZ(priority)) throw CImgArgumentException(_cimg_instance "watershed(): image instance and specified priority (%u,%u,%u,%u,%p) " "have different dimensions.", cimg_instance, priority._width,priority._height,priority._depth,priority._spectrum,priority._data); if (_spectrum!=1) { cimg_forC(*this,c) get_shared_channel(c).watershed(priority.get_shared_channel(c%priority._spectrum)); return *this; } CImg<uintT> labels(_width,_height,_depth,1,0), seeds(64,3); CImg<typename cimg::superset2<T,t,int>::type> Q; unsigned int sizeQ = 0; int px, nx, py, ny, pz, nz; bool is_px, is_nx, is_py, is_ny, is_pz, is_nz; const bool is_3d = _depth>1; // Find seed points and insert them in priority queue. unsigned int nb_seeds = 0; const T *ptrs = _data; cimg_forXYZ(*this,x,y,z) if (*(ptrs++)) { // 3D version if (nb_seeds>=seeds._width) seeds.resize(2*seeds._width,3,1,1,0); seeds(nb_seeds,0) = x; seeds(nb_seeds,1) = y; seeds(nb_seeds++,2) = z; px = x - 1; nx = x + 1; py = y - 1; ny = y + 1; pz = z - 1; nz = z + 1; is_px = px>=0; is_nx = nx<width(); is_py = py>=0; is_ny = ny<height(); is_pz = pz>=0; is_nz = nz<depth(); _cimg_watershed_init(is_px,px,y,z); _cimg_watershed_init(is_nx,nx,y,z); _cimg_watershed_init(is_py,x,py,z); _cimg_watershed_init(is_ny,x,ny,z); if (is_3d) { _cimg_watershed_init(is_pz,x,y,pz); _cimg_watershed_init(is_nz,x,y,nz); } if (is_high_connectivity) { _cimg_watershed_init(is_px && is_py,px,py,z); _cimg_watershed_init(is_nx && is_py,nx,py,z); _cimg_watershed_init(is_px && is_ny,px,ny,z); _cimg_watershed_init(is_nx && is_ny,nx,ny,z); if (is_3d) { _cimg_watershed_init(is_px && is_pz,px,y,pz); _cimg_watershed_init(is_nx && is_pz,nx,y,pz); _cimg_watershed_init(is_px && is_nz,px,y,nz); _cimg_watershed_init(is_nx && is_nz,nx,y,nz); _cimg_watershed_init(is_py && is_pz,x,py,pz); _cimg_watershed_init(is_ny && is_pz,x,ny,pz); _cimg_watershed_init(is_py && is_nz,x,py,nz); _cimg_watershed_init(is_ny && is_nz,x,ny,nz); _cimg_watershed_init(is_px && is_py && is_pz,px,py,pz); _cimg_watershed_init(is_nx && is_py && is_pz,nx,py,pz); _cimg_watershed_init(is_px && is_ny && is_pz,px,ny,pz); _cimg_watershed_init(is_nx && is_ny && is_pz,nx,ny,pz); _cimg_watershed_init(is_px && is_py && is_nz,px,py,nz); _cimg_watershed_init(is_nx && is_py && is_nz,nx,py,nz); _cimg_watershed_init(is_px && is_ny && is_nz,px,ny,nz); _cimg_watershed_init(is_nx && is_ny && is_nz,nx,ny,nz); } } labels(x,y,z) = nb_seeds; } // Start watershed computation. while (sizeQ) { // Get and remove point with maximal priority from the queue. const int x = (int)Q(0,1), y = (int)Q(0,2), z = (int)Q(0,3); const unsigned int n = labels(x,y,z); px = x - 1; nx = x + 1; py = y - 1; ny = y + 1; pz = z - 1; nz = z + 1; is_px = px>=0; is_nx = nx<width(); is_py = py>=0; is_ny = ny<height(); is_pz = pz>=0; is_nz = nz<depth(); // Check labels of the neighbors. Q._priority_queue_remove(sizeQ); unsigned int xs, ys, zs, ns, nmin = 0; float d, dmin = cimg::type<float>::inf(); T nlabel = (T)0; _cimg_watershed_propagate(is_px,px,y,z); _cimg_watershed_propagate(is_nx,nx,y,z); _cimg_watershed_propagate(is_py,x,py,z); _cimg_watershed_propagate(is_ny,x,ny,z); if (is_3d) { _cimg_watershed_propagate(is_pz,x,y,pz); _cimg_watershed_propagate(is_nz,x,y,nz); } if (is_high_connectivity) { _cimg_watershed_propagate(is_px && is_py,px,py,z); _cimg_watershed_propagate(is_nx && is_py,nx,py,z); _cimg_watershed_propagate(is_px && is_ny,px,ny,z); _cimg_watershed_propagate(is_nx && is_ny,nx,ny,z); if (is_3d) { _cimg_watershed_propagate(is_px && is_pz,px,y,pz); _cimg_watershed_propagate(is_nx && is_pz,nx,y,pz); _cimg_watershed_propagate(is_px && is_nz,px,y,nz); _cimg_watershed_propagate(is_nx && is_nz,nx,y,nz); _cimg_watershed_propagate(is_py && is_pz,x,py,pz); _cimg_watershed_propagate(is_ny && is_pz,x,ny,pz); _cimg_watershed_propagate(is_py && is_nz,x,py,nz); _cimg_watershed_propagate(is_ny && is_nz,x,ny,nz); _cimg_watershed_propagate(is_px && is_py && is_pz,px,py,pz); _cimg_watershed_propagate(is_nx && is_py && is_pz,nx,py,pz); _cimg_watershed_propagate(is_px && is_ny && is_pz,px,ny,pz); _cimg_watershed_propagate(is_nx && is_ny && is_pz,nx,ny,pz); _cimg_watershed_propagate(is_px && is_py && is_nz,px,py,nz); _cimg_watershed_propagate(is_nx && is_py && is_nz,nx,py,nz); _cimg_watershed_propagate(is_px && is_ny && is_nz,px,ny,nz); _cimg_watershed_propagate(is_nx && is_ny && is_nz,nx,ny,nz); } } (*this)(x,y,z) = nlabel; labels(x,y,z) = ++nmin; } return *this; } //! Compute watershed transform \newinstance. template<typename t> CImg<T> get_watershed(const CImg<t>& priority, const bool is_high_connectivity=false) const { return (+*this).watershed(priority,is_high_connectivity); } // [internal] Insert/Remove items in priority queue, for watershed/distance transforms. template<typename tq, typename tv> bool _priority_queue_insert(CImg<tq>& is_queued, unsigned int& siz, const tv value, const unsigned int x, const unsigned int y, const unsigned int z, const unsigned int n=1) { if (is_queued(x,y,z)) return false; is_queued(x,y,z) = (tq)n; if (++siz>=_width) { if (!is_empty()) resize(_width*2,4,1,1,0); else assign(64,4); } (*this)(siz - 1,0) = (T)value; (*this)(siz - 1,1) = (T)x; (*this)(siz - 1,2) = (T)y; (*this)(siz - 1,3) = (T)z; for (unsigned int pos = siz - 1, par = 0; pos && value>(tv)(*this)(par=(pos + 1)/2 - 1,0); pos = par) { cimg::swap((*this)(pos,0),(*this)(par,0)); cimg::swap((*this)(pos,1),(*this)(par,1)); cimg::swap((*this)(pos,2),(*this)(par,2)); cimg::swap((*this)(pos,3),(*this)(par,3)); } return true; } CImg<T>& _priority_queue_remove(unsigned int& siz) { (*this)(0,0) = (*this)(--siz,0); (*this)(0,1) = (*this)(siz,1); (*this)(0,2) = (*this)(siz,2); (*this)(0,3) = (*this)(siz,3); const float value = (*this)(0,0); unsigned int pos = 0, swap = 0; do { const unsigned int left = 2*pos + 1, right = left + 1; if (right<siz && value<(*this)(right,0)) swap = (*this)(left,0)>(*this)(right,0)?left:right; else if (left<siz && value<(*this)(left,0)) swap = left; else break; cimg::swap((*this)(pos,0),(*this)(swap,0)); cimg::swap((*this)(pos,1),(*this)(swap,1)); cimg::swap((*this)(pos,2),(*this)(swap,2)); cimg::swap((*this)(pos,3),(*this)(swap,3)); pos = swap; } while (true); return *this; } //! Apply recursive Deriche filter. /** \param sigma Standard deviation of the filter. \param order Order of the filter. Can be <tt>{ 0=smooth-filter | 1=1st-derivative | 2=2nd-derivative }</tt>. \param axis Axis along which the filter is computed. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param boundary_conditions Boundary conditions. Can be <tt>{ 0=dirichlet | 1=neumann }</tt>. **/ CImg<T>& deriche(const float sigma, const unsigned int order=0, const char axis='x', const bool boundary_conditions=true) { #define _cimg_deriche_apply \ CImg<Tfloat> Y(N); \ Tfloat *ptrY = Y._data, yb = 0, yp = 0; \ T xp = (T)0; \ if (boundary_conditions) { xp = *ptrX; yb = yp = (Tfloat)(coefp*xp); } \ for (int m = 0; m<N; ++m) { \ const T xc = *ptrX; ptrX+=off; \ const Tfloat yc = *(ptrY++) = (Tfloat)(a0*xc + a1*xp - b1*yp - b2*yb); \ xp = xc; yb = yp; yp = yc; \ } \ T xn = (T)0, xa = (T)0; \ Tfloat yn = 0, ya = 0; \ if (boundary_conditions) { xn = xa = *(ptrX-off); yn = ya = (Tfloat)coefn*xn; } \ for (int n = N - 1; n>=0; --n) { \ const T xc = *(ptrX-=off); \ const Tfloat yc = (Tfloat)(a2*xn + a3*xa - b1*yn - b2*ya); \ xa = xn; xn = xc; ya = yn; yn = yc; \ *ptrX = (T)(*(--ptrY)+yc); \ } const char naxis = cimg::lowercase(axis); const float nsigma = sigma>=0?sigma:-sigma*(naxis=='x'?_width:naxis=='y'?_height:naxis=='z'?_depth:_spectrum)/100; if (is_empty() || (nsigma<0.1f && !order)) return *this; const float nnsigma = nsigma<0.1f?0.1f:nsigma, alpha = 1.695f/nnsigma, ema = (float)std::exp(-alpha), ema2 = (float)std::exp(-2*alpha), b1 = -2*ema, b2 = ema2; float a0 = 0, a1 = 0, a2 = 0, a3 = 0, coefp = 0, coefn = 0; switch (order) { case 0 : { const float k = (1-ema)*(1-ema)/(1 + 2*alpha*ema-ema2); a0 = k; a1 = k*(alpha - 1)*ema; a2 = k*(alpha + 1)*ema; a3 = -k*ema2; } break; case 1 : { const float k = -(1-ema)*(1-ema)*(1-ema)/(2*(ema + 1)*ema); a0 = a3 = 0; a1 = k*ema; a2 = -a1; } break; case 2 : { const float ea = (float)std::exp(-alpha), k = -(ema2 - 1)/(2*alpha*ema), kn = (-2*(-1 + 3*ea - 3*ea*ea + ea*ea*ea)/(3*ea + 1 + 3*ea*ea + ea*ea*ea)); a0 = kn; a1 = -kn*(1 + k*alpha)*ema; a2 = kn*(1 - k*alpha)*ema; a3 = -kn*ema2; } break; default : throw CImgArgumentException(_cimg_instance "deriche(): Invalid specified filter order %u " "(should be { 0=smoothing | 1=1st-derivative | 2=2nd-derivative }).", cimg_instance, order); } coefp = (a0 + a1)/(1 + b1 + b2); coefn = (a2 + a3)/(1 + b1 + b2); switch (naxis) { case 'x' : { const int N = width(); const ulongT off = 1U; cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height*_depth*_spectrum>=16)) cimg_forYZC(*this,y,z,c) { T *ptrX = data(0,y,z,c); _cimg_deriche_apply; } } break; case 'y' : { const int N = height(); const ulongT off = (ulongT)_width; cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height*_depth*_spectrum>=16)) cimg_forXZC(*this,x,z,c) { T *ptrX = data(x,0,z,c); _cimg_deriche_apply; } } break; case 'z' : { const int N = depth(); const ulongT off = (ulongT)_width*_height; cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height*_depth*_spectrum>=16)) cimg_forXYC(*this,x,y,c) { T *ptrX = data(x,y,0,c); _cimg_deriche_apply; } } break; default : { const int N = spectrum(); const ulongT off = (ulongT)_width*_height*_depth; cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height*_depth*_spectrum>=16)) cimg_forXYZ(*this,x,y,z) { T *ptrX = data(x,y,z,0); _cimg_deriche_apply; } } } return *this; } //! Apply recursive Deriche filter \newinstance. CImg<Tfloat> get_deriche(const float sigma, const unsigned int order=0, const char axis='x', const bool boundary_conditions=true) const { return CImg<Tfloat>(*this,false).deriche(sigma,order,axis,boundary_conditions); } // [internal] Apply a recursive filter (used by CImg<T>::vanvliet()). /* \param ptr the pointer of the data \param filter the coefficient of the filter in the following order [n,n - 1,n - 2,n - 3]. \param N size of the data \param off the offset between two data point \param order the order of the filter 0 (smoothing), 1st derivtive, 2nd derivative, 3rd derivative \param boundary_conditions Boundary conditions. Can be <tt>{ 0=dirichlet | 1=neumann }</tt>. \note Boundary condition using B. Triggs method (IEEE trans on Sig Proc 2005). */ static void _cimg_recursive_apply(T *data, const double filter[], const int N, const ulongT off, const unsigned int order, const bool boundary_conditions) { double val[4] = { 0 }; // res[n,n - 1,n - 2,n - 3,..] or res[n,n + 1,n + 2,n + 3,..] const double sumsq = filter[0], sum = sumsq * sumsq, a1 = filter[1], a2 = filter[2], a3 = filter[3], scaleM = 1. / ( (1. + a1 - a2 + a3) * (1. - a1 - a2 - a3) * (1. + a2 + (a1 - a3) * a3) ); double M[9]; // Triggs matrix M[0] = scaleM * (-a3 * a1 + 1. - a3 * a3 - a2); M[1] = scaleM * (a3 + a1) * (a2 + a3 * a1); M[2] = scaleM * a3 * (a1 + a3 * a2); M[3] = scaleM * (a1 + a3 * a2); M[4] = -scaleM * (a2 - 1.) * (a2 + a3 * a1); M[5] = -scaleM * a3 * (a3 * a1 + a3 * a3 + a2 - 1.); M[6] = scaleM * (a3 * a1 + a2 + a1 * a1 - a2 * a2); M[7] = scaleM * (a1 * a2 + a3 * a2 * a2 - a1 * a3 * a3 - a3 * a3 * a3 - a3 * a2 + a3); M[8] = scaleM * a3 * (a1 + a3 * a2); switch (order) { case 0 : { const double iplus = (boundary_conditions?data[(N - 1)*off]:(T)0); for (int pass = 0; pass<2; ++pass) { if (!pass) { for (int k = 1; k<4; ++k) val[k] = (boundary_conditions?*data/sumsq:0); } else { // apply Triggs boundary conditions const double uplus = iplus/(1. - a1 - a2 - a3), vplus = uplus/(1. - a1 - a2 - a3), unp = val[1] - uplus, unp1 = val[2] - uplus, unp2 = val[3] - uplus; val[0] = (M[0] * unp + M[1] * unp1 + M[2] * unp2 + vplus) * sum; val[1] = (M[3] * unp + M[4] * unp1 + M[5] * unp2 + vplus) * sum; val[2] = (M[6] * unp + M[7] * unp1 + M[8] * unp2 + vplus) * sum; *data = (T)val[0]; data -= off; for (int k = 3; k>0; --k) val[k] = val[k - 1]; } for (int n = pass; n<N; ++n) { val[0] = (*data); if (pass) val[0] *= sum; for (int k = 1; k<4; ++k) val[0] += val[k] * filter[k]; *data = (T)val[0]; if (!pass) data += off; else data -= off; for (int k = 3; k>0; --k) val[k] = val[k - 1]; } if (!pass) data -= off; } } break; case 1 : { double x[3]; // [front,center,back] for (int pass = 0; pass<2; ++pass) { if (!pass) { for (int k = 0; k<3; ++k) x[k] = (boundary_conditions?*data:(T)0); for (int k = 0; k<4; ++k) val[k] = 0; } else { // apply Triggs boundary conditions const double unp = val[1], unp1 = val[2], unp2 = val[3]; val[0] = (M[0] * unp + M[1] * unp1 + M[2] * unp2) * sum; val[1] = (M[3] * unp + M[4] * unp1 + M[5] * unp2) * sum; val[2] = (M[6] * unp + M[7] * unp1 + M[8] * unp2) * sum; *data = (T)val[0]; data -= off; for (int k = 3; k>0; --k) val[k] = val[k - 1]; } for (int n = pass; n<N - 1; ++n) { if (!pass) { x[0] = *(data + off); val[0] = 0.5f * (x[0] - x[2]); } else val[0] = (*data) * sum; for (int k = 1; k<4; ++k) val[0] += val[k] * filter[k]; *data = (T)val[0]; if (!pass) { data += off; for (int k = 2; k>0; --k) x[k] = x[k - 1]; } else { data-=off;} for (int k = 3; k>0; --k) val[k] = val[k - 1]; } *data = (T)0; } } break; case 2: { double x[3]; // [front,center,back] for (int pass = 0; pass<2; ++pass) { if (!pass) { for (int k = 0; k<3; ++k) x[k] = (boundary_conditions?*data:(T)0); for (int k = 0; k<4; ++k) val[k] = 0; } else { // apply Triggs boundary conditions const double unp = val[1], unp1 = val[2], unp2 = val[3]; val[0] = (M[0] * unp + M[1] * unp1 + M[2] * unp2) * sum; val[1] = (M[3] * unp + M[4] * unp1 + M[5] * unp2) * sum; val[2] = (M[6] * unp + M[7] * unp1 + M[8] * unp2) * sum; *data = (T)val[0]; data -= off; for (int k = 3; k>0; --k) val[k] = val[k - 1]; } for (int n = pass; n<N - 1; ++n) { if (!pass) { x[0] = *(data + off); val[0] = (x[1] - x[2]); } else { x[0] = *(data - off); val[0] = (x[2] - x[1]) * sum; } for (int k = 1; k<4; ++k) val[0] += val[k]*filter[k]; *data = (T)val[0]; if (!pass) data += off; else data -= off; for (int k = 2; k>0; --k) x[k] = x[k - 1]; for (int k = 3; k>0; --k) val[k] = val[k - 1]; } *data = (T)0; } } break; case 3: { double x[3]; // [front,center,back] for (int pass = 0; pass<2; ++pass) { if (!pass) { for (int k = 0; k<3; ++k) x[k] = (boundary_conditions?*data:(T)0); for (int k = 0; k<4; ++k) val[k] = 0; } else { // apply Triggs boundary conditions const double unp = val[1], unp1 = val[2], unp2 = val[3]; val[0] = (M[0] * unp + M[1] * unp1 + M[2] * unp2) * sum; val[1] = (M[3] * unp + M[4] * unp1 + M[5] * unp2) * sum; val[2] = (M[6] * unp + M[7] * unp1 + M[8] * unp2) * sum; *data = (T)val[0]; data -= off; for (int k = 3; k>0; --k) val[k] = val[k - 1]; } for (int n = pass; n<N - 1; ++n) { if (!pass) { x[0] = *(data + off); val[0] = (x[0] - 2*x[1] + x[2]); } else { x[0] = *(data - off); val[0] = 0.5f * (x[2] - x[0]) * sum; } for (int k = 1; k<4; ++k) val[0] += val[k] * filter[k]; *data = (T)val[0]; if (!pass) data += off; else data -= off; for (int k = 2; k>0; --k) x[k] = x[k - 1]; for (int k = 3; k>0; --k) val[k] = val[k - 1]; } *data = (T)0; } } break; } } //! Van Vliet recursive Gaussian filter. /** \param sigma standard deviation of the Gaussian filter \param order the order of the filter 0,1,2,3 \param axis Axis along which the filter is computed. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param boundary_conditions Boundary conditions. Can be <tt>{ 0=dirichlet | 1=neumann }</tt>. \note dirichlet boundary condition has a strange behavior I.T. Young, L.J. van Vliet, M. van Ginkel, Recursive Gabor filtering. IEEE Trans. Sig. Proc., vol. 50, pp. 2799-2805, 2002. (this is an improvement over Young-Van Vliet, Sig. Proc. 44, 1995) Boundary conditions (only for order 0) using Triggs matrix, from B. Triggs and M. Sdika. Boundary conditions for Young-van Vliet recursive filtering. IEEE Trans. Signal Processing, vol. 54, pp. 2365-2367, 2006. **/ CImg<T>& vanvliet(const float sigma, const unsigned int order, const char axis='x', const bool boundary_conditions=true) { if (is_empty()) return *this; if (!cimg::type<T>::is_float()) return CImg<Tfloat>(*this,false).vanvliet(sigma,order,axis,boundary_conditions).move_to(*this); const char naxis = cimg::lowercase(axis); const float nsigma = sigma>=0?sigma:-sigma*(naxis=='x'?_width:naxis=='y'?_height:naxis=='z'?_depth:_spectrum)/100; if (is_empty() || (nsigma<0.5f && !order)) return *this; const double nnsigma = nsigma<0.5f?0.5f:nsigma, m0 = 1.16680, m1 = 1.10783, m2 = 1.40586, m1sq = m1 * m1, m2sq = m2 * m2, q = (nnsigma<3.556?-0.2568 + 0.5784*nnsigma + 0.0561*nnsigma*nnsigma:2.5091 + 0.9804*(nnsigma - 3.556)), qsq = q * q, scale = (m0 + q) * (m1sq + m2sq + 2 * m1 * q + qsq), b1 = -q * (2 * m0 * m1 + m1sq + m2sq + (2 * m0 + 4 * m1) * q + 3 * qsq) / scale, b2 = qsq * (m0 + 2 * m1 + 3 * q) / scale, b3 = -qsq * q / scale, B = ( m0 * (m1sq + m2sq) ) / scale; double filter[4]; filter[0] = B; filter[1] = -b1; filter[2] = -b2; filter[3] = -b3; switch (naxis) { case 'x' : { cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height*_depth*_spectrum>=16)) cimg_forYZC(*this,y,z,c) _cimg_recursive_apply(data(0,y,z,c),filter,_width,1U,order,boundary_conditions); } break; case 'y' : { cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height*_depth*_spectrum>=16)) cimg_forXZC(*this,x,z,c) _cimg_recursive_apply(data(x,0,z,c),filter,_height,(ulongT)_width,order,boundary_conditions); } break; case 'z' : { cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height*_depth*_spectrum>=16)) cimg_forXYC(*this,x,y,c) _cimg_recursive_apply(data(x,y,0,c),filter,_depth,(ulongT)_width*_height, order,boundary_conditions); } break; default : { cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height*_depth*_spectrum>=16)) cimg_forXYZ(*this,x,y,z) _cimg_recursive_apply(data(x,y,z,0),filter,_spectrum,(ulongT)_width*_height*_depth, order,boundary_conditions); } } return *this; } //! Blur image using Van Vliet recursive Gaussian filter. \newinstance. CImg<Tfloat> get_vanvliet(const float sigma, const unsigned int order, const char axis='x', const bool boundary_conditions=true) const { return CImg<Tfloat>(*this,false).vanvliet(sigma,order,axis,boundary_conditions); } //! Blur image. /** \param sigma_x Standard deviation of the blur, along the X-axis. \param sigma_y Standard deviation of the blur, along the Y-axis. \param sigma_z Standard deviation of the blur, along the Z-axis. \param boundary_conditions Boundary conditions. Can be <tt>{ false=dirichlet | true=neumann }</tt>. \param is_gaussian Tells if the blur uses a gaussian (\c true) or quasi-gaussian (\c false) kernel. \note - The blur is computed as a 0-order Deriche filter. This is not a gaussian blur. - This is a recursive algorithm, not depending on the values of the standard deviations. \see deriche(), vanvliet(). **/ CImg<T>& blur(const float sigma_x, const float sigma_y, const float sigma_z, const bool boundary_conditions=true, const bool is_gaussian=false) { if (is_empty()) return *this; if (is_gaussian) { if (_width>1) vanvliet(sigma_x,0,'x',boundary_conditions); if (_height>1) vanvliet(sigma_y,0,'y',boundary_conditions); if (_depth>1) vanvliet(sigma_z,0,'z',boundary_conditions); } else { if (_width>1) deriche(sigma_x,0,'x',boundary_conditions); if (_height>1) deriche(sigma_y,0,'y',boundary_conditions); if (_depth>1) deriche(sigma_z,0,'z',boundary_conditions); } return *this; } //! Blur image \newinstance. CImg<Tfloat> get_blur(const float sigma_x, const float sigma_y, const float sigma_z, const bool boundary_conditions=true, const bool is_gaussian=false) const { return CImg<Tfloat>(*this,false).blur(sigma_x,sigma_y,sigma_z,boundary_conditions,is_gaussian); } //! Blur image isotropically. /** \param sigma Standard deviation of the blur. \param boundary_conditions Boundary conditions. Can be <tt>{ 0=dirichlet | 1=neumann }</tt>.a \param is_gaussian Use a gaussian kernel (VanVliet) is set, a pseudo-gaussian (Deriche) otherwise. \see deriche(), vanvliet(). **/ CImg<T>& blur(const float sigma, const bool boundary_conditions=true, const bool is_gaussian=false) { const float nsigma = sigma>=0?sigma:-sigma*cimg::max(_width,_height,_depth)/100; return blur(nsigma,nsigma,nsigma,boundary_conditions,is_gaussian); } //! Blur image isotropically \newinstance. CImg<Tfloat> get_blur(const float sigma, const bool boundary_conditions=true, const bool is_gaussian=false) const { return CImg<Tfloat>(*this,false).blur(sigma,boundary_conditions,is_gaussian); } //! Blur image anisotropically, directed by a field of diffusion tensors. /** \param G Field of square roots of diffusion tensors/vectors used to drive the smoothing. \param amplitude Amplitude of the smoothing. \param dl Spatial discretization. \param da Angular discretization. \param gauss_prec Precision of the diffusion process. \param interpolation_type Interpolation scheme. Can be <tt>{ 0=nearest-neighbor | 1=linear | 2=Runge-Kutta }</tt>. \param is_fast_approx Tells if a fast approximation of the gaussian function is used or not. **/ template<typename t> CImg<T>& blur_anisotropic(const CImg<t>& G, const float amplitude=60, const float dl=0.8f, const float da=30, const float gauss_prec=2, const unsigned int interpolation_type=0, const bool is_fast_approx=1) { // Check arguments and init variables if (!is_sameXYZ(G) || (G._spectrum!=3 && G._spectrum!=6)) throw CImgArgumentException(_cimg_instance "blur_anisotropic(): Invalid specified diffusion tensor field (%u,%u,%u,%u,%p).", cimg_instance, G._width,G._height,G._depth,G._spectrum,G._data); if (is_empty() || dl<0) return *this; const float namplitude = amplitude>=0?amplitude:-amplitude*cimg::max(_width,_height,_depth)/100; unsigned int iamplitude = cimg::round(namplitude); const bool is_3d = (G._spectrum==6); T val_min, val_max = max_min(val_min); _cimg_abort_init_omp; cimg_abort_init; if (da<=0) { // Iterated oriented Laplacians CImg<Tfloat> velocity(_width,_height,_depth,_spectrum); for (unsigned int iteration = 0; iteration<iamplitude; ++iteration) { Tfloat *ptrd = velocity._data, veloc_max = 0; if (is_3d) // 3D version cimg_forC(*this,c) { cimg_abort_test; CImg_3x3x3(I,Tfloat); cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) { const Tfloat ixx = Incc + Ipcc - 2*Iccc, ixy = (Innc + Ippc - Inpc - Ipnc)/4, ixz = (Incn + Ipcp - Incp - Ipcn)/4, iyy = Icnc + Icpc - 2*Iccc, iyz = (Icnn + Icpp - Icnp - Icpn)/4, izz = Iccn + Iccp - 2*Iccc, veloc = (Tfloat)(G(x,y,z,0)*ixx + 2*G(x,y,z,1)*ixy + 2*G(x,y,z,2)*ixz + G(x,y,z,3)*iyy + 2*G(x,y,z,4)*iyz + G(x,y,z,5)*izz); *(ptrd++) = veloc; if (veloc>veloc_max) veloc_max = veloc; else if (-veloc>veloc_max) veloc_max = -veloc; } } else // 2D version cimg_forZC(*this,z,c) { cimg_abort_test; CImg_3x3(I,Tfloat); cimg_for3x3(*this,x,y,z,c,I,Tfloat) { const Tfloat ixx = Inc + Ipc - 2*Icc, ixy = (Inn + Ipp - Inp - Ipn)/4, iyy = Icn + Icp - 2*Icc, veloc = (Tfloat)(G(x,y,0,0)*ixx + 2*G(x,y,0,1)*ixy + G(x,y,0,2)*iyy); *(ptrd++) = veloc; if (veloc>veloc_max) veloc_max = veloc; else if (-veloc>veloc_max) veloc_max = -veloc; } } if (veloc_max>0) *this+=(velocity*=dl/veloc_max); } } else { // LIC-based smoothing const ulongT whd = (ulongT)_width*_height*_depth; const float sqrt2amplitude = (float)std::sqrt(2*namplitude); const int dx1 = width() - 1, dy1 = height() - 1, dz1 = depth() - 1; CImg<Tfloat> res(_width,_height,_depth,_spectrum,0), W(_width,_height,_depth,is_3d?4:3), val(_spectrum,1,1,1,0); int N = 0; if (is_3d) { // 3D version for (float phi = cimg::mod(180.f,da)/2.f; phi<=180; phi+=da) { const float phir = (float)(phi*cimg::PI/180), datmp = (float)(da/std::cos(phir)), da2 = datmp<1?360.f:datmp; for (float theta = 0; theta<360; (theta+=da2),++N) { const float thetar = (float)(theta*cimg::PI/180), vx = (float)(std::cos(thetar)*std::cos(phir)), vy = (float)(std::sin(thetar)*std::cos(phir)), vz = (float)std::sin(phir); const t *pa = G.data(0,0,0,0), *pb = G.data(0,0,0,1), *pc = G.data(0,0,0,2), *pd = G.data(0,0,0,3), *pe = G.data(0,0,0,4), *pf = G.data(0,0,0,5); Tfloat *pd0 = W.data(0,0,0,0), *pd1 = W.data(0,0,0,1), *pd2 = W.data(0,0,0,2), *pd3 = W.data(0,0,0,3); cimg_forXYZ(G,xg,yg,zg) { const t a = *(pa++), b = *(pb++), c = *(pc++), d = *(pd++), e = *(pe++), f = *(pf++); const float u = (float)(a*vx + b*vy + c*vz), v = (float)(b*vx + d*vy + e*vz), w = (float)(c*vx + e*vy + f*vz), n = 1e-5f + cimg::hypot(u,v,w), dln = dl/n; *(pd0++) = (Tfloat)(u*dln); *(pd1++) = (Tfloat)(v*dln); *(pd2++) = (Tfloat)(w*dln); *(pd3++) = (Tfloat)n; } cimg_abort_test; cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height*_depth>=2) firstprivate(val)) cimg_forYZ(*this,y,z) _cimg_abort_try_omp2 { cimg_abort_test2; cimg_forX(*this,x) { val.fill(0); const float n = (float)W(x,y,z,3), fsigma = (float)(n*sqrt2amplitude), fsigma2 = 2*fsigma*fsigma, length = gauss_prec*fsigma; float S = 0, X = (float)x, Y = (float)y, Z = (float)z; switch (interpolation_type) { case 0 : { // Nearest neighbor for (float l = 0; l<length && X>=0 && X<=dx1 && Y>=0 && Y<=dy1 && Z>=0 && Z<=dz1; l+=dl) { const int cx = (int)(X + 0.5f), cy = (int)(Y + 0.5f), cz = (int)(Z + 0.5f); const float u = (float)W(cx,cy,cz,0), v = (float)W(cx,cy,cz,1), w = (float)W(cx,cy,cz,2); if (is_fast_approx) { cimg_forC(*this,c) val[c]+=(Tfloat)(*this)(cx,cy,cz,c); ++S; } else { const float coef = (float)std::exp(-l*l/fsigma2); cimg_forC(*this,c) val[c]+=(Tfloat)(coef*(*this)(cx,cy,cz,c)); S+=coef; } X+=u; Y+=v; Z+=w; } } break; case 1 : { // Linear interpolation for (float l = 0; l<length && X>=0 && X<=dx1 && Y>=0 && Y<=dy1 && Z>=0 && Z<=dz1; l+=dl) { const float u = (float)(W._linear_atXYZ(X,Y,Z,0)), v = (float)(W._linear_atXYZ(X,Y,Z,1)), w = (float)(W._linear_atXYZ(X,Y,Z,2)); if (is_fast_approx) { cimg_forC(*this,c) val[c]+=(Tfloat)_linear_atXYZ(X,Y,Z,c); ++S; } else { const float coef = (float)std::exp(-l*l/fsigma2); cimg_forC(*this,c) val[c]+=(Tfloat)(coef*_linear_atXYZ(X,Y,Z,c)); S+=coef; } X+=u; Y+=v; Z+=w; } } break; default : { // 2nd order Runge Kutta for (float l = 0; l<length && X>=0 && X<=dx1 && Y>=0 && Y<=dy1 && Z>=0 && Z<=dz1; l+=dl) { const float u0 = (float)(0.5f*W._linear_atXYZ(X,Y,Z,0)), v0 = (float)(0.5f*W._linear_atXYZ(X,Y,Z,1)), w0 = (float)(0.5f*W._linear_atXYZ(X,Y,Z,2)), u = (float)(W._linear_atXYZ(X + u0,Y + v0,Z + w0,0)), v = (float)(W._linear_atXYZ(X + u0,Y + v0,Z + w0,1)), w = (float)(W._linear_atXYZ(X + u0,Y + v0,Z + w0,2)); if (is_fast_approx) { cimg_forC(*this,c) val[c]+=(Tfloat)_linear_atXYZ(X,Y,Z,c); ++S; } else { const float coef = (float)std::exp(-l*l/fsigma2); cimg_forC(*this,c) val[c]+=(Tfloat)(coef*_linear_atXYZ(X,Y,Z,c)); S+=coef; } X+=u; Y+=v; Z+=w; } } break; } Tfloat *ptrd = res.data(x,y,z); if (S>0) cimg_forC(res,c) { *ptrd+=val[c]/S; ptrd+=whd; } else cimg_forC(res,c) { *ptrd+=(Tfloat)((*this)(x,y,z,c)); ptrd+=whd; } } } _cimg_abort_catch_omp2 } } } else { // 2D LIC algorithm for (float theta = cimg::mod(360.f,da)/2.f; theta<360; (theta+=da),++N) { const float thetar = (float)(theta*cimg::PI/180), vx = (float)(std::cos(thetar)), vy = (float)(std::sin(thetar)); const t *pa = G.data(0,0,0,0), *pb = G.data(0,0,0,1), *pc = G.data(0,0,0,2); Tfloat *pd0 = W.data(0,0,0,0), *pd1 = W.data(0,0,0,1), *pd2 = W.data(0,0,0,2); cimg_forXY(G,xg,yg) { const t a = *(pa++), b = *(pb++), c = *(pc++); const float u = (float)(a*vx + b*vy), v = (float)(b*vx + c*vy), n = std::max(1e-5f,cimg::hypot(u,v)), dln = dl/n; *(pd0++) = (Tfloat)(u*dln); *(pd1++) = (Tfloat)(v*dln); *(pd2++) = (Tfloat)n; } cimg_abort_test; cimg_pragma_openmp(parallel for cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height>=2) firstprivate(val)) cimg_forY(*this,y) _cimg_abort_try_omp2 { cimg_abort_test2; cimg_forX(*this,x) { val.fill(0); const float n = (float)W(x,y,0,2), fsigma = (float)(n*sqrt2amplitude), fsigma2 = 2*fsigma*fsigma, length = gauss_prec*fsigma; float S = 0, X = (float)x, Y = (float)y; switch (interpolation_type) { case 0 : { // Nearest-neighbor for (float l = 0; l<length && X>=0 && X<=dx1 && Y>=0 && Y<=dy1; l+=dl) { const int cx = (int)(X + 0.5f), cy = (int)(Y + 0.5f); const float u = (float)W(cx,cy,0,0), v = (float)W(cx,cy,0,1); if (is_fast_approx) { cimg_forC(*this,c) val[c]+=(Tfloat)(*this)(cx,cy,0,c); ++S; } else { const float coef = (float)std::exp(-l*l/fsigma2); cimg_forC(*this,c) val[c]+=(Tfloat)(coef*(*this)(cx,cy,0,c)); S+=coef; } X+=u; Y+=v; } } break; case 1 : { // Linear interpolation for (float l = 0; l<length && X>=0 && X<=dx1 && Y>=0 && Y<=dy1; l+=dl) { const float u = (float)(W._linear_atXY(X,Y,0,0)), v = (float)(W._linear_atXY(X,Y,0,1)); if (is_fast_approx) { cimg_forC(*this,c) val[c]+=(Tfloat)_linear_atXY(X,Y,0,c); ++S; } else { const float coef = (float)std::exp(-l*l/fsigma2); cimg_forC(*this,c) val[c]+=(Tfloat)(coef*_linear_atXY(X,Y,0,c)); S+=coef; } X+=u; Y+=v; } } break; default : { // 2nd-order Runge-kutta interpolation for (float l = 0; l<length && X>=0 && X<=dx1 && Y>=0 && Y<=dy1; l+=dl) { const float u0 = (float)(0.5f*W._linear_atXY(X,Y,0,0)), v0 = (float)(0.5f*W._linear_atXY(X,Y,0,1)), u = (float)(W._linear_atXY(X + u0,Y + v0,0,0)), v = (float)(W._linear_atXY(X + u0,Y + v0,0,1)); if (is_fast_approx) { cimg_forC(*this,c) val[c]+=(Tfloat)_linear_atXY(X,Y,0,c); ++S; } else { const float coef = (float)std::exp(-l*l/fsigma2); cimg_forC(*this,c) val[c]+=(Tfloat)(coef*_linear_atXY(X,Y,0,c)); S+=coef; } X+=u; Y+=v; } } } Tfloat *ptrd = res.data(x,y); if (S>0) cimg_forC(res,c) { *ptrd+=val[c]/S; ptrd+=whd; } else cimg_forC(res,c) { *ptrd+=(Tfloat)((*this)(x,y,0,c)); ptrd+=whd; } } } _cimg_abort_catch_omp2 } } const Tfloat *ptrs = res._data; cimg_for(*this,ptrd,T) { const Tfloat _val = *(ptrs++)/N; *ptrd = _val<val_min?val_min:(_val>val_max?val_max:(T)_val); } } cimg_abort_test; return *this; } //! Blur image anisotropically, directed by a field of diffusion tensors \newinstance. template<typename t> CImg<Tfloat> get_blur_anisotropic(const CImg<t>& G, const float amplitude=60, const float dl=0.8f, const float da=30, const float gauss_prec=2, const unsigned int interpolation_type=0, const bool is_fast_approx=true) const { return CImg<Tfloat>(*this,false).blur_anisotropic(G,amplitude,dl,da,gauss_prec,interpolation_type,is_fast_approx); } //! Blur image anisotropically, in an edge-preserving way. /** \param amplitude Amplitude of the smoothing. \param sharpness Sharpness. \param anisotropy Anisotropy. \param alpha Standard deviation of the gradient blur. \param sigma Standard deviation of the structure tensor blur. \param dl Spatial discretization. \param da Angular discretization. \param gauss_prec Precision of the diffusion process. \param interpolation_type Interpolation scheme. Can be <tt>{ 0=nearest-neighbor | 1=linear | 2=Runge-Kutta }</tt>. \param is_fast_approx Tells if a fast approximation of the gaussian function is used or not. **/ CImg<T>& blur_anisotropic(const float amplitude, const float sharpness=0.7f, const float anisotropy=0.6f, const float alpha=0.6f, const float sigma=1.1f, const float dl=0.8f, const float da=30, const float gauss_prec=2, const unsigned int interpolation_type=0, const bool is_fast_approx=true) { const float nalpha = alpha>=0?alpha:-alpha*cimg::max(_width,_height,_depth)/100; const float nsigma = sigma>=0?sigma:-sigma*cimg::max(_width,_height,_depth)/100; return blur_anisotropic(get_diffusion_tensors(sharpness,anisotropy,nalpha,nsigma,interpolation_type!=3), amplitude,dl,da,gauss_prec,interpolation_type,is_fast_approx); } //! Blur image anisotropically, in an edge-preserving way \newinstance. CImg<Tfloat> get_blur_anisotropic(const float amplitude, const float sharpness=0.7f, const float anisotropy=0.6f, const float alpha=0.6f, const float sigma=1.1f, const float dl=0.8f, const float da=30, const float gauss_prec=2, const unsigned int interpolation_type=0, const bool is_fast_approx=true) const { return CImg<Tfloat>(*this,false).blur_anisotropic(amplitude,sharpness,anisotropy,alpha,sigma,dl,da,gauss_prec, interpolation_type,is_fast_approx); } //! Blur image, with the joint bilateral filter. /** \param guide Image used to model the smoothing weights. \param sigma_x Amount of blur along the X-axis. \param sigma_y Amount of blur along the Y-axis. \param sigma_z Amount of blur along the Z-axis. \param sigma_r Amount of blur along the value axis. \param sampling_x Amount of downsampling along the X-axis used for the approximation. Defaults (0) to sigma_x. \param sampling_y Amount of downsampling along the Y-axis used for the approximation. Defaults (0) to sigma_y. \param sampling_z Amount of downsampling along the Z-axis used for the approximation. Defaults (0) to sigma_z. \param sampling_r Amount of downsampling along the value axis used for the approximation. Defaults (0) to sigma_r. \note This algorithm uses the optimisation technique proposed by S. Paris and F. Durand, in ECCV'2006 (extended for 3D volumetric images). It is based on the reference implementation http://people.csail.mit.edu/jiawen/software/bilateralFilter.m **/ template<typename t> CImg<T>& blur_bilateral(const CImg<t>& guide, const float sigma_x, const float sigma_y, const float sigma_z, const float sigma_r, const float sampling_x, const float sampling_y, const float sampling_z, const float sampling_r) { if (!is_sameXYZ(guide)) throw CImgArgumentException(_cimg_instance "blur_bilateral(): Invalid size for specified guide image (%u,%u,%u,%u,%p).", cimg_instance, guide._width,guide._height,guide._depth,guide._spectrum,guide._data); if (is_empty() || (!sigma_x && !sigma_y && !sigma_z)) return *this; T edge_min, edge_max = guide.max_min(edge_min); if (edge_min==edge_max) return blur(sigma_x,sigma_y,sigma_z); const float edge_delta = (float)(edge_max - edge_min), _sigma_x = sigma_x>=0?sigma_x:-sigma_x*_width/100, _sigma_y = sigma_y>=0?sigma_y:-sigma_y*_height/100, _sigma_z = sigma_z>=0?sigma_z:-sigma_z*_depth/100, _sigma_r = sigma_r>=0?sigma_r:-sigma_r*(edge_max - edge_min)/100, _sampling_x = sampling_x?sampling_x:std::max(_sigma_x,1.f), _sampling_y = sampling_y?sampling_y:std::max(_sigma_y,1.f), _sampling_z = sampling_z?sampling_z:std::max(_sigma_z,1.f), _sampling_r = sampling_r?sampling_r:std::max(_sigma_r,edge_delta/256), derived_sigma_x = _sigma_x / _sampling_x, derived_sigma_y = _sigma_y / _sampling_y, derived_sigma_z = _sigma_z / _sampling_z, derived_sigma_r = _sigma_r / _sampling_r; const int padding_x = (int)(2*derived_sigma_x) + 1, padding_y = (int)(2*derived_sigma_y) + 1, padding_z = (int)(2*derived_sigma_z) + 1, padding_r = (int)(2*derived_sigma_r) + 1; const unsigned int bx = (unsigned int)((_width - 1)/_sampling_x + 1 + 2*padding_x), by = (unsigned int)((_height - 1)/_sampling_y + 1 + 2*padding_y), bz = (unsigned int)((_depth - 1)/_sampling_z + 1 + 2*padding_z), br = (unsigned int)(edge_delta/_sampling_r + 1 + 2*padding_r); if (bx>0 || by>0 || bz>0 || br>0) { const bool is_3d = (_depth>1); if (is_3d) { // 3D version of the algorithm CImg<floatT> bgrid(bx,by,bz,br), bgridw(bx,by,bz,br); cimg_forC(*this,c) { const CImg<t> _guide = guide.get_shared_channel(c%guide._spectrum); bgrid.fill(0); bgridw.fill(0); cimg_forXYZ(*this,x,y,z) { const T val = (*this)(x,y,z,c); const float edge = (float)_guide(x,y,z); const int X = (int)cimg::round(x/_sampling_x) + padding_x, Y = (int)cimg::round(y/_sampling_y) + padding_y, Z = (int)cimg::round(z/_sampling_z) + padding_z, R = (int)cimg::round((edge - edge_min)/_sampling_r) + padding_r; bgrid(X,Y,Z,R)+=(float)val; bgridw(X,Y,Z,R)+=1; } bgrid.blur(derived_sigma_x,derived_sigma_y,derived_sigma_z,true).deriche(derived_sigma_r,0,'c',false); bgridw.blur(derived_sigma_x,derived_sigma_y,derived_sigma_z,true).deriche(derived_sigma_r,0,'c',false); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(size(),4096)) cimg_forXYZ(*this,x,y,z) { const float edge = (float)_guide(x,y,z); const float X = x/_sampling_x + padding_x, Y = y/_sampling_y + padding_y, Z = z/_sampling_z + padding_z, R = (edge - edge_min)/_sampling_r + padding_r; const float bval0 = bgrid._linear_atXYZC(X,Y,Z,R), bval1 = bgridw._linear_atXYZC(X,Y,Z,R); (*this)(x,y,z,c) = (T)(bval0/bval1); } } } else { // 2D version of the algorithm CImg<floatT> bgrid(bx,by,br,2); cimg_forC(*this,c) { const CImg<t> _guide = guide.get_shared_channel(c%guide._spectrum); bgrid.fill(0); cimg_forXY(*this,x,y) { const T val = (*this)(x,y,c); const float edge = (float)_guide(x,y); const int X = (int)cimg::round(x/_sampling_x) + padding_x, Y = (int)cimg::round(y/_sampling_y) + padding_y, R = (int)cimg::round((edge - edge_min)/_sampling_r) + padding_r; bgrid(X,Y,R,0)+=(float)val; bgrid(X,Y,R,1)+=1; } bgrid.blur(derived_sigma_x,derived_sigma_y,0,true).blur(0,0,derived_sigma_r,false); cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(size(),4096)) cimg_forXY(*this,x,y) { const float edge = (float)_guide(x,y); const float X = x/_sampling_x + padding_x, Y = y/_sampling_y + padding_y, R = (edge - edge_min)/_sampling_r + padding_r; const float bval0 = bgrid._linear_atXYZ(X,Y,R,0), bval1 = bgrid._linear_atXYZ(X,Y,R,1); (*this)(x,y,c) = (T)(bval0/bval1); } } } } return *this; } //! Blur image, with the joint bilateral filter \newinstance. template<typename t> CImg<Tfloat> get_blur_bilateral(const CImg<t>& guide, const float sigma_x, const float sigma_y, const float sigma_z, const float sigma_r, const float sampling_x, const float sampling_y, const float sampling_z, const float sampling_r) const { return CImg<Tfloat>(*this,false).blur_bilateral(guide,sigma_x,sigma_y,sigma_z,sigma_r, sampling_x,sampling_y,sampling_z,sampling_r); } //! Blur image using the joint bilateral filter. /** \param guide Image used to model the smoothing weights. \param sigma_s Amount of blur along the XYZ-axes. \param sigma_r Amount of blur along the value axis. \param sampling_s Amount of downsampling along the XYZ-axes used for the approximation. Defaults to sigma_s. \param sampling_r Amount of downsampling along the value axis used for the approximation. Defaults to sigma_r. **/ template<typename t> CImg<T>& blur_bilateral(const CImg<t>& guide, const float sigma_s, const float sigma_r, const float sampling_s=0, const float sampling_r=0) { const float _sigma_s = sigma_s>=0?sigma_s:-sigma_s*cimg::max(_width,_height,_depth)/100; return blur_bilateral(guide,_sigma_s,_sigma_s,_sigma_s,sigma_r,sampling_s,sampling_s,sampling_s,sampling_r); } //! Blur image using the bilateral filter \newinstance. template<typename t> CImg<Tfloat> get_blur_bilateral(const CImg<t>& guide, const float sigma_s, const float sigma_r, const float sampling_s=0, const float sampling_r=0) const { return CImg<Tfloat>(*this,false).blur_bilateral(guide,sigma_s,sigma_r,sampling_s,sampling_r); } // [internal] Apply a box filter (used by CImg<T>::boxfilter() and CImg<T>::blur_box()). /* \param ptr the pointer of the data \param N size of the data \param boxsize Size of the box filter (can be subpixel). \param off the offset between two data point \param order the order of the filter 0 (smoothing), 1st derivtive and 2nd derivative. \param boundary_conditions Boundary conditions. Can be <tt>{ 0=dirichlet | 1=neumann }</tt>. */ static void _cimg_blur_box_apply(T *ptr, const float boxsize, const int N, const ulongT off, const int order, const bool boundary_conditions, const unsigned int nb_iter) { // Smooth. if (boxsize>1 && nb_iter) { const int w2 = (int)(boxsize - 1)/2; const unsigned int winsize = 2*w2 + 1U; const double frac = (boxsize - winsize)/2.; CImg<T> win(winsize); for (unsigned int iter = 0; iter<nb_iter; ++iter) { Tdouble sum = 0; // window sum for (int x = -w2; x<=w2; ++x) { win[x + w2] = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,x); sum+=win[x + w2]; } int ifirst = 0, ilast = 2*w2; T prev = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,-w2 - 1), next = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,w2 + 1); for (int x = 0; x < N - 1; ++x) { const double sum2 = sum + frac * (prev + next); ptr[x*off] = (T)(sum2/boxsize); prev = win[ifirst]; sum-=prev; ifirst = (int)((ifirst + 1)%winsize); ilast = (int)((ilast + 1)%winsize); win[ilast] = next; sum+=next; next = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,x + w2 + 2); } const double sum2 = sum + frac * (prev + next); ptr[(N - 1)*off] = (T)(sum2/boxsize); } } // Derive. switch (order) { case 0 : break; case 1 : { Tfloat p = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,-1), c = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,0), n = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,1); for (int x = 0; x<N - 1; ++x) { ptr[x*off] = (T)((n-p)/2.); p = c; c = n; n = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,x + 2); } ptr[(N - 1)*off] = (T)((n-p)/2.); } break; case 2: { Tfloat p = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,-1), c = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,0), n = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,1); for (int x = 0; x<N - 1; ++x) { ptr[x*off] = (T)(n - 2*c + p); p = c; c = n; n = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,x + 2); } ptr[(N - 1)*off] = (T)(n - 2*c + p); } break; } } static T __cimg_blur_box_apply(T *ptr, const int N, const ulongT off, const bool boundary_conditions, const int x) { if (x<0) return boundary_conditions?ptr[0]:T(); if (x>=N) return boundary_conditions?ptr[(N - 1)*off]:T(); return ptr[x*off]; } // Apply box filter of order 0,1,2. /** \param boxsize Size of the box window (can be subpixel) \param order the order of the filter 0,1 or 2. \param axis Axis along which the filter is computed. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param boundary_conditions Boundary conditions. Can be <tt>{ 0=dirichlet | 1=neumann }</tt>. \param nb_iter Number of filter iterations. **/ CImg<T>& boxfilter(const float boxsize, const int order, const char axis='x', const bool boundary_conditions=true, const unsigned int nb_iter=1) { if (is_empty() || !boxsize || (boxsize<=1 && !order)) return *this; const char naxis = cimg::lowercase(axis); const float nboxsize = boxsize>=0?boxsize:-boxsize* (naxis=='x'?_width:naxis=='y'?_height:naxis=='z'?_depth:_spectrum)/100; switch (naxis) { case 'x' : { cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height*_depth*_spectrum>=16)) cimg_forYZC(*this,y,z,c) _cimg_blur_box_apply(data(0,y,z,c),nboxsize,_width,1U,order,boundary_conditions,nb_iter); } break; case 'y' : { cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height*_depth*_spectrum>=16)) cimg_forXZC(*this,x,z,c) _cimg_blur_box_apply(data(x,0,z,c),nboxsize,_height,(ulongT)_width,order,boundary_conditions,nb_iter); } break; case 'z' : { cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height*_depth*_spectrum>=16)) cimg_forXYC(*this,x,y,c) _cimg_blur_box_apply(data(x,y,0,c),nboxsize,_depth,(ulongT)_width*_height,order,boundary_conditions,nb_iter); } break; default : { cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height*_depth*_spectrum>=16)) cimg_forXYZ(*this,x,y,z) _cimg_blur_box_apply(data(x,y,z,0),nboxsize,_spectrum,(ulongT)_width*_height*_depth, order,boundary_conditions,nb_iter); } } return *this; } // Apply box filter of order 0,1 or 2 \newinstance. CImg<Tfloat> get_boxfilter(const float boxsize, const int order, const char axis='x', const bool boundary_conditions=true, const unsigned int nb_iter=1) const { return CImg<Tfloat>(*this,false).boxfilter(boxsize,order,axis,boundary_conditions,nb_iter); } //! Blur image with a box filter. /** \param boxsize_x Size of the box window, along the X-axis (can be subpixel). \param boxsize_y Size of the box window, along the Y-axis (can be subpixel). \param boxsize_z Size of the box window, along the Z-axis (can be subpixel). \param boundary_conditions Boundary conditions. Can be <tt>{ false=dirichlet | true=neumann }</tt>. \param nb_iter Number of filter iterations. \note - This is a recursive algorithm, not depending on the values of the box kernel size. \see blur(). **/ CImg<T>& blur_box(const float boxsize_x, const float boxsize_y, const float boxsize_z, const bool boundary_conditions=true, const unsigned int nb_iter=1) { if (is_empty()) return *this; if (_width>1) boxfilter(boxsize_x,0,'x',boundary_conditions,nb_iter); if (_height>1) boxfilter(boxsize_y,0,'y',boundary_conditions,nb_iter); if (_depth>1) boxfilter(boxsize_z,0,'z',boundary_conditions,nb_iter); return *this; } //! Blur image with a box filter \newinstance. CImg<Tfloat> get_blur_box(const float boxsize_x, const float boxsize_y, const float boxsize_z, const bool boundary_conditions=true) const { return CImg<Tfloat>(*this,false).blur_box(boxsize_x,boxsize_y,boxsize_z,boundary_conditions); } //! Blur image with a box filter. /** \param boxsize Size of the box window (can be subpixel). \param boundary_conditions Boundary conditions. Can be <tt>{ 0=dirichlet | 1=neumann }</tt>.a \see deriche(), vanvliet(). **/ CImg<T>& blur_box(const float boxsize, const bool boundary_conditions=true) { const float nboxsize = boxsize>=0?boxsize:-boxsize*cimg::max(_width,_height,_depth)/100; return blur_box(nboxsize,nboxsize,nboxsize,boundary_conditions); } //! Blur image with a box filter \newinstance. CImg<Tfloat> get_blur_box(const float boxsize, const bool boundary_conditions=true) const { return CImg<Tfloat>(*this,false).blur_box(boxsize,boundary_conditions); } //! Blur image, with the image guided filter. /** \param guide Image used to guide the smoothing process. \param radius Spatial radius. If negative, it is expressed as a percentage of the largest image size. \param regularization Regularization parameter. If negative, it is expressed as a percentage of the guide value range. \note This method implements the filtering algorithm described in: He, Kaiming; Sun, Jian; Tang, Xiaoou, "Guided Image Filtering," Pattern Analysis and Machine Intelligence, IEEE Transactions on , vol.35, no.6, pp.1397,1409, June 2013 **/ template<typename t> CImg<T>& blur_guided(const CImg<t>& guide, const float radius, const float regularization) { return get_blur_guided(guide,radius,regularization).move_to(*this); } //! Blur image, with the image guided filter \newinstance. template<typename t> CImg<Tfloat> get_blur_guided(const CImg<t>& guide, const float radius, const float regularization) const { if (!is_sameXYZ(guide)) throw CImgArgumentException(_cimg_instance "blur_guided(): Invalid size for specified guide image (%u,%u,%u,%u,%p).", cimg_instance, guide._width,guide._height,guide._depth,guide._spectrum,guide._data); if (is_empty() || !radius) return *this; const int _radius = radius>=0?(int)radius:(int)(-radius*cimg::max(_width,_height,_depth)/100); float _regularization = regularization; if (regularization<0) { T edge_min, edge_max = guide.max_min(edge_min); if (edge_min==edge_max) return *this; _regularization = -regularization*(edge_max - edge_min)/100; } _regularization = std::max(_regularization,0.01f); const unsigned int psize = (unsigned int)(1 + 2*_radius); CImg<Tfloat> mean_p = get_blur_box(psize,true), mean_I = guide.get_blur_box(psize,true).resize(mean_p), cov_Ip = get_mul(guide).blur_box(psize,true)-=mean_p.get_mul(mean_I), var_I = guide.get_sqr().blur_box(psize,true)-=mean_I.get_sqr(), &a = cov_Ip.div(var_I+=_regularization), &b = mean_p-=a.get_mul(mean_I); a.blur_box(psize,true); b.blur_box(psize,true); return a.mul(guide)+=b; } //! Blur image using patch-based space. /** \param sigma_s Amount of blur along the XYZ-axes. \param sigma_p Amount of blur along the value axis. \param patch_size Size of the patches. \param lookup_size Size of the window to search similar patches. \param smoothness Smoothness for the patch comparison. \param is_fast_approx Tells if a fast approximation of the gaussian function is used or not. **/ CImg<T>& blur_patch(const float sigma_s, const float sigma_p, const unsigned int patch_size=3, const unsigned int lookup_size=4, const float smoothness=0, const bool is_fast_approx=true) { if (is_empty() || !patch_size || !lookup_size) return *this; return get_blur_patch(sigma_s,sigma_p,patch_size,lookup_size,smoothness,is_fast_approx).move_to(*this); } //! Blur image using patch-based space \newinstance. CImg<Tfloat> get_blur_patch(const float sigma_s, const float sigma_p, const unsigned int patch_size=3, const unsigned int lookup_size=4, const float smoothness=0, const bool is_fast_approx=true) const { #define _cimg_blur_patch3d_fast(N) \ cimg_for##N##XYZ(res,x,y,z) { \ T *pP = P._data; cimg_forC(res,c) { cimg_get##N##x##N##x##N(img,x,y,z,c,pP,T); pP+=N3; } \ const int x0 = x - rsize1, y0 = y - rsize1, z0 = z - rsize1, \ x1 = x + rsize2, y1 = y + rsize2, z1 = z + rsize2; \ float sum_weights = 0; \ cimg_for_in##N##XYZ(res,x0,y0,z0,x1,y1,z1,p,q,r) \ if (cimg::abs((Tfloat)img(x,y,z,0) - (Tfloat)img(p,q,r,0))<sigma_p3) { \ T *pQ = Q._data; cimg_forC(res,c) { cimg_get##N##x##N##x##N(img,p,q,r,c,pQ,T); pQ+=N3; } \ float distance2 = 0; \ pQ = Q._data; cimg_for(P,_pP,T) { const float dI = (float)*_pP - (float)*(pQ++); distance2+=dI*dI; } \ distance2/=Pnorm; \ const float dx = (float)p - x, dy = (float)q - y, dz = (float)r - z, \ alldist = distance2 + (dx*dx + dy*dy + dz*dz)/sigma_s2, weight = alldist>3?0.f:1.f; \ sum_weights+=weight; \ cimg_forC(res,c) res(x,y,z,c)+=weight*(*this)(p,q,r,c); \ } \ if (sum_weights>0) cimg_forC(res,c) res(x,y,z,c)/=sum_weights; \ else cimg_forC(res,c) res(x,y,z,c) = (Tfloat)((*this)(x,y,z,c)); \ } #define _cimg_blur_patch3d(N) \ cimg_for##N##XYZ(res,x,y,z) { \ T *pP = P._data; cimg_forC(res,c) { cimg_get##N##x##N##x##N(img,x,y,z,c,pP,T); pP+=N3; } \ const int x0 = x - rsize1, y0 = y - rsize1, z0 = z - rsize1, \ x1 = x + rsize2, y1 = y + rsize2, z1 = z + rsize2; \ float sum_weights = 0, weight_max = 0; \ cimg_for_in##N##XYZ(res,x0,y0,z0,x1,y1,z1,p,q,r) if (p!=x || q!=y || r!=z) { \ T *pQ = Q._data; cimg_forC(res,c) { cimg_get##N##x##N##x##N(img,p,q,r,c,pQ,T); pQ+=N3; } \ float distance2 = 0; \ pQ = Q._data; cimg_for(P,_pP,T) { const float dI = (float)*_pP - (float)*(pQ++); distance2+=dI*dI; } \ distance2/=Pnorm; \ const float dx = (float)p - x, dy = (float)q - y, dz = (float)r - z, \ alldist = distance2 + (dx*dx + dy*dy + dz*dz)/sigma_s2, weight = (float)std::exp(-alldist); \ if (weight>weight_max) weight_max = weight; \ sum_weights+=weight; \ cimg_forC(res,c) res(x,y,z,c)+=weight*(*this)(p,q,r,c); \ } \ sum_weights+=weight_max; cimg_forC(res,c) res(x,y,z,c)+=weight_max*(*this)(x,y,z,c); \ if (sum_weights>0) cimg_forC(res,c) res(x,y,z,c)/=sum_weights; \ else cimg_forC(res,c) res(x,y,z,c) = (Tfloat)((*this)(x,y,z,c)); \ } #define _cimg_blur_patch2d_fast(N) \ cimg_for##N##XY(res,x,y) { \ T *pP = P._data; cimg_forC(res,c) { cimg_get##N##x##N(img,x,y,0,c,pP,T); pP+=N2; } \ const int x0 = x - rsize1, y0 = y - rsize1, x1 = x + rsize2, y1 = y + rsize2; \ float sum_weights = 0; \ cimg_for_in##N##XY(res,x0,y0,x1,y1,p,q) \ if (cimg::abs((Tfloat)img(x,y,0,0) - (Tfloat)img(p,q,0,0))<sigma_p3) { \ T *pQ = Q._data; cimg_forC(res,c) { cimg_get##N##x##N(img,p,q,0,c,pQ,T); pQ+=N2; } \ float distance2 = 0; \ pQ = Q._data; cimg_for(P,_pP,T) { const float dI = (float)*_pP - (float)*(pQ++); distance2+=dI*dI; } \ distance2/=Pnorm; \ const float dx = (float)p - x, dy = (float)q - y, \ alldist = distance2 + (dx*dx+dy*dy)/sigma_s2, weight = alldist>3?0.f:1.f; \ sum_weights+=weight; \ cimg_forC(res,c) res(x,y,c)+=weight*(*this)(p,q,c); \ } \ if (sum_weights>0) cimg_forC(res,c) res(x,y,c)/=sum_weights; \ else cimg_forC(res,c) res(x,y,c) = (Tfloat)((*this)(x,y,c)); \ } #define _cimg_blur_patch2d(N) \ cimg_for##N##XY(res,x,y) { \ T *pP = P._data; cimg_forC(res,c) { cimg_get##N##x##N(img,x,y,0,c,pP,T); pP+=N2; } \ const int x0 = x - rsize1, y0 = y - rsize1, x1 = x + rsize2, y1 = y + rsize2; \ float sum_weights = 0, weight_max = 0; \ cimg_for_in##N##XY(res,x0,y0,x1,y1,p,q) if (p!=x || q!=y) { \ T *pQ = Q._data; cimg_forC(res,c) { cimg_get##N##x##N(img,p,q,0,c,pQ,T); pQ+=N2; } \ float distance2 = 0; \ pQ = Q._data; cimg_for(P,_pP,T) { const float dI = (float)*_pP - (float)*(pQ++); distance2+=dI*dI; } \ distance2/=Pnorm; \ const float dx = (float)p - x, dy = (float)q - y, \ alldist = distance2 + (dx*dx+dy*dy)/sigma_s2, weight = (float)std::exp(-alldist); \ if (weight>weight_max) weight_max = weight; \ sum_weights+=weight; \ cimg_forC(res,c) res(x,y,c)+=weight*(*this)(p,q,c); \ } \ sum_weights+=weight_max; cimg_forC(res,c) res(x,y,c)+=weight_max*(*this)(x,y,c); \ if (sum_weights>0) cimg_forC(res,c) res(x,y,c)/=sum_weights; \ else cimg_forC(res,c) res(x,y,c) = (Tfloat)((*this)(x,y,c)); \ } if (is_empty() || !patch_size || !lookup_size) return +*this; CImg<Tfloat> res(_width,_height,_depth,_spectrum,0); const CImg<T> _img = smoothness>0?get_blur(smoothness):CImg<Tfloat>(),&img = smoothness>0?_img:*this; CImg<T> P(patch_size*patch_size*_spectrum), Q(P); const float nsigma_s = sigma_s>=0?sigma_s:-sigma_s*cimg::max(_width,_height,_depth)/100, sigma_s2 = nsigma_s*nsigma_s, sigma_p2 = sigma_p*sigma_p, sigma_p3 = 3*sigma_p, Pnorm = P.size()*sigma_p2; const int rsize2 = (int)lookup_size/2, rsize1 = (int)lookup_size - rsize2 - 1; const unsigned int N2 = patch_size*patch_size, N3 = N2*patch_size; cimg::unused(N2,N3); if (_depth>1) switch (patch_size) { // 3D case 2 : if (is_fast_approx) _cimg_blur_patch3d_fast(2) else _cimg_blur_patch3d(2) break; case 3 : if (is_fast_approx) _cimg_blur_patch3d_fast(3) else _cimg_blur_patch3d(3) break; default : { const int psize2 = (int)patch_size/2, psize1 = (int)patch_size - psize2 - 1; if (is_fast_approx) cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(res._width>=(cimg_openmp_sizefactor)*32 && res._height*res._depth>=4) private(P,Q)) cimg_forXYZ(res,x,y,z) { // Fast P = img.get_crop(x - psize1,y - psize1,z - psize1,x + psize2,y + psize2,z + psize2,true); const int x0 = x - rsize1, y0 = y - rsize1, z0 = z - rsize1, x1 = x + rsize2, y1 = y + rsize2, z1 = z + rsize2; float sum_weights = 0; cimg_for_inXYZ(res,x0,y0,z0,x1,y1,z1,p,q,r) if (cimg::abs((Tfloat)img(x,y,z,0) - (Tfloat)img(p,q,r,0))<sigma_p3) { (Q = img.get_crop(p - psize1,q - psize1,r - psize1,p + psize2,q + psize2,r + psize2,true))-=P; const float dx = (float)x - p, dy = (float)y - q, dz = (float)z - r, distance2 = (float)(Q.pow(2).sum()/Pnorm + (dx*dx + dy*dy + dz*dz)/sigma_s2), weight = distance2>3?0.f:1.f; sum_weights+=weight; cimg_forC(res,c) res(x,y,z,c)+=weight*(*this)(p,q,r,c); } if (sum_weights>0) cimg_forC(res,c) res(x,y,z,c)/=sum_weights; else cimg_forC(res,c) res(x,y,z,c) = (Tfloat)((*this)(x,y,z,c)); } else cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) if (res._width>=32 && res._height*res._depth>=4) firstprivate(P,Q)) cimg_forXYZ(res,x,y,z) { // Exact P = img.get_crop(x - psize1,y - psize1,z - psize1,x + psize2,y + psize2,z + psize2,true); const int x0 = x - rsize1, y0 = y - rsize1, z0 = z - rsize1, x1 = x + rsize2, y1 = y + rsize2, z1 = z + rsize2; float sum_weights = 0, weight_max = 0; cimg_for_inXYZ(res,x0,y0,z0,x1,y1,z1,p,q,r) if (p!=x || q!=y || r!=z) { (Q = img.get_crop(p - psize1,q - psize1,r - psize1,p + psize2,q + psize2,r + psize2,true))-=P; const float dx = (float)x - p, dy = (float)y - q, dz = (float)z - r, distance2 = (float)(Q.pow(2).sum()/Pnorm + (dx*dx + dy*dy + dz*dz)/sigma_s2), weight = (float)std::exp(-distance2); if (weight>weight_max) weight_max = weight; sum_weights+=weight; cimg_forC(res,c) res(x,y,z,c)+=weight*(*this)(p,q,r,c); } sum_weights+=weight_max; cimg_forC(res,c) res(x,y,z,c)+=weight_max*(*this)(x,y,z,c); if (sum_weights>0) cimg_forC(res,c) res(x,y,z,c)/=sum_weights; else cimg_forC(res,c) res(x,y,z,c) = (Tfloat)((*this)(x,y,z,c)); } } } else switch (patch_size) { // 2D case 2 : if (is_fast_approx) _cimg_blur_patch2d_fast(2) else _cimg_blur_patch2d(2) break; case 3 : if (is_fast_approx) _cimg_blur_patch2d_fast(3) else _cimg_blur_patch2d(3) break; case 4 : if (is_fast_approx) _cimg_blur_patch2d_fast(4) else _cimg_blur_patch2d(4) break; case 5 : if (is_fast_approx) _cimg_blur_patch2d_fast(5) else _cimg_blur_patch2d(5) break; case 6 : if (is_fast_approx) _cimg_blur_patch2d_fast(6) else _cimg_blur_patch2d(6) break; case 7 : if (is_fast_approx) _cimg_blur_patch2d_fast(7) else _cimg_blur_patch2d(7) break; case 8 : if (is_fast_approx) _cimg_blur_patch2d_fast(8) else _cimg_blur_patch2d(8) break; case 9 : if (is_fast_approx) _cimg_blur_patch2d_fast(9) else _cimg_blur_patch2d(9) break; default : { // Fast const int psize2 = (int)patch_size/2, psize1 = (int)patch_size - psize2 - 1; if (is_fast_approx) cimg_pragma_openmp(parallel for cimg_openmp_if(res._width>=(cimg_openmp_sizefactor)*32 && res._height>=4) firstprivate(P,Q)) cimg_forXY(res,x,y) { // Fast P = img.get_crop(x - psize1,y - psize1,x + psize2,y + psize2,true); const int x0 = x - rsize1, y0 = y - rsize1, x1 = x + rsize2, y1 = y + rsize2; float sum_weights = 0; cimg_for_inXY(res,x0,y0,x1,y1,p,q) if ((Tfloat)cimg::abs(img(x,y,0) - (Tfloat)img(p,q,0))<sigma_p3) { (Q = img.get_crop(p - psize1,q - psize1,p + psize2,q + psize2,true))-=P; const float dx = (float)x - p, dy = (float)y - q, distance2 = (float)(Q.pow(2).sum()/Pnorm + (dx*dx + dy*dy)/sigma_s2), weight = distance2>3?0.f:1.f; sum_weights+=weight; cimg_forC(res,c) res(x,y,c)+=weight*(*this)(p,q,c); } if (sum_weights>0) cimg_forC(res,c) res(x,y,c)/=sum_weights; else cimg_forC(res,c) res(x,y,c) = (Tfloat)((*this)(x,y,c)); } else cimg_pragma_openmp(parallel for cimg_openmp_if(res._width>=(cimg_openmp_sizefactor)*32 && res._height>=4) firstprivate(P,Q)) cimg_forXY(res,x,y) { // Exact P = img.get_crop(x - psize1,y - psize1,x + psize2,y + psize2,true); const int x0 = x - rsize1, y0 = y - rsize1, x1 = x + rsize2, y1 = y + rsize2; float sum_weights = 0, weight_max = 0; cimg_for_inXY(res,x0,y0,x1,y1,p,q) if (p!=x || q!=y) { (Q = img.get_crop(p - psize1,q - psize1,p + psize2,q + psize2,true))-=P; const float dx = (float)x - p, dy = (float)y - q, distance2 = (float)(Q.pow(2).sum()/Pnorm + (dx*dx + dy*dy)/sigma_s2), weight = (float)std::exp(-distance2); if (weight>weight_max) weight_max = weight; sum_weights+=weight; cimg_forC(res,c) res(x,y,c)+=weight*(*this)(p,q,c); } sum_weights+=weight_max; cimg_forC(res,c) res(x,y,c)+=weight_max*(*this)(x,y,c); if (sum_weights>0) cimg_forC(res,c) res(x,y,c)/=sum_weights; else cimg_forC(res,c) res(x,y,0,c) = (Tfloat)((*this)(x,y,c)); } } } return res; } //! Blur image with the median filter. /** \param n Size of the median filter. \param threshold Threshold used to discard pixels too far from the current pixel value in the median computation. **/ CImg<T>& blur_median(const unsigned int n, const float threshold=0) { if (!n) return *this; return get_blur_median(n,threshold).move_to(*this); } //! Blur image with the median filter \newinstance. CImg<T> get_blur_median(const unsigned int n, const float threshold=0) const { if (is_empty() || n<=1) return +*this; CImg<T> res(_width,_height,_depth,_spectrum); T *ptrd = res._data; cimg::unused(ptrd); const int hr = (int)n/2, hl = n - hr - 1; if (res._depth!=1) { // 3D if (threshold>0) cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*16 && _height*_depth*_spectrum>=4)) cimg_forXYZC(*this,x,y,z,c) { // With threshold const int x0 = x - hl, y0 = y - hl, z0 = z - hl, x1 = x + hr, y1 = y + hr, z1 = z + hr, nx0 = x0<0?0:x0, ny0 = y0<0?0:y0, nz0 = z0<0?0:z0, nx1 = x1>=width()?width() - 1:x1, ny1 = y1>=height()?height() - 1:y1, nz1 = z1>=depth()?depth() - 1:z1; const Tfloat val0 = (Tfloat)(*this)(x,y,z,c); CImg<T> values(n*n*n); unsigned int nb_values = 0; T *_ptrd = values.data(); cimg_for_inXYZ(*this,nx0,ny0,nz0,nx1,ny1,nz1,p,q,r) if (cimg::abs((*this)(p,q,r,c) - val0)<=threshold) { *(_ptrd++) = (*this)(p,q,r,c); ++nb_values; } res(x,y,z,c) = nb_values?values.get_shared_points(0,nb_values - 1).median():(*this)(x,y,z,c); } else cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*16 && _height*_depth*_spectrum>=4)) cimg_forXYZC(*this,x,y,z,c) { // Without threshold const int x0 = x - hl, y0 = y - hl, z0 = z - hl, x1 = x + hr, y1 = y + hr, z1 = z + hr, nx0 = x0<0?0:x0, ny0 = y0<0?0:y0, nz0 = z0<0?0:z0, nx1 = x1>=width()?width() - 1:x1, ny1 = y1>=height()?height() - 1:y1, nz1 = z1>=depth()?depth() - 1:z1; res(x,y,z,c) = get_crop(nx0,ny0,nz0,c,nx1,ny1,nz1,c).median(); } } else { if (threshold>0) cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*16 && _height*_spectrum>=4)) cimg_forXYC(*this,x,y,c) { // With threshold const int x0 = x - hl, y0 = y - hl, x1 = x + hr, y1 = y + hr, nx0 = x0<0?0:x0, ny0 = y0<0?0:y0, nx1 = x1>=width()?width() - 1:x1, ny1 = y1>=height()?height() - 1:y1; const Tfloat val0 = (Tfloat)(*this)(x,y,c); CImg<T> values(n*n); unsigned int nb_values = 0; T *_ptrd = values.data(); cimg_for_inXY(*this,nx0,ny0,nx1,ny1,p,q) if (cimg::abs((*this)(p,q,c) - val0)<=threshold) { *(_ptrd++) = (*this)(p,q,c); ++nb_values; } res(x,y,c) = nb_values?values.get_shared_points(0,nb_values - 1).median():(*this)(x,y,c); } else { const int w1 = width() - 1, h1 = height() - 1, w2 = width() - 2, h2 = height() - 2, w3 = width() - 3, h3 = height() - 3, w4 = width() - 4, h4 = height() - 4; switch (n) { // Without threshold case 3 : { cimg_pragma_openmp(parallel for cimg_openmp_if(_spectrum>=2)) cimg_forC(*this,c) { CImg<T> I(9); cimg_for_in3x3(*this,1,1,w2,h2,x,y,0,c,I,T) res(x,y,c) = cimg::median(I[0],I[1],I[2],I[3],I[4],I[5],I[6],I[7],I[8]); cimg_for_borderXY(*this,x,y,1) res(x,y,c) = get_crop(std::max(0,x - 1),std::max(0,y - 1),0,c, std::min(w1,x + 1),std::min(h1,y + 1),0,c).median(); } } break; case 5 : { cimg_pragma_openmp(parallel for cimg_openmp_if(_spectrum>=2)) cimg_forC(*this,c) { CImg<T> I(25); cimg_for_in5x5(*this,2,2,w3,h3,x,y,0,c,I,T) res(x,y,c) = cimg::median(I[0],I[1],I[2],I[3],I[4], I[5],I[6],I[7],I[8],I[9], I[10],I[11],I[12],I[13],I[14], I[15],I[16],I[17],I[18],I[19], I[20],I[21],I[22],I[23],I[24]); cimg_for_borderXY(*this,x,y,2) res(x,y,c) = get_crop(std::max(0,x - 2),std::max(0,y - 2),0,c, std::min(w1,x + 2),std::min(h1,y + 2),0,c).median(); } } break; case 7 : { cimg_pragma_openmp(parallel for cimg_openmp_if(_spectrum>=2)) cimg_forC(*this,c) { CImg<T> I(49); cimg_for_in7x7(*this,3,3,w4,h4,x,y,0,c,I,T) res(x,y,c) = cimg::median(I[0],I[1],I[2],I[3],I[4],I[5],I[6], I[7],I[8],I[9],I[10],I[11],I[12],I[13], I[14],I[15],I[16],I[17],I[18],I[19],I[20], I[21],I[22],I[23],I[24],I[25],I[26],I[27], I[28],I[29],I[30],I[31],I[32],I[33],I[34], I[35],I[36],I[37],I[38],I[39],I[40],I[41], I[42],I[43],I[44],I[45],I[46],I[47],I[48]); cimg_for_borderXY(*this,x,y,3) res(x,y,c) = get_crop(std::max(0,x - 3),std::max(0,y - 3),0,c, std::min(w1,x + 3),std::min(h1,y + 3),0,c).median(); } } break; default : { cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*16 && _height*_spectrum>=4)) cimg_forXYC(*this,x,y,c) { const int x0 = x - hl, y0 = y - hl, x1 = x + hr, y1 = y + hr, nx0 = x0<0?0:x0, ny0 = y0<0?0:y0, nx1 = x1>=width()?width() - 1:x1, ny1 = y1>=height()?height() - 1:y1; res(x,y,c) = get_crop(nx0,ny0,0,c,nx1,ny1,0,c).median(); } } } } } return res; } //! Sharpen image. /** \param amplitude Sharpening amplitude \param sharpen_type Select sharpening method. Can be <tt>{ false=inverse diffusion | true=shock filters }</tt>. \param edge Edge threshold (shock filters only). \param alpha Gradient smoothness (shock filters only). \param sigma Tensor smoothness (shock filters only). **/ CImg<T>& sharpen(const float amplitude, const bool sharpen_type=false, const float edge=1, const float alpha=0, const float sigma=0) { if (is_empty()) return *this; T val_min, val_max = max_min(val_min); const float nedge = edge/2; CImg<Tfloat> velocity(_width,_height,_depth,_spectrum), _veloc_max(_spectrum); if (_depth>1) { // 3D if (sharpen_type) { // Shock filters CImg<Tfloat> G = (alpha>0?get_blur(alpha).get_structure_tensors():get_structure_tensors()); if (sigma>0) G.blur(sigma); cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*32 && _height*_depth>=16)) cimg_forYZ(G,y,z) { Tfloat *ptrG0 = G.data(0,y,z,0), *ptrG1 = G.data(0,y,z,1), *ptrG2 = G.data(0,y,z,2), *ptrG3 = G.data(0,y,z,3); CImg<Tfloat> val, vec; cimg_forX(G,x) { G.get_tensor_at(x,y,z).symmetric_eigen(val,vec); if (val[0]<0) val[0] = 0; if (val[1]<0) val[1] = 0; if (val[2]<0) val[2] = 0; *(ptrG0++) = vec(0,0); *(ptrG1++) = vec(0,1); *(ptrG2++) = vec(0,2); *(ptrG3++) = 1 - (Tfloat)std::pow(1 + val[0] + val[1] + val[2],-(Tfloat)nedge); } } cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height*_depth>=(cimg_openmp_sizefactor)*512 && _spectrum>=2)) cimg_forC(*this,c) { Tfloat *ptrd = velocity.data(0,0,0,c), veloc_max = 0; CImg_3x3x3(I,Tfloat); cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) { const Tfloat u = G(x,y,z,0), v = G(x,y,z,1), w = G(x,y,z,2), amp = G(x,y,z,3), ixx = Incc + Ipcc - 2*Iccc, ixy = (Innc + Ippc - Inpc - Ipnc)/4, ixz = (Incn + Ipcp - Incp - Ipcn)/4, iyy = Icnc + Icpc - 2*Iccc, iyz = (Icnn + Icpp - Icnp - Icpn)/4, izz = Iccn + Iccp - 2*Iccc, ixf = Incc - Iccc, ixb = Iccc - Ipcc, iyf = Icnc - Iccc, iyb = Iccc - Icpc, izf = Iccn - Iccc, izb = Iccc - Iccp, itt = u*u*ixx + v*v*iyy + w*w*izz + 2*u*v*ixy + 2*u*w*ixz + 2*v*w*iyz, it = u*cimg::minmod(ixf,ixb) + v*cimg::minmod(iyf,iyb) + w*cimg::minmod(izf,izb), veloc = -amp*cimg::sign(itt)*cimg::abs(it); *(ptrd++) = veloc; if (veloc>veloc_max) veloc_max = veloc; else if (-veloc>veloc_max) veloc_max = -veloc; } _veloc_max[c] = veloc_max; } } else // Inverse diffusion cimg_forC(*this,c) { Tfloat *ptrd = velocity.data(0,0,0,c), veloc_max = 0; CImg_3x3x3(I,Tfloat); cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) { const Tfloat veloc = -Ipcc - Incc - Icpc - Icnc - Iccp - Iccn + 6*Iccc; *(ptrd++) = veloc; if (veloc>veloc_max) veloc_max = veloc; else if (-veloc>veloc_max) veloc_max = -veloc; } _veloc_max[c] = veloc_max; } } else { // 2D if (sharpen_type) { // Shock filters CImg<Tfloat> G = (alpha>0?get_blur(alpha).get_structure_tensors():get_structure_tensors()); if (sigma>0) G.blur(sigma); cimg_pragma_openmp(parallel for cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*32 && _height>=(cimg_openmp_sizefactor)*16)) cimg_forY(G,y) { CImg<Tfloat> val, vec; Tfloat *ptrG0 = G.data(0,y,0,0), *ptrG1 = G.data(0,y,0,1), *ptrG2 = G.data(0,y,0,2); cimg_forX(G,x) { G.get_tensor_at(x,y).symmetric_eigen(val,vec); if (val[0]<0) val[0] = 0; if (val[1]<0) val[1] = 0; *(ptrG0++) = vec(0,0); *(ptrG1++) = vec(0,1); *(ptrG2++) = 1 - (Tfloat)std::pow(1 + val[0] + val[1],-(Tfloat)nedge); } } cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height>=(cimg_openmp_sizefactor)*512 && _spectrum>=2)) cimg_forC(*this,c) { Tfloat *ptrd = velocity.data(0,0,0,c), veloc_max = 0; CImg_3x3(I,Tfloat); cimg_for3x3(*this,x,y,0,c,I,Tfloat) { const Tfloat u = G(x,y,0), v = G(x,y,1), amp = G(x,y,2), ixx = Inc + Ipc - 2*Icc, ixy = (Inn + Ipp - Inp - Ipn)/4, iyy = Icn + Icp - 2*Icc, ixf = Inc - Icc, ixb = Icc - Ipc, iyf = Icn - Icc, iyb = Icc - Icp, itt = u*u*ixx + v*v*iyy + 2*u*v*ixy, it = u*cimg::minmod(ixf,ixb) + v*cimg::minmod(iyf,iyb), veloc = -amp*cimg::sign(itt)*cimg::abs(it); *(ptrd++) = veloc; if (veloc>veloc_max) veloc_max = veloc; else if (-veloc>veloc_max) veloc_max = -veloc; } _veloc_max[c] = veloc_max; } } else // Inverse diffusion cimg_forC(*this,c) { Tfloat *ptrd = velocity.data(0,0,0,c), veloc_max = 0; CImg_3x3(I,Tfloat); cimg_for3x3(*this,x,y,0,c,I,Tfloat) { const Tfloat veloc = -Ipc - Inc - Icp - Icn + 4*Icc; *(ptrd++) = veloc; if (veloc>veloc_max) veloc_max = veloc; else if (-veloc>veloc_max) veloc_max = -veloc; } _veloc_max[c] = veloc_max; } } const Tfloat veloc_max = _veloc_max.max(); if (veloc_max<=0) return *this; return ((velocity*=amplitude/veloc_max)+=*this).cut(val_min,val_max).move_to(*this); } //! Sharpen image \newinstance. CImg<T> get_sharpen(const float amplitude, const bool sharpen_type=false, const float edge=1, const float alpha=0, const float sigma=0) const { return (+*this).sharpen(amplitude,sharpen_type,edge,alpha,sigma); } //! Return image gradient. /** \param axes Axes considered for the gradient computation, as a C-string (e.g "xy"). \param scheme = Numerical scheme used for the gradient computation: - -1 = Backward finite differences - 0 = Centered finite differences - 1 = Forward finite differences - 2 = Using Sobel kernels - 3 = Using rotation invariant kernels - 4 = Using Deriche recusrsive filter. - 5 = Using Van Vliet recusrsive filter. **/ CImgList<Tfloat> get_gradient(const char *const axes=0, const int scheme=3) const { CImgList<Tfloat> grad(2,_width,_height,_depth,_spectrum); bool is_3d = false; if (axes) { for (unsigned int a = 0; axes[a]; ++a) { const char axis = cimg::lowercase(axes[a]); switch (axis) { case 'x' : case 'y' : break; case 'z' : is_3d = true; break; default : throw CImgArgumentException(_cimg_instance "get_gradient(): Invalid specified axis '%c'.", cimg_instance, axis); } } } else is_3d = (_depth>1); if (is_3d) { CImg<Tfloat>(_width,_height,_depth,_spectrum).move_to(grad); switch (scheme) { // 3D case -1 : { // Backward finite differences cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height*_depth>=(cimg_openmp_sizefactor)*1048576 && _spectrum>=2)) cimg_forC(*this,c) { const ulongT off = (ulongT)c*_width*_height*_depth; Tfloat *ptrd0 = grad[0]._data + off, *ptrd1 = grad[1]._data + off, *ptrd2 = grad[2]._data + off; CImg_3x3x3(I,Tfloat); cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = Iccc - Ipcc; *(ptrd1++) = Iccc - Icpc; *(ptrd2++) = Iccc - Iccp; } } } break; case 1 : { // Forward finite differences cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height*_depth>=(cimg_openmp_sizefactor)*1048576 && _spectrum>=2)) cimg_forC(*this,c) { const ulongT off = (ulongT)c*_width*_height*_depth; Tfloat *ptrd0 = grad[0]._data + off, *ptrd1 = grad[1]._data + off, *ptrd2 = grad[2]._data + off; CImg_2x2x2(I,Tfloat); cimg_for2x2x2(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = Incc - Iccc; *(ptrd1++) = Icnc - Iccc; *(ptrd2++) = Iccn - Iccc; } } } break; case 4 : { // Deriche filter with low standard variation grad[0] = get_deriche(0,1,'x'); grad[1] = get_deriche(0,1,'y'); grad[2] = get_deriche(0,1,'z'); } break; case 5 : { // Van Vliet filter with low standard variation grad[0] = get_vanvliet(0,1,'x'); grad[1] = get_vanvliet(0,1,'y'); grad[2] = get_vanvliet(0,1,'z'); } break; default : { // Central finite differences cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height*_depth>=(cimg_openmp_sizefactor)*1048576 && _spectrum>=2)) cimg_forC(*this,c) { const ulongT off = (ulongT)c*_width*_height*_depth; Tfloat *ptrd0 = grad[0]._data + off, *ptrd1 = grad[1]._data + off, *ptrd2 = grad[2]._data + off; CImg_3x3x3(I,Tfloat); cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = (Incc - Ipcc)/2; *(ptrd1++) = (Icnc - Icpc)/2; *(ptrd2++) = (Iccn - Iccp)/2; } } } } } else switch (scheme) { // 2D case -1 : { // Backward finite differences cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width*_height>=(cimg_openmp_sizefactor)*1048576 && _depth*_spectrum>=2)) cimg_forZC(*this,z,c) { const ulongT off = (ulongT)c*_width*_height*_depth + z*_width*_height; Tfloat *ptrd0 = grad[0]._data + off, *ptrd1 = grad[1]._data + off; CImg_3x3(I,Tfloat); cimg_for3x3(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = Icc - Ipc; *(ptrd1++) = Icc - Icp; } } } break; case 1 : { // Forward finite differences cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width*_height>=(cimg_openmp_sizefactor)*1048576 && _depth*_spectrum>=2)) cimg_forZC(*this,z,c) { const ulongT off = (ulongT)c*_width*_height*_depth + z*_width*_height; Tfloat *ptrd0 = grad[0]._data + off, *ptrd1 = grad[1]._data + off; CImg_2x2(I,Tfloat); cimg_for2x2(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = Inc - Icc; *(ptrd1++) = Icn - Icc; } } } break; case 2 : { // Sobel scheme cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width*_height>=(cimg_openmp_sizefactor)*1048576 && _depth*_spectrum>=2)) cimg_forZC(*this,z,c) { const ulongT off = (ulongT)c*_width*_height*_depth + z*_width*_height; Tfloat *ptrd0 = grad[0]._data + off, *ptrd1 = grad[1]._data + off; CImg_3x3(I,Tfloat); cimg_for3x3(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = -Ipp - 2*Ipc - Ipn + Inp + 2*Inc + Inn; *(ptrd1++) = -Ipp - 2*Icp - Inp + Ipn + 2*Icn + Inn; } } } break; case 3 : { // Rotation invariant kernel cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width*_height>=(cimg_openmp_sizefactor)*1048576 && _depth*_spectrum>=2)) cimg_forZC(*this,z,c) { const ulongT off = (ulongT)c*_width*_height*_depth + z*_width*_height; Tfloat *ptrd0 = grad[0]._data + off, *ptrd1 = grad[1]._data + off; CImg_3x3(I,Tfloat); const Tfloat a = (Tfloat)(0.25f*(2 - std::sqrt(2.f))), b = (Tfloat)(0.5f*(std::sqrt(2.f) - 1)); cimg_for3x3(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = -a*Ipp - b*Ipc - a*Ipn + a*Inp + b*Inc + a*Inn; *(ptrd1++) = -a*Ipp - b*Icp - a*Inp + a*Ipn + b*Icn + a*Inn; } } } break; case 4 : { // Van Vliet filter with low standard variation grad[0] = get_deriche(0,1,'x'); grad[1] = get_deriche(0,1,'y'); } break; case 5 : { // Deriche filter with low standard variation grad[0] = get_vanvliet(0,1,'x'); grad[1] = get_vanvliet(0,1,'y'); } break; default : { // Central finite differences cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width*_height>=(cimg_openmp_sizefactor)*1048576 && _depth*_spectrum>=2)) cimg_forZC(*this,z,c) { const ulongT off = (ulongT)c*_width*_height*_depth + z*_width*_height; Tfloat *ptrd0 = grad[0]._data + off, *ptrd1 = grad[1]._data + off; CImg_3x3(I,Tfloat); cimg_for3x3(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = (Inc - Ipc)/2; *(ptrd1++) = (Icn - Icp)/2; } } } } if (!axes) return grad; CImgList<Tfloat> res; for (unsigned int l = 0; axes[l]; ++l) { const char axis = cimg::lowercase(axes[l]); switch (axis) { case 'x' : res.insert(grad[0]); break; case 'y' : res.insert(grad[1]); break; case 'z' : res.insert(grad[2]); break; } } grad.assign(); return res; } //! Return image hessian. /** \param axes Axes considered for the hessian computation, as a C-string (e.g "xy"). **/ CImgList<Tfloat> get_hessian(const char *const axes=0) const { CImgList<Tfloat> res; const char *naxes = axes, *const def_axes2d = "xxxyyy", *const def_axes3d = "xxxyxzyyyzzz"; if (!axes) naxes = _depth>1?def_axes3d:def_axes2d; const unsigned int lmax = (unsigned int)std::strlen(naxes); if (lmax%2) throw CImgArgumentException(_cimg_instance "get_hessian(): Invalid specified axes '%s'.", cimg_instance, naxes); res.assign(lmax/2,_width,_height,_depth,_spectrum); if (!cimg::strcasecmp(naxes,def_axes3d)) { // 3D cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height*_depth>=(cimg_openmp_sizefactor)*1048576 && _spectrum>=2)) cimg_forC(*this,c) { const ulongT off = (ulongT)c*_width*_height*_depth; Tfloat *ptrd0 = res[0]._data + off, *ptrd1 = res[1]._data + off, *ptrd2 = res[2]._data + off, *ptrd3 = res[3]._data + off, *ptrd4 = res[4]._data + off, *ptrd5 = res[5]._data + off; CImg_3x3x3(I,Tfloat); cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = Ipcc + Incc - 2*Iccc; // Ixx *(ptrd1++) = (Ippc + Innc - Ipnc - Inpc)/4; // Ixy *(ptrd2++) = (Ipcp + Incn - Ipcn - Incp)/4; // Ixz *(ptrd3++) = Icpc + Icnc - 2*Iccc; // Iyy *(ptrd4++) = (Icpp + Icnn - Icpn - Icnp)/4; // Iyz *(ptrd5++) = Iccn + Iccp - 2*Iccc; // Izz } } } else if (!cimg::strcasecmp(naxes,def_axes2d)) { // 2D cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width*_height>=(cimg_openmp_sizefactor)*1048576 && _depth*_spectrum>=2)) cimg_forZC(*this,z,c) { const ulongT off = (ulongT)c*_width*_height*_depth + z*_width*_height; Tfloat *ptrd0 = res[0]._data + off, *ptrd1 = res[1]._data + off, *ptrd2 = res[2]._data + off; CImg_3x3(I,Tfloat); cimg_for3x3(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = Ipc + Inc - 2*Icc; // Ixx *(ptrd1++) = (Ipp + Inn - Ipn - Inp)/4; // Ixy *(ptrd2++) = Icp + Icn - 2*Icc; // Iyy } } } else for (unsigned int l = 0; l<lmax; ) { // Version with custom axes const unsigned int l2 = l/2; char axis1 = naxes[l++], axis2 = naxes[l++]; if (axis1>axis2) cimg::swap(axis1,axis2); bool valid_axis = false; if (axis1=='x' && axis2=='x') { // Ixx valid_axis = true; cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width*_height>=(cimg_openmp_sizefactor)*1048576 && _depth*_spectrum>=2)) cimg_forZC(*this,z,c) { Tfloat *ptrd = res[l2].data(0,0,z,c); CImg_3x3(I,Tfloat); cimg_for3x3(*this,x,y,z,c,I,Tfloat) *(ptrd++) = Ipc + Inc - 2*Icc; } } else if (axis1=='x' && axis2=='y') { // Ixy valid_axis = true; cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width*_height>=(cimg_openmp_sizefactor)*1048576 && _depth*_spectrum>=2)) cimg_forZC(*this,z,c) { Tfloat *ptrd = res[l2].data(0,0,z,c); CImg_3x3(I,Tfloat); cimg_for3x3(*this,x,y,z,c,I,Tfloat) *(ptrd++) = (Ipp + Inn - Ipn - Inp)/4; } } else if (axis1=='x' && axis2=='z') { // Ixz valid_axis = true; cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height*_depth>=(cimg_openmp_sizefactor)*1048576 && _spectrum>=2)) cimg_forC(*this,c) { Tfloat *ptrd = res[l2].data(0,0,0,c); CImg_3x3x3(I,Tfloat); cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) *(ptrd++) = (Ipcp + Incn - Ipcn - Incp)/4; } } else if (axis1=='y' && axis2=='y') { // Iyy valid_axis = true; cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width*_height>=(cimg_openmp_sizefactor)*1048576 && _depth*_spectrum>=2)) cimg_forZC(*this,z,c) { Tfloat *ptrd = res[l2].data(0,0,z,c); CImg_3x3(I,Tfloat); cimg_for3x3(*this,x,y,z,c,I,Tfloat) *(ptrd++) = Icp + Icn - 2*Icc; } } else if (axis1=='y' && axis2=='z') { // Iyz valid_axis = true; cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height*_depth>=(cimg_openmp_sizefactor)*1048576 && _spectrum>=2)) cimg_forC(*this,c) { Tfloat *ptrd = res[l2].data(0,0,0,c); CImg_3x3x3(I,Tfloat); cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) *(ptrd++) = (Icpp + Icnn - Icpn - Icnp)/4; } } else if (axis1=='z' && axis2=='z') { // Izz valid_axis = true; cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height*_depth>=(cimg_openmp_sizefactor)*1048576 && _spectrum>=2)) cimg_forC(*this,c) { Tfloat *ptrd = res[l2].data(0,0,0,c); CImg_3x3x3(I,Tfloat); cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) *(ptrd++) = Iccn + Iccp - 2*Iccc; } } else if (!valid_axis) throw CImgArgumentException(_cimg_instance "get_hessian(): Invalid specified axes '%s'.", cimg_instance, naxes); } return res; } //! Compute image Laplacian. CImg<T>& laplacian() { return get_laplacian().move_to(*this); } //! Compute image Laplacian \newinstance. CImg<Tfloat> get_laplacian() const { if (is_empty()) return CImg<Tfloat>(); CImg<Tfloat> res(_width,_height,_depth,_spectrum); if (_depth>1) { // 3D cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height*_depth>=(cimg_openmp_sizefactor)*1048576 && _spectrum>=2)) cimg_forC(*this,c) { Tfloat *ptrd = res.data(0,0,0,c); CImg_3x3x3(I,Tfloat); cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) *(ptrd++) = Incc + Ipcc + Icnc + Icpc + Iccn + Iccp - 6*Iccc; } } else if (_height>1) { // 2D cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height>=(cimg_openmp_sizefactor)*1048576 && _depth*_spectrum>=2)) cimg_forC(*this,c) { Tfloat *ptrd = res.data(0,0,0,c); CImg_3x3(I,Tfloat); cimg_for3x3(*this,x,y,0,c,I,Tfloat) *(ptrd++) = Inc + Ipc + Icn + Icp - 4*Icc; } } else { // 1D cimg_pragma_openmp(parallel for cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*1048576 && _height*_depth*_spectrum>=2)) cimg_forC(*this,c) { Tfloat *ptrd = res.data(0,0,0,c); CImg_3x3(I,Tfloat); cimg_for3x3(*this,x,y,0,c,I,Tfloat) *(ptrd++) = Inc + Ipc - 2*Icc; } } return res; } //! Compute the structure tensor field of an image. /** \param is_fwbw_scheme scheme. Can be <tt>{ false=centered | true=forward-backward }</tt> **/ CImg<T>& structure_tensors(const bool is_fwbw_scheme=false) { return get_structure_tensors(is_fwbw_scheme).move_to(*this); } //! Compute the structure tensor field of an image \newinstance. CImg<Tfloat> get_structure_tensors(const bool is_fwbw_scheme=false) const { if (is_empty()) return *this; CImg<Tfloat> res; if (_depth>1) { // 3D res.assign(_width,_height,_depth,6,0); if (!is_fwbw_scheme) { // Classical central finite differences cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height*_depth>=(cimg_openmp_sizefactor)*1048576 && _spectrum>=2)) cimg_forC(*this,c) { Tfloat *ptrd0 = res.data(0,0,0,0), *ptrd1 = res.data(0,0,0,1), *ptrd2 = res.data(0,0,0,2), *ptrd3 = res.data(0,0,0,3), *ptrd4 = res.data(0,0,0,4), *ptrd5 = res.data(0,0,0,5); CImg_3x3x3(I,Tfloat); cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) { const Tfloat ix = (Incc - Ipcc)/2, iy = (Icnc - Icpc)/2, iz = (Iccn - Iccp)/2; *(ptrd0++)+=ix*ix; *(ptrd1++)+=ix*iy; *(ptrd2++)+=ix*iz; *(ptrd3++)+=iy*iy; *(ptrd4++)+=iy*iz; *(ptrd5++)+=iz*iz; } } } else { // Forward/backward finite differences cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height*_depth>=(cimg_openmp_sizefactor)*1048576 && _spectrum>=2)) cimg_forC(*this,c) { Tfloat *ptrd0 = res.data(0,0,0,0), *ptrd1 = res.data(0,0,0,1), *ptrd2 = res.data(0,0,0,2), *ptrd3 = res.data(0,0,0,3), *ptrd4 = res.data(0,0,0,4), *ptrd5 = res.data(0,0,0,5); CImg_3x3x3(I,Tfloat); cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) { const Tfloat ixf = Incc - Iccc, ixb = Iccc - Ipcc, iyf = Icnc - Iccc, iyb = Iccc - Icpc, izf = Iccn - Iccc, izb = Iccc - Iccp; *(ptrd0++)+=(ixf*ixf + ixb*ixb)/2; *(ptrd1++)+=(ixf*iyf + ixf*iyb + ixb*iyf + ixb*iyb)/4; *(ptrd2++)+=(ixf*izf + ixf*izb + ixb*izf + ixb*izb)/4; *(ptrd3++)+=(iyf*iyf + iyb*iyb)/2; *(ptrd4++)+=(iyf*izf + iyf*izb + iyb*izf + iyb*izb)/4; *(ptrd5++)+=(izf*izf + izb*izb)/2; } } } } else { // 2D res.assign(_width,_height,_depth,3,0); if (!is_fwbw_scheme) { // Classical central finite differences cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height>=(cimg_openmp_sizefactor)*1048576 && _depth*_spectrum>=2)) cimg_forC(*this,c) { Tfloat *ptrd0 = res.data(0,0,0,0), *ptrd1 = res.data(0,0,0,1), *ptrd2 = res.data(0,0,0,2); CImg_3x3(I,Tfloat); cimg_for3x3(*this,x,y,0,c,I,Tfloat) { const Tfloat ix = (Inc - Ipc)/2, iy = (Icn - Icp)/2; *(ptrd0++)+=ix*ix; *(ptrd1++)+=ix*iy; *(ptrd2++)+=iy*iy; } } } else { // Forward/backward finite differences (version 2) cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height>=(cimg_openmp_sizefactor)*1048576 && _depth*_spectrum>=2)) cimg_forC(*this,c) { Tfloat *ptrd0 = res.data(0,0,0,0), *ptrd1 = res.data(0,0,0,1), *ptrd2 = res.data(0,0,0,2); CImg_3x3(I,Tfloat); cimg_for3x3(*this,x,y,0,c,I,Tfloat) { const Tfloat ixf = Inc - Icc, ixb = Icc - Ipc, iyf = Icn - Icc, iyb = Icc - Icp; *(ptrd0++)+=(ixf*ixf + ixb*ixb)/2; *(ptrd1++)+=(ixf*iyf + ixf*iyb + ixb*iyf + ixb*iyb)/4; *(ptrd2++)+=(iyf*iyf + iyb*iyb)/2; } } } } return res; } //! Compute field of diffusion tensors for edge-preserving smoothing. /** \param sharpness Sharpness \param anisotropy Anisotropy \param alpha Standard deviation of the gradient blur. \param sigma Standard deviation of the structure tensor blur. \param is_sqrt Tells if the square root of the tensor field is computed instead. **/ CImg<T>& diffusion_tensors(const float sharpness=0.7f, const float anisotropy=0.6f, const float alpha=0.6f, const float sigma=1.1f, const bool is_sqrt=false) { CImg<Tfloat> res; const float nsharpness = std::max(sharpness,1e-5f), power1 = (is_sqrt?0.5f:1)*nsharpness, power2 = power1/(1e-7f + 1 - anisotropy); blur(alpha).normalize(0,(T)255); if (_depth>1) { // 3D get_structure_tensors().move_to(res).blur(sigma); cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height*_depth>=(cimg_openmp_sizefactor)*256)) cimg_forYZ(*this,y,z) { Tfloat *ptrd0 = res.data(0,y,z,0), *ptrd1 = res.data(0,y,z,1), *ptrd2 = res.data(0,y,z,2), *ptrd3 = res.data(0,y,z,3), *ptrd4 = res.data(0,y,z,4), *ptrd5 = res.data(0,y,z,5); CImg<floatT> val(3), vec(3,3); cimg_forX(*this,x) { res.get_tensor_at(x,y,z).symmetric_eigen(val,vec); const float _l1 = val[2], _l2 = val[1], _l3 = val[0], l1 = _l1>0?_l1:0, l2 = _l2>0?_l2:0, l3 = _l3>0?_l3:0, ux = vec(0,0), uy = vec(0,1), uz = vec(0,2), vx = vec(1,0), vy = vec(1,1), vz = vec(1,2), wx = vec(2,0), wy = vec(2,1), wz = vec(2,2), n1 = (float)std::pow(1 + l1 + l2 + l3,-power1), n2 = (float)std::pow(1 + l1 + l2 + l3,-power2); *(ptrd0++) = n1*(ux*ux + vx*vx) + n2*wx*wx; *(ptrd1++) = n1*(ux*uy + vx*vy) + n2*wx*wy; *(ptrd2++) = n1*(ux*uz + vx*vz) + n2*wx*wz; *(ptrd3++) = n1*(uy*uy + vy*vy) + n2*wy*wy; *(ptrd4++) = n1*(uy*uz + vy*vz) + n2*wy*wz; *(ptrd5++) = n1*(uz*uz + vz*vz) + n2*wz*wz; } } } else { // for 2D images get_structure_tensors().move_to(res).blur(sigma); cimg_pragma_openmp(parallel for cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height>=(cimg_openmp_sizefactor)*256)) cimg_forY(*this,y) { Tfloat *ptrd0 = res.data(0,y,0,0), *ptrd1 = res.data(0,y,0,1), *ptrd2 = res.data(0,y,0,2); CImg<floatT> val(2), vec(2,2); cimg_forX(*this,x) { res.get_tensor_at(x,y).symmetric_eigen(val,vec); const float _l1 = val[1], _l2 = val[0], l1 = _l1>0?_l1:0, l2 = _l2>0?_l2:0, ux = vec(1,0), uy = vec(1,1), vx = vec(0,0), vy = vec(0,1), n1 = (float)std::pow(1 + l1 + l2,-power1), n2 = (float)std::pow(1 + l1 + l2,-power2); *(ptrd0++) = n1*ux*ux + n2*vx*vx; *(ptrd1++) = n1*ux*uy + n2*vx*vy; *(ptrd2++) = n1*uy*uy + n2*vy*vy; } } } return res.move_to(*this); } //! Compute field of diffusion tensors for edge-preserving smoothing \newinstance. CImg<Tfloat> get_diffusion_tensors(const float sharpness=0.7f, const float anisotropy=0.6f, const float alpha=0.6f, const float sigma=1.1f, const bool is_sqrt=false) const { return CImg<Tfloat>(*this,false).diffusion_tensors(sharpness,anisotropy,alpha,sigma,is_sqrt); } //! Estimate displacement field between two images. /** \param source Reference image. \param smoothness Smoothness of estimated displacement field. \param precision Precision required for algorithm convergence. \param nb_scales Number of scales used to estimate the displacement field. \param iteration_max Maximum number of iterations allowed for one scale. \param is_backward If false, match I2(X + U(X)) = I1(X), else match I2(X) = I1(X - U(X)). \param guide Image used as the initial correspondence estimate for the algorithm. 'guide' may have a last channel with boolean values (0=false | other=true) that tells for each pixel if its correspondence vector is constrained to its initial value (constraint mask). **/ CImg<T>& displacement(const CImg<T>& source, const float smoothness=0.1f, const float precision=5.f, const unsigned int nb_scales=0, const unsigned int iteration_max=10000, const bool is_backward=false, const CImg<floatT>& guide=CImg<floatT>::const_empty()) { return get_displacement(source,smoothness,precision,nb_scales,iteration_max,is_backward,guide). move_to(*this); } //! Estimate displacement field between two images \newinstance. CImg<floatT> get_displacement(const CImg<T>& source, const float smoothness=0.1f, const float precision=5.f, const unsigned int nb_scales=0, const unsigned int iteration_max=10000, const bool is_backward=false, const CImg<floatT>& guide=CImg<floatT>::const_empty()) const { if (is_empty() || !source) return +*this; if (!is_sameXYZC(source)) throw CImgArgumentException(_cimg_instance "displacement(): Instance and source image (%u,%u,%u,%u,%p) have " "different dimensions.", cimg_instance, source._width,source._height,source._depth,source._spectrum,source._data); if (precision<0) throw CImgArgumentException(_cimg_instance "displacement(): Invalid specified precision %g " "(should be >=0)", cimg_instance, precision); const bool is_3d = source._depth>1; const unsigned int constraint = is_3d?3:2; if (guide && (guide._width!=_width || guide._height!=_height || guide._depth!=_depth || guide._spectrum<constraint)) throw CImgArgumentException(_cimg_instance "displacement(): Specified guide (%u,%u,%u,%u,%p) " "has invalid dimensions.", cimg_instance, guide._width,guide._height,guide._depth,guide._spectrum,guide._data); const unsigned int mins = is_3d?cimg::min(_width,_height,_depth):std::min(_width,_height), _nb_scales = nb_scales>0?nb_scales: (unsigned int)cimg::round(std::log(mins/8.)/std::log(1.5),1,1); const float _precision = (float)std::pow(10.,-(double)precision); float sm, sM = source.max_min(sm), tm, tM = max_min(tm); const float sdelta = sm==sM?1:(sM - sm), tdelta = tm==tM?1:(tM - tm); CImg<floatT> U, V; floatT bound = 0; for (int scale = (int)_nb_scales - 1; scale>=0; --scale) { const float factor = (float)std::pow(1.5,(double)scale); const unsigned int _sw = (unsigned int)(_width/factor), sw = _sw?_sw:1, _sh = (unsigned int)(_height/factor), sh = _sh?_sh:1, _sd = (unsigned int)(_depth/factor), sd = _sd?_sd:1; if (sw<5 && sh<5 && (!is_3d || sd<5)) continue; // Skip too small scales const CImg<Tfloat> I1 = (source.get_resize(sw,sh,sd,-100,2)-=sm)/=sdelta, I2 = (get_resize(I1,2)-=tm)/=tdelta; if (guide._spectrum>constraint) guide.get_resize(I2._width,I2._height,I2._depth,-100,1).move_to(V); if (U) (U*=1.5f).resize(I2._width,I2._height,I2._depth,-100,3); else { if (guide) guide.get_shared_channels(0,is_3d?2:1).get_resize(I2._width,I2._height,I2._depth,-100,2).move_to(U); else U.assign(I2._width,I2._height,I2._depth,is_3d?3:2,0); } float dt = 2, energy = cimg::type<float>::max(); const CImgList<Tfloat> dI = is_backward?I1.get_gradient():I2.get_gradient(); cimg_abort_init; for (unsigned int iteration = 0; iteration<iteration_max; ++iteration) { cimg_abort_test; float _energy = 0; if (is_3d) { // 3D version if (smoothness>=0) // Isotropic regularization cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_height*_depth>=(cimg_openmp_sizefactor)*8 && _width>=(cimg_openmp_sizefactor)*16) reduction(+:_energy)) cimg_forYZ(U,y,z) { const int _p1y = y?y - 1:0, _n1y = y<U.height() - 1?y + 1:y, _p1z = z?z - 1:0, _n1z = z<U.depth() - 1?z + 1:z; cimg_for3X(U,x) { const float X = is_backward?x - U(x,y,z,0):x + U(x,y,z,0), Y = is_backward?y - U(x,y,z,1):y + U(x,y,z,1), Z = is_backward?z - U(x,y,z,2):z + U(x,y,z,2); float delta_I = 0, _energy_regul = 0; if (is_backward) cimg_forC(I2,c) delta_I+=(float)(I1._linear_atXYZ(X,Y,Z,c) - I2(x,y,z,c)); else cimg_forC(I2,c) delta_I+=(float)(I1(x,y,z,c) - I2._linear_atXYZ(X,Y,Z,c)); cimg_forC(U,c) { const float Ux = 0.5f*(U(_n1x,y,z,c) - U(_p1x,y,z,c)), Uy = 0.5f*(U(x,_n1y,z,c) - U(x,_p1y,z,c)), Uz = 0.5f*(U(x,y,_n1z,c) - U(x,y,_p1z,c)), Uxx = U(_n1x,y,z,c) + U(_p1x,y,z,c), Uyy = U(x,_n1y,z,c) + U(x,_p1y,z,c), Uzz = U(x,y,_n1z,c) + U(x,y,_p1z,c); U(x,y,z,c) = (float)(U(x,y,z,c) + dt*(delta_I*dI[c]._linear_atXYZ(X,Y,Z) + smoothness* ( Uxx + Uyy + Uzz)))/(1 + 6*smoothness*dt); _energy_regul+=Ux*Ux + Uy*Uy + Uz*Uz; } if (is_backward) { // Constraint displacement vectors to stay in image if (U(x,y,z,0)>x) U(x,y,z,0) = (float)x; if (U(x,y,z,1)>y) U(x,y,z,1) = (float)y; if (U(x,y,z,2)>z) U(x,y,z,2) = (float)z; bound = (float)x - _width; if (U(x,y,z,0)<=bound) U(x,y,z,0) = bound; bound = (float)y - _height; if (U(x,y,z,1)<=bound) U(x,y,z,1) = bound; bound = (float)z - _depth; if (U(x,y,z,2)<=bound) U(x,y,z,2) = bound; } else { if (U(x,y,z,0)<-x) U(x,y,z,0) = -(float)x; if (U(x,y,z,1)<-y) U(x,y,z,1) = -(float)y; if (U(x,y,z,2)<-z) U(x,y,z,2) = -(float)z; bound = (float)_width - x; if (U(x,y,z,0)>=bound) U(x,y,z,0) = bound; bound = (float)_height - y; if (U(x,y,z,1)>=bound) U(x,y,z,1) = bound; bound = (float)_depth - z; if (U(x,y,z,2)>=bound) U(x,y,z,2) = bound; } _energy+=delta_I*delta_I + smoothness*_energy_regul; } if (V) cimg_forXYZ(V,_x,_y,_z) if (V(_x,_y,_z,3)) { // Apply constraints U(_x,_y,_z,0) = V(_x,_y,_z,0)/factor; U(_x,_y,_z,1) = V(_x,_y,_z,1)/factor; U(_x,_y,_z,2) = V(_x,_y,_z,2)/factor; } } else { // Anisotropic regularization const float nsmoothness = -smoothness; cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_height*_depth>=(cimg_openmp_sizefactor)*8 && _width>=(cimg_openmp_sizefactor)*16) reduction(+:_energy)) cimg_forYZ(U,y,z) { const int _p1y = y?y - 1:0, _n1y = y<U.height() - 1?y + 1:y, _p1z = z?z - 1:0, _n1z = z<U.depth() - 1?z + 1:z; cimg_for3X(U,x) { const float X = is_backward?x - U(x,y,z,0):x + U(x,y,z,0), Y = is_backward?y - U(x,y,z,1):y + U(x,y,z,1), Z = is_backward?z - U(x,y,z,2):z + U(x,y,z,2); float delta_I = 0, _energy_regul = 0; if (is_backward) cimg_forC(I2,c) delta_I+=(float)(I1._linear_atXYZ(X,Y,Z,c) - I2(x,y,z,c)); else cimg_forC(I2,c) delta_I+=(float)(I1(x,y,z,c) - I2._linear_atXYZ(X,Y,Z,c)); cimg_forC(U,c) { const float Ux = 0.5f*(U(_n1x,y,z,c) - U(_p1x,y,z,c)), Uy = 0.5f*(U(x,_n1y,z,c) - U(x,_p1y,z,c)), Uz = 0.5f*(U(x,y,_n1z,c) - U(x,y,_p1z,c)), N2 = Ux*Ux + Uy*Uy + Uz*Uz, N = std::sqrt(N2), N3 = 1e-5f + N2*N, coef_a = (1 - Ux*Ux/N2)/N, coef_b = -2*Ux*Uy/N3, coef_c = -2*Ux*Uz/N3, coef_d = (1 - Uy*Uy/N2)/N, coef_e = -2*Uy*Uz/N3, coef_f = (1 - Uz*Uz/N2)/N, Uxx = U(_n1x,y,z,c) + U(_p1x,y,z,c), Uyy = U(x,_n1y,z,c) + U(x,_p1y,z,c), Uzz = U(x,y,_n1z,c) + U(x,y,_p1z,c), Uxy = 0.25f*(U(_n1x,_n1y,z,c) + U(_p1x,_p1y,z,c) - U(_n1x,_p1y,z,c) - U(_n1x,_p1y,z,c)), Uxz = 0.25f*(U(_n1x,y,_n1z,c) + U(_p1x,y,_p1z,c) - U(_n1x,y,_p1z,c) - U(_n1x,y,_p1z,c)), Uyz = 0.25f*(U(x,_n1y,_n1z,c) + U(x,_p1y,_p1z,c) - U(x,_n1y,_p1z,c) - U(x,_n1y,_p1z,c)); U(x,y,z,c) = (float)(U(x,y,z,c) + dt*(delta_I*dI[c]._linear_atXYZ(X,Y,Z) + nsmoothness* ( coef_a*Uxx + coef_b*Uxy + coef_c*Uxz + coef_d*Uyy + coef_e*Uyz + coef_f*Uzz )) )/(1 + 2*(coef_a + coef_d + coef_f)*nsmoothness*dt); _energy_regul+=N; } if (is_backward) { // Constraint displacement vectors to stay in image if (U(x,y,z,0)>x) U(x,y,z,0) = (float)x; if (U(x,y,z,1)>y) U(x,y,z,1) = (float)y; if (U(x,y,z,2)>z) U(x,y,z,2) = (float)z; bound = (float)x - _width; if (U(x,y,z,0)<=bound) U(x,y,z,0) = bound; bound = (float)y - _height; if (U(x,y,z,1)<=bound) U(x,y,z,1) = bound; bound = (float)z - _depth; if (U(x,y,z,2)<=bound) U(x,y,z,2) = bound; } else { if (U(x,y,z,0)<-x) U(x,y,z,0) = -(float)x; if (U(x,y,z,1)<-y) U(x,y,z,1) = -(float)y; if (U(x,y,z,2)<-z) U(x,y,z,2) = -(float)z; bound = (float)_width - x; if (U(x,y,z,0)>=bound) U(x,y,z,0) = bound; bound = (float)_height - y; if (U(x,y,z,1)>=bound) U(x,y,z,1) = bound; bound = (float)_depth - z; if (U(x,y,z,2)>=bound) U(x,y,z,2) = bound; } _energy+=delta_I*delta_I + nsmoothness*_energy_regul; } if (V) cimg_forXYZ(V,_x,_y,_z) if (V(_x,_y,_z,3)) { // Apply constraints U(_x,_y,_z,0) = V(_x,_y,_z,0)/factor; U(_x,_y,_z,1) = V(_x,_y,_z,1)/factor; U(_x,_y,_z,2) = V(_x,_y,_z,2)/factor; } } } } else { // 2D version if (smoothness>=0) // Isotropic regularization cimg_pragma_openmp(parallel for cimg_openmp_if(_height>=(cimg_openmp_sizefactor)*8 && _width>=(cimg_openmp_sizefactor)*16) reduction(+:_energy)) cimg_forY(U,y) { const int _p1y = y?y - 1:0, _n1y = y<U.height() - 1?y + 1:y; cimg_for3X(U,x) { const float X = is_backward?x - U(x,y,0):x + U(x,y,0), Y = is_backward?y - U(x,y,1):y + U(x,y,1); float delta_I = 0, _energy_regul = 0; if (is_backward) cimg_forC(I2,c) delta_I+=(float)(I1._linear_atXY(X,Y,c) - I2(x,y,c)); else cimg_forC(I2,c) delta_I+=(float)(I1(x,y,c) - I2._linear_atXY(X,Y,c)); cimg_forC(U,c) { const float Ux = 0.5f*(U(_n1x,y,c) - U(_p1x,y,c)), Uy = 0.5f*(U(x,_n1y,c) - U(x,_p1y,c)), Uxx = U(_n1x,y,c) + U(_p1x,y,c), Uyy = U(x,_n1y,c) + U(x,_p1y,c); U(x,y,c) = (float)(U(x,y,c) + dt*(delta_I*dI[c]._linear_atXY(X,Y) + smoothness*( Uxx + Uyy )))/(1 + 4*smoothness*dt); _energy_regul+=Ux*Ux + Uy*Uy; } if (is_backward) { // Constraint displacement vectors to stay in image if (U(x,y,0)>x) U(x,y,0) = (float)x; if (U(x,y,1)>y) U(x,y,1) = (float)y; bound = (float)x - _width; if (U(x,y,0)<=bound) U(x,y,0) = bound; bound = (float)y - _height; if (U(x,y,1)<=bound) U(x,y,1) = bound; } else { if (U(x,y,0)<-x) U(x,y,0) = -(float)x; if (U(x,y,1)<-y) U(x,y,1) = -(float)y; bound = (float)_width - x; if (U(x,y,0)>=bound) U(x,y,0) = bound; bound = (float)_height - y; if (U(x,y,1)>=bound) U(x,y,1) = bound; } _energy+=delta_I*delta_I + smoothness*_energy_regul; } if (V) cimg_forXY(V,_x,_y) if (V(_x,_y,2)) { // Apply constraints U(_x,_y,0) = V(_x,_y,0)/factor; U(_x,_y,1) = V(_x,_y,1)/factor; } } else { // Anisotropic regularization const float nsmoothness = -smoothness; cimg_pragma_openmp(parallel for cimg_openmp_if(_height>=(cimg_openmp_sizefactor)*8 && _width>=(cimg_openmp_sizefactor)*16) reduction(+:_energy)) cimg_forY(U,y) { const int _p1y = y?y - 1:0, _n1y = y<U.height() - 1?y + 1:y; cimg_for3X(U,x) { const float X = is_backward?x - U(x,y,0):x + U(x,y,0), Y = is_backward?y - U(x,y,1):y + U(x,y,1); float delta_I = 0, _energy_regul = 0; if (is_backward) cimg_forC(I2,c) delta_I+=(float)(I1._linear_atXY(X,Y,c) - I2(x,y,c)); else cimg_forC(I2,c) delta_I+=(float)(I1(x,y,c) - I2._linear_atXY(X,Y,c)); cimg_forC(U,c) { const float Ux = 0.5f*(U(_n1x,y,c) - U(_p1x,y,c)), Uy = 0.5f*(U(x,_n1y,c) - U(x,_p1y,c)), N2 = Ux*Ux + Uy*Uy, N = std::sqrt(N2), N3 = 1e-5f + N2*N, coef_a = Uy*Uy/N3, coef_b = -2*Ux*Uy/N3, coef_c = Ux*Ux/N3, Uxx = U(_n1x,y,c) + U(_p1x,y,c), Uyy = U(x,_n1y,c) + U(x,_p1y,c), Uxy = 0.25f*(U(_n1x,_n1y,c) + U(_p1x,_p1y,c) - U(_n1x,_p1y,c) - U(_n1x,_p1y,c)); U(x,y,c) = (float)(U(x,y,c) + dt*(delta_I*dI[c]._linear_atXY(X,Y) + nsmoothness*( coef_a*Uxx + coef_b*Uxy + coef_c*Uyy )))/ (1 + 2*(coef_a + coef_c)*nsmoothness*dt); _energy_regul+=N; } if (is_backward) { // Constraint displacement vectors to stay in image if (U(x,y,0)>x) U(x,y,0) = (float)x; if (U(x,y,1)>y) U(x,y,1) = (float)y; bound = (float)x - _width; if (U(x,y,0)<=bound) U(x,y,0) = bound; bound = (float)y - _height; if (U(x,y,1)<=bound) U(x,y,1) = bound; } else { if (U(x,y,0)<-x) U(x,y,0) = -(float)x; if (U(x,y,1)<-y) U(x,y,1) = -(float)y; bound = (float)_width - x; if (U(x,y,0)>=bound) U(x,y,0) = bound; bound = (float)_height - y; if (U(x,y,1)>=bound) U(x,y,1) = bound; } _energy+=delta_I*delta_I + nsmoothness*_energy_regul; } if (V) cimg_forXY(V,_x,_y) if (V(_x,_y,2)) { // Apply constraints U(_x,_y,0) = V(_x,_y,0)/factor; U(_x,_y,1) = V(_x,_y,1)/factor; } } } } const float d_energy = (_energy - energy)/(sw*sh*sd); if (d_energy<=0 && -d_energy<_precision) break; if (d_energy>0) dt*=0.5f; energy = _energy; } } return U; } //! Compute correspondence map between two images, using a patch-matching algorithm. /** \param patch_image The image containing the reference patches to match with the instance image. \param patch_width Width of the patch used for matching. \param patch_height Height of the patch used for matching. \param patch_depth Depth of the patch used for matching. \param nb_iterations Number of patch-match iterations. \param nb_randoms Number of randomization attempts (per pixel). \param occ_penalization Penalization factor in score related patch occurrences. \param guide Image used as the initial correspondence estimate for the algorithm. 'guide' may have a last channel with boolean values (0=false | other=true) that tells for each pixel if its correspondence vector is constrained to its initial value (constraint mask). \param[out] matching_score Returned as the image of matching scores. **/ template<typename t1, typename t2> CImg<T>& matchpatch(const CImg<T>& patch_image, const unsigned int patch_width, const unsigned int patch_height, const unsigned int patch_depth, const unsigned int nb_iterations, const unsigned int nb_randoms, const float occ_penalization, const CImg<t1> &guide, CImg<t2> &matching_score) { return get_matchpatch(patch_image,patch_width,patch_height,patch_depth, nb_iterations,nb_randoms,occ_penalization,guide,matching_score).move_to(*this); } //! Compute correspondence map between two images, using the patch-match algorithm \newinstance. template<typename t1, typename t2> CImg<intT> get_matchpatch(const CImg<T>& patch_image, const unsigned int patch_width, const unsigned int patch_height, const unsigned int patch_depth, const unsigned int nb_iterations, const unsigned int nb_randoms, const float occ_penalization, const CImg<t1> &guide, CImg<t2> &matching_score) const { return _matchpatch(patch_image,patch_width,patch_height,patch_depth, nb_iterations,nb_randoms,occ_penalization, guide,true,matching_score); } //! Compute correspondence map between two images, using the patch-match algorithm \overloading. template<typename t> CImg<T>& matchpatch(const CImg<T>& patch_image, const unsigned int patch_width, const unsigned int patch_height, const unsigned int patch_depth, const unsigned int nb_iterations=5, const unsigned int nb_randoms=5, const float occ_penalization=0, const CImg<t> &guide=CImg<t>::const_empty()) { return get_matchpatch(patch_image,patch_width,patch_height,patch_depth, nb_iterations,nb_randoms,occ_penalization,guide).move_to(*this); } //! Compute correspondence map between two images, using the patch-match algorithm \overloading. template<typename t> CImg<intT> get_matchpatch(const CImg<T>& patch_image, const unsigned int patch_width, const unsigned int patch_height, const unsigned int patch_depth, const unsigned int nb_iterations=5, const unsigned int nb_randoms=5, const float occ_penalization=0, const CImg<t> &guide=CImg<t>::const_empty()) const { CImg<T> matching_score; return _matchpatch(patch_image,patch_width,patch_height,patch_depth, nb_iterations,nb_randoms,occ_penalization,guide,false,matching_score); } template<typename t1, typename t2> CImg<intT> _matchpatch(const CImg<T>& patch_image, const unsigned int patch_width, const unsigned int patch_height, const unsigned int patch_depth, const unsigned int nb_iterations, const unsigned int nb_randoms, const float occ_penalization, const CImg<t1> &guide, const bool is_matching_score, CImg<t2> &matching_score) const { if (is_empty()) return CImg<intT>::const_empty(); if (patch_image._spectrum!=_spectrum) throw CImgArgumentException(_cimg_instance "matchpatch(): Instance image and specified patch image (%u,%u,%u,%u,%p) " "have different spectrums.", cimg_instance, patch_image._width,patch_image._height,patch_image._depth,patch_image._spectrum, patch_image._data); if (patch_width>_width || patch_height>_height || patch_depth>_depth) throw CImgArgumentException(_cimg_instance "matchpatch(): Specified patch size %ux%ux%u is bigger than the dimensions " "of the instance image.", cimg_instance,patch_width,patch_height,patch_depth); if (patch_width>patch_image._width || patch_height>patch_image._height || patch_depth>patch_image._depth) throw CImgArgumentException(_cimg_instance "matchpatch(): Specified patch size %ux%ux%u is bigger than the dimensions " "of the patch image image (%u,%u,%u,%u,%p).", cimg_instance,patch_width,patch_height,patch_depth, patch_image._width,patch_image._height,patch_image._depth,patch_image._spectrum, patch_image._data); const unsigned int _constraint = patch_image._depth>1?3:2, constraint = guide._spectrum>_constraint?_constraint:0; if (guide && (guide._width!=_width || guide._height!=_height || guide._depth!=_depth || guide._spectrum<_constraint)) throw CImgArgumentException(_cimg_instance "matchpatch(): Specified guide (%u,%u,%u,%u,%p) has invalid dimensions " "considering instance and patch image (%u,%u,%u,%u,%p).", cimg_instance, guide._width,guide._height,guide._depth,guide._spectrum,guide._data, patch_image._width,patch_image._height,patch_image._depth,patch_image._spectrum, patch_image._data); CImg<intT> a_map(_width,_height,_depth,patch_image._depth>1?3:2); CImg<ucharT> is_updated(_width,_height,_depth,1,3); CImg<floatT> score(_width,_height,_depth); CImg<uintT> occ, loop_order; ulongT rng = (cimg::_rand(),cimg::rng()); if (occ_penalization!=0) { occ.assign(patch_image._width,patch_image._height,patch_image._depth,1,0); loop_order.assign(_width,_height,_depth,_depth>1?3:2); cimg_forXYZ(loop_order,x,y,z) { loop_order(x,y,z,0) = x; loop_order(x,y,z,1) = y; if (loop_order._spectrum>2) loop_order(x,y,z,2) = z; } cimg_forXYZ(loop_order,x,y,z) { // Randomize loop order in case of constraints on patch occurrence const unsigned int X = (unsigned int)cimg::round(cimg::rand(loop_order._width - 1.,&rng)), Y = (unsigned int)cimg::round(cimg::rand(loop_order._height - 1.,&rng)), Z = loop_order._depth>1?(unsigned int)cimg::round(cimg::rand(loop_order._depth - 1.,&rng)):0U; cimg::swap(loop_order(x,y,z,0),loop_order(X,Y,Z,0)); cimg::swap(loop_order(x,y,z,1),loop_order(X,Y,Z,1)); if (loop_order._spectrum>2) cimg::swap(loop_order(x,y,z,2),loop_order(X,Y,Z,2)); } } const int psizew = (int)patch_width, psizew1 = psizew/2, psizew2 = psizew - psizew1 - 1, psizeh = (int)patch_height, psizeh1 = psizeh/2, psizeh2 = psizeh - psizeh1 - 1, psized = (int)patch_depth, psized1 = psized/2, psized2 = psized - psized1 - 1; // Interleave image buffers to speed up patch comparison (cache-friendly). CImg<T> in_this = get_permute_axes("cxyz"); in_this._width = _width*_spectrum; in_this._height = _height; in_this._depth = _depth; in_this._spectrum = 1; CImg<T> in_patch = patch_image.get_permute_axes("cxyz"); in_patch._width = patch_image._width*patch_image._spectrum; in_patch._height = patch_image._height; in_patch._depth = patch_image._depth; in_patch._spectrum = 1; if (_depth>1 || patch_image._depth>1) { // 3D version // Initialize correspondence map. if (guide) cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(_width,64)) cimg_forXYZ(*this,x,y,z) { // User-defined initialization const int cx1 = x<=psizew1?x:(x<width() - psizew2?psizew1:psizew + x - width()), cx2 = psizew - cx1 - 1, cy1 = y<=psizeh1?y:(y<height() - psizeh2?psizeh1:psizeh + y - height()), cy2 = psizeh - cy1 - 1, cz1 = z<=psized1?z:(z<depth() - psized2?psized1:psized + z - depth()), cz2 = psized - cz1 - 1, u = cimg::cut((int)guide(x,y,z,0),cx1,patch_image.width() - 1 - cx2), v = cimg::cut((int)guide(x,y,z,1),cy1,patch_image.height() - 1 - cy2), w = cimg::cut((int)guide(x,y,z,2),cz1,patch_image.depth() - 1 - cz2); a_map(x,y,z,0) = u; a_map(x,y,z,1) = v; a_map(x,y,z,2) = w; score(x,y,z) = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,patch_depth,_spectrum, x - cx1,y - cy1,z - cz1, u - cx1,v - cy1,w - cz1, u,v,w,0,cimg::type<float>::inf()); } else cimg_pragma_openmp(parallel cimg_openmp_if_size(_width,64)) { ulongT _rng = (cimg::_rand(),cimg::rng()); #if cimg_use_openmp!=0 _rng+=omp_get_thread_num(); #endif cimg_pragma_openmp(for cimg_openmp_collapse(2)) cimg_forXYZ(*this,x,y,z) { // Random initialization const int cx1 = x<=psizew1?x:(x<width() - psizew2?psizew1:psizew + x - width()), cx2 = psizew - cx1 - 1, cy1 = y<=psizeh1?y:(y<height() - psizeh2?psizeh1:psizeh + y - height()), cy2 = psizeh - cy1 - 1, cz1 = z<=psized1?z:(z<depth() - psized2?psized1:psized + z - depth()), cz2 = psized - cz1 - 1, u = (int)cimg::round(cimg::rand(cx1,patch_image.width() - 1 - cx2,&_rng)), v = (int)cimg::round(cimg::rand(cy1,patch_image.height() - 1 - cy2,&_rng)), w = (int)cimg::round(cimg::rand(cz1,patch_image.depth() - 1 - cz2,&_rng)); a_map(x,y,z,0) = u; a_map(x,y,z,1) = v; a_map(x,y,z,2) = w; score(x,y,z) = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,patch_depth,_spectrum, x - cx1,y - cy1,z - cz1, u - cx1,v - cy1,w - cz1, u,v,w,0,cimg::type<float>::inf()); } cimg::srand(_rng); } // Start iteration loop. cimg_abort_init; for (unsigned int iter = 0; iter<nb_iterations; ++iter) { cimg_abort_test; const bool is_odd = iter%2; const unsigned int cmask = is_odd?1:2, nmask = 3 - cmask; if (iter) occ.fill(0); cimg_pragma_openmp(parallel cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*64 && iter<nb_iterations-2)) { ulongT _rng = (cimg::_rand(),cimg::rng()); #if cimg_use_openmp!=0 _rng+=omp_get_thread_num(); #endif cimg_pragma_openmp(for cimg_openmp_collapse(2)) cimg_forXYZ(*this,X,Y,Z) { const int _x = is_odd?width() - 1 - X:X, _y = is_odd?height() - 1 - Y:Y, _z = is_odd?depth() - 1 - Z:Z; int x, y, z; if (occ_penalization) { x = loop_order(_x,_y,_z,0); y = loop_order(_x,_y,_z,1); if (loop_order._spectrum>2) z = loop_order(_x,_y,_z,2); else z = _z; } else { x = _x; y = _y; z = _z; } if (score(x,y,z)<=1e-5 || (constraint && guide(x,y,z,constraint)!=0)) continue; const int cx1 = x<=psizew1?x:(x<width() - psizew2?psizew1:psizew + x - width()), cx2 = psizew - cx1 - 1, cy1 = y<=psizeh1?y:(y<height() - psizeh2?psizeh1:psizeh + y - height()), cy2 = psizeh - cy1 - 1, cz1 = z<=psized1?z:(z<depth() - psized2?psized1:psized + z - depth()), cz2 = psized - cz1 - 1, xp = x - cx1, yp = y - cy1, zp = z - cz1; int best_u = a_map(x,y,z,0), best_v = a_map(x,y,z,1), best_w = a_map(x,y,z,2), u, v, w; const float best_score0 = score(x,y,z); float best_score = best_score0, s; // Propagation. if (x>0 && (is_updated(x - 1,y,z)&cmask)) { // Compare with left neighbor u = a_map(x - 1,y,z,0); v = a_map(x - 1,y,z,1); w = a_map(x - 1,y,z,2); if (u>=cx1 - 1 && u<patch_image.width() - 1 - cx2 && v>=cy1 && v<patch_image.height() - cy2 && w>=cz1 && w<patch_image.depth() - cz2) { s = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,patch_depth,_spectrum, xp,yp,zp,u + 1 - cx1,v - cy1,w - cz1, u,v,w,occ_penalization,best_score); if (s<best_score) { best_u = u + 1; best_v = v; best_w = w; best_score = s; } } } if (y>0 && (is_updated(x,y - 1,z)&cmask)) { // Compare with up neighbor u = a_map(x,y - 1,z,0); v = a_map(x,y - 1,z,1); w = a_map(x,y - 1,z,2); if (u>=cx1 && u<patch_image.width() - cx2 && v>=cy1 - 1 && v<patch_image.height() - 1 - cy2 && w>=cz1 && w<patch_image.depth() - cz2) { s = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,patch_depth,_spectrum, xp,yp,zp,u - cx1,v + 1 - cy1,w - cz1, u,v,w,occ_penalization,best_score); if (s<best_score) { best_u = u; best_v = v + 1; best_w = w; best_score = s; } } } if (z>0 && (is_updated(x,y,z - 1)&cmask)) { // Compare with backward neighbor u = a_map(x,y,z - 1,0); v = a_map(x,y,z - 1,1); w = a_map(x,y,z - 1,2); if (u>=cx1 && u<patch_image.width() - cx2 && v>=cy1 && v<patch_image.height() - cy2 && w>=cz1 - 1 && w<patch_image.depth() - 1 - cz2) { s = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,patch_depth,_spectrum, xp,yp,zp,u - cx1,v - cy1,w + 1 - cz1, u,v,w,occ_penalization,best_score); if (s<best_score) { best_u = u; best_v = v; best_w = w + 1; best_score = s; } } } if (x<width() - 1 && (is_updated(x + 1,y,z)&cmask)) { // Compare with right neighbor u = a_map(x + 1,y,z,0); v = a_map(x + 1,y,z,1); w = a_map(x + 1,y,z,2); if (u>=cx1 + 1 && u<patch_image.width() + 1 - cx2 && v>=cy1 && v<patch_image.height() - cy2 && w>=cz1 && w<patch_image.depth() - cz2) { s = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,patch_depth,_spectrum, xp,yp,zp,u - 1 - cx1,v - cy1,w - cz1, u,v,w,occ_penalization,best_score); if (s<best_score) { best_u = u - 1; best_v = v; best_w = w; best_score = s; } } } if (y<height() - 1 && (is_updated(x,y + 1,z)&cmask)) { // Compare with bottom neighbor u = a_map(x,y + 1,z,0); v = a_map(x,y + 1,z,1); w = a_map(x,y + 1,z,2); if (u>=cx1 && u<patch_image.width() - cx2 && v>=cy1 + 1 && v<patch_image.height() + 1 - cy2 && w>=cz1 && w<patch_image.depth() - cz2) { s = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,patch_depth,_spectrum, xp,yp,zp,u - cx1,v - 1 - cy1,w - cz1, u,v,w,occ_penalization,best_score); if (s<best_score) { best_u = u; best_v = v - 1; best_w = w; best_score = s; } } } if (z<depth() - 1 && (is_updated(x,y,z + 1)&cmask)) { // Compare with forward neighbor u = a_map(x,y,z + 1,0); v = a_map(x,y,z + 1,1); w = a_map(x,y,z + 1,2); if (u>=cx1 && u<patch_image.width() - cx2 && v>=cy1 && v<patch_image.height() - cy2 && w>=cz1 + 1 && w<patch_image.depth() + 1 - cz2) { s = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,patch_depth,_spectrum, xp,yp,zp,u - cx1,v - cy1,w - 1 - cz1, u,v,w,occ_penalization,best_score); if (s<best_score) { best_u = u; best_v = v; best_w = w - 1; best_score = s; } } } // Randomization. float dw = (float)patch_image.width(), dh = (float)patch_image.height(), dd = (float)patch_image.depth(); for (unsigned int i = 0; i<nb_randoms; ++i) { u = (int)cimg::round(cimg::rand(std::max((float)cx1,best_u - dw), std::min(patch_image.width() - 1.f - cx2,best_u + dw),&_rng)); v = (int)cimg::round(cimg::rand(std::max((float)cy1,best_v - dh), std::min(patch_image.height() - 1.f - cy2,best_v + dh),&_rng)); w = (int)cimg::round(cimg::rand(std::max((float)cz1,best_w - dd), std::min(patch_image.depth() - 1.f - cz2,best_w + dd),&_rng)); if (u!=best_u || v!=best_v || w!=best_w) { s = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,patch_depth,_spectrum, xp,yp,zp,u - cx1,v - cy1,w - cz1, u,v,w,occ_penalization,best_score); if (s<best_score) { best_u = u; best_v = v; best_w = w; best_score = s; } dw = std::max(5.f,dw*0.5f); dh = std::max(5.f,dh*0.5f); dd = std::max(5.f,dd*0.5f); } } if (best_score<best_score0) { a_map(x,y,z,0) = best_u; a_map(x,y,z,1) = best_v; a_map(x,y,z,2) = best_w; score(x,y,z) = best_score; is_updated(x,y,z) = 3; } else is_updated(x,y,z)&=~nmask; if (occ_penalization!=0) cimg_pragma_openmp(atomic) ++occ(best_u,best_v,best_w); } cimg::srand(_rng); } } } else { // 2D version // Initialize correspondence map. if (guide) cimg_pragma_openmp(parallel for cimg_openmp_if_size(_width,64)) cimg_forXY(*this,x,y) { // User-defined initialization const int cx1 = x<=psizew1?x:(x<width() - psizew2?psizew1:psizew + x - width()), cx2 = psizew - cx1 - 1, cy1 = y<=psizeh1?y:(y<height() - psizeh2?psizeh1:psizeh + y - height()), cy2 = psizeh - cy1 - 1, u = cimg::cut((int)guide(x,y,0),cx1,patch_image.width() - 1 - cx2), v = cimg::cut((int)guide(x,y,1),cy1,patch_image.height() - 1 - cy2); a_map(x,y,0) = u; a_map(x,y,1) = v; score(x,y) = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,_spectrum, x - cx1,y - cy1,u - cx1,v - cy1, u,v,0,cimg::type<float>::inf()); } else cimg_pragma_openmp(parallel cimg_openmp_if_size(_width,64)) { ulongT _rng = (cimg::_rand(),cimg::rng()); #if cimg_use_openmp!=0 _rng+=omp_get_thread_num(); #endif cimg_pragma_openmp(for) cimg_forXY(*this,x,y) { // Random initialization const int cx1 = x<=psizew1?x:(x<width() - psizew2?psizew1:psizew + x - width()), cx2 = psizew - cx1 - 1, cy1 = y<=psizeh1?y:(y<height() - psizeh2?psizeh1:psizeh + y - height()), cy2 = psizeh - cy1 - 1, u = (int)cimg::round(cimg::rand(cx1,patch_image.width() - 1 - cx2,&_rng)), v = (int)cimg::round(cimg::rand(cy1,patch_image.height() - 1 - cy2,&_rng)); a_map(x,y,0) = u; a_map(x,y,1) = v; score(x,y) = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,_spectrum, x - cx1,y - cy1,u - cx1,v - cy1, u,v,0,cimg::type<float>::inf()); } cimg::srand(_rng); } // Start iteration loop. cimg_abort_init; for (unsigned int iter = 0; iter<nb_iterations; ++iter) { cimg_abort_test; const bool is_odd = iter%2; const unsigned int cmask = is_odd?1:2, nmask = 3 - cmask; if (iter) occ.fill(0); cimg_pragma_openmp(parallel cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*64 && iter<nb_iterations-2)) { ulongT _rng = (cimg::_rand(),cimg::rng()); #if cimg_use_openmp!=0 _rng+=omp_get_thread_num(); #endif cimg_pragma_openmp(for) cimg_forXY(*this,X,Y) { const int _x = is_odd?width() - 1 - X:X, _y = is_odd?height() - 1 - Y:Y; int x, y; if (occ_penalization) { x = loop_order(_x,_y,0); y = loop_order(_x,_y,1); } else { x = _x; y = _y; } if (score(x,y)<=1e-5 || (constraint && guide(x,y,constraint)!=0)) continue; const int cx1 = x<=psizew1?x:(x<width() - psizew2?psizew1:psizew + x - width()), cx2 = psizew - cx1 - 1, cy1 = y<=psizeh1?y:(y<height() - psizeh2?psizeh1:psizeh + y - height()), cy2 = psizeh - cy1 - 1, xp = x - cx1, yp = y - cy1; int best_u = a_map(x,y,0), best_v = a_map(x,y,1), u, v; const float best_score0 = score(x,y); float best_score = best_score0, s; // Propagation. if (x>0 && (is_updated(x - 1,y)&cmask)) { // Compare with left neighbor u = a_map(x - 1,y,0); v = a_map(x - 1,y,1); if (u>=cx1 - 1 && u<patch_image.width() - 1 - cx2 && v>=cy1 && v<patch_image.height() - cy2) { s = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,_spectrum, xp,yp,u + 1 - cx1,v - cy1, u,v,occ_penalization,best_score); if (s<best_score) { best_u = u + 1; best_v = v; best_score = s; } } } if (y>0 && (is_updated(x,y - 1)&cmask)) { // Compare with up neighbor u = a_map(x,y - 1,0); v = a_map(x,y - 1,1); if (u>=cx1 && u<patch_image.width() - cx2 && v>=cy1 - 1 && v<patch_image.height() - 1 - cy2) { s = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,_spectrum, xp,yp,u - cx1,v + 1 - cy1, u,v,occ_penalization,best_score); if (s<best_score) { best_u = u; best_v = v + 1; best_score = s; } } } if (x<width() - 1 && (is_updated(x + 1,y)&cmask)) { // Compare with right neighbor u = a_map(x + 1,y,0); v = a_map(x + 1,y,1); if (u>=cx1 + 1 && u<patch_image.width() + 1 - cx2 && v>=cy1 && v<patch_image.height() - cy2) { s = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,_spectrum, xp,yp,u - 1 - cx1,v - cy1, u,v,occ_penalization,best_score); if (s<best_score) { best_u = u - 1; best_v = v; best_score = s; } } } if (y<height() - 1 && (is_updated(x,y + 1)&cmask)) { // Compare with bottom neighbor u = a_map(x,y + 1,0); v = a_map(x,y + 1,1); if (u>=cx1 && u<patch_image.width() - cx2 && v>=cy1 + 1 && v<patch_image.height() + 1 - cy2) { s = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,_spectrum, xp,yp,u - cx1,v - 1 - cy1, u,v,occ_penalization,best_score); if (s<best_score) { best_u = u; best_v = v - 1; best_score = s; } } } // Randomization. float dw = (float)patch_image.width(), dh = (float)patch_image.height(); for (unsigned int i = 0; i<nb_randoms; ++i) { u = (int)cimg::round(cimg::rand(std::max((float)cx1,best_u - dw), std::min(patch_image.width() - 1.f - cx2,best_u + dw),&_rng)); v = (int)cimg::round(cimg::rand(std::max((float)cy1,best_v - dh), std::min(patch_image.height() - 1.f - cy2,best_v + dh),&_rng)); if (u!=best_u || v!=best_v) { s = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,_spectrum, xp,yp,u - cx1,v - cy1, u,v,occ_penalization,best_score); if (s<best_score) { best_u = u; best_v = v; best_score = s; } dw = std::max(5.f,dw*0.5f); dh = std::max(5.f,dh*0.5f); } } if (best_score<best_score0) { a_map(x,y,0) = best_u; a_map(x,y,1) = best_v; score(x,y) = best_score; is_updated(x,y) = 3; } else is_updated(x,y)&=~nmask; if (occ_penalization!=0) cimg_pragma_openmp(atomic) ++occ(best_u,best_v); } } cimg::srand(rng); } } if (is_matching_score) score.move_to(matching_score); return a_map; } // Compute SSD between two patches in different images. static float _matchpatch(const CImg<T>& img1, const CImg<T>& img2, const CImg<uintT>& occ, const unsigned int psizew, const unsigned int psizeh, const unsigned int psized, const unsigned int psizec, const int x1, const int y1, const int z1, const int x2, const int y2, const int z2, const int xc, const int yc, const int zc, const float occ_penalization, const float max_score) { // 3D version const T *p1 = img1.data(x1*psizec,y1,z1), *p2 = img2.data(x2*psizec,y2,z2); const unsigned int psizewc = psizew*psizec; const ulongT offx1 = (ulongT)img1._width - psizewc, offx2 = (ulongT)img2._width - psizewc, offy1 = (ulongT)img1._width*img1._height - (ulongT)psizeh*img1._width, offy2 = (ulongT)img2._width*img2._height - (ulongT)psizeh*img2._width; float ssd = 0; for (unsigned int k = 0; k<psized; ++k) { for (unsigned int j = 0; j<psizeh; ++j) { for (unsigned int i = 0; i<psizewc; ++i) ssd += cimg::sqr((Tfloat)*(p1++) - *(p2++)); if (ssd>max_score) return max_score; p1+=offx1; p2+=offx2; } p1+=offy1; p2+=offy2; } return occ_penalization==0?ssd:cimg::sqr(std::sqrt(ssd) + occ_penalization*occ(xc,yc,zc)); } static float _matchpatch(const CImg<T>& img1, const CImg<T>& img2, const CImg<uintT>& occ, const unsigned int psizew, const unsigned int psizeh, const unsigned int psizec, const int x1, const int y1, const int x2, const int y2, const int xc, const int yc, const float occ_penalization, const float max_score) { // 2D version const T *p1 = img1.data(x1*psizec,y1), *p2 = img2.data(x2*psizec,y2); const unsigned int psizewc = psizew*psizec; const ulongT offx1 = (ulongT)img1._width - psizewc, offx2 = (ulongT)img2._width - psizewc; float ssd = 0; for (unsigned int j = 0; j<psizeh; ++j) { for (unsigned int i = 0; i<psizewc; ++i) ssd += cimg::sqr((Tfloat)*(p1++) - *(p2++)); if (ssd>max_score) return max_score; p1+=offx1; p2+=offx2; } return occ_penalization==0?ssd:cimg::sqr(std::sqrt(ssd) + occ_penalization*occ(xc,yc)); } //! Compute Euclidean distance function to a specified value. /** \param value Reference value. \param metric Type of metric. Can be <tt>{ 0=Chebyshev | 1=Manhattan | 2=Euclidean | 3=Squared-euclidean }</tt>. \note The distance transform implementation has been submitted by A. Meijster, and implements the article 'W.H. Hesselink, A. Meijster, J.B.T.M. Roerdink, "A general algorithm for computing distance transforms in linear time.", In: Mathematical Morphology and its Applications to Image and Signal Processing, J. Goutsias, L. Vincent, and D.S. Bloomberg (eds.), Kluwer, 2000, pp. 331-340.' The submitted code has then been modified to fit CImg coding style and constraints. **/ CImg<T>& distance(const T& value, const unsigned int metric=2) { if (is_empty()) return *this; if (cimg::type<Tint>::string()!=cimg::type<T>::string()) // For datatype < int return CImg<Tint>(*this,false).distance((Tint)value,metric). cut((Tint)cimg::type<T>::min(),(Tint)cimg::type<T>::max()).move_to(*this); bool is_value = false; cimg_for(*this,ptr,T) *ptr = *ptr==value?is_value=true,(T)0:(T)std::max(0,99999999); // (avoid VC++ warning) if (!is_value) return fill(cimg::type<T>::max()); switch (metric) { case 0 : return _distance_core(_distance_sep_cdt,_distance_dist_cdt); // Chebyshev case 1 : return _distance_core(_distance_sep_mdt,_distance_dist_mdt); // Manhattan case 3 : return _distance_core(_distance_sep_edt,_distance_dist_edt); // Squared Euclidean default : return _distance_core(_distance_sep_edt,_distance_dist_edt).sqrt(); // Euclidean } return *this; } //! Compute distance to a specified value \newinstance. CImg<Tfloat> get_distance(const T& value, const unsigned int metric=2) const { return CImg<Tfloat>(*this,false).distance((Tfloat)value,metric); } static longT _distance_sep_edt(const longT i, const longT u, const longT *const g) { return (u*u - i*i + g[u] - g[i])/(2*(u - i)); } static longT _distance_dist_edt(const longT x, const longT i, const longT *const g) { return (x - i)*(x - i) + g[i]; } static longT _distance_sep_mdt(const longT i, const longT u, const longT *const g) { return (u - i<=g[u] - g[i]?999999999:(g[u] - g[i] + u + i)/2); } static longT _distance_dist_mdt(const longT x, const longT i, const longT *const g) { return (x<i?i - x:x - i) + g[i]; } static longT _distance_sep_cdt(const longT i, const longT u, const longT *const g) { const longT h = (i + u)/2; if (g[i]<=g[u]) { return h<i + g[u]?i + g[u]:h; } return h<u - g[i]?h:u - g[i]; } static longT _distance_dist_cdt(const longT x, const longT i, const longT *const g) { const longT d = x<i?i - x:x - i; return d<g[i]?g[i]:d; } static void _distance_scan(const unsigned int len, const longT *const g, longT (*const sep)(const longT, const longT, const longT *const), longT (*const f)(const longT, const longT, const longT *const), longT *const s, longT *const t, longT *const dt) { longT q = s[0] = t[0] = 0; for (int u = 1; u<(int)len; ++u) { // Forward scan while ((q>=0) && f(t[q],s[q],g)>f(t[q],u,g)) { --q; } if (q<0) { q = 0; s[0] = u; } else { const longT w = 1 + sep(s[q], u, g); if (w<(longT)len) { ++q; s[q] = u; t[q] = w; }} } for (int u = (int)len - 1; u>=0; --u) { dt[u] = f(u,s[q],g); if (u==t[q]) --q; } // Backward scan } CImg<T>& _distance_core(longT (*const sep)(const longT, const longT, const longT *const), longT (*const f)(const longT, const longT, const longT *const)) { // Check for g++ 4.9.X, as OpenMP seems to crash for this particular function. I have no clues why. #define cimg_is_gcc49x (__GNUC__==4 && __GNUC_MINOR__==9) const ulongT wh = (ulongT)_width*_height; #if cimg_use_openmp!=0 && !cimg_is_gcc49x cimg_pragma_openmp(parallel for cimg_openmp_if(_spectrum>=2)) #endif cimg_forC(*this,c) { CImg<longT> g(_width), dt(_width), s(_width), t(_width); CImg<T> img = get_shared_channel(c); #if cimg_use_openmp!=0 && !cimg_is_gcc49x cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*512 && _height*_depth>=16) firstprivate(g,dt,s,t)) #endif cimg_forYZ(*this,y,z) { // Over X-direction cimg_forX(*this,x) g[x] = (longT)img(x,y,z,0,wh); _distance_scan(_width,g,sep,f,s,t,dt); cimg_forX(*this,x) img(x,y,z,0,wh) = (T)dt[x]; } if (_height>1) { g.assign(_height); dt.assign(_height); s.assign(_height); t.assign(_height); #if cimg_use_openmp!=0 && !cimg_is_gcc49x cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_height>=(cimg_openmp_sizefactor)*512 && _width*_depth>=16) firstprivate(g,dt,s,t)) #endif cimg_forXZ(*this,x,z) { // Over Y-direction cimg_forY(*this,y) g[y] = (longT)img(x,y,z,0,wh); _distance_scan(_height,g,sep,f,s,t,dt); cimg_forY(*this,y) img(x,y,z,0,wh) = (T)dt[y]; } } if (_depth>1) { g.assign(_depth); dt.assign(_depth); s.assign(_depth); t.assign(_depth); #if cimg_use_openmp!=0 && !cimg_is_gcc49x cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_depth>=(cimg_openmp_sizefactor)*512 && _width*_height>=16) firstprivate(g,dt,s,t)) #endif cimg_forXY(*this,x,y) { // Over Z-direction cimg_forZ(*this,z) g[z] = (longT)img(x,y,z,0,wh); _distance_scan(_depth,g,sep,f,s,t,dt); cimg_forZ(*this,z) img(x,y,z,0,wh) = (T)dt[z]; } } } return *this; } //! Compute chamfer distance to a specified value, with a custom metric. /** \param value Reference value. \param metric_mask Metric mask. \note The algorithm code has been initially proposed by A. Meijster, and modified by D. Tschumperlé. **/ template<typename t> CImg<T>& distance(const T& value, const CImg<t>& metric_mask) { if (is_empty()) return *this; bool is_value = false; cimg_for(*this,ptr,T) *ptr = *ptr==value?is_value=true,0:(T)999999999; if (!is_value) return fill(cimg::type<T>::max()); const ulongT wh = (ulongT)_width*_height; cimg_pragma_openmp(parallel for cimg_openmp_if(_spectrum>=2)) cimg_forC(*this,c) { CImg<T> img = get_shared_channel(c); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width*_height*_depth>=(cimg_openmp_sizefactor)*1024)) cimg_forXYZ(metric_mask,dx,dy,dz) { const t weight = metric_mask(dx,dy,dz); if (weight) { for (int z = dz, nz = 0; z<depth(); ++z,++nz) { // Forward scan for (int y = dy , ny = 0; y<height(); ++y,++ny) { for (int x = dx, nx = 0; x<width(); ++x,++nx) { const T dd = img(nx,ny,nz,0,wh) + weight; if (dd<img(x,y,z,0,wh)) img(x,y,z,0,wh) = dd; } } } for (int z = depth() - 1 - dz, nz = depth() - 1; z>=0; --z,--nz) { // Backward scan for (int y = height() - 1 - dy, ny = height() - 1; y>=0; --y,--ny) { for (int x = width() - 1 - dx, nx = width() - 1; x>=0; --x,--nx) { const T dd = img(nx,ny,nz,0,wh) + weight; if (dd<img(x,y,z,0,wh)) img(x,y,z,0,wh) = dd; } } } } } } return *this; } //! Compute chamfer distance to a specified value, with a custom metric \newinstance. template<typename t> CImg<Tfloat> get_distance(const T& value, const CImg<t>& metric_mask) const { return CImg<Tfloat>(*this,false).distance(value,metric_mask); } //! Compute distance to a specified value, according to a custom metric (use dijkstra algorithm). /** \param value Reference value. \param metric Field of distance potentials. \param is_high_connectivity Tells if the algorithm uses low or high connectivity. \param[out] return_path An image containing the nodes of the minimal path. **/ template<typename t, typename to> CImg<T>& distance_dijkstra(const T& value, const CImg<t>& metric, const bool is_high_connectivity, CImg<to>& return_path) { return get_distance_dijkstra(value,metric,is_high_connectivity,return_path).move_to(*this); } //! Compute distance map to a specified value, according to a custom metric (use dijkstra algorithm) \newinstance. template<typename t, typename to> CImg<typename cimg::superset<t,long>::type> get_distance_dijkstra(const T& value, const CImg<t>& metric, const bool is_high_connectivity, CImg<to>& return_path) const { if (is_empty()) return return_path.assign(); if (!is_sameXYZ(metric)) throw CImgArgumentException(_cimg_instance "distance_dijkstra(): image instance and metric map (%u,%u,%u,%u) " "have incompatible dimensions.", cimg_instance, metric._width,metric._height,metric._depth,metric._spectrum); typedef typename cimg::superset<t,long>::type td; // Type used for computing cumulative distances CImg<td> result(_width,_height,_depth,_spectrum), Q; CImg<boolT> is_queued(_width,_height,_depth,1); if (return_path) return_path.assign(_width,_height,_depth,_spectrum); cimg_forC(*this,c) { const CImg<T> img = get_shared_channel(c); const CImg<t> met = metric.get_shared_channel(c%metric._spectrum); CImg<td> res = result.get_shared_channel(c); CImg<to> path = return_path?return_path.get_shared_channel(c):CImg<to>(); unsigned int sizeQ = 0; // Detect initial seeds. is_queued.fill(0); cimg_forXYZ(img,x,y,z) if (img(x,y,z)==value) { Q._priority_queue_insert(is_queued,sizeQ,0,x,y,z); res(x,y,z) = 0; if (path) path(x,y,z) = (to)0; } // Start distance propagation. while (sizeQ) { // Get and remove point with minimal potential from the queue. const int x = (int)Q(0,1), y = (int)Q(0,2), z = (int)Q(0,3); const td P = (td)-Q(0,0); Q._priority_queue_remove(sizeQ); // Update neighbors. td npot = 0; if (x - 1>=0 && Q._priority_queue_insert(is_queued,sizeQ,-(npot=met(x - 1,y,z) + P),x - 1,y,z)) { res(x - 1,y,z) = npot; if (path) path(x - 1,y,z) = (to)2; } if (x + 1<width() && Q._priority_queue_insert(is_queued,sizeQ,-(npot=met(x + 1,y,z) + P),x + 1,y,z)) { res(x + 1,y,z) = npot; if (path) path(x + 1,y,z) = (to)1; } if (y - 1>=0 && Q._priority_queue_insert(is_queued,sizeQ,-(npot=met(x,y - 1,z) + P),x,y - 1,z)) { res(x,y - 1,z) = npot; if (path) path(x,y - 1,z) = (to)8; } if (y + 1<height() && Q._priority_queue_insert(is_queued,sizeQ,-(npot=met(x,y + 1,z) + P),x,y + 1,z)) { res(x,y + 1,z) = npot; if (path) path(x,y + 1,z) = (to)4; } if (z - 1>=0 && Q._priority_queue_insert(is_queued,sizeQ,-(npot=met(x,y,z - 1) + P),x,y,z - 1)) { res(x,y,z - 1) = npot; if (path) path(x,y,z - 1) = (to)32; } if (z + 1<depth() && Q._priority_queue_insert(is_queued,sizeQ,-(npot=met(x,y,z + 1) + P),x,y,z + 1)) { res(x,y,z + 1) = npot; if (path) path(x,y,z + 1) = (to)16; } if (is_high_connectivity) { const float sqrt2 = std::sqrt(2.f), sqrt3 = std::sqrt(3.f); // Diagonal neighbors on slice z. if (x - 1>=0 && y - 1>=0 && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt2*met(x - 1,y - 1,z) + P)),x - 1,y - 1,z)) { res(x - 1,y - 1,z) = npot; if (path) path(x - 1,y - 1,z) = (to)10; } if (x + 1<width() && y - 1>=0 && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt2*met(x + 1,y - 1,z) + P)),x + 1,y - 1,z)) { res(x + 1,y - 1,z) = npot; if (path) path(x + 1,y - 1,z) = (to)9; } if (x - 1>=0 && y + 1<height() && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt2*met(x - 1,y + 1,z) + P)),x - 1,y + 1,z)) { res(x - 1,y + 1,z) = npot; if (path) path(x - 1,y + 1,z) = (to)6; } if (x + 1<width() && y + 1<height() && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt2*met(x + 1,y + 1,z) + P)),x + 1,y + 1,z)) { res(x + 1,y + 1,z) = npot; if (path) path(x + 1,y + 1,z) = (to)5; } if (z - 1>=0) { // Diagonal neighbors on slice z - 1 if (x - 1>=0 && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt2*met(x - 1,y,z - 1) + P)),x - 1,y,z - 1)) { res(x - 1,y,z - 1) = npot; if (path) path(x - 1,y,z - 1) = (to)34; } if (x + 1<width() && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt2*met(x + 1,y,z - 1) + P)),x + 1,y,z - 1)) { res(x + 1,y,z - 1) = npot; if (path) path(x + 1,y,z - 1) = (to)33; } if (y - 1>=0 && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt2*met(x,y - 1,z - 1) + P)),x,y - 1,z - 1)) { res(x,y - 1,z - 1) = npot; if (path) path(x,y - 1,z - 1) = (to)40; } if (y + 1<height() && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt2*met(x,y + 1,z - 1) + P)),x,y + 1,z - 1)) { res(x,y + 1,z - 1) = npot; if (path) path(x,y + 1,z - 1) = (to)36; } if (x - 1>=0 && y - 1>=0 && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt3*met(x - 1,y - 1,z - 1) + P)), x - 1,y - 1,z - 1)) { res(x - 1,y - 1,z - 1) = npot; if (path) path(x - 1,y - 1,z - 1) = (to)42; } if (x + 1<width() && y - 1>=0 && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt3*met(x + 1,y - 1,z - 1) + P)), x + 1,y - 1,z - 1)) { res(x + 1,y - 1,z - 1) = npot; if (path) path(x + 1,y - 1,z - 1) = (to)41; } if (x - 1>=0 && y + 1<height() && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt3*met(x - 1,y + 1,z - 1) + P)), x - 1,y + 1,z - 1)) { res(x - 1,y + 1,z - 1) = npot; if (path) path(x - 1,y + 1,z - 1) = (to)38; } if (x + 1<width() && y + 1<height() && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt3*met(x + 1,y + 1,z - 1) + P)), x + 1,y + 1,z - 1)) { res(x + 1,y + 1,z - 1) = npot; if (path) path(x + 1,y + 1,z - 1) = (to)37; } } if (z + 1<depth()) { // Diagonal neighbors on slice z + 1 if (x - 1>=0 && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt2*met(x - 1,y,z + 1) + P)),x - 1,y,z + 1)) { res(x - 1,y,z + 1) = npot; if (path) path(x - 1,y,z + 1) = (to)18; } if (x + 1<width() && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt2*met(x + 1,y,z + 1) + P)),x + 1,y,z + 1)) { res(x + 1,y,z + 1) = npot; if (path) path(x + 1,y,z + 1) = (to)17; } if (y - 1>=0 && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt2*met(x,y - 1,z + 1) + P)),x,y - 1,z + 1)) { res(x,y - 1,z + 1) = npot; if (path) path(x,y - 1,z + 1) = (to)24; } if (y + 1<height() && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt2*met(x,y + 1,z + 1) + P)),x,y + 1,z + 1)) { res(x,y + 1,z + 1) = npot; if (path) path(x,y + 1,z + 1) = (to)20; } if (x - 1>=0 && y - 1>=0 && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt3*met(x - 1,y - 1,z + 1) + P)), x - 1,y - 1,z + 1)) { res(x - 1,y - 1,z + 1) = npot; if (path) path(x - 1,y - 1,z + 1) = (to)26; } if (x + 1<width() && y - 1>=0 && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt3*met(x + 1,y - 1,z + 1) + P)), x + 1,y - 1,z + 1)) { res(x + 1,y - 1,z + 1) = npot; if (path) path(x + 1,y - 1,z + 1) = (to)25; } if (x - 1>=0 && y + 1<height() && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt3*met(x - 1,y + 1,z + 1) + P)), x - 1,y + 1,z + 1)) { res(x - 1,y + 1,z + 1) = npot; if (path) path(x - 1,y + 1,z + 1) = (to)22; } if (x + 1<width() && y + 1<height() && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt3*met(x + 1,y + 1,z + 1) + P)), x + 1,y + 1,z + 1)) { res(x + 1,y + 1,z + 1) = npot; if (path) path(x + 1,y + 1,z + 1) = (to)21; } } } } } return result; } //! Compute distance map to a specified value, according to a custom metric (use dijkstra algorithm). \overloading. template<typename t> CImg<T>& distance_dijkstra(const T& value, const CImg<t>& metric, const bool is_high_connectivity=false) { return get_distance_dijkstra(value,metric,is_high_connectivity).move_to(*this); } //! Compute distance map to a specified value, according to a custom metric (use dijkstra algorithm). \newinstance. template<typename t> CImg<Tfloat> get_distance_dijkstra(const T& value, const CImg<t>& metric, const bool is_high_connectivity=false) const { CImg<T> return_path; return get_distance_dijkstra(value,metric,is_high_connectivity,return_path); } //! Compute distance map to one source point, according to a custom metric (use fast marching algorithm). /** \param value Reference value. \param metric Field of distance potentials. **/ template<typename t> CImg<T>& distance_eikonal(const T& value, const CImg<t>& metric) { return get_distance_eikonal(value,metric).move_to(*this); } //! Compute distance map to one source point, according to a custom metric (use fast marching algorithm). template<typename t> CImg<Tfloat> get_distance_eikonal(const T& value, const CImg<t>& metric) const { if (is_empty()) return *this; if (!is_sameXYZ(metric)) throw CImgArgumentException(_cimg_instance "distance_eikonal(): image instance and metric map (%u,%u,%u,%u) have " "incompatible dimensions.", cimg_instance, metric._width,metric._height,metric._depth,metric._spectrum); CImg<Tfloat> result(_width,_height,_depth,_spectrum,cimg::type<Tfloat>::max()), Q; CImg<charT> state(_width,_height,_depth); // -1=far away, 0=narrow, 1=frozen cimg_pragma_openmp(parallel for cimg_openmp_if(_spectrum>=2) firstprivate(Q,state)) cimg_forC(*this,c) { const CImg<T> img = get_shared_channel(c); const CImg<t> met = metric.get_shared_channel(c%metric._spectrum); CImg<Tfloat> res = result.get_shared_channel(c); unsigned int sizeQ = 0; state.fill(-1); // Detect initial seeds. Tfloat *ptr1 = res._data; char *ptr2 = state._data; cimg_for(img,ptr0,T) { if (*ptr0==value) { *ptr1 = 0; *ptr2 = 1; } ++ptr1; ++ptr2; } // Initialize seeds neighbors. ptr2 = state._data; cimg_forXYZ(img,x,y,z) if (*(ptr2++)==1) { if (x - 1>=0 && state(x - 1,y,z)==-1) { const Tfloat dist = res(x - 1,y,z) = __distance_eikonal(res,met(x - 1,y,z),x - 1,y,z); Q._eik_priority_queue_insert(state,sizeQ,-dist,x - 1,y,z); } if (x + 1<width() && state(x + 1,y,z)==-1) { const Tfloat dist = res(x + 1,y,z) = __distance_eikonal(res,met(x + 1,y,z),x + 1,y,z); Q._eik_priority_queue_insert(state,sizeQ,-dist,x + 1,y,z); } if (y - 1>=0 && state(x,y - 1,z)==-1) { const Tfloat dist = res(x,y - 1,z) = __distance_eikonal(res,met(x,y - 1,z),x,y - 1,z); Q._eik_priority_queue_insert(state,sizeQ,-dist,x,y - 1,z); } if (y + 1<height() && state(x,y + 1,z)==-1) { const Tfloat dist = res(x,y + 1,z) = __distance_eikonal(res,met(x,y + 1,z),x,y + 1,z); Q._eik_priority_queue_insert(state,sizeQ,-dist,x,y + 1,z); } if (z - 1>=0 && state(x,y,z - 1)==-1) { const Tfloat dist = res(x,y,z - 1) = __distance_eikonal(res,met(x,y,z - 1),x,y,z - 1); Q._eik_priority_queue_insert(state,sizeQ,-dist,x,y,z - 1); } if (z + 1<depth() && state(x,y,z + 1)==-1) { const Tfloat dist = res(x,y,z + 1) = __distance_eikonal(res,met(x,y,z + 1),x,y,z + 1); Q._eik_priority_queue_insert(state,sizeQ,-dist,x,y,z + 1); } } // Propagate front. while (sizeQ) { int x = -1, y = -1, z = -1; while (sizeQ && x<0) { x = (int)Q(0,1); y = (int)Q(0,2); z = (int)Q(0,3); Q._priority_queue_remove(sizeQ); if (state(x,y,z)==1) x = -1; else state(x,y,z) = 1; } if (x>=0) { if (x - 1>=0 && state(x - 1,y,z)!=1) { const Tfloat dist = __distance_eikonal(res,met(x - 1,y,z),x - 1,y,z); if (dist<res(x - 1,y,z)) { res(x - 1,y,z) = dist; Q._eik_priority_queue_insert(state,sizeQ,-dist,x - 1,y,z); } } if (x + 1<width() && state(x + 1,y,z)!=1) { const Tfloat dist = __distance_eikonal(res,met(x + 1,y,z),x + 1,y,z); if (dist<res(x + 1,y,z)) { res(x + 1,y,z) = dist; Q._eik_priority_queue_insert(state,sizeQ,-dist,x + 1,y,z); } } if (y - 1>=0 && state(x,y - 1,z)!=1) { const Tfloat dist = __distance_eikonal(res,met(x,y - 1,z),x,y - 1,z); if (dist<res(x,y - 1,z)) { res(x,y - 1,z) = dist; Q._eik_priority_queue_insert(state,sizeQ,-dist,x,y - 1,z); } } if (y + 1<height() && state(x,y + 1,z)!=1) { const Tfloat dist = __distance_eikonal(res,met(x,y + 1,z),x,y + 1,z); if (dist<res(x,y + 1,z)) { res(x,y + 1,z) = dist; Q._eik_priority_queue_insert(state,sizeQ,-dist,x,y + 1,z); } } if (z - 1>=0 && state(x,y,z - 1)!=1) { const Tfloat dist = __distance_eikonal(res,met(x,y,z - 1),x,y,z - 1); if (dist<res(x,y,z - 1)) { res(x,y,z - 1) = dist; Q._eik_priority_queue_insert(state,sizeQ,-dist,x,y,z - 1); } } if (z + 1<depth() && state(x,y,z + 1)!=1) { const Tfloat dist = __distance_eikonal(res,met(x,y,z + 1),x,y,z + 1); if (dist<res(x,y,z + 1)) { res(x,y,z + 1) = dist; Q._eik_priority_queue_insert(state,sizeQ,-dist,x,y,z + 1); } } } } } return result; } // Locally solve eikonal equation. Tfloat __distance_eikonal(const CImg<Tfloat>& res, const Tfloat P, const int x=0, const int y=0, const int z=0) const { const Tfloat M = (Tfloat)cimg::type<T>::max(); T T1 = (T)std::min(x - 1>=0?res(x - 1,y,z):M,x + 1<width()?res(x + 1,y,z):M); Tfloat root = 0; if (_depth>1) { // 3D T T2 = (T)std::min(y - 1>=0?res(x,y - 1,z):M,y + 1<height()?res(x,y + 1,z):M), T3 = (T)std::min(z - 1>=0?res(x,y,z - 1):M,z + 1<depth()?res(x,y,z + 1):M); if (T1>T2) cimg::swap(T1,T2); if (T2>T3) cimg::swap(T2,T3); if (T1>T2) cimg::swap(T1,T2); if (P<=0) return (Tfloat)T1; if (T3<M && ___distance_eikonal(3,-2*(T1 + T2 + T3),T1*T1 + T2*T2 + T3*T3 - P*P,root)) return std::max((Tfloat)T3,root); if (T2<M && ___distance_eikonal(2,-2*(T1 + T2),T1*T1 + T2*T2 - P*P,root)) return std::max((Tfloat)T2,root); return P + T1; } else if (_height>1) { // 2D T T2 = (T)std::min(y - 1>=0?res(x,y - 1,z):M,y + 1<height()?res(x,y + 1,z):M); if (T1>T2) cimg::swap(T1,T2); if (P<=0) return (Tfloat)T1; if (T2<M && ___distance_eikonal(2,-2*(T1 + T2),T1*T1 + T2*T2 - P*P,root)) return std::max((Tfloat)T2,root); return P + T1; } else { // 1D if (P<=0) return (Tfloat)T1; return P + T1; } return 0; } // Find max root of a 2nd-order polynomial. static bool ___distance_eikonal(const Tfloat a, const Tfloat b, const Tfloat c, Tfloat &root) { const Tfloat delta = b*b - 4*a*c; if (delta<0) return false; root = 0.5f*(-b + std::sqrt(delta))/a; return true; } // Insert new point in heap. template<typename t> void _eik_priority_queue_insert(CImg<charT>& state, unsigned int& siz, const t value, const unsigned int x, const unsigned int y, const unsigned int z) { if (state(x,y,z)>0) return; state(x,y,z) = 0; if (++siz>=_width) { if (!is_empty()) resize(_width*2,4,1,1,0); else assign(64,4); } (*this)(siz - 1,0) = (T)value; (*this)(siz - 1,1) = (T)x; (*this)(siz - 1,2) = (T)y; (*this)(siz - 1,3) = (T)z; for (unsigned int pos = siz - 1, par = 0; pos && value>(t)(*this)(par=(pos + 1)/2 - 1,0); pos = par) { cimg::swap((*this)(pos,0),(*this)(par,0)); cimg::swap((*this)(pos,1),(*this)(par,1)); cimg::swap((*this)(pos,2),(*this)(par,2)); cimg::swap((*this)(pos,3),(*this)(par,3)); } } //! Compute distance function to 0-valued isophotes, using the Eikonal PDE. /** \param nb_iterations Number of PDE iterations. \param band_size Size of the narrow band. \param time_step Time step of the PDE iterations. **/ CImg<T>& distance_eikonal(const unsigned int nb_iterations, const float band_size=0, const float time_step=0.5f) { if (is_empty()) return *this; CImg<Tfloat> velocity(*this,false); for (unsigned int iteration = 0; iteration<nb_iterations; ++iteration) { Tfloat *ptrd = velocity._data, veloc_max = 0; if (_depth>1) { // 3D CImg_3x3x3(I,Tfloat); cimg_forC(*this,c) cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) if (band_size<=0 || cimg::abs(Iccc)<band_size) { const Tfloat gx = (Incc - Ipcc)/2, gy = (Icnc - Icpc)/2, gz = (Iccn - Iccp)/2, sgn = -cimg::sign(Iccc), ix = gx*sgn>0?(Incc - Iccc):(Iccc - Ipcc), iy = gy*sgn>0?(Icnc - Iccc):(Iccc - Icpc), iz = gz*sgn>0?(Iccn - Iccc):(Iccc - Iccp), ng = 1e-5f + cimg::hypot(gx,gy,gz), ngx = gx/ng, ngy = gy/ng, ngz = gz/ng, veloc = sgn*(ngx*ix + ngy*iy + ngz*iz - 1); *(ptrd++) = veloc; if (veloc>veloc_max) veloc_max = veloc; else if (-veloc>veloc_max) veloc_max = -veloc; } else *(ptrd++) = 0; } else { // 2D version CImg_3x3(I,Tfloat); cimg_forC(*this,c) cimg_for3x3(*this,x,y,0,c,I,Tfloat) if (band_size<=0 || cimg::abs(Icc)<band_size) { const Tfloat gx = (Inc - Ipc)/2, gy = (Icn - Icp)/2, sgn = -cimg::sign(Icc), ix = gx*sgn>0?(Inc - Icc):(Icc - Ipc), iy = gy*sgn>0?(Icn - Icc):(Icc - Icp), ng = std::max((Tfloat)1e-5,cimg::hypot(gx,gy)), ngx = gx/ng, ngy = gy/ng, veloc = sgn*(ngx*ix + ngy*iy - 1); *(ptrd++) = veloc; if (veloc>veloc_max) veloc_max = veloc; else if (-veloc>veloc_max) veloc_max = -veloc; } else *(ptrd++) = 0; } if (veloc_max>0) *this+=(velocity*=time_step/veloc_max); } return *this; } //! Compute distance function to 0-valued isophotes, using the Eikonal PDE \newinstance. CImg<Tfloat> get_distance_eikonal(const unsigned int nb_iterations, const float band_size=0, const float time_step=0.5f) const { return CImg<Tfloat>(*this,false).distance_eikonal(nb_iterations,band_size,time_step); } //! Compute Haar multiscale wavelet transform. /** \param axis Axis considered for the transform. \param invert Set inverse of direct transform. \param nb_scales Number of scales used for the transform. **/ CImg<T>& haar(const char axis, const bool invert=false, const unsigned int nb_scales=1) { return get_haar(axis,invert,nb_scales).move_to(*this); } //! Compute Haar multiscale wavelet transform \newinstance. CImg<Tfloat> get_haar(const char axis, const bool invert=false, const unsigned int nb_scales=1) const { if (is_empty() || !nb_scales) return +*this; CImg<Tfloat> res; const Tfloat sqrt2 = std::sqrt(2.f); if (nb_scales==1) { switch (cimg::lowercase(axis)) { // Single scale transform case 'x' : { const unsigned int w = _width/2; if (w) { if ((w%2) && w!=1) throw CImgInstanceException(_cimg_instance "haar(): Sub-image width %u is not even.", cimg_instance, w); res.assign(_width,_height,_depth,_spectrum); if (invert) cimg_forYZC(*this,y,z,c) { // Inverse transform along X for (unsigned int x = 0, xw = w, x2 = 0; x<w; ++x, ++xw) { const Tfloat val0 = (Tfloat)(*this)(x,y,z,c), val1 = (Tfloat)(*this)(xw,y,z,c); res(x2++,y,z,c) = (val0 - val1)/sqrt2; res(x2++,y,z,c) = (val0 + val1)/sqrt2; } } else cimg_forYZC(*this,y,z,c) { // Direct transform along X for (unsigned int x = 0, xw = w, x2 = 0; x<w; ++x, ++xw) { const Tfloat val0 = (Tfloat)(*this)(x2++,y,z,c), val1 = (Tfloat)(*this)(x2++,y,z,c); res(x,y,z,c) = (val0 + val1)/sqrt2; res(xw,y,z,c) = (val1 - val0)/sqrt2; } } } else return *this; } break; case 'y' : { const unsigned int h = _height/2; if (h) { if ((h%2) && h!=1) throw CImgInstanceException(_cimg_instance "haar(): Sub-image height %u is not even.", cimg_instance, h); res.assign(_width,_height,_depth,_spectrum); if (invert) cimg_forXZC(*this,x,z,c) { // Inverse transform along Y for (unsigned int y = 0, yh = h, y2 = 0; y<h; ++y, ++yh) { const Tfloat val0 = (Tfloat)(*this)(x,y,z,c), val1 = (Tfloat)(*this)(x,yh,z,c); res(x,y2++,z,c) = (val0 - val1)/sqrt2; res(x,y2++,z,c) = (val0 + val1)/sqrt2; } } else cimg_forXZC(*this,x,z,c) { for (unsigned int y = 0, yh = h, y2 = 0; y<h; ++y, ++yh) { // Direct transform along Y const Tfloat val0 = (Tfloat)(*this)(x,y2++,z,c), val1 = (Tfloat)(*this)(x,y2++,z,c); res(x,y,z,c) = (val0 + val1)/sqrt2; res(x,yh,z,c) = (val1 - val0)/sqrt2; } } } else return *this; } break; case 'z' : { const unsigned int d = _depth/2; if (d) { if ((d%2) && d!=1) throw CImgInstanceException(_cimg_instance "haar(): Sub-image depth %u is not even.", cimg_instance, d); res.assign(_width,_height,_depth,_spectrum); if (invert) cimg_forXYC(*this,x,y,c) { // Inverse transform along Z for (unsigned int z = 0, zd = d, z2 = 0; z<d; ++z, ++zd) { const Tfloat val0 = (Tfloat)(*this)(x,y,z,c), val1 = (Tfloat)(*this)(x,y,zd,c); res(x,y,z2++,c) = (val0 - val1)/sqrt2; res(x,y,z2++,c) = (val0 + val1)/sqrt2; } } else cimg_forXYC(*this,x,y,c) { for (unsigned int z = 0, zd = d, z2 = 0; z<d; ++z, ++zd) { // Direct transform along Z const Tfloat val0 = (Tfloat)(*this)(x,y,z2++,c), val1 = (Tfloat)(*this)(x,y,z2++,c); res(x,y,z,c) = (val0 + val1)/sqrt2; res(x,y,zd,c) = (val1 - val0)/sqrt2; } } } else return *this; } break; default : throw CImgArgumentException(_cimg_instance "haar(): Invalid specified axis '%c' " "(should be { x | y | z }).", cimg_instance, axis); } } else { // Multi-scale version if (invert) { res.assign(*this,false); switch (cimg::lowercase(axis)) { case 'x' : { unsigned int w = _width; for (unsigned int s = 1; w && s<nb_scales; ++s) w/=2; for (w = w?w:1; w<=_width; w*=2) res.draw_image(res.get_crop(0,w - 1).get_haar('x',true,1)); } break; case 'y' : { unsigned int h = _width; for (unsigned int s = 1; h && s<nb_scales; ++s) h/=2; for (h = h?h:1; h<=_height; h*=2) res.draw_image(res.get_crop(0,0,_width - 1,h - 1).get_haar('y',true,1)); } break; case 'z' : { unsigned int d = _depth; for (unsigned int s = 1; d && s<nb_scales; ++s) d/=2; for (d = d?d:1; d<=_depth; d*=2) res.draw_image(res.get_crop(0,0,0,_width - 1,_height - 1,d - 1).get_haar('z',true,1)); } break; default : throw CImgArgumentException(_cimg_instance "haar(): Invalid specified axis '%c' " "(should be { x | y | z }).", cimg_instance, axis); } } else { // Direct transform res = get_haar(axis,false,1); switch (cimg::lowercase(axis)) { case 'x' : { for (unsigned int s = 1, w = _width/2; w && s<nb_scales; ++s, w/=2) res.draw_image(res.get_crop(0,w - 1).get_haar('x',false,1)); } break; case 'y' : { for (unsigned int s = 1, h = _height/2; h && s<nb_scales; ++s, h/=2) res.draw_image(res.get_crop(0,0,_width - 1,h - 1).get_haar('y',false,1)); } break; case 'z' : { for (unsigned int s = 1, d = _depth/2; d && s<nb_scales; ++s, d/=2) res.draw_image(res.get_crop(0,0,0,_width - 1,_height - 1,d - 1).get_haar('z',false,1)); } break; default : throw CImgArgumentException(_cimg_instance "haar(): Invalid specified axis '%c' " "(should be { x | y | z }).", cimg_instance, axis); } } } return res; } //! Compute Haar multiscale wavelet transform \overloading. /** \param invert Set inverse of direct transform. \param nb_scales Number of scales used for the transform. **/ CImg<T>& haar(const bool invert=false, const unsigned int nb_scales=1) { return get_haar(invert,nb_scales).move_to(*this); } //! Compute Haar multiscale wavelet transform \newinstance. CImg<Tfloat> get_haar(const bool invert=false, const unsigned int nb_scales=1) const { CImg<Tfloat> res; if (nb_scales==1) { // Single scale transform if (_width>1) get_haar('x',invert,1).move_to(res); if (_height>1) { if (res) res.haar('y',invert,1); else get_haar('y',invert,1).move_to(res); } if (_depth>1) { if (res) res.haar('z',invert,1); else get_haar('z',invert,1).move_to(res); } if (res) return res; } else { // Multi-scale transform if (invert) { // Inverse transform res.assign(*this,false); if (_width>1) { if (_height>1) { if (_depth>1) { unsigned int w = _width, h = _height, d = _depth; for (unsigned int s = 1; w && h && d && s<nb_scales; ++s) { w/=2; h/=2; d/=2; } for (w = w?w:1, h = h?h:1, d = d?d:1; w<=_width && h<=_height && d<=_depth; w*=2, h*=2, d*=2) res.draw_image(res.get_crop(0,0,0,w - 1,h - 1,d - 1).get_haar(true,1)); } else { unsigned int w = _width, h = _height; for (unsigned int s = 1; w && h && s<nb_scales; ++s) { w/=2; h/=2; } for (w = w?w:1, h = h?h:1; w<=_width && h<=_height; w*=2, h*=2) res.draw_image(res.get_crop(0,0,0,w - 1,h - 1,0).get_haar(true,1)); } } else { if (_depth>1) { unsigned int w = _width, d = _depth; for (unsigned int s = 1; w && d && s<nb_scales; ++s) { w/=2; d/=2; } for (w = w?w:1, d = d?d:1; w<=_width && d<=_depth; w*=2, d*=2) res.draw_image(res.get_crop(0,0,0,w - 1,0,d - 1).get_haar(true,1)); } else { unsigned int w = _width; for (unsigned int s = 1; w && s<nb_scales; ++s) w/=2; for (w = w?w:1; w<=_width; w*=2) res.draw_image(res.get_crop(0,0,0,w - 1,0,0).get_haar(true,1)); } } } else { if (_height>1) { if (_depth>1) { unsigned int h = _height, d = _depth; for (unsigned int s = 1; h && d && s<nb_scales; ++s) { h/=2; d/=2; } for (h = h?h:1, d = d?d:1; h<=_height && d<=_depth; h*=2, d*=2) res.draw_image(res.get_crop(0,0,0,0,h - 1,d - 1).get_haar(true,1)); } else { unsigned int h = _height; for (unsigned int s = 1; h && s<nb_scales; ++s) h/=2; for (h = h?h:1; h<=_height; h*=2) res.draw_image(res.get_crop(0,0,0,0,h - 1,0).get_haar(true,1)); } } else { if (_depth>1) { unsigned int d = _depth; for (unsigned int s = 1; d && s<nb_scales; ++s) d/=2; for (d = d?d:1; d<=_depth; d*=2) res.draw_image(res.get_crop(0,0,0,0,0,d - 1).get_haar(true,1)); } else return *this; } } } else { // Direct transform res = get_haar(false,1); if (_width>1) { if (_height>1) { if (_depth>1) for (unsigned int s = 1, w = _width/2, h = _height/2, d = _depth/2; w && h && d && s<nb_scales; ++s, w/=2, h/=2, d/=2) res.draw_image(res.get_crop(0,0,0,w - 1,h - 1,d - 1).haar(false,1)); else for (unsigned int s = 1, w = _width/2, h = _height/2; w && h && s<nb_scales; ++s, w/=2, h/=2) res.draw_image(res.get_crop(0,0,0,w - 1,h - 1,0).haar(false,1)); } else { if (_depth>1) for (unsigned int s = 1, w = _width/2, d = _depth/2; w && d && s<nb_scales; ++s, w/=2, d/=2) res.draw_image(res.get_crop(0,0,0,w - 1,0,d - 1).haar(false,1)); else for (unsigned int s = 1, w = _width/2; w && s<nb_scales; ++s, w/=2) res.draw_image(res.get_crop(0,0,0,w - 1,0,0).haar(false,1)); } } else { if (_height>1) { if (_depth>1) for (unsigned int s = 1, h = _height/2, d = _depth/2; h && d && s<nb_scales; ++s, h/=2, d/=2) res.draw_image(res.get_crop(0,0,0,0,h - 1,d - 1).haar(false,1)); else for (unsigned int s = 1, h = _height/2; h && s<nb_scales; ++s, h/=2) res.draw_image(res.get_crop(0,0,0,0,h - 1,0).haar(false,1)); } else { if (_depth>1) for (unsigned int s = 1, d = _depth/2; d && s<nb_scales; ++s, d/=2) res.draw_image(res.get_crop(0,0,0,0,0,d - 1).haar(false,1)); else return *this; } } } return res; } return *this; } //! Compute 1D Fast Fourier Transform, along a specified axis. /** \param axis Axis along which the FFT is computed. \param is_inverse Tells if the forward (\c false) or inverse (\c true) FFT is computed. **/ CImgList<Tfloat> get_FFT(const char axis, const bool is_inverse=false) const { CImgList<Tfloat> res(*this,CImg<Tfloat>()); CImg<Tfloat>::FFT(res[0],res[1],axis,is_inverse); return res; } //! Compute n-D Fast Fourier Transform. /* \param is_inverse Tells if the forward (\c false) or inverse (\c true) FFT is computed. **/ CImgList<Tfloat> get_FFT(const bool is_inverse=false) const { CImgList<Tfloat> res(*this,CImg<Tfloat>()); CImg<Tfloat>::FFT(res[0],res[1],is_inverse); return res; } //! Compute 1D Fast Fourier Transform, along a specified axis. /** \param[in,out] real Real part of the pixel values. \param[in,out] imag Imaginary part of the pixel values. \param axis Axis along which the FFT is computed. \param is_inverse Tells if the forward (\c false) or inverse (\c true) FFT is computed. **/ static void FFT(CImg<T>& real, CImg<T>& imag, const char axis, const bool is_inverse=false, const unsigned int nb_threads=0) { if (!real) throw CImgInstanceException("CImg<%s>::FFT(): Specified real part is empty.", pixel_type()); if (!imag) imag.assign(real._width,real._height,real._depth,real._spectrum,(T)0); if (!real.is_sameXYZC(imag)) throw CImgInstanceException("CImg<%s>::FFT(): Specified real part (%u,%u,%u,%u,%p) and " "imaginary part (%u,%u,%u,%u,%p) have different dimensions.", pixel_type(), real._width,real._height,real._depth,real._spectrum,real._data, imag._width,imag._height,imag._depth,imag._spectrum,imag._data); const char _axis = cimg::lowercase(axis); if (_axis!='x' && _axis!='y' && _axis!='z') throw CImgArgumentException("CImgList<%s>::FFT(): Invalid specified axis '%c' for real and imaginary parts " "(%u,%u,%u,%u) " "(should be { x | y | z }).", pixel_type(),axis, real._width,real._height,real._depth,real._spectrum); cimg::unused(nb_threads); #ifdef cimg_use_fftw3 cimg::mutex(12); #ifndef cimg_use_fftw3_singlethread fftw_plan_with_nthreads(nb_threads?nb_threads:cimg::nb_cpus()); #endif fftw_complex *data_in = (fftw_complex*)fftw_malloc(sizeof(fftw_complex)*real._width*real._height*real._depth); if (!data_in) throw CImgInstanceException("CImgList<%s>::FFT(): Failed to allocate memory (%s) " "for computing FFT of image (%u,%u,%u,%u) along the X-axis.", pixel_type(), cimg::strbuffersize(sizeof(fftw_complex)*real._width), real._width,real._height,real._depth,real._spectrum); double *const ptrf = (double*)data_in; fftw_plan data_plan = _axis=='x'?fftw_plan_many_dft(1,(int*)&real._width,real.height()*real.depth(), data_in,0,1,real.width(), data_in,0,1,real.width(), is_inverse?FFTW_BACKWARD:FFTW_FORWARD,FFTW_ESTIMATE): _axis=='y'?fftw_plan_many_dft(1,(int*)&real._height,real.width()*real.depth(), data_in,0,real.width(),1, data_in,0,real.width(),1, is_inverse?FFTW_BACKWARD:FFTW_FORWARD,FFTW_ESTIMATE): fftw_plan_many_dft(1,(int*)&real._depth,real.width()*real.height(), data_in,0,real.width()*real.height(),1, data_in,0,real.width()*real.height(),1, is_inverse?FFTW_BACKWARD:FFTW_FORWARD,FFTW_ESTIMATE); cimg_forC(real,c) { CImg<T> realc = real.get_shared_channel(c), imagc = imag.get_shared_channel(c); cimg_pragma_openmp(parallel for cimg_openmp_if_size(real.width()*real.height()*real.depth(),125000)) cimg_rofoff(realc,i) { const ulongT i2 = 2*i; ptrf[i2] = (double)realc[i]; ptrf[i2 + 1] = (double)imagc[i]; } fftw_execute(data_plan); if (is_inverse) { const double a = 1.0/(_axis=='x'?real.width():_axis=='y'?real.height():real.depth()); cimg_pragma_openmp(parallel for cimg_openmp_if_size(real.width()*real.height()*real.depth(),125000)) cimg_rofoff(realc,i) { const ulongT i2 = 2*i; realc[i] = (T)(a*ptrf[i2]); imagc[i] = (T)(a*ptrf[i2 + 1]); } } else cimg_pragma_openmp(parallel for cimg_openmp_if_size(real.width()*real.height()*real.depth(),125000)) cimg_rofoff(realc,i) { const ulongT i2 = 2*i; realc[i] = (T)ptrf[i2]; imagc[i] = (T)ptrf[i2 + 1]; } } fftw_destroy_plan(data_plan); fftw_free(data_in); #ifndef cimg_use_fftw3_singlethread fftw_cleanup_threads(); #endif cimg::mutex(12,0); #else switch (_axis) { case 'x' : { // Fourier along X, using built-in functions const unsigned int N = real._width, N2 = N>>1; if (((N - 1)&N) && N!=1) throw CImgInstanceException("CImgList<%s>::FFT(): Specified real and imaginary parts (%u,%u,%u,%u) " "have non 2^N dimension along the X-axis.", pixel_type(), real._width,real._height,real._depth,real._spectrum); for (unsigned int i = 0, j = 0; i<N2; ++i) { if (j>i) cimg_forYZC(real,y,z,c) { cimg::swap(real(i,y,z,c),real(j,y,z,c)); cimg::swap(imag(i,y,z,c),imag(j,y,z,c)); if (j<N2) { const unsigned int ri = N - 1 - i, rj = N - 1 - j; cimg::swap(real(ri,y,z,c),real(rj,y,z,c)); cimg::swap(imag(ri,y,z,c),imag(rj,y,z,c)); } } for (unsigned int m = N, n = N2; (j+=n)>=m; j-=m, m = n, n>>=1) {} } for (unsigned int delta = 2; delta<=N; delta<<=1) { const unsigned int delta2 = delta>>1; for (unsigned int i = 0; i<N; i+=delta) { float wr = 1, wi = 0; const float angle = (float)((is_inverse?+1:-1)*2*cimg::PI/delta), ca = (float)std::cos(angle), sa = (float)std::sin(angle); for (unsigned int k = 0; k<delta2; ++k) { const unsigned int j = i + k, nj = j + delta2; cimg_forYZC(real,y,z,c) { T &ir = real(j,y,z,c), &ii = imag(j,y,z,c), &nir = real(nj,y,z,c), &nii = imag(nj,y,z,c); const float tmpr = (float)(wr*nir - wi*nii), tmpi = (float)(wr*nii + wi*nir); nir = (T)(ir - tmpr); nii = (T)(ii - tmpi); ir+=(T)tmpr; ii+=(T)tmpi; } const float nwr = wr*ca-wi*sa; wi = wi*ca + wr*sa; wr = nwr; } } } if (is_inverse) { real/=N; imag/=N; } } break; case 'y' : { // Fourier along Y, using built-in functions const unsigned int N = real._height, N2 = N>>1; if (((N - 1)&N) && N!=1) throw CImgInstanceException("CImgList<%s>::FFT(): Specified real and imaginary parts (%u,%u,%u,%u) " "have non 2^N dimension along the Y-axis.", pixel_type(), real._width,real._height,real._depth,real._spectrum); for (unsigned int i = 0, j = 0; i<N2; ++i) { if (j>i) cimg_forXZC(real,x,z,c) { cimg::swap(real(x,i,z,c),real(x,j,z,c)); cimg::swap(imag(x,i,z,c),imag(x,j,z,c)); if (j<N2) { const unsigned int ri = N - 1 - i, rj = N - 1 - j; cimg::swap(real(x,ri,z,c),real(x,rj,z,c)); cimg::swap(imag(x,ri,z,c),imag(x,rj,z,c)); } } for (unsigned int m = N, n = N2; (j+=n)>=m; j-=m, m = n, n>>=1) {} } for (unsigned int delta = 2; delta<=N; delta<<=1) { const unsigned int delta2 = (delta>>1); for (unsigned int i = 0; i<N; i+=delta) { float wr = 1, wi = 0; const float angle = (float)((is_inverse?+1:-1)*2*cimg::PI/delta), ca = (float)std::cos(angle), sa = (float)std::sin(angle); for (unsigned int k = 0; k<delta2; ++k) { const unsigned int j = i + k, nj = j + delta2; cimg_forXZC(real,x,z,c) { T &ir = real(x,j,z,c), &ii = imag(x,j,z,c), &nir = real(x,nj,z,c), &nii = imag(x,nj,z,c); const float tmpr = (float)(wr*nir - wi*nii), tmpi = (float)(wr*nii + wi*nir); nir = (T)(ir - tmpr); nii = (T)(ii - tmpi); ir+=(T)tmpr; ii+=(T)tmpi; } const float nwr = wr*ca-wi*sa; wi = wi*ca + wr*sa; wr = nwr; } } } if (is_inverse) { real/=N; imag/=N; } } break; default : { // Fourier along Z, using built-in functions const unsigned int N = real._depth, N2 = N>>1; if (((N - 1)&N) && N!=1) throw CImgInstanceException("CImgList<%s>::FFT(): Specified real and imaginary parts (%u,%u,%u,%u) " "have non 2^N dimension along the Z-axis.", pixel_type(), real._width,real._height,real._depth,real._spectrum); for (unsigned int i = 0, j = 0; i<N2; ++i) { if (j>i) cimg_forXYC(real,x,y,c) { cimg::swap(real(x,y,i,c),real(x,y,j,c)); cimg::swap(imag(x,y,i,c),imag(x,y,j,c)); if (j<N2) { const unsigned int ri = N - 1 - i, rj = N - 1 - j; cimg::swap(real(x,y,ri,c),real(x,y,rj,c)); cimg::swap(imag(x,y,ri,c),imag(x,y,rj,c)); } } for (unsigned int m = N, n = N2; (j+=n)>=m; j-=m, m = n, n>>=1) {} } for (unsigned int delta = 2; delta<=N; delta<<=1) { const unsigned int delta2 = (delta>>1); for (unsigned int i = 0; i<N; i+=delta) { float wr = 1, wi = 0; const float angle = (float)((is_inverse?+1:-1)*2*cimg::PI/delta), ca = (float)std::cos(angle), sa = (float)std::sin(angle); for (unsigned int k = 0; k<delta2; ++k) { const unsigned int j = i + k, nj = j + delta2; cimg_forXYC(real,x,y,c) { T &ir = real(x,y,j,c), &ii = imag(x,y,j,c), &nir = real(x,y,nj,c), &nii = imag(x,y,nj,c); const float tmpr = (float)(wr*nir - wi*nii), tmpi = (float)(wr*nii + wi*nir); nir = (T)(ir - tmpr); nii = (T)(ii - tmpi); ir+=(T)tmpr; ii+=(T)tmpi; } const float nwr = wr*ca-wi*sa; wi = wi*ca + wr*sa; wr = nwr; } } } if (is_inverse) { real/=N; imag/=N; } } break; } #endif } //! Compute n-D Fast Fourier Transform. /** \param[in,out] real Real part of the pixel values. \param[in,out] imag Imaginary part of the pixel values. \param is_inverse Tells if the forward (\c false) or inverse (\c true) FFT is computed. \param nb_threads Number of parallel threads used for the computation. Use \c 0 to set this to the number of available cpus. **/ static void FFT(CImg<T>& real, CImg<T>& imag, const bool is_inverse=false, const unsigned int nb_threads=0) { if (!real) throw CImgInstanceException("CImgList<%s>::FFT(): Empty specified real part.", pixel_type()); if (!imag) imag.assign(real._width,real._height,real._depth,real._spectrum,(T)0); if (!real.is_sameXYZC(imag)) throw CImgInstanceException("CImgList<%s>::FFT(): Specified real part (%u,%u,%u,%u,%p) and " "imaginary part (%u,%u,%u,%u,%p) have different dimensions.", pixel_type(), real._width,real._height,real._depth,real._spectrum,real._data, imag._width,imag._height,imag._depth,imag._spectrum,imag._data); cimg::unused(nb_threads); #ifdef cimg_use_fftw3 cimg::mutex(12); #ifndef cimg_use_fftw3_singlethread fftw_plan_with_nthreads(nb_threads?nb_threads:cimg::nb_cpus()); #endif fftw_complex *data_in = (fftw_complex*)fftw_malloc(sizeof(fftw_complex)*real._width*real._height*real._depth); if (!data_in) throw CImgInstanceException("CImgList<%s>::FFT(): Failed to allocate memory (%s) " "for computing FFT of image (%u,%u,%u,%u).", pixel_type(), cimg::strbuffersize(sizeof(fftw_complex)*real._width* real._height*real._depth*real._spectrum), real._width,real._height,real._depth,real._spectrum); double *const ptrf = (double*)data_in; fftw_plan data_plan = real._depth>1?fftw_plan_dft_3d(real._depth,real._height,real._width,data_in,data_in, is_inverse?FFTW_BACKWARD:FFTW_FORWARD,FFTW_ESTIMATE): real._height>1?fftw_plan_dft_2d(real._height,real._width,data_in,data_in, is_inverse?FFTW_BACKWARD:FFTW_FORWARD,FFTW_ESTIMATE): fftw_plan_dft_1d(real._width,data_in,data_in, is_inverse?FFTW_BACKWARD:FFTW_FORWARD,FFTW_ESTIMATE); cimg_forC(real,c) { CImg<T> realc = real.get_shared_channel(c), imagc = imag.get_shared_channel(c); cimg_pragma_openmp(parallel for cimg_openmp_if_size(real.width()*real.height()*real.depth(),125000)) cimg_rofoff(realc,i) { const ulongT i2 = 2*i; ptrf[i2] = (double)realc[i]; ptrf[i2 + 1] = (double)imagc[i]; } fftw_execute(data_plan); if (is_inverse) { const double a = 1.0/(real.width()*real.height()*real.depth()); cimg_pragma_openmp(parallel for cimg_openmp_if_size(real.width()*real.height()*real.depth(),125000)) cimg_rofoff(realc,i) { const ulongT i2 = 2*i; realc[i] = (T)(a*ptrf[i2]); imagc[i] = (T)(a*ptrf[i2 + 1]); } } else cimg_pragma_openmp(parallel for cimg_openmp_if_size(real.width()*real.height()*real.depth(),125000)) cimg_rofoff(realc,i) { const ulongT i2 = 2*i; realc[i] = (T)ptrf[i2]; imagc[i] = (T)ptrf[i2 + 1]; } } fftw_destroy_plan(data_plan); fftw_free(data_in); #ifndef cimg_use_fftw3_singlethread fftw_cleanup_threads(); #endif cimg::mutex(12,0); #else if (real._depth>1) FFT(real,imag,'z',is_inverse); if (real._height>1) FFT(real,imag,'y',is_inverse); if (real._width>1) FFT(real,imag,'x',is_inverse); #endif } //@} //------------------------------------- // //! \name 3D Objects Management //@{ //------------------------------------- //! Shift 3D object's vertices. /** \param tx X-coordinate of the 3D displacement vector. \param ty Y-coordinate of the 3D displacement vector. \param tz Z-coordinate of the 3D displacement vector. **/ CImg<T>& shift_object3d(const float tx, const float ty=0, const float tz=0) { if (_height!=3 || _depth>1 || _spectrum>1) throw CImgInstanceException(_cimg_instance "shift_object3d(): Instance is not a set of 3D vertices.", cimg_instance); get_shared_row(0)+=tx; get_shared_row(1)+=ty; get_shared_row(2)+=tz; return *this; } //! Shift 3D object's vertices \newinstance. CImg<Tfloat> get_shift_object3d(const float tx, const float ty=0, const float tz=0) const { return CImg<Tfloat>(*this,false).shift_object3d(tx,ty,tz); } //! Shift 3D object's vertices, so that it becomes centered. /** \note The object center is computed as its barycenter. **/ CImg<T>& shift_object3d() { if (_height!=3 || _depth>1 || _spectrum>1) throw CImgInstanceException(_cimg_instance "shift_object3d(): Instance is not a set of 3D vertices.", cimg_instance); CImg<T> xcoords = get_shared_row(0), ycoords = get_shared_row(1), zcoords = get_shared_row(2); float xm, xM = (float)xcoords.max_min(xm), ym, yM = (float)ycoords.max_min(ym), zm, zM = (float)zcoords.max_min(zm); xcoords-=(xm + xM)/2; ycoords-=(ym + yM)/2; zcoords-=(zm + zM)/2; return *this; } //! Shift 3D object's vertices, so that it becomes centered \newinstance. CImg<Tfloat> get_shift_object3d() const { return CImg<Tfloat>(*this,false).shift_object3d(); } //! Resize 3D object. /** \param sx Width of the 3D object's bounding box. \param sy Height of the 3D object's bounding box. \param sz Depth of the 3D object's bounding box. **/ CImg<T>& resize_object3d(const float sx, const float sy=-100, const float sz=-100) { if (_height!=3 || _depth>1 || _spectrum>1) throw CImgInstanceException(_cimg_instance "resize_object3d(): Instance is not a set of 3D vertices.", cimg_instance); CImg<T> xcoords = get_shared_row(0), ycoords = get_shared_row(1), zcoords = get_shared_row(2); float xm, xM = (float)xcoords.max_min(xm), ym, yM = (float)ycoords.max_min(ym), zm, zM = (float)zcoords.max_min(zm); if (xm<xM) { if (sx>0) xcoords*=sx/(xM-xm); else xcoords*=-sx/100; } if (ym<yM) { if (sy>0) ycoords*=sy/(yM-ym); else ycoords*=-sy/100; } if (zm<zM) { if (sz>0) zcoords*=sz/(zM-zm); else zcoords*=-sz/100; } return *this; } //! Resize 3D object \newinstance. CImg<Tfloat> get_resize_object3d(const float sx, const float sy=-100, const float sz=-100) const { return CImg<Tfloat>(*this,false).resize_object3d(sx,sy,sz); } //! Resize 3D object to unit size. CImg<T> resize_object3d() { if (_height!=3 || _depth>1 || _spectrum>1) throw CImgInstanceException(_cimg_instance "resize_object3d(): Instance is not a set of 3D vertices.", cimg_instance); CImg<T> xcoords = get_shared_row(0), ycoords = get_shared_row(1), zcoords = get_shared_row(2); float xm, xM = (float)xcoords.max_min(xm), ym, yM = (float)ycoords.max_min(ym), zm, zM = (float)zcoords.max_min(zm); const float dx = xM - xm, dy = yM - ym, dz = zM - zm, dmax = cimg::max(dx,dy,dz); if (dmax>0) { xcoords/=dmax; ycoords/=dmax; zcoords/=dmax; } return *this; } //! Resize 3D object to unit size \newinstance. CImg<Tfloat> get_resize_object3d() const { return CImg<Tfloat>(*this,false).resize_object3d(); } //! Merge two 3D objects together. /** \param[in,out] primitives Primitives data of the current 3D object. \param obj_vertices Vertices data of the additional 3D object. \param obj_primitives Primitives data of the additional 3D object. **/ template<typename tf, typename tp, typename tff> CImg<T>& append_object3d(CImgList<tf>& primitives, const CImg<tp>& obj_vertices, const CImgList<tff>& obj_primitives) { if (!obj_vertices || !obj_primitives) return *this; if (obj_vertices._height!=3 || obj_vertices._depth>1 || obj_vertices._spectrum>1) throw CImgInstanceException(_cimg_instance "append_object3d(): Specified vertice image (%u,%u,%u,%u,%p) is not a " "set of 3D vertices.", cimg_instance, obj_vertices._width,obj_vertices._height, obj_vertices._depth,obj_vertices._spectrum,obj_vertices._data); if (is_empty()) { primitives.assign(obj_primitives); return assign(obj_vertices); } if (_height!=3 || _depth>1 || _spectrum>1) throw CImgInstanceException(_cimg_instance "append_object3d(): Instance is not a set of 3D vertices.", cimg_instance); const unsigned int P = _width; append(obj_vertices,'x'); const unsigned int N = primitives._width; primitives.insert(obj_primitives); for (unsigned int i = N; i<primitives._width; ++i) { CImg<tf> &p = primitives[i]; switch (p.size()) { case 1 : p[0]+=P; break; // Point case 5 : p[0]+=P; p[1]+=P; break; // Sphere case 2 : case 6 : p[0]+=P; p[1]+=P; break; // Segment case 3 : case 9 : p[0]+=P; p[1]+=P; p[2]+=P; break; // Triangle case 4 : case 12 : p[0]+=P; p[1]+=P; p[2]+=P; p[3]+=P; break; // Rectangle } } return *this; } //! Texturize primitives of a 3D object. /** \param[in,out] primitives Primitives data of the 3D object. \param[in,out] colors Colors data of the 3D object. \param texture Texture image to map to 3D object. \param coords Texture-mapping coordinates. **/ template<typename tp, typename tc, typename tt, typename tx> const CImg<T>& texturize_object3d(CImgList<tp>& primitives, CImgList<tc>& colors, const CImg<tt>& texture, const CImg<tx>& coords=CImg<tx>::const_empty()) const { if (is_empty()) return *this; if (_height!=3) throw CImgInstanceException(_cimg_instance "texturize_object3d(): image instance is not a set of 3D points.", cimg_instance); if (coords && (coords._width!=_width || coords._height!=2)) throw CImgArgumentException(_cimg_instance "texturize_object3d(): Invalid specified texture coordinates (%u,%u,%u,%u,%p).", cimg_instance, coords._width,coords._height,coords._depth,coords._spectrum,coords._data); CImg<intT> _coords; if (!coords) { // If no texture coordinates specified, do a default XY-projection _coords.assign(_width,2); float xmin, xmax = (float)get_shared_row(0).max_min(xmin), ymin, ymax = (float)get_shared_row(1).max_min(ymin), dx = xmax>xmin?xmax-xmin:1, dy = ymax>ymin?ymax-ymin:1; cimg_forX(*this,p) { _coords(p,0) = (int)(((*this)(p,0) - xmin)*texture._width/dx); _coords(p,1) = (int)(((*this)(p,1) - ymin)*texture._height/dy); } } else _coords = coords; int texture_ind = -1; cimglist_for(primitives,l) { CImg<tp> &p = primitives[l]; const unsigned int siz = p.size(); switch (siz) { case 1 : { // Point const unsigned int i0 = (unsigned int)p[0]; const int x0 = _coords(i0,0), y0 = _coords(i0,1); texture.get_vector_at(x0<=0?0:x0>=texture.width()?texture.width() - 1:x0, y0<=0?0:y0>=texture.height()?texture.height() - 1:y0).move_to(colors[l]); } break; case 2 : case 6 : { // Line const unsigned int i0 = (unsigned int)p[0], i1 = (unsigned int)p[1]; const int x0 = _coords(i0,0), y0 = _coords(i0,1), x1 = _coords(i1,0), y1 = _coords(i1,1); if (texture_ind<0) colors[texture_ind=l].assign(texture,false); else colors[l].assign(colors[texture_ind],true); CImg<tp>::vector(i0,i1,x0,y0,x1,y1).move_to(p); } break; case 3 : case 9 : { // Triangle const unsigned int i0 = (unsigned int)p[0], i1 = (unsigned int)p[1], i2 = (unsigned int)p[2]; const int x0 = _coords(i0,0), y0 = _coords(i0,1), x1 = _coords(i1,0), y1 = _coords(i1,1), x2 = _coords(i2,0), y2 = _coords(i2,1); if (texture_ind<0) colors[texture_ind=l].assign(texture,false); else colors[l].assign(colors[texture_ind],true); CImg<tp>::vector(i0,i1,i2,x0,y0,x1,y1,x2,y2).move_to(p); } break; case 4 : case 12 : { // Quadrangle const unsigned int i0 = (unsigned int)p[0], i1 = (unsigned int)p[1], i2 = (unsigned int)p[2], i3 = (unsigned int)p[3]; const int x0 = _coords(i0,0), y0 = _coords(i0,1), x1 = _coords(i1,0), y1 = _coords(i1,1), x2 = _coords(i2,0), y2 = _coords(i2,1), x3 = _coords(i3,0), y3 = _coords(i3,1); if (texture_ind<0) colors[texture_ind=l].assign(texture,false); else colors[l].assign(colors[texture_ind],true); CImg<tp>::vector(i0,i1,i2,i3,x0,y0,x1,y1,x2,y2,x3,y3).move_to(p); } break; } } return *this; } //! Generate a 3D elevation of the image instance. /** \param[out] primitives The returned list of the 3D object primitives (template type \e tf should be at least \e unsigned \e int). \param[out] colors The returned list of the 3D object colors. \param elevation The input elevation map. \return The N vertices (xi,yi,zi) of the 3D object as a Nx3 CImg<float> image (0<=i<=N - 1). \par Example \code const CImg<float> img("reference.jpg"); CImgList<unsigned int> faces3d; CImgList<unsigned char> colors3d; const CImg<float> points3d = img.get_elevation3d(faces3d,colors3d,img.get_norm()*0.2); CImg<unsigned char>().display_object3d("Elevation3d",points3d,faces3d,colors3d); \endcode \image html ref_elevation3d.jpg **/ template<typename tf, typename tc, typename te> CImg<floatT> get_elevation3d(CImgList<tf>& primitives, CImgList<tc>& colors, const CImg<te>& elevation) const { if (!is_sameXY(elevation) || elevation._depth>1 || elevation._spectrum>1) throw CImgArgumentException(_cimg_instance "get_elevation3d(): Instance and specified elevation (%u,%u,%u,%u,%p) " "have incompatible dimensions.", cimg_instance, elevation._width,elevation._height,elevation._depth, elevation._spectrum,elevation._data); if (is_empty()) return *this; float m, M = (float)max_min(m); if (M==m) ++M; colors.assign(); const unsigned int size_x1 = _width - 1, size_y1 = _height - 1; for (unsigned int y = 0; y<size_y1; ++y) for (unsigned int x = 0; x<size_x1; ++x) { const unsigned char r = (unsigned char)(((*this)(x,y,0) - m)*255/(M-m)), g = (unsigned char)(_spectrum>1?((*this)(x,y,1) - m)*255/(M-m):r), b = (unsigned char)(_spectrum>2?((*this)(x,y,2) - m)*255/(M-m):_spectrum>1?0:r); CImg<tc>::vector((tc)r,(tc)g,(tc)b).move_to(colors); } const typename CImg<te>::_functor2d_int func(elevation); return elevation3d(primitives,func,0,0,_width - 1.f,_height - 1.f,_width,_height); } //! Generate the 3D projection planes of the image instance. /** \param[out] primitives Primitives data of the returned 3D object. \param[out] colors Colors data of the returned 3D object. \param x0 X-coordinate of the projection point. \param y0 Y-coordinate of the projection point. \param z0 Z-coordinate of the projection point. \param normalize_colors Tells if the created textures have normalized colors. **/ template<typename tf, typename tc> CImg<floatT> get_projections3d(CImgList<tf>& primitives, CImgList<tc>& colors, const unsigned int x0, const unsigned int y0, const unsigned int z0, const bool normalize_colors=false) const { float m = 0, M = 0, delta = 1; if (normalize_colors) { m = (float)min_max(M); delta = 255/(m==M?1:M-m); } const unsigned int _x0 = (x0>=_width)?_width - 1:x0, _y0 = (y0>=_height)?_height - 1:y0, _z0 = (z0>=_depth)?_depth - 1:z0; CImg<tc> img_xy, img_xz, img_yz; if (normalize_colors) { ((get_crop(0,0,_z0,0,_width - 1,_height - 1,_z0,_spectrum - 1)-=m)*=delta).move_to(img_xy); ((get_crop(0,_y0,0,0,_width - 1,_y0,_depth - 1,_spectrum - 1)-=m)*=delta).resize(_width,_depth,1,-100,-1). move_to(img_xz); ((get_crop(_x0,0,0,0,_x0,_height - 1,_depth - 1,_spectrum - 1)-=m)*=delta).resize(_height,_depth,1,-100,-1). move_to(img_yz); } else { get_crop(0,0,_z0,0,_width - 1,_height - 1,_z0,_spectrum - 1).move_to(img_xy); get_crop(0,_y0,0,0,_width - 1,_y0,_depth - 1,_spectrum - 1).resize(_width,_depth,1,-100,-1).move_to(img_xz); get_crop(_x0,0,0,0,_x0,_height - 1,_depth - 1,_spectrum - 1).resize(_height,_depth,1,-100,-1).move_to(img_yz); } CImg<floatT> points(12,3,1,1, 0,_width - 1,_width - 1,0, 0,_width - 1,_width - 1,0, _x0,_x0,_x0,_x0, 0,0,_height - 1,_height - 1, _y0,_y0,_y0,_y0, 0,_height - 1,_height - 1,0, _z0,_z0,_z0,_z0, 0,0,_depth - 1,_depth - 1, 0,0,_depth - 1,_depth - 1); primitives.assign(); CImg<tf>::vector(0,1,2,3,0,0,img_xy._width - 1,0,img_xy._width - 1,img_xy._height - 1,0,img_xy._height - 1). move_to(primitives); CImg<tf>::vector(4,5,6,7,0,0,img_xz._width - 1,0,img_xz._width - 1,img_xz._height - 1,0,img_xz._height - 1). move_to(primitives); CImg<tf>::vector(8,9,10,11,0,0,img_yz._width - 1,0,img_yz._width - 1,img_yz._height - 1,0,img_yz._height - 1). move_to(primitives); colors.assign(); img_xy.move_to(colors); img_xz.move_to(colors); img_yz.move_to(colors); return points; } //! Generate a isoline of the image instance as a 3D object. /** \param[out] primitives The returned list of the 3D object primitives (template type \e tf should be at least \e unsigned \e int). \param isovalue The returned list of the 3D object colors. \param size_x The number of subdivisions along the X-axis. \param size_y The number of subdisivions along the Y-axis. \return The N vertices (xi,yi,zi) of the 3D object as a Nx3 CImg<float> image (0<=i<=N - 1). \par Example \code const CImg<float> img("reference.jpg"); CImgList<unsigned int> faces3d; const CImg<float> points3d = img.get_isoline3d(faces3d,100); CImg<unsigned char>().display_object3d("Isoline3d",points3d,faces3d,colors3d); \endcode \image html ref_isoline3d.jpg **/ template<typename tf> CImg<floatT> get_isoline3d(CImgList<tf>& primitives, const float isovalue, const int size_x=-100, const int size_y=-100) const { if (_spectrum>1) throw CImgInstanceException(_cimg_instance "get_isoline3d(): Instance is not a scalar image.", cimg_instance); if (_depth>1) throw CImgInstanceException(_cimg_instance "get_isoline3d(): Instance is not a 2D image.", cimg_instance); primitives.assign(); if (is_empty()) return *this; CImg<floatT> vertices; if ((size_x==-100 && size_y==-100) || (size_x==width() && size_y==height())) { const _functor2d_int func(*this); vertices = isoline3d(primitives,func,isovalue,0,0,width() - 1.f,height() - 1.f,width(),height()); } else { const _functor2d_float func(*this); vertices = isoline3d(primitives,func,isovalue,0,0,width() - 1.f,height() - 1.f,size_x,size_y); } return vertices; } //! Generate an isosurface of the image instance as a 3D object. /** \param[out] primitives The returned list of the 3D object primitives (template type \e tf should be at least \e unsigned \e int). \param isovalue The returned list of the 3D object colors. \param size_x Number of subdivisions along the X-axis. \param size_y Number of subdisivions along the Y-axis. \param size_z Number of subdisivions along the Z-axis. \return The N vertices (xi,yi,zi) of the 3D object as a Nx3 CImg<float> image (0<=i<=N - 1). \par Example \code const CImg<float> img = CImg<unsigned char>("reference.jpg").resize(-100,-100,20); CImgList<unsigned int> faces3d; const CImg<float> points3d = img.get_isosurface3d(faces3d,100); CImg<unsigned char>().display_object3d("Isosurface3d",points3d,faces3d,colors3d); \endcode \image html ref_isosurface3d.jpg **/ template<typename tf> CImg<floatT> get_isosurface3d(CImgList<tf>& primitives, const float isovalue, const int size_x=-100, const int size_y=-100, const int size_z=-100) const { if (_spectrum>1) throw CImgInstanceException(_cimg_instance "get_isosurface3d(): Instance is not a scalar image.", cimg_instance); primitives.assign(); if (is_empty()) return *this; CImg<floatT> vertices; if ((size_x==-100 && size_y==-100 && size_z==-100) || (size_x==width() && size_y==height() && size_z==depth())) { const _functor3d_int func(*this); vertices = isosurface3d(primitives,func,isovalue,0,0,0,width() - 1.f,height() - 1.f,depth() - 1.f, width(),height(),depth()); } else { const _functor3d_float func(*this); vertices = isosurface3d(primitives,func,isovalue,0,0,0,width() - 1.f,height() - 1.f,depth() - 1.f, size_x,size_y,size_z); } return vertices; } //! Compute 3D elevation of a function as a 3D object. /** \param[out] primitives Primitives data of the resulting 3D object. \param func Elevation function. Is of type <tt>float (*func)(const float x,const float y)</tt>. \param x0 X-coordinate of the starting point. \param y0 Y-coordinate of the starting point. \param x1 X-coordinate of the ending point. \param y1 Y-coordinate of the ending point. \param size_x Resolution of the function along the X-axis. \param size_y Resolution of the function along the Y-axis. **/ template<typename tf, typename tfunc> static CImg<floatT> elevation3d(CImgList<tf>& primitives, const tfunc& func, const float x0, const float y0, const float x1, const float y1, const int size_x=256, const int size_y=256) { const float nx0 = x0<x1?x0:x1, ny0 = y0<y1?y0:y1, nx1 = x0<x1?x1:x0, ny1 = y0<y1?y1:y0; const unsigned int _nsize_x = (unsigned int)(size_x>=0?size_x:(nx1-nx0)*-size_x/100), nsize_x = _nsize_x?_nsize_x:1, nsize_x1 = nsize_x - 1, _nsize_y = (unsigned int)(size_y>=0?size_y:(ny1-ny0)*-size_y/100), nsize_y = _nsize_y?_nsize_y:1, nsize_y1 = nsize_y - 1; if (nsize_x<2 || nsize_y<2) throw CImgArgumentException("CImg<%s>::elevation3d(): Invalid specified size (%d,%d).", pixel_type(), nsize_x,nsize_y); CImg<floatT> vertices(nsize_x*nsize_y,3); floatT *ptr_x = vertices.data(0,0), *ptr_y = vertices.data(0,1), *ptr_z = vertices.data(0,2); for (unsigned int y = 0; y<nsize_y; ++y) { const float Y = ny0 + y*(ny1-ny0)/nsize_y1; for (unsigned int x = 0; x<nsize_x; ++x) { const float X = nx0 + x*(nx1-nx0)/nsize_x1; *(ptr_x++) = (float)x; *(ptr_y++) = (float)y; *(ptr_z++) = (float)func(X,Y); } } primitives.assign(nsize_x1*nsize_y1,1,4); for (unsigned int p = 0, y = 0; y<nsize_y1; ++y) { const unsigned int yw = y*nsize_x; for (unsigned int x = 0; x<nsize_x1; ++x) { const unsigned int xpyw = x + yw, xpyww = xpyw + nsize_x; primitives[p++].fill(xpyw,xpyww,xpyww + 1,xpyw + 1); } } return vertices; } //! Compute 3D elevation of a function, as a 3D object \overloading. template<typename tf> static CImg<floatT> elevation3d(CImgList<tf>& primitives, const char *const expression, const float x0, const float y0, const float x1, const float y1, const int size_x=256, const int size_y=256) { const _functor2d_expr func(expression); return elevation3d(primitives,func,x0,y0,x1,y1,size_x,size_y); } //! Compute 0-isolines of a function, as a 3D object. /** \param[out] primitives Primitives data of the resulting 3D object. \param func Elevation function. Is of type <tt>float (*func)(const float x,const float y)</tt>. \param isovalue Isovalue to extract from function. \param x0 X-coordinate of the starting point. \param y0 Y-coordinate of the starting point. \param x1 X-coordinate of the ending point. \param y1 Y-coordinate of the ending point. \param size_x Resolution of the function along the X-axis. \param size_y Resolution of the function along the Y-axis. \note Use the marching squares algorithm for extracting the isolines. **/ template<typename tf, typename tfunc> static CImg<floatT> isoline3d(CImgList<tf>& primitives, const tfunc& func, const float isovalue, const float x0, const float y0, const float x1, const float y1, const int size_x=256, const int size_y=256) { static const unsigned int edges[16] = { 0x0, 0x9, 0x3, 0xa, 0x6, 0xf, 0x5, 0xc, 0xc, 0x5, 0xf, 0x6, 0xa, 0x3, 0x9, 0x0 }; static const int segments[16][4] = { { -1,-1,-1,-1 }, { 0,3,-1,-1 }, { 0,1,-1,-1 }, { 1,3,-1,-1 }, { 1,2,-1,-1 }, { 0,1,2,3 }, { 0,2,-1,-1 }, { 2,3,-1,-1 }, { 2,3,-1,-1 }, { 0,2,-1,-1}, { 0,3,1,2 }, { 1,2,-1,-1 }, { 1,3,-1,-1 }, { 0,1,-1,-1}, { 0,3,-1,-1}, { -1,-1,-1,-1 } }; const unsigned int _nx = (unsigned int)(size_x>=0?size_x:cimg::round((x1-x0)*-size_x/100 + 1)), _ny = (unsigned int)(size_y>=0?size_y:cimg::round((y1-y0)*-size_y/100 + 1)), nx = _nx?_nx:1, ny = _ny?_ny:1, nxm1 = nx - 1, nym1 = ny - 1; primitives.assign(); if (!nxm1 || !nym1) return CImg<floatT>(); const float dx = (x1 - x0)/nxm1, dy = (y1 - y0)/nym1; CImgList<floatT> vertices; CImg<intT> indices1(nx,1,1,2,-1), indices2(nx,1,1,2); CImg<floatT> values1(nx), values2(nx); float X = x0, Y = y0, nX = X + dx, nY = Y + dy; // Fill first line with values cimg_forX(values1,x) { values1(x) = (float)func(X,Y); X+=dx; } // Run the marching squares algorithm for (unsigned int yi = 0, nyi = 1; yi<nym1; ++yi, ++nyi, Y=nY, nY+=dy) { X = x0; nX = X + dx; indices2.fill(-1); for (unsigned int xi = 0, nxi = 1; xi<nxm1; ++xi, ++nxi, X=nX, nX+=dx) { // Determine square configuration const float val0 = values1(xi), val1 = values1(nxi), val2 = values2(nxi) = (float)func(nX,nY), val3 = values2(xi) = (float)func(X,nY); const unsigned int configuration = (val0<isovalue?1U:0U) | (val1<isovalue?2U:0U) | (val2<isovalue?4U:0U) | (val3<isovalue?8U:0U), edge = edges[configuration]; // Compute intersection vertices if (edge) { if ((edge&1) && indices1(xi,0)<0) { const float Xi = X + (isovalue-val0)*dx/(val1-val0); indices1(xi,0) = vertices.width(); CImg<floatT>::vector(Xi,Y,0).move_to(vertices); } if ((edge&2) && indices1(nxi,1)<0) { const float Yi = Y + (isovalue-val1)*dy/(val2-val1); indices1(nxi,1) = vertices.width(); CImg<floatT>::vector(nX,Yi,0).move_to(vertices); } if ((edge&4) && indices2(xi,0)<0) { const float Xi = X + (isovalue-val3)*dx/(val2-val3); indices2(xi,0) = vertices.width(); CImg<floatT>::vector(Xi,nY,0).move_to(vertices); } if ((edge&8) && indices1(xi,1)<0) { const float Yi = Y + (isovalue-val0)*dy/(val3-val0); indices1(xi,1) = vertices.width(); CImg<floatT>::vector(X,Yi,0).move_to(vertices); } // Create segments for (const int *segment = segments[configuration]; *segment!=-1; ) { const unsigned int p0 = (unsigned int)*(segment++), p1 = (unsigned int)*(segment++); const tf i0 = (tf)(_isoline3d_index(p0,indices1,indices2,xi,nxi)), i1 = (tf)(_isoline3d_index(p1,indices1,indices2,xi,nxi)); CImg<tf>::vector(i0,i1).move_to(primitives); } } } values1.swap(values2); indices1.swap(indices2); } return vertices>'x'; } //! Compute isolines of a function, as a 3D object \overloading. template<typename tf> static CImg<floatT> isoline3d(CImgList<tf>& primitives, const char *const expression, const float isovalue, const float x0, const float y0, const float x1, const float y1, const int size_x=256, const int size_y=256) { const _functor2d_expr func(expression); return isoline3d(primitives,func,isovalue,x0,y0,x1,y1,size_x,size_y); } template<typename t> static int _isoline3d_index(const unsigned int edge, const CImg<t>& indices1, const CImg<t>& indices2, const unsigned int x, const unsigned int nx) { switch (edge) { case 0 : return (int)indices1(x,0); case 1 : return (int)indices1(nx,1); case 2 : return (int)indices2(x,0); case 3 : return (int)indices1(x,1); } return 0; } //! Compute isosurface of a function, as a 3D object. /** \param[out] primitives Primitives data of the resulting 3D object. \param func Implicit function. Is of type <tt>float (*func)(const float x, const float y, const float z)</tt>. \param isovalue Isovalue to extract. \param x0 X-coordinate of the starting point. \param y0 Y-coordinate of the starting point. \param z0 Z-coordinate of the starting point. \param x1 X-coordinate of the ending point. \param y1 Y-coordinate of the ending point. \param z1 Z-coordinate of the ending point. \param size_x Resolution of the elevation function along the X-axis. \param size_y Resolution of the elevation function along the Y-axis. \param size_z Resolution of the elevation function along the Z-axis. \note Use the marching cubes algorithm for extracting the isosurface. **/ template<typename tf, typename tfunc> static CImg<floatT> isosurface3d(CImgList<tf>& primitives, const tfunc& func, const float isovalue, const float x0, const float y0, const float z0, const float x1, const float y1, const float z1, const int size_x=32, const int size_y=32, const int size_z=32) { static const unsigned int edges[256] = { 0x000, 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, 0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00, 0x190, 0x99 , 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c, 0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90, 0x230, 0x339, 0x33 , 0x13a, 0x636, 0x73f, 0x435, 0x53c, 0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30, 0x3a0, 0x2a9, 0x1a3, 0xaa , 0x7a6, 0x6af, 0x5a5, 0x4ac, 0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0, 0x460, 0x569, 0x663, 0x76a, 0x66 , 0x16f, 0x265, 0x36c, 0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60, 0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0xff , 0x3f5, 0x2fc, 0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0, 0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x55 , 0x15c, 0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950, 0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0xcc , 0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0, 0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc, 0xcc , 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0, 0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c, 0x15c, 0x55 , 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650, 0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc, 0x2fc, 0x3f5, 0xff , 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0, 0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c, 0x36c, 0x265, 0x16f, 0x66 , 0x76a, 0x663, 0x569, 0x460, 0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac, 0x4ac, 0x5a5, 0x6af, 0x7a6, 0xaa , 0x1a3, 0x2a9, 0x3a0, 0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c, 0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x33 , 0x339, 0x230, 0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c, 0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x99 , 0x190, 0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c, 0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x000 }; static const int triangles[256][16] = { { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1 }, { 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1 }, { 3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1 }, { 3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1 }, { 9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1 }, { 9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1 }, { 2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1 }, { 8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1 }, { 9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1 }, { 4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1 }, { 3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1 }, { 1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1 }, { 4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1 }, { 4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1 }, { 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1 }, { 5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1 }, { 2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1 }, { 9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1 }, { 0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1 }, { 2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1 }, { 10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1 }, { 4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1 }, { 5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1 }, { 5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1 }, { 9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1 }, { 0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1 }, { 1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1 }, { 10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1 }, { 8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1 }, { 2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1 }, { 7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1 }, { 9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1 }, { 2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1 }, { 11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1 }, { 9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1 }, { 5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1 }, { 11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1 }, { 11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1 }, { 1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1 }, { 9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1 }, { 5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1 }, { 2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1 }, { 0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1 }, { 5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1 }, { 6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1 }, { 3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1 }, { 6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1 }, { 5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1 }, { 1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1 }, { 10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1 }, { 6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1 }, { 8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1 }, { 7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1 }, { 3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1 }, { 5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1 }, { 0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1 }, { 9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1 }, { 8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1 }, { 5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1 }, { 0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1 }, { 6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1 }, { 10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1 }, { 10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1 }, { 8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1 }, { 1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1 }, { 3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1 }, { 0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1 }, { 10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1 }, { 3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1 }, { 6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1 }, { 9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1 }, { 8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1 }, { 3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1 }, { 6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1 }, { 0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1 }, { 10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1 }, { 10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1 }, { 2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1 }, { 7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1 }, { 7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1 }, { 2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1 }, { 1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1 }, { 11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1 }, { 8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1 }, { 0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1 }, { 7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1 }, { 10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1 }, { 2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1 }, { 6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1 }, { 7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1 }, { 2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1 }, { 1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1 }, { 10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1 }, { 10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1 }, { 0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1 }, { 7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1 }, { 6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1 }, { 8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1 }, { 9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1 }, { 6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1 }, { 4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1 }, { 10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1 }, { 8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1 }, { 0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1 }, { 1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1 }, { 8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1 }, { 10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1 }, { 4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1 }, { 10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1 }, { 5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1 }, { 11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1 }, { 9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1 }, { 6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1 }, { 7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1 }, { 3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1 }, { 7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1 }, { 9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1 }, { 3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1 }, { 6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1 }, { 9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1 }, { 1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1 }, { 4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1 }, { 7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1 }, { 6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1 }, { 3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1 }, { 0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1 }, { 6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1 }, { 0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1 }, { 11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1 }, { 6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1 }, { 5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1 }, { 9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1 }, { 1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1 }, { 1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1 }, { 10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1 }, { 0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1 }, { 5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1 }, { 10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1 }, { 11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1 }, { 9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1 }, { 7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1 }, { 2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1 }, { 8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1 }, { 9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1 }, { 9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1 }, { 1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1 }, { 9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1 }, { 9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1 }, { 5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1 }, { 0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1 }, { 10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1 }, { 2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1 }, { 0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1 }, { 0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1 }, { 9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1 }, { 5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1 }, { 3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1 }, { 5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1 }, { 8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1 }, { 9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1 }, { 1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1 }, { 3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1 }, { 4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1 }, { 9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1 }, { 11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1 }, { 11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1 }, { 2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1 }, { 9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1 }, { 3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1 }, { 1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1 }, { 4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1 }, { 4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1 }, { 0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1 }, { 3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1 }, { 3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1 }, { 0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1 }, { 9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1 }, { 1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } }; const unsigned int _nx = (unsigned int)(size_x>=0?size_x:cimg::round((x1-x0)*-size_x/100 + 1)), _ny = (unsigned int)(size_y>=0?size_y:cimg::round((y1-y0)*-size_y/100 + 1)), _nz = (unsigned int)(size_z>=0?size_z:cimg::round((z1-z0)*-size_z/100 + 1)), nx = _nx?_nx:1, ny = _ny?_ny:1, nz = _nz?_nz:1, nxm1 = nx - 1, nym1 = ny - 1, nzm1 = nz - 1; primitives.assign(); if (!nxm1 || !nym1 || !nzm1) return CImg<floatT>(); const float dx = (x1 - x0)/nxm1, dy = (y1 - y0)/nym1, dz = (z1 - z0)/nzm1; CImgList<floatT> vertices; CImg<intT> indices1(nx,ny,1,3,-1), indices2(indices1); CImg<floatT> values1(nx,ny), values2(nx,ny); float X = 0, Y = 0, Z = 0, nX = 0, nY = 0, nZ = 0; // Fill the first plane with function values Y = y0; cimg_forY(values1,y) { X = x0; cimg_forX(values1,x) { values1(x,y) = (float)func(X,Y,z0); X+=dx; } Y+=dy; } // Run Marching Cubes algorithm Z = z0; nZ = Z + dz; for (unsigned int zi = 0; zi<nzm1; ++zi, Z = nZ, nZ+=dz) { Y = y0; nY = Y + dy; indices2.fill(-1); for (unsigned int yi = 0, nyi = 1; yi<nym1; ++yi, ++nyi, Y = nY, nY+=dy) { X = x0; nX = X + dx; for (unsigned int xi = 0, nxi = 1; xi<nxm1; ++xi, ++nxi, X = nX, nX+=dx) { // Determine cube configuration const float val0 = values1(xi,yi), val1 = values1(nxi,yi), val2 = values1(nxi,nyi), val3 = values1(xi,nyi), val4 = values2(xi,yi) = (float)func(X,Y,nZ), val5 = values2(nxi,yi) = (float)func(nX,Y,nZ), val6 = values2(nxi,nyi) = (float)func(nX,nY,nZ), val7 = values2(xi,nyi) = (float)func(X,nY,nZ); const unsigned int configuration = (val0<isovalue?1U:0U) | (val1<isovalue?2U:0U) | (val2<isovalue?4U:0U) | (val3<isovalue?8U:0U) | (val4<isovalue?16U:0U) | (val5<isovalue?32U:0U) | (val6<isovalue?64U:0U) | (val7<isovalue?128U:0U), edge = edges[configuration]; // Compute intersection vertices if (edge) { if ((edge&1) && indices1(xi,yi,0)<0) { const float Xi = X + (isovalue-val0)*dx/(val1-val0); indices1(xi,yi,0) = vertices.width(); CImg<floatT>::vector(Xi,Y,Z).move_to(vertices); } if ((edge&2) && indices1(nxi,yi,1)<0) { const float Yi = Y + (isovalue-val1)*dy/(val2-val1); indices1(nxi,yi,1) = vertices.width(); CImg<floatT>::vector(nX,Yi,Z).move_to(vertices); } if ((edge&4) && indices1(xi,nyi,0)<0) { const float Xi = X + (isovalue-val3)*dx/(val2-val3); indices1(xi,nyi,0) = vertices.width(); CImg<floatT>::vector(Xi,nY,Z).move_to(vertices); } if ((edge&8) && indices1(xi,yi,1)<0) { const float Yi = Y + (isovalue-val0)*dy/(val3-val0); indices1(xi,yi,1) = vertices.width(); CImg<floatT>::vector(X,Yi,Z).move_to(vertices); } if ((edge&16) && indices2(xi,yi,0)<0) { const float Xi = X + (isovalue-val4)*dx/(val5-val4); indices2(xi,yi,0) = vertices.width(); CImg<floatT>::vector(Xi,Y,nZ).move_to(vertices); } if ((edge&32) && indices2(nxi,yi,1)<0) { const float Yi = Y + (isovalue-val5)*dy/(val6-val5); indices2(nxi,yi,1) = vertices.width(); CImg<floatT>::vector(nX,Yi,nZ).move_to(vertices); } if ((edge&64) && indices2(xi,nyi,0)<0) { const float Xi = X + (isovalue-val7)*dx/(val6-val7); indices2(xi,nyi,0) = vertices.width(); CImg<floatT>::vector(Xi,nY,nZ).move_to(vertices); } if ((edge&128) && indices2(xi,yi,1)<0) { const float Yi = Y + (isovalue-val4)*dy/(val7-val4); indices2(xi,yi,1) = vertices.width(); CImg<floatT>::vector(X,Yi,nZ).move_to(vertices); } if ((edge&256) && indices1(xi,yi,2)<0) { const float Zi = Z+ (isovalue-val0)*dz/(val4-val0); indices1(xi,yi,2) = vertices.width(); CImg<floatT>::vector(X,Y,Zi).move_to(vertices); } if ((edge&512) && indices1(nxi,yi,2)<0) { const float Zi = Z + (isovalue-val1)*dz/(val5-val1); indices1(nxi,yi,2) = vertices.width(); CImg<floatT>::vector(nX,Y,Zi).move_to(vertices); } if ((edge&1024) && indices1(nxi,nyi,2)<0) { const float Zi = Z + (isovalue-val2)*dz/(val6-val2); indices1(nxi,nyi,2) = vertices.width(); CImg<floatT>::vector(nX,nY,Zi).move_to(vertices); } if ((edge&2048) && indices1(xi,nyi,2)<0) { const float Zi = Z + (isovalue-val3)*dz/(val7-val3); indices1(xi,nyi,2) = vertices.width(); CImg<floatT>::vector(X,nY,Zi).move_to(vertices); } // Create triangles for (const int *triangle = triangles[configuration]; *triangle!=-1; ) { const unsigned int p0 = (unsigned int)*(triangle++), p1 = (unsigned int)*(triangle++), p2 = (unsigned int)*(triangle++); const tf i0 = (tf)(_isosurface3d_index(p0,indices1,indices2,xi,yi,nxi,nyi)), i1 = (tf)(_isosurface3d_index(p1,indices1,indices2,xi,yi,nxi,nyi)), i2 = (tf)(_isosurface3d_index(p2,indices1,indices2,xi,yi,nxi,nyi)); CImg<tf>::vector(i0,i2,i1).move_to(primitives); } } } } cimg::swap(values1,values2); cimg::swap(indices1,indices2); } return vertices>'x'; } //! Compute isosurface of a function, as a 3D object \overloading. template<typename tf> static CImg<floatT> isosurface3d(CImgList<tf>& primitives, const char *const expression, const float isovalue, const float x0, const float y0, const float z0, const float x1, const float y1, const float z1, const int dx=32, const int dy=32, const int dz=32) { const _functor3d_expr func(expression); return isosurface3d(primitives,func,isovalue,x0,y0,z0,x1,y1,z1,dx,dy,dz); } template<typename t> static int _isosurface3d_index(const unsigned int edge, const CImg<t>& indices1, const CImg<t>& indices2, const unsigned int x, const unsigned int y, const unsigned int nx, const unsigned int ny) { switch (edge) { case 0 : return indices1(x,y,0); case 1 : return indices1(nx,y,1); case 2 : return indices1(x,ny,0); case 3 : return indices1(x,y,1); case 4 : return indices2(x,y,0); case 5 : return indices2(nx,y,1); case 6 : return indices2(x,ny,0); case 7 : return indices2(x,y,1); case 8 : return indices1(x,y,2); case 9 : return indices1(nx,y,2); case 10 : return indices1(nx,ny,2); case 11 : return indices1(x,ny,2); } return 0; } // Define functors for accessing image values (used in previous functions). struct _functor2d_int { const CImg<T>& ref; _functor2d_int(const CImg<T>& pref):ref(pref) {} float operator()(const float x, const float y) const { return (float)ref((int)x,(int)y); } }; struct _functor2d_float { const CImg<T>& ref; _functor2d_float(const CImg<T>& pref):ref(pref) {} float operator()(const float x, const float y) const { return (float)ref._linear_atXY(x,y); } }; struct _functor2d_expr { _cimg_math_parser *mp; ~_functor2d_expr() { mp->end(); delete mp; } _functor2d_expr(const char *const expr):mp(0) { mp = new _cimg_math_parser(expr,0,CImg<T>::const_empty(),0); } float operator()(const float x, const float y) const { return (float)(*mp)(x,y,0,0); } }; struct _functor3d_int { const CImg<T>& ref; _functor3d_int(const CImg<T>& pref):ref(pref) {} float operator()(const float x, const float y, const float z) const { return (float)ref((int)x,(int)y,(int)z); } }; struct _functor3d_float { const CImg<T>& ref; _functor3d_float(const CImg<T>& pref):ref(pref) {} float operator()(const float x, const float y, const float z) const { return (float)ref._linear_atXYZ(x,y,z); } }; struct _functor3d_expr { _cimg_math_parser *mp; ~_functor3d_expr() { mp->end(); delete mp; } _functor3d_expr(const char *const expr):mp(0) { mp = new _cimg_math_parser(expr,0,CImg<T>::const_empty(),0); } float operator()(const float x, const float y, const float z) const { return (float)(*mp)(x,y,z,0); } }; struct _functor4d_int { const CImg<T>& ref; _functor4d_int(const CImg<T>& pref):ref(pref) {} float operator()(const float x, const float y, const float z, const unsigned int c) const { return (float)ref((int)x,(int)y,(int)z,c); } }; //! Generate a 3D box object. /** \param[out] primitives The returned list of the 3D object primitives (template type \e tf should be at least \e unsigned \e int). \param size_x The width of the box (dimension along the X-axis). \param size_y The height of the box (dimension along the Y-axis). \param size_z The depth of the box (dimension along the Z-axis). \return The N vertices (xi,yi,zi) of the 3D object as a Nx3 CImg<float> image (0<=i<=N - 1). \par Example \code CImgList<unsigned int> faces3d; const CImg<float> points3d = CImg<float>::box3d(faces3d,10,20,30); CImg<unsigned char>().display_object3d("Box3d",points3d,faces3d); \endcode \image html ref_box3d.jpg **/ template<typename tf> static CImg<floatT> box3d(CImgList<tf>& primitives, const float size_x=200, const float size_y=100, const float size_z=100) { primitives.assign(6,1,4,1,1, 0,3,2,1, 4,5,6,7, 0,1,5,4, 3,7,6,2, 0,4,7,3, 1,2,6,5); return CImg<floatT>(8,3,1,1, 0.,size_x,size_x, 0., 0.,size_x,size_x, 0., 0., 0.,size_y,size_y, 0., 0.,size_y,size_y, 0., 0., 0., 0.,size_z,size_z,size_z,size_z); } //! Generate a 3D cone. /** \param[out] primitives The returned list of the 3D object primitives (template type \e tf should be at least \e unsigned \e int). \param radius The radius of the cone basis. \param size_z The cone's height. \param subdivisions The number of basis angular subdivisions. \return The N vertices (xi,yi,zi) of the 3D object as a Nx3 CImg<float> image (0<=i<=N - 1). \par Example \code CImgList<unsigned int> faces3d; const CImg<float> points3d = CImg<float>::cone3d(faces3d,50); CImg<unsigned char>().display_object3d("Cone3d",points3d,faces3d); \endcode \image html ref_cone3d.jpg **/ template<typename tf> static CImg<floatT> cone3d(CImgList<tf>& primitives, const float radius=50, const float size_z=100, const unsigned int subdivisions=24) { primitives.assign(); if (!subdivisions) return CImg<floatT>(); CImgList<floatT> vertices(2,1,3,1,1, 0.,0.,size_z, 0.,0.,0.); for (float delta = 360.f/subdivisions, angle = 0; angle<360; angle+=delta) { const float a = (float)(angle*cimg::PI/180); CImg<floatT>::vector((float)(radius*std::cos(a)),(float)(radius*std::sin(a)),0).move_to(vertices); } const unsigned int nbr = vertices._width - 2; for (unsigned int p = 0; p<nbr; ++p) { const unsigned int curr = 2 + p, next = 2 + ((p + 1)%nbr); CImg<tf>::vector(1,next,curr).move_to(primitives); CImg<tf>::vector(0,curr,next).move_to(primitives); } return vertices>'x'; } //! Generate a 3D cylinder. /** \param[out] primitives The returned list of the 3D object primitives (template type \e tf should be at least \e unsigned \e int). \param radius The radius of the cylinder basis. \param size_z The cylinder's height. \param subdivisions The number of basis angular subdivisions. \return The N vertices (xi,yi,zi) of the 3D object as a Nx3 CImg<float> image (0<=i<=N - 1). \par Example \code CImgList<unsigned int> faces3d; const CImg<float> points3d = CImg<float>::cylinder3d(faces3d,50); CImg<unsigned char>().display_object3d("Cylinder3d",points3d,faces3d); \endcode \image html ref_cylinder3d.jpg **/ template<typename tf> static CImg<floatT> cylinder3d(CImgList<tf>& primitives, const float radius=50, const float size_z=100, const unsigned int subdivisions=24) { primitives.assign(); if (!subdivisions) return CImg<floatT>(); CImgList<floatT> vertices(2,1,3,1,1, 0.,0.,0., 0.,0.,size_z); for (float delta = 360.f/subdivisions, angle = 0; angle<360; angle+=delta) { const float a = (float)(angle*cimg::PI/180); CImg<floatT>::vector((float)(radius*std::cos(a)),(float)(radius*std::sin(a)),0.f).move_to(vertices); CImg<floatT>::vector((float)(radius*std::cos(a)),(float)(radius*std::sin(a)),size_z).move_to(vertices); } const unsigned int nbr = (vertices._width - 2)/2; for (unsigned int p = 0; p<nbr; ++p) { const unsigned int curr = 2 + 2*p, next = 2 + (2*((p + 1)%nbr)); CImg<tf>::vector(0,next,curr).move_to(primitives); CImg<tf>::vector(1,curr + 1,next + 1).move_to(primitives); CImg<tf>::vector(curr,next,next + 1,curr + 1).move_to(primitives); } return vertices>'x'; } //! Generate a 3D torus. /** \param[out] primitives The returned list of the 3D object primitives (template type \e tf should be at least \e unsigned \e int). \param radius1 The large radius. \param radius2 The small radius. \param subdivisions1 The number of angular subdivisions for the large radius. \param subdivisions2 The number of angular subdivisions for the small radius. \return The N vertices (xi,yi,zi) of the 3D object as a Nx3 CImg<float> image (0<=i<=N - 1). \par Example \code CImgList<unsigned int> faces3d; const CImg<float> points3d = CImg<float>::torus3d(faces3d,20,4); CImg<unsigned char>().display_object3d("Torus3d",points3d,faces3d); \endcode \image html ref_torus3d.jpg **/ template<typename tf> static CImg<floatT> torus3d(CImgList<tf>& primitives, const float radius1=100, const float radius2=30, const unsigned int subdivisions1=24, const unsigned int subdivisions2=12) { primitives.assign(); if (!subdivisions1 || !subdivisions2) return CImg<floatT>(); CImgList<floatT> vertices; for (unsigned int v = 0; v<subdivisions1; ++v) { const float beta = (float)(v*2*cimg::PI/subdivisions1), xc = radius1*(float)std::cos(beta), yc = radius1*(float)std::sin(beta); for (unsigned int u = 0; u<subdivisions2; ++u) { const float alpha = (float)(u*2*cimg::PI/subdivisions2), x = xc + radius2*(float)(std::cos(alpha)*std::cos(beta)), y = yc + radius2*(float)(std::cos(alpha)*std::sin(beta)), z = radius2*(float)std::sin(alpha); CImg<floatT>::vector(x,y,z).move_to(vertices); } } for (unsigned int vv = 0; vv<subdivisions1; ++vv) { const unsigned int nv = (vv + 1)%subdivisions1; for (unsigned int uu = 0; uu<subdivisions2; ++uu) { const unsigned int nu = (uu + 1)%subdivisions2, svv = subdivisions2*vv, snv = subdivisions2*nv; CImg<tf>::vector(svv + nu,svv + uu,snv + uu,snv + nu).move_to(primitives); } } return vertices>'x'; } //! Generate a 3D XY-plane. /** \param[out] primitives The returned list of the 3D object primitives (template type \e tf should be at least \e unsigned \e int). \param size_x The width of the plane (dimension along the X-axis). \param size_y The height of the plane (dimensions along the Y-axis). \param subdivisions_x The number of planar subdivisions along the X-axis. \param subdivisions_y The number of planar subdivisions along the Y-axis. \return The N vertices (xi,yi,zi) of the 3D object as a Nx3 CImg<float> image (0<=i<=N - 1). \par Example \code CImgList<unsigned int> faces3d; const CImg<float> points3d = CImg<float>::plane3d(faces3d,100,50); CImg<unsigned char>().display_object3d("Plane3d",points3d,faces3d); \endcode \image html ref_plane3d.jpg **/ template<typename tf> static CImg<floatT> plane3d(CImgList<tf>& primitives, const float size_x=100, const float size_y=100, const unsigned int subdivisions_x=10, const unsigned int subdivisions_y=10) { primitives.assign(); if (!subdivisions_x || !subdivisions_y) return CImg<floatT>(); CImgList<floatT> vertices; const unsigned int w = subdivisions_x + 1, h = subdivisions_y + 1; const float fx = (float)size_x/w, fy = (float)size_y/h; for (unsigned int y = 0; y<h; ++y) for (unsigned int x = 0; x<w; ++x) CImg<floatT>::vector(fx*x,fy*y,0).move_to(vertices); for (unsigned int y = 0; y<subdivisions_y; ++y) for (unsigned int x = 0; x<subdivisions_x; ++x) { const int off1 = x + y*w, off2 = x + 1 + y*w, off3 = x + 1 + (y + 1)*w, off4 = x + (y + 1)*w; CImg<tf>::vector(off1,off4,off3,off2).move_to(primitives); } return vertices>'x'; } //! Generate a 3D sphere. /** \param[out] primitives The returned list of the 3D object primitives (template type \e tf should be at least \e unsigned \e int). \param radius The radius of the sphere (dimension along the X-axis). \param subdivisions The number of recursive subdivisions from an initial icosahedron. \return The N vertices (xi,yi,zi) of the 3D object as a Nx3 CImg<float> image (0<=i<=N - 1). \par Example \code CImgList<unsigned int> faces3d; const CImg<float> points3d = CImg<float>::sphere3d(faces3d,100,4); CImg<unsigned char>().display_object3d("Sphere3d",points3d,faces3d); \endcode \image html ref_sphere3d.jpg **/ template<typename tf> static CImg<floatT> sphere3d(CImgList<tf>& primitives, const float radius=50, const unsigned int subdivisions=3) { // Create initial icosahedron primitives.assign(); const double tmp = (1 + std::sqrt(5.f))/2, a = 1./std::sqrt(1 + tmp*tmp), b = tmp*a; CImgList<floatT> vertices(12,1,3,1,1, b,a,0., -b,a,0., -b,-a,0., b,-a,0., a,0.,b, a,0.,-b, -a,0.,-b, -a,0.,b, 0.,b,a, 0.,-b,a, 0.,-b,-a, 0.,b,-a); primitives.assign(20,1,3,1,1, 4,8,7, 4,7,9, 5,6,11, 5,10,6, 0,4,3, 0,3,5, 2,7,1, 2,1,6, 8,0,11, 8,11,1, 9,10,3, 9,2,10, 8,4,0, 11,0,5, 4,9,3, 5,3,10, 7,8,1, 6,1,11, 7,2,9, 6,10,2); // edge - length/2 float he = (float)a; // Recurse subdivisions for (unsigned int i = 0; i<subdivisions; ++i) { const unsigned int L = primitives._width; he/=2; const float he2 = he*he; for (unsigned int l = 0; l<L; ++l) { const unsigned int p0 = (unsigned int)primitives(0,0), p1 = (unsigned int)primitives(0,1), p2 = (unsigned int)primitives(0,2); const float x0 = vertices(p0,0), y0 = vertices(p0,1), z0 = vertices(p0,2), x1 = vertices(p1,0), y1 = vertices(p1,1), z1 = vertices(p1,2), x2 = vertices(p2,0), y2 = vertices(p2,1), z2 = vertices(p2,2), tnx0 = (x0 + x1)/2, tny0 = (y0 + y1)/2, tnz0 = (z0 + z1)/2, nn0 = cimg::hypot(tnx0,tny0,tnz0), tnx1 = (x0 + x2)/2, tny1 = (y0 + y2)/2, tnz1 = (z0 + z2)/2, nn1 = cimg::hypot(tnx1,tny1,tnz1), tnx2 = (x1 + x2)/2, tny2 = (y1 + y2)/2, tnz2 = (z1 + z2)/2, nn2 = cimg::hypot(tnx2,tny2,tnz2), nx0 = tnx0/nn0, ny0 = tny0/nn0, nz0 = tnz0/nn0, nx1 = tnx1/nn1, ny1 = tny1/nn1, nz1 = tnz1/nn1, nx2 = tnx2/nn2, ny2 = tny2/nn2, nz2 = tnz2/nn2; int i0 = -1, i1 = -1, i2 = -1; cimglist_for(vertices,p) { const float x = (float)vertices(p,0), y = (float)vertices(p,1), z = (float)vertices(p,2); if (cimg::sqr(x-nx0) + cimg::sqr(y-ny0) + cimg::sqr(z-nz0)<he2) i0 = p; if (cimg::sqr(x-nx1) + cimg::sqr(y-ny1) + cimg::sqr(z-nz1)<he2) i1 = p; if (cimg::sqr(x-nx2) + cimg::sqr(y-ny2) + cimg::sqr(z-nz2)<he2) i2 = p; } if (i0<0) { CImg<floatT>::vector(nx0,ny0,nz0).move_to(vertices); i0 = vertices.width() - 1; } if (i1<0) { CImg<floatT>::vector(nx1,ny1,nz1).move_to(vertices); i1 = vertices.width() - 1; } if (i2<0) { CImg<floatT>::vector(nx2,ny2,nz2).move_to(vertices); i2 = vertices.width() - 1; } primitives.remove(0); CImg<tf>::vector(p0,i0,i1).move_to(primitives); CImg<tf>::vector((tf)i0,(tf)p1,(tf)i2).move_to(primitives); CImg<tf>::vector((tf)i1,(tf)i2,(tf)p2).move_to(primitives); CImg<tf>::vector((tf)i1,(tf)i0,(tf)i2).move_to(primitives); } } return (vertices>'x')*=radius; } //! Generate a 3D ellipsoid. /** \param[out] primitives The returned list of the 3D object primitives (template type \e tf should be at least \e unsigned \e int). \param tensor The tensor which gives the shape and size of the ellipsoid. \param subdivisions The number of recursive subdivisions from an initial stretched icosahedron. \return The N vertices (xi,yi,zi) of the 3D object as a Nx3 CImg<float> image (0<=i<=N - 1). \par Example \code CImgList<unsigned int> faces3d; const CImg<float> tensor = CImg<float>::diagonal(10,7,3), points3d = CImg<float>::ellipsoid3d(faces3d,tensor,4); CImg<unsigned char>().display_object3d("Ellipsoid3d",points3d,faces3d); \endcode \image html ref_ellipsoid3d.jpg **/ template<typename tf, typename t> static CImg<floatT> ellipsoid3d(CImgList<tf>& primitives, const CImg<t>& tensor, const unsigned int subdivisions=3) { primitives.assign(); if (!subdivisions) return CImg<floatT>(); CImg<floatT> S, V; tensor.symmetric_eigen(S,V); const float orient = (V(0,1)*V(1,2) - V(0,2)*V(1,1))*V(2,0) + (V(0,2)*V(1,0) - V(0,0)*V(1,2))*V(2,1) + (V(0,0)*V(1,1) - V(0,1)*V(1,0))*V(2,2); if (orient<0) { V(2,0) = -V(2,0); V(2,1) = -V(2,1); V(2,2) = -V(2,2); } const float l0 = S[0], l1 = S[1], l2 = S[2]; CImg<floatT> vertices = sphere3d(primitives,1.,subdivisions); vertices.get_shared_row(0)*=l0; vertices.get_shared_row(1)*=l1; vertices.get_shared_row(2)*=l2; return V*vertices; } //! Convert 3D object into a CImg3d representation. /** \param primitives Primitives data of the 3D object. \param colors Colors data of the 3D object. \param opacities Opacities data of the 3D object. \param full_check Tells if full checking of the 3D object must be performed. **/ template<typename tp, typename tc, typename to> CImg<T>& object3dtoCImg3d(const CImgList<tp>& primitives, const CImgList<tc>& colors, const to& opacities, const bool full_check=true) { return get_object3dtoCImg3d(primitives,colors,opacities,full_check).move_to(*this); } //! Convert 3D object into a CImg3d representation \overloading. template<typename tp, typename tc> CImg<T>& object3dtoCImg3d(const CImgList<tp>& primitives, const CImgList<tc>& colors, const bool full_check=true) { return get_object3dtoCImg3d(primitives,colors,full_check).move_to(*this); } //! Convert 3D object into a CImg3d representation \overloading. template<typename tp> CImg<T>& object3dtoCImg3d(const CImgList<tp>& primitives, const bool full_check=true) { return get_object3dtoCImg3d(primitives,full_check).move_to(*this); } //! Convert 3D object into a CImg3d representation \overloading. CImg<T>& object3dtoCImg3d(const bool full_check=true) { return get_object3dtoCImg3d(full_check).move_to(*this); } //! Convert 3D object into a CImg3d representation \newinstance. template<typename tp, typename tc, typename to> CImg<floatT> get_object3dtoCImg3d(const CImgList<tp>& primitives, const CImgList<tc>& colors, const to& opacities, const bool full_check=true) const { CImg<charT> error_message(1024); if (!is_object3d(primitives,colors,opacities,full_check,error_message)) throw CImgInstanceException(_cimg_instance "object3dtoCImg3d(): Invalid specified 3D object (%u,%u) (%s).", cimg_instance,_width,primitives._width,error_message.data()); CImg<floatT> res(1,_size_object3dtoCImg3d(primitives,colors,opacities)); float *ptrd = res._data; // Put magick number. *(ptrd++) = 'C' + 0.5f; *(ptrd++) = 'I' + 0.5f; *(ptrd++) = 'm' + 0.5f; *(ptrd++) = 'g' + 0.5f; *(ptrd++) = '3' + 0.5f; *(ptrd++) = 'd' + 0.5f; // Put number of vertices and primitives. *(ptrd++) = cimg::uint2float(_width); *(ptrd++) = cimg::uint2float(primitives._width); // Put vertex data. if (is_empty() || !primitives) return res; const T *ptrx = data(0,0), *ptry = data(0,1), *ptrz = data(0,2); cimg_forX(*this,p) { *(ptrd++) = (float)*(ptrx++); *(ptrd++) = (float)*(ptry++); *(ptrd++) = (float)*(ptrz++); } // Put primitive data. cimglist_for(primitives,p) { *(ptrd++) = (float)primitives[p].size(); const tp *ptrp = primitives[p]._data; cimg_foroff(primitives[p],i) *(ptrd++) = cimg::uint2float((unsigned int)*(ptrp++)); } // Put color/texture data. const unsigned int csiz = std::min(colors._width,primitives._width); for (int c = 0; c<(int)csiz; ++c) { const CImg<tc>& color = colors[c]; const tc *ptrc = color._data; if (color.size()==3) { *(ptrd++) = (float)*(ptrc++); *(ptrd++) = (float)*(ptrc++); *(ptrd++) = (float)*ptrc; } else { *(ptrd++) = -128.f; int shared_ind = -1; if (color.is_shared()) for (int i = 0; i<c; ++i) if (ptrc==colors[i]._data) { shared_ind = i; break; } if (shared_ind<0) { *(ptrd++) = (float)color._width; *(ptrd++) = (float)color._height; *(ptrd++) = (float)color._spectrum; cimg_foroff(color,l) *(ptrd++) = (float)*(ptrc++); } else { *(ptrd++) = (float)shared_ind; *(ptrd++) = 0; *(ptrd++) = 0; } } } const int csiz2 = primitives.width() - colors.width(); for (int c = 0; c<csiz2; ++c) { *(ptrd++) = 200.f; *(ptrd++) = 200.f; *(ptrd++) = 200.f; } // Put opacity data. ptrd = _object3dtoCImg3d(opacities,ptrd); const float *ptre = res.end(); while (ptrd<ptre) *(ptrd++) = 1.f; return res; } template<typename to> float* _object3dtoCImg3d(const CImgList<to>& opacities, float *ptrd) const { cimglist_for(opacities,o) { const CImg<to>& opacity = opacities[o]; const to *ptro = opacity._data; if (opacity.size()==1) *(ptrd++) = (float)*ptro; else { *(ptrd++) = -128.f; int shared_ind = -1; if (opacity.is_shared()) for (int i = 0; i<o; ++i) if (ptro==opacities[i]._data) { shared_ind = i; break; } if (shared_ind<0) { *(ptrd++) = (float)opacity._width; *(ptrd++) = (float)opacity._height; *(ptrd++) = (float)opacity._spectrum; cimg_foroff(opacity,l) *(ptrd++) = (float)*(ptro++); } else { *(ptrd++) = (float)shared_ind; *(ptrd++) = 0; *(ptrd++) = 0; } } } return ptrd; } template<typename to> float* _object3dtoCImg3d(const CImg<to>& opacities, float *ptrd) const { const to *ptro = opacities._data; cimg_foroff(opacities,o) *(ptrd++) = (float)*(ptro++); return ptrd; } template<typename tp, typename tc, typename to> unsigned int _size_object3dtoCImg3d(const CImgList<tp>& primitives, const CImgList<tc>& colors, const CImgList<to>& opacities) const { unsigned int siz = 8U + 3*_width; cimglist_for(primitives,p) siz+=primitives[p].size() + 1; for (int c = std::min(primitives.width(),colors.width()) - 1; c>=0; --c) { if (colors[c].is_shared()) siz+=4; else { const unsigned int csiz = colors[c].size(); siz+=(csiz!=3)?4 + csiz:3; } } if (colors._width<primitives._width) siz+=3*(primitives._width - colors._width); cimglist_for(opacities,o) { if (opacities[o].is_shared()) siz+=4; else { const unsigned int osiz = opacities[o].size(); siz+=(osiz!=1)?4 + osiz:1; } } siz+=primitives._width - opacities._width; return siz; } template<typename tp, typename tc, typename to> unsigned int _size_object3dtoCImg3d(const CImgList<tp>& primitives, const CImgList<tc>& colors, const CImg<to>& opacities) const { unsigned int siz = 8U + 3*_width; cimglist_for(primitives,p) siz+=primitives[p].size() + 1; for (int c = std::min(primitives.width(),colors.width()) - 1; c>=0; --c) { const unsigned int csiz = colors[c].size(); siz+=(csiz!=3)?4 + csiz:3; } if (colors._width<primitives._width) siz+=3*(primitives._width - colors._width); siz+=primitives.size(); cimg::unused(opacities); return siz; } //! Convert 3D object into a CImg3d representation \overloading. template<typename tp, typename tc> CImg<floatT> get_object3dtoCImg3d(const CImgList<tp>& primitives, const CImgList<tc>& colors, const bool full_check=true) const { CImgList<T> opacities; return get_object3dtoCImg3d(primitives,colors,opacities,full_check); } //! Convert 3D object into a CImg3d representation \overloading. template<typename tp> CImg<floatT> get_object3dtoCImg3d(const CImgList<tp>& primitives, const bool full_check=true) const { CImgList<T> colors, opacities; return get_object3dtoCImg3d(primitives,colors,opacities,full_check); } //! Convert 3D object into a CImg3d representation \overloading. CImg<floatT> get_object3dtoCImg3d(const bool full_check=true) const { CImgList<T> opacities, colors; CImgList<uintT> primitives(width(),1,1,1,1); cimglist_for(primitives,p) primitives(p,0) = p; return get_object3dtoCImg3d(primitives,colors,opacities,full_check); } //! Convert CImg3d representation into a 3D object. /** \param[out] primitives Primitives data of the 3D object. \param[out] colors Colors data of the 3D object. \param[out] opacities Opacities data of the 3D object. \param full_check Tells if full checking of the 3D object must be performed. **/ template<typename tp, typename tc, typename to> CImg<T>& CImg3dtoobject3d(CImgList<tp>& primitives, CImgList<tc>& colors, CImgList<to>& opacities, const bool full_check=true) { return get_CImg3dtoobject3d(primitives,colors,opacities,full_check).move_to(*this); } //! Convert CImg3d representation into a 3D object \newinstance. template<typename tp, typename tc, typename to> CImg<T> get_CImg3dtoobject3d(CImgList<tp>& primitives, CImgList<tc>& colors, CImgList<to>& opacities, const bool full_check=true) const { CImg<charT> error_message(1024); if (!is_CImg3d(full_check,error_message)) throw CImgInstanceException(_cimg_instance "CImg3dtoobject3d(): image instance is not a CImg3d (%s).", cimg_instance,error_message.data()); const T *ptrs = _data + 6; const unsigned int nb_points = cimg::float2uint((float)*(ptrs++)), nb_primitives = cimg::float2uint((float)*(ptrs++)); const CImg<T> points = CImg<T>(ptrs,3,nb_points,1,1,true).get_transpose(); ptrs+=3*nb_points; primitives.assign(nb_primitives); cimglist_for(primitives,p) { const unsigned int nb_inds = (unsigned int)*(ptrs++); primitives[p].assign(1,nb_inds); tp *ptrp = primitives[p]._data; for (unsigned int i = 0; i<nb_inds; ++i) *(ptrp++) = (tp)cimg::float2uint((float)*(ptrs++)); } colors.assign(nb_primitives); cimglist_for(colors,c) { if (*ptrs==(T)-128) { ++ptrs; const unsigned int w = (unsigned int)*(ptrs++), h = (unsigned int)*(ptrs++), s = (unsigned int)*(ptrs++); if (!h && !s) colors[c].assign(colors[w],true); else { colors[c].assign(ptrs,w,h,1,s,false); ptrs+=w*h*s; } } else { colors[c].assign(ptrs,1,1,1,3,false); ptrs+=3; } } opacities.assign(nb_primitives); cimglist_for(opacities,o) { if (*ptrs==(T)-128) { ++ptrs; const unsigned int w = (unsigned int)*(ptrs++), h = (unsigned int)*(ptrs++), s = (unsigned int)*(ptrs++); if (!h && !s) opacities[o].assign(opacities[w],true); else { opacities[o].assign(ptrs,w,h,1,s,false); ptrs+=w*h*s; } } else opacities[o].assign(1,1,1,1,*(ptrs++)); } return points; } //@} //--------------------------- // //! \name Drawing Functions //@{ //--------------------------- #define cimg_init_scanline(opacity) \ static const T _sc_maxval = (T)std::min(cimg::type<T>::max(),(T)cimg::type<tc>::max()); \ const float _sc_nopacity = cimg::abs((float)opacity), _sc_copacity = 1 - std::max((float)opacity,0.f); \ const ulongT _sc_whd = (ulongT)_width*_height*_depth; \ cimg::unused(_sc_maxval); #define cimg_draw_scanline(x0,x1,y,color,opacity,brightness) \ _draw_scanline(x0,x1,y,color,opacity,brightness,_sc_nopacity,_sc_copacity,_sc_whd,_sc_maxval) // [internal] The following _draw_scanline() routines are *non user-friendly functions*, // used only for internal purpose. // Pre-requisites: x0<=x1, y-coordinate is valid, col is valid. template<typename tc> CImg<T>& _draw_scanline(const int x0, const int x1, const int y, const tc *const color, const float opacity, const float brightness, const float nopacity, const float copacity, const ulongT whd, const T _sc_maxval) { const int nx0 = x0>0?x0:0, nx1 = x1<width()?x1:width() - 1, dx = nx1 - nx0; if (dx>=0) { const tc *col = color; const ulongT off = whd - dx - 1; T *ptrd = data(nx0,y); if (opacity>=1) { // ** Opaque drawing ** if (brightness==1) { // Brightness==1 if (sizeof(T)!=1) cimg_forC(*this,c) { const T val = (T)*(col++); for (int x = dx; x>=0; --x) *(ptrd++) = val; ptrd+=off; } else cimg_forC(*this,c) { const T val = (T)*(col++); std::memset(ptrd,(int)val,dx + 1); ptrd+=whd; } } else if (brightness<1) { // Brightness<1 if (sizeof(T)!=1) cimg_forC(*this,c) { const T val = (T)(*(col++)*brightness); for (int x = dx; x>=0; --x) *(ptrd++) = val; ptrd+=off; } else cimg_forC(*this,c) { const T val = (T)(*(col++)*brightness); std::memset(ptrd,(int)val,dx + 1); ptrd+=whd; } } else { // Brightness>1 if (sizeof(T)!=1) cimg_forC(*this,c) { const T val = (T)((2-brightness)**(col++) + (brightness - 1)*_sc_maxval); for (int x = dx; x>=0; --x) *(ptrd++) = val; ptrd+=off; } else cimg_forC(*this,c) { const T val = (T)((2-brightness)**(col++) + (brightness - 1)*_sc_maxval); std::memset(ptrd,(int)val,dx + 1); ptrd+=whd; } } } else { // ** Transparent drawing ** if (brightness==1) { // Brightness==1 cimg_forC(*this,c) { const Tfloat val = *(col++)*nopacity; for (int x = dx; x>=0; --x) { *ptrd = (T)(val + *ptrd*copacity); ++ptrd; } ptrd+=off; } } else if (brightness<=1) { // Brightness<1 cimg_forC(*this,c) { const Tfloat val = *(col++)*brightness*nopacity; for (int x = dx; x>=0; --x) { *ptrd = (T)(val + *ptrd*copacity); ++ptrd; } ptrd+=off; } } else { // Brightness>1 cimg_forC(*this,c) { const Tfloat val = ((2-brightness)**(col++) + (brightness - 1)*_sc_maxval)*nopacity; for (int x = dx; x>=0; --x) { *ptrd = (T)(val + *ptrd*copacity); ++ptrd; } ptrd+=off; } } } } return *this; } //! Draw a 3D point. /** \param x0 X-coordinate of the point. \param y0 Y-coordinate of the point. \param z0 Z-coordinate of the point. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \note - To set pixel values without clipping needs, you should use the faster CImg::operator()() function. \par Example: \code CImg<unsigned char> img(100,100,1,3,0); const unsigned char color[] = { 255,128,64 }; img.draw_point(50,50,color); \endcode **/ template<typename tc> CImg<T>& draw_point(const int x0, const int y0, const int z0, const tc *const color, const float opacity=1) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_point(): Specified color is (null).", cimg_instance); if (x0>=0 && y0>=0 && z0>=0 && x0<width() && y0<height() && z0<depth()) { const ulongT whd = (ulongT)_width*_height*_depth; const float nopacity = cimg::abs(opacity), copacity = 1 - std::max(opacity,0.f); T *ptrd = data(x0,y0,z0,0); const tc *col = color; if (opacity>=1) cimg_forC(*this,c) { *ptrd = (T)*(col++); ptrd+=whd; } else cimg_forC(*this,c) { *ptrd = (T)(*(col++)*nopacity + *ptrd*copacity); ptrd+=whd; } } return *this; } //! Draw a 2D point \simplification. template<typename tc> CImg<T>& draw_point(const int x0, const int y0, const tc *const color, const float opacity=1) { return draw_point(x0,y0,0,color,opacity); } // Draw a points cloud. /** \param points Image of vertices coordinates. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. **/ template<typename t, typename tc> CImg<T>& draw_point(const CImg<t>& points, const tc *const color, const float opacity=1) { if (is_empty() || !points) return *this; switch (points._height) { case 0 : case 1 : throw CImgArgumentException(_cimg_instance "draw_point(): Invalid specified point set (%u,%u,%u,%u,%p).", cimg_instance, points._width,points._height,points._depth,points._spectrum,points._data); case 2 : { cimg_forX(points,i) draw_point((int)points(i,0),(int)points(i,1),color,opacity); } break; default : { cimg_forX(points,i) draw_point((int)points(i,0),(int)points(i,1),(int)points(i,2),color,opacity); } } return *this; } //! Draw a 2D line. /** \param x0 X-coordinate of the starting line point. \param y0 Y-coordinate of the starting line point. \param x1 X-coordinate of the ending line point. \param y1 Y-coordinate of the ending line point. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. \param pattern An integer whose bits describe the line pattern. \param init_hatch Tells if a reinitialization of the hash state must be done. \note - Line routine uses Bresenham's algorithm. - Set \p init_hatch = false to draw consecutive hatched segments without breaking the line pattern. \par Example: \code CImg<unsigned char> img(100,100,1,3,0); const unsigned char color[] = { 255,128,64 }; img.draw_line(40,40,80,70,color); \endcode **/ template<typename tc> CImg<T>& draw_line(int x0, int y0, int x1, int y1, const tc *const color, const float opacity=1, const unsigned int pattern=~0U, const bool init_hatch=true) { if (is_empty() || !opacity || !pattern || std::min(y0,y1)>=height() || std::max(y0,y1)<0 || std::min(x0,x1)>=width() || std::max(x0,x1)<0) return *this; int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dy01 = y1 - y0; const bool is_horizontal = cimg::abs(dx01)>cimg::abs(dy01); if (is_horizontal) cimg::swap(x0,y0,x1,y1,w1,h1,dx01,dy01); if (pattern==~0U && y0>y1) { cimg::swap(x0,x1,y0,y1); dx01*=-1; dy01*=-1; } static unsigned int hatch = ~0U - (~0U>>1); if (init_hatch) hatch = ~0U - (~0U>>1); cimg_init_scanline(opacity); const int step = y0<=y1?1:-1,hdy01 = dy01*cimg::sign(dx01)/2, cy0 = cimg::cut(y0,0,h1), cy1 = cimg::cut(y1,0,h1) + step; dy01+=dy01?0:1; for (int y = cy0; y!=cy1; y+=step) { const int yy0 = y - y0, x = x0 + (dx01*yy0 + hdy01)/dy01; if (x>=0 && x<=w1 && pattern&hatch) { T *const ptrd = is_horizontal?data(y,x):data(x,y); cimg_forC(*this,c) { const T val = color[c]; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } } if (!(hatch>>=1)) hatch = ~0U - (~0U>>1); } return *this; } //! Draw a 2D line, with z-buffering. /** \param zbuffer Zbuffer image. \param x0 X-coordinate of the starting point. \param y0 Y-coordinate of the starting point. \param z0 Z-coordinate of the starting point \param x1 X-coordinate of the ending point. \param y1 Y-coordinate of the ending point. \param z1 Z-coordinate of the ending point. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. \param pattern An integer whose bits describe the line pattern. \param init_hatch Tells if a reinitialization of the hash state must be done. **/ template<typename tz,typename tc> CImg<T>& draw_line(CImg<tz>& zbuffer, int x0, int y0, const float z0, int x1, int y1, const float z1, const tc *const color, const float opacity=1, const unsigned int pattern=~0U, const bool init_hatch=true) { if (is_empty() || z0<=0 || z1<=0 || !opacity || !pattern) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_line(): Specified color is (null).", cimg_instance); if (!is_sameXY(zbuffer)) throw CImgArgumentException(_cimg_instance "draw_line(): Instance and specified Z-buffer (%u,%u,%u,%u,%p) have " "different dimensions.", cimg_instance, zbuffer._width,zbuffer._height,zbuffer._depth,zbuffer._spectrum,zbuffer._data); if (std::min(y0,y1)>=height() || std::max(y0,y1)<0 || std::min(x0,x1)>=width() || std::max(x0,x1)<0) return *this; float iz0 = 1/z0, iz1 = 1/z1; int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dy01 = y1 - y0; float diz01 = iz1 - iz0; const bool is_horizontal = cimg::abs(dx01)>cimg::abs(dy01); if (is_horizontal) cimg::swap(x0,y0,x1,y1,w1,h1,dx01,dy01); if (pattern==~0U && y0>y1) { cimg::swap(x0,x1,y0,y1,iz0,iz1); dx01*=-1; dy01*=-1; diz01*=-1; } static unsigned int hatch = ~0U - (~0U>>1); if (init_hatch) hatch = ~0U - (~0U>>1); cimg_init_scanline(opacity); const int step = y0<=y1?1:-1, hdy01 = dy01*cimg::sign(dx01)/2, cy0 = cimg::cut(y0,0,h1), cy1 = cimg::cut(y1,0,h1) + step; dy01+=dy01?0:1; for (int y = cy0; y!=cy1; y+=step) { const int yy0 = y - y0, x = x0 + (dx01*yy0 + hdy01)/dy01; const float iz = iz0 + diz01*yy0/dy01; tz *const ptrz = is_horizontal?zbuffer.data(y,x):zbuffer.data(x,y); if (x>=0 && x<=w1 && pattern&hatch && iz>=*ptrz) { *ptrz = (tz)iz; T *const ptrd = is_horizontal?data(y,x):data(x,y); cimg_forC(*this,c) { const T val = color[c]; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } } if (!(hatch>>=1)) hatch = ~0U - (~0U>>1); } return *this; } //! Draw a textured 2D line. /** \param x0 X-coordinate of the starting line point. \param y0 Y-coordinate of the starting line point. \param x1 X-coordinate of the ending line point. \param y1 Y-coordinate of the ending line point. \param texture Texture image defining the pixel colors. \param tx0 X-coordinate of the starting texture point. \param ty0 Y-coordinate of the starting texture point. \param tx1 X-coordinate of the ending texture point. \param ty1 Y-coordinate of the ending texture point. \param opacity Drawing opacity. \param pattern An integer whose bits describe the line pattern. \param init_hatch Tells if the hash variable must be reinitialized. \note - Line routine uses the well known Bresenham's algorithm. \par Example: \code CImg<unsigned char> img(100,100,1,3,0), texture("texture256x256.ppm"); const unsigned char color[] = { 255,128,64 }; img.draw_line(40,40,80,70,texture,0,0,255,255); \endcode **/ template<typename tc> CImg<T>& draw_line(int x0, int y0, int x1, int y1, const CImg<tc>& texture, int tx0, int ty0, int tx1, int ty1, const float opacity=1, const unsigned int pattern=~0U, const bool init_hatch=true) { if (is_empty() || !opacity || !pattern) return *this; if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_line(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_overlapped(texture)) return draw_line(x0,y0,x1,y1,+texture,tx0,ty0,tx1,ty1,opacity,pattern,init_hatch); if (std::min(y0,y1)>=height() || std::max(y0,y1)<0 || std::min(x0,x1)>=width() || std::max(x0,x1)<0) return *this; int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dy01 = y1 - y0; int dtx01 = tx1 - tx0, dty01 = ty1 - ty0; const bool is_horizontal = cimg::abs(dx01)>cimg::abs(dy01); if (is_horizontal) cimg::swap(x0,y0,x1,y1,w1,h1,dx01,dy01); if (pattern==~0U && y0>y1) { cimg::swap(x0,x1,y0,y1,tx0,tx1,ty0,ty1); dx01*=-1; dy01*=-1; dtx01*=-1; dty01*=-1; } const ulongT twhd = (ulongT)texture._width*texture._height*texture._depth; static unsigned int hatch = ~0U - (~0U>>1); if (init_hatch) hatch = ~0U - (~0U>>1); cimg_init_scanline(opacity); const int step = y0<=y1?1:-1, hdy01 = dy01*cimg::sign(dx01)/2, hdy01tx = dy01*cimg::sign(dtx01)/2, hdy01ty = dy01*cimg::sign(dty01)/2, cy0 = cimg::cut(y0,0,h1), cy1 = cimg::cut(y1,0,h1) + step; dy01+=dy01?0:1; for (int y = cy0; y!=cy1; y+=step) { const int yy0 = y - y0, x = x0 + (dx01*yy0 + hdy01)/dy01, tx = tx0 + (dtx01*yy0 + hdy01tx)/dy01, ty = ty0 + (dty01*yy0 + hdy01ty)/dy01; if (x>=0 && x<=w1 && pattern&hatch) { T *const ptrd = is_horizontal?data(y,x):data(x,y); const tc *const color = &texture._atXY(tx,ty); cimg_forC(*this,c) { const T val = color[c*twhd]; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } } if (!(hatch>>=1)) hatch = ~0U - (~0U>>1); } return *this; } //! Draw a textured 2D line, with perspective correction. /** \param x0 X-coordinate of the starting point. \param y0 Y-coordinate of the starting point. \param z0 Z-coordinate of the starting point \param x1 X-coordinate of the ending point. \param y1 Y-coordinate of the ending point. \param z1 Z-coordinate of the ending point. \param texture Texture image defining the pixel colors. \param tx0 X-coordinate of the starting texture point. \param ty0 Y-coordinate of the starting texture point. \param tx1 X-coordinate of the ending texture point. \param ty1 Y-coordinate of the ending texture point. \param opacity Drawing opacity. \param pattern An integer whose bits describe the line pattern. \param init_hatch Tells if the hash variable must be reinitialized. **/ template<typename tc> CImg<T>& draw_line(int x0, int y0, const float z0, int x1, int y1, const float z1, const CImg<tc>& texture, const int tx0, const int ty0, const int tx1, const int ty1, const float opacity=1, const unsigned int pattern=~0U, const bool init_hatch=true) { if (is_empty() || z0<=0 || z1<=0 || !opacity || !pattern) return *this; if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_line(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_overlapped(texture)) return draw_line(x0,y0,z0,x1,y1,z1,+texture,tx0,ty0,tx1,ty1,opacity,pattern,init_hatch); if (std::min(y0,y1)>=height() || std::max(y0,y1)<0 || std::min(x0,x1)>=width() || std::max(x0,x1)<0) return *this; float iz0 = 1/z0, iz1 = 1/z1; int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dy01 = y1 - y0; float diz01 = iz1 - iz0, txz0 = tx0*iz0, txz1 = tx1*iz1, tyz0 = ty0*iz0, tyz1 = ty1*iz1, dtxz01 = txz1 - txz0, dtyz01 = tyz1 - tyz0; const bool is_horizontal = cimg::abs(dx01)>cimg::abs(dy01); if (is_horizontal) cimg::swap(x0,y0,x1,y1,w1,h1,dx01,dy01); if (pattern==~0U && y0>y1) { cimg::swap(x0,x1,y0,y1,iz0,iz1,txz0,txz1,tyz0,tyz1); dx01*=-1; dy01*=-1; diz01*=-1; dtxz01*=-1; dtyz01*=-1; } const ulongT twhd = (ulongT)texture._width*texture._height*texture._depth; static unsigned int hatch = ~0U - (~0U>>1); if (init_hatch) hatch = ~0U - (~0U>>1); cimg_init_scanline(opacity); const int step = y0<=y1?1:-1, hdy01 = dy01*cimg::sign(dx01)/2, cy0 = cimg::cut(y0,0,h1), cy1 = cimg::cut(y1,0,h1) + step; dy01+=dy01?0:1; for (int y = cy0; y!=cy1; y+=step) { const int yy0 = y - y0, x = x0 + (dx01*yy0 + hdy01)/dy01; const float iz = iz0 + diz01*yy0/dy01, txz = txz0 + dtxz01*yy0/dy01, tyz = tyz0 + dtyz01*yy0/dy01; if (x>=0 && x<=w1 && pattern&hatch) { const int tx = (int)cimg::round(txz/iz), ty = (int)cimg::round(tyz/iz); T *const ptrd = is_horizontal?data(y,x):data(x,y); const tc *const color = &texture._atXY(tx,ty); cimg_forC(*this,c) { const T val = color[c*twhd]; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } } if (!(hatch>>=1)) hatch = ~0U - (~0U>>1); } return *this; } //! Draw a textured 2D line, with perspective correction and z-buffering. /** \param zbuffer Z-buffer image. \param x0 X-coordinate of the starting point. \param y0 Y-coordinate of the starting point. \param z0 Z-coordinate of the starting point \param x1 X-coordinate of the ending point. \param y1 Y-coordinate of the ending point. \param z1 Z-coordinate of the ending point. \param texture Texture image defining the pixel colors. \param tx0 X-coordinate of the starting texture point. \param ty0 Y-coordinate of the starting texture point. \param tx1 X-coordinate of the ending texture point. \param ty1 Y-coordinate of the ending texture point. \param opacity Drawing opacity. \param pattern An integer whose bits describe the line pattern. \param init_hatch Tells if the hash variable must be reinitialized. **/ template<typename tz, typename tc> CImg<T>& draw_line(CImg<tz>& zbuffer, int x0, int y0, const float z0, int x1, int y1, const float z1, const CImg<tc>& texture, const int tx0, const int ty0, const int tx1, const int ty1, const float opacity=1, const unsigned int pattern=~0U, const bool init_hatch=true) { if (is_empty() || z0<=0 || z1<=0 || !opacity || !pattern) return *this; if (!is_sameXY(zbuffer)) throw CImgArgumentException(_cimg_instance "draw_line(): Instance and specified Z-buffer (%u,%u,%u,%u,%p) have " "different dimensions.", cimg_instance, zbuffer._width,zbuffer._height,zbuffer._depth,zbuffer._spectrum,zbuffer._data); if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_line(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_overlapped(texture)) return draw_line(zbuffer,x0,y0,z0,x1,y1,z1,+texture,tx0,ty0,tx1,ty1,opacity,pattern,init_hatch); if (std::min(y0,y1)>=height() || std::max(y0,y1)<0 || std::min(x0,x1)>=width() || std::max(x0,x1)<0) return *this; float iz0 = 1/z0, iz1 = 1/z1; int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dy01 = y1 - y0; float diz01 = iz1 - iz0, txz0 = tx0*iz0, txz1 = tx1*iz1, tyz0 = ty0*iz0, tyz1 = ty1*iz1, dtxz01 = txz1 - txz0, dtyz01 = tyz1 - tyz0; const bool is_horizontal = cimg::abs(dx01)>cimg::abs(dy01); if (is_horizontal) cimg::swap(x0,y0,x1,y1,w1,h1,dx01,dy01); if (pattern==~0U && y0>y1) { cimg::swap(x0,x1,y0,y1,iz0,iz1,txz0,txz1,tyz0,tyz1); dx01*=-1; dy01*=-1; diz01*=-1; dtxz01*=-1; dtyz01*=-1; } const ulongT twhd = (ulongT)texture._width*texture._height*texture._depth; static unsigned int hatch = ~0U - (~0U>>1); if (init_hatch) hatch = ~0U - (~0U>>1); cimg_init_scanline(opacity); const int step = y0<=y1?1:-1, hdy01 = dy01*cimg::sign(dx01)/2, cy0 = cimg::cut(y0,0,h1), cy1 = cimg::cut(y1,0,h1) + step; dy01+=dy01?0:1; for (int y = cy0; y!=cy1; y+=step) { const int yy0 = y - y0, x = x0 + (dx01*yy0 + hdy01)/dy01; const float iz = iz0 + diz01*yy0/dy01, txz = txz0 + dtxz01*yy0/dy01, tyz = tyz0 + dtyz01*yy0/dy01; tz *const ptrz = is_horizontal?zbuffer.data(y,x):zbuffer.data(x,y); if (x>=0 && x<=w1 && pattern&hatch && iz>=*ptrz) { *ptrz = (tz)iz; const int tx = (int)cimg::round(txz/iz), ty = (int)cimg::round(tyz/iz); T *const ptrd = is_horizontal?data(y,x):data(x,y); const tc *const color = &texture._atXY(tx,ty); cimg_forC(*this,c) { const T val = color[c*twhd]; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } } if (!(hatch>>=1)) hatch = ~0U - (~0U>>1); } return *this; } //! Draw a set of consecutive lines. /** \param points Coordinates of vertices, stored as a list of vectors. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. \param pattern An integer whose bits describe the line pattern. \param init_hatch If set to true, init hatch motif. \note - This function uses several call to the single CImg::draw_line() procedure, depending on the vectors size in \p points. **/ template<typename t, typename tc> CImg<T>& draw_line(const CImg<t>& points, const tc *const color, const float opacity=1, const unsigned int pattern=~0U, const bool init_hatch=true) { if (is_empty() || !points || points._width<2) return *this; bool ninit_hatch = init_hatch; switch (points._height) { case 0 : case 1 : throw CImgArgumentException(_cimg_instance "draw_line(): Invalid specified point set (%u,%u,%u,%u,%p).", cimg_instance, points._width,points._height,points._depth,points._spectrum,points._data); default : { const int x0 = (int)points(0,0), y0 = (int)points(0,1); int ox = x0, oy = y0; for (unsigned int i = 1; i<points._width; ++i) { const int x = (int)points(i,0), y = (int)points(i,1); draw_line(ox,oy,x,y,color,opacity,pattern,ninit_hatch); ninit_hatch = false; ox = x; oy = y; } } } return *this; } //! Draw a 2D arrow. /** \param x0 X-coordinate of the starting arrow point (tail). \param y0 Y-coordinate of the starting arrow point (tail). \param x1 X-coordinate of the ending arrow point (head). \param y1 Y-coordinate of the ending arrow point (head). \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param angle Aperture angle of the arrow head. \param length Length of the arrow head. If negative, describes a percentage of the arrow length. \param opacity Drawing opacity. \param pattern An integer whose bits describe the line pattern. **/ template<typename tc> CImg<T>& draw_arrow(const int x0, const int y0, const int x1, const int y1, const tc *const color, const float opacity=1, const float angle=30, const float length=-10, const unsigned int pattern=~0U) { if (is_empty()) return *this; const float u = (float)(x0 - x1), v = (float)(y0 - y1), sq = u*u + v*v, deg = (float)(angle*cimg::PI/180), ang = (sq>0)?(float)std::atan2(v,u):0.f, l = (length>=0)?length:-length*(float)std::sqrt(sq)/100; if (sq>0) { const float cl = (float)std::cos(ang - deg), sl = (float)std::sin(ang - deg), cr = (float)std::cos(ang + deg), sr = (float)std::sin(ang + deg); const int xl = x1 + (int)(l*cl), yl = y1 + (int)(l*sl), xr = x1 + (int)(l*cr), yr = y1 + (int)(l*sr), xc = x1 + (int)((l + 1)*(cl + cr))/2, yc = y1 + (int)((l + 1)*(sl + sr))/2; draw_line(x0,y0,xc,yc,color,opacity,pattern).draw_triangle(x1,y1,xl,yl,xr,yr,color,opacity); } else draw_point(x0,y0,color,opacity); return *this; } //! Draw a 2D spline. /** \param x0 X-coordinate of the starting curve point \param y0 Y-coordinate of the starting curve point \param u0 X-coordinate of the starting velocity \param v0 Y-coordinate of the starting velocity \param x1 X-coordinate of the ending curve point \param y1 Y-coordinate of the ending curve point \param u1 X-coordinate of the ending velocity \param v1 Y-coordinate of the ending velocity \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param precision Curve drawing precision. \param opacity Drawing opacity. \param pattern An integer whose bits describe the line pattern. \param init_hatch If \c true, init hatch motif. \note - The curve is a 2D cubic Bezier spline, from the set of specified starting/ending points and corresponding velocity vectors. - The spline is drawn as a serie of connected segments. The \p precision parameter sets the average number of pixels in each drawn segment. - A cubic Bezier curve is sometimes defined by a set of 4 points { (\p x0,\p y0), (\p xa,\p ya), (\p xb,\p yb), (\p x1,\p y1) } where (\p x0,\p y0) is the starting point, (\p x1,\p y1) is the ending point and (\p xa,\p ya), (\p xb,\p yb) are two \e control points. The starting and ending velocities (\p u0,\p v0) and (\p u1,\p v1) can be deduced easily from the control points as \p u0 = (\p xa - \p x0), \p v0 = (\p ya - \p y0), \p u1 = (\p x1 - \p xb) and \p v1 = (\p y1 - \p yb). \par Example: \code CImg<unsigned char> img(100,100,1,3,0); const unsigned char color[] = { 255,255,255 }; img.draw_spline(30,30,0,100,90,40,0,-100,color); \endcode **/ template<typename tc> CImg<T>& draw_spline(const int x0, const int y0, const float u0, const float v0, const int x1, const int y1, const float u1, const float v1, const tc *const color, const float opacity=1, const float precision=0.25, const unsigned int pattern=~0U, const bool init_hatch=true) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_spline(): Specified color is (null).", cimg_instance); if (x0==x1 && y0==y1) return draw_point(x0,y0,color,opacity); bool ninit_hatch = init_hatch; const float ax = u0 + u1 + 2*(x0 - x1), bx = 3*(x1 - x0) - 2*u0 - u1, ay = v0 + v1 + 2*(y0 - y1), by = 3*(y1 - y0) - 2*v0 - v1, _precision = 1/(cimg::hypot((float)x0 - x1,(float)y0 - y1)*(precision>0?precision:1)); int ox = x0, oy = y0; for (float t = 0; t<1; t+=_precision) { const float t2 = t*t, t3 = t2*t; const int nx = (int)(ax*t3 + bx*t2 + u0*t + x0), ny = (int)(ay*t3 + by*t2 + v0*t + y0); draw_line(ox,oy,nx,ny,color,opacity,pattern,ninit_hatch); ninit_hatch = false; ox = nx; oy = ny; } return draw_line(ox,oy,x1,y1,color,opacity,pattern,false); } //! Draw a textured 2D spline. /** \param x0 X-coordinate of the starting curve point \param y0 Y-coordinate of the starting curve point \param u0 X-coordinate of the starting velocity \param v0 Y-coordinate of the starting velocity \param x1 X-coordinate of the ending curve point \param y1 Y-coordinate of the ending curve point \param u1 X-coordinate of the ending velocity \param v1 Y-coordinate of the ending velocity \param texture Texture image defining line pixel colors. \param tx0 X-coordinate of the starting texture point. \param ty0 Y-coordinate of the starting texture point. \param tx1 X-coordinate of the ending texture point. \param ty1 Y-coordinate of the ending texture point. \param precision Curve drawing precision. \param opacity Drawing opacity. \param pattern An integer whose bits describe the line pattern. \param init_hatch if \c true, reinit hatch motif. **/ template<typename t> CImg<T>& draw_spline(const int x0, const int y0, const float u0, const float v0, const int x1, const int y1, const float u1, const float v1, const CImg<t>& texture, const int tx0, const int ty0, const int tx1, const int ty1, const float opacity=1, const float precision=4, const unsigned int pattern=~0U, const bool init_hatch=true) { if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_spline(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_empty()) return *this; if (is_overlapped(texture)) return draw_spline(x0,y0,u0,v0,x1,y1,u1,v1,+texture,tx0,ty0,tx1,ty1,precision,opacity,pattern,init_hatch); if (x0==x1 && y0==y1) return draw_point(x0,y0,texture.get_vector_at(x0<=0?0:x0>=texture.width()?texture.width() - 1:x0, y0<=0?0:y0>=texture.height()?texture.height() - 1:y0).data(), opacity); bool ninit_hatch = init_hatch; const float ax = u0 + u1 + 2*(x0 - x1), bx = 3*(x1 - x0) - 2*u0 - u1, ay = v0 + v1 + 2*(y0 - y1), by = 3*(y1 - y0) - 2*v0 - v1, _precision = 1/(cimg::hypot((float)x0 - x1,(float)y0 - y1)*(precision>0?precision:1)); int ox = x0, oy = y0, otx = tx0, oty = ty0; for (float t1 = 0; t1<1; t1+=_precision) { const float t2 = t1*t1, t3 = t2*t1; const int nx = (int)(ax*t3 + bx*t2 + u0*t1 + x0), ny = (int)(ay*t3 + by*t2 + v0*t1 + y0), ntx = tx0 + (int)((tx1 - tx0)*t1), nty = ty0 + (int)((ty1 - ty0)*t1); draw_line(ox,oy,nx,ny,texture,otx,oty,ntx,nty,opacity,pattern,ninit_hatch); ninit_hatch = false; ox = nx; oy = ny; otx = ntx; oty = nty; } return draw_line(ox,oy,x1,y1,texture,otx,oty,tx1,ty1,opacity,pattern,false); } //! Draw a set of consecutive splines. /** \param points Vertices data. \param tangents Tangents data. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. \param is_closed_set Tells if the drawn spline set is closed. \param precision Precision of the drawing. \param pattern An integer whose bits describe the line pattern. \param init_hatch If \c true, init hatch motif. **/ template<typename tp, typename tt, typename tc> CImg<T>& draw_spline(const CImg<tp>& points, const CImg<tt>& tangents, const tc *const color, const float opacity=1, const bool is_closed_set=false, const float precision=4, const unsigned int pattern=~0U, const bool init_hatch=true) { if (is_empty() || !points || !tangents || points._width<2 || tangents._width<2) return *this; bool ninit_hatch = init_hatch; switch (points._height) { case 0 : case 1 : throw CImgArgumentException(_cimg_instance "draw_spline(): Invalid specified point set (%u,%u,%u,%u,%p).", cimg_instance, points._width,points._height,points._depth,points._spectrum,points._data); default : { const int x0 = (int)points(0,0), y0 = (int)points(0,1); const float u0 = (float)tangents(0,0), v0 = (float)tangents(0,1); int ox = x0, oy = y0; float ou = u0, ov = v0; for (unsigned int i = 1; i<points._width; ++i) { const int x = (int)points(i,0), y = (int)points(i,1); const float u = (float)tangents(i,0), v = (float)tangents(i,1); draw_spline(ox,oy,ou,ov,x,y,u,v,color,precision,opacity,pattern,ninit_hatch); ninit_hatch = false; ox = x; oy = y; ou = u; ov = v; } if (is_closed_set) draw_spline(ox,oy,ou,ov,x0,y0,u0,v0,color,precision,opacity,pattern,false); } } return *this; } //! Draw a set of consecutive splines \overloading. /** Similar to previous function, with the point tangents automatically estimated from the given points set. **/ template<typename tp, typename tc> CImg<T>& draw_spline(const CImg<tp>& points, const tc *const color, const float opacity=1, const bool is_closed_set=false, const float precision=4, const unsigned int pattern=~0U, const bool init_hatch=true) { if (is_empty() || !points || points._width<2) return *this; CImg<Tfloat> tangents; switch (points._height) { case 0 : case 1 : throw CImgArgumentException(_cimg_instance "draw_spline(): Invalid specified point set (%u,%u,%u,%u,%p).", cimg_instance, points._width,points._height,points._depth,points._spectrum,points._data); case 2 : { tangents.assign(points._width,points._height); cimg_forX(points,p) { const unsigned int p0 = is_closed_set?(p + points.width() - 1)%points.width():(p?p - 1:0), p1 = is_closed_set?(p + 1)%points.width():(p + 1<points.width()?p + 1:p); const float x = (float)points(p,0), y = (float)points(p,1), x0 = (float)points(p0,0), y0 = (float)points(p0,1), x1 = (float)points(p1,0), y1 = (float)points(p1,1), u0 = x - x0, v0 = y - y0, n0 = 1e-8f + cimg::hypot(u0,v0), u1 = x1 - x, v1 = y1 - y, n1 = 1e-8f + cimg::hypot(u1,v1), u = u0/n0 + u1/n1, v = v0/n0 + v1/n1, n = 1e-8f + cimg::hypot(u,v), fact = 0.5f*(n0 + n1); tangents(p,0) = (Tfloat)(fact*u/n); tangents(p,1) = (Tfloat)(fact*v/n); } } break; default : { tangents.assign(points._width,points._height); cimg_forX(points,p) { const unsigned int p0 = is_closed_set?(p + points.width() - 1)%points.width():(p?p - 1:0), p1 = is_closed_set?(p + 1)%points.width():(p + 1<points.width()?p + 1:p); const float x = (float)points(p,0), y = (float)points(p,1), z = (float)points(p,2), x0 = (float)points(p0,0), y0 = (float)points(p0,1), z0 = (float)points(p0,2), x1 = (float)points(p1,0), y1 = (float)points(p1,1), z1 = (float)points(p1,2), u0 = x - x0, v0 = y - y0, w0 = z - z0, n0 = 1e-8f + cimg::hypot(u0,v0,w0), u1 = x1 - x, v1 = y1 - y, w1 = z1 - z, n1 = 1e-8f + cimg::hypot(u1,v1,w1), u = u0/n0 + u1/n1, v = v0/n0 + v1/n1, w = w0/n0 + w1/n1, n = 1e-8f + cimg::hypot(u,v,w), fact = 0.5f*(n0 + n1); tangents(p,0) = (Tfloat)(fact*u/n); tangents(p,1) = (Tfloat)(fact*v/n); tangents(p,2) = (Tfloat)(fact*w/n); } } } return draw_spline(points,tangents,color,opacity,is_closed_set,precision,pattern,init_hatch); } // [internal] Draw a filled triangle. template<typename tc> CImg<T>& _draw_triangle(int x0, int y0, int x1, int y1, int x2, int y2, const tc *const color, const float opacity, const float brightness) { if (y0>y1) cimg::swap(x0,x1,y0,y1); if (y0>y2) cimg::swap(x0,x2,y0,y2); if (y1>y2) cimg::swap(x1,x2,y1,y2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2; const float cbs = cimg::cut(brightness,0,2); cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02; if (xm>xM) cimg::swap(xm,xM); cimg_draw_scanline(xm,xM,y,color,opacity,cbs); } return *this; } //! Draw a filled 2D triangle. /** \param x0 X-coordinate of the first vertex. \param y0 Y-coordinate of the first vertex. \param x1 X-coordinate of the second vertex. \param y1 Y-coordinate of the second vertex. \param x2 X-coordinate of the third vertex. \param y2 Y-coordinate of the third vertex. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. **/ template<typename tc> CImg<T>& draw_triangle(const int x0, const int y0, const int x1, const int y1, const int x2, const int y2, const tc *const color, const float opacity=1) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_triangle(): Specified color is (null).", cimg_instance); _draw_triangle(x0,y0,x1,y1,x2,y2,color,opacity,1); return *this; } //! Draw a outlined 2D triangle. /** \param x0 X-coordinate of the first vertex. \param y0 Y-coordinate of the first vertex. \param x1 X-coordinate of the second vertex. \param y1 Y-coordinate of the second vertex. \param x2 X-coordinate of the third vertex. \param y2 Y-coordinate of the third vertex. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. \param pattern An integer whose bits describe the outline pattern. **/ template<typename tc> CImg<T>& draw_triangle(const int x0, const int y0, const int x1, const int y1, const int x2, const int y2, const tc *const color, const float opacity, const unsigned int pattern) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_triangle(): Specified color is (null).", cimg_instance); draw_line(x0,y0,x1,y1,color,opacity,pattern,true). draw_line(x1,y1,x2,y2,color,opacity,pattern,false). draw_line(x2,y2,x0,y0,color,opacity,pattern,false); return *this; } //! Draw a filled 2D triangle, with z-buffering. /** \param zbuffer Z-buffer image. \param x0 X-coordinate of the first vertex. \param y0 Y-coordinate of the first vertex. \param z0 Z-coordinate of the first vertex. \param x1 X-coordinate of the second vertex. \param y1 Y-coordinate of the second vertex. \param z1 Z-coordinate of the second vertex. \param x2 X-coordinate of the third vertex. \param y2 Y-coordinate of the third vertex. \param z2 Z-coordinate of the third vertex. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. \param brightness Brightness factor. **/ template<typename tz, typename tc> CImg<T>& draw_triangle(CImg<tz>& zbuffer, int x0, int y0, const float z0, int x1, int y1, const float z1, int x2, int y2, const float z2, const tc *const color, const float opacity=1, const float brightness=1) { if (is_empty() || z0<=0 || z1<=0 || z2<=0) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_triangle(): Specified color is (null).", cimg_instance); if (!is_sameXY(zbuffer)) throw CImgArgumentException(_cimg_instance "draw_triangle(): Instance and specified Z-buffer (%u,%u,%u,%u,%p) have " "different dimensions.", cimg_instance, zbuffer._width,zbuffer._height,zbuffer._depth,zbuffer._spectrum,zbuffer._data); float iz0 = 1/z0, iz1 = 1/z1, iz2 = 1/z2; if (y0>y1) cimg::swap(x0,x1,y0,y1,iz0,iz1); if (y0>y2) cimg::swap(x0,x2,y0,y2,iz0,iz2); if (y1>y2) cimg::swap(x1,x2,y1,y2,iz1,iz2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2; const float diz01 = iz1 - iz0, diz02 = iz2 - iz0, diz12 = iz2 - iz1; const float cbs = cimg::cut(brightness,0,2); cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02; float izm = y<y1?(iz0 + diz01*yy0/dy01):(iz1 + diz12*yy1/dy12), izM = iz0 + diz02*yy0/dy02; if (xm>xM) cimg::swap(xm,xM,izm,izM); if (xM>=0 || xm<=w1) { const int cxm = cimg::cut(xm,0,w1), cxM = cimg::cut(xM,0,w1); T *ptrd = data(cxm,y); tz *ptrz = zbuffer.data(cxm,y); const int dxmM = std::max(1,xM - xm); const float dizmM = izM - izm; for (int x = cxm; x<cxM; ++x) { const int xxm = x - xm; const float iz = izm + dizmM*xxm/dxmM; if (iz>=*ptrz) { *ptrz = (tz)iz; cimg_forC(*this,c) { const Tfloat val = cbs<=1?color[c]*cbs:(2 - cbs)*color[c] + (cbs - 1)*_sc_maxval; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } } ++ptrd; ++ptrz; } } } return *this; } //! Draw a Gouraud-shaded 2D triangle. /** \param x0 X-coordinate of the first vertex in the image instance. \param y0 Y-coordinate of the first vertex in the image instance. \param x1 X-coordinate of the second vertex in the image instance. \param y1 Y-coordinate of the second vertex in the image instance. \param x2 X-coordinate of the third vertex in the image instance. \param y2 Y-coordinate of the third vertex in the image instance. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param bs0 Brightness factor of the first vertex (in [0,2]). \param bs1 brightness factor of the second vertex (in [0,2]). \param bs2 brightness factor of the third vertex (in [0,2]). \param opacity Drawing opacity. **/ template<typename tc> CImg<T>& draw_triangle(int x0, int y0, int x1, int y1, int x2, int y2, const tc *const color, float bs0, float bs1, float bs2, const float opacity=1) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_triangle(): Specified color is (null).", cimg_instance); if (y0>y1) cimg::swap(x0,x1,y0,y1,bs0,bs1); if (y0>y2) cimg::swap(x0,x2,y0,y2,bs0,bs2); if (y1>y2) cimg::swap(x1,x2,y1,y2,bs1,bs2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2; const float dbs01 = bs1 - bs0, dbs02 = bs2 - bs0, dbs12 = bs2 - bs1; cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02; float bsm = y<y1?(bs0 + dbs01*yy0/dy01):(bs1 + dbs12*yy1/dy12), bsM = bs0 + dbs02*yy0/dy02; if (xm>xM) cimg::swap(xm,xM,bsm,bsM); if (xM>=0 || xm<=w1) { const int cxm = cimg::cut(xm,0,w1), cxM = cimg::cut(xM,0,w1); T *ptrd = data(cxm,y); const int dxmM = std::max(1,xM - xm); const float dbsmM = bsM - bsm; for (int x = cxm; x<=cxM; ++x) { const int xxm = x - xm; const float cbs = cimg::cut(bsm + dbsmM*xxm/dxmM,0,2); cimg_forC(*this,c) { const Tfloat val = cbs<=1?color[c]*cbs:(2 - cbs)*color[c] + (cbs - 1)*_sc_maxval; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } ++ptrd; } } } return *this; } //! Draw a Gouraud-shaded 2D triangle, with z-buffering \overloading. template<typename tz, typename tc> CImg<T>& draw_triangle(CImg<tz>& zbuffer, int x0, int y0, const float z0, int x1, int y1, const float z1, int x2, int y2, const float z2, const tc *const color, float bs0, float bs1, float bs2, float opacity=1) { if (is_empty() || z0<=0 || z1<=0 || z2<=0) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_triangle(): Specified color is (null).", cimg_instance); if (!is_sameXY(zbuffer)) throw CImgArgumentException(_cimg_instance "draw_triangle(): Instance and specified Z-buffer (%u,%u,%u,%u,%p) have " "different dimensions.", cimg_instance, zbuffer._width,zbuffer._height,zbuffer._depth,zbuffer._spectrum,zbuffer._data); float iz0 = 1/z0, iz1 = 1/z1, iz2 = 1/z2; if (y0>y1) cimg::swap(x0,x1,y0,y1,iz0,iz1,bs0,bs1); if (y0>y2) cimg::swap(x0,x2,y0,y2,iz0,iz2,bs0,bs2); if (y1>y2) cimg::swap(x1,x2,y1,y2,iz1,iz2,bs1,bs2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2; const float diz01 = iz1 - iz0, diz02 = iz2 - iz0, diz12 = iz2 - iz1, dbs01 = bs1 - bs0, dbs02 = bs2 - bs0, dbs12 = bs2 - bs1; cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02; float izm = y<y1?(iz0 + diz01*yy0/dy01):(iz1 + diz12*yy1/dy12), izM = iz0 + diz02*yy0/dy02, bsm = y<y1?(bs0 + dbs01*yy0/dy01):(bs1 + dbs12*yy1/dy12), bsM = bs0 + dbs02*yy0/dy02; if (xm>xM) cimg::swap(xm,xM,izm,izM,bsm,bsM); if (xM>=0 || xm<=w1) { const int cxm = cimg::cut(xm,0,w1), cxM = cimg::cut(xM,0,w1); T *ptrd = data(cxm,y); tz *ptrz = zbuffer.data(cxm,y); const int dxmM = std::max(1,xM - xm); const float dizmM = izM - izm, dbsmM = bsM - bsm; for (int x = cxm; x<=cxM; ++x) { const int xxm = x - xm; const float iz = izm + dizmM*xxm/dxmM; if (iz>=*ptrz) { *ptrz = (tz)iz; const float cbs = cimg::cut(bsm + dbsmM*xxm/dxmM,0,2); cimg_forC(*this,c) { const Tfloat val = cbs<=1?color[c]*cbs:(2 - cbs)*color[c] + (cbs - 1)*_sc_maxval; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } } ++ptrd; ++ptrz; } } } return *this; } //! Draw a color-interpolated 2D triangle. /** \param x0 X-coordinate of the first vertex in the image instance. \param y0 Y-coordinate of the first vertex in the image instance. \param x1 X-coordinate of the second vertex in the image instance. \param y1 Y-coordinate of the second vertex in the image instance. \param x2 X-coordinate of the third vertex in the image instance. \param y2 Y-coordinate of the third vertex in the image instance. \param color1 Pointer to \c spectrum() consecutive values of type \c T, defining the color of the first vertex. \param color2 Pointer to \c spectrum() consecutive values of type \c T, defining the color of the seconf vertex. \param color3 Pointer to \c spectrum() consecutive values of type \c T, defining the color of the third vertex. \param opacity Drawing opacity. **/ template<typename tc1, typename tc2, typename tc3> CImg<T>& draw_triangle(const int x0, const int y0, const int x1, const int y1, const int x2, const int y2, const tc1 *const color1, const tc2 *const color2, const tc3 *const color3, const float opacity=1) { const unsigned char one = 1; cimg_forC(*this,c) get_shared_channel(c).draw_triangle(x0,y0,x1,y1,x2,y2,&one,color1[c],color2[c],color3[c],opacity); return *this; } //! Draw a textured 2D triangle. /** \param x0 X-coordinate of the first vertex in the image instance. \param y0 Y-coordinate of the first vertex in the image instance. \param x1 X-coordinate of the second vertex in the image instance. \param y1 Y-coordinate of the second vertex in the image instance. \param x2 X-coordinate of the third vertex in the image instance. \param y2 Y-coordinate of the third vertex in the image instance. \param texture Texture image used to fill the triangle. \param tx0 X-coordinate of the first vertex in the texture image. \param ty0 Y-coordinate of the first vertex in the texture image. \param tx1 X-coordinate of the second vertex in the texture image. \param ty1 Y-coordinate of the second vertex in the texture image. \param tx2 X-coordinate of the third vertex in the texture image. \param ty2 Y-coordinate of the third vertex in the texture image. \param opacity Drawing opacity. \param brightness Brightness factor of the drawing (in [0,2]). **/ template<typename tc> CImg<T>& draw_triangle(int x0, int y0, int x1, int y1, int x2, int y2, const CImg<tc>& texture, int tx0, int ty0, int tx1, int ty1, int tx2, int ty2, const float opacity=1, const float brightness=1) { if (is_empty()) return *this; if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_overlapped(texture)) return draw_triangle(x0,y0,x1,y1,x2,y2,+texture,tx0,ty0,tx1,ty1,tx2,ty2,opacity,brightness); if (y0>y1) cimg::swap(x0,x1,y0,y1,tx0,tx1,ty0,ty1); if (y0>y2) cimg::swap(x0,x2,y0,y2,tx0,tx2,ty0,ty2); if (y1>y2) cimg::swap(x1,x2,y1,y2,tx1,ty1,tx2,ty2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2, dtx01 = tx1 - tx0, dtx02 = tx2 - tx0, dtx12 = tx2 - tx1, dty01 = ty1 - ty0, dty02 = ty2 - ty0, dty12 = ty2 - ty1, hdy01tx = dy01*cimg::sign(dtx01)/2, hdy02tx = dy02*cimg::sign(dtx02)/2, hdy12tx = dy12*cimg::sign(dtx12)/2, hdy01ty = dy01*cimg::sign(dty01)/2, hdy02ty = dy02*cimg::sign(dty02)/2, hdy12ty = dy12*cimg::sign(dty12)/2; const ulongT twhd = (ulongT)texture._width*texture._height*texture._depth; const float cbs = cimg::cut(brightness,0,2); cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02, txm = y<y1?tx0 + (dtx01*yy0 + hdy01tx)/dy01:tx1 + (dtx12*yy1 + hdy12tx)/dy12, txM = tx0 + (dtx02*yy0 + hdy02tx)/dy02, tym = y<y1?ty0 + (dty01*yy0 + hdy01ty)/dy01:ty1 + (dty12*yy1 + hdy12ty)/dy12, tyM = ty0 + (dty02*yy0 + hdy02ty)/dy02; if (xm>xM) cimg::swap(xm,xM,txm,txM,tym,tyM); if (xM>=0 || xm<=w1) { const int cxm = cimg::cut(xm,0,w1), cxM = cimg::cut(xM,0,w1); T *ptrd = data(cxm,y); const int dxmM = std::max(1,xM - xm), hdxmM = dxmM/2, dtxmM = txM - txm, dtymM = tyM - tym; for (int x = cxm; x<=cxM; ++x) { const int xxm = x - xm, tx = (txm*dxmM + dtxmM*xxm + hdxmM)/dxmM, ty = (tym*dxmM + dtymM*xxm + hdxmM)/dxmM; const tc *const color = &texture._atXY(tx,ty); cimg_forC(*this,c) { const Tfloat val = cbs<=1?color[c*twhd]*cbs:(2 - cbs)*color[c*twhd] + (cbs - 1)*_sc_maxval; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } ++ptrd; } } } return *this; } //! Draw a 2D textured triangle, with perspective correction. template<typename tc> CImg<T>& draw_triangle(int x0, int y0, const float z0, int x1, int y1, const float z1, int x2, int y2, const float z2, const CImg<tc>& texture, int tx0, int ty0, int tx1, int ty1, int tx2, int ty2, const float opacity=1, const float brightness=1) { if (is_empty() || z0<=0 || z1<=0 || z2<=0) return *this; if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_overlapped(texture)) return draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,+texture,tx0,ty0,tx1,ty1,tx2,ty2,opacity,brightness); float iz0 = 1/z0, iz1 = 1/z1, iz2 = 1/z2; if (y0>y1) cimg::swap(x0,x1,y0,y1,iz0,iz1,tx0,tx1,ty0,ty1); if (y0>y2) cimg::swap(x0,x2,y0,y2,iz0,iz2,tx0,tx2,ty0,ty2); if (y1>y2) cimg::swap(x1,x2,y1,y2,iz1,iz2,tx1,tx2,ty1,ty2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2; const float diz01 = iz1 - iz0, diz02 = iz2 - iz0, diz12 = iz2 - iz1, txz0 = tx0*iz0, txz1 = tx1*iz1, txz2 = tx2*iz2, tyz0 = ty0*iz0, tyz1 = ty1*iz1, tyz2 = ty2*iz2, dtxz01 = txz1 - txz0, dtxz02 = txz2 - txz0, dtxz12 = txz2 - txz1, dtyz01 = tyz1 - tyz0, dtyz02 = tyz2 - tyz0, dtyz12 = tyz2 - tyz1; const ulongT twhd = (ulongT)texture._width*texture._height*texture._depth; const float cbs = cimg::cut(brightness,0,2); cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02; float izm = y<y1?(iz0 + diz01*yy0/dy01):(iz1 + diz12*yy1/dy12), izM = iz0 + diz02*yy0/dy02, txzm = y<y1?(txz0 + dtxz01*yy0/dy01):(txz1 + dtxz12*yy1/dy12), txzM = txz0 + dtxz02*yy0/dy02, tyzm = y<y1?(tyz0 + dtyz01*yy0/dy01):(tyz1 + dtyz12*yy1/dy12), tyzM = tyz0 + dtyz02*yy0/dy02; if (xm>xM) cimg::swap(xm,xM,txzm,txzM,tyzm,tyzM,izm,izM); if (xM>=0 || xm<=w1) { const int cxm = cimg::cut(xm,0,w1), cxM = cimg::cut(xM,0,w1); T *ptrd = data(cxm,y); const int dxmM = std::max(1,xM - xm); const float dizmM = izM - izm, dtxzmM = txzM - txzm, dtyzmM = tyzM - tyzm; for (int x = cxm; x<cxM; ++x) { const int xxm = x - xm; const float iz = izm + dizmM*xxm/dxmM, txz = txzm + dtxzmM*xxm/dxmM, tyz = tyzm + dtyzmM*xxm/dxmM; const int tx = (int)cimg::round(txz/iz), ty = (int)cimg::round(tyz/iz); const tc *const color = &texture._atXY(tx,ty); cimg_forC(*this,c) { const Tfloat val = cbs<=1?color[c*twhd]*cbs:(2 - cbs)*color[c*twhd] + (cbs - 1)*_sc_maxval; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } ++ptrd; } } } return *this; } //! Draw a textured 2D triangle, with perspective correction and z-buffering. template<typename tz, typename tc> CImg<T>& draw_triangle(CImg<tz>& zbuffer, int x0, int y0, const float z0, int x1, int y1, const float z1, int x2, int y2, const float z2, const CImg<tc>& texture, int tx0, int ty0, int tx1, int ty1, int tx2, int ty2, const float opacity=1, const float brightness=1) { if (is_empty() || z0<=0 || z1<=0 || z2<=0) return *this; if (!is_sameXY(zbuffer)) throw CImgArgumentException(_cimg_instance "draw_triangle(): Instance and specified Z-buffer (%u,%u,%u,%u,%p) have " "different dimensions.", cimg_instance, zbuffer._width,zbuffer._height,zbuffer._depth,zbuffer._spectrum,zbuffer._data); if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_overlapped(texture)) return draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,+texture,tx0,ty0,tx1,ty1,tx2,ty2,opacity,brightness); float iz0 = 1/z0, iz1 = 1/z1, iz2 = 1/z2; if (y0>y1) cimg::swap(x0,x1,y0,y1,iz0,iz1,tx0,tx1,ty0,ty1); if (y0>y2) cimg::swap(x0,x2,y0,y2,iz0,iz2,tx0,tx2,ty0,ty2); if (y1>y2) cimg::swap(x1,x2,y1,y2,iz1,iz2,tx1,tx2,ty1,ty2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2; const float diz01 = iz1 - iz0, diz02 = iz2 - iz0, diz12 = iz2 - iz1, txz0 = tx0*iz0, txz1 = tx1*iz1, txz2 = tx2*iz2, tyz0 = ty0*iz0, tyz1 = ty1*iz1, tyz2 = ty2*iz2, dtxz01 = txz1 - txz0, dtxz02 = txz2 - txz0, dtxz12 = txz2 - txz1, dtyz01 = tyz1 - tyz0, dtyz02 = tyz2 - tyz0, dtyz12 = tyz2 - tyz1; const ulongT twhd = (ulongT)texture._width*texture._height*texture._depth; const float cbs = cimg::cut(brightness,0,2); cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02; float izm = y<y1?(iz0 + diz01*yy0/dy01):(iz1 + diz12*yy1/dy12), izM = iz0 + diz02*yy0/dy02, txzm = y<y1?(txz0 + dtxz01*yy0/dy01):(txz1 + dtxz12*yy1/dy12), txzM = txz0 + dtxz02*yy0/dy02, tyzm = y<y1?(tyz0 + dtyz01*yy0/dy01):(tyz1 + dtyz12*yy1/dy12), tyzM = tyz0 + dtyz02*yy0/dy02; if (xm>xM) cimg::swap(xm,xM,txzm,txzM,tyzm,tyzM,izm,izM); if (xM>=0 || xm<=w1) { const int cxm = cimg::cut(xm,0,w1), cxM = cimg::cut(xM,0,w1); T *ptrd = data(cxm,y); tz *ptrz = zbuffer.data(cxm,y); const int dxmM = std::max(1,xM - xm); const float dizmM = izM - izm, dtxzmM = txzM - txzm, dtyzmM = tyzM - tyzm; for (int x = cxm; x<cxM; ++x) { const int xxm = x - xm; const float iz = izm + dizmM*xxm/dxmM; if (iz>=*ptrz) { *ptrz = (tz)iz; const float txz = txzm + dtxzmM*xxm/dxmM, tyz = tyzm + dtyzmM*xxm/dxmM; const int tx = (int)cimg::round(txz/iz), ty = (int)cimg::round(tyz/iz); const tc *const color = &texture._atXY(tx,ty); cimg_forC(*this,c) { const Tfloat val = cbs<=1?color[c*twhd]*cbs:(2 - cbs)*color[c*twhd] + (cbs - 1)*_sc_maxval; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } } ++ptrd; ++ptrz; } } } return *this; } //! Draw a Phong-shaded 2D triangle. /** \param x0 X-coordinate of the first vertex in the image instance. \param y0 Y-coordinate of the first vertex in the image instance. \param x1 X-coordinate of the second vertex in the image instance. \param y1 Y-coordinate of the second vertex in the image instance. \param x2 X-coordinate of the third vertex in the image instance. \param y2 Y-coordinate of the third vertex in the image instance. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param light Light image. \param lx0 X-coordinate of the first vertex in the light image. \param ly0 Y-coordinate of the first vertex in the light image. \param lx1 X-coordinate of the second vertex in the light image. \param ly1 Y-coordinate of the second vertex in the light image. \param lx2 X-coordinate of the third vertex in the light image. \param ly2 Y-coordinate of the third vertex in the light image. \param opacity Drawing opacity. **/ template<typename tc, typename tl> CImg<T>& draw_triangle(int x0, int y0, int x1, int y1, int x2, int y2, const tc *const color, const CImg<tl>& light, int lx0, int ly0, int lx1, int ly1, int lx2, int ly2, const float opacity=1) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_triangle(): Specified color is (null).", cimg_instance); if (light._depth>1 || light._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified light texture (%u,%u,%u,%u,%p).", cimg_instance,light._width,light._height,light._depth,light._spectrum,light._data); if (y0>y1) cimg::swap(x0,x1,y0,y1,lx0,lx1,ly0,ly1); if (y0>y2) cimg::swap(x0,x2,y0,y2,lx0,lx2,ly0,ly2); if (y1>y2) cimg::swap(x1,x2,y1,y2,lx1,lx2,ly1,ly2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2, dlx01 = lx1 - lx0, dlx02 = lx2 - lx0, dlx12 = lx2 - lx1, dly01 = ly1 - ly0, dly02 = ly2 - ly0, dly12 = ly2 - ly1, hdy01lx = dy01*cimg::sign(dlx01)/2, hdy02lx = dy02*cimg::sign(dlx02)/2, hdy12lx = dy12*cimg::sign(dlx12)/2, hdy01ly = dy01*cimg::sign(dly01)/2, hdy02ly = dy02*cimg::sign(dly02)/2, hdy12ly = dy12*cimg::sign(dly12)/2; const ulongT lwhd = (ulongT)light._width*light._height*light._depth; cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02, lxm = y<y1?lx0 + (dlx01*yy0 + hdy01lx)/dy01:lx1 + (dlx12*yy1 + hdy12lx)/dy12, lxM = lx0 + (dlx02*yy0 + hdy02lx)/dy02, lym = y<y1?ly0 + (dly01*yy0 + hdy01ly)/dy01:ly1 + (dly12*yy1 + hdy12ly)/dy12, lyM = ly0 + (dly02*yy0 + hdy02ly)/dy02; if (xm>xM) cimg::swap(xm,xM,lxm,lxM,lym,lyM); if (xM>=0 || xm<=w1) { const int cxm = cimg::cut(xm,0,w1), cxM = cimg::cut(xM,0,w1); T *ptrd = data(cxm,y); const int dxmM = std::max(1,xM - xm), hdxmM = dxmM/2, dlxmM = lxM - lxm, dlymM = lyM - lym; for (int x = cxm; x<cxM; ++x) { const int xxm = x - xm, lx = (lxm*dxmM + dlxmM*xxm + hdxmM)/dxmM, ly = (lym*dxmM + dlymM*xxm + hdxmM)/dxmM; const tl *const lig = &light._atXY(lx,ly); cimg_forC(*this,c) { const tc col = color[c]; const float cbs = cimg::cut((float)lig[c*lwhd],0,2); const Tfloat val = cbs<=1?cbs*col:(2 - cbs)*col + (cbs - 1)*_sc_maxval; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } ++ptrd; } } } return *this; } //! Draw a Phong-shaded 2D triangle, with z-buffering. template<typename tz, typename tc, typename tl> CImg<T>& draw_triangle(CImg<tz>& zbuffer, int x0, int y0, const float z0, int x1, int y1, const float z1, int x2, int y2, const float z2, const tc *const color, const CImg<tl>& light, int lx0, int ly0, int lx1, int ly1, int lx2, int ly2, const float opacity=1) { if (is_empty() || z0<=0 || z1<=0 || z2<=0) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_triangle(): Specified color is (null).", cimg_instance); if (light._depth>1 || light._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified light texture (%u,%u,%u,%u,%p).", cimg_instance,light._width,light._height,light._depth,light._spectrum,light._data); if (!is_sameXY(zbuffer)) throw CImgArgumentException(_cimg_instance "draw_triangle(): Instance and specified Z-buffer (%u,%u,%u,%u,%p) have " "different dimensions.", cimg_instance, zbuffer._width,zbuffer._height,zbuffer._depth,zbuffer._spectrum,zbuffer._data); if (is_overlapped(light)) return draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color, +light,lx0,ly0,lx1,ly1,lx2,ly2,opacity); float iz0 = 1/z0, iz1 = 1/z1, iz2 = 1/z2; if (y0>y1) cimg::swap(x0,x1,y0,y1,iz0,iz1,lx0,lx1,ly0,ly1); if (y0>y2) cimg::swap(x0,x2,y0,y2,iz0,iz2,lx0,lx2,ly0,ly2); if (y1>y2) cimg::swap(x1,x2,y1,y2,iz1,iz2,lx1,lx2,ly1,ly2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2, dlx01 = lx1 - lx0, dlx02 = lx2 - lx0, dlx12 = lx2 - lx1, dly01 = ly1 - ly0, dly02 = ly2 - ly0, dly12 = ly2 - ly1, hdy01lx = dy01*cimg::sign(dlx01)/2, hdy02lx = dy02*cimg::sign(dlx02)/2, hdy12lx = dy12*cimg::sign(dlx12)/2, hdy01ly = dy01*cimg::sign(dly01)/2, hdy02ly = dy02*cimg::sign(dly02)/2, hdy12ly = dy12*cimg::sign(dly12)/2; const float diz01 = iz1 - iz0, diz02 = iz2 - iz0, diz12 = iz2 - iz1; const ulongT lwhd = (ulongT)light._width*light._height*light._depth; cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02, lxm = y<y1?lx0 + (dlx01*yy0 + hdy01lx)/dy01:lx1 + (dlx12*yy1 + hdy12lx)/dy12, lxM = lx0 + (dlx02*yy0 + hdy02lx)/dy02, lym = y<y1?ly0 + (dly01*yy0 + hdy01ly)/dy01:ly1 + (dly12*yy1 + hdy12ly)/dy12, lyM = ly0 + (dly02*yy0 + hdy02ly)/dy02; float izm = y<y1?(iz0 + diz01*yy0/dy01):(iz1 + diz12*yy1/dy12), izM = iz0 + diz02*yy0/dy02; if (xm>xM) cimg::swap(xm,xM,lxm,lxM,lym,lyM,izm,izM); if (xM>=0 || xm<=w1) { const int cxm = cimg::cut(xm,0,w1), cxM = cimg::cut(xM,0,w1); T *ptrd = data(cxm,y); tz *ptrz = zbuffer.data(cxm,y); const int dxmM = std::max(1,xM - xm), hdxmM = dxmM/2, dlxmM = lxM - lxm, dlymM = lyM - lym; const float dizmM = izM - izm; for (int x = cxm; x<cxM; ++x) { const int xxm = x - xm; const float iz = izm + dizmM*xxm/dxmM; if (iz>=*ptrz) { *ptrz = (tz)iz; const int lx = (lxm*dxmM + dlxmM*xxm + hdxmM)/dxmM, ly = (lym*dxmM + dlymM*xxm + hdxmM)/dxmM; const tl *const lig = &light._atXY(lx,ly); cimg_forC(*this,c) { const float cbs = cimg::cut((float)lig[c*lwhd],0,2); const tc col = color[c]; const Tfloat val = cbs<=1?cbs*col:(2 - cbs)*col + (cbs - 1)*_sc_maxval; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } } ++ptrd; ++ptrz; } } } return *this; } //! Draw a textured Gouraud-shaded 2D triangle. /** \param x0 X-coordinate of the first vertex in the image instance. \param y0 Y-coordinate of the first vertex in the image instance. \param x1 X-coordinate of the second vertex in the image instance. \param y1 Y-coordinate of the second vertex in the image instance. \param x2 X-coordinate of the third vertex in the image instance. \param y2 Y-coordinate of the third vertex in the image instance. \param texture Texture image used to fill the triangle. \param tx0 X-coordinate of the first vertex in the texture image. \param ty0 Y-coordinate of the first vertex in the texture image. \param tx1 X-coordinate of the second vertex in the texture image. \param ty1 Y-coordinate of the second vertex in the texture image. \param tx2 X-coordinate of the third vertex in the texture image. \param ty2 Y-coordinate of the third vertex in the texture image. \param bs0 Brightness factor of the first vertex. \param bs1 Brightness factor of the second vertex. \param bs2 Brightness factor of the third vertex. \param opacity Drawing opacity. **/ template<typename tc> CImg<T>& draw_triangle(int x0, int y0, int x1, int y1, int x2, int y2, const CImg<tc>& texture, int tx0, int ty0, int tx1, int ty1, int tx2, int ty2, float bs0, float bs1, float bs2, const float opacity=1) { if (is_empty()) return *this; if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_overlapped(texture)) return draw_triangle(x0,y0,x1,y1,x2,y2,+texture,tx0,ty0,tx1,ty1,tx2,ty2, bs0,bs1,bs2,opacity); if (y0>y1) cimg::swap(x0,x1,y0,y1,tx0,tx1,ty0,ty1,bs0,bs1); if (y0>y2) cimg::swap(x0,x2,y0,y2,tx0,tx2,ty0,ty2,bs0,bs2); if (y1>y2) cimg::swap(x1,x2,y1,y2,tx1,tx2,ty1,ty2,bs1,bs2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2, dtx01 = tx1 - tx0, dtx02 = tx2 - tx0, dtx12 = tx2 - tx1, dty01 = ty1 - ty0, dty02 = ty2 - ty0, dty12 = ty2 - ty1, hdy01tx = dy01*cimg::sign(dtx01)/2, hdy02tx = dy02*cimg::sign(dtx02)/2, hdy12tx = dy12*cimg::sign(dtx12)/2, hdy01ty = dy01*cimg::sign(dty01)/2, hdy02ty = dy02*cimg::sign(dty02)/2, hdy12ty = dy12*cimg::sign(dty12)/2; const float dbs01 = bs1 - bs0, dbs02 = bs2 - bs0, dbs12 = bs2 - bs1; const ulongT twhd = (ulongT)texture._width*texture._height*texture._depth; cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02, txm = y<y1?tx0 + (dtx01*yy0 + hdy01tx)/dy01:tx1 + (dtx12*yy1 + hdy12tx)/dy12, txM = tx0 + (dtx02*yy0 + hdy02tx)/dy02, tym = y<y1?ty0 + (dty01*yy0 + hdy01ty)/dy01:ty1 + (dty12*yy1 + hdy12ty)/dy12, tyM = ty0 + (dty02*yy0 + hdy02ty)/dy02; float bsm = y<y1?(bs0 + dbs01*yy0/dy01):(bs1 + dbs12*yy1/dy12), bsM = bs0 + dbs02*yy0/dy02; if (xm>xM) cimg::swap(xm,xM,txm,txM,tym,tyM,bsm,bsM); if (xM>=0 || xm<=w1) { const int cxm = cimg::cut(xm,0,w1), cxM = cimg::cut(xM,0,w1); T *ptrd = data(cxm,y); const int dxmM = std::max(1,xM - xm), hdxmM = dxmM/2, dtxmM = txM - txm, dtymM = tyM - tym; const float dbsmM = bsM - bsm; for (int x = cxm; x<cxM; ++x) { const int xxm = x - xm, tx = (txm*dxmM + dtxmM*xxm + hdxmM)/dxmM, ty = (tym*dxmM + dtymM*xxm + hdxmM)/dxmM; const float cbs = cimg::cut(bsm + dbsmM*xxm/dxmM,0,2); const tc *const color = &texture._atXY(tx,ty); cimg_forC(*this,c) { const tc col = color[c*twhd]; const Tfloat val = cbs<=1?cbs*col:(2 - cbs)*col + (cbs - 1)*_sc_maxval; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } ++ptrd; } } } return *this; } //! Draw a textured Gouraud-shaded 2D triangle, with perspective correction \overloading. template<typename tc> CImg<T>& draw_triangle(int x0, int y0, const float z0, int x1, int y1, const float z1, int x2, int y2, const float z2, const CImg<tc>& texture, int tx0, int ty0, int tx1, int ty1, int tx2, int ty2, float bs0, float bs1, float bs2, const float opacity=1) { if (is_empty() || z0<=0 || z1<=0 || z2<=0) return *this; if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_overlapped(texture)) return draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,+texture,tx0,ty0,tx1,ty1,tx2,ty2, bs0,bs1,bs2,opacity); float iz0 = 1/z0, iz1 = 1/z1, iz2 = 1/z2; if (y0>y1) cimg::swap(x0,x1,y0,y1,iz0,iz1,tx0,tx1,ty0,ty1,bs0,bs1); if (y0>y2) cimg::swap(x0,x2,y0,y2,iz0,iz2,tx0,tx2,ty0,ty2,bs0,bs2); if (y1>y2) cimg::swap(x1,x2,y1,y2,iz1,iz2,tx1,tx2,ty1,ty2,bs1,bs2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2; const float diz01 = iz1 - iz0, diz02 = iz2 - iz0, diz12 = iz2 - iz1, txz0 = tx0*iz0, txz1 = tx1*iz1, txz2 = tx2*iz2, tyz0 = ty0*iz0, tyz1 = ty1*iz1, tyz2 = ty2*iz2, dtxz01 = txz1 - txz0, dtxz02 = txz2 - txz0, dtxz12 = txz2 - txz1, dtyz01 = tyz1 - tyz0, dtyz02 = tyz2 - tyz0, dtyz12 = tyz2 - tyz1, dbs01 = bs1 - bs0, dbs02 = bs2 - bs0, dbs12 = bs2 - bs1; const ulongT twhd = (ulongT)texture._width*texture._height*texture._depth; cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02; float izm = y<y1?(iz0 + diz01*yy0/dy01):(iz1 + diz12*yy1/dy12), izM = iz0 + diz02*yy0/dy02, txzm = y<y1?(txz0 + dtxz01*yy0/dy01):(txz1 + dtxz12*yy1/dy12), txzM = txz0 + dtxz02*yy0/dy02, tyzm = y<y1?(tyz0 + dtyz01*yy0/dy01):(tyz1 + dtyz12*yy1/dy12), tyzM = tyz0 + dtyz02*yy0/dy02, bsm = y<y1?(bs0 + dbs01*yy0/dy01):(bs1 + dbs12*yy1/dy12), bsM = bs0 + dbs02*yy0/dy02; if (xm>xM) cimg::swap(xm,xM,txzm,txzM,tyzm,tyzM,izm,izM,bsm,bsM); if (xM>=0 || xm<=w1) { const int cxm = cimg::cut(xm,0,w1), cxM = cimg::cut(xM,0,w1); T *ptrd = data(cxm,y); const int dxmM = std::max(1,xM - xm); const float dizmM = izM - izm, dtxzmM = txzM - txzm, dtyzmM = tyzM - tyzm, dbsmM = bsM - bsm; for (int x = cxm; x<cxM; ++x) { const int xxm = x - xm; const float iz = izm + dizmM*xxm/dxmM, txz = txzm + dtxzmM*xxm/dxmM, tyz = tyzm + dtyzmM*xxm/dxmM, cbs = cimg::cut(bsm + dbsmM*xxm/dxmM,0,2); const int tx = (int)cimg::round(txz/iz), ty = (int)cimg::round(tyz/iz); const tc *const color = &texture._atXY(tx,ty); cimg_forC(*this,c) { const tc col = color[c*twhd]; const Tfloat val = cbs<=1?cbs*col:(2 - cbs)*col + (cbs - 1)*_sc_maxval; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } ++ptrd; } } } return *this; } //! Draw a textured Gouraud-shaded 2D triangle, with perspective correction and z-buffering \overloading. template<typename tz, typename tc> CImg<T>& draw_triangle(CImg<tz>& zbuffer, int x0, int y0, const float z0, int x1, int y1, const float z1, int x2, int y2, const float z2, const CImg<tc>& texture, int tx0, int ty0, int tx1, int ty1, int tx2, int ty2, float bs0, float bs1, float bs2, const float opacity=1) { if (is_empty() || z0<=0 || z1<=0 || z2<=0) return *this; if (!is_sameXY(zbuffer)) throw CImgArgumentException(_cimg_instance "draw_triangle(): Instance and specified Z-buffer (%u,%u,%u,%u,%p) have " "different dimensions.", cimg_instance, zbuffer._width,zbuffer._height,zbuffer._depth,zbuffer._spectrum,zbuffer._data); if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_overlapped(texture)) return draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,+texture,tx0,ty0,tx1,ty1,tx2,ty2,bs0,bs1,bs2,opacity); float iz0 = 1/z0, iz1 = 1/z1, iz2 = 1/z2; if (y0>y1) cimg::swap(x0,x1,y0,y1,iz0,iz1,tx0,tx1,ty0,ty1,bs0,bs1); if (y0>y2) cimg::swap(x0,x2,y0,y2,iz0,iz2,tx0,tx2,ty0,ty2,bs0,bs2); if (y1>y2) cimg::swap(x1,x2,y1,y2,iz1,iz2,tx1,tx2,ty1,ty2,bs1,bs2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2; const float diz01 = iz1 - iz0, diz02 = iz2 - iz0, diz12 = iz2 - iz1, txz0 = tx0*iz0, txz1 = tx1*iz1, txz2 = tx2*iz2, tyz0 = ty0*iz0, tyz1 = ty1*iz1, tyz2 = ty2*iz2, dtxz01 = txz1 - txz0, dtxz02 = txz2 - txz0, dtxz12 = txz2 - txz1, dtyz01 = tyz1 - tyz0, dtyz02 = tyz2 - tyz0, dtyz12 = tyz2 - tyz1, dbs01 = bs1 - bs0, dbs02 = bs2 - bs0, dbs12 = bs2 - bs1; const ulongT twhd = (ulongT)texture._width*texture._height*texture._depth; cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02; float izm = y<y1?(iz0 + diz01*yy0/dy01):(iz1 + diz12*yy1/dy12), izM = iz0 + diz02*yy0/dy02, txzm = y<y1?(txz0 + dtxz01*yy0/dy01):(txz1 + dtxz12*yy1/dy12), txzM = txz0 + dtxz02*yy0/dy02, tyzm = y<y1?(tyz0 + dtyz01*yy0/dy01):(tyz1 + dtyz12*yy1/dy12), tyzM = tyz0 + dtyz02*yy0/dy02, bsm = y<y1?(bs0 + dbs01*yy0/dy01):(bs1 + dbs12*yy1/dy12), bsM = bs0 + dbs02*yy0/dy02; if (xm>xM) cimg::swap(xm,xM,txzm,txzM,tyzm,tyzM,izm,izM,bsm,bsM); if (xM>=0 || xm<=w1) { const int cxm = cimg::cut(xm,0,w1), cxM = cimg::cut(xM,0,w1); T *ptrd = data(cxm,y); tz *ptrz = zbuffer.data(cxm,y); const int dxmM = std::max(1,xM - xm); const float dizmM = izM - izm, dtxzmM = txzM - txzm, dtyzmM = tyzM - tyzm, dbsmM = bsM - bsm; for (int x = cxm; x<cxM; ++x) { const int xxm = x - xm; const float iz = izm + dizmM*xxm/dxmM; if (iz>=*ptrz) { *ptrz = (tz)iz; const float txz = txzm + dtxzmM*xxm/dxmM, tyz = tyzm + dtyzmM*xxm/dxmM, cbs = cimg::cut(bsm + dbsmM*xxm/dxmM,0,2); const int tx = (int)cimg::round(txz/iz), ty = (int)cimg::round(tyz/iz); const tc *const color = &texture._atXY(tx,ty); cimg_forC(*this,c) { const tc col = color[c*twhd]; const Tfloat val = cbs<=1?cbs*col:(2 - cbs)*col + (cbs - 1)*_sc_maxval; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } } ++ptrd; ++ptrz; } } } return *this; } //! Draw a textured Phong-shaded 2D triangle. /** \param x0 X-coordinate of the first vertex in the image instance. \param y0 Y-coordinate of the first vertex in the image instance. \param x1 X-coordinate of the second vertex in the image instance. \param y1 Y-coordinate of the second vertex in the image instance. \param x2 X-coordinate of the third vertex in the image instance. \param y2 Y-coordinate of the third vertex in the image instance. \param texture Texture image used to fill the triangle. \param tx0 X-coordinate of the first vertex in the texture image. \param ty0 Y-coordinate of the first vertex in the texture image. \param tx1 X-coordinate of the second vertex in the texture image. \param ty1 Y-coordinate of the second vertex in the texture image. \param tx2 X-coordinate of the third vertex in the texture image. \param ty2 Y-coordinate of the third vertex in the texture image. \param light Light image. \param lx0 X-coordinate of the first vertex in the light image. \param ly0 Y-coordinate of the first vertex in the light image. \param lx1 X-coordinate of the second vertex in the light image. \param ly1 Y-coordinate of the second vertex in the light image. \param lx2 X-coordinate of the third vertex in the light image. \param ly2 Y-coordinate of the third vertex in the light image. \param opacity Drawing opacity. **/ template<typename tc, typename tl> CImg<T>& draw_triangle(int x0, int y0, int x1, int y1, int x2, int y2, const CImg<tc>& texture, int tx0, int ty0, int tx1, int ty1, int tx2, int ty2, const CImg<tl>& light, int lx0, int ly0, int lx1, int ly1, int lx2, int ly2, const float opacity=1) { if (is_empty()) return *this; if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (light._depth>1 || light._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified light texture (%u,%u,%u,%u,%p).", cimg_instance,light._width,light._height,light._depth,light._spectrum,light._data); if (is_overlapped(texture)) return draw_triangle(x0,y0,x1,y1,x2,y2,+texture,tx0,ty0,tx1,ty1,tx2,ty2,light,lx0,ly0,lx1,ly1,lx2,ly2,opacity); if (is_overlapped(light)) return draw_triangle(x0,y0,x1,y1,x2,y2,texture,tx0,ty0,tx1,ty1,tx2,ty2,+light,lx0,ly0,lx1,ly1,lx2,ly2,opacity); if (y0>y1) cimg::swap(x0,x1,y0,y1,tx0,tx1,ty0,ty1,lx0,lx1,ly0,ly1); if (y0>y2) cimg::swap(x0,x2,y0,y2,tx0,tx2,ty0,ty2,lx0,lx2,ly0,ly2); if (y1>y2) cimg::swap(x1,x2,y1,y2,tx1,tx2,ty1,ty2,lx1,lx2,ly1,ly2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2, dtx01 = tx1 - tx0, dtx02 = tx2 - tx0, dtx12 = tx2 - tx1, dty01 = ty1 - ty0, dty02 = ty2 - ty0, dty12 = ty2 - ty1, hdy01tx = dy01*cimg::sign(dtx01)/2, hdy02tx = dy02*cimg::sign(dtx02)/2, hdy12tx = dy12*cimg::sign(dtx12)/2, hdy01ty = dy01*cimg::sign(dty01)/2, hdy02ty = dy02*cimg::sign(dty02)/2, hdy12ty = dy12*cimg::sign(dty12)/2, dlx01 = lx1 - lx0, dlx02 = lx2 - lx0, dlx12 = lx2 - lx1, dly01 = ly1 - ly0, dly02 = ly2 - ly0, dly12 = ly2 - ly1, hdy01lx = dy01*cimg::sign(dlx01)/2, hdy02lx = dy02*cimg::sign(dlx02)/2, hdy12lx = dy12*cimg::sign(dlx12)/2, hdy01ly = dy01*cimg::sign(dly01)/2, hdy02ly = dy02*cimg::sign(dly02)/2, hdy12ly = dy12*cimg::sign(dly12)/2; const ulongT twhd = (ulongT)texture._width*texture._height*texture._depth, lwhd = (ulongT)light._width*light._height*light._depth; cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02, txm = y<y1?tx0 + (dtx01*yy0 + hdy01tx)/dy01:tx1 + (dtx12*yy1 + hdy12tx)/dy12, txM = tx0 + (dtx02*yy0 + hdy02tx)/dy02, tym = y<y1?ty0 + (dty01*yy0 + hdy01ty)/dy01:ty1 + (dty12*yy1 + hdy12ty)/dy12, tyM = ty0 + (dty02*yy0 + hdy02ty)/dy02, lxm = y<y1?lx0 + (dlx01*yy0 + hdy01lx)/dy01:lx1 + (dlx12*yy1 + hdy12lx)/dy12, lxM = lx0 + (dlx02*yy0 + hdy02lx)/dy02, lym = y<y1?ly0 + (dly01*yy0 + hdy01ly)/dy01:ly1 + (dly12*yy1 + hdy12ly)/dy12, lyM = ly0 + (dly02*yy0 + hdy02ly)/dy02; if (xm>xM) cimg::swap(xm,xM,txm,txM,tym,tyM,lxm,lxM,lym,lyM); if (xM>=0 || xm<=w1) { const int cxm = cimg::cut(xm,0,w1), cxM = cimg::cut(xM,0,w1); T *ptrd = data(cxm,y); const int dxmM = std::max(1,xM - xm), hdxmM = dxmM/2, dtxmM = txM - txm, dtymM = tyM - tym, dlxmM = lxM - lxm, dlymM = lyM - lym; for (int x = cxm; x<cxM; ++x) { const int xxm = x - xm, tx = (txm*dxmM + dtxmM*xxm + hdxmM)/dxmM, ty = (tym*dxmM + dtymM*xxm + hdxmM)/dxmM, lx = (lxm*dxmM + dlxmM*xxm + hdxmM)/dxmM, ly = (lym*dxmM + dlymM*xxm + hdxmM)/dxmM; const tc *const color = &texture._atXY(tx,ty); const tl *const lig = &light._atXY(lx,ly); cimg_forC(*this,c) { const tc col = color[c*twhd]; const float cbs = cimg::cut((float)lig[c*lwhd],0,2); const Tfloat val = cbs<=1?cbs*col:(2 - cbs)*col + (cbs - 1)*_sc_maxval; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } ++ptrd; } } } return *this; } //! Draw a textured Phong-shaded 2D triangle, with perspective correction. template<typename tc, typename tl> CImg<T>& draw_triangle(int x0, int y0, const float z0, int x1, int y1, const float z1, int x2, int y2, const float z2, const CImg<tc>& texture, int tx0, int ty0, int tx1, int ty1, int tx2, int ty2, const CImg<tl>& light, int lx0, int ly0, int lx1, int ly1, int lx2, int ly2, const float opacity=1) { if (is_empty() || z0<=0 || z1<=0 || z2<=0) return *this; if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (light._depth>1 || light._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified light texture (%u,%u,%u,%u,%p).", cimg_instance,light._width,light._height,light._depth,light._spectrum,light._data); if (is_overlapped(texture)) return draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,+texture,tx0,ty0,tx1,ty1,tx2,ty2, light,lx0,ly0,lx1,ly1,lx2,ly2,opacity); if (is_overlapped(light)) return draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,texture,tx0,ty0,tx1,ty1,tx2,ty2, +light,lx0,ly0,lx1,ly1,lx2,ly2,opacity); float iz0 = 1/z0, iz1 = 1/z1, iz2 = 1/z2; if (y0>y1) cimg::swap(x0,x1,y0,y1,iz0,iz1,tx0,tx1,ty0,ty1,lx0,lx1,ly0,ly1); if (y0>y2) cimg::swap(x0,x2,y0,y2,iz0,iz2,tx0,tx2,ty0,ty2,lx0,lx2,ly0,ly2); if (y1>y2) cimg::swap(x1,x2,y1,y2,iz1,iz2,tx1,tx2,ty1,ty2,lx1,lx2,ly1,ly2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2; const float diz01 = iz1 - iz0, diz02 = iz2 - iz0, diz12 = iz2 - iz1, txz0 = tx0*iz0, txz1 = tx1*iz1, txz2 = tx2*iz2, tyz0 = ty0*iz0, tyz1 = ty1*iz1, tyz2 = ty2*iz2, dtxz01 = txz1 - txz0, dtxz02 = txz2 - txz0, dtxz12 = txz2 - txz1, dtyz01 = tyz1 - tyz0, dtyz02 = tyz2 - tyz0, dtyz12 = tyz2 - tyz1, lxz0 = lx0*iz0, lxz1 = lx1*iz1, lxz2 = lx2*iz2, lyz0 = ly0*iz0, lyz1 = ly1*iz1, lyz2 = ly2*iz2, dlxz01 = lxz1 - lxz0, dlxz02 = lxz2 - lxz0, dlxz12 = lxz2 - lxz1, dlyz01 = lyz1 - lyz0, dlyz02 = lyz2 - lyz0, dlyz12 = lyz2 - lyz1; const ulongT twhd = (ulongT)texture._width*texture._height*texture._depth, lwhd = (ulongT)light._width*light._height*light._depth; cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02; float izm = y<y1?(iz0 + diz01*yy0/dy01):(iz1 + diz12*yy1/dy12), izM = iz0 + diz02*yy0/dy02, txzm = y<y1?(txz0 + dtxz01*yy0/dy01):(txz1 + dtxz12*yy1/dy12), txzM = txz0 + dtxz02*yy0/dy02, tyzm = y<y1?(tyz0 + dtyz01*yy0/dy01):(tyz1 + dtyz12*yy1/dy12), tyzM = tyz0 + dtyz02*yy0/dy02, lxzm = y<y1?(lxz0 + dlxz01*yy0/dy01):(lxz1 + dlxz12*yy1/dy12), lxzM = lxz0 + dlxz02*yy0/dy02, lyzm = y<y1?(lyz0 + dlyz01*yy0/dy01):(lyz1 + dlyz12*yy1/dy12), lyzM = lyz0 + dlyz02*yy0/dy02; if (xm>xM) cimg::swap(xm,xM,izm,izM,txzm,txzM,tyzm,tyzM,lxzm,lxzM,lyzm,lyzM); if (xM>=0 || xm<=w1) { const int cxm = cimg::cut(xm,0,w1), cxM = cimg::cut(xM,0,w1); T *ptrd = data(cxm,y); const int dxmM = std::max(1,xM - xm); const float dizmM = izM - izm, dtxzmM = txzM - txzm, dtyzmM = tyzM - tyzm, dlxzmM = lxzM - lxzm, dlyzmM = lyzM - lyzm; for (int x = cxm; x<cxM; ++x) { const int xxm = x - xm; const float iz = izm + dizmM*xxm/dxmM, txz = txzm + dtxzmM*xxm/dxmM, tyz = tyzm + dtyzmM*xxm/dxmM, lxz = lxzm + dlxzmM*xxm/dxmM, lyz = lyzm + dlyzmM*xxm/dxmM; const int tx = (int)cimg::round(txz/iz), ty = (int)cimg::round(tyz/iz), lx = (int)cimg::round(lxz/iz), ly = (int)cimg::round(lyz/iz); const tc *const color = &texture._atXY(tx,ty); const tl *const lig = &light._atXY(lx,ly); cimg_forC(*this,c) { const tc col = color[c*twhd]; const float cbs = cimg::cut((float)lig[c*lwhd],0,2); const Tfloat val = cbs<=1?cbs*col:(2 - cbs)*col + (cbs - 1)*_sc_maxval; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } ++ptrd; } } } return *this; } //! Draw a textured Phong-shaded 2D triangle, with perspective correction and z-buffering. template<typename tz, typename tc, typename tl> CImg<T>& draw_triangle(CImg<tz>& zbuffer, int x0, int y0, const float z0, int x1, int y1, const float z1, int x2, int y2, const float z2, const CImg<tc>& texture, int tx0, int ty0, int tx1, int ty1, int tx2, int ty2, const CImg<tl>& light, int lx0, int ly0, int lx1, int ly1, int lx2, int ly2, const float opacity=1) { if (is_empty() || z0<=0 || z1<=0 || z2<=0) return *this; if (!is_sameXY(zbuffer)) throw CImgArgumentException(_cimg_instance "draw_triangle(): Instance and specified Z-buffer (%u,%u,%u,%u,%p) have " "different dimensions.", cimg_instance, zbuffer._width,zbuffer._height,zbuffer._depth,zbuffer._spectrum,zbuffer._data); if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (light._depth>1 || light._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified light texture (%u,%u,%u,%u,%p).", cimg_instance,light._width,light._height,light._depth,light._spectrum,light._data); if (is_overlapped(texture)) return draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2, +texture,tx0,ty0,tx1,ty1,tx2,ty2,light,lx0,ly0,lx1,ly1,lx2,ly2,opacity); if (is_overlapped(light)) return draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2, texture,tx0,ty0,tx1,ty1,tx2,ty2,+light,lx0,ly0,lx1,ly1,lx2,ly2,opacity); float iz0 = 1/z0, iz1 = 1/z1, iz2 = 1/z2; if (y0>y1) cimg::swap(x0,x1,y0,y1,iz0,iz1,tx0,tx1,ty0,ty1,lx0,lx1,ly0,ly1); if (y0>y2) cimg::swap(x0,x2,y0,y2,iz0,iz2,tx0,tx2,ty0,ty2,lx0,lx2,ly0,ly2); if (y1>y2) cimg::swap(x1,x2,y1,y2,iz1,iz2,tx1,tx2,ty1,ty2,lx1,lx2,ly1,ly2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2; const float diz01 = iz1 - iz0, diz02 = iz2 - iz0, diz12 = iz2 - iz1, txz0 = tx0*iz0, txz1 = tx1*iz1, txz2 = tx2*iz2, tyz0 = ty0*iz0, tyz1 = ty1*iz1, tyz2 = ty2*iz2, dtxz01 = txz1 - txz0, dtxz02 = txz2 - txz0, dtxz12 = txz2 - txz1, dtyz01 = tyz1 - tyz0, dtyz02 = tyz2 - tyz0, dtyz12 = tyz2 - tyz1, lxz0 = lx0*iz0, lxz1 = lx1*iz1, lxz2 = lx2*iz2, lyz0 = ly0*iz0, lyz1 = ly1*iz1, lyz2 = ly2*iz2, dlxz01 = lxz1 - lxz0, dlxz02 = lxz2 - lxz0, dlxz12 = lxz2 - lxz1, dlyz01 = lyz1 - lyz0, dlyz02 = lyz2 - lyz0, dlyz12 = lyz2 - lyz1; const ulongT twhd = (ulongT)texture._width*texture._height*texture._depth, lwhd = (ulongT)light._width*light._height*light._depth; cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02; float izm = y<y1?(iz0 + diz01*yy0/dy01):(iz1 + diz12*yy1/dy12), izM = iz0 + diz02*yy0/dy02, txzm = y<y1?(txz0 + dtxz01*yy0/dy01):(txz1 + dtxz12*yy1/dy12), txzM = txz0 + dtxz02*yy0/dy02, tyzm = y<y1?(tyz0 + dtyz01*yy0/dy01):(tyz1 + dtyz12*yy1/dy12), tyzM = tyz0 + dtyz02*yy0/dy02, lxzm = y<y1?(lxz0 + dlxz01*yy0/dy01):(lxz1 + dlxz12*yy1/dy12), lxzM = lxz0 + dlxz02*yy0/dy02, lyzm = y<y1?(lyz0 + dlyz01*yy0/dy01):(lyz1 + dlyz12*yy1/dy12), lyzM = lyz0 + dlyz02*yy0/dy02; if (xm>xM) cimg::swap(xm,xM,izm,izM,txzm,txzM,tyzm,tyzM,lxzm,lxzM,lyzm,lyzM); if (xM>=0 || xm<=w1) { const int cxm = cimg::cut(xm,0,w1), cxM = cimg::cut(xM,0,w1); T *ptrd = data(cxm,y); tz *ptrz = zbuffer.data(cxm,y); const int dxmM = std::max(1,xM - xm); const float dizmM = izM - izm, dtxzmM = txzM - txzm, dtyzmM = tyzM - tyzm, dlxzmM = lxzM - lxzm, dlyzmM = lyzM - lyzm; for (int x = cxm; x<cxM; ++x) { const int xxm = x - xm; const float iz = izm + dizmM*xxm/dxmM; if (iz>=*ptrz) { *ptrz = (tz)iz; const float txz = txzm + dtxzmM*xxm/dxmM, tyz = tyzm + dtyzmM*xxm/dxmM, lxz = lxzm + dlxzmM*xxm/dxmM, lyz = lyzm + dlyzmM*xxm/dxmM; const int tx = (int)cimg::round(txz/iz), ty = (int)cimg::round(tyz/iz), lx = (int)cimg::round(lxz/iz), ly = (int)cimg::round(lyz/iz); const tc *const color = &texture._atXY(tx,ty); const tl *const lig = &light._atXY(lx,ly); cimg_forC(*this,c) { const tc col = color[c*twhd]; const float cbs = cimg::cut((float)lig[c*lwhd],0,2); const Tfloat val = cbs<=1?cbs*col:(2 - cbs)*col + (cbs - 1)*_sc_maxval; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } } ++ptrd; ++ptrz; } } } return *this; } //! Draw a filled 4D rectangle. /** \param x0 X-coordinate of the upper-left rectangle corner. \param y0 Y-coordinate of the upper-left rectangle corner. \param z0 Z-coordinate of the upper-left rectangle corner. \param c0 C-coordinate of the upper-left rectangle corner. \param x1 X-coordinate of the lower-right rectangle corner. \param y1 Y-coordinate of the lower-right rectangle corner. \param z1 Z-coordinate of the lower-right rectangle corner. \param c1 C-coordinate of the lower-right rectangle corner. \param val Scalar value used to fill the rectangle area. \param opacity Drawing opacity. **/ CImg<T>& draw_rectangle(const int x0, const int y0, const int z0, const int c0, const int x1, const int y1, const int z1, const int c1, const T val, const float opacity=1) { if (is_empty()) return *this; const int nx0 = x0<x1?x0:x1, nx1 = x0^x1^nx0, ny0 = y0<y1?y0:y1, ny1 = y0^y1^ny0, nz0 = z0<z1?z0:z1, nz1 = z0^z1^nz0, nc0 = c0<c1?c0:c1, nc1 = c0^c1^nc0; const int lX = (1 + nx1 - nx0) + (nx1>=width()?width() - 1 - nx1:0) + (nx0<0?nx0:0), lY = (1 + ny1 - ny0) + (ny1>=height()?height() - 1 - ny1:0) + (ny0<0?ny0:0), lZ = (1 + nz1 - nz0) + (nz1>=depth()?depth() - 1 - nz1:0) + (nz0<0?nz0:0), lC = (1 + nc1 - nc0) + (nc1>=spectrum()?spectrum() - 1 - nc1:0) + (nc0<0?nc0:0); const ulongT offX = (ulongT)_width - lX, offY = (ulongT)_width*(_height - lY), offZ = (ulongT)_width*_height*(_depth - lZ); const float nopacity = cimg::abs(opacity), copacity = 1 - std::max(opacity,0.f); T *ptrd = data(nx0<0?0:nx0,ny0<0?0:ny0,nz0<0?0:nz0,nc0<0?0:nc0); if (lX>0 && lY>0 && lZ>0 && lC>0) for (int v = 0; v<lC; ++v) { for (int z = 0; z<lZ; ++z) { for (int y = 0; y<lY; ++y) { if (opacity>=1) { if (sizeof(T)!=1) { for (int x = 0; x<lX; ++x) *(ptrd++) = val; ptrd+=offX; } else { std::memset(ptrd,(int)val,lX); ptrd+=_width; } } else { for (int x = 0; x<lX; ++x) { *ptrd = (T)(nopacity*val + *ptrd*copacity); ++ptrd; } ptrd+=offX; } } ptrd+=offY; } ptrd+=offZ; } return *this; } //! Draw a filled 3D rectangle. /** \param x0 X-coordinate of the upper-left rectangle corner. \param y0 Y-coordinate of the upper-left rectangle corner. \param z0 Z-coordinate of the upper-left rectangle corner. \param x1 X-coordinate of the lower-right rectangle corner. \param y1 Y-coordinate of the lower-right rectangle corner. \param z1 Z-coordinate of the lower-right rectangle corner. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. **/ template<typename tc> CImg<T>& draw_rectangle(const int x0, const int y0, const int z0, const int x1, const int y1, const int z1, const tc *const color, const float opacity=1) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_rectangle(): Specified color is (null).", cimg_instance); cimg_forC(*this,c) draw_rectangle(x0,y0,z0,c,x1,y1,z1,c,(T)color[c],opacity); return *this; } //! Draw a filled 2D rectangle. /** \param x0 X-coordinate of the upper-left rectangle corner. \param y0 Y-coordinate of the upper-left rectangle corner. \param x1 X-coordinate of the lower-right rectangle corner. \param y1 Y-coordinate of the lower-right rectangle corner. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. **/ template<typename tc> CImg<T>& draw_rectangle(const int x0, const int y0, const int x1, const int y1, const tc *const color, const float opacity=1) { return draw_rectangle(x0,y0,0,x1,y1,_depth - 1,color,opacity); } //! Draw a outlined 2D rectangle \overloading. template<typename tc> CImg<T>& draw_rectangle(const int x0, const int y0, const int x1, const int y1, const tc *const color, const float opacity, const unsigned int pattern) { if (is_empty()) return *this; if (y0==y1) return draw_line(x0,y0,x1,y0,color,opacity,pattern,true); if (x0==x1) return draw_line(x0,y0,x0,y1,color,opacity,pattern,true); const int nx0 = x0<x1?x0:x1, nx1 = x0^x1^nx0, ny0 = y0<y1?y0:y1, ny1 = y0^y1^ny0; if (ny1==ny0 + 1) return draw_line(nx0,ny0,nx1,ny0,color,opacity,pattern,true). draw_line(nx1,ny1,nx0,ny1,color,opacity,pattern,false); return draw_line(nx0,ny0,nx1,ny0,color,opacity,pattern,true). draw_line(nx1,ny0 + 1,nx1,ny1 - 1,color,opacity,pattern,false). draw_line(nx1,ny1,nx0,ny1,color,opacity,pattern,false). draw_line(nx0,ny1 - 1,nx0,ny0 + 1,color,opacity,pattern,false); } //! Draw a filled 2D polygon. /** \param points Set of polygon vertices. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. **/ template<typename tp, typename tc> CImg<T>& draw_polygon(const CImg<tp>& points, const tc *const color, const float opacity=1) { if (is_empty() || !points) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_polygon(): Specified color is (null).", cimg_instance); if (points.height()!=2) throw CImgArgumentException(_cimg_instance "draw_polygon(): Invalid specified point set (%u,%u,%u,%u).", cimg_instance, points._width,points._height,points._depth,points._spectrum); if (points._width==1) return draw_point(cimg::uiround(points(0,0)),cimg::uiround(points(0,1)),color,opacity); if (points._width==2) return draw_line(cimg::uiround(points(0,0)),cimg::uiround(points(0,1)), cimg::uiround(points(1,0)),cimg::uiround(points(1,1)),color,opacity); if (points._width==3) return draw_triangle(cimg::uiround(points(0,0)),cimg::uiround(points(0,1)), cimg::uiround(points(1,0)),cimg::uiround(points(1,1)), cimg::uiround(points(2,0)),cimg::uiround(points(2,1)),color,opacity); cimg_init_scanline(opacity); int xmin = 0, ymin = 0, xmax = points.get_shared_row(0).max_min(xmin), ymax = points.get_shared_row(1).max_min(ymin); if (xmax<0 || xmin>=width() || ymax<0 || ymin>=height()) return *this; if (ymin==ymax) return draw_line(xmin,ymin,xmax,ymax,color,opacity); ymin = std::max(0,ymin); ymax = std::min(height() - 1,ymax); CImg<intT> Xs(points._width,ymax - ymin + 1); CImg<uintT> count(Xs._height,1,1,1,0); unsigned int n = 0, nn = 1; bool go_on = true; while (go_on) { unsigned int an = (nn + 1)%points._width; const int x0 = cimg::uiround(points(n,0)), y0 = cimg::uiround(points(n,1)); if (points(nn,1)==y0) while (points(an,1)==y0) { nn = an; (an+=1)%=points._width; } const int x1 = cimg::uiround(points(nn,0)), y1 = cimg::uiround(points(nn,1)); unsigned int tn = an; while (points(tn,1)==y1) (tn+=1)%=points._width; if (y0!=y1) { const int y2 = cimg::uiround(points(tn,1)), x01 = x1 - x0, y01 = y1 - y0, y12 = y2 - y1, step = cimg::sign(y01), tmax = std::max(1,cimg::abs(y01)), htmax = tmax*cimg::sign(x01)/2, tend = tmax - (step==cimg::sign(y12)); unsigned int y = (unsigned int)y0 - ymin; for (int t = 0; t<=tend; ++t, y+=step) if (y<Xs._height) Xs(count[y]++,y) = x0 + (t*x01 + htmax)/tmax; } go_on = nn>n; n = nn; nn = an; } cimg_pragma_openmp(parallel for cimg_openmp_if(Xs._height>=(cimg_openmp_sizefactor)*32)) cimg_forY(Xs,y) { const CImg<intT> Xsy = Xs.get_shared_points(0,count[y] - 1,y).sort(); int px = width(); for (unsigned int k = 0; k<Xsy._width; k+=2) { int x0 = Xsy[k]; const int x1 = Xsy[k + 1]; x0+=x0==px; cimg_draw_scanline(x0,x1,y + ymin,color,opacity,1); px = x1; } } return *this; } //! Draw a outlined 2D or 3D polygon \overloading. template<typename t, typename tc> CImg<T>& draw_polygon(const CImg<t>& points, const tc *const color, const float opacity, const unsigned int pattern) { if (is_empty() || !points) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_polygon(): Specified color is (null).", cimg_instance); if (points._width==1) return draw_point((int)points(0,0),(int)points(0,1),color,opacity); if (points._width==2) return draw_line((int)points(0,0),(int)points(0,1), (int)points(1,0),(int)points(1,1),color,opacity,pattern); bool ninit_hatch = true; switch (points._height) { case 0 : case 1 : throw CImgArgumentException(_cimg_instance "draw_polygon(): Invalid specified point set (%u,%u,%u,%u).", cimg_instance, points._width,points._height,points._depth,points._spectrum); default : { CImg<intT> npoints(points._width,2); int x = npoints(0,0) = (int)points(0,0), y = npoints(0,1) = (int)points(0,1); unsigned int nb_points = 1; for (unsigned int p = 1; p<points._width; ++p) { const int nx = (int)points(p,0), ny = (int)points(p,1); if (nx!=x || ny!=y) { npoints(nb_points,0) = nx; npoints(nb_points++,1) = ny; x = nx; y = ny; } } const int x0 = (int)npoints(0,0), y0 = (int)npoints(0,1); int ox = x0, oy = y0; for (unsigned int i = 1; i<nb_points; ++i) { const int _x = (int)npoints(i,0), _y = (int)npoints(i,1); draw_line(ox,oy,_x,_y,color,opacity,pattern,ninit_hatch); ninit_hatch = false; ox = _x; oy = _y; } draw_line(ox,oy,x0,y0,color,opacity,pattern,false); } } return *this; } //! Draw a filled 2D ellipse. /** \param x0 X-coordinate of the ellipse center. \param y0 Y-coordinate of the ellipse center. \param r1 First radius of the ellipse. \param r2 Second radius of the ellipse. \param angle Angle of the first radius. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. **/ template<typename tc> CImg<T>& draw_ellipse(const int x0, const int y0, const float r1, const float r2, const float angle, const tc *const color, const float opacity=1) { return _draw_ellipse(x0,y0,r1,r2,angle,color,opacity,0U,true); } //! Draw a filled 2D ellipse \overloading. /** \param x0 X-coordinate of the ellipse center. \param y0 Y-coordinate of the ellipse center. \param tensor Diffusion tensor describing the ellipse. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. **/ template<typename t, typename tc> CImg<T>& draw_ellipse(const int x0, const int y0, const CImg<t> &tensor, const tc *const color, const float opacity=1) { CImgList<t> eig = tensor.get_symmetric_eigen(); const CImg<t> &val = eig[0], &vec = eig[1]; return draw_ellipse(x0,y0,std::sqrt(val(0)),std::sqrt(val(1)), std::atan2(vec(0,1),vec(0,0))*180/cimg::PI, color,opacity); } //! Draw an outlined 2D ellipse. /** \param x0 X-coordinate of the ellipse center. \param y0 Y-coordinate of the ellipse center. \param r1 First radius of the ellipse. \param r2 Second radius of the ellipse. \param angle Angle of the first radius. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \param pattern An integer whose bits describe the outline pattern. **/ template<typename tc> CImg<T>& draw_ellipse(const int x0, const int y0, const float r1, const float r2, const float angle, const tc *const color, const float opacity, const unsigned int pattern) { if (pattern) _draw_ellipse(x0,y0,r1,r2,angle,color,opacity,pattern,false); return *this; } //! Draw an outlined 2D ellipse \overloading. /** \param x0 X-coordinate of the ellipse center. \param y0 Y-coordinate of the ellipse center. \param tensor Diffusion tensor describing the ellipse. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \param pattern An integer whose bits describe the outline pattern. **/ template<typename t, typename tc> CImg<T>& draw_ellipse(const int x0, const int y0, const CImg<t> &tensor, const tc *const color, const float opacity, const unsigned int pattern) { CImgList<t> eig = tensor.get_symmetric_eigen(); const CImg<t> &val = eig[0], &vec = eig[1]; return draw_ellipse(x0,y0,std::sqrt(val(0)),std::sqrt(val(1)), std::atan2(vec(0,1),vec(0,0))*180/cimg::PI, color,opacity,pattern); } template<typename tc> CImg<T>& _draw_ellipse(const int x0, const int y0, const float radius1, const float radius2, const float angle, const tc *const color, const float opacity, const unsigned int pattern, const bool is_filled) { if (is_empty() || (!is_filled && !pattern)) return *this; const float radiusM = std::max(radius1,radius2); if (radius1<0 || radius2<0 || x0 - radiusM>=width() || y0 + radiusM<0 || y0 - radiusM>=height()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_ellipse(): Specified color is (null).", cimg_instance); const int iradius1 = (int)cimg::round(radius1), iradius2 = (int)cimg::round(radius2); if (!iradius1 && !iradius2) return draw_point(x0,y0,color,opacity); if (iradius1==iradius2) { if (is_filled) return draw_circle(x0,y0,iradius1,color,opacity); else return draw_circle(x0,y0,iradius1,color,opacity,pattern); } const float ang = (float)(angle*cimg::PI/180); if (!is_filled) { // Outlined const float ca = std::cos(ang), sa = std::sin(ang); CImg<int> points((unsigned int)cimg::round(6*radiusM),2); cimg_forX(points,k) { const float _ang = (float)(2*cimg::PI*k/points._width), X = (float)(radius1*std::cos(_ang)), Y = (float)(radius2*std::sin(_ang)); points(k,0) = (int)cimg::round(x0 + (X*ca - Y*sa)); points(k,1) = (int)cimg::round(y0 + (X*sa + Y*ca)); } draw_polygon(points,color,opacity,pattern); } else { // Filled cimg_init_scanline(opacity); const float ca = std::cos(ang), sa = -std::sin(ang), ca2 = ca*ca, sa2 = sa*sa, casa = ca*sa, i1 = 1/cimg::sqr(radius1), i2 = 1/cimg::sqr(radius2), t1 = i1*ca2 + i2*sa2, t2 = (i2 - i1)*casa, t3 = i2*ca2 + i1*sa2, t12 = t1*2; const int _ymin = (int)std::floor(y0 - radiusM), _ymax = (int)std::ceil(y0 + radiusM), ymin = _ymin<0?0:_ymin, ymax = _ymax>=height()?height() - 1:_ymax; for (int y = ymin; y<=ymax; ++y) { const float Y = y - y0 + 0.5f, B = 2*t2*Y, C = t3*Y*Y - 1, D = B*B - 4*t1*C; if (D>=0) { const float sD = std::sqrt(D); const int xmin = (int)(x0 + cimg::round((-B - sD)/t12)), xmax = (int)(x0 + cimg::round((-B + sD)/t12)); cimg_draw_scanline(xmin,xmax,y,color,opacity,1); } } } return *this; } //! Draw a filled 2D circle. /** \param x0 X-coordinate of the circle center. \param y0 Y-coordinate of the circle center. \param radius Circle radius. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \note - Circle version of the Bresenham's algorithm is used. **/ template<typename tc> CImg<T>& draw_circle(const int x0, const int y0, int radius, const tc *const color, const float opacity=1) { if (is_empty()) return *this; if (radius<0 || x0 - radius>=width() || y0 + radius<0 || y0 - radius>=height()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_circle(): Specified color is (null).", cimg_instance); if (!radius) return draw_point(x0,y0,color,opacity); cimg_init_scanline(opacity); if (y0>=0 && y0<height()) cimg_draw_scanline(x0 - radius,x0 + radius,y0,color,opacity,1); for (int f = 1 - radius, ddFx = 0, ddFy = -(radius<<1), x = 0, y = radius; x<y; ) { if (f>=0) { const int x1 = x0 - x, x2 = x0 + x, y1 = y0 - y, y2 = y0 + y; if (y1>=0 && y1<height()) cimg_draw_scanline(x1,x2,y1,color,opacity,1); if (y2>=0 && y2<height()) cimg_draw_scanline(x1,x2,y2,color,opacity,1); f+=(ddFy+=2); --y; } const bool no_diag = y!=(x++); ++(f+=(ddFx+=2)); const int x1 = x0 - y, x2 = x0 + y, y1 = y0 - x, y2 = y0 + x; if (no_diag) { if (y1>=0 && y1<height()) cimg_draw_scanline(x1,x2,y1,color,opacity,1); if (y2>=0 && y2<height()) cimg_draw_scanline(x1,x2,y2,color,opacity,1); } } return *this; } //! Draw an outlined 2D circle. /** \param x0 X-coordinate of the circle center. \param y0 Y-coordinate of the circle center. \param radius Circle radius. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \param pattern An integer whose bits describe the outline pattern. **/ template<typename tc> CImg<T>& draw_circle(const int x0, const int y0, int radius, const tc *const color, const float opacity, const unsigned int pattern) { if (pattern!=~0U) return draw_ellipse(x0,y0,radius,radius,0,color,opacity,pattern); if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_circle(): Specified color is (null).", cimg_instance); if (radius<0 || x0 - radius>=width() || y0 + radius<0 || y0 - radius>=height()) return *this; if (!radius) return draw_point(x0,y0,color,opacity); draw_point(x0 - radius,y0,color,opacity).draw_point(x0 + radius,y0,color,opacity). draw_point(x0,y0 - radius,color,opacity).draw_point(x0,y0 + radius,color,opacity); if (radius==1) return *this; for (int f = 1 - radius, ddFx = 0, ddFy = -(radius<<1), x = 0, y = radius; x<y; ) { if (f>=0) { f+=(ddFy+=2); --y; } ++x; ++(f+=(ddFx+=2)); if (x!=y + 1) { const int x1 = x0 - y, x2 = x0 + y, y1 = y0 - x, y2 = y0 + x, x3 = x0 - x, x4 = x0 + x, y3 = y0 - y, y4 = y0 + y; draw_point(x1,y1,color,opacity).draw_point(x1,y2,color,opacity). draw_point(x2,y1,color,opacity).draw_point(x2,y2,color,opacity); if (x!=y) draw_point(x3,y3,color,opacity).draw_point(x4,y4,color,opacity). draw_point(x4,y3,color,opacity).draw_point(x3,y4,color,opacity); } } return *this; } //! Draw an image. /** \param sprite Sprite image. \param x0 X-coordinate of the sprite position. \param y0 Y-coordinate of the sprite position. \param z0 Z-coordinate of the sprite position. \param c0 C-coordinate of the sprite position. \param opacity Drawing opacity. **/ template<typename t> CImg<T>& draw_image(const int x0, const int y0, const int z0, const int c0, const CImg<t>& sprite, const float opacity=1) { if (is_empty() || !sprite) return *this; if (is_overlapped(sprite)) return draw_image(x0,y0,z0,c0,+sprite,opacity); if (x0==0 && y0==0 && z0==0 && c0==0 && is_sameXYZC(sprite) && opacity>=1 && !is_shared()) return assign(sprite,false); const bool bx = (x0<0), by = (y0<0), bz = (z0<0), bc = (c0<0); const int lX = sprite.width() - (x0 + sprite.width()>width()?x0 + sprite.width() - width():0) + (bx?x0:0), lY = sprite.height() - (y0 + sprite.height()>height()?y0 + sprite.height() - height():0) + (by?y0:0), lZ = sprite.depth() - (z0 + sprite.depth()>depth()?z0 + sprite.depth() - depth():0) + (bz?z0:0), lC = sprite.spectrum() - (c0 + sprite.spectrum()>spectrum()?c0 + sprite.spectrum() - spectrum():0) + (bc?c0:0); const t *ptrs = sprite._data + (bx?-x0:0) + (by?-y0*(ulongT)sprite.width():0) + (bz?-z0*(ulongT)sprite.width()*sprite.height():0) + (bc?-c0*(ulongT)sprite.width()*sprite.height()*sprite.depth():0); const ulongT offX = (ulongT)_width - lX, soffX = (ulongT)sprite._width - lX, offY = (ulongT)_width*(_height - lY), soffY = (ulongT)sprite._width*(sprite._height - lY), offZ = (ulongT)_width*_height*(_depth - lZ), soffZ = (ulongT)sprite._width*sprite._height*(sprite._depth - lZ); const float nopacity = cimg::abs(opacity), copacity = 1 - std::max(opacity,0.f); if (lX>0 && lY>0 && lZ>0 && lC>0) { T *ptrd = data(x0<0?0:x0,y0<0?0:y0,z0<0?0:z0,c0<0?0:c0); for (int v = 0; v<lC; ++v) { for (int z = 0; z<lZ; ++z) { for (int y = 0; y<lY; ++y) { if (opacity>=1) for (int x = 0; x<lX; ++x) *(ptrd++) = (T)*(ptrs++); else for (int x = 0; x<lX; ++x) { *ptrd = (T)(nopacity*(*(ptrs++)) + *ptrd*copacity); ++ptrd; } ptrd+=offX; ptrs+=soffX; } ptrd+=offY; ptrs+=soffY; } ptrd+=offZ; ptrs+=soffZ; } } return *this; } //! Draw an image \specialization. CImg<T>& draw_image(const int x0, const int y0, const int z0, const int c0, const CImg<T>& sprite, const float opacity=1) { if (is_empty() || !sprite) return *this; if (is_overlapped(sprite)) return draw_image(x0,y0,z0,c0,+sprite,opacity); if (x0==0 && y0==0 && z0==0 && c0==0 && is_sameXYZC(sprite) && opacity>=1 && !is_shared()) return assign(sprite,false); const bool bx = (x0<0), by = (y0<0), bz = (z0<0), bc = (c0<0); const int lX = sprite.width() - (x0 + sprite.width()>width()?x0 + sprite.width() - width():0) + (bx?x0:0), lY = sprite.height() - (y0 + sprite.height()>height()?y0 + sprite.height() - height():0) + (by?y0:0), lZ = sprite.depth() - (z0 + sprite.depth()>depth()?z0 + sprite.depth() - depth():0) + (bz?z0:0), lC = sprite.spectrum() - (c0 + sprite.spectrum()>spectrum()?c0 + sprite.spectrum() - spectrum():0) + (bc?c0:0); const T *ptrs = sprite._data + (bx?-x0:0) + (by?-y0*(ulongT)sprite.width():0) + (bz?-z0*(ulongT)sprite.width()*sprite.height():0) + (bc?-c0*(ulongT)sprite.width()*sprite.height()*sprite.depth():0); const ulongT offX = (ulongT)_width - lX, soffX = (ulongT)sprite._width - lX, offY = (ulongT)_width*(_height - lY), soffY = (ulongT)sprite._width*(sprite._height - lY), offZ = (ulongT)_width*_height*(_depth - lZ), soffZ = (ulongT)sprite._width*sprite._height*(sprite._depth - lZ), slX = lX*sizeof(T); const float nopacity = cimg::abs(opacity), copacity = 1 - std::max(opacity,0.f); if (lX>0 && lY>0 && lZ>0 && lC>0) { T *ptrd = data(x0<0?0:x0,y0<0?0:y0,z0<0?0:z0,c0<0?0:c0); for (int v = 0; v<lC; ++v) { for (int z = 0; z<lZ; ++z) { if (opacity>=1) for (int y = 0; y<lY; ++y) { std::memcpy(ptrd,ptrs,slX); ptrd+=_width; ptrs+=sprite._width; } else for (int y = 0; y<lY; ++y) { for (int x = 0; x<lX; ++x) { *ptrd = (T)(nopacity*(*(ptrs++)) + *ptrd*copacity); ++ptrd; } ptrd+=offX; ptrs+=soffX; } ptrd+=offY; ptrs+=soffY; } ptrd+=offZ; ptrs+=soffZ; } } return *this; } //! Draw an image \overloading. template<typename t> CImg<T>& draw_image(const int x0, const int y0, const int z0, const CImg<t>& sprite, const float opacity=1) { return draw_image(x0,y0,z0,0,sprite,opacity); } //! Draw an image \overloading. template<typename t> CImg<T>& draw_image(const int x0, const int y0, const CImg<t>& sprite, const float opacity=1) { return draw_image(x0,y0,0,sprite,opacity); } //! Draw an image \overloading. template<typename t> CImg<T>& draw_image(const int x0, const CImg<t>& sprite, const float opacity=1) { return draw_image(x0,0,sprite,opacity); } //! Draw an image \overloading. template<typename t> CImg<T>& draw_image(const CImg<t>& sprite, const float opacity=1) { return draw_image(0,sprite,opacity); } //! Draw a masked image. /** \param sprite Sprite image. \param mask Mask image. \param x0 X-coordinate of the sprite position in the image instance. \param y0 Y-coordinate of the sprite position in the image instance. \param z0 Z-coordinate of the sprite position in the image instance. \param c0 C-coordinate of the sprite position in the image instance. \param mask_max_value Maximum pixel value of the mask image \c mask. \param opacity Drawing opacity. \note - Pixel values of \c mask set the opacity of the corresponding pixels in \c sprite. - Dimensions along x,y and z of \p sprite and \p mask must be the same. **/ template<typename ti, typename tm> CImg<T>& draw_image(const int x0, const int y0, const int z0, const int c0, const CImg<ti>& sprite, const CImg<tm>& mask, const float opacity=1, const float mask_max_value=1) { if (is_empty() || !sprite || !mask) return *this; if (is_overlapped(sprite)) return draw_image(x0,y0,z0,c0,+sprite,mask,opacity,mask_max_value); if (is_overlapped(mask)) return draw_image(x0,y0,z0,c0,sprite,+mask,opacity,mask_max_value); if (mask._width!=sprite._width || mask._height!=sprite._height || mask._depth!=sprite._depth) throw CImgArgumentException(_cimg_instance "draw_image(): Sprite (%u,%u,%u,%u,%p) and mask (%u,%u,%u,%u,%p) have " "incompatible dimensions.", cimg_instance, sprite._width,sprite._height,sprite._depth,sprite._spectrum,sprite._data, mask._width,mask._height,mask._depth,mask._spectrum,mask._data); const bool bx = (x0<0), by = (y0<0), bz = (z0<0), bc = (c0<0); const int lX = sprite.width() - (x0 + sprite.width()>width()?x0 + sprite.width() - width():0) + (bx?x0:0), lY = sprite.height() - (y0 + sprite.height()>height()?y0 + sprite.height() - height():0) + (by?y0:0), lZ = sprite.depth() - (z0 + sprite.depth()>depth()?z0 + sprite.depth() - depth():0) + (bz?z0:0), lC = sprite.spectrum() - (c0 + sprite.spectrum()>spectrum()?c0 + sprite.spectrum() - spectrum():0) + (bc?c0:0); const ulongT coff = (bx?-x0:0) + (by?-y0*(ulongT)mask.width():0) + (bz?-z0*(ulongT)mask.width()*mask.height():0) + (bc?-c0*(ulongT)mask.width()*mask.height()*mask.depth():0), ssize = (ulongT)mask.width()*mask.height()*mask.depth()*mask.spectrum(); const ti *ptrs = sprite._data + coff; const tm *ptrm = mask._data + coff; const ulongT offX = (ulongT)_width - lX, soffX = (ulongT)sprite._width - lX, offY = (ulongT)_width*(_height - lY), soffY = (ulongT)sprite._width*(sprite._height - lY), offZ = (ulongT)_width*_height*(_depth - lZ), soffZ = (ulongT)sprite._width*sprite._height*(sprite._depth - lZ); if (lX>0 && lY>0 && lZ>0 && lC>0) { T *ptrd = data(x0<0?0:x0,y0<0?0:y0,z0<0?0:z0,c0<0?0:c0); for (int c = 0; c<lC; ++c) { ptrm = mask._data + (ptrm - mask._data)%ssize; for (int z = 0; z<lZ; ++z) { for (int y = 0; y<lY; ++y) { for (int x = 0; x<lX; ++x) { const float mopacity = (float)(*(ptrm++)*opacity), nopacity = cimg::abs(mopacity), copacity = mask_max_value - std::max(mopacity,0.f); *ptrd = (T)((nopacity*(*(ptrs++)) + *ptrd*copacity)/mask_max_value); ++ptrd; } ptrd+=offX; ptrs+=soffX; ptrm+=soffX; } ptrd+=offY; ptrs+=soffY; ptrm+=soffY; } ptrd+=offZ; ptrs+=soffZ; ptrm+=soffZ; } } return *this; } //! Draw a masked image \overloading. template<typename ti, typename tm> CImg<T>& draw_image(const int x0, const int y0, const int z0, const CImg<ti>& sprite, const CImg<tm>& mask, const float opacity=1, const float mask_max_value=1) { return draw_image(x0,y0,z0,0,sprite,mask,opacity,mask_max_value); } //! Draw a image \overloading. template<typename ti, typename tm> CImg<T>& draw_image(const int x0, const int y0, const CImg<ti>& sprite, const CImg<tm>& mask, const float opacity=1, const float mask_max_value=1) { return draw_image(x0,y0,0,sprite,mask,opacity,mask_max_value); } //! Draw a image \overloading. template<typename ti, typename tm> CImg<T>& draw_image(const int x0, const CImg<ti>& sprite, const CImg<tm>& mask, const float opacity=1, const float mask_max_value=1) { return draw_image(x0,0,sprite,mask,opacity,mask_max_value); } //! Draw an image. template<typename ti, typename tm> CImg<T>& draw_image(const CImg<ti>& sprite, const CImg<tm>& mask, const float opacity=1, const float mask_max_value=1) { return draw_image(0,sprite,mask,opacity,mask_max_value); } //! Draw a text string. /** \param x0 X-coordinate of the text in the image instance. \param y0 Y-coordinate of the text in the image instance. \param text Format of the text ('printf'-style format string). \param foreground_color Pointer to \c spectrum() consecutive values, defining the foreground drawing color. \param background_color Pointer to \c spectrum() consecutive values, defining the background drawing color. \param opacity Drawing opacity. \param font Font used for drawing text. **/ template<typename tc1, typename tc2, typename t> CImg<T>& draw_text(const int x0, const int y0, const char *const text, const tc1 *const foreground_color, const tc2 *const background_color, const float opacity, const CImgList<t>& font, ...) { if (!font) return *this; CImg<charT> tmp(2048); std::va_list ap; va_start(ap,font); cimg_vsnprintf(tmp,tmp._width,text,ap); va_end(ap); return _draw_text(x0,y0,tmp,foreground_color,background_color,opacity,font,false); } //! Draw a text string \overloading. /** \note A transparent background is used for the text. **/ template<typename tc, typename t> CImg<T>& draw_text(const int x0, const int y0, const char *const text, const tc *const foreground_color, const int, const float opacity, const CImgList<t>& font, ...) { if (!font) return *this; CImg<charT> tmp(2048); std::va_list ap; va_start(ap,font); cimg_vsnprintf(tmp,tmp._width,text,ap); va_end(ap); return _draw_text(x0,y0,tmp,foreground_color,(tc*)0,opacity,font,false); } //! Draw a text string \overloading. /** \note A transparent foreground is used for the text. **/ template<typename tc, typename t> CImg<T>& draw_text(const int x0, const int y0, const char *const text, const int, const tc *const background_color, const float opacity, const CImgList<t>& font, ...) { if (!font) return *this; CImg<charT> tmp(2048); std::va_list ap; va_start(ap,font); cimg_vsnprintf(tmp,tmp._width,text,ap); va_end(ap); return _draw_text(x0,y0,tmp,(tc*)0,background_color,opacity,font,false); } //! Draw a text string \overloading. /** \param x0 X-coordinate of the text in the image instance. \param y0 Y-coordinate of the text in the image instance. \param text Format of the text ('printf'-style format string). \param foreground_color Array of spectrum() values of type \c T, defining the foreground color (0 means 'transparent'). \param background_color Array of spectrum() values of type \c T, defining the background color (0 means 'transparent'). \param opacity Drawing opacity. \param font_height Height of the text font (exact match for 13,23,53,103, interpolated otherwise). **/ template<typename tc1, typename tc2> CImg<T>& draw_text(const int x0, const int y0, const char *const text, const tc1 *const foreground_color, const tc2 *const background_color, const float opacity=1, const unsigned int font_height=13, ...) { if (!font_height) return *this; CImg<charT> tmp(2048); std::va_list ap; va_start(ap,font_height); cimg_vsnprintf(tmp,tmp._width,text,ap); va_end(ap); const CImgList<ucharT>& font = CImgList<ucharT>::font(font_height,true); _draw_text(x0,y0,tmp,foreground_color,background_color,opacity,font,true); return *this; } //! Draw a text string \overloading. template<typename tc> CImg<T>& draw_text(const int x0, const int y0, const char *const text, const tc *const foreground_color, const int background_color=0, const float opacity=1, const unsigned int font_height=13, ...) { if (!font_height) return *this; cimg::unused(background_color); CImg<charT> tmp(2048); std::va_list ap; va_start(ap,font_height); cimg_vsnprintf(tmp,tmp._width,text,ap); va_end(ap); return draw_text(x0,y0,"%s",foreground_color,(const tc*)0,opacity,font_height,tmp._data); } //! Draw a text string \overloading. template<typename tc> CImg<T>& draw_text(const int x0, const int y0, const char *const text, const int, const tc *const background_color, const float opacity=1, const unsigned int font_height=13, ...) { if (!font_height) return *this; CImg<charT> tmp(2048); std::va_list ap; va_start(ap,font_height); cimg_vsnprintf(tmp,tmp._width,text,ap); va_end(ap); return draw_text(x0,y0,"%s",(tc*)0,background_color,opacity,font_height,tmp._data); } template<typename tc1, typename tc2, typename t> CImg<T>& _draw_text(const int x0, const int y0, const char *const text, const tc1 *const foreground_color, const tc2 *const background_color, const float opacity, const CImgList<t>& font, const bool is_native_font) { if (!text) return *this; if (!font) throw CImgArgumentException(_cimg_instance "draw_text(): Empty specified font.", cimg_instance); const unsigned int text_length = (unsigned int)std::strlen(text); if (is_empty()) { // If needed, pre-compute necessary size of the image int x = 0, y = 0, w = 0; unsigned char c = 0; for (unsigned int i = 0; i<text_length; ++i) { c = (unsigned char)text[i]; switch (c) { case '\n' : y+=font[0]._height; if (x>w) w = x; x = 0; break; case '\t' : x+=4*font[(int)' ']._width; break; default : if (c<font._width) x+=font[c]._width; } } if (x!=0 || c=='\n') { if (x>w) w=x; y+=font[0]._height; } assign(x0 + w,y0 + y,1,is_native_font?1:font[0]._spectrum,(T)0); } int x = x0, y = y0; for (unsigned int i = 0; i<text_length; ++i) { const unsigned char ch = (unsigned char)text[i]; switch (ch) { case '\n' : y+=font[0]._height; x = x0; break; case '\t' : x+=4*font[(int)' ']._width; break; default : if (ch<font._width) { CImg<T> letter = font[ch]; if (letter) { if (is_native_font && _spectrum>letter._spectrum) letter.resize(-100,-100,1,_spectrum,0,2); const unsigned int cmin = std::min(_spectrum,letter._spectrum); if (foreground_color) for (unsigned int c = 0; c<cmin; ++c) if (foreground_color[c]!=1) letter.get_shared_channel(c)*=foreground_color[c]; if (ch + 256<font.width()) { // Letter has mask if (background_color) for (unsigned int c = 0; c<cmin; ++c) draw_rectangle(x,y,0,c,x + letter._width - 1,y + letter._height - 1,0,c, background_color[c],opacity); draw_image(x,y,letter,font[ch + 256],opacity,255.f); } else draw_image(x,y,letter,opacity); // Letter has no mask x+=letter._width; } } } } return *this; } // [internal] Version used to display text in interactive viewers. CImg<T>& __draw_text(const char *const text, const int is_down, ...) { CImg<charT> tmp(2048); std::va_list ap; va_start(ap,is_down); cimg_vsnprintf(tmp,tmp._width,text,ap); va_end(ap); CImg<ucharT> a_label, a_labelmask; const unsigned char a_labelcolor = 255; const unsigned int fsize = 14; a_label.draw_text(0,0,"%s",&a_labelcolor,0,1,fsize,tmp._data).normalize(0,255); if (a_label) { a_label+=(255 - a_label.get_dilate(3)).normalize(0,80); a_label.resize(-100,-100,1,3,1); return draw_image(0,is_down?height() - a_label.height():0,a_label,0.85f); } return *this; } //! Draw a 2D vector field. /** \param flow Image of 2D vectors used as input data. \param color Image of spectrum()-D vectors corresponding to the color of each arrow. \param opacity Drawing opacity. \param sampling Length (in pixels) between each arrow. \param factor Length factor of each arrow (if <0, computed as a percentage of the maximum length). \param is_arrow Tells if arrows must be drawn, instead of oriented segments. \param pattern Used pattern to draw lines. \note Clipping is supported. **/ template<typename t1, typename t2> CImg<T>& draw_quiver(const CImg<t1>& flow, const t2 *const color, const float opacity=1, const unsigned int sampling=25, const float factor=-20, const bool is_arrow=true, const unsigned int pattern=~0U) { return draw_quiver(flow,CImg<t2>(color,_spectrum,1,1,1,true),opacity,sampling,factor,is_arrow,pattern); } //! Draw a 2D vector field, using a field of colors. /** \param flow Image of 2D vectors used as input data. \param color Image of spectrum()-D vectors corresponding to the color of each arrow. \param opacity Opacity of the drawing. \param sampling Length (in pixels) between each arrow. \param factor Length factor of each arrow (if <0, computed as a percentage of the maximum length). \param is_arrow Tells if arrows must be drawn, instead of oriented segments. \param pattern Used pattern to draw lines. \note Clipping is supported. **/ template<typename t1, typename t2> CImg<T>& draw_quiver(const CImg<t1>& flow, const CImg<t2>& color, const float opacity=1, const unsigned int sampling=25, const float factor=-20, const bool is_arrow=true, const unsigned int pattern=~0U) { if (is_empty()) return *this; if (!flow || flow._spectrum!=2) throw CImgArgumentException(_cimg_instance "draw_quiver(): Invalid dimensions of specified flow (%u,%u,%u,%u,%p).", cimg_instance, flow._width,flow._height,flow._depth,flow._spectrum,flow._data); if (sampling<=0) throw CImgArgumentException(_cimg_instance "draw_quiver(): Invalid sampling value %g " "(should be >0)", cimg_instance, sampling); const bool colorfield = (color._width==flow._width && color._height==flow._height && color._depth==1 && color._spectrum==_spectrum); if (is_overlapped(flow)) return draw_quiver(+flow,color,opacity,sampling,factor,is_arrow,pattern); float vmax,fact; if (factor<=0) { float m, M = (float)flow.get_norm(2).max_min(m); vmax = (float)std::max(cimg::abs(m),cimg::abs(M)); if (!vmax) vmax = 1; fact = -factor; } else { fact = factor; vmax = 1; } for (unsigned int y = sampling/2; y<_height; y+=sampling) for (unsigned int x = sampling/2; x<_width; x+=sampling) { const unsigned int X = x*flow._width/_width, Y = y*flow._height/_height; float u = (float)flow(X,Y,0,0)*fact/vmax, v = (float)flow(X,Y,0,1)*fact/vmax; if (is_arrow) { const int xx = (int)(x + u), yy = (int)(y + v); if (colorfield) draw_arrow(x,y,xx,yy,color.get_vector_at(X,Y)._data,opacity,45,sampling/5.f,pattern); else draw_arrow(x,y,xx,yy,color._data,opacity,45,sampling/5.f,pattern); } else { if (colorfield) draw_line((int)(x - 0.5*u),(int)(y - 0.5*v),(int)(x + 0.5*u),(int)(y + 0.5*v), color.get_vector_at(X,Y)._data,opacity,pattern); else draw_line((int)(x - 0.5*u),(int)(y - 0.5*v),(int)(x + 0.5*u),(int)(y + 0.5*v), color._data,opacity,pattern); } } return *this; } //! Draw a labeled horizontal axis. /** \param values_x Values along the horizontal axis. \param y Y-coordinate of the horizontal axis in the image instance. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \param pattern Drawing pattern. \param font_height Height of the labels (exact match for 13,23,53,103, interpolated otherwise). \param allow_zero Enable/disable the drawing of label '0' if found. **/ template<typename t, typename tc> CImg<T>& draw_axis(const CImg<t>& values_x, const int y, const tc *const color, const float opacity=1, const unsigned int pattern=~0U, const unsigned int font_height=13, const bool allow_zero=true, const float round_x=0) { if (is_empty()) return *this; const int yt = (y + 3 + font_height)<_height?y + 3:y - 2 - (int)font_height; const int siz = (int)values_x.size() - 1; CImg<charT> txt(32); CImg<T> a_label; if (siz<=0) { // Degenerated case draw_line(0,y,_width - 1,y,color,opacity,pattern); if (!siz) { cimg_snprintf(txt,txt._width,"%g",round_x?cimg::round((double)*values_x,round_x):(double)*values_x); a_label.assign().draw_text(0,0,txt,color,(tc*)0,opacity,font_height); const int _xt = (width() - a_label.width())/2, xt = _xt<3?3:_xt + a_label.width()>=width() - 2?width() - 3 - a_label.width():_xt; draw_point(width()/2,y - 1,color,opacity).draw_point(width()/2,y + 1,color,opacity); if (allow_zero || *txt!='0' || txt[1]!=0) draw_text(xt,yt,txt,color,(tc*)0,opacity,font_height); } } else { // Regular case if (values_x[0]<values_x[siz]) draw_arrow(0,y,_width - 1,y,color,opacity,30,5,pattern); else draw_arrow(_width - 1,y,0,y,color,opacity,30,5,pattern); cimg_foroff(values_x,x) { cimg_snprintf(txt,txt._width,"%g",round_x?cimg::round((double)values_x(x),round_x):(double)values_x(x)); a_label.assign().draw_text(0,0,txt,color,(tc*)0,opacity,font_height); const int xi = (int)(x*(_width - 1)/siz), _xt = xi - a_label.width()/2, xt = _xt<3?3:_xt + a_label.width()>=width() - 2?width() - 3 - a_label.width():_xt; draw_point(xi,y - 1,color,opacity).draw_point(xi,y + 1,color,opacity); if (allow_zero || *txt!='0' || txt[1]!=0) draw_text(xt,yt,txt,color,(tc*)0,opacity,font_height); } } return *this; } //! Draw a labeled vertical axis. /** \param x X-coordinate of the vertical axis in the image instance. \param values_y Values along the Y-axis. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \param pattern Drawing pattern. \param font_height Height of the labels (exact match for 13,23,53,103, interpolated otherwise). \param allow_zero Enable/disable the drawing of label '0' if found. **/ template<typename t, typename tc> CImg<T>& draw_axis(const int x, const CImg<t>& values_y, const tc *const color, const float opacity=1, const unsigned int pattern=~0U, const unsigned int font_height=13, const bool allow_zero=true, const float round_y=0) { if (is_empty()) return *this; int siz = (int)values_y.size() - 1; CImg<charT> txt(32); CImg<T> a_label; if (siz<=0) { // Degenerated case draw_line(x,0,x,_height - 1,color,opacity,pattern); if (!siz) { cimg_snprintf(txt,txt._width,"%g",round_y?cimg::round((double)*values_y,round_y):(double)*values_y); a_label.assign().draw_text(0,0,txt,color,(tc*)0,opacity,font_height); const int _yt = (height() - a_label.height())/2, yt = _yt<0?0:_yt + a_label.height()>=height()?height() - 1 - a_label.height():_yt, _xt = x - 2 - a_label.width(), xt = _xt>=0?_xt:x + 3; draw_point(x - 1,height()/2,color,opacity).draw_point(x + 1,height()/2,color,opacity); if (allow_zero || *txt!='0' || txt[1]!=0) draw_text(xt,yt,txt,color,(tc*)0,opacity,font_height); } } else { // Regular case if (values_y[0]<values_y[siz]) draw_arrow(x,0,x,_height - 1,color,opacity,30,5,pattern); else draw_arrow(x,_height - 1,x,0,color,opacity,30,5,pattern); cimg_foroff(values_y,y) { cimg_snprintf(txt,txt._width,"%g",round_y?cimg::round((double)values_y(y),round_y):(double)values_y(y)); a_label.assign().draw_text(0,0,txt,color,(tc*)0,opacity,font_height); const int yi = (int)(y*(_height - 1)/siz), _yt = yi - a_label.height()/2, yt = _yt<0?0:_yt + a_label.height()>=height()?height() - 1 - a_label.height():_yt, _xt = x - 2 - a_label.width(), xt = _xt>=0?_xt:x + 3; draw_point(x - 1,yi,color,opacity).draw_point(x + 1,yi,color,opacity); if (allow_zero || *txt!='0' || txt[1]!=0) draw_text(xt,yt,txt,color,(tc*)0,opacity,font_height); } } return *this; } //! Draw labeled horizontal and vertical axes. /** \param values_x Values along the X-axis. \param values_y Values along the Y-axis. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \param pattern_x Drawing pattern for the X-axis. \param pattern_y Drawing pattern for the Y-axis. \param font_height Height of the labels (exact match for 13,23,53,103, interpolated otherwise). \param allow_zero Enable/disable the drawing of label '0' if found. **/ template<typename tx, typename ty, typename tc> CImg<T>& draw_axes(const CImg<tx>& values_x, const CImg<ty>& values_y, const tc *const color, const float opacity=1, const unsigned int pattern_x=~0U, const unsigned int pattern_y=~0U, const unsigned int font_height=13, const bool allow_zero=true, const float round_x=0, const float round_y=0) { if (is_empty()) return *this; const CImg<tx> nvalues_x(values_x._data,values_x.size(),1,1,1,true); const int sizx = (int)values_x.size() - 1, wm1 = width() - 1; if (sizx>=0) { float ox = (float)*nvalues_x; for (unsigned int x = sizx?1U:0U; x<_width; ++x) { const float nx = (float)nvalues_x._linear_atX((float)x*sizx/wm1); if (nx*ox<=0) { draw_axis(nx==0?x:x - 1,values_y,color,opacity,pattern_y,font_height,allow_zero,round_y); break; } ox = nx; } } const CImg<ty> nvalues_y(values_y._data,values_y.size(),1,1,1,true); const int sizy = (int)values_y.size() - 1, hm1 = height() - 1; if (sizy>0) { float oy = (float)nvalues_y[0]; for (unsigned int y = sizy?1U:0U; y<_height; ++y) { const float ny = (float)nvalues_y._linear_atX((float)y*sizy/hm1); if (ny*oy<=0) { draw_axis(values_x,ny==0?y:y - 1,color,opacity,pattern_x,font_height,allow_zero,round_x); break; } oy = ny; } } return *this; } //! Draw labeled horizontal and vertical axes \overloading. template<typename tc> CImg<T>& draw_axes(const float x0, const float x1, const float y0, const float y1, const tc *const color, const float opacity=1, const int subdivisionx=-60, const int subdivisiony=-60, const float precisionx=0, const float precisiony=0, const unsigned int pattern_x=~0U, const unsigned int pattern_y=~0U, const unsigned int font_height=13) { if (is_empty()) return *this; const bool allow_zero = (x0*x1>0) || (y0*y1>0); const float dx = cimg::abs(x1 - x0), dy = cimg::abs(y1 - y0), px = dx<=0?1:precisionx==0?(float)std::pow(10.,(int)std::log10(dx) - 2.):precisionx, py = dy<=0?1:precisiony==0?(float)std::pow(10.,(int)std::log10(dy) - 2.):precisiony; if (x0!=x1 && y0!=y1) draw_axes(CImg<floatT>::sequence(subdivisionx>0?subdivisionx:1-width()/subdivisionx,x0,x1), CImg<floatT>::sequence(subdivisiony>0?subdivisiony:1-height()/subdivisiony,y0,y1), color,opacity,pattern_x,pattern_y,font_height,allow_zero,px,py); else if (x0==x1 && y0!=y1) draw_axis((int)x0,CImg<floatT>::sequence(subdivisiony>0?subdivisiony:1-height()/subdivisiony,y0,y1), color,opacity,pattern_y,font_height,py); else if (x0!=x1 && y0==y1) draw_axis(CImg<floatT>::sequence(subdivisionx>0?subdivisionx:1-width()/subdivisionx,x0,x1),(int)y0, color,opacity,pattern_x,font_height,px); return *this; } //! Draw 2D grid. /** \param values_x X-coordinates of the vertical lines. \param values_y Y-coordinates of the horizontal lines. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \param pattern_x Drawing pattern for vertical lines. \param pattern_y Drawing pattern for horizontal lines. **/ template<typename tx, typename ty, typename tc> CImg<T>& draw_grid(const CImg<tx>& values_x, const CImg<ty>& values_y, const tc *const color, const float opacity=1, const unsigned int pattern_x=~0U, const unsigned int pattern_y=~0U) { if (is_empty()) return *this; if (values_x) cimg_foroff(values_x,x) { const int xi = (int)values_x[x]; if (xi>=0 && xi<width()) draw_line(xi,0,xi,_height - 1,color,opacity,pattern_x); } if (values_y) cimg_foroff(values_y,y) { const int yi = (int)values_y[y]; if (yi>=0 && yi<height()) draw_line(0,yi,_width - 1,yi,color,opacity,pattern_y); } return *this; } //! Draw 2D grid \simplification. template<typename tc> CImg<T>& draw_grid(const float delta_x, const float delta_y, const float offsetx, const float offsety, const bool invertx, const bool inverty, const tc *const color, const float opacity=1, const unsigned int pattern_x=~0U, const unsigned int pattern_y=~0U) { if (is_empty()) return *this; CImg<uintT> seqx, seqy; if (delta_x!=0) { const float dx = delta_x>0?delta_x:_width*-delta_x/100; const unsigned int nx = (unsigned int)(_width/dx); seqx = CImg<uintT>::sequence(1 + nx,0,(unsigned int)(dx*nx)); if (offsetx) cimg_foroff(seqx,x) seqx(x) = (unsigned int)cimg::mod(seqx(x) + offsetx,(float)_width); if (invertx) cimg_foroff(seqx,x) seqx(x) = _width - 1 - seqx(x); } if (delta_y!=0) { const float dy = delta_y>0?delta_y:_height*-delta_y/100; const unsigned int ny = (unsigned int)(_height/dy); seqy = CImg<uintT>::sequence(1 + ny,0,(unsigned int)(dy*ny)); if (offsety) cimg_foroff(seqy,y) seqy(y) = (unsigned int)cimg::mod(seqy(y) + offsety,(float)_height); if (inverty) cimg_foroff(seqy,y) seqy(y) = _height - 1 - seqy(y); } return draw_grid(seqx,seqy,color,opacity,pattern_x,pattern_y); } //! Draw 1D graph. /** \param data Image containing the graph values I = f(x). \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \param plot_type Define the type of the plot: - 0 = No plot. - 1 = Plot using segments. - 2 = Plot using cubic splines. - 3 = Plot with bars. \param vertex_type Define the type of points: - 0 = No points. - 1 = Point. - 2 = Straight cross. - 3 = Diagonal cross. - 4 = Filled circle. - 5 = Outlined circle. - 6 = Square. - 7 = Diamond. \param ymin Lower bound of the y-range. \param ymax Upper bound of the y-range. \param pattern Drawing pattern. \note - if \c ymin==ymax==0, the y-range is computed automatically from the input samples. **/ template<typename t, typename tc> CImg<T>& draw_graph(const CImg<t>& data, const tc *const color, const float opacity=1, const unsigned int plot_type=1, const int vertex_type=1, const double ymin=0, const double ymax=0, const unsigned int pattern=~0U) { if (is_empty() || _height<=1) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_graph(): Specified color is (null).", cimg_instance); // Create shaded colors for displaying bar plots. CImg<tc> color1, color2; if (plot_type==3) { color1.assign(_spectrum); color2.assign(_spectrum); cimg_forC(*this,c) { color1[c] = (tc)std::min((float)cimg::type<tc>::max(),(float)color[c]*1.2f); color2[c] = (tc)(color[c]*0.4f); } } // Compute min/max and normalization factors. const ulongT siz = data.size(), _siz1 = siz - (plot_type!=3), siz1 = _siz1?_siz1:1; const unsigned int _width1 = _width - (plot_type!=3), width1 = _width1?_width1:1; double m = ymin, M = ymax; if (ymin==ymax) m = (double)data.max_min(M); if (m==M) { --m; ++M; } const float ca = (float)(M-m)/(_height - 1); bool init_hatch = true; // Draw graph edges switch (plot_type%4) { case 1 : { // Segments int oX = 0, oY = (int)((data[0] - m)/ca); if (siz==1) { const int Y = (int)((*data - m)/ca); draw_line(0,Y,width() - 1,Y,color,opacity,pattern); } else { const float fx = (float)_width/siz1; for (ulongT off = 1; off<siz; ++off) { const int X = (int)(off*fx) - 1, Y = (int)((data[off]-m)/ca); draw_line(oX,oY,X,Y,color,opacity,pattern,init_hatch); oX = X; oY = Y; init_hatch = false; } } } break; case 2 : { // Spline const CImg<t> ndata(data._data,siz,1,1,1,true); int oY = (int)((data[0] - m)/ca); cimg_forX(*this,x) { const int Y = (int)((ndata._cubic_atX((float)x*siz1/width1)-m)/ca); if (x>0) draw_line(x,oY,x + 1,Y,color,opacity,pattern,init_hatch); init_hatch = false; oY = Y; } } break; case 3 : { // Bars const int Y0 = (int)(-m/ca); const float fx = (float)_width/siz1; int oX = 0; cimg_foroff(data,off) { const int X = (int)((off + 1)*fx) - 1, Y = (int)((data[off] - m)/ca); draw_rectangle(oX,Y0,X,Y,color,opacity). draw_line(oX,Y,oX,Y0,color2.data(),opacity). draw_line(oX,Y0,X,Y0,Y<=Y0?color2.data():color1.data(),opacity). draw_line(X,Y,X,Y0,color1.data(),opacity). draw_line(oX,Y,X,Y,Y<=Y0?color1.data():color2.data(),opacity); oX = X + 1; } } break; default : break; // No edges } // Draw graph points const unsigned int wb2 = plot_type==3?_width1/(2*siz):0; const float fx = (float)_width1/siz1; switch (vertex_type%8) { case 1 : { // Point cimg_foroff(data,off) { const int X = (int)(off*fx + wb2), Y = (int)((data[off]-m)/ca); draw_point(X,Y,color,opacity); } } break; case 2 : { // Straight Cross cimg_foroff(data,off) { const int X = (int)(off*fx + wb2), Y = (int)((data[off]-m)/ca); draw_line(X - 3,Y,X + 3,Y,color,opacity).draw_line(X,Y - 3,X,Y + 3,color,opacity); } } break; case 3 : { // Diagonal Cross cimg_foroff(data,off) { const int X = (int)(off*fx + wb2), Y = (int)((data[off]-m)/ca); draw_line(X - 3,Y - 3,X + 3,Y + 3,color,opacity).draw_line(X - 3,Y + 3,X + 3,Y - 3,color,opacity); } } break; case 4 : { // Filled Circle cimg_foroff(data,off) { const int X = (int)(off*fx + wb2), Y = (int)((data[off]-m)/ca); draw_circle(X,Y,3,color,opacity); } } break; case 5 : { // Outlined circle cimg_foroff(data,off) { const int X = (int)(off*fx + wb2), Y = (int)((data[off]-m)/ca); draw_circle(X,Y,3,color,opacity,~0U); } } break; case 6 : { // Square cimg_foroff(data,off) { const int X = (int)(off*fx + wb2), Y = (int)((data[off]-m)/ca); draw_rectangle(X - 3,Y - 3,X + 3,Y + 3,color,opacity,~0U); } } break; case 7 : { // Diamond cimg_foroff(data,off) { const int X = (int)(off*fx + wb2), Y = (int)((data[off]-m)/ca); draw_line(X,Y - 4,X + 4,Y,color,opacity). draw_line(X + 4,Y,X,Y + 4,color,opacity). draw_line(X,Y + 4,X - 4,Y,color,opacity). draw_line(X - 4,Y,X,Y - 4,color,opacity); } } break; default : break; // No points } return *this; } bool _draw_fill(const int x, const int y, const int z, const CImg<T>& ref, const float tolerance2) const { const T *ptr1 = data(x,y,z), *ptr2 = ref._data; const unsigned long off = _width*_height*_depth; float diff = 0; cimg_forC(*this,c) { diff += cimg::sqr(*ptr1 - *(ptr2++)); ptr1+=off; } return diff<=tolerance2; } //! Draw filled 3D region with the flood fill algorithm. /** \param x0 X-coordinate of the starting point of the region to fill. \param y0 Y-coordinate of the starting point of the region to fill. \param z0 Z-coordinate of the starting point of the region to fill. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param[out] region Image that will contain the mask of the filled region mask, as an output. \param tolerance Tolerance concerning neighborhood values. \param opacity Opacity of the drawing. \param is_high_connectivity Tells if 8-connexity must be used. \return \c region is initialized with the binary mask of the filled region. **/ template<typename tc, typename t> CImg<T>& draw_fill(const int x0, const int y0, const int z0, const tc *const color, const float opacity, CImg<t> &region, const float tolerance = 0, const bool is_high_connectivity = false) { #define _draw_fill_push(x,y,z) if (N>=stack._width) stack.resize(2*N + 1,1,1,3,0); \ stack[N] = x; stack(N,1) = y; stack(N++,2) = z #define _draw_fill_pop(x,y,z) x = stack[--N]; y = stack(N,1); z = stack(N,2) #define _draw_fill_is_inside(x,y,z) !_region(x,y,z) && _draw_fill(x,y,z,ref,tolerance2) if (!containsXYZC(x0,y0,z0,0)) return *this; const float nopacity = cimg::abs((float)opacity), copacity = 1 - std::max((float)opacity,0.f); const float tolerance2 = cimg::sqr(tolerance); const CImg<T> ref = get_vector_at(x0,y0,z0); CImg<uintT> stack(256,1,1,3); CImg<ucharT> _region(_width,_height,_depth,1,0); unsigned int N = 0; int x, y, z; _draw_fill_push(x0,y0,z0); while (N>0) { _draw_fill_pop(x,y,z); if (!_region(x,y,z)) { const int yp = y - 1, yn = y + 1, zp = z - 1, zn = z + 1; int xl = x, xr = x; // Using these booleans reduces the number of pushes drastically. bool is_yp = false, is_yn = false, is_zp = false, is_zn = false; for (int step = -1; step<2; step+=2) { while (x>=0 && x<width() && _draw_fill_is_inside(x,y,z)) { if (yp>=0 && _draw_fill_is_inside(x,yp,z)) { if (!is_yp) { _draw_fill_push(x,yp,z); is_yp = true; } } else is_yp = false; if (yn<height() && _draw_fill_is_inside(x,yn,z)) { if (!is_yn) { _draw_fill_push(x,yn,z); is_yn = true; } } else is_yn = false; if (depth()>1) { if (zp>=0 && _draw_fill_is_inside(x,y,zp)) { if (!is_zp) { _draw_fill_push(x,y,zp); is_zp = true; } } else is_zp = false; if (zn<depth() && _draw_fill_is_inside(x,y,zn)) { if (!is_zn) { _draw_fill_push(x,y,zn); is_zn = true; } } else is_zn = false; } if (is_high_connectivity) { const int xp = x - 1, xn = x + 1; if (yp>=0 && !is_yp) { if (xp>=0 && _draw_fill_is_inside(xp,yp,z)) { _draw_fill_push(xp,yp,z); if (step<0) is_yp = true; } if (xn<width() && _draw_fill_is_inside(xn,yp,z)) { _draw_fill_push(xn,yp,z); if (step>0) is_yp = true; } } if (yn<height() && !is_yn) { if (xp>=0 && _draw_fill_is_inside(xp,yn,z)) { _draw_fill_push(xp,yn,z); if (step<0) is_yn = true; } if (xn<width() && _draw_fill_is_inside(xn,yn,z)) { _draw_fill_push(xn,yn,z); if (step>0) is_yn = true; } } if (depth()>1) { if (zp>=0 && !is_zp) { if (xp>=0 && _draw_fill_is_inside(xp,y,zp)) { _draw_fill_push(xp,y,zp); if (step<0) is_zp = true; } if (xn<width() && _draw_fill_is_inside(xn,y,zp)) { _draw_fill_push(xn,y,zp); if (step>0) is_zp = true; } if (yp>=0 && !is_yp) { if (_draw_fill_is_inside(x,yp,zp)) { _draw_fill_push(x,yp,zp); } if (xp>=0 && _draw_fill_is_inside(xp,yp,zp)) { _draw_fill_push(xp,yp,zp); } if (xn<width() && _draw_fill_is_inside(xn,yp,zp)) { _draw_fill_push(xn,yp,zp); } } if (yn<height() && !is_yn) { if (_draw_fill_is_inside(x,yn,zp)) { _draw_fill_push(x,yn,zp); } if (xp>=0 && _draw_fill_is_inside(xp,yn,zp)) { _draw_fill_push(xp,yn,zp); } if (xn<width() && _draw_fill_is_inside(xn,yn,zp)) { _draw_fill_push(xn,yn,zp); } } } if (zn<depth() && !is_zn) { if (xp>=0 && _draw_fill_is_inside(xp,y,zn)) { _draw_fill_push(xp,y,zn); if (step<0) is_zn = true; } if (xn<width() && _draw_fill_is_inside(xn,y,zn)) { _draw_fill_push(xn,y,zn); if (step>0) is_zn = true; } if (yp>=0 && !is_yp) { if (_draw_fill_is_inside(x,yp,zn)) { _draw_fill_push(x,yp,zn); } if (xp>=0 && _draw_fill_is_inside(xp,yp,zn)) { _draw_fill_push(xp,yp,zn); } if (xn<width() && _draw_fill_is_inside(xn,yp,zn)) { _draw_fill_push(xn,yp,zn); } } if (yn<height() && !is_yn) { if (_draw_fill_is_inside(x,yn,zn)) { _draw_fill_push(x,yn,zn); } if (xp>=0 && _draw_fill_is_inside(xp,yn,zn)) { _draw_fill_push(xp,yn,zn); } if (xn<width() && _draw_fill_is_inside(xn,yn,zn)) { _draw_fill_push(xn,yn,zn); } } } } } x+=step; } if (step<0) { xl = ++x; x = xr + 1; is_yp = is_yn = is_zp = is_zn = false; } else xr = --x; } std::memset(_region.data(xl,y,z),1,xr - xl + 1); if (opacity==1) { if (sizeof(T)==1) { const int dx = xr - xl + 1; cimg_forC(*this,c) std::memset(data(xl,y,z,c),(int)color[c],dx); } else cimg_forC(*this,c) { const T val = (T)color[c]; T *ptri = data(xl,y,z,c); for (int k = xl; k<=xr; ++k) *(ptri++) = val; } } else cimg_forC(*this,c) { const T val = (T)(color[c]*nopacity); T *ptri = data(xl,y,z,c); for (int k = xl; k<=xr; ++k) { *ptri = (T)(val + *ptri*copacity); ++ptri; } } } } _region.move_to(region); return *this; } //! Draw filled 3D region with the flood fill algorithm \simplification. template<typename tc> CImg<T>& draw_fill(const int x0, const int y0, const int z0, const tc *const color, const float opacity=1, const float tolerance=0, const bool is_high_connexity=false) { CImg<ucharT> tmp; return draw_fill(x0,y0,z0,color,opacity,tmp,tolerance,is_high_connexity); } //! Draw filled 2D region with the flood fill algorithm \simplification. template<typename tc> CImg<T>& draw_fill(const int x0, const int y0, const tc *const color, const float opacity=1, const float tolerance=0, const bool is_high_connexity=false) { CImg<ucharT> tmp; return draw_fill(x0,y0,0,color,opacity,tmp,tolerance,is_high_connexity); } //! Draw a random plasma texture. /** \param alpha Alpha-parameter. \param beta Beta-parameter. \param scale Scale-parameter. \note Use the mid-point algorithm to render. **/ CImg<T>& draw_plasma(const float alpha=1, const float beta=0, const unsigned int scale=8) { if (is_empty()) return *this; const int w = width(), h = height(); const Tfloat m = (Tfloat)cimg::type<T>::min(), M = (Tfloat)cimg::type<T>::max(); ulongT rng = (cimg::_rand(),cimg::rng()); cimg_forZC(*this,z,c) { CImg<T> ref = get_shared_slice(z,c); for (int delta = 1<<std::min(scale,31U); delta>1; delta>>=1) { const int delta2 = delta>>1; const float r = alpha*delta + beta; // Square step. for (int y0 = 0; y0<h; y0+=delta) for (int x0 = 0; x0<w; x0+=delta) { const int x1 = (x0 + delta)%w, y1 = (y0 + delta)%h, xc = (x0 + delta2)%w, yc = (y0 + delta2)%h; const Tfloat val = (Tfloat)(0.25f*(ref(x0,y0) + ref(x0,y1) + ref(x0,y1) + ref(x1,y1)) + r*cimg::rand(-1,1,&rng)); ref(xc,yc) = (T)(val<m?m:val>M?M:val); } // Diamond steps. for (int y = -delta2; y<h; y+=delta) for (int x0=0; x0<w; x0+=delta) { const int y0 = cimg::mod(y,h), x1 = (x0 + delta)%w, y1 = (y + delta)%h, xc = (x0 + delta2)%w, yc = (y + delta2)%h; const Tfloat val = (Tfloat)(0.25f*(ref(xc,y0) + ref(x0,yc) + ref(xc,y1) + ref(x1,yc)) + r*cimg::rand(-1,1,&rng)); ref(xc,yc) = (T)(val<m?m:val>M?M:val); } for (int y0 = 0; y0<h; y0+=delta) for (int x = -delta2; x<w; x+=delta) { const int x0 = cimg::mod(x,w), x1 = (x + delta)%w, y1 = (y0 + delta)%h, xc = (x + delta2)%w, yc = (y0 + delta2)%h; const Tfloat val = (Tfloat)(0.25f*(ref(xc,y0) + ref(x0,yc) + ref(xc,y1) + ref(x1,yc)) + r*cimg::rand(-1,1,&rng)); ref(xc,yc) = (T)(val<m?m:val>M?M:val); } for (int y = -delta2; y<h; y+=delta) for (int x = -delta2; x<w; x+=delta) { const int x0 = cimg::mod(x,w), y0 = cimg::mod(y,h), x1 = (x + delta)%w, y1 = (y + delta)%h, xc = (x + delta2)%w, yc = (y + delta2)%h; const Tfloat val = (Tfloat)(0.25f*(ref(xc,y0) + ref(x0,yc) + ref(xc,y1) + ref(x1,yc)) + r*cimg::rand(-1,1,&rng)); ref(xc,yc) = (T)(val<m?m:val>M?M:val); } } } cimg::srand(rng); return *this; } //! Draw a quadratic Mandelbrot or Julia 2D fractal. /** \param x0 X-coordinate of the upper-left pixel. \param y0 Y-coordinate of the upper-left pixel. \param x1 X-coordinate of the lower-right pixel. \param y1 Y-coordinate of the lower-right pixel. \param colormap Colormap. \param opacity Drawing opacity. \param z0r Real part of the upper-left fractal vertex. \param z0i Imaginary part of the upper-left fractal vertex. \param z1r Real part of the lower-right fractal vertex. \param z1i Imaginary part of the lower-right fractal vertex. \param iteration_max Maximum number of iterations for each estimated point. \param is_normalized_iteration Tells if iterations are normalized. \param is_julia_set Tells if the Mandelbrot or Julia set is rendered. \param param_r Real part of the Julia set parameter. \param param_i Imaginary part of the Julia set parameter. \note Fractal rendering is done by the Escape Time Algorithm. **/ template<typename tc> CImg<T>& draw_mandelbrot(const int x0, const int y0, const int x1, const int y1, const CImg<tc>& colormap, const float opacity=1, const double z0r=-2, const double z0i=-2, const double z1r=2, const double z1i=2, const unsigned int iteration_max=255, const bool is_normalized_iteration=false, const bool is_julia_set=false, const double param_r=0, const double param_i=0) { if (is_empty()) return *this; CImg<tc> palette; if (colormap) palette.assign(colormap._data,colormap.size()/colormap._spectrum,1,1,colormap._spectrum,true); if (palette && palette._spectrum!=_spectrum) throw CImgArgumentException(_cimg_instance "draw_mandelbrot(): Instance and specified colormap (%u,%u,%u,%u,%p) have " "incompatible dimensions.", cimg_instance, colormap._width,colormap._height,colormap._depth,colormap._spectrum,colormap._data); const float nopacity = cimg::abs(opacity), copacity = 1 - std::max(opacity,0.f), ln2 = (float)std::log(2.); const int _x0 = cimg::cut(x0,0,width() - 1), _y0 = cimg::cut(y0,0,height() - 1), _x1 = cimg::cut(x1,0,width() - 1), _y1 = cimg::cut(y1,0,height() - 1); cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if((1 + _x1 - _x0)*(1 + _y1 - _y0)>=(cimg_openmp_sizefactor)*2048)) for (int q = _y0; q<=_y1; ++q) for (int p = _x0; p<=_x1; ++p) { unsigned int iteration = 0; const double x = z0r + p*(z1r-z0r)/_width, y = z0i + q*(z1i-z0i)/_height; double zr, zi, cr, ci; if (is_julia_set) { zr = x; zi = y; cr = param_r; ci = param_i; } else { zr = param_r; zi = param_i; cr = x; ci = y; } for (iteration=1; zr*zr + zi*zi<=4 && iteration<=iteration_max; ++iteration) { const double temp = zr*zr - zi*zi + cr; zi = 2*zr*zi + ci; zr = temp; } if (iteration>iteration_max) { if (palette) { if (opacity>=1) cimg_forC(*this,c) (*this)(p,q,0,c) = (T)palette(0,c); else cimg_forC(*this,c) (*this)(p,q,0,c) = (T)(palette(0,c)*nopacity + (*this)(p,q,0,c)*copacity); } else { if (opacity>=1) cimg_forC(*this,c) (*this)(p,q,0,c) = (T)0; else cimg_forC(*this,c) (*this)(p,q,0,c) = (T)((*this)(p,q,0,c)*copacity); } } else if (is_normalized_iteration) { const float normz = (float)cimg::abs(zr*zr + zi*zi), niteration = (float)(iteration + 1 - std::log(std::log(normz))/ln2); if (palette) { if (opacity>=1) cimg_forC(*this,c) (*this)(p,q,0,c) = (T)palette._linear_atX(niteration,c); else cimg_forC(*this,c) (*this)(p,q,0,c) = (T)(palette._linear_atX(niteration,c)*nopacity + (*this)(p,q,0,c)*copacity); } else { if (opacity>=1) cimg_forC(*this,c) (*this)(p,q,0,c) = (T)niteration; else cimg_forC(*this,c) (*this)(p,q,0,c) = (T)(niteration*nopacity + (*this)(p,q,0,c)*copacity); } } else { if (palette) { if (opacity>=1) cimg_forC(*this,c) (*this)(p,q,0,c) = (T)palette._atX(iteration,c); else cimg_forC(*this,c) (*this)(p,q,0,c) = (T)(palette(iteration,c)*nopacity + (*this)(p,q,0,c)*copacity); } else { if (opacity>=1) cimg_forC(*this,c) (*this)(p,q,0,c) = (T)iteration; else cimg_forC(*this,c) (*this)(p,q,0,c) = (T)(iteration*nopacity + (*this)(p,q,0,c)*copacity); } } } return *this; } //! Draw a quadratic Mandelbrot or Julia 2D fractal \overloading. template<typename tc> CImg<T>& draw_mandelbrot(const CImg<tc>& colormap, const float opacity=1, const double z0r=-2, const double z0i=-2, const double z1r=2, const double z1i=2, const unsigned int iteration_max=255, const bool is_normalized_iteration=false, const bool is_julia_set=false, const double param_r=0, const double param_i=0) { return draw_mandelbrot(0,0,_width - 1,_height - 1,colormap,opacity, z0r,z0i,z1r,z1i,iteration_max,is_normalized_iteration,is_julia_set,param_r,param_i); } //! Draw a 1D gaussian function. /** \param xc X-coordinate of the gaussian center. \param sigma Standard variation of the gaussian distribution. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. **/ template<typename tc> CImg<T>& draw_gaussian(const float xc, const float sigma, const tc *const color, const float opacity=1) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_gaussian(): Specified color is (null).", cimg_instance); const float sigma2 = 2*sigma*sigma, nopacity = cimg::abs(opacity), copacity = 1 - std::max(opacity,0.f); const ulongT whd = (ulongT)_width*_height*_depth; const tc *col = color; cimg_forX(*this,x) { const float dx = (x - xc), val = (float)std::exp(-dx*dx/sigma2); T *ptrd = data(x,0,0,0); if (opacity>=1) cimg_forC(*this,c) { *ptrd = (T)(val*(*col++)); ptrd+=whd; } else cimg_forC(*this,c) { *ptrd = (T)(nopacity*val*(*col++) + *ptrd*copacity); ptrd+=whd; } col-=_spectrum; } return *this; } //! Draw a 2D gaussian function. /** \param xc X-coordinate of the gaussian center. \param yc Y-coordinate of the gaussian center. \param tensor Covariance matrix (must be 2x2). \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. **/ template<typename t, typename tc> CImg<T>& draw_gaussian(const float xc, const float yc, const CImg<t>& tensor, const tc *const color, const float opacity=1) { if (is_empty()) return *this; if (tensor._width!=2 || tensor._height!=2 || tensor._depth!=1 || tensor._spectrum!=1) throw CImgArgumentException(_cimg_instance "draw_gaussian(): Specified tensor (%u,%u,%u,%u,%p) is not a 2x2 matrix.", cimg_instance, tensor._width,tensor._height,tensor._depth,tensor._spectrum,tensor._data); if (!color) throw CImgArgumentException(_cimg_instance "draw_gaussian(): Specified color is (null).", cimg_instance); typedef typename CImg<t>::Tfloat tfloat; const CImg<tfloat> invT = tensor.get_invert(), invT2 = (invT*invT)/=-2.; const tfloat a = invT2(0,0), b = 2*invT2(1,0), c = invT2(1,1); const float nopacity = cimg::abs(opacity), copacity = 1 - std::max(opacity,0.f); const ulongT whd = (ulongT)_width*_height*_depth; const tc *col = color; float dy = -yc; cimg_forY(*this,y) { float dx = -xc; cimg_forX(*this,x) { const float val = (float)std::exp(a*dx*dx + b*dx*dy + c*dy*dy); T *ptrd = data(x,y,0,0); if (opacity>=1) cimg_forC(*this,k) { *ptrd = (T)(val*(*col++)); ptrd+=whd; } else cimg_forC(*this,k) { *ptrd = (T)(nopacity*val*(*col++) + *ptrd*copacity); ptrd+=whd; } col-=_spectrum; ++dx; } ++dy; } return *this; } //! Draw a 2D gaussian function \overloading. template<typename tc> CImg<T>& draw_gaussian(const int xc, const int yc, const float r1, const float r2, const float ru, const float rv, const tc *const color, const float opacity=1) { const double a = r1*ru*ru + r2*rv*rv, b = (r1-r2)*ru*rv, c = r1*rv*rv + r2*ru*ru; const CImg<Tfloat> tensor(2,2,1,1, a,b,b,c); return draw_gaussian(xc,yc,tensor,color,opacity); } //! Draw a 2D gaussian function \overloading. template<typename tc> CImg<T>& draw_gaussian(const float xc, const float yc, const float sigma, const tc *const color, const float opacity=1) { return draw_gaussian(xc,yc,CImg<floatT>::diagonal(sigma,sigma),color,opacity); } //! Draw a 3D gaussian function \overloading. template<typename t, typename tc> CImg<T>& draw_gaussian(const float xc, const float yc, const float zc, const CImg<t>& tensor, const tc *const color, const float opacity=1) { if (is_empty()) return *this; typedef typename CImg<t>::Tfloat tfloat; if (tensor._width!=3 || tensor._height!=3 || tensor._depth!=1 || tensor._spectrum!=1) throw CImgArgumentException(_cimg_instance "draw_gaussian(): Specified tensor (%u,%u,%u,%u,%p) is not a 3x3 matrix.", cimg_instance, tensor._width,tensor._height,tensor._depth,tensor._spectrum,tensor._data); const CImg<tfloat> invT = tensor.get_invert(), invT2 = (invT*invT)/=-2.; const tfloat a = invT2(0,0), b = 2*invT2(1,0), c = 2*invT2(2,0), d = invT2(1,1), e = 2*invT2(2,1), f = invT2(2,2); const float nopacity = cimg::abs(opacity), copacity = 1 - std::max(opacity,0.f); const ulongT whd = (ulongT)_width*_height*_depth; const tc *col = color; cimg_forXYZ(*this,x,y,z) { const float dx = (x - xc), dy = (y - yc), dz = (z - zc), val = (float)std::exp(a*dx*dx + b*dx*dy + c*dx*dz + d*dy*dy + e*dy*dz + f*dz*dz); T *ptrd = data(x,y,z,0); if (opacity>=1) cimg_forC(*this,k) { *ptrd = (T)(val*(*col++)); ptrd+=whd; } else cimg_forC(*this,k) { *ptrd = (T)(nopacity*val*(*col++) + *ptrd*copacity); ptrd+=whd; } col-=_spectrum; } return *this; } //! Draw a 3D gaussian function \overloading. template<typename tc> CImg<T>& draw_gaussian(const float xc, const float yc, const float zc, const float sigma, const tc *const color, const float opacity=1) { return draw_gaussian(xc,yc,zc,CImg<floatT>::diagonal(sigma,sigma,sigma),color,opacity); } //! Draw a 3D object. /** \param x0 X-coordinate of the 3D object position \param y0 Y-coordinate of the 3D object position \param z0 Z-coordinate of the 3D object position \param vertices Image Nx3 describing 3D point coordinates \param primitives List of P primitives \param colors List of P color (or textures) \param opacities Image or list of P opacities \param render_type d Render type (0=Points, 1=Lines, 2=Faces (no light), 3=Faces (flat), 4=Faces(Gouraud) \param is_double_sided Tells if object faces have two sides or are oriented. \param focale length of the focale (0 for parallel projection) \param lightx X-coordinate of the light \param lighty Y-coordinate of the light \param lightz Z-coordinate of the light \param specular_lightness Amount of specular light. \param specular_shininess Shininess of the object \param g_opacity Global opacity of the object. **/ template<typename tp, typename tf, typename tc, typename to> CImg<T>& draw_object3d(const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const CImg<to>& opacities, const unsigned int render_type=4, const bool is_double_sided=false, const float focale=700, const float lightx=0, const float lighty=0, const float lightz=-5e8, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const float g_opacity=1) { return draw_object3d(x0,y0,z0,vertices,primitives,colors,opacities,render_type, is_double_sided,focale,lightx,lighty,lightz, specular_lightness,specular_shininess,g_opacity,CImg<floatT>::empty()); } //! Draw a 3D object \simplification. template<typename tp, typename tf, typename tc, typename to, typename tz> CImg<T>& draw_object3d(const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const CImg<to>& opacities, const unsigned int render_type, const bool is_double_sided, const float focale, const float lightx, const float lighty, const float lightz, const float specular_lightness, const float specular_shininess, const float g_opacity, CImg<tz>& zbuffer) { return _draw_object3d(0,zbuffer,x0,y0,z0,vertices,primitives,colors,opacities, render_type,is_double_sided,focale,lightx,lighty,lightz, specular_lightness,specular_shininess,g_opacity,1); } #ifdef cimg_use_board template<typename tp, typename tf, typename tc, typename to> CImg<T>& draw_object3d(LibBoard::Board& board, const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const CImg<to>& opacities, const unsigned int render_type=4, const bool is_double_sided=false, const float focale=700, const float lightx=0, const float lighty=0, const float lightz=-5e8, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const float g_opacity=1) { return draw_object3d(board,x0,y0,z0,vertices,primitives,colors,opacities,render_type, is_double_sided,focale,lightx,lighty,lightz, specular_lightness,specular_shininess,g_opacity,CImg<floatT>::empty()); } template<typename tp, typename tf, typename tc, typename to, typename tz> CImg<T>& draw_object3d(LibBoard::Board& board, const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const CImg<to>& opacities, const unsigned int render_type, const bool is_double_sided, const float focale, const float lightx, const float lighty, const float lightz, const float specular_lightness, const float specular_shininess, const float g_opacity, CImg<tz>& zbuffer) { return _draw_object3d((void*)&board,zbuffer,x0,y0,z0,vertices,primitives,colors,opacities, render_type,is_double_sided,focale,lightx,lighty,lightz, specular_lightness,specular_shininess,g_opacity,1); } #endif //! Draw a 3D object \simplification. template<typename tp, typename tf, typename tc, typename to> CImg<T>& draw_object3d(const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const CImgList<to>& opacities, const unsigned int render_type=4, const bool is_double_sided=false, const float focale=700, const float lightx=0, const float lighty=0, const float lightz=-5e8, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const float g_opacity=1) { return draw_object3d(x0,y0,z0,vertices,primitives,colors,opacities,render_type, is_double_sided,focale,lightx,lighty,lightz, specular_lightness,specular_shininess,g_opacity,CImg<floatT>::empty()); } //! Draw a 3D object \simplification. template<typename tp, typename tf, typename tc, typename to, typename tz> CImg<T>& draw_object3d(const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const CImgList<to>& opacities, const unsigned int render_type, const bool is_double_sided, const float focale, const float lightx, const float lighty, const float lightz, const float specular_lightness, const float specular_shininess, const float g_opacity, CImg<tz>& zbuffer) { return _draw_object3d(0,zbuffer,x0,y0,z0,vertices,primitives,colors,opacities, render_type,is_double_sided,focale,lightx,lighty,lightz, specular_lightness,specular_shininess,g_opacity,1); } #ifdef cimg_use_board template<typename tp, typename tf, typename tc, typename to> CImg<T>& draw_object3d(LibBoard::Board& board, const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const CImgList<to>& opacities, const unsigned int render_type=4, const bool is_double_sided=false, const float focale=700, const float lightx=0, const float lighty=0, const float lightz=-5e8, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const float g_opacity=1) { return draw_object3d(board,x0,y0,z0,vertices,primitives,colors,opacities,render_type, is_double_sided,focale,lightx,lighty,lightz, specular_lightness,specular_shininess,g_opacity,CImg<floatT>::empty()); } template<typename tp, typename tf, typename tc, typename to, typename tz> CImg<T>& draw_object3d(LibBoard::Board& board, const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const CImgList<to>& opacities, const unsigned int render_type, const bool is_double_sided, const float focale, const float lightx, const float lighty, const float lightz, const float specular_lightness, const float specular_shininess, const float g_opacity, CImg<tz>& zbuffer) { return _draw_object3d((void*)&board,zbuffer,x0,y0,z0,vertices,primitives,colors,opacities, render_type,is_double_sided,focale,lightx,lighty,lightz, specular_lightness,specular_shininess,g_opacity,1); } #endif //! Draw a 3D object \simplification. template<typename tp, typename tf, typename tc> CImg<T>& draw_object3d(const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const unsigned int render_type=4, const bool is_double_sided=false, const float focale=700, const float lightx=0, const float lighty=0, const float lightz=-5e8, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const float g_opacity=1) { return draw_object3d(x0,y0,z0,vertices,primitives,colors,CImg<floatT>::const_empty(), render_type,is_double_sided,focale,lightx,lighty,lightz, specular_lightness,specular_shininess,g_opacity,CImg<floatT>::empty()); } //! Draw a 3D object \simplification. template<typename tp, typename tf, typename tc, typename tz> CImg<T>& draw_object3d(const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const unsigned int render_type, const bool is_double_sided, const float focale, const float lightx, const float lighty, const float lightz, const float specular_lightness, const float specular_shininess, const float g_opacity, CImg<tz>& zbuffer) { return draw_object3d(x0,y0,z0,vertices,primitives,colors,CImg<floatT>::const_empty(), render_type,is_double_sided,focale,lightx,lighty,lightz, specular_lightness,specular_shininess,g_opacity,zbuffer); } #ifdef cimg_use_board template<typename tp, typename tf, typename tc, typename to> CImg<T>& draw_object3d(LibBoard::Board& board, const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const unsigned int render_type=4, const bool is_double_sided=false, const float focale=700, const float lightx=0, const float lighty=0, const float lightz=-5e8, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const float g_opacity=1) { return draw_object3d(x0,y0,z0,vertices,primitives,colors,CImg<floatT>::const_empty(), render_type,is_double_sided,focale,lightx,lighty,lightz, specular_lightness,specular_shininess,g_opacity,CImg<floatT>::empty()); } template<typename tp, typename tf, typename tc, typename to, typename tz> CImg<T>& draw_object3d(LibBoard::Board& board, const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const unsigned int render_type, const bool is_double_sided, const float focale, const float lightx, const float lighty, const float lightz, const float specular_lightness, const float specular_shininess, const float g_opacity, CImg<tz>& zbuffer) { return draw_object3d(x0,y0,z0,vertices,primitives,colors,CImg<floatT>::const_empty(), render_type,is_double_sided,focale,lightx,lighty,lightz, specular_lightness,specular_shininess,g_opacity,zbuffer); } #endif template<typename t, typename to> static float __draw_object3d(const CImgList<t>& opacities, const unsigned int n_primitive, CImg<to>& opacity) { if (n_primitive>=opacities._width || opacities[n_primitive].is_empty()) { opacity.assign(); return 1; } if (opacities[n_primitive].size()==1) { opacity.assign(); return opacities(n_primitive,0); } opacity.assign(opacities[n_primitive],true); return 1.f; } template<typename t, typename to> static float __draw_object3d(const CImg<t>& opacities, const unsigned int n_primitive, CImg<to>& opacity) { opacity.assign(); return n_primitive>=opacities._width?1.f:(float)opacities[n_primitive]; } template<typename t> static float ___draw_object3d(const CImgList<t>& opacities, const unsigned int n_primitive) { return n_primitive<opacities._width && opacities[n_primitive].size()==1?(float)opacities(n_primitive,0):1.f; } template<typename t> static float ___draw_object3d(const CImg<t>& opacities, const unsigned int n_primitive) { return n_primitive<opacities._width?(float)opacities[n_primitive]:1.f; } template<typename tz, typename tp, typename tf, typename tc, typename to> CImg<T>& _draw_object3d(void *const pboard, CImg<tz>& zbuffer, const float X, const float Y, const float Z, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const to& opacities, const unsigned int render_type, const bool is_double_sided, const float focale, const float lightx, const float lighty, const float lightz, const float specular_lightness, const float specular_shininess, const float g_opacity, const float sprite_scale) { typedef typename cimg::superset2<tp,tz,float>::type tpfloat; typedef typename to::value_type _to; if (is_empty() || !vertices || !primitives) return *this; CImg<char> error_message(1024); if (!vertices.is_object3d(primitives,colors,opacities,false,error_message)) throw CImgArgumentException(_cimg_instance "draw_object3d(): Invalid specified 3D object (%u,%u) (%s).", cimg_instance,vertices._width,primitives._width,error_message.data()); #ifndef cimg_use_board if (pboard) return *this; #endif if (render_type==5) cimg::mutex(10); // Static variable used in this case, breaks thread-safety const float nspec = 1 - (specular_lightness<0.f?0.f:(specular_lightness>1.f?1.f:specular_lightness)), nspec2 = 1 + (specular_shininess<0.f?0.f:specular_shininess), nsl1 = (nspec2 - 1)/cimg::sqr(nspec - 1), nsl2 = 1 - 2*nsl1*nspec, nsl3 = nspec2 - nsl1 - nsl2; // Create light texture for phong-like rendering. CImg<floatT> light_texture; if (render_type==5) { if (colors._width>primitives._width) { static CImg<floatT> default_light_texture; static const tc *lptr = 0; static tc ref_values[64] = { 0 }; const CImg<tc>& img = colors.back(); bool is_same_texture = (lptr==img._data); if (is_same_texture) for (unsigned int r = 0, j = 0; j<8; ++j) for (unsigned int i = 0; i<8; ++i) if (ref_values[r++]!=img(i*img._width/9,j*img._height/9,0,(i + j)%img._spectrum)) { is_same_texture = false; break; } if (!is_same_texture || default_light_texture._spectrum<_spectrum) { (default_light_texture.assign(img,false)/=255).resize(-100,-100,1,_spectrum); lptr = colors.back().data(); for (unsigned int r = 0, j = 0; j<8; ++j) for (unsigned int i = 0; i<8; ++i) ref_values[r++] = img(i*img._width/9,j*img._height/9,0,(i + j)%img._spectrum); } light_texture.assign(default_light_texture,true); } else { static CImg<floatT> default_light_texture; static float olightx = 0, olighty = 0, olightz = 0, ospecular_shininess = 0; if (!default_light_texture || lightx!=olightx || lighty!=olighty || lightz!=olightz || specular_shininess!=ospecular_shininess || default_light_texture._spectrum<_spectrum) { default_light_texture.assign(512,512); const float dlx = lightx - X, dly = lighty - Y, dlz = lightz - Z, nl = cimg::hypot(dlx,dly,dlz), nlx = (default_light_texture._width - 1)/2*(1 + dlx/nl), nly = (default_light_texture._height - 1)/2*(1 + dly/nl), white[] = { 1 }; default_light_texture.draw_gaussian(nlx,nly,default_light_texture._width/3.f,white); cimg_forXY(default_light_texture,x,y) { const float factor = default_light_texture(x,y); if (factor>nspec) default_light_texture(x,y) = std::min(2.f,nsl1*factor*factor + nsl2*factor + nsl3); } default_light_texture.resize(-100,-100,1,_spectrum); olightx = lightx; olighty = lighty; olightz = lightz; ospecular_shininess = specular_shininess; } light_texture.assign(default_light_texture,true); } } // Compute 3D to 2D projection. CImg<tpfloat> projections(vertices._width,2); tpfloat parallzmin = cimg::type<tpfloat>::max(); const float absfocale = focale?cimg::abs(focale):0; if (absfocale) { cimg_pragma_openmp(parallel for cimg_openmp_if_size(projections.size(),4096)) cimg_forX(projections,l) { // Perspective projection const tpfloat x = (tpfloat)vertices(l,0), y = (tpfloat)vertices(l,1), z = (tpfloat)vertices(l,2); const tpfloat projectedz = z + Z + absfocale; projections(l,1) = Y + absfocale*y/projectedz; projections(l,0) = X + absfocale*x/projectedz; } } else { cimg_pragma_openmp(parallel for cimg_openmp_if_size(projections.size(),4096)) cimg_forX(projections,l) { // Parallel projection const tpfloat x = (tpfloat)vertices(l,0), y = (tpfloat)vertices(l,1), z = (tpfloat)vertices(l,2); if (z<parallzmin) parallzmin = z; projections(l,1) = Y + y; projections(l,0) = X + x; } } const float _focale = absfocale?absfocale:(1e5f-parallzmin); float zmax = 0; if (zbuffer) zmax = vertices.get_shared_row(2).max(); // Compute visible primitives. CImg<uintT> visibles(primitives._width,1,1,1,~0U); CImg<tpfloat> zrange(primitives._width); const tpfloat zmin = absfocale?(tpfloat)(1.5f - absfocale):cimg::type<tpfloat>::min(); bool is_forward = zbuffer?true:false; cimg_pragma_openmp(parallel for cimg_openmp_if_size(primitives.size(),4096)) cimglist_for(primitives,l) { const CImg<tf>& primitive = primitives[l]; switch (primitive.size()) { case 1 : { // Point CImg<_to> _opacity; __draw_object3d(opacities,l,_opacity); if (l<=colors.width() && (colors[l].size()!=_spectrum || _opacity)) is_forward = false; const unsigned int i0 = (unsigned int)primitive(0); const tpfloat z0 = Z + vertices(i0,2); if (z0>zmin) { visibles(l) = (unsigned int)l; zrange(l) = z0; } } break; case 5 : { // Sphere const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1); const tpfloat Xc = 0.5f*((float)vertices(i0,0) + (float)vertices(i1,0)), Yc = 0.5f*((float)vertices(i0,1) + (float)vertices(i1,1)), Zc = 0.5f*((float)vertices(i0,2) + (float)vertices(i1,2)), _zc = Z + Zc, zc = _zc + _focale, xc = X + Xc*(absfocale?absfocale/zc:1), yc = Y + Yc*(absfocale?absfocale/zc:1), radius = 0.5f*cimg::hypot(vertices(i1,0) - vertices(i0,0), vertices(i1,1) - vertices(i0,1), vertices(i1,2) - vertices(i0,2))*(absfocale?absfocale/zc:1), xm = xc - radius, ym = yc - radius, xM = xc + radius, yM = yc + radius; if (xM>=0 && xm<_width && yM>=0 && ym<_height && _zc>zmin) { visibles(l) = (unsigned int)l; zrange(l) = _zc; } is_forward = false; } break; case 2 : case 6 : { // Segment const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1); const tpfloat x0 = projections(i0,0), y0 = projections(i0,1), z0 = Z + vertices(i0,2), x1 = projections(i1,0), y1 = projections(i1,1), z1 = Z + vertices(i1,2); tpfloat xm, xM, ym, yM; if (x0<x1) { xm = x0; xM = x1; } else { xm = x1; xM = x0; } if (y0<y1) { ym = y0; yM = y1; } else { ym = y1; yM = y0; } if (xM>=0 && xm<_width && yM>=0 && ym<_height && z0>zmin && z1>zmin) { visibles(l) = (unsigned int)l; zrange(l) = (z0 + z1)/2; } } break; case 3 : case 9 : { // Triangle const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1), i2 = (unsigned int)primitive(2); const tpfloat x0 = projections(i0,0), y0 = projections(i0,1), z0 = Z + vertices(i0,2), x1 = projections(i1,0), y1 = projections(i1,1), z1 = Z + vertices(i1,2), x2 = projections(i2,0), y2 = projections(i2,1), z2 = Z + vertices(i2,2); tpfloat xm, xM, ym, yM; if (x0<x1) { xm = x0; xM = x1; } else { xm = x1; xM = x0; } if (x2<xm) xm = x2; if (x2>xM) xM = x2; if (y0<y1) { ym = y0; yM = y1; } else { ym = y1; yM = y0; } if (y2<ym) ym = y2; if (y2>yM) yM = y2; if (xM>=0 && xm<_width && yM>=0 && ym<_height && z0>zmin && z1>zmin && z2>zmin) { const tpfloat d = (x1-x0)*(y2-y0) - (x2-x0)*(y1-y0); if (is_double_sided || d<0) { visibles(l) = (unsigned int)l; zrange(l) = (z0 + z1 + z2)/3; } } } break; case 4 : case 12 : { // Quadrangle const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1), i2 = (unsigned int)primitive(2), i3 = (unsigned int)primitive(3); const tpfloat x0 = projections(i0,0), y0 = projections(i0,1), z0 = Z + vertices(i0,2), x1 = projections(i1,0), y1 = projections(i1,1), z1 = Z + vertices(i1,2), x2 = projections(i2,0), y2 = projections(i2,1), z2 = Z + vertices(i2,2), x3 = projections(i3,0), y3 = projections(i3,1), z3 = Z + vertices(i3,2); tpfloat xm, xM, ym, yM; if (x0<x1) { xm = x0; xM = x1; } else { xm = x1; xM = x0; } if (x2<xm) xm = x2; if (x2>xM) xM = x2; if (x3<xm) xm = x3; if (x3>xM) xM = x3; if (y0<y1) { ym = y0; yM = y1; } else { ym = y1; yM = y0; } if (y2<ym) ym = y2; if (y2>yM) yM = y2; if (y3<ym) ym = y3; if (y3>yM) yM = y3; if (xM>=0 && xm<_width && yM>=0 && ym<_height && z0>zmin && z1>zmin && z2>zmin && z3>zmin) { const float d = (x1 - x0)*(y2 - y0) - (x2 - x0)*(y1 - y0); if (is_double_sided || d<0) { visibles(l) = (unsigned int)l; zrange(l) = (z0 + z1 + z2 + z3)/4; } } } break; default : if (render_type==5) cimg::mutex(10,0); throw CImgArgumentException(_cimg_instance "draw_object3d(): Invalid primitive[%u] with size %u " "(should have size 1,2,3,4,5,6,9 or 12).", cimg_instance, l,primitive.size()); } } // Force transparent primitives to be drawn last when zbuffer is activated // (and if object contains no spheres or sprites). if (is_forward) cimglist_for(primitives,l) if (___draw_object3d(opacities,l)!=1) zrange(l) = 2*zmax - zrange(l); // Sort only visibles primitives. unsigned int *p_visibles = visibles._data; tpfloat *p_zrange = zrange._data; const tpfloat *ptrz = p_zrange; cimg_for(visibles,ptr,unsigned int) { if (*ptr!=~0U) { *(p_visibles++) = *ptr; *(p_zrange++) = *ptrz; } ++ptrz; } const unsigned int nb_visibles = (unsigned int)(p_zrange - zrange._data); if (!nb_visibles) { if (render_type==5) cimg::mutex(10,0); return *this; } CImg<uintT> permutations; CImg<tpfloat>(zrange._data,nb_visibles,1,1,1,true).sort(permutations,is_forward); // Compute light properties CImg<floatT> lightprops; switch (render_type) { case 3 : { // Flat Shading lightprops.assign(nb_visibles); cimg_pragma_openmp(parallel for cimg_openmp_if_size(nb_visibles,4096)) cimg_forX(lightprops,l) { const CImg<tf>& primitive = primitives(visibles(permutations(l))); const unsigned int psize = (unsigned int)primitive.size(); if (psize==3 || psize==4 || psize==9 || psize==12) { const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1), i2 = (unsigned int)primitive(2); const tpfloat x0 = (tpfloat)vertices(i0,0), y0 = (tpfloat)vertices(i0,1), z0 = (tpfloat)vertices(i0,2), x1 = (tpfloat)vertices(i1,0), y1 = (tpfloat)vertices(i1,1), z1 = (tpfloat)vertices(i1,2), x2 = (tpfloat)vertices(i2,0), y2 = (tpfloat)vertices(i2,1), z2 = (tpfloat)vertices(i2,2), dx1 = x1 - x0, dy1 = y1 - y0, dz1 = z1 - z0, dx2 = x2 - x0, dy2 = y2 - y0, dz2 = z2 - z0, nx = dy1*dz2 - dz1*dy2, ny = dz1*dx2 - dx1*dz2, nz = dx1*dy2 - dy1*dx2, norm = 1e-5f + cimg::hypot(nx,ny,nz), lx = X + (x0 + x1 + x2)/3 - lightx, ly = Y + (y0 + y1 + y2)/3 - lighty, lz = Z + (z0 + z1 + z2)/3 - lightz, nl = 1e-5f + cimg::hypot(lx,ly,lz), factor = std::max(cimg::abs(-lx*nx - ly*ny - lz*nz)/(norm*nl),(tpfloat)0); lightprops[l] = factor<=nspec?factor:(nsl1*factor*factor + nsl2*factor + nsl3); } else lightprops[l] = 1; } } break; case 4 : // Gouraud Shading case 5 : { // Phong-Shading CImg<tpfloat> vertices_normals(vertices._width,6,1,1,0); cimg_pragma_openmp(parallel for cimg_openmp_if_size(nb_visibles,4096)) for (int l = 0; l<(int)nb_visibles; ++l) { const CImg<tf>& primitive = primitives[visibles(l)]; const unsigned int psize = (unsigned int)primitive.size(); const bool triangle_flag = (psize==3) || (psize==9), quadrangle_flag = (psize==4) || (psize==12); if (triangle_flag || quadrangle_flag) { const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1), i2 = (unsigned int)primitive(2), i3 = quadrangle_flag?(unsigned int)primitive(3):0; const tpfloat x0 = (tpfloat)vertices(i0,0), y0 = (tpfloat)vertices(i0,1), z0 = (tpfloat)vertices(i0,2), x1 = (tpfloat)vertices(i1,0), y1 = (tpfloat)vertices(i1,1), z1 = (tpfloat)vertices(i1,2), x2 = (tpfloat)vertices(i2,0), y2 = (tpfloat)vertices(i2,1), z2 = (tpfloat)vertices(i2,2), dx1 = x1 - x0, dy1 = y1 - y0, dz1 = z1 - z0, dx2 = x2 - x0, dy2 = y2 - y0, dz2 = z2 - z0, nnx = dy1*dz2 - dz1*dy2, nny = dz1*dx2 - dx1*dz2, nnz = dx1*dy2 - dy1*dx2, norm = 1e-5f + cimg::hypot(nnx,nny,nnz), nx = nnx/norm, ny = nny/norm, nz = nnz/norm; unsigned int ix = 0, iy = 1, iz = 2; if (is_double_sided && nz>0) { ix = 3; iy = 4; iz = 5; } vertices_normals(i0,ix)+=nx; vertices_normals(i0,iy)+=ny; vertices_normals(i0,iz)+=nz; vertices_normals(i1,ix)+=nx; vertices_normals(i1,iy)+=ny; vertices_normals(i1,iz)+=nz; vertices_normals(i2,ix)+=nx; vertices_normals(i2,iy)+=ny; vertices_normals(i2,iz)+=nz; if (quadrangle_flag) { vertices_normals(i3,ix)+=nx; vertices_normals(i3,iy)+=ny; vertices_normals(i3,iz)+=nz; } } } if (is_double_sided) cimg_forX(vertices_normals,p) { const float nx0 = vertices_normals(p,0), ny0 = vertices_normals(p,1), nz0 = vertices_normals(p,2), nx1 = vertices_normals(p,3), ny1 = vertices_normals(p,4), nz1 = vertices_normals(p,5), n0 = nx0*nx0 + ny0*ny0 + nz0*nz0, n1 = nx1*nx1 + ny1*ny1 + nz1*nz1; if (n1>n0) { vertices_normals(p,0) = -nx1; vertices_normals(p,1) = -ny1; vertices_normals(p,2) = -nz1; } } if (render_type==4) { lightprops.assign(vertices._width); cimg_pragma_openmp(parallel for cimg_openmp_if_size(nb_visibles,4096)) cimg_forX(lightprops,l) { const tpfloat nx = vertices_normals(l,0), ny = vertices_normals(l,1), nz = vertices_normals(l,2), norm = 1e-5f + cimg::hypot(nx,ny,nz), lx = X + vertices(l,0) - lightx, ly = Y + vertices(l,1) - lighty, lz = Z + vertices(l,2) - lightz, nl = 1e-5f + cimg::hypot(lx,ly,lz), factor = std::max((-lx*nx - ly*ny - lz*nz)/(norm*nl),(tpfloat)0); lightprops[l] = factor<=nspec?factor:(nsl1*factor*factor + nsl2*factor + nsl3); } } else { const unsigned int lw2 = light_texture._width/2 - 1, lh2 = light_texture._height/2 - 1; lightprops.assign(vertices._width,2); cimg_pragma_openmp(parallel for cimg_openmp_if_size(nb_visibles,4096)) cimg_forX(lightprops,l) { const tpfloat nx = vertices_normals(l,0), ny = vertices_normals(l,1), nz = vertices_normals(l,2), norm = 1e-5f + cimg::hypot(nx,ny,nz), nnx = nx/norm, nny = ny/norm; lightprops(l,0) = lw2*(1 + nnx); lightprops(l,1) = lh2*(1 + nny); } } } break; } // Draw visible primitives const CImg<tc> default_color(1,_spectrum,1,1,(tc)200); CImg<_to> _opacity; for (unsigned int l = 0; l<nb_visibles; ++l) { const unsigned int n_primitive = visibles(permutations(l)); const CImg<tf>& primitive = primitives[n_primitive]; const CImg<tc> &__color = n_primitive<colors._width?colors[n_primitive]:CImg<tc>(), _color = (__color && __color.size()!=_spectrum && __color._spectrum<_spectrum)? __color.get_resize(-100,-100,-100,_spectrum,0):CImg<tc>(), &color = _color?_color:(__color?__color:default_color); const tc *const pcolor = color._data; float opacity = __draw_object3d(opacities,n_primitive,_opacity); if (_opacity.is_empty()) opacity*=g_opacity; #ifdef cimg_use_board LibBoard::Board &board = *(LibBoard::Board*)pboard; #endif switch (primitive.size()) { case 1 : { // Colored point or sprite const unsigned int n0 = (unsigned int)primitive[0]; const int x0 = cimg::uiround(projections(n0,0)), y0 = cimg::uiround(projections(n0,1)); if (_opacity.is_empty()) { // Scalar opacity if (color.size()==_spectrum) { // Colored point draw_point(x0,y0,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawDot((float)x0,height()-(float)y0); } #endif } else { // Sprite const tpfloat z = Z + vertices(n0,2); const float factor = focale<0?1:sprite_scale*(absfocale?absfocale/(z + absfocale):1); const unsigned int _sw = (unsigned int)(color._width*factor), _sh = (unsigned int)(color._height*factor), sw = _sw?_sw:1, sh = _sh?_sh:1; const int nx0 = x0 - (int)sw/2, ny0 = y0 - (int)sh/2; if (sw<=3*_width/2 && sh<=3*_height/2 && (nx0 + (int)sw/2>=0 || nx0 - (int)sw/2<width() || ny0 + (int)sh/2>=0 || ny0 - (int)sh/2<height())) { const CImg<tc> _sprite = (sw!=color._width || sh!=color._height)? color.get_resize(sw,sh,1,-100,render_type<=3?1:3):CImg<tc>(), &sprite = _sprite?_sprite:color; draw_image(nx0,ny0,sprite,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128); board.setFillColor(LibBoard::Color::Null); board.drawRectangle((float)nx0,height() - (float)ny0,sw,sh); } #endif } } } else { // Opacity mask const tpfloat z = Z + vertices(n0,2); const float factor = focale<0?1:sprite_scale*(absfocale?absfocale/(z + absfocale):1); const unsigned int _sw = (unsigned int)(std::max(color._width,_opacity._width)*factor), _sh = (unsigned int)(std::max(color._height,_opacity._height)*factor), sw = _sw?_sw:1, sh = _sh?_sh:1; const int nx0 = x0 - (int)sw/2, ny0 = y0 - (int)sh/2; if (sw<=3*_width/2 && sh<=3*_height/2 && (nx0 + (int)sw/2>=0 || nx0 - (int)sw/2<width() || ny0 + (int)sh/2>=0 || ny0 - (int)sh/2<height())) { const CImg<tc> _sprite = (sw!=color._width || sh!=color._height)? color.get_resize(sw,sh,1,-100,render_type<=3?1:3):CImg<tc>(), &sprite = _sprite?_sprite:color; const CImg<_to> _nopacity = (sw!=_opacity._width || sh!=_opacity._height)? _opacity.get_resize(sw,sh,1,-100,render_type<=3?1:3):CImg<_to>(), &nopacity = _nopacity?_nopacity:_opacity; draw_image(nx0,ny0,sprite,nopacity,g_opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128); board.setFillColor(LibBoard::Color::Null); board.drawRectangle((float)nx0,height() - (float)ny0,sw,sh); } #endif } } } break; case 2 : { // Colored line const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1]; const int x0 = cimg::uiround(projections(n0,0)), y0 = cimg::uiround(projections(n0,1)), x1 = cimg::uiround(projections(n1,0)), y1 = cimg::uiround(projections(n1,1)); const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale; if (render_type) { if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,pcolor,opacity); else draw_line(x0,y0,x1,y1,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawLine((float)x0,height() - (float)y0,x1,height() - (float)y1); } #endif } else { draw_point(x0,y0,pcolor,opacity).draw_point(x1,y1,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawDot((float)x0,height() - (float)y0); board.drawDot((float)x1,height() - (float)y1); } #endif } } break; case 5 : { // Colored sphere const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1], is_wireframe = (unsigned int)primitive[2]; const float Xc = 0.5f*((float)vertices(n0,0) + (float)vertices(n1,0)), Yc = 0.5f*((float)vertices(n0,1) + (float)vertices(n1,1)), Zc = 0.5f*((float)vertices(n0,2) + (float)vertices(n1,2)), zc = Z + Zc + _focale, xc = X + Xc*(absfocale?absfocale/zc:1), yc = Y + Yc*(absfocale?absfocale/zc:1), radius = 0.5f*cimg::hypot(vertices(n1,0) - vertices(n0,0), vertices(n1,1) - vertices(n0,1), vertices(n1,2) - vertices(n0,2))*(absfocale?absfocale/zc:1); switch (render_type) { case 0 : draw_point((int)xc,(int)yc,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawDot(xc,height() - yc); } #endif break; case 1 : draw_circle((int)xc,(int)yc,(int)radius,pcolor,opacity,~0U); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.setFillColor(LibBoard::Color::Null); board.drawCircle(xc,height() - yc,radius); } #endif break; default : if (is_wireframe) draw_circle((int)xc,(int)yc,(int)radius,pcolor,opacity,~0U); else draw_circle((int)xc,(int)yc,(int)radius,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); if (!is_wireframe) board.fillCircle(xc,height() - yc,radius); else { board.setFillColor(LibBoard::Color::Null); board.drawCircle(xc,height() - yc,radius); } } #endif break; } } break; case 6 : { // Textured line if (!__color) { if (render_type==5) cimg::mutex(10,0); throw CImgArgumentException(_cimg_instance "draw_object3d(): Undefined texture for line primitive [%u].", cimg_instance,n_primitive); } const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1]; const int tx0 = (int)primitive[2], ty0 = (int)primitive[3], tx1 = (int)primitive[4], ty1 = (int)primitive[5], x0 = cimg::uiround(projections(n0,0)), y0 = cimg::uiround(projections(n0,1)), x1 = cimg::uiround(projections(n1,0)), y1 = cimg::uiround(projections(n1,1)); const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale; if (render_type) { if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,color,tx0,ty0,tx1,ty1,opacity); else draw_line(x0,y0,z0,x1,y1,z1,color,tx0,ty0,tx1,ty1,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.drawLine((float)x0,height() - (float)y0,(float)x1,height() - (float)y1); } #endif } else { draw_point(x0,y0,color.get_vector_at(tx0<=0?0:tx0>=color.width()?color.width() - 1:tx0, ty0<=0?0:ty0>=color.height()?color.height() - 1:ty0)._data,opacity). draw_point(x1,y1,color.get_vector_at(tx1<=0?0:tx1>=color.width()?color.width() - 1:tx1, ty1<=0?0:ty1>=color.height()?color.height() - 1:ty1)._data,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.drawDot((float)x0,height() - (float)y0); board.drawDot((float)x1,height() - (float)y1); } #endif } } break; case 3 : { // Colored triangle const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1], n2 = (unsigned int)primitive[2]; const int x0 = cimg::uiround(projections(n0,0)), y0 = cimg::uiround(projections(n0,1)), x1 = cimg::uiround(projections(n1,0)), y1 = cimg::uiround(projections(n1,1)), x2 = cimg::uiround(projections(n2,0)), y2 = cimg::uiround(projections(n2,1)); const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale, z2 = vertices(n2,2) + Z + _focale; switch (render_type) { case 0 : draw_point(x0,y0,pcolor,opacity).draw_point(x1,y1,pcolor,opacity).draw_point(x2,y2,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawDot((float)x0,height() - (float)y0); board.drawDot((float)x1,height() - (float)y1); board.drawDot((float)x2,height() - (float)y2); } #endif break; case 1 : if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,pcolor,opacity).draw_line(zbuffer,x0,y0,z0,x2,y2,z2,pcolor,opacity). draw_line(zbuffer,x1,y1,z1,x2,y2,z2,pcolor,opacity); else draw_line(x0,y0,x1,y1,pcolor,opacity).draw_line(x0,y0,x2,y2,pcolor,opacity). draw_line(x1,y1,x2,y2,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawLine((float)x0,height() - (float)y0,(float)x1,height() - (float)y1); board.drawLine((float)x0,height() - (float)y0,(float)x2,height() - (float)y2); board.drawLine((float)x1,height() - (float)y1,(float)x2,height() - (float)y2); } #endif break; case 2 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,opacity); else draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); } #endif break; case 3 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,opacity,lightprops(l)); else _draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,opacity,lightprops(l)); #ifdef cimg_use_board if (pboard) { const float lp = std::min(lightprops(l),1.f); board.setPenColorRGBi((unsigned char)(color[0]*lp), (unsigned char)(color[1]*lp), (unsigned char)(color[2]*lp), (unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); } #endif break; case 4 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor, lightprops(n0),lightprops(n1),lightprops(n2),opacity); else draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,lightprops(n0),lightprops(n1),lightprops(n2),opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi((unsigned char)(color[0]), (unsigned char)(color[1]), (unsigned char)(color[2]), (unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,lightprops(n0), (float)x1,height() - (float)y1,lightprops(n1), (float)x2,height() - (float)y2,lightprops(n2)); } #endif break; case 5 : { const unsigned int lx0 = (unsigned int)cimg::uiround(lightprops(n0,0)), ly0 = (unsigned int)cimg::uiround(lightprops(n0,1)), lx1 = (unsigned int)cimg::uiround(lightprops(n1,0)), ly1 = (unsigned int)cimg::uiround(lightprops(n1,1)), lx2 = (unsigned int)cimg::uiround(lightprops(n2,0)), ly2 = (unsigned int)cimg::uiround(lightprops(n2,1)); if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,light_texture,lx0,ly0,lx1,ly1,lx2,ly2,opacity); else draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,light_texture,lx0,ly0,lx1,ly1,lx2,ly2,opacity); #ifdef cimg_use_board if (pboard) { const float l0 = light_texture((int)(light_texture.width()/2*(1 + lightprops(n0,0))), (int)(light_texture.height()/2*(1 + lightprops(n0,1)))), l1 = light_texture((int)(light_texture.width()/2*(1 + lightprops(n1,0))), (int)(light_texture.height()/2*(1 + lightprops(n1,1)))), l2 = light_texture((int)(light_texture.width()/2*(1 + lightprops(n2,0))), (int)(light_texture.height()/2*(1 + lightprops(n2,1)))); board.setPenColorRGBi((unsigned char)(color[0]), (unsigned char)(color[1]), (unsigned char)(color[2]), (unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,l0, (float)x1,height() - (float)y1,l1, (float)x2,height() - (float)y2,l2); } #endif } break; } } break; case 4 : { // Colored quadrangle const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1], n2 = (unsigned int)primitive[2], n3 = (unsigned int)primitive[3]; const int x0 = cimg::uiround(projections(n0,0)), y0 = cimg::uiround(projections(n0,1)), x1 = cimg::uiround(projections(n1,0)), y1 = cimg::uiround(projections(n1,1)), x2 = cimg::uiround(projections(n2,0)), y2 = cimg::uiround(projections(n2,1)), x3 = cimg::uiround(projections(n3,0)), y3 = cimg::uiround(projections(n3,1)), xc = (x0 + x1 + x2 + x3)/4, yc = (y0 + y1 + y2 + y3)/4; const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale, z2 = vertices(n2,2) + Z + _focale, z3 = vertices(n3,2) + Z + _focale, zc = (z0 + z1 + z2 + z3)/4; switch (render_type) { case 0 : draw_point(x0,y0,pcolor,opacity).draw_point(x1,y1,pcolor,opacity). draw_point(x2,y2,pcolor,opacity).draw_point(x3,y3,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawDot((float)x0,height() - (float)y0); board.drawDot((float)x1,height() - (float)y1); board.drawDot((float)x2,height() - (float)y2); board.drawDot((float)x3,height() - (float)y3); } #endif break; case 1 : if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,pcolor,opacity).draw_line(zbuffer,x1,y1,z1,x2,y2,z2,pcolor,opacity). draw_line(zbuffer,x2,y2,z2,x3,y3,z3,pcolor,opacity).draw_line(zbuffer,x3,y3,z3,x0,y0,z0,pcolor,opacity); else draw_line(x0,y0,x1,y1,pcolor,opacity).draw_line(x1,y1,x2,y2,pcolor,opacity). draw_line(x2,y2,x3,y3,pcolor,opacity).draw_line(x3,y3,x0,y0,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawLine((float)x0,height() - (float)y0,(float)x1,height() - (float)y1); board.drawLine((float)x1,height() - (float)y1,(float)x2,height() - (float)y2); board.drawLine((float)x2,height() - (float)y2,(float)x3,height() - (float)y3); board.drawLine((float)x3,height() - (float)y3,(float)x0,height() - (float)y0); } #endif break; case 2 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,opacity). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,pcolor,opacity); else draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,opacity).draw_triangle(x0,y0,x2,y2,x3,y3,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); board.fillTriangle((float)x0,height() - (float)y0, (float)x2,height() - (float)y2, (float)x3,height() - (float)y3); } #endif break; case 3 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,opacity,lightprops(l)). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,pcolor,opacity,lightprops(l)); else _draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,opacity,lightprops(l)). _draw_triangle(x0,y0,x2,y2,x3,y3,pcolor,opacity,lightprops(l)); #ifdef cimg_use_board if (pboard) { const float lp = std::min(lightprops(l),1.f); board.setPenColorRGBi((unsigned char)(color[0]*lp), (unsigned char)(color[1]*lp), (unsigned char)(color[2]*lp),(unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); board.fillTriangle((float)x0,height() - (float)y0, (float)x2,height() - (float)y2, (float)x3,height() - (float)y3); } #endif break; case 4 : { const float lightprop0 = lightprops(n0), lightprop1 = lightprops(n1), lightprop2 = lightprops(n2), lightprop3 = lightprops(n3), lightpropc = (lightprop0 + lightprop1 + lightprop2 + lightprop2)/4; if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,xc,yc,zc,pcolor,lightprop0,lightprop1,lightpropc,opacity). draw_triangle(zbuffer,x1,y1,z1,x2,y2,z2,xc,yc,zc,pcolor,lightprop1,lightprop2,lightpropc,opacity). draw_triangle(zbuffer,x2,y2,z2,x3,y3,z3,xc,yc,zc,pcolor,lightprop2,lightprop3,lightpropc,opacity). draw_triangle(zbuffer,x3,y3,z3,x0,y0,z0,xc,yc,zc,pcolor,lightprop3,lightprop0,lightpropc,opacity); else draw_triangle(x0,y0,x1,y1,xc,yc,pcolor,lightprop0,lightprop1,lightpropc,opacity). draw_triangle(x1,y1,x2,y2,xc,yc,pcolor,lightprop1,lightprop2,lightpropc,opacity). draw_triangle(x2,y2,x3,y3,xc,yc,pcolor,lightprop2,lightprop3,lightpropc,opacity). draw_triangle(x3,y3,x0,y0,xc,yc,pcolor,lightprop3,lightprop0,lightpropc,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi((unsigned char)(color[0]), (unsigned char)(color[1]), (unsigned char)(color[2]), (unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,lightprop0, (float)x1,height() - (float)y1,lightprop1, (float)x2,height() - (float)y2,lightprop2); board.fillGouraudTriangle((float)x0,height() - (float)y0,lightprop0, (float)x2,height() - (float)y2,lightprop2, (float)x3,height() - (float)y3,lightprop3); } #endif } break; case 5 : { const unsigned int lx0 = (unsigned int)cimg::uiround(lightprops(n0,0)), ly0 = (unsigned int)cimg::uiround(lightprops(n0,1)), lx1 = (unsigned int)cimg::uiround(lightprops(n1,0)), ly1 = (unsigned int)cimg::uiround(lightprops(n1,1)), lx2 = (unsigned int)cimg::uiround(lightprops(n2,0)), ly2 = (unsigned int)cimg::uiround(lightprops(n2,1)), lx3 = (unsigned int)cimg::uiround(lightprops(n3,0)), ly3 = (unsigned int)cimg::uiround(lightprops(n3,1)), lxc = (lx0 + lx1 + lx2 + lx3)/4, lyc = (ly0 + ly1 + ly2 + ly3)/4; if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,xc,yc,zc,pcolor,light_texture,lx0,ly0,lx1,ly1,lxc,lyc,opacity). draw_triangle(zbuffer,x1,y1,z1,x2,y2,z2,xc,yc,zc,pcolor,light_texture,lx1,ly1,lx2,ly2,lxc,lyc,opacity). draw_triangle(zbuffer,x2,y2,z2,x3,y3,z3,xc,yc,zc,pcolor,light_texture,lx2,ly2,lx3,ly3,lxc,lyc,opacity). draw_triangle(zbuffer,x3,y3,z3,x0,y0,z0,xc,yc,zc,pcolor,light_texture,lx3,ly3,lx0,ly0,lxc,lyc,opacity); else draw_triangle(x0,y0,x1,y1,xc,yc,pcolor,light_texture,lx0,ly0,lx1,ly1,lxc,lyc,opacity). draw_triangle(x1,y1,x2,y2,xc,yc,pcolor,light_texture,lx1,ly1,lx2,ly2,lxc,lyc,opacity). draw_triangle(x2,y2,x3,y3,xc,yc,pcolor,light_texture,lx2,ly2,lx3,ly3,lxc,lyc,opacity). draw_triangle(x3,y3,x0,y0,xc,yc,pcolor,light_texture,lx3,ly3,lx0,ly0,lxc,lyc,opacity); #ifdef cimg_use_board if (pboard) { const float l0 = light_texture((int)(light_texture.width()/2*(1 + lx0)), (int)(light_texture.height()/2*(1 + ly0))), l1 = light_texture((int)(light_texture.width()/2*(1 + lx1)), (int)(light_texture.height()/2*(1 + ly1))), l2 = light_texture((int)(light_texture.width()/2*(1 + lx2)), (int)(light_texture.height()/2*(1 + ly2))), l3 = light_texture((int)(light_texture.width()/2*(1 + lx3)), (int)(light_texture.height()/2*(1 + ly3))); board.setPenColorRGBi((unsigned char)(color[0]), (unsigned char)(color[1]), (unsigned char)(color[2]), (unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,l0, (float)x1,height() - (float)y1,l1, (float)x2,height() - (float)y2,l2); board.fillGouraudTriangle((float)x0,height() - (float)y0,l0, (float)x2,height() - (float)y2,l2, (float)x3,height() - (float)y3,l3); } #endif } break; } } break; case 9 : { // Textured triangle if (!__color) { if (render_type==5) cimg::mutex(10,0); throw CImgArgumentException(_cimg_instance "draw_object3d(): Undefined texture for triangle primitive [%u].", cimg_instance,n_primitive); } const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1], n2 = (unsigned int)primitive[2]; const int tx0 = (int)primitive[3], ty0 = (int)primitive[4], tx1 = (int)primitive[5], ty1 = (int)primitive[6], tx2 = (int)primitive[7], ty2 = (int)primitive[8], x0 = cimg::uiround(projections(n0,0)), y0 = cimg::uiround(projections(n0,1)), x1 = cimg::uiround(projections(n1,0)), y1 = cimg::uiround(projections(n1,1)), x2 = cimg::uiround(projections(n2,0)), y2 = cimg::uiround(projections(n2,1)); const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale, z2 = vertices(n2,2) + Z + _focale; switch (render_type) { case 0 : draw_point(x0,y0,color.get_vector_at(tx0<=0?0:tx0>=color.width()?color.width() - 1:tx0, ty0<=0?0:ty0>=color.height()?color.height() - 1:ty0)._data,opacity). draw_point(x1,y1,color.get_vector_at(tx1<=0?0:tx1>=color.width()?color.width() - 1:tx1, ty1<=0?0:ty1>=color.height()?color.height() - 1:ty1)._data,opacity). draw_point(x2,y2,color.get_vector_at(tx2<=0?0:tx2>=color.width()?color.width() - 1:tx2, ty2<=0?0:ty2>=color.height()?color.height() - 1:ty2)._data,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.drawDot((float)x0,height() - (float)y0); board.drawDot((float)x1,height() - (float)y1); board.drawDot((float)x2,height() - (float)y2); } #endif break; case 1 : if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,color,tx0,ty0,tx1,ty1,opacity). draw_line(zbuffer,x0,y0,z0,x2,y2,z2,color,tx0,ty0,tx2,ty2,opacity). draw_line(zbuffer,x1,y1,z1,x2,y2,z2,color,tx1,ty1,tx2,ty2,opacity); else draw_line(x0,y0,z0,x1,y1,z1,color,tx0,ty0,tx1,ty1,opacity). draw_line(x0,y0,z0,x2,y2,z2,color,tx0,ty0,tx2,ty2,opacity). draw_line(x1,y1,z1,x2,y2,z2,color,tx1,ty1,tx2,ty2,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.drawLine((float)x0,height() - (float)y0,(float)x1,height() - (float)y1); board.drawLine((float)x0,height() - (float)y0,(float)x2,height() - (float)y2); board.drawLine((float)x1,height() - (float)y1,(float)x2,height() - (float)y2); } #endif break; case 2 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); } #endif break; case 3 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity,lightprops(l)); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity,lightprops(l)); #ifdef cimg_use_board if (pboard) { const float lp = std::min(lightprops(l),1.f); board.setPenColorRGBi((unsigned char)(128*lp), (unsigned char)(128*lp), (unsigned char)(128*lp), (unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); } #endif break; case 4 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2, lightprops(n0),lightprops(n1),lightprops(n2),opacity); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2, lightprops(n0),lightprops(n1),lightprops(n2),opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,lightprops(n0), (float)x1,height() - (float)y1,lightprops(n1), (float)x2,height() - (float)y2,lightprops(n2)); } #endif break; case 5 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,light_texture, (unsigned int)lightprops(n0,0),(unsigned int)lightprops(n0,1), (unsigned int)lightprops(n1,0),(unsigned int)lightprops(n1,1), (unsigned int)lightprops(n2,0),(unsigned int)lightprops(n2,1), opacity); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,light_texture, (unsigned int)lightprops(n0,0),(unsigned int)lightprops(n0,1), (unsigned int)lightprops(n1,0),(unsigned int)lightprops(n1,1), (unsigned int)lightprops(n2,0),(unsigned int)lightprops(n2,1), opacity); #ifdef cimg_use_board if (pboard) { const float l0 = light_texture((int)(light_texture.width()/2*(1 + lightprops(n0,0))), (int)(light_texture.height()/2*(1 + lightprops(n0,1)))), l1 = light_texture((int)(light_texture.width()/2*(1 + lightprops(n1,0))), (int)(light_texture.height()/2*(1 + lightprops(n1,1)))), l2 = light_texture((int)(light_texture.width()/2*(1 + lightprops(n2,0))), (int)(light_texture.height()/2*(1 + lightprops(n2,1)))); board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,l0, (float)x1,height() - (float)y1,l1, (float)x2,height() - (float)y2,l2); } #endif break; } } break; case 12 : { // Textured quadrangle if (!__color) { if (render_type==5) cimg::mutex(10,0); throw CImgArgumentException(_cimg_instance "draw_object3d(): Undefined texture for quadrangle primitive [%u].", cimg_instance,n_primitive); } const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1], n2 = (unsigned int)primitive[2], n3 = (unsigned int)primitive[3]; const int tx0 = (int)primitive[4], ty0 = (int)primitive[5], tx1 = (int)primitive[6], ty1 = (int)primitive[7], tx2 = (int)primitive[8], ty2 = (int)primitive[9], tx3 = (int)primitive[10], ty3 = (int)primitive[11], x0 = cimg::uiround(projections(n0,0)), y0 = cimg::uiround(projections(n0,1)), x1 = cimg::uiround(projections(n1,0)), y1 = cimg::uiround(projections(n1,1)), x2 = cimg::uiround(projections(n2,0)), y2 = cimg::uiround(projections(n2,1)), x3 = cimg::uiround(projections(n3,0)), y3 = cimg::uiround(projections(n3,1)); const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale, z2 = vertices(n2,2) + Z + _focale, z3 = vertices(n3,2) + Z + _focale; switch (render_type) { case 0 : draw_point(x0,y0,color.get_vector_at(tx0<=0?0:tx0>=color.width()?color.width() - 1:tx0, ty0<=0?0:ty0>=color.height()?color.height() - 1:ty0)._data,opacity). draw_point(x1,y1,color.get_vector_at(tx1<=0?0:tx1>=color.width()?color.width() - 1:tx1, ty1<=0?0:ty1>=color.height()?color.height() - 1:ty1)._data,opacity). draw_point(x2,y2,color.get_vector_at(tx2<=0?0:tx2>=color.width()?color.width() - 1:tx2, ty2<=0?0:ty2>=color.height()?color.height() - 1:ty2)._data,opacity). draw_point(x3,y3,color.get_vector_at(tx3<=0?0:tx3>=color.width()?color.width() - 1:tx3, ty3<=0?0:ty3>=color.height()?color.height() - 1:ty3)._data,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.drawDot((float)x0,height() - (float)y0); board.drawDot((float)x1,height() - (float)y1); board.drawDot((float)x2,height() - (float)y2); board.drawDot((float)x3,height() - (float)y3); } #endif break; case 1 : if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,color,tx0,ty0,tx1,ty1,opacity). draw_line(zbuffer,x1,y1,z1,x2,y2,z2,color,tx1,ty1,tx2,ty2,opacity). draw_line(zbuffer,x2,y2,z2,x3,y3,z3,color,tx2,ty2,tx3,ty3,opacity). draw_line(zbuffer,x3,y3,z3,x0,y0,z0,color,tx3,ty3,tx0,ty0,opacity); else draw_line(x0,y0,z0,x1,y1,z1,color,tx0,ty0,tx1,ty1,opacity). draw_line(x1,y1,z1,x2,y2,z2,color,tx1,ty1,tx2,ty2,opacity). draw_line(x2,y2,z2,x3,y3,z3,color,tx2,ty2,tx3,ty3,opacity). draw_line(x3,y3,z3,x0,y0,z0,color,tx3,ty3,tx0,ty0,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.drawLine((float)x0,height() - (float)y0,(float)x1,height() - (float)y1); board.drawLine((float)x1,height() - (float)y1,(float)x2,height() - (float)y2); board.drawLine((float)x2,height() - (float)y2,(float)x3,height() - (float)y3); board.drawLine((float)x3,height() - (float)y3,(float)x0,height() - (float)y0); } #endif break; case 2 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3,opacity); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity). draw_triangle(x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); board.fillTriangle((float)x0,height() - (float)y0, (float)x2,height() - (float)y2, (float)x3,height() - (float)y3); } #endif break; case 3 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity,lightprops(l)). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3,opacity,lightprops(l)); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity,lightprops(l)). draw_triangle(x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3,opacity,lightprops(l)); #ifdef cimg_use_board if (pboard) { const float lp = std::min(lightprops(l),1.f); board.setPenColorRGBi((unsigned char)(128*lp), (unsigned char)(128*lp), (unsigned char)(128*lp), (unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); board.fillTriangle((float)x0,height() - (float)y0, (float)x2,height() - (float)y2, (float)x3,height() - (float)y3); } #endif break; case 4 : { const float lightprop0 = lightprops(n0), lightprop1 = lightprops(n1), lightprop2 = lightprops(n2), lightprop3 = lightprops(n3); if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2, lightprop0,lightprop1,lightprop2,opacity). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3, lightprop0,lightprop2,lightprop3,opacity); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2, lightprop0,lightprop1,lightprop2,opacity). draw_triangle(x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3, lightprop0,lightprop2,lightprop3,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,lightprop0, (float)x1,height() - (float)y1,lightprop1, (float)x2,height() - (float)y2,lightprop2); board.fillGouraudTriangle((float)x0,height() -(float)y0,lightprop0, (float)x2,height() - (float)y2,lightprop2, (float)x3,height() - (float)y3,lightprop3); } #endif } break; case 5 : { const unsigned int lx0 = (unsigned int)cimg::uiround(lightprops(n0,0)), ly0 = (unsigned int)cimg::uiround(lightprops(n0,1)), lx1 = (unsigned int)cimg::uiround(lightprops(n1,0)), ly1 = (unsigned int)cimg::uiround(lightprops(n1,1)), lx2 = (unsigned int)cimg::uiround(lightprops(n2,0)), ly2 = (unsigned int)cimg::uiround(lightprops(n2,1)), lx3 = (unsigned int)cimg::uiround(lightprops(n3,0)), ly3 = (unsigned int)cimg::uiround(lightprops(n3,1)); if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2, light_texture,lx0,ly0,lx1,ly1,lx2,ly2,opacity). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3, light_texture,lx0,ly0,lx2,ly2,lx3,ly3,opacity); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2, light_texture,lx0,ly0,lx1,ly1,lx2,ly2,opacity). draw_triangle(x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3, light_texture,lx0,ly0,lx2,ly2,lx3,ly3,opacity); #ifdef cimg_use_board if (pboard) { const float l0 = light_texture((int)(light_texture.width()/2*(1 + lx0)), (int)(light_texture.height()/2*(1 + ly0))), l1 = light_texture((int)(light_texture.width()/2*(1 + lx1)), (int)(light_texture.height()/2*(1 + ly1))), l2 = light_texture((int)(light_texture.width()/2*(1 + lx2)), (int)(light_texture.height()/2*(1 + ly2))), l3 = light_texture((int)(light_texture.width()/2*(1 + lx3)), (int)(light_texture.height()/2*(1 + ly3))); board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,l0, (float)x1,height() - (float)y1,l1, (float)x2,height() - (float)y2,l2); board.fillGouraudTriangle((float)x0,height() -(float)y0,l0, (float)x2,height() - (float)y2,l2, (float)x3,height() - (float)y3,l3); } #endif } break; } } break; } } if (render_type==5) cimg::mutex(10,0); return *this; } //@} //--------------------------- // //! \name Data Input //@{ //--------------------------- //! Launch simple interface to select a shape from an image. /** \param disp Display window to use. \param feature_type Type of feature to select. Can be <tt>{ 0=point | 1=line | 2=rectangle | 3=ellipse }</tt>. \param XYZ Pointer to 3 values X,Y,Z which tells about the projection point coordinates, for volumetric images. \param exit_on_anykey Exit function when any key is pressed. **/ CImg<T>& select(CImgDisplay &disp, const unsigned int feature_type=2, unsigned int *const XYZ=0, const bool exit_on_anykey=false, const bool is_deep_selection_default=false) { return get_select(disp,feature_type,XYZ,exit_on_anykey,is_deep_selection_default).move_to(*this); } //! Simple interface to select a shape from an image \overloading. CImg<T>& select(const char *const title, const unsigned int feature_type=2, unsigned int *const XYZ=0, const bool exit_on_anykey=false, const bool is_deep_selection_default=false) { return get_select(title,feature_type,XYZ,exit_on_anykey,is_deep_selection_default).move_to(*this); } //! Simple interface to select a shape from an image \newinstance. CImg<intT> get_select(CImgDisplay &disp, const unsigned int feature_type=2, unsigned int *const XYZ=0, const bool exit_on_anykey=false, const bool is_deep_selection_default=false) const { return _select(disp,0,feature_type,XYZ,0,0,0,exit_on_anykey,true,false,is_deep_selection_default); } //! Simple interface to select a shape from an image \newinstance. CImg<intT> get_select(const char *const title, const unsigned int feature_type=2, unsigned int *const XYZ=0, const bool exit_on_anykey=false, const bool is_deep_selection_default=false) const { CImgDisplay disp; return _select(disp,title,feature_type,XYZ,0,0,0,exit_on_anykey,true,false,is_deep_selection_default); } CImg<intT> _select(CImgDisplay &disp, const char *const title, const unsigned int feature_type, unsigned int *const XYZ, const int origX, const int origY, const int origZ, const bool exit_on_anykey, const bool reset_view3d, const bool force_display_z_coord, const bool is_deep_selection_default) const { if (is_empty()) return CImg<intT>(1,feature_type==0?3:6,1,1,-1); if (!disp) { disp.assign(cimg_fitscreen(_width,_height,_depth),title?title:0,1); if (!title) disp.set_title("CImg<%s> (%ux%ux%ux%u)",pixel_type(),_width,_height,_depth,_spectrum); } else { if (title) disp.set_title("%s",title); disp.move_inside_screen(); } CImg<T> thumb; if (width()>disp.screen_width() || height()>disp.screen_height()) get_resize(cimg_fitscreen(width(),height(),depth()),depth(),-100).move_to(thumb); const unsigned int old_normalization = disp.normalization(); bool old_is_resized = disp.is_resized(); disp._normalization = 0; disp.show().set_key(0).set_wheel().show_mouse(); static const unsigned char foreground_color[] = { 255,255,255 }, background_color[] = { 0,0,0 }; int area = 0, area_started = 0, area_clicked = 0, phase = 0, X0 = (int)((XYZ?XYZ[0]:_width/2)%_width), Y0 = (int)((XYZ?XYZ[1]:_height/2)%_height), Z0 = (int)((XYZ?XYZ[2]:_depth/2)%_depth), X1 =-1, Y1 = -1, Z1 = -1, X3d = -1, Y3d = -1, oX3d = X3d, oY3d = -1, omx = -1, omy = -1; float X = -1, Y = -1, Z = -1; unsigned int key = 0; bool is_deep_selection = is_deep_selection_default, shape_selected = false, text_down = false, visible_cursor = true; static CImg<floatT> pose3d; static bool is_view3d = false, is_axes = true; if (reset_view3d) { pose3d.assign(); is_view3d = false; } CImg<floatT> points3d, opacities3d, sel_opacities3d; CImgList<uintT> primitives3d, sel_primitives3d; CImgList<ucharT> colors3d, sel_colors3d; CImg<ucharT> visu, visu0, view3d; CImg<charT> text(1024); *text = 0; while (!key && !disp.is_closed() && !shape_selected) { // Handle mouse motion and selection int mx = disp.mouse_x(), my = disp.mouse_y(); const float mX = mx<0?-1.f:(float)mx*(width() + (depth()>1?depth():0))/disp.width(), mY = my<0?-1.f:(float)my*(height() + (depth()>1?depth():0))/disp.height(); area = 0; if (mX>=0 && mY>=0 && mX<width() && mY<height()) { area = 1; X = mX; Y = mY; Z = (float)(phase?Z1:Z0); } if (mX>=0 && mX<width() && mY>=height()) { area = 2; X = mX; Z = mY - _height; Y = (float)(phase?Y1:Y0); } if (mY>=0 && mX>=width() && mY<height()) { area = 3; Y = mY; Z = mX - _width; X = (float)(phase?X1:X0); } if (mX>=width() && mY>=height()) area = 4; if (disp.button()) { if (!area_clicked) area_clicked = area; } else area_clicked = 0; CImg<charT> filename(32); switch (key = disp.key()) { #if cimg_OS!=2 case cimg::keyCTRLRIGHT : #endif case 0 : case cimg::keyCTRLLEFT : key = 0; break; case cimg::keyPAGEUP : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_wheel(1); key = 0; } break; case cimg::keyPAGEDOWN : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_wheel(-1); key = 0; } break; case cimg::keyX : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { is_axes = !is_axes; disp.set_key(key,false); key = 0; visu0.assign(); } break; case cimg::keyD : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false). resize(CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,false), CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,true),false). _is_resized = true; disp.set_key(key,false); key = 0; visu0.assign(); } break; case cimg::keyC : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false). resize(cimg_fitscreen(2*disp.width()/3,2*disp.height()/3,1),false)._is_resized = true; disp.set_key(key,false); key = 0; visu0.assign(); } break; case cimg::keyR : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false).resize(cimg_fitscreen(_width,_height,_depth),false)._is_resized = true; disp.set_key(key,false); key = 0; visu0.assign(); } break; case cimg::keyF : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.resize(disp.screen_width(),disp.screen_height(),false).toggle_fullscreen()._is_resized = true; disp.set_key(key,false); key = 0; visu0.assign(); } break; case cimg::keyV : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { is_view3d = !is_view3d; disp.set_key(key,false); key = 0; visu0.assign(); } break; case cimg::keyS : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { static unsigned int snap_number = 0; std::FILE *file; do { cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.bmp",snap_number++); if ((file=cimg::std_fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); if (visu0) { (+visu0).__draw_text(" Saving snapshot...",(int)text_down).display(disp); visu0.save(filename); (+visu0).__draw_text(" Snapshot '%s' saved. ",(int)text_down,filename._data).display(disp); } disp.set_key(key,false); key = 0; } break; case cimg::keyO : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { static unsigned int snap_number = 0; std::FILE *file; do { #ifdef cimg_use_zlib cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.cimgz",snap_number++); #else cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.cimg",snap_number++); #endif if ((file=cimg::std_fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); (+visu0).__draw_text(" Saving instance... ",(int)text_down).display(disp); save(filename); (+visu0).__draw_text(" Instance '%s' saved. ",(int)text_down,filename._data).display(disp); disp.set_key(key,false); key = 0; } break; } switch (area) { case 0 : // When mouse is out of image range mx = my = -1; X = Y = Z = -1; break; case 1 : case 2 : case 3 : { // When mouse is over the XY,XZ or YZ projections const unsigned int but = disp.button(); const bool b1 = (bool)(but&1), b2 = (bool)(but&2), b3 = (bool)(but&4); if (b1 && phase==1 && area_clicked==area) { // When selection has been started (1st step) if (_depth>1 && (X1!=(int)X || Y1!=(int)Y || Z1!=(int)Z)) visu0.assign(); X1 = (int)X; Y1 = (int)Y; Z1 = (int)Z; } if (!b1 && phase==2 && area_clicked!=area) { // When selection is at 2nd step (for volumes) switch (area_started) { case 1 : if (Z1!=(int)Z) visu0.assign(); Z1 = (int)Z; break; case 2 : if (Y1!=(int)Y) visu0.assign(); Y1 = (int)Y; break; case 3 : if (X1!=(int)X) visu0.assign(); X1 = (int)X; break; } } if (b2 && area_clicked==area) { // When moving through the image/volume if (phase) { if (_depth>1 && (X1!=(int)X || Y1!=(int)Y || Z1!=(int)Z)) visu0.assign(); X1 = (int)X; Y1 = (int)Y; Z1 = (int)Z; } else { if (_depth>1 && (X0!=(int)X || Y0!=(int)Y || Z0!=(int)Z)) visu0.assign(); X0 = (int)X; Y0 = (int)Y; Z0 = (int)Z; } } if (b3) { // Reset selection X = (float)X0; Y = (float)Y0; Z = (float)Z0; phase = area = area_clicked = area_started = 0; visu0.assign(); } if (disp.wheel()) { // When moving through the slices of the volume (with mouse wheel) if (_depth>1 && !disp.is_keyCTRLLEFT() && !disp.is_keyCTRLRIGHT() && !disp.is_keySHIFTLEFT() && !disp.is_keySHIFTRIGHT()) { switch (area) { case 1 : if (phase) Z = (float)(Z1+=disp.wheel()); else Z = (float)(Z0+=disp.wheel()); visu0.assign(); break; case 2 : if (phase) Y = (float)(Y1+=disp.wheel()); else Y = (float)(Y0+=disp.wheel()); visu0.assign(); break; case 3 : if (phase) X = (float)(X1+=disp.wheel()); else X = (float)(X0+=disp.wheel()); visu0.assign(); break; } disp.set_wheel(); } else key = ~0U; } if ((phase==0 && b1) || (phase==1 && !b1) || (phase==2 && b1)) switch (phase) { // Detect change of phase case 0 : if (area==area_clicked) { X0 = X1 = (int)X; Y0 = Y1 = (int)Y; Z0 = Z1 = (int)Z; area_started = area; ++phase; } break; case 1 : if (area==area_started) { X1 = (int)X; Y1 = (int)Y; Z1 = (int)Z; ++phase; if (_depth>1) { if (disp.is_keyCTRLLEFT()) is_deep_selection = !is_deep_selection_default; if (is_deep_selection) ++phase; } } else if (!b1) { X = (float)X0; Y = (float)Y0; Z = (float)Z0; phase = 0; visu0.assign(); } break; case 2 : ++phase; break; } } break; case 4 : // When mouse is over the 3D view if (is_view3d && points3d) { X3d = mx - width()*disp.width()/(width() + (depth()>1?depth():0)); Y3d = my - height()*disp.height()/(height() + (depth()>1?depth():0)); if (oX3d<0) { oX3d = X3d; oY3d = Y3d; } // Left + right buttons: reset. if ((disp.button()&3)==3) { pose3d.assign(); view3d.assign(); oX3d = oY3d = X3d = Y3d = -1; } else if (disp.button()&1 && pose3d && (oX3d!=X3d || oY3d!=Y3d)) { // Left button: rotate const float R = 0.45f*std::min(view3d._width,view3d._height), R2 = R*R, u0 = (float)(oX3d - view3d.width()/2), v0 = (float)(oY3d - view3d.height()/2), u1 = (float)(X3d - view3d.width()/2), v1 = (float)(Y3d - view3d.height()/2), n0 = cimg::hypot(u0,v0), n1 = cimg::hypot(u1,v1), nu0 = n0>R?(u0*R/n0):u0, nv0 = n0>R?(v0*R/n0):v0, nw0 = (float)std::sqrt(std::max(0.f,R2 - nu0*nu0 - nv0*nv0)), nu1 = n1>R?(u1*R/n1):u1, nv1 = n1>R?(v1*R/n1):v1, nw1 = (float)std::sqrt(std::max(0.f,R2 - nu1*nu1 - nv1*nv1)), u = nv0*nw1 - nw0*nv1, v = nw0*nu1 - nu0*nw1, w = nv0*nu1 - nu0*nv1, n = cimg::hypot(u,v,w), alpha = (float)std::asin(n/R2)*180/cimg::PI; pose3d.draw_image(CImg<floatT>::rotation_matrix(u,v,w,-alpha)*pose3d.get_crop(0,0,2,2)); view3d.assign(); } else if (disp.button()&2 && pose3d && oY3d!=Y3d) { // Right button: zoom pose3d(3,2)+=(Y3d - oY3d)*1.5f; view3d.assign(); } if (disp.wheel()) { // Wheel: zoom pose3d(3,2)-=disp.wheel()*15; view3d.assign(); disp.set_wheel(); } if (disp.button()&4 && pose3d && (oX3d!=X3d || oY3d!=Y3d)) { // Middle button: shift pose3d(3,0)-=oX3d - X3d; pose3d(3,1)-=oY3d - Y3d; view3d.assign(); } oX3d = X3d; oY3d = Y3d; } mx = my = -1; X = Y = Z = -1; break; } if (phase) { if (!feature_type) shape_selected = phase?true:false; else { if (_depth>1) shape_selected = (phase==3)?true:false; else shape_selected = (phase==2)?true:false; } } if (X0<0) X0 = 0; if (X0>=width()) X0 = width() - 1; if (Y0<0) Y0 = 0; if (Y0>=height()) Y0 = height() - 1; if (Z0<0) Z0 = 0; if (Z0>=depth()) Z0 = depth() - 1; if (X1<1) X1 = 0; if (X1>=width()) X1 = width() - 1; if (Y1<0) Y1 = 0; if (Y1>=height()) Y1 = height() - 1; if (Z1<0) Z1 = 0; if (Z1>=depth()) Z1 = depth() - 1; // Draw visualization image on the display if (mx!=omx || my!=omy || !visu0 || (_depth>1 && !view3d)) { if (!visu0) { // Create image of projected planes if (thumb) thumb._get_select(disp,old_normalization,phase?X1:X0,phase?Y1:Y0,phase?Z1:Z0).move_to(visu0); else _get_select(disp,old_normalization,phase?X1:X0,phase?Y1:Y0,phase?Z1:Z0).move_to(visu0); visu0.resize(disp); view3d.assign(); points3d.assign(); } if (is_view3d && _depth>1 && !view3d) { // Create 3D view for volumetric images const unsigned int _x3d = (unsigned int)cimg::round((float)_width*visu0._width/(_width + _depth),1,1), _y3d = (unsigned int)cimg::round((float)_height*visu0._height/(_height + _depth),1,1), x3d = _x3d>=visu0._width?visu0._width - 1:_x3d, y3d = _y3d>=visu0._height?visu0._height - 1:_y3d; CImg<ucharT>(1,2,1,1,64,128).resize(visu0._width - x3d,visu0._height - y3d,1,visu0._spectrum,3). move_to(view3d); if (!points3d) { get_projections3d(primitives3d,colors3d,phase?X1:X0,phase?Y1:Y0,phase?Z1:Z0,true).move_to(points3d); points3d.append(CImg<floatT>(8,3,1,1, 0,_width - 1,_width - 1,0,0,_width - 1,_width - 1,0, 0,0,_height - 1,_height - 1,0,0,_height - 1,_height - 1, 0,0,0,0,_depth - 1,_depth - 1,_depth - 1,_depth - 1),'x'); CImg<uintT>::vector(12,13).move_to(primitives3d); CImg<uintT>::vector(13,14).move_to(primitives3d); CImg<uintT>::vector(14,15).move_to(primitives3d); CImg<uintT>::vector(15,12).move_to(primitives3d); CImg<uintT>::vector(16,17).move_to(primitives3d); CImg<uintT>::vector(17,18).move_to(primitives3d); CImg<uintT>::vector(18,19).move_to(primitives3d); CImg<uintT>::vector(19,16).move_to(primitives3d); CImg<uintT>::vector(12,16).move_to(primitives3d); CImg<uintT>::vector(13,17).move_to(primitives3d); CImg<uintT>::vector(14,18).move_to(primitives3d); CImg<uintT>::vector(15,19).move_to(primitives3d); colors3d.insert(12,CImg<ucharT>::vector(255,255,255)); opacities3d.assign(primitives3d.width(),1,1,1,0.5f); if (!phase) { opacities3d[0] = opacities3d[1] = opacities3d[2] = 0.8f; sel_primitives3d.assign(); sel_colors3d.assign(); sel_opacities3d.assign(); } else { if (feature_type==2) { points3d.append(CImg<floatT>(8,3,1,1, X0,X1,X1,X0,X0,X1,X1,X0, Y0,Y0,Y1,Y1,Y0,Y0,Y1,Y1, Z0,Z0,Z0,Z0,Z1,Z1,Z1,Z1),'x'); sel_primitives3d.assign(); CImg<uintT>::vector(20,21).move_to(sel_primitives3d); CImg<uintT>::vector(21,22).move_to(sel_primitives3d); CImg<uintT>::vector(22,23).move_to(sel_primitives3d); CImg<uintT>::vector(23,20).move_to(sel_primitives3d); CImg<uintT>::vector(24,25).move_to(sel_primitives3d); CImg<uintT>::vector(25,26).move_to(sel_primitives3d); CImg<uintT>::vector(26,27).move_to(sel_primitives3d); CImg<uintT>::vector(27,24).move_to(sel_primitives3d); CImg<uintT>::vector(20,24).move_to(sel_primitives3d); CImg<uintT>::vector(21,25).move_to(sel_primitives3d); CImg<uintT>::vector(22,26).move_to(sel_primitives3d); CImg<uintT>::vector(23,27).move_to(sel_primitives3d); } else { points3d.append(CImg<floatT>(2,3,1,1, X0,X1, Y0,Y1, Z0,Z1),'x'); sel_primitives3d.assign(CImg<uintT>::vector(20,21)); } sel_colors3d.assign(sel_primitives3d._width,CImg<ucharT>::vector(255,255,255)); sel_opacities3d.assign(sel_primitives3d._width,1,1,1,0.8f); } points3d.shift_object3d(-0.5f*(_width - 1),-0.5f*(_height - 1),-0.5f*(_depth - 1)).resize_object3d(); points3d*=0.75f*std::min(view3d._width,view3d._height); } if (!pose3d) CImg<floatT>(4,3,1,1, 1,0,0,0, 0,1,0,0, 0,0,1,0).move_to(pose3d); CImg<floatT> zbuffer3d(view3d._width,view3d._height,1,1,0); const CImg<floatT> rotated_points3d = pose3d.get_crop(0,0,2,2)*points3d; if (sel_primitives3d) view3d.draw_object3d(pose3d(3,0) + 0.5f*view3d._width, pose3d(3,1) + 0.5f*view3d._height, pose3d(3,2), rotated_points3d,sel_primitives3d,sel_colors3d,sel_opacities3d, 2,true,500,0,0,0,0,0,1,zbuffer3d); view3d.draw_object3d(pose3d(3,0) + 0.5f*view3d._width, pose3d(3,1) + 0.5f*view3d._height, pose3d(3,2), rotated_points3d,primitives3d,colors3d,opacities3d, 2,true,500,0,0,0,0,0,1,zbuffer3d); visu0.draw_image(x3d,y3d,view3d); } visu = visu0; if (X<0 || Y<0 || Z<0) { if (!visible_cursor) { disp.show_mouse(); visible_cursor = true; }} else { if (is_axes) { if (visible_cursor) { disp.hide_mouse(); visible_cursor = false; }} else { if (!visible_cursor) { disp.show_mouse(); visible_cursor = true; }} const int d = (depth()>1)?depth():0; int _vX = (int)X, _vY = (int)Y, _vZ = (int)Z; if (phase>=2) { _vX = X1; _vY = Y1; _vZ = Z1; } int w = disp.width(), W = width() + d, h = disp.height(), H = height() + d, _xp = (int)(_vX*(float)w/W), xp = _xp + ((int)(_xp*(float)W/w)!=_vX), _yp = (int)(_vY*(float)h/H), yp = _yp + ((int)(_yp*(float)H/h)!=_vY), _xn = (int)((_vX + 1.f)*w/W - 1), xn = _xn + ((int)((_xn + 1.f)*W/w)!=_vX + 1), _yn = (int)((_vY + 1.f)*h/H - 1), yn = _yn + ((int)((_yn + 1.f)*H/h)!=_vY + 1), _zxp = (int)((_vZ + width())*(float)w/W), zxp = _zxp + ((int)(_zxp*(float)W/w)!=_vZ + width()), _zyp = (int)((_vZ + height())*(float)h/H), zyp = _zyp + ((int)(_zyp*(float)H/h)!=_vZ + height()), _zxn = (int)((_vZ + width() + 1.f)*w/W - 1), zxn = _zxn + ((int)((_zxn + 1.f)*W/w)!=_vZ + width() + 1), _zyn = (int)((_vZ + height() + 1.f)*h/H - 1), zyn = _zyn + ((int)((_zyn + 1.f)*H/h)!=_vZ + height() + 1), _xM = (int)(width()*(float)w/W - 1), xM = _xM + ((int)((_xM + 1.f)*W/w)!=width()), _yM = (int)(height()*(float)h/H - 1), yM = _yM + ((int)((_yM + 1.f)*H/h)!=height()), xc = (xp + xn)/2, yc = (yp + yn)/2, zxc = (zxp + zxn)/2, zyc = (zyp + zyn)/2, xf = (int)(X*w/W), yf = (int)(Y*h/H), zxf = (int)((Z + width())*w/W), zyf = (int)((Z + height())*h/H); if (is_axes) { // Draw axes visu.draw_line(0,yf,visu.width() - 1,yf,foreground_color,0.7f,0xFF00FF00). draw_line(0,yf,visu.width() - 1,yf,background_color,0.7f,0x00FF00FF). draw_line(xf,0,xf,visu.height() - 1,foreground_color,0.7f,0xFF00FF00). draw_line(xf,0,xf,visu.height() - 1,background_color,0.7f,0x00FF00FF); if (_depth>1) visu.draw_line(zxf,0,zxf,yM,foreground_color,0.7f,0xFF00FF00). draw_line(zxf,0,zxf,yM,background_color,0.7f,0x00FF00FF). draw_line(0,zyf,xM,zyf,foreground_color,0.7f,0xFF00FF00). draw_line(0,zyf,xM,zyf,background_color,0.7f,0x00FF00FF); } // Draw box cursor. if (xn - xp>=4 && yn - yp>=4) visu.draw_rectangle(xp,yp,xn,yn,foreground_color,0.2f). draw_rectangle(xp,yp,xn,yn,foreground_color,1,0xAAAAAAAA). draw_rectangle(xp,yp,xn,yn,background_color,1,0x55555555); if (_depth>1) { if (yn - yp>=4 && zxn - zxp>=4) visu.draw_rectangle(zxp,yp,zxn,yn,background_color,0.2f). draw_rectangle(zxp,yp,zxn,yn,foreground_color,1,0xAAAAAAAA). draw_rectangle(zxp,yp,zxn,yn,background_color,1,0x55555555); if (xn - xp>=4 && zyn - zyp>=4) visu.draw_rectangle(xp,zyp,xn,zyn,background_color,0.2f). draw_rectangle(xp,zyp,xn,zyn,foreground_color,1,0xAAAAAAAA). draw_rectangle(xp,zyp,xn,zyn,background_color,1,0x55555555); } // Draw selection. if (phase && (phase!=1 || area_started==area)) { const int _xp0 = (int)(X0*(float)w/W), xp0 = _xp0 + ((int)(_xp0*(float)W/w)!=X0), _yp0 = (int)(Y0*(float)h/H), yp0 = _yp0 + ((int)(_yp0*(float)H/h)!=Y0), _xn0 = (int)((X0 + 1.f)*w/W - 1), xn0 = _xn0 + ((int)((_xn0 + 1.f)*W/w)!=X0 + 1), _yn0 = (int)((Y0 + 1.f)*h/H - 1), yn0 = _yn0 + ((int)((_yn0 + 1.f)*H/h)!=Y0 + 1), _zxp0 = (int)((Z0 + width())*(float)w/W), zxp0 = _zxp0 + ((int)(_zxp0*(float)W/w)!=Z0 + width()), _zyp0 = (int)((Z0 + height())*(float)h/H), zyp0 = _zyp0 + ((int)(_zyp0*(float)H/h)!=Z0 + height()), _zxn0 = (int)((Z0 + width() + 1.f)*w/W - 1), zxn0 = _zxn0 + ((int)((_zxn0 + 1.f)*W/w)!=Z0 + width() + 1), _zyn0 = (int)((Z0 + height() + 1.f)*h/H - 1), zyn0 = _zyn0 + ((int)((_zyn0 + 1.f)*H/h)!=Z0 + height() + 1), xc0 = (xp0 + xn0)/2, yc0 = (yp0 + yn0)/2, zxc0 = (zxp0 + zxn0)/2, zyc0 = (zyp0 + zyn0)/2; switch (feature_type) { case 1 : { // Vector visu.draw_arrow(xc0,yc0,xc,yc,background_color,0.9f,30,5,0x33333333). draw_arrow(xc0,yc0,xc,yc,foreground_color,0.9f,30,5,0xCCCCCCCC); if (d) { visu.draw_arrow(zxc0,yc0,zxc,yc,background_color,0.9f,30,5,0x33333333). draw_arrow(zxc0,yc0,zxc,yc,foreground_color,0.9f,30,5,0xCCCCCCCC). draw_arrow(xc0,zyc0,xc,zyc,background_color,0.9f,30,5,0x33333333). draw_arrow(xc0,zyc0,xc,zyc,foreground_color,0.9f,30,5,0xCCCCCCCC); } } break; case 2 : { // Box visu.draw_rectangle(X0<X1?xp0:xp,Y0<Y1?yp0:yp,X0<X1?xn:xn0,Y0<Y1?yn:yn0,background_color,0.2f). draw_rectangle(X0<X1?xp0:xp,Y0<Y1?yp0:yp,X0<X1?xn:xn0,Y0<Y1?yn:yn0,background_color,0.9f,0x55555555). draw_rectangle(X0<X1?xp0:xp,Y0<Y1?yp0:yp,X0<X1?xn:xn0,Y0<Y1?yn:yn0,foreground_color,0.9f,0xAAAAAAAA); if (xc0!=xc && yc0!=yc) visu.draw_line(xc0,yc0,xc,yc,background_color,0.9f,0x33333333). draw_line(xc0,yc0,xc,yc,foreground_color,0.9f,0xCCCCCCCC); if (d) { visu.draw_rectangle(Z0<Z1?zxp0:zxp,Y0<Y1?yp0:yp,Z0<Z1?zxn:zxn0,Y0<Y1?yn:yn0,background_color,0.2f). draw_rectangle(Z0<Z1?zxp0:zxp,Y0<Y1?yp0:yp,Z0<Z1?zxn:zxn0,Y0<Y1?yn:yn0, background_color,0.9f,0x55555555). draw_rectangle(Z0<Z1?zxp0:zxp,Y0<Y1?yp0:yp,Z0<Z1?zxn:zxn0,Y0<Y1?yn:yn0, foreground_color,0.9f,0xAAAAAAAA); if (zxc0!=zxc && yc0!=yc) visu.draw_line(zxc0,yc0,zxc,yc,background_color,0.9f,0x33333333). draw_line(zxc0,yc0,zxc,yc,foreground_color,0.9f,0xCCCCCCCC); visu.draw_rectangle(X0<X1?xp0:xp,Z0<Z1?zyp0:zyp,X0<X1?xn:xn0,Z0<Z1?zyn:zyn0, background_color,0.2f). draw_rectangle(X0<X1?xp0:xp,Z0<Z1?zyp0:zyp,X0<X1?xn:xn0,Z0<Z1?zyn:zyn0, background_color,0.9f,0x55555555). draw_rectangle(X0<X1?xp0:xp,Z0<Z1?zyp0:zyp,X0<X1?xn:xn0,Z0<Z1?zyn:zyn0, foreground_color,0.9f,0xAAAAAAAA); if (xp0!=xn && zyp0!=zyn) visu.draw_line(xp0,zyp0,xn,zyn,background_color,0.9f,0x33333333). draw_line(xp0,zyp0,xn,zyn,foreground_color,0.9f,0xCCCCCCCC); } } break; case 3 : { // Ellipse visu.draw_ellipse(xc0,yc0, (float)cimg::abs(xc - xc0), (float)cimg::abs(yc - yc0),0,background_color,0.2f). draw_ellipse(xc0,yc0, (float)cimg::abs(xc - xc0), (float)cimg::abs(yc - yc0),0,foreground_color,0.9f,~0U). draw_point(xc0,yc0,foreground_color,0.9f); if (d) { visu.draw_ellipse(zxc0,yc0,(float)cimg::abs(zxc - zxc0),(float)cimg::abs(yc - yc0),0, background_color,0.2f). draw_ellipse(zxc0,yc0,(float)cimg::abs(zxc - zxc0),(float)cimg::abs(yc - yc0),0, foreground_color,0.9f,~0U). draw_point(zxc0,yc0,foreground_color,0.9f). draw_ellipse(xc0,zyc0,(float)cimg::abs(xc - xc0),(float)cimg::abs(zyc - zyc0),0, background_color,0.2f). draw_ellipse(xc0,zyc0,(float)cimg::abs(xc - xc0),(float)cimg::abs(zyc - zyc0),0, foreground_color,0.9f,~0U). draw_point(xc0,zyc0,foreground_color,0.9f); } } break; } } // Draw text info. if (my>=0 && my<13) text_down = true; else if (my>=visu.height() - 13) text_down = false; if (!feature_type || !phase) { if (X>=0 && Y>=0 && Z>=0 && X<width() && Y<height() && Z<depth()) { if (_depth>1 || force_display_z_coord) cimg_snprintf(text,text._width," Point (%d,%d,%d) = [ ",origX + (int)X,origY + (int)Y,origZ + (int)Z); else cimg_snprintf(text,text._width," Point (%d,%d) = [ ",origX + (int)X,origY + (int)Y); CImg<T> values = get_vector_at((int)X,(int)Y,(int)Z); const bool is_large_spectrum = values._height>8; if (is_large_spectrum) values.draw_image(0,4,values.get_rows(values._height - 4,values._height - 1)).resize(1,8,1,1,0); char *ctext = text._data + std::strlen(text), *const ltext = text._data + 512; for (unsigned int c = 0; c<values._height && ctext<ltext; ++c) { cimg_snprintf(ctext,24,cimg::type<T>::format_s(), cimg::type<T>::format(values[c])); ctext += std::strlen(ctext); if (c==3 && is_large_spectrum) { cimg_snprintf(ctext,24," ..."); ctext += std::strlen(ctext); } *(ctext++) = ' '; *ctext = 0; } std::strcpy(text._data + std::strlen(text),"] "); } } else switch (feature_type) { case 1 : { const double dX = (double)(X0 - X1), dY = (double)(Y0 - Y1), dZ = (double)(Z0 - Z1), length = cimg::round(cimg::hypot(dX,dY,dZ),0.1); if (_depth>1 || force_display_z_coord) cimg_snprintf(text,text._width," Vect (%d,%d,%d)-(%d,%d,%d), Length = %g ", origX + X0,origY + Y0,origZ + Z0,origX + X1,origY + Y1,origZ + Z1,length); else if (_width!=1 && _height!=1) cimg_snprintf(text,text._width," Vect (%d,%d)-(%d,%d), Length = %g, Angle = %g\260 ", origX + X0,origY + Y0,origX + X1,origY + Y1,length, cimg::round(cimg::mod(180*std::atan2(-dY,-dX)/cimg::PI,360.),0.1)); else cimg_snprintf(text,text._width," Vect (%d,%d)-(%d,%d), Length = %g ", origX + X0,origY + Y0,origX + X1,origY + Y1,length); } break; case 2 : { const double dX = (double)(X0 - X1), dY = (double)(Y0 - Y1), dZ = (double)(Z0 - Z1), length = cimg::round(cimg::hypot(dX,dY,dZ),0.1); if (_depth>1 || force_display_z_coord) cimg_snprintf(text,text._width, " Box ( %d,%d,%d ) - ( %d,%d,%d )\n Size = ( %d,%d,%d ), Length = %g ", origX + (X0<X1?X0:X1),origY + (Y0<Y1?Y0:Y1),origZ + (Z0<Z1?Z0:Z1), origX + (X0<X1?X1:X0),origY + (Y0<Y1?Y1:Y0),origZ + (Z0<Z1?Z1:Z0), 1 + cimg::abs(X0 - X1),1 + cimg::abs(Y0 - Y1),1 + cimg::abs(Z0 - Z1),length); else if (_width!=1 && _height!=1) cimg_snprintf(text,text._width, " Box ( %d,%d ) - ( %d,%d )\n Size = ( %d,%d ), Length = %g \n Angle = %g\260 ", origX + (X0<X1?X0:X1),origY + (Y0<Y1?Y0:Y1), origX + (X0<X1?X1:X0),origY + (Y0<Y1?Y1:Y0), 1 + cimg::abs(X0 - X1),1 + cimg::abs(Y0 - Y1),length, cimg::round(cimg::mod(180*std::atan2(-dY,-dX)/cimg::PI,360.),0.1)); else cimg_snprintf(text,text._width, " Box ( %d,%d ) - ( %d,%d )\n Size = (%d,%d), Length = %g ", origX + (X0<X1?X0:X1),origY + (Y0<Y1?Y0:Y1), origX + (X0<X1?X1:X0),origY + (Y0<Y1?Y1:Y0), 1 + cimg::abs(X0 - X1),1 + cimg::abs(Y0 - Y1),length); } break; default : if (_depth>1 || force_display_z_coord) cimg_snprintf(text,text._width," Ellipse ( %d,%d,%d ) - ( %d,%d,%d ), Radii = ( %d,%d,%d ) ", origX + X0,origY + Y0,origZ + Z0,origX + X1,origY + Y1,origZ + Z1, 1 + cimg::abs(X0 - X1),1 + cimg::abs(Y0 - Y1),1 + cimg::abs(Z0 - Z1)); else cimg_snprintf(text,text._width," Ellipse ( %d,%d ) - ( %d,%d ), Radii = ( %d,%d ) ", origX + X0,origY + Y0,origX + X1,origY + Y1, 1 + cimg::abs(X0 - X1),1 + cimg::abs(Y0 - Y1)); } if (phase || (mx>=0 && my>=0)) visu.__draw_text("%s",(int)text_down,text._data); } disp.display(visu); } if (!shape_selected) disp.wait(); if (disp.is_resized()) { disp.resize(false)._is_resized = false; old_is_resized = true; visu0.assign(); } omx = mx; omy = my; if (!exit_on_anykey && key && key!=cimg::keyESC && (key!=cimg::keyW || (!disp.is_keyCTRLLEFT() && !disp.is_keyCTRLRIGHT()))) { key = 0; } } // Return result. CImg<intT> res(1,feature_type==0?3:6,1,1,-1); if (XYZ) { XYZ[0] = (unsigned int)X0; XYZ[1] = (unsigned int)Y0; XYZ[2] = (unsigned int)Z0; } if (shape_selected) { if (feature_type==2) { if (is_deep_selection) switch (area_started) { case 1 : Z0 = 0; Z1 = _depth - 1; break; case 2 : Y0 = 0; Y1 = _height - 1; break; case 3 : X0 = 0; X1 = _width - 1; break; } if (X0>X1) cimg::swap(X0,X1); if (Y0>Y1) cimg::swap(Y0,Y1); if (Z0>Z1) cimg::swap(Z0,Z1); } if (X1<0 || Y1<0 || Z1<0) X0 = Y0 = Z0 = X1 = Y1 = Z1 = -1; switch (feature_type) { case 1 : case 2 : res[0] = X0; res[1] = Y0; res[2] = Z0; res[3] = X1; res[4] = Y1; res[5] = Z1; break; case 3 : res[3] = cimg::abs(X1 - X0); res[4] = cimg::abs(Y1 - Y0); res[5] = cimg::abs(Z1 - Z0); res[0] = X0; res[1] = Y0; res[2] = Z0; break; default : res[0] = X0; res[1] = Y0; res[2] = Z0; } } if (!exit_on_anykey || !(disp.button()&4)) disp.set_button(); if (!visible_cursor) disp.show_mouse(); disp._normalization = old_normalization; disp._is_resized = old_is_resized; if (key!=~0U) disp.set_key(key); return res; } // Return a visualizable uchar8 image for display routines. CImg<ucharT> _get_select(const CImgDisplay& disp, const int normalization, const int x, const int y, const int z) const { if (is_empty()) return CImg<ucharT>(1,1,1,1,0); const CImg<T> crop = get_shared_channels(0,std::min(2,spectrum() - 1)); CImg<Tuchar> img2d; if (_depth>1) { const int mdisp = std::min(disp.screen_width(),disp.screen_height()); if (depth()>mdisp) { crop.get_resize(-100,-100,mdisp,-100,0).move_to(img2d); img2d.projections2d(x,y,z*img2d._depth/_depth); } else crop.get_projections2d(x,y,z).move_to(img2d); } else CImg<Tuchar>(crop,false).move_to(img2d); // Check for inf and NaN values. if (cimg::type<T>::is_float() && normalization) { bool is_inf = false, is_nan = false; cimg_for(img2d,ptr,Tuchar) if (cimg::type<T>::is_inf(*ptr)) { is_inf = true; break; } else if (cimg::type<T>::is_nan(*ptr)) { is_nan = true; break; } if (is_inf || is_nan) { Tint m0 = (Tint)cimg::type<T>::max(), M0 = (Tint)cimg::type<T>::min(); if (!normalization) { m0 = 0; M0 = 255; } else if (normalization==2) { m0 = (Tint)disp._min; M0 = (Tint)disp._max; } else cimg_for(img2d,ptr,Tuchar) if (!cimg::type<T>::is_inf(*ptr) && !cimg::type<T>::is_nan(*ptr)) { if (*ptr<(Tuchar)m0) m0 = *ptr; if (*ptr>(Tuchar)M0) M0 = *ptr; } const T val_minf = (T)(normalization==1 || normalization==3?m0 - (M0 - m0)*20 - 1:m0), val_pinf = (T)(normalization==1 || normalization==3?M0 + (M0 - m0)*20 + 1:M0); if (is_nan) cimg_for(img2d,ptr,Tuchar) if (cimg::type<T>::is_nan(*ptr)) *ptr = val_minf; // Replace NaN values if (is_inf) cimg_for(img2d,ptr,Tuchar) if (cimg::type<T>::is_inf(*ptr)) *ptr = (float)*ptr<0?val_minf:val_pinf; // Replace +-inf values } } switch (normalization) { case 1 : img2d.normalize((ucharT)0,(ucharT)255); break; case 2 : { const float m = disp._min, M = disp._max; (img2d-=m)*=255.f/(M - m>0?M - m:1); } break; case 3 : if (cimg::type<T>::is_float()) img2d.normalize((ucharT)0,(ucharT)255); else { const float m = (float)cimg::type<T>::min(), M = (float)cimg::type<T>::max(); (img2d-=m)*=255.f/(M - m>0?M - m:1); } break; } if (img2d.spectrum()==2) img2d.channels(0,2); return img2d; } //! Select sub-graph in a graph. CImg<intT> get_select_graph(CImgDisplay &disp, const unsigned int plot_type=1, const unsigned int vertex_type=1, const char *const labelx=0, const double xmin=0, const double xmax=0, const char *const labely=0, const double ymin=0, const double ymax=0, const bool exit_on_anykey=false) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "select_graph(): Empty instance.", cimg_instance); if (!disp) disp.assign(cimg_fitscreen(CImgDisplay::screen_width()/2,CImgDisplay::screen_height()/2,1),0,0). set_title("CImg<%s>",pixel_type()); const ulongT siz = (ulongT)_width*_height*_depth; const unsigned int old_normalization = disp.normalization(); disp.show().set_button().set_wheel()._normalization = 0; double nymin = ymin, nymax = ymax, nxmin = xmin, nxmax = xmax; if (nymin==nymax) { nymin = (Tfloat)min_max(nymax); const double dy = nymax - nymin; nymin-=dy/20; nymax+=dy/20; } if (nymin==nymax) { --nymin; ++nymax; } if (nxmin==nxmax && nxmin==0) { nxmin = 0; nxmax = siz - 1.; } static const unsigned char black[] = { 0, 0, 0 }, white[] = { 255, 255, 255 }, gray[] = { 220, 220, 220 }; static const unsigned char gray2[] = { 110, 110, 110 }, ngray[] = { 35, 35, 35 }; CImg<ucharT> colormap(3,_spectrum); if (_spectrum==1) { colormap[0] = colormap[1] = 120; colormap[2] = 200; } else { colormap(0,0) = 220; colormap(1,0) = 10; colormap(2,0) = 10; if (_spectrum>1) { colormap(0,1) = 10; colormap(1,1) = 220; colormap(2,1) = 10; } if (_spectrum>2) { colormap(0,2) = 10; colormap(1,2) = 10; colormap(2,2) = 220; } if (_spectrum>3) { colormap(0,3) = 220; colormap(1,3) = 220; colormap(2,3) = 10; } if (_spectrum>4) { colormap(0,4) = 220; colormap(1,4) = 10; colormap(2,4) = 220; } if (_spectrum>5) { colormap(0,5) = 10; colormap(1,5) = 220; colormap(2,5) = 220; } if (_spectrum>6) { ulongT rng = 10; cimg_for_inY(colormap,6,colormap.height()-1,k) { colormap(0,k) = (unsigned char)(120 + cimg::rand(-100.f,100.f,&rng)); colormap(1,k) = (unsigned char)(120 + cimg::rand(-100.f,100.f,&rng)); colormap(2,k) = (unsigned char)(120 + cimg::rand(-100.f,100.f,&rng)); } } } CImg<ucharT> visu0, visu, graph, text, axes; int x0 = -1, x1 = -1, y0 = -1, y1 = -1, omouse_x = -2, omouse_y = -2; const unsigned int one = plot_type==3?0U:1U; unsigned int okey = 0, obutton = 0; CImg<charT> message(1024); CImg_3x3(I,unsigned char); for (bool selected = false; !selected && !disp.is_closed() && !okey && !disp.wheel(); ) { const int mouse_x = disp.mouse_x(), mouse_y = disp.mouse_y(); const unsigned int key = disp.key(), button = disp.button(); // Generate graph representation. if (!visu0) { visu0.assign(disp.width(),disp.height(),1,3,220); const int gdimx = disp.width() - 32, gdimy = disp.height() - 32; if (gdimx>0 && gdimy>0) { graph.assign(gdimx,gdimy,1,3,255); if (siz<32) { if (siz>1) graph.draw_grid(gdimx/(float)(siz - one),gdimy/(float)(siz - one),0,0, false,true,black,0.2f,0x33333333,0x33333333); } else graph.draw_grid(-10,-10,0,0,false,true,black,0.2f,0x33333333,0x33333333); cimg_forC(*this,c) graph.draw_graph(get_shared_channel(c),&colormap(0,c),(plot_type!=3 || _spectrum==1)?1:0.6f, plot_type,vertex_type,nymax,nymin); axes.assign(gdimx,gdimy,1,1,0); const float dx = (float)cimg::abs(nxmax - nxmin), dy = (float)cimg::abs(nymax - nymin), px = (float)std::pow(10.,(int)std::log10(dx?dx:1) - 2.), py = (float)std::pow(10.,(int)std::log10(dy?dy:1) - 2.); const CImg<Tdouble> seqx = dx<=0?CImg<Tdouble>::vector(nxmin): CImg<Tdouble>::sequence(1 + gdimx/60,nxmin,one?nxmax:nxmin + (nxmax - nxmin)*(siz + 1)/siz), seqy = CImg<Tdouble>::sequence(1 + gdimy/60,nymax,nymin); const bool allow_zero = (nxmin*nxmax>0) || (nymin*nymax>0); axes.draw_axes(seqx,seqy,white,1,~0U,~0U,13,allow_zero,px,py); if (nymin>0) axes.draw_axis(seqx,gdimy - 1,gray,1,~0U,13,allow_zero,px); if (nymax<0) axes.draw_axis(seqx,0,gray,1,~0U,13,allow_zero,px); if (nxmin>0) axes.draw_axis(0,seqy,gray,1,~0U,13,allow_zero,py); if (nxmax<0) axes.draw_axis(gdimx - 1,seqy,gray,1,~0U,13,allow_zero,py); cimg_for3x3(axes,x,y,0,0,I,unsigned char) if (Icc) { if (Icc==255) cimg_forC(graph,c) graph(x,y,c) = 0; else cimg_forC(graph,c) graph(x,y,c) = (unsigned char)(2*graph(x,y,c)/3); } else if (Ipc || Inc || Icp || Icn || Ipp || Inn || Ipn || Inp) cimg_forC(graph,c) graph(x,y,c) = (unsigned char)((graph(x,y,c) + 511)/3); visu0.draw_image(16,16,graph); visu0.draw_line(15,15,16 + gdimx,15,gray2).draw_line(16 + gdimx,15,16 + gdimx,16 + gdimy,gray2). draw_line(16 + gdimx,16 + gdimy,15,16 + gdimy,white).draw_line(15,16 + gdimy,15,15,white); } else graph.assign(); text.assign().draw_text(0,0,labelx?labelx:"X-axis",white,ngray,1,13).resize(-100,-100,1,3); visu0.draw_image((visu0.width() - text.width())/2,visu0.height() - 14,~text); text.assign().draw_text(0,0,labely?labely:"Y-axis",white,ngray,1,13).rotate(-90).resize(-100,-100,1,3); visu0.draw_image(1,(visu0.height() - text.height())/2,~text); visu.assign(); } // Generate and display current view. if (!visu) { visu.assign(visu0); if (graph && x0>=0 && x1>=0) { const int nx0 = x0<=x1?x0:x1, nx1 = x0<=x1?x1:x0, ny0 = y0<=y1?y0:y1, ny1 = y0<=y1?y1:y0, sx0 = (int)(16 + nx0*(visu.width() - 32)/std::max((ulongT)1,siz - one)), sx1 = (int)(15 + (nx1 + 1)*(visu.width() - 32)/std::max((ulongT)1,siz - one)), sy0 = 16 + ny0, sy1 = 16 + ny1; if (y0>=0 && y1>=0) visu.draw_rectangle(sx0,sy0,sx1,sy1,gray,0.5f).draw_rectangle(sx0,sy0,sx1,sy1,black,0.5f,0xCCCCCCCCU); else visu.draw_rectangle(sx0,0,sx1,visu.height() - 17,gray,0.5f). draw_line(sx0,16,sx0,visu.height() - 17,black,0.5f,0xCCCCCCCCU). draw_line(sx1,16,sx1,visu.height() - 17,black,0.5f,0xCCCCCCCCU); } if (mouse_x>=16 && mouse_y>=16 && mouse_x<visu.width() - 16 && mouse_y<visu.height() - 16) { if (graph) visu.draw_line(mouse_x,16,mouse_x,visu.height() - 17,black,0.5f,0x55555555U); const unsigned int x = (unsigned int)cimg::round((mouse_x - 16.f)*(siz - one)/(disp.width() - 32),1,one?0:-1); const double cx = nxmin + x*(nxmax - nxmin)/std::max((ulongT)1,siz - 1); if (_spectrum>=7) cimg_snprintf(message,message._width,"Value[%u:%g] = ( %g %g %g ... %g %g %g )",x,cx, (double)(*this)(x,0,0,0),(double)(*this)(x,0,0,1),(double)(*this)(x,0,0,2), (double)(*this)(x,0,0,_spectrum - 4),(double)(*this)(x,0,0,_spectrum - 3), (double)(*this)(x,0,0,_spectrum - 1)); else { cimg_snprintf(message,message._width,"Value[%u:%g] = ( ",x,cx); cimg_forC(*this,c) cimg_sprintf(message._data + std::strlen(message),"%g ",(double)(*this)(x,0,0,c)); cimg_sprintf(message._data + std::strlen(message),")"); } if (x0>=0 && x1>=0) { const unsigned int nx0 = (unsigned int)(x0<=x1?x0:x1), nx1 = (unsigned int)(x0<=x1?x1:x0), ny0 = (unsigned int)(y0<=y1?y0:y1), ny1 = (unsigned int)(y0<=y1?y1:y0); const double cx0 = nxmin + nx0*(nxmax - nxmin)/std::max((ulongT)1,siz - 1), cx1 = nxmin + (nx1 + one)*(nxmax - nxmin)/std::max((ulongT)1,siz - 1), cy0 = nymax - ny0*(nymax - nymin)/(visu._height - 32), cy1 = nymax - ny1*(nymax - nymin)/(visu._height - 32); if (y0>=0 && y1>=0) cimg_sprintf(message._data + std::strlen(message)," - Range ( %u:%g, %g ) - ( %u:%g, %g )", x0,cx0,cy0,x1 + one,cx1,cy1); else cimg_sprintf(message._data + std::strlen(message)," - Range [ %u:%g - %u:%g ]", x0,cx0,x1 + one,cx1); } text.assign().draw_text(0,0,message,white,ngray,1,13).resize(-100,-100,1,3); visu.draw_image((visu.width() - text.width())/2,1,~text); } visu.display(disp); } // Test keys. CImg<charT> filename(32); switch (okey = key) { #if cimg_OS!=2 case cimg::keyCTRLRIGHT : case cimg::keySHIFTRIGHT : #endif case cimg::keyCTRLLEFT : case cimg::keySHIFTLEFT : okey = 0; break; case cimg::keyD : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false). resize(CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,false), CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,true),false). _is_resized = true; disp.set_key(key,false); okey = 0; } break; case cimg::keyC : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false). resize(cimg_fitscreen(2*disp.width()/3,2*disp.height()/3,1),false)._is_resized = true; disp.set_key(key,false); okey = 0; } break; case cimg::keyR : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false). resize(cimg_fitscreen(CImgDisplay::screen_width()/2, CImgDisplay::screen_height()/2,1),false)._is_resized = true; disp.set_key(key,false); okey = 0; } break; case cimg::keyF : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.resize(disp.screen_width(),disp.screen_height(),false).toggle_fullscreen()._is_resized = true; disp.set_key(key,false); okey = 0; } break; case cimg::keyS : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { static unsigned int snap_number = 0; if (visu || visu0) { CImg<ucharT> &screen = visu?visu:visu0; std::FILE *file; do { cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.bmp",snap_number++); if ((file=cimg::std_fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); (+screen).__draw_text(" Saving snapshot... ",0).display(disp); screen.save(filename); (+screen).__draw_text(" Snapshot '%s' saved. ",0,filename._data).display(disp); } disp.set_key(key,false); okey = 0; } break; case cimg::keyO : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { static unsigned int snap_number = 0; if (visu || visu0) { CImg<ucharT> &screen = visu?visu:visu0; std::FILE *file; do { #ifdef cimg_use_zlib cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.cimgz",snap_number++); #else cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.cimg",snap_number++); #endif if ((file=cimg::std_fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); (+screen).__draw_text(" Saving instance... ",0).display(disp); save(filename); (+screen).__draw_text(" Instance '%s' saved. ",0,filename._data).display(disp); } disp.set_key(key,false); okey = 0; } break; } // Handle mouse motion and mouse buttons. if (obutton!=button || omouse_x!=mouse_x || omouse_y!=mouse_y) { visu.assign(); if (disp.mouse_x()>=0 && disp.mouse_y()>=0) { const int mx = (mouse_x - 16)*(int)(siz - one)/(disp.width() - 32), cx = cimg::cut(mx,0,(int)(siz - 1 - one)), my = mouse_y - 16, cy = cimg::cut(my,0,disp.height() - 32); if (button&1) { if (!obutton) { x0 = cx; y0 = -1; } else { x1 = cx; y1 = -1; } } else if (button&2) { if (!obutton) { x0 = cx; y0 = cy; } else { x1 = cx; y1 = cy; } } else if (obutton) { x1 = x1>=0?cx:-1; y1 = y1>=0?cy:-1; selected = true; } } else if (!button && obutton) selected = true; obutton = button; omouse_x = mouse_x; omouse_y = mouse_y; } if (disp.is_resized()) { disp.resize(false); visu0.assign(); } if (visu && visu0) disp.wait(); if (!exit_on_anykey && okey && okey!=cimg::keyESC && (okey!=cimg::keyW || (!disp.is_keyCTRLLEFT() && !disp.is_keyCTRLRIGHT()))) { disp.set_key(key,false); okey = 0; } } disp._normalization = old_normalization; if (x1>=0 && x1<x0) cimg::swap(x0,x1); if (y1<y0) cimg::swap(y0,y1); disp.set_key(okey); return CImg<intT>(4,1,1,1,x0,y0,x1>=0?x1 + (int)one:-1,y1); } //! Load image from a file. /** \param filename Filename, as a C-string. \note The extension of \c filename defines the file format. If no filename extension is provided, CImg<T>::get_load() will try to load the file as a .cimg or .cimgz file. **/ CImg<T>& load(const char *const filename) { if (!filename) throw CImgArgumentException(_cimg_instance "load(): Specified filename is (null).", cimg_instance); if (!cimg::strncasecmp(filename,"http://",7) || !cimg::strncasecmp(filename,"https://",8)) { CImg<charT> filename_local(256); load(cimg::load_network(filename,filename_local)); std::remove(filename_local); return *this; } const char *const ext = cimg::split_filename(filename); const unsigned int omode = cimg::exception_mode(); cimg::exception_mode(0); bool is_loaded = true; try { #ifdef cimg_load_plugin cimg_load_plugin(filename); #endif #ifdef cimg_load_plugin1 cimg_load_plugin1(filename); #endif #ifdef cimg_load_plugin2 cimg_load_plugin2(filename); #endif #ifdef cimg_load_plugin3 cimg_load_plugin3(filename); #endif #ifdef cimg_load_plugin4 cimg_load_plugin4(filename); #endif #ifdef cimg_load_plugin5 cimg_load_plugin5(filename); #endif #ifdef cimg_load_plugin6 cimg_load_plugin6(filename); #endif #ifdef cimg_load_plugin7 cimg_load_plugin7(filename); #endif #ifdef cimg_load_plugin8 cimg_load_plugin8(filename); #endif // Ascii formats if (!cimg::strcasecmp(ext,"asc")) load_ascii(filename); else if (!cimg::strcasecmp(ext,"dlm") || !cimg::strcasecmp(ext,"txt")) load_dlm(filename); // 2D binary formats else if (!cimg::strcasecmp(ext,"bmp")) load_bmp(filename); else if (!cimg::strcasecmp(ext,"jpg") || !cimg::strcasecmp(ext,"jpeg") || !cimg::strcasecmp(ext,"jpe") || !cimg::strcasecmp(ext,"jfif") || !cimg::strcasecmp(ext,"jif")) load_jpeg(filename); else if (!cimg::strcasecmp(ext,"png")) load_png(filename); else if (!cimg::strcasecmp(ext,"ppm") || !cimg::strcasecmp(ext,"pgm") || !cimg::strcasecmp(ext,"pnm") || !cimg::strcasecmp(ext,"pbm") || !cimg::strcasecmp(ext,"pnk")) load_pnm(filename); else if (!cimg::strcasecmp(ext,"pfm")) load_pfm(filename); else if (!cimg::strcasecmp(ext,"tif") || !cimg::strcasecmp(ext,"tiff")) load_tiff(filename); else if (!cimg::strcasecmp(ext,"exr")) load_exr(filename); else if (!cimg::strcasecmp(ext,"cr2") || !cimg::strcasecmp(ext,"crw") || !cimg::strcasecmp(ext,"dcr") || !cimg::strcasecmp(ext,"mrw") || !cimg::strcasecmp(ext,"nef") || !cimg::strcasecmp(ext,"orf") || !cimg::strcasecmp(ext,"pix") || !cimg::strcasecmp(ext,"ptx") || !cimg::strcasecmp(ext,"raf") || !cimg::strcasecmp(ext,"srf")) load_dcraw_external(filename); else if (!cimg::strcasecmp(ext,"gif")) load_gif_external(filename); // 3D binary formats else if (!cimg::strcasecmp(ext,"dcm") || !cimg::strcasecmp(ext,"dicom")) load_medcon_external(filename); else if (!cimg::strcasecmp(ext,"hdr") || !cimg::strcasecmp(ext,"nii")) load_analyze(filename); else if (!cimg::strcasecmp(ext,"par") || !cimg::strcasecmp(ext,"rec")) load_parrec(filename); else if (!cimg::strcasecmp(ext,"mnc")) load_minc2(filename); else if (!cimg::strcasecmp(ext,"inr")) load_inr(filename); else if (!cimg::strcasecmp(ext,"pan")) load_pandore(filename); else if (!cimg::strcasecmp(ext,"cimg") || !cimg::strcasecmp(ext,"cimgz") || !*ext) return load_cimg(filename); // Archive files else if (!cimg::strcasecmp(ext,"gz")) load_gzip_external(filename); // Image sequences else if (!cimg::strcasecmp(ext,"avi") || !cimg::strcasecmp(ext,"mov") || !cimg::strcasecmp(ext,"asf") || !cimg::strcasecmp(ext,"divx") || !cimg::strcasecmp(ext,"flv") || !cimg::strcasecmp(ext,"mpg") || !cimg::strcasecmp(ext,"m1v") || !cimg::strcasecmp(ext,"m2v") || !cimg::strcasecmp(ext,"m4v") || !cimg::strcasecmp(ext,"mjp") || !cimg::strcasecmp(ext,"mp4") || !cimg::strcasecmp(ext,"mkv") || !cimg::strcasecmp(ext,"mpe") || !cimg::strcasecmp(ext,"movie") || !cimg::strcasecmp(ext,"ogm") || !cimg::strcasecmp(ext,"ogg") || !cimg::strcasecmp(ext,"ogv") || !cimg::strcasecmp(ext,"qt") || !cimg::strcasecmp(ext,"rm") || !cimg::strcasecmp(ext,"vob") || !cimg::strcasecmp(ext,"wmv") || !cimg::strcasecmp(ext,"xvid") || !cimg::strcasecmp(ext,"mpeg")) load_video(filename); else is_loaded = false; } catch (CImgIOException&) { is_loaded = false; } // If nothing loaded, try to guess file format from magic number in file. if (!is_loaded) { std::FILE *file = cimg::std_fopen(filename,"rb"); if (!file) { cimg::exception_mode(omode); throw CImgIOException(_cimg_instance "load(): Failed to open file '%s'.", cimg_instance, filename); } const char *const f_type = cimg::ftype(file,filename); cimg::fclose(file); is_loaded = true; try { if (!cimg::strcasecmp(f_type,"pnm")) load_pnm(filename); else if (!cimg::strcasecmp(f_type,"pfm")) load_pfm(filename); else if (!cimg::strcasecmp(f_type,"bmp")) load_bmp(filename); else if (!cimg::strcasecmp(f_type,"inr")) load_inr(filename); else if (!cimg::strcasecmp(f_type,"jpg")) load_jpeg(filename); else if (!cimg::strcasecmp(f_type,"pan")) load_pandore(filename); else if (!cimg::strcasecmp(f_type,"png")) load_png(filename); else if (!cimg::strcasecmp(f_type,"tif")) load_tiff(filename); else if (!cimg::strcasecmp(f_type,"gif")) load_gif_external(filename); else if (!cimg::strcasecmp(f_type,"dcm")) load_medcon_external(filename); else is_loaded = false; } catch (CImgIOException&) { is_loaded = false; } } // If nothing loaded, try to load file with other means. if (!is_loaded) { try { load_other(filename); } catch (CImgIOException&) { cimg::exception_mode(omode); throw CImgIOException(_cimg_instance "load(): Failed to recognize format of file '%s'.", cimg_instance, filename); } } cimg::exception_mode(omode); return *this; } //! Load image from a file \newinstance. static CImg<T> get_load(const char *const filename) { return CImg<T>().load(filename); } //! Load image from an Ascii file. /** \param filename Filename, as a C -string. **/ CImg<T>& load_ascii(const char *const filename) { return _load_ascii(0,filename); } //! Load image from an Ascii file \inplace. static CImg<T> get_load_ascii(const char *const filename) { return CImg<T>().load_ascii(filename); } //! Load image from an Ascii file \overloading. CImg<T>& load_ascii(std::FILE *const file) { return _load_ascii(file,0); } //! Loadimage from an Ascii file \newinstance. static CImg<T> get_load_ascii(std::FILE *const file) { return CImg<T>().load_ascii(file); } CImg<T>& _load_ascii(std::FILE *const file, const char *const filename) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_ascii(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); CImg<charT> line(256); *line = 0; int err = std::fscanf(nfile,"%255[^\n]",line._data); unsigned int dx = 0, dy = 1, dz = 1, dc = 1; cimg_sscanf(line,"%u%*c%u%*c%u%*c%u",&dx,&dy,&dz,&dc); err = std::fscanf(nfile,"%*[^0-9.eEinfa+-]"); if (!dx || !dy || !dz || !dc) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_ascii(): Invalid Ascii header in file '%s', image dimensions are set " "to (%u,%u,%u,%u).", cimg_instance, filename?filename:"(FILE*)",dx,dy,dz,dc); } assign(dx,dy,dz,dc); const ulongT siz = size(); ulongT off = 0; double val; T *ptr = _data; for (err = 1, off = 0; off<siz && err==1; ++off) { err = std::fscanf(nfile,"%lf%*[^0-9.eEinfa+-]",&val); *(ptr++) = (T)val; } if (err!=1) cimg::warn(_cimg_instance "load_ascii(): Only %lu/%lu values read from file '%s'.", cimg_instance, off - 1,siz,filename?filename:"(FILE*)"); if (!file) cimg::fclose(nfile); return *this; } //! Load image from a DLM file. /** \param filename Filename, as a C-string. **/ CImg<T>& load_dlm(const char *const filename) { return _load_dlm(0,filename); } //! Load image from a DLM file \newinstance. static CImg<T> get_load_dlm(const char *const filename) { return CImg<T>().load_dlm(filename); } //! Load image from a DLM file \overloading. CImg<T>& load_dlm(std::FILE *const file) { return _load_dlm(file,0); } //! Load image from a DLM file \newinstance. static CImg<T> get_load_dlm(std::FILE *const file) { return CImg<T>().load_dlm(file); } CImg<T>& _load_dlm(std::FILE *const file, const char *const filename) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_dlm(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"r"); CImg<charT> delimiter(256), tmp(256); *delimiter = *tmp = 0; unsigned int cdx = 0, dx = 0, dy = 0; int err = 0; double val; assign(256,256,1,1,(T)0); while ((err = std::fscanf(nfile,"%lf%255[^0-9eEinfa.+-]",&val,delimiter._data))>0) { if (err>0) (*this)(cdx++,dy) = (T)val; if (cdx>=_width) resize(3*_width/2,_height,1,1,0); char c = 0; if (!cimg_sscanf(delimiter,"%255[^\n]%c",tmp._data,&c) || c=='\n') { dx = std::max(cdx,dx); if (++dy>=_height) resize(_width,3*_height/2,1,1,0); cdx = 0; } } if (cdx && err==1) { dx = cdx; ++dy; } if (!dx || !dy) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_dlm(): Invalid DLM file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } resize(dx,dy,1,1,0); if (!file) cimg::fclose(nfile); return *this; } //! Load image from a BMP file. /** \param filename Filename, as a C-string. **/ CImg<T>& load_bmp(const char *const filename) { return _load_bmp(0,filename); } //! Load image from a BMP file \newinstance. static CImg<T> get_load_bmp(const char *const filename) { return CImg<T>().load_bmp(filename); } //! Load image from a BMP file \overloading. CImg<T>& load_bmp(std::FILE *const file) { return _load_bmp(file,0); } //! Load image from a BMP file \newinstance. static CImg<T> get_load_bmp(std::FILE *const file) { return CImg<T>().load_bmp(file); } CImg<T>& _load_bmp(std::FILE *const file, const char *const filename) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_bmp(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); CImg<ucharT> header(54); cimg::fread(header._data,54,nfile); if (*header!='B' || header[1]!='M') { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_bmp(): Invalid BMP file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } // Read header and pixel buffer int file_size = header[0x02] + (header[0x03]<<8) + (header[0x04]<<16) + (header[0x05]<<24), offset = header[0x0A] + (header[0x0B]<<8) + (header[0x0C]<<16) + (header[0x0D]<<24), header_size = header[0x0E] + (header[0x0F]<<8) + (header[0x10]<<16) + (header[0x11]<<24), dx = header[0x12] + (header[0x13]<<8) + (header[0x14]<<16) + (header[0x15]<<24), dy = header[0x16] + (header[0x17]<<8) + (header[0x18]<<16) + (header[0x19]<<24), compression = header[0x1E] + (header[0x1F]<<8) + (header[0x20]<<16) + (header[0x21]<<24), nb_colors = header[0x2E] + (header[0x2F]<<8) + (header[0x30]<<16) + (header[0x31]<<24), bpp = header[0x1C] + (header[0x1D]<<8); if (!file_size || file_size==offset) { cimg::fseek(nfile,0,SEEK_END); file_size = (int)cimg::ftell(nfile); cimg::fseek(nfile,54,SEEK_SET); } if (header_size>40) cimg::fseek(nfile,header_size - 40,SEEK_CUR); const int dx_bytes = (bpp==1)?(dx/8 + (dx%8?1:0)):((bpp==4)?(dx/2 + (dx%2)):(int)((longT)dx*bpp/8)), align_bytes = (4 - dx_bytes%4)%4; const ulongT cimg_iobuffer = (ulongT)24*1024*1024, buf_size = std::min((ulongT)cimg::abs(dy)*(dx_bytes + align_bytes),(ulongT)file_size - offset); CImg<intT> colormap; if (bpp<16) { if (!nb_colors) nb_colors = 1<<bpp; } else nb_colors = 0; if (nb_colors) { colormap.assign(nb_colors); cimg::fread(colormap._data,nb_colors,nfile); } const int xoffset = offset - 14 - header_size - 4*nb_colors; if (xoffset>0) cimg::fseek(nfile,xoffset,SEEK_CUR); CImg<ucharT> buffer; if (buf_size<cimg_iobuffer) { buffer.assign(cimg::abs(dy)*(dx_bytes + align_bytes),1,1,1,0); cimg::fread(buffer._data,buf_size,nfile); } else buffer.assign(dx_bytes + align_bytes); unsigned char *ptrs = buffer; // Decompress buffer (if necessary) if (compression) { if (file) throw CImgIOException(_cimg_instance "load_bmp(): Unable to load compressed data from '(*FILE)' inputs.", cimg_instance); else { if (!file) cimg::fclose(nfile); return load_other(filename); } } // Read pixel data assign(dx,cimg::abs(dy),1,3,0); switch (bpp) { case 1 : { // Monochrome if (colormap._width>=2) for (int y = height() - 1; y>=0; --y) { if (buf_size>=cimg_iobuffer) { if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break; cimg::fseek(nfile,align_bytes,SEEK_CUR); } unsigned char mask = 0x80, val = 0; cimg_forX(*this,x) { if (mask==0x80) val = *(ptrs++); const unsigned char *col = (unsigned char*)(colormap._data + (val&mask?1:0)); (*this)(x,y,2) = (T)*(col++); (*this)(x,y,1) = (T)*(col++); (*this)(x,y,0) = (T)*(col++); mask = cimg::ror(mask); } ptrs+=align_bytes; } } break; case 4 : { // 16 colors if (colormap._width>=16) for (int y = height() - 1; y>=0; --y) { if (buf_size>=cimg_iobuffer) { if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break; cimg::fseek(nfile,align_bytes,SEEK_CUR); } unsigned char mask = 0xF0, val = 0; cimg_forX(*this,x) { if (mask==0xF0) val = *(ptrs++); const unsigned char color = (unsigned char)((mask<16)?(val&mask):((val&mask)>>4)); const unsigned char *col = (unsigned char*)(colormap._data + color); (*this)(x,y,2) = (T)*(col++); (*this)(x,y,1) = (T)*(col++); (*this)(x,y,0) = (T)*(col++); mask = cimg::ror(mask,4); } ptrs+=align_bytes; } } break; case 8 : { // 256 colors if (colormap._width>=256) for (int y = height() - 1; y>=0; --y) { if (buf_size>=cimg_iobuffer) { if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break; cimg::fseek(nfile,align_bytes,SEEK_CUR); } cimg_forX(*this,x) { const unsigned char *col = (unsigned char*)(colormap._data + *(ptrs++)); (*this)(x,y,2) = (T)*(col++); (*this)(x,y,1) = (T)*(col++); (*this)(x,y,0) = (T)*(col++); } ptrs+=align_bytes; } } break; case 16 : { // 16 bits colors for (int y = height() - 1; y>=0; --y) { if (buf_size>=cimg_iobuffer) { if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break; cimg::fseek(nfile,align_bytes,SEEK_CUR); } cimg_forX(*this,x) { const unsigned char c1 = *(ptrs++), c2 = *(ptrs++); const unsigned short col = (unsigned short)(c1|(c2<<8)); (*this)(x,y,2) = (T)(col&0x1F); (*this)(x,y,1) = (T)((col>>5)&0x1F); (*this)(x,y,0) = (T)((col>>10)&0x1F); } ptrs+=align_bytes; } } break; case 24 : { // 24 bits colors for (int y = height() - 1; y>=0; --y) { if (buf_size>=cimg_iobuffer) { if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break; cimg::fseek(nfile,align_bytes,SEEK_CUR); } cimg_forX(*this,x) { (*this)(x,y,2) = (T)*(ptrs++); (*this)(x,y,1) = (T)*(ptrs++); (*this)(x,y,0) = (T)*(ptrs++); } ptrs+=align_bytes; } } break; case 32 : { // 32 bits colors for (int y = height() - 1; y>=0; --y) { if (buf_size>=cimg_iobuffer) { if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break; cimg::fseek(nfile,align_bytes,SEEK_CUR); } cimg_forX(*this,x) { (*this)(x,y,2) = (T)*(ptrs++); (*this)(x,y,1) = (T)*(ptrs++); (*this)(x,y,0) = (T)*(ptrs++); ++ptrs; } ptrs+=align_bytes; } } break; } if (dy<0) mirror('y'); if (!file) cimg::fclose(nfile); return *this; } //! Load image from a JPEG file. /** \param filename Filename, as a C-string. **/ CImg<T>& load_jpeg(const char *const filename) { return _load_jpeg(0,filename); } //! Load image from a JPEG file \newinstance. static CImg<T> get_load_jpeg(const char *const filename) { return CImg<T>().load_jpeg(filename); } //! Load image from a JPEG file \overloading. CImg<T>& load_jpeg(std::FILE *const file) { return _load_jpeg(file,0); } //! Load image from a JPEG file \newinstance. static CImg<T> get_load_jpeg(std::FILE *const file) { return CImg<T>().load_jpeg(file); } // Custom error handler for libjpeg. #ifdef cimg_use_jpeg struct _cimg_error_mgr { struct jpeg_error_mgr original; jmp_buf setjmp_buffer; char message[JMSG_LENGTH_MAX]; }; typedef struct _cimg_error_mgr *_cimg_error_ptr; METHODDEF(void) _cimg_jpeg_error_exit(j_common_ptr cinfo) { _cimg_error_ptr c_err = (_cimg_error_ptr) cinfo->err; // Return control to the setjmp point (*cinfo->err->format_message)(cinfo,c_err->message); jpeg_destroy(cinfo); // Clean memory and temp files longjmp(c_err->setjmp_buffer,1); } #endif CImg<T>& _load_jpeg(std::FILE *const file, const char *const filename) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_jpeg(): Specified filename is (null).", cimg_instance); #ifndef cimg_use_jpeg if (file) throw CImgIOException(_cimg_instance "load_jpeg(): Unable to load data from '(FILE*)' unless libjpeg is enabled.", cimg_instance); else return load_other(filename); #else std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); struct jpeg_decompress_struct cinfo; struct _cimg_error_mgr jerr; cinfo.err = jpeg_std_error(&jerr.original); jerr.original.error_exit = _cimg_jpeg_error_exit; if (setjmp(jerr.setjmp_buffer)) { // JPEG error if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_jpeg(): Error message returned by libjpeg: %s.", cimg_instance,jerr.message); } jpeg_create_decompress(&cinfo); jpeg_stdio_src(&cinfo,nfile); jpeg_read_header(&cinfo,TRUE); jpeg_start_decompress(&cinfo); if (cinfo.output_components!=1 && cinfo.output_components!=3 && cinfo.output_components!=4) { if (!file) { cimg::fclose(nfile); return load_other(filename); } else throw CImgIOException(_cimg_instance "load_jpeg(): Failed to load JPEG data from file '%s'.", cimg_instance,filename?filename:"(FILE*)"); } CImg<ucharT> buffer(cinfo.output_width*cinfo.output_components); JSAMPROW row_pointer[1]; try { assign(cinfo.output_width,cinfo.output_height,1,cinfo.output_components); } catch (...) { if (!file) cimg::fclose(nfile); throw; } T *ptr_r = _data, *ptr_g = _data + 1UL*_width*_height, *ptr_b = _data + 2UL*_width*_height, *ptr_a = _data + 3UL*_width*_height; while (cinfo.output_scanline<cinfo.output_height) { *row_pointer = buffer._data; if (jpeg_read_scanlines(&cinfo,row_pointer,1)!=1) { cimg::warn(_cimg_instance "load_jpeg(): Incomplete data in file '%s'.", cimg_instance,filename?filename:"(FILE*)"); break; } const unsigned char *ptrs = buffer._data; switch (_spectrum) { case 1 : { cimg_forX(*this,x) *(ptr_r++) = (T)*(ptrs++); } break; case 3 : { cimg_forX(*this,x) { *(ptr_r++) = (T)*(ptrs++); *(ptr_g++) = (T)*(ptrs++); *(ptr_b++) = (T)*(ptrs++); } } break; case 4 : { cimg_forX(*this,x) { *(ptr_r++) = (T)*(ptrs++); *(ptr_g++) = (T)*(ptrs++); *(ptr_b++) = (T)*(ptrs++); *(ptr_a++) = (T)*(ptrs++); } } break; } } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); if (!file) cimg::fclose(nfile); return *this; #endif } //! Load image from a file, using Magick++ library. /** \param filename Filename, as a C-string. **/ // Added April/may 2006 by Christoph Hormann <chris_hormann@gmx.de> // This is experimental code, not much tested, use with care. CImg<T>& load_magick(const char *const filename) { if (!filename) throw CImgArgumentException(_cimg_instance "load_magick(): Specified filename is (null).", cimg_instance); #ifdef cimg_use_magick Magick::Image image(filename); const unsigned int W = image.size().width(), H = image.size().height(); switch (image.type()) { case Magick::PaletteMatteType : case Magick::TrueColorMatteType : case Magick::ColorSeparationType : { assign(W,H,1,4); T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2), *ptr_a = data(0,0,0,3); Magick::PixelPacket *pixels = image.getPixels(0,0,W,H); for (ulongT off = (ulongT)W*H; off; --off) { *(ptr_r++) = (T)(pixels->red); *(ptr_g++) = (T)(pixels->green); *(ptr_b++) = (T)(pixels->blue); *(ptr_a++) = (T)(pixels->opacity); ++pixels; } } break; case Magick::PaletteType : case Magick::TrueColorType : { assign(W,H,1,3); T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2); Magick::PixelPacket *pixels = image.getPixels(0,0,W,H); for (ulongT off = (ulongT)W*H; off; --off) { *(ptr_r++) = (T)(pixels->red); *(ptr_g++) = (T)(pixels->green); *(ptr_b++) = (T)(pixels->blue); ++pixels; } } break; case Magick::GrayscaleMatteType : { assign(W,H,1,2); T *ptr_r = data(0,0,0,0), *ptr_a = data(0,0,0,1); Magick::PixelPacket *pixels = image.getPixels(0,0,W,H); for (ulongT off = (ulongT)W*H; off; --off) { *(ptr_r++) = (T)(pixels->red); *(ptr_a++) = (T)(pixels->opacity); ++pixels; } } break; default : { assign(W,H,1,1); T *ptr_r = data(0,0,0,0); Magick::PixelPacket *pixels = image.getPixels(0,0,W,H); for (ulongT off = (ulongT)W*H; off; --off) { *(ptr_r++) = (T)(pixels->red); ++pixels; } } } return *this; #else throw CImgIOException(_cimg_instance "load_magick(): Unable to load file '%s' unless libMagick++ is enabled.", cimg_instance, filename); #endif } //! Load image from a file, using Magick++ library \newinstance. static CImg<T> get_load_magick(const char *const filename) { return CImg<T>().load_magick(filename); } //! Load image from a PNG file. /** \param filename Filename, as a C-string. \param[out] bits_per_pixel Number of bits per pixels used to store pixel values in the image file. **/ CImg<T>& load_png(const char *const filename, unsigned int *const bits_per_pixel=0) { return _load_png(0,filename,bits_per_pixel); } //! Load image from a PNG file \newinstance. static CImg<T> get_load_png(const char *const filename, unsigned int *const bits_per_pixel=0) { return CImg<T>().load_png(filename,bits_per_pixel); } //! Load image from a PNG file \overloading. CImg<T>& load_png(std::FILE *const file, unsigned int *const bits_per_pixel=0) { return _load_png(file,0,bits_per_pixel); } //! Load image from a PNG file \newinstance. static CImg<T> get_load_png(std::FILE *const file, unsigned int *const bits_per_pixel=0) { return CImg<T>().load_png(file,bits_per_pixel); } // (Note: Most of this function has been written by Eric Fausett) CImg<T>& _load_png(std::FILE *const file, const char *const filename, unsigned int *const bits_per_pixel) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_png(): Specified filename is (null).", cimg_instance); #ifndef cimg_use_png cimg::unused(bits_per_pixel); if (file) throw CImgIOException(_cimg_instance "load_png(): Unable to load data from '(FILE*)' unless libpng is enabled.", cimg_instance); else return load_other(filename); #else // Open file and check for PNG validity #if defined __GNUC__ const char *volatile nfilename = filename; // Use 'volatile' to avoid (wrong) g++ warning std::FILE *volatile nfile = file?file:cimg::fopen(nfilename,"rb"); #else const char *nfilename = filename; std::FILE *nfile = file?file:cimg::fopen(nfilename,"rb"); #endif unsigned char pngCheck[8] = { 0 }; cimg::fread(pngCheck,8,(std::FILE*)nfile); if (png_sig_cmp(pngCheck,0,8)) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_png(): Invalid PNG file '%s'.", cimg_instance, nfilename?nfilename:"(FILE*)"); } // Setup PNG structures for read png_voidp user_error_ptr = 0; png_error_ptr user_error_fn = 0, user_warning_fn = 0; png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,user_error_ptr,user_error_fn,user_warning_fn); if (!png_ptr) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_png(): Failed to initialize 'png_ptr' structure for file '%s'.", cimg_instance, nfilename?nfilename:"(FILE*)"); } png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { if (!file) cimg::fclose(nfile); png_destroy_read_struct(&png_ptr,(png_infopp)0,(png_infopp)0); throw CImgIOException(_cimg_instance "load_png(): Failed to initialize 'info_ptr' structure for file '%s'.", cimg_instance, nfilename?nfilename:"(FILE*)"); } png_infop end_info = png_create_info_struct(png_ptr); if (!end_info) { if (!file) cimg::fclose(nfile); png_destroy_read_struct(&png_ptr,&info_ptr,(png_infopp)0); throw CImgIOException(_cimg_instance "load_png(): Failed to initialize 'end_info' structure for file '%s'.", cimg_instance, nfilename?nfilename:"(FILE*)"); } // Error handling callback for png file reading if (setjmp(png_jmpbuf(png_ptr))) { if (!file) cimg::fclose((std::FILE*)nfile); png_destroy_read_struct(&png_ptr, &end_info, (png_infopp)0); throw CImgIOException(_cimg_instance "load_png(): Encountered unknown fatal error in libpng for file '%s'.", cimg_instance, nfilename?nfilename:"(FILE*)"); } png_init_io(png_ptr, nfile); png_set_sig_bytes(png_ptr, 8); // Get PNG Header Info up to data block png_read_info(png_ptr,info_ptr); png_uint_32 W, H; int bit_depth, color_type, interlace_type; bool is_gray = false; png_get_IHDR(png_ptr,info_ptr,&W,&H,&bit_depth,&color_type,&interlace_type,(int*)0,(int*)0); if (bits_per_pixel) *bits_per_pixel = (unsigned int)bit_depth; // Transforms to unify image data if (color_type==PNG_COLOR_TYPE_PALETTE) { png_set_palette_to_rgb(png_ptr); color_type = PNG_COLOR_TYPE_RGB; bit_depth = 8; } if (color_type==PNG_COLOR_TYPE_GRAY && bit_depth<8) { png_set_expand_gray_1_2_4_to_8(png_ptr); is_gray = true; bit_depth = 8; } if (png_get_valid(png_ptr,info_ptr,PNG_INFO_tRNS)) { png_set_tRNS_to_alpha(png_ptr); color_type |= PNG_COLOR_MASK_ALPHA; } if (color_type==PNG_COLOR_TYPE_GRAY || color_type==PNG_COLOR_TYPE_GRAY_ALPHA) { png_set_gray_to_rgb(png_ptr); color_type |= PNG_COLOR_MASK_COLOR; is_gray = true; } if (color_type==PNG_COLOR_TYPE_RGB) png_set_filler(png_ptr,0xffffU,PNG_FILLER_AFTER); png_read_update_info(png_ptr,info_ptr); if (bit_depth!=8 && bit_depth!=16) { if (!file) cimg::fclose(nfile); png_destroy_read_struct(&png_ptr,&end_info,(png_infopp)0); throw CImgIOException(_cimg_instance "load_png(): Invalid bit depth %u in file '%s'.", cimg_instance, bit_depth,nfilename?nfilename:"(FILE*)"); } const int byte_depth = bit_depth>>3; // Allocate memory for image reading png_bytep *const imgData = new png_bytep[H]; for (unsigned int row = 0; row<H; ++row) imgData[row] = new png_byte[(size_t)byte_depth*4*W]; png_read_image(png_ptr,imgData); png_read_end(png_ptr,end_info); // Read pixel data if (color_type!=PNG_COLOR_TYPE_RGB && color_type!=PNG_COLOR_TYPE_RGB_ALPHA) { if (!file) cimg::fclose(nfile); png_destroy_read_struct(&png_ptr,&end_info,(png_infopp)0); throw CImgIOException(_cimg_instance "load_png(): Invalid color coding type %u in file '%s'.", cimg_instance, color_type,nfilename?nfilename:"(FILE*)"); } const bool is_alpha = (color_type==PNG_COLOR_TYPE_RGBA); try { assign(W,H,1,(is_gray?1:3) + (is_alpha?1:0)); } catch (...) { if (!file) cimg::fclose(nfile); throw; } T *ptr_r = data(0,0,0,0), *ptr_g = is_gray?0:data(0,0,0,1), *ptr_b = is_gray?0:data(0,0,0,2), *ptr_a = !is_alpha?0:data(0,0,0,is_gray?1:3); switch (bit_depth) { case 8 : { cimg_forY(*this,y) { const unsigned char *ptrs = (unsigned char*)imgData[y]; cimg_forX(*this,x) { *(ptr_r++) = (T)*(ptrs++); if (ptr_g) *(ptr_g++) = (T)*(ptrs++); else ++ptrs; if (ptr_b) *(ptr_b++) = (T)*(ptrs++); else ++ptrs; if (ptr_a) *(ptr_a++) = (T)*(ptrs++); else ++ptrs; } } } break; case 16 : { cimg_forY(*this,y) { const unsigned short *ptrs = (unsigned short*)(imgData[y]); if (!cimg::endianness()) cimg::invert_endianness(ptrs,4*_width); cimg_forX(*this,x) { *(ptr_r++) = (T)*(ptrs++); if (ptr_g) *(ptr_g++) = (T)*(ptrs++); else ++ptrs; if (ptr_b) *(ptr_b++) = (T)*(ptrs++); else ++ptrs; if (ptr_a) *(ptr_a++) = (T)*(ptrs++); else ++ptrs; } } } break; } png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); // Deallocate image read memory cimg_forY(*this,n) delete[] imgData[n]; delete[] imgData; if (!file) cimg::fclose(nfile); return *this; #endif } //! Load image from a PNM file. /** \param filename Filename, as a C-string. **/ CImg<T>& load_pnm(const char *const filename) { return _load_pnm(0,filename); } //! Load image from a PNM file \newinstance. static CImg<T> get_load_pnm(const char *const filename) { return CImg<T>().load_pnm(filename); } //! Load image from a PNM file \overloading. CImg<T>& load_pnm(std::FILE *const file) { return _load_pnm(file,0); } //! Load image from a PNM file \newinstance. static CImg<T> get_load_pnm(std::FILE *const file) { return CImg<T>().load_pnm(file); } CImg<T>& _load_pnm(std::FILE *const file, const char *const filename) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_pnm(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); unsigned int ppm_type, W, H, D = 1, colormax = 255; CImg<charT> item(16384,1,1,1,0); int err, rval, gval, bval; const longT cimg_iobuffer = (longT)24*1024*1024; while ((err=std::fscanf(nfile,"%16383[^\n]",item.data()))!=EOF && (*item=='#' || !err)) std::fgetc(nfile); if (cimg_sscanf(item," P%u",&ppm_type)!=1) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_pnm(): PNM header not found in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } while ((err=std::fscanf(nfile," %16383[^\n]",item.data()))!=EOF && (*item=='#' || !err)) std::fgetc(nfile); if ((err=cimg_sscanf(item," %u %u %u %u",&W,&H,&D,&colormax))<2) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_pnm(): WIDTH and HEIGHT fields undefined in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } if (ppm_type!=1 && ppm_type!=4) { if (err==2 || (err==3 && (ppm_type==5 || ppm_type==7 || ppm_type==8 || ppm_type==9))) { while ((err=std::fscanf(nfile," %16383[^\n]",item.data()))!=EOF && (*item=='#' || !err)) std::fgetc(nfile); if (cimg_sscanf(item,"%u",&colormax)!=1) cimg::warn(_cimg_instance "load_pnm(): COLORMAX field is undefined in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } else { colormax = D; D = 1; } } std::fgetc(nfile); switch (ppm_type) { case 1 : { // 2D b&w Ascii assign(W,H,1,1); T* ptrd = _data; cimg_foroff(*this,off) { if (std::fscanf(nfile,"%d",&rval)>0) *(ptrd++) = (T)(rval?0:255); else break; } } break; case 2 : { // 2D grey Ascii assign(W,H,1,1); T* ptrd = _data; cimg_foroff(*this,off) { if (std::fscanf(nfile,"%d",&rval)>0) *(ptrd++) = (T)rval; else break; } } break; case 3 : { // 2D color Ascii assign(W,H,1,3); T *ptrd = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2); cimg_forXY(*this,x,y) { if (std::fscanf(nfile,"%d %d %d",&rval,&gval,&bval)==3) { *(ptrd++) = (T)rval; *(ptr_g++) = (T)gval; *(ptr_b++) = (T)bval; } else break; } } break; case 4 : { // 2D b&w binary (support 3D PINK extension) CImg<ucharT> raw; assign(W,H,D,1); T *ptrd = data(0,0,0,0); unsigned int w = 0, h = 0, d = 0; for (longT to_read = (longT)((W/8 + (W%8?1:0))*H*D); to_read>0; ) { raw.assign(std::min(to_read,cimg_iobuffer)); cimg::fread(raw._data,raw._width,nfile); to_read-=raw._width; const unsigned char *ptrs = raw._data; unsigned char mask = 0, val = 0; for (ulongT off = (ulongT)raw._width; off || mask; mask>>=1) { if (!mask) { if (off--) val = *(ptrs++); mask = 128; } *(ptrd++) = (T)((val&mask)?0:255); if (++w==W) { w = 0; mask = 0; if (++h==H) { h = 0; if (++d==D) break; }} } } } break; case 5 : case 7 : { // 2D/3D grey binary (support 3D PINK extension) if (colormax<256) { // 8 bits CImg<ucharT> raw; assign(W,H,D,1); T *ptrd = data(0,0,0,0); for (longT to_read = (longT)size(); to_read>0; ) { raw.assign(std::min(to_read,cimg_iobuffer)); cimg::fread(raw._data,raw._width,nfile); to_read-=raw._width; const unsigned char *ptrs = raw._data; for (ulongT off = (ulongT)raw._width; off; --off) *(ptrd++) = (T)*(ptrs++); } } else { // 16 bits CImg<ushortT> raw; assign(W,H,D,1); T *ptrd = data(0,0,0,0); for (longT to_read = (longT)size(); to_read>0; ) { raw.assign(std::min(to_read,cimg_iobuffer/2)); cimg::fread(raw._data,raw._width,nfile); if (!cimg::endianness()) cimg::invert_endianness(raw._data,raw._width); to_read-=raw._width; const unsigned short *ptrs = raw._data; for (ulongT off = (ulongT)raw._width; off; --off) *(ptrd++) = (T)*(ptrs++); } } } break; case 6 : { // 2D color binary if (colormax<256) { // 8 bits CImg<ucharT> raw; assign(W,H,1,3); T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2); for (longT to_read = (longT)size(); to_read>0; ) { raw.assign(std::min(to_read,cimg_iobuffer)); cimg::fread(raw._data,raw._width,nfile); to_read-=raw._width; const unsigned char *ptrs = raw._data; for (ulongT off = (ulongT)raw._width/3; off; --off) { *(ptr_r++) = (T)*(ptrs++); *(ptr_g++) = (T)*(ptrs++); *(ptr_b++) = (T)*(ptrs++); } } } else { // 16 bits CImg<ushortT> raw; assign(W,H,1,3); T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2); for (longT to_read = (longT)size(); to_read>0; ) { raw.assign(std::min(to_read,cimg_iobuffer/2)); cimg::fread(raw._data,raw._width,nfile); if (!cimg::endianness()) cimg::invert_endianness(raw._data,raw._width); to_read-=raw._width; const unsigned short *ptrs = raw._data; for (ulongT off = (ulongT)raw._width/3; off; --off) { *(ptr_r++) = (T)*(ptrs++); *(ptr_g++) = (T)*(ptrs++); *(ptr_b++) = (T)*(ptrs++); } } } } break; case 8 : { // 2D/3D grey binary with int32 integers (PINK extension) CImg<intT> raw; assign(W,H,D,1); T *ptrd = data(0,0,0,0); for (longT to_read = (longT)size(); to_read>0; ) { raw.assign(std::min(to_read,cimg_iobuffer)); cimg::fread(raw._data,raw._width,nfile); to_read-=raw._width; const int *ptrs = raw._data; for (ulongT off = (ulongT)raw._width; off; --off) *(ptrd++) = (T)*(ptrs++); } } break; case 9 : { // 2D/3D grey binary with float values (PINK extension) CImg<floatT> raw; assign(W,H,D,1); T *ptrd = data(0,0,0,0); for (longT to_read = (longT)size(); to_read>0; ) { raw.assign(std::min(to_read,cimg_iobuffer)); cimg::fread(raw._data,raw._width,nfile); to_read-=raw._width; const float *ptrs = raw._data; for (ulongT off = (ulongT)raw._width; off; --off) *(ptrd++) = (T)*(ptrs++); } } break; default : assign(); if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_pnm(): PNM type 'P%d' found, but type is not supported.", cimg_instance, filename?filename:"(FILE*)",ppm_type); } if (!file) cimg::fclose(nfile); return *this; } //! Load image from a PFM file. /** \param filename Filename, as a C-string. **/ CImg<T>& load_pfm(const char *const filename) { return _load_pfm(0,filename); } //! Load image from a PFM file \newinstance. static CImg<T> get_load_pfm(const char *const filename) { return CImg<T>().load_pfm(filename); } //! Load image from a PFM file \overloading. CImg<T>& load_pfm(std::FILE *const file) { return _load_pfm(file,0); } //! Load image from a PFM file \newinstance. static CImg<T> get_load_pfm(std::FILE *const file) { return CImg<T>().load_pfm(file); } CImg<T>& _load_pfm(std::FILE *const file, const char *const filename) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_pfm(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); char pfm_type; CImg<charT> item(16384,1,1,1,0); int W = 0, H = 0, err = 0; double scale = 0; while ((err=std::fscanf(nfile,"%16383[^\n]",item.data()))!=EOF && (*item=='#' || !err)) std::fgetc(nfile); if (cimg_sscanf(item," P%c",&pfm_type)!=1) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_pfm(): PFM header not found in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } while ((err=std::fscanf(nfile," %16383[^\n]",item.data()))!=EOF && (*item=='#' || !err)) std::fgetc(nfile); if ((err=cimg_sscanf(item," %d %d",&W,&H))<2) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_pfm(): WIDTH and HEIGHT fields are undefined in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } else if (W<=0 || H<=0) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_pfm(): WIDTH (%d) and HEIGHT (%d) fields are invalid in file '%s'.", cimg_instance,W,H, filename?filename:"(FILE*)"); } if (err==2) { while ((err=std::fscanf(nfile," %16383[^\n]",item.data()))!=EOF && (*item=='#' || !err)) std::fgetc(nfile); if (cimg_sscanf(item,"%lf",&scale)!=1) cimg::warn(_cimg_instance "load_pfm(): SCALE field is undefined in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } std::fgetc(nfile); const bool is_color = (pfm_type=='F'), is_inverted = (scale>0)!=cimg::endianness(); if (is_color) { assign(W,H,1,3,(T)0); CImg<floatT> buf(3*W); T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2); cimg_forY(*this,y) { cimg::fread(buf._data,3*W,nfile); if (is_inverted) cimg::invert_endianness(buf._data,3*W); const float *ptrs = buf._data; cimg_forX(*this,x) { *(ptr_r++) = (T)*(ptrs++); *(ptr_g++) = (T)*(ptrs++); *(ptr_b++) = (T)*(ptrs++); } } } else { assign(W,H,1,1,(T)0); CImg<floatT> buf(W); T *ptrd = data(0,0,0,0); cimg_forY(*this,y) { cimg::fread(buf._data,W,nfile); if (is_inverted) cimg::invert_endianness(buf._data,W); const float *ptrs = buf._data; cimg_forX(*this,x) *(ptrd++) = (T)*(ptrs++); } } if (!file) cimg::fclose(nfile); return mirror('y'); // Most of the .pfm files are flipped along the y-axis } //! Load image from a RGB file. /** \param filename Filename, as a C-string. \param dimw Width of the image buffer. \param dimh Height of the image buffer. **/ CImg<T>& load_rgb(const char *const filename, const unsigned int dimw, const unsigned int dimh=1) { return _load_rgb(0,filename,dimw,dimh); } //! Load image from a RGB file \newinstance. static CImg<T> get_load_rgb(const char *const filename, const unsigned int dimw, const unsigned int dimh=1) { return CImg<T>().load_rgb(filename,dimw,dimh); } //! Load image from a RGB file \overloading. CImg<T>& load_rgb(std::FILE *const file, const unsigned int dimw, const unsigned int dimh=1) { return _load_rgb(file,0,dimw,dimh); } //! Load image from a RGB file \newinstance. static CImg<T> get_load_rgb(std::FILE *const file, const unsigned int dimw, const unsigned int dimh=1) { return CImg<T>().load_rgb(file,dimw,dimh); } CImg<T>& _load_rgb(std::FILE *const file, const char *const filename, const unsigned int dimw, const unsigned int dimh) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_rgb(): Specified filename is (null).", cimg_instance); if (!dimw || !dimh) return assign(); const longT cimg_iobuffer = (longT)24*1024*1024; std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); CImg<ucharT> raw; assign(dimw,dimh,1,3); T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2); for (longT to_read = (longT)size(); to_read>0; ) { raw.assign(std::min(to_read,cimg_iobuffer)); cimg::fread(raw._data,raw._width,nfile); to_read-=raw._width; const unsigned char *ptrs = raw._data; for (ulongT off = raw._width/3UL; off; --off) { *(ptr_r++) = (T)*(ptrs++); *(ptr_g++) = (T)*(ptrs++); *(ptr_b++) = (T)*(ptrs++); } } if (!file) cimg::fclose(nfile); return *this; } //! Load image from a RGBA file. /** \param filename Filename, as a C-string. \param dimw Width of the image buffer. \param dimh Height of the image buffer. **/ CImg<T>& load_rgba(const char *const filename, const unsigned int dimw, const unsigned int dimh=1) { return _load_rgba(0,filename,dimw,dimh); } //! Load image from a RGBA file \newinstance. static CImg<T> get_load_rgba(const char *const filename, const unsigned int dimw, const unsigned int dimh=1) { return CImg<T>().load_rgba(filename,dimw,dimh); } //! Load image from a RGBA file \overloading. CImg<T>& load_rgba(std::FILE *const file, const unsigned int dimw, const unsigned int dimh=1) { return _load_rgba(file,0,dimw,dimh); } //! Load image from a RGBA file \newinstance. static CImg<T> get_load_rgba(std::FILE *const file, const unsigned int dimw, const unsigned int dimh=1) { return CImg<T>().load_rgba(file,dimw,dimh); } CImg<T>& _load_rgba(std::FILE *const file, const char *const filename, const unsigned int dimw, const unsigned int dimh) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_rgba(): Specified filename is (null).", cimg_instance); if (!dimw || !dimh) return assign(); const longT cimg_iobuffer = (longT)24*1024*1024; std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); CImg<ucharT> raw; assign(dimw,dimh,1,4); T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2), *ptr_a = data(0,0,0,3); for (longT to_read = (longT)size(); to_read>0; ) { raw.assign(std::min(to_read,cimg_iobuffer)); cimg::fread(raw._data,raw._width,nfile); to_read-=raw._width; const unsigned char *ptrs = raw._data; for (ulongT off = raw._width/4UL; off; --off) { *(ptr_r++) = (T)*(ptrs++); *(ptr_g++) = (T)*(ptrs++); *(ptr_b++) = (T)*(ptrs++); *(ptr_a++) = (T)*(ptrs++); } } if (!file) cimg::fclose(nfile); return *this; } //! Load image from a TIFF file. /** \param filename Filename, as a C-string. \param first_frame First frame to read (for multi-pages tiff). \param last_frame Last frame to read (for multi-pages tiff). \param step_frame Step value of frame reading. \param[out] voxel_size Voxel size, as stored in the filename. \param[out] description Description, as stored in the filename. \note - libtiff support is enabled by defining the precompilation directive \c cimg_use_tif. - When libtiff is enabled, 2D and 3D (multipage) several channel per pixel are supported for <tt>char,uchar,short,ushort,float</tt> and \c double pixel types. - If \c cimg_use_tif is not defined at compile time the function uses CImg<T>& load_other(const char*). **/ CImg<T>& load_tiff(const char *const filename, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, float *const voxel_size=0, CImg<charT> *const description=0) { if (!filename) throw CImgArgumentException(_cimg_instance "load_tiff(): Specified filename is (null).", cimg_instance); const unsigned int nfirst_frame = first_frame<last_frame?first_frame:last_frame, nstep_frame = step_frame?step_frame:1; unsigned int nlast_frame = first_frame<last_frame?last_frame:first_frame; #ifndef cimg_use_tiff cimg::unused(voxel_size,description); if (nfirst_frame || nlast_frame!=~0U || nstep_frame>1) throw CImgArgumentException(_cimg_instance "load_tiff(): Unable to read sub-images from file '%s' unless libtiff is enabled.", cimg_instance, filename); return load_other(filename); #else #if cimg_verbosity<3 TIFFSetWarningHandler(0); TIFFSetErrorHandler(0); #endif TIFF *tif = TIFFOpen(filename,"r"); if (tif) { unsigned int nb_images = 0; do ++nb_images; while (TIFFReadDirectory(tif)); if (nfirst_frame>=nb_images || (nlast_frame!=~0U && nlast_frame>=nb_images)) cimg::warn(_cimg_instance "load_tiff(): File '%s' contains %u image(s) while specified frame range is [%u,%u] (step %u).", cimg_instance, filename,nb_images,nfirst_frame,nlast_frame,nstep_frame); if (nfirst_frame>=nb_images) return assign(); if (nlast_frame>=nb_images) nlast_frame = nb_images - 1; TIFFSetDirectory(tif,0); CImg<T> frame; for (unsigned int l = nfirst_frame; l<=nlast_frame; l+=nstep_frame) { frame._load_tiff(tif,l,voxel_size,description); if (l==nfirst_frame) assign(frame._width,frame._height,1 + (nlast_frame - nfirst_frame)/nstep_frame,frame._spectrum); if (frame._width>_width || frame._height>_height || frame._spectrum>_spectrum) resize(std::max(frame._width,_width), std::max(frame._height,_height),-100, std::max(frame._spectrum,_spectrum),0); draw_image(0,0,(l - nfirst_frame)/nstep_frame,frame); } TIFFClose(tif); } else throw CImgIOException(_cimg_instance "load_tiff(): Failed to open file '%s'.", cimg_instance, filename); return *this; #endif } //! Load image from a TIFF file \newinstance. static CImg<T> get_load_tiff(const char *const filename, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, float *const voxel_size=0, CImg<charT> *const description=0) { return CImg<T>().load_tiff(filename,first_frame,last_frame,step_frame,voxel_size,description); } // (Original contribution by Jerome Boulanger). #ifdef cimg_use_tiff template<typename t> void _load_tiff_tiled_contig(TIFF *const tif, const uint16 samplesperpixel, const uint32 nx, const uint32 ny, const uint32 tw, const uint32 th) { t *const buf = (t*)_TIFFmalloc(TIFFTileSize(tif)); if (buf) { for (unsigned int row = 0; row<ny; row+=th) for (unsigned int col = 0; col<nx; col+=tw) { if (TIFFReadTile(tif,buf,col,row,0,0)<0) { _TIFFfree(buf); TIFFClose(tif); throw CImgIOException(_cimg_instance "load_tiff(): Invalid tile in file '%s'.", cimg_instance, TIFFFileName(tif)); } const t *ptr = buf; for (unsigned int rr = row; rr<std::min((unsigned int)(row + th),(unsigned int)ny); ++rr) for (unsigned int cc = col; cc<std::min((unsigned int)(col + tw),(unsigned int)nx); ++cc) for (unsigned int vv = 0; vv<samplesperpixel; ++vv) (*this)(cc,rr,vv) = (T)(ptr[(rr - row)*th*samplesperpixel + (cc - col)*samplesperpixel + vv]); } _TIFFfree(buf); } } template<typename t> void _load_tiff_tiled_separate(TIFF *const tif, const uint16 samplesperpixel, const uint32 nx, const uint32 ny, const uint32 tw, const uint32 th) { t *const buf = (t*)_TIFFmalloc(TIFFTileSize(tif)); if (buf) { for (unsigned int vv = 0; vv<samplesperpixel; ++vv) for (unsigned int row = 0; row<ny; row+=th) for (unsigned int col = 0; col<nx; col+=tw) { if (TIFFReadTile(tif,buf,col,row,0,vv)<0) { _TIFFfree(buf); TIFFClose(tif); throw CImgIOException(_cimg_instance "load_tiff(): Invalid tile in file '%s'.", cimg_instance, TIFFFileName(tif)); } const t *ptr = buf; for (unsigned int rr = row; rr<std::min((unsigned int)(row + th),(unsigned int)ny); ++rr) for (unsigned int cc = col; cc<std::min((unsigned int)(col + tw),(unsigned int)nx); ++cc) (*this)(cc,rr,vv) = (T)*(ptr++); } _TIFFfree(buf); } } template<typename t> void _load_tiff_contig(TIFF *const tif, const uint16 samplesperpixel, const uint32 nx, const uint32 ny) { t *const buf = (t*)_TIFFmalloc(TIFFStripSize(tif)); if (buf) { uint32 row, rowsperstrip = (uint32)-1; TIFFGetField(tif,TIFFTAG_ROWSPERSTRIP,&rowsperstrip); for (row = 0; row<ny; row+= rowsperstrip) { uint32 nrow = (row + rowsperstrip>ny?ny - row:rowsperstrip); tstrip_t strip = TIFFComputeStrip(tif, row, 0); if ((TIFFReadEncodedStrip(tif,strip,buf,-1))<0) { _TIFFfree(buf); TIFFClose(tif); throw CImgIOException(_cimg_instance "load_tiff(): Invalid strip in file '%s'.", cimg_instance, TIFFFileName(tif)); } const t *ptr = buf; for (unsigned int rr = 0; rr<nrow; ++rr) for (unsigned int cc = 0; cc<nx; ++cc) for (unsigned int vv = 0; vv<samplesperpixel; ++vv) (*this)(cc,row + rr,vv) = (T)*(ptr++); } _TIFFfree(buf); } } template<typename t> void _load_tiff_separate(TIFF *const tif, const uint16 samplesperpixel, const uint32 nx, const uint32 ny) { t *buf = (t*)_TIFFmalloc(TIFFStripSize(tif)); if (buf) { uint32 row, rowsperstrip = (uint32)-1; TIFFGetField(tif,TIFFTAG_ROWSPERSTRIP,&rowsperstrip); for (unsigned int vv = 0; vv<samplesperpixel; ++vv) for (row = 0; row<ny; row+= rowsperstrip) { uint32 nrow = (row + rowsperstrip>ny?ny - row:rowsperstrip); tstrip_t strip = TIFFComputeStrip(tif, row, vv); if ((TIFFReadEncodedStrip(tif,strip,buf,-1))<0) { _TIFFfree(buf); TIFFClose(tif); throw CImgIOException(_cimg_instance "load_tiff(): Invalid strip in file '%s'.", cimg_instance, TIFFFileName(tif)); } const t *ptr = buf; for (unsigned int rr = 0;rr<nrow; ++rr) for (unsigned int cc = 0; cc<nx; ++cc) (*this)(cc,row + rr,vv) = (T)*(ptr++); } _TIFFfree(buf); } } CImg<T>& _load_tiff(TIFF *const tif, const unsigned int directory, float *const voxel_size, CImg<charT> *const description) { if (!TIFFSetDirectory(tif,directory)) return assign(); uint16 samplesperpixel = 1, bitspersample = 8, photo = 0; uint16 sampleformat = 1; uint32 nx = 1, ny = 1; const char *const filename = TIFFFileName(tif); const bool is_spp = (bool)TIFFGetField(tif,TIFFTAG_SAMPLESPERPIXEL,&samplesperpixel); TIFFGetField(tif,TIFFTAG_IMAGEWIDTH,&nx); TIFFGetField(tif,TIFFTAG_IMAGELENGTH,&ny); TIFFGetField(tif, TIFFTAG_SAMPLEFORMAT, &sampleformat); TIFFGetFieldDefaulted(tif,TIFFTAG_BITSPERSAMPLE,&bitspersample); TIFFGetField(tif,TIFFTAG_PHOTOMETRIC,&photo); if (voxel_size) { const char *s_description = 0; float vx = 0, vy = 0, vz = 0; if (TIFFGetField(tif,TIFFTAG_IMAGEDESCRIPTION,&s_description) && s_description) { const char *s_desc = std::strstr(s_description,"VX="); if (s_desc && cimg_sscanf(s_desc,"VX=%f VY=%f VZ=%f",&vx,&vy,&vz)==3) { // CImg format voxel_size[0] = vx; voxel_size[1] = vy; voxel_size[2] = vz; } s_desc = std::strstr(s_description,"spacing="); if (s_desc && cimg_sscanf(s_desc,"spacing=%f",&vz)==1) { // Fiji format voxel_size[2] = vz; } } TIFFGetField(tif,TIFFTAG_XRESOLUTION,voxel_size); TIFFGetField(tif,TIFFTAG_YRESOLUTION,voxel_size + 1); voxel_size[0] = 1.f/voxel_size[0]; voxel_size[1] = 1.f/voxel_size[1]; } if (description) { const char *s_description = 0; if (TIFFGetField(tif,TIFFTAG_IMAGEDESCRIPTION,&s_description) && s_description) CImg<charT>::string(s_description).move_to(*description); } const unsigned int spectrum = !is_spp || photo>=3?(photo>1?3:1):samplesperpixel; assign(nx,ny,1,spectrum); if ((photo>=3 && sampleformat==1 && (bitspersample==4 || bitspersample==8) && (samplesperpixel==1 || samplesperpixel==3 || samplesperpixel==4)) || (bitspersample==1 && samplesperpixel==1)) { // Special case for unsigned color images. uint32 *const raster = (uint32*)_TIFFmalloc(nx*ny*sizeof(uint32)); if (!raster) { _TIFFfree(raster); TIFFClose(tif); throw CImgException(_cimg_instance "load_tiff(): Failed to allocate memory (%s) for file '%s'.", cimg_instance, cimg::strbuffersize(nx*ny*sizeof(uint32)),filename); } TIFFReadRGBAImage(tif,nx,ny,raster,0); switch (spectrum) { case 1 : cimg_forXY(*this,x,y) (*this)(x,y,0) = (T)(float)TIFFGetR(raster[nx*(ny - 1 -y) + x]); break; case 3 : cimg_forXY(*this,x,y) { (*this)(x,y,0) = (T)(float)TIFFGetR(raster[nx*(ny - 1 -y) + x]); (*this)(x,y,1) = (T)(float)TIFFGetG(raster[nx*(ny - 1 -y) + x]); (*this)(x,y,2) = (T)(float)TIFFGetB(raster[nx*(ny - 1 -y) + x]); } break; case 4 : cimg_forXY(*this,x,y) { (*this)(x,y,0) = (T)(float)TIFFGetR(raster[nx*(ny - 1 - y) + x]); (*this)(x,y,1) = (T)(float)TIFFGetG(raster[nx*(ny - 1 - y) + x]); (*this)(x,y,2) = (T)(float)TIFFGetB(raster[nx*(ny - 1 - y) + x]); (*this)(x,y,3) = (T)(float)TIFFGetA(raster[nx*(ny - 1 - y) + x]); } break; } _TIFFfree(raster); } else { // Other cases uint16 config; TIFFGetField(tif,TIFFTAG_PLANARCONFIG,&config); if (TIFFIsTiled(tif)) { uint32 tw = 1, th = 1; TIFFGetField(tif,TIFFTAG_TILEWIDTH,&tw); TIFFGetField(tif,TIFFTAG_TILELENGTH,&th); if (config==PLANARCONFIG_CONTIG) switch (bitspersample) { case 8 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_tiled_contig<unsigned char>(tif,samplesperpixel,nx,ny,tw,th); else _load_tiff_tiled_contig<signed char>(tif,samplesperpixel,nx,ny,tw,th); break; case 16 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_tiled_contig<unsigned short>(tif,samplesperpixel,nx,ny,tw,th); else _load_tiff_tiled_contig<short>(tif,samplesperpixel,nx,ny,tw,th); break; case 32 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_tiled_contig<unsigned int>(tif,samplesperpixel,nx,ny,tw,th); else if (sampleformat==SAMPLEFORMAT_INT) _load_tiff_tiled_contig<int>(tif,samplesperpixel,nx,ny,tw,th); else _load_tiff_tiled_contig<float>(tif,samplesperpixel,nx,ny,tw,th); break; case 64 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_tiled_contig<uint64T>(tif,samplesperpixel,nx,ny,tw,th); else if (sampleformat==SAMPLEFORMAT_INT) _load_tiff_tiled_contig<int64T>(tif,samplesperpixel,nx,ny,tw,th); else _load_tiff_tiled_contig<double>(tif,samplesperpixel,nx,ny,tw,th); break; } else switch (bitspersample) { case 8 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_tiled_separate<unsigned char>(tif,samplesperpixel,nx,ny,tw,th); else _load_tiff_tiled_separate<signed char>(tif,samplesperpixel,nx,ny,tw,th); break; case 16 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_tiled_separate<unsigned short>(tif,samplesperpixel,nx,ny,tw,th); else _load_tiff_tiled_separate<short>(tif,samplesperpixel,nx,ny,tw,th); break; case 32 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_tiled_separate<unsigned int>(tif,samplesperpixel,nx,ny,tw,th); else if (sampleformat==SAMPLEFORMAT_INT) _load_tiff_tiled_separate<int>(tif,samplesperpixel,nx,ny,tw,th); else _load_tiff_tiled_separate<float>(tif,samplesperpixel,nx,ny,tw,th); break; case 64 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_tiled_separate<uint64T>(tif,samplesperpixel,nx,ny,tw,th); else if (sampleformat==SAMPLEFORMAT_INT) _load_tiff_tiled_separate<int64T>(tif,samplesperpixel,nx,ny,tw,th); else _load_tiff_tiled_separate<double>(tif,samplesperpixel,nx,ny,tw,th); break; } } else { if (config==PLANARCONFIG_CONTIG) switch (bitspersample) { case 8 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_contig<unsigned char>(tif,samplesperpixel,nx,ny); else _load_tiff_contig<signed char>(tif,samplesperpixel,nx,ny); break; case 16 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_contig<unsigned short>(tif,samplesperpixel,nx,ny); else _load_tiff_contig<short>(tif,samplesperpixel,nx,ny); break; case 32 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_contig<unsigned int>(tif,samplesperpixel,nx,ny); else if (sampleformat==SAMPLEFORMAT_INT) _load_tiff_contig<int>(tif,samplesperpixel,nx,ny); else _load_tiff_contig<float>(tif,samplesperpixel,nx,ny); break; case 64 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_contig<uint64T>(tif,samplesperpixel,nx,ny); else if (sampleformat==SAMPLEFORMAT_INT) _load_tiff_contig<int64T>(tif,samplesperpixel,nx,ny); else _load_tiff_contig<double>(tif,samplesperpixel,nx,ny); break; } else switch (bitspersample) { case 8 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_separate<unsigned char>(tif,samplesperpixel,nx,ny); else _load_tiff_separate<signed char>(tif,samplesperpixel,nx,ny); break; case 16 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_separate<unsigned short>(tif,samplesperpixel,nx,ny); else _load_tiff_separate<short>(tif,samplesperpixel,nx,ny); break; case 32 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_separate<unsigned int>(tif,samplesperpixel,nx,ny); else if (sampleformat==SAMPLEFORMAT_INT) _load_tiff_separate<int>(tif,samplesperpixel,nx,ny); else _load_tiff_separate<float>(tif,samplesperpixel,nx,ny); break; case 64 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_separate<uint64T>(tif,samplesperpixel,nx,ny); else if (sampleformat==SAMPLEFORMAT_INT) _load_tiff_separate<int64T>(tif,samplesperpixel,nx,ny); else _load_tiff_separate<double>(tif,samplesperpixel,nx,ny); break; } } } return *this; } #endif //! Load image from a MINC2 file. /** \param filename Filename, as a C-string. **/ // (Original code by Haz-Edine Assemlal). CImg<T>& load_minc2(const char *const filename) { if (!filename) throw CImgArgumentException(_cimg_instance "load_minc2(): Specified filename is (null).", cimg_instance); #ifndef cimg_use_minc2 return load_other(filename); #else minc::minc_1_reader rdr; rdr.open(filename); assign(rdr.ndim(1)?rdr.ndim(1):1, rdr.ndim(2)?rdr.ndim(2):1, rdr.ndim(3)?rdr.ndim(3):1, rdr.ndim(4)?rdr.ndim(4):1); if (cimg::type<T>::string()==cimg::type<unsigned char>::string()) rdr.setup_read_byte(); else if (cimg::type<T>::string()==cimg::type<int>::string()) rdr.setup_read_int(); else if (cimg::type<T>::string()==cimg::type<double>::string()) rdr.setup_read_double(); else rdr.setup_read_float(); minc::load_standard_volume(rdr,this->_data); return *this; #endif } //! Load image from a MINC2 file \newinstance. static CImg<T> get_load_minc2(const char *const filename) { return CImg<T>().load_analyze(filename); } //! Load image from an ANALYZE7.5/NIFTI file. /** \param filename Filename, as a C-string. \param[out] voxel_size Pointer to the three voxel sizes read from the file. **/ CImg<T>& load_analyze(const char *const filename, float *const voxel_size=0) { return _load_analyze(0,filename,voxel_size); } //! Load image from an ANALYZE7.5/NIFTI file \newinstance. static CImg<T> get_load_analyze(const char *const filename, float *const voxel_size=0) { return CImg<T>().load_analyze(filename,voxel_size); } //! Load image from an ANALYZE7.5/NIFTI file \overloading. CImg<T>& load_analyze(std::FILE *const file, float *const voxel_size=0) { return _load_analyze(file,0,voxel_size); } //! Load image from an ANALYZE7.5/NIFTI file \newinstance. static CImg<T> get_load_analyze(std::FILE *const file, float *const voxel_size=0) { return CImg<T>().load_analyze(file,voxel_size); } CImg<T>& _load_analyze(std::FILE *const file, const char *const filename, float *const voxel_size=0) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_analyze(): Specified filename is (null).", cimg_instance); std::FILE *nfile_header = 0, *nfile = 0; if (!file) { CImg<charT> body(1024); const char *const ext = cimg::split_filename(filename,body); if (!cimg::strcasecmp(ext,"hdr")) { // File is an Analyze header file nfile_header = cimg::fopen(filename,"rb"); cimg_sprintf(body._data + std::strlen(body),".img"); nfile = cimg::fopen(body,"rb"); } else if (!cimg::strcasecmp(ext,"img")) { // File is an Analyze data file nfile = cimg::fopen(filename,"rb"); cimg_sprintf(body._data + std::strlen(body),".hdr"); nfile_header = cimg::fopen(body,"rb"); } else nfile_header = nfile = cimg::fopen(filename,"rb"); // File is a Niftii file } else nfile_header = nfile = file; // File is a Niftii file if (!nfile || !nfile_header) throw CImgIOException(_cimg_instance "load_analyze(): Invalid Analyze7.5 or NIFTI header in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); // Read header. bool endian = false; unsigned int header_size; cimg::fread(&header_size,1,nfile_header); if (!header_size) throw CImgIOException(_cimg_instance "load_analyze(): Invalid zero-size header in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); if (header_size>=4096) { endian = true; cimg::invert_endianness(header_size); } unsigned char *const header = new unsigned char[header_size]; cimg::fread(header + 4,header_size - 4,nfile_header); if (!file && nfile_header!=nfile) cimg::fclose(nfile_header); if (endian) { cimg::invert_endianness((short*)(header + 40),5); cimg::invert_endianness((short*)(header + 70),1); cimg::invert_endianness((short*)(header + 72),1); cimg::invert_endianness((float*)(header + 76),4); cimg::invert_endianness((float*)(header + 108),1); cimg::invert_endianness((float*)(header + 112),1); } if (nfile_header==nfile) { const unsigned int vox_offset = (unsigned int)*(float*)(header + 108); std::fseek(nfile,vox_offset,SEEK_SET); } unsigned short *dim = (unsigned short*)(header + 40), dimx = 1, dimy = 1, dimz = 1, dimv = 1; if (!dim[0]) cimg::warn(_cimg_instance "load_analyze(): File '%s' defines an image with zero dimensions.", cimg_instance, filename?filename:"(FILE*)"); if (dim[0]>4) cimg::warn(_cimg_instance "load_analyze(): File '%s' defines an image with %u dimensions, reading only the 4 first.", cimg_instance, filename?filename:"(FILE*)",dim[0]); if (dim[0]>=1) dimx = dim[1]; if (dim[0]>=2) dimy = dim[2]; if (dim[0]>=3) dimz = dim[3]; if (dim[0]>=4) dimv = dim[4]; float scalefactor = *(float*)(header + 112); if (scalefactor==0) scalefactor = 1; const unsigned short datatype = *(unsigned short*)(header + 70); if (voxel_size) { const float *vsize = (float*)(header + 76); voxel_size[0] = vsize[1]; voxel_size[1] = vsize[2]; voxel_size[2] = vsize[3]; } delete[] header; // Read pixel data. assign(dimx,dimy,dimz,dimv); const size_t pdim = (size_t)dimx*dimy*dimz*dimv; switch (datatype) { case 2 : { unsigned char *const buffer = new unsigned char[pdim]; cimg::fread(buffer,pdim,nfile); cimg_foroff(*this,off) _data[off] = (T)(buffer[off]*scalefactor); delete[] buffer; } break; case 4 : { short *const buffer = new short[pdim]; cimg::fread(buffer,pdim,nfile); if (endian) cimg::invert_endianness(buffer,pdim); cimg_foroff(*this,off) _data[off] = (T)(buffer[off]*scalefactor); delete[] buffer; } break; case 8 : { int *const buffer = new int[pdim]; cimg::fread(buffer,pdim,nfile); if (endian) cimg::invert_endianness(buffer,pdim); cimg_foroff(*this,off) _data[off] = (T)(buffer[off]*scalefactor); delete[] buffer; } break; case 16 : { float *const buffer = new float[pdim]; cimg::fread(buffer,pdim,nfile); if (endian) cimg::invert_endianness(buffer,pdim); cimg_foroff(*this,off) _data[off] = (T)(buffer[off]*scalefactor); delete[] buffer; } break; case 64 : { double *const buffer = new double[pdim]; cimg::fread(buffer,pdim,nfile); if (endian) cimg::invert_endianness(buffer,pdim); cimg_foroff(*this,off) _data[off] = (T)(buffer[off]*scalefactor); delete[] buffer; } break; default : if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_analyze(): Unable to load datatype %d in file '%s'", cimg_instance, datatype,filename?filename:"(FILE*)"); } if (!file) cimg::fclose(nfile); return *this; } //! Load image from a .cimg[z] file. /** \param filename Filename, as a C-string. \param axis Appending axis, if file contains multiple images. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param align Appending alignment. **/ CImg<T>& load_cimg(const char *const filename, const char axis='z', const float align=0) { CImgList<T> list; list.load_cimg(filename); if (list._width==1) return list[0].move_to(*this); return assign(list.get_append(axis,align)); } //! Load image from a .cimg[z] file \newinstance static CImg<T> get_load_cimg(const char *const filename, const char axis='z', const float align=0) { return CImg<T>().load_cimg(filename,axis,align); } //! Load image from a .cimg[z] file \overloading. CImg<T>& load_cimg(std::FILE *const file, const char axis='z', const float align=0) { CImgList<T> list; list.load_cimg(file); if (list._width==1) return list[0].move_to(*this); return assign(list.get_append(axis,align)); } //! Load image from a .cimg[z] file \newinstance static CImg<T> get_load_cimg(std::FILE *const file, const char axis='z', const float align=0) { return CImg<T>().load_cimg(file,axis,align); } //! Load sub-images of a .cimg file. /** \param filename Filename, as a C-string. \param n0 Starting frame. \param n1 Ending frame (~0U for max). \param x0 X-coordinate of the starting sub-image vertex. \param y0 Y-coordinate of the starting sub-image vertex. \param z0 Z-coordinate of the starting sub-image vertex. \param c0 C-coordinate of the starting sub-image vertex. \param x1 X-coordinate of the ending sub-image vertex (~0U for max). \param y1 Y-coordinate of the ending sub-image vertex (~0U for max). \param z1 Z-coordinate of the ending sub-image vertex (~0U for max). \param c1 C-coordinate of the ending sub-image vertex (~0U for max). \param axis Appending axis, if file contains multiple images. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param align Appending alignment. **/ CImg<T>& load_cimg(const char *const filename, const unsigned int n0, const unsigned int n1, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0, const unsigned int x1, const unsigned int y1, const unsigned int z1, const unsigned int c1, const char axis='z', const float align=0) { CImgList<T> list; list.load_cimg(filename,n0,n1,x0,y0,z0,c0,x1,y1,z1,c1); if (list._width==1) return list[0].move_to(*this); return assign(list.get_append(axis,align)); } //! Load sub-images of a .cimg file \newinstance. static CImg<T> get_load_cimg(const char *const filename, const unsigned int n0, const unsigned int n1, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0, const unsigned int x1, const unsigned int y1, const unsigned int z1, const unsigned int c1, const char axis='z', const float align=0) { return CImg<T>().load_cimg(filename,n0,n1,x0,y0,z0,c0,x1,y1,z1,c1,axis,align); } //! Load sub-images of a .cimg file \overloading. CImg<T>& load_cimg(std::FILE *const file, const unsigned int n0, const unsigned int n1, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0, const unsigned int x1, const unsigned int y1, const unsigned int z1, const unsigned int c1, const char axis='z', const float align=0) { CImgList<T> list; list.load_cimg(file,n0,n1,x0,y0,z0,c0,x1,y1,z1,c1); if (list._width==1) return list[0].move_to(*this); return assign(list.get_append(axis,align)); } //! Load sub-images of a .cimg file \newinstance. static CImg<T> get_load_cimg(std::FILE *const file, const unsigned int n0, const unsigned int n1, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0, const unsigned int x1, const unsigned int y1, const unsigned int z1, const unsigned int c1, const char axis='z', const float align=0) { return CImg<T>().load_cimg(file,n0,n1,x0,y0,z0,c0,x1,y1,z1,c1,axis,align); } //! Load image from an INRIMAGE-4 file. /** \param filename Filename, as a C-string. \param[out] voxel_size Pointer to the three voxel sizes read from the file. **/ CImg<T>& load_inr(const char *const filename, float *const voxel_size=0) { return _load_inr(0,filename,voxel_size); } //! Load image from an INRIMAGE-4 file \newinstance. static CImg<T> get_load_inr(const char *const filename, float *const voxel_size=0) { return CImg<T>().load_inr(filename,voxel_size); } //! Load image from an INRIMAGE-4 file \overloading. CImg<T>& load_inr(std::FILE *const file, float *const voxel_size=0) { return _load_inr(file,0,voxel_size); } //! Load image from an INRIMAGE-4 file \newinstance. static CImg<T> get_load_inr(std::FILE *const file, float *voxel_size=0) { return CImg<T>().load_inr(file,voxel_size); } static void _load_inr_header(std::FILE *file, int out[8], float *const voxel_size) { CImg<charT> item(1024), tmp1(64), tmp2(64); *item = *tmp1 = *tmp2 = 0; out[0] = std::fscanf(file,"%63s",item._data); out[0] = out[1] = out[2] = out[3] = out[5] = 1; out[4] = out[6] = out[7] = -1; if (cimg::strncasecmp(item,"#INRIMAGE-4#{",13)!=0) throw CImgIOException("CImg<%s>::load_inr(): INRIMAGE-4 header not found.", pixel_type()); while (std::fscanf(file," %63[^\n]%*c",item._data)!=EOF && std::strncmp(item,"##}",3)) { cimg_sscanf(item," XDIM%*[^0-9]%d",out); cimg_sscanf(item," YDIM%*[^0-9]%d",out + 1); cimg_sscanf(item," ZDIM%*[^0-9]%d",out + 2); cimg_sscanf(item," VDIM%*[^0-9]%d",out + 3); cimg_sscanf(item," PIXSIZE%*[^0-9]%d",out + 6); if (voxel_size) { cimg_sscanf(item," VX%*[^0-9.+-]%f",voxel_size); cimg_sscanf(item," VY%*[^0-9.+-]%f",voxel_size + 1); cimg_sscanf(item," VZ%*[^0-9.+-]%f",voxel_size + 2); } if (cimg_sscanf(item," CPU%*[ =]%s",tmp1._data)) out[7] = cimg::strncasecmp(tmp1,"sun",3)?0:1; switch (cimg_sscanf(item," TYPE%*[ =]%s %s",tmp1._data,tmp2._data)) { case 0 : break; case 2 : out[5] = cimg::strncasecmp(tmp1,"unsigned",8)?1:0; std::strncpy(tmp1,tmp2,tmp1._width - 1); // fallthrough case 1 : if (!cimg::strncasecmp(tmp1,"int",3) || !cimg::strncasecmp(tmp1,"fixed",5)) out[4] = 0; if (!cimg::strncasecmp(tmp1,"float",5) || !cimg::strncasecmp(tmp1,"double",6)) out[4] = 1; if (!cimg::strncasecmp(tmp1,"packed",6)) out[4] = 2; if (out[4]>=0) break; // fallthrough default : throw CImgIOException("CImg<%s>::load_inr(): Invalid pixel type '%s' defined in header.", pixel_type(), tmp2._data); } } if (out[0]<0 || out[1]<0 || out[2]<0 || out[3]<0) throw CImgIOException("CImg<%s>::load_inr(): Invalid dimensions (%d,%d,%d,%d) defined in header.", pixel_type(), out[0],out[1],out[2],out[3]); if (out[4]<0 || out[5]<0) throw CImgIOException("CImg<%s>::load_inr(): Incomplete pixel type defined in header.", pixel_type()); if (out[6]<0) throw CImgIOException("CImg<%s>::load_inr(): Incomplete PIXSIZE field defined in header.", pixel_type()); if (out[7]<0) throw CImgIOException("CImg<%s>::load_inr(): Big/Little Endian coding type undefined in header.", pixel_type()); } CImg<T>& _load_inr(std::FILE *const file, const char *const filename, float *const voxel_size) { #define _cimg_load_inr_case(Tf,sign,pixsize,Ts) \ if (!loaded && fopt[6]==pixsize && fopt[4]==Tf && fopt[5]==sign) { \ Ts *xval, *const val = new Ts[(size_t)fopt[0]*fopt[3]]; \ cimg_forYZ(*this,y,z) { \ cimg::fread(val,fopt[0]*fopt[3],nfile); \ if (fopt[7]!=endian) cimg::invert_endianness(val,fopt[0]*fopt[3]); \ xval = val; cimg_forX(*this,x) cimg_forC(*this,c) (*this)(x,y,z,c) = (T)*(xval++); \ } \ delete[] val; \ loaded = true; \ } if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_inr(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); int fopt[8], endian = cimg::endianness()?1:0; bool loaded = false; if (voxel_size) voxel_size[0] = voxel_size[1] = voxel_size[2] = 1; _load_inr_header(nfile,fopt,voxel_size); assign(fopt[0],fopt[1],fopt[2],fopt[3]); _cimg_load_inr_case(0,0,8,unsigned char); _cimg_load_inr_case(0,1,8,char); _cimg_load_inr_case(0,0,16,unsigned short); _cimg_load_inr_case(0,1,16,short); _cimg_load_inr_case(0,0,32,unsigned int); _cimg_load_inr_case(0,1,32,int); _cimg_load_inr_case(1,0,32,float); _cimg_load_inr_case(1,1,32,float); _cimg_load_inr_case(1,0,64,double); _cimg_load_inr_case(1,1,64,double); if (!loaded) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_inr(): Unknown pixel type defined in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } if (!file) cimg::fclose(nfile); return *this; } //! Load image from a EXR file. /** \param filename Filename, as a C-string. **/ CImg<T>& load_exr(const char *const filename) { if (!filename) throw CImgArgumentException(_cimg_instance "load_exr(): Specified filename is (null).", cimg_instance); #if defined(cimg_use_openexr) Imf::RgbaInputFile file(filename); Imath::Box2i dw = file.dataWindow(); const int inwidth = dw.max.x - dw.min.x + 1, inheight = dw.max.y - dw.min.y + 1; Imf::Array2D<Imf::Rgba> pixels; pixels.resizeErase(inheight,inwidth); file.setFrameBuffer(&pixels[0][0] - dw.min.x - dw.min.y*inwidth, 1, inwidth); file.readPixels(dw.min.y, dw.max.y); assign(inwidth,inheight,1,4); T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2), *ptr_a = data(0,0,0,3); cimg_forXY(*this,x,y) { *(ptr_r++) = (T)pixels[y][x].r; *(ptr_g++) = (T)pixels[y][x].g; *(ptr_b++) = (T)pixels[y][x].b; *(ptr_a++) = (T)pixels[y][x].a; } #elif defined(cimg_use_tinyexr) float *res; const char *err = 0; int width = 0, height = 0; const int ret = LoadEXR(&res,&width,&height,filename,&err); if (ret) throw CImgIOException(_cimg_instance "load_exr(): Unable to load EXR file '%s'.", cimg_instance,filename); CImg<floatT>(out,4,width,height,1,true).get_permute_axes("yzcx").move_to(*this); std::free(res); #else return load_other(filename); #endif return *this; } //! Load image from a EXR file \newinstance. static CImg<T> get_load_exr(const char *const filename) { return CImg<T>().load_exr(filename); } //! Load image from a PANDORE-5 file. /** \param filename Filename, as a C-string. **/ CImg<T>& load_pandore(const char *const filename) { return _load_pandore(0,filename); } //! Load image from a PANDORE-5 file \newinstance. static CImg<T> get_load_pandore(const char *const filename) { return CImg<T>().load_pandore(filename); } //! Load image from a PANDORE-5 file \overloading. CImg<T>& load_pandore(std::FILE *const file) { return _load_pandore(file,0); } //! Load image from a PANDORE-5 file \newinstance. static CImg<T> get_load_pandore(std::FILE *const file) { return CImg<T>().load_pandore(file); } CImg<T>& _load_pandore(std::FILE *const file, const char *const filename) { #define __cimg_load_pandore_case(nbdim,nwidth,nheight,ndepth,ndim,stype) \ cimg::fread(dims,nbdim,nfile); \ if (endian) cimg::invert_endianness(dims,nbdim); \ assign(nwidth,nheight,ndepth,ndim); \ const size_t siz = size(); \ stype *buffer = new stype[siz]; \ cimg::fread(buffer,siz,nfile); \ if (endian) cimg::invert_endianness(buffer,siz); \ T *ptrd = _data; \ cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); \ buffer-=siz; \ delete[] buffer #define _cimg_load_pandore_case(nbdim,nwidth,nheight,ndepth,dim,stype1,stype2,stype3,ltype) { \ if (sizeof(stype1)==ltype) { __cimg_load_pandore_case(nbdim,nwidth,nheight,ndepth,dim,stype1); } \ else if (sizeof(stype2)==ltype) { __cimg_load_pandore_case(nbdim,nwidth,nheight,ndepth,dim,stype2); } \ else if (sizeof(stype3)==ltype) { __cimg_load_pandore_case(nbdim,nwidth,nheight,ndepth,dim,stype3); } \ else throw CImgIOException(_cimg_instance \ "load_pandore(): Unknown pixel datatype in file '%s'.", \ cimg_instance, \ filename?filename:"(FILE*)"); } if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_pandore(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); CImg<charT> header(32); cimg::fread(header._data,12,nfile); if (cimg::strncasecmp("PANDORE",header,7)) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_pandore(): PANDORE header not found in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } unsigned int imageid, dims[8] = { 0 }; int ptbuf[4] = { 0 }; cimg::fread(&imageid,1,nfile); const bool endian = imageid>255; if (endian) cimg::invert_endianness(imageid); cimg::fread(header._data,20,nfile); switch (imageid) { case 2 : _cimg_load_pandore_case(2,dims[1],1,1,1,unsigned char,unsigned char,unsigned char,1); break; case 3 : _cimg_load_pandore_case(2,dims[1],1,1,1,long,int,short,4); break; case 4 : _cimg_load_pandore_case(2,dims[1],1,1,1,double,float,float,4); break; case 5 : _cimg_load_pandore_case(3,dims[2],dims[1],1,1,unsigned char,unsigned char,unsigned char,1); break; case 6 : _cimg_load_pandore_case(3,dims[2],dims[1],1,1,long,int,short,4); break; case 7 : _cimg_load_pandore_case(3,dims[2],dims[1],1,1,double,float,float,4); break; case 8 : _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],1,unsigned char,unsigned char,unsigned char,1); break; case 9 : _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],1,long,int,short,4); break; case 10 : _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],1,double,float,float,4); break; case 11 : { // Region 1D cimg::fread(dims,3,nfile); if (endian) cimg::invert_endianness(dims,3); assign(dims[1],1,1,1); const unsigned siz = size(); if (dims[2]<256) { unsigned char *buffer = new unsigned char[siz]; cimg::fread(buffer,siz,nfile); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } else { if (dims[2]<65536) { unsigned short *buffer = new unsigned short[siz]; cimg::fread(buffer,siz,nfile); if (endian) cimg::invert_endianness(buffer,siz); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } else { unsigned int *buffer = new unsigned int[siz]; cimg::fread(buffer,siz,nfile); if (endian) cimg::invert_endianness(buffer,siz); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } } } break; case 12 : { // Region 2D cimg::fread(dims,4,nfile); if (endian) cimg::invert_endianness(dims,4); assign(dims[2],dims[1],1,1); const size_t siz = size(); if (dims[3]<256) { unsigned char *buffer = new unsigned char[siz]; cimg::fread(buffer,siz,nfile); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } else { if (dims[3]<65536) { unsigned short *buffer = new unsigned short[siz]; cimg::fread(buffer,siz,nfile); if (endian) cimg::invert_endianness(buffer,siz); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } else { unsigned int *buffer = new unsigned int[siz]; cimg::fread(buffer,siz,nfile); if (endian) cimg::invert_endianness(buffer,siz); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } } } break; case 13 : { // Region 3D cimg::fread(dims,5,nfile); if (endian) cimg::invert_endianness(dims,5); assign(dims[3],dims[2],dims[1],1); const size_t siz = size(); if (dims[4]<256) { unsigned char *buffer = new unsigned char[siz]; cimg::fread(buffer,siz,nfile); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } else { if (dims[4]<65536) { unsigned short *buffer = new unsigned short[siz]; cimg::fread(buffer,siz,nfile); if (endian) cimg::invert_endianness(buffer,siz); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } else { unsigned int *buffer = new unsigned int[siz]; cimg::fread(buffer,siz,nfile); if (endian) cimg::invert_endianness(buffer,siz); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } } } break; case 16 : _cimg_load_pandore_case(4,dims[2],dims[1],1,3,unsigned char,unsigned char,unsigned char,1); break; case 17 : _cimg_load_pandore_case(4,dims[2],dims[1],1,3,long,int,short,4); break; case 18 : _cimg_load_pandore_case(4,dims[2],dims[1],1,3,double,float,float,4); break; case 19 : _cimg_load_pandore_case(5,dims[3],dims[2],dims[1],3,unsigned char,unsigned char,unsigned char,1); break; case 20 : _cimg_load_pandore_case(5,dims[3],dims[2],dims[1],3,long,int,short,4); break; case 21 : _cimg_load_pandore_case(5,dims[3],dims[2],dims[1],3,double,float,float,4); break; case 22 : _cimg_load_pandore_case(2,dims[1],1,1,dims[0],unsigned char,unsigned char,unsigned char,1); break; case 23 : _cimg_load_pandore_case(2,dims[1],1,1,dims[0],long,int,short,4); break; case 24 : _cimg_load_pandore_case(2,dims[1],1,1,dims[0],unsigned long,unsigned int,unsigned short,4); break; case 25 : _cimg_load_pandore_case(2,dims[1],1,1,dims[0],double,float,float,4); break; case 26 : _cimg_load_pandore_case(3,dims[2],dims[1],1,dims[0],unsigned char,unsigned char,unsigned char,1); break; case 27 : _cimg_load_pandore_case(3,dims[2],dims[1],1,dims[0],long,int,short,4); break; case 28 : _cimg_load_pandore_case(3,dims[2],dims[1],1,dims[0],unsigned long,unsigned int,unsigned short,4); break; case 29 : _cimg_load_pandore_case(3,dims[2],dims[1],1,dims[0],double,float,float,4); break; case 30 : _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],dims[0],unsigned char,unsigned char,unsigned char,1); break; case 31 : _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],dims[0],long,int,short,4); break; case 32 : _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],dims[0],unsigned long,unsigned int,unsigned short,4); break; case 33 : _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],dims[0],double,float,float,4); break; case 34 : { // Points 1D cimg::fread(ptbuf,1,nfile); if (endian) cimg::invert_endianness(ptbuf,1); assign(1); (*this)(0) = (T)ptbuf[0]; } break; case 35 : { // Points 2D cimg::fread(ptbuf,2,nfile); if (endian) cimg::invert_endianness(ptbuf,2); assign(2); (*this)(0) = (T)ptbuf[1]; (*this)(1) = (T)ptbuf[0]; } break; case 36 : { // Points 3D cimg::fread(ptbuf,3,nfile); if (endian) cimg::invert_endianness(ptbuf,3); assign(3); (*this)(0) = (T)ptbuf[2]; (*this)(1) = (T)ptbuf[1]; (*this)(2) = (T)ptbuf[0]; } break; default : if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_pandore(): Unable to load data with ID_type %u in file '%s'.", cimg_instance, imageid,filename?filename:"(FILE*)"); } if (!file) cimg::fclose(nfile); return *this; } //! Load image from a PAR-REC (Philips) file. /** \param filename Filename, as a C-string. \param axis Appending axis, if file contains multiple images. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param align Appending alignment. **/ CImg<T>& load_parrec(const char *const filename, const char axis='c', const float align=0) { CImgList<T> list; list.load_parrec(filename); if (list._width==1) return list[0].move_to(*this); return assign(list.get_append(axis,align)); } //! Load image from a PAR-REC (Philips) file \newinstance. static CImg<T> get_load_parrec(const char *const filename, const char axis='c', const float align=0) { return CImg<T>().load_parrec(filename,axis,align); } //! Load image from a raw binary file. /** \param filename Filename, as a C-string. \param size_x Width of the image buffer. \param size_y Height of the image buffer. \param size_z Depth of the image buffer. \param size_c Spectrum of the image buffer. \param is_multiplexed Tells if the image values are multiplexed along the C-axis. \param invert_endianness Tells if the endianness of the image buffer must be inverted. \param offset Starting offset of the read in the specified file. **/ CImg<T>& load_raw(const char *const filename, const unsigned int size_x=0, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1, const bool is_multiplexed=false, const bool invert_endianness=false, const ulongT offset=0) { return _load_raw(0,filename,size_x,size_y,size_z,size_c,is_multiplexed,invert_endianness,offset); } //! Load image from a raw binary file \newinstance. static CImg<T> get_load_raw(const char *const filename, const unsigned int size_x=0, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1, const bool is_multiplexed=false, const bool invert_endianness=false, const ulongT offset=0) { return CImg<T>().load_raw(filename,size_x,size_y,size_z,size_c,is_multiplexed,invert_endianness,offset); } //! Load image from a raw binary file \overloading. CImg<T>& load_raw(std::FILE *const file, const unsigned int size_x=0, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1, const bool is_multiplexed=false, const bool invert_endianness=false, const ulongT offset=0) { return _load_raw(file,0,size_x,size_y,size_z,size_c,is_multiplexed,invert_endianness,offset); } //! Load image from a raw binary file \newinstance. static CImg<T> get_load_raw(std::FILE *const file, const unsigned int size_x=0, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1, const bool is_multiplexed=false, const bool invert_endianness=false, const ulongT offset=0) { return CImg<T>().load_raw(file,size_x,size_y,size_z,size_c,is_multiplexed,invert_endianness,offset); } CImg<T>& _load_raw(std::FILE *const file, const char *const filename, const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const bool is_multiplexed, const bool invert_endianness, const ulongT offset) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_raw(): Specified filename is (null).", cimg_instance); if (cimg::is_directory(filename)) throw CImgArgumentException(_cimg_instance "load_raw(): Specified filename '%s' is a directory.", cimg_instance,filename); ulongT siz = (ulongT)size_x*size_y*size_z*size_c; unsigned int _size_x = size_x, _size_y = size_y, _size_z = size_z, _size_c = size_c; std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); if (!siz) { // Retrieve file size const longT fpos = cimg::ftell(nfile); if (fpos<0) throw CImgArgumentException(_cimg_instance "load_raw(): Cannot determine size of input file '%s'.", cimg_instance,filename?filename:"(FILE*)"); cimg::fseek(nfile,0,SEEK_END); siz = cimg::ftell(nfile)/sizeof(T); _size_y = (unsigned int)siz; _size_x = _size_z = _size_c = 1; cimg::fseek(nfile,fpos,SEEK_SET); } cimg::fseek(nfile,offset,SEEK_SET); assign(_size_x,_size_y,_size_z,_size_c,0); if (siz && (!is_multiplexed || size_c==1)) { cimg::fread(_data,siz,nfile); if (invert_endianness) cimg::invert_endianness(_data,siz); } else if (siz) { CImg<T> buf(1,1,1,_size_c); cimg_forXYZ(*this,x,y,z) { cimg::fread(buf._data,_size_c,nfile); if (invert_endianness) cimg::invert_endianness(buf._data,_size_c); set_vector_at(buf,x,y,z); } } if (!file) cimg::fclose(nfile); return *this; } //! Load image sequence from a YUV file. /** \param filename Filename, as a C-string. \param size_x Width of the frames. \param size_y Height of the frames. \param chroma_subsampling Type of chroma subsampling. Can be <tt>{ 420 | 422 | 444 }</tt>. \param first_frame Index of the first frame to read. \param last_frame Index of the last frame to read. \param step_frame Step value for frame reading. \param yuv2rgb Tells if the YUV to RGB transform must be applied. \param axis Appending axis, if file contains multiple images. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. **/ CImg<T>& load_yuv(const char *const filename, const unsigned int size_x, const unsigned int size_y=1, const unsigned int chroma_subsampling=444, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const bool yuv2rgb=true, const char axis='z') { return get_load_yuv(filename,size_x,size_y,chroma_subsampling, first_frame,last_frame,step_frame,yuv2rgb,axis).move_to(*this); } //! Load image sequence from a YUV file \newinstance. static CImg<T> get_load_yuv(const char *const filename, const unsigned int size_x, const unsigned int size_y=1, const unsigned int chroma_subsampling=444, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const bool yuv2rgb=true, const char axis='z') { return CImgList<T>().load_yuv(filename,size_x,size_y,chroma_subsampling, first_frame,last_frame,step_frame,yuv2rgb).get_append(axis); } //! Load image sequence from a YUV file \overloading. CImg<T>& load_yuv(std::FILE *const file, const unsigned int size_x, const unsigned int size_y=1, const unsigned int chroma_subsampling=444, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const bool yuv2rgb=true, const char axis='z') { return get_load_yuv(file,size_x,size_y,chroma_subsampling, first_frame,last_frame,step_frame,yuv2rgb,axis).move_to(*this); } //! Load image sequence from a YUV file \newinstance. static CImg<T> get_load_yuv(std::FILE *const file, const unsigned int size_x, const unsigned int size_y=1, const unsigned int chroma_subsampling=444, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const bool yuv2rgb=true, const char axis='z') { return CImgList<T>().load_yuv(file,size_x,size_y,chroma_subsampling, first_frame,last_frame,step_frame,yuv2rgb).get_append(axis); } //! Load 3D object from a .OFF file. /** \param[out] primitives Primitives data of the 3D object. \param[out] colors Colors data of the 3D object. \param filename Filename, as a C-string. **/ template<typename tf, typename tc> CImg<T>& load_off(CImgList<tf>& primitives, CImgList<tc>& colors, const char *const filename) { return _load_off(primitives,colors,0,filename); } //! Load 3D object from a .OFF file \newinstance. template<typename tf, typename tc> static CImg<T> get_load_off(CImgList<tf>& primitives, CImgList<tc>& colors, const char *const filename) { return CImg<T>().load_off(primitives,colors,filename); } //! Load 3D object from a .OFF file \overloading. template<typename tf, typename tc> CImg<T>& load_off(CImgList<tf>& primitives, CImgList<tc>& colors, std::FILE *const file) { return _load_off(primitives,colors,file,0); } //! Load 3D object from a .OFF file \newinstance. template<typename tf, typename tc> static CImg<T> get_load_off(CImgList<tf>& primitives, CImgList<tc>& colors, std::FILE *const file) { return CImg<T>().load_off(primitives,colors,file); } template<typename tf, typename tc> CImg<T>& _load_off(CImgList<tf>& primitives, CImgList<tc>& colors, std::FILE *const file, const char *const filename) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_off(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"r"); unsigned int nb_points = 0, nb_primitives = 0, nb_read = 0; CImg<charT> line(256); *line = 0; int err; // Skip comments, and read magic string OFF do { err = std::fscanf(nfile,"%255[^\n] ",line._data); } while (!err || (err==1 && *line=='#')); if (cimg::strncasecmp(line,"OFF",3) && cimg::strncasecmp(line,"COFF",4)) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_off(): OFF header not found in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } do { err = std::fscanf(nfile,"%255[^\n] ",line._data); } while (!err || (err==1 && *line=='#')); if ((err = cimg_sscanf(line,"%u%u%*[^\n] ",&nb_points,&nb_primitives))!=2) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_off(): Invalid number of vertices or primitives specified in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } // Read points data assign(nb_points,3); float X = 0, Y = 0, Z = 0; cimg_forX(*this,l) { do { err = std::fscanf(nfile,"%255[^\n] ",line._data); } while (!err || (err==1 && *line=='#')); if ((err = cimg_sscanf(line,"%f%f%f%*[^\n] ",&X,&Y,&Z))!=3) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_off(): Failed to read vertex %u/%u in file '%s'.", cimg_instance, l + 1,nb_points,filename?filename:"(FILE*)"); } (*this)(l,0) = (T)X; (*this)(l,1) = (T)Y; (*this)(l,2) = (T)Z; } // Read primitive data primitives.assign(); colors.assign(); bool stop_flag = false; while (!stop_flag) { float c0 = 0.7f, c1 = 0.7f, c2 = 0.7f; unsigned int prim = 0, i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0, i6 = 0, i7 = 0; *line = 0; if ((err = std::fscanf(nfile,"%u",&prim))!=1) stop_flag = true; else { ++nb_read; switch (prim) { case 1 : { if ((err = std::fscanf(nfile,"%u%255[^\n] ",&i0,line._data))<2) { cimg::warn(_cimg_instance "load_off(): Failed to read primitive %u/%u from file '%s'.", cimg_instance, nb_read,nb_primitives,filename?filename:"(FILE*)"); err = std::fscanf(nfile,"%*[^\n] "); } else { err = cimg_sscanf(line,"%f%f%f",&c0,&c1,&c2); CImg<tf>::vector(i0).move_to(primitives); CImg<tc>::vector((tc)(c0*255),(tc)(c1*255),(tc)(c2*255)).move_to(colors); } } break; case 2 : { if ((err = std::fscanf(nfile,"%u%u%255[^\n] ",&i0,&i1,line._data))<2) { cimg::warn(_cimg_instance "load_off(): Failed to read primitive %u/%u from file '%s'.", cimg_instance, nb_read,nb_primitives,filename?filename:"(FILE*)"); err = std::fscanf(nfile,"%*[^\n] "); } else { err = cimg_sscanf(line,"%f%f%f",&c0,&c1,&c2); CImg<tf>::vector(i0,i1).move_to(primitives); CImg<tc>::vector((tc)(c0*255),(tc)(c1*255),(tc)(c2*255)).move_to(colors); } } break; case 3 : { if ((err = std::fscanf(nfile,"%u%u%u%255[^\n] ",&i0,&i1,&i2,line._data))<3) { cimg::warn(_cimg_instance "load_off(): Failed to read primitive %u/%u from file '%s'.", cimg_instance, nb_read,nb_primitives,filename?filename:"(FILE*)"); err = std::fscanf(nfile,"%*[^\n] "); } else { err = cimg_sscanf(line,"%f%f%f",&c0,&c1,&c2); CImg<tf>::vector(i0,i2,i1).move_to(primitives); CImg<tc>::vector((tc)(c0*255),(tc)(c1*255),(tc)(c2*255)).move_to(colors); } } break; case 4 : { if ((err = std::fscanf(nfile,"%u%u%u%u%255[^\n] ",&i0,&i1,&i2,&i3,line._data))<4) { cimg::warn(_cimg_instance "load_off(): Failed to read primitive %u/%u from file '%s'.", cimg_instance, nb_read,nb_primitives,filename?filename:"(FILE*)"); err = std::fscanf(nfile,"%*[^\n] "); } else { err = cimg_sscanf(line,"%f%f%f",&c0,&c1,&c2); CImg<tf>::vector(i0,i3,i2,i1).move_to(primitives); CImg<tc>::vector((tc)(c0*255),(tc)(c1*255),(tc)(c2*255)).move_to(colors); } } break; case 5 : { if ((err = std::fscanf(nfile,"%u%u%u%u%u%255[^\n] ",&i0,&i1,&i2,&i3,&i4,line._data))<5) { cimg::warn(_cimg_instance "load_off(): Failed to read primitive %u/%u from file '%s'.", cimg_instance, nb_read,nb_primitives,filename?filename:"(FILE*)"); err = std::fscanf(nfile,"%*[^\n] "); } else { err = cimg_sscanf(line,"%f%f%f",&c0,&c1,&c2); CImg<tf>::vector(i0,i3,i2,i1).move_to(primitives); CImg<tf>::vector(i0,i4,i3).move_to(primitives); colors.insert(2,CImg<tc>::vector((tc)(c0*255),(tc)(c1*255),(tc)(c2*255))); ++nb_primitives; } } break; case 6 : { if ((err = std::fscanf(nfile,"%u%u%u%u%u%u%255[^\n] ",&i0,&i1,&i2,&i3,&i4,&i5,line._data))<6) { cimg::warn(_cimg_instance "load_off(): Failed to read primitive %u/%u from file '%s'.", cimg_instance, nb_read,nb_primitives,filename?filename:"(FILE*)"); err = std::fscanf(nfile,"%*[^\n] "); } else { err = cimg_sscanf(line,"%f%f%f",&c0,&c1,&c2); CImg<tf>::vector(i0,i3,i2,i1).move_to(primitives); CImg<tf>::vector(i0,i5,i4,i3).move_to(primitives); colors.insert(2,CImg<tc>::vector((tc)(c0*255),(tc)(c1*255),(tc)(c2*255))); ++nb_primitives; } } break; case 7 : { if ((err = std::fscanf(nfile,"%u%u%u%u%u%u%u%255[^\n] ",&i0,&i1,&i2,&i3,&i4,&i5,&i6,line._data))<7) { cimg::warn(_cimg_instance "load_off(): Failed to read primitive %u/%u from file '%s'.", cimg_instance, nb_read,nb_primitives,filename?filename:"(FILE*)"); err = std::fscanf(nfile,"%*[^\n] "); } else { err = cimg_sscanf(line,"%f%f%f",&c0,&c1,&c2); CImg<tf>::vector(i0,i4,i3,i1).move_to(primitives); CImg<tf>::vector(i0,i6,i5,i4).move_to(primitives); CImg<tf>::vector(i3,i2,i1).move_to(primitives); colors.insert(3,CImg<tc>::vector((tc)(c0*255),(tc)(c1*255),(tc)(c2*255))); ++(++nb_primitives); } } break; case 8 : { if ((err = std::fscanf(nfile,"%u%u%u%u%u%u%u%u%255[^\n] ",&i0,&i1,&i2,&i3,&i4,&i5,&i6,&i7,line._data))<7) { cimg::warn(_cimg_instance "load_off(): Failed to read primitive %u/%u from file '%s'.", cimg_instance, nb_read,nb_primitives,filename?filename:"(FILE*)"); err = std::fscanf(nfile,"%*[^\n] "); } else { err = cimg_sscanf(line,"%f%f%f",&c0,&c1,&c2); CImg<tf>::vector(i0,i3,i2,i1).move_to(primitives); CImg<tf>::vector(i0,i5,i4,i3).move_to(primitives); CImg<tf>::vector(i0,i7,i6,i5).move_to(primitives); colors.insert(3,CImg<tc>::vector((tc)(c0*255),(tc)(c1*255),(tc)(c2*255))); ++(++nb_primitives); } } break; default : cimg::warn(_cimg_instance "load_off(): Failed to read primitive %u/%u (%u vertices) from file '%s'.", cimg_instance, nb_read,nb_primitives,prim,filename?filename:"(FILE*)"); err = std::fscanf(nfile,"%*[^\n] "); } } } if (!file) cimg::fclose(nfile); if (primitives._width!=nb_primitives) cimg::warn(_cimg_instance "load_off(): Only %u/%u primitives read from file '%s'.", cimg_instance, primitives._width,nb_primitives,filename?filename:"(FILE*)"); return *this; } //! Load image sequence from a video file, using OpenCV library. /** \param filename Filename, as a C-string. \param first_frame Index of the first frame to read. \param last_frame Index of the last frame to read. \param step_frame Step value for frame reading. \param axis Alignment axis. \param align Apending alignment. **/ CImg<T>& load_video(const char *const filename, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const char axis='z', const float align=0) { return get_load_video(filename,first_frame,last_frame,step_frame,axis,align).move_to(*this); } //! Load image sequence from a video file, using OpenCV library \newinstance. static CImg<T> get_load_video(const char *const filename, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const char axis='z', const float align=0) { return CImgList<T>().load_video(filename,first_frame,last_frame,step_frame).get_append(axis,align); } //! Load image sequence using FFMPEG's external tool 'ffmpeg'. /** \param filename Filename, as a C-string. \param axis Appending axis, if file contains multiple images. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param align Appending alignment. **/ CImg<T>& load_ffmpeg_external(const char *const filename, const char axis='z', const float align=0) { return get_load_ffmpeg_external(filename,axis,align).move_to(*this); } //! Load image sequence using FFMPEG's external tool 'ffmpeg' \newinstance. static CImg<T> get_load_ffmpeg_external(const char *const filename, const char axis='z', const float align=0) { return CImgList<T>().load_ffmpeg_external(filename).get_append(axis,align); } //! Load gif file, using Imagemagick or GraphicsMagicks's external tools. /** \param filename Filename, as a C-string. \param axis Appending axis, if file contains multiple images. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param align Appending alignment. **/ CImg<T>& load_gif_external(const char *const filename, const char axis='z', const float align=0) { return get_load_gif_external(filename,axis,align).move_to(*this); } //! Load gif file, using ImageMagick or GraphicsMagick's external tool 'convert' \newinstance. static CImg<T> get_load_gif_external(const char *const filename, const char axis='z', const float align=0) { return CImgList<T>().load_gif_external(filename).get_append(axis,align); } //! Load image using GraphicsMagick's external tool 'gm'. /** \param filename Filename, as a C-string. **/ CImg<T>& load_graphicsmagick_external(const char *const filename) { if (!filename) throw CImgArgumentException(_cimg_instance "load_graphicsmagick_external(): Specified filename is (null).", cimg_instance); cimg::fclose(cimg::fopen(filename,"rb")); // Check if file exists CImg<charT> command(1024), filename_tmp(256); std::FILE *file = 0; const CImg<charT> s_filename = CImg<charT>::string(filename)._system_strescape(); #if cimg_OS==1 if (!cimg::system("which gm")) { cimg_snprintf(command,command._width,"%s convert \"%s\" pnm:-", cimg::graphicsmagick_path(),s_filename.data()); file = popen(command,"r"); if (file) { const unsigned int omode = cimg::exception_mode(); cimg::exception_mode(0); try { load_pnm(file); } catch (...) { pclose(file); cimg::exception_mode(omode); throw CImgIOException(_cimg_instance "load_graphicsmagick_external(): Failed to load file '%s' " "with external command 'gm'.", cimg_instance, filename); } pclose(file); return *this; } } #endif do { cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.pnm", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); if ((file=cimg::std_fopen(filename_tmp,"rb"))!=0) cimg::fclose(file); } while (file); cimg_snprintf(command,command._width,"%s convert \"%s\" \"%s\"", cimg::graphicsmagick_path(),s_filename.data(), CImg<charT>::string(filename_tmp)._system_strescape().data()); cimg::system(command,cimg::graphicsmagick_path()); if (!(file=cimg::std_fopen(filename_tmp,"rb"))) { cimg::fclose(cimg::fopen(filename,"r")); throw CImgIOException(_cimg_instance "load_graphicsmagick_external(): Failed to load file '%s' with external command 'gm'.", cimg_instance, filename); } else cimg::fclose(file); load_pnm(filename_tmp); std::remove(filename_tmp); return *this; } //! Load image using GraphicsMagick's external tool 'gm' \newinstance. static CImg<T> get_load_graphicsmagick_external(const char *const filename) { return CImg<T>().load_graphicsmagick_external(filename); } //! Load gzipped image file, using external tool 'gunzip'. /** \param filename Filename, as a C-string. **/ CImg<T>& load_gzip_external(const char *const filename) { if (!filename) throw CImgIOException(_cimg_instance "load_gzip_external(): Specified filename is (null).", cimg_instance); cimg::fclose(cimg::fopen(filename,"rb")); // Check if file exists CImg<charT> command(1024), filename_tmp(256), body(256); const char *const ext = cimg::split_filename(filename,body), *const ext2 = cimg::split_filename(body,0); std::FILE *file = 0; do { if (!cimg::strcasecmp(ext,"gz")) { if (*ext2) cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),ext2); else cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); } else { if (*ext) cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),ext); else cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); } if ((file=cimg::std_fopen(filename_tmp,"rb"))!=0) cimg::fclose(file); } while (file); cimg_snprintf(command,command._width,"%s -c \"%s\" > \"%s\"", cimg::gunzip_path(), CImg<charT>::string(filename)._system_strescape().data(), CImg<charT>::string(filename_tmp)._system_strescape().data()); cimg::system(command); if (!(file=cimg::std_fopen(filename_tmp,"rb"))) { cimg::fclose(cimg::fopen(filename,"r")); throw CImgIOException(_cimg_instance "load_gzip_external(): Failed to load file '%s' with external command 'gunzip'.", cimg_instance, filename); } else cimg::fclose(file); load(filename_tmp); std::remove(filename_tmp); return *this; } //! Load gzipped image file, using external tool 'gunzip' \newinstance. static CImg<T> get_load_gzip_external(const char *const filename) { return CImg<T>().load_gzip_external(filename); } //! Load image using ImageMagick's external tool 'convert'. /** \param filename Filename, as a C-string. **/ CImg<T>& load_imagemagick_external(const char *const filename) { if (!filename) throw CImgArgumentException(_cimg_instance "load_imagemagick_external(): Specified filename is (null).", cimg_instance); cimg::fclose(cimg::fopen(filename,"rb")); // Check if file exists CImg<charT> command(1024), filename_tmp(256); std::FILE *file = 0; const CImg<charT> s_filename = CImg<charT>::string(filename)._system_strescape(); #if cimg_OS==1 if (!cimg::system("which convert")) { cimg_snprintf(command,command._width,"%s%s \"%s\" pnm:-", cimg::imagemagick_path(), !cimg::strcasecmp(cimg::split_filename(filename),"pdf")?" -density 400x400":"", s_filename.data()); file = popen(command,"r"); if (file) { const unsigned int omode = cimg::exception_mode(); cimg::exception_mode(0); try { load_pnm(file); } catch (...) { pclose(file); cimg::exception_mode(omode); throw CImgIOException(_cimg_instance "load_imagemagick_external(): Failed to load file '%s' with " "external command 'magick/convert'.", cimg_instance, filename); } pclose(file); return *this; } } #endif do { cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.pnm", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); if ((file=cimg::std_fopen(filename_tmp,"rb"))!=0) cimg::fclose(file); } while (file); cimg_snprintf(command,command._width,"%s%s \"%s\" \"%s\"", cimg::imagemagick_path(), !cimg::strcasecmp(cimg::split_filename(filename),"pdf")?" -density 400x400":"", s_filename.data(),CImg<charT>::string(filename_tmp)._system_strescape().data()); cimg::system(command,cimg::imagemagick_path()); if (!(file=cimg::std_fopen(filename_tmp,"rb"))) { cimg::fclose(cimg::fopen(filename,"r")); throw CImgIOException(_cimg_instance "load_imagemagick_external(): Failed to load file '%s' with " "external command 'magick/convert'.", cimg_instance, filename); } else cimg::fclose(file); load_pnm(filename_tmp); std::remove(filename_tmp); return *this; } //! Load image using ImageMagick's external tool 'convert' \newinstance. static CImg<T> get_load_imagemagick_external(const char *const filename) { return CImg<T>().load_imagemagick_external(filename); } //! Load image from a DICOM file, using XMedcon's external tool 'medcon'. /** \param filename Filename, as a C-string. **/ CImg<T>& load_medcon_external(const char *const filename) { if (!filename) throw CImgArgumentException(_cimg_instance "load_medcon_external(): Specified filename is (null).", cimg_instance); cimg::fclose(cimg::fopen(filename,"rb")); // Check if file exists CImg<charT> command(1024), filename_tmp(256), body(256); cimg::fclose(cimg::fopen(filename,"r")); std::FILE *file = 0; do { cimg_snprintf(filename_tmp,filename_tmp._width,"%s.hdr",cimg::filenamerand()); if ((file=cimg::std_fopen(filename_tmp,"rb"))!=0) cimg::fclose(file); } while (file); cimg_snprintf(command,command._width,"%s -w -c anlz -o \"%s\" -f \"%s\"", cimg::medcon_path(), CImg<charT>::string(filename_tmp)._system_strescape().data(), CImg<charT>::string(filename)._system_strescape().data()); cimg::system(command); cimg::split_filename(filename_tmp,body); cimg_snprintf(command,command._width,"%s.hdr",body._data); file = cimg::std_fopen(command,"rb"); if (!file) { cimg_snprintf(command,command._width,"m000-%s.hdr",body._data); file = cimg::std_fopen(command,"rb"); if (!file) { throw CImgIOException(_cimg_instance "load_medcon_external(): Failed to load file '%s' with external command 'medcon'.", cimg_instance, filename); } } cimg::fclose(file); load_analyze(command); std::remove(command); cimg::split_filename(command,body); cimg_snprintf(command,command._width,"%s.img",body._data); std::remove(command); return *this; } //! Load image from a DICOM file, using XMedcon's external tool 'medcon' \newinstance. static CImg<T> get_load_medcon_external(const char *const filename) { return CImg<T>().load_medcon_external(filename); } //! Load image from a RAW Color Camera file, using external tool 'dcraw'. /** \param filename Filename, as a C-string. **/ CImg<T>& load_dcraw_external(const char *const filename) { if (!filename) throw CImgArgumentException(_cimg_instance "load_dcraw_external(): Specified filename is (null).", cimg_instance); cimg::fclose(cimg::fopen(filename,"rb")); // Check if file exists CImg<charT> command(1024), filename_tmp(256); std::FILE *file = 0; const CImg<charT> s_filename = CImg<charT>::string(filename)._system_strescape(); #if cimg_OS==1 cimg_snprintf(command,command._width,"%s -w -4 -c \"%s\"", cimg::dcraw_path(),s_filename.data()); file = popen(command,"r"); if (file) { const unsigned int omode = cimg::exception_mode(); cimg::exception_mode(0); try { load_pnm(file); } catch (...) { pclose(file); cimg::exception_mode(omode); throw CImgIOException(_cimg_instance "load_dcraw_external(): Failed to load file '%s' with external command 'dcraw'.", cimg_instance, filename); } pclose(file); return *this; } #endif do { cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.ppm", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); if ((file=cimg::std_fopen(filename_tmp,"rb"))!=0) cimg::fclose(file); } while (file); cimg_snprintf(command,command._width,"%s -w -4 -c \"%s\" > \"%s\"", cimg::dcraw_path(),s_filename.data(),CImg<charT>::string(filename_tmp)._system_strescape().data()); cimg::system(command,cimg::dcraw_path()); if (!(file=cimg::std_fopen(filename_tmp,"rb"))) { cimg::fclose(cimg::fopen(filename,"r")); throw CImgIOException(_cimg_instance "load_dcraw_external(): Failed to load file '%s' with external command 'dcraw'.", cimg_instance, filename); } else cimg::fclose(file); load_pnm(filename_tmp); std::remove(filename_tmp); return *this; } //! Load image from a RAW Color Camera file, using external tool 'dcraw' \newinstance. static CImg<T> get_load_dcraw_external(const char *const filename) { return CImg<T>().load_dcraw_external(filename); } #ifdef cimg_use_opencv // Convert a continuous cv::Mat<uchar> to a CImg<uchar>. static CImg<ucharT> _cvmat2cimg(const cv::Mat &src) { if (src.channels()==1) return CImg<ucharT>(src.ptr(),src.cols,src.rows,1,1); else if (src.channels()==3) { // BGR CImg<ucharT> res(src.cols,src.rows,1,src.channels()); const unsigned char *ptrs = src.ptr(); unsigned char *pR = res.data(), *pG = res.data(0,0,0,1), *pB = res.data(0,0,0,2); cimg_forXY(res,x,y) { *(pB++) = *(ptrs++); *(pG++) = *(ptrs++); *(pR++) = *(ptrs++); } return res; } return CImg<ucharT>(src.ptr(),src.channels(),src.cols,src.rows,1,true).get_permute_axes("yzcx"); } // Convert a CImg<T> to a cv::Mat. cv::Mat _cimg2cvmat() const { if (is_empty()) throw CImgInstanceException(_cimg_instance "_cimg2cvmat() : Instance image is empty.", cimg_instance); if (_spectrum==2) throw CImgInstanceException(_cimg_instance "_cimg2cvmat() : Invalid number of channels (should be '1' or '3+').", cimg_instance); if (_depth!=1) throw CImgInstanceException(_cimg_instance "_cimg2cvmat() : Invalid number of slices (should be '1').", cimg_instance); int mat_type = -1; if (cimg::type<T>::string()==cimg::type<unsigned char>::string()) mat_type = CV_8UC1; if (cimg::type<T>::string()==cimg::type<char>::string()) mat_type = CV_8SC1; if (cimg::type<T>::string()==cimg::type<unsigned short>::string()) mat_type = CV_16UC1; if (cimg::type<T>::string()==cimg::type<short>::string()) mat_type = CV_16SC1; if (cimg::type<T>::string()==cimg::type<int>::string()) mat_type = CV_32SC1; if (cimg::type<T>::string()==cimg::type<float>::string()) mat_type = CV_32FC1; if (cimg::type<T>::string()==cimg::type<double>::string()) mat_type = CV_64FC1; if (mat_type<0) throw CImgInstanceException(_cimg_instance "_cvmat2cimg() : pixel type '%s' is not supported.", cimg_instance,pixel_type()); cv::Mat res; std::vector<cv::Mat> channels(_spectrum); if (_spectrum>1) { cimg_forC(*this,c) channels[c] = cv::Mat(_height,_width,mat_type,_data + _width*_height*(_spectrum - 1 - c)); cv::merge(channels,res); } else res = cv::Mat(_height,_width,mat_type,_data).clone(); return res; } #endif //! Load image from a camera stream, using OpenCV. /** \param index Index of the camera to capture images from (from 0 to 63). \param capture_width Width of the desired image ('0' stands for default value). \param capture_height Height of the desired image ('0' stands for default value). \param skip_frames Number of frames to skip before the capture. \param release_camera Tells if the camera ressource must be released at the end of the method. **/ CImg<T>& load_camera(const unsigned int camera_index=0, const unsigned int capture_width=0, const unsigned int capture_height=0, const unsigned int skip_frames=0, const bool release_camera=true) { #ifdef cimg_use_opencv if (camera_index>=64) throw CImgArgumentException(_cimg_instance "load_camera(): Invalid request for camera #%u " "(no more than 100 cameras can be managed simultaneously).", cimg_instance, camera_index); static cv::VideoCapture *captures[64] = { 0 }; static unsigned int captures_w[64], captures_h[64]; if (release_camera) { cimg::mutex(9); if (captures[camera_index]) captures[camera_index]->release(); delete captures[camera_index]; captures[camera_index] = 0; captures_w[camera_index] = captures_h[camera_index] = 0; cimg::mutex(9,0); return *this; } if (!captures[camera_index]) { cimg::mutex(9); captures[camera_index] = new cv::VideoCapture(camera_index); captures_w[camera_index] = captures_h[camera_index] = 0; if (!captures[camera_index]->isOpened()) { delete captures[camera_index]; captures[camera_index] = 0; cimg::mutex(9,0); throw CImgIOException(_cimg_instance "load_camera(): Failed to initialize camera #%u.", cimg_instance, camera_index); } cimg::mutex(9,0); } cimg::mutex(9); if (capture_width!=captures_w[camera_index]) { captures[camera_index]->set(_cimg_cap_prop_frame_width,capture_width); captures_w[camera_index] = capture_width; } if (capture_height!=captures_h[camera_index]) { captures[camera_index]->set(_cimg_cap_prop_frame_height,capture_height); captures_h[camera_index] = capture_height; } for (unsigned int i = 0; i<skip_frames; ++i) captures[camera_index]->grab(); cv::Mat cvimg; captures[camera_index]->read(cvimg); if (cvimg.empty()) assign(); else _cvmat2cimg(cvimg).move_to(*this); cimg::mutex(9,0); return *this; #else cimg::unused(camera_index,skip_frames,release_camera,capture_width,capture_height); throw CImgIOException(_cimg_instance "load_camera(): This function requires the OpenCV library to run " "(macro 'cimg_use_opencv' must be defined).", cimg_instance); #endif } //! Load image from a camera stream, using OpenCV \newinstance. static CImg<T> get_load_camera(const unsigned int camera_index=0, const unsigned int capture_width=0, const unsigned int capture_height=0, const unsigned int skip_frames=0, const bool release_camera=true) { return CImg<T>().load_camera(camera_index,capture_width,capture_height,skip_frames,release_camera); } //! Load image using various non-native ways. /** \param filename Filename, as a C-string. **/ CImg<T>& load_other(const char *const filename) { if (!filename) throw CImgArgumentException(_cimg_instance "load_other(): Specified filename is (null).", cimg_instance); const unsigned int omode = cimg::exception_mode(); cimg::exception_mode(0); try { load_magick(filename); } catch (CImgException&) { try { load_imagemagick_external(filename); } catch (CImgException&) { try { load_graphicsmagick_external(filename); } catch (CImgException&) { try { load_cimg(filename); } catch (CImgException&) { try { cimg::fclose(cimg::fopen(filename,"rb")); } catch (CImgException&) { cimg::exception_mode(omode); throw CImgIOException(_cimg_instance "load_other(): Failed to open file '%s'.", cimg_instance, filename); } cimg::exception_mode(omode); throw CImgIOException(_cimg_instance "load_other(): Failed to recognize format of file '%s'.", cimg_instance, filename); } } } } cimg::exception_mode(omode); return *this; } //! Load image using various non-native ways \newinstance. static CImg<T> get_load_other(const char *const filename) { return CImg<T>().load_other(filename); } //@} //--------------------------- // //! \name Data Output //@{ //--------------------------- //! Display information about the image data. /** \param title Name for the considered image. \param display_stats Tells to compute and display image statistics. **/ const CImg<T>& print(const char *const title=0, const bool display_stats=true) const { int xm = 0, ym = 0, zm = 0, vm = 0, xM = 0, yM = 0, zM = 0, vM = 0; CImg<doubleT> st; if (!is_empty() && display_stats) { st = get_stats(); xm = (int)st[4]; ym = (int)st[5], zm = (int)st[6], vm = (int)st[7]; xM = (int)st[8]; yM = (int)st[9], zM = (int)st[10], vM = (int)st[11]; } const ulongT siz = size(), msiz = siz*sizeof(T), siz1 = siz - 1, mdisp = msiz<8*1024?0U:msiz<8*1024*1024?1U:2U, width1 = _width - 1; CImg<charT> _title(64); if (!title) cimg_snprintf(_title,_title._width,"CImg<%s>",pixel_type()); std::fprintf(cimg::output(),"%s%s%s%s: %sthis%s = %p, %ssize%s = (%u,%u,%u,%u) [%lu %s], %sdata%s = (%s*)%p", cimg::t_magenta,cimg::t_bold,title?title:_title._data,cimg::t_normal, cimg::t_bold,cimg::t_normal,(void*)this, cimg::t_bold,cimg::t_normal,_width,_height,_depth,_spectrum, (unsigned long)(mdisp==0?msiz:(mdisp==1?(msiz>>10):(msiz>>20))), mdisp==0?"b":(mdisp==1?"Kio":"Mio"), cimg::t_bold,cimg::t_normal,pixel_type(),(void*)begin()); if (_data) std::fprintf(cimg::output(),"..%p (%s) = [ ",(void*)((char*)end() - 1),_is_shared?"shared":"non-shared"); else std::fprintf(cimg::output()," (%s) = [ ",_is_shared?"shared":"non-shared"); if (!is_empty()) cimg_foroff(*this,off) { std::fprintf(cimg::output(),"%g",(double)_data[off]); if (off!=siz1) std::fprintf(cimg::output(),"%s",off%_width==width1?" ; ":" "); if (off==7 && siz>16) { off = siz1 - 8; std::fprintf(cimg::output(),"... "); } } if (!is_empty() && display_stats) std::fprintf(cimg::output(), " ], %smin%s = %g, %smax%s = %g, %smean%s = %g, %sstd%s = %g, %scoords_min%s = (%u,%u,%u,%u), " "%scoords_max%s = (%u,%u,%u,%u).\n", cimg::t_bold,cimg::t_normal,st[0], cimg::t_bold,cimg::t_normal,st[1], cimg::t_bold,cimg::t_normal,st[2], cimg::t_bold,cimg::t_normal,std::sqrt(st[3]), cimg::t_bold,cimg::t_normal,xm,ym,zm,vm, cimg::t_bold,cimg::t_normal,xM,yM,zM,vM); else std::fprintf(cimg::output(),"%s].\n",is_empty()?"":" "); std::fflush(cimg::output()); return *this; } //! Display image into a CImgDisplay window. /** \param disp Display window. **/ const CImg<T>& display(CImgDisplay& disp) const { disp.display(*this); return *this; } //! Display image into a CImgDisplay window, in an interactive way. /** \param disp Display window. \param display_info Tells if image information are displayed on the standard output. \param[in,out] XYZ Contains the XYZ coordinates at start / exit of the function. \param exit_on_anykey Exit function when any key is pressed. **/ const CImg<T>& display(CImgDisplay &disp, const bool display_info, unsigned int *const XYZ=0, const bool exit_on_anykey=false) const { return _display(disp,0,display_info,XYZ,exit_on_anykey,false); } //! Display image into an interactive window. /** \param title Window title \param display_info Tells if image information are displayed on the standard output. \param[in,out] XYZ Contains the XYZ coordinates at start / exit of the function. \param exit_on_anykey Exit function when any key is pressed. **/ const CImg<T>& display(const char *const title=0, const bool display_info=true, unsigned int *const XYZ=0, const bool exit_on_anykey=false) const { CImgDisplay disp; return _display(disp,title,display_info,XYZ,exit_on_anykey,false); } const CImg<T>& _display(CImgDisplay &disp, const char *const title, const bool display_info, unsigned int *const XYZ, const bool exit_on_anykey, const bool exit_on_singleclick) const { unsigned int oldw = 0, oldh = 0, _XYZ[3] = { 0 }, key = 0; int x0 = 0, y0 = 0, z0 = 0, x1 = width() - 1, y1 = height() - 1, z1 = depth() - 1, old_mouse_x = -1, old_mouse_y = -1; if (!disp) { disp.assign(cimg_fitscreen(_width,_height,_depth),title?title:0,1); if (!title) disp.set_title("CImg<%s> (%ux%ux%ux%u)",pixel_type(),_width,_height,_depth,_spectrum); else disp.set_title("%s",title); } else if (title) disp.set_title("%s",title); disp.show().flush(); const CImg<char> dtitle = CImg<char>::string(disp.title()); if (display_info) print(dtitle); CImg<T> zoom; for (bool reset_view = true, resize_disp = false, is_first_select = true; !key && !disp.is_closed(); ) { if (reset_view) { if (XYZ) { _XYZ[0] = XYZ[0]; _XYZ[1] = XYZ[1]; _XYZ[2] = XYZ[2]; } else { _XYZ[0] = (unsigned int)(x0 + x1 + 1)/2; _XYZ[1] = (unsigned int)(y0 + y1 + 1)/2; _XYZ[2] = (unsigned int)(z0 + z1 + 1)/2; } x0 = 0; y0 = 0; z0 = 0; x1 = width() - 1; y1 = height() - 1; z1 = depth() - 1; disp.resize(cimg_fitscreen(_width,_height,_depth),false); oldw = disp._width; oldh = disp._height; resize_disp = true; reset_view = false; } if (!x0 && !y0 && !z0 && x1==width() - 1 && y1==height() - 1 && z1==depth() - 1) { if (is_empty()) zoom.assign(1,1,1,1,(T)0); else zoom.assign(); } else zoom = get_crop(x0,y0,z0,x1,y1,z1); const CImg<T>& visu = zoom?zoom:*this; const unsigned int dx = 1U + x1 - x0, dy = 1U + y1 - y0, dz = 1U + z1 - z0, tw = dx + (dz>1?dz:0U), th = dy + (dz>1?dz:0U); if (!is_empty() && !disp.is_fullscreen() && resize_disp) { const float ttw = (float)tw*disp.width()/oldw, tth = (float)th*disp.height()/oldh, dM = std::max(ttw,tth), diM = (float)std::max(disp.width(),disp.height()); const unsigned int imgw = (unsigned int)(ttw*diM/dM), imgh = (unsigned int)(tth*diM/dM); disp.set_fullscreen(false).resize(cimg_fitscreen(imgw,imgh,1),false); resize_disp = false; } oldw = tw; oldh = th; bool go_up = false, go_down = false, go_left = false, go_right = false, go_inc = false, go_dec = false, go_in = false, go_out = false, go_in_center = false; disp.set_title("%s",dtitle._data); if (_width>1 && visu._width==1) disp.set_title("%s | x=%u",disp._title,x0); if (_height>1 && visu._height==1) disp.set_title("%s | y=%u",disp._title,y0); if (_depth>1 && visu._depth==1) disp.set_title("%s | z=%u",disp._title,z0); disp._mouse_x = old_mouse_x; disp._mouse_y = old_mouse_y; CImg<intT> selection = visu._select(disp,0,2,_XYZ,x0,y0,z0,true,is_first_select,_depth>1,true); old_mouse_x = disp._mouse_x; old_mouse_y = disp._mouse_y; is_first_select = false; if (disp.wheel()) { if ((disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) && (disp.is_keySHIFTLEFT() || disp.is_keySHIFTRIGHT())) { go_left = !(go_right = disp.wheel()>0); } else if (disp.is_keySHIFTLEFT() || disp.is_keySHIFTRIGHT()) { go_down = !(go_up = disp.wheel()>0); } else if (depth()==1 || disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { go_out = !(go_in = disp.wheel()>0); go_in_center = false; } disp.set_wheel(); } const int sx0 = selection(0), sy0 = selection(1), sz0 = selection(2), sx1 = selection(3), sy1 = selection(4), sz1 = selection(5); if (sx0>=0 && sy0>=0 && sz0>=0 && sx1>=0 && sy1>=0 && sz1>=0) { x1 = x0 + sx1; y1 = y0 + sy1; z1 = z0 + sz1; x0+=sx0; y0+=sy0; z0+=sz0; if ((sx0==sx1 && sy0==sy1) || (_depth>1 && sx0==sx1 && sz0==sz1) || (_depth>1 && sy0==sy1 && sz0==sz1)) { if (exit_on_singleclick && (!zoom || is_empty())) break; else reset_view = true; } resize_disp = true; } else switch (key = disp.key()) { #if cimg_OS!=2 case cimg::keyCTRLRIGHT : case cimg::keySHIFTRIGHT : #endif case 0 : case cimg::keyCTRLLEFT : case cimg::keySHIFTLEFT : key = 0; break; case cimg::keyP : if (visu._depth>1 && (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT())) { // Special mode: play stack of frames const unsigned int w1 = visu._width*disp.width()/(visu._width + (visu._depth>1?visu._depth:0)), h1 = visu._height*disp.height()/(visu._height + (visu._depth>1?visu._depth:0)); float frame_timing = 5; bool is_stopped = false; disp.set_key(key,false).set_wheel().resize(cimg_fitscreen(w1,h1,1),false); key = 0; for (unsigned int timer = 0; !key && !disp.is_closed() && !disp.button(); ) { if (disp.is_resized()) disp.resize(false); if (!timer) { visu.get_slice((int)_XYZ[2]).display(disp.set_title("%s | z=%d",dtitle.data(),_XYZ[2])); (++_XYZ[2])%=visu._depth; } if (!is_stopped) { if (++timer>(unsigned int)frame_timing) timer = 0; } else timer = ~0U; if (disp.wheel()) { frame_timing-=disp.wheel()/3.f; disp.set_wheel(); } switch (key = disp.key()) { #if cimg_OS!=2 case cimg::keyCTRLRIGHT : #endif case cimg::keyCTRLLEFT : key = 0; break; case cimg::keyPAGEUP : frame_timing-=0.3f; key = 0; break; case cimg::keyPAGEDOWN : frame_timing+=0.3f; key = 0; break; case cimg::keySPACE : is_stopped = !is_stopped; disp.set_key(key,false); key = 0; break; case cimg::keyARROWLEFT : case cimg::keyARROWUP : is_stopped = true; timer = 0; key = 0; break; case cimg::keyARROWRIGHT : case cimg::keyARROWDOWN : is_stopped = true; (_XYZ[2]+=visu._depth - 2)%=visu._depth; timer = 0; key = 0; break; case cimg::keyD : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false). resize(CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,false), CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,true),false); disp.set_key(key,false); key = 0; } break; case cimg::keyC : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false). resize(cimg_fitscreen(2*disp.width()/3,2*disp.height()/3,1),false).set_key(key,false); key = 0; } break; case cimg::keyR : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false). resize(cimg_fitscreen(_width,_height,_depth),false).set_key(key,false); key = 0; } break; case cimg::keyF : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.resize(disp.screen_width(),disp.screen_height(),false). toggle_fullscreen().set_key(key,false); key = 0; } break; } frame_timing = frame_timing<1?1:(frame_timing>39?39:frame_timing); disp.wait(20); } const unsigned int w2 = (visu._width + (visu._depth>1?visu._depth:0))*disp.width()/visu._width, h2 = (visu._height + (visu._depth>1?visu._depth:0))*disp.height()/visu._height; disp.resize(cimg_fitscreen(w2,h2,1),false).set_title(dtitle.data()).set_key().set_button().set_wheel(); key = 0; } break; case cimg::keyHOME : reset_view = resize_disp = true; key = 0; break; case cimg::keyPADADD : go_in = true; go_in_center = true; key = 0; break; case cimg::keyPADSUB : go_out = true; key = 0; break; case cimg::keyARROWLEFT : case cimg::keyPAD4: go_left = true; key = 0; break; case cimg::keyARROWRIGHT : case cimg::keyPAD6: go_right = true; key = 0; break; case cimg::keyARROWUP : case cimg::keyPAD8: go_up = true; key = 0; break; case cimg::keyARROWDOWN : case cimg::keyPAD2: go_down = true; key = 0; break; case cimg::keyPAD7 : go_up = go_left = true; key = 0; break; case cimg::keyPAD9 : go_up = go_right = true; key = 0; break; case cimg::keyPAD1 : go_down = go_left = true; key = 0; break; case cimg::keyPAD3 : go_down = go_right = true; key = 0; break; case cimg::keyPAGEUP : go_inc = true; key = 0; break; case cimg::keyPAGEDOWN : go_dec = true; key = 0; break; } if (go_in) { const int mx = go_in_center?disp.width()/2:disp.mouse_x(), my = go_in_center?disp.height()/2:disp.mouse_y(), mX = mx*(width() + (depth()>1?depth():0))/disp.width(), mY = my*(height() + (depth()>1?depth():0))/disp.height(); int X = (int)_XYZ[0], Y = (int)_XYZ[1], Z = (int)_XYZ[2]; if (mX<width() && mY<height()) { X = x0 + mX*(1 + x1 - x0)/width(); Y = y0 + mY*(1 + y1 - y0)/height(); } if (mX<width() && mY>=height()) { X = x0 + mX*(1 + x1 - x0)/width(); Z = z0 + (mY - height())*(1 + z1 - z0)/depth(); } if (mX>=width() && mY<height()) { Y = y0 + mY*(1 + y1 - y0)/height(); Z = z0 + (mX - width())*(1 + z1 - z0)/depth(); } if (x1 - x0>4) { x0 = X - 3*(X - x0)/4; x1 = X + 3*(x1 - X)/4; } if (y1 - y0>4) { y0 = Y - 3*(Y - y0)/4; y1 = Y + 3*(y1 - Y)/4; } if (z1 - z0>4) { z0 = Z - 3*(Z - z0)/4; z1 = Z + 3*(z1 - Z)/4; } } if (go_out) { const int delta_x = (x1 - x0)/8, delta_y = (y1 - y0)/8, delta_z = (z1 - z0)/8, ndelta_x = delta_x?delta_x:(_width>1), ndelta_y = delta_y?delta_y:(_height>1), ndelta_z = delta_z?delta_z:(_depth>1); x0-=ndelta_x; y0-=ndelta_y; z0-=ndelta_z; x1+=ndelta_x; y1+=ndelta_y; z1+=ndelta_z; if (x0<0) { x1-=x0; x0 = 0; if (x1>=width()) x1 = width() - 1; } if (y0<0) { y1-=y0; y0 = 0; if (y1>=height()) y1 = height() - 1; } if (z0<0) { z1-=z0; z0 = 0; if (z1>=depth()) z1 = depth() - 1; } if (x1>=width()) { x0-=(x1 - width() + 1); x1 = width() - 1; if (x0<0) x0 = 0; } if (y1>=height()) { y0-=(y1 - height() + 1); y1 = height() - 1; if (y0<0) y0 = 0; } if (z1>=depth()) { z0-=(z1 - depth() + 1); z1 = depth() - 1; if (z0<0) z0 = 0; } const float ratio = (float)(x1-x0)/(y1-y0), ratiow = (float)disp._width/disp._height, sub = std::min(cimg::abs(ratio - ratiow),cimg::abs(1/ratio-1/ratiow)); if (sub>0.01) resize_disp = true; } if (go_left) { const int delta = (x1 - x0)/4, ndelta = delta?delta:(_width>1); if (x0 - ndelta>=0) { x0-=ndelta; x1-=ndelta; } else { x1-=x0; x0 = 0; } } if (go_right) { const int delta = (x1 - x0)/4, ndelta = delta?delta:(_width>1); if (x1+ndelta<width()) { x0+=ndelta; x1+=ndelta; } else { x0+=(width() - 1 - x1); x1 = width() - 1; } } if (go_up) { const int delta = (y1 - y0)/4, ndelta = delta?delta:(_height>1); if (y0 - ndelta>=0) { y0-=ndelta; y1-=ndelta; } else { y1-=y0; y0 = 0; } } if (go_down) { const int delta = (y1 - y0)/4, ndelta = delta?delta:(_height>1); if (y1+ndelta<height()) { y0+=ndelta; y1+=ndelta; } else { y0+=(height() - 1 - y1); y1 = height() - 1; } } if (go_inc) { const int delta = (z1 - z0)/4, ndelta = delta?delta:(_depth>1); if (z0 - ndelta>=0) { z0-=ndelta; z1-=ndelta; } else { z1-=z0; z0 = 0; } } if (go_dec) { const int delta = (z1 - z0)/4, ndelta = delta?delta:(_depth>1); if (z1+ndelta<depth()) { z0+=ndelta; z1+=ndelta; } else { z0+=(depth() - 1 - z1); z1 = depth() - 1; } } disp.wait(100); if (!exit_on_anykey && key && key!=cimg::keyESC && (key!=cimg::keyW || (!disp.is_keyCTRLLEFT() && !disp.is_keyCTRLRIGHT()))) { key = 0; } } disp.set_key(key); if (XYZ) { XYZ[0] = _XYZ[0]; XYZ[1] = _XYZ[1]; XYZ[2] = _XYZ[2]; } return *this; } //! Display object 3D in an interactive window. /** \param disp Display window. \param vertices Vertices data of the 3D object. \param primitives Primitives data of the 3D object. \param colors Colors data of the 3D object. \param opacities Opacities data of the 3D object. \param centering Tells if the 3D object must be centered for the display. \param render_static Rendering mode. \param render_motion Rendering mode, when the 3D object is moved. \param is_double_sided Tells if the object primitives are double-sided. \param focale Focale \param light_x X-coordinate of the light source. \param light_y Y-coordinate of the light source. \param light_z Z-coordinate of the light source. \param specular_lightness Amount of specular light. \param specular_shininess Shininess of the object material. \param display_axes Tells if the 3D axes are displayed. \param pose_matrix Pointer to 12 values, defining a 3D pose (as a 4x3 matrix). \param exit_on_anykey Exit function when any key is pressed. **/ template<typename tp, typename tf, typename tc, typename to> const CImg<T>& display_object3d(CImgDisplay& disp, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const to& opacities, const bool centering=true, const int render_static=4, const int render_motion=1, const bool is_double_sided=true, const float focale=700, const float light_x=0, const float light_y=0, const float light_z=-5e8f, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const bool display_axes=true, float *const pose_matrix=0, const bool exit_on_anykey=false) const { return _display_object3d(disp,0,vertices,primitives,colors,opacities,centering,render_static, render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix,exit_on_anykey); } //! Display object 3D in an interactive window \simplification. template<typename tp, typename tf, typename tc, typename to> const CImg<T>& display_object3d(const char *const title, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const to& opacities, const bool centering=true, const int render_static=4, const int render_motion=1, const bool is_double_sided=true, const float focale=700, const float light_x=0, const float light_y=0, const float light_z=-5e8f, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const bool display_axes=true, float *const pose_matrix=0, const bool exit_on_anykey=false) const { CImgDisplay disp; return _display_object3d(disp,title,vertices,primitives,colors,opacities,centering,render_static, render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix,exit_on_anykey); } //! Display object 3D in an interactive window \simplification. template<typename tp, typename tf, typename tc> const CImg<T>& display_object3d(CImgDisplay &disp, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const bool centering=true, const int render_static=4, const int render_motion=1, const bool is_double_sided=true, const float focale=700, const float light_x=0, const float light_y=0, const float light_z=-5e8f, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const bool display_axes=true, float *const pose_matrix=0, const bool exit_on_anykey=false) const { return display_object3d(disp,vertices,primitives,colors,CImgList<floatT>(),centering, render_static,render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix,exit_on_anykey); } //! Display object 3D in an interactive window \simplification. template<typename tp, typename tf, typename tc> const CImg<T>& display_object3d(const char *const title, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const bool centering=true, const int render_static=4, const int render_motion=1, const bool is_double_sided=true, const float focale=700, const float light_x=0, const float light_y=0, const float light_z=-5e8f, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const bool display_axes=true, float *const pose_matrix=0, const bool exit_on_anykey=false) const { return display_object3d(title,vertices,primitives,colors,CImgList<floatT>(),centering, render_static,render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix,exit_on_anykey); } //! Display object 3D in an interactive window \simplification. template<typename tp, typename tf> const CImg<T>& display_object3d(CImgDisplay &disp, const CImg<tp>& vertices, const CImgList<tf>& primitives, const bool centering=true, const int render_static=4, const int render_motion=1, const bool is_double_sided=true, const float focale=700, const float light_x=0, const float light_y=0, const float light_z=-5e8f, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const bool display_axes=true, float *const pose_matrix=0, const bool exit_on_anykey=false) const { return display_object3d(disp,vertices,primitives,CImgList<T>(),centering, render_static,render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix,exit_on_anykey); } //! Display object 3D in an interactive window \simplification. template<typename tp, typename tf> const CImg<T>& display_object3d(const char *const title, const CImg<tp>& vertices, const CImgList<tf>& primitives, const bool centering=true, const int render_static=4, const int render_motion=1, const bool is_double_sided=true, const float focale=700, const float light_x=0, const float light_y=0, const float light_z=-5e8f, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const bool display_axes=true, float *const pose_matrix=0, const bool exit_on_anykey=false) const { return display_object3d(title,vertices,primitives,CImgList<T>(),centering, render_static,render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix,exit_on_anykey); } //! Display object 3D in an interactive window \simplification. template<typename tp> const CImg<T>& display_object3d(CImgDisplay &disp, const CImg<tp>& vertices, const bool centering=true, const int render_static=4, const int render_motion=1, const bool is_double_sided=true, const float focale=700, const float light_x=0, const float light_y=0, const float light_z=-5e8f, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const bool display_axes=true, float *const pose_matrix=0, const bool exit_on_anykey=false) const { return display_object3d(disp,vertices,CImgList<uintT>(),centering, render_static,render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix,exit_on_anykey); } //! Display object 3D in an interactive window \simplification. template<typename tp> const CImg<T>& display_object3d(const char *const title, const CImg<tp>& vertices, const bool centering=true, const int render_static=4, const int render_motion=1, const bool is_double_sided=true, const float focale=700, const float light_x=0, const float light_y=0, const float light_z=-5e8f, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const bool display_axes=true, float *const pose_matrix=0, const bool exit_on_anykey=false) const { return display_object3d(title,vertices,CImgList<uintT>(),centering, render_static,render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix,exit_on_anykey); } template<typename tp, typename tf, typename tc, typename to> const CImg<T>& _display_object3d(CImgDisplay& disp, const char *const title, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const to& opacities, const bool centering, const int render_static, const int render_motion, const bool is_double_sided, const float focale, const float light_x, const float light_y, const float light_z, const float specular_lightness, const float specular_shininess, const bool display_axes, float *const pose_matrix, const bool exit_on_anykey) const { typedef typename cimg::superset<tp,float>::type tpfloat; // Check input arguments if (is_empty()) { if (disp) return CImg<T>(disp.width(),disp.height(),1,(colors && colors[0].size()==1)?1:3,0). _display_object3d(disp,title,vertices,primitives,colors,opacities,centering, render_static,render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix,exit_on_anykey); else return CImg<T>(1,2,1,1,64,128).resize(cimg_fitscreen(CImgDisplay::screen_width()/2, CImgDisplay::screen_height()/2,1), 1,(colors && colors[0].size()==1)?1:3,3). _display_object3d(disp,title,vertices,primitives,colors,opacities,centering, render_static,render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix,exit_on_anykey); } else { if (disp) disp.resize(*this,false); } CImg<charT> error_message(1024); if (!vertices.is_object3d(primitives,colors,opacities,true,error_message)) throw CImgArgumentException(_cimg_instance "display_object3d(): Invalid specified 3D object (%u,%u) (%s).", cimg_instance,vertices._width,primitives._width,error_message.data()); if (vertices._width && !primitives) { CImgList<tf> nprimitives(vertices._width,1,1,1,1); cimglist_for(nprimitives,l) nprimitives(l,0) = (tf)l; return _display_object3d(disp,title,vertices,nprimitives,colors,opacities,centering, render_static,render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix,exit_on_anykey); } if (!disp) { disp.assign(cimg_fitscreen(_width,_height,_depth),title?title:0,3); if (!title) disp.set_title("CImg<%s> (%u vertices, %u primitives)", pixel_type(),vertices._width,primitives._width); } else if (title) disp.set_title("%s",title); // Init 3D objects and compute object statistics CImg<floatT> pose, rotated_vertices(vertices._width,3), bbox_vertices, rotated_bbox_vertices, axes_vertices, rotated_axes_vertices, bbox_opacities, axes_opacities; CImgList<uintT> bbox_primitives, axes_primitives; CImgList<tf> reverse_primitives; CImgList<T> bbox_colors, bbox_colors2, axes_colors; unsigned int ns_width = 0, ns_height = 0; int _is_double_sided = (int)is_double_sided; bool ndisplay_axes = display_axes; const CImg<T> background_color(1,1,1,_spectrum,0), foreground_color(1,1,1,_spectrum,(T)std::min((int)cimg::type<T>::max(),255)); float Xoff = 0, Yoff = 0, Zoff = 0, sprite_scale = 1, xm = 0, xM = vertices?vertices.get_shared_row(0).max_min(xm):0, ym = 0, yM = vertices?vertices.get_shared_row(1).max_min(ym):0, zm = 0, zM = vertices?vertices.get_shared_row(2).max_min(zm):0; const float delta = cimg::max(xM - xm,yM - ym,zM - zm); rotated_bbox_vertices = bbox_vertices.assign(8,3,1,1, xm,xM,xM,xm,xm,xM,xM,xm, ym,ym,yM,yM,ym,ym,yM,yM, zm,zm,zm,zm,zM,zM,zM,zM); bbox_primitives.assign(6,1,4,1,1, 0,3,2,1, 4,5,6,7, 1,2,6,5, 0,4,7,3, 0,1,5,4, 2,3,7,6); bbox_colors.assign(6,_spectrum,1,1,1,background_color[0]); bbox_colors2.assign(6,_spectrum,1,1,1,foreground_color[0]); bbox_opacities.assign(bbox_colors._width,1,1,1,0.3f); rotated_axes_vertices = axes_vertices.assign(7,3,1,1, 0,20,0,0,22,-6,-6, 0,0,20,0,-6,22,-6, 0,0,0,20,0,0,22); axes_opacities.assign(3,1,1,1,1); axes_colors.assign(3,_spectrum,1,1,1,foreground_color[0]); axes_primitives.assign(3,1,2,1,1, 0,1, 0,2, 0,3); // Begin user interaction loop CImg<T> visu0(*this,false), visu; CImg<tpfloat> zbuffer(visu0.width(),visu0.height(),1,1,0); bool init_pose = true, clicked = false, redraw = true; unsigned int key = 0; int x0 = 0, y0 = 0, x1 = 0, y1 = 0, nrender_static = render_static, nrender_motion = render_motion; disp.show().flush(); while (!disp.is_closed() && !key) { // Init object pose if (init_pose) { const float ratio = delta>0?(2.f*std::min(disp.width(),disp.height())/(3.f*delta)):1, dx = (xM + xm)/2, dy = (yM + ym)/2, dz = (zM + zm)/2; if (centering) CImg<floatT>(4,3,1,1, ratio,0.,0.,-ratio*dx, 0.,ratio,0.,-ratio*dy, 0.,0.,ratio,-ratio*dz).move_to(pose); else CImg<floatT>(4,3,1,1, 1,0,0,0, 0,1,0,0, 0,0,1,0).move_to(pose); if (pose_matrix) { CImg<floatT> pose0(pose_matrix,4,3,1,1,false); pose0.resize(4,4,1,1,0); pose.resize(4,4,1,1,0); pose0(3,3) = pose(3,3) = 1; (pose0*pose).get_crop(0,0,3,2).move_to(pose); Xoff = pose_matrix[12]; Yoff = pose_matrix[13]; Zoff = pose_matrix[14]; sprite_scale = pose_matrix[15]; } else { Xoff = Yoff = Zoff = 0; sprite_scale = 1; } init_pose = false; redraw = true; } // Rotate and draw 3D object if (redraw) { const float r00 = pose(0,0), r10 = pose(1,0), r20 = pose(2,0), r30 = pose(3,0), r01 = pose(0,1), r11 = pose(1,1), r21 = pose(2,1), r31 = pose(3,1), r02 = pose(0,2), r12 = pose(1,2), r22 = pose(2,2), r32 = pose(3,2); if ((clicked && nrender_motion>=0) || (!clicked && nrender_static>=0)) cimg_forX(vertices,l) { const float x = (float)vertices(l,0), y = (float)vertices(l,1), z = (float)vertices(l,2); rotated_vertices(l,0) = r00*x + r10*y + r20*z + r30; rotated_vertices(l,1) = r01*x + r11*y + r21*z + r31; rotated_vertices(l,2) = r02*x + r12*y + r22*z + r32; } else cimg_forX(bbox_vertices,l) { const float x = bbox_vertices(l,0), y = bbox_vertices(l,1), z = bbox_vertices(l,2); rotated_bbox_vertices(l,0) = r00*x + r10*y + r20*z + r30; rotated_bbox_vertices(l,1) = r01*x + r11*y + r21*z + r31; rotated_bbox_vertices(l,2) = r02*x + r12*y + r22*z + r32; } // Draw objects const bool render_with_zbuffer = !clicked && nrender_static>0; visu = visu0; if ((clicked && nrender_motion<0) || (!clicked && nrender_static<0)) visu.draw_object3d(Xoff + visu._width/2.f,Yoff + visu._height/2.f,Zoff, rotated_bbox_vertices,bbox_primitives,bbox_colors,bbox_opacities,2,false,focale). draw_object3d(Xoff + visu._width/2.f,Yoff + visu._height/2.f,Zoff, rotated_bbox_vertices,bbox_primitives,bbox_colors2,1,false,focale); else visu._draw_object3d((void*)0,render_with_zbuffer?zbuffer.fill(0):CImg<tpfloat>::empty(), Xoff + visu._width/2.f,Yoff + visu._height/2.f,Zoff, rotated_vertices,reverse_primitives?reverse_primitives:primitives, colors,opacities,clicked?nrender_motion:nrender_static,_is_double_sided==1,focale, width()/2.f + light_x,height()/2.f + light_y,light_z + Zoff, specular_lightness,specular_shininess,1,sprite_scale); // Draw axes if (ndisplay_axes) { const float n = 1e-8f + cimg::hypot(r00,r01,r02), _r00 = r00/n, _r10 = r10/n, _r20 = r20/n, _r01 = r01/n, _r11 = r11/n, _r21 = r21/n, _r02 = r01/n, _r12 = r12/n, _r22 = r22/n, Xaxes = 25, Yaxes = visu._height - 38.f; cimg_forX(axes_vertices,l) { const float x = axes_vertices(l,0), y = axes_vertices(l,1), z = axes_vertices(l,2); rotated_axes_vertices(l,0) = _r00*x + _r10*y + _r20*z; rotated_axes_vertices(l,1) = _r01*x + _r11*y + _r21*z; rotated_axes_vertices(l,2) = _r02*x + _r12*y + _r22*z; } axes_opacities(0,0) = (rotated_axes_vertices(1,2)>0)?0.5f:1.f; axes_opacities(1,0) = (rotated_axes_vertices(2,2)>0)?0.5f:1.f; axes_opacities(2,0) = (rotated_axes_vertices(3,2)>0)?0.5f:1.f; visu.draw_object3d(Xaxes,Yaxes,0,rotated_axes_vertices,axes_primitives, axes_colors,axes_opacities,1,false,focale). draw_text((int)(Xaxes + rotated_axes_vertices(4,0)), (int)(Yaxes + rotated_axes_vertices(4,1)), "X",axes_colors[0]._data,0,axes_opacities(0,0),13). draw_text((int)(Xaxes + rotated_axes_vertices(5,0)), (int)(Yaxes + rotated_axes_vertices(5,1)), "Y",axes_colors[1]._data,0,axes_opacities(1,0),13). draw_text((int)(Xaxes + rotated_axes_vertices(6,0)), (int)(Yaxes + rotated_axes_vertices(6,1)), "Z",axes_colors[2]._data,0,axes_opacities(2,0),13); } visu.display(disp); if (!clicked || nrender_motion==nrender_static) redraw = false; } // Handle user interaction disp.wait(); if ((disp.button() || disp.wheel()) && disp.mouse_x()>=0 && disp.mouse_y()>=0) { redraw = true; if (!clicked) { x0 = x1 = disp.mouse_x(); y0 = y1 = disp.mouse_y(); if (!disp.wheel()) clicked = true; } else { x1 = disp.mouse_x(); y1 = disp.mouse_y(); } if (disp.button()&1) { const float R = 0.45f*std::min(disp.width(),disp.height()), R2 = R*R, u0 = (float)(x0 - disp.width()/2), v0 = (float)(y0 - disp.height()/2), u1 = (float)(x1 - disp.width()/2), v1 = (float)(y1 - disp.height()/2), n0 = cimg::hypot(u0,v0), n1 = cimg::hypot(u1,v1), nu0 = n0>R?(u0*R/n0):u0, nv0 = n0>R?(v0*R/n0):v0, nw0 = (float)std::sqrt(std::max(0.f,R2 - nu0*nu0 - nv0*nv0)), nu1 = n1>R?(u1*R/n1):u1, nv1 = n1>R?(v1*R/n1):v1, nw1 = (float)std::sqrt(std::max(0.f,R2 - nu1*nu1 - nv1*nv1)), u = nv0*nw1 - nw0*nv1, v = nw0*nu1 - nu0*nw1, w = nv0*nu1 - nu0*nv1, n = cimg::hypot(u,v,w), alpha = (float)std::asin(n/R2)*180/cimg::PI; (CImg<floatT>::rotation_matrix(u,v,w,-alpha)*pose).move_to(pose); x0 = x1; y0 = y1; } if (disp.button()&2) { if (focale>0) Zoff-=(y0 - y1)*focale/400; else { const float s = std::exp((y0 - y1)/400.f); pose*=s; sprite_scale*=s; } x0 = x1; y0 = y1; } if (disp.wheel()) { if (focale>0) Zoff-=disp.wheel()*focale/20; else { const float s = std::exp(disp.wheel()/20.f); pose*=s; sprite_scale*=s; } disp.set_wheel(); } if (disp.button()&4) { Xoff+=(x1 - x0); Yoff+=(y1 - y0); x0 = x1; y0 = y1; } if ((disp.button()&1) && (disp.button()&2)) { init_pose = true; disp.set_button(); x0 = x1; y0 = y1; pose = CImg<floatT>(4,3,1,1, 1,0,0,0, 0,1,0,0, 0,0,1,0); } } else if (clicked) { x0 = x1; y0 = y1; clicked = false; redraw = true; } CImg<charT> filename(32); switch (key = disp.key()) { #if cimg_OS!=2 case cimg::keyCTRLRIGHT : #endif case 0 : case cimg::keyCTRLLEFT : key = 0; break; case cimg::keyD: if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false). resize(CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,false), CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,true),false). _is_resized = true; disp.set_key(key,false); key = 0; } break; case cimg::keyC : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false). resize(cimg_fitscreen(2*disp.width()/3,2*disp.height()/3,1),false)._is_resized = true; disp.set_key(key,false); key = 0; } break; case cimg::keyR : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false).resize(cimg_fitscreen(_width,_height,_depth),false)._is_resized = true; disp.set_key(key,false); key = 0; } break; case cimg::keyF : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { if (!ns_width || !ns_height || ns_width>(unsigned int)disp.screen_width() || ns_height>(unsigned int)disp.screen_height()) { ns_width = disp.screen_width()*3U/4; ns_height = disp.screen_height()*3U/4; } if (disp.is_fullscreen()) disp.resize(ns_width,ns_height,false); else { ns_width = disp._width; ns_height = disp._height; disp.resize(disp.screen_width(),disp.screen_height(),false); } disp.toggle_fullscreen()._is_resized = true; disp.set_key(key,false); key = 0; } break; case cimg::keyT : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Switch single/double-sided primitives. if (--_is_double_sided==-2) _is_double_sided = 1; if (_is_double_sided>=0) reverse_primitives.assign(); else primitives.get_reverse_object3d().move_to(reverse_primitives); disp.set_key(key,false); key = 0; redraw = true; } break; case cimg::keyZ : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Enable/disable Z-buffer if (zbuffer) zbuffer.assign(); else zbuffer.assign(visu0.width(),visu0.height(),1,1,0); disp.set_key(key,false); key = 0; redraw = true; } break; case cimg::keyX : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Show/hide 3D axes ndisplay_axes = !ndisplay_axes; disp.set_key(key,false); key = 0; redraw = true; } break; case cimg::keyF1 : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Set rendering mode to points nrender_motion = (nrender_static==0 && nrender_motion!=0)?0:-1; nrender_static = 0; disp.set_key(key,false); key = 0; redraw = true; } break; case cimg::keyF2 : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Set rendering mode to lines nrender_motion = (nrender_static==1 && nrender_motion!=1)?1:-1; nrender_static = 1; disp.set_key(key,false); key = 0; redraw = true; } break; case cimg::keyF3 : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Set rendering mode to flat nrender_motion = (nrender_static==2 && nrender_motion!=2)?2:-1; nrender_static = 2; disp.set_key(key,false); key = 0; redraw = true; } break; case cimg::keyF4 : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Set rendering mode to flat-shaded nrender_motion = (nrender_static==3 && nrender_motion!=3)?3:-1; nrender_static = 3; disp.set_key(key,false); key = 0; redraw = true; } break; case cimg::keyF5 : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Set rendering mode to gouraud-shaded. nrender_motion = (nrender_static==4 && nrender_motion!=4)?4:-1; nrender_static = 4; disp.set_key(key,false); key = 0; redraw = true; } break; case cimg::keyF6 : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Set rendering mode to phong-shaded nrender_motion = (nrender_static==5 && nrender_motion!=5)?5:-1; nrender_static = 5; disp.set_key(key,false); key = 0; redraw = true; } break; case cimg::keyS : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Save snapshot static unsigned int snap_number = 0; std::FILE *file; do { cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.bmp",snap_number++); if ((file=cimg::std_fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); (+visu).__draw_text(" Saving snapshot... ",0).display(disp); visu.save(filename); (+visu).__draw_text(" Snapshot '%s' saved. ",0,filename._data).display(disp); disp.set_key(key,false); key = 0; } break; case cimg::keyG : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Save object as a .off file static unsigned int snap_number = 0; std::FILE *file; do { cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.off",snap_number++); if ((file=cimg::std_fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); (+visu).__draw_text(" Saving object... ",0).display(disp); vertices.save_off(reverse_primitives?reverse_primitives:primitives,colors,filename); (+visu).__draw_text(" Object '%s' saved. ",0,filename._data).display(disp); disp.set_key(key,false); key = 0; } break; case cimg::keyO : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Save object as a .cimg file static unsigned int snap_number = 0; std::FILE *file; do { #ifdef cimg_use_zlib cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.cimgz",snap_number++); #else cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.cimg",snap_number++); #endif if ((file=cimg::std_fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); (+visu).__draw_text(" Saving object... ",0).display(disp); vertices.get_object3dtoCImg3d(reverse_primitives?reverse_primitives:primitives,colors,opacities). save(filename); (+visu).__draw_text(" Object '%s' saved. ",0,filename._data).display(disp); disp.set_key(key,false); key = 0; } break; #ifdef cimg_use_board case cimg::keyP : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Save object as a .EPS file static unsigned int snap_number = 0; std::FILE *file; do { cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.eps",snap_number++); if ((file=cimg::std_fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); (+visu).__draw_text(" Saving EPS snapshot... ",0).display(disp); LibBoard::Board board; (+visu)._draw_object3d(&board,zbuffer.fill(0), Xoff + visu._width/2.f,Yoff + visu._height/2.f,Zoff, rotated_vertices,reverse_primitives?reverse_primitives:primitives, colors,opacities,clicked?nrender_motion:nrender_static, _is_double_sided==1,focale, visu.width()/2.f + light_x,visu.height()/2.f + light_y,light_z + Zoff, specular_lightness,specular_shininess,1, sprite_scale); board.saveEPS(filename); (+visu).__draw_text(" Object '%s' saved. ",0,filename._data).display(disp); disp.set_key(key,false); key = 0; } break; case cimg::keyV : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Save object as a .SVG file static unsigned int snap_number = 0; std::FILE *file; do { cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.svg",snap_number++); if ((file=cimg::std_fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); (+visu).__draw_text(" Saving SVG snapshot... ",0,13).display(disp); LibBoard::Board board; (+visu)._draw_object3d(&board,zbuffer.fill(0), Xoff + visu._width/2.f,Yoff + visu._height/2.f,Zoff, rotated_vertices,reverse_primitives?reverse_primitives:primitives, colors,opacities,clicked?nrender_motion:nrender_static, _is_double_sided==1,focale, visu.width()/2.f + light_x,visu.height()/2.f + light_y,light_z + Zoff, specular_lightness,specular_shininess,1, sprite_scale); board.saveSVG(filename); (+visu).__draw_text(" Object '%s' saved. ",0,filename._data).display(disp); disp.set_key(key,false); key = 0; } break; #endif } if (disp.is_resized()) { disp.resize(false); visu0 = get_resize(disp,1); if (zbuffer) zbuffer.assign(disp.width(),disp.height()); redraw = true; } if (!exit_on_anykey && key && key!=cimg::keyESC && (key!=cimg::keyW || (!disp.is_keyCTRLLEFT() && !disp.is_keyCTRLRIGHT()))) { key = 0; } } if (pose_matrix) { std::memcpy(pose_matrix,pose._data,12*sizeof(float)); pose_matrix[12] = Xoff; pose_matrix[13] = Yoff; pose_matrix[14] = Zoff; pose_matrix[15] = sprite_scale; } disp.set_button().set_key(key); return *this; } //! Display 1D graph in an interactive window. /** \param disp Display window. \param plot_type Plot type. Can be <tt>{ 0=points | 1=segments | 2=splines | 3=bars }</tt>. \param vertex_type Vertex type. \param labelx Title for the horizontal axis, as a C-string. \param xmin Minimum value along the X-axis. \param xmax Maximum value along the X-axis. \param labely Title for the vertical axis, as a C-string. \param ymin Minimum value along the X-axis. \param ymax Maximum value along the X-axis. \param exit_on_anykey Exit function when any key is pressed. **/ const CImg<T>& display_graph(CImgDisplay &disp, const unsigned int plot_type=1, const unsigned int vertex_type=1, const char *const labelx=0, const double xmin=0, const double xmax=0, const char *const labely=0, const double ymin=0, const double ymax=0, const bool exit_on_anykey=false) const { return _display_graph(disp,0,plot_type,vertex_type,labelx,xmin,xmax,labely,ymin,ymax,exit_on_anykey); } //! Display 1D graph in an interactive window \overloading. const CImg<T>& display_graph(const char *const title=0, const unsigned int plot_type=1, const unsigned int vertex_type=1, const char *const labelx=0, const double xmin=0, const double xmax=0, const char *const labely=0, const double ymin=0, const double ymax=0, const bool exit_on_anykey=false) const { CImgDisplay disp; return _display_graph(disp,title,plot_type,vertex_type,labelx,xmin,xmax,labely,ymin,ymax,exit_on_anykey); } const CImg<T>& _display_graph(CImgDisplay &disp, const char *const title=0, const unsigned int plot_type=1, const unsigned int vertex_type=1, const char *const labelx=0, const double xmin=0, const double xmax=0, const char *const labely=0, const double ymin=0, const double ymax=0, const bool exit_on_anykey=false) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "display_graph(): Empty instance.", cimg_instance); if (!disp) disp.assign(cimg_fitscreen(CImgDisplay::screen_width()/2,CImgDisplay::screen_height()/2,1),0,0). set_title(title?"%s":"CImg<%s>",title?title:pixel_type()); const ulongT siz = (ulongT)_width*_height*_depth, siz1 = std::max((ulongT)1,siz - 1); const unsigned int old_normalization = disp.normalization(); disp.show().flush()._normalization = 0; double y0 = ymin, y1 = ymax, nxmin = xmin, nxmax = xmax; if (nxmin==nxmax) { nxmin = 0; nxmax = siz1; } int x0 = 0, x1 = width()*height()*depth() - 1, key = 0; for (bool reset_view = true; !key && !disp.is_closed(); ) { if (reset_view) { x0 = 0; x1 = width()*height()*depth() - 1; y0 = ymin; y1 = ymax; reset_view = false; } CImg<T> zoom(x1 - x0 + 1,1,1,spectrum()); cimg_forC(*this,c) zoom.get_shared_channel(c) = CImg<T>(data(x0,0,0,c),x1 - x0 + 1,1,1,1,true); if (y0==y1) { y0 = zoom.min_max(y1); const double dy = y1 - y0; y0-=dy/20; y1+=dy/20; } if (y0==y1) { --y0; ++y1; } const CImg<intT> selection = zoom.get_select_graph(disp,plot_type,vertex_type, labelx, nxmin + x0*(nxmax - nxmin)/siz1, nxmin + x1*(nxmax - nxmin)/siz1, labely,y0,y1,true); const int mouse_x = disp.mouse_x(), mouse_y = disp.mouse_y(); if (selection[0]>=0) { if (selection[2]<0) reset_view = true; else { x1 = x0 + selection[2]; x0+=selection[0]; if (selection[1]>=0 && selection[3]>=0) { y0 = y1 - selection[3]*(y1 - y0)/(disp.height() - 32); y1-=selection[1]*(y1 - y0)/(disp.height() - 32); } } } else { bool go_in = false, go_out = false, go_left = false, go_right = false, go_up = false, go_down = false; switch (key = (int)disp.key()) { case cimg::keyHOME : reset_view = true; key = 0; disp.set_key(); break; case cimg::keyPADADD : go_in = true; go_out = false; key = 0; disp.set_key(); break; case cimg::keyPADSUB : go_out = true; go_in = false; key = 0; disp.set_key(); break; case cimg::keyARROWLEFT : case cimg::keyPAD4 : go_left = true; go_right = false; key = 0; disp.set_key(); break; case cimg::keyARROWRIGHT : case cimg::keyPAD6 : go_right = true; go_left = false; key = 0; disp.set_key(); break; case cimg::keyARROWUP : case cimg::keyPAD8 : go_up = true; go_down = false; key = 0; disp.set_key(); break; case cimg::keyARROWDOWN : case cimg::keyPAD2 : go_down = true; go_up = false; key = 0; disp.set_key(); break; case cimg::keyPAD7 : go_left = true; go_up = true; key = 0; disp.set_key(); break; case cimg::keyPAD9 : go_right = true; go_up = true; key = 0; disp.set_key(); break; case cimg::keyPAD1 : go_left = true; go_down = true; key = 0; disp.set_key(); break; case cimg::keyPAD3 : go_right = true; go_down = true; key = 0; disp.set_key(); break; } if (disp.wheel()) { if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) go_up = !(go_down = disp.wheel()<0); else if (disp.is_keySHIFTLEFT() || disp.is_keySHIFTRIGHT()) go_left = !(go_right = disp.wheel()>0); else go_out = !(go_in = disp.wheel()>0); key = 0; } if (go_in) { const int xsiz = x1 - x0, mx = (mouse_x - 16)*xsiz/(disp.width() - 32), cx = x0 + cimg::cut(mx,0,xsiz); if (x1 - x0>4) { x0 = cx - 7*(cx - x0)/8; x1 = cx + 7*(x1 - cx)/8; if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { const double ysiz = y1 - y0, my = (mouse_y - 16)*ysiz/(disp.height() - 32), cy = y1 - cimg::cut(my,0.,ysiz); y0 = cy - 7*(cy - y0)/8; y1 = cy + 7*(y1 - cy)/8; } else y0 = y1 = 0; } } if (go_out) { if (x0>0 || x1<(int)siz1) { const int delta_x = (x1 - x0)/8, ndelta_x = delta_x?delta_x:(siz>1); const double ndelta_y = (y1 - y0)/8; x0-=ndelta_x; x1+=ndelta_x; y0-=ndelta_y; y1+=ndelta_y; if (x0<0) { x1-=x0; x0 = 0; if (x1>=(int)siz) x1 = (int)siz1; } if (x1>=(int)siz) { x0-=(x1 - siz1); x1 = (int)siz1; if (x0<0) x0 = 0; } } } if (go_left) { const int delta = (x1 - x0)/5, ndelta = delta?delta:1; if (x0 - ndelta>=0) { x0-=ndelta; x1-=ndelta; } else { x1-=x0; x0 = 0; } go_left = false; } if (go_right) { const int delta = (x1 - x0)/5, ndelta = delta?delta:1; if (x1 + ndelta<(int)siz) { x0+=ndelta; x1+=ndelta; } else { x0+=(siz1 - x1); x1 = (int)siz1; } go_right = false; } if (go_up) { const double delta = (y1 - y0)/10, ndelta = delta?delta:1; y0+=ndelta; y1+=ndelta; go_up = false; } if (go_down) { const double delta = (y1 - y0)/10, ndelta = delta?delta:1; y0-=ndelta; y1-=ndelta; go_down = false; } } if (!exit_on_anykey && key && key!=(int)cimg::keyESC && (key!=(int)cimg::keyW || (!disp.is_keyCTRLLEFT() && !disp.is_keyCTRLRIGHT()))) { disp.set_key(key,false); key = 0; } } disp._normalization = old_normalization; return *this; } //! Save image as a file. /** \param filename Filename, as a C-string. \param number When positive, represents an index added to the filename. Otherwise, no number is added. \param digits Number of digits used for adding the number to the filename. \note - The used file format is defined by the file extension in the filename \p filename. - Parameter \p number can be used to add a 6-digit number to the filename before saving. **/ const CImg<T>& save(const char *const filename, const int number=-1, const unsigned int digits=6) const { if (!filename) throw CImgArgumentException(_cimg_instance "save(): Specified filename is (null).", cimg_instance); // Do not test for empty instances, since .cimg format is able to manage empty instances. const bool is_stdout = *filename=='-' && (!filename[1] || filename[1]=='.'); const char *const ext = cimg::split_filename(filename); CImg<charT> nfilename(1024); const char *const fn = is_stdout?filename:(number>=0)?cimg::number_filename(filename,number,digits,nfilename): filename; #ifdef cimg_save_plugin cimg_save_plugin(fn); #endif #ifdef cimg_save_plugin1 cimg_save_plugin1(fn); #endif #ifdef cimg_save_plugin2 cimg_save_plugin2(fn); #endif #ifdef cimg_save_plugin3 cimg_save_plugin3(fn); #endif #ifdef cimg_save_plugin4 cimg_save_plugin4(fn); #endif #ifdef cimg_save_plugin5 cimg_save_plugin5(fn); #endif #ifdef cimg_save_plugin6 cimg_save_plugin6(fn); #endif #ifdef cimg_save_plugin7 cimg_save_plugin7(fn); #endif #ifdef cimg_save_plugin8 cimg_save_plugin8(fn); #endif // Ascii formats if (!cimg::strcasecmp(ext,"asc")) return save_ascii(fn); else if (!cimg::strcasecmp(ext,"dlm") || !cimg::strcasecmp(ext,"txt")) return save_dlm(fn); else if (!cimg::strcasecmp(ext,"cpp") || !cimg::strcasecmp(ext,"hpp") || !cimg::strcasecmp(ext,"h") || !cimg::strcasecmp(ext,"c")) return save_cpp(fn); // 2D binary formats else if (!cimg::strcasecmp(ext,"bmp")) return save_bmp(fn); else if (!cimg::strcasecmp(ext,"jpg") || !cimg::strcasecmp(ext,"jpeg") || !cimg::strcasecmp(ext,"jpe") || !cimg::strcasecmp(ext,"jfif") || !cimg::strcasecmp(ext,"jif")) return save_jpeg(fn); else if (!cimg::strcasecmp(ext,"rgb")) return save_rgb(fn); else if (!cimg::strcasecmp(ext,"rgba")) return save_rgba(fn); else if (!cimg::strcasecmp(ext,"png")) return save_png(fn); else if (!cimg::strcasecmp(ext,"pgm") || !cimg::strcasecmp(ext,"ppm") || !cimg::strcasecmp(ext,"pnm")) return save_pnm(fn); else if (!cimg::strcasecmp(ext,"pnk")) return save_pnk(fn); else if (!cimg::strcasecmp(ext,"pfm")) return save_pfm(fn); else if (!cimg::strcasecmp(ext,"exr")) return save_exr(fn); else if (!cimg::strcasecmp(ext,"tif") || !cimg::strcasecmp(ext,"tiff")) return save_tiff(fn); // 3D binary formats else if (!*ext) { #ifdef cimg_use_zlib return save_cimg(fn,true); #else return save_cimg(fn,false); #endif } else if (!cimg::strcasecmp(ext,"cimgz")) return save_cimg(fn,true); else if (!cimg::strcasecmp(ext,"cimg")) return save_cimg(fn,false); else if (!cimg::strcasecmp(ext,"dcm")) return save_medcon_external(fn); else if (!cimg::strcasecmp(ext,"hdr") || !cimg::strcasecmp(ext,"nii")) return save_analyze(fn); else if (!cimg::strcasecmp(ext,"inr")) return save_inr(fn); else if (!cimg::strcasecmp(ext,"mnc")) return save_minc2(fn); else if (!cimg::strcasecmp(ext,"pan")) return save_pandore(fn); else if (!cimg::strcasecmp(ext,"raw")) return save_raw(fn); // Archive files else if (!cimg::strcasecmp(ext,"gz")) return save_gzip_external(fn); // Image sequences else if (!cimg::strcasecmp(ext,"yuv")) return save_yuv(fn,444,true); else if (!cimg::strcasecmp(ext,"avi") || !cimg::strcasecmp(ext,"mov") || !cimg::strcasecmp(ext,"asf") || !cimg::strcasecmp(ext,"divx") || !cimg::strcasecmp(ext,"flv") || !cimg::strcasecmp(ext,"mpg") || !cimg::strcasecmp(ext,"m1v") || !cimg::strcasecmp(ext,"m2v") || !cimg::strcasecmp(ext,"m4v") || !cimg::strcasecmp(ext,"mjp") || !cimg::strcasecmp(ext,"mp4") || !cimg::strcasecmp(ext,"mkv") || !cimg::strcasecmp(ext,"mpe") || !cimg::strcasecmp(ext,"movie") || !cimg::strcasecmp(ext,"ogm") || !cimg::strcasecmp(ext,"ogg") || !cimg::strcasecmp(ext,"ogv") || !cimg::strcasecmp(ext,"qt") || !cimg::strcasecmp(ext,"rm") || !cimg::strcasecmp(ext,"vob") || !cimg::strcasecmp(ext,"wmv") || !cimg::strcasecmp(ext,"xvid") || !cimg::strcasecmp(ext,"mpeg")) return save_video(fn); return save_other(fn); } //! Save image as an Ascii file. /** \param filename Filename, as a C-string. **/ const CImg<T>& save_ascii(const char *const filename) const { return _save_ascii(0,filename); } //! Save image as an Ascii file \overloading. const CImg<T>& save_ascii(std::FILE *const file) const { return _save_ascii(file,0); } const CImg<T>& _save_ascii(std::FILE *const file, const char *const filename) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_ascii(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"w"); std::fprintf(nfile,"%u %u %u %u\n",_width,_height,_depth,_spectrum); const T* ptrs = _data; cimg_forYZC(*this,y,z,c) { cimg_forX(*this,x) std::fprintf(nfile,"%.17g ",(double)*(ptrs++)); std::fputc('\n',nfile); } if (!file) cimg::fclose(nfile); return *this; } //! Save image as a .cpp source file. /** \param filename Filename, as a C-string. **/ const CImg<T>& save_cpp(const char *const filename) const { return _save_cpp(0,filename); } //! Save image as a .cpp source file \overloading. const CImg<T>& save_cpp(std::FILE *const file) const { return _save_cpp(file,0); } const CImg<T>& _save_cpp(std::FILE *const file, const char *const filename) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_cpp(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"w"); CImg<charT> varname(1024); *varname = 0; if (filename) cimg_sscanf(cimg::basename(filename),"%1023[a-zA-Z0-9_]",varname._data); if (!*varname) cimg_snprintf(varname,varname._width,"unnamed"); std::fprintf(nfile, "/* Define image '%s' of size %ux%ux%ux%u and type '%s' */\n" "%s data_%s[] = { %s\n ", varname._data,_width,_height,_depth,_spectrum,pixel_type(),pixel_type(),varname._data, is_empty()?"};":""); if (!is_empty()) for (ulongT off = 0, siz = size() - 1; off<=siz; ++off) { std::fprintf(nfile,cimg::type<T>::format(),cimg::type<T>::format((*this)[off])); if (off==siz) std::fprintf(nfile," };\n"); else if (!((off + 1)%16)) std::fprintf(nfile,",\n "); else std::fprintf(nfile,", "); } if (!file) cimg::fclose(nfile); return *this; } //! Save image as a DLM file. /** \param filename Filename, as a C-string. **/ const CImg<T>& save_dlm(const char *const filename) const { return _save_dlm(0,filename); } //! Save image as a DLM file \overloading. const CImg<T>& save_dlm(std::FILE *const file) const { return _save_dlm(file,0); } const CImg<T>& _save_dlm(std::FILE *const file, const char *const filename) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_dlm(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(file,filename); return *this; } if (_depth>1) cimg::warn(_cimg_instance "save_dlm(): Instance is volumetric, values along Z will be unrolled in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); if (_spectrum>1) cimg::warn(_cimg_instance "save_dlm(): Instance is multispectral, values along C will be unrolled in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"w"); const T* ptrs = _data; cimg_forYZC(*this,y,z,c) { cimg_forX(*this,x) std::fprintf(nfile,"%.17g%s",(double)*(ptrs++),(x==width() - 1)?"":","); std::fputc('\n',nfile); } if (!file) cimg::fclose(nfile); return *this; } //! Save image as a BMP file. /** \param filename Filename, as a C-string. **/ const CImg<T>& save_bmp(const char *const filename) const { return _save_bmp(0,filename); } //! Save image as a BMP file \overloading. const CImg<T>& save_bmp(std::FILE *const file) const { return _save_bmp(file,0); } const CImg<T>& _save_bmp(std::FILE *const file, const char *const filename) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_bmp(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(file,filename); return *this; } if (_depth>1) cimg::warn(_cimg_instance "save_bmp(): Instance is volumetric, only the first slice will be saved in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); if (_spectrum>3) cimg::warn(_cimg_instance "save_bmp(): Instance is multispectral, only the three first channels will be saved in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); CImg<ucharT> header(54,1,1,1,0); unsigned char align_buf[4] = { 0 }; const unsigned int align = (4 - (3*_width)%4)%4, buf_size = (3*_width + align)*height(), file_size = 54 + buf_size; header[0] = 'B'; header[1] = 'M'; header[0x02] = file_size&0xFF; header[0x03] = (file_size>>8)&0xFF; header[0x04] = (file_size>>16)&0xFF; header[0x05] = (file_size>>24)&0xFF; header[0x0A] = 0x36; header[0x0E] = 0x28; header[0x12] = _width&0xFF; header[0x13] = (_width>>8)&0xFF; header[0x14] = (_width>>16)&0xFF; header[0x15] = (_width>>24)&0xFF; header[0x16] = _height&0xFF; header[0x17] = (_height>>8)&0xFF; header[0x18] = (_height>>16)&0xFF; header[0x19] = (_height>>24)&0xFF; header[0x1A] = 1; header[0x1B] = 0; header[0x1C] = 24; header[0x1D] = 0; header[0x22] = buf_size&0xFF; header[0x23] = (buf_size>>8)&0xFF; header[0x24] = (buf_size>>16)&0xFF; header[0x25] = (buf_size>>24)&0xFF; header[0x27] = 0x1; header[0x2B] = 0x1; cimg::fwrite(header._data,54,nfile); const T *ptr_r = data(0,_height - 1,0,0), *ptr_g = (_spectrum>=2)?data(0,_height - 1,0,1):0, *ptr_b = (_spectrum>=3)?data(0,_height - 1,0,2):0; switch (_spectrum) { case 1 : { cimg_forY(*this,y) { cimg_forX(*this,x) { const unsigned char val = (unsigned char)*(ptr_r++); std::fputc(val,nfile); std::fputc(val,nfile); std::fputc(val,nfile); } cimg::fwrite(align_buf,align,nfile); ptr_r-=2*_width; } } break; case 2 : { cimg_forY(*this,y) { cimg_forX(*this,x) { std::fputc(0,nfile); std::fputc((unsigned char)(*(ptr_g++)),nfile); std::fputc((unsigned char)(*(ptr_r++)),nfile); } cimg::fwrite(align_buf,align,nfile); ptr_r-=2*_width; ptr_g-=2*_width; } } break; default : { cimg_forY(*this,y) { cimg_forX(*this,x) { std::fputc((unsigned char)(*(ptr_b++)),nfile); std::fputc((unsigned char)(*(ptr_g++)),nfile); std::fputc((unsigned char)(*(ptr_r++)),nfile); } cimg::fwrite(align_buf,align,nfile); ptr_r-=2*_width; ptr_g-=2*_width; ptr_b-=2*_width; } } } if (!file) cimg::fclose(nfile); return *this; } //! Save image as a JPEG file. /** \param filename Filename, as a C-string. \param quality Image quality (in %) **/ const CImg<T>& save_jpeg(const char *const filename, const unsigned int quality=100) const { return _save_jpeg(0,filename,quality); } //! Save image as a JPEG file \overloading. const CImg<T>& save_jpeg(std::FILE *const file, const unsigned int quality=100) const { return _save_jpeg(file,0,quality); } const CImg<T>& _save_jpeg(std::FILE *const file, const char *const filename, const unsigned int quality) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_jpeg(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(file,filename); return *this; } if (_depth>1) cimg::warn(_cimg_instance "save_jpeg(): Instance is volumetric, only the first slice will be saved in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); #ifndef cimg_use_jpeg if (!file) return save_other(filename,quality); else throw CImgIOException(_cimg_instance "save_jpeg(): Unable to save data in '(*FILE)' unless libjpeg is enabled.", cimg_instance); #else unsigned int dimbuf = 0; J_COLOR_SPACE colortype = JCS_RGB; switch (_spectrum) { case 1 : dimbuf = 1; colortype = JCS_GRAYSCALE; break; case 2 : dimbuf = 3; colortype = JCS_RGB; break; case 3 : dimbuf = 3; colortype = JCS_RGB; break; default : dimbuf = 4; colortype = JCS_CMYK; break; } // Call libjpeg functions struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); jpeg_stdio_dest(&cinfo,nfile); cinfo.image_width = _width; cinfo.image_height = _height; cinfo.input_components = dimbuf; cinfo.in_color_space = colortype; jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo,quality<100?quality:100,TRUE); jpeg_start_compress(&cinfo,TRUE); JSAMPROW row_pointer[1]; CImg<ucharT> buffer(_width*dimbuf); while (cinfo.next_scanline<cinfo.image_height) { unsigned char *ptrd = buffer._data; // Fill pixel buffer switch (_spectrum) { case 1 : { // Greyscale images const T *ptr_g = data(0, cinfo.next_scanline); for (unsigned int b = 0; b<cinfo.image_width; b++) *(ptrd++) = (unsigned char)*(ptr_g++); } break; case 2 : { // RG images const T *ptr_r = data(0,cinfo.next_scanline,0,0), *ptr_g = data(0,cinfo.next_scanline,0,1); for (unsigned int b = 0; b<cinfo.image_width; ++b) { *(ptrd++) = (unsigned char)*(ptr_r++); *(ptrd++) = (unsigned char)*(ptr_g++); *(ptrd++) = 0; } } break; case 3 : { // RGB images const T *ptr_r = data(0,cinfo.next_scanline,0,0), *ptr_g = data(0,cinfo.next_scanline,0,1), *ptr_b = data(0,cinfo.next_scanline,0,2); for (unsigned int b = 0; b<cinfo.image_width; ++b) { *(ptrd++) = (unsigned char)*(ptr_r++); *(ptrd++) = (unsigned char)*(ptr_g++); *(ptrd++) = (unsigned char)*(ptr_b++); } } break; default : { // CMYK images const T *ptr_r = data(0,cinfo.next_scanline,0,0), *ptr_g = data(0,cinfo.next_scanline,0,1), *ptr_b = data(0,cinfo.next_scanline,0,2), *ptr_a = data(0,cinfo.next_scanline,0,3); for (unsigned int b = 0; b<cinfo.image_width; ++b) { *(ptrd++) = (unsigned char)*(ptr_r++); *(ptrd++) = (unsigned char)*(ptr_g++); *(ptrd++) = (unsigned char)*(ptr_b++); *(ptrd++) = (unsigned char)*(ptr_a++); } } } *row_pointer = buffer._data; jpeg_write_scanlines(&cinfo,row_pointer,1); } jpeg_finish_compress(&cinfo); if (!file) cimg::fclose(nfile); jpeg_destroy_compress(&cinfo); return *this; #endif } //! Save image, using built-in ImageMagick++ library. /** \param filename Filename, as a C-string. \param bytes_per_pixel Force the number of bytes per pixel for the saving, when possible. **/ const CImg<T>& save_magick(const char *const filename, const unsigned int bytes_per_pixel=0) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_magick(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(0,filename); return *this; } #ifdef cimg_use_magick double stmin, stmax = (double)max_min(stmin); if (_depth>1) cimg::warn(_cimg_instance "save_magick(): Instance is volumetric, only the first slice will be saved in file '%s'.", cimg_instance, filename); if (_spectrum>3) cimg::warn(_cimg_instance "save_magick(): Instance is multispectral, only the three first channels will be " "saved in file '%s'.", cimg_instance, filename); if (stmin<0 || (bytes_per_pixel==1 && stmax>=256) || stmax>=65536) cimg::warn(_cimg_instance "save_magick(): Instance has pixel values in [%g,%g], probable type overflow in file '%s'.", cimg_instance, filename,stmin,stmax); Magick::Image image(Magick::Geometry(_width,_height),"black"); image.type(Magick::TrueColorType); image.depth(bytes_per_pixel?(8*bytes_per_pixel):(stmax>=256?16:8)); const T *ptr_r = data(0,0,0,0), *ptr_g = _spectrum>1?data(0,0,0,1):0, *ptr_b = _spectrum>2?data(0,0,0,2):0; Magick::PixelPacket *pixels = image.getPixels(0,0,_width,_height); switch (_spectrum) { case 1 : // Scalar images for (ulongT off = (ulongT)_width*_height; off; --off) { pixels->red = pixels->green = pixels->blue = (Magick::Quantum)*(ptr_r++); ++pixels; } break; case 2 : // RG images for (ulongT off = (ulongT)_width*_height; off; --off) { pixels->red = (Magick::Quantum)*(ptr_r++); pixels->green = (Magick::Quantum)*(ptr_g++); pixels->blue = 0; ++pixels; } break; default : // RGB images for (ulongT off = (ulongT)_width*_height; off; --off) { pixels->red = (Magick::Quantum)*(ptr_r++); pixels->green = (Magick::Quantum)*(ptr_g++); pixels->blue = (Magick::Quantum)*(ptr_b++); ++pixels; } } image.syncPixels(); image.write(filename); return *this; #else cimg::unused(bytes_per_pixel); throw CImgIOException(_cimg_instance "save_magick(): Unable to save file '%s' unless libMagick++ is enabled.", cimg_instance, filename); #endif } //! Save image as a PNG file. /** \param filename Filename, as a C-string. \param bytes_per_pixel Force the number of bytes per pixels for the saving, when possible. **/ const CImg<T>& save_png(const char *const filename, const unsigned int bytes_per_pixel=0) const { return _save_png(0,filename,bytes_per_pixel); } //! Save image as a PNG file \overloading. const CImg<T>& save_png(std::FILE *const file, const unsigned int bytes_per_pixel=0) const { return _save_png(file,0,bytes_per_pixel); } const CImg<T>& _save_png(std::FILE *const file, const char *const filename, const unsigned int bytes_per_pixel=0) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_png(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(file,filename); return *this; } #ifndef cimg_use_png cimg::unused(bytes_per_pixel); if (!file) return save_other(filename); else throw CImgIOException(_cimg_instance "save_png(): Unable to save data in '(*FILE)' unless libpng is enabled.", cimg_instance); #else #if defined __GNUC__ const char *volatile nfilename = filename; // Use 'volatile' to avoid (wrong) g++ warning std::FILE *volatile nfile = file?file:cimg::fopen(nfilename,"wb"); volatile double stmin, stmax = (double)max_min(stmin); #else const char *nfilename = filename; std::FILE *nfile = file?file:cimg::fopen(nfilename,"wb"); double stmin, stmax = (double)max_min(stmin); #endif if (_depth>1) cimg::warn(_cimg_instance "save_png(): Instance is volumetric, only the first slice will be saved in file '%s'.", cimg_instance, filename); if (_spectrum>4) cimg::warn(_cimg_instance "save_png(): Instance is multispectral, only the three first channels will be saved in file '%s'.", cimg_instance, filename); if (stmin<0 || (bytes_per_pixel==1 && stmax>=256) || stmax>=65536) cimg::warn(_cimg_instance "save_png(): Instance has pixel values in [%g,%g], probable type overflow in file '%s'.", cimg_instance, filename,stmin,stmax); // Setup PNG structures for write png_voidp user_error_ptr = 0; png_error_ptr user_error_fn = 0, user_warning_fn = 0; png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,user_error_ptr, user_error_fn, user_warning_fn); if (!png_ptr){ if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "save_png(): Failed to initialize 'png_ptr' structure when saving file '%s'.", cimg_instance, nfilename?nfilename:"(FILE*)"); } png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_write_struct(&png_ptr,(png_infopp)0); if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "save_png(): Failed to initialize 'info_ptr' structure when saving file '%s'.", cimg_instance, nfilename?nfilename:"(FILE*)"); } if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_write_struct(&png_ptr, &info_ptr); if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "save_png(): Encountered unknown fatal error in libpng when saving file '%s'.", cimg_instance, nfilename?nfilename:"(FILE*)"); } png_init_io(png_ptr, nfile); const int bit_depth = bytes_per_pixel?(bytes_per_pixel*8):(stmax>=256?16:8); int color_type; switch (spectrum()) { case 1 : color_type = PNG_COLOR_TYPE_GRAY; break; case 2 : color_type = PNG_COLOR_TYPE_GRAY_ALPHA; break; case 3 : color_type = PNG_COLOR_TYPE_RGB; break; default : color_type = PNG_COLOR_TYPE_RGB_ALPHA; } const int interlace_type = PNG_INTERLACE_NONE; const int compression_type = PNG_COMPRESSION_TYPE_DEFAULT; const int filter_method = PNG_FILTER_TYPE_DEFAULT; png_set_IHDR(png_ptr,info_ptr,_width,_height,bit_depth,color_type,interlace_type,compression_type,filter_method); png_write_info(png_ptr,info_ptr); const int byte_depth = bit_depth>>3; const int numChan = spectrum()>4?4:spectrum(); const int pixel_bit_depth_flag = numChan * (bit_depth - 1); // Allocate Memory for Image Save and Fill pixel data png_bytep *const imgData = new png_byte*[_height]; for (unsigned int row = 0; row<_height; ++row) imgData[row] = new png_byte[byte_depth*numChan*_width]; const T *pC0 = data(0,0,0,0); switch (pixel_bit_depth_flag) { case 7 : { // Gray 8-bit cimg_forY(*this,y) { unsigned char *ptrd = imgData[y]; cimg_forX(*this,x) *(ptrd++) = (unsigned char)*(pC0++); } } break; case 14 : { // Gray w/ Alpha 8-bit const T *pC1 = data(0,0,0,1); cimg_forY(*this,y) { unsigned char *ptrd = imgData[y]; cimg_forX(*this,x) { *(ptrd++) = (unsigned char)*(pC0++); *(ptrd++) = (unsigned char)*(pC1++); } } } break; case 21 : { // RGB 8-bit const T *pC1 = data(0,0,0,1), *pC2 = data(0,0,0,2); cimg_forY(*this,y) { unsigned char *ptrd = imgData[y]; cimg_forX(*this,x) { *(ptrd++) = (unsigned char)*(pC0++); *(ptrd++) = (unsigned char)*(pC1++); *(ptrd++) = (unsigned char)*(pC2++); } } } break; case 28 : { // RGB x/ Alpha 8-bit const T *pC1 = data(0,0,0,1), *pC2 = data(0,0,0,2), *pC3 = data(0,0,0,3); cimg_forY(*this,y){ unsigned char *ptrd = imgData[y]; cimg_forX(*this,x){ *(ptrd++) = (unsigned char)*(pC0++); *(ptrd++) = (unsigned char)*(pC1++); *(ptrd++) = (unsigned char)*(pC2++); *(ptrd++) = (unsigned char)*(pC3++); } } } break; case 15 : { // Gray 16-bit cimg_forY(*this,y){ unsigned short *ptrd = (unsigned short*)(imgData[y]); cimg_forX(*this,x) *(ptrd++) = (unsigned short)*(pC0++); if (!cimg::endianness()) cimg::invert_endianness((unsigned short*)imgData[y],_width); } } break; case 30 : { // Gray w/ Alpha 16-bit const T *pC1 = data(0,0,0,1); cimg_forY(*this,y){ unsigned short *ptrd = (unsigned short*)(imgData[y]); cimg_forX(*this,x) { *(ptrd++) = (unsigned short)*(pC0++); *(ptrd++) = (unsigned short)*(pC1++); } if (!cimg::endianness()) cimg::invert_endianness((unsigned short*)imgData[y],2*_width); } } break; case 45 : { // RGB 16-bit const T *pC1 = data(0,0,0,1), *pC2 = data(0,0,0,2); cimg_forY(*this,y) { unsigned short *ptrd = (unsigned short*)(imgData[y]); cimg_forX(*this,x) { *(ptrd++) = (unsigned short)*(pC0++); *(ptrd++) = (unsigned short)*(pC1++); *(ptrd++) = (unsigned short)*(pC2++); } if (!cimg::endianness()) cimg::invert_endianness((unsigned short*)imgData[y],3*_width); } } break; case 60 : { // RGB w/ Alpha 16-bit const T *pC1 = data(0,0,0,1), *pC2 = data(0,0,0,2), *pC3 = data(0,0,0,3); cimg_forY(*this,y) { unsigned short *ptrd = (unsigned short*)(imgData[y]); cimg_forX(*this,x) { *(ptrd++) = (unsigned short)*(pC0++); *(ptrd++) = (unsigned short)*(pC1++); *(ptrd++) = (unsigned short)*(pC2++); *(ptrd++) = (unsigned short)*(pC3++); } if (!cimg::endianness()) cimg::invert_endianness((unsigned short*)imgData[y],4*_width); } } break; default : if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "save_png(): Encountered unknown fatal error in libpng when saving file '%s'.", cimg_instance, nfilename?nfilename:"(FILE*)"); } png_write_image(png_ptr,imgData); png_write_end(png_ptr,info_ptr); png_destroy_write_struct(&png_ptr, &info_ptr); // Deallocate Image Write Memory cimg_forY(*this,n) delete[] imgData[n]; delete[] imgData; if (!file) cimg::fclose(nfile); return *this; #endif } //! Save image as a PNM file. /** \param filename Filename, as a C-string. \param bytes_per_pixel Force the number of bytes per pixels for the saving. **/ const CImg<T>& save_pnm(const char *const filename, const unsigned int bytes_per_pixel=0) const { return _save_pnm(0,filename,bytes_per_pixel); } //! Save image as a PNM file \overloading. const CImg<T>& save_pnm(std::FILE *const file, const unsigned int bytes_per_pixel=0) const { return _save_pnm(file,0,bytes_per_pixel); } const CImg<T>& _save_pnm(std::FILE *const file, const char *const filename, const unsigned int bytes_per_pixel=0) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_pnm(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(file,filename); return *this; } double stmin, stmax = (double)max_min(stmin); if (_depth>1) cimg::warn(_cimg_instance "save_pnm(): Instance is volumetric, only the first slice will be saved in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); if (_spectrum>3) cimg::warn(_cimg_instance "save_pnm(): Instance is multispectral, only the three first channels will be saved in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); if (stmin<0 || (bytes_per_pixel==1 && stmax>=256) || stmax>=65536) cimg::warn(_cimg_instance "save_pnm(): Instance has pixel values in [%g,%g], probable type overflow in file '%s'.", cimg_instance, stmin,stmax,filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); const T *ptr_r = data(0,0,0,0), *ptr_g = (_spectrum>=2)?data(0,0,0,1):0, *ptr_b = (_spectrum>=3)?data(0,0,0,2):0; const ulongT buf_size = std::min((ulongT)(1024*1024),(ulongT)(_width*_height*(_spectrum==1?1UL:3UL))); std::fprintf(nfile,"P%c\n%u %u\n%u\n", (_spectrum==1?'5':'6'),_width,_height,stmax<256?255:(stmax<4096?4095:65535)); switch (_spectrum) { case 1 : { // Scalar image if (bytes_per_pixel==1 || (!bytes_per_pixel && stmax<256)) { // Binary PGM 8 bits CImg<ucharT> buf((unsigned int)buf_size); for (longT to_write = (longT)width()*height(); to_write>0; ) { const ulongT N = std::min((ulongT)to_write,buf_size); unsigned char *ptrd = buf._data; for (ulongT i = N; i>0; --i) *(ptrd++) = (unsigned char)*(ptr_r++); cimg::fwrite(buf._data,N,nfile); to_write-=N; } } else { // Binary PGM 16 bits CImg<ushortT> buf((unsigned int)buf_size); for (longT to_write = (longT)width()*height(); to_write>0; ) { const ulongT N = std::min((ulongT)to_write,buf_size); unsigned short *ptrd = buf._data; for (ulongT i = N; i>0; --i) *(ptrd++) = (unsigned short)*(ptr_r++); if (!cimg::endianness()) cimg::invert_endianness(buf._data,buf_size); cimg::fwrite(buf._data,N,nfile); to_write-=N; } } } break; case 2 : { // RG image if (bytes_per_pixel==1 || (!bytes_per_pixel && stmax<256)) { // Binary PPM 8 bits CImg<ucharT> buf((unsigned int)buf_size); for (longT to_write = (longT)width()*height(); to_write>0; ) { const ulongT N = std::min((ulongT)to_write,buf_size/3); unsigned char *ptrd = buf._data; for (ulongT i = N; i>0; --i) { *(ptrd++) = (unsigned char)*(ptr_r++); *(ptrd++) = (unsigned char)*(ptr_g++); *(ptrd++) = 0; } cimg::fwrite(buf._data,3*N,nfile); to_write-=N; } } else { // Binary PPM 16 bits CImg<ushortT> buf((unsigned int)buf_size); for (longT to_write = (longT)width()*height(); to_write>0; ) { const ulongT N = std::min((ulongT)to_write,buf_size/3); unsigned short *ptrd = buf._data; for (ulongT i = N; i>0; --i) { *(ptrd++) = (unsigned short)*(ptr_r++); *(ptrd++) = (unsigned short)*(ptr_g++); *(ptrd++) = 0; } if (!cimg::endianness()) cimg::invert_endianness(buf._data,buf_size); cimg::fwrite(buf._data,3*N,nfile); to_write-=N; } } } break; default : { // RGB image if (bytes_per_pixel==1 || (!bytes_per_pixel && stmax<256)) { // Binary PPM 8 bits CImg<ucharT> buf((unsigned int)buf_size); for (longT to_write = (longT)width()*height(); to_write>0; ) { const ulongT N = std::min((ulongT)to_write,buf_size/3); unsigned char *ptrd = buf._data; for (ulongT i = N; i>0; --i) { *(ptrd++) = (unsigned char)*(ptr_r++); *(ptrd++) = (unsigned char)*(ptr_g++); *(ptrd++) = (unsigned char)*(ptr_b++); } cimg::fwrite(buf._data,3*N,nfile); to_write-=N; } } else { // Binary PPM 16 bits CImg<ushortT> buf((unsigned int)buf_size); for (longT to_write = (longT)width()*height(); to_write>0; ) { const ulongT N = std::min((ulongT)to_write,buf_size/3); unsigned short *ptrd = buf._data; for (ulongT i = N; i>0; --i) { *(ptrd++) = (unsigned short)*(ptr_r++); *(ptrd++) = (unsigned short)*(ptr_g++); *(ptrd++) = (unsigned short)*(ptr_b++); } if (!cimg::endianness()) cimg::invert_endianness(buf._data,buf_size); cimg::fwrite(buf._data,3*N,nfile); to_write-=N; } } } } if (!file) cimg::fclose(nfile); return *this; } //! Save image as a PNK file. /** \param filename Filename, as a C-string. **/ const CImg<T>& save_pnk(const char *const filename) const { return _save_pnk(0,filename); } //! Save image as a PNK file \overloading. const CImg<T>& save_pnk(std::FILE *const file) const { return _save_pnk(file,0); } const CImg<T>& _save_pnk(std::FILE *const file, const char *const filename) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_pnk(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(file,filename); return *this; } if (_spectrum>1) cimg::warn(_cimg_instance "save_pnk(): Instance is multispectral, only the first channel will be saved in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); const ulongT buf_size = std::min((ulongT)1024*1024,(ulongT)_width*_height*_depth); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); const T *ptr = data(0,0,0,0); if (!cimg::type<T>::is_float() && sizeof(T)==1 && _depth<2) // Can be saved as regular PNM file _save_pnm(file,filename,0); else if (!cimg::type<T>::is_float() && sizeof(T)==1) { // Save as extended P5 file: Binary byte-valued 3D std::fprintf(nfile,"P5\n%u %u %u\n255\n",_width,_height,_depth); CImg<ucharT> buf((unsigned int)buf_size); for (longT to_write = (longT)width()*height()*depth(); to_write>0; ) { const ulongT N = std::min((ulongT)to_write,buf_size); unsigned char *ptrd = buf._data; for (ulongT i = N; i>0; --i) *(ptrd++) = (unsigned char)*(ptr++); cimg::fwrite(buf._data,N,nfile); to_write-=N; } } else if (!cimg::type<T>::is_float()) { // Save as P8: Binary int32-valued 3D if (_depth>1) std::fprintf(nfile,"P8\n%u %u %u\n%d\n",_width,_height,_depth,(int)max()); else std::fprintf(nfile,"P8\n%u %u\n%d\n",_width,_height,(int)max()); CImg<intT> buf((unsigned int)buf_size); for (longT to_write = (longT)width()*height()*depth(); to_write>0; ) { const ulongT N = std::min((ulongT)to_write,buf_size); int *ptrd = buf._data; for (ulongT i = N; i>0; --i) *(ptrd++) = (int)*(ptr++); cimg::fwrite(buf._data,N,nfile); to_write-=N; } } else { // Save as P9: Binary float-valued 3D if (_depth>1) std::fprintf(nfile,"P9\n%u %u %u\n%g\n",_width,_height,_depth,(double)max()); else std::fprintf(nfile,"P9\n%u %u\n%g\n",_width,_height,(double)max()); CImg<floatT> buf((unsigned int)buf_size); for (longT to_write = (longT)width()*height()*depth(); to_write>0; ) { const ulongT N = std::min((ulongT)to_write,buf_size); float *ptrd = buf._data; for (ulongT i = N; i>0; --i) *(ptrd++) = (float)*(ptr++); cimg::fwrite(buf._data,N,nfile); to_write-=N; } } if (!file) cimg::fclose(nfile); return *this; } //! Save image as a PFM file. /** \param filename Filename, as a C-string. **/ const CImg<T>& save_pfm(const char *const filename) const { get_mirror('y')._save_pfm(0,filename); return *this; } //! Save image as a PFM file \overloading. const CImg<T>& save_pfm(std::FILE *const file) const { get_mirror('y')._save_pfm(file,0); return *this; } const CImg<T>& _save_pfm(std::FILE *const file, const char *const filename) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_pfm(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(file,filename); return *this; } if (_depth>1) cimg::warn(_cimg_instance "save_pfm(): Instance is volumetric, only the first slice will be saved in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); if (_spectrum>3) cimg::warn(_cimg_instance "save_pfm(): image instance is multispectral, only the three first channels will be saved " "in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); const T *ptr_r = data(0,0,0,0), *ptr_g = (_spectrum>=2)?data(0,0,0,1):0, *ptr_b = (_spectrum>=3)?data(0,0,0,2):0; const unsigned int buf_size = std::min(1024*1024U,_width*_height*(_spectrum==1?1:3)); std::fprintf(nfile,"P%c\n%u %u\n1.0\n", (_spectrum==1?'f':'F'),_width,_height); switch (_spectrum) { case 1 : { // Scalar image CImg<floatT> buf(buf_size); for (longT to_write = (longT)width()*height(); to_write>0; ) { const ulongT N = std::min((ulongT)to_write,(ulongT)buf_size); float *ptrd = buf._data; for (ulongT i = N; i>0; --i) *(ptrd++) = (float)*(ptr_r++); if (!cimg::endianness()) cimg::invert_endianness(buf._data,buf_size); cimg::fwrite(buf._data,N,nfile); to_write-=N; } } break; case 2 : { // RG image CImg<floatT> buf(buf_size); for (longT to_write = (longT)width()*height(); to_write>0; ) { const unsigned int N = std::min((unsigned int)to_write,buf_size/3); float *ptrd = buf._data; for (ulongT i = N; i>0; --i) { *(ptrd++) = (float)*(ptr_r++); *(ptrd++) = (float)*(ptr_g++); *(ptrd++) = 0; } if (!cimg::endianness()) cimg::invert_endianness(buf._data,buf_size); cimg::fwrite(buf._data,3*N,nfile); to_write-=N; } } break; default : { // RGB image CImg<floatT> buf(buf_size); for (longT to_write = (longT)width()*height(); to_write>0; ) { const unsigned int N = std::min((unsigned int)to_write,buf_size/3); float *ptrd = buf._data; for (ulongT i = N; i>0; --i) { *(ptrd++) = (float)*(ptr_r++); *(ptrd++) = (float)*(ptr_g++); *(ptrd++) = (float)*(ptr_b++); } if (!cimg::endianness()) cimg::invert_endianness(buf._data,buf_size); cimg::fwrite(buf._data,3*N,nfile); to_write-=N; } } } if (!file) cimg::fclose(nfile); return *this; } //! Save image as a RGB file. /** \param filename Filename, as a C-string. **/ const CImg<T>& save_rgb(const char *const filename) const { return _save_rgb(0,filename); } //! Save image as a RGB file \overloading. const CImg<T>& save_rgb(std::FILE *const file) const { return _save_rgb(file,0); } const CImg<T>& _save_rgb(std::FILE *const file, const char *const filename) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_rgb(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(file,filename); return *this; } if (_spectrum!=3) cimg::warn(_cimg_instance "save_rgb(): image instance has not exactly 3 channels, for file '%s'.", cimg_instance, filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); const ulongT wh = (ulongT)_width*_height; unsigned char *const buffer = new unsigned char[3*wh], *nbuffer = buffer; const T *ptr1 = data(0,0,0,0), *ptr2 = _spectrum>1?data(0,0,0,1):0, *ptr3 = _spectrum>2?data(0,0,0,2):0; switch (_spectrum) { case 1 : { // Scalar image for (ulongT k = 0; k<wh; ++k) { const unsigned char val = (unsigned char)*(ptr1++); *(nbuffer++) = val; *(nbuffer++) = val; *(nbuffer++) = val; } } break; case 2 : { // RG image for (ulongT k = 0; k<wh; ++k) { *(nbuffer++) = (unsigned char)(*(ptr1++)); *(nbuffer++) = (unsigned char)(*(ptr2++)); *(nbuffer++) = 0; } } break; default : { // RGB image for (ulongT k = 0; k<wh; ++k) { *(nbuffer++) = (unsigned char)(*(ptr1++)); *(nbuffer++) = (unsigned char)(*(ptr2++)); *(nbuffer++) = (unsigned char)(*(ptr3++)); } } } cimg::fwrite(buffer,3*wh,nfile); if (!file) cimg::fclose(nfile); delete[] buffer; return *this; } //! Save image as a RGBA file. /** \param filename Filename, as a C-string. **/ const CImg<T>& save_rgba(const char *const filename) const { return _save_rgba(0,filename); } //! Save image as a RGBA file \overloading. const CImg<T>& save_rgba(std::FILE *const file) const { return _save_rgba(file,0); } const CImg<T>& _save_rgba(std::FILE *const file, const char *const filename) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_rgba(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(file,filename); return *this; } if (_spectrum!=4) cimg::warn(_cimg_instance "save_rgba(): image instance has not exactly 4 channels, for file '%s'.", cimg_instance, filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); const ulongT wh = (ulongT)_width*_height; unsigned char *const buffer = new unsigned char[4*wh], *nbuffer = buffer; const T *ptr1 = data(0,0,0,0), *ptr2 = _spectrum>1?data(0,0,0,1):0, *ptr3 = _spectrum>2?data(0,0,0,2):0, *ptr4 = _spectrum>3?data(0,0,0,3):0; switch (_spectrum) { case 1 : { // Scalar images for (ulongT k = 0; k<wh; ++k) { const unsigned char val = (unsigned char)*(ptr1++); *(nbuffer++) = val; *(nbuffer++) = val; *(nbuffer++) = val; *(nbuffer++) = 255; } } break; case 2 : { // RG images for (ulongT k = 0; k<wh; ++k) { *(nbuffer++) = (unsigned char)(*(ptr1++)); *(nbuffer++) = (unsigned char)(*(ptr2++)); *(nbuffer++) = 0; *(nbuffer++) = 255; } } break; case 3 : { // RGB images for (ulongT k = 0; k<wh; ++k) { *(nbuffer++) = (unsigned char)(*(ptr1++)); *(nbuffer++) = (unsigned char)(*(ptr2++)); *(nbuffer++) = (unsigned char)(*(ptr3++)); *(nbuffer++) = 255; } } break; default : { // RGBA images for (ulongT k = 0; k<wh; ++k) { *(nbuffer++) = (unsigned char)(*(ptr1++)); *(nbuffer++) = (unsigned char)(*(ptr2++)); *(nbuffer++) = (unsigned char)(*(ptr3++)); *(nbuffer++) = (unsigned char)(*(ptr4++)); } } } cimg::fwrite(buffer,4*wh,nfile); if (!file) cimg::fclose(nfile); delete[] buffer; return *this; } //! Save image as a TIFF file. /** \param filename Filename, as a C-string. \param compression_type Type of data compression. Can be <tt>{ 0=None | 1=LZW | 2=JPEG }</tt>. \param voxel_size Voxel size, to be stored in the filename. \param description Description, to be stored in the filename. \param use_bigtiff Allow to save big tiff files (>4Gb). \note - libtiff support is enabled by defining the precompilation directive \c cimg_use_tif. - When libtiff is enabled, 2D and 3D (multipage) several channel per pixel are supported for <tt>char,uchar,short,ushort,float</tt> and \c double pixel types. - If \c cimg_use_tif is not defined at compile time the function uses CImg<T>&save_other(const char*). **/ const CImg<T>& save_tiff(const char *const filename, const unsigned int compression_type=0, const float *const voxel_size=0, const char *const description=0, const bool use_bigtiff=true) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_tiff(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(0,filename); return *this; } #ifdef cimg_use_tiff const bool _use_bigtiff = use_bigtiff && sizeof(ulongT)>=8 && size()*sizeof(T)>=1UL<<31; // No bigtiff for small images TIFF *tif = TIFFOpen(filename,_use_bigtiff?"w8":"w4"); if (tif) { cimg_forZ(*this,z) _save_tiff(tif,z,z,compression_type,voxel_size,description); TIFFClose(tif); } else throw CImgIOException(_cimg_instance "save_tiff(): Failed to open file '%s' for writing.", cimg_instance, filename); return *this; #else cimg::unused(compression_type,voxel_size,description,use_bigtiff); return save_other(filename); #endif } #ifdef cimg_use_tiff #define _cimg_save_tiff(types,typed,compression_type) if (!std::strcmp(types,pixel_type())) { \ const typed foo = (typed)0; return _save_tiff(tif,directory,z,foo,compression_type,voxel_size,description); } // [internal] Save a plane into a tiff file template<typename t> const CImg<T>& _save_tiff(TIFF *tif, const unsigned int directory, const unsigned int z, const t& pixel_t, const unsigned int compression_type, const float *const voxel_size, const char *const description) const { if (is_empty() || !tif || pixel_t) return *this; const char *const filename = TIFFFileName(tif); uint32 rowsperstrip = (uint32)-1; uint16 spp = _spectrum, bpp = sizeof(t)*8, photometric; if (spp==3 || spp==4) photometric = PHOTOMETRIC_RGB; else photometric = PHOTOMETRIC_MINISBLACK; TIFFSetDirectory(tif,directory); TIFFSetField(tif,TIFFTAG_IMAGEWIDTH,_width); TIFFSetField(tif,TIFFTAG_IMAGELENGTH,_height); if (voxel_size) { const float vx = voxel_size[0], vy = voxel_size[1], vz = voxel_size[2]; TIFFSetField(tif,TIFFTAG_RESOLUTIONUNIT,RESUNIT_NONE); TIFFSetField(tif,TIFFTAG_XRESOLUTION,1.f/vx); TIFFSetField(tif,TIFFTAG_YRESOLUTION,1.f/vy); CImg<charT> s_description(256); cimg_snprintf(s_description,s_description._width,"VX=%g VY=%g VZ=%g spacing=%g",vx,vy,vz,vz); TIFFSetField(tif,TIFFTAG_IMAGEDESCRIPTION,s_description.data()); } if (description) TIFFSetField(tif,TIFFTAG_IMAGEDESCRIPTION,description); TIFFSetField(tif,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT); TIFFSetField(tif,TIFFTAG_SAMPLESPERPIXEL,spp); if (cimg::type<t>::is_float()) TIFFSetField(tif,TIFFTAG_SAMPLEFORMAT,3); else if (cimg::type<t>::min()==0) TIFFSetField(tif,TIFFTAG_SAMPLEFORMAT,1); else TIFFSetField(tif,TIFFTAG_SAMPLEFORMAT,2); double valm, valM = max_min(valm); TIFFSetField(tif,TIFFTAG_SMINSAMPLEVALUE,valm); TIFFSetField(tif,TIFFTAG_SMAXSAMPLEVALUE,valM); TIFFSetField(tif,TIFFTAG_BITSPERSAMPLE,bpp); TIFFSetField(tif,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG); TIFFSetField(tif,TIFFTAG_PHOTOMETRIC,photometric); TIFFSetField(tif,TIFFTAG_COMPRESSION,compression_type==2?COMPRESSION_JPEG: compression_type==1?COMPRESSION_LZW:COMPRESSION_NONE); rowsperstrip = TIFFDefaultStripSize(tif,rowsperstrip); TIFFSetField(tif,TIFFTAG_ROWSPERSTRIP,rowsperstrip); TIFFSetField(tif,TIFFTAG_FILLORDER,FILLORDER_MSB2LSB); TIFFSetField(tif,TIFFTAG_SOFTWARE,"CImg"); t *const buf = (t*)_TIFFmalloc(TIFFStripSize(tif)); if (buf) { for (unsigned int row = 0; row<_height; row+=rowsperstrip) { uint32 nrow = (row + rowsperstrip>_height?_height - row:rowsperstrip); tstrip_t strip = TIFFComputeStrip(tif,row,0); tsize_t i = 0; for (unsigned int rr = 0; rr<nrow; ++rr) for (unsigned int cc = 0; cc<_width; ++cc) for (unsigned int vv = 0; vv<spp; ++vv) buf[i++] = (t)(*this)(cc,row + rr,z,vv); if (TIFFWriteEncodedStrip(tif,strip,buf,i*sizeof(t))<0) throw CImgIOException(_cimg_instance "save_tiff(): Invalid strip writing when saving file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } _TIFFfree(buf); } TIFFWriteDirectory(tif); return *this; } const CImg<T>& _save_tiff(TIFF *tif, const unsigned int directory, const unsigned int z, const unsigned int compression_type, const float *const voxel_size, const char *const description) const { _cimg_save_tiff("bool",unsigned char,compression_type); _cimg_save_tiff("unsigned char",unsigned char,compression_type); _cimg_save_tiff("char",char,compression_type); _cimg_save_tiff("unsigned short",unsigned short,compression_type); _cimg_save_tiff("short",short,compression_type); _cimg_save_tiff("unsigned int",unsigned int,compression_type); _cimg_save_tiff("int",int,compression_type); _cimg_save_tiff("unsigned int64",unsigned int,compression_type); _cimg_save_tiff("int64",int,compression_type); _cimg_save_tiff("float",float,compression_type); _cimg_save_tiff("double",float,compression_type); const char *const filename = TIFFFileName(tif); throw CImgInstanceException(_cimg_instance "save_tiff(): Unsupported pixel type '%s' for file '%s'.", cimg_instance, pixel_type(),filename?filename:"(FILE*)"); return *this; } #endif //! Save image as a MINC2 file. /** \param filename Filename, as a C-string. \param imitate_file If non-zero, reference filename, as a C-string, to borrow header from. **/ const CImg<T>& save_minc2(const char *const filename, const char *const imitate_file=0) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_minc2(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(0,filename); return *this; } #ifndef cimg_use_minc2 cimg::unused(imitate_file); return save_other(filename); #else minc::minc_1_writer wtr; if (imitate_file) wtr.open(filename, imitate_file); else { minc::minc_info di; if (width()) di.push_back(minc::dim_info(width(),width()*0.5,-1,minc::dim_info::DIM_X)); if (height()) di.push_back(minc::dim_info(height(),height()*0.5,-1,minc::dim_info::DIM_Y)); if (depth()) di.push_back(minc::dim_info(depth(),depth()*0.5,-1,minc::dim_info::DIM_Z)); if (spectrum()) di.push_back(minc::dim_info(spectrum(),spectrum()*0.5,-1,minc::dim_info::DIM_TIME)); wtr.open(filename,di,1,NC_FLOAT,0); } if (cimg::type<T>::string()==cimg::type<unsigned char>::string()) wtr.setup_write_byte(); else if (cimg::type<T>::string()==cimg::type<int>::string()) wtr.setup_write_int(); else if (cimg::type<T>::string()==cimg::type<double>::string()) wtr.setup_write_double(); else wtr.setup_write_float(); minc::save_standard_volume(wtr, this->_data); return *this; #endif } //! Save image as an ANALYZE7.5 or NIFTI file. /** \param filename Filename, as a C-string. \param voxel_size Pointer to 3 consecutive values that tell about the voxel sizes along the X,Y and Z dimensions. **/ const CImg<T>& save_analyze(const char *const filename, const float *const voxel_size=0) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_analyze(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(0,filename); return *this; } std::FILE *file; CImg<charT> hname(1024), iname(1024); const char *const ext = cimg::split_filename(filename); short datatype = -1; if (!*ext) { cimg_snprintf(hname,hname._width,"%s.hdr",filename); cimg_snprintf(iname,iname._width,"%s.img",filename); } if (!cimg::strncasecmp(ext,"hdr",3)) { std::strcpy(hname,filename); std::strncpy(iname,filename,iname._width - 1); cimg_sprintf(iname._data + std::strlen(iname) - 3,"img"); } if (!cimg::strncasecmp(ext,"img",3)) { std::strcpy(hname,filename); std::strncpy(iname,filename,iname._width - 1); cimg_sprintf(hname._data + std::strlen(iname) - 3,"hdr"); } if (!cimg::strncasecmp(ext,"nii",3)) { std::strncpy(hname,filename,hname._width - 1); *iname = 0; } CImg<charT> header(*iname?348:352,1,1,1,0); int *const iheader = (int*)header._data; *iheader = 348; std::strcpy(header._data + 4,"CImg"); std::strcpy(header._data + 14," "); ((short*)&(header[36]))[0] = 4096; ((char*)&(header[38]))[0] = 114; ((short*)&(header[40]))[0] = 4; ((short*)&(header[40]))[1] = (short)_width; ((short*)&(header[40]))[2] = (short)_height; ((short*)&(header[40]))[3] = (short)_depth; ((short*)&(header[40]))[4] = (short)_spectrum; if (!cimg::strcasecmp(pixel_type(),"bool")) datatype = 2; if (!cimg::strcasecmp(pixel_type(),"unsigned char")) datatype = 2; if (!cimg::strcasecmp(pixel_type(),"char")) datatype = 2; if (!cimg::strcasecmp(pixel_type(),"unsigned short")) datatype = 4; if (!cimg::strcasecmp(pixel_type(),"short")) datatype = 4; if (!cimg::strcasecmp(pixel_type(),"unsigned int")) datatype = 8; if (!cimg::strcasecmp(pixel_type(),"int")) datatype = 8; if (!cimg::strcasecmp(pixel_type(),"unsigned int64")) datatype = 8; if (!cimg::strcasecmp(pixel_type(),"int64")) datatype = 8; if (!cimg::strcasecmp(pixel_type(),"float")) datatype = 16; if (!cimg::strcasecmp(pixel_type(),"double")) datatype = 64; if (datatype<0) throw CImgIOException(_cimg_instance "save_analyze(): Unsupported pixel type '%s' for file '%s'.", cimg_instance, pixel_type(),filename); ((short*)&(header[70]))[0] = datatype; ((short*)&(header[72]))[0] = sizeof(T); ((float*)&(header[108]))[0] = (float)(*iname?0:header.width()); ((float*)&(header[112]))[0] = 1; ((float*)&(header[76]))[0] = 0; if (voxel_size) { ((float*)&(header[76]))[1] = voxel_size[0]; ((float*)&(header[76]))[2] = voxel_size[1]; ((float*)&(header[76]))[3] = voxel_size[2]; } else ((float*)&(header[76]))[1] = ((float*)&(header[76]))[2] = ((float*)&(header[76]))[3] = 1; file = cimg::fopen(hname,"wb"); cimg::fwrite(header._data,header.width(),file); if (*iname) { cimg::fclose(file); file = cimg::fopen(iname,"wb"); } cimg::fwrite(_data,size(),file); cimg::fclose(file); return *this; } //! Save image as a .cimg file. /** \param filename Filename, as a C-string. \param is_compressed Tells if the file contains compressed image data. **/ const CImg<T>& save_cimg(const char *const filename, const bool is_compressed=false) const { CImgList<T>(*this,true).save_cimg(filename,is_compressed); return *this; } //! Save image as a .cimg file \overloading. const CImg<T>& save_cimg(std::FILE *const file, const bool is_compressed=false) const { CImgList<T>(*this,true).save_cimg(file,is_compressed); return *this; } //! Save image as a sub-image into an existing .cimg file. /** \param filename Filename, as a C-string. \param n0 Index of the image inside the file. \param x0 X-coordinate of the sub-image location. \param y0 Y-coordinate of the sub-image location. \param z0 Z-coordinate of the sub-image location. \param c0 C-coordinate of the sub-image location. **/ const CImg<T>& save_cimg(const char *const filename, const unsigned int n0, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0) const { CImgList<T>(*this,true).save_cimg(filename,n0,x0,y0,z0,c0); return *this; } //! Save image as a sub-image into an existing .cimg file \overloading. const CImg<T>& save_cimg(std::FILE *const file, const unsigned int n0, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0) const { CImgList<T>(*this,true).save_cimg(file,n0,x0,y0,z0,c0); return *this; } //! Save blank image as a .cimg file. /** \param filename Filename, as a C-string. \param dx Width of the image. \param dy Height of the image. \param dz Depth of the image. \param dc Number of channels of the image. \note - All pixel values of the saved image are set to \c 0. - Use this method to save large images without having to instanciate and allocate them. **/ static void save_empty_cimg(const char *const filename, const unsigned int dx, const unsigned int dy=1, const unsigned int dz=1, const unsigned int dc=1) { return CImgList<T>::save_empty_cimg(filename,1,dx,dy,dz,dc); } //! Save blank image as a .cimg file \overloading. /** Same as save_empty_cimg(const char *,unsigned int,unsigned int,unsigned int,unsigned int) with a file stream argument instead of a filename string. **/ static void save_empty_cimg(std::FILE *const file, const unsigned int dx, const unsigned int dy=1, const unsigned int dz=1, const unsigned int dc=1) { return CImgList<T>::save_empty_cimg(file,1,dx,dy,dz,dc); } //! Save image as an INRIMAGE-4 file. /** \param filename Filename, as a C-string. \param voxel_size Pointer to 3 values specifying the voxel sizes along the X,Y and Z dimensions. **/ const CImg<T>& save_inr(const char *const filename, const float *const voxel_size=0) const { return _save_inr(0,filename,voxel_size); } //! Save image as an INRIMAGE-4 file \overloading. const CImg<T>& save_inr(std::FILE *const file, const float *const voxel_size=0) const { return _save_inr(file,0,voxel_size); } const CImg<T>& _save_inr(std::FILE *const file, const char *const filename, const float *const voxel_size) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_inr(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(file,filename); return *this; } int inrpixsize = -1; const char *inrtype = "unsigned fixed\nPIXSIZE=8 bits\nSCALE=2**0"; if (!cimg::strcasecmp(pixel_type(),"unsigned char")) { inrtype = "unsigned fixed\nPIXSIZE=8 bits\nSCALE=2**0"; inrpixsize = 1; } if (!cimg::strcasecmp(pixel_type(),"char")) { inrtype = "fixed\nPIXSIZE=8 bits\nSCALE=2**0"; inrpixsize = 1; } if (!cimg::strcasecmp(pixel_type(),"unsigned short")) { inrtype = "unsigned fixed\nPIXSIZE=16 bits\nSCALE=2**0";inrpixsize = 2; } if (!cimg::strcasecmp(pixel_type(),"short")) { inrtype = "fixed\nPIXSIZE=16 bits\nSCALE=2**0"; inrpixsize = 2; } if (!cimg::strcasecmp(pixel_type(),"unsigned int")) { inrtype = "unsigned fixed\nPIXSIZE=32 bits\nSCALE=2**0";inrpixsize = 4; } if (!cimg::strcasecmp(pixel_type(),"int")) { inrtype = "fixed\nPIXSIZE=32 bits\nSCALE=2**0"; inrpixsize = 4; } if (!cimg::strcasecmp(pixel_type(),"float")) { inrtype = "float\nPIXSIZE=32 bits"; inrpixsize = 4; } if (!cimg::strcasecmp(pixel_type(),"double")) { inrtype = "float\nPIXSIZE=64 bits"; inrpixsize = 8; } if (inrpixsize<=0) throw CImgIOException(_cimg_instance "save_inr(): Unsupported pixel type '%s' for file '%s'", cimg_instance, pixel_type(),filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); CImg<charT> header(257); int err = cimg_snprintf(header,header._width,"#INRIMAGE-4#{\nXDIM=%u\nYDIM=%u\nZDIM=%u\nVDIM=%u\n", _width,_height,_depth,_spectrum); if (voxel_size) err+=cimg_sprintf(header._data + err,"VX=%g\nVY=%g\nVZ=%g\n", voxel_size[0],voxel_size[1],voxel_size[2]); err+=cimg_sprintf(header._data + err,"TYPE=%s\nCPU=%s\n",inrtype,cimg::endianness()?"sun":"decm"); std::memset(header._data + err,'\n',252 - err); std::memcpy(header._data + 252,"##}\n",4); cimg::fwrite(header._data,256,nfile); cimg_forXYZ(*this,x,y,z) cimg_forC(*this,c) cimg::fwrite(&((*this)(x,y,z,c)),1,nfile); if (!file) cimg::fclose(nfile); return *this; } //! Save image as an OpenEXR file. /** \param filename Filename, as a C-string. \note The OpenEXR file format is <a href="http://en.wikipedia.org/wiki/OpenEXR">described here</a>. **/ const CImg<T>& save_exr(const char *const filename) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_exr(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(0,filename); return *this; } if (_depth>1) cimg::warn(_cimg_instance "save_exr(): Instance is volumetric, only the first slice will be saved in file '%s'.", cimg_instance, filename); #ifndef cimg_use_openexr return save_other(filename); #else Imf::Rgba *const ptrd0 = new Imf::Rgba[(size_t)_width*_height], *ptrd = ptrd0, rgba; switch (_spectrum) { case 1 : { // Grayscale image for (const T *ptr_r = data(), *const ptr_e = ptr_r + (ulongT)_width*_height; ptr_r<ptr_e;) { rgba.r = rgba.g = rgba.b = (half)(*(ptr_r++)); rgba.a = (half)1; *(ptrd++) = rgba; } } break; case 2 : { // RG image for (const T *ptr_r = data(), *ptr_g = data(0,0,0,1), *const ptr_e = ptr_r + (ulongT)_width*_height; ptr_r<ptr_e; ) { rgba.r = (half)(*(ptr_r++)); rgba.g = (half)(*(ptr_g++)); rgba.b = (half)0; rgba.a = (half)1; *(ptrd++) = rgba; } } break; case 3 : { // RGB image for (const T *ptr_r = data(), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2), *const ptr_e = ptr_r + (ulongT)_width*_height; ptr_r<ptr_e;) { rgba.r = (half)(*(ptr_r++)); rgba.g = (half)(*(ptr_g++)); rgba.b = (half)(*(ptr_b++)); rgba.a = (half)1; *(ptrd++) = rgba; } } break; default : { // RGBA image for (const T *ptr_r = data(), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2), *ptr_a = data(0,0,0,3), *const ptr_e = ptr_r + (ulongT)_width*_height; ptr_r<ptr_e;) { rgba.r = (half)(*(ptr_r++)); rgba.g = (half)(*(ptr_g++)); rgba.b = (half)(*(ptr_b++)); rgba.a = (half)(*(ptr_a++)); *(ptrd++) = rgba; } } break; } Imf::RgbaOutputFile outFile(filename,_width,_height, _spectrum==1?Imf::WRITE_Y:_spectrum==2?Imf::WRITE_YA:_spectrum==3? Imf::WRITE_RGB:Imf::WRITE_RGBA); outFile.setFrameBuffer(ptrd0,1,_width); outFile.writePixels(_height); delete[] ptrd0; return *this; #endif } //! Save image as a Pandore-5 file. /** \param filename Filename, as a C-string. \param colorspace Colorspace data field in output file (see <a href="http://www.greyc.ensicaen.fr/~regis/Pandore">Pandore file specifications</a> for more information). **/ const CImg<T>& save_pandore(const char *const filename, const unsigned int colorspace=0) const { return _save_pandore(0,filename,colorspace); } //! Save image as a Pandore-5 file \overloading. /** Same as save_pandore(const char *,unsigned int) const with a file stream argument instead of a filename string. **/ const CImg<T>& save_pandore(std::FILE *const file, const unsigned int colorspace=0) const { return _save_pandore(file,0,colorspace); } unsigned int _save_pandore_header_length(unsigned int id, unsigned int *dims, const unsigned int colorspace) const { unsigned int nbdims = 0; if (id==2 || id==3 || id==4) { dims[0] = 1; dims[1] = _width; nbdims = 2; } if (id==5 || id==6 || id==7) { dims[0] = 1; dims[1] = _height; dims[2] = _width; nbdims=3; } if (id==8 || id==9 || id==10) { dims[0] = _spectrum; dims[1] = _depth; dims[2] = _height; dims[3] = _width; nbdims = 4; } if (id==16 || id==17 || id==18) { dims[0] = 3; dims[1] = _height; dims[2] = _width; dims[3] = colorspace; nbdims = 4; } if (id==19 || id==20 || id==21) { dims[0] = 3; dims[1] = _depth; dims[2] = _height; dims[3] = _width; dims[4] = colorspace; nbdims = 5; } if (id==22 || id==23 || id==25) { dims[0] = _spectrum; dims[1] = _width; nbdims = 2; } if (id==26 || id==27 || id==29) { dims[0] = _spectrum; dims[1] = _height; dims[2] = _width; nbdims=3; } if (id==30 || id==31 || id==33) { dims[0] = _spectrum; dims[1] = _depth; dims[2] = _height; dims[3] = _width; nbdims = 4; } return nbdims; } const CImg<T>& _save_pandore(std::FILE *const file, const char *const filename, const unsigned int colorspace) const { #define __cimg_save_pandore_case(dtype) \ dtype *buffer = new dtype[size()]; \ const T *ptrs = _data; \ cimg_foroff(*this,off) *(buffer++) = (dtype)(*(ptrs++)); \ buffer-=size(); \ cimg::fwrite(buffer,size(),nfile); \ delete[] buffer #define _cimg_save_pandore_case(sy,sz,sv,stype,id) \ if (!saved && (sy?(sy==_height):true) && (sz?(sz==_depth):true) && \ (sv?(sv==_spectrum):true) && !std::strcmp(stype,pixel_type())) { \ unsigned int *iheader = (unsigned int*)(header + 12); \ nbdims = _save_pandore_header_length((*iheader=id),dims,colorspace); \ cimg::fwrite(header,36,nfile); \ if (sizeof(unsigned long)==4) { CImg<ulongT> ndims(5); \ for (int d = 0; d<5; ++d) ndims[d] = (unsigned long)dims[d]; cimg::fwrite(ndims._data,nbdims,nfile); } \ else if (sizeof(unsigned int)==4) { CImg<uintT> ndims(5); \ for (int d = 0; d<5; ++d) ndims[d] = (unsigned int)dims[d]; cimg::fwrite(ndims._data,nbdims,nfile); } \ else if (sizeof(unsigned short)==4) { CImg<ushortT> ndims(5); \ for (int d = 0; d<5; ++d) ndims[d] = (unsigned short)dims[d]; cimg::fwrite(ndims._data,nbdims,nfile); } \ else throw CImgIOException(_cimg_instance \ "save_pandore(): Unsupported datatype for file '%s'.",\ cimg_instance, \ filename?filename:"(FILE*)"); \ if (id==2 || id==5 || id==8 || id==16 || id==19 || id==22 || id==26 || id==30) { \ __cimg_save_pandore_case(unsigned char); \ } else if (id==3 || id==6 || id==9 || id==17 || id==20 || id==23 || id==27 || id==31) { \ if (sizeof(unsigned long)==4) { __cimg_save_pandore_case(unsigned long); } \ else if (sizeof(unsigned int)==4) { __cimg_save_pandore_case(unsigned int); } \ else if (sizeof(unsigned short)==4) { __cimg_save_pandore_case(unsigned short); } \ else throw CImgIOException(_cimg_instance \ "save_pandore(): Unsupported datatype for file '%s'.",\ cimg_instance, \ filename?filename:"(FILE*)"); \ } else if (id==4 || id==7 || id==10 || id==18 || id==21 || id==25 || id==29 || id==33) { \ if (sizeof(double)==4) { __cimg_save_pandore_case(double); } \ else if (sizeof(float)==4) { __cimg_save_pandore_case(float); } \ else throw CImgIOException(_cimg_instance \ "save_pandore(): Unsupported datatype for file '%s'.",\ cimg_instance, \ filename?filename:"(FILE*)"); \ } \ saved = true; \ } if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_pandore(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(file,filename); return *this; } std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); unsigned char header[36] = { 'P','A','N','D','O','R','E','0','4',0,0,0, 0,0,0,0,'C','I','m','g',0,0,0,0,0, 'N','o',' ','d','a','t','e',0,0,0,0 }; unsigned int nbdims, dims[5] = { 0 }; bool saved = false; _cimg_save_pandore_case(1,1,1,"unsigned char",2); _cimg_save_pandore_case(1,1,1,"char",3); _cimg_save_pandore_case(1,1,1,"unsigned short",3); _cimg_save_pandore_case(1,1,1,"short",3); _cimg_save_pandore_case(1,1,1,"unsigned int",3); _cimg_save_pandore_case(1,1,1,"int",3); _cimg_save_pandore_case(1,1,1,"unsigned int64",3); _cimg_save_pandore_case(1,1,1,"int64",3); _cimg_save_pandore_case(1,1,1,"float",4); _cimg_save_pandore_case(1,1,1,"double",4); _cimg_save_pandore_case(0,1,1,"unsigned char",5); _cimg_save_pandore_case(0,1,1,"char",6); _cimg_save_pandore_case(0,1,1,"unsigned short",6); _cimg_save_pandore_case(0,1,1,"short",6); _cimg_save_pandore_case(0,1,1,"unsigned int",6); _cimg_save_pandore_case(0,1,1,"int",6); _cimg_save_pandore_case(0,1,1,"unsigned int64",6); _cimg_save_pandore_case(0,1,1,"int64",6); _cimg_save_pandore_case(0,1,1,"float",7); _cimg_save_pandore_case(0,1,1,"double",7); _cimg_save_pandore_case(0,0,1,"unsigned char",8); _cimg_save_pandore_case(0,0,1,"char",9); _cimg_save_pandore_case(0,0,1,"unsigned short",9); _cimg_save_pandore_case(0,0,1,"short",9); _cimg_save_pandore_case(0,0,1,"unsigned int",9); _cimg_save_pandore_case(0,0,1,"int",9); _cimg_save_pandore_case(0,0,1,"unsigned int64",9); _cimg_save_pandore_case(0,0,1,"int64",9); _cimg_save_pandore_case(0,0,1,"float",10); _cimg_save_pandore_case(0,0,1,"double",10); _cimg_save_pandore_case(0,1,3,"unsigned char",16); _cimg_save_pandore_case(0,1,3,"char",17); _cimg_save_pandore_case(0,1,3,"unsigned short",17); _cimg_save_pandore_case(0,1,3,"short",17); _cimg_save_pandore_case(0,1,3,"unsigned int",17); _cimg_save_pandore_case(0,1,3,"int",17); _cimg_save_pandore_case(0,1,3,"unsigned int64",17); _cimg_save_pandore_case(0,1,3,"int64",17); _cimg_save_pandore_case(0,1,3,"float",18); _cimg_save_pandore_case(0,1,3,"double",18); _cimg_save_pandore_case(0,0,3,"unsigned char",19); _cimg_save_pandore_case(0,0,3,"char",20); _cimg_save_pandore_case(0,0,3,"unsigned short",20); _cimg_save_pandore_case(0,0,3,"short",20); _cimg_save_pandore_case(0,0,3,"unsigned int",20); _cimg_save_pandore_case(0,0,3,"int",20); _cimg_save_pandore_case(0,0,3,"unsigned int64",20); _cimg_save_pandore_case(0,0,3,"int64",20); _cimg_save_pandore_case(0,0,3,"float",21); _cimg_save_pandore_case(0,0,3,"double",21); _cimg_save_pandore_case(1,1,0,"unsigned char",22); _cimg_save_pandore_case(1,1,0,"char",23); _cimg_save_pandore_case(1,1,0,"unsigned short",23); _cimg_save_pandore_case(1,1,0,"short",23); _cimg_save_pandore_case(1,1,0,"unsigned int",23); _cimg_save_pandore_case(1,1,0,"int",23); _cimg_save_pandore_case(1,1,0,"unsigned int64",23); _cimg_save_pandore_case(1,1,0,"int64",23); _cimg_save_pandore_case(1,1,0,"float",25); _cimg_save_pandore_case(1,1,0,"double",25); _cimg_save_pandore_case(0,1,0,"unsigned char",26); _cimg_save_pandore_case(0,1,0,"char",27); _cimg_save_pandore_case(0,1,0,"unsigned short",27); _cimg_save_pandore_case(0,1,0,"short",27); _cimg_save_pandore_case(0,1,0,"unsigned int",27); _cimg_save_pandore_case(0,1,0,"int",27); _cimg_save_pandore_case(0,1,0,"unsigned int64",27); _cimg_save_pandore_case(0,1,0,"int64",27); _cimg_save_pandore_case(0,1,0,"float",29); _cimg_save_pandore_case(0,1,0,"double",29); _cimg_save_pandore_case(0,0,0,"unsigned char",30); _cimg_save_pandore_case(0,0,0,"char",31); _cimg_save_pandore_case(0,0,0,"unsigned short",31); _cimg_save_pandore_case(0,0,0,"short",31); _cimg_save_pandore_case(0,0,0,"unsigned int",31); _cimg_save_pandore_case(0,0,0,"int",31); _cimg_save_pandore_case(0,0,0,"unsigned int64",31); _cimg_save_pandore_case(0,0,0,"int64",31); _cimg_save_pandore_case(0,0,0,"float",33); _cimg_save_pandore_case(0,0,0,"double",33); if (!file) cimg::fclose(nfile); return *this; } //! Save image as a raw data file. /** \param filename Filename, as a C-string. \param is_multiplexed Tells if the image channels are stored in a multiplexed way (\c true) or not (\c false). \note The .raw format does not store the image dimensions in the output file, so you have to keep track of them somewhere to be able to read the file correctly afterwards. **/ const CImg<T>& save_raw(const char *const filename, const bool is_multiplexed=false) const { return _save_raw(0,filename,is_multiplexed); } //! Save image as a raw data file \overloading. /** Same as save_raw(const char *,bool) const with a file stream argument instead of a filename string. **/ const CImg<T>& save_raw(std::FILE *const file, const bool is_multiplexed=false) const { return _save_raw(file,0,is_multiplexed); } const CImg<T>& _save_raw(std::FILE *const file, const char *const filename, const bool is_multiplexed) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_raw(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(file,filename); return *this; } std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); if (!is_multiplexed) cimg::fwrite(_data,size(),nfile); else { CImg<T> buf(_spectrum); cimg_forXYZ(*this,x,y,z) { cimg_forC(*this,c) buf[c] = (*this)(x,y,z,c); cimg::fwrite(buf._data,_spectrum,nfile); } } if (!file) cimg::fclose(nfile); return *this; } //! Save image as a .yuv video file. /** \param filename Filename, as a C-string. \param chroma_subsampling Type of chroma subsampling. Can be <tt>{ 420 | 422 | 444 }</tt>. \param is_rgb Tells if pixel values of the instance image are RGB-coded (\c true) or YUV-coded (\c false). \note Each slice of the instance image is considered to be a single frame of the output video file. **/ const CImg<T>& save_yuv(const char *const filename, const unsigned int chroma_subsampling=444, const bool is_rgb=true) const { CImgList<T>(*this,true).save_yuv(filename,chroma_subsampling,is_rgb); return *this; } //! Save image as a .yuv video file \overloading. /** Same as save_yuv(const char*,const unsigned int,const bool) const with a file stream argument instead of a filename string. **/ const CImg<T>& save_yuv(std::FILE *const file, const unsigned int chroma_subsampling=444, const bool is_rgb=true) const { CImgList<T>(*this,true).save_yuv(file,chroma_subsampling,is_rgb); return *this; } //! Save 3D object as an Object File Format (.off) file. /** \param filename Filename, as a C-string. \param primitives List of 3D object primitives. \param colors List of 3D object colors. \note - Instance image contains the vertices data of the 3D object. - Textured, transparent or sphere-shaped primitives cannot be managed by the .off file format. Such primitives will be lost or simplified during file saving. - The .off file format is <a href="http://people.sc.fsu.edu/~jburkardt/html/off_format.html">described here</a>. **/ template<typename tf, typename tc> const CImg<T>& save_off(const CImgList<tf>& primitives, const CImgList<tc>& colors, const char *const filename) const { return _save_off(primitives,colors,0,filename); } //! Save 3D object as an Object File Format (.off) file \overloading. /** Same as save_off(const CImgList<tf>&,const CImgList<tc>&,const char*) const with a file stream argument instead of a filename string. **/ template<typename tf, typename tc> const CImg<T>& save_off(const CImgList<tf>& primitives, const CImgList<tc>& colors, std::FILE *const file) const { return _save_off(primitives,colors,file,0); } template<typename tf, typename tc> const CImg<T>& _save_off(const CImgList<tf>& primitives, const CImgList<tc>& colors, std::FILE *const file, const char *const filename) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_off(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_off(): Empty instance, for file '%s'.", cimg_instance, filename?filename:"(FILE*)"); CImgList<T> opacities; CImg<charT> error_message(1024); if (!is_object3d(primitives,colors,opacities,true,error_message)) throw CImgInstanceException(_cimg_instance "save_off(): Invalid specified 3D object, for file '%s' (%s).", cimg_instance, filename?filename:"(FILE*)",error_message.data()); const CImg<tc> default_color(1,3,1,1,(tc)std::min((int)cimg::type<tc>::max(),200)); std::FILE *const nfile = file?file:cimg::fopen(filename,"w"); unsigned int supported_primitives = 0; cimglist_for(primitives,l) if (primitives[l].size()!=5) ++supported_primitives; std::fprintf(nfile,"OFF\n%u %u %u\n",_width,supported_primitives,3*primitives._width); cimg_forX(*this,i) std::fprintf(nfile,"%f %f %f\n", (float)((*this)(i,0)),(float)((*this)(i,1)),(float)((*this)(i,2))); cimglist_for(primitives,l) { const CImg<tc>& color = l<colors.width()?colors[l]:default_color; const unsigned int psiz = primitives[l].size(), csiz = color.size(); const float r = color[0]/255.f, g = (csiz>1?color[1]:r)/255.f, b = (csiz>2?color[2]:g)/255.f; switch (psiz) { case 1 : std::fprintf(nfile,"1 %u %f %f %f\n", (unsigned int)primitives(l,0),r,g,b); break; case 2 : std::fprintf(nfile,"2 %u %u %f %f %f\n", (unsigned int)primitives(l,0),(unsigned int)primitives(l,1),r,g,b); break; case 3 : std::fprintf(nfile,"3 %u %u %u %f %f %f\n", (unsigned int)primitives(l,0),(unsigned int)primitives(l,2), (unsigned int)primitives(l,1),r,g,b); break; case 4 : std::fprintf(nfile,"4 %u %u %u %u %f %f %f\n", (unsigned int)primitives(l,0),(unsigned int)primitives(l,3), (unsigned int)primitives(l,2),(unsigned int)primitives(l,1),r,g,b); break; case 5 : std::fprintf(nfile,"2 %u %u %f %f %f\n", (unsigned int)primitives(l,0),(unsigned int)primitives(l,1),r,g,b); break; case 6 : { const unsigned int xt = (unsigned int)primitives(l,2), yt = (unsigned int)primitives(l,3); const float rt = color.atXY(xt,yt,0)/255.f, gt = (csiz>1?color.atXY(xt,yt,1):r)/255.f, bt = (csiz>2?color.atXY(xt,yt,2):g)/255.f; std::fprintf(nfile,"2 %u %u %f %f %f\n", (unsigned int)primitives(l,0),(unsigned int)primitives(l,1),rt,gt,bt); } break; case 9 : { const unsigned int xt = (unsigned int)primitives(l,3), yt = (unsigned int)primitives(l,4); const float rt = color.atXY(xt,yt,0)/255.f, gt = (csiz>1?color.atXY(xt,yt,1):r)/255.f, bt = (csiz>2?color.atXY(xt,yt,2):g)/255.f; std::fprintf(nfile,"3 %u %u %u %f %f %f\n", (unsigned int)primitives(l,0),(unsigned int)primitives(l,2), (unsigned int)primitives(l,1),rt,gt,bt); } break; case 12 : { const unsigned int xt = (unsigned int)primitives(l,4), yt = (unsigned int)primitives(l,5); const float rt = color.atXY(xt,yt,0)/255.f, gt = (csiz>1?color.atXY(xt,yt,1):r)/255.f, bt = (csiz>2?color.atXY(xt,yt,2):g)/255.f; std::fprintf(nfile,"4 %u %u %u %u %f %f %f\n", (unsigned int)primitives(l,0),(unsigned int)primitives(l,3), (unsigned int)primitives(l,2),(unsigned int)primitives(l,1),rt,gt,bt); } break; } } if (!file) cimg::fclose(nfile); return *this; } //! Save volumetric image as a video, using the OpenCV library. /** \param filename Filename to write data to. \param fps Number of frames per second. \param codec Type of compression (See http://www.fourcc.org/codecs.php to see available codecs). \param keep_open Tells if the video writer associated to the specified filename must be kept open or not (to allow frames to be added in the same file afterwards). **/ const CImg<T>& save_video(const char *const filename, const unsigned int fps=25, const char *codec=0, const bool keep_open=false) const { if (is_empty()) { CImgList<T>().save_video(filename,fps,codec,keep_open); return *this; } CImgList<T> list; get_split('z').move_to(list); list.save_video(filename,fps,codec,keep_open); return *this; } //! Save volumetric image as a video, using ffmpeg external binary. /** \param filename Filename, as a C-string. \param fps Video framerate. \param codec Video codec, as a C-string. \param bitrate Video bitrate. \note - Each slice of the instance image is considered to be a single frame of the output video file. - This method uses \c ffmpeg, an external executable binary provided by <a href="http://www.ffmpeg.org">FFmpeg</a>. It must be installed for the method to succeed. **/ const CImg<T>& save_ffmpeg_external(const char *const filename, const unsigned int fps=25, const char *const codec=0, const unsigned int bitrate=2048) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_ffmpeg_external(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(0,filename); return *this; } CImgList<T> list; get_split('z').move_to(list); list.save_ffmpeg_external(filename,fps,codec,bitrate); return *this; } //! Save image using gzip external binary. /** \param filename Filename, as a C-string. \note This method uses \c gzip, an external executable binary provided by <a href="//http://www.gzip.org">gzip</a>. It must be installed for the method to succeed. **/ const CImg<T>& save_gzip_external(const char *const filename) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_gzip_external(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(0,filename); return *this; } CImg<charT> command(1024), filename_tmp(256), body(256); const char *ext = cimg::split_filename(filename,body), *ext2 = cimg::split_filename(body,0); std::FILE *file; do { if (!cimg::strcasecmp(ext,"gz")) { if (*ext2) cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),ext2); else cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.cimg", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); } else { if (*ext) cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),ext); else cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.cimg", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); } if ((file=cimg::std_fopen(filename_tmp,"rb"))!=0) cimg::fclose(file); } while (file); save(filename_tmp); cimg_snprintf(command,command._width,"%s -c \"%s\" > \"%s\"", cimg::gzip_path(), CImg<charT>::string(filename_tmp)._system_strescape().data(), CImg<charT>::string(filename)._system_strescape().data()); cimg::system(command); file = cimg::std_fopen(filename,"rb"); if (!file) throw CImgIOException(_cimg_instance "save_gzip_external(): Failed to save file '%s' with external command 'gzip'.", cimg_instance, filename); else cimg::fclose(file); std::remove(filename_tmp); return *this; } //! Save image using GraphicsMagick's external binary. /** \param filename Filename, as a C-string. \param quality Image quality (expressed in percent), when the file format supports it. \note This method uses \c gm, an external executable binary provided by <a href="http://www.graphicsmagick.org">GraphicsMagick</a>. It must be installed for the method to succeed. **/ const CImg<T>& save_graphicsmagick_external(const char *const filename, const unsigned int quality=100) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_graphicsmagick_external(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(0,filename); return *this; } if (_depth>1) cimg::warn(_cimg_instance "save_other(): File '%s', saving a volumetric image with an external call to " "GraphicsMagick only writes the first image slice.", cimg_instance,filename); #ifdef cimg_use_png #define _cimg_sge_ext1 "png" #define _cimg_sge_ext2 "png" #else #define _cimg_sge_ext1 "pgm" #define _cimg_sge_ext2 "ppm" #endif CImg<charT> command(1024), filename_tmp(256); std::FILE *file; do { cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(), _spectrum==1?_cimg_sge_ext1:_cimg_sge_ext2); if ((file=cimg::std_fopen(filename_tmp,"rb"))!=0) cimg::fclose(file); } while (file); #ifdef cimg_use_png save_png(filename_tmp); #else save_pnm(filename_tmp); #endif cimg_snprintf(command,command._width,"%s convert -quality %u \"%s\" \"%s\"", cimg::graphicsmagick_path(),quality, CImg<charT>::string(filename_tmp)._system_strescape().data(), CImg<charT>::string(filename)._system_strescape().data()); cimg::system(command); file = cimg::std_fopen(filename,"rb"); if (!file) throw CImgIOException(_cimg_instance "save_graphicsmagick_external(): Failed to save file '%s' with external command 'gm'.", cimg_instance, filename); if (file) cimg::fclose(file); std::remove(filename_tmp); return *this; } //! Save image using ImageMagick's external binary. /** \param filename Filename, as a C-string. \param quality Image quality (expressed in percent), when the file format supports it. \note This method uses \c convert, an external executable binary provided by <a href="http://www.imagemagick.org">ImageMagick</a>. It must be installed for the method to succeed. **/ const CImg<T>& save_imagemagick_external(const char *const filename, const unsigned int quality=100) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_imagemagick_external(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(0,filename); return *this; } if (_depth>1) cimg::warn(_cimg_instance "save_other(): File '%s', saving a volumetric image with an external call to " "ImageMagick only writes the first image slice.", cimg_instance,filename); #ifdef cimg_use_png #define _cimg_sie_ext1 "png" #define _cimg_sie_ext2 "png" #else #define _cimg_sie_ext1 "pgm" #define _cimg_sie_ext2 "ppm" #endif CImg<charT> command(1024), filename_tmp(256); std::FILE *file; do { cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.%s",cimg::temporary_path(), cimg_file_separator,cimg::filenamerand(),_spectrum==1?_cimg_sie_ext1:_cimg_sie_ext2); if ((file=cimg::std_fopen(filename_tmp,"rb"))!=0) cimg::fclose(file); } while (file); #ifdef cimg_use_png save_png(filename_tmp); #else save_pnm(filename_tmp); #endif cimg_snprintf(command,command._width,"%s -quality %u \"%s\" \"%s\"", cimg::imagemagick_path(),quality, CImg<charT>::string(filename_tmp)._system_strescape().data(), CImg<charT>::string(filename)._system_strescape().data()); cimg::system(command); file = cimg::std_fopen(filename,"rb"); if (!file) throw CImgIOException(_cimg_instance "save_imagemagick_external(): Failed to save file '%s' with " "external command 'magick/convert'.", cimg_instance, filename); if (file) cimg::fclose(file); std::remove(filename_tmp); return *this; } //! Save image as a Dicom file. /** \param filename Filename, as a C-string. \note This method uses \c medcon, an external executable binary provided by <a href="http://xmedcon.sourceforge.net">(X)Medcon</a>. It must be installed for the method to succeed. **/ const CImg<T>& save_medcon_external(const char *const filename) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_medcon_external(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(0,filename); return *this; } CImg<charT> command(1024), filename_tmp(256), body(256); std::FILE *file; do { cimg_snprintf(filename_tmp,filename_tmp._width,"%s.hdr",cimg::filenamerand()); if ((file=cimg::std_fopen(filename_tmp,"rb"))!=0) cimg::fclose(file); } while (file); save_analyze(filename_tmp); cimg_snprintf(command,command._width,"%s -w -c dicom -o \"%s\" -f \"%s\"", cimg::medcon_path(), CImg<charT>::string(filename)._system_strescape().data(), CImg<charT>::string(filename_tmp)._system_strescape().data()); cimg::system(command); std::remove(filename_tmp); cimg::split_filename(filename_tmp,body); cimg_snprintf(filename_tmp,filename_tmp._width,"%s.img",body._data); std::remove(filename_tmp); file = cimg::std_fopen(filename,"rb"); if (!file) { cimg_snprintf(command,command._width,"m000-%s",filename); file = cimg::std_fopen(command,"rb"); if (!file) { cimg::fclose(cimg::fopen(filename,"r")); throw CImgIOException(_cimg_instance "save_medcon_external(): Failed to save file '%s' with external command 'medcon'.", cimg_instance, filename); } } cimg::fclose(file); std::rename(command,filename); return *this; } // Save image for non natively supported formats. /** \param filename Filename, as a C-string. \param quality Image quality (expressed in percent), when the file format supports it. \note - The filename extension tells about the desired file format. - This method tries to save the instance image as a file, using external tools from <a href="http://www.imagemagick.org">ImageMagick</a> or <a href="http://www.graphicsmagick.org">GraphicsMagick</a>. At least one of these tool must be installed for the method to succeed. - It is recommended to use the generic method save(const char*, int) const instead, as it can handle some file formats natively. **/ const CImg<T>& save_other(const char *const filename, const unsigned int quality=100) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_other(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(0,filename); return *this; } if (_depth>1) cimg::warn(_cimg_instance "save_other(): File '%s', saving a volumetric image with an external call to " "ImageMagick or GraphicsMagick only writes the first image slice.", cimg_instance,filename); const unsigned int omode = cimg::exception_mode(); bool is_saved = true; cimg::exception_mode(0); try { save_magick(filename); } catch (CImgException&) { try { save_imagemagick_external(filename,quality); } catch (CImgException&) { try { save_graphicsmagick_external(filename,quality); } catch (CImgException&) { is_saved = false; } } } cimg::exception_mode(omode); if (!is_saved) throw CImgIOException(_cimg_instance "save_other(): Failed to save file '%s'. Format is not natively supported, " "and no external commands succeeded.", cimg_instance, filename); return *this; } //! Serialize a CImg<T> instance into a raw CImg<unsigned char> buffer. /** \param is_compressed tells if zlib compression must be used for serialization (this requires 'cimg_use_zlib' been enabled). **/ CImg<ucharT> get_serialize(const bool is_compressed=false) const { return CImgList<T>(*this,true).get_serialize(is_compressed); } // [internal] Return a 40x38 color logo of a 'danger' item. static CImg<T> _logo40x38() { CImg<T> res(40,38,1,3); const unsigned char *ptrs = cimg::logo40x38; T *ptr1 = res.data(0,0,0,0), *ptr2 = res.data(0,0,0,1), *ptr3 = res.data(0,0,0,2); for (ulongT off = 0; off<(ulongT)res._width*res._height;) { const unsigned char n = *(ptrs++), r = *(ptrs++), g = *(ptrs++), b = *(ptrs++); for (unsigned int l = 0; l<n; ++off, ++l) { *(ptr1++) = (T)r; *(ptr2++) = (T)g; *(ptr3++) = (T)b; } } return res; } //@} }; // struct CImg { ... /* #----------------------------------------- # # # # Definition of the CImgList<T> structure # # # #------------------------------------------ */ //! Represent a list of images CImg<T>. template<typename T> struct CImgList { unsigned int _width, _allocated_width; CImg<T> *_data; //! Simple iterator type, to loop through each image of a list. /** \note - The \c CImgList<T>::iterator type is defined as a <tt>CImg<T>*</tt>. - You may use it like this: \code CImgList<> list; // Assuming this image list is not empty for (CImgList<>::iterator it = list.begin(); it<list.end(); ++it) (*it).mirror('x'); \endcode - Using the loop macro \c cimglist_for is another (more concise) alternative: \code cimglist_for(list,l) list[l].mirror('x'); \endcode **/ typedef CImg<T>* iterator; //! Simple const iterator type, to loop through each image of a \c const list instance. /** \note - The \c CImgList<T>::const_iterator type is defined to be a <tt>const CImg<T>*</tt>. - Similar to CImgList<T>::iterator, but for constant list instances. **/ typedef const CImg<T>* const_iterator; //! Pixel value type. /** Refer to the pixels value type of the images in the list. \note - The \c CImgList<T>::value_type type of a \c CImgList<T> is defined to be a \c T. It is then similar to CImg<T>::value_type. - \c CImgList<T>::value_type is actually not used in %CImg methods. It has been mainly defined for compatibility with STL naming conventions. **/ typedef T value_type; // Define common types related to template type T. typedef typename cimg::superset<T,bool>::type Tbool; typedef typename cimg::superset<T,unsigned char>::type Tuchar; typedef typename cimg::superset<T,char>::type Tchar; typedef typename cimg::superset<T,unsigned short>::type Tushort; typedef typename cimg::superset<T,short>::type Tshort; typedef typename cimg::superset<T,unsigned int>::type Tuint; typedef typename cimg::superset<T,int>::type Tint; typedef typename cimg::superset<T,cimg_ulong>::type Tulong; typedef typename cimg::superset<T,cimg_long>::type Tlong; typedef typename cimg::superset<T,float>::type Tfloat; typedef typename cimg::superset<T,double>::type Tdouble; typedef typename cimg::last<T,bool>::type boolT; typedef typename cimg::last<T,unsigned char>::type ucharT; typedef typename cimg::last<T,char>::type charT; typedef typename cimg::last<T,unsigned short>::type ushortT; typedef typename cimg::last<T,short>::type shortT; typedef typename cimg::last<T,unsigned int>::type uintT; typedef typename cimg::last<T,int>::type intT; typedef typename cimg::last<T,cimg_ulong>::type ulongT; typedef typename cimg::last<T,cimg_long>::type longT; typedef typename cimg::last<T,cimg_uint64>::type uint64T; typedef typename cimg::last<T,cimg_int64>::type int64T; typedef typename cimg::last<T,float>::type floatT; typedef typename cimg::last<T,double>::type doubleT; //@} //--------------------------- // //! \name Plugins //@{ //--------------------------- #ifdef cimglist_plugin #include cimglist_plugin #endif #ifdef cimglist_plugin1 #include cimglist_plugin1 #endif #ifdef cimglist_plugin2 #include cimglist_plugin2 #endif #ifdef cimglist_plugin3 #include cimglist_plugin3 #endif #ifdef cimglist_plugin4 #include cimglist_plugin4 #endif #ifdef cimglist_plugin5 #include cimglist_plugin5 #endif #ifdef cimglist_plugin6 #include cimglist_plugin6 #endif #ifdef cimglist_plugin7 #include cimglist_plugin7 #endif #ifdef cimglist_plugin8 #include cimglist_plugin8 #endif //@} //-------------------------------------------------------- // //! \name Constructors / Destructor / Instance Management //@{ //-------------------------------------------------------- //! Destructor. /** Destroy current list instance. \note - Any allocated buffer is deallocated. - Destroying an empty list does nothing actually. **/ ~CImgList() { delete[] _data; } //! Default constructor. /** Construct a new empty list instance. \note - An empty list has no pixel data and its dimension width() is set to \c 0, as well as its image buffer pointer data(). - An empty list may be reassigned afterwards, with the family of the assign() methods. In all cases, the type of pixels stays \c T. **/ CImgList(): _width(0),_allocated_width(0),_data(0) {} //! Construct list containing empty images. /** \param n Number of empty images. \note Useful when you know by advance the number of images you want to manage, as it will allocate the right amount of memory for the list, without needs for reallocation (that may occur when starting from an empty list and inserting several images in it). **/ explicit CImgList(const unsigned int n):_width(n) { if (n) _data = new CImg<T>[_allocated_width = std::max(16U,(unsigned int)cimg::nearest_pow2(n))]; else { _allocated_width = 0; _data = 0; } } //! Construct list containing images of specified size. /** \param n Number of images. \param width Width of images. \param height Height of images. \param depth Depth of images. \param spectrum Number of channels of images. \note Pixel values are not initialized and may probably contain garbage. **/ CImgList(const unsigned int n, const unsigned int width, const unsigned int height=1, const unsigned int depth=1, const unsigned int spectrum=1): _width(0),_allocated_width(0),_data(0) { assign(n); cimglist_apply(*this,assign)(width,height,depth,spectrum); } //! Construct list containing images of specified size, and initialize pixel values. /** \param n Number of images. \param width Width of images. \param height Height of images. \param depth Depth of images. \param spectrum Number of channels of images. \param val Initialization value for images pixels. **/ CImgList(const unsigned int n, const unsigned int width, const unsigned int height, const unsigned int depth, const unsigned int spectrum, const T& val): _width(0),_allocated_width(0),_data(0) { assign(n); cimglist_apply(*this,assign)(width,height,depth,spectrum,val); } //! Construct list containing images of specified size, and initialize pixel values from a sequence of integers. /** \param n Number of images. \param width Width of images. \param height Height of images. \param depth Depth of images. \param spectrum Number of channels of images. \param val0 First value of the initializing integers sequence. \param val1 Second value of the initializing integers sequence. \warning You must specify at least <tt>width*height*depth*spectrum</tt> values in your argument list, or you will probably segfault. **/ CImgList(const unsigned int n, const unsigned int width, const unsigned int height, const unsigned int depth, const unsigned int spectrum, const int val0, const int val1, ...): _width(0),_allocated_width(0),_data(0) { #define _CImgList_stdarg(t) { \ assign(n,width,height,depth,spectrum); \ const ulongT siz = (ulongT)width*height*depth*spectrum, nsiz = siz*n; \ T *ptrd = _data->_data; \ va_list ap; \ va_start(ap,val1); \ for (ulongT l = 0, s = 0, i = 0; i<nsiz; ++i) { \ *(ptrd++) = (T)(i==0?val0:(i==1?val1:va_arg(ap,t))); \ if ((++s)==siz) { ptrd = _data[++l]._data; s = 0; } \ } \ va_end(ap); \ } _CImgList_stdarg(int); } //! Construct list containing images of specified size, and initialize pixel values from a sequence of doubles. /** \param n Number of images. \param width Width of images. \param height Height of images. \param depth Depth of images. \param spectrum Number of channels of images. \param val0 First value of the initializing doubles sequence. \param val1 Second value of the initializing doubles sequence. \warning You must specify at least <tt>width*height*depth*spectrum</tt> values in your argument list, or you will probably segfault. **/ CImgList(const unsigned int n, const unsigned int width, const unsigned int height, const unsigned int depth, const unsigned int spectrum, const double val0, const double val1, ...): _width(0),_allocated_width(0),_data(0) { _CImgList_stdarg(double); } //! Construct list containing copies of an input image. /** \param n Number of images. \param img Input image to copy in the constructed list. \param is_shared Tells if the elements of the list are shared or non-shared copies of \c img. **/ template<typename t> CImgList(const unsigned int n, const CImg<t>& img, const bool is_shared=false): _width(0),_allocated_width(0),_data(0) { assign(n); cimglist_apply(*this,assign)(img,is_shared); } //! Construct list from one image. /** \param img Input image to copy in the constructed list. \param is_shared Tells if the element of the list is a shared or non-shared copy of \c img. **/ template<typename t> explicit CImgList(const CImg<t>& img, const bool is_shared=false): _width(0),_allocated_width(0),_data(0) { assign(1); _data[0].assign(img,is_shared); } //! Construct list from two images. /** \param img1 First input image to copy in the constructed list. \param img2 Second input image to copy in the constructed list. \param is_shared Tells if the elements of the list are shared or non-shared copies of input images. **/ template<typename t1, typename t2> CImgList(const CImg<t1>& img1, const CImg<t2>& img2, const bool is_shared=false): _width(0),_allocated_width(0),_data(0) { assign(2); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); } //! Construct list from three images. /** \param img1 First input image to copy in the constructed list. \param img2 Second input image to copy in the constructed list. \param img3 Third input image to copy in the constructed list. \param is_shared Tells if the elements of the list are shared or non-shared copies of input images. **/ template<typename t1, typename t2, typename t3> CImgList(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const bool is_shared=false): _width(0),_allocated_width(0),_data(0) { assign(3); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); } //! Construct list from four images. /** \param img1 First input image to copy in the constructed list. \param img2 Second input image to copy in the constructed list. \param img3 Third input image to copy in the constructed list. \param img4 Fourth input image to copy in the constructed list. \param is_shared Tells if the elements of the list are shared or non-shared copies of input images. **/ template<typename t1, typename t2, typename t3, typename t4> CImgList(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const bool is_shared=false): _width(0),_allocated_width(0),_data(0) { assign(4); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); } //! Construct list from five images. /** \param img1 First input image to copy in the constructed list. \param img2 Second input image to copy in the constructed list. \param img3 Third input image to copy in the constructed list. \param img4 Fourth input image to copy in the constructed list. \param img5 Fifth input image to copy in the constructed list. \param is_shared Tells if the elements of the list are shared or non-shared copies of input images. **/ template<typename t1, typename t2, typename t3, typename t4, typename t5> CImgList(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const CImg<t5>& img5, const bool is_shared=false): _width(0),_allocated_width(0),_data(0) { assign(5); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); _data[4].assign(img5,is_shared); } //! Construct list from six images. /** \param img1 First input image to copy in the constructed list. \param img2 Second input image to copy in the constructed list. \param img3 Third input image to copy in the constructed list. \param img4 Fourth input image to copy in the constructed list. \param img5 Fifth input image to copy in the constructed list. \param img6 Sixth input image to copy in the constructed list. \param is_shared Tells if the elements of the list are shared or non-shared copies of input images. **/ template<typename t1, typename t2, typename t3, typename t4, typename t5, typename t6> CImgList(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const CImg<t5>& img5, const CImg<t6>& img6, const bool is_shared=false): _width(0),_allocated_width(0),_data(0) { assign(6); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); _data[4].assign(img5,is_shared); _data[5].assign(img6,is_shared); } //! Construct list from seven images. /** \param img1 First input image to copy in the constructed list. \param img2 Second input image to copy in the constructed list. \param img3 Third input image to copy in the constructed list. \param img4 Fourth input image to copy in the constructed list. \param img5 Fifth input image to copy in the constructed list. \param img6 Sixth input image to copy in the constructed list. \param img7 Seventh input image to copy in the constructed list. \param is_shared Tells if the elements of the list are shared or non-shared copies of input images. **/ template<typename t1, typename t2, typename t3, typename t4, typename t5, typename t6, typename t7> CImgList(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const CImg<t5>& img5, const CImg<t6>& img6, const CImg<t7>& img7, const bool is_shared=false): _width(0),_allocated_width(0),_data(0) { assign(7); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); _data[4].assign(img5,is_shared); _data[5].assign(img6,is_shared); _data[6].assign(img7,is_shared); } //! Construct list from eight images. /** \param img1 First input image to copy in the constructed list. \param img2 Second input image to copy in the constructed list. \param img3 Third input image to copy in the constructed list. \param img4 Fourth input image to copy in the constructed list. \param img5 Fifth input image to copy in the constructed list. \param img6 Sixth input image to copy in the constructed list. \param img7 Seventh input image to copy in the constructed list. \param img8 Eighth input image to copy in the constructed list. \param is_shared Tells if the elements of the list are shared or non-shared copies of input images. **/ template<typename t1, typename t2, typename t3, typename t4, typename t5, typename t6, typename t7, typename t8> CImgList(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const CImg<t5>& img5, const CImg<t6>& img6, const CImg<t7>& img7, const CImg<t8>& img8, const bool is_shared=false): _width(0),_allocated_width(0),_data(0) { assign(8); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); _data[4].assign(img5,is_shared); _data[5].assign(img6,is_shared); _data[6].assign(img7,is_shared); _data[7].assign(img8,is_shared); } //! Construct list copy. /** \param list Input list to copy. \note The shared state of each element of the constructed list is kept the same as in \c list. **/ template<typename t> CImgList(const CImgList<t>& list):_width(0),_allocated_width(0),_data(0) { assign(list._width); cimglist_for(*this,l) _data[l].assign(list[l],false); } //! Construct list copy \specialization. CImgList(const CImgList<T>& list):_width(0),_allocated_width(0),_data(0) { assign(list._width); cimglist_for(*this,l) _data[l].assign(list[l],list[l]._is_shared); } //! Construct list copy, and force the shared state of the list elements. /** \param list Input list to copy. \param is_shared Tells if the elements of the list are shared or non-shared copies of input images. **/ template<typename t> CImgList(const CImgList<t>& list, const bool is_shared):_width(0),_allocated_width(0),_data(0) { assign(list._width); cimglist_for(*this,l) _data[l].assign(list[l],is_shared); } //! Construct list by reading the content of a file. /** \param filename Filename, as a C-string. **/ explicit CImgList(const char *const filename):_width(0),_allocated_width(0),_data(0) { assign(filename); } //! Construct list from the content of a display window. /** \param disp Display window to get content from. \note Constructed list contains a single image only. **/ explicit CImgList(const CImgDisplay& disp):_width(0),_allocated_width(0),_data(0) { assign(disp); } //! Return a list with elements being shared copies of images in the list instance. /** \note <tt>list2 = list1.get_shared()</tt> is equivalent to <tt>list2.assign(list1,true)</tt>. **/ CImgList<T> get_shared() { CImgList<T> res(_width); cimglist_for(*this,l) res[l].assign(_data[l],true); return res; } //! Return a list with elements being shared copies of images in the list instance \const. const CImgList<T> get_shared() const { CImgList<T> res(_width); cimglist_for(*this,l) res[l].assign(_data[l],true); return res; } //! Destructor \inplace. /** \see CImgList(). **/ CImgList<T>& assign() { delete[] _data; _width = _allocated_width = 0; _data = 0; return *this; } //! Destructor \inplace. /** Equivalent to assign(). \note Only here for compatibility with STL naming conventions. **/ CImgList<T>& clear() { return assign(); } //! Construct list containing empty images \inplace. /** \see CImgList(unsigned int). **/ CImgList<T>& assign(const unsigned int n) { if (!n) return assign(); if (_allocated_width<n || _allocated_width>(n<<2)) { delete[] _data; _data = new CImg<T>[_allocated_width = std::max(16U,(unsigned int)cimg::nearest_pow2(n))]; } _width = n; return *this; } //! Construct list containing images of specified size \inplace. /** \see CImgList(unsigned int, unsigned int, unsigned int, unsigned int, unsigned int). **/ CImgList<T>& assign(const unsigned int n, const unsigned int width, const unsigned int height=1, const unsigned int depth=1, const unsigned int spectrum=1) { assign(n); cimglist_apply(*this,assign)(width,height,depth,spectrum); return *this; } //! Construct list containing images of specified size, and initialize pixel values \inplace. /** \see CImgList(unsigned int, unsigned int, unsigned int, unsigned int, unsigned int, const T). **/ CImgList<T>& assign(const unsigned int n, const unsigned int width, const unsigned int height, const unsigned int depth, const unsigned int spectrum, const T& val) { assign(n); cimglist_apply(*this,assign)(width,height,depth,spectrum,val); return *this; } //! Construct list with images of specified size, and initialize pixel values from a sequence of integers \inplace. /** \see CImgList(unsigned int, unsigned int, unsigned int, unsigned int, unsigned int, const int, const int, ...). **/ CImgList<T>& assign(const unsigned int n, const unsigned int width, const unsigned int height, const unsigned int depth, const unsigned int spectrum, const int val0, const int val1, ...) { _CImgList_stdarg(int); return *this; } //! Construct list with images of specified size, and initialize pixel values from a sequence of doubles \inplace. /** \see CImgList(unsigned int,unsigned int,unsigned int,unsigned int,unsigned int,const double,const double,...). **/ CImgList<T>& assign(const unsigned int n, const unsigned int width, const unsigned int height, const unsigned int depth, const unsigned int spectrum, const double val0, const double val1, ...) { _CImgList_stdarg(double); return *this; } //! Construct list containing copies of an input image \inplace. /** \see CImgList(unsigned int, const CImg<t>&, bool). **/ template<typename t> CImgList<T>& assign(const unsigned int n, const CImg<t>& img, const bool is_shared=false) { assign(n); cimglist_apply(*this,assign)(img,is_shared); return *this; } //! Construct list from one image \inplace. /** \see CImgList(const CImg<t>&, bool). **/ template<typename t> CImgList<T>& assign(const CImg<t>& img, const bool is_shared=false) { assign(1); _data[0].assign(img,is_shared); return *this; } //! Construct list from two images \inplace. /** \see CImgList(const CImg<t>&, const CImg<t>&, bool). **/ template<typename t1, typename t2> CImgList<T>& assign(const CImg<t1>& img1, const CImg<t2>& img2, const bool is_shared=false) { assign(2); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); return *this; } //! Construct list from three images \inplace. /** \see CImgList(const CImg<t>&, const CImg<t>&, const CImg<t>&, bool). **/ template<typename t1, typename t2, typename t3> CImgList<T>& assign(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const bool is_shared=false) { assign(3); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); return *this; } //! Construct list from four images \inplace. /** \see CImgList(const CImg<t>&, const CImg<t>&, const CImg<t>&, const CImg<t>&, bool). **/ template<typename t1, typename t2, typename t3, typename t4> CImgList<T>& assign(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const bool is_shared=false) { assign(4); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); return *this; } //! Construct list from five images \inplace. /** \see CImgList(const CImg<t>&, const CImg<t>&, const CImg<t>&, const CImg<t>&, const CImg<t>&, bool). **/ template<typename t1, typename t2, typename t3, typename t4, typename t5> CImgList<T>& assign(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const CImg<t5>& img5, const bool is_shared=false) { assign(5); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); _data[4].assign(img5,is_shared); return *this; } //! Construct list from six images \inplace. /** \see CImgList(const CImg<t>&,const CImg<t>&,const CImg<t>&,const CImg<t>&,const CImg<t>&,const CImg<t>&, bool). **/ template<typename t1, typename t2, typename t3, typename t4, typename t5, typename t6> CImgList<T>& assign(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const CImg<t5>& img5, const CImg<t6>& img6, const bool is_shared=false) { assign(6); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); _data[4].assign(img5,is_shared); _data[5].assign(img6,is_shared); return *this; } //! Construct list from seven images \inplace. /** \see CImgList(const CImg<t>&,const CImg<t>&,const CImg<t>&,const CImg<t>&,const CImg<t>&,const CImg<t>&, const CImg<t>&, bool). **/ template<typename t1, typename t2, typename t3, typename t4, typename t5, typename t6, typename t7> CImgList<T>& assign(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const CImg<t5>& img5, const CImg<t6>& img6, const CImg<t7>& img7, const bool is_shared=false) { assign(7); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); _data[4].assign(img5,is_shared); _data[5].assign(img6,is_shared); _data[6].assign(img7,is_shared); return *this; } //! Construct list from eight images \inplace. /** \see CImgList(const CImg<t>&,const CImg<t>&,const CImg<t>&,const CImg<t>&,const CImg<t>&,const CImg<t>&, const CImg<t>&, const CImg<t>&, bool). **/ template<typename t1, typename t2, typename t3, typename t4, typename t5, typename t6, typename t7, typename t8> CImgList<T>& assign(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const CImg<t5>& img5, const CImg<t6>& img6, const CImg<t7>& img7, const CImg<t8>& img8, const bool is_shared=false) { assign(8); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); _data[4].assign(img5,is_shared); _data[5].assign(img6,is_shared); _data[6].assign(img7,is_shared); _data[7].assign(img8,is_shared); return *this; } //! Construct list as a copy of an existing list and force the shared state of the list elements \inplace. /** \see CImgList(const CImgList<t>&, bool is_shared). **/ template<typename t> CImgList<T>& assign(const CImgList<t>& list, const bool is_shared=false) { cimg::unused(is_shared); assign(list._width); cimglist_for(*this,l) _data[l].assign(list[l],false); return *this; } //! Construct list as a copy of an existing list and force shared state of elements \inplace \specialization. CImgList<T>& assign(const CImgList<T>& list, const bool is_shared=false) { if (this==&list) return *this; CImgList<T> res(list._width); cimglist_for(res,l) res[l].assign(list[l],is_shared); return res.move_to(*this); } //! Construct list by reading the content of a file \inplace. /** \see CImgList(const char *const). **/ CImgList<T>& assign(const char *const filename) { return load(filename); } //! Construct list from the content of a display window \inplace. /** \see CImgList(const CImgDisplay&). **/ CImgList<T>& assign(const CImgDisplay &disp) { return assign(CImg<T>(disp)); } //! Transfer the content of the list instance to another list. /** \param list Destination list. \note When returning, the current list instance is empty and the initial content of \c list is destroyed. **/ template<typename t> CImgList<t>& move_to(CImgList<t>& list) { list.assign(_width); bool is_one_shared_element = false; cimglist_for(*this,l) is_one_shared_element|=_data[l]._is_shared; if (is_one_shared_element) cimglist_for(*this,l) list[l].assign(_data[l]); else cimglist_for(*this,l) _data[l].move_to(list[l]); assign(); return list; } //! Transfer the content of the list instance at a specified position in another list. /** \param list Destination list. \param pos Index of the insertion in the list. \note When returning, the list instance is empty and the initial content of \c list is preserved (only images indexes may be modified). **/ template<typename t> CImgList<t>& move_to(CImgList<t>& list, const unsigned int pos) { if (is_empty()) return list; const unsigned int npos = pos>list._width?list._width:pos; list.insert(_width,npos); bool is_one_shared_element = false; cimglist_for(*this,l) is_one_shared_element|=_data[l]._is_shared; if (is_one_shared_element) cimglist_for(*this,l) list[npos + l].assign(_data[l]); else cimglist_for(*this,l) _data[l].move_to(list[npos + l]); assign(); return list; } //! Swap all fields between two list instances. /** \param list List to swap fields with. \note Can be used to exchange the content of two lists in a fast way. **/ CImgList<T>& swap(CImgList<T>& list) { cimg::swap(_width,list._width,_allocated_width,list._allocated_width); cimg::swap(_data,list._data); return list; } //! Return a reference to an empty list. /** \note Can be used to define default values in a function taking a CImgList<T> as an argument. \code void f(const CImgList<char>& list=CImgList<char>::empty()); \endcode **/ static CImgList<T>& empty() { static CImgList<T> _empty; return _empty.assign(); } //! Return a reference to an empty list \const. static const CImgList<T>& const_empty() { static const CImgList<T> _empty; return _empty; } //@} //------------------------------------------ // //! \name Overloaded Operators //@{ //------------------------------------------ //! Return a reference to one image element of the list. /** \param pos Index of the image element. **/ CImg<T>& operator()(const unsigned int pos) { #if cimg_verbosity>=3 if (pos>=_width) { cimg::warn(_cimglist_instance "operator(): Invalid image request, at position [%u].", cimglist_instance, pos); return *_data; } #endif return _data[pos]; } //! Return a reference to one image of the list. /** \param pos Index of the image element. **/ const CImg<T>& operator()(const unsigned int pos) const { return const_cast<CImgList<T>*>(this)->operator()(pos); } //! Return a reference to one pixel value of one image of the list. /** \param pos Index of the image element. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note <tt>list(n,x,y,z,c)</tt> is equivalent to <tt>list[n](x,y,z,c)</tt>. **/ T& operator()(const unsigned int pos, const unsigned int x, const unsigned int y=0, const unsigned int z=0, const unsigned int c=0) { return (*this)[pos](x,y,z,c); } //! Return a reference to one pixel value of one image of the list \const. const T& operator()(const unsigned int pos, const unsigned int x, const unsigned int y=0, const unsigned int z=0, const unsigned int c=0) const { return (*this)[pos](x,y,z,c); } //! Return pointer to the first image of the list. /** \note Images in a list are stored as a buffer of \c CImg<T>. **/ operator CImg<T>*() { return _data; } //! Return pointer to the first image of the list \const. operator const CImg<T>*() const { return _data; } //! Construct list from one image \inplace. /** \param img Input image to copy in the constructed list. \note <tt>list = img;</tt> is equivalent to <tt>list.assign(img);</tt>. **/ template<typename t> CImgList<T>& operator=(const CImg<t>& img) { return assign(img); } //! Construct list from another list. /** \param list Input list to copy. \note <tt>list1 = list2</tt> is equivalent to <tt>list1.assign(list2);</tt>. **/ template<typename t> CImgList<T>& operator=(const CImgList<t>& list) { return assign(list); } //! Construct list from another list \specialization. CImgList<T>& operator=(const CImgList<T>& list) { return assign(list); } //! Construct list by reading the content of a file \inplace. /** \see CImgList(const char *const). **/ CImgList<T>& operator=(const char *const filename) { return assign(filename); } //! Construct list from the content of a display window \inplace. /** \see CImgList(const CImgDisplay&). **/ CImgList<T>& operator=(const CImgDisplay& disp) { return assign(disp); } //! Return a non-shared copy of a list. /** \note <tt>+list</tt> is equivalent to <tt>CImgList<T>(list,false)</tt>. It forces the copy to have non-shared elements. **/ CImgList<T> operator+() const { return CImgList<T>(*this,false); } //! Return a copy of the list instance, where image \c img has been inserted at the end. /** \param img Image inserted at the end of the instance copy. \note Define a convenient way to create temporary lists of images, as in the following code: \code (img1,img2,img3,img4).display("My four images"); \endcode **/ template<typename t> CImgList<T>& operator,(const CImg<t>& img) { return insert(img); } //! Return a copy of the list instance, where image \c img has been inserted at the end \const. template<typename t> CImgList<T> operator,(const CImg<t>& img) const { return (+*this).insert(img); } //! Return a copy of the list instance, where all elements of input list \c list have been inserted at the end. /** \param list List inserted at the end of the instance copy. **/ template<typename t> CImgList<T>& operator,(const CImgList<t>& list) { return insert(list); } //! Return a copy of the list instance, where all elements of input \c list have been inserted at the end \const. template<typename t> CImgList<T>& operator,(const CImgList<t>& list) const { return (+*this).insert(list); } //! Return image corresponding to the appending of all images of the instance list along specified axis. /** \param axis Appending axis. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \note <tt>list>'x'</tt> is equivalent to <tt>list.get_append('x')</tt>. **/ CImg<T> operator>(const char axis) const { return get_append(axis,0); } //! Return list corresponding to the splitting of all images of the instance list along specified axis. /** \param axis Axis used for image splitting. \note <tt>list<'x'</tt> is equivalent to <tt>list.get_split('x')</tt>. **/ CImgList<T> operator<(const char axis) const { return get_split(axis); } //@} //------------------------------------- // //! \name Instance Characteristics //@{ //------------------------------------- //! Return the type of image pixel values as a C string. /** Return a \c char* string containing the usual type name of the image pixel values (i.e. a stringified version of the template parameter \c T). \note - The returned string may contain spaces (as in \c "unsigned char"). - If the pixel type \c T does not correspond to a registered type, the string <tt>"unknown"</tt> is returned. **/ static const char* pixel_type() { return cimg::type<T>::string(); } //! Return the size of the list, i.e. the number of images contained in it. /** \note Similar to size() but returns result as a (signed) integer. **/ int width() const { return (int)_width; } //! Return the size of the list, i.e. the number of images contained in it. /** \note Similar to width() but returns result as an unsigned integer. **/ unsigned int size() const { return _width; } //! Return pointer to the first image of the list. /** \note Images in a list are stored as a buffer of \c CImg<T>. **/ CImg<T> *data() { return _data; } //! Return pointer to the first image of the list \const. const CImg<T> *data() const { return _data; } //! Return pointer to the pos-th image of the list. /** \param pos Index of the image element to access. \note <tt>list.data(n);</tt> is equivalent to <tt>list.data + n;</tt>. **/ #if cimg_verbosity>=3 CImg<T> *data(const unsigned int pos) { if (pos>=size()) cimg::warn(_cimglist_instance "data(): Invalid pointer request, at position [%u].", cimglist_instance, pos); return _data + pos; } const CImg<T> *data(const unsigned int l) const { return const_cast<CImgList<T>*>(this)->data(l); } #else CImg<T> *data(const unsigned int l) { return _data + l; } //! Return pointer to the pos-th image of the list \const. const CImg<T> *data(const unsigned int l) const { return _data + l; } #endif //! Return iterator to the first image of the list. /** **/ iterator begin() { return _data; } //! Return iterator to the first image of the list \const. const_iterator begin() const { return _data; } //! Return iterator to one position after the last image of the list. /** **/ iterator end() { return _data + _width; } //! Return iterator to one position after the last image of the list \const. const_iterator end() const { return _data + _width; } //! Return reference to the first image of the list. /** **/ CImg<T>& front() { return *_data; } //! Return reference to the first image of the list \const. const CImg<T>& front() const { return *_data; } //! Return a reference to the last image of the list. /** **/ const CImg<T>& back() const { return *(_data + _width - 1); } //! Return a reference to the last image of the list \const. CImg<T>& back() { return *(_data + _width - 1); } //! Return pos-th image of the list. /** \param pos Index of the image element to access. **/ CImg<T>& at(const int pos) { if (is_empty()) throw CImgInstanceException(_cimglist_instance "at(): Empty instance.", cimglist_instance); return _data[cimg::cut(pos,0,width() - 1)]; } //! Access to pixel value with Dirichlet boundary conditions. /** \param pos Index of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param out_value Default value returned if \c offset is outside image bounds. \note <tt>list.atNXYZC(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZC(x,y,z,c);</tt>. **/ T& atNXYZC(const int pos, const int x, const int y, const int z, const int c, const T& out_value) { return (pos<0 || pos>=width())?(cimg::temporary(out_value)=out_value):_data[pos].atXYZC(x,y,z,c,out_value); } //! Access to pixel value with Dirichlet boundary conditions \const. T atNXYZC(const int pos, const int x, const int y, const int z, const int c, const T& out_value) const { return (pos<0 || pos>=width())?out_value:_data[pos].atXYZC(x,y,z,c,out_value); } //! Access to pixel value with Neumann boundary conditions. /** \param pos Index of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note <tt>list.atNXYZC(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZC(x,y,z,c);</tt>. **/ T& atNXYZC(const int pos, const int x, const int y, const int z, const int c) { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atNXYZC(): Empty instance.", cimglist_instance); return _atNXYZC(pos,x,y,z,c); } //! Access to pixel value with Neumann boundary conditions \const. T atNXYZC(const int pos, const int x, const int y, const int z, const int c) const { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atNXYZC(): Empty instance.", cimglist_instance); return _atNXYZC(pos,x,y,z,c); } T& _atNXYZC(const int pos, const int x, const int y, const int z, const int c) { return _data[cimg::cut(pos,0,width() - 1)].atXYZC(x,y,z,c); } T _atNXYZC(const int pos, const int x, const int y, const int z, const int c) const { return _data[cimg::cut(pos,0,width() - 1)].atXYZC(x,y,z,c); } //! Access pixel value with Dirichlet boundary conditions for the 3 coordinates (\c pos, \c x,\c y,\c z). /** \param pos Index of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param out_value Default value returned if \c offset is outside image bounds. \note <tt>list.atNXYZ(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZ(x,y,z,c);</tt>. **/ T& atNXYZ(const int pos, const int x, const int y, const int z, const int c, const T& out_value) { return (pos<0 || pos>=width())?(cimg::temporary(out_value)=out_value):_data[pos].atXYZ(x,y,z,c,out_value); } //! Access pixel value with Dirichlet boundary conditions for the 3 coordinates (\c pos, \c x,\c y,\c z) \const. T atNXYZ(const int pos, const int x, const int y, const int z, const int c, const T& out_value) const { return (pos<0 || pos>=width())?out_value:_data[pos].atXYZ(x,y,z,c,out_value); } //! Access to pixel value with Neumann boundary conditions for the 4 coordinates (\c pos, \c x,\c y,\c z). /** \param pos Index of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note <tt>list.atNXYZ(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZ(x,y,z,c);</tt>. **/ T& atNXYZ(const int pos, const int x, const int y, const int z, const int c=0) { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atNXYZ(): Empty instance.", cimglist_instance); return _atNXYZ(pos,x,y,z,c); } //! Access to pixel value with Neumann boundary conditions for the 4 coordinates (\c pos, \c x,\c y,\c z) \const. T atNXYZ(const int pos, const int x, const int y, const int z, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atNXYZ(): Empty instance.", cimglist_instance); return _atNXYZ(pos,x,y,z,c); } T& _atNXYZ(const int pos, const int x, const int y, const int z, const int c=0) { return _data[cimg::cut(pos,0,width() - 1)].atXYZ(x,y,z,c); } T _atNXYZ(const int pos, const int x, const int y, const int z, const int c=0) const { return _data[cimg::cut(pos,0,width() - 1)].atXYZ(x,y,z,c); } //! Access to pixel value with Dirichlet boundary conditions for the 3 coordinates (\c pos, \c x,\c y). /** \param pos Index of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param out_value Default value returned if \c offset is outside image bounds. \note <tt>list.atNXYZ(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZ(x,y,z,c);</tt>. **/ T& atNXY(const int pos, const int x, const int y, const int z, const int c, const T& out_value) { return (pos<0 || pos>=width())?(cimg::temporary(out_value)=out_value):_data[pos].atXY(x,y,z,c,out_value); } //! Access to pixel value with Dirichlet boundary conditions for the 3 coordinates (\c pos, \c x,\c y) \const. T atNXY(const int pos, const int x, const int y, const int z, const int c, const T& out_value) const { return (pos<0 || pos>=width())?out_value:_data[pos].atXY(x,y,z,c,out_value); } //! Access to pixel value with Neumann boundary conditions for the 3 coordinates (\c pos, \c x,\c y). /** \param pos Index of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note <tt>list.atNXYZ(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZ(x,y,z,c);</tt>. **/ T& atNXY(const int pos, const int x, const int y, const int z=0, const int c=0) { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atNXY(): Empty instance.", cimglist_instance); return _atNXY(pos,x,y,z,c); } //! Access to pixel value with Neumann boundary conditions for the 3 coordinates (\c pos, \c x,\c y) \const. T atNXY(const int pos, const int x, const int y, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atNXY(): Empty instance.", cimglist_instance); return _atNXY(pos,x,y,z,c); } T& _atNXY(const int pos, const int x, const int y, const int z=0, const int c=0) { return _data[cimg::cut(pos,0,width() - 1)].atXY(x,y,z,c); } T _atNXY(const int pos, const int x, const int y, const int z=0, const int c=0) const { return _data[cimg::cut(pos,0,width() - 1)].atXY(x,y,z,c); } //! Access to pixel value with Dirichlet boundary conditions for the 2 coordinates (\c pos,\c x). /** \param pos Index of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param out_value Default value returned if \c offset is outside image bounds. \note <tt>list.atNXYZ(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZ(x,y,z,c);</tt>. **/ T& atNX(const int pos, const int x, const int y, const int z, const int c, const T& out_value) { return (pos<0 || pos>=width())?(cimg::temporary(out_value)=out_value):_data[pos].atX(x,y,z,c,out_value); } //! Access to pixel value with Dirichlet boundary conditions for the 2 coordinates (\c pos,\c x) \const. T atNX(const int pos, const int x, const int y, const int z, const int c, const T& out_value) const { return (pos<0 || pos>=width())?out_value:_data[pos].atX(x,y,z,c,out_value); } //! Access to pixel value with Neumann boundary conditions for the 2 coordinates (\c pos, \c x). /** \param pos Index of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note <tt>list.atNXYZ(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZ(x,y,z,c);</tt>. **/ T& atNX(const int pos, const int x, const int y=0, const int z=0, const int c=0) { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atNX(): Empty instance.", cimglist_instance); return _atNX(pos,x,y,z,c); } //! Access to pixel value with Neumann boundary conditions for the 2 coordinates (\c pos, \c x) \const. T atNX(const int pos, const int x, const int y=0, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atNX(): Empty instance.", cimglist_instance); return _atNX(pos,x,y,z,c); } T& _atNX(const int pos, const int x, const int y=0, const int z=0, const int c=0) { return _data[cimg::cut(pos,0,width() - 1)].atX(x,y,z,c); } T _atNX(const int pos, const int x, const int y=0, const int z=0, const int c=0) const { return _data[cimg::cut(pos,0,width() - 1)].atX(x,y,z,c); } //! Access to pixel value with Dirichlet boundary conditions for the coordinate (\c pos). /** \param pos Index of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param out_value Default value returned if \c offset is outside image bounds. \note <tt>list.atNXYZ(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZ(x,y,z,c);</tt>. **/ T& atN(const int pos, const int x, const int y, const int z, const int c, const T& out_value) { return (pos<0 || pos>=width())?(cimg::temporary(out_value)=out_value):(*this)(pos,x,y,z,c); } //! Access to pixel value with Dirichlet boundary conditions for the coordinate (\c pos) \const. T atN(const int pos, const int x, const int y, const int z, const int c, const T& out_value) const { return (pos<0 || pos>=width())?out_value:(*this)(pos,x,y,z,c); } //! Return pixel value with Neumann boundary conditions for the coordinate (\c pos). /** \param pos Index of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note <tt>list.atNXYZ(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZ(x,y,z,c);</tt>. **/ T& atN(const int pos, const int x=0, const int y=0, const int z=0, const int c=0) { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atN(): Empty instance.", cimglist_instance); return _atN(pos,x,y,z,c); } //! Return pixel value with Neumann boundary conditions for the coordinate (\c pos) \const. T atN(const int pos, const int x=0, const int y=0, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atN(): Empty instance.", cimglist_instance); return _atN(pos,x,y,z,c); } T& _atN(const int pos, const int x=0, const int y=0, const int z=0, const int c=0) { return _data[cimg::cut(pos,0,width() - 1)](x,y,z,c); } T _atN(const int pos, const int x=0, const int y=0, const int z=0, const int c=0) const { return _data[cimg::cut(pos,0,width() - 1)](x,y,z,c); } //@} //------------------------------------- // //! \name Instance Checking //@{ //------------------------------------- //! Return \c true if list is empty. /** **/ bool is_empty() const { return (!_data || !_width); } //! Test if number of image elements is equal to specified value. /** \param size_n Number of image elements to test. **/ bool is_sameN(const unsigned int size_n) const { return _width==size_n; } //! Test if number of image elements is equal between two images lists. /** \param list Input list to compare with. **/ template<typename t> bool is_sameN(const CImgList<t>& list) const { return is_sameN(list._width); } // Define useful functions to check list dimensions. // (cannot be documented because macro-generated). #define _cimglist_def_is_same1(axis) \ bool is_same##axis(const unsigned int val) const { \ bool res = true; \ for (unsigned int l = 0; l<_width && res; ++l) res = _data[l].is_same##axis(val); return res; \ } \ bool is_sameN##axis(const unsigned int n, const unsigned int val) const { \ return is_sameN(n) && is_same##axis(val); \ } \ #define _cimglist_def_is_same2(axis1,axis2) \ bool is_same##axis1##axis2(const unsigned int val1, const unsigned int val2) const { \ bool res = true; \ for (unsigned int l = 0; l<_width && res; ++l) res = _data[l].is_same##axis1##axis2(val1,val2); return res; \ } \ bool is_sameN##axis1##axis2(const unsigned int n, const unsigned int val1, const unsigned int val2) const { \ return is_sameN(n) && is_same##axis1##axis2(val1,val2); \ } \ #define _cimglist_def_is_same3(axis1,axis2,axis3) \ bool is_same##axis1##axis2##axis3(const unsigned int val1, const unsigned int val2, \ const unsigned int val3) const { \ bool res = true; \ for (unsigned int l = 0; l<_width && res; ++l) res = _data[l].is_same##axis1##axis2##axis3(val1,val2,val3); \ return res; \ } \ bool is_sameN##axis1##axis2##axis3(const unsigned int n, const unsigned int val1, \ const unsigned int val2, const unsigned int val3) const { \ return is_sameN(n) && is_same##axis1##axis2##axis3(val1,val2,val3); \ } \ #define _cimglist_def_is_same(axis) \ template<typename t> bool is_same##axis(const CImg<t>& img) const { \ bool res = true; for (unsigned int l = 0; l<_width && res; ++l) res = _data[l].is_same##axis(img); return res; \ } \ template<typename t> bool is_same##axis(const CImgList<t>& list) const { \ const unsigned int lmin = std::min(_width,list._width); \ bool res = true; for (unsigned int l = 0; l<lmin && res; ++l) res = _data[l].is_same##axis(list[l]); return res; \ } \ template<typename t> bool is_sameN##axis(const unsigned int n, const CImg<t>& img) const { \ return (is_sameN(n) && is_same##axis(img)); \ } \ template<typename t> bool is_sameN##axis(const CImgList<t>& list) const { \ return (is_sameN(list) && is_same##axis(list)); \ } _cimglist_def_is_same(XY) _cimglist_def_is_same(XZ) _cimglist_def_is_same(XC) _cimglist_def_is_same(YZ) _cimglist_def_is_same(YC) _cimglist_def_is_same(XYZ) _cimglist_def_is_same(XYC) _cimglist_def_is_same(YZC) _cimglist_def_is_same(XYZC) _cimglist_def_is_same1(X) _cimglist_def_is_same1(Y) _cimglist_def_is_same1(Z) _cimglist_def_is_same1(C) _cimglist_def_is_same2(X,Y) _cimglist_def_is_same2(X,Z) _cimglist_def_is_same2(X,C) _cimglist_def_is_same2(Y,Z) _cimglist_def_is_same2(Y,C) _cimglist_def_is_same2(Z,C) _cimglist_def_is_same3(X,Y,Z) _cimglist_def_is_same3(X,Y,C) _cimglist_def_is_same3(X,Z,C) _cimglist_def_is_same3(Y,Z,C) //! Test if dimensions of each image of the list match specified arguments. /** \param dx Checked image width. \param dy Checked image height. \param dz Checked image depth. \param dc Checked image spectrum. **/ bool is_sameXYZC(const unsigned int dx, const unsigned int dy, const unsigned int dz, const unsigned int dc) const { bool res = true; for (unsigned int l = 0; l<_width && res; ++l) res = _data[l].is_sameXYZC(dx,dy,dz,dc); return res; } //! Test if list dimensions match specified arguments. /** \param n Number of images in the list. \param dx Checked image width. \param dy Checked image height. \param dz Checked image depth. \param dc Checked image spectrum. **/ bool is_sameNXYZC(const unsigned int n, const unsigned int dx, const unsigned int dy, const unsigned int dz, const unsigned int dc) const { return is_sameN(n) && is_sameXYZC(dx,dy,dz,dc); } //! Test if list contains one particular pixel location. /** \param n Index of the image whom checked pixel value belong to. \param x X-coordinate of the checked pixel value. \param y Y-coordinate of the checked pixel value. \param z Z-coordinate of the checked pixel value. \param c C-coordinate of the checked pixel value. **/ bool containsNXYZC(const int n, const int x=0, const int y=0, const int z=0, const int c=0) const { if (is_empty()) return false; return n>=0 && n<width() && x>=0 && x<_data[n].width() && y>=0 && y<_data[n].height() && z>=0 && z<_data[n].depth() && c>=0 && c<_data[n].spectrum(); } //! Test if list contains image with specified index. /** \param n Index of the checked image. **/ bool containsN(const int n) const { if (is_empty()) return false; return n>=0 && n<width(); } //! Test if one image of the list contains the specified referenced value. /** \param pixel Reference to pixel value to test. \param[out] n Index of image containing the pixel value, if test succeeds. \param[out] x X-coordinate of the pixel value, if test succeeds. \param[out] y Y-coordinate of the pixel value, if test succeeds. \param[out] z Z-coordinate of the pixel value, if test succeeds. \param[out] c C-coordinate of the pixel value, if test succeeds. \note If true, set coordinates (n,x,y,z,c). **/ template<typename t> bool contains(const T& pixel, t& n, t& x, t&y, t& z, t& c) const { if (is_empty()) return false; cimglist_for(*this,l) if (_data[l].contains(pixel,x,y,z,c)) { n = (t)l; return true; } return false; } //! Test if one of the image list contains the specified referenced value. /** \param pixel Reference to pixel value to test. \param[out] n Index of image containing the pixel value, if test succeeds. \param[out] x X-coordinate of the pixel value, if test succeeds. \param[out] y Y-coordinate of the pixel value, if test succeeds. \param[out] z Z-coordinate of the pixel value, if test succeeds. \note If true, set coordinates (n,x,y,z). **/ template<typename t> bool contains(const T& pixel, t& n, t& x, t&y, t& z) const { t c; return contains(pixel,n,x,y,z,c); } //! Test if one of the image list contains the specified referenced value. /** \param pixel Reference to pixel value to test. \param[out] n Index of image containing the pixel value, if test succeeds. \param[out] x X-coordinate of the pixel value, if test succeeds. \param[out] y Y-coordinate of the pixel value, if test succeeds. \note If true, set coordinates (n,x,y). **/ template<typename t> bool contains(const T& pixel, t& n, t& x, t&y) const { t z, c; return contains(pixel,n,x,y,z,c); } //! Test if one of the image list contains the specified referenced value. /** \param pixel Reference to pixel value to test. \param[out] n Index of image containing the pixel value, if test succeeds. \param[out] x X-coordinate of the pixel value, if test succeeds. \note If true, set coordinates (n,x). **/ template<typename t> bool contains(const T& pixel, t& n, t& x) const { t y, z, c; return contains(pixel,n,x,y,z,c); } //! Test if one of the image list contains the specified referenced value. /** \param pixel Reference to pixel value to test. \param[out] n Index of image containing the pixel value, if test succeeds. \note If true, set coordinates (n). **/ template<typename t> bool contains(const T& pixel, t& n) const { t x, y, z, c; return contains(pixel,n,x,y,z,c); } //! Test if one of the image list contains the specified referenced value. /** \param pixel Reference to pixel value to test. **/ bool contains(const T& pixel) const { unsigned int n, x, y, z, c; return contains(pixel,n,x,y,z,c); } //! Test if the list contains the image 'img'. /** \param img Reference to image to test. \param[out] n Index of image in the list, if test succeeds. \note If true, returns the position (n) of the image in the list. **/ template<typename t> bool contains(const CImg<T>& img, t& n) const { if (is_empty()) return false; const CImg<T> *const ptr = &img; cimglist_for(*this,i) if (_data + i==ptr) { n = (t)i; return true; } return false; } //! Test if the list contains the image img. /** \param img Reference to image to test. **/ bool contains(const CImg<T>& img) const { unsigned int n; return contains(img,n); } //@} //------------------------------------- // //! \name Mathematical Functions //@{ //------------------------------------- //! Return a reference to the minimum pixel value of the instance list. /** **/ T& min() { bool is_all_empty = true; T *ptr_min = 0; cimglist_for(*this,l) if (!_data[l].is_empty()) { ptr_min = _data[l]._data; is_all_empty = false; break; } if (is_all_empty) throw CImgInstanceException(_cimglist_instance "min(): %s.", _data?"List of empty images":"Empty instance", cimglist_instance); T min_value = *ptr_min; cimglist_for(*this,l) { const CImg<T>& img = _data[l]; cimg_for(img,ptrs,T) if (*ptrs<min_value) min_value = *(ptr_min=ptrs); } return *ptr_min; } //! Return a reference to the minimum pixel value of the instance list \const. const T& min() const { bool is_all_empty = true; T *ptr_min = 0; cimglist_for(*this,l) if (!_data[l].is_empty()) { ptr_min = _data[l]._data; is_all_empty = false; break; } if (is_all_empty) throw CImgInstanceException(_cimglist_instance "min(): %s.", _data?"List of empty images":"Empty instance", cimglist_instance); T min_value = *ptr_min; cimglist_for(*this,l) { const CImg<T>& img = _data[l]; cimg_for(img,ptrs,T) if (*ptrs<min_value) min_value = *(ptr_min=ptrs); } return *ptr_min; } //! Return a reference to the maximum pixel value of the instance list. /** **/ T& max() { bool is_all_empty = true; T *ptr_max = 0; cimglist_for(*this,l) if (!_data[l].is_empty()) { ptr_max = _data[l]._data; is_all_empty = false; break; } if (is_all_empty) throw CImgInstanceException(_cimglist_instance "max(): %s.", _data?"List of empty images":"Empty instance", cimglist_instance); T max_value = *ptr_max; cimglist_for(*this,l) { const CImg<T>& img = _data[l]; cimg_for(img,ptrs,T) if (*ptrs>max_value) max_value = *(ptr_max=ptrs); } return *ptr_max; } //! Return a reference to the maximum pixel value of the instance list \const. const T& max() const { bool is_all_empty = true; T *ptr_max = 0; cimglist_for(*this,l) if (!_data[l].is_empty()) { ptr_max = _data[l]._data; is_all_empty = false; break; } if (is_all_empty) throw CImgInstanceException(_cimglist_instance "max(): %s.", _data?"List of empty images":"Empty instance", cimglist_instance); T max_value = *ptr_max; cimglist_for(*this,l) { const CImg<T>& img = _data[l]; cimg_for(img,ptrs,T) if (*ptrs>max_value) max_value = *(ptr_max=ptrs); } return *ptr_max; } //! Return a reference to the minimum pixel value of the instance list and return the maximum vvalue as well. /** \param[out] max_val Value of the maximum value found. **/ template<typename t> T& min_max(t& max_val) { bool is_all_empty = true; T *ptr_min = 0; cimglist_for(*this,l) if (!_data[l].is_empty()) { ptr_min = _data[l]._data; is_all_empty = false; break; } if (is_all_empty) throw CImgInstanceException(_cimglist_instance "min_max(): %s.", _data?"List of empty images":"Empty instance", cimglist_instance); T min_value = *ptr_min, max_value = min_value; cimglist_for(*this,l) { const CImg<T>& img = _data[l]; cimg_for(img,ptrs,T) { const T val = *ptrs; if (val<min_value) { min_value = val; ptr_min = ptrs; } if (val>max_value) max_value = val; } } max_val = (t)max_value; return *ptr_min; } //! Return a reference to the minimum pixel value of the instance list and return the maximum vvalue as well \const. /** \param[out] max_val Value of the maximum value found. **/ template<typename t> const T& min_max(t& max_val) const { bool is_all_empty = true; T *ptr_min = 0; cimglist_for(*this,l) if (!_data[l].is_empty()) { ptr_min = _data[l]._data; is_all_empty = false; break; } if (is_all_empty) throw CImgInstanceException(_cimglist_instance "min_max(): %s.", _data?"List of empty images":"Empty instance", cimglist_instance); T min_value = *ptr_min, max_value = min_value; cimglist_for(*this,l) { const CImg<T>& img = _data[l]; cimg_for(img,ptrs,T) { const T val = *ptrs; if (val<min_value) { min_value = val; ptr_min = ptrs; } if (val>max_value) max_value = val; } } max_val = (t)max_value; return *ptr_min; } //! Return a reference to the minimum pixel value of the instance list and return the minimum value as well. /** \param[out] min_val Value of the minimum value found. **/ template<typename t> T& max_min(t& min_val) { bool is_all_empty = true; T *ptr_max = 0; cimglist_for(*this,l) if (!_data[l].is_empty()) { ptr_max = _data[l]._data; is_all_empty = false; break; } if (is_all_empty) throw CImgInstanceException(_cimglist_instance "max_min(): %s.", _data?"List of empty images":"Empty instance", cimglist_instance); T min_value = *ptr_max, max_value = min_value; cimglist_for(*this,l) { const CImg<T>& img = _data[l]; cimg_for(img,ptrs,T) { const T val = *ptrs; if (val>max_value) { max_value = val; ptr_max = ptrs; } if (val<min_value) min_value = val; } } min_val = (t)min_value; return *ptr_max; } //! Return a reference to the minimum pixel value of the instance list and return the minimum value as well \const. template<typename t> const T& max_min(t& min_val) const { bool is_all_empty = true; T *ptr_max = 0; cimglist_for(*this,l) if (!_data[l].is_empty()) { ptr_max = _data[l]._data; is_all_empty = false; break; } if (is_all_empty) throw CImgInstanceException(_cimglist_instance "max_min(): %s.", _data?"List of empty images":"Empty instance", cimglist_instance); T min_value = *ptr_max, max_value = min_value; cimglist_for(*this,l) { const CImg<T>& img = _data[l]; cimg_for(img,ptrs,T) { const T val = *ptrs; if (val>max_value) { max_value = val; ptr_max = ptrs; } if (val<min_value) min_value = val; } } min_val = (t)min_value; return *ptr_max; } //@} //--------------------------- // //! \name List Manipulation //@{ //--------------------------- //! Insert a copy of the image \c img into the current image list, at position \c pos. /** \param img Image to insert a copy to the list. \param pos Index of the insertion. \param is_shared Tells if the inserted image is a shared copy of \c img or not. **/ template<typename t> CImgList<T>& insert(const CImg<t>& img, const unsigned int pos=~0U, const bool is_shared=false) { const unsigned int npos = pos==~0U?_width:pos; if (npos>_width) throw CImgArgumentException(_cimglist_instance "insert(): Invalid insertion request of specified image (%u,%u,%u,%u,%p) " "at position %u.", cimglist_instance, img._width,img._height,img._depth,img._spectrum,img._data,npos); if (is_shared) throw CImgArgumentException(_cimglist_instance "insert(): Invalid insertion request of specified shared image " "CImg<%s>(%u,%u,%u,%u,%p) at position %u (pixel types are different).", cimglist_instance, img.pixel_type(),img._width,img._height,img._depth,img._spectrum,img._data,npos); CImg<T> *const new_data = (++_width>_allocated_width)?new CImg<T>[_allocated_width?(_allocated_width<<=1): (_allocated_width=16)]:0; if (!_data) { // Insert new element into empty list _data = new_data; *_data = img; } else { if (new_data) { // Insert with re-allocation if (npos) std::memcpy((void*)new_data,(void*)_data,sizeof(CImg<T>)*npos); if (npos!=_width - 1) std::memcpy((void*)(new_data + npos + 1),(void*)(_data + npos),sizeof(CImg<T>)*(_width - 1 - npos)); std::memset((void*)_data,0,sizeof(CImg<T>)*(_width - 1)); delete[] _data; _data = new_data; } else if (npos!=_width - 1) // Insert without re-allocation std::memmove((void*)(_data + npos + 1),(void*)(_data + npos),sizeof(CImg<T>)*(_width - 1 - npos)); _data[npos]._width = _data[npos]._height = _data[npos]._depth = _data[npos]._spectrum = 0; _data[npos]._data = 0; _data[npos] = img; } return *this; } //! Insert a copy of the image \c img into the current image list, at position \c pos \specialization. CImgList<T>& insert(const CImg<T>& img, const unsigned int pos=~0U, const bool is_shared=false) { const unsigned int npos = pos==~0U?_width:pos; if (npos>_width) throw CImgArgumentException(_cimglist_instance "insert(): Invalid insertion request of specified image (%u,%u,%u,%u,%p) " "at position %u.", cimglist_instance, img._width,img._height,img._depth,img._spectrum,img._data,npos); CImg<T> *const new_data = (++_width>_allocated_width)?new CImg<T>[_allocated_width?(_allocated_width<<=1): (_allocated_width=16)]:0; if (!_data) { // Insert new element into empty list _data = new_data; if (is_shared && img) { _data->_width = img._width; _data->_height = img._height; _data->_depth = img._depth; _data->_spectrum = img._spectrum; _data->_is_shared = true; _data->_data = img._data; } else *_data = img; } else { if (new_data) { // Insert with re-allocation if (npos) std::memcpy((void*)new_data,(void*)_data,sizeof(CImg<T>)*npos); if (npos!=_width - 1) std::memcpy((void*)(new_data + npos + 1),(void*)(_data + npos),sizeof(CImg<T>)*(_width - 1 - npos)); if (is_shared && img) { new_data[npos]._width = img._width; new_data[npos]._height = img._height; new_data[npos]._depth = img._depth; new_data[npos]._spectrum = img._spectrum; new_data[npos]._is_shared = true; new_data[npos]._data = img._data; } else { new_data[npos]._width = new_data[npos]._height = new_data[npos]._depth = new_data[npos]._spectrum = 0; new_data[npos]._data = 0; new_data[npos] = img; } std::memset((void*)_data,0,sizeof(CImg<T>)*(_width - 1)); delete[] _data; _data = new_data; } else { // Insert without re-allocation if (npos!=_width - 1) std::memmove((void*)(_data + npos + 1),(void*)(_data + npos),sizeof(CImg<T>)*(_width - 1 - npos)); if (is_shared && img) { _data[npos]._width = img._width; _data[npos]._height = img._height; _data[npos]._depth = img._depth; _data[npos]._spectrum = img._spectrum; _data[npos]._is_shared = true; _data[npos]._data = img._data; } else { _data[npos]._width = _data[npos]._height = _data[npos]._depth = _data[npos]._spectrum = 0; _data[npos]._data = 0; _data[npos] = img; } } } return *this; } //! Insert a copy of the image \c img into the current image list, at position \c pos \newinstance. template<typename t> CImgList<T> get_insert(const CImg<t>& img, const unsigned int pos=~0U, const bool is_shared=false) const { return (+*this).insert(img,pos,is_shared); } //! Insert n empty images img into the current image list, at position \p pos. /** \param n Number of empty images to insert. \param pos Index of the insertion. **/ CImgList<T>& insert(const unsigned int n, const unsigned int pos=~0U) { CImg<T> empty; if (!n) return *this; const unsigned int npos = pos==~0U?_width:pos; for (unsigned int i = 0; i<n; ++i) insert(empty,npos+i); return *this; } //! Insert n empty images img into the current image list, at position \p pos \newinstance. CImgList<T> get_insert(const unsigned int n, const unsigned int pos=~0U) const { return (+*this).insert(n,pos); } //! Insert \c n copies of the image \c img into the current image list, at position \c pos. /** \param n Number of image copies to insert. \param img Image to insert by copy. \param pos Index of the insertion. \param is_shared Tells if inserted images are shared copies of \c img or not. **/ template<typename t> CImgList<T>& insert(const unsigned int n, const CImg<t>& img, const unsigned int pos=~0U, const bool is_shared=false) { if (!n) return *this; const unsigned int npos = pos==~0U?_width:pos; insert(img,npos,is_shared); for (unsigned int i = 1; i<n; ++i) insert(_data[npos],npos + i,is_shared); return *this; } //! Insert \c n copies of the image \c img into the current image list, at position \c pos \newinstance. template<typename t> CImgList<T> get_insert(const unsigned int n, const CImg<t>& img, const unsigned int pos=~0U, const bool is_shared=false) const { return (+*this).insert(n,img,pos,is_shared); } //! Insert a copy of the image list \c list into the current image list, starting from position \c pos. /** \param list Image list to insert. \param pos Index of the insertion. \param is_shared Tells if inserted images are shared copies of images of \c list or not. **/ template<typename t> CImgList<T>& insert(const CImgList<t>& list, const unsigned int pos=~0U, const bool is_shared=false) { const unsigned int npos = pos==~0U?_width:pos; if ((void*)this!=(void*)&list) cimglist_for(list,l) insert(list[l],npos + l,is_shared); else insert(CImgList<T>(list),npos,is_shared); return *this; } //! Insert a copy of the image list \c list into the current image list, starting from position \c pos \newinstance. template<typename t> CImgList<T> get_insert(const CImgList<t>& list, const unsigned int pos=~0U, const bool is_shared=false) const { return (+*this).insert(list,pos,is_shared); } //! Insert n copies of the list \c list at position \c pos of the current list. /** \param n Number of list copies to insert. \param list Image list to insert. \param pos Index of the insertion. \param is_shared Tells if inserted images are shared copies of images of \c list or not. **/ template<typename t> CImgList<T>& insert(const unsigned int n, const CImgList<t>& list, const unsigned int pos=~0U, const bool is_shared=false) { if (!n) return *this; const unsigned int npos = pos==~0U?_width:pos; for (unsigned int i = 0; i<n; ++i) insert(list,npos,is_shared); return *this; } //! Insert n copies of the list \c list at position \c pos of the current list \newinstance. template<typename t> CImgList<T> get_insert(const unsigned int n, const CImgList<t>& list, const unsigned int pos=~0U, const bool is_shared=false) const { return (+*this).insert(n,list,pos,is_shared); } //! Remove all images between from indexes. /** \param pos1 Starting index of the removal. \param pos2 Ending index of the removal. **/ CImgList<T>& remove(const unsigned int pos1, const unsigned int pos2) { const unsigned int npos1 = pos1<pos2?pos1:pos2, tpos2 = pos1<pos2?pos2:pos1, npos2 = tpos2<_width?tpos2:_width - 1; if (npos1>=_width) throw CImgArgumentException(_cimglist_instance "remove(): Invalid remove request at positions %u->%u.", cimglist_instance, npos1,tpos2); else { if (tpos2>=_width) throw CImgArgumentException(_cimglist_instance "remove(): Invalid remove request at positions %u->%u.", cimglist_instance, npos1,tpos2); for (unsigned int k = npos1; k<=npos2; ++k) _data[k].assign(); const unsigned int nb = 1 + npos2 - npos1; if (!(_width-=nb)) return assign(); if (_width>(_allocated_width>>2) || _allocated_width<=16) { // Removing items without reallocation if (npos1!=_width) std::memmove((void*)(_data + npos1),(void*)(_data + npos2 + 1),sizeof(CImg<T>)*(_width - npos1)); std::memset((void*)(_data + _width),0,sizeof(CImg<T>)*nb); } else { // Removing items with reallocation _allocated_width>>=2; while (_allocated_width>16 && _width<(_allocated_width>>1)) _allocated_width>>=1; CImg<T> *const new_data = new CImg<T>[_allocated_width]; if (npos1) std::memcpy((void*)new_data,(void*)_data,sizeof(CImg<T>)*npos1); if (npos1!=_width) std::memcpy((void*)(new_data + npos1),(void*)(_data + npos2 + 1),sizeof(CImg<T>)*(_width - npos1)); if (_width!=_allocated_width) std::memset((void*)(new_data + _width),0,sizeof(CImg<T>)*(_allocated_width - _width)); std::memset((void*)_data,0,sizeof(CImg<T>)*(_width + nb)); delete[] _data; _data = new_data; } } return *this; } //! Remove all images between from indexes \newinstance. CImgList<T> get_remove(const unsigned int pos1, const unsigned int pos2) const { return (+*this).remove(pos1,pos2); } //! Remove image at index \c pos from the image list. /** \param pos Index of the image to remove. **/ CImgList<T>& remove(const unsigned int pos) { return remove(pos,pos); } //! Remove image at index \c pos from the image list \newinstance. CImgList<T> get_remove(const unsigned int pos) const { return (+*this).remove(pos); } //! Remove last image. /** **/ CImgList<T>& remove() { return remove(_width - 1); } //! Remove last image \newinstance. CImgList<T> get_remove() const { return (+*this).remove(); } //! Reverse list order. CImgList<T>& reverse() { for (unsigned int l = 0; l<_width/2; ++l) (*this)[l].swap((*this)[_width - 1 - l]); return *this; } //! Reverse list order \newinstance. CImgList<T> get_reverse() const { return (+*this).reverse(); } //! Return a sublist. /** \param pos0 Starting index of the sublist. \param pos1 Ending index of the sublist. **/ CImgList<T>& images(const unsigned int pos0, const unsigned int pos1) { return get_images(pos0,pos1).move_to(*this); } //! Return a sublist \newinstance. CImgList<T> get_images(const unsigned int pos0, const unsigned int pos1) const { if (pos0>pos1 || pos1>=_width) throw CImgArgumentException(_cimglist_instance "images(): Specified sub-list indices (%u->%u) are out of bounds.", cimglist_instance, pos0,pos1); CImgList<T> res(pos1 - pos0 + 1); cimglist_for(res,l) res[l].assign(_data[pos0 + l]); return res; } //! Return a shared sublist. /** \param pos0 Starting index of the sublist. \param pos1 Ending index of the sublist. **/ CImgList<T> get_shared_images(const unsigned int pos0, const unsigned int pos1) { if (pos0>pos1 || pos1>=_width) throw CImgArgumentException(_cimglist_instance "get_shared_images(): Specified sub-list indices (%u->%u) are out of bounds.", cimglist_instance, pos0,pos1); CImgList<T> res(pos1 - pos0 + 1); cimglist_for(res,l) res[l].assign(_data[pos0 + l],_data[pos0 + l]?true:false); return res; } //! Return a shared sublist \newinstance. const CImgList<T> get_shared_images(const unsigned int pos0, const unsigned int pos1) const { if (pos0>pos1 || pos1>=_width) throw CImgArgumentException(_cimglist_instance "get_shared_images(): Specified sub-list indices (%u->%u) are out of bounds.", cimglist_instance, pos0,pos1); CImgList<T> res(pos1 - pos0 + 1); cimglist_for(res,l) res[l].assign(_data[pos0 + l],_data[pos0 + l]?true:false); return res; } //! Return a single image which is the appending of all images of the current CImgList instance. /** \param axis Appending axis. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param align Appending alignment. **/ CImg<T> get_append(const char axis, const float align=0) const { if (is_empty()) return CImg<T>(); if (_width==1) return +((*this)[0]); unsigned int dx = 0, dy = 0, dz = 0, dc = 0, pos = 0; CImg<T> res; switch (cimg::lowercase(axis)) { case 'x' : { // Along the X-axis cimglist_for(*this,l) { const CImg<T>& img = (*this)[l]; if (img) { dx+=img._width; dy = std::max(dy,img._height); dz = std::max(dz,img._depth); dc = std::max(dc,img._spectrum); } } res.assign(dx,dy,dz,dc,(T)0); if (res) cimglist_for(*this,l) { const CImg<T>& img = (*this)[l]; if (img) res.draw_image(pos, (int)(align*(dy - img._height)), (int)(align*(dz - img._depth)), (int)(align*(dc - img._spectrum)), img); pos+=img._width; } } break; case 'y' : { // Along the Y-axis cimglist_for(*this,l) { const CImg<T>& img = (*this)[l]; if (img) { dx = std::max(dx,img._width); dy+=img._height; dz = std::max(dz,img._depth); dc = std::max(dc,img._spectrum); } } res.assign(dx,dy,dz,dc,(T)0); if (res) cimglist_for(*this,l) { const CImg<T>& img = (*this)[l]; if (img) res.draw_image((int)(align*(dx - img._width)), pos, (int)(align*(dz - img._depth)), (int)(align*(dc - img._spectrum)), img); pos+=img._height; } } break; case 'z' : { // Along the Z-axis cimglist_for(*this,l) { const CImg<T>& img = (*this)[l]; if (img) { dx = std::max(dx,img._width); dy = std::max(dy,img._height); dz+=img._depth; dc = std::max(dc,img._spectrum); } } res.assign(dx,dy,dz,dc,(T)0); if (res) cimglist_for(*this,l) { const CImg<T>& img = (*this)[l]; if (img) res.draw_image((int)(align*(dx - img._width)), (int)(align*(dy - img._height)), pos, (int)(align*(dc - img._spectrum)), img); pos+=img._depth; } } break; default : { // Along the C-axis cimglist_for(*this,l) { const CImg<T>& img = (*this)[l]; if (img) { dx = std::max(dx,img._width); dy = std::max(dy,img._height); dz = std::max(dz,img._depth); dc+=img._spectrum; } } res.assign(dx,dy,dz,dc,(T)0); if (res) cimglist_for(*this,l) { const CImg<T>& img = (*this)[l]; if (img) res.draw_image((int)(align*(dx - img._width)), (int)(align*(dy - img._height)), (int)(align*(dz - img._depth)), pos, img); pos+=img._spectrum; } } } return res; } //! Return a list where each image has been split along the specified axis. /** \param axis Axis to split images along. \param nb Number of spliting parts for each image. **/ CImgList<T>& split(const char axis, const int nb=-1) { return get_split(axis,nb).move_to(*this); } //! Return a list where each image has been split along the specified axis \newinstance. CImgList<T> get_split(const char axis, const int nb=-1) const { CImgList<T> res; cimglist_for(*this,l) _data[l].get_split(axis,nb).move_to(res,~0U); return res; } //! Insert image at the end of the list. /** \param img Image to insert. **/ template<typename t> CImgList<T>& push_back(const CImg<t>& img) { return insert(img); } //! Insert image at the front of the list. /** \param img Image to insert. **/ template<typename t> CImgList<T>& push_front(const CImg<t>& img) { return insert(img,0); } //! Insert list at the end of the current list. /** \param list List to insert. **/ template<typename t> CImgList<T>& push_back(const CImgList<t>& list) { return insert(list); } //! Insert list at the front of the current list. /** \param list List to insert. **/ template<typename t> CImgList<T>& push_front(const CImgList<t>& list) { return insert(list,0); } //! Remove last image. /** **/ CImgList<T>& pop_back() { return remove(_width - 1); } //! Remove first image. /** **/ CImgList<T>& pop_front() { return remove(0); } //! Remove image pointed by iterator. /** \param iter Iterator pointing to the image to remove. **/ CImgList<T>& erase(const iterator iter) { return remove(iter - _data); } //@} //---------------------------------- // //! \name Data Input //@{ //---------------------------------- //! Display a simple interactive interface to select images or sublists. /** \param disp Window instance to display selection and user interface. \param feature_type Can be \c false to select a single image, or \c true to select a sublist. \param axis Axis along whom images are appended for visualization. \param align Alignment setting when images have not all the same size. \param exit_on_anykey Exit function when any key is pressed. \return A one-column vector containing the selected image indexes. **/ CImg<intT> get_select(CImgDisplay &disp, const bool feature_type=true, const char axis='x', const float align=0, const bool exit_on_anykey=false) const { return _select(disp,0,feature_type,axis,align,exit_on_anykey,0,false,false,false); } //! Display a simple interactive interface to select images or sublists. /** \param title Title of a new window used to display selection and user interface. \param feature_type Can be \c false to select a single image, or \c true to select a sublist. \param axis Axis along whom images are appended for visualization. \param align Alignment setting when images have not all the same size. \param exit_on_anykey Exit function when any key is pressed. \return A one-column vector containing the selected image indexes. **/ CImg<intT> get_select(const char *const title, const bool feature_type=true, const char axis='x', const float align=0, const bool exit_on_anykey=false) const { CImgDisplay disp; return _select(disp,title,feature_type,axis,align,exit_on_anykey,0,false,false,false); } CImg<intT> _select(CImgDisplay &disp, const char *const title, const bool feature_type, const char axis, const float align, const bool exit_on_anykey, const unsigned int orig, const bool resize_disp, const bool exit_on_rightbutton, const bool exit_on_wheel) const { if (is_empty()) throw CImgInstanceException(_cimglist_instance "select(): Empty instance.", cimglist_instance); // Create image correspondence table and get list dimensions for visualization. CImgList<uintT> _indices; unsigned int max_width = 0, max_height = 0, sum_width = 0, sum_height = 0; cimglist_for(*this,l) { const CImg<T>& img = _data[l]; const unsigned int w = CImgDisplay::_fitscreen(img._width,img._height,img._depth,128,-85,false), h = CImgDisplay::_fitscreen(img._width,img._height,img._depth,128,-85,true); if (w>max_width) max_width = w; if (h>max_height) max_height = h; sum_width+=w; sum_height+=h; if (axis=='x') CImg<uintT>(w,1,1,1,(unsigned int)l).move_to(_indices); else CImg<uintT>(h,1,1,1,(unsigned int)l).move_to(_indices); } const CImg<uintT> indices0 = _indices>'x'; // Create display window. if (!disp) { if (axis=='x') disp.assign(cimg_fitscreen(sum_width,max_height,1),title?title:0,1); else disp.assign(cimg_fitscreen(max_width,sum_height,1),title?title:0,1); if (!title) disp.set_title("CImgList<%s> (%u)",pixel_type(),_width); } else { if (title) disp.set_title("%s",title); disp.move_inside_screen(); } if (resize_disp) { if (axis=='x') disp.resize(cimg_fitscreen(sum_width,max_height,1),false); else disp.resize(cimg_fitscreen(max_width,sum_height,1),false); } const unsigned int old_normalization = disp.normalization(); bool old_is_resized = disp.is_resized(); disp._normalization = 0; disp.show().set_key(0).show_mouse(); static const unsigned char foreground_color[] = { 255,255,255 }, background_color[] = { 0,0,0 }; // Enter event loop. CImg<ucharT> visu0, visu; CImg<uintT> indices; CImg<intT> positions(_width,4,1,1,-1); int oindex0 = -1, oindex1 = -1, index0 = -1, index1 = -1; bool is_clicked = false, is_selected = false, text_down = false, update_display = true; unsigned int key = 0; while (!is_selected && !disp.is_closed() && !key) { // Create background image. if (!visu0) { visu0.assign(disp._width,disp._height,1,3,0); visu.assign(); (indices0.get_resize(axis=='x'?visu0._width:visu0._height,1)).move_to(indices); unsigned int _ind = 0; const CImg<T> onexone(1,1,1,1,(T)0); if (axis=='x') cimg_pragma_openmp(parallel for cimg_openmp_if_size(_width,4)) cimglist_for(*this,ind) { unsigned int x0 = 0; while (x0<visu0._width && indices[x0++]!=(unsigned int)ind) {} unsigned int x1 = x0; while (x1<visu0._width && indices[x1++]==(unsigned int)ind) {} const CImg<T> &src = _data[ind]?_data[ind]:onexone; CImg<ucharT> res; src._get_select(disp,old_normalization,src._width/2,src._height/2,src._depth/2). move_to(res); const unsigned int h = CImgDisplay::_fitscreen(res._width,res._height,1,128,-85,true); res.resize(x1 - x0,std::max(32U,h*disp._height/max_height),1,res._spectrum==1?3:-100); positions(ind,0) = positions(ind,2) = (int)x0; positions(ind,1) = positions(ind,3) = (int)(align*(visu0.height() - res.height())); positions(ind,2)+=res._width; positions(ind,3)+=res._height - 1; visu0.draw_image(positions(ind,0),positions(ind,1),res); } else cimg_pragma_openmp(parallel for cimg_openmp_if_size(_width,4)) cimglist_for(*this,ind) { unsigned int y0 = 0; while (y0<visu0._height && indices[y0++]!=(unsigned int)ind) {} unsigned int y1 = y0; while (y1<visu0._height && indices[y1++]==(unsigned int)ind) {} const CImg<T> &src = _data[ind]?_data[ind]:onexone; CImg<ucharT> res; src._get_select(disp,old_normalization,(src._width - 1)/2,(src._height - 1)/2,(src._depth - 1)/2). move_to(res); const unsigned int w = CImgDisplay::_fitscreen(res._width,res._height,1,128,-85,false); res.resize(std::max(32U,w*disp._width/max_width),y1 - y0,1,res._spectrum==1?3:-100); positions(ind,0) = positions(ind,2) = (int)(align*(visu0.width() - res.width())); positions(ind,1) = positions(ind,3) = (int)y0; positions(ind,2)+=res._width - 1; positions(ind,3)+=res._height; visu0.draw_image(positions(ind,0),positions(ind,1),res); } if (axis=='x') --positions(_ind,2); else --positions(_ind,3); update_display = true; } if (!visu || oindex0!=index0 || oindex1!=index1) { if (index0>=0 && index1>=0) { visu.assign(visu0,false); const int indm = std::min(index0,index1), indM = std::max(index0,index1); for (int ind = indm; ind<=indM; ++ind) if (positions(ind,0)>=0) { visu.draw_rectangle(positions(ind,0),positions(ind,1),positions(ind,2),positions(ind,3), background_color,0.2f); if ((axis=='x' && positions(ind,2) - positions(ind,0)>=8) || (axis!='x' && positions(ind,3) - positions(ind,1)>=8)) visu.draw_rectangle(positions(ind,0),positions(ind,1),positions(ind,2),positions(ind,3), foreground_color,0.9f,0xAAAAAAAA); } if (is_clicked) visu.__draw_text(" Images #%u - #%u, Size = %u ",(int)text_down, orig + indm,orig + indM,indM - indm + 1); else visu.__draw_text(" Image #%u (%u,%u,%u,%u) ",(int)text_down, orig + index0, _data[index0]._width, _data[index0]._height, _data[index0]._depth, _data[index0]._spectrum); update_display = true; } else visu.assign(); } if (!visu) { visu.assign(visu0,true); update_display = true; } if (update_display) { visu.display(disp); update_display = false; } disp.wait(); // Manage user events. const int xm = disp.mouse_x(), ym = disp.mouse_y(); int index = -1; if (xm>=0) { index = (int)indices(axis=='x'?xm:ym); if (disp.button()&1) { if (!is_clicked) { is_clicked = true; oindex0 = index0; index0 = index; } oindex1 = index1; index1 = index; if (!feature_type) is_selected = true; } else { if (!is_clicked) { oindex0 = oindex1 = index0; index0 = index1 = index; } else is_selected = true; } } else { if (is_clicked) { if (!(disp.button()&1)) { is_clicked = is_selected = false; index0 = index1 = -1; } else index1 = -1; } else index0 = index1 = -1; } if (disp.button()&4) { is_clicked = is_selected = false; index0 = index1 = -1; } if (disp.button()&2 && exit_on_rightbutton) { is_selected = true; index1 = index0 = -1; } if (disp.wheel() && exit_on_wheel) is_selected = true; CImg<charT> filename(32); switch (key = disp.key()) { #if cimg_OS!=2 case cimg::keyCTRLRIGHT : #endif case 0 : case cimg::keyCTRLLEFT : key = 0; break; case cimg::keyD : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false). resize(CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,false), CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,true),false). _is_resized = true; disp.set_key(key,false); key = 0; visu0.assign(); } break; case cimg::keyC : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false). resize(cimg_fitscreen(2*disp.width()/3,2*disp.height()/3,1),false)._is_resized = true; disp.set_key(key,false); key = 0; visu0.assign(); } break; case cimg::keyR : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false). resize(cimg_fitscreen(axis=='x'?sum_width:max_width,axis=='x'?max_height:sum_height,1),false). _is_resized = true; disp.set_key(key,false); key = 0; visu0.assign(); } break; case cimg::keyF : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.resize(disp.screen_width(),disp.screen_height(),false).toggle_fullscreen()._is_resized = true; disp.set_key(key,false); key = 0; visu0.assign(); } break; case cimg::keyS : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { static unsigned int snap_number = 0; std::FILE *file; do { cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.bmp",snap_number++); if ((file=cimg::std_fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); if (visu0) { (+visu0).__draw_text(" Saving snapshot... ",(int)text_down).display(disp); visu0.save(filename); (+visu0).__draw_text(" Snapshot '%s' saved. ",(int)text_down,filename._data).display(disp); } disp.set_key(key,false).wait(); key = 0; } break; case cimg::keyO : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { static unsigned int snap_number = 0; std::FILE *file; do { #ifdef cimg_use_zlib cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.cimgz",snap_number++); #else cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.cimg",snap_number++); #endif if ((file=cimg::std_fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); (+visu0).__draw_text(" Saving instance... ",(int)text_down).display(disp); save(filename); (+visu0).__draw_text(" Instance '%s' saved. ",(int)text_down,filename._data).display(disp); disp.set_key(key,false).wait(); key = 0; } break; } if (disp.is_resized()) { disp.resize(false); visu0.assign(); } if (ym>=0 && ym<13) { if (!text_down) { visu.assign(); text_down = true; }} else if (ym>=visu.height() - 13) { if (text_down) { visu.assign(); text_down = false; }} if (!exit_on_anykey && key && key!=cimg::keyESC && (key!=cimg::keyW || (!disp.is_keyCTRLLEFT() && !disp.is_keyCTRLRIGHT()))) { key = 0; } } CImg<intT> res(1,2,1,1,-1); if (is_selected) { if (feature_type) res.fill(std::min(index0,index1),std::max(index0,index1)); else res.fill(index0); } if (!(disp.button()&2)) disp.set_button(); disp._normalization = old_normalization; disp._is_resized = old_is_resized; disp.set_key(key); return res; } //! Load a list from a file. /** \param filename Filename to read data from. **/ CImgList<T>& load(const char *const filename) { if (!filename) throw CImgArgumentException(_cimglist_instance "load(): Specified filename is (null).", cimglist_instance); if (!cimg::strncasecmp(filename,"http://",7) || !cimg::strncasecmp(filename,"https://",8)) { CImg<charT> filename_local(256); load(cimg::load_network(filename,filename_local)); std::remove(filename_local); return *this; } const bool is_stdin = *filename=='-' && (!filename[1] || filename[1]=='.'); const char *const ext = cimg::split_filename(filename); const unsigned int omode = cimg::exception_mode(); cimg::exception_mode(0); bool is_loaded = true; try { #ifdef cimglist_load_plugin cimglist_load_plugin(filename); #endif #ifdef cimglist_load_plugin1 cimglist_load_plugin1(filename); #endif #ifdef cimglist_load_plugin2 cimglist_load_plugin2(filename); #endif #ifdef cimglist_load_plugin3 cimglist_load_plugin3(filename); #endif #ifdef cimglist_load_plugin4 cimglist_load_plugin4(filename); #endif #ifdef cimglist_load_plugin5 cimglist_load_plugin5(filename); #endif #ifdef cimglist_load_plugin6 cimglist_load_plugin6(filename); #endif #ifdef cimglist_load_plugin7 cimglist_load_plugin7(filename); #endif #ifdef cimglist_load_plugin8 cimglist_load_plugin8(filename); #endif if (!cimg::strcasecmp(ext,"tif") || !cimg::strcasecmp(ext,"tiff")) load_tiff(filename); else if (!cimg::strcasecmp(ext,"gif")) load_gif_external(filename); else if (!cimg::strcasecmp(ext,"cimg") || !cimg::strcasecmp(ext,"cimgz") || !*ext) load_cimg(filename); else if (!cimg::strcasecmp(ext,"rec") || !cimg::strcasecmp(ext,"par")) load_parrec(filename); else if (!cimg::strcasecmp(ext,"avi") || !cimg::strcasecmp(ext,"mov") || !cimg::strcasecmp(ext,"asf") || !cimg::strcasecmp(ext,"divx") || !cimg::strcasecmp(ext,"flv") || !cimg::strcasecmp(ext,"mpg") || !cimg::strcasecmp(ext,"m1v") || !cimg::strcasecmp(ext,"m2v") || !cimg::strcasecmp(ext,"m4v") || !cimg::strcasecmp(ext,"mjp") || !cimg::strcasecmp(ext,"mp4") || !cimg::strcasecmp(ext,"mkv") || !cimg::strcasecmp(ext,"mpe") || !cimg::strcasecmp(ext,"movie") || !cimg::strcasecmp(ext,"ogm") || !cimg::strcasecmp(ext,"ogg") || !cimg::strcasecmp(ext,"ogv") || !cimg::strcasecmp(ext,"qt") || !cimg::strcasecmp(ext,"rm") || !cimg::strcasecmp(ext,"vob") || !cimg::strcasecmp(ext,"wmv") || !cimg::strcasecmp(ext,"xvid") || !cimg::strcasecmp(ext,"mpeg")) load_video(filename); else if (!cimg::strcasecmp(ext,"gz")) load_gzip_external(filename); else is_loaded = false; } catch (CImgIOException&) { is_loaded = false; } // If nothing loaded, try to guess file format from magic number in file. if (!is_loaded && !is_stdin) { std::FILE *const file = cimg::std_fopen(filename,"rb"); if (!file) { cimg::exception_mode(omode); throw CImgIOException(_cimglist_instance "load(): Failed to open file '%s'.", cimglist_instance, filename); } const char *const f_type = cimg::ftype(file,filename); cimg::fclose(file); is_loaded = true; try { if (!cimg::strcasecmp(f_type,"gif")) load_gif_external(filename); else if (!cimg::strcasecmp(f_type,"tif")) load_tiff(filename); else is_loaded = false; } catch (CImgIOException&) { is_loaded = false; } } // If nothing loaded, try to load file as a single image. if (!is_loaded) { assign(1); try { _data->load(filename); } catch (CImgIOException&) { cimg::exception_mode(omode); throw CImgIOException(_cimglist_instance "load(): Failed to recognize format of file '%s'.", cimglist_instance, filename); } } cimg::exception_mode(omode); return *this; } //! Load a list from a file \newinstance. static CImgList<T> get_load(const char *const filename) { return CImgList<T>().load(filename); } //! Load a list from a .cimg file. /** \param filename Filename to read data from. **/ CImgList<T>& load_cimg(const char *const filename) { return _load_cimg(0,filename); } //! Load a list from a .cimg file \newinstance. static CImgList<T> get_load_cimg(const char *const filename) { return CImgList<T>().load_cimg(filename); } //! Load a list from a .cimg file. /** \param file File to read data from. **/ CImgList<T>& load_cimg(std::FILE *const file) { return _load_cimg(file,0); } //! Load a list from a .cimg file \newinstance. static CImgList<T> get_load_cimg(std::FILE *const file) { return CImgList<T>().load_cimg(file); } CImgList<T>& _load_cimg(std::FILE *const file, const char *const filename) { #ifdef cimg_use_zlib #define _cimgz_load_cimg_case(Tss) { \ Bytef *const cbuf = new Bytef[csiz]; \ cimg::fread(cbuf,csiz,nfile); \ raw.assign(W,H,D,C); \ uLongf destlen = (ulongT)raw.size()*sizeof(Tss); \ uncompress((Bytef*)raw._data,&destlen,cbuf,csiz); \ delete[] cbuf; \ if (endian!=cimg::endianness()) cimg::invert_endianness(raw._data,raw.size()); \ raw.move_to(img); \ } #else #define _cimgz_load_cimg_case(Tss) \ throw CImgIOException(_cimglist_instance \ "load_cimg(): Unable to load compressed data from file '%s' unless zlib is enabled.", \ cimglist_instance, \ filename?filename:"(FILE*)"); #endif #define _cimg_load_cimg_case(Ts,Tss) \ if (!loaded && !cimg::strcasecmp(Ts,str_pixeltype)) { \ for (unsigned int l = 0; l<N; ++l) { \ j = 0; while ((i=std::fgetc(nfile))!='\n' && i>=0 && j<255) tmp[j++] = (char)i; tmp[j] = 0; \ W = H = D = C = 0; csiz = 0; \ if ((err = cimg_sscanf(tmp,"%u %u %u %u #%lu",&W,&H,&D,&C,&csiz))<4) \ throw CImgIOException(_cimglist_instance \ "load_cimg(): Invalid specified size (%u,%u,%u,%u) of image %u in file '%s'.", \ cimglist_instance, \ W,H,D,C,l,filename?filename:("(FILE*)")); \ if (W*H*D*C>0) { \ CImg<Tss> raw; \ CImg<T> &img = _data[l]; \ if (err==5) _cimgz_load_cimg_case(Tss) \ else { \ img.assign(W,H,D,C); \ T *ptrd = img._data; \ for (ulongT to_read = img.size(); to_read; ) { \ raw.assign((unsigned int)std::min(to_read,cimg_iobuffer)); \ cimg::fread(raw._data,raw._width,nfile); \ if (endian!=cimg::endianness()) cimg::invert_endianness(raw._data,raw.size()); \ const Tss *ptrs = raw._data; \ for (ulongT off = (ulongT)raw._width; off; --off) *(ptrd++) = (T)*(ptrs++); \ to_read-=raw._width; \ } \ } \ } \ } \ loaded = true; \ } if (!filename && !file) throw CImgArgumentException(_cimglist_instance "load_cimg(): Specified filename is (null).", cimglist_instance); const ulongT cimg_iobuffer = (ulongT)24*1024*1024; std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); bool loaded = false, endian = cimg::endianness(); CImg<charT> tmp(256), str_pixeltype(256), str_endian(256); *tmp = *str_pixeltype = *str_endian = 0; unsigned int j, N = 0, W, H, D, C; unsigned long csiz; int i, err; do { j = 0; while ((i=std::fgetc(nfile))!='\n' && i>=0 && j<255) tmp[j++] = (char)i; tmp[j] = 0; } while (*tmp=='#' && i>=0); err = cimg_sscanf(tmp,"%u%*c%255[A-Za-z64_]%*c%255[sA-Za-z_ ]", &N,str_pixeltype._data,str_endian._data); if (err<2) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimglist_instance "load_cimg(): CImg header not found in file '%s'.", cimglist_instance, filename?filename:"(FILE*)"); } if (!cimg::strncasecmp("little",str_endian,6)) endian = false; else if (!cimg::strncasecmp("big",str_endian,3)) endian = true; assign(N); _cimg_load_cimg_case("bool",bool); _cimg_load_cimg_case("unsigned_char",unsigned char); _cimg_load_cimg_case("uchar",unsigned char); _cimg_load_cimg_case("char",char); _cimg_load_cimg_case("unsigned_short",unsigned short); _cimg_load_cimg_case("ushort",unsigned short); _cimg_load_cimg_case("short",short); _cimg_load_cimg_case("unsigned_int",unsigned int); _cimg_load_cimg_case("uint",unsigned int); _cimg_load_cimg_case("int",int); _cimg_load_cimg_case("unsigned_long",ulongT); _cimg_load_cimg_case("ulong",ulongT); _cimg_load_cimg_case("long",longT); _cimg_load_cimg_case("unsigned_int64",uint64T); _cimg_load_cimg_case("uint64",uint64T); _cimg_load_cimg_case("int64",int64T); _cimg_load_cimg_case("float",float); _cimg_load_cimg_case("double",double); if (!loaded) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimglist_instance "load_cimg(): Unsupported pixel type '%s' for file '%s'.", cimglist_instance, str_pixeltype._data,filename?filename:"(FILE*)"); } if (!file) cimg::fclose(nfile); return *this; } //! Load a sublist list from a (non compressed) .cimg file. /** \param filename Filename to read data from. \param n0 Starting index of images to read (~0U for max). \param n1 Ending index of images to read (~0U for max). \param x0 Starting X-coordinates of image regions to read. \param y0 Starting Y-coordinates of image regions to read. \param z0 Starting Z-coordinates of image regions to read. \param c0 Starting C-coordinates of image regions to read. \param x1 Ending X-coordinates of image regions to read (~0U for max). \param y1 Ending Y-coordinates of image regions to read (~0U for max). \param z1 Ending Z-coordinates of image regions to read (~0U for max). \param c1 Ending C-coordinates of image regions to read (~0U for max). **/ CImgList<T>& load_cimg(const char *const filename, const unsigned int n0, const unsigned int n1, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0, const unsigned int x1, const unsigned int y1, const unsigned int z1, const unsigned int c1) { return _load_cimg(0,filename,n0,n1,x0,y0,z0,c0,x1,y1,z1,c1); } //! Load a sublist list from a (non compressed) .cimg file \newinstance. static CImgList<T> get_load_cimg(const char *const filename, const unsigned int n0, const unsigned int n1, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0, const unsigned int x1, const unsigned int y1, const unsigned int z1, const unsigned int c1) { return CImgList<T>().load_cimg(filename,n0,n1,x0,y0,z0,c0,x1,y1,z1,c1); } //! Load a sub-image list from a (non compressed) .cimg file \overloading. CImgList<T>& load_cimg(std::FILE *const file, const unsigned int n0, const unsigned int n1, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0, const unsigned int x1, const unsigned int y1, const unsigned int z1, const unsigned int c1) { return _load_cimg(file,0,n0,n1,x0,y0,z0,c0,x1,y1,z1,c1); } //! Load a sub-image list from a (non compressed) .cimg file \newinstance. static CImgList<T> get_load_cimg(std::FILE *const file, const unsigned int n0, const unsigned int n1, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0, const unsigned int x1, const unsigned int y1, const unsigned int z1, const unsigned int c1) { return CImgList<T>().load_cimg(file,n0,n1,x0,y0,z0,c0,x1,y1,z1,c1); } CImgList<T>& _load_cimg(std::FILE *const file, const char *const filename, const unsigned int n0, const unsigned int n1, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0, const unsigned int x1, const unsigned int y1, const unsigned int z1, const unsigned int c1) { #define _cimg_load_cimg_case2(Ts,Tss) \ if (!loaded && !cimg::strcasecmp(Ts,str_pixeltype)) { \ for (unsigned int l = 0; l<=nn1; ++l) { \ j = 0; while ((i=std::fgetc(nfile))!='\n' && i>=0) tmp[j++] = (char)i; tmp[j] = 0; \ W = H = D = C = 0; \ if (cimg_sscanf(tmp,"%u %u %u %u",&W,&H,&D,&C)!=4) \ throw CImgIOException(_cimglist_instance \ "load_cimg(): Invalid specified size (%u,%u,%u,%u) of image %u in file '%s'", \ cimglist_instance, \ W,H,D,C,l,filename?filename:"(FILE*)"); \ if (W*H*D*C>0) { \ if (l<nn0 || nx0>=W || ny0>=H || nz0>=D || nc0>=C) cimg::fseek(nfile,W*H*D*C*sizeof(Tss),SEEK_CUR); \ else { \ const unsigned int \ _nx1 = nx1==~0U?W - 1:nx1, \ _ny1 = ny1==~0U?H - 1:ny1, \ _nz1 = nz1==~0U?D - 1:nz1, \ _nc1 = nc1==~0U?C - 1:nc1; \ if (_nx1>=W || _ny1>=H || _nz1>=D || _nc1>=C) \ throw CImgArgumentException(_cimglist_instance \ "load_cimg(): Invalid specified coordinates " \ "[%u](%u,%u,%u,%u) -> [%u](%u,%u,%u,%u) " \ "because image [%u] in file '%s' has size (%u,%u,%u,%u).", \ cimglist_instance, \ n0,x0,y0,z0,c0,n1,x1,y1,z1,c1,l,filename?filename:"(FILE*)",W,H,D,C); \ CImg<Tss> raw(1 + _nx1 - nx0); \ CImg<T> &img = _data[l - nn0]; \ img.assign(1 + _nx1 - nx0,1 + _ny1 - ny0,1 + _nz1 - nz0,1 + _nc1 - nc0); \ T *ptrd = img._data; \ ulongT skipvb = nc0*W*H*D*sizeof(Tss); \ if (skipvb) cimg::fseek(nfile,skipvb,SEEK_CUR); \ for (unsigned int c = 1 + _nc1 - nc0; c; --c) { \ const ulongT skipzb = nz0*W*H*sizeof(Tss); \ if (skipzb) cimg::fseek(nfile,skipzb,SEEK_CUR); \ for (unsigned int z = 1 + _nz1 - nz0; z; --z) { \ const ulongT skipyb = ny0*W*sizeof(Tss); \ if (skipyb) cimg::fseek(nfile,skipyb,SEEK_CUR); \ for (unsigned int y = 1 + _ny1 - ny0; y; --y) { \ const ulongT skipxb = nx0*sizeof(Tss); \ if (skipxb) cimg::fseek(nfile,skipxb,SEEK_CUR); \ cimg::fread(raw._data,raw._width,nfile); \ if (endian!=cimg::endianness()) cimg::invert_endianness(raw._data,raw._width); \ const Tss *ptrs = raw._data; \ for (unsigned int off = raw._width; off; --off) *(ptrd++) = (T)*(ptrs++); \ const ulongT skipxe = (W - 1 - _nx1)*sizeof(Tss); \ if (skipxe) cimg::fseek(nfile,skipxe,SEEK_CUR); \ } \ const ulongT skipye = (H - 1 - _ny1)*W*sizeof(Tss); \ if (skipye) cimg::fseek(nfile,skipye,SEEK_CUR); \ } \ const ulongT skipze = (D - 1 - _nz1)*W*H*sizeof(Tss); \ if (skipze) cimg::fseek(nfile,skipze,SEEK_CUR); \ } \ const ulongT skipve = (C - 1 - _nc1)*W*H*D*sizeof(Tss); \ if (skipve) cimg::fseek(nfile,skipve,SEEK_CUR); \ } \ } \ } \ loaded = true; \ } if (!filename && !file) throw CImgArgumentException(_cimglist_instance "load_cimg(): Specified filename is (null).", cimglist_instance); unsigned int nn0 = std::min(n0,n1), nn1 = std::max(n0,n1), nx0 = std::min(x0,x1), nx1 = std::max(x0,x1), ny0 = std::min(y0,y1), ny1 = std::max(y0,y1), nz0 = std::min(z0,z1), nz1 = std::max(z0,z1), nc0 = std::min(c0,c1), nc1 = std::max(c0,c1); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); bool loaded = false, endian = cimg::endianness(); CImg<charT> tmp(256), str_pixeltype(256), str_endian(256); *tmp = *str_pixeltype = *str_endian = 0; unsigned int j, N, W, H, D, C; int i, err; j = 0; while ((i=std::fgetc(nfile))!='\n' && i!=EOF && j<256) tmp[j++] = (char)i; tmp[j] = 0; err = cimg_sscanf(tmp,"%u%*c%255[A-Za-z64_]%*c%255[sA-Za-z_ ]", &N,str_pixeltype._data,str_endian._data); if (err<2) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimglist_instance "load_cimg(): CImg header not found in file '%s'.", cimglist_instance, filename?filename:"(FILE*)"); } if (!cimg::strncasecmp("little",str_endian,6)) endian = false; else if (!cimg::strncasecmp("big",str_endian,3)) endian = true; nn1 = n1==~0U?N - 1:n1; if (nn1>=N) throw CImgArgumentException(_cimglist_instance "load_cimg(): Invalid specified coordinates [%u](%u,%u,%u,%u) -> [%u](%u,%u,%u,%u) " "because file '%s' contains only %u images.", cimglist_instance, n0,x0,y0,z0,c0,n1,x1,y1,z1,c1,filename?filename:"(FILE*)",N); assign(1 + nn1 - n0); _cimg_load_cimg_case2("bool",bool); _cimg_load_cimg_case2("unsigned_char",unsigned char); _cimg_load_cimg_case2("uchar",unsigned char); _cimg_load_cimg_case2("char",char); _cimg_load_cimg_case2("unsigned_short",unsigned short); _cimg_load_cimg_case2("ushort",unsigned short); _cimg_load_cimg_case2("short",short); _cimg_load_cimg_case2("unsigned_int",unsigned int); _cimg_load_cimg_case2("uint",unsigned int); _cimg_load_cimg_case2("int",int); _cimg_load_cimg_case2("unsigned_long",ulongT); _cimg_load_cimg_case2("ulong",ulongT); _cimg_load_cimg_case2("long",longT); _cimg_load_cimg_case2("unsigned_int64",uint64T); _cimg_load_cimg_case2("uint64",uint64T); _cimg_load_cimg_case2("int64",int64T); _cimg_load_cimg_case2("float",float); _cimg_load_cimg_case2("double",double); if (!loaded) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimglist_instance "load_cimg(): Unsupported pixel type '%s' for file '%s'.", cimglist_instance, str_pixeltype._data,filename?filename:"(FILE*)"); } if (!file) cimg::fclose(nfile); return *this; } //! Load a list from a PAR/REC (Philips) file. /** \param filename Filename to read data from. **/ CImgList<T>& load_parrec(const char *const filename) { if (!filename) throw CImgArgumentException(_cimglist_instance "load_parrec(): Specified filename is (null).", cimglist_instance); CImg<charT> body(1024), filenamepar(1024), filenamerec(1024); *body = *filenamepar = *filenamerec = 0; const char *const ext = cimg::split_filename(filename,body); if (!std::strcmp(ext,"par")) { std::strncpy(filenamepar,filename,filenamepar._width - 1); cimg_snprintf(filenamerec,filenamerec._width,"%s.rec",body._data); } if (!std::strcmp(ext,"PAR")) { std::strncpy(filenamepar,filename,filenamepar._width - 1); cimg_snprintf(filenamerec,filenamerec._width,"%s.REC",body._data); } if (!std::strcmp(ext,"rec")) { std::strncpy(filenamerec,filename,filenamerec._width - 1); cimg_snprintf(filenamepar,filenamepar._width,"%s.par",body._data); } if (!std::strcmp(ext,"REC")) { std::strncpy(filenamerec,filename,filenamerec._width - 1); cimg_snprintf(filenamepar,filenamepar._width,"%s.PAR",body._data); } std::FILE *file = cimg::fopen(filenamepar,"r"); // Parse header file CImgList<floatT> st_slices; CImgList<uintT> st_global; CImg<charT> line(256); *line = 0; int err; do { err = std::fscanf(file,"%255[^\n]%*c",line._data); } while (err!=EOF && (*line=='#' || *line=='.')); do { unsigned int sn,size_x,size_y,pixsize; float rs,ri,ss; err = std::fscanf(file,"%u%*u%*u%*u%*u%*u%*u%u%*u%u%u%g%g%g%*[^\n]",&sn,&pixsize,&size_x,&size_y,&ri,&rs,&ss); if (err==7) { CImg<floatT>::vector((float)sn,(float)pixsize,(float)size_x,(float)size_y,ri,rs,ss,0).move_to(st_slices); unsigned int i; for (i = 0; i<st_global._width && sn<=st_global[i][2]; ++i) {} if (i==st_global._width) CImg<uintT>::vector(size_x,size_y,sn).move_to(st_global); else { CImg<uintT> &vec = st_global[i]; if (size_x>vec[0]) vec[0] = size_x; if (size_y>vec[1]) vec[1] = size_y; vec[2] = sn; } st_slices[st_slices._width - 1][7] = (float)i; } } while (err==7); // Read data std::FILE *file2 = cimg::fopen(filenamerec,"rb"); cimglist_for(st_global,l) { const CImg<uintT>& vec = st_global[l]; CImg<T>(vec[0],vec[1],vec[2]).move_to(*this); } cimglist_for(st_slices,l) { const CImg<floatT>& vec = st_slices[l]; const unsigned int sn = (unsigned int)vec[0] - 1, pixsize = (unsigned int)vec[1], size_x = (unsigned int)vec[2], size_y = (unsigned int)vec[3], imn = (unsigned int)vec[7]; const float ri = vec[4], rs = vec[5], ss = vec[6]; switch (pixsize) { case 8 : { CImg<ucharT> buf(size_x,size_y); cimg::fread(buf._data,size_x*size_y,file2); if (cimg::endianness()) cimg::invert_endianness(buf._data,size_x*size_y); CImg<T>& img = (*this)[imn]; cimg_forXY(img,x,y) img(x,y,sn) = (T)(( buf(x,y)*rs + ri )/(rs*ss)); } break; case 16 : { CImg<ushortT> buf(size_x,size_y); cimg::fread(buf._data,size_x*size_y,file2); if (cimg::endianness()) cimg::invert_endianness(buf._data,size_x*size_y); CImg<T>& img = (*this)[imn]; cimg_forXY(img,x,y) img(x,y,sn) = (T)(( buf(x,y)*rs + ri )/(rs*ss)); } break; case 32 : { CImg<uintT> buf(size_x,size_y); cimg::fread(buf._data,size_x*size_y,file2); if (cimg::endianness()) cimg::invert_endianness(buf._data,size_x*size_y); CImg<T>& img = (*this)[imn]; cimg_forXY(img,x,y) img(x,y,sn) = (T)(( buf(x,y)*rs + ri )/(rs*ss)); } break; default : cimg::fclose(file); cimg::fclose(file2); throw CImgIOException(_cimglist_instance "load_parrec(): Unsupported %d-bits pixel type for file '%s'.", cimglist_instance, pixsize,filename); } } cimg::fclose(file); cimg::fclose(file2); if (!_width) throw CImgIOException(_cimglist_instance "load_parrec(): Failed to recognize valid PAR-REC data in file '%s'.", cimglist_instance, filename); return *this; } //! Load a list from a PAR/REC (Philips) file \newinstance. static CImgList<T> get_load_parrec(const char *const filename) { return CImgList<T>().load_parrec(filename); } //! Load a list from a YUV image sequence file. /** \param filename Filename to read data from. \param size_x Width of the images. \param size_y Height of the images. \param chroma_subsampling Type of chroma subsampling. Can be <tt>{ 420 | 422 | 444 }</tt>. \param first_frame Index of first image frame to read. \param last_frame Index of last image frame to read. \param step_frame Step applied between each frame. \param yuv2rgb Apply YUV to RGB transformation during reading. **/ CImgList<T>& load_yuv(const char *const filename, const unsigned int size_x, const unsigned int size_y, const unsigned int chroma_subsampling=444, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const bool yuv2rgb=true) { return _load_yuv(0,filename,size_x,size_y,chroma_subsampling, first_frame,last_frame,step_frame,yuv2rgb); } //! Load a list from a YUV image sequence file \newinstance. static CImgList<T> get_load_yuv(const char *const filename, const unsigned int size_x, const unsigned int size_y=1, const unsigned int chroma_subsampling=444, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const bool yuv2rgb=true) { return CImgList<T>().load_yuv(filename,size_x,size_y,chroma_subsampling, first_frame,last_frame,step_frame,yuv2rgb); } //! Load a list from an image sequence YUV file \overloading. CImgList<T>& load_yuv(std::FILE *const file, const unsigned int size_x, const unsigned int size_y, const unsigned int chroma_subsampling=444, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const bool yuv2rgb=true) { return _load_yuv(file,0,size_x,size_y,chroma_subsampling, first_frame,last_frame,step_frame,yuv2rgb); } //! Load a list from an image sequence YUV file \newinstance. static CImgList<T> get_load_yuv(std::FILE *const file, const unsigned int size_x, const unsigned int size_y=1, const unsigned int chroma_subsampling=444, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const bool yuv2rgb=true) { return CImgList<T>().load_yuv(file,size_x,size_y,chroma_subsampling, first_frame,last_frame,step_frame,yuv2rgb); } CImgList<T>& _load_yuv(std::FILE *const file, const char *const filename, const unsigned int size_x, const unsigned int size_y, const unsigned int chroma_subsampling, const unsigned int first_frame, const unsigned int last_frame, const unsigned int step_frame, const bool yuv2rgb) { if (!filename && !file) throw CImgArgumentException(_cimglist_instance "load_yuv(): Specified filename is (null).", cimglist_instance); if (chroma_subsampling!=420 && chroma_subsampling!=422 && chroma_subsampling!=444) throw CImgArgumentException(_cimglist_instance "load_yuv(): Specified chroma subsampling '%u' is invalid, for file '%s'.", cimglist_instance, chroma_subsampling,filename?filename:"(FILE*)"); const unsigned int cfx = chroma_subsampling==420 || chroma_subsampling==422?2:1, cfy = chroma_subsampling==420?2:1, nfirst_frame = first_frame<last_frame?first_frame:last_frame, nlast_frame = first_frame<last_frame?last_frame:first_frame, nstep_frame = step_frame?step_frame:1; if (!size_x || !size_y || size_x%cfx || size_y%cfy) throw CImgArgumentException(_cimglist_instance "load_yuv(): Specified dimensions (%u,%u) are invalid, for file '%s'.", cimglist_instance, size_x,size_y,filename?filename:"(FILE*)"); CImg<ucharT> YUV(size_x,size_y,1,3), UV(size_x/cfx,size_y/cfy,1,2); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); bool stop_flag = false; int err; if (nfirst_frame) { err = cimg::fseek(nfile,(uint64T)nfirst_frame*(YUV._width*YUV._height + 2*UV._width*UV._height),SEEK_CUR); if (err) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimglist_instance "load_yuv(): File '%s' doesn't contain frame number %u.", cimglist_instance, filename?filename:"(FILE*)",nfirst_frame); } } unsigned int frame; for (frame = nfirst_frame; !stop_flag && frame<=nlast_frame; frame+=nstep_frame) { YUV.get_shared_channel(0).fill(0); // *TRY* to read the luminance part, do not replace by cimg::fread! err = (int)std::fread((void*)(YUV._data),1,(size_t)YUV._width*YUV._height,nfile); if (err!=(int)(YUV._width*YUV._height)) { stop_flag = true; if (err>0) cimg::warn(_cimglist_instance "load_yuv(): File '%s' contains incomplete data or given image dimensions " "(%u,%u) are incorrect.", cimglist_instance, filename?filename:"(FILE*)",size_x,size_y); } else { UV.fill(0); // *TRY* to read the luminance part, do not replace by cimg::fread! err = (int)std::fread((void*)(UV._data),1,(size_t)UV.size(),nfile); if (err!=(int)(UV.size())) { stop_flag = true; if (err>0) cimg::warn(_cimglist_instance "load_yuv(): File '%s' contains incomplete data or given image dimensions " "(%u,%u) are incorrect.", cimglist_instance, filename?filename:"(FILE*)",size_x,size_y); } else { const ucharT *ptrs1 = UV._data, *ptrs2 = UV.data(0,0,0,1); ucharT *ptrd1 = YUV.data(0,0,0,1), *ptrd2 = YUV.data(0,0,0,2); const unsigned int wd = YUV._width; switch (chroma_subsampling) { case 420 : cimg_forY(UV,y) { cimg_forX(UV,x) { const ucharT U = *(ptrs1++), V = *(ptrs2++); ptrd1[wd] = U; *(ptrd1)++ = U; ptrd1[wd] = U; *(ptrd1)++ = U; ptrd2[wd] = V; *(ptrd2)++ = V; ptrd2[wd] = V; *(ptrd2)++ = V; } ptrd1+=wd; ptrd2+=wd; } break; case 422 : cimg_forXY(UV,x,y) { const ucharT U = *(ptrs1++), V = *(ptrs2++); *(ptrd1++) = U; *(ptrd1++) = U; *(ptrd2++) = V; *(ptrd2++) = V; } break; default : YUV.draw_image(0,0,0,1,UV); } if (yuv2rgb) YUV.YCbCrtoRGB(); insert(YUV); if (nstep_frame>1) cimg::fseek(nfile,(uint64T)(nstep_frame - 1)*(size_x*size_y + size_x*size_y/2),SEEK_CUR); } } } if (is_empty()) throw CImgIOException(_cimglist_instance "load_yuv() : Missing data in file '%s'.", cimglist_instance, filename?filename:"(FILE*)"); if (stop_flag && nlast_frame!=~0U && frame!=nlast_frame) cimg::warn(_cimglist_instance "load_yuv(): Frame %d not reached since only %u frames were found in file '%s'.", cimglist_instance, nlast_frame,frame - 1,filename?filename:"(FILE*)"); if (!file) cimg::fclose(nfile); return *this; } //! Load an image from a video file, using OpenCV library. /** \param filename Filename, as a C-string. \param first_frame Index of the first frame to read. \param last_frame Index of the last frame to read (can be higher than the actual number of frames, e.g. '~0U'). \param step_frame Step value for frame reading. \note If step_frame==0, the current video stream is forced to be released (without any frames read). **/ CImgList<T>& load_video(const char *const filename, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1) { #ifndef cimg_use_opencv if (first_frame || last_frame!=~0U || step_frame>1) throw CImgArgumentException(_cimglist_instance "load_video() : File '%s', arguments 'first_frame', 'last_frame' " "and 'step_frame' can be only set when using OpenCV " "(-Dcimg_use_opencv must be enabled).", cimglist_instance,filename); return load_ffmpeg_external(filename); #else static cv::VideoCapture *captures[32] = { 0 }; static CImgList<charT> filenames(32); static CImg<uintT> positions(32,1,1,1,0); static int last_used_index = -1; // Detect if a video capture already exists for the specified filename. cimg::mutex(9); int index = -1; if (filename) { if (last_used_index>=0 && !std::strcmp(filename,filenames[last_used_index])) { index = last_used_index; } else cimglist_for(filenames,l) if (filenames[l] && !std::strcmp(filename,filenames[l])) { index = l; break; } } else index = last_used_index; cimg::mutex(9,0); // Release stream if needed. if (!step_frame || (index>=0 && positions[index]>first_frame)) { if (index>=0) { cimg::mutex(9); captures[index]->release(); delete captures[index]; captures[index] = 0; positions[index] = 0; filenames[index].assign(); if (last_used_index==index) last_used_index = -1; index = -1; cimg::mutex(9,0); } else if (filename) cimg::warn(_cimglist_instance "load_video() : File '%s', no opened video stream associated with filename found.", cimglist_instance,filename); else cimg::warn(_cimglist_instance "load_video() : No opened video stream found.", cimglist_instance,filename); if (!step_frame) return *this; } // Find empty slot for capturing video stream. if (index<0) { if (!filename) throw CImgArgumentException(_cimglist_instance "load_video(): No already open video reader found. You must specify a " "non-(null) filename argument for the first call.", cimglist_instance); else { cimg::mutex(9); cimglist_for(filenames,l) if (!filenames[l]) { index = l; break; } cimg::mutex(9,0); } if (index<0) throw CImgIOException(_cimglist_instance "load_video(): File '%s', no video reader slots available. " "You have to release some of your previously opened videos.", cimglist_instance,filename); cimg::mutex(9); captures[index] = new cv::VideoCapture(filename); positions[index] = 0; if (!captures[index]->isOpened()) { delete captures[index]; captures[index] = 0; cimg::mutex(9,0); cimg::fclose(cimg::fopen(filename,"rb")); // Check file availability throw CImgIOException(_cimglist_instance "load_video(): File '%s', unable to detect format of video file.", cimglist_instance,filename); } CImg<charT>::string(filename).move_to(filenames[index]); cimg::mutex(9,0); } cimg::mutex(9); const unsigned int nb_frames = (unsigned int)std::max(0.,captures[index]->get(_cimg_cap_prop_frame_count)); cimg::mutex(9,0); assign(); // Skip frames if requested. bool go_on = true; unsigned int &pos = positions[index]; while (pos<first_frame) { cimg::mutex(9); if (!captures[index]->grab()) { cimg::mutex(9,0); go_on = false; break; } cimg::mutex(9,0); ++pos; } // Read and convert frames. const unsigned int _last_frame = std::min(nb_frames?nb_frames - 1:~0U,last_frame); while (go_on && pos<=_last_frame) { cv::Mat cvimg; cimg::mutex(9); if (captures[index]->read(cvimg)) { CImg<T>::_cvmat2cimg(cvimg).move_to(*this); ++pos; } else go_on = false; cimg::mutex(9,0); if (go_on) for (unsigned int i = 1; go_on && i<step_frame && pos<=_last_frame; ++i, ++pos) { cimg::mutex(9); if (!captures[index]->grab()) go_on = false; cimg::mutex(9,0); } } if (!go_on || (nb_frames && pos>=nb_frames)) { // Close video stream when necessary cimg::mutex(9); captures[index]->release(); delete captures[index]; captures[index] = 0; filenames[index].assign(); positions[index] = 0; index = -1; cimg::mutex(9,0); } cimg::mutex(9); last_used_index = index; cimg::mutex(9,0); if (is_empty()) throw CImgIOException(_cimglist_instance "load_video(): File '%s', unable to locate frame %u.", cimglist_instance,filename,first_frame); return *this; #endif } //! Load an image from a video file, using OpenCV library \newinstance. static CImgList<T> get_load_video(const char *const filename, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1) { return CImgList<T>().load_video(filename,first_frame,last_frame,step_frame); } //! Load an image from a video file using the external tool 'ffmpeg'. /** \param filename Filename to read data from. **/ CImgList<T>& load_ffmpeg_external(const char *const filename) { if (!filename) throw CImgArgumentException(_cimglist_instance "load_ffmpeg_external(): Specified filename is (null).", cimglist_instance); cimg::fclose(cimg::fopen(filename,"rb")); // Check if file exists CImg<charT> command(1024), filename_tmp(256), filename_tmp2(256); std::FILE *file = 0; do { cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); cimg_snprintf(filename_tmp2,filename_tmp2._width,"%s_000001.ppm",filename_tmp._data); if ((file=cimg::std_fopen(filename_tmp2,"rb"))!=0) cimg::fclose(file); } while (file); cimg_snprintf(filename_tmp2,filename_tmp2._width,"%s_%%6d.ppm",filename_tmp._data); cimg_snprintf(command,command._width,"%s -i \"%s\" \"%s\"", cimg::ffmpeg_path(), CImg<charT>::string(filename)._system_strescape().data(), CImg<charT>::string(filename_tmp2)._system_strescape().data()); cimg::system(command,0); const unsigned int omode = cimg::exception_mode(); cimg::exception_mode(0); assign(); unsigned int i = 1; for (bool stop_flag = false; !stop_flag; ++i) { cimg_snprintf(filename_tmp2,filename_tmp2._width,"%s_%.6u.ppm",filename_tmp._data,i); CImg<T> img; try { img.load_pnm(filename_tmp2); } catch (CImgException&) { stop_flag = true; } if (img) { img.move_to(*this); std::remove(filename_tmp2); } } cimg::exception_mode(omode); if (is_empty()) throw CImgIOException(_cimglist_instance "load_ffmpeg_external(): Failed to open file '%s' with external command 'ffmpeg'.", cimglist_instance, filename); return *this; } //! Load an image from a video file using the external tool 'ffmpeg' \newinstance. static CImgList<T> get_load_ffmpeg_external(const char *const filename) { return CImgList<T>().load_ffmpeg_external(filename); } //! Load gif file, using ImageMagick or GraphicsMagick's external tools. /** \param filename Filename to read data from. **/ CImgList<T>& load_gif_external(const char *const filename) { if (!filename) throw CImgArgumentException(_cimglist_instance "load_gif_external(): Specified filename is (null).", cimglist_instance); cimg::fclose(cimg::fopen(filename,"rb")); // Check if file exists if (!_load_gif_external(filename,false)) if (!_load_gif_external(filename,true)) try { assign(CImg<T>().load_other(filename)); } catch (CImgException&) { assign(); } if (is_empty()) throw CImgIOException(_cimglist_instance "load_gif_external(): Failed to open file '%s'.", cimglist_instance,filename); return *this; } CImgList<T>& _load_gif_external(const char *const filename, const bool use_graphicsmagick=false) { CImg<charT> command(1024), filename_tmp(256), filename_tmp2(256); std::FILE *file = 0; do { cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); if (use_graphicsmagick) cimg_snprintf(filename_tmp2,filename_tmp2._width,"%s.png.0",filename_tmp._data); else cimg_snprintf(filename_tmp2,filename_tmp2._width,"%s-0.png",filename_tmp._data); if ((file=cimg::std_fopen(filename_tmp2,"rb"))!=0) cimg::fclose(file); } while (file); if (use_graphicsmagick) cimg_snprintf(command,command._width,"%s convert \"%s\" \"%s.png\"", cimg::graphicsmagick_path(), CImg<charT>::string(filename)._system_strescape().data(), CImg<charT>::string(filename_tmp)._system_strescape().data()); else cimg_snprintf(command,command._width,"%s \"%s\" \"%s.png\"", cimg::imagemagick_path(), CImg<charT>::string(filename)._system_strescape().data(), CImg<charT>::string(filename_tmp)._system_strescape().data()); cimg::system(command,0); const unsigned int omode = cimg::exception_mode(); cimg::exception_mode(0); assign(); // Try to read a single frame gif. cimg_snprintf(filename_tmp2,filename_tmp2._width,"%s.png",filename_tmp._data); CImg<T> img; try { img.load_png(filename_tmp2); } catch (CImgException&) { } if (img) { img.move_to(*this); std::remove(filename_tmp2); } else { // Try to read animated gif unsigned int i = 0; for (bool stop_flag = false; !stop_flag; ++i) { if (use_graphicsmagick) cimg_snprintf(filename_tmp2,filename_tmp2._width,"%s.png.%u",filename_tmp._data,i); else cimg_snprintf(filename_tmp2,filename_tmp2._width,"%s-%u.png",filename_tmp._data,i); try { img.load_png(filename_tmp2); } catch (CImgException&) { stop_flag = true; } if (img) { img.move_to(*this); std::remove(filename_tmp2); } } } cimg::exception_mode(omode); return *this; } //! Load gif file, using ImageMagick or GraphicsMagick's external tools \newinstance. static CImgList<T> get_load_gif_external(const char *const filename) { return CImgList<T>().load_gif_external(filename); } //! Load a gzipped list, using external tool 'gunzip'. /** \param filename Filename to read data from. **/ CImgList<T>& load_gzip_external(const char *const filename) { if (!filename) throw CImgIOException(_cimglist_instance "load_gzip_external(): Specified filename is (null).", cimglist_instance); cimg::fclose(cimg::fopen(filename,"rb")); // Check if file exists CImg<charT> command(1024), filename_tmp(256), body(256); const char *ext = cimg::split_filename(filename,body), *ext2 = cimg::split_filename(body,0); std::FILE *file = 0; do { if (!cimg::strcasecmp(ext,"gz")) { if (*ext2) cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),ext2); else cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); } else { if (*ext) cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),ext); else cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); } if ((file=cimg::std_fopen(filename_tmp,"rb"))!=0) cimg::fclose(file); } while (file); cimg_snprintf(command,command._width,"%s -c \"%s\" > \"%s\"", cimg::gunzip_path(), CImg<charT>::string(filename)._system_strescape().data(), CImg<charT>::string(filename_tmp)._system_strescape().data()); cimg::system(command); if (!(file=cimg::std_fopen(filename_tmp,"rb"))) { cimg::fclose(cimg::fopen(filename,"r")); throw CImgIOException(_cimglist_instance "load_gzip_external(): Failed to open file '%s'.", cimglist_instance, filename); } else cimg::fclose(file); load(filename_tmp); std::remove(filename_tmp); return *this; } //! Load a gzipped list, using external tool 'gunzip' \newinstance. static CImgList<T> get_load_gzip_external(const char *const filename) { return CImgList<T>().load_gzip_external(filename); } //! Load images from a TIFF file. /** \param filename Filename to read data from. \param first_frame Index of first image frame to read. \param last_frame Index of last image frame to read. \param step_frame Step applied between each frame. \param[out] voxel_size Voxel size, as stored in the filename. \param[out] description Description, as stored in the filename. **/ CImgList<T>& load_tiff(const char *const filename, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, float *const voxel_size=0, CImg<charT> *const description=0) { const unsigned int nfirst_frame = first_frame<last_frame?first_frame:last_frame, nstep_frame = step_frame?step_frame:1; unsigned int nlast_frame = first_frame<last_frame?last_frame:first_frame; #ifndef cimg_use_tiff cimg::unused(voxel_size,description); if (nfirst_frame || nlast_frame!=~0U || nstep_frame!=1) throw CImgArgumentException(_cimglist_instance "load_tiff(): Unable to load sub-images from file '%s' unless libtiff is enabled.", cimglist_instance, filename); return assign(CImg<T>::get_load_tiff(filename)); #else #if cimg_verbosity<3 TIFFSetWarningHandler(0); TIFFSetErrorHandler(0); #endif TIFF *tif = TIFFOpen(filename,"r"); if (tif) { unsigned int nb_images = 0; do ++nb_images; while (TIFFReadDirectory(tif)); if (nfirst_frame>=nb_images || (nlast_frame!=~0U && nlast_frame>=nb_images)) cimg::warn(_cimglist_instance "load_tiff(): Invalid specified frame range is [%u,%u] (step %u) since " "file '%s' contains %u image(s).", cimglist_instance, nfirst_frame,nlast_frame,nstep_frame,filename,nb_images); if (nfirst_frame>=nb_images) return assign(); if (nlast_frame>=nb_images) nlast_frame = nb_images - 1; assign(1 + (nlast_frame - nfirst_frame)/nstep_frame); TIFFSetDirectory(tif,0); cimglist_for(*this,l) _data[l]._load_tiff(tif,nfirst_frame + l*nstep_frame,voxel_size,description); TIFFClose(tif); } else throw CImgIOException(_cimglist_instance "load_tiff(): Failed to open file '%s'.", cimglist_instance, filename); return *this; #endif } //! Load a multi-page TIFF file \newinstance. static CImgList<T> get_load_tiff(const char *const filename, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, float *const voxel_size=0, CImg<charT> *const description=0) { return CImgList<T>().load_tiff(filename,first_frame,last_frame,step_frame,voxel_size,description); } //@} //---------------------------------- // //! \name Data Output //@{ //---------------------------------- //! Print information about the list on the standard output. /** \param title Label set to the information displayed. \param display_stats Tells if image statistics must be computed and displayed. **/ const CImgList<T>& print(const char *const title=0, const bool display_stats=true) const { unsigned int msiz = 0; cimglist_for(*this,l) msiz+=_data[l].size(); msiz*=sizeof(T); const unsigned int mdisp = msiz<8*1024?0U:msiz<8*1024*1024?1U:2U; CImg<charT> _title(64); if (!title) cimg_snprintf(_title,_title._width,"CImgList<%s>",pixel_type()); std::fprintf(cimg::output(),"%s%s%s%s: %sthis%s = %p, %ssize%s = %u/%u [%u %s], %sdata%s = (CImg<%s>*)%p", cimg::t_magenta,cimg::t_bold,title?title:_title._data,cimg::t_normal, cimg::t_bold,cimg::t_normal,(void*)this, cimg::t_bold,cimg::t_normal,_width,_allocated_width, mdisp==0?msiz:(mdisp==1?(msiz>>10):(msiz>>20)), mdisp==0?"b":(mdisp==1?"Kio":"Mio"), cimg::t_bold,cimg::t_normal,pixel_type(),(void*)begin()); if (_data) std::fprintf(cimg::output(),"..%p.\n",(void*)((char*)end() - 1)); else std::fprintf(cimg::output(),".\n"); char tmp[16] = { 0 }; cimglist_for(*this,ll) { cimg_snprintf(tmp,sizeof(tmp),"[%d]",ll); std::fprintf(cimg::output()," "); _data[ll].print(tmp,display_stats); if (ll==3 && width()>8) { ll = width() - 5; std::fprintf(cimg::output()," ...\n"); } } std::fflush(cimg::output()); return *this; } //! Display the current CImgList instance in an existing CImgDisplay window (by reference). /** \param disp Reference to an existing CImgDisplay instance, where the current image list will be displayed. \param axis Appending axis. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param align Appending alignmenet. \note This function displays the list images of the current CImgList instance into an existing CImgDisplay window. Images of the list are appended in a single temporarly image for visualization purposes. The function returns immediately. **/ const CImgList<T>& display(CImgDisplay &disp, const char axis='x', const float align=0) const { disp.display(*this,axis,align); return *this; } //! Display the current CImgList instance in a new display window. /** \param disp Display window. \param display_info Tells if image information are displayed on the standard output. \param axis Alignment axis for images viewing. \param align Apending alignment. \param[in,out] XYZ Contains the XYZ coordinates at start / exit of the function. \param exit_on_anykey Exit function when any key is pressed. \note This function opens a new window with a specific title and displays the list images of the current CImgList instance into it. Images of the list are appended in a single temporarly image for visualization purposes. The function returns when a key is pressed or the display window is closed by the user. **/ const CImgList<T>& display(CImgDisplay &disp, const bool display_info, const char axis='x', const float align=0, unsigned int *const XYZ=0, const bool exit_on_anykey=false) const { bool is_exit = false; return _display(disp,0,0,display_info,axis,align,XYZ,exit_on_anykey,0,true,is_exit); } //! Display the current CImgList instance in a new display window. /** \param title Title of the opening display window. \param display_info Tells if list information must be written on standard output. \param axis Appending axis. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param align Appending alignment. \param[in,out] XYZ Contains the XYZ coordinates at start / exit of the function. \param exit_on_anykey Exit function when any key is pressed. **/ const CImgList<T>& display(const char *const title=0, const bool display_info=true, const char axis='x', const float align=0, unsigned int *const XYZ=0, const bool exit_on_anykey=false) const { CImgDisplay disp; bool is_exit = false; return _display(disp,title,0,display_info,axis,align,XYZ,exit_on_anykey,0,true,is_exit); } const CImgList<T>& _display(CImgDisplay &disp, const char *const title, const CImgList<charT> *const titles, const bool display_info, const char axis, const float align, unsigned int *const XYZ, const bool exit_on_anykey, const unsigned int orig, const bool is_first_call, bool &is_exit) const { if (is_empty()) throw CImgInstanceException(_cimglist_instance "display(): Empty instance.", cimglist_instance); if (!disp) { if (axis=='x') { unsigned int sum_width = 0, max_height = 0; cimglist_for(*this,l) { const CImg<T> &img = _data[l]; const unsigned int w = CImgDisplay::_fitscreen(img._width,img._height,img._depth,128,-85,false), h = CImgDisplay::_fitscreen(img._width,img._height,img._depth,128,-85,true); sum_width+=w; if (h>max_height) max_height = h; } disp.assign(cimg_fitscreen(sum_width,max_height,1),title?title:titles?titles->__display()._data:0,1); } else { unsigned int max_width = 0, sum_height = 0; cimglist_for(*this,l) { const CImg<T> &img = _data[l]; const unsigned int w = CImgDisplay::_fitscreen(img._width,img._height,img._depth,128,-85,false), h = CImgDisplay::_fitscreen(img._width,img._height,img._depth,128,-85,true); if (w>max_width) max_width = w; sum_height+=h; } disp.assign(cimg_fitscreen(max_width,sum_height,1),title?title:titles?titles->__display()._data:0,1); } if (!title && !titles) disp.set_title("CImgList<%s> (%u)",pixel_type(),_width); } else if (title) disp.set_title("%s",title); else if (titles) disp.set_title("%s",titles->__display()._data); const CImg<char> dtitle = CImg<char>::string(disp.title()); if (display_info) print(disp.title()); disp.show().flush(); if (_width==1) { const unsigned int dw = disp._width, dh = disp._height; if (!is_first_call) disp.resize(cimg_fitscreen(_data[0]._width,_data[0]._height,_data[0]._depth),false); disp.set_title("%s (%ux%ux%ux%u)", dtitle.data(),_data[0]._width,_data[0]._height,_data[0]._depth,_data[0]._spectrum); _data[0]._display(disp,0,false,XYZ,exit_on_anykey,!is_first_call); if (disp.key()) is_exit = true; disp.resize(cimg_fitscreen(dw,dh,1),false).set_title("%s",dtitle.data()); } else { bool disp_resize = !is_first_call; while (!disp.is_closed() && !is_exit) { const CImg<intT> s = _select(disp,0,true,axis,align,exit_on_anykey,orig,disp_resize,!is_first_call,true); disp_resize = true; if (s[0]<0 && !disp.wheel()) { // No selections done if (disp.button()&2) { disp.flush(); break; } is_exit = true; } else if (disp.wheel()) { // Zoom in/out const int wheel = disp.wheel(); disp.set_wheel(); if (!is_first_call && wheel<0) break; if (wheel>0 && _width>=4) { const unsigned int delta = std::max(1U,(unsigned int)cimg::round(0.3*_width)), ind0 = (unsigned int)std::max(0,s[0] - (int)delta), ind1 = (unsigned int)std::min(width() - 1,s[0] + (int)delta); if ((ind0!=0 || ind1!=_width - 1) && ind1 - ind0>=3) { const CImgList<T> sublist = get_shared_images(ind0,ind1); CImgList<charT> t_sublist; if (titles) t_sublist = titles->get_shared_images(ind0,ind1); sublist._display(disp,0,titles?&t_sublist:0,false,axis,align,XYZ,exit_on_anykey, orig + ind0,false,is_exit); } } } else if (s[0]!=0 || s[1]!=width() - 1) { const CImgList<T> sublist = get_shared_images(s[0],s[1]); CImgList<charT> t_sublist; if (titles) t_sublist = titles->get_shared_images(s[0],s[1]); sublist._display(disp,0,titles?&t_sublist:0,false,axis,align,XYZ,exit_on_anykey, orig + s[0],false,is_exit); } disp.set_title("%s",dtitle.data()); } } return *this; } // [internal] Return string to describe display title. CImg<charT> __display() const { CImg<charT> res, str; cimglist_for(*this,l) { CImg<charT>::string((char*)_data[l]).move_to(str); if (l!=width() - 1) { str.resize(str._width + 1,1,1,1,0); str[str._width - 2] = ','; str[str._width - 1] = ' '; } res.append(str,'x'); } if (!res) return CImg<charT>(1,1,1,1,0).move_to(res); cimg::strellipsize(res,128,false); if (_width>1) { const unsigned int l = (unsigned int)std::strlen(res); if (res._width<=l + 16) res.resize(l + 16,1,1,1,0); cimg_snprintf(res._data + l,16," (#%u)",_width); } return res; } //! Save list into a file. /** \param filename Filename to write data to. \param number When positive, represents an index added to the filename. Otherwise, no number is added. \param digits Number of digits used for adding the number to the filename. **/ const CImgList<T>& save(const char *const filename, const int number=-1, const unsigned int digits=6) const { if (!filename) throw CImgArgumentException(_cimglist_instance "save(): Specified filename is (null).", cimglist_instance); // Do not test for empty instances, since .cimg format is able to manage empty instances. const bool is_stdout = *filename=='-' && (!filename[1] || filename[1]=='.'); const char *const ext = cimg::split_filename(filename); CImg<charT> nfilename(1024); const char *const fn = is_stdout?filename:number>=0?cimg::number_filename(filename,number,digits,nfilename): filename; #ifdef cimglist_save_plugin cimglist_save_plugin(fn); #endif #ifdef cimglist_save_plugin1 cimglist_save_plugin1(fn); #endif #ifdef cimglist_save_plugin2 cimglist_save_plugin2(fn); #endif #ifdef cimglist_save_plugin3 cimglist_save_plugin3(fn); #endif #ifdef cimglist_save_plugin4 cimglist_save_plugin4(fn); #endif #ifdef cimglist_save_plugin5 cimglist_save_plugin5(fn); #endif #ifdef cimglist_save_plugin6 cimglist_save_plugin6(fn); #endif #ifdef cimglist_save_plugin7 cimglist_save_plugin7(fn); #endif #ifdef cimglist_save_plugin8 cimglist_save_plugin8(fn); #endif if (!cimg::strcasecmp(ext,"cimgz")) return save_cimg(fn,true); else if (!cimg::strcasecmp(ext,"cimg") || !*ext) return save_cimg(fn,false); else if (!cimg::strcasecmp(ext,"yuv")) return save_yuv(fn,444,true); else if (!cimg::strcasecmp(ext,"avi") || !cimg::strcasecmp(ext,"mov") || !cimg::strcasecmp(ext,"asf") || !cimg::strcasecmp(ext,"divx") || !cimg::strcasecmp(ext,"flv") || !cimg::strcasecmp(ext,"mpg") || !cimg::strcasecmp(ext,"m1v") || !cimg::strcasecmp(ext,"m2v") || !cimg::strcasecmp(ext,"m4v") || !cimg::strcasecmp(ext,"mjp") || !cimg::strcasecmp(ext,"mp4") || !cimg::strcasecmp(ext,"mkv") || !cimg::strcasecmp(ext,"mpe") || !cimg::strcasecmp(ext,"movie") || !cimg::strcasecmp(ext,"ogm") || !cimg::strcasecmp(ext,"ogg") || !cimg::strcasecmp(ext,"ogv") || !cimg::strcasecmp(ext,"qt") || !cimg::strcasecmp(ext,"rm") || !cimg::strcasecmp(ext,"vob") || !cimg::strcasecmp(ext,"wmv") || !cimg::strcasecmp(ext,"xvid") || !cimg::strcasecmp(ext,"mpeg")) return save_video(fn); #ifdef cimg_use_tiff else if (!cimg::strcasecmp(ext,"tif") || !cimg::strcasecmp(ext,"tiff")) return save_tiff(fn); #endif else if (!cimg::strcasecmp(ext,"gz")) return save_gzip_external(fn); else { if (_width==1) _data[0].save(fn,-1); else cimglist_for(*this,l) { _data[l].save(fn,is_stdout?-1:l); if (is_stdout) std::fputc(EOF,cimg::_stdout()); } } return *this; } //! Tell if an image list can be saved as one single file. /** \param filename Filename, as a C-string. \return \c true if the file format supports multiple images, \c false otherwise. **/ static bool is_saveable(const char *const filename) { const char *const ext = cimg::split_filename(filename); if (!cimg::strcasecmp(ext,"cimgz") || #ifdef cimg_use_tiff !cimg::strcasecmp(ext,"tif") || !cimg::strcasecmp(ext,"tiff") || #endif !cimg::strcasecmp(ext,"yuv") || !cimg::strcasecmp(ext,"avi") || !cimg::strcasecmp(ext,"mov") || !cimg::strcasecmp(ext,"asf") || !cimg::strcasecmp(ext,"divx") || !cimg::strcasecmp(ext,"flv") || !cimg::strcasecmp(ext,"mpg") || !cimg::strcasecmp(ext,"m1v") || !cimg::strcasecmp(ext,"m2v") || !cimg::strcasecmp(ext,"m4v") || !cimg::strcasecmp(ext,"mjp") || !cimg::strcasecmp(ext,"mp4") || !cimg::strcasecmp(ext,"mkv") || !cimg::strcasecmp(ext,"mpe") || !cimg::strcasecmp(ext,"movie") || !cimg::strcasecmp(ext,"ogm") || !cimg::strcasecmp(ext,"ogg") || !cimg::strcasecmp(ext,"ogv") || !cimg::strcasecmp(ext,"qt") || !cimg::strcasecmp(ext,"rm") || !cimg::strcasecmp(ext,"vob") || !cimg::strcasecmp(ext,"wmv") || !cimg::strcasecmp(ext,"xvid") || !cimg::strcasecmp(ext,"mpeg")) return true; return false; } //! Save image sequence as a GIF animated file. /** \param filename Filename to write data to. \param fps Number of desired frames per second. \param nb_loops Number of loops (\c 0 for infinite looping). **/ const CImgList<T>& save_gif_external(const char *const filename, const float fps=25, const unsigned int nb_loops=0) { CImg<charT> command(1024), filename_tmp(256), filename_tmp2(256); CImgList<charT> filenames; std::FILE *file = 0; #ifdef cimg_use_png #define _cimg_save_gif_ext "png" #else #define _cimg_save_gif_ext "ppm" #endif do { cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); cimg_snprintf(filename_tmp2,filename_tmp2._width,"%s_000001." _cimg_save_gif_ext,filename_tmp._data); if ((file=cimg::std_fopen(filename_tmp2,"rb"))!=0) cimg::fclose(file); } while (file); cimglist_for(*this,l) { cimg_snprintf(filename_tmp2,filename_tmp2._width,"%s_%.6u." _cimg_save_gif_ext,filename_tmp._data,l + 1); CImg<charT>::string(filename_tmp2).move_to(filenames); if (_data[l]._depth>1 || _data[l]._spectrum!=3) _data[l].get_resize(-100,-100,1,3).save(filename_tmp2); else _data[l].save(filename_tmp2); } cimg_snprintf(command,command._width,"%s -delay %u -loop %u", cimg::imagemagick_path(),(unsigned int)std::max(0.f,cimg::round(100/fps)),nb_loops); CImg<ucharT>::string(command).move_to(filenames,0); cimg_snprintf(command,command._width,"\"%s\"", CImg<charT>::string(filename)._system_strescape().data()); CImg<ucharT>::string(command).move_to(filenames); CImg<charT> _command = filenames>'x'; cimg_for(_command,p,char) if (!*p) *p = ' '; _command.back() = 0; cimg::system(_command); file = cimg::std_fopen(filename,"rb"); if (!file) throw CImgIOException(_cimglist_instance "save_gif_external(): Failed to save file '%s' with external command 'magick/convert'.", cimglist_instance, filename); else cimg::fclose(file); cimglist_for_in(*this,1,filenames._width - 1,l) std::remove(filenames[l]); return *this; } //! Save list as a YUV image sequence file. /** \param filename Filename to write data to. \param chroma_subsampling Type of chroma subsampling. Can be <tt>{ 420 | 422 | 444 }</tt>. \param is_rgb Tells if the RGB to YUV conversion must be done for saving. **/ const CImgList<T>& save_yuv(const char *const filename=0, const unsigned int chroma_subsampling=444, const bool is_rgb=true) const { return _save_yuv(0,filename,chroma_subsampling,is_rgb); } //! Save image sequence into a YUV file. /** \param file File to write data to. \param chroma_subsampling Type of chroma subsampling. Can be <tt>{ 420 | 422 | 444 }</tt>. \param is_rgb Tells if the RGB to YUV conversion must be done for saving. **/ const CImgList<T>& save_yuv(std::FILE *const file, const unsigned int chroma_subsampling=444, const bool is_rgb=true) const { return _save_yuv(file,0,chroma_subsampling,is_rgb); } const CImgList<T>& _save_yuv(std::FILE *const file, const char *const filename, const unsigned int chroma_subsampling, const bool is_rgb) const { if (!file && !filename) throw CImgArgumentException(_cimglist_instance "save_yuv(): Specified filename is (null).", cimglist_instance); if (chroma_subsampling!=420 && chroma_subsampling!=422 && chroma_subsampling!=444) throw CImgArgumentException(_cimglist_instance "save_yuv(): Specified chroma subsampling %u is invalid, for file '%s'.", cimglist_instance, chroma_subsampling,filename?filename:"(FILE*)"); if (is_empty()) { cimg::fempty(file,filename); return *this; } const unsigned int cfx = chroma_subsampling==420 || chroma_subsampling==422?2:1, cfy = chroma_subsampling==420?2:1, w0 = (*this)[0]._width, h0 = (*this)[0]._height, width0 = w0 + (w0%cfx), height0 = h0 + (h0%cfy); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); cimglist_for(*this,l) { const CImg<T> &frame = (*this)[l]; cimg_forZ(frame,z) { CImg<ucharT> YUV; if (sizeof(T)==1 && !is_rgb && frame._width==width0 && frame._height==height0 && frame._depth==1 && frame._spectrum==3) YUV.assign((unsigned char*)frame._data,width0,height0,1,3,true); else { YUV = frame.get_slice(z); if (YUV._width!=width0 || YUV._height!=height0) YUV.resize(width0,height0,1,-100,0); if (YUV._spectrum!=3) YUV.resize(-100,-100,1,3,YUV._spectrum==1?1:0); if (is_rgb) YUV.RGBtoYCbCr(); } if (chroma_subsampling==444) cimg::fwrite(YUV._data,(size_t)YUV._width*YUV._height*3,nfile); else { cimg::fwrite(YUV._data,(size_t)YUV._width*YUV._height,nfile); CImg<ucharT> UV = YUV.get_channels(1,2); UV.resize(UV._width/cfx,UV._height/cfy,1,2,2); cimg::fwrite(UV._data,(size_t)UV._width*UV._height*2,nfile); } } } if (!file) cimg::fclose(nfile); return *this; } //! Save list into a .cimg file. /** \param filename Filename to write data to. \param is_compressed Tells if data compression must be enabled. **/ const CImgList<T>& save_cimg(const char *const filename, const bool is_compressed=false) const { return _save_cimg(0,filename,is_compressed); } const CImgList<T>& _save_cimg(std::FILE *const file, const char *const filename, const bool is_compressed) const { if (!file && !filename) throw CImgArgumentException(_cimglist_instance "save_cimg(): Specified filename is (null).", cimglist_instance); #ifndef cimg_use_zlib if (is_compressed) cimg::warn(_cimglist_instance "save_cimg(): Unable to save compressed data in file '%s' unless zlib is enabled, " "saving them uncompressed.", cimglist_instance, filename?filename:"(FILE*)"); #endif std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); const char *const ptype = pixel_type(), *const etype = cimg::endianness()?"big":"little"; if (std::strstr(ptype,"unsigned")==ptype) std::fprintf(nfile,"%u unsigned_%s %s_endian\n",_width,ptype + 9,etype); else std::fprintf(nfile,"%u %s %s_endian\n",_width,ptype,etype); cimglist_for(*this,l) { const CImg<T>& img = _data[l]; std::fprintf(nfile,"%u %u %u %u",img._width,img._height,img._depth,img._spectrum); if (img._data) { CImg<T> tmp; if (cimg::endianness()) { tmp = img; cimg::invert_endianness(tmp._data,tmp.size()); } const CImg<T>& ref = cimg::endianness()?tmp:img; bool failed_to_compress = true; if (is_compressed) { #ifdef cimg_use_zlib const ulongT siz = sizeof(T)*ref.size(); uLongf csiz = siz + siz/100 + 16; Bytef *const cbuf = new Bytef[csiz]; if (compress(cbuf,&csiz,(Bytef*)ref._data,siz)) cimg::warn(_cimglist_instance "save_cimg(): Failed to save compressed data for file '%s', saving them uncompressed.", cimglist_instance, filename?filename:"(FILE*)"); else { std::fprintf(nfile," #%lu\n",csiz); cimg::fwrite(cbuf,csiz,nfile); delete[] cbuf; failed_to_compress = false; } #endif } if (failed_to_compress) { // Write in a non-compressed way std::fputc('\n',nfile); cimg::fwrite(ref._data,ref.size(),nfile); } } else std::fputc('\n',nfile); } if (!file) cimg::fclose(nfile); return *this; } //! Save list into a .cimg file. /** \param file File to write data to. \param is_compressed Tells if data compression must be enabled. **/ const CImgList<T>& save_cimg(std::FILE *file, const bool is_compressed=false) const { return _save_cimg(file,0,is_compressed); } const CImgList<T>& _save_cimg(std::FILE *const file, const char *const filename, const unsigned int n0, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0) const { #define _cimg_save_cimg_case(Ts,Tss) \ if (!saved && !cimg::strcasecmp(Ts,str_pixeltype)) { \ for (unsigned int l = 0; l<lmax; ++l) { \ j = 0; while ((i=std::fgetc(nfile))!='\n') tmp[j++]=(char)i; tmp[j] = 0; \ W = H = D = C = 0; \ if (cimg_sscanf(tmp,"%u %u %u %u",&W,&H,&D,&C)!=4) \ throw CImgIOException(_cimglist_instance \ "save_cimg(): Invalid size (%u,%u,%u,%u) of image[%u], for file '%s'.", \ cimglist_instance, \ W,H,D,C,l,filename?filename:"(FILE*)"); \ if (W*H*D*C>0) { \ if (l<n0 || x0>=W || y0>=H || z0>=D || c0>=D) cimg::fseek(nfile,W*H*D*C*sizeof(Tss),SEEK_CUR); \ else { \ const CImg<T>& img = (*this)[l - n0]; \ const T *ptrs = img._data; \ const unsigned int \ x1 = x0 + img._width - 1, \ y1 = y0 + img._height - 1, \ z1 = z0 + img._depth - 1, \ c1 = c0 + img._spectrum - 1, \ nx1 = x1>=W?W - 1:x1, \ ny1 = y1>=H?H - 1:y1, \ nz1 = z1>=D?D - 1:z1, \ nc1 = c1>=C?C - 1:c1; \ CImg<Tss> raw(1 + nx1 - x0); \ const unsigned int skipvb = c0*W*H*D*sizeof(Tss); \ if (skipvb) cimg::fseek(nfile,skipvb,SEEK_CUR); \ for (unsigned int v = 1 + nc1 - c0; v; --v) { \ const unsigned int skipzb = z0*W*H*sizeof(Tss); \ if (skipzb) cimg::fseek(nfile,skipzb,SEEK_CUR); \ for (unsigned int z = 1 + nz1 - z0; z; --z) { \ const unsigned int skipyb = y0*W*sizeof(Tss); \ if (skipyb) cimg::fseek(nfile,skipyb,SEEK_CUR); \ for (unsigned int y = 1 + ny1 - y0; y; --y) { \ const unsigned int skipxb = x0*sizeof(Tss); \ if (skipxb) cimg::fseek(nfile,skipxb,SEEK_CUR); \ raw.assign(ptrs, raw._width); \ ptrs+=img._width; \ if (endian) cimg::invert_endianness(raw._data,raw._width); \ cimg::fwrite(raw._data,raw._width,nfile); \ const unsigned int skipxe = (W - 1 - nx1)*sizeof(Tss); \ if (skipxe) cimg::fseek(nfile,skipxe,SEEK_CUR); \ } \ const unsigned int skipye = (H - 1 - ny1)*W*sizeof(Tss); \ if (skipye) cimg::fseek(nfile,skipye,SEEK_CUR); \ } \ const unsigned int skipze = (D - 1 - nz1)*W*H*sizeof(Tss); \ if (skipze) cimg::fseek(nfile,skipze,SEEK_CUR); \ } \ const unsigned int skipve = (C - 1 - nc1)*W*H*D*sizeof(Tss); \ if (skipve) cimg::fseek(nfile,skipve,SEEK_CUR); \ } \ } \ } \ saved = true; \ } if (!file && !filename) throw CImgArgumentException(_cimglist_instance "save_cimg(): Specified filename is (null).", cimglist_instance); if (is_empty()) throw CImgInstanceException(_cimglist_instance "save_cimg(): Empty instance, for file '%s'.", cimglist_instance, filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb+"); bool saved = false, endian = cimg::endianness(); CImg<charT> tmp(256), str_pixeltype(256), str_endian(256); *tmp = *str_pixeltype = *str_endian = 0; unsigned int j, N, W, H, D, C; int i, err; j = 0; while ((i=std::fgetc(nfile))!='\n' && i!=EOF && j<256) tmp[j++] = (char)i; tmp[j] = 0; err = cimg_sscanf(tmp,"%u%*c%255[A-Za-z64_]%*c%255[sA-Za-z_ ]",&N,str_pixeltype._data,str_endian._data); if (err<2) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimglist_instance "save_cimg(): CImg header not found in file '%s'.", cimglist_instance, filename?filename:"(FILE*)"); } if (!cimg::strncasecmp("little",str_endian,6)) endian = false; else if (!cimg::strncasecmp("big",str_endian,3)) endian = true; const unsigned int lmax = std::min(N,n0 + _width); _cimg_save_cimg_case("bool",bool); _cimg_save_cimg_case("unsigned_char",unsigned char); _cimg_save_cimg_case("uchar",unsigned char); _cimg_save_cimg_case("char",char); _cimg_save_cimg_case("unsigned_short",unsigned short); _cimg_save_cimg_case("ushort",unsigned short); _cimg_save_cimg_case("short",short); _cimg_save_cimg_case("unsigned_int",unsigned int); _cimg_save_cimg_case("uint",unsigned int); _cimg_save_cimg_case("int",int); _cimg_save_cimg_case("unsigned_int64",uint64T); _cimg_save_cimg_case("uint64",uint64T); _cimg_save_cimg_case("int64",int64T); _cimg_save_cimg_case("float",float); _cimg_save_cimg_case("double",double); if (!saved) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimglist_instance "save_cimg(): Unsupported data type '%s' for file '%s'.", cimglist_instance, filename?filename:"(FILE*)",str_pixeltype._data); } if (!file) cimg::fclose(nfile); return *this; } //! Insert the image instance into into an existing .cimg file, at specified coordinates. /** \param filename Filename to write data to. \param n0 Starting index of images to write. \param x0 Starting X-coordinates of image regions to write. \param y0 Starting Y-coordinates of image regions to write. \param z0 Starting Z-coordinates of image regions to write. \param c0 Starting C-coordinates of image regions to write. **/ const CImgList<T>& save_cimg(const char *const filename, const unsigned int n0, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0) const { return _save_cimg(0,filename,n0,x0,y0,z0,c0); } //! Insert the image instance into into an existing .cimg file, at specified coordinates. /** \param file File to write data to. \param n0 Starting index of images to write. \param x0 Starting X-coordinates of image regions to write. \param y0 Starting Y-coordinates of image regions to write. \param z0 Starting Z-coordinates of image regions to write. \param c0 Starting C-coordinates of image regions to write. **/ const CImgList<T>& save_cimg(std::FILE *const file, const unsigned int n0, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0) const { return _save_cimg(file,0,n0,x0,y0,z0,c0); } static void _save_empty_cimg(std::FILE *const file, const char *const filename, const unsigned int nb, const unsigned int dx, const unsigned int dy, const unsigned int dz, const unsigned int dc) { std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); const ulongT siz = (ulongT)dx*dy*dz*dc*sizeof(T); std::fprintf(nfile,"%u %s\n",nb,pixel_type()); for (unsigned int i=nb; i; --i) { std::fprintf(nfile,"%u %u %u %u\n",dx,dy,dz,dc); for (ulongT off = siz; off; --off) std::fputc(0,nfile); } if (!file) cimg::fclose(nfile); } //! Save empty (non-compressed) .cimg file with specified dimensions. /** \param filename Filename to write data to. \param nb Number of images to write. \param dx Width of images in the written file. \param dy Height of images in the written file. \param dz Depth of images in the written file. \param dc Spectrum of images in the written file. **/ static void save_empty_cimg(const char *const filename, const unsigned int nb, const unsigned int dx, const unsigned int dy=1, const unsigned int dz=1, const unsigned int dc=1) { return _save_empty_cimg(0,filename,nb,dx,dy,dz,dc); } //! Save empty .cimg file with specified dimensions. /** \param file File to write data to. \param nb Number of images to write. \param dx Width of images in the written file. \param dy Height of images in the written file. \param dz Depth of images in the written file. \param dc Spectrum of images in the written file. **/ static void save_empty_cimg(std::FILE *const file, const unsigned int nb, const unsigned int dx, const unsigned int dy=1, const unsigned int dz=1, const unsigned int dc=1) { return _save_empty_cimg(file,0,nb,dx,dy,dz,dc); } //! Save list as a TIFF file. /** \param filename Filename to write data to. \param compression_type Compression mode used to write data. \param voxel_size Voxel size, to be stored in the filename. \param description Description, to be stored in the filename. \param use_bigtiff Allow to save big tiff files (>4Gb). **/ const CImgList<T>& save_tiff(const char *const filename, const unsigned int compression_type=0, const float *const voxel_size=0, const char *const description=0, const bool use_bigtiff=true) const { if (!filename) throw CImgArgumentException(_cimglist_instance "save_tiff(): Specified filename is (null).", cimglist_instance); if (is_empty()) { cimg::fempty(0,filename); return *this; } #ifndef cimg_use_tiff if (_width==1) _data[0].save_tiff(filename,compression_type,voxel_size,description,use_bigtiff); else cimglist_for(*this,l) { CImg<charT> nfilename(1024); cimg::number_filename(filename,l,6,nfilename); _data[l].save_tiff(nfilename,compression_type,voxel_size,description,use_bigtiff); } #else ulongT siz = 0; cimglist_for(*this,l) siz+=_data[l].size(); const bool _use_bigtiff = use_bigtiff && sizeof(siz)>=8 && siz*sizeof(T)>=1UL<<31; // No bigtiff for small images TIFF *tif = TIFFOpen(filename,_use_bigtiff?"w8":"w4"); if (tif) { for (unsigned int dir = 0, l = 0; l<_width; ++l) { const CImg<T>& img = (*this)[l]; cimg_forZ(img,z) img._save_tiff(tif,dir++,z,compression_type,voxel_size,description); } TIFFClose(tif); } else throw CImgIOException(_cimglist_instance "save_tiff(): Failed to open stream for file '%s'.", cimglist_instance, filename); #endif return *this; } //! Save list as a gzipped file, using external tool 'gzip'. /** \param filename Filename to write data to. **/ const CImgList<T>& save_gzip_external(const char *const filename) const { if (!filename) throw CImgIOException(_cimglist_instance "save_gzip_external(): Specified filename is (null).", cimglist_instance); CImg<charT> command(1024), filename_tmp(256), body(256); const char *ext = cimg::split_filename(filename,body), *ext2 = cimg::split_filename(body,0); std::FILE *file; do { if (!cimg::strcasecmp(ext,"gz")) { if (*ext2) cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),ext2); else cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.cimg", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); } else { if (*ext) cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),ext); else cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.cimg", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); } if ((file=cimg::std_fopen(filename_tmp,"rb"))!=0) cimg::fclose(file); } while (file); if (is_saveable(body)) { save(filename_tmp); cimg_snprintf(command,command._width,"%s -c \"%s\" > \"%s\"", cimg::gzip_path(), CImg<charT>::string(filename_tmp)._system_strescape().data(), CImg<charT>::string(filename)._system_strescape().data()); cimg::system(command); file = cimg::std_fopen(filename,"rb"); if (!file) throw CImgIOException(_cimglist_instance "save_gzip_external(): Failed to save file '%s' with external command 'gzip'.", cimglist_instance, filename); else cimg::fclose(file); std::remove(filename_tmp); } else { CImg<charT> nfilename(1024); cimglist_for(*this,l) { cimg::number_filename(body,l,6,nfilename); if (*ext) cimg_sprintf(nfilename._data + std::strlen(nfilename),".%s",ext); _data[l].save_gzip_external(nfilename); } } return *this; } //! Save image sequence, using the OpenCV library. /** \param filename Filename to write data to. \param fps Number of frames per second. \param codec Type of compression (See http://www.fourcc.org/codecs.php to see available codecs). \param keep_open Tells if the video writer associated to the specified filename must be kept open or not (to allow frames to be added in the same file afterwards). **/ const CImgList<T>& save_video(const char *const filename, const unsigned int fps=25, const char *codec=0, const bool keep_open=false) const { #ifndef cimg_use_opencv cimg::unused(codec,keep_open); return save_ffmpeg_external(filename,fps); #else static cv::VideoWriter *writers[32] = { 0 }; static CImgList<charT> filenames(32); static CImg<intT> sizes(32,2,1,1,0); static int last_used_index = -1; // Detect if a video writer already exists for the specified filename. cimg::mutex(9); int index = -1; if (filename) { if (last_used_index>=0 && !std::strcmp(filename,filenames[last_used_index])) { index = last_used_index; } else cimglist_for(filenames,l) if (filenames[l] && !std::strcmp(filename,filenames[l])) { index = l; break; } } else index = last_used_index; cimg::mutex(9,0); // Find empty slot for capturing video stream. if (index<0) { if (!filename) throw CImgArgumentException(_cimglist_instance "save_video(): No already open video writer found. You must specify a " "non-(null) filename argument for the first call.", cimglist_instance); else { cimg::mutex(9); cimglist_for(filenames,l) if (!filenames[l]) { index = l; break; } cimg::mutex(9,0); } if (index<0) throw CImgIOException(_cimglist_instance "save_video(): File '%s', no video writer slots available. " "You have to release some of your previously opened videos.", cimglist_instance,filename); if (is_empty()) throw CImgInstanceException(_cimglist_instance "save_video(): Instance list is empty.", cimglist_instance); const unsigned int W = _data?_data[0]._width:0, H = _data?_data[0]._height:0; if (!W || !H) throw CImgInstanceException(_cimglist_instance "save_video(): Frame [0] is an empty image.", cimglist_instance); const char *const _codec = codec && *codec?codec:cimg_OS==2?"mpeg":"mp4v", codec0 = cimg::uppercase(_codec[0]), codec1 = _codec[0]?cimg::uppercase(_codec[1]):0, codec2 = _codec[1]?cimg::uppercase(_codec[2]):0, codec3 = _codec[2]?cimg::uppercase(_codec[3]):0; cimg::mutex(9); writers[index] = new cv::VideoWriter(filename,_cimg_fourcc(codec0,codec1,codec2,codec3),fps,cv::Size(W,H)); if (!writers[index]->isOpened()) { delete writers[index]; writers[index] = 0; cimg::mutex(9,0); throw CImgIOException(_cimglist_instance "save_video(): File '%s', unable to initialize video writer with codec '%c%c%c%c'.", cimglist_instance,filename, codec0,codec1,codec2,codec3); } CImg<charT>::string(filename).move_to(filenames[index]); sizes(index,0) = W; sizes(index,1) = H; cimg::mutex(9,0); } if (!is_empty()) { const unsigned int W = sizes(index,0), H = sizes(index,1); cimg::mutex(9); cimglist_for(*this,l) { CImg<T> &src = _data[l]; if (src.is_empty()) cimg::warn(_cimglist_instance "save_video(): Skip empty frame %d for file '%s'.", cimglist_instance,l,filename); if (src._depth>1 || src._spectrum>3) cimg::warn(_cimglist_instance "save_video(): Frame %u has incompatible dimension (%u,%u,%u,%u). " "Some image data may be ignored when writing frame into video file '%s'.", cimglist_instance,l,src._width,src._height,src._depth,src._spectrum,filename); if (src._width==W && src._height==H && src._spectrum==3) writers[index]->write(CImg<ucharT>(src)._cimg2cvmat()); else { CImg<ucharT> _src(src,false); _src.channels(0,std::min(_src._spectrum - 1,2U)).resize(W,H); _src.resize(W,H,1,3,_src._spectrum==1); writers[index]->write(_src._cimg2cvmat()); } } cimg::mutex(9,0); } cimg::mutex(9); if (!keep_open) { delete writers[index]; writers[index] = 0; filenames[index].assign(); sizes(index,0) = sizes(index,1) = 0; last_used_index = -1; } else last_used_index = index; cimg::mutex(9,0); return *this; #endif } //! Save image sequence, using the external tool 'ffmpeg'. /** \param filename Filename to write data to. \param fps Number of frames per second. \param codec Type of compression. \param bitrate Output bitrate **/ const CImgList<T>& save_ffmpeg_external(const char *const filename, const unsigned int fps=25, const char *const codec=0, const unsigned int bitrate=2048) const { if (!filename) throw CImgArgumentException(_cimglist_instance "save_ffmpeg_external(): Specified filename is (null).", cimglist_instance); if (is_empty()) { cimg::fempty(0,filename); return *this; } const char *const ext = cimg::split_filename(filename), *const _codec = codec?codec:!cimg::strcasecmp(ext,"flv")?"flv":"mpeg2video"; CImg<charT> command(1024), filename_tmp(256), filename_tmp2(256); CImgList<charT> filenames; std::FILE *file = 0; cimglist_for(*this,l) if (!_data[l].is_sameXYZ(_data[0])) throw CImgInstanceException(_cimglist_instance "save_ffmpeg_external(): Invalid instance dimensions for file '%s'.", cimglist_instance, filename); do { cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); cimg_snprintf(filename_tmp2,filename_tmp2._width,"%s_000001.ppm",filename_tmp._data); if ((file=cimg::std_fopen(filename_tmp2,"rb"))!=0) cimg::fclose(file); } while (file); cimglist_for(*this,l) { cimg_snprintf(filename_tmp2,filename_tmp2._width,"%s_%.6u.ppm",filename_tmp._data,l + 1); CImg<charT>::string(filename_tmp2).move_to(filenames); if (_data[l]._depth>1 || _data[l]._spectrum!=3) _data[l].get_resize(-100,-100,1,3).save_pnm(filename_tmp2); else _data[l].save_pnm(filename_tmp2); } cimg_snprintf(command,command._width,"%s -i \"%s_%%6d.ppm\" -vcodec %s -b %uk -r %u -y \"%s\"", cimg::ffmpeg_path(), CImg<charT>::string(filename_tmp)._system_strescape().data(), _codec,bitrate,fps, CImg<charT>::string(filename)._system_strescape().data()); cimg::system(command); file = cimg::std_fopen(filename,"rb"); if (!file) throw CImgIOException(_cimglist_instance "save_ffmpeg_external(): Failed to save file '%s' with external command 'ffmpeg'.", cimglist_instance, filename); else cimg::fclose(file); cimglist_for(*this,l) std::remove(filenames[l]); return *this; } //! Serialize a CImgList<T> instance into a raw CImg<unsigned char> buffer. /** \param is_compressed tells if zlib compression must be used for serialization (this requires 'cimg_use_zlib' been enabled). **/ CImg<ucharT> get_serialize(const bool is_compressed=false) const { #ifndef cimg_use_zlib if (is_compressed) cimg::warn(_cimglist_instance "get_serialize(): Unable to compress data unless zlib is enabled, " "storing them uncompressed.", cimglist_instance); #endif CImgList<ucharT> stream; CImg<charT> tmpstr(128); const char *const ptype = pixel_type(), *const etype = cimg::endianness()?"big":"little"; if (std::strstr(ptype,"unsigned")==ptype) cimg_snprintf(tmpstr,tmpstr._width,"%u unsigned_%s %s_endian\n",_width,ptype + 9,etype); else cimg_snprintf(tmpstr,tmpstr._width,"%u %s %s_endian\n",_width,ptype,etype); CImg<ucharT>::string(tmpstr,false).move_to(stream); cimglist_for(*this,l) { const CImg<T>& img = _data[l]; cimg_snprintf(tmpstr,tmpstr._width,"%u %u %u %u",img._width,img._height,img._depth,img._spectrum); CImg<ucharT>::string(tmpstr,false).move_to(stream); if (img._data) { CImg<T> tmp; if (cimg::endianness()) { tmp = img; cimg::invert_endianness(tmp._data,tmp.size()); } const CImg<T>& ref = cimg::endianness()?tmp:img; bool failed_to_compress = true; if (is_compressed) { #ifdef cimg_use_zlib const ulongT siz = sizeof(T)*ref.size(); uLongf csiz = (ulongT)compressBound(siz); Bytef *const cbuf = new Bytef[csiz]; if (compress(cbuf,&csiz,(Bytef*)ref._data,siz)) cimg::warn(_cimglist_instance "get_serialize(): Failed to save compressed data, saving them uncompressed.", cimglist_instance); else { cimg_snprintf(tmpstr,tmpstr._width," #%lu\n",csiz); CImg<ucharT>::string(tmpstr,false).move_to(stream); CImg<ucharT>(cbuf,csiz).move_to(stream); delete[] cbuf; failed_to_compress = false; } #endif } if (failed_to_compress) { // Write in a non-compressed way CImg<charT>::string("\n",false).move_to(stream); stream.insert(1); stream.back().assign((unsigned char*)ref._data,ref.size()*sizeof(T),1,1,1,true); } } else CImg<charT>::string("\n",false).move_to(stream); } cimglist_apply(stream,unroll)('y'); return stream>'y'; } //! Unserialize a CImg<unsigned char> serialized buffer into a CImgList<T> list. template<typename t> static CImgList<T> get_unserialize(const CImg<t>& buffer) { #ifdef cimg_use_zlib #define _cimgz_unserialize_case(Tss) { \ Bytef *cbuf = 0; \ if (sizeof(t)!=1 || cimg::type<t>::string()==cimg::type<bool>::string()) { \ cbuf = new Bytef[csiz]; Bytef *_cbuf = cbuf; \ for (ulongT k = 0; k<csiz; ++k) *(_cbuf++) = (Bytef)*(stream++); \ is_bytef = false; \ } else { cbuf = (Bytef*)stream; stream+=csiz; is_bytef = true; } \ raw.assign(W,H,D,C); \ uLongf destlen = raw.size()*sizeof(Tss); \ uncompress((Bytef*)raw._data,&destlen,cbuf,csiz); \ if (!is_bytef) delete[] cbuf; \ } #else #define _cimgz_unserialize_case(Tss) \ throw CImgArgumentException("CImgList<%s>::get_unserialize(): Unable to unserialize compressed data " \ "unless zlib is enabled.", \ pixel_type()); #endif #define _cimg_unserialize_case(Ts,Tss) \ if (!loaded && !cimg::strcasecmp(Ts,str_pixeltype)) { \ for (unsigned int l = 0; l<N; ++l) { \ j = 0; while ((i=(int)*stream)!='\n' && stream<estream && j<255) { ++stream; tmp[j++] = (char)i; } \ ++stream; tmp[j] = 0; \ W = H = D = C = 0; csiz = 0; \ if ((err = cimg_sscanf(tmp,"%u %u %u %u #" cimg_fuint64,&W,&H,&D,&C,&csiz))<4) \ throw CImgArgumentException("CImgList<%s>::unserialize(): Invalid specified size (%u,%u,%u,%u) for " \ "image #%u in serialized buffer.", \ pixel_type(),W,H,D,C,l); \ if (W*H*D*C>0) { \ CImg<Tss> raw; \ CImg<T> &img = res._data[l]; \ if (err==5) _cimgz_unserialize_case(Tss) \ else if (sizeof(Tss)==sizeof(t) && cimg::type<Tss>::is_float()==cimg::type<t>::is_float()) { \ raw.assign((Tss*)stream,W,H,D,C,true); \ stream+=raw.size(); \ } else { \ raw.assign(W,H,D,C); \ CImg<ucharT> _raw((unsigned char*)raw._data,W*sizeof(Tss),H,D,C,true); \ cimg_for(_raw,p,unsigned char) *p = (unsigned char)*(stream++); \ } \ if (endian!=cimg::endianness()) cimg::invert_endianness(raw._data,raw.size()); \ raw.move_to(img); \ } \ } \ loaded = true; \ } if (buffer.is_empty()) throw CImgArgumentException("CImgList<%s>::get_unserialize(): Specified serialized buffer is (null).", pixel_type()); CImgList<T> res; const t *stream = buffer._data, *const estream = buffer._data + buffer.size(); bool loaded = false, endian = cimg::endianness(), is_bytef = false; CImg<charT> tmp(256), str_pixeltype(256), str_endian(256); *tmp = *str_pixeltype = *str_endian = 0; unsigned int j, N = 0, W, H, D, C; uint64T csiz; int i, err; cimg::unused(is_bytef); do { j = 0; while ((i=(int)*stream)!='\n' && stream<estream && j<255) { ++stream; tmp[j++] = (char)i; } ++stream; tmp[j] = 0; } while (*tmp=='#' && stream<estream); err = cimg_sscanf(tmp,"%u%*c%255[A-Za-z64_]%*c%255[sA-Za-z_ ]", &N,str_pixeltype._data,str_endian._data); if (err<2) throw CImgArgumentException("CImgList<%s>::get_unserialize(): CImg header not found in serialized buffer.", pixel_type()); if (!cimg::strncasecmp("little",str_endian,6)) endian = false; else if (!cimg::strncasecmp("big",str_endian,3)) endian = true; res.assign(N); _cimg_unserialize_case("bool",bool); _cimg_unserialize_case("unsigned_char",unsigned char); _cimg_unserialize_case("uchar",unsigned char); _cimg_unserialize_case("char",char); _cimg_unserialize_case("unsigned_short",unsigned short); _cimg_unserialize_case("ushort",unsigned short); _cimg_unserialize_case("short",short); _cimg_unserialize_case("unsigned_int",unsigned int); _cimg_unserialize_case("uint",unsigned int); _cimg_unserialize_case("int",int); _cimg_unserialize_case("unsigned_int64",uint64T); _cimg_unserialize_case("uint64",uint64T); _cimg_unserialize_case("int64",int64T); _cimg_unserialize_case("float",float); _cimg_unserialize_case("double",double); if (!loaded) throw CImgArgumentException("CImgList<%s>::get_unserialize(): Unsupported pixel type '%s' defined " "in serialized buffer.", pixel_type(),str_pixeltype._data); return res; } //@} //---------------------------------- // //! \name Others //@{ //---------------------------------- //! Return a CImg pre-defined font with requested height. /** \param font_height Height of the desired font (exact match for 13,23,53,103). \param is_variable_width Decide if the font has a variable (\c true) or fixed (\c false) width. **/ static const CImgList<ucharT>& font(const unsigned int requested_height, const bool is_variable_width=true) { if (!requested_height) return CImgList<ucharT>::const_empty(); cimg::mutex(11); static const unsigned char font_resizemap[] = { 0, 4, 7, 9, 11, 13, 15, 17, 19, 21, 22, 24, 26, 27, 29, 30, 32, 33, 35, 36, 38, 39, 41, 42, 43, 45, 46, 47, 49, 50, 51, 52, 54, 55, 56, 58, 59, 60, 61, 62, 64, 65, 66, 67, 68, 69, 71, 72, 73, 74, 75, 76, 77, 78, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 157, 158, 159, 160, 161, 162, 163, 164, 164, 165, 166, 167, 168, 169, 170, 170, 171, 172, 173, 174, 175, 176, 176, 177, 178, 179, 180, 181, 181, 182, 183, 184, 185, 186, 186, 187, 188, 189, 190, 191, 191, 192, 193, 194, 195, 196, 196, 197, 198, 199, 200, 200, 201, 202, 203, 204, 205, 205, 206, 207, 208, 209, 209, 210, 211, 212, 213, 213, 214, 215, 216, 216, 217, 218, 219, 220, 220, 221, 222, 223, 224, 224, 225, 226, 227, 227, 228, 229, 230, 231, 231, 232, 233, 234, 234, 235, 236, 237, 238, 238, 239, 240, 241, 241, 242, 243, 244, 244, 245, 246, 247, 247, 248, 249, 250, 250, 251, 252, 253, 253, 254, 255 }; static const char *const *font_data[] = { cimg::data_font_small, cimg::data_font_normal, cimg::data_font_large, cimg::data_font_huge }; static const unsigned int font_width[] = { 10,26,52,104 }, font_height[] = { 13,32,64,128 }, font_M[] = { 86,91,91,47 }, font_chunk[] = { sizeof(cimg::data_font_small)/sizeof(char*), sizeof(cimg::data_font_normal)/sizeof(char*), sizeof(cimg::data_font_large)/sizeof(char*), sizeof(cimg::data_font_huge)/sizeof(char*) }; static const unsigned char font_is_binary[] = { 1,0,0,1 }; static CImg<ucharT> font_base[4]; unsigned int ind = requested_height<=font_height[0]?0U: requested_height<=font_height[1]?1U: requested_height<=font_height[2]?2U:3U; // Decompress nearest base font data if needed. CImg<ucharT> &basef = font_base[ind]; if (!basef) { basef.assign(256*font_width[ind],font_height[ind]); unsigned char *ptrd = basef; const unsigned char *const ptrde = basef.end(); // Recompose font data from several chunks, to deal with MS compiler limit with big strings (64 Kb). CImg<char> dataf; for (unsigned int k = 0; k<font_chunk[ind]; ++k) dataf.append(CImg<char>::string(font_data[ind][k],k==font_chunk[ind] - 1,true),'x'); // Uncompress font data (decode RLE). const unsigned int M = font_M[ind]; if (font_is_binary[ind]) for (const char *ptrs = dataf; *ptrs; ++ptrs) { const int _n = (int)(*ptrs - M - 32), v = _n>=0?255:0, n = _n>=0?_n:-_n; if (ptrd + n<=ptrde) { std::memset(ptrd,v,n); ptrd+=n; } else { std::memset(ptrd,v,ptrde - ptrd); break; } } else for (const char *ptrs = dataf; *ptrs; ++ptrs) { int n = (int)*ptrs - M - 32, v = 0; if (n>=0) { v = 85*n; n = 1; } else { n = -n; v = (int)*(++ptrs) - M - 32; if (v<0) { v = 0; --ptrs; } else v*=85; } if (ptrd + n<=ptrde) { std::memset(ptrd,v,n); ptrd+=n; } else { std::memset(ptrd,v,ptrde - ptrd); break; } } } // Find optimal font cache location to return. static CImgList<ucharT> fonts[16]; static bool is_variable_widths[16] = { 0 }; ind = ~0U; for (int i = 0; i<16; ++i) if (!fonts[i] || (is_variable_widths[i]==is_variable_width && requested_height==fonts[i][0]._height)) { ind = (unsigned int)i; break; // Found empty slot or cached font } if (ind==~0U) { // No empty slots nor existing font in cache fonts->assign(); std::memmove(fonts,fonts + 1,15*sizeof(CImgList<ucharT>)); std::memmove(is_variable_widths,is_variable_widths + 1,15*sizeof(bool)); std::memset((void*)(fonts + (ind=15)),0,sizeof(CImgList<ucharT>)); // Free a slot in cache for new font } CImgList<ucharT> &font = fonts[ind]; // Render requested font. if (!font) { const unsigned int padding_x = requested_height<=64?1U:requested_height<=128?2U:3U; is_variable_widths[ind] = is_variable_width; font = basef.get_split('x',256); if (requested_height!=font[0]._height) cimglist_for(font,l) { font[l].resize(std::max(1U,font[l]._width*requested_height/font[l]._height),requested_height,-100,-100, font[0]._height>requested_height?2:5); cimg_for(font[l],ptr,ucharT) *ptr = font_resizemap[*ptr]; } if (is_variable_width) { // Crop font cimglist_for(font,l) { CImg<ucharT>& letter = font[l]; int xmin = letter.width(), xmax = 0; cimg_forXY(letter,x,y) if (letter(x,y)) { if (x<xmin) xmin = x; if (x>xmax) xmax = x; } if (xmin<=xmax) letter.crop(xmin,0,xmax,letter._height - 1); } font[(int)' '].resize(font[(int)'f']._width,-100,-100,-100,0); if (' ' + 256<font.size()) font[' ' + 256].resize(font[(int)'f']._width,-100,-100,-100,0); cimglist_for(font,l) font[l].resize(std::max(font[(int)';']._width,font[l]._width) + padding_x, -100,1,1,0,0,0.55f); } else cimglist_for(font,l) font[l].resize(font[l]._width + padding_x,-100,1,1,0,0,0.55f); font.insert(256,0); cimglist_for_in(font,0,255,l) font[l].assign(font[l + 256]._width,font[l + 256]._height,1,3,1); } cimg::mutex(11,0); return font; } //! Compute a 1D Fast Fourier Transform, along specified axis. /** \param axis Axis along which the Fourier transform is computed. \param invert Tells if the direct (\c false) or inverse transform (\c true) is computed. **/ CImgList<T>& FFT(const char axis, const bool invert=false) { if (is_empty()) return *this; if (_width==1) insert(1); if (_width>2) cimg::warn(_cimglist_instance "FFT(): Instance has more than 2 images", cimglist_instance); CImg<T>::FFT(_data[0],_data[1],axis,invert); return *this; } //! Compute a 1-D Fast Fourier Transform, along specified axis \newinstance. CImgList<Tfloat> get_FFT(const char axis, const bool invert=false) const { return CImgList<Tfloat>(*this,false).FFT(axis,invert); } //! Compute n-D Fast Fourier Transform. /** \param invert Tells if the direct (\c false) or inverse transform (\c true) is computed. **/ CImgList<T>& FFT(const bool invert=false) { if (is_empty()) return *this; if (_width==1) insert(1); if (_width>2) cimg::warn(_cimglist_instance "FFT(): Instance has more than 2 images", cimglist_instance); CImg<T>::FFT(_data[0],_data[1],invert); return *this; } //! Compute n-D Fast Fourier Transform \newinstance. CImgList<Tfloat> get_FFT(const bool invert=false) const { return CImgList<Tfloat>(*this,false).FFT(invert); } //! Reverse primitives orientations of a 3D object. /** **/ CImgList<T>& reverse_object3d() { cimglist_for(*this,l) { CImg<T>& p = _data[l]; switch (p.size()) { case 2 : case 3: cimg::swap(p[0],p[1]); break; case 6 : cimg::swap(p[0],p[1],p[2],p[4],p[3],p[5]); break; case 9 : cimg::swap(p[0],p[1],p[3],p[5],p[4],p[6]); break; case 4 : cimg::swap(p[0],p[1],p[2],p[3]); break; case 12 : cimg::swap(p[0],p[1],p[2],p[3],p[4],p[6],p[5],p[7],p[8],p[10],p[9],p[11]); break; } } return *this; } //! Reverse primitives orientations of a 3D object \newinstance. CImgList<T> get_reverse_object3d() const { return (+*this).reverse_object3d(); } //@} }; // struct CImgList { ... // Completion of previously declared functions //-------------------------------------------- namespace cimg { // Functions to return standard streams 'stdin', 'stdout' and 'stderr'. // (throw a CImgIOException when macro 'cimg_use_r' is defined). inline FILE* _stdin(const bool throw_exception) { #ifndef cimg_use_r cimg::unused(throw_exception); return stdin; #else if (throw_exception) { cimg::exception_mode(0); throw CImgIOException("cimg::stdin(): Reference to 'stdin' stream not allowed in R mode " "('cimg_use_r' is defined)."); } return 0; #endif } inline FILE* _stdout(const bool throw_exception) { #ifndef cimg_use_r cimg::unused(throw_exception); return stdout; #else if (throw_exception) { cimg::exception_mode(0); throw CImgIOException("cimg::stdout(): Reference to 'stdout' stream not allowed in R mode " "('cimg_use_r' is defined)."); } return 0; #endif } inline FILE* _stderr(const bool throw_exception) { #ifndef cimg_use_r cimg::unused(throw_exception); return stderr; #else if (throw_exception) { cimg::exception_mode(0); throw CImgIOException("cimg::stderr(): Reference to 'stderr' stream not allowed in R mode " "('cimg_use_r' is defined)."); } return 0; #endif } // Open a file (similar to std:: fopen(), but with wide character support on Windows). inline std::FILE *std_fopen(const char *const path, const char *const mode) { std::FILE *const res = std::fopen(path,mode); if (res) return res; #if cimg_OS==2 // Try alternative method, with wide-character string. int err = MultiByteToWideChar(CP_UTF8,0,path,-1,0,0); if (err) { CImg<wchar_t> wpath(err); err = MultiByteToWideChar(CP_UTF8,0,path,-1,wpath,err); if (err) { // Convert 'mode' to a wide-character string err = MultiByteToWideChar(CP_UTF8,0,mode,-1,0,0); if (err) { CImg<wchar_t> wmode(err); if (MultiByteToWideChar(CP_UTF8,0,mode,-1,wmode,err)) return _wfopen(wpath,wmode); } } } #endif return 0; } //! Get/set path to store temporary files. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path where temporary files can be saved. **/ inline const char* temporary_path(const char *const user_path, const bool reinit_path) { #define _cimg_test_temporary_path(p) \ if (!path_found) { \ cimg_snprintf(s_path,s_path.width(),"%s",p); \ cimg_snprintf(tmp,tmp._width,"%s%c%s",s_path.data(),cimg_file_separator,filename_tmp._data); \ if ((file=cimg::std_fopen(tmp,"wb"))!=0) { cimg::fclose(file); std::remove(tmp); path_found = true; } \ } static CImg<char> s_path; cimg::mutex(7); if (reinit_path) s_path.assign(); if (user_path) { if (!s_path) s_path.assign(1024); std::strncpy(s_path,user_path,1023); } else if (!s_path) { s_path.assign(1024); bool path_found = false; CImg<char> tmp(1024), filename_tmp(256); std::FILE *file = 0; cimg_snprintf(filename_tmp,filename_tmp._width,"%s.tmp",cimg::filenamerand()); char *tmpPath = std::getenv("TMP"); if (!tmpPath) { tmpPath = std::getenv("TEMP"); winformat_string(tmpPath); } if (tmpPath) _cimg_test_temporary_path(tmpPath); #if cimg_OS==2 _cimg_test_temporary_path("C:\\WINNT\\Temp"); _cimg_test_temporary_path("C:\\WINDOWS\\Temp"); _cimg_test_temporary_path("C:\\Temp"); _cimg_test_temporary_path("C:"); _cimg_test_temporary_path("D:\\WINNT\\Temp"); _cimg_test_temporary_path("D:\\WINDOWS\\Temp"); _cimg_test_temporary_path("D:\\Temp"); _cimg_test_temporary_path("D:"); #else _cimg_test_temporary_path("/tmp"); _cimg_test_temporary_path("/var/tmp"); #endif if (!path_found) { *s_path = 0; std::strncpy(tmp,filename_tmp,tmp._width - 1); if ((file=cimg::std_fopen(tmp,"wb"))!=0) { cimg::fclose(file); std::remove(tmp); path_found = true; } } if (!path_found) { cimg::mutex(7,0); throw CImgIOException("cimg::temporary_path(): Failed to locate path for writing temporary files.\n"); } } cimg::mutex(7,0); return s_path; } //! Get/set path to the <i>Program Files/</i> directory (Windows only). /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the program files. **/ #if cimg_OS==2 inline const char* programfiles_path(const char *const user_path, const bool reinit_path) { static CImg<char> s_path; cimg::mutex(7); if (reinit_path) s_path.assign(); if (user_path) { if (!s_path) s_path.assign(1024); std::strncpy(s_path,user_path,1023); } else if (!s_path) { s_path.assign(MAX_PATH); *s_path = 0; // Note: in the following line, 0x26 = CSIDL_PROGRAM_FILES (not defined on every compiler). #if !defined(__INTEL_COMPILER) if (!SHGetSpecialFolderPathA(0,s_path,0x0026,false)) { const char *const pfPath = std::getenv("PROGRAMFILES"); if (pfPath) std::strncpy(s_path,pfPath,MAX_PATH - 1); else std::strcpy(s_path,"C:\\PROGRA~1"); } #else std::strcpy(s_path,"C:\\PROGRA~1"); #endif } cimg::mutex(7,0); return s_path; } #endif //! Get/set path to the ImageMagick's \c convert binary. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the \c convert binary. **/ inline const char* imagemagick_path(const char *const user_path, const bool reinit_path) { static CImg<char> s_path; cimg::mutex(7); if (reinit_path) s_path.assign(); if (user_path) { if (!s_path) s_path.assign(1024); std::strncpy(s_path,user_path,1023); } else if (!s_path) { s_path.assign(1024); bool path_found = false; std::FILE *file = 0; #if cimg_OS==2 const char *const pf_path = programfiles_path(); for (int l = 0; l<2 && !path_found; ++l) { const char *const s_exe = l?"convert":"magick"; cimg_snprintf(s_path,s_path._width,".\\%s.exe",s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"%s\\IMAGEM~1.%.2d-\\%s.exe",pf_path,k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"%s\\IMAGEM~1.%d-Q\\%s.exe",pf_path,k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"%s\\IMAGEM~1.%d\\%s.exe",pf_path,k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"%s\\IMAGEM~1.%.2d-\\VISUA~1\\BIN\\%s.exe",pf_path,k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"%s\\IMAGEM~1.%d-Q\\VISUA~1\\BIN\\%s.exe",pf_path,k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"%s\\IMAGEM~1.%d\\VISUA~1\\BIN\\%s.exe",pf_path,k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"C:\\IMAGEM~1.%.2d-\\%s.exe",k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"C:\\IMAGEM~1.%d-Q\\%s.exe",k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"C:\\IMAGEM~1.%d\\%s.exe",k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"C:\\IMAGEM~1.%.2d-\\VISUA~1\\BIN\\%s.exe",k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"C:\\IMAGEM~1.%d-Q\\VISUA~1\\BIN\\%s.exe",k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"C:\\IMAGEM~1.%d\\VISUA~1\\BIN\\%s.exe",k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"D:\\IMAGEM~1.%.2d-\\%s.exe",k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"D:\\IMAGEM~1.%d-Q\\%s.exe",k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"D:\\IMAGEM~1.%d\\%s.exe",k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"D:\\IMAGEM~1.%.2d-\\VISUA~1\\BIN\\%s.exe",k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"D:\\IMAGEM~1.%d-Q\\VISUA~1\\BIN\\%s.exe",k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"D:\\IMAGEM~1.%d\\VISUA~1\\BIN\\%s.exe",k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) cimg_snprintf(s_path,s_path._width,"%s.exe",s_exe); } #else std::strcpy(s_path,"./magick"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } if (!path_found) { std::strcpy(s_path,"./convert"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"convert"); #endif winformat_string(s_path); } cimg::mutex(7,0); return s_path; } //! Get/set path to the GraphicsMagick's \c gm binary. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the \c gm binary. **/ inline const char* graphicsmagick_path(const char *const user_path, const bool reinit_path) { static CImg<char> s_path; cimg::mutex(7); if (reinit_path) s_path.assign(); if (user_path) { if (!s_path) s_path.assign(1024); std::strncpy(s_path,user_path,1023); } else if (!s_path) { s_path.assign(1024); bool path_found = false; std::FILE *file = 0; #if cimg_OS==2 const char *const pf_path = programfiles_path(); if (!path_found) { std::strcpy(s_path,".\\gm.exe"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"%s\\GRAPHI~1.%.2d-\\gm.exe",pf_path,k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"%s\\GRAPHI~1.%d-Q\\gm.exe",pf_path,k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"%s\\GRAPHI~1.%d\\gm.exe",pf_path,k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"%s\\GRAPHI~1.%.2d-\\VISUA~1\\BIN\\gm.exe",pf_path,k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"%s\\GRAPHI~1.%d-Q\\VISUA~1\\BIN\\gm.exe",pf_path,k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"%s\\GRAPHI~1.%d\\VISUA~1\\BIN\\gm.exe",pf_path,k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"C:\\GRAPHI~1.%.2d-\\gm.exe",k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"C:\\GRAPHI~1.%d-Q\\gm.exe",k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"C:\\GRAPHI~1.%d\\gm.exe",k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"C:\\GRAPHI~1.%.2d-\\VISUA~1\\BIN\\gm.exe",k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"C:\\GRAPHI~1.%d-Q\\VISUA~1\\BIN\\gm.exe",k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"C:\\GRAPHI~1.%d\\VISUA~1\\BIN\\gm.exe",k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"D:\\GRAPHI~1.%.2d-\\gm.exe",k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"D:\\GRAPHI~1.%d-Q\\gm.exe",k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"D:\\GRAPHI~1.%d\\gm.exe",k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"D:\\GRAPHI~1.%.2d-\\VISUA~1\\BIN\\gm.exe",k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"D:\\GRAPHI~1.%d-Q\\VISUA~1\\BIN\\gm.exe",k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"D:\\GRAPHI~1.%d\\VISUA~1\\BIN\\gm.exe",k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"gm.exe"); #else if (!path_found) { std::strcpy(s_path,"./gm"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"gm"); #endif winformat_string(s_path); } cimg::mutex(7,0); return s_path; } //! Get/set path to the XMedcon's \c medcon binary. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the \c medcon binary. **/ inline const char* medcon_path(const char *const user_path, const bool reinit_path) { static CImg<char> s_path; cimg::mutex(7); if (reinit_path) s_path.assign(); if (user_path) { if (!s_path) s_path.assign(1024); std::strncpy(s_path,user_path,1023); } else if (!s_path) { s_path.assign(1024); bool path_found = false; std::FILE *file = 0; #if cimg_OS==2 const char *const pf_path = programfiles_path(); if (!path_found) { std::strcpy(s_path,".\\medcon.exe"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) { cimg_snprintf(s_path,s_path._width,"%s\\XMedCon\\bin\\medcon.bat",pf_path); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) { cimg_snprintf(s_path,s_path._width,"%s\\XMedCon\\bin\\medcon.exe",pf_path); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) { std::strcpy(s_path,"C:\\XMedCon\\bin\\medcon.exe"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"medcon.exe"); #else if (!path_found) { std::strcpy(s_path,"./medcon"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"medcon"); #endif winformat_string(s_path); } cimg::mutex(7,0); return s_path; } //! Get/set path to the FFMPEG's \c ffmpeg binary. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the \c ffmpeg binary. **/ inline const char *ffmpeg_path(const char *const user_path, const bool reinit_path) { static CImg<char> s_path; cimg::mutex(7); if (reinit_path) s_path.assign(); if (user_path) { if (!s_path) s_path.assign(1024); std::strncpy(s_path,user_path,1023); } else if (!s_path) { s_path.assign(1024); bool path_found = false; std::FILE *file = 0; #if cimg_OS==2 if (!path_found) { std::strcpy(s_path,".\\ffmpeg.exe"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"ffmpeg.exe"); #else if (!path_found) { std::strcpy(s_path,"./ffmpeg"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"ffmpeg"); #endif winformat_string(s_path); } cimg::mutex(7,0); return s_path; } //! Get/set path to the \c gzip binary. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the \c gzip binary. **/ inline const char *gzip_path(const char *const user_path, const bool reinit_path) { static CImg<char> s_path; cimg::mutex(7); if (reinit_path) s_path.assign(); if (user_path) { if (!s_path) s_path.assign(1024); std::strncpy(s_path,user_path,1023); } else if (!s_path) { s_path.assign(1024); bool path_found = false; std::FILE *file = 0; #if cimg_OS==2 if (!path_found) { std::strcpy(s_path,".\\gzip.exe"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"gzip.exe"); #else if (!path_found) { std::strcpy(s_path,"./gzip"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"gzip"); #endif winformat_string(s_path); } cimg::mutex(7,0); return s_path; } //! Get/set path to the \c gunzip binary. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the \c gunzip binary. **/ inline const char *gunzip_path(const char *const user_path, const bool reinit_path) { static CImg<char> s_path; cimg::mutex(7); if (reinit_path) s_path.assign(); if (user_path) { if (!s_path) s_path.assign(1024); std::strncpy(s_path,user_path,1023); } else if (!s_path) { s_path.assign(1024); bool path_found = false; std::FILE *file = 0; #if cimg_OS==2 if (!path_found) { std::strcpy(s_path,".\\gunzip.exe"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"gunzip.exe"); #else if (!path_found) { std::strcpy(s_path,"./gunzip"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"gunzip"); #endif winformat_string(s_path); } cimg::mutex(7,0); return s_path; } //! Get/set path to the \c dcraw binary. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the \c dcraw binary. **/ inline const char *dcraw_path(const char *const user_path, const bool reinit_path) { static CImg<char> s_path; cimg::mutex(7); if (reinit_path) s_path.assign(); if (user_path) { if (!s_path) s_path.assign(1024); std::strncpy(s_path,user_path,1023); } else if (!s_path) { s_path.assign(1024); bool path_found = false; std::FILE *file = 0; #if cimg_OS==2 if (!path_found) { std::strcpy(s_path,".\\dcraw.exe"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"dcraw.exe"); #else if (!path_found) { std::strcpy(s_path,"./dcraw"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"dcraw"); #endif winformat_string(s_path); } cimg::mutex(7,0); return s_path; } //! Get/set path to the \c wget binary. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the \c wget binary. **/ inline const char *wget_path(const char *const user_path, const bool reinit_path) { static CImg<char> s_path; cimg::mutex(7); if (reinit_path) s_path.assign(); if (user_path) { if (!s_path) s_path.assign(1024); std::strncpy(s_path,user_path,1023); } else if (!s_path) { s_path.assign(1024); bool path_found = false; std::FILE *file = 0; #if cimg_OS==2 if (!path_found) { std::strcpy(s_path,".\\wget.exe"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"wget.exe"); #else if (!path_found) { std::strcpy(s_path,"./wget"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"wget"); #endif winformat_string(s_path); } cimg::mutex(7,0); return s_path; } //! Get/set path to the \c curl binary. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the \c curl binary. **/ inline const char *curl_path(const char *const user_path, const bool reinit_path) { static CImg<char> s_path; cimg::mutex(7); if (reinit_path) s_path.assign(); if (user_path) { if (!s_path) s_path.assign(1024); std::strncpy(s_path,user_path,1023); } else if (!s_path) { s_path.assign(1024); bool path_found = false; std::FILE *file = 0; #if cimg_OS==2 if (!path_found) { std::strcpy(s_path,".\\curl.exe"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"curl.exe"); #else if (!path_found) { std::strcpy(s_path,"./curl"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"curl"); #endif winformat_string(s_path); } cimg::mutex(7,0); return s_path; } // [internal] Sorting function, used by cimg::files(). inline int _sort_files(const void* a, const void* b) { const CImg<char> &sa = *(CImg<char>*)a, &sb = *(CImg<char>*)b; return std::strcmp(sa._data,sb._data); } //! Return list of files/directories in specified directory. /** \param path Path to the directory. Set to 0 for current directory. \param is_pattern Tell if specified path has a matching pattern in it. \param mode Output type, can be primary { 0=files only | 1=folders only | 2=files + folders }. \param include_path Tell if \c path must be included in resulting filenames. \return A list of filenames. **/ inline CImgList<char> files(const char *const path, const bool is_pattern=false, const unsigned int mode=2, const bool include_path=false) { if (!path || !*path) return files("*",true,mode,include_path); CImgList<char> res; // If path is a valid folder name, ignore argument 'is_pattern'. const bool _is_pattern = is_pattern && !cimg::is_directory(path); bool is_root = false, is_current = false; cimg::unused(is_root,is_current); // Clean format of input path. CImg<char> pattern, _path = CImg<char>::string(path); #if cimg_OS==2 for (char *ps = _path; *ps; ++ps) if (*ps=='\\') *ps='/'; #endif char *pd = _path; for (char *ps = pd; *ps; ++ps) { if (*ps!='/' || *ps!=*(ps+1)) *(pd++) = *ps; } *pd = 0; unsigned int lp = (unsigned int)std::strlen(_path); if (!_is_pattern && lp && _path[lp - 1]=='/') { _path[lp - 1] = 0; --lp; #if cimg_OS!=2 is_root = !*_path; #endif } // Separate folder path and matching pattern. if (_is_pattern) { const unsigned int bpos = (unsigned int)(cimg::basename(_path,'/') - _path.data()); CImg<char>::string(_path).move_to(pattern); if (bpos) { _path[bpos - 1] = 0; // End 'path' at last slash #if cimg_OS!=2 is_root = !*_path; #endif } else { // No path to folder specified, assuming current folder is_current = true; *_path = 0; } lp = (unsigned int)std::strlen(_path); } // Windows version. #if cimg_OS==2 if (!_is_pattern) { pattern.assign(lp + 3); std::memcpy(pattern,_path,lp); pattern[lp] = '/'; pattern[lp + 1] = '*'; pattern[lp + 2] = 0; } WIN32_FIND_DATAA file_data; const HANDLE dir = FindFirstFileA(pattern.data(),&file_data); if (dir==INVALID_HANDLE_VALUE) return CImgList<char>::const_empty(); do { const char *const filename = file_data.cFileName; if (*filename!='.' || (filename[1] && (filename[1]!='.' || filename[2]))) { const unsigned int lf = (unsigned int)std::strlen(filename); const bool is_directory = (file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)!=0; if ((!mode && !is_directory) || (mode==1 && is_directory) || mode>=2) { if (include_path) { CImg<char> full_filename((lp?lp+1:0) + lf + 1); if (lp) { std::memcpy(full_filename,_path,lp); full_filename[lp] = '/'; } std::memcpy(full_filename._data + (lp?lp + 1:0),filename,lf + 1); full_filename.move_to(res); } else CImg<char>(filename,lf + 1).move_to(res); } } } while (FindNextFileA(dir,&file_data)); FindClose(dir); // Unix version (posix). #elif cimg_OS == 1 DIR *const dir = opendir(is_root?"/":is_current?".":_path.data()); if (!dir) return CImgList<char>::const_empty(); struct dirent *ent; while ((ent=readdir(dir))!=0) { const char *const filename = ent->d_name; if (*filename!='.' || (filename[1] && (filename[1]!='.' || filename[2]))) { const unsigned int lf = (unsigned int)std::strlen(filename); CImg<char> full_filename(lp + lf + 2); if (!is_current) { full_filename.assign(lp + lf + 2); if (lp) std::memcpy(full_filename,_path,lp); full_filename[lp] = '/'; std::memcpy(full_filename._data + lp + 1,filename,lf + 1); } else full_filename.assign(filename,lf + 1); struct stat st; if (stat(full_filename,&st)==-1) continue; const bool is_directory = (st.st_mode & S_IFDIR)!=0; if ((!mode && !is_directory) || (mode==1 && is_directory) || mode==2) { if (include_path) { if (!_is_pattern || (_is_pattern && !fnmatch(pattern,full_filename,0))) full_filename.move_to(res); } else { if (!_is_pattern || (_is_pattern && !fnmatch(pattern,full_filename,0))) CImg<char>(filename,lf + 1).move_to(res); } } } } closedir(dir); #endif // Sort resulting list by lexicographic order. if (res._width>=2) std::qsort(res._data,res._width,sizeof(CImg<char>),_sort_files); return res; } //! Try to guess format from an image file. /** \param file Input file (can be \c 0 if \c filename is set). \param filename Filename, as a C-string (can be \c 0 if \c file is set). \return C-string containing the guessed file format, or \c 0 if nothing has been guessed. **/ inline const char *ftype(std::FILE *const file, const char *const filename) { if (!file && !filename) throw CImgArgumentException("cimg::ftype(): Specified filename is (null)."); static const char *const _pnm = "pnm", *const _pfm = "pfm", *const _bmp = "bmp", *const _gif = "gif", *const _jpg = "jpg", *const _off = "off", *const _pan = "pan", *const _png = "png", *const _tif = "tif", *const _inr = "inr", *const _dcm = "dcm"; const char *f_type = 0; CImg<char> header; const unsigned int omode = cimg::exception_mode(); cimg::exception_mode(0); try { header._load_raw(file,filename,512,1,1,1,false,false,0); const unsigned char *const uheader = (unsigned char*)header._data; if (!std::strncmp(header,"OFF\n",4)) f_type = _off; // OFF else if (!std::strncmp(header,"#INRIMAGE",9)) // INRIMAGE f_type = _inr; else if (!std::strncmp(header,"PANDORE",7)) // PANDORE f_type = _pan; else if (!std::strncmp(header.data() + 128,"DICM",4)) // DICOM f_type = _dcm; else if (uheader[0]==0xFF && uheader[1]==0xD8 && uheader[2]==0xFF) // JPEG f_type = _jpg; else if (header[0]=='B' && header[1]=='M') // BMP f_type = _bmp; else if (header[0]=='G' && header[1]=='I' && header[2]=='F' && header[3]=='8' && header[5]=='a' && (header[4]=='7' || header[4]=='9')) // GIF f_type = _gif; else if (uheader[0]==0x89 && uheader[1]==0x50 && uheader[2]==0x4E && uheader[3]==0x47 && uheader[4]==0x0D && uheader[5]==0x0A && uheader[6]==0x1A && uheader[7]==0x0A) // PNG f_type = _png; else if ((uheader[0]==0x49 && uheader[1]==0x49) || (uheader[0]==0x4D && uheader[1]==0x4D)) // TIFF f_type = _tif; else { // PNM or PFM CImgList<char> _header = header.get_split(CImg<char>::vector('\n'),0,false); cimglist_for(_header,l) { if (_header(l,0)=='#') continue; if (_header[l]._height==2 && _header(l,0)=='P') { const char c = _header(l,1); if (c=='f' || c=='F') { f_type = _pfm; break; } if (c>='1' && c<='9') { f_type = _pnm; break; } } f_type = 0; break; } } } catch (CImgIOException&) { } cimg::exception_mode(omode); return f_type; } //! Load file from network as a local temporary file. /** \param url URL of the filename, as a C-string. \param[out] filename_local C-string containing the path to a local copy of \c filename. \param timeout Maximum time (in seconds) authorized for downloading the file from the URL. \param try_fallback When using libcurl, tells using system calls as fallbacks in case of libcurl failure. \param referer Referer used, as a C-string. \return Value of \c filename_local. \note Use the \c libcurl library, or the external binaries \c wget or \c curl to perform the download. **/ inline char *load_network(const char *const url, char *const filename_local, const unsigned int timeout, const bool try_fallback, const char *const referer) { if (!url) throw CImgArgumentException("cimg::load_network(): Specified URL is (null)."); if (!filename_local) throw CImgArgumentException("cimg::load_network(): Specified destination string is (null)."); const char *const __ext = cimg::split_filename(url), *const _ext = (*__ext && __ext>url)?__ext - 1:__ext; CImg<char> ext = CImg<char>::string(_ext); std::FILE *file = 0; *filename_local = 0; if (ext._width>16 || !cimg::strncasecmp(ext,"cgi",3)) *ext = 0; else cimg::strwindows_reserved(ext); do { cimg_snprintf(filename_local,256,"%s%c%s%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),ext._data); if ((file=cimg::std_fopen(filename_local,"rb"))!=0) cimg::fclose(file); } while (file); #ifdef cimg_use_curl const unsigned int omode = cimg::exception_mode(); cimg::exception_mode(0); try { CURL *curl = 0; CURLcode res; curl = curl_easy_init(); if (curl) { file = cimg::fopen(filename_local,"wb"); curl_easy_setopt(curl,CURLOPT_URL,url); curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,0); curl_easy_setopt(curl,CURLOPT_WRITEDATA,file); curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,0L); curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,0L); curl_easy_setopt(curl,CURLOPT_FOLLOWLOCATION,1L); if (timeout) curl_easy_setopt(curl,CURLOPT_TIMEOUT,(long)timeout); if (std::strchr(url,'?')) curl_easy_setopt(curl,CURLOPT_HTTPGET,1L); if (referer) curl_easy_setopt(curl,CURLOPT_REFERER,referer); res = curl_easy_perform(curl); curl_easy_cleanup(curl); cimg::fseek(file,0,SEEK_END); // Check if file size is 0 const cimg_ulong siz = cimg::ftell(file); cimg::fclose(file); if (siz>0 && res==CURLE_OK) { cimg::exception_mode(omode); return filename_local; } else std::remove(filename_local); } } catch (...) { } cimg::exception_mode(omode); if (!try_fallback) throw CImgIOException("cimg::load_network(): Failed to load file '%s' with libcurl.",url); #endif CImg<char> command((unsigned int)std::strlen(url) + 64); cimg::unused(try_fallback); // Try with 'curl' first. if (timeout) { if (referer) cimg_snprintf(command,command._width,"%s -e %s -m %u -f --silent --compressed -o \"%s\" \"%s\"", cimg::curl_path(),referer,timeout,filename_local, CImg<char>::string(url)._system_strescape().data()); else cimg_snprintf(command,command._width,"%s -m %u -f --silent --compressed -o \"%s\" \"%s\"", cimg::curl_path(),timeout,filename_local, CImg<char>::string(url)._system_strescape().data()); } else { if (referer) cimg_snprintf(command,command._width,"%s -e %s -f --silent --compressed -o \"%s\" \"%s\"", cimg::curl_path(),referer,filename_local, CImg<char>::string(url)._system_strescape().data()); else cimg_snprintf(command,command._width,"%s -f --silent --compressed -o \"%s\" \"%s\"", cimg::curl_path(),filename_local, CImg<char>::string(url)._system_strescape().data()); } cimg::system(command); if (!(file=cimg::std_fopen(filename_local,"rb"))) { // Try with 'wget' otherwise. if (timeout) { if (referer) cimg_snprintf(command,command._width,"%s --referer=%s -T %u -q -r -l 0 --no-cache -O \"%s\" \"%s\"", cimg::wget_path(),referer,timeout,filename_local, CImg<char>::string(url)._system_strescape().data()); else cimg_snprintf(command,command._width,"%s -T %u -q -r -l 0 --no-cache -O \"%s\" \"%s\"", cimg::wget_path(),timeout,filename_local, CImg<char>::string(url)._system_strescape().data()); } else { if (referer) cimg_snprintf(command,command._width,"%s --referer=%s -q -r -l 0 --no-cache -O \"%s\" \"%s\"", cimg::wget_path(),referer,filename_local, CImg<char>::string(url)._system_strescape().data()); else cimg_snprintf(command,command._width,"%s -q -r -l 0 --no-cache -O \"%s\" \"%s\"", cimg::wget_path(),filename_local, CImg<char>::string(url)._system_strescape().data()); } cimg::system(command); if (!(file=cimg::std_fopen(filename_local,"rb"))) throw CImgIOException("cimg::load_network(): Failed to load file '%s' with external commands " "'wget' or 'curl'.",url); cimg::fclose(file); // Try gunzip it. cimg_snprintf(command,command._width,"%s.gz",filename_local); std::rename(filename_local,command); cimg_snprintf(command,command._width,"%s --quiet \"%s.gz\"", gunzip_path(),filename_local); cimg::system(command); file = cimg::std_fopen(filename_local,"rb"); if (!file) { cimg_snprintf(command,command._width,"%s.gz",filename_local); std::rename(command,filename_local); file = cimg::std_fopen(filename_local,"rb"); } } cimg::fseek(file,0,SEEK_END); // Check if file size is 0 if (std::ftell(file)<=0) throw CImgIOException("cimg::load_network(): Failed to load URL '%s' with external commands " "'wget' or 'curl'.",url); cimg::fclose(file); return filename_local; } // Implement a tic/toc mechanism to display elapsed time of algorithms. inline cimg_ulong tictoc(const bool is_tic) { cimg::mutex(2); static CImg<cimg_ulong> times(64); static unsigned int pos = 0; const cimg_ulong t1 = cimg::time(); if (is_tic) { // Tic times[pos++] = t1; if (pos>=times._width) throw CImgArgumentException("cimg::tic(): Too much calls to 'cimg::tic()' without calls to 'cimg::toc()'."); cimg::mutex(2,0); return t1; } // Toc if (!pos) throw CImgArgumentException("cimg::toc(): No previous call to 'cimg::tic()' has been made."); const cimg_ulong t0 = times[--pos], dt = t1>=t0?(t1 - t0):cimg::type<cimg_ulong>::max(); const unsigned int edays = (unsigned int)(dt/86400000.), ehours = (unsigned int)((dt - edays*86400000.)/3600000.), emin = (unsigned int)((dt - edays*86400000. - ehours*3600000.)/60000.), esec = (unsigned int)((dt - edays*86400000. - ehours*3600000. - emin*60000.)/1000.), ems = (unsigned int)(dt - edays*86400000. - ehours*3600000. - emin*60000. - esec*1000.); if (!edays && !ehours && !emin && !esec) std::fprintf(cimg::output(),"%s[CImg]%*sElapsed time: %u ms%s\n", cimg::t_red,1 + 2*pos,"",ems,cimg::t_normal); else { if (!edays && !ehours && !emin) std::fprintf(cimg::output(),"%s[CImg]%*sElapsed time: %u sec %u ms%s\n", cimg::t_red,1 + 2*pos,"",esec,ems,cimg::t_normal); else { if (!edays && !ehours) std::fprintf(cimg::output(),"%s[CImg]%*sElapsed time: %u min %u sec %u ms%s\n", cimg::t_red,1 + 2*pos,"",emin,esec,ems,cimg::t_normal); else{ if (!edays) std::fprintf(cimg::output(),"%s[CImg]%*sElapsed time: %u hours %u min %u sec %u ms%s\n", cimg::t_red,1 + 2*pos,"",ehours,emin,esec,ems,cimg::t_normal); else{ std::fprintf(cimg::output(),"%s[CImg]%*sElapsed time: %u days %u hours %u min %u sec %u ms%s\n", cimg::t_red,1 + 2*pos,"",edays,ehours,emin,esec,ems,cimg::t_normal); } } } } cimg::mutex(2,0); return dt; } // Return a temporary string describing the size of a memory buffer. inline const char *strbuffersize(const cimg_ulong size) { static CImg<char> res(256); cimg::mutex(5); if (size<1024LU) cimg_snprintf(res,res._width,"%lu byte%s",(unsigned long)size,size>1?"s":""); else if (size<1024*1024LU) { const float nsize = size/1024.f; cimg_snprintf(res,res._width,"%.1f Kio",nsize); } else if (size<1024*1024*1024LU) { const float nsize = size/(1024*1024.f); cimg_snprintf(res,res._width,"%.1f Mio",nsize); } else { const float nsize = size/(1024*1024*1024.f); cimg_snprintf(res,res._width,"%.1f Gio",nsize); } cimg::mutex(5,0); return res; } //! Display a simple dialog box, and wait for the user's response. /** \param title Title of the dialog window. \param msg Main message displayed inside the dialog window. \param button1_label Label of the 1st button. \param button2_label Label of the 2nd button (\c 0 to hide button). \param button3_label Label of the 3rd button (\c 0 to hide button). \param button4_label Label of the 4th button (\c 0 to hide button). \param button5_label Label of the 5th button (\c 0 to hide button). \param button6_label Label of the 6th button (\c 0 to hide button). \param logo Image logo displayed at the left of the main message. \param is_centered Tells if the dialog window must be centered on the screen. \return Index of clicked button (from \c 0 to \c 5), or \c -1 if the dialog window has been closed by the user. \note - Up to 6 buttons can be defined in the dialog window. - The function returns when a user clicked one of the button or closed the dialog window. - If a button text is set to 0, the corresponding button (and the followings) will not appear in the dialog box. At least one button must be specified. **/ template<typename t> inline int dialog(const char *const title, const char *const msg, const char *const button1_label, const char *const button2_label, const char *const button3_label, const char *const button4_label, const char *const button5_label, const char *const button6_label, const CImg<t>& logo, const bool is_centered=false) { #if cimg_display==0 cimg::unused(title,msg,button1_label,button2_label,button3_label,button4_label,button5_label,button6_label, logo._data,is_centered); throw CImgIOException("cimg::dialog(): No display available."); #else static const unsigned char black[] = { 0,0,0 }, white[] = { 255,255,255 }, gray[] = { 200,200,200 }, gray2[] = { 150,150,150 }; // Create buttons and canvas graphics CImgList<unsigned char> buttons, cbuttons, sbuttons; if (button1_label) { CImg<unsigned char>().draw_text(0,0,button1_label,black,gray,1,13).move_to(buttons); if (button2_label) { CImg<unsigned char>().draw_text(0,0,button2_label,black,gray,1,13).move_to(buttons); if (button3_label) { CImg<unsigned char>().draw_text(0,0,button3_label,black,gray,1,13).move_to(buttons); if (button4_label) { CImg<unsigned char>().draw_text(0,0,button4_label,black,gray,1,13).move_to(buttons); if (button5_label) { CImg<unsigned char>().draw_text(0,0,button5_label,black,gray,1,13).move_to(buttons); if (button6_label) { CImg<unsigned char>().draw_text(0,0,button6_label,black,gray,1,13).move_to(buttons); }}}}}} if (!buttons._width) throw CImgArgumentException("cimg::dialog(): No buttons have been defined."); cimglist_for(buttons,l) buttons[l].resize(-100,-100,1,3); unsigned int bw = 0, bh = 0; cimglist_for(buttons,l) { bw = std::max(bw,buttons[l]._width); bh = std::max(bh,buttons[l]._height); } bw+=8; bh+=8; if (bw<64) bw = 64; if (bw>128) bw = 128; if (bh<24) bh = 24; if (bh>48) bh = 48; CImg<unsigned char> button(bw,bh,1,3); button.draw_rectangle(0,0,bw - 1,bh - 1,gray); button.draw_line(0,0,bw - 1,0,white).draw_line(0,bh - 1,0,0,white); button.draw_line(bw - 1,0,bw - 1,bh - 1,black).draw_line(bw - 1,bh - 1,0,bh - 1,black); button.draw_line(1,bh - 2,bw - 2,bh - 2,gray2).draw_line(bw - 2,bh - 2,bw - 2,1,gray2); CImg<unsigned char> sbutton(bw,bh,1,3); sbutton.draw_rectangle(0,0,bw - 1,bh - 1,gray); sbutton.draw_line(0,0,bw - 1,0,black).draw_line(bw - 1,0,bw - 1,bh - 1,black); sbutton.draw_line(bw - 1,bh - 1,0,bh - 1,black).draw_line(0,bh - 1,0,0,black); sbutton.draw_line(1,1,bw - 2,1,white).draw_line(1,bh - 2,1,1,white); sbutton.draw_line(bw - 2,1,bw - 2,bh - 2,black).draw_line(bw - 2,bh - 2,1,bh - 2,black); sbutton.draw_line(2,bh - 3,bw - 3,bh - 3,gray2).draw_line(bw - 3,bh - 3,bw - 3,2,gray2); sbutton.draw_line(4,4,bw - 5,4,black,1,0xAAAAAAAA,true). draw_line(bw - 5,4,bw - 5,bh - 5,black,1,0xAAAAAAAA,false); sbutton.draw_line(bw - 5,bh - 5,4,bh - 5,black,1,0xAAAAAAAA,false). draw_line(4,bh - 5,4,4,black,1,0xAAAAAAAA,false); CImg<unsigned char> cbutton(bw,bh,1,3); cbutton.draw_rectangle(0,0,bw - 1,bh - 1,black).draw_rectangle(1,1,bw - 2,bh - 2,gray2). draw_rectangle(2,2,bw - 3,bh - 3,gray); cbutton.draw_line(4,4,bw - 5,4,black,1,0xAAAAAAAA,true). draw_line(bw - 5,4,bw - 5,bh - 5,black,1,0xAAAAAAAA,false); cbutton.draw_line(bw - 5,bh - 5,4,bh - 5,black,1,0xAAAAAAAA,false). draw_line(4,bh - 5,4,4,black,1,0xAAAAAAAA,false); cimglist_for(buttons,ll) { CImg<unsigned char>(cbutton). draw_image(1 + (bw -buttons[ll].width())/2,1 + (bh - buttons[ll].height())/2,buttons[ll]). move_to(cbuttons); CImg<unsigned char>(sbutton). draw_image((bw - buttons[ll].width())/2,(bh - buttons[ll].height())/2,buttons[ll]). move_to(sbuttons); CImg<unsigned char>(button). draw_image((bw - buttons[ll].width())/2,(bh - buttons[ll].height())/2,buttons[ll]). move_to(buttons[ll]); } CImg<unsigned char> canvas; if (msg) ((CImg<unsigned char>().draw_text(0,0,"%s",gray,0,1,13,msg)*=-1)+=200).resize(-100,-100,1,3).move_to(canvas); const unsigned int bwall = (buttons._width - 1)*(12 + bw) + bw, w = cimg::max(196U,36 + logo._width + canvas._width,24 + bwall), h = cimg::max(96U,36 + canvas._height + bh,36 + logo._height + bh), lx = 12 + (canvas._data?0:((w - 24 - logo._width)/2)), ly = (h - 12 - bh - logo._height)/2, tx = lx + logo._width + 12, ty = (h - 12 - bh - canvas._height)/2, bx = (w - bwall)/2, by = h - 12 - bh; if (canvas._data) canvas = CImg<unsigned char>(w,h,1,3). draw_rectangle(0,0,w - 1,h - 1,gray). draw_line(0,0,w - 1,0,white).draw_line(0,h - 1,0,0,white). draw_line(w - 1,0,w - 1,h - 1,black).draw_line(w - 1,h - 1,0,h - 1,black). draw_image(tx,ty,canvas); else canvas = CImg<unsigned char>(w,h,1,3). draw_rectangle(0,0,w - 1,h - 1,gray). draw_line(0,0,w - 1,0,white).draw_line(0,h - 1,0,0,white). draw_line(w - 1,0,w - 1,h - 1,black).draw_line(w - 1,h - 1,0,h - 1,black); if (logo._data) canvas.draw_image(lx,ly,logo); unsigned int xbuttons[6] = { 0 }; cimglist_for(buttons,lll) { xbuttons[lll] = bx + (bw + 12)*lll; canvas.draw_image(xbuttons[lll],by,buttons[lll]); } // Open window and enter events loop CImgDisplay disp(canvas,title?title:" ",0,false,is_centered?true:false); if (is_centered) disp.move((CImgDisplay::screen_width() - disp.width())/2, (CImgDisplay::screen_height() - disp.height())/2); bool stop_flag = false, refresh = false; int oselected = -1, oclicked = -1, selected = -1, clicked = -1; while (!disp.is_closed() && !stop_flag) { if (refresh) { if (clicked>=0) CImg<unsigned char>(canvas).draw_image(xbuttons[clicked],by,cbuttons[clicked]).display(disp); else { if (selected>=0) CImg<unsigned char>(canvas).draw_image(xbuttons[selected],by,sbuttons[selected]).display(disp); else canvas.display(disp); } refresh = false; } disp.wait(15); if (disp.is_resized()) disp.resize(disp,false); if (disp.button()&1) { oclicked = clicked; clicked = -1; cimglist_for(buttons,l) if (disp.mouse_y()>=(int)by && disp.mouse_y()<(int)(by + bh) && disp.mouse_x()>=(int)xbuttons[l] && disp.mouse_x()<(int)(xbuttons[l] + bw)) { clicked = selected = l; refresh = true; } if (clicked!=oclicked) refresh = true; } else if (clicked>=0) stop_flag = true; if (disp.key()) { oselected = selected; switch (disp.key()) { case cimg::keyESC : selected = -1; stop_flag = true; break; case cimg::keyENTER : if (selected<0) selected = 0; stop_flag = true; break; case cimg::keyTAB : case cimg::keyARROWRIGHT : case cimg::keyARROWDOWN : selected = (selected + 1)%buttons.width(); break; case cimg::keyARROWLEFT : case cimg::keyARROWUP : selected = (selected + buttons.width() - 1)%buttons.width(); break; } disp.set_key(); if (selected!=oselected) refresh = true; } } if (!disp) selected = -1; return selected; #endif } //! Display a simple dialog box, and wait for the user's response \specialization. inline int dialog(const char *const title, const char *const msg, const char *const button1_label, const char *const button2_label, const char *const button3_label, const char *const button4_label, const char *const button5_label, const char *const button6_label, const bool is_centered) { return dialog(title,msg,button1_label,button2_label,button3_label,button4_label,button5_label,button6_label, CImg<unsigned char>::_logo40x38(),is_centered); } //! Evaluate math expression. /** \param expression C-string describing the formula to evaluate. \param x Value of the pre-defined variable \c x. \param y Value of the pre-defined variable \c y. \param z Value of the pre-defined variable \c z. \param c Value of the pre-defined variable \c c. \return Result of the formula evaluation. \note Set \c expression to \c 0 to keep evaluating the last specified \c expression. \par Example \code const double res1 = cimg::eval("cos(x)^2 + sin(y)^2",2,2), // will return '1' res2 = cimg::eval(0,1,1); // will return '1' too \endcode **/ inline double eval(const char *const expression, const double x, const double y, const double z, const double c) { static const CImg<float> empty; return empty.eval(expression,x,y,z,c); } template<typename t> inline CImg<typename cimg::superset<double,t>::type> eval(const char *const expression, const CImg<t>& xyzc) { static const CImg<float> empty; return empty.eval(expression,xyzc); } } // namespace cimg { ... } // namespace cimg_library { ... //! Short alias name. namespace cil = cimg_library_suffixed; #ifdef _cimg_redefine_False #define False 0 #endif #ifdef _cimg_redefine_True #define True 1 #endif #ifdef _cimg_redefine_Status #define Status int #endif #ifdef _cimg_redefine_Success #define Success 0 #endif #ifdef _cimg_redefine_min #define min(a,b) (((a)<(b))?(a):(b)) #endif #ifdef _cimg_redefine_max #define max(a,b) (((a)>(b))?(a):(b)) #endif #ifdef _cimg_redefine_PI #define PI 3.141592653589793238462643383 #endif #ifdef _MSC_VER #pragma warning(pop) #endif #endif // Local Variables: // mode: c++ // End:
null
/* # # File : CImg.h # ( C++ header file ) # # Description : The C++ Template Image Processing Toolkit. # This file is the main component of the CImg Library project. # ( http://cimg.eu ) # # Project manager : David Tschumperle. # ( http://tschumperle.users.greyc.fr/ ) # # A complete list of contributors is available in file 'README.txt' # distributed within the CImg package. # # Licenses : This file is 'dual-licensed', you have to choose one # of the two licenses below to apply. # # CeCILL-C # The CeCILL-C license is close to the GNU LGPL. # ( http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.html ) # # or CeCILL v2.1 # The CeCILL license is compatible with the GNU GPL. # ( http://www.cecill.info/licences/Licence_CeCILL_V2.1-en.html ) # # This software is governed either by the CeCILL or the CeCILL-C license # under French law and abiding by the rules of distribution of free software. # You can use, modify and or redistribute the software under the terms of # the CeCILL or CeCILL-C licenses as circulated by CEA, CNRS and INRIA # at the following URL: "http://www.cecill.info". # # As a counterpart to the access to the source code and rights to copy, # modify and redistribute granted by the license, users are provided only # with a limited warranty and the software's author, the holder of the # economic rights, and the successive licensors have only limited # liability. # # In this respect, the user's attention is drawn to the risks associated # with loading, using, modifying and/or developing or reproducing the # software by the user in light of its specific status of free software, # that may mean that it is complicated to manipulate, and that also # therefore means that it is reserved for developers and experienced # professionals having in-depth computer knowledge. Users are therefore # encouraged to load and test the software's suitability as regards their # requirements in conditions enabling the security of their systems and/or # data to be ensured and, more generally, to use and operate it in the # same conditions as regards security. # # The fact that you are presently reading this means that you have had # knowledge of the CeCILL and CeCILL-C licenses and that you accept its terms. # */ // Set version number of the library. #ifndef cimg_version #define cimg_version 270 /*----------------------------------------------------------- # # Test and possibly auto-set CImg configuration variables # and include required headers. # # If you find that the default configuration variables are # not adapted to your system, you can override their values # before including the header file "CImg.h" # (use the #define directive). # ------------------------------------------------------------*/ // Include standard C++ headers. // This is the minimal set of required headers to make CImg-based codes compile. #include <cstdio> #include <cstdlib> #include <cstdarg> #include <cstring> #include <cmath> #include <cfloat> #include <climits> #include <ctime> #include <exception> #include <algorithm> // Detect/configure OS variables. // // Define 'cimg_OS' to: '0' for an unknown OS (will try to minize library dependencies). // '1' for a Unix-like OS (Linux, Solaris, BSD, MacOSX, Irix, ...). // '2' for Microsoft Windows. // (auto-detection is performed if 'cimg_OS' is not set by the user). #ifndef cimg_OS #if defined(unix) || defined(__unix) || defined(__unix__) \ || defined(linux) || defined(__linux) || defined(__linux__) \ || defined(sun) || defined(__sun) \ || defined(BSD) || defined(__OpenBSD__) || defined(__NetBSD__) \ || defined(__FreeBSD__) || defined (__DragonFly__) \ || defined(sgi) || defined(__sgi) \ || defined(__MACOSX__) || defined(__APPLE__) \ || defined(__CYGWIN__) #define cimg_OS 1 #elif defined(_MSC_VER) || defined(WIN32) || defined(_WIN32) || defined(__WIN32__) \ || defined(WIN64) || defined(_WIN64) || defined(__WIN64__) #define cimg_OS 2 #else #define cimg_OS 0 #endif #elif !(cimg_OS==0 || cimg_OS==1 || cimg_OS==2) #error CImg Library: Invalid configuration variable 'cimg_OS'. #error (correct values are '0 = unknown OS', '1 = Unix-like OS', '2 = Microsoft Windows'). #endif #ifndef cimg_date #define cimg_date __DATE__ #endif #ifndef cimg_time #define cimg_time __TIME__ #endif // Disable silly warnings on some Microsoft VC++ compilers. #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4127) #pragma warning(disable:4244) #pragma warning(disable:4311) #pragma warning(disable:4312) #pragma warning(disable:4319) #pragma warning(disable:4512) #pragma warning(disable:4571) #pragma warning(disable:4640) #pragma warning(disable:4706) #pragma warning(disable:4710) #pragma warning(disable:4800) #pragma warning(disable:4804) #pragma warning(disable:4820) #pragma warning(disable:4996) #ifndef _CRT_SECURE_NO_DEPRECATE #define _CRT_SECURE_NO_DEPRECATE 1 #endif #ifndef _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS 1 #endif #ifndef _CRT_NONSTDC_NO_DEPRECATE #define _CRT_NONSTDC_NO_DEPRECATE 1 #endif #endif // Define correct string functions for each compiler and OS. #if cimg_OS==2 && defined(_MSC_VER) #define cimg_sscanf std::sscanf #define cimg_sprintf std::sprintf #define cimg_snprintf cimg::_snprintf #define cimg_vsnprintf cimg::_vsnprintf #else #include <stdio.h> #if defined(__MACOSX__) || defined(__APPLE__) #define cimg_sscanf cimg::_sscanf #define cimg_sprintf cimg::_sprintf #define cimg_snprintf cimg::_snprintf #define cimg_vsnprintf cimg::_vsnprintf #else #define cimg_sscanf std::sscanf #define cimg_sprintf std::sprintf #define cimg_snprintf snprintf #define cimg_vsnprintf vsnprintf #endif #endif // Include OS-specific headers. #if cimg_OS==1 #include <sys/types.h> #include <sys/time.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <fnmatch.h> #elif cimg_OS==2 #ifndef NOMINMAX #define NOMINMAX #endif #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #ifndef _WIN32_IE #define _WIN32_IE 0x0400 #endif #include <shlobj.h> #include <process.h> #include <io.h> #endif // Look for C++11 features. #ifndef cimg_use_cpp11 #if __cplusplus>201100 #define cimg_use_cpp11 1 #else #define cimg_use_cpp11 0 #endif #endif #if cimg_use_cpp11==1 #include <initializer_list> #include <utility> #endif // Convenient macro to define pragma #ifdef _MSC_VER #define cimg_pragma(x) __pragma(x) #else #define cimg_pragma(x) _Pragma(#x) #endif // Define own types 'cimg_long/ulong' and 'cimg_int64/uint64' to ensure portability. // ( constrained to 'sizeof(cimg_ulong/cimg_long) = sizeof(void*)' and 'sizeof(cimg_int64/cimg_uint64)=8' ). #if cimg_OS==2 #define cimg_uint64 unsigned __int64 #define cimg_int64 __int64 #define cimg_ulong UINT_PTR #define cimg_long INT_PTR #ifdef _MSC_VER #define cimg_fuint64 "%I64u" #define cimg_fint64 "%I64d" #else #define cimg_fuint64 "%llu" #define cimg_fint64 "%lld" #endif #else #if UINTPTR_MAX==0xffffffff || defined(__arm__) || defined(_M_ARM) || ((ULONG_MAX)==(UINT_MAX)) #define cimg_uint64 unsigned long long #define cimg_int64 long long #define cimg_fuint64 "%llu" #define cimg_fint64 "%lld" #else #define cimg_uint64 unsigned long #define cimg_int64 long #define cimg_fuint64 "%lu" #define cimg_fint64 "%ld" #endif #if defined(__arm__) || defined(_M_ARM) #define cimg_ulong unsigned long long #define cimg_long long long #else #define cimg_ulong unsigned long #define cimg_long long #endif #endif // Configure filename separator. // // Filename separator is set by default to '/', except for Windows where it is '\'. #ifndef cimg_file_separator #if cimg_OS==2 #define cimg_file_separator '\\' #else #define cimg_file_separator '/' #endif #endif // Configure verbosity of output messages. // // Define 'cimg_verbosity' to: '0' to hide library messages (quiet mode). // '1' to output library messages on the console. // '2' to output library messages on a basic dialog window (default behavior). // '3' to do as '1' + add extra warnings (may slow down the code!). // '4' to do as '2' + add extra warnings (may slow down the code!). // // Define 'cimg_strict_warnings' to replace warning messages by exception throwns. // // Define 'cimg_use_vt100' to allow output of color messages on VT100-compatible terminals. #ifndef cimg_verbosity #if cimg_OS==2 #define cimg_verbosity 2 #else #define cimg_verbosity 1 #endif #elif !(cimg_verbosity==0 || cimg_verbosity==1 || cimg_verbosity==2 || cimg_verbosity==3 || cimg_verbosity==4) #error CImg Library: Configuration variable 'cimg_verbosity' is badly defined. #error (should be { 0=quiet | 1=console | 2=dialog | 3=console+warnings | 4=dialog+warnings }). #endif // Configure OpenMP support. // (http://www.openmp.org) // // Define 'cimg_use_openmp' to enable OpenMP support (requires OpenMP 3.0+). // // OpenMP directives are used in many CImg functions to get // advantages of multi-core CPUs. #if !defined(cimg_use_openmp) #ifdef _OPENMP #define cimg_use_openmp 1 #else #define cimg_use_openmp 0 #endif #endif #if cimg_use_openmp!=0 #include <omp.h> #define cimg_pragma_openmp(p) cimg_pragma(omp p) #else #define cimg_pragma_openmp(p) #endif // Configure the 'abort' signal handler (does nothing by default). // A typical signal handler can be defined in your own source like this: // #define cimg_abort_test if (is_abort) throw CImgAbortException("") // // where 'is_abort' is a boolean variable defined somewhere in your code and reachable in the method. // 'cimg_abort_test2' does the same but is called more often (in inner loops). #if defined(cimg_abort_test) && cimg_use_openmp!=0 // Define abort macros to be used with OpenMP. #ifndef _cimg_abort_init_omp #define _cimg_abort_init_omp bool _cimg_abort_go_omp = true; cimg::unused(_cimg_abort_go_omp) #endif #ifndef _cimg_abort_try_omp #define _cimg_abort_try_omp if (_cimg_abort_go_omp) try #endif #ifndef _cimg_abort_catch_omp #define _cimg_abort_catch_omp catch (CImgAbortException&) { cimg_pragma(omp atomic) _cimg_abort_go_omp&=false; } #endif #ifdef cimg_abort_test2 #ifndef _cimg_abort_try_omp2 #define _cimg_abort_try_omp2 _cimg_abort_try_omp #endif #ifndef _cimg_abort_catch_omp2 #define _cimg_abort_catch_omp2 _cimg_abort_catch_omp #endif #ifndef _cimg_abort_catch_fill_omp #define _cimg_abort_catch_fill_omp \ catch (CImgException& e) { cimg_pragma(omp critical(abort)) CImg<charT>::string(e._message).move_to(is_error); \ cimg_pragma(omp atomic) _cimg_abort_go_omp&=false; } #endif #endif #endif #ifndef _cimg_abort_init_omp #define _cimg_abort_init_omp #endif #ifndef _cimg_abort_try_omp #define _cimg_abort_try_omp #endif #ifndef _cimg_abort_catch_omp #define _cimg_abort_catch_omp #endif #ifndef _cimg_abort_try_omp2 #define _cimg_abort_try_omp2 #endif #ifndef _cimg_abort_catch_omp2 #define _cimg_abort_catch_omp2 #endif #ifndef _cimg_abort_catch_fill_omp #define _cimg_abort_catch_fill_omp #endif #ifndef cimg_abort_init #define cimg_abort_init #endif #ifndef cimg_abort_test #define cimg_abort_test #endif #ifndef cimg_abort_test2 #define cimg_abort_test2 #endif // Configure display framework. // // Define 'cimg_display' to: '0' to disable display capabilities. // '1' to use the X-Window framework (X11). // '2' to use the Microsoft GDI32 framework. #ifndef cimg_display #if cimg_OS==0 #define cimg_display 0 #elif cimg_OS==1 #define cimg_display 1 #elif cimg_OS==2 #define cimg_display 2 #endif #elif !(cimg_display==0 || cimg_display==1 || cimg_display==2) #error CImg Library: Configuration variable 'cimg_display' is badly defined. #error (should be { 0=none | 1=X-Window (X11) | 2=Microsoft GDI32 }). #endif // Include display-specific headers. #if cimg_display==1 #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/keysym.h> #include <pthread.h> #ifdef cimg_use_xshm #include <sys/ipc.h> #include <sys/shm.h> #include <X11/extensions/XShm.h> #endif #ifdef cimg_use_xrandr #include <X11/extensions/Xrandr.h> #endif #endif #ifndef cimg_appname #define cimg_appname "CImg" #endif // Configure OpenCV support. // (http://opencv.willowgarage.com/wiki/) // // Define 'cimg_use_opencv' to enable OpenCV support. // // OpenCV library may be used to access images from cameras // (see method 'CImg<T>::load_camera()'). #ifdef cimg_use_opencv #ifdef True #undef True #define _cimg_redefine_True #endif #ifdef False #undef False #define _cimg_redefine_False #endif #ifdef Status #undef Status #define _cimg_redefine_Status #endif #include <cstddef> #include <opencv2/opencv.hpp> #if CV_MAJOR_VERSION>=3 #define _cimg_fourcc cv::VideoWriter::fourcc #define _cimg_cap_prop_frame_width cv::VideoCaptureProperties::CAP_PROP_FRAME_WIDTH #define _cimg_cap_prop_frame_height cv::VideoCaptureProperties::CAP_PROP_FRAME_HEIGHT #define _cimg_cap_prop_frame_count cv::VideoCaptureProperties::CAP_PROP_FRAME_COUNT #else #define _cimg_fourcc CV_FOURCC #define _cimg_cap_prop_frame_width CV_CAP_PROP_FRAME_WIDTH #define _cimg_cap_prop_frame_height CV_CAP_PROP_FRAME_HEIGHT #define _cimg_cap_prop_frame_count CV_CAP_PROP_FRAME_COUNT #endif #endif // Configure LibPNG support. // (http://www.libpng.org) // // Define 'cimg_use_png' to enable LibPNG support. // // PNG library may be used to get a native support of '.png' files. // (see methods 'CImg<T>::{load,save}_png()'. #ifdef cimg_use_png extern "C" { #include "png.h" } #endif // Configure LibJPEG support. // (http://en.wikipedia.org/wiki/Libjpeg) // // Define 'cimg_use_jpeg' to enable LibJPEG support. // // JPEG library may be used to get a native support of '.jpg' files. // (see methods 'CImg<T>::{load,save}_jpeg()'). #ifdef cimg_use_jpeg extern "C" { #include "jpeglib.h" #include "setjmp.h" } #endif // Configure LibTIFF support. // (http://www.libtiff.org) // // Define 'cimg_use_tiff' to enable LibTIFF support. // // TIFF library may be used to get a native support of '.tif' files. // (see methods 'CImg[List]<T>::{load,save}_tiff()'). #ifdef cimg_use_tiff extern "C" { #define uint64 uint64_hack_ #define int64 int64_hack_ #include "tiffio.h" #undef uint64 #undef int64 } #endif // Configure LibMINC2 support. // (http://en.wikibooks.org/wiki/MINC/Reference/MINC2.0_File_Format_Reference) // // Define 'cimg_use_minc2' to enable LibMINC2 support. // // MINC2 library may be used to get a native support of '.mnc' files. // (see methods 'CImg<T>::{load,save}_minc2()'). #ifdef cimg_use_minc2 #include "minc_io_simple_volume.h" #include "minc_1_simple.h" #include "minc_1_simple_rw.h" #endif // Configure Zlib support. // (http://www.zlib.net) // // Define 'cimg_use_zlib' to enable Zlib support. // // Zlib library may be used to allow compressed data in '.cimgz' files // (see methods 'CImg[List]<T>::{load,save}_cimg()'). #ifdef cimg_use_zlib extern "C" { #include "zlib.h" } #endif // Configure libcurl support. // (http://curl.haxx.se/libcurl/) // // Define 'cimg_use_curl' to enable libcurl support. // // Libcurl may be used to get a native support of file downloading from the network. // (see method 'cimg::load_network()'.) #ifdef cimg_use_curl #include "curl/curl.h" #endif // Configure Magick++ support. // (http://www.imagemagick.org/Magick++) // // Define 'cimg_use_magick' to enable Magick++ support. // // Magick++ library may be used to get a native support of various image file formats. // (see methods 'CImg<T>::{load,save}()'). #ifdef cimg_use_magick #include "Magick++.h" #endif // Configure FFTW3 support. // (http://www.fftw.org) // // Define 'cimg_use_fftw3' to enable libFFTW3 support. // // FFTW3 library may be used to efficiently compute the Fast Fourier Transform // of image data, without restriction on the image size. // (see method 'CImg[List]<T>::FFT()'). #ifdef cimg_use_fftw3 extern "C" { #include "fftw3.h" } #endif // Configure LibBoard support. // (http://libboard.sourceforge.net/) // // Define 'cimg_use_board' to enable Board support. // // Board library may be used to draw 3D objects in vector-graphics canvas // that can be saved as '.ps' or '.svg' files afterwards. // (see method 'CImg<T>::draw_object3d()'). #ifdef cimg_use_board #include "Board.h" #endif // Configure OpenEXR support. // (http://www.openexr.com/) // // Define 'cimg_use_openexr' to enable OpenEXR support. // // OpenEXR library may be used to get a native support of '.exr' files. // (see methods 'CImg<T>::{load,save}_exr()'). #ifdef cimg_use_openexr #include "ImfRgbaFile.h" #include "ImfInputFile.h" #include "ImfChannelList.h" #include "ImfMatrixAttribute.h" #include "ImfArray.h" #endif // Configure TinyEXR support. // (https://github.com/syoyo/tinyexr) // // Define 'cimg_use_tinyexr' to enable TinyEXR support. // // TinyEXR is a small, single header-only library to load and save OpenEXR(.exr) images. #ifdef cimg_use_tinyexr #ifndef TINYEXR_IMPLEMENTATION #define TINYEXR_IMPLEMENTATION #endif #include "tinyexr.h" #endif // Lapack configuration. // (http://www.netlib.org/lapack) // // Define 'cimg_use_lapack' to enable LAPACK support. // // Lapack library may be used in several CImg methods to speed up // matrix computations (eigenvalues, inverse, ...). #ifdef cimg_use_lapack extern "C" { extern void sgetrf_(int*, int*, float*, int*, int*, int*); extern void sgetri_(int*, float*, int*, int*, float*, int*, int*); extern void sgetrs_(char*, int*, int*, float*, int*, int*, float*, int*, int*); extern void sgesvd_(char*, char*, int*, int*, float*, int*, float*, float*, int*, float*, int*, float*, int*, int*); extern void ssyev_(char*, char*, int*, float*, int*, float*, float*, int*, int*); extern void dgetrf_(int*, int*, double*, int*, int*, int*); extern void dgetri_(int*, double*, int*, int*, double*, int*, int*); extern void dgetrs_(char*, int*, int*, double*, int*, int*, double*, int*, int*); extern void dgesvd_(char*, char*, int*, int*, double*, int*, double*, double*, int*, double*, int*, double*, int*, int*); extern void dsyev_(char*, char*, int*, double*, int*, double*, double*, int*, int*); extern void dgels_(char*, int*,int*,int*,double*,int*,double*,int*,double*,int*,int*); extern void sgels_(char*, int*,int*,int*,float*,int*,float*,int*,float*,int*,int*); } #endif // Check if min/max/PI macros are defined. // // CImg does not compile if macros 'min', 'max' or 'PI' are defined, // because it redefines functions min(), max() and const variable PI in the cimg:: namespace. // so it '#undef' these macros if necessary, and restore them to reasonable // values at the end of this file. #ifdef min #undef min #define _cimg_redefine_min #endif #ifdef max #undef max #define _cimg_redefine_max #endif #ifdef PI #undef PI #define _cimg_redefine_PI #endif // Define 'cimg_library' namespace suffix. // // You may want to add a suffix to the 'cimg_library' namespace, for instance if you need to work // with several versions of the library at the same time. #ifdef cimg_namespace_suffix #define __cimg_library_suffixed(s) cimg_library_##s #define _cimg_library_suffixed(s) __cimg_library_suffixed(s) #define cimg_library_suffixed _cimg_library_suffixed(cimg_namespace_suffix) #else #define cimg_library_suffixed cimg_library #endif /*------------------------------------------------------------------------------ # # Define user-friendly macros. # # These CImg macros are prefixed by 'cimg_' and can be used safely in your own # code. They are useful to parse command line options, or to write image loops. # ------------------------------------------------------------------------------*/ // Macros to define program usage, and retrieve command line arguments. #define cimg_usage(usage) cimg_library_suffixed::cimg::option((char*)0,argc,argv,(char*)0,usage,false) #define cimg_help(str) cimg_library_suffixed::cimg::option((char*)0,argc,argv,str,(char*)0) #define cimg_option(name,defaut,usage) cimg_library_suffixed::cimg::option(name,argc,argv,defaut,usage) // Macros to define and manipulate local neighborhoods. #define CImg_2x2(I,T) T I[4]; \ T& I##cc = I[0]; T& I##nc = I[1]; \ T& I##cn = I[2]; T& I##nn = I[3]; \ I##cc = I##nc = \ I##cn = I##nn = 0 #define CImg_3x3(I,T) T I[9]; \ T& I##pp = I[0]; T& I##cp = I[1]; T& I##np = I[2]; \ T& I##pc = I[3]; T& I##cc = I[4]; T& I##nc = I[5]; \ T& I##pn = I[6]; T& I##cn = I[7]; T& I##nn = I[8]; \ I##pp = I##cp = I##np = \ I##pc = I##cc = I##nc = \ I##pn = I##cn = I##nn = 0 #define CImg_4x4(I,T) T I[16]; \ T& I##pp = I[0]; T& I##cp = I[1]; T& I##np = I[2]; T& I##ap = I[3]; \ T& I##pc = I[4]; T& I##cc = I[5]; T& I##nc = I[6]; T& I##ac = I[7]; \ T& I##pn = I[8]; T& I##cn = I[9]; T& I##nn = I[10]; T& I##an = I[11]; \ T& I##pa = I[12]; T& I##ca = I[13]; T& I##na = I[14]; T& I##aa = I[15]; \ I##pp = I##cp = I##np = I##ap = \ I##pc = I##cc = I##nc = I##ac = \ I##pn = I##cn = I##nn = I##an = \ I##pa = I##ca = I##na = I##aa = 0 #define CImg_5x5(I,T) T I[25]; \ T& I##bb = I[0]; T& I##pb = I[1]; T& I##cb = I[2]; T& I##nb = I[3]; T& I##ab = I[4]; \ T& I##bp = I[5]; T& I##pp = I[6]; T& I##cp = I[7]; T& I##np = I[8]; T& I##ap = I[9]; \ T& I##bc = I[10]; T& I##pc = I[11]; T& I##cc = I[12]; T& I##nc = I[13]; T& I##ac = I[14]; \ T& I##bn = I[15]; T& I##pn = I[16]; T& I##cn = I[17]; T& I##nn = I[18]; T& I##an = I[19]; \ T& I##ba = I[20]; T& I##pa = I[21]; T& I##ca = I[22]; T& I##na = I[23]; T& I##aa = I[24]; \ I##bb = I##pb = I##cb = I##nb = I##ab = \ I##bp = I##pp = I##cp = I##np = I##ap = \ I##bc = I##pc = I##cc = I##nc = I##ac = \ I##bn = I##pn = I##cn = I##nn = I##an = \ I##ba = I##pa = I##ca = I##na = I##aa = 0 #define CImg_2x2x2(I,T) T I[8]; \ T& I##ccc = I[0]; T& I##ncc = I[1]; \ T& I##cnc = I[2]; T& I##nnc = I[3]; \ T& I##ccn = I[4]; T& I##ncn = I[5]; \ T& I##cnn = I[6]; T& I##nnn = I[7]; \ I##ccc = I##ncc = \ I##cnc = I##nnc = \ I##ccn = I##ncn = \ I##cnn = I##nnn = 0 #define CImg_3x3x3(I,T) T I[27]; \ T& I##ppp = I[0]; T& I##cpp = I[1]; T& I##npp = I[2]; \ T& I##pcp = I[3]; T& I##ccp = I[4]; T& I##ncp = I[5]; \ T& I##pnp = I[6]; T& I##cnp = I[7]; T& I##nnp = I[8]; \ T& I##ppc = I[9]; T& I##cpc = I[10]; T& I##npc = I[11]; \ T& I##pcc = I[12]; T& I##ccc = I[13]; T& I##ncc = I[14]; \ T& I##pnc = I[15]; T& I##cnc = I[16]; T& I##nnc = I[17]; \ T& I##ppn = I[18]; T& I##cpn = I[19]; T& I##npn = I[20]; \ T& I##pcn = I[21]; T& I##ccn = I[22]; T& I##ncn = I[23]; \ T& I##pnn = I[24]; T& I##cnn = I[25]; T& I##nnn = I[26]; \ I##ppp = I##cpp = I##npp = \ I##pcp = I##ccp = I##ncp = \ I##pnp = I##cnp = I##nnp = \ I##ppc = I##cpc = I##npc = \ I##pcc = I##ccc = I##ncc = \ I##pnc = I##cnc = I##nnc = \ I##ppn = I##cpn = I##npn = \ I##pcn = I##ccn = I##ncn = \ I##pnn = I##cnn = I##nnn = 0 #define cimg_get2x2(img,x,y,z,c,I,T) \ I[0] = (T)(img)(x,y,z,c), I[1] = (T)(img)(_n1##x,y,z,c), I[2] = (T)(img)(x,_n1##y,z,c), \ I[3] = (T)(img)(_n1##x,_n1##y,z,c) #define cimg_get3x3(img,x,y,z,c,I,T) \ I[0] = (T)(img)(_p1##x,_p1##y,z,c), I[1] = (T)(img)(x,_p1##y,z,c), I[2] = (T)(img)(_n1##x,_p1##y,z,c), \ I[3] = (T)(img)(_p1##x,y,z,c), I[4] = (T)(img)(x,y,z,c), I[5] = (T)(img)(_n1##x,y,z,c), \ I[6] = (T)(img)(_p1##x,_n1##y,z,c), I[7] = (T)(img)(x,_n1##y,z,c), I[8] = (T)(img)(_n1##x,_n1##y,z,c) #define cimg_get4x4(img,x,y,z,c,I,T) \ I[0] = (T)(img)(_p1##x,_p1##y,z,c), I[1] = (T)(img)(x,_p1##y,z,c), I[2] = (T)(img)(_n1##x,_p1##y,z,c), \ I[3] = (T)(img)(_n2##x,_p1##y,z,c), I[4] = (T)(img)(_p1##x,y,z,c), I[5] = (T)(img)(x,y,z,c), \ I[6] = (T)(img)(_n1##x,y,z,c), I[7] = (T)(img)(_n2##x,y,z,c), I[8] = (T)(img)(_p1##x,_n1##y,z,c), \ I[9] = (T)(img)(x,_n1##y,z,c), I[10] = (T)(img)(_n1##x,_n1##y,z,c), I[11] = (T)(img)(_n2##x,_n1##y,z,c), \ I[12] = (T)(img)(_p1##x,_n2##y,z,c), I[13] = (T)(img)(x,_n2##y,z,c), I[14] = (T)(img)(_n1##x,_n2##y,z,c), \ I[15] = (T)(img)(_n2##x,_n2##y,z,c) #define cimg_get5x5(img,x,y,z,c,I,T) \ I[0] = (T)(img)(_p2##x,_p2##y,z,c), I[1] = (T)(img)(_p1##x,_p2##y,z,c), I[2] = (T)(img)(x,_p2##y,z,c), \ I[3] = (T)(img)(_n1##x,_p2##y,z,c), I[4] = (T)(img)(_n2##x,_p2##y,z,c), I[5] = (T)(img)(_p2##x,_p1##y,z,c), \ I[6] = (T)(img)(_p1##x,_p1##y,z,c), I[7] = (T)(img)(x,_p1##y,z,c), I[8] = (T)(img)(_n1##x,_p1##y,z,c), \ I[9] = (T)(img)(_n2##x,_p1##y,z,c), I[10] = (T)(img)(_p2##x,y,z,c), I[11] = (T)(img)(_p1##x,y,z,c), \ I[12] = (T)(img)(x,y,z,c), I[13] = (T)(img)(_n1##x,y,z,c), I[14] = (T)(img)(_n2##x,y,z,c), \ I[15] = (T)(img)(_p2##x,_n1##y,z,c), I[16] = (T)(img)(_p1##x,_n1##y,z,c), I[17] = (T)(img)(x,_n1##y,z,c), \ I[18] = (T)(img)(_n1##x,_n1##y,z,c), I[19] = (T)(img)(_n2##x,_n1##y,z,c), I[20] = (T)(img)(_p2##x,_n2##y,z,c), \ I[21] = (T)(img)(_p1##x,_n2##y,z,c), I[22] = (T)(img)(x,_n2##y,z,c), I[23] = (T)(img)(_n1##x,_n2##y,z,c), \ I[24] = (T)(img)(_n2##x,_n2##y,z,c) #define cimg_get6x6(img,x,y,z,c,I,T) \ I[0] = (T)(img)(_p2##x,_p2##y,z,c), I[1] = (T)(img)(_p1##x,_p2##y,z,c), I[2] = (T)(img)(x,_p2##y,z,c), \ I[3] = (T)(img)(_n1##x,_p2##y,z,c), I[4] = (T)(img)(_n2##x,_p2##y,z,c), I[5] = (T)(img)(_n3##x,_p2##y,z,c), \ I[6] = (T)(img)(_p2##x,_p1##y,z,c), I[7] = (T)(img)(_p1##x,_p1##y,z,c), I[8] = (T)(img)(x,_p1##y,z,c), \ I[9] = (T)(img)(_n1##x,_p1##y,z,c), I[10] = (T)(img)(_n2##x,_p1##y,z,c), I[11] = (T)(img)(_n3##x,_p1##y,z,c), \ I[12] = (T)(img)(_p2##x,y,z,c), I[13] = (T)(img)(_p1##x,y,z,c), I[14] = (T)(img)(x,y,z,c), \ I[15] = (T)(img)(_n1##x,y,z,c), I[16] = (T)(img)(_n2##x,y,z,c), I[17] = (T)(img)(_n3##x,y,z,c), \ I[18] = (T)(img)(_p2##x,_n1##y,z,c), I[19] = (T)(img)(_p1##x,_n1##y,z,c), I[20] = (T)(img)(x,_n1##y,z,c), \ I[21] = (T)(img)(_n1##x,_n1##y,z,c), I[22] = (T)(img)(_n2##x,_n1##y,z,c), I[23] = (T)(img)(_n3##x,_n1##y,z,c), \ I[24] = (T)(img)(_p2##x,_n2##y,z,c), I[25] = (T)(img)(_p1##x,_n2##y,z,c), I[26] = (T)(img)(x,_n2##y,z,c), \ I[27] = (T)(img)(_n1##x,_n2##y,z,c), I[28] = (T)(img)(_n2##x,_n2##y,z,c), I[29] = (T)(img)(_n3##x,_n2##y,z,c), \ I[30] = (T)(img)(_p2##x,_n3##y,z,c), I[31] = (T)(img)(_p1##x,_n3##y,z,c), I[32] = (T)(img)(x,_n3##y,z,c), \ I[33] = (T)(img)(_n1##x,_n3##y,z,c), I[34] = (T)(img)(_n2##x,_n3##y,z,c), I[35] = (T)(img)(_n3##x,_n3##y,z,c) #define cimg_get7x7(img,x,y,z,c,I,T) \ I[0] = (T)(img)(_p3##x,_p3##y,z,c), I[1] = (T)(img)(_p2##x,_p3##y,z,c), I[2] = (T)(img)(_p1##x,_p3##y,z,c), \ I[3] = (T)(img)(x,_p3##y,z,c), I[4] = (T)(img)(_n1##x,_p3##y,z,c), I[5] = (T)(img)(_n2##x,_p3##y,z,c), \ I[6] = (T)(img)(_n3##x,_p3##y,z,c), I[7] = (T)(img)(_p3##x,_p2##y,z,c), I[8] = (T)(img)(_p2##x,_p2##y,z,c), \ I[9] = (T)(img)(_p1##x,_p2##y,z,c), I[10] = (T)(img)(x,_p2##y,z,c), I[11] = (T)(img)(_n1##x,_p2##y,z,c), \ I[12] = (T)(img)(_n2##x,_p2##y,z,c), I[13] = (T)(img)(_n3##x,_p2##y,z,c), I[14] = (T)(img)(_p3##x,_p1##y,z,c), \ I[15] = (T)(img)(_p2##x,_p1##y,z,c), I[16] = (T)(img)(_p1##x,_p1##y,z,c), I[17] = (T)(img)(x,_p1##y,z,c), \ I[18] = (T)(img)(_n1##x,_p1##y,z,c), I[19] = (T)(img)(_n2##x,_p1##y,z,c), I[20] = (T)(img)(_n3##x,_p1##y,z,c), \ I[21] = (T)(img)(_p3##x,y,z,c), I[22] = (T)(img)(_p2##x,y,z,c), I[23] = (T)(img)(_p1##x,y,z,c), \ I[24] = (T)(img)(x,y,z,c), I[25] = (T)(img)(_n1##x,y,z,c), I[26] = (T)(img)(_n2##x,y,z,c), \ I[27] = (T)(img)(_n3##x,y,z,c), I[28] = (T)(img)(_p3##x,_n1##y,z,c), I[29] = (T)(img)(_p2##x,_n1##y,z,c), \ I[30] = (T)(img)(_p1##x,_n1##y,z,c), I[31] = (T)(img)(x,_n1##y,z,c), I[32] = (T)(img)(_n1##x,_n1##y,z,c), \ I[33] = (T)(img)(_n2##x,_n1##y,z,c), I[34] = (T)(img)(_n3##x,_n1##y,z,c), I[35] = (T)(img)(_p3##x,_n2##y,z,c), \ I[36] = (T)(img)(_p2##x,_n2##y,z,c), I[37] = (T)(img)(_p1##x,_n2##y,z,c), I[38] = (T)(img)(x,_n2##y,z,c), \ I[39] = (T)(img)(_n1##x,_n2##y,z,c), I[40] = (T)(img)(_n2##x,_n2##y,z,c), I[41] = (T)(img)(_n3##x,_n2##y,z,c), \ I[42] = (T)(img)(_p3##x,_n3##y,z,c), I[43] = (T)(img)(_p2##x,_n3##y,z,c), I[44] = (T)(img)(_p1##x,_n3##y,z,c), \ I[45] = (T)(img)(x,_n3##y,z,c), I[46] = (T)(img)(_n1##x,_n3##y,z,c), I[47] = (T)(img)(_n2##x,_n3##y,z,c), \ I[48] = (T)(img)(_n3##x,_n3##y,z,c) #define cimg_get8x8(img,x,y,z,c,I,T) \ I[0] = (T)(img)(_p3##x,_p3##y,z,c), I[1] = (T)(img)(_p2##x,_p3##y,z,c), I[2] = (T)(img)(_p1##x,_p3##y,z,c), \ I[3] = (T)(img)(x,_p3##y,z,c), I[4] = (T)(img)(_n1##x,_p3##y,z,c), I[5] = (T)(img)(_n2##x,_p3##y,z,c), \ I[6] = (T)(img)(_n3##x,_p3##y,z,c), I[7] = (T)(img)(_n4##x,_p3##y,z,c), I[8] = (T)(img)(_p3##x,_p2##y,z,c), \ I[9] = (T)(img)(_p2##x,_p2##y,z,c), I[10] = (T)(img)(_p1##x,_p2##y,z,c), I[11] = (T)(img)(x,_p2##y,z,c), \ I[12] = (T)(img)(_n1##x,_p2##y,z,c), I[13] = (T)(img)(_n2##x,_p2##y,z,c), I[14] = (T)(img)(_n3##x,_p2##y,z,c), \ I[15] = (T)(img)(_n4##x,_p2##y,z,c), I[16] = (T)(img)(_p3##x,_p1##y,z,c), I[17] = (T)(img)(_p2##x,_p1##y,z,c), \ I[18] = (T)(img)(_p1##x,_p1##y,z,c), I[19] = (T)(img)(x,_p1##y,z,c), I[20] = (T)(img)(_n1##x,_p1##y,z,c), \ I[21] = (T)(img)(_n2##x,_p1##y,z,c), I[22] = (T)(img)(_n3##x,_p1##y,z,c), I[23] = (T)(img)(_n4##x,_p1##y,z,c), \ I[24] = (T)(img)(_p3##x,y,z,c), I[25] = (T)(img)(_p2##x,y,z,c), I[26] = (T)(img)(_p1##x,y,z,c), \ I[27] = (T)(img)(x,y,z,c), I[28] = (T)(img)(_n1##x,y,z,c), I[29] = (T)(img)(_n2##x,y,z,c), \ I[30] = (T)(img)(_n3##x,y,z,c), I[31] = (T)(img)(_n4##x,y,z,c), I[32] = (T)(img)(_p3##x,_n1##y,z,c), \ I[33] = (T)(img)(_p2##x,_n1##y,z,c), I[34] = (T)(img)(_p1##x,_n1##y,z,c), I[35] = (T)(img)(x,_n1##y,z,c), \ I[36] = (T)(img)(_n1##x,_n1##y,z,c), I[37] = (T)(img)(_n2##x,_n1##y,z,c), I[38] = (T)(img)(_n3##x,_n1##y,z,c), \ I[39] = (T)(img)(_n4##x,_n1##y,z,c), I[40] = (T)(img)(_p3##x,_n2##y,z,c), I[41] = (T)(img)(_p2##x,_n2##y,z,c), \ I[42] = (T)(img)(_p1##x,_n2##y,z,c), I[43] = (T)(img)(x,_n2##y,z,c), I[44] = (T)(img)(_n1##x,_n2##y,z,c), \ I[45] = (T)(img)(_n2##x,_n2##y,z,c), I[46] = (T)(img)(_n3##x,_n2##y,z,c), I[47] = (T)(img)(_n4##x,_n2##y,z,c), \ I[48] = (T)(img)(_p3##x,_n3##y,z,c), I[49] = (T)(img)(_p2##x,_n3##y,z,c), I[50] = (T)(img)(_p1##x,_n3##y,z,c), \ I[51] = (T)(img)(x,_n3##y,z,c), I[52] = (T)(img)(_n1##x,_n3##y,z,c), I[53] = (T)(img)(_n2##x,_n3##y,z,c), \ I[54] = (T)(img)(_n3##x,_n3##y,z,c), I[55] = (T)(img)(_n4##x,_n3##y,z,c), I[56] = (T)(img)(_p3##x,_n4##y,z,c), \ I[57] = (T)(img)(_p2##x,_n4##y,z,c), I[58] = (T)(img)(_p1##x,_n4##y,z,c), I[59] = (T)(img)(x,_n4##y,z,c), \ I[60] = (T)(img)(_n1##x,_n4##y,z,c), I[61] = (T)(img)(_n2##x,_n4##y,z,c), I[62] = (T)(img)(_n3##x,_n4##y,z,c), \ I[63] = (T)(img)(_n4##x,_n4##y,z,c); #define cimg_get9x9(img,x,y,z,c,I,T) \ I[0] = (T)(img)(_p4##x,_p4##y,z,c), I[1] = (T)(img)(_p3##x,_p4##y,z,c), I[2] = (T)(img)(_p2##x,_p4##y,z,c), \ I[3] = (T)(img)(_p1##x,_p4##y,z,c), I[4] = (T)(img)(x,_p4##y,z,c), I[5] = (T)(img)(_n1##x,_p4##y,z,c), \ I[6] = (T)(img)(_n2##x,_p4##y,z,c), I[7] = (T)(img)(_n3##x,_p4##y,z,c), I[8] = (T)(img)(_n4##x,_p4##y,z,c), \ I[9] = (T)(img)(_p4##x,_p3##y,z,c), I[10] = (T)(img)(_p3##x,_p3##y,z,c), I[11] = (T)(img)(_p2##x,_p3##y,z,c), \ I[12] = (T)(img)(_p1##x,_p3##y,z,c), I[13] = (T)(img)(x,_p3##y,z,c), I[14] = (T)(img)(_n1##x,_p3##y,z,c), \ I[15] = (T)(img)(_n2##x,_p3##y,z,c), I[16] = (T)(img)(_n3##x,_p3##y,z,c), I[17] = (T)(img)(_n4##x,_p3##y,z,c), \ I[18] = (T)(img)(_p4##x,_p2##y,z,c), I[19] = (T)(img)(_p3##x,_p2##y,z,c), I[20] = (T)(img)(_p2##x,_p2##y,z,c), \ I[21] = (T)(img)(_p1##x,_p2##y,z,c), I[22] = (T)(img)(x,_p2##y,z,c), I[23] = (T)(img)(_n1##x,_p2##y,z,c), \ I[24] = (T)(img)(_n2##x,_p2##y,z,c), I[25] = (T)(img)(_n3##x,_p2##y,z,c), I[26] = (T)(img)(_n4##x,_p2##y,z,c), \ I[27] = (T)(img)(_p4##x,_p1##y,z,c), I[28] = (T)(img)(_p3##x,_p1##y,z,c), I[29] = (T)(img)(_p2##x,_p1##y,z,c), \ I[30] = (T)(img)(_p1##x,_p1##y,z,c), I[31] = (T)(img)(x,_p1##y,z,c), I[32] = (T)(img)(_n1##x,_p1##y,z,c), \ I[33] = (T)(img)(_n2##x,_p1##y,z,c), I[34] = (T)(img)(_n3##x,_p1##y,z,c), I[35] = (T)(img)(_n4##x,_p1##y,z,c), \ I[36] = (T)(img)(_p4##x,y,z,c), I[37] = (T)(img)(_p3##x,y,z,c), I[38] = (T)(img)(_p2##x,y,z,c), \ I[39] = (T)(img)(_p1##x,y,z,c), I[40] = (T)(img)(x,y,z,c), I[41] = (T)(img)(_n1##x,y,z,c), \ I[42] = (T)(img)(_n2##x,y,z,c), I[43] = (T)(img)(_n3##x,y,z,c), I[44] = (T)(img)(_n4##x,y,z,c), \ I[45] = (T)(img)(_p4##x,_n1##y,z,c), I[46] = (T)(img)(_p3##x,_n1##y,z,c), I[47] = (T)(img)(_p2##x,_n1##y,z,c), \ I[48] = (T)(img)(_p1##x,_n1##y,z,c), I[49] = (T)(img)(x,_n1##y,z,c), I[50] = (T)(img)(_n1##x,_n1##y,z,c), \ I[51] = (T)(img)(_n2##x,_n1##y,z,c), I[52] = (T)(img)(_n3##x,_n1##y,z,c), I[53] = (T)(img)(_n4##x,_n1##y,z,c), \ I[54] = (T)(img)(_p4##x,_n2##y,z,c), I[55] = (T)(img)(_p3##x,_n2##y,z,c), I[56] = (T)(img)(_p2##x,_n2##y,z,c), \ I[57] = (T)(img)(_p1##x,_n2##y,z,c), I[58] = (T)(img)(x,_n2##y,z,c), I[59] = (T)(img)(_n1##x,_n2##y,z,c), \ I[60] = (T)(img)(_n2##x,_n2##y,z,c), I[61] = (T)(img)(_n3##x,_n2##y,z,c), I[62] = (T)(img)(_n4##x,_n2##y,z,c), \ I[63] = (T)(img)(_p4##x,_n3##y,z,c), I[64] = (T)(img)(_p3##x,_n3##y,z,c), I[65] = (T)(img)(_p2##x,_n3##y,z,c), \ I[66] = (T)(img)(_p1##x,_n3##y,z,c), I[67] = (T)(img)(x,_n3##y,z,c), I[68] = (T)(img)(_n1##x,_n3##y,z,c), \ I[69] = (T)(img)(_n2##x,_n3##y,z,c), I[70] = (T)(img)(_n3##x,_n3##y,z,c), I[71] = (T)(img)(_n4##x,_n3##y,z,c), \ I[72] = (T)(img)(_p4##x,_n4##y,z,c), I[73] = (T)(img)(_p3##x,_n4##y,z,c), I[74] = (T)(img)(_p2##x,_n4##y,z,c), \ I[75] = (T)(img)(_p1##x,_n4##y,z,c), I[76] = (T)(img)(x,_n4##y,z,c), I[77] = (T)(img)(_n1##x,_n4##y,z,c), \ I[78] = (T)(img)(_n2##x,_n4##y,z,c), I[79] = (T)(img)(_n3##x,_n4##y,z,c), I[80] = (T)(img)(_n4##x,_n4##y,z,c) #define cimg_get2x2x2(img,x,y,z,c,I,T) \ I[0] = (T)(img)(x,y,z,c), I[1] = (T)(img)(_n1##x,y,z,c), I[2] = (T)(img)(x,_n1##y,z,c), \ I[3] = (T)(img)(_n1##x,_n1##y,z,c), I[4] = (T)(img)(x,y,_n1##z,c), I[5] = (T)(img)(_n1##x,y,_n1##z,c), \ I[6] = (T)(img)(x,_n1##y,_n1##z,c), I[7] = (T)(img)(_n1##x,_n1##y,_n1##z,c) #define cimg_get3x3x3(img,x,y,z,c,I,T) \ I[0] = (T)(img)(_p1##x,_p1##y,_p1##z,c), I[1] = (T)(img)(x,_p1##y,_p1##z,c), \ I[2] = (T)(img)(_n1##x,_p1##y,_p1##z,c), I[3] = (T)(img)(_p1##x,y,_p1##z,c), I[4] = (T)(img)(x,y,_p1##z,c), \ I[5] = (T)(img)(_n1##x,y,_p1##z,c), I[6] = (T)(img)(_p1##x,_n1##y,_p1##z,c), I[7] = (T)(img)(x,_n1##y,_p1##z,c), \ I[8] = (T)(img)(_n1##x,_n1##y,_p1##z,c), I[9] = (T)(img)(_p1##x,_p1##y,z,c), I[10] = (T)(img)(x,_p1##y,z,c), \ I[11] = (T)(img)(_n1##x,_p1##y,z,c), I[12] = (T)(img)(_p1##x,y,z,c), I[13] = (T)(img)(x,y,z,c), \ I[14] = (T)(img)(_n1##x,y,z,c), I[15] = (T)(img)(_p1##x,_n1##y,z,c), I[16] = (T)(img)(x,_n1##y,z,c), \ I[17] = (T)(img)(_n1##x,_n1##y,z,c), I[18] = (T)(img)(_p1##x,_p1##y,_n1##z,c), I[19] = (T)(img)(x,_p1##y,_n1##z,c), \ I[20] = (T)(img)(_n1##x,_p1##y,_n1##z,c), I[21] = (T)(img)(_p1##x,y,_n1##z,c), I[22] = (T)(img)(x,y,_n1##z,c), \ I[23] = (T)(img)(_n1##x,y,_n1##z,c), I[24] = (T)(img)(_p1##x,_n1##y,_n1##z,c), I[25] = (T)(img)(x,_n1##y,_n1##z,c), \ I[26] = (T)(img)(_n1##x,_n1##y,_n1##z,c) // Macros to perform various image loops. // // These macros are simpler to use than loops with C++ iterators. #define cimg_for(img,ptrs,T_ptrs) \ for (T_ptrs *ptrs = (img)._data, *_max##ptrs = (img)._data + (img).size(); ptrs<_max##ptrs; ++ptrs) #define cimg_rof(img,ptrs,T_ptrs) for (T_ptrs *ptrs = (img)._data + (img).size() - 1; ptrs>=(img)._data; --ptrs) #define cimg_foroff(img,off) for (cimg_ulong off = 0, _max##off = (img).size(); off<_max##off; ++off) #define cimg_rofoff(img,off) for (cimg_long off = (cimg_long)((img).size() - 1); off>=0; --off) #define cimg_for1(bound,i) for (int i = 0; i<(int)(bound); ++i) #define cimg_forX(img,x) cimg_for1((img)._width,x) #define cimg_forY(img,y) cimg_for1((img)._height,y) #define cimg_forZ(img,z) cimg_for1((img)._depth,z) #define cimg_forC(img,c) cimg_for1((img)._spectrum,c) #define cimg_forXY(img,x,y) cimg_forY(img,y) cimg_forX(img,x) #define cimg_forXZ(img,x,z) cimg_forZ(img,z) cimg_forX(img,x) #define cimg_forYZ(img,y,z) cimg_forZ(img,z) cimg_forY(img,y) #define cimg_forXC(img,x,c) cimg_forC(img,c) cimg_forX(img,x) #define cimg_forYC(img,y,c) cimg_forC(img,c) cimg_forY(img,y) #define cimg_forZC(img,z,c) cimg_forC(img,c) cimg_forZ(img,z) #define cimg_forXYZ(img,x,y,z) cimg_forZ(img,z) cimg_forXY(img,x,y) #define cimg_forXYC(img,x,y,c) cimg_forC(img,c) cimg_forXY(img,x,y) #define cimg_forXZC(img,x,z,c) cimg_forC(img,c) cimg_forXZ(img,x,z) #define cimg_forYZC(img,y,z,c) cimg_forC(img,c) cimg_forYZ(img,y,z) #define cimg_forXYZC(img,x,y,z,c) cimg_forC(img,c) cimg_forXYZ(img,x,y,z) #define cimg_rof1(bound,i) for (int i = (int)(bound) - 1; i>=0; --i) #define cimg_rofX(img,x) cimg_rof1((img)._width,x) #define cimg_rofY(img,y) cimg_rof1((img)._height,y) #define cimg_rofZ(img,z) cimg_rof1((img)._depth,z) #define cimg_rofC(img,c) cimg_rof1((img)._spectrum,c) #define cimg_rofXY(img,x,y) cimg_rofY(img,y) cimg_rofX(img,x) #define cimg_rofXZ(img,x,z) cimg_rofZ(img,z) cimg_rofX(img,x) #define cimg_rofYZ(img,y,z) cimg_rofZ(img,z) cimg_rofY(img,y) #define cimg_rofXC(img,x,c) cimg_rofC(img,c) cimg_rofX(img,x) #define cimg_rofYC(img,y,c) cimg_rofC(img,c) cimg_rofY(img,y) #define cimg_rofZC(img,z,c) cimg_rofC(img,c) cimg_rofZ(img,z) #define cimg_rofXYZ(img,x,y,z) cimg_rofZ(img,z) cimg_rofXY(img,x,y) #define cimg_rofXYC(img,x,y,c) cimg_rofC(img,c) cimg_rofXY(img,x,y) #define cimg_rofXZC(img,x,z,c) cimg_rofC(img,c) cimg_rofXZ(img,x,z) #define cimg_rofYZC(img,y,z,c) cimg_rofC(img,c) cimg_rofYZ(img,y,z) #define cimg_rofXYZC(img,x,y,z,c) cimg_rofC(img,c) cimg_rofXYZ(img,x,y,z) #define cimg_for_in1(bound,i0,i1,i) \ for (int i = (int)(i0)<0?0:(int)(i0), _max##i = (int)(i1)<(int)(bound)?(int)(i1):(int)(bound) - 1; i<=_max##i; ++i) #define cimg_for_inX(img,x0,x1,x) cimg_for_in1((img)._width,x0,x1,x) #define cimg_for_inY(img,y0,y1,y) cimg_for_in1((img)._height,y0,y1,y) #define cimg_for_inZ(img,z0,z1,z) cimg_for_in1((img)._depth,z0,z1,z) #define cimg_for_inC(img,c0,c1,c) cimg_for_in1((img)._spectrum,c0,c1,c) #define cimg_for_inXY(img,x0,y0,x1,y1,x,y) cimg_for_inY(img,y0,y1,y) cimg_for_inX(img,x0,x1,x) #define cimg_for_inXZ(img,x0,z0,x1,z1,x,z) cimg_for_inZ(img,z0,z1,z) cimg_for_inX(img,x0,x1,x) #define cimg_for_inXC(img,x0,c0,x1,c1,x,c) cimg_for_inC(img,c0,c1,c) cimg_for_inX(img,x0,x1,x) #define cimg_for_inYZ(img,y0,z0,y1,z1,y,z) cimg_for_inZ(img,x0,z1,z) cimg_for_inY(img,y0,y1,y) #define cimg_for_inYC(img,y0,c0,y1,c1,y,c) cimg_for_inC(img,c0,c1,c) cimg_for_inY(img,y0,y1,y) #define cimg_for_inZC(img,z0,c0,z1,c1,z,c) cimg_for_inC(img,c0,c1,c) cimg_for_inZ(img,z0,z1,z) #define cimg_for_inXYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) cimg_for_inZ(img,z0,z1,z) cimg_for_inXY(img,x0,y0,x1,y1,x,y) #define cimg_for_inXYC(img,x0,y0,c0,x1,y1,c1,x,y,c) cimg_for_inC(img,c0,c1,c) cimg_for_inXY(img,x0,y0,x1,y1,x,y) #define cimg_for_inXZC(img,x0,z0,c0,x1,z1,c1,x,z,c) cimg_for_inC(img,c0,c1,c) cimg_for_inXZ(img,x0,z0,x1,z1,x,z) #define cimg_for_inYZC(img,y0,z0,c0,y1,z1,c1,y,z,c) cimg_for_inC(img,c0,c1,c) cimg_for_inYZ(img,y0,z0,y1,z1,y,z) #define cimg_for_inXYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) \ cimg_for_inC(img,c0,c1,c) cimg_for_inXYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for_insideX(img,x,n) cimg_for_inX(img,n,(img)._width - 1 - (n),x) #define cimg_for_insideY(img,y,n) cimg_for_inY(img,n,(img)._height - 1 - (n),y) #define cimg_for_insideZ(img,z,n) cimg_for_inZ(img,n,(img)._depth - 1 - (n),z) #define cimg_for_insideC(img,c,n) cimg_for_inC(img,n,(img)._spectrum - 1 - (n),c) #define cimg_for_insideXY(img,x,y,n) cimg_for_inXY(img,n,n,(img)._width - 1 - (n),(img)._height - 1 - (n),x,y) #define cimg_for_insideXYZ(img,x,y,z,n) \ cimg_for_inXYZ(img,n,n,n,(img)._width - 1 - (n),(img)._height - 1 - (n),(img)._depth - 1 - (n),x,y,z) #define cimg_for_insideXYZC(img,x,y,z,c,n) \ cimg_for_inXYZ(img,n,n,n,(img)._width - 1 - (n),(img)._height - 1 - (n),(img)._depth - 1 - (n),x,y,z) #define cimg_for_out1(boundi,i0,i1,i) \ for (int i = (int)(i0)>0?0:(int)(i1) + 1; i<(int)(boundi); ++i, i = i==(int)(i0)?(int)(i1) + 1:i) #define cimg_for_out2(boundi,boundj,i0,j0,i1,j1,i,j) \ for (int j = 0; j<(int)(boundj); ++j) \ for (int _n1j = (int)(j<(int)(j0) || j>(int)(j1)), i = _n1j?0:(int)(i0)>0?0:(int)(i1) + 1; i<(int)(boundi); \ ++i, i = _n1j?i:(i==(int)(i0)?(int)(i1) + 1:i)) #define cimg_for_out3(boundi,boundj,boundk,i0,j0,k0,i1,j1,k1,i,j,k) \ for (int k = 0; k<(int)(boundk); ++k) \ for (int _n1k = (int)(k<(int)(k0) || k>(int)(k1)), j = 0; j<(int)(boundj); ++j) \ for (int _n1j = (int)(j<(int)(j0) || j>(int)(j1)), i = _n1j || _n1k?0:(int)(i0)>0?0:(int)(i1) + 1; i<(int)(boundi); \ ++i, i = _n1j || _n1k?i:(i==(int)(i0)?(int)(i1) + 1:i)) #define cimg_for_out4(boundi,boundj,boundk,boundl,i0,j0,k0,l0,i1,j1,k1,l1,i,j,k,l) \ for (int l = 0; l<(int)(boundl); ++l) \ for (int _n1l = (int)(l<(int)(l0) || l>(int)(l1)), k = 0; k<(int)(boundk); ++k) \ for (int _n1k = (int)(k<(int)(k0) || k>(int)(k1)), j = 0; j<(int)(boundj); ++j) \ for (int _n1j = (int)(j<(int)(j0) || j>(int)(j1)), i = _n1j || _n1k || _n1l?0:(int)(i0)>0?0:(int)(i1) + 1; \ i<(int)(boundi); ++i, i = _n1j || _n1k || _n1l?i:(i==(int)(i0)?(int)(i1) + 1:i)) #define cimg_for_outX(img,x0,x1,x) cimg_for_out1((img)._width,x0,x1,x) #define cimg_for_outY(img,y0,y1,y) cimg_for_out1((img)._height,y0,y1,y) #define cimg_for_outZ(img,z0,z1,z) cimg_for_out1((img)._depth,z0,z1,z) #define cimg_for_outC(img,c0,c1,c) cimg_for_out1((img)._spectrum,c0,c1,c) #define cimg_for_outXY(img,x0,y0,x1,y1,x,y) cimg_for_out2((img)._width,(img)._height,x0,y0,x1,y1,x,y) #define cimg_for_outXZ(img,x0,z0,x1,z1,x,z) cimg_for_out2((img)._width,(img)._depth,x0,z0,x1,z1,x,z) #define cimg_for_outXC(img,x0,c0,x1,c1,x,c) cimg_for_out2((img)._width,(img)._spectrum,x0,c0,x1,c1,x,c) #define cimg_for_outYZ(img,y0,z0,y1,z1,y,z) cimg_for_out2((img)._height,(img)._depth,y0,z0,y1,z1,y,z) #define cimg_for_outYC(img,y0,c0,y1,c1,y,c) cimg_for_out2((img)._height,(img)._spectrum,y0,c0,y1,c1,y,c) #define cimg_for_outZC(img,z0,c0,z1,c1,z,c) cimg_for_out2((img)._depth,(img)._spectrum,z0,c0,z1,c1,z,c) #define cimg_for_outXYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) \ cimg_for_out3((img)._width,(img)._height,(img)._depth,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for_outXYC(img,x0,y0,c0,x1,y1,c1,x,y,c) \ cimg_for_out3((img)._width,(img)._height,(img)._spectrum,x0,y0,c0,x1,y1,c1,x,y,c) #define cimg_for_outXZC(img,x0,z0,c0,x1,z1,c1,x,z,c) \ cimg_for_out3((img)._width,(img)._depth,(img)._spectrum,x0,z0,c0,x1,z1,c1,x,z,c) #define cimg_for_outYZC(img,y0,z0,c0,y1,z1,c1,y,z,c) \ cimg_for_out3((img)._height,(img)._depth,(img)._spectrum,y0,z0,c0,y1,z1,c1,y,z,c) #define cimg_for_outXYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) \ cimg_for_out4((img)._width,(img)._height,(img)._depth,(img)._spectrum,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) #define cimg_for_borderX(img,x,n) cimg_for_outX(img,n,(img)._width - 1 - (n),x) #define cimg_for_borderY(img,y,n) cimg_for_outY(img,n,(img)._height - 1 - (n),y) #define cimg_for_borderZ(img,z,n) cimg_for_outZ(img,n,(img)._depth - 1 - (n),z) #define cimg_for_borderC(img,c,n) cimg_for_outC(img,n,(img)._spectrum - 1 - (n),c) #define cimg_for_borderXY(img,x,y,n) cimg_for_outXY(img,n,n,(img)._width - 1 - (n),(img)._height - 1 - (n),x,y) #define cimg_for_borderXYZ(img,x,y,z,n) \ cimg_for_outXYZ(img,n,n,n,(img)._width - 1 - (n),(img)._height - 1 - (n),(img)._depth - 1 - (n),x,y,z) #define cimg_for_borderXYZC(img,x,y,z,c,n) \ cimg_for_outXYZC(img,n,n,n,n,(img)._width - 1 - (n),(img)._height - 1 - (n), \ (img)._depth - 1 - (n),(img)._spectrum - 1 - (n),x,y,z,c) #define cimg_for_spiralXY(img,x,y) \ for (int x = 0, y = 0, _n1##x = 1, _n1##y = (img).width()*(img).height(); _n1##y; \ --_n1##y, _n1##x+=(_n1##x>>2) - ((!(_n1##x&3)?--y:((_n1##x&3)==1?(img)._width - 1 - ++x:\ ((_n1##x&3)==2?(img)._height - 1 - ++y:--x))))?0:1) #define cimg_for_lineXY(x,y,x0,y0,x1,y1) \ for (int x = (int)(x0), y = (int)(y0), _sx = 1, _sy = 1, _steep = 0, \ _dx=(x1)>(x0)?(int)(x1) - (int)(x0):(_sx=-1,(int)(x0) - (int)(x1)), \ _dy=(y1)>(y0)?(int)(y1) - (int)(y0):(_sy=-1,(int)(y0) - (int)(y1)), \ _counter = _dx, \ _err = _dx>_dy?(_dy>>1):((_steep=1),(_counter=_dy),(_dx>>1)); \ _counter>=0; \ --_counter, x+=_steep? \ (y+=_sy,(_err-=_dx)<0?_err+=_dy,_sx:0): \ (y+=(_err-=_dy)<0?_err+=_dx,_sy:0,_sx)) #define cimg_for2(bound,i) \ for (int i = 0, _n1##i = 1>=(bound)?(int)(bound) - 1:1; \ _n1##i<(int)(bound) || i==--_n1##i; \ ++i, ++_n1##i) #define cimg_for2X(img,x) cimg_for2((img)._width,x) #define cimg_for2Y(img,y) cimg_for2((img)._height,y) #define cimg_for2Z(img,z) cimg_for2((img)._depth,z) #define cimg_for2C(img,c) cimg_for2((img)._spectrum,c) #define cimg_for2XY(img,x,y) cimg_for2Y(img,y) cimg_for2X(img,x) #define cimg_for2XZ(img,x,z) cimg_for2Z(img,z) cimg_for2X(img,x) #define cimg_for2XC(img,x,c) cimg_for2C(img,c) cimg_for2X(img,x) #define cimg_for2YZ(img,y,z) cimg_for2Z(img,z) cimg_for2Y(img,y) #define cimg_for2YC(img,y,c) cimg_for2C(img,c) cimg_for2Y(img,y) #define cimg_for2ZC(img,z,c) cimg_for2C(img,c) cimg_for2Z(img,z) #define cimg_for2XYZ(img,x,y,z) cimg_for2Z(img,z) cimg_for2XY(img,x,y) #define cimg_for2XZC(img,x,z,c) cimg_for2C(img,c) cimg_for2XZ(img,x,z) #define cimg_for2YZC(img,y,z,c) cimg_for2C(img,c) cimg_for2YZ(img,y,z) #define cimg_for2XYZC(img,x,y,z,c) cimg_for2C(img,c) cimg_for2XYZ(img,x,y,z) #define cimg_for_in2(bound,i0,i1,i) \ for (int i = (int)(i0)<0?0:(int)(i0), \ _n1##i = i + 1>=(int)(bound)?(int)(bound) - 1:i + 1; \ i<=(int)(i1) && (_n1##i<(int)(bound) || i==--_n1##i); \ ++i, ++_n1##i) #define cimg_for_in2X(img,x0,x1,x) cimg_for_in2((img)._width,x0,x1,x) #define cimg_for_in2Y(img,y0,y1,y) cimg_for_in2((img)._height,y0,y1,y) #define cimg_for_in2Z(img,z0,z1,z) cimg_for_in2((img)._depth,z0,z1,z) #define cimg_for_in2C(img,c0,c1,c) cimg_for_in2((img)._spectrum,c0,c1,c) #define cimg_for_in2XY(img,x0,y0,x1,y1,x,y) cimg_for_in2Y(img,y0,y1,y) cimg_for_in2X(img,x0,x1,x) #define cimg_for_in2XZ(img,x0,z0,x1,z1,x,z) cimg_for_in2Z(img,z0,z1,z) cimg_for_in2X(img,x0,x1,x) #define cimg_for_in2XC(img,x0,c0,x1,c1,x,c) cimg_for_in2C(img,c0,c1,c) cimg_for_in2X(img,x0,x1,x) #define cimg_for_in2YZ(img,y0,z0,y1,z1,y,z) cimg_for_in2Z(img,z0,z1,z) cimg_for_in2Y(img,y0,y1,y) #define cimg_for_in2YC(img,y0,c0,y1,c1,y,c) cimg_for_in2C(img,c0,c1,c) cimg_for_in2Y(img,y0,y1,y) #define cimg_for_in2ZC(img,z0,c0,z1,c1,z,c) cimg_for_in2C(img,c0,c1,c) cimg_for_in2Z(img,z0,z1,z) #define cimg_for_in2XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) cimg_for_in2Z(img,z0,z1,z) cimg_for_in2XY(img,x0,y0,x1,y1,x,y) #define cimg_for_in2XZC(img,x0,z0,c0,x1,y1,c1,x,z,c) cimg_for_in2C(img,c0,c1,c) cimg_for_in2XZ(img,x0,y0,x1,y1,x,z) #define cimg_for_in2YZC(img,y0,z0,c0,y1,z1,c1,y,z,c) cimg_for_in2C(img,c0,c1,c) cimg_for_in2YZ(img,y0,z0,y1,z1,y,z) #define cimg_for_in2XYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) \ cimg_for_in2C(img,c0,c1,c) cimg_for_in2XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for3(bound,i) \ for (int i = 0, _p1##i = 0, \ _n1##i = 1>=(bound)?(int)(bound) - 1:1; \ _n1##i<(int)(bound) || i==--_n1##i; \ _p1##i = i++, ++_n1##i) #define cimg_for3X(img,x) cimg_for3((img)._width,x) #define cimg_for3Y(img,y) cimg_for3((img)._height,y) #define cimg_for3Z(img,z) cimg_for3((img)._depth,z) #define cimg_for3C(img,c) cimg_for3((img)._spectrum,c) #define cimg_for3XY(img,x,y) cimg_for3Y(img,y) cimg_for3X(img,x) #define cimg_for3XZ(img,x,z) cimg_for3Z(img,z) cimg_for3X(img,x) #define cimg_for3XC(img,x,c) cimg_for3C(img,c) cimg_for3X(img,x) #define cimg_for3YZ(img,y,z) cimg_for3Z(img,z) cimg_for3Y(img,y) #define cimg_for3YC(img,y,c) cimg_for3C(img,c) cimg_for3Y(img,y) #define cimg_for3ZC(img,z,c) cimg_for3C(img,c) cimg_for3Z(img,z) #define cimg_for3XYZ(img,x,y,z) cimg_for3Z(img,z) cimg_for3XY(img,x,y) #define cimg_for3XZC(img,x,z,c) cimg_for3C(img,c) cimg_for3XZ(img,x,z) #define cimg_for3YZC(img,y,z,c) cimg_for3C(img,c) cimg_for3YZ(img,y,z) #define cimg_for3XYZC(img,x,y,z,c) cimg_for3C(img,c) cimg_for3XYZ(img,x,y,z) #define cimg_for_in3(bound,i0,i1,i) \ for (int i = (int)(i0)<0?0:(int)(i0), \ _p1##i = i - 1<0?0:i - 1, \ _n1##i = i + 1>=(int)(bound)?(int)(bound) - 1:i + 1; \ i<=(int)(i1) && (_n1##i<(int)(bound) || i==--_n1##i); \ _p1##i = i++, ++_n1##i) #define cimg_for_in3X(img,x0,x1,x) cimg_for_in3((img)._width,x0,x1,x) #define cimg_for_in3Y(img,y0,y1,y) cimg_for_in3((img)._height,y0,y1,y) #define cimg_for_in3Z(img,z0,z1,z) cimg_for_in3((img)._depth,z0,z1,z) #define cimg_for_in3C(img,c0,c1,c) cimg_for_in3((img)._spectrum,c0,c1,c) #define cimg_for_in3XY(img,x0,y0,x1,y1,x,y) cimg_for_in3Y(img,y0,y1,y) cimg_for_in3X(img,x0,x1,x) #define cimg_for_in3XZ(img,x0,z0,x1,z1,x,z) cimg_for_in3Z(img,z0,z1,z) cimg_for_in3X(img,x0,x1,x) #define cimg_for_in3XC(img,x0,c0,x1,c1,x,c) cimg_for_in3C(img,c0,c1,c) cimg_for_in3X(img,x0,x1,x) #define cimg_for_in3YZ(img,y0,z0,y1,z1,y,z) cimg_for_in3Z(img,z0,z1,z) cimg_for_in3Y(img,y0,y1,y) #define cimg_for_in3YC(img,y0,c0,y1,c1,y,c) cimg_for_in3C(img,c0,c1,c) cimg_for_in3Y(img,y0,y1,y) #define cimg_for_in3ZC(img,z0,c0,z1,c1,z,c) cimg_for_in3C(img,c0,c1,c) cimg_for_in3Z(img,z0,z1,z) #define cimg_for_in3XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) cimg_for_in3Z(img,z0,z1,z) cimg_for_in3XY(img,x0,y0,x1,y1,x,y) #define cimg_for_in3XZC(img,x0,z0,c0,x1,y1,c1,x,z,c) cimg_for_in3C(img,c0,c1,c) cimg_for_in3XZ(img,x0,y0,x1,y1,x,z) #define cimg_for_in3YZC(img,y0,z0,c0,y1,z1,c1,y,z,c) cimg_for_in3C(img,c0,c1,c) cimg_for_in3YZ(img,y0,z0,y1,z1,y,z) #define cimg_for_in3XYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) \ cimg_for_in3C(img,c0,c1,c) cimg_for_in3XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for4(bound,i) \ for (int i = 0, _p1##i = 0, _n1##i = 1>=(bound)?(int)(bound) - 1:1, \ _n2##i = 2>=(bound)?(int)(bound) - 1:2; \ _n2##i<(int)(bound) || _n1##i==--_n2##i || i==(_n2##i = --_n1##i); \ _p1##i = i++, ++_n1##i, ++_n2##i) #define cimg_for4X(img,x) cimg_for4((img)._width,x) #define cimg_for4Y(img,y) cimg_for4((img)._height,y) #define cimg_for4Z(img,z) cimg_for4((img)._depth,z) #define cimg_for4C(img,c) cimg_for4((img)._spectrum,c) #define cimg_for4XY(img,x,y) cimg_for4Y(img,y) cimg_for4X(img,x) #define cimg_for4XZ(img,x,z) cimg_for4Z(img,z) cimg_for4X(img,x) #define cimg_for4XC(img,x,c) cimg_for4C(img,c) cimg_for4X(img,x) #define cimg_for4YZ(img,y,z) cimg_for4Z(img,z) cimg_for4Y(img,y) #define cimg_for4YC(img,y,c) cimg_for4C(img,c) cimg_for4Y(img,y) #define cimg_for4ZC(img,z,c) cimg_for4C(img,c) cimg_for4Z(img,z) #define cimg_for4XYZ(img,x,y,z) cimg_for4Z(img,z) cimg_for4XY(img,x,y) #define cimg_for4XZC(img,x,z,c) cimg_for4C(img,c) cimg_for4XZ(img,x,z) #define cimg_for4YZC(img,y,z,c) cimg_for4C(img,c) cimg_for4YZ(img,y,z) #define cimg_for4XYZC(img,x,y,z,c) cimg_for4C(img,c) cimg_for4XYZ(img,x,y,z) #define cimg_for_in4(bound,i0,i1,i) \ for (int i = (int)(i0)<0?0:(int)(i0), \ _p1##i = i - 1<0?0:i - 1, \ _n1##i = i + 1>=(int)(bound)?(int)(bound) - 1:i + 1, \ _n2##i = i + 2>=(int)(bound)?(int)(bound) - 1:i + 2; \ i<=(int)(i1) && (_n2##i<(int)(bound) || _n1##i==--_n2##i || i==(_n2##i = --_n1##i)); \ _p1##i = i++, ++_n1##i, ++_n2##i) #define cimg_for_in4X(img,x0,x1,x) cimg_for_in4((img)._width,x0,x1,x) #define cimg_for_in4Y(img,y0,y1,y) cimg_for_in4((img)._height,y0,y1,y) #define cimg_for_in4Z(img,z0,z1,z) cimg_for_in4((img)._depth,z0,z1,z) #define cimg_for_in4C(img,c0,c1,c) cimg_for_in4((img)._spectrum,c0,c1,c) #define cimg_for_in4XY(img,x0,y0,x1,y1,x,y) cimg_for_in4Y(img,y0,y1,y) cimg_for_in4X(img,x0,x1,x) #define cimg_for_in4XZ(img,x0,z0,x1,z1,x,z) cimg_for_in4Z(img,z0,z1,z) cimg_for_in4X(img,x0,x1,x) #define cimg_for_in4XC(img,x0,c0,x1,c1,x,c) cimg_for_in4C(img,c0,c1,c) cimg_for_in4X(img,x0,x1,x) #define cimg_for_in4YZ(img,y0,z0,y1,z1,y,z) cimg_for_in4Z(img,z0,z1,z) cimg_for_in4Y(img,y0,y1,y) #define cimg_for_in4YC(img,y0,c0,y1,c1,y,c) cimg_for_in4C(img,c0,c1,c) cimg_for_in4Y(img,y0,y1,y) #define cimg_for_in4ZC(img,z0,c0,z1,c1,z,c) cimg_for_in4C(img,c0,c1,c) cimg_for_in4Z(img,z0,z1,z) #define cimg_for_in4XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) cimg_for_in4Z(img,z0,z1,z) cimg_for_in4XY(img,x0,y0,x1,y1,x,y) #define cimg_for_in4XZC(img,x0,z0,c0,x1,y1,c1,x,z,c) cimg_for_in4C(img,c0,c1,c) cimg_for_in4XZ(img,x0,y0,x1,y1,x,z) #define cimg_for_in4YZC(img,y0,z0,c0,y1,z1,c1,y,z,c) cimg_for_in4C(img,c0,c1,c) cimg_for_in4YZ(img,y0,z0,y1,z1,y,z) #define cimg_for_in4XYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) \ cimg_for_in4C(img,c0,c1,c) cimg_for_in4XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for5(bound,i) \ for (int i = 0, _p2##i = 0, _p1##i = 0, \ _n1##i = 1>=(bound)?(int)(bound) - 1:1, \ _n2##i = 2>=(bound)?(int)(bound) - 1:2; \ _n2##i<(int)(bound) || _n1##i==--_n2##i || i==(_n2##i = --_n1##i); \ _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i) #define cimg_for5X(img,x) cimg_for5((img)._width,x) #define cimg_for5Y(img,y) cimg_for5((img)._height,y) #define cimg_for5Z(img,z) cimg_for5((img)._depth,z) #define cimg_for5C(img,c) cimg_for5((img)._spectrum,c) #define cimg_for5XY(img,x,y) cimg_for5Y(img,y) cimg_for5X(img,x) #define cimg_for5XZ(img,x,z) cimg_for5Z(img,z) cimg_for5X(img,x) #define cimg_for5XC(img,x,c) cimg_for5C(img,c) cimg_for5X(img,x) #define cimg_for5YZ(img,y,z) cimg_for5Z(img,z) cimg_for5Y(img,y) #define cimg_for5YC(img,y,c) cimg_for5C(img,c) cimg_for5Y(img,y) #define cimg_for5ZC(img,z,c) cimg_for5C(img,c) cimg_for5Z(img,z) #define cimg_for5XYZ(img,x,y,z) cimg_for5Z(img,z) cimg_for5XY(img,x,y) #define cimg_for5XZC(img,x,z,c) cimg_for5C(img,c) cimg_for5XZ(img,x,z) #define cimg_for5YZC(img,y,z,c) cimg_for5C(img,c) cimg_for5YZ(img,y,z) #define cimg_for5XYZC(img,x,y,z,c) cimg_for5C(img,c) cimg_for5XYZ(img,x,y,z) #define cimg_for_in5(bound,i0,i1,i) \ for (int i = (int)(i0)<0?0:(int)(i0), \ _p2##i = i - 2<0?0:i - 2, \ _p1##i = i - 1<0?0:i - 1, \ _n1##i = i + 1>=(int)(bound)?(int)(bound) - 1:i + 1, \ _n2##i = i + 2>=(int)(bound)?(int)(bound) - 1:i + 2; \ i<=(int)(i1) && (_n2##i<(int)(bound) || _n1##i==--_n2##i || i==(_n2##i = --_n1##i)); \ _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i) #define cimg_for_in5X(img,x0,x1,x) cimg_for_in5((img)._width,x0,x1,x) #define cimg_for_in5Y(img,y0,y1,y) cimg_for_in5((img)._height,y0,y1,y) #define cimg_for_in5Z(img,z0,z1,z) cimg_for_in5((img)._depth,z0,z1,z) #define cimg_for_in5C(img,c0,c1,c) cimg_for_in5((img)._spectrum,c0,c1,c) #define cimg_for_in5XY(img,x0,y0,x1,y1,x,y) cimg_for_in5Y(img,y0,y1,y) cimg_for_in5X(img,x0,x1,x) #define cimg_for_in5XZ(img,x0,z0,x1,z1,x,z) cimg_for_in5Z(img,z0,z1,z) cimg_for_in5X(img,x0,x1,x) #define cimg_for_in5XC(img,x0,c0,x1,c1,x,c) cimg_for_in5C(img,c0,c1,c) cimg_for_in5X(img,x0,x1,x) #define cimg_for_in5YZ(img,y0,z0,y1,z1,y,z) cimg_for_in5Z(img,z0,z1,z) cimg_for_in5Y(img,y0,y1,y) #define cimg_for_in5YC(img,y0,c0,y1,c1,y,c) cimg_for_in5C(img,c0,c1,c) cimg_for_in5Y(img,y0,y1,y) #define cimg_for_in5ZC(img,z0,c0,z1,c1,z,c) cimg_for_in5C(img,c0,c1,c) cimg_for_in5Z(img,z0,z1,z) #define cimg_for_in5XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) cimg_for_in5Z(img,z0,z1,z) cimg_for_in5XY(img,x0,y0,x1,y1,x,y) #define cimg_for_in5XZC(img,x0,z0,c0,x1,y1,c1,x,z,c) cimg_for_in5C(img,c0,c1,c) cimg_for_in5XZ(img,x0,y0,x1,y1,x,z) #define cimg_for_in5YZC(img,y0,z0,c0,y1,z1,c1,y,z,c) cimg_for_in5C(img,c0,c1,c) cimg_for_in5YZ(img,y0,z0,y1,z1,y,z) #define cimg_for_in5XYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) \ cimg_for_in5C(img,c0,c1,c) cimg_for_in5XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for6(bound,i) \ for (int i = 0, _p2##i = 0, _p1##i = 0, \ _n1##i = 1>=(bound)?(int)(bound) - 1:1, \ _n2##i = 2>=(bound)?(int)(bound) - 1:2, \ _n3##i = 3>=(bound)?(int)(bound) - 1:3; \ _n3##i<(int)(bound) || _n2##i==--_n3##i || _n1##i==--_n2##i || i==(_n3##i = _n2##i = --_n1##i); \ _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i, ++_n3##i) #define cimg_for6X(img,x) cimg_for6((img)._width,x) #define cimg_for6Y(img,y) cimg_for6((img)._height,y) #define cimg_for6Z(img,z) cimg_for6((img)._depth,z) #define cimg_for6C(img,c) cimg_for6((img)._spectrum,c) #define cimg_for6XY(img,x,y) cimg_for6Y(img,y) cimg_for6X(img,x) #define cimg_for6XZ(img,x,z) cimg_for6Z(img,z) cimg_for6X(img,x) #define cimg_for6XC(img,x,c) cimg_for6C(img,c) cimg_for6X(img,x) #define cimg_for6YZ(img,y,z) cimg_for6Z(img,z) cimg_for6Y(img,y) #define cimg_for6YC(img,y,c) cimg_for6C(img,c) cimg_for6Y(img,y) #define cimg_for6ZC(img,z,c) cimg_for6C(img,c) cimg_for6Z(img,z) #define cimg_for6XYZ(img,x,y,z) cimg_for6Z(img,z) cimg_for6XY(img,x,y) #define cimg_for6XZC(img,x,z,c) cimg_for6C(img,c) cimg_for6XZ(img,x,z) #define cimg_for6YZC(img,y,z,c) cimg_for6C(img,c) cimg_for6YZ(img,y,z) #define cimg_for6XYZC(img,x,y,z,c) cimg_for6C(img,c) cimg_for6XYZ(img,x,y,z) #define cimg_for_in6(bound,i0,i1,i) \ for (int i = (int)(i0)<0?0:(int)(i0), \ _p2##i = i - 2<0?0:i - 2, \ _p1##i = i - 1<0?0:i - 1, \ _n1##i = i + 1>=(int)(bound)?(int)(bound) - 1:i + 1, \ _n2##i = i + 2>=(int)(bound)?(int)(bound) - 1:i + 2, \ _n3##i = i + 3>=(int)(bound)?(int)(bound) - 1:i + 3; \ i<=(int)(i1) && \ (_n3##i<(int)(bound) || _n2##i==--_n3##i || _n1##i==--_n2##i || i==(_n3##i = _n2##i = --_n1##i)); \ _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i, ++_n3##i) #define cimg_for_in6X(img,x0,x1,x) cimg_for_in6((img)._width,x0,x1,x) #define cimg_for_in6Y(img,y0,y1,y) cimg_for_in6((img)._height,y0,y1,y) #define cimg_for_in6Z(img,z0,z1,z) cimg_for_in6((img)._depth,z0,z1,z) #define cimg_for_in6C(img,c0,c1,c) cimg_for_in6((img)._spectrum,c0,c1,c) #define cimg_for_in6XY(img,x0,y0,x1,y1,x,y) cimg_for_in6Y(img,y0,y1,y) cimg_for_in6X(img,x0,x1,x) #define cimg_for_in6XZ(img,x0,z0,x1,z1,x,z) cimg_for_in6Z(img,z0,z1,z) cimg_for_in6X(img,x0,x1,x) #define cimg_for_in6XC(img,x0,c0,x1,c1,x,c) cimg_for_in6C(img,c0,c1,c) cimg_for_in6X(img,x0,x1,x) #define cimg_for_in6YZ(img,y0,z0,y1,z1,y,z) cimg_for_in6Z(img,z0,z1,z) cimg_for_in6Y(img,y0,y1,y) #define cimg_for_in6YC(img,y0,c0,y1,c1,y,c) cimg_for_in6C(img,c0,c1,c) cimg_for_in6Y(img,y0,y1,y) #define cimg_for_in6ZC(img,z0,c0,z1,c1,z,c) cimg_for_in6C(img,c0,c1,c) cimg_for_in6Z(img,z0,z1,z) #define cimg_for_in6XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) cimg_for_in6Z(img,z0,z1,z) cimg_for_in6XY(img,x0,y0,x1,y1,x,y) #define cimg_for_in6XZC(img,x0,z0,c0,x1,y1,c1,x,z,c) cimg_for_in6C(img,c0,c1,c) cimg_for_in6XZ(img,x0,y0,x1,y1,x,z) #define cimg_for_in6YZC(img,y0,z0,c0,y1,z1,c1,y,z,c) cimg_for_in6C(img,c0,c1,c) cimg_for_in6YZ(img,y0,z0,y1,z1,y,z) #define cimg_for_in6XYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) \ cimg_for_in6C(img,c0,c1,c) cimg_for_in6XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for7(bound,i) \ for (int i = 0, _p3##i = 0, _p2##i = 0, _p1##i = 0, \ _n1##i = 1>=(bound)?(int)(bound) - 1:1, \ _n2##i = 2>=(bound)?(int)(bound) - 1:2, \ _n3##i = 3>=(bound)?(int)(bound) - 1:3; \ _n3##i<(int)(bound) || _n2##i==--_n3##i || _n1##i==--_n2##i || i==(_n3##i = _n2##i = --_n1##i); \ _p3##i = _p2##i, _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i, ++_n3##i) #define cimg_for7X(img,x) cimg_for7((img)._width,x) #define cimg_for7Y(img,y) cimg_for7((img)._height,y) #define cimg_for7Z(img,z) cimg_for7((img)._depth,z) #define cimg_for7C(img,c) cimg_for7((img)._spectrum,c) #define cimg_for7XY(img,x,y) cimg_for7Y(img,y) cimg_for7X(img,x) #define cimg_for7XZ(img,x,z) cimg_for7Z(img,z) cimg_for7X(img,x) #define cimg_for7XC(img,x,c) cimg_for7C(img,c) cimg_for7X(img,x) #define cimg_for7YZ(img,y,z) cimg_for7Z(img,z) cimg_for7Y(img,y) #define cimg_for7YC(img,y,c) cimg_for7C(img,c) cimg_for7Y(img,y) #define cimg_for7ZC(img,z,c) cimg_for7C(img,c) cimg_for7Z(img,z) #define cimg_for7XYZ(img,x,y,z) cimg_for7Z(img,z) cimg_for7XY(img,x,y) #define cimg_for7XZC(img,x,z,c) cimg_for7C(img,c) cimg_for7XZ(img,x,z) #define cimg_for7YZC(img,y,z,c) cimg_for7C(img,c) cimg_for7YZ(img,y,z) #define cimg_for7XYZC(img,x,y,z,c) cimg_for7C(img,c) cimg_for7XYZ(img,x,y,z) #define cimg_for_in7(bound,i0,i1,i) \ for (int i = (int)(i0)<0?0:(int)(i0), \ _p3##i = i - 3<0?0:i - 3, \ _p2##i = i - 2<0?0:i - 2, \ _p1##i = i - 1<0?0:i - 1, \ _n1##i = i + 1>=(int)(bound)?(int)(bound) - 1:i + 1, \ _n2##i = i + 2>=(int)(bound)?(int)(bound) - 1:i + 2, \ _n3##i = i + 3>=(int)(bound)?(int)(bound) - 1:i + 3; \ i<=(int)(i1) && \ (_n3##i<(int)(bound) || _n2##i==--_n3##i || _n1##i==--_n2##i || i==(_n3##i = _n2##i = --_n1##i)); \ _p3##i = _p2##i, _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i, ++_n3##i) #define cimg_for_in7X(img,x0,x1,x) cimg_for_in7((img)._width,x0,x1,x) #define cimg_for_in7Y(img,y0,y1,y) cimg_for_in7((img)._height,y0,y1,y) #define cimg_for_in7Z(img,z0,z1,z) cimg_for_in7((img)._depth,z0,z1,z) #define cimg_for_in7C(img,c0,c1,c) cimg_for_in7((img)._spectrum,c0,c1,c) #define cimg_for_in7XY(img,x0,y0,x1,y1,x,y) cimg_for_in7Y(img,y0,y1,y) cimg_for_in7X(img,x0,x1,x) #define cimg_for_in7XZ(img,x0,z0,x1,z1,x,z) cimg_for_in7Z(img,z0,z1,z) cimg_for_in7X(img,x0,x1,x) #define cimg_for_in7XC(img,x0,c0,x1,c1,x,c) cimg_for_in7C(img,c0,c1,c) cimg_for_in7X(img,x0,x1,x) #define cimg_for_in7YZ(img,y0,z0,y1,z1,y,z) cimg_for_in7Z(img,z0,z1,z) cimg_for_in7Y(img,y0,y1,y) #define cimg_for_in7YC(img,y0,c0,y1,c1,y,c) cimg_for_in7C(img,c0,c1,c) cimg_for_in7Y(img,y0,y1,y) #define cimg_for_in7ZC(img,z0,c0,z1,c1,z,c) cimg_for_in7C(img,c0,c1,c) cimg_for_in7Z(img,z0,z1,z) #define cimg_for_in7XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) cimg_for_in7Z(img,z0,z1,z) cimg_for_in7XY(img,x0,y0,x1,y1,x,y) #define cimg_for_in7XZC(img,x0,z0,c0,x1,y1,c1,x,z,c) cimg_for_in7C(img,c0,c1,c) cimg_for_in7XZ(img,x0,y0,x1,y1,x,z) #define cimg_for_in7YZC(img,y0,z0,c0,y1,z1,c1,y,z,c) cimg_for_in7C(img,c0,c1,c) cimg_for_in7YZ(img,y0,z0,y1,z1,y,z) #define cimg_for_in7XYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) \ cimg_for_in7C(img,c0,c1,c) cimg_for_in7XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for8(bound,i) \ for (int i = 0, _p3##i = 0, _p2##i = 0, _p1##i = 0, \ _n1##i = 1>=(bound)?(int)(bound) - 1:1, \ _n2##i = 2>=(bound)?(int)(bound) - 1:2, \ _n3##i = 3>=(bound)?(int)(bound) - 1:3, \ _n4##i = 4>=(bound)?(int)(bound) - 1:4; \ _n4##i<(int)(bound) || _n3##i==--_n4##i || _n2##i==--_n3##i || _n1##i==--_n2##i || \ i==(_n4##i = _n3##i = _n2##i = --_n1##i); \ _p3##i = _p2##i, _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i, ++_n3##i, ++_n4##i) #define cimg_for8X(img,x) cimg_for8((img)._width,x) #define cimg_for8Y(img,y) cimg_for8((img)._height,y) #define cimg_for8Z(img,z) cimg_for8((img)._depth,z) #define cimg_for8C(img,c) cimg_for8((img)._spectrum,c) #define cimg_for8XY(img,x,y) cimg_for8Y(img,y) cimg_for8X(img,x) #define cimg_for8XZ(img,x,z) cimg_for8Z(img,z) cimg_for8X(img,x) #define cimg_for8XC(img,x,c) cimg_for8C(img,c) cimg_for8X(img,x) #define cimg_for8YZ(img,y,z) cimg_for8Z(img,z) cimg_for8Y(img,y) #define cimg_for8YC(img,y,c) cimg_for8C(img,c) cimg_for8Y(img,y) #define cimg_for8ZC(img,z,c) cimg_for8C(img,c) cimg_for8Z(img,z) #define cimg_for8XYZ(img,x,y,z) cimg_for8Z(img,z) cimg_for8XY(img,x,y) #define cimg_for8XZC(img,x,z,c) cimg_for8C(img,c) cimg_for8XZ(img,x,z) #define cimg_for8YZC(img,y,z,c) cimg_for8C(img,c) cimg_for8YZ(img,y,z) #define cimg_for8XYZC(img,x,y,z,c) cimg_for8C(img,c) cimg_for8XYZ(img,x,y,z) #define cimg_for_in8(bound,i0,i1,i) \ for (int i = (int)(i0)<0?0:(int)(i0), \ _p3##i = i - 3<0?0:i - 3, \ _p2##i = i - 2<0?0:i - 2, \ _p1##i = i - 1<0?0:i - 1, \ _n1##i = i + 1>=(int)(bound)?(int)(bound) - 1:i + 1, \ _n2##i = i + 2>=(int)(bound)?(int)(bound) - 1:i + 2, \ _n3##i = i + 3>=(int)(bound)?(int)(bound) - 1:i + 3, \ _n4##i = i + 4>=(int)(bound)?(int)(bound) - 1:i + 4; \ i<=(int)(i1) && (_n4##i<(int)(bound) || _n3##i==--_n4##i || _n2##i==--_n3##i || _n1##i==--_n2##i || \ i==(_n4##i = _n3##i = _n2##i = --_n1##i)); \ _p3##i = _p2##i, _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i, ++_n3##i, ++_n4##i) #define cimg_for_in8X(img,x0,x1,x) cimg_for_in8((img)._width,x0,x1,x) #define cimg_for_in8Y(img,y0,y1,y) cimg_for_in8((img)._height,y0,y1,y) #define cimg_for_in8Z(img,z0,z1,z) cimg_for_in8((img)._depth,z0,z1,z) #define cimg_for_in8C(img,c0,c1,c) cimg_for_in8((img)._spectrum,c0,c1,c) #define cimg_for_in8XY(img,x0,y0,x1,y1,x,y) cimg_for_in8Y(img,y0,y1,y) cimg_for_in8X(img,x0,x1,x) #define cimg_for_in8XZ(img,x0,z0,x1,z1,x,z) cimg_for_in8Z(img,z0,z1,z) cimg_for_in8X(img,x0,x1,x) #define cimg_for_in8XC(img,x0,c0,x1,c1,x,c) cimg_for_in8C(img,c0,c1,c) cimg_for_in8X(img,x0,x1,x) #define cimg_for_in8YZ(img,y0,z0,y1,z1,y,z) cimg_for_in8Z(img,z0,z1,z) cimg_for_in8Y(img,y0,y1,y) #define cimg_for_in8YC(img,y0,c0,y1,c1,y,c) cimg_for_in8C(img,c0,c1,c) cimg_for_in8Y(img,y0,y1,y) #define cimg_for_in8ZC(img,z0,c0,z1,c1,z,c) cimg_for_in8C(img,c0,c1,c) cimg_for_in8Z(img,z0,z1,z) #define cimg_for_in8XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) cimg_for_in8Z(img,z0,z1,z) cimg_for_in8XY(img,x0,y0,x1,y1,x,y) #define cimg_for_in8XZC(img,x0,z0,c0,x1,y1,c1,x,z,c) cimg_for_in8C(img,c0,c1,c) cimg_for_in8XZ(img,x0,y0,x1,y1,x,z) #define cimg_for_in8YZC(img,y0,z0,c0,y1,z1,c1,y,z,c) cimg_for_in8C(img,c0,c1,c) cimg_for_in8YZ(img,y0,z0,y1,z1,y,z) #define cimg_for_in8XYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) \ cimg_for_in8C(img,c0,c1,c) cimg_for_in8XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for9(bound,i) \ for (int i = 0, _p4##i = 0, _p3##i = 0, _p2##i = 0, _p1##i = 0, \ _n1##i = 1>=(int)(bound)?(int)(bound) - 1:1, \ _n2##i = 2>=(int)(bound)?(int)(bound) - 1:2, \ _n3##i = 3>=(int)(bound)?(int)(bound) - 1:3, \ _n4##i = 4>=(int)(bound)?(int)(bound) - 1:4; \ _n4##i<(int)(bound) || _n3##i==--_n4##i || _n2##i==--_n3##i || _n1##i==--_n2##i || \ i==(_n4##i = _n3##i = _n2##i = --_n1##i); \ _p4##i = _p3##i, _p3##i = _p2##i, _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i, ++_n3##i, ++_n4##i) #define cimg_for9X(img,x) cimg_for9((img)._width,x) #define cimg_for9Y(img,y) cimg_for9((img)._height,y) #define cimg_for9Z(img,z) cimg_for9((img)._depth,z) #define cimg_for9C(img,c) cimg_for9((img)._spectrum,c) #define cimg_for9XY(img,x,y) cimg_for9Y(img,y) cimg_for9X(img,x) #define cimg_for9XZ(img,x,z) cimg_for9Z(img,z) cimg_for9X(img,x) #define cimg_for9XC(img,x,c) cimg_for9C(img,c) cimg_for9X(img,x) #define cimg_for9YZ(img,y,z) cimg_for9Z(img,z) cimg_for9Y(img,y) #define cimg_for9YC(img,y,c) cimg_for9C(img,c) cimg_for9Y(img,y) #define cimg_for9ZC(img,z,c) cimg_for9C(img,c) cimg_for9Z(img,z) #define cimg_for9XYZ(img,x,y,z) cimg_for9Z(img,z) cimg_for9XY(img,x,y) #define cimg_for9XZC(img,x,z,c) cimg_for9C(img,c) cimg_for9XZ(img,x,z) #define cimg_for9YZC(img,y,z,c) cimg_for9C(img,c) cimg_for9YZ(img,y,z) #define cimg_for9XYZC(img,x,y,z,c) cimg_for9C(img,c) cimg_for9XYZ(img,x,y,z) #define cimg_for_in9(bound,i0,i1,i) \ for (int i = (int)(i0)<0?0:(int)(i0), \ _p4##i = i - 4<0?0:i - 4, \ _p3##i = i - 3<0?0:i - 3, \ _p2##i = i - 2<0?0:i - 2, \ _p1##i = i - 1<0?0:i - 1, \ _n1##i = i + 1>=(int)(bound)?(int)(bound) - 1:i + 1, \ _n2##i = i + 2>=(int)(bound)?(int)(bound) - 1:i + 2, \ _n3##i = i + 3>=(int)(bound)?(int)(bound) - 1:i + 3, \ _n4##i = i + 4>=(int)(bound)?(int)(bound) - 1:i + 4; \ i<=(int)(i1) && (_n4##i<(int)(bound) || _n3##i==--_n4##i || _n2##i==--_n3##i || _n1##i==--_n2##i || \ i==(_n4##i = _n3##i = _n2##i = --_n1##i)); \ _p4##i = _p3##i, _p3##i = _p2##i, _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i, ++_n3##i, ++_n4##i) #define cimg_for_in9X(img,x0,x1,x) cimg_for_in9((img)._width,x0,x1,x) #define cimg_for_in9Y(img,y0,y1,y) cimg_for_in9((img)._height,y0,y1,y) #define cimg_for_in9Z(img,z0,z1,z) cimg_for_in9((img)._depth,z0,z1,z) #define cimg_for_in9C(img,c0,c1,c) cimg_for_in9((img)._spectrum,c0,c1,c) #define cimg_for_in9XY(img,x0,y0,x1,y1,x,y) cimg_for_in9Y(img,y0,y1,y) cimg_for_in9X(img,x0,x1,x) #define cimg_for_in9XZ(img,x0,z0,x1,z1,x,z) cimg_for_in9Z(img,z0,z1,z) cimg_for_in9X(img,x0,x1,x) #define cimg_for_in9XC(img,x0,c0,x1,c1,x,c) cimg_for_in9C(img,c0,c1,c) cimg_for_in9X(img,x0,x1,x) #define cimg_for_in9YZ(img,y0,z0,y1,z1,y,z) cimg_for_in9Z(img,z0,z1,z) cimg_for_in9Y(img,y0,y1,y) #define cimg_for_in9YC(img,y0,c0,y1,c1,y,c) cimg_for_in9C(img,c0,c1,c) cimg_for_in9Y(img,y0,y1,y) #define cimg_for_in9ZC(img,z0,c0,z1,c1,z,c) cimg_for_in9C(img,c0,c1,c) cimg_for_in9Z(img,z0,z1,z) #define cimg_for_in9XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) cimg_for_in9Z(img,z0,z1,z) cimg_for_in9XY(img,x0,y0,x1,y1,x,y) #define cimg_for_in9XZC(img,x0,z0,c0,x1,y1,c1,x,z,c) cimg_for_in9C(img,c0,c1,c) cimg_for_in9XZ(img,x0,y0,x1,y1,x,z) #define cimg_for_in9YZC(img,y0,z0,c0,y1,z1,c1,y,z,c) cimg_for_in9C(img,c0,c1,c) cimg_for_in9YZ(img,y0,z0,y1,z1,y,z) #define cimg_for_in9XYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) \ cimg_for_in9C(img,c0,c1,c) cimg_for_in9XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for2x2(img,x,y,z,c,I,T) \ cimg_for2((img)._height,y) for (int x = 0, \ _n1##x = (int)( \ (I[0] = (T)(img)(0,y,z,c)), \ (I[2] = (T)(img)(0,_n1##y,z,c)), \ 1>=(img)._width?(img).width() - 1:1); \ (_n1##x<(img).width() && ( \ (I[1] = (T)(img)(_n1##x,y,z,c)), \ (I[3] = (T)(img)(_n1##x,_n1##y,z,c)),1)) || \ x==--_n1##x; \ I[0] = I[1], \ I[2] = I[3], \ ++x, ++_n1##x) #define cimg_for_in2x2(img,x0,y0,x1,y1,x,y,z,c,I,T) \ cimg_for_in2((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)(x0), \ _n1##x = (int)( \ (I[0] = (T)(img)(x,y,z,c)), \ (I[2] = (T)(img)(x,_n1##y,z,c)), \ x + 1>=(int)(img)._width?(img).width() - 1:x + 1); \ x<=(int)(x1) && ((_n1##x<(img).width() && ( \ (I[1] = (T)(img)(_n1##x,y,z,c)), \ (I[3] = (T)(img)(_n1##x,_n1##y,z,c)),1)) || \ x==--_n1##x); \ I[0] = I[1], \ I[2] = I[3], \ ++x, ++_n1##x) #define cimg_for3x3(img,x,y,z,c,I,T) \ cimg_for3((img)._height,y) for (int x = 0, \ _p1##x = 0, \ _n1##x = (int)( \ (I[0] = I[1] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[3] = I[4] = (T)(img)(0,y,z,c)), \ (I[6] = I[7] = (T)(img)(0,_n1##y,z,c)), \ 1>=(img)._width?(img).width() - 1:1); \ (_n1##x<(img).width() && ( \ (I[2] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[5] = (T)(img)(_n1##x,y,z,c)), \ (I[8] = (T)(img)(_n1##x,_n1##y,z,c)),1)) || \ x==--_n1##x; \ I[0] = I[1], I[1] = I[2], \ I[3] = I[4], I[4] = I[5], \ I[6] = I[7], I[7] = I[8], \ _p1##x = x++, ++_n1##x) #define cimg_for_in3x3(img,x0,y0,x1,y1,x,y,z,c,I,T) \ cimg_for_in3((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)(x0), \ _p1##x = x - 1<0?0:x - 1, \ _n1##x = (int)( \ (I[0] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[3] = (T)(img)(_p1##x,y,z,c)), \ (I[6] = (T)(img)(_p1##x,_n1##y,z,c)), \ (I[1] = (T)(img)(x,_p1##y,z,c)), \ (I[4] = (T)(img)(x,y,z,c)), \ (I[7] = (T)(img)(x,_n1##y,z,c)), \ x + 1>=(int)(img)._width?(img).width() - 1:x + 1); \ x<=(int)(x1) && ((_n1##x<(img).width() && ( \ (I[2] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[5] = (T)(img)(_n1##x,y,z,c)), \ (I[8] = (T)(img)(_n1##x,_n1##y,z,c)),1)) || \ x==--_n1##x); \ I[0] = I[1], I[1] = I[2], \ I[3] = I[4], I[4] = I[5], \ I[6] = I[7], I[7] = I[8], \ _p1##x = x++, ++_n1##x) #define cimg_for4x4(img,x,y,z,c,I,T) \ cimg_for4((img)._height,y) for (int x = 0, \ _p1##x = 0, \ _n1##x = 1>=(img)._width?(img).width() - 1:1, \ _n2##x = (int)( \ (I[0] = I[1] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[4] = I[5] = (T)(img)(0,y,z,c)), \ (I[8] = I[9] = (T)(img)(0,_n1##y,z,c)), \ (I[12] = I[13] = (T)(img)(0,_n2##y,z,c)), \ (I[2] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[6] = (T)(img)(_n1##x,y,z,c)), \ (I[10] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[14] = (T)(img)(_n1##x,_n2##y,z,c)), \ 2>=(img)._width?(img).width() - 1:2); \ (_n2##x<(img).width() && ( \ (I[3] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[7] = (T)(img)(_n2##x,y,z,c)), \ (I[11] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[15] = (T)(img)(_n2##x,_n2##y,z,c)),1)) || \ _n1##x==--_n2##x || x==(_n2##x = --_n1##x); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], \ I[4] = I[5], I[5] = I[6], I[6] = I[7], \ I[8] = I[9], I[9] = I[10], I[10] = I[11], \ I[12] = I[13], I[13] = I[14], I[14] = I[15], \ _p1##x = x++, ++_n1##x, ++_n2##x) #define cimg_for_in4x4(img,x0,y0,x1,y1,x,y,z,c,I,T) \ cimg_for_in4((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)(x0), \ _p1##x = x - 1<0?0:x - 1, \ _n1##x = x + 1>=(int)(img)._width?(img).width() - 1:x + 1, \ _n2##x = (int)( \ (I[0] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[4] = (T)(img)(_p1##x,y,z,c)), \ (I[8] = (T)(img)(_p1##x,_n1##y,z,c)), \ (I[12] = (T)(img)(_p1##x,_n2##y,z,c)), \ (I[1] = (T)(img)(x,_p1##y,z,c)), \ (I[5] = (T)(img)(x,y,z,c)), \ (I[9] = (T)(img)(x,_n1##y,z,c)), \ (I[13] = (T)(img)(x,_n2##y,z,c)), \ (I[2] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[6] = (T)(img)(_n1##x,y,z,c)), \ (I[10] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[14] = (T)(img)(_n1##x,_n2##y,z,c)), \ x + 2>=(int)(img)._width?(img).width() - 1:x + 2); \ x<=(int)(x1) && ((_n2##x<(img).width() && ( \ (I[3] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[7] = (T)(img)(_n2##x,y,z,c)), \ (I[11] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[15] = (T)(img)(_n2##x,_n2##y,z,c)),1)) || \ _n1##x==--_n2##x || x==(_n2##x = --_n1##x)); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], \ I[4] = I[5], I[5] = I[6], I[6] = I[7], \ I[8] = I[9], I[9] = I[10], I[10] = I[11], \ I[12] = I[13], I[13] = I[14], I[14] = I[15], \ _p1##x = x++, ++_n1##x, ++_n2##x) #define cimg_for5x5(img,x,y,z,c,I,T) \ cimg_for5((img)._height,y) for (int x = 0, \ _p2##x = 0, _p1##x = 0, \ _n1##x = 1>=(img)._width?(img).width() - 1:1, \ _n2##x = (int)( \ (I[0] = I[1] = I[2] = (T)(img)(_p2##x,_p2##y,z,c)), \ (I[5] = I[6] = I[7] = (T)(img)(0,_p1##y,z,c)), \ (I[10] = I[11] = I[12] = (T)(img)(0,y,z,c)), \ (I[15] = I[16] = I[17] = (T)(img)(0,_n1##y,z,c)), \ (I[20] = I[21] = I[22] = (T)(img)(0,_n2##y,z,c)), \ (I[3] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[8] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[13] = (T)(img)(_n1##x,y,z,c)), \ (I[18] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[23] = (T)(img)(_n1##x,_n2##y,z,c)), \ 2>=(img)._width?(img).width() - 1:2); \ (_n2##x<(img).width() && ( \ (I[4] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[9] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[14] = (T)(img)(_n2##x,y,z,c)), \ (I[19] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[24] = (T)(img)(_n2##x,_n2##y,z,c)),1)) || \ _n1##x==--_n2##x || x==(_n2##x = --_n1##x); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], \ I[5] = I[6], I[6] = I[7], I[7] = I[8], I[8] = I[9], \ I[10] = I[11], I[11] = I[12], I[12] = I[13], I[13] = I[14], \ I[15] = I[16], I[16] = I[17], I[17] = I[18], I[18] = I[19], \ I[20] = I[21], I[21] = I[22], I[22] = I[23], I[23] = I[24], \ _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x) #define cimg_for_in5x5(img,x0,y0,x1,y1,x,y,z,c,I,T) \ cimg_for_in5((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)(x0), \ _p2##x = x - 2<0?0:x - 2, \ _p1##x = x - 1<0?0:x - 1, \ _n1##x = x + 1>=(int)(img)._width?(img).width() - 1:x + 1, \ _n2##x = (int)( \ (I[0] = (T)(img)(_p2##x,_p2##y,z,c)), \ (I[5] = (T)(img)(_p2##x,_p1##y,z,c)), \ (I[10] = (T)(img)(_p2##x,y,z,c)), \ (I[15] = (T)(img)(_p2##x,_n1##y,z,c)), \ (I[20] = (T)(img)(_p2##x,_n2##y,z,c)), \ (I[1] = (T)(img)(_p1##x,_p2##y,z,c)), \ (I[6] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[11] = (T)(img)(_p1##x,y,z,c)), \ (I[16] = (T)(img)(_p1##x,_n1##y,z,c)), \ (I[21] = (T)(img)(_p1##x,_n2##y,z,c)), \ (I[2] = (T)(img)(x,_p2##y,z,c)), \ (I[7] = (T)(img)(x,_p1##y,z,c)), \ (I[12] = (T)(img)(x,y,z,c)), \ (I[17] = (T)(img)(x,_n1##y,z,c)), \ (I[22] = (T)(img)(x,_n2##y,z,c)), \ (I[3] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[8] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[13] = (T)(img)(_n1##x,y,z,c)), \ (I[18] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[23] = (T)(img)(_n1##x,_n2##y,z,c)), \ x + 2>=(int)(img)._width?(img).width() - 1:x + 2); \ x<=(int)(x1) && ((_n2##x<(img).width() && ( \ (I[4] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[9] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[14] = (T)(img)(_n2##x,y,z,c)), \ (I[19] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[24] = (T)(img)(_n2##x,_n2##y,z,c)),1)) || \ _n1##x==--_n2##x || x==(_n2##x = --_n1##x)); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], \ I[5] = I[6], I[6] = I[7], I[7] = I[8], I[8] = I[9], \ I[10] = I[11], I[11] = I[12], I[12] = I[13], I[13] = I[14], \ I[15] = I[16], I[16] = I[17], I[17] = I[18], I[18] = I[19], \ I[20] = I[21], I[21] = I[22], I[22] = I[23], I[23] = I[24], \ _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x) #define cimg_for6x6(img,x,y,z,c,I,T) \ cimg_for6((img)._height,y) for (int x = 0, \ _p2##x = 0, _p1##x = 0, \ _n1##x = 1>=(img)._width?(img).width() - 1:1, \ _n2##x = 2>=(img)._width?(img).width() - 1:2, \ _n3##x = (int)( \ (I[0] = I[1] = I[2] = (T)(img)(_p2##x,_p2##y,z,c)), \ (I[6] = I[7] = I[8] = (T)(img)(0,_p1##y,z,c)), \ (I[12] = I[13] = I[14] = (T)(img)(0,y,z,c)), \ (I[18] = I[19] = I[20] = (T)(img)(0,_n1##y,z,c)), \ (I[24] = I[25] = I[26] = (T)(img)(0,_n2##y,z,c)), \ (I[30] = I[31] = I[32] = (T)(img)(0,_n3##y,z,c)), \ (I[3] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[9] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[15] = (T)(img)(_n1##x,y,z,c)), \ (I[21] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[27] = (T)(img)(_n1##x,_n2##y,z,c)), \ (I[33] = (T)(img)(_n1##x,_n3##y,z,c)), \ (I[4] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[10] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[16] = (T)(img)(_n2##x,y,z,c)), \ (I[22] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[28] = (T)(img)(_n2##x,_n2##y,z,c)), \ (I[34] = (T)(img)(_n2##x,_n3##y,z,c)), \ 3>=(img)._width?(img).width() - 1:3); \ (_n3##x<(img).width() && ( \ (I[5] = (T)(img)(_n3##x,_p2##y,z,c)), \ (I[11] = (T)(img)(_n3##x,_p1##y,z,c)), \ (I[17] = (T)(img)(_n3##x,y,z,c)), \ (I[23] = (T)(img)(_n3##x,_n1##y,z,c)), \ (I[29] = (T)(img)(_n3##x,_n2##y,z,c)), \ (I[35] = (T)(img)(_n3##x,_n3##y,z,c)),1)) || \ _n2##x==--_n3##x || _n1##x==--_n2##x || x==(_n3## x = _n2##x = --_n1##x); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], I[4] = I[5], \ I[6] = I[7], I[7] = I[8], I[8] = I[9], I[9] = I[10], I[10] = I[11], \ I[12] = I[13], I[13] = I[14], I[14] = I[15], I[15] = I[16], I[16] = I[17], \ I[18] = I[19], I[19] = I[20], I[20] = I[21], I[21] = I[22], I[22] = I[23], \ I[24] = I[25], I[25] = I[26], I[26] = I[27], I[27] = I[28], I[28] = I[29], \ I[30] = I[31], I[31] = I[32], I[32] = I[33], I[33] = I[34], I[34] = I[35], \ _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x, ++_n3##x) #define cimg_for_in6x6(img,x0,y0,x1,y1,x,y,z,c,I,T) \ cimg_for_in6((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)x0, \ _p2##x = x - 2<0?0:x - 2, \ _p1##x = x - 1<0?0:x - 1, \ _n1##x = x + 1>=(int)(img)._width?(img).width() - 1:x + 1, \ _n2##x = x + 2>=(int)(img)._width?(img).width() - 1:x + 2, \ _n3##x = (int)( \ (I[0] = (T)(img)(_p2##x,_p2##y,z,c)), \ (I[6] = (T)(img)(_p2##x,_p1##y,z,c)), \ (I[12] = (T)(img)(_p2##x,y,z,c)), \ (I[18] = (T)(img)(_p2##x,_n1##y,z,c)), \ (I[24] = (T)(img)(_p2##x,_n2##y,z,c)), \ (I[30] = (T)(img)(_p2##x,_n3##y,z,c)), \ (I[1] = (T)(img)(_p1##x,_p2##y,z,c)), \ (I[7] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[13] = (T)(img)(_p1##x,y,z,c)), \ (I[19] = (T)(img)(_p1##x,_n1##y,z,c)), \ (I[25] = (T)(img)(_p1##x,_n2##y,z,c)), \ (I[31] = (T)(img)(_p1##x,_n3##y,z,c)), \ (I[2] = (T)(img)(x,_p2##y,z,c)), \ (I[8] = (T)(img)(x,_p1##y,z,c)), \ (I[14] = (T)(img)(x,y,z,c)), \ (I[20] = (T)(img)(x,_n1##y,z,c)), \ (I[26] = (T)(img)(x,_n2##y,z,c)), \ (I[32] = (T)(img)(x,_n3##y,z,c)), \ (I[3] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[9] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[15] = (T)(img)(_n1##x,y,z,c)), \ (I[21] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[27] = (T)(img)(_n1##x,_n2##y,z,c)), \ (I[33] = (T)(img)(_n1##x,_n3##y,z,c)), \ (I[4] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[10] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[16] = (T)(img)(_n2##x,y,z,c)), \ (I[22] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[28] = (T)(img)(_n2##x,_n2##y,z,c)), \ (I[34] = (T)(img)(_n2##x,_n3##y,z,c)), \ x + 3>=(int)(img)._width?(img).width() - 1:x + 3); \ x<=(int)(x1) && ((_n3##x<(img).width() && ( \ (I[5] = (T)(img)(_n3##x,_p2##y,z,c)), \ (I[11] = (T)(img)(_n3##x,_p1##y,z,c)), \ (I[17] = (T)(img)(_n3##x,y,z,c)), \ (I[23] = (T)(img)(_n3##x,_n1##y,z,c)), \ (I[29] = (T)(img)(_n3##x,_n2##y,z,c)), \ (I[35] = (T)(img)(_n3##x,_n3##y,z,c)),1)) || \ _n2##x==--_n3##x || _n1##x==--_n2##x || x==(_n3## x = _n2##x = --_n1##x)); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], I[4] = I[5], \ I[6] = I[7], I[7] = I[8], I[8] = I[9], I[9] = I[10], I[10] = I[11], \ I[12] = I[13], I[13] = I[14], I[14] = I[15], I[15] = I[16], I[16] = I[17], \ I[18] = I[19], I[19] = I[20], I[20] = I[21], I[21] = I[22], I[22] = I[23], \ I[24] = I[25], I[25] = I[26], I[26] = I[27], I[27] = I[28], I[28] = I[29], \ I[30] = I[31], I[31] = I[32], I[32] = I[33], I[33] = I[34], I[34] = I[35], \ _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x, ++_n3##x) #define cimg_for7x7(img,x,y,z,c,I,T) \ cimg_for7((img)._height,y) for (int x = 0, \ _p3##x = 0, _p2##x = 0, _p1##x = 0, \ _n1##x = 1>=(img)._width?(img).width() - 1:1, \ _n2##x = 2>=(img)._width?(img).width() - 1:2, \ _n3##x = (int)( \ (I[0] = I[1] = I[2] = I[3] = (T)(img)(_p3##x,_p3##y,z,c)), \ (I[7] = I[8] = I[9] = I[10] = (T)(img)(0,_p2##y,z,c)), \ (I[14] = I[15] = I[16] = I[17] = (T)(img)(0,_p1##y,z,c)), \ (I[21] = I[22] = I[23] = I[24] = (T)(img)(0,y,z,c)), \ (I[28] = I[29] = I[30] = I[31] = (T)(img)(0,_n1##y,z,c)), \ (I[35] = I[36] = I[37] = I[38] = (T)(img)(0,_n2##y,z,c)), \ (I[42] = I[43] = I[44] = I[45] = (T)(img)(0,_n3##y,z,c)), \ (I[4] = (T)(img)(_n1##x,_p3##y,z,c)), \ (I[11] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[18] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[25] = (T)(img)(_n1##x,y,z,c)), \ (I[32] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[39] = (T)(img)(_n1##x,_n2##y,z,c)), \ (I[46] = (T)(img)(_n1##x,_n3##y,z,c)), \ (I[5] = (T)(img)(_n2##x,_p3##y,z,c)), \ (I[12] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[19] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[26] = (T)(img)(_n2##x,y,z,c)), \ (I[33] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[40] = (T)(img)(_n2##x,_n2##y,z,c)), \ (I[47] = (T)(img)(_n2##x,_n3##y,z,c)), \ 3>=(img)._width?(img).width() - 1:3); \ (_n3##x<(img).width() && ( \ (I[6] = (T)(img)(_n3##x,_p3##y,z,c)), \ (I[13] = (T)(img)(_n3##x,_p2##y,z,c)), \ (I[20] = (T)(img)(_n3##x,_p1##y,z,c)), \ (I[27] = (T)(img)(_n3##x,y,z,c)), \ (I[34] = (T)(img)(_n3##x,_n1##y,z,c)), \ (I[41] = (T)(img)(_n3##x,_n2##y,z,c)), \ (I[48] = (T)(img)(_n3##x,_n3##y,z,c)),1)) || \ _n2##x==--_n3##x || _n1##x==--_n2##x || x==(_n3##x = _n2##x = --_n1##x); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], I[4] = I[5], I[5] = I[6], \ I[7] = I[8], I[8] = I[9], I[9] = I[10], I[10] = I[11], I[11] = I[12], I[12] = I[13], \ I[14] = I[15], I[15] = I[16], I[16] = I[17], I[17] = I[18], I[18] = I[19], I[19] = I[20], \ I[21] = I[22], I[22] = I[23], I[23] = I[24], I[24] = I[25], I[25] = I[26], I[26] = I[27], \ I[28] = I[29], I[29] = I[30], I[30] = I[31], I[31] = I[32], I[32] = I[33], I[33] = I[34], \ I[35] = I[36], I[36] = I[37], I[37] = I[38], I[38] = I[39], I[39] = I[40], I[40] = I[41], \ I[42] = I[43], I[43] = I[44], I[44] = I[45], I[45] = I[46], I[46] = I[47], I[47] = I[48], \ _p3##x = _p2##x, _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x, ++_n3##x) #define cimg_for_in7x7(img,x0,y0,x1,y1,x,y,z,c,I,T) \ cimg_for_in7((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)(x0), \ _p3##x = x - 3<0?0:x - 3, \ _p2##x = x - 2<0?0:x - 2, \ _p1##x = x - 1<0?0:x - 1, \ _n1##x = x + 1>=(int)(img)._width?(img).width() - 1:x + 1, \ _n2##x = x + 2>=(int)(img)._width?(img).width() - 1:x + 2, \ _n3##x = (int)( \ (I[0] = (T)(img)(_p3##x,_p3##y,z,c)), \ (I[7] = (T)(img)(_p3##x,_p2##y,z,c)), \ (I[14] = (T)(img)(_p3##x,_p1##y,z,c)), \ (I[21] = (T)(img)(_p3##x,y,z,c)), \ (I[28] = (T)(img)(_p3##x,_n1##y,z,c)), \ (I[35] = (T)(img)(_p3##x,_n2##y,z,c)), \ (I[42] = (T)(img)(_p3##x,_n3##y,z,c)), \ (I[1] = (T)(img)(_p2##x,_p3##y,z,c)), \ (I[8] = (T)(img)(_p2##x,_p2##y,z,c)), \ (I[15] = (T)(img)(_p2##x,_p1##y,z,c)), \ (I[22] = (T)(img)(_p2##x,y,z,c)), \ (I[29] = (T)(img)(_p2##x,_n1##y,z,c)), \ (I[36] = (T)(img)(_p2##x,_n2##y,z,c)), \ (I[43] = (T)(img)(_p2##x,_n3##y,z,c)), \ (I[2] = (T)(img)(_p1##x,_p3##y,z,c)), \ (I[9] = (T)(img)(_p1##x,_p2##y,z,c)), \ (I[16] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[23] = (T)(img)(_p1##x,y,z,c)), \ (I[30] = (T)(img)(_p1##x,_n1##y,z,c)), \ (I[37] = (T)(img)(_p1##x,_n2##y,z,c)), \ (I[44] = (T)(img)(_p1##x,_n3##y,z,c)), \ (I[3] = (T)(img)(x,_p3##y,z,c)), \ (I[10] = (T)(img)(x,_p2##y,z,c)), \ (I[17] = (T)(img)(x,_p1##y,z,c)), \ (I[24] = (T)(img)(x,y,z,c)), \ (I[31] = (T)(img)(x,_n1##y,z,c)), \ (I[38] = (T)(img)(x,_n2##y,z,c)), \ (I[45] = (T)(img)(x,_n3##y,z,c)), \ (I[4] = (T)(img)(_n1##x,_p3##y,z,c)), \ (I[11] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[18] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[25] = (T)(img)(_n1##x,y,z,c)), \ (I[32] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[39] = (T)(img)(_n1##x,_n2##y,z,c)), \ (I[46] = (T)(img)(_n1##x,_n3##y,z,c)), \ (I[5] = (T)(img)(_n2##x,_p3##y,z,c)), \ (I[12] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[19] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[26] = (T)(img)(_n2##x,y,z,c)), \ (I[33] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[40] = (T)(img)(_n2##x,_n2##y,z,c)), \ (I[47] = (T)(img)(_n2##x,_n3##y,z,c)), \ x + 3>=(int)(img)._width?(img).width() - 1:x + 3); \ x<=(int)(x1) && ((_n3##x<(img).width() && ( \ (I[6] = (T)(img)(_n3##x,_p3##y,z,c)), \ (I[13] = (T)(img)(_n3##x,_p2##y,z,c)), \ (I[20] = (T)(img)(_n3##x,_p1##y,z,c)), \ (I[27] = (T)(img)(_n3##x,y,z,c)), \ (I[34] = (T)(img)(_n3##x,_n1##y,z,c)), \ (I[41] = (T)(img)(_n3##x,_n2##y,z,c)), \ (I[48] = (T)(img)(_n3##x,_n3##y,z,c)),1)) || \ _n2##x==--_n3##x || _n1##x==--_n2##x || x==(_n3##x = _n2##x = --_n1##x)); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], I[4] = I[5], I[5] = I[6], \ I[7] = I[8], I[8] = I[9], I[9] = I[10], I[10] = I[11], I[11] = I[12], I[12] = I[13], \ I[14] = I[15], I[15] = I[16], I[16] = I[17], I[17] = I[18], I[18] = I[19], I[19] = I[20], \ I[21] = I[22], I[22] = I[23], I[23] = I[24], I[24] = I[25], I[25] = I[26], I[26] = I[27], \ I[28] = I[29], I[29] = I[30], I[30] = I[31], I[31] = I[32], I[32] = I[33], I[33] = I[34], \ I[35] = I[36], I[36] = I[37], I[37] = I[38], I[38] = I[39], I[39] = I[40], I[40] = I[41], \ I[42] = I[43], I[43] = I[44], I[44] = I[45], I[45] = I[46], I[46] = I[47], I[47] = I[48], \ _p3##x = _p2##x, _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x, ++_n3##x) #define cimg_for8x8(img,x,y,z,c,I,T) \ cimg_for8((img)._height,y) for (int x = 0, \ _p3##x = 0, _p2##x = 0, _p1##x = 0, \ _n1##x = 1>=((img)._width)?(img).width() - 1:1, \ _n2##x = 2>=((img)._width)?(img).width() - 1:2, \ _n3##x = 3>=((img)._width)?(img).width() - 1:3, \ _n4##x = (int)( \ (I[0] = I[1] = I[2] = I[3] = (T)(img)(_p3##x,_p3##y,z,c)), \ (I[8] = I[9] = I[10] = I[11] = (T)(img)(0,_p2##y,z,c)), \ (I[16] = I[17] = I[18] = I[19] = (T)(img)(0,_p1##y,z,c)), \ (I[24] = I[25] = I[26] = I[27] = (T)(img)(0,y,z,c)), \ (I[32] = I[33] = I[34] = I[35] = (T)(img)(0,_n1##y,z,c)), \ (I[40] = I[41] = I[42] = I[43] = (T)(img)(0,_n2##y,z,c)), \ (I[48] = I[49] = I[50] = I[51] = (T)(img)(0,_n3##y,z,c)), \ (I[56] = I[57] = I[58] = I[59] = (T)(img)(0,_n4##y,z,c)), \ (I[4] = (T)(img)(_n1##x,_p3##y,z,c)), \ (I[12] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[20] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[28] = (T)(img)(_n1##x,y,z,c)), \ (I[36] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[44] = (T)(img)(_n1##x,_n2##y,z,c)), \ (I[52] = (T)(img)(_n1##x,_n3##y,z,c)), \ (I[60] = (T)(img)(_n1##x,_n4##y,z,c)), \ (I[5] = (T)(img)(_n2##x,_p3##y,z,c)), \ (I[13] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[21] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[29] = (T)(img)(_n2##x,y,z,c)), \ (I[37] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[45] = (T)(img)(_n2##x,_n2##y,z,c)), \ (I[53] = (T)(img)(_n2##x,_n3##y,z,c)), \ (I[61] = (T)(img)(_n2##x,_n4##y,z,c)), \ (I[6] = (T)(img)(_n3##x,_p3##y,z,c)), \ (I[14] = (T)(img)(_n3##x,_p2##y,z,c)), \ (I[22] = (T)(img)(_n3##x,_p1##y,z,c)), \ (I[30] = (T)(img)(_n3##x,y,z,c)), \ (I[38] = (T)(img)(_n3##x,_n1##y,z,c)), \ (I[46] = (T)(img)(_n3##x,_n2##y,z,c)), \ (I[54] = (T)(img)(_n3##x,_n3##y,z,c)), \ (I[62] = (T)(img)(_n3##x,_n4##y,z,c)), \ 4>=((img)._width)?(img).width() - 1:4); \ (_n4##x<(img).width() && ( \ (I[7] = (T)(img)(_n4##x,_p3##y,z,c)), \ (I[15] = (T)(img)(_n4##x,_p2##y,z,c)), \ (I[23] = (T)(img)(_n4##x,_p1##y,z,c)), \ (I[31] = (T)(img)(_n4##x,y,z,c)), \ (I[39] = (T)(img)(_n4##x,_n1##y,z,c)), \ (I[47] = (T)(img)(_n4##x,_n2##y,z,c)), \ (I[55] = (T)(img)(_n4##x,_n3##y,z,c)), \ (I[63] = (T)(img)(_n4##x,_n4##y,z,c)),1)) || \ _n3##x==--_n4##x || _n2##x==--_n3##x || _n1##x==--_n2##x || x==(_n4##x = _n3##x = _n2##x = --_n1##x); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], I[4] = I[5], I[5] = I[6], I[6] = I[7], \ I[8] = I[9], I[9] = I[10], I[10] = I[11], I[11] = I[12], I[12] = I[13], I[13] = I[14], I[14] = I[15], \ I[16] = I[17], I[17] = I[18], I[18] = I[19], I[19] = I[20], I[20] = I[21], I[21] = I[22], I[22] = I[23], \ I[24] = I[25], I[25] = I[26], I[26] = I[27], I[27] = I[28], I[28] = I[29], I[29] = I[30], I[30] = I[31], \ I[32] = I[33], I[33] = I[34], I[34] = I[35], I[35] = I[36], I[36] = I[37], I[37] = I[38], I[38] = I[39], \ I[40] = I[41], I[41] = I[42], I[42] = I[43], I[43] = I[44], I[44] = I[45], I[45] = I[46], I[46] = I[47], \ I[48] = I[49], I[49] = I[50], I[50] = I[51], I[51] = I[52], I[52] = I[53], I[53] = I[54], I[54] = I[55], \ I[56] = I[57], I[57] = I[58], I[58] = I[59], I[59] = I[60], I[60] = I[61], I[61] = I[62], I[62] = I[63], \ _p3##x = _p2##x, _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x, ++_n3##x, ++_n4##x) #define cimg_for_in8x8(img,x0,y0,x1,y1,x,y,z,c,I,T) \ cimg_for_in8((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)(x0), \ _p3##x = x - 3<0?0:x - 3, \ _p2##x = x - 2<0?0:x - 2, \ _p1##x = x - 1<0?0:x - 1, \ _n1##x = x + 1>=(img).width()?(img).width() - 1:x + 1, \ _n2##x = x + 2>=(img).width()?(img).width() - 1:x + 2, \ _n3##x = x + 3>=(img).width()?(img).width() - 1:x + 3, \ _n4##x = (int)( \ (I[0] = (T)(img)(_p3##x,_p3##y,z,c)), \ (I[8] = (T)(img)(_p3##x,_p2##y,z,c)), \ (I[16] = (T)(img)(_p3##x,_p1##y,z,c)), \ (I[24] = (T)(img)(_p3##x,y,z,c)), \ (I[32] = (T)(img)(_p3##x,_n1##y,z,c)), \ (I[40] = (T)(img)(_p3##x,_n2##y,z,c)), \ (I[48] = (T)(img)(_p3##x,_n3##y,z,c)), \ (I[56] = (T)(img)(_p3##x,_n4##y,z,c)), \ (I[1] = (T)(img)(_p2##x,_p3##y,z,c)), \ (I[9] = (T)(img)(_p2##x,_p2##y,z,c)), \ (I[17] = (T)(img)(_p2##x,_p1##y,z,c)), \ (I[25] = (T)(img)(_p2##x,y,z,c)), \ (I[33] = (T)(img)(_p2##x,_n1##y,z,c)), \ (I[41] = (T)(img)(_p2##x,_n2##y,z,c)), \ (I[49] = (T)(img)(_p2##x,_n3##y,z,c)), \ (I[57] = (T)(img)(_p2##x,_n4##y,z,c)), \ (I[2] = (T)(img)(_p1##x,_p3##y,z,c)), \ (I[10] = (T)(img)(_p1##x,_p2##y,z,c)), \ (I[18] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[26] = (T)(img)(_p1##x,y,z,c)), \ (I[34] = (T)(img)(_p1##x,_n1##y,z,c)), \ (I[42] = (T)(img)(_p1##x,_n2##y,z,c)), \ (I[50] = (T)(img)(_p1##x,_n3##y,z,c)), \ (I[58] = (T)(img)(_p1##x,_n4##y,z,c)), \ (I[3] = (T)(img)(x,_p3##y,z,c)), \ (I[11] = (T)(img)(x,_p2##y,z,c)), \ (I[19] = (T)(img)(x,_p1##y,z,c)), \ (I[27] = (T)(img)(x,y,z,c)), \ (I[35] = (T)(img)(x,_n1##y,z,c)), \ (I[43] = (T)(img)(x,_n2##y,z,c)), \ (I[51] = (T)(img)(x,_n3##y,z,c)), \ (I[59] = (T)(img)(x,_n4##y,z,c)), \ (I[4] = (T)(img)(_n1##x,_p3##y,z,c)), \ (I[12] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[20] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[28] = (T)(img)(_n1##x,y,z,c)), \ (I[36] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[44] = (T)(img)(_n1##x,_n2##y,z,c)), \ (I[52] = (T)(img)(_n1##x,_n3##y,z,c)), \ (I[60] = (T)(img)(_n1##x,_n4##y,z,c)), \ (I[5] = (T)(img)(_n2##x,_p3##y,z,c)), \ (I[13] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[21] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[29] = (T)(img)(_n2##x,y,z,c)), \ (I[37] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[45] = (T)(img)(_n2##x,_n2##y,z,c)), \ (I[53] = (T)(img)(_n2##x,_n3##y,z,c)), \ (I[61] = (T)(img)(_n2##x,_n4##y,z,c)), \ (I[6] = (T)(img)(_n3##x,_p3##y,z,c)), \ (I[14] = (T)(img)(_n3##x,_p2##y,z,c)), \ (I[22] = (T)(img)(_n3##x,_p1##y,z,c)), \ (I[30] = (T)(img)(_n3##x,y,z,c)), \ (I[38] = (T)(img)(_n3##x,_n1##y,z,c)), \ (I[46] = (T)(img)(_n3##x,_n2##y,z,c)), \ (I[54] = (T)(img)(_n3##x,_n3##y,z,c)), \ (I[62] = (T)(img)(_n3##x,_n4##y,z,c)), \ x + 4>=(img).width()?(img).width() - 1:x + 4); \ x<=(int)(x1) && ((_n4##x<(img).width() && ( \ (I[7] = (T)(img)(_n4##x,_p3##y,z,c)), \ (I[15] = (T)(img)(_n4##x,_p2##y,z,c)), \ (I[23] = (T)(img)(_n4##x,_p1##y,z,c)), \ (I[31] = (T)(img)(_n4##x,y,z,c)), \ (I[39] = (T)(img)(_n4##x,_n1##y,z,c)), \ (I[47] = (T)(img)(_n4##x,_n2##y,z,c)), \ (I[55] = (T)(img)(_n4##x,_n3##y,z,c)), \ (I[63] = (T)(img)(_n4##x,_n4##y,z,c)),1)) || \ _n3##x==--_n4##x || _n2##x==--_n3##x || _n1##x==--_n2##x || x==(_n4##x = _n3##x = _n2##x = --_n1##x)); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], I[4] = I[5], I[5] = I[6], I[6] = I[7], \ I[8] = I[9], I[9] = I[10], I[10] = I[11], I[11] = I[12], I[12] = I[13], I[13] = I[14], I[14] = I[15], \ I[16] = I[17], I[17] = I[18], I[18] = I[19], I[19] = I[20], I[20] = I[21], I[21] = I[22], I[22] = I[23], \ I[24] = I[25], I[25] = I[26], I[26] = I[27], I[27] = I[28], I[28] = I[29], I[29] = I[30], I[30] = I[31], \ I[32] = I[33], I[33] = I[34], I[34] = I[35], I[35] = I[36], I[36] = I[37], I[37] = I[38], I[38] = I[39], \ I[40] = I[41], I[41] = I[42], I[42] = I[43], I[43] = I[44], I[44] = I[45], I[45] = I[46], I[46] = I[47], \ I[48] = I[49], I[49] = I[50], I[50] = I[51], I[51] = I[52], I[52] = I[53], I[53] = I[54], I[54] = I[55], \ I[56] = I[57], I[57] = I[58], I[58] = I[59], I[59] = I[60], I[60] = I[61], I[61] = I[62], I[62] = I[63], \ _p3##x = _p2##x, _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x, ++_n3##x, ++_n4##x) #define cimg_for9x9(img,x,y,z,c,I,T) \ cimg_for9((img)._height,y) for (int x = 0, \ _p4##x = 0, _p3##x = 0, _p2##x = 0, _p1##x = 0, \ _n1##x = 1>=((img)._width)?(img).width() - 1:1, \ _n2##x = 2>=((img)._width)?(img).width() - 1:2, \ _n3##x = 3>=((img)._width)?(img).width() - 1:3, \ _n4##x = (int)( \ (I[0] = I[1] = I[2] = I[3] = I[4] = (T)(img)(_p4##x,_p4##y,z,c)), \ (I[9] = I[10] = I[11] = I[12] = I[13] = (T)(img)(0,_p3##y,z,c)), \ (I[18] = I[19] = I[20] = I[21] = I[22] = (T)(img)(0,_p2##y,z,c)), \ (I[27] = I[28] = I[29] = I[30] = I[31] = (T)(img)(0,_p1##y,z,c)), \ (I[36] = I[37] = I[38] = I[39] = I[40] = (T)(img)(0,y,z,c)), \ (I[45] = I[46] = I[47] = I[48] = I[49] = (T)(img)(0,_n1##y,z,c)), \ (I[54] = I[55] = I[56] = I[57] = I[58] = (T)(img)(0,_n2##y,z,c)), \ (I[63] = I[64] = I[65] = I[66] = I[67] = (T)(img)(0,_n3##y,z,c)), \ (I[72] = I[73] = I[74] = I[75] = I[76] = (T)(img)(0,_n4##y,z,c)), \ (I[5] = (T)(img)(_n1##x,_p4##y,z,c)), \ (I[14] = (T)(img)(_n1##x,_p3##y,z,c)), \ (I[23] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[32] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[41] = (T)(img)(_n1##x,y,z,c)), \ (I[50] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[59] = (T)(img)(_n1##x,_n2##y,z,c)), \ (I[68] = (T)(img)(_n1##x,_n3##y,z,c)), \ (I[77] = (T)(img)(_n1##x,_n4##y,z,c)), \ (I[6] = (T)(img)(_n2##x,_p4##y,z,c)), \ (I[15] = (T)(img)(_n2##x,_p3##y,z,c)), \ (I[24] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[33] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[42] = (T)(img)(_n2##x,y,z,c)), \ (I[51] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[60] = (T)(img)(_n2##x,_n2##y,z,c)), \ (I[69] = (T)(img)(_n2##x,_n3##y,z,c)), \ (I[78] = (T)(img)(_n2##x,_n4##y,z,c)), \ (I[7] = (T)(img)(_n3##x,_p4##y,z,c)), \ (I[16] = (T)(img)(_n3##x,_p3##y,z,c)), \ (I[25] = (T)(img)(_n3##x,_p2##y,z,c)), \ (I[34] = (T)(img)(_n3##x,_p1##y,z,c)), \ (I[43] = (T)(img)(_n3##x,y,z,c)), \ (I[52] = (T)(img)(_n3##x,_n1##y,z,c)), \ (I[61] = (T)(img)(_n3##x,_n2##y,z,c)), \ (I[70] = (T)(img)(_n3##x,_n3##y,z,c)), \ (I[79] = (T)(img)(_n3##x,_n4##y,z,c)), \ 4>=((img)._width)?(img).width() - 1:4); \ (_n4##x<(img).width() && ( \ (I[8] = (T)(img)(_n4##x,_p4##y,z,c)), \ (I[17] = (T)(img)(_n4##x,_p3##y,z,c)), \ (I[26] = (T)(img)(_n4##x,_p2##y,z,c)), \ (I[35] = (T)(img)(_n4##x,_p1##y,z,c)), \ (I[44] = (T)(img)(_n4##x,y,z,c)), \ (I[53] = (T)(img)(_n4##x,_n1##y,z,c)), \ (I[62] = (T)(img)(_n4##x,_n2##y,z,c)), \ (I[71] = (T)(img)(_n4##x,_n3##y,z,c)), \ (I[80] = (T)(img)(_n4##x,_n4##y,z,c)),1)) || \ _n3##x==--_n4##x || _n2##x==--_n3##x || _n1##x==--_n2##x || x==(_n4##x = _n3##x = _n2##x = --_n1##x); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], I[4] = I[5], I[5] = I[6], I[6] = I[7], I[7] = I[8], \ I[9] = I[10], I[10] = I[11], I[11] = I[12], I[12] = I[13], I[13] = I[14], I[14] = I[15], I[15] = I[16], \ I[16] = I[17], I[18] = I[19], I[19] = I[20], I[20] = I[21], I[21] = I[22], I[22] = I[23], I[23] = I[24], \ I[24] = I[25], I[25] = I[26], I[27] = I[28], I[28] = I[29], I[29] = I[30], I[30] = I[31], I[31] = I[32], \ I[32] = I[33], I[33] = I[34], I[34] = I[35], I[36] = I[37], I[37] = I[38], I[38] = I[39], I[39] = I[40], \ I[40] = I[41], I[41] = I[42], I[42] = I[43], I[43] = I[44], I[45] = I[46], I[46] = I[47], I[47] = I[48], \ I[48] = I[49], I[49] = I[50], I[50] = I[51], I[51] = I[52], I[52] = I[53], I[54] = I[55], I[55] = I[56], \ I[56] = I[57], I[57] = I[58], I[58] = I[59], I[59] = I[60], I[60] = I[61], I[61] = I[62], I[63] = I[64], \ I[64] = I[65], I[65] = I[66], I[66] = I[67], I[67] = I[68], I[68] = I[69], I[69] = I[70], I[70] = I[71], \ I[72] = I[73], I[73] = I[74], I[74] = I[75], I[75] = I[76], I[76] = I[77], I[77] = I[78], I[78] = I[79], \ I[79] = I[80], \ _p4##x = _p3##x, _p3##x = _p2##x, _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x, ++_n3##x, ++_n4##x) #define cimg_for_in9x9(img,x0,y0,x1,y1,x,y,z,c,I,T) \ cimg_for_in9((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)(x0), \ _p4##x = x - 4<0?0:x - 4, \ _p3##x = x - 3<0?0:x - 3, \ _p2##x = x - 2<0?0:x - 2, \ _p1##x = x - 1<0?0:x - 1, \ _n1##x = x + 1>=(img).width()?(img).width() - 1:x + 1, \ _n2##x = x + 2>=(img).width()?(img).width() - 1:x + 2, \ _n3##x = x + 3>=(img).width()?(img).width() - 1:x + 3, \ _n4##x = (int)( \ (I[0] = (T)(img)(_p4##x,_p4##y,z,c)), \ (I[9] = (T)(img)(_p4##x,_p3##y,z,c)), \ (I[18] = (T)(img)(_p4##x,_p2##y,z,c)), \ (I[27] = (T)(img)(_p4##x,_p1##y,z,c)), \ (I[36] = (T)(img)(_p4##x,y,z,c)), \ (I[45] = (T)(img)(_p4##x,_n1##y,z,c)), \ (I[54] = (T)(img)(_p4##x,_n2##y,z,c)), \ (I[63] = (T)(img)(_p4##x,_n3##y,z,c)), \ (I[72] = (T)(img)(_p4##x,_n4##y,z,c)), \ (I[1] = (T)(img)(_p3##x,_p4##y,z,c)), \ (I[10] = (T)(img)(_p3##x,_p3##y,z,c)), \ (I[19] = (T)(img)(_p3##x,_p2##y,z,c)), \ (I[28] = (T)(img)(_p3##x,_p1##y,z,c)), \ (I[37] = (T)(img)(_p3##x,y,z,c)), \ (I[46] = (T)(img)(_p3##x,_n1##y,z,c)), \ (I[55] = (T)(img)(_p3##x,_n2##y,z,c)), \ (I[64] = (T)(img)(_p3##x,_n3##y,z,c)), \ (I[73] = (T)(img)(_p3##x,_n4##y,z,c)), \ (I[2] = (T)(img)(_p2##x,_p4##y,z,c)), \ (I[11] = (T)(img)(_p2##x,_p3##y,z,c)), \ (I[20] = (T)(img)(_p2##x,_p2##y,z,c)), \ (I[29] = (T)(img)(_p2##x,_p1##y,z,c)), \ (I[38] = (T)(img)(_p2##x,y,z,c)), \ (I[47] = (T)(img)(_p2##x,_n1##y,z,c)), \ (I[56] = (T)(img)(_p2##x,_n2##y,z,c)), \ (I[65] = (T)(img)(_p2##x,_n3##y,z,c)), \ (I[74] = (T)(img)(_p2##x,_n4##y,z,c)), \ (I[3] = (T)(img)(_p1##x,_p4##y,z,c)), \ (I[12] = (T)(img)(_p1##x,_p3##y,z,c)), \ (I[21] = (T)(img)(_p1##x,_p2##y,z,c)), \ (I[30] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[39] = (T)(img)(_p1##x,y,z,c)), \ (I[48] = (T)(img)(_p1##x,_n1##y,z,c)), \ (I[57] = (T)(img)(_p1##x,_n2##y,z,c)), \ (I[66] = (T)(img)(_p1##x,_n3##y,z,c)), \ (I[75] = (T)(img)(_p1##x,_n4##y,z,c)), \ (I[4] = (T)(img)(x,_p4##y,z,c)), \ (I[13] = (T)(img)(x,_p3##y,z,c)), \ (I[22] = (T)(img)(x,_p2##y,z,c)), \ (I[31] = (T)(img)(x,_p1##y,z,c)), \ (I[40] = (T)(img)(x,y,z,c)), \ (I[49] = (T)(img)(x,_n1##y,z,c)), \ (I[58] = (T)(img)(x,_n2##y,z,c)), \ (I[67] = (T)(img)(x,_n3##y,z,c)), \ (I[76] = (T)(img)(x,_n4##y,z,c)), \ (I[5] = (T)(img)(_n1##x,_p4##y,z,c)), \ (I[14] = (T)(img)(_n1##x,_p3##y,z,c)), \ (I[23] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[32] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[41] = (T)(img)(_n1##x,y,z,c)), \ (I[50] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[59] = (T)(img)(_n1##x,_n2##y,z,c)), \ (I[68] = (T)(img)(_n1##x,_n3##y,z,c)), \ (I[77] = (T)(img)(_n1##x,_n4##y,z,c)), \ (I[6] = (T)(img)(_n2##x,_p4##y,z,c)), \ (I[15] = (T)(img)(_n2##x,_p3##y,z,c)), \ (I[24] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[33] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[42] = (T)(img)(_n2##x,y,z,c)), \ (I[51] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[60] = (T)(img)(_n2##x,_n2##y,z,c)), \ (I[69] = (T)(img)(_n2##x,_n3##y,z,c)), \ (I[78] = (T)(img)(_n2##x,_n4##y,z,c)), \ (I[7] = (T)(img)(_n3##x,_p4##y,z,c)), \ (I[16] = (T)(img)(_n3##x,_p3##y,z,c)), \ (I[25] = (T)(img)(_n3##x,_p2##y,z,c)), \ (I[34] = (T)(img)(_n3##x,_p1##y,z,c)), \ (I[43] = (T)(img)(_n3##x,y,z,c)), \ (I[52] = (T)(img)(_n3##x,_n1##y,z,c)), \ (I[61] = (T)(img)(_n3##x,_n2##y,z,c)), \ (I[70] = (T)(img)(_n3##x,_n3##y,z,c)), \ (I[79] = (T)(img)(_n3##x,_n4##y,z,c)), \ x + 4>=(img).width()?(img).width() - 1:x + 4); \ x<=(int)(x1) && ((_n4##x<(img).width() && ( \ (I[8] = (T)(img)(_n4##x,_p4##y,z,c)), \ (I[17] = (T)(img)(_n4##x,_p3##y,z,c)), \ (I[26] = (T)(img)(_n4##x,_p2##y,z,c)), \ (I[35] = (T)(img)(_n4##x,_p1##y,z,c)), \ (I[44] = (T)(img)(_n4##x,y,z,c)), \ (I[53] = (T)(img)(_n4##x,_n1##y,z,c)), \ (I[62] = (T)(img)(_n4##x,_n2##y,z,c)), \ (I[71] = (T)(img)(_n4##x,_n3##y,z,c)), \ (I[80] = (T)(img)(_n4##x,_n4##y,z,c)),1)) || \ _n3##x==--_n4##x || _n2##x==--_n3##x || _n1##x==--_n2##x || x==(_n4##x = _n3##x = _n2##x = --_n1##x)); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], I[4] = I[5], I[5] = I[6], I[6] = I[7], I[7] = I[8], \ I[9] = I[10], I[10] = I[11], I[11] = I[12], I[12] = I[13], I[13] = I[14], I[14] = I[15], I[15] = I[16], \ I[16] = I[17], I[18] = I[19], I[19] = I[20], I[20] = I[21], I[21] = I[22], I[22] = I[23], I[23] = I[24], \ I[24] = I[25], I[25] = I[26], I[27] = I[28], I[28] = I[29], I[29] = I[30], I[30] = I[31], I[31] = I[32], \ I[32] = I[33], I[33] = I[34], I[34] = I[35], I[36] = I[37], I[37] = I[38], I[38] = I[39], I[39] = I[40], \ I[40] = I[41], I[41] = I[42], I[42] = I[43], I[43] = I[44], I[45] = I[46], I[46] = I[47], I[47] = I[48], \ I[48] = I[49], I[49] = I[50], I[50] = I[51], I[51] = I[52], I[52] = I[53], I[54] = I[55], I[55] = I[56], \ I[56] = I[57], I[57] = I[58], I[58] = I[59], I[59] = I[60], I[60] = I[61], I[61] = I[62], I[63] = I[64], \ I[64] = I[65], I[65] = I[66], I[66] = I[67], I[67] = I[68], I[68] = I[69], I[69] = I[70], I[70] = I[71], \ I[72] = I[73], I[73] = I[74], I[74] = I[75], I[75] = I[76], I[76] = I[77], I[77] = I[78], I[78] = I[79], \ I[79] = I[80], \ _p4##x = _p3##x, _p3##x = _p2##x, _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x, ++_n3##x, ++_n4##x) #define cimg_for2x2x2(img,x,y,z,c,I,T) \ cimg_for2((img)._depth,z) cimg_for2((img)._height,y) for (int x = 0, \ _n1##x = (int)( \ (I[0] = (T)(img)(0,y,z,c)), \ (I[2] = (T)(img)(0,_n1##y,z,c)), \ (I[4] = (T)(img)(0,y,_n1##z,c)), \ (I[6] = (T)(img)(0,_n1##y,_n1##z,c)), \ 1>=(img)._width?(img).width() - 1:1); \ (_n1##x<(img).width() && ( \ (I[1] = (T)(img)(_n1##x,y,z,c)), \ (I[3] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[5] = (T)(img)(_n1##x,y,_n1##z,c)), \ (I[7] = (T)(img)(_n1##x,_n1##y,_n1##z,c)),1)) || \ x==--_n1##x; \ I[0] = I[1], I[2] = I[3], I[4] = I[5], I[6] = I[7], \ ++x, ++_n1##x) #define cimg_for_in2x2x2(img,x0,y0,z0,x1,y1,z1,x,y,z,c,I,T) \ cimg_for_in2((img)._depth,z0,z1,z) cimg_for_in2((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)(x0), \ _n1##x = (int)( \ (I[0] = (T)(img)(x,y,z,c)), \ (I[2] = (T)(img)(x,_n1##y,z,c)), \ (I[4] = (T)(img)(x,y,_n1##z,c)), \ (I[6] = (T)(img)(x,_n1##y,_n1##z,c)), \ x + 1>=(int)(img)._width?(img).width() - 1:x + 1); \ x<=(int)(x1) && ((_n1##x<(img).width() && ( \ (I[1] = (T)(img)(_n1##x,y,z,c)), \ (I[3] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[5] = (T)(img)(_n1##x,y,_n1##z,c)), \ (I[7] = (T)(img)(_n1##x,_n1##y,_n1##z,c)),1)) || \ x==--_n1##x); \ I[0] = I[1], I[2] = I[3], I[4] = I[5], I[6] = I[7], \ ++x, ++_n1##x) #define cimg_for3x3x3(img,x,y,z,c,I,T) \ cimg_for3((img)._depth,z) cimg_for3((img)._height,y) for (int x = 0, \ _p1##x = 0, \ _n1##x = (int)( \ (I[0] = I[1] = (T)(img)(_p1##x,_p1##y,_p1##z,c)), \ (I[3] = I[4] = (T)(img)(0,y,_p1##z,c)), \ (I[6] = I[7] = (T)(img)(0,_n1##y,_p1##z,c)), \ (I[9] = I[10] = (T)(img)(0,_p1##y,z,c)), \ (I[12] = I[13] = (T)(img)(0,y,z,c)), \ (I[15] = I[16] = (T)(img)(0,_n1##y,z,c)), \ (I[18] = I[19] = (T)(img)(0,_p1##y,_n1##z,c)), \ (I[21] = I[22] = (T)(img)(0,y,_n1##z,c)), \ (I[24] = I[25] = (T)(img)(0,_n1##y,_n1##z,c)), \ 1>=(img)._width?(img).width() - 1:1); \ (_n1##x<(img).width() && ( \ (I[2] = (T)(img)(_n1##x,_p1##y,_p1##z,c)), \ (I[5] = (T)(img)(_n1##x,y,_p1##z,c)), \ (I[8] = (T)(img)(_n1##x,_n1##y,_p1##z,c)), \ (I[11] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[14] = (T)(img)(_n1##x,y,z,c)), \ (I[17] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[20] = (T)(img)(_n1##x,_p1##y,_n1##z,c)), \ (I[23] = (T)(img)(_n1##x,y,_n1##z,c)), \ (I[26] = (T)(img)(_n1##x,_n1##y,_n1##z,c)),1)) || \ x==--_n1##x; \ I[0] = I[1], I[1] = I[2], I[3] = I[4], I[4] = I[5], I[6] = I[7], I[7] = I[8], \ I[9] = I[10], I[10] = I[11], I[12] = I[13], I[13] = I[14], I[15] = I[16], I[16] = I[17], \ I[18] = I[19], I[19] = I[20], I[21] = I[22], I[22] = I[23], I[24] = I[25], I[25] = I[26], \ _p1##x = x++, ++_n1##x) #define cimg_for_in3x3x3(img,x0,y0,z0,x1,y1,z1,x,y,z,c,I,T) \ cimg_for_in3((img)._depth,z0,z1,z) cimg_for_in3((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)(x0), \ _p1##x = x - 1<0?0:x - 1, \ _n1##x = (int)( \ (I[0] = (T)(img)(_p1##x,_p1##y,_p1##z,c)), \ (I[3] = (T)(img)(_p1##x,y,_p1##z,c)), \ (I[6] = (T)(img)(_p1##x,_n1##y,_p1##z,c)), \ (I[9] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[12] = (T)(img)(_p1##x,y,z,c)), \ (I[15] = (T)(img)(_p1##x,_n1##y,z,c)), \ (I[18] = (T)(img)(_p1##x,_p1##y,_n1##z,c)), \ (I[21] = (T)(img)(_p1##x,y,_n1##z,c)), \ (I[24] = (T)(img)(_p1##x,_n1##y,_n1##z,c)), \ (I[1] = (T)(img)(x,_p1##y,_p1##z,c)), \ (I[4] = (T)(img)(x,y,_p1##z,c)), \ (I[7] = (T)(img)(x,_n1##y,_p1##z,c)), \ (I[10] = (T)(img)(x,_p1##y,z,c)), \ (I[13] = (T)(img)(x,y,z,c)), \ (I[16] = (T)(img)(x,_n1##y,z,c)), \ (I[19] = (T)(img)(x,_p1##y,_n1##z,c)), \ (I[22] = (T)(img)(x,y,_n1##z,c)), \ (I[25] = (T)(img)(x,_n1##y,_n1##z,c)), \ x + 1>=(int)(img)._width?(img).width() - 1:x + 1); \ x<=(int)(x1) && ((_n1##x<(img).width() && ( \ (I[2] = (T)(img)(_n1##x,_p1##y,_p1##z,c)), \ (I[5] = (T)(img)(_n1##x,y,_p1##z,c)), \ (I[8] = (T)(img)(_n1##x,_n1##y,_p1##z,c)), \ (I[11] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[14] = (T)(img)(_n1##x,y,z,c)), \ (I[17] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[20] = (T)(img)(_n1##x,_p1##y,_n1##z,c)), \ (I[23] = (T)(img)(_n1##x,y,_n1##z,c)), \ (I[26] = (T)(img)(_n1##x,_n1##y,_n1##z,c)),1)) || \ x==--_n1##x); \ I[0] = I[1], I[1] = I[2], I[3] = I[4], I[4] = I[5], I[6] = I[7], I[7] = I[8], \ I[9] = I[10], I[10] = I[11], I[12] = I[13], I[13] = I[14], I[15] = I[16], I[16] = I[17], \ I[18] = I[19], I[19] = I[20], I[21] = I[22], I[22] = I[23], I[24] = I[25], I[25] = I[26], \ _p1##x = x++, ++_n1##x) #define cimglist_for(list,l) for (int l = 0; l<(int)(list)._width; ++l) #define cimglist_for_in(list,l0,l1,l) \ for (int l = (int)(l0)<0?0:(int)(l0), _max##l = (unsigned int)l1<(list)._width?(int)(l1):(int)(list)._width - 1; \ l<=_max##l; ++l) #define cimglist_apply(list,fn) cimglist_for(list,__##fn) (list)[__##fn].fn // Macros used to display error messages when exceptions are thrown. // You should not use these macros is your own code. #define _cimgdisplay_instance "[instance(%u,%u,%u,%c%s%c)] CImgDisplay::" #define cimgdisplay_instance _width,_height,_normalization,_title?'\"':'[',_title?_title:"untitled",_title?'\"':']' #define _cimg_instance "[instance(%u,%u,%u,%u,%p,%sshared)] CImg<%s>::" #define cimg_instance _width,_height,_depth,_spectrum,_data,_is_shared?"":"non-",pixel_type() #define _cimglist_instance "[instance(%u,%u,%p)] CImgList<%s>::" #define cimglist_instance _width,_allocated_width,_data,pixel_type() /*------------------------------------------------ # # # Define cimg_library:: namespace # # -------------------------------------------------*/ //! Contains <i>all classes and functions</i> of the \CImg library. /** This namespace is defined to avoid functions and class names collisions that could happen with the inclusion of other C++ header files. Anyway, it should not happen often and you should reasonnably start most of your \CImg-based programs with \code #include "CImg.h" using namespace cimg_library; \endcode to simplify the declaration of \CImg Library objects afterwards. **/ namespace cimg_library_suffixed { // Declare the four classes of the CImg Library. template<typename T=float> struct CImg; template<typename T=float> struct CImgList; struct CImgDisplay; struct CImgException; // Declare cimg:: namespace. // This is an uncomplete namespace definition here. It only contains some // necessary stuff to ensure a correct declaration order of the classes and functions // defined afterwards. namespace cimg { // Define Ascii sequences for colored terminal output. #ifdef cimg_use_vt100 static const char t_normal[] = { 0x1b, '[', '0', ';', '0', ';', '0', 'm', 0 }; static const char t_black[] = { 0x1b, '[', '0', ';', '3', '0', ';', '5', '9', 'm', 0 }; static const char t_red[] = { 0x1b, '[', '0', ';', '3', '1', ';', '5', '9', 'm', 0 }; static const char t_green[] = { 0x1b, '[', '0', ';', '3', '2', ';', '5', '9', 'm', 0 }; static const char t_yellow[] = { 0x1b, '[', '0', ';', '3', '3', ';', '5', '9', 'm', 0 }; static const char t_blue[] = { 0x1b, '[', '0', ';', '3', '4', ';', '5', '9', 'm', 0 }; static const char t_magenta[] = { 0x1b, '[', '0', ';', '3', '5', ';', '5', '9', 'm', 0 }; static const char t_cyan[] = { 0x1b, '[', '0', ';', '3', '6', ';', '5', '9', 'm', 0 }; static const char t_white[] = { 0x1b, '[', '0', ';', '3', '7', ';', '5', '9', 'm', 0 }; static const char t_bold[] = { 0x1b, '[', '1', 'm', 0 }; static const char t_underscore[] = { 0x1b, '[', '4', 'm', 0 }; #else static const char t_normal[] = { 0 }; static const char *const t_black = cimg::t_normal, *const t_red = cimg::t_normal, *const t_green = cimg::t_normal, *const t_yellow = cimg::t_normal, *const t_blue = cimg::t_normal, *const t_magenta = cimg::t_normal, *const t_cyan = cimg::t_normal, *const t_white = cimg::t_normal, *const t_bold = cimg::t_normal, *const t_underscore = cimg::t_normal; #endif inline std::FILE* output(std::FILE *file=0); inline void info(); //! Avoid warning messages due to unused parameters. Do nothing actually. template<typename T> inline void unused(const T&, ...) {} // [internal] Lock/unlock a mutex for managing concurrent threads. // 'lock_mode' can be { 0=unlock | 1=lock | 2=trylock }. // 'n' can be in [0,31] but mutex range [0,15] is reserved by CImg. inline int mutex(const unsigned int n, const int lock_mode=1); inline unsigned int& exception_mode(const unsigned int value, const bool is_set) { static unsigned int mode = cimg_verbosity; if (is_set) { cimg::mutex(0); mode = value<4?value:4; cimg::mutex(0,0); } return mode; } // Functions to return standard streams 'stdin', 'stdout' and 'stderr'. inline FILE* _stdin(const bool throw_exception=true); inline FILE* _stdout(const bool throw_exception=true); inline FILE* _stderr(const bool throw_exception=true); // Mandatory because Microsoft's _snprintf() and _vsnprintf() do not add the '\0' character // at the end of the string. #if cimg_OS==2 && defined(_MSC_VER) inline int _snprintf(char *const s, const size_t size, const char *const format, ...) { va_list ap; va_start(ap,format); const int result = _vsnprintf(s,size,format,ap); va_end(ap); return result; } inline int _vsnprintf(char *const s, const size_t size, const char *const format, va_list ap) { int result = -1; cimg::mutex(6); if (size) result = _vsnprintf_s(s,size,_TRUNCATE,format,ap); if (result==-1) result = _vscprintf(format,ap); cimg::mutex(6,0); return result; } // Mutex-protected version of sscanf, sprintf and snprintf. // Used only MacOSX, as it seems those functions are not re-entrant on MacOSX. #elif defined(__MACOSX__) || defined(__APPLE__) inline int _sscanf(const char *const s, const char *const format, ...) { cimg::mutex(6); va_list args; va_start(args,format); const int result = std::vsscanf(s,format,args); va_end(args); cimg::mutex(6,0); return result; } inline int _sprintf(char *const s, const char *const format, ...) { cimg::mutex(6); va_list args; va_start(args,format); const int result = std::vsprintf(s,format,args); va_end(args); cimg::mutex(6,0); return result; } inline int _snprintf(char *const s, const size_t n, const char *const format, ...) { cimg::mutex(6); va_list args; va_start(args,format); const int result = std::vsnprintf(s,n,format,args); va_end(args); cimg::mutex(6,0); return result; } inline int _vsnprintf(char *const s, const size_t size, const char* format, va_list ap) { cimg::mutex(6); const int result = std::vsnprintf(s,size,format,ap); cimg::mutex(6,0); return result; } #endif //! Set current \CImg exception mode. /** The way error messages are handled by \CImg can be changed dynamically, using this function. \param mode Desired exception mode. Possible values are: - \c 0: Hide library messages (quiet mode). - \c 1: Print library messages on the console. - \c 2: Display library messages on a dialog window. - \c 3: Do as \c 1 + add extra debug warnings (slow down the code!). - \c 4: Do as \c 2 + add extra debug warnings (slow down the code!). **/ inline unsigned int& exception_mode(const unsigned int mode) { return exception_mode(mode,true); } //! Return current \CImg exception mode. /** \note By default, return the value of configuration macro \c cimg_verbosity **/ inline unsigned int& exception_mode() { return exception_mode(0,false); } inline unsigned int openmp_mode(const unsigned int value, const bool is_set) { static unsigned int mode = 2; if (is_set) { cimg::mutex(0); mode = value<2?value:2; cimg::mutex(0,0); } return mode; } //! Set current \CImg openmp mode. /** The way openmp-based methods are handled by \CImg can be changed dynamically, using this function. \param mode Desired openmp mode. Possible values are: - \c 0: Never parallelize. - \c 1: Always parallelize. - \c 2: Adaptive parallelization mode (default behavior). **/ inline unsigned int openmp_mode(const unsigned int mode) { return openmp_mode(mode,true); } //! Return current \CImg openmp mode. inline unsigned int openmp_mode() { return openmp_mode(0,false); } #ifndef cimg_openmp_sizefactor #define cimg_openmp_sizefactor 1 #endif #define cimg_openmp_if(cond) if ((cimg::openmp_mode()==1 || (cimg::openmp_mode()>1 && (cond)))) #define cimg_openmp_if_size(size,min_size) cimg_openmp_if((size)>=(cimg_openmp_sizefactor)*(min_size)) #ifdef _MSC_VER // Disable 'collapse()' directive for MSVC (supports only OpenMP 2.0). #define cimg_openmp_collapse(k) #else #define cimg_openmp_collapse(k) collapse(k) #endif #if cimg_OS==2 // Disable parallelization of simple loops on Windows, due to noticed performance drop. #define cimg_openmp_for(instance,expr,min_size) cimg_rof((instance),ptr,T) *ptr = (T)(expr); #else #define cimg_openmp_for(instance,expr,min_size) \ cimg_pragma_openmp(parallel for cimg_openmp_if_size((instance).size(),min_size)) \ cimg_rof((instance),ptr,T) *ptr = (T)(expr); #endif // Display a simple dialog box, and wait for the user's response. inline int dialog(const char *const title, const char *const msg, const char *const button1_label="OK", const char *const button2_label=0, const char *const button3_label=0, const char *const button4_label=0, const char *const button5_label=0, const char *const button6_label=0, const bool centering=false); // Evaluate math expression. inline double eval(const char *const expression, const double x=0, const double y=0, const double z=0, const double c=0); } // namespace cimg { ... /*--------------------------------------- # # Define the CImgException structures # --------------------------------------*/ //! Instances of \c CImgException are thrown when errors are encountered in a \CImg function call. /** \par Overview CImgException is the base class of all exceptions thrown by \CImg (except \b CImgAbortException). CImgException is never thrown itself. Derived classes that specify the type of errord are thrown instead. These classes can be: - \b CImgAbortException: Thrown when a computationally-intensive function is aborted by an external signal. This is the only \c non-derived exception class. - \b CImgArgumentException: Thrown when one argument of a called \CImg function is invalid. This is probably one of the most thrown exception by \CImg. For instance, the following example throws a \c CImgArgumentException: \code CImg<float> img(100,100,1,3); // Define a 100x100 color image with float-valued pixels img.mirror('e'); // Try to mirror image along the (non-existing) 'e'-axis \endcode - \b CImgDisplayException: Thrown when something went wrong during the display of images in CImgDisplay instances. - \b CImgInstanceException: Thrown when an instance associated to a called \CImg method does not fit the function requirements. For instance, the following example throws a \c CImgInstanceException: \code const CImg<float> img; // Define an empty image const float value = img.at(0); // Try to read first pixel value (does not exist) \endcode - \b CImgIOException: Thrown when an error occured when trying to load or save image files. This happens when trying to read files that do not exist or with invalid formats. For instance, the following example throws a \c CImgIOException: \code const CImg<float> img("missing_file.jpg"); // Try to load a file that does not exist \endcode - \b CImgWarningException: Thrown only if configuration macro \c cimg_strict_warnings is set, and when a \CImg function has to display a warning message (see cimg::warn()). It is not recommended to throw CImgException instances by yourself, since they are expected to be thrown only by \CImg. When an error occurs in a library function call, \CImg may display error messages on the screen or on the standard output, depending on the current \CImg exception mode. The \CImg exception mode can be get and set by functions cimg::exception_mode() and cimg::exception_mode(unsigned int). \par Exceptions handling In all cases, when an error occurs in \CImg, an instance of the corresponding exception class is thrown. This may lead the program to break (this is the default behavior), but you can bypass this behavior by handling the exceptions by yourself, using a usual <tt>try { ... } catch () { ... }</tt> bloc, as in the following example: \code #define "CImg.h" using namespace cimg_library; int main() { cimg::exception_mode(0); // Enable quiet exception mode try { ... // Here, do what you want to stress CImg } catch (CImgException& e) { // You succeeded: something went wrong! std::fprintf(stderr,"CImg Library Error: %s",e.what()); // Display your custom error message ... // Do what you want now to save the ship! } } \endcode **/ struct CImgException : public std::exception { #define _cimg_exception_err(etype,disp_flag) \ std::va_list ap, ap2; \ va_start(ap,format); va_start(ap2,format); \ int size = cimg_vsnprintf(0,0,format,ap2); \ if (size++>=0) { \ delete[] _message; \ _message = new char[size]; \ cimg_vsnprintf(_message,size,format,ap); \ if (cimg::exception_mode()) { \ std::fprintf(cimg::output(),"\n%s[CImg] *** %s ***%s %s\n",cimg::t_red,etype,cimg::t_normal,_message); \ if (cimg_display && disp_flag && !(cimg::exception_mode()%2)) try { cimg::dialog(etype,_message,"Abort"); } \ catch (CImgException&) {} \ if (cimg::exception_mode()>=3) cimg_library_suffixed::cimg::info(); \ } \ } \ va_end(ap); va_end(ap2); \ char *_message; CImgException() { _message = new char[1]; *_message = 0; } CImgException(const char *const format, ...):_message(0) { _cimg_exception_err("CImgException",true); } CImgException(const CImgException& e):std::exception(e) { const size_t size = std::strlen(e._message); _message = new char[size + 1]; std::strncpy(_message,e._message,size); _message[size] = 0; } ~CImgException() throw() { delete[] _message; } CImgException& operator=(const CImgException& e) { const size_t size = std::strlen(e._message); _message = new char[size + 1]; std::strncpy(_message,e._message,size); _message[size] = 0; return *this; } //! Return a C-string containing the error message associated to the thrown exception. const char *what() const throw() { return _message; } }; // struct CImgException { ... // The CImgAbortException class is used to throw an exception when // a computationally-intensive function has been aborted by an external signal. struct CImgAbortException : public std::exception { char *_message; CImgAbortException() { _message = new char[1]; *_message = 0; } CImgAbortException(const char *const format, ...):_message(0) { _cimg_exception_err("CImgAbortException",true); } CImgAbortException(const CImgAbortException& e):std::exception(e) { const size_t size = std::strlen(e._message); _message = new char[size + 1]; std::strncpy(_message,e._message,size); _message[size] = 0; } ~CImgAbortException() throw() { delete[] _message; } CImgAbortException& operator=(const CImgAbortException& e) { const size_t size = std::strlen(e._message); _message = new char[size + 1]; std::strncpy(_message,e._message,size); _message[size] = 0; return *this; } //! Return a C-string containing the error message associated to the thrown exception. const char *what() const throw() { return _message; } }; // struct CImgAbortException { ... // The CImgArgumentException class is used to throw an exception related // to invalid arguments encountered in a library function call. struct CImgArgumentException : public CImgException { CImgArgumentException(const char *const format, ...) { _cimg_exception_err("CImgArgumentException",true); } }; // struct CImgArgumentException { ... // The CImgDisplayException class is used to throw an exception related // to display problems encountered in a library function call. struct CImgDisplayException : public CImgException { CImgDisplayException(const char *const format, ...) { _cimg_exception_err("CImgDisplayException",false); } }; // struct CImgDisplayException { ... // The CImgInstanceException class is used to throw an exception related // to an invalid instance encountered in a library function call. struct CImgInstanceException : public CImgException { CImgInstanceException(const char *const format, ...) { _cimg_exception_err("CImgInstanceException",true); } }; // struct CImgInstanceException { ... // The CImgIOException class is used to throw an exception related // to input/output file problems encountered in a library function call. struct CImgIOException : public CImgException { CImgIOException(const char *const format, ...) { _cimg_exception_err("CImgIOException",true); } }; // struct CImgIOException { ... // The CImgWarningException class is used to throw an exception for warnings // encountered in a library function call. struct CImgWarningException : public CImgException { CImgWarningException(const char *const format, ...) { _cimg_exception_err("CImgWarningException",false); } }; // struct CImgWarningException { ... /*------------------------------------- # # Define cimg:: namespace # -----------------------------------*/ //! Contains \a low-level functions and variables of the \CImg Library. /** Most of the functions and variables within this namespace are used by the \CImg library for low-level operations. You may use them to access specific const values or environment variables internally used by \CImg. \warning Never write <tt>using namespace cimg_library::cimg;</tt> in your source code. Lot of functions in the <tt>cimg:: namespace</tt> have the same names as standard C functions that may be defined in the global namespace <tt>::</tt>. **/ namespace cimg { // Define traits that will be used to determine the best data type to work in CImg functions. // template<typename T> struct type { static const char* string() { static const char* s[] = { "unknown", "unknown8", "unknown16", "unknown24", "unknown32", "unknown40", "unknown48", "unknown56", "unknown64", "unknown72", "unknown80", "unknown88", "unknown96", "unknown104", "unknown112", "unknown120", "unknown128" }; return s[(sizeof(T)<17)?sizeof(T):0]; } static bool is_float() { return false; } static bool is_inf(const T) { return false; } static bool is_nan(const T) { return false; } static T min() { return ~max(); } static T max() { return (T)1<<(8*sizeof(T) - 1); } static T inf() { return max(); } static T cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(T)val; } static const char* format() { return "%s"; } static const char* format_s() { return "%s"; } static const char* format(const T& val) { static const char *const s = "unknown"; cimg::unused(val); return s; } }; template<> struct type<bool> { static const char* string() { static const char *const s = "bool"; return s; } static bool is_float() { return false; } static bool is_inf(const bool) { return false; } static bool is_nan(const bool) { return false; } static bool min() { return false; } static bool max() { return true; } static bool inf() { return max(); } static bool is_inf() { return false; } static bool cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(bool)val; } static const char* format() { return "%s"; } static const char* format_s() { return "%s"; } static const char* format(const bool val) { static const char* s[] = { "false", "true" }; return s[val?1:0]; } }; template<> struct type<unsigned char> { static const char* string() { static const char *const s = "unsigned char"; return s; } static bool is_float() { return false; } static bool is_inf(const unsigned char) { return false; } static bool is_nan(const unsigned char) { return false; } static unsigned char min() { return 0; } static unsigned char max() { return (unsigned char)-1; } static unsigned char inf() { return max(); } static unsigned char cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(unsigned char)val; } static const char* format() { return "%u"; } static const char* format_s() { return "%u"; } static unsigned int format(const unsigned char val) { return (unsigned int)val; } }; #if defined(CHAR_MAX) && CHAR_MAX==255 template<> struct type<char> { static const char* string() { static const char *const s = "char"; return s; } static bool is_float() { return false; } static bool is_inf(const char) { return false; } static bool is_nan(const char) { return false; } static char min() { return 0; } static char max() { return (char)-1; } static char inf() { return max(); } static char cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(unsigned char)val; } static const char* format() { return "%u"; } static const char* format_s() { return "%u"; } static unsigned int format(const char val) { return (unsigned int)val; } }; #else template<> struct type<char> { static const char* string() { static const char *const s = "char"; return s; } static bool is_float() { return false; } static bool is_inf(const char) { return false; } static bool is_nan(const char) { return false; } static char min() { return ~max(); } static char max() { return (char)((unsigned char)-1>>1); } static char inf() { return max(); } static char cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(char)val; } static const char* format() { return "%d"; } static const char* format_s() { return "%d"; } static int format(const char val) { return (int)val; } }; #endif template<> struct type<signed char> { static const char* string() { static const char *const s = "signed char"; return s; } static bool is_float() { return false; } static bool is_inf(const signed char) { return false; } static bool is_nan(const signed char) { return false; } static signed char min() { return ~max(); } static signed char max() { return (signed char)((unsigned char)-1>>1); } static signed char inf() { return max(); } static signed char cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(signed char)val; } static const char* format() { return "%d"; } static const char* format_s() { return "%d"; } static int format(const signed char val) { return (int)val; } }; template<> struct type<unsigned short> { static const char* string() { static const char *const s = "unsigned short"; return s; } static bool is_float() { return false; } static bool is_inf(const unsigned short) { return false; } static bool is_nan(const unsigned short) { return false; } static unsigned short min() { return 0; } static unsigned short max() { return (unsigned short)-1; } static unsigned short inf() { return max(); } static unsigned short cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(unsigned short)val; } static const char* format() { return "%u"; } static const char* format_s() { return "%u"; } static unsigned int format(const unsigned short val) { return (unsigned int)val; } }; template<> struct type<short> { static const char* string() { static const char *const s = "short"; return s; } static bool is_float() { return false; } static bool is_inf(const short) { return false; } static bool is_nan(const short) { return false; } static short min() { return ~max(); } static short max() { return (short)((unsigned short)-1>>1); } static short inf() { return max(); } static short cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(short)val; } static const char* format() { return "%d"; } static const char* format_s() { return "%d"; } static int format(const short val) { return (int)val; } }; template<> struct type<unsigned int> { static const char* string() { static const char *const s = "unsigned int"; return s; } static bool is_float() { return false; } static bool is_inf(const unsigned int) { return false; } static bool is_nan(const unsigned int) { return false; } static unsigned int min() { return 0; } static unsigned int max() { return (unsigned int)-1; } static unsigned int inf() { return max(); } static unsigned int cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(unsigned int)val; } static const char* format() { return "%u"; } static const char* format_s() { return "%u"; } static unsigned int format(const unsigned int val) { return val; } }; template<> struct type<int> { static const char* string() { static const char *const s = "int"; return s; } static bool is_float() { return false; } static bool is_inf(const int) { return false; } static bool is_nan(const int) { return false; } static int min() { return ~max(); } static int max() { return (int)((unsigned int)-1>>1); } static int inf() { return max(); } static int cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(int)val; } static const char* format() { return "%d"; } static const char* format_s() { return "%d"; } static int format(const int val) { return val; } }; template<> struct type<cimg_uint64> { static const char* string() { static const char *const s = "unsigned int64"; return s; } static bool is_float() { return false; } static bool is_inf(const cimg_uint64) { return false; } static bool is_nan(const cimg_uint64) { return false; } static cimg_uint64 min() { return 0; } static cimg_uint64 max() { return (cimg_uint64)-1; } static cimg_uint64 inf() { return max(); } static cimg_uint64 cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(cimg_uint64)val; } static const char* format() { return cimg_fuint64; } static const char* format_s() { return cimg_fuint64; } static unsigned long format(const cimg_uint64 val) { return (unsigned long)val; } }; template<> struct type<cimg_int64> { static const char* string() { static const char *const s = "int64"; return s; } static bool is_float() { return false; } static bool is_inf(const cimg_int64) { return false; } static bool is_nan(const cimg_int64) { return false; } static cimg_int64 min() { return ~max(); } static cimg_int64 max() { return (cimg_int64)((cimg_uint64)-1>>1); } static cimg_int64 inf() { return max(); } static cimg_int64 cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(cimg_int64)val; } static const char* format() { return cimg_fint64; } static const char* format_s() { return cimg_fint64; } static long format(const long val) { return (long)val; } }; template<> struct type<double> { static const char* string() { static const char *const s = "double"; return s; } static bool is_float() { return true; } static bool is_inf(const double val) { #ifdef isinf return (bool)isinf(val); #else return !is_nan(val) && (val<cimg::type<double>::min() || val>cimg::type<double>::max()); #endif } static bool is_nan(const double val) { // Custom version that works with '-ffast-math' if (sizeof(double)==8) { cimg_uint64 u; std::memcpy(&u,&val,sizeof(double)); return ((unsigned int)(u>>32)&0x7fffffff) + ((unsigned int)u!=0)>0x7ff00000; } #ifdef isnan return (bool)isnan(val); #else return !(val==val); #endif } static double min() { return -DBL_MAX; } static double max() { return DBL_MAX; } static double inf() { #ifdef INFINITY return (double)INFINITY; #else return max()*max(); #endif } static double nan() { #ifdef NAN return (double)NAN; #else const double val_nan = -std::sqrt(-1.); return val_nan; #endif } static double cut(const double val) { return val; } static const char* format() { return "%.17g"; } static const char* format_s() { return "%g"; } static double format(const double val) { return val; } }; template<> struct type<float> { static const char* string() { static const char *const s = "float"; return s; } static bool is_float() { return true; } static bool is_inf(const float val) { #ifdef isinf return (bool)isinf(val); #else return !is_nan(val) && (val<cimg::type<float>::min() || val>cimg::type<float>::max()); #endif } static bool is_nan(const float val) { // Custom version that works with '-ffast-math' if (sizeof(float)==4) { unsigned int u; std::memcpy(&u,&val,sizeof(float)); return (u&0x7fffffff)>0x7f800000; } #ifdef isnan return (bool)isnan(val); #else return !(val==val); #endif } static float min() { return -FLT_MAX; } static float max() { return FLT_MAX; } static float inf() { return (float)cimg::type<double>::inf(); } static float nan() { return (float)cimg::type<double>::nan(); } static float cut(const double val) { return (float)val; } static float cut(const float val) { return (float)val; } static const char* format() { return "%.9g"; } static const char* format_s() { return "%g"; } static double format(const float val) { return (double)val; } }; template<> struct type<long double> { static const char* string() { static const char *const s = "long double"; return s; } static bool is_float() { return true; } static bool is_inf(const long double val) { #ifdef isinf return (bool)isinf(val); #else return !is_nan(val) && (val<cimg::type<long double>::min() || val>cimg::type<long double>::max()); #endif } static bool is_nan(const long double val) { #ifdef isnan return (bool)isnan(val); #else return !(val==val); #endif } static long double min() { return -LDBL_MAX; } static long double max() { return LDBL_MAX; } static long double inf() { return max()*max(); } static long double nan() { const long double val_nan = -std::sqrt(-1.L); return val_nan; } static long double cut(const long double val) { return val; } static const char* format() { return "%.17g"; } static const char* format_s() { return "%g"; } static double format(const long double val) { return (double)val; } }; #ifdef cimg_use_half template<> struct type<half> { static const char* string() { static const char *const s = "half"; return s; } static bool is_float() { return true; } static bool is_inf(const long double val) { #ifdef isinf return (bool)isinf(val); #else return !is_nan(val) && (val<cimg::type<half>::min() || val>cimg::type<half>::max()); #endif } static bool is_nan(const half val) { // Custom version that works with '-ffast-math' if (sizeof(half)==2) { short u; std::memcpy(&u,&val,sizeof(short)); return (bool)((u&0x7fff)>0x7c00); } return cimg::type<float>::is_nan((float)val); } static half min() { return (half)-65504; } static half max() { return (half)65504; } static half inf() { return max()*max(); } static half nan() { const half val_nan = (half)-std::sqrt(-1.); return val_nan; } static half cut(const double val) { return (half)val; } static const char* format() { return "%.9g"; } static const char* format_s() { return "%g"; } static double format(const half val) { return (double)val; } }; #endif template<typename T, typename t> struct superset { typedef T type; }; template<> struct superset<bool,unsigned char> { typedef unsigned char type; }; template<> struct superset<bool,char> { typedef char type; }; template<> struct superset<bool,signed char> { typedef signed char type; }; template<> struct superset<bool,unsigned short> { typedef unsigned short type; }; template<> struct superset<bool,short> { typedef short type; }; template<> struct superset<bool,unsigned int> { typedef unsigned int type; }; template<> struct superset<bool,int> { typedef int type; }; template<> struct superset<bool,cimg_uint64> { typedef cimg_uint64 type; }; template<> struct superset<bool,cimg_int64> { typedef cimg_int64 type; }; template<> struct superset<bool,float> { typedef float type; }; template<> struct superset<bool,double> { typedef double type; }; template<> struct superset<unsigned char,char> { typedef short type; }; template<> struct superset<unsigned char,signed char> { typedef short type; }; template<> struct superset<unsigned char,unsigned short> { typedef unsigned short type; }; template<> struct superset<unsigned char,short> { typedef short type; }; template<> struct superset<unsigned char,unsigned int> { typedef unsigned int type; }; template<> struct superset<unsigned char,int> { typedef int type; }; template<> struct superset<unsigned char,cimg_uint64> { typedef cimg_uint64 type; }; template<> struct superset<unsigned char,cimg_int64> { typedef cimg_int64 type; }; template<> struct superset<unsigned char,float> { typedef float type; }; template<> struct superset<unsigned char,double> { typedef double type; }; template<> struct superset<signed char,unsigned char> { typedef short type; }; template<> struct superset<signed char,char> { typedef short type; }; template<> struct superset<signed char,unsigned short> { typedef int type; }; template<> struct superset<signed char,short> { typedef short type; }; template<> struct superset<signed char,unsigned int> { typedef cimg_int64 type; }; template<> struct superset<signed char,int> { typedef int type; }; template<> struct superset<signed char,cimg_uint64> { typedef cimg_int64 type; }; template<> struct superset<signed char,cimg_int64> { typedef cimg_int64 type; }; template<> struct superset<signed char,float> { typedef float type; }; template<> struct superset<signed char,double> { typedef double type; }; template<> struct superset<char,unsigned char> { typedef short type; }; template<> struct superset<char,signed char> { typedef short type; }; template<> struct superset<char,unsigned short> { typedef int type; }; template<> struct superset<char,short> { typedef short type; }; template<> struct superset<char,unsigned int> { typedef cimg_int64 type; }; template<> struct superset<char,int> { typedef int type; }; template<> struct superset<char,cimg_uint64> { typedef cimg_int64 type; }; template<> struct superset<char,cimg_int64> { typedef cimg_int64 type; }; template<> struct superset<char,float> { typedef float type; }; template<> struct superset<char,double> { typedef double type; }; template<> struct superset<unsigned short,char> { typedef int type; }; template<> struct superset<unsigned short,signed char> { typedef int type; }; template<> struct superset<unsigned short,short> { typedef int type; }; template<> struct superset<unsigned short,unsigned int> { typedef unsigned int type; }; template<> struct superset<unsigned short,int> { typedef int type; }; template<> struct superset<unsigned short,cimg_uint64> { typedef cimg_uint64 type; }; template<> struct superset<unsigned short,cimg_int64> { typedef cimg_int64 type; }; template<> struct superset<unsigned short,float> { typedef float type; }; template<> struct superset<unsigned short,double> { typedef double type; }; template<> struct superset<short,unsigned short> { typedef int type; }; template<> struct superset<short,unsigned int> { typedef cimg_int64 type; }; template<> struct superset<short,int> { typedef int type; }; template<> struct superset<short,cimg_uint64> { typedef cimg_int64 type; }; template<> struct superset<short,cimg_int64> { typedef cimg_int64 type; }; template<> struct superset<short,float> { typedef float type; }; template<> struct superset<short,double> { typedef double type; }; template<> struct superset<unsigned int,char> { typedef cimg_int64 type; }; template<> struct superset<unsigned int,signed char> { typedef cimg_int64 type; }; template<> struct superset<unsigned int,short> { typedef cimg_int64 type; }; template<> struct superset<unsigned int,int> { typedef cimg_int64 type; }; template<> struct superset<unsigned int,cimg_uint64> { typedef cimg_uint64 type; }; template<> struct superset<unsigned int,cimg_int64> { typedef cimg_int64 type; }; template<> struct superset<unsigned int,float> { typedef float type; }; template<> struct superset<unsigned int,double> { typedef double type; }; template<> struct superset<int,unsigned int> { typedef cimg_int64 type; }; template<> struct superset<int,cimg_uint64> { typedef cimg_int64 type; }; template<> struct superset<int,cimg_int64> { typedef cimg_int64 type; }; template<> struct superset<int,float> { typedef float type; }; template<> struct superset<int,double> { typedef double type; }; template<> struct superset<cimg_uint64,char> { typedef cimg_int64 type; }; template<> struct superset<cimg_uint64,signed char> { typedef cimg_int64 type; }; template<> struct superset<cimg_uint64,short> { typedef cimg_int64 type; }; template<> struct superset<cimg_uint64,int> { typedef cimg_int64 type; }; template<> struct superset<cimg_uint64,cimg_int64> { typedef cimg_int64 type; }; template<> struct superset<cimg_uint64,float> { typedef double type; }; template<> struct superset<cimg_uint64,double> { typedef double type; }; template<> struct superset<cimg_int64,float> { typedef double type; }; template<> struct superset<cimg_int64,double> { typedef double type; }; template<> struct superset<float,double> { typedef double type; }; #ifdef cimg_use_half template<> struct superset<half,unsigned short> { typedef float type; }; template<> struct superset<half,short> { typedef float type; }; template<> struct superset<half,unsigned int> { typedef float type; }; template<> struct superset<half,int> { typedef float type; }; template<> struct superset<half,cimg_uint64> { typedef float type; }; template<> struct superset<half,cimg_int64> { typedef float type; }; template<> struct superset<half,float> { typedef float type; }; template<> struct superset<half,double> { typedef double type; }; #endif template<typename t1, typename t2, typename t3> struct superset2 { typedef typename superset<t1, typename superset<t2,t3>::type>::type type; }; template<typename t1, typename t2, typename t3, typename t4> struct superset3 { typedef typename superset<t1, typename superset2<t2,t3,t4>::type>::type type; }; template<typename t1, typename t2> struct last { typedef t2 type; }; #define _cimg_Tt typename cimg::superset<T,t>::type #define _cimg_Tfloat typename cimg::superset<T,float>::type #define _cimg_Ttfloat typename cimg::superset2<T,t,float>::type #define _cimg_Ttdouble typename cimg::superset2<T,t,double>::type // Define variables used internally by CImg. #if cimg_display==1 struct X11_info { unsigned int nb_wins; pthread_t *events_thread; pthread_cond_t wait_event; pthread_mutex_t wait_event_mutex; CImgDisplay **wins; Display *display; unsigned int nb_bits; bool is_blue_first; bool is_shm_enabled; bool byte_order; #ifdef cimg_use_xrandr XRRScreenSize *resolutions; Rotation curr_rotation; unsigned int curr_resolution; unsigned int nb_resolutions; #endif X11_info():nb_wins(0),events_thread(0),display(0), nb_bits(0),is_blue_first(false),is_shm_enabled(false),byte_order(false) { #ifdef __FreeBSD__ XInitThreads(); #endif wins = new CImgDisplay*[1024]; pthread_mutex_init(&wait_event_mutex,0); pthread_cond_init(&wait_event,0); #ifdef cimg_use_xrandr resolutions = 0; curr_rotation = 0; curr_resolution = nb_resolutions = 0; #endif } ~X11_info() { delete[] wins; /* if (events_thread) { pthread_cancel(*events_thread); delete events_thread; } if (display) { } // XCloseDisplay(display); } pthread_cond_destroy(&wait_event); pthread_mutex_unlock(&wait_event_mutex); pthread_mutex_destroy(&wait_event_mutex); */ } }; // struct X11_info { ... #if defined(cimg_module) X11_info& X11_attr(); #elif defined(cimg_main) X11_info& X11_attr() { static X11_info val; return val; } #else inline X11_info& X11_attr() { static X11_info val; return val; } #endif #elif cimg_display==2 struct Win32_info { HANDLE wait_event; Win32_info() { wait_event = CreateEvent(0,FALSE,FALSE,0); } }; // struct Win32_info { ... #if defined(cimg_module) Win32_info& Win32_attr(); #elif defined(cimg_main) Win32_info& Win32_attr() { static Win32_info val; return val; } #else inline Win32_info& Win32_attr() { static Win32_info val; return val; } #endif #endif #define cimg_lock_display() cimg::mutex(15) #define cimg_unlock_display() cimg::mutex(15,0) struct Mutex_info { #ifdef _PTHREAD_H pthread_mutex_t mutex[32]; Mutex_info() { for (unsigned int i = 0; i<32; ++i) pthread_mutex_init(&mutex[i],0); } void lock(const unsigned int n) { pthread_mutex_lock(&mutex[n]); } void unlock(const unsigned int n) { pthread_mutex_unlock(&mutex[n]); } int trylock(const unsigned int n) { return pthread_mutex_trylock(&mutex[n]); } #elif cimg_OS==2 HANDLE mutex[32]; Mutex_info() { for (unsigned int i = 0; i<32; ++i) mutex[i] = CreateMutex(0,FALSE,0); } void lock(const unsigned int n) { WaitForSingleObject(mutex[n],INFINITE); } void unlock(const unsigned int n) { ReleaseMutex(mutex[n]); } int trylock(const unsigned int) { return 0; } #else Mutex_info() {} void lock(const unsigned int) {} void unlock(const unsigned int) {} int trylock(const unsigned int) { return 0; } #endif }; // struct Mutex_info { ... #if defined(cimg_module) Mutex_info& Mutex_attr(); #elif defined(cimg_main) Mutex_info& Mutex_attr() { static Mutex_info val; return val; } #else inline Mutex_info& Mutex_attr() { static Mutex_info val; return val; } #endif #if defined(cimg_use_magick) struct Magick_info { Magick_info() { Magick::InitializeMagick(""); } }; // struct Magick_info { ... static Magick_info _Magick_info; #endif #if defined(cimg_use_fftw3) struct FFTW3_info { FFTW3_info() { fftw_init_threads(); } }; // struct FFTW3_info { ... static FFTW3_info _FFTW3_info; #endif #if cimg_display==1 // Define keycodes for X11-based graphical systems. const unsigned int keyESC = XK_Escape; const unsigned int keyF1 = XK_F1; const unsigned int keyF2 = XK_F2; const unsigned int keyF3 = XK_F3; const unsigned int keyF4 = XK_F4; const unsigned int keyF5 = XK_F5; const unsigned int keyF6 = XK_F6; const unsigned int keyF7 = XK_F7; const unsigned int keyF8 = XK_F8; const unsigned int keyF9 = XK_F9; const unsigned int keyF10 = XK_F10; const unsigned int keyF11 = XK_F11; const unsigned int keyF12 = XK_F12; const unsigned int keyPAUSE = XK_Pause; const unsigned int key1 = XK_1; const unsigned int key2 = XK_2; const unsigned int key3 = XK_3; const unsigned int key4 = XK_4; const unsigned int key5 = XK_5; const unsigned int key6 = XK_6; const unsigned int key7 = XK_7; const unsigned int key8 = XK_8; const unsigned int key9 = XK_9; const unsigned int key0 = XK_0; const unsigned int keyBACKSPACE = XK_BackSpace; const unsigned int keyINSERT = XK_Insert; const unsigned int keyHOME = XK_Home; const unsigned int keyPAGEUP = XK_Page_Up; const unsigned int keyTAB = XK_Tab; const unsigned int keyQ = XK_q; const unsigned int keyW = XK_w; const unsigned int keyE = XK_e; const unsigned int keyR = XK_r; const unsigned int keyT = XK_t; const unsigned int keyY = XK_y; const unsigned int keyU = XK_u; const unsigned int keyI = XK_i; const unsigned int keyO = XK_o; const unsigned int keyP = XK_p; const unsigned int keyDELETE = XK_Delete; const unsigned int keyEND = XK_End; const unsigned int keyPAGEDOWN = XK_Page_Down; const unsigned int keyCAPSLOCK = XK_Caps_Lock; const unsigned int keyA = XK_a; const unsigned int keyS = XK_s; const unsigned int keyD = XK_d; const unsigned int keyF = XK_f; const unsigned int keyG = XK_g; const unsigned int keyH = XK_h; const unsigned int keyJ = XK_j; const unsigned int keyK = XK_k; const unsigned int keyL = XK_l; const unsigned int keyENTER = XK_Return; const unsigned int keySHIFTLEFT = XK_Shift_L; const unsigned int keyZ = XK_z; const unsigned int keyX = XK_x; const unsigned int keyC = XK_c; const unsigned int keyV = XK_v; const unsigned int keyB = XK_b; const unsigned int keyN = XK_n; const unsigned int keyM = XK_m; const unsigned int keySHIFTRIGHT = XK_Shift_R; const unsigned int keyARROWUP = XK_Up; const unsigned int keyCTRLLEFT = XK_Control_L; const unsigned int keyAPPLEFT = XK_Super_L; const unsigned int keyALT = XK_Alt_L; const unsigned int keySPACE = XK_space; const unsigned int keyALTGR = XK_Alt_R; const unsigned int keyAPPRIGHT = XK_Super_R; const unsigned int keyMENU = XK_Menu; const unsigned int keyCTRLRIGHT = XK_Control_R; const unsigned int keyARROWLEFT = XK_Left; const unsigned int keyARROWDOWN = XK_Down; const unsigned int keyARROWRIGHT = XK_Right; const unsigned int keyPAD0 = XK_KP_0; const unsigned int keyPAD1 = XK_KP_1; const unsigned int keyPAD2 = XK_KP_2; const unsigned int keyPAD3 = XK_KP_3; const unsigned int keyPAD4 = XK_KP_4; const unsigned int keyPAD5 = XK_KP_5; const unsigned int keyPAD6 = XK_KP_6; const unsigned int keyPAD7 = XK_KP_7; const unsigned int keyPAD8 = XK_KP_8; const unsigned int keyPAD9 = XK_KP_9; const unsigned int keyPADADD = XK_KP_Add; const unsigned int keyPADSUB = XK_KP_Subtract; const unsigned int keyPADMUL = XK_KP_Multiply; const unsigned int keyPADDIV = XK_KP_Divide; #elif cimg_display==2 // Define keycodes for Windows. const unsigned int keyESC = VK_ESCAPE; const unsigned int keyF1 = VK_F1; const unsigned int keyF2 = VK_F2; const unsigned int keyF3 = VK_F3; const unsigned int keyF4 = VK_F4; const unsigned int keyF5 = VK_F5; const unsigned int keyF6 = VK_F6; const unsigned int keyF7 = VK_F7; const unsigned int keyF8 = VK_F8; const unsigned int keyF9 = VK_F9; const unsigned int keyF10 = VK_F10; const unsigned int keyF11 = VK_F11; const unsigned int keyF12 = VK_F12; const unsigned int keyPAUSE = VK_PAUSE; const unsigned int key1 = '1'; const unsigned int key2 = '2'; const unsigned int key3 = '3'; const unsigned int key4 = '4'; const unsigned int key5 = '5'; const unsigned int key6 = '6'; const unsigned int key7 = '7'; const unsigned int key8 = '8'; const unsigned int key9 = '9'; const unsigned int key0 = '0'; const unsigned int keyBACKSPACE = VK_BACK; const unsigned int keyINSERT = VK_INSERT; const unsigned int keyHOME = VK_HOME; const unsigned int keyPAGEUP = VK_PRIOR; const unsigned int keyTAB = VK_TAB; const unsigned int keyQ = 'Q'; const unsigned int keyW = 'W'; const unsigned int keyE = 'E'; const unsigned int keyR = 'R'; const unsigned int keyT = 'T'; const unsigned int keyY = 'Y'; const unsigned int keyU = 'U'; const unsigned int keyI = 'I'; const unsigned int keyO = 'O'; const unsigned int keyP = 'P'; const unsigned int keyDELETE = VK_DELETE; const unsigned int keyEND = VK_END; const unsigned int keyPAGEDOWN = VK_NEXT; const unsigned int keyCAPSLOCK = VK_CAPITAL; const unsigned int keyA = 'A'; const unsigned int keyS = 'S'; const unsigned int keyD = 'D'; const unsigned int keyF = 'F'; const unsigned int keyG = 'G'; const unsigned int keyH = 'H'; const unsigned int keyJ = 'J'; const unsigned int keyK = 'K'; const unsigned int keyL = 'L'; const unsigned int keyENTER = VK_RETURN; const unsigned int keySHIFTLEFT = VK_SHIFT; const unsigned int keyZ = 'Z'; const unsigned int keyX = 'X'; const unsigned int keyC = 'C'; const unsigned int keyV = 'V'; const unsigned int keyB = 'B'; const unsigned int keyN = 'N'; const unsigned int keyM = 'M'; const unsigned int keySHIFTRIGHT = VK_SHIFT; const unsigned int keyARROWUP = VK_UP; const unsigned int keyCTRLLEFT = VK_CONTROL; const unsigned int keyAPPLEFT = VK_LWIN; const unsigned int keyALT = VK_LMENU; const unsigned int keySPACE = VK_SPACE; const unsigned int keyALTGR = VK_CONTROL; const unsigned int keyAPPRIGHT = VK_RWIN; const unsigned int keyMENU = VK_APPS; const unsigned int keyCTRLRIGHT = VK_CONTROL; const unsigned int keyARROWLEFT = VK_LEFT; const unsigned int keyARROWDOWN = VK_DOWN; const unsigned int keyARROWRIGHT = VK_RIGHT; const unsigned int keyPAD0 = 0x60; const unsigned int keyPAD1 = 0x61; const unsigned int keyPAD2 = 0x62; const unsigned int keyPAD3 = 0x63; const unsigned int keyPAD4 = 0x64; const unsigned int keyPAD5 = 0x65; const unsigned int keyPAD6 = 0x66; const unsigned int keyPAD7 = 0x67; const unsigned int keyPAD8 = 0x68; const unsigned int keyPAD9 = 0x69; const unsigned int keyPADADD = VK_ADD; const unsigned int keyPADSUB = VK_SUBTRACT; const unsigned int keyPADMUL = VK_MULTIPLY; const unsigned int keyPADDIV = VK_DIVIDE; #else // Define random keycodes when no display is available. // (should rarely be used then!). const unsigned int keyESC = 1U; //!< Keycode for the \c ESC key (architecture-dependent) const unsigned int keyF1 = 2U; //!< Keycode for the \c F1 key (architecture-dependent) const unsigned int keyF2 = 3U; //!< Keycode for the \c F2 key (architecture-dependent) const unsigned int keyF3 = 4U; //!< Keycode for the \c F3 key (architecture-dependent) const unsigned int keyF4 = 5U; //!< Keycode for the \c F4 key (architecture-dependent) const unsigned int keyF5 = 6U; //!< Keycode for the \c F5 key (architecture-dependent) const unsigned int keyF6 = 7U; //!< Keycode for the \c F6 key (architecture-dependent) const unsigned int keyF7 = 8U; //!< Keycode for the \c F7 key (architecture-dependent) const unsigned int keyF8 = 9U; //!< Keycode for the \c F8 key (architecture-dependent) const unsigned int keyF9 = 10U; //!< Keycode for the \c F9 key (architecture-dependent) const unsigned int keyF10 = 11U; //!< Keycode for the \c F10 key (architecture-dependent) const unsigned int keyF11 = 12U; //!< Keycode for the \c F11 key (architecture-dependent) const unsigned int keyF12 = 13U; //!< Keycode for the \c F12 key (architecture-dependent) const unsigned int keyPAUSE = 14U; //!< Keycode for the \c PAUSE key (architecture-dependent) const unsigned int key1 = 15U; //!< Keycode for the \c 1 key (architecture-dependent) const unsigned int key2 = 16U; //!< Keycode for the \c 2 key (architecture-dependent) const unsigned int key3 = 17U; //!< Keycode for the \c 3 key (architecture-dependent) const unsigned int key4 = 18U; //!< Keycode for the \c 4 key (architecture-dependent) const unsigned int key5 = 19U; //!< Keycode for the \c 5 key (architecture-dependent) const unsigned int key6 = 20U; //!< Keycode for the \c 6 key (architecture-dependent) const unsigned int key7 = 21U; //!< Keycode for the \c 7 key (architecture-dependent) const unsigned int key8 = 22U; //!< Keycode for the \c 8 key (architecture-dependent) const unsigned int key9 = 23U; //!< Keycode for the \c 9 key (architecture-dependent) const unsigned int key0 = 24U; //!< Keycode for the \c 0 key (architecture-dependent) const unsigned int keyBACKSPACE = 25U; //!< Keycode for the \c BACKSPACE key (architecture-dependent) const unsigned int keyINSERT = 26U; //!< Keycode for the \c INSERT key (architecture-dependent) const unsigned int keyHOME = 27U; //!< Keycode for the \c HOME key (architecture-dependent) const unsigned int keyPAGEUP = 28U; //!< Keycode for the \c PAGEUP key (architecture-dependent) const unsigned int keyTAB = 29U; //!< Keycode for the \c TAB key (architecture-dependent) const unsigned int keyQ = 30U; //!< Keycode for the \c Q key (architecture-dependent) const unsigned int keyW = 31U; //!< Keycode for the \c W key (architecture-dependent) const unsigned int keyE = 32U; //!< Keycode for the \c E key (architecture-dependent) const unsigned int keyR = 33U; //!< Keycode for the \c R key (architecture-dependent) const unsigned int keyT = 34U; //!< Keycode for the \c T key (architecture-dependent) const unsigned int keyY = 35U; //!< Keycode for the \c Y key (architecture-dependent) const unsigned int keyU = 36U; //!< Keycode for the \c U key (architecture-dependent) const unsigned int keyI = 37U; //!< Keycode for the \c I key (architecture-dependent) const unsigned int keyO = 38U; //!< Keycode for the \c O key (architecture-dependent) const unsigned int keyP = 39U; //!< Keycode for the \c P key (architecture-dependent) const unsigned int keyDELETE = 40U; //!< Keycode for the \c DELETE key (architecture-dependent) const unsigned int keyEND = 41U; //!< Keycode for the \c END key (architecture-dependent) const unsigned int keyPAGEDOWN = 42U; //!< Keycode for the \c PAGEDOWN key (architecture-dependent) const unsigned int keyCAPSLOCK = 43U; //!< Keycode for the \c CAPSLOCK key (architecture-dependent) const unsigned int keyA = 44U; //!< Keycode for the \c A key (architecture-dependent) const unsigned int keyS = 45U; //!< Keycode for the \c S key (architecture-dependent) const unsigned int keyD = 46U; //!< Keycode for the \c D key (architecture-dependent) const unsigned int keyF = 47U; //!< Keycode for the \c F key (architecture-dependent) const unsigned int keyG = 48U; //!< Keycode for the \c G key (architecture-dependent) const unsigned int keyH = 49U; //!< Keycode for the \c H key (architecture-dependent) const unsigned int keyJ = 50U; //!< Keycode for the \c J key (architecture-dependent) const unsigned int keyK = 51U; //!< Keycode for the \c K key (architecture-dependent) const unsigned int keyL = 52U; //!< Keycode for the \c L key (architecture-dependent) const unsigned int keyENTER = 53U; //!< Keycode for the \c ENTER key (architecture-dependent) const unsigned int keySHIFTLEFT = 54U; //!< Keycode for the \c SHIFTLEFT key (architecture-dependent) const unsigned int keyZ = 55U; //!< Keycode for the \c Z key (architecture-dependent) const unsigned int keyX = 56U; //!< Keycode for the \c X key (architecture-dependent) const unsigned int keyC = 57U; //!< Keycode for the \c C key (architecture-dependent) const unsigned int keyV = 58U; //!< Keycode for the \c V key (architecture-dependent) const unsigned int keyB = 59U; //!< Keycode for the \c B key (architecture-dependent) const unsigned int keyN = 60U; //!< Keycode for the \c N key (architecture-dependent) const unsigned int keyM = 61U; //!< Keycode for the \c M key (architecture-dependent) const unsigned int keySHIFTRIGHT = 62U; //!< Keycode for the \c SHIFTRIGHT key (architecture-dependent) const unsigned int keyARROWUP = 63U; //!< Keycode for the \c ARROWUP key (architecture-dependent) const unsigned int keyCTRLLEFT = 64U; //!< Keycode for the \c CTRLLEFT key (architecture-dependent) const unsigned int keyAPPLEFT = 65U; //!< Keycode for the \c APPLEFT key (architecture-dependent) const unsigned int keyALT = 66U; //!< Keycode for the \c ALT key (architecture-dependent) const unsigned int keySPACE = 67U; //!< Keycode for the \c SPACE key (architecture-dependent) const unsigned int keyALTGR = 68U; //!< Keycode for the \c ALTGR key (architecture-dependent) const unsigned int keyAPPRIGHT = 69U; //!< Keycode for the \c APPRIGHT key (architecture-dependent) const unsigned int keyMENU = 70U; //!< Keycode for the \c MENU key (architecture-dependent) const unsigned int keyCTRLRIGHT = 71U; //!< Keycode for the \c CTRLRIGHT key (architecture-dependent) const unsigned int keyARROWLEFT = 72U; //!< Keycode for the \c ARROWLEFT key (architecture-dependent) const unsigned int keyARROWDOWN = 73U; //!< Keycode for the \c ARROWDOWN key (architecture-dependent) const unsigned int keyARROWRIGHT = 74U; //!< Keycode for the \c ARROWRIGHT key (architecture-dependent) const unsigned int keyPAD0 = 75U; //!< Keycode for the \c PAD0 key (architecture-dependent) const unsigned int keyPAD1 = 76U; //!< Keycode for the \c PAD1 key (architecture-dependent) const unsigned int keyPAD2 = 77U; //!< Keycode for the \c PAD2 key (architecture-dependent) const unsigned int keyPAD3 = 78U; //!< Keycode for the \c PAD3 key (architecture-dependent) const unsigned int keyPAD4 = 79U; //!< Keycode for the \c PAD4 key (architecture-dependent) const unsigned int keyPAD5 = 80U; //!< Keycode for the \c PAD5 key (architecture-dependent) const unsigned int keyPAD6 = 81U; //!< Keycode for the \c PAD6 key (architecture-dependent) const unsigned int keyPAD7 = 82U; //!< Keycode for the \c PAD7 key (architecture-dependent) const unsigned int keyPAD8 = 83U; //!< Keycode for the \c PAD8 key (architecture-dependent) const unsigned int keyPAD9 = 84U; //!< Keycode for the \c PAD9 key (architecture-dependent) const unsigned int keyPADADD = 85U; //!< Keycode for the \c PADADD key (architecture-dependent) const unsigned int keyPADSUB = 86U; //!< Keycode for the \c PADSUB key (architecture-dependent) const unsigned int keyPADMUL = 87U; //!< Keycode for the \c PADMUL key (architecture-dependent) const unsigned int keyPADDIV = 88U; //!< Keycode for the \c PADDDIV key (architecture-dependent) #endif const double PI = 3.14159265358979323846; //!< Value of the mathematical constant PI // Define a 10x13 binary font (small sans). static const char *const data_font_small[] = { " UwlwnwoyuwHwlwmwcwlwnw[xuwowlwmwoyuwRwlwnxcw Mw (wnwnwuwpwuypwuwoy" "ZwnwmwuwowuwmwnwnwuwowuwfwuxnwnwmwuwpwuypwuwZwnwnwtwpwtwow'y Hw cwnw >{ jw %xdxZwdw_wexfwYwkw 7yowoyFx=w " "ry qw %wuw !xnwkwnwoyuwfwuw[wkwnwcwowrwpwdwuwoxuwpwkwnwoyuwRwkwnwbwpwNyoyoyoyoy;wdwnxpxtxowG|!ydwnwuwowtwow" "pxswqxlwnxnxmwDwoyoxnyoymwp{oyq{pyoy>ypwqwpwp{oyqzo{q{pzrwrwowlwqwswpwnwqwsxswpypzoyqzozq}swrwrwqwtwswswtxsxswq" "ws}qwnwkwnydwew_wfwdwkwmwowkw(w0wmwmwGwtwdxQw swuwnwo{q{pynwp|rwtwtwqydwcwcwcwmwmxgwqwpwnzpwuwpzoyRzoyoyexnynwd" "z\\xnxgxrwsxrwsyswowmwmwmwmwmwmwo}ryp{q{q{q{nwmwnwmwozqxswpyoyoyoyoyeyuwswrwrwrwrwrwrwrwrwqwrwmwtwnwmwnwuwpwuyp" "wuwoyZwmwnwuwowuwmwqwkwuwowuwoxnwuxowmwnwuwpwuypwuwZwmwnwuwowuwnwowmwtw\\wuwuwqwswqwswqwswqwswEwqwtweypzr~qyIw " "rwswewnwuwowuwozswtwuwqwtwmwnwlwowuwuwowOxpxuxqwuwowswqwswoxpwlwjwqwswqwsw<wrwowrwuwqwrwqwswrwswpwmwmwrwswrwowl" "wqwtwownxsxsxswqwswqwswqwswrwswqwrwowpwrwrwqwtwswswswswqwswmwpwmwlwoxuxSw_wfwdwYwkw(w0wmwmwGwtwoxnwNw uwswpwuwp" "wmwmwswq{rwrwrwtwtwrwswfydwdyZwnwtwrwqwrwswowowdwrwqxuwSwrwfwuwnwlwnw[yuw[wowtwgwswqwswqwswewuwowuwowuwowuwowuw" "nwowuwowswqwmwmwmwjwmwnwmwowswrxswqwswqwswqwswqwswqwswrwrwqwswrwrwrwrwrwrwrwrwqwswqzpwtw #w DwPwtwtwswqwswuwuwu" "wswswuwswqwGwqxtwf{qzr~r{qzqwrwpxowtwrw rzcwnwuwq}rwuwqwtwuwqwtwmwnwlwnynwOwowswowkwmwpwuwpwmwjwpwswqwswowmwjwi" "wjxswsytwrwuwqwrwrwmwrwqwmwnwmwrwowlwqwuwnwnxsxswuwtwrwqwrwswrwqwswswqwjwpwrwqwswrwtwtwqwuwowuwmwowmwlwpxsx]ypz" "oyozpypzozqznwmwowtwnwqzuyrzoypzozqwuxoypzpwswrwrwrwtwtwswrwrwrwq{owmwmwQyuwqwtwmwoxnypzqxswowowswqwswqwtxr|rwt" "wtwqyp{q{qwswpwuwownwnwqwsxuwuxswrwrwtwtwswqwrwmwuwuwnwnwowtwpwuwuwewnzpwn{pwuwnwnxgwtxtwrwtwowtw_wuytwgynwmwlw" "gwswpyuw[wowtwqwtwpwtwpwtwowuwmwnwuwowuwowuwowuwowuwowuwqxuwpwlwmwmwmwjwmwnwmwowrwswuwtwrwqwswqwswqwswqwswqwrwt" "wqwswuwswrwrwrwrwrwrwrwpwuwpwswqwuwnyoyoyoyoyoyqyuyqyoyoyoyoymwqwjwmwnypzoyoyoyoyoynwnzqwswqwswqwswqwswrwrwqzqw" "rw^}s}swtwtwswtwtwswtwtwK}rwuwe{s~t~s}rwtwqwrwpxowtwrw qwawewtwpwuwpxuwpycwlwnynwOwowswowkwpypwtwpzpzmwoypwsw[y" "r}rymwrwtwtwtwrwuwq{qwmwrwq{q{rwm|owlwqxmwnwuwuwuwswuwtwrwqwrwswrwqwswswqylwpwrwqwswrwuwuwuwpwmwmwnwmwlwMwqwswq" "wmwswqwswpwnwswqwswowmwowuwmwqwswswswswqwswqwswqwswqxnwswpwnwswrwrwrwtwtwrwtwqwrwmwqxlwlx]xuxrwtyqwuwlwpwtwpwmw" "swqwtxpxowswrwqwswtwuxrwtwqwtwtwrwswrwswnwo{pwuwnxpwnwqwswtwtwswrwrwtwtwswuyuwswjwkwowpwrwowcwowuwnwnwswqxuxowo" "wtwhwuwrwrzpwtwq}jwuwtwuw_}qyoxfwswpyuwowdyoxowtwryuwqyuwqyuwmwnwuwowuwowuwowuwowuwowuwqwt{twl{q{q{q{nwmwnwmwpz" "twswuwtwrwqwswqwswqwswqwswqwqxpwtwtwswrwrwrwrwrwrwrwowowswqwuwkwmwmwmwmwmwowswswmwswqwswqwswqwswnwqwjwmwowswqws" "wqwswqwswqwswqwswqwswgwtxqwswqwswqwswqwswrwrwqwswrwrw^wtwtwswqwswuwuwuwswuwswswqwHwowuwf}t~s|r}swrwrwrwqwtwpwtw" "r~#zcwewtwoynwuxtwtwswgwlwowuwuwr}gyexowswowlwlwrwswlwqwswowowswpz^yayqwqwtwtwuwrwswrwrwrwmwrwqwmwnwsyswrwowlwq" "wuwnwnwuwuwuwswtwuwrwqwrzqwqwszmyowpwrwpwuwqwuwuwuwpwmwmwnwlwmwPzqwswqwmwswq{pwnwswqwswowmwoxlwqwswswswswqwswqw" "swqwswqwlxnwnwswqwtwqwuwuwuwqxowtwmwnwmwmwoytwiwtwtwswswpwtxqzpwswpxowswpwuwowuwpwswrwtwtwswtwtwrwtwqwtwtwrwswr" "wswnwowswqwswowownwqwswtwtwswrwqwuwuwrwuyuwt~pwq~pwq~pwcwowuwozpwswowewswiwuwrwiwtwjwjwuytw\\wRwswoxuwHwtwpwswq" "wtxqwswqxowswqwswqwswqwswqwswqwswrwtwpwlwmwmwmwjwmwnwmwowrwswtwuwrwqwswqwswqwswqwswqwqxpwtwtwswrwrwrwrwrwrwrwow" "owswqwtwozpzpzpzpzpzr~swm{q{q{q{nwqwjwmwowswqwswqwswqwswqwswqwswqwswr}rwuwuwqwswqwswqwswqwswqwtwpwswqwtw\\wuwuw" "qwswqwswqwswqwswJ}qxf}t~rzp{rwrwrwrwqwtwpwtwrw qwawg}owuwpwuwtwuwswuwfwlwmwmwPwnwswowmwkwr|mwqwswowowswmw^yo}oy" "qwqwszq{rwrwrwmwrwqwmwnwqwswrwowlwqwtwownwtwtwswtwuwrwqwrwnwqwswtwkwowpwrwpwuwqwuwuwuwqwuwnwnwmwlwmwQwswqwswqwm" "wswqwlwnwswqwswowmwowuwmwqwswswswswqwswqwswqwswqwjwownwswqwtwqwuwuwuwqxowtwnwmwmwmwpwtyhwtwtwswswpwswqwtwpwswqw" "mwswpwuwpwtwpwswrwtwtwswtwtwrwtwqwtwtwrwswrwswnwowswqwswpwnwnwqwsxuwuxswrwpyqwqwswjwkwqwuwuwrwrwqwuwuwewowuwnwn" "wswq{ownxuwiwtxtwrzpwtwkwjwuwtwuw\\wRwswnwuwSzpwtwowtxqwrwrwtxrxn{q{q{q{q{q{s{pwlwmwmwmwjwmwnwmwowrwswtwuwrwqws" "wqwswqwswqwswqwrwtwqwuwswswrwrwrwrwrwrwrwowozpwswqwswqwswqwswqwswqwswqwswswswowmwmwmwmwjwqwjwmwowswqwswqwswqwsw" "qwswqwswqwswgwuwuwqwswqwswqwswqwswqwtwpwswqwtw[yoyoyoyoyGwmwdwuwuwpxnxnyqwrwqwtwpwtwoxpw rwswSwuwmwuwpwuwtwuxsw" "ewlwcwPwnxuxownwnwswnwlwqwswowowswnwZygygwkwswrwrwqwswrwswpwmwmwrwswrwowlwqwswpwnwqwswsxqwswqwmwswrwswqwrwowpxt" "xowowswqwswowowlwlwmwQwswqwswqwmwswqwswpwnwswqwswowmwowtwnwqwswswswswqwswqwswqwswqwmwswpwnwswpxowswqwtwoxnwlwmw" "mw[xuxrwtxpwswqwtwpwswqwmwswpypwtwpwswrwtwtwsxuwuxrwtwqwtwtwrwswrwswnwnwuwpwswqwmwmwswq{rwrwowowswqwkwlwoypwtwo" "ydwowuwnwn{owmwlwgwrwfwtw^wrw6wswnwuwJwtwowtzswrwrwtzswmwswqwswqwswqwswqwswqwswswswowswqwmwmwmwjwmwnwmwowswrwsx" "qwswqwswqwswqwswqwswrwrwqwswrxtxrxtxrxtxrxtxowowmwswqwswqwswqwswqwswqwswqwswswtxowmwswqwswqwswqwswnwqwjwmwowswq" "wswqwswqwswqwswqwswqwswowoxtwqwswqwswqwswqwswpxowswpx Wwlwbwnxcwpwrwqzpwtwoxo|!ydwfwtwozpwsxszuxgxnxcwmwcwoxmyp" "{q{pymwpzoyowmypymwmwjwiwkwowrwrwqws{oyqzo{qwlzrwrwowlwqwrwq{rwqwswsxpypwlyqwrwqznwoznwowswrxsxpwp}qwkwnwPzqzoy" "ozpyowmzqwswowmwowswowqwswswswswpypzozqwlynxozpxowswrwrwpwn{owmwmwQxuxqzoxnyoypwswowpwrwqzpxuxq{qwtxq{qzpylwoyq" "}r{qwnyuypwpwrwownydwcwcwcwnzq{rwqwpwmwkwgzHz]}U|owuw@wqwswrytwqwqyqwqwswqwswqwswqwswqwswqwuwr{ryp{q{q{q{nwmwnw" "mwozqwsxpyoyoyoyoygwuypzpzpzpznwowmwuypzpzpzpzpzpzryuzryoyoyoyoymwqwjwmwnypwswpyoyoyoyoyfzozpzpzpzpwnzow \\w" "OwnwXw[w SwGz kx0x lxdx gw[w=wiw*wbyowoyGwKwowewawcwow YwOwoz Ewjwuwdw 7w 9w Iwnwlw \\w 0|*y[x=wiw," "xWw=wKwowewawcwow Yw hwVx 8w 9w Jxmwnxp" }; // Define a 26x32 font (normal sans). static const char *const data_font_normal[] = { " #{}~}a{|y~f{|y~}f{|}|x{}|j{|y}y{|y}g{}y~}|2y~|a{}~}f{}y~|" "gy}|yy}|i{}~}a{}~}f{}y~}gy}|yx}N{|}|x{}|hy~|ay~|fx~|g{}y~|y{}~j{|y~|yy~}5{}~}a{}~}f{}y~}gy~}yy~}e{|y~ " " 2{}~}c{|y~f{|y~}~}h{}w~y}~|j{}y~y{}y~h{}~y}y~|2y~|c{}~}f{" "}~y}~|hy~}yy~}hy~|c{|~}f{|~y}~|hy~}y{}y~O{}w~y}~|gy~|cy~|fy~|}~|i{|~y}y~}~}j{|y~|yy~}4{}~|c{}~}f{}~|}~}hy~}yy~}" "ey~| g{|}y~} J{}~|dy~|fy~y{}~|i{~}{|}y~}i{}y~y{}y" "~i{|~}x{~}2{|y~d{|~}f{|~}yy~hy~}yy~}gy~cy~f{|~}y{}~|iy~}y{}y~P{|~}{|}y~|ey~d{}~|fy~x{}~|j{}~y{|}~}i{|y}|yy}|3{}" "~|e{}~}f{}~|y{|~|iy}|yx}f{}~| fy~y}~} k{|y~| /{|y~| y{}" "~} Xy|e{|}|f{|}wy|5{|~|x{}~1{|}|ey|ey|wy|M{|}|e{|}|fy|wy| g{|}|3{|y~|_{}~}g{|y~2{}~|y{}~|5{|y~^y~}g{}y~N{|" "}|^{|}|g{|}| s{}~}_{|y~|gy~} Z{}~}_{|y~|gy~} )y}| -{|y~ Jy}|yy}| " "X{}y~ 4{|~}y{|~} P{| n{|y~`{|y~fx~}3{}~x{|~|4{}~}`{}~}g{|x~}N{}~}`{|y~|gx~| sy~|`y~|g{}x~| Z{}~}`y~}g{}" "x~|I{}y~ 1{|x~|oi| r{|~|O{|d{|y}|j{|y}|u{|y}|h{| \"{|}x~}|Ny~}g{|y~y{|~}g{|~}x{|~}i{|~l{|}y~}|s{|~}l{|}x~}|e" "{|y~by~g{}~}b{~} S{|y~i{|}x~}|i{|y}x~|i{|y}x~y}i{|y}w~}|d{}x~kq~|i{|}w~}|m{}o~k{|}x~y}h{|}x~}| B{|}w~}L{|x~j{|s" "~y}g{|}w~}|o{|s~y}|k{|o~n{|p~j{|}w~y}|o{|y~|ry~}k{|y~|e{|y~|j{|y~|t{|x~n{|y~|i{|x~}r{|x~}s{|x~|sy~}l{|}x~y}|l{|" "s~}|i{|}x~y}|m{|s~}|hy}w~y}|ok~}r{}y~r{|y~|r{}y~|p{}y~vy~}t{|x~sy~}ux~rx~q{}y~|r{}y~|r{|l~l{}v~hy~|c{|v~|f{|}|L" "{}~}M{}y~@{}~}O{|}w~R{}y~`{|y~d{|y~h{}y~`{|y~ ay}y~}h{}~}h{}y~y} Wy}x~}|O{|y}w~}| xx~} I{|}x~}f{|x~i{|o~m{|" "o~m{|y}x~}|f{}y~k{|m~}r{|y~|w{}y~vy~}n{|}x~y}|My}Iy}|J{}~| q{|}x~y}T{}y~r{}~}R{}w~}|j{|y~}yy~}O{|}w~} \\{|t~}h{" "|}y~}M{|}x~}|h{|}x~}|e{|y~L{|}t~|7y}y~}f{|}x~}Uy|y}|py}p{|n{|t{|}w~}r{|y~P{|x~e{|x~e{|x~e{|x~e{|x~f{}v~|jk~|o{|" "}w~}|m{|o~n{|o~n{|o~n{|o~j{|y~|e{|y~|e{|y~|e{|y~|k{|s~y}|m{|x~|sy~}l{|}x~y}|i{|}x~y}|i{|}x~y}|i{|}x~y}|i{|}x~y}" "|O{|}x~y}|y{|~}s{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|q{}y~|r{}y~|p{|y~|b{|}x~}|h{}~}b{|y~|g{}~|}~|h{|y~}|" "{}~iy~}yy~}i{}~|y{}~|3{}~}b{|~}fy~{}~|i{|y~|{|y~}iy~|ay~}g{}~}y~gy~}yy~}i{|y~}wy|j{|y~}y{}~hy~|b{}~}g{|~}|~}h{|" "}y~}{|~}j{}y~y{}y~|4y~|b{}~}g{|~}{y~h{}y~y{|y~|f{|y~|k{}y~by~}y{}y~ ev~o{}k~} r{}~O{|~e{}v~l{}v~w{}w~}j{}~ Y{}" "o~ S{|s~}Oy~}g{|y~y{|~}g{}~|x{}~|i{|~m{|y~y}y~|ty~l{}t~}f{|y~c{}~}fy~b{~} S{}~}j{}t~}kt~|j{}r~|l{|r~}f{|w~kq~|" "j{}s~|n{}p~}m{|r~|l{|s~| D{}s~|i{|y}y~y}|hw~|k{|p~|k{|q~}q{|p~}|m{|o~n{|p~l{|p~}q{|y~|ry~}k{|y~|e{|y~|j{|y~|u{|" "x~m{|y~|i{|w~|sw~}s{|w~sy~}n{}r~}m{|q~}l{}r~}n{|q~}k{|q~|pk~}r{}y~r{|y~|r{|y~}py~}v{}y~t{}x~|u{|y~|u{|y~}t{}y~|" "py~}s{|y~}q{|l~l{}w~}h{}~}c{|v~|gw~}L{}~|N{}y~@{}~}P{|u~R{}y~`{|y~d{|y~h{}y~`{|y~ e{}y~ {}w~}h{}~}h{}v~ Ys~}Q" "{|r~| yv~ K{}t~|hw~|j{|o~m{|o~n{}r~|h{}y~k{|m~}r{|y~|w{}y~vy~}p{}r~}O{}x~Jy~|K{}x~|/{~|f{}t~}Ty~|t{|y~|Ss~j{|y" "~}yy~}i{|}v~}|j{}~w}y~ v{|}v~}|k{|t~}i{|y~}x~N{}~}|}y~|i{|y}y|}~}fy~|N{|u~y}y~|8{|~y}~}g{|y~x}y~W{|w~}q{}~}s{}x" "~}q{|y~t{|}x|}~}s{}~|Pw~|fw~|fw~|fw~|fw~|fw~|j{|k~|q{|q~}o{|o~n{|o~n{|o~n{|o~j{|y~|e{|y~|e{|y~|e{|y~|k{|o~|o{|w" "~sy~}n{}r~}l{}r~}l{}r~}l{}r~}l{}r~}R{}r~}|y~|s{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|py~}s{|y~}o{|y~|cs~}h{" "}~}cy~|g{|~}yy~i{|y~}w~}iy~}yy~}hy~y}~}1y~|d{|y~f{}~|{|~}i{|y~|{|y~}i{|y~b{}~}g{|~}{|~}hy~}yy~}h{|y~y}y~}|k{|y~" "}y~}~}h{|y~c{|~}fy~y{|~|i{}~}v~|j{}y~y{}y~|4{|y~c{|~}fy~y{|~}i{}y~y{|y~|fy~|j{}y~by~}y{}y~ f{|y~{}~|p{|k~| r{~" "}Oy~}g{}u~}n{}t~y{}u~}l{}y~} \\{}m~ T{|x~}|{y|y~|Py~}g{|y~y{|~}gy~|xy~|i{|~my~|y{|y~u{}~}m{}y~}|y{|y}f{|y~d{|y" "~e{}~}hy|x{~}x{| Wy~|k{|y~}|{|}y~}lx~y}y~|jx~}x|}x~|m{|~}v|x~}gv~ky~s|j{}x~w|}~|nr|}y~|mx~}|{y|x~|mx~y|{|}y~| E" "y~}x|}x~k{}q~|k{|w~}k{|y~u|}x~l{}x~}v|}y~|r{|y~u|y}x~}n{|y~q|n{|y~r|m{}x~}v|}x~|r{|y~|ry~}k{|y~|e{|y~|j{|y~|v{|" "x~l{|y~|i{|w~}t{|w~}s{|w~}ty~}o{}x~}|{y|}x~n{|y~v|}x~|n{}x~}|{y|}x~o{|y~v|}x~}m{|x~}v|}~|pt|y~}u|q{}y~r{|y~|qx~" "q{|y~|v{|y~|u{}x~|u{}y~|t{}y~|v{|y~}o{|y~|tx~op|}y~}l{}~}e{|y~`{|y~|h{}v~}L{}~|O{}y~@{}~}Py~}|O{}y~`{|y~d{|y~h{" "}y~`{|y~ e{}y~ !{|y~}e{}~}e{|y~| [{}y~|x{}y~|jy}~y}|ix~|w{|}| w{}y~| M{}y~|y{|}y~i{|w~}ix~r|m{|y~q|p{|w~}x|}x" "~}l{|y}x~y}|n{|y~q|y~}r{|y~|w{}y~vy~}q{}x~}|{y|}x~Q{}v~Ky~|L{}v~|0{~|g{|y~}|y{|y}T{}y~t{}~}i{}~}h{}y~|x{|}P{}~y" "}x|y}~}k{|v{}~| x{}~y}x|y}~}Qy~x{|~}J{|y~cy~g{}~|Mt~y{}~|5{|~}gy~|x{}~}U{|~}r{|y~r{}y|~}qy~|ny~t{|~}P{|w~}g{|w~" "}g{|w~}g{|w~}g{|w~}fw~}j{}y~y|y~}r|q{}x~}v|}y~|p{|y~q|n{|y~q|n{|y~q|n{|y~q|j{|y~|e{|y~|e{|y~|e{|y~|k{|y~}u|}x~}" "p{|w~}ty~}o{}x~}|{y|}x~n{}x~}|{y|}x~n{}x~}|{y|}x~n{}x~}|{y|}x~n{}x~}|{y|}x~T{}x~}|{y|v~|r{}y~r{|y~|q{}y~r{|y~|q" "{}y~r{|y~|q{}y~r{|y~|p{|y~|tx~n{|y~|d{}y~|x{}y~|h{}~|e{}~|f{~}x{|~}j{|}xx}hy}|yy}|h{|}y~}/y~dy~|g{|~}x{|~|j{|y}" "|yy}|h{|~}d{|~}f{}~x{}~|iy}|yy}|iy|w~|h{}~y{|}~}f{|~}e{|~}f{}~|x{}~|j{}|y{|y}|i{|y}y{|y}2{|~}dy~f{}~|x{}~|j{|y}" "y{|y}|g{}~|i{}y~by}|y{|y}5{|}w~}|i{|}w~}|i{|}w~}|i{|}w~}|i{|}w~}|f{}~}{y|ny~}q{}y~ r{|~O{}x~|hs~|p{|s~y|s~|n{|w" "~} ^{}y~}| Ix~|u{}|Py~}g{|y~y{|~}gy~wy~k{|}v~y}|s{|y~w{}~|w{|y~ly~}_{|y~d{}~}dy~|iy~}y{~}{|y~|hy}| o{|y~jx~v{}" "y~l{|x{|y~|j{}|u{|x~d{}y~|i{}~|}y~ky~|d{|y~}]{}y~m{|y~|v{|y~}n{}y~|v{}y~ E{}u{}y~|n{|x~}|w{|}y~}|m{}y~}y~k{|y~|" "u{|y~}n{}y~}s{|~|r{|y~|t{|x~|o{|y~|e{|y~|f{}y~}r{}~|r{|y~|ry~}k{|y~|e{|y~|j{|y~|w{}y~}k{|y~|i{|y~}y~t{}~}y~}s{|" "v~ty~}p{}y~}t{}y~}o{|y~|v{|x~o{}y~}t{}y~}p{|y~|v{|x~mx~r{|iy~}k{}y~r{|y~|q{|y~|r{}y~u{|y~|uy~}~}u{}y~rx~vx~m{}y" "~u{}y~|e{|y~}k{}~}dy~|a{|y~|i{}y~|{}y~| y{}y~@{}~}Py~|N{}y~0{}y~`{|y~ e{}y~ !{|y~d{}~}dy~} [y~}v{}~}ju~}jy~| n" "{}y~ N{|y~|v{}~}j{}y~}y~i{|y~}e{|y~|gx~}t{}y~}o{|}q~|p{|y~|ry~}r{|y~|w{}y~vy~}r{}y~}t{}y~}S{}t~Ly~|M{}t~|1{~|g" "{}y~Ly~|v{|y~|i{}~}hy~}L{|y~|t{|y~|g{|~} {{|y~|t{|y~|T{|~|wy~f{}~|ay~ey|y~7{}t~y{}~|5{|~}h{|~}vy~U{|~}r{}~|p{|~" "}r{|~}my~ty~O{}y~}y~g{}y~}y~g{}y~}y~g{}y~}y~g{}y~}y~g{|y~}y~jy~}yy~}i{}y~}s{|~|p{|y~|e{|y~|e{|y~|e{|y~|a{|y~|e{" "|y~|e{|y~|e{|y~|k{|y~|t{|x~}q{|v~ty~}p{}y~}t{}y~}p{}y~}t{}y~}p{}y~}t{}y~}p{}y~}t{}y~}p{}y~}t{}y~}V{}y~}t{}x~q{}" "y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|o{}y~u{}y~|n{|y~|e{|y~|v{}~} A{|}|ey|e{}|wy|Py~}y|y~} ?{}~}h{}y~ p" "{}r~|l{}r~|l{}r~|l{}r~|l{}r~|h{}~}k{}y~qy~}1{|~}dy}P{}v~|is~|p{|r~}s~}nu~|h{|w}|k{|y}sy}|jx}|j{|y}t{|y}o{}y~| " "H{|y~|Gy~}g{|y~y{|~}h{|~}x{|~}l{}r~}s{|~}w{}~}w{}~|ly~}_{|y~dy~|d{}~}h{|y~|~y}~}|g{}~| o{}~}k{|y~|uy~}i{|y~|a{}" "y~|e{|y~}j{|~}{}y~ky~|dy~}]{|y~}m{}y~tx~ny~}u{|y~|,{|X{|X{|y~|o{}y~|q{}y~my~}|y~|l{|y~|ty~}o{|x~p{|r{|y~|s{|x~o" "{|y~|e{|y~|g{|x~p{|q{|y~|ry~}k{|y~|e{|y~|j{|y~|x{}y~}j{|y~|i{|y~|y~|uy~|y~}s{|y~|y~}uy~}q{|x~r{}y~|p{|y~|u{}y~|" "q{|x~r{}y~|q{|y~|u{}y~|ny~}_y~}k{}y~r{|y~|py~}s{|y~}ty~}v{|y~|y~uy~}r{|y~}x{}y~|ly~}w{|y~}e{|x~j{}~}d{}~}a{|y~|" "j{}y~|x{}y~| {{}y~@{}~}Py~|N{}y~0{}y~`{|y~ e{}y~ !{}y~d{}~}d{}~} \\{|y~u{}y~j{}x|}y~|kx~| o{|y~| O{}~}u{|y~jy" "~}|y~|i{|y~}f{|y~|h{}y~|rx~|q{|w~y}y~y}x~}q{|y~|ry~}r{|y~|w{}y~vy~}s{|x~r{}y~|U{}y~|y~}x~My~|N{}y~|y~|x~|2{~|gy" "~}g{|p{}m{}y~v{}~}h{}~}h{}~}L{~}xy|}y|x{}~l{|}u~ {{~}p{}~T{|~|wy~f{}~|b{}~}g{}w~|7{}t~y{}~|5{|~}h{}~|v{}~|V{|~}" "s{|~}o{|~}ry~n{|}~|u{}~}Oy~}|y~|hy~}|y~|hy~}|y~|hy~}|y~|hy~}|y~|hy~}|y~|l{}y~|yy~}j{|x~p{|p{|y~|e{|y~|e{|y~|e{|" "y~|a{|y~|e{|y~|e{|y~|e{|y~|k{|y~|rx~q{|y~|y~}uy~}q{|x~r{}y~|r{|x~r{}y~|r{|x~r{}y~|r{|x~r{}y~|r{|x~r{}y~|q{|}q{|" "}p{|x~s{}x~|r{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|ny~}w{|y~}m{|s~}|l{|y~u{|y~ 8{|w{|y~} _{} G{}y~ r{|" "x~|w{|}y~|o{|x~|w{|}y~|o{|x~|w{|}y~|o{|x~|w{|}y~|o{|x~|w{|}y~|i{}~|jy~|s{|y~|1y~}d{~|Q{|t~is~|p{}i~}os~j{|s~|m{" "|y~sy~|jw~j{|y~|u{}y~p{|y~| Gx~Fy~}g{|y~y{|~}h{}~}x{}~}m{|y~}{|~x{|}s{|~}w{}~}x{|~}ky~}_{|y~e{|y~c{|y~f{}x~}|e" "{}~| oy~|k{}y~t{}y~i{|y~|a{|y~|dy~|jy~|{}y~ky~|e{|y~|]{}y~|m{}y~ty~}o{|y~|ty~}/{|}~}Xy~}|[{|y~|p{}y~|o{}y~o{|y~" "|{y~}l{|y~|ty~}o{}y~|f{|y~|r{}y~|p{|y~|e{|y~|g{}y~|e{|y~|ry~}k{|y~|e{|y~|j{|y~|y{}y~}i{|y~|i{|y~|}~}v{|y~{y~}s{" "|y~|}y~uy~}q{}y~|qx~p{|y~|u{}y~|q{}y~|qx~q{|y~|u{}y~|o{|y~|_y~}k{}y~r{|y~|p{}y~s{}y~|t{}y~v{|~}{y~|w{|y~|q{}y~|" "{|y~}k{|y~|xx~dx~|j{}~}d{|y~a{|y~|k{}y~|v{}y~|9{|y}x~y}j{}y~y{}x~}|h{|}x~y}|j{}x~}|{}~}k{|}x~}|j{|s~|i{}x~}|{}~" "}n{}y~y{}x~}|h{|y~d{|y~h{}y~u{|y~}j{|y~m{}y~y{}x~}w{|}y~}|p{}y~y{}x~}|i{|}x~}|k{}y~y{}x~}|i{}x~}|{}~}k{}y~y{}x~" "k{|}w~y}|k{|r~l{}~}t{}~}oy~}s{}y~r{}~}v{}y~}v{}~}r{|y~|u{|y~|oy~}s{}y~n{}p~h{}y~d{}~}d{}~} t{}x~}|y{|~}n{|y~u{}" "~}e{}y~k{|w~y}|g{|}w~y}l{}y~y{}x~}|n{}~}|s{}y~iy~}i{}~}t{}~}p{|y~|r{}y~n{|y}y{}y~}lm~p{}y~x{|y~x{|y~|k{}w~}|j{|" "}q~|q{}n~ny~|ty~|l{|y~|{y~}h{|y~}g{|y~|hy~}q{|y~}qx~}y{}y~y{|x~|r{|y~|ry~}r{|y~|w{}y~vy~}s{}y~|qx~V{|y~|{y~y|y~" "}Ny~|O{|y~|{y~|{y~}Ny~}e{|}w~}|jy~}h{|y~r{}~}my~|x{|y~|h{}~}h{|y~}Ny}x{}u~|yy}n{}y~w}y~ y}y{}v~}|xy}T{~}x{|~}f{" "}~|c{|~}fx|y}|Q{}~}t{}~}ns~y{}~|5{|~}h{}~|v{}~|V{|~}sy~n{|~}s{}~|p{}x~}u{|y~f{|y~|h{|y~|{y~}i{|y~|{y~}i{|y~|{y~" "}i{|y~|{y~}i{|y~|{y~}i{|y~|{y~}ly~}xy~}j{}y~|d{|y~|e{|y~|e{|y~|e{|y~|a{|y~|e{|y~|e{|y~|e{|y~|k{|y~|r{|y~}r{|y~|" "}y~uy~}q{}y~|qx~r{}y~|qx~r{}y~|qx~r{}y~|qx~r{}y~|qx~qy~}s{|y~}q{}y~|t{}~}x~r{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|q{}" "y~r{|y~|n{|y~|xx~l{|q~}m{}y~w{|w~l{|y}x~y}i{|y}x~y}i{|y}x~y}i{|y}x~y}i{|y}x~y}i{|y}x~y}n{|y}x~y}w{|}x~}|l{|}x~y" "}|j{|}x~}|h{|}x~}|h{|}x~}|h{|}x~}|g{|y~d{|y~d{|y~d{|y~e{|}v~|l{}y~y{}x~}|i{|}x~}|h{|}x~}|h{|}x~}|h{|}x~}|h{|}x~" "}|g{|x~f{|}x~}|{}~|o{}~}t{}~}n{}~}t{}~}n{}~}t{}~}n{}~}t{}~}oy~}s{}y~n{}y~y{}x~}|my~}s{}y~;y~}xy~|y{|y~|py~}s{|y" "~|py~}s{|y~|py~}s{|y~|py~}s{|y~|j{}~|j{}y~sy~}1y~}d{|~Q{|s~}j{}t~o{|i~}p{}s~}kx~}y|}x~m{|y~sy~|k{|w~|jy~}uy~}py" "~} Fy~}Fy~}g{|y~y{|~}m{|k~}q{}y~y{|~n{|~}w{}~|xy~j{}y~|`{|y~e{}~}by~|g{|x~}d{}~| p{|y~jy~}t{}y~i{|y~|a{|y~|e{|" "y~|k{}~}y{}y~ky~|{|g{}y~\\x~l{|y~|v{|y~|o{|y~|tx~i{}y~d{}y~a{|}w~}Xv~}|^x~p{|y~l{}~}p{}y~y{|y~|m{|y~|ty~}ox~e{|" "y~|qy~}p{|y~|e{|y~|gx~d{|y~|ry~}k{|y~|e{|y~|j{|y~|{}y~}h{|y~|i{|y~y|y~v{}~}{y~}s{|y~|{y~}vy~}qx~p{}y~|q{|y~|u{|" "y~|qx~p{}y~|r{|y~|u{}y~|ny~}_y~}k{}y~r{|y~|p{|y~|ty~}s{}y~|w{}~|{}~|w{|y~|py~}{x~i{}y~y{}y~|e{}y~|i{}~}cy~|b{|y" "~|l{}y~|t{}y~|;{|r~|l{}y~|t~|j{}s~|m{|t~|}~}l{}s~|l{|s~|k{|t~|}~}n{}y~|t~|i{|y~d{|y~h{}y~v{}y~}i{|y~m{}y~|t~y{}" "u~}q{}y~|t~|l{|s~}l{}y~|t~|l{|t~|}~}k{}y~|v~l{|r~k{|s~}l{}~}t{}~}o{}y~sy~}r{|y~v{}x~vy~}q{}y~|w{|y~}n{}y~sy~}n{" "|p~h{}y~d{}~}d{}~} v{|t~|{}~|n{|y~u{}~}e{|y~|k{|t~|j{}s~|m{}y~|t~|o{}x~|ty~}ix~i{}~}t{}~}py~}q{|y~|p{|y~}{}v~|n" "m~p{}y~x{|y~x{|y~|ls~|l{|o~|q{}n~o{|y~|t{}~}l{}y~y{}y~|h{}y~}h{|y~|i{|y~|p{}y~r{}y~|x{}y~x{|x~r{|y~|ry~}r{|y~|w" "{}y~vy~}sx~p{}y~|p{}b{}|yy~|{|}b{}|hy~|i{|}s{}|ly|yy~|y{}My~}g{|r~k{|y~|gx~|}x~}|}y~|m{}y~xy~}g{}~}g{}x~|Q{|~|y" "y~}|yx|y{|~|p{|~}w{|y~gy|w{|<{|~|y{}~}x|y~|y{|~|U{}y~y}y~e{}~|d{|y~a{}~Q{}~}t{}~}n{}t~y{}~|5{|~}h{}~|v{}~|m{|v{" "|k{|~}t{}~|n{|~}t{|~}ox|}y~v{}~|f{|y~|h{}y~y{|y~|j{}y~y{|y~|j{}y~y{|y~|j{}y~y{|y~|j{}y~y{|y~|j{}y~y{}y~m{|y~|xy" "~}jx~c{|y~|e{|y~|e{|y~|e{|y~|a{|y~|e{|y~|e{|y~|e{|y~|k{|y~|qx~r{|y~|{y~}vy~}qx~p{}y~|sx~p{}y~|sx~p{}y~|sx~p{}y~" "|sx~p{}y~|r{|y~}u{|x~px~t{}~}{}y~|s{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|m{}y~y{}y~|l{|y~v|}x~}n{}y~x{}y~|" "k{|r~|l{|r~|l{|r~|l{|r~|l{|r~|l{|r~|q{|r~|{}s~n{}s~|l{}s~|k{}s~|k{}s~|k{}s~|i{|y~d{|y~d{|y~d{|y~g{|r~l{}y~|t~|l" "{|s~}k{|s~}k{|s~}k{|s~}k{|s~}h{|x~h{|q~|n{}~}t{}~}n{}~}t{}~}n{}~}t{}~}n{}~}t{}~}o{}y~sy~}n{}y~|t~|n{}y~sy~}<{}~" "}wy~|x{|y~q{}~}q{|y~q{}~}{~}w{|~y|y~q{}~}t{|~y|y~q{}~}q{|y~j{}~|j{|y~|u{|y~|<q|}y~w|p{|y}uy}Qq~}k{|u~}o{|i~|q{|" "q~}m{}y~uy~}n{|y~sy~|k{}w~|j{}y~v{|y~|q{|y~ H{}o~My~}fy|xy|m{|k~}q{}~}y{|~n{|y~wy~|y{}~|ix~_y|ey~|by~}i{|}~}~}" "y~}f{}~| p{|~}jy~}t{|y~|j{|y~|a{}y~f{|}y~}k{|y~x{}y~kt~}|ky~}{|w~}|e{|y~|kx~|x{|y~}n{|y~|tx~i{}y~d{}y~d{|}v~}|q" "k|p{|}w~}|a{}y~|p{}~|w{|}y~}|{y|xy~|qy~}xy~}m{|y~|u{|y~|p{|y~}e{|y~|qx~p{|y~|e{|y~|h{|y~}d{|y~|ry~}k{|y~|e{|y~|" "j{|y~|}y~}g{|y~|i{|y~|{y~|wy~|{y~}s{|y~|{}y~vy~}r{|y~}p{|y~|q{|y~|u{}y~|r{|y~}p{|y~|r{|y~|u{}y~mx~}`y~}k{}y~r{|" "y~|oy~}u{|y~|s{|y~|wy~|{|~}w{}y~o{|v~|hy~}|y~}e{}y~}h{}~}c{}~}b{|y~|m{}y~|r{|y~|<{|}y|x{|}y~l{}w~|y{|x~|lx~}|yy" "|}|mx~|y{|}x~}mx~y|y{|x~iy~|h{|x~|y{|}x~}n{}w~|y{|x~i{|y~d{|y~h{}y~w{}y~|h{|y~m{}w~|y{|y~}|~}|{|}y~|r{}w~|y{|x~" "lx~|y{|}y~}m{}w~|y{|x~|mx~|y{|}x~}k{}w~w|ly~}|xy|}i{}y~g{}~}t{}~}o{|y~|u{|y~|r{|y~|ww~vy~|px~wx~m{|y~|u{|y~|f{|" "y~}h{}y~d{}~}d{}~}6{|}x~|x{}x~|o{|y~}|{|}y~{y~m{|y~v{|y~|dy~|l{}~}x{|x~|l{}y~}|yy|}|m{}w~|y{|x~n{|}~}u{|y~|j{|x" "~|j{}~}t{}~}q{|y~|py~}q{|x~y|y~y|x~ny|y~}w|}y~}|p{}y~x{|y~x{|y~|mx~|y{|x~|n{|x~|x{}x~y|pu|y~}v|o{|y~s{}y~ly~}xy" "~}g{}y~|i{|y~|i{}y~o{}y~|sx~w{}y~w{}y~|s{|y~|ry~}r{|y~|w{}y~w{|y~}t{|y~}p{|y~|qy~}_y~|`{|y~|iy~|j{|y~}u{|y~|iy~" "|Jy~}h{|x~y|~|{|}k{|y~|fp~|ky~}{|y~f{}~}h{}~y}y~}|Sy}y{}~}qy}p{|~}w{|y~h{|~|x{}~<y}x{}~}x{|~}xy}T{|}y~}d{}~|e{|" "~}`{}~|R{}~}t{}~}n{}t~y{}~|5{|~}h{|~}vy~l{|~|xy}l{|~}u{|~}m{|~}ty~|k{}~|x{|~}e{|y~|hy~}xy~}jy~}xy~}jy~}xy~}jy~}" "xy~}jy~}xy~}jy~}xy~|n{}y~wy~}k{|y~}c{|y~|e{|y~|e{|y~|e{|y~|a{|y~|e{|y~|e{|y~|e{|y~|k{|y~|q{}y~r{|y~|{}y~vy~}r{|" "y~}p{|y~|t{|y~}p{|y~|t{|y~}p{|y~|t{|y~}p{|y~|t{|y~}p{|y~|q{|y~}w{|x~p{|y~}u{|~}y{|y~|s{}y~r{|y~|q{}y~r{|y~|q{}y" "~r{|y~|q{}y~r{|y~|ly~}|y~}k{|y~|ux~n{}y~y{|y~|j{|}y|x{|}y~l{|}y|x{|}y~l{|}y|x{|}y~l{|}y|x{|}y~l{|}y|x{|}y~l{|}y" "|x{|}y~q{|}y|x{|}v~|x{|y~}px~}|yy|}|mx~y|y{|x~lx~y|y{|x~lx~y|y{|x~lx~y|y{|x~i{|y~d{|y~d{|y~d{|y~gx~|x{|y~}m{}w~" "|y{|x~lx~|y{|}y~}lx~|y{|}y~}lx~|y{|}y~}lx~|y{|}y~}lx~|y{|}y~}i{|x~hx~|y{|}y~}m{}~}t{}~}n{}~}t{}~}n{}~}t{}~}n{}~" "}t{}~}o{|y~|u{|y~|n{}w~|y{|x~|o{|y~|u{|y~|={|y~vy~|w{}~|s{|y~o{}~|s{|y~{}y~}y{|y~}{}~|s{|y~t{|y~}{}~|s{|y~o{}~|" "ky~|iy~}u{}y~;k~}qw~u{~|R{}p~|k{}w~}mi~q{|o~|ny~|u{}y~n{|y~sy~|ky~}y~}j{|y~|w{}y~p{}~} Hx}y~t}|My~}M{|y~x{|~}l" "{}y~y{|~m{}~}y{}~}y{|~}i{|w~I{|y~|b{}y~j{}~}|{~}{|y~|h{}~| p{}~|jy~}t{|y~|j{|y~|b{|y~}j{}u~}jy~|x{}y~kr~}ly~y}t" "~}f{}y~i{}t~|ly~}u{|x~|j{}y~d{}y~f{}v~}|nk~}n{|}w~}|e{}y~|p{|~}w{|u~y}~x{|~}r{|y~|x{}y~m{|y~|xy|}y~}o{|y~|e{|y~" "|q{}y~p{|y~r|m{|y~s|o{|y~|d{|y~q|y~}k{|y~|e{|y~|j{|v~}f{|y~|i{|y~|{}~}x{|~}yy~}s{|y~|yy~}wy~}r{|y~|p{|y~}q{|y~|" "ux~q{|y~|p{|y~}r{|y~|v{|y~}m{|v~}y|ey~}k{}y~r{|y~|o{}y~u{}y~qy~}x{|y~y{|y~wy~}n{}x~}g{|v~e{|y~}g{}~}c{|y~b{|y~|" " o{}~}m{}x~ux~m{}y~|f{}y~u{}y~}n{}y~|uy~}jy~|h{}y~u{}y~}n{}x~v{|y~|j{|y~d{|y~h{}y~x{}y~|g{|y~m{}x~v{}x~|vy~}r{}" "x~v{|y~|n{}y~|v{}y~|n{}x~ux~n{}y~u{}y~}k{}x~h{|y~a{}y~g{}~}t{}~}ny~}u{}y~py~|x{|y~}~|x{|y~o{|y~}y{}y~|l{}~}u{}~" "}ex~g{}y~d{}~}d{}~}6y~y}y~|{}y~}y~}p{}y~vy~}y~m{|y~x{|}x~c{}~}m{|y~u{}y~l{}~}e{}x~v{|y~|n{|y~u{}~}i{}x~}j{}~}t{" "}~}q{}y~o{}y~q{}y~|{|y~y{|y~}my~|w{|y~|o{}y~x{|y~x{|y~|n{}y~ux~n{}y~u{}y~|iy~|j{|n~m{|y~|x{}y~f{}y~|j{|y~|i{}y~" "o{|y~|t{|y~}w{}y~w{|y~}s{|y~|ry~}qy~}w{}y~w{|y~|t{|y~|{r~y|y~}rx~|_y~|_{}y~|jy~|k{|x~s{}y~|jy~|Jx|h{}y~|y{~|h{|" "y~|f{|y~}|y{}y~|n{|u~{u~|j{}~}i{|~}y{|}y~}T{~|yy~p{|~p{|~}wx~i{|y~|y{}y~ok|X{~|x{}~}x{|~}x{|~?k~}m{}~}_y~|R{}~}" "t{}~}mt~y{}~|ix|J{|~}gy~|x{}~}l{|y~|y{}~}m{|~}uy~|u{|t{|~}u{}~}j{}~|xy~cy|h{|y~|x{}y~k{|y~|x{}y~k{|y~|x{}y~k{|y" "~|x{}y~k{|y~|x{}y~k{|y~|x{}y~ny~}wy~}r|t{|y~|c{|y~r|m{|y~r|m{|y~r|m{|y~r|i{|y~|e{|y~|e{|y~|e{|y~|k{|y~|q{}y~|s{" "|y~|yy~}wy~}r{|y~|p{|y~}t{|y~|p{|y~}t{|y~|p{|y~}t{|y~|p{|y~}t{|y~|p{|y~}p{|y~}y{|x~o{|y~|v{|y~wy~}s{}y~r{|y~|q{" "}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|l{|v~j{|y~|u{}y~|o{}y~y{|y~`{}~}d{}~}d{}~}d{}~}d{}~}d{}~}i{}x~u{|y~|r{}y~|f{}y~|" "uy~}n{}y~|uy~}n{}y~|uy~}n{}y~|uy~}j{|y~d{|y~d{|y~d{|y~h{}y~|v{|y~|n{}x~v{|y~|n{}y~|v{}y~|n{}y~|v{}y~|n{}y~|v{}y" "~|n{}y~|v{}y~|n{}y~|v{}y~|ix|i{}y~|w{|x~|n{}~}t{}~}n{}~}t{}~}n{}~}t{}~}n{}~}t{}~}n{}~}u{}~}m{}x~ux~n{}~}u{}~}<{" "|~}vy~|w{|~}s{|~}o{|~}s{|~}y{}y~}|y~}y{|~}s{|~}u{|y~}y{|~}s{|~}o{|~}ky~|i{}y~uy~};k~}q{|{y~|w{}~R{|n~o{}o~}|r{|" "k~}qm~|oy~|u{|y~n{|y~sy~|l{|y~|}y~iy~}wy~}p{}~} F{|y~|Fy~}M{}~}x{}~}l{|y~}y|~lu~xy~|xx}|q{|y~|x~ty|S{|y~a{}y~j" "{}|x{~}x{}|h{}~| py~j{|y~|t{|y~|j{|y~|bx~i{}v~}|k{}~}w{}y~k{}y|x{|x~}mw~}|y{|x~|gy~}h{}u~}l{}y~|v{}x~|jx|dx|i{|" "}w~}|kk~}l{|}v~}|i{}y~|o{}~|wy~}x{}x~wy~rx~w{|y~|n{|q~|n{|y~|e{|y~|q{}y~|q{|p~}n{|q~o{|y~|tu|q{|m~}k{|y~|e{|y~|" "j{|v~e{|y~|i{|y~|yy~xy~|yy~}s{|y~|y{}y~|xy~}r{|y~|oy~}q{|y~|w{|x~}q{|y~|oy~}r{|y~v|}y~}k{|}t~}gy~}k{}y~r{|y~|o{" "|y~}vy~}q{}y~x{|~}xy~|y{|y~|n{|x~e{}x~|ex~f{}~}by~|c{|y~| o{|y~m{}y~|u{|y~|ny~}ey~}u{|y~}ny~|t{}y~jy~|hy~}u{|y~" "}n{}y~|u{}~}j{|y~d{|y~h{}y~y{}y~|f{|y~m{}y~|v{|x~u{}y~r{}y~|u{}~}ny~}ty~}n{}y~|u{|y~|oy~}u{|y~}k{}y~|h{|y~a{}y~" "g{}~}t{}~}n{}y~uy~}p{}~}x{}~}|~}x{}~}n{|y~y|y~}k{|y~uy~|f{}y~f{}~}d{}~}d{}y~7{}~x{|y~|~}x{}~py~}v{}x~}m{|y~{|v~" "|i{}y~}|{}~}my~|ty~}m{}~}e{}y~|u{}~}my~|vy~|j{|y~}y~j{}~}t{}~}qx~o{|y~|ry~}y{|y~x{}y~my~|w{|y~|o{}y~x{|y~x{|y~|" "ny~|u{|y~|oy~}ty~}iy~|j{|n~mx~w{|y~|g{|y~}j{|y~|i{}y~o{|y~|t{|y~|w{}y~vy~}s{|y~|ry~}qx~w{}y~w{}y~|t{|y~|{r~|{y~" "}sx~|^y~|^{}y~|ky~|l{|x~q{}y~|ky~|5{|y~|x{~|h{|y~|f{}~}v{|~}mw}v~w}|j{}~}i{}~|w{|y~}U{~y{|y~p{|~ox~y}~}y~j{}y~|" "y{}y~nk~}Y{~w{}~}y{|}~|x{|~?k~}n{}y~v|ix}|}y~}Q{}~}t{}~}m{|u~y{}~|iy~}Ly|}~}y|i{|y~x}y~j{}y~|y{}y~n{|~}v{|~}v{|" "y~}u{|~}v{|y~y{}w~}wx|{|}y~x{}~|uy~}Wx~w{|y~|lx~w{|y~|lx~w{|y~|lx~w{|y~|lx~w{|y~|l{}y~w{|y~|p{}y~|wo~t{|y~|c{|p" "~}n{|p~}n{|p~}n{|p~}j{|y~|e{|y~|e{|y~|e{|y~|mq~u{}y~|s{|y~|y{}y~|xy~}r{|y~|oy~}t{|y~|oy~}t{|y~|oy~}t{|y~|oy~}t{" "|y~|oy~}o{|y~}|x~n{|y~|vy~|wy~}s{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|k{}x~|j{|y~|u{|y~|o{}y~y{|y~|a{|y~d{" "|y~d{|y~d{|y~d{|y~d{|y~i{|y~|t{}~}ry~}ey~|t{}y~ny~|t{}y~ny~|t{}y~ny~|t{}y~j{|y~d{|y~d{|y~d{|y~hy~}ty~}n{}y~|u{}" "~}ny~}ty~}ny~}ty~}ny~}ty~}ny~}ty~}ny~}ty~}Ty~}w{|~}y~}n{}~}t{}~}n{}~}t{}~}n{}~}t{}~}n{}~}t{}~}n{|y~uy~|m{}y~|u{" "|y~|o{|y~uy~|<{}~u|y~}w|{y~s{}~n|{y~s{}~|x{}w~}wy~s{}~|v{|y~}wy~s{}~|vy~}vy~ky~|i{|y~|w{|y~|4{|y~}i{}~}w{~}Rm~}" "qk~|r{}l~q{|m~|p{|y~sy~|o{|y~sy~|l{}y~{|y~|j{}y~x{|y~|p{}i~ V{|y~|F{}~}M{}~|x{}~|k{}v~}|m{|y}|x{}~}y{|v~}s{|y~" "|{|x~v{|y~S{}y~a{|y~e{~}jt|y~}u| w{|~}j{|y~|t{|y~|j{|y~|cx~|hw|}y~|m{|y~v{}y~cx~|nx~}ux~h{|y~|j{|y~}|{y|x~m{|x~" "|y{|}w~|={}w~}|E{|}v~|l{|y~|ny~w{}~}v{}y~wy~s{|y~|vy~}n{|q~}|o{|y~|e{|y~|q{}y~p{|p~}n{|q~o{|y~|u{|u~}r{|m~}k{|y" "~|e{|y~|j{|y~}x~f{|y~|i{|y~|y{}~|{|y~xy~}s{|y~|xy~}xy~}r{|y~|oy~}q{|q~}p{|y~|oy~}r{|r~}h{|y}u~|iy~}k{}y~r{|y~|n" "x~w{|y~|q{}y~x{}~|x{}~|y{|y~|nw~|ey~}e{}y~|f{}~}b{}~}c{|y~| v{|y}t~m{}y~sy~|o{|y~|f{|y~|ty~}o{|y~|t{|y~jy~|i{|y" "~|ty~}n{}y~t{}~}j{|y~d{|y~h{}y~{x~|e{|y~m{}y~ty~}u{|y~r{}y~t{}~}o{|y~|t{}y~n{}y~sy~|p{|y~|ty~}k{}y~g{|y~}b{}y~g" "{}~}t{}~}n{|y~|w{|y~o{|y~x{}~y|y~xy~}m{}w~}iy~|w{}y~f{}y~|g{|y~|d{}~}d{|y~}jy}y~}|t{|}X{~}w{|y~}v{~|r{|y~|v{|x~" "|m{|y~{|v~}|ku~|y~}n{|y~|t{}y~m{|y~}f{}y~t{}~}m{}y~w{}y~i{}y~{y~}k{}~}t{}~}qy~}ny~}s{|y~|y{|y~x{|y~my~|w{|y~|o{" "}y~x{|y~x{|y~|o{|y~sy~|p{|y~|t{}y~iy~|j{|y~s|}y~n{|y~}vy~}gx~|j{|y~|i{}y~o{|y~|t{|y~|w{}y~vy~}s{|y~|ry~}q{}y~|x" "{}y~x{|y~}s{|y~|{r|yy~}tx~}l|ly~|mk|x~|ly~|m{|x~o|x~|ly~|5{}y~w{~|j{}r~}ky~|uy~i{|x~}e{}~}i{}~}v{|y~V{|~y{|y~o{" "~|o{}x~|{y}k{}y~|y{}~}mk~}Z{|~w{}u~|v{~|@t|y~}t|n{}t~i{|}x~y}P{}~}t{}~}k{|}x~y{}~|iy~}Lt~|i{|}x~}h{|y~|y{}y~|rt" "~|yy~ux~}wt~|y{}~|{|~}y|}y~x{}v~}|y{|y~u{}y~}m{|y}i{|y~|vy~}m{|y~|vy~}m{|y~|vy~}m{|y~|vy~}m{|y~|vy~}ly~|vy~}py~" "}vo~t{|y~|c{|p~}n{|p~}n{|p~}n{|p~}j{|y~|e{|y~|e{|y~|e{|y~|m{}s~}u{}y~|s{|y~|xy~}xy~}r{|y~|oy~}t{|y~|oy~}t{|y~|o" "y~}t{|y~|oy~}t{|y~|oy~}n{|v~m{|y~|wy~|vy~}s{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|jy~}i{|y~|u{}y~|o{}y~xx~|" "i{|y}t~k{|y}t~k{|y}t~k{|y}t~k{|y}t~k{|y}t~p{|y}t~s{|y~s{|y~|f{|y~|t{|y~o{|y~|t{|y~o{|y~|t{|y~o{|y~|t{|y~j{|y~d{" "|y~d{|y~d{|y~i{|y~|t{}~}n{}y~t{}~}o{|y~|t{}y~o{|y~|t{}y~o{|y~|t{}y~o{|y~|t{}y~o{|y~|t{}y~pk~}q{|y~|w{~}{}y~n{}~" "}t{}~}n{}~}t{}~}n{}~}t{}~}n{}~}t{}~}my~|w{}y~l{}y~sy~|ny~|w{}y~;{}~|}p~{y~s{}~|}p~{y~s{}~|w{}x~vy~s{}~|w{|y~}vy" "~s{}~|vy~}vy~ky~|h{}~}w{}y~3y~}h{|y~x{|~|S{|l~r{}k~}qm~|p{}o~}o{|y~sy~|o{|y~sy~|ly~}yy~}j{|y~|y{|y~o{}i~ X{|y}" "y~u}K{}~}My~|xy~i{|}u~}i{|y~y{|y~|{|y~|t{}~}x{|x~w{|y~S{}y~a{|y~|f{~}jk~} x{}~}iy~}t{|y~|j{|y~|d{}y~|b{}y~|ny~|" "v{}y~c{|y~}nx~|u{}y~|ix~j{|y~|v{|y~}m{|t~y}y~|=x~}?{|x~}l{}y~m{~}wy~|v{|y~w{}~s{}y~u{}y~n{|y~|v{|}y~|p{|y~|e{|y" "~|q{}y~p{|y~|e{|y~|h{|y~|u{|u~}r{|y~|ry~}k{|y~|e{|y~|j{|y~|}x~g{|y~|i{|y~|y{|y~{}~}xy~}s{|y~|x{|y~|yy~}r{|y~|p{" "|y~}q{|s~}|o{|y~|p{|y~}r{|q~|ey|w~iy~}k{}y~r{|y~|n{|y~|x{}y~p{|y~|yy~|x{}~}y{}y~n{}v~ey~}f{}y~|e{}~}b{|~}c{|y~|" " w{}q~m{}y~sy~}o{|y~e{|y~s{}~}o{|n~jy~|i{|y~s{}~}n{}y~t{}~}j{|y~d{|y~h{}v~c{|y~m{}y~ty~|u{|y~r{}y~t{}~}o{|y~s{}" "y~n{}y~sy~}p{|y~s{}~}k{}y~f{}w~}|f{}y~g{}~}t{}~}m{}~}w{}~}o{|y~|yy~yy~xy~|lw~h{}y~wy~}g{}y~|i{}w~}c{}~}c{|w~}o{" "|s~}w|}~}X{~|vy~|vy}r{|y~tx~l{|y~w{|}x~|m{}y~x{}x~|n{|y~s{}y~l{|}v~j{}y~t{}~}m{|y~|xy~}j{|y~|{}y~k{}~}t{}~}qy~}" "vy~|vy~}s{|y~x{|y~x{|y~|ny~|w{|y~|o{}y~x{|y~x{|y~|o{|y~sy~}p{|y~s{}y~iy~|j{|y~s{}y~n{}y~u{}y~h{}y~|i{|y~|i{}y~|" "p{}y~s{|y~}w{}y~w{|y~}s{|y~|ry~}px~x{}y~x{}y~|s{|y~|p{|y~}u{}h~ly~|m{}h~ly~|mg~ly~|J{}~}i{}y~w{~|j{}r~}ky~ty~|i" "x~d{}~}i{}y~|vy~|W{|~y{|y~o{~|X{}y~xy~}^{|~}Z{|~w{}~}|}~}u{~|9{}~| v{}~}t{}~}hy~y{}~|iy~} s{|y~}y{}y~|st|y{}~|v" "{}~|~}wt|y{|~}sy~|wx|v{}~|vy}|~}m{|y~i{}y~u{}y~m{}y~u{}y~m{}y~u{}y~m{}y~u{}y~m{}y~u{}y~m{}y~u{}y~q{|y~|vy~}k{|y" "~|c{|y~|e{|y~|e{|y~|e{|y~|a{|y~|e{|y~|e{|y~|e{|y~|k{|y~|q{}y~|s{|y~|x{|y~|yy~}r{|y~|p{|y~}t{|y~|p{|y~}t{|y~|p{|" "y~}t{|y~|p{|y~}t{|y~|p{|y~}m{}x~|m{|y~|x{}~|v{|y~}s{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|jy~}i{|y~|ux~n{}y" "~x{|x~}k{}q~l{}q~l{}q~l{}q~l{}q~l{}q~q{}f~s{|y~e{|n~o{|n~o{|n~o{|n~j{|y~d{|y~d{|y~d{|y~i{|y~s{}y~n{}y~t{}~}o{|y" "~s{}y~o{|y~s{}y~o{|y~s{}y~o{|y~s{}y~o{|y~s{}y~pk~}q{|y~wy~y{}y~n{}~}t{}~}n{}~}t{}~}n{}~}t{}~}n{}~}t{}~}m{}y~wy~" "}l{}y~sy~}n{}y~wy~};{}~|}q~}{y~s{}~|}q~}{y~s{}~|x{|w~}wy~s{}~|x{|y~}uy~s{}~|vy~}vy~ky~g{|y~|xy~|4{}y~fy~|yy}R{|" "l~ri~po~|n{}p~n{|y~sy~|o{|y~sy~|m{|y~|y{}y~iy~}y{}~}o{}~} H{}r~}K{}~}N{|y~x{|y~f{|~}w~j{}~|y{}~}x{|y~ty~|w{|x~" "x{}~}S{}y~a{|y~|f{|ik~}T{}u~|Ly~|iy~}t{|y~|j{|y~|e{}y~|`y~}o{}~}u{}y~by~}nx~t{|y~|j{|y~}jy~}t{}y~k{}x~}|{}y~<v~" "}|hk|g{|}w~}l{}~}n{|~}wy~ty~wy~sy~}t|y~|o{|y~|t{}y~p{|y~}e{|y~|qx~p{|y~|e{|y~|h{|y~}py~}r{|y~|ry~}k{|y~|e{|y~|j" "{|y~|{}y~}h{|y~|i{|y~|xy~|y~|xy~}s{|y~|wy~}yy~}r{|y~}p{|y~|q{|y~w|k{|y~}p{|y~|r{|y~|w{}x~bx~|jy~}k{}y~r{|y~|my~" "}xy~}oy~}{|y~w{|y~yy~}o{|y~}{y~}fy~}g{|y~}d{}~}ay~c{|y~| x{}y~}|w{|y~m{}y~sy~}o{|y~e{}y~s{}~}o{|n~jy~|i{}y~s{}~" "}n{}y~t{}~}j{|y~d{|y~h{}w~}c{|y~m{}y~ty~|u{|y~r{}y~t{}~}o{}y~s{}y~n{}y~sy~}p{}y~s{}~}k{}y~e{|u~}h{}y~g{}~}t{}~}" "m{|y~wy~|ny~}{|~}y{}~|{|y~k{}y~}h{|y~|y{|y~|h{|y~}h{}w~|c{}~}c{|}x~}oy~}x|}r~|X{~|v{}~|v{~}r{}y~ty~}l{|y~t{}y~n" "{|y~|wx~|n{|y~s{}y~l{|u~j{}y~t{}~}ly~}y{|y~|j{}y~y{|y~|l{}~}t{}~}r{|y~}vy~|vy~}s{}y~x{|y~x{|y~|ny~|w{|y~|o{}y~x" "{|y~x{|y~|o{}y~sy~}p{|y~s{}y~iy~|j{|y~|t{}y~ny~}u{|y~|j{|y~}h{|y~|i{|y~}px~ry~}w{}y~w{}y~|s{|y~|ry~}p{|x~|{}y~y" "{}y~}r{|y~}p{|y~|u{|h~ly~|m{}h~ly~|m{}h~ly~|J{}~}i{}y~w{~|h{|y~|fy~|uy~mv}x~v}|Tx~|wy~U{~|yy~|q{|~or}ly~}xy~|^{" "|~}Y{~|x{}~}y{}~}w{|~8{}~| v{}~}t{}~}hy~y{}~| yr}h{}~}y{|y~|k{|~}v{|~y|~}ny~r{}~|p{|~}v{|~{|~}m{|y~iy~}t|y~|ny~" "}t|y~|ny~}t|y~|ny~}t|y~|ny~}t|y~|ny~}t|y~|r{}y~u|y~}k{|y~}c{|y~|e{|y~|e{|y~|e{|y~|a{|y~|e{|y~|e{|y~|e{|y~|k{|y~" "|q{}y~r{|y~|wy~}yy~}r{|y~}p{|y~|t{|y~}p{|y~|t{|y~}p{|y~|t{|y~}p{|y~|t{|y~}p{|y~|n{|w~}m{|y~}y{}~}u{|y~|s{}y~r{|" "y~|q{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|jy~}i{|y~|w{|x~}n{}y~v{}x~|n{}y~}|w{|y~m{}y~}|w{|y~m{}y~}|w{|y~m{}y~}|w{|y~" "m{}y~}|w{|y~m{}y~}|w{|y~r{}y~}|w{|n~s{|y~e{|n~o{|n~o{|n~o{|n~j{|y~d{|y~d{|y~d{|y~i{|y~s{}y~n{}y~t{}~}o{}y~s{}y~" "o{}y~s{}y~o{}y~s{}y~o{}y~s{}y~o{}y~s{}y~pk|p{}y~x{}~|y{}y~n{}~}t{}~}n{}~}t{}~}n{}~}t{}~}n{}~}t{}~}m{|y~|y{|y~|l" "{}y~sy~}n{|y~|y{|y~|;{|~}vy~|w{|~}s{|~}o{|~}s{|~}y{}y~}|y~}y{|~}s{|~}y{}y~}u{|~}s{|~}vy|v{|~}ky~fy~}y{}y~9k~}n{" "}y~y{~|R{}l~ri~p{|q~}lq~m{|y~sy~|o{|y~sy~|m{}y~x{|y~|j{}y~yy~}o{|y~ Ey~}E{|Qj~j{|~y{|y~}l{|~}xy~|wy~u{|y~|v{|x" "~{|y~R{}y~a{|y~K{}~|M{}u~|M{|y~hy~}t{}y~i{|y~|f{}y~|_{}y~o{}n~}ey~}n{}y~t{|y~|j{}y~|jy~}t{|y~|e{}y~;{|}v~}jk~}k" "{|}v~}j{}~}n{|~}wy~ty~wy~t{|o~}o{|y~|t{|y~|px~e{|y~|qy~}p{|y~|e{|y~|gx~py~}r{|y~|ry~}k{|y~|e{|y~|j{|y~|y{}y~}i{" "|y~|i{|y~|x{}w~wy~}s{|y~|w{|y~|{y~}qx~p{}y~|q{|y~|gx~p{}y~|r{|y~|v{|y~}c{|y~}jy~}k{}y~r{|y~|m{}y~y{}y~|o{}y~{|~" "}vy~{|y~|ox~y{|y~|gy~}h{|x~c{}~}a{}~|d{|y~| xy~|u{|y~m{}y~sy~}o{|y~e{|y~s{}~}o{|y~_y~|i{|y~s{}~}n{}y~t{}~}j{|y~" "d{|y~h{}y~|y~}d{|y~m{}y~ty~|u{|y~r{}y~t{}~}o{|y~s{}y~n{}y~sy~}p{|y~s{}~}k{}y~b{|}w~i{}y~g{}~}t{}~}ly~|y{}y~m{}~" "}{}~}y{|~}{}~}l{|w~|h{}~}y{}y~h{|y~}d{}y~|d{}~}d{|y~}|m{}t{|}x~}|V{~}w{|x~v{~|r{|y~ty~|l{|y~t{|y~|o{}y~v{}y~m{|" "y~s{}y~m{}y~}f{}y~t{}~}l{|y~y{}~}iy~|xy~}l{}~}t{}~}qy~}vy~}vy~}s{|y~x{|y~x{|y~|ny~|w{|y~|o{}y~x{|y~x{|y~|o{}y~s" "y~}p{|y~s{}y~iy~|j{|y~|ty~}o{|y~|ty~}k{|x~g{|y~|hx~q{|y~}r{}y~|x{}y~x{|x~r{|y~|ry~}o{}x~}x~}x~}px~p{}y~|t{}y~}]" "y~|^{|x~oy|yy~|y{|o{}y~|q{|x~oy|yy~|y{|M{}~}i{}y~w{~|h{|y~|f{}~}v{}~}n{|n~|S{}x~|{}~}Uy}y{}~}qy}p{|r~ky~}y{|y~}" "_{|~}Yy}x{}~}xy~|xy}8{}~| v{}~}t{}~}hy~y{}~| {{|r~iy~}y{|y~}jy~|w{|~|{|~}o{}~|s{|y~oy~v{|~|{|~}m{|y~j{|o~}o{|o~" "}o{|o~}o{|o~}o{|o~}o{|o~}s{|p~}jx~c{|y~|e{|y~|e{|y~|e{|y~|a{|y~|e{|y~|e{|y~|e{|y~|k{|y~|qx~r{|y~|w{|y~|{y~}qx~p" "{}y~|sx~p{}y~|sx~p{}y~|sx~p{}y~|sx~p{}y~|o{|x~|y~}my~}{}~}t{}y~|s{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|q{}y~r{|y~|jy~" "}i{|q~}m{}y~u{|x~|oy~|u{|y~my~|u{|y~my~|u{|y~my~|u{|y~my~|u{|y~my~|u{|y~ry~|u{|y~h{|y~e{|y~d{|y~d{|y~d{|y~_{|y~" "d{|y~d{|y~d{|y~i{|y~s{}y~n{}y~t{}~}o{|y~s{}y~o{|y~s{}y~o{|y~s{}y~o{|y~s{}y~o{|y~s{}y~U{|y~y{}~|x{}y~n{}~}t{}~}n" "{}~}t{}~}n{}~}t{}~}n{}~}t{}~}l{}~}y{}y~k{}y~sy~}m{}~}y{}y~:{|y~vy~|w{}~|s{|y~o{}~|s{|y~{|y~}y{|y~}{}~|s{|y~{|y~" "}t{}~|s{|y~o{}~|ky~f{}y~yy~}9k~}n{|y~y|~Q{|u~|y}u~r{}t~y}s~o{|s~}k{|s~|m{|y~sy~|ny~sy~ly~}wy~}j{|y~y|y~|ny~| F" "x~ uj~j{|~x{}y~ly~wy~|wy~u{|y~|u{|x~}~}R{|y~a{}y~K{}~| r{}~}h{}y~t{}y~i{|y~|g{}y~|^{}y~o{}n~}ey~}n{}y~t{|y~|jy~" "}iy~}t{|y~|ey~}8{|}w~}|mk~}n{|}v~}|hx}m{~}wy~|v{|y~x{|~}t{}n~|p{|y~|t{|y~}p{}y~|f{|y~|r{}y~|p{|y~|e{|y~|g{}y~|q" "y~}r{|y~|ry~}k{|y~|e{|y~|j{|y~|x{}y~}j{|y~|i{|y~|x{|x~}wy~}s{|y~|vy~}{y~}q{}y~|qx~p{|y~|g{}y~|qx~q{|y~|u{}y~|d{" "|y~}jy~}k{|y~|s{}y~|m{|y~|{y~}n{}y~{}~}v{}~y|y~|p{}y~|x{}y~gy~}hx~|c{}~}a{|~}d{|y~| y{|y~t{}y~m{}y~sy~|o{|y~|f{" "|y~|ty~}o{|y~|`y~|i{|y~|ty~}n{}y~t{}~}j{|y~d{|y~h{}y~{|x~e{|y~m{}y~ty~|u{|y~r{}y~t{}~}o{|y~|t{}y~n{}y~sy~|p{|y~" "|ty~}k{}y~_{|y~}j{}y~g{}~}ty~}l{}y~yy~}m{|y~{y~|y{|y~{y~}m{|y~y}y~h{|y~yy~|hx~by~}d{}~}d{}y~7{}~|y{|~}|~}x{}~q{" "|y~|v{|y~}l{|y~t{|y~|o{}~}v{}~}m{|y~|t{}y~my~|e{}y~t{}~}ky~|{y~|j{}y~w{}y~l{}~}ty~}qy~}vy~}vy~}s{|y~|y{|y~x{}y~" "my~|w{|y~|o{|y~x{|y~x{|y~|o{}y~sy~|p{|y~|t{}~}iy~|iy~}ty~|o{}y~s{}y~|lx~|g{|y~|h{|y~}rx~px~|y{}y~y{|x~|r{|y~|ry" "~}n{|r~}o{}y~|qx~r{}y~}^y~|_{|x~o{|y~|{y~|{}~}o{}y~|s{|x~o{|y~|{y~|{}~}Ny~}i{}y~w{~|h{|y~|f{|y~}|{|}y~|h{}y~L{|" "v~}T{|~xy~}|yx|x{~|U{}y~y{|y~}`{|~}Y{|~x{}~}x{|y~x{~|8{}~| v{}~}ty~}hy~y{}~| `{|y~}y{|y~|j{}~}v{~}y{|~}p{|y~ry~" "|p{}~|v{~}y{|~}mx~j{}n~|p{}n~|p{}n~|p{}n~|p{}n~|p{}n~s{}p~}j{}y~|d{|y~|e{|y~|e{|y~|e{|y~|a{|y~|e{|y~|e{|y~|e{|y" "~|k{|y~|r{|y~}r{|y~|vy~}{y~}q{}y~|qx~r{}y~|qx~r{}y~|qx~r{}y~|qx~r{}y~|qx~o{|x~y{|y~}n{}y~}~}sx~r{|y~|s{}y~|q{|y" "~|s{}y~|q{|y~|s{}y~|q{|y~|s{}y~|jy~}i{|s~}|l{}y~sy~}p{|y~t{}y~n{|y~t{}y~n{|y~t{}y~n{|y~t{}y~n{|y~t{}y~n{|y~t{}y" "~s{|y~t{}y~|i{|y~|f{|y~|e{|y~|e{|y~|e{|y~|`{|y~d{|y~d{|y~d{|y~i{|y~|t{}y~n{}y~t{}~}o{|y~|t{}y~o{|y~|t{}y~o{|y~|" "t{}y~o{|y~|t{}y~o{|y~|t{}y~ix|j{|y~|}~}w{}y~n{}~}ty~}n{}~}ty~}n{}~}ty~}n{}~}ty~}l{|y~yy~|k{}y~sy~|m{|y~yy~|9{}~" "}wy~|x{|y~q{}~}q{|y~q{}~}{~}w{|~y|y~q{}~}{~}t{|y~q{}~}q{|y~k{|y~f{|y~y|y~|9x|}y~}q|m{}~x}P{}w~}{}{v~|r{|t~y|}u~" "|n{}u~}i{|u~}l{|y~sy~|ny~|u{|y~ly~|w{}y~iy~y}y~m{|y~| G{|y~| ry~|xy~|f{|~x{}y~m{}~|wy~|wy~ty~}t{|w~Q{|y~|b{}y~" "K{}~| ry~|h{|y~|uy~}i{|y~|h{}y~|]x~ns|x~y|e{|y~}n{|y~|u{}y~|k{|y~|iy~}t{}y~e{}y~4{|}w~}|U{|}v~}|Ty~w{}~}v{}y~xy" "~sy~}ry~}p{|y~|t{|y~}p{|x~p{|r{|y~|s{|x~o{|y~|e{|y~|g{|x~qy~}r{|y~|ry~}k{|y~|e{|y~|j{|y~|w{}y~}k{|y~|i{|y~|wx~|" "wy~}s{|y~|v{|y~|y~}q{|x~r{}y~|p{|y~|g{|y~}r{}y~|q{|y~|u{|y~}d{|y~}jy~}k{|y~}sx~ky~}|y~|n{|y~|y~|v{}~y}y~p{|y~}w" "{|y~}hy~}i{}y~|b{}~}a{|y~d{|y~| y{|y~tx~m{}y~|u{|y~|ny~}ey~}u{|y~}ny~}`y~|hy~}u{|y~}n{}y~t{}~}j{|y~d{|y~h{}y~y{" "|x~f{|y~m{}y~ty~|u{|y~r{}y~t{}~}ny~}ty~}n{}y~|u{|y~|oy~}u{|y~}k{}y~^{}~}j{|y~g{}y~u{|y~}l{|y~y|y~|ly~|y~wy~|y~|" "mx~yy~}hy~y|y~hx~a{}y~d{}~}d{}~}6u~y{}y~}y~|py~|v{}y~}l{|y~t{|y~|o{}~}vy~|ly~}ty~}n{|y~|e{}y~t{}~}k{}~y}y~iy~}v" "y~|m{}y~ty~}qx~w{|x~w{|y~|ry~}y{|y~x{}~}my~|w{|y~|o{|y~x{|y~x{|y~n{}y~|u{|y~|oy~}ty~}iy~|i{}y~u{|y~ny~}s{|y~}m{" "}y~|f{|y~|g{}y~|t{}y~|p{|w~y}y~y}x~}q{|y~|ry~}ly}x~y}|n{|x~r{}y~|q{}y~}_y~|`{|x~mx~|y~|}y~|n{}y~|u{|x~mx~|y~|}y" "~|Ny~}i{|y~|x{~|h{|y~|fp~|i{}y~d{}~}d{|x~|S{~}x{}u~|y{}~S{}y~xy~}a{|~}X{~}y{|~|w{}~|{}~7y| u{}y~ty~}hy~y{}~| a{" "|y~}y{|y~|j{|y~v{}~x{|~}p{}~|s{}~|p{|y~v{}~x{|~}n{}y~|jy~}ry~}py~}ry~}py~}ry~}py~}ry~}py~}ry~}py~}ry~}ty~}ty~}j" "{|x~p{|p{|y~|e{|y~|e{|y~|e{|y~|a{|y~|e{|y~|e{|y~|e{|y~|k{|y~|rx~q{|y~|v{|y~|y~}q{|x~r{}y~|r{|x~r{}y~|r{|x~r{}y~" "|r{|x~r{}y~|r{|x~r{}y~|p{|x~w{|y~}o{|w~s{}y~|r{|y~}sx~p{|y~}sx~p{|y~}sx~p{|y~}sx~iy~}i{|y~w|h{}y~s{}~}p{|y~tx~n" "{|y~tx~n{|y~tx~n{|y~tx~n{|y~tx~n{|y~tx~s{|y~tx~}hy~}ey~}dy~}dy~}dy~}`{|y~d{|y~d{|y~d{|y~hy~}ty~}n{}y~t{}~}ny~}t" "y~}ny~}ty~}ny~}ty~}ny~}ty~}ny~}ty~}j{|x~iy~}~}vy~}n{}y~u{|y~}n{}y~u{|y~}n{}y~u{|y~}n{}y~u{|y~}ky~y|y~j{}y~|u{|y" "~|ly~y|y~7y~}xy~|y{|y~|py~}s{|y~|py~}s{|y~|py~}s{|y~|py~}s{|y~|k{|y~ey~y}y~6{|y~}b{|x~|O{}y~}y{}{|}y~|p{|w~}{|}" "{}w~}l{}v~g{}w~}k{|y~sy~|n{}y~uy~}m{|y~v{|y~|j{}w~}l{}y~| Gx~|u{}|Px|O{|y~x{|y~j{|w{|~x{}~}n{|y~v{}~|x{|y~t{}y" "~}t{}x~Py~|by~}K{}~|dx|Jx|f{|y~fx~v{}y~h{|y~|i{}y~|f{|s{}y~}f{}y~l{|t{|x~l{}y~ux~j{}y~h{}y~|v{|x~f{|y~}hx|dx|a{" "}v~}Xv~}|bx|m{}~|x{|y~}x{|x~{|y~|t{|y~|r{}y~p{|y~|t{}y~|o{}y~}s{|~|r{|y~|t{|x~|o{|y~|e{|y~|f{}y~}ry~}r{|y~|ry~}" "k{|y~|e{|y~|j{|y~|v{}y~}l{|y~|i{|y~|oy~}s{|y~|uv~}p{}y~}t{}y~}o{|y~|f{}y~}t{}y~}p{|y~|t{}y~|o{}r{}y~|jy~}j{}y~|" "u{|y~}k{}y~}y~ly~}y~u{|w~}px~u{|y~|iy~}j{}y~}a{}~}`y~|e{|y~| y{|y~|v{}x~m{}x~ux~m{}y~|f{}y~u{}y~}n{}y~|ay~|h{}y" "~u{}y~}n{}y~t{}~}j{|y~d{|y~h{}y~x{|x~g{|y~m{}y~ty~|u{|y~r{}y~t{}~}n{}y~|v{}y~|n{}x~ux~n{}y~u{}y~}k{}y~^y~}j{|y~" "g{|y~|v{}y~}ky~y}y~kw~}w{}w~m{}y~|y{|y~}i{}~}y~}i{}y~|a{}y~d{}~}d{}~}5{}y~}w{|y~}|o{}y~w{|w~l{|y~}u{}y~n{}~}w{}" "y~k{}y~|v{}y~|my~|e{}y~t{}~}k{|w~}j{}y~u{}~}m{}y~|v{}y~}q{}y~|x{}~}~|x{}y~q{}y~|{|y~y{|y~|my~|w{|y~|ny~}y{|y~x{" "}y~n{}x~ux~n{}y~|v{}y~|iy~|i{|y~}vy~}o{|y~|rx~n{|y~}e{|y~|fx~|v{}y~}n{|}q~|p{|y~|ry~}j{}y~j{}y~}t{}y~}o{}~}_y~|" "`{|y~ks~|l{}~|u{|y~ks~|My~}hx~x{~|h{|y~|gx~|}x~}|}y~|j{}y~d{}~}c{|x~S{|~}xy|}y|x{}~|R{}~|x{}~a{|}|X{|~}p{}~| /{" "}y~|v{}y~}hy~y{}~| a{|~|x{}~|i{}~|vr~|s{|~}s{}~|o{}~|vr~|q{}y~}j{|y~|r{}y~q{|y~|r{}y~q{|y~|r{}y~q{|y~|r{}y~q{|y" "~|r{}y~q{|y~|r{}y~u{|y~|ty~}i{}y~}s{|~|p{|y~|e{|y~|e{|y~|e{|y~|a{|y~|e{|y~|e{|y~|e{|y~|k{|y~|t{|x~}q{|y~|uv~}p{" "}y~}t{}y~}p{}y~}t{}y~}p{}y~}t{}y~}p{}y~}t{}y~}p{}y~}t{}y~}p{|x~u{|y~}o{}y~}t{}y~}p{}y~|u{|y~}o{}y~|u{|y~}o{}y~|" "u{|y~}o{}y~|u{|y~}iy~}i{|y~|e{}y~sy~}p{|y~|v{}x~n{|y~|v{}x~n{|y~|v{}x~n{|y~|v{}x~n{|y~|v{}x~n{|y~|v{}x~s{|y~|v{" "}w~|i{}y~|f{}y~|e{}y~|e{}y~|e{}y~|a{|y~d{|y~d{|y~d{|y~h{}y~|v{}y~|n{}y~t{}~}n{}y~|v{}y~|n{}y~|v{}y~|n{}y~|v{}y~" "|n{}y~|v{}y~|n{}y~|v{}y~|j{|x~i{}y~}v{}y~|n{|y~|v{}y~}n{|y~|v{}y~}n{|y~|v{}y~}n{|y~|v{}y~}k{}~}y~}j{}x~ux~k{}~}" "y~}7{|y~}|{y|{|}y~|o{|y~}|w{|}y~|o{|y~}|w{|}y~|o{|y~}|w{|}y~|o{|y~}|w{|}y~|j{|y~e{|w~|6y~}`x~I{|~hx|y{|}yw|jw~|" "f{}x~j{|y~sy~|mx~w|x~l{}~}uy~}j{}w~|k{}y~}| I{|x~}|{y|y~|Py~}O{|~}x{|~}j{}~|y{|~{|}y~|n{}~|v{|y~x{}~}sx~}|y{|}" "u~Q{}~}by~|K{}~|d{}y~Jy~}f{}~}f{|y~}|{|}y~}kw|y~w|m{}y~}s|my~}w|}w~e{}y~ly~}w|}x~}l{|x~|y{|x~|jy~}h{|x~}|{y|x~|" "m{~}w|}y~}g{}y~d{}y~_{|}y~}Xy~}|_y~}m{|~}w{|u~y}w~|sx~q{|y~|q{|y~t|}y~}m{}x~}v|}y~|r{|y~u|y}x~}n{|y~q|n{|y~|e{}" "x~}v|}x~}r{|y~|ry~}k{|y~|e{|y~|j{|y~|u{}y~}m{|y~q|r{|y~|oy~}s{|y~|u{|w~}o{}x~}|{y|}x~n{|y~|e{}x~}|{y|}x~o{|y~|t" "{|y~}oy~}x|{y|x~}iy~}j{|x~}w|}x~j{|w~}l{}x~}tw~|q{}y~|t{}y~iy~}k{|x~o|l{}~}`{}~}e{|y~| xx~|y{|}w~m{}w~|y{|x~|lx" "~}|yy|}|mx~|y{|}x~}m{}y~}|x{|}~}jy~|h{|x~|y{|}x~}n{}y~t{}~}j{|y~d{|y~h{}y~w{|x~h{|y~m{}y~ty~|u{|y~r{}y~t{}~}mx~" "|y{|}y~}m{}w~|y{|x~|mx~|y{|}x~}k{}y~g{}~}|x{|}y~|j{|y~}gx~|y{|}x~}k{}w~}k{}x~}w{|x~}n{|y~|w{}y~|j{|w~|j{}y~|`{}" "y~d{}~}d{}~} w{|y~}|{|y~}y~}m{|x~}|y{|}y~}n{|~}x{|y~|jx~|y{|}y~}l{}y~}|x{|y}m{}y~t{}~}jw~|jy~}u{|y~|n{}x~}|{|}w" "~y|s{|x~|{|y~|~}|{}y~}px~y|y~|}y~}ly~|vy~}n{}y~|{|y~y{}y~|n{}w~|y{|x~|mx~|y{|}y~}h{}y~|i{}y~}y{|x~nx~q|}y~|ox~r" "|m{|y~|iw|x~}x{}y~}w|o{|y}x~y}|n{|y~|ry~}j{}y~i{}x~}|{y|}x~m{|^y~|_{|iu~|j{|s{|iu~|Ly~}h{|y~}|{~|{|}mx|y~}t|o{|" "y~r{}~}j{}y~d{}~}b{|y~|S{|~}r{}~|Py|w{}:{|~}r{}~|=k|!{}x~}|{|}w~y|jy~y{}~| ay|w{}h{|~}uv|}~}|ry~s{}~|o{|~}uv|}~" "}|q{|y~}ix~q{|y~|rx~q{|y~|rx~q{|y~|rx~q{|y~|rx~q{|y~|r{}y~q{|y~|vx~sy~}r|q{}x~}v|}y~|p{|y~q|n{|y~q|n{|y~q|n{|y~" "q|j{|y~|e{|y~|e{|y~|e{|y~|k{|y~}u|}x~}p{|y~|u{|w~}o{}x~}|{y|}x~n{}x~}|{y|}x~n{}x~}|{y|}x~n{}x~}|{y|}x~n{}x~}|{y" "|}x~ox~s{|y~}pv~}|{y|}x~o{|x~}w|}x~n{|x~}w|}x~n{|x~}w|}x~n{|x~}w|}x~hy~}i{|y~|e{}y~{x|y{|}y~|ox~|y{|}w~mx~|y{|}" "w~mx~|y{|}w~mx~|y{|}w~mx~|y{|}w~mx~|y{|}w~rx~|y{|}y~|}y~}|x{|}~}qx~}|yy|}|m{}y~}|x{|}~}m{}y~}|x{|}~}m{}y~}|x{|}" "~}m{}y~}|x{|}~}j{|y~d{|y~d{|y~d{|y~gx~|y{|}y~}m{}y~t{}~}mx~|y{|}y~}lx~|y{|}y~}lx~|y{|}y~}lx~|y{|}y~}lx~|y{|}y~}" "i{|x~i{|x~|y{|}y~}lx~|y{|}x~}mx~|y{|}x~}mx~|y{|}x~}mx~|y{|}x~}k{|w~|j{}w~|y{|x~|k{|w~|6{|q~|m{|q~|m{|q~|m{|q~|m" "{|q~|i{|y~dw~5{}~_{}~}I{}~c{}~d{|y~|dy~|j{|y~sy~|m{|s~|ly~}u{}~}j{|w~i{}m~ S{|s~}Oy~}O{}~|x{}~|j{}q~}n{|~}t{}y" "~}x~q{}s~}{|y~}R{|y~c{|y~J{}~|dx~Jy~}fy~|e{}t~}k{}q~}no~|nq~}d{}y~lq~|j{|s~|j{|y~|g{|r~|ls~}f{}y~dx~\\y|X{}|]y~" "}ly~|w{|}y~}|{}~}|r{|y~}py~}q{|p~}k{|q~}q{|p~}|m{|o~|o{|y~|d{|p~}q{|y~|ry~}k{|y~|e{|y~|j{|y~|t{}y~}n{|o~r{|y~|o" "y~}s{|y~|t{}x~}n{}r~}m{|y~|d{}r~}n{|y~|s{}y~|pp~}hy~}i{|r~}hw~|l{}x~}tw~|r{|y~}s{|y~}jy~}k{}l~|m{}~}`{|y~e{|y~|" " x{|t~}|y~m{}y~|t~|j{}s~|m{|t~|}~}l{}r~}jy~|g{|t~|}~}n{}y~t{}~}j{|y~d{|y~h{}y~v{|x~i{|y~m{}y~ty~|u{|y~r{}y~t{}~" "}m{|s~}l{}y~|t~|l{|t~|}~}k{}y~g{}r~}h{}u~k{|t~|}~}k{|w~|k{|x~|w{|x~|ny~}u{}y~iw~io~h{}y~d{}~}d{}~} v{}t~{}x~}o{" "|q~}ly~}y|y~}i{|s~}j{}s~}m{}y~t{}~}j{}x~j{}y~sy~}n{}~}t~}x~}r{|u~|{t~o{|q~ky~|vw~}ot~}x~}m{}y~|t~|l{|s~}g{|v~j{" "}t~|o{|k~}p{|o~|n{|y~|is~y{|t~}l{}y~k{|y~|ry~}j{}y~h{}r~}Ny~|Kw~|Lw~|Ky~}g{|r~n{|o~}n{|p{|i{}y~d{}~}ay~|R{|y~}y" "|{y|}y~| a{|y~}y|{y|}y~|<k~}\"{}~}t~}x~}jy~y{}~| Gy~o{|~}r{}~|ty~|ny~o{|~}q{|y~}i{|y~}py~}s{|y~}py~}s{|y~}py~}s" "{|y~}py~}s{|y~}py~}s{|y~}py~}w{|y~|so~}q{|q~}o{|o~|o{|o~|o{|o~|o{|o~|k{|y~|e{|y~|e{|y~|e{|y~|k{|o~|o{|y~|t{}x~}" "n{}r~}l{}r~}l{}r~}l{}r~}l{}r~}n{|~q{|~p{}~y|r~}m{|r~}l{|r~}l{|r~}l{|r~}gy~}i{|y~|e{}y~{}t~}n{|t~}|y~m{|t~}|y~m{" "|t~}|y~m{|t~}|y~m{|t~}|y~m{|t~}|y~r{|s~|y{}r~|p{}s~|l{}r~}l{}r~}l{}r~}l{}r~}j{|y~d{|y~d{|y~d{|y~fs~}l{}y~t{}~}m" "{|s~}k{|s~}k{|s~}k{|s~}k{|s~}Rq~}k{|t~|}~}m{|t~|}~}m{|t~|}~}m{|t~|}~}jw~i{}y~|t~|iw~3{|}w~}|i{|}w~}|i{|}w~}|i{|" "}w~}|i{|}w~}|g{|~}d{}y~} r{|~|Iy~|dy~|d{|}cy|i{|y}sy}|k{}w~}k{|y~|u{|y~ix~}gy}p~ Q{|}x~}|Ny~}Oy~wy~h{|y}v~}|my" "~r{|x~}o{|}w~}|x{}y~}Ry~|d{}~}J{}~|dy~}Jy~}g{|y~c{|}x~}|j{}q~}no~|m{|}w~y}|c{}y~l{|y}w~y}f{}w~}hx~dy}x~y}|k{|}w" "~}|e{}y~dy~} ry~}l{|y~c{}y~|p{}y~q{|r~}|h{|}w~}|o{|s~y}|k{|o~|o{|y~|b{|}w~y}|o{|y~|ry~}k{|y~|e{|y~|j{|y~|s{}y~}" "o{|o~r{|y~|oy~}s{|y~|t{|x~}l{|}x~y}|l{|y~|b{|}v~}m{|y~|ry~}o{|y}w~y}|gy~}g{|}w~}|g{|x~k{|x~|t{}x~qx~q{}y~|ky~}k" "{}l~|m{}~}_y~|f{|y~| v{}x~}|{|y~m{}y~{|}x~}|h{|}x~y}|j{}x~}|{}~}k{|}w~y}|iy~|e{}x~}|{}~}n{}y~t{}~}j{|y~d{|y~h{}" "y~u{|x~j{|y~m{}y~ty~|u{|y~r{}y~t{}~}k{|}x~}|k{}y~{|}x~}|i{}x~}|{}~}k{}y~f{|y}w~}|fy}w~j{|}x~}y{}~}jx~}ix~ux~|o{" "}y~t{|y~}j{|y~}io~h{}y~d{}~}d{}~} u{|}x~}|y{}y~}o{|y~|}w~}|k{|v~}f{|}x~}|h{|}w~y}|m{}y~t{}~}j{|y~|jy~}s{}y~n{}~" "}{}x~}y{}~}|q{|}y~}|x{}x~}l{}v~}|jy~|v{|}y~}n{}s~|l{}y~{|}x~}|i{|}x~}|e{|}x~i{|}x~}m{}j~p{|o~|n{|y~|is~y{|t~}l{" "}y~k{|y~|ry~}j{}y~f{|}x~y}|My~|Jy~|Jy~|Jy~}f{|}u~}n{|o~}O{}y~d{}~}h{}|w{}y~O{|}v~}| ]{|}v~}|:k~}\"{}~}{}x~}y{}~" "}|jy~y{}~| H{}~|o{|~|s{|~}t{|t~|t{}~|o{|~|q{}y~h{}y~|p{}y~s{}y~|p{}y~s{}y~|p{}y~s{}y~|p{}y~s{}y~|p{}y~s{}y~|p{}" "y~w{}y~ro~}o{|}w~}|m{|o~|o{|o~|o{|o~|o{|o~|k{|y~|e{|y~|e{|y~|e{|y~|k{|s~y}|m{|y~|t{|x~}l{|}x~y}|i{|}x~y}|i{|}x~" "y}|i{|}x~y}|i{|}x~y}|U{|~}x{|}x~y}|j{|}w~}|i{|}w~}|i{|}w~}|i{|}w~}|fy~}i{|y~|e{}y~{|}w~}|k{}x~}|{|y~k{}x~}|{|y~" "k{}x~}|{|y~k{}x~}|{|y~k{}x~}|{|y~k{}x~}|{|y~p{}x~}|v{|}w~y}|n{|}x~y}|j{|}w~y}|j{|}w~y}|j{|}w~y}|j{|}w~y}|i{|y~d" "{|y~d{|y~d{|y~e{|}x~}|k{}y~t{}~}k{|}x~}|h{|}x~}|h{|}x~}|h{|}x~}|h{|}x~}|R{}~|{|}x~}|i{|}x~}y{}~}l{|}x~}y{}~}l{|" "}x~}y{}~}l{|}x~}y{}~}j{|y~}i{}y~{|}x~}|h{|y~} e{|~} V{| .{|~ p{}~}dy~|1{|y~2{}~} U{|y~ ^{}~} ){|y~| {" "}y~} 6{}~}_{}~}f{|y~| -y~}6{|y~ A{}y~Z{}~} j{|y~I{}y~d{}~}d{}~} \\{|y~a{|}y|*{}~}j{|y~|O{}~}F{|y~K{|}y~y|j{}" "y~ Ry~}c{|~| r{}~}h{}t~|K{| U{| '{}~}^y~y{}~|O{|~| wy|cy}|st|sy|ay~} ^{|~| 9{| Y{|~| 8y| Q{|y~h{}" "y~`{|y~ d{|~} c{|~ oy~e{}~}0{}~}2y~| U{}~} ]{}y~|r{|y} 7{}y~ y{}y~| 7{}~}_{|y~f{|y~| .{|y~|6{|y~ " "A{}y~Z{}~} j{}~}I{|y~d{}~}dy~} \\{|y~ g{}~}j{|y~|O{}~}F{|y~J{|y~h{}y~ Ry~}b{~| r{}~}h{|y}x~}| ){}~}^y~y{" "}~|N{}~ 'y~} ]y~ p{~} g{}~}h{}y~`{}~} h{|}|{}~} c{|~ o{}~}fy~/{}~ c{}~ [{}y~}|v{|}y~} " " 7x~ x{}y~| 8{}v~M{|v~| .{}y~5{}~} A{}y~Z{}~} k{|y~|I{|y~}e{}~}e{|y~| \\{|y~ g{}~}j{|y~|O{}~}F{|y~J{|y~h{}y" "~ Ry~}b{~| r{}~} i{}~}*{}~| (x~uy| e{}~| q{}~ h{|y~|h{}y~a{|y~| h{|y~|y~| c{|~ ny~" "g{}~} M{|}q~| 9y|}y~| 1{}w~}M{|v~| 6y}|x{|}y~|6{|y~} A{}y~Z{}~} l{|x~G{}w~}h{}~}h{}w~} [{|y~ g{}~}j{" "|y~|O{}~}F{|y~J{|y~h{}y~ Ry~}b{~| r{}~} i{}~}-x}y~ '{}x~w|y~| e{}~| qy~ i{|x~g{}y~b{|x~ f" "{}w~ e{|y}w~}| 8{|w~} ({|n~} m{}s~}7{|w~ @{}y~Z{}~} nv~|F{|y}~}h{}~}h{}~y}| Z{|y~ g{}~}j{" "|y~|O{}~}F{|y~J{|y~h{}y~ Rx| W{}~} i{}~}-{}y~}| &{}s~| i{|~y}y~ t{|~y}y~ kv~|g{}y~dv~| ex" "} s{|y~}| '{|n~} m{|y}w~}|6{|y~} ?{}y~Z{}~} nx~}|-{}~} B{|y~ g{}~}j{|y~|O{}~}F{|y~J{|y~" "h{}y~ q{}~} -{|}x~}| f{}y~}| t{|x~}| kx~}|f{}y~dx~}| " " :{}~} I{" }; // Define a 52x64 font (large sans). static const char *const data_font_large[] = { " " " -{| " " [{|x}|Dw}|Pw}| @{}v~} C{|w}|Ew}|Pv}| xv|Ev|Pu| kv|Dw|P{|v} 6{|w}|E{|x}|P{" "|w}| pw}| " " G{|w~}F{}w~P{}v~}Q{}w~}|w{|x~X{|v~vv~|U{|r~| D{}w~F{}w~P{}u~S{|v~|wv~}V{}w~|G{|w~|Q{" "|u~|Sv~}w{}w~}\"{|}x~}|v{|x~W{}w~|F{}w~Q{|u~}Q{}x~}|v{|x~X{}w~}w{|v~ G{}w~F{}w~|Q{}u~Rv~|w{}w~}O{}w~ " " " " E{|w~|H{}w~P{}t~}Ss~}|y{}x~X{|v~vv~|V{|p~ Cw~}H{|w~|Q{|t~}T{|v~|wv~}U{}w~Gw~}Q{|s~|Tv~}w{}w~}#{|s~}|{|x~" "}V{}w~|H{}w~Ps~}St~}w{}y~}X{}w~}w{|v~ Fw~}H{|w~|Q{|t~}Sv~|w{}w~}P{|w~| " " D{|w~|J{|w~|Q{|x~}{w~|U" "{}l~}X{|v~vv~|Vw~}x{}x~} D{|w~|J{|w~|Q{|w~{}x~}U{|v~|wv~}T{}x~}Iw~}Pw~y|w~Tv~}w{}w~}#k~|U{}w~I{|w~|Q{}x~|{}x~|U" "{}r~|{|x~}X{}w~}w{|v~ Ew~|Iw~}Pw~|}x~}Tv~|w{}w~}Q{|w~| M{| " " q{}w~Jw~|Q{|x~}xw~Ux~}y{|}t~}W{|v~vv" "~|W{|x~|v{|x~| D{|w~|Kw~}Pw~x{}x~|V{|v~|wv~}S{}x~}K{}x~}P{}x~|y{|x~}Uv~}w{}w~}${|x~|y{|s~}S{}x~}K{|w~|Q{}x~}xw~" "Ux~}{|}r~W{}w~}w{|v~ E{|w~|K{}x~}Pw~|y{}x~|Uv~|w{}w~}Qw~| O{}v~} " " s{}x~}L{}x~|Pw~vw~W{|x~v{|}w~}" "V{|v~vv~|W{}y~}tx~} C{|w~L{}x~}P{}x~|w{}x~|W{|v~|wv~}R{}x~|M{}x~}P{}x~|w{|x~}Vv~}w{}w~}${|x~v{|}w~|Q{}x~}Lw~|Q{" "|x~}vw~W{|x~w{|t~|W{}w~}w{|v~ D{|w~L{|x~}P{}x~|w{}x~|Vv~|w{}w~}R{}x~} P{|r~| Y{}w~| " " A{}x~|N{}x~}P" "{}x~u{|x~}\"v|vv|V{}y~}t{}y~} B{}x~}N{|x~}P{}x~|u{}x~Vv|vv|P{}x~|O{|x~}P{}x~|u{|x~}Wv|uv| D{}x~|N{}x~|Q{|x~}tx~" "}X{|x~u{|}y~}|Vu|vv| C{|x~}N{|w~P{|x~|u{}x~Vv|vu|S{|x~} Op~| Zv~| " " ;v~ u{|v~ 6{|y}|N{|y}|P{|x}s{|x} I" "{}y~}t{}y~} Aw|Nw|Ow|sw| Qw|Nw|Pw|rx| 5{|x}N{|x}O{|y}|s{|y}| {{|y}| Dv|@v|Rv| C{}x~}x{|w~ Hu|@v|Rw| yv}@v}R" "{|w} lv|@v|Rv| 8v}@v}|S{|w} m{}w~| E{|y~x}| ;{|w~} " " vv~| J{}y~}t{}y~} e{}w~}B{|w~}Rv~| Dx~|v{|x~| H" "v~A{}w~|S{|w~} {{|w~}B{}w~|S{|v~| Ay|sx|Y{}w~|B{|w~}Rv~ 8{|w~}B{|w~}Rv~| o{|w~} ?y}~}| *x~ J{" "|y~| b{}x~|T{|x~} L{|q~} y{}q~| H{|w~} xw~} `{|w~| {{|}t~)w~}Cv~Lv~Tw~}Dv~ G" "{|x}w~}Tw~|U{|v~y}| 1{|y}v~y}| cv~y} p{|y}x~y}| {{v|vv| 3{}w~| I{|x~|v{|x~| " " %{| 5{|y}w~y}|U{}w~|Cv~R{}v~}Q{|}y~}|ux~|Y{|v~|wv~}W{|x~t{}y~} H{|w~}C{}w~|Ru~|S{}w~}w{|v~W{}w~|D{|w~}R" "t~S{|v~vv~|X{|v~}K{}w~}ux~X{}w~C{|w~}R{}v~}Q{|}y~}|ux~|Y{|v~vv~| J{|w~}D{|w~}R{}u~Rv~|w{}w~}N{|w~}Zw~}Hv~}w{}w~" "} N{|u~} ,{|y~} Ix|Tx|kw| Ru| 6{|y~|Yv|fx}|Zu| o{|w~Rw~|Hx| Xu| vt|Ns| =t| xt|Ot| [u| ds| kr|" " Qt| ut| ts| S{|q~} y{}q~| G{}w~| yw~} `{|w~|!{}q~)w~}Cv~Lv~Tw~}Dv~ I{|r~}Tw~|U{|r~} 5{|}o~| yr| " " ps~} t{|p~| kt| is| s{|y} r{|x}| rx}| bt| lu|S{|v~vv~|!{|y}w~y}| :{|l~|Qx| u{|y}w~}|Q{|x}w~y}|K{|w~| " " 9y|y}w~|O{|y}w~}|)y|x}dw~|hy|x}dw~|ly|x}y~y}|e{}x~| 6w~}x{}x~} us| lt|Nt|Nt|Nt|Nt| ut|p{}~| 9{|}o~|V{" "}w~D{}w~R{|t~|S{|u~}vx~|Y{|v~|wv~}W{}y~}t{|x~ G{|w~}E{|w~}R{}t~S{}w~}w{|v~V{}w~E{|w~}R{}t~}T{|v~vv~|W{|v~}s{|y}" "X{}u~}w{|x~Ww~}Dv~R{|t~|S{|u~}w{|x~X{|v~vv~| I{}w~|Ew~}R{|t~}Sv~|w{}w~}Nw~}Yw~}Hv~}w{}w~} O{|s~|cW} i{}y~|" "\"{|}L{|u~}|Z{|}v~}|p{}u~}V{|} /g| ({}r~}| v~}R{}x~}vw~}R{|x}|t{|x}|V{|y~|\\{|}t~|i{}x~|]{}q~}|O{}x~}Iw~|R{|" "w~Hx~ *{|w~V{|}s~}|Sy|y}v~}T{|}q~}|V{|y}p~}|L{|u~}\\{|g~}T{}q~y}|_{}c~}[{|}q~}|U{|}r~}| b{|}q~| w{}v~}X{}k~y" "}|R{|y}p~}|b{}m~x}y|W{}c~|`{}e~Y{|}o~}|a{}w~}hv~|Y{}w~}M{}w~}W{}w~}k{|u~}b{}w~}V{}t~|h{}t~|h{}u~}jv~^{|}p~}|Z{}" "m~y}|U{|}p~}|\\{}m~y}y|S{|}o~}y|bZ~g{|v~h{}w~}i{|v~|d{|v~|rv~|l{|v~}kv~|p{|v~|i{}v~g{}v~fv~}g\\~]{|q~}Uw~}I{}q~" "|P{|w}| w{}w~ yw~} `{|w~|\"o~)w~}Cv~Lv~Tw~}Dv~ J{|q~}Tw~|U{|q~} 7{}l~}\"y}p~y} sr~} v{}n~}R{}v~}V{" "}c~|_{}d~}^{|}p~}|R{|v~Y{}^~|iv~}r{|v~qv~}a{|}p~}| x{}x~} s{}w~ s{}w~| f{|}r~}|-{}w~|i{|v~({|q~}|W{|v~vv~|Ty|u" "}y|U{|}o~| ly|u}y|U{|l~|T{|}v~}| {|}p~|T{}p~}|N{|w~} yy|}m~} N{|r~|P{}q~|0{|y}t~|f{}x~}l{|y}t~|f{}x~}l{}p~}h{}" "x~}%{}v~}N{}v~}N{}v~}N{}v~}N{}v~}Q{|p~W{}\\~}b{|y}p~}|^{}c~|a{}c~|a{}c~|a{}c~|X{}w~}M{}w~}M{}w~}M{}w~}Z{|m~x}y|" "Z{}u~}jv~^{|}p~}|V{|}p~}|V{|}p~}|V{|}p~}|V{|}p~}|\"{|}q~y}t{}x~|i{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}g{}" "v~fv~}c{}w~}J{|l~}Vw~}F{}w~|R{}x~|w~Ss~}x{|x~X{|v~|wv~}W{}y~}t{|x~ F{|w~|Fw~}R{|x~y}x~}T{}w~}w{|v~U{}x~}Fw~}R{|" "w~{w~|U{|v~vv~|V{}v~|x{|}v~Y{|s~}x{}x~W{|w~}F{}w~Qw~|w~Ss~}x{|x~X{|v~vv~| H{}w~F{}w~Qw~|}x~|Tv~|w{}w~}O{}w~Xw~}" "Hv~}w{}w~} P{|q~c{}Y~} ix~!y~|N{}r~}\\{}r~}s{|q~|Y{|y~} 5{|}e~} *{}m~|\"v~}R{}x~}vw~}Rw~|tw~|V{|y~|]{}q" "~}k{|w~^{|l~|Q{}x~}J{}w~P{}x~}Ix~ *{}x~}W{}n~|Zy|}p~}W{|}k~}Z{}i~|Nt~}\\{|g~}V{}l~|`{}c~}\\{}l~|X{}n~} e{|l~" "|Ty|y}u~y}|Rt~X{}g~}V{|}j~}d{}g~}|Z{}c~|`{}e~\\{|}i~}|d{}w~}hv~|Y{}w~}M{}w~}W{}w~}l{|u~}a{}w~}V{}t~}i{|s~|h{}t~" "|kv~`{|k~}|\\{}i~}|Z{|k~}|^{}i~}|W{|h~}dZ~g{|v~h{}w~}hv~}d{}v~q{}w~}l{}u~kv~|o{}v~j{|v~|fv~}h{}v~f\\~]{|v~u}U{}" "w~Iu}v~|Qt~| w{}x~} {{w~} `{|w~|#{}o~)w~}Cv~Lv~Tw~}Dv~ Ov| s~x}|Tw~|U{|x}s~| 9{}j~}%{}j~| uq~| x{}l" "~}St~V{}c~|_{}d~}`{|}k~|T{|v~Y{}^~|iv~}r{|v~qv~}c{|k~}| {}v~} t{}w~ t{}u~| i{|l~-v~i{}w~|Xw}|R{|l~X{|v~vv~|W{|" "}o~}|X{|m~| p{|}o~}|X{|l~|U{}r~}!{|n~}U{}n~|Ow~} {{|}j~} N{|r~|R{|n~}1{|r~|g{|w~k{|r~|g{|w~k{}n~iw~$t~Nt~Nt~Nt" "~Nt~P{|r~V[~}d{|}j~}`{}c~|a{}c~|a{}c~|a{}c~|X{}w~}M{}w~}M{}w~}M{}w~}Z{|g~}|]{}t~|kv~`{|k~}|Z{|k~}|Z{|k~}|Z{|k~}" "|Z{|k~}|&{|k~}w{|w~|i{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}fv~}h{}v~b{}w~}K{}j~}W{|w~|H{|w~|R{|x~}{|x~}U{|" "x~}|w~}|{}x~X{|v~|wv~}W{|x~t{}y~} E{}w~G{}x~}Qw~|{}x~|U{}w~}w{|v~Tw~}H{}w~Q{}x~|{|x~}U{|v~vv~|U{}v~|}t~}Y{}x~|{" "}w~y|x~}V{|w~|H{|w~|R{}x~|{|x~}U{}x~}|w~}{|x~}X{|v~vv~| G{}x~}H{|w~|R{}x~|yw~Tv~|w{}w~}P{|w~|Xw~}Hv~}w{}w~} " "P{}w~y|w~|d{|Y~| j{|y~}\"{}x~Oo~}_{|o~}u{|o~}Zw~| 8{}b~} ,{|j~}#v~}R{}x~}vw~}Rw~sw~U{|y~|^{}o~}lw~|_{}k~|Q" "{}x~}Jw~|P{|w~|Jx~ *w~|Xk~|[m~}X{}h~}[{}h~}P{}t~}\\{|g~}X{|j~|`{}c~}^{|i~}[{|j~ gi~|X{|}l~}|V{}t~|Y{}e~|Y{}f" "~}f{}d~}\\{}c~|`{}e~]{}e~}|f{}w~}hv~|Y{}w~}M{}w~}W{}w~}m{|u~|`{}w~}V{}s~|j{}s~|h{}t~}kv~b{|g~}]{}g~}]{|g~}_{}g~" "}Y{}f~dZ~g{|v~h{}w~}h{}v~dv~}q{}w~}lt~|m{|v~mv~}kv~}e{|v~|j{|v~|f\\~]{|w~}O{|w~|D{|w~|Rr~| ww~} w~} `{|w~|${|v~" "}|#w~}Cv~Lv~Tw~}Dv~ Ov~ !{|v~}Nw~|O{|v~} :{|u~}|w{|}v~|'{}i~| r{|}v~} y{}v~}|x{|}v~}U{}t~|W{}c~|_{}d" "~}a{}g~|V{|v~Y{}^~|iv~}r{|v~qv~}e{|g~}\"{}t~} u{}w~ u{}s~| >y~}P{|k~-{|w~}k{|w~}Ww~|S{|k~X{|v~vv~|Y{|}k~}|Z{|y~" "}y|xy|}w~| s{|}k~}|Z{|l~|V{}p~}\"{|y~}|w{|}w~|V{|}|u{|v~P{}x~} {{}h~} N{|~y}y|}x~|S{|v~}|y{|}w~}2{|w~y}x~|g{}x" "~|k{|w~y}x~|g{}x~|kx}|w{|}w~}k{}x~}%{}t~|P{}t~|P{}t~|P{}t~|P{}t~|P{}t~}W{|[~}e{}f~}b{}c~|a{}c~|a{}c~|a{}c~|X{}w" "~}M{}w~}M{}w~}M{}w~}Z{|d~}|`{}t~}kv~b{|g~}]{|g~}]{|g~}]{|g~}]{|g~}){|g~|{|w~|h{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f" "{|v~h{}w~}f{|v~|j{|v~|b{}w~}L{|u~}|w{|}v~|W{|w~|Iw~}Qw~x{}x~|V{}y~}x{}s~|X{|v~|wv~}Vx~}v{|x~| D{}x~}I{}w~Q{}x~|" "xw~U{}w~}w{|v~T{|w~|J{|w~Q{|x~}x{|x~|V{|v~vv~|T{}q~}|Wx~|x{}s~T{|w~I{|w~|R{|x~}x{}x~|Vx~}x{}s~|X{|v~vv~| Fw~}J{" "|w~|R{|x~}x{|x~}Uv~|w{}w~}Q{|w~|Ww~}Hv~}w{}w~} Pw~}y{|x~}cY~ i{}y~|#{|w~}Qm~|`m~}w{|m~|\\{}v~| ;{}`~} -" "{|r~x}t~}$v~}R{}x~}vw~}S{|w~t{|x~}U{|y~|_{|w~}w{}w~|n{}x~}_{|t~w}u~|Q{}x~}K{}w~N{}x~}Jx~ +{|w~Xs~y}s~|\\m~}X{}" "f~\\{}g~}R{|s~}\\{|g~}Y{|i~|`{}c~|_{|s~w}s~}]{|s~x}s~ hr~}r~|[{|f~}Xs~}Y{}d~|\\{|c~}g{}b~|^{}c~|`{}e~_{|a~|g{" "}w~}hv~|Y{}w~}M{}w~}W{}w~}n{|u~|_{}w~}V{}s~}jr~|h{}s~|lv~c{|p~}q~}^{}f~}_{|p~}q~}`{}e~[{}q~}p~dZ~g{|v~h{}w~}h{|" "v~|f{|v~p{|v~m{|t~}m{}w~}m{|v~|m{}v~c{}v~jv~}e\\~]{|w~}Nw~}D{|w~|Sp~| ww~|!w~} `{|w~|${}w~}!w~}Cv~Lv~Tw~}Dv~ " " Ov~ !{}w~}Mw~|N{|v~ :{}v~|s{|v~V{|t}|V{|t~s}w~| p{|v~ {{|v~|t{|v~|Vs~}W{}c~|_{}d~}c{|d~|W{|v~Y{}^~|iv~" "}r{|v~qv~}f{|p~}q~}${}r~} v{}w~ v{}q~| ?y~}Ps~x}u~,v~k{}w~|Ww~|Su~}v|}w~X{|v~vv~|Z{}v~}y|wy|}v~}[{|}q{}x~} t{}" "v~}y|wy|}v~}&{}w~|x{|w~}#y|r{}x~}Kw~|R{|w~ {{}p~}v|x~} H{}x~|S{}w~t{}w~|3x|x{}x~|h{|x~}j{|}|x{}x~|h{|x~}`{|w~l{" "|w~$s~}Ps~}Ps~}Ps~}Ps~}Pr~W{}[~}g{|c~}c{}c~|a{}c~|a{}c~|a{}c~|X{}w~}M{}w~}M{}w~}M{}w~}Z{|b~}a{}s~|lv~c{|p~}q~}_" "{|p~}q~}_{|p~}q~}_{|p~}q~}_{|p~}q~}+{|p~}q~}w~|g{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}e{}v~jv~}a{}w~}Lu~r{" "|v~V{|w~J{}x~}Q{}x~|w{}x~Vx~|w{}u~}Vv|vv|U{}x~}x|}w~ Bw~|K{|w~|R{|x~}w{|x~}Vu|vv|S{|w~K{|w~|Qx~}v{}x~Uv|vv|T{|}" "t~}|Tx~|w{|u~|S{}x~}Jw~}Qw~vw~Vx~|w{}u~}Vv|vv| Dw~|Kw~|Qw~v{}x~|Vv|vv|Pw~|Vw~}Hv|uv| G{|t}|P{|t}|P{|t}|P{|t}|P{" "|t}|Lw~|xw~c{|[~} iy~}\"u~|S{|l~a{}l~|x{}l~]{}t~ ={|^~} .{|u~}|u{|}w~}$v~}R{}x~}vw~}S{}x~}t{}x~}Xy|y}y~y}x" "|cw~}u{}w~o{|w~^u~}t{|}y~|Q{}x~}Kw~|N{|w~|T{}sx~s{} 4{}x~}Y{}v~}|v{}u~\\m~}X{}v~y}|wy|s~]{}x~}x|v{|}t~}Sr~}\\{" "|v~k|Z{|t~}|v{|y}y~|`h|u~^t~|u{|}u~|^u~}|v{|}v~} iv~y|v{|t~]{|o~y}p~|[{|r~|Z{}w~}q|}s~]{|s~}|t{|}u~}g{}w~}r|y" "}q~}_{}w~}h|_{}w~}j|`{|s~}|s{|}t~|g{}w~}hv~|Y{}w~}M{}w~}W{}w~}o{}u~|^{}w~}V{}r~k{|r~|h{}r~lv~d{|t~}|uy|s~_{}w~}" "s|y}t~}a{|t~}|uy|s~a{}w~}s|y}s~]{}u~}|ty|}v~dn|}v~}n|g{|v~h{}w~}gv~}f{}w~}ov~|n{|t~}mv~|l{}v~|o{|v~|bv~}l{}v~dc" "|u~}]{|w~}N{}w~D{|w~|T{}o~| x{|w~!w~} `{|w~|${}w~ w~} >w~}Dv~ Ov~ !{}w~|Mw~|M{}w~ :v~|q{}w~|Xp~}X{}v~|p{|" "}| o{}w~| v~|r{|v~W{|r~|X{}v~}i|^{}w~}h|d{|s~}y|xy|}s~}[{|y}u~y}y|]{}w~}h|v~|iv~}r{|v~qv~}g{|t~}|uy|s~&{}p" "~} w{}w~ w{}o~| @y~}Q{}v~}|u{|}y~,{|w~}m{|w~}Vw~|T{|v~|s{|}~({|w~}|o{|}w~|P{}x~| w{|w~}|o{|}w~|(x~}tw~ rw~K{}x" "~|Rw~ {{}o~}w{|x~} H{}x~|T{|w~r{}x~}-{}x~|hw~|d{}x~|hw~|_{}x~|mw~|%{|r~|R{|r~|R{|r~|R{|r~|R{|r~|R{}r~|Y{|v~|y{|" "v~}h|h{|s~}|t{|}u~}c{}w~}h|`{}w~}h|`{}w~}h|`{}w~}h|W{}w~}M{}w~}M{}w~}M{}w~}Z{|v~r|x}q~b{}r~lv~d{|t~}|uy|s~a{|t~" "}|uy|s~a{|t~}|uy|s~a{|t~}|uy|s~a{|t~}|uy|s~-{|t~}|u{|}q~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}dv~}l{}v~`" "{}w~}M{|v~p{}w~|V{}x~}L{}x~}Q{|x~|ux~}Wx~|v{|w~} {{}q~| Aw~|Lw~|Qw~u{}x~| y{|x~}Lw~|Q{}x~tx~}#{|}r~}Rx~u{|}y~}|" "Q{}x~}L{}x~}Q{}x~|v{|x~}Wx~|v{}w~} j{|w~L{}x~}Q{}x~|u{}x~ x{}x~}Uw~} b{|}p~}|V{|}p~}|V{|}p~}|V{|}p~}|V{|}p~}|" "P{|w~|xx|av~|fv~| j{|y~|#{}t~Sk~|c{|k~}y{|k~}_{|s~} ?{}t~}y| u{|u~|p{}y~}$v~}R{}x~}vw~}Sw~|tw~|[{|}m~}|h{" "|w~sw~|p{}x~|_{}v~|q{|}|Q{}x~}L{}w~Lw~}U{}y~|ux~u{|y~}U{|x}| `w~|Z{|v~}s{|v~}]w~y}y|{}w~}X{}x~|p{|u~|^y}|n{|u~" "|U{}x~y}w~}\\{|w~}K{|u~}o{}|Mv~|_{}v~}q{|u~_{}v~}r{|v~| jy~}|qu~|_{}t~}y|s{|}t~}\\{}w~}w~}Z{}w~}o{|u~}_{|t~|n" "{|}x~}g{}w~}n{|}t~}`{}w~}L{}w~}P{|t~}m{|}w~|g{}w~}hv~|Y{}w~}M{}w~}W{}w~}p{}u~|]{}w~}V{}w~}w~|l{}r~|h{}r~|mv~e{|" "u~}|p{|t~`{}w~}q{|}u~|c{|u~}|p{|t~b{}w~}p{}u~|_{|u~|n{|}y~W{|v~|Z{|v~h{}w~}g{|v~fv~|o{}w~}n{}x~}w~mv~|kv~}ov~}a" "{|v~|n{|v~|M{}v~}\\{|w~}N{|w~|E{|w~|U{}v~}{|u~| x{|x~}\"w~} `{|w~|$v~ w~} >w~}Dv~ Ov~ !v~Lw~|M{}w~| <{|w~" "}p{|w~}Xn~|Zv~ _{|v~ !{|w~}p{}w~}X{}w~}w~}W{}v~|M{}w~}R{|t~|p{|t~|_{|}l~}|`{}w~}hv~|iv~}r{|v~qv~}h{|u~}|p{|" "t~({}n~} x{}w~ x{}m~| Ay~}R{|v~}p{}+{}w~|nv~Uw~|T{}w~| x{|w~|k{|w~|Q{|x~| x{|w~|k{|w~|*{|x~rx~|R{|w}Fw~Kw~|S{}" "x~| {|n~}w{|x~} H{}x~|T{}x~}qw~|.{}x~|i{}x~}c{}x~|i{}x~}^{}x~|n{}x~}${}w~}w~}R{}w~}w~}R{}w~}w~}R{}w~}w~}R{}w~}w" "~}Rv~|w~}Y{}w~}x{|v~U{|t~|n{|}x~}c{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~n{|}s~c{}r~|mv~e{|u~}|p{|" "t~c{|u~}|p{|t~c{|u~}|p{|t~c{|u~}|p{|t~c{|u~}|p{|t~/{|u~}|p{}t~}e{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}d{|v" "~|n{|v~|`{}w~}M{}w~}ow~}U{}x~|N{|w~Px~}t{|x~|Xx|sy| w{}s~| @{|w~M{}x~|Q{}x~|tw~ x{}x~}N{}x~|Q{|x~|t{|x~|&{}t~}v" "~} t{}x~|N{|x~}Q{|x~}t{}x~|Xx|sy| g{|x~}N{|x~}Q{|x~}sx~} {{|x~}Tw~} d{|j~|Z{|j~|Z{|j~|Z{|j~|Z{|j~|R{|w~Z{}w~}" "g{}w~} Ay|J{}y~#{|s~}Tk~}c{}j~|{}j~_q~| A{}u~} q{}v~|n{}~}$v~}R{}x~}vw~}Sw~t{|w~\\{|h~|i{}x~}s{}x~}q{|x~}^" "v~|C{}x~}Lw~}L{}w~V{|v~|wx~w{|v~|V{}w~ a{|w~Yv~}q{|v~|^{}y|u{}w~}Xy}|m{|u~M{|v~}V{|w~|}w~}\\{|w~}Ku~|?{|v~^u~o" "{}v~|a{|v~}p{}v~ j{~|nv~}`u~}|l{|}u~]v~{v~Z{}w~}mu~_u~}j{|y~}g{}w~}l{|}u~}a{}w~}L{}w~}Q{|u~}i{|}y~|g{}w~}hv~|" "Y{}w~}M{}w~}W{}w~}q{}u~|\\{}w~}V{}w~|w~}lw~|v~|h{}q~mv~f{|u~}m{|u~}a{}w~}o{}v~}d{|u~}m{|u~}c{}w~}o{|u~_{}v~|j{|" "W{|v~|Z{|v~h{}w~}fv~|h{}v~n{}w~}nw~|w~|o{|v~j{|v~}q{}v~_{}v~nv~}M{|u~[{|w~}Mw~}E{|w~|V{}v~}x{|u~| vw~} `{|w~|$" "w~} w~} >w~}Dv~ Ov~ !v~Lw~|M{}w~| <{}w~|ow~}Xm~|[v~ ^v~| \"v~|p{|v~Xv~{v~V{}v~|N{}w~}Ru~}l{}u~|b{|g~}" "|b{}w~}hv~|iv~}r{|v~qv~}i{|u~}m{|u~}*{}l~} y{}w~ y{}k~| By~}R{}v~ y{|w~}o{|w~}Uw~|T{}w~ x{|x~}g{}x~|R{|x~} y{|" "x~}g{}x~|+{}y~}r{}y~}R{}w~Fx~}M{|}w~ Mm~}w{|x~} H{}x~|Tw~p{}x~|.{}x~|j{|w~b{}x~|j{|w~]w~n{|w~#v~{v~Rv~{v~Rv~{v~" "Rv~{v~Rv~{v~S{|w~}{}w~|Zv~|x{|v~Uu~}j{|y~}c{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~k{}t~d{}q~mv~f{|" "u~}m{|u~}e{|u~}m{|u~}e{|u~}m{|u~}e{|u~}m{|u~}e{|u~}m{|u~}1{|u~}m{|u~}e{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w" "~}c{}v~nv~}_{}w~}Mv~n{}w~Tw}N{|x}P{|x}r{|x} F{|}x~}| ={|x}|O{|x}|Px}|s{|x}| xw|Nw|Pw|rw|'{|v~}|y{|v~} tw}Nw}P{|" "x}rx}| 6w|Nw|Ox|rw| Nw~} e{}h~}\\{}h~}\\{}h~}\\{}h~}\\{}h~}S{|w~Z{|v~gv~| Ay~}L{|y~}${|q~}V{|j~ci~}|i~|a{}p~|" "Oy|Uw|jw|Vu|Wv|kw|b{}v~} p{|v~|l{|}$v~}R{}x~}vw~}T{|x~}t{|x~}]{|g~|i{}x~|s{|w~qw~|^v~B{}x~}M{|w~|L{|w~}V{|}" "w~}xx~x{}w~}|U{}w~ a{}w~Z{|v~o{}w~}U{}w~}X{|j{}v~|M{}v~Vw~}{}w~}\\{|w~}L{|v~|>v~}_{|v~|nv~}a{}v~nv~| \\{}w~}" "b{|u~|h{|}v~|`{|w~}{}w~|[{}w~}m{|v~|a{}v~}gy}g{}w~}j{}u~|b{}w~}L{}w~}Q{}v~}f{|~|g{}w~}hv~|Y{}w~}M{}w~}W{}w~}r{}" "u~|[{}w~}V{}w~y|w~m{|w~{v~|h{}w~}v~|nv~f{}v~}ju~|b{}w~}nu~d{}v~}ju~|d{}w~}n{}v~|`v~}D{|v~|Z{|v~h{}w~}f{}w~}hv~}" "n{|v~o{|w~{}x~}o{}w~}i{}v~|s{|v~|^v~}p{}v~M{|u~|[{|w~}M{}x~}E{|w~|W{}v~|v{|u~| ww~} `{|w~|$w~} w~} >w~}Dv~ " "Ov~ !v~Lw~|M{|w~| <{}w~|ow~}Xy~}w|}t~[v~| _{}w~} #{|w~}n{}w~|Z{|w~}{}w~|Vu~|O{}w~}S{}v~}j{}u~c{}d~|c{}w~" "}hv~|iv~}r{|v~qv~}i{}v~}ju~|,{}v~y}w~|v~} {{}w~ {{}v~y}w~|u~| Cy~}R{}w~}R{|ey|_{}w~|pv~Tw~|T{}w~ y{|x~}e{}x~|\\" "{|}p~} {{|x~}e{}x~|,{}y~}r{}y~}R{}w~G{}x~|Rq~| N{|m~}w{|x~} H{}x~|U{|w~p{|x~}.{}x~|j{}x~|b{}x~|j{}x~|_{|w~|n{}" "x~|${|w~}{}w~|T{|w~}{}w~|T{|w~}{}w~|T{|w~}{}w~|T{|w~}{}w~|T{}w~|{|w~}[{|v~w{|v~V{}v~}gy}c{}w~}M{}w~}M{}w~}M{}w~" "}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~j{|u~}e{}w~}v~|nv~f{}v~}ju~|f{}v~}ju~|f{}v~}ju~|f{}v~}ju~|f{}v~}ju~|c{}d{}|d{}v~}" "k{}u~|f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}bv~}p{}v~^{}m~y}|Yv~o{|}w~ Py~}|u{|v~} 2w~} f{" "}u~}x|{x|}t~^{}u~}x|{x|}t~^{}u~}x|{x|}t~^{}u~}x|{x|}t~^{}u~}x|{x|}t~T{|w~Yv~|i{|v~ A{}x~}M{}y~|$o~|W{|j~ch~}i~}" "b{}n~T{|}t~y}|Zw~}kw~}X{}u~|X{}w~|m{}w~|d{|v~| ov~}j{|$v~}R{}x~}vw~}T{}x~}t{}x~}]u~}|{|y~|y{|y}x~|iw~|rw~r{" "}x~}]v~B{}x~}Mv~Jv~T{|}w~|{x~{|w~}|S{}w~ aw~}Z{}w~}o{|v~U{}w~}Ev~}M{|v~W{}w~y{}w~}\\{|w~}Lv~}>{|v~|_{|v~m{}w~}" "av~|n{|v~ 8{|y}6{|~|4{}v~c{|v~}d{|v~`{}w~|{|w~}[{}w~}lv~|b{|v~}e{|g{}w~}i{}u~b{}w~}L{}w~}R{|v~}dy|g{}w~}hv~|Y{}" "w~}M{}w~}W{}w~}s{}u~Y{}w~}V{}w~|{w~|nw~}{v~|h{}w~y|v~nv~g{|v~}i{|u~b{}w~}n{|v~|f{|v~}i{|u~d{}w~}n{|v~|a{|v~C{|v" "~|Z{|v~h{}w~}f{|v~|j{|v~|mv~|p{|w~{|x~}ov~|hv~}sv~}]{|v~|r{|v~|Mu~|Z{|w~}M{|w~E{|w~|X{}v~|t{|u~| xw~} `{|w~|$w" "~} w~} >w~}Dv~ Ov~ !w~}Lw~|M{|w~| <v~nw~}X{|s{}v~}\\{}v~| `{|v~ #{}w~|n{|w~}Z{}w~|{|w~}Uu~|P{}w~}T{|u" "~h{}v~}f{|r~y}v~}r~}d{}w~}hv~|iv~}r{|v~qv~}j{|v~}i{|u~-{}v~}{}w~{|v~} {}w~ {}v~}{}w~{|u~ Cy~}Rv~|S{}~}g{|y~|_v~" "q{}w~|Tw~|T{}w~| {{x~}t{|y}u~}|u{}x~^{}m~} {{x~}wq}y|s{}x~,{}y~}r{}y~}R{}w~H{|x~}Qs~} L{}m~}w{|x~} H{}x~|U{|x~" "}p{|x~}.{}x~|k{|x~}a{}x~|k{|w~cx}u~|n{|x~}#{}w~|{|w~}T{}w~|{|w~}T{}w~|{|w~}T{}w~|{|w~}T{}w~|{|w~}Tv~xv~[v~}w{|v" "~W{|v~}e{|c{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~i{|u~|f{}w~y|v~nv~g{|v~}i{|u~g{|v~}i{|u~g{|v~}i{" "|u~g{|v~}i{|u~g{|v~}i{|u~d{}y~f{}y~|f{|v~}k{|s~f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}b{|v~|r{|v~|^{}i~}|" "\\v~q{}t~| F{}v~| C{~| mw~} gu~}p{}u~|au~}p{}u~|au~}p{}u~|au~}p{}u~|au~}p{}u~|V{|w~Y{}w~}i{}w~} B{" "}w~}Mx~${}n~W{|k~}d{|U~}c{|m~}W{|n~}[w~}kw~}Xt~}X{|w~}mv~cv~| o{|v~| mv~}R{}x~}vw~}Tw~|tw~|^{}v~|x{|y~|u{|~" "|iw~|rw~s{|w~\\v~B{}x~}N{|w~}J{}w~|S{|n~|Q{}w~ b{|w~|Zv~|nv~|V{}w~}E{}w~}M{|v~X{|w~|y{}w~}\\{|w~}M{|v~={}v~^{|" "v~m{}w~}b{|v~lv~| <{|}x~}6{|x~}|7{}w~}cv~|b{|w~}b{|v~xv~[{}w~}l{}w~}bu~|P{}w~}h{}v~}c{}w~}L{}w~}Ru~M{}w~}hv~|Y{" "}w~}M{}w~}W{}w~}t{}u~X{}w~}V{}w~|{}x~}o{|w~|{v~|h{}w~|{v~}ov~gu~|h{}v~|c{}w~}mv~}fu~|h{}v~|e{}w~}mv~}a{|v~C{|v~" "|Z{|v~h{}w~}ev~}j{}v~l{}w~}p{}x~}{|w~ov~|h{|v~}u{}v~[{}v~rv~}M{}v~}Y{|w~}Lw~|F{|w~|Y{}v~|qu~| Kt|Uw~}uu|Mt|Ru|u" "{|w~|Wt|Ow~}Mu|Tw~}uu| Jw~}Dv~Tu|mv|Vu|Pt|Ku|Qu|Bv|Us|Rv~ !w~}Lw~|M{|w~| iv|Sv~o{|w~}N{}v~\\{|t~}|Is|Mu| u{}" "w~| Zt| Lv~|n{|v~[{|v~xv~Tu~P{}w~}T{}v~|gu~g{|t~}|y{|v~x{}t~}e{}w~}hv~|iv~}r{|v~qv~}ju~|h{}v~|/{}v~}y{}w~y{|v" "~}!{}w~!{}v~}y{}w~y{|u~ F{|}y~}x|V{|v~S{}x~}i{|w~|`{}w~|rw~}Sw~|T{|v~|!{}y~}u{|n~}v{}y~}a{|k~} {}y~}vn~}t{}y~}" "-{}y~}r{}y~}R{}w~I{|w~Pt~}| L{}m~}w{|x~} H{}x~|U{|x~}p{|w~.{}x~|kw~|a{}x~|kw~|ct~}lw~|${|v~xv~U{|v~xv~U{|v~xv~U" "{|v~xv~U{|v~xv~U{|w~}x{}w~|]{|v~v{|v~Wu~|L{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~h{|v~}f{}w~|{v~}o" "v~gu~|h{}v~|hu~|h{}v~|hu~|h{}v~|hu~|h{}v~|hu~|h{}v~|f{}w~h{}w~|gu~|l{|r~|g{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~" "h{}w~}a{}v~rv~}]{}g~}]w~}s{|r~|Xt|Nt|Nt|Nt|Nt|Nt|Xt|lu|Ut|Pt|Nt|Nt|Nt| 0{}v~|Pu|Pt|Nt|Nt|Nt|Nt| ut|t{}y~} nw" "~}uu| t{}w~}|wv|v{}v~b{}w~}|m{}v~b{}w~}|m{}v~b{}w~}|m{}v~b{}w~}|m{}v~V{|w~Xv~iv~| C{|v~M{|y~}%{}m~}Wk~}d{|U~}d" "{|k~}Y{}k~|]w~}kw~}Y{|s~X{|v~n{|w~}d{}w~} n{}w~} lv~}R{}x~}vw~}U{|w~t{|w~]v~|w{|y~|`w~|rw~s{}x~|\\v~|C{}x~}" "N{}w~|J{|w~}Q{|r~|O{}w~ b{}w~Z{|v~m{}w~}V{}w~}E{}w~}M{|v~Xw~}x{}w~}\\{|w~}M{}w~}=v~}^{|v~m{}w~}b{|v~lv~} ?{|}u" "~}6{|u~}|:{}w~}d{}w~|`{|w~}c{}w~|x{}w~}\\{}w~}l{}w~}c{|v~}O{}w~}gu~c{}w~}L{}w~}S{|v~}M{}w~}hv~|Y{}w~}M{}w~}W{}w" "~}uu~}W{}w~}V{}w~|{|w~|p{}w~yv~|h{}w~|{|v~ov~h{|v~}fu~c{}w~}mv~}g{|v~}fu~e{}w~}mv~}a{|v~C{|v~|Z{|v~h{}w~}e{}v~j" "v~|l{}w~}pw~|yw~|q{|v~f{}v~|w{|v~|Zv~}t{}v~M{}v~}X{|w~}L{}x~}F{|w~|Z{}v~|o{}v~| P{|}q~}|Xw~}w{}s~}|S{|}q~}|X{}s" "~}|x{|w~|Z{|}r~}|W{}k~}W{}s~}|x{|w~|`w~}w{|s~}|Rv~Lv~Tw~}n{|v~}Xv~_w~}w{}s~}r{|s~}cw~}w{|s~}|V{|}r~}|Yw~}w{}s~}" "|V{}s~}|x{|w~|Zw~}w{}t~|Y{}o~}|Z{}i~]{|w~|m{}w~|c{|v~iv~i{}w~|pu~ow~}hv~}m{|v~|d{|v~iv~`d~Uw~}Lw~|M{|w~| l{|s~" "}|u{}x~}av~o{|w~}M{}w~|\\{}q~}|P{}o~}|\\w~}w{|s~}|^x~y}hv~W{}w~}X{|w~|m{}w~|d{}w~}h{}w~}]{|y}w{|}x~}|]_~|dv~t{}" "w~t{|w~}[{|q~}|U{|y}i~}f{|`~b{|v~lv~|\\{}w~|x{}w~}U{|u~Q{}w~}U{|v~}f{|v~|ht~|w{|v~v{}u~}f{}w~}hv~|iv~}r{|v~qv~}" "k{|v~}fu~/{|w~}x{}w~x{|w~}I{|T{}w~S{|i{|\\w~}x{}w~x{|w~|!v~}O{|}p~}|Y{|v~T{|v~}k{|v~}_v~s{}w~|Sw~|Su~|#{|x~u{}l" "~ux~|bv~}y|v{|x~} !{|x~ul~|ux~|.{|x~|t{|x~|R{}w~J{|w~|L{|}x~}&{|w~|m{}w~|a{}m~}w{|x~} H{}x~|U{|x~}p{|w~.{}x~|l{" "}x~}`{}x~|l{}x~}br~|o{}x~}Qv~|S{}w~|x{}w~}V{}w~|x{}w~}V{}w~|x{}w~}V{}w~|x{}w~}V{}w~|x{}w~}V{}w~|x{|w~}]{}w~}v{|" "v~X{|v~}K{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~gu~|g{}w~|{|v~ov~h{|v~}fu~i{|v~}fu~i{|v~}fu~i{|v~}" "fu~i{|v~}fu~g{|u~j{}v~}h{|v~}l{|w~}v~}g{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}`v~}t{}v~\\{}f~}^w~}t{}v~}y|Y" "{|}q~}|U{|}q~}|U{|}q~}|U{|}q~}|U{|}q~}|U{|}q~}|_{|}q~}|r{|}r~}[{|}q~}|W{|}r~}|T{|}r~}|T{|}r~}|T{|}r~}|Qv~Lv~Lv~" "Lv~O{|y}w~}u~|\\w~}w{|s~}|V{|}r~}|T{|}r~}|T{|}r~}|T{|}r~}|T{|}r~}|Q{}u~Q{|}r~}|x{}x~}b{|w~|m{}w~|a{|w~|m{}w~|a{" "|w~|m{}w~|a{|w~|m{}w~|c{|v~iv~aw~}w{}s~}|^{|v~iv~ W{}w~}u{}w~u{}w~}d{}w~}j{}w~}d{}w~}j{}w~}d{}w~}j{}w~}d{}w~}j{" "}w~}W{}w~X{}w~}k{|v~ C{|v~|M{}y~|&{|k~}X{}l~|cU~}di~|[{}i~|^w~}kw~}Y{}s~|Xv~|o{}w~|dw~} mv~| lv~}R{}x~}vw~}" "^{}Z~f{|w~}v{|y~|`w~|rw~t{|x~}[{}w~}C{}x~}Nv~Hv~O{}v~}M{}w~ bw~}Z{}w~}m{|v~V{}w~}E{}w~}M{|v~Y{}w~w{}w~}\\{|w~}" "Mv~|>{|v~]{|v~m{}w~}b{|w~}l{}w~}W{|v}M{}v~D{}r~}6{|r~}|>{|v~|e{}w~|^{|w~|dv~w{|v~\\{}w~}lv~|c{}v~N{}w~}g{}v~|d{" "}w~}L{}w~}S{}v~L{}w~}hv~|Y{}w~}M{}w~}W{}w~}vu~}V{}w~}V{}w~|yw~}pw~}yv~|h{}w~|y{}w~}pv~h{}v~e{}v~|d{}w~}mv~}g{}v" "~e{}v~|f{}w~}mv~}a{|v~C{|v~|Z{|v~h{}w~}dv~|l{|v~k{|v~q{|w~x{}x~}q{}w~}e{}v~wv~}Y{|v~|v{|v~|N{|v~}W{|w~}L{|w~F{|" "w~|[{}v~l{}v~ S{|}k~|Zw~}y{|o~}V{|k~|\\{|o~}y{|w~|\\{|m~}X{}k~}Y{|o~}y{|w~|`w~}y{|o~}Sv~Lv~Tw~}o{|v~}Wv~_w~}y{|" "o~|v{|o~|ew~}y{|o~}Y{|}n~}|[w~}y{|o~}Y{|o~}y{|w~|Zw~}y{|r~|[{}j~[{}i~]{|w~|m{}w~|b{}w~|k{|w~}i{|w~}q{|u~|q{|w~|" "h{|v~|o{|v~}b{}w~|k{|w~}`d~Uw~}Lw~|M{|w~| n{|o~}vw~|av~o{}w~|M{|v~[{|o~}|U{}k~}]w~}y{|o~}_u~|k{|w~}Wu~X{|w~|m{" "}w~|dv~|h{|v~_{}x~}x{}s~}__~|dv~t{}w~t{|w~}\\{}n~}Y{|}e~}f{|`~b{|w~}l{}w~|\\v~w{|v~T{|u~R{}w~}U{}v~dv~}i{}u~u{|" "v~u{|u~|g{}w~}hv~|iv~}r{|v~qv~|k{}v~e{}v~|c{~}I{|y~}w{}w~w{|y~}I{}~|U{}w~T{}~|k{}~|\\y~}w{}w~w{|y~| v~}P{}k~Z{|" "v~S{|v~}x{|}v~}|y{|v~}^{|w~}u{|w~}Rw~|S{|u~}${}y~|v{}v~}|wy|}y~u{|y~}c{|x~}r{|x~}Q{|q{| W{}y~|uw~vy|v~u{|y~}-w~" "|v{|w~Q{}w~K{|w~|I{|w~'{|w~|m{}w~|a{}m~}w{|x~} H{}x~|U{|x~}p{|x~}]{|q{|X{}x~|m{|w~_{}x~|m{|w~]{|}w~}q{|w~Pv~|Sv" "~w{|v~Vv~w{|v~Vv~w{|v~Vv~w{|v~Vv~w{|v~W{|v~vv~^{|v~|v{|v~X{}v~J{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z" "{|v~g{|v~}g{}w~|y{}w~}pv~h{}v~e{}v~|j{}v~e{}v~|j{}v~e{}v~|j{}v~e{}v~|j{}v~e{}v~|g{|u~l{}v~}g{}v~kw~}{}v~g{|v~h{" "}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}`{|v~|v{|v~|\\{}w~}s|y}t~}_w~}u{|v~|Y{|}k~|Z{|}k~|Z{|}k~|Z{|}k~|Z{|}k~|Z{|" "}k~|d{|}k~|v{|m~}_{|k~|[{|m~}W{|m~}W{|m~}W{|m~}Rv~Lv~Lv~Lv~Q{|}l~\\w~}y{|o~}Y{|}n~}|X{|}n~}|X{|}n~}|X{|}n~}|X{|" "}n~}|S{}u~S{|}n~}{|x~}a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|b{}w~|k{|w~}aw~}y{|o~}^{}w~|k{|w~} X{|w~}" "t{}w~t{|w~}f{|w~}h{|w~}f{|w~}yy|p{|}y{|w~}f{|w~}ly|y{|w~}f{|w~}h{|w~}X{}x~}X{|v~kv~| Cv~|Lx~&{|i~|Y{|m~}bU~|e{}" "h~\\{|u~}|xy|}u~^w~}kw~}Yr~}X{}w~}ov~d{}w~ lv~| lv~}R{}x~}vw~}^{}Z~f{|w~|v{|y~|`w~|s{|w~tw~|[{|v~|D{}x~}Nw~" "}H{}w~|Q{|t~|N{}w~ c{|w~|Zv~|lv~|W{}w~}E{}w~}M{}w~}Z{|w~|w{}w~}\\{|w~}N{|v~={}w~}\\v~|nv~|b{}w~}l{}v~W{}v~M{}v" "~G{|}p~|6{|o~}@u~e{|w~|\\{}w~e{|w~}v{}w~|]{}w~}m{|v~|cv~}N{}w~}g{|v~}d{}w~}L{}w~}Sv~}L{}w~}hv~|Y{}w~}M{}w~}W{}w" "~}x{|u~}U{}w~}V{}w~|y{}w~q{|w~|yv~|h{}w~|y{|v~pv~hv~}e{|v~}d{}w~}mv~}gv~}e{|v~}f{}w~}mv~}a{|v~|D{|v~|Z{|v~h{}w~" "}d{}w~}l{}w~}jv~|r{|w~x{|x~}qv~|e{|v~}y{}v~W{}v~vv~}N{|u~V{|w~}Kw~|G{|w~|\\{}w~}j{}v~ T{}i~}[w~}{}m~}X{}j~|]{}m" "~}{|w~|]{}j~Y{}k~}Z{}m~}{|w~|`w~}{|l~Tv~Lv~Tw~}p{}v~}Vv~_w~}{|m~|x{|m~|fw~}{|m~}[{|j~|\\w~}{}m~}[{}m~}{|w~|Zw~}" "{|q~|\\{}i~[{}i~]{|w~|m{}w~|b{|w~}k{}w~|hw~}q{|u~}q{}w~|g{}v~ov~}a{|w~}k{}w~|`d~Uw~}Lw~|M{|w~| Gy|l{|Z{}m~}x{|w" "~`v~p{|v~Kv~Z{|m~|X{}j~}]w~}{|l~`t~|l{}w~|X{|u~}Y{|w~|m{}w~|e{}v~f{}w~}b{|v~}y{|q~}`_~|dv~t{}w~t{|w~}^{|k~}[{|c" "~}f{|`~b{}w~}l{}w~}]{|w~}vv~|T{|v~}S{}w~}Uv~}d{}v~j{|u~t{|v~t{|u~g{}w~}hv~|iv~}r{|v~r{|v~|kv~}e{|v~}dx~}I{|}v{}" "w~v{|}I{}x~|V{}w~U{}x~|m{}x~|\\{|v{}w~vy| {{v~}R{|i~Z{|v~R{|v~}|q~}|v~}\\v~u{}w~Qw~|R{|t~|'{|y~}v{}w~}p{|t{}y~|" "d{}x~|r{|x~}Ry}r{|~ X{|y~}tw~sw~|u{}y~|.{|w~}x|}w~|Q{}w~L{|w~|G{|x~}({|w~|m{}w~|a{}m~}w{|x~} H{}x~|U{|w~p{|x~}]" "{~|r{|}Y{}x~|mw~|_{}x~|m{}x~|[{|w~|r{}x~|Pv~|T{|w~}v{}w~|X{|w~}v{}w~|X{|w~}v{}w~|X{|w~}v{}w~|X{|w~}v{}w~|X{}w~}" "v{}w~}_{}w~}u{|v~Xv~}J{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~fu~g{}w~|y{|v~pv~hv~}e{|v~}jv~}e{|v~}" "jv~}e{|v~}jv~}e{|v~}jv~}e{|v~}f{|u~n{}v~}fv~}l{}x~}y{|v~|h{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}_{}v~vv~}[" "{}w~}q{|}u~|`w~}uv~W{}i~}[{}i~}[{}i~}[{}i~}[{}i~}[{}i~}e{}i~}x{}k~}a{}j~|\\{}j~Y{}j~Y{}j~Y{}j~Sv~Lv~Lv~Lv~R{}j~" "}]w~}{|m~}[{|j~|Z{|j~|Z{|j~|Z{|j~|Z{|j~|T{}u~T{|f~`{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|b{|w~}k{}w~|a" "w~}{}m~}_{|w~}k{}w~| Xw~}s{}w~s{}w~fw~}f{}w~fw~}y{|y~|r{|y~}y{}w~fw~}l{|y~}y{}w~fw~}f{}w~X{}x~}Wv~|m{|v~ C{}w~}" "[{|}|o{|y~|&g~|Y{}n~|b{}V~e{|g~}]v~}r{|v~}_w~}kw~}Z{|r~}X{|v~p{|w~}dw~} pw|v~l| {{v~}R{}x~}vw~}^{}Z~f{|w~|v" "{|y~|`{}x~}s{|x~}u{}x~}Y{}v~|E{}x~}O{|w~}H{}w~|S{|}r~}|P{}w~ c{|w~Yv~|lv~|W{}w~}Ev~|N{|v~|Zw~}v{}w~}\\{|w~}|}v" "~y}|X{}w~}>{|v~|\\{}w~}o{|v~a{}w~}l{}v~W{}v~M{}v~J{|}p~}|2{|}p~}|D{}v~|e{}x~}p{|}w~}|vx|uw~|f{}w~|v{|w~}]{}w~}m" "{}v~c{|v~|N{}w~}fv~}d{}w~}L{}w~}T{|v~|L{}w~}hv~|Y{}w~}M{}w~}W{}w~}y{|u~}T{}w~}V{}w~|y{|w~|r{}x~}xv~|h{}w~|x{}w~" "}qv~i{|v~|dv~}d{}w~}mv~}h{|v~|dv~}f{}w~}n{|v~|`u~D{|v~|Z{|v~h{}w~}d{|v~m{|v~|j{}w~}r{}x~}x{|w~qv~|d{}v~y|v~|Vv~" "}x{}v~Mu~|V{|w~}K{}x~}G{|w~|]{}w~}h{|v~ U{}u~v}s~}\\w~}|v~w}t~}Zr~v}v~|^{}t~w}v~}|w~|^{}t~v}t~Zv}v~s}[{}t~w}v~}" "|w~|`w~}|u~x}t~}Uv~Lv~Tw~}q{}v~|Uv~_w~}|v~x}s~y{|v~x}s~fw~}|u~x}t~}]{|s~x}s~|]w~}|v~w}t~}]{|t~w}v~}|w~|Zw~}|t~}" "x~|]{}t~u}u~[{|x}v~q}]{|w~|m{}w~|av~kv~g{}w~q{}t~qv~e{}v~q{}v~_v~|m{|v~_d~Uw~}Lw~|M{|w~| J{|}v~}r{}v~}|_{}u~w}u" "~|y{}x~}`v~q{|v~}K{}w~|\\{}w~}p~}Z{}s~w}u~}]w~}|u~x}t~}as~m{|v~W{}t~Y{|w~|m{}w~|ev~|f{|v~c{|u~}yn~a_~|dv~t{}w~t" "{|w~}_{|t~w}t~}]{|b~}f{|`~b{}w~|l{}w~}]{}w~|v{|w~}S{|v~}T{}w~}Uv~|d{|v~|k{}v~|t{|v~s{}v~|h{}w~}hv~|i{}w~}r{|v~r" "{|v~|l{|v~|dv~}ev~}C{}w~C{}v~|W{}w~V{}v~n{|v~|W{}w~ sv~}S{|s~}y~x}v~Z{|v~Q{|e~}[{|w~}w{|w~}Qw~|R{}r~|){}y~|w{|w" "~}g{|y~}dw~q{}x~}S{}~}s{}y~ X{}y~|tw~s{}x~}u{|y~}-{}p~}P{}w~M{|w~|F{|x~}({|w~|m{}w~|a{}m~}w{|x~} H{}x~|Tw~p{}x~" "|]y~}s{|y~Z{}x~|n{|x~}^{}x~|n{|w~Y{|x~}s{|x~}Ov~|T{}w~|v{|w~}X{}w~|v{|w~}X{}w~|v{|w~}X{}w~|v{|w~}X{}w~|v{|w~}Xv" "~u{|v~_v~|u{|v~Y{|v~|J{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~f{}v~g{}w~|x{}w~}qv~i{|v~|dv~}k{|v~|d" "v~}k{|v~|dv~}k{|v~|dv~}k{|v~|dv~}e{|u~p{}v~}f{|v~|m{}w~wv~}h{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}^v~}x{}v" "~Z{}w~}o{}v~}`w~}v{|w~|W{}u~v}s~}\\{}u~v}s~}\\{}u~v}s~}\\{}u~v}s~}\\{}u~v}s~}\\{}u~v}s~}f{}u~v}s~}{s~w}t~}cr~v}" "v~|]{}t~v}t~[{}t~v}t~[{}t~v}t~[{}t~v}t~Tv~Lv~Lv~Lv~S{}h~|^w~}|u~x}t~}]{|s~x}s~|\\{|s~x}s~|\\{|s~x}s~|\\{|s~x}s~" "|\\{|s~x}s~|U{}u~U{|s~x}q~|`{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|av~|m{|v~`w~}|v~w}t~}_v~|m{|v~ X{|w~" "r{}w~rw~}h{|w~dw~}h{|w~y{|w~|t{|w~}yw~}h{|w~l{|w~}yw~}h{|w~dw~}Y{}x~}W{}w~}m{}w~} Xg|}v~s|e{|}x~}o{}y~&{}f~Y{|o" "~}a{|V~f{|e~}_{|w~}p{|v~_w~}kw~}Z{}w~}v~Wv~|q{}w~}e{|w~ pc~} {{v~}R{|x}|v{|x}|^{}Z~f{|w~|v{|y~|`{|w~s{}x~}v" "{|w~Wu~|F{|x}|O{}w~|H{|w~}U{|}w~|x~|w~}|R{}w~ c{}x~}Yv~|lv~|W{}w~}F{|v~N{|v~}Z{}w~u{}w~}\\{|k~}Z{}w~}x{|}u~y}|" "L{}v~Zv~|pv~}a{|v~l{}v~|X{}v~M{}v~M{|}p~}|,{|}p~}|H{}v~|e{|w~q{|q~}y{}x~|v{|x~}fv~tv~]{}w~}n{}v~|c{|v~|N{}w~}f{" "}v~d{}w~}L{}w~}T{}v~|L{}w~}hv~|Y{}w~}M{}w~}W{}w~}{|u~}S{}w~}V{}w~|xw~}rw~|xv~|h{}w~|x{|v~|rv~i{|v~|d{}v~d{}w~}n" "{|v~|h{|v~|d{}v~f{}w~}n{}v~|`{}v~}|F{|v~|Z{|v~h{}w~}cv~|n{}v~i{}w~}rw~|ww~|s{|v~b{}q~}U{|v~|{|v~|N{}v~|U{|w~}K{" "|w~G{|w~|^{}w~}f{|v~ V{}y~}|r{|u~|]r~|u{|u~}\\{}u~}s{|}y~|_{|u~|u{|}s~|_{}v~}|t{}v~}Vw~}T{|u~|u{|}s~|`r~|u{|u~|" "Vv~Lv~Tw~}ru~|Tv~_r~|v{|}v~}{w~|u{}v~}gr~|u{|u~|^u~}|v{|}u~]r~|u{|u~|_{|u~|u{|}s~|Zr~}|v{|\\v~}|r{|}y~Wv~S{|w~|" "m{}w~|a{}w~|m{|w~}g{}w~|rs~qw~}dv~}s{|v~|_{}w~}m{}w~|Nu~Uw~}Lw~|M{|w~| K{}r~u{|r~}a{|v~}|v{}v~yw~|`v~r{|u~|K{|w" "~|]{}w~|xy|}t~}[u~}|s{|}~}]r~|u{|u~|ay|v~|n{}w~|X{|s~|Z{|w~|m{}w~|f{|v~dv~|e{|u~}|{|v~y|}v~}bx}u~q}u~x}|dv~t{}w" "~t{|w~}_u~|u{|u~|_{|u~}|v{|}t~v}f{|q}u~p}b{}w~|l{|v~]v~tv~R{}v~}U{}w~}V{|v~|cv~}l{|v~}s{|v~s{|v~}h{}w~}hv~|i{}v" "~r{|v~r{|v~|l{|v~|d{}v~fu~|C{}w~C{|u~|X{}w~W{}v~}m{}v~|X{}w~ sv~}T{|u~}|yy~}x{|}y~Z{|v~P{|g~}Y{}w~|xv~Pw~|T{|v~" "}u~}*x~v{}w~ex~dw~qw~}U{|x~}t{}x~ Xx~sw~s{}x~}tx~,{|r~|O{}w~N{|w~|Dw~({|w~|m{}w~|a{|m~}w{|x~} H{}x~|T{}x~}qw~|]" "x~}t{|x~|\\{}x~|nw~]{}x~|nw~|Xw~sw~|Ov~|Tv~tv~Xv~tv~Xv~tv~Xv~tv~Xv~tv~Y{|w~}tv~|a{|v~t{|v~Y{|v~|J{}w~}M{}w~}M{}" "w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~f{|v~|h{}w~|x{|v~|rv~i{|v~|d{}v~k{|v~|d{}v~k{|v~|d{}v~k{|v~|d{}v~k{|v~|d{" "}v~d{|u~r{}v~}e{|v~|n{}w~v{}v~h{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}^{|v~|{|v~|Z{}w~}nu~`w~}v{}w~V{}y~}|r" "{|u~|]{}y~}|r{|u~|]{}y~}|r{|u~|]{}y~}|r{|u~|]{}y~}|r{|u~|]{}y~}|r{|u~|g{}y~}|r{|o~}|u{|}v~}e{}u~}s{|}y~|^{}v~}|" "t{}v~}]{}v~}|t{}v~}]{}v~}|t{}v~}]{}v~}|t{}v~}Uv~Lv~Lv~Lv~T{}u~}|v{|}v~}^r~|u{|u~|^u~}|v{|}u~\\u~}|v{|}u~\\u~}|v" "{|}u~\\u~}|v{|}u~\\u~}|v{|}u~U{}u~Uu~}|u{}u~|_{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|a{}w~}m{}w~|`r~|u{" "|u~|`{}w~}m{}w~| Xw~|r{}w~r{|w~hw~|d{|w~hw~|yu~|v{|u~y{|w~hw~|m{|u~y{|w~hw~|d{|w~Y{}x~}Vv~mv~| XZ~}g{}t~oy~}'{}" "e~}Y{}p~_W~|fc~|`v~n{}w~|`w~}kw~}Zv~|}w~|X{}w~}qv~|e{}x~} q{|c~| {{v~} y{|x~}t{}x~}]{|w~}v{|y~|_w~|u{|w~|vw" "~|Wt~ p{}w~|H{|v~V{}w~}yx~y{}w~}S{}w~ cw~|Z{|v~k{}w~}W{}w~}Fv~}Qy|u~}Z{|w~|u{}w~}\\{|i~|\\v~|y{}p~}|Nv~}Z{|v~|" "s{|v~}`{|v~lu~|X{}v~M{}v~P{|}p~}|b{|Z~}b{|}p~}|L{}v~}d{}x~|r{|n~{}x~|uw~|h{}w~}t{}w~|^{}w~}q{|}u~}b{}v~M{}w~}f{" "}v~d{}w~}L{}w~}T{}v~K{}w~}hv~|Y{}w~}M{}w~}W{}w~}|u~}R{}w~}V{}w~|x{|w~s{}w~wv~|h{}w~|w{}w~}rv~i{}v~c{}v~d{}w~}n{" "}v~|h{}v~c{}v~f{}w~}o{|u~_{|t~}|H{|v~|Z{|v~h{}w~}c{}v~nv~}i{|v~s{|w~|w{}x~}s{}w~}b{|q~S{}v~|v~}N{}v~}T{|w~}K{|w" "~|H{|w~| s{}|m{}w~}]t~}q{}v~|^{}v~}ny|_u~q{}t~|`{|v~|q{|v~|Ww~}Tu~q{|t~|`t~}r{|v~}Vv~Lv~Tw~}t{|u~Rv~_t~}r{}v~}" "y~}r{}v~gt~}r{|v~}_{}v~|r{|v~}^s~q{}v~_{}v~|r{}t~|Zs~T{|w~}m{|Wv~S{|w~|m{}w~|a{|w~}mv~|g{|w~}s{|s~|s{|w~|d{|v~|" "u{|v~}]v~mv~N{}v~Tw~}Lw~|M{|w~| L{}p~w{|p~}bv~}s{}w~y|w~_v~wx|}t~}J{|w~}^{}w~r{}u~|]{|v~|Ot~}r{|v~}_{|v~nv~W{}s" "~}Z{|w~|m{}w~|f{}w~}d{}w~}eu~}x{|w~|x{}v~|`{|w~}q{|w~}`v~t{}w~t{|w~}`{}v~q{}v~_u~}r{|v~}V{|w~}Wv~|l{|v~^{}w~}t{" "}w~|R{}v~}V{}w~}V{|v~bv~}l{|v~|s{|v~r{}v~h{}w~}hv~|i{}v~r{|v~r{}v~k{}v~c{}v~gu~|B{}w~B{|u~|Y{}w~X{}v~}k{}v~|Y{}" "w~ sv~}Tu~|wy~}u{|Z{|v~O{|u~}|x{|}v~}_{|p~}y{|p~}Ww~|Tw~}y{|t~|,y~}vw~|e{}y~dw~|s{}w~}V{|w~}u{}w~ Xy~}sw~s{}x~}" "t{}y~*y}x~}|[m|}w~l|^{}w~C{|x~}({|w~|m{}w~|`m~}w{|x~} H{}x~|T{|w~|s{}x~}\\w~}u{|w~|]{}x~|o{}x~}]{}x~|o{}x~}Ww~t" "{}x~}Nv~|U{}w~}t{}w~|Z{}w~}t{}w~|Z{}w~}t{}w~|Z{}w~}t{}w~|Z{}w~}t{}w~|Z{}w~|t{|w~}av~}t{|v~Y{}v~I{}w~}M{}w~}M{}w" "~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~f{|v~|h{}w~|w{}w~}rv~i{}v~c{}v~k{}v~c{}v~k{}v~c{}v~k{}v~c{}v~k{}v~c{}v~c{|" "u~t{}v~}d{}v~n{|w~|v{|v~h{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}]{}v~|v~}Y{}w~}n{|v~|aw~}vv~V{}|m{}w~}]{}|m" "{}w~}]{}|m{}w~}]{}|m{}w~}]{}|m{}w~}]{}|m{}w~}g{}|m{}r~|q{|v~|g{}v~}ny|_{|v~|q{|v~|_{|v~|q{|v~|_{|v~|q{|v~|_{|v~" "|q{|v~|Vv~Lv~Lv~Lv~U{|v~}q{|v~|_t~}r{|v~}_{}v~|r{|v~}^{}v~|r{|v~}^{}v~|r{|v~}^{}v~|r{|v~}^{}v~|r{|v~}V{}u~V{}v~" "|r{|v~}_{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|`v~mv~_s~q{}v~_v~mv~ X{|w~q{}w~q{}x~|j{|w~b{}x~|j{|w~wu~" "|x{|u~|x{}x~|j{|w~m{|u~|x{}x~|j{|w~b{}x~|Z{}x~}V{}w~|o{|v~ WZ~}gx~}w~|q{}y~|({|c~}_v|{}r~u|d{}X~f{}b~|b{|w~}mw~" "}`w~}kw~}[{|v~{}w~}X{|w~}r{|v~d{}x~| q{}c~ yv~} y{}x~}t{}x~}\\v~}w{|y~|_{}w~|vw~}v{|x~}X{|r~ qv~Fv~X{}w~}|x" "x~x{|}w~}U{}w~ d{|w~Y{|v~k{}w~}W{}w~}G{}v~|Xm~}Y{}x~}t{}w~}\\{|h~}]v~y|l~}P{|v~|Y{|u~u|}v~}_{|v~|n{|u~|X{}v~M{" "}v~R{|o~}|`{|Z~}_{|}p~}|P{}v~}cw~r{|l~}x~|u{|x~|hv~|t{|v~^{}e~}a{}v~M{}w~}f{|v~|e{}d~|_{}g~|d{}v~K{}^~|Y{}w~}M{" "}w~}W{}p~|Q{}w~}V{}w~|ww~|tw~}wv~|h{}w~|vv~|sv~i{}v~c{|v~|e{}w~}o{|u~g{}v~c{|v~|g{}w~}p{|u~|^{}q~y}|M{|v~|Z{|v~" "h{}w~}c{|v~|p{|v~gv~|t{|w~v{|x~}sv~|a{|s~|Rq~}N{}v~}S{|w~}Jw~}H{|w~| bv~|^t~ov~}^v~}P{|v~|p{}u~|`v~|o{|v~Ww~}U" "{|v~o{}u~|`u~}p{|v~Vv~Lv~Tw~}u{|v~}Qv~_u~}pt~}pv~|hu~}p{|v~`{|v~|p{|v~|_t~ov~}a{|v~|p{}u~|Zt~S{}w~Gv~S{|w~|m{}w" "~|`v~|o{|v~ev~s{|x~y}x~}s{}w~|c{}v~uv~}\\{}w~|o{|w~}O{}v~|U{|w~}Lw~|M{|w~} M{|x~}x|}w~}xv~}x|}x~|d{}v~qw~y}x~}_" "v~x{}q~}I{|w~}_{|w~|q{|u~]{}w~|Nu~}p{|v~^{}w~|p{|w~}X{|q~Z{|w~|m{}w~|fv~|d{|v~f{|v~}w{}w~|wu~`{|w~}q{|w~}`v~t{}" "w~t{|w~}a{|v~ov~}a{|v~}p{}v~|W{|w~}Wv~}l|}v~^v~|t{|v~Q{}v~}W{}w~}V{|v~b{}w~}l{}v~r{|v~r{}v~|i{}w~}hv~|i{|v~|s{|" "v~r{}v~k{}v~xi~}y{|v~|iu~|A{}w~A{|u~|Z{}w~Y{}v~}i{}v~|Z{}w~ sv}|U{}v~|vy~}S{|v~O{|w~}s{|v~_{|o~|{o~}Ww~|U{}x~}v" "{}u~}.{|y~|w{|w~d{|y~|e{}w~t{}v~}W{|v~|v{}w~}cY|8{|y~|sw~sw~|t{|y~| `{|Z~}_{}x~}C{|w~}({|w~|m{}w~|`{|n~}w{|x~} " "H{}x~|Sv~|u{}w~|\\{}v~v{|v~|^{}x~|p{|w~\\{}x~|p{|w~W{|x~}u{|w~Mv}|Uv~|t{|v~Zv~|t{|v~Zv~|t{|v~Zv~|t{|v~Zv~|t{|v~" "Zv~rv~b{|v~s{|c~l{}v~I{}d~|`{}d~|`{}d~|`{}d~|W{}w~}M{}w~}M{}w~}M{}w~}Z{|v~ev~}h{}w~|vv~|sv~i{}v~c{|v~|l{}v~c{|v" "~|l{}v~c{|v~|l{}v~c{|v~|l{}v~c{|v~|c{|u~v{}v~}c{}v~o{|w~|u{|v~|i{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}\\q~" "}X{}w~}mv~}aw~}vv~Ev~|Mv~|Mv~|Mv~|Mv~|Mv~|Ws~|o{}w~}gv~}Ov~|o{|v~_v~|o{|v~_v~|o{|v~_v~|o{|v~Vv~Lv~Lv~Lv~Uv~}o{}" "w~}_u~}p{|v~`{|v~|p{|v~|`{|v~|p{|v~|`{|v~|p{|v~|`{|v~|p{|v~|`{|v~|p{|v~|Wt|W{|v~|q{}u~|`{|w~|m{}w~|a{|w~|m{}w~|" "a{|w~|m{}w~|a{|w~|m{}w~|`{}w~|o{|w~}_t~ov~}`{}w~|o{|w~} X{}x~}q{}w~q{|x~}j{}x~}b{|x~}j{}x~}vu~|yu~|w{|x~}j{}x~}" "mu~|w{|x~}j{}x~}b{|x~}Z{}x~}V{|v~o{}w~} WZ~}g{}|yw~}qx~'a~|c{|}t~}k~}|fY~}g{}`~b{|w~|m{}w~`w~}kw~}[{|w~}{|v~Wv~" "r{}w~}dw~| lv~| kv~| yw~|tw~|\\{}v~}|y{|y~|^v~}y|}v~uw~X{|p~ rv~Fv~Xw~|vx~v{|w~U{}w~ d{}x~}Y{|v~k{}w~}W{}w" "~}H{|v~}Wo~}|Y{|w~|t{}w~}\\{|v~x}|x}s~}^v~|j~}Q{}w~}V{}l~}]v~}n{}u~}X{}v~M{|v}U{|}p~}|]{|Z~}\\{}o~|S{}v~}c{|x~}" "rv~}|w{|}t~|tx~}i{|v~rv~|_{}h~}|_v~}M{}w~}f{|v~|e{}d~|_{}g~|dv~}K{}^~|Y{}w~}M{}w~}W{}q~|P{}w~}V{}w~|w{}w~u{|w~|" "wv~|h{}w~|v{}w~}sv~iv~}c{|v~|e{}w~}p{|u~|gv~}c{|v~|g{}w~}sy|}u~}\\{}m~}|Q{|v~|Z{|v~h{}w~}bv~}p{}w~}g{}w~}t{}x~}" "v{|w~sv~|`{}u~}Q{|r~|O{|u~R{|w~}J{}w~H{|w~| b{|w~}^u~|o{|v~_{}v~Ov~}nu~|a{}w~}m{}w~|Xw~}Uv~|nu~|`u~nv~|Wv~Lv~T" "w~}v{}v~}Pv~_u~o{}u~|p{}w~}hu~nv~|a{}w~}n{}w~}_u~|o{|v~a{}w~}nu~|Zu~|S{}w~Gv~S{|w~|m{}w~|`{}w~}o{}w~}e{}w~s{}x~" "}|w~sv~a{}v~w{}v~[{|w~}ov~|P{}v~|T{|w~}Lw~|M{|w~}:{|4x~|v{|w~}{}x~}u{}x~dv~}q{}s~|_v~x{}r~}S{|y}~y}|w{|w~}_w~}o" "{|v~}^{}w~Mu~nv~|_{|w~}pv~|X{}w~}v~|[{|w~|m{}w~|g{|v~bv~|g{}v~v{}w~v{|v~|a{|w~}q{|w~}`v~t{}w~t{|w~}a{}w~|o{|v~a" "{}v~nv~}W{|w~}W`~_{|v~rv~|Q{}v~|X{}w~}V{|v~b{}w~}lu~r{|v~r{|v~|i{}w~}hv~|hv~}s{|v~rv~}kv~}xi~}y{|v~|ju~|@{}w~@{" "|u~|[{}w~Z{}v~}g{}v~|[{}w~ Gv~}uy~}S{|v~Ow~}q{|w~|`{|n~}o~}Ww~|Uw~|t{}u~|0{|y~|w{|x~}d{|y~|e{|v~}w|t~}X{|v~|vv~" "}c{|Z~}8{|y~|sw~t{}w~s{|y~| `{|Z~}`{}x~}M{|~}|v{|}v~'{|w~|m{}w~|_{}o~}w{|x~}Vv}| s{}x~|S{|v~}|{y|}w~}Z{}v~|w{|v" "~}_{}x~|pw~|o{}w~m{}x~|p{}x~|vy|}w~y}|g{|w~|u{}x~|o{}w~3{|v~rv~|\\{|v~rv~|\\{|v~rv~|\\{|v~rv~|\\{|v~rv~|\\{}w~}" "r{}w~|c{}w~}s{|c~lv~}I{}d~|`{}d~|`{}d~|`{}d~|W{}w~}M{}w~}M{}w~}M{}w~}_{}i~}nv~}h{}w~|v{}w~}sv~iv~}c{|v~|lv~}c{|" "v~|lv~}c{|v~|lv~}c{|v~|lv~}c{|v~|b{|u~x{}v~}bv~}p{|w~}t{|v~|i{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}\\{|r~|" "X{}w~}mv~}aw~}v{}w~}F{|w~}M{|w~}M{|w~}M{|w~}M{|w~}M{|w~}W{|u~}m{}w~h{}v~O{}w~}m{}w~|a{}w~}m{}w~|a{}w~}m{}w~|a{}" "w~}m{}w~|Wv~Lv~Lv~Lv~V{}v~n{|v~_u~nv~|a{}w~}n{}w~}`{}w~}n{}w~}`{}w~}n{}w~}`{}w~}n{}w~}`{}w~}n{}w~},{}w~}q{}t~}`" "{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|`{|w~}ov~|_u~|o{|v~`{|w~}ov~| X{}x~|q{}w~q{|w~j{}x~|b{|w~j{}x~|u" "u~|u~|v{|w~j{}x~|nu~|v{|w~j{}x~|b{|w~Zw~}Uv~|q{|v~ VZ~}c{}w~r{|y~}({}`~d{}^~|h{|Z~g{|_~}c{}w~l{|w~`w~}kw~}[{}w~" "|yv~|X{}w~|sv~|dV~} 2v~| k{}w~| {{|w~t{|w~Zs~y}y~|^{|o~|v{}x~}rx|e{|v~y}u~n{|w~},{|v~Fv~|Y{|~}tx~t{}~|U{}w~ " " dw~|Y{|v~k{}w~}W{}w~}Hu~Vp~}|Y{|w~}s{}w~}\\{|~}|q{}t~|`{|q~}|xy|t~|Rv~|U{|}p~|[{}v~|ot~} V{|}p~}|Z{|Z~}Z{|}p~}" "|W{}v~|b{}x~|s{}w~|s{|u~|tw~i{}w~}r{}w~}_{}g~}|`v~}M{}w~}f{|v~|e{}d~|_{}g~|dv~}K{}^~|Y{}w~}M{}w~}W{}q~O{}w~}V{}" "w~|w{|w~|v{}w~vv~|h{}w~|uv~|tv~iv~}c{|v~|e{}w~}sy|s~fv~}c{|v~|g{}f~}Z{}k~}S{|v~|Z{|v~h{}w~}b{|v~pv~|g{}w~}tw~|u" "w~|u{|v~_{}u~O{}t~|O{|u~|R{|w~}J{|w~|I{|w~| aw~}^v~}m{}w~}`v~|P{|v~m{}v~|av~l{|w~}Xw~}V{|v~m{|v~|`v~}n{}w~|Wv~" "Lv~Tw~}w{}v~}Ov~_v~}o{|v~}o{|w~}hv~}n{}w~|av~|n{|v~|`u~mv~|bv~m{}v~|Zv~}R{}w~Gv~S{|w~|m{}w~|`{|v~ov~d{}w~|tw~|{" "w~|u{|w~}`v~}y{|v~|Z{}w~|q{|v~P{}v~|Sv~|Lw~|Lv~|W{|y}w~}|iy}5{|y~}sw~|x~}s{}y~|f{|v~|ps~^v~x{}q~}|W{|r~|y{|w~}`" "{}w~m{}v~^{}w~Mv~}n{}w~|^{}w~q{|v~Wv~y|w~}[{|w~|m{}w~|g{}v~b{}w~}h{|v~|v{}w~u{}w~}a{|w~}q{|w~}`v~t{}w~t{|w~}av~" "mv~|c{|v~|n{|v~W{|w~}W`~_{}w~}r{}w~}Q{|v~}X{}w~}V{|v~b{}w~}lv~}r{|v~r{|v~|i{}w~}hv~|h{}v~s{|v~s{|v~|kv~}xi~}y{|" "v~|ku~|?{}w~?{|u~|\\{}w~[{}v~}e{}v~|\\{}w~ H{}v~ty~}S{|v~P{|w~o{}w~_s|}r~s|Vw~|V{|w~r{|u~0{|y~v{}x~}d{|y~|d{}o~" "|x~}Y{}v~v{|v~|b{|Z~}8{|y~rw~u}v~|s{|y~| `{|Z~}a{}l~|X{|m~|'{|w~|m{}w~|^o~}w{|x~}W{|v~| xm~}W{|n~}X{|v~|vv~}e{}" "n~}v{}x~}o{|v~m{}x~|q{|w~w{|o~|t{|~}y|w{|}v~u{|x~}o{|v~3{}w~}r{}w~}\\{}w~}r{}w~}\\{}w~}r{}w~}\\{}w~}r{}w~}\\{}w" "~}r{}w~}\\v~|r{|w~}cv~|s{|c~lv~}I{}d~|`{}d~|`{}d~|`{}d~|W{}w~}M{}w~}M{}w~}M{}w~}_{}i~}nv~}h{}w~|uv~|tv~iv~}c{|v" "~|lv~}c{|v~|lv~}c{|v~|lv~}c{|v~|lv~}c{|v~|a{|u~|}v~}av~}pw~}s{|v~|i{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}[" "{}t~|W{}w~}mv~}aw~}v{}v~|Fw~}Lw~}Lw~}Lw~}Lw~}Lw~}Vu~l{|w~|iv~|Ov~l{|w~}av~l{|w~}av~l{|w~}av~l{|w~}Wv~Lv~Lv~Lv~V" "v~|mv~|`v~}n{}w~|av~|n{|v~|av~|n{|v~|av~|n{|v~|av~|n{|v~|av~|n{|v~|-v~|r{|x~}v~`{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{" "}w~|a{|w~|m{}w~|_{}w~|q{|v~^u~mv~|`{}w~|q{|v~ Ww~p{}w~pw~jw~yd|yw~jw~t{|p~|tw~jw~nu~|tw~jw~pv~}qw~Zw~|U{}w~}q{}" "w~} F{}w~}W{|w~|s{}y~|){|_~}f{}\\~|h{}\\~|g{}^~c{}w~l{|w~|aw~}kw~}[v~x{}w~}X{|w~}t{|v~cV~} 2v~| k{}w~| {{|x~" "}t{|x~}Z{|o~}y|`{|}r~|v{|w~t{}u~}|hv~}y{}u~o{|w~|,{|v~F{}w~|X{|sx~s{|T{}w~ e{|w~X{|v~k{}w~}W{}w~}Iu~|Vm~|[{}w~" "r{}w~}L{}u~`{|r~|s{|u~S{}v~V{|}m~}|\\u~p{}t~} Y{|}p~}|VY|W{|}p~}|[{|v~|aw~rw~}q{|v~|t{}x~iv~q{|v~_{}e~}av~}M{}w" "~}f{|v~|e{}d~|_{}g~|dv~}m{}n~|h{}^~|Y{}w~}M{}w~}W{}q~}P{}w~}V{}w~|vw~}vw~}vv~|h{}w~|u{}v~tv~iv~}bv~|e{}e~|fv~}b" "v~|g{}g~}X{|}k~}U{|v~|Z{|v~h{}w~}av~|r{|v~f{|v~u{|w~|u{}x~}u{}w~}`{|t~|O{}v~}Nu~|Q{|w~}Iw~}I{|w~| a{}w~^v~|m{|" "w~}a{|v~O{|w~}lv~|b{|w~}kv~Xw~}V{|w~}lv~|`v~|n{|w~}Wv~Lv~Tw~}x{}v~|Nv~_v~|nv~|nv~hv~|n{|w~}b{|v~lv~|`v~}m{|w~}c" "{|w~}m{|v~|Zv~|R{}w~|Hv~S{|w~|m{}w~|_{}w~|q{|w~}d{|w~}u{|w~y{}x~|u{|w~|`{|v~y|v~}Y{|w~}q{}w~|Q{|v~}S{}v~Kw~|L{}" "w~}Y{|p~}|n{|y~}5{}y~r{|t~qy~}f{}v~ot~}^v~x{}o~}Y{}p~|{|w~|`w~}lv~|_{|w~}Nv~|n{|w~}^{|w~|r{}w~|X{}w~}yv~[{|w~|m" "{}w~|gv~}b{}v~h{|v~u{}w~u{|v~a{|w~}q{|w~}`v~t{}w~t{|w~}b{|w~}m{|w~}c{|v~lv~|X{|w~}W`~_v~|r{|v~Qu~W{}w~}V{|v~b{}" "w~}lv~}r{|v~qv~|i{}w~}hv~|h{|v~|t{|v~s{}v~jv~}xi~}xv~|lu~[|]{}w~\\\\|u~|]{}w~\\{}v~}c|u~|]{}w~ H{}w~}ty~}X{}g~|" "[{}x~}nw~Vs~|Nw~|V{}x~}pv~}1{}y~v{}x~}d{|y~}c{}r~}{|x~}Z{}w~}v{|v~|a{|Z~}8{}y~rn~}q{|y~} `{|Z~}a{}l~|X{|o~}|&{|" "w~|m{}w~|]{}q~}w{|x~}W{|v~| xm~}V{|}q~|V{|v~|v{}w~}fm~}vw~o{|u~rm~}vw~|w{}n~|u{|m~|uw~|p{|u~3v~q{|v~\\v~q{|v~\\" "v~q{|v~\\v~q{|v~\\v~q{|v~]{|v~pv~|e{}w~}r{|c~lv~}I{}d~|`{}d~|`{}d~|`{}d~|W{}w~}M{}w~}M{}w~}M{}w~}_{}i~}nv~}h{}w" "~|u{}v~tv~iv~}bv~|lv~}bv~|lv~}bv~|lv~}bv~|lv~}bv~|`{|p~}`v~}q{}x~}qv~|i{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}" "w~}Z{}v~}V{}w~}mv~}aw~}uu~}G{}w~L{}w~L{}w~L{}w~L{}w~L{}w~V{}w~}kw~}j{|v~O{|w~}kv~b{|w~}kv~b{|w~}kv~b{|w~}kv~Wv~" "Lv~Lv~Lv~W{|v~l{}w~}`v~|n{|w~}b{|v~lv~|b{|v~lv~|b{|v~lv~|b{|v~lv~|b{|v~lv~|.{|v~r{|w~{}w~|a{|w~|m{}w~|a{|w~|m{}" "w~|a{|w~|m{}w~|a{|w~|m{}w~|_{|w~}q{}w~|^v~}m{|w~}`{|w~}q{}w~| Ww~yd~|{w~jw~yd~|{w~jw~s{|r~|sw~jw~ou~|sw~jw~pv~}" "qw~Zw~|U{|v~qv~| G{}w~}Uw~}sx~({}^~g{}Z~g]~}f{|_~|cw~}l{|w~|aw~}kw~}\\{|v~x{|v~Wv~t{}w~}cV~} 2v~| k{}w~| {{}" "x~}t{}x~}Y{|}m~}`{|}w~}|tw~|v{|q~}j{}v~w{}u~p{}w~|,{|w~}F{}w~|Ox~Z{|Z~} t{}x~}X{|v~k{}w~}W{}w~}J{}v~|Ut|}t~}]{" "|w~|r{}w~}K{}v~|a{|s~p{|v~}Tv~}W{}i~}]{}u~|t{|}s~} Z{|q~}| e{|}q~}\\v~}`x~}s{}w~ov~|t{}x~|k{|w~}p{}w~|`{}w~}p|}" "t~|cv~}M{}w~}f{|v~|e{}w~}i|^{}w~}l|cv~}m{}n~|h{}w~}h|v~|Y{}w~}M{}w~}W{}w~}u~}Q{}w~}V{}w~|v{}w~w{|w~uv~|h{}w~|tv" "~|uv~iv~}c{|v~|e{}f~|ev~}c{|v~|g{}i~}S{|}m~}V{|v~|Z{|v~h{}w~}a{}w~}rv~}ev~|v{|w~t{|w~uv~|`r~O{|v~|O{}v~}P{|w~}I" "{}w~I{|w~| a{}w~^v~|lv~a{}w~}O{}w~|lv~|b{|w~|k{}w~Xw~}V{}w~|lv~|`v~m{|w~}Wv~Lv~Tw~}yu~|Mv~_v~mv~mv~hv~m{|w~}b{" "}w~}l{}w~}`v~|m{|v~c{}w~|lv~|Zv~Q{}v~|Iv~S{|w~|m{}w~|_{|w~}q{}w~|cv~u{}x~}y{}x~}u{}w~^{}q~}Wv~qv~Q{|v~}Uy|}v~|K" "w~|L{|u~}|^{|k~}|s{|}x~}5y~}q{}v~|q{}y~f{}w~}o{}u~|^v~ty|}s~[{|u~y}v~y|w~|a{|w~}l{}w~}^{}w~|Ov~m{|w~}]w~}rv~Wv~" "|y{}w~}\\{|w~|m{}w~|gv~|b{|v~h{}w~}u{}w~tv~a{|w~}q{|w~}`v~t{}w~t{|w~}b{}w~|m{|v~c{}w~}l{}w~}X{|w~}W`~`{|w~}pv~|" "S{}v~|W{}w~}V{|v~bv~}lv~}r{|v~r{|v~|i{}w~}hv~|gu~t{|v~t{|v~}jv~}xh|y{|v~|mT~]{}w~]T~|^{}w~]{}U~|^{}w~ Hv~|ty~}X" "{}g~|[w~|nw~|W{}u~}Mw~|V{}w~ov~1{|y~v{}x~}d{|y~|ay}x~y}ww|[{}w~}v{|v~|`{|Z~}8{|y~ro~o{|y~| Q{}w~R{}l~|V{|y}v~y}" "|${|w~|m{}w~|\\{|}s~}w{|x~}W{|v~| xm~}T{|y}w~}|S{|v~|v{}w~}gm~}w{}x~}oy~y}x~rm~}w{}x~}v{}~}y|w{|v~u{|o~}t{}x~}o", "t~^v|V{|w~}p{}w~|^{|w~}p{}w~|^{|w~}p{}w~|^{|w~}p{}w~|^{|w~}p{}w~|^{}w~}p{}w~}ev~|r{|v~h|lv~}I{}w~}i|_{}w~}i|_{}" "w~}i|_{}w~}i|V{}w~}M{}w~}M{}w~}M{}w~}_v}u~r}nv~}h{}w~|tv~|uv~iv~}c{|v~|lv~}c{|v~|lv~}c{|v~|lv~}c{|v~|lv~}c{|v~|" "_{|r~}_v~}r{}w~q{|v~|i{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}Z{|v~|V{}w~}mv~}aw~}u{|t~|I{}w~L{}w~L{}w~L{}w~" "L{}w~L{}w~V{}w~|kv~j{}w~}O{|w~|k{}w~b{|w~|k{}w~b{|w~|k{}w~b{|w~|k{}w~Wv~Lv~Lv~Lv~W{}w~}l{|w~}`v~m{|w~}b{}w~}l{}" "w~}b{}w~}l{}w~}b{}w~}l{}w~}b{}w~}l{}w~}b{}w~}l{}w~}eY|f{}w~}rw~y{|w~}a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|" "m{}w~|^v~qv~]v~|m{|v~_v~qv~ Vw~yd~|{}x~|kw~yd~|{}x~|kw~r{|t~|r{}x~|kw~pu~|r{}x~|kw~pv~}q{}x~|[w~|T{}w~|s{|v~ G{" "}v~T{}w~t{|y~}(]~|i{|Y~}h{|_~}d{|a~}bw~}kw~|aw~}kw~}\\{}w~}wv~|Xv~|u{}w~|cV~} 2v~| k{}w~| {{w~|tw~|W{|}m~}T{" "}x~}v{|o~}l{|v~|v{}u~q{}w~+{|w~}F{}w~|Ox~Z{|Z~}+m| ww~|X{|v~k{}w~}W{}w~}K{}v~}K{|}v~}^w~}q{}w~}Ju~a{|t~|o{}v~U{" "|v~|X{}u~}|wy|u~}]t~}y|{y|}q~} Z{|t~}| _{|}t~}\\v~`{|x~}s{}x~}o{|w~|t{}x~|kv~|p{|w~}`{}w~}n{|u~cv~}M{}w~}f{|v~|" "e{}w~}L{}w~}Tv~}m{}n~|h{}w~}hv~|Y{}w~}M{}w~}W{}w~}|u~}R{}w~}V{}w~|v{|w~|x{}x~}uv~|h{}w~|t{|v~uv~iv~}c{|v~|e{}h~" "}cv~}c{|v~|g{}h~}Qy|y}p~W{|v~|Z{|v~h{}w~}a{|v~s{|v~|e{}w~}v{}x~}t{|w~uv~|a{}r~}P{|v~|P{}v~}O{|w~}I{|w~|J{|w~| " "n{|y}l~^v~kv~a{}w~|Ov~|l{}w~|b{}w~|k{}w~|Yw~}Vv~|l{}w~|`v~m{|w~}Wv~Lv~Tw~}|u~Kv~_v~mv~mv~hv~m{|w~}b{}w~|l{|v~`v" "~kv~c{}w~|l{}w~|Zv~Pu~}|Kv~S{|w~|m{}w~|^v~qv~b{}w~u{}x~|y{|w~uv~]{}r~V{}w~|s{|w~}R{|v~}X{|q~}Jw~|K{|q~}c{}g~}w|" "}u~}5y~}pw~}p{}y~fv~|o{}u~]v~p{|t~\\v~}w{|w~}w~|a{}w~|l{|w~}]{}w~}y|Rv~m{|w~}]{}w~s{}w~}X{}w~}x{|v~\\{|w~|m{}w~" "|h{|v~|b{|v~|i{}w~|u{}w~tv~|b{|w~}q{|w~}`v~t{}w~t{|w~}bv~kv~c{}w~|l{|w~}X{|w~}Wv~jv~`v~|p{}w~}T{}v~|V{}w~}V{|v~" "|cv~|lv~}r{|v~r{|v~|i{}w~}hv~|g{}v~}u{|v~tu~|jv~}c{|v~|n{|T~]{}w~]T~}^{}w~]T~}^{}w~ I{|v~sy~}X{}g~|[w~m{}x~|Vu~" "|#{|w~|p{|w~|2{|y~|w{|x~}d{|y~|3v~}v{}v~|Aw~}8{|y~|sw~x{|w~}p{|y~| Q{}w~ p{|w~|m{}w~|Y{|}v~}w{|x~}W{|v~| jv~}" "v{}v~|W{|w~o{}y~{}x~r{}n~}x{|w~uy|rw~|ty|t}|s{|w~o{}y~|}x~^{}w~|Wv~|p{|w~}^v~|p{|w~}^v~|p{|w~}^v~|p{|w~}^v~|p{|" "w~}^v~|p{|v~f{|v~q{|v~Yv~}I{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~ev~}h{}w~|t{|v~uv~iv~}c{|v~|lv~}" "c{|v~|lv~}c{|v~|lv~}c{|v~|lv~}c{|v~|^{|t~}^v~}s{}w~p{|v~|i{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}Z{|v~|V{}w" "~}n{|v~|aw~}t{}t~}W{|y}l~Y{|y}l~Y{|y}l~Y{|y}l~Y{|y}l~Y{|y}l~c{|y}l~j{}w~j{}w~|O{}w~|k{}w~|c{}w~|k{}w~|c{}w~|k{}" "w~|c{}w~|k{}w~|Xv~Lv~Lv~Lv~W{}w~|l{|v~`v~m{|w~}b{}w~|l{|v~b{}w~|l{|v~b{}w~|l{|v~b{}w~|l{|v~b{}w~|l{|v~f{|Z~}f{}" "w~|s{}x~|y{|w~}a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|^{}w~|s{|w~}]v~kv~_{}w~|s{|w~} Vw~yd~|{}x~|kw~yd" "~|{}x~|kw~qt~|r{}x~|kw~qu~|q{}x~|kw~pv~}q{}x~|[w~|T{|w~}s{}w~} H{|v~|T{|w~|u{}y~({|]~}i{}X~g{|`~b{}b~aw~}kw~}aw" "~}kw~}\\v~|w{}w~}X{}w~}uv~bw~}Z| 5x|v~}p| v{}w~| {|w~t{|w~S{|}n~|Vw~uv~|y{|}w~}m{}w~}t{}u~rw~}+{|w~}F{}w~|Ox" "~Z{|Z~},{|m~ x{|w~|X{|v~k{}w~}W{}w~}L{}v~}H{}v~}`{}w~p{}w~}J{}v~`t~n{|v~|V{}v~X{}v~}q{}v~}^{|j~|v~| Z{|t~| ]{|}" "u~}]{|w~}`{|x~|sw~|o{|w~|t{}x~|l{|v~nv~`{}w~}lv~}dv~}M{}w~}f{|v~|e{}w~}L{}w~}Tv~}m{}n~|h{}w~}hv~|Y{}w~}M{}w~}W{" "}w~}{|t~S{}w~}V{}w~|u{}x~}y{|w~|uv~|h{}w~|sv~|vv~iv~}c{|v~|e{}k~}|av~}c{|v~|g{}w~}t|y}u~}M{|}s~}X{|v~|Z{|v~h{}w" "~}`v~}t{}v~d{}w~}vw~|sw~|w{|v~a{|v~}v~|Q{|v~|Q{|u~N{|w~}Hw~|J{|w~| p{}h~|_v~k{}w~|bv~|Ov~k{}w~|bv~j}v~|Yw~}Vv~" "k{}w~|`w~}m{|w~}Wv~Lv~Tq~}Jv~_w~}mv~mv~hw~}m{|w~}bv~|l{|v~`v~kv~|dv~k{}w~|Zv~P{}r~}y|Pv~S{|w~|m{}w~|^{}w~|s{|w~" "}b{|w~|vw~|xw~|w{|w~}\\s~|Uv~sv~|Ru~W{|s~}|Iw~|I{|}t~}d{|u~}w|}g~}5{|y~|p{|x~|p{}y~fv~|o{|v~}]v~n{}v~|^{}w~|ts~" "`v~|l{|v~\\{}p~}Xw~}m{|w~}]{|w~|tv~|Xv~|wv~|]{|w~|m{}w~|h{|v~|q{}x~}q{|v~|iv~|u{}w~t{}w~|b{|w~}q{|w~}`v~t{}w~t{" "|w~}bv~kv~|dv~|l{|v~X{|w~}Wv~|l{|v~a{|v~nv~U{|v~}U{}w~}Uv~}d{|v~|l{}v~r{|v~r{|v~|i{}w~}hv~|fu~|v{|v~u{}v~}iv~}c" "{|v~|n{|T~]{}w~]T~}^{}w~]T~}^{}w~ rw|V{|w~}sy~}X{|w}u~q}Zw~m{}x~|V{}v~\"{|v~ow~|2{|y~|w{|w~d{|y~|4{}w~}v{|v~?w~" "}8{|y~|sw~vw~}q{|y~| Q{}w~ p{|w~|m{}w~|Ux~}w{|x~}W{|v~| i{}w~|v{|v~Ww~|p{|y~|{}x~`{}x~|j{|x~}bw~|p{|y~}{}x~^{" "}w~|X{|v~nv~_{|v~nv~_{|v~nv~_{|v~nv~_{|v~nv~_{|w~}nv~|g{}w~}q{|v~Yv~}I{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}" "M{}w~}Z{|v~ev~}h{}w~|sv~|vv~iv~}c{|v~|lv~}c{|v~|lv~}c{|v~|lv~}c{|v~|lv~}c{|v~|]{}u~|^v~}t{|w~|p{|v~|i{|v~h{}w~}" "f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}Z{|v~|V{}w~}n{}v~|aw~}s{|s~|[{}h~|\\{}h~|\\{}h~|\\{}h~|\\{}h~|\\{}h~|f{}h~j}v~" "jv~|Ov~j}v~|cv~j}v~|cv~j}v~|cv~j}v~|Xv~Lv~Lv~Lv~Wv~|l{|v~`w~}m{|w~}bv~|l{|v~bv~|l{|v~bv~|l{|v~bv~|l{|v~bv~|l{|v" "~f{|Z~}fv~|t{}x~|wv~a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|]v~sv~|]v~kv~|_v~sv~| Vw~yd~|{w~jw~yd~|{w~j" "w~rr~|sw~jw~ru~|pw~jw~pv~}qw~Zw~|Sv~sv~ H{|v~|Rw~}uy~}({|]~}i{}X~|g{}b~|a{}d~|aw~}kw~}aw~}kw~}]{|v~v{|v~X{|v~v{" "|w~}b{}x~} pf~ v{|w~ {{|w~t{|x~}P{|y~}r~W{}x~|v{}w~u{}w~mv~r{}u~t{|w~|+{|v~F{}w~|Ox~Z{|Z~},{|m~ x{}w~W{|v~k" "{}w~}W{}w~}M{}v~}F{}v~a{|w~|p{}w~}Iv~|au~}mv~}Vv~|Y{|v~}o{|v~|]{}m~|{v~| Z{|r~}| c{|}r~}]{|w~}`{|x~|sw~|nw~|t{}" "x~k{}w~}n{}w~}a{}w~}l{|v~|e{}v~M{}w~}f{}v~d{}w~}L{}w~}T{}v~mr|v~|h{}w~}hv~|Y{}w~}M{}w~}W{}w~}y{|t~T{}w~}V{}w~|u" "{|w~y{}w~tv~|h{}w~|s{|v~vv~i{}v~c{|v~|e{}w~}r|]{}v~c{|v~|g{}w~}q{}v~}K{|t~|Y{|v~|Z{|v~h{}w~}`{}v~tv~|d{|v~w{|w~" "|s{}x~}w{}w~}av~}{}v~Q{|v~|R{|u~M{|w~}H{}x~}J{|w~| r{|f~|_w~}k{}w~|bv~|Ov~k{}w~|b`~|Yw~}Vv~k{}w~|`w~}m{|w~}Wv~" "Lv~Tq~Iv~_w~}mv~mv~hw~}m{|w~}bv~jv~`v~k{}w~|dv~k{}w~|Zw~}O{}o~}|Sv~S{|w~|m{}w~|^{|w~}s{}w~|b{|w~}w{|w~w{}x~}w{|" "w~|\\{|u~}T{}w~|u{|w~}Ru~V{|s~}|Iw~|J{|}s~}d{|w~|s{|}k~|3y~}p{|x~}p{}y~fv~mv~|]v~m{}v~_{|w~}rt~`v~jv~Z{}r~}Xw~}" "m{|w~}\\w~}u{|w~}X{|w~}v{}w~}]{|w~|m{}w~|h{|v~|q{}x~}pv~|iv~t{}w~t{}w~|b{|w~}q{|w~}`v~t{}w~t{|w~}bv~k{}w~|dv~jv" "~X{|w~}W{}w~|l{|v~a{}w~}n{}w~}W{|u~T{}w~}U{}w~}d{}v~k{}v~|s{|v~r{}v~h{}w~}hv~|f{|u~|w{|v~v{}u~h{}v~c{|v~|n{|T~]" "{}w~]T~|^{}w~]{}U~}^{}w~ s{|w~V{|w~}sy~}S{|v~Pw~|nw~|V{|w~}!{}v~|q{}x~|1y~}vw~|e{}y~ci|]{}w~u{|w~|?w~}7y~}sw~v{" "|w~|r{}y~ P{}w~ p{|w~|m{}w~|Ux~}w{|x~}W{|v~| Fi|U{|w~|u{}w~X{}x~}p{|y~}y{}x~a{|w~i{|x~}c{}x~}p{|y~}y{}x~^{}w~|" "X{}w~}n{}w~}`{}w~}n{}w~}`{}w~}n{}w~}`{}w~}n{}w~}`{}w~}n{}w~}`{}w~|n{}w~}h{|v~p{|v~Y{}v~I{}w~}M{}w~}M{}w~}M{}w~}" "D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~f{|v~|h{}w~|s{|v~vv~i{}v~c{|v~|l{}v~c{|v~|l{}v~c{|v~|l{}v~c{|v~|l{}v~c{|v~|^{}s~|_" "{}v~u{|w~|o{|v~|i{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}Z{|v~|V{}w~}o{|u~`w~}q{}t~|^{|f~|^{|f~|^{|f~|^{|f~|" "^{|f~|^{|f~|h{|P~jv~|O`~|c`~|c`~|c`~|Xv~Lv~Lv~Lv~Wv~jv~`w~}m{|w~}bv~jv~bv~jv~bv~jv~bv~jv~bv~jv~f{|Z~}fv~|u{}x~}" "vv~a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|]{}w~|u{|w~}\\v~k{}w~|_{}w~|u{|w~} Uw~yq}w~r}yw~jw~yd|yw~jw~" "sp~|tw~jw~su~|ow~jw~pv~}qw~Zw~|S{}w~}u{|w~} Hv~|Q{}w~|w{|y~|({|\\~iW~|f{}d~|_e~|`w~}kw~}aw~}kw~|]{}w~}uv~Wv~|w{" "}w~|b{}x~} q{|g~| v{|w~({}Z~X{|y~|{|}u~}Y{|w~uw~|tw~}o{|w~}q{}u~u{}w~*{|v~F{}w~|*m|}w~l|,{|m~ xw~}W{|v~k{}w" "~}W{}w~}N{}v~}Dv~|bw~}o{}w~}Iv~|au~|m{}w~}W{|v~X{}v~m{}v~\\{|p~}xv~| Y{}p~}| i{|}p~}|]{}w~}`{|x~|sw~mw~|t{}x~kv" "~}n|}v~a{}w~}kv~}e{}v~M{}w~}f{}v~d{}w~}L{}w~}T{}v~dv~|h{}w~}hv~|Y{}w~}M{}w~}W{}w~}x{|t~U{}w~}V{}w~|tw~|{w~}tv~|" "h{}w~|rv~}wv~i{}v~c{}v~d{}w~}T{}v~c{}v~f{}w~}p{}v~|Ju~}Y{|v~|Z{|v~h{}w~}_v~|v{|v~bv~|x{|w~r{}w~wv~|b{}v~xv~}R{|" "v~|Ru~|M{|w~}H{|w~J{|w~| s{|q~t}v~|_w~}k{}w~|bv~Nv~k{}w~|b`~|Yw~}Vv~k{}w~|`w~}m{|w~}Wv~Lv~Tp~Jv~_w~}mv~mv~hw~}" "m{|w~}bv~jv~`w~}k{}w~|dv~k{}w~|Zw~}N{|m~|Uv~S{|w~|m{}w~|]v~t{|v~`v~w{}x~}w{|x~}w{}w~[{|u~|T{|w~}u{}w~|S{}v~|V{|" "x}t~}Jw~|K{|s~y}|d{|y~}n{|}p~}1y~}p{}w~p{}y~fv~mv~\\v~lv~|`{}w~|r{|v~}`v~jv~\\{|p~}Xw~}m{|w~}\\{}w~u{}w~|Xv~|v{" "|v~]{|w~|m{}w~|h{|v~p{}w~pv~}iv~t{}w~t{}w~|b{|w~}q{|w~}`v~t{}w~t{|w~}bw~}k{}w~|dv~jv~X{|w~}W{}w~|l{|w~}av~|n{|v" "~Wu~|T{}w~}U{}v~dv~}k{|v~}s{|v~s{|v~}h{}w~}hv~|e{}u~|x{|v~w{}u~|h{}v~c{}v~l{|u~}\\|]{}w~][|u~|]{}w~\\{}v~}c|u~}" "]{}w~ s{|w~V{|w~}sy~}S{|v~P{}x~}o{|w~`{|a~}+u~|rw~|1y~}v{}w~ex~d{|j~}]{}w~}v{|v~|@w~}7y~}sw~u{}w~rx~ P{}w~ p{|" "w~|m{}w~|Ux~}w{|x~} w{|j~}V{|v~|v{}w~}Xw~oy~}x{}x~aw~|i{|x~|cw~ox~x{}x~^{}w~|Xv~}n|}v~`v~}n|}v~`v~}n|}v~`v~}n|" "}v~`v~}n|}v~a{|b~h{}v~p|}v~Y{}v~I{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~f{|v~|h{}w~|rv~}wv~i{}v~c{" "}v~k{}v~c{}v~k{}v~c{}v~k{}v~c{}v~k{}v~c{}v~^{}q~|`{}v~v{|w~}n{}v~h{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}Z{" "|v~|V{}w~}p{|u~|`w~}p{|t~}`{|q~t}v~|_{|q~t}v~|_{|q~t}v~|_{|q~t}v~|_{|q~t}v~|_{|q~t}v~|i{|q~t}`~|kv~N`~|c`~|c`~|" "c`~|Xv~Lv~Lv~Lv~Wv~jv~`w~}m{|w~}bv~jv~bv~jv~bv~jv~bv~jv~bv~jv~f{|Z~}fv~u{|x~}uv~a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m" "{}w~|a{|w~|m{}w~|]{|w~}u{}w~|\\w~}k{}w~|_{|w~}u{}w~| U{}x~|q{}w~q{|w~j{}x~|b{|w~j{}x~|uu~|u~|v{|w~j{}x~|uu~|o{|" "w~j{}x~|qv}|r{|w~[{|w~|S{|v~uv~| TZ~}a{|w~}wx~'{|\\~iW~|ee~|^{|g~}_w~}kw~}aw~}kw~|]v~|u{}w~|X{}w~}wv~|b{|w~| " " r{}g~ u{|w~({}Z~X{|y~|w{}v~|Zw~|v{|w~s{|w~o{|w~}p{}u~vw~})v~Fv~| w{}w~ x{|m~ y{|w~|Vv~|lv~|W{}w~}O{}v~}C{}w~}" "c{|w~n|}w~}v|N{}w~}au~l{|v~Wv~}Xv~}m{|v~|[{|y}w~y}|x{|v~ V{|}p~}|XY|X{|}q~}|Z{}w~}`{|x~|sw~mw~|tw~l{|b~|b{}w~}k" "{}v~e{|v~|N{}w~}fv~}d{}w~}L{}w~}T{|v~|ev~|h{}w~}hv~|Y{}w~}M{}w~}W{}w~}w{|t~V{}w~}V{}w~|t{}w~|w~|tv~|h{}w~|r{|v~" "wv~i{|v~|d{}v~d{}w~}T{|v~|d{}v~f{}w~}o{}v~J{|u~Y{|v~|Z{|v~h{}w~}_{}w~}v{}w~}b{}w~}x{}x~}r{|w~wv~b{|v~|x{|v~|S{|" "v~|S{}v~|L{|w~}Gw~|K{|w~| t{|u~}|q{}w~|_v~k{}w~|bv~Nv~k{}w~|b`~|Yw~}Vv~k{}w~|`w~}m{|w~}Wv~Lv~Tw~}|u~Kv~_w~}mv~" "mv~hw~}m{|w~}bv~jv~`w~}k{}w~|dv~k{}w~|Zw~}L{|}o~}Vv~S{|w~|m{}w~|]{}w~}u{}w~}`{}w~|xw~|w{|w~wv~\\{|s~Sv~uv~S{}v~" "|O{}v~}Kw~|L{|v~}|_{|~|j{|y}x~y}|/x~q{|v~}qx~fv~m{}x~}\\v~l{}w~|`v~pv~}`v~jv~]n~}Xw~}m{|w~}\\{|w~|vv~X{|v~t{}w~" "|^{|w~|m{}w~|h{|v~p{}w~pv~|iv~t{}w~t{}w~|b{|w~}q{|w~}`v~t{}w~t{|w~}bw~}k{}w~|dv~jv~X{|w~}W{}w~}l{}w~}b{|v~lv~|Y" "{}v~|S{}w~}U{|v~}f{|v~|ju~|t{|v~s{}v~|h{}w~}hv~|dt~}y{|v~y{|t~|g{|v~|d{}v~k{|u~|?{}w~>u~|b{|v{}w~[{}v~|e{}v~}\\" "{}w~ s{|w~V{|w~}sy~}S{|v~P{|w~o{}x~}`{|a~}+{|u~}|u{|w~0{}y~v{|w~}g{|y~}d{|j~}\\{}v~|w{|v~}Aw~}7{}y~sw~tw~}t{|y~" "} P{}w~ p{|w~|m{}w~|Ux~}w{|x~} w{|j~}W{|v~|vv~}X{}x~|p{}y~|x{}x~b{}x~}hw~c{}x~}p{}y~|x{}x~^v~X{|b~|b{|b~|b{|b" "~|b{|b~|b{|b~|b{}b~}id~Y{|v~|J{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~f{}v~g{}w~|r{|v~wv~i{|v~|d{}v" "~k{|v~|d{}v~k{|v~|d{}v~k{|v~|d{}v~k{|v~|d{}v~_{}v~}u~|a{|v~|ww~}m{}v~h{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w~}f{|v~h{}w" "~}Z{|v~|V{}w~}sy|s~_w~}n{}u~|b{|u~}|q{}w~|`{|u~}|q{}w~|`{|u~}|q{}w~|`{|u~}|q{}w~|`{|u~}|q{}w~|`{|u~}|q{}w~|j{|u" "~}|q{}a~|kv~N`~|c`~|c`~|c`~|Xv~Lv~Lv~Lv~Wv~jv~`w~}m{|w~}bv~jv~bv~jv~bv~jv~bv~jv~bv~jv~.v~v{|w~tv~a{|w~|m{}w~|a{" "|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|\\v~uv~[w~}k{}w~|^v~uv~ T{}x~}q{}w~q{|x~}j{}x~}b{|x~}j{}x~}vu~|{|u~|w{|x~}j{}" "x~}vu~|n{|x~}j{}x~}b{|x~}[{|w~Qv~|w{|v~ SZ~}`v~x{|y~}'{|]~}iW~|e{|g~}\\{}i~}^w~}kw~}aw~}l{|w~|^{|v~t{|w~}X{|v~x" "{|v~`w~} m{|v~ jw|({}Z~X{|y~|v{}w~}[{}x~}u{}x~}s{|w~o{}w~}o{}u~x{|w~|)v~Fv~ v{}w~ g{}w~Uv~|lv~|W{}w~}P{}v~" "}B{|v~c{|_~|O{}w~}a{}v~l{|v~X{|v~|Y{|v~|lv~|N{|v~ S{|}p~|[{|Z~}[{|}p~}|X{}w~}`{|x~|sw~|nw~|u{|x~}l{}b~}b{}w~}k{" "|v~e{|v~}N{}w~}g{|v~}d{}w~}L{}w~}T{|v~}ev~|h{}w~}hv~|Y{}w~}M{}w~}W{}w~}v{|t~W{}w~}V{}w~|t{|r~sv~|h{}w~|q{}w~}xv" "~i{|v~}dv~}d{}w~}T{|v~}dv~}f{}w~}nv~}J{}v~Y{|v~|Z{|v~|i{}w~}_{|v~vv~|b{}w~}xw~|qw~|y{|v~bv~}v{}v~S{|v~|T{}v~}K{" "|w~}G{}x~}K{|w~| tv~}n{}w~|_v~kv~|bv~|Ov~k{}w~|bv~Bw~}Vv~k{}w~|`w~}m{|w~}Wv~Lv~Tw~}{|u~|Mv~_w~}mv~mv~hw~}m{|w~" "}bv~|kv~`v~k{}w~|dv~k{}w~|Zw~}Iy|}q~Wv~S{|w~|m{}w~|]{|v~uv~_{|w~|xw~uw~|y{|w~}\\r~}T{|w~|w{}w~}T{}v~|M{|v~Kw~|L" "{}w~} O{}y~|rt~|s{|y~}fv~|nw~}\\v~l{|w~}`w~}p{}w~|`v~|kv~^u~}|Qw~}m{|w~}[w~}w{}w~}X{}w~|t{|w~}^{|w~|m{}w~|h{|v~" "pv~pv~|iv~t{}w~t{}w~|b{|w~}q{|w~}`v~t{}w~t{|w~}bv~k{}w~|dv~|l{|v~X{|w~}W{|w~}l{}w~|b{}w~}l{}w~}Z{|v~}R{}w~}T{}v" "~f{}v~i{|u~t{|v~t{|u~g{}w~}hv~|cr~}v~}s~}f{|v~}dv~}j{|u~|@{}w~?u~|b{}~|w{}w~vy~a{}v~|g{}v~}b{}~|w{}w~vy} {{}w~|" "W{|w~}sy~}S{|v~Ow~}q{|w~|`{|a~}){}u~}vw~}0{|y~}v{}w~}p{|t{}y~|d{|j~}[{|v~|vv~}Bw~}7{|y~}tw~t{|w~|u{}y~| P{}w~ " "p{|w~|m{}w~|Ux~}w{|x~} w{|j~}X{}v~v{|v~}X{|w~p{|y~|w{}x~bw~h{}x~|d{|w~p{|y~}w{}x~^v~X{}b~}b{}b~}b{}b~}b{}b~}b{" "}b~}b`~j{}d~Y{|v~}J{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~fv~}g{}w~|q{}w~}xv~i{|v~}dv~}k{|v~}dv~}k" "{|v~}dv~}k{|v~}dv~}k{|v~}dv~}`{}v~|{|u~|b{|v~}x{}x~}lv~}h{|v~|i{}w~}f{|v~|i{}w~}f{|v~|i{}w~}f{|v~|i{}w~}Z{|v~|V" "{}e~|_w~}m{|u~bv~}n{}w~|`v~}n{}w~|`v~}n{}w~|`v~}n{}w~|`v~}n{}w~|`v~}n{}w~|jv~}n{}w~Tv~|Ov~Lv~Lv~Lv~Av~Lv~Lv~Lv~" "Wv~|l{|v~`w~}m{|w~}bv~|kv~bv~|kv~bv~|kv~bv~|kv~bv~|kv~.v~vw~|u{|v~a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}" "w~|\\{|w~|w{}w~}[v~k{}w~|^{|w~|w{}w~} T{|w~q{}w~q{}x~|j{|w~b{}x~|j{|w~wu~|x{|u~|x{}x~|j{|w~wu~|m{}x~|j{|w~b{}x~" "|[{|w~Q{|w~}w{}w~} SZ~}`{}w~|y{}y~|'{|n~y}~|n~}i{}k~x}k~c{|i~}Z{}j~]w~}kw~}a{}w~l{|w~|^{}w~}sv~Wv~|y{}w~}`{}w~|" " mv~| o{}Z~X{|y~|v{|w~}\\{|w~t{}x~|rw~|p{}w~}n{}u~yw~}(v~|Gv~ v{}w~ gw~}U{}w~}m{|v~V{}w~}Q{}v~}A{|v~c{|_~" "|O{}w~}a{}v~l{|v~X{}v~X{|v~k{}w~}N{}w~} Q{|}p~}|^{|Z~}^{|}p~}|U{}w~}`{|x~}sw~|o{|w~|u{}x~|l`~b{}w~}k{|v~|eu~N{}" "w~}g{}v~|d{}w~}L{}w~}Su~ev~|h{}w~}hv~|Y{}w~}M{}w~}W{}w~}u{|t~X{}w~}V{}w~|ss~}sv~|h{}w~|q{|v~|yv~hu~e{|v~|d{}w~}" "Su~e{|v~|f{}w~}n{}v~|K{|v~|Z{|v~|Yv~|i{}w~}^v~|x{}v~a{|v~y{|w~|q{}x~}y{}w~}c{}v~tv~}T{|v~|U{|v~}J{|w~}G{|w~K{|w" "~| u{|v~m{}w~|_v~kv~a{}w~|O{}w~|l{}w~|bv~|Cw~}V{}w~|l{}w~|`w~}m{|w~}Wv~Lv~Tw~}y{|u~|Nv~_w~}mv~mv~hw~}m{|w~}bv~" "|l{|v~`v~kv~cv~|l{}w~|Zw~}D{|}u~}Xv~S{|w~|m{}w~|\\{}w~|w{|w~}^w~}y{|w~u{}x~}y{}w~|]{}q~|Tv~wv~|U{|v~}K{}w~|Lw~|" "Lv~ N{|x~s{}x~{w~|tx~|fv~|o{|v~\\v~l{|w~}a{|w~|p{}w~_{}w~|l{|v~_{}v~|Ow~}m{|w~}[{}w~|xv~X{|v~rv~|_{|w~|m{}w~|h{" "|v~|qv~pv~|iv~|u{}w~t{}w~|b{|w~}q{|w~}`v~t{}w~t{|w~|bv~kv~c{}w~|l{|v~X{|w~}Vv~l{}w~|bv~|l{|v~[{|v~}Q{}w~}T{|v~}" "h{|v~|hu~}u{|v~u{|u~|g{}w~}hv~|b{}f~|du~e{|v~|i{|u~|A{}w~@u~|b{}x~|x{}w~ww~a{}v~|i{}v~}b{}x~|x{}w~w{}y~} {}w~|W" "{|v~sy~}S{|v~O{|w~}s{}w~}^q|}v~q|'{}t~|{|w~}.x~u{}v~}|wy|}y~tx~/{|v~|v{}w~}Cw~}6x~tw~s{}w~ux~ O{}w~ p{|w~|m{}w" "~|Ux~}w{|x~} B{}w~}v{|v~|Ww~|q{|y~}v{}x~c{}x~|i{}x~}cw~|q{|y~}v{}x~_{|v~X`~b`~b`~b`~b`~c{|`~|kc~Xu~J{}w~}M{}w~" "}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~g{|v~}g{}w~|q{|v~|yv~hu~e{|v~|ju~e{|v~|ju~e{|v~|ju~e{|v~|ju~e{|v~|a{}" "v~|x{|u~|bu~y{}w~l{|v~|gv~|i{}w~}ev~|i{}w~}ev~|i{}w~}ev~|i{}w~}Z{|v~|V{}f~|^w~}l{|v~|d{|v~m{}w~|a{|v~m{}w~|a{|v" "~m{}w~|a{|v~m{}w~|a{|v~m{}w~|a{|v~m{}w~|k{|v~m{}w~T{}w~|Ov~|Mv~|Mv~|Mv~|Bv~Lv~Lv~Lv~W{}w~|l{|v~`w~}m{|w~}bv~|l{" "|v~bv~|l{|v~bv~|l{|v~bv~|l{|v~bv~|l{|v~.v~|x{}x~|t{|v~a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|a{|w~|m{}w~|[v~wv~|[v" "~kv~\\v~wv~| Sw~|r{}w~r{|w~hw~|d{|w~hw~|yu~|v{|u~y{|w~hw~|yu~|m{|w~hw~|d{|w~Z{|w~Pv~wv~| SZ~}_w~}yx~%n~{|~{|o~|" "i{|l~}|}|l~}b{}j~Xk~|]w~}kw~}a{}w~l{}w~]v~|s{}w~|X{}w~}yv~|_w~} mv~} g{}x~}t{}x~}O{|y~|uw~}\\{}x~|t{}x~|rw" "~|p{|w~}m{}u~}w~|({}w~|H{|w~} v{}w~ h{|w~|U{}w~}m{|v~V{}w~}R{}v~}@{|v~c{|_~|Ov~|a{|v~l{}w~}Xv~}X{|v~k{}w~}Nv~|" " N{|}p~}|a{|Z~}a{|}p~}|R{|w}|_x~}s{}x~}o{}w~|v{|w~l{}`~|c{}w~}k{|v~|e{}v~|O{}w~}gu~c{}w~}L{}w~}S{}v~|fv~|h{}w~}" "hv~|Y{}w~}M{}w~}W{}w~}t{|t~Y{}w~}V{}w~|s{}t~rv~|h{}w~|p{}w~}yv~h{}v~|f{}v~c{}w~}S{}v~|f{}v~e{}w~}mv~}K{|v~|Z{|v" "~|Yv~|iv~|^{}w~}xv~}`v~|{|w~p{}w~yv~|d{|v~|t{|v~|U{|v~|V{|u~I{|w~}Fw~|L{|w~| u{}w~|mv~|_v~|m{|v~a{}w~}O{}w~|lv" "~|b{}w~|Cw~}V{}w~|lv~|`w~}m{|w~}Wv~Lv~Tw~}x{|u~|Ov~_w~}mv~mv~hw~}m{|w~}b{}w~|l{|w~}`v~kv~c{}w~|lv~|Zw~}B{|u~Xv~" "S{|w~|m{}w~|\\{|w~}w{}w~|^v~y{}x~}u{|x~}y{}w~]{|v~|}v~T{}w~|y{|w~}U{|v~}J{|w~}Lw~|M{|w~} Mx~}v{|w~|{|w~|v{}x~e{" "}w~|o{}v~\\v~l{|w~}a{|w~|pw~}_{}w~|l{|w~}_v~Mw~}m{|w~}[{|w~}y{|w~}X{}w~|r{}w~}_{|w~|m{}w~|h{|v~|qv~|r{|v~|i{}w~" "|u{}w~tv~|b{|w~}q{|w~}`v~t{}w~t{}w~|bv~kv~c{}w~|l{|w~}X{|w~}Vv~lv~b{}v~jv~|\\u~P{}w~}S{}v~|iu~g{|t~|w{|v~v{}u~}" "f{}w~}hv~|a{}h~|c{}v~|f{}v~g{|u~|B{}w~Au~|b{}v~|y{}w~xu~a{}v~|k{}v~}b{}v~|y{}w~x{}w~}!{}w~|Vv~sy~}S{|v~O{|u~}y|" "{y|u~}T{|w~}Lw}|P{|}p~}-{|y~}u{}l~u{}y~|.{|v~|v{}w~}Dw~}6{|y~}uw~rw~}w{}y~| O{}w~ p{|w~|m{}w~|Ux~}w{|x~} C{}w" "~}v{|v~|W{}x~}px~u{}x~d{|w~i{}x~}c{}x~}px~u{}x~_{}w~}Y{}`~|d{}`~|d{}`~|d{}`~|d{}`~|d{}w~}j|}w~}l{|c~X{}v~|K{}w~" "}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~gu~|g{}w~|p{}w~}yv~h{}v~|f{}v~i{}v~|f{}v~i{}v~|f{}v~i{}v~|f{}v~" "i{}v~|f{}v~a{}v~|v{|u~|c{}v~|}w~|l{}v~fv~|iv~|ev~|iv~|ev~|iv~|ev~|iv~|Z{|v~|V{}h~}\\w~}k{}w~|d{}w~|mv~|a{}w~|mv" "~|a{}w~|mv~|a{}w~|mv~|a{}w~|mv~|a{}w~|mv~|k{}w~|mv~|U{}w~}O{}w~|M{}w~|M{}w~|M{}w~|Bv~Lv~Lv~Lv~W{}w~}l{}w~}`w~}m" "{|w~}b{}w~|l{|w~}b{}w~|l{|w~}b{}w~|l{|w~}b{}w~|l{|w~}b{}w~|l{|w~}.{}w~|y{}x~|s{|w~}a{|w~|m{}w~|a{|w~|m{}w~|a{|w" "~|m{}w~|a{|w~|m{}w~|[{}w~|y{|w~}Zv~kv~\\{}w~|y{|w~} R{|w~r{}w~rw~}h{|w~dw~}h{|w~y{|w~|t{|w~}yw~}h{|w~y{|w~|lw~}" "h{|w~dw~}Z{|w~P{}w~|y{|w~} Rs}v~g}|_{}w~{|y~}%{|p~|{|~yp~}g{}m~{}~{}m~|a{}l~|X{|m~}\\w~}kw~}a{|w~|mv~]v~r{}w~}X" "{|v~{|v~^{}w~} n{}v~ gw~|tw~|O{|y~|uw~}]{|x~}sw~|rw~|p{|v~l{}r~}'{|w~}H{|w~} v{}w~ h{|w~T{|v~m{}w~}V{}w~}" "S{}v~}?{|v~c{|_~|Ov~|`v~|m{}w~}Y{|v~W{|v~k{}w~}O{|v~ J{|}p~}|d{|Z~}d{|}p~}|-w~s{|w~ov~|v{}x~|lv~|j{|v~c{}w~}k{}" "v~cv~}O{}w~}h{}v~|c{}w~}L{}w~}Rv~}fv~|h{}w~}hv~|Y{}w~}M{}w~}W{}w~}rt~Z{}w~}V{}w~|ru~}rv~|h{}w~|p{|v~|{v~h{|v~}g" "{|v~}c{}w~}Rv~}g{|v~}e{}w~}m{|v~|L{|v~|Z{|v~|Y{}w~}j{|v~|^{|v~|{|v~_{}w~}{}x~}p{|w~yv~cv~}r{}v~U{|v~|W{|u~|I{|w" "~}F{}x~}L{|w~| u{}w~|n{|v~|_v~}m{}w~}a{|w~}O{|w~}m{|v~|b{}w~}Cw~}V{|w~}m{|v~|`w~}m{|w~}Wv~Lv~Tw~}vu~|Pv~_w~}mv" "~mv~hw~}m{|w~}b{|w~}l{}w~}`v~|m{|w~}c{|w~}lv~|Zw~}@v~|Yv~S{|w~}mv~|[v~wv~]{}w~|{w~|u{|w~yw~}]v~}y{}v~U{|w~}y{}w" "~|V{|v~}I{|w~}Lw~|M{|w~} M{|w~x}v~}x{}v~x}w~|e{}w~}ou~|]v~l{|w~|a{|w~p{}w~|_{|w~}l{}w~}`{|w~}Mw~}m{|w~}Zv~y{}w~" "|Y{|v~q{|v~_{|w~}m{}w~|gv~|r{|v~|r{|v~h{}w~}u{}w~tv~a{|w~}q{|w~}`v~t{}w~t{}w~|bv~|m{|w~}c{|w~}l{}w~}X{|w~}V{}w~" "|n{|w~}bv~}j{}v~]{}v~|P{}w~}Ru~j{}v~|f{|t~}|y{|v~x{|t~}e{}w~}hv~|`{|}l~}`v~}g{|v~}f{|u~|C{}w~Bu~|`u~|{}w~yu~|`{" "}v~|m{}v~}a{|u~|{}w~y{}v~}!{}w~|Vv~|ty~}S{|v~P{|g~}U{|w~}Lw~|N{|r~}+{}y~|u{|}o~}v{|y~}+v~}v{}v~Ew~}5{}y~|vw~r{|" "w~|y{|y~} N{}w~ p{|w~}m{}w~|Ux~}w{|x~} Dv~}v{}v~|W{|w~p{}y~|u{}x~dw~|j{}w~c{|w~p{}y~|u{}x~`{}v~|Yv~|j{|v~dv~|" "j{|v~dv~|j{|v~dv~|j{|v~dv~|j{|v~dv~|j{|v~l{}w~}n{|v~Wv~}K{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~h{" "|v~}f{}w~|p{|v~|{v~h{|v~}g{|v~}i{|v~}g{|v~}i{|v~}g{|v~}i{|v~}g{|v~}i{|v~}g{|v~}b{}v~|t{|u~|cq~|l{|v~}f{}w~}j{|v" "~|e{}w~}j{|v~|e{}w~}j{|v~|e{}w~}j{|v~|Z{|v~|V{}k~}|Zw~}k{}w~}d{}w~|n{|v~|a{}w~|n{|v~|a{}w~|n{|v~|a{}w~|n{|v~|a{" "}w~|n{|v~|a{}w~|n{|v~|k{}w~|n{|v~}U{|w~}O{}w~}M{}w~}M{}w~}M{}w~}Bv~Lv~Lv~Lv~W{|v~lv~|`w~}m{|w~}b{|w~}l{}w~}b{|w" "~}l{}w~}b{|w~}l{}w~}b{|w~}l{}w~}b{|w~}l{}w~}Xt|X{}w~}{}x~}r{}w~}a{|w~}mv~|a{|w~}mv~|a{|w~}mv~|a{|w~}mv~|[{|w~}y" "{}w~|Zv~|m{|w~}\\{|w~}y{}w~| Qw~}s{}w~s{}w~fw~}f{}w~fw~}y{|y~|r{|y~}y{}w~fw~}y{|y~|l{}w~fw~}f{}w~Y{|w~P{|v~y{}w" "~| Kv~}J{|w~|}y~|${}r~}y{}~y{|q~f{|n~|{}~yn~}_m~|V{|o~}[w~}kw~}`w~}n{|w~}^{|w~}r{|v~Wv~{}w~}]v~| o{|v~| hw" "~t{|w~N{|y~|uw~}]w~|s{}x~|rw~|ov~|l{}s~&{|w~}H{}w~| v{}w~ h{}x~}Sv~|nv~|V{}w~}T{}v~}>{}w~}Q{}w~}J{}v~_{}w~}mv~" "}Y{}w~}Vv~|lv~|Ov~} G{|}p~}|0{|}o~}*{}x~rw~}q{}v~|w{}w~l{|v~hv~|d{}w~}ku~c{}v~}P{}w~}i{}u~b{}w~}L{}w~}R{}v~|gv~" "|h{}w~}hv~|Y{}w~}M{}w~}W{}w~}qt~[{}w~}V{}w~|r{}v~|rv~|h{}w~|o{}w~}{v~g{}v~|hu~|c{}w~}R{}v~|hu~|e{}w~}lv~}L{}v~Y" "{|v~|Y{}v~j{}v~\\{}w~}{}w~}_{|v~{w~|ow~y|v~d{}v~pv~}V{|v~|Wu~|H{|w~}F{|w~L{|w~| u{}w~m{}v~|_u~mv~|a{|v~Nv~|n{}" "v~|b{|v~Cw~}Uv~|n{}v~|`w~}m{|w~}Wv~Lv~Tw~}uu~|Qv~_w~}mv~mv~hw~}m{|w~}b{|v~lv~|`v~}m{}w~}c{|v~m{|v~|Zw~}@{}w~|Yv" "~S{|w~}mv~|[{}w~|y{|w~}]{|w~}{w~sw~y|w~}^{}w~}wv~}U{}w~yv~Uv~}Gw~}Lw~|M{|w~| L{|q~}v{}q~|d{|w~}p{|u~|]v~l{}w~|a" "{|w~pv~^{|v~lv~|`{|w~|Mw~}m{|w~}Z{}w~y|v~X{}w~}pv~|`{|w~}mv~|gv~}r{|v~}r{}v~h{|v~u{}w~u{|w~}a{|w~}q{|w~}`{}w~|u" "{}w~tv~av~}m{}w~}c{|v~lv~|X{|w~}V{|w~}n{}w~|c{|v~i{|v~|_{}v~}O{}w~}R{|v~}l{}v~|d{|r~y}v~y}s~}d{}w~}hv~|]{|}s~y}" "|^{}v~|hu~|e{|v~}C{}w~C{}v~|^u~|}w~{}v~|^{}v~n{|v~}_{|u~|}w~{}v~} {}w~|V{}w~}ty~}S{|v~Q{}e~}V{|w~}Lw~|L{|t~*{|x" "~|t{|y}u~}|u{|x~|*{}w~|v{|v~Fw~}5{|x~|ww|qw|y{|x~| >{|w~}mv~|Ux~}w{|x~} Ev~}v{|v~U{}x~|q{|y~}t{}x~e{}x~}j{}w" "~b{}x~|q{|y~}t{}x~a{}v~}Y{|v~hv~|f{|v~hv~|f{|v~hv~|f{|v~hv~|f{|v~hv~|f{}v~hv~|n{|v~|n{|v~W{}v~}L{}w~}M{}w~}M{}w" "~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~i{|u~|f{}w~|o{}w~}{v~g{}v~|hu~|h{}v~|hu~|h{}v~|hu~|h{}v~|hu~|h{}v~|hu~|c{}" "v~|r{|u~|d{}s~|ku~|f{}v~j{}v~d{}v~j{}v~d{}v~j{}v~d{}v~j{}v~Y{|v~|V{}w~}r|Vw~}k{|w~|d{}w~m{}v~|a{}w~m{}v~|a{}w~m" "{}v~|a{}w~m{}v~|a{}w~m{}v~|a{}w~m{}v~|k{}w~m{}u~U{|v~O{|v~M{|v~M{|v~M{|v~Bv~Lv~Lv~Lv~Vv~|n{|v~_w~}m{|w~}b{|v~lv" "~|b{|v~lv~|b{|v~lv~|b{|v~lv~|b{|v~lv~|X{}u~X{|v~|x~}qv~|a{|w~}mv~|a{|w~}mv~|a{|w~}mv~|a{|w~}mv~|Z{}w~yv~Yv~}m{}" "w~}[{}w~yv~ P{|w~}t{}w~t{|w~}f{|w~}h{|w~}f{|w~}yy|p{|}y{|w~}f{|w~}yy|l{|w~}f{|w~}h{|w~}Y{|w~Ov~y|v~ K{}w~}Hw~}y" "~}\"{}t~}x{}~x{|s~d{|p~}y{}~y{|p~}]o~|T{}p~Zw~}kw~}`{}w~|o{}w~|^{}w~|qv~|X{}w~|v~|]{|v~| o{}v~j{} {|x~}t{|" "x~}N{|y~|v{}w~}^{}x~}r{}x~}rw~|o{}v~k{}u~|%v~Hv~ u{}w~ hw~|S{}v~o{}v~U{}w~}U{}v~}>{|v~}Q{}w~}Ju~_{|v~n{|v~|Z{|" "v~|Vv~}m{|v~|P{}v~ C{}o~}4{|o~}|({|x~}s{}w~}s{}u~|x{}w~|l{}w~}h{}w~}d{}w~}l{|v~}bu~|g{|}g{}w~}j{}u~|b{}w~}L{}w~" "}R{|u~|hv~|h{}w~}hv~|Y{}w~}M{}w~}W{}w~}pt~\\{}w~}V{}w~|r{|v}qv~|h{}w~|nv~|v~g{|u~|j{}v~}b{}w~}R{|u~i{}v~}d{}w~}" "l{|v~|M{}v~Y{|v~|Y{|v~|kv~}\\{|v~{v~|_{|v~|w~|o{}x~y}w~}e{|v~|p{|v~|W{|v~|X{}v~}G{|w~}F{|w~|M{|w~| u{}w~|nu~|_" "u~}o{}v~_v~}O{}w~}o{|u~|av~}Dw~}U{}w~}o{|u~|`w~}m{|w~}Wv~Lv~Tw~}t{}v~|Rv~_w~}mv~mv~hw~}m{|w~}av~|n{|v~_u~mv~|bv" "~|n{}v~|Zw~}@{}w~|Yv~Rv~n{}v~|[{|w~}y{}w~|\\w~}|x~}s{}x~y}w~|_{}v~v{|v~|V{|w~y}w~}Vu~Fw~}Lw~|M{|w~| K{|s~}t{}s~" "|bv~p{}u~}]v~|mv~`{|w~q{}w~}]v~}n{}v~_{|w~|Mw~}m{|w~}Yw~y}w~|Xv~o{|w~}`{|v~n{|v~|g{}v~r{}u~rv~}gv~|v{}w~uv~|a{|" "w~}q{|w~}`{|w~}u{}w~u{|v~au~mv~|bv~}n{}v~Vv~Uv~nv~b{}w~}hv~}`{|v~}N{}w~}Q{|v~}n{}v~}b{|c~}c{}w~}hv~|Z{|v~Z{|u~|" "j{}v~}c{|w~B{}w~B{}x~|\\u~}w~}v~|\\{}x~|m{}x~}]{|u~}w~}v~} {{v~|V{|v~|uy~}S{|v~R{}v~y|q~}|u~W{|w~}Lw~|J{}u~*{|x" "~|e{|x~|({}x~}u{|w~F{|x}|4{|x~|e{|x~| ={|v~n{|v~|Ux~}w{|x~} Ew~|u{|x~}U{|x~}p{}j~}iw~j{}w~b{|x~}p{}j~}f{}v~}" "X{}w~}h{}w~}f{}w~}h{}w~}f{}w~}h{}w~}f{}w~}h{}w~}f{}w~}h{}w~}fv~}h{}w~}n{}w~}m{|v~Vu~|g{|}c{}w~}M{}w~}M{}w~}M{}w" "~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~j{|u~}e{}w~|nv~|v~g{|u~|j{}v~}g{|u~|j{}v~}g{|u~|j{}v~}g{|u~|j{}v~}g{|u~|j{}v~}c{" "}v~|p{|u~|e{|t~}k{}v~}e{|v~|kv~}d{|v~|kv~}d{|v~|kv~}d{|v~|kv~}Y{|v~|V{}w~}Mw~}k{}w~|d{}w~|nu~|a{}w~|nu~|a{}w~|n" "u~|a{}w~|nu~|a{}w~|nu~|a{}w~|nu~|k{}w~|nt~|Uv~}Ov~}Mv~}Mv~}Mv~}Cv~Lv~Lv~Lv~V{}v~nv~}_w~}m{|w~}av~|n{|v~`v~|n{|v" "~`v~|n{|v~`v~|n{|v~`v~|n{|v~W{}u~Wr~q{|v~_v~n{}v~|`v~n{}v~|`v~n{}v~|`v~n{}v~|Z{|w~y}w~}Yu~mv~|[{|w~y}w~} O{}w~}" "u{}w~u{}w~}d{}w~}j{}w~}d{}w~}j{}w~}d{}w~}j{}w~}d{}w~}j{}w~}X{}w~O{|w~y}w~} L{}w~}G{}u~|!{|}x~}|w{}~v{}w~}b{|r~|" "x{}~w{}s~|\\{|q~}Rq~|Zw~}kw~}`{|v~p{|v~]v~p{}w~}X{|q~[{}v~} p{|v~}ly}$v}|\"{}x~}t{}x~}Yy}|s{|y~|w{|v~|_{|w~" "q{}x~}s{|w~n{|v~}l{|u~}%{}w~|Iw~} u{}w~L{}w~} tv}|P{|w~R{|v~|pv~}U{}w~}V{}v~}={}v~|Q{}w~}K{}v~|^v~|o{}v~Y{}v~U{" "}v~m{}v~P{|v~}U{|v}M{}w~}F{|}q~}6{|q~}|G{|w}|^w~ru~y|x{|}t~y|}v~|kv~|h{|v~d{}w~}m{|u~|b{|u~|i{|~}g{}w~}l{|}u~}a" "{}w~}L{}w~}Q{}u~|iv~|h{}w~}hv~|Y{}w~}M{}w~}W{}w~}ot~]{}w~}V{}w~|bv~|h{}w~|n{}q~f{}u~k{}u~a{}w~}Q{}u~k{|u~c{}w~}" "kv~}c{|}h{|v~}Y{|v~|X{}v~l{}v~|[v~}v~]v~}w~n{}r~|ev~}n{}v~W{|v~|Y{}v~}F{|w~}Ew~}M{|w~| u{}w~|o{}u~|_t~|q{|v~}_" "{|v~|P{|v~}pt~|a{|v~|Ew~}U{|v~|pt~|`w~}m{|w~}Wv~Lv~Tw~}s{}v~|Sv~_w~}mv~mv~hw~}m{|w~}a{}v~nv~}_u~}o{}v~a{}v~o{|u" "~|Zw~}@{}w~|Y{}w~|Sv~|p{|u~|Zv~{|v~[v~}x~}s{|r~_{|v~|u{}v~Uq~V{}v~|Fw~}Lw~|M{|w~| I{|y}~y}|r{|}x~}|`{}w~}qs~]u~" "n{|v~`{|w~r{|v~\\{|v~nv~}_{|w~}Mw~}m{|w~}Y{}r~X{}w~}nv~`{|v~|o{}v~|g{|v~|st~|t{|v~|g{}v~v{}w~v{|v~`{|w~}q{|w~}_" "v~|v{}w~uv~}au~}o{}v~a{|v~nv~}Vv~U{|w~}p{}w~}bv~|h{|v~`u~M{}w~}P{|u~|q{}v~}_{}g~}|b{}w~}hv~|Z{|v~Y{}u~k{}u~a{|y" "~A{}w~A{}~|Zl~|Z{}~|k{}~}[{|l~} yv~}Uv~}uy~}S{|v~S{}v~|x{|y}x~}|wu~X{|w~}Lw~|I{|v~}*{}x~|g{|x~}&{}y~}t{|x~ T{}x" "~|g{|x~} <{|v~|o{}v~|Ux~}w{|x~} Ex~|t{|y~}Tw~|p{}j~}j{}x~|k{}x~}aw~|p{}j~}g{}v~}Wv~|h{|v~fv~|h{|v~fv~|h{|v~f" "v~|h{|v~fv~|h{|v~g{|v~g{|v~|ov~|m{|v~V{|u~|i{|~}c{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~k{}t~d{}w~" "|n{}q~f{}u~k{}u~e{}u~k{}u~e{}u~k{}u~e{}u~k{}u~e{}u~k{}u~c{}v~|n{|u~|e{}u~|l{}u~c{}v~l{}v~|c{}v~l{}v~|c{}v~l{}v~" "|c{}v~l{}v~|Y{|v~|V{}w~}Mw~}kv~c{}w~|o{}u~|a{}w~|o{}u~|a{}w~|o{}u~|a{}w~|o{}u~|a{}w~|o{}u~|a{}w~|o{}u~|k{}w~|o{" "}s~U{|v~|P{|v~|N{|v~|N{|v~|N{|v~|Dv~Lv~Lv~Lv~Uv~}p{}v~^w~}m{|w~}a{}v~nv~}`{}v~nv~}`{}v~nv~}`{}v~nv~}`{}v~nv~}W{" "}u~W{}t~|qv~}_v~|p{|u~|`v~|p{|u~|`v~|p{|u~|`v~|p{|u~|Yq~Xu~}o{}v~Yq~ M{}w~}|w{}x~}v{}v~b{}w~}|m{}v~b{}w~}|m{}v~" "b{}w~}|m{}v~b{}w~}|m{}v~W{}x~}Nq~| M{|v~F{|u~ py~|V{|}y~y}|vy~|w{|y}y~y}Y{|s~}Q{|s~|Yw~}kw~}_{}v~|s{}v~|^{|w~}p" "{|v~X{|r~}Z{}u~} q{}v~}o{|y~}$v~}\"w~|tw~|Y{}y~}|u{|y~|x{|u~^{}x~|q{|w~s{}x~}mu~}n{|s~}&{|w~|J{|w~| u{}w~L{" "}v~ u{|v~|P{}x~}Q{}v~|r{}v~T{}w~}W{}v~}O{}|k{}v~}P{}w~}]{}|l{}u~]{|v~|q{}v~|Yv~}U{|v~}o{}v~}Q{|v~}T{}v~M{}v~C{|" "}t~}6{|t~}|D{}w~}^{}x~|s{|m~y}q~|k{|v~fv~|e{}w~}n{|u~}`{}u~|l{|}y~}g{}w~}n{|}t~}`{}w~}L{}w~}P{}u~}jv~|h{}w~}hv~" "|Y{}w~}M{}w~}W{}w~}nt~^{}w~}V{}w~|bv~|h{}w~|mq~e{}u~|n{}u~|a{}w~}P{}u~|n{}u~|c{}w~}k{|v~|d{|y~}k{|u~|Y{|v~|X{|u" "~n{|u~Z{}r~}]{}s~}n{|r~e{}v~lv~}X{|v~|Z{|u~E{|w~}E{}w~M{|w~| u{|v~p{|t~|_s~|s{|u~]u~|P{}v~}s{|s~|`u~|k{|Ww~}T{" "}v~}s{|s~|`w~}m{|w~}Wv~Lv~Tw~}r{}v~}Tv~_w~}mv~mv~hw~}m{|w~}`v~}p{}v~|_t~|q{|v~|`v~}q{|t~|Zw~}Q{|kv~|Y{}w~}S{}v~" "pt~|Z{}w~y}w~}[{}s~|rs~}_v~}s{}w~}V{}s~}W{}v~|Ew~}Lw~|M{|w~| r{|v~|s{}s~}^u~}ov~|_w~|s{}w~|[v~}pu~]v~|Nw~}m{|w" "~}Y{|s~}Xv~m{}w~|a{|u~p{|u~|fv~}t{}x~}x~}t{}v~ev~}w{}w~w{|v~}`{|w~}q{|w~}_{}v~|w{}w~v{}v~`t~|q{|v~|`v~}p{}v~U{}" "w~|Uv~|r{|v~b{|v~fv~|bu~|M{}w~}O{|u~}t{|u~}\\{|k~}|`{}w~}hv~|Z{|v~X{}u~|n{}u~|`{|@{}w~@{|Xn~|X{|i{|Y{|n~} xv~}U" "{|v~}vy~}S{|v~T{|v~|jv~}Y{|w~}Lw~|H{|v~|*{}x~}i{}x~}${}~}s{|y~ S{}x~}i{}x~} ;{|u~p{|u~|Ux~}w{|x~} Ey~|s{|~}T" "{}x~}o{}j~}k{|w~k{}x~}a{}x~}o{}j~}h{}v~}W{|v~fv~|h{|v~fv~|h{|v~fv~|h{|v~fv~|h{|v~fv~|h{}w~}f{}w~}p{|v~l{|v~U{}u" "~|l{|}y~}c{}w~}M{}w~}M{}w~}M{}w~}D{}w~}M{}w~}M{}w~}M{}w~}Z{|v~n{|}s~c{}w~|mq~e{}u~|n{}u~|d{}u~|n{}u~|d{}u~|n{}u" "~|d{}u~|n{}u~|d{}u~|n{}u~|d{}v~|l{|u~|et~|n{}u~|c{|u~n{|u~b{|u~n{|u~b{|u~n{|u~b{|u~n{|u~X{|v~|V{}w~}Mw~}x{|p{}v" "~c{|v~p{|t~|a{|v~p{|t~|a{|v~p{|t~|a{|v~p{|t~|a{|v~p{|t~|a{|v~p{|t~|k{|v~p{|q~j{|gu~|Pu~|k{|_u~|k{|_u~|k{|_u~|k{" "|Vv~Lv~Lv~Lv~U{|v~}r{}v~}^w~}m{|w~}`v~}p{}v~|_v~}p{}v~|_v~}p{}v~|_v~}p{}v~|_v~}p{}v~|W{}u~Vu~|q{}v~|_{}v~pt~|`{" "}v~pt~|`{}v~pt~|`{}v~pt~|Y{}s~}Xt~|q{|v~|Y{}s~} Lu~}p{}u~|au~}p{}u~|au~}p{}u~|au~}p{}u~|au~}p{}u~|W{}x~}N{}s~} " "M{|v~|Ev~} py~|Jy~|M{}t~O{|u~}Xw~}kw~}_{|t~}w|}u~}]{}w~}ov~|Xr~|Y{}t~}y| tt~|r{}x~}$v~}\"w~t{|w~X{}v~}y|y{|" "y~y|}t~|_{|x~}ow~}tw~|m{|t~|r{|}q~}&w~}J{}w~ t{}w~L{}v~ u{|v~|Pw~|Pu~|t{}v~|\\s|}w~}r|a{}v~}Nx~}|p{}t~O{}w~}]{}" "y~}|q{}t~|\\{}v~|s{}u~Y{|v~|T{}u~|r{}u~|_{~}|r{|}u~|T{}v~M{}v~@{|}w~}6{|w~}|A{}w~}^{|w~r{|o~}{}s~}iv~}f{}w~}e{}" "w~}q|y}s~|_{}t~|p{|}w~}g{}w~}r|y}q~}_{}w~}g|`{}w~}O{}t~}o{|}u~|h{}w~}hv~|Y{}w~}M{}w~}W{}w~}mt~_{}w~}h|i{}w~|bv~" "|h{}w~|m{}r~dt~}|r{|t~|`{}w~}Ot~}q{|t~}b{}w~}jv~}d{|w~}|p{|}u~}X{|v~|W{}u~|q{}u~|Z{|r~|]{|s~|mr~f{|v~|l{|v~|Y{|" "v~|[{|u~}b|^{|w~}E{|w~|N{|w~| tv~}r{}s~|_w~y}x~}|w{|}u~|]{|u~|p{|}|^t~y|x{|}w~}w~|`{|u~|n{|y~|Xw~}St~y|x{|}w~}" "w~|`w~}m{|w~}Wv~Lv~Tw~}q{}v~}Uv~_w~}mv~mv~hw~}m{|w~}`{}v~}r{}v~}^s~}s{|v~}_{}v~}s{|s~|Zw~}Qy~}|o{}w~}X{|v~}|U{|" "v~}s{|s~|Z{|q~Z{|s~qs~|`{}w~}qv~}Vs~|X{}v~|Dw~}Lw~|M{|w~| qu~|u{}w~|v~}_s~|s{|u~^{}w~t{}w~}Z{|v~}|t{|}v~|]{}v~" "|ny|^w~}m{|w~}Xs~|Y{}w~}m{|w~}a{|t~|s{}t~}f{}v~}v{|w~{w~|v{}v~}e{}v~}x{}w~x{}u~_{|w~}q{|w~}^u~}|y{}w~x{}u~}`s~}" "s{|v~}_{|v~}|t{|}v~|U{|v~}|W{|v~|t{|v~|bu~f|v~}c{}v~}h|_{}w~}Vs}t~}v{}t~s}`{|y}t~y}|]{}w~}hv~|Z{|v~Wt~}|r{|t~|#" "{}w~ vp~| {|p~} wv~}T{}v~}wy~}v{}~Z{|v~S{}x~|hx~}X{|w~}Lw~|G{}w~}){|w~|m{|w~|\"{|}q{} R{|w~|m{|w~| XY| ${|u~}r{" "|t~}Ux~}w{|x~} E{}qy|T{|w~c{}x~gw~|lw~}a{|w~c{}x~e{}v~}Vv~}f{}w~}hv~}f{}w~}hv~}f{}w~}hv~}f{}w~}hv~}f{}w~}hv~|f" "{|v~pv~}l{|v~}h|h{}t~|p{|}w~}c{}w~}g|a{}w~}g|a{}w~}g|a{}w~}g|X{}w~}M{}w~}M{}w~}M{}w~}Z{|v~r|x}q~b{}w~|m{}r~dt~}" "|r{|t~|bt~}|r{|t~|bt~}|r{|t~|bt~}|r{|t~|bt~}|r{|t~|d{|v~|j{|v~}f{}s~}|r{|t~|a{}u~|q{}u~|a{}u~|q{}u~|a{}u~|q{}u~" "|a{}u~|q{}u~|X{|v~|V{}w~}Mw~}xy~}y|wy|u~|bv~}r{}s~|`v~}r{}s~|`v~}r{}s~|`v~}r{}s~|`v~}r{}s~|`v~}r{}s~|jv~}r{}w~}" "|u~|o{|}y~g{|u~|p{|}|_{|u~|n{|y~|`{|u~|n{|y~|`{|u~|n{|y~|`{|u~|n{|y~|Wv~Lv~Lv~Lv~T{}u~}|x{|}u~}]w~}m{|w~}`{}v~}" "r{}v~}^{}v~}r{}v~}^{}v~}r{}v~}^{}v~}r{}v~}^{}v~}r{}v~}V{}u~V{|v~}r{}v~}^{|v~}s{|s~|`{|v~}s{|s~|`{|v~}s{|s~|`{|v" "~}s{|s~|Xs~|Xs~}s{|v~}Ws~| K{}u~}x|{x|}t~^{}u~}x|{x|}t~^{}u~}x|{x|}t~^{}u~}x|{x|}t~^{}u~}x|{x|}t~U{}x~}N{|s~| M" "{|w~|D{}w~| q{|y~}K{|y~}L{}v~|N{}v~Ww~}kw~}^{|j~}\\v~|o{}w~}X{}s~W{|^~} -s~}v|}v~}$v~}#{|w~t{|x~}X{}e~|^w~|o" "{|w~|v{}w~k{|s~}v|}t~y}v~}'{}w~Jw~} t{}w~L{}v~ u{|v~|Q{|w~O{|u~}w|}u~}\\{|e~|ab~`u~w}|x}r~|O{}w~}]{}v~w}|x}s~}Z" "t~}w|}t~X{}w~}S{|t~y}v|}t~}^v~y}y|y}s~|S{}v~M{}v~={|}~}6{|y~}|?{}w~}]w~}q{}r~|y{}u~}h{|v~|f{|v~e{}c~|]{}s~y}v|y" "}t~}g{}b~|^{}c~}`{}w~}N{}r~y}v|y}r~|h{}w~}hv~|Y{}w~}M{}w~}W{}w~}lt~`{}d~}i{}w~|bv~|h{}w~|lr~cr~}v|}s~}_{}w~}Ns~" "y}v|}s~}a{}w~}j{|v~|e{|s~}u|}r~W{|v~|Vs~}v|y}t~|Xs~}\\{|s~|m{}t~}fv~}j{}v~Y{|v~|[{}\\~}^{|w~}Dw~}N{|w~| t{}u~y" "|x{|}w~y}w~|_w~}{k~|[{|t~}|wy|}x~|^{|k~y|w~|_{|t~}|vy|y}w~|Xw~}S{|k~y|w~|`w~}m{|w~}Wv~Lv~Tw~}p{}v~}Vv~_w~}mv~mv" "~hw~}m{|w~}_{}u~}|x{|}u~}]w~y}w~y|yy|}u~|^{}u~}|x{|}w~}w~|Zw~}Qv~}y|v{|}u~|Wm~[{}u~}w|}v~}w~|Y{}s~}Yt~}q{}t~|a{" "}v~p{|v~|W{}t~W{}d~Uw~}Lw~|M{|w~| q{|u~}|y{|}v~{|s~br~}y|yy|}u~|^{|w~}v{}v~X{}u~}y|{y|}u~}\\{|t~}|vy|y}y~}^w~}" "m{|w~}X{}t~Xv~|lv~|b{|s~}v|}q~x}hu~}|{y|w~}{}w~}|{|}u~c{}u~}|}w~|}t~|_{|w~}q{|v~}_{|s~}v~}s~}_w~y}w~y|yy|}u~|^{" "}u~}y|{y|}u~}S{}r~}Z{}v~}|x{|}v~}b{|Z~c{}c~}_{}w~}Vk~v{}l~|^{|v~Y{}w~}hv~|Z{|v~Vr~}v|}s~|\"{}w~ ur~| y{|r~} vv~" "}St~}y|y~}{y|}x~`{}b~}a{}~|f{~}W{|w~}Lw~|G{|w~}({|v~}|s{|}v~| E{|v~}|s{|}v~| X{|Z~} ${|s~}y|{y|}q~}|}Xx~}w{|x~" "} l{}x~|c{}x~h{}x~}m{|w~|`{}x~|c{}x~f{|v~}V{|v~|f{|v~i{|v~|f{|v~i{|v~|f{|v~i{|v~|f{|v~i{|v~|f{|v~i{|v~dv~|r{|" "v~k{|b~g{}s~y}v|y}t~}c{}c~}a{}c~}a{}c~}a{}c~}X{}w~}M{}w~}M{}w~}M{}w~}Z{|b~}a{}w~|lr~cr~}v|}s~}`r~}v|}s~}`r~}v|}" "s~}`r~}v|}s~}`r~}v|}s~}b{|x~|h{|x~}f{}o~}v|}s~}_s~}v|y}t~|_s~}v|y}t~|_s~}v|y}t~|_s~}v|y}t~|W{|v~|V{}w~}Mw~}xk~}" "a{}u~y|x{|}w~y}w~|`{}u~y|x{|}w~y}w~|`{}u~y|x{|}w~y}w~|`{}u~y|x{|}w~y}w~|`{}u~y|x{|}w~y}w~|`{}u~y|x{|}w~y}w~|j{}" "u~y|x{|}u~y{|t~}|vy|}v~f{|t~}|wy|}x~|^{|t~}|vy|y}w~|_{|t~}|vy|y}w~|_{|t~}|vy|y}w~|_{|t~}|vy|y}w~|Wv~Lv~Lv~Lv~S{" "}j~}\\w~}m{|w~}_{}u~}|x{|}u~}\\{}u~}|x{|}u~}\\{}u~}|x{|}u~}\\{}u~}|x{|}u~}\\{}u~}|x{|}u~}U{}u~V{}t~}|x{|}u~}\\{" "}u~}w|}v~}w~|_{}u~}w|}v~}w~|_{}u~}w|}v~}w~|_{}u~}w|}v~}w~|X{}t~Ww~y}w~y|yy|}u~|W{}t~ I{}h~}\\{}h~}\\{}h~}\\{}h~" "}\\{}h~}T{}x~}Ms~ K{|y~}C{|w~ p{}x~K{}x~Kw~|L{}x~|Ww~}kw~}]{|l~}\\{|v~n{|w~}X{|s~U{}`~} -{|h~|$v~}#{}x~}t{}x" "~}X{|}g~|^{}x~}m{}w~}y|}v~|j{|g~}y{}v~}({|w~|L{|w~| t{}w~L{}v~ u{|v~|Q{}x~}N{}k~}[{|e~|ab~`e~|N{}w~}]{}g~}Y{|i~" "|Xv~|R{|g~}]i~|R{}v~M{}v~;y|5{|<{}w~}]{|w~|p{|v}|w{|x}|e{}v~dv~}f{}e~}|[{}d~|g{}d~}\\{}c~}`{}w~}M{}c~}|g{}w~}hv" "~|Y{}w~}M{}w~}W{}w~}kt~a{}d~}i{}w~|bv~|h{}w~|l{|s~b{}f~|^{}w~}M{}f~|`{}w~}iv~}e{|c~V{|v~|Uf~}W{}t~|[s~l{}t~|g{}" "v~hv~}Z{|v~|[{}\\~}^{|w~}D{}w~N{|w~| sj~{}w~|_w~}{|m~|Y{}i~|]{|m~|{|w~|^{|f~|Xw~}R{|m~|{}w~|`w~}m{|w~}Wv~Lv~Tw" "~}o{}v~}Wv~_w~}mv~mv~hw~}m{|w~}^h~\\w~}{k~|\\k~y|w~|Zw~}Qg~}V{|n~Zk~{}w~|Y{|s~|Y{}u~}q{|t~a{|v~|o{}v~W{|u~|W{}d" "~Uw~}Lw~|M{|w~| p{|l~|ys~be~}\\{}v~x}u~V{}j~}Z{|h~}^w~}m{|w~}X{|u~|Y{|w~}k{}w~}b{|w~}m~|s~h{|m~xm~|b{}g~|^{|w~" "}pr~a{|f~}^w~}{k~|\\{}j~}R{|r~}Y{}l~}a{}Z~}d{}c~}_{}w~}Vk~v{}l~|^{|v~Y{}w~}hv~|Z{|v~U{}f~|!{}w~ tt~| w{|t~} uv~" "}R{}i~`{}b~}`{|?{|w~}Lw~|Fw~}&{}t~w}t~} A{}t~w}t~} V{|Z~} ${|w~}m~|s~Xx~}w{|x~} m{|x~}b{}x~hw~lk~k{|x~}b{}x~" "fv~}U{}v~dv~}j{}v~dv~}j{}v~dv~}j{}v~dv~}j{}v~dv~}j{}w~}d{}w~}r{}w~}k{|b~f{}d~|c{}c~}a{}c~}a{}c~}a{}c~}X{}w~}M{}" "w~}M{}w~}M{}w~}Z{|d~}|`{}w~|l{|s~b{}f~|^{}f~|^{}f~|^{}f~|^{}f~|`{|~|f{|~}f{|w~|}f~|]f~}]f~}]f~}]f~}V{|v~|V{}w~}" "Mw~}xl~}_j~{}w~|_j~{}w~|_j~{}w~|_j~{}w~|_j~{}w~|_j~{}w~|ii~w{|f~e{}i~|]{|f~|^{|f~|^{|f~|^{|f~|Wv~Lv~Lv~Lv~R{}l~" "}[w~}m{|w~}^h~Zh~Zh~Zh~Zh~){|f~Zk~{}w~|^k~{}w~|^k~{}w~|^k~{}w~|X{|u~|Ww~}{k~|V{|u~| H{|j~|Z{|j~|Z{|j~|Z{|j~|Z{|" "j~|S{}x~}M{}u~} I{}Ax~} pw~|Lw~|L{|y~|Jy~|Vw~}kw~}[{}o~|[{}w~}mv~Wt~}T{|}b~} +{}l~}\"v~}#w~|tw~|U{|}l~}]{|w~" "ko~|h{|j~}|w{}u~({}w~L{}w~ s{}w~Lv~| u{|v~|Qw~}M{|m~}Z{|e~|ab~`g~}|M{}w~}]{}h~|W{|k~W{}v~P{|i~|\\k~}P{}v~Mv~| " "i{}w~}\\{}w~Jv~}d{}v~f{}g~}|X{|}h~}e{}g~}|Z{}c~}`{}w~}L{|}g~}|e{}w~}hv~|Y{}w~}M{}w~}W{}w~}jt~b{}d~}i{}w~|bv~|h{" "}w~|ks~a{|i~}\\{}w~}L{|i~}^{}w~}i{|v~|e{}f~}U{|v~|T{}i~|Ut~Z{}u~}l{|t~g{|v~|h{|v~|[{|v~|[{}\\~}^{|w~}D{|w~N{|w~" "| s{|l~|{}w~|_w~}x{}q~}|W{|j~|[{}p~|y{|w~|]{|g~|Xw~}P{}q~}|y{}w~|`w~}m{|w~}Wv~Lv~Tw~}n{|v~}Xv~_w~}mv~mv~hw~}m{" "|w~}]{}l~}[w~}{|m~|Zm~|{|w~|Zw~}Qh~|T{|o~Z{|m~|{}w~|Xs~X{}u~|pu~}av~}m{}w~}Wu~V{}d~Uw~}Lw~|M{|w~| o{|n~|w{}u~b" "f~}Z{}p~}T{}l~}X{|i~}^w~}m{|w~}Wu~Xv~|k{|v~b{|w~y|o~|{}t~g{|o~|x{|o~}`{}i~|]{|w~}p{}s~_{}j~}|]w~}{|m~|Z{}l~}P{|" "s~}X{}n~}`X~d{}c~}_{}w~}Vk~v{}l~|^{|v~Y{}w~}hv~|Z{|v~T{|i~} {{}w~ sv~| u{|v~} tv~}Q{}j~`{}b~}#{|w~}Lw~|G{|w~}${" "}m~} ={}m~} T{|Z~} ${|w~y|o~|{}t~Xx~}w{|x~} mw~|b{}x~i{}x~|lk~kw~|b{}x~g{|v~Tv~}d{}v~jv~}d{}v~jv~}d{}v~jv~}d" "{}v~jv~}d{}v~k{|v~|d{|v~rv~|k{|b~e{|}h~}a{}c~}a{}c~}a{}c~}a{}c~}X{}w~}M{}w~}M{}w~}M{}w~}Z{|g~}|]{}w~|ks~a{|i~}[" "{|i~}[{|i~}[{|i~}[{|i~}/{|w~|y{|i~}Z{}i~|[{}i~|[{}i~|[{}i~|U{|v~|V{}w~}Mw~}xm~|^{|l~|{}w~|_{|l~|{}w~|_{|l~|{}w~" "|_{|l~|{}w~|_{|l~|{}w~|_{|l~|{}w~|i{|l~}u{|g~d{|j~|\\{|g~|]{|g~|]{|g~|]{|g~|Wv~Lv~Lv~Lv~Q{|}p~}|Zw~}m{|w~}]{}l~" "}X{}l~}X{}l~}X{}l~}X{}l~}){|w~}l~}Y{|m~|{}w~|^{|m~|{}w~|^{|m~|{}w~|^{|m~|{}w~|Wu~Vw~}{|m~|Tu~ E{|}p~}|V{|}p~}|V" "{|}p~}|V{|}p~}|V{|}p~}|Qw~}Lu~| i{}y~| q{|w~}M{|w~}K{|}I{|}Uw~}kw~}Y{|y}w~y}|Yv~|m{}w~|X{}u~|Q{|}e~} *{|}p~" "}|!v~}#w~t{|w~Py|x}y~x}y|[w~|j{}r~|e{|n~}|t{}u~){|w~|N{|w~| s{}w~Lv~ t{|v~|R{|w~|L{|}p~|Y{|e~|ab~`y|}l~}|K{}w~}" "]{|}k~|S{}o~|Vv~}N{|m~}Z{}n~}|O{}v~Mv~ h{}w~}[v~L{|v~|d{|v~|g{}k~y}y|T{|}m~}|c{}m~x}y|W{}c~}`{}w~}J{|}k~}|c{}w" "~}hv~|Y{}w~}M{}w~}W{}w~}it~c{}d~}i{}w~|bv~|h{}w~|k{|t~_{|m~}|[{}w~}J{|l~|]{}w~}h{}w~}c{|}k~}|T{|v~R{|}m~|S{}v~}" "Z{|u~|kt~gv~}f{}v~[{|v~|[{}\\~}^{|w~}Cw~|O{|w~| q{}p~}x{}w~|_v}vy}w~y}|S{}m~}Xy}w~y}|w{|w}|[{|l~}|Vw~}N{|}w~y}" "|w{}w~|`v}lw}|Wv~Lv~Tv}m{|u}Yv}_w~}mv~mv~hw~}m{|w~}\\{|n~|Zw~}x{}q~}W{}q~}|y{|w~|Zw~}Q{|}l~}P{|y}s~X{}q~}x{}w~|" "X{}u~}X{|u~o{}v~|b{}w~}kv~}X{}w~}V{}d~Uv~Lw~|M{|w~| n{|}q~}u{|}w~bv~{}o~}|X{|r~|R{|}p~}|U{}l~}|^w~}m{|w~}W{}w~" "}Xw}|i{|w}b{|w~|{|q~|y{|t~f{|q~|v{|q~|^{|l~}[{|w~}os~]{|}o~}|[w~}x{}q~}W{|}p~}|M{|}v~}W{|p~|`{|X~|e{}c~}_{}w~}V" "k~v{}l~|^{|v~Y{}w~}hv~|Z{|v~R{|m~}| y{}w~ rx~| s{|x~} sv~}P{|}n~}|`{}b~}#{|w~}Lw~|Ty|pv~|\"y|}u~}y| 9y|}u~}y| " "R{|Z~} ${|w~|{|q~|y{|t~Xx~}w{|x~} y}| q{}x~}aw}j{|w~kk~l{}x~}aw}gv~}U{|v~|d{|v~|l{|v~|d{|v~|l{|v~|d{|v~|l{|v~|" "d{|v~|l{|v~|d{|v~|l{|v}bv}|t{}w~}j{|b~c{|}m~}|_{}c~}a{}c~}a{}c~}a{}c~}X{}w~}M{}w~}M{}w~}M{}w~}Z{|m~x}y|Z{}w~|k{" "|t~_{|m~}|X{|m~}|X{|m~}|X{|m~}|X{|m~}|.w~}v{|}n~}|X{|}m~|X{|}m~|X{|}m~|X{|}m~|S{|v~|V{}w~}Mv|wy|}u~y}|Z{}p~}x{}" "w~|]{}p~}x{}w~|]{}p~}x{}w~|]{}p~}x{}w~|]{}p~}x{}w~|]{}p~}x{}w~|g{}o~|r{|l~}|a{}m~}Y{|l~}|Y{|l~}|Y{|l~}|Y{|l~}|U" "v~Lv~Lv~Lv~O{|y}v~y}|Xw~}m{|w~}\\{|n~|V{|n~|V{|n~|V{|n~|V{|n~|(w~|{|n~|V{}q~}x{}w~|\\{}q~}x{}w~|\\{}q~}x{}w~|\\" "{}q~}x{}w~|W{}w~}Vw~}x{}q~}R{}w~} B{|t}|P{|t}|P{|t}|P{|t}|P{|t}|Nw~} 3{|~} ;f| '{|y}w~}y| 8{|y~|X{|x~}" "h{|}w~}|ay|y}w~y}| rw~}N{}w~ ?{|w~| D{}w~I{|y}w~y}|%b|\\{|x}u~y}|!y|y}u~y}y|O{|y}w~y}| {{y|}u~y}|Vy|y}v~}y| u{|" "w~| B{|v~| 1{|y}u~y}| o{|x}u~y}y| Fv~| 7y|y}v~y}| {{y|y}q~|#y|y}u~y}y| {{|y}v~y}y| a{|w~}C{}x~}O{|w~| oy}" "v~}|vv|!{|}t~y}|!{|y}t~y}|Sv|Av~\"v|Lv~ Rv|mv|mv|hv|lv|Z{|y}u~}|Xw~}v{|}w~y}|T{|}w~y}|w{|w~|Zv|Ny|y}u~y}| {{|y}" "w~}|uw|W{|u}|Wv}|o{|v}av|ju|Xv~| sv~Lw~|M{}w~| ly|}v~}|Uv~yy|}v~y}|S{|y}~y}|N{|y}v~y}|Qy|y}v~x}|[v|m{|w~}W{|w~" "|#{|w~|x{|}w~}|v{|}y~y}c{|y}x~y}ry}x~y}|Z{|y}s~}y|G{}w~}|Zy|v~}|Ww~}v{|}w~y}|T{|y}v~y}| x{|y}w~}| Ry|y}v~y}|" " Zy| rv~}M{|y}u~}|]`| Iw~|T{|y~}|u{|u~ 5{|w~|x{|}w~}|v{|}x~}Wx~}w{|x~} {}y~} r{|y}|Kw~|L{|y}|Hv~| E" "{|y}u~y}| qy|y}v~y}|Sy|y}v~y}|Sy|y}v~y}|Sy|y}v~y}|Sy|y}v~y}|+{|y~}r{|y}v~y}|R{|y}v~y}y|S{|y}v~y}y|S{|y}v~y" "}y|S{|y}v~y}y| oy}v~}|vv|Zy}v~}|vv|Zy}v~}|vv|Zy}v~}|vv|Zy}v~}|vv|Zy}v~}|vv|d{|}v~y}|n{|y}u~y}y|\\{|}t~y}|U{|y}" "t~y}|T{|y}t~y}|T{|y}t~y}|T{|y}t~y}|Rv|Lv|Lv|Lv|!v|lv|Z{|y}u~}|R{|y}u~}|R{|y}u~}|R{|y}u~}|R{|y}u~}|'{}x~|w{|y}u~" "}|S{|y}w~}|uw|Z{|y}w~}|uw|Z{|y}w~}|uw|Z{|y}w~}|uw|Vv~|Vw~}v{|}w~y}|Qv~| Mw~| K{|y~| e{|w~Nw~" "| ?{}w~ Cw~} .{}w~ @{|v~|d{}| Kv~| !u~| J{|w~}C{|w~O{|w~| 9w~} Iv~ bw~}9{|w~| X{|v~ rv" "~Lw~|M{}w~| <v~ S{|w~}W{|w~|#{|w~| j{}w~ s{}w~Uw~} )v~}Iy~} gw~|T{|u~y}s~| 5{|w~|Ax~}w{|x~} {" "{x~| 0{|v~ ?{}y~} R{|} 5x~| O{|y~} &{|v~Uw~}D{|v~ Lw~| K{|y~| d" "{}x~}P{}w~ >w~| D{|w~| .w~| ?{|v~}g{|x~| M{|v~ {|u~| K{|w~}Bw~|P{|w~| :{}w~} Iw~} bw~}9{" "|w~| X{}w~| r{}w~|Mw~|Mv~ ;v~ S{|w~}W{|w~|#{|w~| j{}w~ s{}w~Uw~} )v~}Iy~} gw~|T{|l~| 4{|w~" "|Ax~}w{|x~} {{}y~} /v~| ?x~| f{|x~ M{} %{}w~|Uw~}D{}w~| Lw~| K" "{|y~| d{|w~Pw~| ?{|w~ C{}w~ .{|w~ ={|u~}|l{|u~| N{}v~ {{|u~| L{|q~}H{}x~}V{}q~| :v~| Iw~}" " bw~}9{|w~| Xv~ q{}w~}Mw~|N{|v~ ;v~ S{|w~}W{|w~|#{|w~| j{}w~ s{}w~Uw~} )v~}Iy~} gw~|T{|}o~}| " " 3{|w~|Ax~}w{|x~} {{|x~| 0v~}m{} N{|x~ e{}y~} Rv~Tw~}Dv~ S{}x~x{|w~| " " K{|y~| c{}x~}R{}x~} >{|x~| Cw~} .{|x~| ;{}t~}|sy|}t~| N{|v~} y{|u~| M{|q~}H{|w~V" "{}q~| ;{}v~ I{|w~} bw~}9{|w~| Y{}w~} q{|v~}|Ow~|P{|}v~} ;v~ S{|w~}W{|w~|#{|w~| j{}w~ s{}w~Uw~} " " )v~}Iy~} gw~|Q{|y}v~y}| 1{|w~|Ax~}w{|x~} yx~| 0{}v~|p{|~} N{|x~| f{|x~ " " S{}w~}Tw~}E{}w~} S{}x~|y{|w~ J{|y~| bw~|Sw~| >{}y~} K{}y~} 9{|p~x}q~}| N{|u~" "| x{|u~ M{|q~} y{}q~| K{|}|p{|u~| I{}w~| bw~}9{|w~| Z{|v~ o{}q~}Tw~|U{|p~ :v~ S{|w~}W{|w~|#{|" "w~| j{}w~ s{}w~Uw~} )v~}Iy~} gw~| W{|w~|Aw|vx| y{|x~} 0{|u~|s{}x~} N{|x~| " " f{|x~| U{|v~Sw~}F{|v~ R{|x~}y{}w~ J{|y~| b{|x}|T{|x}| w{}g~}| Q" "x|y}u~} v{|u~ N{|p} yp}| K{|x~}y|wy|}u~} J{|}v~ aw~}9{|w~| \\{|}v~} nq~}Tw~|U{|q~| :v~ S{|w~}" "W{|w~|#{|w~| j{}w~ s{}w~Uw~} )v~}Iy~} gw~| W{|w~| :{|}w|}w~| /t~y}x|y}v~} U{|}|x{|w~| " " f{}x~| W{|}v~}Sw~}H{|}v~} Qq~| J{|y} *{|}l~}| O{}q" "~ tt| `{|i~} Lr~| aw~}9{|w~| `{}q~ l{}s~}Tw~|U{|s~}| 9v~ S{|w~}W{|w~|#{|w~| j{}w~ s{}w~Uw~" "} )v~}Iy~} gw~| W{|w~| :{|q~ .{|i~} U{|q~ ly}w|}w~| [{}q~Rw~}" "L{}q~ P{}r~ M{|y}u~y}y| L{}r~| R{|j~} Ks~} `w~}9{|w~| " " `{}r~| jy|v}|Tw~|U{|u}| 6v~ S{|w~}W{|w~|#{|w~| j{}w~ s{}w~Uw~} )v~}Iy}| gw~| W{|w~| :{|r~| " " -{|k~}| U{|r~} l{}r~} Z{}r~|Rw~}L{}r~| O{}t~ " " k{}t~} -{|`}| `{|}m~}| Jt~} _w~}9{|w~| `{}s~| :w~| cv~ S{|w~}W{|w~|#{|w~| j{}w~ s{}" "w~Uw~} )v~} d{|w~| 9y}w~y} ){}o~}| S{|}u~}| k{}r~ Y{}s~|Qw~" "}L{}s~| M{}w~} j{}w~}| +{}`~} ]{|x}v~y}| Gw~y} ]w~}9{|w~" "| `{}v~}| 8w~| cv~ S{|w~}W{|w~|#{|w~| j{}w~ s{}w~Uw~} g{|w~| 8{|}v~y}| Ly| " " g{|y}w~}| X{}v~}|Ow~}L{}v~}| Iy| " "l{}`~} Ww~| " " L{}`~} Ww}| " " r{" }; // Define a 104x128 binary font (huge sans). static const char *const data_font_huge[] = { " " " " " " " " " " " " " " " " " FY AY " "'Z ;W @Y @Y 'Z Y @Y (Z :Y ?Y (Z 0Y ?Y (Z >X " " " " " " " " " " )X AX '\\ )XAV 7YDY -] BY BY '[ +YEY 2X AY (\\ -YDY 'XAU 3Y AY (\\ )XAV 8YD" "Y LY AY (\\ ,YEY #Y " " " " " " " " (X CX '^ +[CU 6ZEY .` C" "X CY '] -ZEZ 2X CY (^ .ZEZ )[CU 2Y CY (] *[CU 7ZEZ LY CY (] -ZEZ %Y " " " " " " " " " " 'Y EY '^ ,^FV 6ZEY /b CX DX '_ .ZEZ 2Y DX '_ /ZEZ +_FV 1X CX (_ ,^FV 7ZEZ " " KX CX (_ .ZEZ &Y " " " " " " " " %Y GY '` .aHV 6ZEY 1e DY FX" " 'a /ZEZ 1Y FX '` /ZEZ +aHV 0X EX '` .aHV 7ZEZ JX EX (a /ZEZ &X " " " " " " " " " " #X GX 'XNX 0dKW 6ZEY 1f DY HX &WMX 0ZEZ 0X GX 'XMW 0ZEZ ,dLX /X GX 'WMX 0dLX 7ZEZ" " IX GX 'WMX 0ZEZ 'X :T " " " " " " " " ;X IX 'XLX 1o 5ZEY 2ZLY " " CX IX &WKW 0ZEZ /X HX (XLX 1ZEZ ,o .Y HX (WKX 1o 6ZEZ IY IY (WKW 0ZEZ (X <Z " " " " " " " " " " =X KX 'XJX 3WKd 5ZEY 3XGX CX JX 'WIW 1ZEZ .X JX (XJX 2ZEZ -WKd -X " "IX (WIW 2WKd 6ZEZ HX IX (WIW 1ZEZ )X =^ " " " " " " " " >X MX &WH" "W 3VHa 4ZEY 3WDW CX LX 'WGW 2ZEZ -X LX 'WHW 2ZEZ -VHa +X KX (XHW 3VHa 5ZEZ GX KX (WGW 2ZEZ )X " " ?b " " " " " " " " ?W MW &WFW 4VF^ 3ZEY 4WBV BW MX 'WEW 3ZEZ ,W M" "X 'WFW 3ZEZ -VF^ )X MX 'WFW 4VF^ 4ZEZ FX MX 'WFW 3ZEZ *X ?d " " " " " " " " " " ?W X 'WDW 5UC[ 2ZEY 4VAV AW X &WDW 4ZEZ +W NW 'WDW 4ZEZ -UC[ 'W MW 'WDW 5UC[ 3ZEZ " "EW MW 'WDW 4ZEZ +X ?f " " " " " " " " @X \"X 'WBW 6UAW 0ZEY 4V@V B" "X !W &WBV 4ZEZ +X !W 'WBW 5ZEZ .VAW $W W 'WBW 6UAW 1ZEZ DW W 'WBV 4ZEZ +W >f " " " " " " " " " " ?X #W 'W@W U?V AX #W &W@V NX #W &V@W 9W \"W 'W@V .W " "\"W 'W@V !W >XHX " " 3Y " " " " " " 6W $W &V>V U?V @W $W &W>V " " NW $X 'V>V 8W $X (W>V /X $W 'W>V #W >XFX " " 5Z " " " " ,Z " " GZ " " #U?V NY 7Z ,X CVCW MY " " 7Z ,X $Z 7Z ,X >Z 6Y ,X 4Z 7Y +W 7Y @Z " " " " +Z " " " " HY \"U?V " " MY 8Y ,Y CVBV LY 9Z ,Y #Z 9Z ,Z >Z 8Y ,Y 3Y 8Z ,Y 9Y " " ?Z " " *Y " " " " IY !U?V " " LY :Y ,[ $R>U ,V@V MZ :Y +Z #Y 9Y +Z ?R" ">U 8Y 9Y +Z %S?U HY :Z ,[ ;Y ?[ " " " " )Y " " 8U " " 9Y V@U JY <Y" " +[ 'XAU ,V@V LY ;Y +\\ #Y ;Y +\\ CXAU 7Y ;Z ,\\ )XAV HY ;Y +[ <Z " " ?U ;T $W /W " " 8e !f LY Y LX " " L] :Y <Y NX 0X >Y @Y /X 0Y K` .X " " ^ =ZEY @Y " " NVAV <P -X +Y =Y +] )[CU 7YDY 4V@V KY =" "Y +] ,YDY 5Y =Y *] .YDY 5[ M[CU 6Y <Y ,] *[CV 7YDY Y =Y +] ,YEZ !Y =Y FYDY 8X " " EU :T %W .X " " 9e !f KY !Y LY \"a :Y " "<Y NX 0X >Y E^ /X 0_ %f 1] 'c " " @ZEZ AY MV" "CW <R 4a .Y >X *^ +]DU 7ZEZ 5U>U JY ?Y *^ -YEZ 4Y " " ?Y *^ .ZEZ 5[ ]DU 5Y >Y +^ ,]DU 6ZEZ Y ?Y +_ .ZEZ \"Y <Y FYEZ :[ FU " " 7Y -T 7W#W <Y 9X -W DU KY HZ \"\\ 4Z M[ \"" "Y LZ +\\ 8] >Z G[ G\\ @e !f JX !Y " "LY %d :Y <Y NX 0X >Y Ha /X 0b *j L] D_ " " +g A[ LY 8Z -ZEZ \"Y 1o )V FX NZ FY " "%Y ,X NX*Z NW 3WEW H\\ #[ !Z \"[ \"[ \"[ G[7T 8g 0Y " "@Y +_ ,_FV 7ZEZ 5U>U IY @Y +` .YEZ 3X ?X *` /ZEZ 4[:P 8_FV 4X ?Y +` ._EU 6ZEZ NX @Y *_ .ZEZ #Y ;Y" " FYEZ ;] GU <b 1T :]'X @b >W ,X " " FV a \"d -g >d (d +b %b 4f Bg Ie \"e \"h " " Ge !f IX \"Y LY &e :Y <Y NX 0X >Y Jc /X 0c " " -n $g I` .j >a ;e HU .U +b Ac 2ZEZ 'b " " 5o -] Na (c KY .Y #_ 8Y!W'Y\"X.c$X 3XGX Mf -e +d " ",e ,e ,e \"e=V ;k 1Y BY +XNW .aGV 7ZEZ 5V@V HX AY +XNW .YEZ 3Y AY *WNW /ZEZ 4\\>T 9`GV 3" "X AY +XNW .`GV 6ZEZ NY AX *XNW /ZEZ $Y :Y FYEZ <_ IU (Q LZ 4Z2Z 1Q " " &g %Z +XCX MT <a)W Ah $X HX +X GV GX 3e )_ /j 4n L] ?y /i C~S =i 0g " " +g L\\ 8t (m Ks 2~R E} <o HZ(Z :Z \"Z 4Z,] LZ 2_'_(^-Z Ck :q 0k ?q *n J~d'Z(Z*Z LZ=Z.\\.Z7Z(Z([$Z'~^" " @e 3X Ff )\\ MY #Y LY (g :Y <Y NX 0X >Y Kd /X 0e 0p " " (m Lb 1m ,\\ 5~S E~R Ah 'Z :~]+[;Z;Z Ik LW DX DW /i ?Y(Y 4h 5ZEZ" " ,\\ ,h 7\\ -o .` $f -h NY No %_ %c @_\"X-_\"W0h&W .\\ $\\ \"\\ #\\ #\\ )g 5~a Lm D~S I~S " "H~R H~R 6Z !Z !Z \"Z :r 8^,Y Bk 2k 2k 2k 2k (kAX+Z(Z#Z(Z$Z(Z$Y'Y&[%[ MZ Im 1X CY *WMX /bHV 7ZEZ 5V@V G" "X CY *WLW /YEZ 2Y CY *WLW 0ZEZ 3[AW :bHV 3Y BX *WLW 0bHV 6ZEZ MY CX *XMX 0ZEZ $X 9Y FYEZ " " =a M~i 7U (Q N_ 9_8_ 3R )k 'Z +XCX +X@X 4T >e,X Cl &X IX *X GV " " GX 5i 0d 2p ;u !^ ?y 2o F~S @n 4j /l N\\ 8x .r Nx 7~R E} >t KZ(Z :Z \"Z 4Z-] KZ 2_'_(^-Z" " Ep =t 5o Au 1u N~d'Z(Z)Z MZ<Z/\\/Z5Z*['[&Z&~^ @e 3X Ff )] MY $Y LY )h :Y <Y NX 0X >Y " " Le /X 0e 1r +r c 3o -\\ 5~S E~R Dn *Z :~]+[;Z;Z Ko " " Y EX EY 2m @Y)Y 6l 7ZEZ 0e 2k >e 1o 0c 'j /i X !r (b 'g Eb\"W0c#X0i(W -" "\\ $] #\\ $] #\\ (f 6~b r F~S I~S H~R H~R 6Z !Z !Z \"Z :w =^,Y Ep 6p 7p 7o 7p ,oDY+Z(Z#Z(Z$Z(Z$Y'Y%Z%Z LZ Kp" " 1X DX *WKW /WMYJV 6ZEZ 5V@V GY EY *WKX 0YEZ 1Y EY *XKW 1ZEZ 2[EZ :WMZKV 1Y DX *WKX 1WLYKW 6ZEZ L" "Y EY *WKW 0ZEZ %X 8Y FYEZ >c M~h 7T (S !a <b:b 6S %| $o " ")Z +XCX +W?W 3T ?g.X Dp (X IX )X HV HY 6l 7i 5t <v #_ ?y 3p F~S Aq 8n 3p (Y $^ 9z 2v!{ :" "~R E} Az NZ(Z :Z \"Z 4Z.] JZ 2`)`(_.Z Gt ?w :s Cx 5x!~d'Z(Z)Z N[<Z/\\/Z5[,[%Z'[&~^ @e 2X Gf *_ MX $Y " "LY )h :Y <Y NX 0X >Y >X 8f /X 0f 3t -s c " " 4q /^ 6~S E~R Fr ,Z :~]+[;Z;Z Ms #[ FX F[ 4n @Y*Y 6m 7ZEZ 3k 5l Bk 4o 1f )k 0k #" "X #u (b (i Fb#X0c#W/k+X .^ %] $^ %] $^ (d 5~b\"v H~S I~S H~R H~R 6Z !Z !Z \"Z :{ A_-Y Gt :t ;t ;s ;t " " 0sGY*Z(Z#Z(Z$Z(Z$Y'Y$Z'[ LZ Ls 2X FX *WIW 1WJc 6ZEZ 4VBV EY FX *XJW 0YEZ 0X EX )WJW 1ZEZ 1[I^ <WJc 0" "X EX )WJW 2WJZNW 5ZEZ KX FY *WIW 1ZEZ &X 7Y FYEZ ?d M~h 8U )T #e ?d=e 8U " " *~Q &r *Z +XCX +W?W 3T @i/W Dq (X JX (X HV HX 7o <m 7x >x %_ ?y 5r F~S Ct :p" " 6s /e *^ 9| 6z#~ =~R E} B}!Z(Z :Z \"Z 4Z/\\ HZ 2`)`(_.Z Iw @y >w Ez 9z!~d'Z(Z)[ Z;Z0]/Z4Z,Z$[(Z%~^ " "@e 2X Gf +a MX %Y LY *i :Y <Y NX 0X >Y >Y 9f /X 0g 5v " " 0u d 6_K_ 0^ 6~S E~R Gu .Z :~]+[;Z;Z w &] GX G] 6U &o ?Y+Y 7X )n 7ZEZ " "6p 7m Eo 6o 2h *l 1l %X #v (b )k Gb$X/c$X/l,W -^ &_ %^ &_ %^ 'b 4~b$z J~S I~S H~R H~R 6Z !Z " "!Z \"Z :~ D_-Y Hw =v >w >w >w 4wIX)Z(Z#Z(Z$Z(Z$Y'Y$[)[ KZ Mt 1X HX )WHW 2VHb 6ZEZ 4WDW DX GX )WHW 1YE" "Z /X GX )WHW 2ZEZ 0[M` ;VHb /X GY *WHW 3VHb 5ZEZ JX GX )WHW 2ZEZ 'Y 7Y FYEZ ?e M~f " " 7U )U %g Bh@g :W .~T 't +Z +XCX ,X@X 3T Ak1X Er (X JX 'X IV HX 8q" " =m 7y ?y '` ?y 6s F~S Dv <r 8u 4m /_ 9~ :~%~Q ?~R E} D~Q\"Z(Z :Z \"Z 4Z0\\ GZ 2`*a(`/Z Jz Bz Az F{ " ";{!~d'Z(Z(Z Z;Z0^0Z3Z.[#[*Z$~^ @X %X :Y ,c MX &Y LY +^ .Y <Y NX 0X >Y >Y " " :] %X &] 5]C\\ 1v Nc 7\\D\\ 1_ 6~S E~R Iy 0Z :~]+[;Z;Z!y (_ H" "X H_ 7U 'p ?Y,Y 6X *o 7ZEZ 8t 9YH] Ht 9o 3i *XG[ 1VE[ &Y %x (b *[I[ Hb$W.c%X.VE[-X " " ._ &_ %_ '_ %_ '` 4~c%} L~S I~S H~R H~R 6Z !Z !Z \"Z :~Q F`.Y Jz @z Az Ay Az 7zKX(Z(Z#Z(Z$Z(Z$Y'Y#[*Z JZ Na" "J_ 2X IX )WGW 2VG` 5ZEZ 4XFX CX IX )WFW 2YEZ .X IX )WFW 3ZEZ /j 8VG` -X HX *WFW 4VG` 4ZEZ IX IX " ")WGW 2ZEZ 'X 6Y FYEZ ?XKX M~f 7T )W 'i DiAi ;X 1~V (w -Z " "+XCX ,X@X 3T AZI[2W Es (X KX &X IV HX 9s >m 7z @z )a ?y 7t F~R Dx >t 9v 8s 2` :~P <~Q&~S" " A~R E} E~T$Z(Z :Z \"Z 4Z2] FZ 2a+a(`/Z K| C{ C} H| =|!~d'Z(Z(Z!Z9Z1^1Z2[0[!Z+[$~^ @X $X ;Y -e MX 'Y " "LY +[ +Y <Y NX 0X >Y >Y :[ #X #Z 6\\?[ 2v F\\ " " 8Z@[ 2` 7~S E~R J{ 1Z :~]+[;Z;Z#} +` HX Ia 8U (q >Y-Y 6X +p 7ZEZ 9bMb ;U@Y JbMb :" "n 3ZIZ +T@Y 2R>Y 'X %y (XLV +ZEZ IXMW%X.YMW%W-R>Y.W -` '_ &` '_ &` '` 4~c'~R N~S I~S H~R H~R 6Z !Z " "!Z \"Z :~S Ha/Y K| B| C| D} D| 9|MX'Z(Z#Z(Z$Z(Z$Y'Y\"Z+[ JZ N]B\\ 2X JX *WEW 3UE_ 5ZEZ 3YJY AX JW )WE" "W 2YEZ -X KX (WFW 3ZEZ .f 5UE_ ,X JX )WFW 4VF_ 4ZEZ HX KX )WEW 3ZEZ (X 5Y FYEZ @YJW M~" "e 7U *X (j EkCk =Y 3~X )x -Z +XCX ,W?X 3T BYEY3X Ft (X KX %X JV " " IX 9u ?m 7{ A{ *a ?y 8u F~R Ez @v :v :w 4` :~Q >~S'~U C~R E} G~V$Z(Z :Z \"Z 4Z3] EZ 2a+a(a0Z M~P D" "| E~P I} ?}!~d'Z(Z'Z\"Z9Z1^1Z1Z0Z [,Z#~^ @X $X ;Y .g MW 'Y LY +Y )Y <Y NX 0X >Y " " >Y :Z \"X \"Z 7[=Z 3aE[ E[ 9Z>[ 3` 7~S E~R L~ 2Z :~]+[;Z;Z$" "~P -b IX Jc 9U )r >Y.Y 5X ,]DX 7ZEZ ;\\>\\ <R;X M]>\\ 0XDX ,R=Y MX (X %hEW (SG" "V ,YAY JSHW%W-SGW&X GX/W ,` (a '` (a '` (a 5~d(~S N~S I~S H~R H~R 6Z !Z !Z \"Z :~T Ia/Y L~P F~P F~P F~P F~P" " <~X&Z(Z#Z(Z$Z(Z$Y'Y\"[-[ IZ \\>Z 1X LX )VCW 4UD] 4ZEZ 2f ?X LX )WDW 3YEZ ,W KX )WDW 4ZEZ -b 2UD] *W" " KX )WDW 5UD] 3ZEZ GW LX (VCW 4ZEZ )X 4Y FYEZ @XIX M~d 7U *Y *l GmDl ?[ " " 6~Z *`C\\ -Z +XCX ,W?W 2T CYCY5X E]CZ (X LX $X JV IX 9]E^ @m 7aGb B^Ec ,b ?y " "9aF[ F~R E_C_ B_E^ ;]E_ ={ 7b ;~R @cBb'~V D~R E} HeBc$Z(Z :Z \"Z 4Z4] DZ 2b-b(a0Z NbCb E} GbCb J~ Aa" "B_!~d'Z(Z'Z#[9Z2_1Z0Z2[ N[.Z\"~^ @X $X ;Y /i MW (Y LY ,Y (Y <Y NX 0X >Y >Y " " :Y !X !Y 8[;Z 1\\ 0\\:U D[ ;Z<Z 4b 8~S E~R M~R 4Z :~]+[;Z;Z%bCb " "/d JX Ke :U )]BW =Y/Y 5X ,[?U 3Z8[ &W NZ7Z 2XBW EX LW )X %iEW KV -Y?Y @W&X" "!W&W EW0X -b )a (b )a 'a )a 5~d)dCb N~S I~S H~R H~R 6Z !Z !Z \"Z :~V Kb0Y MbCb HbCb HbCb HbCb HbCb >bCh%Z(Z" "#Z(Z$Z(Z$Y'Y![.Z HZ Z;Z 1X NX )WBV 5VBZ $e >W MX )WBW !X MX )WBW #` /UBZ (W MX )WBW 6UBZ " " 9X MW (WCW MX 3Y GXHW M~d 8U *[ +m HnFn A] 9~\\ +^=Y" " -Z +XCX -X@X 2U DXAX5W E\\=V (X LX #X .R@V?Q ,X :\\A\\ @m 7\\>_ CY<_ -c ?y :^=V F~Q E]>^ D]@] " " <Z@^ @~P 9b ;Z=d Aa;^'Z>j E~R E| Ha8^$Z(Z :Z \"Z 4Z5] CZ 2b-b(b1Z `<_ FZ@d I`=` K[@d C_:Z ~b&Z(Z'Z#Z8Z2`" "2Z0[4[ LZ/[\"~^ @X #X <Y 0\\N] NX )Y LY ,Y (Y ;X NX 0X >Y >Y ;Z " "!X !Y 8Z9Y 6d 4[5R CZ ;Y:Z 5b 8~R D~Q MbAb 8` =~]+[;Z;Z&`=` 1f KX Lg " " ;U *\\=T =Y0Y 4X ,Z;R 5Z3Y &W !Y3Y 3W@W EW LX *W %jEW KV -X=X @W'X W'X EX1W ,b " "*b (b )b )b )b 7ZH~R)a:] N~R H~R G~R H~R 6Z !Z !Z \"Z :Z>j Lb0Y N_<` J`<_ J`=` J`=` J`=` @`=e%Z(Z#Z(Z$Z(Z$Y'Y" " Z/[ HZ !Z9Y 0W X )WAW 6VAW \"d <W X (VAW X X (V@V &a .VAW &X NW (V@V 6UAW 6X X )WAW " " NW 2Y N\\ #[ \"\\ #\\ #[ MXHW L~b 7U +\\ ,n IoGp C_ ;~] ,]:X -Z " "+XCX -X@X 8c LX@X7X E[:T (X MX \"X /TAVAT .X :\\?\\ Am 7Y9] CT4] .c ?Y J]8S Z E\\;\\ E]=[ " " <W;\\ B~T ;b ;Z7_ C_5['Z7e GZ MZ '`3[$Z(Z :Z \"Z 4Z6] BZ 2b-b(b1Z!_8^ GZ;` K_9_ LZ:` D]5W 3Y 9Z(Z&Z$Z7Z3`3Z." "Z4Z JZ0Z \\ ?X #X <Y 1\\L] NX *Y LY ,Y (Y 8X >Y >Y ;Y X !Y " " 8Y8Y 6f 6Z2P BY <Z9Z 7c 7\\ Z (`;` >j BZ(Z+[;Z;Z'_9_ 3h LX Mi <" "U *[:R <Y2Z 4X -Z8P 6Y/X 'W #Y/Y 6W>V EW KW +W %kEW KV .X;W @W'W NW(X CW2X -c *c )b " "*c )c +c 7ZHZ 2_5[ NZ !Z Z !Z >Z !Z !Z \"Z :Z7d Mc1Y ^8_ K^8^ L_8^ L_9_ L^8_ B_9b$Z(Z#Z(Z$Z(Z$Y'Y [1[ GZ !Z" "8Y 0W !W (V?W I` :X !W (V?W X \"X (W@W *d EX !W (W@W 0X \"X (V?W !W 1Y #d ," "e +d +d ,e #XHW LZ#Z 7U +] -o KqHp C_ <c 2]7V -Z +XCX -W?X <l#X?X7W E[7R " "(X MX \"Y 0VCVCV .X :[<[ B\\IZ 7V5] DQ0] 0XNZ ?Y K\\4Q !Z E\\9\\ F\\;[ =U8[ DdAc =d <Z5^ " "E^1Y'Z3b HZ MZ (_/Y$Z(Z :Z \"Z 4Z7] AZ 2c/c(c2Z!]4] HZ9^ L^5^ MZ8^ E\\0T 3Y 9Z(Z&Z%Z6Z3`3Z-Z6[ J[2Z \\ >X #X " " <Y 2\\J] NW *Y LY ,X 'Y 8X >Y >Y ;Y X X 9Z7X 6g 7Y" " #Z =Y8Z 7d 7[ Z )_7_ Bp EZ(Z+[;Z;Z(^5^ 5j MX Nk =U +[7P <Z3Y 3X -Y " " MX+W 'V $X+X 7V=W FW KW ,W $kEW KV .X;X AW(X NW(W BW2W ,d +c *d +c *d +c 7ZHZ 3^0X NZ !" "Z Z !Z >Z !Z !Z \"Z :Z3a Nc1Y!^5] L]4] N^5^ N^5^ N^5] C^5_#Z(Z#Z(Z$Z(Z$Y'Y N[2Z FZ \"Z7Y /W #W (W>V H^" " 8X #W (W>V NW \"W (W>W .h EW \"X )W>W 0W #X (V=V \"W 0Y &j 1i 0j 1j 1i &X <Z#Y " " 7U +_ /p KrJr Ea >` .\\5U -Z +XCX -W?W =r'X>W8X EZ ;X NY !X 1XDVDX 2X " " &X ;[;[ BWDZ 7T2\\ \"\\ 1XMZ ?Y L\\ 2Z E[7[ G\\9[ >S5[ F`7` ?YNY <Z3\\ F]-W'Z0` IZ MZ )^+W$" "Z(Z :Z \"Z 4Z8] @Z 2YNX/XNY(c2Z\"]2] IZ7] N]2] MZ6] G\\-R 3Y 9Z(Z&[&Z6Z4XNW3Z-[8[ HZ3[ !\\ =X #X <Y 3\\H] N" "W +Y LY ,X 'Y 8X >Y >Y ;Y X Y :Y6Y 7i 9Y \"Y " " >Y6Y 7YNY 6[ !Z *^3] Dt GZ(Z+[;Z;Z)]2] 6l NX m >U +Z !Y4Z 3X -Y NW(W (W " " &X)X 8V<V +X DW LW ,W $lEW KV .W9W AW(W MW)X CW2W +YNY ,YNZ +YNY ,ZNY +YNY +YNY 9ZGZ 4^.W NZ !Z" " Z !Z >Z !Z !Z \"Z :Z1` d2Y\"]2] N]2] ]2]!^2]!]2] E]2]\"Z(Z#Z(Z$Z(Z$Y'Y MZ3[ FZ \"Z6X .V $W 'V<V GZ " " 5W $W 'V<V NW $W 'V<V 2m EW #W (V<V /W $W (W=W #W 0Y (n 6o 5n 5n 6n (X ;Z%Z " " 7U ,a 0q LrJr Fc A_ ,\\2S -Z +XCX .X@X ?u(W=X:X DY :X NX Y 2ZFVFZ 2X " "'X :Z9[ CR?Z 7R/\\ \"[ 1XMZ ?Y L[ 2[ F[5Z G[7Z >R4[ G^1^ AZNY <Z2[ G]*U'Z.^ IZ MZ )](U$Z(Z :Z \"Z" " 4Z9] ?Z 2YNX0YNY(d3Z#]0] JZ6\\ N\\/\\ NZ5\\ G[ <Y 9Z(Z%Z&Z6Z4XNX4Z,Z8Z FZ4Z [ <X \"X =Y 4\\F] #Y " "LY -Y 'Y 8X >Y >Y ;Y X Y :Y6Y 7j :Y \"Y " " >Y6Z 9YMY 5[ \"Z *]1] Hy IZ(Z+[;Z;Z)\\/\\ 8n X !o ?U ,[ Y5Y 2X -Y W&W )W 'W%W 9V" "<V +X DW LW )mEW KV /X9X BW)X MW)W BW3X ,YMY ,YMY ,ZNZ -YMY +YNZ -YMY 9ZGZ 5]*U NZ !Z Z !Z >Z " "!Z !Z \"Z :Z/_!d2Y#]0]!]0]\"]0\\!\\/\\\"]0] F\\0]#Z(Z#Z(Z$Z(Z$Y'Y M[5[ EZ \"Y5X +P " " %_K[ CY *r 9q 8r 9r 9q *X ;Z%Z >Q JT ,b 0q MsKs Ge " "C^ *[0R -Z +XCX .X@X @v)X=X:W CY :X Y NX 1[HVH[ 1X 'X ;Z7Z 0Z 7P,[ ![ 3XLZ ?Y M[" " 1Z EZ4[ I[5Z ?P1Z I^-] BYLY =Z1[ H\\(T'Z-^ JZ MZ *\\$S$Z(Z :Z \"Z 4Z:] >Z 2YMX1XMY(YNZ4Z$].\\ JZ5" "\\!\\-\\ Z4[ GZ ;Y 9Z(Z%Z'Z4Z5XNX5Z*Z:[ F[6Z [ ;X \"X =Y 5\\C[ #Y LY -Y 'Y 8X >Y " " >Y ;Y X Y :Y6Y 7k ;Y \"Z @Z5Y 9YLY 5[ #Z +\\.] J| KZ" "(Z+[;Z;Z*\\-\\ :p !X \"q @U ,Z NY6Y 1X -X W#V *W (W#W :U;V +X DW LW )mEW KV" " /X9X BW*X LW*X BW3W +YLY -YMY ,YLY -YMY ,YLY -YMZ ;ZFZ 5\\'S NZ !Z Z !Z >Z !Z !Z \"Z :Z-^\"e3Y#\\.]#].\\" "#\\-\\#\\-\\#\\-\\ H\\.]$Z(Z#Z(Z$Z(Z$Y'Y L[6Z DZ \"Y5Y /[G[ " " DY +u =u <u ;u =u ,X :Y&Z >S LU ,c 1q MtLt Hf E] )[.Q " " -Z +XCX .W?X Bx)X=X;X DZ :X X MY 0ZIVIZ /X 'X ;Z7[ 1Z AZ ![ 4XKZ ?Y MZ 0Z EZ3Z I[5Z " "Z J])\\ CYLY =Z1[ I\\%R'Z+] KZ MZ +\\\"R$Z(Z :Z \"Z 4Z;] =Z 2YMX1XMY(YNZ4Z$\\,\\ KZ4[\"\\+[ Z4\\ I[ ;Y 9Z(Z$Z" "(Z4Z5WLW5Z*[<[ DZ7[ !\\ ;X \"X =Y 6\\A[ $Y LY -Y 'Y 8X >Y >Y " " ;Y X Y :Y6Y 7l <Y !Y @Y4Z :YLY 4[ $Z ,\\,] M~Q MZ(Z+[;Z;Z+\\+\\ <r \"X" " #s AU ,Z MY7Y 1X -Y \"W!V :f (V!W ;U;V +X EX MW (mEW KV /W7W BW*W KW+X BW3X " " +YLY .YKY -YLY .YKY -YLY .ZLY ;ZFZ 6\\%R NZ !Z Z !Z >Z !Z !Z \"Z :Z,^#YNZ3Y$\\,\\#\\,\\$\\,\\%\\+\\%\\,\\ MP" " NP N\\-]$Z(Z#Z(Z$Z(Z$Y'Y KZ7[ Dq :Z4X /XC[ EY " " -x @x >x ?x @x -X :Z'Z ?U MU -e 2q MtLt Ig E[ 'Z,P -Z +XCX .W?W By)" "X<W;W CZ :X X MY .ZKVKZ -X (Y <Z5Z 1Z A[ !Z 4XKZ ?Y N[ 1Z DZ3Z IZ3Y NY K\\%[ EYKZ >Z0Z" " J\\#Q'Z*\\ KZ MZ +[ Q$Z(Z :Z \"Z 4Z<] <Z 2YMY3XLY(YMZ5Z%\\*\\ LZ4[\"[*\\!Z3[ IZ :Y 9Z(Z$Z)[4Z6XLW5Z)Z<Z BZ8Z" " !\\ :X !X >Y 7[>[ %Y LY -Y 'Y 8X >Y >Y ;Y X Y ;Y" "5Y 7UH_ <Z \"Z AY3Y ;YKZ 4[ %Z ,[*\\ N~S NZ(Z+[;Z;Z+[*\\ =\\NXM[ #X $\\MXN\\ " " BU ,Z *P DY8Y 0X -Y #W NV @k )V NV <V;V +X EW NY )nEW KV /W7W BW+X KW+W CY4X +YKZ /" "YKY .ZLZ /YKY .ZKY /YKY <ZEZ 7\\#Q NZ !Z Z !Z >Z !Z !Z \"Z :Z+]#YMZ4Y%\\*\\%\\*\\&\\*[%[)[%[*\\ R!R [-_%Z(Z#Z" "(Z$Z(Z$Y'Y K[9[ Ct =Y3X /U@[ \"Q EY .z B{ " "B{ Az B{ /X :Z'Y >V U -g 4r NvNu Ji *\\ 5X.X 6\\ 7Z1Z M[ '[ 8Z +XCX /X@X C`MTL_)W;" "W<X CY 9X !Y LX ,ZMVMZ +X (X ;Z5Z 1Z A[ !Z 5XJZ ?Y NZ 0Z DY2Z J[3Z )Q Q JZ M[!Z FYJY >Z0Z " "J[ 'Z)\\ LZ MZ ,\\ \"Z(Z :Z \"Z 4Z=] ;Z 2YLX3XLY(YMZ5Z%[([ LZ3[$\\)\\\"Z3[ IZ :Y 9Z(Z$Z)Z3Z6XLX6Z(Z>[ B[:Z !" "\\ 9X !X >Y 8[<[ &Y LY -Y 'Y 8X >Y >Y ;Y X Y ;Y5Y " "7RB] =\\ $Z BY2Y ;YJY 3[ &Z -[(\\!~U Z(Z+[;Z;Z,\\)\\ ?\\MXL[ $X %\\LXM\\ CU" " ,Y *Q\"R DY9Y 0X -Y #V=_?V Cm *V LV <U;V +X FX \"[ (nEW KV /W7W BW+W JW,X F[3W *YJY 0Z" "KZ /YJY /YKZ /YJY /YJY =ZEZ 7[!P NZ !Z Z !Z >Z !Z !Z \"Z :Z*]$YMZ4Y%[([%[(['\\)\\'\\)\\'\\)[!T#T\"\\-`&Z(Z#Z(" "Z$Z(Z$Y'Y J[:Z Bw @Y6[ .Q<[ #S GY /`Da E`C" "` DaD` C`Da E`C` 0X 9Y(Z ?X !U .h 4r NvNu Kk .c 9X.X 7^ 7Y1Y M[ &Z 7Z +XCX /X@X C\\" "ITFY)W;W=X BY 9X !X KY +YNVNZ *X (X ;Z4Z 2Z @Z !Z 6YJZ ?Y Z /Z DY2Z JZ1Y ,T T MZ N[ NZ HZJ" "Y >Z0Z K[ &Z(\\ MZ MZ ,[ !Z(Z :Z \"Z 4Z>] :Z 2YLX3XLY(YLZ6Z&['\\ MZ3[$['[\"Z2Z IZ :Y 9Z(Z#Z*Z2Z7XLX7Z'[@[ @Z;" "[ ![ 8X !X >Y 9[:[ 'Y LY -Y 'Y 8X >Y >Y ;Y X Y ;Y" "5Y %\\ =] %Y BY2Z =ZJY 3\\ 'Z .\\'[#cLZLb!Z(Z+[;Z;Z,['[ @\\LXK[ %X &\\KXL\\ " " DU -Z +S$T EY:Y /X -Z %V?fBU Eo +VEg=V =V<V +X GX *b &nEW KV /W7W BW,X JW,W Nb2X +ZJY " "0YIY /YJY 0YIY /YJZ 1YIY =ZEZ 8\\ NZ !Z Z !Z >Z !Z !Z \"Z :Z)\\$YLZ5Y&\\'['['\\(['['['['['[#V%V#[-a&Z(Z#Z(Z$" "Z(Z$Y'Y IZ;Z Ay BY9^ G[ %U HY 0]<^ G^=^ F" "^<] E]<^ G^=^ 1X 9Z)Z @Z \"U .i 5r NvNu Lm 2h ;X.X 7^ 7Y1Y N[ &[ 7Z +XCX /W?X D[GTC" "V)W;W=W AZ :X \"Y KY *j (X (X <Z3Z 2Z @Z !Z 6XIZ ?Y Z 0Z DZ2Z JZ1Z 0W V Y NZ KZ IYIZ ?Z0Z " "K[ &Z(\\ MZ MZ -[ Z(Z :Z \"Z 4Z?\\ 8Z 2YKX5XKY(YLZ6Z&[&[ MZ3[%[&\\#Z2[ JZ :Y 9Z(Z#Z+Z1Z7WJW7Z&Z@Z >Z<Z ![ 7X" " X ?Y :[8[ \"\\ 3YBZ \\ ,ZAY 4\\ &Y \"Z 0YAZ \"X >Y .Y3Y 3Z '\\ MZ )Z ;Z 2^ +Y ;Y " "X Y 6Y /Y5Y $[ =` G^ !Z IZ M\\ #Y2Z =YIZ 3\\ (Z .[%[%aIZI`\"Z(Z+[;Z;Z-[%[ B\\KXJ[" " &X '\\JXK\\ H\\ 1Z ,U&V EY;Y /X ,Z 'V@jDV Gp +UDj?V >V<V +X GW )` $nEW KV /W7W " "BW-X IW-X N`0W *YIZ 1YIY 0YHY 1YIY 0ZIY 1YIZ ?ZDZ 8[ MZ !Z Z !Z >Z !Z !Z \"Z :Z(\\%YLZ5Y&[&['[&[)\\&[)[%[)" "[&[$X'X%[-b&Z(Z#Z(Z$Z(Z$Y'Y I[=[ Az CY;` 5\\ $] $\\ \"\\ #\\ $] 8\\/[ 3\\ '\\ #\\ \"[ \"[ \"[ &Z &[ ![" " #\\ #[ ![ G[@W IYBZ J]8] I\\7\\ H]8] I]8] I\\7\\ 2X 8Y*Z @Z \"U .k 5q N~o Mm 4l =X" ".X 7^ 7Z3Z NZ %Z 6Z +XCX /W?W D[FT@S)W;W>X AZ :X \"Y JX (f &X )X ;Z3Z 2Z @Z !Z 7" "XHZ ?Y !Z /Z CY1Y JZ1Z 2Y Y $Z Z HY JYHY ?Z/Y L[ %Z'\\ NZ MZ -[ Z(Z :Z \"Z 4Z@\\ 7Z 2YKX5XKY(YKZ7Z'[" "$[ NZ2Z%[%[#Z2[ JZ :Y 9Z(Z#[,Z1Z8XJW7Z%ZB[ >[>Z !\\ 7X X ?Y ;[6[ (e 7YE` (e 3aEY 8c 2r 5`DX GYEa (X NX " "0X1Z 8Y FXD`9` YD` -c 9XD` /aEX :XD] 6g 7t BX0Y LY)Y+X6Z6X)Z/Z NX)Y I} 2Y X Y 9_>W KY5Y #[ =c h >XD` " "AT#X 5Y 6X0X LY'Y ?RCW ?~Y!X?X?X ;d 'r!~W KZ1Y =YHY 2\\ )Z /[$[%_GZG_#Z(Z+[;Z;Z-[%[ C\\JXI[ 'X (\\IXJ\\ " " (Y d 5Z -W(X FY<Y .X ,[ (UAmDV Iq ,VDl@U >V=W +X HX )^ ,Y1Y HnEW KV 0X7W BW-W HW.X M^/X )" "Y +YHY 2YHZ 1YHY 2ZHY 1YHY 2ZHY ?ZDZ 9[ LZ !Z Z !Z >Z !Z !Z \"Z :Z'[%YKZ6Y'\\%[)[$[*[%[)[%[)[%[%Y)Z&[.d'Z(Z#" "Z(Z$Z(Z$Y'Y H[>Z @{ DY=b ;f -f -f ,e -f -f Ae7c ;e /b )c *c *c 'Y NX NX X E[ >XD` -c )c *b *c )c '\\ &bDX L" "X0X GX0X GX0X GX0X KY)X KYE` ?Y*Y 8[4\\ K[3[ J\\4[ I[4\\ K[3[ 3X 8Z+Z AZ !U /m 6q N~o No 6o ?X.X 8_ " "6Y3Z Z $Z 6Z +XCX 0X@X DZET>Q)W;W>W ?Y :X \"X IY 'b $X )X ;Z2Y 2Z @Z !Z 8YHZ ?Y " "!Z 0[ CY1Y JZ1Z 5\\ \\ 'Z!Z FY LZHZ @Z/Y L[ %Z&[ NZ MZ .[ NZ(Z :Z \"Z 4ZA\\ 6Z 2YKX6YKY(YKZ7Z'[$[ NZ" "2Z&[#Z#Z2[ JZ :Y 9Z(Z\"Z,Z1Z8XJX8Z%[D[ <Z?[ \"\\ 6X X ?Y <[4[ -l :YGd ,k 9eGY :h 5r 8eGY GYGe +Y NX 0X3" "\\ 8Y FYGd=c!YGe 2h ;YGd 3eGX ;YG` 9m :t BY1Y LZ+Z+Y7[7Y*[1Z MY+Z J~ 2Y X Y <eAW KY5Y \"Z <f 'o CYFd D" "Y(Y 5Y 6Y1Y MY'Z CUE\\ B~Y!Y@X@Y =h 0z\"~W KY0Y >ZHY 1\\ *Z /[#['^EZE^$Z(Z+[;Z;Z.[#Z C[IXH[ (X ([HXI[ (" "Z $k 9Z .Y*Z FY=Y .X ,\\ *UAnCU J^CW -VCmAV ?W>V *X IX (a /Y1Y HnEW KV 0X7W BW.X HW.W La3X " "(Y ,ZHY 2YGY 2ZHZ 3YGY 1YHZ 3YGY @ZCZ 9[ LZ !Z Z !Z >Z !Z !Z \"Z :Z'\\&YJY6Y'[$[)[$[*[$[+[#[+[$[&[+\\([.e'Z(" "Z#Z(Z$Z(Z$Y'Y GZ?Z ?| EY>c >l 4l 3l 2l 3l 4l Gl=h @k 5h /h /h /h )Y Y NX Y E[ ?XFd 1g .h /h /h /h )\\ )hHX " "LY0X HY0X GX0X GX0Y LZ+Y KYGd AY*Y 9[EXD[ M[1[ L[1[ K[1[ M[1[ 4X 8Z+Y A[ !T /n 6q N~o q 8q @X.X 8` 7" "Y3Y Z $Z 5Z +XCX 0X@X DYDT EW;W?X ?Y :X #Y IY %^ \"X )X <Z1Z 3Z @Z !Z 8XGZ ?Y !Z" " 0Z BY2Z JY0Z 8_ _ *Z!Y DX LYFY @Z/Y M[ $Z&[ NZ MZ .[ NZ(Z :Z \"Z 4ZB\\ 5Z 2YJX7XJY(YJZ8Z([#[ NZ2Z&[" "#[$Z2[ JZ :Y 9Z(Z\"Z-Z/Z9XJX9Z#ZDZ :Z@Z \"\\ 5X NX @Y =[1Z 1q <YIh 0o =hHY <l 7r 9hIY GYHg ,Y NX 0X4\\ " "7Y FYIg@g#YHh 6l =YIh 7hHX ;YHa ;q <t BY1Y KY+Y*Y8\\8Y([3[ MY+Y I~ 2Y X Y =gCX KY6Z !Z <i -q CYHh F[*Y" " 5Z 7Y1Y NZ&Y EWG` D~Y!Y@X@Y >k 5}\"~W KY0Z ?YGZ 1[ *Z /Z\"[(]CZD^%Z(Z+[;Z;Z.[#[ CYHXGY 'X 'YGXHY 'Z &o" " ;Z /[,[ FZ?Y -X +\\ +UBoBU LZ>W -UBnAU >W@W *X JX 'c 1Y1Y HnEW KV /W7W BW.W GW/X Lc5W 'Y ," "YFY 4ZGY 2YFY 3YGZ 3YFY 3YGZ AZCZ 9Z KZ !Z Z !Z >Z !Z !Z \"Z :Z&[&YJZ7Y'[#[*Z\"Z+[#[+[#[+[#[&[-\\'[/YM[(Z(Z#" "Z(Z$Z(Z$Y'Y G[A[ ?} FY?] :p 8q 8q 7q 8q 8p LqAl Do 9l 3l 3l 3l +Y Y NX Y #i @XHh 5k 2l 3l 3k 2l +\\ +lKX KY0" "X HY0X GX0X GX0Y KY,Z KYIh CZ,Z :ZCXC[ [/[ N[.Z MZ.[ [/[ 5X 7Y,Z AZ !U /o 7p M~n s :s AX.X 8` 7Z4Y Y" " #Z 5Z +XCX 0W?X EYCT EW;W@X >Z ;X #Y HX #Z X *X ;Z1Z 3Z @Z !Z 9XFZ ?Y \"Z /Z " "BY2Z KZ0[ <b a -[\"Y BX MYFY @Z0Z M[ $Z%[ Z MZ .Z MZ(Z :Z \"Z 4ZD] 4Z 2YJX7XJY(YJZ8Z([\"[ Z2Z&Z\"[$Z2" "[ JZ :Y 9Z(Z!Z.Z/Z9WHW9Z\"ZF[ :[BZ \"\\ 4X NX @Y >[/Z 4t =YJj 3q >kJY >o 8r ;kJY GYJk .Y NX 0X5\\ 6Y FY" "JiBi$YJk 8o ?YJj 9kJX ;YJc <r <t BY1Y KZ-Z)X8\\8Y'Z4[ LZ,Y I~ 2Y X Y ?jDX KY6Y Z ;k 1r CYIj G]-Z 5Z 7" "Y1Y NZ&Z HYHb E~Y!Y@X@Y @n 8~P\"~W KY0Z ?YFY 0[ +Z 0[!Z)]BZB]&Z(Z+[;Z;Z.Z\"[ LQ GWGXFW HQ /X /Q*Q @WFXGW &Z" " (q ;Z .[BVB[ DY@Z -X *] .UC^EXBU LX<W .VBWC[AU ?WAW )X KX %c 2Y1Y HnEW KV /W7W BW/X GW/W J" "c7X 'Y ,YFY 4YFZ 3YFY 4YEY 3YFY 4ZFY AYBZ :[ KZ !Z Z !Z >Z !Z !Z \"Z :Z&[&YIZ8Y([\"[+[\"[,[\"Z+Z!Z,[\"[%[/\\" "&Z/YL[(Z(Z#Z(Z$Z(Z$Y'Y F[BZ >Z@d GY@\\ :t ;t <u ;t ;t ;t tDn Gr <o 6o 6o 6o ,Y Y NX Y &l @XIj 8o 5o 6n 6o 5o" " -\\ ,nLW JY0X HY0X GX0X GX0Y KY,Y JYJj CY,Y :ZBXBZ!Z+Z Z,Z Z,Z!Z+Z 6X 7Z-Z BZ U 0q 7o M~n s ;u BX." "X 9a 6Y5Z!Y \"Z 5Z +XCX C~d&YCT EW;W@W =[ <X #Y HY $Z X *X ;Z1Z 3Z @Z !Z :YFZ ?" "Y \"Z 0Z AZ3Z KZ0[ 5Z \"[ ?e d 0Z\"Y AY YEZ AZ0Z MZ #Z%[ Z MZ /[ MZ(Z :Z \"Z 4ZE] 3Z 2YJY9XIY(YIZ9Z(Z![ " "Z2Z'[!Z$Z2[ JZ :Y 9Z(Z!Z/[/Z:XHW9Z\"[H[ 8ZC[ \"[ 3X NX @Y ?[-Z 5v ?YKm 6r ?mKY ?q 9r <mKY GYKm /Y NX 0X" "6[ 4Y FYKkEl%YKm ;r @YKl ;mKX ;YKd >t <t BY1Y JY-Y(Y9]9Y&Z5Z JY-Y H~ 2Y X Y @lFX JY6Y NY 9k 4s CYJl H" "^.Y 4[ 8Y1Y NY$Y J[Ie G~Y!Y@X@Y Ap ;~R\"~W KY0Z @YEZ 0[ ,Z 0Z [*\\AZA\\&Z(Z+[;Z;Z/[![ NS GUFXEU HS 0X 0S,S @U" "EXFU %Z )r ;Z -[G^G[ CZAY ,X )] /UC[>TAU NX;W )P9P =UAWAYAU >XDX )X LX HY 3Y1Y HnEW KV /W7W " "AP9P 9W0X FW0X ?Y8W &Y -YEZ 5YEY 4ZFZ 5YEY 4ZEY 5YEY BZBZ :[ KZ !Z Z !Z >Z !Z !Z \"Z :Z%['YIZ8Y([!Z+Z![,Z![-" "[![-[!Z$[1\\&[/XJZ(Z(Z#Z(Z$Z(Z$Y'Y EZCZ =Z;` HYA[ 8u <u =v <v =u <u!uGr Js =r 9r 9r 9r .Y Y NX Y (o AXJl :q " "7q 9r 9q 7q .\\ -y IY0X HY0X GX0X GX0Y KZ-Y JYKl DY-Z ;ZAXAZ\"Y)Y!Z*Z\"Z*Z\"Y)Y 6X 7Z-Y BZ NT 0s 8o" " L~m!u =w CX.X 9b 7Y5Y Y \"Z 5Z +XCX C~d&YCT EX<WAX <Z <X #X GY &^ \"X *X ;Z0Y 3Z" " @Z !Y 9XEZ ?Y \"Z 0Z AZ3Y JZ/Z 5Z \"[ Ag g 4[\"X ?X YDY AZ0Z MZ #Z%[ Z MZ /[ MZ(Z :Z \"Z 4ZF] 2Z 2YIX9" "XIY(YIZ9Z(Z Z Z2Z'[![%Z2[ JZ :Y 9Z(Z!Z/Z.Z:XHX:Z!ZHZ 6ZDZ \"\\ 3X NY AY @Z*Z 6w @YLo 9t @oLY At :r =oLY " "GYLo 0Y NX 0X7[ 3Y FYLmGn&YLo =t AYLo >oLX ;YLe ?u <t BY1Y JY-Y(Y9]9X%[7Z IZ.Y H~ 2Y X Y AnGX JY7Z N" "Z 9k 6t CYKn I^/Z 5\\ 8Y1Y Z$Z L\\Jg H~Y!Y@X@Y Br =~S\"~W LZ/Y @YDY /[ -Z 0Z NZ+\\@Z@\\'Z(Z*Z;Z;Z/[![ U GSEXDS" " HU 1X 1U.U @SDXES $Z +t ;Z ,[JbJ[ AYBY +X (^ 2UCZ9QAU NW:W *Q:Q >VAW?XAU ?ZHY (X MX EX 4Y1Y HnE" "W KV /W7W AQ:Q :W0W EW1X <X:X &Y -YDY 6ZEZ 5YDY 6ZEZ 5YDY 5YEZ CZBZ :Z JZ !Z Z !Z >Z !Z !Z \"Z :Z%['YHZ" "9Y(Z Z+Z Z-[![-[![-Z [$[3\\%[0XI[)Z(Z#Z(Z$Z(Z$Y'Y E[E[ =Z9^ HYBZ 6v =v >w =w >v =v\"vIt Lt >t ;t ;t ;t /Y Y N" "X Y *r BXKn <s :t ;t ;s :t /\\ /{ IY0X HY0X GX0X GX0Y JY.Z JYLo FZ.Y :Y@X?Y$Y'Y#YIP5PIY\"Y.PIY$Y'Y 7X 6Z/Z" " CZ NU 1u 8m K~m\"w ?^C] CX.X 9b 7Z6Y X \"Z 4Z +XCX C~d&XBT EX=XAW ;[ =X $Y GY (" "b $X +X :Y/Z 4Z @Z \"Z :XDZ ?Y \"Y 0[ @Y4Z JZ/Z 5Z \"[ Dj j 8[\"X =X\"ZDY AZ0Z N[ #Z$[!Z MZ /Z L" "Z(Z :Z \"Z 4ZG] 1Z 2YIX:YIY(YHZ:Z)[ [!Z2Z'Z [%Z2[ J[ ;Y 9Z(Z Z0Z-Z;XHX;Z NZJ[ 6[FZ \"\\ 2X MX AY AZ(Z 7x" " AYMq ;u AqMY Bv ;r >qMY GYMp 0Y NX 0X8[ 2Y FYMoIp'YMq ?v BYMp ?qMX ;YMf ?u <t BY1Y JZ/Z(Y:^:Y$[9[ HY/Z H~ 2Y " " X Y BpHX JY7Z MY ;o 9u CYLp J_0Y 4\\ 8Y1Y Y#Z M]Jh I~Y!Y@X@Y Ct ?~T\"~W LZ/Y AZDY .[ .Z 1[ NZ+[?Z?['Z" "(Z*Z;Z;Z/Z NZ!W GQDXCQ HW 2X 2W0W @QCXDQ #Z ,u ;Z +[MfM[ ?YCY +X '_ 4UDZ'U W:W +R;R >U@W?XAU >j (X " " NX CX 5Y1Y HnEW KV /W7W AR;R ;W1X EW1W :X<X %Y .ZDY 6YCY 5YDZ 7YCY 5YDZ 7ZDY DZAZ ;[ JZ !Z Z !Z >Z " "!Z !Z \"Z :Z$Z'YHZ9Y)[ [-[ [.[ Z-Z NZ-Z [#[5\\$Z0XH[)Z(Z#Z(Z$Z(Z$Y'Y D[FZ <Z7] IYBY 5w >w ?x >x ?w >w#wKv Nu ?v" " =v =v =v 0Y Y NX Y +s BXLp >u <v =v =u <v 0\\ 0{ HY0X HY0X GX0X GX0Y JZ/Y IYMp EY.Y ;Y?X?Y%Y%Y$YJR7RIY$" "Y.RJY%Y%Y 8X 6Z/Y CZ MU 2v 8m K~m#y @[>\\ DX.X :c 7Z7Z!Y \"Z 4Z +XCX C~d&XBT DW=XB" "X :[ >X $Y FY +f &X +X ;Z/Z 4Z AZ !Z ;YDZ ?YFP -Z?Q BZ ?Z5Z JZ/Z 5Z \"[ Gj Ii ;[\"X1Q,W\"YCZ BZ1" "Z MZ \"Z$[!Z MZ /Z LZ(Z :Z \"Z 4ZH] 0Z 2YHX;XHY(YHZ:Z)Z N[!Z2Z([ NZ%Z2Z I[ ;Y 9Z(Z Z1Z,Z;XGW;Z N[L[ 4[H[ #\\" " 1X MX AY BZ&Z 8^Ga AYN[H_ <cI\\ B`I[MY CaH_ <r ?`H[NY GYNr 1Y NX 0X9[ 1Y FYNqJp'YMq @aJa CYN[H_ A`I[MX " ";YNg @`E[ <t BY1Y IY/Y&X:^:Y#Z:[ GY/Y G~ 2Y X Y JW5V B`M_JX IY8Z LY =r ;cL_ CYM^Na J`1Y 5^ 9Y1Y!Z\"Z ^K" "j J~Y!Y@X@Y D_I` A~U\"~W LY.Y AYCZ .[ /Z 1Z MZ,\\?Z?\\(Z(Z*Z;Z<[/Z NZ\"Y ;X ;Y 3X 3Y2Y 3X EZ -hM[ ;Z *~Q >" "YDY *X )b 6UDY%U V9W ,S<S >U@W>W@T =h 'X X AW 5Y1Y HnEW KV /X9X AS<S <W1W DW2X 9W<W $Y .YCZ 7Y" "CY 6YBY 7YCY 6ZCY 7YCZ EZAZ ;[ JZ !Z Z !Z >Z !Z !Z \"Z :Z$Z'YGZ:Y)[ NZ-[ [.Z N[.Z NZ.[ NZ\"[7\\$[1XFZ)Z(Z#Z(" "Z$Z(Z$Y'Y CZGZ ;Z6\\ IYCY 4^Ga ?^Ga @_Hb ?^Ga ?^Ga ?^Ga$^GaMaI`!bH\\ @aI` ?aI` ?aI` ?aI` 1Y Y NX Y ,u CXM^Nb" " @aKa >aJa ?aJa ?aKa =`Ja 1\\ 0`Ic GY0X HY0X GX0X GX0Y IY0Z IYN[H_ FZ0Z <Y>X>Y&X#X%YJT9TIY&Y.TJY&X#X 8X 5Y0" "Z CZ ;P4U 1w 9l J~m#z B[;[ EX.X :d 7Y7Y X )~Q #Z +XCX C~d&XBT DW=XCX 9\\ ?X $Y FY " "-j (X +X ;Z/Z 4Z AZ \"Z :XCZ ?YM_ 5ZE^ IZ >Y6Z IZ0[ 5Z \"[ Jj Ci ?\\\"X6\\2X#YBY BZ1Z MZ \"Z$[!Z " "MZ 0[ LZ(Z :Z \"Z 4ZI] /Z 2YHX;XHY(YGZ;Z)Z N[!Z3[([ NZ%Z2Z H[ <Y 9Z(Z NZ2Z,Z<XFW;Z MZLZ 2ZHZ #\\ 0X MX AY C" "Z$Z 9Y>^ BcB] >_?W C^CYNY C]A] 4Y /]Bc GYNYD^ 2Y NX 0X;\\ 0Y FYNXC\\KYD](YNYC] A]B^ DcB] C^CYNX ;YNZDQ A\\" ";V 5Y .Y1Y IY/Y&Y;_;Y\"Z;Z FZ0Y $[ 2Y X Y M];\\ F]E[JX IY9[ LY >ZKf =]=V CYNYC] K`2Z 5^ 9Y1Y!Z\"Z!^JZM^" " K~Y!Y@X@Y E]C^ CaHl\"~W LY.Z BYBY .\\ 0Z 1Z M[-[>Z>[(Z(Z*Z;Z<[0[ N[$[ <X <[ 4X 4[4[ 4X EZ ._KUHV ;Z )~ <Y" "EY *X *e 8UDY$T!W:X .U=T ?U?W>W@U =f &X !X @W 5Y1Y HnEW KV /X9X AT=T =W2X DW2W 8W=X $Y .YBY 8ZC" "Z 7YBY 8ZCZ 7YBY 8ZBY FZ@Z ;Z IZ !Z Z !Z >Z !Z !Z \"Z :Z$[(YGZ:Y)[ NZ-Z MZ.Z N[/[ N[/[ NZ![9\\#[2YFZ)Z(Z#Z(Z" "$Z(Z$Y'Y C[I[ ;Z5\\ JYCY 4X=^ @X=] @Y=] ?Y>^ @X=^ @X=^%X=l@\\\"_?W A]@\\ @]@\\ @^A\\ @^A\\ 1Y Y NX Y -w DXNY" "C] A^C^ ?^C^ A^B] @^C^ ?^C^ 2\\ 1^C_ FY0X HY0X GX0X GX0Y IY0Y HcB] FY0Y ;X=X=Y(Y#Y'YJV;VIX&X.VJY(Y#Y 9W 4Z1" "Z DZ =S4U 2y 9j I~l#{ BZ9Z EX.X :d 7Z8Y!Y *~R #Z +XCX C~d'YBT DX?XBW 7\\ @X $Y FY " "/ZNVNZ *X ,X :Z/Z 4Z AZ #Z :XBZ ?o 9ZGc MZ =Z8[ HY0\\ 6Z \"[ Li >j C\\\"X8aGVBW$ZBZ CZ2Z LZ \"Z#Z!" "Z MZ 0[ LZ(Z :Z \"Z 4ZJ] .Z 2YHX<YHY(YFY;Z)Z MZ!Z3[([ N[&Z3[ H] >Y 9Z(Z NZ2Z,Z<XFX<Z LZN[ 2[JZ \"[ /X LX B" "Y DZ\"Z :U7\\ Ca>\\ @^:T C\\?b D\\=\\ 5Y 0\\>a Ga?\\ 2Y NX 0X<\\ /Y Fa@\\MX@[(b@\\ B]?\\ Da?] D\\?a ;b 1Z6" "S 5Y .Y1Y IZ1Z&Y;_;X![=Z DY1Y #[ 2Y X Y `>` I\\B[KX IY:\\ LY ?ZDa ?\\7R Cb?\\ F[3Y 5_ 9Y1Y\"Z Y!]IYJ] L" "~Y!Y@X@Y F\\?\\ D^Ai\"~W LY.Z CZBZ .\\ 1Z 1Z LZ.[=Z>[(Z(Z*Z;Z<[0[ N[%\\ <X <\\ 5X 5\\4\\ 5X EZ /^IUFT ;Z (" "| ;YFY )X +h :TDY#U\"W:X /V?V ?U?W>XAU <c $X \"X ?X 6Y1Y HnEW KV .W9W @U>V ?W3X CW3X 8X>W #Y /Z" "BZ 9YAY 8ZBZ 9YAY 8ZBZ 9YAY FZ@Z ;Z IZ !Z Z !Z >Z !Z !Z \"Z :Z$[(YFZ;Y)Z MZ-Z MZ/[ MZ/[ N[/Z M[![;\\\"[3YE[*" "Z(Z#Z(Z$Z(Z$Y'Y B[JZ :Z4[ JYCX 3U8\\ @U8\\ AV8\\ @U7\\ AU7[ @U8\\%U8h=\\$]9T B\\=\\ B\\=\\ B\\=\\ B\\<[ 2Y Y " "NX Y .x Da?\\ C]?] A]?] B\\?] B]?] A]?] 3\\ 2]?] FY0X HY0X GX0X GX0Y IZ1Y Ha?] GY1Z <X<X<X(X!X'XJX=XJY(X.X" "JX(X!X 9W 4Z1Y >~d W5T 2{ 9i H~k$} DZ7Z FX.X :d 7Z9Z!X )~R #Z 0~d&XBT DX?XCX 6\\ " " =Y EY 0ZMVMZ +X ,X :Z/Z 4Z B[ %\\ :XBZ ?q ;YHg Z <Z:[ GZ1\\ 6Z \"[ i M~c Nj G\\!W9eIVBX%Y@Y CZ3[ M" "[ \"Z#Z!Z MZ 0Z KZ(Z :Z \"Z 4ZK] -Z 2YGX=XGY(YFZ<Z*[ MZ!Z3[(Z M[&Z3[ H^ ?Y 9Z(Z NZ3Z*Z=XFX=Z Kf 0[L[ #\\ /X " " LX BY JS4[ C`<\\ A\\5Q D[;` E[9Z 5Y 1\\<` G`<Z 2Y NX 0X=\\ .Y F_=[MV=[)`<[ D\\<\\ E`<[ E[;_ ;` 0Z3Q 5" "Y .Y1Y HY1Y%Y<`<Y [?[ DZ2Y $[ 1Y X Y !cBc J[?YLX HY<] JX @Y?_ @[ '`<[ EZ4Z 5` :Y1Y\"Z Z#\\GYI\\ EZ:Z IY@" "X@Y FZ;[ E]>\\ 0Z 6Y.Z CYAZ -\\ 2Z 1Z LZ.[=Z=[)Z(Z*Z;Z<Z/Z LZ&\\ ;X ;\\ 6X 6\\2\\ 6X EZ /\\GUCQ ;Z 'z 9YGY" " )X -ZN_ ;TDX\"U\"W;Y 0W@W ?T>W>X@T ;a #X #X =W 6Y1Y GmEW KV .X;X @W@W @W3W BW4X 6W?X #Y /Y@Y :" "ZAY 8Y@Y 9YAZ 9Y@Y 9YAZ GZ@Z ;Z IZ !Z Z !Z >Z !Z !Z \"Z :Z#Z(YFZ;Y)Z M[/[ MZ/[ MZ/Z LZ/Z M[ [=\\!Z3YD[*Z(Z#Z" "(Z$Z(Z$Y'Y AZKZ 9Z4[ JYDY 3R3[ AR3[ BS3Z @S4[ AS4[ AR3[&R3e:[&]6R C\\:[ D\\:[ D\\:[ D\\:[ 3Y Y NX Y /_B] E_<" "[ C[;[ B\\<\\ C\\<\\ C[;\\ C\\<\\ 3\\ 3\\<\\ FY0X HY0X GX0X GX0Y HY2Z H`<[ FY2Y ;X<X<X)X NX)YKZ?ZJX(X/ZKX)X" " NX ;X 3Y2Z >~d#Z6U 3} :h G~k%~P EY5Y FX.X ;ZNY 6Y9Z!X *~R \"Z 0~d&YCT CXAXBW 5] " " >Y EY 2ZKVKZ -X ,X :Z/Z 4Z BZ &] :XAZ ?s =YJk #[ ;[=[ FZ1\\ 6Z \"[ #j L~d Ki J\\!X:hKVAW%Y@Y CZ5\\ L" "[ \"Z#Z!Z MZ 0Z KZ(Z :Z \"Z 4ZL] ,Z 2YGX=XGY(YEZ=Z*[ M[\"Z4['Z LZ&Z4[ F` BY 9Z(Z MZ4Z*Z=XEW=Z Jd .ZLZ #\\ .X" " LX BY JQ1[ D_:[ B\\ ([9_ F[7Z 6Y 1[:_ G^9Z 3Y NX 0X>\\ -Y F^;b;Z)_:Z D[:\\ F_:[ G[9^ ;_ /Y EY .Y1Y " "HY2Z$Y=a=Y NZ@[ BY3Z %[ 0Y X Y \"eCd L[>YLX HY>^ IY AY=] @Z &_:Z DY4Y 5a :Y1Y\"Z Z$\\GYG\\ EY9Y IY@X@Y G" "Z9[ G\\;[ 0Y 5Y.Z DZ@Y ,\\ 3Z 1Z LZ.Z<Z=[)Z(Z*Z;Z<Z/Z LZ'\\ :X :\\ 7X 7\\0\\ 7X EZ 0\\FU -Z &x 8YHY (X -YK" "_ >UDX!T\"X<Y 1XAX ?T>W>X@U :] !X $X <W 6Y1Y GmEW KV .Y=X ?XAX AW4X BW4W 5W@X \"Y 0Z@Y :Y@Z 9Y@" "Y :Z@Y 9Y@Z ;Z@Y HZ?Z <[ IZ !Z Z !Z >Z !Z !Z \"Z :Z#Z(YEZ<Y*[ M[/[ M[0Z LZ/Z LZ/Z M[ N[?\\ Z3XBZ*Z(Z#Z(Z$Z(Z" "$Y'Y @ZM[ 9Z3[ KYDY 3P0Z AP0Z BQ0Z AQ0Z BP0Z AP0Z&P0b7Z'\\2P CZ7Z DZ7Z DZ7Z DZ7Z 3Y Y NX Y 0]<Z E^:Z D[9[ C[" ":\\ E\\:[ D[9[ C[:\\ 4\\ 3[9[ GY0X HY0X GX0X GX0Y HZ3Y G_:[ GY2Y <X;X;X*X NX)XJ[A\\JX*X/[JX*X NX ;X 3Z3Z " " >~d&^7U 4~ 9f E~i%~R GY4Y FX.X ;ZNZ 7Y9Y!X )~R \"Z NW?W BYCT CYBXCX 6_ ?Y EZ 5ZI" "VIZ /X ,X :Z.Y 4Z C[ )_ :YAZ ?t >YKn %Z 9\\A\\ EZ1\\ 6Z \"[ &j I~d Hi N\\ W:jLVAW&Z@Z DZ8^ KZ !Z#[\"Z " " MZ 0Z KZ(Z :Z \"Z 4ZM] +Z 2YGY?XFY(YEZ=Z*Z L[\"Z4['Z LZ&Z4[ Fc EY 9Z(Z MZ5Z)Z>XDW=Z Ic .[NZ #\\ -X KX CY " " )Z D^8[ D\\ '[8^ FZ5Z 7Y 2[8^ G]8Z 3Y NX 0X?[ +Y F]9`9Y)^9Z E[8[ F^8Z GZ8^ ;^ .Y EY .Y1Y GY3Y#Y=WNX=Y M" "ZAZ AY3Y %[ /Y X Y #gEf N[<YMX HYBb IY BY;] BZ %^8Z DY5Y 5b ;Y1Y#Z NZ$[FYF[ EY9Y IY@X@Y HZ8[ H\\9[ 1Y 5Y" ".Z DZ@Z ,\\ 4Z 2[ LZ.Z<Z<Z)Z(Z*[<Z<Z/Z LZ(\\ 9X 9\\ 8X 8\\.\\ 8X EZ 1\\EU -Z %^E] EhIg 6X .YI_ ?UEX T!W=" "Z 2YBY @U>W>W?U 7W <~d BX ;W 6Y1Y GmEW KV -X=X ?YBY BW4W AW5X 5W@W !Y 0Y?Z ;Y?Y :Z@Z ;Y?Y :Z?Y ;Y" "?Y HZ?Z <[ IZ !Z Z !Z >Z !Z !Z \"Z :Z#Z(YEZ<Y*[ LZ/[ M[0Z LZ/Z LZ0[ LZ M[A\\ NZ4XAZ*Z(Z#Z(Z$Z(Z$Y'Y @[NZ 8Z3" "[ KYDY AZ !Y Y Z !Z !Z 5`5Z([ %Z5Z FZ5Z FZ5Z FZ5Z 4Y Y NX Y 1\\:[ F]8Z F[7[ E[8[ E[8[ E[8[ E[8[ 4\\ 4[9\\" " GY0X HY0X GX0X GX0Y GY4Z G^8Z GZ4Z <X;X:W+X LX*WH[C\\IX*X0[HW+X LX <X 2Y4Z =~d(`7T 4~Q 9e E~i%~R GY3" "Y GX.X ;YMZ 7Z;Z!X *~R !Z X@X BZDT BXCYDX 6` ?Y DY 7[HVH[ 1X -X 9Z.Y 4Z D[ 7" "m 9X@Z ?v AZLp &Z 8^H_ DZ1\\ 6Z \"[ (i F~d Ei #\\ NW;lMV@W'Y>Y D~P JZ !Z#[\"~Q Dy Z K~] :Z \"Z 4ZN] *Z 2YFX?XF" "Y(YDZ>Z*Z L[\"Z5\\([ LZ&Z5\\ Eg JY 9Z(Z MZ5Z)Z>XDX>Z Ib ,f $\\ ,X KX CY (Y D]6Z D[ '[7^ GZ4Z 7Y 2Z6] " "G]7Z 4Y NX 0X@[ *Y F]8^8Z*]7Z FZ6[ G]6Z I[7] ;] -X DY .Y1Y GY3Y#Y=WNX=X L[CZ ?Y4Y &[ .X NX Y $iGh Z:XNX" " GYHg HY CY8\\ CY $]7Z DY6Y 4b ;Y1Y#Z MZ&[EYE[ FY9Y IY@X@Y HZ7[ I[7[ 2Y 5~V DY>Y +\\ 5Z 2Z KZ/[<Z<[*Z(Z)Z<Z<Z/" "ZIuIZ)\\ 8X 8\\ 9X 9\\,\\ 9X EZ 1[DU -Z $Z@[ EhJh 6X /YF_ ATDX U\"X?[ 3ZCZ @U>W>W?U K~d CX ;X " " 6Y1Y FlEW KV -Y?Y ?ZCZ CW5X AW5W 5XAX !Y 0Y>Y <Z?Z ;Y>Y <Z?Z ;Y>Y ;Y?Z JZ>~Q3[ I~Q G~Q F~Q G~Q 5Z !Z !Z " "\"Z :Z#Z(YDZ=Y*[ LZ/Z L[0Z L[0Z LZ0[ LZ L[C\\ N[5X@Z*Z(Z#Z(Z$Z(Z$Y'Y ?e 7Z3[ KYDY @Y Y !Z Y Y Y 4_4Y)[ %Z3" "Y GZ3Y FZ4Y FZ4Y 4Y Y NX Y 1[8Z F\\7Z F[7[ EZ6[ G[6[ G[6Z EZ6[ <Z9^ HY0X HY0X GX0X GX0Y GY4Y F]6Z GY4Y " " ;W:X:X,X LX+XG[E\\GW*W0[GX,X LX <X 2Z5Z =~d(`8U 4~R 9c D~h%~T HX2Y GX.X <ZLY 6Y;Z!X *~" "R !Z X@X BZDT BZGZCW 6b @Y DY 8ZFVFZ 2X -X 9Z.Y 4Z DZ 7l 8X?Z ?w BZMr ([ 7s C[3] 6Z \"[ +i C~d" " Cj '\\ NW;nNV@W(Z>Y D~ IZ !Z#[\"~Q Dy![ K~] :Z \"Z 4h )Z 2YFX@YFY(YDZ>Z*Z KZ\"Z5\\([ LZ&Z6\\ Ck Y 9Z(Z LZ6Z(" "Z?XDX?Z G` *d #[ +X KX CY 'Y E]6[ F[ &Z5] GY2Y 7Y 3Z4\\ G\\6Z 4Y NX 0XA[ )Y F\\7]6Y*\\5Y G[5Z G\\5Z I" "Z5\\ ;] -X DY .Y1Y GZ5Z#Y>XMW>Y K[E[ ?Y5Y &[ .Y NX Y $XIZHZIY!Z:XNX GYHf GY DY6[ CY $\\5Y CX6Y 5c ;Y1Y#" "Z MZ&[EYDZ FY9Y IY@X@Y IZ5Z IZ5Z 2Y 5~V EZ>Y *[ 5Z 2Z KZ/[<Z<[*Z(Z)Z<Z=[0[IuIZ*\\ 7X 7\\ :X :\\*\\ :X L[" "CU -Z %Z>Z EiKh 6X /XC^ BTDX U\"YA\\ 4ZCZ N~d &U>W?X>T K~d EY :W 5Y1Y EkEW KV ,YAY =ZCZ DW6X @W6" "X 5W@W 'Z>Y <Y=Y <Z>Z =Y=Y ;Y>Z =Z>Y JZ>~Q3Z H~Q G~Q F~Q G~Q 5Z !Z !Z \"Z :Z#[)YDZ=Y*[ LZ/Z KZ0Z L[1[ LZ0[ L" "Z K[E\\ M[6Y@Z*Z(Z#Z(Z$Z(Z$Y'Y >d 7Z2Z KYDY @Y Y Y NY Y !Y 4^3Z*Z $Z3Z HZ3Z HZ3Z HZ2Y 5Y Y NX Y 2[6Z G" "\\6Y FZ5[ G[5Z GZ5[ GZ5[ G[5Z =[:_ HY0X HY0X GX0X GX0Y GZ5Y F\\5Z GY5Z <X:X:X,W JW+XF[G\\FX,X1[FX,W JW <X " "2Z5Y <~d'UNY9U 5~T H[LaM[!~g&~V JY1X GX.X <ZLZ 7Y;Y X Z 3Z W?X AZET A\\M\\CX 7d " " BZ DY 8XDVDX 2X -X 9Z.Y 4Z E[ 7j 7Y?Z ?x CZNt )Z 5p @Z3] 6Z \"[ .i @~d @i *\\ MW<^Ib@W(Y=Z E| GZ !Z" "\"Z\"~Q Dy![ K~] :Z \"Z 4f 'Z 2YEXAXEY(YCZ?Z*Z KZ\"Z6\\'[ LZ&Z8] An $Y 9Z(Z LZ7Z'Z?XDX?Z F_ *c #\\ +X JX DY " " 'Y E\\4Z FZ %Z4\\ HZ1Y 8Y 3Z4\\ G[4Y 4Y NX 0XC\\ (Y F[6]6Y*[4Y GZ4[ H\\4Z JY4\\ ;\\ ,X DY .Y1Y FY5Y!Y?" "XMX?Y JZF[ >Z6Y &[ .Y NX Y %WEYJYEX#Z8a GYHe FY DX4[ DY $\\5Y CY8Z 5d <Y1Y$Z LZ'[DYD[ GY9Y IY@X@Y IY4Z J" "[5[ 3Y 6~W EY=Z *[ 6Z 2Z KZ/Z;Z<[*Z(Z)Z<Z=Z/[IuI[,\\ 6X 6\\ ;X ;\\(\\ ;X LZBU -Z %Y<Z FjMi 6X 0X@] CTD" "W NU!ZE^ 5ZCZ M~d &T=W@X=T K~d FY :X 5Y1Y EkEW 3Z CV +ZEZ ;ZCZ EW6W ?W7XA]\"XAX 'Y=Z =Y=Y <Y<Y =Y=" "Y <Z=Y =Y=Z KY=~Q3Z H~Q G~Q F~Q G~Q 5Z !Z !Z \"Z Ew5[)YCZ>Y*Z KZ/Z KZ0Z L[1[ L[1[ LZ J[G\\ L[7Y?Z*Z(Z#Z(Z$Z(Z$" "Y'Y >c 6Z2Z KYDY ?Y X NX NY Y Y 4\\1Y+[ %Z1Y HY1Y HY1Y HY1Y 5Y Y NX Y 3[5Z G[5Z HZ3Z GZ4[ HZ4Z HZ3Z GZ" "4[ >Z9` IY0X HY0X GX0X GX0Y FY6Z F\\4Z GY6Y ;W9X9W-X JX,WD[I\\DW,W1[DW-X JX =X 1Y6Z <~d'RKY:U 5~U J" "~T$~g'~X KY1X GX.X <YKZ 7Z<Y W NZ 3Y NW?W @\\GT @jCW 7f CZ DY 7VCVCV 1X .X " "8Z.Y 4Z F[ 6h 5X>Z ?y DgF` *Z 2k >Z4^ 6Z \"[ 1j >~d =i -[ LW=\\C_?W)Y<Y Ez EZ !Z\"Z\"~Q Dy![ K~] :Z \"Z 4e &Z" " 2YEXAXEY(YCZ?Z*Z KZ\"Z8^'[ L['Z:_ @p 'Y 9Z(Z KZ8Z'Z@XBW?Z F^ (b $\\ *X JX DY &X E[2Y FZ &Z3\\ HY0Y 8Y" " 3Y2[ G[4Y 4Y NX 0XD\\ 'Y F[5[5Y*[4Y HZ2Z H[3Z KZ3[ ;[ ,Y DY .Y1Y FY5Y!Y?WLX?Y J[GZ <Y7Z '[ -Y NX Z 'WC" "YKXBV#Z8` FYHc +YCY EY4[ DY $[4Z CX8Y 5e <Y1Y$Z KZ([DYCZ GY9Y IY@X@Y IY3Z KZ3Z 3Y 6~W EY<Y )[ 7Z 2Z KZ/Z;Z;Z*Z(" "Z)[=Z=Z/[IuI[-\\ 5X 5\\ <X <\\&\\ <X LZBU -Z &Y:Y FjNj 6X 0X?] EUEX NU!s 6ZCZ L~d &T=WAY=T K~d GX" " 9Y 5Y1Y DjEW 3Z CV *]M] 9ZCZ FW7X5X3W7WCc%XBX5Y JY<Y >Z=Z =Y<Y >Z=Z =Y<Y >Z=Z LZ=~Q3Z H~Q G~Q F~Q G~Q" " 5Z !Z !Z \"Z Ew5[)YCZ>Y*Z KZ/Z KZ0Z KZ1[ L[1Z KZ I[I\\ K[8Y>[+Z(Z#Z(Z$Z(Z$Y'Y =a 5Z2Z KYDY ?Y Y X MX Y Y" " 4\\1Y+Z $Y0Y IZ1Y IZ1Y IZ0X 5Y Y NX Y 3Z3Y GZ3Y HZ3Z HZ2Z IZ2Z IZ3Z GZ3Z >Z:a IY0X HY0X GX0X GX0Y FZ7Y E[" "3Z GY6Y ;W9X9W-W HW,WC[K\\CW,W2[CW-W HW =X 1Z7Z <~d NX:U 5~V M~X%~e&~Y LX0Y HX.X =ZJY 6Y=Z W " " NZ 3Y X@X ?]IT ?hCW 7h2X ;Y CY 7TAVAT 1X .X 8Z.Y 4Z G\\ 6g 5X=Z ?X?a EeB^ +Z /f ;[5" "^ 4i ;~d :i 1[ LW<Z?]?W*Z<Z Fx CZ !Z\"Z\"~Q Dy![ K~] :Z \"Z 4e &Z 2YEXBYEY(YBZ@Z*Z KZ\"Z9^&[ L['[Ad >r *Y " "9Z(Z KZ8Z'Z@XBX@Y D\\ &` $\\ )X JX DY &X E[2Z HZ %Z3\\ IZ/X 8Y 4Z2[ GZ3Y 4Y NX 0XE\\ &Y FZ4[5Y*[4Z IZ" "2Z H[2Y KY2[ ;[ +X DY .Y1Y FZ7Z!Y?WLX?X H[IZ ;Y7Y '[ ,Y NX NY *Q NV@WLW?U#Z8` FYHd .^FY EX2[ DX $[3Y CX8Y" " 5YMY <Y1Y$Z KZ(ZCYCZ GY9Y IY@X@Y JY2Z L[3Z 3Y 6~W FZ<Z )[ 8Z 2Z KZ/Z;Z;Z*Z(Z)[=Z>[/[IuI[.\\ 4X 4\\ =X =\\$\\" " =X MZAU -Z &X8Y G~W 6X 0W<\\ FUEX MT iNW 8[D[ K~d &T=WE\\<T K~d HX NQ<Y 4Y1Y CiEW 3Z CV )k 7" "ZC[ HW7W5Y3W8XFh>Q<YAW5Z KZ<Z ?Y;Y >Z<Z ?Y;Y >Z<Z ?Z<Y LZ=~Q3Z H~Q G~Q F~Q G~Q 5Z !Z !Z \"Z Ew5[)YBZ?Y*Z KZ/" "Z KZ0Z KZ1[ L[1Z KZ H[K\\ J[8X=[+Z(Z#Z(Z$Z(Z$Y'Y <` 5Z2Z KYDZ ?X Y Y NX NX NX 4[/Y,Z $Y/Y JY/Y JY/Y JY/Y " "6Y Y NX Y 3Z3Z HZ3Y IZ1Z IZ2Z IZ2Z JZ1Z IZ2Z ?Z:b IY0X HY0X GX0X GX0Y EY8Z E[2Y GZ8Z ;W9X9X.W HW-XB[M" "\\BW,W3[BX.W HW =X 0Y8Z ;~d NY;U 6~X!~[%~c&~Z LX0Y HX.X =ZJZ 7Y=Y N~l 4Z 3Y X@X ?`L" "T >eBX<U\"[M\\4Y ;Y CZ 7Q?V?Q 0X .X 8Y-Z 5Z H\\ 5j 9Y=Z ?T9_ Ec>] ,Z 1j <[7_ 7i 8~d 7i 5[ KW=Z=" "\\?W*Y:Y F{ FZ !Z\"Z\"~Q Dy![1j&~] :Z \"Z 4e &Z 2YDXCXDY(YBZ@Z*Z KZ\"Z<a&Z K['} <s ,Y 9Z(Z KZ9Z%ZAXBXAZ E] &_ $" "\\ (X JY EY &Y F[2Z HZ %Y1[ IY.Y 9Y 4Z1Z GZ3Z 5Y NX 0XF\\ %Y FZ4Z3Y+Z2Y IZ1Z I[2Z LY1Z ;[ +X DY .Y1Y " "EY7Y NX@XKW@Y G[K[ :Y8Y ([ ,Z NX NY /[(R NU?XNW=U%Z7_ EYHg 3bHY FY1Z DX $Z2Y CY:Y 5ZMZ =Y1Y$Z KZ)[CYBY GY9Y" " IY@X@Y JY1Y LZ1Z 4Y 6~W FY;Z *[ 7Z 2Z KZ/Z;Z;Z*Z(Z(Z=Z>[/[IuI[/\\ 3X 3\\ >X >\\\"\\ >X MZAU -Z 'X6X 5c " "%X 1X;\\ GUEX MT NgMW 9[D[ J~d &T=m;T K~d In 4TA[ 4Y1Y BhEW 3Z DX )i 5[D[ IX9W5Z3W8WFj?TA[BX5Z KY" ";Z @Z;Z ?Y:Y @Z;Z ?Z;Y ?Y;Z NZ<~Q3Z H~Q G~Q F~Q G~Q 5Z !Z !Z \"Z Ew5[)YAY?Y*Z KZ/Z KZ1[ KZ1[ L[1Z KZ G[M\\ IZ8" "X<[+Z(Z#Z(Z$Z(Z$Y'Y <_ 4Z2Z KYD[ @X NX Y NY X NX 3Z/Y-Z $Z/Y KZ/Y KZ/Y KZ/Y 6Y Y NX Y 4Z2Z HZ3Y IZ1Z I" "Z1Z JY1Z JZ1Z IZ1Z @Z;XNZ JY0X HY0X GX0X GX0Y EY8Y D[2Z GY8Y ;X9X8W.W HW-W@hAW-X4[@W.W:[:W =X 0Z9Z I" "[ 7Y<U 6~Y\"~^'~c'~\\ MX/X HX.X =YIZ 7Z>Y ~m 4Z 3Y W?X >g =cAW?]'[K\\5Y ;Y CZ %V M" "X /X 7Y-Z 5Z H[ 4l ;X<Z ?Q4^ Fb<] .[ 3o ?[7_ :i 5j 9[ JW=Y;[?W+Z:Y F~ IZ !Z\"Z\"~Q Dy![2l'~] :Z " "\"Z 4f 'Z 2YDXCXDY(YAZAZ*Z KZ\"~%Z K['| 9s .Y 9Z(Z JZ:Z%ZAXBXAZ E] %] #[ 'X IX EY &Y FZ0Y HY %Z1[ IY.Y" " 9Y 4Y0Z GZ2Y 5Y NX 0XG[ #Y FZ4Z3Y+Z2Y JZ0Z IZ0Y MZ1Z ;Z *Y EY .Y1Y EY8Z NYAXKXAY FZL[ 9Y9Y ([ +Y MX NZ 4b," "S U=`=U%Z6^ EYHi 6dIY FY1Z DY %Z2Y BX:Y 5ZLY =Y1Y%[ KZ)ZBYBZ HY9Y IY@X@Y JY1Z MZ1Z 4Y 6~W GZ:Y +\\ 7Z 2Z KZ/Z" ";Z;Z*Z(Z([>Z>Z.[IuI[0\\ 2X 2\\ ?X ?\\ \\ ?X MY@U 8y ;X6X 4a $X 1X9[ HUEX MT MeLW :[D[ I~d &T=l:T " "K~d Io 5m 3Y1Y AgEW 3Z Nl 2g 3[D[%lDX5Z>mDXFk@mAW5[ LZ:Y @Y:Z ?Y:Y @Z:Y ?Y:Z AZ:Y NZ<~Q3Z H~Q G~Q F~Q G" "~Q 5Z !Z !Z \"Z Ew5[)YAZ@Y*Z KZ/Z KZ1[ KZ1[ L[1Z K[ Gh HZ9X;[+Z(Z#Z(Z$Z(Z$Y'Y ;] 3Z2Z KYC[ AX NX Y NY Y X" " 3Y.Y-Z $Y.Y KY.Y KY.Y KY.Y 6Y Y NX Y 4Z1Y HY2Y IZ1Z IY0Z KZ0Z KZ1Z IY0Z @Y;XMZ JY0X HY0X GX0X GX0Y DY9Y D" "Z0Y GY9Z ;W8X8W.W HW-W?f?W.W4[?W.W:[:W =X 0Z9Y HZ 5X<U 6~Z$~`'~a&~\\ NY/X HX.X =YHY 7Z?Z ~m " " 4Z 3Y W?W <i >_@XAa*[I\\6Y ;Y CZ %V MX /X 7Y-Z 5Z I[ 3n >X;Z ] G`9\\ .Z 4s @[9` " " =i /i ;Z IV=Y9Z>V+Z:Z G~P JZ !Z\"Z\"~Q Dy!Z1l'~] :Z \"Z 4g (Z 2YDYEXCY(YAZAZ*Z KZ\"}$Z K['z 5r /Y 9Z(Z JZ;Z" "$ZAW@WAZ F_ %\\ $[ &X IX EY &Y FZ0Y IZ %Y/Z IY.Y 9Y 4Y0Z GY1Y 5Y NX 0XH[ \"Y FY3Z3Y+Z2Y JZ0Z IZ0Y MY0" "Z ;Z *Z FY .Y1Y DY9Y MYAWJXAY F[MZ 8Z:Y )[ +Z MX N[ 7g1U U<^;U&Z6^ EYHj 9gJY FX/Y CY &Z2Y BY<Z 6ZKZ >Y1Y%Z" " J[*ZBYBZ HY9Y IY@X@Y KY0Z MY/Y 4Y 6~W GZ:Z ,[ 6Z 2Z KZ/Z;Z;Z*Z(Z([>Z?[.ZHuI[1\\ 1X 1\\ @X @\\ M\\ @X NZ" "@U 8y ;W4X 5` #X 1X8Z HUEX MT LbJW ;ZC[ H~d &T=j8U L~d Io 5l 2Y1Y @fEW 3Z Nl 0c 0[CZ&lDW5[>mEXE\\N^" "AlAX6\\ LZ:Z AY9Y @Z:Z AY9Y @Z:Z AY9Z!Z;~Q3Z H~Q G~Q F~Q G~Q 5Z !Z !Z \"Z Ew5[)Y@ZAY*Z KZ/Z KZ1[ KZ1[ L[1Z K" "[ Ff GZ:X:[+Z(Z#Z(Z$Z(Z$Y'Y :\\ 3Z2Z KYC\\ BY X NX NY Y X 3Y-X-Y #Y-X KY-X KY-X KY-X 6Y Y NX Y 5Z0Y HY" "2Y IY/Y JZ0Z KZ0Z KY/Z KZ/Y AZ;WKY JY0X HY0X GX0X GX0Y DY:Z DZ0Y FY:Y :WK~KW.WK}KW-W>d>W.W5[>W.W:[:W =X /" "Y:Z IZ 4Y=T 6~[%~b'~_%~\\ NY/X HX.X >ZHY 6Y?Y N~m 4Z 3Y !X@X ;l @[>WBe,ZG\\7Y ;Y" " CZ %V ;~c LX 7Y-Z 5Z J\\ 2n @Y;Z N\\ G`8\\ /Z 5u A\\<b ?i *i ?Z IW=X8Z>V+Y8Y G~R LZ !Z\"Z\"~Q" " Dy![2l'~] :Z \"Z 4h )Z 2YCXEXCY(Y@ZBZ*Z KZ\"|#Z K['x 0q 1Y 9Z(Z IZ<Z$ZBX@XBY F` %[ $\\ &X IX EY &Y FZ" "0Z JZ %Y/Z JY,X 9Y 5Z0Z GY1Y 5Y NX 0XI[ !Y FY3Z3Y+Y1Y JZ/Y IZ0Y MY/Y ;Z *[ GY .Y1Y DY9Y MYBXIWBY Dg 7Y;Z *[ +" "[ MX M[ :l6W T:\\:U&Y5] DYHk :hKY GY/Z DZ 'Z2Y BY<Y 5ZKZ >Y1Y%Z IZ*YAYBZ HY9Y IY@X@Y KY/Y MY/Y 4Y 6~W GY9Z " "-[ 5Z 2[ LZ/Z;Z;Z*Z(Z'[?Z?[.[IuI[2~n BX B~n AX A~m AX NZ@U 8y <X4X 4_ #X 1X7Z IUEX MT J^HW <ZCZ F~d &T=" "g5T -X ,o 5k 1Y1Y >dEW 3Z Nl ._ ,ZCZ'lEX6\\>mEWDVCZBkAX6] LY8Y BZ9Z AY8Y BZ9Z AY8Y BZ9Z!Z;~Q3Z H~Q " "G~Q F~Q G~Q 5Z !Z !Z \"Z Ew5[)Y@ZAY*Z KZ/Z KZ1[ KZ1[ L[1Z KZ Ee FZ;Y:[+Z(Z#Z(Z$Z(Z$Y'Y :[ 2Z2Z KYB\\ CY X NX" " NY Y Y 4Y-Y.Y #Y-X KY-X KY-Y LY-Y 7Y Y NX Y 5Z0Z IY2Y JZ/Z KZ/Y KY/Z KY/Z KZ/Y#~d$Z<WJY JY0X HY0X GX0X G" "X0Y DZ;Y CZ0Y FY:Y :WK~KW/WJ}JW.W=b=W.W6[=W/W9[9W >X /Z;Z JZ 2X>U 6~\\'~c&~^$~Z MY/X HX.X >YGZ 7Z@Y " "N~m 4Z 3Y !X@X :n 'WBg.ZE\\8X :Y CZ %V <~e NX 6Y-Y 4Z K\\ #a AX:Z M\\ H_6[ 0Z" " 6aI` A]?c ?f $f ?Z IW>Y7Y>V,Z8Z HZ8` MZ !Z\"Z\"Z MZ 1[2l'Z(Z :Z \"Z 4ZN] *Z 2YCXFYCY(Y@ZBZ*Z KZ\"{\"Z " "K['v +o 2Y 9Z(Z IZ<Z#YBX@XCZ Fa %Z %\\ %X HX FY 6i FZ0Z JZ %Y/Z JY,X 9Y 5Z/Y GY1Y 5Y NX 0XK\\ Y FY3Z" "3Y+Y1Y JY.Y IY/Z NY/Y ;Z *\\ HY .Y1Y DZ;Z LXBXIWBY Ce 6Y;Y )[ -\\ LX L\\ >q:X !U:[9U&Y5] DY?d =jLX FY/Z C[ " ")Y1Y AX=Z 6ZIY >Y1Y%Z IZ*YAYAY HY9Y IY@X@Y KY/Y NZ/Z 5Y 5Y-Y HZ8Y .[ 4Z 1Z LZ/Z;Z;Z*Z(Z'[?Z@[-[ L[3~o BX B~o BX" " B~o BX NZ@U 8y <X4X 4^ \"X 1X6Y IUEX MT GW *ZCZ E~d &T=g5T -X ,o 5i /Y1Y <bEW 3Z Nl *W 'ZCZ(l", "EW6]>mFXDS?YBi?W5] CY 4Z8Y BY7Y BZ8Z CY7Y AY8Z CZ8Y!Y:Z <Z HZ !Z Z !Z >Z !Z !Z \"Z Ew5[)Y?ZBY*Z KZ/Z KZ1[ KZ" "1[ L[1Z KZ Dc E[=Y9[+Z(Z#Z(Z$Z(Z$Y'Y 9Z 2Z2Z KYB^ &i 0i 1i /i 0i 0i Ej-Y/Z $Z-Y MZ-Y MZ-Y LY-Y 7Y Y NX Y 5Y/" "Z IY1X JZ/Z KZ/Z LY.Y LZ/Z KZ/Z$~d$Z=WIZ KY0X HY0X GX0X GX0Y CY<Z CY/Z GZ<Z :WK~KW/WJ}JW.W<`<W.W7[<W/W9[9W " ">X .Y;Y JZ 1Y?U 6~\\(~e'~]\"~X LX.X HX.X >YFY 7ZAZ N~m 4Z 3Y !W?X 9p +XCi0ZC\\9X " " :Y CZ %V <~e NX 6Z.Y 4Z L\\ M^ CY:Z L[ H^4Z 0Z 7^A^ C_Ce ?c Mc @Z HW>X6Y>V,Y7Z HZ5^ NZ !Z\"" "Z\"Z MZ 1[2l'Z(Z :Z \"Z 4ZM] +Z 2YBXGXBY(Y?ZCZ*Z KZ\"z![ LZ&w 'k 3Y 9Z(Z IZ=Z\"ZCX@XCZ Gc &Z &\\ $X HX FY " " >q FY.Y JY $Y/Z JY,X 9Y 5Y.Y GY1Y 5Y NX 0XL\\ NY FY3Z3Y+Y1Y JY.Z JY/Z NY/Y ;Y (^ KY .Y1Y CY;Y KYCXIXCY " "Bc 4Y<Y *[ 2a KX La Du?Z !U9Z8T'Z5] DY9^ >\\IYMX FY/Z B\\ +Y1Y AY>Y 5ZIZ ?Y1Y%Z IZ*YAYAY HY9Y IY@X@Y KY/Y NZ" "/Z 5Y 5Y-Y HZ8Z 0\\ 4Z 1Z LZ/Z;Z;Z*Z(Z&[@Z@[-[ L[4~p BX B~o BX B~p CX NY?U 8y <W2W 3] \"X 1Y7Y IUEX MT " " JZCZ 8X &T=WIZ6T -X ,o 3e -Y1Y :`EW 3Z Nl (ZCZ)lFW5UNV>mFWCQ;XAe>X6UNW CY 4Y7Z DZ7Y BZ8Z CY7Z CZ7" "Y CY7Z#Z:Z <Z HZ !Z Z !Z >Z !Z !Z \"Z :Z#[)Y?ZBY*Z KZ/Z KZ0Z KZ1[ L[1Z KZ Ca D[>Y8[+Z(Z#Z(Z$Z(Z$Y'Y 9Z 2Z3[ " "KYA^ /q 9r 9q 7q 8q 9r Mq,Y/Z $Y,Y MY,Y MY,Y MZ-Y 7Y Y NX Y 5Y.Y IY1X JZ/Z KY.Z LY.Y LZ/Z KY.Z$~d$Y=XIZ KY0X" " HY0X GX0X GX0Y CY<Y BY/Z FY<Y 9WK~KW/WJ}JW.W;^;W.W8[;W/W9[9W >X .Y<Z K[ 1Y@U 6~](~f'~[ ~V KX.Y IX.X" " ?ZFY 6YAZ N~m 4Z 3Y !W?W 6p -WCk1ZB\\;Y :Y CZ %V <~e NX 6Z.Y 4Z M\\ J] EY9Z " " L[ H^4[ 2[ 8\\<\\ BbKi ?` Ha @Z HV=X5X>W-Y6Y HZ2\\ Z !Z\"Z\"Z MZ 1[2l'Z(Z :Z \"Z 4ZL] ,Z 2YBXGXBY(Y?Z" "CZ*Z KZ\"x N[ LZ&x #f 3Y 9Z(Z HZ>Z\"ZCW>WCZ Hd &Z &[ #X HX FY At FY.Y JY $Y/Z JY,Y :Y 5Y.Y GY1Y 5Y NX" " 0XM\\ MY FY3Y2Y+Y1Y JY.Z JY.Y Z/Y ;Y (b Y .Y1Y CY;Y KYCWHXCY Bb 3Y=Y *[ 6e JX Ke KzF^ !U9Y7T'Z4[ CY7] @[E" "XNX GZ.Y Ai 9Y1Y AY>Y 5YHZ ?Y1Y&[ IZ+ZAYAY HY9Y IY@X@Y KY/Y NZ.Y 5Y 5Y-Y IZ6Y 0[ 3Z 1Z LZ/Z;Z;Z*Z(Z&\\AZA[,[ L[" "4~p BX B~o BX C~q CX NY?U 8y <W2W 3\\ )Y6Y JUEX NU KZCZ 7X &T=WGY7T -X J^ *Y1Y 7]EW 3Z " " 8ZCZ 4X6UMV GX-X=^;W6UMW CY 4Y6Y DZ7Z CY6Y DZ7Z CY6Y DZ7Z#Z:Z <Z HZ !Z Z !Z >Z !Z !Z \"Z :Z#[)Y>ZCY*Z K" "Z/Z KZ0Z L[1[ L[1Z KZ B_ C[>X7[+Z(Z#Z(Z$Z(Z$Y'Y 9Z 2Z3[ KY@_ 5u <u <t :t <u <u!t,Y/Y #Y,Y MY,Y MY,Y MY,Y 7Y Y " " NX Y 6Z.Y IX0X JY-Y KY.Z MZ.Y LZ.Y KY.Z$~d$Y>XHZ KY0X HY0X GX0X GX0Y BY=Y BY.Y FY=Z 9WK~KW/WJ}JW.W:\\:W.W" "9[:W/W9[9W >X .Z=Y JZ /X@U 6~^*~g&~Y N~V KX.Y IX.X ?ZFZ 7ZBY L~l 4Z 3Y \"X@X 3n /X" "CZIZ2Z@\\<Y :Y BY %V <~e Y 6Z.Y 4Z N\\ G\\ FX8Z K[ I]2Z 2Z 8\\9[ BsNZ ?] B^ @Y GV=W4X>W.Z6" "Z IZ1[ Z !Z#[\"Z MZ 1[2l'Z(Z :Z \"Z 4ZK] -Z 2YBXHYBY(Y>ZDZ*Z KZ\"v L[ LZ&z !c 4Y 9Z(Z HZ>Z\"ZDX>XDY Ge 'Z '[ " "\"X GX GY Dw FY.Y JY %Z/Z J~W :Y 5Y.Y GY1Y 5Y NX 0XN\\ LY FY3Y2Y+Y1Y JY.Z JY.Y Z/Y ;Y 'e $Y .Y1Y CZ=Z" " KYDXGWDY @a 3Z>Y +[ 5d IX Ic L~d !U8X7T'Z4[ CY5\\ AZCa GY-Y @h 9Y1Y @X?Z 6ZGY ?Y1Y&[9X9Z+ZAYAZ IY9Y IY@X@Y " "KY/Z Y-Y 5Y 5Y.Z IZ6Z 2[ 2Z 1Z M[/Z;Z<[*Z(Z%[AZB\\,[ LZ3~p BX B~o BX C~q CX NY?U 8y <W2W 2[ (Y7Y ITDW " "NU M[CZ 6X &T=WFY8T -X EY1Y 1WEW 3Z 7ZC[ 6W6ULV HX+W JX7ULW CY 5Z6Z EY5Y DZ6Z EY5Y DZ6Z E" "Z6Y$Z9Z <Z HZ !Z Z !Z >Z !Z !Z \"Z :Z#[)Y>ZCY*Z KZ/Z KZ0Z L[1[ L[1[ LZ A] B[?X6Z*Z(Z#Z(Z$Z(Z$Y'Y 9Z 2Z3[ KY?" "_ 8w ?x ?w =w >w >w$~u/Y #~W M~W M~W M~W 7Y Y NX Y 6Z.Y IX0X JY-Y KY.Z MZ.Z MY-Y KY-Y$~d$Y?XFY KY0X HY0X GX0" "X GX0Y BY>Z BY.Y EY>Y 8WK~KW/WJ}JW.W;]:W.W:[9W/W9[9W >X -Y>Z KZ .YAU 6~^*~g%~W L~T JX.Y IX.X ?YEZ 7Z" "CZ L~k :y KY \"X@X 0m 1WCYEY3Y>\\=X 9Y BY %V <~e =l X 5Z.Y 4Z \\ E[ GY8Z JZ I]" "2Z 2Z 8[7[ BqMZ ?^ C^ @Y GV=W4X>V-Y5Z IZ0[!Z !Z#[\"Z MZ 1[2l'Z(Z :Z \"Z 4ZJ] .Z 2YAXIXAY(Y=YDZ*Z L[\"s" " I[ LZ&[Cc Na 5Y 9Z(Z HZ?Z YDX>XEZ Hg (Z (\\ \"X GX GY Fy FY.Y KZ %Z/Z J~W :Y 5Y.Y GY1Y 5Y NX 0e KY" " FY3Y2Y+Y1Y KZ.Z JY.Y Y.Y ;Y &h (Y .Y1Y BY=Y IXDXGWDY ?_ 1Y?Z ,[ 4b GX Ga L~c T6V6T'Z4[ CY4\\ CZ@_ GY-Y >f " "9Y1Y @Y@Y 5YFZ @Y1Y&Z8X9[,ZAYAZ IY9Y IY@X@Y KX.Z Y-Y 5Y 5Y.Z IY5Z 3[ 1Z 1Z M[/[<Z<[*Z(Z%\\BZC\\+[ LZ3~p BX B~o " "BX C~q CX DX 4Z?U -Z (W2W 2Z 'Z7X ITDX U MZCZ 5X &U>WEY9T -X EY1Y 1WEW 3Z 6ZCZ 7X7" "UKV HW*W KX6ULW CY 5Y5Z FZ5Z EY4Y FZ5Z EZ5Y EY5Z%Z9Z <Z HZ !Z Z !Z >Z !Z !Z \"Z :Z#Z(Y=ZDY*[ LZ/Z KZ0Z L[0Z " "LZ0[ LZ A] B[@X5Z*Z(Z#Z(Z$Z(Z$Y'Y 9Z 2Z4[ JY>` <y @y Ay ?y @y @y%~v/Y #~W M~W M~W M~W 7Y Y NX Y 6Z.Y IX0X JY" "-Y KY-Y MZ.Z MY-Y KY-Y$~d$Y?WEY KY0X HY0X GX0X GX0Y BZ?Y AY.Y EY>Y 8WK~KW/WJ}JW.W<_;W.W;[8W/W9[9W >X -Z?Z " " LZ -YBU 5~^*~h%~U J~R IX.Y IX.X @ZDY 6YCZ LW 'y JY \"W?X ,j 3WCYCY4Y=\\>X 9Y CZ" " %V <~e =l X 5Z.Y 4Z !\\ C[ IY7Z JZ I]2Z 3[ 9[5[ BoLZ ?a Ia @Y HW>X3W>V.Z4Y IZ/Z!Z !Z#[\"Z MZ 0" "Z Z'Z(Z :Z \"Z 4ZI] /Z 2YAXIXAY(Y=ZEZ*Z L[\"o DZ LZ&Z<^ M_ 5Y 9Z(Z GZ@Z ZEX>XEZ I[MZ (Z )\\ !X GX GY " "Gz FY.Y KZ %Y-Y J~W :Y 5Y.Y GY1Y 5Y NX 0c IY FY3Y2Y+Y1Y KZ.Z JY.Y Y.Y ;Y %j +Y .Y1Y BY=Y IYEXGXEY >] 0Y?Y ,[ " "3` EX E_ L\\Cx NT6V6T'Z4Z BY2Z CY>^ GY-Y ;c 9Y1Y @YAZ 6ZEY @Y1Y&Z8X9[,ZAYAZ IY9Y IY@X@Y KX.Z Y-Y 5Y 5Y.Z JZ" "4Y 4\\ 1Z 1[ NZ.[<Z<Z)Z(Z$\\CZD]*Z LZ3~p BX B~o BX C~q CX DX 4Z?U -Z (W2W 2Z 'Z7X ITDX U MYBY 4X &U>" "WDX:U -X EY1Y 1WEW 3Z 5YBY 7W6UKV IX*W KW6UKW CY 6Z4Y FZ5Z FZ4Z GZ4Y EY4Z GZ4Y%Y8Z <[ IZ !Z " " Z !Z >Z !Z !Z \"Z :Z#Z(Y=ZDY*[ LZ/Z L[0Z L[0Z LZ0[ LZ B_ BZAY5Z*Z(Z#Z(Z$Z(Z$Y'Y 9Z 2Z5\\ JY=` ?{ B{ Bz @z B{ " "B{'~x/Y #~W M~W M~W M~W 7Y Y NX Y 6Z.Y IX0X JY-Y LZ-Y MZ.Z MY-Y KY-Y$~d$Y@WDY KY0X HY0X GX0X GX0Y AY@Z AY.Y " "DY@Z 8WK~KW/WJ}JW.W=a<W.W<[7W/W9[9W >X ,Y?Y LZ +XBU 6~_+~i%~U I~P HX.Y IX.X @ZDZ 7YCY KX " " (y JY \"W?W (h 5XCXAX5Z<\\@Y 9Y CZ $T ;~e =l X 5Z/Z 4Z \"\\ AZ IX6Z JZ I\\1[ 4Z 8Z3Z AmKZ" " ?d d AZ HW>X3W>V.Z4Z JZ.Z\"[ \"Z#[\"Z MZ 0Z Z'Z(Z :Z \"Z 4ZH] 0Z 2YAYKX@Y(Y<ZFZ*[ M[\"Z /Z LZ&Z:\\ K" "^ 6Y 9Z(Z GZAZ NZEW<WEZ IZL[ )Z *\\ X FX HY H{ FY.Y KZ %Y-Y K~X :Y 5Y.Y GY1Y 5Y NX 0c IY FY3Y2Y+Y1Y" " KZ-Y JY.Y Y-X ;Y $l .Y .Y1Y AY?Y HYEWFXEX =\\ .Y@Y -[ 2b GX Ga LY=s LT6W7T'Z4Z BY2Z DY=^ GY-Z =d 9Y1Y ?XAY" " 5YDZ AY1Y&Z8X9[,ZAYAZ IY9Y IY@X@Y KX.Z Y-Y 5Y 5Y.Z JZ4Z 5[ 0Z 0Z NZ-Z<Z<Z)Z(Z#\\DZD\\)Z LZ3~p BX B~o BX B~p CX" " DX 4Z?U -Z (W2W 2Z &[9X IUEX T s AXAY 4X &U>WCX;U -X EY1Y 1WEW 3Z Is 0YAX 8W6UJV IW)W" " LX7UJW CY 6Z4Z GY3Y FZ4Z GY3Y FZ4Z GY3Z'Z8Z <[ IZ !Z Z !Z >Z !Z !Z \"Z :Z#Z(Y<ZEY*[ M[/[ M[0Z LZ/Z LZ/Z LZ " "Ca CZBY4Z*Z(Z#Z(Z$Z(Z$Y'Y 9Z 2Z5\\ JY<` A| C| C{ A{ C| C|(~y/Y #~W M~W M~W M~W 7Y Y NX Y 6Y-Z JX0X JY-Y LZ-Y" " MZ.Z MY-Y KY-Y$~d$YAWCY KY0X HY0X GX0X GX0Y AY@Y @Y.Y DY@Y 7WK~KW/XK}KX.W>c=W.W=[6W/X:[:X >X ,Y@Z M[ " "+YCT 5~`,~i$~S H~P HX.Y IX.X @YCZ 7ZDY KX )y HX #X@X (TNc 6WCX@X5Y:\\AX 8Y CZ :~e" " =l !X 4Z/Z 4Z #\\ @[ KY6Z IZ I[0Z 4Z 9Z2[ @jJZ ?f %g AZ HW>X3W>V.Y2Y JZ.Z\"[ \"Z#Z!Z MZ 0Z Z'Z(Z" " :Z \"Z 4ZG] 1Z 2Y@XKX@Y(Y<ZFZ*[ MZ!Z /Z LZ&Z8[ K] 6Y 9Z(Z FZBZ NZFX<XFY I[KZ )Z +\\ NX FX HY I| FY." "Y KZ %Y-Y K~X :Y 5Y.Y GY1Y 5Y NX 0d JY FY3Y2Y+Y1Y KZ-Y JY.Y Y-X ;Y #m 0Y .Y1Y AY?Y HYFXEWFY =\\ .YAY ,[ 2d I" "X Ic LW8n JU7W7T'Y2Y BY1Z EY<\\ FY-Z @g 9Y1Y ?YBY 6ZDZ AY1Y&Z8X8Z,Y@YAZ IY9Y IY@X@Y LY-Y Y-Y 5Y 5Y.Z JY3Z 6[" " /Z 0Z [-[=Z=[)Z(Z#]EZE\\(Z LZ2~o BX B~n AX A~n BX DX 4Z?U -Z (X4X H~W <\\:W HUDX!T s AZCZ 5X %T>WBX<U" " -X EY1Y 1WEW \"s 1ZCZ 9X7UIV JX)W LW7UIW CY 6Y2Y HZ3Z GY2Y HZ3Z GY2Y HZ3Z'Z8Z <[ IZ !Z Z !Z" " >Z !Z !Z \"Z :Z#Z(Y<ZEY)Z M[/[ M[0[ MZ/Z LZ/Z M[ Dc DZCY3Z*Z(Z#Z(Z$Z(Z$Y'Y 9Z 2Z6\\ IY:` D} D} D| B| D} D})~z" "/Y #~W M~W M~W M~W 7Y Y NX Y 6Y-Z JX0X JY-Y LZ-Y MY-Z MY-Y LZ-Y$~d%ZBXCY KY0X HY0X GX0X GX0Y @YAY @Y.Y DYAZ " " 7W8X8W.W HW-W?e>W.W>[5W.W:[:W =W +ZAY LZ *YDU 5~`,~i#~Q F} GX.Y IX.X AZBY 7ZEZ KX " ")y HX 6~e 9TJ_ 7XCX?X6Y9\\BX 8Y CZ KX Nl !X 4Z/Z 4Z $\\ >Z LY5Z IZ I[0Z 5Z 8Z1Z >fHY =h " " +i @Z HW>X3W?W/Z2Z KZ.[#[ \"Z#Z!Z MZ 0Z Z'Z(Z :Z \"Z 4ZF] 2Z 2Y@XLY@Y(Y;ZGZ*[ MZ!Z /Z M[&Z7[ K\\ 6Y 9Z(Z FZ" "BZ MYFX<XGZ J[IZ *Z +[ MX FX HY Jb>Y FY.Y KZ %Y-Y K~X :Y 5Y.Y GY1Y 5Y NX 0e KY FY3Y2Y+Y1Y KZ-Y JY.Y" " Y-X ;Y !m 2Y .Y1Y AZAZ GYGXEXGY >] .ZBY -[ 1e JX Ke LU4k IU8Y8T'Y2X AY0Y EX:[ FY-Z Ah 9Y1Y >XCZ 6YBY AY1Y&" "Z8X8Z,Y@YAZ IY9Y IY@X@Y LY-Y Y-Y 5Y 5Z/Y JZ2Z 8[ .Z 0[!Z,[=Z=[)Z(Z\"]FZG]'Z M[1] 1X 1\\ @X @\\ L\\ AX DX 4" "Z?U -Z (X4X H~W ;\\;W GTDX\"U s A[D[ 6X %T>WBX<T ,X EY1Y 1WEW \"s 2[D[ 9W7UHV KX(W MX7UI" "W CY 7Z2Z IZ3Z HZ2Z IZ3Z HZ2Z IZ3Z(Z7Z ;Z IZ !Z Z !Z >Z !Z !Z \"Z :Z$[(Y;ZFY)Z M[/[ MZ/[ MZ/Z M[/Z M[ Ee EZC" "X3[*Z(Z#Z(Z$Z(Z$Y(Z 9Z 2Z8^ IY9` Fb=Y Eb=Y Eb=X Cb>Y Eb=Y Eb=Y*b=~V/Y #~W M~W M~W M~W 7Y Y NX Y 6Y-Z JX0X JY" "-Y LZ-Y MY-Z MY-Y LZ-Y CZCXBY KY0X HY0X GX0X GX0Y @YBZ @Y.Y CYBY 6W8X8W.W HW-W@g@X.W?[4W.W:[:W =W *YBZ " " MZ (XDU 5~`,~i\"~ D{ FX.Y IX.X AZBZ 7YEY IX +y GX 6~e 9TG] 8WBW>X6Y8\\DY 8Y CZ " " KX Nl !X 4Z/Z 4Z %\\ =Z LX4Z IZ I[0Z 5Z 9Z0Z <bFY ;i 1i =Z HW>X3W?W/~S KZ-Z\"Z \"Z#Z!Z MZ 0[!Z" "'Z(Z :Z \"Z 4ZE] 3Z 2Y?XMX?Y(Y;ZGZ)Z MZ!Z /[ N[&Z6[ K\\ 7Y 9Z(Z FZCZ LZGX<XGZ JZH[ +Z ,\\ MX FY IY K" "]8Y FY.Y KZ %Y-Y K~X :Y 5Y.Y GY1Y 5Y NX 0f LY FY3Y2Y+Y1Y KZ-Y JY.Y Y-X ;Y Mk 3Y .Y1Y @YAY FYGWDXGY >^ .YCZ ." "[ )_ KX L_ ES/e FU8Z9T'Z3X AY0Y FY:[ FY-Z Cj 9Y1Y >XCY 6ZBZ BY1Y&Z8X9[,Y@YAZ IY9Y IY@X@Y LY-Y Y-Y 5Y 5Z/Y J" "Z2Z 9\\ .Z /Z!Z,\\>Z>[(Z(Z!]GZH^'[ N[0\\ 1X 2\\ ?X ?[ M\\ @X DX 4Z?U -Z 'W4W G~W :]>X GTDY#U s @[D[ 7" "X %U?WAX>U ,X EY1Y 1WEW \"s 3ZC[ 9X7UHV KW(W MX7UHW CY 7~S J~S H~S I~S I~S I~S)} ;Z IZ !Z Z" " !Z >Z !Z !Z \"Z :Z$[(Y;ZFY)Z MZ-Z MZ/[ N[/[ N[/Z MZ Eg F[EX2[*Z(Z#Z(Z$Z(Z$Y(Z 9Z 2Z9^ HY7_ G]8Y F^8Y F^8X D]8" "Y E]8Y F^8Y+^8~V/Y #~W M~W M~W M~W 7Y Y NX Y 6Y-Z JX0X JY-Y LZ-Y MY-Z MY-Y LZ-Y BYDXAY KY0X HY0X GX0X GX0Y" " @ZCY ?Y.Y CYBY 5W9X8W.W HW-WAiAW,WA[3W.W9Y9W >X *ZCZ 6~d IYET 4~`,~i!| By EX.Y IX.X AYAZ 7ZFY IX " " Z 3X 6~e 9TF\\ 9WBX=W7Z7\\EX 7Y CZ KX Nl \"X 3Z/Z 4Z &\\ ;Z M~Z %Z I[0Z 6[ 9Z/" "Y 8ZCZ 8i 6~d 5i ;Z HW>X3W?W0~T KZ-Z\"Z \"Z$[!Z MZ 0[!Z'Z(Z :Z \"Z 4ZD] 4Z 2Y?XMX?Y(Y:ZHZ)Z N[!Z /[ NZ%Z6[" " J[ 7Y 9Z(Y DZDZ LZGW:WGZ K[GZ +Z -\\ LX EX IY L\\6Y FY.Y KZ %Y-Y K~W 9Y 5Y.Y GY1Y 5Y NX 0XM\\ MY " "FY3Y2Y+Y1Y KZ.Z JY.Y Y-X ;Y Ji 4Y .Y1Y @YAY FYGWDXGX >` /YCY .[ $\\ LX M\\ AR+` CT9[:U'Z3X AY0Y FY9Z FY-Z " "D` .Y1Y >YEZ 6YAZ BY1Y&Z8X9[,ZAYAZ IY9Y IY@X@Y LY.Z Y-Y 5Y 5Z/Y KZ1Z 9[ -Z /Z\"[+[>Z>[(Z(Z ^IZJ_&[ NZ.\\ 2X 3" "\\ >X >[ \\ ?X DX 4Z?U -Z 'X6X G~W 9^@X GUDY$T Ns ?[CZ 8X %U?WAY?U ,X EY1Y 1WEW \"s 4" "ZCZ 7W7UGV LX)X MW7UGW CY 8~T J~T I~S J~T I~T K~T*~ ;Z IZ !Z Z !Z >Z !Z !Z \"Z :Z$[(Y:ZGY)[ NZ-Z N[.Z N[/[ N" "[/[ NZ Fi G[FX1Z)Z(Z#Z(Z$Z(Z$Z)Z 9Z 2Z<a HY5^ I[5Y F[5Y G\\5X E\\6Y F\\6Y F[5Y+[5~V/Y #~V L~V L~W M~W 7Y Y NX" " Y 6Y-Z JX0X JY-Y LZ-Y MZ.Z MY-Y KY-Y BYDW@Y KY0X HY0X GX0X GX0Y ?YDZ ?Y.Y BYDY 4W9X9X.W HW-XC\\L[BW,WB[" "3X.W HW >X )YCY 5~d IYFU 4~`,~i!{ @x EX.Y IX.X AY@Y 7ZGZ IX Z 3X 6~e 9TD[ ;XBX=X8" "Z6\\GY 7Y CY JX Nl \"X 2Y/Z 4Z '\\ :Z M~Z %Z I[0Z 6Z 8Z/Z \"Z 5i 9~d 8i 8Z HW>X3W?W0~U LZ-Z\"[ " "#Z$[!Z MZ /Z!Z'Z(Z :Z \"Z 4ZC] 5Z 2Y?XNY?Y(Y:ZHZ)[ [!Z .Z NZ%Z5[ K[ 7Y 9Z(Y DZDY KZHX:XHY K[EZ ,Z .\\ KX EX" " IY LZ4Y FY.Y KZ %Z.Y KZ <Y 5Y.Y GY1Y 5Y NX 0XL\\ NY FY3Y2Y+Y1Y KZ.Z JY.Y Y.Y ;Y Ff 5Y .Y1Y @ZCZ FY" "HXCWHY ?b /YDY /[ ![ MX M[ @Q%W ?T9\\;U'Z3X AY0Z GX8Z FY-Z E\\ )Y1Y =XEY 6Z@Y BY1Y&Z9Y9[,ZAYAZ IY9Y IY@X@Y " "LY.Z Y-Y 5Y 4Y/Y KZ0Z ;[ ,Z /[#Z*\\?Z?\\(Z(Z N`LZL`$Z NZ-\\ 3X 4\\ JPCXCP J[\"\\ >X DX 4Z?U -Z 'X6X G~W " "8^BX FUDY%U Ns =ZCZ 9X $U@W@X?T +X EY1Y 1WEW \"s 5ZCZ 7W7UFV LW(W MX8UFW CY 8~U K~T J~U K~" "T J~U K~T*~ ;[ JZ !Z Z !Z >Z !Z !Z \"Z :Z$Z'Y9YGY)[ [-[ [.Z N[.Z NZ.[ NZ G\\L[ GZGX0Z)Z(Z#Z(Z$Z(Y#Z)Z 9Z 2~ " "GY4] J[4Y G[4Y G[4X EZ4Y FZ4Y G[4Y,[4X 1Y #Y Y Y Y 9Y Y NX Y 6Y-Z JX0X JY-Y LZ-Y MZ.Z MY-Y KY-Y BYEW?Y" " KY0X HY0X GX0X GX0Y ?YDY >Y.Y BYDY 4W9X9W-X JX,WD\\J[CW,WC[2W-X JX >X )YDZ 5~d HXFU 4~_+~i z @w DX.Y" " IX.X BZ@Y 6YGZ IY Y @~e 9TCZ ;WAX=X8Y4\\HX 6Y CY JX Mj !X 2Y/Y 3Z (\\ 9Z" " M~Z %Z I[0Z 6Z 8Z/Z \"Z 2i <~d ;i 5Z HW>X3W@W/~U LZ-[#[ #Z$Z Z MZ /Z!Z'Z(Z :Z \"Z 4ZB] 6Z 2Y>a>Y(Y9ZIZ)[ " "Z Z .Z [%Z4Z JZ 7Y 9Z)Z DZEZ JYHX:XIZ KZD[ -Z /\\ JX EX IY MZ3Y FY.Y JY %Z/Z JY <Y 5Y.Y GY1Y 5Y NX" " 0XK\\ Y FY3Y2Y+Y1Y KZ.Z JY.Y Y.Y ;Y Bc 6Y .Y1Y ?YCY DYIXCXIY @c /YEY /[ NZ MX N[ *U;^=U&Z4Y AY/Y HY7X" " EY-Y E[ 'Y1Y =YFY 6Z@Z CY1Y&Z9Y9Z+ZAYAZ IY9Y IY@X@Y LZ/Z Y-Y 5Y 4Y0Z KZ0Z <[ +Z .Z$[)\\@Z@\\'Z(Z M~Q#Z [,\\ 4" "X 5\\ JRDXDR J[$\\ KQCXDQ #Y 4Z?U -Z &X8X F~W 7_EY EUDY&U Ns <ZCZ :X $U@W?XAU +X EY1Y 1WEW " " \"s 6ZCZ 7X8UEV MX)X MW7UFW DZ 8~U L~V K~U L~V K~U K~U+~ :Z JZ !Z Z !Z >Z !Z !Z \"Z :Z%['Y9ZHY(Z [-[ Z" "-[ Z-Z [-Z [ H\\J[ HZHY1[)Z(Z#Z(Z$Z(Y#Z)Z 9Z 2} FY2\\ KZ3Y GZ3Y GY3Y FZ3Y GZ3Y GZ3Y,Z3X 1Y #Y Y Y Y 9Y Y " "NX Y 6Y-Z JX0X JY-Y KY.Z MZ.Z MY-Y KY-Y BYFX?Y KY0X HY0X GX0X GX0Y >YEY >Y.Y BYEZ 4X:X9W,W JW+WE\\H[EX,X" "E[1W,W JW =X )ZEY 4~d HYHU 2~^+~i Nx >u CX.Y IX.X BY?Z 7ZHY GX Z A~e 9TCZ <XAW<" "X8Z4\\JY 6Z DY JX 4X 1Z0Y 3Z )\\ 8Z M~Z %Z I[0Z 7Z 7Z/Z \"Y /i >~d >i 2Z GV>X3W@W0~V LZ-[\"Z " "#Z%[ Z MZ /[\"Z'Z(Z :Z \"Z 4ZA] 7Z 2Y>a>Y(Y9ZIZ(Z Z Z .[![%Z4[ KZ 7Y 9Z)Z CZFZ JZIX:XIZ L[CZ -Z /[ IX DX J" "Y MY2Y FY.Y JY %Z/Z JY <Y 5Y.Y GY1Y 5Y NX 0XJ\\ !Y FY3Y2Y+Y1Y JY.Z JY.Y Z/Y ;Y ?a 7Y .Y1Y ?YCY DYIWBX" "IY @d /YFY 0[ LY MX NZ )U<VNW=U&Z4Y AY/Y HY8Y EZ.Y F[ &Y1Y =YGZ 7Z>Y CY1Y&Z9Y9Z+ZAYAY HY9Y IY@X@Y LZ/Y N" "Y-Y 5Y 4Y0Z LZ.Y =[ *Z .[%Z(]AZA]'Z(Z L~\"[![+\\ 5X 6\\ JTEXET J[&\\ KSDXES $Y 3Y?U -Z &Y:Y F~W 5_GX DU" "CZ9QAU DZCZ ;X $VAW?YBU +X EY1Y 1WEW DZCZ 6W7UEV NX)X MX8UEW DY 8~V L~V L~W M~V K~V M~V" ",~P :Z JZ !Z Z !Z >Z !Z !Z \"Z :Z%['Y8ZIY(Z Z+Z Z-[![-[![-[![ I\\H[ I[JY0[(Y(Z#Z(Z$Z)Z#Z)Z 9Z 2| EY1\\ LY2Y " "HZ2Y HZ3Y FY2Y GY2Y GY2Y-Z2X 1Y #Y Y Y Y 9Y Y NX Y 6Z.Y IX0X JY-Y KY.Z MZ.Z MY-Y KY.Z BYGX?Z KY1Y HY0X" " GX0X GX0Y >YFZ >Y.Y AYFY 2W:X:X,W JW+XG\\F[FW+XF[1X,W JW =X (YEY 4~d GXHU 2kNRMk*tNq Mv <s BX.Y IY/X" " BY>Y 7ZIZ GY !Z A~e 9TBY <W@W;W8Z3\\KX 5Z DY JX 4X 1Z1Z 3Z *\\ 7Z M~Z %" "Z HZ0Z 7Z 7Y.Z #Z ,i A~d Aj 0Z GV=W4X@W0~W MZ-[\"[ $Z%[ Z MZ /[\"Z'Z(Z :Z \"Z 4Z@] 8Z 2Y>`=Y(Y8ZJZ([\"[ Z " ".[!Z$Z3Z KZ 7Y 9Z)Z CZGZ IZIW8WIZ M[AZ .Z 0\\ IX DX JY MY2Y FY.Y JY $Y/Z JY <Y 5Z/Y GY1Y 5Y NX 0XI" "\\ \"Y FY3Y2Y+Y1Y JY.Z JY.Y NY/Y ;Y ;] 7Y .Y1Y >YEY CYIWBXIX @f 0YGZ 0[ LZ NX NY 'U>WMW?V&Z4Y AY/Y HY8Y" " EZ.Y FZ %Y1Y <XGY 6Z>Y CY1Y&[:Z:Z+ZAYAY HY9Y IY@X@Y LZ/Y NZ.Y 5Y 4Y0Y KZ.Z ?\\ *Z -['['\\AZB]&Z(Z K|![!Z)\\ 6" "X 7\\ JVFXFV J[(\\ KUEXFU %Y 3Y?U -Z %Y<Y /Z M`KY BUC[=SAU CZCZ <X #UAW>XCU *X EY1Y 1WEW" " F[CZ 6X8UDV NW)X MX8UDW DY 8~W N~W L~W M~V L~W M~W-~P :[ KZ !Z Z !Z >Z !Z !Z \"Z :Z%['Y8ZIY([\"[+[" "\"[,Z![-[!Z,[!Z I\\F[ J[KY/Z'Z)Z#Z)Z#Z)Z#Z)Z 9Z 2{ DY0[ MY1Y HY1Y HY2Y FY2Y HZ2Y HY1Y-Y2Y 1Z $Y Y Y Z :Y Y" " NX Y 6Z.Y IX0X JZ.Y KY.Z MZ.Y LZ.Y KY.Z BYHX>Z KY1Y HY1Y GX0X GX0Y =YGY =Y.Y AYFY 2X;X:W+X LX*WH\\D[HX" "*WG[0W+X LX =X (YFZ 4~d GYIU 2jLQLj*pNRNq Lt :q AX.Y IY0Y CZ>Y 6YIZ FX !Z A~e 9T" "BZ >W?W;W8Z2\\MY 4Y DY JX 4X 1Z1Z 3Z +\\ 6Z M~Z %Z HZ0Z 8[ 7Y.Z #Z )i D~d Ci -Z GV=W4XAW/~W M" "Z-[\"[ $Z&[ NZ MZ .Z\"Z'Z(Z :Z \"Z 4Z?] 9Z 2Y=_=Y(Y8ZJZ([\"[ Z -Z\"[$Z3[ L[ 8Y 9Z)Z BZHZ IZJX8XJY LZ@[ /Z 1\\" " HX DX JY NY1Y FZ0Z JY $Y/Z JY <Y 5Z0Z GY1Y 5Y NX 0XH\\ #Y FY3Y2Y+Y1Y JY.Y IY/Z NY/Y ;Y 9\\ 8Y .Y1" "Y >YEY BXJXAWJY A[N[ 1YGY 0[ JY NX NY 'V@WLX@U$Y5[ BY/Y HX7X DZ.Y FY $Y1Y <YIZ 6Y=Z DY1Y&[:Z:Z*YAYAY HY9" "Y IY@X@Y LZ/Y NZ/Z 5Y 3Y1Y KY-Z ?[ )Z -[([%]CZC]%Z(Z Jy M[#[(\\ 7X 8\\ JXGXGX J[*\\ KWFXGW &Y 3Y?U -Z %Z>Z " "/Z K_MZ BUC]BVBU A[D[ >X #VBW=XDU *X EY1Y 1WEW G[D[ 5W8UCV X*X LW8UCW EZ 8~W N~X M" "~W N~X M~W N~X.~Q :[ KZ !Z Z !Z >Z !Z !Z \"Z :Z&[&Y7ZJY([\"[+[\"[,[\"Z+[#[+Z\"[ J\\D[ JZKX/['Z*[#[*Z#Z)Z#Z)Z" " 9Z 2z CY/Z MY1Y HY2Z HY2Y GY1Y HY1Y HY1Y-Y2Z 2Z $Z !Z !Z !Z :Y Y NX Y 6Z.Y IX0X JZ/Z KY.Z LY.Y LZ/Z KY.Z " " BYHW=Z KY1Y GX1Y GX1Y GX0Y =YHZ =Y/Z @YHY 1X;X;X*W LW)XJ\\B[IX*XI[0X*W LW <X (ZGY 3~d GYJU 1iKQKi*pN" "RMo Jr 9q AX.Y HX0Y CZ>Z 7ZJY EY !Z 1X@X &TAY ?X?W;W8Z1\\NX 3Y DY JX 5Y 0" "Y1Z 3Z ,\\ 5Z M~Z %Z HZ0Z 8Z 6Y.Z #Z &i G~d Fi )X FV=X5XAW0~Y NZ-[!Z $Z&[ NZ MZ .[#Z'Z(Z :Z \"Z 4Z>] :Z 2" "Y=_=Y(Y7ZKZ'Z#[ NZ -[#[$Z2[ M[ 8Y 9Z)Z BZHZ HYJX8XKZ M[?Z /Z 2\\ GX CX KY NY1Y FZ0Z JZ %Y/Z JZ =Y 4" "Y0Z GY1Y 5Y NX 0XG\\ $Y FY3Y2Y+Y1Y JZ/Y IZ0Y MY/Y ;Y 8[ 8Y .Y1Y >ZGZ BYKXAXKY B[LZ 0YHY 1[ IY NX Z &VB" "XKXBV$Y5[ BY/Y HX8Y CY/Z GY #Y1Y <YIY 6Z<Y DY1Y%Z:Z:Z*YAYAY HY9Y IY@X@Y LZ/Y NZ/Z 5Y 3Y2Z LZ,Z A[ (Z ,[)[%^DZD^" "%Z(Z Iw L[#['\\ 8X 9\\ JZHXHZ J[,\\ KYGXHY 'Y 3Z@U -Z $[B[ .Z NW $j @UCpBU @[D[ ?X \"UBW=XEU )X " " EY1Y 1WEW H[D[ 5W8UBV W*X LX8UCW F[ 9~Y ~X N~Y ~X N~Y ~X.~Q 9[ LZ !Z Z !Z >Z !Z !Z \"Z :Z&[&" "Y7ZJY'[#Z)Z#[+[#[+[#[+[#[ K\\B[ K[MX.['Z*Z!Z*Z#Z)Z#Z)Z 9Z 2x AY.Z NY2Z HY2Z IY1Y GY1Y HY1Y HY2Z-X1Z 2Z $Z !Z !Z" " !Z :Y Y NX Y 5Y/Z IX0X JZ/Z KZ/Y KY.Y LZ/Z KZ/Y AYIW<Y IX1Y GX1Y GX1Y GY2Z =YHY <Z0Y ?YHY 0X<X;X*X N" "X)XJ[@[KX(XK[/X*X NX <X 'YHZ 3~d FXJU 0hKQKh(nMRMo Jq 7o @X.Y HX0X BY=Z 7ZKZ DY \"Z " " 1W?X &TAY ?W>W;W8Z0e 3Y EZ JX 5X /Z2Y 2Z -\\ 4Z M~Z %Z HZ0Z 8Z 6Z/Z $Z #j J~d Ii CW>X6Y" "BX0~Y NZ-[![ %Z'\\ NZ MZ -Z#Z'Z(Z :Z \"Z 4Z=] ;Z 2Y<]<Y(Y7ZKZ'[$[ NZ -[$[#Z1Z M[ 8Y 8Z*Z BZIZ GZKX8XKZ N[>[ 0" "Z 3\\ FX CX KY NY2Z FZ0Y IZ %Y/Z JZ =Y 4Y0Z GY1Y 5Y NX 0XF\\ %Y FY3Y2Y+Y1Y JZ/Y IZ0Y MY/Y ;Y 7Z 8Y" " .Y2Z =YGY AYKW@XKY BZJZ 1YIY 1[ HY NX Y %WEYIYFW#Y5[ BY/Y HX8Y CY/Z GY #Y1Y ;XIY 6Y;Z EY1Y%Z:Z:Z*ZBYBZ " "HY9Y IY@X@Y LZ/Y MY/Z 4Y 4Y2Y KZ,Z B[ 'Z +[+[#_FZF_$Z(Z Gt JZ$[%\\ 9X :\\ J\\IXI[ I\\/\\ K[HXI[ (Y 3Z@U -Z " "%^F^ /Z X \"f >VBnCU >[D[ @X \"VCW<XGV )X EY1Y 1WEW I[D[ 5X8UBV!W)X LW8UBW FZ 8~Y!~Z" " ~Y!~Z ~Y ~Y0~R 9[ LZ !Z Z !Z >Z !Z !Z \"Z :Z'[%Y6ZKY'[$[)[$[*[$[*[%[*[$[ K\\@[ Le.[&Z*Z!Z*Z\"Z*Z#Z*[ 9Z 2v " "?Y.Z NY2Z HX1Z IY1Y GY1Y HY2Z HX1Z.Y1Z 1Y #Y Y Y Y :Y Y NX Y 5Y/Z IX0X IY/Z KZ/Y KY/Z KY/Z KZ/Y 7\\ 7ZKW" ";Y IX1Y GX1Y GY2Y GY2Z <YIY <Z0Y ?YIZ 0X<X<X)X Y(XJY>YJX(XJY/X)X Y <X 'ZIZ 3~d FYKT /gJQJg(nMRLm Hp 6" "m ?X.Y HY1X CZ<Y 6YKZ DY \"Z 1W?W %TAY @X>W;W7Y/c 2Y EY IX 5X /Z3Z 2Z .\\" " 3Z M~Z &Z FY1Z 8[ 6Z/Z $Z i L~d Li @W>Y7YBW0Z*Y NZ-[![ %Z'[ MZ MZ -[$Z'Z(Z :Z \"Z 4Z<] <Z 2Y<]<Y(Y6ZL" "Z'[%[ MZ ,[%[#Z1[ N[ 8Y 8Z+[ AZJZ GZKW6WKZ NZ<[ 1Z 3[ EX CX KY NY2Z FZ0Y IZ %Z1[ IY =Y 4Z1Z GY1Y 5Y" " NX 0XE\\ &Y FY3Y2Y+Y1Y JZ0Z IZ0Y MZ1Z ;Y 6Y 8Y .Y2Z =YGY AYKW?WKX B[J[ 1YJY 2[ GY NX Y $ZL[H[JY#Y6\\ " "BY0Y GX8X BZ0Z GY #Y1Y ;YKZ 7Z:Y EY2Z%Z:Z:Z*ZBYBZ HY9Y IY@X@Y L[1Z MY/Y 3Y 4Z3Y LZ+Z C\\ 'Z +[,[!_GZG_#Z(Z Fq H" "[%[$\\ :X ;\\ H\\JXJ\\ H\\1\\ J\\IXJ\\ (Y 3Z@U -Z &x 0Z X c <UAmDV =[CZ AX !VDW<YHU (X E" "Y1Y 1WEW JZCZ 3W8UAV\"X*X LX9UAW G[ 9Z*Y!Z+Z Y*Y!Z+Z Y*Z\"Z+Z0Z3Z 8[ MZ !Z Z !Z >Z !Z !Z \"Z :Z(\\%" "Y6ZKY&[%[)\\&[)[%[)[%[)[%[ L\\>[ Ld.[&Z*Z!Z*Z\"Z+[\"Z+Z 8Z 2s <Y-Y NX1Z IY1Z IY2Z GY2Z HY2Z HX1Z.Y1Z 1Z $Y Y " "Z !Z ;Y Y NX Y 5Y/Z IX0X IY/Y JZ0Z KZ0Z KY/Y IY0Z 7\\ 6YLX<Z IX1Y GY2Y GY2Y GY2Z <YJZ <Z0Y >YJY .X=X=Y(" "X!X'YJW<WJX&XJW/Y(X!X ;X &YIY #[ LYLU .fJQJf&lLRLm Gn 4k >X.Y HY2Y CZ<Z 7YKY BY #[ " " 3X@X %TAY @W=W;W7Z0b 1Y EY IX 5X /Z3Z 2Z /\\ 2Z )Z JZ FZ2Z 8Z 5Z/Z %Z Ki :j >W=X8ZC" "W/Z*Z Z-Z N[ &Z(\\ MZ MZ -\\%Z'Z(Z :Z \"Z 4Z;] =Z 2Y<]<Y(Y6ZLZ&[&[ MZ ,\\'[\"Z0Z NZ 7Y 8Z+Z @ZJY FZLX6XLY N[;" "Z 1Z 4\\ EX BX LY NY2Z F[2Z HZ %Y1[ IZ >Y 4Z2[ GY1Y 5Y NX 0XD\\ 'Y FY3Y2Y+Y1Y IY0Z IZ1Z MZ1Z ;Y 6Y" " 8Y .Y2Z =ZIZ @XLX?WLY C[H[ 2YKZ 3[ EX NX Y $hFh\"Z7\\ BY0Y GX9Y BZ1Z FX \"Y1Y ;YKY 6Y9Y EY2Z%Z;[:Z*ZBYB" "Y GY9Y IY@XAZ L[1Y LZ1Z 3Y 3Y3Y LZ*Z D[ &Z *[-[ aJZJa\"Z(Z Cl F\\'[\"\\ ;X <\\ F\\KXK\\ F\\3\\ H\\JXK\\ 'Y " "2ZAU -Z 'z 1Z X Na ;V@jDV :ZCZ BX UDW;XIU 'X EY2Z 1WEW KZCZ 3X9U@V\"W*X LX9VAW H[ " "8Z*Z\"Y)Y!Z*Z\"Z*Y!Z*Z\"Z*Z1Z3Z 8[ MZ !Z Z !Z >Z !Z !Z \"Z :Z(\\%Y5ZLY&[&['[&[([&[)\\'\\)[&[ L\\<[ Mc.[$Z,[!" "[,[\"Z+Z!Z+Z 8Z 2n 7Y-Y NX1Z IY2[ IY2Z GY2Z HY2Z IY2[.Y2\\ 2Z $Z !Z !Z !Z ;Y Y NX Y 5Z0Y HX0X IZ1Z IY0Z KZ0" "Y JZ1Z IZ1Z 7\\ 6YMX;Z IY3Z GY2Y GY2Y GY2Z ;YKY ;Z1Z >YJY .Y>X=X'Y#Y&XIU:UJY&YJU.X'Y#Y ;X &YJZ #Z JXLU" " -dIQId%kKRKk El 2j >X.Y HY2Y CY;Z 7ZMZ BZ #Z 3X@X %TAX @W<W;W7Z/a 0Y FY IX " " 6X -Z4Z 2Z 0\\ 2[ )Z JZ FZ2Z 8Z 5Z/Z %Z Hi @j :V=Y9ZDX/Z*Z Z-Z N\\ 'Z)\\ LZ MZ ,[%Z'Z(Z :Z \"Z" " 4Z:] >Z 2Y;[;Y(Y5ZMZ&\\([ LZ +['[\"Z0[ Z 7Y 8[,Z ?YKZ EYLX6XLY [:[ 2Z 5\\ DX BX LY NY3[ F[2Z HZ %Y1" "[ IZ >Y 3Y2[ GY1Y 5Y NX 0XC\\ (Y FY3Y2Y+Y1Y IZ2Z H[2Z LY1Z ;Y 6Z 9Y .Y2Z <YIY ?YMX?XMY CZFZ 2YKY 3[ DY X " "Y #gEf!Z7\\ BY0Y GX9Y BZ1Z FX \"Y1Y :XLZ 7Z9Z FY2Z%Z;\\<[)ZCYCZ GY9Y IZAXAZ L[1Y LZ1Z 3Y 3Y4Y KZ*Z E[ %Z )[" "/[ MdNZNd!Z(Z Ag B['[!\\ <X =\\ D\\LXL\\ D[4\\ F\\KXL\\ &Z 3ZAU -Z (| 2Z X L^ 9V?fBU 8ZCZ CX V JV " " CY2Z 1WEW LZCZ 2W9V@V#X+X KW8U@W I[ 7Z*Z#Z)Z\"Z)Y#Z)Z\"Z)Y#Z)Z2Z2Z 7[ NZ !Z Z !Z >Z !Z" " !Z \"Z :Z)\\$Y5ZLY%[(\\'\\(['\\(['['['[(\\ M\\:[ Ma-[$Z,Z NZ,Z![,Z!Z,[ 8Z 2Z #Y-Y NX2[ IY2[ IY2Z GY3[ HX2[ IY2" "[.Y2\\ 2Z $Z !Z !Z Y ;Y Y NX Y 5Z1Z HX0X IZ1Z IZ1Z JZ2Z JZ1Z IZ1Z 7\\ 6c:Z IY3Z GY3Z GY3Z GY3[ ;YKY ;[2Z =" "YLY ,Y?X>Y&Y%Y%YIS8SJY$YJS.Y&Y%Y :X &ZKY #Z IYNU ,cISIb#jKRJi Cj 1i =X.Y GY4Y BY:Y 7ZMZ AZ " " $[,P )W?X %TBY AX<W;W7[/_ /Y FY IX 6X -Z5Z 1Z 1\\ 1Z (Z K[ EY2Z 9Z 4Z0[ &[ F" "j Ei 7W=Y;[EX/Z(Z!Z.[ M[!P'Z*] LZ MZ ,\\&Z'Z(Z :Z \"Z 4Z9] ?Z 2Y;[;Y(Y4YMZ%[)\\ LZ +\\)[!Z/Z Z 7Y 7Z-[ ?Z" "LZ EZMX6XMZ Z8[ 3Z 6\\ CX BX LY NY3[ F[2Y GZ %Z3\\ HZ ?Y 3Z4\\ GY1Y 5Y NX 0XB\\ )Y FY3Y2Y+Y1Y IZ2Z " "H[2Y KZ3[ ;Y 6Z 9Y .Z4[ <YIY ?YMW>XMY DZDZ 2YLY 3[ DY X Y \"eCd NY8^ CY0Y GX:Y @Z2Z FX \"Y1Y :YMY 6Y7Y " "FY2Z%[<\\<Z(ZCYCZ GY9Y HYAXAY K\\3Z KZ2Z 3Y 3Z5Y LZ)Z F[ $Z ([1[ K~U Z(Z ;[ <\\)[ N[ <X <Z B\\MXM\\ BZ3Z D\\L" "XM\\ %Z 3ZAU -Z )~ 3Z X J] 9V>a@V 7YBY CX NV LV BZ3Z 1WEW LYBY 2W8U?V#W+X KX9U" "?W J[ 7Z(Y#Z)Z#Z(Z$Z)Z\"Y(Z$Z(Y2Z2Z 7\\\"P NZ !Z Z !Z >Z !Z !Z \"Z :Z*\\#Y4ZMY%\\)[%[)\\&[)\\'\\)\\'\\)[ M\\8" "[ N`-[#Z,Z NZ,Z Z-[![-[ 8Z 2Z #Y-Y NX2[ IY2[ IY3[ GY3[ HY3[ HX2[.Y3^ 2Z $Z !Z !Z !Z <Y Y NX Y 4Z2Z HX0X HZ2" "Z IZ2Z IZ2Z IZ2Z IZ2Z 6\\ 5a:Z HY3Z GY3Z GY3Z GY3[ ;YLY :[2Y <YLY ,Y?X?Y$Y'Y#YIQ6QIY$YIQ.Y$Y'Y 9X %YLZ " "$Z HYNU +aHSH`!hJRIg Bi /g <X.Y GY4Y CZ:Y 6YMY @[ $Z-Q )W?W $TBY AW;W<X6Z.] .Y GY" " HX 6X -Z5Z 1Z 2\\ 0Z (Z L[ DZ4Z 8Z 4[1Z %Z Bj Ki 4W=Z=\\GY.Z(Z!Z.[ M\\#Q'Z+] KZ MZ +\\'Z" "'Z(Z :Z \"Z 4Z8] @Z 2Y:Y:Y(Y4ZNZ%\\*[ KZ *\\+\\!Z/[ \"[ 7Y 7Z-Z >ZMZ DZMW4WMZ![7Z 3Z 7\\ BX AX MY NY3" "[ F\\4Z FZ &Z3\\ HZ ?Y 3Z4\\ GY1Y 5Y NX 0X@[ *Y FY3Y2Y+Y1Y HZ3Z H\\4Z KZ3[ ;Y 5Y 9Y -Y4[ ;YKY >YNX=WNY D[D[ " "3YMY 3[ CY X Y !cAb MZ9^ CZ2Z GX:Y @Z3Z EX \"Y1Y :YMY 7Z7Y FZ4[$Z<\\<Z(ZCYCY FY9Y HYAXBZ K\\3Z KZ3Z 2Y 2" "Y6Z LZ(Z H\\ $Z (\\3[ I~R MZ(Z :Z ;\\+\\ MY ;X ;X @\\NXN\\ @X1X B\\MXN\\ $Z 2ZBU -Z *~Q 4Z X I] :W9U;V " " 5XAX CX MV NV AZ3Z 1WEW LXAX 2X8s+W,Y JW8t#\\ 7Z(Z%Z'Y#Z(Z$Y'Z$Z(Z$Z(Z4Z1Z 6[#Q NZ !" "Z Z !Z >Z !Z !Z \"Z :Z+]#Y4ZMY$[*\\%\\*[%\\+\\%\\+\\%\\+\\ N\\6[ N^-\\#[.[ N[.[ [.Z NZ-Z 7Z 2Z #Y-Y NY4\\ IY3" "\\ IY3[ GY3[ HY4\\ HX3\\.Y3^ 2Z $Z !Z !Z !Z <Y Y NX Y 4Z3Z GX0X HZ3Z GZ3Z IZ3[ IZ3Z GZ3Z 6\\ 5`9Z HY4[ GY4[" " GZ5[ GZ5\\ :YMY :\\4Z ;XMZ +Y@X@Y#Z)Z\"Y(Y\"Y(Y#Z)Z 9X %ZMZ %Z F_ )^GSG^ NfIRHe @g -e ;X.Y GZ6Z CY9" "Z 7ZNY ?[ %[/R *X@X $TBY BX;X=X6[.] /Y GY HX 7X +Z7Z 0Z 3\\ 0[ (Z L[ DZ4" "Z 9[ 3Z2[ &Z >i i 2W<Z?]HZ.Y'Z!Z/\\ L\\&S'Z,] JZ MZ *\\(Z'Z(Z :Z \"Z 4Z7] AZ 2Y JY(Y3e$\\,\\ KZ )\\-" "\\ Z.Z \"[ 7Y 7[/[ =ZNZ DZNX4XNY![6[ 4Z 7[ AX AX MY NY4\\ F\\4Z F[ &Z5] H[ @Y 2Z6] GY1Y 5Y NX 0X?[ +" "Y FY3Y2Y+Y1Y HZ4Z G\\4Z JZ5\\ ;Y 6Y 8Y -Y5\\ ;YKY =XNX=WNY E[B[ 3YNY 4[ BY X Y N_=_ LZ:_ CZ2Y FX;Y >Z4" "Z EY #Y1Y 9XNZ 7Y6Z GZ4[$Z=]=['ZDYDZ FY9Y HZBXBZ K]5Z J[5[ 2Y 2Z7Y L[(Z H[ #Z '\\5[ F~ LZ(Z :Z :\\-\\ KW :X :" "V >r >V/V @s #Z 2[CU -Z +[MeL[ 5Z X G\\ :W!V 3W@W 7V!W AZ4[ 1WEW LW@W 1W7s,X-" "Y JX8t$\\ 7Z'Z%Z'Z$Z'Y%Z'Z$Z'Y%Z'Z4Z1Z 6\\&S NZ !Z Z !Z >Z !Z !Z \"Z :Z,]\"Y3ZNY$\\,\\#\\,\\$\\,\\$\\-\\$\\," "\\ N\\4[ ]-\\![/Z LZ/[ N[/[ N[/[ 7Z 2Z #Y-Y NY4\\ HY5] IY4\\ GY4\\ HY4\\ HY4\\.Z5` 2Z $Z !Z !Z !Z =Y Y NX Y " "3Z4Z GX0X H[5[ GZ4Z GZ4Z H[5[ GZ4[ 6\\ 5_9[ HZ5[ GZ5[ FY5[ FY5\\ :YNZ :\\4Z ;YNY )YAXAZ\"Z+Z!Z*Y Y*Z\"Z+Z 8" "X $YMY %[ F^ '\\FSF\\ LcGRGc >f ,c :X.Y FZ7Y BY8Y 7e >[ %[1S -Y 'X@X ;Q:TCZ CX:X=X" "5[.] /Y HY HX NZ GZ 'X +[8Z 0Z 4\\ 0[ 'Z M\\ CZ6[ 9Z 2[3[ '[ 0Y Y ?f f BX DW=\\C_J[.Z&Z\"Z0\\ " "J\\(T'Z._ JZ MZ *])Z'Z(Z :Z \"Z 4Z6] BZ 2Y JY(Y3e#\\.\\ JZ )]/\\ NZ.[ NQ'[ 6Y 6[0[ =ZNZ CYNX4XNY!Z4[ 5Z 8[ @X" " AX MY NY5] F]6Z DZ &Z5] G[ AY 2[8^ GY1Y 5Y NX 0X>[ ,Y FY3Y2Y+Y1Y H[6[ G]6Z IZ5\\ ;Y 6Y 8Y -Z6\\ ;Z" "MZ =b=b EZ@Z 3d 5[ AY X Y L[:\\ IZ;` D[4Z FX<Z >Z5[ EY #Y1Y 9c 7Z5Y GZ5\\$[>^>['[EYE[ FY9Y HZBXCZ J]5Z " "IZ5Z 1Y 1Y8Z LZ&Z J[ \"Z &\\8] E| KZ(Z :Z :]/] JU 9X 9T <p <T-T >q \"Z 1ZCU -Z ,[JaI[ 6Z X F\\ :W#V 1" "V?V 7W#W @[5[ 1WEW LV?V 1X7s,W-Y JX7t%\\ 6Z&Z&Z'Z%Z&Z&Z'Z%Z&Z&Z&Y4Y0Z 5\\(T NZ !Z Z " "!Z >Z !Z !Z \"Z :Z.^!Y3e#\\.\\!\\.\\#].\\#]/]#\\.\\ N\\2[ ]/]![0[ L[0[ M[0[ N\\1[ 6Z 2Z #Y-Y NY5] HY5] IZ6] GY" "5] HY5] HY5]-Y5a 3[ %[ \"[ \"[ \"[ >Y Y NX Y 3Z5[ GX0X GZ5Z F[6[ G[6[ GZ5Z F[5Z 5\\ 4^9Z FY6\\ FY6\\ FY6\\ " "FY6] 9c 9]6Z :d )[CXBZ Z-Z NZ-[ [-Z Z-Z 7X $YNZ %Z D] $VCSDW G`FSG` ;d +c :X.Y F[9Z CZ8Y 6d =\\ " " '\\3T -Z (W?X ;S<TDZ BW8W=W4\\1` 0Y HY HX NZ GZ 'X *Z9Z /Z 5\\ 0\\ 'Z N\\ B[8[ 8Z" " 2\\5[ '[ /Z \"[ >d c @Z EW<_Ks-Z&Z\"Z1] J^,V'Z/_ IZ MZ )]*Z'Z(Z :Z \"Z 4Z5] CZ 2Y JY(Y2d#]0\\ IZ (]1] NZ-" "Z NS*\\ 6Y 6[1[ <e Bc4c\"[3Z 5Z 9\\ @X AX MY NZ6] F^8[ D[ &Z7^ G[ AY 1[:_ GY1Y 5Y NX 0X=[ -Y FY3Y2Y" "+Y1Y G[7Z F]7[ HZ7] ;Y 6Y 7Y .Z7] :YMY <a<a EZ>Z 4c 5[ @Y X Y HS3V FZ<a D\\5Z FX<Y =[7[ DZ $Y1Y 9c 7Y4" "Z H[6\\#Z?WNV>Z%ZEYF[ EY9Y GZCXD[ J^7Z H[7[ 1Y 1Z:Z KZ&Z K[ !Z %];] Bx IZ(Z :Z 9]1] HS 8X 8R :n :R+R <o !Z " "1[DU -Z -[F\\F[ 7Z X E\\ :W&W /U>U 6W%W ?[6\\ 1WEW LU>U 0W6s-X.X HW6t&\\ 5Z&Z'Z" "%Z&Z&Z'Z%Z&Z&Z&Z&Z6Z0Z 4],V NZ !Z Z !Z >Z !Z !Z \"Z :Z0`!Y2d\"\\0]!]0\\!]0\\!]1]!]1] \\0[ ]1] N[2\\ L\\2[ L\\" "2[ L[1[ 6Z 2Z #Y.Y MZ7^ HY6^ HY6] GZ6] HZ7^ HZ7^-Y6c 3[ %[ \"[ \"[ \"[ ?Y Y NX Y 3[7[ FX0X G[7[ E[7[ FZ7[ F" "[7[ E[7[ 5\\ 4]9[ FZ8] FZ8] FZ8] FZ7] 9c 9]7[ 9b '[DXD[ N[/Z LZ/[ M[0[ N[/Z 6X $d %Z C\\ ?S 2\\ETD" "\\ 9b )a 9X.Y E[<[ BY7Z 7c ;\\ '\\5U -Z (W?W :U>TE[ CX8X?X3\\3b 1Y IY GX NZ GZ (" "X )[;[ /Z 5[ %Q-\\ &Z BQ/] AZ9\\ 9Z 0[6\\ (\\ /Z \"[ ;a ` =Z EX<nNd,Z$Y\"Z2] H^.W'Z2a HZ MZ (^,Z'Z(Z :Z \"" "Z 4Z4] DZ 2Y JY(Y2d\"]3^ IZ ']3] MZ-[ U-] 6Y 5\\4\\ ;d Bb2b#[2[ 6Z :\\ ?X @X NY MZ8^ F^8Z B[ '[9_ F[," "P 7Y 1\\<` GY1Y 5Y NX 0X<[ .Y FY3Y2Y+Y1Y G[8[ F^9[ G[9^ ;Y *Q/Z 7Y -Z9^ :YMY <a;` F[>[ 4b 6[ ?Y X Y " "FZ=b E]7Z EX=Z <[9\\ D[ %Y1Y 8a 6Y3Y H\\8]#[@WNW@[%[FYG\\ EY9Y G[DXD[ J_9[ G[9[ /Y 1Z;Z LZ%Z L\\ !Z $]=\\ >t GZ" "(Z :Z 8]3] FQ 7X 7P 8l 8P)P :m Z 0[EU -Z .[?P?[ 8Z X D[ 9W(W -T<S 5X)X >\\8] 1WEW " " LS<T 0W5s-W.X HX6t'\\ 5Z$Y'Z%Z'[%Z(Z%Z&Z%Z(Z%Z6Z0Z 4^.W NZ !Z Z !Z >Z !Z !Z \"Z :Z2a Y2d\"^3] N]3^ ]3" "] N]3] N]3] \\.[!^3] M\\4\\ J\\4\\ K\\4\\ L\\4\\ 5Z 2Z #Y.Y MZ8_ HZ8_ HZ8^ FZ8^ HZ8_ HZ8_-Z8e-Q)\\ &\\-Q G\\-Q " "G\\-Q G\\-Q 5Y Y NX Y 2[9\\ FX0X F[9[ D\\9[ E[8[ E[9[ D\\9[ 4\\ 3[9[ EZ9^ FZ9^ FZ9^ F[9^ 9b 8^9[ 8b &[2[" " L\\3\\ K[2[ K[2[ L\\3\\ 6X #c &Z B\\ ?S /UATAT 4a '_ 8X.Y E\\>\\ BY6Y 7c :] (\\7V " "-Z )X@X :W@TF[ BW7X?X3]6e 1X IY GX NZ GZ (X ([=[ .Z 6[ $S1^ &Z BS3^ @\\<\\ 8Z 0]9] FR6] .Z \"[ 8^ " " ^ ;Z DW;lMc+Z$Z#Z4_ G_2Y'Z5c GZ MZ '^/\\'Z(Z :Z \"Z 4Z3] EZ 2Y JY(Y1c!^6^ HZ '^6^ LZ,Z X1] 5Y 5]6\\ :c Ab2a" "\"Z0[ 7Z ;\\ >X @X NY MZ:` F_:[ B\\3P D[;` E\\1S 7Y 0\\>a GY1Y 5Y NX 0X;\\ 0Y FY3Y2Y+Y1Y F[:[ E_;\\ " "F[;_ ;Y *S1Y 6Z .[;_ :e ;`;` G[<[ 5a 6[ >Y X Y F[?YNY F_:[ DX?Z :[;\\ B[ &Y1Y 8a 7Z3Y H]:^#\\BXNWA[#[" "GYH\\ DY9Y F\\FXF\\ I`;[ F\\;\\ /Z 2[=Z KZ$Z N\\ Z #^A] :n DZ(Z :Z 7]5] +X Mj (k NZ 0\\FUBP ;Z /[,[ " "9Z X CZ 8X+W *R;R 4X+X =]:^ 1WEW LR;R /X5s.W.X GW5t(\\ 4Z$Z(Z%Z'Z$Z(Z$Y'Z$Z(Z$Z" "8Z/Z 3_2Y NZ !Z Z !Z >Z !Z !Z \"Z :Z5c NY1c!^6^ L^6^ M^6^ M]5] M^6^ \\,[#a7^ K\\6] I\\6\\ J]6\\ J\\6] 5Z 2Z #" "Y/Z LZ:` H[:` H[:_ FZ:` GZ:` GZ:`-[:YN\\0S(\\4Q C\\0S F\\0S F\\0S F\\0S 5Y Y NX Y 1[:[ EX0X F\\;\\ C\\;[ C[:" "[ D\\;\\ C\\;\\ 4\\ 3[:\\ DZ;_ EZ;_ EZ;_ EZ;` 8a 8_;\\ 7a %\\6\\ J\\5\\ I\\6\\ I\\6\\ J\\5\\ 5X #c 'Z " "@[ @T JT _ %] 7X.Y D^D^ BZ6Y 6b 9_ *];X -Z )X@X :ZCTH] CX7YAX1^:h 2Y JY GX NZ" " GZ (X (\\?\\ .Z 7\\ $W7_ %Z BV8` ?\\>] 9[ /];] ET9] -Z \"[ 5[ [ 8Z DX;jLb*Z$Z#Z7a E`7\\'Z9f FZ MZ &`4^" "'Z(Z :Z \"Z 4Z2] FZ 2Y JY(Y1c _:_ GZ &_9^ KZ,[![6^ 4Y 4]9] 8b @a2a#[/Z 7Z ;[ =X @X NY M[<a Fa>\\ @]7R" " D\\=a E]4U 7Y /]Bc GY1Y 5Y NX 0X:\\ 1Y FY3Y2Y+Y1Y E\\>] E`=\\ E\\=` ;Y *U5[ 6[ /\\>a 9c :_:` GZ:Z 4` 6[ >Y " "X Y E[AYMZ G`<[ CX@Z 9\\=\\ A\\3Q EY1Y 7` 7Y2Z I^<_\"[BWMXC\\#]IYI\\ CY9Y F]GXG] Ia=\\ E\\=\\ .[ 2[?Z J" "Z$Z N[ NZ \"^C^ 7g @Z(Z :Z 7_9_ +X Lh &i MZ /]HUDR ;Z .Y*Y 8Z X BZ 8Y/X (Q:Q 2X/Y " " <^<` 2WEW LQ:Q .W MV(X/X GX NW\"\\ 3Z$Z)Z#Z(Z$Z)Z#Z(Z$Z)Z#Z8Z/Z 2`7\\ NZ !Z Z !Z >Z !Z !Z \"Z :" "Z9f MY0b _:_ J_:_ K_:_ L_9_ L_9^ N[*[$c:^ J^:^ H^:^ I^:] H]9] 4Z 2Z #YIP7[ L[<a G[<a G[=a F[<a G[<a G[<a,[=ZL\\" "4V'\\7S B\\4V E]5V E]5V E]5V 5Y Y NX Y 1\\=\\ DX0X E\\=\\ A\\=\\ C]>] C\\=\\ A\\=\\ 3\\ 2\\=\\ C[=` E[=` E[=" "` E[=a 8a 8`=\\ 6` #]:] H]9] G]:] G]:] H]9] 4W !a 'Z ?Z ?U KT N] $] 7X.Y Cv AZ6Z 7a 7a " " -_?Z -Z )W?X :^GTK_ CX5XAX0_>k 3Y JX FX NZ GZ )Y ']C] ?} I~S IZ=b %Z BZ>a =]B^ 8Z ._?^ DX" "@_ ,Z \"[ 3Y X 5Z CW:gJ`)Z\"Z$~T Cb=_'~W E~S FZ %b:a'Z(Z :Z \"Z 4Z1] G~Q)Y JY(Y0b N`>` FZ %a?` JZ+Z!^<a 4Y " "3_>_ 8b @a2a$[.[ 8Z <~` AX ?X Y L\\@c Fb@] ?^<U C]Ac D^9X 7Y /aI[NY GY1Y 5Y NX 0X9\\ 2Y FY3Y2Y+Y1Y E]" "@] Db@\\ C]Ab ;Y *X9\\ 5] 1\\Ac 9c :_:_ GZ9[ 5` 7[ =Y X Y E]DZM[ Hb@] BXB[ 8]A^ @]8T EY1Y 7_ 7Z1Y I`@" "b#]EXLXE\\!]JYK^ CY9Y E_JXJ_ HcA] C]A] ,] 4[B\\ K~c!~T FZ 3oDo A[ :Z(Z :Z 6a?a *X Kf $g LZ .^JUGU H~U" " JW(W 7Z X AY 7Z3Y &P9P 1Y3Y <~d 3`@b 2WEW LP9P .X MV(W/X GX MW#\\ 3Z\"Z*Z#Z)Z\"Z*" "Z#Z)[#Z*Z#Z9Z.~T+b=_ N~T J~T I~S I~S 7Z !Z !Z \"Z :~V KY0b N`>` H`>` I`>` Ja?a Ja?` LY(Y$f?` H_>_ F_>_ G_>_ H_>" "_ 3Z 2Z #YIS;[ K\\?c G\\?c G\\?b E\\@c F\\@c G\\?c,\\?[L^9Y'^<V B_:Y E_:Y E_:Y D^:Y 5Y Y NX Y 0]@] DX0X D]A]" " @]@] A]@] A]A^ A]@] 2\\ 2]@] B]Ab E]Ab D\\Ab D\\Ac 7_ 7b@\\ 5` \"_@_ F_?_ E_@_ E_@_ F_?_ 3W !a 'Z ?Z " " ?U KT M\\ #[ 6X.Y Bu AY5Z 7a 6f 2aE] -Z )W?W 9~ BW4YCY/bFp 3X KY FX NZ GZ " ")X %^G^ >} I~S I~ $Z B| ;^F_ 7Z -aEa Dv +Z \"[ 0V U 2Z CX9dI^'Z\"Z$~S AfGd'~U C~S FZ $gGg&Z(Z :Z \"Z 4Z0] H" "~Q)Y JY(Y0b McGd EZ $dGc IZ+[\"cEd 3Y 3cGc 7a ?`1a$Z,[ 9Z =~a AX ?X Y L^DZNY FYNZF_ =`CY B^EZNY CaB] 7" "Y .qMY GY1Y 5Y NX 0X8\\ 3Y FY3Y2Y+Y1Y D_F_ CYNYE_ B^EZNX ;Y *]A^ 4k >^G[NY 8a 9_9^ H[8[ 5^ 6~P 2Y X Y " " D^H[La NfH` AYD[ 6^E_ ?`?X EY1Y 7_ 7Y0Y IcFk(]HZLZI^ `Nk BY9Z E~Q GYNZE^ B_E_ ,e ;]G] J~c!~T FZ 3oDo @Z :Z(Z :" "Z 5dGd )X Jd \"e KZ -`MUKY H~U IU&U 6Z X AY 5Z7Z LZ7Z ;~d 3cFk 8WEW " " BW LV)X0X FW LW$\\ 2Z\"Z+[#Z)Z\"Z*Z\"Z*Z\"Z*Z\"Z:Z.~T*fGd N~T J~T I~S I~S 7Z !Z !Z \"Z :~U JY/a MdGc FcGd GcGd" " HdGd HdGc JW&W$kGc FbFb DbFb FcFb FcGc 3Z 2Z #YIWB] I^DZNY F]D[NY F]D[NX E^DZNY F^DZNY F^E[NY+]D]J`@]&`BY AaA]" " DaA] DaA] DaA] 5Y Y NX Y /_F_ CX0X D_E_ ?_F_ ?_F_ @_E_ ?_F_ 7aF_ @^FZMX D^FZMX D_GZMX D_G[NY 7_ 7YNYE_ 4^" " dLd CdMd BdLd CdLd DeMd 2X !` %X =Y ?U LV MZ !Y 5X.Y As AZ4Y 6` 5~] )x -Z " "*X@X 9} BX3YFZ-{L] 4Y LY FX NZ GZ )X $t >} I~S I} #Z B{ :v 7[ ,{ Cu *Z \"[ -S S 0Z BW8aG[%[\"Z$~R" " ?~S'~T B~S FZ #~V%Z(Z :Z \"Z 4Z/] I~Q)Y JY(Y/a L~ DZ #~ HZ*Z\"~R 2Y 2} 5` ?`0_$[+Z 9Z =~a AX ?X Y KsN" "Y FYNr ;u AqMY B{ 7Y -oLY GY1Y 5Y NX 0X7\\ 4Y FY3Y2Y+Y1Y Cv BYNr ArMX ;Y *y 2j >qMY 8a 8^9^ I[6Z 5^ 6~P 2Y X " " Y CpK` N} ?YF[ 5w =x EY1Y 6] 7Z0Z J~Y(nJm M{ AY9\\ F~ FYMq @w *d ;r J~d!~T FZ 3oDo @Z :Z(Z :Z 4~ 'X " " Ib c JZ ,u H~U HS$S 5Z X AY 4\\>\\ I]>\\ :~d 3~Y 8WEW CW KV)W0X FX LW" "$[ 2[\"Z+Z!Z*Z\"Z+Z!Z*Z!Z,Z!Z:Z.~T)~S N~T J~T I~S I~S 7Z !Z !Z \"Z :~T IY/a L~ D~ E~ F~ E~ HU$U$~X D| B| D} D} " "2Z 2Z #YIr HrMY FsMY FsMX DsNY ErMY FsMY+uH|%v @| C| C| C| 5Y Y NX Y .v BX0X Cw =w >v >w =w 8{ ?qMX CqMX C" "qMX CqMY 6] 6YNr 3^ My Ay @y @z Ay 1X _ $V <X ?V LV LX NW 4X.Y @p ?Z4Z 7_ 2~[ " " (v ,Z *X@X 9| AW1[K[+yJ] 5Y LX EX NZ GZ )X #r =} I~S I| \"Z Bz 8t 6Z *y Bt )Z \"[ *P P -Z BX" "6[DX\"Z Z%~Q <~P&~R @~S FZ \"~T$Z(Z :Z \"Z 4Z.] J~Q)Y JY(Y/a K| CZ !{ GZ*[#~Q 1Y 1{ 4_ =_0_%[*[ :Z =~a AX >X !" "Y JqMY FYMp 9t ApLY Az 7Y ,mKY GY1Y 5Y NX 0X6\\ 5Y FY3Y2Y+Y1Y Bt AYMp ?pLX ;Y *x 1j =oLY 8a 8]8^ IZ4Z 6" "] 5~P 2Y X Y CoI_ N} ?[K] 3u ;w EY1Y 6] 7Y.Y JvM_'mJm Ly @Y9b K| EYLp ?u (c :p I~e\"~T FZ 3oDo @Z :Z(Z" " :Z 2{ &X H` Ma IZ +t H~U GQ\"Q 4Z X AY 2aLb FaKa 8~d 3YNlN_ 8WEW " "DX KV*W0o-W KW%[ 1Z Z,Z!Z+Z Z,Z!Z+Z Z,Z!Z;Z-~T'~P M~T J~T I~S I~S 7Z !Z !Z \"Z :~R GY.` K| B| C{ B{ B{ FS\"S$YM" "{ Bz @z B{ B{ 1Z 2Z #YIq GqLY EqLY EqLX CqMY ErMY EqLY*sF{$u ?{ B{ B{ B{ 5Y Y NX Y -t AX0X Bu ;u <t <u ;u " "8{ >pLX CpLX CpLX BoLY 6] 6YMp 1] Lv >w =v =v >w 0X _ #T ;X ?W MV LW LV 4X.Y ?n >Y3Z 7_ 1~Z " " 't +Z *W?X 8y @X1j)vG] 5X MY EX NZ GZ *X !p <} I~S Iz Z By 6r 5Z )w As (Z \"[ " " 5Z AX HZ Z%~ 9|$~P >~S FZ ~P\"Z(Z :Z \"Z 4Z-] K~Q)Y JY(Y.` Jy AZ x EZ)Z#~P 0Y /x 3_ =_0_%Z([ ;Z =~a AX " ">X !Y JpLY FYLn 7s @nKY @y 7Y +kJY GY1Y 5Y NX 0X5\\ 6Y FY3Y2Y+Y1Y Ar @YLn =nKX ;Y *w /i <mKY 7_ 7]8] IZ" "3[ 6\\ 5~P 2Y X Y BmH_ N{ <k 0r 9v EY1Y 6] 8Z.Z KYNkM_&kHk Jw ?Y8a Jy CYKn =s &b 9n H~e\"~T FZ 3oDo @Z" " :Z(Z :Z 1y %X G^ K_ HZ *s H~U *Z X AY 1t Bs 6~d 3YNkM_ 8WEW DW " "JV+X0o.X KW%Z 0Z Z-Z NZ,Z Z-[ Z,Z Z-[ Z<Z-~T&| K~T J~T I~S I~S 7Z !Z !Z \"Z :~P EY.` Iy @y @y @y @y DQ Q$YKy @x" " >x ?x @y 0Z 2Z #YIp EoKY DoKY DoKX BoLY DpLY DoKY)qCy#t =y @y @y @y 5Y Y NX Y ,r @X0X As 9s :r :s 9s 7z <" "nKX BnKX BnKX BnKY 6] 6YLn 0\\ Jt ;s :t ;t ;s .X N] !R 9V >W NX LU KU 3X.Y >l =Y2Y 7_ /~X " " %p )Z *W?W 4u @X/i(tE] 6Y NX DX NZ GZ *X m :} I~S Iy NZ Bw 2o 5Z 'u @r 'Z \"Z " " 4Z AY J[ Z%} 6x\"} <~S FZ N| Z(Z :Z \"Z 4Z,] L~Q)Y JY(Y.` Hv @Z Mu DZ)[$~ /Y .u 0^ =^/_&['Z ;Z =~a AX >X" " !Y InKY FYKl 5r ?lJY >w 7Y )hIY GY1Y 5Y NX 0X4\\ 7Y FY3Y2Y+Y1Y @p ?YKl ;lJX ;Y *v -h ;kJY 7_ 7]7\\ J[2" "[ 7\\ 5~P 2Y X Y AkE] Nz :i .p 7u EY1Y 5[ 7Y,Y KYMiL_%iGj Hu >Y8a Hv BYJl :p $a 7k H~f\"~T FZ 3oDo @Z " ":Z(Z :Z /u #X F\\ I] GZ )r H~U *Z X AY /p >o 4~d 3YMiK^ 8WEW EX " "JV+W/o/X JW&Z 0[ Z-Z NZ-[ [.Z NZ,Z NZ.Z NZ=Z,~T$x I~T J~T I~S I~S 7Z !Z !Z \"Z :| BY-_ Hv <v =v =u =v BXHu =v" " <v =u <u .Z 2Z #YIo CmJY CmJY CmJX BnKY CmJY CmJY(oAx!r <x ?x ?x ?x 5Y Y NX Y +p ?X0X ?p 7p 7p 7p 7p 6WNp" " 9lJX AlJX AlJX AlJY 5[ 5YKl /\\ Hp 8q 7p 7p 8q -X N] NP 9V ?Y X KS IS 2X.Y <h <Z2Y 6^ -~V " " $n (Z +X@X 1o =W-f$pB] 6X NX DX Z FZ *X Nk 9} I~S Iw LZ Bv 0m 4Z %q >p %Z \"Z " " 4Z @X JZ MZ&{ 3u z 9~S FZ Lx MZ(Z :Z \"Z 4Z+] M~Q)Y JY(Y-_ Fr >Z Lr BZ(Z!y -Y -s /] <^.]&[&[ <Z =~a AX " " =X \"Y GjIY FYJj 2p =iIY =u 6Y 'dGY GY1Y 5Y NX 0X3\\ 8Y FY3Y2Y+Y1Y >m >YJj 8iIX ;Y *u *f :iIY 7_ 6\\7" "\\ K[0Z 6Z 4~P 2Y X Y ?hC\\ NYMm 8f +m 3s EY1Y 5[ 8Z,Y KYLgJ^$gEh Fs =Y8a Fr @YIi 7m !` 6i G~g#~T FZ 3o" "Do @Z :Z(Z :Z .s \"X EZ G[ FZ 'p H~U *Z X AY ,k :k 2~d 3YLgJ^ 8WEW " " EW IV,X/o/W IW&Z 0Z MZ/[ NZ-Z MZ.Z N[.Z MZ.Z MZ>Z,~T\"t G~T J~T I~S I~S 7Z !Z !Z \"Z :y ?Y-_ Fr 8r 9r :s :r " " AXEr :r 8r :s :s -Z 2Z #YIn AkIY BkIY BkIX @jIY BkIY BkIY'l=t Mq :t ;t ;t ;t 3Y Y NX Y *m =X0X >m 3m 5n 5m" " 3m 6XLm 7iHX @iHX @jIX @jIY 5[ 5YJj -Z El 3k 2l 3l 4l *X N\\ 5U ?Y Y KR HQ 1X.Y 9b 9Y1Z 7" "] )~S \"j &Z +X@X -h ;X+c!l?\\ 6X Y DX Z FZ +X Kh 8} I~S Fr JZ As ,i 3[ $n ;m " "#Z \"Y 3Z ?X KZ MZ&x -p Mu 4~S FZ Js JZ(Z :Z \"Z 4Z*] N~Q)Y JY(Y-_ Dn <Z Jn @Z([ Nt +Y +o ,\\ ;].]&Z$" "[ =Z =~a AX =X \"Y FhHY FYHf .m ;gHY ;p 3Y %`EY GY1Y 5Y NX 0X2\\ 9Y FY3Y2Y+Y1Y =j <YHf 5gHX ;Y (q &d 9" "fGY 6] 5[6\\ KZ.Z 7Z 4~P 2Y X Y >gB[ NYLj 5d (j 0q EY1Y 5Z 7Y+Z LYKdG]\"dBd Bo ;Y7` Dn >YHg 4i L^ 4e " "E~g#~T FZ 3oDo @Z :Z(Z :Z ,n NX DX EY EZ %m G~U *Z X BZ )e 4e /~d 3YKeH] 8" "WEW FW HV,W.o0X IW'Z /Z MZ/Z LZ.Z MZ/[ MZ.Z MZ/[ MZ>Y+~T p E~T J~T I~S I~S 7Z !Z !Z \"Z :u ;Y,^ Dn 4" "n 5n 6o 6n @XBm 5n 4n 6o 6o +Z 2Z #YIl =gGY AhGY AhGX ?hHY @hHY @gGY%i:o Hm 7p 6o 6p 7p 1Y Y NX Y (i ;X0X " "<i 0j 1j 1j 1j 5XIi 3fGX >fGX >fGX >fGY 4Y 4YHf +Z Bg /g .g -g /g (X M[ 5T ?Z !Z JP 'X.Y 5" "[ 6Y0Y 7] &~P Ne $Z +W?X '] 6W)a Mh<\\ 7Y !X CX Y EZ +X Id 6} I~S Cm HZ =l 'e " "1Z i 6h !Z #Z 3Z ?Y M[ M['s &k Jo .~S FZ Gm GZ(Z :Z \"Z 4Z)] ~Q)Y JY(Y,^ Bi 9Z Gl AZ'Z Jm (Y (i )\\ " ";].]'[#Z =Z =~a AX =X \"Y DdFY FYFb *h 6cFY 8j 0Y \"YAY GY1Y 5Y NX 0X1\\ :Y FY3Y2Y+Y1Y ;f :YFb 1cFX ;Y" " $k ` 7cFY 6] 5[5Z KZ-[ 8Y 3~P 2Y X Y ;b=X NYJe 0` $e +l BY1Y 4Y 7Y*Y LYIaE[ b@a >k 9Y6_ Ah ;YFc 0e " "FZ 2a D~i$~T FZ 3oDo @Z :Z(Z :Z )i LX CV CW DZ #h D~U *Z X -R9Z #[ *[ *~d 3" "YIaE\\ 8WEW GX HV-W-o0W HW'Z 0Z L[0Z LZ/[ LZ0Z LZ/[ LZ0Z LZ?Z+~T Lj B~T J~T I~S I~S 7Z !Z !Z \"Z :o " "5Y,^ Ai /h 0i 0i 0i >W?i 1j 0j 1j 1i (Z 2Z #YGh 9cEY ?dEY ?dEX =dFY >dFY >cEY#d5j Ch 1j 1j 1j 1j -Y Y NX Y" " &e 9X0X :e ,f -f -e ,f 4XFe 0cEX <bEX <bEX <bEY 4Y 4YFb )Z ?` (a '` '` (a %X 'T " " L{ K_ 0T 4X&[ Ga AX \"Y :Y EX G_ Ie #e !_ c /a EY " " EY Hc ?e FZ +b Ni )d Nc (X =Y #Y A^ J^ %a /] N" "c ;Y NX *` 7YD^ ,]CX 1c ^ /Y DY X Y 8] 1YF] *\\ N` %c DY 4Y *YG\\A" "X J\\;] 9e A^ =` 7YC] *_ G[ >a NU CZ N` 9X -T<[ " " LYG]BX 5WEW %U HW NX MX GZ (d +b (b )b )a )b 9V;a " ")c *c *c *c =a 4_ &^ %^ $^ &_ &_ :_/c <b +c *c *c *c 3_ K_ &` '` '_ &` 1WB_ *] $] $^ %^ NZ " "4YD^ 'Y 6Q HQ GQ FQ HQ LX &S DQ )T 4W Q :Q" " 9Y #X :Y EX ?Q 8R ?R @Q @R MQ =Y DY @R -Q <Z " " #R >RM] !R <R X <X #Y ;Q <Q GR !Q @Q 2Y MX #R 0Y=Q Q=X 'Q " " @Q *Z DY X Y ;Y <P AQ CQ ;Y 4Y *YAQ8P @Q0Q -Y 8X 7Y 3Y=Q LQ " " JQ 4Z IU 3X -W@[ KYAQ8P 1WEW $U IV MW LW FZ " " V KQ GR HQ GQ GQ 0T2Q HR GR HR HQ ,Q %Q GP GQ FQ GQ " "GP *P NQ ,V MQ GR HR HR #Q =Q FQ HR HQ FQ *V:Q LQ GQ GQ GQ GY 3Y=Q !Y " " 9X MT +X #X :Y EX " " 5X BZ 7Y 7] 8X <X #Y " " HY MX 0Y 'X MY CY X Y ;Y 8Y 4Y *Y 1Y E" "X 3Y CZ IU 3X -\\I_ KY 8WEW $V" " %Z NU 0R #V " " )T <Z 3Y =Y 8X " " MT +X $X 9X DX 6Y AZ NR " " =Z 6\\ 8X <X #Y HY MX 0Y '" "X NZ CY X X :Y 8Y 4Y *Y 1Y EX 3Y " " CZ IU 3X -q JY 8WEW #V &Z NV " " 0V (R " " <Y 2Y =Y 8X MT *X " "%X 9X EY 6X @[!T >Z 5\\ " " 9X ;X $Y HY NY 0Y 'X NY BY X !Y " ":Y 8Y 4Y *Y 1Y EX 3Y CZ IU 3X -p " " IY 8WEW #V &Z MV " " 0U 'P ;Y 2Y >Z 8X " " MT *X &X 9X DX " " 5X ?\\%W ?Z 4\\ :X ;X $Y " " IZ NY 0Y 'X NY BZ !X !Y :Y 8Y 4Y *Y 1Y EX 3Y " " CZ IU 3X -o HY 8WEW \"V " " 'Z LU 0V " " CZ 2Y >Y 7X " " MT )X 'X 9X DX 5W <\\(X ?" "Z 3\\ ;Y <X $Y IY MY 0Y 'X " " Z AY !X !Y :Y 8Y 4Y *Y 1Y EX 3Y CZ I" "U 3X -n GY 8WEW \"V '[3Q <V " " 0V DY 1Y " "?Z 7X MT )X (X 8W " " CX 6X ;],[ AZ 1\\ <e" " GX 2f JZ MY 0Y 'X Y @Z \"X \"Z :Y 8" "Y 4Y *Y 1Y EX 3Y CZ IU 3X ,k " " EY 8WEW !V 'Z4R <V " " 0V EZ 1Y ?Y ARGX " " MT (X )X 8W DX 5W " " 9^1^ AZ 0\\ =e GX 2f KZ LY" " 0Y 'X !Z @[ #X #Z 9Y 8Y 4Y *Y 1Y EX 3Y " " CZ IU 3X )f CY 8WEW !V '[7T " " ;V 1V " " EY 0Y ?Y FWGW " " LT 'W *X 8W CX 5W 8`7` A[ " " /\\ >e GX 2f KZ LY 0Y 'X !Y >" "\\ %X &] 9Y 8Y 4Y *Y 1Y EX 3Y CZ IU 3" "X $^ @Y 8WEW !V '\\:V ;V " " 1W GZ 0Y @Z " " FWHX LT 'X +W 7W " " V 5b?c A[ -\\ ?e !f " " <P2\\ MY /Y 'X \"Z >f /X 0g 9Y 8Y 4Y *Y " " 1Y EX 3Y CZ IU 3X 5Y " " NV &\\=X ;V " "1W GY /Y AZ EWHX " " LT &W ,X 7V V 3~T " " A] ,\\ @e !f <R5\\ LY /Y " "'X #Z =f /X 0f 8Y 8Y 4Y *Y 1Y EX 3Y " " CZ IU 3X 5Y NW '^B[ <W " " 1W " " HZ /Y AZ DWIX LT &X -" "W 6U NV 1~P B_ *\\ " " Ae !f <U:] LZ /Y 'X #Z <e /X 0e 7Y " " 8Y 4Y *Y 1Y EX 3Y CZ IU 3X " " 5Y X &aJ_ <W " " 2X IZ .Y BZ CWJY " " LT %X /X " " 7| Hf )\\ Be !f <X?_ N[ " " .Y 'X %[ :d /X 0e 7Y 8Y 4Y *Y 1Y EX 3Y " " CZ IU 3X 5Y -PDX %v " " JQDX ?QEY " " J[ .Y D\\ CXLY " " KT 7x Fe " " -_Me %b .Y 'X /e 9c /X 0c " "5Y 8Y 4Y *Y 1Y EX 3Y CZ IU 3X " " 5Y -d $u Je " " ?d $d -Y Ne Ad " " KT " " 5s Cd ,v %b -" "Y 'X 0e 6a /X 0b 4Y 8Y 4Y *Y 1Y EX 3Y " " CZ IU 3X 5Y -d #t Jd " " >d " " %e -Y Nd @c " " (m @c " " +u $b -Y 'X 0d 2^ /X 0_ 1Y 8Y 4Y *Y " " 1Y EX 3Y CZ IT 2X 5Y " "-c !q Hd >c " " $d ,Y Nd ?b " " %g =" "b *t #a ,Y 'X 0d " " ,X /X 0Y +Y 8Y 4Y *Y 1Y EX 3Y CZ '" "X 5Y -c Nm Fc " " =c $c +Y Nc " " >a " " M\\ 8a \"~Y 1" "r !` +Y 'X 0c 1X 1Y 8Y 4Y *Y 1Y EX 3Y " " CZ &W 5Y -b Lj " " Db <b " " #b *Y Nb <_ " " (_ " " ~Y 1q _ *Y 'X 0b 0X 1Y " " 8Y 4Y *Y 1Y EX 3Y CZ " " 3Y -` He A` " " :` !a )Y Na :] " " " " '] M~Y .l M] (Y 'X " " 0` .X 1Y 8Y 4Y *Y 1Y EX 3Y " " KY *Z B^ 9Z " " 5Z M` (Y N` " " 8Z " " %X H~Y " " *d I[ &Y 'X 0^ ,X 1Y 8Y 4Y *Y 1Y EX 3Y" " KY " " " " H^ &Y N] 3V " " " " B~Y #X CU !X &X /Y (X 1" "Y 7X 4X )X 0Y EX 2X " " KY " " HZ \"X MY " " " " J~Y " " 9X " " " " " " " " 3~Y " " 9X " " " " " " " " 3~Y " " 9X " " " " " " '" }; // Define a 40x38 'danger' color logo (used by cimg::dialog()). static const unsigned char logo40x38[4576] = { 177,200,200,200,3,123,123,0,36,200,200,200,1,123,123,0,2,255,255,0,1,189,189,189,1,0,0,0,34,200,200,200, 1,123,123,0,4,255,255,0,1,189,189,189,1,0,0,0,1,123,123,123,32,200,200,200,1,123,123,0,5,255,255,0,1,0,0, 0,2,123,123,123,30,200,200,200,1,123,123,0,6,255,255,0,1,189,189,189,1,0,0,0,2,123,123,123,29,200,200,200, 1,123,123,0,7,255,255,0,1,0,0,0,2,123,123,123,28,200,200,200,1,123,123,0,8,255,255,0,1,189,189,189,1,0,0,0, 2,123,123,123,27,200,200,200,1,123,123,0,9,255,255,0,1,0,0,0,2,123,123,123,26,200,200,200,1,123,123,0,10,255, 255,0,1,189,189,189,1,0,0,0,2,123,123,123,25,200,200,200,1,123,123,0,3,255,255,0,1,189,189,189,3,0,0,0,1,189, 189,189,3,255,255,0,1,0,0,0,2,123,123,123,24,200,200,200,1,123,123,0,4,255,255,0,5,0,0,0,3,255,255,0,1,189, 189,189,1,0,0,0,2,123,123,123,23,200,200,200,1,123,123,0,4,255,255,0,5,0,0,0,4,255,255,0,1,0,0,0,2,123,123,123, 22,200,200,200,1,123,123,0,5,255,255,0,5,0,0,0,4,255,255,0,1,189,189,189,1,0,0,0,2,123,123,123,21,200,200,200, 1,123,123,0,5,255,255,0,5,0,0,0,5,255,255,0,1,0,0,0,2,123,123,123,20,200,200,200,1,123,123,0,6,255,255,0,5,0,0, 0,5,255,255,0,1,189,189,189,1,0,0,0,2,123,123,123,19,200,200,200,1,123,123,0,6,255,255,0,1,123,123,0,3,0,0,0,1, 123,123,0,6,255,255,0,1,0,0,0,2,123,123,123,18,200,200,200,1,123,123,0,7,255,255,0,1,189,189,189,3,0,0,0,1,189, 189,189,6,255,255,0,1,189,189,189,1,0,0,0,2,123,123,123,17,200,200,200,1,123,123,0,8,255,255,0,3,0,0,0,8,255,255, 0,1,0,0,0,2,123,123,123,16,200,200,200,1,123,123,0,9,255,255,0,1,123,123,0,1,0,0,0,1,123,123,0,8,255,255,0,1,189, 189,189,1,0,0,0,2,123,123,123,15,200,200,200,1,123,123,0,9,255,255,0,1,189,189,189,1,0,0,0,1,189,189,189,9,255, 255,0,1,0,0,0,2,123,123,123,14,200,200,200,1,123,123,0,11,255,255,0,1,0,0,0,10,255,255,0,1,189,189,189,1,0,0,0,2, 123,123,123,13,200,200,200,1,123,123,0,23,255,255,0,1,0,0,0,2,123,123,123,12,200,200,200,1,123,123,0,11,255,255,0, 1,189,189,189,2,0,0,0,1,189,189,189,9,255,255,0,1,189,189,189,1,0,0,0,2,123,123,123,11,200,200,200,1,123,123,0,11, 255,255,0,4,0,0,0,10,255,255,0,1,0,0,0,2,123,123,123,10,200,200,200,1,123,123,0,12,255,255,0,4,0,0,0,10,255,255,0, 1,189,189,189,1,0,0,0,2,123,123,123,9,200,200,200,1,123,123,0,12,255,255,0,1,189,189,189,2,0,0,0,1,189,189,189,11, 255,255,0,1,0,0,0,2,123,123,123,9,200,200,200,1,123,123,0,27,255,255,0,1,0,0,0,3,123,123,123,8,200,200,200,1,123, 123,0,26,255,255,0,1,189,189,189,1,0,0,0,3,123,123,123,9,200,200,200,1,123,123,0,24,255,255,0,1,189,189,189,1,0,0, 0,4,123,123,123,10,200,200,200,1,123,123,0,24,0,0,0,5,123,123,123,12,200,200,200,27,123,123,123,14,200,200,200,25, 123,123,123,86,200,200,200,91,49,124,118,124,71,32,124,95,49,56,114,52,82,121,0 }; //! Get/set default output stream for the \CImg library messages. /** \param file Desired output stream. Set to \c 0 to get the currently used output stream only. \return Currently used output stream. **/ inline std::FILE* output(std::FILE *file) { cimg::mutex(1); static std::FILE *res = cimg::_stderr(); if (file) res = file; cimg::mutex(1,0); return res; } // Return number of available CPU cores. inline unsigned int nb_cpus() { unsigned int res = 1; #if cimg_OS==2 SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); res = (unsigned int)sysinfo.dwNumberOfProcessors; #elif cimg_OS == 1 res = (unsigned int)sysconf(_SC_NPROCESSORS_ONLN); #endif return res?res:1U; } // Lock/unlock mutex for CImg multi-thread programming. inline int mutex(const unsigned int n, const int lock_mode) { switch (lock_mode) { case 0 : cimg::Mutex_attr().unlock(n); return 0; case 1 : cimg::Mutex_attr().lock(n); return 0; default : return cimg::Mutex_attr().trylock(n); } } //! Display a warning message on the default output stream. /** \param format C-string containing the format of the message, as with <tt>std::printf()</tt>. \note If configuration macro \c cimg_strict_warnings is set, this function throws a \c CImgWarningException instead. \warning As the first argument is a format string, it is highly recommended to write \code cimg::warn("%s",warning_message); \endcode instead of \code cimg::warn(warning_message); \endcode if \c warning_message can be arbitrary, to prevent nasty memory access. **/ inline void warn(const char *const format, ...) { if (cimg::exception_mode()>=1) { char *const message = new char[16384]; std::va_list ap; va_start(ap,format); cimg_vsnprintf(message,16384,format,ap); va_end(ap); #ifdef cimg_strict_warnings throw CImgWarningException(message); #else std::fprintf(cimg::output(),"\n%s[CImg] *** Warning ***%s%s\n",cimg::t_red,cimg::t_normal,message); #endif delete[] message; } } // Execute an external system command. /** \param command C-string containing the command line to execute. \param module_name Module name. \return Status value of the executed command, whose meaning is OS-dependent. \note This function is similar to <tt>std::system()</tt> but it does not open an extra console windows on Windows-based systems. **/ inline int system(const char *const command, const char *const module_name=0, const bool is_verbose=false) { cimg::unused(module_name); #ifdef cimg_no_system_calls return -1; #else if (is_verbose) return std::system(command); #if cimg_OS==1 const unsigned int l = (unsigned int)std::strlen(command); if (l) { char *const ncommand = new char[l + 24]; std::memcpy(ncommand,command,l); std::strcpy(ncommand + l," >/dev/null 2>&1"); // Make command silent const int out_val = std::system(ncommand); delete[] ncommand; return out_val; } else return -1; #elif cimg_OS==2 PROCESS_INFORMATION pi; STARTUPINFO si; std::memset(&pi,0,sizeof(PROCESS_INFORMATION)); std::memset(&si,0,sizeof(STARTUPINFO)); GetStartupInfo(&si); si.cb = sizeof(si); si.wShowWindow = SW_HIDE; si.dwFlags |= SW_HIDE | STARTF_USESHOWWINDOW; const BOOL res = CreateProcess((LPCTSTR)module_name,(LPTSTR)command,0,0,FALSE,0,0,0,&si,&pi); if (res) { WaitForSingleObject(pi.hProcess,INFINITE); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); return 0; } else return std::system(command); #else return std::system(command); #endif #endif } //! Return a reference to a temporary variable of type T. template<typename T> inline T& temporary(const T&) { static T temp; return temp; } //! Exchange values of variables \c a and \c b. template<typename T> inline void swap(T& a, T& b) { T t = a; a = b; b = t; } //! Exchange values of variables (\c a1,\c a2) and (\c b1,\c b2). template<typename T1, typename T2> inline void swap(T1& a1, T1& b1, T2& a2, T2& b2) { cimg::swap(a1,b1); cimg::swap(a2,b2); } //! Exchange values of variables (\c a1,\c a2,\c a3) and (\c b1,\c b2,\c b3). template<typename T1, typename T2, typename T3> inline void swap(T1& a1, T1& b1, T2& a2, T2& b2, T3& a3, T3& b3) { cimg::swap(a1,b1,a2,b2); cimg::swap(a3,b3); } //! Exchange values of variables (\c a1,\c a2,...,\c a4) and (\c b1,\c b2,...,\c b4). template<typename T1, typename T2, typename T3, typename T4> inline void swap(T1& a1, T1& b1, T2& a2, T2& b2, T3& a3, T3& b3, T4& a4, T4& b4) { cimg::swap(a1,b1,a2,b2,a3,b3); cimg::swap(a4,b4); } //! Exchange values of variables (\c a1,\c a2,...,\c a5) and (\c b1,\c b2,...,\c b5). template<typename T1, typename T2, typename T3, typename T4, typename T5> inline void swap(T1& a1, T1& b1, T2& a2, T2& b2, T3& a3, T3& b3, T4& a4, T4& b4, T5& a5, T5& b5) { cimg::swap(a1,b1,a2,b2,a3,b3,a4,b4); cimg::swap(a5,b5); } //! Exchange values of variables (\c a1,\c a2,...,\c a6) and (\c b1,\c b2,...,\c b6). template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> inline void swap(T1& a1, T1& b1, T2& a2, T2& b2, T3& a3, T3& b3, T4& a4, T4& b4, T5& a5, T5& b5, T6& a6, T6& b6) { cimg::swap(a1,b1,a2,b2,a3,b3,a4,b4,a5,b5); cimg::swap(a6,b6); } //! Exchange values of variables (\c a1,\c a2,...,\c a7) and (\c b1,\c b2,...,\c b7). template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> inline void swap(T1& a1, T1& b1, T2& a2, T2& b2, T3& a3, T3& b3, T4& a4, T4& b4, T5& a5, T5& b5, T6& a6, T6& b6, T7& a7, T7& b7) { cimg::swap(a1,b1,a2,b2,a3,b3,a4,b4,a5,b5,a6,b6); cimg::swap(a7,b7); } //! Exchange values of variables (\c a1,\c a2,...,\c a8) and (\c b1,\c b2,...,\c b8). template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> inline void swap(T1& a1, T1& b1, T2& a2, T2& b2, T3& a3, T3& b3, T4& a4, T4& b4, T5& a5, T5& b5, T6& a6, T6& b6, T7& a7, T7& b7, T8& a8, T8& b8) { cimg::swap(a1,b1,a2,b2,a3,b3,a4,b4,a5,b5,a6,b6,a7,b7); cimg::swap(a8,b8); } //! Return the endianness of the current architecture. /** \return \c false for <i>Little Endian</i> or \c true for <i>Big Endian</i>. **/ inline bool endianness() { const int x = 1; return ((unsigned char*)&x)[0]?false:true; } //! Reverse endianness of all elements in a memory buffer. /** \param[in,out] buffer Memory buffer whose endianness must be reversed. \param size Number of buffer elements to reverse. **/ template<typename T> inline void invert_endianness(T* const buffer, const cimg_ulong size) { if (size) switch (sizeof(T)) { case 1 : break; case 2 : { for (unsigned short *ptr = (unsigned short*)buffer + size; ptr>(unsigned short*)buffer; ) { const unsigned short val = *(--ptr); *ptr = (unsigned short)((val>>8) | ((val<<8))); } } break; case 4 : { for (unsigned int *ptr = (unsigned int*)buffer + size; ptr>(unsigned int*)buffer; ) { const unsigned int val = *(--ptr); *ptr = (val>>24) | ((val>>8)&0xff00) | ((val<<8)&0xff0000) | (val<<24); } } break; case 8 : { const cimg_uint64 m0 = (cimg_uint64)0xff, m1 = m0<<8, m2 = m0<<16, m3 = m0<<24, m4 = m0<<32, m5 = m0<<40, m6 = m0<<48, m7 = m0<<56; for (cimg_uint64 *ptr = (cimg_uint64*)buffer + size; ptr>(cimg_uint64*)buffer; ) { const cimg_uint64 val = *(--ptr); *ptr = (((val&m7)>>56) | ((val&m6)>>40) | ((val&m5)>>24) | ((val&m4)>>8) | ((val&m3)<<8) |((val&m2)<<24) | ((val&m1)<<40) | ((val&m0)<<56)); } } break; default : { for (T* ptr = buffer + size; ptr>buffer; ) { unsigned char *pb = (unsigned char*)(--ptr), *pe = pb + sizeof(T); for (int i = 0; i<(int)sizeof(T)/2; ++i) swap(*(pb++),*(--pe)); } } } } //! Reverse endianness of a single variable. /** \param[in,out] a Variable to reverse. \return Reference to reversed variable. **/ template<typename T> inline T& invert_endianness(T& a) { invert_endianness(&a,1); return a; } // Conversion functions to get more precision when trying to store unsigned ints values as floats. inline unsigned int float2uint(const float f) { int tmp = 0; std::memcpy(&tmp,&f,sizeof(float)); if (tmp>=0) return (unsigned int)f; unsigned int u; // use memcpy instead of assignment to avoid undesired optimizations by C++-compiler. std::memcpy(&u,&f,sizeof(float)); return ((u)<<1)>>1; // set sign bit to 0 } inline float uint2float(const unsigned int u) { if (u<(1U<<19)) return (float)u; // Consider safe storage of unsigned int as floats until 19bits (i.e 524287) float f; const unsigned int v = u|(1U<<(8*sizeof(unsigned int)-1)); // set sign bit to 1 // use memcpy instead of simple assignment to avoid undesired optimizations by C++-compiler. std::memcpy(&f,&v,sizeof(float)); return f; } //! Return the value of a system timer, with a millisecond precision. /** \note The timer does not necessarily starts from \c 0. **/ inline cimg_ulong time() { #if cimg_OS==1 struct timeval st_time; gettimeofday(&st_time,0); return (cimg_ulong)(st_time.tv_usec/1000 + st_time.tv_sec*1000); #elif cimg_OS==2 SYSTEMTIME st_time; GetLocalTime(&st_time); return (cimg_ulong)(st_time.wMilliseconds + 1000*(st_time.wSecond + 60*(st_time.wMinute + 60*st_time.wHour))); #else return 0; #endif } // Implement a tic/toc mechanism to display elapsed time of algorithms. inline cimg_ulong tictoc(const bool is_tic); //! Start tic/toc timer for time measurement between code instructions. /** \return Current value of the timer (same value as time()). **/ inline cimg_ulong tic() { return cimg::tictoc(true); } //! End tic/toc timer and displays elapsed time from last call to tic(). /** \return Time elapsed (in ms) since last call to tic(). **/ inline cimg_ulong toc() { return cimg::tictoc(false); } //! Sleep for a given numbers of milliseconds. /** \param milliseconds Number of milliseconds to wait for. \note This function frees the CPU ressources during the sleeping time. It can be used to temporize your program properly, without wasting CPU time. **/ inline void sleep(const unsigned int milliseconds) { #if cimg_OS==1 struct timespec tv; tv.tv_sec = milliseconds/1000; tv.tv_nsec = (milliseconds%1000)*1000000; nanosleep(&tv,0); #elif cimg_OS==2 Sleep(milliseconds); #else cimg::unused(milliseconds); #endif } inline unsigned int wait(const unsigned int milliseconds, cimg_ulong *const p_timer) { if (!*p_timer) *p_timer = cimg::time(); const cimg_ulong current_time = cimg::time(); if (current_time>=*p_timer + milliseconds) { *p_timer = current_time; return 0; } const unsigned int time_diff = (unsigned int)(*p_timer + milliseconds - current_time); *p_timer = current_time + time_diff; cimg::sleep(time_diff); return time_diff; } //! Wait for a given number of milliseconds since the last call to wait(). /** \param milliseconds Number of milliseconds to wait for. \return Number of milliseconds elapsed since the last call to wait(). \note Same as sleep() with a waiting time computed with regard to the last call of wait(). It may be used to temporize your program properly, without wasting CPU time. **/ inline cimg_long wait(const unsigned int milliseconds) { cimg::mutex(3); static cimg_ulong timer = cimg::time(); cimg::mutex(3,0); return cimg::wait(milliseconds,&timer); } // Custom random number generator (allow re-entrance). inline cimg_ulong& rng() { // Used as a shared global number for rng static cimg_ulong rng = 0xB16B00B5U; return rng; } inline unsigned int _rand(cimg_ulong *const p_rng) { *p_rng = *p_rng*1103515245 + 12345U; return (unsigned int)*p_rng; } inline unsigned int _rand() { cimg::mutex(4); const unsigned int res = cimg::_rand(&cimg::rng()); cimg::mutex(4,0); return res; } inline void srand(cimg_ulong *const p_rng) { #if cimg_OS==1 *p_rng = cimg::time() + (cimg_ulong)getpid(); #elif cimg_OS==2 *p_rng = cimg::time() + (cimg_ulong)_getpid(); #endif } inline void srand() { cimg::mutex(4); cimg::srand(&cimg::rng()); cimg::mutex(4,0); } inline void srand(const cimg_ulong seed) { cimg::mutex(4); cimg::rng() = seed; cimg::mutex(4,0); } inline double rand(const double val_min, const double val_max, cimg_ulong *const p_rng) { const double val = cimg::_rand(p_rng)/(double)~0U; return val_min + (val_max - val_min)*val; } inline double rand(const double val_min, const double val_max) { cimg::mutex(4); const double res = cimg::rand(val_min,val_max,&cimg::rng()); cimg::mutex(4,0); return res; } inline double rand(const double val_max, cimg_ulong *const p_rng) { const double val = cimg::_rand(p_rng)/(double)~0U; return val_max*val; } inline double rand(const double val_max=1) { cimg::mutex(4); const double res = cimg::rand(val_max,&cimg::rng()); cimg::mutex(4,0); return res; } inline double grand(cimg_ulong *const p_rng) { double x1, w; do { const double x2 = cimg::rand(-1,1,p_rng); x1 = cimg::rand(-1,1,p_rng); w = x1*x1 + x2*x2; } while (w<=0 || w>=1.); return x1*std::sqrt((-2*std::log(w))/w); } inline double grand() { cimg::mutex(4); const double res = cimg::grand(&cimg::rng()); cimg::mutex(4,0); return res; } inline unsigned int prand(const double z, cimg_ulong *const p_rng) { if (z<=1.e-10) return 0; if (z>100) return (unsigned int)((std::sqrt(z) * cimg::grand(p_rng)) + z); unsigned int k = 0; const double y = std::exp(-z); for (double s = 1.; s>=y; ++k) s*=cimg::rand(1,p_rng); return k - 1; } inline unsigned int prand(const double z) { cimg::mutex(4); const unsigned int res = cimg::prand(z,&cimg::rng()); cimg::mutex(4,0); return res; } //! Cut (i.e. clamp) value in specified interval. template<typename T, typename t> inline T cut(const T& val, const t& val_min, const t& val_max) { return val<val_min?(T)val_min:val>val_max?(T)val_max:val; } //! Bitwise-rotate value on the left. template<typename T> inline T rol(const T& a, const unsigned int n=1) { return n?(T)((a<<n)|(a>>((sizeof(T)<<3) - n))):a; } inline float rol(const float a, const unsigned int n=1) { return (float)rol((int)a,n); } inline double rol(const double a, const unsigned int n=1) { return (double)rol((cimg_long)a,n); } inline double rol(const long double a, const unsigned int n=1) { return (double)rol((cimg_long)a,n); } #ifdef cimg_use_half inline half rol(const half a, const unsigned int n=1) { return (half)rol((int)a,n); } #endif //! Bitwise-rotate value on the right. template<typename T> inline T ror(const T& a, const unsigned int n=1) { return n?(T)((a>>n)|(a<<((sizeof(T)<<3) - n))):a; } inline float ror(const float a, const unsigned int n=1) { return (float)ror((int)a,n); } inline double ror(const double a, const unsigned int n=1) { return (double)ror((cimg_long)a,n); } inline double ror(const long double a, const unsigned int n=1) { return (double)ror((cimg_long)a,n); } #ifdef cimg_use_half inline half ror(const half a, const unsigned int n=1) { return (half)ror((int)a,n); } #endif //! Return absolute value of a value. template<typename T> inline T abs(const T& a) { return a>=0?a:-a; } inline bool abs(const bool a) { return a; } inline int abs(const unsigned char a) { return (int)a; } inline int abs(const unsigned short a) { return (int)a; } inline int abs(const unsigned int a) { return (int)a; } inline int abs(const int a) { return std::abs(a); } inline cimg_int64 abs(const cimg_uint64 a) { return (cimg_int64)a; } inline double abs(const double a) { return std::fabs(a); } inline float abs(const float a) { return (float)std::fabs((double)a); } //! Return hyperbolic arcosine of a value. inline double acosh(const double x) { #if cimg_use_cpp11==1 && !defined(_MSC_VER) return std::acosh(x); #else return std::log(x + std::sqrt(x*x - 1)); #endif } //! Return hyperbolic arcsine of a value. inline double asinh(const double x) { #if cimg_use_cpp11==1 && !defined(_MSC_VER) return std::asinh(x); #else return std::log(x + std::sqrt(x*x + 1)); #endif } //! Return hyperbolic arctangent of a value. inline double atanh(const double x) { #if cimg_use_cpp11==1 && !defined(_MSC_VER) return std::atanh(x); #else return 0.5*std::log((1. + x)/(1. - x)); #endif } //! Return the sinc of a given value. inline double sinc(const double x) { return x?std::sin(x)/x:1; } //! Return base-2 logarithm of a value. inline double log2(const double x) { #if cimg_use_cpp11==1 && !defined(_MSC_VER) return std::log2(x); #else const double base2 = std::log(2.); return std::log(x)/base2; #endif } //! Return square of a value. template<typename T> inline T sqr(const T& val) { return val*val; } //! Return cubic root of a value. template<typename T> inline double cbrt(const T& x) { #if cimg_use_cpp11==1 return std::cbrt(x); #else return x>=0?std::pow((double)x,1./3):-std::pow(-(double)x,1./3); #endif } template<typename T> inline T pow3(const T& val) { return val*val*val; } template<typename T> inline T pow4(const T& val) { return val*val*val*val; } //! Return the minimum between three values. template<typename t> inline t min(const t& a, const t& b, const t& c) { return std::min(std::min(a,b),c); } //! Return the minimum between four values. template<typename t> inline t min(const t& a, const t& b, const t& c, const t& d) { return std::min(std::min(a,b),std::min(c,d)); } //! Return the maximum between three values. template<typename t> inline t max(const t& a, const t& b, const t& c) { return std::max(std::max(a,b),c); } //! Return the maximum between four values. template<typename t> inline t max(const t& a, const t& b, const t& c, const t& d) { return std::max(std::max(a,b),std::max(c,d)); } //! Return the sign of a value. template<typename T> inline T sign(const T& x) { return (T)(cimg::type<T>::is_nan(x)?0:x<0?-1:x>0); } //! Return the nearest power of 2 higher than given value. template<typename T> inline cimg_ulong nearest_pow2(const T& x) { cimg_ulong i = 1; while (x>i) i<<=1; return i; } //! Return the modulo of a value. /** \param x Input value. \param m Modulo value. \note This modulo function accepts negative and floating-points modulo numbers, as well as variables of any type. **/ template<typename T> inline T mod(const T& x, const T& m) { const double dx = (double)x, dm = (double)m; return (T)(dx - dm * std::floor(dx / dm)); } inline int mod(const bool x, const bool m) { return m?(x?1:0):0; } inline int mod(const unsigned char x, const unsigned char m) { return x%m; } inline int mod(const char x, const char m) { #if defined(CHAR_MAX) && CHAR_MAX==255 return x%m; #else return x>=0?x%m:(x%m?m + x%m:0); #endif } inline int mod(const unsigned short x, const unsigned short m) { return x%m; } inline int mod(const short x, const short m) { return x>=0?x%m:(x%m?m + x%m:0); } inline int mod(const unsigned int x, const unsigned int m) { return (int)(x%m); } inline int mod(const int x, const int m) { return x>=0?x%m:(x%m?m + x%m:0); } inline cimg_int64 mod(const cimg_uint64 x, const cimg_uint64 m) { return x%m; } inline cimg_int64 mod(const cimg_int64 x, const cimg_int64 m) { return x>=0?x%m:(x%m?m + x%m:0); } //! Return the min-mod of two values. /** \note <i>minmod(\p a,\p b)</i> is defined to be: - <i>minmod(\p a,\p b) = min(\p a,\p b)</i>, if \p a and \p b have the same sign. - <i>minmod(\p a,\p b) = 0</i>, if \p a and \p b have different signs. **/ template<typename T> inline T minmod(const T& a, const T& b) { return a*b<=0?0:(a>0?(a<b?a:b):(a<b?b:a)); } template<typename T> inline T round(const T& x) { return (T)std::floor((_cimg_Tfloat)x + 0.5f); } template<typename T> inline int uiround(const T x) { return cimg::type<T>::is_float()?(int)(x + 0.5f):(int)x; } //! Return rounded value. /** \param x Value to be rounded. \param y Rounding precision. \param rounding_type Type of rounding operation (\c 0 = nearest, \c -1 = backward, \c 1 = forward). \return Rounded value, having the same type as input value \c x. **/ template<typename T> inline T round(const T& x, const double y, const int rounding_type=0) { if (y<=0) return x; if (y==1) switch (rounding_type) { case 0 : return cimg::round(x); case 1 : return (T)std::ceil((_cimg_Tfloat)x); default : return (T)std::floor((_cimg_Tfloat)x); } const double sx = (double)x/y, floor = std::floor(sx), delta = sx - floor; return (T)(y*(rounding_type<0?floor:rounding_type>0?std::ceil(sx):delta<0.5?floor:std::ceil(sx))); } // Code to compute fast median from 2,3,5,7,9,13,25 and 49 values. // (contribution by RawTherapee: http://rawtherapee.com/). template<typename T> inline T median(T val0, T val1) { return (val0 + val1)/2; } template<typename T> inline T median(T val0, T val1, T val2) { return std::max(std::min(val0,val1),std::min(val2,std::max(val0,val1))); } template<typename T> inline T median(T val0, T val1, T val2, T val3, T val4) { T tmp = std::min(val0,val1); val1 = std::max(val0,val1); val0 = tmp; tmp = std::min(val3,val4); val4 = std::max(val3,val4); val3 = std::max(val0,tmp); val1 = std::min(val1,val4); tmp = std::min(val1,val2); val2 = std::max(val1,val2); val1 = tmp; tmp = std::min(val2,val3); return std::max(val1,tmp); } template<typename T> inline T median(T val0, T val1, T val2, T val3, T val4, T val5, T val6) { T tmp = std::min(val0,val5); val5 = std::max(val0,val5); val0 = tmp; tmp = std::min(val0,val3); val3 = std::max(val0,val3); val0 = tmp; tmp = std::min(val1,val6); val6 = std::max(val1,val6); val1 = tmp; tmp = std::min(val2,val4); val4 = std::max(val2,val4); val2 = tmp; val1 = std::max(val0,val1); tmp = std::min(val3,val5); val5 = std::max(val3,val5); val3 = tmp; tmp = std::min(val2,val6); val6 = std::max(val2,val6); val3 = std::max(tmp,val3); val3 = std::min(val3,val6); tmp = std::min(val4,val5); val4 = std::max(val1,tmp); tmp = std::min(val1,tmp); val3 = std::max(tmp,val3); return std::min(val3,val4); } template<typename T> inline T median(T val0, T val1, T val2, T val3, T val4, T val5, T val6, T val7, T val8) { T tmp = std::min(val1,val2); val2 = std::max(val1,val2); val1 = tmp; tmp = std::min(val4,val5); val5 = std::max(val4,val5); val4 = tmp; tmp = std::min(val7,val8); val8 = std::max(val7,val8); val7 = tmp; tmp = std::min(val0,val1); val1 = std::max(val0,val1); val0 = tmp; tmp = std::min(val3,val4); val4 = std::max(val3,val4); val3 = tmp; tmp = std::min(val6,val7); val7 = std::max(val6,val7); val6 = tmp; tmp = std::min(val1,val2); val2 = std::max(val1,val2); val1 = tmp; tmp = std::min(val4,val5); val5 = std::max(val4,val5); val4 = tmp; tmp = std::min(val7,val8); val8 = std::max(val7,val8); val3 = std::max(val0,val3); val5 = std::min(val5,val8); val7 = std::max(val4,tmp); tmp = std::min(val4,tmp); val6 = std::max(val3,val6); val4 = std::max(val1,tmp); val2 = std::min(val2,val5); val4 = std::min(val4,val7); tmp = std::min(val4,val2); val2 = std::max(val4,val2); val4 = std::max(val6,tmp); return std::min(val4,val2); } template<typename T> inline T median(T val0, T val1, T val2, T val3, T val4, T val5, T val6, T val7, T val8, T val9, T val10, T val11, T val12) { T tmp = std::min(val1,val7); val7 = std::max(val1,val7); val1 = tmp; tmp = std::min(val9,val11); val11 = std::max(val9,val11); val9 = tmp; tmp = std::min(val3,val4); val4 = std::max(val3,val4); val3 = tmp; tmp = std::min(val5,val8); val8 = std::max(val5,val8); val5 = tmp; tmp = std::min(val0,val12); val12 = std::max(val0,val12); val0 = tmp; tmp = std::min(val2,val6); val6 = std::max(val2,val6); val2 = tmp; tmp = std::min(val0,val1); val1 = std::max(val0,val1); val0 = tmp; tmp = std::min(val2,val3); val3 = std::max(val2,val3); val2 = tmp; tmp = std::min(val4,val6); val6 = std::max(val4,val6); val4 = tmp; tmp = std::min(val8,val11); val11 = std::max(val8,val11); val8 = tmp; tmp = std::min(val7,val12); val12 = std::max(val7,val12); val7 = tmp; tmp = std::min(val5,val9); val9 = std::max(val5,val9); val5 = tmp; tmp = std::min(val0,val2); val2 = std::max(val0,val2); val0 = tmp; tmp = std::min(val3,val7); val7 = std::max(val3,val7); val3 = tmp; tmp = std::min(val10,val11); val11 = std::max(val10,val11); val10 = tmp; tmp = std::min(val1,val4); val4 = std::max(val1,val4); val1 = tmp; tmp = std::min(val6,val12); val12 = std::max(val6,val12); val6 = tmp; tmp = std::min(val7,val8); val8 = std::max(val7,val8); val7 = tmp; val11 = std::min(val11,val12); tmp = std::min(val4,val9); val9 = std::max(val4,val9); val4 = tmp; tmp = std::min(val6,val10); val10 = std::max(val6,val10); val6 = tmp; tmp = std::min(val3,val4); val4 = std::max(val3,val4); val3 = tmp; tmp = std::min(val5,val6); val6 = std::max(val5,val6); val5 = tmp; val8 = std::min(val8,val9); val10 = std::min(val10,val11); tmp = std::min(val1,val7); val7 = std::max(val1,val7); val1 = tmp; tmp = std::min(val2,val6); val6 = std::max(val2,val6); val2 = tmp; val3 = std::max(val1,val3); tmp = std::min(val4,val7); val7 = std::max(val4,val7); val4 = tmp; val8 = std::min(val8,val10); val5 = std::max(val0,val5); val5 = std::max(val2,val5); tmp = std::min(val6,val8); val8 = std::max(val6,val8); val5 = std::max(val3,val5); val7 = std::min(val7,val8); val6 = std::max(val4,tmp); tmp = std::min(val4,tmp); val5 = std::max(tmp,val5); val6 = std::min(val6,val7); return std::max(val5,val6); } template<typename T> inline T median(T val0, T val1, T val2, T val3, T val4, T val5, T val6, T val7, T val8, T val9, T val10, T val11, T val12, T val13, T val14, T val15, T val16, T val17, T val18, T val19, T val20, T val21, T val22, T val23, T val24) { T tmp = std::min(val0,val1); val1 = std::max(val0,val1); val0 = tmp; tmp = std::min(val3,val4); val4 = std::max(val3,val4); val3 = tmp; tmp = std::min(val2,val4); val4 = std::max(val2,val4); val2 = std::min(tmp,val3); val3 = std::max(tmp,val3); tmp = std::min(val6,val7); val7 = std::max(val6,val7); val6 = tmp; tmp = std::min(val5,val7); val7 = std::max(val5,val7); val5 = std::min(tmp,val6); val6 = std::max(tmp,val6); tmp = std::min(val9,val10); val10 = std::max(val9,val10); val9 = tmp; tmp = std::min(val8,val10); val10 = std::max(val8,val10); val8 = std::min(tmp,val9); val9 = std::max(tmp,val9); tmp = std::min(val12,val13); val13 = std::max(val12,val13); val12 = tmp; tmp = std::min(val11,val13); val13 = std::max(val11,val13); val11 = std::min(tmp,val12); val12 = std::max(tmp,val12); tmp = std::min(val15,val16); val16 = std::max(val15,val16); val15 = tmp; tmp = std::min(val14,val16); val16 = std::max(val14,val16); val14 = std::min(tmp,val15); val15 = std::max(tmp,val15); tmp = std::min(val18,val19); val19 = std::max(val18,val19); val18 = tmp; tmp = std::min(val17,val19); val19 = std::max(val17,val19); val17 = std::min(tmp,val18); val18 = std::max(tmp,val18); tmp = std::min(val21,val22); val22 = std::max(val21,val22); val21 = tmp; tmp = std::min(val20,val22); val22 = std::max(val20,val22); val20 = std::min(tmp,val21); val21 = std::max(tmp,val21); tmp = std::min(val23,val24); val24 = std::max(val23,val24); val23 = tmp; tmp = std::min(val2,val5); val5 = std::max(val2,val5); val2 = tmp; tmp = std::min(val3,val6); val6 = std::max(val3,val6); val3 = tmp; tmp = std::min(val0,val6); val6 = std::max(val0,val6); val0 = std::min(tmp,val3); val3 = std::max(tmp,val3); tmp = std::min(val4,val7); val7 = std::max(val4,val7); val4 = tmp; tmp = std::min(val1,val7); val7 = std::max(val1,val7); val1 = std::min(tmp,val4); val4 = std::max(tmp,val4); tmp = std::min(val11,val14); val14 = std::max(val11,val14); val11 = tmp; tmp = std::min(val8,val14); val14 = std::max(val8,val14); val8 = std::min(tmp,val11); val11 = std::max(tmp,val11); tmp = std::min(val12,val15); val15 = std::max(val12,val15); val12 = tmp; tmp = std::min(val9,val15); val15 = std::max(val9,val15); val9 = std::min(tmp,val12); val12 = std::max(tmp,val12); tmp = std::min(val13,val16); val16 = std::max(val13,val16); val13 = tmp; tmp = std::min(val10,val16); val16 = std::max(val10,val16); val10 = std::min(tmp,val13); val13 = std::max(tmp,val13); tmp = std::min(val20,val23); val23 = std::max(val20,val23); val20 = tmp; tmp = std::min(val17,val23); val23 = std::max(val17,val23); val17 = std::min(tmp,val20); val20 = std::max(tmp,val20); tmp = std::min(val21,val24); val24 = std::max(val21,val24); val21 = tmp; tmp = std::min(val18,val24); val24 = std::max(val18,val24); val18 = std::min(tmp,val21); val21 = std::max(tmp,val21); tmp = std::min(val19,val22); val22 = std::max(val19,val22); val19 = tmp; val17 = std::max(val8,val17); tmp = std::min(val9,val18); val18 = std::max(val9,val18); val9 = tmp; tmp = std::min(val0,val18); val18 = std::max(val0,val18); val9 = std::max(tmp,val9); tmp = std::min(val10,val19); val19 = std::max(val10,val19); val10 = tmp; tmp = std::min(val1,val19); val19 = std::max(val1,val19); val1 = std::min(tmp,val10); val10 = std::max(tmp,val10); tmp = std::min(val11,val20); val20 = std::max(val11,val20); val11 = tmp; tmp = std::min(val2,val20); val20 = std::max(val2,val20); val11 = std::max(tmp,val11); tmp = std::min(val12,val21); val21 = std::max(val12,val21); val12 = tmp; tmp = std::min(val3,val21); val21 = std::max(val3,val21); val3 = std::min(tmp,val12); val12 = std::max(tmp,val12); tmp = std::min(val13,val22); val22 = std::max(val13,val22); val4 = std::min(val4,val22); val13 = std::max(val4,tmp); tmp = std::min(val4,tmp); val4 = tmp; tmp = std::min(val14,val23); val23 = std::max(val14,val23); val14 = tmp; tmp = std::min(val5,val23); val23 = std::max(val5,val23); val5 = std::min(tmp,val14); val14 = std::max(tmp,val14); tmp = std::min(val15,val24); val24 = std::max(val15,val24); val15 = tmp; val6 = std::min(val6,val24); tmp = std::min(val6,val15); val15 = std::max(val6,val15); val6 = tmp; tmp = std::min(val7,val16); val7 = std::min(tmp,val19); tmp = std::min(val13,val21); val15 = std::min(val15,val23); tmp = std::min(val7,tmp); val7 = std::min(tmp,val15); val9 = std::max(val1,val9); val11 = std::max(val3,val11); val17 = std::max(val5,val17); val17 = std::max(val11,val17); val17 = std::max(val9,val17); tmp = std::min(val4,val10); val10 = std::max(val4,val10); val4 = tmp; tmp = std::min(val6,val12); val12 = std::max(val6,val12); val6 = tmp; tmp = std::min(val7,val14); val14 = std::max(val7,val14); val7 = tmp; tmp = std::min(val4,val6); val6 = std::max(val4,val6); val7 = std::max(tmp,val7); tmp = std::min(val12,val14); val14 = std::max(val12,val14); val12 = tmp; val10 = std::min(val10,val14); tmp = std::min(val6,val7); val7 = std::max(val6,val7); val6 = tmp; tmp = std::min(val10,val12); val12 = std::max(val10,val12); val10 = std::max(val6,tmp); tmp = std::min(val6,tmp); val17 = std::max(tmp,val17); tmp = std::min(val12,val17); val17 = std::max(val12,val17); val12 = tmp; val7 = std::min(val7,val17); tmp = std::min(val7,val10); val10 = std::max(val7,val10); val7 = tmp; tmp = std::min(val12,val18); val18 = std::max(val12,val18); val12 = std::max(val7,tmp); val10 = std::min(val10,val18); tmp = std::min(val12,val20); val20 = std::max(val12,val20); val12 = tmp; tmp = std::min(val10,val20); return std::max(tmp,val12); } template<typename T> inline T median(T val0, T val1, T val2, T val3, T val4, T val5, T val6, T val7, T val8, T val9, T val10, T val11, T val12, T val13, T val14, T val15, T val16, T val17, T val18, T val19, T val20, T val21, T val22, T val23, T val24, T val25, T val26, T val27, T val28, T val29, T val30, T val31, T val32, T val33, T val34, T val35, T val36, T val37, T val38, T val39, T val40, T val41, T val42, T val43, T val44, T val45, T val46, T val47, T val48) { T tmp = std::min(val0,val32); val32 = std::max(val0,val32); val0 = tmp; tmp = std::min(val1,val33); val33 = std::max(val1,val33); val1 = tmp; tmp = std::min(val2,val34); val34 = std::max(val2,val34); val2 = tmp; tmp = std::min(val3,val35); val35 = std::max(val3,val35); val3 = tmp; tmp = std::min(val4,val36); val36 = std::max(val4,val36); val4 = tmp; tmp = std::min(val5,val37); val37 = std::max(val5,val37); val5 = tmp; tmp = std::min(val6,val38); val38 = std::max(val6,val38); val6 = tmp; tmp = std::min(val7,val39); val39 = std::max(val7,val39); val7 = tmp; tmp = std::min(val8,val40); val40 = std::max(val8,val40); val8 = tmp; tmp = std::min(val9,val41); val41 = std::max(val9,val41); val9 = tmp; tmp = std::min(val10,val42); val42 = std::max(val10,val42); val10 = tmp; tmp = std::min(val11,val43); val43 = std::max(val11,val43); val11 = tmp; tmp = std::min(val12,val44); val44 = std::max(val12,val44); val12 = tmp; tmp = std::min(val13,val45); val45 = std::max(val13,val45); val13 = tmp; tmp = std::min(val14,val46); val46 = std::max(val14,val46); val14 = tmp; tmp = std::min(val15,val47); val47 = std::max(val15,val47); val15 = tmp; tmp = std::min(val16,val48); val48 = std::max(val16,val48); val16 = tmp; tmp = std::min(val0,val16); val16 = std::max(val0,val16); val0 = tmp; tmp = std::min(val1,val17); val17 = std::max(val1,val17); val1 = tmp; tmp = std::min(val2,val18); val18 = std::max(val2,val18); val2 = tmp; tmp = std::min(val3,val19); val19 = std::max(val3,val19); val3 = tmp; tmp = std::min(val4,val20); val20 = std::max(val4,val20); val4 = tmp; tmp = std::min(val5,val21); val21 = std::max(val5,val21); val5 = tmp; tmp = std::min(val6,val22); val22 = std::max(val6,val22); val6 = tmp; tmp = std::min(val7,val23); val23 = std::max(val7,val23); val7 = tmp; tmp = std::min(val8,val24); val24 = std::max(val8,val24); val8 = tmp; tmp = std::min(val9,val25); val25 = std::max(val9,val25); val9 = tmp; tmp = std::min(val10,val26); val26 = std::max(val10,val26); val10 = tmp; tmp = std::min(val11,val27); val27 = std::max(val11,val27); val11 = tmp; tmp = std::min(val12,val28); val28 = std::max(val12,val28); val12 = tmp; tmp = std::min(val13,val29); val29 = std::max(val13,val29); val13 = tmp; tmp = std::min(val14,val30); val30 = std::max(val14,val30); val14 = tmp; tmp = std::min(val15,val31); val31 = std::max(val15,val31); val15 = tmp; tmp = std::min(val32,val48); val48 = std::max(val32,val48); val32 = tmp; tmp = std::min(val16,val32); val32 = std::max(val16,val32); val16 = tmp; tmp = std::min(val17,val33); val33 = std::max(val17,val33); val17 = tmp; tmp = std::min(val18,val34); val34 = std::max(val18,val34); val18 = tmp; tmp = std::min(val19,val35); val35 = std::max(val19,val35); val19 = tmp; tmp = std::min(val20,val36); val36 = std::max(val20,val36); val20 = tmp; tmp = std::min(val21,val37); val37 = std::max(val21,val37); val21 = tmp; tmp = std::min(val22,val38); val38 = std::max(val22,val38); val22 = tmp; tmp = std::min(val23,val39); val39 = std::max(val23,val39); val23 = tmp; tmp = std::min(val24,val40); val40 = std::max(val24,val40); val24 = tmp; tmp = std::min(val25,val41); val41 = std::max(val25,val41); val25 = tmp; tmp = std::min(val26,val42); val42 = std::max(val26,val42); val26 = tmp; tmp = std::min(val27,val43); val43 = std::max(val27,val43); val27 = tmp; tmp = std::min(val28,val44); val44 = std::max(val28,val44); val28 = tmp; tmp = std::min(val29,val45); val45 = std::max(val29,val45); val29 = tmp; tmp = std::min(val30,val46); val46 = std::max(val30,val46); val30 = tmp; tmp = std::min(val31,val47); val47 = std::max(val31,val47); val31 = tmp; tmp = std::min(val0,val8); val8 = std::max(val0,val8); val0 = tmp; tmp = std::min(val1,val9); val9 = std::max(val1,val9); val1 = tmp; tmp = std::min(val2,val10); val10 = std::max(val2,val10); val2 = tmp; tmp = std::min(val3,val11); val11 = std::max(val3,val11); val3 = tmp; tmp = std::min(val4,val12); val12 = std::max(val4,val12); val4 = tmp; tmp = std::min(val5,val13); val13 = std::max(val5,val13); val5 = tmp; tmp = std::min(val6,val14); val14 = std::max(val6,val14); val6 = tmp; tmp = std::min(val7,val15); val15 = std::max(val7,val15); val7 = tmp; tmp = std::min(val16,val24); val24 = std::max(val16,val24); val16 = tmp; tmp = std::min(val17,val25); val25 = std::max(val17,val25); val17 = tmp; tmp = std::min(val18,val26); val26 = std::max(val18,val26); val18 = tmp; tmp = std::min(val19,val27); val27 = std::max(val19,val27); val19 = tmp; tmp = std::min(val20,val28); val28 = std::max(val20,val28); val20 = tmp; tmp = std::min(val21,val29); val29 = std::max(val21,val29); val21 = tmp; tmp = std::min(val22,val30); val30 = std::max(val22,val30); val22 = tmp; tmp = std::min(val23,val31); val31 = std::max(val23,val31); val23 = tmp; tmp = std::min(val32,val40); val40 = std::max(val32,val40); val32 = tmp; tmp = std::min(val33,val41); val41 = std::max(val33,val41); val33 = tmp; tmp = std::min(val34,val42); val42 = std::max(val34,val42); val34 = tmp; tmp = std::min(val35,val43); val43 = std::max(val35,val43); val35 = tmp; tmp = std::min(val36,val44); val44 = std::max(val36,val44); val36 = tmp; tmp = std::min(val37,val45); val45 = std::max(val37,val45); val37 = tmp; tmp = std::min(val38,val46); val46 = std::max(val38,val46); val38 = tmp; tmp = std::min(val39,val47); val47 = std::max(val39,val47); val39 = tmp; tmp = std::min(val8,val32); val32 = std::max(val8,val32); val8 = tmp; tmp = std::min(val9,val33); val33 = std::max(val9,val33); val9 = tmp; tmp = std::min(val10,val34); val34 = std::max(val10,val34); val10 = tmp; tmp = std::min(val11,val35); val35 = std::max(val11,val35); val11 = tmp; tmp = std::min(val12,val36); val36 = std::max(val12,val36); val12 = tmp; tmp = std::min(val13,val37); val37 = std::max(val13,val37); val13 = tmp; tmp = std::min(val14,val38); val38 = std::max(val14,val38); val14 = tmp; tmp = std::min(val15,val39); val39 = std::max(val15,val39); val15 = tmp; tmp = std::min(val24,val48); val48 = std::max(val24,val48); val24 = tmp; tmp = std::min(val8,val16); val16 = std::max(val8,val16); val8 = tmp; tmp = std::min(val9,val17); val17 = std::max(val9,val17); val9 = tmp; tmp = std::min(val10,val18); val18 = std::max(val10,val18); val10 = tmp; tmp = std::min(val11,val19); val19 = std::max(val11,val19); val11 = tmp; tmp = std::min(val12,val20); val20 = std::max(val12,val20); val12 = tmp; tmp = std::min(val13,val21); val21 = std::max(val13,val21); val13 = tmp; tmp = std::min(val14,val22); val22 = std::max(val14,val22); val14 = tmp; tmp = std::min(val15,val23); val23 = std::max(val15,val23); val15 = tmp; tmp = std::min(val24,val32); val32 = std::max(val24,val32); val24 = tmp; tmp = std::min(val25,val33); val33 = std::max(val25,val33); val25 = tmp; tmp = std::min(val26,val34); val34 = std::max(val26,val34); val26 = tmp; tmp = std::min(val27,val35); val35 = std::max(val27,val35); val27 = tmp; tmp = std::min(val28,val36); val36 = std::max(val28,val36); val28 = tmp; tmp = std::min(val29,val37); val37 = std::max(val29,val37); val29 = tmp; tmp = std::min(val30,val38); val38 = std::max(val30,val38); val30 = tmp; tmp = std::min(val31,val39); val39 = std::max(val31,val39); val31 = tmp; tmp = std::min(val40,val48); val48 = std::max(val40,val48); val40 = tmp; tmp = std::min(val0,val4); val4 = std::max(val0,val4); val0 = tmp; tmp = std::min(val1,val5); val5 = std::max(val1,val5); val1 = tmp; tmp = std::min(val2,val6); val6 = std::max(val2,val6); val2 = tmp; tmp = std::min(val3,val7); val7 = std::max(val3,val7); val3 = tmp; tmp = std::min(val8,val12); val12 = std::max(val8,val12); val8 = tmp; tmp = std::min(val9,val13); val13 = std::max(val9,val13); val9 = tmp; tmp = std::min(val10,val14); val14 = std::max(val10,val14); val10 = tmp; tmp = std::min(val11,val15); val15 = std::max(val11,val15); val11 = tmp; tmp = std::min(val16,val20); val20 = std::max(val16,val20); val16 = tmp; tmp = std::min(val17,val21); val21 = std::max(val17,val21); val17 = tmp; tmp = std::min(val18,val22); val22 = std::max(val18,val22); val18 = tmp; tmp = std::min(val19,val23); val23 = std::max(val19,val23); val19 = tmp; tmp = std::min(val24,val28); val28 = std::max(val24,val28); val24 = tmp; tmp = std::min(val25,val29); val29 = std::max(val25,val29); val25 = tmp; tmp = std::min(val26,val30); val30 = std::max(val26,val30); val26 = tmp; tmp = std::min(val27,val31); val31 = std::max(val27,val31); val27 = tmp; tmp = std::min(val32,val36); val36 = std::max(val32,val36); val32 = tmp; tmp = std::min(val33,val37); val37 = std::max(val33,val37); val33 = tmp; tmp = std::min(val34,val38); val38 = std::max(val34,val38); val34 = tmp; tmp = std::min(val35,val39); val39 = std::max(val35,val39); val35 = tmp; tmp = std::min(val40,val44); val44 = std::max(val40,val44); val40 = tmp; tmp = std::min(val41,val45); val45 = std::max(val41,val45); val41 = tmp; tmp = std::min(val42,val46); val46 = std::max(val42,val46); val42 = tmp; tmp = std::min(val43,val47); val47 = std::max(val43,val47); val43 = tmp; tmp = std::min(val4,val32); val32 = std::max(val4,val32); val4 = tmp; tmp = std::min(val5,val33); val33 = std::max(val5,val33); val5 = tmp; tmp = std::min(val6,val34); val34 = std::max(val6,val34); val6 = tmp; tmp = std::min(val7,val35); val35 = std::max(val7,val35); val7 = tmp; tmp = std::min(val12,val40); val40 = std::max(val12,val40); val12 = tmp; tmp = std::min(val13,val41); val41 = std::max(val13,val41); val13 = tmp; tmp = std::min(val14,val42); val42 = std::max(val14,val42); val14 = tmp; tmp = std::min(val15,val43); val43 = std::max(val15,val43); val15 = tmp; tmp = std::min(val20,val48); val48 = std::max(val20,val48); val20 = tmp; tmp = std::min(val4,val16); val16 = std::max(val4,val16); val4 = tmp; tmp = std::min(val5,val17); val17 = std::max(val5,val17); val5 = tmp; tmp = std::min(val6,val18); val18 = std::max(val6,val18); val6 = tmp; tmp = std::min(val7,val19); val19 = std::max(val7,val19); val7 = tmp; tmp = std::min(val12,val24); val24 = std::max(val12,val24); val12 = tmp; tmp = std::min(val13,val25); val25 = std::max(val13,val25); val13 = tmp; tmp = std::min(val14,val26); val26 = std::max(val14,val26); val14 = tmp; tmp = std::min(val15,val27); val27 = std::max(val15,val27); val15 = tmp; tmp = std::min(val20,val32); val32 = std::max(val20,val32); val20 = tmp; tmp = std::min(val21,val33); val33 = std::max(val21,val33); val21 = tmp; tmp = std::min(val22,val34); val34 = std::max(val22,val34); val22 = tmp; tmp = std::min(val23,val35); val35 = std::max(val23,val35); val23 = tmp; tmp = std::min(val28,val40); val40 = std::max(val28,val40); val28 = tmp; tmp = std::min(val29,val41); val41 = std::max(val29,val41); val29 = tmp; tmp = std::min(val30,val42); val42 = std::max(val30,val42); val30 = tmp; tmp = std::min(val31,val43); val43 = std::max(val31,val43); val31 = tmp; tmp = std::min(val36,val48); val48 = std::max(val36,val48); val36 = tmp; tmp = std::min(val4,val8); val8 = std::max(val4,val8); val4 = tmp; tmp = std::min(val5,val9); val9 = std::max(val5,val9); val5 = tmp; tmp = std::min(val6,val10); val10 = std::max(val6,val10); val6 = tmp; tmp = std::min(val7,val11); val11 = std::max(val7,val11); val7 = tmp; tmp = std::min(val12,val16); val16 = std::max(val12,val16); val12 = tmp; tmp = std::min(val13,val17); val17 = std::max(val13,val17); val13 = tmp; tmp = std::min(val14,val18); val18 = std::max(val14,val18); val14 = tmp; tmp = std::min(val15,val19); val19 = std::max(val15,val19); val15 = tmp; tmp = std::min(val20,val24); val24 = std::max(val20,val24); val20 = tmp; tmp = std::min(val21,val25); val25 = std::max(val21,val25); val21 = tmp; tmp = std::min(val22,val26); val26 = std::max(val22,val26); val22 = tmp; tmp = std::min(val23,val27); val27 = std::max(val23,val27); val23 = tmp; tmp = std::min(val28,val32); val32 = std::max(val28,val32); val28 = tmp; tmp = std::min(val29,val33); val33 = std::max(val29,val33); val29 = tmp; tmp = std::min(val30,val34); val34 = std::max(val30,val34); val30 = tmp; tmp = std::min(val31,val35); val35 = std::max(val31,val35); val31 = tmp; tmp = std::min(val36,val40); val40 = std::max(val36,val40); val36 = tmp; tmp = std::min(val37,val41); val41 = std::max(val37,val41); val37 = tmp; tmp = std::min(val38,val42); val42 = std::max(val38,val42); val38 = tmp; tmp = std::min(val39,val43); val43 = std::max(val39,val43); val39 = tmp; tmp = std::min(val44,val48); val48 = std::max(val44,val48); val44 = tmp; tmp = std::min(val0,val2); val2 = std::max(val0,val2); val0 = tmp; tmp = std::min(val1,val3); val3 = std::max(val1,val3); val1 = tmp; tmp = std::min(val4,val6); val6 = std::max(val4,val6); val4 = tmp; tmp = std::min(val5,val7); val7 = std::max(val5,val7); val5 = tmp; tmp = std::min(val8,val10); val10 = std::max(val8,val10); val8 = tmp; tmp = std::min(val9,val11); val11 = std::max(val9,val11); val9 = tmp; tmp = std::min(val12,val14); val14 = std::max(val12,val14); val12 = tmp; tmp = std::min(val13,val15); val15 = std::max(val13,val15); val13 = tmp; tmp = std::min(val16,val18); val18 = std::max(val16,val18); val16 = tmp; tmp = std::min(val17,val19); val19 = std::max(val17,val19); val17 = tmp; tmp = std::min(val20,val22); val22 = std::max(val20,val22); val20 = tmp; tmp = std::min(val21,val23); val23 = std::max(val21,val23); val21 = tmp; tmp = std::min(val24,val26); val26 = std::max(val24,val26); val24 = tmp; tmp = std::min(val25,val27); val27 = std::max(val25,val27); val25 = tmp; tmp = std::min(val28,val30); val30 = std::max(val28,val30); val28 = tmp; tmp = std::min(val29,val31); val31 = std::max(val29,val31); val29 = tmp; tmp = std::min(val32,val34); val34 = std::max(val32,val34); val32 = tmp; tmp = std::min(val33,val35); val35 = std::max(val33,val35); val33 = tmp; tmp = std::min(val36,val38); val38 = std::max(val36,val38); val36 = tmp; tmp = std::min(val37,val39); val39 = std::max(val37,val39); val37 = tmp; tmp = std::min(val40,val42); val42 = std::max(val40,val42); val40 = tmp; tmp = std::min(val41,val43); val43 = std::max(val41,val43); val41 = tmp; tmp = std::min(val44,val46); val46 = std::max(val44,val46); val44 = tmp; tmp = std::min(val45,val47); val47 = std::max(val45,val47); val45 = tmp; tmp = std::min(val2,val32); val32 = std::max(val2,val32); val2 = tmp; tmp = std::min(val3,val33); val33 = std::max(val3,val33); val3 = tmp; tmp = std::min(val6,val36); val36 = std::max(val6,val36); val6 = tmp; tmp = std::min(val7,val37); val37 = std::max(val7,val37); val7 = tmp; tmp = std::min(val10,val40); val40 = std::max(val10,val40); val10 = tmp; tmp = std::min(val11,val41); val41 = std::max(val11,val41); val11 = tmp; tmp = std::min(val14,val44); val44 = std::max(val14,val44); val14 = tmp; tmp = std::min(val15,val45); val45 = std::max(val15,val45); val15 = tmp; tmp = std::min(val18,val48); val48 = std::max(val18,val48); val18 = tmp; tmp = std::min(val2,val16); val16 = std::max(val2,val16); val2 = tmp; tmp = std::min(val3,val17); val17 = std::max(val3,val17); val3 = tmp; tmp = std::min(val6,val20); val20 = std::max(val6,val20); val6 = tmp; tmp = std::min(val7,val21); val21 = std::max(val7,val21); val7 = tmp; tmp = std::min(val10,val24); val24 = std::max(val10,val24); val10 = tmp; tmp = std::min(val11,val25); val25 = std::max(val11,val25); val11 = tmp; tmp = std::min(val14,val28); val28 = std::max(val14,val28); val14 = tmp; tmp = std::min(val15,val29); val29 = std::max(val15,val29); val15 = tmp; tmp = std::min(val18,val32); val32 = std::max(val18,val32); val18 = tmp; tmp = std::min(val19,val33); val33 = std::max(val19,val33); val19 = tmp; tmp = std::min(val22,val36); val36 = std::max(val22,val36); val22 = tmp; tmp = std::min(val23,val37); val37 = std::max(val23,val37); val23 = tmp; tmp = std::min(val26,val40); val40 = std::max(val26,val40); val26 = tmp; tmp = std::min(val27,val41); val41 = std::max(val27,val41); val27 = tmp; tmp = std::min(val30,val44); val44 = std::max(val30,val44); val30 = tmp; tmp = std::min(val31,val45); val45 = std::max(val31,val45); val31 = tmp; tmp = std::min(val34,val48); val48 = std::max(val34,val48); val34 = tmp; tmp = std::min(val2,val8); val8 = std::max(val2,val8); val2 = tmp; tmp = std::min(val3,val9); val9 = std::max(val3,val9); val3 = tmp; tmp = std::min(val6,val12); val12 = std::max(val6,val12); val6 = tmp; tmp = std::min(val7,val13); val13 = std::max(val7,val13); val7 = tmp; tmp = std::min(val10,val16); val16 = std::max(val10,val16); val10 = tmp; tmp = std::min(val11,val17); val17 = std::max(val11,val17); val11 = tmp; tmp = std::min(val14,val20); val20 = std::max(val14,val20); val14 = tmp; tmp = std::min(val15,val21); val21 = std::max(val15,val21); val15 = tmp; tmp = std::min(val18,val24); val24 = std::max(val18,val24); val18 = tmp; tmp = std::min(val19,val25); val25 = std::max(val19,val25); val19 = tmp; tmp = std::min(val22,val28); val28 = std::max(val22,val28); val22 = tmp; tmp = std::min(val23,val29); val29 = std::max(val23,val29); val23 = tmp; tmp = std::min(val26,val32); val32 = std::max(val26,val32); val26 = tmp; tmp = std::min(val27,val33); val33 = std::max(val27,val33); val27 = tmp; tmp = std::min(val30,val36); val36 = std::max(val30,val36); val30 = tmp; tmp = std::min(val31,val37); val37 = std::max(val31,val37); val31 = tmp; tmp = std::min(val34,val40); val40 = std::max(val34,val40); val34 = tmp; tmp = std::min(val35,val41); val41 = std::max(val35,val41); val35 = tmp; tmp = std::min(val38,val44); val44 = std::max(val38,val44); val38 = tmp; tmp = std::min(val39,val45); val45 = std::max(val39,val45); val39 = tmp; tmp = std::min(val42,val48); val48 = std::max(val42,val48); val42 = tmp; tmp = std::min(val2,val4); val4 = std::max(val2,val4); val2 = tmp; tmp = std::min(val3,val5); val5 = std::max(val3,val5); val3 = tmp; tmp = std::min(val6,val8); val8 = std::max(val6,val8); val6 = tmp; tmp = std::min(val7,val9); val9 = std::max(val7,val9); val7 = tmp; tmp = std::min(val10,val12); val12 = std::max(val10,val12); val10 = tmp; tmp = std::min(val11,val13); val13 = std::max(val11,val13); val11 = tmp; tmp = std::min(val14,val16); val16 = std::max(val14,val16); val14 = tmp; tmp = std::min(val15,val17); val17 = std::max(val15,val17); val15 = tmp; tmp = std::min(val18,val20); val20 = std::max(val18,val20); val18 = tmp; tmp = std::min(val19,val21); val21 = std::max(val19,val21); val19 = tmp; tmp = std::min(val22,val24); val24 = std::max(val22,val24); val22 = tmp; tmp = std::min(val23,val25); val25 = std::max(val23,val25); val23 = tmp; tmp = std::min(val26,val28); val28 = std::max(val26,val28); val26 = tmp; tmp = std::min(val27,val29); val29 = std::max(val27,val29); val27 = tmp; tmp = std::min(val30,val32); val32 = std::max(val30,val32); val30 = tmp; tmp = std::min(val31,val33); val33 = std::max(val31,val33); val31 = tmp; tmp = std::min(val34,val36); val36 = std::max(val34,val36); val34 = tmp; tmp = std::min(val35,val37); val37 = std::max(val35,val37); val35 = tmp; tmp = std::min(val38,val40); val40 = std::max(val38,val40); val38 = tmp; tmp = std::min(val39,val41); val41 = std::max(val39,val41); val39 = tmp; tmp = std::min(val42,val44); val44 = std::max(val42,val44); val42 = tmp; tmp = std::min(val43,val45); val45 = std::max(val43,val45); val43 = tmp; tmp = std::min(val46,val48); val48 = std::max(val46,val48); val46 = tmp; val1 = std::max(val0,val1); val3 = std::max(val2,val3); val5 = std::max(val4,val5); val7 = std::max(val6,val7); val9 = std::max(val8,val9); val11 = std::max(val10,val11); val13 = std::max(val12,val13); val15 = std::max(val14,val15); val17 = std::max(val16,val17); val19 = std::max(val18,val19); val21 = std::max(val20,val21); val23 = std::max(val22,val23); val24 = std::min(val24,val25); val26 = std::min(val26,val27); val28 = std::min(val28,val29); val30 = std::min(val30,val31); val32 = std::min(val32,val33); val34 = std::min(val34,val35); val36 = std::min(val36,val37); val38 = std::min(val38,val39); val40 = std::min(val40,val41); val42 = std::min(val42,val43); val44 = std::min(val44,val45); val46 = std::min(val46,val47); val32 = std::max(val1,val32); val34 = std::max(val3,val34); val36 = std::max(val5,val36); val38 = std::max(val7,val38); val9 = std::min(val9,val40); val11 = std::min(val11,val42); val13 = std::min(val13,val44); val15 = std::min(val15,val46); val17 = std::min(val17,val48); val24 = std::max(val9,val24); val26 = std::max(val11,val26); val28 = std::max(val13,val28); val30 = std::max(val15,val30); val17 = std::min(val17,val32); val19 = std::min(val19,val34); val21 = std::min(val21,val36); val23 = std::min(val23,val38); val24 = std::max(val17,val24); val26 = std::max(val19,val26); val21 = std::min(val21,val28); val23 = std::min(val23,val30); val24 = std::max(val21,val24); val23 = std::min(val23,val26); return std::max(val23,val24); } //! Return sqrt(x^2 + y^2). template<typename T> inline T hypot(const T x, const T y) { return std::sqrt(x*x + y*y); } template<typename T> inline T hypot(const T x, const T y, const T z) { return std::sqrt(x*x + y*y + z*z); } template<typename T> inline T _hypot(const T x, const T y) { // Slower but more precise version T nx = cimg::abs(x), ny = cimg::abs(y), t; if (nx<ny) { t = nx; nx = ny; } else t = ny; if (nx>0) { t/=nx; return nx*std::sqrt(1 + t*t); } return 0; } //! Return the factorial of n inline double factorial(const int n) { if (n<0) return cimg::type<double>::nan(); if (n<2) return 1; double res = 2; for (int i = 3; i<=n; ++i) res*=i; return res; } //! Return the number of permutations of k objects in a set of n objects. inline double permutations(const int k, const int n, const bool with_order) { if (n<0 || k<0) return cimg::type<double>::nan(); if (k>n) return 0; double res = 1; for (int i = n; i>=n - k + 1; --i) res*=i; return with_order?res:res/cimg::factorial(k); } inline double _fibonacci(int exp) { double base = (1 + std::sqrt(5.))/2, result = 1/std::sqrt(5.); while (exp) { if (exp&1) result*=base; exp>>=1; base*=base; } return result; } //! Calculate fibonacci number. // (Precise up to n = 78, less precise for n>78). inline double fibonacci(const int n) { if (n<0) return cimg::type<double>::nan(); if (n<3) return 1; if (n<11) { cimg_uint64 fn1 = 1, fn2 = 1, fn = 0; for (int i = 3; i<=n; ++i) { fn = fn1 + fn2; fn2 = fn1; fn1 = fn; } return (double)fn; } if (n<75) // precise up to n = 74, faster than the integer calculation above for n>10 return (double)((cimg_uint64)(_fibonacci(n) + 0.5)); if (n<94) { // precise up to n = 78, less precise for n>78 up to n = 93, overflows for n>93 cimg_uint64 fn1 = (cimg_uint64)1304969544928657ULL, fn2 = (cimg_uint64)806515533049393ULL, fn = 0; for (int i = 75; i<=n; ++i) { fn = fn1 + fn2; fn2 = fn1; fn1 = fn; } return (double)fn; } return _fibonacci(n); // Not precise, but better than the wrong overflowing calculation } //! Calculate greatest common divisor. inline long gcd(long a, long b) { while (a) { const long c = a; a = b%a; b = c; } return b; } //! Convert Ascii character to lower case. inline char lowercase(const char x) { return (char)((x<'A'||x>'Z')?x:x - 'A' + 'a'); } inline double lowercase(const double x) { return (double)((x<'A'||x>'Z')?x:x - 'A' + 'a'); } //! Convert C-string to lower case. inline void lowercase(char *const str) { if (str) for (char *ptr = str; *ptr; ++ptr) *ptr = lowercase(*ptr); } //! Convert Ascii character to upper case. inline char uppercase(const char x) { return (char)((x<'a'||x>'z')?x:x - 'a' + 'A'); } inline double uppercase(const double x) { return (double)((x<'a'||x>'z')?x:x - 'a' + 'A'); } //! Convert C-string to upper case. inline void uppercase(char *const str) { if (str) for (char *ptr = str; *ptr; ++ptr) *ptr = uppercase(*ptr); } //! Return \c true if input character is blank (space, tab, or non-printable character). inline bool is_blank(const char c) { return c>=0 && c<=' '; } //! Read value in a C-string. /** \param str C-string containing the float value to read. \return Read value. \note Same as <tt>std::atof()</tt> extended to manage the retrieval of fractions from C-strings, as in <em>"1/2"</em>. **/ inline double atof(const char *const str) { double x = 0, y = 1; return str && cimg_sscanf(str,"%lf/%lf",&x,&y)>0?x/y:0; } //! Compare the first \p l characters of two C-strings, ignoring the case. /** \param str1 C-string. \param str2 C-string. \param l Number of characters to compare. \return \c 0 if the two strings are equal, something else otherwise. \note This function has to be defined since it is not provided by all C++-compilers (not ANSI). **/ inline int strncasecmp(const char *const str1, const char *const str2, const int l) { if (!l) return 0; if (!str1) return str2?-1:0; const char *nstr1 = str1, *nstr2 = str2; int k, diff = 0; for (k = 0; k<l && !(diff = lowercase(*nstr1) - lowercase(*nstr2)); ++k) { ++nstr1; ++nstr2; } return k!=l?diff:0; } //! Compare two C-strings, ignoring the case. /** \param str1 C-string. \param str2 C-string. \return \c 0 if the two strings are equal, something else otherwise. \note This function has to be defined since it is not provided by all C++-compilers (not ANSI). **/ inline int strcasecmp(const char *const str1, const char *const str2) { if (!str1) return str2?-1:0; const int l1 = (int)std::strlen(str1), l2 = (int)std::strlen(str2); return cimg::strncasecmp(str1,str2,1 + (l1<l2?l1:l2)); } //! Ellipsize a string. /** \param str C-string. \param l Max number of characters. \param is_ending Tell if the dots are placed at the end or at the center of the ellipsized string. **/ inline char *strellipsize(char *const str, const unsigned int l=64, const bool is_ending=true) { if (!str) return str; const unsigned int nl = l<5?5:l, ls = (unsigned int)std::strlen(str); if (ls<=nl) return str; if (is_ending) std::strcpy(str + nl - 5,"(...)"); else { const unsigned int ll = (nl - 5)/2 + 1 - (nl%2), lr = nl - ll - 5; std::strcpy(str + ll,"(...)"); std::memmove(str + ll + 5,str + ls - lr,lr); } str[nl] = 0; return str; } //! Ellipsize a string. /** \param str C-string. \param res output C-string. \param l Max number of characters. \param is_ending Tell if the dots are placed at the end or at the center of the ellipsized string. **/ inline char *strellipsize(const char *const str, char *const res, const unsigned int l=64, const bool is_ending=true) { const unsigned int nl = l<5?5:l, ls = (unsigned int)std::strlen(str); if (ls<=nl) { std::strcpy(res,str); return res; } if (is_ending) { std::strncpy(res,str,nl - 5); std::strcpy(res + nl -5,"(...)"); } else { const unsigned int ll = (nl - 5)/2 + 1 - (nl%2), lr = nl - ll - 5; std::strncpy(res,str,ll); std::strcpy(res + ll,"(...)"); std::strncpy(res + ll + 5,str + ls - lr,lr); } res[nl] = 0; return res; } //! Remove delimiters on the start and/or end of a C-string. /** \param[in,out] str C-string to work with (modified at output). \param delimiter Delimiter character code to remove. \param is_symmetric Tells if the removal is done only if delimiters are symmetric (both at the beginning and the end of \c s). \param is_iterative Tells if the removal is done if several iterations are possible. \return \c true if delimiters have been removed, \c false otherwise. **/ inline bool strpare(char *const str, const char delimiter, const bool is_symmetric, const bool is_iterative) { if (!str) return false; const int l = (int)std::strlen(str); int p, q; if (is_symmetric) for (p = 0, q = l - 1; p<q && str[p]==delimiter && str[q]==delimiter; ) { --q; ++p; if (!is_iterative) break; } else { for (p = 0; p<l && str[p]==delimiter; ) { ++p; if (!is_iterative) break; } for (q = l - 1; q>p && str[q]==delimiter; ) { --q; if (!is_iterative) break; } } const int n = q - p + 1; if (n!=l) { std::memmove(str,str + p,(unsigned int)n); str[n] = 0; return true; } return false; } //! Remove white spaces on the start and/or end of a C-string. inline bool strpare(char *const str, const bool is_symmetric, const bool is_iterative) { if (!str) return false; const int l = (int)std::strlen(str); int p, q; if (is_symmetric) for (p = 0, q = l - 1; p<q && is_blank(str[p]) && is_blank(str[q]); ) { --q; ++p; if (!is_iterative) break; } else { for (p = 0; p<l && is_blank(str[p]); ) { ++p; if (!is_iterative) break; } for (q = l - 1; q>p && is_blank(str[q]); ) { --q; if (!is_iterative) break; } } const int n = q - p + 1; if (n!=l) { std::memmove(str,str + p,(unsigned int)n); str[n] = 0; return true; } return false; } //! Replace reserved characters (for Windows filename) by another character. /** \param[in,out] str C-string to work with (modified at output). \param[in] c Replacement character. **/ inline void strwindows_reserved(char *const str, const char c='_') { for (char *s = str; *s; ++s) { const char i = *s; if (i=='<' || i=='>' || i==':' || i=='\"' || i=='/' || i=='\\' || i=='|' || i=='?' || i=='*') *s = c; } } //! Replace escape sequences in C-strings by their binary Ascii values. /** \param[in,out] str C-string to work with (modified at output). **/ inline void strunescape(char *const str) { #define cimg_strunescape(ci,co) case ci : *nd = co; ++ns; break; unsigned int val = 0; for (char *ns = str, *nd = str; *ns || (bool)(*nd=0); ++nd) if (*ns=='\\') switch (*(++ns)) { cimg_strunescape('a','\a'); cimg_strunescape('b','\b'); cimg_strunescape('e',0x1B); cimg_strunescape('f','\f'); cimg_strunescape('n','\n'); cimg_strunescape('r','\r'); cimg_strunescape('t','\t'); cimg_strunescape('v','\v'); cimg_strunescape('\\','\\'); cimg_strunescape('\'','\''); cimg_strunescape('\"','\"'); cimg_strunescape('\?','\?'); case 0 : *nd = 0; break; case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : cimg_sscanf(ns,"%o",&val); while (*ns>='0' && *ns<='7') ++ns; *nd = (char)val; break; case 'x' : cimg_sscanf(++ns,"%x",&val); while ((*ns>='0' && *ns<='9') || (*ns>='a' && *ns<='f') || (*ns>='A' && *ns<='F')) ++ns; *nd = (char)val; break; default : *nd = *(ns++); } else *nd = *(ns++); } // Return a temporary string describing the size of a memory buffer. inline const char *strbuffersize(const cimg_ulong size); // Return string that identifies the running OS. inline const char *stros() { #if defined(linux) || defined(__linux) || defined(__linux__) static const char *const str = "Linux"; #elif defined(sun) || defined(__sun) static const char *const str = "Sun OS"; #elif defined(BSD) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__) || defined (__DragonFly__) static const char *const str = "BSD"; #elif defined(sgi) || defined(__sgi) static const char *const str = "Irix"; #elif defined(__MACOSX__) || defined(__APPLE__) static const char *const str = "Mac OS"; #elif defined(unix) || defined(__unix) || defined(__unix__) static const char *const str = "Generic Unix"; #elif defined(_MSC_VER) || defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || \ defined(WIN64) || defined(_WIN64) || defined(__WIN64__) static const char *const str = "Windows"; #else const char *const _str1 = std::getenv("OSTYPE"), *const _str2 = _str1?_str1:std::getenv("OS"), *const str = _str2?_str2:"Unknown OS"; #endif return str; } //! Return the basename of a filename. inline const char* basename(const char *const s, const char separator=cimg_file_separator) { const char *p = 0, *np = s; while (np>=s && (p=np)) np = std::strchr(np,separator) + 1; return p; } // Return a random filename. inline const char* filenamerand() { cimg::mutex(6); static char randomid[9]; for (unsigned int k = 0; k<8; ++k) { const int v = (int)cimg::rand(65535)%3; randomid[k] = (char)(v==0?('0' + ((int)cimg::rand(65535)%10)): (v==1?('a' + ((int)cimg::rand(65535)%26)): ('A' + ((int)cimg::rand(65535)%26)))); } cimg::mutex(6,0); return randomid; } // Convert filename as a Windows-style filename (short path name). inline void winformat_string(char *const str) { if (str && *str) { #if cimg_OS==2 char *const nstr = new char[MAX_PATH]; if (GetShortPathNameA(str,nstr,MAX_PATH)) std::strcpy(str,nstr); delete[] nstr; #endif } } // Open a file (similar to std:: fopen(), but with wide character support on Windows). inline std::FILE *std_fopen(const char *const path, const char *const mode); //! Open a file. /** \param path Path of the filename to open. \param mode C-string describing the opening mode. \return Opened file. \note Same as <tt>std::fopen()</tt> but throw a \c CImgIOException when the specified file cannot be opened, instead of returning \c 0. **/ inline std::FILE *fopen(const char *const path, const char *const mode) { if (!path) throw CImgArgumentException("cimg::fopen(): Specified file path is (null)."); if (!mode) throw CImgArgumentException("cimg::fopen(): File '%s', specified mode is (null).", path); std::FILE *res = 0; if (*path=='-' && (!path[1] || path[1]=='.')) { res = (*mode=='r')?cimg::_stdin():cimg::_stdout(); #if cimg_OS==2 if (*mode && mode[1]=='b') { // Force stdin/stdout to be in binary mode #ifdef __BORLANDC__ if (setmode(_fileno(res),0x8000)==-1) res = 0; #else if (_setmode(_fileno(res),0x8000)==-1) res = 0; #endif } #endif } else res = cimg::std_fopen(path,mode); if (!res) throw CImgIOException("cimg::fopen(): Failed to open file '%s' with mode '%s'.", path,mode); return res; } //! Close a file. /** \param file File to close. \return \c 0 if file has been closed properly, something else otherwise. \note Same as <tt>std::fclose()</tt> but display a warning message if the file has not been closed properly. **/ inline int fclose(std::FILE *file) { if (!file) { warn("cimg::fclose(): Specified file is (null)."); return 0; } if (file==cimg::_stdin(false) || file==cimg::_stdout(false)) return 0; const int errn = std::fclose(file); if (errn!=0) warn("cimg::fclose(): Error code %d returned during file closing.", errn); return errn; } //! Version of 'fseek()' that supports >=64bits offsets everywhere (for Windows). inline int fseek(FILE *stream, cimg_long offset, int origin) { #if defined(WIN64) || defined(_WIN64) || defined(__WIN64__) return _fseeki64(stream,(__int64)offset,origin); #else return std::fseek(stream,offset,origin); #endif } //! Version of 'ftell()' that supports >=64bits offsets everywhere (for Windows). inline cimg_long ftell(FILE *stream) { #if defined(WIN64) || defined(_WIN64) || defined(__WIN64__) return (cimg_long)_ftelli64(stream); #else return (cimg_long)std::ftell(stream); #endif } //! Check if a path is a directory. /** \param path Specified path to test. **/ inline bool is_directory(const char *const path) { if (!path || !*path) return false; #if cimg_OS==1 struct stat st_buf; return (!stat(path,&st_buf) && S_ISDIR(st_buf.st_mode)); #elif cimg_OS==2 const unsigned int res = (unsigned int)GetFileAttributesA(path); return res==INVALID_FILE_ATTRIBUTES?false:(res&16); #else return false; #endif } //! Check if a path is a file. /** \param path Specified path to test. **/ inline bool is_file(const char *const path) { if (!path || !*path) return false; std::FILE *const file = cimg::std_fopen(path,"rb"); if (!file) return false; cimg::fclose(file); return !is_directory(path); } //! Get file size. /** \param filename Specified filename to get size from. \return File size or '-1' if file does not exist. **/ inline cimg_int64 fsize(const char *const filename) { std::FILE *const file = cimg::std_fopen(filename,"rb"); if (!file) return (cimg_int64)-1; std::fseek(file,0,SEEK_END); const cimg_int64 siz = (cimg_int64)std::ftell(file); cimg::fclose(file); return siz; } //! Get last write time of a given file or directory (multiple-attributes version). /** \param path Specified path to get attributes from. \param[in,out] attr Type of requested time attributes. Can be { 0=year | 1=month | 2=day | 3=day of week | 4=hour | 5=minute | 6=second } Replaced by read attributes after return (or -1 if an error occured). \param nb_attr Number of attributes to read/write. \return Latest read attribute. **/ template<typename T> inline int fdate(const char *const path, T *attr, const unsigned int nb_attr) { #define _cimg_fdate_err() for (unsigned int i = 0; i<nb_attr; ++i) attr[i] = (T)-1 int res = -1; if (!path || !*path) { _cimg_fdate_err(); return -1; } cimg::mutex(6); #if cimg_OS==2 HANDLE file = CreateFileA(path,GENERIC_READ,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0); if (file!=INVALID_HANDLE_VALUE) { FILETIME _ft; SYSTEMTIME ft; if (GetFileTime(file,0,0,&_ft) && FileTimeToSystemTime(&_ft,&ft)) { for (unsigned int i = 0; i<nb_attr; ++i) { res = (int)(attr[i]==0?ft.wYear:attr[i]==1?ft.wMonth:attr[i]==2?ft.wDay: attr[i]==3?ft.wDayOfWeek:attr[i]==4?ft.wHour:attr[i]==5?ft.wMinute: attr[i]==6?ft.wSecond:-1); attr[i] = (T)res; } } else _cimg_fdate_err(); CloseHandle(file); } else _cimg_fdate_err(); #elif cimg_OS==1 struct stat st_buf; if (!stat(path,&st_buf)) { const time_t _ft = st_buf.st_mtime; const struct tm& ft = *std::localtime(&_ft); for (unsigned int i = 0; i<nb_attr; ++i) { res = (int)(attr[i]==0?ft.tm_year + 1900:attr[i]==1?ft.tm_mon + 1:attr[i]==2?ft.tm_mday: attr[i]==3?ft.tm_wday:attr[i]==4?ft.tm_hour:attr[i]==5?ft.tm_min: attr[i]==6?ft.tm_sec:-1); attr[i] = (T)res; } } else _cimg_fdate_err(); #endif cimg::mutex(6,0); return res; } //! Get last write time of a given file or directory (single-attribute version). /** \param path Specified path to get attributes from. \param attr Type of requested time attributes. Can be { 0=year | 1=month | 2=day | 3=day of week | 4=hour | 5=minute | 6=second } \return Specified attribute or -1 if an error occured. **/ inline int fdate(const char *const path, unsigned int attr) { int out = (int)attr; return fdate(path,&out,1); } //! Get current local time (multiple-attributes version). /** \param[in,out] attr Type of requested time attributes. Can be { 0=year | 1=month | 2=day | 3=day of week | 4=hour | 5=minute | 6=second } Replaced by read attributes after return (or -1 if an error occured). \param nb_attr Number of attributes to read/write. \return Latest read attribute. **/ template<typename T> inline int date(T *attr, const unsigned int nb_attr) { int res = -1; cimg::mutex(6); #if cimg_OS==2 SYSTEMTIME st; GetLocalTime(&st); for (unsigned int i = 0; i<nb_attr; ++i) { res = (int)(attr[i]==0?st.wYear:attr[i]==1?st.wMonth:attr[i]==2?st.wDay: attr[i]==3?st.wDayOfWeek:attr[i]==4?st.wHour:attr[i]==5?st.wMinute: attr[i]==6?st.wSecond:-1); attr[i] = (T)res; } #else time_t _st; std::time(&_st); struct tm *st = std::localtime(&_st); for (unsigned int i = 0; i<nb_attr; ++i) { res = (int)(attr[i]==0?st->tm_year + 1900:attr[i]==1?st->tm_mon + 1:attr[i]==2?st->tm_mday: attr[i]==3?st->tm_wday:attr[i]==4?st->tm_hour:attr[i]==5?st->tm_min: attr[i]==6?st->tm_sec:-1); attr[i] = (T)res; } #endif cimg::mutex(6,0); return res; } //! Get current local time (single-attribute version). /** \param attr Type of requested time attribute. Can be { 0=year | 1=month | 2=day | 3=day of week | 4=hour | 5=minute | 6=second } \return Specified attribute or -1 if an error occured. **/ inline int date(unsigned int attr) { int out = (int)attr; return date(&out,1); } // Get/set path to store temporary files. inline const char* temporary_path(const char *const user_path=0, const bool reinit_path=false); // Get/set path to the <i>Program Files/</i> directory (Windows only). #if cimg_OS==2 inline const char* programfiles_path(const char *const user_path=0, const bool reinit_path=false); #endif // Get/set path to the ImageMagick's \c convert binary. inline const char* imagemagick_path(const char *const user_path=0, const bool reinit_path=false); // Get/set path to the GraphicsMagick's \c gm binary. inline const char* graphicsmagick_path(const char *const user_path=0, const bool reinit_path=false); // Get/set path to the XMedcon's \c medcon binary. inline const char* medcon_path(const char *const user_path=0, const bool reinit_path=false); // Get/set path to the FFMPEG's \c ffmpeg binary. inline const char *ffmpeg_path(const char *const user_path=0, const bool reinit_path=false); // Get/set path to the \c gzip binary. inline const char *gzip_path(const char *const user_path=0, const bool reinit_path=false); // Get/set path to the \c gunzip binary. inline const char *gunzip_path(const char *const user_path=0, const bool reinit_path=false); // Get/set path to the \c dcraw binary. inline const char *dcraw_path(const char *const user_path=0, const bool reinit_path=false); // Get/set path to the \c wget binary. inline const char *wget_path(const char *const user_path=0, const bool reinit_path=false); // Get/set path to the \c curl binary. inline const char *curl_path(const char *const user_path=0, const bool reinit_path=false); //! Split filename into two C-strings \c body and \c extension. /** filename and body must not overlap! **/ inline const char *split_filename(const char *const filename, char *const body=0) { if (!filename) { if (body) *body = 0; return 0; } const char *p = 0; for (const char *np = filename; np>=filename && (p=np); np = std::strchr(np,'.') + 1) {} if (p==filename || std::strchr(p,'/') || std::strchr(p,'\\')) { if (body) std::strcpy(body,filename); return filename + std::strlen(filename); } const unsigned int l = (unsigned int)(p - filename - 1); if (body) { if (l) std::memcpy(body,filename,l); body[l] = 0; } return p; } //! Generate a numbered version of a filename. inline char* number_filename(const char *const filename, const int number, const unsigned int digits, char *const str) { if (!filename) { if (str) *str = 0; return 0; } char *const format = new char[1024], *const body = new char[1024]; const char *const ext = cimg::split_filename(filename,body); if (*ext) cimg_snprintf(format,1024,"%%s_%%.%ud.%%s",digits); else cimg_snprintf(format,1024,"%%s_%%.%ud",digits); cimg_sprintf(str,format,body,number,ext); delete[] format; delete[] body; return str; } //! Read data from file. /** \param[out] ptr Pointer to memory buffer that will contain the binary data read from file. \param nmemb Number of elements to read. \param stream File to read data from. \return Number of read elements. \note Same as <tt>std::fread()</tt> but may display warning message if all elements could not be read. **/ template<typename T> inline size_t fread(T *const ptr, const size_t nmemb, std::FILE *stream) { if (!ptr || !stream) throw CImgArgumentException("cimg::fread(): Invalid reading request of %u %s%s from file %p to buffer %p.", nmemb,cimg::type<T>::string(),nmemb>1?"s":"",stream,ptr); if (!nmemb) return 0; const size_t wlimitT = 63*1024*1024, wlimit = wlimitT/sizeof(T); size_t to_read = nmemb, al_read = 0, l_to_read = 0, l_al_read = 0; do { l_to_read = (to_read*sizeof(T))<wlimitT?to_read:wlimit; l_al_read = std::fread((void*)(ptr + al_read),sizeof(T),l_to_read,stream); al_read+=l_al_read; to_read-=l_al_read; } while (l_to_read==l_al_read && to_read>0); if (to_read>0) warn("cimg::fread(): Only %lu/%lu elements could be read from file.", (unsigned long)al_read,(unsigned long)nmemb); return al_read; } //! Write data to file. /** \param ptr Pointer to memory buffer containing the binary data to write on file. \param nmemb Number of elements to write. \param[out] stream File to write data on. \return Number of written elements. \note Similar to <tt>std::fwrite</tt> but may display warning messages if all elements could not be written. **/ template<typename T> inline size_t fwrite(const T *ptr, const size_t nmemb, std::FILE *stream) { if (!ptr || !stream) throw CImgArgumentException("cimg::fwrite(): Invalid writing request of %u %s%s from buffer %p to file %p.", nmemb,cimg::type<T>::string(),nmemb>1?"s":"",ptr,stream); if (!nmemb) return 0; const size_t wlimitT = 63*1024*1024, wlimit = wlimitT/sizeof(T); size_t to_write = nmemb, al_write = 0, l_to_write = 0, l_al_write = 0; do { l_to_write = (to_write*sizeof(T))<wlimitT?to_write:wlimit; l_al_write = std::fwrite((void*)(ptr + al_write),sizeof(T),l_to_write,stream); al_write+=l_al_write; to_write-=l_al_write; } while (l_to_write==l_al_write && to_write>0); if (to_write>0) warn("cimg::fwrite(): Only %lu/%lu elements could be written in file.", (unsigned long)al_write,(unsigned long)nmemb); return al_write; } //! Create an empty file. /** \param file Input file (can be \c 0 if \c filename is set). \param filename Filename, as a C-string (can be \c 0 if \c file is set). **/ inline void fempty(std::FILE *const file, const char *const filename) { if (!file && !filename) throw CImgArgumentException("cimg::fempty(): Specified filename is (null)."); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); if (!file) cimg::fclose(nfile); } // Try to guess format from an image file. inline const char *ftype(std::FILE *const file, const char *const filename); // Load file from network as a local temporary file. inline char *load_network(const char *const url, char *const filename_local, const unsigned int timeout=0, const bool try_fallback=false, const char *const referer=0); //! Return options specified on the command line. inline const char* option(const char *const name, const int argc, const char *const *const argv, const char *const defaut, const char *const usage, const bool reset_static) { static bool first = true, visu = false; if (reset_static) { first = true; return 0; } const char *res = 0; if (first) { first = false; visu = cimg::option("-h",argc,argv,(char*)0,(char*)0,false)!=0; visu |= cimg::option("-help",argc,argv,(char*)0,(char*)0,false)!=0; visu |= cimg::option("--help",argc,argv,(char*)0,(char*)0,false)!=0; } if (!name && visu) { if (usage) { std::fprintf(cimg::output(),"\n %s%s%s",cimg::t_red,cimg::basename(argv[0]),cimg::t_normal); std::fprintf(cimg::output(),": %s",usage); std::fprintf(cimg::output()," (%s, %s)\n\n",cimg_date,cimg_time); } if (defaut) std::fprintf(cimg::output(),"%s\n",defaut); } if (name) { if (argc>0) { int k = 0; while (k<argc && std::strcmp(argv[k],name)) ++k; res = (k++==argc?defaut:(k==argc?argv[--k]:argv[k])); } else res = defaut; if (visu && usage) std::fprintf(cimg::output()," %s%-16s%s %-24s %s%s%s\n", cimg::t_bold,name,cimg::t_normal,res?res:"0", cimg::t_green,usage,cimg::t_normal); } return res; } inline const char* option(const char *const name, const int argc, const char *const *const argv, const char *const defaut, const char *const usage=0) { return option(name,argc,argv,defaut,usage,false); } inline bool option(const char *const name, const int argc, const char *const *const argv, const bool defaut, const char *const usage=0) { const char *const s = cimg::option(name,argc,argv,(char*)0); const bool res = s?(cimg::strcasecmp(s,"false") && cimg::strcasecmp(s,"off") && cimg::strcasecmp(s,"0")):defaut; cimg::option(name,0,0,res?"true":"false",usage); return res; } inline int option(const char *const name, const int argc, const char *const *const argv, const int defaut, const char *const usage=0) { const char *const s = cimg::option(name,argc,argv,(char*)0); const int res = s?std::atoi(s):defaut; char *const tmp = new char[256]; cimg_snprintf(tmp,256,"%d",res); cimg::option(name,0,0,tmp,usage); delete[] tmp; return res; } inline char option(const char *const name, const int argc, const char *const *const argv, const char defaut, const char *const usage=0) { const char *const s = cimg::option(name,argc,argv,(char*)0); const char res = s?*s:defaut; char tmp[8]; *tmp = res; tmp[1] = 0; cimg::option(name,0,0,tmp,usage); return res; } inline float option(const char *const name, const int argc, const char *const *const argv, const float defaut, const char *const usage=0) { const char *const s = cimg::option(name,argc,argv,(char*)0); const float res = s?(float)cimg::atof(s):defaut; char *const tmp = new char[256]; cimg_snprintf(tmp,256,"%g",res); cimg::option(name,0,0,tmp,usage); delete[] tmp; return res; } inline double option(const char *const name, const int argc, const char *const *const argv, const double defaut, const char *const usage=0) { const char *const s = cimg::option(name,argc,argv,(char*)0); const double res = s?cimg::atof(s):defaut; char *const tmp = new char[256]; cimg_snprintf(tmp,256,"%g",res); cimg::option(name,0,0,tmp,usage); delete[] tmp; return res; } //! Print information about \CImg environement variables. /** \note Output is done on the default output stream. **/ inline void info() { std::fprintf(cimg::output(),"\n %s%sCImg Library %u.%u.%u%s, compiled %s ( %s ) with the following flags:\n\n", cimg::t_red,cimg::t_bold,cimg_version/100,(cimg_version/10)%10,cimg_version%10, cimg::t_normal,cimg_date,cimg_time); std::fprintf(cimg::output()," > Operating System: %s%-13s%s %s('cimg_OS'=%d)%s\n", cimg::t_bold, cimg_OS==1?"Unix":(cimg_OS==2?"Windows":"Unknow"), cimg::t_normal,cimg::t_green, cimg_OS, cimg::t_normal); std::fprintf(cimg::output()," > CPU endianness: %s%s Endian%s\n", cimg::t_bold, cimg::endianness()?"Big":"Little", cimg::t_normal); std::fprintf(cimg::output()," > Verbosity mode: %s%-13s%s %s('cimg_verbosity'=%d)%s\n", cimg::t_bold, cimg_verbosity==0?"Quiet": cimg_verbosity==1?"Console": cimg_verbosity==2?"Dialog": cimg_verbosity==3?"Console+Warnings":"Dialog+Warnings", cimg::t_normal,cimg::t_green, cimg_verbosity, cimg::t_normal); std::fprintf(cimg::output()," > Stricts warnings: %s%-13s%s %s('cimg_strict_warnings' %s)%s\n", cimg::t_bold, #ifdef cimg_strict_warnings "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); std::fprintf(cimg::output()," > Support for C++11: %s%-13s%s %s('cimg_use_cpp11'=%d)%s\n", cimg::t_bold, cimg_use_cpp11?"Yes":"No", cimg::t_normal,cimg::t_green, (int)cimg_use_cpp11, cimg::t_normal); std::fprintf(cimg::output()," > Using VT100 messages: %s%-13s%s %s('cimg_use_vt100' %s)%s\n", cimg::t_bold, #ifdef cimg_use_vt100 "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); std::fprintf(cimg::output()," > Display type: %s%-13s%s %s('cimg_display'=%d)%s\n", cimg::t_bold, cimg_display==0?"No display":cimg_display==1?"X11":cimg_display==2?"Windows GDI":"Unknown", cimg::t_normal,cimg::t_green, (int)cimg_display, cimg::t_normal); #if cimg_display==1 std::fprintf(cimg::output()," > Using XShm for X11: %s%-13s%s %s('cimg_use_xshm' %s)%s\n", cimg::t_bold, #ifdef cimg_use_xshm "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); std::fprintf(cimg::output()," > Using XRand for X11: %s%-13s%s %s('cimg_use_xrandr' %s)%s\n", cimg::t_bold, #ifdef cimg_use_xrandr "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); #endif std::fprintf(cimg::output()," > Using OpenMP: %s%-13s%s %s('cimg_use_openmp' %s)%s\n", cimg::t_bold, #if cimg_use_openmp!=0 "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); std::fprintf(cimg::output()," > Using PNG library: %s%-13s%s %s('cimg_use_png' %s)%s\n", cimg::t_bold, #ifdef cimg_use_png "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); std::fprintf(cimg::output()," > Using JPEG library: %s%-13s%s %s('cimg_use_jpeg' %s)%s\n", cimg::t_bold, #ifdef cimg_use_jpeg "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); std::fprintf(cimg::output()," > Using TIFF library: %s%-13s%s %s('cimg_use_tiff' %s)%s\n", cimg::t_bold, #ifdef cimg_use_tiff "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); std::fprintf(cimg::output()," > Using Magick++ library: %s%-13s%s %s('cimg_use_magick' %s)%s\n", cimg::t_bold, #ifdef cimg_use_magick "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); std::fprintf(cimg::output()," > Using FFTW3 library: %s%-13s%s %s('cimg_use_fftw3' %s)%s\n", cimg::t_bold, #ifdef cimg_use_fftw3 "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); std::fprintf(cimg::output()," > Using LAPACK library: %s%-13s%s %s('cimg_use_lapack' %s)%s\n", cimg::t_bold, #ifdef cimg_use_lapack "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); char *const tmp = new char[1024]; cimg_snprintf(tmp,1024,"\"%.1020s\"",cimg::imagemagick_path()); std::fprintf(cimg::output()," > Path of ImageMagick: %s%-13s%s\n", cimg::t_bold, tmp, cimg::t_normal); cimg_snprintf(tmp,1024,"\"%.1020s\"",cimg::graphicsmagick_path()); std::fprintf(cimg::output()," > Path of GraphicsMagick: %s%-13s%s\n", cimg::t_bold, tmp, cimg::t_normal); cimg_snprintf(tmp,1024,"\"%.1020s\"",cimg::medcon_path()); std::fprintf(cimg::output()," > Path of 'medcon': %s%-13s%s\n", cimg::t_bold, tmp, cimg::t_normal); cimg_snprintf(tmp,1024,"\"%.1020s\"",cimg::temporary_path()); std::fprintf(cimg::output()," > Temporary path: %s%-13s%s\n", cimg::t_bold, tmp, cimg::t_normal); std::fprintf(cimg::output(),"\n"); delete[] tmp; } // Declare LAPACK function signatures if LAPACK support is enabled. #ifdef cimg_use_lapack template<typename T> inline void getrf(int &N, T *lapA, int *IPIV, int &INFO) { dgetrf_(&N,&N,lapA,&N,IPIV,&INFO); } inline void getrf(int &N, float *lapA, int *IPIV, int &INFO) { sgetrf_(&N,&N,lapA,&N,IPIV,&INFO); } template<typename T> inline void getri(int &N, T *lapA, int *IPIV, T* WORK, int &LWORK, int &INFO) { dgetri_(&N,lapA,&N,IPIV,WORK,&LWORK,&INFO); } inline void getri(int &N, float *lapA, int *IPIV, float* WORK, int &LWORK, int &INFO) { sgetri_(&N,lapA,&N,IPIV,WORK,&LWORK,&INFO); } template<typename T> inline void gesvd(char &JOB, int &M, int &N, T *lapA, int &MN, T *lapS, T *lapU, T *lapV, T *WORK, int &LWORK, int &INFO) { dgesvd_(&JOB,&JOB,&M,&N,lapA,&MN,lapS,lapU,&M,lapV,&N,WORK,&LWORK,&INFO); } inline void gesvd(char &JOB, int &M, int &N, float *lapA, int &MN, float *lapS, float *lapU, float *lapV, float *WORK, int &LWORK, int &INFO) { sgesvd_(&JOB,&JOB,&M,&N,lapA,&MN,lapS,lapU,&M,lapV,&N,WORK,&LWORK,&INFO); } template<typename T> inline void getrs(char &TRANS, int &N, T *lapA, int *IPIV, T *lapB, int &INFO) { int one = 1; dgetrs_(&TRANS,&N,&one,lapA,&N,IPIV,lapB,&N,&INFO); } inline void getrs(char &TRANS, int &N, float *lapA, int *IPIV, float *lapB, int &INFO) { int one = 1; sgetrs_(&TRANS,&N,&one,lapA,&N,IPIV,lapB,&N,&INFO); } template<typename T> inline void syev(char &JOB, char &UPLO, int &N, T *lapA, T *lapW, T *WORK, int &LWORK, int &INFO) { dsyev_(&JOB,&UPLO,&N,lapA,&N,lapW,WORK,&LWORK,&INFO); } inline void syev(char &JOB, char &UPLO, int &N, float *lapA, float *lapW, float *WORK, int &LWORK, int &INFO) { ssyev_(&JOB,&UPLO,&N,lapA,&N,lapW,WORK,&LWORK,&INFO); } template<typename T> inline void sgels(char & TRANS, int &M, int &N, int &NRHS, T* lapA, int &LDA, T* lapB, int &LDB, T* WORK, int &LWORK, int &INFO){ dgels_(&TRANS, &M, &N, &NRHS, lapA, &LDA, lapB, &LDB, WORK, &LWORK, &INFO); } inline void sgels(char & TRANS, int &M, int &N, int &NRHS, float* lapA, int &LDA, float* lapB, int &LDB, float* WORK, int &LWORK, int &INFO){ sgels_(&TRANS, &M, &N, &NRHS, lapA, &LDA, lapB, &LDB, WORK, &LWORK, &INFO); } #endif } // namespace cimg { ... /*------------------------------------------------ # # # Definition of mathematical operators and # external functions. # # -------------------------------------------------*/ #define _cimg_create_ext_operators(typ) \ template<typename T> \ inline CImg<typename cimg::superset<T,typ>::type> operator+(const typ val, const CImg<T>& img) { \ return img + val; \ } \ template<typename T> \ inline CImg<typename cimg::superset<T,typ>::type> operator-(const typ val, const CImg<T>& img) { \ typedef typename cimg::superset<T,typ>::type Tt; \ return CImg<Tt>(img._width,img._height,img._depth,img._spectrum,val)-=img; \ } \ template<typename T> \ inline CImg<typename cimg::superset<T,typ>::type> operator*(const typ val, const CImg<T>& img) { \ return img*val; \ } \ template<typename T> \ inline CImg<typename cimg::superset<T,typ>::type> operator/(const typ val, const CImg<T>& img) { \ return val*img.get_invert(); \ } \ template<typename T> \ inline CImg<typename cimg::superset<T,typ>::type> operator&(const typ val, const CImg<T>& img) { \ return img & val; \ } \ template<typename T> \ inline CImg<typename cimg::superset<T,typ>::type> operator|(const typ val, const CImg<T>& img) { \ return img | val; \ } \ template<typename T> \ inline CImg<typename cimg::superset<T,typ>::type> operator^(const typ val, const CImg<T>& img) { \ return img ^ val; \ } \ template<typename T> \ inline bool operator==(const typ val, const CImg<T>& img) { \ return img == val; \ } \ template<typename T> \ inline bool operator!=(const typ val, const CImg<T>& img) { \ return img != val; \ } _cimg_create_ext_operators(bool) _cimg_create_ext_operators(unsigned char) _cimg_create_ext_operators(char) _cimg_create_ext_operators(signed char) _cimg_create_ext_operators(unsigned short) _cimg_create_ext_operators(short) _cimg_create_ext_operators(unsigned int) _cimg_create_ext_operators(int) _cimg_create_ext_operators(cimg_uint64) _cimg_create_ext_operators(cimg_int64) _cimg_create_ext_operators(float) _cimg_create_ext_operators(double) _cimg_create_ext_operators(long double) template<typename T> inline CImg<_cimg_Tfloat> operator+(const char *const expression, const CImg<T>& img) { return img + expression; } template<typename T> inline CImg<_cimg_Tfloat> operator-(const char *const expression, const CImg<T>& img) { return CImg<_cimg_Tfloat>(img,false).fill(expression,true)-=img; } template<typename T> inline CImg<_cimg_Tfloat> operator*(const char *const expression, const CImg<T>& img) { return img*expression; } template<typename T> inline CImg<_cimg_Tfloat> operator/(const char *const expression, const CImg<T>& img) { return expression*img.get_invert(); } template<typename T> inline CImg<T> operator&(const char *const expression, const CImg<T>& img) { return img & expression; } template<typename T> inline CImg<T> operator|(const char *const expression, const CImg<T>& img) { return img | expression; } template<typename T> inline CImg<T> operator^(const char *const expression, const CImg<T>& img) { return img ^ expression; } template<typename T> inline bool operator==(const char *const expression, const CImg<T>& img) { return img==expression; } template<typename T> inline bool operator!=(const char *const expression, const CImg<T>& img) { return img!=expression; } template<typename T> inline CImg<T> transpose(const CImg<T>& instance) { return instance.get_transpose(); } template<typename T> inline CImg<_cimg_Tfloat> invert(const CImg<T>& instance) { return instance.get_invert(); } template<typename T> inline CImg<_cimg_Tfloat> pseudoinvert(const CImg<T>& instance) { return instance.get_pseudoinvert(); } #define _cimg_create_ext_pointwise_function(name) \ template<typename T> \ inline CImg<_cimg_Tfloat> name(const CImg<T>& instance) { \ return instance.get_##name(); \ } _cimg_create_ext_pointwise_function(sqr) _cimg_create_ext_pointwise_function(sqrt) _cimg_create_ext_pointwise_function(exp) _cimg_create_ext_pointwise_function(log) _cimg_create_ext_pointwise_function(log2) _cimg_create_ext_pointwise_function(log10) _cimg_create_ext_pointwise_function(abs) _cimg_create_ext_pointwise_function(sign) _cimg_create_ext_pointwise_function(cos) _cimg_create_ext_pointwise_function(sin) _cimg_create_ext_pointwise_function(sinc) _cimg_create_ext_pointwise_function(tan) _cimg_create_ext_pointwise_function(acos) _cimg_create_ext_pointwise_function(asin) _cimg_create_ext_pointwise_function(atan) _cimg_create_ext_pointwise_function(cosh) _cimg_create_ext_pointwise_function(sinh) _cimg_create_ext_pointwise_function(tanh) _cimg_create_ext_pointwise_function(acosh) _cimg_create_ext_pointwise_function(asinh) _cimg_create_ext_pointwise_function(atanh) /*----------------------------------- # # Define the CImgDisplay structure # ----------------------------------*/ //! Allow the creation of windows, display images on them and manage user events (keyboard, mouse and windows events). /** CImgDisplay methods rely on a low-level graphic library to perform: it can be either \b X-Window (X11, for Unix-based systems) or \b GDI32 (for Windows-based systems). If both libraries are missing, CImgDisplay will not be able to display images on screen, and will enter a minimal mode where warning messages will be outputed each time the program is trying to call one of the CImgDisplay method. The configuration variable \c cimg_display tells about the graphic library used. It is set automatically by \CImg when one of these graphic libraries has been detected. But, you can override its value if necessary. Valid choices are: - 0: Disable display capabilities. - 1: Use \b X-Window (X11) library. - 2: Use \b GDI32 library. Remember to link your program against \b X11 or \b GDI32 libraries if you use CImgDisplay. **/ struct CImgDisplay { cimg_ulong _timer, _fps_frames, _fps_timer; unsigned int _width, _height, _normalization; float _fps_fps, _min, _max; bool _is_fullscreen; char *_title; unsigned int _window_width, _window_height, _button, *_keys, *_released_keys; int _window_x, _window_y, _mouse_x, _mouse_y, _wheel; bool _is_closed, _is_resized, _is_moved, _is_event, _is_keyESC, _is_keyF1, _is_keyF2, _is_keyF3, _is_keyF4, _is_keyF5, _is_keyF6, _is_keyF7, _is_keyF8, _is_keyF9, _is_keyF10, _is_keyF11, _is_keyF12, _is_keyPAUSE, _is_key1, _is_key2, _is_key3, _is_key4, _is_key5, _is_key6, _is_key7, _is_key8, _is_key9, _is_key0, _is_keyBACKSPACE, _is_keyINSERT, _is_keyHOME, _is_keyPAGEUP, _is_keyTAB, _is_keyQ, _is_keyW, _is_keyE, _is_keyR, _is_keyT, _is_keyY, _is_keyU, _is_keyI, _is_keyO, _is_keyP, _is_keyDELETE, _is_keyEND, _is_keyPAGEDOWN, _is_keyCAPSLOCK, _is_keyA, _is_keyS, _is_keyD, _is_keyF, _is_keyG, _is_keyH, _is_keyJ, _is_keyK, _is_keyL, _is_keyENTER, _is_keySHIFTLEFT, _is_keyZ, _is_keyX, _is_keyC, _is_keyV, _is_keyB, _is_keyN, _is_keyM, _is_keySHIFTRIGHT, _is_keyARROWUP, _is_keyCTRLLEFT, _is_keyAPPLEFT, _is_keyALT, _is_keySPACE, _is_keyALTGR, _is_keyAPPRIGHT, _is_keyMENU, _is_keyCTRLRIGHT, _is_keyARROWLEFT, _is_keyARROWDOWN, _is_keyARROWRIGHT, _is_keyPAD0, _is_keyPAD1, _is_keyPAD2, _is_keyPAD3, _is_keyPAD4, _is_keyPAD5, _is_keyPAD6, _is_keyPAD7, _is_keyPAD8, _is_keyPAD9, _is_keyPADADD, _is_keyPADSUB, _is_keyPADMUL, _is_keyPADDIV; //@} //--------------------------- // //! \name Plugins //@{ //--------------------------- #ifdef cimgdisplay_plugin #include cimgdisplay_plugin #endif #ifdef cimgdisplay_plugin1 #include cimgdisplay_plugin1 #endif #ifdef cimgdisplay_plugin2 #include cimgdisplay_plugin2 #endif #ifdef cimgdisplay_plugin3 #include cimgdisplay_plugin3 #endif #ifdef cimgdisplay_plugin4 #include cimgdisplay_plugin4 #endif #ifdef cimgdisplay_plugin5 #include cimgdisplay_plugin5 #endif #ifdef cimgdisplay_plugin6 #include cimgdisplay_plugin6 #endif #ifdef cimgdisplay_plugin7 #include cimgdisplay_plugin7 #endif #ifdef cimgdisplay_plugin8 #include cimgdisplay_plugin8 #endif //@} //-------------------------------------------------------- // //! \name Constructors / Destructor / Instance Management //@{ //-------------------------------------------------------- //! Destructor. /** \note If the associated window is visible on the screen, it is closed by the call to the destructor. **/ ~CImgDisplay() { assign(); delete[] _keys; delete[] _released_keys; } //! Construct an empty display. /** \note Constructing an empty CImgDisplay instance does not make a window appearing on the screen, until display of valid data is performed. \par Example \code CImgDisplay disp; // Does actually nothing ... disp.display(img); // Construct new window and display image in it \endcode **/ CImgDisplay(): _width(0),_height(0),_normalization(0), _min(0),_max(0), _is_fullscreen(false), _title(0), _window_width(0),_window_height(0),_button(0), _keys(new unsigned int[128]),_released_keys(new unsigned int[128]), _window_x(0),_window_y(0),_mouse_x(-1),_mouse_y(-1),_wheel(0), _is_closed(true),_is_resized(false),_is_moved(false),_is_event(false) { assign(); } //! Construct a display with specified dimensions. /** \param width Window width. \param height Window height. \param title Window title. \param normalization Normalization type (<tt>0</tt>=none, <tt>1</tt>=always, <tt>2</tt>=once, <tt>3</tt>=pixel type-dependent, see normalization()). \param is_fullscreen Tells if fullscreen mode is enabled. \param is_closed Tells if associated window is initially visible or not. \note A black background is initially displayed on the associated window. **/ CImgDisplay(const unsigned int width, const unsigned int height, const char *const title=0, const unsigned int normalization=3, const bool is_fullscreen=false, const bool is_closed=false): _width(0),_height(0),_normalization(0), _min(0),_max(0), _is_fullscreen(false), _title(0), _window_width(0),_window_height(0),_button(0), _keys(new unsigned int[128]),_released_keys(new unsigned int[128]), _window_x(0),_window_y(0),_mouse_x(-1),_mouse_y(-1),_wheel(0), _is_closed(true),_is_resized(false),_is_moved(false),_is_event(false) { assign(width,height,title,normalization,is_fullscreen,is_closed); } //! Construct a display from an image. /** \param img Image used as a model to create the window. \param title Window title. \param normalization Normalization type (<tt>0</tt>=none, <tt>1</tt>=always, <tt>2</tt>=once, <tt>3</tt>=pixel type-dependent, see normalization()). \param is_fullscreen Tells if fullscreen mode is enabled. \param is_closed Tells if associated window is initially visible or not. \note The pixels of the input image are initially displayed on the associated window. **/ template<typename T> explicit CImgDisplay(const CImg<T>& img, const char *const title=0, const unsigned int normalization=3, const bool is_fullscreen=false, const bool is_closed=false): _width(0),_height(0),_normalization(0), _min(0),_max(0), _is_fullscreen(false), _title(0), _window_width(0),_window_height(0),_button(0), _keys(new unsigned int[128]),_released_keys(new unsigned int[128]), _window_x(0),_window_y(0),_mouse_x(-1),_mouse_y(-1),_wheel(0), _is_closed(true),_is_resized(false),_is_moved(false),_is_event(false) { assign(img,title,normalization,is_fullscreen,is_closed); } //! Construct a display from an image list. /** \param list The images list to display. \param title Window title. \param normalization Normalization type (<tt>0</tt>=none, <tt>1</tt>=always, <tt>2</tt>=once, <tt>3</tt>=pixel type-dependent, see normalization()). \param is_fullscreen Tells if fullscreen mode is enabled. \param is_closed Tells if associated window is initially visible or not. \note All images of the list, appended along the X-axis, are initially displayed on the associated window. **/ template<typename T> explicit CImgDisplay(const CImgList<T>& list, const char *const title=0, const unsigned int normalization=3, const bool is_fullscreen=false, const bool is_closed=false): _width(0),_height(0),_normalization(0), _min(0),_max(0), _is_fullscreen(false), _title(0), _window_width(0),_window_height(0),_button(0), _keys(new unsigned int[128]),_released_keys(new unsigned int[128]), _window_x(0),_window_y(0),_mouse_x(-1),_mouse_y(-1),_wheel(0), _is_closed(true),_is_resized(false),_is_moved(false),_is_event(false) { assign(list,title,normalization,is_fullscreen,is_closed); } //! Construct a display as a copy of an existing one. /** \param disp Display instance to copy. \note The pixel buffer of the input window is initially displayed on the associated window. **/ CImgDisplay(const CImgDisplay& disp): _width(0),_height(0),_normalization(0), _min(0),_max(0), _is_fullscreen(false), _title(0), _window_width(0),_window_height(0),_button(0), _keys(new unsigned int[128]),_released_keys(new unsigned int[128]), _window_x(0),_window_y(0),_mouse_x(-1),_mouse_y(-1),_wheel(0), _is_closed(true),_is_resized(false),_is_moved(false),_is_event(false) { assign(disp); } //! Take a screenshot. /** \param[out] img Output screenshot. Can be empty on input **/ template<typename T> static void screenshot(CImg<T>& img) { return screenshot(0,0,cimg::type<int>::max(),cimg::type<int>::max(),img); } #if cimg_display==0 static void _no_display_exception() { throw CImgDisplayException("CImgDisplay(): No display available."); } //! Destructor - Empty constructor \inplace. /** \note Replace the current instance by an empty display. **/ CImgDisplay& assign() { return flush(); } //! Construct a display with specified dimensions \inplace. /** **/ CImgDisplay& assign(const unsigned int width, const unsigned int height, const char *const title=0, const unsigned int normalization=3, const bool is_fullscreen=false, const bool is_closed=false) { cimg::unused(width,height,title,normalization,is_fullscreen,is_closed); _no_display_exception(); return assign(); } //! Construct a display from an image \inplace. /** **/ template<typename T> CImgDisplay& assign(const CImg<T>& img, const char *const title=0, const unsigned int normalization=3, const bool is_fullscreen=false, const bool is_closed=false) { _no_display_exception(); return assign(img._width,img._height,title,normalization,is_fullscreen,is_closed); } //! Construct a display from an image list \inplace. /** **/ template<typename T> CImgDisplay& assign(const CImgList<T>& list, const char *const title=0, const unsigned int normalization=3, const bool is_fullscreen=false, const bool is_closed=false) { _no_display_exception(); return assign(list._width,list._width,title,normalization,is_fullscreen,is_closed); } //! Construct a display as a copy of another one \inplace. /** **/ CImgDisplay& assign(const CImgDisplay &disp) { _no_display_exception(); return assign(disp._width,disp._height); } #endif //! Return a reference to an empty display. /** \note Can be useful for writing function prototypes where one of the argument (of type CImgDisplay&) must have a default value. \par Example \code void foo(CImgDisplay& disp=CImgDisplay::empty()); \endcode **/ static CImgDisplay& empty() { static CImgDisplay _empty; return _empty.assign(); } //! Return a reference to an empty display \const. static const CImgDisplay& const_empty() { static const CImgDisplay _empty; return _empty; } #define cimg_fitscreen(dx,dy,dz) CImgDisplay::_fitscreen(dx,dy,dz,128,-85,false), \ CImgDisplay::_fitscreen(dx,dy,dz,128,-85,true) static unsigned int _fitscreen(const unsigned int dx, const unsigned int dy, const unsigned int dz, const int dmin, const int dmax, const bool return_y) { const int u = CImgDisplay::screen_width(), v = CImgDisplay::screen_height(); const float mw = dmin<0?cimg::round(u*-dmin/100.f):(float)dmin, mh = dmin<0?cimg::round(v*-dmin/100.f):(float)dmin, Mw = dmax<0?cimg::round(u*-dmax/100.f):(float)dmax, Mh = dmax<0?cimg::round(v*-dmax/100.f):(float)dmax; float w = (float)std::max(1U,dx), h = (float)std::max(1U,dy); if (dz>1) { w+=dz; h+=dz; } if (w<mw) { h = h*mw/w; w = mw; } if (h<mh) { w = w*mh/h; h = mh; } if (w>Mw) { h = h*Mw/w; w = Mw; } if (h>Mh) { w = w*Mh/h; h = Mh; } if (w<mw) w = mw; if (h<mh) h = mh; return std::max(1U,(unsigned int)cimg::round(return_y?h:w)); } //@} //------------------------------------------ // //! \name Overloaded Operators //@{ //------------------------------------------ //! Display image on associated window. /** \note <tt>disp = img</tt> is equivalent to <tt>disp.display(img)</tt>. **/ template<typename t> CImgDisplay& operator=(const CImg<t>& img) { return display(img); } //! Display list of images on associated window. /** \note <tt>disp = list</tt> is equivalent to <tt>disp.display(list)</tt>. **/ template<typename t> CImgDisplay& operator=(const CImgList<t>& list) { return display(list); } //! Construct a display as a copy of another one \inplace. /** \note Equivalent to assign(const CImgDisplay&). **/ CImgDisplay& operator=(const CImgDisplay& disp) { return assign(disp); } //! Return \c false if display is empty, \c true otherwise. /** \note <tt>if (disp) { ... }</tt> is equivalent to <tt>if (!disp.is_empty()) { ... }</tt>. **/ operator bool() const { return !is_empty(); } //@} //------------------------------------------ // //! \name Instance Checking //@{ //------------------------------------------ //! Return \c true if display is empty, \c false otherwise. /** **/ bool is_empty() const { return !(_width && _height); } //! Return \c true if display is closed (i.e. not visible on the screen), \c false otherwise. /** \note - When a user physically closes the associated window, the display is set to closed. - A closed display is not destroyed. Its associated window can be show again on the screen using show(). **/ bool is_closed() const { return _is_closed; } //! Return \c true if associated window has been resized on the screen, \c false otherwise. /** **/ bool is_resized() const { return _is_resized; } //! Return \c true if associated window has been moved on the screen, \c false otherwise. /** **/ bool is_moved() const { return _is_moved; } //! Return \c true if any event has occured on the associated window, \c false otherwise. /** **/ bool is_event() const { return _is_event; } //! Return \c true if current display is in fullscreen mode, \c false otherwise. /** **/ bool is_fullscreen() const { return _is_fullscreen; } //! Return \c true if any key is being pressed on the associated window, \c false otherwise. /** \note The methods below do the same only for specific keys. **/ bool is_key() const { return _is_keyESC || _is_keyF1 || _is_keyF2 || _is_keyF3 || _is_keyF4 || _is_keyF5 || _is_keyF6 || _is_keyF7 || _is_keyF8 || _is_keyF9 || _is_keyF10 || _is_keyF11 || _is_keyF12 || _is_keyPAUSE || _is_key1 || _is_key2 || _is_key3 || _is_key4 || _is_key5 || _is_key6 || _is_key7 || _is_key8 || _is_key9 || _is_key0 || _is_keyBACKSPACE || _is_keyINSERT || _is_keyHOME || _is_keyPAGEUP || _is_keyTAB || _is_keyQ || _is_keyW || _is_keyE || _is_keyR || _is_keyT || _is_keyY || _is_keyU || _is_keyI || _is_keyO || _is_keyP || _is_keyDELETE || _is_keyEND || _is_keyPAGEDOWN || _is_keyCAPSLOCK || _is_keyA || _is_keyS || _is_keyD || _is_keyF || _is_keyG || _is_keyH || _is_keyJ || _is_keyK || _is_keyL || _is_keyENTER || _is_keySHIFTLEFT || _is_keyZ || _is_keyX || _is_keyC || _is_keyV || _is_keyB || _is_keyN || _is_keyM || _is_keySHIFTRIGHT || _is_keyARROWUP || _is_keyCTRLLEFT || _is_keyAPPLEFT || _is_keyALT || _is_keySPACE || _is_keyALTGR || _is_keyAPPRIGHT || _is_keyMENU || _is_keyCTRLRIGHT || _is_keyARROWLEFT || _is_keyARROWDOWN || _is_keyARROWRIGHT || _is_keyPAD0 || _is_keyPAD1 || _is_keyPAD2 || _is_keyPAD3 || _is_keyPAD4 || _is_keyPAD5 || _is_keyPAD6 || _is_keyPAD7 || _is_keyPAD8 || _is_keyPAD9 || _is_keyPADADD || _is_keyPADSUB || _is_keyPADMUL || _is_keyPADDIV; } //! Return \c true if key specified by given keycode is being pressed on the associated window, \c false otherwise. /** \param keycode Keycode to test. \note Keycode constants are defined in the cimg namespace and are architecture-dependent. Use them to ensure your code stay portable (see cimg::keyESC). \par Example \code CImgDisplay disp(400,400); while (!disp.is_closed()) { if (disp.key(cimg::keyTAB)) { ... } // Equivalent to 'if (disp.is_keyTAB())' disp.wait(); } \endcode **/ bool is_key(const unsigned int keycode) const { #define _cimg_iskey_test(k) if (keycode==cimg::key##k) return _is_key##k; _cimg_iskey_test(ESC); _cimg_iskey_test(F1); _cimg_iskey_test(F2); _cimg_iskey_test(F3); _cimg_iskey_test(F4); _cimg_iskey_test(F5); _cimg_iskey_test(F6); _cimg_iskey_test(F7); _cimg_iskey_test(F8); _cimg_iskey_test(F9); _cimg_iskey_test(F10); _cimg_iskey_test(F11); _cimg_iskey_test(F12); _cimg_iskey_test(PAUSE); _cimg_iskey_test(1); _cimg_iskey_test(2); _cimg_iskey_test(3); _cimg_iskey_test(4); _cimg_iskey_test(5); _cimg_iskey_test(6); _cimg_iskey_test(7); _cimg_iskey_test(8); _cimg_iskey_test(9); _cimg_iskey_test(0); _cimg_iskey_test(BACKSPACE); _cimg_iskey_test(INSERT); _cimg_iskey_test(HOME); _cimg_iskey_test(PAGEUP); _cimg_iskey_test(TAB); _cimg_iskey_test(Q); _cimg_iskey_test(W); _cimg_iskey_test(E); _cimg_iskey_test(R); _cimg_iskey_test(T); _cimg_iskey_test(Y); _cimg_iskey_test(U); _cimg_iskey_test(I); _cimg_iskey_test(O); _cimg_iskey_test(P); _cimg_iskey_test(DELETE); _cimg_iskey_test(END); _cimg_iskey_test(PAGEDOWN); _cimg_iskey_test(CAPSLOCK); _cimg_iskey_test(A); _cimg_iskey_test(S); _cimg_iskey_test(D); _cimg_iskey_test(F); _cimg_iskey_test(G); _cimg_iskey_test(H); _cimg_iskey_test(J); _cimg_iskey_test(K); _cimg_iskey_test(L); _cimg_iskey_test(ENTER); _cimg_iskey_test(SHIFTLEFT); _cimg_iskey_test(Z); _cimg_iskey_test(X); _cimg_iskey_test(C); _cimg_iskey_test(V); _cimg_iskey_test(B); _cimg_iskey_test(N); _cimg_iskey_test(M); _cimg_iskey_test(SHIFTRIGHT); _cimg_iskey_test(ARROWUP); _cimg_iskey_test(CTRLLEFT); _cimg_iskey_test(APPLEFT); _cimg_iskey_test(ALT); _cimg_iskey_test(SPACE); _cimg_iskey_test(ALTGR); _cimg_iskey_test(APPRIGHT); _cimg_iskey_test(MENU); _cimg_iskey_test(CTRLRIGHT); _cimg_iskey_test(ARROWLEFT); _cimg_iskey_test(ARROWDOWN); _cimg_iskey_test(ARROWRIGHT); _cimg_iskey_test(PAD0); _cimg_iskey_test(PAD1); _cimg_iskey_test(PAD2); _cimg_iskey_test(PAD3); _cimg_iskey_test(PAD4); _cimg_iskey_test(PAD5); _cimg_iskey_test(PAD6); _cimg_iskey_test(PAD7); _cimg_iskey_test(PAD8); _cimg_iskey_test(PAD9); _cimg_iskey_test(PADADD); _cimg_iskey_test(PADSUB); _cimg_iskey_test(PADMUL); _cimg_iskey_test(PADDIV); return false; } //! Return \c true if key specified by given keycode is being pressed on the associated window, \c false otherwise. /** \param keycode C-string containing the keycode label of the key to test. \note Use it when the key you want to test can be dynamically set by the user. \par Example \code CImgDisplay disp(400,400); const char *const keycode = "TAB"; while (!disp.is_closed()) { if (disp.is_key(keycode)) { ... } // Equivalent to 'if (disp.is_keyTAB())' disp.wait(); } \endcode **/ bool& is_key(const char *const keycode) { static bool f = false; f = false; #define _cimg_iskey_test2(k) if (!cimg::strcasecmp(keycode,#k)) return _is_key##k; _cimg_iskey_test2(ESC); _cimg_iskey_test2(F1); _cimg_iskey_test2(F2); _cimg_iskey_test2(F3); _cimg_iskey_test2(F4); _cimg_iskey_test2(F5); _cimg_iskey_test2(F6); _cimg_iskey_test2(F7); _cimg_iskey_test2(F8); _cimg_iskey_test2(F9); _cimg_iskey_test2(F10); _cimg_iskey_test2(F11); _cimg_iskey_test2(F12); _cimg_iskey_test2(PAUSE); _cimg_iskey_test2(1); _cimg_iskey_test2(2); _cimg_iskey_test2(3); _cimg_iskey_test2(4); _cimg_iskey_test2(5); _cimg_iskey_test2(6); _cimg_iskey_test2(7); _cimg_iskey_test2(8); _cimg_iskey_test2(9); _cimg_iskey_test2(0); _cimg_iskey_test2(BACKSPACE); _cimg_iskey_test2(INSERT); _cimg_iskey_test2(HOME); _cimg_iskey_test2(PAGEUP); _cimg_iskey_test2(TAB); _cimg_iskey_test2(Q); _cimg_iskey_test2(W); _cimg_iskey_test2(E); _cimg_iskey_test2(R); _cimg_iskey_test2(T); _cimg_iskey_test2(Y); _cimg_iskey_test2(U); _cimg_iskey_test2(I); _cimg_iskey_test2(O); _cimg_iskey_test2(P); _cimg_iskey_test2(DELETE); _cimg_iskey_test2(END); _cimg_iskey_test2(PAGEDOWN); _cimg_iskey_test2(CAPSLOCK); _cimg_iskey_test2(A); _cimg_iskey_test2(S); _cimg_iskey_test2(D); _cimg_iskey_test2(F); _cimg_iskey_test2(G); _cimg_iskey_test2(H); _cimg_iskey_test2(J); _cimg_iskey_test2(K); _cimg_iskey_test2(L); _cimg_iskey_test2(ENTER); _cimg_iskey_test2(SHIFTLEFT); _cimg_iskey_test2(Z); _cimg_iskey_test2(X); _cimg_iskey_test2(C); _cimg_iskey_test2(V); _cimg_iskey_test2(B); _cimg_iskey_test2(N); _cimg_iskey_test2(M); _cimg_iskey_test2(SHIFTRIGHT); _cimg_iskey_test2(ARROWUP); _cimg_iskey_test2(CTRLLEFT); _cimg_iskey_test2(APPLEFT); _cimg_iskey_test2(ALT); _cimg_iskey_test2(SPACE); _cimg_iskey_test2(ALTGR); _cimg_iskey_test2(APPRIGHT); _cimg_iskey_test2(MENU); _cimg_iskey_test2(CTRLRIGHT); _cimg_iskey_test2(ARROWLEFT); _cimg_iskey_test2(ARROWDOWN); _cimg_iskey_test2(ARROWRIGHT); _cimg_iskey_test2(PAD0); _cimg_iskey_test2(PAD1); _cimg_iskey_test2(PAD2); _cimg_iskey_test2(PAD3); _cimg_iskey_test2(PAD4); _cimg_iskey_test2(PAD5); _cimg_iskey_test2(PAD6); _cimg_iskey_test2(PAD7); _cimg_iskey_test2(PAD8); _cimg_iskey_test2(PAD9); _cimg_iskey_test2(PADADD); _cimg_iskey_test2(PADSUB); _cimg_iskey_test2(PADMUL); _cimg_iskey_test2(PADDIV); return f; } //! Return \c true if specified key sequence has been typed on the associated window, \c false otherwise. /** \param keycodes_sequence Buffer of keycodes to test. \param length Number of keys in the \c keycodes_sequence buffer. \param remove_sequence Tells if the key sequence must be removed from the key history, if found. \note Keycode constants are defined in the cimg namespace and are architecture-dependent. Use them to ensure your code stay portable (see cimg::keyESC). \par Example \code CImgDisplay disp(400,400); const unsigned int key_seq[] = { cimg::keyCTRLLEFT, cimg::keyD }; while (!disp.is_closed()) { if (disp.is_key_sequence(key_seq,2)) { ... } // Test for the 'CTRL+D' keyboard event disp.wait(); } \endcode **/ bool is_key_sequence(const unsigned int *const keycodes_sequence, const unsigned int length, const bool remove_sequence=false) { if (keycodes_sequence && length) { const unsigned int *const ps_end = keycodes_sequence + length - 1, *const pk_end = (unsigned int*)_keys + 1 + 128 - length, k = *ps_end; for (unsigned int *pk = (unsigned int*)_keys; pk<pk_end; ) { if (*(pk++)==k) { bool res = true; const unsigned int *ps = ps_end, *pk2 = pk; for (unsigned int i = 1; i<length; ++i) res = (*(--ps)==*(pk2++)); if (res) { if (remove_sequence) std::memset((void*)(pk - 1),0,sizeof(unsigned int)*length); return true; } } } } return false; } #define _cimg_iskey_def(k) \ bool is_key##k() const { \ return _is_key##k; \ } //! Return \c true if the \c ESC key is being pressed on the associated window, \c false otherwise. /** \note Similar methods exist for all keys managed by \CImg (see cimg::keyESC). **/ _cimg_iskey_def(ESC); _cimg_iskey_def(F1); _cimg_iskey_def(F2); _cimg_iskey_def(F3); _cimg_iskey_def(F4); _cimg_iskey_def(F5); _cimg_iskey_def(F6); _cimg_iskey_def(F7); _cimg_iskey_def(F8); _cimg_iskey_def(F9); _cimg_iskey_def(F10); _cimg_iskey_def(F11); _cimg_iskey_def(F12); _cimg_iskey_def(PAUSE); _cimg_iskey_def(1); _cimg_iskey_def(2); _cimg_iskey_def(3); _cimg_iskey_def(4); _cimg_iskey_def(5); _cimg_iskey_def(6); _cimg_iskey_def(7); _cimg_iskey_def(8); _cimg_iskey_def(9); _cimg_iskey_def(0); _cimg_iskey_def(BACKSPACE); _cimg_iskey_def(INSERT); _cimg_iskey_def(HOME); _cimg_iskey_def(PAGEUP); _cimg_iskey_def(TAB); _cimg_iskey_def(Q); _cimg_iskey_def(W); _cimg_iskey_def(E); _cimg_iskey_def(R); _cimg_iskey_def(T); _cimg_iskey_def(Y); _cimg_iskey_def(U); _cimg_iskey_def(I); _cimg_iskey_def(O); _cimg_iskey_def(P); _cimg_iskey_def(DELETE); _cimg_iskey_def(END); _cimg_iskey_def(PAGEDOWN); _cimg_iskey_def(CAPSLOCK); _cimg_iskey_def(A); _cimg_iskey_def(S); _cimg_iskey_def(D); _cimg_iskey_def(F); _cimg_iskey_def(G); _cimg_iskey_def(H); _cimg_iskey_def(J); _cimg_iskey_def(K); _cimg_iskey_def(L); _cimg_iskey_def(ENTER); _cimg_iskey_def(SHIFTLEFT); _cimg_iskey_def(Z); _cimg_iskey_def(X); _cimg_iskey_def(C); _cimg_iskey_def(V); _cimg_iskey_def(B); _cimg_iskey_def(N); _cimg_iskey_def(M); _cimg_iskey_def(SHIFTRIGHT); _cimg_iskey_def(ARROWUP); _cimg_iskey_def(CTRLLEFT); _cimg_iskey_def(APPLEFT); _cimg_iskey_def(ALT); _cimg_iskey_def(SPACE); _cimg_iskey_def(ALTGR); _cimg_iskey_def(APPRIGHT); _cimg_iskey_def(MENU); _cimg_iskey_def(CTRLRIGHT); _cimg_iskey_def(ARROWLEFT); _cimg_iskey_def(ARROWDOWN); _cimg_iskey_def(ARROWRIGHT); _cimg_iskey_def(PAD0); _cimg_iskey_def(PAD1); _cimg_iskey_def(PAD2); _cimg_iskey_def(PAD3); _cimg_iskey_def(PAD4); _cimg_iskey_def(PAD5); _cimg_iskey_def(PAD6); _cimg_iskey_def(PAD7); _cimg_iskey_def(PAD8); _cimg_iskey_def(PAD9); _cimg_iskey_def(PADADD); _cimg_iskey_def(PADSUB); _cimg_iskey_def(PADMUL); _cimg_iskey_def(PADDIV); //@} //------------------------------------------ // //! \name Instance Characteristics //@{ //------------------------------------------ #if cimg_display==0 //! Return width of the screen (current resolution along the X-axis). /** **/ static int screen_width() { _no_display_exception(); return 0; } //! Return height of the screen (current resolution along the Y-axis). /** **/ static int screen_height() { _no_display_exception(); return 0; } #endif //! Return display width. /** \note The width of the display (i.e. the width of the pixel data buffer associated to the CImgDisplay instance) may be different from the actual width of the associated window. **/ int width() const { return (int)_width; } //! Return display height. /** \note The height of the display (i.e. the height of the pixel data buffer associated to the CImgDisplay instance) may be different from the actual height of the associated window. **/ int height() const { return (int)_height; } //! Return normalization type of the display. /** The normalization type tells about how the values of an input image are normalized by the CImgDisplay to be correctly displayed. The range of values for pixels displayed on screen is <tt>[0,255]</tt>. If the range of values of the data to display is different, a normalization may be required for displaying the data in a correct way. The normalization type can be one of: - \c 0: Value normalization is disabled. It is then assumed that all input data to be displayed by the CImgDisplay instance have values in range <tt>[0,255]</tt>. - \c 1: Value normalization is always performed (this is the default behavior). Before displaying an input image, its values will be (virtually) stretched in range <tt>[0,255]</tt>, so that the contrast of the displayed pixels will be maximum. Use this mode for images whose minimum and maximum values are not prescribed to known values (e.g. float-valued images). Note that when normalized versions of images are computed for display purposes, the actual values of these images are not modified. - \c 2: Value normalization is performed once (on the first image display), then the same normalization coefficients are kept for next displayed frames. - \c 3: Value normalization depends on the pixel type of the data to display. For integer pixel types, the normalization is done regarding the minimum/maximum values of the type (no normalization occurs then for <tt>unsigned char</tt>). For float-valued pixel types, the normalization is done regarding the minimum/maximum value of the image data instead. **/ unsigned int normalization() const { return _normalization; } //! Return title of the associated window as a C-string. /** \note Window title may be not visible, depending on the used window manager or if the current display is in fullscreen mode. **/ const char *title() const { return _title?_title:""; } //! Return width of the associated window. /** \note The width of the display (i.e. the width of the pixel data buffer associated to the CImgDisplay instance) may be different from the actual width of the associated window. **/ int window_width() const { return (int)_window_width; } //! Return height of the associated window. /** \note The height of the display (i.e. the height of the pixel data buffer associated to the CImgDisplay instance) may be different from the actual height of the associated window. **/ int window_height() const { return (int)_window_height; } //! Return X-coordinate of the associated window. /** \note The returned coordinate corresponds to the location of the upper-left corner of the associated window. **/ int window_x() const { return _window_x; } //! Return Y-coordinate of the associated window. /** \note The returned coordinate corresponds to the location of the upper-left corner of the associated window. **/ int window_y() const { return _window_y; } //! Return X-coordinate of the mouse pointer. /** \note - If the mouse pointer is outside window area, \c -1 is returned. - Otherwise, the returned value is in the range [0,width()-1]. **/ int mouse_x() const { return _mouse_x; } //! Return Y-coordinate of the mouse pointer. /** \note - If the mouse pointer is outside window area, \c -1 is returned. - Otherwise, the returned value is in the range [0,height()-1]. **/ int mouse_y() const { return _mouse_y; } //! Return current state of the mouse buttons. /** \note Three mouse buttons can be managed. If one button is pressed, its corresponding bit in the returned value is set: - bit \c 0 (value \c 0x1): State of the left mouse button. - bit \c 1 (value \c 0x2): State of the right mouse button. - bit \c 2 (value \c 0x4): State of the middle mouse button. Several bits can be activated if more than one button are pressed at the same time. \par Example \code CImgDisplay disp(400,400); while (!disp.is_closed()) { if (disp.button()&1) { // Left button clicked ... } if (disp.button()&2) { // Right button clicked ... } if (disp.button()&4) { // Middle button clicked ... } disp.wait(); } \endcode **/ unsigned int button() const { return _button; } //! Return current state of the mouse wheel. /** \note - The returned value can be positive or negative depending on whether the mouse wheel has been scrolled forward or backward. - Scrolling the wheel forward add \c 1 to the wheel value. - Scrolling the wheel backward substract \c 1 to the wheel value. - The returned value cumulates the number of forward of backward scrolls since the creation of the display, or since the last reset of the wheel value (using set_wheel()). It is strongly recommended to quickly reset the wheel counter when an action has been performed regarding the current wheel value. Otherwise, the returned wheel value may be for instance \c 0 despite the fact that many scrolls have been done (as many in forward as in backward directions). \par Example \code CImgDisplay disp(400,400); while (!disp.is_closed()) { if (disp.wheel()) { int counter = disp.wheel(); // Read the state of the mouse wheel ... // Do what you want with 'counter' disp.set_wheel(); // Reset the wheel value to 0 } disp.wait(); } \endcode **/ int wheel() const { return _wheel; } //! Return one entry from the pressed keys history. /** \param pos Index to read from the pressed keys history (index \c 0 corresponds to latest entry). \return Keycode of a pressed key or \c 0 for a released key. \note - Each CImgDisplay stores a history of the pressed keys in a buffer of size \c 128. When a new key is pressed, its keycode is stored in the pressed keys history. When a key is released, \c 0 is put instead. This means that up to the 64 last pressed keys may be read from the pressed keys history. When a new value is stored, the pressed keys history is shifted so that the latest entry is always stored at position \c 0. - Keycode constants are defined in the cimg namespace and are architecture-dependent. Use them to ensure your code stay portable (see cimg::keyESC). **/ unsigned int key(const unsigned int pos=0) const { return pos<128?_keys[pos]:0; } //! Return one entry from the released keys history. /** \param pos Index to read from the released keys history (index \c 0 corresponds to latest entry). \return Keycode of a released key or \c 0 for a pressed key. \note - Each CImgDisplay stores a history of the released keys in a buffer of size \c 128. When a new key is released, its keycode is stored in the pressed keys history. When a key is pressed, \c 0 is put instead. This means that up to the 64 last released keys may be read from the released keys history. When a new value is stored, the released keys history is shifted so that the latest entry is always stored at position \c 0. - Keycode constants are defined in the cimg namespace and are architecture-dependent. Use them to ensure your code stay portable (see cimg::keyESC). **/ unsigned int released_key(const unsigned int pos=0) const { return pos<128?_released_keys[pos]:0; } //! Return keycode corresponding to the specified string. /** \note Keycode constants are defined in the cimg namespace and are architecture-dependent. Use them to ensure your code stay portable (see cimg::keyESC). \par Example \code const unsigned int keyTAB = CImgDisplay::keycode("TAB"); // Return cimg::keyTAB \endcode **/ static unsigned int keycode(const char *const keycode) { #define _cimg_keycode(k) if (!cimg::strcasecmp(keycode,#k)) return cimg::key##k; _cimg_keycode(ESC); _cimg_keycode(F1); _cimg_keycode(F2); _cimg_keycode(F3); _cimg_keycode(F4); _cimg_keycode(F5); _cimg_keycode(F6); _cimg_keycode(F7); _cimg_keycode(F8); _cimg_keycode(F9); _cimg_keycode(F10); _cimg_keycode(F11); _cimg_keycode(F12); _cimg_keycode(PAUSE); _cimg_keycode(1); _cimg_keycode(2); _cimg_keycode(3); _cimg_keycode(4); _cimg_keycode(5); _cimg_keycode(6); _cimg_keycode(7); _cimg_keycode(8); _cimg_keycode(9); _cimg_keycode(0); _cimg_keycode(BACKSPACE); _cimg_keycode(INSERT); _cimg_keycode(HOME); _cimg_keycode(PAGEUP); _cimg_keycode(TAB); _cimg_keycode(Q); _cimg_keycode(W); _cimg_keycode(E); _cimg_keycode(R); _cimg_keycode(T); _cimg_keycode(Y); _cimg_keycode(U); _cimg_keycode(I); _cimg_keycode(O); _cimg_keycode(P); _cimg_keycode(DELETE); _cimg_keycode(END); _cimg_keycode(PAGEDOWN); _cimg_keycode(CAPSLOCK); _cimg_keycode(A); _cimg_keycode(S); _cimg_keycode(D); _cimg_keycode(F); _cimg_keycode(G); _cimg_keycode(H); _cimg_keycode(J); _cimg_keycode(K); _cimg_keycode(L); _cimg_keycode(ENTER); _cimg_keycode(SHIFTLEFT); _cimg_keycode(Z); _cimg_keycode(X); _cimg_keycode(C); _cimg_keycode(V); _cimg_keycode(B); _cimg_keycode(N); _cimg_keycode(M); _cimg_keycode(SHIFTRIGHT); _cimg_keycode(ARROWUP); _cimg_keycode(CTRLLEFT); _cimg_keycode(APPLEFT); _cimg_keycode(ALT); _cimg_keycode(SPACE); _cimg_keycode(ALTGR); _cimg_keycode(APPRIGHT); _cimg_keycode(MENU); _cimg_keycode(CTRLRIGHT); _cimg_keycode(ARROWLEFT); _cimg_keycode(ARROWDOWN); _cimg_keycode(ARROWRIGHT); _cimg_keycode(PAD0); _cimg_keycode(PAD1); _cimg_keycode(PAD2); _cimg_keycode(PAD3); _cimg_keycode(PAD4); _cimg_keycode(PAD5); _cimg_keycode(PAD6); _cimg_keycode(PAD7); _cimg_keycode(PAD8); _cimg_keycode(PAD9); _cimg_keycode(PADADD); _cimg_keycode(PADSUB); _cimg_keycode(PADMUL); _cimg_keycode(PADDIV); return 0; } //! Return the current refresh rate, in frames per second. /** \note Returns a significant value when the current instance is used to display successive frames. It measures the delay between successive calls to frames_per_second(). **/ float frames_per_second() { if (!_fps_timer) _fps_timer = cimg::time(); const float delta = (cimg::time() - _fps_timer)/1000.f; ++_fps_frames; if (delta>=1) { _fps_fps = _fps_frames/delta; _fps_frames = 0; _fps_timer = cimg::time(); } return _fps_fps; } // Move current display window so that its content stays inside the current screen. CImgDisplay& move_inside_screen() { if (is_empty()) return *this; const int x0 = window_x(), y0 = window_y(), x1 = x0 + window_width() - 1, y1 = y0 + window_height() - 1, sw = CImgDisplay::screen_width(), sh = CImgDisplay::screen_height(); if (x0<0 || y0<0 || x1>=sw || y1>=sh) move(std::max(0,std::min(x0,sw - x1 + x0)), std::max(0,std::min(y0,sh - y1 + y0))); return *this; } //@} //--------------------------------------- // //! \name Window Manipulation //@{ //--------------------------------------- #if cimg_display==0 //! Display image on associated window. /** \param img Input image to display. \note This method returns immediately. **/ template<typename T> CImgDisplay& display(const CImg<T>& img) { return assign(img); } #endif //! Display list of images on associated window. /** \param list List of images to display. \param axis Axis used to append the images along, for the visualization (can be \c x, \c y, \c z or \c c). \param align Relative position of aligned images when displaying lists with images of different sizes (\c 0 for upper-left, \c 0.5 for centering and \c 1 for lower-right). \note This method returns immediately. **/ template<typename T> CImgDisplay& display(const CImgList<T>& list, const char axis='x', const float align=0) { if (list._width==1) { const CImg<T>& img = list[0]; if (img._depth==1 && (img._spectrum==1 || img._spectrum>=3) && _normalization!=1) return display(img); } CImgList<typename CImg<T>::ucharT> visu(list._width); unsigned int dims = 0; cimglist_for(list,l) { const CImg<T>& img = list._data[l]; img._get_select(*this,_normalization,(img._width - 1)/2,(img._height - 1)/2, (img._depth - 1)/2).move_to(visu[l]); dims = std::max(dims,visu[l]._spectrum); } cimglist_for(list,l) if (visu[l]._spectrum<dims) visu[l].resize(-100,-100,-100,dims,1); visu.get_append(axis,align).display(*this); return *this; } #if cimg_display==0 //! Show (closed) associated window on the screen. /** \note - Force the associated window of a display to be visible on the screen, even if it has been closed before. - Using show() on a visible display does nothing. **/ CImgDisplay& show() { return assign(); } //! Close (visible) associated window and make it disappear from the screen. /** \note - A closed display only means the associated window is not visible anymore. This does not mean the display has been destroyed. Use show() to make the associated window reappear. - Using close() on a closed display does nothing. **/ CImgDisplay& close() { return assign(); } //! Move associated window to a new location. /** \param pos_x X-coordinate of the new window location. \param pos_y Y-coordinate of the new window location. \note Depending on the window manager behavior, this method may not succeed (no exceptions are thrown nevertheless). **/ CImgDisplay& move(const int pos_x, const int pos_y) { return assign(pos_x,pos_y); } #endif //! Resize display to the size of the associated window. /** \param force_redraw Tells if the previous window content must be updated and refreshed as well. \note - Calling this method ensures that width() and window_width() become equal, as well as height() and window_height(). - The associated window is also resized to specified dimensions. **/ CImgDisplay& resize(const bool force_redraw=true) { resize(window_width(),window_height(),force_redraw); return *this; } #if cimg_display==0 //! Resize display to the specified size. /** \param width Requested display width. \param height Requested display height. \param force_redraw Tells if the previous window content must be updated and refreshed as well. \note The associated window is also resized to specified dimensions. **/ CImgDisplay& resize(const int width, const int height, const bool force_redraw=true) { return assign(width,height,0,3,force_redraw); } #endif //! Resize display to the size of an input image. /** \param img Input image to take size from. \param force_redraw Tells if the previous window content must be resized and updated as well. \note - Calling this method ensures that width() and <tt>img.width()</tt> become equal, as well as height() and <tt>img.height()</tt>. - The associated window is also resized to specified dimensions. **/ template<typename T> CImgDisplay& resize(const CImg<T>& img, const bool force_redraw=true) { return resize(img._width,img._height,force_redraw); } //! Resize display to the size of another CImgDisplay instance. /** \param disp Input display to take size from. \param force_redraw Tells if the previous window content must be resized and updated as well. \note - Calling this method ensures that width() and <tt>disp.width()</tt> become equal, as well as height() and <tt>disp.height()</tt>. - The associated window is also resized to specified dimensions. **/ CImgDisplay& resize(const CImgDisplay& disp, const bool force_redraw=true) { return resize(disp.width(),disp.height(),force_redraw); } // [internal] Render pixel buffer with size (wd,hd) from source buffer of size (ws,hs). template<typename t, typename T> static void _render_resize(const T *ptrs, const unsigned int ws, const unsigned int hs, t *ptrd, const unsigned int wd, const unsigned int hd) { typedef typename cimg::last<T,cimg_ulong>::type ulongT; const ulongT one = (ulongT)1; CImg<ulongT> off_x(wd), off_y(hd + 1); if (wd==ws) off_x.fill(1); else { ulongT *poff_x = off_x._data, curr = 0; for (unsigned int x = 0; x<wd; ++x) { const ulongT old = curr; curr = (x + one)*ws/wd; *(poff_x++) = curr - old; } } if (hd==hs) off_y.fill(ws); else { ulongT *poff_y = off_y._data, curr = 0; for (unsigned int y = 0; y<hd; ++y) { const ulongT old = curr; curr = (y + one)*hs/hd; *(poff_y++) = ws*(curr - old); } *poff_y = 0; } ulongT *poff_y = off_y._data; for (unsigned int y = 0; y<hd; ) { const T *ptr = ptrs; ulongT *poff_x = off_x._data; for (unsigned int x = 0; x<wd; ++x) { *(ptrd++) = *ptr; ptr+=*(poff_x++); } ++y; ulongT dy = *(poff_y++); for ( ; !dy && y<hd; std::memcpy(ptrd,ptrd - wd,sizeof(t)*wd), ++y, ptrd+=wd, dy = *(poff_y++)) {} ptrs+=dy; } } //! Set normalization type. /** \param normalization New normalization mode. **/ CImgDisplay& set_normalization(const unsigned int normalization) { _normalization = normalization; _min = _max = 0; return *this; } #if cimg_display==0 //! Set title of the associated window. /** \param format C-string containing the format of the title, as with <tt>std::printf()</tt>. \warning As the first argument is a format string, it is highly recommended to write \code disp.set_title("%s",window_title); \endcode instead of \code disp.set_title(window_title); \endcode if \c window_title can be arbitrary, to prevent nasty memory access. **/ CImgDisplay& set_title(const char *const format, ...) { return assign(0,0,format); } #endif //! Enable or disable fullscreen mode. /** \param is_fullscreen Tells is the fullscreen mode must be activated or not. \param force_redraw Tells if the previous window content must be displayed as well. \note - When the fullscreen mode is enabled, the associated window fills the entire screen but the size of the current display is not modified. - The screen resolution may be switched to fit the associated window size and ensure it appears the largest as possible. For X-Window (X11) users, the configuration flag \c cimg_use_xrandr has to be set to allow the screen resolution change (requires the X11 extensions to be enabled). **/ CImgDisplay& set_fullscreen(const bool is_fullscreen, const bool force_redraw=true) { if (is_empty() || _is_fullscreen==is_fullscreen) return *this; return toggle_fullscreen(force_redraw); } #if cimg_display==0 //! Toggle fullscreen mode. /** \param force_redraw Tells if the previous window content must be displayed as well. \note Enable fullscreen mode if it was not enabled, and disable it otherwise. **/ CImgDisplay& toggle_fullscreen(const bool force_redraw=true) { return assign(_width,_height,0,3,force_redraw); } //! Show mouse pointer. /** \note Depending on the window manager behavior, this method may not succeed (no exceptions are thrown nevertheless). **/ CImgDisplay& show_mouse() { return assign(); } //! Hide mouse pointer. /** \note Depending on the window manager behavior, this method may not succeed (no exceptions are thrown nevertheless). **/ CImgDisplay& hide_mouse() { return assign(); } //! Move mouse pointer to a specified location. /** \note Depending on the window manager behavior, this method may not succeed (no exceptions are thrown nevertheless). **/ CImgDisplay& set_mouse(const int pos_x, const int pos_y) { return assign(pos_x,pos_y); } #endif //! Simulate a mouse button release event. /** \note All mouse buttons are considered released at the same time. **/ CImgDisplay& set_button() { _button = 0; _is_event = true; #if cimg_display==1 pthread_cond_broadcast(&cimg::X11_attr().wait_event); #elif cimg_display==2 SetEvent(cimg::Win32_attr().wait_event); #endif return *this; } //! Simulate a mouse button press or release event. /** \param button Buttons event code, where each button is associated to a single bit. \param is_pressed Tells if the mouse button is considered as pressed or released. **/ CImgDisplay& set_button(const unsigned int button, const bool is_pressed=true) { const unsigned int buttoncode = button==1U?1U:button==2U?2U:button==3U?4U:0U; if (is_pressed) _button |= buttoncode; else _button &= ~buttoncode; _is_event = buttoncode?true:false; if (buttoncode) { #if cimg_display==1 pthread_cond_broadcast(&cimg::X11_attr().wait_event); #elif cimg_display==2 SetEvent(cimg::Win32_attr().wait_event); #endif } return *this; } //! Flush all mouse wheel events. /** \note Make wheel() to return \c 0, if called afterwards. **/ CImgDisplay& set_wheel() { _wheel = 0; _is_event = true; #if cimg_display==1 pthread_cond_broadcast(&cimg::X11_attr().wait_event); #elif cimg_display==2 SetEvent(cimg::Win32_attr().wait_event); #endif return *this; } //! Simulate a wheel event. /** \param amplitude Amplitude of the wheel scrolling to simulate. \note Make wheel() to return \c amplitude, if called afterwards. **/ CImgDisplay& set_wheel(const int amplitude) { _wheel+=amplitude; _is_event = amplitude?true:false; if (amplitude) { #if cimg_display==1 pthread_cond_broadcast(&cimg::X11_attr().wait_event); #elif cimg_display==2 SetEvent(cimg::Win32_attr().wait_event); #endif } return *this; } //! Flush all key events. /** \note Make key() to return \c 0, if called afterwards. **/ CImgDisplay& set_key() { std::memset((void*)_keys,0,128*sizeof(unsigned int)); std::memset((void*)_released_keys,0,128*sizeof(unsigned int)); _is_keyESC = _is_keyF1 = _is_keyF2 = _is_keyF3 = _is_keyF4 = _is_keyF5 = _is_keyF6 = _is_keyF7 = _is_keyF8 = _is_keyF9 = _is_keyF10 = _is_keyF11 = _is_keyF12 = _is_keyPAUSE = _is_key1 = _is_key2 = _is_key3 = _is_key4 = _is_key5 = _is_key6 = _is_key7 = _is_key8 = _is_key9 = _is_key0 = _is_keyBACKSPACE = _is_keyINSERT = _is_keyHOME = _is_keyPAGEUP = _is_keyTAB = _is_keyQ = _is_keyW = _is_keyE = _is_keyR = _is_keyT = _is_keyY = _is_keyU = _is_keyI = _is_keyO = _is_keyP = _is_keyDELETE = _is_keyEND = _is_keyPAGEDOWN = _is_keyCAPSLOCK = _is_keyA = _is_keyS = _is_keyD = _is_keyF = _is_keyG = _is_keyH = _is_keyJ = _is_keyK = _is_keyL = _is_keyENTER = _is_keySHIFTLEFT = _is_keyZ = _is_keyX = _is_keyC = _is_keyV = _is_keyB = _is_keyN = _is_keyM = _is_keySHIFTRIGHT = _is_keyARROWUP = _is_keyCTRLLEFT = _is_keyAPPLEFT = _is_keyALT = _is_keySPACE = _is_keyALTGR = _is_keyAPPRIGHT = _is_keyMENU = _is_keyCTRLRIGHT = _is_keyARROWLEFT = _is_keyARROWDOWN = _is_keyARROWRIGHT = _is_keyPAD0 = _is_keyPAD1 = _is_keyPAD2 = _is_keyPAD3 = _is_keyPAD4 = _is_keyPAD5 = _is_keyPAD6 = _is_keyPAD7 = _is_keyPAD8 = _is_keyPAD9 = _is_keyPADADD = _is_keyPADSUB = _is_keyPADMUL = _is_keyPADDIV = false; _is_event = true; #if cimg_display==1 pthread_cond_broadcast(&cimg::X11_attr().wait_event); #elif cimg_display==2 SetEvent(cimg::Win32_attr().wait_event); #endif return *this; } //! Simulate a keyboard press/release event. /** \param keycode Keycode of the associated key. \param is_pressed Tells if the key is considered as pressed or released. \note Keycode constants are defined in the cimg namespace and are architecture-dependent. Use them to ensure your code stay portable (see cimg::keyESC). **/ CImgDisplay& set_key(const unsigned int keycode, const bool is_pressed=true) { #define _cimg_set_key(k) if (keycode==cimg::key##k) _is_key##k = is_pressed; _cimg_set_key(ESC); _cimg_set_key(F1); _cimg_set_key(F2); _cimg_set_key(F3); _cimg_set_key(F4); _cimg_set_key(F5); _cimg_set_key(F6); _cimg_set_key(F7); _cimg_set_key(F8); _cimg_set_key(F9); _cimg_set_key(F10); _cimg_set_key(F11); _cimg_set_key(F12); _cimg_set_key(PAUSE); _cimg_set_key(1); _cimg_set_key(2); _cimg_set_key(3); _cimg_set_key(4); _cimg_set_key(5); _cimg_set_key(6); _cimg_set_key(7); _cimg_set_key(8); _cimg_set_key(9); _cimg_set_key(0); _cimg_set_key(BACKSPACE); _cimg_set_key(INSERT); _cimg_set_key(HOME); _cimg_set_key(PAGEUP); _cimg_set_key(TAB); _cimg_set_key(Q); _cimg_set_key(W); _cimg_set_key(E); _cimg_set_key(R); _cimg_set_key(T); _cimg_set_key(Y); _cimg_set_key(U); _cimg_set_key(I); _cimg_set_key(O); _cimg_set_key(P); _cimg_set_key(DELETE); _cimg_set_key(END); _cimg_set_key(PAGEDOWN); _cimg_set_key(CAPSLOCK); _cimg_set_key(A); _cimg_set_key(S); _cimg_set_key(D); _cimg_set_key(F); _cimg_set_key(G); _cimg_set_key(H); _cimg_set_key(J); _cimg_set_key(K); _cimg_set_key(L); _cimg_set_key(ENTER); _cimg_set_key(SHIFTLEFT); _cimg_set_key(Z); _cimg_set_key(X); _cimg_set_key(C); _cimg_set_key(V); _cimg_set_key(B); _cimg_set_key(N); _cimg_set_key(M); _cimg_set_key(SHIFTRIGHT); _cimg_set_key(ARROWUP); _cimg_set_key(CTRLLEFT); _cimg_set_key(APPLEFT); _cimg_set_key(ALT); _cimg_set_key(SPACE); _cimg_set_key(ALTGR); _cimg_set_key(APPRIGHT); _cimg_set_key(MENU); _cimg_set_key(CTRLRIGHT); _cimg_set_key(ARROWLEFT); _cimg_set_key(ARROWDOWN); _cimg_set_key(ARROWRIGHT); _cimg_set_key(PAD0); _cimg_set_key(PAD1); _cimg_set_key(PAD2); _cimg_set_key(PAD3); _cimg_set_key(PAD4); _cimg_set_key(PAD5); _cimg_set_key(PAD6); _cimg_set_key(PAD7); _cimg_set_key(PAD8); _cimg_set_key(PAD9); _cimg_set_key(PADADD); _cimg_set_key(PADSUB); _cimg_set_key(PADMUL); _cimg_set_key(PADDIV); if (is_pressed) { if (*_keys) std::memmove((void*)(_keys + 1),(void*)_keys,127*sizeof(unsigned int)); *_keys = keycode; if (*_released_keys) { std::memmove((void*)(_released_keys + 1),(void*)_released_keys,127*sizeof(unsigned int)); *_released_keys = 0; } } else { if (*_keys) { std::memmove((void*)(_keys + 1),(void*)_keys,127*sizeof(unsigned int)); *_keys = 0; } if (*_released_keys) std::memmove((void*)(_released_keys + 1),(void*)_released_keys,127*sizeof(unsigned int)); *_released_keys = keycode; } _is_event = keycode?true:false; if (keycode) { #if cimg_display==1 pthread_cond_broadcast(&cimg::X11_attr().wait_event); #elif cimg_display==2 SetEvent(cimg::Win32_attr().wait_event); #endif } return *this; } //! Flush all display events. /** \note Remove all passed events from the current display. **/ CImgDisplay& flush() { set_key().set_button().set_wheel(); _is_resized = _is_moved = _is_event = false; _fps_timer = _fps_frames = _timer = 0; _fps_fps = 0; return *this; } //! Wait for any user event occuring on the current display. CImgDisplay& wait() { wait(*this); return *this; } //! Wait for a given number of milliseconds since the last call to wait(). /** \param milliseconds Number of milliseconds to wait for. \note Similar to cimg::wait(). **/ CImgDisplay& wait(const unsigned int milliseconds) { cimg::wait(milliseconds,&_timer); return *this; } //! Wait for any event occuring on the display \c disp1. static void wait(CImgDisplay& disp1) { disp1._is_event = false; while (!disp1._is_closed && !disp1._is_event) wait_all(); } //! Wait for any event occuring either on the display \c disp1 or \c disp2. static void wait(CImgDisplay& disp1, CImgDisplay& disp2) { disp1._is_event = disp2._is_event = false; while ((!disp1._is_closed || !disp2._is_closed) && !disp1._is_event && !disp2._is_event) wait_all(); } //! Wait for any event occuring either on the display \c disp1, \c disp2 or \c disp3. static void wait(CImgDisplay& disp1, CImgDisplay& disp2, CImgDisplay& disp3) { disp1._is_event = disp2._is_event = disp3._is_event = false; while ((!disp1._is_closed || !disp2._is_closed || !disp3._is_closed) && !disp1._is_event && !disp2._is_event && !disp3._is_event) wait_all(); } //! Wait for any event occuring either on the display \c disp1, \c disp2, \c disp3 or \c disp4. static void wait(CImgDisplay& disp1, CImgDisplay& disp2, CImgDisplay& disp3, CImgDisplay& disp4) { disp1._is_event = disp2._is_event = disp3._is_event = disp4._is_event = false; while ((!disp1._is_closed || !disp2._is_closed || !disp3._is_closed || !disp4._is_closed) && !disp1._is_event && !disp2._is_event && !disp3._is_event && !disp4._is_event) wait_all(); } //! Wait for any event occuring either on the display \c disp1, \c disp2, \c disp3, \c disp4 or \c disp5. static void wait(CImgDisplay& disp1, CImgDisplay& disp2, CImgDisplay& disp3, CImgDisplay& disp4, CImgDisplay& disp5) { disp1._is_event = disp2._is_event = disp3._is_event = disp4._is_event = disp5._is_event = false; while ((!disp1._is_closed || !disp2._is_closed || !disp3._is_closed || !disp4._is_closed || !disp5._is_closed) && !disp1._is_event && !disp2._is_event && !disp3._is_event && !disp4._is_event && !disp5._is_event) wait_all(); } //! Wait for any event occuring either on the display \c disp1, \c disp2, \c disp3, \c disp4, ... \c disp6. static void wait(CImgDisplay& disp1, CImgDisplay& disp2, CImgDisplay& disp3, CImgDisplay& disp4, CImgDisplay& disp5, CImgDisplay& disp6) { disp1._is_event = disp2._is_event = disp3._is_event = disp4._is_event = disp5._is_event = disp6._is_event = false; while ((!disp1._is_closed || !disp2._is_closed || !disp3._is_closed || !disp4._is_closed || !disp5._is_closed || !disp6._is_closed) && !disp1._is_event && !disp2._is_event && !disp3._is_event && !disp4._is_event && !disp5._is_event && !disp6._is_event) wait_all(); } //! Wait for any event occuring either on the display \c disp1, \c disp2, \c disp3, \c disp4, ... \c disp7. static void wait(CImgDisplay& disp1, CImgDisplay& disp2, CImgDisplay& disp3, CImgDisplay& disp4, CImgDisplay& disp5, CImgDisplay& disp6, CImgDisplay& disp7) { disp1._is_event = disp2._is_event = disp3._is_event = disp4._is_event = disp5._is_event = disp6._is_event = disp7._is_event = false; while ((!disp1._is_closed || !disp2._is_closed || !disp3._is_closed || !disp4._is_closed || !disp5._is_closed || !disp6._is_closed || !disp7._is_closed) && !disp1._is_event && !disp2._is_event && !disp3._is_event && !disp4._is_event && !disp5._is_event && !disp6._is_event && !disp7._is_event) wait_all(); } //! Wait for any event occuring either on the display \c disp1, \c disp2, \c disp3, \c disp4, ... \c disp8. static void wait(CImgDisplay& disp1, CImgDisplay& disp2, CImgDisplay& disp3, CImgDisplay& disp4, CImgDisplay& disp5, CImgDisplay& disp6, CImgDisplay& disp7, CImgDisplay& disp8) { disp1._is_event = disp2._is_event = disp3._is_event = disp4._is_event = disp5._is_event = disp6._is_event = disp7._is_event = disp8._is_event = false; while ((!disp1._is_closed || !disp2._is_closed || !disp3._is_closed || !disp4._is_closed || !disp5._is_closed || !disp6._is_closed || !disp7._is_closed || !disp8._is_closed) && !disp1._is_event && !disp2._is_event && !disp3._is_event && !disp4._is_event && !disp5._is_event && !disp6._is_event && !disp7._is_event && !disp8._is_event) wait_all(); } //! Wait for any event occuring either on the display \c disp1, \c disp2, \c disp3, \c disp4, ... \c disp9. static void wait(CImgDisplay& disp1, CImgDisplay& disp2, CImgDisplay& disp3, CImgDisplay& disp4, CImgDisplay& disp5, CImgDisplay& disp6, CImgDisplay& disp7, CImgDisplay& disp8, CImgDisplay& disp9) { disp1._is_event = disp2._is_event = disp3._is_event = disp4._is_event = disp5._is_event = disp6._is_event = disp7._is_event = disp8._is_event = disp9._is_event = false; while ((!disp1._is_closed || !disp2._is_closed || !disp3._is_closed || !disp4._is_closed || !disp5._is_closed || !disp6._is_closed || !disp7._is_closed || !disp8._is_closed || !disp9._is_closed) && !disp1._is_event && !disp2._is_event && !disp3._is_event && !disp4._is_event && !disp5._is_event && !disp6._is_event && !disp7._is_event && !disp8._is_event && !disp9._is_event) wait_all(); } //! Wait for any event occuring either on the display \c disp1, \c disp2, \c disp3, \c disp4, ... \c disp10. static void wait(CImgDisplay& disp1, CImgDisplay& disp2, CImgDisplay& disp3, CImgDisplay& disp4, CImgDisplay& disp5, CImgDisplay& disp6, CImgDisplay& disp7, CImgDisplay& disp8, CImgDisplay& disp9, CImgDisplay& disp10) { disp1._is_event = disp2._is_event = disp3._is_event = disp4._is_event = disp5._is_event = disp6._is_event = disp7._is_event = disp8._is_event = disp9._is_event = disp10._is_event = false; while ((!disp1._is_closed || !disp2._is_closed || !disp3._is_closed || !disp4._is_closed || !disp5._is_closed || !disp6._is_closed || !disp7._is_closed || !disp8._is_closed || !disp9._is_closed || !disp10._is_closed) && !disp1._is_event && !disp2._is_event && !disp3._is_event && !disp4._is_event && !disp5._is_event && !disp6._is_event && !disp7._is_event && !disp8._is_event && !disp9._is_event && !disp10._is_event) wait_all(); } #if cimg_display==0 //! Wait for any window event occuring in any opened CImgDisplay. static void wait_all() { return _no_display_exception(); } //! Render image into internal display buffer. /** \param img Input image data to render. \note - Convert image data representation into the internal display buffer (architecture-dependent structure). - The content of the associated window is not modified, until paint() is called. - Should not be used for common CImgDisplay uses, since display() is more useful. **/ template<typename T> CImgDisplay& render(const CImg<T>& img) { return assign(img); } //! Paint internal display buffer on associated window. /** \note - Update the content of the associated window with the internal display buffer, e.g. after a render() call. - Should not be used for common CImgDisplay uses, since display() is more useful. **/ CImgDisplay& paint() { return assign(); } //! Take a snapshot of the current screen content. /** \param x0 X-coordinate of the upper left corner. \param y0 Y-coordinate of the upper left corner. \param x1 X-coordinate of the lower right corner. \param y1 Y-coordinate of the lower right corner. \param[out] img Output screenshot. Can be empty on input **/ template<typename T> static void screenshot(const int x0, const int y0, const int x1, const int y1, CImg<T>& img) { cimg::unused(x0,y0,x1,y1,&img); _no_display_exception(); } //! Take a snapshot of the associated window content. /** \param[out] img Output snapshot. Can be empty on input. **/ template<typename T> const CImgDisplay& snapshot(CImg<T>& img) const { cimg::unused(img); _no_display_exception(); return *this; } #endif // X11-based implementation //-------------------------- #if cimg_display==1 Atom _wm_window_atom, _wm_protocol_atom; Window _window, _background_window; Colormap _colormap; XImage *_image; void *_data; #ifdef cimg_use_xshm XShmSegmentInfo *_shminfo; #endif static int screen_width() { Display *const dpy = cimg::X11_attr().display; int res = 0; if (!dpy) { Display *const _dpy = XOpenDisplay(0); if (!_dpy) throw CImgDisplayException("CImgDisplay::screen_width(): Failed to open X11 display."); res = DisplayWidth(_dpy,DefaultScreen(_dpy)); XCloseDisplay(_dpy); } else { #ifdef cimg_use_xrandr if (cimg::X11_attr().resolutions && cimg::X11_attr().curr_resolution) res = cimg::X11_attr().resolutions[cimg::X11_attr().curr_resolution].width; else res = DisplayWidth(dpy,DefaultScreen(dpy)); #else res = DisplayWidth(dpy,DefaultScreen(dpy)); #endif } return res; } static int screen_height() { Display *const dpy = cimg::X11_attr().display; int res = 0; if (!dpy) { Display *const _dpy = XOpenDisplay(0); if (!_dpy) throw CImgDisplayException("CImgDisplay::screen_height(): Failed to open X11 display."); res = DisplayHeight(_dpy,DefaultScreen(_dpy)); XCloseDisplay(_dpy); } else { #ifdef cimg_use_xrandr if (cimg::X11_attr().resolutions && cimg::X11_attr().curr_resolution) res = cimg::X11_attr().resolutions[cimg::X11_attr().curr_resolution].height; else res = DisplayHeight(dpy,DefaultScreen(dpy)); #else res = DisplayHeight(dpy,DefaultScreen(dpy)); #endif } return res; } static void wait_all() { if (!cimg::X11_attr().display) return; pthread_mutex_lock(&cimg::X11_attr().wait_event_mutex); pthread_cond_wait(&cimg::X11_attr().wait_event,&cimg::X11_attr().wait_event_mutex); pthread_mutex_unlock(&cimg::X11_attr().wait_event_mutex); } void _handle_events(const XEvent *const pevent) { Display *const dpy = cimg::X11_attr().display; XEvent event = *pevent; switch (event.type) { case ClientMessage : { if ((int)event.xclient.message_type==(int)_wm_protocol_atom && (int)event.xclient.data.l[0]==(int)_wm_window_atom) { XUnmapWindow(cimg::X11_attr().display,_window); _is_closed = _is_event = true; pthread_cond_broadcast(&cimg::X11_attr().wait_event); } } break; case ConfigureNotify : { while (XCheckWindowEvent(dpy,_window,StructureNotifyMask,&event)) {} const unsigned int nw = event.xconfigure.width, nh = event.xconfigure.height; const int nx = event.xconfigure.x, ny = event.xconfigure.y; if (nw && nh && (nw!=_window_width || nh!=_window_height)) { _window_width = nw; _window_height = nh; _mouse_x = _mouse_y = -1; XResizeWindow(dpy,_window,_window_width,_window_height); _is_resized = _is_event = true; pthread_cond_broadcast(&cimg::X11_attr().wait_event); } if (nx!=_window_x || ny!=_window_y) { _window_x = nx; _window_y = ny; _is_moved = _is_event = true; pthread_cond_broadcast(&cimg::X11_attr().wait_event); } } break; case Expose : { while (XCheckWindowEvent(dpy,_window,ExposureMask,&event)) {} _paint(false); if (_is_fullscreen) { XWindowAttributes attr; XGetWindowAttributes(dpy,_window,&attr); while (attr.map_state!=IsViewable) XSync(dpy,0); XSetInputFocus(dpy,_window,RevertToParent,CurrentTime); } } break; case ButtonPress : { do { _mouse_x = event.xmotion.x; _mouse_y = event.xmotion.y; if (_mouse_x<0 || _mouse_y<0 || _mouse_x>=width() || _mouse_y>=height()) _mouse_x = _mouse_y = -1; switch (event.xbutton.button) { case 1 : set_button(1); break; case 3 : set_button(2); break; case 2 : set_button(3); break; } } while (XCheckWindowEvent(dpy,_window,ButtonPressMask,&event)); } break; case ButtonRelease : { do { _mouse_x = event.xmotion.x; _mouse_y = event.xmotion.y; if (_mouse_x<0 || _mouse_y<0 || _mouse_x>=width() || _mouse_y>=height()) _mouse_x = _mouse_y = -1; switch (event.xbutton.button) { case 1 : set_button(1,false); break; case 3 : set_button(2,false); break; case 2 : set_button(3,false); break; case 4 : set_wheel(1); break; case 5 : set_wheel(-1); break; } } while (XCheckWindowEvent(dpy,_window,ButtonReleaseMask,&event)); } break; case KeyPress : { char tmp = 0; KeySym ksym; XLookupString(&event.xkey,&tmp,1,&ksym,0); set_key((unsigned int)ksym,true); } break; case KeyRelease : { char keys_return[32]; // Check that the key has been physically unpressed XQueryKeymap(dpy,keys_return); const unsigned int kc = event.xkey.keycode, kc1 = kc/8, kc2 = kc%8; const bool is_key_pressed = kc1>=32?false:(keys_return[kc1]>>kc2)&1; if (!is_key_pressed) { char tmp = 0; KeySym ksym; XLookupString(&event.xkey,&tmp,1,&ksym,0); set_key((unsigned int)ksym,false); } } break; case EnterNotify: { while (XCheckWindowEvent(dpy,_window,EnterWindowMask,&event)) {} _mouse_x = event.xmotion.x; _mouse_y = event.xmotion.y; if (_mouse_x<0 || _mouse_y<0 || _mouse_x>=width() || _mouse_y>=height()) _mouse_x = _mouse_y = -1; } break; case LeaveNotify : { while (XCheckWindowEvent(dpy,_window,LeaveWindowMask,&event)) {} _mouse_x = _mouse_y = -1; _is_event = true; pthread_cond_broadcast(&cimg::X11_attr().wait_event); } break; case MotionNotify : { while (XCheckWindowEvent(dpy,_window,PointerMotionMask,&event)) {} _mouse_x = event.xmotion.x; _mouse_y = event.xmotion.y; if (_mouse_x<0 || _mouse_y<0 || _mouse_x>=width() || _mouse_y>=height()) _mouse_x = _mouse_y = -1; _is_event = true; pthread_cond_broadcast(&cimg::X11_attr().wait_event); } break; } } static void* _events_thread(void *arg) { // Thread to manage events for all opened display windows Display *const dpy = cimg::X11_attr().display; XEvent event; pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED,0); pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,0); if (!arg) for ( ; ; ) { cimg_lock_display(); bool event_flag = XCheckTypedEvent(dpy,ClientMessage,&event); if (!event_flag) event_flag = XCheckMaskEvent(dpy, ExposureMask | StructureNotifyMask | ButtonPressMask | KeyPressMask | PointerMotionMask | EnterWindowMask | LeaveWindowMask | ButtonReleaseMask | KeyReleaseMask,&event); if (event_flag) for (unsigned int i = 0; i<cimg::X11_attr().nb_wins; ++i) if (!cimg::X11_attr().wins[i]->_is_closed && event.xany.window==cimg::X11_attr().wins[i]->_window) cimg::X11_attr().wins[i]->_handle_events(&event); cimg_unlock_display(); pthread_testcancel(); cimg::sleep(8); } return 0; } void _set_colormap(Colormap& cmap, const unsigned int dim) { XColor *const colormap = new XColor[256]; switch (dim) { case 1 : { // colormap for greyscale images for (unsigned int index = 0; index<256; ++index) { colormap[index].pixel = index; colormap[index].red = colormap[index].green = colormap[index].blue = (unsigned short)(index<<8); colormap[index].flags = DoRed | DoGreen | DoBlue; } } break; case 2 : { // colormap for RG images for (unsigned int index = 0, r = 8; r<256; r+=16) for (unsigned int g = 8; g<256; g+=16) { colormap[index].pixel = index; colormap[index].red = colormap[index].blue = (unsigned short)(r<<8); colormap[index].green = (unsigned short)(g<<8); colormap[index++].flags = DoRed | DoGreen | DoBlue; } } break; default : { // colormap for RGB images for (unsigned int index = 0, r = 16; r<256; r+=32) for (unsigned int g = 16; g<256; g+=32) for (unsigned int b = 32; b<256; b+=64) { colormap[index].pixel = index; colormap[index].red = (unsigned short)(r<<8); colormap[index].green = (unsigned short)(g<<8); colormap[index].blue = (unsigned short)(b<<8); colormap[index++].flags = DoRed | DoGreen | DoBlue; } } } XStoreColors(cimg::X11_attr().display,cmap,colormap,256); delete[] colormap; } void _map_window() { Display *const dpy = cimg::X11_attr().display; bool is_exposed = false, is_mapped = false; XWindowAttributes attr; XEvent event; XMapRaised(dpy,_window); do { // Wait for the window to be mapped XWindowEvent(dpy,_window,StructureNotifyMask | ExposureMask,&event); switch (event.type) { case MapNotify : is_mapped = true; break; case Expose : is_exposed = true; break; } } while (!is_exposed || !is_mapped); do { // Wait for the window to be visible XGetWindowAttributes(dpy,_window,&attr); if (attr.map_state!=IsViewable) { XSync(dpy,0); cimg::sleep(10); } } while (attr.map_state!=IsViewable); _window_x = attr.x; _window_y = attr.y; } void _paint(const bool wait_expose=true) { if (_is_closed || !_image) return; Display *const dpy = cimg::X11_attr().display; if (wait_expose) { // Send an expose event sticked to display window to force repaint XEvent event; event.xexpose.type = Expose; event.xexpose.serial = 0; event.xexpose.send_event = 1; event.xexpose.display = dpy; event.xexpose.window = _window; event.xexpose.x = 0; event.xexpose.y = 0; event.xexpose.width = width(); event.xexpose.height = height(); event.xexpose.count = 0; XSendEvent(dpy,_window,0,0,&event); } else { // Repaint directly (may be called from the expose event) GC gc = DefaultGC(dpy,DefaultScreen(dpy)); #ifdef cimg_use_xshm if (_shminfo) XShmPutImage(dpy,_window,gc,_image,0,0,0,0,_width,_height,1); else XPutImage(dpy,_window,gc,_image,0,0,0,0,_width,_height); #else XPutImage(dpy,_window,gc,_image,0,0,0,0,_width,_height); #endif } } template<typename T> void _resize(T pixel_type, const unsigned int ndimx, const unsigned int ndimy, const bool force_redraw) { Display *const dpy = cimg::X11_attr().display; cimg::unused(pixel_type); #ifdef cimg_use_xshm if (_shminfo) { XShmSegmentInfo *const nshminfo = new XShmSegmentInfo; XImage *const nimage = XShmCreateImage(dpy,DefaultVisual(dpy,DefaultScreen(dpy)), cimg::X11_attr().nb_bits,ZPixmap,0,nshminfo,ndimx,ndimy); if (!nimage) { delete nshminfo; return; } else { nshminfo->shmid = shmget(IPC_PRIVATE,ndimx*ndimy*sizeof(T),IPC_CREAT | 0777); if (nshminfo->shmid==-1) { XDestroyImage(nimage); delete nshminfo; return; } else { nshminfo->shmaddr = nimage->data = (char*)shmat(nshminfo->shmid,0,0); if (nshminfo->shmaddr==(char*)-1) { shmctl(nshminfo->shmid,IPC_RMID,0); XDestroyImage(nimage); delete nshminfo; return; } else { nshminfo->readOnly = 0; cimg::X11_attr().is_shm_enabled = true; XErrorHandler oldXErrorHandler = XSetErrorHandler(_assign_xshm); XShmAttach(dpy,nshminfo); XFlush(dpy); XSetErrorHandler(oldXErrorHandler); if (!cimg::X11_attr().is_shm_enabled) { shmdt(nshminfo->shmaddr); shmctl(nshminfo->shmid,IPC_RMID,0); XDestroyImage(nimage); delete nshminfo; return; } else { T *const ndata = (T*)nimage->data; if (force_redraw) _render_resize((T*)_data,_width,_height,ndata,ndimx,ndimy); else std::memset(ndata,0,sizeof(T)*ndimx*ndimy); XShmDetach(dpy,_shminfo); XDestroyImage(_image); shmdt(_shminfo->shmaddr); shmctl(_shminfo->shmid,IPC_RMID,0); delete _shminfo; _shminfo = nshminfo; _image = nimage; _data = (void*)ndata; } } } } } else #endif { T *ndata = (T*)std::malloc(ndimx*ndimy*sizeof(T)); if (force_redraw) _render_resize((T*)_data,_width,_height,ndata,ndimx,ndimy); else std::memset(ndata,0,sizeof(T)*ndimx*ndimy); _data = (void*)ndata; XDestroyImage(_image); _image = XCreateImage(dpy,DefaultVisual(dpy,DefaultScreen(dpy)), cimg::X11_attr().nb_bits,ZPixmap,0,(char*)_data,ndimx,ndimy,8,0); } } void _init_fullscreen() { if (!_is_fullscreen || _is_closed) return; Display *const dpy = cimg::X11_attr().display; _background_window = 0; #ifdef cimg_use_xrandr int foo; if (XRRQueryExtension(dpy,&foo,&foo)) { XRRRotations(dpy,DefaultScreen(dpy),&cimg::X11_attr().curr_rotation); if (!cimg::X11_attr().resolutions) { cimg::X11_attr().resolutions = XRRSizes(dpy,DefaultScreen(dpy),&foo); cimg::X11_attr().nb_resolutions = (unsigned int)foo; } if (cimg::X11_attr().resolutions) { cimg::X11_attr().curr_resolution = 0; for (unsigned int i = 0; i<cimg::X11_attr().nb_resolutions; ++i) { const unsigned int nw = (unsigned int)(cimg::X11_attr().resolutions[i].width), nh = (unsigned int)(cimg::X11_attr().resolutions[i].height); if (nw>=_width && nh>=_height && nw<=(unsigned int)(cimg::X11_attr().resolutions[cimg::X11_attr().curr_resolution].width) && nh<=(unsigned int)(cimg::X11_attr().resolutions[cimg::X11_attr().curr_resolution].height)) cimg::X11_attr().curr_resolution = i; } if (cimg::X11_attr().curr_resolution>0) { XRRScreenConfiguration *config = XRRGetScreenInfo(dpy,DefaultRootWindow(dpy)); XRRSetScreenConfig(dpy,config,DefaultRootWindow(dpy), cimg::X11_attr().curr_resolution,cimg::X11_attr().curr_rotation,CurrentTime); XRRFreeScreenConfigInfo(config); XSync(dpy,0); } } } if (!cimg::X11_attr().resolutions) cimg::warn(_cimgdisplay_instance "init_fullscreen(): Xrandr extension not supported by the X server.", cimgdisplay_instance); #endif const unsigned int sx = screen_width(), sy = screen_height(); if (sx==_width && sy==_height) return; XSetWindowAttributes winattr; winattr.override_redirect = 1; _background_window = XCreateWindow(dpy,DefaultRootWindow(dpy),0,0,sx,sy,0,0, InputOutput,CopyFromParent,CWOverrideRedirect,&winattr); const cimg_ulong buf_size = (cimg_ulong)sx*sy*(cimg::X11_attr().nb_bits==8?1: (cimg::X11_attr().nb_bits==16?2:4)); void *background_data = std::malloc(buf_size); std::memset(background_data,0,buf_size); XImage *background_image = XCreateImage(dpy,DefaultVisual(dpy,DefaultScreen(dpy)),cimg::X11_attr().nb_bits, ZPixmap,0,(char*)background_data,sx,sy,8,0); XEvent event; XSelectInput(dpy,_background_window,StructureNotifyMask); XMapRaised(dpy,_background_window); do XWindowEvent(dpy,_background_window,StructureNotifyMask,&event); while (event.type!=MapNotify); GC gc = DefaultGC(dpy,DefaultScreen(dpy)); #ifdef cimg_use_xshm if (_shminfo) XShmPutImage(dpy,_background_window,gc,background_image,0,0,0,0,sx,sy,0); else XPutImage(dpy,_background_window,gc,background_image,0,0,0,0,sx,sy); #else XPutImage(dpy,_background_window,gc,background_image,0,0,0,0,sx,sy); #endif XWindowAttributes attr; XGetWindowAttributes(dpy,_background_window,&attr); while (attr.map_state!=IsViewable) XSync(dpy,0); XDestroyImage(background_image); } void _desinit_fullscreen() { if (!_is_fullscreen) return; Display *const dpy = cimg::X11_attr().display; XUngrabKeyboard(dpy,CurrentTime); #ifdef cimg_use_xrandr if (cimg::X11_attr().resolutions && cimg::X11_attr().curr_resolution) { XRRScreenConfiguration *config = XRRGetScreenInfo(dpy,DefaultRootWindow(dpy)); XRRSetScreenConfig(dpy,config,DefaultRootWindow(dpy),0,cimg::X11_attr().curr_rotation,CurrentTime); XRRFreeScreenConfigInfo(config); XSync(dpy,0); cimg::X11_attr().curr_resolution = 0; } #endif if (_background_window) XDestroyWindow(dpy,_background_window); _background_window = 0; _is_fullscreen = false; } static int _assign_xshm(Display *dpy, XErrorEvent *error) { cimg::unused(dpy,error); cimg::X11_attr().is_shm_enabled = false; return 0; } void _assign(const unsigned int dimw, const unsigned int dimh, const char *const ptitle=0, const unsigned int normalization_type=3, const bool fullscreen_flag=false, const bool closed_flag=false) { cimg::mutex(14); // Allocate space for window title const char *const nptitle = ptitle?ptitle:""; const unsigned int s = (unsigned int)std::strlen(nptitle) + 1; char *const tmp_title = s?new char[s]:0; if (s) std::memcpy(tmp_title,nptitle,s*sizeof(char)); // Destroy previous display window if existing if (!is_empty()) assign(); // Open X11 display and retrieve graphical properties. Display* &dpy = cimg::X11_attr().display; if (!dpy) { dpy = XOpenDisplay(0); if (!dpy) throw CImgDisplayException(_cimgdisplay_instance "assign(): Failed to open X11 display.", cimgdisplay_instance); cimg::X11_attr().nb_bits = DefaultDepth(dpy,DefaultScreen(dpy)); if (cimg::X11_attr().nb_bits!=8 && cimg::X11_attr().nb_bits!=16 && cimg::X11_attr().nb_bits!=24 && cimg::X11_attr().nb_bits!=32) throw CImgDisplayException(_cimgdisplay_instance "assign(): Invalid %u bits screen mode detected " "(only 8, 16, 24 and 32 bits modes are managed).", cimgdisplay_instance, cimg::X11_attr().nb_bits); XVisualInfo vtemplate; vtemplate.visualid = XVisualIDFromVisual(DefaultVisual(dpy,DefaultScreen(dpy))); int nb_visuals; XVisualInfo *vinfo = XGetVisualInfo(dpy,VisualIDMask,&vtemplate,&nb_visuals); if (vinfo && vinfo->red_mask<vinfo->blue_mask) cimg::X11_attr().is_blue_first = true; cimg::X11_attr().byte_order = ImageByteOrder(dpy); XFree(vinfo); cimg_lock_display(); cimg::X11_attr().events_thread = new pthread_t; pthread_create(cimg::X11_attr().events_thread,0,_events_thread,0); } else cimg_lock_display(); // Set display variables. _width = std::min(dimw,(unsigned int)screen_width()); _height = std::min(dimh,(unsigned int)screen_height()); _normalization = normalization_type<4?normalization_type:3; _is_fullscreen = fullscreen_flag; _window_x = _window_y = 0; _is_closed = closed_flag; _title = tmp_title; flush(); // Create X11 window (and LUT, if 8bits display) if (_is_fullscreen) { if (!_is_closed) _init_fullscreen(); const unsigned int sx = screen_width(), sy = screen_height(); XSetWindowAttributes winattr; winattr.override_redirect = 1; _window = XCreateWindow(dpy,DefaultRootWindow(dpy),(sx - _width)/2,(sy - _height)/2,_width,_height,0,0, InputOutput,CopyFromParent,CWOverrideRedirect,&winattr); } else _window = XCreateSimpleWindow(dpy,DefaultRootWindow(dpy),0,0,_width,_height,0,0L,0L); XSelectInput(dpy,_window, ExposureMask | StructureNotifyMask | ButtonPressMask | KeyPressMask | PointerMotionMask | EnterWindowMask | LeaveWindowMask | ButtonReleaseMask | KeyReleaseMask); XStoreName(dpy,_window,_title?_title:" "); if (cimg::X11_attr().nb_bits==8) { _colormap = XCreateColormap(dpy,_window,DefaultVisual(dpy,DefaultScreen(dpy)),AllocAll); _set_colormap(_colormap,3); XSetWindowColormap(dpy,_window,_colormap); } static const char *const _window_class = cimg_appname; XClassHint *const window_class = XAllocClassHint(); window_class->res_name = (char*)_window_class; window_class->res_class = (char*)_window_class; XSetClassHint(dpy,_window,window_class); XFree(window_class); _window_width = _width; _window_height = _height; // Create XImage #ifdef cimg_use_xshm _shminfo = 0; if (XShmQueryExtension(dpy)) { _shminfo = new XShmSegmentInfo; _image = XShmCreateImage(dpy,DefaultVisual(dpy,DefaultScreen(dpy)),cimg::X11_attr().nb_bits, ZPixmap,0,_shminfo,_width,_height); if (!_image) { delete _shminfo; _shminfo = 0; } else { _shminfo->shmid = shmget(IPC_PRIVATE,_image->bytes_per_line*_image->height,IPC_CREAT|0777); if (_shminfo->shmid==-1) { XDestroyImage(_image); delete _shminfo; _shminfo = 0; } else { _shminfo->shmaddr = _image->data = (char*)(_data = shmat(_shminfo->shmid,0,0)); if (_shminfo->shmaddr==(char*)-1) { shmctl(_shminfo->shmid,IPC_RMID,0); XDestroyImage(_image); delete _shminfo; _shminfo = 0; } else { _shminfo->readOnly = 0; cimg::X11_attr().is_shm_enabled = true; XErrorHandler oldXErrorHandler = XSetErrorHandler(_assign_xshm); XShmAttach(dpy,_shminfo); XSync(dpy,0); XSetErrorHandler(oldXErrorHandler); if (!cimg::X11_attr().is_shm_enabled) { shmdt(_shminfo->shmaddr); shmctl(_shminfo->shmid,IPC_RMID,0); XDestroyImage(_image); delete _shminfo; _shminfo = 0; } } } } } if (!_shminfo) #endif { const cimg_ulong buf_size = (cimg_ulong)_width*_height*(cimg::X11_attr().nb_bits==8?1: (cimg::X11_attr().nb_bits==16?2:4)); _data = std::malloc(buf_size); _image = XCreateImage(dpy,DefaultVisual(dpy,DefaultScreen(dpy)),cimg::X11_attr().nb_bits, ZPixmap,0,(char*)_data,_width,_height,8,0); } _wm_window_atom = XInternAtom(dpy,"WM_DELETE_WINDOW",0); _wm_protocol_atom = XInternAtom(dpy,"WM_PROTOCOLS",0); XSetWMProtocols(dpy,_window,&_wm_window_atom,1); if (_is_fullscreen) XGrabKeyboard(dpy,_window,1,GrabModeAsync,GrabModeAsync,CurrentTime); cimg::X11_attr().wins[cimg::X11_attr().nb_wins++]=this; if (!_is_closed) _map_window(); else { _window_x = _window_y = cimg::type<int>::min(); } cimg_unlock_display(); cimg::mutex(14,0); } CImgDisplay& assign() { if (is_empty()) return flush(); Display *const dpy = cimg::X11_attr().display; cimg_lock_display(); // Remove display window from event thread list. unsigned int i; for (i = 0; i<cimg::X11_attr().nb_wins && cimg::X11_attr().wins[i]!=this; ++i) {} for ( ; i<cimg::X11_attr().nb_wins - 1; ++i) cimg::X11_attr().wins[i] = cimg::X11_attr().wins[i + 1]; --cimg::X11_attr().nb_wins; // Destroy window, image, colormap and title. if (_is_fullscreen && !_is_closed) _desinit_fullscreen(); XDestroyWindow(dpy,_window); _window = 0; #ifdef cimg_use_xshm if (_shminfo) { XShmDetach(dpy,_shminfo); XDestroyImage(_image); shmdt(_shminfo->shmaddr); shmctl(_shminfo->shmid,IPC_RMID,0); delete _shminfo; _shminfo = 0; } else #endif XDestroyImage(_image); _data = 0; _image = 0; if (cimg::X11_attr().nb_bits==8) XFreeColormap(dpy,_colormap); _colormap = 0; XSync(dpy,0); // Reset display variables. delete[] _title; _width = _height = _normalization = _window_width = _window_height = 0; _window_x = _window_y = 0; _is_fullscreen = false; _is_closed = true; _min = _max = 0; _title = 0; flush(); cimg_unlock_display(); return *this; } CImgDisplay& assign(const unsigned int dimw, const unsigned int dimh, const char *const title=0, const unsigned int normalization_type=3, const bool fullscreen_flag=false, const bool closed_flag=false) { if (!dimw || !dimh) return assign(); _assign(dimw,dimh,title,normalization_type,fullscreen_flag,closed_flag); _min = _max = 0; std::memset(_data,0,(cimg::X11_attr().nb_bits==8?sizeof(unsigned char): (cimg::X11_attr().nb_bits==16?sizeof(unsigned short):sizeof(unsigned int)))* (size_t)_width*_height); return paint(); } template<typename T> CImgDisplay& assign(const CImg<T>& img, const char *const title=0, const unsigned int normalization_type=3, const bool fullscreen_flag=false, const bool closed_flag=false) { if (!img) return assign(); CImg<T> tmp; const CImg<T>& nimg = (img._depth==1)?img:(tmp=img.get_projections2d((img._width - 1)/2, (img._height - 1)/2, (img._depth - 1)/2)); _assign(nimg._width,nimg._height,title,normalization_type,fullscreen_flag,closed_flag); if (_normalization==2) _min = (float)nimg.min_max(_max); return render(nimg).paint(); } template<typename T> CImgDisplay& assign(const CImgList<T>& list, const char *const title=0, const unsigned int normalization_type=3, const bool fullscreen_flag=false, const bool closed_flag=false) { if (!list) return assign(); CImg<T> tmp; const CImg<T> img = list>'x', &nimg = (img._depth==1)?img:(tmp=img.get_projections2d((img._width - 1)/2, (img._height - 1)/2, (img._depth - 1)/2)); _assign(nimg._width,nimg._height,title,normalization_type,fullscreen_flag,closed_flag); if (_normalization==2) _min = (float)nimg.min_max(_max); return render(nimg).paint(); } CImgDisplay& assign(const CImgDisplay& disp) { if (!disp) return assign(); _assign(disp._width,disp._height,disp._title,disp._normalization,disp._is_fullscreen,disp._is_closed); std::memcpy(_data,disp._data,(cimg::X11_attr().nb_bits==8?sizeof(unsigned char): cimg::X11_attr().nb_bits==16?sizeof(unsigned short): sizeof(unsigned int))*(size_t)_width*_height); return paint(); } CImgDisplay& resize(const int nwidth, const int nheight, const bool force_redraw=true) { if (!nwidth || !nheight || (is_empty() && (nwidth<0 || nheight<0))) return assign(); if (is_empty()) return assign(nwidth,nheight); Display *const dpy = cimg::X11_attr().display; const unsigned int tmpdimx = (nwidth>0)?nwidth:(-nwidth*width()/100), tmpdimy = (nheight>0)?nheight:(-nheight*height()/100), dimx = tmpdimx?tmpdimx:1, dimy = tmpdimy?tmpdimy:1; if (_width!=dimx || _height!=dimy || _window_width!=dimx || _window_height!=dimy) { show(); cimg_lock_display(); if (_window_width!=dimx || _window_height!=dimy) { XWindowAttributes attr; for (unsigned int i = 0; i<10; ++i) { XResizeWindow(dpy,_window,dimx,dimy); XGetWindowAttributes(dpy,_window,&attr); if (attr.width==(int)dimx && attr.height==(int)dimy) break; cimg::wait(5,&_timer); } } if (_width!=dimx || _height!=dimy) switch (cimg::X11_attr().nb_bits) { case 8 : { unsigned char pixel_type = 0; _resize(pixel_type,dimx,dimy,force_redraw); } break; case 16 : { unsigned short pixel_type = 0; _resize(pixel_type,dimx,dimy,force_redraw); } break; default : { unsigned int pixel_type = 0; _resize(pixel_type,dimx,dimy,force_redraw); } } _window_width = _width = dimx; _window_height = _height = dimy; cimg_unlock_display(); } _is_resized = false; if (_is_fullscreen) move((screen_width() - _width)/2,(screen_height() - _height)/2); if (force_redraw) return paint(); return *this; } CImgDisplay& toggle_fullscreen(const bool force_redraw=true) { if (is_empty()) return *this; if (force_redraw) { const cimg_ulong buf_size = (cimg_ulong)_width*_height* (cimg::X11_attr().nb_bits==8?1:(cimg::X11_attr().nb_bits==16?2:4)); void *image_data = std::malloc(buf_size); std::memcpy(image_data,_data,buf_size); assign(_width,_height,_title,_normalization,!_is_fullscreen,false); std::memcpy(_data,image_data,buf_size); std::free(image_data); return paint(); } return assign(_width,_height,_title,_normalization,!_is_fullscreen,false); } CImgDisplay& show() { if (is_empty() || !_is_closed) return *this; cimg_lock_display(); if (_is_fullscreen) _init_fullscreen(); _map_window(); _is_closed = false; cimg_unlock_display(); return paint(); } CImgDisplay& close() { if (is_empty() || _is_closed) return *this; Display *const dpy = cimg::X11_attr().display; cimg_lock_display(); if (_is_fullscreen) _desinit_fullscreen(); XUnmapWindow(dpy,_window); _window_x = _window_y = -1; _is_closed = true; cimg_unlock_display(); return *this; } CImgDisplay& move(const int posx, const int posy) { if (is_empty()) return *this; if (_window_x!=posx || _window_y!=posy) { show(); Display *const dpy = cimg::X11_attr().display; cimg_lock_display(); XMoveWindow(dpy,_window,posx,posy); _window_x = posx; _window_y = posy; cimg_unlock_display(); } _is_moved = false; return paint(); } CImgDisplay& show_mouse() { if (is_empty()) return *this; Display *const dpy = cimg::X11_attr().display; cimg_lock_display(); XUndefineCursor(dpy,_window); cimg_unlock_display(); return *this; } CImgDisplay& hide_mouse() { if (is_empty()) return *this; Display *const dpy = cimg::X11_attr().display; cimg_lock_display(); static const char pix_data[8] = { 0 }; XColor col; col.red = col.green = col.blue = 0; Pixmap pix = XCreateBitmapFromData(dpy,_window,pix_data,8,8); Cursor cur = XCreatePixmapCursor(dpy,pix,pix,&col,&col,0,0); XFreePixmap(dpy,pix); XDefineCursor(dpy,_window,cur); cimg_unlock_display(); return *this; } CImgDisplay& set_mouse(const int posx, const int posy) { if (is_empty() || _is_closed) return *this; Display *const dpy = cimg::X11_attr().display; cimg_lock_display(); XWarpPointer(dpy,0L,_window,0,0,0,0,posx,posy); _mouse_x = posx; _mouse_y = posy; _is_moved = false; XSync(dpy,0); cimg_unlock_display(); return *this; } CImgDisplay& set_title(const char *const format, ...) { if (is_empty()) return *this; char *const tmp = new char[1024]; va_list ap; va_start(ap, format); cimg_vsnprintf(tmp,1024,format,ap); va_end(ap); if (!std::strcmp(_title,tmp)) { delete[] tmp; return *this; } delete[] _title; const unsigned int s = (unsigned int)std::strlen(tmp) + 1; _title = new char[s]; std::memcpy(_title,tmp,s*sizeof(char)); Display *const dpy = cimg::X11_attr().display; cimg_lock_display(); XStoreName(dpy,_window,tmp); cimg_unlock_display(); delete[] tmp; return *this; } template<typename T> CImgDisplay& display(const CImg<T>& img) { if (!img) throw CImgArgumentException(_cimgdisplay_instance "display(): Empty specified image.", cimgdisplay_instance); if (is_empty()) return assign(img); return render(img).paint(false); } CImgDisplay& paint(const bool wait_expose=true) { if (is_empty()) return *this; cimg_lock_display(); _paint(wait_expose); cimg_unlock_display(); return *this; } template<typename T> CImgDisplay& render(const CImg<T>& img, const bool flag8=false) { if (!img) throw CImgArgumentException(_cimgdisplay_instance "render(): Empty specified image.", cimgdisplay_instance); if (is_empty()) return *this; if (img._depth!=1) return render(img.get_projections2d((img._width - 1)/2,(img._height - 1)/2, (img._depth - 1)/2)); if (cimg::X11_attr().nb_bits==8 && (img._width!=_width || img._height!=_height)) return render(img.get_resize(_width,_height,1,-100,1)); if (cimg::X11_attr().nb_bits==8 && !flag8 && img._spectrum==3) { static const CImg<typename CImg<T>::ucharT> default_colormap = CImg<typename CImg<T>::ucharT>::default_LUT256(); return render(img.get_index(default_colormap,1,false)); } const T *data1 = img._data, *data2 = (img._spectrum>1)?img.data(0,0,0,1):data1, *data3 = (img._spectrum>2)?img.data(0,0,0,2):data1; if (cimg::X11_attr().is_blue_first) cimg::swap(data1,data3); cimg_lock_display(); if (!_normalization || (_normalization==3 && cimg::type<T>::string()==cimg::type<unsigned char>::string())) { _min = _max = 0; switch (cimg::X11_attr().nb_bits) { case 8 : { // 256 colormap, no normalization _set_colormap(_colormap,img._spectrum); unsigned char *const ndata = (img._width==_width && img._height==_height)?(unsigned char*)_data: new unsigned char[(size_t)img._width*img._height], *ptrd = (unsigned char*)ndata; switch (img._spectrum) { case 1 : for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) (*ptrd++) = (unsigned char)*(data1++); break; case 2 : for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char R = (unsigned char)*(data1++), G = (unsigned char)*(data2++); (*ptrd++) = (R&0xf0) | (G>>4); } break; default : for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char R = (unsigned char)*(data1++), G = (unsigned char)*(data2++), B = (unsigned char)*(data3++); (*ptrd++) = (R&0xe0) | ((G>>5)<<2) | (B>>6); } } if (ndata!=_data) { _render_resize(ndata,img._width,img._height,(unsigned char*)_data,_width,_height); delete[] ndata; } } break; case 16 : { // 16 bits colors, no normalization unsigned short *const ndata = (img._width==_width && img._height==_height)?(unsigned short*)_data: new unsigned short[(size_t)img._width*img._height]; unsigned char *ptrd = (unsigned char*)ndata; const unsigned int M = 248; switch (img._spectrum) { case 1 : if (cimg::X11_attr().byte_order) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)*(data1++), G = val>>2; ptrd[0] = (val&M) | (G>>3); ptrd[1] = (G<<5) | (G>>1); ptrd+=2; } else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)*(data1++), G = val>>2; ptrd[0] = (G<<5) | (G>>1); ptrd[1] = (val&M) | (G>>3); ptrd+=2; } break; case 2 : if (cimg::X11_attr().byte_order) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char G = (unsigned char)*(data2++)>>2; ptrd[0] = ((unsigned char)*(data1++)&M) | (G>>3); ptrd[1] = (G<<5); ptrd+=2; } else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char G = (unsigned char)*(data2++)>>2; ptrd[0] = (G<<5); ptrd[1] = ((unsigned char)*(data1++)&M) | (G>>3); ptrd+=2; } break; default : if (cimg::X11_attr().byte_order) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char G = (unsigned char)*(data2++)>>2; ptrd[0] = ((unsigned char)*(data1++)&M) | (G>>3); ptrd[1] = (G<<5) | ((unsigned char)*(data3++)>>3); ptrd+=2; } else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char G = (unsigned char)*(data2++)>>2; ptrd[0] = (G<<5) | ((unsigned char)*(data3++)>>3); ptrd[1] = ((unsigned char)*(data1++)&M) | (G>>3); ptrd+=2; } } if (ndata!=_data) { _render_resize(ndata,img._width,img._height,(unsigned short*)_data,_width,_height); delete[] ndata; } } break; default : { // 24 bits colors, no normalization unsigned int *const ndata = (img._width==_width && img._height==_height)?(unsigned int*)_data: new unsigned int[(size_t)img._width*img._height]; if (sizeof(int)==4) { // 32 bits int uses optimized version unsigned int *ptrd = ndata; switch (img._spectrum) { case 1 : if (cimg::X11_attr().byte_order==cimg::endianness()) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)*(data1++); *(ptrd++) = (val<<16) | (val<<8) | val; } else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)*(data1++); *(ptrd++) = (val<<16) | (val<<8) | val; } break; case 2 : if (cimg::X11_attr().byte_order==cimg::endianness()) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) *(ptrd++) = ((unsigned char)*(data1++)<<16) | ((unsigned char)*(data2++)<<8); else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) *(ptrd++) = ((unsigned char)*(data2++)<<16) | ((unsigned char)*(data1++)<<8); break; default : if (cimg::X11_attr().byte_order==cimg::endianness()) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) *(ptrd++) = ((unsigned char)*(data1++)<<16) | ((unsigned char)*(data2++)<<8) | (unsigned char)*(data3++); else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) *(ptrd++) = ((unsigned char)*(data3++)<<24) | ((unsigned char)*(data2++)<<16) | ((unsigned char)*(data1++)<<8); } } else { unsigned char *ptrd = (unsigned char*)ndata; switch (img._spectrum) { case 1 : if (cimg::X11_attr().byte_order) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { ptrd[0] = 0; ptrd[1] = (unsigned char)*(data1++); ptrd[2] = 0; ptrd[3] = 0; ptrd+=4; } else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { ptrd[0] = 0; ptrd[1] = 0; ptrd[2] = (unsigned char)*(data1++); ptrd[3] = 0; ptrd+=4; } break; case 2 : if (cimg::X11_attr().byte_order) cimg::swap(data1,data2); for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { ptrd[0] = 0; ptrd[1] = (unsigned char)*(data2++); ptrd[2] = (unsigned char)*(data1++); ptrd[3] = 0; ptrd+=4; } break; default : if (cimg::X11_attr().byte_order) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { ptrd[0] = 0; ptrd[1] = (unsigned char)*(data1++); ptrd[2] = (unsigned char)*(data2++); ptrd[3] = (unsigned char)*(data3++); ptrd+=4; } else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { ptrd[0] = (unsigned char)*(data3++); ptrd[1] = (unsigned char)*(data2++); ptrd[2] = (unsigned char)*(data1++); ptrd[3] = 0; ptrd+=4; } } } if (ndata!=_data) { _render_resize(ndata,img._width,img._height,(unsigned int*)_data,_width,_height); delete[] ndata; } } } } else { if (_normalization==3) { if (cimg::type<T>::is_float()) _min = (float)img.min_max(_max); else { _min = (float)cimg::type<T>::min(); _max = (float)cimg::type<T>::max(); } } else if ((_min>_max) || _normalization==1) _min = (float)img.min_max(_max); const float delta = _max - _min, mm = 255/(delta?delta:1.f); switch (cimg::X11_attr().nb_bits) { case 8 : { // 256 colormap, with normalization _set_colormap(_colormap,img._spectrum); unsigned char *const ndata = (img._width==_width && img._height==_height)?(unsigned char*)_data: new unsigned char[(size_t)img._width*img._height]; unsigned char *ptrd = (unsigned char*)ndata; switch (img._spectrum) { case 1 : for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char R = (unsigned char)((*(data1++) - _min)*mm); *(ptrd++) = R; } break; case 2 : for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char R = (unsigned char)((*(data1++) - _min)*mm), G = (unsigned char)((*(data2++) - _min)*mm); (*ptrd++) = (R&0xf0) | (G>>4); } break; default : for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char R = (unsigned char)((*(data1++) - _min)*mm), G = (unsigned char)((*(data2++) - _min)*mm), B = (unsigned char)((*(data3++) - _min)*mm); *(ptrd++) = (R&0xe0) | ((G>>5)<<2) | (B>>6); } } if (ndata!=_data) { _render_resize(ndata,img._width,img._height,(unsigned char*)_data,_width,_height); delete[] ndata; } } break; case 16 : { // 16 bits colors, with normalization unsigned short *const ndata = (img._width==_width && img._height==_height)?(unsigned short*)_data: new unsigned short[(size_t)img._width*img._height]; unsigned char *ptrd = (unsigned char*)ndata; const unsigned int M = 248; switch (img._spectrum) { case 1 : if (cimg::X11_attr().byte_order) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)((*(data1++) - _min)*mm), G = val>>2; ptrd[0] = (val&M) | (G>>3); ptrd[1] = (G<<5) | (val>>3); ptrd+=2; } else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)((*(data1++) - _min)*mm), G = val>>2; ptrd[0] = (G<<5) | (val>>3); ptrd[1] = (val&M) | (G>>3); ptrd+=2; } break; case 2 : if (cimg::X11_attr().byte_order) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char G = (unsigned char)((*(data2++) - _min)*mm)>>2; ptrd[0] = ((unsigned char)((*(data1++) - _min)*mm)&M) | (G>>3); ptrd[1] = (G<<5); ptrd+=2; } else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char G = (unsigned char)((*(data2++) - _min)*mm)>>2; ptrd[0] = (G<<5); ptrd[1] = ((unsigned char)((*(data1++) - _min)*mm)&M) | (G>>3); ptrd+=2; } break; default : if (cimg::X11_attr().byte_order) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char G = (unsigned char)((*(data2++) - _min)*mm)>>2; ptrd[0] = ((unsigned char)((*(data1++) - _min)*mm)&M) | (G>>3); ptrd[1] = (G<<5) | ((unsigned char)((*(data3++) - _min)*mm)>>3); ptrd+=2; } else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char G = (unsigned char)((*(data2++) - _min)*mm)>>2; ptrd[0] = (G<<5) | ((unsigned char)((*(data3++) - _min)*mm)>>3); ptrd[1] = ((unsigned char)((*(data1++) - _min)*mm)&M) | (G>>3); ptrd+=2; } } if (ndata!=_data) { _render_resize(ndata,img._width,img._height,(unsigned short*)_data,_width,_height); delete[] ndata; } } break; default : { // 24 bits colors, with normalization unsigned int *const ndata = (img._width==_width && img._height==_height)?(unsigned int*)_data: new unsigned int[(size_t)img._width*img._height]; if (sizeof(int)==4) { // 32 bits int uses optimized version unsigned int *ptrd = ndata; switch (img._spectrum) { case 1 : if (cimg::X11_attr().byte_order==cimg::endianness()) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)((*(data1++) - _min)*mm); *(ptrd++) = (val<<16) | (val<<8) | val; } else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)((*(data1++) - _min)*mm); *(ptrd++) = (val<<24) | (val<<16) | (val<<8); } break; case 2 : if (cimg::X11_attr().byte_order==cimg::endianness()) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) *(ptrd++) = ((unsigned char)((*(data1++) - _min)*mm)<<16) | ((unsigned char)((*(data2++) - _min)*mm)<<8); else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) *(ptrd++) = ((unsigned char)((*(data2++) - _min)*mm)<<16) | ((unsigned char)((*(data1++) - _min)*mm)<<8); break; default : if (cimg::X11_attr().byte_order==cimg::endianness()) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) *(ptrd++) = ((unsigned char)((*(data1++) - _min)*mm)<<16) | ((unsigned char)((*(data2++) - _min)*mm)<<8) | (unsigned char)((*(data3++) - _min)*mm); else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) *(ptrd++) = ((unsigned char)((*(data3++) - _min)*mm)<<24) | ((unsigned char)((*(data2++) - _min)*mm)<<16) | ((unsigned char)((*(data1++) - _min)*mm)<<8); } } else { unsigned char *ptrd = (unsigned char*)ndata; switch (img._spectrum) { case 1 : if (cimg::X11_attr().byte_order) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)((*(data1++) - _min)*mm); ptrd[0] = 0; ptrd[1] = val; ptrd[2] = val; ptrd[3] = val; ptrd+=4; } else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)((*(data1++) - _min)*mm); ptrd[0] = val; ptrd[1] = val; ptrd[2] = val; ptrd[3] = 0; ptrd+=4; } break; case 2 : if (cimg::X11_attr().byte_order) cimg::swap(data1,data2); for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { ptrd[0] = 0; ptrd[1] = (unsigned char)((*(data2++) - _min)*mm); ptrd[2] = (unsigned char)((*(data1++) - _min)*mm); ptrd[3] = 0; ptrd+=4; } break; default : if (cimg::X11_attr().byte_order) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { ptrd[0] = 0; ptrd[1] = (unsigned char)((*(data1++) - _min)*mm); ptrd[2] = (unsigned char)((*(data2++) - _min)*mm); ptrd[3] = (unsigned char)((*(data3++) - _min)*mm); ptrd+=4; } else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { ptrd[0] = (unsigned char)((*(data3++) - _min)*mm); ptrd[1] = (unsigned char)((*(data2++) - _min)*mm); ptrd[2] = (unsigned char)((*(data1++) - _min)*mm); ptrd[3] = 0; ptrd+=4; } } } if (ndata!=_data) { _render_resize(ndata,img._width,img._height,(unsigned int*)_data,_width,_height); delete[] ndata; } } } } cimg_unlock_display(); return *this; } template<typename T> static void screenshot(const int x0, const int y0, const int x1, const int y1, CImg<T>& img) { img.assign(); Display *dpy = cimg::X11_attr().display; cimg_lock_display(); if (!dpy) { dpy = XOpenDisplay(0); if (!dpy) throw CImgDisplayException("CImgDisplay::screenshot(): Failed to open X11 display."); } Window root = DefaultRootWindow(dpy); XWindowAttributes gwa; XGetWindowAttributes(dpy,root,&gwa); const int width = gwa.width, height = gwa.height; int _x0 = x0, _y0 = y0, _x1 = x1, _y1 = y1; if (_x0>_x1) cimg::swap(_x0,_x1); if (_y0>_y1) cimg::swap(_y0,_y1); XImage *image = 0; if (_x1>=0 && _x0<width && _y1>=0 && _y0<height) { _x0 = std::max(_x0,0); _y0 = std::max(_y0,0); _x1 = std::min(_x1,width - 1); _y1 = std::min(_y1,height - 1); image = XGetImage(dpy,root,_x0,_y0,_x1 - _x0 + 1,_y1 - _y0 + 1,AllPlanes,ZPixmap); if (image) { const unsigned long red_mask = image->red_mask, green_mask = image->green_mask, blue_mask = image->blue_mask; img.assign(image->width,image->height,1,3); T *pR = img.data(0,0,0,0), *pG = img.data(0,0,0,1), *pB = img.data(0,0,0,2); cimg_forXY(img,x,y) { const unsigned long pixel = XGetPixel(image,x,y); *(pR++) = (T)((pixel & red_mask)>>16); *(pG++) = (T)((pixel & green_mask)>>8); *(pB++) = (T)(pixel & blue_mask); } XDestroyImage(image); } } if (!cimg::X11_attr().display) XCloseDisplay(dpy); cimg_unlock_display(); if (img.is_empty()) throw CImgDisplayException("CImgDisplay::screenshot(): Failed to take screenshot " "with coordinates (%d,%d)-(%d,%d).", x0,y0,x1,y1); } template<typename T> const CImgDisplay& snapshot(CImg<T>& img) const { if (is_empty()) { img.assign(); return *this; } const unsigned char *ptrs = (unsigned char*)_data; img.assign(_width,_height,1,3); T *data1 = img.data(0,0,0,0), *data2 = img.data(0,0,0,1), *data3 = img.data(0,0,0,2); if (cimg::X11_attr().is_blue_first) cimg::swap(data1,data3); switch (cimg::X11_attr().nb_bits) { case 8 : { for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char val = *(ptrs++); *(data1++) = (T)(val&0xe0); *(data2++) = (T)((val&0x1c)<<3); *(data3++) = (T)(val<<6); } } break; case 16 : { if (cimg::X11_attr().byte_order) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char val0 = ptrs[0], val1 = ptrs[1]; ptrs+=2; *(data1++) = (T)(val0&0xf8); *(data2++) = (T)((val0<<5) | ((val1&0xe0)>>5)); *(data3++) = (T)(val1<<3); } else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned short val0 = ptrs[0], val1 = ptrs[1]; ptrs+=2; *(data1++) = (T)(val1&0xf8); *(data2++) = (T)((val1<<5) | ((val0&0xe0)>>5)); *(data3++) = (T)(val0<<3); } } break; default : { if (cimg::X11_attr().byte_order) for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { ++ptrs; *(data1++) = (T)ptrs[0]; *(data2++) = (T)ptrs[1]; *(data3++) = (T)ptrs[2]; ptrs+=3; } else for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { *(data3++) = (T)ptrs[0]; *(data2++) = (T)ptrs[1]; *(data1++) = (T)ptrs[2]; ptrs+=3; ++ptrs; } } } return *this; } // Windows-based implementation. //------------------------------- #elif cimg_display==2 bool _is_mouse_tracked, _is_cursor_visible; HANDLE _thread, _is_created, _mutex; HWND _window, _background_window; CLIENTCREATESTRUCT _ccs; unsigned int *_data; DEVMODE _curr_mode; BITMAPINFO _bmi; HDC _hdc; static int screen_width() { DEVMODE mode; mode.dmSize = sizeof(DEVMODE); mode.dmDriverExtra = 0; EnumDisplaySettings(0,ENUM_CURRENT_SETTINGS,&mode); return (int)mode.dmPelsWidth; } static int screen_height() { DEVMODE mode; mode.dmSize = sizeof(DEVMODE); mode.dmDriverExtra = 0; EnumDisplaySettings(0,ENUM_CURRENT_SETTINGS,&mode); return (int)mode.dmPelsHeight; } static void wait_all() { WaitForSingleObject(cimg::Win32_attr().wait_event,INFINITE); } static LRESULT APIENTRY _handle_events(HWND window, UINT msg, WPARAM wParam, LPARAM lParam) { #ifdef _WIN64 CImgDisplay *const disp = (CImgDisplay*)GetWindowLongPtr(window,GWLP_USERDATA); #else CImgDisplay *const disp = (CImgDisplay*)GetWindowLong(window,GWL_USERDATA); #endif MSG st_msg; switch (msg) { case WM_CLOSE : disp->_mouse_x = disp->_mouse_y = -1; disp->_window_x = disp->_window_y = 0; disp->set_button().set_key(0).set_key(0,false)._is_closed = true; ReleaseMutex(disp->_mutex); ShowWindow(disp->_window,SW_HIDE); disp->_is_event = true; SetEvent(cimg::Win32_attr().wait_event); return 0; case WM_SIZE : { while (PeekMessage(&st_msg,window,WM_SIZE,WM_SIZE,PM_REMOVE)) {} WaitForSingleObject(disp->_mutex,INFINITE); const unsigned int nw = LOWORD(lParam),nh = HIWORD(lParam); if (nw && nh && (nw!=disp->_width || nh!=disp->_height)) { disp->_window_width = nw; disp->_window_height = nh; disp->_mouse_x = disp->_mouse_y = -1; disp->_is_resized = disp->_is_event = true; SetEvent(cimg::Win32_attr().wait_event); } ReleaseMutex(disp->_mutex); } break; case WM_MOVE : { while (PeekMessage(&st_msg,window,WM_SIZE,WM_SIZE,PM_REMOVE)) {} WaitForSingleObject(disp->_mutex,INFINITE); const int nx = (int)(short)(LOWORD(lParam)), ny = (int)(short)(HIWORD(lParam)); if (nx!=disp->_window_x || ny!=disp->_window_y) { disp->_window_x = nx; disp->_window_y = ny; disp->_is_moved = disp->_is_event = true; SetEvent(cimg::Win32_attr().wait_event); } ReleaseMutex(disp->_mutex); } break; case WM_PAINT : disp->paint(); cimg_lock_display(); if (disp->_is_cursor_visible) while (ShowCursor(TRUE)<0); else while (ShowCursor(FALSE)>=0); cimg_unlock_display(); break; case WM_ERASEBKGND : // return 0; break; case WM_KEYDOWN : disp->set_key((unsigned int)wParam); SetEvent(cimg::Win32_attr().wait_event); break; case WM_KEYUP : disp->set_key((unsigned int)wParam,false); SetEvent(cimg::Win32_attr().wait_event); break; case WM_MOUSEMOVE : { while (PeekMessage(&st_msg,window,WM_MOUSEMOVE,WM_MOUSEMOVE,PM_REMOVE)) {} disp->_mouse_x = LOWORD(lParam); disp->_mouse_y = HIWORD(lParam); #if (_WIN32_WINNT>=0x0400) && !defined(NOTRACKMOUSEEVENT) if (!disp->_is_mouse_tracked) { TRACKMOUSEEVENT tme; tme.cbSize = sizeof(TRACKMOUSEEVENT); tme.dwFlags = TME_LEAVE; tme.hwndTrack = disp->_window; if (TrackMouseEvent(&tme)) disp->_is_mouse_tracked = true; } #endif if (disp->_mouse_x<0 || disp->_mouse_y<0 || disp->_mouse_x>=disp->width() || disp->_mouse_y>=disp->height()) disp->_mouse_x = disp->_mouse_y = -1; disp->_is_event = true; SetEvent(cimg::Win32_attr().wait_event); cimg_lock_display(); if (disp->_is_cursor_visible) while (ShowCursor(TRUE)<0); else while (ShowCursor(FALSE)>=0); cimg_unlock_display(); } break; case WM_MOUSELEAVE : { disp->_mouse_x = disp->_mouse_y = -1; disp->_is_mouse_tracked = false; cimg_lock_display(); while (ShowCursor(TRUE)<0) {} cimg_unlock_display(); } break; case WM_LBUTTONDOWN : disp->set_button(1); SetEvent(cimg::Win32_attr().wait_event); break; case WM_RBUTTONDOWN : disp->set_button(2); SetEvent(cimg::Win32_attr().wait_event); break; case WM_MBUTTONDOWN : disp->set_button(3); SetEvent(cimg::Win32_attr().wait_event); break; case WM_LBUTTONUP : disp->set_button(1,false); SetEvent(cimg::Win32_attr().wait_event); break; case WM_RBUTTONUP : disp->set_button(2,false); SetEvent(cimg::Win32_attr().wait_event); break; case WM_MBUTTONUP : disp->set_button(3,false); SetEvent(cimg::Win32_attr().wait_event); break; case 0x020A : // WM_MOUSEWHEEL: disp->set_wheel((int)((short)HIWORD(wParam))/120); SetEvent(cimg::Win32_attr().wait_event); } return DefWindowProc(window,msg,wParam,lParam); } static DWORD WINAPI _events_thread(void* arg) { CImgDisplay *const disp = (CImgDisplay*)(((void**)arg)[0]); const char *const title = (const char*)(((void**)arg)[1]); MSG msg; delete[] (void**)arg; disp->_bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); disp->_bmi.bmiHeader.biWidth = disp->width(); disp->_bmi.bmiHeader.biHeight = -disp->height(); disp->_bmi.bmiHeader.biPlanes = 1; disp->_bmi.bmiHeader.biBitCount = 32; disp->_bmi.bmiHeader.biCompression = BI_RGB; disp->_bmi.bmiHeader.biSizeImage = 0; disp->_bmi.bmiHeader.biXPelsPerMeter = 1; disp->_bmi.bmiHeader.biYPelsPerMeter = 1; disp->_bmi.bmiHeader.biClrUsed = 0; disp->_bmi.bmiHeader.biClrImportant = 0; disp->_data = new unsigned int[(size_t)disp->_width*disp->_height]; if (!disp->_is_fullscreen) { // Normal window RECT rect; rect.left = rect.top = 0; rect.right = (LONG)disp->_width - 1; rect.bottom = (LONG)disp->_height - 1; AdjustWindowRect(&rect,WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX,false); const int border1 = (int)((rect.right - rect.left + 1 - disp->_width)/2), border2 = (int)(rect.bottom - rect.top + 1 - disp->_height - border1), ww = disp->_width + 2*border1, wh = disp->_height + border1 + border2, sw = CImgDisplay::screen_width(), sh = CImgDisplay::screen_height(); int wx = (int)cimg::round(cimg::rand(0,sw - ww -1)), wy = (int)cimg::round(cimg::rand(64,sh - wh - 65)); if (wx + ww>=sw) wx = sw - ww; if (wy + wh>=sh) wy = sh - wh; if (wx<0) wx = 0; if (wy<0) wy = 0; disp->_window = CreateWindowA("MDICLIENT",title?title:" ", WS_OVERLAPPEDWINDOW | (disp->_is_closed?0:WS_VISIBLE), wx,wy,ww,wh,0,0,0,&(disp->_ccs)); if (!disp->_is_closed) { GetWindowRect(disp->_window,&rect); disp->_window_x = rect.left + border1; disp->_window_y = rect.top + border2; } else disp->_window_x = disp->_window_y = 0; } else { // Fullscreen window const unsigned int sx = (unsigned int)screen_width(), sy = (unsigned int)screen_height(); disp->_window = CreateWindowA("MDICLIENT",title?title:" ", WS_POPUP | (disp->_is_closed?0:WS_VISIBLE), (sx - disp->_width)/2, (sy - disp->_height)/2, disp->_width,disp->_height,0,0,0,&(disp->_ccs)); disp->_window_x = disp->_window_y = 0; } SetForegroundWindow(disp->_window); disp->_hdc = GetDC(disp->_window); disp->_window_width = disp->_width; disp->_window_height = disp->_height; disp->flush(); #ifdef _WIN64 SetWindowLongPtr(disp->_window,GWLP_USERDATA,(LONG_PTR)disp); SetWindowLongPtr(disp->_window,GWLP_WNDPROC,(LONG_PTR)_handle_events); #else SetWindowLong(disp->_window,GWL_USERDATA,(LONG)disp); SetWindowLong(disp->_window,GWL_WNDPROC,(LONG)_handle_events); #endif SetEvent(disp->_is_created); while (GetMessage(&msg,0,0,0)) DispatchMessage(&msg); return 0; } CImgDisplay& _update_window_pos() { if (_is_closed) _window_x = _window_y = -1; else { RECT rect; rect.left = rect.top = 0; rect.right = (LONG)_width - 1; rect.bottom = (LONG)_height - 1; AdjustWindowRect(&rect,WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX,false); const int border1 = (int)((rect.right - rect.left + 1 - _width)/2), border2 = (int)(rect.bottom - rect.top + 1 - _height - border1); GetWindowRect(_window,&rect); _window_x = rect.left + border1; _window_y = rect.top + border2; } return *this; } void _init_fullscreen() { _background_window = 0; if (!_is_fullscreen || _is_closed) _curr_mode.dmSize = 0; else { DEVMODE mode; unsigned int imode = 0, ibest = 0, bestbpp = 0, bw = ~0U, bh = ~0U; for (mode.dmSize = sizeof(DEVMODE), mode.dmDriverExtra = 0; EnumDisplaySettings(0,imode,&mode); ++imode) { const unsigned int nw = mode.dmPelsWidth, nh = mode.dmPelsHeight; if (nw>=_width && nh>=_height && mode.dmBitsPerPel>=bestbpp && nw<=bw && nh<=bh) { bestbpp = mode.dmBitsPerPel; ibest = imode; bw = nw; bh = nh; } } if (bestbpp) { _curr_mode.dmSize = sizeof(DEVMODE); _curr_mode.dmDriverExtra = 0; EnumDisplaySettings(0,ENUM_CURRENT_SETTINGS,&_curr_mode); EnumDisplaySettings(0,ibest,&mode); ChangeDisplaySettings(&mode,0); } else _curr_mode.dmSize = 0; const unsigned int sx = (unsigned int)screen_width(), sy = (unsigned int)screen_height(); if (sx!=_width || sy!=_height) { CLIENTCREATESTRUCT background_ccs; _background_window = CreateWindowA("MDICLIENT","",WS_POPUP | WS_VISIBLE, 0,0,sx,sy,0,0,0,&background_ccs); SetForegroundWindow(_background_window); } } } void _desinit_fullscreen() { if (!_is_fullscreen) return; if (_background_window) DestroyWindow(_background_window); _background_window = 0; if (_curr_mode.dmSize) ChangeDisplaySettings(&_curr_mode,0); _is_fullscreen = false; } CImgDisplay& _assign(const unsigned int dimw, const unsigned int dimh, const char *const ptitle=0, const unsigned int normalization_type=3, const bool fullscreen_flag=false, const bool closed_flag=false) { // Allocate space for window title const char *const nptitle = ptitle?ptitle:""; const unsigned int s = (unsigned int)std::strlen(nptitle) + 1; char *const tmp_title = s?new char[s]:0; if (s) std::memcpy(tmp_title,nptitle,s*sizeof(char)); // Destroy previous window if existing if (!is_empty()) assign(); // Set display variables _width = std::min(dimw,(unsigned int)screen_width()); _height = std::min(dimh,(unsigned int)screen_height()); _normalization = normalization_type<4?normalization_type:3; _is_fullscreen = fullscreen_flag; _window_x = _window_y = 0; _is_closed = closed_flag; _is_cursor_visible = true; _is_mouse_tracked = false; _title = tmp_title; flush(); if (_is_fullscreen) _init_fullscreen(); // Create event thread void *const arg = (void*)(new void*[2]); ((void**)arg)[0] = (void*)this; ((void**)arg)[1] = (void*)_title; _mutex = CreateMutex(0,FALSE,0); _is_created = CreateEvent(0,FALSE,FALSE,0); _thread = CreateThread(0,0,_events_thread,arg,0,0); WaitForSingleObject(_is_created,INFINITE); return *this; } CImgDisplay& assign() { if (is_empty()) return flush(); DestroyWindow(_window); TerminateThread(_thread,0); delete[] _data; delete[] _title; _data = 0; _title = 0; if (_is_fullscreen) _desinit_fullscreen(); _width = _height = _normalization = _window_width = _window_height = 0; _window_x = _window_y = 0; _is_fullscreen = false; _is_closed = true; _min = _max = 0; _title = 0; flush(); return *this; } CImgDisplay& assign(const unsigned int dimw, const unsigned int dimh, const char *const title=0, const unsigned int normalization_type=3, const bool fullscreen_flag=false, const bool closed_flag=false) { if (!dimw || !dimh) return assign(); _assign(dimw,dimh,title,normalization_type,fullscreen_flag,closed_flag); _min = _max = 0; std::memset(_data,0,sizeof(unsigned int)*_width*_height); return paint(); } template<typename T> CImgDisplay& assign(const CImg<T>& img, const char *const title=0, const unsigned int normalization_type=3, const bool fullscreen_flag=false, const bool closed_flag=false) { if (!img) return assign(); CImg<T> tmp; const CImg<T>& nimg = (img._depth==1)?img:(tmp=img.get_projections2d((img._width - 1)/2, (img._height - 1)/2, (img._depth - 1)/2)); _assign(nimg._width,nimg._height,title,normalization_type,fullscreen_flag,closed_flag); if (_normalization==2) _min = (float)nimg.min_max(_max); return display(nimg); } template<typename T> CImgDisplay& assign(const CImgList<T>& list, const char *const title=0, const unsigned int normalization_type=3, const bool fullscreen_flag=false, const bool closed_flag=false) { if (!list) return assign(); CImg<T> tmp; const CImg<T> img = list>'x', &nimg = (img._depth==1)?img:(tmp=img.get_projections2d((img._width - 1)/2, (img._height - 1)/2, (img._depth - 1)/2)); _assign(nimg._width,nimg._height,title,normalization_type,fullscreen_flag,closed_flag); if (_normalization==2) _min = (float)nimg.min_max(_max); return display(nimg); } CImgDisplay& assign(const CImgDisplay& disp) { if (!disp) return assign(); _assign(disp._width,disp._height,disp._title,disp._normalization,disp._is_fullscreen,disp._is_closed); std::memcpy(_data,disp._data,sizeof(unsigned int)*_width*_height); return paint(); } CImgDisplay& resize(const int nwidth, const int nheight, const bool force_redraw=true) { if (!nwidth || !nheight || (is_empty() && (nwidth<0 || nheight<0))) return assign(); if (is_empty()) return assign(nwidth,nheight); const unsigned int tmpdimx = (nwidth>0)?nwidth:(-nwidth*_width/100), tmpdimy = (nheight>0)?nheight:(-nheight*_height/100), dimx = tmpdimx?tmpdimx:1, dimy = tmpdimy?tmpdimy:1; if (_width!=dimx || _height!=dimy || _window_width!=dimx || _window_height!=dimy) { if (_window_width!=dimx || _window_height!=dimy) { RECT rect; rect.left = rect.top = 0; rect.right = (LONG)dimx - 1; rect.bottom = (LONG)dimy - 1; AdjustWindowRect(&rect,WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX,false); const int cwidth = rect.right - rect.left + 1, cheight = rect.bottom - rect.top + 1; SetWindowPos(_window,0,0,0,cwidth,cheight,SWP_NOMOVE | SWP_NOZORDER | SWP_NOCOPYBITS); } if (_width!=dimx || _height!=dimy) { unsigned int *const ndata = new unsigned int[dimx*dimy]; if (force_redraw) _render_resize(_data,_width,_height,ndata,dimx,dimy); else std::memset(ndata,0x80,sizeof(unsigned int)*dimx*dimy); delete[] _data; _data = ndata; _bmi.bmiHeader.biWidth = (LONG)dimx; _bmi.bmiHeader.biHeight = -(int)dimy; _width = dimx; _height = dimy; } _window_width = dimx; _window_height = dimy; show(); } _is_resized = false; if (_is_fullscreen) move((screen_width() - width())/2,(screen_height() - height())/2); if (force_redraw) return paint(); return *this; } CImgDisplay& toggle_fullscreen(const bool force_redraw=true) { if (is_empty()) return *this; if (force_redraw) { const cimg_ulong buf_size = (cimg_ulong)_width*_height*4; void *odata = std::malloc(buf_size); if (odata) { std::memcpy(odata,_data,buf_size); assign(_width,_height,_title,_normalization,!_is_fullscreen,false); std::memcpy(_data,odata,buf_size); std::free(odata); } return paint(); } return assign(_width,_height,_title,_normalization,!_is_fullscreen,false); } CImgDisplay& show() { if (is_empty() || !_is_closed) return *this; _is_closed = false; if (_is_fullscreen) _init_fullscreen(); ShowWindow(_window,SW_SHOW); _update_window_pos(); return paint(); } CImgDisplay& close() { if (is_empty() || _is_closed) return *this; _is_closed = true; if (_is_fullscreen) _desinit_fullscreen(); ShowWindow(_window,SW_HIDE); _window_x = _window_y = 0; return *this; } CImgDisplay& move(const int posx, const int posy) { if (is_empty()) return *this; if (_window_x!=posx || _window_y!=posy) { if (!_is_fullscreen) { RECT rect; rect.left = rect.top = 0; rect.right = (LONG)_window_width - 1; rect.bottom = (LONG)_window_height - 1; AdjustWindowRect(&rect,WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX,false); const int border1 = (int)((rect.right - rect.left + 1 -_width)/2), border2 = (int)(rect.bottom - rect.top + 1 - _height - border1); SetWindowPos(_window,0,posx - border1,posy - border2,0,0,SWP_NOSIZE | SWP_NOZORDER); } else SetWindowPos(_window,0,posx,posy,0,0,SWP_NOSIZE | SWP_NOZORDER); _window_x = posx; _window_y = posy; show(); } _is_moved = false; return *this; } CImgDisplay& show_mouse() { if (is_empty()) return *this; _is_cursor_visible = true; return *this; } CImgDisplay& hide_mouse() { if (is_empty()) return *this; _is_cursor_visible = false; return *this; } CImgDisplay& set_mouse(const int posx, const int posy) { if (is_empty() || _is_closed || posx<0 || posy<0) return *this; _update_window_pos(); const int res = (int)SetCursorPos(_window_x + posx,_window_y + posy); if (res) { _mouse_x = posx; _mouse_y = posy; } return *this; } CImgDisplay& set_title(const char *const format, ...) { if (is_empty()) return *this; char *const tmp = new char[1024]; va_list ap; va_start(ap, format); cimg_vsnprintf(tmp,1024,format,ap); va_end(ap); if (!std::strcmp(_title,tmp)) { delete[] tmp; return *this; } delete[] _title; const unsigned int s = (unsigned int)std::strlen(tmp) + 1; _title = new char[s]; std::memcpy(_title,tmp,s*sizeof(char)); SetWindowTextA(_window, tmp); delete[] tmp; return *this; } template<typename T> CImgDisplay& display(const CImg<T>& img) { if (!img) throw CImgArgumentException(_cimgdisplay_instance "display(): Empty specified image.", cimgdisplay_instance); if (is_empty()) return assign(img); return render(img).paint(); } CImgDisplay& paint() { if (_is_closed) return *this; WaitForSingleObject(_mutex,INFINITE); SetDIBitsToDevice(_hdc,0,0,_width,_height,0,0,0,_height,_data,&_bmi,DIB_RGB_COLORS); ReleaseMutex(_mutex); return *this; } template<typename T> CImgDisplay& render(const CImg<T>& img) { if (!img) throw CImgArgumentException(_cimgdisplay_instance "render(): Empty specified image.", cimgdisplay_instance); if (is_empty()) return *this; if (img._depth!=1) return render(img.get_projections2d((img._width - 1)/2,(img._height - 1)/2, (img._depth - 1)/2)); const T *data1 = img._data, *data2 = (img._spectrum>=2)?img.data(0,0,0,1):data1, *data3 = (img._spectrum>=3)?img.data(0,0,0,2):data1; WaitForSingleObject(_mutex,INFINITE); unsigned int *const ndata = (img._width==_width && img._height==_height)?_data: new unsigned int[(size_t)img._width*img._height], *ptrd = ndata; if (!_normalization || (_normalization==3 && cimg::type<T>::string()==cimg::type<unsigned char>::string())) { _min = _max = 0; switch (img._spectrum) { case 1 : { for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)*(data1++); *(ptrd++) = (unsigned int)((val<<16) | (val<<8) | val); } } break; case 2 : { for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char R = (unsigned char)*(data1++), G = (unsigned char)*(data2++); *(ptrd++) = (unsigned int)((R<<16) | (G<<8)); } } break; default : { for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char R = (unsigned char)*(data1++), G = (unsigned char)*(data2++), B = (unsigned char)*(data3++); *(ptrd++) = (unsigned int)((R<<16) | (G<<8) | B); } } } } else { if (_normalization==3) { if (cimg::type<T>::is_float()) _min = (float)img.min_max(_max); else { _min = (float)cimg::type<T>::min(); _max = (float)cimg::type<T>::max(); } } else if ((_min>_max) || _normalization==1) _min = (float)img.min_max(_max); const float delta = _max - _min, mm = 255/(delta?delta:1.f); switch (img._spectrum) { case 1 : { for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)((*(data1++) - _min)*mm); *(ptrd++) = (unsigned int)((val<<16) | (val<<8) | val); } } break; case 2 : { for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char R = (unsigned char)((*(data1++) - _min)*mm), G = (unsigned char)((*(data2++) - _min)*mm); *(ptrd++) = (unsigned int)((R<<16) | (G<<8)); } } break; default : { for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned char R = (unsigned char)((*(data1++) - _min)*mm), G = (unsigned char)((*(data2++) - _min)*mm), B = (unsigned char)((*(data3++) - _min)*mm); *(ptrd++) = (unsigned int)((R<<16) | (G<<8) | B); } } } } if (ndata!=_data) { _render_resize(ndata,img._width,img._height,_data,_width,_height); delete[] ndata; } ReleaseMutex(_mutex); return *this; } template<typename T> static void screenshot(const int x0, const int y0, const int x1, const int y1, CImg<T>& img) { img.assign(); HDC hScreen = GetDC(GetDesktopWindow()); if (hScreen) { const int width = GetDeviceCaps(hScreen,HORZRES), height = GetDeviceCaps(hScreen,VERTRES); int _x0 = x0, _y0 = y0, _x1 = x1, _y1 = y1; if (_x0>_x1) cimg::swap(_x0,_x1); if (_y0>_y1) cimg::swap(_y0,_y1); if (_x1>=0 && _x0<width && _y1>=0 && _y0<height) { _x0 = std::max(_x0,0); _y0 = std::max(_y0,0); _x1 = std::min(_x1,width - 1); _y1 = std::min(_y1,height - 1); const int bw = _x1 - _x0 + 1, bh = _y1 - _y0 + 1; HDC hdcMem = CreateCompatibleDC(hScreen); if (hdcMem) { HBITMAP hBitmap = CreateCompatibleBitmap(hScreen,bw,bh); if (hBitmap) { HGDIOBJ hOld = SelectObject(hdcMem,hBitmap); if (hOld && BitBlt(hdcMem,0,0,bw,bh,hScreen,_x0,_y0,SRCCOPY) && SelectObject(hdcMem,hOld)) { BITMAPINFOHEADER bmi; bmi.biSize = sizeof(BITMAPINFOHEADER); bmi.biWidth = bw; bmi.biHeight = -bh; bmi.biPlanes = 1; bmi.biBitCount = 32; bmi.biCompression = BI_RGB; bmi.biSizeImage = 0; bmi.biXPelsPerMeter = bmi.biYPelsPerMeter = 0; bmi.biClrUsed = bmi.biClrImportant = 0; unsigned char *buf = new unsigned char[4*bw*bh]; if (GetDIBits(hdcMem,hBitmap,0,bh,buf,(BITMAPINFO*)&bmi,DIB_RGB_COLORS)) { img.assign(bw,bh,1,3); const unsigned char *ptrs = buf; T *pR = img.data(0,0,0,0), *pG = img.data(0,0,0,1), *pB = img.data(0,0,0,2); cimg_forXY(img,x,y) { *(pR++) = (T)ptrs[2]; *(pG++) = (T)ptrs[1]; *(pB++) = (T)ptrs[0]; ptrs+=4; } } delete[] buf; } DeleteObject(hBitmap); } DeleteDC(hdcMem); } } ReleaseDC(GetDesktopWindow(),hScreen); } if (img.is_empty()) throw CImgDisplayException("CImgDisplay::screenshot(): Failed to take screenshot " "with coordinates (%d,%d)-(%d,%d).", x0,y0,x1,y1); } template<typename T> const CImgDisplay& snapshot(CImg<T>& img) const { if (is_empty()) { img.assign(); return *this; } const unsigned int *ptrs = _data; img.assign(_width,_height,1,3); T *data1 = img.data(0,0,0,0), *data2 = img.data(0,0,0,1), *data3 = img.data(0,0,0,2); for (cimg_ulong xy = (cimg_ulong)img._width*img._height; xy>0; --xy) { const unsigned int val = *(ptrs++); *(data1++) = (T)(unsigned char)(val>>16); *(data2++) = (T)(unsigned char)((val>>8)&0xFF); *(data3++) = (T)(unsigned char)(val&0xFF); } return *this; } #endif //@} }; // struct CImgDisplay { ... /* #-------------------------------------- # # # # Definition of the CImg<T> structure # # # #-------------------------------------- */ //! Class representing an image (up to 4 dimensions wide), each pixel being of type \c T. /** This is the main class of the %CImg Library. It declares and constructs an image, allows access to its pixel values, and is able to perform various image operations. \par Image representation A %CImg image is defined as an instance of the container \c CImg<T>, which contains a regular grid of pixels, each pixel value being of type \c T. The image grid can have up to 4 dimensions: width, height, depth and number of channels. Usually, the three first dimensions are used to describe spatial coordinates <tt>(x,y,z)</tt>, while the number of channels is rather used as a vector-valued dimension (it may describe the R,G,B color channels for instance). If you need a fifth dimension, you can use image lists \c CImgList<T> rather than simple images \c CImg<T>. Thus, the \c CImg<T> class is able to represent volumetric images of vector-valued pixels, as well as images with less dimensions (1D scalar signal, 2D color images, ...). Most member functions of the class CImg<\c T> are designed to handle this maximum case of (3+1) dimensions. Concerning the pixel value type \c T: fully supported template types are the basic C++ types: <tt>unsigned char, char, short, unsigned int, int, unsigned long, long, float, double, ... </tt>. Typically, fast image display can be done using <tt>CImg<unsigned char></tt> images, while complex image processing algorithms may be rather coded using <tt>CImg<float></tt> or <tt>CImg<double></tt> images that have floating-point pixel values. The default value for the template T is \c float. Using your own template types may be possible. However, you will certainly have to define the complete set of arithmetic and logical operators for your class. \par Image structure The \c CImg<T> structure contains \e six fields: - \c _width defines the number of \a columns of the image (size along the X-axis). - \c _height defines the number of \a rows of the image (size along the Y-axis). - \c _depth defines the number of \a slices of the image (size along the Z-axis). - \c _spectrum defines the number of \a channels of the image (size along the C-axis). - \c _data defines a \a pointer to the \a pixel \a data (of type \c T). - \c _is_shared is a boolean that tells if the memory buffer \c data is shared with another image. You can access these fields publicly although it is recommended to use the dedicated functions width(), height(), depth(), spectrum() and ptr() to do so. Image dimensions are not limited to a specific range (as long as you got enough available memory). A value of \e 1 usually means that the corresponding dimension is \a flat. If one of the dimensions is \e 0, or if the data pointer is null, the image is considered as \e empty. Empty images should not contain any pixel data and thus, will not be processed by CImg member functions (a CImgInstanceException will be thrown instead). Pixel data are stored in memory, in a non interlaced mode (See \ref cimg_storage). \par Image declaration and construction Declaring an image can be done by using one of the several available constructors. Here is a list of the most used: - Construct images from arbitrary dimensions: - <tt>CImg<char> img;</tt> declares an empty image. - <tt>CImg<unsigned char> img(128,128);</tt> declares a 128x128 greyscale image with \c unsigned \c char pixel values. - <tt>CImg<double> img(3,3);</tt> declares a 3x3 matrix with \c double coefficients. - <tt>CImg<unsigned char> img(256,256,1,3);</tt> declares a 256x256x1x3 (color) image (colors are stored as an image with three channels). - <tt>CImg<double> img(128,128,128);</tt> declares a 128x128x128 volumetric and greyscale image (with \c double pixel values). - <tt>CImg<> img(128,128,128,3);</tt> declares a 128x128x128 volumetric color image (with \c float pixels, which is the default value of the template parameter \c T). - \b Note: images pixels are <b>not automatically initialized to 0</b>. You may use the function \c fill() to do it, or use the specific constructor taking 5 parameters like this: <tt>CImg<> img(128,128,128,3,0);</tt> declares a 128x128x128 volumetric color image with all pixel values to 0. - Construct images from filenames: - <tt>CImg<unsigned char> img("image.jpg");</tt> reads a JPEG color image from the file "image.jpg". - <tt>CImg<float> img("analyze.hdr");</tt> reads a volumetric image (ANALYZE7.5 format) from the file "analyze.hdr". - \b Note: You need to install <a href="http://www.imagemagick.org">ImageMagick</a> to be able to read common compressed image formats (JPG,PNG, ...) (See \ref cimg_files_io). - Construct images from C-style arrays: - <tt>CImg<int> img(data_buffer,256,256);</tt> constructs a 256x256 greyscale image from a \c int* buffer \c data_buffer (of size 256x256=65536). - <tt>CImg<unsigned char> img(data_buffer,256,256,1,3);</tt> constructs a 256x256 color image from a \c unsigned \c char* buffer \c data_buffer (where R,G,B channels follow each others). The complete list of constructors can be found <a href="#constructors">here</a>. \par Most useful functions The \c CImg<T> class contains a lot of functions that operates on images. Some of the most useful are: - operator()(): Read or write pixel values. - display(): displays the image in a new window. **/ template<typename T> struct CImg { unsigned int _width, _height, _depth, _spectrum; bool _is_shared; T *_data; //! Simple iterator type, to loop through each pixel value of an image instance. /** \note - The \c CImg<T>::iterator type is defined to be a <tt>T*</tt>. - You will seldom have to use iterators in %CImg, most classical operations being achieved (often in a faster way) using methods of \c CImg<T>. \par Example \code CImg<float> img("reference.jpg"); // Load image from file // Set all pixels to '0', with a CImg iterator. for (CImg<float>::iterator it = img.begin(), it<img.end(); ++it) *it = 0; img.fill(0); // Do the same with a built-in method \endcode **/ typedef T* iterator; //! Simple const iterator type, to loop through each pixel value of a \c const image instance. /** \note - The \c CImg<T>::const_iterator type is defined to be a \c const \c T*. - You will seldom have to use iterators in %CImg, most classical operations being achieved (often in a faster way) using methods of \c CImg<T>. \par Example \code const CImg<float> img("reference.jpg"); // Load image from file float sum = 0; // Compute sum of all pixel values, with a CImg iterator. for (CImg<float>::iterator it = img.begin(), it<img.end(); ++it) sum+=*it; const float sum2 = img.sum(); // Do the same with a built-in method \endcode **/ typedef const T* const_iterator; //! Pixel value type. /** Refer to the type of the pixel values of an image instance. \note - The \c CImg<T>::value_type type of a \c CImg<T> is defined to be a \c T. - \c CImg<T>::value_type is actually not used in %CImg methods. It has been mainly defined for compatibility with STL naming conventions. **/ typedef T value_type; // Define common types related to template type T. typedef typename cimg::superset<T,bool>::type Tbool; typedef typename cimg::superset<T,unsigned char>::type Tuchar; typedef typename cimg::superset<T,char>::type Tchar; typedef typename cimg::superset<T,unsigned short>::type Tushort; typedef typename cimg::superset<T,short>::type Tshort; typedef typename cimg::superset<T,unsigned int>::type Tuint; typedef typename cimg::superset<T,int>::type Tint; typedef typename cimg::superset<T,cimg_ulong>::type Tulong; typedef typename cimg::superset<T,cimg_long>::type Tlong; typedef typename cimg::superset<T,float>::type Tfloat; typedef typename cimg::superset<T,double>::type Tdouble; typedef typename cimg::last<T,bool>::type boolT; typedef typename cimg::last<T,unsigned char>::type ucharT; typedef typename cimg::last<T,char>::type charT; typedef typename cimg::last<T,unsigned short>::type ushortT; typedef typename cimg::last<T,short>::type shortT; typedef typename cimg::last<T,unsigned int>::type uintT; typedef typename cimg::last<T,int>::type intT; typedef typename cimg::last<T,cimg_ulong>::type ulongT; typedef typename cimg::last<T,cimg_long>::type longT; typedef typename cimg::last<T,cimg_uint64>::type uint64T; typedef typename cimg::last<T,cimg_int64>::type int64T; typedef typename cimg::last<T,float>::type floatT; typedef typename cimg::last<T,double>::type doubleT; //@} //--------------------------- // //! \name Plugins //@{ //--------------------------- #ifdef cimg_plugin #include cimg_plugin #endif #ifdef cimg_plugin1 #include cimg_plugin1 #endif #ifdef cimg_plugin2 #include cimg_plugin2 #endif #ifdef cimg_plugin3 #include cimg_plugin3 #endif #ifdef cimg_plugin4 #include cimg_plugin4 #endif #ifdef cimg_plugin5 #include cimg_plugin5 #endif #ifdef cimg_plugin6 #include cimg_plugin6 #endif #ifdef cimg_plugin7 #include cimg_plugin7 #endif #ifdef cimg_plugin8 #include cimg_plugin8 #endif //@} //--------------------------------------------------------- // //! \name Constructors / Destructor / Instance Management //@{ //--------------------------------------------------------- //! Destroy image. /** \note - The pixel buffer data() is deallocated if necessary, e.g. for non-empty and non-shared image instances. - Destroying an empty or shared image does nothing actually. \warning - When destroying a non-shared image, make sure that you will \e not operate on a remaining shared image that shares its buffer with the destroyed instance, in order to avoid further invalid memory access (to a deallocated buffer). **/ ~CImg() { if (!_is_shared) delete[] _data; } //! Construct empty image. /** \note - An empty image has no pixel data and all of its dimensions width(), height(), depth(), spectrum() are set to \c 0, as well as its pixel buffer pointer data(). - An empty image may be re-assigned afterwards, e.g. with the family of assign(unsigned int,unsigned int,unsigned int,unsigned int) methods, or by operator=(const CImg<t>&). In all cases, the type of pixels stays \c T. - An empty image is never shared. \par Example \code CImg<float> img1, img2; // Construct two empty images img1.assign(256,256,1,3); // Re-assign 'img1' to be a 256x256x1x3 (color) image img2 = img1.get_rand(0,255); // Re-assign 'img2' to be a random-valued version of 'img1' img2.assign(); // Re-assign 'img2' to be an empty image again \endcode **/ CImg():_width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) {} //! Construct image with specified size. /** \param size_x Image width(). \param size_y Image height(). \param size_z Image depth(). \param size_c Image spectrum() (number of channels). \note - It is able to create only \e non-shared images, and allocates thus a pixel buffer data() for each constructed image instance. - Setting one dimension \c size_x,\c size_y,\c size_z or \c size_c to \c 0 leads to the construction of an \e empty image. - A \c CImgInstanceException is thrown when the pixel buffer cannot be allocated (e.g. when requested size is too big for available memory). \warning - The allocated pixel buffer is \e not filled with a default value, and is likely to contain garbage values. In order to initialize pixel values during construction (e.g. with \c 0), use constructor CImg(unsigned int,unsigned int,unsigned int,unsigned int,T) instead. \par Example \code CImg<float> img1(256,256,1,3); // Construct a 256x256x1x3 (color) image, filled with garbage values CImg<float> img2(256,256,1,3,0); // Construct a 256x256x1x3 (color) image, filled with value '0' \endcode **/ explicit CImg(const unsigned int size_x, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1): _is_shared(false) { size_t siz = (size_t)size_x*size_y*size_z*size_c; if (siz) { _width = size_x; _height = size_y; _depth = size_z; _spectrum = size_c; try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*size_x*size_y*size_z*size_c), size_x,size_y,size_z,size_c); } } else { _width = _height = _depth = _spectrum = 0; _data = 0; } } //! Construct image with specified size and initialize pixel values. /** \param size_x Image width(). \param size_y Image height(). \param size_z Image depth(). \param size_c Image spectrum() (number of channels). \param value Initialization value. \note - Similar to CImg(unsigned int,unsigned int,unsigned int,unsigned int), but it also fills the pixel buffer with the specified \c value. \warning - It cannot be used to construct a vector-valued image and initialize it with \e vector-valued pixels (e.g. RGB vector, for color images). For this task, you may use fillC() after construction. **/ CImg(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const T& value): _is_shared(false) { const size_t siz = (size_t)size_x*size_y*size_z*size_c; if (siz) { _width = size_x; _height = size_y; _depth = size_z; _spectrum = size_c; try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*size_x*size_y*size_z*size_c), size_x,size_y,size_z,size_c); } fill(value); } else { _width = _height = _depth = _spectrum = 0; _data = 0; } } //! Construct image with specified size and initialize pixel values from a sequence of integers. /** Construct a new image instance of size \c size_x x \c size_y x \c size_z x \c size_c, with pixels of type \c T, and initialize pixel values from the specified sequence of integers \c value0,\c value1,\c ... \param size_x Image width(). \param size_y Image height(). \param size_z Image depth(). \param size_c Image spectrum() (number of channels). \param value0 First value of the initialization sequence (must be an \e integer). \param value1 Second value of the initialization sequence (must be an \e integer). \param ... \note - Similar to CImg(unsigned int,unsigned int,unsigned int,unsigned int), but it also fills the pixel buffer with a sequence of specified integer values. \warning - You must specify \e exactly \c size_x*\c size_y*\c size_z*\c size_c integers in the initialization sequence. Otherwise, the constructor may crash or fill your image pixels with garbage. \par Example \code const CImg<float> img(2,2,1,3, // Construct a 2x2 color (RGB) image 0,255,0,255, // Set the 4 values for the red component 0,0,255,255, // Set the 4 values for the green component 64,64,64,64); // Set the 4 values for the blue component img.resize(150,150).display(); \endcode \image html ref_constructor1.jpg **/ CImg(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const int value0, const int value1, ...): _width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { #define _CImg_stdarg(img,a0,a1,N,t) { \ size_t _siz = (size_t)N; \ if (_siz--) { \ va_list ap; \ va_start(ap,a1); \ T *ptrd = (img)._data; \ *(ptrd++) = (T)a0; \ if (_siz--) { \ *(ptrd++) = (T)a1; \ for ( ; _siz; --_siz) *(ptrd++) = (T)va_arg(ap,t); \ } \ va_end(ap); \ } \ } assign(size_x,size_y,size_z,size_c); _CImg_stdarg(*this,value0,value1,(size_t)size_x*size_y*size_z*size_c,int); } #if cimg_use_cpp11==1 //! Construct image with specified size and initialize pixel values from an initializer list of integers. /** Construct a new image instance of size \c size_x x \c size_y x \c size_z x \c size_c, with pixels of type \c T, and initialize pixel values from the specified initializer list of integers { \c value0,\c value1,\c ... } \param size_x Image width(). \param size_y Image height(). \param size_z Image depth(). \param size_c Image spectrum() (number of channels). \param { value0, value1, ... } Initialization list \param repeat_values Tells if the value filling process is repeated over the image. \note - Similar to CImg(unsigned int,unsigned int,unsigned int,unsigned int), but it also fills the pixel buffer with a sequence of specified integer values. \par Example \code const CImg<float> img(2,2,1,3, // Construct a 2x2 color (RGB) image { 0,255,0,255, // Set the 4 values for the red component 0,0,255,255, // Set the 4 values for the green component 64,64,64,64 }); // Set the 4 values for the blue component img.resize(150,150).display(); \endcode \image html ref_constructor1.jpg **/ template<typename t> CImg(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const std::initializer_list<t> values, const bool repeat_values=true): _width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { #define _cimg_constructor_cpp11(repeat_values) \ auto it = values.begin(); \ size_t siz = size(); \ if (repeat_values) for (T *ptrd = _data; siz--; ) { \ *(ptrd++) = (T)(*(it++)); if (it==values.end()) it = values.begin(); } \ else { siz = std::min(siz,values.size()); for (T *ptrd = _data; siz--; ) *(ptrd++) = (T)(*(it++)); } assign(size_x,size_y,size_z,size_c); _cimg_constructor_cpp11(repeat_values); } template<typename t> CImg(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, std::initializer_list<t> values, const bool repeat_values=true): _width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { assign(size_x,size_y,size_z); _cimg_constructor_cpp11(repeat_values); } template<typename t> CImg(const unsigned int size_x, const unsigned int size_y, std::initializer_list<t> values, const bool repeat_values=true): _width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { assign(size_x,size_y); _cimg_constructor_cpp11(repeat_values); } template<typename t> CImg(const unsigned int size_x, std::initializer_list<t> values, const bool repeat_values=true):_width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { assign(size_x); _cimg_constructor_cpp11(repeat_values); } //! Construct single channel 1D image with pixel values and width obtained from an initializer list of integers. /** Construct a new image instance of size \c width x \c 1 x \c 1 x \c 1, with pixels of type \c T, and initialize pixel values from the specified initializer list of integers { \c value0,\c value1,\c ... }. Image width is given by the size of the initializer list. \param { value0, value1, ... } Initialization list \note - Similar to CImg(unsigned int,unsigned int,unsigned int,unsigned int) with height=1, depth=1, and spectrum=1, but it also fills the pixel buffer with a sequence of specified integer values. \par Example \code const CImg<float> img = {10,20,30,20,10 }; // Construct a 5x1 image with one channel, and set its pixel values img.resize(150,150).display(); \endcode \image html ref_constructor1.jpg **/ template<typename t> CImg(const std::initializer_list<t> values): _width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { assign(values.size(),1,1,1); auto it = values.begin(); unsigned int siz = _width; for (T *ptrd = _data; siz--; ) *(ptrd++) = (T)(*(it++)); } template<typename t> CImg<T> & operator=(std::initializer_list<t> values) { _cimg_constructor_cpp11(siz>values.size()); return *this; } #endif //! Construct image with specified size and initialize pixel values from a sequence of doubles. /** Construct a new image instance of size \c size_x x \c size_y x \c size_z x \c size_c, with pixels of type \c T, and initialize pixel values from the specified sequence of doubles \c value0,\c value1,\c ... \param size_x Image width(). \param size_y Image height(). \param size_z Image depth(). \param size_c Image spectrum() (number of channels). \param value0 First value of the initialization sequence (must be a \e double). \param value1 Second value of the initialization sequence (must be a \e double). \param ... \note - Similar to CImg(unsigned int,unsigned int,unsigned int,unsigned int,int,int,...), but takes a sequence of double values instead of integers. \warning - You must specify \e exactly \c dx*\c dy*\c dz*\c dc doubles in the initialization sequence. Otherwise, the constructor may crash or fill your image with garbage. For instance, the code below will probably crash on most platforms: \code const CImg<float> img(2,2,1,1, 0.5,0.5,255,255); // FAIL: The two last arguments are 'int', not 'double'! \endcode **/ CImg(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const double value0, const double value1, ...): _width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { assign(size_x,size_y,size_z,size_c); _CImg_stdarg(*this,value0,value1,(size_t)size_x*size_y*size_z*size_c,double); } //! Construct image with specified size and initialize pixel values from a value string. /** Construct a new image instance of size \c size_x x \c size_y x \c size_z x \c size_c, with pixels of type \c T, and initializes pixel values from the specified string \c values. \param size_x Image width(). \param size_y Image height(). \param size_z Image depth(). \param size_c Image spectrum() (number of channels). \param values Value string describing the way pixel values are set. \param repeat_values Tells if the value filling process is repeated over the image. \note - Similar to CImg(unsigned int,unsigned int,unsigned int,unsigned int), but it also fills the pixel buffer with values described in the value string \c values. - Value string \c values may describe two different filling processes: - Either \c values is a sequences of values assigned to the image pixels, as in <tt>"1,2,3,7,8,2"</tt>. In this case, set \c repeat_values to \c true to periodically fill the image with the value sequence. - Either, \c values is a formula, as in <tt>"cos(x/10)*sin(y/20)"</tt>. In this case, parameter \c repeat_values is pointless. - For both cases, specifying \c repeat_values is mandatory. It disambiguates the possible overloading of constructor CImg(unsigned int,unsigned int,unsigned int,unsigned int,T) with \c T being a <tt>const char*</tt>. - A \c CImgArgumentException is thrown when an invalid value string \c values is specified. \par Example \code const CImg<float> img1(129,129,1,3,"0,64,128,192,255",true), // Construct image from a value sequence img2(129,129,1,3,"if(c==0,255*abs(cos(x/10)),1.8*y)",false); // Construct image from a formula (img1,img2).display(); \endcode \image html ref_constructor2.jpg **/ CImg(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const char *const values, const bool repeat_values):_is_shared(false) { const size_t siz = (size_t)size_x*size_y*size_z*size_c; if (siz) { _width = size_x; _height = size_y; _depth = size_z; _spectrum = size_c; try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*size_x*size_y*size_z*size_c), size_x,size_y,size_z,size_c); } fill(values,repeat_values); } else { _width = _height = _depth = _spectrum = 0; _data = 0; } } //! Construct image with specified size and initialize pixel values from a memory buffer. /** Construct a new image instance of size \c size_x x \c size_y x \c size_z x \c size_c, with pixels of type \c T, and initializes pixel values from the specified \c t* memory buffer. \param values Pointer to the input memory buffer. \param size_x Image width(). \param size_y Image height(). \param size_z Image depth(). \param size_c Image spectrum() (number of channels). \param is_shared Tells if input memory buffer must be shared by the current instance. \note - If \c is_shared is \c false, the image instance allocates its own pixel buffer, and values from the specified input buffer are copied to the instance buffer. If buffer types \c T and \c t are different, a regular static cast is performed during buffer copy. - Otherwise, the image instance does \e not allocate a new buffer, and uses the input memory buffer as its own pixel buffer. This case requires that types \c T and \c t are the same. Later, destroying such a shared image will not deallocate the pixel buffer, this task being obviously charged to the initial buffer allocator. - A \c CImgInstanceException is thrown when the pixel buffer cannot be allocated (e.g. when requested size is too big for available memory). \warning - You must take care when operating on a shared image, since it may have an invalid pixel buffer pointer data() (e.g. already deallocated). \par Example \code unsigned char tab[256*256] = { 0 }; CImg<unsigned char> img1(tab,256,256,1,1,false), // Construct new non-shared image from buffer 'tab' img2(tab,256,256,1,1,true); // Construct new shared-image from buffer 'tab' tab[1024] = 255; // Here, 'img2' is indirectly modified, but not 'img1' \endcode **/ template<typename t> CImg(const t *const values, const unsigned int size_x, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1, const bool is_shared=false):_is_shared(false) { if (is_shared) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgArgumentException(_cimg_instance "CImg(): Invalid construction request of a (%u,%u,%u,%u) shared instance " "from a (%s*) buffer (pixel types are different).", cimg_instance, size_x,size_y,size_z,size_c,CImg<t>::pixel_type()); } const size_t siz = (size_t)size_x*size_y*size_z*size_c; if (values && siz) { _width = size_x; _height = size_y; _depth = size_z; _spectrum = size_c; try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*size_x*size_y*size_z*size_c), size_x,size_y,size_z,size_c); } const t *ptrs = values; cimg_for(*this,ptrd,T) *ptrd = (T)*(ptrs++); } else { _width = _height = _depth = _spectrum = 0; _data = 0; } } //! Construct image with specified size and initialize pixel values from a memory buffer \specialization. CImg(const T *const values, const unsigned int size_x, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1, const bool is_shared=false) { const size_t siz = (size_t)size_x*size_y*size_z*size_c; if (values && siz) { _width = size_x; _height = size_y; _depth = size_z; _spectrum = size_c; _is_shared = is_shared; if (_is_shared) _data = const_cast<T*>(values); else { try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*size_x*size_y*size_z*size_c), size_x,size_y,size_z,size_c); } std::memcpy(_data,values,siz*sizeof(T)); } } else { _width = _height = _depth = _spectrum = 0; _is_shared = false; _data = 0; } } //! Construct image from reading an image file. /** Construct a new image instance with pixels of type \c T, and initialize pixel values with the data read from an image file. \param filename Filename, as a C-string. \note - Similar to CImg(unsigned int,unsigned int,unsigned int,unsigned int), but it reads the image dimensions and pixel values from the specified image file. - The recognition of the image file format by %CImg higly depends on the tools installed on your system and on the external libraries you used to link your code against. - Considered pixel type \c T should better fit the file format specification, or data loss may occur during file load (e.g. constructing a \c CImg<unsigned char> from a float-valued image file). - A \c CImgIOException is thrown when the specified \c filename cannot be read, or if the file format is not recognized. \par Example \code const CImg<float> img("reference.jpg"); img.display(); \endcode \image html ref_image.jpg **/ explicit CImg(const char *const filename):_width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { assign(filename); } //! Construct image copy. /** Construct a new image instance with pixels of type \c T, as a copy of an existing \c CImg<t> instance. \param img Input image to copy. \note - Constructed copy has the same size width() x height() x depth() x spectrum() and pixel values as the input image \c img. - If input image \c img is \e shared and if types \c T and \c t are the same, the constructed copy is also \e shared, and shares its pixel buffer with \c img. Modifying a pixel value in the constructed copy will thus also modifies it in the input image \c img. This behavior is needful to allow functions to return shared images. - Otherwise, the constructed copy allocates its own pixel buffer, and copies pixel values from the input image \c img into its buffer. The copied pixel values may be eventually statically casted if types \c T and \c t are different. - Constructing a copy from an image \c img when types \c t and \c T are the same is significantly faster than with different types. - A \c CImgInstanceException is thrown when the pixel buffer cannot be allocated (e.g. not enough available memory). **/ template<typename t> CImg(const CImg<t>& img):_is_shared(false) { const size_t siz = (size_t)img.size(); if (img._data && siz) { _width = img._width; _height = img._height; _depth = img._depth; _spectrum = img._spectrum; try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*img._width*img._height*img._depth*img._spectrum), img._width,img._height,img._depth,img._spectrum); } const t *ptrs = img._data; cimg_for(*this,ptrd,T) *ptrd = (T)*(ptrs++); } else { _width = _height = _depth = _spectrum = 0; _data = 0; } } //! Construct image copy \specialization. CImg(const CImg<T>& img) { const size_t siz = (size_t)img.size(); if (img._data && siz) { _width = img._width; _height = img._height; _depth = img._depth; _spectrum = img._spectrum; _is_shared = img._is_shared; if (_is_shared) _data = const_cast<T*>(img._data); else { try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*img._width*img._height*img._depth*img._spectrum), img._width,img._height,img._depth,img._spectrum); } std::memcpy(_data,img._data,siz*sizeof(T)); } } else { _width = _height = _depth = _spectrum = 0; _is_shared = false; _data = 0; } } //! Advanced copy constructor. /** Construct a new image instance with pixels of type \c T, as a copy of an existing \c CImg<t> instance, while forcing the shared state of the constructed copy. \param img Input image to copy. \param is_shared Tells about the shared state of the constructed copy. \note - Similar to CImg(const CImg<t>&), except that it allows to decide the shared state of the constructed image, which does not depend anymore on the shared state of the input image \c img: - If \c is_shared is \c true, the constructed copy will share its pixel buffer with the input image \c img. For that case, the pixel types \c T and \c t \e must be the same. - If \c is_shared is \c false, the constructed copy will allocate its own pixel buffer, whether the input image \c img is shared or not. - A \c CImgArgumentException is thrown when a shared copy is requested with different pixel types \c T and \c t. **/ template<typename t> CImg(const CImg<t>& img, const bool is_shared):_is_shared(false) { if (is_shared) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgArgumentException(_cimg_instance "CImg(): Invalid construction request of a shared instance from a " "CImg<%s> image (%u,%u,%u,%u,%p) (pixel types are different).", cimg_instance, CImg<t>::pixel_type(),img._width,img._height,img._depth,img._spectrum,img._data); } const size_t siz = (size_t)img.size(); if (img._data && siz) { _width = img._width; _height = img._height; _depth = img._depth; _spectrum = img._spectrum; try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*img._width*img._height*img._depth*img._spectrum), img._width,img._height,img._depth,img._spectrum); } const t *ptrs = img._data; cimg_for(*this,ptrd,T) *ptrd = (T)*(ptrs++); } else { _width = _height = _depth = _spectrum = 0; _data = 0; } } //! Advanced copy constructor \specialization. CImg(const CImg<T>& img, const bool is_shared) { const size_t siz = (size_t)img.size(); if (img._data && siz) { _width = img._width; _height = img._height; _depth = img._depth; _spectrum = img._spectrum; _is_shared = is_shared; if (_is_shared) _data = const_cast<T*>(img._data); else { try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*img._width*img._height*img._depth*img._spectrum), img._width,img._height,img._depth,img._spectrum); } std::memcpy(_data,img._data,siz*sizeof(T)); } } else { _width = _height = _depth = _spectrum = 0; _is_shared = false; _data = 0; } } //! Construct image with dimensions borrowed from another image. /** Construct a new image instance with pixels of type \c T, and size get from some dimensions of an existing \c CImg<t> instance. \param img Input image from which dimensions are borrowed. \param dimensions C-string describing the image size along the X,Y,Z and C-dimensions. \note - Similar to CImg(unsigned int,unsigned int,unsigned int,unsigned int), but it takes the image dimensions (\e not its pixel values) from an existing \c CImg<t> instance. - The allocated pixel buffer is \e not filled with a default value, and is likely to contain garbage values. In order to initialize pixel values (e.g. with \c 0), use constructor CImg(const CImg<t>&,const char*,T) instead. \par Example \code const CImg<float> img1(256,128,1,3), // 'img1' is a 256x128x1x3 image img2(img1,"xyzc"), // 'img2' is a 256x128x1x3 image img3(img1,"y,x,z,c"), // 'img3' is a 128x256x1x3 image img4(img1,"c,x,y,3",0), // 'img4' is a 3x128x256x3 image (with pixels initialized to '0') \endcode **/ template<typename t> CImg(const CImg<t>& img, const char *const dimensions): _width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { assign(img,dimensions); } //! Construct image with dimensions borrowed from another image and initialize pixel values. /** Construct a new image instance with pixels of type \c T, and size get from the dimensions of an existing \c CImg<t> instance, and set all pixel values to specified \c value. \param img Input image from which dimensions are borrowed. \param dimensions String describing the image size along the X,Y,Z and V-dimensions. \param value Value used for initialization. \note - Similar to CImg(const CImg<t>&,const char*), but it also fills the pixel buffer with the specified \c value. **/ template<typename t> CImg(const CImg<t>& img, const char *const dimensions, const T& value): _width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { assign(img,dimensions).fill(value); } //! Construct image from a display window. /** Construct a new image instance with pixels of type \c T, as a snapshot of an existing \c CImgDisplay instance. \param disp Input display window. \note - The width() and height() of the constructed image instance are the same as the specified \c CImgDisplay. - The depth() and spectrum() of the constructed image instance are respectively set to \c 1 and \c 3 (i.e. a 2D color image). - The image pixels are read as 8-bits RGB values. **/ explicit CImg(const CImgDisplay &disp):_width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { disp.snapshot(*this); } // Constructor and assignment operator for rvalue references (c++11). // This avoids an additional image copy for methods returning new images. Can save RAM for big images ! #if cimg_use_cpp11==1 CImg(CImg<T>&& img):_width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { swap(img); } CImg<T>& operator=(CImg<T>&& img) { if (_is_shared) return assign(img); return img.swap(*this); } #endif //! Construct empty image \inplace. /** In-place version of the default constructor CImg(). It simply resets the instance to an empty image. **/ CImg<T>& assign() { if (!_is_shared) delete[] _data; _width = _height = _depth = _spectrum = 0; _is_shared = false; _data = 0; return *this; } //! Construct image with specified size \inplace. /** In-place version of the constructor CImg(unsigned int,unsigned int,unsigned int,unsigned int). **/ CImg<T>& assign(const unsigned int size_x, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1) { const size_t siz = (size_t)size_x*size_y*size_z*size_c; if (!siz) return assign(); const size_t curr_siz = (size_t)size(); if (siz!=curr_siz) { if (_is_shared) throw CImgArgumentException(_cimg_instance "assign(): Invalid assignement request of shared instance from specified " "image (%u,%u,%u,%u).", cimg_instance, size_x,size_y,size_z,size_c); else { delete[] _data; try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "assign(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*size_x*size_y*size_z*size_c), size_x,size_y,size_z,size_c); } } } _width = size_x; _height = size_y; _depth = size_z; _spectrum = size_c; return *this; } //! Construct image with specified size and initialize pixel values \inplace. /** In-place version of the constructor CImg(unsigned int,unsigned int,unsigned int,unsigned int,T). **/ CImg<T>& assign(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const T& value) { return assign(size_x,size_y,size_z,size_c).fill(value); } //! Construct image with specified size and initialize pixel values from a sequence of integers \inplace. /** In-place version of the constructor CImg(unsigned int,unsigned int,unsigned int,unsigned int,int,int,...). **/ CImg<T>& assign(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const int value0, const int value1, ...) { assign(size_x,size_y,size_z,size_c); _CImg_stdarg(*this,value0,value1,(size_t)size_x*size_y*size_z*size_c,int); return *this; } //! Construct image with specified size and initialize pixel values from a sequence of doubles \inplace. /** In-place version of the constructor CImg(unsigned int,unsigned int,unsigned int,unsigned int,double,double,...). **/ CImg<T>& assign(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const double value0, const double value1, ...) { assign(size_x,size_y,size_z,size_c); _CImg_stdarg(*this,value0,value1,(size_t)size_x*size_y*size_z*size_c,double); return *this; } //! Construct image with specified size and initialize pixel values from a value string \inplace. /** In-place version of the constructor CImg(unsigned int,unsigned int,unsigned int,unsigned int,const char*,bool). **/ CImg<T>& assign(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const char *const values, const bool repeat_values) { return assign(size_x,size_y,size_z,size_c).fill(values,repeat_values); } //! Construct image with specified size and initialize pixel values from a memory buffer \inplace. /** In-place version of the constructor CImg(const t*,unsigned int,unsigned int,unsigned int,unsigned int). **/ template<typename t> CImg<T>& assign(const t *const values, const unsigned int size_x, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1) { const size_t siz = (size_t)size_x*size_y*size_z*size_c; if (!values || !siz) return assign(); assign(size_x,size_y,size_z,size_c); const t *ptrs = values; cimg_for(*this,ptrd,T) *ptrd = (T)*(ptrs++); return *this; } //! Construct image with specified size and initialize pixel values from a memory buffer \specialization. CImg<T>& assign(const T *const values, const unsigned int size_x, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1) { const size_t siz = (size_t)size_x*size_y*size_z*size_c; if (!values || !siz) return assign(); const size_t curr_siz = (size_t)size(); if (values==_data && siz==curr_siz) return assign(size_x,size_y,size_z,size_c); if (_is_shared || values + siz<_data || values>=_data + size()) { assign(size_x,size_y,size_z,size_c); if (_is_shared) std::memmove((void*)_data,(void*)values,siz*sizeof(T)); else std::memcpy((void*)_data,(void*)values,siz*sizeof(T)); } else { T *new_data = 0; try { new_data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "assign(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*size_x*size_y*size_z*size_c), size_x,size_y,size_z,size_c); } std::memcpy((void*)new_data,(void*)values,siz*sizeof(T)); delete[] _data; _data = new_data; _width = size_x; _height = size_y; _depth = size_z; _spectrum = size_c; } return *this; } //! Construct image with specified size and initialize pixel values from a memory buffer \overloading. template<typename t> CImg<T>& assign(const t *const values, const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const bool is_shared) { if (is_shared) throw CImgArgumentException(_cimg_instance "assign(): Invalid assignment request of shared instance from (%s*) buffer" "(pixel types are different).", cimg_instance, CImg<t>::pixel_type()); return assign(values,size_x,size_y,size_z,size_c); } //! Construct image with specified size and initialize pixel values from a memory buffer \overloading. CImg<T>& assign(const T *const values, const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const bool is_shared) { const size_t siz = (size_t)size_x*size_y*size_z*size_c; if (!values || !siz) return assign(); if (!is_shared) { if (_is_shared) assign(); assign(values,size_x,size_y,size_z,size_c); } else { if (!_is_shared) { if (values + siz<_data || values>=_data + size()) assign(); else cimg::warn(_cimg_instance "assign(): Shared image instance has overlapping memory.", cimg_instance); } _width = size_x; _height = size_y; _depth = size_z; _spectrum = size_c; _is_shared = true; _data = const_cast<T*>(values); } return *this; } //! Construct image from reading an image file \inplace. /** In-place version of the constructor CImg(const char*). **/ CImg<T>& assign(const char *const filename) { return load(filename); } //! Construct image copy \inplace. /** In-place version of the constructor CImg(const CImg<t>&). **/ template<typename t> CImg<T>& assign(const CImg<t>& img) { return assign(img._data,img._width,img._height,img._depth,img._spectrum); } //! In-place version of the advanced copy constructor. /** In-place version of the constructor CImg(const CImg<t>&,bool). **/ template<typename t> CImg<T>& assign(const CImg<t>& img, const bool is_shared) { return assign(img._data,img._width,img._height,img._depth,img._spectrum,is_shared); } //! Construct image with dimensions borrowed from another image \inplace. /** In-place version of the constructor CImg(const CImg<t>&,const char*). **/ template<typename t> CImg<T>& assign(const CImg<t>& img, const char *const dimensions) { if (!dimensions || !*dimensions) return assign(img._width,img._height,img._depth,img._spectrum); unsigned int siz[4] = { 0,1,1,1 }, k = 0; CImg<charT> item(256); for (const char *s = dimensions; *s && k<4; ++k) { if (cimg_sscanf(s,"%255[^0-9%xyzvwhdcXYZVWHDC]",item._data)>0) s+=std::strlen(item); if (*s) { unsigned int val = 0; char sep = 0; if (cimg_sscanf(s,"%u%c",&val,&sep)>0) { if (sep=='%') siz[k] = val*(k==0?_width:k==1?_height:k==2?_depth:_spectrum)/100; else siz[k] = val; while (*s>='0' && *s<='9') ++s; if (sep=='%') ++s; } else switch (cimg::lowercase(*s)) { case 'x' : case 'w' : siz[k] = img._width; ++s; break; case 'y' : case 'h' : siz[k] = img._height; ++s; break; case 'z' : case 'd' : siz[k] = img._depth; ++s; break; case 'c' : case 's' : siz[k] = img._spectrum; ++s; break; default : throw CImgArgumentException(_cimg_instance "assign(): Invalid character '%c' detected in specified dimension string '%s'.", cimg_instance, *s,dimensions); } } } return assign(siz[0],siz[1],siz[2],siz[3]); } //! Construct image with dimensions borrowed from another image and initialize pixel values \inplace. /** In-place version of the constructor CImg(const CImg<t>&,const char*,T). **/ template<typename t> CImg<T>& assign(const CImg<t>& img, const char *const dimensions, const T& value) { return assign(img,dimensions).fill(value); } //! Construct image from a display window \inplace. /** In-place version of the constructor CImg(const CImgDisplay&). **/ CImg<T>& assign(const CImgDisplay &disp) { disp.snapshot(*this); return *this; } //! Construct empty image \inplace. /** Equivalent to assign(). \note - It has been defined for compatibility with STL naming conventions. **/ CImg<T>& clear() { return assign(); } //! Transfer content of an image instance into another one. /** Transfer the dimensions and the pixel buffer content of an image instance into another one, and replace instance by an empty image. It avoids the copy of the pixel buffer when possible. \param img Destination image. \note - Pixel types \c T and \c t of source and destination images can be different, though the process is designed to be instantaneous when \c T and \c t are the same. \par Example \code CImg<float> src(256,256,1,3,0), // Construct a 256x256x1x3 (color) image filled with value '0' dest(16,16); // Construct a 16x16x1x1 (scalar) image src.move_to(dest); // Now, 'src' is empty and 'dest' is the 256x256x1x3 image \endcode **/ template<typename t> CImg<t>& move_to(CImg<t>& img) { img.assign(*this); assign(); return img; } //! Transfer content of an image instance into another one \specialization. CImg<T>& move_to(CImg<T>& img) { if (_is_shared || img._is_shared) img.assign(*this); else swap(img); assign(); return img; } //! Transfer content of an image instance into a new image in an image list. /** Transfer the dimensions and the pixel buffer content of an image instance into a newly inserted image at position \c pos in specified \c CImgList<t> instance. \param list Destination list. \param pos Position of the newly inserted image in the list. \note - When optional parameter \c pos is ommited, the image instance is transfered as a new image at the end of the specified \c list. - It is convenient to sequentially insert new images into image lists, with no additional copies of memory buffer. \par Example \code CImgList<float> list; // Construct an empty image list CImg<float> img("reference.jpg"); // Read image from filename img.move_to(list); // Transfer image content as a new item in the list (no buffer copy) \endcode **/ template<typename t> CImgList<t>& move_to(CImgList<t>& list, const unsigned int pos=~0U) { const unsigned int npos = pos>list._width?list._width:pos; move_to(list.insert(1,npos)[npos]); return list; } //! Swap fields of two image instances. /** \param img Image to swap fields with. \note - It can be used to interchange the content of two images in a very fast way. Can be convenient when dealing with algorithms requiring two swapping buffers. \par Example \code CImg<float> img1("lena.jpg"), img2("milla.jpg"); img1.swap(img2); // Now, 'img1' is 'milla' and 'img2' is 'lena' \endcode **/ CImg<T>& swap(CImg<T>& img) { cimg::swap(_width,img._width,_height,img._height,_depth,img._depth,_spectrum,img._spectrum); cimg::swap(_data,img._data); cimg::swap(_is_shared,img._is_shared); return img; } //! Return a reference to an empty image. /** \note This function is useful mainly to declare optional parameters having type \c CImg<T> in functions prototypes, e.g. \code void f(const int x=0, const int y=0, const CImg<float>& img=CImg<float>::empty()); \endcode **/ static CImg<T>& empty() { static CImg<T> _empty; return _empty.assign(); } //! Return a reference to an empty image \const. static const CImg<T>& const_empty() { static const CImg<T> _empty; return _empty; } //@} //------------------------------------------ // //! \name Overloaded Operators //@{ //------------------------------------------ //! Access to a pixel value. /** Return a reference to a located pixel value of the image instance, being possibly \e const, whether the image instance is \e const or not. This is the standard method to get/set pixel values in \c CImg<T> images. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note - Range of pixel coordinates start from <tt>(0,0,0,0)</tt> to <tt>(width() - 1,height() - 1,depth() - 1,spectrum() - 1)</tt>. - Due to the particular arrangement of the pixel buffers defined in %CImg, you can omit one coordinate if the corresponding dimension is equal to \c 1. For instance, pixels of a 2D image (depth() equal to \c 1) can be accessed by <tt>img(x,y,c)</tt> instead of <tt>img(x,y,0,c)</tt>. \warning - There is \e no boundary checking done in this operator, to make it as fast as possible. You \e must take care of out-of-bounds access by yourself, if necessary. For debuging purposes, you may want to define macro \c 'cimg_verbosity'>=3 to enable additional boundary checking operations in this operator. In that case, warning messages will be printed on the error output when accessing out-of-bounds pixels. \par Example \code CImg<float> img(100,100,1,3,0); // Construct a 100x100x1x3 (color) image with pixels set to '0' const float valR = img(10,10,0,0), // Read red value at coordinates (10,10) valG = img(10,10,0,1), // Read green value at coordinates (10,10) valB = img(10,10,2), // Read blue value at coordinates (10,10) (Z-coordinate can be omitted) avg = (valR + valG + valB)/3; // Compute average pixel value img(10,10,0) = img(10,10,1) = img(10,10,2) = avg; // Replace the color pixel (10,10) by the average grey value \endcode **/ #if cimg_verbosity>=3 T& operator()(const unsigned int x, const unsigned int y=0, const unsigned int z=0, const unsigned int c=0) { const ulongT off = (ulongT)offset(x,y,z,c); if (!_data || off>=size()) { cimg::warn(_cimg_instance "operator(): Invalid pixel request, at coordinates (%d,%d,%d,%d) [offset=%u].", cimg_instance, (int)x,(int)y,(int)z,(int)c,off); return *_data; } else return _data[off]; } //! Access to a pixel value \const. const T& operator()(const unsigned int x, const unsigned int y=0, const unsigned int z=0, const unsigned int c=0) const { return const_cast<CImg<T>*>(this)->operator()(x,y,z,c); } //! Access to a pixel value. /** \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param wh Precomputed offset, must be equal to <tt>width()*\ref height()</tt>. \param whd Precomputed offset, must be equal to <tt>width()*\ref height()*\ref depth()</tt>. \note - Similar to (but faster than) operator()(). It uses precomputed offsets to optimize memory access. You may use it to optimize the reading/writing of several pixel values in the same image (e.g. in a loop). **/ T& operator()(const unsigned int x, const unsigned int y, const unsigned int z, const unsigned int c, const ulongT wh, const ulongT whd=0) { cimg::unused(wh,whd); return (*this)(x,y,z,c); } //! Access to a pixel value \const. const T& operator()(const unsigned int x, const unsigned int y, const unsigned int z, const unsigned int c, const ulongT wh, const ulongT whd=0) const { cimg::unused(wh,whd); return (*this)(x,y,z,c); } #else T& operator()(const unsigned int x) { return _data[x]; } const T& operator()(const unsigned int x) const { return _data[x]; } T& operator()(const unsigned int x, const unsigned int y) { return _data[x + y*_width]; } const T& operator()(const unsigned int x, const unsigned int y) const { return _data[x + y*_width]; } T& operator()(const unsigned int x, const unsigned int y, const unsigned int z) { return _data[x + y*(ulongT)_width + z*(ulongT)_width*_height]; } const T& operator()(const unsigned int x, const unsigned int y, const unsigned int z) const { return _data[x + y*(ulongT)_width + z*(ulongT)_width*_height]; } T& operator()(const unsigned int x, const unsigned int y, const unsigned int z, const unsigned int c) { return _data[x + y*(ulongT)_width + z*(ulongT)_width*_height + c*(ulongT)_width*_height*_depth]; } const T& operator()(const unsigned int x, const unsigned int y, const unsigned int z, const unsigned int c) const { return _data[x + y*(ulongT)_width + z*(ulongT)_width*_height + c*(ulongT)_width*_height*_depth]; } T& operator()(const unsigned int x, const unsigned int y, const unsigned int z, const unsigned int, const ulongT wh) { return _data[x + y*_width + z*wh]; } const T& operator()(const unsigned int x, const unsigned int y, const unsigned int z, const unsigned int, const ulongT wh) const { return _data[x + y*_width + z*wh]; } T& operator()(const unsigned int x, const unsigned int y, const unsigned int z, const unsigned int c, const ulongT wh, const ulongT whd) { return _data[x + y*_width + z*wh + c*whd]; } const T& operator()(const unsigned int x, const unsigned int y, const unsigned int z, const unsigned int c, const ulongT wh, const ulongT whd) const { return _data[x + y*_width + z*wh + c*whd]; } #endif //! Implicitely cast an image into a \c T*. /** Implicitely cast a \c CImg<T> instance into a \c T* or \c const \c T* pointer, whether the image instance is \e const or not. The returned pointer points on the first value of the image pixel buffer. \note - It simply returns the pointer data() to the pixel buffer. - This implicit conversion is convenient to test the empty state of images (data() being \c 0 in this case), e.g. \code CImg<float> img1(100,100), img2; // 'img1' is a 100x100 image, 'img2' is an empty image if (img1) { // Test succeeds, 'img1' is not an empty image if (!img2) { // Test succeeds, 'img2' is an empty image std::printf("'img1' is not empty, 'img2' is empty."); } } \endcode - It also allows to use brackets to access pixel values, without need for a \c CImg<T>::operator[](), e.g. \code CImg<float> img(100,100); const float value = img[99]; // Access to value of the last pixel on the first row img[510] = 255; // Set pixel value at (10,5) \endcode **/ operator T*() { return _data; } //! Implicitely cast an image into a \c T* \const. operator const T*() const { return _data; } //! Assign a value to all image pixels. /** Assign specified \c value to each pixel value of the image instance. \param value Value that will be assigned to image pixels. \note - The image size is never modified. - The \c value may be casted to pixel type \c T if necessary. \par Example \code CImg<char> img(100,100); // Declare image (with garbage values) img = 0; // Set all pixel values to '0' img = 1.2; // Set all pixel values to '1' (cast of '1.2' as a 'char') \endcode **/ CImg<T>& operator=(const T& value) { return fill(value); } //! Assign pixels values from a specified expression. /** Initialize all pixel values from the specified string \c expression. \param expression Value string describing the way pixel values are set. \note - String parameter \c expression may describe different things: - If \c expression is a list of values (as in \c "1,2,3,8,3,2"), or a formula (as in \c "(x*y)%255"), the pixel values are set from specified \c expression and the image size is not modified. - If \c expression is a filename (as in \c "reference.jpg"), the corresponding image file is loaded and replace the image instance. The image size is modified if necessary. \par Example \code CImg<float> img1(100,100), img2(img1), img3(img1); // Declare 3 scalar images 100x100 with unitialized values img1 = "0,50,100,150,200,250,200,150,100,50"; // Set pixel values of 'img1' from a value sequence img2 = "10*((x*y)%25)"; // Set pixel values of 'img2' from a formula img3 = "reference.jpg"; // Set pixel values of 'img3' from a file (image size is modified) (img1,img2,img3).display(); \endcode \image html ref_operator_eq.jpg **/ CImg<T>& operator=(const char *const expression) { const unsigned int omode = cimg::exception_mode(); cimg::exception_mode(0); try { _fill(expression,true,1,0,0,"operator=",0); } catch (CImgException&) { cimg::exception_mode(omode); load(expression); } cimg::exception_mode(omode); return *this; } //! Copy an image into the current image instance. /** Similar to the in-place copy constructor assign(const CImg<t>&). **/ template<typename t> CImg<T>& operator=(const CImg<t>& img) { return assign(img); } //! Copy an image into the current image instance \specialization. CImg<T>& operator=(const CImg<T>& img) { return assign(img); } //! Copy the content of a display window to the current image instance. /** Similar to assign(const CImgDisplay&). **/ CImg<T>& operator=(const CImgDisplay& disp) { disp.snapshot(*this); return *this; } //! In-place addition operator. /** Add specified \c value to all pixels of an image instance. \param value Value to add. \note - Resulting pixel values are casted to fit the pixel type \c T. For instance, adding \c 0.2 to a \c CImg<char> is possible but does nothing indeed. - Overflow values are treated as with standard C++ numeric types. For instance, \code CImg<unsigned char> img(100,100,1,1,255); // Construct a 100x100 image with pixel values '255' img+=1; // Add '1' to each pixels -> Overflow // here all pixels of image 'img' are equal to '0'. \endcode - To prevent value overflow, you may want to consider pixel type \c T as \c float or \c double, and use cut() after addition. \par Example \code CImg<unsigned char> img1("reference.jpg"); // Load a 8-bits RGB image (values in [0,255]) CImg<float> img2(img1); // Construct a float-valued copy of 'img1' img2+=100; // Add '100' to pixel values -> goes out of [0,255] but no problems with floats img2.cut(0,255); // Cut values in [0,255] to fit the 'unsigned char' constraint img1 = img2; // Rewrite safe result in 'unsigned char' version 'img1' const CImg<unsigned char> img3 = (img1 + 100).cut(0,255); // Do the same in a more simple and elegant way (img1,img2,img3).display(); \endcode \image html ref_operator_plus.jpg **/ template<typename t> CImg<T>& operator+=(const t value) { if (is_empty()) return *this; cimg_openmp_for(*this,*ptr + value,524288); return *this; } //! In-place addition operator. /** Add values to image pixels, according to the specified string \c expression. \param expression Value string describing the way pixel values are added. \note - Similar to operator=(const char*), except that it adds values to the pixels of the current image instance, instead of assigning them. **/ CImg<T>& operator+=(const char *const expression) { return *this+=(+*this)._fill(expression,true,1,0,0,"operator+=",this); } //! In-place addition operator. /** Add values to image pixels, according to the values of the input image \c img. \param img Input image to add. \note - The size of the image instance is never modified. - It is not mandatory that input image \c img has the same size as the image instance. If less values are available in \c img, then the values are added periodically. For instance, adding one WxH scalar image (spectrum() equal to \c 1) to one WxH color image (spectrum() equal to \c 3) means each color channel will be incremented with the same values at the same locations. \par Example \code CImg<float> img1("reference.jpg"); // Load a RGB color image (img1.spectrum()==3) // Construct a scalar shading (img2.spectrum()==1). const CImg<float> img2(img1.width(),img.height(),1,1,"255*(x/w)^2"); img1+=img2; // Add shading to each channel of 'img1' img1.cut(0,255); // Prevent [0,255] overflow (img2,img1).display(); \endcode \image html ref_operator_plus1.jpg **/ template<typename t> CImg<T>& operator+=(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return *this+=+img; T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)(*ptrd + *(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)(*ptrd + *(ptrs++)); } return *this; } //! In-place increment operator (prefix). /** Add \c 1 to all image pixels, and return a reference to the current incremented image instance. \note - Writing \c ++img is equivalent to \c img+=1. **/ CImg<T>& operator++() { if (is_empty()) return *this; cimg_openmp_for(*this,*ptr + 1,524288); return *this; } //! In-place increment operator (postfix). /** Add \c 1 to all image pixels, and return a new copy of the initial (pre-incremented) image instance. \note - Use the prefixed version operator++() if you don't need a copy of the initial (pre-incremented) image instance, since a useless image copy may be expensive in terms of memory usage. **/ CImg<T> operator++(int) { const CImg<T> copy(*this,false); ++*this; return copy; } //! Return a non-shared copy of the image instance. /** \note - Use this operator to ensure you get a non-shared copy of an image instance with same pixel type \c T. Indeed, the usual copy constructor CImg<T>(const CImg<T>&) returns a shared copy of a shared input image, and it may be not desirable to work on a regular copy (e.g. for a resize operation) if you have no information about the shared state of the input image. - Writing \c (+img) is equivalent to \c CImg<T>(img,false). **/ CImg<T> operator+() const { return CImg<T>(*this,false); } //! Addition operator. /** Similar to operator+=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator+(const t value) const { return CImg<_cimg_Tt>(*this,false)+=value; } //! Addition operator. /** Similar to operator+=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ CImg<Tfloat> operator+(const char *const expression) const { return CImg<Tfloat>(*this,false)+=expression; } //! Addition operator. /** Similar to operator+=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator+(const CImg<t>& img) const { return CImg<_cimg_Tt>(*this,false)+=img; } //! In-place substraction operator. /** Similar to operator+=(const t), except that it performs a substraction instead of an addition. **/ template<typename t> CImg<T>& operator-=(const t value) { if (is_empty()) return *this; cimg_openmp_for(*this,*ptr - value,524288); return *this; } //! In-place substraction operator. /** Similar to operator+=(const char*), except that it performs a substraction instead of an addition. **/ CImg<T>& operator-=(const char *const expression) { return *this-=(+*this)._fill(expression,true,1,0,0,"operator-=",this); } //! In-place substraction operator. /** Similar to operator+=(const CImg<t>&), except that it performs a substraction instead of an addition. **/ template<typename t> CImg<T>& operator-=(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return *this-=+img; T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)(*ptrd - *(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)(*ptrd - *(ptrs++)); } return *this; } //! In-place decrement operator (prefix). /** Similar to operator++(), except that it performs a decrement instead of an increment. **/ CImg<T>& operator--() { if (is_empty()) return *this; cimg_openmp_for(*this,*ptr - 1,524288); return *this; } //! In-place decrement operator (postfix). /** Similar to operator++(int), except that it performs a decrement instead of an increment. **/ CImg<T> operator--(int) { const CImg<T> copy(*this,false); --*this; return copy; } //! Replace each pixel by its opposite value. /** \note - If the computed opposite values are out-of-range, they are treated as with standard C++ numeric types. For instance, the \c unsigned \c char opposite of \c 1 is \c 255. \par Example \code const CImg<unsigned char> img1("reference.jpg"), // Load a RGB color image img2 = -img1; // Compute its opposite (in 'unsigned char') (img1,img2).display(); \endcode \image html ref_operator_minus.jpg **/ CImg<T> operator-() const { return CImg<T>(_width,_height,_depth,_spectrum,(T)0)-=*this; } //! Substraction operator. /** Similar to operator-=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator-(const t value) const { return CImg<_cimg_Tt>(*this,false)-=value; } //! Substraction operator. /** Similar to operator-=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ CImg<Tfloat> operator-(const char *const expression) const { return CImg<Tfloat>(*this,false)-=expression; } //! Substraction operator. /** Similar to operator-=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator-(const CImg<t>& img) const { return CImg<_cimg_Tt>(*this,false)-=img; } //! In-place multiplication operator. /** Similar to operator+=(const t), except that it performs a multiplication instead of an addition. **/ template<typename t> CImg<T>& operator*=(const t value) { if (is_empty()) return *this; cimg_openmp_for(*this,*ptr * value,262144); return *this; } //! In-place multiplication operator. /** Similar to operator+=(const char*), except that it performs a multiplication instead of an addition. **/ CImg<T>& operator*=(const char *const expression) { return mul((+*this)._fill(expression,true,1,0,0,"operator*=",this)); } //! In-place multiplication operator. /** Replace the image instance by the matrix multiplication between the image instance and the specified matrix \c img. \param img Second operand of the matrix multiplication. \note - It does \e not compute a pointwise multiplication between two images. For this purpose, use mul(const CImg<t>&) instead. - The size of the image instance can be modified by this operator. \par Example \code CImg<float> A(2,2,1,1, 1,2,3,4); // Construct 2x2 matrix A = [1,2;3,4] const CImg<float> X(1,2,1,1, 1,2); // Construct 1x2 vector X = [1;2] A*=X; // Assign matrix multiplication A*X to 'A' // 'A' is now a 1x2 vector whose values are [5;11]. \endcode **/ template<typename t> CImg<T>& operator*=(const CImg<t>& img) { return ((*this)*img).move_to(*this); } //! Multiplication operator. /** Similar to operator*=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator*(const t value) const { return CImg<_cimg_Tt>(*this,false)*=value; } //! Multiplication operator. /** Similar to operator*=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ CImg<Tfloat> operator*(const char *const expression) const { return CImg<Tfloat>(*this,false)*=expression; } //! Multiplication operator. /** Similar to operator*=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator*(const CImg<t>& img) const { typedef _cimg_Ttdouble Ttdouble; typedef _cimg_Tt Tt; if (_width!=img._height || _depth!=1 || _spectrum!=1) throw CImgArgumentException(_cimg_instance "operator*(): Invalid multiplication of instance by specified " "matrix (%u,%u,%u,%u,%p)", cimg_instance, img._width,img._height,img._depth,img._spectrum,img._data); CImg<Tt> res(img._width,_height); // Check for common cases to optimize. if (img._width==1) { // Matrix * Vector if (_height==1) switch (_width) { // Vector^T * Vector case 1 : res[0] = (Tt)((Ttdouble)_data[0]*img[0]); return res; case 2 : res[0] = (Tt)((Ttdouble)_data[0]*img[0] + (Ttdouble)_data[1]*img[1]); return res; case 3 : res[0] = (Tt)((Ttdouble)_data[0]*img[0] + (Ttdouble)_data[1]*img[1] + (Ttdouble)_data[2]*img[2]); return res; case 4 : res[0] = (Tt)((Ttdouble)_data[0]*img[0] + (Ttdouble)_data[1]*img[1] + (Ttdouble)_data[2]*img[2] + (Ttdouble)_data[3]*img[3]); return res; default : { Ttdouble val = 0; cimg_forX(*this,i) val+=(Ttdouble)_data[i]*img[i]; res[0] = val; return res; } } else if (_height==_width) switch (_width) { // Square_matrix * Vector case 2 : // 2x2_matrix * Vector res[0] = (Tt)((Ttdouble)_data[0]*img[0] + (Ttdouble)_data[1]*img[1]); res[1] = (Tt)((Ttdouble)_data[2]*img[0] + (Ttdouble)_data[3]*img[1]); return res; case 3 : // 3x3_matrix * Vector res[0] = (Tt)((Ttdouble)_data[0]*img[0] + (Ttdouble)_data[1]*img[1] + (Ttdouble)_data[2]*img[2]); res[1] = (Tt)((Ttdouble)_data[3]*img[0] + (Ttdouble)_data[4]*img[1] + (Ttdouble)_data[5]*img[2]); res[2] = (Tt)((Ttdouble)_data[6]*img[0] + (Ttdouble)_data[7]*img[1] + (Ttdouble)_data[8]*img[2]); return res; case 4 : // 4x4_matrix * Vector res[0] = (Tt)((Ttdouble)_data[0]*img[0] + (Ttdouble)_data[1]*img[1] + (Ttdouble)_data[2]*img[2] + (Ttdouble)_data[3]*img[3]); res[1] = (Tt)((Ttdouble)_data[4]*img[0] + (Ttdouble)_data[5]*img[1] + (Ttdouble)_data[6]*img[2] + (Ttdouble)_data[7]*img[3]); res[2] = (Tt)((Ttdouble)_data[8]*img[0] + (Ttdouble)_data[9]*img[1] + (Ttdouble)_data[10]*img[2] + (Ttdouble)_data[11]*img[3]); res[3] = (Tt)((Ttdouble)_data[12]*img[0] + (Ttdouble)_data[13]*img[1] + (Ttdouble)_data[14]*img[2] + (Ttdouble)_data[15]*img[3]); return res; } } else if (_height==_width) { if (img._height==img._width) switch (_width) { // Square_matrix * Square_matrix case 2 : // 2x2_matrix * 2x2_matrix res[0] = (Tt)((Ttdouble)_data[0]*img[0] + (Ttdouble)_data[1]*img[2]); res[1] = (Tt)((Ttdouble)_data[0]*img[1] + (Ttdouble)_data[1]*img[3]); res[2] = (Tt)((Ttdouble)_data[2]*img[0] + (Ttdouble)_data[3]*img[2]); res[3] = (Tt)((Ttdouble)_data[2]*img[1] + (Ttdouble)_data[3]*img[3]); return res; case 3 : // 3x3_matrix * 3x3_matrix res[0] = (Tt)((Ttdouble)_data[0]*img[0] + (Ttdouble)_data[1]*img[3] + (Ttdouble)_data[2]*img[6]); res[1] = (Tt)((Ttdouble)_data[0]*img[1] + (Ttdouble)_data[1]*img[4] + (Ttdouble)_data[2]*img[7]); res[2] = (Tt)((Ttdouble)_data[0]*img[2] + (Ttdouble)_data[1]*img[5] + (Ttdouble)_data[2]*img[8]); res[3] = (Tt)((Ttdouble)_data[3]*img[0] + (Ttdouble)_data[4]*img[3] + (Ttdouble)_data[5]*img[6]); res[4] = (Tt)((Ttdouble)_data[3]*img[1] + (Ttdouble)_data[4]*img[4] + (Ttdouble)_data[5]*img[7]); res[5] = (Tt)((Ttdouble)_data[3]*img[2] + (Ttdouble)_data[4]*img[5] + (Ttdouble)_data[5]*img[8]); res[6] = (Tt)((Ttdouble)_data[6]*img[0] + (Ttdouble)_data[7]*img[3] + (Ttdouble)_data[8]*img[6]); res[7] = (Tt)((Ttdouble)_data[6]*img[1] + (Ttdouble)_data[7]*img[4] + (Ttdouble)_data[8]*img[7]); res[8] = (Tt)((Ttdouble)_data[6]*img[2] + (Ttdouble)_data[7]*img[5] + (Ttdouble)_data[8]*img[8]); return res; case 4 : // 4x4_matrix * 4x4_matrix res[0] = (Tt)((Ttdouble)_data[0]*img[0] + (Ttdouble)_data[1]*img[4] + (Ttdouble)_data[2]*img[8] + (Ttdouble)_data[3]*img[12]); res[1] = (Tt)((Ttdouble)_data[0]*img[1] + (Ttdouble)_data[1]*img[5] + (Ttdouble)_data[2]*img[9] + (Ttdouble)_data[3]*img[13]); res[2] = (Tt)((Ttdouble)_data[0]*img[2] + (Ttdouble)_data[1]*img[6] + (Ttdouble)_data[2]*img[10] + (Ttdouble)_data[3]*img[14]); res[3] = (Tt)((Ttdouble)_data[0]*img[3] + (Ttdouble)_data[1]*img[7] + (Ttdouble)_data[2]*img[11] + (Ttdouble)_data[3]*img[15]); res[4] = (Tt)((Ttdouble)_data[4]*img[0] + (Ttdouble)_data[5]*img[4] + (Ttdouble)_data[6]*img[8] + (Ttdouble)_data[7]*img[12]); res[5] = (Tt)((Ttdouble)_data[4]*img[1] + (Ttdouble)_data[5]*img[5] + (Ttdouble)_data[6]*img[9] + (Ttdouble)_data[7]*img[13]); res[6] = (Tt)((Ttdouble)_data[4]*img[2] + (Ttdouble)_data[5]*img[6] + (Ttdouble)_data[6]*img[10] + (Ttdouble)_data[7]*img[14]); res[7] = (Tt)((Ttdouble)_data[4]*img[3] + (Ttdouble)_data[5]*img[7] + (Ttdouble)_data[6]*img[11] + (Ttdouble)_data[7]*img[15]); res[8] = (Tt)((Ttdouble)_data[8]*img[0] + (Ttdouble)_data[9]*img[4] + (Ttdouble)_data[10]*img[8] + (Ttdouble)_data[11]*img[12]); res[9] = (Tt)((Ttdouble)_data[8]*img[1] + (Ttdouble)_data[9]*img[5] + (Ttdouble)_data[10]*img[9] + (Ttdouble)_data[11]*img[13]); res[10] = (Tt)((Ttdouble)_data[8]*img[2] + (Ttdouble)_data[9]*img[6] + (Ttdouble)_data[10]*img[10] + (Ttdouble)_data[11]*img[14]); res[11] = (Tt)((Ttdouble)_data[8]*img[3] + (Ttdouble)_data[9]*img[7] + (Ttdouble)_data[10]*img[11] + (Ttdouble)_data[11]*img[15]); res[12] = (Tt)((Ttdouble)_data[12]*img[0] + (Ttdouble)_data[13]*img[4] + (Ttdouble)_data[14]*img[8] + (Ttdouble)_data[15]*img[12]); res[13] = (Tt)((Ttdouble)_data[12]*img[1] + (Ttdouble)_data[13]*img[5] + (Ttdouble)_data[14]*img[9] + (Ttdouble)_data[15]*img[13]); res[14] = (Tt)((Ttdouble)_data[12]*img[2] + (Ttdouble)_data[13]*img[6] + (Ttdouble)_data[14]*img[10] + (Ttdouble)_data[15]*img[14]); res[15] = (Tt)((Ttdouble)_data[12]*img[3] + (Ttdouble)_data[13]*img[7] + (Ttdouble)_data[14]*img[11] + (Ttdouble)_data[15]*img[15]); return res; } else switch (_width) { // Square_matrix * Matrix case 2 : { // 2x2_matrix * Matrix const t *ps0 = img.data(), *ps1 = img.data(0,1); Tt *pd0 = res.data(), *pd1 = res.data(0,1); const Ttdouble a0 = (Ttdouble)_data[0], a1 = (Ttdouble)_data[1], a2 = (Ttdouble)_data[2], a3 = (Ttdouble)_data[3]; cimg_forX(img,i) { const Ttdouble x = (Ttdouble)*(ps0++), y = (Ttdouble)*(ps1++); *(pd0++) = (Tt)(a0*x + a1*y); *(pd1++) = (Tt)(a2*x + a3*y); } return res; } case 3 : { // 3x3_matrix * Matrix const t *ps0 = img.data(), *ps1 = img.data(0,1), *ps2 = img.data(0,2); Tt *pd0 = res.data(), *pd1 = res.data(0,1), *pd2 = res.data(0,2); const Ttdouble a0 = (Ttdouble)_data[0], a1 = (Ttdouble)_data[1], a2 = (Ttdouble)_data[2], a3 = (Ttdouble)_data[3], a4 = (Ttdouble)_data[4], a5 = (Ttdouble)_data[5], a6 = (Ttdouble)_data[6], a7 = (Ttdouble)_data[7], a8 = (Ttdouble)_data[8]; cimg_forX(img,i) { const Ttdouble x = (Ttdouble)*(ps0++), y = (Ttdouble)*(ps1++), z = (Ttdouble)*(ps2++); *(pd0++) = (Tt)(a0*x + a1*y + a2*z); *(pd1++) = (Tt)(a3*x + a4*y + a5*z); *(pd2++) = (Tt)(a6*x + a7*y + a8*z); } return res; } case 4 : { // 4x4_matrix * Matrix const t *ps0 = img.data(), *ps1 = img.data(0,1), *ps2 = img.data(0,2), *ps3 = img.data(0,3); Tt *pd0 = res.data(), *pd1 = res.data(0,1), *pd2 = res.data(0,2), *pd3 = res.data(0,3); const Ttdouble a0 = (Ttdouble)_data[0], a1 = (Ttdouble)_data[1], a2 = (Ttdouble)_data[2], a3 = (Ttdouble)_data[3], a4 = (Ttdouble)_data[4], a5 = (Ttdouble)_data[5], a6 = (Ttdouble)_data[6], a7 = (Ttdouble)_data[7], a8 = (Ttdouble)_data[8], a9 = (Ttdouble)_data[9], a10 = (Ttdouble)_data[10], a11 = (Ttdouble)_data[11], a12 = (Ttdouble)_data[12], a13 = (Ttdouble)_data[13], a14 = (Ttdouble)_data[14], a15 = (Ttdouble)_data[15]; cimg_forX(img,col) { const Ttdouble x = (Ttdouble)*(ps0++), y = (Ttdouble)*(ps1++), z = (Ttdouble)*(ps2++), c = (Ttdouble)*(ps3++); *(pd0++) = (Tt)(a0*x + a1*y + a2*z + a3*c); *(pd1++) = (Tt)(a4*x + a5*y + a6*z + a7*c); *(pd2++) = (Tt)(a8*x + a9*y + a10*z + a11*c); *(pd3++) = (Tt)(a12*x + a13*y + a14*z + a15*c); } return res; } } } // Fallback to generic version. #if cimg_use_openmp!=0 cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(size()>(cimg_openmp_sizefactor)*1024 && img.size()>(cimg_openmp_sizefactor)*1024)) cimg_forXY(res,i,j) { Ttdouble value = 0; cimg_forX(*this,k) value+=(*this)(k,j)*img(i,k); res(i,j) = (Tt)value; } #else Tt *ptrd = res._data; cimg_forXY(res,i,j) { Ttdouble value = 0; cimg_forX(*this,k) value+=(*this)(k,j)*img(i,k); *(ptrd++) = (Tt)value; } #endif return res; } //! In-place division operator. /** Similar to operator+=(const t), except that it performs a division instead of an addition. **/ template<typename t> CImg<T>& operator/=(const t value) { if (is_empty()) return *this; cimg_openmp_for(*this,*ptr / value,32768); return *this; } //! In-place division operator. /** Similar to operator+=(const char*), except that it performs a division instead of an addition. **/ CImg<T>& operator/=(const char *const expression) { return div((+*this)._fill(expression,true,1,0,0,"operator/=",this)); } //! In-place division operator. /** Replace the image instance by the (right) matrix division between the image instance and the specified matrix \c img. \param img Second operand of the matrix division. \note - It does \e not compute a pointwise division between two images. For this purpose, use div(const CImg<t>&) instead. - It returns the matrix operation \c A*inverse(img). - The size of the image instance can be modified by this operator. **/ template<typename t> CImg<T>& operator/=(const CImg<t>& img) { return (*this*img.get_invert()).move_to(*this); } //! Division operator. /** Similar to operator/=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator/(const t value) const { return CImg<_cimg_Tt>(*this,false)/=value; } //! Division operator. /** Similar to operator/=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ CImg<Tfloat> operator/(const char *const expression) const { return CImg<Tfloat>(*this,false)/=expression; } //! Division operator. /** Similar to operator/=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator/(const CImg<t>& img) const { return (*this)*img.get_invert(); } //! In-place modulo operator. /** Similar to operator+=(const t), except that it performs a modulo operation instead of an addition. **/ template<typename t> CImg<T>& operator%=(const t value) { if (is_empty()) return *this; cimg_openmp_for(*this,cimg::mod(*ptr,(T)value),16384); return *this; } //! In-place modulo operator. /** Similar to operator+=(const char*), except that it performs a modulo operation instead of an addition. **/ CImg<T>& operator%=(const char *const expression) { return *this%=(+*this)._fill(expression,true,1,0,0,"operator%=",this); } //! In-place modulo operator. /** Similar to operator+=(const CImg<t>&), except that it performs a modulo operation instead of an addition. **/ template<typename t> CImg<T>& operator%=(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return *this%=+img; T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = cimg::mod(*ptrd,(T)*(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = cimg::mod(*ptrd,(T)*(ptrs++)); } return *this; } //! Modulo operator. /** Similar to operator%=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator%(const t value) const { return CImg<_cimg_Tt>(*this,false)%=value; } //! Modulo operator. /** Similar to operator%=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ CImg<Tfloat> operator%(const char *const expression) const { return CImg<Tfloat>(*this,false)%=expression; } //! Modulo operator. /** Similar to operator%=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator%(const CImg<t>& img) const { return CImg<_cimg_Tt>(*this,false)%=img; } //! In-place bitwise AND operator. /** Similar to operator+=(const t), except that it performs a bitwise AND operation instead of an addition. **/ template<typename t> CImg<T>& operator&=(const t value) { if (is_empty()) return *this; cimg_openmp_for(*this,(ulongT)*ptr & (ulongT)value,32768); return *this; } //! In-place bitwise AND operator. /** Similar to operator+=(const char*), except that it performs a bitwise AND operation instead of an addition. **/ CImg<T>& operator&=(const char *const expression) { return *this&=(+*this)._fill(expression,true,1,0,0,"operator&=",this); } //! In-place bitwise AND operator. /** Similar to operator+=(const CImg<t>&), except that it performs a bitwise AND operation instead of an addition. **/ template<typename t> CImg<T>& operator&=(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return *this&=+img; T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)((ulongT)*ptrd & (ulongT)*(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)((ulongT)*ptrd & (ulongT)*(ptrs++)); } return *this; } //! Bitwise AND operator. /** Similar to operator&=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator&(const t value) const { return (+*this)&=value; } //! Bitwise AND operator. /** Similar to operator&=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ CImg<T> operator&(const char *const expression) const { return (+*this)&=expression; } //! Bitwise AND operator. /** Similar to operator&=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator&(const CImg<t>& img) const { return (+*this)&=img; } //! In-place bitwise OR operator. /** Similar to operator+=(const t), except that it performs a bitwise OR operation instead of an addition. **/ template<typename t> CImg<T>& operator|=(const t value) { if (is_empty()) return *this; cimg_openmp_for(*this,(ulongT)*ptr | (ulongT)value,32768); return *this; } //! In-place bitwise OR operator. /** Similar to operator+=(const char*), except that it performs a bitwise OR operation instead of an addition. **/ CImg<T>& operator|=(const char *const expression) { return *this|=(+*this)._fill(expression,true,1,0,0,"operator|=",this); } //! In-place bitwise OR operator. /** Similar to operator+=(const CImg<t>&), except that it performs a bitwise OR operation instead of an addition. **/ template<typename t> CImg<T>& operator|=(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return *this|=+img; T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)((ulongT)*ptrd | (ulongT)*(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)((ulongT)*ptrd | (ulongT)*(ptrs++)); } return *this; } //! Bitwise OR operator. /** Similar to operator|=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator|(const t value) const { return (+*this)|=value; } //! Bitwise OR operator. /** Similar to operator|=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ CImg<T> operator|(const char *const expression) const { return (+*this)|=expression; } //! Bitwise OR operator. /** Similar to operator|=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator|(const CImg<t>& img) const { return (+*this)|=img; } //! In-place bitwise XOR operator. /** Similar to operator+=(const t), except that it performs a bitwise XOR operation instead of an addition. \warning - It does \e not compute the \e power of pixel values. For this purpose, use pow(const t) instead. **/ template<typename t> CImg<T>& operator^=(const t value) { if (is_empty()) return *this; cimg_openmp_for(*this,(ulongT)*ptr ^ (ulongT)value,32768); return *this; } //! In-place bitwise XOR operator. /** Similar to operator+=(const char*), except that it performs a bitwise XOR operation instead of an addition. \warning - It does \e not compute the \e power of pixel values. For this purpose, use pow(const char*) instead. **/ CImg<T>& operator^=(const char *const expression) { return *this^=(+*this)._fill(expression,true,1,0,0,"operator^=",this); } //! In-place bitwise XOR operator. /** Similar to operator+=(const CImg<t>&), except that it performs a bitwise XOR operation instead of an addition. \warning - It does \e not compute the \e power of pixel values. For this purpose, use pow(const CImg<t>&) instead. **/ template<typename t> CImg<T>& operator^=(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return *this^=+img; T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)((ulongT)*ptrd ^ (ulongT)*(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)((ulongT)*ptrd ^ (ulongT)*(ptrs++)); } return *this; } //! Bitwise XOR operator. /** Similar to operator^=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator^(const t value) const { return (+*this)^=value; } //! Bitwise XOR operator. /** Similar to operator^=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ CImg<T> operator^(const char *const expression) const { return (+*this)^=expression; } //! Bitwise XOR operator. /** Similar to operator^=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator^(const CImg<t>& img) const { return (+*this)^=img; } //! In-place bitwise left shift operator. /** Similar to operator+=(const t), except that it performs a bitwise left shift instead of an addition. **/ template<typename t> CImg<T>& operator<<=(const t value) { if (is_empty()) return *this; cimg_openmp_for(*this,((longT)*ptr) << (int)value,65536); return *this; } //! In-place bitwise left shift operator. /** Similar to operator+=(const char*), except that it performs a bitwise left shift instead of an addition. **/ CImg<T>& operator<<=(const char *const expression) { return *this<<=(+*this)._fill(expression,true,1,0,0,"operator<<=",this); } //! In-place bitwise left shift operator. /** Similar to operator+=(const CImg<t>&), except that it performs a bitwise left shift instead of an addition. **/ template<typename t> CImg<T>& operator<<=(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return *this^=+img; T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)((longT)*ptrd << (int)*(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)((longT)*ptrd << (int)*(ptrs++)); } return *this; } //! Bitwise left shift operator. /** Similar to operator<<=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator<<(const t value) const { return (+*this)<<=value; } //! Bitwise left shift operator. /** Similar to operator<<=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ CImg<T> operator<<(const char *const expression) const { return (+*this)<<=expression; } //! Bitwise left shift operator. /** Similar to operator<<=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator<<(const CImg<t>& img) const { return (+*this)<<=img; } //! In-place bitwise right shift operator. /** Similar to operator+=(const t), except that it performs a bitwise right shift instead of an addition. **/ template<typename t> CImg<T>& operator>>=(const t value) { if (is_empty()) return *this; cimg_openmp_for(*this,((longT)*ptr) >> (int)value,65536); return *this; } //! In-place bitwise right shift operator. /** Similar to operator+=(const char*), except that it performs a bitwise right shift instead of an addition. **/ CImg<T>& operator>>=(const char *const expression) { return *this>>=(+*this)._fill(expression,true,1,0,0,"operator>>=",this); } //! In-place bitwise right shift operator. /** Similar to operator+=(const CImg<t>&), except that it performs a bitwise right shift instead of an addition. **/ template<typename t> CImg<T>& operator>>=(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return *this^=+img; T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)((longT)*ptrd >> (int)*(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)((longT)*ptrd >> (int)*(ptrs++)); } return *this; } //! Bitwise right shift operator. /** Similar to operator>>=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator>>(const t value) const { return (+*this)>>=value; } //! Bitwise right shift operator. /** Similar to operator>>=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ CImg<T> operator>>(const char *const expression) const { return (+*this)>>=expression; } //! Bitwise right shift operator. /** Similar to operator>>=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator>>(const CImg<t>& img) const { return (+*this)>>=img; } //! Bitwise inversion operator. /** Similar to operator-(), except that it compute the bitwise inverse instead of the opposite value. **/ CImg<T> operator~() const { CImg<T> res(_width,_height,_depth,_spectrum); const T *ptrs = _data; cimg_for(res,ptrd,T) { const ulongT value = (ulongT)*(ptrs++); *ptrd = (T)~value; } return res; } //! Test if all pixels of an image have the same value. /** Return \c true is all pixels of the image instance are equal to the specified \c value. \param value Reference value to compare with. **/ template<typename t> bool operator==(const t value) const { if (is_empty()) return false; typedef _cimg_Tt Tt; bool is_equal = true; for (T *ptrd = _data + size(); is_equal && ptrd>_data; is_equal = ((Tt)*(--ptrd)==(Tt)value)) {} return is_equal; } //! Test if all pixel values of an image follow a specified expression. /** Return \c true is all pixels of the image instance are equal to the specified \c expression. \param expression Value string describing the way pixel values are compared. **/ bool operator==(const char *const expression) const { return *this==(+*this)._fill(expression,true,1,0,0,"operator==",this); } //! Test if two images have the same size and values. /** Return \c true if the image instance and the input image \c img have the same dimensions and pixel values, and \c false otherwise. \param img Input image to compare with. \note - The pixel buffer pointers data() of the two compared images do not have to be the same for operator==() to return \c true. Only the dimensions and the pixel values matter. Thus, the comparison can be \c true even for different pixel types \c T and \c t. \par Example \code const CImg<float> img1(1,3,1,1, 0,1,2); // Construct a 1x3 vector [0;1;2] (with 'float' pixel values) const CImg<char> img2(1,3,1,1, 0,1,2); // Construct a 1x3 vector [0;1;2] (with 'char' pixel values) if (img1==img2) { // Test succeeds, image dimensions and values are the same std::printf("'img1' and 'img2' have same dimensions and values."); } \endcode **/ template<typename t> bool operator==(const CImg<t>& img) const { typedef _cimg_Tt Tt; const ulongT siz = size(); bool is_equal = true; if (siz!=img.size()) return false; t *ptrs = img._data + siz; for (T *ptrd = _data + siz; is_equal && ptrd>_data; is_equal = ((Tt)*(--ptrd)==(Tt)*(--ptrs))) {} return is_equal; } //! Test if pixels of an image are all different from a value. /** Return \c true is all pixels of the image instance are different than the specified \c value. \param value Reference value to compare with. **/ template<typename t> bool operator!=(const t value) const { return !((*this)==value); } //! Test if all pixel values of an image are different from a specified expression. /** Return \c true is all pixels of the image instance are different to the specified \c expression. \param expression Value string describing the way pixel values are compared. **/ bool operator!=(const char *const expression) const { return !((*this)==expression); } //! Test if two images have different sizes or values. /** Return \c true if the image instance and the input image \c img have different dimensions or pixel values, and \c false otherwise. \param img Input image to compare with. \note - Writing \c img1!=img2 is equivalent to \c !(img1==img2). **/ template<typename t> bool operator!=(const CImg<t>& img) const { return !((*this)==img); } //! Construct an image list from two images. /** Return a new list of image (\c CImgList instance) containing exactly two elements: - A copy of the image instance, at position [\c 0]. - A copy of the specified image \c img, at position [\c 1]. \param img Input image that will be the second image of the resulting list. \note - The family of operator,() is convenient to easily create list of images, but it is also \e quite \e slow in practice (see warning below). - Constructed lists contain no shared images. If image instance or input image \c img are shared, they are inserted as new non-shared copies in the resulting list. - The pixel type of the returned list may be a superset of the initial pixel type \c T, if necessary. \warning - Pipelining operator,() \c N times will perform \c N copies of the entire content of a (growing) image list. This may become very expensive in terms of speed and used memory. You should avoid using this technique to build a new CImgList instance from several images, if you are seeking for performance. Fast insertions of images in an image list are possible with CImgList<T>::insert(const CImg<t>&,unsigned int,bool) or move_to(CImgList<t>&,unsigned int). \par Example \code const CImg<float> img1("reference.jpg"), img2 = img1.get_mirror('x'), img3 = img2.get_blur(5); const CImgList<float> list = (img1,img2); // Create list of two elements from 'img1' and 'img2' (list,img3).display(); // Display image list containing copies of 'img1','img2' and 'img3' \endcode \image html ref_operator_comma.jpg **/ template<typename t> CImgList<_cimg_Tt> operator,(const CImg<t>& img) const { return CImgList<_cimg_Tt>(*this,img); } //! Construct an image list from image instance and an input image list. /** Return a new list of images (\c CImgList instance) containing exactly \c list.size() \c + \c 1 elements: - A copy of the image instance, at position [\c 0]. - A copy of the specified image list \c list, from positions [\c 1] to [\c list.size()]. \param list Input image list that will be appended to the image instance. \note - Similar to operator,(const CImg<t>&) const, except that it takes an image list as an argument. **/ template<typename t> CImgList<_cimg_Tt> operator,(const CImgList<t>& list) const { return CImgList<_cimg_Tt>(list,false).insert(*this,0); } //! Split image along specified axis. /** Return a new list of images (\c CImgList instance) containing the splitted components of the instance image along the specified axis. \param axis Splitting axis (can be '\c x','\c y','\c z' or '\c c') \note - Similar to get_split(char,int) const, with default second argument. \par Example \code const CImg<unsigned char> img("reference.jpg"); // Load a RGB color image const CImgList<unsigned char> list = (img<'c'); // Get a list of its three R,G,B channels (img,list).display(); \endcode \image html ref_operator_less.jpg **/ CImgList<T> operator<(const char axis) const { return get_split(axis); } //@} //------------------------------------- // //! \name Instance Characteristics //@{ //------------------------------------- //! Return the type of image pixel values as a C string. /** Return a \c char* string containing the usual type name of the image pixel values (i.e. a stringified version of the template parameter \c T). \note - The returned string may contain spaces (as in \c "unsigned char"). - If the pixel type \c T does not correspond to a registered type, the string <tt>"unknown"</tt> is returned. **/ static const char* pixel_type() { return cimg::type<T>::string(); } //! Return the number of image columns. /** Return the image width, i.e. the image dimension along the X-axis. \note - The width() of an empty image is equal to \c 0. - width() is typically equal to \c 1 when considering images as \e vectors for matrix calculations. - width() returns an \c int, although the image width is internally stored as an \c unsigned \c int. Using an \c int is safer and prevents arithmetic traps possibly encountered when doing calculations involving \c unsigned \c int variables. Access to the initial \c unsigned \c int variable is possible (though not recommended) by <tt>(*this)._width</tt>. **/ int width() const { return (int)_width; } //! Return the number of image rows. /** Return the image height, i.e. the image dimension along the Y-axis. \note - The height() of an empty image is equal to \c 0. - height() returns an \c int, although the image height is internally stored as an \c unsigned \c int. Using an \c int is safer and prevents arithmetic traps possibly encountered when doing calculations involving \c unsigned \c int variables. Access to the initial \c unsigned \c int variable is possible (though not recommended) by <tt>(*this)._height</tt>. **/ int height() const { return (int)_height; } //! Return the number of image slices. /** Return the image depth, i.e. the image dimension along the Z-axis. \note - The depth() of an empty image is equal to \c 0. - depth() is typically equal to \c 1 when considering usual 2D images. When depth()\c > \c 1, the image is said to be \e volumetric. - depth() returns an \c int, although the image depth is internally stored as an \c unsigned \c int. Using an \c int is safer and prevents arithmetic traps possibly encountered when doing calculations involving \c unsigned \c int variables. Access to the initial \c unsigned \c int variable is possible (though not recommended) by <tt>(*this)._depth</tt>. **/ int depth() const { return (int)_depth; } //! Return the number of image channels. /** Return the number of image channels, i.e. the image dimension along the C-axis. \note - The spectrum() of an empty image is equal to \c 0. - spectrum() is typically equal to \c 1 when considering scalar-valued images, to \c 3 for RGB-coded color images, and to \c 4 for RGBA-coded color images (with alpha-channel). The number of channels of an image instance is not limited. The meaning of the pixel values is not linked up to the number of channels (e.g. a 4-channel image may indifferently stands for a RGBA or CMYK color image). - spectrum() returns an \c int, although the image spectrum is internally stored as an \c unsigned \c int. Using an \c int is safer and prevents arithmetic traps possibly encountered when doing calculations involving \c unsigned \c int variables. Access to the initial \c unsigned \c int variable is possible (though not recommended) by <tt>(*this)._spectrum</tt>. **/ int spectrum() const { return (int)_spectrum; } //! Return the total number of pixel values. /** Return <tt>width()*\ref height()*\ref depth()*\ref spectrum()</tt>, i.e. the total number of values of type \c T in the pixel buffer of the image instance. \note - The size() of an empty image is equal to \c 0. - The allocated memory size for a pixel buffer of a non-shared \c CImg<T> instance is equal to <tt>size()*sizeof(T)</tt>. \par Example \code const CImg<float> img(100,100,1,3); // Construct new 100x100 color image if (img.size()==30000) // Test succeeds std::printf("Pixel buffer uses %lu bytes", img.size()*sizeof(float)); \endcode **/ ulongT size() const { return (ulongT)_width*_height*_depth*_spectrum; } //! Return a pointer to the first pixel value. /** Return a \c T*, or a \c const \c T* pointer to the first value in the pixel buffer of the image instance, whether the instance is \c const or not. \note - The data() of an empty image is equal to \c 0 (null pointer). - The allocated pixel buffer for the image instance starts from \c data() and goes to <tt>data()+\ref size() - 1</tt> (included). - To get the pointer to one particular location of the pixel buffer, use data(unsigned int,unsigned int,unsigned int,unsigned int) instead. **/ T* data() { return _data; } //! Return a pointer to the first pixel value \const. const T* data() const { return _data; } //! Return a pointer to a located pixel value. /** Return a \c T*, or a \c const \c T* pointer to the value located at (\c x,\c y,\c z,\c c) in the pixel buffer of the image instance, whether the instance is \c const or not. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note - Writing \c img.data(x,y,z,c) is equivalent to <tt>&(img(x,y,z,c))</tt>. Thus, this method has the same properties as operator()(unsigned int,unsigned int,unsigned int,unsigned int). **/ #if cimg_verbosity>=3 T *data(const unsigned int x, const unsigned int y=0, const unsigned int z=0, const unsigned int c=0) { const ulongT off = (ulongT)offset(x,y,z,c); if (off>=size()) cimg::warn(_cimg_instance "data(): Invalid pointer request, at coordinates (%u,%u,%u,%u) [offset=%u].", cimg_instance, x,y,z,c,off); return _data + off; } //! Return a pointer to a located pixel value \const. const T* data(const unsigned int x, const unsigned int y=0, const unsigned int z=0, const unsigned int c=0) const { return const_cast<CImg<T>*>(this)->data(x,y,z,c); } #else T* data(const unsigned int x, const unsigned int y=0, const unsigned int z=0, const unsigned int c=0) { return _data + x + (ulongT)y*_width + (ulongT)z*_width*_height + (ulongT)c*_width*_height*_depth; } const T* data(const unsigned int x, const unsigned int y=0, const unsigned int z=0, const unsigned int c=0) const { return _data + x + (ulongT)y*_width + (ulongT)z*_width*_height + (ulongT)c*_width*_height*_depth; } #endif //! Return the offset to a located pixel value, with respect to the beginning of the pixel buffer. /** \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note - Writing \c img.data(x,y,z,c) is equivalent to <tt>&(img(x,y,z,c)) - img.data()</tt>. Thus, this method has the same properties as operator()(unsigned int,unsigned int,unsigned int,unsigned int). \par Example \code const CImg<float> img(100,100,1,3); // Define a 100x100 RGB-color image const long off = img.offset(10,10,0,2); // Get the offset of the blue value of the pixel located at (10,10) const float val = img[off]; // Get the blue value of this pixel \endcode **/ longT offset(const int x, const int y=0, const int z=0, const int c=0) const { return x + (longT)y*_width + (longT)z*_width*_height + (longT)c*_width*_height*_depth; } //! Return a CImg<T>::iterator pointing to the first pixel value. /** \note - Equivalent to data(). - It has been mainly defined for compatibility with STL naming conventions. **/ iterator begin() { return _data; } //! Return a CImg<T>::iterator pointing to the first value of the pixel buffer \const. const_iterator begin() const { return _data; } //! Return a CImg<T>::iterator pointing next to the last pixel value. /** \note - Writing \c img.end() is equivalent to <tt>img.data() + img.size()</tt>. - It has been mainly defined for compatibility with STL naming conventions. \warning - The returned iterator actually points to a value located \e outside the acceptable bounds of the pixel buffer. Trying to read or write the content of the returned iterator will probably result in a crash. Use it mainly as a strict upper bound for a CImg<T>::iterator. \par Example \code CImg<float> img(100,100,1,3); // Define a 100x100 RGB color image // 'img.end()' used below as an upper bound for the iterator. for (CImg<float>::iterator it = img.begin(); it<img.end(); ++it) *it = 0; \endcode **/ iterator end() { return _data + size(); } //! Return a CImg<T>::iterator pointing next to the last pixel value \const. const_iterator end() const { return _data + size(); } //! Return a reference to the first pixel value. /** \note - Writing \c img.front() is equivalent to <tt>img[0]</tt>, or <tt>img(0,0,0,0)</tt>. - It has been mainly defined for compatibility with STL naming conventions. **/ T& front() { return *_data; } //! Return a reference to the first pixel value \const. const T& front() const { return *_data; } //! Return a reference to the last pixel value. /** \note - Writing \c img.back() is equivalent to <tt>img[img.size() - 1]</tt>, or <tt>img(img.width() - 1,img.height() - 1,img.depth() - 1,img.spectrum() - 1)</tt>. - It has been mainly defined for compatibility with STL naming conventions. **/ T& back() { return *(_data + size() - 1); } //! Return a reference to the last pixel value \const. const T& back() const { return *(_data + size() - 1); } //! Access to a pixel value at a specified offset, using Dirichlet boundary conditions. /** Return a reference to the pixel value of the image instance located at a specified \c offset, or to a specified default value in case of out-of-bounds access. \param offset Offset to the desired pixel value. \param out_value Default value returned if \c offset is outside image bounds. \note - Writing \c img.at(offset,out_value) is similar to <tt>img[offset]</tt>, except that if \c offset is outside bounds (e.g. \c offset<0 or \c offset>=img.size()), a reference to a value \c out_value is safely returned instead. - Due to the additional boundary checking operation, this method is slower than operator()(). Use it when you are \e not sure about the validity of the specified pixel offset. **/ T& at(const int offset, const T& out_value) { return (offset<0 || offset>=(int)size())?(cimg::temporary(out_value)=out_value):(*this)[offset]; } //! Access to a pixel value at a specified offset, using Dirichlet boundary conditions \const. T at(const int offset, const T& out_value) const { return (offset<0 || offset>=(int)size())?out_value:(*this)[offset]; } //! Access to a pixel value at a specified offset, using Neumann boundary conditions. /** Return a reference to the pixel value of the image instance located at a specified \c offset, or to the nearest pixel location in the image instance in case of out-of-bounds access. \param offset Offset to the desired pixel value. \note - Similar to at(int,const T), except that an out-of-bounds access returns the value of the nearest pixel in the image instance, regarding the specified offset, i.e. - If \c offset<0, then \c img[0] is returned. - If \c offset>=img.size(), then \c img[img.size() - 1] is returned. - Due to the additional boundary checking operation, this method is slower than operator()(). Use it when you are \e not sure about the validity of the specified pixel offset. - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _at(int). **/ T& at(const int offset) { if (is_empty()) throw CImgInstanceException(_cimg_instance "at(): Empty instance.", cimg_instance); return _at(offset); } T& _at(const int offset) { const unsigned int siz = (unsigned int)size(); return (*this)[offset<0?0:(unsigned int)offset>=siz?siz - 1:offset]; } //! Access to a pixel value at a specified offset, using Neumann boundary conditions \const. const T& at(const int offset) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "at(): Empty instance.", cimg_instance); return _at(offset); } const T& _at(const int offset) const { const unsigned int siz = (unsigned int)size(); return (*this)[offset<0?0:(unsigned int)offset>=siz?siz - 1:offset]; } //! Access to a pixel value, using Dirichlet boundary conditions for the X-coordinate. /** Return a reference to the pixel value of the image instance located at (\c x,\c y,\c z,\c c), or to a specified default value in case of out-of-bounds access along the X-axis. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param out_value Default value returned if \c (\c x,\c y,\c z,\c c) is outside image bounds. \note - Similar to operator()(), except that an out-of-bounds access along the X-axis returns the specified value \c out_value. - Due to the additional boundary checking operation, this method is slower than operator()(). Use it when you are \e not sure about the validity of the specified pixel coordinates. \warning - There is \e no boundary checking performed for the Y,Z and C-coordinates, so they must be inside image bounds. **/ T& atX(const int x, const int y, const int z, const int c, const T& out_value) { return (x<0 || x>=width())?(cimg::temporary(out_value)=out_value):(*this)(x,y,z,c); } //! Access to a pixel value, using Dirichlet boundary conditions for the X-coordinate \const. T atX(const int x, const int y, const int z, const int c, const T& out_value) const { return (x<0 || x>=width())?out_value:(*this)(x,y,z,c); } //! Access to a pixel value, using Neumann boundary conditions for the X-coordinate. /** Return a reference to the pixel value of the image instance located at (\c x,\c y,\c z,\c c), or to the nearest pixel location in the image instance in case of out-of-bounds access along the X-axis. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note - Similar to at(int,int,int,int,const T), except that an out-of-bounds access returns the value of the nearest pixel in the image instance, regarding the specified X-coordinate. - Due to the additional boundary checking operation, this method is slower than operator()(). Use it when you are \e not sure about the validity of the specified pixel coordinates. - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _at(int,int,int,int). \warning - There is \e no boundary checking performed for the Y,Z and C-coordinates, so they must be inside image bounds. **/ T& atX(const int x, const int y=0, const int z=0, const int c=0) { if (is_empty()) throw CImgInstanceException(_cimg_instance "atX(): Empty instance.", cimg_instance); return _atX(x,y,z,c); } T& _atX(const int x, const int y=0, const int z=0, const int c=0) { return (*this)(x<0?0:(x>=width()?width() - 1:x),y,z,c); } //! Access to a pixel value, using Neumann boundary conditions for the X-coordinate \const. const T& atX(const int x, const int y=0, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "atX(): Empty instance.", cimg_instance); return _atX(x,y,z,c); } const T& _atX(const int x, const int y=0, const int z=0, const int c=0) const { return (*this)(x<0?0:(x>=width()?width() - 1:x),y,z,c); } //! Access to a pixel value, using Dirichlet boundary conditions for the X and Y-coordinates. /** Similar to atX(int,int,int,int,const T), except that boundary checking is performed both on X and Y-coordinates. **/ T& atXY(const int x, const int y, const int z, const int c, const T& out_value) { return (x<0 || y<0 || x>=width() || y>=height())?(cimg::temporary(out_value)=out_value):(*this)(x,y,z,c); } //! Access to a pixel value, using Dirichlet boundary conditions for the X and Y coordinates \const. T atXY(const int x, const int y, const int z, const int c, const T& out_value) const { return (x<0 || y<0 || x>=width() || y>=height())?out_value:(*this)(x,y,z,c); } //! Access to a pixel value, using Neumann boundary conditions for the X and Y-coordinates. /** Similar to atX(int,int,int,int), except that boundary checking is performed both on X and Y-coordinates. \note - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _atXY(int,int,int,int). **/ T& atXY(const int x, const int y, const int z=0, const int c=0) { if (is_empty()) throw CImgInstanceException(_cimg_instance "atXY(): Empty instance.", cimg_instance); return _atXY(x,y,z,c); } T& _atXY(const int x, const int y, const int z=0, const int c=0) { return (*this)(cimg::cut(x,0,width() - 1), cimg::cut(y,0,height() - 1),z,c); } //! Access to a pixel value, using Neumann boundary conditions for the X and Y-coordinates \const. const T& atXY(const int x, const int y, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "atXY(): Empty instance.", cimg_instance); return _atXY(x,y,z,c); } const T& _atXY(const int x, const int y, const int z=0, const int c=0) const { return (*this)(cimg::cut(x,0,width() - 1), cimg::cut(y,0,height() - 1),z,c); } //! Access to a pixel value, using Dirichlet boundary conditions for the X,Y and Z-coordinates. /** Similar to atX(int,int,int,int,const T), except that boundary checking is performed both on X,Y and Z-coordinates. **/ T& atXYZ(const int x, const int y, const int z, const int c, const T& out_value) { return (x<0 || y<0 || z<0 || x>=width() || y>=height() || z>=depth())? (cimg::temporary(out_value)=out_value):(*this)(x,y,z,c); } //! Access to a pixel value, using Dirichlet boundary conditions for the X,Y and Z-coordinates \const. T atXYZ(const int x, const int y, const int z, const int c, const T& out_value) const { return (x<0 || y<0 || z<0 || x>=width() || y>=height() || z>=depth())?out_value:(*this)(x,y,z,c); } //! Access to a pixel value, using Neumann boundary conditions for the X,Y and Z-coordinates. /** Similar to atX(int,int,int,int), except that boundary checking is performed both on X,Y and Z-coordinates. \note - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _atXYZ(int,int,int,int). **/ T& atXYZ(const int x, const int y, const int z, const int c=0) { if (is_empty()) throw CImgInstanceException(_cimg_instance "atXYZ(): Empty instance.", cimg_instance); return _atXYZ(x,y,z,c); } T& _atXYZ(const int x, const int y, const int z, const int c=0) { return (*this)(cimg::cut(x,0,width() - 1), cimg::cut(y,0,height() - 1), cimg::cut(z,0,depth() - 1),c); } //! Access to a pixel value, using Neumann boundary conditions for the X,Y and Z-coordinates \const. const T& atXYZ(const int x, const int y, const int z, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "atXYZ(): Empty instance.", cimg_instance); return _atXYZ(x,y,z,c); } const T& _atXYZ(const int x, const int y, const int z, const int c=0) const { return (*this)(cimg::cut(x,0,width() - 1), cimg::cut(y,0,height() - 1), cimg::cut(z,0,depth() - 1),c); } //! Access to a pixel value, using Dirichlet boundary conditions. /** Similar to atX(int,int,int,int,const T), except that boundary checking is performed on all X,Y,Z and C-coordinates. **/ T& atXYZC(const int x, const int y, const int z, const int c, const T& out_value) { return (x<0 || y<0 || z<0 || c<0 || x>=width() || y>=height() || z>=depth() || c>=spectrum())? (cimg::temporary(out_value)=out_value):(*this)(x,y,z,c); } //! Access to a pixel value, using Dirichlet boundary conditions \const. T atXYZC(const int x, const int y, const int z, const int c, const T& out_value) const { return (x<0 || y<0 || z<0 || c<0 || x>=width() || y>=height() || z>=depth() || c>=spectrum())?out_value: (*this)(x,y,z,c); } //! Access to a pixel value, using Neumann boundary conditions. /** Similar to atX(int,int,int,int), except that boundary checking is performed on all X,Y,Z and C-coordinates. \note - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _atXYZC(int,int,int,int). **/ T& atXYZC(const int x, const int y, const int z, const int c) { if (is_empty()) throw CImgInstanceException(_cimg_instance "atXYZC(): Empty instance.", cimg_instance); return _atXYZC(x,y,z,c); } T& _atXYZC(const int x, const int y, const int z, const int c) { return (*this)(cimg::cut(x,0,width() - 1), cimg::cut(y,0,height() - 1), cimg::cut(z,0,depth() - 1), cimg::cut(c,0,spectrum() - 1)); } //! Access to a pixel value, using Neumann boundary conditions \const. const T& atXYZC(const int x, const int y, const int z, const int c) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "atXYZC(): Empty instance.", cimg_instance); return _atXYZC(x,y,z,c); } const T& _atXYZC(const int x, const int y, const int z, const int c) const { return (*this)(cimg::cut(x,0,width() - 1), cimg::cut(y,0,height() - 1), cimg::cut(z,0,depth() - 1), cimg::cut(c,0,spectrum() - 1)); } //! Return pixel value, using linear interpolation and Dirichlet boundary conditions for the X-coordinate. /** Return a linearly-interpolated pixel value of the image instance located at (\c fx,\c y,\c z,\c c), or a specified default value in case of out-of-bounds access along the X-axis. \param fx X-coordinate of the pixel value (float-valued). \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param out_value Default value returned if \c (\c fx,\c y,\c z,\c c) is outside image bounds. \note - Similar to atX(int,int,int,int,const T), except that the returned pixel value is approximated by a linear interpolation along the X-axis, if corresponding coordinates are not integers. - The type of the returned pixel value is extended to \c float, if the pixel type \c T is not float-valued. \warning - There is \e no boundary checking performed for the Y,Z and C-coordinates, so they must be inside image bounds. **/ Tfloat linear_atX(const float fx, const int y, const int z, const int c, const T& out_value) const { const int x = (int)fx - (fx>=0?0:1), nx = x + 1; const float dx = fx - x; const Tfloat Ic = (Tfloat)atX(x,y,z,c,out_value), In = (Tfloat)atXY(nx,y,z,c,out_value); return Ic + dx*(In - Ic); } //! Return pixel value, using linear interpolation and Neumann boundary conditions for the X-coordinate. /** Return a linearly-interpolated pixel value of the image instance located at (\c fx,\c y,\c z,\c c), or the value of the nearest pixel location in the image instance in case of out-of-bounds access along the X-axis. \param fx X-coordinate of the pixel value (float-valued). \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note - Similar to linear_atX(float,int,int,int,const T) const, except that an out-of-bounds access returns the value of the nearest pixel in the image instance, regarding the specified X-coordinate. - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _linear_atX(float,int,int,int). \warning - There is \e no boundary checking performed for the Y,Z and C-coordinates, so they must be inside image bounds. **/ Tfloat linear_atX(const float fx, const int y=0, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "linear_atX(): Empty instance.", cimg_instance); return _linear_atX(fx,y,z,c); } Tfloat _linear_atX(const float fx, const int y=0, const int z=0, const int c=0) const { const float nfx = cimg::cut(fx,0,width() - 1); const unsigned int x = (unsigned int)nfx; const float dx = nfx - x; const unsigned int nx = dx>0?x + 1:x; const Tfloat Ic = (Tfloat)(*this)(x,y,z,c), In = (Tfloat)(*this)(nx,y,z,c); return Ic + dx*(In - Ic); } //! Return pixel value, using linear interpolation and periodic boundary conditions for the X-coordinate. Tfloat linear_atX_p(const float fx, const int y=0, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "linear_atX_p(): Empty instance.", cimg_instance); return _linear_atX_p(fx,y,z,c); } Tfloat _linear_atX_p(const float fx, const int y=0, const int z=0, const int c=0) const { const float nfx = cimg::mod(fx,(float)_width); const unsigned int x = (unsigned int)nfx; const float dx = nfx - x; const unsigned int nx = cimg::mod(x + 1,_width); const Tfloat Ic = (Tfloat)(*this)(x,y,z,c), In = (Tfloat)(*this)(nx,y,z,c); return Ic + dx*(In - Ic); } //! Return pixel value, using linear interpolation and Dirichlet boundary conditions for the X and Y-coordinates. /** Similar to linear_atX(float,int,int,int,const T) const, except that the linear interpolation and the boundary checking are achieved both for X and Y-coordinates. **/ Tfloat linear_atXY(const float fx, const float fy, const int z, const int c, const T& out_value) const { const int x = (int)fx - (fx>=0?0:1), nx = x + 1, y = (int)fy - (fy>=0?0:1), ny = y + 1; const float dx = fx - x, dy = fy - y; const Tfloat Icc = (Tfloat)atXY(x,y,z,c,out_value), Inc = (Tfloat)atXY(nx,y,z,c,out_value), Icn = (Tfloat)atXY(x,ny,z,c,out_value), Inn = (Tfloat)atXY(nx,ny,z,c,out_value); return Icc + dx*(Inc - Icc + dy*(Icc + Inn - Icn - Inc)) + dy*(Icn - Icc); } //! Return pixel value, using linear interpolation and Neumann boundary conditions for the X and Y-coordinates. /** Similar to linear_atX(float,int,int,int) const, except that the linear interpolation and the boundary checking are achieved both for X and Y-coordinates. \note - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _linear_atXY(float,float,int,int). **/ Tfloat linear_atXY(const float fx, const float fy, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "linear_atXY(): Empty instance.", cimg_instance); return _linear_atXY(fx,fy,z,c); } Tfloat _linear_atXY(const float fx, const float fy, const int z=0, const int c=0) const { const float nfx = cimg::cut(fx,0,width() - 1), nfy = cimg::cut(fy,0,height() - 1); const unsigned int x = (unsigned int)nfx, y = (unsigned int)nfy; const float dx = nfx - x, dy = nfy - y; const unsigned int nx = dx>0?x + 1:x, ny = dy>0?y + 1:y; const Tfloat Icc = (Tfloat)(*this)(x,y,z,c), Inc = (Tfloat)(*this)(nx,y,z,c), Icn = (Tfloat)(*this)(x,ny,z,c), Inn = (Tfloat)(*this)(nx,ny,z,c); return Icc + dx*(Inc - Icc + dy*(Icc + Inn - Icn - Inc)) + dy*(Icn - Icc); } //! Return pixel value, using linear interpolation and periodic boundary conditions for the X and Y-coordinates. Tfloat linear_atXY_p(const float fx, const float fy, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "linear_atXY_p(): Empty instance.", cimg_instance); return _linear_atXY_p(fx,fy,z,c); } Tfloat _linear_atXY_p(const float fx, const float fy, const int z=0, const int c=0) const { const float nfx = cimg::mod(fx,(float)_width), nfy = cimg::mod(fy,(float)_height); const unsigned int x = (unsigned int)nfx, y = (unsigned int)nfy; const float dx = nfx - x, dy = nfy - y; const unsigned int nx = cimg::mod(x + 1,_width), ny = cimg::mod(y + 1,_height); const Tfloat Icc = (Tfloat)(*this)(x,y,z,c), Inc = (Tfloat)(*this)(nx,y,z,c), Icn = (Tfloat)(*this)(x,ny,z,c), Inn = (Tfloat)(*this)(nx,ny,z,c); return Icc + dx*(Inc - Icc + dy*(Icc + Inn - Icn - Inc)) + dy*(Icn - Icc); } //! Return pixel value, using linear interpolation and Dirichlet boundary conditions for the X,Y and Z-coordinates. /** Similar to linear_atX(float,int,int,int,const T) const, except that the linear interpolation and the boundary checking are achieved both for X,Y and Z-coordinates. **/ Tfloat linear_atXYZ(const float fx, const float fy, const float fz, const int c, const T& out_value) const { const int x = (int)fx - (fx>=0?0:1), nx = x + 1, y = (int)fy - (fy>=0?0:1), ny = y + 1, z = (int)fz - (fz>=0?0:1), nz = z + 1; const float dx = fx - x, dy = fy - y, dz = fz - z; const Tfloat Iccc = (Tfloat)atXYZ(x,y,z,c,out_value), Incc = (Tfloat)atXYZ(nx,y,z,c,out_value), Icnc = (Tfloat)atXYZ(x,ny,z,c,out_value), Innc = (Tfloat)atXYZ(nx,ny,z,c,out_value), Iccn = (Tfloat)atXYZ(x,y,nz,c,out_value), Incn = (Tfloat)atXYZ(nx,y,nz,c,out_value), Icnn = (Tfloat)atXYZ(x,ny,nz,c,out_value), Innn = (Tfloat)atXYZ(nx,ny,nz,c,out_value); return Iccc + dx*(Incc - Iccc + dy*(Iccc + Innc - Icnc - Incc + dz*(Iccn + Innn + Icnc + Incc - Icnn - Incn - Iccc - Innc)) + dz*(Iccc + Incn - Iccn - Incc)) + dy*(Icnc - Iccc + dz*(Iccc + Icnn - Iccn - Icnc)) + dz*(Iccn - Iccc); } //! Return pixel value, using linear interpolation and Neumann boundary conditions for the X,Y and Z-coordinates. /** Similar to linear_atX(float,int,int,int) const, except that the linear interpolation and the boundary checking are achieved both for X,Y and Z-coordinates. \note - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _linear_atXYZ(float,float,float,int). **/ Tfloat linear_atXYZ(const float fx, const float fy=0, const float fz=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "linear_atXYZ(): Empty instance.", cimg_instance); return _linear_atXYZ(fx,fy,fz,c); } Tfloat _linear_atXYZ(const float fx, const float fy=0, const float fz=0, const int c=0) const { const float nfx = cimg::cut(fx,0,width() - 1), nfy = cimg::cut(fy,0,height() - 1), nfz = cimg::cut(fz,0,depth() - 1); const unsigned int x = (unsigned int)nfx, y = (unsigned int)nfy, z = (unsigned int)nfz; const float dx = nfx - x, dy = nfy - y, dz = nfz - z; const unsigned int nx = dx>0?x + 1:x, ny = dy>0?y + 1:y, nz = dz>0?z + 1:z; const Tfloat Iccc = (Tfloat)(*this)(x,y,z,c), Incc = (Tfloat)(*this)(nx,y,z,c), Icnc = (Tfloat)(*this)(x,ny,z,c), Innc = (Tfloat)(*this)(nx,ny,z,c), Iccn = (Tfloat)(*this)(x,y,nz,c), Incn = (Tfloat)(*this)(nx,y,nz,c), Icnn = (Tfloat)(*this)(x,ny,nz,c), Innn = (Tfloat)(*this)(nx,ny,nz,c); return Iccc + dx*(Incc - Iccc + dy*(Iccc + Innc - Icnc - Incc + dz*(Iccn + Innn + Icnc + Incc - Icnn - Incn - Iccc - Innc)) + dz*(Iccc + Incn - Iccn - Incc)) + dy*(Icnc - Iccc + dz*(Iccc + Icnn - Iccn - Icnc)) + dz*(Iccn - Iccc); } //! Return pixel value, using linear interpolation and periodic boundary conditions for the X,Y and Z-coordinates. Tfloat linear_atXYZ_p(const float fx, const float fy=0, const float fz=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "linear_atXYZ_p(): Empty instance.", cimg_instance); return _linear_atXYZ_p(fx,fy,fz,c); } Tfloat _linear_atXYZ_p(const float fx, const float fy=0, const float fz=0, const int c=0) const { const float nfx = cimg::mod(fx,(float)_width), nfy = cimg::mod(fy,(float)_height), nfz = cimg::mod(fz,(float)_depth); const unsigned int x = (unsigned int)nfx, y = (unsigned int)nfy, z = (unsigned int)nfz; const float dx = nfx - x, dy = nfy - y, dz = nfz - z; const unsigned int nx = cimg::mod(x + 1,_width), ny = cimg::mod(y + 1,_height), nz = cimg::mod(z + 1,_depth); const Tfloat Iccc = (Tfloat)(*this)(x,y,z,c), Incc = (Tfloat)(*this)(nx,y,z,c), Icnc = (Tfloat)(*this)(x,ny,z,c), Innc = (Tfloat)(*this)(nx,ny,z,c), Iccn = (Tfloat)(*this)(x,y,nz,c), Incn = (Tfloat)(*this)(nx,y,nz,c), Icnn = (Tfloat)(*this)(x,ny,nz,c), Innn = (Tfloat)(*this)(nx,ny,nz,c); return Iccc + dx*(Incc - Iccc + dy*(Iccc + Innc - Icnc - Incc + dz*(Iccn + Innn + Icnc + Incc - Icnn - Incn - Iccc - Innc)) + dz*(Iccc + Incn - Iccn - Incc)) + dy*(Icnc - Iccc + dz*(Iccc + Icnn - Iccn - Icnc)) + dz*(Iccn - Iccc); } //! Return pixel value, using linear interpolation and Dirichlet boundary conditions for all X,Y,Z,C-coordinates. /** Similar to linear_atX(float,int,int,int,const T) const, except that the linear interpolation and the boundary checking are achieved for all X,Y,Z and C-coordinates. **/ Tfloat linear_atXYZC(const float fx, const float fy, const float fz, const float fc, const T& out_value) const { const int x = (int)fx - (fx>=0?0:1), nx = x + 1, y = (int)fy - (fy>=0?0:1), ny = y + 1, z = (int)fz - (fz>=0?0:1), nz = z + 1, c = (int)fc - (fc>=0?0:1), nc = c + 1; const float dx = fx - x, dy = fy - y, dz = fz - z, dc = fc - c; const Tfloat Icccc = (Tfloat)atXYZC(x,y,z,c,out_value), Inccc = (Tfloat)atXYZC(nx,y,z,c,out_value), Icncc = (Tfloat)atXYZC(x,ny,z,c,out_value), Inncc = (Tfloat)atXYZC(nx,ny,z,c,out_value), Iccnc = (Tfloat)atXYZC(x,y,nz,c,out_value), Incnc = (Tfloat)atXYZC(nx,y,nz,c,out_value), Icnnc = (Tfloat)atXYZC(x,ny,nz,c,out_value), Innnc = (Tfloat)atXYZC(nx,ny,nz,c,out_value), Icccn = (Tfloat)atXYZC(x,y,z,nc,out_value), Inccn = (Tfloat)atXYZC(nx,y,z,nc,out_value), Icncn = (Tfloat)atXYZC(x,ny,z,nc,out_value), Inncn = (Tfloat)atXYZC(nx,ny,z,nc,out_value), Iccnn = (Tfloat)atXYZC(x,y,nz,nc,out_value), Incnn = (Tfloat)atXYZC(nx,y,nz,nc,out_value), Icnnn = (Tfloat)atXYZC(x,ny,nz,nc,out_value), Innnn = (Tfloat)atXYZC(nx,ny,nz,nc,out_value); return Icccc + dx*(Inccc - Icccc + dy*(Icccc + Inncc - Icncc - Inccc + dz*(Iccnc + Innnc + Icncc + Inccc - Icnnc - Incnc - Icccc - Inncc + dc*(Iccnn + Innnn + Icncn + Inccn + Icnnc + Incnc + Icccc + Inncc - Icnnn - Incnn - Icccn - Inncn - Iccnc - Innnc - Icncc - Inccc)) + dc*(Icccn + Inncn + Icncc + Inccc - Icncn - Inccn - Icccc - Inncc)) + dz*(Icccc + Incnc - Iccnc - Inccc + dc*(Icccn + Incnn + Iccnc + Inccc - Iccnn - Inccn - Icccc - Incnc)) + dc*(Icccc + Inccn - Inccc - Icccn)) + dy*(Icncc - Icccc + dz*(Icccc + Icnnc - Iccnc - Icncc + dc*(Icccn + Icnnn + Iccnc + Icncc - Iccnn - Icncn - Icccc - Icnnc)) + dc*(Icccc + Icncn - Icncc - Icccn)) + dz*(Iccnc - Icccc + dc*(Icccc + Iccnn - Iccnc - Icccn)) + dc*(Icccn -Icccc); } //! Return pixel value, using linear interpolation and Neumann boundary conditions for all X,Y,Z and C-coordinates. /** Similar to linear_atX(float,int,int,int) const, except that the linear interpolation and the boundary checking are achieved for all X,Y,Z and C-coordinates. \note - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _linear_atXYZC(float,float,float,float). **/ Tfloat linear_atXYZC(const float fx, const float fy=0, const float fz=0, const float fc=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "linear_atXYZC(): Empty instance.", cimg_instance); return _linear_atXYZC(fx,fy,fz,fc); } Tfloat _linear_atXYZC(const float fx, const float fy=0, const float fz=0, const float fc=0) const { const float nfx = cimg::cut(fx,0,width() - 1), nfy = cimg::cut(fy,0,height() - 1), nfz = cimg::cut(fz,0,depth() - 1), nfc = cimg::cut(fc,0,spectrum() - 1); const unsigned int x = (unsigned int)nfx, y = (unsigned int)nfy, z = (unsigned int)nfz, c = (unsigned int)nfc; const float dx = nfx - x, dy = nfy - y, dz = nfz - z, dc = nfc - c; const unsigned int nx = dx>0?x + 1:x, ny = dy>0?y + 1:y, nz = dz>0?z + 1:z, nc = dc>0?c + 1:c; const Tfloat Icccc = (Tfloat)(*this)(x,y,z,c), Inccc = (Tfloat)(*this)(nx,y,z,c), Icncc = (Tfloat)(*this)(x,ny,z,c), Inncc = (Tfloat)(*this)(nx,ny,z,c), Iccnc = (Tfloat)(*this)(x,y,nz,c), Incnc = (Tfloat)(*this)(nx,y,nz,c), Icnnc = (Tfloat)(*this)(x,ny,nz,c), Innnc = (Tfloat)(*this)(nx,ny,nz,c), Icccn = (Tfloat)(*this)(x,y,z,nc), Inccn = (Tfloat)(*this)(nx,y,z,nc), Icncn = (Tfloat)(*this)(x,ny,z,nc), Inncn = (Tfloat)(*this)(nx,ny,z,nc), Iccnn = (Tfloat)(*this)(x,y,nz,nc), Incnn = (Tfloat)(*this)(nx,y,nz,nc), Icnnn = (Tfloat)(*this)(x,ny,nz,nc), Innnn = (Tfloat)(*this)(nx,ny,nz,nc); return Icccc + dx*(Inccc - Icccc + dy*(Icccc + Inncc - Icncc - Inccc + dz*(Iccnc + Innnc + Icncc + Inccc - Icnnc - Incnc - Icccc - Inncc + dc*(Iccnn + Innnn + Icncn + Inccn + Icnnc + Incnc + Icccc + Inncc - Icnnn - Incnn - Icccn - Inncn - Iccnc - Innnc - Icncc - Inccc)) + dc*(Icccn + Inncn + Icncc + Inccc - Icncn - Inccn - Icccc - Inncc)) + dz*(Icccc + Incnc - Iccnc - Inccc + dc*(Icccn + Incnn + Iccnc + Inccc - Iccnn - Inccn - Icccc - Incnc)) + dc*(Icccc + Inccn - Inccc - Icccn)) + dy*(Icncc - Icccc + dz*(Icccc + Icnnc - Iccnc - Icncc + dc*(Icccn + Icnnn + Iccnc + Icncc - Iccnn - Icncn - Icccc - Icnnc)) + dc*(Icccc + Icncn - Icncc - Icccn)) + dz*(Iccnc - Icccc + dc*(Icccc + Iccnn - Iccnc - Icccn)) + dc*(Icccn - Icccc); } //! Return pixel value, using linear interpolation and periodic boundary conditions for all X,Y,Z and C-coordinates. Tfloat linear_atXYZC_p(const float fx, const float fy=0, const float fz=0, const float fc=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "linear_atXYZC_p(): Empty instance.", cimg_instance); return _linear_atXYZC_p(fx,fy,fz,fc); } Tfloat _linear_atXYZC_p(const float fx, const float fy=0, const float fz=0, const float fc=0) const { const float nfx = cimg::mod(fx,(float)_width), nfy = cimg::mod(fy,(float)_height), nfz = cimg::mod(fz,(float)_depth), nfc = cimg::mod(fc,(float)_spectrum); const unsigned int x = (unsigned int)nfx, y = (unsigned int)nfy, z = (unsigned int)nfz, c = (unsigned int)nfc; const float dx = nfx - x, dy = nfy - y, dz = nfz - z, dc = nfc - c; const unsigned int nx = cimg::mod(x + 1,_width), ny = cimg::mod(y + 1,_height), nz = cimg::mod(z + 1,_depth), nc = cimg::mod(c + 1,_spectrum); const Tfloat Icccc = (Tfloat)(*this)(x,y,z,c), Inccc = (Tfloat)(*this)(nx,y,z,c), Icncc = (Tfloat)(*this)(x,ny,z,c), Inncc = (Tfloat)(*this)(nx,ny,z,c), Iccnc = (Tfloat)(*this)(x,y,nz,c), Incnc = (Tfloat)(*this)(nx,y,nz,c), Icnnc = (Tfloat)(*this)(x,ny,nz,c), Innnc = (Tfloat)(*this)(nx,ny,nz,c), Icccn = (Tfloat)(*this)(x,y,z,nc), Inccn = (Tfloat)(*this)(nx,y,z,nc), Icncn = (Tfloat)(*this)(x,ny,z,nc), Inncn = (Tfloat)(*this)(nx,ny,z,nc), Iccnn = (Tfloat)(*this)(x,y,nz,nc), Incnn = (Tfloat)(*this)(nx,y,nz,nc), Icnnn = (Tfloat)(*this)(x,ny,nz,nc), Innnn = (Tfloat)(*this)(nx,ny,nz,nc); return Icccc + dx*(Inccc - Icccc + dy*(Icccc + Inncc - Icncc - Inccc + dz*(Iccnc + Innnc + Icncc + Inccc - Icnnc - Incnc - Icccc - Inncc + dc*(Iccnn + Innnn + Icncn + Inccn + Icnnc + Incnc + Icccc + Inncc - Icnnn - Incnn - Icccn - Inncn - Iccnc - Innnc - Icncc - Inccc)) + dc*(Icccn + Inncn + Icncc + Inccc - Icncn - Inccn - Icccc - Inncc)) + dz*(Icccc + Incnc - Iccnc - Inccc + dc*(Icccn + Incnn + Iccnc + Inccc - Iccnn - Inccn - Icccc - Incnc)) + dc*(Icccc + Inccn - Inccc - Icccn)) + dy*(Icncc - Icccc + dz*(Icccc + Icnnc - Iccnc - Icncc + dc*(Icccn + Icnnn + Iccnc + Icncc - Iccnn - Icncn - Icccc - Icnnc)) + dc*(Icccc + Icncn - Icncc - Icccn)) + dz*(Iccnc - Icccc + dc*(Icccc + Iccnn - Iccnc - Icccn)) + dc*(Icccn - Icccc); } //! Return pixel value, using cubic interpolation and Dirichlet boundary conditions for the X-coordinate. /** Return a cubicly-interpolated pixel value of the image instance located at (\c fx,\c y,\c z,\c c), or a specified default value in case of out-of-bounds access along the X-axis. The cubic interpolation uses Hermite splines. \param fx d X-coordinate of the pixel value (float-valued). \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param out_value Default value returned if \c (\c fx,\c y,\c z,\c c) is outside image bounds. \note - Similar to linear_atX(float,int,int,int,const T) const, except that the returned pixel value is approximated by a \e cubic interpolation along the X-axis. - The type of the returned pixel value is extended to \c float, if the pixel type \c T is not float-valued. \warning - There is \e no boundary checking performed for the Y,Z and C-coordinates, so they must be inside image bounds. **/ Tfloat cubic_atX(const float fx, const int y, const int z, const int c, const T& out_value) const { const int x = (int)fx - (fx>=0?0:1), px = x - 1, nx = x + 1, ax = x + 2; const float dx = fx - x; const Tfloat Ip = (Tfloat)atX(px,y,z,c,out_value), Ic = (Tfloat)atX(x,y,z,c,out_value), In = (Tfloat)atX(nx,y,z,c,out_value), Ia = (Tfloat)atX(ax,y,z,c,out_value); return Ic + 0.5f*(dx*(-Ip + In) + dx*dx*(2*Ip - 5*Ic + 4*In - Ia) + dx*dx*dx*(-Ip + 3*Ic - 3*In + Ia)); } //! Return clamped pixel value, using cubic interpolation and Dirichlet boundary conditions for the X-coordinate. /** Similar to cubic_atX(float,int,int,int,const T) const, except that the return value is clamped to stay in the min/max range of the datatype \c T. **/ T cubic_atX_c(const float fx, const int y, const int z, const int c, const T& out_value) const { return cimg::type<T>::cut(cubic_atX(fx,y,z,c,out_value)); } //! Return pixel value, using cubic interpolation and Neumann boundary conditions for the X-coordinate. /** Return a cubicly-interpolated pixel value of the image instance located at (\c fx,\c y,\c z,\c c), or the value of the nearest pixel location in the image instance in case of out-of-bounds access along the X-axis. The cubic interpolation uses Hermite splines. \param fx X-coordinate of the pixel value (float-valued). \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note - Similar to cubic_atX(float,int,int,int,const T) const, except that the returned pixel value is approximated by a cubic interpolation along the X-axis. - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _cubic_atX(float,int,int,int). \warning - There is \e no boundary checking performed for the Y,Z and C-coordinates, so they must be inside image bounds. **/ Tfloat cubic_atX(const float fx, const int y=0, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "cubic_atX(): Empty instance.", cimg_instance); return _cubic_atX(fx,y,z,c); } Tfloat _cubic_atX(const float fx, const int y=0, const int z=0, const int c=0) const { const float nfx = cimg::type<float>::is_nan(fx)?0:cimg::cut(fx,0,width() - 1); const int x = (int)nfx; const float dx = nfx - x; const int px = x - 1<0?0:x - 1, nx = dx>0?x + 1:x, ax = x + 2>=width()?width() - 1:x + 2; const Tfloat Ip = (Tfloat)(*this)(px,y,z,c), Ic = (Tfloat)(*this)(x,y,z,c), In = (Tfloat)(*this)(nx,y,z,c), Ia = (Tfloat)(*this)(ax,y,z,c); return Ic + 0.5f*(dx*(-Ip + In) + dx*dx*(2*Ip - 5*Ic + 4*In - Ia) + dx*dx*dx*(-Ip + 3*Ic - 3*In + Ia)); } //! Return clamped pixel value, using cubic interpolation and Neumann boundary conditions for the X-coordinate. /** Similar to cubic_atX(float,int,int,int) const, except that the return value is clamped to stay in the min/max range of the datatype \c T. **/ T cubic_atX_c(const float fx, const int y, const int z, const int c) const { return cimg::type<T>::cut(cubic_atX(fx,y,z,c)); } T _cubic_atX_c(const float fx, const int y, const int z, const int c) const { return cimg::type<T>::cut(_cubic_atX(fx,y,z,c)); } //! Return pixel value, using cubic interpolation and periodic boundary conditions for the X-coordinate. Tfloat cubic_atX_p(const float fx, const int y=0, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "cubic_atX_p(): Empty instance.", cimg_instance); return _cubic_atX_p(fx,y,z,c); } Tfloat _cubic_atX_p(const float fx, const int y=0, const int z=0, const int c=0) const { const float nfx = cimg::type<float>::is_nan(fx)?0:cimg::mod(fx,(float)_width); const int x = (int)nfx; const float dx = nfx - x; const int px = cimg::mod(x - 1,width()), nx = cimg::mod(x + 1,width()), ax = cimg::mod(x + 2,width()); const Tfloat Ip = (Tfloat)(*this)(px,y,z,c), Ic = (Tfloat)(*this)(x,y,z,c), In = (Tfloat)(*this)(nx,y,z,c), Ia = (Tfloat)(*this)(ax,y,z,c); return Ic + 0.5f*(dx*(-Ip + In) + dx*dx*(2*Ip - 5*Ic + 4*In - Ia) + dx*dx*dx*(-Ip + 3*Ic - 3*In + Ia)); } T cubic_atX_pc(const float fx, const int y, const int z, const int c) const { return cimg::type<T>::cut(cubic_atX_p(fx,y,z,c)); } T _cubic_atX_pc(const float fx, const int y, const int z, const int c) const { return cimg::type<T>::cut(_cubic_atX_p(fx,y,z,c)); } //! Return pixel value, using cubic interpolation and Dirichlet boundary conditions for the X and Y-coordinates. /** Similar to cubic_atX(float,int,int,int,const T) const, except that the cubic interpolation and boundary checking are achieved both for X and Y-coordinates. **/ Tfloat cubic_atXY(const float fx, const float fy, const int z, const int c, const T& out_value) const { const int x = (int)fx - (fx>=0?0:1), px = x - 1, nx = x + 1, ax = x + 2, y = (int)fy - (fy>=0?0:1), py = y - 1, ny = y + 1, ay = y + 2; const float dx = fx - x, dy = fy - y; const Tfloat Ipp = (Tfloat)atXY(px,py,z,c,out_value), Icp = (Tfloat)atXY(x,py,z,c,out_value), Inp = (Tfloat)atXY(nx,py,z,c,out_value), Iap = (Tfloat)atXY(ax,py,z,c,out_value), Ip = Icp + 0.5f*(dx*(-Ipp + Inp) + dx*dx*(2*Ipp - 5*Icp + 4*Inp - Iap) + dx*dx*dx*(-Ipp + 3*Icp - 3*Inp + Iap)), Ipc = (Tfloat)atXY(px,y,z,c,out_value), Icc = (Tfloat)atXY(x, y,z,c,out_value), Inc = (Tfloat)atXY(nx,y,z,c,out_value), Iac = (Tfloat)atXY(ax,y,z,c,out_value), Ic = Icc + 0.5f*(dx*(-Ipc + Inc) + dx*dx*(2*Ipc - 5*Icc + 4*Inc - Iac) + dx*dx*dx*(-Ipc + 3*Icc - 3*Inc + Iac)), Ipn = (Tfloat)atXY(px,ny,z,c,out_value), Icn = (Tfloat)atXY(x,ny,z,c,out_value), Inn = (Tfloat)atXY(nx,ny,z,c,out_value), Ian = (Tfloat)atXY(ax,ny,z,c,out_value), In = Icn + 0.5f*(dx*(-Ipn + Inn) + dx*dx*(2*Ipn - 5*Icn + 4*Inn - Ian) + dx*dx*dx*(-Ipn + 3*Icn - 3*Inn + Ian)), Ipa = (Tfloat)atXY(px,ay,z,c,out_value), Ica = (Tfloat)atXY(x,ay,z,c,out_value), Ina = (Tfloat)atXY(nx,ay,z,c,out_value), Iaa = (Tfloat)atXY(ax,ay,z,c,out_value), Ia = Ica + 0.5f*(dx*(-Ipa + Ina) + dx*dx*(2*Ipa - 5*Ica + 4*Ina - Iaa) + dx*dx*dx*(-Ipa + 3*Ica - 3*Ina + Iaa)); return Ic + 0.5f*(dy*(-Ip + In) + dy*dy*(2*Ip - 5*Ic + 4*In - Ia) + dy*dy*dy*(-Ip + 3*Ic - 3*In + Ia)); } //! Return clamped pixel value, using cubic interpolation and Dirichlet boundary conditions for the X,Y-coordinates. /** Similar to cubic_atXY(float,float,int,int,const T) const, except that the return value is clamped to stay in the min/max range of the datatype \c T. **/ T cubic_atXY_c(const float fx, const float fy, const int z, const int c, const T& out_value) const { return cimg::type<T>::cut(cubic_atXY(fx,fy,z,c,out_value)); } //! Return pixel value, using cubic interpolation and Neumann boundary conditions for the X and Y-coordinates. /** Similar to cubic_atX(float,int,int,int) const, except that the cubic interpolation and boundary checking are achieved for both X and Y-coordinates. \note - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _cubic_atXY(float,float,int,int). **/ Tfloat cubic_atXY(const float fx, const float fy, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "cubic_atXY(): Empty instance.", cimg_instance); return _cubic_atXY(fx,fy,z,c); } Tfloat _cubic_atXY(const float fx, const float fy, const int z=0, const int c=0) const { const float nfx = cimg::type<float>::is_nan(fx)?0:cimg::cut(fx,0,width() - 1), nfy = cimg::type<float>::is_nan(fy)?0:cimg::cut(fy,0,height() - 1); const int x = (int)nfx, y = (int)nfy; const float dx = nfx - x, dy = nfy - y; const int px = x - 1<0?0:x - 1, nx = dx<=0?x:x + 1, ax = x + 2>=width()?width() - 1:x + 2, py = y - 1<0?0:y - 1, ny = dy<=0?y:y + 1, ay = y + 2>=height()?height() - 1:y + 2; const Tfloat Ipp = (Tfloat)(*this)(px,py,z,c), Icp = (Tfloat)(*this)(x,py,z,c), Inp = (Tfloat)(*this)(nx,py,z,c), Iap = (Tfloat)(*this)(ax,py,z,c), Ip = Icp + 0.5f*(dx*(-Ipp + Inp) + dx*dx*(2*Ipp - 5*Icp + 4*Inp - Iap) + dx*dx*dx*(-Ipp + 3*Icp - 3*Inp + Iap)), Ipc = (Tfloat)(*this)(px,y,z,c), Icc = (Tfloat)(*this)(x, y,z,c), Inc = (Tfloat)(*this)(nx,y,z,c), Iac = (Tfloat)(*this)(ax,y,z,c), Ic = Icc + 0.5f*(dx*(-Ipc + Inc) + dx*dx*(2*Ipc - 5*Icc + 4*Inc - Iac) + dx*dx*dx*(-Ipc + 3*Icc - 3*Inc + Iac)), Ipn = (Tfloat)(*this)(px,ny,z,c), Icn = (Tfloat)(*this)(x,ny,z,c), Inn = (Tfloat)(*this)(nx,ny,z,c), Ian = (Tfloat)(*this)(ax,ny,z,c), In = Icn + 0.5f*(dx*(-Ipn + Inn) + dx*dx*(2*Ipn - 5*Icn + 4*Inn - Ian) + dx*dx*dx*(-Ipn + 3*Icn - 3*Inn + Ian)), Ipa = (Tfloat)(*this)(px,ay,z,c), Ica = (Tfloat)(*this)(x,ay,z,c), Ina = (Tfloat)(*this)(nx,ay,z,c), Iaa = (Tfloat)(*this)(ax,ay,z,c), Ia = Ica + 0.5f*(dx*(-Ipa + Ina) + dx*dx*(2*Ipa - 5*Ica + 4*Ina - Iaa) + dx*dx*dx*(-Ipa + 3*Ica - 3*Ina + Iaa)); return Ic + 0.5f*(dy*(-Ip + In) + dy*dy*(2*Ip - 5*Ic + 4*In - Ia) + dy*dy*dy*(-Ip + 3*Ic - 3*In + Ia)); } //! Return clamped pixel value, using cubic interpolation and Neumann boundary conditions for the X,Y-coordinates. /** Similar to cubic_atXY(float,float,int,int) const, except that the return value is clamped to stay in the min/max range of the datatype \c T. **/ T cubic_atXY_c(const float fx, const float fy, const int z, const int c) const { return cimg::type<T>::cut(cubic_atXY(fx,fy,z,c)); } T _cubic_atXY_c(const float fx, const float fy, const int z, const int c) const { return cimg::type<T>::cut(_cubic_atXY(fx,fy,z,c)); } //! Return pixel value, using cubic interpolation and mirror boundary conditions for the X and Y-coordinates. Tfloat cubic_atXY_p(const float fx, const float fy, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "cubic_atXY_p(): Empty instance.", cimg_instance); return _cubic_atXY_p(fx,fy,z,c); } Tfloat _cubic_atXY_p(const float fx, const float fy, const int z=0, const int c=0) const { const float nfx = cimg::type<float>::is_nan(fx)?0:cimg::mod(fx,(float)_width), nfy = cimg::type<float>::is_nan(fy)?0:cimg::mod(fy,(float)_height); const int x = (int)nfx, y = (int)nfy; const float dx = nfx - x, dy = nfy - y; const int px = cimg::mod(x - 1,width()), nx = cimg::mod(x + 1,width()), ax = cimg::mod(x + 2,width()), py = cimg::mod(y - 1,height()), ny = cimg::mod(y + 1,height()), ay = cimg::mod(y + 2,height()); const Tfloat Ipp = (Tfloat)(*this)(px,py,z,c), Icp = (Tfloat)(*this)(x,py,z,c), Inp = (Tfloat)(*this)(nx,py,z,c), Iap = (Tfloat)(*this)(ax,py,z,c), Ip = Icp + 0.5f*(dx*(-Ipp + Inp) + dx*dx*(2*Ipp - 5*Icp + 4*Inp - Iap) + dx*dx*dx*(-Ipp + 3*Icp - 3*Inp + Iap)), Ipc = (Tfloat)(*this)(px,y,z,c), Icc = (Tfloat)(*this)(x, y,z,c), Inc = (Tfloat)(*this)(nx,y,z,c), Iac = (Tfloat)(*this)(ax,y,z,c), Ic = Icc + 0.5f*(dx*(-Ipc + Inc) + dx*dx*(2*Ipc - 5*Icc + 4*Inc - Iac) + dx*dx*dx*(-Ipc + 3*Icc - 3*Inc + Iac)), Ipn = (Tfloat)(*this)(px,ny,z,c), Icn = (Tfloat)(*this)(x,ny,z,c), Inn = (Tfloat)(*this)(nx,ny,z,c), Ian = (Tfloat)(*this)(ax,ny,z,c), In = Icn + 0.5f*(dx*(-Ipn + Inn) + dx*dx*(2*Ipn - 5*Icn + 4*Inn - Ian) + dx*dx*dx*(-Ipn + 3*Icn - 3*Inn + Ian)), Ipa = (Tfloat)(*this)(px,ay,z,c), Ica = (Tfloat)(*this)(x,ay,z,c), Ina = (Tfloat)(*this)(nx,ay,z,c), Iaa = (Tfloat)(*this)(ax,ay,z,c), Ia = Ica + 0.5f*(dx*(-Ipa + Ina) + dx*dx*(2*Ipa - 5*Ica + 4*Ina - Iaa) + dx*dx*dx*(-Ipa + 3*Ica - 3*Ina + Iaa)); return Ic + 0.5f*(dy*(-Ip + In) + dy*dy*(2*Ip - 5*Ic + 4*In - Ia) + dy*dy*dy*(-Ip + 3*Ic - 3*In + Ia)); } T cubic_atXY_pc(const float fx, const float fy, const int z, const int c) const { return cimg::type<T>::cut(cubic_atXY_p(fx,fy,z,c)); } T _cubic_atXY_pc(const float fx, const float fy, const int z, const int c) const { return cimg::type<T>::cut(_cubic_atXY_p(fx,fy,z,c)); } //! Return pixel value, using cubic interpolation and Dirichlet boundary conditions for the X,Y and Z-coordinates. /** Similar to cubic_atX(float,int,int,int,const T) const, except that the cubic interpolation and boundary checking are achieved both for X,Y and Z-coordinates. **/ Tfloat cubic_atXYZ(const float fx, const float fy, const float fz, const int c, const T& out_value) const { const int x = (int)fx - (fx>=0?0:1), px = x - 1, nx = x + 1, ax = x + 2, y = (int)fy - (fy>=0?0:1), py = y - 1, ny = y + 1, ay = y + 2, z = (int)fz - (fz>=0?0:1), pz = z - 1, nz = z + 1, az = z + 2; const float dx = fx - x, dy = fy - y, dz = fz - z; const Tfloat Ippp = (Tfloat)atXYZ(px,py,pz,c,out_value), Icpp = (Tfloat)atXYZ(x,py,pz,c,out_value), Inpp = (Tfloat)atXYZ(nx,py,pz,c,out_value), Iapp = (Tfloat)atXYZ(ax,py,pz,c,out_value), Ipp = Icpp + 0.5f*(dx*(-Ippp + Inpp) + dx*dx*(2*Ippp - 5*Icpp + 4*Inpp - Iapp) + dx*dx*dx*(-Ippp + 3*Icpp - 3*Inpp + Iapp)), Ipcp = (Tfloat)atXYZ(px,y,pz,c,out_value), Iccp = (Tfloat)atXYZ(x, y,pz,c,out_value), Incp = (Tfloat)atXYZ(nx,y,pz,c,out_value), Iacp = (Tfloat)atXYZ(ax,y,pz,c,out_value), Icp = Iccp + 0.5f*(dx*(-Ipcp + Incp) + dx*dx*(2*Ipcp - 5*Iccp + 4*Incp - Iacp) + dx*dx*dx*(-Ipcp + 3*Iccp - 3*Incp + Iacp)), Ipnp = (Tfloat)atXYZ(px,ny,pz,c,out_value), Icnp = (Tfloat)atXYZ(x,ny,pz,c,out_value), Innp = (Tfloat)atXYZ(nx,ny,pz,c,out_value), Ianp = (Tfloat)atXYZ(ax,ny,pz,c,out_value), Inp = Icnp + 0.5f*(dx*(-Ipnp + Innp) + dx*dx*(2*Ipnp - 5*Icnp + 4*Innp - Ianp) + dx*dx*dx*(-Ipnp + 3*Icnp - 3*Innp + Ianp)), Ipap = (Tfloat)atXYZ(px,ay,pz,c,out_value), Icap = (Tfloat)atXYZ(x,ay,pz,c,out_value), Inap = (Tfloat)atXYZ(nx,ay,pz,c,out_value), Iaap = (Tfloat)atXYZ(ax,ay,pz,c,out_value), Iap = Icap + 0.5f*(dx*(-Ipap + Inap) + dx*dx*(2*Ipap - 5*Icap + 4*Inap - Iaap) + dx*dx*dx*(-Ipap + 3*Icap - 3*Inap + Iaap)), Ip = Icp + 0.5f*(dy*(-Ipp + Inp) + dy*dy*(2*Ipp - 5*Icp + 4*Inp - Iap) + dy*dy*dy*(-Ipp + 3*Icp - 3*Inp + Iap)), Ippc = (Tfloat)atXYZ(px,py,z,c,out_value), Icpc = (Tfloat)atXYZ(x,py,z,c,out_value), Inpc = (Tfloat)atXYZ(nx,py,z,c,out_value), Iapc = (Tfloat)atXYZ(ax,py,z,c,out_value), Ipc = Icpc + 0.5f*(dx*(-Ippc + Inpc) + dx*dx*(2*Ippc - 5*Icpc + 4*Inpc - Iapc) + dx*dx*dx*(-Ippc + 3*Icpc - 3*Inpc + Iapc)), Ipcc = (Tfloat)atXYZ(px,y,z,c,out_value), Iccc = (Tfloat)atXYZ(x, y,z,c,out_value), Incc = (Tfloat)atXYZ(nx,y,z,c,out_value), Iacc = (Tfloat)atXYZ(ax,y,z,c,out_value), Icc = Iccc + 0.5f*(dx*(-Ipcc + Incc) + dx*dx*(2*Ipcc - 5*Iccc + 4*Incc - Iacc) + dx*dx*dx*(-Ipcc + 3*Iccc - 3*Incc + Iacc)), Ipnc = (Tfloat)atXYZ(px,ny,z,c,out_value), Icnc = (Tfloat)atXYZ(x,ny,z,c,out_value), Innc = (Tfloat)atXYZ(nx,ny,z,c,out_value), Ianc = (Tfloat)atXYZ(ax,ny,z,c,out_value), Inc = Icnc + 0.5f*(dx*(-Ipnc + Innc) + dx*dx*(2*Ipnc - 5*Icnc + 4*Innc - Ianc) + dx*dx*dx*(-Ipnc + 3*Icnc - 3*Innc + Ianc)), Ipac = (Tfloat)atXYZ(px,ay,z,c,out_value), Icac = (Tfloat)atXYZ(x,ay,z,c,out_value), Inac = (Tfloat)atXYZ(nx,ay,z,c,out_value), Iaac = (Tfloat)atXYZ(ax,ay,z,c,out_value), Iac = Icac + 0.5f*(dx*(-Ipac + Inac) + dx*dx*(2*Ipac - 5*Icac + 4*Inac - Iaac) + dx*dx*dx*(-Ipac + 3*Icac - 3*Inac + Iaac)), Ic = Icc + 0.5f*(dy*(-Ipc + Inc) + dy*dy*(2*Ipc - 5*Icc + 4*Inc - Iac) + dy*dy*dy*(-Ipc + 3*Icc - 3*Inc + Iac)), Ippn = (Tfloat)atXYZ(px,py,nz,c,out_value), Icpn = (Tfloat)atXYZ(x,py,nz,c,out_value), Inpn = (Tfloat)atXYZ(nx,py,nz,c,out_value), Iapn = (Tfloat)atXYZ(ax,py,nz,c,out_value), Ipn = Icpn + 0.5f*(dx*(-Ippn + Inpn) + dx*dx*(2*Ippn - 5*Icpn + 4*Inpn - Iapn) + dx*dx*dx*(-Ippn + 3*Icpn - 3*Inpn + Iapn)), Ipcn = (Tfloat)atXYZ(px,y,nz,c,out_value), Iccn = (Tfloat)atXYZ(x, y,nz,c,out_value), Incn = (Tfloat)atXYZ(nx,y,nz,c,out_value), Iacn = (Tfloat)atXYZ(ax,y,nz,c,out_value), Icn = Iccn + 0.5f*(dx*(-Ipcn + Incn) + dx*dx*(2*Ipcn - 5*Iccn + 4*Incn - Iacn) + dx*dx*dx*(-Ipcn + 3*Iccn - 3*Incn + Iacn)), Ipnn = (Tfloat)atXYZ(px,ny,nz,c,out_value), Icnn = (Tfloat)atXYZ(x,ny,nz,c,out_value), Innn = (Tfloat)atXYZ(nx,ny,nz,c,out_value), Iann = (Tfloat)atXYZ(ax,ny,nz,c,out_value), Inn = Icnn + 0.5f*(dx*(-Ipnn + Innn) + dx*dx*(2*Ipnn - 5*Icnn + 4*Innn - Iann) + dx*dx*dx*(-Ipnn + 3*Icnn - 3*Innn + Iann)), Ipan = (Tfloat)atXYZ(px,ay,nz,c,out_value), Ican = (Tfloat)atXYZ(x,ay,nz,c,out_value), Inan = (Tfloat)atXYZ(nx,ay,nz,c,out_value), Iaan = (Tfloat)atXYZ(ax,ay,nz,c,out_value), Ian = Ican + 0.5f*(dx*(-Ipan + Inan) + dx*dx*(2*Ipan - 5*Ican + 4*Inan - Iaan) + dx*dx*dx*(-Ipan + 3*Ican - 3*Inan + Iaan)), In = Icn + 0.5f*(dy*(-Ipn + Inn) + dy*dy*(2*Ipn - 5*Icn + 4*Inn - Ian) + dy*dy*dy*(-Ipn + 3*Icn - 3*Inn + Ian)), Ippa = (Tfloat)atXYZ(px,py,az,c,out_value), Icpa = (Tfloat)atXYZ(x,py,az,c,out_value), Inpa = (Tfloat)atXYZ(nx,py,az,c,out_value), Iapa = (Tfloat)atXYZ(ax,py,az,c,out_value), Ipa = Icpa + 0.5f*(dx*(-Ippa + Inpa) + dx*dx*(2*Ippa - 5*Icpa + 4*Inpa - Iapa) + dx*dx*dx*(-Ippa + 3*Icpa - 3*Inpa + Iapa)), Ipca = (Tfloat)atXYZ(px,y,az,c,out_value), Icca = (Tfloat)atXYZ(x, y,az,c,out_value), Inca = (Tfloat)atXYZ(nx,y,az,c,out_value), Iaca = (Tfloat)atXYZ(ax,y,az,c,out_value), Ica = Icca + 0.5f*(dx*(-Ipca + Inca) + dx*dx*(2*Ipca - 5*Icca + 4*Inca - Iaca) + dx*dx*dx*(-Ipca + 3*Icca - 3*Inca + Iaca)), Ipna = (Tfloat)atXYZ(px,ny,az,c,out_value), Icna = (Tfloat)atXYZ(x,ny,az,c,out_value), Inna = (Tfloat)atXYZ(nx,ny,az,c,out_value), Iana = (Tfloat)atXYZ(ax,ny,az,c,out_value), Ina = Icna + 0.5f*(dx*(-Ipna + Inna) + dx*dx*(2*Ipna - 5*Icna + 4*Inna - Iana) + dx*dx*dx*(-Ipna + 3*Icna - 3*Inna + Iana)), Ipaa = (Tfloat)atXYZ(px,ay,az,c,out_value), Icaa = (Tfloat)atXYZ(x,ay,az,c,out_value), Inaa = (Tfloat)atXYZ(nx,ay,az,c,out_value), Iaaa = (Tfloat)atXYZ(ax,ay,az,c,out_value), Iaa = Icaa + 0.5f*(dx*(-Ipaa + Inaa) + dx*dx*(2*Ipaa - 5*Icaa + 4*Inaa - Iaaa) + dx*dx*dx*(-Ipaa + 3*Icaa - 3*Inaa + Iaaa)), Ia = Ica + 0.5f*(dy*(-Ipa + Ina) + dy*dy*(2*Ipa - 5*Ica + 4*Ina - Iaa) + dy*dy*dy*(-Ipa + 3*Ica - 3*Ina + Iaa)); return Ic + 0.5f*(dz*(-Ip + In) + dz*dz*(2*Ip - 5*Ic + 4*In - Ia) + dz*dz*dz*(-Ip + 3*Ic - 3*In + Ia)); } //! Return clamped pixel value, using cubic interpolation and Dirichlet boundary conditions for the XYZ-coordinates. /** Similar to cubic_atXYZ(float,float,float,int,const T) const, except that the return value is clamped to stay in the min/max range of the datatype \c T. **/ T cubic_atXYZ_c(const float fx, const float fy, const float fz, const int c, const T& out_value) const { return cimg::type<T>::cut(cubic_atXYZ(fx,fy,fz,c,out_value)); } //! Return pixel value, using cubic interpolation and Neumann boundary conditions for the X,Y and Z-coordinates. /** Similar to cubic_atX(float,int,int,int) const, except that the cubic interpolation and boundary checking are achieved both for X,Y and Z-coordinates. \note - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _cubic_atXYZ(float,float,float,int). **/ Tfloat cubic_atXYZ(const float fx, const float fy, const float fz, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "cubic_atXYZ(): Empty instance.", cimg_instance); return _cubic_atXYZ(fx,fy,fz,c); } Tfloat _cubic_atXYZ(const float fx, const float fy, const float fz, const int c=0) const { const float nfx = cimg::type<float>::is_nan(fx)?0:cimg::cut(fx,0,width() - 1), nfy = cimg::type<float>::is_nan(fy)?0:cimg::cut(fy,0,height() - 1), nfz = cimg::type<float>::is_nan(fz)?0:cimg::cut(fz,0,depth() - 1); const int x = (int)nfx, y = (int)nfy, z = (int)nfz; const float dx = nfx - x, dy = nfy - y, dz = nfz - z; const int px = x - 1<0?0:x - 1, nx = dx>0?x + 1:x, ax = x + 2>=width()?width() - 1:x + 2, py = y - 1<0?0:y - 1, ny = dy>0?y + 1:y, ay = y + 2>=height()?height() - 1:y + 2, pz = z - 1<0?0:z - 1, nz = dz>0?z + 1:z, az = z + 2>=depth()?depth() - 1:z + 2; const Tfloat Ippp = (Tfloat)(*this)(px,py,pz,c), Icpp = (Tfloat)(*this)(x,py,pz,c), Inpp = (Tfloat)(*this)(nx,py,pz,c), Iapp = (Tfloat)(*this)(ax,py,pz,c), Ipp = Icpp + 0.5f*(dx*(-Ippp + Inpp) + dx*dx*(2*Ippp - 5*Icpp + 4*Inpp - Iapp) + dx*dx*dx*(-Ippp + 3*Icpp - 3*Inpp + Iapp)), Ipcp = (Tfloat)(*this)(px,y,pz,c), Iccp = (Tfloat)(*this)(x, y,pz,c), Incp = (Tfloat)(*this)(nx,y,pz,c), Iacp = (Tfloat)(*this)(ax,y,pz,c), Icp = Iccp + 0.5f*(dx*(-Ipcp + Incp) + dx*dx*(2*Ipcp - 5*Iccp + 4*Incp - Iacp) + dx*dx*dx*(-Ipcp + 3*Iccp - 3*Incp + Iacp)), Ipnp = (Tfloat)(*this)(px,ny,pz,c), Icnp = (Tfloat)(*this)(x,ny,pz,c), Innp = (Tfloat)(*this)(nx,ny,pz,c), Ianp = (Tfloat)(*this)(ax,ny,pz,c), Inp = Icnp + 0.5f*(dx*(-Ipnp + Innp) + dx*dx*(2*Ipnp - 5*Icnp + 4*Innp - Ianp) + dx*dx*dx*(-Ipnp + 3*Icnp - 3*Innp + Ianp)), Ipap = (Tfloat)(*this)(px,ay,pz,c), Icap = (Tfloat)(*this)(x,ay,pz,c), Inap = (Tfloat)(*this)(nx,ay,pz,c), Iaap = (Tfloat)(*this)(ax,ay,pz,c), Iap = Icap + 0.5f*(dx*(-Ipap + Inap) + dx*dx*(2*Ipap - 5*Icap + 4*Inap - Iaap) + dx*dx*dx*(-Ipap + 3*Icap - 3*Inap + Iaap)), Ip = Icp + 0.5f*(dy*(-Ipp + Inp) + dy*dy*(2*Ipp - 5*Icp + 4*Inp - Iap) + dy*dy*dy*(-Ipp + 3*Icp - 3*Inp + Iap)), Ippc = (Tfloat)(*this)(px,py,z,c), Icpc = (Tfloat)(*this)(x,py,z,c), Inpc = (Tfloat)(*this)(nx,py,z,c), Iapc = (Tfloat)(*this)(ax,py,z,c), Ipc = Icpc + 0.5f*(dx*(-Ippc + Inpc) + dx*dx*(2*Ippc - 5*Icpc + 4*Inpc - Iapc) + dx*dx*dx*(-Ippc + 3*Icpc - 3*Inpc + Iapc)), Ipcc = (Tfloat)(*this)(px,y,z,c), Iccc = (Tfloat)(*this)(x, y,z,c), Incc = (Tfloat)(*this)(nx,y,z,c), Iacc = (Tfloat)(*this)(ax,y,z,c), Icc = Iccc + 0.5f*(dx*(-Ipcc + Incc) + dx*dx*(2*Ipcc - 5*Iccc + 4*Incc - Iacc) + dx*dx*dx*(-Ipcc + 3*Iccc - 3*Incc + Iacc)), Ipnc = (Tfloat)(*this)(px,ny,z,c), Icnc = (Tfloat)(*this)(x,ny,z,c), Innc = (Tfloat)(*this)(nx,ny,z,c), Ianc = (Tfloat)(*this)(ax,ny,z,c), Inc = Icnc + 0.5f*(dx*(-Ipnc + Innc) + dx*dx*(2*Ipnc - 5*Icnc + 4*Innc - Ianc) + dx*dx*dx*(-Ipnc + 3*Icnc - 3*Innc + Ianc)), Ipac = (Tfloat)(*this)(px,ay,z,c), Icac = (Tfloat)(*this)(x,ay,z,c), Inac = (Tfloat)(*this)(nx,ay,z,c), Iaac = (Tfloat)(*this)(ax,ay,z,c), Iac = Icac + 0.5f*(dx*(-Ipac + Inac) + dx*dx*(2*Ipac - 5*Icac + 4*Inac - Iaac) + dx*dx*dx*(-Ipac + 3*Icac - 3*Inac + Iaac)), Ic = Icc + 0.5f*(dy*(-Ipc + Inc) + dy*dy*(2*Ipc - 5*Icc + 4*Inc - Iac) + dy*dy*dy*(-Ipc + 3*Icc - 3*Inc + Iac)), Ippn = (Tfloat)(*this)(px,py,nz,c), Icpn = (Tfloat)(*this)(x,py,nz,c), Inpn = (Tfloat)(*this)(nx,py,nz,c), Iapn = (Tfloat)(*this)(ax,py,nz,c), Ipn = Icpn + 0.5f*(dx*(-Ippn + Inpn) + dx*dx*(2*Ippn - 5*Icpn + 4*Inpn - Iapn) + dx*dx*dx*(-Ippn + 3*Icpn - 3*Inpn + Iapn)), Ipcn = (Tfloat)(*this)(px,y,nz,c), Iccn = (Tfloat)(*this)(x, y,nz,c), Incn = (Tfloat)(*this)(nx,y,nz,c), Iacn = (Tfloat)(*this)(ax,y,nz,c), Icn = Iccn + 0.5f*(dx*(-Ipcn + Incn) + dx*dx*(2*Ipcn - 5*Iccn + 4*Incn - Iacn) + dx*dx*dx*(-Ipcn + 3*Iccn - 3*Incn + Iacn)), Ipnn = (Tfloat)(*this)(px,ny,nz,c), Icnn = (Tfloat)(*this)(x,ny,nz,c), Innn = (Tfloat)(*this)(nx,ny,nz,c), Iann = (Tfloat)(*this)(ax,ny,nz,c), Inn = Icnn + 0.5f*(dx*(-Ipnn + Innn) + dx*dx*(2*Ipnn - 5*Icnn + 4*Innn - Iann) + dx*dx*dx*(-Ipnn + 3*Icnn - 3*Innn + Iann)), Ipan = (Tfloat)(*this)(px,ay,nz,c), Ican = (Tfloat)(*this)(x,ay,nz,c), Inan = (Tfloat)(*this)(nx,ay,nz,c), Iaan = (Tfloat)(*this)(ax,ay,nz,c), Ian = Ican + 0.5f*(dx*(-Ipan + Inan) + dx*dx*(2*Ipan - 5*Ican + 4*Inan - Iaan) + dx*dx*dx*(-Ipan + 3*Ican - 3*Inan + Iaan)), In = Icn + 0.5f*(dy*(-Ipn + Inn) + dy*dy*(2*Ipn - 5*Icn + 4*Inn - Ian) + dy*dy*dy*(-Ipn + 3*Icn - 3*Inn + Ian)), Ippa = (Tfloat)(*this)(px,py,az,c), Icpa = (Tfloat)(*this)(x,py,az,c), Inpa = (Tfloat)(*this)(nx,py,az,c), Iapa = (Tfloat)(*this)(ax,py,az,c), Ipa = Icpa + 0.5f*(dx*(-Ippa + Inpa) + dx*dx*(2*Ippa - 5*Icpa + 4*Inpa - Iapa) + dx*dx*dx*(-Ippa + 3*Icpa - 3*Inpa + Iapa)), Ipca = (Tfloat)(*this)(px,y,az,c), Icca = (Tfloat)(*this)(x, y,az,c), Inca = (Tfloat)(*this)(nx,y,az,c), Iaca = (Tfloat)(*this)(ax,y,az,c), Ica = Icca + 0.5f*(dx*(-Ipca + Inca) + dx*dx*(2*Ipca - 5*Icca + 4*Inca - Iaca) + dx*dx*dx*(-Ipca + 3*Icca - 3*Inca + Iaca)), Ipna = (Tfloat)(*this)(px,ny,az,c), Icna = (Tfloat)(*this)(x,ny,az,c), Inna = (Tfloat)(*this)(nx,ny,az,c), Iana = (Tfloat)(*this)(ax,ny,az,c), Ina = Icna + 0.5f*(dx*(-Ipna + Inna) + dx*dx*(2*Ipna - 5*Icna + 4*Inna - Iana) + dx*dx*dx*(-Ipna + 3*Icna - 3*Inna + Iana)), Ipaa = (Tfloat)(*this)(px,ay,az,c), Icaa = (Tfloat)(*this)(x,ay,az,c), Inaa = (Tfloat)(*this)(nx,ay,az,c), Iaaa = (Tfloat)(*this)(ax,ay,az,c), Iaa = Icaa + 0.5f*(dx*(-Ipaa + Inaa) + dx*dx*(2*Ipaa - 5*Icaa + 4*Inaa - Iaaa) + dx*dx*dx*(-Ipaa + 3*Icaa - 3*Inaa + Iaaa)), Ia = Ica + 0.5f*(dy*(-Ipa + Ina) + dy*dy*(2*Ipa - 5*Ica + 4*Ina - Iaa) + dy*dy*dy*(-Ipa + 3*Ica - 3*Ina + Iaa)); return Ic + 0.5f*(dz*(-Ip + In) + dz*dz*(2*Ip - 5*Ic + 4*In - Ia) + dz*dz*dz*(-Ip + 3*Ic - 3*In + Ia)); } //! Return clamped pixel value, using cubic interpolation and Neumann boundary conditions for the XYZ-coordinates. /** Similar to cubic_atXYZ(float,float,float,int) const, except that the return value is clamped to stay in the min/max range of the datatype \c T. **/ T cubic_atXYZ_c(const float fx, const float fy, const float fz, const int c) const { return cimg::type<T>::cut(cubic_atXYZ(fx,fy,fz,c)); } T _cubic_atXYZ_c(const float fx, const float fy, const float fz, const int c) const { return cimg::type<T>::cut(_cubic_atXYZ(fx,fy,fz,c)); } //! Return pixel value, using cubic interpolation and Neumann boundary conditions for the X,Y and Z-coordinates. /** Similar to cubic_atX(float,int,int,int) const, except that the cubic interpolation and boundary checking are achieved both for X,Y and Z-coordinates. \note - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _cubic_atXYZ(float,float,float,int). **/ Tfloat cubic_atXYZ_p(const float fx, const float fy, const float fz, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "cubic_atXYZ_p(): Empty instance.", cimg_instance); return _cubic_atXYZ_p(fx,fy,fz,c); } Tfloat _cubic_atXYZ_p(const float fx, const float fy, const float fz, const int c=0) const { const float nfx = cimg::type<float>::is_nan(fx)?0:cimg::mod(fx,(float)_width), nfy = cimg::type<float>::is_nan(fy)?0:cimg::mod(fy,(float)_height), nfz = cimg::type<float>::is_nan(fz)?0:cimg::mod(fz,(float)_depth); const int x = (int)nfx, y = (int)nfy, z = (int)nfz; const float dx = nfx - x, dy = nfy - y, dz = nfz - z; const int px = cimg::mod(x - 1,width()), nx = cimg::mod(x + 1,width()), ax = cimg::mod(x + 2,width()), py = cimg::mod(y - 1,height()), ny = cimg::mod(y + 1,height()), ay = cimg::mod(y + 2,height()), pz = cimg::mod(z - 1,depth()), nz = cimg::mod(z + 1,depth()), az = cimg::mod(z + 2,depth()); const Tfloat Ippp = (Tfloat)(*this)(px,py,pz,c), Icpp = (Tfloat)(*this)(x,py,pz,c), Inpp = (Tfloat)(*this)(nx,py,pz,c), Iapp = (Tfloat)(*this)(ax,py,pz,c), Ipp = Icpp + 0.5f*(dx*(-Ippp + Inpp) + dx*dx*(2*Ippp - 5*Icpp + 4*Inpp - Iapp) + dx*dx*dx*(-Ippp + 3*Icpp - 3*Inpp + Iapp)), Ipcp = (Tfloat)(*this)(px,y,pz,c), Iccp = (Tfloat)(*this)(x, y,pz,c), Incp = (Tfloat)(*this)(nx,y,pz,c), Iacp = (Tfloat)(*this)(ax,y,pz,c), Icp = Iccp + 0.5f*(dx*(-Ipcp + Incp) + dx*dx*(2*Ipcp - 5*Iccp + 4*Incp - Iacp) + dx*dx*dx*(-Ipcp + 3*Iccp - 3*Incp + Iacp)), Ipnp = (Tfloat)(*this)(px,ny,pz,c), Icnp = (Tfloat)(*this)(x,ny,pz,c), Innp = (Tfloat)(*this)(nx,ny,pz,c), Ianp = (Tfloat)(*this)(ax,ny,pz,c), Inp = Icnp + 0.5f*(dx*(-Ipnp + Innp) + dx*dx*(2*Ipnp - 5*Icnp + 4*Innp - Ianp) + dx*dx*dx*(-Ipnp + 3*Icnp - 3*Innp + Ianp)), Ipap = (Tfloat)(*this)(px,ay,pz,c), Icap = (Tfloat)(*this)(x,ay,pz,c), Inap = (Tfloat)(*this)(nx,ay,pz,c), Iaap = (Tfloat)(*this)(ax,ay,pz,c), Iap = Icap + 0.5f*(dx*(-Ipap + Inap) + dx*dx*(2*Ipap - 5*Icap + 4*Inap - Iaap) + dx*dx*dx*(-Ipap + 3*Icap - 3*Inap + Iaap)), Ip = Icp + 0.5f*(dy*(-Ipp + Inp) + dy*dy*(2*Ipp - 5*Icp + 4*Inp - Iap) + dy*dy*dy*(-Ipp + 3*Icp - 3*Inp + Iap)), Ippc = (Tfloat)(*this)(px,py,z,c), Icpc = (Tfloat)(*this)(x,py,z,c), Inpc = (Tfloat)(*this)(nx,py,z,c), Iapc = (Tfloat)(*this)(ax,py,z,c), Ipc = Icpc + 0.5f*(dx*(-Ippc + Inpc) + dx*dx*(2*Ippc - 5*Icpc + 4*Inpc - Iapc) + dx*dx*dx*(-Ippc + 3*Icpc - 3*Inpc + Iapc)), Ipcc = (Tfloat)(*this)(px,y,z,c), Iccc = (Tfloat)(*this)(x, y,z,c), Incc = (Tfloat)(*this)(nx,y,z,c), Iacc = (Tfloat)(*this)(ax,y,z,c), Icc = Iccc + 0.5f*(dx*(-Ipcc + Incc) + dx*dx*(2*Ipcc - 5*Iccc + 4*Incc - Iacc) + dx*dx*dx*(-Ipcc + 3*Iccc - 3*Incc + Iacc)), Ipnc = (Tfloat)(*this)(px,ny,z,c), Icnc = (Tfloat)(*this)(x,ny,z,c), Innc = (Tfloat)(*this)(nx,ny,z,c), Ianc = (Tfloat)(*this)(ax,ny,z,c), Inc = Icnc + 0.5f*(dx*(-Ipnc + Innc) + dx*dx*(2*Ipnc - 5*Icnc + 4*Innc - Ianc) + dx*dx*dx*(-Ipnc + 3*Icnc - 3*Innc + Ianc)), Ipac = (Tfloat)(*this)(px,ay,z,c), Icac = (Tfloat)(*this)(x,ay,z,c), Inac = (Tfloat)(*this)(nx,ay,z,c), Iaac = (Tfloat)(*this)(ax,ay,z,c), Iac = Icac + 0.5f*(dx*(-Ipac + Inac) + dx*dx*(2*Ipac - 5*Icac + 4*Inac - Iaac) + dx*dx*dx*(-Ipac + 3*Icac - 3*Inac + Iaac)), Ic = Icc + 0.5f*(dy*(-Ipc + Inc) + dy*dy*(2*Ipc - 5*Icc + 4*Inc - Iac) + dy*dy*dy*(-Ipc + 3*Icc - 3*Inc + Iac)), Ippn = (Tfloat)(*this)(px,py,nz,c), Icpn = (Tfloat)(*this)(x,py,nz,c), Inpn = (Tfloat)(*this)(nx,py,nz,c), Iapn = (Tfloat)(*this)(ax,py,nz,c), Ipn = Icpn + 0.5f*(dx*(-Ippn + Inpn) + dx*dx*(2*Ippn - 5*Icpn + 4*Inpn - Iapn) + dx*dx*dx*(-Ippn + 3*Icpn - 3*Inpn + Iapn)), Ipcn = (Tfloat)(*this)(px,y,nz,c), Iccn = (Tfloat)(*this)(x, y,nz,c), Incn = (Tfloat)(*this)(nx,y,nz,c), Iacn = (Tfloat)(*this)(ax,y,nz,c), Icn = Iccn + 0.5f*(dx*(-Ipcn + Incn) + dx*dx*(2*Ipcn - 5*Iccn + 4*Incn - Iacn) + dx*dx*dx*(-Ipcn + 3*Iccn - 3*Incn + Iacn)), Ipnn = (Tfloat)(*this)(px,ny,nz,c), Icnn = (Tfloat)(*this)(x,ny,nz,c), Innn = (Tfloat)(*this)(nx,ny,nz,c), Iann = (Tfloat)(*this)(ax,ny,nz,c), Inn = Icnn + 0.5f*(dx*(-Ipnn + Innn) + dx*dx*(2*Ipnn - 5*Icnn + 4*Innn - Iann) + dx*dx*dx*(-Ipnn + 3*Icnn - 3*Innn + Iann)), Ipan = (Tfloat)(*this)(px,ay,nz,c), Ican = (Tfloat)(*this)(x,ay,nz,c), Inan = (Tfloat)(*this)(nx,ay,nz,c), Iaan = (Tfloat)(*this)(ax,ay,nz,c), Ian = Ican + 0.5f*(dx*(-Ipan + Inan) + dx*dx*(2*Ipan - 5*Ican + 4*Inan - Iaan) + dx*dx*dx*(-Ipan + 3*Ican - 3*Inan + Iaan)), In = Icn + 0.5f*(dy*(-Ipn + Inn) + dy*dy*(2*Ipn - 5*Icn + 4*Inn - Ian) + dy*dy*dy*(-Ipn + 3*Icn - 3*Inn + Ian)), Ippa = (Tfloat)(*this)(px,py,az,c), Icpa = (Tfloat)(*this)(x,py,az,c), Inpa = (Tfloat)(*this)(nx,py,az,c), Iapa = (Tfloat)(*this)(ax,py,az,c), Ipa = Icpa + 0.5f*(dx*(-Ippa + Inpa) + dx*dx*(2*Ippa - 5*Icpa + 4*Inpa - Iapa) + dx*dx*dx*(-Ippa + 3*Icpa - 3*Inpa + Iapa)), Ipca = (Tfloat)(*this)(px,y,az,c), Icca = (Tfloat)(*this)(x, y,az,c), Inca = (Tfloat)(*this)(nx,y,az,c), Iaca = (Tfloat)(*this)(ax,y,az,c), Ica = Icca + 0.5f*(dx*(-Ipca + Inca) + dx*dx*(2*Ipca - 5*Icca + 4*Inca - Iaca) + dx*dx*dx*(-Ipca + 3*Icca - 3*Inca + Iaca)), Ipna = (Tfloat)(*this)(px,ny,az,c), Icna = (Tfloat)(*this)(x,ny,az,c), Inna = (Tfloat)(*this)(nx,ny,az,c), Iana = (Tfloat)(*this)(ax,ny,az,c), Ina = Icna + 0.5f*(dx*(-Ipna + Inna) + dx*dx*(2*Ipna - 5*Icna + 4*Inna - Iana) + dx*dx*dx*(-Ipna + 3*Icna - 3*Inna + Iana)), Ipaa = (Tfloat)(*this)(px,ay,az,c), Icaa = (Tfloat)(*this)(x,ay,az,c), Inaa = (Tfloat)(*this)(nx,ay,az,c), Iaaa = (Tfloat)(*this)(ax,ay,az,c), Iaa = Icaa + 0.5f*(dx*(-Ipaa + Inaa) + dx*dx*(2*Ipaa - 5*Icaa + 4*Inaa - Iaaa) + dx*dx*dx*(-Ipaa + 3*Icaa - 3*Inaa + Iaaa)), Ia = Ica + 0.5f*(dy*(-Ipa + Ina) + dy*dy*(2*Ipa - 5*Ica + 4*Ina - Iaa) + dy*dy*dy*(-Ipa + 3*Ica - 3*Ina + Iaa)); return Ic + 0.5f*(dz*(-Ip + In) + dz*dz*(2*Ip - 5*Ic + 4*In - Ia) + dz*dz*dz*(-Ip + 3*Ic - 3*In + Ia)); } T cubic_atXYZ_pc(const float fx, const float fy, const float fz, const int c) const { return cimg::type<T>::cut(cubic_atXYZ_p(fx,fy,fz,c)); } T _cubic_atXYZ_pc(const float fx, const float fy, const float fz, const int c) const { return cimg::type<T>::cut(_cubic_atXYZ_p(fx,fy,fz,c)); } //! Set pixel value, using linear interpolation for the X-coordinates. /** Set pixel value at specified coordinates (\c fx,\c y,\c z,\c c) in the image instance, in a way that the value is spread amongst several neighbors if the pixel coordinates are float-valued. \param value Pixel value to set. \param fx X-coordinate of the pixel value (float-valued). \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param is_added Tells if the pixel value is added to (\c true), or simply replace (\c false) the current image pixel(s). \return A reference to the current image instance. \note - Calling this method with out-of-bounds coordinates does nothing. **/ CImg<T>& set_linear_atX(const T& value, const float fx, const int y=0, const int z=0, const int c=0, const bool is_added=false) { const int x = (int)fx - (fx>=0?0:1), nx = x + 1; const float dx = fx - x; if (y>=0 && y<height() && z>=0 && z<depth() && c>=0 && c<spectrum()) { if (x>=0 && x<width()) { const float w1 = 1 - dx, w2 = is_added?1:(1 - w1); (*this)(x,y,z,c) = (T)(w1*value + w2*(*this)(x,y,z,c)); } if (nx>=0 && nx<width()) { const float w1 = dx, w2 = is_added?1:(1 - w1); (*this)(nx,y,z,c) = (T)(w1*value + w2*(*this)(nx,y,z,c)); } } return *this; } //! Set pixel value, using linear interpolation for the X and Y-coordinates. /** Similar to set_linear_atX(const T&,float,int,int,int,bool), except that the linear interpolation is achieved both for X and Y-coordinates. **/ CImg<T>& set_linear_atXY(const T& value, const float fx, const float fy=0, const int z=0, const int c=0, const bool is_added=false) { const int x = (int)fx - (fx>=0?0:1), nx = x + 1, y = (int)fy - (fy>=0?0:1), ny = y + 1; const float dx = fx - x, dy = fy - y; if (z>=0 && z<depth() && c>=0 && c<spectrum()) { if (y>=0 && y<height()) { if (x>=0 && x<width()) { const float w1 = (1 - dx)*(1 - dy), w2 = is_added?1:(1 - w1); (*this)(x,y,z,c) = (T)(w1*value + w2*(*this)(x,y,z,c)); } if (nx>=0 && nx<width()) { const float w1 = dx*(1 - dy), w2 = is_added?1:(1 - w1); (*this)(nx,y,z,c) = (T)(w1*value + w2*(*this)(nx,y,z,c)); } } if (ny>=0 && ny<height()) { if (x>=0 && x<width()) { const float w1 = (1 - dx)*dy, w2 = is_added?1:(1 - w1); (*this)(x,ny,z,c) = (T)(w1*value + w2*(*this)(x,ny,z,c)); } if (nx>=0 && nx<width()) { const float w1 = dx*dy, w2 = is_added?1:(1 - w1); (*this)(nx,ny,z,c) = (T)(w1*value + w2*(*this)(nx,ny,z,c)); } } } return *this; } //! Set pixel value, using linear interpolation for the X,Y and Z-coordinates. /** Similar to set_linear_atXY(const T&,float,float,int,int,bool), except that the linear interpolation is achieved both for X,Y and Z-coordinates. **/ CImg<T>& set_linear_atXYZ(const T& value, const float fx, const float fy=0, const float fz=0, const int c=0, const bool is_added=false) { const int x = (int)fx - (fx>=0?0:1), nx = x + 1, y = (int)fy - (fy>=0?0:1), ny = y + 1, z = (int)fz - (fz>=0?0:1), nz = z + 1; const float dx = fx - x, dy = fy - y, dz = fz - z; if (c>=0 && c<spectrum()) { if (z>=0 && z<depth()) { if (y>=0 && y<height()) { if (x>=0 && x<width()) { const float w1 = (1 - dx)*(1 - dy)*(1 - dz), w2 = is_added?1:(1 - w1); (*this)(x,y,z,c) = (T)(w1*value + w2*(*this)(x,y,z,c)); } if (nx>=0 && nx<width()) { const float w1 = dx*(1 - dy)*(1 - dz), w2 = is_added?1:(1 - w1); (*this)(nx,y,z,c) = (T)(w1*value + w2*(*this)(nx,y,z,c)); } } if (ny>=0 && ny<height()) { if (x>=0 && x<width()) { const float w1 = (1 - dx)*dy*(1 - dz), w2 = is_added?1:(1 - w1); (*this)(x,ny,z,c) = (T)(w1*value + w2*(*this)(x,ny,z,c)); } if (nx>=0 && nx<width()) { const float w1 = dx*dy*(1 - dz), w2 = is_added?1:(1 - w1); (*this)(nx,ny,z,c) = (T)(w1*value + w2*(*this)(nx,ny,z,c)); } } } if (nz>=0 && nz<depth()) { if (y>=0 && y<height()) { if (x>=0 && x<width()) { const float w1 = (1 - dx)*(1 - dy)*dz, w2 = is_added?1:(1 - w1); (*this)(x,y,nz,c) = (T)(w1*value + w2*(*this)(x,y,nz,c)); } if (nx>=0 && nx<width()) { const float w1 = dx*(1 - dy)*dz, w2 = is_added?1:(1 - w1); (*this)(nx,y,nz,c) = (T)(w1*value + w2*(*this)(nx,y,nz,c)); } } if (ny>=0 && ny<height()) { if (x>=0 && x<width()) { const float w1 = (1 - dx)*dy*dz, w2 = is_added?1:(1 - w1); (*this)(x,ny,nz,c) = (T)(w1*value + w2*(*this)(x,ny,nz,c)); } if (nx>=0 && nx<width()) { const float w1 = dx*dy*dz, w2 = is_added?1:(1 - w1); (*this)(nx,ny,nz,c) = (T)(w1*value + w2*(*this)(nx,ny,nz,c)); } } } } return *this; } //! Return a C-string containing a list of all values of the image instance. /** Return a new \c CImg<char> image whose buffer data() is a \c char* string describing the list of all pixel values of the image instance (written in base 10), separated by specified \c separator character. \param separator A \c char character which specifies the separator between values in the returned C-string. \param max_size Maximum size of the returned image (or \c 0 if no limits are set). \param format For float/double-values, tell the printf format used to generate the Ascii representation of the numbers (or \c 0 for default representation). \note - The returned image is never empty. - For an empty image instance, the returned string is <tt>""</tt>. - If \c max_size is equal to \c 0, there are no limits on the size of the returned string. - Otherwise, if the maximum number of string characters is exceeded, the value string is cut off and terminated by character \c '\0'. In that case, the returned image size is <tt>max_size + 1</tt>. **/ CImg<charT> value_string(const char separator=',', const unsigned int max_size=0, const char *const format=0) const { if (is_empty() || max_size==1) return CImg<charT>(1,1,1,1,0); CImgList<charT> items; CImg<charT> s_item(256); *s_item = 0; const T *ptrs = _data; unsigned int string_size = 0; const char *const _format = format?format:cimg::type<T>::format(); for (ulongT off = 0, siz = size(); off<siz && (!max_size || string_size<max_size); ++off) { const unsigned int printed_size = 1U + cimg_snprintf(s_item,s_item._width,_format, cimg::type<T>::format(*(ptrs++))); CImg<charT> item(s_item._data,printed_size); item[printed_size - 1] = separator; item.move_to(items); if (max_size) string_size+=printed_size; } CImg<charT> res; (items>'x').move_to(res); if (max_size && res._width>=max_size) res.crop(0,max_size - 1); res.back() = 0; return res; } //@} //------------------------------------- // //! \name Instance Checking //@{ //------------------------------------- //! Test shared state of the pixel buffer. /** Return \c true if image instance has a shared memory buffer, and \c false otherwise. \note - A shared image do not own his pixel buffer data() and will not deallocate it on destruction. - Most of the time, a \c CImg<T> image instance will \e not be shared. - A shared image can only be obtained by a limited set of constructors and methods (see list below). **/ bool is_shared() const { return _is_shared; } //! Test if image instance is empty. /** Return \c true, if image instance is empty, i.e. does \e not contain any pixel values, has dimensions \c 0 x \c 0 x \c 0 x \c 0 and a pixel buffer pointer set to \c 0 (null pointer), and \c false otherwise. **/ bool is_empty() const { return !(_data && _width && _height && _depth && _spectrum); } //! Test if image instance contains a 'inf' value. /** Return \c true, if image instance contains a 'inf' value, and \c false otherwise. **/ bool is_inf() const { if (cimg::type<T>::is_float()) cimg_for(*this,p,T) if (cimg::type<T>::is_inf((float)*p)) return true; return false; } //! Test if image instance contains a NaN value. /** Return \c true, if image instance contains a NaN value, and \c false otherwise. **/ bool is_nan() const { if (cimg::type<T>::is_float()) cimg_for(*this,p,T) if (cimg::type<T>::is_nan((float)*p)) return true; return false; } //! Test if image width is equal to specified value. bool is_sameX(const unsigned int size_x) const { return _width==size_x; } //! Test if image width is equal to specified value. template<typename t> bool is_sameX(const CImg<t>& img) const { return is_sameX(img._width); } //! Test if image width is equal to specified value. bool is_sameX(const CImgDisplay& disp) const { return is_sameX(disp._width); } //! Test if image height is equal to specified value. bool is_sameY(const unsigned int size_y) const { return _height==size_y; } //! Test if image height is equal to specified value. template<typename t> bool is_sameY(const CImg<t>& img) const { return is_sameY(img._height); } //! Test if image height is equal to specified value. bool is_sameY(const CImgDisplay& disp) const { return is_sameY(disp._height); } //! Test if image depth is equal to specified value. bool is_sameZ(const unsigned int size_z) const { return _depth==size_z; } //! Test if image depth is equal to specified value. template<typename t> bool is_sameZ(const CImg<t>& img) const { return is_sameZ(img._depth); } //! Test if image spectrum is equal to specified value. bool is_sameC(const unsigned int size_c) const { return _spectrum==size_c; } //! Test if image spectrum is equal to specified value. template<typename t> bool is_sameC(const CImg<t>& img) const { return is_sameC(img._spectrum); } //! Test if image width and height are equal to specified values. /** Test if is_sameX(unsigned int) const and is_sameY(unsigned int) const are both verified. **/ bool is_sameXY(const unsigned int size_x, const unsigned int size_y) const { return _width==size_x && _height==size_y; } //! Test if image width and height are the same as that of another image. /** Test if is_sameX(const CImg<t>&) const and is_sameY(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameXY(const CImg<t>& img) const { return is_sameXY(img._width,img._height); } //! Test if image width and height are the same as that of an existing display window. /** Test if is_sameX(const CImgDisplay&) const and is_sameY(const CImgDisplay&) const are both verified. **/ bool is_sameXY(const CImgDisplay& disp) const { return is_sameXY(disp._width,disp._height); } //! Test if image width and depth are equal to specified values. /** Test if is_sameX(unsigned int) const and is_sameZ(unsigned int) const are both verified. **/ bool is_sameXZ(const unsigned int size_x, const unsigned int size_z) const { return _width==size_x && _depth==size_z; } //! Test if image width and depth are the same as that of another image. /** Test if is_sameX(const CImg<t>&) const and is_sameZ(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameXZ(const CImg<t>& img) const { return is_sameXZ(img._width,img._depth); } //! Test if image width and spectrum are equal to specified values. /** Test if is_sameX(unsigned int) const and is_sameC(unsigned int) const are both verified. **/ bool is_sameXC(const unsigned int size_x, const unsigned int size_c) const { return _width==size_x && _spectrum==size_c; } //! Test if image width and spectrum are the same as that of another image. /** Test if is_sameX(const CImg<t>&) const and is_sameC(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameXC(const CImg<t>& img) const { return is_sameXC(img._width,img._spectrum); } //! Test if image height and depth are equal to specified values. /** Test if is_sameY(unsigned int) const and is_sameZ(unsigned int) const are both verified. **/ bool is_sameYZ(const unsigned int size_y, const unsigned int size_z) const { return _height==size_y && _depth==size_z; } //! Test if image height and depth are the same as that of another image. /** Test if is_sameY(const CImg<t>&) const and is_sameZ(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameYZ(const CImg<t>& img) const { return is_sameYZ(img._height,img._depth); } //! Test if image height and spectrum are equal to specified values. /** Test if is_sameY(unsigned int) const and is_sameC(unsigned int) const are both verified. **/ bool is_sameYC(const unsigned int size_y, const unsigned int size_c) const { return _height==size_y && _spectrum==size_c; } //! Test if image height and spectrum are the same as that of another image. /** Test if is_sameY(const CImg<t>&) const and is_sameC(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameYC(const CImg<t>& img) const { return is_sameYC(img._height,img._spectrum); } //! Test if image depth and spectrum are equal to specified values. /** Test if is_sameZ(unsigned int) const and is_sameC(unsigned int) const are both verified. **/ bool is_sameZC(const unsigned int size_z, const unsigned int size_c) const { return _depth==size_z && _spectrum==size_c; } //! Test if image depth and spectrum are the same as that of another image. /** Test if is_sameZ(const CImg<t>&) const and is_sameC(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameZC(const CImg<t>& img) const { return is_sameZC(img._depth,img._spectrum); } //! Test if image width, height and depth are equal to specified values. /** Test if is_sameXY(unsigned int,unsigned int) const and is_sameZ(unsigned int) const are both verified. **/ bool is_sameXYZ(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z) const { return is_sameXY(size_x,size_y) && _depth==size_z; } //! Test if image width, height and depth are the same as that of another image. /** Test if is_sameXY(const CImg<t>&) const and is_sameZ(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameXYZ(const CImg<t>& img) const { return is_sameXYZ(img._width,img._height,img._depth); } //! Test if image width, height and spectrum are equal to specified values. /** Test if is_sameXY(unsigned int,unsigned int) const and is_sameC(unsigned int) const are both verified. **/ bool is_sameXYC(const unsigned int size_x, const unsigned int size_y, const unsigned int size_c) const { return is_sameXY(size_x,size_y) && _spectrum==size_c; } //! Test if image width, height and spectrum are the same as that of another image. /** Test if is_sameXY(const CImg<t>&) const and is_sameC(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameXYC(const CImg<t>& img) const { return is_sameXYC(img._width,img._height,img._spectrum); } //! Test if image width, depth and spectrum are equal to specified values. /** Test if is_sameXZ(unsigned int,unsigned int) const and is_sameC(unsigned int) const are both verified. **/ bool is_sameXZC(const unsigned int size_x, const unsigned int size_z, const unsigned int size_c) const { return is_sameXZ(size_x,size_z) && _spectrum==size_c; } //! Test if image width, depth and spectrum are the same as that of another image. /** Test if is_sameXZ(const CImg<t>&) const and is_sameC(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameXZC(const CImg<t>& img) const { return is_sameXZC(img._width,img._depth,img._spectrum); } //! Test if image height, depth and spectrum are equal to specified values. /** Test if is_sameYZ(unsigned int,unsigned int) const and is_sameC(unsigned int) const are both verified. **/ bool is_sameYZC(const unsigned int size_y, const unsigned int size_z, const unsigned int size_c) const { return is_sameYZ(size_y,size_z) && _spectrum==size_c; } //! Test if image height, depth and spectrum are the same as that of another image. /** Test if is_sameYZ(const CImg<t>&) const and is_sameC(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameYZC(const CImg<t>& img) const { return is_sameYZC(img._height,img._depth,img._spectrum); } //! Test if image width, height, depth and spectrum are equal to specified values. /** Test if is_sameXYZ(unsigned int,unsigned int,unsigned int) const and is_sameC(unsigned int) const are both verified. **/ bool is_sameXYZC(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c) const { return is_sameXYZ(size_x,size_y,size_z) && _spectrum==size_c; } //! Test if image width, height, depth and spectrum are the same as that of another image. /** Test if is_sameXYZ(const CImg<t>&) const and is_sameC(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameXYZC(const CImg<t>& img) const { return is_sameXYZC(img._width,img._height,img._depth,img._spectrum); } //! Test if specified coordinates are inside image bounds. /** Return \c true if pixel located at (\c x,\c y,\c z,\c c) is inside bounds of the image instance, and \c false otherwise. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note - Return \c true only if all these conditions are verified: - The image instance is \e not empty. - <tt>0<=x<=\ref width() - 1</tt>. - <tt>0<=y<=\ref height() - 1</tt>. - <tt>0<=z<=\ref depth() - 1</tt>. - <tt>0<=c<=\ref spectrum() - 1</tt>. **/ bool containsXYZC(const int x, const int y=0, const int z=0, const int c=0) const { return !is_empty() && x>=0 && x<width() && y>=0 && y<height() && z>=0 && z<depth() && c>=0 && c<spectrum(); } //! Test if pixel value is inside image bounds and get its X,Y,Z and C-coordinates. /** Return \c true, if specified reference refers to a pixel value inside bounds of the image instance, and \c false otherwise. \param pixel Reference to pixel value to test. \param[out] x X-coordinate of the pixel value, if test succeeds. \param[out] y Y-coordinate of the pixel value, if test succeeds. \param[out] z Z-coordinate of the pixel value, if test succeeds. \param[out] c C-coordinate of the pixel value, if test succeeds. \note - Useful to convert an offset to a buffer value into pixel value coordinates: \code const CImg<float> img(100,100,1,3); // Construct a 100x100 RGB color image const unsigned long offset = 1249; // Offset to the pixel (49,12,0,0) unsigned int x,y,z,c; if (img.contains(img[offset],x,y,z,c)) { // Convert offset to (x,y,z,c) coordinates std::printf("Offset %u refers to pixel located at (%u,%u,%u,%u).\n", offset,x,y,z,c); } \endcode **/ template<typename t> bool contains(const T& pixel, t& x, t& y, t& z, t& c) const { const ulongT wh = (ulongT)_width*_height, whd = wh*_depth, siz = whd*_spectrum; const T *const ppixel = &pixel; if (is_empty() || ppixel<_data || ppixel>=_data + siz) return false; ulongT off = (ulongT)(ppixel - _data); const ulongT nc = off/whd; off%=whd; const ulongT nz = off/wh; off%=wh; const ulongT ny = off/_width, nx = off%_width; x = (t)nx; y = (t)ny; z = (t)nz; c = (t)nc; return true; } //! Test if pixel value is inside image bounds and get its X,Y and Z-coordinates. /** Similar to contains(const T&,t&,t&,t&,t&) const, except that only the X,Y and Z-coordinates are set. **/ template<typename t> bool contains(const T& pixel, t& x, t& y, t& z) const { const ulongT wh = (ulongT)_width*_height, whd = wh*_depth, siz = whd*_spectrum; const T *const ppixel = &pixel; if (is_empty() || ppixel<_data || ppixel>=_data + siz) return false; ulongT off = ((ulongT)(ppixel - _data))%whd; const ulongT nz = off/wh; off%=wh; const ulongT ny = off/_width, nx = off%_width; x = (t)nx; y = (t)ny; z = (t)nz; return true; } //! Test if pixel value is inside image bounds and get its X and Y-coordinates. /** Similar to contains(const T&,t&,t&,t&,t&) const, except that only the X and Y-coordinates are set. **/ template<typename t> bool contains(const T& pixel, t& x, t& y) const { const ulongT wh = (ulongT)_width*_height, siz = wh*_depth*_spectrum; const T *const ppixel = &pixel; if (is_empty() || ppixel<_data || ppixel>=_data + siz) return false; ulongT off = ((unsigned int)(ppixel - _data))%wh; const ulongT ny = off/_width, nx = off%_width; x = (t)nx; y = (t)ny; return true; } //! Test if pixel value is inside image bounds and get its X-coordinate. /** Similar to contains(const T&,t&,t&,t&,t&) const, except that only the X-coordinate is set. **/ template<typename t> bool contains(const T& pixel, t& x) const { const T *const ppixel = &pixel; if (is_empty() || ppixel<_data || ppixel>=_data + size()) return false; x = (t)(((ulongT)(ppixel - _data))%_width); return true; } //! Test if pixel value is inside image bounds. /** Similar to contains(const T&,t&,t&,t&,t&) const, except that no pixel coordinates are set. **/ bool contains(const T& pixel) const { const T *const ppixel = &pixel; return !is_empty() && ppixel>=_data && ppixel<_data + size(); } //! Test if pixel buffers of instance and input images overlap. /** Return \c true, if pixel buffers attached to image instance and input image \c img overlap, and \c false otherwise. \param img Input image to compare with. \note - Buffer overlapping may happen when manipulating \e shared images. - If two image buffers overlap, operating on one of the image will probably modify the other one. - Most of the time, \c CImg<T> instances are \e non-shared and do not overlap between each others. \par Example \code const CImg<float> img1("reference.jpg"), // Load RGB-color image img2 = img1.get_shared_channel(1); // Get shared version of the green channel if (img1.is_overlapped(img2)) { // Test succeeds, 'img1' and 'img2' overlaps std::printf("Buffers overlap!\n"); } \endcode **/ template<typename t> bool is_overlapped(const CImg<t>& img) const { const ulongT csiz = size(), isiz = img.size(); return !((void*)(_data + csiz)<=(void*)img._data || (void*)_data>=(void*)(img._data + isiz)); } //! Test if the set {\c *this,\c primitives,\c colors,\c opacities} defines a valid 3D object. /** Return \c true is the 3D object represented by the set {\c *this,\c primitives,\c colors,\c opacities} defines a valid 3D object, and \c false otherwise. The vertex coordinates are defined by the instance image. \param primitives List of primitives of the 3D object. \param colors List of colors of the 3D object. \param opacities List (or image) of opacities of the 3D object. \param full_check Tells if full checking of the 3D object must be performed. \param[out] error_message C-string to contain the error message, if the test does not succeed. \note - Set \c full_checking to \c false to speed-up the 3D object checking. In this case, only the size of each 3D object component is checked. - Size of the string \c error_message should be at least 128-bytes long, to be able to contain the error message. **/ template<typename tp, typename tc, typename to> bool is_object3d(const CImgList<tp>& primitives, const CImgList<tc>& colors, const to& opacities, const bool full_check=true, char *const error_message=0) const { if (error_message) *error_message = 0; // Check consistency for the particular case of an empty 3D object. if (is_empty()) { if (primitives || colors || opacities) { if (error_message) cimg_sprintf(error_message, "3D object (%u,%u) defines no vertices but %u primitives, " "%u colors and %lu opacities", _width,primitives._width,primitives._width, colors._width,(unsigned long)opacities.size()); return false; } return true; } // Check consistency of vertices. if (_height!=3 || _depth>1 || _spectrum>1) { // Check vertices dimensions if (error_message) cimg_sprintf(error_message, "3D object (%u,%u) has invalid vertex dimensions (%u,%u,%u,%u)", _width,primitives._width,_width,_height,_depth,_spectrum); return false; } if (colors._width>primitives._width + 1) { if (error_message) cimg_sprintf(error_message, "3D object (%u,%u) defines %u colors", _width,primitives._width,colors._width); return false; } if (opacities.size()>primitives._width) { if (error_message) cimg_sprintf(error_message, "3D object (%u,%u) defines %lu opacities", _width,primitives._width,(unsigned long)opacities.size()); return false; } if (!full_check) return true; // Check consistency of primitives. cimglist_for(primitives,l) { const CImg<tp>& primitive = primitives[l]; const unsigned int psiz = (unsigned int)primitive.size(); switch (psiz) { case 1 : { // Point const unsigned int i0 = (unsigned int)primitive(0); if (i0>=_width) { if (error_message) cimg_sprintf(error_message, "3D object (%u,%u) refers to invalid vertex index %u in " "point primitive [%u]", _width,primitives._width,i0,l); return false; } } break; case 5 : { // Sphere const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1); if (i0>=_width || i1>=_width) { if (error_message) cimg_sprintf(error_message, "3D object (%u,%u) refers to invalid vertex indices (%u,%u) in " "sphere primitive [%u]", _width,primitives._width,i0,i1,l); return false; } } break; case 2 : case 6 : { // Segment const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1); if (i0>=_width || i1>=_width) { if (error_message) cimg_sprintf(error_message, "3D object (%u,%u) refers to invalid vertex indices (%u,%u) in " "segment primitive [%u]", _width,primitives._width,i0,i1,l); return false; } } break; case 3 : case 9 : { // Triangle const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1), i2 = (unsigned int)primitive(2); if (i0>=_width || i1>=_width || i2>=_width) { if (error_message) cimg_sprintf(error_message, "3D object (%u,%u) refers to invalid vertex indices (%u,%u,%u) in " "triangle primitive [%u]", _width,primitives._width,i0,i1,i2,l); return false; } } break; case 4 : case 12 : { // Quadrangle const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1), i2 = (unsigned int)primitive(2), i3 = (unsigned int)primitive(3); if (i0>=_width || i1>=_width || i2>=_width || i3>=_width) { if (error_message) cimg_sprintf(error_message, "3D object (%u,%u) refers to invalid vertex indices (%u,%u,%u,%u) in " "quadrangle primitive [%u]", _width,primitives._width,i0,i1,i2,i3,l); return false; } } break; default : if (error_message) cimg_sprintf(error_message, "3D object (%u,%u) defines an invalid primitive [%u] of size %u", _width,primitives._width,l,(unsigned int)psiz); return false; } } // Check consistency of colors. cimglist_for(colors,c) { const CImg<tc>& color = colors[c]; if (!color) { if (error_message) cimg_sprintf(error_message, "3D object (%u,%u) defines no color for primitive [%u]", _width,primitives._width,c); return false; } } // Check consistency of light texture. if (colors._width>primitives._width) { const CImg<tc> &light = colors.back(); if (!light || light._depth>1) { if (error_message) cimg_sprintf(error_message, "3D object (%u,%u) defines an invalid light texture (%u,%u,%u,%u)", _width,primitives._width,light._width, light._height,light._depth,light._spectrum); return false; } } return true; } //! Test if image instance represents a valid serialization of a 3D object. /** Return \c true if the image instance represents a valid serialization of a 3D object, and \c false otherwise. \param full_check Tells if full checking of the instance must be performed. \param[out] error_message C-string to contain the error message, if the test does not succeed. \note - Set \c full_check to \c false to speed-up the 3D object checking. In this case, only the size of each 3D object component is checked. - Size of the string \c error_message should be at least 128-bytes long, to be able to contain the error message. **/ bool is_CImg3d(const bool full_check=true, char *const error_message=0) const { if (error_message) *error_message = 0; // Check instance dimension and header. if (_width!=1 || _height<8 || _depth!=1 || _spectrum!=1) { if (error_message) cimg_sprintf(error_message, "CImg3d has invalid dimensions (%u,%u,%u,%u)", _width,_height,_depth,_spectrum); return false; } const T *ptrs = _data, *const ptre = end(); if (!_is_CImg3d(*(ptrs++),'C') || !_is_CImg3d(*(ptrs++),'I') || !_is_CImg3d(*(ptrs++),'m') || !_is_CImg3d(*(ptrs++),'g') || !_is_CImg3d(*(ptrs++),'3') || !_is_CImg3d(*(ptrs++),'d')) { if (error_message) cimg_sprintf(error_message, "CImg3d header not found"); return false; } const unsigned int nb_points = cimg::float2uint((float)*(ptrs++)), nb_primitives = cimg::float2uint((float)*(ptrs++)); // Check consistency of number of vertices / primitives. if (!full_check) { const ulongT minimal_size = 8UL + 3*nb_points + 6*nb_primitives; if (_data + minimal_size>ptre) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) has only %lu values, while at least %lu values were expected", nb_points,nb_primitives,(unsigned long)size(),(unsigned long)minimal_size); return false; } } // Check consistency of vertex data. if (!nb_points) { if (nb_primitives) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) defines no vertices but %u primitives", nb_points,nb_primitives,nb_primitives); return false; } if (ptrs!=ptre) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) is an empty object but contains %u value%s " "more than expected", nb_points,nb_primitives,(unsigned int)(ptre - ptrs),(ptre - ptrs)>1?"s":""); return false; } return true; } if (ptrs + 3*nb_points>ptre) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) defines only %u vertices data", nb_points,nb_primitives,(unsigned int)(ptre - ptrs)/3); return false; } ptrs+=3*nb_points; // Check consistency of primitive data. if (ptrs==ptre) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) defines %u vertices but no primitive", nb_points,nb_primitives,nb_points); return false; } if (!full_check) return true; for (unsigned int p = 0; p<nb_primitives; ++p) { const unsigned int nb_inds = (unsigned int)*(ptrs++); switch (nb_inds) { case 1 : { // Point const unsigned int i0 = cimg::float2uint((float)*(ptrs++)); if (i0>=nb_points) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) refers to invalid vertex index %u in point primitive [%u]", nb_points,nb_primitives,i0,p); return false; } } break; case 5 : { // Sphere const unsigned int i0 = cimg::float2uint((float)*(ptrs++)), i1 = cimg::float2uint((float)*(ptrs++)); ptrs+=3; if (i0>=nb_points || i1>=nb_points) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) refers to invalid vertex indices (%u,%u) in " "sphere primitive [%u]", nb_points,nb_primitives,i0,i1,p); return false; } } break; case 2 : case 6 : { // Segment const unsigned int i0 = cimg::float2uint((float)*(ptrs++)), i1 = cimg::float2uint((float)*(ptrs++)); if (nb_inds==6) ptrs+=4; if (i0>=nb_points || i1>=nb_points) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) refers to invalid vertex indices (%u,%u) in " "segment primitive [%u]", nb_points,nb_primitives,i0,i1,p); return false; } } break; case 3 : case 9 : { // Triangle const unsigned int i0 = cimg::float2uint((float)*(ptrs++)), i1 = cimg::float2uint((float)*(ptrs++)), i2 = cimg::float2uint((float)*(ptrs++)); if (nb_inds==9) ptrs+=6; if (i0>=nb_points || i1>=nb_points || i2>=nb_points) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) refers to invalid vertex indices (%u,%u,%u) in " "triangle primitive [%u]", nb_points,nb_primitives,i0,i1,i2,p); return false; } } break; case 4 : case 12 : { // Quadrangle const unsigned int i0 = cimg::float2uint((float)*(ptrs++)), i1 = cimg::float2uint((float)*(ptrs++)), i2 = cimg::float2uint((float)*(ptrs++)), i3 = cimg::float2uint((float)*(ptrs++)); if (nb_inds==12) ptrs+=8; if (i0>=nb_points || i1>=nb_points || i2>=nb_points || i3>=nb_points) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) refers to invalid vertex indices (%u,%u,%u,%u) in " "quadrangle primitive [%u]", nb_points,nb_primitives,i0,i1,i2,i3,p); return false; } } break; default : if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) defines an invalid primitive [%u] of size %u", nb_points,nb_primitives,p,nb_inds); return false; } if (ptrs>ptre) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) has incomplete primitive data for primitive [%u], " "%u values missing", nb_points,nb_primitives,p,(unsigned int)(ptrs - ptre)); return false; } } // Check consistency of color data. if (ptrs==ptre) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) defines no color/texture data", nb_points,nb_primitives); return false; } for (unsigned int c = 0; c<nb_primitives; ++c) { if (*(ptrs++)!=(T)-128) ptrs+=2; else if ((ptrs+=3)<ptre) { const unsigned int w = (unsigned int)*(ptrs - 3), h = (unsigned int)*(ptrs - 2), s = (unsigned int)*(ptrs - 1); if (!h && !s) { if (w>=c) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) refers to invalid shared sprite/texture index %u " "for primitive [%u]", nb_points,nb_primitives,w,c); return false; } } else ptrs+=w*h*s; } if (ptrs>ptre) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) has incomplete color/texture data for primitive [%u], " "%u values missing", nb_points,nb_primitives,c,(unsigned int)(ptrs - ptre)); return false; } } // Check consistency of opacity data. if (ptrs==ptre) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) defines no opacity data", nb_points,nb_primitives); return false; } for (unsigned int o = 0; o<nb_primitives; ++o) { if (*(ptrs++)==(T)-128 && (ptrs+=3)<ptre) { const unsigned int w = (unsigned int)*(ptrs - 3), h = (unsigned int)*(ptrs - 2), s = (unsigned int)*(ptrs - 1); if (!h && !s) { if (w>=o) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) refers to invalid shared opacity index %u " "for primitive [%u]", nb_points,nb_primitives,w,o); return false; } } else ptrs+=w*h*s; } if (ptrs>ptre) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) has incomplete opacity data for primitive [%u]", nb_points,nb_primitives,o); return false; } } // Check end of data. if (ptrs<ptre) { if (error_message) cimg_sprintf(error_message, "CImg3d (%u,%u) contains %u value%s more than expected", nb_points,nb_primitives,(unsigned int)(ptre - ptrs),(ptre - ptrs)>1?"s":""); return false; } return true; } static bool _is_CImg3d(const T val, const char c) { return val>=(T)c && val<(T)(c + 1); } //@} //------------------------------------- // //! \name Mathematical Functions //@{ //------------------------------------- // Define the math formula parser/compiler and expression evaluator. struct _cimg_math_parser { CImg<doubleT> mem; CImg<intT> memtype; CImgList<ulongT> _code, &code, code_begin, code_end; CImg<ulongT> opcode; const CImg<ulongT> *p_code_end, *p_code; const CImg<ulongT> *const p_break; CImg<charT> expr, pexpr; const CImg<T>& imgin; const CImgList<T>& listin; CImg<T> &imgout; CImgList<T>& listout; CImg<doubleT> _img_stats, &img_stats, constcache_vals; CImgList<doubleT> _list_stats, &list_stats, _list_median, &list_median; CImg<uintT> mem_img_stats, constcache_inds; CImg<uintT> level, variable_pos, reserved_label; CImgList<charT> variable_def, macro_def, macro_body; CImgList<boolT> macro_body_is_string; char *user_macro; unsigned int mempos, mem_img_median, debug_indent, result_dim, break_type, constcache_size; bool is_parallelizable, is_fill, need_input_copy; double *result; ulongT rng; const char *const calling_function, *s_op, *ss_op; typedef double (*mp_func)(_cimg_math_parser&); #define _cimg_mp_is_constant(arg) (memtype[arg]==1) // Is constant value? #define _cimg_mp_is_scalar(arg) (memtype[arg]<2) // Is scalar value? #define _cimg_mp_is_comp(arg) (!memtype[arg]) // Is computation value? #define _cimg_mp_is_variable(arg) (memtype[arg]==-1) // Is scalar variable? #define _cimg_mp_is_vector(arg) (memtype[arg]>1) // Is vector? #define _cimg_mp_size(arg) (_cimg_mp_is_scalar(arg)?0U:(unsigned int)memtype[arg] - 1) // Size (0=scalar, N>0=vectorN) #define _cimg_mp_calling_function calling_function_s()._data #define _cimg_mp_op(s) s_op = s; ss_op = ss #define _cimg_mp_check_type(arg,n_arg,mode,N) check_type(arg,n_arg,mode,N,ss,se,saved_char) #define _cimg_mp_check_constant(arg,n_arg,mode) check_constant(arg,n_arg,mode,ss,se,saved_char) #define _cimg_mp_check_matrix_square(arg,n_arg) check_matrix_square(arg,n_arg,ss,se,saved_char) #define _cimg_mp_check_list(is_out) check_list(is_out,ss,se,saved_char) #define _cimg_mp_defunc(mp) (*(mp_func)(*(mp).opcode))(mp) #define _cimg_mp_return(x) { *se = saved_char; s_op = previous_s_op; ss_op = previous_ss_op; return x; } #define _cimg_mp_return_nan() _cimg_mp_return(_cimg_mp_slot_nan) #define _cimg_mp_constant(val) _cimg_mp_return(constant((double)(val))) #define _cimg_mp_scalar0(op) _cimg_mp_return(scalar0(op)) #define _cimg_mp_scalar1(op,i1) _cimg_mp_return(scalar1(op,i1)) #define _cimg_mp_scalar2(op,i1,i2) _cimg_mp_return(scalar2(op,i1,i2)) #define _cimg_mp_scalar3(op,i1,i2,i3) _cimg_mp_return(scalar3(op,i1,i2,i3)) #define _cimg_mp_scalar4(op,i1,i2,i3,i4) _cimg_mp_return(scalar4(op,i1,i2,i3,i4)) #define _cimg_mp_scalar5(op,i1,i2,i3,i4,i5) _cimg_mp_return(scalar5(op,i1,i2,i3,i4,i5)) #define _cimg_mp_scalar6(op,i1,i2,i3,i4,i5,i6) _cimg_mp_return(scalar6(op,i1,i2,i3,i4,i5,i6)) #define _cimg_mp_scalar7(op,i1,i2,i3,i4,i5,i6,i7) _cimg_mp_return(scalar7(op,i1,i2,i3,i4,i5,i6,i7)) #define _cimg_mp_vector1_v(op,i1) _cimg_mp_return(vector1_v(op,i1)) #define _cimg_mp_vector2_sv(op,i1,i2) _cimg_mp_return(vector2_sv(op,i1,i2)) #define _cimg_mp_vector2_vs(op,i1,i2) _cimg_mp_return(vector2_vs(op,i1,i2)) #define _cimg_mp_vector2_vv(op,i1,i2) _cimg_mp_return(vector2_vv(op,i1,i2)) #define _cimg_mp_vector3_vss(op,i1,i2,i3) _cimg_mp_return(vector3_vss(op,i1,i2,i3)) // Constructors / Destructors. ~_cimg_math_parser() { cimg::srand(rng); } _cimg_math_parser(const char *const expression, const char *const funcname=0, const CImg<T>& img_input=CImg<T>::const_empty(), CImg<T> *const img_output=0, const CImgList<T> *const list_inputs=0, CImgList<T> *const list_outputs=0, const bool _is_fill=false): code(_code),p_break((CImg<ulongT>*)(cimg_ulong)-2), imgin(img_input),listin(list_inputs?*list_inputs:CImgList<T>::const_empty()), imgout(img_output?*img_output:CImg<T>::empty()),listout(list_outputs?*list_outputs:CImgList<T>::empty()), img_stats(_img_stats),list_stats(_list_stats),list_median(_list_median),user_macro(0), mem_img_median(~0U),debug_indent(0),result_dim(0),break_type(0),constcache_size(0), is_parallelizable(true),is_fill(_is_fill),need_input_copy(false), rng((cimg::_rand(),cimg::rng())),calling_function(funcname?funcname:"cimg_math_parser") { #if cimg_use_openmp!=0 rng+=omp_get_thread_num(); #endif if (!expression || !*expression) throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: Empty expression.", pixel_type(),_cimg_mp_calling_function); const char *_expression = expression; while (*_expression && (cimg::is_blank(*_expression) || *_expression==';')) ++_expression; CImg<charT>::string(_expression).move_to(expr); char *ps = &expr.back() - 1; while (ps>expr._data && (cimg::is_blank(*ps) || *ps==';')) --ps; *(++ps) = 0; expr._width = (unsigned int)(ps - expr._data + 1); // Ease the retrieval of previous non-space characters afterwards. pexpr.assign(expr._width); char c, *pe = pexpr._data; for (ps = expr._data, c = ' '; *ps; ++ps) { if (!cimg::is_blank(*ps)) c = *ps; else *ps = ' '; *(pe++) = c; } *pe = 0; level = get_level(expr); // Init constant values. #define _cimg_mp_interpolation (reserved_label[29]!=~0U?reserved_label[29]:0) #define _cimg_mp_boundary (reserved_label[30]!=~0U?reserved_label[30]:0) #define _cimg_mp_slot_nan 29 #define _cimg_mp_slot_x 30 #define _cimg_mp_slot_y 31 #define _cimg_mp_slot_z 32 #define _cimg_mp_slot_c 33 mem.assign(96); for (unsigned int i = 0; i<=10; ++i) mem[i] = (double)i; // mem[0-10] = 0...10 for (unsigned int i = 1; i<=5; ++i) mem[i + 10] = -(double)i; // mem[11-15] = -1...-5 mem[16] = 0.5; mem[17] = 0; // thread_id mem[18] = (double)imgin._width; // w mem[19] = (double)imgin._height; // h mem[20] = (double)imgin._depth; // d mem[21] = (double)imgin._spectrum; // s mem[22] = (double)imgin._is_shared; // r mem[23] = (double)imgin._width*imgin._height; // wh mem[24] = (double)imgin._width*imgin._height*imgin._depth; // whd mem[25] = (double)imgin._width*imgin._height*imgin._depth*imgin._spectrum; // whds mem[26] = (double)listin._width; // l mem[27] = std::exp(1.); // e mem[28] = cimg::PI; // pi mem[_cimg_mp_slot_nan] = cimg::type<double>::nan(); // nan // Set value property : // { -2 = other | -1 = variable | 0 = computation value | // 1 = compile-time constant | N>1 = constant ptr to vector[N-1] }. memtype.assign(mem._width,1,1,1,0); for (unsigned int i = 0; i<_cimg_mp_slot_x; ++i) memtype[i] = 1; memtype[17] = 0; memtype[_cimg_mp_slot_x] = memtype[_cimg_mp_slot_y] = memtype[_cimg_mp_slot_z] = memtype[_cimg_mp_slot_c] = -2; mempos = _cimg_mp_slot_c + 1; variable_pos.assign(8); reserved_label.assign(128,1,1,1,~0U); // reserved_label[4-28] are used to store these two-char variables: // [0] = wh, [1] = whd, [2] = whds, [3] = pi, [4] = im, [5] = iM, [6] = ia, [7] = iv, // [8] = is, [9] = ip, [10] = ic, [11] = xm, [12] = ym, [13] = zm, [14] = cm, [15] = xM, // [16] = yM, [17] = zM, [18]=cM, [19]=i0...[28]=i9, [29] = interpolation, [30] = boundary // Compile expression into a serie of opcodes. s_op = ""; ss_op = expr._data; const unsigned int ind_result = compile(expr._data,expr._data + expr._width - 1,0,0,false); if (!_cimg_mp_is_constant(ind_result)) { if (_cimg_mp_is_vector(ind_result)) CImg<doubleT>(&mem[ind_result] + 1,_cimg_mp_size(ind_result),1,1,1,true). fill(cimg::type<double>::nan()); else mem[ind_result] = cimg::type<double>::nan(); } // Free resources used for compiling expression and prepare evaluation. result_dim = _cimg_mp_size(ind_result); if (mem._width>=256 && mem._width - mempos>=mem._width/2) mem.resize(mempos,1,1,1,-1); result = mem._data + ind_result; memtype.assign(); constcache_vals.assign(); constcache_inds.assign(); level.assign(); variable_pos.assign(); reserved_label.assign(); expr.assign(); pexpr.assign(); opcode.assign(); opcode._is_shared = true; // Execute begin() bloc if any specified. if (code_begin) { mem[_cimg_mp_slot_x] = mem[_cimg_mp_slot_y] = mem[_cimg_mp_slot_z] = mem[_cimg_mp_slot_c] = 0; p_code_end = code_begin.end(); for (p_code = code_begin; p_code<p_code_end; ++p_code) { opcode._data = p_code->_data; const ulongT target = opcode[1]; mem[target] = _cimg_mp_defunc(*this); } } p_code_end = code.end(); } _cimg_math_parser(): code(_code),p_code_end(0),p_break((CImg<ulongT>*)(cimg_ulong)-2), imgin(CImg<T>::const_empty()),listin(CImgList<T>::const_empty()), imgout(CImg<T>::empty()),listout(CImgList<T>::empty()), img_stats(_img_stats),list_stats(_list_stats),list_median(_list_median),debug_indent(0), result_dim(0),break_type(0),constcache_size(0),is_parallelizable(true),is_fill(false),need_input_copy(false), rng(0),calling_function(0) { mem.assign(1 + _cimg_mp_slot_c,1,1,1,0); // Allow to skip 'is_empty?' test in operator()() result = mem._data; } _cimg_math_parser(const _cimg_math_parser& mp): mem(mp.mem),code(mp.code),p_code_end(mp.p_code_end),p_break(mp.p_break), imgin(mp.imgin),listin(mp.listin),imgout(mp.imgout),listout(mp.listout),img_stats(mp.img_stats), list_stats(mp.list_stats),list_median(mp.list_median),debug_indent(0),result_dim(mp.result_dim), break_type(0),constcache_size(0),is_parallelizable(mp.is_parallelizable),is_fill(mp.is_fill), need_input_copy(mp.need_input_copy), result(mem._data + (mp.result - mp.mem._data)), rng((cimg::_rand(),cimg::rng())),calling_function(0) { #if cimg_use_openmp!=0 mem[17] = omp_get_thread_num(); rng+=omp_get_thread_num(); #endif opcode.assign(); opcode._is_shared = true; } // Count parentheses/brackets level of each character of the expression. CImg<uintT> get_level(CImg<charT>& _expr) const { bool is_escaped = false, next_is_escaped = false; unsigned int mode = 0, next_mode = 0; // { 0=normal | 1=char-string | 2=vector-string CImg<uintT> res(_expr._width - 1); unsigned int *pd = res._data; int _level = 0; for (const char *ps = _expr._data; *ps && _level>=0; ++ps) { if (!is_escaped && !next_is_escaped && *ps=='\\') next_is_escaped = true; if (!is_escaped && *ps=='\'') { // Non-escaped character if (!mode && ps>_expr._data && *(ps - 1)=='[') next_mode = mode = 2; // Start vector-string else if (mode==2 && *(ps + 1)==']') next_mode = !mode; // End vector-string else if (mode<2) next_mode = mode?(mode = 0):1; // Start/end char-string } *(pd++) = (unsigned int)(mode>=1 || is_escaped?_level + (mode==1): *ps=='(' || *ps=='['?_level++: *ps==')' || *ps==']'?--_level: _level); mode = next_mode; is_escaped = next_is_escaped; next_is_escaped = false; } if (mode) { cimg::strellipsize(_expr,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: Unterminated string literal, in expression '%s'.", pixel_type(),_cimg_mp_calling_function, _expr._data); } if (_level) { cimg::strellipsize(_expr,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: Unbalanced parentheses/brackets, in expression '%s'.", pixel_type(),_cimg_mp_calling_function, _expr._data); } return res; } // Tell for each character of an expression if it is inside a string or not. CImg<boolT> is_inside_string(CImg<charT>& _expr) const { bool is_escaped = false, next_is_escaped = false; unsigned int mode = 0, next_mode = 0; // { 0=normal | 1=char-string | 2=vector-string CImg<boolT> res = CImg<charT>::string(_expr); bool *pd = res._data; for (const char *ps = _expr._data; *ps; ++ps) { if (!next_is_escaped && *ps=='\\') next_is_escaped = true; if (!is_escaped && *ps=='\'') { // Non-escaped character if (!mode && ps>_expr._data && *(ps - 1)=='[') next_mode = mode = 2; // Start vector-string else if (mode==2 && *(ps + 1)==']') next_mode = !mode; // End vector-string else if (mode<2) next_mode = mode?(mode = 0):1; // Start/end char-string } *(pd++) = mode>=1 || is_escaped; mode = next_mode; is_escaped = next_is_escaped; next_is_escaped = false; } return res; } // Compilation procedure. unsigned int compile(char *ss, char *se, const unsigned int depth, unsigned int *const p_ref, const bool is_single) { if (depth>256) { cimg::strellipsize(expr,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: Call stack overflow (infinite recursion?), " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function, (ss - 4)>expr._data?"...":"", (ss - 4)>expr._data?ss - 4:expr._data, se<&expr.back()?"...":""); } char c1, c2, c3, c4; // Simplify expression when possible. do { c2 = 0; if (ss<se) { while (*ss && (cimg::is_blank(*ss) || *ss==';')) ++ss; while (se>ss && (cimg::is_blank(c1 = *(se - 1)) || c1==';')) --se; } while (*ss=='(' && *(se - 1)==')' && std::strchr(ss,')')==se - 1) { ++ss; --se; c2 = 1; } } while (c2 && ss<se); if (se<=ss || !*ss) { cimg::strellipsize(expr,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s%s Missing %s, in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op,*s_op?":":"", *s_op=='F'?"argument":"item", (ss_op - 4)>expr._data?"...":"", (ss_op - 4)>expr._data?ss_op - 4:expr._data, ss_op + std::strlen(ss_op)<&expr.back()?"...":""); } const char *const previous_s_op = s_op, *const previous_ss_op = ss_op; const unsigned int depth1 = depth + 1; unsigned int pos, p1, p2, p3, arg1, arg2, arg3, arg4, arg5, arg6; char *const se1 = se - 1, *const se2 = se - 2, *const se3 = se - 3, *const ss1 = ss + 1, *const ss2 = ss + 2, *const ss3 = ss + 3, *const ss4 = ss + 4, *const ss5 = ss + 5, *const ss6 = ss + 6, *const ss7 = ss + 7, *const ss8 = ss + 8, *s, *ps, *ns, *s0, *s1, *s2, *s3, sep = 0, end = 0; double val = 0, val1, val2; mp_func op; // 'p_ref' is a 'unsigned int[7]' used to return a reference to an image or vector value // linked to the returned memory slot (reference that cannot be determined at compile time). // p_ref[0] can be { 0 = scalar (unlinked) | 1 = vector value | 2 = image value (offset) | // 3 = image value (coordinates) | 4 = image value as a vector (offsets) | // 5 = image value as a vector (coordinates) }. // Depending on p_ref[0], the remaining p_ref[k] have the following meaning: // When p_ref[0]==0, p_ref is actually unlinked. // When p_ref[0]==1, p_ref = [ 1, vector_ind, offset ]. // When p_ref[0]==2, p_ref = [ 2, image_ind (or ~0U), is_relative, offset ]. // When p_ref[0]==3, p_ref = [ 3, image_ind (or ~0U), is_relative, x, y, z, c ]. // When p_ref[0]==4, p_ref = [ 4, image_ind (or ~0U), is_relative, offset ]. // When p_ref[0]==5, p_ref = [ 5, image_ind (or ~0U), is_relative, x, y, z ]. if (p_ref) { *p_ref = 0; p_ref[1] = p_ref[2] = p_ref[3] = p_ref[4] = p_ref[5] = p_ref[6] = ~0U; } const char saved_char = *se; *se = 0; const unsigned int clevel = level[ss - expr._data], clevel1 = clevel + 1; bool is_sth, is_relative; CImg<uintT> ref; CImg<charT> variable_name; CImgList<ulongT> l_opcode; // Look for a single value or a pre-defined variable. int nb = 0; s = ss + (*ss=='+' || *ss=='-'?1:0); if (*s=='i' || *s=='I' || *s=='n' || *s=='N') { // Particular cases : +/-NaN and +/-Inf is_sth = *ss=='-'; if (!cimg::strcasecmp(s,"inf")) { val = cimg::type<double>::inf(); nb = 1; } else if (!cimg::strcasecmp(s,"nan")) { val = cimg::type<double>::nan(); nb = 1; } if (nb==1 && is_sth) val = -val; } else if (*s=='0' && (s[1]=='x' || s[1]=='X')) { // Hexadecimal number is_sth = *ss=='-'; if (cimg_sscanf(s + 2,"%x%c",&arg1,&sep)==1) { nb = 1; val = (double)arg1; if (is_sth) val = -val; } } if (!nb) nb = cimg_sscanf(ss,"%lf%c%c",&val,&(sep=0),&(end=0)); if (nb==1) _cimg_mp_constant(val); if (nb==2 && sep=='%') _cimg_mp_constant(val/100); if (ss1==se) switch (*ss) { // One-char reserved variable case 'c' : _cimg_mp_return(reserved_label[(int)'c']!=~0U?reserved_label[(int)'c']:_cimg_mp_slot_c); case 'd' : _cimg_mp_return(reserved_label[(int)'d']!=~0U?reserved_label[(int)'d']:20); case 'e' : _cimg_mp_return(reserved_label[(int)'e']!=~0U?reserved_label[(int)'e']:27); case 'h' : _cimg_mp_return(reserved_label[(int)'h']!=~0U?reserved_label[(int)'h']:19); case 'l' : _cimg_mp_return(reserved_label[(int)'l']!=~0U?reserved_label[(int)'l']:26); case 'r' : _cimg_mp_return(reserved_label[(int)'r']!=~0U?reserved_label[(int)'r']:22); case 's' : _cimg_mp_return(reserved_label[(int)'s']!=~0U?reserved_label[(int)'s']:21); case 't' : _cimg_mp_return(reserved_label[(int)'t']!=~0U?reserved_label[(int)'t']:17); case 'w' : _cimg_mp_return(reserved_label[(int)'w']!=~0U?reserved_label[(int)'w']:18); case 'x' : _cimg_mp_return(reserved_label[(int)'x']!=~0U?reserved_label[(int)'x']:_cimg_mp_slot_x); case 'y' : _cimg_mp_return(reserved_label[(int)'y']!=~0U?reserved_label[(int)'y']:_cimg_mp_slot_y); case 'z' : _cimg_mp_return(reserved_label[(int)'z']!=~0U?reserved_label[(int)'z']:_cimg_mp_slot_z); case 'u' : if (reserved_label[(int)'u']!=~0U) _cimg_mp_return(reserved_label[(int)'u']); _cimg_mp_scalar2(mp_u,0,1); case 'g' : if (reserved_label[(int)'g']!=~0U) _cimg_mp_return(reserved_label[(int)'g']); _cimg_mp_scalar0(mp_g); case 'i' : if (reserved_label[(int)'i']!=~0U) _cimg_mp_return(reserved_label[(int)'i']); _cimg_mp_scalar0(mp_i); case 'I' : _cimg_mp_op("Variable 'I'"); if (reserved_label[(int)'I']!=~0U) _cimg_mp_return(reserved_label[(int)'I']); if (!imgin._spectrum) _cimg_mp_return(0); need_input_copy = true; pos = vector(imgin._spectrum); CImg<ulongT>::vector((ulongT)mp_Joff,pos,0,0,imgin._spectrum).move_to(code); _cimg_mp_return(pos); case 'R' : if (reserved_label[(int)'R']!=~0U) _cimg_mp_return(reserved_label[(int)'R']); need_input_copy = true; _cimg_mp_scalar6(mp_ixyzc,_cimg_mp_slot_x,_cimg_mp_slot_y,_cimg_mp_slot_z,0,0,0); case 'G' : if (reserved_label[(int)'G']!=~0U) _cimg_mp_return(reserved_label[(int)'G']); need_input_copy = true; _cimg_mp_scalar6(mp_ixyzc,_cimg_mp_slot_x,_cimg_mp_slot_y,_cimg_mp_slot_z,1,0,0); case 'B' : if (reserved_label[(int)'B']!=~0U) _cimg_mp_return(reserved_label[(int)'B']); need_input_copy = true; _cimg_mp_scalar6(mp_ixyzc,_cimg_mp_slot_x,_cimg_mp_slot_y,_cimg_mp_slot_z,2,0,0); case 'A' : if (reserved_label[(int)'A']!=~0U) _cimg_mp_return(reserved_label[(int)'A']); need_input_copy = true; _cimg_mp_scalar6(mp_ixyzc,_cimg_mp_slot_x,_cimg_mp_slot_y,_cimg_mp_slot_z,3,0,0); } else if (ss2==se) { // Two-chars reserved variable arg1 = arg2 = ~0U; if (*ss=='w' && *ss1=='h') // wh _cimg_mp_return(reserved_label[0]!=~0U?reserved_label[0]:23); if (*ss=='p' && *ss1=='i') // pi _cimg_mp_return(reserved_label[3]!=~0U?reserved_label[3]:28); if (*ss=='i') { if (*ss1>='0' && *ss1<='9') { // i0...i9 pos = 19 + *ss1 - '0'; if (reserved_label[pos]!=~0U) _cimg_mp_return(reserved_label[pos]); need_input_copy = true; _cimg_mp_scalar6(mp_ixyzc,_cimg_mp_slot_x,_cimg_mp_slot_y,_cimg_mp_slot_z,pos - 19,0,0); } switch (*ss1) { case 'm' : arg1 = 4; arg2 = 0; break; // im case 'M' : arg1 = 5; arg2 = 1; break; // iM case 'a' : arg1 = 6; arg2 = 2; break; // ia case 'v' : arg1 = 7; arg2 = 3; break; // iv case 's' : arg1 = 8; arg2 = 12; break; // is case 'p' : arg1 = 9; arg2 = 13; break; // ip case 'c' : // ic if (reserved_label[10]!=~0U) _cimg_mp_return(reserved_label[10]); if (mem_img_median==~0U) mem_img_median = imgin?constant(imgin.median()):0; _cimg_mp_return(mem_img_median); break; } } else if (*ss1=='m') switch (*ss) { case 'x' : arg1 = 11; arg2 = 4; break; // xm case 'y' : arg1 = 12; arg2 = 5; break; // ym case 'z' : arg1 = 13; arg2 = 6; break; // zm case 'c' : arg1 = 14; arg2 = 7; break; // cm } else if (*ss1=='M') switch (*ss) { case 'x' : arg1 = 15; arg2 = 8; break; // xM case 'y' : arg1 = 16; arg2 = 9; break; // yM case 'z' : arg1 = 17; arg2 = 10; break; // zM case 'c' : arg1 = 18; arg2 = 11; break; // cM } if (arg1!=~0U) { if (reserved_label[arg1]!=~0U) _cimg_mp_return(reserved_label[arg1]); if (!img_stats) { img_stats.assign(1,14,1,1,0).fill(imgin.get_stats(),false); mem_img_stats.assign(1,14,1,1,~0U); } if (mem_img_stats[arg2]==~0U) mem_img_stats[arg2] = constant(img_stats[arg2]); _cimg_mp_return(mem_img_stats[arg2]); } } else if (ss3==se) { // Three-chars reserved variable if (*ss=='w' && *ss1=='h' && *ss2=='d') // whd _cimg_mp_return(reserved_label[1]!=~0U?reserved_label[1]:24); } else if (ss4==se) { // Four-chars reserved variable if (*ss=='w' && *ss1=='h' && *ss2=='d' && *ss3=='s') // whds _cimg_mp_return(reserved_label[2]!=~0U?reserved_label[2]:25); } pos = ~0U; is_sth = false; for (s0 = ss, s = ss1; s<se1; ++s) if (*s==';' && level[s - expr._data]==clevel) { // Separator ';' arg1 = code_end._width; arg2 = compile(s0,s++,depth,0,is_single); if (code_end._width==arg1) pos = arg2; // makes 'end()' return void is_sth = true; while (*s && (cimg::is_blank(*s) || *s==';')) ++s; s0 = s; } if (is_sth) { arg1 = code_end._width; arg2 = compile(s0,se,depth,p_ref,is_single); if (code_end._width==arg1) pos = arg2; // makes 'end()' return void _cimg_mp_return(pos); } // Declare / assign variable, vector value or image value. for (s = ss1, ps = ss, ns = ss2; s<se1; ++s, ++ps, ++ns) if (*s=='=' && *ns!='=' && *ps!='=' && *ps!='>' && *ps!='<' && *ps!='!' && *ps!='+' && *ps!='-' && *ps!='*' && *ps!='/' && *ps!='%' && *ps!='>' && *ps!='<' && *ps!='&' && *ps!='|' && *ps!='^' && level[s - expr._data]==clevel) { variable_name.assign(ss,(unsigned int)(s + 1 - ss)).back() = 0; cimg::strpare(variable_name,false,true); const unsigned int l_variable_name = (unsigned int)std::strlen(variable_name); char *const ve1 = ss + l_variable_name - 1; _cimg_mp_op("Operator '='"); // Assign image value (direct). if (l_variable_name>2 && (*ss=='i' || *ss=='j' || *ss=='I' || *ss=='J') && (*ss1=='(' || *ss1=='[') && (reserved_label[(int)*ss]==~0U || *ss1=='(' || !_cimg_mp_is_vector(reserved_label[(int)*ss]))) { is_relative = *ss=='j' || *ss=='J'; if (*ss1=='[' && *ve1==']') { // i/j/I/J[_#ind,offset] = value if (!is_single) is_parallelizable = false; if (*ss2=='#') { // Index specified s0 = ss3; while (s0<ve1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; p1 = compile(ss3,s0++,depth1,0,is_single); _cimg_mp_check_list(true); } else { p1 = ~0U; s0 = ss2; } arg1 = compile(s0,ve1,depth1,0,is_single); // Offset _cimg_mp_check_type(arg1,0,1,0); arg2 = compile(s + 1,se,depth1,0,is_single); // Value to assign if (_cimg_mp_is_vector(arg2)) { p2 = ~0U; // 'p2' must be the dimension of the vector-valued operand if any if (p1==~0U) p2 = imgin._spectrum; else if (_cimg_mp_is_constant(p1)) { p3 = (unsigned int)cimg::mod((int)mem[p1],listin.width()); p2 = listin[p3]._spectrum; } if (!p2) _cimg_mp_return(0); } else p2 = 0; _cimg_mp_check_type(arg2,2,*ss>='i'?1:3,p2); if (p_ref) { *p_ref = _cimg_mp_is_vector(arg2)?4:2; p_ref[1] = p1; p_ref[2] = (unsigned int)is_relative; p_ref[3] = arg1; if (_cimg_mp_is_vector(arg2)) set_variable_vector(arg2); // Prevent from being used in further optimization else if (_cimg_mp_is_comp(arg2)) memtype[arg2] = -2; if (p1!=~0U && _cimg_mp_is_comp(p1)) memtype[p1] = -2; if (_cimg_mp_is_comp(arg1)) memtype[arg1] = -2; } if (p1!=~0U) { if (!listout) _cimg_mp_return(arg2); if (*ss>='i') CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_joff:mp_list_set_ioff), arg2,p1,arg1).move_to(code); else if (_cimg_mp_is_scalar(arg2)) CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_Joff_s:mp_list_set_Ioff_s), arg2,p1,arg1).move_to(code); else CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_Joff_v:mp_list_set_Ioff_v), arg2,p1,arg1,_cimg_mp_size(arg2)).move_to(code); } else { if (!imgout) _cimg_mp_return(arg2); if (*ss>='i') CImg<ulongT>::vector((ulongT)(is_relative?mp_set_joff:mp_set_ioff), arg2,arg1).move_to(code); else if (_cimg_mp_is_scalar(arg2)) CImg<ulongT>::vector((ulongT)(is_relative?mp_set_Joff_s:mp_set_Ioff_s), arg2,arg1).move_to(code); else CImg<ulongT>::vector((ulongT)(is_relative?mp_set_Joff_v:mp_set_Ioff_v), arg2,arg1,_cimg_mp_size(arg2)).move_to(code); } _cimg_mp_return(arg2); } if (*ss1=='(' && *ve1==')') { // i/j/I/J(_#ind,_x,_y,_z,_c) = value if (!is_single) is_parallelizable = false; if (*ss2=='#') { // Index specified s0 = ss3; while (s0<ve1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; p1 = compile(ss3,s0++,depth1,0,is_single); _cimg_mp_check_list(true); } else { p1 = ~0U; s0 = ss2; } arg1 = is_relative?0U:(unsigned int)_cimg_mp_slot_x; arg2 = is_relative?0U:(unsigned int)_cimg_mp_slot_y; arg3 = is_relative?0U:(unsigned int)_cimg_mp_slot_z; arg4 = is_relative?0U:(unsigned int)_cimg_mp_slot_c; arg5 = compile(s + 1,se,depth1,0,is_single); // Value to assign if (s0<ve1) { // X or [ X,_Y,_Z,_C ] s1 = s0; while (s1<ve1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(s0,s1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) { // Coordinates specified as a vector p2 = _cimg_mp_size(arg1); // Vector size ++arg1; if (p2>1) { arg2 = arg1 + 1; if (p2>2) { arg3 = arg2 + 1; if (p2>3) arg4 = arg3 + 1; } } } else if (s1<ve1) { // Y s2 = ++s1; while (s2<ve1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(s1,s2,depth1,0,is_single); if (s2<ve1) { // Z s3 = ++s2; while (s3<ve1 && (*s3!=',' || level[s3 - expr._data]!=clevel1)) ++s3; arg3 = compile(s2,s3,depth1,0,is_single); if (s3<ve1) arg4 = compile(++s3,ve1,depth1,0,is_single); // C } } } if (_cimg_mp_is_vector(arg5)) { p2 = ~0U; // 'p2' must be the dimension of the vector-valued operand if any if (p1==~0U) p2 = imgin._spectrum; else if (_cimg_mp_is_constant(p1)) { p3 = (unsigned int)cimg::mod((int)mem[p1],listin.width()); p2 = listin[p3]._spectrum; } if (!p2) _cimg_mp_return(0); } else p2 = 0; _cimg_mp_check_type(arg5,2,*ss>='i'?1:3,p2); if (p_ref) { *p_ref = _cimg_mp_is_vector(arg5)?5:3; p_ref[1] = p1; p_ref[2] = (unsigned int)is_relative; p_ref[3] = arg1; p_ref[4] = arg2; p_ref[5] = arg3; p_ref[6] = arg4; if (_cimg_mp_is_vector(arg5)) set_variable_vector(arg5); // Prevent from being used in further optimization else if (_cimg_mp_is_comp(arg5)) memtype[arg5] = -2; if (p1!=~0U && _cimg_mp_is_comp(p1)) memtype[p1] = -2; if (_cimg_mp_is_comp(arg1)) memtype[arg1] = -2; if (_cimg_mp_is_comp(arg2)) memtype[arg2] = -2; if (_cimg_mp_is_comp(arg3)) memtype[arg3] = -2; if (_cimg_mp_is_comp(arg4)) memtype[arg4] = -2; } if (p1!=~0U) { if (!listout) _cimg_mp_return(arg5); if (*ss>='i') CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_jxyzc:mp_list_set_ixyzc), arg5,p1,arg1,arg2,arg3,arg4).move_to(code); else if (_cimg_mp_is_scalar(arg5)) CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_Jxyz_s:mp_list_set_Ixyz_s), arg5,p1,arg1,arg2,arg3).move_to(code); else CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_Jxyz_v:mp_list_set_Ixyz_v), arg5,p1,arg1,arg2,arg3,_cimg_mp_size(arg5)).move_to(code); } else { if (!imgout) _cimg_mp_return(arg5); if (*ss>='i') CImg<ulongT>::vector((ulongT)(is_relative?mp_set_jxyzc:mp_set_ixyzc), arg5,arg1,arg2,arg3,arg4).move_to(code); else if (_cimg_mp_is_scalar(arg5)) CImg<ulongT>::vector((ulongT)(is_relative?mp_set_Jxyz_s:mp_set_Ixyz_s), arg5,arg1,arg2,arg3).move_to(code); else CImg<ulongT>::vector((ulongT)(is_relative?mp_set_Jxyz_v:mp_set_Ixyz_v), arg5,arg1,arg2,arg3,_cimg_mp_size(arg5)).move_to(code); } _cimg_mp_return(arg5); } } // Assign vector value (direct). if (l_variable_name>3 && *ve1==']' && *ss!='[') { s0 = ve1; while (s0>ss && (*s0!='[' || level[s0 - expr._data]!=clevel)) --s0; is_sth = true; // is_valid_variable_name? if (*ss>='0' && *ss<='9') is_sth = false; else for (ns = ss; ns<s0; ++ns) if (!is_varchar(*ns)) { is_sth = false; break; } if (is_sth && s0>ss) { variable_name[s0 - ss] = 0; // Remove brackets in variable name arg1 = ~0U; // Vector slot arg2 = compile(++s0,ve1,depth1,0,is_single); // Index arg3 = compile(s + 1,se,depth1,0,is_single); // Value to assign _cimg_mp_check_type(arg3,2,1,0); if (variable_name[1]) { // Multi-char variable cimglist_for(variable_def,i) if (!std::strcmp(variable_name,variable_def[i])) { arg1 = variable_pos[i]; break; } } else arg1 = reserved_label[(int)*variable_name]; // Single-char variable if (arg1==~0U) compile(ss,s0 - 1,depth1,0,is_single); // Variable does not exist -> error else { // Variable already exists if (_cimg_mp_is_scalar(arg1)) compile(ss,s,depth1,0,is_single); // Variable is not a vector -> error if (_cimg_mp_is_constant(arg2)) { // Constant index -> return corresponding variable slot directly nb = (int)mem[arg2]; if (nb>=0 && nb<(int)_cimg_mp_size(arg1)) { arg1+=nb + 1; CImg<ulongT>::vector((ulongT)mp_copy,arg1,arg3).move_to(code); _cimg_mp_return(arg1); } compile(ss,s,depth1,0,is_single); // Out-of-bounds reference -> error } // Case of non-constant index -> return assigned value + linked reference if (p_ref) { *p_ref = 1; p_ref[1] = arg1; p_ref[2] = arg2; if (_cimg_mp_is_comp(arg3)) memtype[arg3] = -2; // Prevent from being used in further optimization if (_cimg_mp_is_comp(arg2)) memtype[arg2] = -2; } CImg<ulongT>::vector((ulongT)mp_vector_set_off,arg3,arg1,(ulongT)_cimg_mp_size(arg1), arg2,arg3). move_to(code); _cimg_mp_return(arg3); } } } // Assign user-defined macro. if (l_variable_name>2 && *ve1==')' && *ss!='(') { s0 = ve1; while (s0>ss && *s0!='(') --s0; is_sth = std::strncmp(variable_name,"debug(",6) && std::strncmp(variable_name,"print(",6); // is_valid_function_name? if (*ss>='0' && *ss<='9') is_sth = false; else for (ns = ss; ns<s0; ++ns) if (!is_varchar(*ns)) { is_sth = false; break; } if (is_sth && s0>ss) { // Looks like a valid function declaration s0 = variable_name._data + (s0 - ss); *s0 = 0; s1 = variable_name._data + l_variable_name - 1; // Pointer to closing parenthesis CImg<charT>(variable_name._data,(unsigned int)(s0 - variable_name._data + 1)).move_to(macro_def,0); ++s; while (*s && cimg::is_blank(*s)) ++s; CImg<charT>(s,(unsigned int)(se - s + 1)).move_to(macro_body,0); p1 = 1; // Index of current parsed argument for (s = s0 + 1; s<=s1; ++p1, s = ns + 1) { // Parse function arguments if (p1>24) { *se = saved_char; cimg::strellipsize(variable_name,64); s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Too much specified arguments (>24) in macro " "definition '%s()', in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, variable_name._data, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } while (*s && cimg::is_blank(*s)) ++s; if (*s==')' && p1==1) break; // Function has no arguments s2 = s; // Start of the argument name is_sth = true; // is_valid_argument_name? if (*s>='0' && *s<='9') is_sth = false; else for (ns = s; ns<s1 && *ns!=',' && !cimg::is_blank(*ns); ++ns) if (!is_varchar(*ns)) { is_sth = false; break; } s3 = ns; // End of the argument name while (*ns && cimg::is_blank(*ns)) ++ns; if (!is_sth || s2==s3 || (*ns!=',' && ns!=s1)) { *se = saved_char; cimg::strellipsize(variable_name,64); s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: %s name specified for argument %u when defining " "macro '%s()', in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, is_sth?"Empty":"Invalid",p1, variable_name._data, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } if (ns==s1 || *ns==',') { // New argument found *s3 = 0; p2 = (unsigned int)(s3 - s2); // Argument length for (ps = std::strstr(macro_body[0],s2); ps; ps = std::strstr(ps,s2)) { // Replace by arg number if (!((ps>macro_body[0]._data && is_varchar(*(ps - 1))) || (ps + p2<macro_body[0].end() && is_varchar(*(ps + p2))))) { if (ps>macro_body[0]._data && *(ps - 1)=='#') { // Remove pre-number sign *(ps - 1) = (char)p1; if (ps + p2<macro_body[0].end() && *(ps + p2)=='#') { // Has pre & post number signs std::memmove(ps,ps + p2 + 1,macro_body[0].end() - ps - p2 - 1); macro_body[0]._width-=p2 + 1; } else { // Has pre number sign only std::memmove(ps,ps + p2,macro_body[0].end() - ps - p2); macro_body[0]._width-=p2; } } else if (ps + p2<macro_body[0].end() && *(ps + p2)=='#') { // Remove post-number sign *(ps++) = (char)p1; std::memmove(ps,ps + p2,macro_body[0].end() - ps - p2); macro_body[0]._width-=p2; } else { // Not near a number sign if (p2<3) { ps-=(ulongT)macro_body[0]._data; macro_body[0].resize(macro_body[0]._width - p2 + 3,1,1,1,0); ps+=(ulongT)macro_body[0]._data; } else macro_body[0]._width-=p2 - 3; std::memmove(ps + 3,ps + p2,macro_body[0].end() - ps - 3); *(ps++) = '('; *(ps++) = (char)p1; *(ps++) = ')'; } } else ++ps; } } } // Store number of arguments. macro_def[0].resize(macro_def[0]._width + 1,1,1,1,0).back() = (char)(p1 - 1); // Detect parts of function body inside a string. is_inside_string(macro_body[0]).move_to(macro_body_is_string,0); _cimg_mp_return_nan(); } } // Check if the variable name could be valid. If not, this is probably an lvalue assignment. is_sth = true; // is_valid_variable_name? const bool is_const = l_variable_name>6 && !std::strncmp(variable_name,"const ",6); s0 = variable_name._data; if (is_const) { s0+=6; while (cimg::is_blank(*s0)) ++s0; variable_name.resize(variable_name.end() - s0,1,1,1,0,0,1); } if (*variable_name>='0' && *variable_name<='9') is_sth = false; else for (ns = variable_name._data; *ns; ++ns) if (!is_varchar(*ns)) { is_sth = false; break; } // Assign variable (direct). if (is_sth) { arg3 = variable_name[1]?~0U:*variable_name; // One-char variable if (variable_name[1] && !variable_name[2]) { // Two-chars variable c1 = variable_name[0]; c2 = variable_name[1]; if (c1=='w' && c2=='h') arg3 = 0; // wh else if (c1=='p' && c2=='i') arg3 = 3; // pi else if (c1=='i') { if (c2>='0' && c2<='9') arg3 = 19 + c2 - '0'; // i0...i9 else if (c2=='m') arg3 = 4; // im else if (c2=='M') arg3 = 5; // iM else if (c2=='a') arg3 = 6; // ia else if (c2=='v') arg3 = 7; // iv else if (c2=='s') arg3 = 8; // is else if (c2=='p') arg3 = 9; // ip else if (c2=='c') arg3 = 10; // ic } else if (c2=='m') { if (c1=='x') arg3 = 11; // xm else if (c1=='y') arg3 = 12; // ym else if (c1=='z') arg3 = 13; // zm else if (c1=='c') arg3 = 14; // cm } else if (c2=='M') { if (c1=='x') arg3 = 15; // xM else if (c1=='y') arg3 = 16; // yM else if (c1=='z') arg3 = 17; // zM else if (c1=='c') arg3 = 18; // cM } } else if (variable_name[1] && variable_name[2] && !variable_name[3]) { // Three-chars variable c1 = variable_name[0]; c2 = variable_name[1]; c3 = variable_name[2]; if (c1=='w' && c2=='h' && c3=='d') arg3 = 1; // whd } else if (variable_name[1] && variable_name[2] && variable_name[3] && !variable_name[4]) { // Four-chars variable c1 = variable_name[0]; c2 = variable_name[1]; c3 = variable_name[2]; c4 = variable_name[3]; if (c1=='w' && c2=='h' && c3=='d' && c4=='s') arg3 = 2; // whds } else if (!std::strcmp(variable_name,"interpolation")) arg3 = 29; // interpolation else if (!std::strcmp(variable_name,"boundary")) arg3 = 30; // boundary arg1 = ~0U; arg2 = compile(s + 1,se,depth1,0,is_single); if (is_const) _cimg_mp_check_constant(arg2,2,0); if (arg3!=~0U) // One-char variable, or variable in reserved_labels arg1 = reserved_label[arg3]; else // Multi-char variable name : check for existing variable with same name cimglist_for(variable_def,i) if (!std::strcmp(variable_name,variable_def[i])) { arg1 = variable_pos[i]; break; } if (arg1==~0U) { // Create new variable if (_cimg_mp_is_vector(arg2)) { // Vector variable arg1 = is_comp_vector(arg2)?arg2:vector_copy(arg2); set_variable_vector(arg1); } else { // Scalar variable if (is_const) arg1 = arg2; else { arg1 = _cimg_mp_is_comp(arg2)?arg2:scalar1(mp_copy,arg2); memtype[arg1] = -1; } } if (arg3!=~0U) reserved_label[arg3] = arg1; else { if (variable_def._width>=variable_pos._width) variable_pos.resize(-200,1,1,1,0); variable_pos[variable_def._width] = arg1; variable_name.move_to(variable_def); } } else { // Variable already exists -> assign a new value if (is_const || _cimg_mp_is_constant(arg1)) { *se = saved_char; cimg::strellipsize(variable_name,64); s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Invalid assignment of %sconst variable '%s'%s, " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, _cimg_mp_is_constant(arg1)?"already-defined ":"non-", variable_name._data, !_cimg_mp_is_constant(arg1) && is_const?" as a new const variable":"", s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } _cimg_mp_check_type(arg2,2,_cimg_mp_is_vector(arg1)?3:1,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg1)) { // Vector if (_cimg_mp_is_vector(arg2)) // From vector CImg<ulongT>::vector((ulongT)mp_vector_copy,arg1,arg2,(ulongT)_cimg_mp_size(arg1)). move_to(code); else // From scalar CImg<ulongT>::vector((ulongT)mp_vector_init,arg1,1,(ulongT)_cimg_mp_size(arg1),arg2). move_to(code); } else // Scalar CImg<ulongT>::vector((ulongT)mp_copy,arg1,arg2).move_to(code); } _cimg_mp_return(arg1); } // Assign lvalue (variable name was not valid for a direct assignment). arg1 = ~0U; is_sth = (bool)std::strchr(variable_name,'?'); // Contains_ternary_operator? if (is_sth) break; // Do nothing and make ternary operator prioritary over assignment if (l_variable_name>2 && (std::strchr(variable_name,'(') || std::strchr(variable_name,'['))) { ref.assign(7); arg1 = compile(ss,s,depth1,ref,is_single); // Lvalue slot arg2 = compile(s + 1,se,depth1,0,is_single); // Value to assign if (*ref==1) { // Vector value (scalar): V[k] = scalar _cimg_mp_check_type(arg2,2,1,0); arg3 = ref[1]; // Vector slot arg4 = ref[2]; // Index if (p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); CImg<ulongT>::vector((ulongT)mp_vector_set_off,arg2,arg3,(ulongT)_cimg_mp_size(arg3),arg4,arg2). move_to(code); _cimg_mp_return(arg2); } if (*ref==2) { // Image value (scalar): i/j[_#ind,off] = scalar if (!is_single) is_parallelizable = false; _cimg_mp_check_type(arg2,2,1,0); p1 = ref[1]; // Index is_relative = (bool)ref[2]; arg3 = ref[3]; // Offset if (p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); if (p1!=~0U) { if (!listout) _cimg_mp_return(arg2); CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_joff:mp_list_set_ioff), arg2,p1,arg3).move_to(code); } else { if (!imgout) _cimg_mp_return(arg2); CImg<ulongT>::vector((ulongT)(is_relative?mp_set_joff:mp_set_ioff), arg2,arg3).move_to(code); } _cimg_mp_return(arg2); } if (*ref==3) { // Image value (scalar): i/j(_#ind,_x,_y,_z,_c) = scalar if (!is_single) is_parallelizable = false; _cimg_mp_check_type(arg2,2,1,0); p1 = ref[1]; // Index is_relative = (bool)ref[2]; arg3 = ref[3]; // X arg4 = ref[4]; // Y arg5 = ref[5]; // Z arg6 = ref[6]; // C if (p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); if (p1!=~0U) { if (!listout) _cimg_mp_return(arg2); CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_jxyzc:mp_list_set_ixyzc), arg2,p1,arg3,arg4,arg5,arg6).move_to(code); } else { if (!imgout) _cimg_mp_return(arg2); CImg<ulongT>::vector((ulongT)(is_relative?mp_set_jxyzc:mp_set_ixyzc), arg2,arg3,arg4,arg5,arg6).move_to(code); } _cimg_mp_return(arg2); } if (*ref==4) { // Image value (vector): I/J[_#ind,off] = value if (!is_single) is_parallelizable = false; _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); p1 = ref[1]; // Index is_relative = (bool)ref[2]; arg3 = ref[3]; // Offset if (p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); if (p1!=~0U) { if (!listout) _cimg_mp_return(arg2); if (_cimg_mp_is_scalar(arg2)) CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_Joff_s:mp_list_set_Ioff_s), arg2,p1,arg3).move_to(code); else CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_Joff_v:mp_list_set_Ioff_v), arg2,p1,arg3,_cimg_mp_size(arg2)).move_to(code); } else { if (!imgout) _cimg_mp_return(arg2); if (_cimg_mp_is_scalar(arg2)) CImg<ulongT>::vector((ulongT)(is_relative?mp_set_Joff_s:mp_set_Ioff_s), arg2,arg3).move_to(code); else CImg<ulongT>::vector((ulongT)(is_relative?mp_set_Joff_v:mp_set_Ioff_v), arg2,arg3,_cimg_mp_size(arg2)).move_to(code); } _cimg_mp_return(arg2); } if (*ref==5) { // Image value (vector): I/J(_#ind,_x,_y,_z,_c) = value if (!is_single) is_parallelizable = false; _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); p1 = ref[1]; // Index is_relative = (bool)ref[2]; arg3 = ref[3]; // X arg4 = ref[4]; // Y arg5 = ref[5]; // Z if (p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); if (p1!=~0U) { if (!listout) _cimg_mp_return(arg2); if (_cimg_mp_is_scalar(arg2)) CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_Jxyz_s:mp_list_set_Ixyz_s), arg2,p1,arg3,arg4,arg5).move_to(code); else CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_Jxyz_v:mp_list_set_Ixyz_v), arg2,p1,arg3,arg4,arg5,_cimg_mp_size(arg2)).move_to(code); } else { if (!imgout) _cimg_mp_return(arg2); if (_cimg_mp_is_scalar(arg2)) CImg<ulongT>::vector((ulongT)(is_relative?mp_set_Jxyz_s:mp_set_Ixyz_s), arg2,arg3,arg4,arg5).move_to(code); else CImg<ulongT>::vector((ulongT)(is_relative?mp_set_Jxyz_v:mp_set_Ixyz_v), arg2,arg3,arg4,arg5,_cimg_mp_size(arg2)).move_to(code); } _cimg_mp_return(arg2); } if (_cimg_mp_is_vector(arg1)) { // Vector variable: V = value _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg2)) // From vector CImg<ulongT>::vector((ulongT)mp_vector_copy,arg1,arg2,(ulongT)_cimg_mp_size(arg1)). move_to(code); else // From scalar CImg<ulongT>::vector((ulongT)mp_vector_init,arg1,1,(ulongT)_cimg_mp_size(arg1),arg2). move_to(code); _cimg_mp_return(arg1); } if (_cimg_mp_is_variable(arg1)) { // Scalar variable: s = scalar _cimg_mp_check_type(arg2,2,1,0); CImg<ulongT>::vector((ulongT)mp_copy,arg1,arg2).move_to(code); _cimg_mp_return(arg1); } } // No assignment expressions match -> error *se = saved_char; cimg::strellipsize(variable_name,64); s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Invalid %slvalue '%s', " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, arg1!=~0U && _cimg_mp_is_constant(arg1)?"const ":"", variable_name._data, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } // Apply unary/binary/ternary operators. The operator precedences should be the same as in C++. for (s = se2, ps = se3, ns = ps - 1; s>ss1; --s, --ps, --ns) // Here, ns = ps - 1 if (*s=='=' && (*ps=='*' || *ps=='/' || *ps=='^') && *ns==*ps && level[s - expr._data]==clevel) { // Self-operators for complex numbers only (**=,//=,^^=) _cimg_mp_op(*ps=='*'?"Operator '**='":*ps=='/'?"Operator '//='":"Operator '^^='"); ref.assign(7); arg1 = compile(ss,ns,depth1,ref,is_single); // Vector slot arg2 = compile(s + 1,se,depth1,0,is_single); // Right operand _cimg_mp_check_type(arg1,1,2,2); _cimg_mp_check_type(arg2,2,3,2); if (_cimg_mp_is_vector(arg2)) { // Complex **= complex if (*ps=='*') CImg<ulongT>::vector((ulongT)mp_complex_mul,arg1,arg1,arg2).move_to(code); else if (*ps=='/') CImg<ulongT>::vector((ulongT)mp_complex_div_vv,arg1,arg1,arg2).move_to(code); else CImg<ulongT>::vector((ulongT)mp_complex_pow_vv,arg1,arg1,arg2).move_to(code); } else { // Complex **= scalar if (*ps=='*') { if (arg2==1) _cimg_mp_return(arg1); self_vector_s(arg1,mp_self_mul,arg2); } else if (*ps=='/') { if (arg2==1) _cimg_mp_return(arg1); self_vector_s(arg1,mp_self_div,arg2); } else { if (arg2==1) _cimg_mp_return(arg1); CImg<ulongT>::vector((ulongT)mp_complex_pow_vs,arg1,arg1,arg2).move_to(code); } } // Write computed value back in image if necessary. if (*ref==4) { // Image value (vector): I/J[_#ind,off] **= value if (!is_single) is_parallelizable = false; p1 = ref[1]; // Index is_relative = (bool)ref[2]; arg3 = ref[3]; // Offset if (p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); if (p1!=~0U) { if (!listout) _cimg_mp_return(arg1); CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_Joff_v:mp_list_set_Ioff_v), arg1,p1,arg3,_cimg_mp_size(arg1)).move_to(code); } else { if (!imgout) _cimg_mp_return(arg1); CImg<ulongT>::vector((ulongT)(is_relative?mp_set_Joff_v:mp_set_Ioff_v), arg1,arg3,_cimg_mp_size(arg1)).move_to(code); } } else if (*ref==5) { // Image value (vector): I/J(_#ind,_x,_y,_z,_c) **= value if (!is_single) is_parallelizable = false; p1 = ref[1]; // Index is_relative = (bool)ref[2]; arg3 = ref[3]; // X arg4 = ref[4]; // Y arg5 = ref[5]; // Z if (p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); if (p1!=~0U) { if (!listout) _cimg_mp_return(arg1); CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_Jxyz_v:mp_list_set_Ixyz_v), arg1,p1,arg3,arg4,arg5,_cimg_mp_size(arg1)).move_to(code); } else { if (!imgout) _cimg_mp_return(arg1); CImg<ulongT>::vector((ulongT)(is_relative?mp_set_Jxyz_v:mp_set_Ixyz_v), arg1,arg3,arg4,arg5,_cimg_mp_size(arg1)).move_to(code); } } _cimg_mp_return(arg1); } for (s = se2, ps = se3, ns = ps - 1; s>ss1; --s, --ps, --ns) // Here, ns = ps - 1 if (*s=='=' && (*ps=='+' || *ps=='-' || *ps=='*' || *ps=='/' || *ps=='%' || *ps=='&' || *ps=='^' || *ps=='|' || (*ps=='>' && *ns=='>') || (*ps=='<' && *ns=='<')) && level[s - expr._data]==clevel) { // Self-operators (+=,-=,*=,/=,%=,>>=,<<=,&=,^=,|=) switch (*ps) { case '+' : op = mp_self_add; _cimg_mp_op("Operator '+='"); break; case '-' : op = mp_self_sub; _cimg_mp_op("Operator '-='"); break; case '*' : op = mp_self_mul; _cimg_mp_op("Operator '*='"); break; case '/' : op = mp_self_div; _cimg_mp_op("Operator '/='"); break; case '%' : op = mp_self_modulo; _cimg_mp_op("Operator '%='"); break; case '<' : op = mp_self_bitwise_left_shift; _cimg_mp_op("Operator '<<='"); break; case '>' : op = mp_self_bitwise_right_shift; _cimg_mp_op("Operator '>>='"); break; case '&' : op = mp_self_bitwise_and; _cimg_mp_op("Operator '&='"); break; case '|' : op = mp_self_bitwise_or; _cimg_mp_op("Operator '|='"); break; default : op = mp_self_pow; _cimg_mp_op("Operator '^='"); break; } s1 = *ps=='>' || *ps=='<'?ns:ps; ref.assign(7); arg1 = compile(ss,s1,depth1,ref,is_single); // Variable slot arg2 = compile(s + 1,se,depth1,0,is_single); // Value to apply // Check for particular case to be simplified. if ((op==mp_self_add || op==mp_self_sub) && !arg2) _cimg_mp_return(arg1); if ((op==mp_self_mul || op==mp_self_div) && arg2==1) _cimg_mp_return(arg1); // Apply operator on a copy to prevent modifying a constant or a variable. if (*ref && (_cimg_mp_is_constant(arg1) || _cimg_mp_is_vector(arg1) || _cimg_mp_is_variable(arg1))) { if (_cimg_mp_is_vector(arg1)) arg1 = vector_copy(arg1); else arg1 = scalar1(mp_copy,arg1); } if (*ref==1) { // Vector value (scalar): V[k] += scalar _cimg_mp_check_type(arg2,2,1,0); arg3 = ref[1]; // Vector slot arg4 = ref[2]; // Index if (p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); CImg<ulongT>::vector((ulongT)op,arg1,arg2).move_to(code); CImg<ulongT>::vector((ulongT)mp_vector_set_off,arg1,arg3,(ulongT)_cimg_mp_size(arg3),arg4,arg1). move_to(code); _cimg_mp_return(arg1); } if (*ref==2) { // Image value (scalar): i/j[_#ind,off] += scalar if (!is_single) is_parallelizable = false; _cimg_mp_check_type(arg2,2,1,0); p1 = ref[1]; // Index is_relative = (bool)ref[2]; arg3 = ref[3]; // Offset if (p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); CImg<ulongT>::vector((ulongT)op,arg1,arg2).move_to(code); if (p1!=~0U) { if (!listout) _cimg_mp_return(arg1); CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_joff:mp_list_set_ioff), arg1,p1,arg3).move_to(code); } else { if (!imgout) _cimg_mp_return(arg1); CImg<ulongT>::vector((ulongT)(is_relative?mp_set_joff:mp_set_ioff), arg1,arg3).move_to(code); } _cimg_mp_return(arg1); } if (*ref==3) { // Image value (scalar): i/j(_#ind,_x,_y,_z,_c) += scalar if (!is_single) is_parallelizable = false; _cimg_mp_check_type(arg2,2,1,0); p1 = ref[1]; // Index is_relative = (bool)ref[2]; arg3 = ref[3]; // X arg4 = ref[4]; // Y arg5 = ref[5]; // Z arg6 = ref[6]; // C if (p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); CImg<ulongT>::vector((ulongT)op,arg1,arg2).move_to(code); if (p1!=~0U) { if (!listout) _cimg_mp_return(arg1); CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_jxyzc:mp_list_set_ixyzc), arg1,p1,arg3,arg4,arg5,arg6).move_to(code); } else { if (!imgout) _cimg_mp_return(arg1); CImg<ulongT>::vector((ulongT)(is_relative?mp_set_jxyzc:mp_set_ixyzc), arg1,arg3,arg4,arg5,arg6).move_to(code); } _cimg_mp_return(arg1); } if (*ref==4) { // Image value (vector): I/J[_#ind,off] += value if (!is_single) is_parallelizable = false; _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); p1 = ref[1]; // Index is_relative = (bool)ref[2]; arg3 = ref[3]; // Offset if (p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); if (_cimg_mp_is_scalar(arg2)) self_vector_s(arg1,op,arg2); else self_vector_v(arg1,op,arg2); if (p1!=~0U) { if (!listout) _cimg_mp_return(arg1); CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_Joff_v:mp_list_set_Ioff_v), arg1,p1,arg3,_cimg_mp_size(arg1)).move_to(code); } else { if (!imgout) _cimg_mp_return(arg1); CImg<ulongT>::vector((ulongT)(is_relative?mp_set_Joff_v:mp_set_Ioff_v), arg1,arg3,_cimg_mp_size(arg1)).move_to(code); } _cimg_mp_return(arg1); } if (*ref==5) { // Image value (vector): I/J(_#ind,_x,_y,_z,_c) += value if (!is_single) is_parallelizable = false; _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); p1 = ref[1]; // Index is_relative = (bool)ref[2]; arg3 = ref[3]; // X arg4 = ref[4]; // Y arg5 = ref[5]; // Z if (p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); if (_cimg_mp_is_scalar(arg2)) self_vector_s(arg1,op,arg2); else self_vector_v(arg1,op,arg2); if (p1!=~0U) { if (!listout) _cimg_mp_return(arg1); CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_Jxyz_v:mp_list_set_Ixyz_v), arg1,p1,arg3,arg4,arg5,_cimg_mp_size(arg1)).move_to(code); } else { if (!imgout) _cimg_mp_return(arg1); CImg<ulongT>::vector((ulongT)(is_relative?mp_set_Jxyz_v:mp_set_Ixyz_v), arg1,arg3,arg4,arg5,_cimg_mp_size(arg1)).move_to(code); } _cimg_mp_return(arg1); } if (_cimg_mp_is_vector(arg1)) { // Vector variable: V += value _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg2)) self_vector_v(arg1,op,arg2); // Vector += vector else self_vector_s(arg1,op,arg2); // Vector += scalar _cimg_mp_return(arg1); } if (_cimg_mp_is_variable(arg1)) { // Scalar variable: s += scalar _cimg_mp_check_type(arg2,2,1,0); CImg<ulongT>::vector((ulongT)op,arg1,arg2).move_to(code); _cimg_mp_return(arg1); } variable_name.assign(ss,(unsigned int)(s - ss)).back() = 0; cimg::strpare(variable_name,false,true); *se = saved_char; s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Invalid %slvalue '%s', " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, _cimg_mp_is_constant(arg1)?"const ":"", variable_name._data, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } for (s = ss1; s<se1; ++s) if (*s=='?' && level[s - expr._data]==clevel) { // Ternary operator 'cond?expr1:expr2' _cimg_mp_op("Operator '?:'"); s1 = s + 1; while (s1<se1 && (*s1!=':' || level[s1 - expr._data]!=clevel)) ++s1; arg1 = compile(ss,s,depth1,0,is_single); _cimg_mp_check_type(arg1,1,1,0); if (_cimg_mp_is_constant(arg1)) { if ((bool)mem[arg1]) return compile(s + 1,*s1!=':'?se:s1,depth1,0,is_single); else return *s1!=':'?0:compile(++s1,se,depth1,0,is_single); } p2 = code._width; arg2 = compile(s + 1,*s1!=':'?se:s1,depth1,0,is_single); p3 = code._width; arg3 = *s1==':'?compile(++s1,se,depth1,0,is_single): _cimg_mp_is_vector(arg2)?vector(_cimg_mp_size(arg2),0):0; _cimg_mp_check_type(arg3,3,_cimg_mp_is_vector(arg2)?2:1,_cimg_mp_size(arg2)); arg4 = _cimg_mp_size(arg2); if (arg4) pos = vector(arg4); else pos = scalar(); CImg<ulongT>::vector((ulongT)mp_if,pos,arg1,arg2,arg3, p3 - p2,code._width - p3,arg4).move_to(code,p2); _cimg_mp_return(pos); } for (s = se3, ns = se2; s>ss; --s, --ns) if (*s=='|' && *ns=='|' && level[s - expr._data]==clevel) { // Logical or ('||') _cimg_mp_op("Operator '||'"); arg1 = compile(ss,s,depth1,0,is_single); _cimg_mp_check_type(arg1,1,1,0); if (arg1>0 && arg1<=16) _cimg_mp_return(1); p2 = code._width; arg2 = compile(s + 2,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,1,0); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(mem[arg1] || mem[arg2]); if (!arg1) _cimg_mp_return(arg2); pos = scalar(); CImg<ulongT>::vector((ulongT)mp_logical_or,pos,arg1,arg2,code._width - p2). move_to(code,p2); _cimg_mp_return(pos); } for (s = se3, ns = se2; s>ss; --s, --ns) if (*s=='&' && *ns=='&' && level[s - expr._data]==clevel) { // Logical and ('&&') _cimg_mp_op("Operator '&&'"); arg1 = compile(ss,s,depth1,0,is_single); _cimg_mp_check_type(arg1,1,1,0); if (!arg1) _cimg_mp_return(0); p2 = code._width; arg2 = compile(s + 2,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,1,0); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(mem[arg1] && mem[arg2]); if (arg1>0 && arg1<=16) _cimg_mp_return(arg2); pos = scalar(); CImg<ulongT>::vector((ulongT)mp_logical_and,pos,arg1,arg2,code._width - p2). move_to(code,p2); _cimg_mp_return(pos); } for (s = se2; s>ss; --s) if (*s=='|' && level[s - expr._data]==clevel) { // Bitwise or ('|') _cimg_mp_op("Operator '|'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 1,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_bitwise_or,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) { if (!arg2) _cimg_mp_return(arg1); _cimg_mp_vector2_vs(mp_bitwise_or,arg1,arg2); } if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) { if (!arg1) _cimg_mp_return(arg2); _cimg_mp_vector2_sv(mp_bitwise_or,arg1,arg2); } if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant((longT)mem[arg1] | (longT)mem[arg2]); if (!arg2) _cimg_mp_return(arg1); if (!arg1) _cimg_mp_return(arg2); _cimg_mp_scalar2(mp_bitwise_or,arg1,arg2); } for (s = se2; s>ss; --s) if (*s=='&' && level[s - expr._data]==clevel) { // Bitwise and ('&') _cimg_mp_op("Operator '&'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 1,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_bitwise_and,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_bitwise_and,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_bitwise_and,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant((longT)mem[arg1] & (longT)mem[arg2]); if (!arg1 || !arg2) _cimg_mp_return(0); _cimg_mp_scalar2(mp_bitwise_and,arg1,arg2); } for (s = se3, ns = se2; s>ss; --s, --ns) if (*s=='!' && *ns=='=' && level[s - expr._data]==clevel) { // Not equal to ('!=') _cimg_mp_op("Operator '!='"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 2,se,depth1,0,is_single); if (arg1==arg2) _cimg_mp_return(0); p1 = _cimg_mp_size(arg1); p2 = _cimg_mp_size(arg2); if (p1 || p2) { if (p1 && p2 && p1!=p2) _cimg_mp_return(1); pos = scalar(); CImg<ulongT>::vector((ulongT)mp_vector_neq,pos,arg1,p1,arg2,p2,11,1).move_to(code); _cimg_mp_return(pos); } if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(mem[arg1]!=mem[arg2]); _cimg_mp_scalar2(mp_neq,arg1,arg2); } for (s = se3, ns = se2; s>ss; --s, --ns) if (*s=='=' && *ns=='=' && level[s - expr._data]==clevel) { // Equal to ('==') _cimg_mp_op("Operator '=='"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 2,se,depth1,0,is_single); if (arg1==arg2) _cimg_mp_return(1); p1 = _cimg_mp_size(arg1); p2 = _cimg_mp_size(arg2); if (p1 || p2) { if (p1 && p2 && p1!=p2) _cimg_mp_return(0); pos = scalar(); CImg<ulongT>::vector((ulongT)mp_vector_eq,pos,arg1,p1,arg2,p2,11,1).move_to(code); _cimg_mp_return(pos); } if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(mem[arg1]==mem[arg2]); _cimg_mp_scalar2(mp_eq,arg1,arg2); } for (s = se3, ns = se2; s>ss; --s, --ns) if (*s=='<' && *ns=='=' && level[s - expr._data]==clevel) { // Less or equal than ('<=') _cimg_mp_op("Operator '<='"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 2,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_lte,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_lte,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_lte,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(mem[arg1]<=mem[arg2]); if (arg1==arg2) _cimg_mp_return(1); _cimg_mp_scalar2(mp_lte,arg1,arg2); } for (s = se3, ns = se2; s>ss; --s, --ns) if (*s=='>' && *ns=='=' && level[s - expr._data]==clevel) { // Greater or equal than ('>=') _cimg_mp_op("Operator '>='"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 2,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_gte,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_gte,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_gte,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(mem[arg1]>=mem[arg2]); if (arg1==arg2) _cimg_mp_return(1); _cimg_mp_scalar2(mp_gte,arg1,arg2); } for (s = se2, ns = se1, ps = se3; s>ss; --s, --ns, --ps) if (*s=='<' && *ns!='<' && *ps!='<' && level[s - expr._data]==clevel) { // Less than ('<') _cimg_mp_op("Operator '<'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 1,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_lt,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_lt,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_lt,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(mem[arg1]<mem[arg2]); if (arg1==arg2) _cimg_mp_return(0); _cimg_mp_scalar2(mp_lt,arg1,arg2); } for (s = se2, ns = se1, ps = se3; s>ss; --s, --ns, --ps) if (*s=='>' && *ns!='>' && *ps!='>' && level[s - expr._data]==clevel) { // Greather than ('>') _cimg_mp_op("Operator '>'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 1,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_gt,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_gt,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_gt,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(mem[arg1]>mem[arg2]); if (arg1==arg2) _cimg_mp_return(0); _cimg_mp_scalar2(mp_gt,arg1,arg2); } for (s = se3, ns = se2; s>ss; --s, --ns) if (*s=='<' && *ns=='<' && level[s - expr._data]==clevel) { // Left bit shift ('<<') _cimg_mp_op("Operator '<<'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 2,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_bitwise_left_shift,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) { if (!arg2) _cimg_mp_return(arg1); _cimg_mp_vector2_vs(mp_bitwise_left_shift,arg1,arg2); } if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_bitwise_left_shift,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant((longT)mem[arg1]<<(unsigned int)mem[arg2]); if (!arg1) _cimg_mp_return(0); if (!arg2) _cimg_mp_return(arg1); _cimg_mp_scalar2(mp_bitwise_left_shift,arg1,arg2); } for (s = se3, ns = se2; s>ss; --s, --ns) if (*s=='>' && *ns=='>' && level[s - expr._data]==clevel) { // Right bit shift ('>>') _cimg_mp_op("Operator '>>'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 2,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_bitwise_right_shift,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) { if (!arg2) _cimg_mp_return(arg1); _cimg_mp_vector2_vs(mp_bitwise_right_shift,arg1,arg2); } if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_bitwise_right_shift,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant((longT)mem[arg1]>>(unsigned int)mem[arg2]); if (!arg1) _cimg_mp_return(0); if (!arg2) _cimg_mp_return(arg1); _cimg_mp_scalar2(mp_bitwise_right_shift,arg1,arg2); } for (ns = se1, s = se2, ps = pexpr._data + (se3 - expr._data); s>ss; --ns, --s, --ps) if (*s=='+' && (*ns!='+' || ns!=se1) && *ps!='-' && *ps!='+' && *ps!='*' && *ps!='/' && *ps!='%' && *ps!='&' && *ps!='|' && *ps!='^' && *ps!='!' && *ps!='~' && *ps!='#' && (*ps!='e' || !(ps - pexpr._data>ss - expr._data && (*(ps - 1)=='.' || (*(ps - 1)>='0' && *(ps - 1)<='9')))) && level[s - expr._data]==clevel) { // Addition ('+') _cimg_mp_op("Operator '+'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 1,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (!arg2) _cimg_mp_return(arg1); if (!arg1) _cimg_mp_return(arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_add,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_add,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_add,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(mem[arg1] + mem[arg2]); if (code) { // Try to spot linear case 'a*b + c' CImg<ulongT> &pop = code.back(); if (pop[0]==(ulongT)mp_mul && _cimg_mp_is_comp(pop[1]) && (pop[1]==arg1 || pop[1]==arg2)) { arg3 = (unsigned int)pop[1]; arg4 = (unsigned int)pop[2]; arg5 = (unsigned int)pop[3]; code.remove(); CImg<ulongT>::vector((ulongT)mp_linear_add,arg3,arg4,arg5,arg3==arg2?arg1:arg2).move_to(code); _cimg_mp_return(arg3); } } if (arg2==1) _cimg_mp_scalar1(mp_increment,arg1); if (arg1==1) _cimg_mp_scalar1(mp_increment,arg2); _cimg_mp_scalar2(mp_add,arg1,arg2); } for (ns = se1, s = se2, ps = pexpr._data + (se3 - expr._data); s>ss; --ns, --s, --ps) if (*s=='-' && (*ns!='-' || ns!=se1) && *ps!='-' && *ps!='+' && *ps!='*' && *ps!='/' && *ps!='%' && *ps!='&' && *ps!='|' && *ps!='^' && *ps!='!' && *ps!='~' && *ps!='#' && (*ps!='e' || !(ps - pexpr._data>ss - expr._data && (*(ps - 1)=='.' || (*(ps - 1)>='0' && *(ps - 1)<='9')))) && level[s - expr._data]==clevel) { // Subtraction ('-') _cimg_mp_op("Operator '-'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 1,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (!arg2) _cimg_mp_return(arg1); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_sub,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_sub,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) { if (!arg1) _cimg_mp_vector1_v(mp_minus,arg2); _cimg_mp_vector2_sv(mp_sub,arg1,arg2); } if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(mem[arg1] - mem[arg2]); if (!arg1) _cimg_mp_scalar1(mp_minus,arg2); if (code) { // Try to spot linear cases 'a*b - c' and 'c - a*b' CImg<ulongT> &pop = code.back(); if (pop[0]==(ulongT)mp_mul && _cimg_mp_is_comp(pop[1]) && (pop[1]==arg1 || pop[1]==arg2)) { arg3 = (unsigned int)pop[1]; arg4 = (unsigned int)pop[2]; arg5 = (unsigned int)pop[3]; code.remove(); CImg<ulongT>::vector((ulongT)(arg3==arg1?mp_linear_sub_left:mp_linear_sub_right), arg3,arg4,arg5,arg3==arg1?arg2:arg1).move_to(code); _cimg_mp_return(arg3); } } if (arg2==1) _cimg_mp_scalar1(mp_decrement,arg1); _cimg_mp_scalar2(mp_sub,arg1,arg2); } for (s = se3, ns = se2; s>ss; --s, --ns) if (*s=='*' && *ns=='*' && level[s - expr._data]==clevel) { // Complex multiplication ('**') _cimg_mp_op("Operator '**'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 2,se,depth1,0,is_single); _cimg_mp_check_type(arg1,1,3,2); _cimg_mp_check_type(arg2,2,3,2); if (arg2==1) _cimg_mp_return(arg1); if (arg1==1) _cimg_mp_return(arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) { pos = vector(2); CImg<ulongT>::vector((ulongT)mp_complex_mul,pos,arg1,arg2).move_to(code); _cimg_mp_return(pos); } if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_mul,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_mul,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(mem[arg1]*mem[arg2]); if (!arg1 || !arg2) _cimg_mp_return(0); _cimg_mp_scalar2(mp_mul,arg1,arg2); } for (s = se3, ns = se2; s>ss; --s, --ns) if (*s=='/' && *ns=='/' && level[s - expr._data]==clevel) { // Complex division ('//') _cimg_mp_op("Operator '//'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 2,se,depth1,0,is_single); _cimg_mp_check_type(arg1,1,3,2); _cimg_mp_check_type(arg2,2,3,2); if (arg2==1) _cimg_mp_return(arg1); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) { pos = vector(2); CImg<ulongT>::vector((ulongT)mp_complex_div_vv,pos,arg1,arg2).move_to(code); _cimg_mp_return(pos); } if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_div,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) { pos = vector(2); CImg<ulongT>::vector((ulongT)mp_complex_div_sv,pos,arg1,arg2).move_to(code); _cimg_mp_return(pos); } if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(mem[arg1]/mem[arg2]); if (!arg1) _cimg_mp_return(0); _cimg_mp_scalar2(mp_div,arg1,arg2); } for (s = se2; s>ss; --s) if (*s=='*' && level[s - expr._data]==clevel) { // Multiplication ('*') _cimg_mp_op("Operator '*'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 1,se,depth1,0,is_single); p2 = _cimg_mp_size(arg2); if (p2>0 && _cimg_mp_size(arg1)==p2*p2) { // Particular case of matrix multiplication pos = vector(p2); CImg<ulongT>::vector((ulongT)mp_matrix_mul,pos,arg1,arg2,p2,p2,1).move_to(code); _cimg_mp_return(pos); } _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (arg2==1) _cimg_mp_return(arg1); if (arg1==1) _cimg_mp_return(arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_mul,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_mul,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_mul,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(mem[arg1]*mem[arg2]); if (code) { // Try to spot double multiplication 'a*b*c' CImg<ulongT> &pop = code.back(); if (pop[0]==(ulongT)mp_mul && _cimg_mp_is_comp(pop[1]) && (pop[1]==arg1 || pop[1]==arg2)) { arg3 = (unsigned int)pop[1]; arg4 = (unsigned int)pop[2]; arg5 = (unsigned int)pop[3]; code.remove(); CImg<ulongT>::vector((ulongT)mp_mul2,arg3,arg4,arg5,arg3==arg2?arg1:arg2).move_to(code); _cimg_mp_return(arg3); } } if (!arg1 || !arg2) _cimg_mp_return(0); _cimg_mp_scalar2(mp_mul,arg1,arg2); } for (s = se2; s>ss; --s) if (*s=='/' && level[s - expr._data]==clevel) { // Division ('/') _cimg_mp_op("Operator '/'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 1,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (arg2==1) _cimg_mp_return(arg1); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_div,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_div,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_div,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(mem[arg1]/mem[arg2]); if (!arg1) _cimg_mp_return(0); _cimg_mp_scalar2(mp_div,arg1,arg2); } for (s = se2, ns = se1; s>ss; --s, --ns) if (*s=='%' && *ns!='^' && level[s - expr._data]==clevel) { // Modulo ('%') _cimg_mp_op("Operator '%'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 1,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_modulo,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_modulo,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_modulo,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(cimg::mod(mem[arg1],mem[arg2])); _cimg_mp_scalar2(mp_modulo,arg1,arg2); } if (se1>ss) { if (*ss=='+' && (*ss1!='+' || (ss2<se && *ss2>='0' && *ss2<='9'))) { // Unary plus ('+') _cimg_mp_op("Operator '+'"); _cimg_mp_return(compile(ss1,se,depth1,0,is_single)); } if (*ss=='-' && (*ss1!='-' || (ss2<se && *ss2>='0' && *ss2<='9'))) { // Unary minus ('-') _cimg_mp_op("Operator '-'"); arg1 = compile(ss1,se,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_minus,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(-mem[arg1]); _cimg_mp_scalar1(mp_minus,arg1); } if (*ss=='!') { // Logical not ('!') _cimg_mp_op("Operator '!'"); if (*ss1=='!') { // '!!expr' optimized as 'bool(expr)' arg1 = compile(ss2,se,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_bool,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant((bool)mem[arg1]); _cimg_mp_scalar1(mp_bool,arg1); } arg1 = compile(ss1,se,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_logical_not,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(!mem[arg1]); _cimg_mp_scalar1(mp_logical_not,arg1); } if (*ss=='~') { // Bitwise not ('~') _cimg_mp_op("Operator '~'"); arg1 = compile(ss1,se,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_bitwise_not,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(~(unsigned int)mem[arg1]); _cimg_mp_scalar1(mp_bitwise_not,arg1); } } for (s = se3, ns = se2; s>ss; --s, --ns) if (*s=='^' && *ns=='^' && level[s - expr._data]==clevel) { // Complex power ('^^') _cimg_mp_op("Operator '^^'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 2,se,depth1,0,is_single); _cimg_mp_check_type(arg1,1,3,2); _cimg_mp_check_type(arg2,2,3,2); if (arg2==1) _cimg_mp_return(arg1); pos = vector(2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) { CImg<ulongT>::vector((ulongT)mp_complex_pow_vv,pos,arg1,arg2).move_to(code); _cimg_mp_return(pos); } if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) { CImg<ulongT>::vector((ulongT)mp_complex_pow_vs,pos,arg1,arg2).move_to(code); _cimg_mp_return(pos); } if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) { CImg<ulongT>::vector((ulongT)mp_complex_pow_sv,pos,arg1,arg2).move_to(code); _cimg_mp_return(pos); } CImg<ulongT>::vector((ulongT)mp_complex_pow_ss,pos,arg1,arg2).move_to(code); _cimg_mp_return(pos); } for (s = se2; s>ss; --s) if (*s=='^' && level[s - expr._data]==clevel) { // Power ('^') _cimg_mp_op("Operator '^'"); arg1 = compile(ss,s,depth1,0,is_single); arg2 = compile(s + 1,se,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (arg2==1) _cimg_mp_return(arg1); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_pow,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_pow,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_pow,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(std::pow(mem[arg1],mem[arg2])); switch (arg2) { case 0 : _cimg_mp_return(1); case 2 : _cimg_mp_scalar1(mp_sqr,arg1); case 3 : _cimg_mp_scalar1(mp_pow3,arg1); case 4 : _cimg_mp_scalar1(mp_pow4,arg1); default : if (_cimg_mp_is_constant(arg2)) { if (mem[arg2]==0.5) { _cimg_mp_scalar1(mp_sqrt,arg1); } else if (mem[arg2]==0.25) { _cimg_mp_scalar1(mp_pow0_25,arg1); } } _cimg_mp_scalar2(mp_pow,arg1,arg2); } } // Percentage computation. if (*se1=='%') { arg1 = compile(ss,se1,depth1,0,is_single); arg2 = _cimg_mp_is_constant(arg1)?0:constant(100); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector2_vs(mp_div,arg1,arg2); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(mem[arg1]/100); _cimg_mp_scalar2(mp_div,arg1,arg2); } is_sth = ss1<se1 && (*ss=='+' || *ss=='-') && *ss1==*ss; // is pre-? if (is_sth || (se2>ss && (*se1=='+' || *se1=='-') && *se2==*se1)) { // Pre/post-decrement and increment if ((is_sth && *ss=='+') || (!is_sth && *se1=='+')) { _cimg_mp_op("Operator '++'"); op = mp_self_increment; } else { _cimg_mp_op("Operator '--'"); op = mp_self_decrement; } ref.assign(7); arg1 = is_sth?compile(ss2,se,depth1,ref,is_single): compile(ss,se2,depth1,ref,is_single); // Variable slot // Apply operator on a copy to prevent modifying a constant or a variable. if (*ref && (_cimg_mp_is_constant(arg1) || _cimg_mp_is_vector(arg1) || _cimg_mp_is_variable(arg1))) { if (_cimg_mp_is_vector(arg1)) arg1 = vector_copy(arg1); else arg1 = scalar1(mp_copy,arg1); } if (is_sth) pos = arg1; // Determine return index, depending on pre/post action else { if (_cimg_mp_is_vector(arg1)) pos = vector_copy(arg1); else pos = scalar1(mp_copy,arg1); } if (*ref==1) { // Vector value (scalar): V[k]++ arg3 = ref[1]; // Vector slot arg4 = ref[2]; // Index if (is_sth && p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); CImg<ulongT>::vector((ulongT)op,arg1,1).move_to(code); CImg<ulongT>::vector((ulongT)mp_vector_set_off,arg1,arg3,(ulongT)_cimg_mp_size(arg3),arg4,arg1). move_to(code); _cimg_mp_return(pos); } if (*ref==2) { // Image value (scalar): i/j[_#ind,off]++ if (!is_single) is_parallelizable = false; p1 = ref[1]; // Index is_relative = (bool)ref[2]; arg3 = ref[3]; // Offset if (is_sth && p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); CImg<ulongT>::vector((ulongT)op,arg1).move_to(code); if (p1!=~0U) { if (!listout) _cimg_mp_return(pos); CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_joff:mp_list_set_ioff), arg1,p1,arg3).move_to(code); } else { if (!imgout) _cimg_mp_return(pos); CImg<ulongT>::vector((ulongT)(is_relative?mp_set_joff:mp_set_ioff), arg1,arg3).move_to(code); } _cimg_mp_return(pos); } if (*ref==3) { // Image value (scalar): i/j(_#ind,_x,_y,_z,_c)++ if (!is_single) is_parallelizable = false; p1 = ref[1]; // Index is_relative = (bool)ref[2]; arg3 = ref[3]; // X arg4 = ref[4]; // Y arg5 = ref[5]; // Z arg6 = ref[6]; // C if (is_sth && p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); CImg<ulongT>::vector((ulongT)op,arg1).move_to(code); if (p1!=~0U) { if (!listout) _cimg_mp_return(pos); CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_jxyzc:mp_list_set_ixyzc), arg1,p1,arg3,arg4,arg5,arg6).move_to(code); } else { if (!imgout) _cimg_mp_return(pos); CImg<ulongT>::vector((ulongT)(is_relative?mp_set_jxyzc:mp_set_ixyzc), arg1,arg3,arg4,arg5,arg6).move_to(code); } _cimg_mp_return(pos); } if (*ref==4) { // Image value (vector): I/J[_#ind,off]++ if (!is_single) is_parallelizable = false; p1 = ref[1]; // Index is_relative = (bool)ref[2]; arg3 = ref[3]; // Offset if (is_sth && p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); self_vector_s(arg1,op==mp_self_increment?mp_self_add:mp_self_sub,1); if (p1!=~0U) { if (!listout) _cimg_mp_return(pos); CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_Joff_v:mp_list_set_Ioff_v), arg1,p1,arg3,_cimg_mp_size(arg1)).move_to(code); } else { if (!imgout) _cimg_mp_return(pos); CImg<ulongT>::vector((ulongT)(is_relative?mp_set_Joff_v:mp_set_Ioff_v), arg1,arg3,_cimg_mp_size(arg1)).move_to(code); } _cimg_mp_return(pos); } if (*ref==5) { // Image value (vector): I/J(_#ind,_x,_y,_z,_c)++ if (!is_single) is_parallelizable = false; p1 = ref[1]; // Index is_relative = (bool)ref[2]; arg3 = ref[3]; // X arg4 = ref[4]; // Y arg5 = ref[5]; // Z if (is_sth && p_ref) std::memcpy(p_ref,ref,ref._width*sizeof(unsigned int)); self_vector_s(arg1,op==mp_self_increment?mp_self_add:mp_self_sub,1); if (p1!=~0U) { if (!listout) _cimg_mp_return(pos); CImg<ulongT>::vector((ulongT)(is_relative?mp_list_set_Jxyz_v:mp_list_set_Ixyz_v), arg1,p1,arg3,arg4,arg5,_cimg_mp_size(arg1)).move_to(code); } else { if (!imgout) _cimg_mp_return(pos); CImg<ulongT>::vector((ulongT)(is_relative?mp_set_Jxyz_v:mp_set_Ixyz_v), arg1,arg3,arg4,arg5,_cimg_mp_size(arg1)).move_to(code); } _cimg_mp_return(pos); } if (_cimg_mp_is_vector(arg1)) { // Vector variable: V++ self_vector_s(arg1,op==mp_self_increment?mp_self_add:mp_self_sub,1); _cimg_mp_return(pos); } if (_cimg_mp_is_variable(arg1)) { // Scalar variable: s++ CImg<ulongT>::vector((ulongT)op,arg1).move_to(code); _cimg_mp_return(pos); } if (is_sth) variable_name.assign(ss2,(unsigned int)(se - ss1)); else variable_name.assign(ss,(unsigned int)(se1 - ss)); variable_name.back() = 0; cimg::strpare(variable_name,false,true); *se = saved_char; cimg::strellipsize(variable_name,64); s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Invalid %slvalue '%s', " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, _cimg_mp_is_constant(arg1)?"const ":"", variable_name._data, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } // Array-like access to vectors and image values 'i/j/I/J[_#ind,offset,_boundary]' and 'vector[offset]'. if (*se1==']' && *ss!='[') { _cimg_mp_op("Value accessor '[]'"); is_relative = *ss=='j' || *ss=='J'; s0 = s1 = std::strchr(ss,'['); if (s0) { do { --s1; } while (cimg::is_blank(*s1)); cimg::swap(*s0,*++s1); } if ((*ss=='I' || *ss=='J') && *ss1=='[' && (reserved_label[(int)*ss]==~0U || !_cimg_mp_is_vector(reserved_label[(int)*ss]))) { // Image value as a vector if (*ss2=='#') { // Index specified s0 = ss3; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; p1 = compile(ss3,s0++,depth1,0,is_single); _cimg_mp_check_list(false); } else { p1 = ~0U; s0 = ss2; } s1 = s0; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; p2 = 1 + (p1!=~0U); arg1 = compile(s0,s1,depth1,0,is_single); // Offset _cimg_mp_check_type(arg1,p2,1,0); arg2 = ~0U; if (s1<se1) { arg2 = compile(++s1,se1,depth1,0,is_single); // Boundary _cimg_mp_check_type(arg2,p2 + 1,1,0); } if (p_ref && arg2==~0U) { *p_ref = 4; p_ref[1] = p1; p_ref[2] = (unsigned int)is_relative; p_ref[3] = arg1; if (p1!=~0U && _cimg_mp_is_comp(p1)) memtype[p1] = -2; // Prevent from being used in further optimization if (_cimg_mp_is_comp(arg1)) memtype[arg1] = -2; } p2 = ~0U; // 'p2' must be the dimension of the vector-valued operand if any if (p1==~0U) p2 = imgin._spectrum; else if (_cimg_mp_is_constant(p1)) { p3 = (unsigned int)cimg::mod((int)mem[p1],listin.width()); p2 = listin[p3]._spectrum; } if (!p2) _cimg_mp_return(0); pos = vector(p2); if (p1!=~0U) { CImg<ulongT>::vector((ulongT)(is_relative?mp_list_Joff:mp_list_Ioff), pos,p1,arg1,arg2==~0U?_cimg_mp_boundary:arg2,p2).move_to(code); } else { need_input_copy = true; CImg<ulongT>::vector((ulongT)(is_relative?mp_Joff:mp_Ioff), pos,arg1,arg2==~0U?_cimg_mp_boundary:arg2,p2).move_to(code); } _cimg_mp_return(pos); } if ((*ss=='i' || *ss=='j') && *ss1=='[' && (reserved_label[(int)*ss]==~0U || !_cimg_mp_is_vector(reserved_label[(int)*ss]))) { // Image value as a scalar if (*ss2=='#') { // Index specified s0 = ss3; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; p1 = compile(ss3,s0++,depth1,0,is_single); } else { p1 = ~0U; s0 = ss2; } s1 = s0; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(s0,s1,depth1,0,is_single); // Offset arg2 = s1<se1?compile(++s1,se1,depth1,0,is_single):~0U; // Boundary if (p_ref && arg2==~0U) { *p_ref = 2; p_ref[1] = p1; p_ref[2] = (unsigned int)is_relative; p_ref[3] = arg1; if (p1!=~0U && _cimg_mp_is_comp(p1)) memtype[p1] = -2; // Prevent from being used in further optimization if (_cimg_mp_is_comp(arg1)) memtype[arg1] = -2; } if (p1!=~0U) { if (!listin) _cimg_mp_return(0); pos = scalar3(is_relative?mp_list_joff:mp_list_ioff,p1,arg1,arg2==~0U?_cimg_mp_boundary:arg2); } else { if (!imgin) _cimg_mp_return(0); need_input_copy = true; pos = scalar2(is_relative?mp_joff:mp_ioff,arg1,arg2==~0U?_cimg_mp_boundary:arg2); } memtype[pos] = -2; // Prevent from being used in further optimization _cimg_mp_return(pos); } s0 = se1; while (s0>ss && (*s0!='[' || level[s0 - expr._data]!=clevel)) --s0; if (s0>ss) { // Vector value arg1 = compile(ss,s0,depth1,0,is_single); if (_cimg_mp_is_scalar(arg1)) { variable_name.assign(ss,(unsigned int)(s0 - ss + 1)).back() = 0; *se = saved_char; cimg::strellipsize(variable_name,64); s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Array brackets used on non-vector variable '%s', " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, variable_name._data, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } s1 = s0 + 1; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; if (s1<se1) { // Two or three arguments -> sub-vector extraction p1 = _cimg_mp_size(arg1); arg2 = compile(++s0,s1,depth1,0,is_single); // Starting index s0 = ++s1; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; arg3 = compile(s1,s0,depth1,0,is_single); // Length arg4 = s0<se1?compile(++s0,se1,depth1,0,is_single):1; // Step _cimg_mp_check_constant(arg3,2,3); arg3 = (unsigned int)mem[arg3]; pos = vector(arg3); CImg<ulongT>::vector((ulongT)mp_vector_crop,pos,arg1,p1,arg2,arg3,arg4).move_to(code); _cimg_mp_return(pos); } // One argument -> vector value reference arg2 = compile(++s0,se1,depth1,0,is_single); if (_cimg_mp_is_constant(arg2)) { // Constant index nb = (int)mem[arg2]; if (nb>=0 && nb<(int)_cimg_mp_size(arg1)) _cimg_mp_return(arg1 + 1 + nb); variable_name.assign(ss,(unsigned int)(s0 - ss)).back() = 0; *se = saved_char; cimg::strellipsize(variable_name,64); s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: Out-of-bounds reference '%s[%d]' " "(vector '%s' has dimension %u), " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function, variable_name._data,nb, variable_name._data,_cimg_mp_size(arg1), s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } if (p_ref) { *p_ref = 1; p_ref[1] = arg1; p_ref[2] = arg2; if (_cimg_mp_is_comp(arg2)) memtype[arg2] = -2; // Prevent from being used in further optimization } pos = scalar3(mp_vector_off,arg1,_cimg_mp_size(arg1),arg2); memtype[pos] = -2; // Prevent from being used in further optimization _cimg_mp_return(pos); } } // Look for a function call, an access to image value, or a parenthesis. if (*se1==')') { if (*ss=='(') _cimg_mp_return(compile(ss1,se1,depth1,p_ref,is_single)); // Simple parentheses _cimg_mp_op("Value accessor '()'"); is_relative = *ss=='j' || *ss=='J'; s0 = s1 = std::strchr(ss,'('); if (s0) { do { --s1; } while (cimg::is_blank(*s1)); cimg::swap(*s0,*++s1); } // I/J(_#ind,_x,_y,_z,_interpolation,_boundary_conditions) if ((*ss=='I' || *ss=='J') && *ss1=='(') { // Image value as scalar if (*ss2=='#') { // Index specified s0 = ss3; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; p1 = compile(ss3,s0++,depth1,0,is_single); _cimg_mp_check_list(false); } else { p1 = ~0U; s0 = ss2; } arg1 = is_relative?0U:(unsigned int)_cimg_mp_slot_x; arg2 = is_relative?0U:(unsigned int)_cimg_mp_slot_y; arg3 = is_relative?0U:(unsigned int)_cimg_mp_slot_z; arg4 = arg5 = ~0U; if (s0<se1) { s1 = s0; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(s0,s1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) { // Coordinates specified as a vector p2 = _cimg_mp_size(arg1); ++arg1; if (p2>1) { arg2 = arg1 + 1; if (p2>2) arg3 = arg2 + 1; } if (s1<se1) { s2 = ++s1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg4 = compile(s1,s2,depth1,0,is_single); arg5 = s2<se1?compile(++s2,se1,depth1,0,is_single):~0U; } } else if (s1<se1) { s2 = ++s1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(s1,s2,depth1,0,is_single); if (s2<se1) { s3 = ++s2; while (s3<se1 && (*s3!=',' || level[s3 - expr._data]!=clevel1)) ++s3; arg3 = compile(s2,s3,depth1,0,is_single); if (s3<se1) { s2 = ++s3; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg4 = compile(s3,s2,depth1,0,is_single); arg5 = s2<se1?compile(++s2,se1,depth1,0,is_single):~0U; } } } } if (p_ref && arg4==~0U && arg5==~0U) { *p_ref = 5; p_ref[1] = p1; p_ref[2] = (unsigned int)is_relative; p_ref[3] = arg1; p_ref[4] = arg2; p_ref[5] = arg3; if (p1!=~0U && _cimg_mp_is_comp(p1)) memtype[p1] = -2; // Prevent from being used in further optimization if (_cimg_mp_is_comp(arg1)) memtype[arg1] = -2; if (_cimg_mp_is_comp(arg2)) memtype[arg2] = -2; if (_cimg_mp_is_comp(arg3)) memtype[arg3] = -2; } p2 = ~0U; // 'p2' must be the dimension of the vector-valued operand if any if (p1==~0U) p2 = imgin._spectrum; else if (_cimg_mp_is_constant(p1)) { p3 = (unsigned int)cimg::mod((int)mem[p1],listin.width()); p2 = listin[p3]._spectrum; } if (!p2) _cimg_mp_return(0); pos = vector(p2); if (p1!=~0U) CImg<ulongT>::vector((ulongT)(is_relative?mp_list_Jxyz:mp_list_Ixyz), pos,p1,arg1,arg2,arg3, arg4==~0U?_cimg_mp_interpolation:arg4, arg5==~0U?_cimg_mp_boundary:arg5,p2).move_to(code); else { need_input_copy = true; CImg<ulongT>::vector((ulongT)(is_relative?mp_Jxyz:mp_Ixyz), pos,arg1,arg2,arg3, arg4==~0U?_cimg_mp_interpolation:arg4, arg5==~0U?_cimg_mp_boundary:arg5,p2).move_to(code); } _cimg_mp_return(pos); } // i/j(_#ind,_x,_y,_z,_c,_interpolation,_boundary_conditions) if ((*ss=='i' || *ss=='j') && *ss1=='(') { // Image value as scalar if (*ss2=='#') { // Index specified s0 = ss3; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; p1 = compile(ss3,s0++,depth1,0,is_single); } else { p1 = ~0U; s0 = ss2; } arg1 = is_relative?0U:(unsigned int)_cimg_mp_slot_x; arg2 = is_relative?0U:(unsigned int)_cimg_mp_slot_y; arg3 = is_relative?0U:(unsigned int)_cimg_mp_slot_z; arg4 = is_relative?0U:(unsigned int)_cimg_mp_slot_c; arg5 = arg6 = ~0U; if (s0<se1) { s1 = s0; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(s0,s1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) { // Coordinates specified as a vector p2 = _cimg_mp_size(arg1); ++arg1; if (p2>1) { arg2 = arg1 + 1; if (p2>2) { arg3 = arg2 + 1; if (p2>3) arg4 = arg3 + 1; } } if (s1<se1) { s2 = ++s1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg5 = compile(s1,s2,depth1,0,is_single); arg6 = s2<se1?compile(++s2,se1,depth1,0,is_single):~0U; } } else if (s1<se1) { s2 = ++s1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(s1,s2,depth1,0,is_single); if (s2<se1) { s3 = ++s2; while (s3<se1 && (*s3!=',' || level[s3 - expr._data]!=clevel1)) ++s3; arg3 = compile(s2,s3,depth1,0,is_single); if (s3<se1) { s2 = ++s3; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg4 = compile(s3,s2,depth1,0,is_single); if (s2<se1) { s3 = ++s2; while (s3<se1 && (*s3!=',' || level[s3 - expr._data]!=clevel1)) ++s3; arg5 = compile(s2,s3,depth1,0,is_single); arg6 = s3<se1?compile(++s3,se1,depth1,0,is_single):~0U; } } } } } if (p_ref && arg5==~0U && arg6==~0U) { *p_ref = 3; p_ref[1] = p1; p_ref[2] = (unsigned int)is_relative; p_ref[3] = arg1; p_ref[4] = arg2; p_ref[5] = arg3; p_ref[6] = arg4; if (p1!=~0U && _cimg_mp_is_comp(p1)) memtype[p1] = -2; // Prevent from being used in further optimization if (_cimg_mp_is_comp(arg1)) memtype[arg1] = -2; if (_cimg_mp_is_comp(arg2)) memtype[arg2] = -2; if (_cimg_mp_is_comp(arg3)) memtype[arg3] = -2; if (_cimg_mp_is_comp(arg4)) memtype[arg4] = -2; } if (p1!=~0U) { if (!listin) _cimg_mp_return(0); pos = scalar7(is_relative?mp_list_jxyzc:mp_list_ixyzc, p1,arg1,arg2,arg3,arg4, arg5==~0U?_cimg_mp_interpolation:arg5, arg6==~0U?_cimg_mp_boundary:arg6); } else { if (!imgin) _cimg_mp_return(0); need_input_copy = true; pos = scalar6(is_relative?mp_jxyzc:mp_ixyzc, arg1,arg2,arg3,arg4, arg5==~0U?_cimg_mp_interpolation:arg5, arg6==~0U?_cimg_mp_boundary:arg6); } memtype[pos] = -2; // Prevent from being used in further optimization _cimg_mp_return(pos); } // Mathematical functions. switch (*ss) { case '_' : if (*ss1=='(') // Skip arguments _cimg_mp_return_nan(); break; case 'a' : if (!std::strncmp(ss,"abs(",4)) { // Absolute value _cimg_mp_op("Function 'abs()'"); arg1 = compile(ss4,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_abs,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(cimg::abs(mem[arg1])); _cimg_mp_scalar1(mp_abs,arg1); } if (!std::strncmp(ss,"acos(",5)) { // Arccos _cimg_mp_op("Function 'acos()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_acos,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::acos(mem[arg1])); _cimg_mp_scalar1(mp_acos,arg1); } if (!std::strncmp(ss,"acosh(",6)) { // Hyperbolic arccosine _cimg_mp_op("Function 'acosh()'"); arg1 = compile(ss6,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_acosh,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(cimg::acosh(mem[arg1])); _cimg_mp_scalar1(mp_acosh,arg1); } if (!std::strncmp(ss,"asinh(",6)) { // Hyperbolic arcsine _cimg_mp_op("Function 'asinh()'"); arg1 = compile(ss6,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_asinh,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(cimg::asinh(mem[arg1])); _cimg_mp_scalar1(mp_asinh,arg1); } if (!std::strncmp(ss,"atanh(",6)) { // Hyperbolic arctangent _cimg_mp_op("Function 'atanh()'"); arg1 = compile(ss6,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_atanh,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(cimg::atanh(mem[arg1])); _cimg_mp_scalar1(mp_atanh,arg1); } if (!std::strncmp(ss,"arg(",4)) { // Nth argument _cimg_mp_op("Function 'arg()'"); s1 = ss4; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss4,s1,depth1,0,is_single); _cimg_mp_check_type(arg1,1,1,0); s2 = ++s1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(s1,s2,depth1,0,is_single); p2 = _cimg_mp_size(arg2); p3 = 3; CImg<ulongT>::vector((ulongT)mp_arg,0,0,p2,arg1,arg2).move_to(l_opcode); for (s = ++s2; s<se; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; arg3 = compile(s,ns,depth1,0,is_single); _cimg_mp_check_type(arg3,p3,p2?2:1,p2); CImg<ulongT>::vector(arg3).move_to(l_opcode); ++p3; s = ns; } (l_opcode>'y').move_to(opcode); opcode[2] = opcode._height; if (_cimg_mp_is_constant(arg1)) { p3-=1; // Number of args arg1 = (unsigned int)(mem[arg1]<0?mem[arg1] + p3:mem[arg1]); if (arg1<p3) _cimg_mp_return(opcode[4 + arg1]); if (p2) { pos = vector(p2); std::memset(&mem[pos] + 1,0,p2*sizeof(double)); _cimg_mp_return(pos); } else _cimg_mp_return(0); } pos = opcode[1] = p2?vector(p2):scalar(); opcode.move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"asin(",5)) { // Arcsin _cimg_mp_op("Function 'asin()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_asin,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::asin(mem[arg1])); _cimg_mp_scalar1(mp_asin,arg1); } if (!std::strncmp(ss,"atan(",5)) { // Arctan _cimg_mp_op("Function 'atan()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_atan,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::atan(mem[arg1])); _cimg_mp_scalar1(mp_atan,arg1); } if (!std::strncmp(ss,"atan2(",6)) { // Arctan2 _cimg_mp_op("Function 'atan2()'"); s1 = ss6; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss6,s1,depth1,0,is_single); arg2 = compile(++s1,se1,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_atan2,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_atan2,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_atan2,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(std::atan2(mem[arg1],mem[arg2])); _cimg_mp_scalar2(mp_atan2,arg1,arg2); } break; case 'b' : if (!std::strncmp(ss,"break(",6)) { // Complex absolute value if (pexpr[se2 - expr._data]=='(') { // no arguments? CImg<ulongT>::vector((ulongT)mp_break,_cimg_mp_slot_nan).move_to(code); _cimg_mp_return_nan(); } } if (!std::strncmp(ss,"breakpoint(",11)) { // Break point (for abort test) _cimg_mp_op("Function 'breakpoint()'"); if (pexpr[se2 - expr._data]=='(') { // no arguments? CImg<ulongT>::vector((ulongT)mp_breakpoint,_cimg_mp_slot_nan).move_to(code); _cimg_mp_return_nan(); } } if (!std::strncmp(ss,"bool(",5)) { // Boolean cast _cimg_mp_op("Function 'bool()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_bool,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant((bool)mem[arg1]); _cimg_mp_scalar1(mp_bool,arg1); } if (!std::strncmp(ss,"begin(",6)) { // Begin _cimg_mp_op("Function 'begin()'"); code.swap(code_begin); arg1 = compile(ss6,se1,depth1,p_ref,true); code.swap(code_begin); _cimg_mp_return(arg1); } break; case 'c' : if (!std::strncmp(ss,"cabs(",5)) { // Complex absolute value _cimg_mp_op("Function 'cabs()'"); arg1 = compile(ss5,se1,depth1,0,is_single); _cimg_mp_check_type(arg1,0,2,2); _cimg_mp_scalar2(mp_complex_abs,arg1 + 1,arg1 + 2); } if (!std::strncmp(ss,"carg(",5)) { // Complex argument _cimg_mp_op("Function 'carg()'"); arg1 = compile(ss5,se1,depth1,0,is_single); _cimg_mp_check_type(arg1,0,2,2); _cimg_mp_scalar2(mp_atan2,arg1 + 2,arg1 + 1); } if (!std::strncmp(ss,"cats(",5)) { // Concatenate strings _cimg_mp_op("Function 'cats()'"); CImg<ulongT>::vector((ulongT)mp_cats,0,0,0).move_to(l_opcode); arg1 = 0; for (s = ss5; s<se; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; arg1 = compile(s,ns,depth1,0,is_single); CImg<ulongT>::vector(arg1,_cimg_mp_size(arg1)).move_to(l_opcode); s = ns; } _cimg_mp_check_constant(arg1,1,3); // Last argument = output vector size l_opcode.remove(); (l_opcode>'y').move_to(opcode); p1 = (unsigned int)mem[arg1]; pos = vector(p1); opcode[1] = pos; opcode[2] = p1; opcode[3] = opcode._height; opcode.move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"cbrt(",5)) { // Cubic root _cimg_mp_op("Function 'cbrt()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_cbrt,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(cimg::cbrt(mem[arg1])); _cimg_mp_scalar1(mp_cbrt,arg1); } if (!std::strncmp(ss,"cconj(",6)) { // Complex conjugate _cimg_mp_op("Function 'cconj()'"); arg1 = compile(ss6,se1,depth1,0,is_single); _cimg_mp_check_type(arg1,0,2,2); pos = vector(2); CImg<ulongT>::vector((ulongT)mp_complex_conj,pos,arg1).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"ceil(",5)) { // Ceil _cimg_mp_op("Function 'ceil()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_ceil,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::ceil(mem[arg1])); _cimg_mp_scalar1(mp_ceil,arg1); } if (!std::strncmp(ss,"cexp(",5)) { // Complex exponential _cimg_mp_op("Function 'cexp()'"); arg1 = compile(ss5,se1,depth1,0,is_single); _cimg_mp_check_type(arg1,0,2,2); pos = vector(2); CImg<ulongT>::vector((ulongT)mp_complex_exp,pos,arg1).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"clog(",5)) { // Complex logarithm _cimg_mp_op("Function 'clog()'"); arg1 = compile(ss5,se1,depth1,0,is_single); _cimg_mp_check_type(arg1,0,2,2); pos = vector(2); CImg<ulongT>::vector((ulongT)mp_complex_log,pos,arg1).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"continue(",9)) { // Complex absolute value if (pexpr[se2 - expr._data]=='(') { // no arguments? CImg<ulongT>::vector((ulongT)mp_continue,_cimg_mp_slot_nan).move_to(code); _cimg_mp_return_nan(); } } if (!std::strncmp(ss,"copy(",5)) { // Memory copy _cimg_mp_op("Function 'copy()'"); ref.assign(14); s1 = ss5; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = p1 = compile(ss5,s1,depth1,ref,is_single); s2 = ++s1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(s1,s2,depth1,ref._data + 7,is_single); arg3 = arg4 = arg5 = ~0U; arg6 = 1; if (s2<se1) { s3 = ++s2; while (s3<se1 && (*s3!=',' || level[s3 - expr._data]!=clevel1)) ++s3; arg3 = compile(s2,s3,depth1,0,is_single); if (s3<se1) { s1 = ++s3; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg4 = compile(s3,s1,depth1,0,is_single); if (s1<se1) { s2 = ++s1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg5 = compile(s1,s2,depth1,0,is_single); arg6 = s2<se1?compile(++s2,se1,depth1,0,is_single):1; } } } if (_cimg_mp_is_vector(arg1)) { if (!ref[0]) ++arg1; else if (ref[0]>=4 && arg4==~0U) arg4 = scalar1(mp_image_whd,ref[1]); } if (_cimg_mp_is_vector(arg2)) { if (arg3==~0U) arg3 = constant(_cimg_mp_size(arg2)); if (!ref[7]) ++arg2; if (ref[7]>=4 && arg5==~0U) arg5 = scalar1(mp_image_whd,ref[8]); } if (arg3==~0U) arg3 = 1; if (arg4==~0U) arg4 = 1; if (arg5==~0U) arg5 = 1; _cimg_mp_check_type(arg3,3,1,0); _cimg_mp_check_type(arg4,4,1,0); _cimg_mp_check_type(arg5,5,1,0); _cimg_mp_check_type(arg6,5,1,0); CImg<ulongT>(1,22).move_to(code); code.back().get_shared_rows(0,7).fill((ulongT)mp_memcopy,p1,arg1,arg2,arg3,arg4,arg5,arg6); code.back().get_shared_rows(8,21).fill(ref); _cimg_mp_return(p1); } if (!std::strncmp(ss,"cos(",4)) { // Cosine _cimg_mp_op("Function 'cos()'"); arg1 = compile(ss4,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_cos,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::cos(mem[arg1])); _cimg_mp_scalar1(mp_cos,arg1); } if (!std::strncmp(ss,"cosh(",5)) { // Hyperbolic cosine _cimg_mp_op("Function 'cosh()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_cosh,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::cosh(mem[arg1])); _cimg_mp_scalar1(mp_cosh,arg1); } if (!std::strncmp(ss,"critical(",9)) { // Critical section (single thread at a time) _cimg_mp_op("Function 'critical()'"); p1 = code._width; arg1 = compile(ss + 9,se1,depth1,p_ref,true); CImg<ulongT>::vector((ulongT)mp_critical,arg1,code._width - p1).move_to(code,p1); _cimg_mp_return(arg1); } if (!std::strncmp(ss,"crop(",5)) { // Image crop _cimg_mp_op("Function 'crop()'"); if (*ss5=='#') { // Index specified s0 = ss6; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; p1 = compile(ss6,s0++,depth1,0,is_single); _cimg_mp_check_list(false); } else { p1 = ~0U; s0 = ss5; need_input_copy = true; } pos = 0; is_sth = false; // Coordinates specified as a vector? if (s0<se1) for (s = s0; s<se; ++s, ++pos) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; arg1 = compile(s,ns,depth1,0,is_single); if (!pos && _cimg_mp_is_vector(arg1)) { // Coordinates specified as a vector opcode = CImg<ulongT>::sequence(_cimg_mp_size(arg1),arg1 + 1, arg1 + (ulongT)_cimg_mp_size(arg1)); opcode.resize(1,std::min(opcode._height,4U),1,1,0).move_to(l_opcode); is_sth = true; } else { _cimg_mp_check_type(arg1,pos + 1,1,0); CImg<ulongT>::vector(arg1).move_to(l_opcode); } s = ns; } (l_opcode>'y').move_to(opcode); arg1 = 0; arg2 = (p1!=~0U); switch (opcode._height) { case 0 : case 1 : CImg<ulongT>::vector(0,0,0,0,~0U,~0U,~0U,~0U,0).move_to(opcode); break; case 2 : CImg<ulongT>::vector(*opcode,0,0,0,opcode[1],~0U,~0U,~0U,_cimg_mp_boundary).move_to(opcode); arg1 = arg2 + 2; break; case 3 : CImg<ulongT>::vector(*opcode,0,0,0,opcode[1],~0U,~0U,~0U,opcode[2]).move_to(opcode); arg1 = arg2 + 2; break; case 4 : CImg<ulongT>::vector(*opcode,opcode[1],0,0,opcode[2],opcode[3],~0U,~0U,_cimg_mp_boundary). move_to(opcode); arg1 = arg2 + (is_sth?2:3); break; case 5 : CImg<ulongT>::vector(*opcode,opcode[1],0,0,opcode[2],opcode[3],~0U,~0U,opcode[4]). move_to(opcode); arg1 = arg2 + (is_sth?2:3); break; case 6 : CImg<ulongT>::vector(*opcode,opcode[1],opcode[2],0,opcode[3],opcode[4],opcode[5],~0U, _cimg_mp_boundary).move_to(opcode); arg1 = arg2 + (is_sth?2:4); break; case 7 : CImg<ulongT>::vector(*opcode,opcode[1],opcode[2],0,opcode[3],opcode[4],opcode[5],~0U, opcode[6]).move_to(opcode); arg1 = arg2 + (is_sth?2:4); break; case 8 : CImg<ulongT>::vector(*opcode,opcode[1],opcode[2],opcode[3],opcode[4],opcode[5],opcode[6], opcode[7],_cimg_mp_boundary).move_to(opcode); arg1 = arg2 + (is_sth?2:5); break; case 9 : arg1 = arg2 + (is_sth?2:5); break; default : // Error -> too much arguments *se = saved_char; s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Too much arguments specified, " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } _cimg_mp_check_type((unsigned int)*opcode,arg2 + 1,1,0); _cimg_mp_check_type((unsigned int)opcode[1],arg2 + 1 + (is_sth?0:1),1,0); _cimg_mp_check_type((unsigned int)opcode[2],arg2 + 1 + (is_sth?0:2),1,0); _cimg_mp_check_type((unsigned int)opcode[3],arg2 + 1 + (is_sth?0:3),1,0); if (opcode[4]!=(ulongT)~0U) { _cimg_mp_check_constant((unsigned int)opcode[4],arg1,3); opcode[4] = (ulongT)mem[opcode[4]]; } if (opcode[5]!=(ulongT)~0U) { _cimg_mp_check_constant((unsigned int)opcode[5],arg1 + 1,3); opcode[5] = (ulongT)mem[opcode[5]]; } if (opcode[6]!=(ulongT)~0U) { _cimg_mp_check_constant((unsigned int)opcode[6],arg1 + 2,3); opcode[6] = (ulongT)mem[opcode[6]]; } if (opcode[7]!=(ulongT)~0U) { _cimg_mp_check_constant((unsigned int)opcode[7],arg1 + 3,3); opcode[7] = (ulongT)mem[opcode[7]]; } _cimg_mp_check_type((unsigned int)opcode[8],arg1 + 4,1,0); if (opcode[4]==(ulongT)~0U || opcode[5]==(ulongT)~0U || opcode[6]==(ulongT)~0U || opcode[7]==(ulongT)~0U) { if (p1!=~0U) { _cimg_mp_check_constant(p1,1,1); p1 = (unsigned int)cimg::mod((int)mem[p1],listin.width()); } const CImg<T> &img = p1!=~0U?listin[p1]:imgin; if (!img) { *se = saved_char; s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Cannot crop empty image when " "some xyzc-coordinates are unspecified, in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } if (opcode[4]==(ulongT)~0U) opcode[4] = (ulongT)img._width; if (opcode[5]==(ulongT)~0U) opcode[5] = (ulongT)img._height; if (opcode[6]==(ulongT)~0U) opcode[6] = (ulongT)img._depth; if (opcode[7]==(ulongT)~0U) opcode[7] = (ulongT)img._spectrum; } pos = vector((unsigned int)(opcode[4]*opcode[5]*opcode[6]*opcode[7])); CImg<ulongT>::vector((ulongT)mp_crop, pos,p1, *opcode,opcode[1],opcode[2],opcode[3], opcode[4],opcode[5],opcode[6],opcode[7], opcode[8]).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"cross(",6)) { // Cross product _cimg_mp_op("Function 'cross()'"); s1 = ss6; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss6,s1,depth1,0,is_single); arg2 = compile(++s1,se1,depth1,0,is_single); _cimg_mp_check_type(arg1,1,2,3); _cimg_mp_check_type(arg2,2,2,3); pos = vector(3); CImg<ulongT>::vector((ulongT)mp_cross,pos,arg1,arg2).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"cut(",4)) { // Cut _cimg_mp_op("Function 'cut()'"); s1 = ss4; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss4,s1,depth1,0,is_single); s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(++s1,s2,depth1,0,is_single); arg3 = compile(++s2,se1,depth1,0,is_single); _cimg_mp_check_type(arg2,2,1,0); _cimg_mp_check_type(arg3,3,1,0); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector3_vss(mp_cut,arg1,arg2,arg3); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2) && _cimg_mp_is_constant(arg3)) { val = mem[arg1]; val1 = mem[arg2]; val2 = mem[arg3]; _cimg_mp_constant(val<val1?val1:val>val2?val2:val); } _cimg_mp_scalar3(mp_cut,arg1,arg2,arg3); } /* if (!std::strncmp(ss,"convolve(",9) || !std::strncmp(ss,"correlate(",10)) { // Convolve & Correlate is_sth = *ss2=='n'; // is_convolve? _cimg_mp_op(is_sth?"Function 'convolve()'":"Function 'correlate()'"); s0 = ss + (is_sth?9:10); s1 = s0; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(s0,s1,depth1,0,is_single); s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(++s1,s2,depth1,0,is_single); arg3 = _cimg_mp_boundary; arg4 = 0; if (s2<se1) { s1 = s2 + 1; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg3 = compile(++s2,s1,depth1,0,is_single); arg4 = s1<se1?compile(++s1,se1,depth1,0,is_single):0; } _cimg_mp_check_type(arg1,1,2,0); _cimg_mp_check_type(arg2,2,2,0); _cimg_mp_check_type(arg3,3,1,0); _cimg_mp_check_type(arg4,4,1,0); p1 = _cimg_mp_size(arg1); p2 = _cimg_mp_size(arg2); pos = vector(p1); CImg<ulongT>::vector((ulongT)is_convolve?mp_matrix_convolve:mp_matrix_correlate,pos, arg1,arg2,arg4,p1,p2).move_to(code); _cimg_mp_return(pos); } */ break; case 'd' : if (*ss1=='(') { // Image depth _cimg_mp_op("Function 'd()'"); if (*ss2=='#') { // Index specified p1 = compile(ss3,se1,depth1,0,is_single); _cimg_mp_check_list(false); } else { if (ss2!=se1) break; p1 = ~0U; } pos = scalar(); CImg<ulongT>::vector((ulongT)mp_image_d,pos,p1).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"date(",5)) { // Current date or file date _cimg_mp_op("Function 'date()'"); s1 = ss5; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = ss5!=se1?compile(ss5,s1,depth1,0,is_single):~0U; arg2 = s1<se1?compile(++s1,se1,depth1,0,is_single):~0U; if (arg2!=~0U) _cimg_mp_check_type(arg2,1,2,0); pos = arg1==~0U || _cimg_mp_is_vector(arg1)?vector(arg1==~0U?7:_cimg_mp_size(arg1)):scalar(); CImg<ulongT>::vector((ulongT)mp_date,pos,_cimg_mp_size(pos), arg1,arg1==~0U?~0U:_cimg_mp_size(arg1), arg2,arg2==~0U?~0U:_cimg_mp_size(arg2)).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"debug(",6)) { // Print debug info _cimg_mp_op("Function 'debug()'"); p1 = code._width; arg1 = compile(ss6,se1,depth1,p_ref,is_single); *se1 = 0; variable_name.assign(CImg<charT>::string(ss6,true,true).unroll('y'),true); cimg::strpare(variable_name,false,true); ((CImg<ulongT>::vector((ulongT)mp_debug,arg1,0,code._width - p1), variable_name)>'y').move_to(opcode); opcode[2] = opcode._height; opcode.move_to(code,p1); *se1 = ')'; _cimg_mp_return(arg1); } if (!std::strncmp(ss,"display(",8)) { // Display memory, vector or image _cimg_mp_op("Function 'display()'"); if (pexpr[se2 - expr._data]=='(') { // no arguments? CImg<ulongT>::vector((ulongT)mp_display_memory,_cimg_mp_slot_nan).move_to(code); _cimg_mp_return_nan(); } if (*ss8!='#') { // Vector s1 = ss8; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss8,s1,depth1,0,is_single); arg2 = 0; arg3 = arg4 = arg5 = 1; if (s1<se1) { s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(s1 + 1,s2,depth1,0,is_single); if (s2<se1) { s3 = ++s2; while (s3<se1 && (*s3!=',' || level[s3 - expr._data]!=clevel1)) ++s3; arg3 = compile(s2,s3,depth1,0,is_single); if (s3<se1) { s2 = ++s3; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg4 = compile(s3,s2,depth1,0,is_single); arg5 = s2<se1?compile(++s2,se1,depth1,0,is_single):0; } } } _cimg_mp_check_type(arg2,2,1,0); _cimg_mp_check_type(arg3,3,1,0); _cimg_mp_check_type(arg4,4,1,0); _cimg_mp_check_type(arg5,5,1,0); c1 = *s1; *s1 = 0; variable_name.assign(CImg<charT>::string(ss8,true,true).unroll('y'),true); cimg::strpare(variable_name,false,true); if (_cimg_mp_is_vector(arg1)) ((CImg<ulongT>::vector((ulongT)mp_vector_print,arg1,0,(ulongT)_cimg_mp_size(arg1),0), variable_name)>'y').move_to(opcode); else ((CImg<ulongT>::vector((ulongT)mp_print,arg1,0,0), variable_name)>'y').move_to(opcode); opcode[2] = opcode._height; opcode.move_to(code); ((CImg<ulongT>::vector((ulongT)mp_display,arg1,0,(ulongT)_cimg_mp_size(arg1), arg2,arg3,arg4,arg5), variable_name)>'y').move_to(opcode); opcode[2] = opcode._height; opcode.move_to(code); *s1 = c1; _cimg_mp_return(arg1); } else { // Image p1 = compile(ss8 + 1,se1,depth1,0,is_single); _cimg_mp_check_list(true); CImg<ulongT>::vector((ulongT)mp_image_display,_cimg_mp_slot_nan,p1).move_to(code); _cimg_mp_return_nan(); } } if (!std::strncmp(ss,"det(",4)) { // Matrix determinant _cimg_mp_op("Function 'det()'"); arg1 = compile(ss4,se1,depth1,0,is_single); _cimg_mp_check_matrix_square(arg1,1); p1 = (unsigned int)cimg::round(std::sqrt((float)_cimg_mp_size(arg1))); _cimg_mp_scalar2(mp_det,arg1,p1); } if (!std::strncmp(ss,"diag(",5)) { // Diagonal matrix _cimg_mp_op("Function 'diag()'"); CImg<ulongT>::vector((ulongT)mp_diag,0,0).move_to(l_opcode); for (s = ss5; s<se; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; arg2 = compile(s,ns,depth1,0,is_single); if (_cimg_mp_is_vector(arg2)) CImg<ulongT>::sequence(_cimg_mp_size(arg2),arg2 + 1, arg2 + (ulongT)_cimg_mp_size(arg2)). move_to(l_opcode); else CImg<ulongT>::vector(arg2).move_to(l_opcode); s = ns; } (l_opcode>'y').move_to(opcode); arg1 = opcode._height - 3; pos = vector(arg1*arg1); opcode[1] = pos; opcode[2] = opcode._height; opcode.move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"dot(",4)) { // Dot product _cimg_mp_op("Function 'dot()'"); s1 = ss4; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss4,s1,depth1,0,is_single); arg2 = compile(++s1,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) { _cimg_mp_check_type(arg2,2,2,_cimg_mp_size(arg1)); _cimg_mp_scalar3(mp_dot,arg1,arg2,_cimg_mp_size(arg1)); } _cimg_mp_check_type(arg2,2,1,0); _cimg_mp_scalar2(mp_mul,arg1,arg2); } if (!std::strncmp(ss,"do(",3)) { // Do..while _cimg_mp_op("Function 'do()'"); s0 = *ss2=='('?ss3:ss8; s1 = s0; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = code._width; arg6 = mempos; p1 = compile(s0,s1,depth1,0,is_single); // Body arg2 = code._width; p2 = s1<se1?compile(++s1,se1,depth1,0,is_single):p1; // Condition _cimg_mp_check_type(p2,2,1,0); CImg<ulongT>::vector((ulongT)mp_do,p1,p2,arg2 - arg1,code._width - arg2,_cimg_mp_size(p1), p1>=arg6 && !_cimg_mp_is_constant(p1), p2>=arg6 && !_cimg_mp_is_constant(p2)).move_to(code,arg1); _cimg_mp_return(p1); } if (!std::strncmp(ss,"draw(",5)) { // Draw image if (!is_single) is_parallelizable = false; _cimg_mp_op("Function 'draw()'"); if (*ss5=='#') { // Index specified s0 = ss6; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; p1 = compile(ss6,s0++,depth1,0,is_single); _cimg_mp_check_list(true); } else { p1 = ~0U; s0 = ss5; } s1 = s0; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(s0,s1,depth1,0,is_single); arg2 = is_relative?0U:(unsigned int)_cimg_mp_slot_x; arg3 = is_relative?0U:(unsigned int)_cimg_mp_slot_y; arg4 = is_relative?0U:(unsigned int)_cimg_mp_slot_z; arg5 = is_relative?0U:(unsigned int)_cimg_mp_slot_c; s0 = se1; if (s1<se1) { s0 = s1 + 1; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; arg2 = compile(++s1,s0,depth1,0,is_single); if (_cimg_mp_is_vector(arg2)) { // Coordinates specified as a vector p2 = _cimg_mp_size(arg2); ++arg2; if (p2>1) { arg3 = arg2 + 1; if (p2>2) { arg4 = arg3 + 1; if (p2>3) arg5 = arg4 + 1; } } ++s0; is_sth = true; } else { if (s0<se1) { is_sth = p1!=~0U; s1 = s0 + 1; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg3 = compile(++s0,s1,depth1,0,is_single); _cimg_mp_check_type(arg3,is_sth?4:3,1,0); if (s1<se1) { s0 = s1 + 1; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; arg4 = compile(++s1,s0,depth1,0,is_single); _cimg_mp_check_type(arg4,is_sth?5:4,1,0); if (s0<se1) { s1 = s0 + 1; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg5 = compile(++s0,s1,depth1,0,is_single); _cimg_mp_check_type(arg5,is_sth?6:5,1,0); s0 = ++s1; } } } is_sth = false; } } l_opcode.assign(); // Don't use 'opcode': it can be modified by further calls to 'compile()'! CImg<ulongT>::vector((ulongT)mp_draw,arg1,(ulongT)_cimg_mp_size(arg1),p1,arg2,arg3,arg4,arg5, 0,0,0,0,1,(ulongT)~0U,0,1).move_to(l_opcode); arg2 = arg3 = arg4 = arg5 = ~0U; p2 = p1!=~0U?0:1; if (s0<se1) { s1 = s0; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg2 = compile(s0,s1,depth1,0,is_single); _cimg_mp_check_type(arg2,p2 + (is_sth?3:6),1,0); if (s1<se1) { s0 = s1 + 1; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; arg3 = compile(++s1,s0,depth1,0,is_single); _cimg_mp_check_type(arg3,p2 + (is_sth?4:7),1,0); if (s0<se1) { s1 = s0 + 1; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg4 = compile(++s0,s1,depth1,0,is_single); _cimg_mp_check_type(arg4,p2 + (is_sth?5:8),1,0); if (s1<se1) { s0 = s1 + 1; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; arg5 = compile(++s1,s0,depth1,0,is_single); _cimg_mp_check_type(arg5,p2 + (is_sth?6:9),1,0); } } } } if (s0<s1) s0 = s1; l_opcode(0,8) = (ulongT)arg2; l_opcode(0,9) = (ulongT)arg3; l_opcode(0,10) = (ulongT)arg4; l_opcode(0,11) = (ulongT)arg5; if (s0<se1) { s1 = s0 + 1; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg6 = compile(++s0,s1,depth1,0,is_single); _cimg_mp_check_type(arg6,0,1,0); l_opcode(0,12) = arg6; if (s1<se1) { s0 = s1 + 1; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; p2 = compile(++s1,s0,depth1,0,is_single); _cimg_mp_check_type(p2,0,2,0); l_opcode(0,13) = p2; l_opcode(0,14) = _cimg_mp_size(p2); p3 = s0<se1?compile(++s0,se1,depth1,0,is_single):1; _cimg_mp_check_type(p3,0,1,0); l_opcode(0,15) = p3; } } l_opcode[0].move_to(code); _cimg_mp_return(arg1); } break; case 'e' : if (!std::strncmp(ss,"echo(",5)) { // Echo _cimg_mp_op("Function 'echo()'"); CImg<ulongT>::vector((ulongT)mp_echo,_cimg_mp_slot_nan,0).move_to(l_opcode); for (s = ss5; s<se; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; arg1 = compile(s,ns,depth1,0,is_single); CImg<ulongT>::vector(arg1,_cimg_mp_size(arg1)).move_to(l_opcode); s = ns; } (l_opcode>'y').move_to(opcode); opcode[2] = opcode._height; opcode.move_to(code); _cimg_mp_return_nan(); } if (!std::strncmp(ss,"eig(",4)) { // Matrix eigenvalues/eigenvector _cimg_mp_op("Function 'eig()'"); arg1 = compile(ss4,se1,depth1,0,is_single); _cimg_mp_check_matrix_square(arg1,1); p1 = (unsigned int)cimg::round(std::sqrt((float)_cimg_mp_size(arg1))); pos = vector((p1 + 1)*p1); CImg<ulongT>::vector((ulongT)mp_matrix_eig,pos,arg1,p1).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"end(",4)) { // End _cimg_mp_op("Function 'end()'"); code.swap(code_end); compile(ss4,se1,depth1,p_ref,true); code.swap(code_end); _cimg_mp_return_nan(); } if (!std::strncmp(ss,"ellipse(",8)) { // Ellipse/circle drawing if (!is_single) is_parallelizable = false; _cimg_mp_op("Function 'ellipse()'"); if (*ss8=='#') { // Index specified s0 = ss + 9; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; p1 = compile(ss + 9,s0++,depth1,0,is_single); _cimg_mp_check_list(true); } else { p1 = ~0U; s0 = ss8; } if (s0==se1) compile(s0,se1,depth1,0,is_single); // 'missing' argument error CImg<ulongT>::vector((ulongT)mp_ellipse,_cimg_mp_slot_nan,0,p1).move_to(l_opcode); for (s = s0; s<se; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; arg2 = compile(s,ns,depth1,0,is_single); if (_cimg_mp_is_vector(arg2)) CImg<ulongT>::sequence(_cimg_mp_size(arg2),arg2 + 1, arg2 + (ulongT)_cimg_mp_size(arg2)). move_to(l_opcode); else CImg<ulongT>::vector(arg2).move_to(l_opcode); s = ns; } (l_opcode>'y').move_to(opcode); opcode[2] = opcode._height; opcode.move_to(code); _cimg_mp_return_nan(); } if (!std::strncmp(ss,"ext(",4)) { // Extern _cimg_mp_op("Function 'ext()'"); if (!is_single) is_parallelizable = false; CImg<ulongT>::vector((ulongT)mp_ext,0,0).move_to(l_opcode); pos = 1; for (s = ss4; s<se; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; arg1 = compile(s,ns,depth1,0,is_single); CImg<ulongT>::vector(arg1,_cimg_mp_size(arg1)).move_to(l_opcode); s = ns; } (l_opcode>'y').move_to(opcode); pos = scalar(); opcode[1] = pos; opcode[2] = opcode._height; opcode.move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"exp(",4)) { // Exponential _cimg_mp_op("Function 'exp()'"); arg1 = compile(ss4,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_exp,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::exp(mem[arg1])); _cimg_mp_scalar1(mp_exp,arg1); } if (!std::strncmp(ss,"eye(",4)) { // Identity matrix _cimg_mp_op("Function 'eye()'"); arg1 = compile(ss4,se1,depth1,0,is_single); _cimg_mp_check_constant(arg1,1,3); p1 = (unsigned int)mem[arg1]; pos = vector(p1*p1); CImg<ulongT>::vector((ulongT)mp_eye,pos,p1).move_to(code); _cimg_mp_return(pos); } break; case 'f' : if (!std::strncmp(ss,"fact(",5)) { // Factorial _cimg_mp_op("Function 'fact()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_factorial,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(cimg::factorial((int)mem[arg1])); _cimg_mp_scalar1(mp_factorial,arg1); } if (!std::strncmp(ss,"fibo(",5)) { // Fibonacci _cimg_mp_op("Function 'fibo()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_fibonacci,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(cimg::fibonacci((int)mem[arg1])); _cimg_mp_scalar1(mp_fibonacci,arg1); } if (!std::strncmp(ss,"find(",5)) { // Find _cimg_mp_op("Function 'find()'"); // First argument: data to look at. s0 = ss5; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; if (*ss5=='#') { // Index specified p1 = compile(ss6,s0,depth1,0,is_single); _cimg_mp_check_list(false); arg1 = ~0U; } else { // Vector specified arg1 = compile(ss5,s0,depth1,0,is_single); _cimg_mp_check_type(arg1,1,2,0); p1 = ~0U; } // Second argument: data to find. s1 = ++s0; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg2 = compile(s0,s1,depth1,0,is_single); // Third and fourth arguments: search direction and starting index. arg3 = 1; arg4 = _cimg_mp_slot_nan; if (s1<se1) { s0 = s1 + 1; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; arg3 = compile(++s1,s0,depth1,0,is_single); _cimg_mp_check_type(arg3,3,1,0); if (s0<se1) { arg4 = compile(++s0,se1,depth1,0,is_single); _cimg_mp_check_type(arg4,4,1,0); } } if (p1!=~0U) { if (_cimg_mp_is_vector(arg2)) _cimg_mp_scalar5(mp_list_find_seq,p1,arg2,_cimg_mp_size(arg2),arg3,arg4); _cimg_mp_scalar4(mp_list_find,p1,arg2,arg3,arg4); } if (_cimg_mp_is_vector(arg2)) _cimg_mp_scalar6(mp_find_seq,arg1,_cimg_mp_size(arg1),arg2,_cimg_mp_size(arg2),arg3,arg4); _cimg_mp_scalar5(mp_find,arg1,_cimg_mp_size(arg1),arg2,arg3,arg4); } if (*ss1=='o' && *ss2=='r' && *ss3=='(') { // For loop _cimg_mp_op("Function 'for()'"); s1 = ss4; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; s3 = s2 + 1; while (s3<se1 && (*s3!=',' || level[s3 - expr._data]!=clevel1)) ++s3; arg1 = code._width; p1 = compile(ss4,s1,depth1,0,is_single); // Init arg2 = code._width; p2 = compile(++s1,s2,depth1,0,is_single); // Cond arg3 = code._width; arg6 = mempos; if (s3<se1) { // Body + post p3 = compile(s3 + 1,se1,depth1,0,is_single); // Body arg4 = code._width; pos = compile(++s2,s3,depth1,0,is_single); // Post } else { p3 = compile(++s2,se1,depth1,0,is_single); // Body only arg4 = pos = code._width; } _cimg_mp_check_type(p2,2,1,0); arg5 = _cimg_mp_size(pos); CImg<ulongT>::vector((ulongT)mp_for,p3,(ulongT)_cimg_mp_size(p3),p2,arg2 - arg1,arg3 - arg2, arg4 - arg3,code._width - arg4, p3>=arg6 && !_cimg_mp_is_constant(p3), p2>=arg6 && !_cimg_mp_is_constant(p2)).move_to(code,arg1); _cimg_mp_return(p3); } if (!std::strncmp(ss,"floor(",6)) { // Floor _cimg_mp_op("Function 'floor()'"); arg1 = compile(ss6,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_floor,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::floor(mem[arg1])); _cimg_mp_scalar1(mp_floor,arg1); } if (!std::strncmp(ss,"fsize(",6)) { // File size _cimg_mp_op("Function 'fsize()'"); arg1 = compile(ss6,se1,depth1,0,is_single); _cimg_mp_check_type(arg1,1,2,0); pos = scalar(); CImg<ulongT>::vector((ulongT)mp_fsize,pos,arg1,(ulongT)_cimg_mp_size(arg1)).move_to(code); _cimg_mp_return(pos); } break; case 'g' : if (!std::strncmp(ss,"gauss(",6)) { // Gaussian function _cimg_mp_op("Function 'gauss()'"); s1 = ss6; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss6,s1,depth1,0,is_single); arg2 = arg3 = 1; if (s1<se1) { s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(++s1,s2,depth1,0,is_single); arg3 = s2<se1?compile(++s2,se1,depth1,0,is_single):1; } _cimg_mp_check_type(arg2,2,1,0); _cimg_mp_check_type(arg3,3,1,0); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector3_vss(mp_gauss,arg1,arg2,arg3); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2) && _cimg_mp_is_constant(arg3)) { val1 = mem[arg1]; val2 = mem[arg2]; _cimg_mp_constant(std::exp(-val1*val1/(2*val2*val2))/(mem[arg3]?std::sqrt(2*val2*val2*cimg::PI):1)); } _cimg_mp_scalar3(mp_gauss,arg1,arg2,arg3); } if (!std::strncmp(ss,"gcd(",4)) { // Gcd _cimg_mp_op("Function 'gcd()'"); s1 = ss4; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss4,s1,depth1,0,is_single); arg2 = compile(++s1,se1,depth1,0,is_single); _cimg_mp_check_type(arg1,1,1,0); _cimg_mp_check_type(arg2,2,1,0); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(cimg::gcd((long)mem[arg1],(long)mem[arg2])); _cimg_mp_scalar2(mp_gcd,arg1,arg2); } break; case 'h' : if (*ss1=='(') { // Image height _cimg_mp_op("Function 'h()'"); if (*ss2=='#') { // Index specified p1 = compile(ss3,se1,depth1,0,is_single); _cimg_mp_check_list(false); } else { if (ss2!=se1) break; p1 = ~0U; } pos = scalar(); CImg<ulongT>::vector((ulongT)mp_image_h,pos,p1).move_to(code); _cimg_mp_return(pos); } break; case 'i' : if (*ss1=='c' && *ss2=='(') { // Image median _cimg_mp_op("Function 'ic()'"); if (*ss3=='#') { // Index specified p1 = compile(ss4,se1,depth1,0,is_single); _cimg_mp_check_list(false); } else { if (ss3!=se1) break; p1 = ~0U; } pos = scalar(); CImg<ulongT>::vector((ulongT)mp_image_median,pos,p1).move_to(code); _cimg_mp_return(pos); } if (*ss1=='f' && *ss2=='(') { // If..then[..else.] _cimg_mp_op("Function 'if()'"); s1 = ss3; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg1 = compile(ss3,s1,depth1,0,is_single); _cimg_mp_check_type(arg1,1,1,0); if (_cimg_mp_is_constant(arg1)) { if ((bool)mem[arg1]) return compile(++s1,s2,depth1,0,is_single); else return s2<se1?compile(++s2,se1,depth1,0,is_single):0; } p2 = code._width; arg2 = compile(++s1,s2,depth1,0,is_single); p3 = code._width; arg3 = s2<se1?compile(++s2,se1,depth1,0,is_single): _cimg_mp_is_vector(arg2)?vector(_cimg_mp_size(arg2),0):0; _cimg_mp_check_type(arg3,3,_cimg_mp_is_vector(arg2)?2:1,_cimg_mp_size(arg2)); arg4 = _cimg_mp_size(arg2); if (arg4) pos = vector(arg4); else pos = scalar(); CImg<ulongT>::vector((ulongT)mp_if,pos,arg1,arg2,arg3, p3 - p2,code._width - p3,arg4).move_to(code,p2); _cimg_mp_return(pos); } if (!std::strncmp(ss,"int(",4)) { // Integer cast _cimg_mp_op("Function 'int()'"); arg1 = compile(ss4,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_int,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant((longT)mem[arg1]); _cimg_mp_scalar1(mp_int,arg1); } if (!std::strncmp(ss,"inv(",4)) { // Matrix/scalar inversion _cimg_mp_op("Function 'inv()'"); arg1 = compile(ss4,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) { _cimg_mp_check_matrix_square(arg1,1); p1 = (unsigned int)cimg::round(std::sqrt((float)_cimg_mp_size(arg1))); pos = vector(p1*p1); CImg<ulongT>::vector((ulongT)mp_matrix_inv,pos,arg1,p1).move_to(code); _cimg_mp_return(pos); } if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(1/mem[arg1]); _cimg_mp_scalar2(mp_div,1,arg1); } if (*ss1=='s') { // Family of 'is_?()' functions if (!std::strncmp(ss,"isbool(",7)) { // Is boolean? _cimg_mp_op("Function 'isbool()'"); if (ss7==se1) _cimg_mp_return(0); try { arg1 = compile(ss7,se1,depth1,0,is_single); } catch(CImgException&) { _cimg_mp_return(0); } if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_isbool,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_return(mem[arg1]==0. || mem[arg1]==1.); _cimg_mp_scalar1(mp_isbool,arg1); } if (!std::strncmp(ss,"isdir(",6)) { // Is directory? _cimg_mp_op("Function 'isdir()'"); arg1 = compile(ss6,se1,depth1,0,is_single); if (_cimg_mp_is_scalar(arg1)) _cimg_mp_return(0); pos = scalar(); CImg<ulongT>::vector((ulongT)mp_isdir,pos,arg1,(ulongT)_cimg_mp_size(arg1)).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"isfile(",7)) { // Is file? _cimg_mp_op("Function 'isfile()'"); arg1 = compile(ss7,se1,depth1,0,is_single); if (_cimg_mp_is_scalar(arg1)) _cimg_mp_return(0); pos = scalar(); CImg<ulongT>::vector((ulongT)mp_isfile,pos,arg1,(ulongT)_cimg_mp_size(arg1)).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"isin(",5)) { // Is in sequence/vector? if (ss5>=se1) _cimg_mp_return(0); _cimg_mp_op("Function 'isin()'"); pos = scalar(); CImg<ulongT>::vector((ulongT)mp_isin,pos,0).move_to(l_opcode); for (s = ss5; s<se; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; arg1 = compile(s,ns,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) CImg<ulongT>::sequence(_cimg_mp_size(arg1),arg1 + 1, arg1 + (ulongT)_cimg_mp_size(arg1)). move_to(l_opcode); else CImg<ulongT>::vector(arg1).move_to(l_opcode); s = ns; } (l_opcode>'y').move_to(opcode); opcode[2] = opcode._height; opcode.move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"isinf(",6)) { // Is infinite? _cimg_mp_op("Function 'isinf()'"); if (ss6==se1) _cimg_mp_return(0); arg1 = compile(ss6,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_isinf,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_return((unsigned int)cimg::type<double>::is_inf(mem[arg1])); _cimg_mp_scalar1(mp_isinf,arg1); } if (!std::strncmp(ss,"isint(",6)) { // Is integer? _cimg_mp_op("Function 'isint()'"); if (ss6==se1) _cimg_mp_return(0); try { arg1 = compile(ss6,se1,depth1,0,is_single); } catch(CImgException&) { _cimg_mp_return(0); } if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_isint,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_return((unsigned int)(cimg::mod(mem[arg1],1.)==0)); _cimg_mp_scalar1(mp_isint,arg1); } if (!std::strncmp(ss,"isnan(",6)) { // Is NaN? _cimg_mp_op("Function 'isnan()'"); if (ss6==se1) _cimg_mp_return(0); arg1 = compile(ss6,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_isnan,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_return((unsigned int)cimg::type<double>::is_nan(mem[arg1])); _cimg_mp_scalar1(mp_isnan,arg1); } if (!std::strncmp(ss,"isnum(",6)) { // Is number? _cimg_mp_op("Function 'isnum()'"); val = 0; if (cimg_sscanf(ss6,"%lf%c%c",&val,&sep,&end)==2 && sep==')') _cimg_mp_return(1); _cimg_mp_return(0); } if (!std::strncmp(ss,"isexpr(",7)) { // Is valid expression? _cimg_mp_op("Function 'isexpr()'"); if (ss7==se1) _cimg_mp_return(0); try { arg1 = compile(ss7,se1,depth1,0,is_single); } catch (CImgException&) { _cimg_mp_return(0); } _cimg_mp_return(1); } } break; case 'l' : if (*ss1=='(') { // Size of image list _cimg_mp_op("Function 'l()'"); if (ss2!=se1) break; _cimg_mp_scalar0(mp_list_l); } if (!std::strncmp(ss,"log(",4)) { // Natural logarithm _cimg_mp_op("Function 'log()'"); arg1 = compile(ss4,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_log,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::log(mem[arg1])); _cimg_mp_scalar1(mp_log,arg1); } if (!std::strncmp(ss,"log2(",5)) { // Base-2 logarithm _cimg_mp_op("Function 'log2()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_log2,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(cimg::log2(mem[arg1])); _cimg_mp_scalar1(mp_log2,arg1); } if (!std::strncmp(ss,"log10(",6)) { // Base-10 logarithm _cimg_mp_op("Function 'log10()'"); arg1 = compile(ss6,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_log10,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::log10(mem[arg1])); _cimg_mp_scalar1(mp_log10,arg1); } if (!std::strncmp(ss,"lowercase(",10)) { // Lower case _cimg_mp_op("Function 'lowercase()'"); arg1 = compile(ss + 10,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_lowercase,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(cimg::lowercase(mem[arg1])); _cimg_mp_scalar1(mp_lowercase,arg1); } break; case 'm' : if (!std::strncmp(ss,"mul(",4)) { // Matrix multiplication _cimg_mp_op("Function 'mul()'"); s1 = ss4; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss4,s1,depth1,0,is_single); s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(++s1,s2,depth1,0,is_single); arg3 = s2<se1?compile(++s2,se1,depth1,0,is_single):1; _cimg_mp_check_type(arg1,1,2,0); _cimg_mp_check_type(arg2,2,2,0); _cimg_mp_check_constant(arg3,3,3); p1 = _cimg_mp_size(arg1); p2 = _cimg_mp_size(arg2); p3 = (unsigned int)mem[arg3]; arg5 = p2/p3; arg4 = p1/arg5; if (arg4*arg5!=p1 || arg5*p3!=p2) { *se = saved_char; s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Types of first and second arguments ('%s' and '%s') " "do not match with third argument 'nb_colsB=%u', " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, s_type(arg1)._data,s_type(arg2)._data,p3, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } pos = vector(arg4*p3); CImg<ulongT>::vector((ulongT)mp_matrix_mul,pos,arg1,arg2,arg4,arg5,p3).move_to(code); _cimg_mp_return(pos); } break; case 'n' : if (!std::strncmp(ss,"narg(",5)) { // Number of arguments _cimg_mp_op("Function 'narg()'"); if (ss5>=se1) _cimg_mp_return(0); arg1 = 0; for (s = ss5; s<se; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; ++arg1; s = ns; } _cimg_mp_constant(arg1); } if ((cimg_sscanf(ss,"norm%u%c",&(arg1=~0U),&sep)==2 && sep=='(') || !std::strncmp(ss,"norminf(",8) || !std::strncmp(ss,"norm(",5) || (!std::strncmp(ss,"norm",4) && ss5<se1 && (s=std::strchr(ss5,'('))!=0)) { // Lp norm _cimg_mp_op("Function 'normP()'"); if (*ss4=='(') { arg1 = 2; s = ss5; } else if (*ss4=='i' && *ss5=='n' && *ss6=='f' && *ss7=='(') { arg1 = ~0U; s = ss8; } else if (arg1==~0U) { arg1 = compile(ss4,s++,depth1,0,is_single); _cimg_mp_check_constant(arg1,0,2); arg1 = (unsigned int)mem[arg1]; } else s = std::strchr(ss4,'(') + 1; pos = scalar(); switch (arg1) { case 0 : CImg<ulongT>::vector((ulongT)mp_norm0,pos,0).move_to(l_opcode); break; case 1 : CImg<ulongT>::vector((ulongT)mp_norm1,pos,0).move_to(l_opcode); break; case 2 : CImg<ulongT>::vector((ulongT)mp_norm2,pos,0).move_to(l_opcode); break; case ~0U : CImg<ulongT>::vector((ulongT)mp_norminf,pos,0).move_to(l_opcode); break; default : CImg<ulongT>::vector((ulongT)mp_normp,pos,0,(ulongT)(arg1==~0U?-1:(int)arg1)). move_to(l_opcode); } for ( ; s<se; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; arg2 = compile(s,ns,depth1,0,is_single); if (_cimg_mp_is_vector(arg2)) CImg<ulongT>::sequence(_cimg_mp_size(arg2),arg2 + 1, arg2 + (ulongT)_cimg_mp_size(arg2)). move_to(l_opcode); else CImg<ulongT>::vector(arg2).move_to(l_opcode); s = ns; } (l_opcode>'y').move_to(opcode); if (arg1>0 && opcode._height==4) // Special case with one argument and p>=1 _cimg_mp_scalar1(mp_abs,opcode[3]); opcode[2] = opcode._height; opcode.move_to(code); _cimg_mp_return(pos); } break; case 'p' : if (!std::strncmp(ss,"permut(",7)) { // Number of permutations _cimg_mp_op("Function 'permut()'"); s1 = ss7; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg1 = compile(ss7,s1,depth1,0,is_single); arg2 = compile(++s1,s2,depth1,0,is_single); arg3 = compile(++s2,se1,depth1,0,is_single); _cimg_mp_check_type(arg1,1,1,0); _cimg_mp_check_type(arg2,2,1,0); _cimg_mp_check_type(arg3,3,1,0); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2) && _cimg_mp_is_constant(arg3)) _cimg_mp_constant(cimg::permutations((int)mem[arg1],(int)mem[arg2],(bool)mem[arg3])); _cimg_mp_scalar3(mp_permutations,arg1,arg2,arg3); } if (!std::strncmp(ss,"polygon(",8)) { // Polygon/line drawing if (!is_single) is_parallelizable = false; _cimg_mp_op("Function 'polygon()'"); if (*ss8=='#') { // Index specified s0 = ss + 9; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; p1 = compile(ss + 9,s0++,depth1,0,is_single); _cimg_mp_check_list(true); } else { p1 = ~0U; s0 = ss8; } if (s0==se1) compile(s0,se1,depth1,0,is_single); // 'missing' argument error CImg<ulongT>::vector((ulongT)mp_polygon,_cimg_mp_slot_nan,0,p1).move_to(l_opcode); for (s = s0; s<se; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; arg2 = compile(s,ns,depth1,0,is_single); if (_cimg_mp_is_vector(arg2)) CImg<ulongT>::sequence(_cimg_mp_size(arg2),arg2 + 1, arg2 + (ulongT)_cimg_mp_size(arg2)). move_to(l_opcode); else CImg<ulongT>::vector(arg2).move_to(l_opcode); s = ns; } (l_opcode>'y').move_to(opcode); opcode[2] = opcode._height; opcode.move_to(code); _cimg_mp_return_nan(); } if (!std::strncmp(ss,"print(",6) || !std::strncmp(ss,"prints(",7)) { // Print expressions is_sth = ss[5]=='s'; // is prints() _cimg_mp_op(is_sth?"Function 'prints()'":"Function 'print()'"); s0 = is_sth?ss7:ss6; if (*s0!='#' || is_sth) { // Regular expression for (s = s0; s<se; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; pos = compile(s,ns,depth1,p_ref,is_single); c1 = *ns; *ns = 0; variable_name.assign(CImg<charT>::string(s,true,true).unroll('y'),true); cimg::strpare(variable_name,false,true); if (_cimg_mp_is_vector(pos)) // Vector ((CImg<ulongT>::vector((ulongT)mp_vector_print,pos,0,(ulongT)_cimg_mp_size(pos),is_sth?1:0), variable_name)>'y').move_to(opcode); else // Scalar ((CImg<ulongT>::vector((ulongT)mp_print,pos,0,is_sth?1:0), variable_name)>'y').move_to(opcode); opcode[2] = opcode._height; opcode.move_to(code); *ns = c1; s = ns; } _cimg_mp_return(pos); } else { // Image p1 = compile(ss7,se1,depth1,0,is_single); _cimg_mp_check_list(true); CImg<ulongT>::vector((ulongT)mp_image_print,_cimg_mp_slot_nan,p1).move_to(code); _cimg_mp_return_nan(); } } if (!std::strncmp(ss,"pseudoinv(",10)) { // Matrix/scalar pseudo-inversion _cimg_mp_op("Function 'pseudoinv()'"); s1 = ss + 10; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss + 10,s1,depth1,0,is_single); arg2 = s1<se1?compile(++s1,se1,depth1,0,is_single):1; _cimg_mp_check_type(arg1,1,2,0); _cimg_mp_check_constant(arg2,2,3); p1 = _cimg_mp_size(arg1); p2 = (unsigned int)mem[arg2]; p3 = p1/p2; if (p3*p2!=p1) { *se = saved_char; s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Type of first argument ('%s') " "does not match with second argument 'nb_colsA=%u', " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, s_type(arg1)._data,p2, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } pos = vector(p1); CImg<ulongT>::vector((ulongT)mp_matrix_pseudoinv,pos,arg1,p2,p3).move_to(code); _cimg_mp_return(pos); } break; case 'r' : if (!std::strncmp(ss,"resize(",7)) { // Vector or image resize _cimg_mp_op("Function 'resize()'"); if (*ss7!='#') { // Vector s1 = ss7; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss7,s1,depth1,0,is_single); s2 = ++s1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(s1,s2,depth1,0,is_single); arg3 = 1; arg4 = 0; if (s2<se1) { s1 = ++s2; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg3 = compile(s2,s1,depth1,0,is_single); arg4 = s1<se1?compile(++s1,se1,depth1,0,is_single):0; } _cimg_mp_check_constant(arg2,2,3); arg2 = (unsigned int)mem[arg2]; _cimg_mp_check_type(arg3,3,1,0); _cimg_mp_check_type(arg4,4,1,0); pos = vector(arg2); CImg<ulongT>::vector((ulongT)mp_vector_resize,pos,arg2,arg1,(ulongT)_cimg_mp_size(arg1), arg3,arg4).move_to(code); _cimg_mp_return(pos); } else { // Image if (!is_single) is_parallelizable = false; s0 = ss8; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; p1 = compile(ss8,s0++,depth1,0,is_single); _cimg_mp_check_list(true); l_opcode.assign(); // Don't use 'opcode': it can be modified by further calls to 'compile()'! CImg<ulongT>::vector((ulongT)mp_image_resize,_cimg_mp_slot_nan,p1,~0U,~0U,~0U,~0U,1,0,0,0,0,0). move_to(l_opcode); pos = 0; for (s = s0; s<se && pos<10; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; arg1 = compile(s,ns,depth1,0,is_single); _cimg_mp_check_type(arg1,pos + 2,1,0); l_opcode(0,pos + 3) = arg1; s = ns; ++pos; } if (pos<1 || pos>10) { *se = saved_char; s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: %s arguments, in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, pos<1?"Missing":"Too much", s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } l_opcode[0].move_to(code); _cimg_mp_return_nan(); } } if (!std::strncmp(ss,"reverse(",8)) { // Vector reverse _cimg_mp_op("Function 'reverse()'"); arg1 = compile(ss8,se1,depth1,0,is_single); if (!_cimg_mp_is_vector(arg1)) _cimg_mp_return(arg1); p1 = _cimg_mp_size(arg1); pos = vector(p1); CImg<ulongT>::vector((ulongT)mp_vector_reverse,pos,arg1,p1).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"rol(",4) || !std::strncmp(ss,"ror(",4)) { // Bitwise rotation _cimg_mp_op(ss[2]=='l'?"Function 'rol()'":"Function 'ror()'"); s1 = ss4; while (s1<se1 && (*s1!=',' || level[s1-expr._data]!=clevel1)) ++s1; arg1 = compile(ss4,s1,depth1,0,is_single); arg2 = s1<se1?compile(++s1,se1,depth1,0,is_single):1; _cimg_mp_check_type(arg2,2,1,0); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector2_vs(*ss2=='l'?mp_rol:mp_ror,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant(*ss2=='l'?cimg::rol(mem[arg1],(unsigned int)mem[arg2]): cimg::ror(mem[arg1],(unsigned int)mem[arg2])); _cimg_mp_scalar2(*ss2=='l'?mp_rol:mp_ror,arg1,arg2); } if (!std::strncmp(ss,"rot(",4)) { // 2D/3D rotation matrix _cimg_mp_op("Function 'rot()'"); s1 = ss4; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss4,s1,depth1,0,is_single); if (s1<se1) { // 3D rotation _cimg_mp_check_type(arg1,1,3,3); is_sth = false; // Is coordinates as vector? if (_cimg_mp_is_vector(arg1)) { // Coordinates specified as a vector is_sth = true; p2 = _cimg_mp_size(arg1); ++arg1; arg2 = arg3 = 0; if (p2>1) { arg2 = arg1 + 1; if (p2>2) arg3 = arg2 + 1; } arg4 = compile(++s1,se1,depth1,0,is_single); } else { s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(++s1,s2,depth1,0,is_single); s3 = s2 + 1; while (s3<se1 && (*s3!=',' || level[s3 - expr._data]!=clevel1)) ++s3; arg3 = compile(++s2,s3,depth1,0,is_single); arg4 = compile(++s3,se1,depth1,0,is_single); _cimg_mp_check_type(arg2,2,1,0); _cimg_mp_check_type(arg3,3,1,0); } _cimg_mp_check_type(arg4,is_sth?2:4,1,0); pos = vector(9); CImg<ulongT>::vector((ulongT)mp_rot3d,pos,arg1,arg2,arg3,arg4).move_to(code); } else { // 2D rotation _cimg_mp_check_type(arg1,1,1,0); pos = vector(4); CImg<ulongT>::vector((ulongT)mp_rot2d,pos,arg1).move_to(code); } _cimg_mp_return(pos); } if (!std::strncmp(ss,"round(",6)) { // Value rounding _cimg_mp_op("Function 'round()'"); s1 = ss6; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss6,s1,depth1,0,is_single); arg2 = 1; arg3 = 0; if (s1<se1) { s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(++s1,s2,depth1,0,is_single); arg3 = s2<se1?compile(++s2,se1,depth1,0,is_single):0; } _cimg_mp_check_type(arg2,2,1,0); _cimg_mp_check_type(arg3,3,1,0); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector3_vss(mp_round,arg1,arg2,arg3); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2) && _cimg_mp_is_constant(arg3)) _cimg_mp_constant(cimg::round(mem[arg1],mem[arg2],(int)mem[arg3])); _cimg_mp_scalar3(mp_round,arg1,arg2,arg3); } break; case 's' : if (*ss1=='(') { // Image spectrum _cimg_mp_op("Function 's()'"); if (*ss2=='#') { // Index specified p1 = compile(ss3,se1,depth1,0,is_single); _cimg_mp_check_list(false); } else { if (ss2!=se1) break; p1 = ~0U; } pos = scalar(); CImg<ulongT>::vector((ulongT)mp_image_s,pos,p1).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"same(",5)) { // Test if operands have the same values _cimg_mp_op("Function 'same()'"); s1 = ss5; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss5,s1,depth1,0,is_single); s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(++s1,s2,depth1,0,is_single); arg3 = 11; arg4 = 1; if (s2<se1) { s3 = s2 + 1; while (s3<se1 && (*s3!=',' || level[s3 - expr._data]!=clevel1)) ++s3; arg3 = compile(++s2,s3,depth1,0,is_single); _cimg_mp_check_type(arg3,3,1,0); arg4 = s3<se1?compile(++s3,se1,depth1,0,is_single):1; } p1 = _cimg_mp_size(arg1); p2 = _cimg_mp_size(arg2); _cimg_mp_scalar6(mp_vector_eq,arg1,p1,arg2,p2,arg3,arg4); } if (!std::strncmp(ss,"shift(",6)) { // Shift vector _cimg_mp_op("Function 'shift()'"); s1 = ss6; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss6,s1,depth1,0,is_single); arg2 = 1; arg3 = 0; if (s1<se1) { s0 = ++s1; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; arg2 = compile(s1,s0,depth1,0,is_single); arg3 = s0<se1?compile(++s0,se1,depth1,0,is_single):0; } _cimg_mp_check_type(arg1,1,2,0); _cimg_mp_check_type(arg2,2,1,0); _cimg_mp_check_type(arg3,3,1,0); p1 = _cimg_mp_size(arg1); pos = vector(p1); CImg<ulongT>::vector((ulongT)mp_shift,pos,arg1,p1,arg2,arg3).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"sign(",5)) { // Sign _cimg_mp_op("Function 'sign()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_sign,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(cimg::sign(mem[arg1])); _cimg_mp_scalar1(mp_sign,arg1); } if (!std::strncmp(ss,"sin(",4)) { // Sine _cimg_mp_op("Function 'sin()'"); arg1 = compile(ss4,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_sin,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::sin(mem[arg1])); _cimg_mp_scalar1(mp_sin,arg1); } if (!std::strncmp(ss,"sinc(",5)) { // Sine cardinal _cimg_mp_op("Function 'sinc()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_sinc,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(cimg::sinc(mem[arg1])); _cimg_mp_scalar1(mp_sinc,arg1); } if (!std::strncmp(ss,"sinh(",5)) { // Hyperbolic sine _cimg_mp_op("Function 'sinh()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_sinh,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::sinh(mem[arg1])); _cimg_mp_scalar1(mp_sinh,arg1); } if (!std::strncmp(ss,"size(",5)) { // Vector size _cimg_mp_op("Function 'size()'"); arg1 = compile(ss5,se1,depth1,0,is_single); _cimg_mp_constant(_cimg_mp_is_scalar(arg1)?0:_cimg_mp_size(arg1)); } if (!std::strncmp(ss,"solve(",6)) { // Solve linear system _cimg_mp_op("Function 'solve()'"); s1 = ss6; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss6,s1,depth1,0,is_single); s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(++s1,s2,depth1,0,is_single); arg3 = s2<se1?compile(++s2,se1,depth1,0,is_single):1; _cimg_mp_check_type(arg1,1,2,0); _cimg_mp_check_type(arg2,2,2,0); _cimg_mp_check_constant(arg3,3,3); p1 = _cimg_mp_size(arg1); p2 = _cimg_mp_size(arg2); p3 = (unsigned int)mem[arg3]; arg5 = p2/p3; arg4 = p1/arg5; if (arg4*arg5!=p1 || arg5*p3!=p2) { *se = saved_char; s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Types of first and second arguments ('%s' and '%s') " "do not match with third argument 'nb_colsB=%u', " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, s_type(arg1)._data,s_type(arg2)._data,p3, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } pos = vector(arg4*p3); CImg<ulongT>::vector((ulongT)mp_solve,pos,arg1,arg2,arg4,arg5,p3).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"sort(",5)) { // Sort vector _cimg_mp_op("Function 'sort()'"); if (*ss5!='#') { // Vector s1 = ss5; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss5,s1,depth1,0,is_single); arg2 = arg3 = 1; if (s1<se1) { s0 = ++s1; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; arg2 = compile(s1,s0,depth1,0,is_single); arg3 = s0<se1?compile(++s0,se1,depth1,0,is_single):1; } _cimg_mp_check_type(arg1,1,2,0); _cimg_mp_check_type(arg2,2,1,0); _cimg_mp_check_constant(arg3,3,3); arg3 = (unsigned int)mem[arg3]; p1 = _cimg_mp_size(arg1); if (p1%arg3) { *se = saved_char; s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Invalid specified chunk size (%u) for first argument " "('%s'), in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, arg3,s_type(arg1)._data, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } pos = vector(p1); CImg<ulongT>::vector((ulongT)mp_sort,pos,arg1,p1,arg2,arg3).move_to(code); _cimg_mp_return(pos); } else { // Image s1 = ss6; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; p1 = compile(ss6,s1,depth1,0,is_single); arg1 = 1; arg2 = constant(-1.); if (s1<se1) { s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg1 = compile(++s1,s2,depth1,0,is_single); if (s2<se1) arg2 = compile(++s2,se1,depth1,0,is_single); } _cimg_mp_check_type(arg1,2,1,0); _cimg_mp_check_type(arg2,3,1,0); _cimg_mp_check_list(true); CImg<ulongT>::vector((ulongT)mp_image_sort,_cimg_mp_slot_nan,p1,arg1,arg2).move_to(code); _cimg_mp_return_nan(); } } if (!std::strncmp(ss,"sqr(",4)) { // Square _cimg_mp_op("Function 'sqr()'"); arg1 = compile(ss4,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_sqr,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(cimg::sqr(mem[arg1])); _cimg_mp_scalar1(mp_sqr,arg1); } if (!std::strncmp(ss,"sqrt(",5)) { // Square root _cimg_mp_op("Function 'sqrt()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_sqrt,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::sqrt(mem[arg1])); _cimg_mp_scalar1(mp_sqrt,arg1); } if (!std::strncmp(ss,"srand(",6)) { // Set RNG seed _cimg_mp_op("Function 'srand()'"); arg1 = ss6<se1?compile(ss6,se1,depth1,0,is_single):~0U; if (arg1!=~0U) { _cimg_mp_check_type(arg1,1,1,0); _cimg_mp_scalar1(mp_srand,arg1); } _cimg_mp_scalar0(mp_srand0); } if (!std::strncmp(ss,"stats(",6)) { // Image statistics _cimg_mp_op("Function 'stats()'"); if (*ss6=='#') { // Index specified p1 = compile(ss7,se1,depth1,0,is_single); _cimg_mp_check_list(false); } else { if (ss6!=se1) break; p1 = ~0U; } pos = vector(14); CImg<ulongT>::vector((ulongT)mp_image_stats,pos,p1).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"stov(",5)) { // String to double _cimg_mp_op("Function 'stov()'"); s1 = ss5; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss5,s1,depth1,0,is_single); arg2 = arg3 = 0; if (s1<se1) { s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(++s1,s2,depth1,0,is_single); arg3 = s2<se1?compile(++s2,se1,depth1,0,is_single):0; } _cimg_mp_check_type(arg2,2,1,0); _cimg_mp_check_type(arg3,3,1,0); p1 = _cimg_mp_size(arg1); pos = scalar(); CImg<ulongT>::vector((ulongT)mp_stov,pos,arg1,p1,arg2,arg3).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"svd(",4)) { // Matrix SVD _cimg_mp_op("Function 'svd()'"); s1 = ss4; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss4,s1,depth1,0,is_single); arg2 = s1<se1?compile(++s1,se1,depth1,0,is_single):1; _cimg_mp_check_type(arg1,1,2,0); _cimg_mp_check_constant(arg2,2,3); p1 = _cimg_mp_size(arg1); p2 = (unsigned int)mem[arg2]; p3 = p1/p2; if (p3*p2!=p1) { *se = saved_char; s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Type of first argument ('%s') " "does not match with second argument 'nb_colsA=%u', " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, s_type(arg1)._data,p2, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } pos = vector(p1 + p2 + p2*p2); CImg<ulongT>::vector((ulongT)mp_matrix_svd,pos,arg1,p2,p3).move_to(code); _cimg_mp_return(pos); } break; case 't' : if (!std::strncmp(ss,"tan(",4)) { // Tangent _cimg_mp_op("Function 'tan()'"); arg1 = compile(ss4,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_tan,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::tan(mem[arg1])); _cimg_mp_scalar1(mp_tan,arg1); } if (!std::strncmp(ss,"tanh(",5)) { // Hyperbolic tangent _cimg_mp_op("Function 'tanh()'"); arg1 = compile(ss5,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_tanh,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(std::tanh(mem[arg1])); _cimg_mp_scalar1(mp_tanh,arg1); } if (!std::strncmp(ss,"trace(",6)) { // Matrix trace _cimg_mp_op("Function 'trace()'"); arg1 = compile(ss6,se1,depth1,0,is_single); _cimg_mp_check_matrix_square(arg1,1); p1 = (unsigned int)cimg::round(std::sqrt((float)_cimg_mp_size(arg1))); _cimg_mp_scalar2(mp_trace,arg1,p1); } if (!std::strncmp(ss,"transp(",7)) { // Matrix transpose _cimg_mp_op("Function 'transp()'"); s1 = ss7; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss7,s1,depth1,0,is_single); arg2 = compile(++s1,se1,depth1,0,is_single); _cimg_mp_check_type(arg1,1,2,0); _cimg_mp_check_constant(arg2,2,3); p1 = _cimg_mp_size(arg1); p2 = (unsigned int)mem[arg2]; p3 = p1/p2; if (p2*p3!=p1) { *se = saved_char; s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Size of first argument ('%s') does not match " "second argument 'nb_cols=%u', in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, s_type(arg1)._data,p2, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } pos = vector(p3*p2); CImg<ulongT>::vector((ulongT)mp_transp,pos,arg1,p2,p3).move_to(code); _cimg_mp_return(pos); } break; case 'u' : if (*ss1=='(') { // Random value with uniform distribution _cimg_mp_op("Function 'u()'"); if (*ss2==')') _cimg_mp_scalar2(mp_u,0,1); s1 = ss2; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss2,s1,depth1,0,is_single); if (s1<se1) arg2 = compile(++s1,se1,depth1,0,is_single); else { arg2 = arg1; arg1 = 0; } _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_u,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_u,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_u,arg1,arg2); _cimg_mp_scalar2(mp_u,arg1,arg2); } if (!std::strncmp(ss,"unref(",6)) { // Un-reference variable _cimg_mp_op("Function 'unref()'"); arg1 = ~0U; for (s0 = ss6; s0<se1; s0 = s1) { if (s0>ss6 && *s0==',') ++s0; s1 = s0; while (s1<se1 && *s1!=',') ++s1; c1 = *s1; if (s1>s0) { *s1 = 0; arg2 = arg3 = ~0U; if (s0[0]=='w' && s0[1]=='h' && !s0[2]) arg1 = reserved_label[arg3 = 0]; else if (s0[0]=='w' && s0[1]=='h' && s0[2]=='d' && !s0[3]) arg1 = reserved_label[arg3 = 1]; else if (s0[0]=='w' && s0[1]=='h' && s0[2]=='d' && s0[3]=='s' && !s0[4]) arg1 = reserved_label[arg3 = 2]; else if (s0[0]=='p' && s0[1]=='i' && !s0[2]) arg1 = reserved_label[arg3 = 3]; else if (s0[0]=='i' && s0[1]=='m' && !s0[2]) arg1 = reserved_label[arg3 = 4]; else if (s0[0]=='i' && s0[1]=='M' && !s0[2]) arg1 = reserved_label[arg3 = 5]; else if (s0[0]=='i' && s0[1]=='a' && !s0[2]) arg1 = reserved_label[arg3 = 6]; else if (s0[0]=='i' && s0[1]=='v' && !s0[2]) arg1 = reserved_label[arg3 = 7]; else if (s0[0]=='i' && s0[1]=='s' && !s0[2]) arg1 = reserved_label[arg3 = 8]; else if (s0[0]=='i' && s0[1]=='p' && !s0[2]) arg1 = reserved_label[arg3 = 9]; else if (s0[0]=='i' && s0[1]=='c' && !s0[2]) arg1 = reserved_label[arg3 = 10]; else if (s0[0]=='x' && s0[1]=='m' && !s0[2]) arg1 = reserved_label[arg3 = 11]; else if (s0[0]=='y' && s0[1]=='m' && !s0[2]) arg1 = reserved_label[arg3 = 12]; else if (s0[0]=='z' && s0[1]=='m' && !s0[2]) arg1 = reserved_label[arg3 = 13]; else if (s0[0]=='c' && s0[1]=='m' && !s0[2]) arg1 = reserved_label[arg3 = 14]; else if (s0[0]=='x' && s0[1]=='M' && !s0[2]) arg1 = reserved_label[arg3 = 15]; else if (s0[0]=='y' && s0[1]=='M' && !s0[2]) arg1 = reserved_label[arg3 = 16]; else if (s0[0]=='z' && s0[1]=='M' && !s0[2]) arg1 = reserved_label[arg3 = 17]; else if (s0[0]=='c' && s0[1]=='M' && !s0[2]) arg1 = reserved_label[arg3 = 18]; else if (s0[0]=='i' && s0[1]>='0' && s0[1]<='9' && !s0[2]) arg1 = reserved_label[arg3 = 19 + s0[1] - '0']; else if (!std::strcmp(s0,"interpolation")) arg1 = reserved_label[arg3 = 29]; else if (!std::strcmp(s0,"boundary")) arg1 = reserved_label[arg3 = 30]; else if (s0[1]) { // Multi-char variable cimglist_for(variable_def,i) if (!std::strcmp(s0,variable_def[i])) { arg1 = variable_pos[i]; arg2 = i; break; } } else arg1 = reserved_label[arg3 = *s0]; // Single-char variable if (arg1!=~0U) { if (arg2==~0U) { if (arg3!=~0U) reserved_label[arg3] = ~0U; } else { variable_def.remove(arg2); if (arg2<variable_pos._width - 1) std::memmove(variable_pos._data + arg2,variable_pos._data + arg2 + 1, sizeof(uintT)*(variable_pos._width - arg2 - 1)); --variable_pos._width; } } *s1 = c1; } else compile(s0,s1,depth1,0,is_single); // Will throw a 'missing argument' exception } _cimg_mp_return(arg1!=~0U?arg1:_cimg_mp_slot_nan); // Return value of last specified variable } if (!std::strncmp(ss,"uppercase(",10)) { // Upper case _cimg_mp_op("Function 'uppercase()'"); arg1 = compile(ss + 10,se1,depth1,0,is_single); if (_cimg_mp_is_vector(arg1)) _cimg_mp_vector1_v(mp_uppercase,arg1); if (_cimg_mp_is_constant(arg1)) _cimg_mp_constant(cimg::uppercase(mem[arg1])); _cimg_mp_scalar1(mp_uppercase,arg1); } break; case 'v' : if ((cimg_sscanf(ss,"vector%u%c",&(arg1=~0U),&sep)==2 && sep=='(' && arg1>0) || !std::strncmp(ss,"vector(",7) || (!std::strncmp(ss,"vector",6) && ss7<se1 && (s=std::strchr(ss7,'('))!=0)) { // Vector _cimg_mp_op("Function 'vector()'"); arg2 = 0; // Number of specified values if (arg1==~0U && *ss6!='(') { arg1 = compile(ss6,s++,depth1,0,is_single); _cimg_mp_check_constant(arg1,0,3); arg1 = (unsigned int)mem[arg1]; } else s = std::strchr(ss6,'(') + 1; if (arg1==~0U && *s=='#') { // Number of elements specified as first argument with '#' s0 = ++s; while (s0<se1 && (*s0!=',' || level[s0 - expr._data]!=clevel1)) ++s0; arg1 = compile(s,s0++,depth1,0,is_single); _cimg_mp_check_constant(arg1,1,3); arg1 = (unsigned int)mem[arg1]; s = s0; } if (s<se1 || arg1==~0U) for ( ; s<se; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; arg3 = compile(s,ns,depth1,0,is_single); if (_cimg_mp_is_vector(arg3)) { arg4 = _cimg_mp_size(arg3); CImg<ulongT>::sequence(arg4,arg3 + 1,arg3 + arg4).move_to(l_opcode); arg2+=arg4; } else { CImg<ulongT>::vector(arg3).move_to(l_opcode); ++arg2; } s = ns; } if (arg1==~0U) arg1 = arg2; if (!arg1) _cimg_mp_return(0); pos = vector(arg1); l_opcode.insert(CImg<ulongT>::vector((ulongT)mp_vector_init,pos,0,arg1),0); (l_opcode>'y').move_to(opcode); opcode[2] = opcode._height; opcode.move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"vtos(",5)) { // Double(s) to string _cimg_mp_op("Function 'vtos()'"); s1 = ss5; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss5,s1,depth1,0,is_single); arg2 = 0; arg3 = ~0U; if (s1<se1) { s2 = s1 + 1; while (s2<se1 && (*s2!=',' || level[s2 - expr._data]!=clevel1)) ++s2; arg2 = compile(++s1,s2,depth1,0,is_single); arg3 = s2<se1?compile(++s2,se1,depth1,0,is_single):~0U; } _cimg_mp_check_type(arg2,2,1,0); if (arg3==~0U) { // Auto-guess best output vector size p1 = _cimg_mp_size(arg1); p1 = p1?22*p1 - 1:18; } else { _cimg_mp_check_constant(arg3,3,3); p1 = (unsigned int)mem[arg3]; } pos = vector(p1); CImg<ulongT>::vector((ulongT)mp_vtos,pos,p1,arg1,_cimg_mp_size(arg1),arg2).move_to(code); _cimg_mp_return(pos); } break; case 'w' : if (*ss1=='(') { // Image width _cimg_mp_op("Function 'w()'"); if (*ss2=='#') { // Index specified p1 = compile(ss3,se1,depth1,0,is_single); _cimg_mp_check_list(false); } else { if (ss2!=se1) break; p1 = ~0U; } pos = scalar(); CImg<ulongT>::vector((ulongT)mp_image_w,pos,p1).move_to(code); _cimg_mp_return(pos); } if (*ss1=='h' && *ss2=='(') { // Image width*height _cimg_mp_op("Function 'wh()'"); if (*ss3=='#') { // Index specified p1 = compile(ss4,se1,depth1,0,is_single); _cimg_mp_check_list(false); } else { if (ss3!=se1) break; p1 = ~0U; } pos = scalar(); CImg<ulongT>::vector((ulongT)mp_image_wh,pos,p1).move_to(code); _cimg_mp_return(pos); } if (*ss1=='h' && *ss2=='d' && *ss3=='(') { // Image width*height*depth _cimg_mp_op("Function 'whd()'"); if (*ss4=='#') { // Index specified p1 = compile(ss5,se1,depth1,0,is_single); _cimg_mp_check_list(false); } else { if (ss4!=se1) break; p1 = ~0U; } pos = scalar(); CImg<ulongT>::vector((ulongT)mp_image_whd,pos,p1).move_to(code); _cimg_mp_return(pos); } if (*ss1=='h' && *ss2=='d' && *ss3=='s' && *ss4=='(') { // Image width*height*depth*spectrum _cimg_mp_op("Function 'whds()'"); if (*ss5=='#') { // Index specified p1 = compile(ss6,se1,depth1,0,is_single); _cimg_mp_check_list(false); } else { if (ss5!=se1) break; p1 = ~0U; } pos = scalar(); CImg<ulongT>::vector((ulongT)mp_image_whds,pos,p1).move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"while(",6)) { // While...do _cimg_mp_op("Function 'while()'"); s0 = *ss5=='('?ss6:ss8; s1 = s0; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; p1 = code._width; arg1 = compile(s0,s1,depth1,0,is_single); p2 = code._width; arg6 = mempos; pos = compile(++s1,se1,depth1,0,is_single); _cimg_mp_check_type(arg1,1,1,0); arg2 = _cimg_mp_size(pos); CImg<ulongT>::vector((ulongT)mp_while,pos,arg1,p2 - p1,code._width - p2,arg2, pos>=arg6 && !_cimg_mp_is_constant(pos), arg1>=arg6 && !_cimg_mp_is_constant(arg1)).move_to(code,p1); _cimg_mp_return(pos); } break; case 'x' : if (!std::strncmp(ss,"xor(",4)) { // Xor _cimg_mp_op("Function 'xor()'"); s1 = ss4; while (s1<se1 && (*s1!=',' || level[s1 - expr._data]!=clevel1)) ++s1; arg1 = compile(ss4,s1,depth1,0,is_single); arg2 = compile(++s1,se1,depth1,0,is_single); _cimg_mp_check_type(arg2,2,3,_cimg_mp_size(arg1)); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_vv(mp_bitwise_xor,arg1,arg2); if (_cimg_mp_is_vector(arg1) && _cimg_mp_is_scalar(arg2)) _cimg_mp_vector2_vs(mp_bitwise_xor,arg1,arg2); if (_cimg_mp_is_scalar(arg1) && _cimg_mp_is_vector(arg2)) _cimg_mp_vector2_sv(mp_bitwise_xor,arg1,arg2); if (_cimg_mp_is_constant(arg1) && _cimg_mp_is_constant(arg2)) _cimg_mp_constant((longT)mem[arg1] ^ (longT)mem[arg2]); _cimg_mp_scalar2(mp_bitwise_xor,arg1,arg2); } break; } if (!std::strncmp(ss,"min(",4) || !std::strncmp(ss,"max(",4) || !std::strncmp(ss,"med(",4) || !std::strncmp(ss,"kth(",4) || !std::strncmp(ss,"sum(",4) || !std::strncmp(ss,"avg(",4) || !std::strncmp(ss,"std(",4) || !std::strncmp(ss,"var(",4) || !std::strncmp(ss,"prod(",5) || !std::strncmp(ss,"argmin(",7) || !std::strncmp(ss,"argmax(",7) || !std::strncmp(ss,"argkth(",7)) { // Multi-argument functions _cimg_mp_op(*ss=='a'?(ss[1]=='v'?"Function 'avg()'": ss[3]=='k'?"Function 'argkth()'": ss[4]=='i'?"Function 'argmin()'": "Function 'argmax()'"): *ss=='s'?(ss[1]=='u'?"Function 'sum()'":"Function 'std()'"): *ss=='k'?"Function 'kth()'": *ss=='p'?"Function 'prod()'": *ss=='v'?"Function 'var()'": ss[1]=='i'?"Function 'min()'": ss[1]=='a'?"Function 'max()'":"Function 'med()'"); op = *ss=='a'?(ss[1]=='v'?mp_avg:ss[3]=='k'?mp_argkth:ss[4]=='i'?mp_argmin:mp_argmax): *ss=='s'?(ss[1]=='u'?mp_sum:mp_std): *ss=='k'?mp_kth: *ss=='p'?mp_prod: *ss=='v'?mp_var: ss[1]=='i'?mp_min: ss[1]=='a'?mp_max: ss[2]=='a'?mp_avg: mp_median; is_sth = true; // Tell if all arguments are constant pos = scalar(); CImg<ulongT>::vector((ulongT)op,pos,0).move_to(l_opcode); for (s = std::strchr(ss,'(') + 1; s<se; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; arg2 = compile(s,ns,depth1,0,is_single); if (_cimg_mp_is_vector(arg2)) CImg<ulongT>::sequence(_cimg_mp_size(arg2),arg2 + 1, arg2 + (ulongT)_cimg_mp_size(arg2)). move_to(l_opcode); else CImg<ulongT>::vector(arg2).move_to(l_opcode); is_sth&=_cimg_mp_is_constant(arg2); s = ns; } (l_opcode>'y').move_to(opcode); opcode[2] = opcode._height; if (is_sth) _cimg_mp_constant(op(*this)); opcode.move_to(code); _cimg_mp_return(pos); } // No corresponding built-in function -> Look for a user-defined macro call. s0 = strchr(ss,'('); if (s0) { variable_name.assign(ss,(unsigned int)(s0 - ss + 1)).back() = 0; // Count number of specified arguments. p1 = 0; for (s = s0 + 1; s<=se1; ++p1, s = ns + 1) { while (*s && cimg::is_blank(*s)) ++s; if (*s==')' && !p1) break; ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; } arg3 = 0; // Number of possible name matches cimglist_for(macro_def,l) if (!std::strcmp(macro_def[l],variable_name) && ++arg3 && macro_def[l].back()==(char)p1) { p2 = (unsigned int)macro_def[l].back(); // Number of required arguments CImg<charT> _expr = macro_body[l]; // Expression to be substituted p1 = 1; // Index of current parsed argument for (s = s0 + 1; s<=se1; ++p1, s = ns + 1) { // Parse function arguments while (*s && cimg::is_blank(*s)) ++s; if (*s==')' && p1==1) break; // Function has no arguments if (p1>p2) { ++p1; break; } ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=')' || level[ns - expr._data]!=clevel)) ++ns; variable_name.assign(s,(unsigned int)(ns - s + 1)).back() = 0; // Argument to write arg2 = 0; cimg_forX(_expr,k) { if (_expr[k]==(char)p1) { // Perform argument substitution arg1 = _expr._width; _expr.resize(arg1 + variable_name._width - 2,1,1,1,0); std::memmove(_expr._data + k + variable_name._width - 1,_expr._data + k + 1,arg1 - k - 1); std::memcpy(_expr._data + k,variable_name,variable_name._width - 1); k+=variable_name._width - 2; } ++arg2; } } // Recompute 'pexpr' and 'level' for evaluating substituted expression. CImg<charT> _pexpr(_expr._width); ns = _pexpr._data; for (ps = _expr._data, c1 = ' '; *ps; ++ps) { if (!cimg::is_blank(*ps)) c1 = *ps; *(ns++) = c1; } *ns = 0; CImg<uintT> _level = get_level(_expr); expr.swap(_expr); pexpr.swap(_pexpr); level.swap(_level); s0 = user_macro; user_macro = macro_def[l]; pos = compile(expr._data,expr._data + expr._width - 1,depth1,p_ref,is_single); user_macro = s0; level.swap(_level); pexpr.swap(_pexpr); expr.swap(_expr); _cimg_mp_return(pos); } if (arg3) { // Macro name matched but number of arguments does not CImg<uintT> sig_nargs(arg3); arg1 = 0; cimglist_for(macro_def,l) if (!std::strcmp(macro_def[l],variable_name)) sig_nargs[arg1++] = (unsigned int)macro_def[l].back(); *se = saved_char; cimg::strellipsize(variable_name,64); s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); if (sig_nargs._width>1) { sig_nargs.sort(); arg1 = sig_nargs.back(); --sig_nargs._width; throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: Function '%s()': Number of specified arguments (%u) " "does not match macro declaration (defined for %s or %u arguments), " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,variable_name._data, p1,sig_nargs.value_string()._data,arg1, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } else throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: Function '%s()': Number of specified arguments (%u) " "does not match macro declaration (defined for %u argument%s), " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,variable_name._data, p1,*sig_nargs,*sig_nargs!=1?"s":"", s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } } } // if (se1==')') // Char / string initializer. if (*se1=='\'' && ((se1>ss && *ss=='\'') || (se1>ss1 && *ss=='_' && *ss1=='\''))) { if (*ss=='_') { _cimg_mp_op("Char initializer"); s1 = ss2; } else { _cimg_mp_op("String initializer"); s1 = ss1; } arg1 = (unsigned int)(se1 - s1); // Original string length if (arg1) { CImg<charT>(s1,arg1 + 1).move_to(variable_name).back() = 0; cimg::strunescape(variable_name); arg1 = (unsigned int)std::strlen(variable_name); } if (!arg1) _cimg_mp_return(0); // Empty string -> 0 if (*ss=='_') { if (arg1==1) _cimg_mp_constant(*variable_name); *se = saved_char; cimg::strellipsize(variable_name,64); s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s: Literal %s contains more than one character, " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op, ss1, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } pos = vector(arg1); CImg<ulongT>::vector((ulongT)mp_string_init,pos,arg1).move_to(l_opcode); CImg<ulongT>(1,arg1/sizeof(ulongT) + (arg1%sizeof(ulongT)?1:0)).move_to(l_opcode); std::memcpy((char*)l_opcode[1]._data,variable_name,arg1); (l_opcode>'y').move_to(code); _cimg_mp_return(pos); } // Vector initializer [ ... ]. if (*ss=='[' && *se1==']') { _cimg_mp_op("Vector initializer"); s1 = ss1; while (s1<se2 && cimg::is_blank(*s1)) ++s1; s2 = se2; while (s2>s1 && cimg::is_blank(*s2)) --s2; if (s2>s1 && *s1=='\'' && *s2=='\'') { // Vector values provided as a string arg1 = (unsigned int)(s2 - s1 - 1); // Original string length if (arg1) { CImg<charT>(s1 + 1,arg1 + 1).move_to(variable_name).back() = 0; cimg::strunescape(variable_name); arg1 = (unsigned int)std::strlen(variable_name); } if (!arg1) _cimg_mp_return(0); // Empty string -> 0 pos = vector(arg1); CImg<ulongT>::vector((ulongT)mp_string_init,pos,arg1).move_to(l_opcode); CImg<ulongT>(1,arg1/sizeof(ulongT) + (arg1%sizeof(ulongT)?1:0)).move_to(l_opcode); std::memcpy((char*)l_opcode[1]._data,variable_name,arg1); (l_opcode>'y').move_to(code); } else { // Vector values provided as list of items arg1 = 0; // Number of specified values if (*ss1!=']') for (s = ss1; s<se; ++s) { ns = s; while (ns<se && (*ns!=',' || level[ns - expr._data]!=clevel1) && (*ns!=']' || level[ns - expr._data]!=clevel)) ++ns; arg2 = compile(s,ns,depth1,0,is_single); if (_cimg_mp_is_vector(arg2)) { arg3 = _cimg_mp_size(arg2); CImg<ulongT>::sequence(arg3,arg2 + 1,arg2 + arg3).move_to(l_opcode); arg1+=arg3; } else { CImg<ulongT>::vector(arg2).move_to(l_opcode); ++arg1; } s = ns; } if (!arg1) _cimg_mp_return(0); pos = vector(arg1); l_opcode.insert(CImg<ulongT>::vector((ulongT)mp_vector_init,pos,0,arg1),0); (l_opcode>'y').move_to(opcode); opcode[2] = opcode._height; opcode.move_to(code); } _cimg_mp_return(pos); } // Variables related to the input list of images. if (*ss1=='#' && ss2<se) { arg1 = compile(ss2,se,depth1,0,is_single); p1 = (unsigned int)(listin._width && _cimg_mp_is_constant(arg1)?cimg::mod((int)mem[arg1],listin.width()):~0U); switch (*ss) { case 'w' : // w#ind if (!listin) _cimg_mp_return(0); if (p1!=~0U) _cimg_mp_constant(listin[p1]._width); _cimg_mp_scalar1(mp_list_width,arg1); case 'h' : // h#ind if (!listin) _cimg_mp_return(0); if (p1!=~0U) _cimg_mp_constant(listin[p1]._height); _cimg_mp_scalar1(mp_list_height,arg1); case 'd' : // d#ind if (!listin) _cimg_mp_return(0); if (p1!=~0U) _cimg_mp_constant(listin[p1]._depth); _cimg_mp_scalar1(mp_list_depth,arg1); case 'r' : // r#ind if (!listin) _cimg_mp_return(0); if (p1!=~0U) _cimg_mp_constant(listin[p1]._is_shared); _cimg_mp_scalar1(mp_list_is_shared,arg1); case 's' : // s#ind if (!listin) _cimg_mp_return(0); if (p1!=~0U) _cimg_mp_constant(listin[p1]._spectrum); _cimg_mp_scalar1(mp_list_spectrum,arg1); case 'i' : // i#ind if (!listin) _cimg_mp_return(0); _cimg_mp_scalar7(mp_list_ixyzc,arg1,_cimg_mp_slot_x,_cimg_mp_slot_y,_cimg_mp_slot_z,_cimg_mp_slot_c, 0,_cimg_mp_boundary); case 'I' : // I#ind p2 = p1!=~0U?listin[p1]._spectrum:listin._width?~0U:0; if (!p2) _cimg_mp_return(0); pos = vector(p2); CImg<ulongT>::vector((ulongT)mp_list_Joff,pos,p1,0,0,p2).move_to(code); _cimg_mp_return(pos); case 'R' : // R#ind if (!listin) _cimg_mp_return(0); _cimg_mp_scalar7(mp_list_ixyzc,arg1,_cimg_mp_slot_x,_cimg_mp_slot_y,_cimg_mp_slot_z,0, 0,_cimg_mp_boundary); case 'G' : // G#ind if (!listin) _cimg_mp_return(0); _cimg_mp_scalar7(mp_list_ixyzc,arg1,_cimg_mp_slot_x,_cimg_mp_slot_y,_cimg_mp_slot_z,1, 0,_cimg_mp_boundary); case 'B' : // B#ind if (!listin) _cimg_mp_return(0); _cimg_mp_scalar7(mp_list_ixyzc,arg1,_cimg_mp_slot_x,_cimg_mp_slot_y,_cimg_mp_slot_z,2, 0,_cimg_mp_boundary); case 'A' : // A#ind if (!listin) _cimg_mp_return(0); _cimg_mp_scalar7(mp_list_ixyzc,arg1,_cimg_mp_slot_x,_cimg_mp_slot_y,_cimg_mp_slot_z,3, 0,_cimg_mp_boundary); } } if (*ss1 && *ss2=='#' && ss3<se) { arg1 = compile(ss3,se,depth1,0,is_single); p1 = (unsigned int)(listin._width && _cimg_mp_is_constant(arg1)?cimg::mod((int)mem[arg1],listin.width()):~0U); if (*ss=='w' && *ss1=='h') { // wh#ind if (!listin) _cimg_mp_return(0); if (p1!=~0U) _cimg_mp_constant(listin[p1]._width*listin[p1]._height); _cimg_mp_scalar1(mp_list_wh,arg1); } arg2 = ~0U; if (*ss=='i') { if (*ss1=='c') { // ic#ind if (!listin) _cimg_mp_return(0); if (_cimg_mp_is_constant(arg1)) { if (!list_median) list_median.assign(listin._width); if (!list_median[p1]) CImg<doubleT>::vector(listin[p1].median()).move_to(list_median[p1]); _cimg_mp_constant(*list_median[p1]); } _cimg_mp_scalar1(mp_list_median,arg1); } if (*ss1>='0' && *ss1<='9') { // i0#ind...i9#ind if (!listin) _cimg_mp_return(0); _cimg_mp_scalar7(mp_list_ixyzc,arg1,_cimg_mp_slot_x,_cimg_mp_slot_y,_cimg_mp_slot_z,*ss1 - '0', 0,_cimg_mp_boundary); } switch (*ss1) { case 'm' : arg2 = 0; break; // im#ind case 'M' : arg2 = 1; break; // iM#ind case 'a' : arg2 = 2; break; // ia#ind case 'v' : arg2 = 3; break; // iv#ind case 's' : arg2 = 12; break; // is#ind case 'p' : arg2 = 13; break; // ip#ind } } else if (*ss1=='m') switch (*ss) { case 'x' : arg2 = 4; break; // xm#ind case 'y' : arg2 = 5; break; // ym#ind case 'z' : arg2 = 6; break; // zm#ind case 'c' : arg2 = 7; break; // cm#ind } else if (*ss1=='M') switch (*ss) { case 'x' : arg2 = 8; break; // xM#ind case 'y' : arg2 = 9; break; // yM#ind case 'z' : arg2 = 10; break; // zM#ind case 'c' : arg2 = 11; break; // cM#ind } if (arg2!=~0U) { if (!listin) _cimg_mp_return(0); if (_cimg_mp_is_constant(arg1)) { if (!list_stats) list_stats.assign(listin._width); if (!list_stats[p1]) list_stats[p1].assign(1,14,1,1,0).fill(listin[p1].get_stats(),false); _cimg_mp_constant(list_stats(p1,arg2)); } _cimg_mp_scalar2(mp_list_stats,arg1,arg2); } } if (*ss=='w' && *ss1=='h' && *ss2=='d' && *ss3=='#' && ss4<se) { // whd#ind arg1 = compile(ss4,se,depth1,0,is_single); if (!listin) _cimg_mp_return(0); p1 = (unsigned int)(_cimg_mp_is_constant(arg1)?cimg::mod((int)mem[arg1],listin.width()):~0U); if (p1!=~0U) _cimg_mp_constant(listin[p1]._width*listin[p1]._height*listin[p1]._depth); _cimg_mp_scalar1(mp_list_whd,arg1); } if (*ss=='w' && *ss1=='h' && *ss2=='d' && *ss3=='s' && *ss4=='#' && ss5<se) { // whds#ind arg1 = compile(ss5,se,depth1,0,is_single); if (!listin) _cimg_mp_return(0); p1 = (unsigned int)(_cimg_mp_is_constant(arg1)?cimg::mod((int)mem[arg1],listin.width()):~0U); if (p1!=~0U) _cimg_mp_constant(listin[p1]._width*listin[p1]._height*listin[p1]._depth*listin[p1]._spectrum); _cimg_mp_scalar1(mp_list_whds,arg1); } if (!std::strcmp(ss,"interpolation")) _cimg_mp_return(_cimg_mp_interpolation); // interpolation if (!std::strcmp(ss,"boundary")) _cimg_mp_return(_cimg_mp_boundary); // boundary // No known item found, assuming this is an already initialized variable. variable_name.assign(ss,(unsigned int)(se - ss + 1)).back() = 0; if (variable_name[1]) { // Multi-char variable cimglist_for(variable_def,i) if (!std::strcmp(variable_name,variable_def[i])) _cimg_mp_return(variable_pos[i]); } else if (reserved_label[(int)*variable_name]!=~0U) // Single-char variable _cimg_mp_return(reserved_label[(int)*variable_name]); // Reached an unknown item -> error. is_sth = true; // is_valid_variable_name if (*variable_name>='0' && *variable_name<='9') is_sth = false; else for (ns = variable_name._data; *ns; ++ns) if (!is_varchar(*ns)) { is_sth = false; break; } *se = saved_char; c1 = *se1; cimg::strellipsize(variable_name,64); s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); if (is_sth) throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: Undefined variable '%s' in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function, variable_name._data, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); s1 = std::strchr(ss,'('); s_op = s1 && c1==')'?"function call":"item"; throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: Unrecognized %s '%s' in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function, s_op,variable_name._data, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } // Evaluation procedure. double operator()(const double x, const double y, const double z, const double c) { mem[_cimg_mp_slot_x] = x; mem[_cimg_mp_slot_y] = y; mem[_cimg_mp_slot_z] = z; mem[_cimg_mp_slot_c] = c; for (p_code = code; p_code<p_code_end; ++p_code) { opcode._data = p_code->_data; const ulongT target = opcode[1]; mem[target] = _cimg_mp_defunc(*this); } return *result; } // Evaluation procedure (return output values in vector 'output'). template<typename t> void operator()(const double x, const double y, const double z, const double c, t *const output) { mem[_cimg_mp_slot_x] = x; mem[_cimg_mp_slot_y] = y; mem[_cimg_mp_slot_z] = z; mem[_cimg_mp_slot_c] = c; for (p_code = code; p_code<p_code_end; ++p_code) { opcode._data = p_code->_data; const ulongT target = opcode[1]; mem[target] = _cimg_mp_defunc(*this); } if (result_dim) { const double *ptrs = result + 1; t *ptrd = output; for (unsigned int k = 0; k<result_dim; ++k) *(ptrd++) = (t)*(ptrs++); } else *output = (t)*result; } // Evaluation procedure for the end() blocks. void end() { if (code_end.is_empty()) return; if (imgin) { mem[_cimg_mp_slot_x] = imgin._width - 1.; mem[_cimg_mp_slot_y] = imgin._height - 1.; mem[_cimg_mp_slot_z] = imgin._depth - 1.; mem[_cimg_mp_slot_c] = imgin._spectrum - 1.; } else mem[_cimg_mp_slot_x] = mem[_cimg_mp_slot_y] = mem[_cimg_mp_slot_z] = mem[_cimg_mp_slot_c] = 0; p_code_end = code_end.end(); for (p_code = code_end; p_code<p_code_end; ++p_code) { opcode._data = p_code->_data; const ulongT target = opcode[1]; mem[target] = _cimg_mp_defunc(*this); } } // Return type of a memory element as a string. CImg<charT> s_type(const unsigned int arg) const { CImg<charT> res; if (_cimg_mp_is_vector(arg)) { // Vector CImg<charT>::string("vectorXXXXXXXXXXXXXXXX").move_to(res); cimg_sprintf(res._data + 6,"%u",_cimg_mp_size(arg)); } else CImg<charT>::string("scalar").move_to(res); return res; } // Insert constant value in memory. unsigned int constant(const double val) { // Search for built-in constant. if (cimg::type<double>::is_nan(val)) return _cimg_mp_slot_nan; if (val==(double)(int)val) { if (val>=0 && val<=10) return (unsigned int)val; if (val<0 && val>=-5) return (unsigned int)(10 - val); } if (val==0.5) return 16; // Search for constant already requested before (in const cache). unsigned int ind = ~0U; if (constcache_size<1024) { if (!constcache_size) { constcache_vals.assign(16,1,1,1,0); constcache_inds.assign(16,1,1,1,0); *constcache_vals = val; constcache_size = 1; ind = 0; } else { // Dichotomic search const double val_beg = *constcache_vals, val_end = constcache_vals[constcache_size - 1]; if (val_beg>=val) ind = 0; else if (val_end==val) ind = constcache_size - 1; else if (val_end<val) ind = constcache_size; else { unsigned int i0 = 1, i1 = constcache_size - 2; while (i0<=i1) { const unsigned int mid = (i0 + i1)/2; if (constcache_vals[mid]==val) { i0 = mid; break; } else if (constcache_vals[mid]<val) i0 = mid + 1; else i1 = mid - 1; } ind = i0; } if (ind>=constcache_size || constcache_vals[ind]!=val) { ++constcache_size; if (constcache_size>constcache_vals._width) { constcache_vals.resize(-200,1,1,1,0); constcache_inds.resize(-200,1,1,1,0); } const int l = constcache_size - (int)ind - 1; if (l>0) { std::memmove(&constcache_vals[ind + 1],&constcache_vals[ind],l*sizeof(double)); std::memmove(&constcache_inds[ind + 1],&constcache_inds[ind],l*sizeof(unsigned int)); } constcache_vals[ind] = val; constcache_inds[ind] = 0; } } if (constcache_inds[ind]) return constcache_inds[ind]; } // Insert new constant in memory if necessary. if (mempos>=mem._width) { mem.resize(-200,1,1,1,0); memtype.resize(-200,1,1,1,0); } const unsigned int pos = mempos++; mem[pos] = val; memtype[pos] = 1; // Set constant property if (ind!=~0U) constcache_inds[ind] = pos; return pos; } // Insert code instructions for processing scalars. unsigned int scalar() { // Insert new scalar in memory if (mempos>=mem._width) { mem.resize(-200,1,1,1,0); memtype.resize(mem._width,1,1,1,0); } return mempos++; } unsigned int scalar0(const mp_func op) { const unsigned int pos = scalar(); CImg<ulongT>::vector((ulongT)op,pos).move_to(code); return pos; } unsigned int scalar1(const mp_func op, const unsigned int arg1) { const unsigned int pos = arg1!=~0U && arg1>_cimg_mp_slot_c && _cimg_mp_is_comp(arg1) && op!=mp_copy?arg1:scalar(); CImg<ulongT>::vector((ulongT)op,pos,arg1).move_to(code); return pos; } unsigned int scalar2(const mp_func op, const unsigned int arg1, const unsigned int arg2) { const unsigned int pos = arg1!=~0U && arg1>_cimg_mp_slot_c && _cimg_mp_is_comp(arg1)?arg1: arg2!=~0U && arg2>_cimg_mp_slot_c && _cimg_mp_is_comp(arg2)?arg2:scalar(); CImg<ulongT>::vector((ulongT)op,pos,arg1,arg2).move_to(code); return pos; } unsigned int scalar3(const mp_func op, const unsigned int arg1, const unsigned int arg2, const unsigned int arg3) { const unsigned int pos = arg1!=~0U && arg1>_cimg_mp_slot_c && _cimg_mp_is_comp(arg1)?arg1: arg2!=~0U && arg2>_cimg_mp_slot_c && _cimg_mp_is_comp(arg2)?arg2: arg3!=~0U && arg3>_cimg_mp_slot_c && _cimg_mp_is_comp(arg3)?arg3:scalar(); CImg<ulongT>::vector((ulongT)op,pos,arg1,arg2,arg3).move_to(code); return pos; } unsigned int scalar4(const mp_func op, const unsigned int arg1, const unsigned int arg2, const unsigned int arg3, const unsigned int arg4) { const unsigned int pos = arg1!=~0U && arg1>_cimg_mp_slot_c && _cimg_mp_is_comp(arg1)?arg1: arg2!=~0U && arg2>_cimg_mp_slot_c && _cimg_mp_is_comp(arg2)?arg2: arg3!=~0U && arg3>_cimg_mp_slot_c && _cimg_mp_is_comp(arg3)?arg3: arg4!=~0U && arg4>_cimg_mp_slot_c && _cimg_mp_is_comp(arg4)?arg4:scalar(); CImg<ulongT>::vector((ulongT)op,pos,arg1,arg2,arg3,arg4).move_to(code); return pos; } unsigned int scalar5(const mp_func op, const unsigned int arg1, const unsigned int arg2, const unsigned int arg3, const unsigned int arg4, const unsigned int arg5) { const unsigned int pos = arg1!=~0U && arg1>_cimg_mp_slot_c && _cimg_mp_is_comp(arg1)?arg1: arg2!=~0U && arg2>_cimg_mp_slot_c && _cimg_mp_is_comp(arg2)?arg2: arg3!=~0U && arg3>_cimg_mp_slot_c && _cimg_mp_is_comp(arg3)?arg3: arg4!=~0U && arg4>_cimg_mp_slot_c && _cimg_mp_is_comp(arg4)?arg4: arg5!=~0U && arg5>_cimg_mp_slot_c && _cimg_mp_is_comp(arg5)?arg5:scalar(); CImg<ulongT>::vector((ulongT)op,pos,arg1,arg2,arg3,arg4,arg5).move_to(code); return pos; } unsigned int scalar6(const mp_func op, const unsigned int arg1, const unsigned int arg2, const unsigned int arg3, const unsigned int arg4, const unsigned int arg5, const unsigned int arg6) { const unsigned int pos = arg1!=~0U && arg1>_cimg_mp_slot_c && _cimg_mp_is_comp(arg1)?arg1: arg2!=~0U && arg2>_cimg_mp_slot_c && _cimg_mp_is_comp(arg2)?arg2: arg3!=~0U && arg3>_cimg_mp_slot_c && _cimg_mp_is_comp(arg3)?arg3: arg4!=~0U && arg4>_cimg_mp_slot_c && _cimg_mp_is_comp(arg4)?arg4: arg5!=~0U && arg5>_cimg_mp_slot_c && _cimg_mp_is_comp(arg5)?arg5: arg6!=~0U && arg6>_cimg_mp_slot_c && _cimg_mp_is_comp(arg6)?arg6:scalar(); CImg<ulongT>::vector((ulongT)op,pos,arg1,arg2,arg3,arg4,arg5,arg6).move_to(code); return pos; } unsigned int scalar7(const mp_func op, const unsigned int arg1, const unsigned int arg2, const unsigned int arg3, const unsigned int arg4, const unsigned int arg5, const unsigned int arg6, const unsigned int arg7) { const unsigned int pos = arg1!=~0U && arg1>_cimg_mp_slot_c && _cimg_mp_is_comp(arg1)?arg1: arg2!=~0U && arg2>_cimg_mp_slot_c && _cimg_mp_is_comp(arg2)?arg2: arg3!=~0U && arg3>_cimg_mp_slot_c && _cimg_mp_is_comp(arg3)?arg3: arg4!=~0U && arg4>_cimg_mp_slot_c && _cimg_mp_is_comp(arg4)?arg4: arg5!=~0U && arg5>_cimg_mp_slot_c && _cimg_mp_is_comp(arg5)?arg5: arg6!=~0U && arg6>_cimg_mp_slot_c && _cimg_mp_is_comp(arg6)?arg6: arg7!=~0U && arg7>_cimg_mp_slot_c && _cimg_mp_is_comp(arg7)?arg7:scalar(); CImg<ulongT>::vector((ulongT)op,pos,arg1,arg2,arg3,arg4,arg5,arg6,arg7).move_to(code); return pos; } // Return a string that defines the calling function + the user-defined function scope. CImg<charT> calling_function_s() const { CImg<charT> res; const unsigned int l1 = calling_function?(unsigned int)std::strlen(calling_function):0U, l2 = user_macro?(unsigned int)std::strlen(user_macro):0U; if (l2) { res.assign(l1 + l2 + 48); cimg_snprintf(res,res._width,"%s(): When substituting function '%s()'",calling_function,user_macro); } else { res.assign(l1 + l2 + 4); cimg_snprintf(res,res._width,"%s()",calling_function); } return res; } // Return true if specified argument can be a part of an allowed variable name. bool is_varchar(const char c) const { return (c>='a' && c<='z') || (c>='A' && c<='Z') || (c>='0' && c<='9') || c=='_'; } // Insert code instructions for processing vectors. bool is_comp_vector(const unsigned int arg) const { unsigned int siz = _cimg_mp_size(arg); if (siz>8) return false; const int *ptr = memtype.data(arg + 1); bool is_tmp = true; while (siz-->0) if (*(ptr++)) { is_tmp = false; break; } return is_tmp; } void set_variable_vector(const unsigned int arg) { unsigned int siz = _cimg_mp_size(arg); int *ptr = memtype.data(arg + 1); while (siz-->0) *(ptr++) = -1; } unsigned int vector(const unsigned int siz) { // Insert new vector of specified size in memory if (mempos + siz>=mem._width) { mem.resize(2*mem._width + siz,1,1,1,0); memtype.resize(mem._width,1,1,1,0); } const unsigned int pos = mempos++; mem[pos] = cimg::type<double>::nan(); memtype[pos] = siz + 1; mempos+=siz; return pos; } unsigned int vector(const unsigned int siz, const double value) { // Insert new initialized vector const unsigned int pos = vector(siz); double *ptr = &mem[pos] + 1; for (unsigned int i = 0; i<siz; ++i) *(ptr++) = value; return pos; } unsigned int vector_copy(const unsigned int arg) { // Insert new copy of specified vector in memory const unsigned int siz = _cimg_mp_size(arg), pos = vector(siz); CImg<ulongT>::vector((ulongT)mp_vector_copy,pos,arg,siz).move_to(code); return pos; } void self_vector_s(const unsigned int pos, const mp_func op, const unsigned int arg1) { const unsigned int siz = _cimg_mp_size(pos); if (siz>24) CImg<ulongT>::vector((ulongT)mp_self_map_vector_s,pos,siz,(ulongT)op,arg1).move_to(code); else { code.insert(siz); for (unsigned int k = 1; k<=siz; ++k) CImg<ulongT>::vector((ulongT)op,pos + k,arg1).move_to(code[code._width - 1 - siz + k]); } } void self_vector_v(const unsigned int pos, const mp_func op, const unsigned int arg1) { const unsigned int siz = _cimg_mp_size(pos); if (siz>24) CImg<ulongT>::vector((ulongT)mp_self_map_vector_v,pos,siz,(ulongT)op,arg1).move_to(code); else { code.insert(siz); for (unsigned int k = 1; k<=siz; ++k) CImg<ulongT>::vector((ulongT)op,pos + k,arg1 + k).move_to(code[code._width - 1 - siz + k]); } } unsigned int vector1_v(const mp_func op, const unsigned int arg1) { const unsigned int siz = _cimg_mp_size(arg1), pos = is_comp_vector(arg1)?arg1:vector(siz); if (siz>24) CImg<ulongT>::vector((ulongT)mp_vector_map_v,pos,siz,(ulongT)op,arg1).move_to(code); else { code.insert(siz); for (unsigned int k = 1; k<=siz; ++k) CImg<ulongT>::vector((ulongT)op,pos + k,arg1 + k).move_to(code[code._width - 1 - siz + k]); } return pos; } unsigned int vector2_vv(const mp_func op, const unsigned int arg1, const unsigned int arg2) { const unsigned int siz = _cimg_mp_size(arg1), pos = is_comp_vector(arg1)?arg1:is_comp_vector(arg2)?arg2:vector(siz); if (siz>24) CImg<ulongT>::vector((ulongT)mp_vector_map_vv,pos,siz,(ulongT)op,arg1,arg2).move_to(code); else { code.insert(siz); for (unsigned int k = 1; k<=siz; ++k) CImg<ulongT>::vector((ulongT)op,pos + k,arg1 + k,arg2 + k).move_to(code[code._width - 1 - siz + k]); } return pos; } unsigned int vector2_vs(const mp_func op, const unsigned int arg1, const unsigned int arg2) { const unsigned int siz = _cimg_mp_size(arg1), pos = is_comp_vector(arg1)?arg1:vector(siz); if (siz>24) CImg<ulongT>::vector((ulongT)mp_vector_map_vs,pos,siz,(ulongT)op,arg1,arg2).move_to(code); else { code.insert(siz); for (unsigned int k = 1; k<=siz; ++k) CImg<ulongT>::vector((ulongT)op,pos + k,arg1 + k,arg2).move_to(code[code._width - 1 - siz + k]); } return pos; } unsigned int vector2_sv(const mp_func op, const unsigned int arg1, const unsigned int arg2) { const unsigned int siz = _cimg_mp_size(arg2), pos = is_comp_vector(arg2)?arg2:vector(siz); if (siz>24) CImg<ulongT>::vector((ulongT)mp_vector_map_sv,pos,siz,(ulongT)op,arg1,arg2).move_to(code); else { code.insert(siz); for (unsigned int k = 1; k<=siz; ++k) CImg<ulongT>::vector((ulongT)op,pos + k,arg1,arg2 + k).move_to(code[code._width - 1 - siz + k]); } return pos; } unsigned int vector3_vss(const mp_func op, const unsigned int arg1, const unsigned int arg2, const unsigned int arg3) { const unsigned int siz = _cimg_mp_size(arg1), pos = is_comp_vector(arg1)?arg1:vector(siz); if (siz>24) CImg<ulongT>::vector((ulongT)mp_vector_map_vss,pos,siz,(ulongT)op,arg1,arg2,arg3).move_to(code); else { code.insert(siz); for (unsigned int k = 1; k<=siz; ++k) CImg<ulongT>::vector((ulongT)op,pos + k,arg1 + k,arg2,arg3).move_to(code[code._width - 1 - siz + k]); } return pos; } // Check if a memory slot is a positive integer constant scalar value. // 'mode' can be: // { 0=constant | 1=integer constant | 2=positive integer constant | 3=strictly-positive integer constant } void check_constant(const unsigned int arg, const unsigned int n_arg, const unsigned int mode, char *const ss, char *const se, const char saved_char) { _cimg_mp_check_type(arg,n_arg,1,0); if (!(_cimg_mp_is_constant(arg) && (!mode || (double)(int)mem[arg]==mem[arg]) && (mode<2 || mem[arg]>=(mode==3)))) { const char *s_arg = !n_arg?"":n_arg==1?"First ":n_arg==2?"Second ":n_arg==3?"Third ": n_arg==4?"Fourth ":n_arg==5?"Fifth ":n_arg==6?"Sixth ":n_arg==7?"Seventh ":n_arg==8?"Eighth ": n_arg==9?"Ninth ":"One of the "; *se = saved_char; char *const s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s%s %s%s (of type '%s') is not a%s constant, " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op,*s_op?":":"", s_arg,*s_arg?"argument":"Argument",s_type(arg)._data, !mode?"":mode==1?"n integer": mode==2?" positive integer":" strictly positive integer", s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } } // Check a matrix is square. void check_matrix_square(const unsigned int arg, const unsigned int n_arg, char *const ss, char *const se, const char saved_char) { _cimg_mp_check_type(arg,n_arg,2,0); const unsigned int siz = _cimg_mp_size(arg), n = (unsigned int)cimg::round(std::sqrt((float)siz)); if (n*n!=siz) { const char *s_arg; if (*s_op!='F') s_arg = !n_arg?"":n_arg==1?"Left-hand ":"Right-hand "; else s_arg = !n_arg?"":n_arg==1?"First ":n_arg==2?"Second ":n_arg==3?"Third ":"One "; *se = saved_char; char *const s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s%s %s%s (of type '%s') " "cannot be considered as a square matrix, in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op,*s_op?":":"", s_arg,*s_op=='F'?(*s_arg?"argument":"Argument"):(*s_arg?"operand":"Operand"), s_type(arg)._data, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } } // Check type compatibility for one argument. // Bits of 'mode' tells what types are allowed: // { 1 = scalar | 2 = vectorN }. // If 'N' is not zero, it also restricts the vectors to be of size N only. void check_type(const unsigned int arg, const unsigned int n_arg, const unsigned int mode, const unsigned int N, char *const ss, char *const se, const char saved_char) { const bool is_scalar = _cimg_mp_is_scalar(arg), is_vector = _cimg_mp_is_vector(arg) && (!N || _cimg_mp_size(arg)==N); bool cond = false; if (mode&1) cond|=is_scalar; if (mode&2) cond|=is_vector; if (!cond) { const char *s_arg; if (*s_op!='F') s_arg = !n_arg?"":n_arg==1?"Left-hand ":"Right-hand "; else s_arg = !n_arg?"":n_arg==1?"First ":n_arg==2?"Second ":n_arg==3?"Third ": n_arg==4?"Fourth ":n_arg==5?"Fifth ":n_arg==6?"Sixth ":n_arg==7?"Seventh ":n_arg==8?"Eighth": n_arg==9?"Ninth":"One of the "; CImg<charT> sb_type(32); if (mode==1) cimg_snprintf(sb_type,sb_type._width,"'scalar'"); else if (mode==2) { if (N) cimg_snprintf(sb_type,sb_type._width,"'vector%u'",N); else cimg_snprintf(sb_type,sb_type._width,"'vector'"); } else { if (N) cimg_snprintf(sb_type,sb_type._width,"'scalar' or 'vector%u'",N); else cimg_snprintf(sb_type,sb_type._width,"'scalar' or 'vector'"); } *se = saved_char; char *const s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s%s %s%s has invalid type '%s' (should be %s), " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op,*s_op?":":"", s_arg,*s_op=='F'?(*s_arg?"argument":"Argument"):(*s_arg?"operand":"Operand"), s_type(arg)._data,sb_type._data, s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } } // Check that listin or listout are not empty. void check_list(const bool is_out, char *const ss, char *const se, const char saved_char) { if ((!is_out && !listin) || (is_out && !listout)) { *se = saved_char; char *const s0 = ss - 4>expr._data?ss - 4:expr._data; cimg::strellipsize(s0,64); throw CImgArgumentException("[" cimg_appname "_math_parser] " "CImg<%s>::%s: %s%s Invalid call with an empty image list, " "in expression '%s%s%s'.", pixel_type(),_cimg_mp_calling_function,s_op,*s_op?":":"", s0!=expr._data?"...":"",s0,se<&expr.back()?"...":""); } } // Evaluation functions, known by the parser. // Defining these functions 'static' ensures that sizeof(mp_func)==sizeof(ulongT), // so we can store pointers to them directly in the opcode vectors. #ifdef _mp_arg #undef _mp_arg #endif #define _mp_arg(x) mp.mem[mp.opcode[x]] static double mp_abs(_cimg_math_parser& mp) { return cimg::abs(_mp_arg(2)); } static double mp_add(_cimg_math_parser& mp) { return _mp_arg(2) + _mp_arg(3); } static double mp_acos(_cimg_math_parser& mp) { return std::acos(_mp_arg(2)); } static double mp_acosh(_cimg_math_parser& mp) { return cimg::acosh(_mp_arg(2)); } static double mp_asinh(_cimg_math_parser& mp) { return cimg::asinh(_mp_arg(2)); } static double mp_atanh(_cimg_math_parser& mp) { return cimg::atanh(_mp_arg(2)); } static double mp_arg(_cimg_math_parser& mp) { const int _ind = (int)_mp_arg(4); const unsigned int nb_args = (unsigned int)mp.opcode[2] - 4, ind = _ind<0?_ind + nb_args:(unsigned int)_ind, siz = (unsigned int)mp.opcode[3]; if (siz>0) { if (ind>=nb_args) std::memset(&_mp_arg(1) + 1,0,siz*sizeof(double)); else std::memcpy(&_mp_arg(1) + 1,&_mp_arg(ind + 4) + 1,siz*sizeof(double)); return cimg::type<double>::nan(); } if (ind>=nb_args) return 0; return _mp_arg(ind + 4); } static double mp_argkth(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; const double val = mp_kth(mp); for (unsigned int i = 4; i<i_end; ++i) if (val==_mp_arg(i)) return i - 3.; return 1; } static double mp_argmin(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; double val = _mp_arg(3); unsigned int argval = 0; for (unsigned int i = 4; i<i_end; ++i) { const double _val = _mp_arg(i); if (_val<val) { val = _val; argval = i - 3; } } return (double)argval; } static double mp_argmax(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; double val = _mp_arg(3); unsigned int argval = 0; for (unsigned int i = 4; i<i_end; ++i) { const double _val = _mp_arg(i); if (_val>val) { val = _val; argval = i - 3; } } return (double)argval; } static double mp_asin(_cimg_math_parser& mp) { return std::asin(_mp_arg(2)); } static double mp_atan(_cimg_math_parser& mp) { return std::atan(_mp_arg(2)); } static double mp_atan2(_cimg_math_parser& mp) { return std::atan2(_mp_arg(2),_mp_arg(3)); } static double mp_avg(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; double val = _mp_arg(3); for (unsigned int i = 4; i<i_end; ++i) val+=_mp_arg(i); return val/(i_end - 3); } static double mp_bitwise_and(_cimg_math_parser& mp) { return (double)((longT)_mp_arg(2) & (longT)_mp_arg(3)); } static double mp_bitwise_left_shift(_cimg_math_parser& mp) { return (double)((longT)_mp_arg(2)<<(unsigned int)_mp_arg(3)); } static double mp_bitwise_not(_cimg_math_parser& mp) { // Limit result to 32bits such that it can be entirely represented as a 'double'. return (double)~(unsigned int)_mp_arg(2); } static double mp_bitwise_or(_cimg_math_parser& mp) { return (double)((longT)_mp_arg(2) | (longT)_mp_arg(3)); } static double mp_bitwise_right_shift(_cimg_math_parser& mp) { return (double)((longT)_mp_arg(2)>>(unsigned int)_mp_arg(3)); } static double mp_bitwise_xor(_cimg_math_parser& mp) { return (double)((longT)_mp_arg(2) ^ (longT)_mp_arg(3)); } static double mp_bool(_cimg_math_parser& mp) { return (double)(bool)_mp_arg(2); } static double mp_break(_cimg_math_parser& mp) { mp.break_type = 1; mp.p_code = mp.p_break - 1; return cimg::type<double>::nan(); } static double mp_breakpoint(_cimg_math_parser& mp) { cimg_abort_init; cimg_abort_test; cimg::unused(mp); return cimg::type<double>::nan(); } static double mp_cats(_cimg_math_parser& mp) { const double *ptrd = &_mp_arg(1) + 1; const unsigned int sizd = (unsigned int)mp.opcode[2], nb_args = (unsigned int)(mp.opcode[3] - 4)/2; CImgList<charT> _str; for (unsigned int n = 0; n<nb_args; ++n) { const unsigned int siz = (unsigned int)mp.opcode[5 + 2*n]; if (siz) { // Vector argument const double *ptrs = &_mp_arg(4 + 2*n) + 1; unsigned int l = 0; while (l<siz && ptrs[l]) ++l; CImg<doubleT>(ptrs,l,1,1,1,true).move_to(_str); } else CImg<charT>::vector((char)_mp_arg(4 + 2*n)).move_to(_str); // Scalar argument } CImg(1,1,1,1,0).move_to(_str); const CImg<charT> str = _str>'x'; const unsigned int l = std::min(str._width,sizd); CImg<doubleT>(ptrd,l,1,1,1,true) = str.get_shared_points(0,l - 1); return cimg::type<double>::nan(); } static double mp_cbrt(_cimg_math_parser& mp) { return cimg::cbrt(_mp_arg(2)); } static double mp_ceil(_cimg_math_parser& mp) { return std::ceil(_mp_arg(2)); } static double mp_complex_abs(_cimg_math_parser& mp) { return cimg::_hypot(_mp_arg(2),_mp_arg(3)); } static double mp_complex_conj(_cimg_math_parser& mp) { const double *ptrs = &_mp_arg(2) + 1; double *ptrd = &_mp_arg(1) + 1; *(ptrd++) = *(ptrs++); *ptrd = -*(ptrs); return cimg::type<double>::nan(); } static double mp_complex_div_sv(_cimg_math_parser& mp) { const double *ptr2 = &_mp_arg(3) + 1, r1 = _mp_arg(2), r2 = *(ptr2++), i2 = *ptr2; double *ptrd = &_mp_arg(1) + 1; const double denom = r2*r2 + i2*i2; *(ptrd++) = r1*r2/denom; *ptrd = -r1*i2/denom; return cimg::type<double>::nan(); } static double mp_complex_div_vv(_cimg_math_parser& mp) { const double *ptr1 = &_mp_arg(2) + 1, *ptr2 = &_mp_arg(3) + 1, r1 = *(ptr1++), i1 = *ptr1, r2 = *(ptr2++), i2 = *ptr2; double *ptrd = &_mp_arg(1) + 1; const double denom = r2*r2 + i2*i2; *(ptrd++) = (r1*r2 + i1*i2)/denom; *ptrd = (r2*i1 - r1*i2)/denom; return cimg::type<double>::nan(); } static double mp_complex_exp(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const double *ptrs = &_mp_arg(2) + 1, r = *(ptrs++), i = *(ptrs), er = std::exp(r); *(ptrd++) = er*std::cos(i); *(ptrd++) = er*std::sin(i); return cimg::type<double>::nan(); } static double mp_complex_log(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const double *ptrs = &_mp_arg(2) + 1, r = *(ptrs++), i = *(ptrs); *(ptrd++) = 0.5*std::log(r*r + i*i); *(ptrd++) = std::atan2(i,r); return cimg::type<double>::nan(); } static double mp_complex_mul(_cimg_math_parser& mp) { const double *ptr1 = &_mp_arg(2) + 1, *ptr2 = &_mp_arg(3) + 1, r1 = *(ptr1++), i1 = *ptr1, r2 = *(ptr2++), i2 = *ptr2; double *ptrd = &_mp_arg(1) + 1; *(ptrd++) = r1*r2 - i1*i2; *(ptrd++) = r1*i2 + r2*i1; return cimg::type<double>::nan(); } static void _mp_complex_pow(const double r1, const double i1, const double r2, const double i2, double *ptrd) { double ro, io; if (cimg::abs(i2)<1e-15) { // Exponent is real if (cimg::abs(r1)<1e-15 && cimg::abs(i1)<1e-15) { if (cimg::abs(r2)<1e-15) { ro = 1; io = 0; } else ro = io = 0; } else { const double mod1_2 = r1*r1 + i1*i1, phi1 = std::atan2(i1,r1), modo = std::pow(mod1_2,0.5*r2), phio = r2*phi1; ro = modo*std::cos(phio); io = modo*std::sin(phio); } } else { // Exponent is complex if (cimg::abs(r1)<1e-15 && cimg::abs(i1)<1e-15) ro = io = 0; const double mod1_2 = r1*r1 + i1*i1, phi1 = std::atan2(i1,r1), modo = std::pow(mod1_2,0.5*r2)*std::exp(-i2*phi1), phio = r2*phi1 + 0.5*i2*std::log(mod1_2); ro = modo*std::cos(phio); io = modo*std::sin(phio); } *(ptrd++) = ro; *ptrd = io; } static double mp_complex_pow_ss(_cimg_math_parser& mp) { const double val1 = _mp_arg(2), val2 = _mp_arg(3); double *ptrd = &_mp_arg(1) + 1; _mp_complex_pow(val1,0,val2,0,ptrd); return cimg::type<double>::nan(); } static double mp_complex_pow_sv(_cimg_math_parser& mp) { const double val1 = _mp_arg(2), *ptr2 = &_mp_arg(3) + 1; double *ptrd = &_mp_arg(1) + 1; _mp_complex_pow(val1,0,ptr2[0],ptr2[1],ptrd); return cimg::type<double>::nan(); } static double mp_complex_pow_vs(_cimg_math_parser& mp) { const double *ptr1 = &_mp_arg(2) + 1, val2 = _mp_arg(3); double *ptrd = &_mp_arg(1) + 1; _mp_complex_pow(ptr1[0],ptr1[1],val2,0,ptrd); return cimg::type<double>::nan(); } static double mp_complex_pow_vv(_cimg_math_parser& mp) { const double *ptr1 = &_mp_arg(2) + 1, *ptr2 = &_mp_arg(3) + 1; double *ptrd = &_mp_arg(1) + 1; _mp_complex_pow(ptr1[0],ptr1[1],ptr2[0],ptr2[1],ptrd); return cimg::type<double>::nan(); } static double mp_continue(_cimg_math_parser& mp) { mp.break_type = 2; mp.p_code = mp.p_break - 1; return cimg::type<double>::nan(); } static double mp_cos(_cimg_math_parser& mp) { return std::cos(_mp_arg(2)); } static double mp_cosh(_cimg_math_parser& mp) { return std::cosh(_mp_arg(2)); } static double mp_critical(_cimg_math_parser& mp) { const double res = _mp_arg(1); cimg_pragma_openmp(critical(mp_critical)) { for (const CImg<ulongT> *const p_end = ++mp.p_code + mp.opcode[2]; mp.p_code<p_end; ++mp.p_code) { // Evaluate body mp.opcode._data = mp.p_code->_data; const ulongT target = mp.opcode[1]; mp.mem[target] = _cimg_mp_defunc(mp); } } --mp.p_code; return res; } static double mp_crop(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const int x = (int)_mp_arg(3), y = (int)_mp_arg(4), z = (int)_mp_arg(5), c = (int)_mp_arg(6); const unsigned int dx = (unsigned int)mp.opcode[7], dy = (unsigned int)mp.opcode[8], dz = (unsigned int)mp.opcode[9], dc = (unsigned int)mp.opcode[10]; const unsigned int boundary_conditions = (unsigned int)_mp_arg(11); unsigned int ind = (unsigned int)mp.opcode[2]; if (ind!=~0U) ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); const CImg<T> &img = ind==~0U?mp.imgin:mp.listin[ind]; if (!img) std::memset(ptrd,0,dx*dy*dz*dc*sizeof(double)); else CImg<doubleT>(ptrd,dx,dy,dz,dc,true) = img.get_crop(x,y,z,c, x + dx - 1,y + dy - 1, z + dz - 1,c + dc - 1, boundary_conditions); return cimg::type<double>::nan(); } static double mp_cross(_cimg_math_parser& mp) { CImg<doubleT> vout(&_mp_arg(1) + 1,1,3,1,1,true), v1(&_mp_arg(2) + 1,1,3,1,1,true), v2(&_mp_arg(3) + 1,1,3,1,1,true); (vout = v1).cross(v2); return cimg::type<double>::nan(); } static double mp_cut(_cimg_math_parser& mp) { double val = _mp_arg(2), cmin = _mp_arg(3), cmax = _mp_arg(4); return val<cmin?cmin:val>cmax?cmax:val; } static double mp_date(_cimg_math_parser& mp) { const unsigned int siz_out = (unsigned int)mp.opcode[2], siz_arg1 = (unsigned int)mp.opcode[4], siz_arg2 = (unsigned int)mp.opcode[6]; double *ptr_out = &_mp_arg(1) + (siz_out?1:0); const double *ptr_arg1 = siz_arg1==~0U?0:&_mp_arg(3) + (siz_arg1?1:0), *ptr_arg2 = siz_arg2==~0U?0:&_mp_arg(5) + 1; if (!ptr_arg2) { // No filename specified if (!siz_arg1) return cimg::date((unsigned int)*ptr_arg1); if (siz_arg1==~0U) for (unsigned int k = 0; k<siz_out; ++k) ptr_out[k] = k; else for (unsigned int k = 0; k<siz_out; ++k) ptr_out[k] = ptr_arg1[k]; cimg::date(ptr_out,siz_out); return cimg::type<double>::nan(); } // Filename specified. CImg<charT> ss(siz_arg2 + 1); cimg_forX(ss,i) ss[i] = (char)ptr_arg2[i]; ss.back() = 0; if (!siz_arg1) return cimg::fdate(ss,(unsigned int)*ptr_arg1); for (unsigned int k = 0; k<siz_out; ++k) ptr_out[k] = ptr_arg1[k]; cimg::fdate(ss,ptr_out,siz_out); return cimg::type<double>::nan(); } static double mp_debug(_cimg_math_parser& mp) { CImg<charT> expr(mp.opcode[2] - 4); { const ulongT *ptrs = mp.opcode._data + 4; cimg_for(expr,ptrd,char) *ptrd = (char)*(ptrs++); } cimg::strellipsize(expr); const ulongT g_target = mp.opcode[1]; #if cimg_use_openmp==0 const unsigned int n_thread = 0; #else const unsigned int n_thread = omp_get_thread_num(); #endif cimg_pragma_openmp(critical(mp_debug)) { std::fprintf(cimg::output(), "\n[" cimg_appname "_math_parser] %p[thread #%u]:%*c" "Start debugging expression '%s', code length %u -> mem[%u] (memsize: %u)", (void*)&mp,n_thread,mp.debug_indent,' ', expr._data,(unsigned int)mp.opcode[3],(unsigned int)g_target,mp.mem._width); std::fflush(cimg::output()); mp.debug_indent+=3; } const CImg<ulongT> *const p_end = (++mp.p_code) + mp.opcode[3]; CImg<ulongT> _op; for ( ; mp.p_code<p_end; ++mp.p_code) { const CImg<ulongT> &op = *mp.p_code; mp.opcode._data = op._data; _op.assign(1,op._height - 1); const ulongT *ptrs = op._data + 1; for (ulongT *ptrd = _op._data, *const ptrde = _op._data + _op._height; ptrd<ptrde; ++ptrd) *ptrd = *(ptrs++); const ulongT target = mp.opcode[1]; mp.mem[target] = _cimg_mp_defunc(mp); cimg_pragma_openmp(critical(mp_debug)) { std::fprintf(cimg::output(), "\n[" cimg_appname "_math_parser] %p[thread #%u]:%*c" "Opcode %p = [ %p,%s ] -> mem[%u] = %g", (void*)&mp,n_thread,mp.debug_indent,' ', (void*)mp.opcode._data,(void*)*mp.opcode,_op.value_string().data(), (unsigned int)target,mp.mem[target]); std::fflush(cimg::output()); } } cimg_pragma_openmp(critical(mp_debug)) { mp.debug_indent-=3; std::fprintf(cimg::output(), "\n[" cimg_appname "_math_parser] %p[thread #%u]:%*c" "End debugging expression '%s' -> mem[%u] = %g (memsize: %u)", (void*)&mp,n_thread,mp.debug_indent,' ', expr._data,(unsigned int)g_target,mp.mem[g_target],mp.mem._width); std::fflush(cimg::output()); } --mp.p_code; return mp.mem[g_target]; } static double mp_decrement(_cimg_math_parser& mp) { return _mp_arg(2) - 1; } static double mp_det(_cimg_math_parser& mp) { const double *ptrs = &_mp_arg(2) + 1; const unsigned int k = (unsigned int)mp.opcode[3]; return CImg<doubleT>(ptrs,k,k,1,1,true).det(); } static double mp_diag(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2], siz = mp.opcode[2] - 3; double *ptrd = &_mp_arg(1) + 1; std::memset(ptrd,0,siz*siz*sizeof(double)); for (unsigned int i = 3; i<i_end; ++i) { *(ptrd++) = _mp_arg(i); ptrd+=siz; } return cimg::type<double>::nan(); } static double mp_display_memory(_cimg_math_parser& mp) { cimg::unused(mp); std::fputc('\n',cimg::output()); mp.mem.display("[" cimg_appname "_math_parser] Memory snapshot"); return cimg::type<double>::nan(); } static double mp_display(_cimg_math_parser& mp) { const unsigned int _siz = (unsigned int)mp.opcode[3], siz = _siz?_siz:1; const double *const ptr = &_mp_arg(1) + (_siz?1:0); const int w = (int)_mp_arg(4), h = (int)_mp_arg(5), d = (int)_mp_arg(6), s = (int)_mp_arg(7); CImg<doubleT> img; if (w>0 && h>0 && d>0 && s>0) { if ((unsigned int)w*h*d*s<=siz) img.assign(ptr,w,h,d,s,true); else img.assign(ptr,siz).resize(w,h,d,s,-1); } else img.assign(ptr,1,siz,1,1,true); CImg<charT> expr(mp.opcode[2] - 8); const ulongT *ptrs = mp.opcode._data + 8; cimg_for(expr,ptrd,char) *ptrd = (char)*(ptrs++); ((CImg<charT>::string("[" cimg_appname "_math_parser] ",false,true),expr)>'x').move_to(expr); cimg::strellipsize(expr); std::fputc('\n',cimg::output()); img.display(expr._data); return cimg::type<double>::nan(); } static double mp_div(_cimg_math_parser& mp) { return _mp_arg(2)/_mp_arg(3); } static double mp_dot(_cimg_math_parser& mp) { const unsigned int siz = (unsigned int)mp.opcode[4]; return CImg<doubleT>(&_mp_arg(2) + 1,1,siz,1,1,true). dot(CImg<doubleT>(&_mp_arg(3) + 1,1,siz,1,1,true)); } static double mp_do(_cimg_math_parser& mp) { const ulongT mem_body = mp.opcode[1], mem_cond = mp.opcode[2]; const CImg<ulongT> *const p_body = ++mp.p_code, *const p_cond = p_body + mp.opcode[3], *const p_end = p_cond + mp.opcode[4]; const unsigned int vsiz = (unsigned int)mp.opcode[5]; if (mp.opcode[6]) { // Set default value for result and condition if necessary if (vsiz) CImg<doubleT>(&mp.mem[mem_body] + 1,vsiz,1,1,1,true).fill(cimg::type<double>::nan()); else mp.mem[mem_body] = cimg::type<double>::nan(); } if (mp.opcode[7]) mp.mem[mem_cond] = 0; const unsigned int _break_type = mp.break_type; mp.break_type = 0; do { for (mp.p_code = p_body; mp.p_code<p_cond; ++mp.p_code) { // Evaluate body mp.opcode._data = mp.p_code->_data; const ulongT target = mp.opcode[1]; mp.mem[target] = _cimg_mp_defunc(mp); } if (mp.break_type==1) break; else if (mp.break_type==2) mp.break_type = 0; for (mp.p_code = p_cond; mp.p_code<p_end; ++mp.p_code) { // Evaluate condition mp.opcode._data = mp.p_code->_data; const ulongT target = mp.opcode[1]; mp.mem[target] = _cimg_mp_defunc(mp); } if (mp.break_type==1) break; else if (mp.break_type==2) mp.break_type = 0; } while (mp.mem[mem_cond]); mp.break_type = _break_type; mp.p_code = p_end - 1; return mp.mem[mem_body]; } static double mp_draw(_cimg_math_parser& mp) { const int x = (int)_mp_arg(4), y = (int)_mp_arg(5), z = (int)_mp_arg(6), c = (int)_mp_arg(7); unsigned int ind = (unsigned int)mp.opcode[3]; if (ind!=~0U) ind = (unsigned int)cimg::mod((int)_mp_arg(3),mp.listin.width()); CImg<T> &img = ind==~0U?mp.imgout:mp.listout[ind]; unsigned int dx = (unsigned int)mp.opcode[8], dy = (unsigned int)mp.opcode[9], dz = (unsigned int)mp.opcode[10], dc = (unsigned int)mp.opcode[11]; dx = dx==~0U?img._width:(unsigned int)_mp_arg(8); dy = dy==~0U?img._height:(unsigned int)_mp_arg(9); dz = dz==~0U?img._depth:(unsigned int)_mp_arg(10); dc = dc==~0U?img._spectrum:(unsigned int)_mp_arg(11); const ulongT sizS = mp.opcode[2]; if (sizS<(ulongT)dx*dy*dz*dc) throw CImgArgumentException("[" cimg_appname "_math_parser] CImg<%s>: Function 'draw()': " "Sprite dimension (%lu values) and specified sprite geometry (%u,%u,%u,%u) " "(%lu values) do not match.", mp.imgin.pixel_type(),sizS,dx,dy,dz,dc,(ulongT)dx*dy*dz*dc); CImg<doubleT> S(&_mp_arg(1) + 1,dx,dy,dz,dc,true); const float opacity = (float)_mp_arg(12); if (img._data) { if (mp.opcode[13]!=~0U) { // Opacity mask specified const ulongT sizM = mp.opcode[14]; if (sizM<(ulongT)dx*dy*dz) throw CImgArgumentException("[" cimg_appname "_math_parser] CImg<%s>: Function 'draw()': " "Mask dimension (%lu values) and specified sprite geometry (%u,%u,%u,%u) " "(%lu values) do not match.", mp.imgin.pixel_type(),sizS,dx,dy,dz,dc,(ulongT)dx*dy*dz*dc); const CImg<doubleT> M(&_mp_arg(13) + 1,dx,dy,dz,(unsigned int)(sizM/(dx*dy*dz)),true); img.draw_image(x,y,z,c,S,M,opacity,(float)_mp_arg(15)); } else img.draw_image(x,y,z,c,S,opacity); } return cimg::type<double>::nan(); } static double mp_echo(_cimg_math_parser& mp) { const unsigned int nb_args = (unsigned int)(mp.opcode[2] - 3)/2; CImgList<charT> _str; CImg<charT> it; for (unsigned int n = 0; n<nb_args; ++n) { const unsigned int siz = (unsigned int)mp.opcode[4 + 2*n]; if (siz) { // Vector argument -> string const double *ptr = &_mp_arg(3 + 2*n) + 1; unsigned int l = 0; while (l<siz && ptr[l]) ++l; CImg<doubleT>(ptr,l,1,1,1,true).move_to(_str); } else { // Scalar argument -> number it.assign(256); cimg_snprintf(it,it._width,"%.17g",_mp_arg(3 + 2*n)); CImg<charT>::string(it,false,true).move_to(_str); } } CImg(1,1,1,1,0).move_to(_str); const CImg<charT> str = _str>'x'; std::fprintf(cimg::output(),"\n%s",str._data); return cimg::type<double>::nan(); } static double mp_ellipse(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; unsigned int ind = (unsigned int)mp.opcode[3]; if (ind!=~0U) ind = (unsigned int)cimg::mod((int)_mp_arg(3),mp.listin.width()); CImg<T> &img = ind==~0U?mp.imgout:mp.listout[ind]; CImg<T> color(img._spectrum,1,1,1,0); bool is_invalid_arguments = false, is_outlined = false; float r1 = 0, r2 = 0, angle = 0, opacity = 1; unsigned int i = 4, pattern = ~0U; int x0 = 0, y0 = 0; if (i>=i_end) is_invalid_arguments = true; else { x0 = (int)cimg::round(_mp_arg(i++)); if (i>=i_end) is_invalid_arguments = true; else { y0 = (int)cimg::round(_mp_arg(i++)); if (i>=i_end) is_invalid_arguments = true; else { r1 = (float)_mp_arg(i++); if (i>=i_end) r2 = r1; else { r2 = (float)_mp_arg(i++); if (i<i_end) { angle = (float)_mp_arg(i++); if (i<i_end) { opacity = (float)_mp_arg(i++); if (r1<0 && r2<0) { pattern = (unsigned int)_mp_arg(i++); is_outlined = true; r1 = -r1; r2 = -r2; } if (i<i_end) { cimg_forX(color,k) if (i<i_end) color[k] = (T)_mp_arg(i++); else { color.resize(k,1,1,1,-1); break; } color.resize(img._spectrum,1,1,1,0,2); } } } } } } } if (!is_invalid_arguments) { if (is_outlined) img.draw_ellipse(x0,y0,r1,r2,angle,color._data,opacity,pattern); else img.draw_ellipse(x0,y0,r1,r2,angle,color._data,opacity); } else { CImg<doubleT> args(i_end - 4); cimg_forX(args,k) args[k] = _mp_arg(4 + k); if (ind==~0U) throw CImgArgumentException("[" cimg_appname "_math_parser] CImg<%s>: Function 'ellipse()': " "Invalid arguments '%s'. ", mp.imgin.pixel_type(),args.value_string()._data); else throw CImgArgumentException("[" cimg_appname "_math_parser] CImg<%s>: Function 'ellipse()': " "Invalid arguments '#%u%s%s'. ", mp.imgin.pixel_type(),ind,args._width?",":"",args.value_string()._data); } return cimg::type<double>::nan(); } static double mp_eq(_cimg_math_parser& mp) { return (double)(_mp_arg(2)==_mp_arg(3)); } static double mp_ext(_cimg_math_parser& mp) { const unsigned int nb_args = (unsigned int)(mp.opcode[2] - 3)/2; CImgList<charT> _str; CImg<charT> it; for (unsigned int n = 0; n<nb_args; ++n) { const unsigned int siz = (unsigned int)mp.opcode[4 + 2*n]; if (siz) { // Vector argument -> string const double *ptr = &_mp_arg(3 + 2*n) + 1; unsigned int l = 0; while (l<siz && ptr[l]) ++l; CImg<doubleT>(ptr,l,1,1,1,true).move_to(_str); } else { // Scalar argument -> number it.assign(256); cimg_snprintf(it,it._width,"%.17g",_mp_arg(3 + 2*n)); CImg<charT>::string(it,false,true).move_to(_str); } } CImg(1,1,1,1,0).move_to(_str); CImg<charT> str = _str>'x'; #ifdef cimg_mp_ext_function cimg_mp_ext_function(str); #endif return cimg::type<double>::nan(); } static double mp_exp(_cimg_math_parser& mp) { return std::exp(_mp_arg(2)); } static double mp_eye(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const unsigned int k = (unsigned int)mp.opcode[2]; CImg<doubleT>(ptrd,k,k,1,1,true).identity_matrix(); return cimg::type<double>::nan(); } static double mp_factorial(_cimg_math_parser& mp) { return cimg::factorial((int)_mp_arg(2)); } static double mp_fibonacci(_cimg_math_parser& mp) { return cimg::fibonacci((int)_mp_arg(2)); } static double mp_find(_cimg_math_parser& mp) { const bool is_forward = (bool)_mp_arg(5); const ulongT siz = (ulongT)mp.opcode[3]; longT ind = (longT)(mp.opcode[6]!=_cimg_mp_slot_nan?_mp_arg(6):is_forward?0:siz - 1); if (ind<0 || ind>=(longT)siz) return -1.; const double *const ptrb = &_mp_arg(2) + 1, *const ptre = ptrb + siz, val = _mp_arg(4), *ptr = ptrb + ind; // Forward search if (is_forward) { while (ptr<ptre && *ptr!=val) ++ptr; return ptr==ptre?-1.:(double)(ptr - ptrb); } // Backward search. while (ptr>=ptrb && *ptr!=val) --ptr; return ptr<ptrb?-1.:(double)(ptr - ptrb); } static double mp_find_seq(_cimg_math_parser& mp) { const bool is_forward = (bool)_mp_arg(6); const ulongT siz1 = (ulongT)mp.opcode[3], siz2 = (ulongT)mp.opcode[5]; longT ind = (longT)(mp.opcode[7]!=_cimg_mp_slot_nan?_mp_arg(7):is_forward?0:siz1 - 1); if (ind<0 || ind>=(longT)siz1) return -1.; const double *const ptr1b = &_mp_arg(2) + 1, *const ptr1e = ptr1b + siz1, *const ptr2b = &_mp_arg(4) + 1, *const ptr2e = ptr2b + siz2, *ptr1 = ptr1b + ind, *p1 = 0, *p2 = 0; // Forward search. if (is_forward) { do { while (ptr1<ptr1e && *ptr1!=*ptr2b) ++ptr1; if (ptr1>=ptr1e) return -1.; p1 = ptr1 + 1; p2 = ptr2b + 1; while (p1<ptr1e && p2<ptr2e && *p1==*p2) { ++p1; ++p2; } } while (p2<ptr2e && ++ptr1<ptr1e); return p2<ptr2e?-1.:(double)(ptr1 - ptr1b); } // Backward search. do { while (ptr1>=ptr1b && *ptr1!=*ptr2b) --ptr1; if (ptr1<ptr1b) return -1.; p1 = ptr1 + 1; p2 = ptr2b + 1; while (p1<ptr1e && p2<ptr2e && *p1==*p2) { ++p1; ++p2; } } while (p2<ptr2e && --ptr1>=ptr1b); return p2<ptr2e?-1.:(double)(ptr1 - ptr1b); } static double mp_floor(_cimg_math_parser& mp) { return std::floor(_mp_arg(2)); } static double mp_for(_cimg_math_parser& mp) { const ulongT mem_body = mp.opcode[1], mem_cond = mp.opcode[3]; const CImg<ulongT> *const p_init = ++mp.p_code, *const p_cond = p_init + mp.opcode[4], *const p_body = p_cond + mp.opcode[5], *const p_post = p_body + mp.opcode[6], *const p_end = p_post + mp.opcode[7]; const unsigned int vsiz = (unsigned int)mp.opcode[2]; bool is_cond = false; if (mp.opcode[8]) { // Set default value for result and condition if necessary if (vsiz) CImg<doubleT>(&mp.mem[mem_body] + 1,vsiz,1,1,1,true).fill(cimg::type<double>::nan()); else mp.mem[mem_body] = cimg::type<double>::nan(); } if (mp.opcode[9]) mp.mem[mem_cond] = 0; const unsigned int _break_type = mp.break_type; mp.break_type = 0; for (mp.p_code = p_init; mp.p_code<p_cond; ++mp.p_code) { // Evaluate init mp.opcode._data = mp.p_code->_data; const ulongT target = mp.opcode[1]; mp.mem[target] = _cimg_mp_defunc(mp); } if (!mp.break_type) do { for (mp.p_code = p_cond; mp.p_code<p_body; ++mp.p_code) { // Evaluate condition mp.opcode._data = mp.p_code->_data; const ulongT target = mp.opcode[1]; mp.mem[target] = _cimg_mp_defunc(mp); } if (mp.break_type==1) break; is_cond = (bool)mp.mem[mem_cond]; if (is_cond && !mp.break_type) { for (mp.p_code = p_body; mp.p_code<p_post; ++mp.p_code) { // Evaluate body mp.opcode._data = mp.p_code->_data; const ulongT target = mp.opcode[1]; mp.mem[target] = _cimg_mp_defunc(mp); } if (mp.break_type==1) break; else if (mp.break_type==2) mp.break_type = 0; for (mp.p_code = p_post; mp.p_code<p_end; ++mp.p_code) { // Evaluate post-code mp.opcode._data = mp.p_code->_data; const ulongT target = mp.opcode[1]; mp.mem[target] = _cimg_mp_defunc(mp); } if (mp.break_type==1) break; else if (mp.break_type==2) mp.break_type = 0; } } while (is_cond); mp.break_type = _break_type; mp.p_code = p_end - 1; return mp.mem[mem_body]; } static double mp_fsize(_cimg_math_parser& mp) { const double *ptrs = &_mp_arg(2) + 1; const ulongT siz = (ulongT)mp.opcode[3]; CImg<charT> ss(siz + 1); cimg_forX(ss,i) ss[i] = (char)ptrs[i]; ss.back() = 0; return (double)cimg::fsize(ss); } static double mp_g(_cimg_math_parser& mp) { cimg::unused(mp); return cimg::grand(&mp.rng); } static double mp_gauss(_cimg_math_parser& mp) { const double x = _mp_arg(2), s = _mp_arg(3); return std::exp(-x*x/(2*s*s))/(_mp_arg(4)?std::sqrt(2*s*s*cimg::PI):1); } static double mp_gcd(_cimg_math_parser& mp) { return cimg::gcd((long)_mp_arg(2),(long)_mp_arg(3)); } static double mp_gt(_cimg_math_parser& mp) { return (double)(_mp_arg(2)>_mp_arg(3)); } static double mp_gte(_cimg_math_parser& mp) { return (double)(_mp_arg(2)>=_mp_arg(3)); } static double mp_i(_cimg_math_parser& mp) { return (double)mp.imgin.atXYZC((int)mp.mem[_cimg_mp_slot_x],(int)mp.mem[_cimg_mp_slot_y], (int)mp.mem[_cimg_mp_slot_z],(int)mp.mem[_cimg_mp_slot_c],(T)0); } static double mp_if(_cimg_math_parser& mp) { const bool is_cond = (bool)_mp_arg(2); const ulongT mem_left = mp.opcode[3], mem_right = mp.opcode[4]; const CImg<ulongT> *const p_right = ++mp.p_code + mp.opcode[5], *const p_end = p_right + mp.opcode[6]; const unsigned int vtarget = (unsigned int)mp.opcode[1], vsiz = (unsigned int)mp.opcode[7]; if (is_cond) for ( ; mp.p_code<p_right; ++mp.p_code) { mp.opcode._data = mp.p_code->_data; const ulongT target = mp.opcode[1]; mp.mem[target] = _cimg_mp_defunc(mp); } else for (mp.p_code = p_right; mp.p_code<p_end; ++mp.p_code) { mp.opcode._data = mp.p_code->_data; const ulongT target = mp.opcode[1]; mp.mem[target] = _cimg_mp_defunc(mp); } if (mp.p_code==mp.p_break) --mp.p_code; else mp.p_code = p_end - 1; if (vsiz) std::memcpy(&mp.mem[vtarget] + 1,&mp.mem[is_cond?mem_left:mem_right] + 1,sizeof(double)*vsiz); return mp.mem[is_cond?mem_left:mem_right]; } static double mp_image_d(_cimg_math_parser& mp) { unsigned int ind = (unsigned int)mp.opcode[2]; if (ind!=~0U) ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); const CImg<T> &img = ind==~0U?mp.imgout:mp.listout[ind]; return (double)img.depth(); } static double mp_image_display(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listout.width()); cimg::mutex(6); CImg<T> &img = mp.listout[ind]; CImg<charT> title(256); std::fputc('\n',cimg::output()); cimg_snprintf(title,title._width,"[ Image #%u ]",ind); img.display(title); cimg::mutex(6,0); return cimg::type<double>::nan(); } static double mp_image_h(_cimg_math_parser& mp) { unsigned int ind = (unsigned int)mp.opcode[2]; if (ind!=~0U) ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); const CImg<T> &img = ind==~0U?mp.imgout:mp.listout[ind]; return (double)img.height(); } static double mp_image_median(_cimg_math_parser& mp) { unsigned int ind = (unsigned int)mp.opcode[2]; if (ind!=~0U) ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); const CImg<T> &img = ind==~0U?mp.imgout:mp.listout[ind]; return (double)img.median(); } static double mp_image_print(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listout.width()); cimg::mutex(6); CImg<T> &img = mp.listout[ind]; CImg<charT> title(256); std::fputc('\n',cimg::output()); cimg_snprintf(title,title._width,"[ Image #%u ]",ind); img.print(title); cimg::mutex(6,0); return cimg::type<double>::nan(); } static double mp_image_resize(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listout.width()); cimg::mutex(6); CImg<T> &img = mp.listout[ind]; const double _w = mp.opcode[3]==~0U?-100:_mp_arg(3), _h = mp.opcode[4]==~0U?-100:_mp_arg(4), _d = mp.opcode[5]==~0U?-100:_mp_arg(5), _s = mp.opcode[6]==~0U?-100:_mp_arg(6); const unsigned int w = (unsigned int)(_w>=0?_w:-_w*img.width()/100), h = (unsigned int)(_h>=0?_h:-_h*img.height()/100), d = (unsigned int)(_d>=0?_d:-_d*img.depth()/100), s = (unsigned int)(_s>=0?_s:-_s*img.spectrum()/100), interp = (int)_mp_arg(7); if (mp.is_fill && img._data==mp.imgout._data) { cimg::mutex(6,0); throw CImgArgumentException("[" cimg_appname "_math_parser] CImg<%s>: Function 'resize()': " "Cannot both fill and resize image (%u,%u,%u,%u) " "to new dimensions (%u,%u,%u,%u).", img.pixel_type(),img._width,img._height,img._depth,img._spectrum,w,h,d,s); } const unsigned int boundary = (int)_mp_arg(8); const float cx = (float)_mp_arg(9), cy = (float)_mp_arg(10), cz = (float)_mp_arg(11), cc = (float)_mp_arg(12); img.resize(w,h,d,s,interp,boundary,cx,cy,cz,cc); cimg::mutex(6,0); return cimg::type<double>::nan(); } static double mp_image_s(_cimg_math_parser& mp) { unsigned int ind = (unsigned int)mp.opcode[2]; if (ind!=~0U) ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); const CImg<T> &img = ind==~0U?mp.imgout:mp.listout[ind]; return (double)img.spectrum(); } static double mp_image_sort(_cimg_math_parser& mp) { const bool is_increasing = (bool)_mp_arg(3); const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listout.width()), axis = (unsigned int)_mp_arg(4); cimg::mutex(6); CImg<T> &img = mp.listout[ind]; img.sort(is_increasing, axis==0 || axis=='x'?'x': axis==1 || axis=='y'?'y': axis==2 || axis=='z'?'z': axis==3 || axis=='c'?'c':0); cimg::mutex(6,0); return cimg::type<double>::nan(); } static double mp_image_stats(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; unsigned int ind = (unsigned int)mp.opcode[2]; if (ind==~0U) CImg<doubleT>(ptrd,14,1,1,1,true) = mp.imgout.get_stats(); else { ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); CImg<doubleT>(ptrd,14,1,1,1,true) = mp.listout[ind].get_stats(); } return cimg::type<double>::nan(); } static double mp_image_w(_cimg_math_parser& mp) { unsigned int ind = (unsigned int)mp.opcode[2]; if (ind!=~0U) ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); const CImg<T> &img = ind==~0U?mp.imgout:mp.listout[ind]; return (double)img.width(); } static double mp_image_wh(_cimg_math_parser& mp) { unsigned int ind = (unsigned int)mp.opcode[2]; if (ind!=~0U) ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); const CImg<T> &img = ind==~0U?mp.imgout:mp.listout[ind]; return (double)img.width()*img.height(); } static double mp_image_whd(_cimg_math_parser& mp) { unsigned int ind = (unsigned int)mp.opcode[2]; if (ind!=~0U) ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); const CImg<T> &img = ind==~0U?mp.imgout:mp.listout[ind]; return (double)img.width()*img.height()*img.depth(); } static double mp_image_whds(_cimg_math_parser& mp) { unsigned int ind = (unsigned int)mp.opcode[2]; if (ind!=~0U) ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); const CImg<T> &img = ind==~0U?mp.imgout:mp.listout[ind]; return (double)img.width()*img.height()*img.depth()*img.spectrum(); } static double mp_increment(_cimg_math_parser& mp) { return _mp_arg(2) + 1; } static double mp_int(_cimg_math_parser& mp) { return (double)(longT)_mp_arg(2); } static double mp_ioff(_cimg_math_parser& mp) { const unsigned int boundary_conditions = (unsigned int)_mp_arg(3); const CImg<T> &img = mp.imgin; const longT off = (longT)_mp_arg(2), whds = (longT)img.size(); if (off>=0 && off<whds) return (double)img[off]; if (img._data) switch (boundary_conditions) { case 3 : { // Mirror const longT whds2 = 2*whds, moff = cimg::mod(off,whds2); return (double)img[moff<whds?moff:whds2 - moff - 1]; } case 2 : // Periodic return (double)img[cimg::mod(off,whds)]; case 1 : // Neumann return (double)img[off<0?0:whds - 1]; default : // Dirichlet return 0; } return 0; } static double mp_isbool(_cimg_math_parser& mp) { const double val = _mp_arg(2); return (double)(val==0. || val==1.); } static double mp_isdir(_cimg_math_parser& mp) { const double *ptrs = &_mp_arg(2) + 1; const ulongT siz = (ulongT)mp.opcode[3]; CImg<charT> ss(siz + 1); cimg_forX(ss,i) ss[i] = (char)ptrs[i]; ss.back() = 0; return (double)cimg::is_directory(ss); } static double mp_isin(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; const double val = _mp_arg(3); for (unsigned int i = 4; i<i_end; ++i) if (val==_mp_arg(i)) return 1.; return 0.; } static double mp_isinf(_cimg_math_parser& mp) { return (double)cimg::type<double>::is_inf(_mp_arg(2)); } static double mp_isint(_cimg_math_parser& mp) { return (double)(cimg::mod(_mp_arg(2),1.)==0); } static double mp_isfile(_cimg_math_parser& mp) { const double *ptrs = &_mp_arg(2) + 1; const ulongT siz = (ulongT)mp.opcode[3]; CImg<charT> ss(siz + 1); cimg_forX(ss,i) ss[i] = (char)ptrs[i]; ss.back() = 0; return (double)cimg::is_file(ss); } static double mp_isnan(_cimg_math_parser& mp) { return (double)cimg::type<double>::is_nan(_mp_arg(2)); } static double mp_ixyzc(_cimg_math_parser& mp) { const unsigned int interpolation = (unsigned int)_mp_arg(6), boundary_conditions = (unsigned int)_mp_arg(7); const CImg<T> &img = mp.imgin; const double x = _mp_arg(2), y = _mp_arg(3), z = _mp_arg(4), c = _mp_arg(5); switch (interpolation) { case 2 : // Cubic interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), s2 = 2.f*img.spectrum(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), mc = cimg::mod((float)c,s2); return (double)img._cubic_atXYZ(mx<img.width()?mx:w2 - mx - 1, my<img.height()?my:h2 - my - 1, mz<img.depth()?mz:d2 - mz - 1, (int)(mc<img.spectrum()?mc:s2 - mc - 1)); } case 2 : // Periodic return (double)img._cubic_atXYZ_p((float)x,(float)y,(float)z, (int)cimg::mod(c,(double)img._spectrum)); case 1 : // Neumann return (double)img._cubic_atXYZ((float)x,(float)y,(float)z, (int)(c<0?0:c>=img._spectrum?img._spectrum - 1:c)); default : // Dirichlet if (c<0 || c>=img._spectrum) return (T)0; return (double)img.cubic_atXYZ((float)x,(float)y,(float)z,(int)c,(T)0); } case 1 : // Linear interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), s2 = 2.f*img.spectrum(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), mc = cimg::mod((float)c,s2); return (double)img._linear_atXYZ(mx<img.width()?mx:w2 - mx - 1, my<img.height()?my:h2 - my - 1, mz<img.depth()?mz:d2 - mz - 1, (int)(mc<img.spectrum()?mc:s2 - mc - 1)); } case 2 : // Periodic return (double)img._linear_atXYZ_p((float)x,(float)y,(float)z, (int)cimg::mod(c,(double)img._spectrum)); case 1 : // Neumann return (double)img._linear_atXYZ((float)x,(float)y,(float)z, (int)(c<0?0:c>=img._spectrum?img._spectrum - 1:c)); default : // Dirichlet if (c<0 || c>=img._spectrum) return (T)0; return (double)img.linear_atXYZ((float)x,(float)y,(float)z,(int)c,(T)0); } default : // Nearest neighbor interpolation switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*img.width(), h2 = 2*img.height(), d2 = 2*img.depth(), s2 = 2*img.spectrum(), mx = cimg::mod((int)x,w2), my = cimg::mod((int)y,h2), mz = cimg::mod((int)z,d2), mc = cimg::mod((int)c,s2); return (double)img(mx<img.width()?mx:w2 - mx - 1, my<img.height()?my:h2 - my - 1, mz<img.depth()?mz:d2 - mz - 1, mc<img.spectrum()?mc:s2 - mc - 1); } case 2 : // Periodic return (double)img((int)cimg::mod(x,(double)img._width), (int)cimg::mod(y,(double)img._height), (int)cimg::mod(z,(double)img._depth), (int)cimg::mod(c,(double)img._spectrum)); case 1 : // Neumann return (double)img._atXYZC((int)x,(int)y,(int)z,(int)c); default : // Dirichlet return (double)img.atXYZC((int)x,(int)y,(int)z,(int)c,(T)0); } } } static double mp_joff(_cimg_math_parser& mp) { const unsigned int boundary_conditions = (unsigned int)_mp_arg(3); const int ox = (int)mp.mem[_cimg_mp_slot_x], oy = (int)mp.mem[_cimg_mp_slot_y], oz = (int)mp.mem[_cimg_mp_slot_z], oc = (int)mp.mem[_cimg_mp_slot_c]; const CImg<T> &img = mp.imgin; const longT off = img.offset(ox,oy,oz,oc) + (longT)_mp_arg(2), whds = (longT)img.size(); if (off>=0 && off<whds) return (double)img[off]; if (img._data) switch (boundary_conditions) { case 3 : { // Mirror const longT whds2 = 2*whds, moff = cimg::mod(off,whds2); return (double)img[moff<whds?moff:whds2 - moff - 1]; } case 2 : // Periodic return (double)img[cimg::mod(off,whds)]; case 1 : // Neumann return (double)img[off<0?0:whds - 1]; default : // Dirichlet return 0; } return 0; } static double mp_jxyzc(_cimg_math_parser& mp) { const unsigned int interpolation = (unsigned int)_mp_arg(6), boundary_conditions = (unsigned int)_mp_arg(7); const CImg<T> &img = mp.imgin; const double ox = mp.mem[_cimg_mp_slot_x], oy = mp.mem[_cimg_mp_slot_y], oz = mp.mem[_cimg_mp_slot_z], oc = mp.mem[_cimg_mp_slot_c], x = ox + _mp_arg(2), y = oy + _mp_arg(3), z = oz + _mp_arg(4), c = oc + _mp_arg(5); switch (interpolation) { case 2 : // Cubic interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), s2 = 2.f*img.spectrum(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), mc = cimg::mod((float)c,s2); return (double)img._cubic_atXYZ(mx<img.width()?mx:w2 - mx - 1, my<img.height()?my:h2 - my - 1, mz<img.depth()?mz:d2 - mz - 1, (int)(mc<img.spectrum()?mc:s2 - mc - 1)); } case 2 : // Periodic return (double)img._cubic_atXYZ_p((float)x,(float)y,(float)z, (int)cimg::mod(c,(double)img._spectrum)); case 1 : // Neumann return (double)img._cubic_atXYZ((float)x,(float)y,(float)z, (int)(c<0?0:c>=img._spectrum?img._spectrum - 1:c)); default : // Dirichlet if (c<0 || c>=img._spectrum) return (T)0; return (double)img.cubic_atXYZ((float)x,(float)y,(float)z,(int)c,(T)0); } case 1 : // Linear interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), s2 = 2.f*img.spectrum(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), mc = cimg::mod((float)c,s2); return (double)img._linear_atXYZ(mx<img.width()?mx:w2 - mx - 1, my<img.height()?my:h2 - my - 1, mz<img.depth()?mz:d2 - mz - 1, (int)(mc<img.spectrum()?mc:s2 - mc - 1)); } case 2 : // Periodic return (double)img._linear_atXYZ_p((float)x,(float)y,(float)z, (int)cimg::mod(c,(double)img._spectrum)); case 1 : // Neumann return (double)img._linear_atXYZ((float)x,(float)y,(float)z, (int)(c<0?0:c>=img._spectrum?img._spectrum - 1:c)); default : // Dirichlet if (c<0 || c>=img._spectrum) return (T)0; return (double)img.linear_atXYZ((float)x,(float)y,(float)z,(int)c,(T)0); } default : // Nearest neighbor interpolation switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*img.width(), h2 = 2*img.height(), d2 = 2*img.depth(), s2 = 2*img.spectrum(), mx = cimg::mod((int)x,w2), my = cimg::mod((int)y,h2), mz = cimg::mod((int)z,d2), mc = cimg::mod((int)c,s2); return (double)img(mx<img.width()?mx:w2 - mx - 1, my<img.height()?my:h2 - my - 1, mz<img.depth()?mz:d2 - mz - 1, mc<img.spectrum()?mc:s2 - mc - 1); } case 2 : // Periodic return (double)img((int)cimg::mod(x,(double)img._width), (int)cimg::mod(y,(double)img._height), (int)cimg::mod(z,(double)img._depth), (int)cimg::mod(c,(double)img._spectrum)); case 1 : // Neumann return (double)img._atXYZC((int)x,(int)y,(int)z,(int)c); default : // Dirichlet return (double)img.atXYZC((int)x,(int)y,(int)z,(int)c,(T)0); } } } static double mp_kth(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; CImg<doubleT> vals(i_end - 4); double *p = vals.data(); for (unsigned int i = 4; i<i_end; ++i) *(p++) = _mp_arg(i); int ind = (int)cimg::round(_mp_arg(3)); if (ind<0) ind+=vals.width() + 1; ind = std::max(1,std::min(vals.width(),ind)); return vals.kth_smallest(ind - 1); } static double mp_linear_add(_cimg_math_parser& mp) { return _mp_arg(2)*_mp_arg(3) + _mp_arg(4); } static double mp_linear_sub_left(_cimg_math_parser& mp) { return _mp_arg(2)*_mp_arg(3) - _mp_arg(4); } static double mp_linear_sub_right(_cimg_math_parser& mp) { return _mp_arg(4) - _mp_arg(2)*_mp_arg(3); } static double mp_list_depth(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); return (double)mp.listin[ind]._depth; } static double mp_list_find(_cimg_math_parser& mp) { const unsigned int indi = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); const CImg<T> &img = mp.listin[indi]; const bool is_forward = (bool)_mp_arg(4); const ulongT siz = (ulongT)img.size(); longT ind = (longT)(mp.opcode[5]!=_cimg_mp_slot_nan?_mp_arg(5):is_forward?0:siz - 1); if (ind<0 || ind>=(longT)siz) return -1.; const T *const ptrb = img.data(), *const ptre = img.end(), *ptr = ptrb + ind; const double val = _mp_arg(3); // Forward search if (is_forward) { while (ptr<ptre && (double)*ptr!=val) ++ptr; return ptr==ptre?-1.:(double)(ptr - ptrb); } // Backward search. while (ptr>=ptrb && (double)*ptr!=val) --ptr; return ptr<ptrb?-1.:(double)(ptr - ptrb); } static double mp_list_find_seq(_cimg_math_parser& mp) { const unsigned int indi = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); const CImg<T> &img = mp.listin[indi]; const bool is_forward = (bool)_mp_arg(5); const ulongT siz1 = (ulongT)img.size(), siz2 = (ulongT)mp.opcode[4]; longT ind = (longT)(mp.opcode[6]!=_cimg_mp_slot_nan?_mp_arg(6):is_forward?0:siz1 - 1); if (ind<0 || ind>=(longT)siz1) return -1.; const T *const ptr1b = img.data(), *const ptr1e = ptr1b + siz1, *ptr1 = ptr1b + ind, *p1 = 0; const double *const ptr2b = &_mp_arg(3) + 1, *const ptr2e = ptr2b + siz2, *p2 = 0; // Forward search. if (is_forward) { do { while (ptr1<ptr1e && *ptr1!=*ptr2b) ++ptr1; if (ptr1>=ptr1e) return -1.; p1 = ptr1 + 1; p2 = ptr2b + 1; while (p1<ptr1e && p2<ptr2e && *p1==*p2) { ++p1; ++p2; } } while (p2<ptr2e && ++ptr1<ptr1e); return p2<ptr2e?-1.:(double)(ptr1 - ptr1b); } // Backward search. do { while (ptr1>=ptr1b && *ptr1!=*ptr2b) --ptr1; if (ptr1<ptr1b) return -1.; p1 = ptr1 + 1; p2 = ptr2b + 1; while (p1<ptr1e && p2<ptr2e && *p1==*p2) { ++p1; ++p2; } } while (p2<ptr2e && --ptr1>=ptr1b); return p2<ptr2e?-1.:(double)(ptr1 - ptr1b); } static double mp_list_height(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); return (double)mp.listin[ind]._height; } static double mp_list_ioff(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()), boundary_conditions = (unsigned int)_mp_arg(4); const CImg<T> &img = mp.listin[ind]; const longT off = (longT)_mp_arg(3), whds = (longT)img.size(); if (off>=0 && off<whds) return (double)img[off]; if (img._data) switch (boundary_conditions) { case 3 : { // Mirror const longT whds2 = 2*whds, moff = cimg::mod(off,whds2); return (double)img[moff<whds?moff:whds2 - moff - 1]; } case 2 : // Periodic return (double)img[cimg::mod(off,whds)]; case 1 : // Neumann return (double)img[off<0?0:whds - 1]; default : // Dirichlet return 0; } return 0; } static double mp_list_is_shared(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); return (double)mp.listin[ind]._is_shared; } static double mp_list_ixyzc(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()), interpolation = (unsigned int)_mp_arg(7), boundary_conditions = (unsigned int)_mp_arg(8); const CImg<T> &img = mp.listin[ind]; const double x = _mp_arg(3), y = _mp_arg(4), z = _mp_arg(5), c = _mp_arg(6); switch (interpolation) { case 2 : // Cubic interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), s2 = 2.f*img.spectrum(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), mc = cimg::mod((float)c,s2); return (double)img._cubic_atXYZ(mx<img.width()?mx:w2 - mx - 1, my<img.height()?my:h2 - my - 1, mz<img.depth()?mz:d2 - mz - 1, (int)(mc<img.spectrum()?mc:s2 - mc - 1)); } case 2 : // Periodic return (double)img._cubic_atXYZ_p((float)x,(float)y,(float)z, (int)cimg::mod(c,(double)img._spectrum)); case 1 : // Neumann return (double)img._cubic_atXYZ((float)x,(float)y,(float)z, (int)(c<0?0:c>=img._spectrum?img._spectrum - 1:c)); default : // Dirichlet if (c<0 || c>=img._spectrum) return (T)0; return (double)img.cubic_atXYZ((float)x,(float)y,(float)z,(int)c,(T)0); } case 1 : // Linear interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), s2 = 2.f*img.spectrum(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), mc = cimg::mod((float)c,s2); return (double)img._linear_atXYZ(mx<img.width()?mx:w2 - mx - 1, my<img.height()?my:h2 - my - 1, mz<img.depth()?mz:d2 - mz - 1, (int)(mc<img.spectrum()?mc:s2 - mc - 1)); } case 2 : // Periodic return (double)img._linear_atXYZ_p((float)x,(float)y,(float)z, (int)cimg::mod(c,(double)img._spectrum)); case 1 : // Neumann return (double)img._linear_atXYZ((float)x,(float)y,(float)z, (int)(c<0?0:c>=img._spectrum?img._spectrum - 1:c)); default : // Dirichlet if (c<0 || c>=img._spectrum) return (T)0; return (double)img.linear_atXYZ((float)x,(float)y,(float)z,(int)c,(T)0); } default : // Nearest neighbor interpolation switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*img.width(), h2 = 2*img.height(), d2 = 2*img.depth(), s2 = 2*img.spectrum(), mx = cimg::mod((int)x,w2), my = cimg::mod((int)y,h2), mz = cimg::mod((int)z,d2), mc = cimg::mod((int)c,s2); return (double)img(mx<img.width()?mx:w2 - mx - 1, my<img.height()?my:h2 - my - 1, mz<img.depth()?mz:d2 - mz - 1, mc<img.spectrum()?mc:s2 - mc - 1); } case 2 : // Periodic return (double)img((int)cimg::mod(x,(double)img._width), (int)cimg::mod(y,(double)img._height), (int)cimg::mod(z,(double)img._depth), (int)cimg::mod(c,(double)img._spectrum)); case 1 : // Neumann return (double)img._atXYZC((int)x,(int)y,(int)z,(int)c); default : // Dirichlet return (double)img.atXYZC((int)x,(int)y,(int)z,(int)c,(T)0); } } } static double mp_list_joff(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()), boundary_conditions = (unsigned int)_mp_arg(4); const int ox = (int)mp.mem[_cimg_mp_slot_x], oy = (int)mp.mem[_cimg_mp_slot_y], oz = (int)mp.mem[_cimg_mp_slot_z], oc = (int)mp.mem[_cimg_mp_slot_c]; const CImg<T> &img = mp.listin[ind]; const longT off = img.offset(ox,oy,oz,oc) + (longT)_mp_arg(3), whds = (longT)img.size(); if (off>=0 && off<whds) return (double)img[off]; if (img._data) switch (boundary_conditions) { case 3 : { // Mirror const longT whds2 = 2*whds, moff = cimg::mod(off,whds2); return (double)img[moff<whds?moff:whds2 - moff - 1]; } case 2 : // Periodic return (double)img[cimg::mod(off,whds)]; case 1 : // Neumann return (double)img[off<0?0:whds - 1]; default : // Dirichlet return 0; } return 0; } static double mp_list_jxyzc(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()), interpolation = (unsigned int)_mp_arg(7), boundary_conditions = (unsigned int)_mp_arg(8); const CImg<T> &img = mp.listin[ind]; const double ox = mp.mem[_cimg_mp_slot_x], oy = mp.mem[_cimg_mp_slot_y], oz = mp.mem[_cimg_mp_slot_z], oc = mp.mem[_cimg_mp_slot_c], x = ox + _mp_arg(3), y = oy + _mp_arg(4), z = oz + _mp_arg(5), c = oc + _mp_arg(6); switch (interpolation) { case 2 : // Cubic interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), s2 = 2.f*img.spectrum(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), mc = cimg::mod((float)c,s2); return (double)img._cubic_atXYZ(mx<img.width()?mx:w2 - mx - 1, my<img.height()?my:h2 - my - 1, mz<img.depth()?mz:d2 - mz - 1, (int)(mc<img.spectrum()?mc:s2 - mc - 1)); } case 2 : // Periodic return (double)img._cubic_atXYZ_p((float)x,(float)y,(float)z, (int)cimg::mod(c,(double)img._spectrum)); case 1 : // Neumann return (double)img._cubic_atXYZ((float)x,(float)y,(float)z, (int)(c<0?0:c>=img._spectrum?img._spectrum - 1:c)); default : // Dirichlet if (c<0 || c>=img._spectrum) return (T)0; return (double)img.cubic_atXYZ((float)x,(float)y,(float)z,(int)c,(T)0); } case 1 : // Linear interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), s2 = 2.f*img.spectrum(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), mc = cimg::mod((float)c,s2); return (double)img._linear_atXYZ(mx<img.width()?mx:w2 - mx - 1, my<img.height()?my:h2 - my - 1, mz<img.depth()?mz:d2 - mz - 1, (int)(mc<img.spectrum()?mc:s2 - mc - 1)); } case 2 : // Periodic return (double)img._linear_atXYZ_p((float)x,(float)y,(float)z, (int)cimg::mod(c,(double)img._spectrum)); case 1 : // Neumann return (double)img._linear_atXYZ((float)x,(float)y,(float)z, (int)(c<0?0:c>=img._spectrum?img._spectrum - 1:c)); default : // Dirichlet if (c<0 || c>=img._spectrum) return (T)0; return (double)img.linear_atXYZ((float)x,(float)y,(float)z,(int)c,(T)0); } default : // Nearest neighbor interpolation switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*img.width(), h2 = 2*img.height(), d2 = 2*img.depth(), s2 = 2*img.spectrum(), mx = cimg::mod((int)x,w2), my = cimg::mod((int)y,h2), mz = cimg::mod((int)z,d2), mc = cimg::mod((int)c,s2); return (double)img(mx<img.width()?mx:w2 - mx - 1, my<img.height()?my:h2 - my - 1, mz<img.depth()?mz:d2 - mz - 1, mc<img.spectrum()?mc:s2 - mc - 1); } case 2 : // Periodic return (double)img((int)cimg::mod(x,(double)img._width), (int)cimg::mod(y,(double)img._height), (int)cimg::mod(z,(double)img._depth), (int)cimg::mod(c,(double)img._spectrum)); case 1 : // Neumann return (double)img._atXYZC((int)x,(int)y,(int)z,(int)c); default : // Dirichlet return (double)img.atXYZC((int)x,(int)y,(int)z,(int)c,(T)0); } } } static double mp_list_l(_cimg_math_parser& mp) { return (double)mp.listout.width(); } static double mp_list_median(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); if (!mp.list_median) mp.list_median.assign(mp.listin._width); if (!mp.list_median[ind]) CImg<doubleT>::vector(mp.listin[ind].median()).move_to(mp.list_median[ind]); return *mp.list_median[ind]; } static double mp_list_set_ioff(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); CImg<T> &img = mp.listout[ind]; const longT off = (longT)_mp_arg(3), whds = (longT)img.size(); const double val = _mp_arg(1); if (off>=0 && off<whds) img[off] = (T)val; return val; } static double mp_list_set_ixyzc(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); CImg<T> &img = mp.listout[ind]; const int x = (int)_mp_arg(3), y = (int)_mp_arg(4), z = (int)_mp_arg(5), c = (int)_mp_arg(6); const double val = _mp_arg(1); if (x>=0 && x<img.width() && y>=0 && y<img.height() && z>=0 && z<img.depth() && c>=0 && c<img.spectrum()) img(x,y,z,c) = (T)val; return val; } static double mp_list_set_joff(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); CImg<T> &img = mp.listout[ind]; const int ox = (int)mp.mem[_cimg_mp_slot_x], oy = (int)mp.mem[_cimg_mp_slot_y], oz = (int)mp.mem[_cimg_mp_slot_z], oc = (int)mp.mem[_cimg_mp_slot_c]; const longT off = img.offset(ox,oy,oz,oc) + (longT)_mp_arg(3), whds = (longT)img.size(); const double val = _mp_arg(1); if (off>=0 && off<whds) img[off] = (T)val; return val; } static double mp_list_set_jxyzc(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); CImg<T> &img = mp.listout[ind]; const double ox = mp.mem[_cimg_mp_slot_x], oy = mp.mem[_cimg_mp_slot_y], oz = mp.mem[_cimg_mp_slot_z], oc = mp.mem[_cimg_mp_slot_c]; const int x = (int)(ox + _mp_arg(3)), y = (int)(oy + _mp_arg(4)), z = (int)(oz + _mp_arg(5)), c = (int)(oc + _mp_arg(6)); const double val = _mp_arg(1); if (x>=0 && x<img.width() && y>=0 && y<img.height() && z>=0 && z<img.depth() && c>=0 && c<img.spectrum()) img(x,y,z,c) = (T)val; return val; } static double mp_list_set_Ioff_s(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); CImg<T> &img = mp.listout[ind]; const longT off = (longT)_mp_arg(3), whd = (longT)img.width()*img.height()*img.depth(); const T val = (T)_mp_arg(1); if (off>=0 && off<whd) { T *ptrd = &img[off]; cimg_forC(img,c) { *ptrd = val; ptrd+=whd; } } return _mp_arg(1); } static double mp_list_set_Ioff_v(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); CImg<T> &img = mp.listout[ind]; const longT off = (longT)_mp_arg(3), whd = (longT)img.width()*img.height()*img.depth(); const double *ptrs = &_mp_arg(1) + 1; if (off>=0 && off<whd) { const unsigned int vsiz = (unsigned int)mp.opcode[4]; T *ptrd = &img[off]; cimg_for_inC(img,0,vsiz - 1,c) { *ptrd = (T)*(ptrs++); ptrd+=whd; } } return cimg::type<double>::nan(); } static double mp_list_set_Ixyz_s(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); CImg<T> &img = mp.listout[ind]; const int x = (int)_mp_arg(3), y = (int)_mp_arg(4), z = (int)_mp_arg(5); const T val = (T)_mp_arg(1); if (x>=0 && x<img.width() && y>=0 && y<img.height() && z>=0 && z<img.depth()) { T *ptrd = &img(x,y,z); const ulongT whd = (ulongT)img._width*img._height*img._depth; cimg_forC(img,c) { *ptrd = val; ptrd+=whd; } } return _mp_arg(1); } static double mp_list_set_Ixyz_v(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); CImg<T> &img = mp.listout[ind]; const int x = (int)_mp_arg(3), y = (int)_mp_arg(4), z = (int)_mp_arg(5); const double *ptrs = &_mp_arg(1) + 1; if (x>=0 && x<img.width() && y>=0 && y<img.height() && z>=0 && z<img.depth()) { const unsigned int vsiz = (unsigned int)mp.opcode[6]; T *ptrd = &img(x,y,z); const ulongT whd = (ulongT)img._width*img._height*img._depth; cimg_for_inC(img,0,vsiz - 1,c) { *ptrd = (T)*(ptrs++); ptrd+=whd; } } return cimg::type<double>::nan(); } static double mp_list_set_Joff_s(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); CImg<T> &img = mp.listout[ind]; const int ox = (int)mp.mem[_cimg_mp_slot_x], oy = (int)mp.mem[_cimg_mp_slot_y], oz = (int)mp.mem[_cimg_mp_slot_z], oc = (int)mp.mem[_cimg_mp_slot_c]; const longT off = img.offset(ox,oy,oz,oc) + (longT)_mp_arg(3), whd = (longT)img.width()*img.height()*img.depth(); const T val = (T)_mp_arg(1); if (off>=0 && off<whd) { T *ptrd = &img[off]; cimg_forC(img,c) { *ptrd = val; ptrd+=whd; } } return _mp_arg(1); } static double mp_list_set_Joff_v(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); CImg<T> &img = mp.listout[ind]; const int ox = (int)mp.mem[_cimg_mp_slot_x], oy = (int)mp.mem[_cimg_mp_slot_y], oz = (int)mp.mem[_cimg_mp_slot_z], oc = (int)mp.mem[_cimg_mp_slot_c]; const longT off = img.offset(ox,oy,oz,oc) + (longT)_mp_arg(3), whd = (longT)img.width()*img.height()*img.depth(); const double *ptrs = &_mp_arg(1) + 1; if (off>=0 && off<whd) { const unsigned int vsiz = (unsigned int)mp.opcode[4]; T *ptrd = &img[off]; cimg_for_inC(img,0,vsiz - 1,c) { *ptrd = (T)*(ptrs++); ptrd+=whd; } } return cimg::type<double>::nan(); } static double mp_list_set_Jxyz_s(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); CImg<T> &img = mp.listout[ind]; const double ox = mp.mem[_cimg_mp_slot_x], oy = mp.mem[_cimg_mp_slot_y], oz = mp.mem[_cimg_mp_slot_z]; const int x = (int)(ox + _mp_arg(3)), y = (int)(oy + _mp_arg(4)), z = (int)(oz + _mp_arg(5)); const T val = (T)_mp_arg(1); if (x>=0 && x<img.width() && y>=0 && y<img.height() && z>=0 && z<img.depth()) { T *ptrd = &img(x,y,z); const ulongT whd = (ulongT)img._width*img._height*img._depth; cimg_forC(img,c) { *ptrd = val; ptrd+=whd; } } return _mp_arg(1); } static double mp_list_set_Jxyz_v(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); CImg<T> &img = mp.listout[ind]; const double ox = mp.mem[_cimg_mp_slot_x], oy = mp.mem[_cimg_mp_slot_y], oz = mp.mem[_cimg_mp_slot_z]; const int x = (int)(ox + _mp_arg(3)), y = (int)(oy + _mp_arg(4)), z = (int)(oz + _mp_arg(5)); const double *ptrs = &_mp_arg(1) + 1; if (x>=0 && x<img.width() && y>=0 && y<img.height() && z>=0 && z<img.depth()) { const unsigned int vsiz = (unsigned int)mp.opcode[6]; T *ptrd = &img(x,y,z); const ulongT whd = (ulongT)img._width*img._height*img._depth; cimg_for_inC(img,0,vsiz - 1,c) { *ptrd = (T)*(ptrs++); ptrd+=whd; } } return cimg::type<double>::nan(); } static double mp_list_spectrum(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); return (double)mp.listin[ind]._spectrum; } static double mp_list_stats(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()), k = (unsigned int)mp.opcode[3]; if (!mp.list_stats) mp.list_stats.assign(mp.listin._width); if (!mp.list_stats[ind]) mp.list_stats[ind].assign(1,14,1,1,0).fill(mp.listin[ind].get_stats(),false); return mp.list_stats(ind,k); } static double mp_list_wh(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); return (double)mp.listin[ind]._width*mp.listin[ind]._height; } static double mp_list_whd(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); return (double)mp.listin[ind]._width*mp.listin[ind]._height*mp.listin[ind]._depth; } static double mp_list_whds(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); return (double)mp.listin[ind]._width*mp.listin[ind]._height*mp.listin[ind]._depth*mp.listin[ind]._spectrum; } static double mp_list_width(_cimg_math_parser& mp) { const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()); return (double)mp.listin[ind]._width; } static double mp_list_Ioff(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()), boundary_conditions = (unsigned int)_mp_arg(4), vsiz = (unsigned int)mp.opcode[5]; const CImg<T> &img = mp.listin[ind]; const longT off = (longT)_mp_arg(3), whd = (longT)img.width()*img.height()*img.depth(); const T *ptrs; if (off>=0 && off<whd) { ptrs = &img[off]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); } if (img._data) switch (boundary_conditions) { case 3 : { // Mirror const longT whd2 = 2*whd, moff = cimg::mod(off,whd2); ptrs = &img[moff<whd?moff:whd2 - moff - 1]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); } case 2 : // Periodic ptrs = &img[cimg::mod(off,whd)]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); case 1 : // Neumann ptrs = off<0?&img[0]:&img[whd - 1]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); default : // Dirichlet std::memset(ptrd,0,vsiz*sizeof(double)); return cimg::type<double>::nan(); } std::memset(ptrd,0,vsiz*sizeof(double)); return cimg::type<double>::nan(); } static double mp_list_Ixyz(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()), interpolation = (unsigned int)_mp_arg(6), boundary_conditions = (unsigned int)_mp_arg(7), vsiz = (unsigned int)mp.opcode[8]; const CImg<T> &img = mp.listin[ind]; const double x = _mp_arg(3), y = _mp_arg(4), z = _mp_arg(5); const ulongT whd = (ulongT)img._width*img._height*img._depth; const T *ptrs; switch (interpolation) { case 2 : // Cubic interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), cx = mx<img.width()?mx:w2 - mx - 1, cy = my<img.height()?my:h2 - my - 1, cz = mz<img.depth()?mz:d2 - mz - 1; cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._cubic_atXYZ(cx,cy,cz,c); } break; case 2 : // Periodic cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._cubic_atXYZ_p((float)x,(float)y,(float)z,c); break; case 1 : // Neumann cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._cubic_atXYZ((float)x,(float)y,(float)z,c); break; default : // Dirichlet cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img.cubic_atXYZ((float)x,(float)y,(float)z,c,(T)0); } break; case 1 : // Linear interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), cx = mx<img.width()?mx:w2 - mx - 1, cy = my<img.height()?my:h2 - my - 1, cz = mz<img.depth()?mz:d2 - mz - 1; cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._linear_atXYZ(cx,cy,cz,c); } break; case 2 : // Periodic cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._linear_atXYZ_p((float)x,(float)y,(float)z,c); break; case 1 : // Neumann cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._linear_atXYZ((float)x,(float)y,(float)z,c); break; default : // Dirichlet cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img.linear_atXYZ((float)x,(float)y,(float)z,c,(T)0); } break; default : // Nearest neighbor interpolation switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*img.width(), h2 = 2*img.height(), d2 = 2*img.depth(), mx = cimg::mod((int)x,w2), my = cimg::mod((int)y,h2), mz = cimg::mod((int)z,d2), cx = mx<img.width()?mx:w2 - mx - 1, cy = my<img.height()?my:h2 - my - 1, cz = mz<img.depth()?mz:d2 - mz - 1; ptrs = &img(cx,cy,cz); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } break; case 2 : { // Periodic const int cx = (int)cimg::mod(x,(double)img._width), cy = (int)cimg::mod(y,(double)img._height), cz = (int)cimg::mod(z,(double)img._depth); ptrs = &img(cx,cy,cz); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } break; case 1 : { // Neumann ptrs = &img._atXYZ((int)x,(int)y,(int)z); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } break; default : // Dirichlet if (img.containsXYZC((int)x,(int)y,(int)z)) { ptrs = &img((int)x,(int)y,(int)z); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } else std::memset(ptrd,0,vsiz*sizeof(double)); } } return cimg::type<double>::nan(); } static double mp_list_Joff(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()), boundary_conditions = (unsigned int)_mp_arg(4), vsiz = (unsigned int)mp.opcode[5]; const int ox = (int)mp.mem[_cimg_mp_slot_x], oy = (int)mp.mem[_cimg_mp_slot_y], oz = (int)mp.mem[_cimg_mp_slot_z]; const CImg<T> &img = mp.listin[ind]; const longT off = img.offset(ox,oy,oz) + (longT)_mp_arg(3), whd = (longT)img.width()*img.height()*img.depth(); const T *ptrs; if (off>=0 && off<whd) { ptrs = &img[off]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); } if (img._data) switch (boundary_conditions) { case 3 : { // Mirror const longT whd2 = 2*whd, moff = cimg::mod(off,whd2); ptrs = &img[moff<whd?moff:whd2 - moff - 1]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); } case 2 : // Periodic ptrs = &img[cimg::mod(off,whd)]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); case 1 : // Neumann ptrs = off<0?&img[0]:&img[whd - 1]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); default : // Dirichlet std::memset(ptrd,0,vsiz*sizeof(double)); return cimg::type<double>::nan(); } std::memset(ptrd,0,vsiz*sizeof(double)); return cimg::type<double>::nan(); } static double mp_list_Jxyz(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width()), interpolation = (unsigned int)_mp_arg(6), boundary_conditions = (unsigned int)_mp_arg(7), vsiz = (unsigned int)mp.opcode[8]; const CImg<T> &img = mp.listin[ind]; const double ox = mp.mem[_cimg_mp_slot_x], oy = mp.mem[_cimg_mp_slot_y], oz = mp.mem[_cimg_mp_slot_z], x = ox + _mp_arg(3), y = oy + _mp_arg(4), z = oz + _mp_arg(5); const ulongT whd = (ulongT)img._width*img._height*img._depth; const T *ptrs; switch (interpolation) { case 2 : // Cubic interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), cx = mx<img.width()?mx:w2 - mx - 1, cy = my<img.height()?my:h2 - my - 1, cz = mz<img.depth()?mz:d2 - mz - 1; cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._cubic_atXYZ(cx,cy,cz,c); } break; case 2 : // Periodic cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._cubic_atXYZ_p((float)x,(float)y,(float)z,c); break; case 1 : // Neumann cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._cubic_atXYZ((float)x,(float)y,(float)z,c); break; default : // Dirichlet cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img.cubic_atXYZ((float)x,(float)y,(float)z,c,(T)0); } break; case 1 : // Linear interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), cx = mx<img.width()?mx:w2 - mx - 1, cy = my<img.height()?my:h2 - my - 1, cz = mz<img.depth()?mz:d2 - mz - 1; cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._linear_atXYZ(cx,cy,cz,c); } break; case 2 : // Periodic cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._linear_atXYZ_p((float)x,(float)y,(float)z,c); break; case 1 : // Neumann cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._linear_atXYZ((float)x,(float)y,(float)z,c); break; default : // Dirichlet cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img.linear_atXYZ((float)x,(float)y,(float)z,c,(T)0); } break; case 0 : // Nearest neighbor interpolation switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*img.width(), h2 = 2*img.height(), d2 = 2*img.depth(), mx = cimg::mod((int)x,w2), my = cimg::mod((int)y,h2), mz = cimg::mod((int)z,d2), cx = mx<img.width()?mx:w2 - mx - 1, cy = my<img.height()?my:h2 - my - 1, cz = mz<img.depth()?mz:d2 - mz - 1; ptrs = &img(cx,cy,cz); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } break; case 2 : { // Periodic const int cx = (int)cimg::mod(x,(double)img._width), cy = (int)cimg::mod(y,(double)img._height), cz = (int)cimg::mod(z,(double)img._depth); ptrs = &img(cx,cy,cz); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } break; case 1 : { // Neumann ptrs = &img._atXYZ((int)x,(int)y,(int)z); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } break; default : // Dirichlet if (img.containsXYZC((int)x,(int)y,(int)z)) { ptrs = &img((int)x,(int)y,(int)z); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } else std::memset(ptrd,0,vsiz*sizeof(double)); } } return cimg::type<double>::nan(); } static double mp_log(_cimg_math_parser& mp) { return std::log(_mp_arg(2)); } static double mp_log10(_cimg_math_parser& mp) { return std::log10(_mp_arg(2)); } static double mp_log2(_cimg_math_parser& mp) { return cimg::log2(_mp_arg(2)); } static double mp_logical_and(_cimg_math_parser& mp) { const bool val_left = (bool)_mp_arg(2); const CImg<ulongT> *const p_end = ++mp.p_code + mp.opcode[4]; if (!val_left) { mp.p_code = p_end - 1; return 0; } const ulongT mem_right = mp.opcode[3]; for ( ; mp.p_code<p_end; ++mp.p_code) { mp.opcode._data = mp.p_code->_data; const ulongT target = mp.opcode[1]; mp.mem[target] = _cimg_mp_defunc(mp); } --mp.p_code; return (double)(bool)mp.mem[mem_right]; } static double mp_logical_not(_cimg_math_parser& mp) { return (double)!_mp_arg(2); } static double mp_logical_or(_cimg_math_parser& mp) { const bool val_left = (bool)_mp_arg(2); const CImg<ulongT> *const p_end = ++mp.p_code + mp.opcode[4]; if (val_left) { mp.p_code = p_end - 1; return 1; } const ulongT mem_right = mp.opcode[3]; for ( ; mp.p_code<p_end; ++mp.p_code) { mp.opcode._data = mp.p_code->_data; const ulongT target = mp.opcode[1]; mp.mem[target] = _cimg_mp_defunc(mp); } --mp.p_code; return (double)(bool)mp.mem[mem_right]; } static double mp_lowercase(_cimg_math_parser& mp) { return cimg::lowercase(_mp_arg(2)); } static double mp_lt(_cimg_math_parser& mp) { return (double)(_mp_arg(2)<_mp_arg(3)); } static double mp_lte(_cimg_math_parser& mp) { return (double)(_mp_arg(2)<=_mp_arg(3)); } static double mp_matrix_eig(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const double *ptr1 = &_mp_arg(2) + 1; const unsigned int k = (unsigned int)mp.opcode[3]; CImg<doubleT> val, vec; CImg<doubleT>(ptr1,k,k,1,1,true).symmetric_eigen(val,vec); CImg<doubleT>(ptrd,1,k,1,1,true) = val; CImg<doubleT>(ptrd + k,k,k,1,1,true) = vec.get_transpose(); return cimg::type<double>::nan(); } static double mp_matrix_inv(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const double *ptr1 = &_mp_arg(2) + 1; const unsigned int k = (unsigned int)mp.opcode[3]; CImg<doubleT>(ptrd,k,k,1,1,true) = CImg<doubleT>(ptr1,k,k,1,1,true).get_invert(); return cimg::type<double>::nan(); } static double mp_matrix_mul(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const double *ptr1 = &_mp_arg(2) + 1, *ptr2 = &_mp_arg(3) + 1; const unsigned int k = (unsigned int)mp.opcode[4], l = (unsigned int)mp.opcode[5], m = (unsigned int)mp.opcode[6]; CImg<doubleT>(ptrd,m,k,1,1,true) = CImg<doubleT>(ptr1,l,k,1,1,true)*CImg<doubleT>(ptr2,m,l,1,1,true); return cimg::type<double>::nan(); } static double mp_matrix_pseudoinv(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const double *ptr1 = &_mp_arg(2) + 1; const unsigned int k = (unsigned int)mp.opcode[3], l = (unsigned int)mp.opcode[4]; CImg<doubleT>(ptrd,l,k,1,1,true) = CImg<doubleT>(ptr1,k,l,1,1,true).get_pseudoinvert(); return cimg::type<double>::nan(); } static double mp_matrix_svd(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const double *ptr1 = &_mp_arg(2) + 1; const unsigned int k = (unsigned int)mp.opcode[3], l = (unsigned int)mp.opcode[4]; CImg<doubleT> U, S, V; CImg<doubleT>(ptr1,k,l,1,1,true).SVD(U,S,V); CImg<doubleT>(ptrd,1,k,1,1,true) = S; CImg<doubleT>(ptrd + k,k,l,1,1,true) = U; CImg<doubleT>(ptrd + k + k*l,k,k,1,1,true) = V; return cimg::type<double>::nan(); } static double mp_max(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; double val = _mp_arg(3); for (unsigned int i = 4; i<i_end; ++i) val = std::max(val,_mp_arg(i)); return val; } static double* _mp_memcopy_double(_cimg_math_parser& mp, const unsigned int ind, const ulongT *const p_ref, const longT siz, const long inc) { const longT off = *p_ref?p_ref[1] + (longT)mp.mem[(longT)p_ref[2]] + 1:ind, eoff = off + (siz - 1)*inc; if (off<0 || eoff>=mp.mem.width()) throw CImgArgumentException("[" cimg_appname "_math_parser] CImg<%s>: Function 'copy()': " "Out-of-bounds variable pointer " "(length: %ld, increment: %ld, offset start: %ld, " "offset end: %ld, offset max: %u).", mp.imgin.pixel_type(),siz,inc,off,eoff,mp.mem._width - 1); return &mp.mem[off]; } static float* _mp_memcopy_float(_cimg_math_parser& mp, const ulongT *const p_ref, const longT siz, const long inc, const bool is_out) { const unsigned ind = (unsigned int)p_ref[1]; const CImg<T> &img = is_out? (ind==~0U?mp.imgout:mp.listout[cimg::mod((int)mp.mem[ind],mp.listout.width())]): (ind==~0U?mp.imgin:mp.listin[cimg::mod((int)mp.mem[ind],mp.listin.width())]); const bool is_relative = (bool)p_ref[2]; int ox, oy, oz, oc; longT off = 0; if (is_relative) { ox = (int)mp.mem[_cimg_mp_slot_x]; oy = (int)mp.mem[_cimg_mp_slot_y]; oz = (int)mp.mem[_cimg_mp_slot_z]; oc = (int)mp.mem[_cimg_mp_slot_c]; off = img.offset(ox,oy,oz,oc); } if ((*p_ref)%2) { const int x = (int)mp.mem[p_ref[3]], y = (int)mp.mem[p_ref[4]], z = (int)mp.mem[p_ref[5]], c = *p_ref==5?0:(int)mp.mem[p_ref[6]]; off+=img.offset(x,y,z,c); } else off+=(longT)mp.mem[p_ref[3]]; const longT eoff = off + (siz - 1)*inc; if (off<0 || eoff>=(longT)img.size()) throw CImgArgumentException("[" cimg_appname "_math_parser] CImg<%s>: Function 'copy()': " "Out-of-bounds image pointer " "(length: %ld, increment: %ld, offset start: %ld, " "offset end: %ld, offset max: %lu).", mp.imgin.pixel_type(),siz,inc,off,eoff,img.size() - 1); return (float*)&img[off]; } static double mp_memcopy(_cimg_math_parser& mp) { longT siz = (longT)_mp_arg(4); const longT inc_d = (longT)_mp_arg(5), inc_s = (longT)_mp_arg(6); const float _opacity = (float)_mp_arg(7), opacity = (float)cimg::abs(_opacity), omopacity = 1 - std::max(_opacity,0.f); if (siz>0) { const bool is_doubled = mp.opcode[8]<=1, is_doubles = mp.opcode[15]<=1; if (is_doubled && is_doubles) { // (double*) <- (double*) double *ptrd = _mp_memcopy_double(mp,(unsigned int)mp.opcode[2],&mp.opcode[8],siz,inc_d); const double *ptrs = _mp_memcopy_double(mp,(unsigned int)mp.opcode[3],&mp.opcode[15],siz,inc_s); if (inc_d==1 && inc_s==1 && _opacity>=1) { if (ptrs + siz - 1<ptrd || ptrs>ptrd + siz - 1) std::memcpy(ptrd,ptrs,siz*sizeof(double)); else std::memmove(ptrd,ptrs,siz*sizeof(double)); } else { if (ptrs + (siz - 1)*inc_s<ptrd || ptrs>ptrd + (siz - 1)*inc_d) { if (_opacity>=1) while (siz-->0) { *ptrd = *ptrs; ptrd+=inc_d; ptrs+=inc_s; } else while (siz-->0) { *ptrd = omopacity**ptrd + opacity**ptrs; ptrd+=inc_d; ptrs+=inc_s; } } else { // Overlapping buffers CImg<doubleT> buf((unsigned int)siz); cimg_for(buf,ptr,double) { *ptr = *ptrs; ptrs+=inc_s; } ptrs = buf; if (_opacity>=1) while (siz-->0) { *ptrd = *(ptrs++); ptrd+=inc_d; } else while (siz-->0) { *ptrd = omopacity**ptrd + opacity**(ptrs++); ptrd+=inc_d; } } } } else if (is_doubled && !is_doubles) { // (double*) <- (float*) double *ptrd = _mp_memcopy_double(mp,(unsigned int)mp.opcode[2],&mp.opcode[8],siz,inc_d); const float *ptrs = _mp_memcopy_float(mp,&mp.opcode[15],siz,inc_s,false); if (_opacity>=1) while (siz-->0) { *ptrd = *ptrs; ptrd+=inc_d; ptrs+=inc_s; } else while (siz-->0) { *ptrd = omopacity**ptrd + _opacity**ptrs; ptrd+=inc_d; ptrs+=inc_s; } } else if (!is_doubled && is_doubles) { // (float*) <- (double*) float *ptrd = _mp_memcopy_float(mp,&mp.opcode[8],siz,inc_d,true); const double *ptrs = _mp_memcopy_double(mp,(unsigned int)mp.opcode[3],&mp.opcode[15],siz,inc_s); if (_opacity>=1) while (siz-->0) { *ptrd = (float)*ptrs; ptrd+=inc_d; ptrs+=inc_s; } else while (siz-->0) { *ptrd = (float)(omopacity**ptrd + opacity**ptrs); ptrd+=inc_d; ptrs+=inc_s; } } else { // (float*) <- (float*) float *ptrd = _mp_memcopy_float(mp,&mp.opcode[8],siz,inc_d,true); const float *ptrs = _mp_memcopy_float(mp,&mp.opcode[15],siz,inc_s,false); if (inc_d==1 && inc_s==1 && _opacity>=1) { if (ptrs + siz - 1<ptrd || ptrs>ptrd + siz - 1) std::memcpy(ptrd,ptrs,siz*sizeof(float)); else std::memmove(ptrd,ptrs,siz*sizeof(float)); } else { if (ptrs + (siz - 1)*inc_s<ptrd || ptrs>ptrd + (siz - 1)*inc_d) { if (_opacity>=1) while (siz-->0) { *ptrd = *ptrs; ptrd+=inc_d; ptrs+=inc_s; } else while (siz-->0) { *ptrd = omopacity**ptrd + opacity**ptrs; ptrd+=inc_d; ptrs+=inc_s; } } else { // Overlapping buffers CImg<floatT> buf((unsigned int)siz); cimg_for(buf,ptr,float) { *ptr = *ptrs; ptrs+=inc_s; } ptrs = buf; if (_opacity>=1) while (siz-->0) { *ptrd = *(ptrs++); ptrd+=inc_d; } else while (siz-->0) { *ptrd = omopacity**ptrd + opacity**(ptrs++); ptrd+=inc_d; } } } } } return _mp_arg(1); } static double mp_min(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; double val = _mp_arg(3); for (unsigned int i = 4; i<i_end; ++i) val = std::min(val,_mp_arg(i)); return val; } static double mp_minus(_cimg_math_parser& mp) { return -_mp_arg(2); } static double mp_median(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; switch (i_end - 3) { case 1 : return _mp_arg(3); case 2 : return cimg::median(_mp_arg(3),_mp_arg(4)); case 3 : return cimg::median(_mp_arg(3),_mp_arg(4),_mp_arg(5)); case 5 : return cimg::median(_mp_arg(3),_mp_arg(4),_mp_arg(5),_mp_arg(6),_mp_arg(7)); case 7 : return cimg::median(_mp_arg(3),_mp_arg(4),_mp_arg(5),_mp_arg(6),_mp_arg(7),_mp_arg(8),_mp_arg(9)); case 9 : return cimg::median(_mp_arg(3),_mp_arg(4),_mp_arg(5),_mp_arg(6),_mp_arg(7),_mp_arg(8),_mp_arg(9), _mp_arg(10),_mp_arg(11)); case 13 : return cimg::median(_mp_arg(3),_mp_arg(4),_mp_arg(5),_mp_arg(6),_mp_arg(7),_mp_arg(8),_mp_arg(9), _mp_arg(10),_mp_arg(11),_mp_arg(12),_mp_arg(13),_mp_arg(14),_mp_arg(15)); } CImg<doubleT> vals(i_end - 3); double *p = vals.data(); for (unsigned int i = 3; i<i_end; ++i) *(p++) = _mp_arg(i); return vals.median(); } static double mp_modulo(_cimg_math_parser& mp) { return cimg::mod(_mp_arg(2),_mp_arg(3)); } static double mp_mul(_cimg_math_parser& mp) { return _mp_arg(2)*_mp_arg(3); } static double mp_mul2(_cimg_math_parser& mp) { return _mp_arg(2)*_mp_arg(3)*_mp_arg(4); } static double mp_neq(_cimg_math_parser& mp) { return (double)(_mp_arg(2)!=_mp_arg(3)); } static double mp_norm0(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; switch (i_end - 3) { case 1 : return _mp_arg(3)!=0; case 2 : return (_mp_arg(3)!=0) + (_mp_arg(4)!=0); } double res = 0; for (unsigned int i = 3; i<i_end; ++i) res+=_mp_arg(i)==0?0:1; return res; } static double mp_norm1(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; switch (i_end - 3) { case 1 : return cimg::abs(_mp_arg(3)); case 2 : return cimg::abs(_mp_arg(3)) + cimg::abs(_mp_arg(4)); } double res = 0; for (unsigned int i = 3; i<i_end; ++i) res+=cimg::abs(_mp_arg(i)); return res; } static double mp_norm2(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; switch (i_end - 3) { case 1 : return cimg::abs(_mp_arg(3)); case 2 : return cimg::_hypot(_mp_arg(3),_mp_arg(4)); } double res = 0; for (unsigned int i = 3; i<i_end; ++i) res+=cimg::sqr(_mp_arg(i)); return std::sqrt(res); } static double mp_norminf(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; switch (i_end - 3) { case 1 : return cimg::abs(_mp_arg(3)); case 2 : return std::max(cimg::abs(_mp_arg(3)),cimg::abs(_mp_arg(4))); } double res = 0; for (unsigned int i = 3; i<i_end; ++i) { const double val = cimg::abs(_mp_arg(i)); if (val>res) res = val; } return res; } static double mp_normp(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; if (i_end==4) return cimg::abs(_mp_arg(3)); const double p = (double)mp.opcode[3]; double res = 0; for (unsigned int i = 4; i<i_end; ++i) res+=std::pow(cimg::abs(_mp_arg(i)),p); res = std::pow(res,1/p); return res>0?res:0.; } static double mp_permutations(_cimg_math_parser& mp) { return cimg::permutations((int)_mp_arg(2),(int)_mp_arg(3),(bool)_mp_arg(4)); } static double mp_polygon(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; unsigned int ind = (unsigned int)mp.opcode[3]; if (ind!=~0U) ind = (unsigned int)cimg::mod((int)_mp_arg(3),mp.listin.width()); CImg<T> &img = ind==~0U?mp.imgout:mp.listout[ind]; bool is_invalid_arguments = i_end<=4, is_outlined = false; if (!is_invalid_arguments) { int nbv = (int)_mp_arg(4); if (!nbv) is_invalid_arguments = true; else { if (nbv<0) { nbv = -nbv; is_outlined = true; } CImg<intT> points(nbv,2,1,1,0); CImg<T> color(img._spectrum,1,1,1,0); float opacity = 1; unsigned int i = 5, pattern=~0U; cimg_foroff(points,k) if (i<i_end) points(k/2,k%2) = (int)cimg::round(_mp_arg(i++)); else { is_invalid_arguments = true; break; } if (!is_invalid_arguments) { if (i<i_end) opacity = (float)_mp_arg(i++); if (is_outlined && i<i_end) pattern = (unsigned int)_mp_arg(i++); cimg_forX(color,k) if (i<i_end) color[k] = (T)_mp_arg(i++); else { color.resize(k,1,1,1,-1); break; } color.resize(img._spectrum,1,1,1,0,2); if (is_outlined) img.draw_polygon(points,color._data,opacity,pattern); else img.draw_polygon(points,color._data,opacity); } } } if (is_invalid_arguments) { CImg<doubleT> args(i_end - 4); cimg_forX(args,k) args[k] = _mp_arg(4 + k); if (ind==~0U) throw CImgArgumentException("[" cimg_appname "_math_parser] CImg<%s>: Function 'polygon()': " "Invalid arguments '%s'. ", mp.imgin.pixel_type(),args.value_string()._data); else throw CImgArgumentException("[" cimg_appname "_math_parser] CImg<%s>: Function 'polygon()': " "Invalid arguments '#%u%s%s'. ", mp.imgin.pixel_type(),ind,args._width?",":"",args.value_string()._data); } return cimg::type<double>::nan(); } static double mp_pow(_cimg_math_parser& mp) { const double v = _mp_arg(2), p = _mp_arg(3); return std::pow(v,p); } static double mp_pow0_25(_cimg_math_parser& mp) { const double val = _mp_arg(2); return std::sqrt(std::sqrt(val)); } static double mp_pow3(_cimg_math_parser& mp) { const double val = _mp_arg(2); return val*val*val; } static double mp_pow4(_cimg_math_parser& mp) { const double val = _mp_arg(2); return val*val*val*val; } static double mp_print(_cimg_math_parser& mp) { const double val = _mp_arg(1); const bool print_char = (bool)mp.opcode[3]; cimg_pragma_openmp(critical(mp_print)) { CImg<charT> _expr(mp.opcode[2] - 4); const ulongT *ptrs = mp.opcode._data + 4; cimg_for(_expr,ptrd,char) *ptrd = (char)*(ptrs++); cimg::strellipsize(_expr); cimg::mutex(6); if (print_char) std::fprintf(cimg::output(),"\n[" cimg_appname "_math_parser] %s = %g = '%c'",_expr._data,val,(int)val); else std::fprintf(cimg::output(),"\n[" cimg_appname "_math_parser] %s = %g",_expr._data,val); std::fflush(cimg::output()); cimg::mutex(6,0); } return val; } static double mp_prod(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; double val = _mp_arg(3); for (unsigned int i = 4; i<i_end; ++i) val*=_mp_arg(i); return val; } static double mp_copy(_cimg_math_parser& mp) { return _mp_arg(2); } static double mp_rol(_cimg_math_parser& mp) { return cimg::rol(_mp_arg(2),(unsigned int)_mp_arg(3)); } static double mp_ror(_cimg_math_parser& mp) { return cimg::ror(_mp_arg(2),(unsigned int)_mp_arg(3)); } static double mp_rot2d(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const float theta = (float)_mp_arg(2)*cimg::PI/180, ca = std::cos(theta), sa = std::sin(theta); *(ptrd++) = ca; *(ptrd++) = -sa; *(ptrd++) = sa; *ptrd = ca; return cimg::type<double>::nan(); } static double mp_rot3d(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const float x = (float)_mp_arg(2), y = (float)_mp_arg(3), z = (float)_mp_arg(4), theta = (float)_mp_arg(5); CImg<doubleT>(ptrd,3,3,1,1,true) = CImg<doubleT>::rotation_matrix(x,y,z,theta); return cimg::type<double>::nan(); } static double mp_round(_cimg_math_parser& mp) { return cimg::round(_mp_arg(2),_mp_arg(3),(int)_mp_arg(4)); } static double mp_self_add(_cimg_math_parser& mp) { return _mp_arg(1)+=_mp_arg(2); } static double mp_self_bitwise_and(_cimg_math_parser& mp) { double &val = _mp_arg(1); return val = (double)((longT)val & (longT)_mp_arg(2)); } static double mp_self_bitwise_left_shift(_cimg_math_parser& mp) { double &val = _mp_arg(1); return val = (double)((longT)val<<(unsigned int)_mp_arg(2)); } static double mp_self_bitwise_or(_cimg_math_parser& mp) { double &val = _mp_arg(1); return val = (double)((longT)val | (longT)_mp_arg(2)); } static double mp_self_bitwise_right_shift(_cimg_math_parser& mp) { double &val = _mp_arg(1); return val = (double)((longT)val>>(unsigned int)_mp_arg(2)); } static double mp_self_decrement(_cimg_math_parser& mp) { return --_mp_arg(1); } static double mp_self_increment(_cimg_math_parser& mp) { return ++_mp_arg(1); } static double mp_self_map_vector_s(_cimg_math_parser& mp) { // Vector += scalar unsigned int ptrd = (unsigned int)mp.opcode[1] + 1, siz = (unsigned int)mp.opcode[2]; mp_func op = (mp_func)mp.opcode[3]; CImg<ulongT> l_opcode(1,3); l_opcode[2] = mp.opcode[4]; // Scalar argument l_opcode.swap(mp.opcode); ulongT &target = mp.opcode[1]; while (siz-->0) { target = ptrd++; (*op)(mp); } l_opcode.swap(mp.opcode); return cimg::type<double>::nan(); } static double mp_self_map_vector_v(_cimg_math_parser& mp) { // Vector += vector unsigned int ptrd = (unsigned int)mp.opcode[1] + 1, siz = (unsigned int)mp.opcode[2], ptrs = (unsigned int)mp.opcode[4] + 1; mp_func op = (mp_func)mp.opcode[3]; CImg<ulongT> l_opcode(1,4); l_opcode.swap(mp.opcode); ulongT &target = mp.opcode[1], &argument = mp.opcode[2]; while (siz-->0) { target = ptrd++; argument = ptrs++; (*op)(mp); } l_opcode.swap(mp.opcode); return cimg::type<double>::nan(); } static double mp_self_mul(_cimg_math_parser& mp) { return _mp_arg(1)*=_mp_arg(2); } static double mp_self_div(_cimg_math_parser& mp) { return _mp_arg(1)/=_mp_arg(2); } static double mp_self_modulo(_cimg_math_parser& mp) { double &val = _mp_arg(1); return val = cimg::mod(val,_mp_arg(2)); } static double mp_self_pow(_cimg_math_parser& mp) { double &val = _mp_arg(1); return val = std::pow(val,_mp_arg(2)); } static double mp_self_sub(_cimg_math_parser& mp) { return _mp_arg(1)-=_mp_arg(2); } static double mp_set_ioff(_cimg_math_parser& mp) { CImg<T> &img = mp.imgout; const longT off = (longT)_mp_arg(2), whds = (longT)img.size(); const double val = _mp_arg(1); if (off>=0 && off<whds) img[off] = (T)val; return val; } static double mp_set_ixyzc(_cimg_math_parser& mp) { CImg<T> &img = mp.imgout; const int x = (int)_mp_arg(2), y = (int)_mp_arg(3), z = (int)_mp_arg(4), c = (int)_mp_arg(5); const double val = _mp_arg(1); if (x>=0 && x<img.width() && y>=0 && y<img.height() && z>=0 && z<img.depth() && c>=0 && c<img.spectrum()) img(x,y,z,c) = (T)val; return val; } static double mp_set_joff(_cimg_math_parser& mp) { CImg<T> &img = mp.imgout; const int ox = (int)mp.mem[_cimg_mp_slot_x], oy = (int)mp.mem[_cimg_mp_slot_y], oz = (int)mp.mem[_cimg_mp_slot_z], oc = (int)mp.mem[_cimg_mp_slot_c]; const longT off = img.offset(ox,oy,oz,oc) + (longT)_mp_arg(2), whds = (longT)img.size(); const double val = _mp_arg(1); if (off>=0 && off<whds) img[off] = (T)val; return val; } static double mp_set_jxyzc(_cimg_math_parser& mp) { CImg<T> &img = mp.imgout; const double ox = mp.mem[_cimg_mp_slot_x], oy = mp.mem[_cimg_mp_slot_y], oz = mp.mem[_cimg_mp_slot_z], oc = mp.mem[_cimg_mp_slot_c]; const int x = (int)(ox + _mp_arg(2)), y = (int)(oy + _mp_arg(3)), z = (int)(oz + _mp_arg(4)), c = (int)(oc + _mp_arg(5)); const double val = _mp_arg(1); if (x>=0 && x<img.width() && y>=0 && y<img.height() && z>=0 && z<img.depth() && c>=0 && c<img.spectrum()) img(x,y,z,c) = (T)val; return val; } static double mp_set_Ioff_s(_cimg_math_parser& mp) { CImg<T> &img = mp.imgout; const longT off = (longT)_mp_arg(2), whd = (longT)img.width()*img.height()*img.depth(); const T val = (T)_mp_arg(1); if (off>=0 && off<whd) { T *ptrd = &img[off]; cimg_forC(img,c) { *ptrd = val; ptrd+=whd; } } return _mp_arg(1); } static double mp_set_Ioff_v(_cimg_math_parser& mp) { CImg<T> &img = mp.imgout; const longT off = (longT)_mp_arg(2), whd = (longT)img.width()*img.height()*img.depth(); const double *ptrs = &_mp_arg(1) + 1; if (off>=0 && off<whd) { const unsigned int vsiz = (unsigned int)mp.opcode[3]; T *ptrd = &img[off]; cimg_for_inC(img,0,vsiz - 1,c) { *ptrd = (T)*(ptrs++); ptrd+=whd; } } return cimg::type<double>::nan(); } static double mp_set_Ixyz_s(_cimg_math_parser& mp) { CImg<T> &img = mp.imgout; const int x = (int)_mp_arg(2), y = (int)_mp_arg(3), z = (int)_mp_arg(4); const T val = (T)_mp_arg(1); if (x>=0 && x<img.width() && y>=0 && y<img.height() && z>=0 && z<img.depth()) { T *ptrd = &img(x,y,z); const ulongT whd = (ulongT)img._width*img._height*img._depth; cimg_forC(img,c) { *ptrd = val; ptrd+=whd; } } return _mp_arg(1); } static double mp_set_Ixyz_v(_cimg_math_parser& mp) { CImg<T> &img = mp.imgout; const int x = (int)_mp_arg(2), y = (int)_mp_arg(3), z = (int)_mp_arg(4); const double *ptrs = &_mp_arg(1) + 1; if (x>=0 && x<img.width() && y>=0 && y<img.height() && z>=0 && z<img.depth()) { const unsigned int vsiz = (unsigned int)mp.opcode[5]; T *ptrd = &img(x,y,z); const ulongT whd = (ulongT)img._width*img._height*img._depth; cimg_for_inC(img,0,vsiz - 1,c) { *ptrd = (T)*(ptrs++); ptrd+=whd; } } return cimg::type<double>::nan(); } static double mp_set_Joff_s(_cimg_math_parser& mp) { CImg<T> &img = mp.imgout; const int ox = (int)mp.mem[_cimg_mp_slot_x], oy = (int)mp.mem[_cimg_mp_slot_y], oz = (int)mp.mem[_cimg_mp_slot_z], oc = (int)mp.mem[_cimg_mp_slot_c]; const longT off = img.offset(ox,oy,oz,oc) + (longT)_mp_arg(2), whd = (longT)img.width()*img.height()*img.depth(); const T val = (T)_mp_arg(1); if (off>=0 && off<whd) { T *ptrd = &img[off]; cimg_forC(img,c) { *ptrd = val; ptrd+=whd; } } return _mp_arg(1); } static double mp_set_Joff_v(_cimg_math_parser& mp) { CImg<T> &img = mp.imgout; const int ox = (int)mp.mem[_cimg_mp_slot_x], oy = (int)mp.mem[_cimg_mp_slot_y], oz = (int)mp.mem[_cimg_mp_slot_z], oc = (int)mp.mem[_cimg_mp_slot_c]; const longT off = img.offset(ox,oy,oz,oc) + (longT)_mp_arg(2), whd = (longT)img.width()*img.height()*img.depth(); const double *ptrs = &_mp_arg(1) + 1; if (off>=0 && off<whd) { const unsigned int vsiz = (unsigned int)mp.opcode[3]; T *ptrd = &img[off]; cimg_for_inC(img,0,vsiz - 1,c) { *ptrd = (T)*(ptrs++); ptrd+=whd; } } return cimg::type<double>::nan(); } static double mp_set_Jxyz_s(_cimg_math_parser& mp) { CImg<T> &img = mp.imgout; const double ox = mp.mem[_cimg_mp_slot_x], oy = mp.mem[_cimg_mp_slot_y], oz = mp.mem[_cimg_mp_slot_z]; const int x = (int)(ox + _mp_arg(2)), y = (int)(oy + _mp_arg(3)), z = (int)(oz + _mp_arg(4)); const T val = (T)_mp_arg(1); if (x>=0 && x<img.width() && y>=0 && y<img.height() && z>=0 && z<img.depth()) { T *ptrd = &img(x,y,z); const ulongT whd = (ulongT)img._width*img._height*img._depth; cimg_forC(img,c) { *ptrd = val; ptrd+=whd; } } return _mp_arg(1); } static double mp_set_Jxyz_v(_cimg_math_parser& mp) { CImg<T> &img = mp.imgout; const double ox = mp.mem[_cimg_mp_slot_x], oy = mp.mem[_cimg_mp_slot_y], oz = mp.mem[_cimg_mp_slot_z]; const int x = (int)(ox + _mp_arg(2)), y = (int)(oy + _mp_arg(3)), z = (int)(oz + _mp_arg(4)); const double *ptrs = &_mp_arg(1) + 1; if (x>=0 && x<img.width() && y>=0 && y<img.height() && z>=0 && z<img.depth()) { const unsigned int vsiz = (unsigned int)mp.opcode[5]; T *ptrd = &img(x,y,z); const ulongT whd = (ulongT)img._width*img._height*img._depth; cimg_for_inC(img,0,vsiz - 1,c) { *ptrd = (T)*(ptrs++); ptrd+=whd; } } return cimg::type<double>::nan(); } static double mp_shift(_cimg_math_parser& mp) { double *const ptrd = &_mp_arg(1) + 1; const double *const ptrs = &_mp_arg(2) + 1; const unsigned int siz = (unsigned int)mp.opcode[3]; const int shift = (int)_mp_arg(4), boundary_conditions = (int)_mp_arg(5); CImg<doubleT>(ptrd,siz,1,1,1,true) = CImg<doubleT>(ptrs,siz,1,1,1,true).shift(shift,0,0,0,boundary_conditions); return cimg::type<double>::nan(); } static double mp_sign(_cimg_math_parser& mp) { return cimg::sign(_mp_arg(2)); } static double mp_sin(_cimg_math_parser& mp) { return std::sin(_mp_arg(2)); } static double mp_sinc(_cimg_math_parser& mp) { return cimg::sinc(_mp_arg(2)); } static double mp_sinh(_cimg_math_parser& mp) { return std::sinh(_mp_arg(2)); } static double mp_solve(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const double *ptr1 = &_mp_arg(2) + 1, *ptr2 = &_mp_arg(3) + 1; const unsigned int k = (unsigned int)mp.opcode[4], l = (unsigned int)mp.opcode[5], m = (unsigned int)mp.opcode[6]; CImg<doubleT>(ptrd,m,k,1,1,true) = CImg<doubleT>(ptr2,m,l,1,1,true).get_solve(CImg<doubleT>(ptr1,k,l,1,1,true)); return cimg::type<double>::nan(); } static double mp_sort(_cimg_math_parser& mp) { double *const ptrd = &_mp_arg(1) + 1; const double *const ptrs = &_mp_arg(2) + 1; const unsigned int siz = (unsigned int)mp.opcode[3], chunk_siz = (unsigned int)mp.opcode[5]; const bool is_increasing = (bool)_mp_arg(4); CImg<doubleT>(ptrd,chunk_siz,siz/chunk_siz,1,1,true) = CImg<doubleT>(ptrs,chunk_siz,siz/chunk_siz,1,1,true). get_sort(is_increasing,chunk_siz>1?'y':0); return cimg::type<double>::nan(); } static double mp_sqr(_cimg_math_parser& mp) { return cimg::sqr(_mp_arg(2)); } static double mp_sqrt(_cimg_math_parser& mp) { return std::sqrt(_mp_arg(2)); } static double mp_srand(_cimg_math_parser& mp) { mp.rng = (ulongT)_mp_arg(2); return cimg::type<double>::nan(); } static double mp_srand0(_cimg_math_parser& mp) { cimg::srand(&mp.rng); #if cimg_use_openmp!=0 mp.rng+=omp_get_thread_num(); #endif return cimg::type<double>::nan(); } static double mp_std(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; CImg<doubleT> vals(i_end - 3); double *p = vals.data(); for (unsigned int i = 3; i<i_end; ++i) *(p++) = _mp_arg(i); return std::sqrt(vals.variance()); } static double mp_string_init(_cimg_math_parser& mp) { const char *ptrs = (char*)&mp.opcode[3]; unsigned int ptrd = (unsigned int)mp.opcode[1] + 1, siz = (unsigned int)mp.opcode[2]; while (siz-->0) mp.mem[ptrd++] = (double)*(ptrs++); return cimg::type<double>::nan(); } static double mp_stov(_cimg_math_parser& mp) { const double *ptrs = &_mp_arg(2); const ulongT siz = (ulongT)mp.opcode[3]; longT ind = (longT)_mp_arg(4); const bool is_strict = (bool)_mp_arg(5); double val = cimg::type<double>::nan(); if (ind<0 || ind>=(longT)siz) return val; if (!siz) return *ptrs>='0' && *ptrs<='9'?*ptrs - '0':val; CImg<charT> ss(siz + 1 - ind); ptrs+=1 + ind; cimg_forX(ss,i) ss[i] = (char)ptrs[i]; ss.back() = 0; const char *s = ss._data; while (*s && *s<=32) ++s; const bool is_negative = *s=='-'; if (is_negative || *s=='+') ++s; int err = 0; char sep; if (*s=='0' && (s[1]=='x' || s[1]=='X') && s[2]>32) { // Hexadecimal number unsigned int ival; err = cimg_sscanf(s + 2,"%x%c",&ival,&sep); if (err>0) val = (double)ival; } else if (*s>32) { // Decimal number err = cimg_sscanf(s,"%lf%c",&val,&sep); #if cimg_OS==2 // Check for +/-NaN and +/-inf as Microsoft's sscanf() version is not able // to read those particular values. if (!err && (*s=='i' || *s=='I' || *s=='n' || *s=='N')) { if (!cimg::strncasecmp(s,"inf",3)) { val = cimg::type<double>::inf(); err = 1 + (s[3]!=0); } else if (!cimg::strncasecmp(s,"nan",3)) { val = cimg::type<double>::nan(); err = 1 + (s[3]!=0); } } #endif } if (err<=0 || (is_strict && err!=1)) return cimg::type<double>::nan(); if (is_negative) val = -val; return val; } static double mp_sub(_cimg_math_parser& mp) { return _mp_arg(2) - _mp_arg(3); } static double mp_sum(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; double val = _mp_arg(3); for (unsigned int i = 4; i<i_end; ++i) val+=_mp_arg(i); return val; } static double mp_tan(_cimg_math_parser& mp) { return std::tan(_mp_arg(2)); } static double mp_tanh(_cimg_math_parser& mp) { return std::tanh(_mp_arg(2)); } static double mp_trace(_cimg_math_parser& mp) { const double *ptrs = &_mp_arg(2) + 1; const unsigned int k = (unsigned int)mp.opcode[3]; return CImg<doubleT>(ptrs,k,k,1,1,true).trace(); } static double mp_transp(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const double *ptrs = &_mp_arg(2) + 1; const unsigned int k = (unsigned int)mp.opcode[3], l = (unsigned int)mp.opcode[4]; CImg<doubleT>(ptrd,l,k,1,1,true) = CImg<doubleT>(ptrs,k,l,1,1,true).get_transpose(); return cimg::type<double>::nan(); } static double mp_u(_cimg_math_parser& mp) { return cimg::rand(_mp_arg(2),_mp_arg(3),&mp.rng); } static double mp_uppercase(_cimg_math_parser& mp) { return cimg::uppercase(_mp_arg(2)); } static double mp_var(_cimg_math_parser& mp) { const unsigned int i_end = (unsigned int)mp.opcode[2]; CImg<doubleT> vals(i_end - 3); double *p = vals.data(); for (unsigned int i = 3; i<i_end; ++i) *(p++) = _mp_arg(i); return vals.variance(); } static double mp_vector_copy(_cimg_math_parser& mp) { std::memcpy(&_mp_arg(1) + 1,&_mp_arg(2) + 1,sizeof(double)*mp.opcode[3]); return cimg::type<double>::nan(); } static double mp_vector_crop(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const double *ptrs = &_mp_arg(2) + 1; const longT length = (longT)mp.opcode[3], start = (longT)_mp_arg(4), sublength = (longT)mp.opcode[5], step = (longT)_mp_arg(6); if (start<0 || start + step*(sublength-1)>=length) throw CImgArgumentException("[" cimg_appname "_math_parser] CImg<%s>: Value accessor '[]': " "Out-of-bounds sub-vector request " "(length: %ld, start: %ld, sub-length: %ld, step: %ld).", mp.imgin.pixel_type(),length,start,sublength,step); ptrs+=start; if (step==1) std::memcpy(ptrd,ptrs,sublength*sizeof(double)); else for (longT k = 0; k<sublength; ++k) { *(ptrd++) = *ptrs; ptrs+=step; } return cimg::type<double>::nan(); } static double mp_vector_init(_cimg_math_parser& mp) { unsigned int ptrs = 4U, ptrd = (unsigned int)mp.opcode[1] + 1, siz = (unsigned int)mp.opcode[3]; switch (mp.opcode[2] - 4) { case 0 : std::memset(mp.mem._data + ptrd,0,siz*sizeof(double)); break; // 0 values given case 1 : { const double val = _mp_arg(ptrs); while (siz-->0) mp.mem[ptrd++] = val; } break; default : while (siz-->0) { mp.mem[ptrd++] = _mp_arg(ptrs++); if (ptrs>=mp.opcode[2]) ptrs = 4U; } } return cimg::type<double>::nan(); } static double mp_vector_eq(_cimg_math_parser& mp) { const double *ptr1 = &_mp_arg(2) + 1, *ptr2 = &_mp_arg(4) + 1; unsigned int p1 = (unsigned int)mp.opcode[3], p2 = (unsigned int)mp.opcode[5], n; const int N = (int)_mp_arg(6); const bool case_sensitive = (bool)_mp_arg(7); bool still_equal = true; double value; if (!N) return true; // Compare all values. if (N<0) { if (p1>0 && p2>0) { // Vector == vector if (p1!=p2) return false; if (case_sensitive) while (still_equal && p1--) still_equal = *(ptr1++)==*(ptr2++); else while (still_equal && p1--) still_equal = cimg::lowercase(*(ptr1++))==cimg::lowercase(*(ptr2++)); return still_equal; } else if (p1>0 && !p2) { // Vector == scalar value = _mp_arg(4); if (!case_sensitive) value = cimg::lowercase(value); while (still_equal && p1--) still_equal = *(ptr1++)==value; return still_equal; } else if (!p1 && p2>0) { // Scalar == vector value = _mp_arg(2); if (!case_sensitive) value = cimg::lowercase(value); while (still_equal && p2--) still_equal = *(ptr2++)==value; return still_equal; } else { // Scalar == scalar if (case_sensitive) return _mp_arg(2)==_mp_arg(4); else return cimg::lowercase(_mp_arg(2))==cimg::lowercase(_mp_arg(4)); } } // Compare only first N values. if (p1>0 && p2>0) { // Vector == vector n = cimg::min((unsigned int)N,p1,p2); if (case_sensitive) while (still_equal && n--) still_equal = *(ptr1++)==(*ptr2++); else while (still_equal && n--) still_equal = cimg::lowercase(*(ptr1++))==cimg::lowercase(*(ptr2++)); return still_equal; } else if (p1>0 && !p2) { // Vector == scalar n = std::min((unsigned int)N,p1); value = _mp_arg(4); if (!case_sensitive) value = cimg::lowercase(value); while (still_equal && n--) still_equal = *(ptr1++)==value; return still_equal; } else if (!p1 && p2>0) { // Scalar == vector n = std::min((unsigned int)N,p2); value = _mp_arg(2); if (!case_sensitive) value = cimg::lowercase(value); while (still_equal && n--) still_equal = *(ptr2++)==value; return still_equal; } // Scalar == scalar if (case_sensitive) return _mp_arg(2)==_mp_arg(4); return cimg::lowercase(_mp_arg(2))==cimg::lowercase(_mp_arg(4)); } static double mp_vector_off(_cimg_math_parser& mp) { const unsigned int ptr = (unsigned int)mp.opcode[2] + 1, siz = (unsigned int)mp.opcode[3]; const int off = (int)_mp_arg(4); return off>=0 && off<(int)siz?mp.mem[ptr + off]:cimg::type<double>::nan(); } static double mp_vector_map_sv(_cimg_math_parser& mp) { // Operator(scalar,vector) unsigned int siz = (unsigned int)mp.opcode[2], ptrs = (unsigned int)mp.opcode[5] + 1; double *ptrd = &_mp_arg(1) + 1; mp_func op = (mp_func)mp.opcode[3]; CImg<ulongT> l_opcode(4); l_opcode[2] = mp.opcode[4]; // Scalar argument1 l_opcode.swap(mp.opcode); ulongT &argument2 = mp.opcode[3]; while (siz-->0) { argument2 = ptrs++; *(ptrd++) = (*op)(mp); } l_opcode.swap(mp.opcode); return cimg::type<double>::nan(); } static double mp_vector_map_v(_cimg_math_parser& mp) { // Operator(vector) unsigned int siz = (unsigned int)mp.opcode[2], ptrs = (unsigned int)mp.opcode[4] + 1; double *ptrd = &_mp_arg(1) + 1; mp_func op = (mp_func)mp.opcode[3]; CImg<ulongT> l_opcode(1,3); l_opcode.swap(mp.opcode); ulongT &argument = mp.opcode[2]; while (siz-->0) { argument = ptrs++; *(ptrd++) = (*op)(mp); } l_opcode.swap(mp.opcode); return cimg::type<double>::nan(); } static double mp_vector_map_vs(_cimg_math_parser& mp) { // Operator(vector,scalar) unsigned int siz = (unsigned int)mp.opcode[2], ptrs = (unsigned int)mp.opcode[4] + 1; double *ptrd = &_mp_arg(1) + 1; mp_func op = (mp_func)mp.opcode[3]; CImg<ulongT> l_opcode(1,4); l_opcode[3] = mp.opcode[5]; // Scalar argument2 l_opcode.swap(mp.opcode); ulongT &argument1 = mp.opcode[2]; while (siz-->0) { argument1 = ptrs++; *(ptrd++) = (*op)(mp); } l_opcode.swap(mp.opcode); return cimg::type<double>::nan(); } static double mp_vector_map_vss(_cimg_math_parser& mp) { // Operator(vector,scalar,scalar) unsigned int siz = (unsigned int)mp.opcode[2], ptrs = (unsigned int)mp.opcode[4] + 1; double *ptrd = &_mp_arg(1) + 1; mp_func op = (mp_func)mp.opcode[3]; CImg<ulongT> l_opcode(1,5); l_opcode[3] = mp.opcode[5]; // Scalar argument2 l_opcode[4] = mp.opcode[6]; // Scalar argument3 l_opcode.swap(mp.opcode); ulongT &argument1 = mp.opcode[2]; while (siz-->0) { argument1 = ptrs++; *(ptrd++) = (*op)(mp); } l_opcode.swap(mp.opcode); return cimg::type<double>::nan(); } static double mp_vector_map_vv(_cimg_math_parser& mp) { // Operator(vector,vector) unsigned int siz = (unsigned int)mp.opcode[2], ptrs1 = (unsigned int)mp.opcode[4] + 1, ptrs2 = (unsigned int)mp.opcode[5] + 1; double *ptrd = &_mp_arg(1) + 1; mp_func op = (mp_func)mp.opcode[3]; CImg<ulongT> l_opcode(1,4); l_opcode.swap(mp.opcode); ulongT &argument1 = mp.opcode[2], &argument2 = mp.opcode[3]; while (siz-->0) { argument1 = ptrs1++; argument2 = ptrs2++; *(ptrd++) = (*op)(mp); } l_opcode.swap(mp.opcode); return cimg::type<double>::nan(); } static double mp_vector_neq(_cimg_math_parser& mp) { return !mp_vector_eq(mp); } static double mp_vector_print(_cimg_math_parser& mp) { const bool print_string = (bool)mp.opcode[4]; cimg_pragma_openmp(critical(mp_vector_print)) { CImg<charT> _expr(mp.opcode[2] - 5); const ulongT *ptrs = mp.opcode._data + 5; cimg_for(_expr,ptrd,char) *ptrd = (char)*(ptrs++); cimg::strellipsize(_expr); unsigned int ptr = (unsigned int)mp.opcode[1] + 1, siz0 = (unsigned int)mp.opcode[3], siz = siz0; cimg::mutex(6); std::fprintf(cimg::output(),"\n[" cimg_appname "_math_parser] %s = [ ",_expr._data); unsigned int count = 0; while (siz-->0) { if (count>=64 && siz>=64) { std::fprintf(cimg::output(),"...,"); ptr = (unsigned int)mp.opcode[1] + 1 + siz0 - 64; siz = 64; } else std::fprintf(cimg::output(),"%g%s",mp.mem[ptr++],siz?",":""); ++count; } if (print_string) { CImg<charT> str(siz0 + 1); ptr = (unsigned int)mp.opcode[1] + 1; for (unsigned int k = 0; k<siz0; ++k) str[k] = (char)mp.mem[ptr++]; str[siz0] = 0; cimg::strellipsize(str,1024,false); std::fprintf(cimg::output()," ] = '%s' (size: %u)",str._data,siz0); } else std::fprintf(cimg::output()," ] (size: %u)",siz0); std::fflush(cimg::output()); cimg::mutex(6,0); } return cimg::type<double>::nan(); } static double mp_vector_resize(_cimg_math_parser& mp) { double *const ptrd = &_mp_arg(1) + 1; const unsigned int p1 = (unsigned int)mp.opcode[2], p2 = (unsigned int)mp.opcode[4]; const int interpolation = (int)_mp_arg(5), boundary_conditions = (int)_mp_arg(6); if (p2) { // Resize vector const double *const ptrs = &_mp_arg(3) + 1; CImg<doubleT>(ptrd,p1,1,1,1,true) = CImg<doubleT>(ptrs,p2,1,1,1,true). get_resize(p1,1,1,1,interpolation,boundary_conditions); } else { // Resize scalar const double value = _mp_arg(3); CImg<doubleT>(ptrd,p1,1,1,1,true) = CImg<doubleT>(1,1,1,1,value).resize(p1,1,1,1,interpolation, boundary_conditions); } return cimg::type<double>::nan(); } static double mp_vector_reverse(_cimg_math_parser& mp) { double *const ptrd = &_mp_arg(1) + 1; const double *const ptrs = &_mp_arg(2) + 1; const unsigned int p1 = (unsigned int)mp.opcode[3]; CImg<doubleT>(ptrd,p1,1,1,1,true) = CImg<doubleT>(ptrs,p1,1,1,1,true).get_mirror('x'); return cimg::type<double>::nan(); } static double mp_vector_set_off(_cimg_math_parser& mp) { const unsigned int ptr = (unsigned int)mp.opcode[2] + 1, siz = (unsigned int)mp.opcode[3]; const int off = (int)_mp_arg(4); if (off>=0 && off<(int)siz) mp.mem[ptr + off] = _mp_arg(5); return _mp_arg(5); } static double mp_vtos(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const unsigned int sizd = (unsigned int)mp.opcode[2], sizs = (unsigned int)mp.opcode[4]; const int nb_digits = (int)_mp_arg(5); CImg<charT> format(8); switch (nb_digits) { case -1 : std::strcpy(format,"%g"); break; case 0 : std::strcpy(format,"%.17g"); break; default : cimg_snprintf(format,format._width,"%%.%dg",nb_digits); } CImg<charT> str; if (sizs) { // Vector expression const double *ptrs = &_mp_arg(3) + 1; CImg<doubleT>(ptrs,sizs,1,1,1,true).value_string(',',sizd + 1,format).move_to(str); } else { // Scalar expression str.assign(sizd + 1); cimg_snprintf(str,sizd + 1,format,_mp_arg(3)); } const unsigned int l = std::min(sizd,(unsigned int)std::strlen(str) + 1); CImg<doubleT>(ptrd,l,1,1,1,true) = str.get_shared_points(0,l - 1); return cimg::type<double>::nan(); } static double mp_while(_cimg_math_parser& mp) { const ulongT mem_body = mp.opcode[1], mem_cond = mp.opcode[2]; const CImg<ulongT> *const p_cond = ++mp.p_code, *const p_body = p_cond + mp.opcode[3], *const p_end = p_body + mp.opcode[4]; const unsigned int vsiz = (unsigned int)mp.opcode[5]; bool is_cond = false; if (mp.opcode[6]) { // Set default value for result and condition if necessary if (vsiz) CImg<doubleT>(&mp.mem[mem_body] + 1,vsiz,1,1,1,true).fill(cimg::type<double>::nan()); else mp.mem[mem_body] = cimg::type<double>::nan(); } if (mp.opcode[7]) mp.mem[mem_cond] = 0; const unsigned int _break_type = mp.break_type; mp.break_type = 0; do { for (mp.p_code = p_cond; mp.p_code<p_body; ++mp.p_code) { // Evaluate condition mp.opcode._data = mp.p_code->_data; const ulongT target = mp.opcode[1]; mp.mem[target] = _cimg_mp_defunc(mp); } if (mp.break_type==1) break; is_cond = (bool)mp.mem[mem_cond]; if (is_cond && !mp.break_type) // Evaluate body for (mp.p_code = p_body; mp.p_code<p_end; ++mp.p_code) { mp.opcode._data = mp.p_code->_data; const ulongT target = mp.opcode[1]; mp.mem[target] = _cimg_mp_defunc(mp); } if (mp.break_type==1) break; else if (mp.break_type==2) mp.break_type = 0; } while (is_cond); mp.break_type = _break_type; mp.p_code = p_end - 1; return mp.mem[mem_body]; } static double mp_Ioff(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const unsigned int boundary_conditions = (unsigned int)_mp_arg(3), vsiz = (unsigned int)mp.opcode[4]; const CImg<T> &img = mp.imgin; const longT off = (longT)_mp_arg(2), whd = (longT)img.width()*img.height()*img.depth(); const T *ptrs; if (off>=0 && off<whd) { ptrs = &img[off]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); } if (img._data) switch (boundary_conditions) { case 3 : { // Mirror const longT whd2 = 2*whd, moff = cimg::mod(off,whd2); ptrs = &img[moff<whd?moff:whd2 - moff - 1]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); } case 2 : // Periodic ptrs = &img[cimg::mod(off,whd)]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); case 1 : // Neumann ptrs = off<0?&img[0]:&img[whd - 1]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); default : // Dirichlet std::memset(ptrd,0,vsiz*sizeof(double)); return cimg::type<double>::nan(); } std::memset(ptrd,0,vsiz*sizeof(double)); return cimg::type<double>::nan(); } static double mp_Ixyz(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const unsigned int interpolation = (unsigned int)_mp_arg(5), boundary_conditions = (unsigned int)_mp_arg(6), vsiz = (unsigned int)mp.opcode[7]; const CImg<T> &img = mp.imgin; const double x = _mp_arg(2), y = _mp_arg(3), z = _mp_arg(4); const ulongT whd = (ulongT)img._width*img._height*img._depth; const T *ptrs; switch (interpolation) { case 2 : // Cubic interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), cx = mx<img.width()?mx:w2 - mx - 1, cy = my<img.height()?my:h2 - my - 1, cz = mz<img.depth()?mz:d2 - mz - 1; cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._cubic_atXYZ(cx,cy,cz,c); } break; case 2 : // Periodic cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._cubic_atXYZ_p((float)x,(float)y,(float)z,c); break; case 1 : // Neumann cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._cubic_atXYZ((float)x,(float)y,(float)z,c); break; default : // Dirichlet cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img.cubic_atXYZ((float)x,(float)y,(float)z,c,(T)0); } break; case 1 : // Linear interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), cx = mx<img.width()?mx:w2 - mx - 1, cy = my<img.height()?my:h2 - my - 1, cz = mz<img.depth()?mz:d2 - mz - 1; cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._linear_atXYZ(cx,cy,cz,c); } break; case 2 : // Periodic cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._linear_atXYZ_p((float)x,(float)y,(float)z,c); break; case 1 : // Neumann cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._linear_atXYZ((float)x,(float)y,(float)z,c); break; default : // Dirichlet cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img.linear_atXYZ((float)x,(float)y,(float)z,c,(T)0); } break; default : // Nearest neighbor interpolation switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*img.width(), h2 = 2*img.height(), d2 = 2*img.depth(), mx = cimg::mod((int)x,w2), my = cimg::mod((int)y,h2), mz = cimg::mod((int)z,d2), cx = mx<img.width()?mx:w2 - mx - 1, cy = my<img.height()?my:h2 - my - 1, cz = mz<img.depth()?mz:d2 - mz - 1; ptrs = &img(cx,cy,cz); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } break; case 2 : { // Periodic const int cx = (int)cimg::mod(x,(double)img._width), cy = (int)cimg::mod(y,(double)img._height), cz = (int)cimg::mod(z,(double)img._depth); ptrs = &img(cx,cy,cz); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } break; case 1 : { // Neumann ptrs = &img._atXYZ((int)x,(int)y,(int)z); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } break; default : // Dirichlet if (img.containsXYZC((int)x,(int)y,(int)z)) { ptrs = &img((int)x,(int)y,(int)z); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } else std::memset(ptrd,0,vsiz*sizeof(double)); } } return cimg::type<double>::nan(); } static double mp_Joff(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const unsigned int boundary_conditions = (unsigned int)_mp_arg(3), vsiz = (unsigned int)mp.opcode[4]; const CImg<T> &img = mp.imgin; const int ox = (int)mp.mem[_cimg_mp_slot_x], oy = (int)mp.mem[_cimg_mp_slot_y], oz = (int)mp.mem[_cimg_mp_slot_z]; const longT off = img.offset(ox,oy,oz) + (longT)_mp_arg(2), whd = (longT)img.width()*img.height()*img.depth(); const T *ptrs; if (off>=0 && off<whd) { ptrs = &img[off]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); } if (img._data) switch (boundary_conditions) { case 3 : { // Mirror const longT whd2 = 2*whd, moff = cimg::mod(off,whd2); ptrs = &img[moff<whd?moff:whd2 - moff - 1]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); } case 2 : // Periodic ptrs = &img[cimg::mod(off,whd)]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); case 1 : // Neumann ptrs = off<0?&img[0]:&img[whd - 1]; cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return cimg::type<double>::nan(); default : // Dirichlet std::memset(ptrd,0,vsiz*sizeof(double)); return cimg::type<double>::nan(); } std::memset(ptrd,0,vsiz*sizeof(double)); return cimg::type<double>::nan(); } static double mp_Jxyz(_cimg_math_parser& mp) { double *ptrd = &_mp_arg(1) + 1; const unsigned int interpolation = (unsigned int)_mp_arg(5), boundary_conditions = (unsigned int)_mp_arg(6), vsiz = (unsigned int)mp.opcode[7]; const CImg<T> &img = mp.imgin; const double ox = mp.mem[_cimg_mp_slot_x], oy = mp.mem[_cimg_mp_slot_y], oz = mp.mem[_cimg_mp_slot_z], x = ox + _mp_arg(2), y = oy + _mp_arg(3), z = oz + _mp_arg(4); const ulongT whd = (ulongT)img._width*img._height*img._depth; const T *ptrs; switch (interpolation) { case 2 : // Cubic interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), cx = mx<img.width()?mx:w2 - mx - 1, cy = my<img.height()?my:h2 - my - 1, cz = mz<img.depth()?mz:d2 - mz - 1; cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._cubic_atXYZ(cx,cy,cz,c); } break; case 2 : // Periodic cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._cubic_atXYZ_p((float)x,(float)y,(float)z,c); break; case 1 : // Neumann cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._cubic_atXYZ((float)x,(float)y,(float)z,c); break; default : // Dirichlet cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img.cubic_atXYZ((float)x,(float)y,(float)z,c,(T)0); } break; case 1 : // Linear interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*img.width(), h2 = 2.f*img.height(), d2 = 2.f*img.depth(), mx = cimg::mod((float)x,w2), my = cimg::mod((float)y,h2), mz = cimg::mod((float)z,d2), cx = mx<img.width()?mx:w2 - mx - 1, cy = my<img.height()?my:h2 - my - 1, cz = mz<img.depth()?mz:d2 - mz - 1; cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._linear_atXYZ(cx,cy,cz,c); } break; case 2 : // Periodic cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._linear_atXYZ_p((float)x,(float)y,(float)z,c); break; case 1 : // Neumann cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img._linear_atXYZ((float)x,(float)y,(float)z,c); break; default : // Dirichlet cimg_for_inC(img,0,vsiz - 1,c) *(ptrd++) = (double)img.linear_atXYZ((float)x,(float)y,(float)z,c,(T)0); } break; default : // Nearest neighbor interpolation switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*img.width(), h2 = 2*img.height(), d2 = 2*img.depth(), mx = cimg::mod((int)x,w2), my = cimg::mod((int)y,h2), mz = cimg::mod((int)z,d2), cx = mx<img.width()?mx:w2 - mx - 1, cy = my<img.height()?my:h2 - my - 1, cz = mz<img.depth()?mz:d2 - mz - 1; ptrs = &img(cx,cy,cz); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } break; case 2 : { // Periodic const int cx = (int)cimg::mod(x,(double)img._width), cy = (int)cimg::mod(y,(double)img._height), cz = (int)cimg::mod(z,(double)img._depth); ptrs = &img(cx,cy,cz); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } break; case 1 : { // Neumann ptrs = &img._atXYZ((int)x,(int)y,(int)z); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } break; default : // Dirichlet if (img.containsXYZC((int)x,(int)y,(int)z)) { ptrs = &img((int)x,(int)y,(int)z); cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = (double)*ptrs; ptrs+=whd; } } else std::memset(ptrd,0,vsiz*sizeof(double)); } } return cimg::type<double>::nan(); } #undef _mp_arg }; // struct _cimg_math_parser {} #define _cimg_create_pointwise_functions(name,func,min_size) \ CImg<T>& name() { \ if (is_empty()) return *this; \ cimg_openmp_for(*this,func((double)*ptr),min_size); \ return *this; \ } \ CImg<Tfloat> get_##name() const { \ return CImg<Tfloat>(*this,false).name(); \ } //! Compute the square value of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its square value \f$I_{(x,y,z,c)}^2\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. \par Example \code const CImg<float> img("reference.jpg"); (img,img.get_sqr().normalize(0,255)).display(); \endcode \image html ref_sqr.jpg **/ _cimg_create_pointwise_functions(sqr,cimg::sqr,524288) //! Compute the square root of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its square root \f$\sqrt{I_{(x,y,z,c)}}\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. \par Example \code const CImg<float> img("reference.jpg"); (img,img.get_sqrt().normalize(0,255)).display(); \endcode \image html ref_sqrt.jpg **/ _cimg_create_pointwise_functions(sqrt,std::sqrt,8192) //! Compute the exponential of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its exponential \f$e^{I_{(x,y,z,c)}}\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(exp,std::exp,4096) //! Compute the logarithm of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its logarithm \f$\mathrm{log}_{e}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(log,std::log,262144) //! Compute the base-2 logarithm of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its base-2 logarithm \f$\mathrm{log}_{2}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(log2,cimg::log2,4096) //! Compute the base-10 logarithm of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its base-10 logarithm \f$\mathrm{log}_{10}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(log10,std::log10,4096) //! Compute the absolute value of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its absolute value \f$|I_{(x,y,z,c)}|\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(abs,cimg::abs,524288) //! Compute the sign of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its sign \f$\mathrm{sign}(I_{(x,y,z,c)})\f$. \note - The sign is set to: - \c 1 if pixel value is strictly positive. - \c -1 if pixel value is strictly negative. - \c 0 if pixel value is equal to \c 0. - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(sign,cimg::sign,32768) //! Compute the cosine of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its cosine \f$\cos(I_{(x,y,z,c)})\f$. \note - Pixel values are regarded as being in \e radian. - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(cos,std::cos,8192) //! Compute the sine of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its sine \f$\sin(I_{(x,y,z,c)})\f$. \note - Pixel values are regarded as being in \e radian. - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(sin,std::sin,8192) //! Compute the sinc of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its sinc \f$\mathrm{sinc}(I_{(x,y,z,c)})\f$. \note - Pixel values are regarded as being exin \e radian. - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(sinc,cimg::sinc,2048) //! Compute the tangent of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its tangent \f$\tan(I_{(x,y,z,c)})\f$. \note - Pixel values are regarded as being exin \e radian. - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(tan,std::tan,2048) //! Compute the hyperbolic cosine of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its hyperbolic cosine \f$\mathrm{cosh}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(cosh,std::cosh,2048) //! Compute the hyperbolic sine of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its hyperbolic sine \f$\mathrm{sinh}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(sinh,std::sinh,2048) //! Compute the hyperbolic tangent of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its hyperbolic tangent \f$\mathrm{tanh}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(tanh,std::tanh,2048) //! Compute the arccosine of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its arccosine \f$\mathrm{acos}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(acos,std::acos,8192) //! Compute the arcsine of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its arcsine \f$\mathrm{asin}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(asin,std::asin,8192) //! Compute the arctangent of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its arctangent \f$\mathrm{atan}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(atan,std::atan,8192) //! Compute the arctangent2 of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its arctangent2 \f$\mathrm{atan2}(I_{(x,y,z,c)})\f$. \param img Image whose pixel values specify the second argument of the \c atan2() function. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. \par Example \code const CImg<float> img_x(100,100,1,1,"x-w/2",false), // Define an horizontal centered gradient, from '-width/2' to 'width/2' img_y(100,100,1,1,"y-h/2",false), // Define a vertical centered gradient, from '-height/2' to 'height/2' img_atan2 = img_y.get_atan2(img_x); // Compute atan2(y,x) for each pixel value (img_x,img_y,img_atan2).display(); \endcode **/ template<typename t> CImg<T>& atan2(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return atan2(+img); T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)std::atan2((double)*ptrd,(double)*(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)std::atan2((double)*ptrd,(double)*(ptrs++)); } return *this; } //! Compute the arctangent2 of each pixel value \newinstance. template<typename t> CImg<Tfloat> get_atan2(const CImg<t>& img) const { return CImg<Tfloat>(*this,false).atan2(img); } //! Compute the hyperbolic arccosine of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its arccosineh \f$\mathrm{acosh}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(acosh,cimg::acosh,8192) //! Compute the hyperbolic arcsine of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its hyperbolic arcsine \f$\mathrm{asinh}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(asinh,cimg::asinh,8192) //! Compute the hyperbolic arctangent of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its hyperbolic arctangent \f$\mathrm{atanh}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ _cimg_create_pointwise_functions(atanh,cimg::atanh,8192) //! In-place pointwise multiplication. /** Compute the pointwise multiplication between the image instance and the specified input image \c img. \param img Input image, as the second operand of the multiplication. \note - Similar to operator+=(const CImg<t>&), except that it performs a pointwise multiplication instead of an addition. - It does \e not perform a \e matrix multiplication. For this purpose, use operator*=(const CImg<t>&) instead. \par Example \code CImg<float> img("reference.jpg"), shade(img.width,img.height(),1,1,"-(x-w/2)^2-(y-h/2)^2",false); shade.normalize(0,1); (img,shade,img.get_mul(shade)).display(); \endcode **/ template<typename t> CImg<T>& mul(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return mul(+img); T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)(*ptrd * *(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)(*ptrd * *(ptrs++)); } return *this; } //! In-place pointwise multiplication \newinstance. template<typename t> CImg<_cimg_Tt> get_mul(const CImg<t>& img) const { return CImg<_cimg_Tt>(*this,false).mul(img); } //! In-place pointwise division. /** Similar to mul(const CImg<t>&), except that it performs a pointwise division instead of a multiplication. **/ template<typename t> CImg<T>& div(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return div(+img); T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)(*ptrd / *(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)(*ptrd / *(ptrs++)); } return *this; } //! In-place pointwise division \newinstance. template<typename t> CImg<_cimg_Tt> get_div(const CImg<t>& img) const { return CImg<_cimg_Tt>(*this,false).div(img); } //! Raise each pixel value to a specified power. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its power \f$I_{(x,y,z,c)}^p\f$. \param p Exponent value. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. \par Example \code const CImg<float> img0("reference.jpg"), // Load reference color image img1 = (img0/255).pow(1.8)*=255, // Compute gamma correction, with gamma = 1.8 img2 = (img0/255).pow(0.5)*=255; // Compute gamma correction, with gamma = 0.5 (img0,img1,img2).display(); \endcode **/ CImg<T>& pow(const double p) { if (is_empty()) return *this; if (p==-4) { cimg_openmp_for(*this,1/(Tfloat)cimg::pow4(*ptr),32768); return *this; } if (p==-3) { cimg_openmp_for(*this,1/(Tfloat)cimg::pow3(*ptr),32768); return *this; } if (p==-2) { cimg_openmp_for(*this,1/(Tfloat)cimg::sqr(*ptr),32768); return *this; } if (p==-1) { cimg_openmp_for(*this,1/(Tfloat)*ptr,32768); return *this; } if (p==-0.5) { cimg_openmp_for(*this,1/std::sqrt((Tfloat)*ptr),8192); return *this; } if (p==0) return fill((T)1); if (p==0.5) return sqrt(); if (p==1) return *this; if (p==2) return sqr(); if (p==3) { cimg_openmp_for(*this,cimg::pow3(*ptr),262144); return *this; } if (p==4) { cimg_openmp_for(*this,cimg::pow4(*ptr),131072); return *this; } cimg_openmp_for(*this,std::pow((Tfloat)*ptr,(Tfloat)p),1024); return *this; } //! Raise each pixel value to a specified power \newinstance. CImg<Tfloat> get_pow(const double p) const { return CImg<Tfloat>(*this,false).pow(p); } //! Raise each pixel value to a power, specified from an expression. /** Similar to operator+=(const char*), except it performs a pointwise exponentiation instead of an addition. **/ CImg<T>& pow(const char *const expression) { return pow((+*this)._fill(expression,true,1,0,0,"pow",this)); } //! Raise each pixel value to a power, specified from an expression \newinstance. CImg<Tfloat> get_pow(const char *const expression) const { return CImg<Tfloat>(*this,false).pow(expression); } //! Raise each pixel value to a power, pointwisely specified from another image. /** Similar to operator+=(const CImg<t>& img), except that it performs an exponentiation instead of an addition. **/ template<typename t> CImg<T>& pow(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return pow(+img); T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)std::pow((double)*ptrd,(double)(*(ptrs++))); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)std::pow((double)*ptrd,(double)(*(ptrs++))); } return *this; } //! Raise each pixel value to a power, pointwisely specified from another image \newinstance. template<typename t> CImg<Tfloat> get_pow(const CImg<t>& img) const { return CImg<Tfloat>(*this,false).pow(img); } //! Compute the bitwise left rotation of each pixel value. /** Similar to operator<<=(unsigned int), except that it performs a left rotation instead of a left shift. **/ CImg<T>& rol(const unsigned int n=1) { if (is_empty()) return *this; cimg_openmp_for(*this,cimg::rol(*ptr,n),32768); return *this; } //! Compute the bitwise left rotation of each pixel value \newinstance. CImg<T> get_rol(const unsigned int n=1) const { return (+*this).rol(n); } //! Compute the bitwise left rotation of each pixel value. /** Similar to operator<<=(const char*), except that it performs a left rotation instead of a left shift. **/ CImg<T>& rol(const char *const expression) { return rol((+*this)._fill(expression,true,1,0,0,"rol",this)); } //! Compute the bitwise left rotation of each pixel value \newinstance. CImg<T> get_rol(const char *const expression) const { return (+*this).rol(expression); } //! Compute the bitwise left rotation of each pixel value. /** Similar to operator<<=(const CImg<t>&), except that it performs a left rotation instead of a left shift. **/ template<typename t> CImg<T>& rol(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return rol(+img); T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)cimg::rol(*ptrd,(unsigned int)(*(ptrs++))); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)cimg::rol(*ptrd,(unsigned int)(*(ptrs++))); } return *this; } //! Compute the bitwise left rotation of each pixel value \newinstance. template<typename t> CImg<T> get_rol(const CImg<t>& img) const { return (+*this).rol(img); } //! Compute the bitwise right rotation of each pixel value. /** Similar to operator>>=(unsigned int), except that it performs a right rotation instead of a right shift. **/ CImg<T>& ror(const unsigned int n=1) { if (is_empty()) return *this; cimg_openmp_for(*this,cimg::ror(*ptr,n),32768); return *this; } //! Compute the bitwise right rotation of each pixel value \newinstance. CImg<T> get_ror(const unsigned int n=1) const { return (+*this).ror(n); } //! Compute the bitwise right rotation of each pixel value. /** Similar to operator>>=(const char*), except that it performs a right rotation instead of a right shift. **/ CImg<T>& ror(const char *const expression) { return ror((+*this)._fill(expression,true,1,0,0,"ror",this)); } //! Compute the bitwise right rotation of each pixel value \newinstance. CImg<T> get_ror(const char *const expression) const { return (+*this).ror(expression); } //! Compute the bitwise right rotation of each pixel value. /** Similar to operator>>=(const CImg<t>&), except that it performs a right rotation instead of a right shift. **/ template<typename t> CImg<T>& ror(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return ror(+img); T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)cimg::ror(*ptrd,(unsigned int)(*(ptrs++))); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)cimg::ror(*ptrd,(unsigned int)(*(ptrs++))); } return *this; } //! Compute the bitwise right rotation of each pixel value \newinstance. template<typename t> CImg<T> get_ror(const CImg<t>& img) const { return (+*this).ror(img); } //! Pointwise min operator between instance image and a value. /** \param val Value used as the reference argument of the min operator. \note Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by \f$\mathrm{min}(I_{(x,y,z,c)},\mathrm{val})\f$. **/ CImg<T>& min(const T& value) { if (is_empty()) return *this; cimg_openmp_for(*this,std::min(*ptr,value),65536); return *this; } //! Pointwise min operator between instance image and a value \newinstance. CImg<T> get_min(const T& value) const { return (+*this).min(value); } //! Pointwise min operator between two images. /** \param img Image used as the reference argument of the min operator. \note Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by \f$\mathrm{min}(I_{(x,y,z,c)},\mathrm{img}_{(x,y,z,c)})\f$. **/ template<typename t> CImg<T>& min(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return min(+img); T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = std::min((T)*(ptrs++),*ptrd); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = std::min((T)*(ptrs++),*ptrd); } return *this; } //! Pointwise min operator between two images \newinstance. template<typename t> CImg<_cimg_Tt> get_min(const CImg<t>& img) const { return CImg<_cimg_Tt>(*this,false).min(img); } //! Pointwise min operator between an image and an expression. /** \param expression Math formula as a C-string. \note Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by \f$\mathrm{min}(I_{(x,y,z,c)},\mathrm{expr}_{(x,y,z,c)})\f$. **/ CImg<T>& min(const char *const expression) { return min((+*this)._fill(expression,true,1,0,0,"min",this)); } //! Pointwise min operator between an image and an expression \newinstance. CImg<Tfloat> get_min(const char *const expression) const { return CImg<Tfloat>(*this,false).min(expression); } //! Pointwise max operator between instance image and a value. /** \param val Value used as the reference argument of the max operator. \note Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by \f$\mathrm{max}(I_{(x,y,z,c)},\mathrm{val})\f$. **/ CImg<T>& max(const T& value) { if (is_empty()) return *this; cimg_openmp_for(*this,std::max(*ptr,value),65536); return *this; } //! Pointwise max operator between instance image and a value \newinstance. CImg<T> get_max(const T& value) const { return (+*this).max(value); } //! Pointwise max operator between two images. /** \param img Image used as the reference argument of the max operator. \note Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by \f$\mathrm{max}(I_{(x,y,z,c)},\mathrm{img}_{(x,y,z,c)})\f$. **/ template<typename t> CImg<T>& max(const CImg<t>& img) { const ulongT siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return max(+img); T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (ulongT n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = std::max((T)*(ptrs++),*ptrd); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = std::max((T)*(ptrs++),*ptrd); } return *this; } //! Pointwise max operator between two images \newinstance. template<typename t> CImg<_cimg_Tt> get_max(const CImg<t>& img) const { return CImg<_cimg_Tt>(*this,false).max(img); } //! Pointwise max operator between an image and an expression. /** \param expression Math formula as a C-string. \note Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by \f$\mathrm{max}(I_{(x,y,z,c)},\mathrm{expr}_{(x,y,z,c)})\f$. **/ CImg<T>& max(const char *const expression) { return max((+*this)._fill(expression,true,1,0,0,"max",this)); } //! Pointwise max operator between an image and an expression \newinstance. CImg<Tfloat> get_max(const char *const expression) const { return CImg<Tfloat>(*this,false).max(expression); } //! Return a reference to the minimum pixel value. /** **/ T& min() { if (is_empty()) throw CImgInstanceException(_cimg_instance "min(): Empty instance.", cimg_instance); T *ptr_min = _data; T min_value = *ptr_min; cimg_for(*this,ptrs,T) if (*ptrs<min_value) min_value = *(ptr_min=ptrs); return *ptr_min; } //! Return a reference to the minimum pixel value \const. const T& min() const { if (is_empty()) throw CImgInstanceException(_cimg_instance "min(): Empty instance.", cimg_instance); const T *ptr_min = _data; T min_value = *ptr_min; cimg_for(*this,ptrs,T) if (*ptrs<min_value) min_value = *(ptr_min=ptrs); return *ptr_min; } //! Return a reference to the maximum pixel value. /** **/ T& max() { if (is_empty()) throw CImgInstanceException(_cimg_instance "max(): Empty instance.", cimg_instance); T *ptr_max = _data; T max_value = *ptr_max; cimg_for(*this,ptrs,T) if (*ptrs>max_value) max_value = *(ptr_max=ptrs); return *ptr_max; } //! Return a reference to the maximum pixel value \const. const T& max() const { if (is_empty()) throw CImgInstanceException(_cimg_instance "max(): Empty instance.", cimg_instance); const T *ptr_max = _data; T max_value = *ptr_max; cimg_for(*this,ptrs,T) if (*ptrs>max_value) max_value = *(ptr_max=ptrs); return *ptr_max; } //! Return a reference to the minimum pixel value as well as the maximum pixel value. /** \param[out] max_val Maximum pixel value. **/ template<typename t> T& min_max(t& max_val) { if (is_empty()) throw CImgInstanceException(_cimg_instance "min_max(): Empty instance.", cimg_instance); T *ptr_min = _data; T min_value = *ptr_min, max_value = min_value; cimg_for(*this,ptrs,T) { const T val = *ptrs; if (val<min_value) { min_value = val; ptr_min = ptrs; } if (val>max_value) max_value = val; } max_val = (t)max_value; return *ptr_min; } //! Return a reference to the minimum pixel value as well as the maximum pixel value \const. template<typename t> const T& min_max(t& max_val) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "min_max(): Empty instance.", cimg_instance); const T *ptr_min = _data; T min_value = *ptr_min, max_value = min_value; cimg_for(*this,ptrs,T) { const T val = *ptrs; if (val<min_value) { min_value = val; ptr_min = ptrs; } if (val>max_value) max_value = val; } max_val = (t)max_value; return *ptr_min; } //! Return a reference to the maximum pixel value as well as the minimum pixel value. /** \param[out] min_val Minimum pixel value. **/ template<typename t> T& max_min(t& min_val) { if (is_empty()) throw CImgInstanceException(_cimg_instance "max_min(): Empty instance.", cimg_instance); T *ptr_max = _data; T max_value = *ptr_max, min_value = max_value; cimg_for(*this,ptrs,T) { const T val = *ptrs; if (val>max_value) { max_value = val; ptr_max = ptrs; } if (val<min_value) min_value = val; } min_val = (t)min_value; return *ptr_max; } //! Return a reference to the maximum pixel value as well as the minimum pixel value \const. template<typename t> const T& max_min(t& min_val) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "max_min(): Empty instance.", cimg_instance); const T *ptr_max = _data; T max_value = *ptr_max, min_value = max_value; cimg_for(*this,ptrs,T) { const T val = *ptrs; if (val>max_value) { max_value = val; ptr_max = ptrs; } if (val<min_value) min_value = val; } min_val = (t)min_value; return *ptr_max; } //! Return the kth smallest pixel value. /** \param k Rank of the search smallest element. **/ T kth_smallest(const ulongT k) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "kth_smallest(): Empty instance.", cimg_instance); CImg<T> arr(*this,false); ulongT l = 0, ir = size() - 1; for ( ; ; ) { if (ir<=l + 1) { if (ir==l + 1 && arr[ir]<arr[l]) cimg::swap(arr[l],arr[ir]); return arr[k]; } else { const ulongT mid = (l + ir)>>1; cimg::swap(arr[mid],arr[l + 1]); if (arr[l]>arr[ir]) cimg::swap(arr[l],arr[ir]); if (arr[l + 1]>arr[ir]) cimg::swap(arr[l + 1],arr[ir]); if (arr[l]>arr[l + 1]) cimg::swap(arr[l],arr[l + 1]); ulongT i = l + 1, j = ir; const T pivot = arr[l + 1]; for ( ; ; ) { do ++i; while (arr[i]<pivot); do --j; while (arr[j]>pivot); if (j<i) break; cimg::swap(arr[i],arr[j]); } arr[l + 1] = arr[j]; arr[j] = pivot; if (j>=k) ir = j - 1; if (j<=k) l = i; } } } //! Return the median pixel value. /** **/ T median() const { if (is_empty()) throw CImgInstanceException(_cimg_instance "median(): Empty instance.", cimg_instance); const ulongT s = size(); switch (s) { case 1 : return _data[0]; case 2 : return cimg::median(_data[0],_data[1]); case 3 : return cimg::median(_data[0],_data[1],_data[2]); case 5 : return cimg::median(_data[0],_data[1],_data[2],_data[3],_data[4]); case 7 : return cimg::median(_data[0],_data[1],_data[2],_data[3],_data[4],_data[5],_data[6]); case 9 : return cimg::median(_data[0],_data[1],_data[2],_data[3],_data[4],_data[5],_data[6],_data[7],_data[8]); case 13 : return cimg::median(_data[0],_data[1],_data[2],_data[3],_data[4],_data[5],_data[6],_data[7],_data[8], _data[9],_data[10],_data[11],_data[12]); } const T res = kth_smallest(s>>1); return (s%2)?res:(T)((res + kth_smallest((s>>1) - 1))/2); } //! Return the product of all the pixel values. /** **/ double product() const { if (is_empty()) return 0; double res = 1; cimg_for(*this,ptrs,T) res*=(double)*ptrs; return res; } //! Return the sum of all the pixel values. /** **/ double sum() const { double res = 0; cimg_for(*this,ptrs,T) res+=(double)*ptrs; return res; } //! Return the average pixel value. /** **/ double mean() const { double res = 0; cimg_for(*this,ptrs,T) res+=(double)*ptrs; return res/size(); } //! Return the variance of the pixel values. /** \param variance_method Method used to estimate the variance. Can be: - \c 0: Second moment, computed as \f$1/N \sum\limits_{k=1}^{N} (x_k - \bar x)^2 = 1/N \left( \sum\limits_{k=1}^N x_k^2 - \left( \sum\limits_{k=1}^N x_k \right)^2 / N \right)\f$ with \f$ \bar x = 1/N \sum\limits_{k=1}^N x_k \f$. - \c 1: Best unbiased estimator, computed as \f$\frac{1}{N - 1} \sum\limits_{k=1}^{N} (x_k - \bar x)^2 \f$. - \c 2: Least median of squares. - \c 3: Least trimmed of squares. **/ double variance(const unsigned int variance_method=1) const { double foo; return variance_mean(variance_method,foo); } //! Return the variance as well as the average of the pixel values. /** \param variance_method Method used to estimate the variance (see variance(const unsigned int) const). \param[out] mean Average pixel value. **/ template<typename t> double variance_mean(const unsigned int variance_method, t& mean) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "variance_mean(): Empty instance.", cimg_instance); double variance = 0, average = 0; const ulongT siz = size(); switch (variance_method) { case 0 : { // Least mean square (standard definition) double S = 0, S2 = 0; cimg_for(*this,ptrs,T) { const double val = (double)*ptrs; S+=val; S2+=val*val; } variance = (S2 - S*S/siz)/siz; average = S; } break; case 1 : { // Least mean square (robust definition) double S = 0, S2 = 0; cimg_for(*this,ptrs,T) { const double val = (double)*ptrs; S+=val; S2+=val*val; } variance = siz>1?(S2 - S*S/siz)/(siz - 1):0; average = S; } break; case 2 : { // Least Median of Squares (MAD) CImg<Tfloat> buf(*this,false); buf.sort(); const ulongT siz2 = siz>>1; const double med_i = (double)buf[siz2]; cimg_for(buf,ptrs,Tfloat) { const double val = (double)*ptrs; *ptrs = (Tfloat)cimg::abs(val - med_i); average+=val; } buf.sort(); const double sig = (double)(1.4828*buf[siz2]); variance = sig*sig; } break; default : { // Least trimmed of Squares CImg<Tfloat> buf(*this,false); const ulongT siz2 = siz>>1; cimg_for(buf,ptrs,Tfloat) { const double val = (double)*ptrs; (*ptrs)=(Tfloat)((*ptrs)*val); average+=val; } buf.sort(); double a = 0; const Tfloat *ptrs = buf._data; for (ulongT j = 0; j<siz2; ++j) a+=(double)*(ptrs++); const double sig = (double)(2.6477*std::sqrt(a/siz2)); variance = sig*sig; } } mean = (t)(average/siz); return variance>0?variance:0; } //! Return estimated variance of the noise. /** \param variance_method Method used to compute the variance (see variance(const unsigned int) const). \note Because of structures such as edges in images it is recommanded to use a robust variance estimation. The variance of the noise is estimated by computing the variance of the Laplacian \f$(\Delta I)^2 \f$ scaled by a factor \f$c\f$ insuring \f$ c E[(\Delta I)^2]= \sigma^2\f$ where \f$\sigma\f$ is the noise variance. **/ double variance_noise(const unsigned int variance_method=2) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "variance_noise(): Empty instance.", cimg_instance); const ulongT siz = size(); if (!siz || !_data) return 0; if (variance_method>1) { // Compute a scaled version of the Laplacian CImg<Tdouble> tmp(*this,false); if (_depth==1) { const double cste = 1./std::sqrt(20.); // Depends on how the Laplacian is computed cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height>=(cimg_openmp_sizefactor)*262144 && _spectrum>=2)) cimg_forC(*this,c) { CImg_3x3(I,T); cimg_for3x3(*this,x,y,0,c,I,T) { tmp(x,y,c) = cste*((double)Inc + (double)Ipc + (double)Icn + (double)Icp - 4*(double)Icc); } } } else { const double cste = 1./std::sqrt(42.); // Depends on how the Laplacian is computed cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height*_depth>=(cimg_openmp_sizefactor)*262144 && _spectrum>=2)) cimg_forC(*this,c) { CImg_3x3x3(I,T); cimg_for3x3x3(*this,x,y,z,c,I,T) { tmp(x,y,z,c) = cste*( (double)Incc + (double)Ipcc + (double)Icnc + (double)Icpc + (double)Iccn + (double)Iccp - 6*(double)Iccc); } } } return tmp.variance(variance_method); } // Version that doesn't need intermediate images. double variance = 0, S = 0, S2 = 0; if (_depth==1) { const double cste = 1./std::sqrt(20.); CImg_3x3(I,T); cimg_forC(*this,c) cimg_for3x3(*this,x,y,0,c,I,T) { const double val = cste*((double)Inc + (double)Ipc + (double)Icn + (double)Icp - 4*(double)Icc); S+=val; S2+=val*val; } } else { const double cste = 1./std::sqrt(42.); CImg_3x3x3(I,T); cimg_forC(*this,c) cimg_for3x3x3(*this,x,y,z,c,I,T) { const double val = cste * ((double)Incc + (double)Ipcc + (double)Icnc + (double)Icpc + (double)Iccn + (double)Iccp - 6*(double)Iccc); S+=val; S2+=val*val; } } if (variance_method) variance = siz>1?(S2 - S*S/siz)/(siz - 1):0; else variance = (S2 - S*S/siz)/siz; return variance>0?variance:0; } //! Compute the MSE (Mean-Squared Error) between two images. /** \param img Image used as the second argument of the MSE operator. **/ template<typename t> double MSE(const CImg<t>& img) const { if (img.size()!=size()) throw CImgArgumentException(_cimg_instance "MSE(): Instance and specified image (%u,%u,%u,%u,%p) have different dimensions.", cimg_instance, img._width,img._height,img._depth,img._spectrum,img._data); double vMSE = 0; const t* ptr2 = img._data; cimg_for(*this,ptr1,T) { const double diff = (double)*ptr1 - (double)*(ptr2++); vMSE+=diff*diff; } const ulongT siz = img.size(); if (siz) vMSE/=siz; return vMSE; } //! Compute the PSNR (Peak Signal-to-Noise Ratio) between two images. /** \param img Image used as the second argument of the PSNR operator. \param max_value Maximum theoretical value of the signal. **/ template<typename t> double PSNR(const CImg<t>& img, const double max_value=255) const { const double vMSE = (double)std::sqrt(MSE(img)); return (vMSE!=0)?(double)(20*std::log10(max_value/vMSE)):(double)(cimg::type<double>::max()); } //! Evaluate math formula. /** \param expression Math formula, as a C-string. \param x Value of the pre-defined variable \c x. \param y Value of the pre-defined variable \c y. \param z Value of the pre-defined variable \c z. \param c Value of the pre-defined variable \c c. \param list_inputs A list of input images attached to the specified math formula. \param[out] list_outputs A pointer to a list of output images attached to the specified math formula. **/ double eval(const char *const expression, const double x=0, const double y=0, const double z=0, const double c=0, const CImgList<T> *const list_inputs=0, CImgList<T> *const list_outputs=0) { return _eval(this,expression,x,y,z,c,list_inputs,list_outputs); } //! Evaluate math formula \const. double eval(const char *const expression, const double x=0, const double y=0, const double z=0, const double c=0, const CImgList<T> *const list_inputs=0, CImgList<T> *const list_outputs=0) const { return _eval(0,expression,x,y,z,c,list_inputs,list_outputs); } double _eval(CImg<T> *const img_output, const char *const expression, const double x, const double y, const double z, const double c, const CImgList<T> *const list_inputs, CImgList<T> *const list_outputs) const { if (!expression || !*expression) return 0; if (!expression[1]) switch (*expression) { // Single-char optimization case 'w' : return (double)_width; case 'h' : return (double)_height; case 'd' : return (double)_depth; case 's' : return (double)_spectrum; case 'r' : return (double)_is_shared; } _cimg_math_parser mp(expression + (*expression=='>' || *expression=='<' || *expression=='*' || *expression==':'),"eval", *this,img_output,list_inputs,list_outputs,false); const double val = mp(x,y,z,c); mp.end(); return val; } //! Evaluate math formula. /** \param[out] output Contains values of output vector returned by the evaluated expression (or is empty if the returned type is scalar). \param expression Math formula, as a C-string. \param x Value of the pre-defined variable \c x. \param y Value of the pre-defined variable \c y. \param z Value of the pre-defined variable \c z. \param c Value of the pre-defined variable \c c. \param list_inputs A list of input images attached to the specified math formula. \param[out] list_outputs A pointer to a list of output images attached to the specified math formula. **/ template<typename t> void eval(CImg<t> &output, const char *const expression, const double x=0, const double y=0, const double z=0, const double c=0, const CImgList<T> *const list_inputs=0, CImgList<T> *const list_outputs=0) { _eval(output,this,expression,x,y,z,c,list_inputs,list_outputs); } //! Evaluate math formula \const. template<typename t> void eval(CImg<t>& output, const char *const expression, const double x=0, const double y=0, const double z=0, const double c=0, const CImgList<T> *const list_inputs=0, CImgList<T> *const list_outputs=0) const { _eval(output,0,expression,x,y,z,c,list_inputs,list_outputs); } template<typename t> void _eval(CImg<t>& output, CImg<T> *const img_output, const char *const expression, const double x, const double y, const double z, const double c, const CImgList<T> *const list_inputs, CImgList<T> *const list_outputs) const { if (!expression || !*expression) { output.assign(1); *output = 0; } if (!expression[1]) switch (*expression) { // Single-char optimization case 'w' : output.assign(1); *output = (t)_width; break; case 'h' : output.assign(1); *output = (t)_height; break; case 'd' : output.assign(1); *output = (t)_depth; break; case 's' : output.assign(1); *output = (t)_spectrum; break; case 'r' : output.assign(1); *output = (t)_is_shared; break; } _cimg_math_parser mp(expression + (*expression=='>' || *expression=='<' || *expression=='*' || *expression==':'),"eval", *this,img_output,list_inputs,list_outputs,false); output.assign(1,std::max(1U,mp.result_dim)); mp(x,y,z,c,output._data); mp.end(); } //! Evaluate math formula on a set of variables. /** \param expression Math formula, as a C-string. \param xyzc Set of values (x,y,z,c) used for the evaluation. \param list_inputs A list of input images attached to the specified math formula. \param[out] list_outputs A pointer to a list of output images attached to the specified math formula. **/ template<typename t> CImg<doubleT> eval(const char *const expression, const CImg<t>& xyzc, const CImgList<T> *const list_inputs=0, CImgList<T> *const list_outputs=0) { return _eval(this,expression,xyzc,list_inputs,list_outputs); } //! Evaluate math formula on a set of variables \const. template<typename t> CImg<doubleT> eval(const char *const expression, const CImg<t>& xyzc, const CImgList<T> *const list_inputs=0, CImgList<T> *const list_outputs=0) const { return _eval(0,expression,xyzc,list_inputs,list_outputs); } template<typename t> CImg<doubleT> _eval(CImg<T> *const output, const char *const expression, const CImg<t>& xyzc, const CImgList<T> *const list_inputs=0, CImgList<T> *const list_outputs=0) const { CImg<doubleT> res(1,xyzc.size()/4); if (!expression || !*expression) return res.fill(0); _cimg_math_parser mp(expression,"eval",*this,output,list_inputs,list_outputs,false); #if cimg_use_openmp!=0 cimg_pragma_openmp(parallel if (res._height>=512)) { _cimg_math_parser _mp = omp_get_thread_num()?mp:_cimg_math_parser(), &lmp = omp_get_thread_num()?_mp:mp; cimg_pragma_openmp(for) for (int i = 0; i<res.height(); ++i) { const unsigned int i4 = 4*i; const double x = (double)xyzc[i4], y = (double)xyzc[i4 + 1], z = (double)xyzc[i4 + 2], c = (double)xyzc[i4 + 3]; res[i] = lmp(x,y,z,c); } } #else const t *ps = xyzc._data; cimg_for(res,pd,double) { const double x = (double)*(ps++), y = (double)*(ps++), z = (double)*(ps++), c = (double)*(ps++); *pd = mp(x,y,z,c); } #endif mp.end(); return res; } //! Compute statistics vector from the pixel values. /* \param variance_method Method used to compute the variance (see variance(const unsigned int) const). \return Statistics vector as <tt>[min, max, mean, variance, xmin, ymin, zmin, cmin, xmax, ymax, zmax, cmax, sum, product]</tt>. **/ CImg<Tdouble> get_stats(const unsigned int variance_method=1) const { if (is_empty()) return CImg<doubleT>(); const ulongT siz = size(); const longT off_end = (longT)siz; double S = 0, S2 = 0, P = 1; longT offm = 0, offM = 0; T m = *_data, M = m; cimg_pragma_openmp(parallel reduction(+:S,S2) reduction(*:P) cimg_openmp_if_size(siz,131072)) { longT loffm = 0, loffM = 0; T lm = *_data, lM = lm; cimg_pragma_openmp(for) for (longT off = 0; off<off_end; ++off) { const T val = _data[off]; const double _val = (double)val; if (val<lm) { lm = val; loffm = off; } if (val>lM) { lM = val; loffM = off; } S+=_val; S2+=_val*_val; P*=_val; } cimg_pragma_openmp(critical(get_stats)) { if (lm<m || (lm==m && loffm<offm)) { m = lm; offm = loffm; } if (lM>M || (lM==M && loffM<offM)) { M = lM; offM = loffM; } } } const double mean_value = S/siz, _variance_value = variance_method==0?(S2 - S*S/siz)/siz: (variance_method==1?(siz>1?(S2 - S*S/siz)/(siz - 1):0): variance(variance_method)), variance_value = _variance_value>0?_variance_value:0; int xm = 0, ym = 0, zm = 0, cm = 0, xM = 0, yM = 0, zM = 0, cM = 0; contains(_data[offm],xm,ym,zm,cm); contains(_data[offM],xM,yM,zM,cM); return CImg<Tdouble>(1,14).fill((double)m,(double)M,mean_value,variance_value, (double)xm,(double)ym,(double)zm,(double)cm, (double)xM,(double)yM,(double)zM,(double)cM, S,P); } //! Compute statistics vector from the pixel values \inplace. CImg<T>& stats(const unsigned int variance_method=1) { return get_stats(variance_method).move_to(*this); } //@} //------------------------------------- // //! \name Vector / Matrix Operations //@{ //------------------------------------- //! Compute norm of the image, viewed as a matrix. /** \param magnitude_type Norm type. Can be: - \c -1: Linf-norm - \c 0: L0-norm - \c 1: L1-norm - \c 2: L2-norm **/ double magnitude(const int magnitude_type=2) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "magnitude(): Empty instance.", cimg_instance); double res = 0; switch (magnitude_type) { case -1 : { cimg_for(*this,ptrs,T) { const double val = (double)cimg::abs(*ptrs); if (val>res) res = val; } } break; case 1 : { cimg_for(*this,ptrs,T) res+=(double)cimg::abs(*ptrs); } break; default : { cimg_for(*this,ptrs,T) res+=(double)cimg::sqr(*ptrs); res = (double)std::sqrt(res); } } return res; } //! Compute the trace of the image, viewed as a matrix. /** **/ double trace() const { if (is_empty()) throw CImgInstanceException(_cimg_instance "trace(): Empty instance.", cimg_instance); double res = 0; cimg_forX(*this,k) res+=(double)(*this)(k,k); return res; } //! Compute the determinant of the image, viewed as a matrix. /** **/ double det() const { if (is_empty() || _width!=_height || _depth!=1 || _spectrum!=1) throw CImgInstanceException(_cimg_instance "det(): Instance is not a square matrix.", cimg_instance); switch (_width) { case 1 : return (double)((*this)(0,0)); case 2 : return (double)((*this)(0,0))*(double)((*this)(1,1)) - (double)((*this)(0,1))*(double)((*this)(1,0)); case 3 : { const double a = (double)_data[0], d = (double)_data[1], g = (double)_data[2], b = (double)_data[3], e = (double)_data[4], h = (double)_data[5], c = (double)_data[6], f = (double)_data[7], i = (double)_data[8]; return i*a*e - a*h*f - i*b*d + b*g*f + c*d*h - c*g*e; } default : { CImg<Tfloat> lu(*this,false); CImg<uintT> indx; bool d; lu._LU(indx,d); double res = d?(double)1:(double)-1; cimg_forX(lu,i) res*=lu(i,i); return res; } } } //! Compute the dot product between instance and argument, viewed as matrices. /** \param img Image used as a second argument of the dot product. **/ template<typename t> double dot(const CImg<t>& img) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "dot(): Empty instance.", cimg_instance); if (!img) throw CImgArgumentException(_cimg_instance "dot(): Empty specified image.", cimg_instance); const ulongT nb = std::min(size(),img.size()); double res = 0; for (ulongT off = 0; off<nb; ++off) res+=(double)_data[off]*(double)img[off]; return res; } //! Get vector-valued pixel located at specified position. /** \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. **/ CImg<T> get_vector_at(const unsigned int x, const unsigned int y=0, const unsigned int z=0) const { CImg<T> res; if (res._height!=_spectrum) res.assign(1,_spectrum); const ulongT whd = (ulongT)_width*_height*_depth; const T *ptrs = data(x,y,z); T *ptrd = res._data; cimg_forC(*this,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return res; } //! Get (square) matrix-valued pixel located at specified position. /** \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \note - The spectrum() of the image must be a square. **/ CImg<T> get_matrix_at(const unsigned int x=0, const unsigned int y=0, const unsigned int z=0) const { const int n = (int)cimg::round(std::sqrt((double)_spectrum)); const T *ptrs = data(x,y,z,0); const ulongT whd = (ulongT)_width*_height*_depth; CImg<T> res(n,n); T *ptrd = res._data; cimg_forC(*this,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return res; } //! Get tensor-valued pixel located at specified position. /** \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. **/ CImg<T> get_tensor_at(const unsigned int x, const unsigned int y=0, const unsigned int z=0) const { const T *ptrs = data(x,y,z,0); const ulongT whd = (ulongT)_width*_height*_depth; if (_spectrum==6) return tensor(*ptrs,*(ptrs + whd),*(ptrs + 2*whd),*(ptrs + 3*whd),*(ptrs + 4*whd),*(ptrs + 5*whd)); if (_spectrum==3) return tensor(*ptrs,*(ptrs + whd),*(ptrs + 2*whd)); return tensor(*ptrs); } //! Set vector-valued pixel at specified position. /** \param vec Vector to put on the instance image. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. **/ template<typename t> CImg<T>& set_vector_at(const CImg<t>& vec, const unsigned int x, const unsigned int y=0, const unsigned int z=0) { if (x<_width && y<_height && z<_depth) { const t *ptrs = vec._data; const ulongT whd = (ulongT)_width*_height*_depth; T *ptrd = data(x,y,z); for (unsigned int k = std::min((unsigned int)vec.size(),_spectrum); k; --k) { *ptrd = (T)*(ptrs++); ptrd+=whd; } } return *this; } //! Set (square) matrix-valued pixel at specified position. /** \param mat Matrix to put on the instance image. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. **/ template<typename t> CImg<T>& set_matrix_at(const CImg<t>& mat, const unsigned int x=0, const unsigned int y=0, const unsigned int z=0) { return set_vector_at(mat,x,y,z); } //! Set tensor-valued pixel at specified position. /** \param ten Tensor to put on the instance image. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. **/ template<typename t> CImg<T>& set_tensor_at(const CImg<t>& ten, const unsigned int x=0, const unsigned int y=0, const unsigned int z=0) { T *ptrd = data(x,y,z,0); const ulongT siz = (ulongT)_width*_height*_depth; if (ten._height==2) { *ptrd = (T)ten[0]; ptrd+=siz; *ptrd = (T)ten[1]; ptrd+=siz; *ptrd = (T)ten[3]; } else { *ptrd = (T)ten[0]; ptrd+=siz; *ptrd = (T)ten[1]; ptrd+=siz; *ptrd = (T)ten[2]; ptrd+=siz; *ptrd = (T)ten[4]; ptrd+=siz; *ptrd = (T)ten[5]; ptrd+=siz; *ptrd = (T)ten[8]; } return *this; } //! Unroll pixel values along axis \c y. /** \note Equivalent to \code unroll('y'); \endcode. **/ CImg<T>& vector() { return unroll('y'); } //! Unroll pixel values along axis \c y \newinstance. CImg<T> get_vector() const { return get_unroll('y'); } //! Resize image to become a scalar square matrix. /** **/ CImg<T>& matrix() { const ulongT siz = size(); switch (siz) { case 1 : break; case 4 : _width = _height = 2; break; case 9 : _width = _height = 3; break; case 16 : _width = _height = 4; break; case 25 : _width = _height = 5; break; case 36 : _width = _height = 6; break; case 49 : _width = _height = 7; break; case 64 : _width = _height = 8; break; case 81 : _width = _height = 9; break; case 100 : _width = _height = 10; break; default : { ulongT i = 11, i2 = i*i; while (i2<siz) { i2+=2*i + 1; ++i; } if (i2==siz) _width = _height = i; else throw CImgInstanceException(_cimg_instance "matrix(): Invalid instance size %u (should be a square integer).", cimg_instance, siz); } } return *this; } //! Resize image to become a scalar square matrix \newinstance. CImg<T> get_matrix() const { return (+*this).matrix(); } //! Resize image to become a symmetric tensor. /** **/ CImg<T>& tensor() { return get_tensor().move_to(*this); } //! Resize image to become a symmetric tensor \newinstance. CImg<T> get_tensor() const { CImg<T> res; const ulongT siz = size(); switch (siz) { case 1 : break; case 3 : res.assign(2,2); res(0,0) = (*this)(0); res(1,0) = res(0,1) = (*this)(1); res(1,1) = (*this)(2); break; case 6 : res.assign(3,3); res(0,0) = (*this)(0); res(1,0) = res(0,1) = (*this)(1); res(2,0) = res(0,2) = (*this)(2); res(1,1) = (*this)(3); res(2,1) = res(1,2) = (*this)(4); res(2,2) = (*this)(5); break; default : throw CImgInstanceException(_cimg_instance "tensor(): Invalid instance size (does not define a 1x1, 2x2 or 3x3 tensor).", cimg_instance); } return res; } //! Resize image to become a diagonal matrix. /** \note Transform the image as a diagonal matrix so that each of its initial value becomes a diagonal coefficient. **/ CImg<T>& diagonal() { return get_diagonal().move_to(*this); } //! Resize image to become a diagonal matrix \newinstance. CImg<T> get_diagonal() const { if (is_empty()) return *this; const unsigned int siz = (unsigned int)size(); CImg<T> res(siz,siz,1,1,0); cimg_foroff(*this,off) res((unsigned int)off,(unsigned int)off) = (*this)[off]; return res; } //! Replace the image by an identity matrix. /** \note If the instance image is not square, it is resized to a square matrix using its maximum dimension as a reference. **/ CImg<T>& identity_matrix() { return identity_matrix(std::max(_width,_height)).move_to(*this); } //! Replace the image by an identity matrix \newinstance. CImg<T> get_identity_matrix() const { return identity_matrix(std::max(_width,_height)); } //! Fill image with a linear sequence of values. /** \param a0 Starting value of the sequence. \param a1 Ending value of the sequence. **/ CImg<T>& sequence(const T& a0, const T& a1) { if (is_empty()) return *this; const ulongT siz = size() - 1; T* ptr = _data; if (siz) { const double delta = (double)a1 - (double)a0; cimg_foroff(*this,l) *(ptr++) = (T)(a0 + delta*l/siz); } else *ptr = a0; return *this; } //! Fill image with a linear sequence of values \newinstance. CImg<T> get_sequence(const T& a0, const T& a1) const { return (+*this).sequence(a0,a1); } //! Transpose the image, viewed as a matrix. /** \note Equivalent to \code permute_axes("yxzc"); \endcode. **/ CImg<T>& transpose() { if (_width==1) { _width = _height; _height = 1; return *this; } if (_height==1) { _height = _width; _width = 1; return *this; } if (_width==_height) { cimg_forYZC(*this,y,z,c) for (int x = y; x<width(); ++x) cimg::swap((*this)(x,y,z,c),(*this)(y,x,z,c)); return *this; } return get_transpose().move_to(*this); } //! Transpose the image, viewed as a matrix \newinstance. CImg<T> get_transpose() const { return get_permute_axes("yxzc"); } //! Compute the cross product between two \c 1x3 images, viewed as 3D vectors. /** \param img Image used as the second argument of the cross product. \note The first argument of the cross product is \c *this. **/ template<typename t> CImg<T>& cross(const CImg<t>& img) { if (_width!=1 || _height<3 || img._width!=1 || img._height<3) throw CImgInstanceException(_cimg_instance "cross(): Instance and/or specified image (%u,%u,%u,%u,%p) are not 3D vectors.", cimg_instance, img._width,img._height,img._depth,img._spectrum,img._data); const T x = (*this)[0], y = (*this)[1], z = (*this)[2]; (*this)[0] = (T)(y*img[2] - z*img[1]); (*this)[1] = (T)(z*img[0] - x*img[2]); (*this)[2] = (T)(x*img[1] - y*img[0]); return *this; } //! Compute the cross product between two \c 1x3 images, viewed as 3D vectors \newinstance. template<typename t> CImg<_cimg_Tt> get_cross(const CImg<t>& img) const { return CImg<_cimg_Tt>(*this).cross(img); } //! Invert the instance image, viewed as a matrix. /** \param use_LU Choose the inverting algorithm. Can be: - \c true: LU-based matrix inversion. - \c false: SVD-based matrix inversion. **/ CImg<T>& invert(const bool use_LU=true) { if (_width!=_height || _depth!=1 || _spectrum!=1) throw CImgInstanceException(_cimg_instance "invert(): Instance is not a square matrix.", cimg_instance); const double dete = _width>3?-1.:det(); if (dete!=0. && _width==2) { const double a = _data[0], c = _data[1], b = _data[2], d = _data[3]; _data[0] = (T)(d/dete); _data[1] = (T)(-c/dete); _data[2] = (T)(-b/dete); _data[3] = (T)(a/dete); } else if (dete!=0. && _width==3) { const double a = _data[0], d = _data[1], g = _data[2], b = _data[3], e = _data[4], h = _data[5], c = _data[6], f = _data[7], i = _data[8]; _data[0] = (T)((i*e - f*h)/dete), _data[1] = (T)((g*f - i*d)/dete), _data[2] = (T)((d*h - g*e)/dete); _data[3] = (T)((h*c - i*b)/dete), _data[4] = (T)((i*a - c*g)/dete), _data[5] = (T)((g*b - a*h)/dete); _data[6] = (T)((b*f - e*c)/dete), _data[7] = (T)((d*c - a*f)/dete), _data[8] = (T)((a*e - d*b)/dete); } else { #ifdef cimg_use_lapack int INFO = (int)use_LU, N = _width, LWORK = 4*N, *const IPIV = new int[N]; Tfloat *const lapA = new Tfloat[N*N], *const WORK = new Tfloat[LWORK]; cimg_forXY(*this,k,l) lapA[k*N + l] = (Tfloat)((*this)(k,l)); cimg::getrf(N,lapA,IPIV,INFO); if (INFO) cimg::warn(_cimg_instance "invert(): LAPACK function dgetrf_() returned error code %d.", cimg_instance, INFO); else { cimg::getri(N,lapA,IPIV,WORK,LWORK,INFO); if (INFO) cimg::warn(_cimg_instance "invert(): LAPACK function dgetri_() returned error code %d.", cimg_instance, INFO); } if (!INFO) cimg_forXY(*this,k,l) (*this)(k,l) = (T)(lapA[k*N + l]); else fill(0); delete[] IPIV; delete[] lapA; delete[] WORK; #else if (use_LU) { // LU-based inverse computation CImg<Tfloat> A(*this,false), indx, col(1,_width); bool d; A._LU(indx,d); cimg_forX(*this,j) { col.fill(0); col(j) = 1; col._solve(A,indx); cimg_forX(*this,i) (*this)(j,i) = (T)col(i); } } else { // SVD-based inverse computation CImg<Tfloat> U(_width,_width), S(1,_width), V(_width,_width); SVD(U,S,V,false); U.transpose(); cimg_forY(S,k) if (S[k]!=0) S[k]=1/S[k]; S.diagonal(); *this = V*S*U; } #endif } return *this; } //! Invert the instance image, viewed as a matrix \newinstance. CImg<Tfloat> get_invert(const bool use_LU=true) const { return CImg<Tfloat>(*this,false).invert(use_LU); } //! Compute the Moore-Penrose pseudo-inverse of the instance image, viewed as a matrix. /** **/ CImg<T>& pseudoinvert() { return get_pseudoinvert().move_to(*this); } //! Compute the Moore-Penrose pseudo-inverse of the instance image, viewed as a matrix \newinstance. CImg<Tfloat> get_pseudoinvert() const { CImg<Tfloat> U, S, V; SVD(U,S,V); const Tfloat tolerance = (sizeof(Tfloat)<=4?5.96e-8f:1.11e-16f)*std::max(_width,_height)*S.max(); cimg_forX(V,x) { const Tfloat s = S(x), invs = s>tolerance?1/s:0; cimg_forY(V,y) V(x,y)*=invs; } return V*U.transpose(); } //! Solve a system of linear equations. /** \param A Matrix of the linear system. \note Solve \c AX = B where \c B=*this. **/ template<typename t> CImg<T>& solve(const CImg<t>& A) { if (_depth!=1 || _spectrum!=1 || _height!=A._height || A._depth!=1 || A._spectrum!=1) throw CImgArgumentException(_cimg_instance "solve(): Instance and specified matrix (%u,%u,%u,%u,%p) have " "incompatible dimensions.", cimg_instance, A._width,A._height,A._depth,A._spectrum,A._data); typedef _cimg_Ttfloat Ttfloat; if (A.size()==1) return (*this)/=A[0]; if (A._width==2 && A._height==2 && _height==2) { const double a = (double)A[0], b = (double)A[1], c = (double)A[2], d = (double)A[3], fa = std::fabs(a), fb = std::fabs(b), fc = std::fabs(c), fd = std::fabs(d), det = a*d - b*c, fM = cimg::max(fa,fb,fc,fd); if (fM==fa) cimg_forX(*this,k) { const double u = (double)(*this)(k,0), v = (double)(*this)(k,1), y = (a*v - c*u)/det; (*this)(k,0) = (T)((u - b*y)/a); (*this)(k,1) = (T)y; } else if (fM==fc) cimg_forX(*this,k) { const double u = (double)(*this)(k,0), v = (double)(*this)(k,1), y = (a*v - c*u)/det; (*this)(k,0) = (T)((v - d*y)/c); (*this)(k,1) = (T)y; } else if (fM==fb) cimg_forX(*this,k) { const double u = (double)(*this)(k,0), v = (double)(*this)(k,1), x = (d*u - b*v)/det; (*this)(k,0) = (T)x; (*this)(k,1) = (T)((u - a*x)/b); } else cimg_forX(*this,k) { const double u = (double)(*this)(k,0), v = (double)(*this)(k,1), x = (d*u - b*v)/det; (*this)(k,0) = (T)x; (*this)(k,1) = (T)((v - c*x)/d); } return *this; } if (_width!=1) { // Process column-by-column CImg<T> res(_width,A._width); cimg_forX(*this,i) res.draw_image(i,get_column(i).solve(A)); return res.move_to(*this); } if (A._width==A._height) { // Square linear system #ifdef cimg_use_lapack char TRANS = 'N'; int INFO, N = _height, LWORK = 4*N, *const IPIV = new int[N]; Ttfloat *const lapA = new Ttfloat[N*N], *const lapB = new Ttfloat[N], *const WORK = new Ttfloat[LWORK]; cimg_forXY(A,k,l) lapA[k*N + l] = (Ttfloat)(A(k,l)); cimg_forY(*this,i) lapB[i] = (Ttfloat)((*this)(i)); cimg::getrf(N,lapA,IPIV,INFO); if (INFO) cimg::warn(_cimg_instance "solve(): LAPACK library function dgetrf_() returned error code %d.", cimg_instance, INFO); if (!INFO) { cimg::getrs(TRANS,N,lapA,IPIV,lapB,INFO); if (INFO) cimg::warn(_cimg_instance "solve(): LAPACK library function dgetrs_() returned error code %d.", cimg_instance, INFO); } if (!INFO) cimg_forY(*this,i) (*this)(i) = (T)(lapB[i]); else fill(0); delete[] IPIV; delete[] lapA; delete[] lapB; delete[] WORK; #else CImg<Ttfloat> lu(A,false); CImg<Ttfloat> indx; bool d; lu._LU(indx,d); _solve(lu,indx); #endif } else { // Least-square solution for non-square systems #ifdef cimg_use_lapack char TRANS = 'N'; int INFO, N = A._width, M = A._height, LWORK = -1, LDA = M, LDB = M, NRHS = _width; Ttfloat WORK_QUERY; Ttfloat * const lapA = new Ttfloat[M*N], * const lapB = new Ttfloat[M*NRHS]; cimg::sgels(TRANS, M, N, NRHS, lapA, LDA, lapB, LDB, &WORK_QUERY, LWORK, INFO); LWORK = (int) WORK_QUERY; Ttfloat *const WORK = new Ttfloat[LWORK]; cimg_forXY(A,k,l) lapA[k*M + l] = (Ttfloat)(A(k,l)); cimg_forXY(*this,k,l) lapB[k*M + l] = (Ttfloat)((*this)(k,l)); cimg::sgels(TRANS, M, N, NRHS, lapA, LDA, lapB, LDB, WORK, LWORK, INFO); if (INFO != 0) cimg::warn(_cimg_instance "solve(): LAPACK library function sgels() returned error code %d.", cimg_instance, INFO); assign(NRHS, N); if (!INFO) cimg_forXY(*this,k,l) (*this)(k,l) = (T)lapB[k*M + l]; else assign(A.get_pseudoinvert()*(*this)); delete[] lapA; delete[] lapB; delete[] WORK; #else assign(A.get_pseudoinvert()*(*this)); #endif } return *this; } //! Solve a system of linear equations \newinstance. template<typename t> CImg<_cimg_Ttfloat> get_solve(const CImg<t>& A) const { typedef _cimg_Ttfloat Ttfloat; return CImg<Ttfloat>(*this,false).solve(A); } template<typename t, typename ti> CImg<T>& _solve(const CImg<t>& A, const CImg<ti>& indx) { typedef _cimg_Ttfloat Ttfloat; const int N = (int)size(); int ii = -1; Ttfloat sum; for (int i = 0; i<N; ++i) { const int ip = (int)indx[i]; sum = (*this)(ip); (*this)(ip) = (*this)(i); if (ii>=0) for (int j = ii; j<=i - 1; ++j) sum-=A(j,i)*(*this)(j); else if (sum!=0) ii = i; (*this)(i) = (T)sum; } for (int i = N - 1; i>=0; --i) { sum = (*this)(i); for (int j = i + 1; j<N; ++j) sum-=A(j,i)*(*this)(j); (*this)(i) = (T)(sum/A(i,i)); } return *this; } //! Solve a tridiagonal system of linear equations. /** \param A Coefficients of the tridiagonal system. A is a tridiagonal matrix A = [ b0,c0,0,...; a1,b1,c1,0,... ; ... ; ...,0,aN,bN ], stored as a 3 columns matrix \note Solve AX=B where \c B=*this, using the Thomas algorithm. **/ template<typename t> CImg<T>& solve_tridiagonal(const CImg<t>& A) { const unsigned int siz = (unsigned int)size(); if (A._width!=3 || A._height!=siz) throw CImgArgumentException(_cimg_instance "solve_tridiagonal(): Instance and tridiagonal matrix " "(%u,%u,%u,%u,%p) have incompatible dimensions.", cimg_instance, A._width,A._height,A._depth,A._spectrum,A._data); typedef _cimg_Ttfloat Ttfloat; const Ttfloat epsilon = 1e-4f; CImg<Ttfloat> B = A.get_column(1), V(*this,false); for (int i = 1; i<(int)siz; ++i) { const Ttfloat m = A(0,i)/(B[i - 1]?B[i - 1]:epsilon); B[i] -= m*A(2,i - 1); V[i] -= m*V[i - 1]; } (*this)[siz - 1] = (T)(V[siz - 1]/(B[siz - 1]?B[siz - 1]:epsilon)); for (int i = (int)siz - 2; i>=0; --i) (*this)[i] = (T)((V[i] - A(2,i)*(*this)[i + 1])/(B[i]?B[i]:epsilon)); return *this; } //! Solve a tridiagonal system of linear equations \newinstance. template<typename t> CImg<_cimg_Ttfloat> get_solve_tridiagonal(const CImg<t>& A) const { return CImg<_cimg_Ttfloat>(*this,false).solve_tridiagonal(A); } //! Compute eigenvalues and eigenvectors of the instance image, viewed as a matrix. /** \param[out] val Vector of the estimated eigenvalues, in decreasing order. \param[out] vec Matrix of the estimated eigenvectors, sorted by columns. **/ template<typename t> const CImg<T>& eigen(CImg<t>& val, CImg<t> &vec) const { if (is_empty()) { val.assign(); vec.assign(); } else { if (_width!=_height || _depth>1 || _spectrum>1) throw CImgInstanceException(_cimg_instance "eigen(): Instance is not a square matrix.", cimg_instance); if (val.size()<(ulongT)_width) val.assign(1,_width); if (vec.size()<(ulongT)_width*_width) vec.assign(_width,_width); switch (_width) { case 1 : { val[0] = (t)(*this)[0]; vec[0] = (t)1; } break; case 2 : { const double a = (*this)[0], b = (*this)[1], c = (*this)[2], d = (*this)[3], e = a + d; double f = e*e - 4*(a*d - b*c); if (f<0) cimg::warn(_cimg_instance "eigen(): Complex eigenvalues found.", cimg_instance); f = std::sqrt(f); const double l1 = 0.5*(e - f), l2 = 0.5*(e + f), b2 = b*b, norm1 = std::sqrt(cimg::sqr(l2 - a) + b2), norm2 = std::sqrt(cimg::sqr(l1 - a) + b2); val[0] = (t)l2; val[1] = (t)l1; if (norm1>0) { vec(0,0) = (t)(b/norm1); vec(0,1) = (t)((l2 - a)/norm1); } else { vec(0,0) = 1; vec(0,1) = 0; } if (norm2>0) { vec(1,0) = (t)(b/norm2); vec(1,1) = (t)((l1 - a)/norm2); } else { vec(1,0) = 1; vec(1,1) = 0; } } break; default : throw CImgInstanceException(_cimg_instance "eigen(): Eigenvalues computation of general matrices is limited " "to 2x2 matrices.", cimg_instance); } } return *this; } //! Compute eigenvalues and eigenvectors of the instance image, viewed as a matrix. /** \return A list of two images <tt>[val; vec]</tt>, whose meaning is similar as in eigen(CImg<t>&,CImg<t>&) const. **/ CImgList<Tfloat> get_eigen() const { CImgList<Tfloat> res(2); eigen(res[0],res[1]); return res; } //! Compute eigenvalues and eigenvectors of the instance image, viewed as a symmetric matrix. /** \param[out] val Vector of the estimated eigenvalues, in decreasing order. \param[out] vec Matrix of the estimated eigenvectors, sorted by columns. **/ template<typename t> const CImg<T>& symmetric_eigen(CImg<t>& val, CImg<t>& vec) const { if (is_empty()) { val.assign(); vec.assign(); return *this; } if (_width!=_height || _depth>1 || _spectrum>1) throw CImgInstanceException(_cimg_instance "eigen(): Instance is not a square matrix.", cimg_instance); val.assign(1,_width); vec.assign(_width,_width); if (_width==1) { val[0] = cimg::abs((*this)[0]); vec[0] = 1; return *this; } if (_width==2) { const double a = (*this)[0], b = (*this)[1], c = (*this)[2], d = (*this)[3], e = a + d, f = std::sqrt(std::max(e*e - 4*(a*d - b*c),0.0)), l1 = 0.5*(e - f), l2 = 0.5*(e + f), n = std::sqrt(cimg::sqr(l2 - a) + b*b); val[0] = (t)l2; val[1] = (t)l1; if (n>0) { vec[0] = (t)(b/n); vec[2] = (t)((l2 - a)/n); } else { vec[0] = 1; vec[2] = 0; } vec[1] = -vec[2]; vec[3] = vec[0]; return *this; } #ifdef cimg_use_lapack char JOB = 'V', UPLO = 'U'; int N = _width, LWORK = 4*N, INFO; Tfloat *const lapA = new Tfloat[N*N], *const lapW = new Tfloat[N], *const WORK = new Tfloat[LWORK]; cimg_forXY(*this,k,l) lapA[k*N + l] = (Tfloat)((*this)(k,l)); cimg::syev(JOB,UPLO,N,lapA,lapW,WORK,LWORK,INFO); if (INFO) cimg::warn(_cimg_instance "symmetric_eigen(): LAPACK library function dsyev_() returned error code %d.", cimg_instance, INFO); if (!INFO) { cimg_forY(val,i) val(i) = (T)lapW[N - 1 -i]; cimg_forXY(vec,k,l) vec(k,l) = (T)(lapA[(N - 1 - k)*N + l]); } else { val.fill(0); vec.fill(0); } delete[] lapA; delete[] lapW; delete[] WORK; #else CImg<t> V(_width,_width); Tfloat M = 0, m = (Tfloat)min_max(M), maxabs = cimg::max((Tfloat)1,cimg::abs(m),cimg::abs(M)); (CImg<Tfloat>(*this,false)/=maxabs).SVD(vec,val,V,false); if (maxabs!=1) val*=maxabs; bool is_ambiguous = false; float eig = 0; cimg_forY(val,p) { // Check for ambiguous cases if (val[p]>eig) eig = (float)val[p]; t scal = 0; cimg_forY(vec,y) scal+=vec(p,y)*V(p,y); if (cimg::abs(scal)<0.9f) is_ambiguous = true; if (scal<0) val[p] = -val[p]; } if (is_ambiguous) { ++(eig*=2); SVD(vec,val,V,false,40,eig); val-=eig; } CImg<intT> permutations; // Sort eigenvalues in decreasing order CImg<t> tmp(_width); val.sort(permutations,false); cimg_forY(vec,k) { cimg_forY(permutations,y) tmp(y) = vec(permutations(y),k); std::memcpy(vec.data(0,k),tmp._data,sizeof(t)*_width); } #endif return *this; } //! Compute eigenvalues and eigenvectors of the instance image, viewed as a symmetric matrix. /** \return A list of two images <tt>[val; vec]</tt>, whose meaning are similar as in symmetric_eigen(CImg<t>&,CImg<t>&) const. **/ CImgList<Tfloat> get_symmetric_eigen() const { CImgList<Tfloat> res(2); symmetric_eigen(res[0],res[1]); return res; } //! Sort pixel values and get sorting permutations. /** \param[out] permutations Permutation map used for the sorting. \param is_increasing Tells if pixel values are sorted in an increasing (\c true) or decreasing (\c false) way. **/ template<typename t> CImg<T>& sort(CImg<t>& permutations, const bool is_increasing=true) { permutations.assign(_width,_height,_depth,_spectrum); if (is_empty()) return *this; cimg_foroff(permutations,off) permutations[off] = (t)off; return _quicksort(0,size() - 1,permutations,is_increasing,true); } //! Sort pixel values and get sorting permutations \newinstance. template<typename t> CImg<T> get_sort(CImg<t>& permutations, const bool is_increasing=true) const { return (+*this).sort(permutations,is_increasing); } //! Sort pixel values. /** \param is_increasing Tells if pixel values are sorted in an increasing (\c true) or decreasing (\c false) way. \param axis Tells if the value sorting must be done along a specific axis. Can be: - \c 0: All pixel values are sorted, independently on their initial position. - \c 'x': Image columns are sorted, according to the first value in each column. - \c 'y': Image rows are sorted, according to the first value in each row. - \c 'z': Image slices are sorted, according to the first value in each slice. - \c 'c': Image channels are sorted, according to the first value in each channel. **/ CImg<T>& sort(const bool is_increasing=true, const char axis=0) { if (is_empty()) return *this; CImg<uintT> perm; switch (cimg::lowercase(axis)) { case 0 : _quicksort(0,size() - 1,perm,is_increasing,false); break; case 'x' : { perm.assign(_width); get_crop(0,0,0,0,_width - 1,0,0,0).sort(perm,is_increasing); CImg<T> img(*this,false); cimg_forXYZC(*this,x,y,z,c) (*this)(x,y,z,c) = img(perm[x],y,z,c); } break; case 'y' : { perm.assign(_height); get_crop(0,0,0,0,0,_height - 1,0,0).sort(perm,is_increasing); CImg<T> img(*this,false); cimg_forXYZC(*this,x,y,z,c) (*this)(x,y,z,c) = img(x,perm[y],z,c); } break; case 'z' : { perm.assign(_depth); get_crop(0,0,0,0,0,0,_depth - 1,0).sort(perm,is_increasing); CImg<T> img(*this,false); cimg_forXYZC(*this,x,y,z,c) (*this)(x,y,z,c) = img(x,y,perm[z],c); } break; case 'c' : { perm.assign(_spectrum); get_crop(0,0,0,0,0,0,0,_spectrum - 1).sort(perm,is_increasing); CImg<T> img(*this,false); cimg_forXYZC(*this,x,y,z,c) (*this)(x,y,z,c) = img(x,y,z,perm[c]); } break; default : throw CImgArgumentException(_cimg_instance "sort(): Invalid specified axis '%c' " "(should be { x | y | z | c }).", cimg_instance,axis); } return *this; } //! Sort pixel values \newinstance. CImg<T> get_sort(const bool is_increasing=true, const char axis=0) const { return (+*this).sort(is_increasing,axis); } template<typename t> CImg<T>& _quicksort(const long indm, const long indM, CImg<t>& permutations, const bool is_increasing, const bool is_permutations) { if (indm<indM) { const long mid = (indm + indM)/2; if (is_increasing) { if ((*this)[indm]>(*this)[mid]) { cimg::swap((*this)[indm],(*this)[mid]); if (is_permutations) cimg::swap(permutations[indm],permutations[mid]); } if ((*this)[mid]>(*this)[indM]) { cimg::swap((*this)[indM],(*this)[mid]); if (is_permutations) cimg::swap(permutations[indM],permutations[mid]); } if ((*this)[indm]>(*this)[mid]) { cimg::swap((*this)[indm],(*this)[mid]); if (is_permutations) cimg::swap(permutations[indm],permutations[mid]); } } else { if ((*this)[indm]<(*this)[mid]) { cimg::swap((*this)[indm],(*this)[mid]); if (is_permutations) cimg::swap(permutations[indm],permutations[mid]); } if ((*this)[mid]<(*this)[indM]) { cimg::swap((*this)[indM],(*this)[mid]); if (is_permutations) cimg::swap(permutations[indM],permutations[mid]); } if ((*this)[indm]<(*this)[mid]) { cimg::swap((*this)[indm],(*this)[mid]); if (is_permutations) cimg::swap(permutations[indm],permutations[mid]); } } if (indM - indm>=3) { const T pivot = (*this)[mid]; long i = indm, j = indM; if (is_increasing) { do { while ((*this)[i]<pivot) ++i; while ((*this)[j]>pivot) --j; if (i<=j) { if (is_permutations) cimg::swap(permutations[i],permutations[j]); cimg::swap((*this)[i++],(*this)[j--]); } } while (i<=j); } else { do { while ((*this)[i]>pivot) ++i; while ((*this)[j]<pivot) --j; if (i<=j) { if (is_permutations) cimg::swap(permutations[i],permutations[j]); cimg::swap((*this)[i++],(*this)[j--]); } } while (i<=j); } if (indm<j) _quicksort(indm,j,permutations,is_increasing,is_permutations); if (i<indM) _quicksort(i,indM,permutations,is_increasing,is_permutations); } } return *this; } //! Compute the SVD of the instance image, viewed as a general matrix. /** Compute the SVD decomposition \c *this=U*S*V' where \c U and \c V are orthogonal matrices and \c S is a diagonal matrix. \c V' denotes the matrix transpose of \c V. \param[out] U First matrix of the SVD product. \param[out] S Coefficients of the second (diagonal) matrix of the SVD product. These coefficients are stored as a vector. \param[out] V Third matrix of the SVD product. \param sorting Tells if the diagonal coefficients are sorted (in decreasing order). \param max_iteration Maximum number of iterations considered for the algorithm convergence. \param lambda Epsilon used for the algorithm convergence. \note The instance matrix can be computed from \c U,\c S and \c V by \code const CImg<> A; // Input matrix (assumed to contain some values) CImg<> U,S,V; A.SVD(U,S,V) \endcode **/ template<typename t> const CImg<T>& SVD(CImg<t>& U, CImg<t>& S, CImg<t>& V, const bool sorting=true, const unsigned int max_iteration=40, const float lambda=0) const { typedef _cimg_Ttfloat Ttfloat; if (is_empty()) { U.assign(); S.assign(); V.assign(); } else { U = *this; if (lambda!=0) { const unsigned int delta = std::min(U._width,U._height); for (unsigned int i = 0; i<delta; ++i) U(i,i) = (t)(U(i,i) + lambda); } if (S.size()<_width) S.assign(1,_width); if (V._width<_width || V._height<_height) V.assign(_width,_width); CImg<t> rv1(_width); Ttfloat anorm = 0, c, f, g = 0, h, s, scale = 0; int l = 0, nm = 0; cimg_forX(U,i) { l = i + 1; rv1[i] = scale*g; g = s = scale = 0; if (i<height()) { for (int k = i; k<height(); ++k) scale+=cimg::abs(U(i,k)); if (scale) { for (int k = i; k<height(); ++k) { U(i,k)/=scale; s+=U(i,k)*U(i,k); } f = U(i,i); g = (Ttfloat)((f>=0?-1:1)*std::sqrt(s)); h=f*g-s; U(i,i) = f-g; for (int j = l; j<width(); ++j) { s = 0; for (int k=i; k<height(); ++k) s+=U(i,k)*U(j,k); f = s/h; for (int k = i; k<height(); ++k) U(j,k)+=f*U(i,k); } for (int k = i; k<height(); ++k) U(i,k)*=scale; } } S[i]=scale*g; g = s = scale = 0; if (i<height() && i!=width() - 1) { for (int k = l; k<width(); ++k) scale+=cimg::abs(U(k,i)); if (scale) { for (int k = l; k<width(); ++k) { U(k,i)/= scale; s+=U(k,i)*U(k,i); } f = U(l,i); g = (Ttfloat)((f>=0?-1:1)*std::sqrt(s)); h = f*g-s; U(l,i) = f-g; for (int k = l; k<width(); ++k) rv1[k]=U(k,i)/h; for (int j = l; j<height(); ++j) { s = 0; for (int k = l; k<width(); ++k) s+=U(k,j)*U(k,i); for (int k = l; k<width(); ++k) U(k,j)+=s*rv1[k]; } for (int k = l; k<width(); ++k) U(k,i)*=scale; } } anorm = (Ttfloat)std::max((float)anorm,(float)(cimg::abs(S[i]) + cimg::abs(rv1[i]))); } for (int i = width() - 1; i>=0; --i) { if (i<width()-1) { if (g) { for (int j = l; j<width(); ++j) V(i,j) =(U(j,i)/U(l,i))/g; for (int j = l; j<width(); ++j) { s = 0; for (int k = l; k<width(); ++k) s+=U(k,i)*V(j,k); for (int k = l; k<width(); ++k) V(j,k)+=s*V(i,k); } } for (int j = l; j<width(); ++j) V(j,i) = V(i,j) = (t)0.; } V(i,i) = (t)1.; g = rv1[i]; l = i; } for (int i = std::min(width(),height()) - 1; i>=0; --i) { l = i + 1; g = S[i]; for (int j = l; j<width(); ++j) U(j,i) = 0; if (g) { g = 1/g; for (int j = l; j<width(); ++j) { s = 0; for (int k = l; k<height(); ++k) s+=U(i,k)*U(j,k); f = (s/U(i,i))*g; for (int k = i; k<height(); ++k) U(j,k)+=f*U(i,k); } for (int j = i; j<height(); ++j) U(i,j)*= g; } else for (int j = i; j<height(); ++j) U(i,j) = 0; ++U(i,i); } for (int k = width() - 1; k>=0; --k) { for (unsigned int its = 0; its<max_iteration; ++its) { bool flag = true; for (l = k; l>=1; --l) { nm = l - 1; if ((cimg::abs(rv1[l]) + anorm)==anorm) { flag = false; break; } if ((cimg::abs(S[nm]) + anorm)==anorm) break; } if (flag) { c = 0; s = 1; for (int i = l; i<=k; ++i) { f = s*rv1[i]; rv1[i] = c*rv1[i]; if ((cimg::abs(f) + anorm)==anorm) break; g = S[i]; h = cimg::_hypot(f,g); S[i] = h; h = 1/h; c = g*h; s = -f*h; cimg_forY(U,j) { const t y = U(nm,j), z = U(i,j); U(nm,j) = y*c + z*s; U(i,j) = z*c - y*s; } } } const t z = S[k]; if (l==k) { if (z<0) { S[k] = -z; cimg_forX(U,j) V(k,j) = -V(k,j); } break; } nm = k - 1; t x = S[l], y = S[nm]; g = rv1[nm]; h = rv1[k]; f = ((y - z)*(y + z)+(g - h)*(g + h))/std::max((Ttfloat)1e-25,(Ttfloat)2*h*y); g = cimg::_hypot(f,(Ttfloat)1); f = ((x - z)*(x + z)+h*((y/(f + (f>=0?g:-g))) - h))/std::max((Ttfloat)1e-25,(Ttfloat)x); c = s = 1; for (int j = l; j<=nm; ++j) { const int i = j + 1; g = rv1[i]; h = s*g; g = c*g; t y1 = S[i]; t z1 = cimg::_hypot(f,h); rv1[j] = z1; c = f/std::max((Ttfloat)1e-25,(Ttfloat)z1); s = h/std::max((Ttfloat)1e-25,(Ttfloat)z1); f = x*c + g*s; g = g*c - x*s; h = y1*s; y1*=c; cimg_forX(U,jj) { const t x2 = V(j,jj), z2 = V(i,jj); V(j,jj) = x2*c + z2*s; V(i,jj) = z2*c - x2*s; } z1 = cimg::_hypot(f,h); S[j] = z1; if (z1) { z1 = 1/std::max((Ttfloat)1e-25,(Ttfloat)z1); c = f*z1; s = h*z1; } f = c*g + s*y1; x = c*y1 - s*g; cimg_forY(U,jj) { const t y2 = U(j,jj), z2 = U(i,jj); U(j,jj) = y2*c + z2*s; U(i,jj) = z2*c - y2*s; } } rv1[l] = 0; rv1[k] = f; S[k] = x; } } if (sorting) { CImg<intT> permutations; CImg<t> tmp(_width); S.sort(permutations,false); cimg_forY(U,k) { cimg_forY(permutations,y) tmp(y) = U(permutations(y),k); std::memcpy(U.data(0,k),tmp._data,sizeof(t)*_width); } cimg_forY(V,k) { cimg_forY(permutations,y) tmp(y) = V(permutations(y),k); std::memcpy(V.data(0,k),tmp._data,sizeof(t)*_width); } } } return *this; } //! Compute the SVD of the instance image, viewed as a general matrix. /** \return A list of three images <tt>[U; S; V]</tt>, whose meaning is similar as in SVD(CImg<t>&,CImg<t>&,CImg<t>&,bool,unsigned int,float) const. **/ CImgList<Tfloat> get_SVD(const bool sorting=true, const unsigned int max_iteration=40, const float lambda=0) const { CImgList<Tfloat> res(3); SVD(res[0],res[1],res[2],sorting,max_iteration,lambda); return res; } // [internal] Compute the LU decomposition of a permuted matrix. template<typename t> CImg<T>& _LU(CImg<t>& indx, bool& d) { const int N = width(); int imax = 0; CImg<Tfloat> vv(N); indx.assign(N); d = true; bool return0 = false; cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height>=512)) cimg_forX(*this,i) { Tfloat vmax = 0; cimg_forX(*this,j) { const Tfloat tmp = cimg::abs((*this)(j,i)); if (tmp>vmax) vmax = tmp; } if (vmax==0) return0 = true; else vv[i] = 1/vmax; } if (return0) { indx.fill(0); return fill(0); } cimg_forX(*this,j) { for (int i = 0; i<j; ++i) { Tfloat sum = (*this)(j,i); for (int k = 0; k<i; ++k) sum-=(*this)(k,i)*(*this)(j,k); (*this)(j,i) = (T)sum; } Tfloat vmax = 0; for (int i = j; i<width(); ++i) { Tfloat sum = (*this)(j,i); for (int k = 0; k<j; ++k) sum-=(*this)(k,i)*(*this)(j,k); (*this)(j,i) = (T)sum; const Tfloat tmp = vv[i]*cimg::abs(sum); if (tmp>=vmax) { vmax = tmp; imax = i; } } if (j!=imax) { cimg_forX(*this,k) cimg::swap((*this)(k,imax),(*this)(k,j)); d = !d; vv[imax] = vv[j]; } indx[j] = (t)imax; if ((*this)(j,j)==0) (*this)(j,j) = (T)1e-20; if (j<N) { const Tfloat tmp = 1/(Tfloat)(*this)(j,j); for (int i = j + 1; i<N; ++i) (*this)(j,i) = (T)((*this)(j,i)*tmp); } } return *this; } //! Compute minimal path in a graph, using the Dijkstra algorithm. /** \param distance An object having operator()(unsigned int i, unsigned int j) which returns distance between two nodes (i,j). \param nb_nodes Number of graph nodes. \param starting_node Index of the starting node. \param ending_node Index of the ending node (set to ~0U to ignore ending node). \param previous_node Array that gives the previous node index in the path to the starting node (optional parameter). \return Array of distances of each node to the starting node. **/ template<typename tf, typename t> static CImg<T> dijkstra(const tf& distance, const unsigned int nb_nodes, const unsigned int starting_node, const unsigned int ending_node, CImg<t>& previous_node) { if (starting_node>=nb_nodes) throw CImgArgumentException("CImg<%s>::dijkstra(): Specified index of starting node %u is higher " "than number of nodes %u.", pixel_type(),starting_node,nb_nodes); CImg<T> dist(1,nb_nodes,1,1,cimg::type<T>::max()); dist(starting_node) = 0; previous_node.assign(1,nb_nodes,1,1,(t)-1); previous_node(starting_node) = (t)starting_node; CImg<uintT> Q(nb_nodes); cimg_forX(Q,u) Q(u) = (unsigned int)u; cimg::swap(Q(starting_node),Q(0)); unsigned int sizeQ = nb_nodes; while (sizeQ) { // Update neighbors from minimal vertex const unsigned int umin = Q(0); if (umin==ending_node) sizeQ = 0; else { const T dmin = dist(umin); const T infty = cimg::type<T>::max(); for (unsigned int q = 1; q<sizeQ; ++q) { const unsigned int v = Q(q); const T d = (T)distance(v,umin); if (d<infty) { const T alt = dmin + d; if (alt<dist(v)) { dist(v) = alt; previous_node(v) = (t)umin; const T distpos = dist(Q(q)); for (unsigned int pos = q, par = 0; pos && distpos<dist(Q(par=(pos + 1)/2 - 1)); pos=par) cimg::swap(Q(pos),Q(par)); } } } // Remove minimal vertex from queue Q(0) = Q(--sizeQ); const T distpos = dist(Q(0)); for (unsigned int pos = 0, left = 0, right = 0; ((right=2*(pos + 1),(left=right - 1))<sizeQ && distpos>dist(Q(left))) || (right<sizeQ && distpos>dist(Q(right)));) { if (right<sizeQ) { if (dist(Q(left))<dist(Q(right))) { cimg::swap(Q(pos),Q(left)); pos = left; } else { cimg::swap(Q(pos),Q(right)); pos = right; } } else { cimg::swap(Q(pos),Q(left)); pos = left; } } } } return dist; } //! Return minimal path in a graph, using the Dijkstra algorithm. template<typename tf, typename t> static CImg<T> dijkstra(const tf& distance, const unsigned int nb_nodes, const unsigned int starting_node, const unsigned int ending_node=~0U) { CImg<uintT> foo; return dijkstra(distance,nb_nodes,starting_node,ending_node,foo); } //! Return minimal path in a graph, using the Dijkstra algorithm. /** \param starting_node Index of the starting node. \param ending_node Index of the ending node. \param previous_node Array that gives the previous node index in the path to the starting node (optional parameter). \return Array of distances of each node to the starting node. \note image instance corresponds to the adjacency matrix of the graph. **/ template<typename t> CImg<T>& dijkstra(const unsigned int starting_node, const unsigned int ending_node, CImg<t>& previous_node) { return get_dijkstra(starting_node,ending_node,previous_node).move_to(*this); } //! Return minimal path in a graph, using the Dijkstra algorithm \newinstance. template<typename t> CImg<T> get_dijkstra(const unsigned int starting_node, const unsigned int ending_node, CImg<t>& previous_node) const { if (_width!=_height || _depth!=1 || _spectrum!=1) throw CImgInstanceException(_cimg_instance "dijkstra(): Instance is not a graph adjacency matrix.", cimg_instance); return dijkstra(*this,_width,starting_node,ending_node,previous_node); } //! Return minimal path in a graph, using the Dijkstra algorithm. CImg<T>& dijkstra(const unsigned int starting_node, const unsigned int ending_node=~0U) { return get_dijkstra(starting_node,ending_node).move_to(*this); } //! Return minimal path in a graph, using the Dijkstra algorithm \newinstance. CImg<Tfloat> get_dijkstra(const unsigned int starting_node, const unsigned int ending_node=~0U) const { CImg<uintT> foo; return get_dijkstra(starting_node,ending_node,foo); } //! Return an image containing the Ascii codes of the specified string. /** \param str input C-string to encode as an image. \param is_last_zero Tells if the ending \c '0' character appear in the resulting image. \param is_shared Return result that shares its buffer with \p str. **/ static CImg<T> string(const char *const str, const bool is_last_zero=true, const bool is_shared=false) { if (!str) return CImg<T>(); return CImg<T>(str,(unsigned int)std::strlen(str) + (is_last_zero?1:0),1,1,1,is_shared); } //! Return a \c 1x1 image containing specified value. /** \param a0 First vector value. **/ static CImg<T> vector(const T& a0) { CImg<T> r(1,1); r[0] = a0; return r; } //! Return a \c 1x2 image containing specified values. /** \param a0 First vector value. \param a1 Second vector value. **/ static CImg<T> vector(const T& a0, const T& a1) { CImg<T> r(1,2); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; return r; } //! Return a \c 1x3 image containing specified values. /** \param a0 First vector value. \param a1 Second vector value. \param a2 Third vector value. **/ static CImg<T> vector(const T& a0, const T& a1, const T& a2) { CImg<T> r(1,3); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; return r; } //! Return a \c 1x4 image containing specified values. /** \param a0 First vector value. \param a1 Second vector value. \param a2 Third vector value. \param a3 Fourth vector value. **/ static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3) { CImg<T> r(1,4); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; return r; } //! Return a \c 1x5 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4) { CImg<T> r(1,5); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; return r; } //! Return a \c 1x6 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5) { CImg<T> r(1,6); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; return r; } //! Return a \c 1x7 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6) { CImg<T> r(1,7); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; return r; } //! Return a \c 1x8 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7) { CImg<T> r(1,8); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; return r; } //! Return a \c 1x9 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8) { CImg<T> r(1,9); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; return r; } //! Return a \c 1x10 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8, const T& a9) { CImg<T> r(1,10); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; *(ptr++) = a9; return r; } //! Return a \c 1x11 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8, const T& a9, const T& a10) { CImg<T> r(1,11); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; *(ptr++) = a9; *(ptr++) = a10; return r; } //! Return a \c 1x12 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8, const T& a9, const T& a10, const T& a11) { CImg<T> r(1,12); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; *(ptr++) = a9; *(ptr++) = a10; *(ptr++) = a11; return r; } //! Return a \c 1x13 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8, const T& a9, const T& a10, const T& a11, const T& a12) { CImg<T> r(1,13); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; *(ptr++) = a9; *(ptr++) = a10; *(ptr++) = a11; *(ptr++) = a12; return r; } //! Return a \c 1x14 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8, const T& a9, const T& a10, const T& a11, const T& a12, const T& a13) { CImg<T> r(1,14); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; *(ptr++) = a9; *(ptr++) = a10; *(ptr++) = a11; *(ptr++) = a12; *(ptr++) = a13; return r; } //! Return a \c 1x15 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8, const T& a9, const T& a10, const T& a11, const T& a12, const T& a13, const T& a14) { CImg<T> r(1,15); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; *(ptr++) = a9; *(ptr++) = a10; *(ptr++) = a11; *(ptr++) = a12; *(ptr++) = a13; *(ptr++) = a14; return r; } //! Return a \c 1x16 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8, const T& a9, const T& a10, const T& a11, const T& a12, const T& a13, const T& a14, const T& a15) { CImg<T> r(1,16); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; *(ptr++) = a9; *(ptr++) = a10; *(ptr++) = a11; *(ptr++) = a12; *(ptr++) = a13; *(ptr++) = a14; *(ptr++) = a15; return r; } //! Return a 1x1 matrix containing specified coefficients. /** \param a0 First matrix value. \note Equivalent to vector(const T&). **/ static CImg<T> matrix(const T& a0) { return vector(a0); } //! Return a 2x2 matrix containing specified coefficients. /** \param a0 First matrix value. \param a1 Second matrix value. \param a2 Third matrix value. \param a3 Fourth matrix value. **/ static CImg<T> matrix(const T& a0, const T& a1, const T& a2, const T& a3) { CImg<T> r(2,2); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; return r; } //! Return a 3x3 matrix containing specified coefficients. /** \param a0 First matrix value. \param a1 Second matrix value. \param a2 Third matrix value. \param a3 Fourth matrix value. \param a4 Fifth matrix value. \param a5 Sixth matrix value. \param a6 Seventh matrix value. \param a7 Eighth matrix value. \param a8 Nineth matrix value. **/ static CImg<T> matrix(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8) { CImg<T> r(3,3); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; return r; } //! Return a 4x4 matrix containing specified coefficients. static CImg<T> matrix(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8, const T& a9, const T& a10, const T& a11, const T& a12, const T& a13, const T& a14, const T& a15) { CImg<T> r(4,4); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; *(ptr++) = a9; *(ptr++) = a10; *(ptr++) = a11; *(ptr++) = a12; *(ptr++) = a13; *(ptr++) = a14; *(ptr++) = a15; return r; } //! Return a 5x5 matrix containing specified coefficients. static CImg<T> matrix(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8, const T& a9, const T& a10, const T& a11, const T& a12, const T& a13, const T& a14, const T& a15, const T& a16, const T& a17, const T& a18, const T& a19, const T& a20, const T& a21, const T& a22, const T& a23, const T& a24) { CImg<T> r(5,5); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; *(ptr++) = a9; *(ptr++) = a10; *(ptr++) = a11; *(ptr++) = a12; *(ptr++) = a13; *(ptr++) = a14; *(ptr++) = a15; *(ptr++) = a16; *(ptr++) = a17; *(ptr++) = a18; *(ptr++) = a19; *(ptr++) = a20; *(ptr++) = a21; *(ptr++) = a22; *(ptr++) = a23; *(ptr++) = a24; return r; } //! Return a 1x1 symmetric matrix containing specified coefficients. /** \param a0 First matrix value. \note Equivalent to vector(const T&). **/ static CImg<T> tensor(const T& a0) { return matrix(a0); } //! Return a 2x2 symmetric matrix tensor containing specified coefficients. static CImg<T> tensor(const T& a0, const T& a1, const T& a2) { return matrix(a0,a1,a1,a2); } //! Return a 3x3 symmetric matrix containing specified coefficients. static CImg<T> tensor(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5) { return matrix(a0,a1,a2,a1,a3,a4,a2,a4,a5); } //! Return a 1x1 diagonal matrix containing specified coefficients. static CImg<T> diagonal(const T& a0) { return matrix(a0); } //! Return a 2x2 diagonal matrix containing specified coefficients. static CImg<T> diagonal(const T& a0, const T& a1) { return matrix(a0,0,0,a1); } //! Return a 3x3 diagonal matrix containing specified coefficients. static CImg<T> diagonal(const T& a0, const T& a1, const T& a2) { return matrix(a0,0,0,0,a1,0,0,0,a2); } //! Return a 4x4 diagonal matrix containing specified coefficients. static CImg<T> diagonal(const T& a0, const T& a1, const T& a2, const T& a3) { return matrix(a0,0,0,0,0,a1,0,0,0,0,a2,0,0,0,0,a3); } //! Return a 5x5 diagonal matrix containing specified coefficients. static CImg<T> diagonal(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4) { return matrix(a0,0,0,0,0,0,a1,0,0,0,0,0,a2,0,0,0,0,0,a3,0,0,0,0,0,a4); } //! Return a NxN identity matrix. /** \param N Dimension of the matrix. **/ static CImg<T> identity_matrix(const unsigned int N) { CImg<T> res(N,N,1,1,0); cimg_forX(res,x) res(x,x) = 1; return res; } //! Return a N-numbered sequence vector from \p a0 to \p a1. /** \param N Size of the resulting vector. \param a0 Starting value of the sequence. \param a1 Ending value of the sequence. **/ static CImg<T> sequence(const unsigned int N, const T& a0, const T& a1) { if (N) return CImg<T>(1,N).sequence(a0,a1); return CImg<T>(); } //! Return a 3x3 rotation matrix from an { axis + angle } or a quaternion. /** \param x X-coordinate of the rotation axis, or first quaternion coordinate. \param y Y-coordinate of the rotation axis, or second quaternion coordinate. \param z Z-coordinate of the rotation axis, or third quaternion coordinate. \param w Angle of the rotation axis (in degree), or fourth quaternion coordinate. \param is_quaternion Tell is the four arguments denotes a set { axis + angle } or a quaternion (x,y,z,w). **/ static CImg<T> rotation_matrix(const float x, const float y, const float z, const float w, const bool is_quaternion=false) { double X, Y, Z, W, N; if (is_quaternion) { N = std::sqrt((double)x*x + (double)y*y + (double)z*z + (double)w*w); if (N>0) { X = x/N; Y = y/N; Z = z/N; W = w/N; } else { X = Y = Z = 0; W = 1; } return CImg<T>::matrix((T)(X*X + Y*Y - Z*Z - W*W),(T)(2*Y*Z - 2*X*W),(T)(2*X*Z + 2*Y*W), (T)(2*X*W + 2*Y*Z),(T)(X*X - Y*Y + Z*Z - W*W),(T)(2*Z*W - 2*X*Y), (T)(2*Y*W - 2*X*Z),(T)(2*X*Y + 2*Z*W),(T)(X*X - Y*Y - Z*Z + W*W)); } N = cimg::hypot((double)x,(double)y,(double)z); if (N>0) { X = x/N; Y = y/N; Z = z/N; } else { X = Y = 0; Z = 1; } const double ang = w*cimg::PI/180, c = std::cos(ang), omc = 1 - c, s = std::sin(ang); return CImg<T>::matrix((T)(X*X*omc + c),(T)(X*Y*omc - Z*s),(T)(X*Z*omc + Y*s), (T)(X*Y*omc + Z*s),(T)(Y*Y*omc + c),(T)(Y*Z*omc - X*s), (T)(X*Z*omc - Y*s),(T)(Y*Z*omc + X*s),(T)(Z*Z*omc + c)); } //@} //----------------------------------- // //! \name Value Manipulation //@{ //----------------------------------- //! Fill all pixel values with specified value. /** \param val Fill value. **/ CImg<T>& fill(const T& val) { if (is_empty()) return *this; if (val && sizeof(T)!=1) cimg_for(*this,ptrd,T) *ptrd = val; else std::memset(_data,(int)(ulongT)val,sizeof(T)*size()); // Double cast to allow val to be (void*) return *this; } //! Fill all pixel values with specified value \newinstance. CImg<T> get_fill(const T& val) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val); } //! Fill sequentially all pixel values with specified values. /** \param val0 First fill value. \param val1 Second fill value. **/ CImg<T>& fill(const T& val0, const T& val1) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 1; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; } if (ptrd!=ptre + 1) *(ptrd++) = val0; return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T& val0, const T& val1, const T& val2) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 2; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; } ptre+=2; switch (ptre - ptrd) { case 2 : *(--ptre) = val1; // fallthrough case 1 : *(--ptre) = val0; // fallthrough } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1, const T& val2) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T& val0, const T& val1, const T& val2, const T& val3) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 3; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; } ptre+=3; switch (ptre - ptrd) { case 3 : *(--ptre) = val2; // fallthrough case 2 : *(--ptre) = val1; // fallthrough case 1 : *(--ptre) = val0; // fallthrough } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1, const T& val2, const T& val3) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 4; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; } ptre+=4; switch (ptre - ptrd) { case 4 : *(--ptre) = val3; // fallthrough case 3 : *(--ptre) = val2; // fallthrough case 2 : *(--ptre) = val1; // fallthrough case 1 : *(--ptre) = val0; // fallthrough } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 5; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; } ptre+=5; switch (ptre - ptrd) { case 5 : *(--ptre) = val4; // fallthrough case 4 : *(--ptre) = val3; // fallthrough case 3 : *(--ptre) = val2; // fallthrough case 2 : *(--ptre) = val1; // fallthrough case 1 : *(--ptre) = val0; // fallthrough } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 6; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; } ptre+=6; switch (ptre - ptrd) { case 6 : *(--ptre) = val5; // fallthrough case 5 : *(--ptre) = val4; // fallthrough case 4 : *(--ptre) = val3; // fallthrough case 3 : *(--ptre) = val2; // fallthrough case 2 : *(--ptre) = val1; // fallthrough case 1 : *(--ptre) = val0; // fallthrough } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 7; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; *(ptrd++) = val7; } ptre+=7; switch (ptre - ptrd) { case 7 : *(--ptre) = val6; // fallthrough case 6 : *(--ptre) = val5; // fallthrough case 5 : *(--ptre) = val4; // fallthrough case 4 : *(--ptre) = val3; // fallthrough case 3 : *(--ptre) = val2; // fallthrough case 2 : *(--ptre) = val1; // fallthrough case 1 : *(--ptre) = val0; // fallthrough } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6,val7); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 8; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; *(ptrd++) = val7; *(ptrd++) = val8; } ptre+=8; switch (ptre - ptrd) { case 8 : *(--ptre) = val7; // fallthrough case 7 : *(--ptre) = val6; // fallthrough case 6 : *(--ptre) = val5; // fallthrough case 5 : *(--ptre) = val4; // fallthrough case 4 : *(--ptre) = val3; // fallthrough case 3 : *(--ptre) = val2; // fallthrough case 2 : *(--ptre) = val1; // fallthrough case 1 : *(--ptre) = val0; // fallthrough } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6,val7,val8); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8, const T& val9) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 9; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; *(ptrd++) = val7; *(ptrd++) = val8; *(ptrd++) = val9; } ptre+=9; switch (ptre - ptrd) { case 9 : *(--ptre) = val8; // fallthrough case 8 : *(--ptre) = val7; // fallthrough case 7 : *(--ptre) = val6; // fallthrough case 6 : *(--ptre) = val5; // fallthrough case 5 : *(--ptre) = val4; // fallthrough case 4 : *(--ptre) = val3; // fallthrough case 3 : *(--ptre) = val2; // fallthrough case 2 : *(--ptre) = val1; // fallthrough case 1 : *(--ptre) = val0; // fallthrough } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8, const T& val9) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6,val7,val8,val9); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8, const T& val9, const T& val10) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 10; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; *(ptrd++) = val7; *(ptrd++) = val8; *(ptrd++) = val9; *(ptrd++) = val10; } ptre+=10; switch (ptre - ptrd) { case 10 : *(--ptre) = val9; // fallthrough case 9 : *(--ptre) = val8; // fallthrough case 8 : *(--ptre) = val7; // fallthrough case 7 : *(--ptre) = val6; // fallthrough case 6 : *(--ptre) = val5; // fallthrough case 5 : *(--ptre) = val4; // fallthrough case 4 : *(--ptre) = val3; // fallthrough case 3 : *(--ptre) = val2; // fallthrough case 2 : *(--ptre) = val1; // fallthrough case 1 : *(--ptre) = val0; // fallthrough } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8, const T& val9, const T& val10) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6,val7,val8,val9,val10); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8, const T& val9, const T& val10, const T& val11) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 11; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; *(ptrd++) = val7; *(ptrd++) = val8; *(ptrd++) = val9; *(ptrd++) = val10; *(ptrd++) = val11; } ptre+=11; switch (ptre - ptrd) { case 11 : *(--ptre) = val10; // fallthrough case 10 : *(--ptre) = val9; // fallthrough case 9 : *(--ptre) = val8; // fallthrough case 8 : *(--ptre) = val7; // fallthrough case 7 : *(--ptre) = val6; // fallthrough case 6 : *(--ptre) = val5; // fallthrough case 5 : *(--ptre) = val4; // fallthrough case 4 : *(--ptre) = val3; // fallthrough case 3 : *(--ptre) = val2; // fallthrough case 2 : *(--ptre) = val1; // fallthrough case 1 : *(--ptre) = val0; // fallthrough } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8, const T& val9, const T& val10, const T& val11) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6,val7,val8,val9,val10, val11); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8, const T& val9, const T& val10, const T& val11, const T& val12) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 12; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; *(ptrd++) = val7; *(ptrd++) = val8; *(ptrd++) = val9; *(ptrd++) = val10; *(ptrd++) = val11; *(ptrd++) = val12; } ptre+=12; switch (ptre - ptrd) { case 12 : *(--ptre) = val11; // fallthrough case 11 : *(--ptre) = val10; // fallthrough case 10 : *(--ptre) = val9; // fallthrough case 9 : *(--ptre) = val8; // fallthrough case 8 : *(--ptre) = val7; // fallthrough case 7 : *(--ptre) = val6; // fallthrough case 6 : *(--ptre) = val5; // fallthrough case 5 : *(--ptre) = val4; // fallthrough case 4 : *(--ptre) = val3; // fallthrough case 3 : *(--ptre) = val2; // fallthrough case 2 : *(--ptre) = val1; // fallthrough case 1 : *(--ptre) = val0; // fallthrough } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8, const T& val9, const T& val10, const T& val11, const T& val12) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6,val7,val8,val9,val10, val11,val12); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8, const T& val9, const T& val10, const T& val11, const T& val12, const T& val13) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 13; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; *(ptrd++) = val7; *(ptrd++) = val8; *(ptrd++) = val9; *(ptrd++) = val10; *(ptrd++) = val11; *(ptrd++) = val12; *(ptrd++) = val13; } ptre+=13; switch (ptre - ptrd) { case 13 : *(--ptre) = val12; // fallthrough case 12 : *(--ptre) = val11; // fallthrough case 11 : *(--ptre) = val10; // fallthrough case 10 : *(--ptre) = val9; // fallthrough case 9 : *(--ptre) = val8; // fallthrough case 8 : *(--ptre) = val7; // fallthrough case 7 : *(--ptre) = val6; // fallthrough case 6 : *(--ptre) = val5; // fallthrough case 5 : *(--ptre) = val4; // fallthrough case 4 : *(--ptre) = val3; // fallthrough case 3 : *(--ptre) = val2; // fallthrough case 2 : *(--ptre) = val1; // fallthrough case 1 : *(--ptre) = val0; // fallthrough } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8, const T& val9, const T& val10, const T& val11, const T& val12, const T& val13) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6,val7,val8,val9,val10, val11,val12,val13); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8, const T& val9, const T& val10, const T& val11, const T& val12, const T& val13, const T& val14) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 14; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; *(ptrd++) = val7; *(ptrd++) = val8; *(ptrd++) = val9; *(ptrd++) = val10; *(ptrd++) = val11; *(ptrd++) = val12; *(ptrd++) = val13; *(ptrd++) = val14; } ptre+=14; switch (ptre - ptrd) { case 14 : *(--ptre) = val13; // fallthrough case 13 : *(--ptre) = val12; // fallthrough case 12 : *(--ptre) = val11; // fallthrough case 11 : *(--ptre) = val10; // fallthrough case 10 : *(--ptre) = val9; // fallthrough case 9 : *(--ptre) = val8; // fallthrough case 8 : *(--ptre) = val7; // fallthrough case 7 : *(--ptre) = val6; // fallthrough case 6 : *(--ptre) = val5; // fallthrough case 5 : *(--ptre) = val4; // fallthrough case 4 : *(--ptre) = val3; // fallthrough case 3 : *(--ptre) = val2; // fallthrough case 2 : *(--ptre) = val1; // fallthrough case 1 : *(--ptre) = val0; // fallthrough } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8, const T& val9, const T& val10, const T& val11, const T& val12, const T& val13, const T& val14) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6,val7,val8,val9,val10, val11,val12,val13,val14); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8, const T& val9, const T& val10, const T& val11, const T& val12, const T& val13, const T& val14, const T& val15) { if (is_empty()) return *this; T *ptrd, *ptre = end() - 15; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; *(ptrd++) = val7; *(ptrd++) = val8; *(ptrd++) = val9; *(ptrd++) = val10; *(ptrd++) = val11; *(ptrd++) = val12; *(ptrd++) = val13; *(ptrd++) = val14; *(ptrd++) = val15; } ptre+=15; switch (ptre - ptrd) { case 15 : *(--ptre) = val14; // fallthrough case 14 : *(--ptre) = val13; // fallthrough case 13 : *(--ptre) = val12; // fallthrough case 12 : *(--ptre) = val11; // fallthrough case 11 : *(--ptre) = val10; // fallthrough case 10 : *(--ptre) = val9; // fallthrough case 9 : *(--ptre) = val8; // fallthrough case 8 : *(--ptre) = val7; // fallthrough case 7 : *(--ptre) = val6; // fallthrough case 6 : *(--ptre) = val5; // fallthrough case 5 : *(--ptre) = val4; // fallthrough case 4 : *(--ptre) = val3; // fallthrough case 3 : *(--ptre) = val2; // fallthrough case 2 : *(--ptre) = val1; // fallthrough case 1 : *(--ptre) = val0; // fallthrough } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5, const T& val6, const T& val7, const T& val8, const T& val9, const T& val10, const T& val11, const T& val12, const T& val13, const T& val14, const T& val15) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6,val7,val8,val9,val10, val11,val12,val13,val14,val15); } //! Fill sequentially pixel values according to a given expression. /** \param expression C-string describing a math formula, or a sequence of values. \param repeat_values In case a list of values is provided, tells if this list must be repeated for the filling. \param allow_formula Tells that mathematical formulas are authorized for the filling. \param list_inputs In case of a mathematical expression, attach a list of images to the specified expression. \param[out] list_outputs In case of a math expression, list of images atatched to the specified expression. **/ CImg<T>& fill(const char *const expression, const bool repeat_values, const bool allow_formula=true, const CImgList<T> *const list_inputs=0, CImgList<T> *const list_outputs=0) { return _fill(expression,repeat_values,allow_formula?1:0,list_inputs,list_outputs,"fill",0); } // 'formula_mode' = { 0 = does not allow formula | 1 = allow formula | // 2 = allow formula but do not fill image values }. CImg<T>& _fill(const char *const expression, const bool repeat_values, const unsigned int formula_mode, const CImgList<T> *const list_inputs, CImgList<T> *const list_outputs, const char *const calling_function, const CImg<T> *provides_copy) { if (is_empty() || !expression || !*expression) return *this; const unsigned int omode = cimg::exception_mode(); cimg::exception_mode(0); CImg<charT> is_error; bool is_value_sequence = false; cimg_abort_init; if (formula_mode) { // Try to pre-detect regular value sequence to avoid exception thrown by _cimg_math_parser. double value; char sep; const int err = cimg_sscanf(expression,"%lf %c",&value,&sep); if (err==1 || (err==2 && sep==',')) { if (err==1) return fill((T)value); else is_value_sequence = true; } // Try to fill values according to a formula. _cimg_abort_init_omp; if (!is_value_sequence) try { CImg<T> base = provides_copy?provides_copy->get_shared():get_shared(); _cimg_math_parser mp(expression + (*expression=='>' || *expression=='<' || *expression=='*' || *expression==':'), calling_function,base,this,list_inputs,list_outputs,true); if (!provides_copy && expression && *expression!='>' && *expression!='<' && *expression!=':' && mp.need_input_copy) base.assign().assign(*this,false); // Needs input copy bool do_in_parallel = false; #if cimg_use_openmp!=0 cimg_openmp_if(*expression=='*' || *expression==':' || (mp.is_parallelizable && _width>=(cimg_openmp_sizefactor)*320 && _height*_depth*_spectrum>=2)) do_in_parallel = true; #endif if (mp.result_dim) { // Vector-valued expression const unsigned int N = std::min(mp.result_dim,_spectrum); const ulongT whd = (ulongT)_width*_height*_depth; T *ptrd = *expression=='<'?_data + _width*_height*_depth - 1:_data; if (*expression=='<') { CImg<doubleT> res(1,mp.result_dim); cimg_rofYZ(*this,y,z) { cimg_abort_test; if (formula_mode==2) cimg_rofX(*this,x) mp(x,y,z,0); else cimg_rofX(*this,x) { mp(x,y,z,0,res._data); const double *ptrs = res._data; T *_ptrd = ptrd--; for (unsigned int n = N; n>0; --n) { *_ptrd = (T)(*ptrs++); _ptrd+=whd; } } } } else if (*expression=='>' || !do_in_parallel) { CImg<doubleT> res(1,mp.result_dim); cimg_forYZ(*this,y,z) { cimg_abort_test; if (formula_mode==2) cimg_forX(*this,x) mp(x,y,z,0); else cimg_forX(*this,x) { mp(x,y,z,0,res._data); const double *ptrs = res._data; T *_ptrd = ptrd++; for (unsigned int n = N; n>0; --n) { *_ptrd = (T)(*ptrs++); _ptrd+=whd; } } } } else { #if cimg_use_openmp!=0 cimg_pragma_openmp(parallel) { _cimg_math_parser _mp = omp_get_thread_num()?mp:_cimg_math_parser(), &lmp = omp_get_thread_num()?_mp:mp; lmp.is_fill = true; cimg_pragma_openmp(for cimg_openmp_collapse(2)) cimg_forYZ(*this,y,z) _cimg_abort_try_omp { cimg_abort_test; if (formula_mode==2) cimg_forX(*this,x) lmp(x,y,z,0); else { CImg<doubleT> res(1,lmp.result_dim); T *__ptrd = data(0,y,z,0); cimg_forX(*this,x) { lmp(x,y,z,0,res._data); const double *ptrs = res._data; T *_ptrd = __ptrd++; for (unsigned int n = N; n>0; --n) { *_ptrd = (T)(*ptrs++); _ptrd+=whd; } } } } _cimg_abort_catch_omp _cimg_abort_catch_fill_omp } #endif } } else { // Scalar-valued expression T *ptrd = *expression=='<'?end() - 1:_data; if (*expression=='<') { if (formula_mode==2) cimg_rofYZC(*this,y,z,c) { cimg_abort_test; cimg_rofX(*this,x) mp(x,y,z,c); } else cimg_rofYZC(*this,y,z,c) { cimg_abort_test; cimg_rofX(*this,x) *(ptrd--) = (T)mp(x,y,z,c); } } else if (*expression=='>' || !do_in_parallel) { if (formula_mode==2) cimg_forYZC(*this,y,z,c) { cimg_abort_test; cimg_forX(*this,x) mp(x,y,z,c); } else cimg_forYZC(*this,y,z,c) { cimg_abort_test; cimg_forX(*this,x) *(ptrd++) = (T)mp(x,y,z,c); } } else { #if cimg_use_openmp!=0 cimg_pragma_openmp(parallel) { _cimg_math_parser _mp = omp_get_thread_num()?mp:_cimg_math_parser(), &lmp = omp_get_thread_num()?_mp:mp; lmp.is_fill = true; cimg_pragma_openmp(for cimg_openmp_collapse(3)) cimg_forYZC(*this,y,z,c) _cimg_abort_try_omp { cimg_abort_test; if (formula_mode==2) cimg_forX(*this,x) lmp(x,y,z,c); else { T *_ptrd = data(0,y,z,c); cimg_forX(*this,x) *(_ptrd++) = (T)lmp(x,y,z,c); } } _cimg_abort_catch_omp _cimg_abort_catch_fill_omp } #endif } } mp.end(); } catch (CImgException& e) { CImg<charT>::string(e._message).move_to(is_error); } } // Try to fill values according to a value sequence. if (!formula_mode || is_value_sequence || is_error) { CImg<charT> item(256); char sep = 0; const char *nexpression = expression; ulongT nb = 0; const ulongT siz = size(); T *ptrd = _data; for (double val = 0; *nexpression && nb<siz; ++nb) { sep = 0; const int err = cimg_sscanf(nexpression,"%255[ \n\t0-9.eEinfa+-]%c",item._data,&sep); if (err>0 && cimg_sscanf(item,"%lf",&val)==1 && (sep==',' || sep==';' || err==1)) { nexpression+=std::strlen(item) + (err>1); *(ptrd++) = (T)val; } else break; } cimg::exception_mode(omode); if (nb<siz && (sep || *nexpression)) { if (is_error) throw CImgArgumentException("%s",is_error._data); else throw CImgArgumentException(_cimg_instance "%s(): Invalid sequence of filling values '%s'.", cimg_instance,calling_function,expression); } if (repeat_values && nb && nb<siz) for (T *ptrs = _data, *const ptre = _data + siz; ptrd<ptre; ++ptrs) *(ptrd++) = *ptrs; } cimg::exception_mode(omode); cimg_abort_test; return *this; } //! Fill sequentially pixel values according to a given expression \newinstance. CImg<T> get_fill(const char *const expression, const bool repeat_values, const bool allow_formula=true, const CImgList<T> *const list_inputs=0, CImgList<T> *const list_outputs=0) const { return (+*this).fill(expression,repeat_values,allow_formula?1:0,list_inputs,list_outputs); } //! Fill sequentially pixel values according to the values found in another image. /** \param values Image containing the values used for the filling. \param repeat_values In case there are less values than necessary in \c values, tells if these values must be repeated for the filling. **/ template<typename t> CImg<T>& fill(const CImg<t>& values, const bool repeat_values=true) { if (is_empty() || !values) return *this; T *ptrd = _data, *ptre = ptrd + size(); for (t *ptrs = values._data, *ptrs_end = ptrs + values.size(); ptrs<ptrs_end && ptrd<ptre; ++ptrs) *(ptrd++) = (T)*ptrs; if (repeat_values && ptrd<ptre) for (T *ptrs = _data; ptrd<ptre; ++ptrs) *(ptrd++) = *ptrs; return *this; } //! Fill sequentially pixel values according to the values found in another image \newinstance. template<typename t> CImg<T> get_fill(const CImg<t>& values, const bool repeat_values=true) const { return repeat_values?CImg<T>(_width,_height,_depth,_spectrum).fill(values,repeat_values): (+*this).fill(values,repeat_values); } //! Fill pixel values along the X-axis at a specified pixel position. /** \param y Y-coordinate of the filled column. \param z Z-coordinate of the filled column. \param c C-coordinate of the filled column. \param a0 First fill value. **/ CImg<T>& fillX(const unsigned int y, const unsigned int z, const unsigned int c, const int a0, ...) { #define _cimg_fill1(x,y,z,c,off,siz,t) { \ va_list ap; va_start(ap,a0); T *ptrd = data(x,y,z,c); *ptrd = (T)a0; \ for (unsigned int k = 1; k<siz; ++k) { ptrd+=off; *ptrd = (T)va_arg(ap,t); } \ va_end(ap); } if (y<_height && z<_depth && c<_spectrum) _cimg_fill1(0,y,z,c,1,_width,int); return *this; } //! Fill pixel values along the X-axis at a specified pixel position \overloading. CImg<T>& fillX(const unsigned int y, const unsigned int z, const unsigned int c, const double a0, ...) { if (y<_height && z<_depth && c<_spectrum) _cimg_fill1(0,y,z,c,1,_width,double); return *this; } //! Fill pixel values along the Y-axis at a specified pixel position. /** \param x X-coordinate of the filled row. \param z Z-coordinate of the filled row. \param c C-coordinate of the filled row. \param a0 First fill value. **/ CImg<T>& fillY(const unsigned int x, const unsigned int z, const unsigned int c, const int a0, ...) { if (x<_width && z<_depth && c<_spectrum) _cimg_fill1(x,0,z,c,_width,_height,int); return *this; } //! Fill pixel values along the Y-axis at a specified pixel position \overloading. CImg<T>& fillY(const unsigned int x, const unsigned int z, const unsigned int c, const double a0, ...) { if (x<_width && z<_depth && c<_spectrum) _cimg_fill1(x,0,z,c,_width,_height,double); return *this; } //! Fill pixel values along the Z-axis at a specified pixel position. /** \param x X-coordinate of the filled slice. \param y Y-coordinate of the filled slice. \param c C-coordinate of the filled slice. \param a0 First fill value. **/ CImg<T>& fillZ(const unsigned int x, const unsigned int y, const unsigned int c, const int a0, ...) { const ulongT wh = (ulongT)_width*_height; if (x<_width && y<_height && c<_spectrum) _cimg_fill1(x,y,0,c,wh,_depth,int); return *this; } //! Fill pixel values along the Z-axis at a specified pixel position \overloading. CImg<T>& fillZ(const unsigned int x, const unsigned int y, const unsigned int c, const double a0, ...) { const ulongT wh = (ulongT)_width*_height; if (x<_width && y<_height && c<_spectrum) _cimg_fill1(x,y,0,c,wh,_depth,double); return *this; } //! Fill pixel values along the C-axis at a specified pixel position. /** \param x X-coordinate of the filled channel. \param y Y-coordinate of the filled channel. \param z Z-coordinate of the filled channel. \param a0 First filling value. **/ CImg<T>& fillC(const unsigned int x, const unsigned int y, const unsigned int z, const int a0, ...) { const ulongT whd = (ulongT)_width*_height*_depth; if (x<_width && y<_height && z<_depth) _cimg_fill1(x,y,z,0,whd,_spectrum,int); return *this; } //! Fill pixel values along the C-axis at a specified pixel position \overloading. CImg<T>& fillC(const unsigned int x, const unsigned int y, const unsigned int z, const double a0, ...) { const ulongT whd = (ulongT)_width*_height*_depth; if (x<_width && y<_height && z<_depth) _cimg_fill1(x,y,z,0,whd,_spectrum,double); return *this; } //! Discard specified sequence of values in the image buffer, along a specific axis. /** \param values Sequence of values to discard. \param axis Axis along which the values are discarded. If set to \c 0 (default value) the method does it for all the buffer values and returns a one-column vector. \note Discarded values will change the image geometry, so the resulting image is returned as a one-column vector. **/ template<typename t> CImg<T>& discard(const CImg<t>& values, const char axis=0) { if (is_empty() || !values) return *this; return get_discard(values,axis).move_to(*this); } template<typename t> CImg<T> get_discard(const CImg<t>& values, const char axis=0) const { CImg<T> res; if (!values) return +*this; if (is_empty()) return res; const ulongT vsiz = values.size(); const char _axis = cimg::lowercase(axis); ulongT j = 0; unsigned int k = 0; int i0 = 0; res.assign(width(),height(),depth(),spectrum()); switch (_axis) { case 'x' : { cimg_forX(*this,i) { if ((*this)(i)!=(T)values[j]) { if (j) --i; res.draw_image(k,get_columns(i0,i)); k+=i - i0 + 1; i0 = i + 1; j = 0; } else { ++j; if (j>=vsiz) { j = 0; i0 = i + 1; } } } if (i0<width()) { res.draw_image(k,get_columns(i0,width() - 1)); k+=width() - i0; } res.resize(k,-100,-100,-100,0); } break; case 'y' : { cimg_forY(*this,i) { if ((*this)(0,i)!=(T)values[j]) { if (j) --i; res.draw_image(0,k,get_rows(i0,i)); k+=i - i0 + 1; i0 = i + 1; j = 0; } else { ++j; if (j>=vsiz) { j = 0; i0 = i + 1; } } } if (i0<height()) { res.draw_image(0,k,get_rows(i0,height() - 1)); k+=height() - i0; } res.resize(-100,k,-100,-100,0); } break; case 'z' : { cimg_forZ(*this,i) { if ((*this)(0,0,i)!=(T)values[j]) { if (j) --i; res.draw_image(0,0,k,get_slices(i0,i)); k+=i - i0 + 1; i0 = i + 1; j = 0; } else { ++j; if (j>=vsiz) { j = 0; i0 = i + 1; } } } if (i0<depth()) { res.draw_image(0,0,k,get_slices(i0,height() - 1)); k+=depth() - i0; } res.resize(-100,-100,k,-100,0); } break; case 'c' : { cimg_forC(*this,i) { if ((*this)(0,0,0,i)!=(T)values[j]) { if (j) --i; res.draw_image(0,0,0,k,get_channels(i0,i)); k+=i - i0 + 1; i0 = i + 1; j = 0; } else { ++j; if (j>=vsiz) { j = 0; i0 = i + 1; } } } if (i0<spectrum()) { res.draw_image(0,0,k,get_channels(i0,height() - 1)); k+=spectrum() - i0; } res.resize(-100,-100,-100,k,0); } break; default : { res.unroll('y'); cimg_foroff(*this,i) { if ((*this)[i]!=(T)values[j]) { if (j) --i; std::memcpy(res._data + k,_data + i0,(i - i0 + 1)*sizeof(T)); k+=i - i0 + 1; i0 = (int)i + 1; j = 0; } else { ++j; if (j>=vsiz) { j = 0; i0 = (int)i + 1; }} } const ulongT siz = size(); if ((ulongT)i0<siz) { std::memcpy(res._data + k,_data + i0,(siz - i0)*sizeof(T)); k+=siz - i0; } res.resize(1,k,1,1,0); } } return res; } //! Discard neighboring duplicates in the image buffer, along the specified axis. CImg<T>& discard(const char axis=0) { return get_discard(axis).move_to(*this); } //! Discard neighboring duplicates in the image buffer, along the specified axis \newinstance. CImg<T> get_discard(const char axis=0) const { CImg<T> res; if (is_empty()) return res; const char _axis = cimg::lowercase(axis); T current = *_data?(T)0:(T)1; int j = 0; res.assign(width(),height(),depth(),spectrum()); switch (_axis) { case 'x' : { cimg_forX(*this,i) if ((*this)(i)!=current) { res.draw_image(j++,get_column(i)); current = (*this)(i); } res.resize(j,-100,-100,-100,0); } break; case 'y' : { cimg_forY(*this,i) if ((*this)(0,i)!=current) { res.draw_image(0,j++,get_row(i)); current = (*this)(0,i); } res.resize(-100,j,-100,-100,0); } break; case 'z' : { cimg_forZ(*this,i) if ((*this)(0,0,i)!=current) { res.draw_image(0,0,j++,get_slice(i)); current = (*this)(0,0,i); } res.resize(-100,-100,j,-100,0); } break; case 'c' : { cimg_forC(*this,i) if ((*this)(0,0,0,i)!=current) { res.draw_image(0,0,0,j++,get_channel(i)); current = (*this)(0,0,0,i); } res.resize(-100,-100,-100,j,0); } break; default : { res.unroll('y'); cimg_foroff(*this,i) if ((*this)[i]!=current) res[j++] = current = (*this)[i]; res.resize(-100,j,-100,-100,0); } } return res; } //! Invert endianness of all pixel values. /** **/ CImg<T>& invert_endianness() { cimg::invert_endianness(_data,size()); return *this; } //! Invert endianness of all pixel values \newinstance. CImg<T> get_invert_endianness() const { return (+*this).invert_endianness(); } //! Fill image with random values in specified range. /** \param val_min Minimal authorized random value. \param val_max Maximal authorized random value. \note Random variables are uniformely distributed in [val_min,val_max]. **/ CImg<T>& rand(const T& val_min, const T& val_max) { const float delta = (float)val_max - (float)val_min + (cimg::type<T>::is_float()?0:1); if (cimg::type<T>::is_float()) cimg_pragma_openmp(parallel cimg_openmp_if_size(size(),524288)) { ulongT rng = (cimg::_rand(),cimg::rng()); #if cimg_use_openmp!=0 rng+=omp_get_thread_num(); #endif cimg_pragma_openmp(for) cimg_rofoff(*this,off) _data[off] = (T)(val_min + delta*cimg::rand(1,&rng)); cimg::srand(rng); } else cimg_pragma_openmp(parallel cimg_openmp_if_size(size(),524288)) { ulongT rng = (cimg::_rand(),cimg::rng()); #if cimg_use_openmp!=0 rng+=omp_get_thread_num(); #endif cimg_pragma_openmp(for) cimg_rofoff(*this,off) _data[off] = std::min(val_max,(T)(val_min + delta*cimg::rand(1,&rng))); cimg::srand(rng); } return *this; } //! Fill image with random values in specified range \newinstance. CImg<T> get_rand(const T& val_min, const T& val_max) const { return (+*this).rand(val_min,val_max); } //! Round pixel values. /** \param y Rounding precision. \param rounding_type Rounding type. Can be: - \c -1: Backward. - \c 0: Nearest. - \c 1: Forward. **/ CImg<T>& round(const double y=1, const int rounding_type=0) { if (y>0) cimg_openmp_for(*this,cimg::round(*ptr,y,rounding_type),8192); return *this; } //! Round pixel values \newinstance. CImg<T> get_round(const double y=1, const unsigned int rounding_type=0) const { return (+*this).round(y,rounding_type); } //! Add random noise to pixel values. /** \param sigma Amplitude of the random additive noise. If \p sigma<0, it stands for a percentage of the global value range. \param noise_type Type of additive noise (can be \p 0=gaussian, \p 1=uniform, \p 2=Salt and Pepper, \p 3=Poisson or \p 4=Rician). \return A reference to the modified image instance. \note - For Poisson noise (\p noise_type=3), parameter \p sigma is ignored, as Poisson noise only depends on the image value itself. - Function \p CImg<T>::get_noise() is also defined. It returns a non-shared modified copy of the image instance. \par Example \code const CImg<float> img("reference.jpg"), res = img.get_noise(40); (img,res.normalize(0,255)).display(); \endcode \image html ref_noise.jpg **/ CImg<T>& noise(const double sigma, const unsigned int noise_type=0) { if (is_empty()) return *this; const Tfloat vmin = (Tfloat)cimg::type<T>::min(), vmax = (Tfloat)cimg::type<T>::max(); Tfloat nsigma = (Tfloat)sigma, m = 0, M = 0; if (nsigma==0 && noise_type!=3) return *this; if (nsigma<0 || noise_type==2) m = (Tfloat)min_max(M); if (nsigma<0) nsigma = (Tfloat)(-nsigma*(M-m)/100.); switch (noise_type) { case 0 : { // Gaussian noise cimg_pragma_openmp(parallel cimg_openmp_if_size(size(),131072)) { ulongT rng = (cimg::_rand(),cimg::rng()); #if cimg_use_openmp!=0 rng+=omp_get_thread_num(); #endif cimg_pragma_openmp(for) cimg_rofoff(*this,off) { Tfloat val = (Tfloat)(_data[off] + nsigma*cimg::grand(&rng)); if (val>vmax) val = vmax; if (val<vmin) val = vmin; _data[off] = (T)val; } cimg::srand(rng); } } break; case 1 : { // Uniform noise cimg_pragma_openmp(parallel cimg_openmp_if_size(size(),131072)) { ulongT rng = (cimg::_rand(),cimg::rng()); #if cimg_use_openmp!=0 rng+=omp_get_thread_num(); #endif cimg_pragma_openmp(for) cimg_rofoff(*this,off) { Tfloat val = (Tfloat)(_data[off] + nsigma*cimg::rand(-1,1,&rng)); if (val>vmax) val = vmax; if (val<vmin) val = vmin; _data[off] = (T)val; } cimg::srand(rng); } } break; case 2 : { // Salt & Pepper noise if (nsigma<0) nsigma = -nsigma; if (M==m) { if (cimg::type<T>::is_float()) { --m; ++M; } else { m = (Tfloat)cimg::type<T>::min(); M = (Tfloat)cimg::type<T>::max(); } } cimg_pragma_openmp(parallel cimg_openmp_if_size(size(),131072)) { ulongT rng = (cimg::_rand(),cimg::rng()); #if cimg_use_openmp!=0 rng+=omp_get_thread_num(); #endif cimg_pragma_openmp(for) cimg_rofoff(*this,off) if (cimg::rand(100,&rng)<nsigma) _data[off] = (T)(cimg::rand(1,&rng)<0.5?M:m); cimg::srand(rng); } } break; case 3 : { // Poisson Noise cimg_pragma_openmp(parallel cimg_openmp_if_size(size(),131072)) { ulongT rng = (cimg::_rand(),cimg::rng()); #if cimg_use_openmp!=0 rng+=omp_get_thread_num(); #endif cimg_pragma_openmp(for) cimg_rofoff(*this,off) _data[off] = (T)cimg::prand(_data[off],&rng); cimg::srand(rng); } } break; case 4 : { // Rice noise const Tfloat sqrt2 = (Tfloat)std::sqrt(2.); cimg_pragma_openmp(parallel cimg_openmp_if_size(size(),131072)) { ulongT rng = (cimg::_rand(),cimg::rng()); #if cimg_use_openmp!=0 rng+=omp_get_thread_num(); #endif cimg_pragma_openmp(for) cimg_rofoff(*this,off) { const Tfloat val0 = (Tfloat)_data[off]/sqrt2, re = (Tfloat)(val0 + nsigma*cimg::grand(&rng)), im = (Tfloat)(val0 + nsigma*cimg::grand(&rng)); Tfloat val = cimg::hypot(re,im); if (val>vmax) val = vmax; if (val<vmin) val = vmin; _data[off] = (T)val; } cimg::srand(rng); } } break; default : throw CImgArgumentException(_cimg_instance "noise(): Invalid specified noise type %d " "(should be { 0=gaussian | 1=uniform | 2=salt&Pepper | 3=poisson }).", cimg_instance, noise_type); } return *this; } //! Add random noise to pixel values \newinstance. CImg<T> get_noise(const double sigma, const unsigned int noise_type=0) const { return (+*this).noise(sigma,noise_type); } //! Linearly normalize pixel values. /** \param min_value Minimum desired value of the resulting image. \param max_value Maximum desired value of the resulting image. \par Example \code const CImg<float> img("reference.jpg"), res = img.get_normalize(160,220); (img,res).display(); \endcode \image html ref_normalize2.jpg **/ CImg<T>& normalize(const T& min_value, const T& max_value) { if (is_empty()) return *this; const T a = min_value<max_value?min_value:max_value, b = min_value<max_value?max_value:min_value; T m, M = max_min(m); const Tfloat fm = (Tfloat)m, fM = (Tfloat)M; if (m==M) return fill(min_value); if (m!=a || M!=b) cimg_rof(*this,ptrd,T) *ptrd = (T)((*ptrd - fm)/(fM - fm)*(b - a) + a); return *this; } //! Linearly normalize pixel values \newinstance. CImg<Tfloat> get_normalize(const T& min_value, const T& max_value) const { return CImg<Tfloat>(*this,false).normalize((Tfloat)min_value,(Tfloat)max_value); } //! Normalize multi-valued pixels of the image instance, with respect to their L2-norm. /** \par Example \code const CImg<float> img("reference.jpg"), res = img.get_normalize(); (img,res.normalize(0,255)).display(); \endcode \image html ref_normalize.jpg **/ CImg<T>& normalize() { const ulongT whd = (ulongT)_width*_height*_depth; cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*512 && _height*_depth>=16)) cimg_forYZ(*this,y,z) { T *ptrd = data(0,y,z,0); cimg_forX(*this,x) { const T *ptrs = ptrd; float n = 0; cimg_forC(*this,c) { n+=cimg::sqr((float)*ptrs); ptrs+=whd; } n = (float)std::sqrt(n); T *_ptrd = ptrd++; if (n>0) cimg_forC(*this,c) { *_ptrd = (T)(*_ptrd/n); _ptrd+=whd; } else cimg_forC(*this,c) { *_ptrd = (T)0; _ptrd+=whd; } } } return *this; } //! Normalize multi-valued pixels of the image instance, with respect to their L2-norm \newinstance. CImg<Tfloat> get_normalize() const { return CImg<Tfloat>(*this,false).normalize(); } //! Compute Lp-norm of each multi-valued pixel of the image instance. /** \param norm_type Type of computed vector norm (can be \p -1=Linf, or \p greater or equal than 0). \par Example \code const CImg<float> img("reference.jpg"), res = img.get_norm(); (img,res.normalize(0,255)).display(); \endcode \image html ref_norm.jpg **/ CImg<T>& norm(const int norm_type=2) { if (_spectrum==1 && norm_type) return abs(); return get_norm(norm_type).move_to(*this); } //! Compute L2-norm of each multi-valued pixel of the image instance \newinstance. CImg<Tfloat> get_norm(const int norm_type=2) const { if (is_empty()) return *this; if (_spectrum==1 && norm_type) return get_abs(); const ulongT whd = (ulongT)_width*_height*_depth; CImg<Tfloat> res(_width,_height,_depth); switch (norm_type) { case -1 : { // Linf-norm cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*512 && _height*_depth>=16)) cimg_forYZ(*this,y,z) { const ulongT off = (ulongT)offset(0,y,z); const T *ptrs = _data + off; Tfloat *ptrd = res._data + off; cimg_forX(*this,x) { Tfloat n = 0; const T *_ptrs = ptrs++; cimg_forC(*this,c) { const Tfloat val = (Tfloat)cimg::abs(*_ptrs); if (val>n) n = val; _ptrs+=whd; } *(ptrd++) = n; } } } break; case 0 : { // L0-norm cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*512 && _height*_depth>=16)) cimg_forYZ(*this,y,z) { const ulongT off = (ulongT)offset(0,y,z); const T *ptrs = _data + off; Tfloat *ptrd = res._data + off; cimg_forX(*this,x) { unsigned int n = 0; const T *_ptrs = ptrs++; cimg_forC(*this,c) { n+=*_ptrs==0?0:1; _ptrs+=whd; } *(ptrd++) = (Tfloat)n; } } } break; case 1 : { // L1-norm cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*512 && _height*_depth>=16)) cimg_forYZ(*this,y,z) { const ulongT off = (ulongT)offset(0,y,z); const T *ptrs = _data + off; Tfloat *ptrd = res._data + off; cimg_forX(*this,x) { Tfloat n = 0; const T *_ptrs = ptrs++; cimg_forC(*this,c) { n+=cimg::abs(*_ptrs); _ptrs+=whd; } *(ptrd++) = n; } } } break; case 2 : { // L2-norm cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*512 && _height*_depth>=16)) cimg_forYZ(*this,y,z) { const ulongT off = (ulongT)offset(0,y,z); const T *ptrs = _data + off; Tfloat *ptrd = res._data + off; cimg_forX(*this,x) { Tfloat n = 0; const T *_ptrs = ptrs++; cimg_forC(*this,c) { n+=cimg::sqr((Tfloat)*_ptrs); _ptrs+=whd; } *(ptrd++) = (Tfloat)std::sqrt((Tfloat)n); } } } break; default : { // Linf-norm cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*512 && _height*_depth>=16)) cimg_forYZ(*this,y,z) { const ulongT off = (ulongT)offset(0,y,z); const T *ptrs = _data + off; Tfloat *ptrd = res._data + off; cimg_forX(*this,x) { Tfloat n = 0; const T *_ptrs = ptrs++; cimg_forC(*this,c) { n+=std::pow(cimg::abs((Tfloat)*_ptrs),(Tfloat)norm_type); _ptrs+=whd; } *(ptrd++) = (Tfloat)std::pow((Tfloat)n,1/(Tfloat)norm_type); } } } } return res; } //! Cut pixel values in specified range. /** \param min_value Minimum desired value of the resulting image. \param max_value Maximum desired value of the resulting image. \par Example \code const CImg<float> img("reference.jpg"), res = img.get_cut(160,220); (img,res).display(); \endcode \image html ref_cut.jpg **/ CImg<T>& cut(const T& min_value, const T& max_value) { if (is_empty()) return *this; const T a = min_value<max_value?min_value:max_value, b = min_value<max_value?max_value:min_value; cimg_openmp_for(*this,cimg::cut(*ptr,a,b),32768); return *this; } //! Cut pixel values in specified range \newinstance. CImg<T> get_cut(const T& min_value, const T& max_value) const { return (+*this).cut(min_value,max_value); } //! Uniformly quantize pixel values. /** \param nb_levels Number of quantization levels. \param keep_range Tells if resulting values keep the same range as the original ones. \par Example \code const CImg<float> img("reference.jpg"), res = img.get_quantize(4); (img,res).display(); \endcode \image html ref_quantize.jpg **/ CImg<T>& quantize(const unsigned int nb_levels, const bool keep_range=true) { if (!nb_levels) throw CImgArgumentException(_cimg_instance "quantize(): Invalid quantization request with 0 values.", cimg_instance); if (is_empty()) return *this; Tfloat m, M = (Tfloat)max_min(m), range = M - m; if (range>0) { if (keep_range) cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),32768)) cimg_rofoff(*this,off) { const unsigned int val = (unsigned int)((_data[off] - m)*nb_levels/range); _data[off] = (T)(m + std::min(val,nb_levels - 1)*range/nb_levels); } else cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),32768)) cimg_rofoff(*this,off) { const unsigned int val = (unsigned int)((_data[off] - m)*nb_levels/range); _data[off] = (T)std::min(val,nb_levels - 1); } } return *this; } //! Uniformly quantize pixel values \newinstance. CImg<T> get_quantize(const unsigned int n, const bool keep_range=true) const { return (+*this).quantize(n,keep_range); } //! Threshold pixel values. /** \param value Threshold value \param soft_threshold Tells if soft thresholding must be applied (instead of hard one). \param strict_threshold Tells if threshold value is strict. \par Example \code const CImg<float> img("reference.jpg"), res = img.get_threshold(128); (img,res.normalize(0,255)).display(); \endcode \image html ref_threshold.jpg **/ CImg<T>& threshold(const T& value, const bool soft_threshold=false, const bool strict_threshold=false) { if (is_empty()) return *this; if (strict_threshold) { if (soft_threshold) cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),32768)) cimg_rofoff(*this,off) { const T v = _data[off]; _data[off] = v>value?(T)(v-value):v<-(float)value?(T)(v + value):(T)0; } else cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),65536)) cimg_rofoff(*this,off) _data[off] = _data[off]>value?(T)1:(T)0; } else { if (soft_threshold) cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),32768)) cimg_rofoff(*this,off) { const T v = _data[off]; _data[off] = v>=value?(T)(v-value):v<=-(float)value?(T)(v + value):(T)0; } else cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),65536)) cimg_rofoff(*this,off) _data[off] = _data[off]>=value?(T)1:(T)0; } return *this; } //! Threshold pixel values \newinstance. CImg<T> get_threshold(const T& value, const bool soft_threshold=false, const bool strict_threshold=false) const { return (+*this).threshold(value,soft_threshold,strict_threshold); } //! Compute the histogram of pixel values. /** \param nb_levels Number of desired histogram levels. \param min_value Minimum pixel value considered for the histogram computation. All pixel values lower than \p min_value will not be counted. \param max_value Maximum pixel value considered for the histogram computation. All pixel values higher than \p max_value will not be counted. \note - The histogram H of an image I is the 1D function where H(x) counts the number of occurrences of the value x in the image I. - The resulting histogram is always defined in 1D. Histograms of multi-valued images are not multi-dimensional. \par Example \code const CImg<float> img = CImg<float>("reference.jpg").histogram(256); img.display_graph(0,3); \endcode \image html ref_histogram.jpg **/ CImg<T>& histogram(const unsigned int nb_levels, const T& min_value, const T& max_value) { return get_histogram(nb_levels,min_value,max_value).move_to(*this); } //! Compute the histogram of pixel values \overloading. CImg<T>& histogram(const unsigned int nb_levels) { return get_histogram(nb_levels).move_to(*this); } //! Compute the histogram of pixel values \newinstance. CImg<ulongT> get_histogram(const unsigned int nb_levels, const T& min_value, const T& max_value) const { if (!nb_levels || is_empty()) return CImg<ulongT>(); const double vmin = (double)(min_value<max_value?min_value:max_value), vmax = (double)(min_value<max_value?max_value:min_value); CImg<ulongT> res(nb_levels,1,1,1,0); cimg_rof(*this,ptrs,T) { const T val = *ptrs; if (val>=vmin && val<=vmax) ++res[val==vmax?nb_levels - 1:(unsigned int)((val - vmin)*nb_levels/(vmax - vmin))]; } return res; } //! Compute the histogram of pixel values \newinstance. CImg<ulongT> get_histogram(const unsigned int nb_levels) const { if (!nb_levels || is_empty()) return CImg<ulongT>(); T vmax = 0, vmin = min_max(vmax); return get_histogram(nb_levels,vmin,vmax); } //! Equalize histogram of pixel values. /** \param nb_levels Number of histogram levels used for the equalization. \param min_value Minimum pixel value considered for the histogram computation. All pixel values lower than \p min_value will not be counted. \param max_value Maximum pixel value considered for the histogram computation. All pixel values higher than \p max_value will not be counted. \par Example \code const CImg<float> img("reference.jpg"), res = img.get_equalize(256); (img,res).display(); \endcode \image html ref_equalize.jpg **/ CImg<T>& equalize(const unsigned int nb_levels, const T& min_value, const T& max_value) { if (!nb_levels || is_empty()) return *this; const T vmin = min_value<max_value?min_value:max_value, vmax = min_value<max_value?max_value:min_value; CImg<ulongT> hist = get_histogram(nb_levels,vmin,vmax); ulongT cumul = 0; cimg_forX(hist,pos) { cumul+=hist[pos]; hist[pos] = cumul; } if (!cumul) cumul = 1; cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),1048576)) cimg_rofoff(*this,off) { const int pos = (int)((_data[off] - vmin)*(nb_levels - 1.)/(vmax - vmin)); if (pos>=0 && pos<(int)nb_levels) _data[off] = (T)(vmin + (vmax - vmin)*hist[pos]/cumul); } return *this; } //! Equalize histogram of pixel values \overloading. CImg<T>& equalize(const unsigned int nb_levels) { if (!nb_levels || is_empty()) return *this; T vmax = 0, vmin = min_max(vmax); return equalize(nb_levels,vmin,vmax); } //! Equalize histogram of pixel values \newinstance. CImg<T> get_equalize(const unsigned int nblevels, const T& val_min, const T& val_max) const { return (+*this).equalize(nblevels,val_min,val_max); } //! Equalize histogram of pixel values \newinstance. CImg<T> get_equalize(const unsigned int nblevels) const { return (+*this).equalize(nblevels); } //! Index multi-valued pixels regarding to a specified colormap. /** \param colormap Multi-valued colormap used as the basis for multi-valued pixel indexing. \param dithering Level of dithering (0=disable, 1=standard level). \param map_indexes Tell if the values of the resulting image are the colormap indices or the colormap vectors. \note - \p img.index(colormap,dithering,1) is equivalent to <tt>img.index(colormap,dithering,0).map(colormap)</tt>. \par Example \code const CImg<float> img("reference.jpg"), colormap(3,1,1,3, 0,128,255, 0,128,255, 0,128,255); const CImg<float> res = img.get_index(colormap,1,true); (img,res).display(); \endcode \image html ref_index.jpg **/ template<typename t> CImg<T>& index(const CImg<t>& colormap, const float dithering=1, const bool map_indexes=false) { return get_index(colormap,dithering,map_indexes).move_to(*this); } //! Index multi-valued pixels regarding to a specified colormap \newinstance. template<typename t> CImg<typename CImg<t>::Tuint> get_index(const CImg<t>& colormap, const float dithering=1, const bool map_indexes=true) const { if (colormap._spectrum!=_spectrum) throw CImgArgumentException(_cimg_instance "index(): Instance and specified colormap (%u,%u,%u,%u,%p) " "have incompatible dimensions.", cimg_instance, colormap._width,colormap._height,colormap._depth,colormap._spectrum,colormap._data); typedef typename CImg<t>::Tuint tuint; if (is_empty()) return CImg<tuint>(); const ulongT whd = (ulongT)_width*_height*_depth, pwhd = (ulongT)colormap._width*colormap._height*colormap._depth; CImg<tuint> res(_width,_height,_depth,map_indexes?_spectrum:1); if (dithering>0) { // Dithered versions tuint *ptrd = res._data; const float ndithering = cimg::cut(dithering,0,1)/16; Tfloat valm = 0, valM = (Tfloat)max_min(valm); if (valm==valM && valm>=0 && valM<=255) { valm = 0; valM = 255; } CImg<Tfloat> cache = get_crop(-1,0,0,0,_width,1,0,_spectrum - 1); Tfloat *cache_current = cache.data(1,0,0,0), *cache_next = cache.data(1,1,0,0); const ulongT cwhd = (ulongT)cache._width*cache._height*cache._depth; switch (_spectrum) { case 1 : { // Optimized for scalars cimg_forYZ(*this,y,z) { if (y<height() - 2) { Tfloat *ptrc0 = cache_next; const T *ptrs0 = data(0,y + 1,z,0); cimg_forX(*this,x) *(ptrc0++) = (Tfloat)*(ptrs0++); } Tfloat *ptrs0 = cache_current, *ptrsn0 = cache_next; cimg_forX(*this,x) { const Tfloat _val0 = (Tfloat)*ptrs0, val0 = _val0<valm?valm:_val0>valM?valM:_val0; Tfloat distmin = cimg::type<Tfloat>::max(); const t *ptrmin0 = colormap._data; for (const t *ptrp0 = colormap._data, *ptrp_end = ptrp0 + pwhd; ptrp0<ptrp_end; ) { const Tfloat pval0 = (Tfloat)*(ptrp0++) - val0, dist = pval0*pval0; if (dist<distmin) { ptrmin0 = ptrp0 - 1; distmin = dist; } } const Tfloat err0 = ((*(ptrs0++)=val0) - (Tfloat)*ptrmin0)*ndithering; *ptrs0+=7*err0; *(ptrsn0 - 1)+=3*err0; *(ptrsn0++)+=5*err0; *ptrsn0+=err0; if (map_indexes) *(ptrd++) = (tuint)*ptrmin0; else *(ptrd++) = (tuint)(ptrmin0 - colormap._data); } cimg::swap(cache_current,cache_next); } } break; case 2 : { // Optimized for 2D vectors tuint *ptrd1 = ptrd + whd; cimg_forYZ(*this,y,z) { if (y<height() - 2) { Tfloat *ptrc0 = cache_next, *ptrc1 = ptrc0 + cwhd; const T *ptrs0 = data(0,y + 1,z,0), *ptrs1 = ptrs0 + whd; cimg_forX(*this,x) { *(ptrc0++) = (Tfloat)*(ptrs0++); *(ptrc1++) = (Tfloat)*(ptrs1++); } } Tfloat *ptrs0 = cache_current, *ptrs1 = ptrs0 + cwhd, *ptrsn0 = cache_next, *ptrsn1 = ptrsn0 + cwhd; cimg_forX(*this,x) { const Tfloat _val0 = (Tfloat)*ptrs0, val0 = _val0<valm?valm:_val0>valM?valM:_val0, _val1 = (Tfloat)*ptrs1, val1 = _val1<valm?valm:_val1>valM?valM:_val1; Tfloat distmin = cimg::type<Tfloat>::max(); const t *ptrmin0 = colormap._data; for (const t *ptrp0 = colormap._data, *ptrp1 = ptrp0 + pwhd, *ptrp_end = ptrp1; ptrp0<ptrp_end; ) { const Tfloat pval0 = (Tfloat)*(ptrp0++) - val0, pval1 = (Tfloat)*(ptrp1++) - val1, dist = pval0*pval0 + pval1*pval1; if (dist<distmin) { ptrmin0 = ptrp0 - 1; distmin = dist; } } const t *const ptrmin1 = ptrmin0 + pwhd; const Tfloat err0 = ((*(ptrs0++)=val0) - (Tfloat)*ptrmin0)*ndithering, err1 = ((*(ptrs1++)=val1) - (Tfloat)*ptrmin1)*ndithering; *ptrs0+=7*err0; *ptrs1+=7*err1; *(ptrsn0 - 1)+=3*err0; *(ptrsn1 - 1)+=3*err1; *(ptrsn0++)+=5*err0; *(ptrsn1++)+=5*err1; *ptrsn0+=err0; *ptrsn1+=err1; if (map_indexes) { *(ptrd++) = (tuint)*ptrmin0; *(ptrd1++) = (tuint)*ptrmin1; } else *(ptrd++) = (tuint)(ptrmin0 - colormap._data); } cimg::swap(cache_current,cache_next); } } break; case 3 : { // Optimized for 3D vectors (colors) tuint *ptrd1 = ptrd + whd, *ptrd2 = ptrd1 + whd; cimg_forYZ(*this,y,z) { if (y<height() - 2) { Tfloat *ptrc0 = cache_next, *ptrc1 = ptrc0 + cwhd, *ptrc2 = ptrc1 + cwhd; const T *ptrs0 = data(0,y + 1,z,0), *ptrs1 = ptrs0 + whd, *ptrs2 = ptrs1 + whd; cimg_forX(*this,x) { *(ptrc0++) = (Tfloat)*(ptrs0++); *(ptrc1++) = (Tfloat)*(ptrs1++); *(ptrc2++) = (Tfloat)*(ptrs2++); } } Tfloat *ptrs0 = cache_current, *ptrs1 = ptrs0 + cwhd, *ptrs2 = ptrs1 + cwhd, *ptrsn0 = cache_next, *ptrsn1 = ptrsn0 + cwhd, *ptrsn2 = ptrsn1 + cwhd; cimg_forX(*this,x) { const Tfloat _val0 = (Tfloat)*ptrs0, val0 = _val0<valm?valm:_val0>valM?valM:_val0, _val1 = (Tfloat)*ptrs1, val1 = _val1<valm?valm:_val1>valM?valM:_val1, _val2 = (Tfloat)*ptrs2, val2 = _val2<valm?valm:_val2>valM?valM:_val2; Tfloat distmin = cimg::type<Tfloat>::max(); const t *ptrmin0 = colormap._data; for (const t *ptrp0 = colormap._data, *ptrp1 = ptrp0 + pwhd, *ptrp2 = ptrp1 + pwhd, *ptrp_end = ptrp1; ptrp0<ptrp_end; ) { const Tfloat pval0 = (Tfloat)*(ptrp0++) - val0, pval1 = (Tfloat)*(ptrp1++) - val1, pval2 = (Tfloat)*(ptrp2++) - val2, dist = pval0*pval0 + pval1*pval1 + pval2*pval2; if (dist<distmin) { ptrmin0 = ptrp0 - 1; distmin = dist; } } const t *const ptrmin1 = ptrmin0 + pwhd, *const ptrmin2 = ptrmin1 + pwhd; const Tfloat err0 = ((*(ptrs0++)=val0) - (Tfloat)*ptrmin0)*ndithering, err1 = ((*(ptrs1++)=val1) - (Tfloat)*ptrmin1)*ndithering, err2 = ((*(ptrs2++)=val2) - (Tfloat)*ptrmin2)*ndithering; *ptrs0+=7*err0; *ptrs1+=7*err1; *ptrs2+=7*err2; *(ptrsn0 - 1)+=3*err0; *(ptrsn1 - 1)+=3*err1; *(ptrsn2 - 1)+=3*err2; *(ptrsn0++)+=5*err0; *(ptrsn1++)+=5*err1; *(ptrsn2++)+=5*err2; *ptrsn0+=err0; *ptrsn1+=err1; *ptrsn2+=err2; if (map_indexes) { *(ptrd++) = (tuint)*ptrmin0; *(ptrd1++) = (tuint)*ptrmin1; *(ptrd2++) = (tuint)*ptrmin2; } else *(ptrd++) = (tuint)(ptrmin0 - colormap._data); } cimg::swap(cache_current,cache_next); } } break; default : // Generic version cimg_forYZ(*this,y,z) { if (y<height() - 2) { Tfloat *ptrc = cache_next; cimg_forC(*this,c) { Tfloat *_ptrc = ptrc; const T *_ptrs = data(0,y + 1,z,c); cimg_forX(*this,x) *(_ptrc++) = (Tfloat)*(_ptrs++); ptrc+=cwhd; } } Tfloat *ptrs = cache_current, *ptrsn = cache_next; cimg_forX(*this,x) { Tfloat distmin = cimg::type<Tfloat>::max(); const t *ptrmin = colormap._data; for (const t *ptrp = colormap._data, *ptrp_end = ptrp + pwhd; ptrp<ptrp_end; ++ptrp) { Tfloat dist = 0; Tfloat *_ptrs = ptrs; const t *_ptrp = ptrp; cimg_forC(*this,c) { const Tfloat _val = *_ptrs, val = _val<valm?valm:_val>valM?valM:_val; dist+=cimg::sqr((*_ptrs=val) - (Tfloat)*_ptrp); _ptrs+=cwhd; _ptrp+=pwhd; } if (dist<distmin) { ptrmin = ptrp; distmin = dist; } } const t *_ptrmin = ptrmin; Tfloat *_ptrs = ptrs++, *_ptrsn = (ptrsn++) - 1; cimg_forC(*this,c) { const Tfloat err = (*(_ptrs++) - (Tfloat)*_ptrmin)*ndithering; *_ptrs+=7*err; *(_ptrsn++)+=3*err; *(_ptrsn++)+=5*err; *_ptrsn+=err; _ptrmin+=pwhd; _ptrs+=cwhd - 1; _ptrsn+=cwhd - 2; } if (map_indexes) { tuint *_ptrd = ptrd++; cimg_forC(*this,c) { *_ptrd = (tuint)*ptrmin; _ptrd+=whd; ptrmin+=pwhd; } } else *(ptrd++) = (tuint)(ptrmin - colormap._data); } cimg::swap(cache_current,cache_next); } } } else { // Non-dithered versions switch (_spectrum) { case 1 : { // Optimized for scalars cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*64 && _height*_depth>=16 && pwhd>=16)) cimg_forYZ(*this,y,z) { tuint *ptrd = res.data(0,y,z); for (const T *ptrs0 = data(0,y,z), *ptrs_end = ptrs0 + _width; ptrs0<ptrs_end; ) { const Tfloat val0 = (Tfloat)*(ptrs0++); Tfloat distmin = cimg::type<Tfloat>::max(); const t *ptrmin0 = colormap._data; for (const t *ptrp0 = colormap._data, *ptrp_end = ptrp0 + pwhd; ptrp0<ptrp_end; ) { const Tfloat pval0 = (Tfloat)*(ptrp0++) - val0, dist = pval0*pval0; if (dist<distmin) { ptrmin0 = ptrp0 - 1; distmin = dist; } } if (map_indexes) *(ptrd++) = (tuint)*ptrmin0; else *(ptrd++) = (tuint)(ptrmin0 - colormap._data); } } } break; case 2 : { // Optimized for 2D vectors cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*64 && _height*_depth>=16 && pwhd>=16)) cimg_forYZ(*this,y,z) { tuint *ptrd = res.data(0,y,z), *ptrd1 = ptrd + whd; for (const T *ptrs0 = data(0,y,z), *ptrs1 = ptrs0 + whd, *ptrs_end = ptrs0 + _width; ptrs0<ptrs_end; ) { const Tfloat val0 = (Tfloat)*(ptrs0++), val1 = (Tfloat)*(ptrs1++); Tfloat distmin = cimg::type<Tfloat>::max(); const t *ptrmin0 = colormap._data; for (const t *ptrp0 = colormap._data, *ptrp1 = ptrp0 + pwhd, *ptrp_end = ptrp1; ptrp0<ptrp_end; ) { const Tfloat pval0 = (Tfloat)*(ptrp0++) - val0, pval1 = (Tfloat)*(ptrp1++) - val1, dist = pval0*pval0 + pval1*pval1; if (dist<distmin) { ptrmin0 = ptrp0 - 1; distmin = dist; } } if (map_indexes) { *(ptrd++) = (tuint)*ptrmin0; *(ptrd1++) = (tuint)*(ptrmin0 + pwhd); } else *(ptrd++) = (tuint)(ptrmin0 - colormap._data); } } } break; case 3 : { // Optimized for 3D vectors (colors) cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*64 && _height*_depth>=16 && pwhd>=16)) cimg_forYZ(*this,y,z) { tuint *ptrd = res.data(0,y,z), *ptrd1 = ptrd + whd, *ptrd2 = ptrd1 + whd; for (const T *ptrs0 = data(0,y,z), *ptrs1 = ptrs0 + whd, *ptrs2 = ptrs1 + whd, *ptrs_end = ptrs0 + _width; ptrs0<ptrs_end; ) { const Tfloat val0 = (Tfloat)*(ptrs0++), val1 = (Tfloat)*(ptrs1++), val2 = (Tfloat)*(ptrs2++); Tfloat distmin = cimg::type<Tfloat>::max(); const t *ptrmin0 = colormap._data; for (const t *ptrp0 = colormap._data, *ptrp1 = ptrp0 + pwhd, *ptrp2 = ptrp1 + pwhd, *ptrp_end = ptrp1; ptrp0<ptrp_end; ) { const Tfloat pval0 = (Tfloat)*(ptrp0++) - val0, pval1 = (Tfloat)*(ptrp1++) - val1, pval2 = (Tfloat)*(ptrp2++) - val2, dist = pval0*pval0 + pval1*pval1 + pval2*pval2; if (dist<distmin) { ptrmin0 = ptrp0 - 1; distmin = dist; } } if (map_indexes) { *(ptrd++) = (tuint)*ptrmin0; *(ptrd1++) = (tuint)*(ptrmin0 + pwhd); *(ptrd2++) = (tuint)*(ptrmin0 + 2*pwhd); } else *(ptrd++) = (tuint)(ptrmin0 - colormap._data); } } } break; default : // Generic version cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*64 && _height*_depth>=16 && pwhd>=16)) cimg_forYZ(*this,y,z) { tuint *ptrd = res.data(0,y,z); for (const T *ptrs = data(0,y,z), *ptrs_end = ptrs + _width; ptrs<ptrs_end; ++ptrs) { Tfloat distmin = cimg::type<Tfloat>::max(); const t *ptrmin = colormap._data; for (const t *ptrp = colormap._data, *ptrp_end = ptrp + pwhd; ptrp<ptrp_end; ++ptrp) { Tfloat dist = 0; const T *_ptrs = ptrs; const t *_ptrp = ptrp; cimg_forC(*this,c) { dist+=cimg::sqr((Tfloat)*_ptrs - (Tfloat)*_ptrp); _ptrs+=whd; _ptrp+=pwhd; } if (dist<distmin) { ptrmin = ptrp; distmin = dist; } } if (map_indexes) { tuint *_ptrd = ptrd++; cimg_forC(*this,c) { *_ptrd = (tuint)*ptrmin; _ptrd+=whd; ptrmin+=pwhd; } } else *(ptrd++) = (tuint)(ptrmin - colormap._data); } } } } return res; } //! Map predefined colormap on the scalar (indexed) image instance. /** \param colormap Multi-valued colormap used for mapping the indexes. \param boundary_conditions The border condition type { 0=dirichlet | 1=neumann | 2=periodic | 3=mirror }. \par Example \code const CImg<float> img("reference.jpg"), colormap1(3,1,1,3, 0,128,255, 0,128,255, 0,128,255), colormap2(3,1,1,3, 255,0,0, 0,255,0, 0,0,255), res = img.get_index(colormap1,0).map(colormap2); (img,res).display(); \endcode \image html ref_map.jpg **/ template<typename t> CImg<T>& map(const CImg<t>& colormap, const unsigned int boundary_conditions=0) { return get_map(colormap,boundary_conditions).move_to(*this); } //! Map predefined colormap on the scalar (indexed) image instance \newinstance. template<typename t> CImg<t> get_map(const CImg<t>& colormap, const unsigned int boundary_conditions=0) const { const ulongT whd = (ulongT)_width*_height*_depth, siz = size(), cwhd = (ulongT)colormap._width*colormap._height*colormap._depth, cwhd2 = 2*cwhd; CImg<t> res(_width,_height,_depth,_spectrum*colormap._spectrum); switch (colormap._spectrum) { case 1 : { // Optimized for scalars switch (boundary_conditions) { case 3 : // Mirror cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)siz; ++off) { const ulongT ind = ((ulongT)_data[off])%cwhd2; res[off] = colormap[ind<cwhd?ind:cwhd2 - ind - 1]; } break; case 2 : // Periodic cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)siz; ++off) { const ulongT ind = (ulongT)_data[off]; res[off] = colormap[ind%cwhd]; } break; case 1 : // Neumann cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)siz; ++off) { const longT ind = (longT)_data[off]; res[off] = colormap[cimg::cut(ind,(longT)0,(longT)cwhd - 1)]; } break; default : // Dirichlet cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)siz; ++off) { const ulongT ind = (ulongT)_data[off]; res[off] = ind<cwhd?colormap[ind]:(t)0; } } } break; case 2 : { // Optimized for 2D vectors const t *const ptrp0 = colormap._data, *const ptrp1 = ptrp0 + cwhd; switch (boundary_conditions) { case 3 : // Mirror cimg_forC(*this,c) { t *const ptrd0 = res.data(0,0,0,2*c), *const ptrd1 = ptrd0 + whd; const T *const ptrs = data(0,0,0,c); cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)whd; ++off) { const ulongT _ind = ((ulongT)ptrs[off])%cwhd2, ind = _ind<cwhd?_ind:cwhd2 - _ind - 1; ptrd0[off] = ptrp0[ind]; ptrd1[off] = ptrp1[ind]; } } break; case 2 : // Periodic cimg_forC(*this,c) { t *const ptrd0 = res.data(0,0,0,2*c), *const ptrd1 = ptrd0 + whd; const T *const ptrs = data(0,0,0,c); cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)whd; ++off) { const ulongT ind = ((ulongT)ptrs[off])%cwhd; ptrd0[off] = ptrp0[ind]; ptrd1[off] = ptrp1[ind]; } } break; case 1 : // Neumann cimg_forC(*this,c) { t *const ptrd0 = res.data(0,0,0,2*c), *const ptrd1 = ptrd0 + whd; const T *const ptrs = data(0,0,0,c); cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)whd; ++off) { const longT ind = cimg::cut((longT)ptrs[off],(longT)0,(longT)cwhd - 1); ptrd0[off] = ptrp0[ind]; ptrd1[off] = ptrp1[ind]; } } break; default : // Dirichlet cimg_forC(*this,c) { t *const ptrd0 = res.data(0,0,0,2*c), *const ptrd1 = ptrd0 + whd; const T *const ptrs = data(0,0,0,c); cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)whd; ++off) { const ulongT ind = (ulongT)ptrs[off]; if (ind<cwhd) { ptrd0[off] = ptrp0[ind]; ptrd1[off] = ptrp1[ind]; } else ptrd0[off] = ptrd1[off] = (t)0; } } } } break; case 3 : { // Optimized for 3D vectors (colors) const t *const ptrp0 = colormap._data, *ptrp1 = ptrp0 + cwhd, *ptrp2 = ptrp0 + 2*cwhd; switch (boundary_conditions) { case 3 : // Mirror cimg_forC(*this,c) { t *const ptrd0 = res.data(0,0,0,3*c), *const ptrd1 = ptrd0 + whd, *const ptrd2 = ptrd1 + whd; const T *const ptrs = data(0,0,0,c); cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)whd; ++off) { const ulongT _ind = ((ulongT)ptrs[off])%cwhd2, ind = _ind<cwhd?_ind:cwhd2 - _ind - 1; ptrd0[off] = ptrp0[ind]; ptrd1[off] = ptrp1[ind]; ptrd2[off] = ptrp2[ind]; } } break; case 2 : // Periodic cimg_forC(*this,c) { t *const ptrd0 = res.data(0,0,0,3*c), *const ptrd1 = ptrd0 + whd, *const ptrd2 = ptrd1 + whd; const T *const ptrs = data(0,0,0,c); cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)whd; ++off) { const ulongT ind = ((ulongT)ptrs[off])%cwhd; ptrd0[off] = ptrp0[ind]; ptrd1[off] = ptrp1[ind]; ptrd2[off] = ptrp2[ind]; } } break; case 1 : // Neumann cimg_forC(*this,c) { t *const ptrd0 = res.data(0,0,0,3*c), *const ptrd1 = ptrd0 + whd, *const ptrd2 = ptrd1 + whd; const T *const ptrs = data(0,0,0,c); cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)whd; ++off) { const longT ind = cimg::cut((longT)ptrs[off],(longT)0,(longT)cwhd - 1); ptrd0[off] = ptrp0[ind]; ptrd1[off] = ptrp1[ind]; ptrd2[off] = ptrp2[ind]; } } break; default : // Dirichlet cimg_forC(*this,c) { t *const ptrd0 = res.data(0,0,0,3*c), *const ptrd1 = ptrd0 + whd, *const ptrd2 = ptrd1 + whd; const T *const ptrs = data(0,0,0,c); cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)whd; ++off) { const ulongT ind = (ulongT)ptrs[off]; if (ind<cwhd) { ptrd0[off] = ptrp0[ind]; ptrd1[off] = ptrp1[ind]; ptrd2[off] = ptrp2[ind]; } else ptrd0[off] = ptrd1[off] = ptrd2[off] = (t)0; } } } } break; default : { // Generic version switch (boundary_conditions) { case 3 : // Mirror cimg_forC(*this,c) { t *const ptrd = res.data(0,0,0,colormap._spectrum*c); const T *const ptrs = data(0,0,0,c); cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)whd; ++off) { const ulongT _ind = ((ulongT)ptrs[off])%cwhd, ind = _ind<cwhd?_ind:cwhd2 - _ind - 1; t *const _ptrd = ptrd + off; const t *const ptrp = &colormap[ind]; cimg_forC(colormap,k) _ptrd[k*whd] = ptrp[k*cwhd]; } } break; case 2 : // Periodic cimg_forC(*this,c) { t *const ptrd = res.data(0,0,0,colormap._spectrum*c); const T *const ptrs = data(0,0,0,c); cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)whd; ++off) { const ulongT ind = ((ulongT)ptrs[off])%cwhd; t *const _ptrd = ptrd + off; const t *const ptrp = &colormap[ind]; cimg_forC(colormap,k) _ptrd[k*whd] = ptrp[k*cwhd]; } } break; case 1 : // Neumann cimg_forC(*this,c) { t *const ptrd = res.data(0,0,0,colormap._spectrum*c); const T *const ptrs = data(0,0,0,c); cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)whd; ++off) { const longT ind = cimg::cut((longT)ptrs[off],(longT)0,(longT)cwhd - 1); t *const _ptrd = ptrd + off; const t *const ptrp = &colormap[ind]; cimg_forC(colormap,k) _ptrd[k*whd] = ptrp[k*cwhd]; } } break; default : // Dirichlet cimg_forC(*this,c) { t *const ptrd = res.data(0,0,0,colormap._spectrum*c); const T *const ptrs = data(0,0,0,c); cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),256)) for (longT off = 0; off<(longT)whd; ++off) { const ulongT ind = (ulongT)ptrs[off]; t *const _ptrd = ptrd + off; if (ind<cwhd) { const t *const ptrp = &colormap[ind]; cimg_forC(colormap,k) _ptrd[k*whd] = ptrp[k*cwhd]; } else cimg_forC(colormap,k) _ptrd[k*whd] = (t)0; } } } } } return res; } //! Label connected components. /** \param is_high_connectivity Boolean that choose between 4(false)- or 8(true)-connectivity in 2D case, and between 6(false)- or 26(true)-connectivity in 3D case. \param tolerance Tolerance used to determine if two neighboring pixels belong to the same region. \note The algorithm of connected components computation has been primarily done by A. Meijster, according to the publication: 'W.H. Hesselink, A. Meijster, C. Bron, "Concurrent Determination of Connected Components.", In: Science of Computer Programming 41 (2001), pp. 173--194'. The submitted code has then been modified to fit CImg coding style and constraints. **/ CImg<T>& label(const bool is_high_connectivity=false, const Tfloat tolerance=0) { return get_label(is_high_connectivity,tolerance).move_to(*this); } //! Label connected components \newinstance. CImg<ulongT> get_label(const bool is_high_connectivity=false, const Tfloat tolerance=0) const { if (is_empty()) return CImg<ulongT>(); // Create neighborhood tables. int dx[13], dy[13], dz[13], nb = 0; dx[nb] = 1; dy[nb] = 0; dz[nb++] = 0; dx[nb] = 0; dy[nb] = 1; dz[nb++] = 0; if (is_high_connectivity) { dx[nb] = 1; dy[nb] = 1; dz[nb++] = 0; dx[nb] = 1; dy[nb] = -1; dz[nb++] = 0; } if (_depth>1) { // 3D version dx[nb] = 0; dy[nb] = 0; dz[nb++]=1; if (is_high_connectivity) { dx[nb] = 1; dy[nb] = 1; dz[nb++] = -1; dx[nb] = 1; dy[nb] = 0; dz[nb++] = -1; dx[nb] = 1; dy[nb] = -1; dz[nb++] = -1; dx[nb] = 0; dy[nb] = 1; dz[nb++] = -1; dx[nb] = 0; dy[nb] = 1; dz[nb++] = 1; dx[nb] = 1; dy[nb] = -1; dz[nb++] = 1; dx[nb] = 1; dy[nb] = 0; dz[nb++] = 1; dx[nb] = 1; dy[nb] = 1; dz[nb++] = 1; } } return _label(nb,dx,dy,dz,tolerance); } //! Label connected components \overloading. /** \param connectivity_mask Mask of the neighboring pixels. \param tolerance Tolerance used to determine if two neighboring pixels belong to the same region. **/ template<typename t> CImg<T>& label(const CImg<t>& connectivity_mask, const Tfloat tolerance=0) { return get_label(connectivity_mask,tolerance).move_to(*this); } //! Label connected components \newinstance. template<typename t> CImg<ulongT> get_label(const CImg<t>& connectivity_mask, const Tfloat tolerance=0) const { int nb = 0; cimg_for(connectivity_mask,ptr,t) if (*ptr) ++nb; CImg<intT> dx(nb,1,1,1,0), dy(nb,1,1,1,0), dz(nb,1,1,1,0); nb = 0; cimg_forXYZ(connectivity_mask,x,y,z) if ((x || y || z) && connectivity_mask(x,y,z)) { dx[nb] = x; dy[nb] = y; dz[nb++] = z; } return _label(nb,dx,dy,dz,tolerance); } CImg<ulongT> _label(const unsigned int nb, const int *const dx, const int *const dy, const int *const dz, const Tfloat tolerance) const { CImg<ulongT> res(_width,_height,_depth,_spectrum); cimg_forC(*this,c) { CImg<ulongT> _res = res.get_shared_channel(c); // Init label numbers. ulongT *ptr = _res.data(); cimg_foroff(_res,p) *(ptr++) = p; // For each neighbour-direction, label. for (unsigned int n = 0; n<nb; ++n) { const int _dx = dx[n], _dy = dy[n], _dz = dz[n]; if (_dx || _dy || _dz) { const int x0 = _dx<0?-_dx:0, x1 = _dx<0?width():width() - _dx, y0 = _dy<0?-_dy:0, y1 = _dy<0?height():height() - _dy, z0 = _dz<0?-_dz:0, z1 = _dz<0?depth():depth() - _dz; const longT wh = (longT)width()*height(), whd = (longT)width()*height()*depth(), offset = _dz*wh + _dy*width() + _dx; for (longT z = z0, nz = z0 + _dz, pz = z0*wh; z<z1; ++z, ++nz, pz+=wh) { for (longT y = y0, ny = y0 + _dy, py = y0*width() + pz; y<y1; ++y, ++ny, py+=width()) { for (longT x = x0, nx = x0 + _dx, p = x0 + py; x<x1; ++x, ++nx, ++p) { if (cimg::abs((Tfloat)(*this)(x,y,z,c,wh,whd) - (Tfloat)(*this)(nx,ny,nz,c,wh,whd))<=tolerance) { const longT q = p + offset; ulongT xk, yk; for (xk = (ulongT)(p<q?q:p), yk = (ulongT)(p<q?p:q); xk!=yk && _res[xk]!=xk; ) { xk = _res[xk]; if (xk<yk) cimg::swap(xk,yk); } if (xk!=yk) _res[xk] = (ulongT)yk; for (ulongT _p = (ulongT)p; _p!=yk; ) { const ulongT h = _res[_p]; _res[_p] = (ulongT)yk; _p = h; } for (ulongT _q = (ulongT)q; _q!=yk; ) { const ulongT h = _res[_q]; _res[_q] = (ulongT)yk; _q = h; } } } } } } } // Resolve equivalences. ulongT counter = 0; ptr = _res.data(); cimg_foroff(_res,p) { *ptr = *ptr==p?counter++:_res[*ptr]; ++ptr; } } return res; } // [internal] Replace possibly malicious characters for commands to be called by system() by their escaped version. CImg<T>& _system_strescape() { #define cimg_system_strescape(c,s) case c : if (p!=ptrs) CImg<T>(ptrs,(unsigned int)(p-ptrs),1,1,1,false).\ move_to(list); \ CImg<T>(s,(unsigned int)std::strlen(s),1,1,1,false).move_to(list); ptrs = p + 1; break CImgList<T> list; const T *ptrs = _data; cimg_for(*this,p,T) switch ((int)*p) { cimg_system_strescape('\\',"\\\\"); cimg_system_strescape('\"',"\\\""); cimg_system_strescape('!',"\"\\!\""); cimg_system_strescape('`',"\\`"); cimg_system_strescape('$',"\\$"); } if (ptrs<end()) CImg<T>(ptrs,(unsigned int)(end()-ptrs),1,1,1,false).move_to(list); return (list>'x').move_to(*this); } //@} //--------------------------------- // //! \name Color Base Management //@{ //--------------------------------- //! Return colormap \e "default", containing 256 colors entries in RGB. /** \return The following \c 256x1x1x3 colormap is returned: \image html ref_colormap_default.jpg **/ static const CImg<Tuchar>& default_LUT256() { static CImg<Tuchar> colormap; cimg::mutex(8); if (!colormap) { colormap.assign(1,256,1,3); for (unsigned int index = 0, r = 16; r<256; r+=32) for (unsigned int g = 16; g<256; g+=32) for (unsigned int b = 32; b<256; b+=64) { colormap(0,index,0) = (Tuchar)r; colormap(0,index,1) = (Tuchar)g; colormap(0,index++,2) = (Tuchar)b; } } cimg::mutex(8,0); return colormap; } //! Return colormap \e "HSV", containing 256 colors entries in RGB. /** \return The following \c 256x1x1x3 colormap is returned: \image html ref_colormap_hsv.jpg **/ static const CImg<Tuchar>& HSV_LUT256() { static CImg<Tuchar> colormap; cimg::mutex(8); if (!colormap) { CImg<Tint> tmp(1,256,1,3,1); tmp.get_shared_channel(0).sequence(0,359); colormap = tmp.HSVtoRGB(); } cimg::mutex(8,0); return colormap; } //! Return colormap \e "lines", containing 256 colors entries in RGB. /** \return The following \c 256x1x1x3 colormap is returned: \image html ref_colormap_lines.jpg **/ static const CImg<Tuchar>& lines_LUT256() { static const unsigned char pal[] = { 0,255,255,0,0,28,125,125,235,210,186,182,36,0,125,255, 53,32,255,210,89,186,65,45,125,210,210,97,130,194,0,125, 206,53,190,89,255,146,20,190,154,73,255,36,130,215,0,138, 101,210,61,194,206,0,77,45,255,154,174,0,190,239,89,125, 16,36,158,223,117,0,97,69,223,255,40,239,0,0,255,0, 97,170,93,255,138,40,117,210,0,170,53,158,186,255,0,121, 227,121,186,40,20,190,89,255,77,57,130,142,255,73,186,85, 210,8,32,166,243,130,210,40,255,45,61,142,223,49,121,255, 20,162,158,73,89,255,53,138,210,190,57,235,36,73,255,49, 210,0,210,85,57,97,255,121,85,174,40,255,162,178,0,121, 166,125,53,146,166,255,97,121,65,89,235,231,12,170,36,190, 85,255,166,97,198,77,20,146,109,166,255,28,40,202,121,81, 247,0,210,255,49,0,65,255,36,166,93,77,255,85,251,0, 170,178,0,182,255,0,162,16,154,142,162,223,223,0,0,81, 215,4,215,162,215,125,77,206,121,36,125,231,101,16,255,121, 0,57,190,215,65,125,89,142,255,101,73,53,146,223,125,125, 0,255,0,255,0,206,93,138,49,255,0,202,154,85,45,219, 251,53,0,255,40,130,219,158,16,117,186,130,202,49,65,239, 89,202,49,28,247,134,150,0,255,117,202,4,215,81,186,57, 202,89,73,210,40,93,45,251,206,28,223,142,40,134,162,125, 32,247,97,170,0,255,57,134,73,247,162,0,251,40,142,142, 8,166,206,81,154,194,93,89,125,243,28,109,227,0,190,65, 194,186,0,255,53,45,109,186,186,0,255,130,49,170,69,210, 154,0,109,227,45,255,125,105,81,81,255,0,219,134,170,85, 146,28,170,89,223,97,8,210,255,158,49,40,125,174,174,125, 0,227,166,28,219,130,0,93,239,0,85,255,81,178,125,49, 89,255,53,206,73,113,146,255,0,150,36,219,162,0,210,125, 69,134,255,85,40,89,235,49,215,121,0,206,36,223,174,69, 40,182,178,130,69,45,255,210,85,77,215,0,231,146,0,194, 125,174,0,255,40,89,121,206,57,0,206,170,231,150,81,0, 125,255,4,174,4,190,121,255,4,166,109,130,49,239,170,93, 16,174,210,0,255,16,105,158,93,255,0,125,0,255,158,85, 0,255,0,0,255,170,166,61,121,28,198,215,45,243,61,97, 255,53,81,130,109,255,8,117,235,121,40,178,174,0,182,49, 162,121,255,69,206,0,219,125,0,101,255,239,121,32,210,130, 36,231,32,125,81,142,215,158,4,178,255,0,40,251,125,125, 219,89,130,0,166,255,24,65,194,125,255,125,77,125,93,125, 202,24,138,174,178,32,255,85,194,40,85,36,174,174,125,210, 85,255,53,16,93,206,40,130,170,202,93,255,0,24,117,255, 97,113,105,81,255,186,194,57,69,206,57,53,223,190,4,255, 85,97,130,255,85,0,125,223,85,219,0,215,146,77,40,239, 89,36,142,154,227,0,255,85,162,0,162,0,235,178,45,166, 0,247,255,20,69,210,89,142,53,255,40,146,166,255,69,0, 174,154,142,130,162,0,215,255,0,89,40,255,166,61,146,69, 162,40,255,32,121,255,117,178,0,186,206,0,57,215,215,81, 158,77,166,210,77,89,210,0,24,202,150,186,0,255,20,97, 57,170,235,251,16,73,142,251,93,0,202,0,255,121,219,4, 73,219,8,162,206,16,219,93,117,0,255,8,130,174,223,45 }; static const CImg<Tuchar> colormap(pal,1,256,1,3,false); return colormap; } //! Return colormap \e "hot", containing 256 colors entries in RGB. /** \return The following \c 256x1x1x3 colormap is returned: \image html ref_colormap_hot.jpg **/ static const CImg<Tuchar>& hot_LUT256() { static CImg<Tuchar> colormap; cimg::mutex(8); if (!colormap) { colormap.assign(1,4,1,3,(T)0); colormap[1] = colormap[2] = colormap[3] = colormap[6] = colormap[7] = colormap[11] = 255; colormap.resize(1,256,1,3,3); } cimg::mutex(8,0); return colormap; } //! Return colormap \e "cool", containing 256 colors entries in RGB. /** \return The following \c 256x1x1x3 colormap is returned: \image html ref_colormap_cool.jpg **/ static const CImg<Tuchar>& cool_LUT256() { static CImg<Tuchar> colormap; cimg::mutex(8); if (!colormap) colormap.assign(1,2,1,3).fill((T)0,(T)255,(T)255,(T)0,(T)255,(T)255).resize(1,256,1,3,3); cimg::mutex(8,0); return colormap; } //! Return colormap \e "jet", containing 256 colors entries in RGB. /** \return The following \c 256x1x1x3 colormap is returned: \image html ref_colormap_jet.jpg **/ static const CImg<Tuchar>& jet_LUT256() { static CImg<Tuchar> colormap; cimg::mutex(8); if (!colormap) { colormap.assign(1,4,1,3,(T)0); colormap[2] = colormap[3] = colormap[5] = colormap[6] = colormap[8] = colormap[9] = 255; colormap.resize(1,256,1,3,3); } cimg::mutex(8,0); return colormap; } //! Return colormap \e "flag", containing 256 colors entries in RGB. /** \return The following \c 256x1x1x3 colormap is returned: \image html ref_colormap_flag.jpg **/ static const CImg<Tuchar>& flag_LUT256() { static CImg<Tuchar> colormap; cimg::mutex(8); if (!colormap) { colormap.assign(1,4,1,3,(T)0); colormap[0] = colormap[1] = colormap[5] = colormap[9] = colormap[10] = 255; colormap.resize(1,256,1,3,0,2); } cimg::mutex(8,0); return colormap; } //! Return colormap \e "cube", containing 256 colors entries in RGB. /** \return The following \c 256x1x1x3 colormap is returned: \image html ref_colormap_cube.jpg **/ static const CImg<Tuchar>& cube_LUT256() { static CImg<Tuchar> colormap; cimg::mutex(8); if (!colormap) { colormap.assign(1,8,1,3,(T)0); colormap[1] = colormap[3] = colormap[5] = colormap[7] = colormap[10] = colormap[11] = colormap[12] = colormap[13] = colormap[20] = colormap[21] = colormap[22] = colormap[23] = 255; colormap.resize(1,256,1,3,3); } cimg::mutex(8,0); return colormap; } //! Convert pixel values from sRGB to RGB color spaces. CImg<T>& sRGBtoRGB() { if (is_empty()) return *this; cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),32)) cimg_rofoff(*this,off) { const Tfloat sval = (Tfloat)_data[off]/255, val = (Tfloat)(sval<=0.04045f?sval/12.92f:std::pow((sval + 0.055f)/(1.055f),2.4f)); _data[off] = (T)cimg::cut(val*255,0,255); } return *this; } //! Convert pixel values from sRGB to RGB color spaces \newinstance. CImg<Tfloat> get_sRGBtoRGB() const { return CImg<Tfloat>(*this,false).sRGBtoRGB(); } //! Convert pixel values from RGB to sRGB color spaces. CImg<T>& RGBtosRGB() { if (is_empty()) return *this; cimg_pragma_openmp(parallel for cimg_openmp_if_size(size(),32)) cimg_rofoff(*this,off) { const Tfloat val = (Tfloat)_data[off]/255, sval = (Tfloat)(val<=0.0031308f?val*12.92f:1.055f*std::pow(val,0.416667f) - 0.055f); _data[off] = (T)cimg::cut(sval*255,0,255); } return *this; } //! Convert pixel values from RGB to sRGB color spaces \newinstance. CImg<Tfloat> get_RGBtosRGB() const { return CImg<Tfloat>(*this,false).RGBtosRGB(); } //! Convert pixel values from RGB to HSI color spaces. CImg<T>& RGBtoHSI() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "RGBtoHSI(): Instance is not a RGB image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,256)) for (longT N = 0; N<whd; ++N) { const Tfloat R = (Tfloat)p1[N], G = (Tfloat)p2[N], B = (Tfloat)p3[N], m = cimg::min(R,G,B), M = cimg::max(R,G,B), C = M - m, sum = R + G + B, H = 60*(C==0?0:M==R?cimg::mod((G - B)/C,(Tfloat)6):M==G?(B - R)/C + 2:(R - G)/C + 4), S = sum<=0?0:1 - 3*m/sum, I = sum/(3*255); p1[N] = (T)H; p2[N] = (T)S; p3[N] = (T)I; } return *this; } //! Convert pixel values from RGB to HSI color spaces \newinstance. CImg<Tfloat> get_RGBtoHSI() const { return CImg<Tfloat>(*this,false).RGBtoHSI(); } //! Convert pixel values from HSI to RGB color spaces. CImg<T>& HSItoRGB() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "HSItoRGB(): Instance is not a HSI image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,256)) for (longT N = 0; N<whd; ++N) { const Tfloat H = cimg::mod((Tfloat)p1[N]/60,(Tfloat)6), S = (Tfloat)p2[N], I = (Tfloat)p3[N], Z = 1 - cimg::abs(cimg::mod(H,(Tfloat)2) - 1), C = I*S/(1 + Z), X = C*Z, m = I*(1 - S)/3; Tfloat R, G, B; switch ((int)H) { case 0 : R = C; G = X; B = 0; break; case 1 : R = X; G = C; B = 0; break; case 2 : R = 0; G = C; B = X; break; case 3 : R = 0; G = X; B = C; break; case 4 : R = X; G = 0; B = C; break; default : R = C; G = 0; B = X; } p1[N] = (T)((R + m)*3*255); p2[N] = (T)((G + m)*3*255); p3[N] = (T)((B + m)*3*255); } return *this; } //! Convert pixel values from HSI to RGB color spaces \newinstance. CImg<Tfloat> get_HSItoRGB() const { return CImg< Tuchar>(*this,false).HSItoRGB(); } //! Convert pixel values from RGB to HSL color spaces. CImg<T>& RGBtoHSL() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "RGBtoHSL(): Instance is not a RGB image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,256)) for (longT N = 0; N<whd; ++N) { const Tfloat R = (Tfloat)p1[N], G = (Tfloat)p2[N], B = (Tfloat)p3[N], m = cimg::min(R,G,B), M = cimg::max(R,G,B), C = M - m, H = 60*(C==0?0:M==R?cimg::mod((G - B)/C,(Tfloat)6):M==G?(B - R)/C + 2:(R - G)/C + 4), L = 0.5f*(m + M)/255, S = L==1 || L==0?0:C/(1 - cimg::abs(2*L - 1))/255; p1[N] = (T)H; p2[N] = (T)S; p3[N] = (T)L; } return *this; } //! Convert pixel values from RGB to HSL color spaces \newinstance. CImg<Tfloat> get_RGBtoHSL() const { return CImg<Tfloat>(*this,false).RGBtoHSL(); } //! Convert pixel values from HSL to RGB color spaces. CImg<T>& HSLtoRGB() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "HSLtoRGB(): Instance is not a HSL image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,256)) for (longT N = 0; N<whd; ++N) { const Tfloat H = cimg::mod((Tfloat)p1[N]/60,(Tfloat)6), S = (Tfloat)p2[N], L = (Tfloat)p3[N], C = (1 - cimg::abs(2*L - 1))*S, X = C*(1 - cimg::abs(cimg::mod(H,(Tfloat)2) - 1)), m = L - C/2; Tfloat R, G, B; switch ((int)H) { case 0 : R = C; G = X; B = 0; break; case 1 : R = X; G = C; B = 0; break; case 2 : R = 0; G = C; B = X; break; case 3 : R = 0; G = X; B = C; break; case 4 : R = X; G = 0; B = C; break; default : R = C; G = 0; B = X; } p1[N] = (T)((R + m)*255); p2[N] = (T)((G + m)*255); p3[N] = (T)((B + m)*255); } return *this; } //! Convert pixel values from HSL to RGB color spaces \newinstance. CImg<Tuchar> get_HSLtoRGB() const { return CImg<Tuchar>(*this,false).HSLtoRGB(); } //! Convert pixel values from RGB to HSV color spaces. CImg<T>& RGBtoHSV() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "RGBtoHSV(): Instance is not a RGB image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,256)) for (longT N = 0; N<whd; ++N) { const Tfloat R = (Tfloat)p1[N], G = (Tfloat)p2[N], B = (Tfloat)p3[N], M = cimg::max(R,G,B), C = M - cimg::min(R,G,B), H = 60*(C==0?0:M==R?cimg::mod((G-B)/C,(Tfloat)6):M==G?(B - R)/C + 2:(R - G)/C + 4), S = M<=0?0:C/M; p1[N] = (T)H; p2[N] = (T)S; p3[N] = (T)(M/255); } return *this; } //! Convert pixel values from RGB to HSV color spaces \newinstance. CImg<Tfloat> get_RGBtoHSV() const { return CImg<Tfloat>(*this,false).RGBtoHSV(); } //! Convert pixel values from HSV to RGB color spaces. CImg<T>& HSVtoRGB() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "HSVtoRGB(): Instance is not a HSV image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,256)) for (longT N = 0; N<whd; ++N) { Tfloat H = cimg::mod((Tfloat)p1[N]/60,(Tfloat)6), S = (Tfloat)p2[N], V = (Tfloat)p3[N], C = V*S, X = C*(1 - cimg::abs(cimg::mod(H,(Tfloat)2) - 1)), m = V - C; Tfloat R, G, B; switch ((int)H) { case 0 : R = C; G = X; B = 0; break; case 1 : R = X; G = C; B = 0; break; case 2 : R = 0; G = C; B = X; break; case 3 : R = 0; G = X; B = C; break; case 4 : R = X; G = 0; B = C; break; default : R = C; G = 0; B = X; } p1[N] = (T)((R + m)*255); p2[N] = (T)((G + m)*255); p3[N] = (T)((B + m)*255); } return *this; } //! Convert pixel values from HSV to RGB color spaces \newinstance. CImg<Tuchar> get_HSVtoRGB() const { return CImg<Tuchar>(*this,false).HSVtoRGB(); } //! Convert pixel values from RGB to YCbCr color spaces. CImg<T>& RGBtoYCbCr() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "RGBtoYCbCr(): Instance is not a RGB image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,512)) for (longT N = 0; N<whd; ++N) { const Tfloat R = (Tfloat)p1[N], G = (Tfloat)p2[N], B = (Tfloat)p3[N], Y = (66*R + 129*G + 25*B + 128)/256 + 16, Cb = (-38*R - 74*G + 112*B + 128)/256 + 128, Cr = (112*R - 94*G - 18*B + 128)/256 + 128; p1[N] = (T)cimg::cut(Y,0,255), p2[N] = (T)cimg::cut(Cb,0,255), p3[N] = (T)cimg::cut(Cr,0,255); } return *this; } //! Convert pixel values from RGB to YCbCr color spaces \newinstance. CImg<Tuchar> get_RGBtoYCbCr() const { return CImg<Tuchar>(*this,false).RGBtoYCbCr(); } //! Convert pixel values from RGB to YCbCr color spaces. CImg<T>& YCbCrtoRGB() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "YCbCrtoRGB(): Instance is not a YCbCr image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,512)) for (longT N = 0; N<whd; ++N) { const Tfloat Y = (Tfloat)p1[N] - 16, Cb = (Tfloat)p2[N] - 128, Cr = (Tfloat)p3[N] - 128, R = (298*Y + 409*Cr + 128)/256, G = (298*Y - 100*Cb - 208*Cr + 128)/256, B = (298*Y + 516*Cb + 128)/256; p1[N] = (T)cimg::cut(R,0,255), p2[N] = (T)cimg::cut(G,0,255), p3[N] = (T)cimg::cut(B,0,255); } return *this; } //! Convert pixel values from RGB to YCbCr color spaces \newinstance. CImg<Tuchar> get_YCbCrtoRGB() const { return CImg<Tuchar>(*this,false).YCbCrtoRGB(); } //! Convert pixel values from RGB to YUV color spaces. CImg<T>& RGBtoYUV() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "RGBtoYUV(): Instance is not a RGB image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,16384)) for (longT N = 0; N<whd; ++N) { const Tfloat R = (Tfloat)p1[N]/255, G = (Tfloat)p2[N]/255, B = (Tfloat)p3[N]/255, Y = 0.299f*R + 0.587f*G + 0.114f*B; p1[N] = (T)Y; p2[N] = (T)(0.492f*(B - Y)); p3[N] = (T)(0.877*(R - Y)); } return *this; } //! Convert pixel values from RGB to YUV color spaces \newinstance. CImg<Tfloat> get_RGBtoYUV() const { return CImg<Tfloat>(*this,false).RGBtoYUV(); } //! Convert pixel values from YUV to RGB color spaces. CImg<T>& YUVtoRGB() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "YUVtoRGB(): Instance is not a YUV image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,16384)) for (longT N = 0; N<whd; ++N) { const Tfloat Y = (Tfloat)p1[N], U = (Tfloat)p2[N], V = (Tfloat)p3[N], R = (Y + 1.140f*V)*255, G = (Y - 0.395f*U - 0.581f*V)*255, B = (Y + 2.032f*U)*255; p1[N] = (T)cimg::cut(R,0,255), p2[N] = (T)cimg::cut(G,0,255), p3[N] = (T)cimg::cut(B,0,255); } return *this; } //! Convert pixel values from YUV to RGB color spaces \newinstance. CImg<Tuchar> get_YUVtoRGB() const { return CImg< Tuchar>(*this,false).YUVtoRGB(); } //! Convert pixel values from RGB to CMY color spaces. CImg<T>& RGBtoCMY() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "RGBtoCMY(): Instance is not a RGB image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,2048)) for (longT N = 0; N<whd; ++N) { const Tfloat R = (Tfloat)p1[N], G = (Tfloat)p2[N], B = (Tfloat)p3[N], C = 255 - R, M = 255 - G, Y = 255 - B; p1[N] = (T)cimg::cut(C,0,255), p2[N] = (T)cimg::cut(M,0,255), p3[N] = (T)cimg::cut(Y,0,255); } return *this; } //! Convert pixel values from RGB to CMY color spaces \newinstance. CImg<Tuchar> get_RGBtoCMY() const { return CImg<Tfloat>(*this,false).RGBtoCMY(); } //! Convert pixel values from CMY to RGB color spaces. CImg<T>& CMYtoRGB() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "CMYtoRGB(): Instance is not a CMY image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,2048)) for (longT N = 0; N<whd; ++N) { const Tfloat C = (Tfloat)p1[N], M = (Tfloat)p2[N], Y = (Tfloat)p3[N], R = 255 - C, G = 255 - M, B = 255 - Y; p1[N] = (T)cimg::cut(R,0,255), p2[N] = (T)cimg::cut(G,0,255), p3[N] = (T)cimg::cut(B,0,255); } return *this; } //! Convert pixel values from CMY to RGB color spaces \newinstance. CImg<Tuchar> get_CMYtoRGB() const { return CImg<Tuchar>(*this,false).CMYtoRGB(); } //! Convert pixel values from CMY to CMYK color spaces. CImg<T>& CMYtoCMYK() { return get_CMYtoCMYK().move_to(*this); } //! Convert pixel values from CMY to CMYK color spaces \newinstance. CImg<Tuchar> get_CMYtoCMYK() const { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "CMYtoCMYK(): Instance is not a CMY image.", cimg_instance); CImg<Tfloat> res(_width,_height,_depth,4); const T *ps1 = data(0,0,0,0), *ps2 = data(0,0,0,1), *ps3 = data(0,0,0,2); Tfloat *pd1 = res.data(0,0,0,0), *pd2 = res.data(0,0,0,1), *pd3 = res.data(0,0,0,2), *pd4 = res.data(0,0,0,3); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,1024)) for (longT N = 0; N<whd; ++N) { Tfloat C = (Tfloat)ps1[N], M = (Tfloat)ps2[N], Y = (Tfloat)ps3[N], K = cimg::min(C,M,Y); if (K>=255) C = M = Y = 0; else { const Tfloat K1 = 255 - K; C = 255*(C - K)/K1; M = 255*(M - K)/K1; Y = 255*(Y - K)/K1; } pd1[N] = (Tfloat)cimg::cut(C,0,255), pd2[N] = (Tfloat)cimg::cut(M,0,255), pd3[N] = (Tfloat)cimg::cut(Y,0,255), pd4[N] = (Tfloat)cimg::cut(K,0,255); } return res; } //! Convert pixel values from CMYK to CMY color spaces. CImg<T>& CMYKtoCMY() { return get_CMYKtoCMY().move_to(*this); } //! Convert pixel values from CMYK to CMY color spaces \newinstance. CImg<Tfloat> get_CMYKtoCMY() const { if (_spectrum!=4) throw CImgInstanceException(_cimg_instance "CMYKtoCMY(): Instance is not a CMYK image.", cimg_instance); CImg<Tfloat> res(_width,_height,_depth,3); const T *ps1 = data(0,0,0,0), *ps2 = data(0,0,0,1), *ps3 = data(0,0,0,2), *ps4 = data(0,0,0,3); Tfloat *pd1 = res.data(0,0,0,0), *pd2 = res.data(0,0,0,1), *pd3 = res.data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,1024)) for (longT N = 0; N<whd; ++N) { const Tfloat C = (Tfloat)ps1[N], M = (Tfloat)ps2[N], Y = (Tfloat)ps3[N], K = (Tfloat)ps4[N], K1 = 1 - K/255, nC = C*K1 + K, nM = M*K1 + K, nY = Y*K1 + K; pd1[N] = (Tfloat)cimg::cut(nC,0,255), pd2[N] = (Tfloat)cimg::cut(nM,0,255), pd3[N] = (Tfloat)cimg::cut(nY,0,255); } return res; } //! Convert pixel values from RGB to XYZ color spaces. /** \param use_D65 Tell to use the D65 illuminant (D50 otherwise). **/ CImg<T>& RGBtoXYZ(const bool use_D65=true) { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "RGBtoXYZ(): Instance is not a RGB image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,2048)) for (longT N = 0; N<whd; ++N) { const Tfloat R = (Tfloat)p1[N]/255, G = (Tfloat)p2[N]/255, B = (Tfloat)p3[N]/255; if (use_D65) { // D65 p1[N] = (T)(0.4124564*R + 0.3575761*G + 0.1804375*B); p2[N] = (T)(0.2126729*R + 0.7151522*G + 0.0721750*B); p3[N] = (T)(0.0193339*R + 0.1191920*G + 0.9503041*B); } else { // D50 p1[N] = (T)(0.43603516*R + 0.38511658*G + 0.14305115*B); p2[N] = (T)(0.22248840*R + 0.71690369*G + 0.06060791*B); p3[N] = (T)(0.01391602*R + 0.09706116*G + 0.71392822*B); } } return *this; } //! Convert pixel values from RGB to XYZ color spaces \newinstance. CImg<Tfloat> get_RGBtoXYZ(const bool use_D65=true) const { return CImg<Tfloat>(*this,false).RGBtoXYZ(use_D65); } //! Convert pixel values from XYZ to RGB color spaces. /** \param use_D65 Tell to use the D65 illuminant (D50 otherwise). **/ CImg<T>& XYZtoRGB(const bool use_D65=true) { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "XYZtoRGB(): Instance is not a XYZ image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,2048)) for (longT N = 0; N<whd; ++N) { const Tfloat X = (Tfloat)p1[N]*255, Y = (Tfloat)p2[N]*255, Z = (Tfloat)p3[N]*255; if (use_D65) { p1[N] = (T)cimg::cut(3.2404542*X - 1.5371385*Y - 0.4985314*Z,0,255); p2[N] = (T)cimg::cut(-0.9692660*X + 1.8760108*Y + 0.0415560*Z,0,255); p3[N] = (T)cimg::cut(0.0556434*X - 0.2040259*Y + 1.0572252*Z,0,255); } else { p1[N] = (T)cimg::cut(3.134274799724*X - 1.617275708956*Y - 0.490724283042*Z,0,255); p2[N] = (T)cimg::cut(-0.978795575994*X + 1.916161689117*Y + 0.033453331711*Z,0,255); p3[N] = (T)cimg::cut(0.071976988401*X - 0.228984974402*Y + 1.405718224383*Z,0,255); } } return *this; } //! Convert pixel values from XYZ to RGB color spaces \newinstance. CImg<Tuchar> get_XYZtoRGB(const bool use_D65=true) const { return CImg<Tuchar>(*this,false).XYZtoRGB(use_D65); } //! Convert pixel values from XYZ to Lab color spaces. CImg<T>& XYZtoLab(const bool use_D65=true) { #define _cimg_Labf(x) (24389*(x)>216?cimg::cbrt(x):(24389*(x)/27 + 16)/116) if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "XYZtoLab(): Instance is not a XYZ image.", cimg_instance); const CImg<Tfloat> white = CImg<Tfloat>(1,1,1,3,255).RGBtoXYZ(use_D65); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,128)) for (longT N = 0; N<whd; ++N) { const Tfloat X = (Tfloat)(p1[N]/white[0]), Y = (Tfloat)(p2[N]/white[1]), Z = (Tfloat)(p3[N]/white[2]), fX = (Tfloat)_cimg_Labf(X), fY = (Tfloat)_cimg_Labf(Y), fZ = (Tfloat)_cimg_Labf(Z); p1[N] = (T)cimg::cut(116*fY - 16,0,100); p2[N] = (T)(500*(fX - fY)); p3[N] = (T)(200*(fY - fZ)); } return *this; } //! Convert pixel values from XYZ to Lab color spaces \newinstance. CImg<Tfloat> get_XYZtoLab(const bool use_D65=true) const { return CImg<Tfloat>(*this,false).XYZtoLab(use_D65); } //! Convert pixel values from Lab to XYZ color spaces. CImg<T>& LabtoXYZ(const bool use_D65=true) { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "LabtoXYZ(): Instance is not a Lab image.", cimg_instance); const CImg<Tfloat> white = CImg<Tfloat>(1,1,1,3,255).RGBtoXYZ(use_D65); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,128)) for (longT N = 0; N<whd; ++N) { const Tfloat L = (Tfloat)p1[N], a = (Tfloat)p2[N], b = (Tfloat)p3[N], cY = (L + 16)/116, cZ = cY - b/200, cX = a/500 + cY, X = (Tfloat)(24389*cX>216?cX*cX*cX:(116*cX - 16)*27/24389), Y = (Tfloat)(27*L>216?cY*cY*cY:27*L/24389), Z = (Tfloat)(24389*cZ>216?cZ*cZ*cZ:(116*cZ - 16)*27/24389); p1[N] = (T)(X*white[0]); p2[N] = (T)(Y*white[1]); p3[N] = (T)(Z*white[2]); } return *this; } //! Convert pixel values from Lab to XYZ color spaces \newinstance. CImg<Tfloat> get_LabtoXYZ(const bool use_D65=true) const { return CImg<Tfloat>(*this,false).LabtoXYZ(use_D65); } //! Convert pixel values from XYZ to xyY color spaces. CImg<T>& XYZtoxyY() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "XYZtoxyY(): Instance is not a XYZ image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,4096)) for (longT N = 0; N<whd; ++N) { const Tfloat X = (Tfloat)p1[N], Y = (Tfloat)p2[N], Z = (Tfloat)p3[N], sum = X + Y + Z, nsum = sum>0?sum:1; p1[N] = (T)(X/nsum); p2[N] = (T)(Y/nsum); p3[N] = (T)Y; } return *this; } //! Convert pixel values from XYZ to xyY color spaces \newinstance. CImg<Tfloat> get_XYZtoxyY() const { return CImg<Tfloat>(*this,false).XYZtoxyY(); } //! Convert pixel values from xyY pixels to XYZ color spaces. CImg<T>& xyYtoXYZ() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "xyYtoXYZ(): Instance is not a xyY image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); const longT whd = (longT)width()*height()*depth(); cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,4096)) for (longT N = 0; N<whd; ++N) { const Tfloat px = (Tfloat)p1[N], py = (Tfloat)p2[N], Y = (Tfloat)p3[N], ny = py>0?py:1; p1[N] = (T)(px*Y/ny); p2[N] = (T)Y; p3[N] = (T)((1 - px - py)*Y/ny); } return *this; } //! Convert pixel values from xyY pixels to XYZ color spaces \newinstance. CImg<Tfloat> get_xyYtoXYZ() const { return CImg<Tfloat>(*this,false).xyYtoXYZ(); } //! Convert pixel values from RGB to Lab color spaces. CImg<T>& RGBtoLab(const bool use_D65=true) { return RGBtoXYZ(use_D65).XYZtoLab(use_D65); } //! Convert pixel values from RGB to Lab color spaces \newinstance. CImg<Tfloat> get_RGBtoLab(const bool use_D65=true) const { return CImg<Tfloat>(*this,false).RGBtoLab(use_D65); } //! Convert pixel values from Lab to RGB color spaces. CImg<T>& LabtoRGB(const bool use_D65=true) { return LabtoXYZ().XYZtoRGB(use_D65); } //! Convert pixel values from Lab to RGB color spaces \newinstance. CImg<Tuchar> get_LabtoRGB(const bool use_D65=true) const { return CImg<Tuchar>(*this,false).LabtoRGB(use_D65); } //! Convert pixel values from RGB to xyY color spaces. CImg<T>& RGBtoxyY(const bool use_D65=true) { return RGBtoXYZ(use_D65).XYZtoxyY(); } //! Convert pixel values from RGB to xyY color spaces \newinstance. CImg<Tfloat> get_RGBtoxyY(const bool use_D65=true) const { return CImg<Tfloat>(*this,false).RGBtoxyY(use_D65); } //! Convert pixel values from xyY to RGB color spaces. CImg<T>& xyYtoRGB(const bool use_D65=true) { return xyYtoXYZ().XYZtoRGB(use_D65); } //! Convert pixel values from xyY to RGB color spaces \newinstance. CImg<Tuchar> get_xyYtoRGB(const bool use_D65=true) const { return CImg<Tuchar>(*this,false).xyYtoRGB(use_D65); } //! Convert pixel values from RGB to CMYK color spaces. CImg<T>& RGBtoCMYK() { return RGBtoCMY().CMYtoCMYK(); } //! Convert pixel values from RGB to CMYK color spaces \newinstance. CImg<Tfloat> get_RGBtoCMYK() const { return CImg<Tfloat>(*this,false).RGBtoCMYK(); } //! Convert pixel values from CMYK to RGB color spaces. CImg<T>& CMYKtoRGB() { return CMYKtoCMY().CMYtoRGB(); } //! Convert pixel values from CMYK to RGB color spaces \newinstance. CImg<Tuchar> get_CMYKtoRGB() const { return CImg<Tuchar>(*this,false).CMYKtoRGB(); } //@} //------------------------------------------ // //! \name Geometric / Spatial Manipulation //@{ //------------------------------------------ static float _cimg_lanczos(const float x) { if (x<=-2 || x>=2) return 0; const float a = (float)cimg::PI*x, b = 0.5f*a; return (float)(x?std::sin(a)*std::sin(b)/(a*b):1); } //! Resize image to new dimensions. /** \param size_x Number of columns (new size along the X-axis). \param size_y Number of rows (new size along the Y-axis). \param size_z Number of slices (new size along the Z-axis). \param size_c Number of vector-channels (new size along the C-axis). \param interpolation_type Method of interpolation: - -1 = no interpolation: raw memory resizing. - 0 = no interpolation: additional space is filled according to \p boundary_conditions. - 1 = nearest-neighbor interpolation. - 2 = moving average interpolation. - 3 = linear interpolation. - 4 = grid interpolation. - 5 = cubic interpolation. - 6 = lanczos interpolation. \param boundary_conditions Type of boundary conditions used if necessary. \param centering_x Set centering type (only if \p interpolation_type=0). \param centering_y Set centering type (only if \p interpolation_type=0). \param centering_z Set centering type (only if \p interpolation_type=0). \param centering_c Set centering type (only if \p interpolation_type=0). \note If pd[x,y,z,v]<0, it corresponds to a percentage of the original size (the default value is -100). **/ CImg<T>& resize(const int size_x, const int size_y=-100, const int size_z=-100, const int size_c=-100, const int interpolation_type=1, const unsigned int boundary_conditions=0, const float centering_x = 0, const float centering_y = 0, const float centering_z = 0, const float centering_c = 0) { if (!size_x || !size_y || !size_z || !size_c) return assign(); const unsigned int _sx = (unsigned int)(size_x<0?-size_x*width()/100:size_x), _sy = (unsigned int)(size_y<0?-size_y*height()/100:size_y), _sz = (unsigned int)(size_z<0?-size_z*depth()/100:size_z), _sc = (unsigned int)(size_c<0?-size_c*spectrum()/100:size_c), sx = _sx?_sx:1, sy = _sy?_sy:1, sz = _sz?_sz:1, sc = _sc?_sc:1; if (sx==_width && sy==_height && sz==_depth && sc==_spectrum) return *this; if (is_empty()) return assign(sx,sy,sz,sc,(T)0); if (interpolation_type==-1 && sx*sy*sz*sc==size()) { _width = sx; _height = sy; _depth = sz; _spectrum = sc; return *this; } return get_resize(sx,sy,sz,sc,interpolation_type,boundary_conditions, centering_x,centering_y,centering_z,centering_c).move_to(*this); } //! Resize image to new dimensions \newinstance. CImg<T> get_resize(const int size_x, const int size_y = -100, const int size_z = -100, const int size_c = -100, const int interpolation_type=1, const unsigned int boundary_conditions=0, const float centering_x = 0, const float centering_y = 0, const float centering_z = 0, const float centering_c = 0) const { if (centering_x<0 || centering_x>1 || centering_y<0 || centering_y>1 || centering_z<0 || centering_z>1 || centering_c<0 || centering_c>1) throw CImgArgumentException(_cimg_instance "resize(): Specified centering arguments (%g,%g,%g,%g) are outside range [0,1].", cimg_instance, centering_x,centering_y,centering_z,centering_c); if (!size_x || !size_y || !size_z || !size_c) return CImg<T>(); const unsigned int sx = std::max(1U,(unsigned int)(size_x>=0?size_x:-size_x*width()/100)), sy = std::max(1U,(unsigned int)(size_y>=0?size_y:-size_y*height()/100)), sz = std::max(1U,(unsigned int)(size_z>=0?size_z:-size_z*depth()/100)), sc = std::max(1U,(unsigned int)(size_c>=0?size_c:-size_c*spectrum()/100)); if (sx==_width && sy==_height && sz==_depth && sc==_spectrum) return +*this; if (is_empty()) return CImg<T>(sx,sy,sz,sc,(T)0); CImg<T> res; switch (interpolation_type) { // Raw resizing. // case -1 : std::memcpy(res.assign(sx,sy,sz,sc,(T)0)._data,_data,sizeof(T)*std::min(size(),(ulongT)sx*sy*sz*sc)); break; // No interpolation. // case 0 : { const int xc = (int)(centering_x*((int)sx - width())), yc = (int)(centering_y*((int)sy - height())), zc = (int)(centering_z*((int)sz - depth())), cc = (int)(centering_c*((int)sc - spectrum())); switch (boundary_conditions) { case 3 : { // Mirror res.assign(sx,sy,sz,sc); const int w2 = 2*width(), h2 = 2*height(), d2 = 2*depth(), s2 = 2*spectrum(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),65536)) cimg_forXYZC(res,x,y,z,c) { const int mx = cimg::mod(x - xc,w2), my = cimg::mod(y - yc,h2), mz = cimg::mod(z - zc,d2), mc = cimg::mod(c - cc,s2); res(x,y,z,c) = (*this)(mx<width()?mx:w2 - mx - 1, my<height()?my:h2 - my - 1, mz<depth()?mz:d2 - mz - 1, mc<spectrum()?mc:s2 - mc - 1); } } break; case 2 : { // Periodic res.assign(sx,sy,sz,sc); const int x0 = ((int)xc%width()) - width(), y0 = ((int)yc%height()) - height(), z0 = ((int)zc%depth()) - depth(), c0 = ((int)cc%spectrum()) - spectrum(), dx = width(), dy = height(), dz = depth(), dc = spectrum(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),65536)) for (int c = c0; c<(int)sc; c+=dc) for (int z = z0; z<(int)sz; z+=dz) for (int y = y0; y<(int)sy; y+=dy) for (int x = x0; x<(int)sx; x+=dx) res.draw_image(x,y,z,c,*this); } break; case 1 : { // Neumann res.assign(sx,sy,sz,sc).draw_image(xc,yc,zc,cc,*this); CImg<T> sprite; if (xc>0) { // X-backward res.get_crop(xc,yc,zc,cc,xc,yc + height() - 1,zc + depth() - 1,cc + spectrum() - 1).move_to(sprite); for (int x = xc - 1; x>=0; --x) res.draw_image(x,yc,zc,cc,sprite); } if (xc + width()<(int)sx) { // X-forward res.get_crop(xc + width() - 1,yc,zc,cc,xc + width() - 1,yc + height() - 1, zc + depth() - 1,cc + spectrum() - 1).move_to(sprite); for (int x = xc + width(); x<(int)sx; ++x) res.draw_image(x,yc,zc,cc,sprite); } if (yc>0) { // Y-backward res.get_crop(0,yc,zc,cc,sx - 1,yc,zc + depth() - 1,cc + spectrum() - 1).move_to(sprite); for (int y = yc - 1; y>=0; --y) res.draw_image(0,y,zc,cc,sprite); } if (yc + height()<(int)sy) { // Y-forward res.get_crop(0,yc + height() - 1,zc,cc,sx - 1,yc + height() - 1, zc + depth() - 1,cc + spectrum() - 1).move_to(sprite); for (int y = yc + height(); y<(int)sy; ++y) res.draw_image(0,y,zc,cc,sprite); } if (zc>0) { // Z-backward res.get_crop(0,0,zc,cc,sx - 1,sy - 1,zc,cc + spectrum() - 1).move_to(sprite); for (int z = zc - 1; z>=0; --z) res.draw_image(0,0,z,cc,sprite); } if (zc + depth()<(int)sz) { // Z-forward res.get_crop(0,0,zc +depth() - 1,cc,sx - 1,sy - 1,zc + depth() - 1,cc + spectrum() - 1).move_to(sprite); for (int z = zc + depth(); z<(int)sz; ++z) res.draw_image(0,0,z,cc,sprite); } if (cc>0) { // C-backward res.get_crop(0,0,0,cc,sx - 1,sy - 1,sz - 1,cc).move_to(sprite); for (int c = cc - 1; c>=0; --c) res.draw_image(0,0,0,c,sprite); } if (cc + spectrum()<(int)sc) { // C-forward res.get_crop(0,0,0,cc + spectrum() - 1,sx - 1,sy - 1,sz - 1,cc + spectrum() - 1).move_to(sprite); for (int c = cc + spectrum(); c<(int)sc; ++c) res.draw_image(0,0,0,c,sprite); } } break; default : // Dirichlet res.assign(sx,sy,sz,sc,(T)0).draw_image(xc,yc,zc,cc,*this); } break; } break; // Nearest neighbor interpolation. // case 1 : { res.assign(sx,sy,sz,sc); CImg<ulongT> off_x(sx), off_y(sy + 1), off_z(sz + 1), off_c(sc + 1); const ulongT wh = (ulongT)_width*_height, whd = (ulongT)_width*_height*_depth, sxy = (ulongT)sx*sy, sxyz = (ulongT)sx*sy*sz, one = (ulongT)1; if (sx==_width) off_x.fill(1); else { ulongT *poff_x = off_x._data, curr = 0; cimg_forX(res,x) { const ulongT old = curr; curr = (x + one)*_width/sx; *(poff_x++) = curr - old; } } if (sy==_height) off_y.fill(_width); else { ulongT *poff_y = off_y._data, curr = 0; cimg_forY(res,y) { const ulongT old = curr; curr = (y + one)*_height/sy; *(poff_y++) = _width*(curr - old); } *poff_y = 0; } if (sz==_depth) off_z.fill(wh); else { ulongT *poff_z = off_z._data, curr = 0; cimg_forZ(res,z) { const ulongT old = curr; curr = (z + one)*_depth/sz; *(poff_z++) = wh*(curr - old); } *poff_z = 0; } if (sc==_spectrum) off_c.fill(whd); else { ulongT *poff_c = off_c._data, curr = 0; cimg_forC(res,c) { const ulongT old = curr; curr = (c + one)*_spectrum/sc; *(poff_c++) = whd*(curr - old); } *poff_c = 0; } T *ptrd = res._data; const T* ptrc = _data; const ulongT *poff_c = off_c._data; for (unsigned int c = 0; c<sc; ) { const T *ptrz = ptrc; const ulongT *poff_z = off_z._data; for (unsigned int z = 0; z<sz; ) { const T *ptry = ptrz; const ulongT *poff_y = off_y._data; for (unsigned int y = 0; y<sy; ) { const T *ptrx = ptry; const ulongT *poff_x = off_x._data; cimg_forX(res,x) { *(ptrd++) = *ptrx; ptrx+=*(poff_x++); } ++y; ulongT dy = *(poff_y++); for ( ; !dy && y<dy; std::memcpy(ptrd,ptrd - sx,sizeof(T)*sx), ++y, ptrd+=sx, dy = *(poff_y++)) {} ptry+=dy; } ++z; ulongT dz = *(poff_z++); for ( ; !dz && z<dz; std::memcpy(ptrd,ptrd - sxy,sizeof(T)*sxy), ++z, ptrd+=sxy, dz = *(poff_z++)) {} ptrz+=dz; } ++c; ulongT dc = *(poff_c++); for ( ; !dc && c<dc; std::memcpy(ptrd,ptrd - sxyz,sizeof(T)*sxyz), ++c, ptrd+=sxyz, dc = *(poff_c++)) {} ptrc+=dc; } } break; // Moving average. // case 2 : { bool instance_first = true; if (sx!=_width) { CImg<Tfloat> tmp(sx,_height,_depth,_spectrum,0); for (unsigned int a = _width*sx, b = _width, c = sx, s = 0, t = 0; a; ) { const unsigned int d = std::min(b,c); a-=d; b-=d; c-=d; cimg_forYZC(tmp,y,z,v) tmp(t,y,z,v)+=(Tfloat)(*this)(s,y,z,v)*d; if (!b) { cimg_forYZC(tmp,y,z,v) tmp(t,y,z,v)/=_width; ++t; b = _width; } if (!c) { ++s; c = sx; } } tmp.move_to(res); instance_first = false; } if (sy!=_height) { CImg<Tfloat> tmp(sx,sy,_depth,_spectrum,0); for (unsigned int a = _height*sy, b = _height, c = sy, s = 0, t = 0; a; ) { const unsigned int d = std::min(b,c); a-=d; b-=d; c-=d; if (instance_first) cimg_forXZC(tmp,x,z,v) tmp(x,t,z,v)+=(Tfloat)(*this)(x,s,z,v)*d; else cimg_forXZC(tmp,x,z,v) tmp(x,t,z,v)+=(Tfloat)res(x,s,z,v)*d; if (!b) { cimg_forXZC(tmp,x,z,v) tmp(x,t,z,v)/=_height; ++t; b = _height; } if (!c) { ++s; c = sy; } } tmp.move_to(res); instance_first = false; } if (sz!=_depth) { CImg<Tfloat> tmp(sx,sy,sz,_spectrum,0); for (unsigned int a = _depth*sz, b = _depth, c = sz, s = 0, t = 0; a; ) { const unsigned int d = std::min(b,c); a-=d; b-=d; c-=d; if (instance_first) cimg_forXYC(tmp,x,y,v) tmp(x,y,t,v)+=(Tfloat)(*this)(x,y,s,v)*d; else cimg_forXYC(tmp,x,y,v) tmp(x,y,t,v)+=(Tfloat)res(x,y,s,v)*d; if (!b) { cimg_forXYC(tmp,x,y,v) tmp(x,y,t,v)/=_depth; ++t; b = _depth; } if (!c) { ++s; c = sz; } } tmp.move_to(res); instance_first = false; } if (sc!=_spectrum) { CImg<Tfloat> tmp(sx,sy,sz,sc,0); for (unsigned int a = _spectrum*sc, b = _spectrum, c = sc, s = 0, t = 0; a; ) { const unsigned int d = std::min(b,c); a-=d; b-=d; c-=d; if (instance_first) cimg_forXYZ(tmp,x,y,z) tmp(x,y,z,t)+=(Tfloat)(*this)(x,y,z,s)*d; else cimg_forXYZ(tmp,x,y,z) tmp(x,y,z,t)+=(Tfloat)res(x,y,z,s)*d; if (!b) { cimg_forXYZ(tmp,x,y,z) tmp(x,y,z,t)/=_spectrum; ++t; b = _spectrum; } if (!c) { ++s; c = sc; } } tmp.move_to(res); instance_first = false; } } break; // Linear interpolation. // case 3 : { CImg<uintT> off(cimg::max(sx,sy,sz,sc)); CImg<doubleT> foff(off._width); CImg<T> resx, resy, resz, resc; double curr, old; if (sx!=_width) { if (_width==1) get_resize(sx,_height,_depth,_spectrum,1).move_to(resx); else if (_width>sx) get_resize(sx,_height,_depth,_spectrum,2).move_to(resx); else { const double fx = (!boundary_conditions && sx>_width)?(sx>1?(_width - 1.)/(sx - 1):0): (double)_width/sx; resx.assign(sx,_height,_depth,_spectrum); curr = old = 0; { unsigned int *poff = off._data; double *pfoff = foff._data; cimg_forX(resx,x) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr = std::min(width() - 1.,curr + fx); *(poff++) = (unsigned int)curr - (unsigned int)old; } } cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(resx.size(),65536)) cimg_forYZC(resx,y,z,c) { const T *ptrs = data(0,y,z,c), *const ptrsmax = ptrs + _width - 1; T *ptrd = resx.data(0,y,z,c); const unsigned int *poff = off._data; const double *pfoff = foff._data; cimg_forX(resx,x) { const double alpha = *(pfoff++); const T val1 = *ptrs, val2 = ptrs<ptrsmax?*(ptrs + 1):val1; *(ptrd++) = (T)((1 - alpha)*val1 + alpha*val2); ptrs+=*(poff++); } } } } else resx.assign(*this,true); if (sy!=_height) { if (_height==1) resx.get_resize(sx,sy,_depth,_spectrum,1).move_to(resy); else { if (_height>sy) resx.get_resize(sx,sy,_depth,_spectrum,2).move_to(resy); else { const double fy = (!boundary_conditions && sy>_height)?(sy>1?(_height - 1.)/(sy - 1):0): (double)_height/sy; resy.assign(sx,sy,_depth,_spectrum); curr = old = 0; { unsigned int *poff = off._data; double *pfoff = foff._data; cimg_forY(resy,y) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr = std::min(height() - 1.,curr + fy); *(poff++) = sx*((unsigned int)curr - (unsigned int)old); } } cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(resy.size(),65536)) cimg_forXZC(resy,x,z,c) { const T *ptrs = resx.data(x,0,z,c), *const ptrsmax = ptrs + (_height - 1)*sx; T *ptrd = resy.data(x,0,z,c); const unsigned int *poff = off._data; const double *pfoff = foff._data; cimg_forY(resy,y) { const double alpha = *(pfoff++); const T val1 = *ptrs, val2 = ptrs<ptrsmax?*(ptrs + sx):val1; *ptrd = (T)((1 - alpha)*val1 + alpha*val2); ptrd+=sx; ptrs+=*(poff++); } } } } resx.assign(); } else resy.assign(resx,true); if (sz!=_depth) { if (_depth==1) resy.get_resize(sx,sy,sz,_spectrum,1).move_to(resz); else { if (_depth>sz) resy.get_resize(sx,sy,sz,_spectrum,2).move_to(resz); else { const double fz = (!boundary_conditions && sz>_depth)?(sz>1?(_depth - 1.)/(sz - 1):0): (double)_depth/sz; const unsigned int sxy = sx*sy; resz.assign(sx,sy,sz,_spectrum); curr = old = 0; { unsigned int *poff = off._data; double *pfoff = foff._data; cimg_forZ(resz,z) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr = std::min(depth() - 1.,curr + fz); *(poff++) = sxy*((unsigned int)curr - (unsigned int)old); } } cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(resz.size(),65536)) cimg_forXYC(resz,x,y,c) { const T *ptrs = resy.data(x,y,0,c), *const ptrsmax = ptrs + (_depth - 1)*sxy; T *ptrd = resz.data(x,y,0,c); const unsigned int *poff = off._data; const double *pfoff = foff._data; cimg_forZ(resz,z) { const double alpha = *(pfoff++); const T val1 = *ptrs, val2 = ptrs<ptrsmax?*(ptrs + sxy):val1; *ptrd = (T)((1 - alpha)*val1 + alpha*val2); ptrd+=sxy; ptrs+=*(poff++); } } } } resy.assign(); } else resz.assign(resy,true); if (sc!=_spectrum) { if (_spectrum==1) resz.get_resize(sx,sy,sz,sc,1).move_to(resc); else { if (_spectrum>sc) resz.get_resize(sx,sy,sz,sc,2).move_to(resc); else { const double fc = (!boundary_conditions && sc>_spectrum)?(sc>1?(_spectrum - 1.)/(sc - 1):0): (double)_spectrum/sc; const unsigned int sxyz = sx*sy*sz; resc.assign(sx,sy,sz,sc); curr = old = 0; { unsigned int *poff = off._data; double *pfoff = foff._data; cimg_forC(resc,c) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr = std::min(spectrum() - 1.,curr + fc); *(poff++) = sxyz*((unsigned int)curr - (unsigned int)old); } } cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(resc.size(),65536)) cimg_forXYZ(resc,x,y,z) { const T *ptrs = resz.data(x,y,z,0), *const ptrsmax = ptrs + (_spectrum - 1)*sxyz; T *ptrd = resc.data(x,y,z,0); const unsigned int *poff = off._data; const double *pfoff = foff._data; cimg_forC(resc,c) { const double alpha = *(pfoff++); const T val1 = *ptrs, val2 = ptrs<ptrsmax?*(ptrs + sxyz):val1; *ptrd = (T)((1 - alpha)*val1 + alpha*val2); ptrd+=sxyz; ptrs+=*(poff++); } } } } resz.assign(); } else resc.assign(resz,true); return resc._is_shared?(resz._is_shared?(resy._is_shared?(resx._is_shared?(+(*this)):resx):resy):resz):resc; } break; // Grid interpolation. // case 4 : { CImg<T> resx, resy, resz, resc; if (sx!=_width) { if (sx<_width) get_resize(sx,_height,_depth,_spectrum,1).move_to(resx); else { resx.assign(sx,_height,_depth,_spectrum,(T)0); const int dx = (int)(2*sx), dy = 2*width(); int err = (int)(dy + centering_x*(sx*dy/width() - dy)), xs = 0; cimg_forX(resx,x) if ((err-=dy)<=0) { cimg_forYZC(resx,y,z,c) resx(x,y,z,c) = (*this)(xs,y,z,c); ++xs; err+=dx; } } } else resx.assign(*this,true); if (sy!=_height) { if (sy<_height) resx.get_resize(sx,sy,_depth,_spectrum,1).move_to(resy); else { resy.assign(sx,sy,_depth,_spectrum,(T)0); const int dx = (int)(2*sy), dy = 2*height(); int err = (int)(dy + centering_y*(sy*dy/height() - dy)), ys = 0; cimg_forY(resy,y) if ((err-=dy)<=0) { cimg_forXZC(resy,x,z,c) resy(x,y,z,c) = resx(x,ys,z,c); ++ys; err+=dx; } } resx.assign(); } else resy.assign(resx,true); if (sz!=_depth) { if (sz<_depth) resy.get_resize(sx,sy,sz,_spectrum,1).move_to(resz); else { resz.assign(sx,sy,sz,_spectrum,(T)0); const int dx = (int)(2*sz), dy = 2*depth(); int err = (int)(dy + centering_z*(sz*dy/depth() - dy)), zs = 0; cimg_forZ(resz,z) if ((err-=dy)<=0) { cimg_forXYC(resz,x,y,c) resz(x,y,z,c) = resy(x,y,zs,c); ++zs; err+=dx; } } resy.assign(); } else resz.assign(resy,true); if (sc!=_spectrum) { if (sc<_spectrum) resz.get_resize(sx,sy,sz,sc,1).move_to(resc); else { resc.assign(sx,sy,sz,sc,(T)0); const int dx = (int)(2*sc), dy = 2*spectrum(); int err = (int)(dy + centering_c*(sc*dy/spectrum() - dy)), cs = 0; cimg_forC(resc,c) if ((err-=dy)<=0) { cimg_forXYZ(resc,x,y,z) resc(x,y,z,c) = resz(x,y,z,cs); ++cs; err+=dx; } } resz.assign(); } else resc.assign(resz,true); return resc._is_shared?(resz._is_shared?(resy._is_shared?(resx._is_shared?(+(*this)):resx):resy):resz):resc; } break; // Cubic interpolation. // case 5 : { const Tfloat vmin = (Tfloat)cimg::type<T>::min(), vmax = (Tfloat)cimg::type<T>::max(); CImg<uintT> off(cimg::max(sx,sy,sz,sc)); CImg<doubleT> foff(off._width); CImg<T> resx, resy, resz, resc; double curr, old; if (sx!=_width) { if (_width==1) get_resize(sx,_height,_depth,_spectrum,1).move_to(resx); else { if (_width>sx) get_resize(sx,_height,_depth,_spectrum,2).move_to(resx); else { const double fx = (!boundary_conditions && sx>_width)?(sx>1?(_width - 1.)/(sx - 1):0): (double)_width/sx; resx.assign(sx,_height,_depth,_spectrum); curr = old = 0; { unsigned int *poff = off._data; double *pfoff = foff._data; cimg_forX(resx,x) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr = std::min(width() - 1.,curr + fx); *(poff++) = (unsigned int)curr - (unsigned int)old; } } cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(resx.size(),65536)) cimg_forYZC(resx,y,z,c) { const T *const ptrs0 = data(0,y,z,c), *ptrs = ptrs0, *const ptrsmax = ptrs + (_width - 2); T *ptrd = resx.data(0,y,z,c); const unsigned int *poff = off._data; const double *pfoff = foff._data; cimg_forX(resx,x) { const double t = *(pfoff++), val1 = (double)*ptrs, val0 = ptrs>ptrs0?(double)*(ptrs - 1):val1, val2 = ptrs<=ptrsmax?(double)*(ptrs + 1):val1, val3 = ptrs<ptrsmax?(double)*(ptrs + 2):val2, val = val1 + 0.5f*(t*(-val0 + val2) + t*t*(2*val0 - 5*val1 + 4*val2 - val3) + t*t*t*(-val0 + 3*val1 - 3*val2 + val3)); *(ptrd++) = (T)(val<vmin?vmin:val>vmax?vmax:val); ptrs+=*(poff++); } } } } } else resx.assign(*this,true); if (sy!=_height) { if (_height==1) resx.get_resize(sx,sy,_depth,_spectrum,1).move_to(resy); else { if (_height>sy) resx.get_resize(sx,sy,_depth,_spectrum,2).move_to(resy); else { const double fy = (!boundary_conditions && sy>_height)?(sy>1?(_height - 1.)/(sy - 1):0): (double)_height/sy; resy.assign(sx,sy,_depth,_spectrum); curr = old = 0; { unsigned int *poff = off._data; double *pfoff = foff._data; cimg_forY(resy,y) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr = std::min(height() - 1.,curr + fy); *(poff++) = sx*((unsigned int)curr - (unsigned int)old); } } cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(resy.size(),65536)) cimg_forXZC(resy,x,z,c) { const T *const ptrs0 = resx.data(x,0,z,c), *ptrs = ptrs0, *const ptrsmax = ptrs + (_height - 2)*sx; T *ptrd = resy.data(x,0,z,c); const unsigned int *poff = off._data; const double *pfoff = foff._data; cimg_forY(resy,y) { const double t = *(pfoff++), val1 = (double)*ptrs, val0 = ptrs>ptrs0?(double)*(ptrs - sx):val1, val2 = ptrs<=ptrsmax?(double)*(ptrs + sx):val1, val3 = ptrs<ptrsmax?(double)*(ptrs + 2*sx):val2, val = val1 + 0.5f*(t*(-val0 + val2) + t*t*(2*val0 - 5*val1 + 4*val2 - val3) + t*t*t*(-val0 + 3*val1 - 3*val2 + val3)); *ptrd = (T)(val<vmin?vmin:val>vmax?vmax:val); ptrd+=sx; ptrs+=*(poff++); } } } } resx.assign(); } else resy.assign(resx,true); if (sz!=_depth) { if (_depth==1) resy.get_resize(sx,sy,sz,_spectrum,1).move_to(resz); else { if (_depth>sz) resy.get_resize(sx,sy,sz,_spectrum,2).move_to(resz); else { const double fz = (!boundary_conditions && sz>_depth)?(sz>1?(_depth - 1.)/(sz - 1):0): (double)_depth/sz; const unsigned int sxy = sx*sy; resz.assign(sx,sy,sz,_spectrum); curr = old = 0; { unsigned int *poff = off._data; double *pfoff = foff._data; cimg_forZ(resz,z) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr = std::min(depth() - 1.,curr + fz); *(poff++) = sxy*((unsigned int)curr - (unsigned int)old); } } cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(resz.size(),65536)) cimg_forXYC(resz,x,y,c) { const T *const ptrs0 = resy.data(x,y,0,c), *ptrs = ptrs0, *const ptrsmax = ptrs + (_depth - 2)*sxy; T *ptrd = resz.data(x,y,0,c); const unsigned int *poff = off._data; const double *pfoff = foff._data; cimg_forZ(resz,z) { const double t = *(pfoff++), val1 = (double)*ptrs, val0 = ptrs>ptrs0?(double)*(ptrs - sxy):val1, val2 = ptrs<=ptrsmax?(double)*(ptrs + sxy):val1, val3 = ptrs<ptrsmax?(double)*(ptrs + 2*sxy):val2, val = val1 + 0.5f*(t*(-val0 + val2) + t*t*(2*val0 - 5*val1 + 4*val2 - val3) + t*t*t*(-val0 + 3*val1 - 3*val2 + val3)); *ptrd = (T)(val<vmin?vmin:val>vmax?vmax:val); ptrd+=sxy; ptrs+=*(poff++); } } } } resy.assign(); } else resz.assign(resy,true); if (sc!=_spectrum) { if (_spectrum==1) resz.get_resize(sx,sy,sz,sc,1).move_to(resc); else { if (_spectrum>sc) resz.get_resize(sx,sy,sz,sc,2).move_to(resc); else { const double fc = (!boundary_conditions && sc>_spectrum)?(sc>1?(_spectrum - 1.)/(sc - 1):0): (double)_spectrum/sc; const unsigned int sxyz = sx*sy*sz; resc.assign(sx,sy,sz,sc); curr = old = 0; { unsigned int *poff = off._data; double *pfoff = foff._data; cimg_forC(resc,c) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr = std::min(spectrum() - 1.,curr + fc); *(poff++) = sxyz*((unsigned int)curr - (unsigned int)old); } } cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(resc.size(),65536)) cimg_forXYZ(resc,x,y,z) { const T *const ptrs0 = resz.data(x,y,z,0), *ptrs = ptrs0, *const ptrsmax = ptrs + (_spectrum - 2)*sxyz; T *ptrd = resc.data(x,y,z,0); const unsigned int *poff = off._data; const double *pfoff = foff._data; cimg_forC(resc,c) { const double t = *(pfoff++), val1 = (double)*ptrs, val0 = ptrs>ptrs0?(double)*(ptrs - sxyz):val1, val2 = ptrs<=ptrsmax?(double)*(ptrs + sxyz):val1, val3 = ptrs<ptrsmax?(double)*(ptrs + 2*sxyz):val2, val = val1 + 0.5f*(t*(-val0 + val2) + t*t*(2*val0 - 5*val1 + 4*val2 - val3) + t*t*t*(-val0 + 3*val1 - 3*val2 + val3)); *ptrd = (T)(val<vmin?vmin:val>vmax?vmax:val); ptrd+=sxyz; ptrs+=*(poff++); } } } } resz.assign(); } else resc.assign(resz,true); return resc._is_shared?(resz._is_shared?(resy._is_shared?(resx._is_shared?(+(*this)):resx):resy):resz):resc; } break; // Lanczos interpolation. // case 6 : { const double vmin = (double)cimg::type<T>::min(), vmax = (double)cimg::type<T>::max(); CImg<uintT> off(cimg::max(sx,sy,sz,sc)); CImg<doubleT> foff(off._width); CImg<T> resx, resy, resz, resc; double curr, old; if (sx!=_width) { if (_width==1) get_resize(sx,_height,_depth,_spectrum,1).move_to(resx); else { if (_width>sx) get_resize(sx,_height,_depth,_spectrum,2).move_to(resx); else { const double fx = (!boundary_conditions && sx>_width)?(sx>1?(_width - 1.)/(sx - 1):0): (double)_width/sx; resx.assign(sx,_height,_depth,_spectrum); curr = old = 0; { unsigned int *poff = off._data; double *pfoff = foff._data; cimg_forX(resx,x) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr = std::min(width() - 1.,curr + fx); *(poff++) = (unsigned int)curr - (unsigned int)old; } } cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(resx.size(),65536)) cimg_forYZC(resx,y,z,c) { const T *const ptrs0 = data(0,y,z,c), *ptrs = ptrs0, *const ptrsmin = ptrs0 + 1, *const ptrsmax = ptrs0 + (_width - 2); T *ptrd = resx.data(0,y,z,c); const unsigned int *poff = off._data; const double *pfoff = foff._data; cimg_forX(resx,x) { const double t = *(pfoff++), w0 = _cimg_lanczos(t + 2), w1 = _cimg_lanczos(t + 1), w2 = _cimg_lanczos(t), w3 = _cimg_lanczos(t - 1), w4 = _cimg_lanczos(t - 2), val2 = (double)*ptrs, val1 = ptrs>=ptrsmin?(double)*(ptrs - 1):val2, val0 = ptrs>ptrsmin?(double)*(ptrs - 2):val1, val3 = ptrs<=ptrsmax?(double)*(ptrs + 1):val2, val4 = ptrs<ptrsmax?(double)*(ptrs + 2):val3, val = (val0*w0 + val1*w1 + val2*w2 + val3*w3 + val4*w4)/(w1 + w2 + w3 + w4); *(ptrd++) = (T)(val<vmin?vmin:val>vmax?vmax:val); ptrs+=*(poff++); } } } } } else resx.assign(*this,true); if (sy!=_height) { if (_height==1) resx.get_resize(sx,sy,_depth,_spectrum,1).move_to(resy); else { if (_height>sy) resx.get_resize(sx,sy,_depth,_spectrum,2).move_to(resy); else { const double fy = (!boundary_conditions && sy>_height)?(sy>1?(_height - 1.)/(sy - 1):0): (double)_height/sy; resy.assign(sx,sy,_depth,_spectrum); curr = old = 0; { unsigned int *poff = off._data; double *pfoff = foff._data; cimg_forY(resy,y) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr = std::min(height() - 1.,curr + fy); *(poff++) = sx*((unsigned int)curr - (unsigned int)old); } } cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(resy.size(),65536)) cimg_forXZC(resy,x,z,c) { const T *const ptrs0 = resx.data(x,0,z,c), *ptrs = ptrs0, *const ptrsmin = ptrs0 + sx, *const ptrsmax = ptrs0 + (_height - 2)*sx; T *ptrd = resy.data(x,0,z,c); const unsigned int *poff = off._data; const double *pfoff = foff._data; cimg_forY(resy,y) { const double t = *(pfoff++), w0 = _cimg_lanczos(t + 2), w1 = _cimg_lanczos(t + 1), w2 = _cimg_lanczos(t), w3 = _cimg_lanczos(t - 1), w4 = _cimg_lanczos(t - 2), val2 = (double)*ptrs, val1 = ptrs>=ptrsmin?(double)*(ptrs - sx):val2, val0 = ptrs>ptrsmin?(double)*(ptrs - 2*sx):val1, val3 = ptrs<=ptrsmax?(double)*(ptrs + sx):val2, val4 = ptrs<ptrsmax?(double)*(ptrs + 2*sx):val3, val = (val0*w0 + val1*w1 + val2*w2 + val3*w3 + val4*w4)/(w1 + w2 + w3 + w4); *ptrd = (T)(val<vmin?vmin:val>vmax?vmax:val); ptrd+=sx; ptrs+=*(poff++); } } } } resx.assign(); } else resy.assign(resx,true); if (sz!=_depth) { if (_depth==1) resy.get_resize(sx,sy,sz,_spectrum,1).move_to(resz); else { if (_depth>sz) resy.get_resize(sx,sy,sz,_spectrum,2).move_to(resz); else { const double fz = (!boundary_conditions && sz>_depth)?(sz>1?(_depth - 1.)/(sz - 1):0): (double)_depth/sz; const unsigned int sxy = sx*sy; resz.assign(sx,sy,sz,_spectrum); curr = old = 0; { unsigned int *poff = off._data; double *pfoff = foff._data; cimg_forZ(resz,z) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr = std::min(depth() - 1.,curr + fz); *(poff++) = sxy*((unsigned int)curr - (unsigned int)old); } } cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(resz.size(),65536)) cimg_forXYC(resz,x,y,c) { const T *const ptrs0 = resy.data(x,y,0,c), *ptrs = ptrs0, *const ptrsmin = ptrs0 + sxy, *const ptrsmax = ptrs0 + (_depth - 2)*sxy; T *ptrd = resz.data(x,y,0,c); const unsigned int *poff = off._data; const double *pfoff = foff._data; cimg_forZ(resz,z) { const double t = *(pfoff++), w0 = _cimg_lanczos(t + 2), w1 = _cimg_lanczos(t + 1), w2 = _cimg_lanczos(t), w3 = _cimg_lanczos(t - 1), w4 = _cimg_lanczos(t - 2), val2 = (double)*ptrs, val1 = ptrs>=ptrsmin?(double)*(ptrs - sxy):val2, val0 = ptrs>ptrsmin?(double)*(ptrs - 2*sxy):val1, val3 = ptrs<=ptrsmax?(double)*(ptrs + sxy):val2, val4 = ptrs<ptrsmax?(double)*(ptrs + 2*sxy):val3, val = (val0*w0 + val1*w1 + val2*w2 + val3*w3 + val4*w4)/(w1 + w2 + w3 + w4); *ptrd = (T)(val<vmin?vmin:val>vmax?vmax:val); ptrd+=sxy; ptrs+=*(poff++); } } } } resy.assign(); } else resz.assign(resy,true); if (sc!=_spectrum) { if (_spectrum==1) resz.get_resize(sx,sy,sz,sc,1).move_to(resc); else { if (_spectrum>sc) resz.get_resize(sx,sy,sz,sc,2).move_to(resc); else { const double fc = (!boundary_conditions && sc>_spectrum)?(sc>1?(_spectrum - 1.)/(sc - 1):0): (double)_spectrum/sc; const unsigned int sxyz = sx*sy*sz; resc.assign(sx,sy,sz,sc); curr = old = 0; { unsigned int *poff = off._data; double *pfoff = foff._data; cimg_forC(resc,c) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr = std::min(spectrum() - 1.,curr + fc); *(poff++) = sxyz*((unsigned int)curr - (unsigned int)old); } } cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(resc.size(),65536)) cimg_forXYZ(resc,x,y,z) { const T *const ptrs0 = resz.data(x,y,z,0), *ptrs = ptrs0, *const ptrsmin = ptrs0 + sxyz, *const ptrsmax = ptrs + (_spectrum - 2)*sxyz; T *ptrd = resc.data(x,y,z,0); const unsigned int *poff = off._data; const double *pfoff = foff._data; cimg_forC(resc,c) { const double t = *(pfoff++), w0 = _cimg_lanczos(t + 2), w1 = _cimg_lanczos(t + 1), w2 = _cimg_lanczos(t), w3 = _cimg_lanczos(t - 1), w4 = _cimg_lanczos(t - 2), val2 = (double)*ptrs, val1 = ptrs>=ptrsmin?(double)*(ptrs - sxyz):val2, val0 = ptrs>ptrsmin?(double)*(ptrs - 2*sxyz):val1, val3 = ptrs<=ptrsmax?(double)*(ptrs + sxyz):val2, val4 = ptrs<ptrsmax?(double)*(ptrs + 2*sxyz):val3, val = (val0*w0 + val1*w1 + val2*w2 + val3*w3 + val4*w4)/(w1 + w2 + w3 + w4); *ptrd = (T)(val<vmin?vmin:val>vmax?vmax:val); ptrd+=sxyz; ptrs+=*(poff++); } } } } resz.assign(); } else resc.assign(resz,true); return resc._is_shared?(resz._is_shared?(resy._is_shared?(resx._is_shared?(+(*this)):resx):resy):resz):resc; } break; // Unknow interpolation. // default : throw CImgArgumentException(_cimg_instance "resize(): Invalid specified interpolation %d " "(should be { -1=raw | 0=none | 1=nearest | 2=average | 3=linear | 4=grid | " "5=cubic | 6=lanczos }).", cimg_instance, interpolation_type); } return res; } //! Resize image to dimensions of another image. /** \param src Reference image used for dimensions. \param interpolation_type Interpolation method. \param boundary_conditions Boundary conditions. \param centering_x Set centering type (only if \p interpolation_type=0). \param centering_y Set centering type (only if \p interpolation_type=0). \param centering_z Set centering type (only if \p interpolation_type=0). \param centering_c Set centering type (only if \p interpolation_type=0). **/ template<typename t> CImg<T>& resize(const CImg<t>& src, const int interpolation_type=1, const unsigned int boundary_conditions=0, const float centering_x = 0, const float centering_y = 0, const float centering_z = 0, const float centering_c = 0) { return resize(src._width,src._height,src._depth,src._spectrum,interpolation_type,boundary_conditions, centering_x,centering_y,centering_z,centering_c); } //! Resize image to dimensions of another image \newinstance. template<typename t> CImg<T> get_resize(const CImg<t>& src, const int interpolation_type=1, const unsigned int boundary_conditions=0, const float centering_x = 0, const float centering_y = 0, const float centering_z = 0, const float centering_c = 0) const { return get_resize(src._width,src._height,src._depth,src._spectrum,interpolation_type,boundary_conditions, centering_x,centering_y,centering_z,centering_c); } //! Resize image to dimensions of a display window. /** \param disp Reference display window used for dimensions. \param interpolation_type Interpolation method. \param boundary_conditions Boundary conditions. \param centering_x Set centering type (only if \p interpolation_type=0). \param centering_y Set centering type (only if \p interpolation_type=0). \param centering_z Set centering type (only if \p interpolation_type=0). \param centering_c Set centering type (only if \p interpolation_type=0). **/ CImg<T>& resize(const CImgDisplay& disp, const int interpolation_type=1, const unsigned int boundary_conditions=0, const float centering_x = 0, const float centering_y = 0, const float centering_z = 0, const float centering_c = 0) { return resize(disp.width(),disp.height(),_depth,_spectrum,interpolation_type,boundary_conditions, centering_x,centering_y,centering_z,centering_c); } //! Resize image to dimensions of a display window \newinstance. CImg<T> get_resize(const CImgDisplay& disp, const int interpolation_type=1, const unsigned int boundary_conditions=0, const float centering_x = 0, const float centering_y = 0, const float centering_z = 0, const float centering_c = 0) const { return get_resize(disp.width(),disp.height(),_depth,_spectrum,interpolation_type,boundary_conditions, centering_x,centering_y,centering_z,centering_c); } //! Resize image to half-size along XY axes, using an optimized filter. CImg<T>& resize_halfXY() { return get_resize_halfXY().move_to(*this); } //! Resize image to half-size along XY axes, using an optimized filter \newinstance. CImg<T> get_resize_halfXY() const { if (is_empty()) return *this; static const Tfloat kernel[9] = { 0.07842776544f, 0.1231940459f, 0.07842776544f, 0.1231940459f, 0.1935127547f, 0.1231940459f, 0.07842776544f, 0.1231940459f, 0.07842776544f }; CImg<T> I(9), res(_width/2,_height/2,_depth,_spectrum); T *ptrd = res._data; cimg_forZC(*this,z,c) cimg_for3x3(*this,x,y,z,c,I,T) if (x%2 && y%2) *(ptrd++) = (T) (I[0]*kernel[0] + I[1]*kernel[1] + I[2]*kernel[2] + I[3]*kernel[3] + I[4]*kernel[4] + I[5]*kernel[5] + I[6]*kernel[6] + I[7]*kernel[7] + I[8]*kernel[8]); return res; } //! Resize image to double-size, using the Scale2X algorithm. /** \note Use anisotropic upscaling algorithm <a href="http://scale2x.sourceforge.net/algorithm.html">described here</a>. **/ CImg<T>& resize_doubleXY() { return get_resize_doubleXY().move_to(*this); } //! Resize image to double-size, using the Scale2X algorithm \newinstance. CImg<T> get_resize_doubleXY() const { #define _cimg_gs2x_for3(bound,i) \ for (int i = 0, _p1##i = 0, \ _n1##i = 1>=(bound)?(int)(bound) - 1:1; \ _n1##i<(int)(bound) || i==--_n1##i; \ _p1##i = i++, ++_n1##i, ptrd1+=(res)._width, ptrd2+=(res)._width) #define _cimg_gs2x_for3x3(img,x,y,z,c,I,T) \ _cimg_gs2x_for3((img)._height,y) for (int x = 0, \ _p1##x = 0, \ _n1##x = (int)( \ (I[1] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[3] = I[4] = (T)(img)(0,y,z,c)), \ (I[7] = (T)(img)(0,_n1##y,z,c)), \ 1>=(img)._width?(img).width() - 1:1); \ (_n1##x<(img).width() && ( \ (I[2] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[5] = (T)(img)(_n1##x,y,z,c)), \ (I[8] = (T)(img)(_n1##x,_n1##y,z,c)),1)) || \ x==--_n1##x; \ I[1] = I[2], \ I[3] = I[4], I[4] = I[5], \ I[7] = I[8], \ _p1##x = x++, ++_n1##x) if (is_empty()) return *this; CImg<T> res(_width<<1,_height<<1,_depth,_spectrum); CImg_3x3(I,T); cimg_forZC(*this,z,c) { T *ptrd1 = res.data(0,0,z,c), *ptrd2 = ptrd1 + res._width; _cimg_gs2x_for3x3(*this,x,y,z,c,I,T) { if (Icp!=Icn && Ipc!=Inc) { *(ptrd1++) = Ipc==Icp?Ipc:Icc; *(ptrd1++) = Icp==Inc?Inc:Icc; *(ptrd2++) = Ipc==Icn?Ipc:Icc; *(ptrd2++) = Icn==Inc?Inc:Icc; } else { *(ptrd1++) = Icc; *(ptrd1++) = Icc; *(ptrd2++) = Icc; *(ptrd2++) = Icc; } } } return res; } //! Resize image to triple-size, using the Scale3X algorithm. /** \note Use anisotropic upscaling algorithm <a href="http://scale2x.sourceforge.net/algorithm.html">described here</a>. **/ CImg<T>& resize_tripleXY() { return get_resize_tripleXY().move_to(*this); } //! Resize image to triple-size, using the Scale3X algorithm \newinstance. CImg<T> get_resize_tripleXY() const { #define _cimg_gs3x_for3(bound,i) \ for (int i = 0, _p1##i = 0, \ _n1##i = 1>=(bound)?(int)(bound) - 1:1; \ _n1##i<(int)(bound) || i==--_n1##i; \ _p1##i = i++, ++_n1##i, ptrd1+=2*(res)._width, ptrd2+=2*(res)._width, ptrd3+=2*(res)._width) #define _cimg_gs3x_for3x3(img,x,y,z,c,I,T) \ _cimg_gs3x_for3((img)._height,y) for (int x = 0, \ _p1##x = 0, \ _n1##x = (int)( \ (I[0] = I[1] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[3] = I[4] = (T)(img)(0,y,z,c)), \ (I[6] = I[7] = (T)(img)(0,_n1##y,z,c)), \ 1>=(img)._width?(img).width() - 1:1); \ (_n1##x<(img).width() && ( \ (I[2] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[5] = (T)(img)(_n1##x,y,z,c)), \ (I[8] = (T)(img)(_n1##x,_n1##y,z,c)),1)) || \ x==--_n1##x; \ I[0] = I[1], I[1] = I[2], \ I[3] = I[4], I[4] = I[5], \ I[6] = I[7], I[7] = I[8], \ _p1##x = x++, ++_n1##x) if (is_empty()) return *this; CImg<T> res(3*_width,3*_height,_depth,_spectrum); CImg_3x3(I,T); cimg_forZC(*this,z,c) { T *ptrd1 = res.data(0,0,z,c), *ptrd2 = ptrd1 + res._width, *ptrd3 = ptrd2 + res._width; _cimg_gs3x_for3x3(*this,x,y,z,c,I,T) { if (Icp != Icn && Ipc != Inc) { *(ptrd1++) = Ipc==Icp?Ipc:Icc; *(ptrd1++) = (Ipc==Icp && Icc!=Inp) || (Icp==Inc && Icc!=Ipp)?Icp:Icc; *(ptrd1++) = Icp==Inc?Inc:Icc; *(ptrd2++) = (Ipc==Icp && Icc!=Ipn) || (Ipc==Icn && Icc!=Ipp)?Ipc:Icc; *(ptrd2++) = Icc; *(ptrd2++) = (Icp==Inc && Icc!=Inn) || (Icn==Inc && Icc!=Inp)?Inc:Icc; *(ptrd3++) = Ipc==Icn?Ipc:Icc; *(ptrd3++) = (Ipc==Icn && Icc!=Inn) || (Icn==Inc && Icc!=Ipn)?Icn:Icc; *(ptrd3++) = Icn==Inc?Inc:Icc; } else { *(ptrd1++) = Icc; *(ptrd1++) = Icc; *(ptrd1++) = Icc; *(ptrd2++) = Icc; *(ptrd2++) = Icc; *(ptrd2++) = Icc; *(ptrd3++) = Icc; *(ptrd3++) = Icc; *(ptrd3++) = Icc; } } } return res; } //! Mirror image content along specified axis. /** \param axis Mirror axis **/ CImg<T>& mirror(const char axis) { if (is_empty()) return *this; T *pf, *pb, *buf = 0; switch (cimg::lowercase(axis)) { case 'x' : { pf = _data; pb = data(_width - 1); const unsigned int width2 = _width/2; for (unsigned int yzv = 0; yzv<_height*_depth*_spectrum; ++yzv) { for (unsigned int x = 0; x<width2; ++x) { const T val = *pf; *(pf++) = *pb; *(pb--) = val; } pf+=_width - width2; pb+=_width + width2; } } break; case 'y' : { buf = new T[_width]; pf = _data; pb = data(0,_height - 1); const unsigned int height2 = _height/2; for (unsigned int zv = 0; zv<_depth*_spectrum; ++zv) { for (unsigned int y = 0; y<height2; ++y) { std::memcpy(buf,pf,_width*sizeof(T)); std::memcpy(pf,pb,_width*sizeof(T)); std::memcpy(pb,buf,_width*sizeof(T)); pf+=_width; pb-=_width; } pf+=(ulongT)_width*(_height - height2); pb+=(ulongT)_width*(_height + height2); } } break; case 'z' : { buf = new T[(ulongT)_width*_height]; pf = _data; pb = data(0,0,_depth - 1); const unsigned int depth2 = _depth/2; cimg_forC(*this,c) { for (unsigned int z = 0; z<depth2; ++z) { std::memcpy(buf,pf,_width*_height*sizeof(T)); std::memcpy(pf,pb,_width*_height*sizeof(T)); std::memcpy(pb,buf,_width*_height*sizeof(T)); pf+=(ulongT)_width*_height; pb-=(ulongT)_width*_height; } pf+=(ulongT)_width*_height*(_depth - depth2); pb+=(ulongT)_width*_height*(_depth + depth2); } } break; case 'c' : { buf = new T[(ulongT)_width*_height*_depth]; pf = _data; pb = data(0,0,0,_spectrum - 1); const unsigned int _spectrum2 = _spectrum/2; for (unsigned int v = 0; v<_spectrum2; ++v) { std::memcpy(buf,pf,_width*_height*_depth*sizeof(T)); std::memcpy(pf,pb,_width*_height*_depth*sizeof(T)); std::memcpy(pb,buf,_width*_height*_depth*sizeof(T)); pf+=(ulongT)_width*_height*_depth; pb-=(ulongT)_width*_height*_depth; } } break; default : throw CImgArgumentException(_cimg_instance "mirror(): Invalid specified axis '%c'.", cimg_instance, axis); } delete[] buf; return *this; } //! Mirror image content along specified axis \newinstance. CImg<T> get_mirror(const char axis) const { return (+*this).mirror(axis); } //! Mirror image content along specified axes. /** \param axes Mirror axes, as a C-string. \note \c axes may contains multiple characters, e.g. \c "xyz" **/ CImg<T>& mirror(const char *const axes) { for (const char *s = axes; *s; ++s) mirror(*s); return *this; } //! Mirror image content along specified axes \newinstance. CImg<T> get_mirror(const char *const axes) const { return (+*this).mirror(axes); } //! Shift image content. /** \param delta_x Amount of displacement along the X-axis. \param delta_y Amount of displacement along the Y-axis. \param delta_z Amount of displacement along the Z-axis. \param delta_c Amount of displacement along the C-axis. \param boundary_conditions Border condition. Can be { 0=dirichlet | 1=neumann | 2=periodic | 3=mirror }. **/ CImg<T>& shift(const int delta_x, const int delta_y=0, const int delta_z=0, const int delta_c=0, const unsigned int boundary_conditions=0) { if (is_empty()) return *this; if (boundary_conditions==3) return get_crop(-delta_x,-delta_y,-delta_z,-delta_c, width() - delta_x - 1, height() - delta_y - 1, depth() - delta_z - 1, spectrum() - delta_c - 1,3).move_to(*this); if (delta_x) // Shift along X-axis switch (boundary_conditions) { case 2 : { // Periodic const int ml = cimg::mod(-delta_x,width()), ndelta_x = (ml<=width()/2)?ml:(ml-width()); if (!ndelta_x) return *this; CImg<T> buf(cimg::abs(ndelta_x)); if (ndelta_x>0) cimg_forYZC(*this,y,z,c) { std::memcpy(buf,data(0,y,z,c),ndelta_x*sizeof(T)); std::memmove(data(0,y,z,c),data(ndelta_x,y,z,c),(_width-ndelta_x)*sizeof(T)); std::memcpy(data(_width-ndelta_x,y,z,c),buf,ndelta_x*sizeof(T)); } else cimg_forYZC(*this,y,z,c) { std::memcpy(buf,data(_width + ndelta_x,y,z,c),-ndelta_x*sizeof(T)); std::memmove(data(-ndelta_x,y,z,c),data(0,y,z,c),(_width + ndelta_x)*sizeof(T)); std::memcpy(data(0,y,z,c),buf,-ndelta_x*sizeof(T)); } } break; case 1 : // Neumann if (delta_x<0) { const int ndelta_x = (-delta_x>=width())?width() - 1:-delta_x; if (!ndelta_x) return *this; cimg_forYZC(*this,y,z,c) { std::memmove(data(0,y,z,c),data(ndelta_x,y,z,c),(_width-ndelta_x)*sizeof(T)); T *ptrd = data(_width - 1,y,z,c); const T val = *ptrd; for (int l = 0; l<ndelta_x - 1; ++l) *(--ptrd) = val; } } else { const int ndelta_x = (delta_x>=width())?width() - 1:delta_x; if (!ndelta_x) return *this; cimg_forYZC(*this,y,z,c) { std::memmove(data(ndelta_x,y,z,c),data(0,y,z,c),(_width-ndelta_x)*sizeof(T)); T *ptrd = data(0,y,z,c); const T val = *ptrd; for (int l = 0; l<ndelta_x - 1; ++l) *(++ptrd) = val; } } break; default : // Dirichlet if (delta_x<=-width() || delta_x>=width()) return fill((T)0); if (delta_x<0) cimg_forYZC(*this,y,z,c) { std::memmove(data(0,y,z,c),data(-delta_x,y,z,c),(_width + delta_x)*sizeof(T)); std::memset(data(_width + delta_x,y,z,c),0,-delta_x*sizeof(T)); } else cimg_forYZC(*this,y,z,c) { std::memmove(data(delta_x,y,z,c),data(0,y,z,c),(_width-delta_x)*sizeof(T)); std::memset(data(0,y,z,c),0,delta_x*sizeof(T)); } } if (delta_y) // Shift along Y-axis switch (boundary_conditions) { case 2 : { // Periodic const int ml = cimg::mod(-delta_y,height()), ndelta_y = (ml<=height()/2)?ml:(ml-height()); if (!ndelta_y) return *this; CImg<T> buf(width(),cimg::abs(ndelta_y)); if (ndelta_y>0) cimg_forZC(*this,z,c) { std::memcpy(buf,data(0,0,z,c),_width*ndelta_y*sizeof(T)); std::memmove(data(0,0,z,c),data(0,ndelta_y,z,c),_width*(_height-ndelta_y)*sizeof(T)); std::memcpy(data(0,_height-ndelta_y,z,c),buf,_width*ndelta_y*sizeof(T)); } else cimg_forZC(*this,z,c) { std::memcpy(buf,data(0,_height + ndelta_y,z,c),-ndelta_y*_width*sizeof(T)); std::memmove(data(0,-ndelta_y,z,c),data(0,0,z,c),_width*(_height + ndelta_y)*sizeof(T)); std::memcpy(data(0,0,z,c),buf,-ndelta_y*_width*sizeof(T)); } } break; case 1 : // Neumann if (delta_y<0) { const int ndelta_y = (-delta_y>=height())?height() - 1:-delta_y; if (!ndelta_y) return *this; cimg_forZC(*this,z,c) { std::memmove(data(0,0,z,c),data(0,ndelta_y,z,c),_width*(_height-ndelta_y)*sizeof(T)); T *ptrd = data(0,_height-ndelta_y,z,c), *ptrs = data(0,_height - 1,z,c); for (int l = 0; l<ndelta_y - 1; ++l) { std::memcpy(ptrd,ptrs,_width*sizeof(T)); ptrd+=_width; } } } else { const int ndelta_y = (delta_y>=height())?height() - 1:delta_y; if (!ndelta_y) return *this; cimg_forZC(*this,z,c) { std::memmove(data(0,ndelta_y,z,c),data(0,0,z,c),_width*(_height-ndelta_y)*sizeof(T)); T *ptrd = data(0,1,z,c), *ptrs = data(0,0,z,c); for (int l = 0; l<ndelta_y - 1; ++l) { std::memcpy(ptrd,ptrs,_width*sizeof(T)); ptrd+=_width; } } } break; default : // Dirichlet if (delta_y<=-height() || delta_y>=height()) return fill((T)0); if (delta_y<0) cimg_forZC(*this,z,c) { std::memmove(data(0,0,z,c),data(0,-delta_y,z,c),_width*(_height + delta_y)*sizeof(T)); std::memset(data(0,_height + delta_y,z,c),0,-delta_y*_width*sizeof(T)); } else cimg_forZC(*this,z,c) { std::memmove(data(0,delta_y,z,c),data(0,0,z,c),_width*(_height-delta_y)*sizeof(T)); std::memset(data(0,0,z,c),0,delta_y*_width*sizeof(T)); } } if (delta_z) // Shift along Z-axis switch (boundary_conditions) { case 2 : { // Periodic const int ml = cimg::mod(-delta_z,depth()), ndelta_z = (ml<=depth()/2)?ml:(ml-depth()); if (!ndelta_z) return *this; CImg<T> buf(width(),height(),cimg::abs(ndelta_z)); if (ndelta_z>0) cimg_forC(*this,c) { std::memcpy(buf,data(0,0,0,c),_width*_height*ndelta_z*sizeof(T)); std::memmove(data(0,0,0,c),data(0,0,ndelta_z,c),_width*_height*(_depth-ndelta_z)*sizeof(T)); std::memcpy(data(0,0,_depth-ndelta_z,c),buf,_width*_height*ndelta_z*sizeof(T)); } else cimg_forC(*this,c) { std::memcpy(buf,data(0,0,_depth + ndelta_z,c),-ndelta_z*_width*_height*sizeof(T)); std::memmove(data(0,0,-ndelta_z,c),data(0,0,0,c),_width*_height*(_depth + ndelta_z)*sizeof(T)); std::memcpy(data(0,0,0,c),buf,-ndelta_z*_width*_height*sizeof(T)); } } break; case 1 : // Neumann if (delta_z<0) { const int ndelta_z = (-delta_z>=depth())?depth() - 1:-delta_z; if (!ndelta_z) return *this; cimg_forC(*this,c) { std::memmove(data(0,0,0,c),data(0,0,ndelta_z,c),_width*_height*(_depth-ndelta_z)*sizeof(T)); T *ptrd = data(0,0,_depth-ndelta_z,c), *ptrs = data(0,0,_depth - 1,c); for (int l = 0; l<ndelta_z - 1; ++l) { std::memcpy(ptrd,ptrs,_width*_height*sizeof(T)); ptrd+=(ulongT)_width*_height; } } } else { const int ndelta_z = (delta_z>=depth())?depth() - 1:delta_z; if (!ndelta_z) return *this; cimg_forC(*this,c) { std::memmove(data(0,0,ndelta_z,c),data(0,0,0,c),_width*_height*(_depth-ndelta_z)*sizeof(T)); T *ptrd = data(0,0,1,c), *ptrs = data(0,0,0,c); for (int l = 0; l<ndelta_z - 1; ++l) { std::memcpy(ptrd,ptrs,_width*_height*sizeof(T)); ptrd+=(ulongT)_width*_height; } } } break; default : // Dirichlet if (delta_z<=-depth() || delta_z>=depth()) return fill((T)0); if (delta_z<0) cimg_forC(*this,c) { std::memmove(data(0,0,0,c),data(0,0,-delta_z,c),_width*_height*(_depth + delta_z)*sizeof(T)); std::memset(data(0,0,_depth + delta_z,c),0,_width*_height*(-delta_z)*sizeof(T)); } else cimg_forC(*this,c) { std::memmove(data(0,0,delta_z,c),data(0,0,0,c),_width*_height*(_depth-delta_z)*sizeof(T)); std::memset(data(0,0,0,c),0,delta_z*_width*_height*sizeof(T)); } } if (delta_c) // Shift along C-axis switch (boundary_conditions) { case 2 : { // Periodic const int ml = cimg::mod(-delta_c,spectrum()), ndelta_c = (ml<=spectrum()/2)?ml:(ml-spectrum()); if (!ndelta_c) return *this; CImg<T> buf(width(),height(),depth(),cimg::abs(ndelta_c)); if (ndelta_c>0) { std::memcpy(buf,_data,_width*_height*_depth*ndelta_c*sizeof(T)); std::memmove(_data,data(0,0,0,ndelta_c),_width*_height*_depth*(_spectrum-ndelta_c)*sizeof(T)); std::memcpy(data(0,0,0,_spectrum-ndelta_c),buf,_width*_height*_depth*ndelta_c*sizeof(T)); } else { std::memcpy(buf,data(0,0,0,_spectrum + ndelta_c),-ndelta_c*_width*_height*_depth*sizeof(T)); std::memmove(data(0,0,0,-ndelta_c),_data,_width*_height*_depth*(_spectrum + ndelta_c)*sizeof(T)); std::memcpy(_data,buf,-ndelta_c*_width*_height*_depth*sizeof(T)); } } break; case 1 : // Neumann if (delta_c<0) { const int ndelta_c = (-delta_c>=spectrum())?spectrum() - 1:-delta_c; if (!ndelta_c) return *this; std::memmove(_data,data(0,0,0,ndelta_c),_width*_height*_depth*(_spectrum-ndelta_c)*sizeof(T)); T *ptrd = data(0,0,0,_spectrum-ndelta_c), *ptrs = data(0,0,0,_spectrum - 1); for (int l = 0; l<ndelta_c - 1; ++l) { std::memcpy(ptrd,ptrs,_width*_height*_depth*sizeof(T)); ptrd+=(ulongT)_width*_height*_depth; } } else { const int ndelta_c = (delta_c>=spectrum())?spectrum() - 1:delta_c; if (!ndelta_c) return *this; std::memmove(data(0,0,0,ndelta_c),_data,_width*_height*_depth*(_spectrum-ndelta_c)*sizeof(T)); T *ptrd = data(0,0,0,1); for (int l = 0; l<ndelta_c - 1; ++l) { std::memcpy(ptrd,_data,_width*_height*_depth*sizeof(T)); ptrd+=(ulongT)_width*_height*_depth; } } break; default : // Dirichlet if (delta_c<=-spectrum() || delta_c>=spectrum()) return fill((T)0); if (delta_c<0) { std::memmove(_data,data(0,0,0,-delta_c),_width*_height*_depth*(_spectrum + delta_c)*sizeof(T)); std::memset(data(0,0,0,_spectrum + delta_c),0,_width*_height*_depth*(-delta_c)*sizeof(T)); } else { std::memmove(data(0,0,0,delta_c),_data,_width*_height*_depth*(_spectrum-delta_c)*sizeof(T)); std::memset(_data,0,delta_c*_width*_height*_depth*sizeof(T)); } } return *this; } //! Shift image content \newinstance. CImg<T> get_shift(const int delta_x, const int delta_y=0, const int delta_z=0, const int delta_c=0, const unsigned int boundary_conditions=0) const { return (+*this).shift(delta_x,delta_y,delta_z,delta_c,boundary_conditions); } //! Permute axes order. /** \param order Axes permutations, as a C-string of 4 characters. This function permutes image content regarding the specified axes permutation. **/ CImg<T>& permute_axes(const char *const order) { return get_permute_axes(order).move_to(*this); } //! Permute axes order \newinstance. CImg<T> get_permute_axes(const char *const order) const { const T foo = (T)0; return _permute_axes(order,foo); } template<typename t> CImg<t> _permute_axes(const char *const order, const t&) const { if (is_empty() || !order) return CImg<t>(*this,false); CImg<t> res; const T* ptrs = _data; unsigned char s_code[4] = { 0,1,2,3 }, n_code[4] = { 0 }; for (unsigned int l = 0; order[l]; ++l) { int c = cimg::lowercase(order[l]); if (c!='x' && c!='y' && c!='z' && c!='c') { *s_code = 4; break; } else { ++n_code[c%=4]; s_code[l] = c; } } if (*order && *s_code<4 && *n_code<=1 && n_code[1]<=1 && n_code[2]<=1 && n_code[3]<=1) { const unsigned int code = (s_code[0]<<12) | (s_code[1]<<8) | (s_code[2]<<4) | (s_code[3]); ulongT wh, whd; switch (code) { case 0x0123 : // xyzc return +*this; case 0x0132 : // xycz res.assign(_width,_height,_spectrum,_depth); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(x,y,c,z,wh,whd) = (t)*(ptrs++); break; case 0x0213 : // xzyc res.assign(_width,_depth,_height,_spectrum); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(x,z,y,c,wh,whd) = (t)*(ptrs++); break; case 0x0231 : // xzcy res.assign(_width,_depth,_spectrum,_height); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(x,z,c,y,wh,whd) = (t)*(ptrs++); break; case 0x0312 : // xcyz res.assign(_width,_spectrum,_height,_depth); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(x,c,y,z,wh,whd) = (t)*(ptrs++); break; case 0x0321 : // xczy res.assign(_width,_spectrum,_depth,_height); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(x,c,z,y,wh,whd) = (t)*(ptrs++); break; case 0x1023 : // yxzc res.assign(_height,_width,_depth,_spectrum); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(y,x,z,c,wh,whd) = (t)*(ptrs++); break; case 0x1032 : // yxcz res.assign(_height,_width,_spectrum,_depth); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(y,x,c,z,wh,whd) = (t)*(ptrs++); break; case 0x1203 : // yzxc res.assign(_height,_depth,_width,_spectrum); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(y,z,x,c,wh,whd) = (t)*(ptrs++); break; case 0x1230 : // yzcx res.assign(_height,_depth,_spectrum,_width); switch (_width) { case 1 : { t *ptr_r = res.data(0,0,0,0); for (unsigned int siz = _height*_depth*_spectrum; siz; --siz) { *(ptr_r++) = (t)*(ptrs++); } } break; case 2 : { t *ptr_r = res.data(0,0,0,0), *ptr_g = res.data(0,0,0,1); for (unsigned int siz = _height*_depth*_spectrum; siz; --siz) { *(ptr_r++) = (t)ptrs[0]; *(ptr_g++) = (t)ptrs[1]; ptrs+=2; } } break; case 3 : { // Optimization for the classical conversion from interleaved RGB to planar RGB t *ptr_r = res.data(0,0,0,0), *ptr_g = res.data(0,0,0,1), *ptr_b = res.data(0,0,0,2); for (unsigned int siz = _height*_depth*_spectrum; siz; --siz) { *(ptr_r++) = (t)ptrs[0]; *(ptr_g++) = (t)ptrs[1]; *(ptr_b++) = (t)ptrs[2]; ptrs+=3; } } break; case 4 : { // Optimization for the classical conversion from interleaved RGBA to planar RGBA t *ptr_r = res.data(0,0,0,0), *ptr_g = res.data(0,0,0,1), *ptr_b = res.data(0,0,0,2), *ptr_a = res.data(0,0,0,3); for (unsigned int siz = _height*_depth*_spectrum; siz; --siz) { *(ptr_r++) = (t)ptrs[0]; *(ptr_g++) = (t)ptrs[1]; *(ptr_b++) = (t)ptrs[2]; *(ptr_a++) = (t)ptrs[3]; ptrs+=4; } } break; default : { wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(y,z,c,x,wh,whd) = *(ptrs++); return res; } } break; case 0x1302 : // ycxz res.assign(_height,_spectrum,_width,_depth); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(y,c,x,z,wh,whd) = (t)*(ptrs++); break; case 0x1320 : // yczx res.assign(_height,_spectrum,_depth,_width); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(y,c,z,x,wh,whd) = (t)*(ptrs++); break; case 0x2013 : // zxyc res.assign(_depth,_width,_height,_spectrum); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(z,x,y,c,wh,whd) = (t)*(ptrs++); break; case 0x2031 : // zxcy res.assign(_depth,_width,_spectrum,_height); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(z,x,c,y,wh,whd) = (t)*(ptrs++); break; case 0x2103 : // zyxc res.assign(_depth,_height,_width,_spectrum); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(z,y,x,c,wh,whd) = (t)*(ptrs++); break; case 0x2130 : // zycx res.assign(_depth,_height,_spectrum,_width); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(z,y,c,x,wh,whd) = (t)*(ptrs++); break; case 0x2301 : // zcxy res.assign(_depth,_spectrum,_width,_height); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(z,c,x,y,wh,whd) = (t)*(ptrs++); break; case 0x2310 : // zcyx res.assign(_depth,_spectrum,_height,_width); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(z,c,y,x,wh,whd) = (t)*(ptrs++); break; case 0x3012 : // cxyz res.assign(_spectrum,_width,_height,_depth); switch (_spectrum) { case 1 : { const T *ptr_r = data(0,0,0,0); t *ptrd = res._data; for (ulongT siz = (ulongT)_width*_height*_depth; siz; --siz) *(ptrd++) = (t)*(ptr_r++); } break; case 2 : { const T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1); t *ptrd = res._data; for (ulongT siz = (ulongT)_width*_height*_depth; siz; --siz) { ptrd[0] = (t)*(ptr_r++); ptrd[1] = (t)*(ptr_g++); ptrd+=2; } } break; case 3 : { // Optimization for the classical conversion from planar RGB to interleaved RGB const T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2); t *ptrd = res._data; for (ulongT siz = (ulongT)_width*_height*_depth; siz; --siz) { ptrd[0] = (t)*(ptr_r++); ptrd[1] = (t)*(ptr_g++); ptrd[2] = (t)*(ptr_b++); ptrd+=3; } } break; case 4 : { // Optimization for the classical conversion from planar RGBA to interleaved RGBA const T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2), *ptr_a = data(0,0,0,3); t *ptrd = res._data; for (ulongT siz = (ulongT)_width*_height*_depth; siz; --siz) { ptrd[0] = (t)*(ptr_r++); ptrd[1] = (t)*(ptr_g++); ptrd[2] = (t)*(ptr_b++); ptrd[3] = (t)*(ptr_a++); ptrd+=4; } } break; default : { wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(c,x,y,z,wh,whd) = (t)*(ptrs++); } } break; case 0x3021 : // cxzy res.assign(_spectrum,_width,_depth,_height); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(c,x,z,y,wh,whd) = (t)*(ptrs++); break; case 0x3102 : // cyxz res.assign(_spectrum,_height,_width,_depth); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(c,y,x,z,wh,whd) = (t)*(ptrs++); break; case 0x3120 : // cyzx res.assign(_spectrum,_height,_depth,_width); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(c,y,z,x,wh,whd) = (t)*(ptrs++); break; case 0x3201 : // czxy res.assign(_spectrum,_depth,_width,_height); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(c,z,x,y,wh,whd) = (t)*(ptrs++); break; case 0x3210 : // czyx res.assign(_spectrum,_depth,_height,_width); wh = (ulongT)res._width*res._height; whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(c,z,y,x,wh,whd) = (t)*(ptrs++); break; } } if (!res) throw CImgArgumentException(_cimg_instance "permute_axes(): Invalid specified permutation '%s'.", cimg_instance, order); return res; } //! Unroll pixel values along specified axis. /** \param axis Unroll axis (can be \c 'x', \c 'y', \c 'z' or c 'c'). **/ CImg<T>& unroll(const char axis) { const unsigned int siz = (unsigned int)size(); if (siz) switch (cimg::lowercase(axis)) { case 'x' : _width = siz; _height = _depth = _spectrum = 1; break; case 'y' : _height = siz; _width = _depth = _spectrum = 1; break; case 'z' : _depth = siz; _width = _height = _spectrum = 1; break; default : _spectrum = siz; _width = _height = _depth = 1; } return *this; } //! Unroll pixel values along specified axis \newinstance. CImg<T> get_unroll(const char axis) const { return (+*this).unroll(axis); } //! Rotate image with arbitrary angle. /** \param angle Rotation angle, in degrees. \param interpolation Type of interpolation. Can be <tt>{ 0=nearest | 1=linear | 2=cubic }</tt>. \param boundary_conditions Boundary conditions. Can be <tt>{ 0=dirichlet | 1=neumann | 2=periodic | 3=mirror }</tt>. \note The size of the image is modified. **/ CImg<T>& rotate(const float angle, const unsigned int interpolation=1, const unsigned int boundary_conditions=0) { const float nangle = cimg::mod(angle,360.f); if (nangle==0.f) return *this; return get_rotate(nangle,interpolation,boundary_conditions).move_to(*this); } //! Rotate image with arbitrary angle \newinstance. CImg<T> get_rotate(const float angle, const unsigned int interpolation=1, const unsigned int boundary_conditions=0) const { if (is_empty()) return *this; CImg<T> res; const float nangle = cimg::mod(angle,360.f); if (boundary_conditions!=1 && cimg::mod(nangle,90.f)==0) { // Optimized version for orthogonal angles const int wm1 = width() - 1, hm1 = height() - 1; const int iangle = (int)nangle/90; switch (iangle) { case 1 : { // 90 deg res.assign(_height,_width,_depth,_spectrum); T *ptrd = res._data; cimg_forXYZC(res,x,y,z,c) *(ptrd++) = (*this)(y,hm1 - x,z,c); } break; case 2 : { // 180 deg res.assign(_width,_height,_depth,_spectrum); T *ptrd = res._data; cimg_forXYZC(res,x,y,z,c) *(ptrd++) = (*this)(wm1 - x,hm1 - y,z,c); } break; case 3 : { // 270 deg res.assign(_height,_width,_depth,_spectrum); T *ptrd = res._data; cimg_forXYZC(res,x,y,z,c) *(ptrd++) = (*this)(wm1 - y,x,z,c); } break; default : // 0 deg return *this; } } else { // Generic angle const float rad = (float)(nangle*cimg::PI/180.), ca = (float)std::cos(rad), sa = (float)std::sin(rad), ux = cimg::abs((_width - 1)*ca), uy = cimg::abs((_width - 1)*sa), vx = cimg::abs((_height - 1)*sa), vy = cimg::abs((_height - 1)*ca), w2 = 0.5f*(_width - 1), h2 = 0.5f*(_height - 1); res.assign((int)cimg::round(1 + ux + vx),(int)cimg::round(1 + uy + vy),_depth,_spectrum); const float rw2 = 0.5f*(res._width - 1), rh2 = 0.5f*(res._height - 1); _rotate(res,nangle,interpolation,boundary_conditions,w2,h2,rw2,rh2); } return res; } //! Rotate image with arbitrary angle, around a center point. /** \param angle Rotation angle, in degrees. \param cx X-coordinate of the rotation center. \param cy Y-coordinate of the rotation center. \param interpolation Type of interpolation, <tt>{ 0=nearest | 1=linear | 2=cubic | 3=mirror }</tt>. \param boundary_conditions Boundary conditions, <tt>{ 0=dirichlet | 1=neumann | 2=periodic | 3=mirror }</tt>. **/ CImg<T>& rotate(const float angle, const float cx, const float cy, const unsigned int interpolation, const unsigned int boundary_conditions=0) { return get_rotate(angle,cx,cy,interpolation,boundary_conditions).move_to(*this); } //! Rotate image with arbitrary angle, around a center point \newinstance. CImg<T> get_rotate(const float angle, const float cx, const float cy, const unsigned int interpolation, const unsigned int boundary_conditions=0) const { if (is_empty()) return *this; CImg<T> res(_width,_height,_depth,_spectrum); _rotate(res,angle,interpolation,boundary_conditions,cx,cy,cx,cy); return res; } // [internal] Perform 2D rotation with arbitrary angle. void _rotate(CImg<T>& res, const float angle, const unsigned int interpolation, const unsigned int boundary_conditions, const float w2, const float h2, const float rw2, const float rh2) const { const float rad = (float)(angle*cimg::PI/180.), ca = (float)std::cos(rad), sa = (float)std::sin(rad); switch (boundary_conditions) { case 3 : { // Mirror switch (interpolation) { case 2 : { // Cubic interpolation const float ww = 2.f*width(), hh = 2.f*height(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZC(res,x,y,z,c) { const float xc = x - rw2, yc = y - rh2, mx = cimg::mod(w2 + xc*ca + yc*sa,ww), my = cimg::mod(h2 - xc*sa + yc*ca,hh); res(x,y,z,c) = _cubic_atXY_c(mx<width()?mx:ww - mx - 1,my<height()?my:hh - my - 1,z,c); } } break; case 1 : { // Linear interpolation const float ww = 2.f*width(), hh = 2.f*height(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZC(res,x,y,z,c) { const float xc = x - rw2, yc = y - rh2, mx = cimg::mod(w2 + xc*ca + yc*sa,ww), my = cimg::mod(h2 - xc*sa + yc*ca,hh); res(x,y,z,c) = (T)_linear_atXY(mx<width()?mx:ww - mx - 1,my<height()?my:hh - my - 1,z,c); } } break; default : { // Nearest-neighbor interpolation const int ww = 2*width(), hh = 2*height(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZC(res,x,y,z,c) { const float xc = x - rw2, yc = y - rh2, mx = cimg::mod((int)cimg::round(w2 + xc*ca + yc*sa),ww), my = cimg::mod((int)cimg::round(h2 - xc*sa + yc*ca),hh); res(x,y,z,c) = (*this)(mx<width()?mx:ww - mx - 1,my<height()?my:hh - my - 1,z,c); } } } } break; case 2 : // Periodic switch (interpolation) { case 2 : { // Cubic interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZC(res,x,y,z,c) { const float xc = x - rw2, yc = y - rh2; res(x,y,z,c) = _cubic_atXY_pc(w2 + xc*ca + yc*sa,h2 - xc*sa + yc*ca,z,c); } } break; case 1 : { // Linear interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZC(res,x,y,z,c) { const float xc = x - rw2, yc = y - rh2; res(x,y,z,c) = (T)_linear_atXY_p(w2 + xc*ca + yc*sa,h2 - xc*sa + yc*ca,z,c); } } break; default : { // Nearest-neighbor interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZC(res,x,y,z,c) { const float xc = x - rw2, yc = y - rh2; res(x,y,z,c) = (*this)(cimg::mod((int)cimg::round(w2 + xc*ca + yc*sa),(float)width()), cimg::mod((int)cimg::round(h2 - xc*sa + yc*ca),(float)height()),z,c); } } } break; case 1 : // Neumann switch (interpolation) { case 2 : { // Cubic interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZC(res,x,y,z,c) { const float xc = x - rw2, yc = y - rh2; res(x,y,z,c) = _cubic_atXY_c(w2 + xc*ca + yc*sa,h2 - xc*sa + yc*ca,z,c); } } break; case 1 : { // Linear interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZC(res,x,y,z,c) { const float xc = x - rw2, yc = y - rh2; res(x,y,z,c) = (T)_linear_atXY(w2 + xc*ca + yc*sa,h2 - xc*sa + yc*ca,z,c); } } break; default : { // Nearest-neighbor interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZC(res,x,y,z,c) { const float xc = x - rw2, yc = y - rh2; res(x,y,z,c) = _atXY((int)cimg::round(w2 + xc*ca + yc*sa), (int)cimg::round(h2 - xc*sa + yc*ca),z,c); } } } break; default : // Dirichlet switch (interpolation) { case 2 : { // Cubic interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZC(res,x,y,z,c) { const float xc = x - rw2, yc = y - rh2; res(x,y,z,c) = cubic_atXY_c(w2 + xc*ca + yc*sa,h2 - xc*sa + yc*ca,z,c,(T)0); } } break; case 1 : { // Linear interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZC(res,x,y,z,c) { const float xc = x - rw2, yc = y - rh2; res(x,y,z,c) = (T)linear_atXY(w2 + xc*ca + yc*sa,h2 - xc*sa + yc*ca,z,c,(T)0); } } break; default : { // Nearest-neighbor interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZC(res,x,y,z,c) { const float xc = x - rw2, yc = y - rh2; res(x,y,z,c) = atXY((int)cimg::round(w2 + xc*ca + yc*sa), (int)cimg::round(h2 - xc*sa + yc*ca),z,c,(T)0); } } } } } //! Rotate volumetric image with arbitrary angle and axis. /** \param u X-coordinate of the 3D rotation axis. \param v Y-coordinate of the 3D rotation axis. \param w Z-coordinate of the 3D rotation axis. \param angle Rotation angle, in degrees. \param interpolation Type of interpolation. Can be <tt>{ 0=nearest | 1=linear | 2=cubic }</tt>. \param boundary_conditions Boundary conditions. Can be <tt>{ 0=dirichlet | 1=neumann | 2=periodic | 3=mirror }</tt>. \note Most of the time, size of the image is modified. **/ CImg<T> rotate(const float u, const float v, const float w, const float angle, const unsigned int interpolation, const unsigned int boundary_conditions) { const float nangle = cimg::mod(angle,360.f); if (nangle==0.f) return *this; return get_rotate(u,v,w,nangle,interpolation,boundary_conditions).move_to(*this); } //! Rotate volumetric image with arbitrary angle and axis \newinstance. CImg<T> get_rotate(const float u, const float v, const float w, const float angle, const unsigned int interpolation, const unsigned int boundary_conditions) const { if (is_empty()) return *this; CImg<T> res; const float w1 = _width - 1, h1 = _height - 1, d1 = _depth -1, w2 = 0.5f*w1, h2 = 0.5f*h1, d2 = 0.5f*d1; CImg<floatT> R = CImg<floatT>::rotation_matrix(u,v,w,angle); const CImg<Tfloat> X = R*CImg<Tfloat>(8,3,1,1, 0.f,w1,w1,0.f,0.f,w1,w1,0.f, 0.f,0.f,h1,h1,0.f,0.f,h1,h1, 0.f,0.f,0.f,0.f,d1,d1,d1,d1); float xm, xM = X.get_shared_row(0).max_min(xm), ym, yM = X.get_shared_row(1).max_min(ym), zm, zM = X.get_shared_row(2).max_min(zm); const int dx = (int)cimg::round(xM - xm), dy = (int)cimg::round(yM - ym), dz = (int)cimg::round(zM - zm); R.transpose(); res.assign(1 + dx,1 + dy,1 + dz,_spectrum); const float rw2 = 0.5f*dx, rh2 = 0.5f*dy, rd2 = 0.5f*dz; _rotate(res,R,interpolation,boundary_conditions,w2,h2,d2,rw2,rh2,rd2); return res; } //! Rotate volumetric image with arbitrary angle and axis, around a center point. /** \param u X-coordinate of the 3D rotation axis. \param v Y-coordinate of the 3D rotation axis. \param w Z-coordinate of the 3D rotation axis. \param angle Rotation angle, in degrees. \param cx X-coordinate of the rotation center. \param cy Y-coordinate of the rotation center. \param cz Z-coordinate of the rotation center. \param interpolation Type of interpolation. Can be <tt>{ 0=nearest | 1=linear | 2=cubic | 3=mirror }</tt>. \param boundary_conditions Boundary conditions. Can be <tt>{ 0=dirichlet | 1=neumann | 2=periodic }</tt>. \note Most of the time, size of the image is modified. **/ CImg<T> rotate(const float u, const float v, const float w, const float angle, const float cx, const float cy, const float cz, const unsigned int interpolation=1, const unsigned int boundary_conditions=0) { const float nangle = cimg::mod(angle,360.f); if (nangle==0.f) return *this; return get_rotate(u,v,w,nangle,cx,cy,cz,interpolation,boundary_conditions).move_to(*this); } //! Rotate volumetric image with arbitrary angle and axis, around a center point \newinstance. CImg<T> get_rotate(const float u, const float v, const float w, const float angle, const float cx, const float cy, const float cz, const unsigned int interpolation=1, const unsigned int boundary_conditions=0) const { if (is_empty()) return *this; CImg<T> res(_width,_height,_depth,_spectrum); CImg<floatT> R = CImg<floatT>::rotation_matrix(u,v,w,-angle); _rotate(res,R,interpolation,boundary_conditions,cx,cy,cz,cx,cy,cz); return res; } // [internal] Perform 3D rotation with arbitrary axis and angle. void _rotate(CImg<T>& res, const CImg<Tfloat>& R, const unsigned int interpolation, const unsigned int boundary_conditions, const float w2, const float h2, const float d2, const float rw2, const float rh2, const float rd2) const { switch (boundary_conditions) { case 3 : // Mirror switch (interpolation) { case 2 : { // Cubic interpolation const float ww = 2.f*width(), hh = 2.f*height(), dd = 2.f*depth(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZ(res,x,y,z) { const float xc = x - rw2, yc = y - rh2, zc = z - rd2, X = cimg::mod((float)(w2 + R(0,0)*xc + R(1,0)*yc + R(2,0)*zc),ww), Y = cimg::mod((float)(h2 + R(0,1)*xc + R(1,1)*yc + R(2,1)*zc),hh), Z = cimg::mod((float)(d2 + R(0,2)*xc + R(1,2)*yc + R(2,2)*zc),dd); cimg_forC(res,c) res(x,y,z,c) = _cubic_atXYZ_c(X<width()?X:ww - X - 1, Y<height()?Y:hh - Y - 1, Z<depth()?Z:dd - Z - z,c); } } break; case 1 : { // Linear interpolation const float ww = 2.f*width(), hh = 2.f*height(), dd = 2.f*depth(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZ(res,x,y,z) { const float xc = x - rw2, yc = y - rh2, zc = z - rd2, X = cimg::mod((float)(w2 + R(0,0)*xc + R(1,0)*yc + R(2,0)*zc),ww), Y = cimg::mod((float)(h2 + R(0,1)*xc + R(1,1)*yc + R(2,1)*zc),hh), Z = cimg::mod((float)(d2 + R(0,2)*xc + R(1,2)*yc + R(2,2)*zc),dd); cimg_forC(res,c) res(x,y,z,c) = (T)_linear_atXYZ(X<width()?X:ww - X - 1, Y<height()?Y:hh - Y - 1, Z<depth()?Z:dd - Z - 1,c); } } break; default : { // Nearest-neighbor interpolation const int ww = 2*width(), hh = 2*height(), dd = 2*depth(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZ(res,x,y,z) { const float xc = x - rw2, yc = y - rh2, zc = z - rd2; const int X = cimg::mod((int)cimg::round(w2 + R(0,0)*xc + R(1,0)*yc + R(2,0)*zc),ww), Y = cimg::mod((int)cimg::round(h2 + R(0,1)*xc + R(1,1)*yc + R(2,1)*zc),hh), Z = cimg::mod((int)cimg::round(d2 + R(0,2)*xc + R(1,2)*yc + R(2,2)*zc),dd); cimg_forC(res,c) res(x,y,z,c) = (*this)(X<width()?X:ww - X - 1, Y<height()?Y:hh - Y - 1, Z<depth()?Z:dd - Z - 1,c); } } } break; case 2 : // Periodic switch (interpolation) { case 2 : { // Cubic interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZ(res,x,y,z) { const float xc = x - rw2, yc = y - rh2, zc = z - rd2, X = w2 + R(0,0)*xc + R(1,0)*yc + R(2,0)*zc, Y = h2 + R(0,1)*xc + R(1,1)*yc + R(2,1)*zc, Z = d2 + R(0,2)*xc + R(1,2)*yc + R(2,2)*zc; cimg_forC(res,c) res(x,y,z,c) = _cubic_atXYZ_pc(X,Y,Z,c); } } break; case 1 : { // Linear interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZ(res,x,y,z) { const float xc = x - rw2, yc = y - rh2, zc = z - rd2, X = w2 + R(0,0)*xc + R(1,0)*yc + R(2,0)*zc, Y = h2 + R(0,1)*xc + R(1,1)*yc + R(2,1)*zc, Z = d2 + R(0,2)*xc + R(1,2)*yc + R(2,2)*zc; cimg_forC(res,c) res(x,y,z,c) = (T)_linear_atXYZ_p(X,Y,Z,c); } } break; default : { // Nearest-neighbor interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZ(res,x,y,z) { const float xc = x - rw2, yc = y - rh2, zc = z - rd2; const int X = cimg::mod((int)cimg::round(w2 + R(0,0)*xc + R(1,0)*yc + R(2,0)*zc),width()), Y = cimg::mod((int)cimg::round(h2 + R(0,1)*xc + R(1,1)*yc + R(2,1)*zc),height()), Z = cimg::mod((int)cimg::round(d2 + R(0,2)*xc + R(1,2)*yc + R(2,2)*zc),depth()); cimg_forC(res,c) res(x,y,z,c) = (*this)(X,Y,Z,c); } } } break; case 1 : // Neumann switch (interpolation) { case 2 : { // Cubic interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZ(res,x,y,z) { const float xc = x - rw2, yc = y - rh2, zc = z - rd2, X = w2 + R(0,0)*xc + R(1,0)*yc + R(2,0)*zc, Y = h2 + R(0,1)*xc + R(1,1)*yc + R(2,1)*zc, Z = d2 + R(0,2)*xc + R(1,2)*yc + R(2,2)*zc; cimg_forC(res,c) res(x,y,z,c) = _cubic_atXYZ_c(X,Y,Z,c); } } break; case 1 : { // Linear interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZ(res,x,y,z) { const float xc = x - rw2, yc = y - rh2, zc = z - rd2, X = w2 + R(0,0)*xc + R(1,0)*yc + R(2,0)*zc, Y = h2 + R(0,1)*xc + R(1,1)*yc + R(2,1)*zc, Z = d2 + R(0,2)*xc + R(1,2)*yc + R(2,2)*zc; cimg_forC(res,c) res(x,y,z,c) = _linear_atXYZ(X,Y,Z,c); } } break; default : { // Nearest-neighbor interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZ(res,x,y,z) { const float xc = x - rw2, yc = y - rh2, zc = z - rd2; const int X = (int)cimg::round(w2 + R(0,0)*xc + R(1,0)*yc + R(2,0)*zc), Y = (int)cimg::round(h2 + R(0,1)*xc + R(1,1)*yc + R(2,1)*zc), Z = (int)cimg::round(d2 + R(0,2)*xc + R(1,2)*yc + R(2,2)*zc); cimg_forC(res,c) res(x,y,z,c) = _atXYZ(X,Y,Z,c); } } } break; default : // Dirichlet switch (interpolation) { case 2 : { // Cubic interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZ(res,x,y,z) { const float xc = x - rw2, yc = y - rh2, zc = z - rd2, X = w2 + R(0,0)*xc + R(1,0)*yc + R(2,0)*zc, Y = h2 + R(0,1)*xc + R(1,1)*yc + R(2,1)*zc, Z = d2 + R(0,2)*xc + R(1,2)*yc + R(2,2)*zc; cimg_forC(res,c) res(x,y,z,c) = cubic_atXYZ_c(X,Y,Z,c,(T)0); } } break; case 1 : { // Linear interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZ(res,x,y,z) { const float xc = x - rw2, yc = y - rh2, zc = z - rd2, X = w2 + R(0,0)*xc + R(1,0)*yc + R(2,0)*zc, Y = h2 + R(0,1)*xc + R(1,1)*yc + R(2,1)*zc, Z = d2 + R(0,2)*xc + R(1,2)*yc + R(2,2)*zc; cimg_forC(res,c) res(x,y,z,c) = linear_atXYZ(X,Y,Z,c,(T)0); } } break; default : { // Nearest-neighbor interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(res.size(),2048)) cimg_forXYZ(res,x,y,z) { const float xc = x - rw2, yc = y - rh2, zc = z - rd2; const int X = (int)cimg::round(w2 + R(0,0)*xc + R(1,0)*yc + R(2,0)*zc), Y = (int)cimg::round(h2 + R(0,1)*xc + R(1,1)*yc + R(2,1)*zc), Z = (int)cimg::round(d2 + R(0,2)*xc + R(1,2)*yc + R(2,2)*zc); cimg_forC(res,c) res(x,y,z,c) = atXYZ(X,Y,Z,c,(T)0); } } } break; } } //! Warp image content by a warping field. /** \param warp Warping field. \param mode Can be { 0=backward-absolute | 1=backward-relative | 2=forward-absolute | 3=foward-relative } \param interpolation Can be <tt>{ 0=nearest | 1=linear | 2=cubic }</tt>. \param boundary_conditions Boundary conditions <tt>{ 0=dirichlet | 1=neumann | 2=periodic | 3=mirror }</tt>. **/ template<typename t> CImg<T>& warp(const CImg<t>& p_warp, const unsigned int mode=0, const unsigned int interpolation=1, const unsigned int boundary_conditions=0) { return get_warp(p_warp,mode,interpolation,boundary_conditions).move_to(*this); } //! Warp image content by a warping field \newinstance template<typename t> CImg<T> get_warp(const CImg<t>& p_warp, const unsigned int mode=0, const unsigned int interpolation=1, const unsigned int boundary_conditions=0) const { if (is_empty() || !p_warp) return *this; if (mode && !is_sameXYZ(p_warp)) throw CImgArgumentException(_cimg_instance "warp(): Instance and specified relative warping field (%u,%u,%u,%u,%p) " "have different XYZ dimensions.", cimg_instance, p_warp._width,p_warp._height,p_warp._depth,p_warp._spectrum,p_warp._data); CImg<T> res(p_warp._width,p_warp._height,p_warp._depth,_spectrum); if (p_warp._spectrum==1) { // 1D warping if (mode>=3) { // Forward-relative warp res.fill((T)0); if (interpolation>=1) // Linear interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); const T *ptrs = data(0,y,z,c); cimg_forX(res,x) res.set_linear_atX(*(ptrs++),x + (float)*(ptrs0++),y,z,c); } else // Nearest-neighbor interpolation cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); const T *ptrs = data(0,y,z,c); cimg_forX(res,x) { const int X = x + (int)cimg::round(*(ptrs0++)); if (X>=0 && X<width()) res(X,y,z,c) = *(ptrs++); } } } else if (mode==2) { // Forward-absolute warp res.fill((T)0); if (interpolation>=1) // Linear interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); const T *ptrs = data(0,y,z,c); cimg_forX(res,x) res.set_linear_atX(*(ptrs++),(float)*(ptrs0++),y,z,c); } else // Nearest-neighbor interpolation cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); const T *ptrs = data(0,y,z,c); cimg_forX(res,x) { const int X = (int)cimg::round(*(ptrs0++)); if (X>=0 && X<width()) res(X,y,z,c) = *(ptrs++); } } } else if (mode==1) { // Backward-relative warp if (interpolation==2) // Cubic interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*width(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const float mx = cimg::mod(x - (float)*(ptrs0++),w2); *(ptrd++) = _cubic_atX_c(mx<width()?mx:w2 - mx - 1,y,z,c); } } } break; case 2 : // Periodic cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _cubic_atX_pc(x - (float)*(ptrs0++),y,z,c); } break; case 1 : // Neumann cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _cubic_atX_c(x - (float)*(ptrs0++),y,z,c); } break; default : // Dirichlet cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = cubic_atX_c(x - (float)*(ptrs0++),y,z,c,(T)0); } } else if (interpolation==1) // Linear interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*width(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const float mx = cimg::mod(x - (float)*(ptrs0++),w2); *(ptrd++) = (T)_linear_atX(mx<width()?mx:w2 - mx - 1,y,z,c); } } } break; case 2 : // Periodic cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)_linear_atX_p(x - (float)*(ptrs0++),y,z,c); } break; case 1 : // Neumann cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)_linear_atX(x - (float)*(ptrs0++),y,z,c); } break; default : // Dirichlet cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)linear_atX(x - (float)*(ptrs0++),y,z,c,(T)0); } } else // Nearest-neighbor interpolation switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*width(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const int mx = cimg::mod(x - (int)cimg::round(*(ptrs0++)),w2); *(ptrd++) = (*this)(mx<width()?mx:w2 - mx - 1,y,z,c); } } } break; case 2 : // Periodic cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (*this)(cimg::mod(x - (int)cimg::round(*(ptrs0++)),width()),y,z,c); } break; case 1 : // Neumann cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _atX(x - (int)cimg::round(*(ptrs0++)),y,z,c); } break; default : // Dirichlet cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = atX(x - (int)cimg::round(*(ptrs0++)),y,z,c,(T)0); } } } else { // Backward-absolute warp if (interpolation==2) // Cubic interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*width(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const float mx = cimg::mod((float)*(ptrs0++),w2); *(ptrd++) = _cubic_atX_c(mx<width()?mx:w2 - mx - 1,0,0,c); } } } break; case 2 : // Periodic cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _cubic_atX_pc((float)*(ptrs0++),0,0,c); } break; case 1 : // Neumann cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _cubic_atX_c((float)*(ptrs0++),0,0,c); } break; default : // Dirichlet cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = cubic_atX_c((float)*(ptrs0++),0,0,c,(T)0); } } else if (interpolation==1) // Linear interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*width(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const float mx = cimg::mod((float)*(ptrs0++),w2); *(ptrd++) = (T)_linear_atX(mx<width()?mx:w2 - mx - 1,0,0,c); } } } break; case 2 : // Periodic cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)_linear_atX_p((float)*(ptrs0++),0,0,c); } break; case 1 : // Neumann cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)_linear_atX((float)*(ptrs0++),0,0,c); } break; default : // Dirichlet cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)linear_atX((float)*(ptrs0++),0,0,c,(T)0); } } else // Nearest-neighbor interpolation switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*width(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const int mx = cimg::mod((int)cimg::round(*(ptrs0++)),w2); *(ptrd++) = (*this)(mx<width()?mx:w2 - mx - 1,0,0,c); } } } break; case 2 : // Periodic cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (*this)(cimg::mod((int)cimg::round(*(ptrs0++)),width()),0,0,c); } break; case 1 : // Neumann cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _atX((int)cimg::round(*(ptrs0++)),0,0,c); } break; default : // Dirichlet cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = atX((int)cimg::round(*(ptrs0++)),0,0,c,(T)0); } } } } else if (p_warp._spectrum==2) { // 2D warping if (mode>=3) { // Forward-relative warp res.fill((T)0); if (interpolation>=1) // Linear interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); const T *ptrs = data(0,y,z,c); cimg_forX(res,x) res.set_linear_atXY(*(ptrs++),x + (float)*(ptrs0++),y + (float)*(ptrs1++),z,c); } else // Nearest-neighbor interpolation cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); const T *ptrs = data(0,y,z,c); cimg_forX(res,x) { const int X = x + (int)cimg::round(*(ptrs0++)), Y = y + (int)cimg::round(*(ptrs1++)); if (X>=0 && X<width() && Y>=0 && Y<height()) res(X,Y,z,c) = *(ptrs++); } } } else if (mode==2) { // Forward-absolute warp res.fill((T)0); if (interpolation>=1) // Linear interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); const T *ptrs = data(0,y,z,c); cimg_forX(res,x) res.set_linear_atXY(*(ptrs++),(float)*(ptrs0++),(float)*(ptrs1++),z,c); } else // Nearest-neighbor interpolation cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); const T *ptrs = data(0,y,z,c); cimg_forX(res,x) { const int X = (int)cimg::round(*(ptrs0++)), Y = (int)cimg::round(*(ptrs1++)); if (X>=0 && X<width() && Y>=0 && Y<height()) res(X,Y,z,c) = *(ptrs++); } } } else if (mode==1) { // Backward-relative warp if (interpolation==2) // Cubic interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*width(), h2 = 2.f*height(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const float mx = cimg::mod(x - (float)*(ptrs0++),w2), my = cimg::mod(y - (float)*(ptrs1++),h2); *(ptrd++) = _cubic_atXY_c(mx<width()?mx:w2 - mx - 1,my<height()?my:h2 - my - 1,z,c); } } } break; case 2 : // Periodic cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _cubic_atXY_pc(x - (float)*(ptrs0++),y - (float)*(ptrs1++),z,c); } break; case 1 : // Neumann cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _cubic_atXY_c(x - (float)*(ptrs0++),y - (float)*(ptrs1++),z,c); } break; default : // Dirichlet cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = cubic_atXY_c(x - (float)*(ptrs0++),y - (float)*(ptrs1++),z,c,(T)0); } } else if (interpolation==1) // Linear interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*width(), h2 = 2.f*height(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const float mx = cimg::mod(x - (float)*(ptrs0++),w2), my = cimg::mod(y - (float)*(ptrs1++),h2); *(ptrd++) = (T)_linear_atXY(mx<width()?mx:w2 - mx - 1,my<height()?my:h2 - my - 1,z,c); } } } break; case 2 : // Periodic cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)_linear_atXY_p(x - (float)*(ptrs0++),y - (float)*(ptrs1++),z,c); } break; case 1 : // Neumann cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)_linear_atXY(x - (float)*(ptrs0++),y - (float)*(ptrs1++),z,c); } break; default : // Dirichlet cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)linear_atXY(x - (float)*(ptrs0++),y - (float)*(ptrs1++),z,c,(T)0); } } else // Nearest-neighbor interpolation switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*width(), h2 = 2*height(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const int mx = cimg::mod(x - (int)cimg::round(*(ptrs0++)),w2), my = cimg::mod(y - (int)cimg::round(*(ptrs1++)),h2); *(ptrd++) = (*this)(mx<width()?mx:w2 - mx - 1,my<height()?my:h2 - my - 1,z,c); } } } break; case 2 : // Periodic cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (*this)(cimg::mod(x - (int)cimg::round(*(ptrs0++)),width()), cimg::mod(y - (int)cimg::round(*(ptrs1++)),height()),z,c); } break; case 1 : // Neumann cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _atXY(x - (int)cimg::round(*(ptrs0++)), y - (int)cimg::round(*(ptrs1++)),z,c); } break; default : // Dirichlet cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = atXY(x - (int)cimg::round(*(ptrs0++)), y - (int)cimg::round(*(ptrs1++)),z,c,(T)0); } } } else { // Backward-absolute warp if (interpolation==2) // Cubic interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*width(), h2 = 2.f*height(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const float mx = cimg::mod((float)*(ptrs0++),w2), my = cimg::mod((float)*(ptrs1++),h2); *(ptrd++) = _cubic_atXY_c(mx<width()?mx:w2 - mx - 1,my<height()?my:h2 - my - 1,0,c); } } } break; case 2 : // Periodic cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _cubic_atXY_pc((float)*(ptrs0++),(float)*(ptrs1++),0,c); } break; case 1 : // Neumann cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _cubic_atXY_c((float)*(ptrs0++),(float)*(ptrs1++),0,c); } break; default : // Dirichlet cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = cubic_atXY_c((float)*(ptrs0++),(float)*(ptrs1++),0,c,(T)0); } } else if (interpolation==1) // Linear interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*width(), h2 = 2.f*height(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const float mx = cimg::mod((float)*(ptrs0++),w2), my = cimg::mod((float)*(ptrs1++),h2); *(ptrd++) = (T)_linear_atXY(mx<width()?mx:w2 - mx - 1,my<height()?my:h2 - my - 1,0,c); } } } break; case 2 : // Periodic cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)_linear_atXY_p((float)*(ptrs0++),(float)*(ptrs1++),0,c); } break; case 1 : // Neumann cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)_linear_atXY((float)*(ptrs0++),(float)*(ptrs1++),0,c); } break; default : // Dirichlet cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)linear_atXY((float)*(ptrs0++),(float)*(ptrs1++),0,c,(T)0); } } else // Nearest-neighbor interpolation switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*width(), h2 = 2*height(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const int mx = cimg::mod((int)cimg::round(*(ptrs0++)),w2), my = cimg::mod((int)cimg::round(*(ptrs1++)),h2); *(ptrd++) = (*this)(mx<width()?mx:w2 - mx - 1,my<height()?my:h2 - my - 1,0,c); } } } break; case 2 : // Periodic cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (*this)(cimg::mod((int)cimg::round(*(ptrs0++)),width()), cimg::mod((int)cimg::round(*(ptrs1++)),height()),0,c); } break; case 1 : // Neumann cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _atXY((int)cimg::round(*(ptrs0++)), (int)cimg::round(*(ptrs1++)),0,c); } break; default : // Dirichlet cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = atXY((int)cimg::round(*(ptrs0++)), (int)cimg::round(*(ptrs1++)),0,c,(T)0); } } } } else { // 3D warping if (mode>=3) { // Forward-relative warp res.fill((T)0); if (interpolation>=1) // Linear interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); const T *ptrs = data(0,y,z,c); cimg_forX(res,x) res.set_linear_atXYZ(*(ptrs++),x + (float)*(ptrs0++),y + (float)*(ptrs1++), z + (float)*(ptrs2++),c); } else // Nearest-neighbor interpolation cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); const T *ptrs = data(0,y,z,c); cimg_forX(res,x) { const int X = x + (int)cimg::round(*(ptrs0++)), Y = y + (int)cimg::round(*(ptrs1++)), Z = z + (int)cimg::round(*(ptrs2++)); if (X>=0 && X<width() && Y>=0 && Y<height() && Z>=0 && Z<depth()) res(X,Y,Z,c) = *(ptrs++); } } } else if (mode==2) { // Forward-absolute warp res.fill((T)0); if (interpolation>=1) // Linear interpolation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); const T *ptrs = data(0,y,z,c); cimg_forX(res,x) res.set_linear_atXYZ(*(ptrs++),(float)*(ptrs0++),(float)*(ptrs1++),(float)*(ptrs2++),c); } else // Nearest-neighbor interpolation cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); const T *ptrs = data(0,y,z,c); cimg_forX(res,x) { const int X = (int)cimg::round(*(ptrs0++)), Y = (int)cimg::round(*(ptrs1++)), Z = (int)cimg::round(*(ptrs2++)); if (X>=0 && X<width() && Y>=0 && Y<height() && Z>=0 && Z<depth()) res(X,Y,Z,c) = *(ptrs++); } } } else if (mode==1) { // Backward-relative warp if (interpolation==2) // Cubic interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*width(), h2 = 2.f*height(), d2 = 2.f*depth(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const float mx = cimg::mod(x - (float)*(ptrs0++),w2), my = cimg::mod(y - (float)*(ptrs1++),h2), mz = cimg::mod(z - (float)*(ptrs2++),d2); *(ptrd++) = _cubic_atXYZ_c(mx<width()?mx:w2 - mx - 1, my<height()?my:h2 - my - 1, mz<depth()?mz:d2 - mz - 1,c); } } } break; case 2 : // Periodic cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _cubic_atXYZ_pc(x - (float)*(ptrs0++),y - (float)*(ptrs1++),z - (float)*(ptrs2++),c); } break; case 1 : // Neumann cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _cubic_atXYZ_c(x - (float)*(ptrs0++),y - (float)*(ptrs1++),z - (float)*(ptrs2++),c); } break; default : // Dirichlet cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = cubic_atXYZ_c(x - (float)*(ptrs0++),y - (float)*(ptrs1++),z - (float)*(ptrs2++),c,(T)0); } } else if (interpolation==1) // Linear interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*width(), h2 = 2.f*height(), d2 = 2.f*depth(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const float mx = cimg::mod(x - (float)*(ptrs0++),w2), my = cimg::mod(y - (float)*(ptrs1++),h2), mz = cimg::mod(z - (float)*(ptrs2++),d2); *(ptrd++) = (T)_linear_atXYZ(mx<width()?mx:w2 - mx - 1, my<height()?my:h2 - my - 1, mz<depth()?mz:d2 - mz - 1,c); } } } break; case 2 : // Periodic cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)_linear_atXYZ_p(x - (float)*(ptrs0++),y - (float)*(ptrs1++), z - (float)*(ptrs2++),c); } break; case 1 : // Neumann cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)_linear_atXYZ(x - (float)*(ptrs0++),y - (float)*(ptrs1++),z - (float)*(ptrs2++),c); } break; default : // Dirichlet cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)linear_atXYZ(x - (float)*(ptrs0++),y - (float)*(ptrs1++),z - (float)*(ptrs2++),c,(T)0); } } else // Nearest neighbor interpolation switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*width(), h2 = 2*height(), d2 = 2*depth(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const int mx = cimg::mod(x - (int)cimg::round(*(ptrs0++)),w2), my = cimg::mod(y - (int)cimg::round(*(ptrs1++)),h2), mz = cimg::mod(z - (int)cimg::round(*(ptrs2++)),d2); *(ptrd++) = (*this)(mx<width()?mx:w2 - mx - 1, my<height()?my:h2 - my - 1, mz<depth()?mz:d2 - mz - 1,c); } } } break; case 2 : // Periodic cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (*this)(cimg::mod(x - (int)cimg::round(*(ptrs0++)),width()), cimg::mod(y - (int)cimg::round(*(ptrs1++)),height()), cimg::mod(z - (int)cimg::round(*(ptrs2++)),depth()),c); } break; case 1 : // Neumann cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _atXYZ(x - (int)cimg::round(*(ptrs0++)), y - (int)cimg::round(*(ptrs1++)), z - (int)cimg::round(*(ptrs2++)),c); } break; default : // Dirichlet cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = atXYZ(x - (int)cimg::round(*(ptrs0++)), y - (int)cimg::round(*(ptrs1++)), z - (int)cimg::round(*(ptrs2++)),c,(T)0); } } } else { // Backward-absolute warp if (interpolation==2) // Cubic interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*width(), h2 = 2.f*height(), d2 = 2.f*depth(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const float mx = cimg::mod((float)*(ptrs0++),w2), my = cimg::mod((float)*(ptrs1++),h2), mz = cimg::mod((float)*(ptrs2++),d2); *(ptrd++) = _cubic_atXYZ_c(mx<width()?mx:w2 - mx - 1, my<height()?my:h2 - my - 1, mz<depth()?mz:d2 - mz - 1,c); } } } break; case 2 : // Periodic cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _cubic_atXYZ_pc((float)*(ptrs0++),(float)*(ptrs1++),(float)*(ptrs2++),c); } break; case 1 : // Neumann cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _cubic_atXYZ_c((float)*(ptrs0++),(float)*(ptrs1++),(float)*(ptrs2++),c); } break; default : // Dirichlet cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = cubic_atXYZ_c((float)*(ptrs0++),(float)*(ptrs1++),(float)*(ptrs2++), c,(T)0); } } else if (interpolation==1) // Linear interpolation switch (boundary_conditions) { case 3 : { // Mirror const float w2 = 2.f*width(), h2 = 2.f*height(), d2 = 2.f*depth(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const float mx = cimg::mod((float)*(ptrs0++),w2), my = cimg::mod((float)*(ptrs1++),h2), mz = cimg::mod((float)*(ptrs2++),d2); *(ptrd++) = (T)_linear_atXYZ(mx<width()?mx:w2 - mx - 1, my<height()?my:h2 - my - 1, mz<depth()?mz:d2 - mz - 1,c); } } } break; case 2 :// Periodic cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)_linear_atXYZ_p((float)*(ptrs0++),(float)*(ptrs1++), (float)*(ptrs2++),c); } break; case 1 : // Neumann cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)_linear_atXYZ((float)*(ptrs0++),(float)*(ptrs1++),(float)*(ptrs2++),c); } break; default : // Dirichlet cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),1048576)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (T)linear_atXYZ((float)*(ptrs0++),(float)*(ptrs1++),(float)*(ptrs2++), c,(T)0); } } else // Nearest-neighbor interpolation switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*width(), h2 = 2*height(), d2 = 2*depth(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(res.size(),4096)) cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) { const int mx = cimg::mod((int)cimg::round(*(ptrs0++)),w2), my = cimg::mod((int)cimg::round(*(ptrs1++)),h2), mz = cimg::mod((int)cimg::round(*(ptrs2++)),d2); *(ptrd++) = (*this)(mx<width()?mx:w2 - mx - 1, my<height()?my:h2 - my - 1, mz<depth()?mz:d2 - mz - 1,c); } } } break; case 2 : // Periodic cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = (*this)(cimg::mod((int)cimg::round(*(ptrs0++)),width()), cimg::mod((int)cimg::round(*(ptrs1++)),height()), cimg::mod((int)cimg::round(*(ptrs2++)),depth()),c); } break; case 1 : // Neumann cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = _atXYZ((int)cimg::round(*(ptrs0++)), (int)cimg::round(*(ptrs1++)), (int)cimg::round(*(ptrs2++)),c); } break; default : // Dirichlet cimg_forYZC(res,y,z,c) { const t *ptrs0 = p_warp.data(0,y,z,0), *ptrs1 = p_warp.data(0,y,z,1), *ptrs2 = p_warp.data(0,y,z,2); T *ptrd = res.data(0,y,z,c); cimg_forX(res,x) *(ptrd++) = atXYZ((int)cimg::round(*(ptrs0++)), (int)cimg::round(*(ptrs1++)), (int)cimg::round(*(ptrs2++)),c,(T)0); } } } } return res; } //! Generate a 2D representation of a 3D image, with XY,XZ and YZ views. /** \param x0 X-coordinate of the projection point. \param y0 Y-coordinate of the projection point. \param z0 Z-coordinate of the projection point. **/ CImg<T> get_projections2d(const unsigned int x0, const unsigned int y0, const unsigned int z0) const { if (is_empty() || _depth<2) return +*this; const unsigned int _x0 = (x0>=_width)?_width - 1:x0, _y0 = (y0>=_height)?_height - 1:y0, _z0 = (z0>=_depth)?_depth - 1:z0; const CImg<T> img_xy = get_crop(0,0,_z0,0,_width - 1,_height - 1,_z0,_spectrum - 1), img_zy = get_crop(_x0,0,0,0,_x0,_height - 1,_depth - 1,_spectrum - 1).permute_axes("xzyc"). resize(_depth,_height,1,-100,-1), img_xz = get_crop(0,_y0,0,0,_width - 1,_y0,_depth - 1,_spectrum - 1).resize(_width,_depth,1,-100,-1); return CImg<T>(_width + _depth,_height + _depth,1,_spectrum,cimg::min(img_xy.min(),img_zy.min(),img_xz.min())). draw_image(0,0,img_xy).draw_image(img_xy._width,0,img_zy). draw_image(0,img_xy._height,img_xz); } //! Construct a 2D representation of a 3D image, with XY,XZ and YZ views \inplace. CImg<T>& projections2d(const unsigned int x0, const unsigned int y0, const unsigned int z0) { if (_depth<2) return *this; return get_projections2d(x0,y0,z0).move_to(*this); } //! Crop image region. /** \param x0 = X-coordinate of the upper-left crop rectangle corner. \param y0 = Y-coordinate of the upper-left crop rectangle corner. \param z0 = Z-coordinate of the upper-left crop rectangle corner. \param c0 = C-coordinate of the upper-left crop rectangle corner. \param x1 = X-coordinate of the lower-right crop rectangle corner. \param y1 = Y-coordinate of the lower-right crop rectangle corner. \param z1 = Z-coordinate of the lower-right crop rectangle corner. \param c1 = C-coordinate of the lower-right crop rectangle corner. \param boundary_conditions = Can be { 0=dirichlet | 1=neumann | 2=periodic | 3=mirror }. **/ CImg<T>& crop(const int x0, const int y0, const int z0, const int c0, const int x1, const int y1, const int z1, const int c1, const unsigned int boundary_conditions=0) { return get_crop(x0,y0,z0,c0,x1,y1,z1,c1,boundary_conditions).move_to(*this); } //! Crop image region \newinstance. CImg<T> get_crop(const int x0, const int y0, const int z0, const int c0, const int x1, const int y1, const int z1, const int c1, const unsigned int boundary_conditions=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "crop(): Empty instance.", cimg_instance); const int nx0 = x0<x1?x0:x1, nx1 = x0^x1^nx0, ny0 = y0<y1?y0:y1, ny1 = y0^y1^ny0, nz0 = z0<z1?z0:z1, nz1 = z0^z1^nz0, nc0 = c0<c1?c0:c1, nc1 = c0^c1^nc0; CImg<T> res(1U + nx1 - nx0,1U + ny1 - ny0,1U + nz1 - nz0,1U + nc1 - nc0); if (nx0<0 || nx1>=width() || ny0<0 || ny1>=height() || nz0<0 || nz1>=depth() || nc0<0 || nc1>=spectrum()) switch (boundary_conditions) { case 3 : { // Mirror const int w2 = 2*width(), h2 = 2*height(), d2 = 2*depth(), s2 = 2*spectrum(); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*16 && _height*_depth*_spectrum>=4)) cimg_forXYZC(res,x,y,z,c) { const int mx = cimg::mod(nx0 + x,w2), my = cimg::mod(ny0 + y,h2), mz = cimg::mod(nz0 + z,d2), mc = cimg::mod(nc0 + c,s2); res(x,y,z,c) = (*this)(mx<width()?mx:w2 - mx - 1, my<height()?my:h2 - my - 1, mz<depth()?mz:d2 - mz - 1, mc<spectrum()?mc:s2 - mc - 1); } } break; case 2 : { // Periodic cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*16 && _height*_depth*_spectrum>=4)) cimg_forXYZC(res,x,y,z,c) { res(x,y,z,c) = (*this)(cimg::mod(nx0 + x,width()),cimg::mod(ny0 + y,height()), cimg::mod(nz0 + z,depth()),cimg::mod(nc0 + c,spectrum())); } } break; case 1 : // Neumann cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*16 && _height*_depth*_spectrum>=4)) cimg_forXYZC(res,x,y,z,c) res(x,y,z,c) = _atXYZC(nx0 + x,ny0 + y,nz0 + z,nc0 + c); break; default : // Dirichlet res.fill((T)0).draw_image(-nx0,-ny0,-nz0,-nc0,*this); } else res.draw_image(-nx0,-ny0,-nz0,-nc0,*this); return res; } //! Crop image region \overloading. CImg<T>& crop(const int x0, const int y0, const int z0, const int x1, const int y1, const int z1, const unsigned int boundary_conditions=0) { return crop(x0,y0,z0,0,x1,y1,z1,_spectrum - 1,boundary_conditions); } //! Crop image region \newinstance. CImg<T> get_crop(const int x0, const int y0, const int z0, const int x1, const int y1, const int z1, const unsigned int boundary_conditions=0) const { return get_crop(x0,y0,z0,0,x1,y1,z1,_spectrum - 1,boundary_conditions); } //! Crop image region \overloading. CImg<T>& crop(const int x0, const int y0, const int x1, const int y1, const unsigned int boundary_conditions=0) { return crop(x0,y0,0,0,x1,y1,_depth - 1,_spectrum - 1,boundary_conditions); } //! Crop image region \newinstance. CImg<T> get_crop(const int x0, const int y0, const int x1, const int y1, const unsigned int boundary_conditions=0) const { return get_crop(x0,y0,0,0,x1,y1,_depth - 1,_spectrum - 1,boundary_conditions); } //! Crop image region \overloading. CImg<T>& crop(const int x0, const int x1, const unsigned int boundary_conditions=0) { return crop(x0,0,0,0,x1,_height - 1,_depth - 1,_spectrum - 1,boundary_conditions); } //! Crop image region \newinstance. CImg<T> get_crop(const int x0, const int x1, const unsigned int boundary_conditions=0) const { return get_crop(x0,0,0,0,x1,_height - 1,_depth - 1,_spectrum - 1,boundary_conditions); } //! Autocrop image region, regarding the specified background value. CImg<T>& autocrop(const T& value, const char *const axes="czyx") { if (is_empty()) return *this; for (const char *s = axes; *s; ++s) { const char axis = cimg::lowercase(*s); const CImg<intT> coords = _autocrop(value,axis); if (coords[0]==-1 && coords[1]==-1) return assign(); // Image has only 'value' pixels else switch (axis) { case 'x' : { const int x0 = coords[0], x1 = coords[1]; if (x0>=0 && x1>=0) crop(x0,x1); } break; case 'y' : { const int y0 = coords[0], y1 = coords[1]; if (y0>=0 && y1>=0) crop(0,y0,_width - 1,y1); } break; case 'z' : { const int z0 = coords[0], z1 = coords[1]; if (z0>=0 && z1>=0) crop(0,0,z0,_width - 1,_height - 1,z1); } break; default : { const int c0 = coords[0], c1 = coords[1]; if (c0>=0 && c1>=0) crop(0,0,0,c0,_width - 1,_height - 1,_depth - 1,c1); } } } return *this; } //! Autocrop image region, regarding the specified background value \newinstance. CImg<T> get_autocrop(const T& value, const char *const axes="czyx") const { return (+*this).autocrop(value,axes); } //! Autocrop image region, regarding the specified background color. /** \param color Color used for the crop. If \c 0, color is guessed. \param axes Axes used for the crop. **/ CImg<T>& autocrop(const T *const color=0, const char *const axes="zyx") { if (is_empty()) return *this; if (!color) { // Guess color const CImg<T> col1 = get_vector_at(0,0,0); const unsigned int w = _width, h = _height, d = _depth, s = _spectrum; autocrop(col1,axes); if (_width==w && _height==h && _depth==d && _spectrum==s) { const CImg<T> col2 = get_vector_at(w - 1,h - 1,d - 1); autocrop(col2,axes); } return *this; } for (const char *s = axes; *s; ++s) { const char axis = cimg::lowercase(*s); switch (axis) { case 'x' : { int x0 = width(), x1 = -1; cimg_forC(*this,c) { const CImg<intT> coords = get_shared_channel(c)._autocrop(color[c],'x'); const int nx0 = coords[0], nx1 = coords[1]; if (nx0>=0 && nx1>=0) { x0 = std::min(x0,nx0); x1 = std::max(x1,nx1); } } if (x0==width() && x1==-1) return assign(); else crop(x0,x1); } break; case 'y' : { int y0 = height(), y1 = -1; cimg_forC(*this,c) { const CImg<intT> coords = get_shared_channel(c)._autocrop(color[c],'y'); const int ny0 = coords[0], ny1 = coords[1]; if (ny0>=0 && ny1>=0) { y0 = std::min(y0,ny0); y1 = std::max(y1,ny1); } } if (y0==height() && y1==-1) return assign(); else crop(0,y0,_width - 1,y1); } break; default : { int z0 = depth(), z1 = -1; cimg_forC(*this,c) { const CImg<intT> coords = get_shared_channel(c)._autocrop(color[c],'z'); const int nz0 = coords[0], nz1 = coords[1]; if (nz0>=0 && nz1>=0) { z0 = std::min(z0,nz0); z1 = std::max(z1,nz1); } } if (z0==depth() && z1==-1) return assign(); else crop(0,0,z0,_width - 1,_height - 1,z1); } } } return *this; } //! Autocrop image region, regarding the specified background color \newinstance. CImg<T> get_autocrop(const T *const color=0, const char *const axes="zyx") const { return (+*this).autocrop(color,axes); } CImg<intT> _autocrop(const T& value, const char axis) const { CImg<intT> res; switch (cimg::lowercase(axis)) { case 'x' : { int x0 = -1, x1 = -1; cimg_forX(*this,x) cimg_forYZC(*this,y,z,c) if ((*this)(x,y,z,c)!=value) { x0 = x; x = width(); y = height(); z = depth(); c = spectrum(); } if (x0>=0) { for (int x = width() - 1; x>=0; --x) cimg_forYZC(*this,y,z,c) if ((*this)(x,y,z,c)!=value) { x1 = x; x = 0; y = height(); z = depth(); c = spectrum(); } } res = CImg<intT>::vector(x0,x1); } break; case 'y' : { int y0 = -1, y1 = -1; cimg_forY(*this,y) cimg_forXZC(*this,x,z,c) if ((*this)(x,y,z,c)!=value) { y0 = y; x = width(); y = height(); z = depth(); c = spectrum(); } if (y0>=0) { for (int y = height() - 1; y>=0; --y) cimg_forXZC(*this,x,z,c) if ((*this)(x,y,z,c)!=value) { y1 = y; x = width(); y = 0; z = depth(); c = spectrum(); } } res = CImg<intT>::vector(y0,y1); } break; case 'z' : { int z0 = -1, z1 = -1; cimg_forZ(*this,z) cimg_forXYC(*this,x,y,c) if ((*this)(x,y,z,c)!=value) { z0 = z; x = width(); y = height(); z = depth(); c = spectrum(); } if (z0>=0) { for (int z = depth() - 1; z>=0; --z) cimg_forXYC(*this,x,y,c) if ((*this)(x,y,z,c)!=value) { z1 = z; x = width(); y = height(); z = 0; c = spectrum(); } } res = CImg<intT>::vector(z0,z1); } break; default : { int c0 = -1, c1 = -1; cimg_forC(*this,c) cimg_forXYZ(*this,x,y,z) if ((*this)(x,y,z,c)!=value) { c0 = c; x = width(); y = height(); z = depth(); c = spectrum(); } if (c0>=0) { for (int c = spectrum() - 1; c>=0; --c) cimg_forXYZ(*this,x,y,z) if ((*this)(x,y,z,c)!=value) { c1 = c; x = width(); y = height(); z = depth(); c = 0; } } res = CImg<intT>::vector(c0,c1); } } return res; } //! Return specified image column. /** \param x0 Image column. **/ CImg<T> get_column(const int x0) const { return get_columns(x0,x0); } //! Return specified image column \inplace. CImg<T>& column(const int x0) { return columns(x0,x0); } //! Return specified range of image columns. /** \param x0 Starting image column. \param x1 Ending image column. **/ CImg<T>& columns(const int x0, const int x1) { return get_columns(x0,x1).move_to(*this); } //! Return specified range of image columns \inplace. CImg<T> get_columns(const int x0, const int x1) const { return get_crop(x0,0,0,0,x1,height() - 1,depth() - 1,spectrum() - 1); } //! Return specified image row. CImg<T> get_row(const int y0) const { return get_rows(y0,y0); } //! Return specified image row \inplace. /** \param y0 Image row. **/ CImg<T>& row(const int y0) { return rows(y0,y0); } //! Return specified range of image rows. /** \param y0 Starting image row. \param y1 Ending image row. **/ CImg<T> get_rows(const int y0, const int y1) const { return get_crop(0,y0,0,0,width() - 1,y1,depth() - 1,spectrum() - 1); } //! Return specified range of image rows \inplace. CImg<T>& rows(const int y0, const int y1) { return get_rows(y0,y1).move_to(*this); } //! Return specified image slice. /** \param z0 Image slice. **/ CImg<T> get_slice(const int z0) const { return get_slices(z0,z0); } //! Return specified image slice \inplace. CImg<T>& slice(const int z0) { return slices(z0,z0); } //! Return specified range of image slices. /** \param z0 Starting image slice. \param z1 Ending image slice. **/ CImg<T> get_slices(const int z0, const int z1) const { return get_crop(0,0,z0,0,width() - 1,height() - 1,z1,spectrum() - 1); } //! Return specified range of image slices \inplace. CImg<T>& slices(const int z0, const int z1) { return get_slices(z0,z1).move_to(*this); } //! Return specified image channel. /** \param c0 Image channel. **/ CImg<T> get_channel(const int c0) const { return get_channels(c0,c0); } //! Return specified image channel \inplace. CImg<T>& channel(const int c0) { return channels(c0,c0); } //! Return specified range of image channels. /** \param c0 Starting image channel. \param c1 Ending image channel. **/ CImg<T> get_channels(const int c0, const int c1) const { return get_crop(0,0,0,c0,width() - 1,height() - 1,depth() - 1,c1); } //! Return specified range of image channels \inplace. CImg<T>& channels(const int c0, const int c1) { return get_channels(c0,c1).move_to(*this); } //! Return stream line of a 2D or 3D vector field. CImg<floatT> get_streamline(const float x, const float y, const float z, const float L=256, const float dl=0.1f, const unsigned int interpolation_type=2, const bool is_backward_tracking=false, const bool is_oriented_only=false) const { if (_spectrum!=2 && _spectrum!=3) throw CImgInstanceException(_cimg_instance "streamline(): Instance is not a 2D or 3D vector field.", cimg_instance); if (_spectrum==2) { if (is_oriented_only) { typename CImg<T>::_functor4d_streamline2d_oriented func(*this); return streamline(func,x,y,z,L,dl,interpolation_type,is_backward_tracking,true, 0,0,0,_width - 1.f,_height - 1.f,0.f); } else { typename CImg<T>::_functor4d_streamline2d_directed func(*this); return streamline(func,x,y,z,L,dl,interpolation_type,is_backward_tracking,false, 0,0,0,_width - 1.f,_height - 1.f,0.f); } } if (is_oriented_only) { typename CImg<T>::_functor4d_streamline3d_oriented func(*this); return streamline(func,x,y,z,L,dl,interpolation_type,is_backward_tracking,true, 0,0,0,_width - 1.f,_height - 1.f,_depth - 1.f); } typename CImg<T>::_functor4d_streamline3d_directed func(*this); return streamline(func,x,y,z,L,dl,interpolation_type,is_backward_tracking,false, 0,0,0,_width - 1.f,_height - 1.f,_depth - 1.f); } //! Return stream line of a 3D vector field. /** \param func Vector field function. \param x X-coordinate of the starting point of the streamline. \param y Y-coordinate of the starting point of the streamline. \param z Z-coordinate of the starting point of the streamline. \param L Streamline length. \param dl Streamline length increment. \param interpolation_type Type of interpolation. Can be <tt>{ 0=nearest int | 1=linear | 2=2nd-order RK | 3=4th-order RK. }</tt>. \param is_backward_tracking Tells if the streamline is estimated forward or backward. \param is_oriented_only Tells if the direction of the vectors must be ignored. \param x0 X-coordinate of the first bounding-box vertex. \param y0 Y-coordinate of the first bounding-box vertex. \param z0 Z-coordinate of the first bounding-box vertex. \param x1 X-coordinate of the second bounding-box vertex. \param y1 Y-coordinate of the second bounding-box vertex. \param z1 Z-coordinate of the second bounding-box vertex. **/ template<typename tfunc> static CImg<floatT> streamline(const tfunc& func, const float x, const float y, const float z, const float L=256, const float dl=0.1f, const unsigned int interpolation_type=2, const bool is_backward_tracking=false, const bool is_oriented_only=false, const float x0=0, const float y0=0, const float z0=0, const float x1=0, const float y1=0, const float z1=0) { if (dl<=0) throw CImgArgumentException("CImg<%s>::streamline(): Invalid specified integration length %g " "(should be >0).", pixel_type(), dl); const bool is_bounded = (x0!=x1 || y0!=y1 || z0!=z1); if (L<=0 || (is_bounded && (x<x0 || x>x1 || y<y0 || y>y1 || z<z0 || z>z1))) return CImg<floatT>(); const unsigned int size_L = (unsigned int)cimg::round(L/dl + 1); CImg<floatT> coordinates(size_L,3); const float dl2 = dl/2; float *ptr_x = coordinates.data(0,0), *ptr_y = coordinates.data(0,1), *ptr_z = coordinates.data(0,2), pu = (float)(dl*func(x,y,z,0)), pv = (float)(dl*func(x,y,z,1)), pw = (float)(dl*func(x,y,z,2)), X = x, Y = y, Z = z; switch (interpolation_type) { case 0 : { // Nearest integer interpolation cimg_forX(coordinates,l) { *(ptr_x++) = X; *(ptr_y++) = Y; *(ptr_z++) = Z; const int xi = (int)(X>0?X + 0.5f:X - 0.5f), yi = (int)(Y>0?Y + 0.5f:Y - 0.5f), zi = (int)(Z>0?Z + 0.5f:Z - 0.5f); float u = (float)(dl*func((float)xi,(float)yi,(float)zi,0)), v = (float)(dl*func((float)xi,(float)yi,(float)zi,1)), w = (float)(dl*func((float)xi,(float)yi,(float)zi,2)); if (is_oriented_only && u*pu + v*pv + w*pw<0) { u = -u; v = -v; w = -w; } if (is_backward_tracking) { X-=(pu=u); Y-=(pv=v); Z-=(pw=w); } else { X+=(pu=u); Y+=(pv=v); Z+=(pw=w); } if (is_bounded && (X<x0 || X>x1 || Y<y0 || Y>y1 || Z<z0 || Z>z1)) break; } } break; case 1 : { // First-order interpolation cimg_forX(coordinates,l) { *(ptr_x++) = X; *(ptr_y++) = Y; *(ptr_z++) = Z; float u = (float)(dl*func(X,Y,Z,0)), v = (float)(dl*func(X,Y,Z,1)), w = (float)(dl*func(X,Y,Z,2)); if (is_oriented_only && u*pu + v*pv + w*pw<0) { u = -u; v = -v; w = -w; } if (is_backward_tracking) { X-=(pu=u); Y-=(pv=v); Z-=(pw=w); } else { X+=(pu=u); Y+=(pv=v); Z+=(pw=w); } if (is_bounded && (X<x0 || X>x1 || Y<y0 || Y>y1 || Z<z0 || Z>z1)) break; } } break; case 2 : { // Second order interpolation cimg_forX(coordinates,l) { *(ptr_x++) = X; *(ptr_y++) = Y; *(ptr_z++) = Z; float u0 = (float)(dl2*func(X,Y,Z,0)), v0 = (float)(dl2*func(X,Y,Z,1)), w0 = (float)(dl2*func(X,Y,Z,2)); if (is_oriented_only && u0*pu + v0*pv + w0*pw<0) { u0 = -u0; v0 = -v0; w0 = -w0; } float u = (float)(dl*func(X + u0,Y + v0,Z + w0,0)), v = (float)(dl*func(X + u0,Y + v0,Z + w0,1)), w = (float)(dl*func(X + u0,Y + v0,Z + w0,2)); if (is_oriented_only && u*pu + v*pv + w*pw<0) { u = -u; v = -v; w = -w; } if (is_backward_tracking) { X-=(pu=u); Y-=(pv=v); Z-=(pw=w); } else { X+=(pu=u); Y+=(pv=v); Z+=(pw=w); } if (is_bounded && (X<x0 || X>x1 || Y<y0 || Y>y1 || Z<z0 || Z>z1)) break; } } break; default : { // Fourth order interpolation cimg_forX(coordinates,k) { *(ptr_x++) = X; *(ptr_y++) = Y; *(ptr_z++) = Z; float u0 = (float)(dl2*func(X,Y,Z,0)), v0 = (float)(dl2*func(X,Y,Z,1)), w0 = (float)(dl2*func(X,Y,Z,2)); if (is_oriented_only && u0*pu + v0*pv + w0*pw<0) { u0 = -u0; v0 = -v0; w0 = -w0; } float u1 = (float)(dl2*func(X + u0,Y + v0,Z + w0,0)), v1 = (float)(dl2*func(X + u0,Y + v0,Z + w0,1)), w1 = (float)(dl2*func(X + u0,Y + v0,Z + w0,2)); if (is_oriented_only && u1*pu + v1*pv + w1*pw<0) { u1 = -u1; v1 = -v1; w1 = -w1; } float u2 = (float)(dl2*func(X + u1,Y + v1,Z + w1,0)), v2 = (float)(dl2*func(X + u1,Y + v1,Z + w1,1)), w2 = (float)(dl2*func(X + u1,Y + v1,Z + w1,2)); if (is_oriented_only && u2*pu + v2*pv + w2*pw<0) { u2 = -u2; v2 = -v2; w2 = -w2; } float u3 = (float)(dl2*func(X + u2,Y + v2,Z + w2,0)), v3 = (float)(dl2*func(X + u2,Y + v2,Z + w2,1)), w3 = (float)(dl2*func(X + u2,Y + v2,Z + w2,2)); if (is_oriented_only && u2*pu + v2*pv + w2*pw<0) { u3 = -u3; v3 = -v3; w3 = -w3; } const float u = (u0 + u3)/3 + (u1 + u2)/1.5f, v = (v0 + v3)/3 + (v1 + v2)/1.5f, w = (w0 + w3)/3 + (w1 + w2)/1.5f; if (is_backward_tracking) { X-=(pu=u); Y-=(pv=v); Z-=(pw=w); } else { X+=(pu=u); Y+=(pv=v); Z+=(pw=w); } if (is_bounded && (X<x0 || X>x1 || Y<y0 || Y>y1 || Z<z0 || Z>z1)) break; } } } if (ptr_x!=coordinates.data(0,1)) coordinates.resize((int)(ptr_x-coordinates.data()),3,1,1,0); return coordinates; } //! Return stream line of a 3D vector field \overloading. static CImg<floatT> streamline(const char *const expression, const float x, const float y, const float z, const float L=256, const float dl=0.1f, const unsigned int interpolation_type=2, const bool is_backward_tracking=true, const bool is_oriented_only=false, const float x0=0, const float y0=0, const float z0=0, const float x1=0, const float y1=0, const float z1=0) { _functor4d_streamline_expr func(expression); return streamline(func,x,y,z,L,dl,interpolation_type,is_backward_tracking,is_oriented_only,x0,y0,z0,x1,y1,z1); } struct _functor4d_streamline2d_directed { const CImg<T>& ref; _functor4d_streamline2d_directed(const CImg<T>& pref):ref(pref) {} float operator()(const float x, const float y, const float z, const unsigned int c) const { return c<2?(float)ref._linear_atXY(x,y,(int)z,c):0; } }; struct _functor4d_streamline3d_directed { const CImg<T>& ref; _functor4d_streamline3d_directed(const CImg<T>& pref):ref(pref) {} float operator()(const float x, const float y, const float z, const unsigned int c) const { return (float)ref._linear_atXYZ(x,y,z,c); } }; struct _functor4d_streamline2d_oriented { const CImg<T>& ref; CImg<floatT> *pI; _functor4d_streamline2d_oriented(const CImg<T>& pref):ref(pref),pI(0) { pI = new CImg<floatT>(2,2,1,2); } ~_functor4d_streamline2d_oriented() { delete pI; } float operator()(const float x, const float y, const float z, const unsigned int c) const { #define _cimg_vecalign2d(i,j) \ if (I(i,j,0)*I(0,0,0) + I(i,j,1)*I(0,0,1)<0) { I(i,j,0) = -I(i,j,0); I(i,j,1) = -I(i,j,1); } int xi = (int)x - (x>=0?0:1), nxi = xi + 1, yi = (int)y - (y>=0?0:1), nyi = yi + 1, zi = (int)z; const float dx = x - xi, dy = y - yi; if (c==0) { CImg<floatT>& I = *pI; if (xi<0) xi = 0; if (nxi<0) nxi = 0; if (xi>=ref.width()) xi = ref.width() - 1; if (nxi>=ref.width()) nxi = ref.width() - 1; if (yi<0) yi = 0; if (nyi<0) nyi = 0; if (yi>=ref.height()) yi = ref.height() - 1; if (nyi>=ref.height()) nyi = ref.height() - 1; I(0,0,0) = (float)ref(xi,yi,zi,0); I(0,0,1) = (float)ref(xi,yi,zi,1); I(1,0,0) = (float)ref(nxi,yi,zi,0); I(1,0,1) = (float)ref(nxi,yi,zi,1); I(1,1,0) = (float)ref(nxi,nyi,zi,0); I(1,1,1) = (float)ref(nxi,nyi,zi,1); I(0,1,0) = (float)ref(xi,nyi,zi,0); I(0,1,1) = (float)ref(xi,nyi,zi,1); _cimg_vecalign2d(1,0); _cimg_vecalign2d(1,1); _cimg_vecalign2d(0,1); } return c<2?(float)pI->_linear_atXY(dx,dy,0,c):0; } }; struct _functor4d_streamline3d_oriented { const CImg<T>& ref; CImg<floatT> *pI; _functor4d_streamline3d_oriented(const CImg<T>& pref):ref(pref),pI(0) { pI = new CImg<floatT>(2,2,2,3); } ~_functor4d_streamline3d_oriented() { delete pI; } float operator()(const float x, const float y, const float z, const unsigned int c) const { #define _cimg_vecalign3d(i,j,k) if (I(i,j,k,0)*I(0,0,0,0) + I(i,j,k,1)*I(0,0,0,1) + I(i,j,k,2)*I(0,0,0,2)<0) { \ I(i,j,k,0) = -I(i,j,k,0); I(i,j,k,1) = -I(i,j,k,1); I(i,j,k,2) = -I(i,j,k,2); } int xi = (int)x - (x>=0?0:1), nxi = xi + 1, yi = (int)y - (y>=0?0:1), nyi = yi + 1, zi = (int)z - (z>=0?0:1), nzi = zi + 1; const float dx = x - xi, dy = y - yi, dz = z - zi; if (c==0) { CImg<floatT>& I = *pI; if (xi<0) xi = 0; if (nxi<0) nxi = 0; if (xi>=ref.width()) xi = ref.width() - 1; if (nxi>=ref.width()) nxi = ref.width() - 1; if (yi<0) yi = 0; if (nyi<0) nyi = 0; if (yi>=ref.height()) yi = ref.height() - 1; if (nyi>=ref.height()) nyi = ref.height() - 1; if (zi<0) zi = 0; if (nzi<0) nzi = 0; if (zi>=ref.depth()) zi = ref.depth() - 1; if (nzi>=ref.depth()) nzi = ref.depth() - 1; I(0,0,0,0) = (float)ref(xi,yi,zi,0); I(0,0,0,1) = (float)ref(xi,yi,zi,1); I(0,0,0,2) = (float)ref(xi,yi,zi,2); I(1,0,0,0) = (float)ref(nxi,yi,zi,0); I(1,0,0,1) = (float)ref(nxi,yi,zi,1); I(1,0,0,2) = (float)ref(nxi,yi,zi,2); I(1,1,0,0) = (float)ref(nxi,nyi,zi,0); I(1,1,0,1) = (float)ref(nxi,nyi,zi,1); I(1,1,0,2) = (float)ref(nxi,nyi,zi,2); I(0,1,0,0) = (float)ref(xi,nyi,zi,0); I(0,1,0,1) = (float)ref(xi,nyi,zi,1); I(0,1,0,2) = (float)ref(xi,nyi,zi,2); I(0,0,1,0) = (float)ref(xi,yi,nzi,0); I(0,0,1,1) = (float)ref(xi,yi,nzi,1); I(0,0,1,2) = (float)ref(xi,yi,nzi,2); I(1,0,1,0) = (float)ref(nxi,yi,nzi,0); I(1,0,1,1) = (float)ref(nxi,yi,nzi,1); I(1,0,1,2) = (float)ref(nxi,yi,nzi,2); I(1,1,1,0) = (float)ref(nxi,nyi,nzi,0); I(1,1,1,1) = (float)ref(nxi,nyi,nzi,1); I(1,1,1,2) = (float)ref(nxi,nyi,nzi,2); I(0,1,1,0) = (float)ref(xi,nyi,nzi,0); I(0,1,1,1) = (float)ref(xi,nyi,nzi,1); I(0,1,1,2) = (float)ref(xi,nyi,nzi,2); _cimg_vecalign3d(1,0,0); _cimg_vecalign3d(1,1,0); _cimg_vecalign3d(0,1,0); _cimg_vecalign3d(0,0,1); _cimg_vecalign3d(1,0,1); _cimg_vecalign3d(1,1,1); _cimg_vecalign3d(0,1,1); } return (float)pI->_linear_atXYZ(dx,dy,dz,c); } }; struct _functor4d_streamline_expr { _cimg_math_parser *mp; ~_functor4d_streamline_expr() { mp->end(); delete mp; } _functor4d_streamline_expr(const char *const expr):mp(0) { mp = new _cimg_math_parser(expr,"streamline",CImg<T>::const_empty(),0); } float operator()(const float x, const float y, const float z, const unsigned int c) const { return (float)(*mp)(x,y,z,c); } }; //! Return a shared-memory image referencing a range of pixels of the image instance. /** \param x0 X-coordinate of the starting pixel. \param x1 X-coordinate of the ending pixel. \param y0 Y-coordinate. \param z0 Z-coordinate. \param c0 C-coordinate. **/ CImg<T> get_shared_points(const unsigned int x0, const unsigned int x1, const unsigned int y0=0, const unsigned int z0=0, const unsigned int c0=0) { const unsigned int beg = (unsigned int)offset(x0,y0,z0,c0), end = (unsigned int)offset(x1,y0,z0,c0); if (beg>end || beg>=size() || end>=size()) throw CImgArgumentException(_cimg_instance "get_shared_points(): Invalid request of a shared-memory subset (%u->%u,%u,%u,%u).", cimg_instance, x0,x1,y0,z0,c0); return CImg<T>(_data + beg,x1 - x0 + 1,1,1,1,true); } //! Return a shared-memory image referencing a range of pixels of the image instance \const. const CImg<T> get_shared_points(const unsigned int x0, const unsigned int x1, const unsigned int y0=0, const unsigned int z0=0, const unsigned int c0=0) const { const unsigned int beg = (unsigned int)offset(x0,y0,z0,c0), end = (unsigned int)offset(x1,y0,z0,c0); if (beg>end || beg>=size() || end>=size()) throw CImgArgumentException(_cimg_instance "get_shared_points(): Invalid request of a shared-memory subset (%u->%u,%u,%u,%u).", cimg_instance, x0,x1,y0,z0,c0); return CImg<T>(_data + beg,x1 - x0 + 1,1,1,1,true); } //! Return a shared-memory image referencing a range of rows of the image instance. /** \param y0 Y-coordinate of the starting row. \param y1 Y-coordinate of the ending row. \param z0 Z-coordinate. \param c0 C-coordinate. **/ CImg<T> get_shared_rows(const unsigned int y0, const unsigned int y1, const unsigned int z0=0, const unsigned int c0=0) { const unsigned int beg = (unsigned int)offset(0,y0,z0,c0), end = (unsigned int)offset(0,y1,z0,c0); if (beg>end || beg>=size() || end>=size()) throw CImgArgumentException(_cimg_instance "get_shared_rows(): Invalid request of a shared-memory subset " "(0->%u,%u->%u,%u,%u).", cimg_instance, _width - 1,y0,y1,z0,c0); return CImg<T>(_data + beg,_width,y1 - y0 + 1,1,1,true); } //! Return a shared-memory image referencing a range of rows of the image instance \const. const CImg<T> get_shared_rows(const unsigned int y0, const unsigned int y1, const unsigned int z0=0, const unsigned int c0=0) const { const unsigned int beg = (unsigned int)offset(0,y0,z0,c0), end = (unsigned int)offset(0,y1,z0,c0); if (beg>end || beg>=size() || end>=size()) throw CImgArgumentException(_cimg_instance "get_shared_rows(): Invalid request of a shared-memory subset " "(0->%u,%u->%u,%u,%u).", cimg_instance, _width - 1,y0,y1,z0,c0); return CImg<T>(_data + beg,_width,y1 - y0 + 1,1,1,true); } //! Return a shared-memory image referencing one row of the image instance. /** \param y0 Y-coordinate. \param z0 Z-coordinate. \param c0 C-coordinate. **/ CImg<T> get_shared_row(const unsigned int y0, const unsigned int z0=0, const unsigned int c0=0) { return get_shared_rows(y0,y0,z0,c0); } //! Return a shared-memory image referencing one row of the image instance \const. const CImg<T> get_shared_row(const unsigned int y0, const unsigned int z0=0, const unsigned int c0=0) const { return get_shared_rows(y0,y0,z0,c0); } //! Return a shared memory image referencing a range of slices of the image instance. /** \param z0 Z-coordinate of the starting slice. \param z1 Z-coordinate of the ending slice. \param c0 C-coordinate. **/ CImg<T> get_shared_slices(const unsigned int z0, const unsigned int z1, const unsigned int c0=0) { const unsigned int beg = (unsigned int)offset(0,0,z0,c0), end = (unsigned int)offset(0,0,z1,c0); if (beg>end || beg>=size() || end>=size()) throw CImgArgumentException(_cimg_instance "get_shared_slices(): Invalid request of a shared-memory subset " "(0->%u,0->%u,%u->%u,%u).", cimg_instance, _width - 1,_height - 1,z0,z1,c0); return CImg<T>(_data + beg,_width,_height,z1 - z0 + 1,1,true); } //! Return a shared memory image referencing a range of slices of the image instance \const. const CImg<T> get_shared_slices(const unsigned int z0, const unsigned int z1, const unsigned int c0=0) const { const unsigned int beg = (unsigned int)offset(0,0,z0,c0), end = (unsigned int)offset(0,0,z1,c0); if (beg>end || beg>=size() || end>=size()) throw CImgArgumentException(_cimg_instance "get_shared_slices(): Invalid request of a shared-memory subset " "(0->%u,0->%u,%u->%u,%u).", cimg_instance, _width - 1,_height - 1,z0,z1,c0); return CImg<T>(_data + beg,_width,_height,z1 - z0 + 1,1,true); } //! Return a shared-memory image referencing one slice of the image instance. /** \param z0 Z-coordinate. \param c0 C-coordinate. **/ CImg<T> get_shared_slice(const unsigned int z0, const unsigned int c0=0) { return get_shared_slices(z0,z0,c0); } //! Return a shared-memory image referencing one slice of the image instance \const. const CImg<T> get_shared_slice(const unsigned int z0, const unsigned int c0=0) const { return get_shared_slices(z0,z0,c0); } //! Return a shared-memory image referencing a range of channels of the image instance. /** \param c0 C-coordinate of the starting channel. \param c1 C-coordinate of the ending channel. **/ CImg<T> get_shared_channels(const unsigned int c0, const unsigned int c1) { const unsigned int beg = (unsigned int)offset(0,0,0,c0), end = (unsigned int)offset(0,0,0,c1); if (beg>end || beg>=size() || end>=size()) throw CImgArgumentException(_cimg_instance "get_shared_channels(): Invalid request of a shared-memory subset " "(0->%u,0->%u,0->%u,%u->%u).", cimg_instance, _width - 1,_height - 1,_depth - 1,c0,c1); return CImg<T>(_data + beg,_width,_height,_depth,c1 - c0 + 1,true); } //! Return a shared-memory image referencing a range of channels of the image instance \const. const CImg<T> get_shared_channels(const unsigned int c0, const unsigned int c1) const { const unsigned int beg = (unsigned int)offset(0,0,0,c0), end = (unsigned int)offset(0,0,0,c1); if (beg>end || beg>=size() || end>=size()) throw CImgArgumentException(_cimg_instance "get_shared_channels(): Invalid request of a shared-memory subset " "(0->%u,0->%u,0->%u,%u->%u).", cimg_instance, _width - 1,_height - 1,_depth - 1,c0,c1); return CImg<T>(_data + beg,_width,_height,_depth,c1 - c0 + 1,true); } //! Return a shared-memory image referencing one channel of the image instance. /** \param c0 C-coordinate. **/ CImg<T> get_shared_channel(const unsigned int c0) { return get_shared_channels(c0,c0); } //! Return a shared-memory image referencing one channel of the image instance \const. const CImg<T> get_shared_channel(const unsigned int c0) const { return get_shared_channels(c0,c0); } //! Return a shared-memory version of the image instance. CImg<T> get_shared() { return CImg<T>(_data,_width,_height,_depth,_spectrum,true); } //! Return a shared-memory version of the image instance \const. const CImg<T> get_shared() const { return CImg<T>(_data,_width,_height,_depth,_spectrum,true); } //! Split image into a list along specified axis. /** \param axis Splitting axis. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param nb Number of splitted parts. \note - If \c nb==0, instance image is splitted into blocs of egal values along the specified axis. - If \c nb<=0, instance image is splitted into blocs of -\c nb pixel wide. - If \c nb>0, instance image is splitted into \c nb blocs. **/ CImgList<T> get_split(const char axis, const int nb=-1) const { CImgList<T> res; if (is_empty()) return res; const char _axis = cimg::lowercase(axis); if (nb<0) { // Split by bloc size const unsigned int dp = (unsigned int)(nb?-nb:1); switch (_axis) { case 'x': { if (_width>dp) { res.assign(_width/dp + (_width%dp?1:0),1,1); const unsigned int pe = _width - dp; cimg_pragma_openmp(parallel for cimg_openmp_if(res._width>=(cimg_openmp_sizefactor)*128 && _height*_depth*_spectrum>=128)) for (int p = 0; p<(int)pe; p+=dp) get_crop(p,0,0,0,p + dp - 1,_height - 1,_depth - 1,_spectrum - 1).move_to(res[p/dp]); get_crop((res._width - 1)*dp,0,0,0,_width - 1,_height - 1,_depth - 1,_spectrum - 1).move_to(res.back()); } else res.assign(*this); } break; case 'y': { if (_height>dp) { res.assign(_height/dp + (_height%dp?1:0),1,1); const unsigned int pe = _height - dp; cimg_pragma_openmp(parallel for cimg_openmp_if(res._width>=(cimg_openmp_sizefactor)*128 && _width*_depth*_spectrum>=128)) for (int p = 0; p<(int)pe; p+=dp) get_crop(0,p,0,0,_width - 1,p + dp - 1,_depth - 1,_spectrum - 1).move_to(res[p/dp]); get_crop(0,(res._width - 1)*dp,0,0,_width - 1,_height - 1,_depth - 1,_spectrum - 1).move_to(res.back()); } else res.assign(*this); } break; case 'z': { if (_depth>dp) { res.assign(_depth/dp + (_depth%dp?1:0),1,1); const unsigned int pe = _depth - dp; cimg_pragma_openmp(parallel for cimg_openmp_if(res._width>=(cimg_openmp_sizefactor)*128 && _width*_height*_spectrum>=128)) for (int p = 0; p<(int)pe; p+=dp) get_crop(0,0,p,0,_width - 1,_height - 1,p + dp - 1,_spectrum - 1).move_to(res[p/dp]); get_crop(0,0,(res._width - 1)*dp,0,_width - 1,_height - 1,_depth - 1,_spectrum - 1).move_to(res.back()); } else res.assign(*this); } break; case 'c' : { if (_spectrum>dp) { res.assign(_spectrum/dp + (_spectrum%dp?1:0),1,1); const unsigned int pe = _spectrum - dp; cimg_pragma_openmp(parallel for cimg_openmp_if(res._width>=(cimg_openmp_sizefactor)*128 && _width*_height*_depth>=128)) for (int p = 0; p<(int)pe; p+=dp) get_crop(0,0,0,p,_width - 1,_height - 1,_depth - 1,p + dp - 1).move_to(res[p/dp]); get_crop(0,0,0,(res._width - 1)*dp,_width - 1,_height - 1,_depth - 1,_spectrum - 1).move_to(res.back()); } else res.assign(*this); } } } else if (nb>0) { // Split by number of (non-homogeneous) blocs const unsigned int siz = _axis=='x'?_width:_axis=='y'?_height:_axis=='z'?_depth:_axis=='c'?_spectrum:0; if ((unsigned int)nb>siz) throw CImgArgumentException(_cimg_instance "get_split(): Instance cannot be split along %c-axis into %u blocs.", cimg_instance, axis,nb); if (nb==1) res.assign(*this); else { int err = (int)siz; unsigned int _p = 0; switch (_axis) { case 'x' : { cimg_forX(*this,p) if ((err-=nb)<=0) { get_crop(_p,0,0,0,p,_height - 1,_depth - 1,_spectrum - 1).move_to(res); err+=(int)siz; _p = p + 1U; } } break; case 'y' : { cimg_forY(*this,p) if ((err-=nb)<=0) { get_crop(0,_p,0,0,_width - 1,p,_depth - 1,_spectrum - 1).move_to(res); err+=(int)siz; _p = p + 1U; } } break; case 'z' : { cimg_forZ(*this,p) if ((err-=nb)<=0) { get_crop(0,0,_p,0,_width - 1,_height - 1,p,_spectrum - 1).move_to(res); err+=(int)siz; _p = p + 1U; } } break; case 'c' : { cimg_forC(*this,p) if ((err-=nb)<=0) { get_crop(0,0,0,_p,_width - 1,_height - 1,_depth - 1,p).move_to(res); err+=(int)siz; _p = p + 1U; } } } } } else { // Split by egal values according to specified axis T current = *_data; switch (_axis) { case 'x' : { int i0 = 0; cimg_forX(*this,i) if ((*this)(i)!=current) { get_columns(i0,i - 1).move_to(res); i0 = i; current = (*this)(i); } get_columns(i0,width() - 1).move_to(res); } break; case 'y' : { int i0 = 0; cimg_forY(*this,i) if ((*this)(0,i)!=current) { get_rows(i0,i - 1).move_to(res); i0 = i; current = (*this)(0,i); } get_rows(i0,height() - 1).move_to(res); } break; case 'z' : { int i0 = 0; cimg_forZ(*this,i) if ((*this)(0,0,i)!=current) { get_slices(i0,i - 1).move_to(res); i0 = i; current = (*this)(0,0,i); } get_slices(i0,depth() - 1).move_to(res); } break; case 'c' : { int i0 = 0; cimg_forC(*this,i) if ((*this)(0,0,0,i)!=current) { get_channels(i0,i - 1).move_to(res); i0 = i; current = (*this)(0,0,0,i); } get_channels(i0,spectrum() - 1).move_to(res); } break; default : { longT i0 = 0; cimg_foroff(*this,i) if ((*this)[i]!=current) { CImg<T>(_data + i0,1,(unsigned int)(i - i0)).move_to(res); i0 = (longT)i; current = (*this)[i]; } CImg<T>(_data + i0,1,(unsigned int)(size() - i0)).move_to(res); } } } return res; } //! Split image into a list of sub-images, according to a specified splitting value sequence and optionally axis. /** \param values Splitting value sequence. \param axis Axis along which the splitting is performed. Can be '0' to ignore axis. \param keep_values Tells if the splitting sequence must be kept in the splitted blocs. **/ template<typename t> CImgList<T> get_split(const CImg<t>& values, const char axis=0, const bool keep_values=true) const { typedef _cimg_Tt Tt; CImgList<T> res; if (is_empty()) return res; const ulongT vsiz = values.size(); const char _axis = cimg::lowercase(axis); if (!vsiz) return CImgList<T>(*this); if (vsiz==1) { // Split according to a single value const T value = (T)*values; switch (_axis) { case 'x' : { unsigned int i0 = 0, i = 0; do { while (i<_width && (*this)(i)==value) ++i; if (i>i0) { if (keep_values) get_columns(i0,i - 1).move_to(res); i0 = i; } while (i<_width && (*this)(i)!=value) ++i; if (i>i0) { get_columns(i0,i - 1).move_to(res); i0 = i; } } while (i<_width); } break; case 'y' : { unsigned int i0 = 0, i = 0; do { while (i<_height && (*this)(0,i)==value) ++i; if (i>i0) { if (keep_values) get_rows(i0,i - 1).move_to(res); i0 = i; } while (i<_height && (*this)(0,i)!=value) ++i; if (i>i0) { get_rows(i0,i - 1).move_to(res); i0 = i; } } while (i<_height); } break; case 'z' : { unsigned int i0 = 0, i = 0; do { while (i<_depth && (*this)(0,0,i)==value) ++i; if (i>i0) { if (keep_values) get_slices(i0,i - 1).move_to(res); i0 = i; } while (i<_depth && (*this)(0,0,i)!=value) ++i; if (i>i0) { get_slices(i0,i - 1).move_to(res); i0 = i; } } while (i<_depth); } break; case 'c' : { unsigned int i0 = 0, i = 0; do { while (i<_spectrum && (*this)(0,0,0,i)==value) ++i; if (i>i0) { if (keep_values) get_channels(i0,i - 1).move_to(res); i0 = i; } while (i<_spectrum && (*this)(0,0,0,i)!=value) ++i; if (i>i0) { get_channels(i0,i - 1).move_to(res); i0 = i; } } while (i<_spectrum); } break; default : { const ulongT siz = size(); ulongT i0 = 0, i = 0; do { while (i<siz && (*this)[i]==value) ++i; if (i>i0) { if (keep_values) CImg<T>(_data + i0,1,(unsigned int)(i - i0)).move_to(res); i0 = i; } while (i<siz && (*this)[i]!=value) ++i; if (i>i0) { CImg<T>(_data + i0,1,(unsigned int)(i - i0)).move_to(res); i0 = i; } } while (i<siz); } } } else { // Split according to multiple values ulongT j = 0; switch (_axis) { case 'x' : { unsigned int i0 = 0, i1 = 0, i = 0; do { if ((Tt)(*this)(i)==(Tt)*values) { i1 = i; j = 0; while (i<_width && (Tt)(*this)(i)==(Tt)values[j]) { ++i; if (++j>=vsiz) j = 0; } i-=j; if (i>i1) { if (i1>i0) get_columns(i0,i1 - 1).move_to(res); if (keep_values) get_columns(i1,i - 1).move_to(res); i0 = i; } else ++i; } else ++i; } while (i<_width); if (i0<_width) get_columns(i0,width() - 1).move_to(res); } break; case 'y' : { unsigned int i0 = 0, i1 = 0, i = 0; do { if ((Tt)(*this)(0,i)==(Tt)*values) { i1 = i; j = 0; while (i<_height && (Tt)(*this)(0,i)==(Tt)values[j]) { ++i; if (++j>=vsiz) j = 0; } i-=j; if (i>i1) { if (i1>i0) get_rows(i0,i1 - 1).move_to(res); if (keep_values) get_rows(i1,i - 1).move_to(res); i0 = i; } else ++i; } else ++i; } while (i<_height); if (i0<_height) get_rows(i0,height() - 1).move_to(res); } break; case 'z' : { unsigned int i0 = 0, i1 = 0, i = 0; do { if ((Tt)(*this)(0,0,i)==(Tt)*values) { i1 = i; j = 0; while (i<_depth && (Tt)(*this)(0,0,i)==(Tt)values[j]) { ++i; if (++j>=vsiz) j = 0; } i-=j; if (i>i1) { if (i1>i0) get_slices(i0,i1 - 1).move_to(res); if (keep_values) get_slices(i1,i - 1).move_to(res); i0 = i; } else ++i; } else ++i; } while (i<_depth); if (i0<_depth) get_slices(i0,depth() - 1).move_to(res); } break; case 'c' : { unsigned int i0 = 0, i1 = 0, i = 0; do { if ((Tt)(*this)(0,0,0,i)==(Tt)*values) { i1 = i; j = 0; while (i<_spectrum && (Tt)(*this)(0,0,0,i)==(Tt)values[j]) { ++i; if (++j>=vsiz) j = 0; } i-=j; if (i>i1) { if (i1>i0) get_channels(i0,i1 - 1).move_to(res); if (keep_values) get_channels(i1,i - 1).move_to(res); i0 = i; } else ++i; } else ++i; } while (i<_spectrum); if (i0<_spectrum) get_channels(i0,spectrum() - 1).move_to(res); } break; default : { ulongT i0 = 0, i1 = 0, i = 0; const ulongT siz = size(); do { if ((Tt)(*this)[i]==(Tt)*values) { i1 = i; j = 0; while (i<siz && (Tt)(*this)[i]==(Tt)values[j]) { ++i; if (++j>=vsiz) j = 0; } i-=j; if (i>i1) { if (i1>i0) CImg<T>(_data + i0,1,(unsigned int)(i1 - i0)).move_to(res); if (keep_values) CImg<T>(_data + i1,1,(unsigned int)(i - i1)).move_to(res); i0 = i; } else ++i; } else ++i; } while (i<siz); if (i0<siz) CImg<T>(_data + i0,1,(unsigned int)(siz - i0)).move_to(res); } break; } } return res; } //! Append two images along specified axis. /** \param img Image to append with instance image. \param axis Appending axis. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param align Append alignment in \c [0,1]. **/ template<typename t> CImg<T>& append(const CImg<t>& img, const char axis='x', const float align=0) { if (is_empty()) return assign(img,false); if (!img) return *this; return CImgList<T>(*this,true).insert(img).get_append(axis,align).move_to(*this); } //! Append two images along specified axis \specialization. CImg<T>& append(const CImg<T>& img, const char axis='x', const float align=0) { if (is_empty()) return assign(img,false); if (!img) return *this; return CImgList<T>(*this,img,true).get_append(axis,align).move_to(*this); } //! Append two images along specified axis \const. template<typename t> CImg<_cimg_Tt> get_append(const CImg<T>& img, const char axis='x', const float align=0) const { if (is_empty()) return +img; if (!img) return +*this; return CImgList<_cimg_Tt>(*this,true).insert(img).get_append(axis,align); } //! Append two images along specified axis \specialization. CImg<T> get_append(const CImg<T>& img, const char axis='x', const float align=0) const { if (is_empty()) return +img; if (!img) return +*this; return CImgList<T>(*this,img,true).get_append(axis,align); } //@} //--------------------------------------- // //! \name Filtering / Transforms //@{ //--------------------------------------- //! Correlate image by a kernel. /** \param kernel = the correlation kernel. \param boundary_conditions boundary conditions can be (false=dirichlet, true=neumann) \param is_normalized = enable local normalization. \param dilation = dilation \note - The correlation of the image instance \p *this by the kernel \p kernel is defined to be: res(x,y,z) = sum_{i,j,k} (*this)(x + i,y + j,z + k)*kernel(i,j,k). **/ template<typename t> CImg<T>& correlate(const CImg<t>& kernel, const bool boundary_conditions=true, const bool is_normalized=false, const int dilation=1) { if (is_empty() || !kernel) return *this; return get_correlate(kernel,boundary_conditions,is_normalized,dilation).move_to(*this); } template<typename t> CImg<_cimg_Ttfloat> get_correlate(const CImg<t>& kernel, const bool boundary_conditions=true, const bool is_normalized=false, const int dilation=1) const { return _correlate(kernel,boundary_conditions,is_normalized,dilation,false); } //! Correlate image by a kernel \newinstance. template<typename t> CImg<_cimg_Ttfloat> _correlate(const CImg<t>& kernel, const bool boundary_conditions, const bool is_normalized, /* const int x0, const int y0, const int z0, const int x1, const int y1, const int z1, const int xstep, const int ystep, const int zstep, */ const int dilation, const bool is_convolution) const { if (is_empty() || !kernel || dilation<0) return *this; typedef _cimg_Ttfloat Ttfloat; CImg<Ttfloat> res; const ulongT res_whd = (ulongT)_width*_height*_depth, res_size = res_whd*std::max(_spectrum,kernel._spectrum); const bool is_inner_parallel = _width*_height*_depth>=(cimg_openmp_sizefactor)*32768, is_outer_parallel = res_size>=(cimg_openmp_sizefactor)*32768; _cimg_abort_init_omp; cimg_abort_init; if (kernel._width==kernel._height && ((kernel._depth==1 && kernel._width<=5) || (kernel._depth==kernel._width && kernel._width<=3))) { // Special optimization done for 2x2, 3x3, 4x4, 5x5, 6x6, 2x2x2 and 3x3x3 kernel. if (!boundary_conditions && res_whd<=3000*3000) { // Dirichlet boundaries // For relatively small images, adding a zero border then use optimized NxN convolution loops is faster. res = (kernel._depth==1?get_crop(-1,-1,_width,_height):get_crop(-1,-1,-1,_width,_height,_depth)). _correlate(kernel,true,is_normalized,dilation,is_convolution); if (kernel._depth==1) res.crop(1,1,res._width - 2,res._height - 2); else res.crop(1,1,1,res._width - 2,res._height - 2,res._depth - 2); } else { // Neumann boundaries res.assign(_width,_height,_depth,std::max(_spectrum,kernel._spectrum)); cimg::unused(is_inner_parallel,is_outer_parallel); CImg<t> _kernel; if (is_convolution) { // Add empty column/row/slice to shift kernel center in case of convolution const int dw = !(kernel.width()%2), dh = !(kernel.height()%2), dd = !(kernel.depth()%2); if (dw || dh || dd) kernel.get_resize(kernel.width() + dw,kernel.height() + dh,kernel.depth() + dd,-100,0,0). move_to(_kernel); } if (!_kernel) _kernel = kernel.get_shared(); switch (_kernel._depth) { case 3 : { // 3x3x3 kernel cimg_forC(res,c) { cimg_abort_test; const CImg<T> I = get_shared_channel(c%_spectrum); const CImg<t> K = _kernel.get_shared_channel(c%kernel._spectrum); CImg<T> _res = res.get_shared_channel(c); if (is_normalized) { const Ttfloat M = (Ttfloat)K.magnitude(2), M2 = M*M; cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(_res.size(),16384)) cimg_forXYZ(res,x,y,z) { const int px = x>dilation?x - dilation:x, nx = x + dilation<res.width()?x + dilation:x, py = y>dilation?y - dilation:y, ny = y + dilation<res.height()?y + dilation:y, pz = z>dilation?z - dilation:z, nz = z + dilation<res.depth()?z + dilation:z; const Ttfloat N = M2*(cimg::sqr(I(px,py,pz)) + cimg::sqr(I(x,py,pz)) + cimg::sqr(I(nx,py,pz)) + cimg::sqr(I(px,y,pz)) + cimg::sqr(I(x,y,pz)) + cimg::sqr(I(nx,y,pz)) + cimg::sqr(I(px,ny,pz)) + cimg::sqr(I(x,ny,pz)) + cimg::sqr(I(nx,ny,pz)) + cimg::sqr(I(px,py,z)) + cimg::sqr(I(x,py,z)) + cimg::sqr(I(nx,py,z)) + cimg::sqr(I(px,y,z)) + cimg::sqr(I(x,y,z)) + cimg::sqr(I(nx,y,z)) + cimg::sqr(I(px,ny,z)) + cimg::sqr(I(x,ny,z)) + cimg::sqr(I(nx,ny,z)) + cimg::sqr(I(px,py,nz)) + cimg::sqr(I(x,py,nz)) + cimg::sqr(I(nx,py,nz)) + cimg::sqr(I(px,y,nz)) + cimg::sqr(I(x,y,nz)) + cimg::sqr(I(nx,y,nz)) + cimg::sqr(I(px,ny,nz)) + cimg::sqr(I(x,ny,nz)) + cimg::sqr(I(nx,ny,nz))); _res(x,y,z) = (Ttfloat)(N?(K[0]*I(px,py,pz) + K[1]*I(x,py,pz) + K[2]*I(nx,py,pz) + K[3]*I(px,y,pz) + K[4]*I(x,y,pz) + K[5]*I(nx,y,pz) + K[6]*I(px,ny,pz) + K[7]*I(x,ny,pz) + K[8]*I(nx,ny,pz) + K[9]*I(px,py,z) + K[10]*I(x,py,z) + K[11]*I(nx,py,z) + K[12]*I(px,y,z) + K[13]*I(x,y,z) + K[14]*I(nx,y,z) + K[15]*I(px,ny,z) + K[16]*I(x,ny,z) + K[17]*I(nx,ny,z) + K[18]*I(px,py,nz) + K[19]*I(x,py,nz) + K[20]*I(nx,py,nz) + K[21]*I(px,y,nz) + K[22]*I(x,y,nz) + K[23]*I(nx,y,nz) + K[24]*I(px,ny,nz) + K[25]*I(x,ny,nz) + K[26]*I(nx,ny,nz))/std::sqrt(N):0); } } else { cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(_res.size(),16384)) cimg_forXYZ(res,x,y,z) { const int px = x>dilation?x - dilation:x, nx = x + dilation<res.width()?x + dilation:x, py = y>dilation?y - dilation:y, ny = y + dilation<res.height()?y + dilation:y, pz = z>dilation?z - dilation:z, nz = z + dilation<res.depth()?z + dilation:z; _res(x,y,z) = (Ttfloat)(K[0]*I(px,py,pz) + K[1]*I(x,py,pz) + K[2]*I(nx,py,pz) + K[3]*I(px,y,pz) + K[4]*I(x,y,pz) + K[5]*I(nx,y,pz) + K[6]*I(px,ny,pz) + K[7]*I(x,ny,pz) + K[8]*I(nx,ny,pz) + K[9]*I(px,py,z) + K[10]*I(x,py,z) + K[11]*I(nx,py,z) + K[12]*I(px,y,z) + K[13]*I(x,y,z) + K[14]*I(nx,y,z) + K[15]*I(px,ny,z) + K[16]*I(x,ny,z) + K[17]*I(nx,ny,z) + K[18]*I(px,py,nz) + K[19]*I(x,py,nz) + K[20]*I(nx,py,nz) + K[21]*I(px,y,nz) + K[22]*I(x,y,nz) + K[23]*I(nx,y,nz) + K[24]*I(px,ny,nz) + K[25]*I(x,ny,nz) + K[26]*I(nx,ny,nz)); } } } } break; case 2 : { // 2x2x2 kernel cimg_forC(res,c) { cimg_abort_test; const CImg<T> I = get_shared_channel(c%_spectrum); const CImg<t> K = _kernel.get_shared_channel(c%kernel._spectrum); CImg<T> _res = res.get_shared_channel(c); if (is_normalized) { const Ttfloat M = (Ttfloat)K.magnitude(2), M2 = M*M; cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(_res.size(),16384)) cimg_forXYZ(res,x,y,z) { const int nx = x + 1<res.width()?x + 1:x, ny = y + 1<res.height()?y + 1:y, nz = z + 1<res.depth()?z + 1:z; const Ttfloat N = M2*(cimg::sqr(I(x,y,z)) + cimg::sqr(I(nx,y,z)) + cimg::sqr(I(x,ny,z)) + cimg::sqr(I(nx,ny,z)) + cimg::sqr(I(x,y,nz)) + cimg::sqr(I(nx,y,nz)) + cimg::sqr(I(x,ny,nz)) + cimg::sqr(I(nx,ny,nz))); _res(x,y,z) = (Ttfloat)(N?(K[0]*I(x,y,z) + K[1]*I(nx,y,z) + K[2]*I(x,ny,z) + K[3]*I(nx,ny,z) + K[4]*I(x,y,nz) + K[5]*I(nx,y,nz) + K[6]*I(x,ny,nz) + K[7]*I(nx,ny,nz))/std::sqrt(N):0); } } else { cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(_res.size(),16384)) cimg_forXYZ(res,x,y,z) { const int nx = x + 1<res.width()?x + 1:x, ny = y + 1<res.height()?y + 1:y, nz = z + 1<res.depth()?z + 1:z; _res(x,y,z) = (Ttfloat)(K[0]*I(x,y,z) + K[1]*I(nx,y,z) + K[2]*I(x,ny,z) + K[3]*I(nx,ny,z) + K[4]*I(x,y,nz) + K[5]*I(nx,y,nz) + K[6]*I(x,ny,nz) + K[7]*I(nx,ny,nz)); } } } } break; default : case 1 : switch (_kernel._width) { case 5 : { // 5x5 kernel cimg_forC(res,c) { cimg_abort_test; const CImg<T> I = get_shared_channel(c%_spectrum); const CImg<t> K = _kernel.get_shared_channel(c%kernel._spectrum); CImg<T> _res = res.get_shared_channel(c); if (is_normalized) { const Ttfloat M = (Ttfloat)K.magnitude(2), M2 = M*M; cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(_res.size(),16384)) cimg_forXYZ(res,x,y,z) { const int px = x>dilation?x - dilation:x, nx = x + dilation<res.width()?x + dilation:x, bx = px>dilation?px - dilation:px, ax = nx + dilation<res.width()?nx + dilation:nx, py = y>dilation?y - dilation:y, ny = y + dilation<res.height()?y + dilation:y, by = py>dilation?py - dilation:py, ay = ny + dilation<res.height()?ny + dilation:ny; const Ttfloat N = M2*(cimg::sqr(I(bx,by,z)) + cimg::sqr(I(px,by,z)) + cimg::sqr(I(x,by,z)) + cimg::sqr(I(nx,by,z)) + cimg::sqr(I(ax,by,z)) + cimg::sqr(I(bx,py,z)) + cimg::sqr(I(px,py,z)) + cimg::sqr(I(x,py,z)) + cimg::sqr(I(nx,py,z)) + cimg::sqr(I(ax,py,z)) + cimg::sqr(I(bx,y,z)) + cimg::sqr(I(px,y,z)) + cimg::sqr(I(x,y,z)) + cimg::sqr(I(nx,y,z)) + cimg::sqr(I(ax,y,z)) + cimg::sqr(I(bx,ny,z)) + cimg::sqr(I(px,ny,z)) + cimg::sqr(I(x,ny,z)) + cimg::sqr(I(nx,ny,z)) + cimg::sqr(I(ax,ny,z)) + cimg::sqr(I(bx,ay,z)) + cimg::sqr(I(px,ay,z)) + cimg::sqr(I(x,ay,z)) + cimg::sqr(I(nx,ay,z)) + cimg::sqr(I(ax,ay,z))); _res(x,y,z) = (Ttfloat)(N?(K[0]*I(bx,by,z) + K[1]*I(px,by,z) + K[2]*I(x,by,z) + K[3]*I(nx,by,z) + K[4]*I(ax,by,z) + K[5]*I(bx,py,z) + K[6]*I(px,py,z) + K[7]*I(x,py,z) + K[8]*I(nx,py,z) + K[9]*I(ax,py,z) + K[10]*I(bx,y,z) + K[11]*I(px,y,z) + K[12]*I(x,y,z) + K[13]*I(nx,y,z) + K[14]*I(ax,y,z) + K[15]*I(bx,ny,z) + K[16]*I(px,ny,z) + K[17]*I(x,ny,z) + K[18]*I(nx,ny,z) + K[19]*I(ax,ny,z) + K[20]*I(bx,ay,z) + K[21]*I(px,ay,z) + K[22]*I(x,ay,z) + K[23]*I(nx,ay,z) + K[24]*I(ax,ay,z))/std::sqrt(N):0); } } else { cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(_res.size(),16384)) cimg_forXYZ(res,x,y,z) { const int px = x>dilation?x - dilation:x, nx = x + dilation<res.width()?x + dilation:x, bx = px>dilation?px - dilation:px, ax = nx + dilation<res.width()?nx + dilation:nx, py = y>dilation?y - dilation:y, ny = y + dilation<res.height()?y + dilation:y, by = py>dilation?py - dilation:py, ay = ny + dilation<res.height()?ny + dilation:ny; _res(x,y,z) = (Ttfloat)(K[0]*I(bx,by,z) + K[1]*I(px,by,z) + K[2]*I(x,by,z) + K[3]*I(nx,by,z) + K[4]*I(ax,by,z) + K[5]*I(bx,py,z) + K[6]*I(px,py,z) + K[7]*I(x,py,z) + K[8]*I(nx,py,z) + K[9]*I(ax,py,z) + K[10]*I(bx,y,z) + K[11]*I(px,y,z) + K[12]*I(x,y,z) + K[13]*I(nx,y,z) + K[14]*I(ax,y,z) + K[15]*I(bx,ny,z) + K[16]*I(px,ny,z) + K[17]*I(x,ny,z) + K[18]*I(nx,ny,z) + K[19]*I(ax,ny,z) + K[20]*I(bx,ay,z) + K[21]*I(px,ay,z) + K[22]*I(x,ay,z) + K[23]*I(nx,ay,z) + K[24]*I(ax,ay,z)); } } } } break; case 4 : { // 4x4 kernel cimg_forC(res,c) { cimg_abort_test; const CImg<T> I = get_shared_channel(c%_spectrum); const CImg<t> K = _kernel.get_shared_channel(c%kernel._spectrum); CImg<T> _res = res.get_shared_channel(c); if (is_normalized) { const Ttfloat M = (Ttfloat)K.magnitude(2), M2 = M*M; cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(_res.size(),16384)) cimg_forXYZ(res,x,y,z) { const int px = x>dilation?x - dilation:x, nx = x + dilation<res.width()?x + dilation:x, ax = nx + dilation<res.width()?nx + dilation:nx, py = y>dilation?y - dilation:y, ny = y + dilation<res.height()?y + dilation:y, ay = ny + dilation<res.height()?ny + dilation:ny; const Ttfloat N = M2*(cimg::sqr(I(px,py,z)) + cimg::sqr(I(x,py,z)) + cimg::sqr(I(nx,py,z)) + cimg::sqr(I(ax,py,z)) + cimg::sqr(I(px,y,z)) + cimg::sqr(I(x,y,z)) + cimg::sqr(I(nx,y,z)) + cimg::sqr(I(ax,y,z)) + cimg::sqr(I(px,ny,z)) + cimg::sqr(I(x,ny,z)) + cimg::sqr(I(nx,ny,z)) + cimg::sqr(I(ax,ny,z)) + cimg::sqr(I(px,ay,z)) + cimg::sqr(I(x,ay,z)) + cimg::sqr(I(nx,ay,z)) + cimg::sqr(I(ax,ay,z))); _res(x,y,z) = (Ttfloat)(N?(K[0]*I(px,py,z) + K[1]*I(x,py,z) + K[2]*I(nx,py,z) + K[3]*I(ax,py,z) + K[4]*I(px,y,z) + K[5]*I(x,y,z) + K[6]*I(nx,y,z) + K[7]*I(ax,y,z) + K[8]*I(px,ny,z) + K[9]*I(x,ny,z) + K[10]*I(nx,ny,z) + K[11]*I(ax,ny,z) + K[12]*I(px,ay,z) + K[13]*I(x,ay,z) + K[14]*I(nx,ay,z) + K[15]*I(ax,ay,z))/std::sqrt(N):0); } } else { cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(_res.size(),16384)) cimg_forXYZ(res,x,y,z) { const int px = x>dilation?x - dilation:x, nx = x + dilation<res.width()?x + dilation:x, ax = nx + dilation<res.width()?nx + dilation:nx, py = y>dilation?y - dilation:y, ny = y + dilation<res.height()?y + dilation:y, ay = ny + dilation<res.height()?ny + dilation:ny; _res(x,y,z) = (Ttfloat)(K[0]*I(px,py,z) + K[1]*I(x,py,z) + K[2]*I(nx,py,z) + K[3]*I(ax,py,z) + K[4]*I(px,y,z) + K[5]*I(x,y,z) + K[6]*I(nx,y,z) + K[7]*I(ax,y,z) + K[8]*I(px,ny,z) + K[9]*I(x,ny,z) + K[10]*I(nx,ny,z) + K[11]*I(ax,ny,z) + K[12]*I(px,ay,z) + K[13]*I(x,ay,z) + K[14]*I(nx,ay,z) + K[15]*I(ax,ay,z)); } } } } break; case 3 : { // 3x3 kernel cimg_forC(res,c) { cimg_abort_test; const CImg<T> I = get_shared_channel(c%_spectrum); const CImg<t> K = _kernel.get_shared_channel(c%kernel._spectrum); CImg<T> _res = res.get_shared_channel(c); if (is_normalized) { const Ttfloat M = (Ttfloat)K.magnitude(2), M2 = M*M; cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(_res.size(),16384)) cimg_forXYZ(res,x,y,z) { const int px = x>dilation?x - dilation:x, nx = x + dilation<res.width()?x + dilation:x, py = y>dilation?y - dilation:y, ny = y + dilation<res.height()?y + dilation:y; const Ttfloat N = M2*(cimg::sqr(I(px,py,z)) + cimg::sqr(I(x,py,z)) + cimg::sqr(I(nx,py,z)) + cimg::sqr(I(px,y,z)) + cimg::sqr(I(x,y,z)) + cimg::sqr(I(nx,y,z)) + cimg::sqr(I(px,ny,z)) + cimg::sqr(I(x,ny,z)) + cimg::sqr(I(nx,ny,z))); _res(x,y,z) = (Ttfloat)(N?(K[0]*I(px,py,z) + K[1]*I(x,py,z) + K[2]*I(nx,py,z) + K[3]*I(px,y,z) + K[4]*I(x,y,z) + K[5]*I(nx,y,z) + K[6]*I(px,ny,z) + K[7]*I(x,ny,z) + K[8]*I(nx,ny,z))/std::sqrt(N):0); } } else { cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(_res.size(),16384)) cimg_forXYZ(res,x,y,z) { const int px = x>dilation?x - dilation:x, nx = x + dilation<res.width()?x + dilation:x, py = y>dilation?y - dilation:y, ny = y + dilation<res.height()?y + dilation:y; _res(x,y,z) = (Ttfloat)(K[0]*I(px,py,z) + K[1]*I(x,py,z) + K[2]*I(nx,py,z) + K[3]*I(px,y,z) + K[4]*I(x,y,z) + K[5]*I(nx,y,z) + K[6]*I(px,ny,z) + K[7]*I(x,ny,z) + K[8]*I(nx,ny,z)); } } } } break; case 2 : { // 2x2 kernel cimg_forC(res,c) { cimg_abort_test; const CImg<T> I = get_shared_channel(c%_spectrum); const CImg<t> K = _kernel.get_shared_channel(c%kernel._spectrum); CImg<T> _res = res.get_shared_channel(c); if (is_normalized) { const Ttfloat M = (Ttfloat)K.magnitude(2), M2 = M*M; cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(_res.size(),16384)) cimg_forXYZ(res,x,y,z) { const int nx = x + 1<res.width()?x + 1:x, ny = y + 1<res.height()?y + 1:y; const Ttfloat N = M2*(cimg::sqr(I(x,y,z)) + cimg::sqr(I(nx,y,z)) + cimg::sqr(I(x,ny,z)) + cimg::sqr(I(nx,ny,z))); _res(x,y,z) = (Ttfloat)(N?(K[0]*I(x,y,z) + K[1]*I(nx,y,z) + K[2]*I(x,ny,z) + K[3]*I(nx,ny,z))/std::sqrt(N):0); } } else { cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(_res.size(),16384)) cimg_forXYZ(res,x,y,z) { const int nx = x + 1<res.width()?x + 1:x, ny = y + 1<res.height()?y + 1:y; _res(x,y,z) = (Ttfloat)(K[0]*I(x,y,z) + K[1]*I(nx,y,z) + K[2]*I(x,ny,z) + K[3]*I(nx,ny,z)); } } } } break; default : case 1 : // 1x1 kernel if (is_normalized) res.fill(1); else cimg_forC(res,c) { cimg_abort_test; const CImg<T> img = get_shared_channel(c%_spectrum); res.get_shared_channel(c).assign(img)*=_kernel(0,0,0,c%kernel._spectrum); } break; } } } } else { // Generic version for other kernels and boundary conditions res.assign(_width,_height,_depth,std::max(_spectrum,kernel._spectrum)); int mx2 = kernel.width()/2, my2 = kernel.height()/2, mz2 = kernel.depth()/2, mx1 = kernel.width() - mx2 - 1, my1 = kernel.height() - my2 - 1, mz1 = kernel.depth() - mz2 - 1; if (is_convolution) cimg::swap(mx1,mx2,my1,my2,mz1,mz2); // Shift kernel center in case of convolution const int mxs = dilation*mx1, mys = dilation*my1, mzs = dilation*mz1, mxe = width() - dilation*mx2, mye = height() - dilation*my2, mze = depth() - dilation*mz2; cimg_pragma_openmp(parallel for cimg_openmp_if(!is_inner_parallel && is_outer_parallel)) cimg_forC(res,c) _cimg_abort_try_omp { cimg_abort_test; const CImg<T> img = get_shared_channel(c%_spectrum); const CImg<t> K = kernel.get_shared_channel(c%kernel._spectrum); if (is_normalized) { // Normalized correlation const Ttfloat M = (Ttfloat)K.magnitude(2), M2 = M*M; cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(is_inner_parallel)) for (int z = mzs; z<mze; ++z) for (int y = mys; y<mye; ++y) for (int x = mxs; x<mxe; ++x) _cimg_abort_try_omp2 { cimg_abort_test2; Ttfloat val = 0, N = 0; for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const Ttfloat _val = (Ttfloat)img(x + dilation*xm,y + dilation*ym,z + dilation*zm); val+=_val*K(mx1 + xm,my1 + ym,mz1 + zm); N+=_val*_val; } N*=M2; res(x,y,z,c) = (Ttfloat)(N?val/std::sqrt(N):0); } _cimg_abort_catch_omp2 if (boundary_conditions) cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(is_inner_parallel)) cimg_forYZ(res,y,z) _cimg_abort_try_omp2 { cimg_abort_test2; for (int x = 0; x<width(); (y<mys || y>=mye || z<mzs || z>=mze)?++x:((x<mxs - 1 || x>=mxe)?++x:(x=mxe))) { Ttfloat val = 0, N = 0; for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const Ttfloat _val = (Ttfloat)img._atXYZ(x + dilation*xm,y + dilation*ym,z + dilation*zm); val+=_val*K(mx1 + xm,my1 + ym,mz1 + zm); N+=_val*_val; } N*=M2; res(x,y,z,c) = (Ttfloat)(N?val/std::sqrt(N):0); } } _cimg_abort_catch_omp2 else cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(is_inner_parallel)) cimg_forYZ(res,y,z) _cimg_abort_try_omp2 { cimg_abort_test2; for (int x = 0; x<width(); (y<mys || y>=mye || z<mzs || z>=mze)?++x:((x<mxs - 1 || x>=mxe)?++x:(x=mxe))) { Ttfloat val = 0, N = 0; for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const Ttfloat _val = (Ttfloat)img.atXYZ(x + dilation*xm,y + dilation*ym,z + dilation*zm,0,(T)0); val+=_val*K(mx1 + xm,my1 + ym,mz1 + zm); N+=_val*_val; } N*=M2; res(x,y,z,c) = (Ttfloat)(N?val/std::sqrt(N):0); } } _cimg_abort_catch_omp2 } else { // Classical correlation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(is_inner_parallel)) for (int z = mzs; z<mze; ++z) for (int y = mys; y<mye; ++y) for (int x = mxs; x<mxe; ++x) _cimg_abort_try_omp2 { cimg_abort_test2; Ttfloat val = 0; for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) val+=img(x + dilation*xm,y + dilation*ym,z + dilation*zm)*K(mx1 + xm,my1 + ym,mz1 + zm); res(x,y,z,c) = (Ttfloat)val; } _cimg_abort_catch_omp2 if (boundary_conditions) cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(is_inner_parallel)) cimg_forYZ(res,y,z) _cimg_abort_try_omp2 { cimg_abort_test2; for (int x = 0; x<width(); (y<mys || y>=mye || z<mzs || z>=mze)?++x:((x<mxs - 1 || x>=mxe)?++x:(x=mxe))) { Ttfloat val = 0; for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) val+=img._atXYZ(x + dilation*xm,y + dilation*ym,z + dilation*zm)*K(mx1 + xm,my1 + ym,mz1 + zm); res(x,y,z,c) = (Ttfloat)val; } } _cimg_abort_catch_omp2 else cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(is_inner_parallel)) cimg_forYZ(res,y,z) _cimg_abort_try_omp2 { cimg_abort_test2; for (int x = 0; x<width(); (y<mys || y>=mye || z<mzs || z>=mze)?++x:((x<mxs - 1 || x>=mxe)?++x:(x=mxe))) { Ttfloat val = 0; for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) val+=img.atXYZ(x + dilation*xm,y + dilation*ym,z + dilation*zm,0,(T)0)* K(mx1 + xm,my1 + ym,mz1 + zm); res(x,y,z,c) = (Ttfloat)val; } } _cimg_abort_catch_omp2 } } _cimg_abort_catch_omp } cimg_abort_test; return res; } //! Convolve image by a kernel. /** \param kernel = the correlation kernel. \param boundary_conditions boundary conditions can be (false=dirichlet, true=neumann) \param is_normalized = enable local normalization. \param dilation = dilation \note - The result \p res of the convolution of an image \p img by a kernel \p kernel is defined to be: res(x,y,z) = sum_{i,j,k} img(x-i,y-j,z-k)*kernel(i,j,k) **/ template<typename t> CImg<T>& convolve(const CImg<t>& kernel, const bool boundary_conditions=true, const bool is_normalized=false, const int dilation=1) { if (is_empty() || !kernel) return *this; return get_convolve(kernel,boundary_conditions,is_normalized,dilation).move_to(*this); } //! Convolve image by a kernel \newinstance. template<typename t> CImg<_cimg_Ttfloat> get_convolve(const CImg<t>& kernel, const bool boundary_conditions=true, const bool is_normalized=false, const int dilation=1) const { return _correlate(CImg<t>(kernel._data,kernel.size()/kernel._spectrum,1,1,kernel._spectrum,true). get_mirror('x').resize(kernel,-1),boundary_conditions,is_normalized,dilation,true); } //! Cumulate image values, optionally along specified axis. /** \param axis Cumulation axis. Set it to 0 to cumulate all values globally without taking axes into account. **/ CImg<T>& cumulate(const char axis=0) { switch (cimg::lowercase(axis)) { case 'x' : cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*512 && _height*_depth*_spectrum>=16)) cimg_forYZC(*this,y,z,c) { T *ptrd = data(0,y,z,c); Tlong cumul = (Tlong)0; cimg_forX(*this,x) { cumul+=(Tlong)*ptrd; *(ptrd++) = (T)cumul; } } break; case 'y' : { const ulongT w = (ulongT)_width; cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_height>=(cimg_openmp_sizefactor)*512 && _width*_depth*_spectrum>=16)) cimg_forXZC(*this,x,z,c) { T *ptrd = data(x,0,z,c); Tlong cumul = (Tlong)0; cimg_forY(*this,y) { cumul+=(Tlong)*ptrd; *ptrd = (T)cumul; ptrd+=w; } } } break; case 'z' : { const ulongT wh = (ulongT)_width*_height; cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_depth>=(cimg_openmp_sizefactor)*512 && _width*_depth*_spectrum>=16)) cimg_forXYC(*this,x,y,c) { T *ptrd = data(x,y,0,c); Tlong cumul = (Tlong)0; cimg_forZ(*this,z) { cumul+=(Tlong)*ptrd; *ptrd = (T)cumul; ptrd+=wh; } } } break; case 'c' : { const ulongT whd = (ulongT)_width*_height*_depth; cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_spectrum>=(cimg_openmp_sizefactor)*512 && _width*_height*_depth>=16)) cimg_forXYZ(*this,x,y,z) { T *ptrd = data(x,y,z,0); Tlong cumul = (Tlong)0; cimg_forC(*this,c) { cumul+=(Tlong)*ptrd; *ptrd = (T)cumul; ptrd+=whd; } } } break; default : { // Global cumulation Tlong cumul = (Tlong)0; cimg_for(*this,ptrd,T) { cumul+=(Tlong)*ptrd; *ptrd = (T)cumul; } } } return *this; } //! Cumulate image values, optionally along specified axis \newinstance. CImg<Tlong> get_cumulate(const char axis=0) const { return CImg<Tlong>(*this,false).cumulate(axis); } //! Cumulate image values, along specified axes. /** \param axes Cumulation axes, as a C-string. \note \c axes may contains multiple characters, e.g. \c "xyz" **/ CImg<T>& cumulate(const char *const axes) { for (const char *s = axes; *s; ++s) cumulate(*s); return *this; } //! Cumulate image values, along specified axes \newinstance. CImg<Tlong> get_cumulate(const char *const axes) const { return CImg<Tlong>(*this,false).cumulate(axes); } //! Erode image by a structuring element. /** \param kernel Structuring element. \param boundary_conditions Boundary conditions. \param is_real Do the erosion in real (a.k.a 'non-flat') mode (\c true) rather than binary mode (\c false). **/ template<typename t> CImg<T>& erode(const CImg<t>& kernel, const bool boundary_conditions=true, const bool is_real=false) { if (is_empty() || !kernel) return *this; return get_erode(kernel,boundary_conditions,is_real).move_to(*this); } //! Erode image by a structuring element \newinstance. template<typename t> CImg<_cimg_Tt> get_erode(const CImg<t>& kernel, const bool boundary_conditions=true, const bool is_real=false) const { if (is_empty() || !kernel) return *this; if (!is_real && kernel==0) return CImg<T>(width(),height(),depth(),spectrum(),0); typedef _cimg_Tt Tt; CImg<Tt> res(_width,_height,_depth,std::max(_spectrum,kernel._spectrum)); const int mx2 = kernel.width()/2, my2 = kernel.height()/2, mz2 = kernel.depth()/2, mx1 = kernel.width() - mx2 - 1, my1 = kernel.height() - my2 - 1, mz1 = kernel.depth() - mz2 - 1, mxe = width() - mx2, mye = height() - my2, mze = depth() - mz2; const bool is_inner_parallel = _width*_height*_depth>=(cimg_openmp_sizefactor)*32768, is_outer_parallel = res.size()>=(cimg_openmp_sizefactor)*32768; cimg::unused(is_inner_parallel,is_outer_parallel); _cimg_abort_init_omp; cimg_abort_init; cimg_pragma_openmp(parallel for cimg_openmp_if(!is_inner_parallel && is_outer_parallel)) cimg_forC(res,c) _cimg_abort_try_omp { cimg_abort_test; const CImg<T> img = get_shared_channel(c%_spectrum); const CImg<t> K = kernel.get_shared_channel(c%kernel._spectrum); if (is_real) { // Real erosion cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(is_inner_parallel)) for (int z = mz1; z<mze; ++z) for (int y = my1; y<mye; ++y) for (int x = mx1; x<mxe; ++x) _cimg_abort_try_omp2 { cimg_abort_test2; Tt min_val = cimg::type<Tt>::max(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const t mval = K(mx1 + xm,my1 + ym,mz1 + zm); const Tt cval = (Tt)(img(x + xm,y + ym,z + zm) - mval); if (cval<min_val) min_val = cval; } res(x,y,z,c) = min_val; } _cimg_abort_catch_omp2 if (boundary_conditions) cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(is_inner_parallel)) cimg_forYZ(res,y,z) _cimg_abort_try_omp2 { cimg_abort_test2; for (int x = 0; x<width(); (y<my1 || y>=mye || z<mz1 || z>=mze)?++x:((x<mx1 - 1 || x>=mxe)?++x:(x=mxe))) { Tt min_val = cimg::type<Tt>::max(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const t mval = K(mx1 + xm,my1 + ym,mz1 + zm); const Tt cval = (Tt)(img._atXYZ(x + xm,y + ym,z + zm) - mval); if (cval<min_val) min_val = cval; } res(x,y,z,c) = min_val; } } _cimg_abort_catch_omp2 else cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(is_inner_parallel)) cimg_forYZ(res,y,z) _cimg_abort_try_omp2 { cimg_abort_test2; for (int x = 0; x<width(); (y<my1 || y>=mye || z<mz1 || z>=mze)?++x:((x<mx1 - 1 || x>=mxe)?++x:(x=mxe))) { Tt min_val = cimg::type<Tt>::max(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const t mval = K(mx1 + xm,my1 + ym,mz1 + zm); const Tt cval = (Tt)(img.atXYZ(x + xm,y + ym,z + zm,0,(T)0) - mval); if (cval<min_val) min_val = cval; } res(x,y,z,c) = min_val; } } _cimg_abort_catch_omp2 } else { // Binary erosion cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(is_inner_parallel)) for (int z = mz1; z<mze; ++z) for (int y = my1; y<mye; ++y) for (int x = mx1; x<mxe; ++x) _cimg_abort_try_omp2 { cimg_abort_test2; Tt min_val = cimg::type<Tt>::max(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) if (K(mx1 + xm,my1 + ym,mz1 + zm)) { const Tt cval = (Tt)img(x + xm,y + ym,z + zm); if (cval<min_val) min_val = cval; } res(x,y,z,c) = min_val; } _cimg_abort_catch_omp2 if (boundary_conditions) cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(is_inner_parallel)) cimg_forYZ(res,y,z) _cimg_abort_try_omp2 { cimg_abort_test2; for (int x = 0; x<width(); (y<my1 || y>=mye || z<mz1 || z>=mze)?++x:((x<mx1 - 1 || x>=mxe)?++x:(x=mxe))) { Tt min_val = cimg::type<Tt>::max(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) if (K(mx1 + xm,my1 + ym,mz1 + zm)) { const Tt cval = (Tt)img._atXYZ(x + xm,y + ym,z + zm); if (cval<min_val) min_val = cval; } res(x,y,z,c) = min_val; } } _cimg_abort_catch_omp2 else cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(is_inner_parallel)) cimg_forYZ(res,y,z) _cimg_abort_try_omp2 { cimg_abort_test2; for (int x = 0; x<width(); (y<my1 || y>=mye || z<mz1 || z>=mze)?++x:((x<mx1 - 1 || x>=mxe)?++x:(x=mxe))) { Tt min_val = cimg::type<Tt>::max(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) if (K(mx1 + xm,my1 + ym,mz1 + zm)) { const Tt cval = (Tt)img.atXYZ(x + xm,y + ym,z + zm,0,(T)0); if (cval<min_val) min_val = cval; } res(x,y,z,c) = min_val; } } _cimg_abort_catch_omp2 } } _cimg_abort_catch_omp cimg_abort_test; return res; } //! Erode image by a rectangular structuring element of specified size. /** \param sx Width of the structuring element. \param sy Height of the structuring element. \param sz Depth of the structuring element. **/ CImg<T>& erode(const unsigned int sx, const unsigned int sy, const unsigned int sz=1) { if (is_empty() || (sx==1 && sy==1 && sz==1)) return *this; if (sx>1 && _width>1) { // Along X-axis const int L = width(), off = 1, s = (int)sx, _s2 = s/2 + 1, _s1 = s - _s2, s1 = _s1>L?L:_s1, s2 = _s2>L?L:_s2; CImg<T> buf(L); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) firstprivate(buf) if (size()>524288)) cimg_forYZC(*this,y,z,c) { T *const ptrdb = buf._data, *ptrd = buf._data, *const ptrde = buf._data + L - 1; const T *const ptrsb = data(0,y,z,c), *ptrs = ptrsb, *const ptrse = ptrs + L*off - off; T cur = *ptrs; ptrs+=off; bool is_first = true; for (int p = s2 - 1; p>0 && ptrs<=ptrse; --p) { const T val = *ptrs; ptrs+=off; if (val<=cur) { cur = val; is_first = false; }} *(ptrd++) = cur; if (ptrs>=ptrse) { T *pd = data(0,y,z,c); cur = std::min(cur,*ptrse); cimg_forX(buf,k) { *pd = cur; pd+=off; } } else { for (int p = s1; p>0 && ptrd<=ptrde; --p) { const T val = *ptrs; if (ptrs<ptrse) ptrs+=off; if (val<=cur) { cur = val; is_first = false; } *(ptrd++) = cur; } for (int p = L - s - 1; p>0; --p) { const T val = *ptrs; ptrs+=off; if (is_first) { const T *nptrs = ptrs - off; cur = val; for (int q = s - 2; q>0; --q) { nptrs-=off; const T nval = *nptrs; if (nval<cur) cur = nval; } nptrs-=off; const T nval = *nptrs; if (nval<cur) { cur = nval; is_first = true; } else is_first = false; } else { if (val<=cur) cur = val; else if (cur==*(ptrs-s*off)) is_first = true; } *(ptrd++) = cur; } ptrd = ptrde; ptrs = ptrse; cur = *ptrs; ptrs-=off; for (int p = s1; p>0 && ptrs>=ptrsb; --p) { const T val = *ptrs; ptrs-=off; if (val<cur) cur = val; } *(ptrd--) = cur; for (int p = s2 - 1; p>0 && ptrd>=ptrdb; --p) { const T val = *ptrs; if (ptrs>ptrsb) ptrs-=off; if (val<cur) cur = val; *(ptrd--) = cur; } T *pd = data(0,y,z,c); cimg_for(buf,ps,T) { *pd = *ps; pd+=off; } } } } if (sy>1 && _height>1) { // Along Y-axis const int L = height(), off = width(), s = (int)sy, _s2 = s/2 + 1, _s1 = s - _s2, s1 = _s1>L?L:_s1, s2 = _s2>L?L:_s2; CImg<T> buf(L); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) firstprivate(buf) if (size()>524288)) cimg_forXZC(*this,x,z,c) { T *const ptrdb = buf._data, *ptrd = ptrdb, *const ptrde = buf._data + L - 1; const T *const ptrsb = data(x,0,z,c), *ptrs = ptrsb, *const ptrse = ptrs + L*off - off; T cur = *ptrs; ptrs+=off; bool is_first = true; for (int p = s2 - 1; p>0 && ptrs<=ptrse; --p) { const T val = *ptrs; ptrs+=off; if (val<=cur) { cur = val; is_first = false; } } *(ptrd++) = cur; if (ptrs>=ptrse) { T *pd = data(x,0,z,c); cur = std::min(cur,*ptrse); cimg_forX(buf,k) { *pd = cur; pd+=off; } } else { for (int p = s1; p>0 && ptrd<=ptrde; --p) { const T val = *ptrs; if (ptrs<ptrse) ptrs+=off; if (val<=cur) { cur = val; is_first = false; } *(ptrd++) = cur; } for (int p = L - s - 1; p>0; --p) { const T val = *ptrs; ptrs+=off; if (is_first) { const T *nptrs = ptrs - off; cur = val; for (int q = s - 2; q>0; --q) { nptrs-=off; const T nval = *nptrs; if (nval<cur) cur = nval; } nptrs-=off; const T nval = *nptrs; if (nval<cur) { cur = nval; is_first = true; } else is_first = false; } else { if (val<=cur) cur = val; else if (cur==*(ptrs-s*off)) is_first = true; } *(ptrd++) = cur; } ptrd = ptrde; ptrs = ptrse; cur = *ptrs; ptrs-=off; for (int p = s1; p>0 && ptrs>=ptrsb; --p) { const T val = *ptrs; ptrs-=off; if (val<cur) cur = val; } *(ptrd--) = cur; for (int p = s2 - 1; p>0 && ptrd>=ptrdb; --p) { const T val = *ptrs; if (ptrs>ptrsb) ptrs-=off; if (val<cur) cur = val; *(ptrd--) = cur; } T *pd = data(x,0,z,c); cimg_for(buf,ps,T) { *pd = *ps; pd+=off; } } } } if (sz>1 && _depth>1) { // Along Z-axis const int L = depth(), off = width()*height(), s = (int)sz, _s2 = s/2 + 1, _s1 = s - _s2, s1 = _s1>L?L:_s1, s2 = _s2>L?L:_s2; CImg<T> buf(L); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) firstprivate(buf) if (size()>524288)) cimg_forXYC(*this,x,y,c) { T *const ptrdb = buf._data, *ptrd = ptrdb, *const ptrde = buf._data + L - 1; const T *const ptrsb = data(x,y,0,c), *ptrs = ptrsb, *const ptrse = ptrs + L*off - off; T cur = *ptrs; ptrs+=off; bool is_first = true; for (int p = s2 - 1; p>0 && ptrs<=ptrse; --p) { const T val = *ptrs; ptrs+=off; if (val<=cur) { cur = val; is_first = false; } } *(ptrd++) = cur; if (ptrs>=ptrse) { T *pd = data(x,y,0,c); cur = std::min(cur,*ptrse); cimg_forX(buf,k) { *pd = cur; pd+=off; } } else { for (int p = s1; p>0 && ptrd<=ptrde; --p) { const T val = *ptrs; if (ptrs<ptrse) ptrs+=off; if (val<=cur) { cur = val; is_first = false; } *(ptrd++) = cur; } for (int p = L - s - 1; p>0; --p) { const T val = *ptrs; ptrs+=off; if (is_first) { const T *nptrs = ptrs - off; cur = val; for (int q = s - 2; q>0; --q) { nptrs-=off; const T nval = *nptrs; if (nval<cur) cur = nval; } nptrs-=off; const T nval = *nptrs; if (nval<cur) { cur = nval; is_first = true; } else is_first = false; } else { if (val<=cur) cur = val; else if (cur==*(ptrs-s*off)) is_first = true; } *(ptrd++) = cur; } ptrd = ptrde; ptrs = ptrse; cur = *ptrs; ptrs-=off; for (int p = s1; p>0 && ptrs>=ptrsb; --p) { const T val = *ptrs; ptrs-=off; if (val<cur) cur = val; } *(ptrd--) = cur; for (int p = s2 - 1; p>0 && ptrd>=ptrdb; --p) { const T val = *ptrs; if (ptrs>ptrsb) ptrs-=off; if (val<cur) cur = val; *(ptrd--) = cur; } T *pd = data(x,y,0,c); cimg_for(buf,ps,T) { *pd = *ps; pd+=off; } } } } return *this; } //! Erode image by a rectangular structuring element of specified size \newinstance. CImg<T> get_erode(const unsigned int sx, const unsigned int sy, const unsigned int sz=1) const { return (+*this).erode(sx,sy,sz); } //! Erode the image by a square structuring element of specified size. /** \param s Size of the structuring element. **/ CImg<T>& erode(const unsigned int s) { return erode(s,s,s); } //! Erode the image by a square structuring element of specified size \newinstance. CImg<T> get_erode(const unsigned int s) const { return (+*this).erode(s); } //! Dilate image by a structuring element. /** \param kernel Structuring element. \param boundary_conditions Boundary conditions. \param is_real Do the dilation in real (a.k.a 'non-flat') mode (\c true) rather than binary mode (\c false). **/ template<typename t> CImg<T>& dilate(const CImg<t>& kernel, const bool boundary_conditions=true, const bool is_real=false) { if (is_empty() || !kernel) return *this; return get_dilate(kernel,boundary_conditions,is_real).move_to(*this); } //! Dilate image by a structuring element \newinstance. template<typename t> CImg<_cimg_Tt> get_dilate(const CImg<t>& kernel, const bool boundary_conditions=true, const bool is_real=false) const { if (is_empty() || !kernel || (!is_real && kernel==0)) return *this; typedef _cimg_Tt Tt; CImg<Tt> res(_width,_height,_depth,std::max(_spectrum,kernel._spectrum)); const int mx1 = kernel.width()/2, my1 = kernel.height()/2, mz1 = kernel.depth()/2, mx2 = kernel.width() - mx1 - 1, my2 = kernel.height() - my1 - 1, mz2 = kernel.depth() - mz1 - 1, mxe = width() - mx2, mye = height() - my2, mze = depth() - mz2; const bool is_inner_parallel = _width*_height*_depth>=(cimg_openmp_sizefactor)*32768, is_outer_parallel = res.size()>=(cimg_openmp_sizefactor)*32768; cimg::unused(is_inner_parallel,is_outer_parallel); _cimg_abort_init_omp; cimg_abort_init; cimg_pragma_openmp(parallel for cimg_openmp_if(!is_inner_parallel && is_outer_parallel)) cimg_forC(res,c) _cimg_abort_try_omp { cimg_abort_test; const CImg<T> img = get_shared_channel(c%_spectrum); const CImg<t> K = kernel.get_shared_channel(c%kernel._spectrum); if (is_real) { // Real dilation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(is_inner_parallel)) for (int z = mz1; z<mze; ++z) for (int y = my1; y<mye; ++y) for (int x = mx1; x<mxe; ++x) _cimg_abort_try_omp2 { cimg_abort_test2; Tt max_val = cimg::type<Tt>::min(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const t mval = K(mx2 - xm,my2 - ym,mz2 - zm); const Tt cval = (Tt)(img(x + xm,y + ym,z + zm) + mval); if (cval>max_val) max_val = cval; } res(x,y,z,c) = max_val; } _cimg_abort_catch_omp2 if (boundary_conditions) cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(is_inner_parallel)) cimg_forYZ(res,y,z) _cimg_abort_try_omp2 { cimg_abort_test2; for (int x = 0; x<width(); (y<my1 || y>=mye || z<mz1 || z>=mze)?++x:((x<mx1 - 1 || x>=mxe)?++x:(x=mxe))) { Tt max_val = cimg::type<Tt>::min(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const t mval = K(mx2 - xm,my2 - ym,mz2 - zm); const Tt cval = (Tt)(img._atXYZ(x + xm,y + ym,z + zm) + mval); if (cval>max_val) max_val = cval; } res(x,y,z,c) = max_val; } } _cimg_abort_catch_omp2 else cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(is_inner_parallel)) cimg_forYZ(*this,y,z) _cimg_abort_try_omp2 { cimg_abort_test2; for (int x = 0; x<width(); (y<my1 || y>=mye || z<mz1 || z>=mze)?++x:((x<mx1 - 1 || x>=mxe)?++x:(x=mxe))) { Tt max_val = cimg::type<Tt>::min(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const t mval = K(mx2 - xm,my2 - ym,mz2 - zm); const Tt cval = (Tt)(img.atXYZ(x + xm,y + ym,z + zm,0,(T)0) + mval); if (cval>max_val) max_val = cval; } res(x,y,z,c) = max_val; } } _cimg_abort_catch_omp2 } else { // Binary dilation cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(is_inner_parallel)) for (int z = mz1; z<mze; ++z) for (int y = my1; y<mye; ++y) for (int x = mx1; x<mxe; ++x) _cimg_abort_try_omp2 { cimg_abort_test2; Tt max_val = cimg::type<Tt>::min(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) if (K(mx2 - xm,my2 - ym,mz2 - zm)) { const Tt cval = (Tt)img(x + xm,y + ym,z + zm); if (cval>max_val) max_val = cval; } res(x,y,z,c) = max_val; } _cimg_abort_catch_omp2 if (boundary_conditions) cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(is_inner_parallel)) cimg_forYZ(res,y,z) _cimg_abort_try_omp2 { cimg_abort_test2; for (int x = 0; x<width(); (y<my1 || y>=mye || z<mz1 || z>=mze)?++x:((x<mx1 - 1 || x>=mxe)?++x:(x=mxe))) { Tt max_val = cimg::type<Tt>::min(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) if (K(mx2 - xm,my2 - ym,mz2 - zm)) { const Tt cval = (Tt)img._atXYZ(x + xm,y + ym,z + zm); if (cval>max_val) max_val = cval; } res(x,y,z,c) = max_val; } } _cimg_abort_catch_omp2 else cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(is_inner_parallel)) cimg_forYZ(res,y,z) _cimg_abort_try_omp2 { cimg_abort_test2; for (int x = 0; x<width(); (y<my1 || y>=mye || z<mz1 || z>=mze)?++x:((x<mx1 - 1 || x>=mxe)?++x:(x=mxe))) { Tt max_val = cimg::type<Tt>::min(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) if (K(mx2 - xm,my2 - ym,mz2 - zm)) { const Tt cval = (Tt)img.atXYZ(x + xm,y + ym,z + zm,0,(T)0); if (cval>max_val) max_val = cval; } res(x,y,z,c) = max_val; } } _cimg_abort_catch_omp2 } } _cimg_abort_catch_omp cimg_abort_test; return res; } //! Dilate image by a rectangular structuring element of specified size. /** \param sx Width of the structuring element. \param sy Height of the structuring element. \param sz Depth of the structuring element. **/ CImg<T>& dilate(const unsigned int sx, const unsigned int sy, const unsigned int sz=1) { if (is_empty() || (sx==1 && sy==1 && sz==1)) return *this; if (sx>1 && _width>1) { // Along X-axis const int L = width(), off = 1, s = (int)sx, _s1 = s/2, _s2 = s - _s1, s1 = _s1>L?L:_s1, s2 = _s2>L?L:_s2; CImg<T> buf(L); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) firstprivate(buf) if (size()>524288)) cimg_forYZC(*this,y,z,c) { T *const ptrdb = buf._data, *ptrd = ptrdb, *const ptrde = buf._data + L - 1; const T *const ptrsb = data(0,y,z,c), *ptrs = ptrsb, *const ptrse = ptrs + L*off - off; T cur = *ptrs; ptrs+=off; bool is_first = true; for (int p = s2 - 1; p>0 && ptrs<=ptrse; --p) { const T val = *ptrs; ptrs+=off; if (val>=cur) { cur = val; is_first = false; } } *(ptrd++) = cur; if (ptrs>=ptrse) { T *pd = data(0,y,z,c); cur = std::max(cur,*ptrse); cimg_forX(buf,k) { *pd = cur; pd+=off; } } else { for (int p = s1; p>0 && ptrd<=ptrde; --p) { const T val = *ptrs; if (ptrs<ptrse) ptrs+=off; if (val>=cur) { cur = val; is_first = false; } *(ptrd++) = cur; } for (int p = L - s - 1; p>0; --p) { const T val = *ptrs; ptrs+=off; if (is_first) { const T *nptrs = ptrs - off; cur = val; for (int q = s - 2; q>0; --q) { nptrs-=off; const T nval = *nptrs; if (nval>cur) cur = nval; } nptrs-=off; const T nval = *nptrs; if (nval>cur) { cur = nval; is_first = true; } else is_first = false; } else { if (val>=cur) cur = val; else if (cur==*(ptrs-s*off)) is_first = true; } *(ptrd++) = cur; } ptrd = ptrde; ptrs = ptrse; cur = *ptrs; ptrs-=off; for (int p = s1; p>0 && ptrs>=ptrsb; --p) { const T val = *ptrs; ptrs-=off; if (val>cur) cur = val; } *(ptrd--) = cur; for (int p = s2 - 1; p>0 && ptrd>=ptrdb; --p) { const T val = *ptrs; if (ptrs>ptrsb) ptrs-=off; if (val>cur) cur = val; *(ptrd--) = cur; } T *pd = data(0,y,z,c); cimg_for(buf,ps,T) { *pd = *ps; pd+=off; } } } } if (sy>1 && _height>1) { // Along Y-axis const int L = height(), off = width(), s = (int)sy, _s1 = s/2, _s2 = s - _s1, s1 = _s1>L?L:_s1, s2 = _s2>L?L:_s2; CImg<T> buf(L); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) firstprivate(buf) if (size()>524288)) cimg_forXZC(*this,x,z,c) { T *const ptrdb = buf._data, *ptrd = ptrdb, *const ptrde = buf._data + L - 1; const T *const ptrsb = data(x,0,z,c), *ptrs = ptrsb, *const ptrse = ptrs + L*off - off; T cur = *ptrs; ptrs+=off; bool is_first = true; for (int p = s2 - 1; p>0 && ptrs<=ptrse; --p) { const T val = *ptrs; ptrs+=off; if (val>=cur) { cur = val; is_first = false; } } *(ptrd++) = cur; if (ptrs>=ptrse) { T *pd = data(x,0,z,c); cur = std::max(cur,*ptrse); cimg_forX(buf,k) { *pd = cur; pd+=off; } } else { for (int p = s1; p>0 && ptrd<=ptrde; --p) { const T val = *ptrs; if (ptrs<ptrse) ptrs+=off; if (val>=cur) { cur = val; is_first = false; } *(ptrd++) = cur; } for (int p = L - s - 1; p>0; --p) { const T val = *ptrs; ptrs+=off; if (is_first) { const T *nptrs = ptrs - off; cur = val; for (int q = s - 2; q>0; --q) { nptrs-=off; const T nval = *nptrs; if (nval>cur) cur = nval; } nptrs-=off; const T nval = *nptrs; if (nval>cur) { cur = nval; is_first = true; } else is_first = false; } else { if (val>=cur) cur = val; else if (cur==*(ptrs-s*off)) is_first = true; } *(ptrd++) = cur; } ptrd = ptrde; ptrs = ptrse; cur = *ptrs; ptrs-=off; for (int p = s1; p>0 && ptrs>=ptrsb; --p) { const T val = *ptrs; ptrs-=off; if (val>cur) cur = val; } *(ptrd--) = cur; for (int p = s2 - 1; p>0 && ptrd>=ptrdb; --p) { const T val = *ptrs; if (ptrs>ptrsb) ptrs-=off; if (val>cur) cur = val; *(ptrd--) = cur; } T *pd = data(x,0,z,c); cimg_for(buf,ps,T) { *pd = *ps; pd+=off; } } } } if (sz>1 && _depth>1) { // Along Z-axis const int L = depth(), off = width()*height(), s = (int)sz, _s1 = s/2, _s2 = s - _s1, s1 = _s1>L?L:_s1, s2 = _s2>L?L:_s2; CImg<T> buf(L); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) firstprivate(buf) if (size()>524288)) cimg_forXYC(*this,x,y,c) { T *const ptrdb = buf._data, *ptrd = ptrdb, *const ptrde = buf._data + L - 1; const T *const ptrsb = data(x,y,0,c), *ptrs = ptrsb, *const ptrse = ptrs + L*off - off; T cur = *ptrs; ptrs+=off; bool is_first = true; for (int p = s2 - 1; p>0 && ptrs<=ptrse; --p) { const T val = *ptrs; ptrs+=off; if (val>=cur) { cur = val; is_first = false; } } *(ptrd++) = cur; if (ptrs>=ptrse) { T *pd = data(x,y,0,c); cur = std::max(cur,*ptrse); cimg_forX(buf,k) { *pd = cur; pd+=off; } } else { for (int p = s1; p>0 && ptrd<=ptrde; --p) { const T val = *ptrs; if (ptrs<ptrse) ptrs+=off; if (val>=cur) { cur = val; is_first = false; } *(ptrd++) = cur; } for (int p = L - s - 1; p>0; --p) { const T val = *ptrs; ptrs+=off; if (is_first) { const T *nptrs = ptrs - off; cur = val; for (int q = s - 2; q>0; --q) { nptrs-=off; const T nval = *nptrs; if (nval>cur) cur = nval; } nptrs-=off; const T nval = *nptrs; if (nval>cur) { cur = nval; is_first = true; } else is_first = false; } else { if (val>=cur) cur = val; else if (cur==*(ptrs-s*off)) is_first = true; } *(ptrd++) = cur; } ptrd = ptrde; ptrs = ptrse; cur = *ptrs; ptrs-=off; for (int p = s1; p>0 && ptrs>=ptrsb; --p) { const T val = *ptrs; ptrs-=off; if (val>cur) cur = val; } *(ptrd--) = cur; for (int p = s2 - 1; p>0 && ptrd>=ptrdb; --p) { const T val = *ptrs; if (ptrs>ptrsb) ptrs-=off; if (val>cur) cur = val; *(ptrd--) = cur; } T *pd = data(x,y,0,c); cimg_for(buf,ps,T) { *pd = *ps; pd+=off; } } } } return *this; } //! Dilate image by a rectangular structuring element of specified size \newinstance. CImg<T> get_dilate(const unsigned int sx, const unsigned int sy, const unsigned int sz=1) const { return (+*this).dilate(sx,sy,sz); } //! Dilate image by a square structuring element of specified size. /** \param s Size of the structuring element. **/ CImg<T>& dilate(const unsigned int s) { return dilate(s,s,s); } //! Dilate image by a square structuring element of specified size \newinstance. CImg<T> get_dilate(const unsigned int s) const { return (+*this).dilate(s); } //! Compute watershed transform. /** \param priority Priority map. \param is_high_connectivity Boolean that choose between 4(false)- or 8(true)-connectivity in 2D case, and between 6(false)- or 26(true)-connectivity in 3D case. \note Non-zero values of the instance instance are propagated to zero-valued ones according to specified the priority map. **/ template<typename t> CImg<T>& watershed(const CImg<t>& priority, const bool is_high_connectivity=false) { #define _cimg_watershed_init(cond,X,Y,Z) \ if (cond && !(*this)(X,Y,Z)) Q._priority_queue_insert(labels,sizeQ,priority(X,Y,Z),X,Y,Z,nb_seeds) #define _cimg_watershed_propagate(cond,X,Y,Z) \ if (cond) { \ if ((*this)(X,Y,Z)) { \ ns = labels(X,Y,Z) - 1; xs = seeds(ns,0); ys = seeds(ns,1); zs = seeds(ns,2); \ d = cimg::sqr((float)x - xs) + cimg::sqr((float)y - ys) + cimg::sqr((float)z - zs); \ if (d<dmin) { dmin = d; nmin = ns; nlabel = (*this)(xs,ys,zs); } \ } else Q._priority_queue_insert(labels,sizeQ,priority(X,Y,Z),X,Y,Z,n); \ } if (is_empty()) return *this; if (!is_sameXYZ(priority)) throw CImgArgumentException(_cimg_instance "watershed(): image instance and specified priority (%u,%u,%u,%u,%p) " "have different dimensions.", cimg_instance, priority._width,priority._height,priority._depth,priority._spectrum,priority._data); if (_spectrum!=1) { cimg_forC(*this,c) get_shared_channel(c).watershed(priority.get_shared_channel(c%priority._spectrum)); return *this; } CImg<uintT> labels(_width,_height,_depth,1,0), seeds(64,3); CImg<typename cimg::superset2<T,t,int>::type> Q; unsigned int sizeQ = 0; int px, nx, py, ny, pz, nz; bool is_px, is_nx, is_py, is_ny, is_pz, is_nz; const bool is_3d = _depth>1; // Find seed points and insert them in priority queue. unsigned int nb_seeds = 0; const T *ptrs = _data; cimg_forXYZ(*this,x,y,z) if (*(ptrs++)) { // 3D version if (nb_seeds>=seeds._width) seeds.resize(2*seeds._width,3,1,1,0); seeds(nb_seeds,0) = x; seeds(nb_seeds,1) = y; seeds(nb_seeds++,2) = z; px = x - 1; nx = x + 1; py = y - 1; ny = y + 1; pz = z - 1; nz = z + 1; is_px = px>=0; is_nx = nx<width(); is_py = py>=0; is_ny = ny<height(); is_pz = pz>=0; is_nz = nz<depth(); _cimg_watershed_init(is_px,px,y,z); _cimg_watershed_init(is_nx,nx,y,z); _cimg_watershed_init(is_py,x,py,z); _cimg_watershed_init(is_ny,x,ny,z); if (is_3d) { _cimg_watershed_init(is_pz,x,y,pz); _cimg_watershed_init(is_nz,x,y,nz); } if (is_high_connectivity) { _cimg_watershed_init(is_px && is_py,px,py,z); _cimg_watershed_init(is_nx && is_py,nx,py,z); _cimg_watershed_init(is_px && is_ny,px,ny,z); _cimg_watershed_init(is_nx && is_ny,nx,ny,z); if (is_3d) { _cimg_watershed_init(is_px && is_pz,px,y,pz); _cimg_watershed_init(is_nx && is_pz,nx,y,pz); _cimg_watershed_init(is_px && is_nz,px,y,nz); _cimg_watershed_init(is_nx && is_nz,nx,y,nz); _cimg_watershed_init(is_py && is_pz,x,py,pz); _cimg_watershed_init(is_ny && is_pz,x,ny,pz); _cimg_watershed_init(is_py && is_nz,x,py,nz); _cimg_watershed_init(is_ny && is_nz,x,ny,nz); _cimg_watershed_init(is_px && is_py && is_pz,px,py,pz); _cimg_watershed_init(is_nx && is_py && is_pz,nx,py,pz); _cimg_watershed_init(is_px && is_ny && is_pz,px,ny,pz); _cimg_watershed_init(is_nx && is_ny && is_pz,nx,ny,pz); _cimg_watershed_init(is_px && is_py && is_nz,px,py,nz); _cimg_watershed_init(is_nx && is_py && is_nz,nx,py,nz); _cimg_watershed_init(is_px && is_ny && is_nz,px,ny,nz); _cimg_watershed_init(is_nx && is_ny && is_nz,nx,ny,nz); } } labels(x,y,z) = nb_seeds; } // Start watershed computation. while (sizeQ) { // Get and remove point with maximal priority from the queue. const int x = (int)Q(0,1), y = (int)Q(0,2), z = (int)Q(0,3); const unsigned int n = labels(x,y,z); px = x - 1; nx = x + 1; py = y - 1; ny = y + 1; pz = z - 1; nz = z + 1; is_px = px>=0; is_nx = nx<width(); is_py = py>=0; is_ny = ny<height(); is_pz = pz>=0; is_nz = nz<depth(); // Check labels of the neighbors. Q._priority_queue_remove(sizeQ); unsigned int xs, ys, zs, ns, nmin = 0; float d, dmin = cimg::type<float>::inf(); T nlabel = (T)0; _cimg_watershed_propagate(is_px,px,y,z); _cimg_watershed_propagate(is_nx,nx,y,z); _cimg_watershed_propagate(is_py,x,py,z); _cimg_watershed_propagate(is_ny,x,ny,z); if (is_3d) { _cimg_watershed_propagate(is_pz,x,y,pz); _cimg_watershed_propagate(is_nz,x,y,nz); } if (is_high_connectivity) { _cimg_watershed_propagate(is_px && is_py,px,py,z); _cimg_watershed_propagate(is_nx && is_py,nx,py,z); _cimg_watershed_propagate(is_px && is_ny,px,ny,z); _cimg_watershed_propagate(is_nx && is_ny,nx,ny,z); if (is_3d) { _cimg_watershed_propagate(is_px && is_pz,px,y,pz); _cimg_watershed_propagate(is_nx && is_pz,nx,y,pz); _cimg_watershed_propagate(is_px && is_nz,px,y,nz); _cimg_watershed_propagate(is_nx && is_nz,nx,y,nz); _cimg_watershed_propagate(is_py && is_pz,x,py,pz); _cimg_watershed_propagate(is_ny && is_pz,x,ny,pz); _cimg_watershed_propagate(is_py && is_nz,x,py,nz); _cimg_watershed_propagate(is_ny && is_nz,x,ny,nz); _cimg_watershed_propagate(is_px && is_py && is_pz,px,py,pz); _cimg_watershed_propagate(is_nx && is_py && is_pz,nx,py,pz); _cimg_watershed_propagate(is_px && is_ny && is_pz,px,ny,pz); _cimg_watershed_propagate(is_nx && is_ny && is_pz,nx,ny,pz); _cimg_watershed_propagate(is_px && is_py && is_nz,px,py,nz); _cimg_watershed_propagate(is_nx && is_py && is_nz,nx,py,nz); _cimg_watershed_propagate(is_px && is_ny && is_nz,px,ny,nz); _cimg_watershed_propagate(is_nx && is_ny && is_nz,nx,ny,nz); } } (*this)(x,y,z) = nlabel; labels(x,y,z) = ++nmin; } return *this; } //! Compute watershed transform \newinstance. template<typename t> CImg<T> get_watershed(const CImg<t>& priority, const bool is_high_connectivity=false) const { return (+*this).watershed(priority,is_high_connectivity); } // [internal] Insert/Remove items in priority queue, for watershed/distance transforms. template<typename tq, typename tv> bool _priority_queue_insert(CImg<tq>& is_queued, unsigned int& siz, const tv value, const unsigned int x, const unsigned int y, const unsigned int z, const unsigned int n=1) { if (is_queued(x,y,z)) return false; is_queued(x,y,z) = (tq)n; if (++siz>=_width) { if (!is_empty()) resize(_width*2,4,1,1,0); else assign(64,4); } (*this)(siz - 1,0) = (T)value; (*this)(siz - 1,1) = (T)x; (*this)(siz - 1,2) = (T)y; (*this)(siz - 1,3) = (T)z; for (unsigned int pos = siz - 1, par = 0; pos && value>(tv)(*this)(par=(pos + 1)/2 - 1,0); pos = par) { cimg::swap((*this)(pos,0),(*this)(par,0)); cimg::swap((*this)(pos,1),(*this)(par,1)); cimg::swap((*this)(pos,2),(*this)(par,2)); cimg::swap((*this)(pos,3),(*this)(par,3)); } return true; } CImg<T>& _priority_queue_remove(unsigned int& siz) { (*this)(0,0) = (*this)(--siz,0); (*this)(0,1) = (*this)(siz,1); (*this)(0,2) = (*this)(siz,2); (*this)(0,3) = (*this)(siz,3); const float value = (*this)(0,0); unsigned int pos = 0, swap = 0; do { const unsigned int left = 2*pos + 1, right = left + 1; if (right<siz && value<(*this)(right,0)) swap = (*this)(left,0)>(*this)(right,0)?left:right; else if (left<siz && value<(*this)(left,0)) swap = left; else break; cimg::swap((*this)(pos,0),(*this)(swap,0)); cimg::swap((*this)(pos,1),(*this)(swap,1)); cimg::swap((*this)(pos,2),(*this)(swap,2)); cimg::swap((*this)(pos,3),(*this)(swap,3)); pos = swap; } while (true); return *this; } //! Apply recursive Deriche filter. /** \param sigma Standard deviation of the filter. \param order Order of the filter. Can be <tt>{ 0=smooth-filter | 1=1st-derivative | 2=2nd-derivative }</tt>. \param axis Axis along which the filter is computed. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param boundary_conditions Boundary conditions. Can be <tt>{ 0=dirichlet | 1=neumann }</tt>. **/ CImg<T>& deriche(const float sigma, const unsigned int order=0, const char axis='x', const bool boundary_conditions=true) { #define _cimg_deriche_apply \ CImg<Tfloat> Y(N); \ Tfloat *ptrY = Y._data, yb = 0, yp = 0; \ T xp = (T)0; \ if (boundary_conditions) { xp = *ptrX; yb = yp = (Tfloat)(coefp*xp); } \ for (int m = 0; m<N; ++m) { \ const T xc = *ptrX; ptrX+=off; \ const Tfloat yc = *(ptrY++) = (Tfloat)(a0*xc + a1*xp - b1*yp - b2*yb); \ xp = xc; yb = yp; yp = yc; \ } \ T xn = (T)0, xa = (T)0; \ Tfloat yn = 0, ya = 0; \ if (boundary_conditions) { xn = xa = *(ptrX-off); yn = ya = (Tfloat)coefn*xn; } \ for (int n = N - 1; n>=0; --n) { \ const T xc = *(ptrX-=off); \ const Tfloat yc = (Tfloat)(a2*xn + a3*xa - b1*yn - b2*ya); \ xa = xn; xn = xc; ya = yn; yn = yc; \ *ptrX = (T)(*(--ptrY)+yc); \ } const char naxis = cimg::lowercase(axis); const float nsigma = sigma>=0?sigma:-sigma*(naxis=='x'?_width:naxis=='y'?_height:naxis=='z'?_depth:_spectrum)/100; if (is_empty() || (nsigma<0.1f && !order)) return *this; const float nnsigma = nsigma<0.1f?0.1f:nsigma, alpha = 1.695f/nnsigma, ema = (float)std::exp(-alpha), ema2 = (float)std::exp(-2*alpha), b1 = -2*ema, b2 = ema2; float a0 = 0, a1 = 0, a2 = 0, a3 = 0, coefp = 0, coefn = 0; switch (order) { case 0 : { const float k = (1-ema)*(1-ema)/(1 + 2*alpha*ema-ema2); a0 = k; a1 = k*(alpha - 1)*ema; a2 = k*(alpha + 1)*ema; a3 = -k*ema2; } break; case 1 : { const float k = -(1-ema)*(1-ema)*(1-ema)/(2*(ema + 1)*ema); a0 = a3 = 0; a1 = k*ema; a2 = -a1; } break; case 2 : { const float ea = (float)std::exp(-alpha), k = -(ema2 - 1)/(2*alpha*ema), kn = (-2*(-1 + 3*ea - 3*ea*ea + ea*ea*ea)/(3*ea + 1 + 3*ea*ea + ea*ea*ea)); a0 = kn; a1 = -kn*(1 + k*alpha)*ema; a2 = kn*(1 - k*alpha)*ema; a3 = -kn*ema2; } break; default : throw CImgArgumentException(_cimg_instance "deriche(): Invalid specified filter order %u " "(should be { 0=smoothing | 1=1st-derivative | 2=2nd-derivative }).", cimg_instance, order); } coefp = (a0 + a1)/(1 + b1 + b2); coefn = (a2 + a3)/(1 + b1 + b2); switch (naxis) { case 'x' : { const int N = width(); const ulongT off = 1U; cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height*_depth*_spectrum>=16)) cimg_forYZC(*this,y,z,c) { T *ptrX = data(0,y,z,c); _cimg_deriche_apply; } } break; case 'y' : { const int N = height(); const ulongT off = (ulongT)_width; cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height*_depth*_spectrum>=16)) cimg_forXZC(*this,x,z,c) { T *ptrX = data(x,0,z,c); _cimg_deriche_apply; } } break; case 'z' : { const int N = depth(); const ulongT off = (ulongT)_width*_height; cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height*_depth*_spectrum>=16)) cimg_forXYC(*this,x,y,c) { T *ptrX = data(x,y,0,c); _cimg_deriche_apply; } } break; default : { const int N = spectrum(); const ulongT off = (ulongT)_width*_height*_depth; cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height*_depth*_spectrum>=16)) cimg_forXYZ(*this,x,y,z) { T *ptrX = data(x,y,z,0); _cimg_deriche_apply; } } } return *this; } //! Apply recursive Deriche filter \newinstance. CImg<Tfloat> get_deriche(const float sigma, const unsigned int order=0, const char axis='x', const bool boundary_conditions=true) const { return CImg<Tfloat>(*this,false).deriche(sigma,order,axis,boundary_conditions); } // [internal] Apply a recursive filter (used by CImg<T>::vanvliet()). /* \param ptr the pointer of the data \param filter the coefficient of the filter in the following order [n,n - 1,n - 2,n - 3]. \param N size of the data \param off the offset between two data point \param order the order of the filter 0 (smoothing), 1st derivtive, 2nd derivative, 3rd derivative \param boundary_conditions Boundary conditions. Can be <tt>{ 0=dirichlet | 1=neumann }</tt>. \note Boundary condition using B. Triggs method (IEEE trans on Sig Proc 2005). */ static void _cimg_recursive_apply(T *data, const double filter[], const int N, const ulongT off, const unsigned int order, const bool boundary_conditions) { double val[4] = { 0 }; // res[n,n - 1,n - 2,n - 3,..] or res[n,n + 1,n + 2,n + 3,..] const double sumsq = filter[0], sum = sumsq * sumsq, a1 = filter[1], a2 = filter[2], a3 = filter[3], scaleM = 1. / ( (1. + a1 - a2 + a3) * (1. - a1 - a2 - a3) * (1. + a2 + (a1 - a3) * a3) ); double M[9]; // Triggs matrix M[0] = scaleM * (-a3 * a1 + 1. - a3 * a3 - a2); M[1] = scaleM * (a3 + a1) * (a2 + a3 * a1); M[2] = scaleM * a3 * (a1 + a3 * a2); M[3] = scaleM * (a1 + a3 * a2); M[4] = -scaleM * (a2 - 1.) * (a2 + a3 * a1); M[5] = -scaleM * a3 * (a3 * a1 + a3 * a3 + a2 - 1.); M[6] = scaleM * (a3 * a1 + a2 + a1 * a1 - a2 * a2); M[7] = scaleM * (a1 * a2 + a3 * a2 * a2 - a1 * a3 * a3 - a3 * a3 * a3 - a3 * a2 + a3); M[8] = scaleM * a3 * (a1 + a3 * a2); switch (order) { case 0 : { const double iplus = (boundary_conditions?data[(N - 1)*off]:(T)0); for (int pass = 0; pass<2; ++pass) { if (!pass) { for (int k = 1; k<4; ++k) val[k] = (boundary_conditions?*data/sumsq:0); } else { // apply Triggs boundary conditions const double uplus = iplus/(1. - a1 - a2 - a3), vplus = uplus/(1. - a1 - a2 - a3), unp = val[1] - uplus, unp1 = val[2] - uplus, unp2 = val[3] - uplus; val[0] = (M[0] * unp + M[1] * unp1 + M[2] * unp2 + vplus) * sum; val[1] = (M[3] * unp + M[4] * unp1 + M[5] * unp2 + vplus) * sum; val[2] = (M[6] * unp + M[7] * unp1 + M[8] * unp2 + vplus) * sum; *data = (T)val[0]; data -= off; for (int k = 3; k>0; --k) val[k] = val[k - 1]; } for (int n = pass; n<N; ++n) { val[0] = (*data); if (pass) val[0] *= sum; for (int k = 1; k<4; ++k) val[0] += val[k] * filter[k]; *data = (T)val[0]; if (!pass) data += off; else data -= off; for (int k = 3; k>0; --k) val[k] = val[k - 1]; } if (!pass) data -= off; } } break; case 1 : { double x[3]; // [front,center,back] for (int pass = 0; pass<2; ++pass) { if (!pass) { for (int k = 0; k<3; ++k) x[k] = (boundary_conditions?*data:(T)0); for (int k = 0; k<4; ++k) val[k] = 0; } else { // apply Triggs boundary conditions const double unp = val[1], unp1 = val[2], unp2 = val[3]; val[0] = (M[0] * unp + M[1] * unp1 + M[2] * unp2) * sum; val[1] = (M[3] * unp + M[4] * unp1 + M[5] * unp2) * sum; val[2] = (M[6] * unp + M[7] * unp1 + M[8] * unp2) * sum; *data = (T)val[0]; data -= off; for (int k = 3; k>0; --k) val[k] = val[k - 1]; } for (int n = pass; n<N - 1; ++n) { if (!pass) { x[0] = *(data + off); val[0] = 0.5f * (x[0] - x[2]); } else val[0] = (*data) * sum; for (int k = 1; k<4; ++k) val[0] += val[k] * filter[k]; *data = (T)val[0]; if (!pass) { data += off; for (int k = 2; k>0; --k) x[k] = x[k - 1]; } else { data-=off;} for (int k = 3; k>0; --k) val[k] = val[k - 1]; } *data = (T)0; } } break; case 2: { double x[3]; // [front,center,back] for (int pass = 0; pass<2; ++pass) { if (!pass) { for (int k = 0; k<3; ++k) x[k] = (boundary_conditions?*data:(T)0); for (int k = 0; k<4; ++k) val[k] = 0; } else { // apply Triggs boundary conditions const double unp = val[1], unp1 = val[2], unp2 = val[3]; val[0] = (M[0] * unp + M[1] * unp1 + M[2] * unp2) * sum; val[1] = (M[3] * unp + M[4] * unp1 + M[5] * unp2) * sum; val[2] = (M[6] * unp + M[7] * unp1 + M[8] * unp2) * sum; *data = (T)val[0]; data -= off; for (int k = 3; k>0; --k) val[k] = val[k - 1]; } for (int n = pass; n<N - 1; ++n) { if (!pass) { x[0] = *(data + off); val[0] = (x[1] - x[2]); } else { x[0] = *(data - off); val[0] = (x[2] - x[1]) * sum; } for (int k = 1; k<4; ++k) val[0] += val[k]*filter[k]; *data = (T)val[0]; if (!pass) data += off; else data -= off; for (int k = 2; k>0; --k) x[k] = x[k - 1]; for (int k = 3; k>0; --k) val[k] = val[k - 1]; } *data = (T)0; } } break; case 3: { double x[3]; // [front,center,back] for (int pass = 0; pass<2; ++pass) { if (!pass) { for (int k = 0; k<3; ++k) x[k] = (boundary_conditions?*data:(T)0); for (int k = 0; k<4; ++k) val[k] = 0; } else { // apply Triggs boundary conditions const double unp = val[1], unp1 = val[2], unp2 = val[3]; val[0] = (M[0] * unp + M[1] * unp1 + M[2] * unp2) * sum; val[1] = (M[3] * unp + M[4] * unp1 + M[5] * unp2) * sum; val[2] = (M[6] * unp + M[7] * unp1 + M[8] * unp2) * sum; *data = (T)val[0]; data -= off; for (int k = 3; k>0; --k) val[k] = val[k - 1]; } for (int n = pass; n<N - 1; ++n) { if (!pass) { x[0] = *(data + off); val[0] = (x[0] - 2*x[1] + x[2]); } else { x[0] = *(data - off); val[0] = 0.5f * (x[2] - x[0]) * sum; } for (int k = 1; k<4; ++k) val[0] += val[k] * filter[k]; *data = (T)val[0]; if (!pass) data += off; else data -= off; for (int k = 2; k>0; --k) x[k] = x[k - 1]; for (int k = 3; k>0; --k) val[k] = val[k - 1]; } *data = (T)0; } } break; } } //! Van Vliet recursive Gaussian filter. /** \param sigma standard deviation of the Gaussian filter \param order the order of the filter 0,1,2,3 \param axis Axis along which the filter is computed. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param boundary_conditions Boundary conditions. Can be <tt>{ 0=dirichlet | 1=neumann }</tt>. \note dirichlet boundary condition has a strange behavior I.T. Young, L.J. van Vliet, M. van Ginkel, Recursive Gabor filtering. IEEE Trans. Sig. Proc., vol. 50, pp. 2799-2805, 2002. (this is an improvement over Young-Van Vliet, Sig. Proc. 44, 1995) Boundary conditions (only for order 0) using Triggs matrix, from B. Triggs and M. Sdika. Boundary conditions for Young-van Vliet recursive filtering. IEEE Trans. Signal Processing, vol. 54, pp. 2365-2367, 2006. **/ CImg<T>& vanvliet(const float sigma, const unsigned int order, const char axis='x', const bool boundary_conditions=true) { if (is_empty()) return *this; if (!cimg::type<T>::is_float()) return CImg<Tfloat>(*this,false).vanvliet(sigma,order,axis,boundary_conditions).move_to(*this); const char naxis = cimg::lowercase(axis); const float nsigma = sigma>=0?sigma:-sigma*(naxis=='x'?_width:naxis=='y'?_height:naxis=='z'?_depth:_spectrum)/100; if (is_empty() || (nsigma<0.5f && !order)) return *this; const double nnsigma = nsigma<0.5f?0.5f:nsigma, m0 = 1.16680, m1 = 1.10783, m2 = 1.40586, m1sq = m1 * m1, m2sq = m2 * m2, q = (nnsigma<3.556?-0.2568 + 0.5784*nnsigma + 0.0561*nnsigma*nnsigma:2.5091 + 0.9804*(nnsigma - 3.556)), qsq = q * q, scale = (m0 + q) * (m1sq + m2sq + 2 * m1 * q + qsq), b1 = -q * (2 * m0 * m1 + m1sq + m2sq + (2 * m0 + 4 * m1) * q + 3 * qsq) / scale, b2 = qsq * (m0 + 2 * m1 + 3 * q) / scale, b3 = -qsq * q / scale, B = ( m0 * (m1sq + m2sq) ) / scale; double filter[4]; filter[0] = B; filter[1] = -b1; filter[2] = -b2; filter[3] = -b3; switch (naxis) { case 'x' : { cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height*_depth*_spectrum>=16)) cimg_forYZC(*this,y,z,c) _cimg_recursive_apply(data(0,y,z,c),filter,_width,1U,order,boundary_conditions); } break; case 'y' : { cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height*_depth*_spectrum>=16)) cimg_forXZC(*this,x,z,c) _cimg_recursive_apply(data(x,0,z,c),filter,_height,(ulongT)_width,order,boundary_conditions); } break; case 'z' : { cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height*_depth*_spectrum>=16)) cimg_forXYC(*this,x,y,c) _cimg_recursive_apply(data(x,y,0,c),filter,_depth,(ulongT)_width*_height, order,boundary_conditions); } break; default : { cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height*_depth*_spectrum>=16)) cimg_forXYZ(*this,x,y,z) _cimg_recursive_apply(data(x,y,z,0),filter,_spectrum,(ulongT)_width*_height*_depth, order,boundary_conditions); } } return *this; } //! Blur image using Van Vliet recursive Gaussian filter. \newinstance. CImg<Tfloat> get_vanvliet(const float sigma, const unsigned int order, const char axis='x', const bool boundary_conditions=true) const { return CImg<Tfloat>(*this,false).vanvliet(sigma,order,axis,boundary_conditions); } //! Blur image. /** \param sigma_x Standard deviation of the blur, along the X-axis. \param sigma_y Standard deviation of the blur, along the Y-axis. \param sigma_z Standard deviation of the blur, along the Z-axis. \param boundary_conditions Boundary conditions. Can be <tt>{ false=dirichlet | true=neumann }</tt>. \param is_gaussian Tells if the blur uses a gaussian (\c true) or quasi-gaussian (\c false) kernel. \note - The blur is computed as a 0-order Deriche filter. This is not a gaussian blur. - This is a recursive algorithm, not depending on the values of the standard deviations. \see deriche(), vanvliet(). **/ CImg<T>& blur(const float sigma_x, const float sigma_y, const float sigma_z, const bool boundary_conditions=true, const bool is_gaussian=false) { if (is_empty()) return *this; if (is_gaussian) { if (_width>1) vanvliet(sigma_x,0,'x',boundary_conditions); if (_height>1) vanvliet(sigma_y,0,'y',boundary_conditions); if (_depth>1) vanvliet(sigma_z,0,'z',boundary_conditions); } else { if (_width>1) deriche(sigma_x,0,'x',boundary_conditions); if (_height>1) deriche(sigma_y,0,'y',boundary_conditions); if (_depth>1) deriche(sigma_z,0,'z',boundary_conditions); } return *this; } //! Blur image \newinstance. CImg<Tfloat> get_blur(const float sigma_x, const float sigma_y, const float sigma_z, const bool boundary_conditions=true, const bool is_gaussian=false) const { return CImg<Tfloat>(*this,false).blur(sigma_x,sigma_y,sigma_z,boundary_conditions,is_gaussian); } //! Blur image isotropically. /** \param sigma Standard deviation of the blur. \param boundary_conditions Boundary conditions. Can be <tt>{ 0=dirichlet | 1=neumann }</tt>.a \param is_gaussian Use a gaussian kernel (VanVliet) is set, a pseudo-gaussian (Deriche) otherwise. \see deriche(), vanvliet(). **/ CImg<T>& blur(const float sigma, const bool boundary_conditions=true, const bool is_gaussian=false) { const float nsigma = sigma>=0?sigma:-sigma*cimg::max(_width,_height,_depth)/100; return blur(nsigma,nsigma,nsigma,boundary_conditions,is_gaussian); } //! Blur image isotropically \newinstance. CImg<Tfloat> get_blur(const float sigma, const bool boundary_conditions=true, const bool is_gaussian=false) const { return CImg<Tfloat>(*this,false).blur(sigma,boundary_conditions,is_gaussian); } //! Blur image anisotropically, directed by a field of diffusion tensors. /** \param G Field of square roots of diffusion tensors/vectors used to drive the smoothing. \param amplitude Amplitude of the smoothing. \param dl Spatial discretization. \param da Angular discretization. \param gauss_prec Precision of the diffusion process. \param interpolation_type Interpolation scheme. Can be <tt>{ 0=nearest-neighbor | 1=linear | 2=Runge-Kutta }</tt>. \param is_fast_approx Tells if a fast approximation of the gaussian function is used or not. **/ template<typename t> CImg<T>& blur_anisotropic(const CImg<t>& G, const float amplitude=60, const float dl=0.8f, const float da=30, const float gauss_prec=2, const unsigned int interpolation_type=0, const bool is_fast_approx=1) { // Check arguments and init variables if (!is_sameXYZ(G) || (G._spectrum!=3 && G._spectrum!=6)) throw CImgArgumentException(_cimg_instance "blur_anisotropic(): Invalid specified diffusion tensor field (%u,%u,%u,%u,%p).", cimg_instance, G._width,G._height,G._depth,G._spectrum,G._data); if (is_empty() || dl<0) return *this; const float namplitude = amplitude>=0?amplitude:-amplitude*cimg::max(_width,_height,_depth)/100; unsigned int iamplitude = cimg::round(namplitude); const bool is_3d = (G._spectrum==6); T val_min, val_max = max_min(val_min); _cimg_abort_init_omp; cimg_abort_init; if (da<=0) { // Iterated oriented Laplacians CImg<Tfloat> velocity(_width,_height,_depth,_spectrum); for (unsigned int iteration = 0; iteration<iamplitude; ++iteration) { Tfloat *ptrd = velocity._data, veloc_max = 0; if (is_3d) // 3D version cimg_forC(*this,c) { cimg_abort_test; CImg_3x3x3(I,Tfloat); cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) { const Tfloat ixx = Incc + Ipcc - 2*Iccc, ixy = (Innc + Ippc - Inpc - Ipnc)/4, ixz = (Incn + Ipcp - Incp - Ipcn)/4, iyy = Icnc + Icpc - 2*Iccc, iyz = (Icnn + Icpp - Icnp - Icpn)/4, izz = Iccn + Iccp - 2*Iccc, veloc = (Tfloat)(G(x,y,z,0)*ixx + 2*G(x,y,z,1)*ixy + 2*G(x,y,z,2)*ixz + G(x,y,z,3)*iyy + 2*G(x,y,z,4)*iyz + G(x,y,z,5)*izz); *(ptrd++) = veloc; if (veloc>veloc_max) veloc_max = veloc; else if (-veloc>veloc_max) veloc_max = -veloc; } } else // 2D version cimg_forZC(*this,z,c) { cimg_abort_test; CImg_3x3(I,Tfloat); cimg_for3x3(*this,x,y,z,c,I,Tfloat) { const Tfloat ixx = Inc + Ipc - 2*Icc, ixy = (Inn + Ipp - Inp - Ipn)/4, iyy = Icn + Icp - 2*Icc, veloc = (Tfloat)(G(x,y,0,0)*ixx + 2*G(x,y,0,1)*ixy + G(x,y,0,2)*iyy); *(ptrd++) = veloc; if (veloc>veloc_max) veloc_max = veloc; else if (-veloc>veloc_max) veloc_max = -veloc; } } if (veloc_max>0) *this+=(velocity*=dl/veloc_max); } } else { // LIC-based smoothing const ulongT whd = (ulongT)_width*_height*_depth; const float sqrt2amplitude = (float)std::sqrt(2*namplitude); const int dx1 = width() - 1, dy1 = height() - 1, dz1 = depth() - 1; CImg<Tfloat> res(_width,_height,_depth,_spectrum,0), W(_width,_height,_depth,is_3d?4:3), val(_spectrum,1,1,1,0); int N = 0; if (is_3d) { // 3D version for (float phi = cimg::mod(180.f,da)/2.f; phi<=180; phi+=da) { const float phir = (float)(phi*cimg::PI/180), datmp = (float)(da/std::cos(phir)), da2 = datmp<1?360.f:datmp; for (float theta = 0; theta<360; (theta+=da2),++N) { const float thetar = (float)(theta*cimg::PI/180), vx = (float)(std::cos(thetar)*std::cos(phir)), vy = (float)(std::sin(thetar)*std::cos(phir)), vz = (float)std::sin(phir); const t *pa = G.data(0,0,0,0), *pb = G.data(0,0,0,1), *pc = G.data(0,0,0,2), *pd = G.data(0,0,0,3), *pe = G.data(0,0,0,4), *pf = G.data(0,0,0,5); Tfloat *pd0 = W.data(0,0,0,0), *pd1 = W.data(0,0,0,1), *pd2 = W.data(0,0,0,2), *pd3 = W.data(0,0,0,3); cimg_forXYZ(G,xg,yg,zg) { const t a = *(pa++), b = *(pb++), c = *(pc++), d = *(pd++), e = *(pe++), f = *(pf++); const float u = (float)(a*vx + b*vy + c*vz), v = (float)(b*vx + d*vy + e*vz), w = (float)(c*vx + e*vy + f*vz), n = 1e-5f + cimg::hypot(u,v,w), dln = dl/n; *(pd0++) = (Tfloat)(u*dln); *(pd1++) = (Tfloat)(v*dln); *(pd2++) = (Tfloat)(w*dln); *(pd3++) = (Tfloat)n; } cimg_abort_test; cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height*_depth>=2) firstprivate(val)) cimg_forYZ(*this,y,z) _cimg_abort_try_omp2 { cimg_abort_test2; cimg_forX(*this,x) { val.fill(0); const float n = (float)W(x,y,z,3), fsigma = (float)(n*sqrt2amplitude), fsigma2 = 2*fsigma*fsigma, length = gauss_prec*fsigma; float S = 0, X = (float)x, Y = (float)y, Z = (float)z; switch (interpolation_type) { case 0 : { // Nearest neighbor for (float l = 0; l<length && X>=0 && X<=dx1 && Y>=0 && Y<=dy1 && Z>=0 && Z<=dz1; l+=dl) { const int cx = (int)(X + 0.5f), cy = (int)(Y + 0.5f), cz = (int)(Z + 0.5f); const float u = (float)W(cx,cy,cz,0), v = (float)W(cx,cy,cz,1), w = (float)W(cx,cy,cz,2); if (is_fast_approx) { cimg_forC(*this,c) val[c]+=(Tfloat)(*this)(cx,cy,cz,c); ++S; } else { const float coef = (float)std::exp(-l*l/fsigma2); cimg_forC(*this,c) val[c]+=(Tfloat)(coef*(*this)(cx,cy,cz,c)); S+=coef; } X+=u; Y+=v; Z+=w; } } break; case 1 : { // Linear interpolation for (float l = 0; l<length && X>=0 && X<=dx1 && Y>=0 && Y<=dy1 && Z>=0 && Z<=dz1; l+=dl) { const float u = (float)(W._linear_atXYZ(X,Y,Z,0)), v = (float)(W._linear_atXYZ(X,Y,Z,1)), w = (float)(W._linear_atXYZ(X,Y,Z,2)); if (is_fast_approx) { cimg_forC(*this,c) val[c]+=(Tfloat)_linear_atXYZ(X,Y,Z,c); ++S; } else { const float coef = (float)std::exp(-l*l/fsigma2); cimg_forC(*this,c) val[c]+=(Tfloat)(coef*_linear_atXYZ(X,Y,Z,c)); S+=coef; } X+=u; Y+=v; Z+=w; } } break; default : { // 2nd order Runge Kutta for (float l = 0; l<length && X>=0 && X<=dx1 && Y>=0 && Y<=dy1 && Z>=0 && Z<=dz1; l+=dl) { const float u0 = (float)(0.5f*W._linear_atXYZ(X,Y,Z,0)), v0 = (float)(0.5f*W._linear_atXYZ(X,Y,Z,1)), w0 = (float)(0.5f*W._linear_atXYZ(X,Y,Z,2)), u = (float)(W._linear_atXYZ(X + u0,Y + v0,Z + w0,0)), v = (float)(W._linear_atXYZ(X + u0,Y + v0,Z + w0,1)), w = (float)(W._linear_atXYZ(X + u0,Y + v0,Z + w0,2)); if (is_fast_approx) { cimg_forC(*this,c) val[c]+=(Tfloat)_linear_atXYZ(X,Y,Z,c); ++S; } else { const float coef = (float)std::exp(-l*l/fsigma2); cimg_forC(*this,c) val[c]+=(Tfloat)(coef*_linear_atXYZ(X,Y,Z,c)); S+=coef; } X+=u; Y+=v; Z+=w; } } break; } Tfloat *ptrd = res.data(x,y,z); if (S>0) cimg_forC(res,c) { *ptrd+=val[c]/S; ptrd+=whd; } else cimg_forC(res,c) { *ptrd+=(Tfloat)((*this)(x,y,z,c)); ptrd+=whd; } } } _cimg_abort_catch_omp2 } } } else { // 2D LIC algorithm for (float theta = cimg::mod(360.f,da)/2.f; theta<360; (theta+=da),++N) { const float thetar = (float)(theta*cimg::PI/180), vx = (float)(std::cos(thetar)), vy = (float)(std::sin(thetar)); const t *pa = G.data(0,0,0,0), *pb = G.data(0,0,0,1), *pc = G.data(0,0,0,2); Tfloat *pd0 = W.data(0,0,0,0), *pd1 = W.data(0,0,0,1), *pd2 = W.data(0,0,0,2); cimg_forXY(G,xg,yg) { const t a = *(pa++), b = *(pb++), c = *(pc++); const float u = (float)(a*vx + b*vy), v = (float)(b*vx + c*vy), n = std::max(1e-5f,cimg::hypot(u,v)), dln = dl/n; *(pd0++) = (Tfloat)(u*dln); *(pd1++) = (Tfloat)(v*dln); *(pd2++) = (Tfloat)n; } cimg_abort_test; cimg_pragma_openmp(parallel for cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height>=2) firstprivate(val)) cimg_forY(*this,y) _cimg_abort_try_omp2 { cimg_abort_test2; cimg_forX(*this,x) { val.fill(0); const float n = (float)W(x,y,0,2), fsigma = (float)(n*sqrt2amplitude), fsigma2 = 2*fsigma*fsigma, length = gauss_prec*fsigma; float S = 0, X = (float)x, Y = (float)y; switch (interpolation_type) { case 0 : { // Nearest-neighbor for (float l = 0; l<length && X>=0 && X<=dx1 && Y>=0 && Y<=dy1; l+=dl) { const int cx = (int)(X + 0.5f), cy = (int)(Y + 0.5f); const float u = (float)W(cx,cy,0,0), v = (float)W(cx,cy,0,1); if (is_fast_approx) { cimg_forC(*this,c) val[c]+=(Tfloat)(*this)(cx,cy,0,c); ++S; } else { const float coef = (float)std::exp(-l*l/fsigma2); cimg_forC(*this,c) val[c]+=(Tfloat)(coef*(*this)(cx,cy,0,c)); S+=coef; } X+=u; Y+=v; } } break; case 1 : { // Linear interpolation for (float l = 0; l<length && X>=0 && X<=dx1 && Y>=0 && Y<=dy1; l+=dl) { const float u = (float)(W._linear_atXY(X,Y,0,0)), v = (float)(W._linear_atXY(X,Y,0,1)); if (is_fast_approx) { cimg_forC(*this,c) val[c]+=(Tfloat)_linear_atXY(X,Y,0,c); ++S; } else { const float coef = (float)std::exp(-l*l/fsigma2); cimg_forC(*this,c) val[c]+=(Tfloat)(coef*_linear_atXY(X,Y,0,c)); S+=coef; } X+=u; Y+=v; } } break; default : { // 2nd-order Runge-kutta interpolation for (float l = 0; l<length && X>=0 && X<=dx1 && Y>=0 && Y<=dy1; l+=dl) { const float u0 = (float)(0.5f*W._linear_atXY(X,Y,0,0)), v0 = (float)(0.5f*W._linear_atXY(X,Y,0,1)), u = (float)(W._linear_atXY(X + u0,Y + v0,0,0)), v = (float)(W._linear_atXY(X + u0,Y + v0,0,1)); if (is_fast_approx) { cimg_forC(*this,c) val[c]+=(Tfloat)_linear_atXY(X,Y,0,c); ++S; } else { const float coef = (float)std::exp(-l*l/fsigma2); cimg_forC(*this,c) val[c]+=(Tfloat)(coef*_linear_atXY(X,Y,0,c)); S+=coef; } X+=u; Y+=v; } } } Tfloat *ptrd = res.data(x,y); if (S>0) cimg_forC(res,c) { *ptrd+=val[c]/S; ptrd+=whd; } else cimg_forC(res,c) { *ptrd+=(Tfloat)((*this)(x,y,0,c)); ptrd+=whd; } } } _cimg_abort_catch_omp2 } } const Tfloat *ptrs = res._data; cimg_for(*this,ptrd,T) { const Tfloat _val = *(ptrs++)/N; *ptrd = _val<val_min?val_min:(_val>val_max?val_max:(T)_val); } } cimg_abort_test; return *this; } //! Blur image anisotropically, directed by a field of diffusion tensors \newinstance. template<typename t> CImg<Tfloat> get_blur_anisotropic(const CImg<t>& G, const float amplitude=60, const float dl=0.8f, const float da=30, const float gauss_prec=2, const unsigned int interpolation_type=0, const bool is_fast_approx=true) const { return CImg<Tfloat>(*this,false).blur_anisotropic(G,amplitude,dl,da,gauss_prec,interpolation_type,is_fast_approx); } //! Blur image anisotropically, in an edge-preserving way. /** \param amplitude Amplitude of the smoothing. \param sharpness Sharpness. \param anisotropy Anisotropy. \param alpha Standard deviation of the gradient blur. \param sigma Standard deviation of the structure tensor blur. \param dl Spatial discretization. \param da Angular discretization. \param gauss_prec Precision of the diffusion process. \param interpolation_type Interpolation scheme. Can be <tt>{ 0=nearest-neighbor | 1=linear | 2=Runge-Kutta }</tt>. \param is_fast_approx Tells if a fast approximation of the gaussian function is used or not. **/ CImg<T>& blur_anisotropic(const float amplitude, const float sharpness=0.7f, const float anisotropy=0.6f, const float alpha=0.6f, const float sigma=1.1f, const float dl=0.8f, const float da=30, const float gauss_prec=2, const unsigned int interpolation_type=0, const bool is_fast_approx=true) { const float nalpha = alpha>=0?alpha:-alpha*cimg::max(_width,_height,_depth)/100; const float nsigma = sigma>=0?sigma:-sigma*cimg::max(_width,_height,_depth)/100; return blur_anisotropic(get_diffusion_tensors(sharpness,anisotropy,nalpha,nsigma,interpolation_type!=3), amplitude,dl,da,gauss_prec,interpolation_type,is_fast_approx); } //! Blur image anisotropically, in an edge-preserving way \newinstance. CImg<Tfloat> get_blur_anisotropic(const float amplitude, const float sharpness=0.7f, const float anisotropy=0.6f, const float alpha=0.6f, const float sigma=1.1f, const float dl=0.8f, const float da=30, const float gauss_prec=2, const unsigned int interpolation_type=0, const bool is_fast_approx=true) const { return CImg<Tfloat>(*this,false).blur_anisotropic(amplitude,sharpness,anisotropy,alpha,sigma,dl,da,gauss_prec, interpolation_type,is_fast_approx); } //! Blur image, with the joint bilateral filter. /** \param guide Image used to model the smoothing weights. \param sigma_x Amount of blur along the X-axis. \param sigma_y Amount of blur along the Y-axis. \param sigma_z Amount of blur along the Z-axis. \param sigma_r Amount of blur along the value axis. \param sampling_x Amount of downsampling along the X-axis used for the approximation. Defaults (0) to sigma_x. \param sampling_y Amount of downsampling along the Y-axis used for the approximation. Defaults (0) to sigma_y. \param sampling_z Amount of downsampling along the Z-axis used for the approximation. Defaults (0) to sigma_z. \param sampling_r Amount of downsampling along the value axis used for the approximation. Defaults (0) to sigma_r. \note This algorithm uses the optimisation technique proposed by S. Paris and F. Durand, in ECCV'2006 (extended for 3D volumetric images). It is based on the reference implementation http://people.csail.mit.edu/jiawen/software/bilateralFilter.m **/ template<typename t> CImg<T>& blur_bilateral(const CImg<t>& guide, const float sigma_x, const float sigma_y, const float sigma_z, const float sigma_r, const float sampling_x, const float sampling_y, const float sampling_z, const float sampling_r) { if (!is_sameXYZ(guide)) throw CImgArgumentException(_cimg_instance "blur_bilateral(): Invalid size for specified guide image (%u,%u,%u,%u,%p).", cimg_instance, guide._width,guide._height,guide._depth,guide._spectrum,guide._data); if (is_empty() || (!sigma_x && !sigma_y && !sigma_z)) return *this; T edge_min, edge_max = guide.max_min(edge_min); if (edge_min==edge_max) return blur(sigma_x,sigma_y,sigma_z); const float edge_delta = (float)(edge_max - edge_min), _sigma_x = sigma_x>=0?sigma_x:-sigma_x*_width/100, _sigma_y = sigma_y>=0?sigma_y:-sigma_y*_height/100, _sigma_z = sigma_z>=0?sigma_z:-sigma_z*_depth/100, _sigma_r = sigma_r>=0?sigma_r:-sigma_r*(edge_max - edge_min)/100, _sampling_x = sampling_x?sampling_x:std::max(_sigma_x,1.f), _sampling_y = sampling_y?sampling_y:std::max(_sigma_y,1.f), _sampling_z = sampling_z?sampling_z:std::max(_sigma_z,1.f), _sampling_r = sampling_r?sampling_r:std::max(_sigma_r,edge_delta/256), derived_sigma_x = _sigma_x / _sampling_x, derived_sigma_y = _sigma_y / _sampling_y, derived_sigma_z = _sigma_z / _sampling_z, derived_sigma_r = _sigma_r / _sampling_r; const int padding_x = (int)(2*derived_sigma_x) + 1, padding_y = (int)(2*derived_sigma_y) + 1, padding_z = (int)(2*derived_sigma_z) + 1, padding_r = (int)(2*derived_sigma_r) + 1; const unsigned int bx = (unsigned int)((_width - 1)/_sampling_x + 1 + 2*padding_x), by = (unsigned int)((_height - 1)/_sampling_y + 1 + 2*padding_y), bz = (unsigned int)((_depth - 1)/_sampling_z + 1 + 2*padding_z), br = (unsigned int)(edge_delta/_sampling_r + 1 + 2*padding_r); if (bx>0 || by>0 || bz>0 || br>0) { const bool is_3d = (_depth>1); if (is_3d) { // 3D version of the algorithm CImg<floatT> bgrid(bx,by,bz,br), bgridw(bx,by,bz,br); cimg_forC(*this,c) { const CImg<t> _guide = guide.get_shared_channel(c%guide._spectrum); bgrid.fill(0); bgridw.fill(0); cimg_forXYZ(*this,x,y,z) { const T val = (*this)(x,y,z,c); const float edge = (float)_guide(x,y,z); const int X = (int)cimg::round(x/_sampling_x) + padding_x, Y = (int)cimg::round(y/_sampling_y) + padding_y, Z = (int)cimg::round(z/_sampling_z) + padding_z, R = (int)cimg::round((edge - edge_min)/_sampling_r) + padding_r; bgrid(X,Y,Z,R)+=(float)val; bgridw(X,Y,Z,R)+=1; } bgrid.blur(derived_sigma_x,derived_sigma_y,derived_sigma_z,true).deriche(derived_sigma_r,0,'c',false); bgridw.blur(derived_sigma_x,derived_sigma_y,derived_sigma_z,true).deriche(derived_sigma_r,0,'c',false); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if_size(size(),4096)) cimg_forXYZ(*this,x,y,z) { const float edge = (float)_guide(x,y,z); const float X = x/_sampling_x + padding_x, Y = y/_sampling_y + padding_y, Z = z/_sampling_z + padding_z, R = (edge - edge_min)/_sampling_r + padding_r; const float bval0 = bgrid._linear_atXYZC(X,Y,Z,R), bval1 = bgridw._linear_atXYZC(X,Y,Z,R); (*this)(x,y,z,c) = (T)(bval0/bval1); } } } else { // 2D version of the algorithm CImg<floatT> bgrid(bx,by,br,2); cimg_forC(*this,c) { const CImg<t> _guide = guide.get_shared_channel(c%guide._spectrum); bgrid.fill(0); cimg_forXY(*this,x,y) { const T val = (*this)(x,y,c); const float edge = (float)_guide(x,y); const int X = (int)cimg::round(x/_sampling_x) + padding_x, Y = (int)cimg::round(y/_sampling_y) + padding_y, R = (int)cimg::round((edge - edge_min)/_sampling_r) + padding_r; bgrid(X,Y,R,0)+=(float)val; bgrid(X,Y,R,1)+=1; } bgrid.blur(derived_sigma_x,derived_sigma_y,0,true).blur(0,0,derived_sigma_r,false); cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(size(),4096)) cimg_forXY(*this,x,y) { const float edge = (float)_guide(x,y); const float X = x/_sampling_x + padding_x, Y = y/_sampling_y + padding_y, R = (edge - edge_min)/_sampling_r + padding_r; const float bval0 = bgrid._linear_atXYZ(X,Y,R,0), bval1 = bgrid._linear_atXYZ(X,Y,R,1); (*this)(x,y,c) = (T)(bval0/bval1); } } } } return *this; } //! Blur image, with the joint bilateral filter \newinstance. template<typename t> CImg<Tfloat> get_blur_bilateral(const CImg<t>& guide, const float sigma_x, const float sigma_y, const float sigma_z, const float sigma_r, const float sampling_x, const float sampling_y, const float sampling_z, const float sampling_r) const { return CImg<Tfloat>(*this,false).blur_bilateral(guide,sigma_x,sigma_y,sigma_z,sigma_r, sampling_x,sampling_y,sampling_z,sampling_r); } //! Blur image using the joint bilateral filter. /** \param guide Image used to model the smoothing weights. \param sigma_s Amount of blur along the XYZ-axes. \param sigma_r Amount of blur along the value axis. \param sampling_s Amount of downsampling along the XYZ-axes used for the approximation. Defaults to sigma_s. \param sampling_r Amount of downsampling along the value axis used for the approximation. Defaults to sigma_r. **/ template<typename t> CImg<T>& blur_bilateral(const CImg<t>& guide, const float sigma_s, const float sigma_r, const float sampling_s=0, const float sampling_r=0) { const float _sigma_s = sigma_s>=0?sigma_s:-sigma_s*cimg::max(_width,_height,_depth)/100; return blur_bilateral(guide,_sigma_s,_sigma_s,_sigma_s,sigma_r,sampling_s,sampling_s,sampling_s,sampling_r); } //! Blur image using the bilateral filter \newinstance. template<typename t> CImg<Tfloat> get_blur_bilateral(const CImg<t>& guide, const float sigma_s, const float sigma_r, const float sampling_s=0, const float sampling_r=0) const { return CImg<Tfloat>(*this,false).blur_bilateral(guide,sigma_s,sigma_r,sampling_s,sampling_r); } // [internal] Apply a box filter (used by CImg<T>::boxfilter() and CImg<T>::blur_box()). /* \param ptr the pointer of the data \param N size of the data \param boxsize Size of the box filter (can be subpixel). \param off the offset between two data point \param order the order of the filter 0 (smoothing), 1st derivtive and 2nd derivative. \param boundary_conditions Boundary conditions. Can be <tt>{ 0=dirichlet | 1=neumann }</tt>. */ static void _cimg_blur_box_apply(T *ptr, const float boxsize, const int N, const ulongT off, const int order, const bool boundary_conditions, const unsigned int nb_iter) { // Smooth. if (boxsize>1 && nb_iter) { const int w2 = (int)(boxsize - 1)/2; const unsigned int winsize = 2*w2 + 1U; const double frac = (boxsize - winsize)/2.; CImg<T> win(winsize); for (unsigned int iter = 0; iter<nb_iter; ++iter) { Tdouble sum = 0; // window sum for (int x = -w2; x<=w2; ++x) { win[x + w2] = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,x); sum+=win[x + w2]; } int ifirst = 0, ilast = 2*w2; T prev = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,-w2 - 1), next = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,w2 + 1); for (int x = 0; x < N - 1; ++x) { const double sum2 = sum + frac * (prev + next); ptr[x*off] = (T)(sum2/boxsize); prev = win[ifirst]; sum-=prev; ifirst = (int)((ifirst + 1)%winsize); ilast = (int)((ilast + 1)%winsize); win[ilast] = next; sum+=next; next = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,x + w2 + 2); } const double sum2 = sum + frac * (prev + next); ptr[(N - 1)*off] = (T)(sum2/boxsize); } } // Derive. switch (order) { case 0 : break; case 1 : { Tfloat p = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,-1), c = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,0), n = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,1); for (int x = 0; x<N - 1; ++x) { ptr[x*off] = (T)((n-p)/2.); p = c; c = n; n = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,x + 2); } ptr[(N - 1)*off] = (T)((n-p)/2.); } break; case 2: { Tfloat p = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,-1), c = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,0), n = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,1); for (int x = 0; x<N - 1; ++x) { ptr[x*off] = (T)(n - 2*c + p); p = c; c = n; n = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,x + 2); } ptr[(N - 1)*off] = (T)(n - 2*c + p); } break; } } static T __cimg_blur_box_apply(T *ptr, const int N, const ulongT off, const bool boundary_conditions, const int x) { if (x<0) return boundary_conditions?ptr[0]:T(); if (x>=N) return boundary_conditions?ptr[(N - 1)*off]:T(); return ptr[x*off]; } // Apply box filter of order 0,1,2. /** \param boxsize Size of the box window (can be subpixel) \param order the order of the filter 0,1 or 2. \param axis Axis along which the filter is computed. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param boundary_conditions Boundary conditions. Can be <tt>{ 0=dirichlet | 1=neumann }</tt>. \param nb_iter Number of filter iterations. **/ CImg<T>& boxfilter(const float boxsize, const int order, const char axis='x', const bool boundary_conditions=true, const unsigned int nb_iter=1) { if (is_empty() || !boxsize || (boxsize<=1 && !order)) return *this; const char naxis = cimg::lowercase(axis); const float nboxsize = boxsize>=0?boxsize:-boxsize* (naxis=='x'?_width:naxis=='y'?_height:naxis=='z'?_depth:_spectrum)/100; switch (naxis) { case 'x' : { cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height*_depth*_spectrum>=16)) cimg_forYZC(*this,y,z,c) _cimg_blur_box_apply(data(0,y,z,c),nboxsize,_width,1U,order,boundary_conditions,nb_iter); } break; case 'y' : { cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height*_depth*_spectrum>=16)) cimg_forXZC(*this,x,z,c) _cimg_blur_box_apply(data(x,0,z,c),nboxsize,_height,(ulongT)_width,order,boundary_conditions,nb_iter); } break; case 'z' : { cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height*_depth*_spectrum>=16)) cimg_forXYC(*this,x,y,c) _cimg_blur_box_apply(data(x,y,0,c),nboxsize,_depth,(ulongT)_width*_height,order,boundary_conditions,nb_iter); } break; default : { cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height*_depth*_spectrum>=16)) cimg_forXYZ(*this,x,y,z) _cimg_blur_box_apply(data(x,y,z,0),nboxsize,_spectrum,(ulongT)_width*_height*_depth, order,boundary_conditions,nb_iter); } } return *this; } // Apply box filter of order 0,1 or 2 \newinstance. CImg<Tfloat> get_boxfilter(const float boxsize, const int order, const char axis='x', const bool boundary_conditions=true, const unsigned int nb_iter=1) const { return CImg<Tfloat>(*this,false).boxfilter(boxsize,order,axis,boundary_conditions,nb_iter); } //! Blur image with a box filter. /** \param boxsize_x Size of the box window, along the X-axis (can be subpixel). \param boxsize_y Size of the box window, along the Y-axis (can be subpixel). \param boxsize_z Size of the box window, along the Z-axis (can be subpixel). \param boundary_conditions Boundary conditions. Can be <tt>{ false=dirichlet | true=neumann }</tt>. \param nb_iter Number of filter iterations. \note - This is a recursive algorithm, not depending on the values of the box kernel size. \see blur(). **/ CImg<T>& blur_box(const float boxsize_x, const float boxsize_y, const float boxsize_z, const bool boundary_conditions=true, const unsigned int nb_iter=1) { if (is_empty()) return *this; if (_width>1) boxfilter(boxsize_x,0,'x',boundary_conditions,nb_iter); if (_height>1) boxfilter(boxsize_y,0,'y',boundary_conditions,nb_iter); if (_depth>1) boxfilter(boxsize_z,0,'z',boundary_conditions,nb_iter); return *this; } //! Blur image with a box filter \newinstance. CImg<Tfloat> get_blur_box(const float boxsize_x, const float boxsize_y, const float boxsize_z, const bool boundary_conditions=true) const { return CImg<Tfloat>(*this,false).blur_box(boxsize_x,boxsize_y,boxsize_z,boundary_conditions); } //! Blur image with a box filter. /** \param boxsize Size of the box window (can be subpixel). \param boundary_conditions Boundary conditions. Can be <tt>{ 0=dirichlet | 1=neumann }</tt>.a \see deriche(), vanvliet(). **/ CImg<T>& blur_box(const float boxsize, const bool boundary_conditions=true) { const float nboxsize = boxsize>=0?boxsize:-boxsize*cimg::max(_width,_height,_depth)/100; return blur_box(nboxsize,nboxsize,nboxsize,boundary_conditions); } //! Blur image with a box filter \newinstance. CImg<Tfloat> get_blur_box(const float boxsize, const bool boundary_conditions=true) const { return CImg<Tfloat>(*this,false).blur_box(boxsize,boundary_conditions); } //! Blur image, with the image guided filter. /** \param guide Image used to guide the smoothing process. \param radius Spatial radius. If negative, it is expressed as a percentage of the largest image size. \param regularization Regularization parameter. If negative, it is expressed as a percentage of the guide value range. \note This method implements the filtering algorithm described in: He, Kaiming; Sun, Jian; Tang, Xiaoou, "Guided Image Filtering," Pattern Analysis and Machine Intelligence, IEEE Transactions on , vol.35, no.6, pp.1397,1409, June 2013 **/ template<typename t> CImg<T>& blur_guided(const CImg<t>& guide, const float radius, const float regularization) { return get_blur_guided(guide,radius,regularization).move_to(*this); } //! Blur image, with the image guided filter \newinstance. template<typename t> CImg<Tfloat> get_blur_guided(const CImg<t>& guide, const float radius, const float regularization) const { if (!is_sameXYZ(guide)) throw CImgArgumentException(_cimg_instance "blur_guided(): Invalid size for specified guide image (%u,%u,%u,%u,%p).", cimg_instance, guide._width,guide._height,guide._depth,guide._spectrum,guide._data); if (is_empty() || !radius) return *this; const int _radius = radius>=0?(int)radius:(int)(-radius*cimg::max(_width,_height,_depth)/100); float _regularization = regularization; if (regularization<0) { T edge_min, edge_max = guide.max_min(edge_min); if (edge_min==edge_max) return *this; _regularization = -regularization*(edge_max - edge_min)/100; } _regularization = std::max(_regularization,0.01f); const unsigned int psize = (unsigned int)(1 + 2*_radius); CImg<Tfloat> mean_p = get_blur_box(psize,true), mean_I = guide.get_blur_box(psize,true).resize(mean_p), cov_Ip = get_mul(guide).blur_box(psize,true)-=mean_p.get_mul(mean_I), var_I = guide.get_sqr().blur_box(psize,true)-=mean_I.get_sqr(), &a = cov_Ip.div(var_I+=_regularization), &b = mean_p-=a.get_mul(mean_I); a.blur_box(psize,true); b.blur_box(psize,true); return a.mul(guide)+=b; } //! Blur image using patch-based space. /** \param sigma_s Amount of blur along the XYZ-axes. \param sigma_p Amount of blur along the value axis. \param patch_size Size of the patches. \param lookup_size Size of the window to search similar patches. \param smoothness Smoothness for the patch comparison. \param is_fast_approx Tells if a fast approximation of the gaussian function is used or not. **/ CImg<T>& blur_patch(const float sigma_s, const float sigma_p, const unsigned int patch_size=3, const unsigned int lookup_size=4, const float smoothness=0, const bool is_fast_approx=true) { if (is_empty() || !patch_size || !lookup_size) return *this; return get_blur_patch(sigma_s,sigma_p,patch_size,lookup_size,smoothness,is_fast_approx).move_to(*this); } //! Blur image using patch-based space \newinstance. CImg<Tfloat> get_blur_patch(const float sigma_s, const float sigma_p, const unsigned int patch_size=3, const unsigned int lookup_size=4, const float smoothness=0, const bool is_fast_approx=true) const { #define _cimg_blur_patch3d_fast(N) \ cimg_for##N##XYZ(res,x,y,z) { \ T *pP = P._data; cimg_forC(res,c) { cimg_get##N##x##N##x##N(img,x,y,z,c,pP,T); pP+=N3; } \ const int x0 = x - rsize1, y0 = y - rsize1, z0 = z - rsize1, \ x1 = x + rsize2, y1 = y + rsize2, z1 = z + rsize2; \ float sum_weights = 0; \ cimg_for_in##N##XYZ(res,x0,y0,z0,x1,y1,z1,p,q,r) \ if (cimg::abs((Tfloat)img(x,y,z,0) - (Tfloat)img(p,q,r,0))<sigma_p3) { \ T *pQ = Q._data; cimg_forC(res,c) { cimg_get##N##x##N##x##N(img,p,q,r,c,pQ,T); pQ+=N3; } \ float distance2 = 0; \ pQ = Q._data; cimg_for(P,_pP,T) { const float dI = (float)*_pP - (float)*(pQ++); distance2+=dI*dI; } \ distance2/=Pnorm; \ const float dx = (float)p - x, dy = (float)q - y, dz = (float)r - z, \ alldist = distance2 + (dx*dx + dy*dy + dz*dz)/sigma_s2, weight = alldist>3?0.f:1.f; \ sum_weights+=weight; \ cimg_forC(res,c) res(x,y,z,c)+=weight*(*this)(p,q,r,c); \ } \ if (sum_weights>0) cimg_forC(res,c) res(x,y,z,c)/=sum_weights; \ else cimg_forC(res,c) res(x,y,z,c) = (Tfloat)((*this)(x,y,z,c)); \ } #define _cimg_blur_patch3d(N) \ cimg_for##N##XYZ(res,x,y,z) { \ T *pP = P._data; cimg_forC(res,c) { cimg_get##N##x##N##x##N(img,x,y,z,c,pP,T); pP+=N3; } \ const int x0 = x - rsize1, y0 = y - rsize1, z0 = z - rsize1, \ x1 = x + rsize2, y1 = y + rsize2, z1 = z + rsize2; \ float sum_weights = 0, weight_max = 0; \ cimg_for_in##N##XYZ(res,x0,y0,z0,x1,y1,z1,p,q,r) if (p!=x || q!=y || r!=z) { \ T *pQ = Q._data; cimg_forC(res,c) { cimg_get##N##x##N##x##N(img,p,q,r,c,pQ,T); pQ+=N3; } \ float distance2 = 0; \ pQ = Q._data; cimg_for(P,_pP,T) { const float dI = (float)*_pP - (float)*(pQ++); distance2+=dI*dI; } \ distance2/=Pnorm; \ const float dx = (float)p - x, dy = (float)q - y, dz = (float)r - z, \ alldist = distance2 + (dx*dx + dy*dy + dz*dz)/sigma_s2, weight = (float)std::exp(-alldist); \ if (weight>weight_max) weight_max = weight; \ sum_weights+=weight; \ cimg_forC(res,c) res(x,y,z,c)+=weight*(*this)(p,q,r,c); \ } \ sum_weights+=weight_max; cimg_forC(res,c) res(x,y,z,c)+=weight_max*(*this)(x,y,z,c); \ if (sum_weights>0) cimg_forC(res,c) res(x,y,z,c)/=sum_weights; \ else cimg_forC(res,c) res(x,y,z,c) = (Tfloat)((*this)(x,y,z,c)); \ } #define _cimg_blur_patch2d_fast(N) \ cimg_for##N##XY(res,x,y) { \ T *pP = P._data; cimg_forC(res,c) { cimg_get##N##x##N(img,x,y,0,c,pP,T); pP+=N2; } \ const int x0 = x - rsize1, y0 = y - rsize1, x1 = x + rsize2, y1 = y + rsize2; \ float sum_weights = 0; \ cimg_for_in##N##XY(res,x0,y0,x1,y1,p,q) \ if (cimg::abs((Tfloat)img(x,y,0,0) - (Tfloat)img(p,q,0,0))<sigma_p3) { \ T *pQ = Q._data; cimg_forC(res,c) { cimg_get##N##x##N(img,p,q,0,c,pQ,T); pQ+=N2; } \ float distance2 = 0; \ pQ = Q._data; cimg_for(P,_pP,T) { const float dI = (float)*_pP - (float)*(pQ++); distance2+=dI*dI; } \ distance2/=Pnorm; \ const float dx = (float)p - x, dy = (float)q - y, \ alldist = distance2 + (dx*dx+dy*dy)/sigma_s2, weight = alldist>3?0.f:1.f; \ sum_weights+=weight; \ cimg_forC(res,c) res(x,y,c)+=weight*(*this)(p,q,c); \ } \ if (sum_weights>0) cimg_forC(res,c) res(x,y,c)/=sum_weights; \ else cimg_forC(res,c) res(x,y,c) = (Tfloat)((*this)(x,y,c)); \ } #define _cimg_blur_patch2d(N) \ cimg_for##N##XY(res,x,y) { \ T *pP = P._data; cimg_forC(res,c) { cimg_get##N##x##N(img,x,y,0,c,pP,T); pP+=N2; } \ const int x0 = x - rsize1, y0 = y - rsize1, x1 = x + rsize2, y1 = y + rsize2; \ float sum_weights = 0, weight_max = 0; \ cimg_for_in##N##XY(res,x0,y0,x1,y1,p,q) if (p!=x || q!=y) { \ T *pQ = Q._data; cimg_forC(res,c) { cimg_get##N##x##N(img,p,q,0,c,pQ,T); pQ+=N2; } \ float distance2 = 0; \ pQ = Q._data; cimg_for(P,_pP,T) { const float dI = (float)*_pP - (float)*(pQ++); distance2+=dI*dI; } \ distance2/=Pnorm; \ const float dx = (float)p - x, dy = (float)q - y, \ alldist = distance2 + (dx*dx+dy*dy)/sigma_s2, weight = (float)std::exp(-alldist); \ if (weight>weight_max) weight_max = weight; \ sum_weights+=weight; \ cimg_forC(res,c) res(x,y,c)+=weight*(*this)(p,q,c); \ } \ sum_weights+=weight_max; cimg_forC(res,c) res(x,y,c)+=weight_max*(*this)(x,y,c); \ if (sum_weights>0) cimg_forC(res,c) res(x,y,c)/=sum_weights; \ else cimg_forC(res,c) res(x,y,c) = (Tfloat)((*this)(x,y,c)); \ } if (is_empty() || !patch_size || !lookup_size) return +*this; CImg<Tfloat> res(_width,_height,_depth,_spectrum,0); const CImg<T> _img = smoothness>0?get_blur(smoothness):CImg<Tfloat>(),&img = smoothness>0?_img:*this; CImg<T> P(patch_size*patch_size*_spectrum), Q(P); const float nsigma_s = sigma_s>=0?sigma_s:-sigma_s*cimg::max(_width,_height,_depth)/100, sigma_s2 = nsigma_s*nsigma_s, sigma_p2 = sigma_p*sigma_p, sigma_p3 = 3*sigma_p, Pnorm = P.size()*sigma_p2; const int rsize2 = (int)lookup_size/2, rsize1 = (int)lookup_size - rsize2 - 1; const unsigned int N2 = patch_size*patch_size, N3 = N2*patch_size; cimg::unused(N2,N3); if (_depth>1) switch (patch_size) { // 3D case 2 : if (is_fast_approx) _cimg_blur_patch3d_fast(2) else _cimg_blur_patch3d(2) break; case 3 : if (is_fast_approx) _cimg_blur_patch3d_fast(3) else _cimg_blur_patch3d(3) break; default : { const int psize2 = (int)patch_size/2, psize1 = (int)patch_size - psize2 - 1; if (is_fast_approx) cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(res._width>=(cimg_openmp_sizefactor)*32 && res._height*res._depth>=4) private(P,Q)) cimg_forXYZ(res,x,y,z) { // Fast P = img.get_crop(x - psize1,y - psize1,z - psize1,x + psize2,y + psize2,z + psize2,true); const int x0 = x - rsize1, y0 = y - rsize1, z0 = z - rsize1, x1 = x + rsize2, y1 = y + rsize2, z1 = z + rsize2; float sum_weights = 0; cimg_for_inXYZ(res,x0,y0,z0,x1,y1,z1,p,q,r) if (cimg::abs((Tfloat)img(x,y,z,0) - (Tfloat)img(p,q,r,0))<sigma_p3) { (Q = img.get_crop(p - psize1,q - psize1,r - psize1,p + psize2,q + psize2,r + psize2,true))-=P; const float dx = (float)x - p, dy = (float)y - q, dz = (float)z - r, distance2 = (float)(Q.pow(2).sum()/Pnorm + (dx*dx + dy*dy + dz*dz)/sigma_s2), weight = distance2>3?0.f:1.f; sum_weights+=weight; cimg_forC(res,c) res(x,y,z,c)+=weight*(*this)(p,q,r,c); } if (sum_weights>0) cimg_forC(res,c) res(x,y,z,c)/=sum_weights; else cimg_forC(res,c) res(x,y,z,c) = (Tfloat)((*this)(x,y,z,c)); } else cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) if (res._width>=32 && res._height*res._depth>=4) firstprivate(P,Q)) cimg_forXYZ(res,x,y,z) { // Exact P = img.get_crop(x - psize1,y - psize1,z - psize1,x + psize2,y + psize2,z + psize2,true); const int x0 = x - rsize1, y0 = y - rsize1, z0 = z - rsize1, x1 = x + rsize2, y1 = y + rsize2, z1 = z + rsize2; float sum_weights = 0, weight_max = 0; cimg_for_inXYZ(res,x0,y0,z0,x1,y1,z1,p,q,r) if (p!=x || q!=y || r!=z) { (Q = img.get_crop(p - psize1,q - psize1,r - psize1,p + psize2,q + psize2,r + psize2,true))-=P; const float dx = (float)x - p, dy = (float)y - q, dz = (float)z - r, distance2 = (float)(Q.pow(2).sum()/Pnorm + (dx*dx + dy*dy + dz*dz)/sigma_s2), weight = (float)std::exp(-distance2); if (weight>weight_max) weight_max = weight; sum_weights+=weight; cimg_forC(res,c) res(x,y,z,c)+=weight*(*this)(p,q,r,c); } sum_weights+=weight_max; cimg_forC(res,c) res(x,y,z,c)+=weight_max*(*this)(x,y,z,c); if (sum_weights>0) cimg_forC(res,c) res(x,y,z,c)/=sum_weights; else cimg_forC(res,c) res(x,y,z,c) = (Tfloat)((*this)(x,y,z,c)); } } } else switch (patch_size) { // 2D case 2 : if (is_fast_approx) _cimg_blur_patch2d_fast(2) else _cimg_blur_patch2d(2) break; case 3 : if (is_fast_approx) _cimg_blur_patch2d_fast(3) else _cimg_blur_patch2d(3) break; case 4 : if (is_fast_approx) _cimg_blur_patch2d_fast(4) else _cimg_blur_patch2d(4) break; case 5 : if (is_fast_approx) _cimg_blur_patch2d_fast(5) else _cimg_blur_patch2d(5) break; case 6 : if (is_fast_approx) _cimg_blur_patch2d_fast(6) else _cimg_blur_patch2d(6) break; case 7 : if (is_fast_approx) _cimg_blur_patch2d_fast(7) else _cimg_blur_patch2d(7) break; case 8 : if (is_fast_approx) _cimg_blur_patch2d_fast(8) else _cimg_blur_patch2d(8) break; case 9 : if (is_fast_approx) _cimg_blur_patch2d_fast(9) else _cimg_blur_patch2d(9) break; default : { // Fast const int psize2 = (int)patch_size/2, psize1 = (int)patch_size - psize2 - 1; if (is_fast_approx) cimg_pragma_openmp(parallel for cimg_openmp_if(res._width>=(cimg_openmp_sizefactor)*32 && res._height>=4) firstprivate(P,Q)) cimg_forXY(res,x,y) { // Fast P = img.get_crop(x - psize1,y - psize1,x + psize2,y + psize2,true); const int x0 = x - rsize1, y0 = y - rsize1, x1 = x + rsize2, y1 = y + rsize2; float sum_weights = 0; cimg_for_inXY(res,x0,y0,x1,y1,p,q) if ((Tfloat)cimg::abs(img(x,y,0) - (Tfloat)img(p,q,0))<sigma_p3) { (Q = img.get_crop(p - psize1,q - psize1,p + psize2,q + psize2,true))-=P; const float dx = (float)x - p, dy = (float)y - q, distance2 = (float)(Q.pow(2).sum()/Pnorm + (dx*dx + dy*dy)/sigma_s2), weight = distance2>3?0.f:1.f; sum_weights+=weight; cimg_forC(res,c) res(x,y,c)+=weight*(*this)(p,q,c); } if (sum_weights>0) cimg_forC(res,c) res(x,y,c)/=sum_weights; else cimg_forC(res,c) res(x,y,c) = (Tfloat)((*this)(x,y,c)); } else cimg_pragma_openmp(parallel for cimg_openmp_if(res._width>=(cimg_openmp_sizefactor)*32 && res._height>=4) firstprivate(P,Q)) cimg_forXY(res,x,y) { // Exact P = img.get_crop(x - psize1,y - psize1,x + psize2,y + psize2,true); const int x0 = x - rsize1, y0 = y - rsize1, x1 = x + rsize2, y1 = y + rsize2; float sum_weights = 0, weight_max = 0; cimg_for_inXY(res,x0,y0,x1,y1,p,q) if (p!=x || q!=y) { (Q = img.get_crop(p - psize1,q - psize1,p + psize2,q + psize2,true))-=P; const float dx = (float)x - p, dy = (float)y - q, distance2 = (float)(Q.pow(2).sum()/Pnorm + (dx*dx + dy*dy)/sigma_s2), weight = (float)std::exp(-distance2); if (weight>weight_max) weight_max = weight; sum_weights+=weight; cimg_forC(res,c) res(x,y,c)+=weight*(*this)(p,q,c); } sum_weights+=weight_max; cimg_forC(res,c) res(x,y,c)+=weight_max*(*this)(x,y,c); if (sum_weights>0) cimg_forC(res,c) res(x,y,c)/=sum_weights; else cimg_forC(res,c) res(x,y,0,c) = (Tfloat)((*this)(x,y,c)); } } } return res; } //! Blur image with the median filter. /** \param n Size of the median filter. \param threshold Threshold used to discard pixels too far from the current pixel value in the median computation. **/ CImg<T>& blur_median(const unsigned int n, const float threshold=0) { if (!n) return *this; return get_blur_median(n,threshold).move_to(*this); } //! Blur image with the median filter \newinstance. CImg<T> get_blur_median(const unsigned int n, const float threshold=0) const { if (is_empty() || n<=1) return +*this; CImg<T> res(_width,_height,_depth,_spectrum); T *ptrd = res._data; cimg::unused(ptrd); const int hr = (int)n/2, hl = n - hr - 1; if (res._depth!=1) { // 3D if (threshold>0) cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*16 && _height*_depth*_spectrum>=4)) cimg_forXYZC(*this,x,y,z,c) { // With threshold const int x0 = x - hl, y0 = y - hl, z0 = z - hl, x1 = x + hr, y1 = y + hr, z1 = z + hr, nx0 = x0<0?0:x0, ny0 = y0<0?0:y0, nz0 = z0<0?0:z0, nx1 = x1>=width()?width() - 1:x1, ny1 = y1>=height()?height() - 1:y1, nz1 = z1>=depth()?depth() - 1:z1; const Tfloat val0 = (Tfloat)(*this)(x,y,z,c); CImg<T> values(n*n*n); unsigned int nb_values = 0; T *_ptrd = values.data(); cimg_for_inXYZ(*this,nx0,ny0,nz0,nx1,ny1,nz1,p,q,r) if (cimg::abs((*this)(p,q,r,c) - val0)<=threshold) { *(_ptrd++) = (*this)(p,q,r,c); ++nb_values; } res(x,y,z,c) = nb_values?values.get_shared_points(0,nb_values - 1).median():(*this)(x,y,z,c); } else cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*16 && _height*_depth*_spectrum>=4)) cimg_forXYZC(*this,x,y,z,c) { // Without threshold const int x0 = x - hl, y0 = y - hl, z0 = z - hl, x1 = x + hr, y1 = y + hr, z1 = z + hr, nx0 = x0<0?0:x0, ny0 = y0<0?0:y0, nz0 = z0<0?0:z0, nx1 = x1>=width()?width() - 1:x1, ny1 = y1>=height()?height() - 1:y1, nz1 = z1>=depth()?depth() - 1:z1; res(x,y,z,c) = get_crop(nx0,ny0,nz0,c,nx1,ny1,nz1,c).median(); } } else { if (threshold>0) cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*16 && _height*_spectrum>=4)) cimg_forXYC(*this,x,y,c) { // With threshold const int x0 = x - hl, y0 = y - hl, x1 = x + hr, y1 = y + hr, nx0 = x0<0?0:x0, ny0 = y0<0?0:y0, nx1 = x1>=width()?width() - 1:x1, ny1 = y1>=height()?height() - 1:y1; const Tfloat val0 = (Tfloat)(*this)(x,y,c); CImg<T> values(n*n); unsigned int nb_values = 0; T *_ptrd = values.data(); cimg_for_inXY(*this,nx0,ny0,nx1,ny1,p,q) if (cimg::abs((*this)(p,q,c) - val0)<=threshold) { *(_ptrd++) = (*this)(p,q,c); ++nb_values; } res(x,y,c) = nb_values?values.get_shared_points(0,nb_values - 1).median():(*this)(x,y,c); } else { const int w1 = width() - 1, h1 = height() - 1, w2 = width() - 2, h2 = height() - 2, w3 = width() - 3, h3 = height() - 3, w4 = width() - 4, h4 = height() - 4; switch (n) { // Without threshold case 3 : { cimg_pragma_openmp(parallel for cimg_openmp_if(_spectrum>=2)) cimg_forC(*this,c) { CImg<T> I(9); cimg_for_in3x3(*this,1,1,w2,h2,x,y,0,c,I,T) res(x,y,c) = cimg::median(I[0],I[1],I[2],I[3],I[4],I[5],I[6],I[7],I[8]); cimg_for_borderXY(*this,x,y,1) res(x,y,c) = get_crop(std::max(0,x - 1),std::max(0,y - 1),0,c, std::min(w1,x + 1),std::min(h1,y + 1),0,c).median(); } } break; case 5 : { cimg_pragma_openmp(parallel for cimg_openmp_if(_spectrum>=2)) cimg_forC(*this,c) { CImg<T> I(25); cimg_for_in5x5(*this,2,2,w3,h3,x,y,0,c,I,T) res(x,y,c) = cimg::median(I[0],I[1],I[2],I[3],I[4], I[5],I[6],I[7],I[8],I[9], I[10],I[11],I[12],I[13],I[14], I[15],I[16],I[17],I[18],I[19], I[20],I[21],I[22],I[23],I[24]); cimg_for_borderXY(*this,x,y,2) res(x,y,c) = get_crop(std::max(0,x - 2),std::max(0,y - 2),0,c, std::min(w1,x + 2),std::min(h1,y + 2),0,c).median(); } } break; case 7 : { cimg_pragma_openmp(parallel for cimg_openmp_if(_spectrum>=2)) cimg_forC(*this,c) { CImg<T> I(49); cimg_for_in7x7(*this,3,3,w4,h4,x,y,0,c,I,T) res(x,y,c) = cimg::median(I[0],I[1],I[2],I[3],I[4],I[5],I[6], I[7],I[8],I[9],I[10],I[11],I[12],I[13], I[14],I[15],I[16],I[17],I[18],I[19],I[20], I[21],I[22],I[23],I[24],I[25],I[26],I[27], I[28],I[29],I[30],I[31],I[32],I[33],I[34], I[35],I[36],I[37],I[38],I[39],I[40],I[41], I[42],I[43],I[44],I[45],I[46],I[47],I[48]); cimg_for_borderXY(*this,x,y,3) res(x,y,c) = get_crop(std::max(0,x - 3),std::max(0,y - 3),0,c, std::min(w1,x + 3),std::min(h1,y + 3),0,c).median(); } } break; default : { cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*16 && _height*_spectrum>=4)) cimg_forXYC(*this,x,y,c) { const int x0 = x - hl, y0 = y - hl, x1 = x + hr, y1 = y + hr, nx0 = x0<0?0:x0, ny0 = y0<0?0:y0, nx1 = x1>=width()?width() - 1:x1, ny1 = y1>=height()?height() - 1:y1; res(x,y,c) = get_crop(nx0,ny0,0,c,nx1,ny1,0,c).median(); } } } } } return res; } //! Sharpen image. /** \param amplitude Sharpening amplitude \param sharpen_type Select sharpening method. Can be <tt>{ false=inverse diffusion | true=shock filters }</tt>. \param edge Edge threshold (shock filters only). \param alpha Gradient smoothness (shock filters only). \param sigma Tensor smoothness (shock filters only). **/ CImg<T>& sharpen(const float amplitude, const bool sharpen_type=false, const float edge=1, const float alpha=0, const float sigma=0) { if (is_empty()) return *this; T val_min, val_max = max_min(val_min); const float nedge = edge/2; CImg<Tfloat> velocity(_width,_height,_depth,_spectrum), _veloc_max(_spectrum); if (_depth>1) { // 3D if (sharpen_type) { // Shock filters CImg<Tfloat> G = (alpha>0?get_blur(alpha).get_structure_tensors():get_structure_tensors()); if (sigma>0) G.blur(sigma); cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*32 && _height*_depth>=16)) cimg_forYZ(G,y,z) { Tfloat *ptrG0 = G.data(0,y,z,0), *ptrG1 = G.data(0,y,z,1), *ptrG2 = G.data(0,y,z,2), *ptrG3 = G.data(0,y,z,3); CImg<Tfloat> val, vec; cimg_forX(G,x) { G.get_tensor_at(x,y,z).symmetric_eigen(val,vec); if (val[0]<0) val[0] = 0; if (val[1]<0) val[1] = 0; if (val[2]<0) val[2] = 0; *(ptrG0++) = vec(0,0); *(ptrG1++) = vec(0,1); *(ptrG2++) = vec(0,2); *(ptrG3++) = 1 - (Tfloat)std::pow(1 + val[0] + val[1] + val[2],-(Tfloat)nedge); } } cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height*_depth>=(cimg_openmp_sizefactor)*512 && _spectrum>=2)) cimg_forC(*this,c) { Tfloat *ptrd = velocity.data(0,0,0,c), veloc_max = 0; CImg_3x3x3(I,Tfloat); cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) { const Tfloat u = G(x,y,z,0), v = G(x,y,z,1), w = G(x,y,z,2), amp = G(x,y,z,3), ixx = Incc + Ipcc - 2*Iccc, ixy = (Innc + Ippc - Inpc - Ipnc)/4, ixz = (Incn + Ipcp - Incp - Ipcn)/4, iyy = Icnc + Icpc - 2*Iccc, iyz = (Icnn + Icpp - Icnp - Icpn)/4, izz = Iccn + Iccp - 2*Iccc, ixf = Incc - Iccc, ixb = Iccc - Ipcc, iyf = Icnc - Iccc, iyb = Iccc - Icpc, izf = Iccn - Iccc, izb = Iccc - Iccp, itt = u*u*ixx + v*v*iyy + w*w*izz + 2*u*v*ixy + 2*u*w*ixz + 2*v*w*iyz, it = u*cimg::minmod(ixf,ixb) + v*cimg::minmod(iyf,iyb) + w*cimg::minmod(izf,izb), veloc = -amp*cimg::sign(itt)*cimg::abs(it); *(ptrd++) = veloc; if (veloc>veloc_max) veloc_max = veloc; else if (-veloc>veloc_max) veloc_max = -veloc; } _veloc_max[c] = veloc_max; } } else // Inverse diffusion cimg_forC(*this,c) { Tfloat *ptrd = velocity.data(0,0,0,c), veloc_max = 0; CImg_3x3x3(I,Tfloat); cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) { const Tfloat veloc = -Ipcc - Incc - Icpc - Icnc - Iccp - Iccn + 6*Iccc; *(ptrd++) = veloc; if (veloc>veloc_max) veloc_max = veloc; else if (-veloc>veloc_max) veloc_max = -veloc; } _veloc_max[c] = veloc_max; } } else { // 2D if (sharpen_type) { // Shock filters CImg<Tfloat> G = (alpha>0?get_blur(alpha).get_structure_tensors():get_structure_tensors()); if (sigma>0) G.blur(sigma); cimg_pragma_openmp(parallel for cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*32 && _height>=(cimg_openmp_sizefactor)*16)) cimg_forY(G,y) { CImg<Tfloat> val, vec; Tfloat *ptrG0 = G.data(0,y,0,0), *ptrG1 = G.data(0,y,0,1), *ptrG2 = G.data(0,y,0,2); cimg_forX(G,x) { G.get_tensor_at(x,y).symmetric_eigen(val,vec); if (val[0]<0) val[0] = 0; if (val[1]<0) val[1] = 0; *(ptrG0++) = vec(0,0); *(ptrG1++) = vec(0,1); *(ptrG2++) = 1 - (Tfloat)std::pow(1 + val[0] + val[1],-(Tfloat)nedge); } } cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height>=(cimg_openmp_sizefactor)*512 && _spectrum>=2)) cimg_forC(*this,c) { Tfloat *ptrd = velocity.data(0,0,0,c), veloc_max = 0; CImg_3x3(I,Tfloat); cimg_for3x3(*this,x,y,0,c,I,Tfloat) { const Tfloat u = G(x,y,0), v = G(x,y,1), amp = G(x,y,2), ixx = Inc + Ipc - 2*Icc, ixy = (Inn + Ipp - Inp - Ipn)/4, iyy = Icn + Icp - 2*Icc, ixf = Inc - Icc, ixb = Icc - Ipc, iyf = Icn - Icc, iyb = Icc - Icp, itt = u*u*ixx + v*v*iyy + 2*u*v*ixy, it = u*cimg::minmod(ixf,ixb) + v*cimg::minmod(iyf,iyb), veloc = -amp*cimg::sign(itt)*cimg::abs(it); *(ptrd++) = veloc; if (veloc>veloc_max) veloc_max = veloc; else if (-veloc>veloc_max) veloc_max = -veloc; } _veloc_max[c] = veloc_max; } } else // Inverse diffusion cimg_forC(*this,c) { Tfloat *ptrd = velocity.data(0,0,0,c), veloc_max = 0; CImg_3x3(I,Tfloat); cimg_for3x3(*this,x,y,0,c,I,Tfloat) { const Tfloat veloc = -Ipc - Inc - Icp - Icn + 4*Icc; *(ptrd++) = veloc; if (veloc>veloc_max) veloc_max = veloc; else if (-veloc>veloc_max) veloc_max = -veloc; } _veloc_max[c] = veloc_max; } } const Tfloat veloc_max = _veloc_max.max(); if (veloc_max<=0) return *this; return ((velocity*=amplitude/veloc_max)+=*this).cut(val_min,val_max).move_to(*this); } //! Sharpen image \newinstance. CImg<T> get_sharpen(const float amplitude, const bool sharpen_type=false, const float edge=1, const float alpha=0, const float sigma=0) const { return (+*this).sharpen(amplitude,sharpen_type,edge,alpha,sigma); } //! Return image gradient. /** \param axes Axes considered for the gradient computation, as a C-string (e.g "xy"). \param scheme = Numerical scheme used for the gradient computation: - -1 = Backward finite differences - 0 = Centered finite differences - 1 = Forward finite differences - 2 = Using Sobel kernels - 3 = Using rotation invariant kernels - 4 = Using Deriche recusrsive filter. - 5 = Using Van Vliet recusrsive filter. **/ CImgList<Tfloat> get_gradient(const char *const axes=0, const int scheme=3) const { CImgList<Tfloat> grad(2,_width,_height,_depth,_spectrum); bool is_3d = false; if (axes) { for (unsigned int a = 0; axes[a]; ++a) { const char axis = cimg::lowercase(axes[a]); switch (axis) { case 'x' : case 'y' : break; case 'z' : is_3d = true; break; default : throw CImgArgumentException(_cimg_instance "get_gradient(): Invalid specified axis '%c'.", cimg_instance, axis); } } } else is_3d = (_depth>1); if (is_3d) { CImg<Tfloat>(_width,_height,_depth,_spectrum).move_to(grad); switch (scheme) { // 3D case -1 : { // Backward finite differences cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height*_depth>=(cimg_openmp_sizefactor)*1048576 && _spectrum>=2)) cimg_forC(*this,c) { const ulongT off = (ulongT)c*_width*_height*_depth; Tfloat *ptrd0 = grad[0]._data + off, *ptrd1 = grad[1]._data + off, *ptrd2 = grad[2]._data + off; CImg_3x3x3(I,Tfloat); cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = Iccc - Ipcc; *(ptrd1++) = Iccc - Icpc; *(ptrd2++) = Iccc - Iccp; } } } break; case 1 : { // Forward finite differences cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height*_depth>=(cimg_openmp_sizefactor)*1048576 && _spectrum>=2)) cimg_forC(*this,c) { const ulongT off = (ulongT)c*_width*_height*_depth; Tfloat *ptrd0 = grad[0]._data + off, *ptrd1 = grad[1]._data + off, *ptrd2 = grad[2]._data + off; CImg_2x2x2(I,Tfloat); cimg_for2x2x2(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = Incc - Iccc; *(ptrd1++) = Icnc - Iccc; *(ptrd2++) = Iccn - Iccc; } } } break; case 4 : { // Deriche filter with low standard variation grad[0] = get_deriche(0,1,'x'); grad[1] = get_deriche(0,1,'y'); grad[2] = get_deriche(0,1,'z'); } break; case 5 : { // Van Vliet filter with low standard variation grad[0] = get_vanvliet(0,1,'x'); grad[1] = get_vanvliet(0,1,'y'); grad[2] = get_vanvliet(0,1,'z'); } break; default : { // Central finite differences cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height*_depth>=(cimg_openmp_sizefactor)*1048576 && _spectrum>=2)) cimg_forC(*this,c) { const ulongT off = (ulongT)c*_width*_height*_depth; Tfloat *ptrd0 = grad[0]._data + off, *ptrd1 = grad[1]._data + off, *ptrd2 = grad[2]._data + off; CImg_3x3x3(I,Tfloat); cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = (Incc - Ipcc)/2; *(ptrd1++) = (Icnc - Icpc)/2; *(ptrd2++) = (Iccn - Iccp)/2; } } } } } else switch (scheme) { // 2D case -1 : { // Backward finite differences cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width*_height>=(cimg_openmp_sizefactor)*1048576 && _depth*_spectrum>=2)) cimg_forZC(*this,z,c) { const ulongT off = (ulongT)c*_width*_height*_depth + z*_width*_height; Tfloat *ptrd0 = grad[0]._data + off, *ptrd1 = grad[1]._data + off; CImg_3x3(I,Tfloat); cimg_for3x3(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = Icc - Ipc; *(ptrd1++) = Icc - Icp; } } } break; case 1 : { // Forward finite differences cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width*_height>=(cimg_openmp_sizefactor)*1048576 && _depth*_spectrum>=2)) cimg_forZC(*this,z,c) { const ulongT off = (ulongT)c*_width*_height*_depth + z*_width*_height; Tfloat *ptrd0 = grad[0]._data + off, *ptrd1 = grad[1]._data + off; CImg_2x2(I,Tfloat); cimg_for2x2(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = Inc - Icc; *(ptrd1++) = Icn - Icc; } } } break; case 2 : { // Sobel scheme cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width*_height>=(cimg_openmp_sizefactor)*1048576 && _depth*_spectrum>=2)) cimg_forZC(*this,z,c) { const ulongT off = (ulongT)c*_width*_height*_depth + z*_width*_height; Tfloat *ptrd0 = grad[0]._data + off, *ptrd1 = grad[1]._data + off; CImg_3x3(I,Tfloat); cimg_for3x3(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = -Ipp - 2*Ipc - Ipn + Inp + 2*Inc + Inn; *(ptrd1++) = -Ipp - 2*Icp - Inp + Ipn + 2*Icn + Inn; } } } break; case 3 : { // Rotation invariant kernel cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width*_height>=(cimg_openmp_sizefactor)*1048576 && _depth*_spectrum>=2)) cimg_forZC(*this,z,c) { const ulongT off = (ulongT)c*_width*_height*_depth + z*_width*_height; Tfloat *ptrd0 = grad[0]._data + off, *ptrd1 = grad[1]._data + off; CImg_3x3(I,Tfloat); const Tfloat a = (Tfloat)(0.25f*(2 - std::sqrt(2.f))), b = (Tfloat)(0.5f*(std::sqrt(2.f) - 1)); cimg_for3x3(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = -a*Ipp - b*Ipc - a*Ipn + a*Inp + b*Inc + a*Inn; *(ptrd1++) = -a*Ipp - b*Icp - a*Inp + a*Ipn + b*Icn + a*Inn; } } } break; case 4 : { // Van Vliet filter with low standard variation grad[0] = get_deriche(0,1,'x'); grad[1] = get_deriche(0,1,'y'); } break; case 5 : { // Deriche filter with low standard variation grad[0] = get_vanvliet(0,1,'x'); grad[1] = get_vanvliet(0,1,'y'); } break; default : { // Central finite differences cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width*_height>=(cimg_openmp_sizefactor)*1048576 && _depth*_spectrum>=2)) cimg_forZC(*this,z,c) { const ulongT off = (ulongT)c*_width*_height*_depth + z*_width*_height; Tfloat *ptrd0 = grad[0]._data + off, *ptrd1 = grad[1]._data + off; CImg_3x3(I,Tfloat); cimg_for3x3(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = (Inc - Ipc)/2; *(ptrd1++) = (Icn - Icp)/2; } } } } if (!axes) return grad; CImgList<Tfloat> res; for (unsigned int l = 0; axes[l]; ++l) { const char axis = cimg::lowercase(axes[l]); switch (axis) { case 'x' : res.insert(grad[0]); break; case 'y' : res.insert(grad[1]); break; case 'z' : res.insert(grad[2]); break; } } grad.assign(); return res; } //! Return image hessian. /** \param axes Axes considered for the hessian computation, as a C-string (e.g "xy"). **/ CImgList<Tfloat> get_hessian(const char *const axes=0) const { CImgList<Tfloat> res; const char *naxes = axes, *const def_axes2d = "xxxyyy", *const def_axes3d = "xxxyxzyyyzzz"; if (!axes) naxes = _depth>1?def_axes3d:def_axes2d; const unsigned int lmax = (unsigned int)std::strlen(naxes); if (lmax%2) throw CImgArgumentException(_cimg_instance "get_hessian(): Invalid specified axes '%s'.", cimg_instance, naxes); res.assign(lmax/2,_width,_height,_depth,_spectrum); if (!cimg::strcasecmp(naxes,def_axes3d)) { // 3D cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height*_depth>=(cimg_openmp_sizefactor)*1048576 && _spectrum>=2)) cimg_forC(*this,c) { const ulongT off = (ulongT)c*_width*_height*_depth; Tfloat *ptrd0 = res[0]._data + off, *ptrd1 = res[1]._data + off, *ptrd2 = res[2]._data + off, *ptrd3 = res[3]._data + off, *ptrd4 = res[4]._data + off, *ptrd5 = res[5]._data + off; CImg_3x3x3(I,Tfloat); cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = Ipcc + Incc - 2*Iccc; // Ixx *(ptrd1++) = (Ippc + Innc - Ipnc - Inpc)/4; // Ixy *(ptrd2++) = (Ipcp + Incn - Ipcn - Incp)/4; // Ixz *(ptrd3++) = Icpc + Icnc - 2*Iccc; // Iyy *(ptrd4++) = (Icpp + Icnn - Icpn - Icnp)/4; // Iyz *(ptrd5++) = Iccn + Iccp - 2*Iccc; // Izz } } } else if (!cimg::strcasecmp(naxes,def_axes2d)) { // 2D cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width*_height>=(cimg_openmp_sizefactor)*1048576 && _depth*_spectrum>=2)) cimg_forZC(*this,z,c) { const ulongT off = (ulongT)c*_width*_height*_depth + z*_width*_height; Tfloat *ptrd0 = res[0]._data + off, *ptrd1 = res[1]._data + off, *ptrd2 = res[2]._data + off; CImg_3x3(I,Tfloat); cimg_for3x3(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = Ipc + Inc - 2*Icc; // Ixx *(ptrd1++) = (Ipp + Inn - Ipn - Inp)/4; // Ixy *(ptrd2++) = Icp + Icn - 2*Icc; // Iyy } } } else for (unsigned int l = 0; l<lmax; ) { // Version with custom axes const unsigned int l2 = l/2; char axis1 = naxes[l++], axis2 = naxes[l++]; if (axis1>axis2) cimg::swap(axis1,axis2); bool valid_axis = false; if (axis1=='x' && axis2=='x') { // Ixx valid_axis = true; cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width*_height>=(cimg_openmp_sizefactor)*1048576 && _depth*_spectrum>=2)) cimg_forZC(*this,z,c) { Tfloat *ptrd = res[l2].data(0,0,z,c); CImg_3x3(I,Tfloat); cimg_for3x3(*this,x,y,z,c,I,Tfloat) *(ptrd++) = Ipc + Inc - 2*Icc; } } else if (axis1=='x' && axis2=='y') { // Ixy valid_axis = true; cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width*_height>=(cimg_openmp_sizefactor)*1048576 && _depth*_spectrum>=2)) cimg_forZC(*this,z,c) { Tfloat *ptrd = res[l2].data(0,0,z,c); CImg_3x3(I,Tfloat); cimg_for3x3(*this,x,y,z,c,I,Tfloat) *(ptrd++) = (Ipp + Inn - Ipn - Inp)/4; } } else if (axis1=='x' && axis2=='z') { // Ixz valid_axis = true; cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height*_depth>=(cimg_openmp_sizefactor)*1048576 && _spectrum>=2)) cimg_forC(*this,c) { Tfloat *ptrd = res[l2].data(0,0,0,c); CImg_3x3x3(I,Tfloat); cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) *(ptrd++) = (Ipcp + Incn - Ipcn - Incp)/4; } } else if (axis1=='y' && axis2=='y') { // Iyy valid_axis = true; cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width*_height>=(cimg_openmp_sizefactor)*1048576 && _depth*_spectrum>=2)) cimg_forZC(*this,z,c) { Tfloat *ptrd = res[l2].data(0,0,z,c); CImg_3x3(I,Tfloat); cimg_for3x3(*this,x,y,z,c,I,Tfloat) *(ptrd++) = Icp + Icn - 2*Icc; } } else if (axis1=='y' && axis2=='z') { // Iyz valid_axis = true; cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height*_depth>=(cimg_openmp_sizefactor)*1048576 && _spectrum>=2)) cimg_forC(*this,c) { Tfloat *ptrd = res[l2].data(0,0,0,c); CImg_3x3x3(I,Tfloat); cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) *(ptrd++) = (Icpp + Icnn - Icpn - Icnp)/4; } } else if (axis1=='z' && axis2=='z') { // Izz valid_axis = true; cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height*_depth>=(cimg_openmp_sizefactor)*1048576 && _spectrum>=2)) cimg_forC(*this,c) { Tfloat *ptrd = res[l2].data(0,0,0,c); CImg_3x3x3(I,Tfloat); cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) *(ptrd++) = Iccn + Iccp - 2*Iccc; } } else if (!valid_axis) throw CImgArgumentException(_cimg_instance "get_hessian(): Invalid specified axes '%s'.", cimg_instance, naxes); } return res; } //! Compute image Laplacian. CImg<T>& laplacian() { return get_laplacian().move_to(*this); } //! Compute image Laplacian \newinstance. CImg<Tfloat> get_laplacian() const { if (is_empty()) return CImg<Tfloat>(); CImg<Tfloat> res(_width,_height,_depth,_spectrum); if (_depth>1) { // 3D cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height*_depth>=(cimg_openmp_sizefactor)*1048576 && _spectrum>=2)) cimg_forC(*this,c) { Tfloat *ptrd = res.data(0,0,0,c); CImg_3x3x3(I,Tfloat); cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) *(ptrd++) = Incc + Ipcc + Icnc + Icpc + Iccn + Iccp - 6*Iccc; } } else if (_height>1) { // 2D cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height>=(cimg_openmp_sizefactor)*1048576 && _depth*_spectrum>=2)) cimg_forC(*this,c) { Tfloat *ptrd = res.data(0,0,0,c); CImg_3x3(I,Tfloat); cimg_for3x3(*this,x,y,0,c,I,Tfloat) *(ptrd++) = Inc + Ipc + Icn + Icp - 4*Icc; } } else { // 1D cimg_pragma_openmp(parallel for cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*1048576 && _height*_depth*_spectrum>=2)) cimg_forC(*this,c) { Tfloat *ptrd = res.data(0,0,0,c); CImg_3x3(I,Tfloat); cimg_for3x3(*this,x,y,0,c,I,Tfloat) *(ptrd++) = Inc + Ipc - 2*Icc; } } return res; } //! Compute the structure tensor field of an image. /** \param is_fwbw_scheme scheme. Can be <tt>{ false=centered | true=forward-backward }</tt> **/ CImg<T>& structure_tensors(const bool is_fwbw_scheme=false) { return get_structure_tensors(is_fwbw_scheme).move_to(*this); } //! Compute the structure tensor field of an image \newinstance. CImg<Tfloat> get_structure_tensors(const bool is_fwbw_scheme=false) const { if (is_empty()) return *this; CImg<Tfloat> res; if (_depth>1) { // 3D res.assign(_width,_height,_depth,6,0); if (!is_fwbw_scheme) { // Classical central finite differences cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height*_depth>=(cimg_openmp_sizefactor)*1048576 && _spectrum>=2)) cimg_forC(*this,c) { Tfloat *ptrd0 = res.data(0,0,0,0), *ptrd1 = res.data(0,0,0,1), *ptrd2 = res.data(0,0,0,2), *ptrd3 = res.data(0,0,0,3), *ptrd4 = res.data(0,0,0,4), *ptrd5 = res.data(0,0,0,5); CImg_3x3x3(I,Tfloat); cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) { const Tfloat ix = (Incc - Ipcc)/2, iy = (Icnc - Icpc)/2, iz = (Iccn - Iccp)/2; *(ptrd0++)+=ix*ix; *(ptrd1++)+=ix*iy; *(ptrd2++)+=ix*iz; *(ptrd3++)+=iy*iy; *(ptrd4++)+=iy*iz; *(ptrd5++)+=iz*iz; } } } else { // Forward/backward finite differences cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height*_depth>=(cimg_openmp_sizefactor)*1048576 && _spectrum>=2)) cimg_forC(*this,c) { Tfloat *ptrd0 = res.data(0,0,0,0), *ptrd1 = res.data(0,0,0,1), *ptrd2 = res.data(0,0,0,2), *ptrd3 = res.data(0,0,0,3), *ptrd4 = res.data(0,0,0,4), *ptrd5 = res.data(0,0,0,5); CImg_3x3x3(I,Tfloat); cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) { const Tfloat ixf = Incc - Iccc, ixb = Iccc - Ipcc, iyf = Icnc - Iccc, iyb = Iccc - Icpc, izf = Iccn - Iccc, izb = Iccc - Iccp; *(ptrd0++)+=(ixf*ixf + ixb*ixb)/2; *(ptrd1++)+=(ixf*iyf + ixf*iyb + ixb*iyf + ixb*iyb)/4; *(ptrd2++)+=(ixf*izf + ixf*izb + ixb*izf + ixb*izb)/4; *(ptrd3++)+=(iyf*iyf + iyb*iyb)/2; *(ptrd4++)+=(iyf*izf + iyf*izb + iyb*izf + iyb*izb)/4; *(ptrd5++)+=(izf*izf + izb*izb)/2; } } } } else { // 2D res.assign(_width,_height,_depth,3,0); if (!is_fwbw_scheme) { // Classical central finite differences cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height>=(cimg_openmp_sizefactor)*1048576 && _depth*_spectrum>=2)) cimg_forC(*this,c) { Tfloat *ptrd0 = res.data(0,0,0,0), *ptrd1 = res.data(0,0,0,1), *ptrd2 = res.data(0,0,0,2); CImg_3x3(I,Tfloat); cimg_for3x3(*this,x,y,0,c,I,Tfloat) { const Tfloat ix = (Inc - Ipc)/2, iy = (Icn - Icp)/2; *(ptrd0++)+=ix*ix; *(ptrd1++)+=ix*iy; *(ptrd2++)+=iy*iy; } } } else { // Forward/backward finite differences (version 2) cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height>=(cimg_openmp_sizefactor)*1048576 && _depth*_spectrum>=2)) cimg_forC(*this,c) { Tfloat *ptrd0 = res.data(0,0,0,0), *ptrd1 = res.data(0,0,0,1), *ptrd2 = res.data(0,0,0,2); CImg_3x3(I,Tfloat); cimg_for3x3(*this,x,y,0,c,I,Tfloat) { const Tfloat ixf = Inc - Icc, ixb = Icc - Ipc, iyf = Icn - Icc, iyb = Icc - Icp; *(ptrd0++)+=(ixf*ixf + ixb*ixb)/2; *(ptrd1++)+=(ixf*iyf + ixf*iyb + ixb*iyf + ixb*iyb)/4; *(ptrd2++)+=(iyf*iyf + iyb*iyb)/2; } } } } return res; } //! Compute field of diffusion tensors for edge-preserving smoothing. /** \param sharpness Sharpness \param anisotropy Anisotropy \param alpha Standard deviation of the gradient blur. \param sigma Standard deviation of the structure tensor blur. \param is_sqrt Tells if the square root of the tensor field is computed instead. **/ CImg<T>& diffusion_tensors(const float sharpness=0.7f, const float anisotropy=0.6f, const float alpha=0.6f, const float sigma=1.1f, const bool is_sqrt=false) { CImg<Tfloat> res; const float nsharpness = std::max(sharpness,1e-5f), power1 = (is_sqrt?0.5f:1)*nsharpness, power2 = power1/(1e-7f + 1 - anisotropy); blur(alpha).normalize(0,(T)255); if (_depth>1) { // 3D get_structure_tensors().move_to(res).blur(sigma); cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height*_depth>=(cimg_openmp_sizefactor)*256)) cimg_forYZ(*this,y,z) { Tfloat *ptrd0 = res.data(0,y,z,0), *ptrd1 = res.data(0,y,z,1), *ptrd2 = res.data(0,y,z,2), *ptrd3 = res.data(0,y,z,3), *ptrd4 = res.data(0,y,z,4), *ptrd5 = res.data(0,y,z,5); CImg<floatT> val(3), vec(3,3); cimg_forX(*this,x) { res.get_tensor_at(x,y,z).symmetric_eigen(val,vec); const float _l1 = val[2], _l2 = val[1], _l3 = val[0], l1 = _l1>0?_l1:0, l2 = _l2>0?_l2:0, l3 = _l3>0?_l3:0, ux = vec(0,0), uy = vec(0,1), uz = vec(0,2), vx = vec(1,0), vy = vec(1,1), vz = vec(1,2), wx = vec(2,0), wy = vec(2,1), wz = vec(2,2), n1 = (float)std::pow(1 + l1 + l2 + l3,-power1), n2 = (float)std::pow(1 + l1 + l2 + l3,-power2); *(ptrd0++) = n1*(ux*ux + vx*vx) + n2*wx*wx; *(ptrd1++) = n1*(ux*uy + vx*vy) + n2*wx*wy; *(ptrd2++) = n1*(ux*uz + vx*vz) + n2*wx*wz; *(ptrd3++) = n1*(uy*uy + vy*vy) + n2*wy*wy; *(ptrd4++) = n1*(uy*uz + vy*vz) + n2*wy*wz; *(ptrd5++) = n1*(uz*uz + vz*vz) + n2*wz*wz; } } } else { // for 2D images get_structure_tensors().move_to(res).blur(sigma); cimg_pragma_openmp(parallel for cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 && _height>=(cimg_openmp_sizefactor)*256)) cimg_forY(*this,y) { Tfloat *ptrd0 = res.data(0,y,0,0), *ptrd1 = res.data(0,y,0,1), *ptrd2 = res.data(0,y,0,2); CImg<floatT> val(2), vec(2,2); cimg_forX(*this,x) { res.get_tensor_at(x,y).symmetric_eigen(val,vec); const float _l1 = val[1], _l2 = val[0], l1 = _l1>0?_l1:0, l2 = _l2>0?_l2:0, ux = vec(1,0), uy = vec(1,1), vx = vec(0,0), vy = vec(0,1), n1 = (float)std::pow(1 + l1 + l2,-power1), n2 = (float)std::pow(1 + l1 + l2,-power2); *(ptrd0++) = n1*ux*ux + n2*vx*vx; *(ptrd1++) = n1*ux*uy + n2*vx*vy; *(ptrd2++) = n1*uy*uy + n2*vy*vy; } } } return res.move_to(*this); } //! Compute field of diffusion tensors for edge-preserving smoothing \newinstance. CImg<Tfloat> get_diffusion_tensors(const float sharpness=0.7f, const float anisotropy=0.6f, const float alpha=0.6f, const float sigma=1.1f, const bool is_sqrt=false) const { return CImg<Tfloat>(*this,false).diffusion_tensors(sharpness,anisotropy,alpha,sigma,is_sqrt); } //! Estimate displacement field between two images. /** \param source Reference image. \param smoothness Smoothness of estimated displacement field. \param precision Precision required for algorithm convergence. \param nb_scales Number of scales used to estimate the displacement field. \param iteration_max Maximum number of iterations allowed for one scale. \param is_backward If false, match I2(X + U(X)) = I1(X), else match I2(X) = I1(X - U(X)). \param guide Image used as the initial correspondence estimate for the algorithm. 'guide' may have a last channel with boolean values (0=false | other=true) that tells for each pixel if its correspondence vector is constrained to its initial value (constraint mask). **/ CImg<T>& displacement(const CImg<T>& source, const float smoothness=0.1f, const float precision=5.f, const unsigned int nb_scales=0, const unsigned int iteration_max=10000, const bool is_backward=false, const CImg<floatT>& guide=CImg<floatT>::const_empty()) { return get_displacement(source,smoothness,precision,nb_scales,iteration_max,is_backward,guide). move_to(*this); } //! Estimate displacement field between two images \newinstance. CImg<floatT> get_displacement(const CImg<T>& source, const float smoothness=0.1f, const float precision=5.f, const unsigned int nb_scales=0, const unsigned int iteration_max=10000, const bool is_backward=false, const CImg<floatT>& guide=CImg<floatT>::const_empty()) const { if (is_empty() || !source) return +*this; if (!is_sameXYZC(source)) throw CImgArgumentException(_cimg_instance "displacement(): Instance and source image (%u,%u,%u,%u,%p) have " "different dimensions.", cimg_instance, source._width,source._height,source._depth,source._spectrum,source._data); if (precision<0) throw CImgArgumentException(_cimg_instance "displacement(): Invalid specified precision %g " "(should be >=0)", cimg_instance, precision); const bool is_3d = source._depth>1; const unsigned int constraint = is_3d?3:2; if (guide && (guide._width!=_width || guide._height!=_height || guide._depth!=_depth || guide._spectrum<constraint)) throw CImgArgumentException(_cimg_instance "displacement(): Specified guide (%u,%u,%u,%u,%p) " "has invalid dimensions.", cimg_instance, guide._width,guide._height,guide._depth,guide._spectrum,guide._data); const unsigned int mins = is_3d?cimg::min(_width,_height,_depth):std::min(_width,_height), _nb_scales = nb_scales>0?nb_scales: (unsigned int)cimg::round(std::log(mins/8.)/std::log(1.5),1,1); const float _precision = (float)std::pow(10.,-(double)precision); float sm, sM = source.max_min(sm), tm, tM = max_min(tm); const float sdelta = sm==sM?1:(sM - sm), tdelta = tm==tM?1:(tM - tm); CImg<floatT> U, V; floatT bound = 0; for (int scale = (int)_nb_scales - 1; scale>=0; --scale) { const float factor = (float)std::pow(1.5,(double)scale); const unsigned int _sw = (unsigned int)(_width/factor), sw = _sw?_sw:1, _sh = (unsigned int)(_height/factor), sh = _sh?_sh:1, _sd = (unsigned int)(_depth/factor), sd = _sd?_sd:1; if (sw<5 && sh<5 && (!is_3d || sd<5)) continue; // Skip too small scales const CImg<Tfloat> I1 = (source.get_resize(sw,sh,sd,-100,2)-=sm)/=sdelta, I2 = (get_resize(I1,2)-=tm)/=tdelta; if (guide._spectrum>constraint) guide.get_resize(I2._width,I2._height,I2._depth,-100,1).move_to(V); if (U) (U*=1.5f).resize(I2._width,I2._height,I2._depth,-100,3); else { if (guide) guide.get_shared_channels(0,is_3d?2:1).get_resize(I2._width,I2._height,I2._depth,-100,2).move_to(U); else U.assign(I2._width,I2._height,I2._depth,is_3d?3:2,0); } float dt = 2, energy = cimg::type<float>::max(); const CImgList<Tfloat> dI = is_backward?I1.get_gradient():I2.get_gradient(); cimg_abort_init; for (unsigned int iteration = 0; iteration<iteration_max; ++iteration) { cimg_abort_test; float _energy = 0; if (is_3d) { // 3D version if (smoothness>=0) // Isotropic regularization cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_height*_depth>=(cimg_openmp_sizefactor)*8 && _width>=(cimg_openmp_sizefactor)*16) reduction(+:_energy)) cimg_forYZ(U,y,z) { const int _p1y = y?y - 1:0, _n1y = y<U.height() - 1?y + 1:y, _p1z = z?z - 1:0, _n1z = z<U.depth() - 1?z + 1:z; cimg_for3X(U,x) { const float X = is_backward?x - U(x,y,z,0):x + U(x,y,z,0), Y = is_backward?y - U(x,y,z,1):y + U(x,y,z,1), Z = is_backward?z - U(x,y,z,2):z + U(x,y,z,2); float delta_I = 0, _energy_regul = 0; if (is_backward) cimg_forC(I2,c) delta_I+=(float)(I1._linear_atXYZ(X,Y,Z,c) - I2(x,y,z,c)); else cimg_forC(I2,c) delta_I+=(float)(I1(x,y,z,c) - I2._linear_atXYZ(X,Y,Z,c)); cimg_forC(U,c) { const float Ux = 0.5f*(U(_n1x,y,z,c) - U(_p1x,y,z,c)), Uy = 0.5f*(U(x,_n1y,z,c) - U(x,_p1y,z,c)), Uz = 0.5f*(U(x,y,_n1z,c) - U(x,y,_p1z,c)), Uxx = U(_n1x,y,z,c) + U(_p1x,y,z,c), Uyy = U(x,_n1y,z,c) + U(x,_p1y,z,c), Uzz = U(x,y,_n1z,c) + U(x,y,_p1z,c); U(x,y,z,c) = (float)(U(x,y,z,c) + dt*(delta_I*dI[c]._linear_atXYZ(X,Y,Z) + smoothness* ( Uxx + Uyy + Uzz)))/(1 + 6*smoothness*dt); _energy_regul+=Ux*Ux + Uy*Uy + Uz*Uz; } if (is_backward) { // Constraint displacement vectors to stay in image if (U(x,y,z,0)>x) U(x,y,z,0) = (float)x; if (U(x,y,z,1)>y) U(x,y,z,1) = (float)y; if (U(x,y,z,2)>z) U(x,y,z,2) = (float)z; bound = (float)x - _width; if (U(x,y,z,0)<=bound) U(x,y,z,0) = bound; bound = (float)y - _height; if (U(x,y,z,1)<=bound) U(x,y,z,1) = bound; bound = (float)z - _depth; if (U(x,y,z,2)<=bound) U(x,y,z,2) = bound; } else { if (U(x,y,z,0)<-x) U(x,y,z,0) = -(float)x; if (U(x,y,z,1)<-y) U(x,y,z,1) = -(float)y; if (U(x,y,z,2)<-z) U(x,y,z,2) = -(float)z; bound = (float)_width - x; if (U(x,y,z,0)>=bound) U(x,y,z,0) = bound; bound = (float)_height - y; if (U(x,y,z,1)>=bound) U(x,y,z,1) = bound; bound = (float)_depth - z; if (U(x,y,z,2)>=bound) U(x,y,z,2) = bound; } _energy+=delta_I*delta_I + smoothness*_energy_regul; } if (V) cimg_forXYZ(V,_x,_y,_z) if (V(_x,_y,_z,3)) { // Apply constraints U(_x,_y,_z,0) = V(_x,_y,_z,0)/factor; U(_x,_y,_z,1) = V(_x,_y,_z,1)/factor; U(_x,_y,_z,2) = V(_x,_y,_z,2)/factor; } } else { // Anisotropic regularization const float nsmoothness = -smoothness; cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_height*_depth>=(cimg_openmp_sizefactor)*8 && _width>=(cimg_openmp_sizefactor)*16) reduction(+:_energy)) cimg_forYZ(U,y,z) { const int _p1y = y?y - 1:0, _n1y = y<U.height() - 1?y + 1:y, _p1z = z?z - 1:0, _n1z = z<U.depth() - 1?z + 1:z; cimg_for3X(U,x) { const float X = is_backward?x - U(x,y,z,0):x + U(x,y,z,0), Y = is_backward?y - U(x,y,z,1):y + U(x,y,z,1), Z = is_backward?z - U(x,y,z,2):z + U(x,y,z,2); float delta_I = 0, _energy_regul = 0; if (is_backward) cimg_forC(I2,c) delta_I+=(float)(I1._linear_atXYZ(X,Y,Z,c) - I2(x,y,z,c)); else cimg_forC(I2,c) delta_I+=(float)(I1(x,y,z,c) - I2._linear_atXYZ(X,Y,Z,c)); cimg_forC(U,c) { const float Ux = 0.5f*(U(_n1x,y,z,c) - U(_p1x,y,z,c)), Uy = 0.5f*(U(x,_n1y,z,c) - U(x,_p1y,z,c)), Uz = 0.5f*(U(x,y,_n1z,c) - U(x,y,_p1z,c)), N2 = Ux*Ux + Uy*Uy + Uz*Uz, N = std::sqrt(N2), N3 = 1e-5f + N2*N, coef_a = (1 - Ux*Ux/N2)/N, coef_b = -2*Ux*Uy/N3, coef_c = -2*Ux*Uz/N3, coef_d = (1 - Uy*Uy/N2)/N, coef_e = -2*Uy*Uz/N3, coef_f = (1 - Uz*Uz/N2)/N, Uxx = U(_n1x,y,z,c) + U(_p1x,y,z,c), Uyy = U(x,_n1y,z,c) + U(x,_p1y,z,c), Uzz = U(x,y,_n1z,c) + U(x,y,_p1z,c), Uxy = 0.25f*(U(_n1x,_n1y,z,c) + U(_p1x,_p1y,z,c) - U(_n1x,_p1y,z,c) - U(_n1x,_p1y,z,c)), Uxz = 0.25f*(U(_n1x,y,_n1z,c) + U(_p1x,y,_p1z,c) - U(_n1x,y,_p1z,c) - U(_n1x,y,_p1z,c)), Uyz = 0.25f*(U(x,_n1y,_n1z,c) + U(x,_p1y,_p1z,c) - U(x,_n1y,_p1z,c) - U(x,_n1y,_p1z,c)); U(x,y,z,c) = (float)(U(x,y,z,c) + dt*(delta_I*dI[c]._linear_atXYZ(X,Y,Z) + nsmoothness* ( coef_a*Uxx + coef_b*Uxy + coef_c*Uxz + coef_d*Uyy + coef_e*Uyz + coef_f*Uzz )) )/(1 + 2*(coef_a + coef_d + coef_f)*nsmoothness*dt); _energy_regul+=N; } if (is_backward) { // Constraint displacement vectors to stay in image if (U(x,y,z,0)>x) U(x,y,z,0) = (float)x; if (U(x,y,z,1)>y) U(x,y,z,1) = (float)y; if (U(x,y,z,2)>z) U(x,y,z,2) = (float)z; bound = (float)x - _width; if (U(x,y,z,0)<=bound) U(x,y,z,0) = bound; bound = (float)y - _height; if (U(x,y,z,1)<=bound) U(x,y,z,1) = bound; bound = (float)z - _depth; if (U(x,y,z,2)<=bound) U(x,y,z,2) = bound; } else { if (U(x,y,z,0)<-x) U(x,y,z,0) = -(float)x; if (U(x,y,z,1)<-y) U(x,y,z,1) = -(float)y; if (U(x,y,z,2)<-z) U(x,y,z,2) = -(float)z; bound = (float)_width - x; if (U(x,y,z,0)>=bound) U(x,y,z,0) = bound; bound = (float)_height - y; if (U(x,y,z,1)>=bound) U(x,y,z,1) = bound; bound = (float)_depth - z; if (U(x,y,z,2)>=bound) U(x,y,z,2) = bound; } _energy+=delta_I*delta_I + nsmoothness*_energy_regul; } if (V) cimg_forXYZ(V,_x,_y,_z) if (V(_x,_y,_z,3)) { // Apply constraints U(_x,_y,_z,0) = V(_x,_y,_z,0)/factor; U(_x,_y,_z,1) = V(_x,_y,_z,1)/factor; U(_x,_y,_z,2) = V(_x,_y,_z,2)/factor; } } } } else { // 2D version if (smoothness>=0) // Isotropic regularization cimg_pragma_openmp(parallel for cimg_openmp_if(_height>=(cimg_openmp_sizefactor)*8 && _width>=(cimg_openmp_sizefactor)*16) reduction(+:_energy)) cimg_forY(U,y) { const int _p1y = y?y - 1:0, _n1y = y<U.height() - 1?y + 1:y; cimg_for3X(U,x) { const float X = is_backward?x - U(x,y,0):x + U(x,y,0), Y = is_backward?y - U(x,y,1):y + U(x,y,1); float delta_I = 0, _energy_regul = 0; if (is_backward) cimg_forC(I2,c) delta_I+=(float)(I1._linear_atXY(X,Y,c) - I2(x,y,c)); else cimg_forC(I2,c) delta_I+=(float)(I1(x,y,c) - I2._linear_atXY(X,Y,c)); cimg_forC(U,c) { const float Ux = 0.5f*(U(_n1x,y,c) - U(_p1x,y,c)), Uy = 0.5f*(U(x,_n1y,c) - U(x,_p1y,c)), Uxx = U(_n1x,y,c) + U(_p1x,y,c), Uyy = U(x,_n1y,c) + U(x,_p1y,c); U(x,y,c) = (float)(U(x,y,c) + dt*(delta_I*dI[c]._linear_atXY(X,Y) + smoothness*( Uxx + Uyy )))/(1 + 4*smoothness*dt); _energy_regul+=Ux*Ux + Uy*Uy; } if (is_backward) { // Constraint displacement vectors to stay in image if (U(x,y,0)>x) U(x,y,0) = (float)x; if (U(x,y,1)>y) U(x,y,1) = (float)y; bound = (float)x - _width; if (U(x,y,0)<=bound) U(x,y,0) = bound; bound = (float)y - _height; if (U(x,y,1)<=bound) U(x,y,1) = bound; } else { if (U(x,y,0)<-x) U(x,y,0) = -(float)x; if (U(x,y,1)<-y) U(x,y,1) = -(float)y; bound = (float)_width - x; if (U(x,y,0)>=bound) U(x,y,0) = bound; bound = (float)_height - y; if (U(x,y,1)>=bound) U(x,y,1) = bound; } _energy+=delta_I*delta_I + smoothness*_energy_regul; } if (V) cimg_forXY(V,_x,_y) if (V(_x,_y,2)) { // Apply constraints U(_x,_y,0) = V(_x,_y,0)/factor; U(_x,_y,1) = V(_x,_y,1)/factor; } } else { // Anisotropic regularization const float nsmoothness = -smoothness; cimg_pragma_openmp(parallel for cimg_openmp_if(_height>=(cimg_openmp_sizefactor)*8 && _width>=(cimg_openmp_sizefactor)*16) reduction(+:_energy)) cimg_forY(U,y) { const int _p1y = y?y - 1:0, _n1y = y<U.height() - 1?y + 1:y; cimg_for3X(U,x) { const float X = is_backward?x - U(x,y,0):x + U(x,y,0), Y = is_backward?y - U(x,y,1):y + U(x,y,1); float delta_I = 0, _energy_regul = 0; if (is_backward) cimg_forC(I2,c) delta_I+=(float)(I1._linear_atXY(X,Y,c) - I2(x,y,c)); else cimg_forC(I2,c) delta_I+=(float)(I1(x,y,c) - I2._linear_atXY(X,Y,c)); cimg_forC(U,c) { const float Ux = 0.5f*(U(_n1x,y,c) - U(_p1x,y,c)), Uy = 0.5f*(U(x,_n1y,c) - U(x,_p1y,c)), N2 = Ux*Ux + Uy*Uy, N = std::sqrt(N2), N3 = 1e-5f + N2*N, coef_a = Uy*Uy/N3, coef_b = -2*Ux*Uy/N3, coef_c = Ux*Ux/N3, Uxx = U(_n1x,y,c) + U(_p1x,y,c), Uyy = U(x,_n1y,c) + U(x,_p1y,c), Uxy = 0.25f*(U(_n1x,_n1y,c) + U(_p1x,_p1y,c) - U(_n1x,_p1y,c) - U(_n1x,_p1y,c)); U(x,y,c) = (float)(U(x,y,c) + dt*(delta_I*dI[c]._linear_atXY(X,Y) + nsmoothness*( coef_a*Uxx + coef_b*Uxy + coef_c*Uyy )))/ (1 + 2*(coef_a + coef_c)*nsmoothness*dt); _energy_regul+=N; } if (is_backward) { // Constraint displacement vectors to stay in image if (U(x,y,0)>x) U(x,y,0) = (float)x; if (U(x,y,1)>y) U(x,y,1) = (float)y; bound = (float)x - _width; if (U(x,y,0)<=bound) U(x,y,0) = bound; bound = (float)y - _height; if (U(x,y,1)<=bound) U(x,y,1) = bound; } else { if (U(x,y,0)<-x) U(x,y,0) = -(float)x; if (U(x,y,1)<-y) U(x,y,1) = -(float)y; bound = (float)_width - x; if (U(x,y,0)>=bound) U(x,y,0) = bound; bound = (float)_height - y; if (U(x,y,1)>=bound) U(x,y,1) = bound; } _energy+=delta_I*delta_I + nsmoothness*_energy_regul; } if (V) cimg_forXY(V,_x,_y) if (V(_x,_y,2)) { // Apply constraints U(_x,_y,0) = V(_x,_y,0)/factor; U(_x,_y,1) = V(_x,_y,1)/factor; } } } } const float d_energy = (_energy - energy)/(sw*sh*sd); if (d_energy<=0 && -d_energy<_precision) break; if (d_energy>0) dt*=0.5f; energy = _energy; } } return U; } //! Compute correspondence map between two images, using a patch-matching algorithm. /** \param patch_image The image containing the reference patches to match with the instance image. \param patch_width Width of the patch used for matching. \param patch_height Height of the patch used for matching. \param patch_depth Depth of the patch used for matching. \param nb_iterations Number of patch-match iterations. \param nb_randoms Number of randomization attempts (per pixel). \param occ_penalization Penalization factor in score related patch occurrences. \param guide Image used as the initial correspondence estimate for the algorithm. 'guide' may have a last channel with boolean values (0=false | other=true) that tells for each pixel if its correspondence vector is constrained to its initial value (constraint mask). \param[out] matching_score Returned as the image of matching scores. **/ template<typename t1, typename t2> CImg<T>& matchpatch(const CImg<T>& patch_image, const unsigned int patch_width, const unsigned int patch_height, const unsigned int patch_depth, const unsigned int nb_iterations, const unsigned int nb_randoms, const float occ_penalization, const CImg<t1> &guide, CImg<t2> &matching_score) { return get_matchpatch(patch_image,patch_width,patch_height,patch_depth, nb_iterations,nb_randoms,occ_penalization,guide,matching_score).move_to(*this); } //! Compute correspondence map between two images, using the patch-match algorithm \newinstance. template<typename t1, typename t2> CImg<intT> get_matchpatch(const CImg<T>& patch_image, const unsigned int patch_width, const unsigned int patch_height, const unsigned int patch_depth, const unsigned int nb_iterations, const unsigned int nb_randoms, const float occ_penalization, const CImg<t1> &guide, CImg<t2> &matching_score) const { return _matchpatch(patch_image,patch_width,patch_height,patch_depth, nb_iterations,nb_randoms,occ_penalization, guide,true,matching_score); } //! Compute correspondence map between two images, using the patch-match algorithm \overloading. template<typename t> CImg<T>& matchpatch(const CImg<T>& patch_image, const unsigned int patch_width, const unsigned int patch_height, const unsigned int patch_depth, const unsigned int nb_iterations=5, const unsigned int nb_randoms=5, const float occ_penalization=0, const CImg<t> &guide=CImg<t>::const_empty()) { return get_matchpatch(patch_image,patch_width,patch_height,patch_depth, nb_iterations,nb_randoms,occ_penalization,guide).move_to(*this); } //! Compute correspondence map between two images, using the patch-match algorithm \overloading. template<typename t> CImg<intT> get_matchpatch(const CImg<T>& patch_image, const unsigned int patch_width, const unsigned int patch_height, const unsigned int patch_depth, const unsigned int nb_iterations=5, const unsigned int nb_randoms=5, const float occ_penalization=0, const CImg<t> &guide=CImg<t>::const_empty()) const { CImg<T> matching_score; return _matchpatch(patch_image,patch_width,patch_height,patch_depth, nb_iterations,nb_randoms,occ_penalization,guide,false,matching_score); } template<typename t1, typename t2> CImg<intT> _matchpatch(const CImg<T>& patch_image, const unsigned int patch_width, const unsigned int patch_height, const unsigned int patch_depth, const unsigned int nb_iterations, const unsigned int nb_randoms, const float occ_penalization, const CImg<t1> &guide, const bool is_matching_score, CImg<t2> &matching_score) const { if (is_empty()) return CImg<intT>::const_empty(); if (patch_image._spectrum!=_spectrum) throw CImgArgumentException(_cimg_instance "matchpatch(): Instance image and specified patch image (%u,%u,%u,%u,%p) " "have different spectrums.", cimg_instance, patch_image._width,patch_image._height,patch_image._depth,patch_image._spectrum, patch_image._data); if (patch_width>_width || patch_height>_height || patch_depth>_depth) throw CImgArgumentException(_cimg_instance "matchpatch(): Specified patch size %ux%ux%u is bigger than the dimensions " "of the instance image.", cimg_instance,patch_width,patch_height,patch_depth); if (patch_width>patch_image._width || patch_height>patch_image._height || patch_depth>patch_image._depth) throw CImgArgumentException(_cimg_instance "matchpatch(): Specified patch size %ux%ux%u is bigger than the dimensions " "of the patch image image (%u,%u,%u,%u,%p).", cimg_instance,patch_width,patch_height,patch_depth, patch_image._width,patch_image._height,patch_image._depth,patch_image._spectrum, patch_image._data); const unsigned int _constraint = patch_image._depth>1?3:2, constraint = guide._spectrum>_constraint?_constraint:0; if (guide && (guide._width!=_width || guide._height!=_height || guide._depth!=_depth || guide._spectrum<_constraint)) throw CImgArgumentException(_cimg_instance "matchpatch(): Specified guide (%u,%u,%u,%u,%p) has invalid dimensions " "considering instance and patch image (%u,%u,%u,%u,%p).", cimg_instance, guide._width,guide._height,guide._depth,guide._spectrum,guide._data, patch_image._width,patch_image._height,patch_image._depth,patch_image._spectrum, patch_image._data); CImg<intT> a_map(_width,_height,_depth,patch_image._depth>1?3:2); CImg<ucharT> is_updated(_width,_height,_depth,1,3); CImg<floatT> score(_width,_height,_depth); CImg<uintT> occ, loop_order; ulongT rng = (cimg::_rand(),cimg::rng()); if (occ_penalization!=0) { occ.assign(patch_image._width,patch_image._height,patch_image._depth,1,0); loop_order.assign(_width,_height,_depth,_depth>1?3:2); cimg_forXYZ(loop_order,x,y,z) { loop_order(x,y,z,0) = x; loop_order(x,y,z,1) = y; if (loop_order._spectrum>2) loop_order(x,y,z,2) = z; } cimg_forXYZ(loop_order,x,y,z) { // Randomize loop order in case of constraints on patch occurrence const unsigned int X = (unsigned int)cimg::round(cimg::rand(loop_order._width - 1.,&rng)), Y = (unsigned int)cimg::round(cimg::rand(loop_order._height - 1.,&rng)), Z = loop_order._depth>1?(unsigned int)cimg::round(cimg::rand(loop_order._depth - 1.,&rng)):0U; cimg::swap(loop_order(x,y,z,0),loop_order(X,Y,Z,0)); cimg::swap(loop_order(x,y,z,1),loop_order(X,Y,Z,1)); if (loop_order._spectrum>2) cimg::swap(loop_order(x,y,z,2),loop_order(X,Y,Z,2)); } } const int psizew = (int)patch_width, psizew1 = psizew/2, psizew2 = psizew - psizew1 - 1, psizeh = (int)patch_height, psizeh1 = psizeh/2, psizeh2 = psizeh - psizeh1 - 1, psized = (int)patch_depth, psized1 = psized/2, psized2 = psized - psized1 - 1; // Interleave image buffers to speed up patch comparison (cache-friendly). CImg<T> in_this = get_permute_axes("cxyz"); in_this._width = _width*_spectrum; in_this._height = _height; in_this._depth = _depth; in_this._spectrum = 1; CImg<T> in_patch = patch_image.get_permute_axes("cxyz"); in_patch._width = patch_image._width*patch_image._spectrum; in_patch._height = patch_image._height; in_patch._depth = patch_image._depth; in_patch._spectrum = 1; if (_depth>1 || patch_image._depth>1) { // 3D version // Initialize correspondence map. if (guide) cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if_size(_width,64)) cimg_forXYZ(*this,x,y,z) { // User-defined initialization const int cx1 = x<=psizew1?x:(x<width() - psizew2?psizew1:psizew + x - width()), cx2 = psizew - cx1 - 1, cy1 = y<=psizeh1?y:(y<height() - psizeh2?psizeh1:psizeh + y - height()), cy2 = psizeh - cy1 - 1, cz1 = z<=psized1?z:(z<depth() - psized2?psized1:psized + z - depth()), cz2 = psized - cz1 - 1, u = cimg::cut((int)guide(x,y,z,0),cx1,patch_image.width() - 1 - cx2), v = cimg::cut((int)guide(x,y,z,1),cy1,patch_image.height() - 1 - cy2), w = cimg::cut((int)guide(x,y,z,2),cz1,patch_image.depth() - 1 - cz2); a_map(x,y,z,0) = u; a_map(x,y,z,1) = v; a_map(x,y,z,2) = w; score(x,y,z) = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,patch_depth,_spectrum, x - cx1,y - cy1,z - cz1, u - cx1,v - cy1,w - cz1, u,v,w,0,cimg::type<float>::inf()); } else cimg_pragma_openmp(parallel cimg_openmp_if_size(_width,64)) { ulongT _rng = (cimg::_rand(),cimg::rng()); #if cimg_use_openmp!=0 _rng+=omp_get_thread_num(); #endif cimg_pragma_openmp(for cimg_openmp_collapse(2)) cimg_forXYZ(*this,x,y,z) { // Random initialization const int cx1 = x<=psizew1?x:(x<width() - psizew2?psizew1:psizew + x - width()), cx2 = psizew - cx1 - 1, cy1 = y<=psizeh1?y:(y<height() - psizeh2?psizeh1:psizeh + y - height()), cy2 = psizeh - cy1 - 1, cz1 = z<=psized1?z:(z<depth() - psized2?psized1:psized + z - depth()), cz2 = psized - cz1 - 1, u = (int)cimg::round(cimg::rand(cx1,patch_image.width() - 1 - cx2,&_rng)), v = (int)cimg::round(cimg::rand(cy1,patch_image.height() - 1 - cy2,&_rng)), w = (int)cimg::round(cimg::rand(cz1,patch_image.depth() - 1 - cz2,&_rng)); a_map(x,y,z,0) = u; a_map(x,y,z,1) = v; a_map(x,y,z,2) = w; score(x,y,z) = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,patch_depth,_spectrum, x - cx1,y - cy1,z - cz1, u - cx1,v - cy1,w - cz1, u,v,w,0,cimg::type<float>::inf()); } cimg::srand(_rng); } // Start iteration loop. cimg_abort_init; for (unsigned int iter = 0; iter<nb_iterations; ++iter) { cimg_abort_test; const bool is_odd = iter%2; const unsigned int cmask = is_odd?1:2, nmask = 3 - cmask; if (iter) occ.fill(0); cimg_pragma_openmp(parallel cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*64 && iter<nb_iterations-2)) { ulongT _rng = (cimg::_rand(),cimg::rng()); #if cimg_use_openmp!=0 _rng+=omp_get_thread_num(); #endif cimg_pragma_openmp(for cimg_openmp_collapse(2)) cimg_forXYZ(*this,X,Y,Z) { const int _x = is_odd?width() - 1 - X:X, _y = is_odd?height() - 1 - Y:Y, _z = is_odd?depth() - 1 - Z:Z; int x, y, z; if (occ_penalization) { x = loop_order(_x,_y,_z,0); y = loop_order(_x,_y,_z,1); if (loop_order._spectrum>2) z = loop_order(_x,_y,_z,2); else z = _z; } else { x = _x; y = _y; z = _z; } if (score(x,y,z)<=1e-5 || (constraint && guide(x,y,z,constraint)!=0)) continue; const int cx1 = x<=psizew1?x:(x<width() - psizew2?psizew1:psizew + x - width()), cx2 = psizew - cx1 - 1, cy1 = y<=psizeh1?y:(y<height() - psizeh2?psizeh1:psizeh + y - height()), cy2 = psizeh - cy1 - 1, cz1 = z<=psized1?z:(z<depth() - psized2?psized1:psized + z - depth()), cz2 = psized - cz1 - 1, xp = x - cx1, yp = y - cy1, zp = z - cz1; int best_u = a_map(x,y,z,0), best_v = a_map(x,y,z,1), best_w = a_map(x,y,z,2), u, v, w; const float best_score0 = score(x,y,z); float best_score = best_score0, s; // Propagation. if (x>0 && (is_updated(x - 1,y,z)&cmask)) { // Compare with left neighbor u = a_map(x - 1,y,z,0); v = a_map(x - 1,y,z,1); w = a_map(x - 1,y,z,2); if (u>=cx1 - 1 && u<patch_image.width() - 1 - cx2 && v>=cy1 && v<patch_image.height() - cy2 && w>=cz1 && w<patch_image.depth() - cz2) { s = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,patch_depth,_spectrum, xp,yp,zp,u + 1 - cx1,v - cy1,w - cz1, u,v,w,occ_penalization,best_score); if (s<best_score) { best_u = u + 1; best_v = v; best_w = w; best_score = s; } } } if (y>0 && (is_updated(x,y - 1,z)&cmask)) { // Compare with up neighbor u = a_map(x,y - 1,z,0); v = a_map(x,y - 1,z,1); w = a_map(x,y - 1,z,2); if (u>=cx1 && u<patch_image.width() - cx2 && v>=cy1 - 1 && v<patch_image.height() - 1 - cy2 && w>=cz1 && w<patch_image.depth() - cz2) { s = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,patch_depth,_spectrum, xp,yp,zp,u - cx1,v + 1 - cy1,w - cz1, u,v,w,occ_penalization,best_score); if (s<best_score) { best_u = u; best_v = v + 1; best_w = w; best_score = s; } } } if (z>0 && (is_updated(x,y,z - 1)&cmask)) { // Compare with backward neighbor u = a_map(x,y,z - 1,0); v = a_map(x,y,z - 1,1); w = a_map(x,y,z - 1,2); if (u>=cx1 && u<patch_image.width() - cx2 && v>=cy1 && v<patch_image.height() - cy2 && w>=cz1 - 1 && w<patch_image.depth() - 1 - cz2) { s = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,patch_depth,_spectrum, xp,yp,zp,u - cx1,v - cy1,w + 1 - cz1, u,v,w,occ_penalization,best_score); if (s<best_score) { best_u = u; best_v = v; best_w = w + 1; best_score = s; } } } if (x<width() - 1 && (is_updated(x + 1,y,z)&cmask)) { // Compare with right neighbor u = a_map(x + 1,y,z,0); v = a_map(x + 1,y,z,1); w = a_map(x + 1,y,z,2); if (u>=cx1 + 1 && u<patch_image.width() + 1 - cx2 && v>=cy1 && v<patch_image.height() - cy2 && w>=cz1 && w<patch_image.depth() - cz2) { s = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,patch_depth,_spectrum, xp,yp,zp,u - 1 - cx1,v - cy1,w - cz1, u,v,w,occ_penalization,best_score); if (s<best_score) { best_u = u - 1; best_v = v; best_w = w; best_score = s; } } } if (y<height() - 1 && (is_updated(x,y + 1,z)&cmask)) { // Compare with bottom neighbor u = a_map(x,y + 1,z,0); v = a_map(x,y + 1,z,1); w = a_map(x,y + 1,z,2); if (u>=cx1 && u<patch_image.width() - cx2 && v>=cy1 + 1 && v<patch_image.height() + 1 - cy2 && w>=cz1 && w<patch_image.depth() - cz2) { s = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,patch_depth,_spectrum, xp,yp,zp,u - cx1,v - 1 - cy1,w - cz1, u,v,w,occ_penalization,best_score); if (s<best_score) { best_u = u; best_v = v - 1; best_w = w; best_score = s; } } } if (z<depth() - 1 && (is_updated(x,y,z + 1)&cmask)) { // Compare with forward neighbor u = a_map(x,y,z + 1,0); v = a_map(x,y,z + 1,1); w = a_map(x,y,z + 1,2); if (u>=cx1 && u<patch_image.width() - cx2 && v>=cy1 && v<patch_image.height() - cy2 && w>=cz1 + 1 && w<patch_image.depth() + 1 - cz2) { s = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,patch_depth,_spectrum, xp,yp,zp,u - cx1,v - cy1,w - 1 - cz1, u,v,w,occ_penalization,best_score); if (s<best_score) { best_u = u; best_v = v; best_w = w - 1; best_score = s; } } } // Randomization. float dw = (float)patch_image.width(), dh = (float)patch_image.height(), dd = (float)patch_image.depth(); for (unsigned int i = 0; i<nb_randoms; ++i) { u = (int)cimg::round(cimg::rand(std::max((float)cx1,best_u - dw), std::min(patch_image.width() - 1.f - cx2,best_u + dw),&_rng)); v = (int)cimg::round(cimg::rand(std::max((float)cy1,best_v - dh), std::min(patch_image.height() - 1.f - cy2,best_v + dh),&_rng)); w = (int)cimg::round(cimg::rand(std::max((float)cz1,best_w - dd), std::min(patch_image.depth() - 1.f - cz2,best_w + dd),&_rng)); if (u!=best_u || v!=best_v || w!=best_w) { s = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,patch_depth,_spectrum, xp,yp,zp,u - cx1,v - cy1,w - cz1, u,v,w,occ_penalization,best_score); if (s<best_score) { best_u = u; best_v = v; best_w = w; best_score = s; } dw = std::max(5.f,dw*0.5f); dh = std::max(5.f,dh*0.5f); dd = std::max(5.f,dd*0.5f); } } if (best_score<best_score0) { a_map(x,y,z,0) = best_u; a_map(x,y,z,1) = best_v; a_map(x,y,z,2) = best_w; score(x,y,z) = best_score; is_updated(x,y,z) = 3; } else is_updated(x,y,z)&=~nmask; if (occ_penalization!=0) cimg_pragma_openmp(atomic) ++occ(best_u,best_v,best_w); } cimg::srand(_rng); } } } else { // 2D version // Initialize correspondence map. if (guide) cimg_pragma_openmp(parallel for cimg_openmp_if_size(_width,64)) cimg_forXY(*this,x,y) { // User-defined initialization const int cx1 = x<=psizew1?x:(x<width() - psizew2?psizew1:psizew + x - width()), cx2 = psizew - cx1 - 1, cy1 = y<=psizeh1?y:(y<height() - psizeh2?psizeh1:psizeh + y - height()), cy2 = psizeh - cy1 - 1, u = cimg::cut((int)guide(x,y,0),cx1,patch_image.width() - 1 - cx2), v = cimg::cut((int)guide(x,y,1),cy1,patch_image.height() - 1 - cy2); a_map(x,y,0) = u; a_map(x,y,1) = v; score(x,y) = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,_spectrum, x - cx1,y - cy1,u - cx1,v - cy1, u,v,0,cimg::type<float>::inf()); } else cimg_pragma_openmp(parallel cimg_openmp_if_size(_width,64)) { ulongT _rng = (cimg::_rand(),cimg::rng()); #if cimg_use_openmp!=0 _rng+=omp_get_thread_num(); #endif cimg_pragma_openmp(for) cimg_forXY(*this,x,y) { // Random initialization const int cx1 = x<=psizew1?x:(x<width() - psizew2?psizew1:psizew + x - width()), cx2 = psizew - cx1 - 1, cy1 = y<=psizeh1?y:(y<height() - psizeh2?psizeh1:psizeh + y - height()), cy2 = psizeh - cy1 - 1, u = (int)cimg::round(cimg::rand(cx1,patch_image.width() - 1 - cx2,&_rng)), v = (int)cimg::round(cimg::rand(cy1,patch_image.height() - 1 - cy2,&_rng)); a_map(x,y,0) = u; a_map(x,y,1) = v; score(x,y) = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,_spectrum, x - cx1,y - cy1,u - cx1,v - cy1, u,v,0,cimg::type<float>::inf()); } cimg::srand(_rng); } // Start iteration loop. cimg_abort_init; for (unsigned int iter = 0; iter<nb_iterations; ++iter) { cimg_abort_test; const bool is_odd = iter%2; const unsigned int cmask = is_odd?1:2, nmask = 3 - cmask; if (iter) occ.fill(0); cimg_pragma_openmp(parallel cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*64 && iter<nb_iterations-2)) { ulongT _rng = (cimg::_rand(),cimg::rng()); #if cimg_use_openmp!=0 _rng+=omp_get_thread_num(); #endif cimg_pragma_openmp(for) cimg_forXY(*this,X,Y) { const int _x = is_odd?width() - 1 - X:X, _y = is_odd?height() - 1 - Y:Y; int x, y; if (occ_penalization) { x = loop_order(_x,_y,0); y = loop_order(_x,_y,1); } else { x = _x; y = _y; } if (score(x,y)<=1e-5 || (constraint && guide(x,y,constraint)!=0)) continue; const int cx1 = x<=psizew1?x:(x<width() - psizew2?psizew1:psizew + x - width()), cx2 = psizew - cx1 - 1, cy1 = y<=psizeh1?y:(y<height() - psizeh2?psizeh1:psizeh + y - height()), cy2 = psizeh - cy1 - 1, xp = x - cx1, yp = y - cy1; int best_u = a_map(x,y,0), best_v = a_map(x,y,1), u, v; const float best_score0 = score(x,y); float best_score = best_score0, s; // Propagation. if (x>0 && (is_updated(x - 1,y)&cmask)) { // Compare with left neighbor u = a_map(x - 1,y,0); v = a_map(x - 1,y,1); if (u>=cx1 - 1 && u<patch_image.width() - 1 - cx2 && v>=cy1 && v<patch_image.height() - cy2) { s = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,_spectrum, xp,yp,u + 1 - cx1,v - cy1, u,v,occ_penalization,best_score); if (s<best_score) { best_u = u + 1; best_v = v; best_score = s; } } } if (y>0 && (is_updated(x,y - 1)&cmask)) { // Compare with up neighbor u = a_map(x,y - 1,0); v = a_map(x,y - 1,1); if (u>=cx1 && u<patch_image.width() - cx2 && v>=cy1 - 1 && v<patch_image.height() - 1 - cy2) { s = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,_spectrum, xp,yp,u - cx1,v + 1 - cy1, u,v,occ_penalization,best_score); if (s<best_score) { best_u = u; best_v = v + 1; best_score = s; } } } if (x<width() - 1 && (is_updated(x + 1,y)&cmask)) { // Compare with right neighbor u = a_map(x + 1,y,0); v = a_map(x + 1,y,1); if (u>=cx1 + 1 && u<patch_image.width() + 1 - cx2 && v>=cy1 && v<patch_image.height() - cy2) { s = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,_spectrum, xp,yp,u - 1 - cx1,v - cy1, u,v,occ_penalization,best_score); if (s<best_score) { best_u = u - 1; best_v = v; best_score = s; } } } if (y<height() - 1 && (is_updated(x,y + 1)&cmask)) { // Compare with bottom neighbor u = a_map(x,y + 1,0); v = a_map(x,y + 1,1); if (u>=cx1 && u<patch_image.width() - cx2 && v>=cy1 + 1 && v<patch_image.height() + 1 - cy2) { s = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,_spectrum, xp,yp,u - cx1,v - 1 - cy1, u,v,occ_penalization,best_score); if (s<best_score) { best_u = u; best_v = v - 1; best_score = s; } } } // Randomization. float dw = (float)patch_image.width(), dh = (float)patch_image.height(); for (unsigned int i = 0; i<nb_randoms; ++i) { u = (int)cimg::round(cimg::rand(std::max((float)cx1,best_u - dw), std::min(patch_image.width() - 1.f - cx2,best_u + dw),&_rng)); v = (int)cimg::round(cimg::rand(std::max((float)cy1,best_v - dh), std::min(patch_image.height() - 1.f - cy2,best_v + dh),&_rng)); if (u!=best_u || v!=best_v) { s = _matchpatch(in_this,in_patch,occ,patch_width,patch_height,_spectrum, xp,yp,u - cx1,v - cy1, u,v,occ_penalization,best_score); if (s<best_score) { best_u = u; best_v = v; best_score = s; } dw = std::max(5.f,dw*0.5f); dh = std::max(5.f,dh*0.5f); } } if (best_score<best_score0) { a_map(x,y,0) = best_u; a_map(x,y,1) = best_v; score(x,y) = best_score; is_updated(x,y) = 3; } else is_updated(x,y)&=~nmask; if (occ_penalization!=0) cimg_pragma_openmp(atomic) ++occ(best_u,best_v); } } cimg::srand(rng); } } if (is_matching_score) score.move_to(matching_score); return a_map; } // Compute SSD between two patches in different images. static float _matchpatch(const CImg<T>& img1, const CImg<T>& img2, const CImg<uintT>& occ, const unsigned int psizew, const unsigned int psizeh, const unsigned int psized, const unsigned int psizec, const int x1, const int y1, const int z1, const int x2, const int y2, const int z2, const int xc, const int yc, const int zc, const float occ_penalization, const float max_score) { // 3D version const T *p1 = img1.data(x1*psizec,y1,z1), *p2 = img2.data(x2*psizec,y2,z2); const unsigned int psizewc = psizew*psizec; const ulongT offx1 = (ulongT)img1._width - psizewc, offx2 = (ulongT)img2._width - psizewc, offy1 = (ulongT)img1._width*img1._height - (ulongT)psizeh*img1._width, offy2 = (ulongT)img2._width*img2._height - (ulongT)psizeh*img2._width; float ssd = 0; for (unsigned int k = 0; k<psized; ++k) { for (unsigned int j = 0; j<psizeh; ++j) { for (unsigned int i = 0; i<psizewc; ++i) ssd += cimg::sqr((Tfloat)*(p1++) - *(p2++)); if (ssd>max_score) return max_score; p1+=offx1; p2+=offx2; } p1+=offy1; p2+=offy2; } return occ_penalization==0?ssd:cimg::sqr(std::sqrt(ssd) + occ_penalization*occ(xc,yc,zc)); } static float _matchpatch(const CImg<T>& img1, const CImg<T>& img2, const CImg<uintT>& occ, const unsigned int psizew, const unsigned int psizeh, const unsigned int psizec, const int x1, const int y1, const int x2, const int y2, const int xc, const int yc, const float occ_penalization, const float max_score) { // 2D version const T *p1 = img1.data(x1*psizec,y1), *p2 = img2.data(x2*psizec,y2); const unsigned int psizewc = psizew*psizec; const ulongT offx1 = (ulongT)img1._width - psizewc, offx2 = (ulongT)img2._width - psizewc; float ssd = 0; for (unsigned int j = 0; j<psizeh; ++j) { for (unsigned int i = 0; i<psizewc; ++i) ssd += cimg::sqr((Tfloat)*(p1++) - *(p2++)); if (ssd>max_score) return max_score; p1+=offx1; p2+=offx2; } return occ_penalization==0?ssd:cimg::sqr(std::sqrt(ssd) + occ_penalization*occ(xc,yc)); } //! Compute Euclidean distance function to a specified value. /** \param value Reference value. \param metric Type of metric. Can be <tt>{ 0=Chebyshev | 1=Manhattan | 2=Euclidean | 3=Squared-euclidean }</tt>. \note The distance transform implementation has been submitted by A. Meijster, and implements the article 'W.H. Hesselink, A. Meijster, J.B.T.M. Roerdink, "A general algorithm for computing distance transforms in linear time.", In: Mathematical Morphology and its Applications to Image and Signal Processing, J. Goutsias, L. Vincent, and D.S. Bloomberg (eds.), Kluwer, 2000, pp. 331-340.' The submitted code has then been modified to fit CImg coding style and constraints. **/ CImg<T>& distance(const T& value, const unsigned int metric=2) { if (is_empty()) return *this; if (cimg::type<Tint>::string()!=cimg::type<T>::string()) // For datatype < int return CImg<Tint>(*this,false).distance((Tint)value,metric). cut((Tint)cimg::type<T>::min(),(Tint)cimg::type<T>::max()).move_to(*this); bool is_value = false; cimg_for(*this,ptr,T) *ptr = *ptr==value?is_value=true,(T)0:(T)std::max(0,99999999); // (avoid VC++ warning) if (!is_value) return fill(cimg::type<T>::max()); switch (metric) { case 0 : return _distance_core(_distance_sep_cdt,_distance_dist_cdt); // Chebyshev case 1 : return _distance_core(_distance_sep_mdt,_distance_dist_mdt); // Manhattan case 3 : return _distance_core(_distance_sep_edt,_distance_dist_edt); // Squared Euclidean default : return _distance_core(_distance_sep_edt,_distance_dist_edt).sqrt(); // Euclidean } return *this; } //! Compute distance to a specified value \newinstance. CImg<Tfloat> get_distance(const T& value, const unsigned int metric=2) const { return CImg<Tfloat>(*this,false).distance((Tfloat)value,metric); } static longT _distance_sep_edt(const longT i, const longT u, const longT *const g) { return (u*u - i*i + g[u] - g[i])/(2*(u - i)); } static longT _distance_dist_edt(const longT x, const longT i, const longT *const g) { return (x - i)*(x - i) + g[i]; } static longT _distance_sep_mdt(const longT i, const longT u, const longT *const g) { return (u - i<=g[u] - g[i]?999999999:(g[u] - g[i] + u + i)/2); } static longT _distance_dist_mdt(const longT x, const longT i, const longT *const g) { return (x<i?i - x:x - i) + g[i]; } static longT _distance_sep_cdt(const longT i, const longT u, const longT *const g) { const longT h = (i + u)/2; if (g[i]<=g[u]) { return h<i + g[u]?i + g[u]:h; } return h<u - g[i]?h:u - g[i]; } static longT _distance_dist_cdt(const longT x, const longT i, const longT *const g) { const longT d = x<i?i - x:x - i; return d<g[i]?g[i]:d; } static void _distance_scan(const unsigned int len, const longT *const g, longT (*const sep)(const longT, const longT, const longT *const), longT (*const f)(const longT, const longT, const longT *const), longT *const s, longT *const t, longT *const dt) { longT q = s[0] = t[0] = 0; for (int u = 1; u<(int)len; ++u) { // Forward scan while ((q>=0) && f(t[q],s[q],g)>f(t[q],u,g)) { --q; } if (q<0) { q = 0; s[0] = u; } else { const longT w = 1 + sep(s[q], u, g); if (w<(longT)len) { ++q; s[q] = u; t[q] = w; }} } for (int u = (int)len - 1; u>=0; --u) { dt[u] = f(u,s[q],g); if (u==t[q]) --q; } // Backward scan } CImg<T>& _distance_core(longT (*const sep)(const longT, const longT, const longT *const), longT (*const f)(const longT, const longT, const longT *const)) { // Check for g++ 4.9.X, as OpenMP seems to crash for this particular function. I have no clues why. #define cimg_is_gcc49x (__GNUC__==4 && __GNUC_MINOR__==9) const ulongT wh = (ulongT)_width*_height; #if cimg_use_openmp!=0 && !cimg_is_gcc49x cimg_pragma_openmp(parallel for cimg_openmp_if(_spectrum>=2)) #endif cimg_forC(*this,c) { CImg<longT> g(_width), dt(_width), s(_width), t(_width); CImg<T> img = get_shared_channel(c); #if cimg_use_openmp!=0 && !cimg_is_gcc49x cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*512 && _height*_depth>=16) firstprivate(g,dt,s,t)) #endif cimg_forYZ(*this,y,z) { // Over X-direction cimg_forX(*this,x) g[x] = (longT)img(x,y,z,0,wh); _distance_scan(_width,g,sep,f,s,t,dt); cimg_forX(*this,x) img(x,y,z,0,wh) = (T)dt[x]; } if (_height>1) { g.assign(_height); dt.assign(_height); s.assign(_height); t.assign(_height); #if cimg_use_openmp!=0 && !cimg_is_gcc49x cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_height>=(cimg_openmp_sizefactor)*512 && _width*_depth>=16) firstprivate(g,dt,s,t)) #endif cimg_forXZ(*this,x,z) { // Over Y-direction cimg_forY(*this,y) g[y] = (longT)img(x,y,z,0,wh); _distance_scan(_height,g,sep,f,s,t,dt); cimg_forY(*this,y) img(x,y,z,0,wh) = (T)dt[y]; } } if (_depth>1) { g.assign(_depth); dt.assign(_depth); s.assign(_depth); t.assign(_depth); #if cimg_use_openmp!=0 && !cimg_is_gcc49x cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if(_depth>=(cimg_openmp_sizefactor)*512 && _width*_height>=16) firstprivate(g,dt,s,t)) #endif cimg_forXY(*this,x,y) { // Over Z-direction cimg_forZ(*this,z) g[z] = (longT)img(x,y,z,0,wh); _distance_scan(_depth,g,sep,f,s,t,dt); cimg_forZ(*this,z) img(x,y,z,0,wh) = (T)dt[z]; } } } return *this; } //! Compute chamfer distance to a specified value, with a custom metric. /** \param value Reference value. \param metric_mask Metric mask. \note The algorithm code has been initially proposed by A. Meijster, and modified by D. Tschumperlé. **/ template<typename t> CImg<T>& distance(const T& value, const CImg<t>& metric_mask) { if (is_empty()) return *this; bool is_value = false; cimg_for(*this,ptr,T) *ptr = *ptr==value?is_value=true,0:(T)999999999; if (!is_value) return fill(cimg::type<T>::max()); const ulongT wh = (ulongT)_width*_height; cimg_pragma_openmp(parallel for cimg_openmp_if(_spectrum>=2)) cimg_forC(*this,c) { CImg<T> img = get_shared_channel(c); cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width*_height*_depth>=(cimg_openmp_sizefactor)*1024)) cimg_forXYZ(metric_mask,dx,dy,dz) { const t weight = metric_mask(dx,dy,dz); if (weight) { for (int z = dz, nz = 0; z<depth(); ++z,++nz) { // Forward scan for (int y = dy , ny = 0; y<height(); ++y,++ny) { for (int x = dx, nx = 0; x<width(); ++x,++nx) { const T dd = img(nx,ny,nz,0,wh) + weight; if (dd<img(x,y,z,0,wh)) img(x,y,z,0,wh) = dd; } } } for (int z = depth() - 1 - dz, nz = depth() - 1; z>=0; --z,--nz) { // Backward scan for (int y = height() - 1 - dy, ny = height() - 1; y>=0; --y,--ny) { for (int x = width() - 1 - dx, nx = width() - 1; x>=0; --x,--nx) { const T dd = img(nx,ny,nz,0,wh) + weight; if (dd<img(x,y,z,0,wh)) img(x,y,z,0,wh) = dd; } } } } } } return *this; } //! Compute chamfer distance to a specified value, with a custom metric \newinstance. template<typename t> CImg<Tfloat> get_distance(const T& value, const CImg<t>& metric_mask) const { return CImg<Tfloat>(*this,false).distance(value,metric_mask); } //! Compute distance to a specified value, according to a custom metric (use dijkstra algorithm). /** \param value Reference value. \param metric Field of distance potentials. \param is_high_connectivity Tells if the algorithm uses low or high connectivity. \param[out] return_path An image containing the nodes of the minimal path. **/ template<typename t, typename to> CImg<T>& distance_dijkstra(const T& value, const CImg<t>& metric, const bool is_high_connectivity, CImg<to>& return_path) { return get_distance_dijkstra(value,metric,is_high_connectivity,return_path).move_to(*this); } //! Compute distance map to a specified value, according to a custom metric (use dijkstra algorithm) \newinstance. template<typename t, typename to> CImg<typename cimg::superset<t,long>::type> get_distance_dijkstra(const T& value, const CImg<t>& metric, const bool is_high_connectivity, CImg<to>& return_path) const { if (is_empty()) return return_path.assign(); if (!is_sameXYZ(metric)) throw CImgArgumentException(_cimg_instance "distance_dijkstra(): image instance and metric map (%u,%u,%u,%u) " "have incompatible dimensions.", cimg_instance, metric._width,metric._height,metric._depth,metric._spectrum); typedef typename cimg::superset<t,long>::type td; // Type used for computing cumulative distances CImg<td> result(_width,_height,_depth,_spectrum), Q; CImg<boolT> is_queued(_width,_height,_depth,1); if (return_path) return_path.assign(_width,_height,_depth,_spectrum); cimg_forC(*this,c) { const CImg<T> img = get_shared_channel(c); const CImg<t> met = metric.get_shared_channel(c%metric._spectrum); CImg<td> res = result.get_shared_channel(c); CImg<to> path = return_path?return_path.get_shared_channel(c):CImg<to>(); unsigned int sizeQ = 0; // Detect initial seeds. is_queued.fill(0); cimg_forXYZ(img,x,y,z) if (img(x,y,z)==value) { Q._priority_queue_insert(is_queued,sizeQ,0,x,y,z); res(x,y,z) = 0; if (path) path(x,y,z) = (to)0; } // Start distance propagation. while (sizeQ) { // Get and remove point with minimal potential from the queue. const int x = (int)Q(0,1), y = (int)Q(0,2), z = (int)Q(0,3); const td P = (td)-Q(0,0); Q._priority_queue_remove(sizeQ); // Update neighbors. td npot = 0; if (x - 1>=0 && Q._priority_queue_insert(is_queued,sizeQ,-(npot=met(x - 1,y,z) + P),x - 1,y,z)) { res(x - 1,y,z) = npot; if (path) path(x - 1,y,z) = (to)2; } if (x + 1<width() && Q._priority_queue_insert(is_queued,sizeQ,-(npot=met(x + 1,y,z) + P),x + 1,y,z)) { res(x + 1,y,z) = npot; if (path) path(x + 1,y,z) = (to)1; } if (y - 1>=0 && Q._priority_queue_insert(is_queued,sizeQ,-(npot=met(x,y - 1,z) + P),x,y - 1,z)) { res(x,y - 1,z) = npot; if (path) path(x,y - 1,z) = (to)8; } if (y + 1<height() && Q._priority_queue_insert(is_queued,sizeQ,-(npot=met(x,y + 1,z) + P),x,y + 1,z)) { res(x,y + 1,z) = npot; if (path) path(x,y + 1,z) = (to)4; } if (z - 1>=0 && Q._priority_queue_insert(is_queued,sizeQ,-(npot=met(x,y,z - 1) + P),x,y,z - 1)) { res(x,y,z - 1) = npot; if (path) path(x,y,z - 1) = (to)32; } if (z + 1<depth() && Q._priority_queue_insert(is_queued,sizeQ,-(npot=met(x,y,z + 1) + P),x,y,z + 1)) { res(x,y,z + 1) = npot; if (path) path(x,y,z + 1) = (to)16; } if (is_high_connectivity) { const float sqrt2 = std::sqrt(2.f), sqrt3 = std::sqrt(3.f); // Diagonal neighbors on slice z. if (x - 1>=0 && y - 1>=0 && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt2*met(x - 1,y - 1,z) + P)),x - 1,y - 1,z)) { res(x - 1,y - 1,z) = npot; if (path) path(x - 1,y - 1,z) = (to)10; } if (x + 1<width() && y - 1>=0 && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt2*met(x + 1,y - 1,z) + P)),x + 1,y - 1,z)) { res(x + 1,y - 1,z) = npot; if (path) path(x + 1,y - 1,z) = (to)9; } if (x - 1>=0 && y + 1<height() && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt2*met(x - 1,y + 1,z) + P)),x - 1,y + 1,z)) { res(x - 1,y + 1,z) = npot; if (path) path(x - 1,y + 1,z) = (to)6; } if (x + 1<width() && y + 1<height() && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt2*met(x + 1,y + 1,z) + P)),x + 1,y + 1,z)) { res(x + 1,y + 1,z) = npot; if (path) path(x + 1,y + 1,z) = (to)5; } if (z - 1>=0) { // Diagonal neighbors on slice z - 1 if (x - 1>=0 && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt2*met(x - 1,y,z - 1) + P)),x - 1,y,z - 1)) { res(x - 1,y,z - 1) = npot; if (path) path(x - 1,y,z - 1) = (to)34; } if (x + 1<width() && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt2*met(x + 1,y,z - 1) + P)),x + 1,y,z - 1)) { res(x + 1,y,z - 1) = npot; if (path) path(x + 1,y,z - 1) = (to)33; } if (y - 1>=0 && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt2*met(x,y - 1,z - 1) + P)),x,y - 1,z - 1)) { res(x,y - 1,z - 1) = npot; if (path) path(x,y - 1,z - 1) = (to)40; } if (y + 1<height() && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt2*met(x,y + 1,z - 1) + P)),x,y + 1,z - 1)) { res(x,y + 1,z - 1) = npot; if (path) path(x,y + 1,z - 1) = (to)36; } if (x - 1>=0 && y - 1>=0 && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt3*met(x - 1,y - 1,z - 1) + P)), x - 1,y - 1,z - 1)) { res(x - 1,y - 1,z - 1) = npot; if (path) path(x - 1,y - 1,z - 1) = (to)42; } if (x + 1<width() && y - 1>=0 && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt3*met(x + 1,y - 1,z - 1) + P)), x + 1,y - 1,z - 1)) { res(x + 1,y - 1,z - 1) = npot; if (path) path(x + 1,y - 1,z - 1) = (to)41; } if (x - 1>=0 && y + 1<height() && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt3*met(x - 1,y + 1,z - 1) + P)), x - 1,y + 1,z - 1)) { res(x - 1,y + 1,z - 1) = npot; if (path) path(x - 1,y + 1,z - 1) = (to)38; } if (x + 1<width() && y + 1<height() && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt3*met(x + 1,y + 1,z - 1) + P)), x + 1,y + 1,z - 1)) { res(x + 1,y + 1,z - 1) = npot; if (path) path(x + 1,y + 1,z - 1) = (to)37; } } if (z + 1<depth()) { // Diagonal neighbors on slice z + 1 if (x - 1>=0 && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt2*met(x - 1,y,z + 1) + P)),x - 1,y,z + 1)) { res(x - 1,y,z + 1) = npot; if (path) path(x - 1,y,z + 1) = (to)18; } if (x + 1<width() && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt2*met(x + 1,y,z + 1) + P)),x + 1,y,z + 1)) { res(x + 1,y,z + 1) = npot; if (path) path(x + 1,y,z + 1) = (to)17; } if (y - 1>=0 && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt2*met(x,y - 1,z + 1) + P)),x,y - 1,z + 1)) { res(x,y - 1,z + 1) = npot; if (path) path(x,y - 1,z + 1) = (to)24; } if (y + 1<height() && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt2*met(x,y + 1,z + 1) + P)),x,y + 1,z + 1)) { res(x,y + 1,z + 1) = npot; if (path) path(x,y + 1,z + 1) = (to)20; } if (x - 1>=0 && y - 1>=0 && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt3*met(x - 1,y - 1,z + 1) + P)), x - 1,y - 1,z + 1)) { res(x - 1,y - 1,z + 1) = npot; if (path) path(x - 1,y - 1,z + 1) = (to)26; } if (x + 1<width() && y - 1>=0 && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt3*met(x + 1,y - 1,z + 1) + P)), x + 1,y - 1,z + 1)) { res(x + 1,y - 1,z + 1) = npot; if (path) path(x + 1,y - 1,z + 1) = (to)25; } if (x - 1>=0 && y + 1<height() && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt3*met(x - 1,y + 1,z + 1) + P)), x - 1,y + 1,z + 1)) { res(x - 1,y + 1,z + 1) = npot; if (path) path(x - 1,y + 1,z + 1) = (to)22; } if (x + 1<width() && y + 1<height() && Q._priority_queue_insert(is_queued,sizeQ,-(npot=(td)(sqrt3*met(x + 1,y + 1,z + 1) + P)), x + 1,y + 1,z + 1)) { res(x + 1,y + 1,z + 1) = npot; if (path) path(x + 1,y + 1,z + 1) = (to)21; } } } } } return result; } //! Compute distance map to a specified value, according to a custom metric (use dijkstra algorithm). \overloading. template<typename t> CImg<T>& distance_dijkstra(const T& value, const CImg<t>& metric, const bool is_high_connectivity=false) { return get_distance_dijkstra(value,metric,is_high_connectivity).move_to(*this); } //! Compute distance map to a specified value, according to a custom metric (use dijkstra algorithm). \newinstance. template<typename t> CImg<Tfloat> get_distance_dijkstra(const T& value, const CImg<t>& metric, const bool is_high_connectivity=false) const { CImg<T> return_path; return get_distance_dijkstra(value,metric,is_high_connectivity,return_path); } //! Compute distance map to one source point, according to a custom metric (use fast marching algorithm). /** \param value Reference value. \param metric Field of distance potentials. **/ template<typename t> CImg<T>& distance_eikonal(const T& value, const CImg<t>& metric) { return get_distance_eikonal(value,metric).move_to(*this); } //! Compute distance map to one source point, according to a custom metric (use fast marching algorithm). template<typename t> CImg<Tfloat> get_distance_eikonal(const T& value, const CImg<t>& metric) const { if (is_empty()) return *this; if (!is_sameXYZ(metric)) throw CImgArgumentException(_cimg_instance "distance_eikonal(): image instance and metric map (%u,%u,%u,%u) have " "incompatible dimensions.", cimg_instance, metric._width,metric._height,metric._depth,metric._spectrum); CImg<Tfloat> result(_width,_height,_depth,_spectrum,cimg::type<Tfloat>::max()), Q; CImg<charT> state(_width,_height,_depth); // -1=far away, 0=narrow, 1=frozen cimg_pragma_openmp(parallel for cimg_openmp_if(_spectrum>=2) firstprivate(Q,state)) cimg_forC(*this,c) { const CImg<T> img = get_shared_channel(c); const CImg<t> met = metric.get_shared_channel(c%metric._spectrum); CImg<Tfloat> res = result.get_shared_channel(c); unsigned int sizeQ = 0; state.fill(-1); // Detect initial seeds. Tfloat *ptr1 = res._data; char *ptr2 = state._data; cimg_for(img,ptr0,T) { if (*ptr0==value) { *ptr1 = 0; *ptr2 = 1; } ++ptr1; ++ptr2; } // Initialize seeds neighbors. ptr2 = state._data; cimg_forXYZ(img,x,y,z) if (*(ptr2++)==1) { if (x - 1>=0 && state(x - 1,y,z)==-1) { const Tfloat dist = res(x - 1,y,z) = __distance_eikonal(res,met(x - 1,y,z),x - 1,y,z); Q._eik_priority_queue_insert(state,sizeQ,-dist,x - 1,y,z); } if (x + 1<width() && state(x + 1,y,z)==-1) { const Tfloat dist = res(x + 1,y,z) = __distance_eikonal(res,met(x + 1,y,z),x + 1,y,z); Q._eik_priority_queue_insert(state,sizeQ,-dist,x + 1,y,z); } if (y - 1>=0 && state(x,y - 1,z)==-1) { const Tfloat dist = res(x,y - 1,z) = __distance_eikonal(res,met(x,y - 1,z),x,y - 1,z); Q._eik_priority_queue_insert(state,sizeQ,-dist,x,y - 1,z); } if (y + 1<height() && state(x,y + 1,z)==-1) { const Tfloat dist = res(x,y + 1,z) = __distance_eikonal(res,met(x,y + 1,z),x,y + 1,z); Q._eik_priority_queue_insert(state,sizeQ,-dist,x,y + 1,z); } if (z - 1>=0 && state(x,y,z - 1)==-1) { const Tfloat dist = res(x,y,z - 1) = __distance_eikonal(res,met(x,y,z - 1),x,y,z - 1); Q._eik_priority_queue_insert(state,sizeQ,-dist,x,y,z - 1); } if (z + 1<depth() && state(x,y,z + 1)==-1) { const Tfloat dist = res(x,y,z + 1) = __distance_eikonal(res,met(x,y,z + 1),x,y,z + 1); Q._eik_priority_queue_insert(state,sizeQ,-dist,x,y,z + 1); } } // Propagate front. while (sizeQ) { int x = -1, y = -1, z = -1; while (sizeQ && x<0) { x = (int)Q(0,1); y = (int)Q(0,2); z = (int)Q(0,3); Q._priority_queue_remove(sizeQ); if (state(x,y,z)==1) x = -1; else state(x,y,z) = 1; } if (x>=0) { if (x - 1>=0 && state(x - 1,y,z)!=1) { const Tfloat dist = __distance_eikonal(res,met(x - 1,y,z),x - 1,y,z); if (dist<res(x - 1,y,z)) { res(x - 1,y,z) = dist; Q._eik_priority_queue_insert(state,sizeQ,-dist,x - 1,y,z); } } if (x + 1<width() && state(x + 1,y,z)!=1) { const Tfloat dist = __distance_eikonal(res,met(x + 1,y,z),x + 1,y,z); if (dist<res(x + 1,y,z)) { res(x + 1,y,z) = dist; Q._eik_priority_queue_insert(state,sizeQ,-dist,x + 1,y,z); } } if (y - 1>=0 && state(x,y - 1,z)!=1) { const Tfloat dist = __distance_eikonal(res,met(x,y - 1,z),x,y - 1,z); if (dist<res(x,y - 1,z)) { res(x,y - 1,z) = dist; Q._eik_priority_queue_insert(state,sizeQ,-dist,x,y - 1,z); } } if (y + 1<height() && state(x,y + 1,z)!=1) { const Tfloat dist = __distance_eikonal(res,met(x,y + 1,z),x,y + 1,z); if (dist<res(x,y + 1,z)) { res(x,y + 1,z) = dist; Q._eik_priority_queue_insert(state,sizeQ,-dist,x,y + 1,z); } } if (z - 1>=0 && state(x,y,z - 1)!=1) { const Tfloat dist = __distance_eikonal(res,met(x,y,z - 1),x,y,z - 1); if (dist<res(x,y,z - 1)) { res(x,y,z - 1) = dist; Q._eik_priority_queue_insert(state,sizeQ,-dist,x,y,z - 1); } } if (z + 1<depth() && state(x,y,z + 1)!=1) { const Tfloat dist = __distance_eikonal(res,met(x,y,z + 1),x,y,z + 1); if (dist<res(x,y,z + 1)) { res(x,y,z + 1) = dist; Q._eik_priority_queue_insert(state,sizeQ,-dist,x,y,z + 1); } } } } } return result; } // Locally solve eikonal equation. Tfloat __distance_eikonal(const CImg<Tfloat>& res, const Tfloat P, const int x=0, const int y=0, const int z=0) const { const Tfloat M = (Tfloat)cimg::type<T>::max(); T T1 = (T)std::min(x - 1>=0?res(x - 1,y,z):M,x + 1<width()?res(x + 1,y,z):M); Tfloat root = 0; if (_depth>1) { // 3D T T2 = (T)std::min(y - 1>=0?res(x,y - 1,z):M,y + 1<height()?res(x,y + 1,z):M), T3 = (T)std::min(z - 1>=0?res(x,y,z - 1):M,z + 1<depth()?res(x,y,z + 1):M); if (T1>T2) cimg::swap(T1,T2); if (T2>T3) cimg::swap(T2,T3); if (T1>T2) cimg::swap(T1,T2); if (P<=0) return (Tfloat)T1; if (T3<M && ___distance_eikonal(3,-2*(T1 + T2 + T3),T1*T1 + T2*T2 + T3*T3 - P*P,root)) return std::max((Tfloat)T3,root); if (T2<M && ___distance_eikonal(2,-2*(T1 + T2),T1*T1 + T2*T2 - P*P,root)) return std::max((Tfloat)T2,root); return P + T1; } else if (_height>1) { // 2D T T2 = (T)std::min(y - 1>=0?res(x,y - 1,z):M,y + 1<height()?res(x,y + 1,z):M); if (T1>T2) cimg::swap(T1,T2); if (P<=0) return (Tfloat)T1; if (T2<M && ___distance_eikonal(2,-2*(T1 + T2),T1*T1 + T2*T2 - P*P,root)) return std::max((Tfloat)T2,root); return P + T1; } else { // 1D if (P<=0) return (Tfloat)T1; return P + T1; } return 0; } // Find max root of a 2nd-order polynomial. static bool ___distance_eikonal(const Tfloat a, const Tfloat b, const Tfloat c, Tfloat &root) { const Tfloat delta = b*b - 4*a*c; if (delta<0) return false; root = 0.5f*(-b + std::sqrt(delta))/a; return true; } // Insert new point in heap. template<typename t> void _eik_priority_queue_insert(CImg<charT>& state, unsigned int& siz, const t value, const unsigned int x, const unsigned int y, const unsigned int z) { if (state(x,y,z)>0) return; state(x,y,z) = 0; if (++siz>=_width) { if (!is_empty()) resize(_width*2,4,1,1,0); else assign(64,4); } (*this)(siz - 1,0) = (T)value; (*this)(siz - 1,1) = (T)x; (*this)(siz - 1,2) = (T)y; (*this)(siz - 1,3) = (T)z; for (unsigned int pos = siz - 1, par = 0; pos && value>(t)(*this)(par=(pos + 1)/2 - 1,0); pos = par) { cimg::swap((*this)(pos,0),(*this)(par,0)); cimg::swap((*this)(pos,1),(*this)(par,1)); cimg::swap((*this)(pos,2),(*this)(par,2)); cimg::swap((*this)(pos,3),(*this)(par,3)); } } //! Compute distance function to 0-valued isophotes, using the Eikonal PDE. /** \param nb_iterations Number of PDE iterations. \param band_size Size of the narrow band. \param time_step Time step of the PDE iterations. **/ CImg<T>& distance_eikonal(const unsigned int nb_iterations, const float band_size=0, const float time_step=0.5f) { if (is_empty()) return *this; CImg<Tfloat> velocity(*this,false); for (unsigned int iteration = 0; iteration<nb_iterations; ++iteration) { Tfloat *ptrd = velocity._data, veloc_max = 0; if (_depth>1) { // 3D CImg_3x3x3(I,Tfloat); cimg_forC(*this,c) cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) if (band_size<=0 || cimg::abs(Iccc)<band_size) { const Tfloat gx = (Incc - Ipcc)/2, gy = (Icnc - Icpc)/2, gz = (Iccn - Iccp)/2, sgn = -cimg::sign(Iccc), ix = gx*sgn>0?(Incc - Iccc):(Iccc - Ipcc), iy = gy*sgn>0?(Icnc - Iccc):(Iccc - Icpc), iz = gz*sgn>0?(Iccn - Iccc):(Iccc - Iccp), ng = 1e-5f + cimg::hypot(gx,gy,gz), ngx = gx/ng, ngy = gy/ng, ngz = gz/ng, veloc = sgn*(ngx*ix + ngy*iy + ngz*iz - 1); *(ptrd++) = veloc; if (veloc>veloc_max) veloc_max = veloc; else if (-veloc>veloc_max) veloc_max = -veloc; } else *(ptrd++) = 0; } else { // 2D version CImg_3x3(I,Tfloat); cimg_forC(*this,c) cimg_for3x3(*this,x,y,0,c,I,Tfloat) if (band_size<=0 || cimg::abs(Icc)<band_size) { const Tfloat gx = (Inc - Ipc)/2, gy = (Icn - Icp)/2, sgn = -cimg::sign(Icc), ix = gx*sgn>0?(Inc - Icc):(Icc - Ipc), iy = gy*sgn>0?(Icn - Icc):(Icc - Icp), ng = std::max((Tfloat)1e-5,cimg::hypot(gx,gy)), ngx = gx/ng, ngy = gy/ng, veloc = sgn*(ngx*ix + ngy*iy - 1); *(ptrd++) = veloc; if (veloc>veloc_max) veloc_max = veloc; else if (-veloc>veloc_max) veloc_max = -veloc; } else *(ptrd++) = 0; } if (veloc_max>0) *this+=(velocity*=time_step/veloc_max); } return *this; } //! Compute distance function to 0-valued isophotes, using the Eikonal PDE \newinstance. CImg<Tfloat> get_distance_eikonal(const unsigned int nb_iterations, const float band_size=0, const float time_step=0.5f) const { return CImg<Tfloat>(*this,false).distance_eikonal(nb_iterations,band_size,time_step); } //! Compute Haar multiscale wavelet transform. /** \param axis Axis considered for the transform. \param invert Set inverse of direct transform. \param nb_scales Number of scales used for the transform. **/ CImg<T>& haar(const char axis, const bool invert=false, const unsigned int nb_scales=1) { return get_haar(axis,invert,nb_scales).move_to(*this); } //! Compute Haar multiscale wavelet transform \newinstance. CImg<Tfloat> get_haar(const char axis, const bool invert=false, const unsigned int nb_scales=1) const { if (is_empty() || !nb_scales) return +*this; CImg<Tfloat> res; const Tfloat sqrt2 = std::sqrt(2.f); if (nb_scales==1) { switch (cimg::lowercase(axis)) { // Single scale transform case 'x' : { const unsigned int w = _width/2; if (w) { if ((w%2) && w!=1) throw CImgInstanceException(_cimg_instance "haar(): Sub-image width %u is not even.", cimg_instance, w); res.assign(_width,_height,_depth,_spectrum); if (invert) cimg_forYZC(*this,y,z,c) { // Inverse transform along X for (unsigned int x = 0, xw = w, x2 = 0; x<w; ++x, ++xw) { const Tfloat val0 = (Tfloat)(*this)(x,y,z,c), val1 = (Tfloat)(*this)(xw,y,z,c); res(x2++,y,z,c) = (val0 - val1)/sqrt2; res(x2++,y,z,c) = (val0 + val1)/sqrt2; } } else cimg_forYZC(*this,y,z,c) { // Direct transform along X for (unsigned int x = 0, xw = w, x2 = 0; x<w; ++x, ++xw) { const Tfloat val0 = (Tfloat)(*this)(x2++,y,z,c), val1 = (Tfloat)(*this)(x2++,y,z,c); res(x,y,z,c) = (val0 + val1)/sqrt2; res(xw,y,z,c) = (val1 - val0)/sqrt2; } } } else return *this; } break; case 'y' : { const unsigned int h = _height/2; if (h) { if ((h%2) && h!=1) throw CImgInstanceException(_cimg_instance "haar(): Sub-image height %u is not even.", cimg_instance, h); res.assign(_width,_height,_depth,_spectrum); if (invert) cimg_forXZC(*this,x,z,c) { // Inverse transform along Y for (unsigned int y = 0, yh = h, y2 = 0; y<h; ++y, ++yh) { const Tfloat val0 = (Tfloat)(*this)(x,y,z,c), val1 = (Tfloat)(*this)(x,yh,z,c); res(x,y2++,z,c) = (val0 - val1)/sqrt2; res(x,y2++,z,c) = (val0 + val1)/sqrt2; } } else cimg_forXZC(*this,x,z,c) { for (unsigned int y = 0, yh = h, y2 = 0; y<h; ++y, ++yh) { // Direct transform along Y const Tfloat val0 = (Tfloat)(*this)(x,y2++,z,c), val1 = (Tfloat)(*this)(x,y2++,z,c); res(x,y,z,c) = (val0 + val1)/sqrt2; res(x,yh,z,c) = (val1 - val0)/sqrt2; } } } else return *this; } break; case 'z' : { const unsigned int d = _depth/2; if (d) { if ((d%2) && d!=1) throw CImgInstanceException(_cimg_instance "haar(): Sub-image depth %u is not even.", cimg_instance, d); res.assign(_width,_height,_depth,_spectrum); if (invert) cimg_forXYC(*this,x,y,c) { // Inverse transform along Z for (unsigned int z = 0, zd = d, z2 = 0; z<d; ++z, ++zd) { const Tfloat val0 = (Tfloat)(*this)(x,y,z,c), val1 = (Tfloat)(*this)(x,y,zd,c); res(x,y,z2++,c) = (val0 - val1)/sqrt2; res(x,y,z2++,c) = (val0 + val1)/sqrt2; } } else cimg_forXYC(*this,x,y,c) { for (unsigned int z = 0, zd = d, z2 = 0; z<d; ++z, ++zd) { // Direct transform along Z const Tfloat val0 = (Tfloat)(*this)(x,y,z2++,c), val1 = (Tfloat)(*this)(x,y,z2++,c); res(x,y,z,c) = (val0 + val1)/sqrt2; res(x,y,zd,c) = (val1 - val0)/sqrt2; } } } else return *this; } break; default : throw CImgArgumentException(_cimg_instance "haar(): Invalid specified axis '%c' " "(should be { x | y | z }).", cimg_instance, axis); } } else { // Multi-scale version if (invert) { res.assign(*this,false); switch (cimg::lowercase(axis)) { case 'x' : { unsigned int w = _width; for (unsigned int s = 1; w && s<nb_scales; ++s) w/=2; for (w = w?w:1; w<=_width; w*=2) res.draw_image(res.get_crop(0,w - 1).get_haar('x',true,1)); } break; case 'y' : { unsigned int h = _width; for (unsigned int s = 1; h && s<nb_scales; ++s) h/=2; for (h = h?h:1; h<=_height; h*=2) res.draw_image(res.get_crop(0,0,_width - 1,h - 1).get_haar('y',true,1)); } break; case 'z' : { unsigned int d = _depth; for (unsigned int s = 1; d && s<nb_scales; ++s) d/=2; for (d = d?d:1; d<=_depth; d*=2) res.draw_image(res.get_crop(0,0,0,_width - 1,_height - 1,d - 1).get_haar('z',true,1)); } break; default : throw CImgArgumentException(_cimg_instance "haar(): Invalid specified axis '%c' " "(should be { x | y | z }).", cimg_instance, axis); } } else { // Direct transform res = get_haar(axis,false,1); switch (cimg::lowercase(axis)) { case 'x' : { for (unsigned int s = 1, w = _width/2; w && s<nb_scales; ++s, w/=2) res.draw_image(res.get_crop(0,w - 1).get_haar('x',false,1)); } break; case 'y' : { for (unsigned int s = 1, h = _height/2; h && s<nb_scales; ++s, h/=2) res.draw_image(res.get_crop(0,0,_width - 1,h - 1).get_haar('y',false,1)); } break; case 'z' : { for (unsigned int s = 1, d = _depth/2; d && s<nb_scales; ++s, d/=2) res.draw_image(res.get_crop(0,0,0,_width - 1,_height - 1,d - 1).get_haar('z',false,1)); } break; default : throw CImgArgumentException(_cimg_instance "haar(): Invalid specified axis '%c' " "(should be { x | y | z }).", cimg_instance, axis); } } } return res; } //! Compute Haar multiscale wavelet transform \overloading. /** \param invert Set inverse of direct transform. \param nb_scales Number of scales used for the transform. **/ CImg<T>& haar(const bool invert=false, const unsigned int nb_scales=1) { return get_haar(invert,nb_scales).move_to(*this); } //! Compute Haar multiscale wavelet transform \newinstance. CImg<Tfloat> get_haar(const bool invert=false, const unsigned int nb_scales=1) const { CImg<Tfloat> res; if (nb_scales==1) { // Single scale transform if (_width>1) get_haar('x',invert,1).move_to(res); if (_height>1) { if (res) res.haar('y',invert,1); else get_haar('y',invert,1).move_to(res); } if (_depth>1) { if (res) res.haar('z',invert,1); else get_haar('z',invert,1).move_to(res); } if (res) return res; } else { // Multi-scale transform if (invert) { // Inverse transform res.assign(*this,false); if (_width>1) { if (_height>1) { if (_depth>1) { unsigned int w = _width, h = _height, d = _depth; for (unsigned int s = 1; w && h && d && s<nb_scales; ++s) { w/=2; h/=2; d/=2; } for (w = w?w:1, h = h?h:1, d = d?d:1; w<=_width && h<=_height && d<=_depth; w*=2, h*=2, d*=2) res.draw_image(res.get_crop(0,0,0,w - 1,h - 1,d - 1).get_haar(true,1)); } else { unsigned int w = _width, h = _height; for (unsigned int s = 1; w && h && s<nb_scales; ++s) { w/=2; h/=2; } for (w = w?w:1, h = h?h:1; w<=_width && h<=_height; w*=2, h*=2) res.draw_image(res.get_crop(0,0,0,w - 1,h - 1,0).get_haar(true,1)); } } else { if (_depth>1) { unsigned int w = _width, d = _depth; for (unsigned int s = 1; w && d && s<nb_scales; ++s) { w/=2; d/=2; } for (w = w?w:1, d = d?d:1; w<=_width && d<=_depth; w*=2, d*=2) res.draw_image(res.get_crop(0,0,0,w - 1,0,d - 1).get_haar(true,1)); } else { unsigned int w = _width; for (unsigned int s = 1; w && s<nb_scales; ++s) w/=2; for (w = w?w:1; w<=_width; w*=2) res.draw_image(res.get_crop(0,0,0,w - 1,0,0).get_haar(true,1)); } } } else { if (_height>1) { if (_depth>1) { unsigned int h = _height, d = _depth; for (unsigned int s = 1; h && d && s<nb_scales; ++s) { h/=2; d/=2; } for (h = h?h:1, d = d?d:1; h<=_height && d<=_depth; h*=2, d*=2) res.draw_image(res.get_crop(0,0,0,0,h - 1,d - 1).get_haar(true,1)); } else { unsigned int h = _height; for (unsigned int s = 1; h && s<nb_scales; ++s) h/=2; for (h = h?h:1; h<=_height; h*=2) res.draw_image(res.get_crop(0,0,0,0,h - 1,0).get_haar(true,1)); } } else { if (_depth>1) { unsigned int d = _depth; for (unsigned int s = 1; d && s<nb_scales; ++s) d/=2; for (d = d?d:1; d<=_depth; d*=2) res.draw_image(res.get_crop(0,0,0,0,0,d - 1).get_haar(true,1)); } else return *this; } } } else { // Direct transform res = get_haar(false,1); if (_width>1) { if (_height>1) { if (_depth>1) for (unsigned int s = 1, w = _width/2, h = _height/2, d = _depth/2; w && h && d && s<nb_scales; ++s, w/=2, h/=2, d/=2) res.draw_image(res.get_crop(0,0,0,w - 1,h - 1,d - 1).haar(false,1)); else for (unsigned int s = 1, w = _width/2, h = _height/2; w && h && s<nb_scales; ++s, w/=2, h/=2) res.draw_image(res.get_crop(0,0,0,w - 1,h - 1,0).haar(false,1)); } else { if (_depth>1) for (unsigned int s = 1, w = _width/2, d = _depth/2; w && d && s<nb_scales; ++s, w/=2, d/=2) res.draw_image(res.get_crop(0,0,0,w - 1,0,d - 1).haar(false,1)); else for (unsigned int s = 1, w = _width/2; w && s<nb_scales; ++s, w/=2) res.draw_image(res.get_crop(0,0,0,w - 1,0,0).haar(false,1)); } } else { if (_height>1) { if (_depth>1) for (unsigned int s = 1, h = _height/2, d = _depth/2; h && d && s<nb_scales; ++s, h/=2, d/=2) res.draw_image(res.get_crop(0,0,0,0,h - 1,d - 1).haar(false,1)); else for (unsigned int s = 1, h = _height/2; h && s<nb_scales; ++s, h/=2) res.draw_image(res.get_crop(0,0,0,0,h - 1,0).haar(false,1)); } else { if (_depth>1) for (unsigned int s = 1, d = _depth/2; d && s<nb_scales; ++s, d/=2) res.draw_image(res.get_crop(0,0,0,0,0,d - 1).haar(false,1)); else return *this; } } } return res; } return *this; } //! Compute 1D Fast Fourier Transform, along a specified axis. /** \param axis Axis along which the FFT is computed. \param is_inverse Tells if the forward (\c false) or inverse (\c true) FFT is computed. **/ CImgList<Tfloat> get_FFT(const char axis, const bool is_inverse=false) const { CImgList<Tfloat> res(*this,CImg<Tfloat>()); CImg<Tfloat>::FFT(res[0],res[1],axis,is_inverse); return res; } //! Compute n-D Fast Fourier Transform. /* \param is_inverse Tells if the forward (\c false) or inverse (\c true) FFT is computed. **/ CImgList<Tfloat> get_FFT(const bool is_inverse=false) const { CImgList<Tfloat> res(*this,CImg<Tfloat>()); CImg<Tfloat>::FFT(res[0],res[1],is_inverse); return res; } //! Compute 1D Fast Fourier Transform, along a specified axis. /** \param[in,out] real Real part of the pixel values. \param[in,out] imag Imaginary part of the pixel values. \param axis Axis along which the FFT is computed. \param is_inverse Tells if the forward (\c false) or inverse (\c true) FFT is computed. **/ static void FFT(CImg<T>& real, CImg<T>& imag, const char axis, const bool is_inverse=false, const unsigned int nb_threads=0) { if (!real) throw CImgInstanceException("CImg<%s>::FFT(): Specified real part is empty.", pixel_type()); if (!imag) imag.assign(real._width,real._height,real._depth,real._spectrum,(T)0); if (!real.is_sameXYZC(imag)) throw CImgInstanceException("CImg<%s>::FFT(): Specified real part (%u,%u,%u,%u,%p) and " "imaginary part (%u,%u,%u,%u,%p) have different dimensions.", pixel_type(), real._width,real._height,real._depth,real._spectrum,real._data, imag._width,imag._height,imag._depth,imag._spectrum,imag._data); const char _axis = cimg::lowercase(axis); if (_axis!='x' && _axis!='y' && _axis!='z') throw CImgArgumentException("CImgList<%s>::FFT(): Invalid specified axis '%c' for real and imaginary parts " "(%u,%u,%u,%u) " "(should be { x | y | z }).", pixel_type(),axis, real._width,real._height,real._depth,real._spectrum); cimg::unused(nb_threads); #ifdef cimg_use_fftw3 cimg::mutex(12); #ifndef cimg_use_fftw3_singlethread fftw_plan_with_nthreads(nb_threads?nb_threads:cimg::nb_cpus()); #endif fftw_complex *data_in = (fftw_complex*)fftw_malloc(sizeof(fftw_complex)*real._width*real._height*real._depth); if (!data_in) throw CImgInstanceException("CImgList<%s>::FFT(): Failed to allocate memory (%s) " "for computing FFT of image (%u,%u,%u,%u) along the X-axis.", pixel_type(), cimg::strbuffersize(sizeof(fftw_complex)*real._width), real._width,real._height,real._depth,real._spectrum); double *const ptrf = (double*)data_in; fftw_plan data_plan = _axis=='x'?fftw_plan_many_dft(1,(int*)&real._width,real.height()*real.depth(), data_in,0,1,real.width(), data_in,0,1,real.width(), is_inverse?FFTW_BACKWARD:FFTW_FORWARD,FFTW_ESTIMATE): _axis=='y'?fftw_plan_many_dft(1,(int*)&real._height,real.width()*real.depth(), data_in,0,real.width(),1, data_in,0,real.width(),1, is_inverse?FFTW_BACKWARD:FFTW_FORWARD,FFTW_ESTIMATE): fftw_plan_many_dft(1,(int*)&real._depth,real.width()*real.height(), data_in,0,real.width()*real.height(),1, data_in,0,real.width()*real.height(),1, is_inverse?FFTW_BACKWARD:FFTW_FORWARD,FFTW_ESTIMATE); cimg_forC(real,c) { CImg<T> realc = real.get_shared_channel(c), imagc = imag.get_shared_channel(c); cimg_pragma_openmp(parallel for cimg_openmp_if_size(real.width()*real.height()*real.depth(),125000)) cimg_rofoff(realc,i) { const ulongT i2 = 2*i; ptrf[i2] = (double)realc[i]; ptrf[i2 + 1] = (double)imagc[i]; } fftw_execute(data_plan); if (is_inverse) { const double a = 1.0/(_axis=='x'?real.width():_axis=='y'?real.height():real.depth()); cimg_pragma_openmp(parallel for cimg_openmp_if_size(real.width()*real.height()*real.depth(),125000)) cimg_rofoff(realc,i) { const ulongT i2 = 2*i; realc[i] = (T)(a*ptrf[i2]); imagc[i] = (T)(a*ptrf[i2 + 1]); } } else cimg_pragma_openmp(parallel for cimg_openmp_if_size(real.width()*real.height()*real.depth(),125000)) cimg_rofoff(realc,i) { const ulongT i2 = 2*i; realc[i] = (T)ptrf[i2]; imagc[i] = (T)ptrf[i2 + 1]; } } fftw_destroy_plan(data_plan); fftw_free(data_in); #ifndef cimg_use_fftw3_singlethread fftw_cleanup_threads(); #endif cimg::mutex(12,0); #else switch (_axis) { case 'x' : { // Fourier along X, using built-in functions const unsigned int N = real._width, N2 = N>>1; if (((N - 1)&N) && N!=1) throw CImgInstanceException("CImgList<%s>::FFT(): Specified real and imaginary parts (%u,%u,%u,%u) " "have non 2^N dimension along the X-axis.", pixel_type(), real._width,real._height,real._depth,real._spectrum); for (unsigned int i = 0, j = 0; i<N2; ++i) { if (j>i) cimg_forYZC(real,y,z,c) { cimg::swap(real(i,y,z,c),real(j,y,z,c)); cimg::swap(imag(i,y,z,c),imag(j,y,z,c)); if (j<N2) { const unsigned int ri = N - 1 - i, rj = N - 1 - j; cimg::swap(real(ri,y,z,c),real(rj,y,z,c)); cimg::swap(imag(ri,y,z,c),imag(rj,y,z,c)); } } for (unsigned int m = N, n = N2; (j+=n)>=m; j-=m, m = n, n>>=1) {} } for (unsigned int delta = 2; delta<=N; delta<<=1) { const unsigned int delta2 = delta>>1; for (unsigned int i = 0; i<N; i+=delta) { float wr = 1, wi = 0; const float angle = (float)((is_inverse?+1:-1)*2*cimg::PI/delta), ca = (float)std::cos(angle), sa = (float)std::sin(angle); for (unsigned int k = 0; k<delta2; ++k) { const unsigned int j = i + k, nj = j + delta2; cimg_forYZC(real,y,z,c) { T &ir = real(j,y,z,c), &ii = imag(j,y,z,c), &nir = real(nj,y,z,c), &nii = imag(nj,y,z,c); const float tmpr = (float)(wr*nir - wi*nii), tmpi = (float)(wr*nii + wi*nir); nir = (T)(ir - tmpr); nii = (T)(ii - tmpi); ir+=(T)tmpr; ii+=(T)tmpi; } const float nwr = wr*ca-wi*sa; wi = wi*ca + wr*sa; wr = nwr; } } } if (is_inverse) { real/=N; imag/=N; } } break; case 'y' : { // Fourier along Y, using built-in functions const unsigned int N = real._height, N2 = N>>1; if (((N - 1)&N) && N!=1) throw CImgInstanceException("CImgList<%s>::FFT(): Specified real and imaginary parts (%u,%u,%u,%u) " "have non 2^N dimension along the Y-axis.", pixel_type(), real._width,real._height,real._depth,real._spectrum); for (unsigned int i = 0, j = 0; i<N2; ++i) { if (j>i) cimg_forXZC(real,x,z,c) { cimg::swap(real(x,i,z,c),real(x,j,z,c)); cimg::swap(imag(x,i,z,c),imag(x,j,z,c)); if (j<N2) { const unsigned int ri = N - 1 - i, rj = N - 1 - j; cimg::swap(real(x,ri,z,c),real(x,rj,z,c)); cimg::swap(imag(x,ri,z,c),imag(x,rj,z,c)); } } for (unsigned int m = N, n = N2; (j+=n)>=m; j-=m, m = n, n>>=1) {} } for (unsigned int delta = 2; delta<=N; delta<<=1) { const unsigned int delta2 = (delta>>1); for (unsigned int i = 0; i<N; i+=delta) { float wr = 1, wi = 0; const float angle = (float)((is_inverse?+1:-1)*2*cimg::PI/delta), ca = (float)std::cos(angle), sa = (float)std::sin(angle); for (unsigned int k = 0; k<delta2; ++k) { const unsigned int j = i + k, nj = j + delta2; cimg_forXZC(real,x,z,c) { T &ir = real(x,j,z,c), &ii = imag(x,j,z,c), &nir = real(x,nj,z,c), &nii = imag(x,nj,z,c); const float tmpr = (float)(wr*nir - wi*nii), tmpi = (float)(wr*nii + wi*nir); nir = (T)(ir - tmpr); nii = (T)(ii - tmpi); ir+=(T)tmpr; ii+=(T)tmpi; } const float nwr = wr*ca-wi*sa; wi = wi*ca + wr*sa; wr = nwr; } } } if (is_inverse) { real/=N; imag/=N; } } break; default : { // Fourier along Z, using built-in functions const unsigned int N = real._depth, N2 = N>>1; if (((N - 1)&N) && N!=1) throw CImgInstanceException("CImgList<%s>::FFT(): Specified real and imaginary parts (%u,%u,%u,%u) " "have non 2^N dimension along the Z-axis.", pixel_type(), real._width,real._height,real._depth,real._spectrum); for (unsigned int i = 0, j = 0; i<N2; ++i) { if (j>i) cimg_forXYC(real,x,y,c) { cimg::swap(real(x,y,i,c),real(x,y,j,c)); cimg::swap(imag(x,y,i,c),imag(x,y,j,c)); if (j<N2) { const unsigned int ri = N - 1 - i, rj = N - 1 - j; cimg::swap(real(x,y,ri,c),real(x,y,rj,c)); cimg::swap(imag(x,y,ri,c),imag(x,y,rj,c)); } } for (unsigned int m = N, n = N2; (j+=n)>=m; j-=m, m = n, n>>=1) {} } for (unsigned int delta = 2; delta<=N; delta<<=1) { const unsigned int delta2 = (delta>>1); for (unsigned int i = 0; i<N; i+=delta) { float wr = 1, wi = 0; const float angle = (float)((is_inverse?+1:-1)*2*cimg::PI/delta), ca = (float)std::cos(angle), sa = (float)std::sin(angle); for (unsigned int k = 0; k<delta2; ++k) { const unsigned int j = i + k, nj = j + delta2; cimg_forXYC(real,x,y,c) { T &ir = real(x,y,j,c), &ii = imag(x,y,j,c), &nir = real(x,y,nj,c), &nii = imag(x,y,nj,c); const float tmpr = (float)(wr*nir - wi*nii), tmpi = (float)(wr*nii + wi*nir); nir = (T)(ir - tmpr); nii = (T)(ii - tmpi); ir+=(T)tmpr; ii+=(T)tmpi; } const float nwr = wr*ca-wi*sa; wi = wi*ca + wr*sa; wr = nwr; } } } if (is_inverse) { real/=N; imag/=N; } } break; } #endif } //! Compute n-D Fast Fourier Transform. /** \param[in,out] real Real part of the pixel values. \param[in,out] imag Imaginary part of the pixel values. \param is_inverse Tells if the forward (\c false) or inverse (\c true) FFT is computed. \param nb_threads Number of parallel threads used for the computation. Use \c 0 to set this to the number of available cpus. **/ static void FFT(CImg<T>& real, CImg<T>& imag, const bool is_inverse=false, const unsigned int nb_threads=0) { if (!real) throw CImgInstanceException("CImgList<%s>::FFT(): Empty specified real part.", pixel_type()); if (!imag) imag.assign(real._width,real._height,real._depth,real._spectrum,(T)0); if (!real.is_sameXYZC(imag)) throw CImgInstanceException("CImgList<%s>::FFT(): Specified real part (%u,%u,%u,%u,%p) and " "imaginary part (%u,%u,%u,%u,%p) have different dimensions.", pixel_type(), real._width,real._height,real._depth,real._spectrum,real._data, imag._width,imag._height,imag._depth,imag._spectrum,imag._data); cimg::unused(nb_threads); #ifdef cimg_use_fftw3 cimg::mutex(12); #ifndef cimg_use_fftw3_singlethread fftw_plan_with_nthreads(nb_threads?nb_threads:cimg::nb_cpus()); #endif fftw_complex *data_in = (fftw_complex*)fftw_malloc(sizeof(fftw_complex)*real._width*real._height*real._depth); if (!data_in) throw CImgInstanceException("CImgList<%s>::FFT(): Failed to allocate memory (%s) " "for computing FFT of image (%u,%u,%u,%u).", pixel_type(), cimg::strbuffersize(sizeof(fftw_complex)*real._width* real._height*real._depth*real._spectrum), real._width,real._height,real._depth,real._spectrum); double *const ptrf = (double*)data_in; fftw_plan data_plan = real._depth>1?fftw_plan_dft_3d(real._depth,real._height,real._width,data_in,data_in, is_inverse?FFTW_BACKWARD:FFTW_FORWARD,FFTW_ESTIMATE): real._height>1?fftw_plan_dft_2d(real._height,real._width,data_in,data_in, is_inverse?FFTW_BACKWARD:FFTW_FORWARD,FFTW_ESTIMATE): fftw_plan_dft_1d(real._width,data_in,data_in, is_inverse?FFTW_BACKWARD:FFTW_FORWARD,FFTW_ESTIMATE); cimg_forC(real,c) { CImg<T> realc = real.get_shared_channel(c), imagc = imag.get_shared_channel(c); cimg_pragma_openmp(parallel for cimg_openmp_if_size(real.width()*real.height()*real.depth(),125000)) cimg_rofoff(realc,i) { const ulongT i2 = 2*i; ptrf[i2] = (double)realc[i]; ptrf[i2 + 1] = (double)imagc[i]; } fftw_execute(data_plan); if (is_inverse) { const double a = 1.0/(real.width()*real.height()*real.depth()); cimg_pragma_openmp(parallel for cimg_openmp_if_size(real.width()*real.height()*real.depth(),125000)) cimg_rofoff(realc,i) { const ulongT i2 = 2*i; realc[i] = (T)(a*ptrf[i2]); imagc[i] = (T)(a*ptrf[i2 + 1]); } } else cimg_pragma_openmp(parallel for cimg_openmp_if_size(real.width()*real.height()*real.depth(),125000)) cimg_rofoff(realc,i) { const ulongT i2 = 2*i; realc[i] = (T)ptrf[i2]; imagc[i] = (T)ptrf[i2 + 1]; } } fftw_destroy_plan(data_plan); fftw_free(data_in); #ifndef cimg_use_fftw3_singlethread fftw_cleanup_threads(); #endif cimg::mutex(12,0); #else if (real._depth>1) FFT(real,imag,'z',is_inverse); if (real._height>1) FFT(real,imag,'y',is_inverse); if (real._width>1) FFT(real,imag,'x',is_inverse); #endif } //@} //------------------------------------- // //! \name 3D Objects Management //@{ //------------------------------------- //! Shift 3D object's vertices. /** \param tx X-coordinate of the 3D displacement vector. \param ty Y-coordinate of the 3D displacement vector. \param tz Z-coordinate of the 3D displacement vector. **/ CImg<T>& shift_object3d(const float tx, const float ty=0, const float tz=0) { if (_height!=3 || _depth>1 || _spectrum>1) throw CImgInstanceException(_cimg_instance "shift_object3d(): Instance is not a set of 3D vertices.", cimg_instance); get_shared_row(0)+=tx; get_shared_row(1)+=ty; get_shared_row(2)+=tz; return *this; } //! Shift 3D object's vertices \newinstance. CImg<Tfloat> get_shift_object3d(const float tx, const float ty=0, const float tz=0) const { return CImg<Tfloat>(*this,false).shift_object3d(tx,ty,tz); } //! Shift 3D object's vertices, so that it becomes centered. /** \note The object center is computed as its barycenter. **/ CImg<T>& shift_object3d() { if (_height!=3 || _depth>1 || _spectrum>1) throw CImgInstanceException(_cimg_instance "shift_object3d(): Instance is not a set of 3D vertices.", cimg_instance); CImg<T> xcoords = get_shared_row(0), ycoords = get_shared_row(1), zcoords = get_shared_row(2); float xm, xM = (float)xcoords.max_min(xm), ym, yM = (float)ycoords.max_min(ym), zm, zM = (float)zcoords.max_min(zm); xcoords-=(xm + xM)/2; ycoords-=(ym + yM)/2; zcoords-=(zm + zM)/2; return *this; } //! Shift 3D object's vertices, so that it becomes centered \newinstance. CImg<Tfloat> get_shift_object3d() const { return CImg<Tfloat>(*this,false).shift_object3d(); } //! Resize 3D object. /** \param sx Width of the 3D object's bounding box. \param sy Height of the 3D object's bounding box. \param sz Depth of the 3D object's bounding box. **/ CImg<T>& resize_object3d(const float sx, const float sy=-100, const float sz=-100) { if (_height!=3 || _depth>1 || _spectrum>1) throw CImgInstanceException(_cimg_instance "resize_object3d(): Instance is not a set of 3D vertices.", cimg_instance); CImg<T> xcoords = get_shared_row(0), ycoords = get_shared_row(1), zcoords = get_shared_row(2); float xm, xM = (float)xcoords.max_min(xm), ym, yM = (float)ycoords.max_min(ym), zm, zM = (float)zcoords.max_min(zm); if (xm<xM) { if (sx>0) xcoords*=sx/(xM-xm); else xcoords*=-sx/100; } if (ym<yM) { if (sy>0) ycoords*=sy/(yM-ym); else ycoords*=-sy/100; } if (zm<zM) { if (sz>0) zcoords*=sz/(zM-zm); else zcoords*=-sz/100; } return *this; } //! Resize 3D object \newinstance. CImg<Tfloat> get_resize_object3d(const float sx, const float sy=-100, const float sz=-100) const { return CImg<Tfloat>(*this,false).resize_object3d(sx,sy,sz); } //! Resize 3D object to unit size. CImg<T> resize_object3d() { if (_height!=3 || _depth>1 || _spectrum>1) throw CImgInstanceException(_cimg_instance "resize_object3d(): Instance is not a set of 3D vertices.", cimg_instance); CImg<T> xcoords = get_shared_row(0), ycoords = get_shared_row(1), zcoords = get_shared_row(2); float xm, xM = (float)xcoords.max_min(xm), ym, yM = (float)ycoords.max_min(ym), zm, zM = (float)zcoords.max_min(zm); const float dx = xM - xm, dy = yM - ym, dz = zM - zm, dmax = cimg::max(dx,dy,dz); if (dmax>0) { xcoords/=dmax; ycoords/=dmax; zcoords/=dmax; } return *this; } //! Resize 3D object to unit size \newinstance. CImg<Tfloat> get_resize_object3d() const { return CImg<Tfloat>(*this,false).resize_object3d(); } //! Merge two 3D objects together. /** \param[in,out] primitives Primitives data of the current 3D object. \param obj_vertices Vertices data of the additional 3D object. \param obj_primitives Primitives data of the additional 3D object. **/ template<typename tf, typename tp, typename tff> CImg<T>& append_object3d(CImgList<tf>& primitives, const CImg<tp>& obj_vertices, const CImgList<tff>& obj_primitives) { if (!obj_vertices || !obj_primitives) return *this; if (obj_vertices._height!=3 || obj_vertices._depth>1 || obj_vertices._spectrum>1) throw CImgInstanceException(_cimg_instance "append_object3d(): Specified vertice image (%u,%u,%u,%u,%p) is not a " "set of 3D vertices.", cimg_instance, obj_vertices._width,obj_vertices._height, obj_vertices._depth,obj_vertices._spectrum,obj_vertices._data); if (is_empty()) { primitives.assign(obj_primitives); return assign(obj_vertices); } if (_height!=3 || _depth>1 || _spectrum>1) throw CImgInstanceException(_cimg_instance "append_object3d(): Instance is not a set of 3D vertices.", cimg_instance); const unsigned int P = _width; append(obj_vertices,'x'); const unsigned int N = primitives._width; primitives.insert(obj_primitives); for (unsigned int i = N; i<primitives._width; ++i) { CImg<tf> &p = primitives[i]; switch (p.size()) { case 1 : p[0]+=P; break; // Point case 5 : p[0]+=P; p[1]+=P; break; // Sphere case 2 : case 6 : p[0]+=P; p[1]+=P; break; // Segment case 3 : case 9 : p[0]+=P; p[1]+=P; p[2]+=P; break; // Triangle case 4 : case 12 : p[0]+=P; p[1]+=P; p[2]+=P; p[3]+=P; break; // Rectangle } } return *this; } //! Texturize primitives of a 3D object. /** \param[in,out] primitives Primitives data of the 3D object. \param[in,out] colors Colors data of the 3D object. \param texture Texture image to map to 3D object. \param coords Texture-mapping coordinates. **/ template<typename tp, typename tc, typename tt, typename tx> const CImg<T>& texturize_object3d(CImgList<tp>& primitives, CImgList<tc>& colors, const CImg<tt>& texture, const CImg<tx>& coords=CImg<tx>::const_empty()) const { if (is_empty()) return *this; if (_height!=3) throw CImgInstanceException(_cimg_instance "texturize_object3d(): image instance is not a set of 3D points.", cimg_instance); if (coords && (coords._width!=_width || coords._height!=2)) throw CImgArgumentException(_cimg_instance "texturize_object3d(): Invalid specified texture coordinates (%u,%u,%u,%u,%p).", cimg_instance, coords._width,coords._height,coords._depth,coords._spectrum,coords._data); CImg<intT> _coords; if (!coords) { // If no texture coordinates specified, do a default XY-projection _coords.assign(_width,2); float xmin, xmax = (float)get_shared_row(0).max_min(xmin), ymin, ymax = (float)get_shared_row(1).max_min(ymin), dx = xmax>xmin?xmax-xmin:1, dy = ymax>ymin?ymax-ymin:1; cimg_forX(*this,p) { _coords(p,0) = (int)(((*this)(p,0) - xmin)*texture._width/dx); _coords(p,1) = (int)(((*this)(p,1) - ymin)*texture._height/dy); } } else _coords = coords; int texture_ind = -1; cimglist_for(primitives,l) { CImg<tp> &p = primitives[l]; const unsigned int siz = p.size(); switch (siz) { case 1 : { // Point const unsigned int i0 = (unsigned int)p[0]; const int x0 = _coords(i0,0), y0 = _coords(i0,1); texture.get_vector_at(x0<=0?0:x0>=texture.width()?texture.width() - 1:x0, y0<=0?0:y0>=texture.height()?texture.height() - 1:y0).move_to(colors[l]); } break; case 2 : case 6 : { // Line const unsigned int i0 = (unsigned int)p[0], i1 = (unsigned int)p[1]; const int x0 = _coords(i0,0), y0 = _coords(i0,1), x1 = _coords(i1,0), y1 = _coords(i1,1); if (texture_ind<0) colors[texture_ind=l].assign(texture,false); else colors[l].assign(colors[texture_ind],true); CImg<tp>::vector(i0,i1,x0,y0,x1,y1).move_to(p); } break; case 3 : case 9 : { // Triangle const unsigned int i0 = (unsigned int)p[0], i1 = (unsigned int)p[1], i2 = (unsigned int)p[2]; const int x0 = _coords(i0,0), y0 = _coords(i0,1), x1 = _coords(i1,0), y1 = _coords(i1,1), x2 = _coords(i2,0), y2 = _coords(i2,1); if (texture_ind<0) colors[texture_ind=l].assign(texture,false); else colors[l].assign(colors[texture_ind],true); CImg<tp>::vector(i0,i1,i2,x0,y0,x1,y1,x2,y2).move_to(p); } break; case 4 : case 12 : { // Quadrangle const unsigned int i0 = (unsigned int)p[0], i1 = (unsigned int)p[1], i2 = (unsigned int)p[2], i3 = (unsigned int)p[3]; const int x0 = _coords(i0,0), y0 = _coords(i0,1), x1 = _coords(i1,0), y1 = _coords(i1,1), x2 = _coords(i2,0), y2 = _coords(i2,1), x3 = _coords(i3,0), y3 = _coords(i3,1); if (texture_ind<0) colors[texture_ind=l].assign(texture,false); else colors[l].assign(colors[texture_ind],true); CImg<tp>::vector(i0,i1,i2,i3,x0,y0,x1,y1,x2,y2,x3,y3).move_to(p); } break; } } return *this; } //! Generate a 3D elevation of the image instance. /** \param[out] primitives The returned list of the 3D object primitives (template type \e tf should be at least \e unsigned \e int). \param[out] colors The returned list of the 3D object colors. \param elevation The input elevation map. \return The N vertices (xi,yi,zi) of the 3D object as a Nx3 CImg<float> image (0<=i<=N - 1). \par Example \code const CImg<float> img("reference.jpg"); CImgList<unsigned int> faces3d; CImgList<unsigned char> colors3d; const CImg<float> points3d = img.get_elevation3d(faces3d,colors3d,img.get_norm()*0.2); CImg<unsigned char>().display_object3d("Elevation3d",points3d,faces3d,colors3d); \endcode \image html ref_elevation3d.jpg **/ template<typename tf, typename tc, typename te> CImg<floatT> get_elevation3d(CImgList<tf>& primitives, CImgList<tc>& colors, const CImg<te>& elevation) const { if (!is_sameXY(elevation) || elevation._depth>1 || elevation._spectrum>1) throw CImgArgumentException(_cimg_instance "get_elevation3d(): Instance and specified elevation (%u,%u,%u,%u,%p) " "have incompatible dimensions.", cimg_instance, elevation._width,elevation._height,elevation._depth, elevation._spectrum,elevation._data); if (is_empty()) return *this; float m, M = (float)max_min(m); if (M==m) ++M; colors.assign(); const unsigned int size_x1 = _width - 1, size_y1 = _height - 1; for (unsigned int y = 0; y<size_y1; ++y) for (unsigned int x = 0; x<size_x1; ++x) { const unsigned char r = (unsigned char)(((*this)(x,y,0) - m)*255/(M-m)), g = (unsigned char)(_spectrum>1?((*this)(x,y,1) - m)*255/(M-m):r), b = (unsigned char)(_spectrum>2?((*this)(x,y,2) - m)*255/(M-m):_spectrum>1?0:r); CImg<tc>::vector((tc)r,(tc)g,(tc)b).move_to(colors); } const typename CImg<te>::_functor2d_int func(elevation); return elevation3d(primitives,func,0,0,_width - 1.f,_height - 1.f,_width,_height); } //! Generate the 3D projection planes of the image instance. /** \param[out] primitives Primitives data of the returned 3D object. \param[out] colors Colors data of the returned 3D object. \param x0 X-coordinate of the projection point. \param y0 Y-coordinate of the projection point. \param z0 Z-coordinate of the projection point. \param normalize_colors Tells if the created textures have normalized colors. **/ template<typename tf, typename tc> CImg<floatT> get_projections3d(CImgList<tf>& primitives, CImgList<tc>& colors, const unsigned int x0, const unsigned int y0, const unsigned int z0, const bool normalize_colors=false) const { float m = 0, M = 0, delta = 1; if (normalize_colors) { m = (float)min_max(M); delta = 255/(m==M?1:M-m); } const unsigned int _x0 = (x0>=_width)?_width - 1:x0, _y0 = (y0>=_height)?_height - 1:y0, _z0 = (z0>=_depth)?_depth - 1:z0; CImg<tc> img_xy, img_xz, img_yz; if (normalize_colors) { ((get_crop(0,0,_z0,0,_width - 1,_height - 1,_z0,_spectrum - 1)-=m)*=delta).move_to(img_xy); ((get_crop(0,_y0,0,0,_width - 1,_y0,_depth - 1,_spectrum - 1)-=m)*=delta).resize(_width,_depth,1,-100,-1). move_to(img_xz); ((get_crop(_x0,0,0,0,_x0,_height - 1,_depth - 1,_spectrum - 1)-=m)*=delta).resize(_height,_depth,1,-100,-1). move_to(img_yz); } else { get_crop(0,0,_z0,0,_width - 1,_height - 1,_z0,_spectrum - 1).move_to(img_xy); get_crop(0,_y0,0,0,_width - 1,_y0,_depth - 1,_spectrum - 1).resize(_width,_depth,1,-100,-1).move_to(img_xz); get_crop(_x0,0,0,0,_x0,_height - 1,_depth - 1,_spectrum - 1).resize(_height,_depth,1,-100,-1).move_to(img_yz); } CImg<floatT> points(12,3,1,1, 0,_width - 1,_width - 1,0, 0,_width - 1,_width - 1,0, _x0,_x0,_x0,_x0, 0,0,_height - 1,_height - 1, _y0,_y0,_y0,_y0, 0,_height - 1,_height - 1,0, _z0,_z0,_z0,_z0, 0,0,_depth - 1,_depth - 1, 0,0,_depth - 1,_depth - 1); primitives.assign(); CImg<tf>::vector(0,1,2,3,0,0,img_xy._width - 1,0,img_xy._width - 1,img_xy._height - 1,0,img_xy._height - 1). move_to(primitives); CImg<tf>::vector(4,5,6,7,0,0,img_xz._width - 1,0,img_xz._width - 1,img_xz._height - 1,0,img_xz._height - 1). move_to(primitives); CImg<tf>::vector(8,9,10,11,0,0,img_yz._width - 1,0,img_yz._width - 1,img_yz._height - 1,0,img_yz._height - 1). move_to(primitives); colors.assign(); img_xy.move_to(colors); img_xz.move_to(colors); img_yz.move_to(colors); return points; } //! Generate a isoline of the image instance as a 3D object. /** \param[out] primitives The returned list of the 3D object primitives (template type \e tf should be at least \e unsigned \e int). \param isovalue The returned list of the 3D object colors. \param size_x The number of subdivisions along the X-axis. \param size_y The number of subdisivions along the Y-axis. \return The N vertices (xi,yi,zi) of the 3D object as a Nx3 CImg<float> image (0<=i<=N - 1). \par Example \code const CImg<float> img("reference.jpg"); CImgList<unsigned int> faces3d; const CImg<float> points3d = img.get_isoline3d(faces3d,100); CImg<unsigned char>().display_object3d("Isoline3d",points3d,faces3d,colors3d); \endcode \image html ref_isoline3d.jpg **/ template<typename tf> CImg<floatT> get_isoline3d(CImgList<tf>& primitives, const float isovalue, const int size_x=-100, const int size_y=-100) const { if (_spectrum>1) throw CImgInstanceException(_cimg_instance "get_isoline3d(): Instance is not a scalar image.", cimg_instance); if (_depth>1) throw CImgInstanceException(_cimg_instance "get_isoline3d(): Instance is not a 2D image.", cimg_instance); primitives.assign(); if (is_empty()) return *this; CImg<floatT> vertices; if ((size_x==-100 && size_y==-100) || (size_x==width() && size_y==height())) { const _functor2d_int func(*this); vertices = isoline3d(primitives,func,isovalue,0,0,width() - 1.f,height() - 1.f,width(),height()); } else { const _functor2d_float func(*this); vertices = isoline3d(primitives,func,isovalue,0,0,width() - 1.f,height() - 1.f,size_x,size_y); } return vertices; } //! Generate an isosurface of the image instance as a 3D object. /** \param[out] primitives The returned list of the 3D object primitives (template type \e tf should be at least \e unsigned \e int). \param isovalue The returned list of the 3D object colors. \param size_x Number of subdivisions along the X-axis. \param size_y Number of subdisivions along the Y-axis. \param size_z Number of subdisivions along the Z-axis. \return The N vertices (xi,yi,zi) of the 3D object as a Nx3 CImg<float> image (0<=i<=N - 1). \par Example \code const CImg<float> img = CImg<unsigned char>("reference.jpg").resize(-100,-100,20); CImgList<unsigned int> faces3d; const CImg<float> points3d = img.get_isosurface3d(faces3d,100); CImg<unsigned char>().display_object3d("Isosurface3d",points3d,faces3d,colors3d); \endcode \image html ref_isosurface3d.jpg **/ template<typename tf> CImg<floatT> get_isosurface3d(CImgList<tf>& primitives, const float isovalue, const int size_x=-100, const int size_y=-100, const int size_z=-100) const { if (_spectrum>1) throw CImgInstanceException(_cimg_instance "get_isosurface3d(): Instance is not a scalar image.", cimg_instance); primitives.assign(); if (is_empty()) return *this; CImg<floatT> vertices; if ((size_x==-100 && size_y==-100 && size_z==-100) || (size_x==width() && size_y==height() && size_z==depth())) { const _functor3d_int func(*this); vertices = isosurface3d(primitives,func,isovalue,0,0,0,width() - 1.f,height() - 1.f,depth() - 1.f, width(),height(),depth()); } else { const _functor3d_float func(*this); vertices = isosurface3d(primitives,func,isovalue,0,0,0,width() - 1.f,height() - 1.f,depth() - 1.f, size_x,size_y,size_z); } return vertices; } //! Compute 3D elevation of a function as a 3D object. /** \param[out] primitives Primitives data of the resulting 3D object. \param func Elevation function. Is of type <tt>float (*func)(const float x,const float y)</tt>. \param x0 X-coordinate of the starting point. \param y0 Y-coordinate of the starting point. \param x1 X-coordinate of the ending point. \param y1 Y-coordinate of the ending point. \param size_x Resolution of the function along the X-axis. \param size_y Resolution of the function along the Y-axis. **/ template<typename tf, typename tfunc> static CImg<floatT> elevation3d(CImgList<tf>& primitives, const tfunc& func, const float x0, const float y0, const float x1, const float y1, const int size_x=256, const int size_y=256) { const float nx0 = x0<x1?x0:x1, ny0 = y0<y1?y0:y1, nx1 = x0<x1?x1:x0, ny1 = y0<y1?y1:y0; const unsigned int _nsize_x = (unsigned int)(size_x>=0?size_x:(nx1-nx0)*-size_x/100), nsize_x = _nsize_x?_nsize_x:1, nsize_x1 = nsize_x - 1, _nsize_y = (unsigned int)(size_y>=0?size_y:(ny1-ny0)*-size_y/100), nsize_y = _nsize_y?_nsize_y:1, nsize_y1 = nsize_y - 1; if (nsize_x<2 || nsize_y<2) throw CImgArgumentException("CImg<%s>::elevation3d(): Invalid specified size (%d,%d).", pixel_type(), nsize_x,nsize_y); CImg<floatT> vertices(nsize_x*nsize_y,3); floatT *ptr_x = vertices.data(0,0), *ptr_y = vertices.data(0,1), *ptr_z = vertices.data(0,2); for (unsigned int y = 0; y<nsize_y; ++y) { const float Y = ny0 + y*(ny1-ny0)/nsize_y1; for (unsigned int x = 0; x<nsize_x; ++x) { const float X = nx0 + x*(nx1-nx0)/nsize_x1; *(ptr_x++) = (float)x; *(ptr_y++) = (float)y; *(ptr_z++) = (float)func(X,Y); } } primitives.assign(nsize_x1*nsize_y1,1,4); for (unsigned int p = 0, y = 0; y<nsize_y1; ++y) { const unsigned int yw = y*nsize_x; for (unsigned int x = 0; x<nsize_x1; ++x) { const unsigned int xpyw = x + yw, xpyww = xpyw + nsize_x; primitives[p++].fill(xpyw,xpyww,xpyww + 1,xpyw + 1); } } return vertices; } //! Compute 3D elevation of a function, as a 3D object \overloading. template<typename tf> static CImg<floatT> elevation3d(CImgList<tf>& primitives, const char *const expression, const float x0, const float y0, const float x1, const float y1, const int size_x=256, const int size_y=256) { const _functor2d_expr func(expression); return elevation3d(primitives,func,x0,y0,x1,y1,size_x,size_y); } //! Compute 0-isolines of a function, as a 3D object. /** \param[out] primitives Primitives data of the resulting 3D object. \param func Elevation function. Is of type <tt>float (*func)(const float x,const float y)</tt>. \param isovalue Isovalue to extract from function. \param x0 X-coordinate of the starting point. \param y0 Y-coordinate of the starting point. \param x1 X-coordinate of the ending point. \param y1 Y-coordinate of the ending point. \param size_x Resolution of the function along the X-axis. \param size_y Resolution of the function along the Y-axis. \note Use the marching squares algorithm for extracting the isolines. **/ template<typename tf, typename tfunc> static CImg<floatT> isoline3d(CImgList<tf>& primitives, const tfunc& func, const float isovalue, const float x0, const float y0, const float x1, const float y1, const int size_x=256, const int size_y=256) { static const unsigned int edges[16] = { 0x0, 0x9, 0x3, 0xa, 0x6, 0xf, 0x5, 0xc, 0xc, 0x5, 0xf, 0x6, 0xa, 0x3, 0x9, 0x0 }; static const int segments[16][4] = { { -1,-1,-1,-1 }, { 0,3,-1,-1 }, { 0,1,-1,-1 }, { 1,3,-1,-1 }, { 1,2,-1,-1 }, { 0,1,2,3 }, { 0,2,-1,-1 }, { 2,3,-1,-1 }, { 2,3,-1,-1 }, { 0,2,-1,-1}, { 0,3,1,2 }, { 1,2,-1,-1 }, { 1,3,-1,-1 }, { 0,1,-1,-1}, { 0,3,-1,-1}, { -1,-1,-1,-1 } }; const unsigned int _nx = (unsigned int)(size_x>=0?size_x:cimg::round((x1-x0)*-size_x/100 + 1)), _ny = (unsigned int)(size_y>=0?size_y:cimg::round((y1-y0)*-size_y/100 + 1)), nx = _nx?_nx:1, ny = _ny?_ny:1, nxm1 = nx - 1, nym1 = ny - 1; primitives.assign(); if (!nxm1 || !nym1) return CImg<floatT>(); const float dx = (x1 - x0)/nxm1, dy = (y1 - y0)/nym1; CImgList<floatT> vertices; CImg<intT> indices1(nx,1,1,2,-1), indices2(nx,1,1,2); CImg<floatT> values1(nx), values2(nx); float X = x0, Y = y0, nX = X + dx, nY = Y + dy; // Fill first line with values cimg_forX(values1,x) { values1(x) = (float)func(X,Y); X+=dx; } // Run the marching squares algorithm for (unsigned int yi = 0, nyi = 1; yi<nym1; ++yi, ++nyi, Y=nY, nY+=dy) { X = x0; nX = X + dx; indices2.fill(-1); for (unsigned int xi = 0, nxi = 1; xi<nxm1; ++xi, ++nxi, X=nX, nX+=dx) { // Determine square configuration const float val0 = values1(xi), val1 = values1(nxi), val2 = values2(nxi) = (float)func(nX,nY), val3 = values2(xi) = (float)func(X,nY); const unsigned int configuration = (val0<isovalue?1U:0U) | (val1<isovalue?2U:0U) | (val2<isovalue?4U:0U) | (val3<isovalue?8U:0U), edge = edges[configuration]; // Compute intersection vertices if (edge) { if ((edge&1) && indices1(xi,0)<0) { const float Xi = X + (isovalue-val0)*dx/(val1-val0); indices1(xi,0) = vertices.width(); CImg<floatT>::vector(Xi,Y,0).move_to(vertices); } if ((edge&2) && indices1(nxi,1)<0) { const float Yi = Y + (isovalue-val1)*dy/(val2-val1); indices1(nxi,1) = vertices.width(); CImg<floatT>::vector(nX,Yi,0).move_to(vertices); } if ((edge&4) && indices2(xi,0)<0) { const float Xi = X + (isovalue-val3)*dx/(val2-val3); indices2(xi,0) = vertices.width(); CImg<floatT>::vector(Xi,nY,0).move_to(vertices); } if ((edge&8) && indices1(xi,1)<0) { const float Yi = Y + (isovalue-val0)*dy/(val3-val0); indices1(xi,1) = vertices.width(); CImg<floatT>::vector(X,Yi,0).move_to(vertices); } // Create segments for (const int *segment = segments[configuration]; *segment!=-1; ) { const unsigned int p0 = (unsigned int)*(segment++), p1 = (unsigned int)*(segment++); const tf i0 = (tf)(_isoline3d_index(p0,indices1,indices2,xi,nxi)), i1 = (tf)(_isoline3d_index(p1,indices1,indices2,xi,nxi)); CImg<tf>::vector(i0,i1).move_to(primitives); } } } values1.swap(values2); indices1.swap(indices2); } return vertices>'x'; } //! Compute isolines of a function, as a 3D object \overloading. template<typename tf> static CImg<floatT> isoline3d(CImgList<tf>& primitives, const char *const expression, const float isovalue, const float x0, const float y0, const float x1, const float y1, const int size_x=256, const int size_y=256) { const _functor2d_expr func(expression); return isoline3d(primitives,func,isovalue,x0,y0,x1,y1,size_x,size_y); } template<typename t> static int _isoline3d_index(const unsigned int edge, const CImg<t>& indices1, const CImg<t>& indices2, const unsigned int x, const unsigned int nx) { switch (edge) { case 0 : return (int)indices1(x,0); case 1 : return (int)indices1(nx,1); case 2 : return (int)indices2(x,0); case 3 : return (int)indices1(x,1); } return 0; } //! Compute isosurface of a function, as a 3D object. /** \param[out] primitives Primitives data of the resulting 3D object. \param func Implicit function. Is of type <tt>float (*func)(const float x, const float y, const float z)</tt>. \param isovalue Isovalue to extract. \param x0 X-coordinate of the starting point. \param y0 Y-coordinate of the starting point. \param z0 Z-coordinate of the starting point. \param x1 X-coordinate of the ending point. \param y1 Y-coordinate of the ending point. \param z1 Z-coordinate of the ending point. \param size_x Resolution of the elevation function along the X-axis. \param size_y Resolution of the elevation function along the Y-axis. \param size_z Resolution of the elevation function along the Z-axis. \note Use the marching cubes algorithm for extracting the isosurface. **/ template<typename tf, typename tfunc> static CImg<floatT> isosurface3d(CImgList<tf>& primitives, const tfunc& func, const float isovalue, const float x0, const float y0, const float z0, const float x1, const float y1, const float z1, const int size_x=32, const int size_y=32, const int size_z=32) { static const unsigned int edges[256] = { 0x000, 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, 0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00, 0x190, 0x99 , 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c, 0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90, 0x230, 0x339, 0x33 , 0x13a, 0x636, 0x73f, 0x435, 0x53c, 0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30, 0x3a0, 0x2a9, 0x1a3, 0xaa , 0x7a6, 0x6af, 0x5a5, 0x4ac, 0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0, 0x460, 0x569, 0x663, 0x76a, 0x66 , 0x16f, 0x265, 0x36c, 0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60, 0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0xff , 0x3f5, 0x2fc, 0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0, 0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x55 , 0x15c, 0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950, 0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0xcc , 0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0, 0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc, 0xcc , 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0, 0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c, 0x15c, 0x55 , 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650, 0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc, 0x2fc, 0x3f5, 0xff , 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0, 0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c, 0x36c, 0x265, 0x16f, 0x66 , 0x76a, 0x663, 0x569, 0x460, 0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac, 0x4ac, 0x5a5, 0x6af, 0x7a6, 0xaa , 0x1a3, 0x2a9, 0x3a0, 0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c, 0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x33 , 0x339, 0x230, 0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c, 0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x99 , 0x190, 0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c, 0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x000 }; static const int triangles[256][16] = { { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1 }, { 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1 }, { 3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1 }, { 3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1 }, { 9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1 }, { 9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1 }, { 2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1 }, { 8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1 }, { 9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1 }, { 4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1 }, { 3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1 }, { 1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1 }, { 4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1 }, { 4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1 }, { 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1 }, { 5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1 }, { 2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1 }, { 9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1 }, { 0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1 }, { 2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1 }, { 10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1 }, { 4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1 }, { 5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1 }, { 5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1 }, { 9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1 }, { 0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1 }, { 1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1 }, { 10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1 }, { 8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1 }, { 2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1 }, { 7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1 }, { 9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1 }, { 2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1 }, { 11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1 }, { 9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1 }, { 5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1 }, { 11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1 }, { 11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1 }, { 1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1 }, { 9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1 }, { 5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1 }, { 2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1 }, { 0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1 }, { 5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1 }, { 6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1 }, { 3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1 }, { 6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1 }, { 5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1 }, { 1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1 }, { 10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1 }, { 6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1 }, { 8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1 }, { 7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1 }, { 3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1 }, { 5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1 }, { 0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1 }, { 9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1 }, { 8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1 }, { 5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1 }, { 0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1 }, { 6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1 }, { 10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1 }, { 10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1 }, { 8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1 }, { 1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1 }, { 3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1 }, { 0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1 }, { 10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1 }, { 3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1 }, { 6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1 }, { 9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1 }, { 8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1 }, { 3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1 }, { 6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1 }, { 0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1 }, { 10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1 }, { 10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1 }, { 2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1 }, { 7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1 }, { 7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1 }, { 2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1 }, { 1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1 }, { 11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1 }, { 8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1 }, { 0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1 }, { 7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1 }, { 10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1 }, { 2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1 }, { 6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1 }, { 7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1 }, { 2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1 }, { 1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1 }, { 10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1 }, { 10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1 }, { 0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1 }, { 7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1 }, { 6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1 }, { 8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1 }, { 9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1 }, { 6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1 }, { 4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1 }, { 10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1 }, { 8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1 }, { 0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1 }, { 1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1 }, { 8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1 }, { 10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1 }, { 4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1 }, { 10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1 }, { 5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1 }, { 11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1 }, { 9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1 }, { 6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1 }, { 7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1 }, { 3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1 }, { 7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1 }, { 9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1 }, { 3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1 }, { 6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1 }, { 9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1 }, { 1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1 }, { 4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1 }, { 7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1 }, { 6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1 }, { 3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1 }, { 0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1 }, { 6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1 }, { 0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1 }, { 11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1 }, { 6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1 }, { 5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1 }, { 9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1 }, { 1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1 }, { 1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1 }, { 10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1 }, { 0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1 }, { 5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1 }, { 10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1 }, { 11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1 }, { 9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1 }, { 7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1 }, { 2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1 }, { 8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1 }, { 9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1 }, { 9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1 }, { 1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1 }, { 9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1 }, { 9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1 }, { 5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1 }, { 0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1 }, { 10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1 }, { 2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1 }, { 0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1 }, { 0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1 }, { 9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1 }, { 5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1 }, { 3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1 }, { 5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1 }, { 8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1 }, { 9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1 }, { 1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1 }, { 3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1 }, { 4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1 }, { 9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1 }, { 11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1 }, { 11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1 }, { 2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1 }, { 9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1 }, { 3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1 }, { 1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1 }, { 4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1 }, { 4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1 }, { 0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1 }, { 3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1 }, { 3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1 }, { 0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1 }, { 9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1 }, { 1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } }; const unsigned int _nx = (unsigned int)(size_x>=0?size_x:cimg::round((x1-x0)*-size_x/100 + 1)), _ny = (unsigned int)(size_y>=0?size_y:cimg::round((y1-y0)*-size_y/100 + 1)), _nz = (unsigned int)(size_z>=0?size_z:cimg::round((z1-z0)*-size_z/100 + 1)), nx = _nx?_nx:1, ny = _ny?_ny:1, nz = _nz?_nz:1, nxm1 = nx - 1, nym1 = ny - 1, nzm1 = nz - 1; primitives.assign(); if (!nxm1 || !nym1 || !nzm1) return CImg<floatT>(); const float dx = (x1 - x0)/nxm1, dy = (y1 - y0)/nym1, dz = (z1 - z0)/nzm1; CImgList<floatT> vertices; CImg<intT> indices1(nx,ny,1,3,-1), indices2(indices1); CImg<floatT> values1(nx,ny), values2(nx,ny); float X = 0, Y = 0, Z = 0, nX = 0, nY = 0, nZ = 0; // Fill the first plane with function values Y = y0; cimg_forY(values1,y) { X = x0; cimg_forX(values1,x) { values1(x,y) = (float)func(X,Y,z0); X+=dx; } Y+=dy; } // Run Marching Cubes algorithm Z = z0; nZ = Z + dz; for (unsigned int zi = 0; zi<nzm1; ++zi, Z = nZ, nZ+=dz) { Y = y0; nY = Y + dy; indices2.fill(-1); for (unsigned int yi = 0, nyi = 1; yi<nym1; ++yi, ++nyi, Y = nY, nY+=dy) { X = x0; nX = X + dx; for (unsigned int xi = 0, nxi = 1; xi<nxm1; ++xi, ++nxi, X = nX, nX+=dx) { // Determine cube configuration const float val0 = values1(xi,yi), val1 = values1(nxi,yi), val2 = values1(nxi,nyi), val3 = values1(xi,nyi), val4 = values2(xi,yi) = (float)func(X,Y,nZ), val5 = values2(nxi,yi) = (float)func(nX,Y,nZ), val6 = values2(nxi,nyi) = (float)func(nX,nY,nZ), val7 = values2(xi,nyi) = (float)func(X,nY,nZ); const unsigned int configuration = (val0<isovalue?1U:0U) | (val1<isovalue?2U:0U) | (val2<isovalue?4U:0U) | (val3<isovalue?8U:0U) | (val4<isovalue?16U:0U) | (val5<isovalue?32U:0U) | (val6<isovalue?64U:0U) | (val7<isovalue?128U:0U), edge = edges[configuration]; // Compute intersection vertices if (edge) { if ((edge&1) && indices1(xi,yi,0)<0) { const float Xi = X + (isovalue-val0)*dx/(val1-val0); indices1(xi,yi,0) = vertices.width(); CImg<floatT>::vector(Xi,Y,Z).move_to(vertices); } if ((edge&2) && indices1(nxi,yi,1)<0) { const float Yi = Y + (isovalue-val1)*dy/(val2-val1); indices1(nxi,yi,1) = vertices.width(); CImg<floatT>::vector(nX,Yi,Z).move_to(vertices); } if ((edge&4) && indices1(xi,nyi,0)<0) { const float Xi = X + (isovalue-val3)*dx/(val2-val3); indices1(xi,nyi,0) = vertices.width(); CImg<floatT>::vector(Xi,nY,Z).move_to(vertices); } if ((edge&8) && indices1(xi,yi,1)<0) { const float Yi = Y + (isovalue-val0)*dy/(val3-val0); indices1(xi,yi,1) = vertices.width(); CImg<floatT>::vector(X,Yi,Z).move_to(vertices); } if ((edge&16) && indices2(xi,yi,0)<0) { const float Xi = X + (isovalue-val4)*dx/(val5-val4); indices2(xi,yi,0) = vertices.width(); CImg<floatT>::vector(Xi,Y,nZ).move_to(vertices); } if ((edge&32) && indices2(nxi,yi,1)<0) { const float Yi = Y + (isovalue-val5)*dy/(val6-val5); indices2(nxi,yi,1) = vertices.width(); CImg<floatT>::vector(nX,Yi,nZ).move_to(vertices); } if ((edge&64) && indices2(xi,nyi,0)<0) { const float Xi = X + (isovalue-val7)*dx/(val6-val7); indices2(xi,nyi,0) = vertices.width(); CImg<floatT>::vector(Xi,nY,nZ).move_to(vertices); } if ((edge&128) && indices2(xi,yi,1)<0) { const float Yi = Y + (isovalue-val4)*dy/(val7-val4); indices2(xi,yi,1) = vertices.width(); CImg<floatT>::vector(X,Yi,nZ).move_to(vertices); } if ((edge&256) && indices1(xi,yi,2)<0) { const float Zi = Z+ (isovalue-val0)*dz/(val4-val0); indices1(xi,yi,2) = vertices.width(); CImg<floatT>::vector(X,Y,Zi).move_to(vertices); } if ((edge&512) && indices1(nxi,yi,2)<0) { const float Zi = Z + (isovalue-val1)*dz/(val5-val1); indices1(nxi,yi,2) = vertices.width(); CImg<floatT>::vector(nX,Y,Zi).move_to(vertices); } if ((edge&1024) && indices1(nxi,nyi,2)<0) { const float Zi = Z + (isovalue-val2)*dz/(val6-val2); indices1(nxi,nyi,2) = vertices.width(); CImg<floatT>::vector(nX,nY,Zi).move_to(vertices); } if ((edge&2048) && indices1(xi,nyi,2)<0) { const float Zi = Z + (isovalue-val3)*dz/(val7-val3); indices1(xi,nyi,2) = vertices.width(); CImg<floatT>::vector(X,nY,Zi).move_to(vertices); } // Create triangles for (const int *triangle = triangles[configuration]; *triangle!=-1; ) { const unsigned int p0 = (unsigned int)*(triangle++), p1 = (unsigned int)*(triangle++), p2 = (unsigned int)*(triangle++); const tf i0 = (tf)(_isosurface3d_index(p0,indices1,indices2,xi,yi,nxi,nyi)), i1 = (tf)(_isosurface3d_index(p1,indices1,indices2,xi,yi,nxi,nyi)), i2 = (tf)(_isosurface3d_index(p2,indices1,indices2,xi,yi,nxi,nyi)); CImg<tf>::vector(i0,i2,i1).move_to(primitives); } } } } cimg::swap(values1,values2); cimg::swap(indices1,indices2); } return vertices>'x'; } //! Compute isosurface of a function, as a 3D object \overloading. template<typename tf> static CImg<floatT> isosurface3d(CImgList<tf>& primitives, const char *const expression, const float isovalue, const float x0, const float y0, const float z0, const float x1, const float y1, const float z1, const int dx=32, const int dy=32, const int dz=32) { const _functor3d_expr func(expression); return isosurface3d(primitives,func,isovalue,x0,y0,z0,x1,y1,z1,dx,dy,dz); } template<typename t> static int _isosurface3d_index(const unsigned int edge, const CImg<t>& indices1, const CImg<t>& indices2, const unsigned int x, const unsigned int y, const unsigned int nx, const unsigned int ny) { switch (edge) { case 0 : return indices1(x,y,0); case 1 : return indices1(nx,y,1); case 2 : return indices1(x,ny,0); case 3 : return indices1(x,y,1); case 4 : return indices2(x,y,0); case 5 : return indices2(nx,y,1); case 6 : return indices2(x,ny,0); case 7 : return indices2(x,y,1); case 8 : return indices1(x,y,2); case 9 : return indices1(nx,y,2); case 10 : return indices1(nx,ny,2); case 11 : return indices1(x,ny,2); } return 0; } // Define functors for accessing image values (used in previous functions). struct _functor2d_int { const CImg<T>& ref; _functor2d_int(const CImg<T>& pref):ref(pref) {} float operator()(const float x, const float y) const { return (float)ref((int)x,(int)y); } }; struct _functor2d_float { const CImg<T>& ref; _functor2d_float(const CImg<T>& pref):ref(pref) {} float operator()(const float x, const float y) const { return (float)ref._linear_atXY(x,y); } }; struct _functor2d_expr { _cimg_math_parser *mp; ~_functor2d_expr() { mp->end(); delete mp; } _functor2d_expr(const char *const expr):mp(0) { mp = new _cimg_math_parser(expr,0,CImg<T>::const_empty(),0); } float operator()(const float x, const float y) const { return (float)(*mp)(x,y,0,0); } }; struct _functor3d_int { const CImg<T>& ref; _functor3d_int(const CImg<T>& pref):ref(pref) {} float operator()(const float x, const float y, const float z) const { return (float)ref((int)x,(int)y,(int)z); } }; struct _functor3d_float { const CImg<T>& ref; _functor3d_float(const CImg<T>& pref):ref(pref) {} float operator()(const float x, const float y, const float z) const { return (float)ref._linear_atXYZ(x,y,z); } }; struct _functor3d_expr { _cimg_math_parser *mp; ~_functor3d_expr() { mp->end(); delete mp; } _functor3d_expr(const char *const expr):mp(0) { mp = new _cimg_math_parser(expr,0,CImg<T>::const_empty(),0); } float operator()(const float x, const float y, const float z) const { return (float)(*mp)(x,y,z,0); } }; struct _functor4d_int { const CImg<T>& ref; _functor4d_int(const CImg<T>& pref):ref(pref) {} float operator()(const float x, const float y, const float z, const unsigned int c) const { return (float)ref((int)x,(int)y,(int)z,c); } }; //! Generate a 3D box object. /** \param[out] primitives The returned list of the 3D object primitives (template type \e tf should be at least \e unsigned \e int). \param size_x The width of the box (dimension along the X-axis). \param size_y The height of the box (dimension along the Y-axis). \param size_z The depth of the box (dimension along the Z-axis). \return The N vertices (xi,yi,zi) of the 3D object as a Nx3 CImg<float> image (0<=i<=N - 1). \par Example \code CImgList<unsigned int> faces3d; const CImg<float> points3d = CImg<float>::box3d(faces3d,10,20,30); CImg<unsigned char>().display_object3d("Box3d",points3d,faces3d); \endcode \image html ref_box3d.jpg **/ template<typename tf> static CImg<floatT> box3d(CImgList<tf>& primitives, const float size_x=200, const float size_y=100, const float size_z=100) { primitives.assign(6,1,4,1,1, 0,3,2,1, 4,5,6,7, 0,1,5,4, 3,7,6,2, 0,4,7,3, 1,2,6,5); return CImg<floatT>(8,3,1,1, 0.,size_x,size_x, 0., 0.,size_x,size_x, 0., 0., 0.,size_y,size_y, 0., 0.,size_y,size_y, 0., 0., 0., 0.,size_z,size_z,size_z,size_z); } //! Generate a 3D cone. /** \param[out] primitives The returned list of the 3D object primitives (template type \e tf should be at least \e unsigned \e int). \param radius The radius of the cone basis. \param size_z The cone's height. \param subdivisions The number of basis angular subdivisions. \return The N vertices (xi,yi,zi) of the 3D object as a Nx3 CImg<float> image (0<=i<=N - 1). \par Example \code CImgList<unsigned int> faces3d; const CImg<float> points3d = CImg<float>::cone3d(faces3d,50); CImg<unsigned char>().display_object3d("Cone3d",points3d,faces3d); \endcode \image html ref_cone3d.jpg **/ template<typename tf> static CImg<floatT> cone3d(CImgList<tf>& primitives, const float radius=50, const float size_z=100, const unsigned int subdivisions=24) { primitives.assign(); if (!subdivisions) return CImg<floatT>(); CImgList<floatT> vertices(2,1,3,1,1, 0.,0.,size_z, 0.,0.,0.); for (float delta = 360.f/subdivisions, angle = 0; angle<360; angle+=delta) { const float a = (float)(angle*cimg::PI/180); CImg<floatT>::vector((float)(radius*std::cos(a)),(float)(radius*std::sin(a)),0).move_to(vertices); } const unsigned int nbr = vertices._width - 2; for (unsigned int p = 0; p<nbr; ++p) { const unsigned int curr = 2 + p, next = 2 + ((p + 1)%nbr); CImg<tf>::vector(1,next,curr).move_to(primitives); CImg<tf>::vector(0,curr,next).move_to(primitives); } return vertices>'x'; } //! Generate a 3D cylinder. /** \param[out] primitives The returned list of the 3D object primitives (template type \e tf should be at least \e unsigned \e int). \param radius The radius of the cylinder basis. \param size_z The cylinder's height. \param subdivisions The number of basis angular subdivisions. \return The N vertices (xi,yi,zi) of the 3D object as a Nx3 CImg<float> image (0<=i<=N - 1). \par Example \code CImgList<unsigned int> faces3d; const CImg<float> points3d = CImg<float>::cylinder3d(faces3d,50); CImg<unsigned char>().display_object3d("Cylinder3d",points3d,faces3d); \endcode \image html ref_cylinder3d.jpg **/ template<typename tf> static CImg<floatT> cylinder3d(CImgList<tf>& primitives, const float radius=50, const float size_z=100, const unsigned int subdivisions=24) { primitives.assign(); if (!subdivisions) return CImg<floatT>(); CImgList<floatT> vertices(2,1,3,1,1, 0.,0.,0., 0.,0.,size_z); for (float delta = 360.f/subdivisions, angle = 0; angle<360; angle+=delta) { const float a = (float)(angle*cimg::PI/180); CImg<floatT>::vector((float)(radius*std::cos(a)),(float)(radius*std::sin(a)),0.f).move_to(vertices); CImg<floatT>::vector((float)(radius*std::cos(a)),(float)(radius*std::sin(a)),size_z).move_to(vertices); } const unsigned int nbr = (vertices._width - 2)/2; for (unsigned int p = 0; p<nbr; ++p) { const unsigned int curr = 2 + 2*p, next = 2 + (2*((p + 1)%nbr)); CImg<tf>::vector(0,next,curr).move_to(primitives); CImg<tf>::vector(1,curr + 1,next + 1).move_to(primitives); CImg<tf>::vector(curr,next,next + 1,curr + 1).move_to(primitives); } return vertices>'x'; } //! Generate a 3D torus. /** \param[out] primitives The returned list of the 3D object primitives (template type \e tf should be at least \e unsigned \e int). \param radius1 The large radius. \param radius2 The small radius. \param subdivisions1 The number of angular subdivisions for the large radius. \param subdivisions2 The number of angular subdivisions for the small radius. \return The N vertices (xi,yi,zi) of the 3D object as a Nx3 CImg<float> image (0<=i<=N - 1). \par Example \code CImgList<unsigned int> faces3d; const CImg<float> points3d = CImg<float>::torus3d(faces3d,20,4); CImg<unsigned char>().display_object3d("Torus3d",points3d,faces3d); \endcode \image html ref_torus3d.jpg **/ template<typename tf> static CImg<floatT> torus3d(CImgList<tf>& primitives, const float radius1=100, const float radius2=30, const unsigned int subdivisions1=24, const unsigned int subdivisions2=12) { primitives.assign(); if (!subdivisions1 || !subdivisions2) return CImg<floatT>(); CImgList<floatT> vertices; for (unsigned int v = 0; v<subdivisions1; ++v) { const float beta = (float)(v*2*cimg::PI/subdivisions1), xc = radius1*(float)std::cos(beta), yc = radius1*(float)std::sin(beta); for (unsigned int u = 0; u<subdivisions2; ++u) { const float alpha = (float)(u*2*cimg::PI/subdivisions2), x = xc + radius2*(float)(std::cos(alpha)*std::cos(beta)), y = yc + radius2*(float)(std::cos(alpha)*std::sin(beta)), z = radius2*(float)std::sin(alpha); CImg<floatT>::vector(x,y,z).move_to(vertices); } } for (unsigned int vv = 0; vv<subdivisions1; ++vv) { const unsigned int nv = (vv + 1)%subdivisions1; for (unsigned int uu = 0; uu<subdivisions2; ++uu) { const unsigned int nu = (uu + 1)%subdivisions2, svv = subdivisions2*vv, snv = subdivisions2*nv; CImg<tf>::vector(svv + nu,svv + uu,snv + uu,snv + nu).move_to(primitives); } } return vertices>'x'; } //! Generate a 3D XY-plane. /** \param[out] primitives The returned list of the 3D object primitives (template type \e tf should be at least \e unsigned \e int). \param size_x The width of the plane (dimension along the X-axis). \param size_y The height of the plane (dimensions along the Y-axis). \param subdivisions_x The number of planar subdivisions along the X-axis. \param subdivisions_y The number of planar subdivisions along the Y-axis. \return The N vertices (xi,yi,zi) of the 3D object as a Nx3 CImg<float> image (0<=i<=N - 1). \par Example \code CImgList<unsigned int> faces3d; const CImg<float> points3d = CImg<float>::plane3d(faces3d,100,50); CImg<unsigned char>().display_object3d("Plane3d",points3d,faces3d); \endcode \image html ref_plane3d.jpg **/ template<typename tf> static CImg<floatT> plane3d(CImgList<tf>& primitives, const float size_x=100, const float size_y=100, const unsigned int subdivisions_x=10, const unsigned int subdivisions_y=10) { primitives.assign(); if (!subdivisions_x || !subdivisions_y) return CImg<floatT>(); CImgList<floatT> vertices; const unsigned int w = subdivisions_x + 1, h = subdivisions_y + 1; const float fx = (float)size_x/w, fy = (float)size_y/h; for (unsigned int y = 0; y<h; ++y) for (unsigned int x = 0; x<w; ++x) CImg<floatT>::vector(fx*x,fy*y,0).move_to(vertices); for (unsigned int y = 0; y<subdivisions_y; ++y) for (unsigned int x = 0; x<subdivisions_x; ++x) { const int off1 = x + y*w, off2 = x + 1 + y*w, off3 = x + 1 + (y + 1)*w, off4 = x + (y + 1)*w; CImg<tf>::vector(off1,off4,off3,off2).move_to(primitives); } return vertices>'x'; } //! Generate a 3D sphere. /** \param[out] primitives The returned list of the 3D object primitives (template type \e tf should be at least \e unsigned \e int). \param radius The radius of the sphere (dimension along the X-axis). \param subdivisions The number of recursive subdivisions from an initial icosahedron. \return The N vertices (xi,yi,zi) of the 3D object as a Nx3 CImg<float> image (0<=i<=N - 1). \par Example \code CImgList<unsigned int> faces3d; const CImg<float> points3d = CImg<float>::sphere3d(faces3d,100,4); CImg<unsigned char>().display_object3d("Sphere3d",points3d,faces3d); \endcode \image html ref_sphere3d.jpg **/ template<typename tf> static CImg<floatT> sphere3d(CImgList<tf>& primitives, const float radius=50, const unsigned int subdivisions=3) { // Create initial icosahedron primitives.assign(); const double tmp = (1 + std::sqrt(5.f))/2, a = 1./std::sqrt(1 + tmp*tmp), b = tmp*a; CImgList<floatT> vertices(12,1,3,1,1, b,a,0., -b,a,0., -b,-a,0., b,-a,0., a,0.,b, a,0.,-b, -a,0.,-b, -a,0.,b, 0.,b,a, 0.,-b,a, 0.,-b,-a, 0.,b,-a); primitives.assign(20,1,3,1,1, 4,8,7, 4,7,9, 5,6,11, 5,10,6, 0,4,3, 0,3,5, 2,7,1, 2,1,6, 8,0,11, 8,11,1, 9,10,3, 9,2,10, 8,4,0, 11,0,5, 4,9,3, 5,3,10, 7,8,1, 6,1,11, 7,2,9, 6,10,2); // edge - length/2 float he = (float)a; // Recurse subdivisions for (unsigned int i = 0; i<subdivisions; ++i) { const unsigned int L = primitives._width; he/=2; const float he2 = he*he; for (unsigned int l = 0; l<L; ++l) { const unsigned int p0 = (unsigned int)primitives(0,0), p1 = (unsigned int)primitives(0,1), p2 = (unsigned int)primitives(0,2); const float x0 = vertices(p0,0), y0 = vertices(p0,1), z0 = vertices(p0,2), x1 = vertices(p1,0), y1 = vertices(p1,1), z1 = vertices(p1,2), x2 = vertices(p2,0), y2 = vertices(p2,1), z2 = vertices(p2,2), tnx0 = (x0 + x1)/2, tny0 = (y0 + y1)/2, tnz0 = (z0 + z1)/2, nn0 = cimg::hypot(tnx0,tny0,tnz0), tnx1 = (x0 + x2)/2, tny1 = (y0 + y2)/2, tnz1 = (z0 + z2)/2, nn1 = cimg::hypot(tnx1,tny1,tnz1), tnx2 = (x1 + x2)/2, tny2 = (y1 + y2)/2, tnz2 = (z1 + z2)/2, nn2 = cimg::hypot(tnx2,tny2,tnz2), nx0 = tnx0/nn0, ny0 = tny0/nn0, nz0 = tnz0/nn0, nx1 = tnx1/nn1, ny1 = tny1/nn1, nz1 = tnz1/nn1, nx2 = tnx2/nn2, ny2 = tny2/nn2, nz2 = tnz2/nn2; int i0 = -1, i1 = -1, i2 = -1; cimglist_for(vertices,p) { const float x = (float)vertices(p,0), y = (float)vertices(p,1), z = (float)vertices(p,2); if (cimg::sqr(x-nx0) + cimg::sqr(y-ny0) + cimg::sqr(z-nz0)<he2) i0 = p; if (cimg::sqr(x-nx1) + cimg::sqr(y-ny1) + cimg::sqr(z-nz1)<he2) i1 = p; if (cimg::sqr(x-nx2) + cimg::sqr(y-ny2) + cimg::sqr(z-nz2)<he2) i2 = p; } if (i0<0) { CImg<floatT>::vector(nx0,ny0,nz0).move_to(vertices); i0 = vertices.width() - 1; } if (i1<0) { CImg<floatT>::vector(nx1,ny1,nz1).move_to(vertices); i1 = vertices.width() - 1; } if (i2<0) { CImg<floatT>::vector(nx2,ny2,nz2).move_to(vertices); i2 = vertices.width() - 1; } primitives.remove(0); CImg<tf>::vector(p0,i0,i1).move_to(primitives); CImg<tf>::vector((tf)i0,(tf)p1,(tf)i2).move_to(primitives); CImg<tf>::vector((tf)i1,(tf)i2,(tf)p2).move_to(primitives); CImg<tf>::vector((tf)i1,(tf)i0,(tf)i2).move_to(primitives); } } return (vertices>'x')*=radius; } //! Generate a 3D ellipsoid. /** \param[out] primitives The returned list of the 3D object primitives (template type \e tf should be at least \e unsigned \e int). \param tensor The tensor which gives the shape and size of the ellipsoid. \param subdivisions The number of recursive subdivisions from an initial stretched icosahedron. \return The N vertices (xi,yi,zi) of the 3D object as a Nx3 CImg<float> image (0<=i<=N - 1). \par Example \code CImgList<unsigned int> faces3d; const CImg<float> tensor = CImg<float>::diagonal(10,7,3), points3d = CImg<float>::ellipsoid3d(faces3d,tensor,4); CImg<unsigned char>().display_object3d("Ellipsoid3d",points3d,faces3d); \endcode \image html ref_ellipsoid3d.jpg **/ template<typename tf, typename t> static CImg<floatT> ellipsoid3d(CImgList<tf>& primitives, const CImg<t>& tensor, const unsigned int subdivisions=3) { primitives.assign(); if (!subdivisions) return CImg<floatT>(); CImg<floatT> S, V; tensor.symmetric_eigen(S,V); const float orient = (V(0,1)*V(1,2) - V(0,2)*V(1,1))*V(2,0) + (V(0,2)*V(1,0) - V(0,0)*V(1,2))*V(2,1) + (V(0,0)*V(1,1) - V(0,1)*V(1,0))*V(2,2); if (orient<0) { V(2,0) = -V(2,0); V(2,1) = -V(2,1); V(2,2) = -V(2,2); } const float l0 = S[0], l1 = S[1], l2 = S[2]; CImg<floatT> vertices = sphere3d(primitives,1.,subdivisions); vertices.get_shared_row(0)*=l0; vertices.get_shared_row(1)*=l1; vertices.get_shared_row(2)*=l2; return V*vertices; } //! Convert 3D object into a CImg3d representation. /** \param primitives Primitives data of the 3D object. \param colors Colors data of the 3D object. \param opacities Opacities data of the 3D object. \param full_check Tells if full checking of the 3D object must be performed. **/ template<typename tp, typename tc, typename to> CImg<T>& object3dtoCImg3d(const CImgList<tp>& primitives, const CImgList<tc>& colors, const to& opacities, const bool full_check=true) { return get_object3dtoCImg3d(primitives,colors,opacities,full_check).move_to(*this); } //! Convert 3D object into a CImg3d representation \overloading. template<typename tp, typename tc> CImg<T>& object3dtoCImg3d(const CImgList<tp>& primitives, const CImgList<tc>& colors, const bool full_check=true) { return get_object3dtoCImg3d(primitives,colors,full_check).move_to(*this); } //! Convert 3D object into a CImg3d representation \overloading. template<typename tp> CImg<T>& object3dtoCImg3d(const CImgList<tp>& primitives, const bool full_check=true) { return get_object3dtoCImg3d(primitives,full_check).move_to(*this); } //! Convert 3D object into a CImg3d representation \overloading. CImg<T>& object3dtoCImg3d(const bool full_check=true) { return get_object3dtoCImg3d(full_check).move_to(*this); } //! Convert 3D object into a CImg3d representation \newinstance. template<typename tp, typename tc, typename to> CImg<floatT> get_object3dtoCImg3d(const CImgList<tp>& primitives, const CImgList<tc>& colors, const to& opacities, const bool full_check=true) const { CImg<charT> error_message(1024); if (!is_object3d(primitives,colors,opacities,full_check,error_message)) throw CImgInstanceException(_cimg_instance "object3dtoCImg3d(): Invalid specified 3D object (%u,%u) (%s).", cimg_instance,_width,primitives._width,error_message.data()); CImg<floatT> res(1,_size_object3dtoCImg3d(primitives,colors,opacities)); float *ptrd = res._data; // Put magick number. *(ptrd++) = 'C' + 0.5f; *(ptrd++) = 'I' + 0.5f; *(ptrd++) = 'm' + 0.5f; *(ptrd++) = 'g' + 0.5f; *(ptrd++) = '3' + 0.5f; *(ptrd++) = 'd' + 0.5f; // Put number of vertices and primitives. *(ptrd++) = cimg::uint2float(_width); *(ptrd++) = cimg::uint2float(primitives._width); // Put vertex data. if (is_empty() || !primitives) return res; const T *ptrx = data(0,0), *ptry = data(0,1), *ptrz = data(0,2); cimg_forX(*this,p) { *(ptrd++) = (float)*(ptrx++); *(ptrd++) = (float)*(ptry++); *(ptrd++) = (float)*(ptrz++); } // Put primitive data. cimglist_for(primitives,p) { *(ptrd++) = (float)primitives[p].size(); const tp *ptrp = primitives[p]._data; cimg_foroff(primitives[p],i) *(ptrd++) = cimg::uint2float((unsigned int)*(ptrp++)); } // Put color/texture data. const unsigned int csiz = std::min(colors._width,primitives._width); for (int c = 0; c<(int)csiz; ++c) { const CImg<tc>& color = colors[c]; const tc *ptrc = color._data; if (color.size()==3) { *(ptrd++) = (float)*(ptrc++); *(ptrd++) = (float)*(ptrc++); *(ptrd++) = (float)*ptrc; } else { *(ptrd++) = -128.f; int shared_ind = -1; if (color.is_shared()) for (int i = 0; i<c; ++i) if (ptrc==colors[i]._data) { shared_ind = i; break; } if (shared_ind<0) { *(ptrd++) = (float)color._width; *(ptrd++) = (float)color._height; *(ptrd++) = (float)color._spectrum; cimg_foroff(color,l) *(ptrd++) = (float)*(ptrc++); } else { *(ptrd++) = (float)shared_ind; *(ptrd++) = 0; *(ptrd++) = 0; } } } const int csiz2 = primitives.width() - colors.width(); for (int c = 0; c<csiz2; ++c) { *(ptrd++) = 200.f; *(ptrd++) = 200.f; *(ptrd++) = 200.f; } // Put opacity data. ptrd = _object3dtoCImg3d(opacities,ptrd); const float *ptre = res.end(); while (ptrd<ptre) *(ptrd++) = 1.f; return res; } template<typename to> float* _object3dtoCImg3d(const CImgList<to>& opacities, float *ptrd) const { cimglist_for(opacities,o) { const CImg<to>& opacity = opacities[o]; const to *ptro = opacity._data; if (opacity.size()==1) *(ptrd++) = (float)*ptro; else { *(ptrd++) = -128.f; int shared_ind = -1; if (opacity.is_shared()) for (int i = 0; i<o; ++i) if (ptro==opacities[i]._data) { shared_ind = i; break; } if (shared_ind<0) { *(ptrd++) = (float)opacity._width; *(ptrd++) = (float)opacity._height; *(ptrd++) = (float)opacity._spectrum; cimg_foroff(opacity,l) *(ptrd++) = (float)*(ptro++); } else { *(ptrd++) = (float)shared_ind; *(ptrd++) = 0; *(ptrd++) = 0; } } } return ptrd; } template<typename to> float* _object3dtoCImg3d(const CImg<to>& opacities, float *ptrd) const { const to *ptro = opacities._data; cimg_foroff(opacities,o) *(ptrd++) = (float)*(ptro++); return ptrd; } template<typename tp, typename tc, typename to> unsigned int _size_object3dtoCImg3d(const CImgList<tp>& primitives, const CImgList<tc>& colors, const CImgList<to>& opacities) const { unsigned int siz = 8U + 3*_width; cimglist_for(primitives,p) siz+=primitives[p].size() + 1; for (int c = std::min(primitives.width(),colors.width()) - 1; c>=0; --c) { if (colors[c].is_shared()) siz+=4; else { const unsigned int csiz = colors[c].size(); siz+=(csiz!=3)?4 + csiz:3; } } if (colors._width<primitives._width) siz+=3*(primitives._width - colors._width); cimglist_for(opacities,o) { if (opacities[o].is_shared()) siz+=4; else { const unsigned int osiz = opacities[o].size(); siz+=(osiz!=1)?4 + osiz:1; } } siz+=primitives._width - opacities._width; return siz; } template<typename tp, typename tc, typename to> unsigned int _size_object3dtoCImg3d(const CImgList<tp>& primitives, const CImgList<tc>& colors, const CImg<to>& opacities) const { unsigned int siz = 8U + 3*_width; cimglist_for(primitives,p) siz+=primitives[p].size() + 1; for (int c = std::min(primitives.width(),colors.width()) - 1; c>=0; --c) { const unsigned int csiz = colors[c].size(); siz+=(csiz!=3)?4 + csiz:3; } if (colors._width<primitives._width) siz+=3*(primitives._width - colors._width); siz+=primitives.size(); cimg::unused(opacities); return siz; } //! Convert 3D object into a CImg3d representation \overloading. template<typename tp, typename tc> CImg<floatT> get_object3dtoCImg3d(const CImgList<tp>& primitives, const CImgList<tc>& colors, const bool full_check=true) const { CImgList<T> opacities; return get_object3dtoCImg3d(primitives,colors,opacities,full_check); } //! Convert 3D object into a CImg3d representation \overloading. template<typename tp> CImg<floatT> get_object3dtoCImg3d(const CImgList<tp>& primitives, const bool full_check=true) const { CImgList<T> colors, opacities; return get_object3dtoCImg3d(primitives,colors,opacities,full_check); } //! Convert 3D object into a CImg3d representation \overloading. CImg<floatT> get_object3dtoCImg3d(const bool full_check=true) const { CImgList<T> opacities, colors; CImgList<uintT> primitives(width(),1,1,1,1); cimglist_for(primitives,p) primitives(p,0) = p; return get_object3dtoCImg3d(primitives,colors,opacities,full_check); } //! Convert CImg3d representation into a 3D object. /** \param[out] primitives Primitives data of the 3D object. \param[out] colors Colors data of the 3D object. \param[out] opacities Opacities data of the 3D object. \param full_check Tells if full checking of the 3D object must be performed. **/ template<typename tp, typename tc, typename to> CImg<T>& CImg3dtoobject3d(CImgList<tp>& primitives, CImgList<tc>& colors, CImgList<to>& opacities, const bool full_check=true) { return get_CImg3dtoobject3d(primitives,colors,opacities,full_check).move_to(*this); } //! Convert CImg3d representation into a 3D object \newinstance. template<typename tp, typename tc, typename to> CImg<T> get_CImg3dtoobject3d(CImgList<tp>& primitives, CImgList<tc>& colors, CImgList<to>& opacities, const bool full_check=true) const { CImg<charT> error_message(1024); if (!is_CImg3d(full_check,error_message)) throw CImgInstanceException(_cimg_instance "CImg3dtoobject3d(): image instance is not a CImg3d (%s).", cimg_instance,error_message.data()); const T *ptrs = _data + 6; const unsigned int nb_points = cimg::float2uint((float)*(ptrs++)), nb_primitives = cimg::float2uint((float)*(ptrs++)); const CImg<T> points = CImg<T>(ptrs,3,nb_points,1,1,true).get_transpose(); ptrs+=3*nb_points; primitives.assign(nb_primitives); cimglist_for(primitives,p) { const unsigned int nb_inds = (unsigned int)*(ptrs++); primitives[p].assign(1,nb_inds); tp *ptrp = primitives[p]._data; for (unsigned int i = 0; i<nb_inds; ++i) *(ptrp++) = (tp)cimg::float2uint((float)*(ptrs++)); } colors.assign(nb_primitives); cimglist_for(colors,c) { if (*ptrs==(T)-128) { ++ptrs; const unsigned int w = (unsigned int)*(ptrs++), h = (unsigned int)*(ptrs++), s = (unsigned int)*(ptrs++); if (!h && !s) colors[c].assign(colors[w],true); else { colors[c].assign(ptrs,w,h,1,s,false); ptrs+=w*h*s; } } else { colors[c].assign(ptrs,1,1,1,3,false); ptrs+=3; } } opacities.assign(nb_primitives); cimglist_for(opacities,o) { if (*ptrs==(T)-128) { ++ptrs; const unsigned int w = (unsigned int)*(ptrs++), h = (unsigned int)*(ptrs++), s = (unsigned int)*(ptrs++); if (!h && !s) opacities[o].assign(opacities[w],true); else { opacities[o].assign(ptrs,w,h,1,s,false); ptrs+=w*h*s; } } else opacities[o].assign(1,1,1,1,*(ptrs++)); } return points; } //@} //--------------------------- // //! \name Drawing Functions //@{ //--------------------------- #define cimg_init_scanline(opacity) \ static const T _sc_maxval = (T)std::min(cimg::type<T>::max(),(T)cimg::type<tc>::max()); \ const float _sc_nopacity = cimg::abs((float)opacity), _sc_copacity = 1 - std::max((float)opacity,0.f); \ const ulongT _sc_whd = (ulongT)_width*_height*_depth; \ cimg::unused(_sc_maxval); #define cimg_draw_scanline(x0,x1,y,color,opacity,brightness) \ _draw_scanline(x0,x1,y,color,opacity,brightness,_sc_nopacity,_sc_copacity,_sc_whd,_sc_maxval) // [internal] The following _draw_scanline() routines are *non user-friendly functions*, // used only for internal purpose. // Pre-requisites: x0<=x1, y-coordinate is valid, col is valid. template<typename tc> CImg<T>& _draw_scanline(const int x0, const int x1, const int y, const tc *const color, const float opacity, const float brightness, const float nopacity, const float copacity, const ulongT whd, const T _sc_maxval) { const int nx0 = x0>0?x0:0, nx1 = x1<width()?x1:width() - 1, dx = nx1 - nx0; if (dx>=0) { const tc *col = color; const ulongT off = whd - dx - 1; T *ptrd = data(nx0,y); if (opacity>=1) { // ** Opaque drawing ** if (brightness==1) { // Brightness==1 if (sizeof(T)!=1) cimg_forC(*this,c) { const T val = (T)*(col++); for (int x = dx; x>=0; --x) *(ptrd++) = val; ptrd+=off; } else cimg_forC(*this,c) { const T val = (T)*(col++); std::memset(ptrd,(int)val,dx + 1); ptrd+=whd; } } else if (brightness<1) { // Brightness<1 if (sizeof(T)!=1) cimg_forC(*this,c) { const T val = (T)(*(col++)*brightness); for (int x = dx; x>=0; --x) *(ptrd++) = val; ptrd+=off; } else cimg_forC(*this,c) { const T val = (T)(*(col++)*brightness); std::memset(ptrd,(int)val,dx + 1); ptrd+=whd; } } else { // Brightness>1 if (sizeof(T)!=1) cimg_forC(*this,c) { const T val = (T)((2-brightness)**(col++) + (brightness - 1)*_sc_maxval); for (int x = dx; x>=0; --x) *(ptrd++) = val; ptrd+=off; } else cimg_forC(*this,c) { const T val = (T)((2-brightness)**(col++) + (brightness - 1)*_sc_maxval); std::memset(ptrd,(int)val,dx + 1); ptrd+=whd; } } } else { // ** Transparent drawing ** if (brightness==1) { // Brightness==1 cimg_forC(*this,c) { const Tfloat val = *(col++)*nopacity; for (int x = dx; x>=0; --x) { *ptrd = (T)(val + *ptrd*copacity); ++ptrd; } ptrd+=off; } } else if (brightness<=1) { // Brightness<1 cimg_forC(*this,c) { const Tfloat val = *(col++)*brightness*nopacity; for (int x = dx; x>=0; --x) { *ptrd = (T)(val + *ptrd*copacity); ++ptrd; } ptrd+=off; } } else { // Brightness>1 cimg_forC(*this,c) { const Tfloat val = ((2-brightness)**(col++) + (brightness - 1)*_sc_maxval)*nopacity; for (int x = dx; x>=0; --x) { *ptrd = (T)(val + *ptrd*copacity); ++ptrd; } ptrd+=off; } } } } return *this; } //! Draw a 3D point. /** \param x0 X-coordinate of the point. \param y0 Y-coordinate of the point. \param z0 Z-coordinate of the point. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \note - To set pixel values without clipping needs, you should use the faster CImg::operator()() function. \par Example: \code CImg<unsigned char> img(100,100,1,3,0); const unsigned char color[] = { 255,128,64 }; img.draw_point(50,50,color); \endcode **/ template<typename tc> CImg<T>& draw_point(const int x0, const int y0, const int z0, const tc *const color, const float opacity=1) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_point(): Specified color is (null).", cimg_instance); if (x0>=0 && y0>=0 && z0>=0 && x0<width() && y0<height() && z0<depth()) { const ulongT whd = (ulongT)_width*_height*_depth; const float nopacity = cimg::abs(opacity), copacity = 1 - std::max(opacity,0.f); T *ptrd = data(x0,y0,z0,0); const tc *col = color; if (opacity>=1) cimg_forC(*this,c) { *ptrd = (T)*(col++); ptrd+=whd; } else cimg_forC(*this,c) { *ptrd = (T)(*(col++)*nopacity + *ptrd*copacity); ptrd+=whd; } } return *this; } //! Draw a 2D point \simplification. template<typename tc> CImg<T>& draw_point(const int x0, const int y0, const tc *const color, const float opacity=1) { return draw_point(x0,y0,0,color,opacity); } // Draw a points cloud. /** \param points Image of vertices coordinates. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. **/ template<typename t, typename tc> CImg<T>& draw_point(const CImg<t>& points, const tc *const color, const float opacity=1) { if (is_empty() || !points) return *this; switch (points._height) { case 0 : case 1 : throw CImgArgumentException(_cimg_instance "draw_point(): Invalid specified point set (%u,%u,%u,%u,%p).", cimg_instance, points._width,points._height,points._depth,points._spectrum,points._data); case 2 : { cimg_forX(points,i) draw_point((int)points(i,0),(int)points(i,1),color,opacity); } break; default : { cimg_forX(points,i) draw_point((int)points(i,0),(int)points(i,1),(int)points(i,2),color,opacity); } } return *this; } //! Draw a 2D line. /** \param x0 X-coordinate of the starting line point. \param y0 Y-coordinate of the starting line point. \param x1 X-coordinate of the ending line point. \param y1 Y-coordinate of the ending line point. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. \param pattern An integer whose bits describe the line pattern. \param init_hatch Tells if a reinitialization of the hash state must be done. \note - Line routine uses Bresenham's algorithm. - Set \p init_hatch = false to draw consecutive hatched segments without breaking the line pattern. \par Example: \code CImg<unsigned char> img(100,100,1,3,0); const unsigned char color[] = { 255,128,64 }; img.draw_line(40,40,80,70,color); \endcode **/ template<typename tc> CImg<T>& draw_line(int x0, int y0, int x1, int y1, const tc *const color, const float opacity=1, const unsigned int pattern=~0U, const bool init_hatch=true) { if (is_empty() || !opacity || !pattern || std::min(y0,y1)>=height() || std::max(y0,y1)<0 || std::min(x0,x1)>=width() || std::max(x0,x1)<0) return *this; int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dy01 = y1 - y0; const bool is_horizontal = cimg::abs(dx01)>cimg::abs(dy01); if (is_horizontal) cimg::swap(x0,y0,x1,y1,w1,h1,dx01,dy01); if (pattern==~0U && y0>y1) { cimg::swap(x0,x1,y0,y1); dx01*=-1; dy01*=-1; } static unsigned int hatch = ~0U - (~0U>>1); if (init_hatch) hatch = ~0U - (~0U>>1); cimg_init_scanline(opacity); const int step = y0<=y1?1:-1,hdy01 = dy01*cimg::sign(dx01)/2, cy0 = cimg::cut(y0,0,h1), cy1 = cimg::cut(y1,0,h1) + step; dy01+=dy01?0:1; for (int y = cy0; y!=cy1; y+=step) { const int yy0 = y - y0, x = x0 + (dx01*yy0 + hdy01)/dy01; if (x>=0 && x<=w1 && pattern&hatch) { T *const ptrd = is_horizontal?data(y,x):data(x,y); cimg_forC(*this,c) { const T val = color[c]; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } } if (!(hatch>>=1)) hatch = ~0U - (~0U>>1); } return *this; } //! Draw a 2D line, with z-buffering. /** \param zbuffer Zbuffer image. \param x0 X-coordinate of the starting point. \param y0 Y-coordinate of the starting point. \param z0 Z-coordinate of the starting point \param x1 X-coordinate of the ending point. \param y1 Y-coordinate of the ending point. \param z1 Z-coordinate of the ending point. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. \param pattern An integer whose bits describe the line pattern. \param init_hatch Tells if a reinitialization of the hash state must be done. **/ template<typename tz,typename tc> CImg<T>& draw_line(CImg<tz>& zbuffer, int x0, int y0, const float z0, int x1, int y1, const float z1, const tc *const color, const float opacity=1, const unsigned int pattern=~0U, const bool init_hatch=true) { if (is_empty() || z0<=0 || z1<=0 || !opacity || !pattern) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_line(): Specified color is (null).", cimg_instance); if (!is_sameXY(zbuffer)) throw CImgArgumentException(_cimg_instance "draw_line(): Instance and specified Z-buffer (%u,%u,%u,%u,%p) have " "different dimensions.", cimg_instance, zbuffer._width,zbuffer._height,zbuffer._depth,zbuffer._spectrum,zbuffer._data); if (std::min(y0,y1)>=height() || std::max(y0,y1)<0 || std::min(x0,x1)>=width() || std::max(x0,x1)<0) return *this; float iz0 = 1/z0, iz1 = 1/z1; int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dy01 = y1 - y0; float diz01 = iz1 - iz0; const bool is_horizontal = cimg::abs(dx01)>cimg::abs(dy01); if (is_horizontal) cimg::swap(x0,y0,x1,y1,w1,h1,dx01,dy01); if (pattern==~0U && y0>y1) { cimg::swap(x0,x1,y0,y1,iz0,iz1); dx01*=-1; dy01*=-1; diz01*=-1; } static unsigned int hatch = ~0U - (~0U>>1); if (init_hatch) hatch = ~0U - (~0U>>1); cimg_init_scanline(opacity); const int step = y0<=y1?1:-1, hdy01 = dy01*cimg::sign(dx01)/2, cy0 = cimg::cut(y0,0,h1), cy1 = cimg::cut(y1,0,h1) + step; dy01+=dy01?0:1; for (int y = cy0; y!=cy1; y+=step) { const int yy0 = y - y0, x = x0 + (dx01*yy0 + hdy01)/dy01; const float iz = iz0 + diz01*yy0/dy01; tz *const ptrz = is_horizontal?zbuffer.data(y,x):zbuffer.data(x,y); if (x>=0 && x<=w1 && pattern&hatch && iz>=*ptrz) { *ptrz = (tz)iz; T *const ptrd = is_horizontal?data(y,x):data(x,y); cimg_forC(*this,c) { const T val = color[c]; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } } if (!(hatch>>=1)) hatch = ~0U - (~0U>>1); } return *this; } //! Draw a textured 2D line. /** \param x0 X-coordinate of the starting line point. \param y0 Y-coordinate of the starting line point. \param x1 X-coordinate of the ending line point. \param y1 Y-coordinate of the ending line point. \param texture Texture image defining the pixel colors. \param tx0 X-coordinate of the starting texture point. \param ty0 Y-coordinate of the starting texture point. \param tx1 X-coordinate of the ending texture point. \param ty1 Y-coordinate of the ending texture point. \param opacity Drawing opacity. \param pattern An integer whose bits describe the line pattern. \param init_hatch Tells if the hash variable must be reinitialized. \note - Line routine uses the well known Bresenham's algorithm. \par Example: \code CImg<unsigned char> img(100,100,1,3,0), texture("texture256x256.ppm"); const unsigned char color[] = { 255,128,64 }; img.draw_line(40,40,80,70,texture,0,0,255,255); \endcode **/ template<typename tc> CImg<T>& draw_line(int x0, int y0, int x1, int y1, const CImg<tc>& texture, int tx0, int ty0, int tx1, int ty1, const float opacity=1, const unsigned int pattern=~0U, const bool init_hatch=true) { if (is_empty() || !opacity || !pattern) return *this; if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_line(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_overlapped(texture)) return draw_line(x0,y0,x1,y1,+texture,tx0,ty0,tx1,ty1,opacity,pattern,init_hatch); if (std::min(y0,y1)>=height() || std::max(y0,y1)<0 || std::min(x0,x1)>=width() || std::max(x0,x1)<0) return *this; int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dy01 = y1 - y0; int dtx01 = tx1 - tx0, dty01 = ty1 - ty0; const bool is_horizontal = cimg::abs(dx01)>cimg::abs(dy01); if (is_horizontal) cimg::swap(x0,y0,x1,y1,w1,h1,dx01,dy01); if (pattern==~0U && y0>y1) { cimg::swap(x0,x1,y0,y1,tx0,tx1,ty0,ty1); dx01*=-1; dy01*=-1; dtx01*=-1; dty01*=-1; } const ulongT twhd = (ulongT)texture._width*texture._height*texture._depth; static unsigned int hatch = ~0U - (~0U>>1); if (init_hatch) hatch = ~0U - (~0U>>1); cimg_init_scanline(opacity); const int step = y0<=y1?1:-1, hdy01 = dy01*cimg::sign(dx01)/2, hdy01tx = dy01*cimg::sign(dtx01)/2, hdy01ty = dy01*cimg::sign(dty01)/2, cy0 = cimg::cut(y0,0,h1), cy1 = cimg::cut(y1,0,h1) + step; dy01+=dy01?0:1; for (int y = cy0; y!=cy1; y+=step) { const int yy0 = y - y0, x = x0 + (dx01*yy0 + hdy01)/dy01, tx = tx0 + (dtx01*yy0 + hdy01tx)/dy01, ty = ty0 + (dty01*yy0 + hdy01ty)/dy01; if (x>=0 && x<=w1 && pattern&hatch) { T *const ptrd = is_horizontal?data(y,x):data(x,y); const tc *const color = &texture._atXY(tx,ty); cimg_forC(*this,c) { const T val = color[c*twhd]; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } } if (!(hatch>>=1)) hatch = ~0U - (~0U>>1); } return *this; } //! Draw a textured 2D line, with perspective correction. /** \param x0 X-coordinate of the starting point. \param y0 Y-coordinate of the starting point. \param z0 Z-coordinate of the starting point \param x1 X-coordinate of the ending point. \param y1 Y-coordinate of the ending point. \param z1 Z-coordinate of the ending point. \param texture Texture image defining the pixel colors. \param tx0 X-coordinate of the starting texture point. \param ty0 Y-coordinate of the starting texture point. \param tx1 X-coordinate of the ending texture point. \param ty1 Y-coordinate of the ending texture point. \param opacity Drawing opacity. \param pattern An integer whose bits describe the line pattern. \param init_hatch Tells if the hash variable must be reinitialized. **/ template<typename tc> CImg<T>& draw_line(int x0, int y0, const float z0, int x1, int y1, const float z1, const CImg<tc>& texture, const int tx0, const int ty0, const int tx1, const int ty1, const float opacity=1, const unsigned int pattern=~0U, const bool init_hatch=true) { if (is_empty() || z0<=0 || z1<=0 || !opacity || !pattern) return *this; if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_line(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_overlapped(texture)) return draw_line(x0,y0,z0,x1,y1,z1,+texture,tx0,ty0,tx1,ty1,opacity,pattern,init_hatch); if (std::min(y0,y1)>=height() || std::max(y0,y1)<0 || std::min(x0,x1)>=width() || std::max(x0,x1)<0) return *this; float iz0 = 1/z0, iz1 = 1/z1; int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dy01 = y1 - y0; float diz01 = iz1 - iz0, txz0 = tx0*iz0, txz1 = tx1*iz1, tyz0 = ty0*iz0, tyz1 = ty1*iz1, dtxz01 = txz1 - txz0, dtyz01 = tyz1 - tyz0; const bool is_horizontal = cimg::abs(dx01)>cimg::abs(dy01); if (is_horizontal) cimg::swap(x0,y0,x1,y1,w1,h1,dx01,dy01); if (pattern==~0U && y0>y1) { cimg::swap(x0,x1,y0,y1,iz0,iz1,txz0,txz1,tyz0,tyz1); dx01*=-1; dy01*=-1; diz01*=-1; dtxz01*=-1; dtyz01*=-1; } const ulongT twhd = (ulongT)texture._width*texture._height*texture._depth; static unsigned int hatch = ~0U - (~0U>>1); if (init_hatch) hatch = ~0U - (~0U>>1); cimg_init_scanline(opacity); const int step = y0<=y1?1:-1, hdy01 = dy01*cimg::sign(dx01)/2, cy0 = cimg::cut(y0,0,h1), cy1 = cimg::cut(y1,0,h1) + step; dy01+=dy01?0:1; for (int y = cy0; y!=cy1; y+=step) { const int yy0 = y - y0, x = x0 + (dx01*yy0 + hdy01)/dy01; const float iz = iz0 + diz01*yy0/dy01, txz = txz0 + dtxz01*yy0/dy01, tyz = tyz0 + dtyz01*yy0/dy01; if (x>=0 && x<=w1 && pattern&hatch) { const int tx = (int)cimg::round(txz/iz), ty = (int)cimg::round(tyz/iz); T *const ptrd = is_horizontal?data(y,x):data(x,y); const tc *const color = &texture._atXY(tx,ty); cimg_forC(*this,c) { const T val = color[c*twhd]; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } } if (!(hatch>>=1)) hatch = ~0U - (~0U>>1); } return *this; } //! Draw a textured 2D line, with perspective correction and z-buffering. /** \param zbuffer Z-buffer image. \param x0 X-coordinate of the starting point. \param y0 Y-coordinate of the starting point. \param z0 Z-coordinate of the starting point \param x1 X-coordinate of the ending point. \param y1 Y-coordinate of the ending point. \param z1 Z-coordinate of the ending point. \param texture Texture image defining the pixel colors. \param tx0 X-coordinate of the starting texture point. \param ty0 Y-coordinate of the starting texture point. \param tx1 X-coordinate of the ending texture point. \param ty1 Y-coordinate of the ending texture point. \param opacity Drawing opacity. \param pattern An integer whose bits describe the line pattern. \param init_hatch Tells if the hash variable must be reinitialized. **/ template<typename tz, typename tc> CImg<T>& draw_line(CImg<tz>& zbuffer, int x0, int y0, const float z0, int x1, int y1, const float z1, const CImg<tc>& texture, const int tx0, const int ty0, const int tx1, const int ty1, const float opacity=1, const unsigned int pattern=~0U, const bool init_hatch=true) { if (is_empty() || z0<=0 || z1<=0 || !opacity || !pattern) return *this; if (!is_sameXY(zbuffer)) throw CImgArgumentException(_cimg_instance "draw_line(): Instance and specified Z-buffer (%u,%u,%u,%u,%p) have " "different dimensions.", cimg_instance, zbuffer._width,zbuffer._height,zbuffer._depth,zbuffer._spectrum,zbuffer._data); if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_line(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_overlapped(texture)) return draw_line(zbuffer,x0,y0,z0,x1,y1,z1,+texture,tx0,ty0,tx1,ty1,opacity,pattern,init_hatch); if (std::min(y0,y1)>=height() || std::max(y0,y1)<0 || std::min(x0,x1)>=width() || std::max(x0,x1)<0) return *this; float iz0 = 1/z0, iz1 = 1/z1; int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dy01 = y1 - y0; float diz01 = iz1 - iz0, txz0 = tx0*iz0, txz1 = tx1*iz1, tyz0 = ty0*iz0, tyz1 = ty1*iz1, dtxz01 = txz1 - txz0, dtyz01 = tyz1 - tyz0; const bool is_horizontal = cimg::abs(dx01)>cimg::abs(dy01); if (is_horizontal) cimg::swap(x0,y0,x1,y1,w1,h1,dx01,dy01); if (pattern==~0U && y0>y1) { cimg::swap(x0,x1,y0,y1,iz0,iz1,txz0,txz1,tyz0,tyz1); dx01*=-1; dy01*=-1; diz01*=-1; dtxz01*=-1; dtyz01*=-1; } const ulongT twhd = (ulongT)texture._width*texture._height*texture._depth; static unsigned int hatch = ~0U - (~0U>>1); if (init_hatch) hatch = ~0U - (~0U>>1); cimg_init_scanline(opacity); const int step = y0<=y1?1:-1, hdy01 = dy01*cimg::sign(dx01)/2, cy0 = cimg::cut(y0,0,h1), cy1 = cimg::cut(y1,0,h1) + step; dy01+=dy01?0:1; for (int y = cy0; y!=cy1; y+=step) { const int yy0 = y - y0, x = x0 + (dx01*yy0 + hdy01)/dy01; const float iz = iz0 + diz01*yy0/dy01, txz = txz0 + dtxz01*yy0/dy01, tyz = tyz0 + dtyz01*yy0/dy01; tz *const ptrz = is_horizontal?zbuffer.data(y,x):zbuffer.data(x,y); if (x>=0 && x<=w1 && pattern&hatch && iz>=*ptrz) { *ptrz = (tz)iz; const int tx = (int)cimg::round(txz/iz), ty = (int)cimg::round(tyz/iz); T *const ptrd = is_horizontal?data(y,x):data(x,y); const tc *const color = &texture._atXY(tx,ty); cimg_forC(*this,c) { const T val = color[c*twhd]; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } } if (!(hatch>>=1)) hatch = ~0U - (~0U>>1); } return *this; } //! Draw a set of consecutive lines. /** \param points Coordinates of vertices, stored as a list of vectors. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. \param pattern An integer whose bits describe the line pattern. \param init_hatch If set to true, init hatch motif. \note - This function uses several call to the single CImg::draw_line() procedure, depending on the vectors size in \p points. **/ template<typename t, typename tc> CImg<T>& draw_line(const CImg<t>& points, const tc *const color, const float opacity=1, const unsigned int pattern=~0U, const bool init_hatch=true) { if (is_empty() || !points || points._width<2) return *this; bool ninit_hatch = init_hatch; switch (points._height) { case 0 : case 1 : throw CImgArgumentException(_cimg_instance "draw_line(): Invalid specified point set (%u,%u,%u,%u,%p).", cimg_instance, points._width,points._height,points._depth,points._spectrum,points._data); default : { const int x0 = (int)points(0,0), y0 = (int)points(0,1); int ox = x0, oy = y0; for (unsigned int i = 1; i<points._width; ++i) { const int x = (int)points(i,0), y = (int)points(i,1); draw_line(ox,oy,x,y,color,opacity,pattern,ninit_hatch); ninit_hatch = false; ox = x; oy = y; } } } return *this; } //! Draw a 2D arrow. /** \param x0 X-coordinate of the starting arrow point (tail). \param y0 Y-coordinate of the starting arrow point (tail). \param x1 X-coordinate of the ending arrow point (head). \param y1 Y-coordinate of the ending arrow point (head). \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param angle Aperture angle of the arrow head. \param length Length of the arrow head. If negative, describes a percentage of the arrow length. \param opacity Drawing opacity. \param pattern An integer whose bits describe the line pattern. **/ template<typename tc> CImg<T>& draw_arrow(const int x0, const int y0, const int x1, const int y1, const tc *const color, const float opacity=1, const float angle=30, const float length=-10, const unsigned int pattern=~0U) { if (is_empty()) return *this; const float u = (float)(x0 - x1), v = (float)(y0 - y1), sq = u*u + v*v, deg = (float)(angle*cimg::PI/180), ang = (sq>0)?(float)std::atan2(v,u):0.f, l = (length>=0)?length:-length*(float)std::sqrt(sq)/100; if (sq>0) { const float cl = (float)std::cos(ang - deg), sl = (float)std::sin(ang - deg), cr = (float)std::cos(ang + deg), sr = (float)std::sin(ang + deg); const int xl = x1 + (int)(l*cl), yl = y1 + (int)(l*sl), xr = x1 + (int)(l*cr), yr = y1 + (int)(l*sr), xc = x1 + (int)((l + 1)*(cl + cr))/2, yc = y1 + (int)((l + 1)*(sl + sr))/2; draw_line(x0,y0,xc,yc,color,opacity,pattern).draw_triangle(x1,y1,xl,yl,xr,yr,color,opacity); } else draw_point(x0,y0,color,opacity); return *this; } //! Draw a 2D spline. /** \param x0 X-coordinate of the starting curve point \param y0 Y-coordinate of the starting curve point \param u0 X-coordinate of the starting velocity \param v0 Y-coordinate of the starting velocity \param x1 X-coordinate of the ending curve point \param y1 Y-coordinate of the ending curve point \param u1 X-coordinate of the ending velocity \param v1 Y-coordinate of the ending velocity \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param precision Curve drawing precision. \param opacity Drawing opacity. \param pattern An integer whose bits describe the line pattern. \param init_hatch If \c true, init hatch motif. \note - The curve is a 2D cubic Bezier spline, from the set of specified starting/ending points and corresponding velocity vectors. - The spline is drawn as a serie of connected segments. The \p precision parameter sets the average number of pixels in each drawn segment. - A cubic Bezier curve is sometimes defined by a set of 4 points { (\p x0,\p y0), (\p xa,\p ya), (\p xb,\p yb), (\p x1,\p y1) } where (\p x0,\p y0) is the starting point, (\p x1,\p y1) is the ending point and (\p xa,\p ya), (\p xb,\p yb) are two \e control points. The starting and ending velocities (\p u0,\p v0) and (\p u1,\p v1) can be deduced easily from the control points as \p u0 = (\p xa - \p x0), \p v0 = (\p ya - \p y0), \p u1 = (\p x1 - \p xb) and \p v1 = (\p y1 - \p yb). \par Example: \code CImg<unsigned char> img(100,100,1,3,0); const unsigned char color[] = { 255,255,255 }; img.draw_spline(30,30,0,100,90,40,0,-100,color); \endcode **/ template<typename tc> CImg<T>& draw_spline(const int x0, const int y0, const float u0, const float v0, const int x1, const int y1, const float u1, const float v1, const tc *const color, const float opacity=1, const float precision=0.25, const unsigned int pattern=~0U, const bool init_hatch=true) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_spline(): Specified color is (null).", cimg_instance); if (x0==x1 && y0==y1) return draw_point(x0,y0,color,opacity); bool ninit_hatch = init_hatch; const float ax = u0 + u1 + 2*(x0 - x1), bx = 3*(x1 - x0) - 2*u0 - u1, ay = v0 + v1 + 2*(y0 - y1), by = 3*(y1 - y0) - 2*v0 - v1, _precision = 1/(cimg::hypot((float)x0 - x1,(float)y0 - y1)*(precision>0?precision:1)); int ox = x0, oy = y0; for (float t = 0; t<1; t+=_precision) { const float t2 = t*t, t3 = t2*t; const int nx = (int)(ax*t3 + bx*t2 + u0*t + x0), ny = (int)(ay*t3 + by*t2 + v0*t + y0); draw_line(ox,oy,nx,ny,color,opacity,pattern,ninit_hatch); ninit_hatch = false; ox = nx; oy = ny; } return draw_line(ox,oy,x1,y1,color,opacity,pattern,false); } //! Draw a textured 2D spline. /** \param x0 X-coordinate of the starting curve point \param y0 Y-coordinate of the starting curve point \param u0 X-coordinate of the starting velocity \param v0 Y-coordinate of the starting velocity \param x1 X-coordinate of the ending curve point \param y1 Y-coordinate of the ending curve point \param u1 X-coordinate of the ending velocity \param v1 Y-coordinate of the ending velocity \param texture Texture image defining line pixel colors. \param tx0 X-coordinate of the starting texture point. \param ty0 Y-coordinate of the starting texture point. \param tx1 X-coordinate of the ending texture point. \param ty1 Y-coordinate of the ending texture point. \param precision Curve drawing precision. \param opacity Drawing opacity. \param pattern An integer whose bits describe the line pattern. \param init_hatch if \c true, reinit hatch motif. **/ template<typename t> CImg<T>& draw_spline(const int x0, const int y0, const float u0, const float v0, const int x1, const int y1, const float u1, const float v1, const CImg<t>& texture, const int tx0, const int ty0, const int tx1, const int ty1, const float opacity=1, const float precision=4, const unsigned int pattern=~0U, const bool init_hatch=true) { if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_spline(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_empty()) return *this; if (is_overlapped(texture)) return draw_spline(x0,y0,u0,v0,x1,y1,u1,v1,+texture,tx0,ty0,tx1,ty1,precision,opacity,pattern,init_hatch); if (x0==x1 && y0==y1) return draw_point(x0,y0,texture.get_vector_at(x0<=0?0:x0>=texture.width()?texture.width() - 1:x0, y0<=0?0:y0>=texture.height()?texture.height() - 1:y0).data(), opacity); bool ninit_hatch = init_hatch; const float ax = u0 + u1 + 2*(x0 - x1), bx = 3*(x1 - x0) - 2*u0 - u1, ay = v0 + v1 + 2*(y0 - y1), by = 3*(y1 - y0) - 2*v0 - v1, _precision = 1/(cimg::hypot((float)x0 - x1,(float)y0 - y1)*(precision>0?precision:1)); int ox = x0, oy = y0, otx = tx0, oty = ty0; for (float t1 = 0; t1<1; t1+=_precision) { const float t2 = t1*t1, t3 = t2*t1; const int nx = (int)(ax*t3 + bx*t2 + u0*t1 + x0), ny = (int)(ay*t3 + by*t2 + v0*t1 + y0), ntx = tx0 + (int)((tx1 - tx0)*t1), nty = ty0 + (int)((ty1 - ty0)*t1); draw_line(ox,oy,nx,ny,texture,otx,oty,ntx,nty,opacity,pattern,ninit_hatch); ninit_hatch = false; ox = nx; oy = ny; otx = ntx; oty = nty; } return draw_line(ox,oy,x1,y1,texture,otx,oty,tx1,ty1,opacity,pattern,false); } //! Draw a set of consecutive splines. /** \param points Vertices data. \param tangents Tangents data. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. \param is_closed_set Tells if the drawn spline set is closed. \param precision Precision of the drawing. \param pattern An integer whose bits describe the line pattern. \param init_hatch If \c true, init hatch motif. **/ template<typename tp, typename tt, typename tc> CImg<T>& draw_spline(const CImg<tp>& points, const CImg<tt>& tangents, const tc *const color, const float opacity=1, const bool is_closed_set=false, const float precision=4, const unsigned int pattern=~0U, const bool init_hatch=true) { if (is_empty() || !points || !tangents || points._width<2 || tangents._width<2) return *this; bool ninit_hatch = init_hatch; switch (points._height) { case 0 : case 1 : throw CImgArgumentException(_cimg_instance "draw_spline(): Invalid specified point set (%u,%u,%u,%u,%p).", cimg_instance, points._width,points._height,points._depth,points._spectrum,points._data); default : { const int x0 = (int)points(0,0), y0 = (int)points(0,1); const float u0 = (float)tangents(0,0), v0 = (float)tangents(0,1); int ox = x0, oy = y0; float ou = u0, ov = v0; for (unsigned int i = 1; i<points._width; ++i) { const int x = (int)points(i,0), y = (int)points(i,1); const float u = (float)tangents(i,0), v = (float)tangents(i,1); draw_spline(ox,oy,ou,ov,x,y,u,v,color,precision,opacity,pattern,ninit_hatch); ninit_hatch = false; ox = x; oy = y; ou = u; ov = v; } if (is_closed_set) draw_spline(ox,oy,ou,ov,x0,y0,u0,v0,color,precision,opacity,pattern,false); } } return *this; } //! Draw a set of consecutive splines \overloading. /** Similar to previous function, with the point tangents automatically estimated from the given points set. **/ template<typename tp, typename tc> CImg<T>& draw_spline(const CImg<tp>& points, const tc *const color, const float opacity=1, const bool is_closed_set=false, const float precision=4, const unsigned int pattern=~0U, const bool init_hatch=true) { if (is_empty() || !points || points._width<2) return *this; CImg<Tfloat> tangents; switch (points._height) { case 0 : case 1 : throw CImgArgumentException(_cimg_instance "draw_spline(): Invalid specified point set (%u,%u,%u,%u,%p).", cimg_instance, points._width,points._height,points._depth,points._spectrum,points._data); case 2 : { tangents.assign(points._width,points._height); cimg_forX(points,p) { const unsigned int p0 = is_closed_set?(p + points.width() - 1)%points.width():(p?p - 1:0), p1 = is_closed_set?(p + 1)%points.width():(p + 1<points.width()?p + 1:p); const float x = (float)points(p,0), y = (float)points(p,1), x0 = (float)points(p0,0), y0 = (float)points(p0,1), x1 = (float)points(p1,0), y1 = (float)points(p1,1), u0 = x - x0, v0 = y - y0, n0 = 1e-8f + cimg::hypot(u0,v0), u1 = x1 - x, v1 = y1 - y, n1 = 1e-8f + cimg::hypot(u1,v1), u = u0/n0 + u1/n1, v = v0/n0 + v1/n1, n = 1e-8f + cimg::hypot(u,v), fact = 0.5f*(n0 + n1); tangents(p,0) = (Tfloat)(fact*u/n); tangents(p,1) = (Tfloat)(fact*v/n); } } break; default : { tangents.assign(points._width,points._height); cimg_forX(points,p) { const unsigned int p0 = is_closed_set?(p + points.width() - 1)%points.width():(p?p - 1:0), p1 = is_closed_set?(p + 1)%points.width():(p + 1<points.width()?p + 1:p); const float x = (float)points(p,0), y = (float)points(p,1), z = (float)points(p,2), x0 = (float)points(p0,0), y0 = (float)points(p0,1), z0 = (float)points(p0,2), x1 = (float)points(p1,0), y1 = (float)points(p1,1), z1 = (float)points(p1,2), u0 = x - x0, v0 = y - y0, w0 = z - z0, n0 = 1e-8f + cimg::hypot(u0,v0,w0), u1 = x1 - x, v1 = y1 - y, w1 = z1 - z, n1 = 1e-8f + cimg::hypot(u1,v1,w1), u = u0/n0 + u1/n1, v = v0/n0 + v1/n1, w = w0/n0 + w1/n1, n = 1e-8f + cimg::hypot(u,v,w), fact = 0.5f*(n0 + n1); tangents(p,0) = (Tfloat)(fact*u/n); tangents(p,1) = (Tfloat)(fact*v/n); tangents(p,2) = (Tfloat)(fact*w/n); } } } return draw_spline(points,tangents,color,opacity,is_closed_set,precision,pattern,init_hatch); } // [internal] Draw a filled triangle. template<typename tc> CImg<T>& _draw_triangle(int x0, int y0, int x1, int y1, int x2, int y2, const tc *const color, const float opacity, const float brightness) { if (y0>y1) cimg::swap(x0,x1,y0,y1); if (y0>y2) cimg::swap(x0,x2,y0,y2); if (y1>y2) cimg::swap(x1,x2,y1,y2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2; const float cbs = cimg::cut(brightness,0,2); cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02; if (xm>xM) cimg::swap(xm,xM); cimg_draw_scanline(xm,xM,y,color,opacity,cbs); } return *this; } //! Draw a filled 2D triangle. /** \param x0 X-coordinate of the first vertex. \param y0 Y-coordinate of the first vertex. \param x1 X-coordinate of the second vertex. \param y1 Y-coordinate of the second vertex. \param x2 X-coordinate of the third vertex. \param y2 Y-coordinate of the third vertex. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. **/ template<typename tc> CImg<T>& draw_triangle(const int x0, const int y0, const int x1, const int y1, const int x2, const int y2, const tc *const color, const float opacity=1) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_triangle(): Specified color is (null).", cimg_instance); _draw_triangle(x0,y0,x1,y1,x2,y2,color,opacity,1); return *this; } //! Draw a outlined 2D triangle. /** \param x0 X-coordinate of the first vertex. \param y0 Y-coordinate of the first vertex. \param x1 X-coordinate of the second vertex. \param y1 Y-coordinate of the second vertex. \param x2 X-coordinate of the third vertex. \param y2 Y-coordinate of the third vertex. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. \param pattern An integer whose bits describe the outline pattern. **/ template<typename tc> CImg<T>& draw_triangle(const int x0, const int y0, const int x1, const int y1, const int x2, const int y2, const tc *const color, const float opacity, const unsigned int pattern) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_triangle(): Specified color is (null).", cimg_instance); draw_line(x0,y0,x1,y1,color,opacity,pattern,true). draw_line(x1,y1,x2,y2,color,opacity,pattern,false). draw_line(x2,y2,x0,y0,color,opacity,pattern,false); return *this; } //! Draw a filled 2D triangle, with z-buffering. /** \param zbuffer Z-buffer image. \param x0 X-coordinate of the first vertex. \param y0 Y-coordinate of the first vertex. \param z0 Z-coordinate of the first vertex. \param x1 X-coordinate of the second vertex. \param y1 Y-coordinate of the second vertex. \param z1 Z-coordinate of the second vertex. \param x2 X-coordinate of the third vertex. \param y2 Y-coordinate of the third vertex. \param z2 Z-coordinate of the third vertex. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. \param brightness Brightness factor. **/ template<typename tz, typename tc> CImg<T>& draw_triangle(CImg<tz>& zbuffer, int x0, int y0, const float z0, int x1, int y1, const float z1, int x2, int y2, const float z2, const tc *const color, const float opacity=1, const float brightness=1) { if (is_empty() || z0<=0 || z1<=0 || z2<=0) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_triangle(): Specified color is (null).", cimg_instance); if (!is_sameXY(zbuffer)) throw CImgArgumentException(_cimg_instance "draw_triangle(): Instance and specified Z-buffer (%u,%u,%u,%u,%p) have " "different dimensions.", cimg_instance, zbuffer._width,zbuffer._height,zbuffer._depth,zbuffer._spectrum,zbuffer._data); float iz0 = 1/z0, iz1 = 1/z1, iz2 = 1/z2; if (y0>y1) cimg::swap(x0,x1,y0,y1,iz0,iz1); if (y0>y2) cimg::swap(x0,x2,y0,y2,iz0,iz2); if (y1>y2) cimg::swap(x1,x2,y1,y2,iz1,iz2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2; const float diz01 = iz1 - iz0, diz02 = iz2 - iz0, diz12 = iz2 - iz1; const float cbs = cimg::cut(brightness,0,2); cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02; float izm = y<y1?(iz0 + diz01*yy0/dy01):(iz1 + diz12*yy1/dy12), izM = iz0 + diz02*yy0/dy02; if (xm>xM) cimg::swap(xm,xM,izm,izM); if (xM>=0 || xm<=w1) { const int cxm = cimg::cut(xm,0,w1), cxM = cimg::cut(xM,0,w1); T *ptrd = data(cxm,y); tz *ptrz = zbuffer.data(cxm,y); const int dxmM = std::max(1,xM - xm); const float dizmM = izM - izm; for (int x = cxm; x<cxM; ++x) { const int xxm = x - xm; const float iz = izm + dizmM*xxm/dxmM; if (iz>=*ptrz) { *ptrz = (tz)iz; cimg_forC(*this,c) { const Tfloat val = cbs<=1?color[c]*cbs:(2 - cbs)*color[c] + (cbs - 1)*_sc_maxval; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } } ++ptrd; ++ptrz; } } } return *this; } //! Draw a Gouraud-shaded 2D triangle. /** \param x0 X-coordinate of the first vertex in the image instance. \param y0 Y-coordinate of the first vertex in the image instance. \param x1 X-coordinate of the second vertex in the image instance. \param y1 Y-coordinate of the second vertex in the image instance. \param x2 X-coordinate of the third vertex in the image instance. \param y2 Y-coordinate of the third vertex in the image instance. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param bs0 Brightness factor of the first vertex (in [0,2]). \param bs1 brightness factor of the second vertex (in [0,2]). \param bs2 brightness factor of the third vertex (in [0,2]). \param opacity Drawing opacity. **/ template<typename tc> CImg<T>& draw_triangle(int x0, int y0, int x1, int y1, int x2, int y2, const tc *const color, float bs0, float bs1, float bs2, const float opacity=1) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_triangle(): Specified color is (null).", cimg_instance); if (y0>y1) cimg::swap(x0,x1,y0,y1,bs0,bs1); if (y0>y2) cimg::swap(x0,x2,y0,y2,bs0,bs2); if (y1>y2) cimg::swap(x1,x2,y1,y2,bs1,bs2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2; const float dbs01 = bs1 - bs0, dbs02 = bs2 - bs0, dbs12 = bs2 - bs1; cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02; float bsm = y<y1?(bs0 + dbs01*yy0/dy01):(bs1 + dbs12*yy1/dy12), bsM = bs0 + dbs02*yy0/dy02; if (xm>xM) cimg::swap(xm,xM,bsm,bsM); if (xM>=0 || xm<=w1) { const int cxm = cimg::cut(xm,0,w1), cxM = cimg::cut(xM,0,w1); T *ptrd = data(cxm,y); const int dxmM = std::max(1,xM - xm); const float dbsmM = bsM - bsm; for (int x = cxm; x<=cxM; ++x) { const int xxm = x - xm; const float cbs = cimg::cut(bsm + dbsmM*xxm/dxmM,0,2); cimg_forC(*this,c) { const Tfloat val = cbs<=1?color[c]*cbs:(2 - cbs)*color[c] + (cbs - 1)*_sc_maxval; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } ++ptrd; } } } return *this; } //! Draw a Gouraud-shaded 2D triangle, with z-buffering \overloading. template<typename tz, typename tc> CImg<T>& draw_triangle(CImg<tz>& zbuffer, int x0, int y0, const float z0, int x1, int y1, const float z1, int x2, int y2, const float z2, const tc *const color, float bs0, float bs1, float bs2, float opacity=1) { if (is_empty() || z0<=0 || z1<=0 || z2<=0) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_triangle(): Specified color is (null).", cimg_instance); if (!is_sameXY(zbuffer)) throw CImgArgumentException(_cimg_instance "draw_triangle(): Instance and specified Z-buffer (%u,%u,%u,%u,%p) have " "different dimensions.", cimg_instance, zbuffer._width,zbuffer._height,zbuffer._depth,zbuffer._spectrum,zbuffer._data); float iz0 = 1/z0, iz1 = 1/z1, iz2 = 1/z2; if (y0>y1) cimg::swap(x0,x1,y0,y1,iz0,iz1,bs0,bs1); if (y0>y2) cimg::swap(x0,x2,y0,y2,iz0,iz2,bs0,bs2); if (y1>y2) cimg::swap(x1,x2,y1,y2,iz1,iz2,bs1,bs2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2; const float diz01 = iz1 - iz0, diz02 = iz2 - iz0, diz12 = iz2 - iz1, dbs01 = bs1 - bs0, dbs02 = bs2 - bs0, dbs12 = bs2 - bs1; cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02; float izm = y<y1?(iz0 + diz01*yy0/dy01):(iz1 + diz12*yy1/dy12), izM = iz0 + diz02*yy0/dy02, bsm = y<y1?(bs0 + dbs01*yy0/dy01):(bs1 + dbs12*yy1/dy12), bsM = bs0 + dbs02*yy0/dy02; if (xm>xM) cimg::swap(xm,xM,izm,izM,bsm,bsM); if (xM>=0 || xm<=w1) { const int cxm = cimg::cut(xm,0,w1), cxM = cimg::cut(xM,0,w1); T *ptrd = data(cxm,y); tz *ptrz = zbuffer.data(cxm,y); const int dxmM = std::max(1,xM - xm); const float dizmM = izM - izm, dbsmM = bsM - bsm; for (int x = cxm; x<=cxM; ++x) { const int xxm = x - xm; const float iz = izm + dizmM*xxm/dxmM; if (iz>=*ptrz) { *ptrz = (tz)iz; const float cbs = cimg::cut(bsm + dbsmM*xxm/dxmM,0,2); cimg_forC(*this,c) { const Tfloat val = cbs<=1?color[c]*cbs:(2 - cbs)*color[c] + (cbs - 1)*_sc_maxval; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } } ++ptrd; ++ptrz; } } } return *this; } //! Draw a color-interpolated 2D triangle. /** \param x0 X-coordinate of the first vertex in the image instance. \param y0 Y-coordinate of the first vertex in the image instance. \param x1 X-coordinate of the second vertex in the image instance. \param y1 Y-coordinate of the second vertex in the image instance. \param x2 X-coordinate of the third vertex in the image instance. \param y2 Y-coordinate of the third vertex in the image instance. \param color1 Pointer to \c spectrum() consecutive values of type \c T, defining the color of the first vertex. \param color2 Pointer to \c spectrum() consecutive values of type \c T, defining the color of the seconf vertex. \param color3 Pointer to \c spectrum() consecutive values of type \c T, defining the color of the third vertex. \param opacity Drawing opacity. **/ template<typename tc1, typename tc2, typename tc3> CImg<T>& draw_triangle(const int x0, const int y0, const int x1, const int y1, const int x2, const int y2, const tc1 *const color1, const tc2 *const color2, const tc3 *const color3, const float opacity=1) { const unsigned char one = 1; cimg_forC(*this,c) get_shared_channel(c).draw_triangle(x0,y0,x1,y1,x2,y2,&one,color1[c],color2[c],color3[c],opacity); return *this; } //! Draw a textured 2D triangle. /** \param x0 X-coordinate of the first vertex in the image instance. \param y0 Y-coordinate of the first vertex in the image instance. \param x1 X-coordinate of the second vertex in the image instance. \param y1 Y-coordinate of the second vertex in the image instance. \param x2 X-coordinate of the third vertex in the image instance. \param y2 Y-coordinate of the third vertex in the image instance. \param texture Texture image used to fill the triangle. \param tx0 X-coordinate of the first vertex in the texture image. \param ty0 Y-coordinate of the first vertex in the texture image. \param tx1 X-coordinate of the second vertex in the texture image. \param ty1 Y-coordinate of the second vertex in the texture image. \param tx2 X-coordinate of the third vertex in the texture image. \param ty2 Y-coordinate of the third vertex in the texture image. \param opacity Drawing opacity. \param brightness Brightness factor of the drawing (in [0,2]). **/ template<typename tc> CImg<T>& draw_triangle(int x0, int y0, int x1, int y1, int x2, int y2, const CImg<tc>& texture, int tx0, int ty0, int tx1, int ty1, int tx2, int ty2, const float opacity=1, const float brightness=1) { if (is_empty()) return *this; if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_overlapped(texture)) return draw_triangle(x0,y0,x1,y1,x2,y2,+texture,tx0,ty0,tx1,ty1,tx2,ty2,opacity,brightness); if (y0>y1) cimg::swap(x0,x1,y0,y1,tx0,tx1,ty0,ty1); if (y0>y2) cimg::swap(x0,x2,y0,y2,tx0,tx2,ty0,ty2); if (y1>y2) cimg::swap(x1,x2,y1,y2,tx1,ty1,tx2,ty2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2, dtx01 = tx1 - tx0, dtx02 = tx2 - tx0, dtx12 = tx2 - tx1, dty01 = ty1 - ty0, dty02 = ty2 - ty0, dty12 = ty2 - ty1, hdy01tx = dy01*cimg::sign(dtx01)/2, hdy02tx = dy02*cimg::sign(dtx02)/2, hdy12tx = dy12*cimg::sign(dtx12)/2, hdy01ty = dy01*cimg::sign(dty01)/2, hdy02ty = dy02*cimg::sign(dty02)/2, hdy12ty = dy12*cimg::sign(dty12)/2; const ulongT twhd = (ulongT)texture._width*texture._height*texture._depth; const float cbs = cimg::cut(brightness,0,2); cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02, txm = y<y1?tx0 + (dtx01*yy0 + hdy01tx)/dy01:tx1 + (dtx12*yy1 + hdy12tx)/dy12, txM = tx0 + (dtx02*yy0 + hdy02tx)/dy02, tym = y<y1?ty0 + (dty01*yy0 + hdy01ty)/dy01:ty1 + (dty12*yy1 + hdy12ty)/dy12, tyM = ty0 + (dty02*yy0 + hdy02ty)/dy02; if (xm>xM) cimg::swap(xm,xM,txm,txM,tym,tyM); if (xM>=0 || xm<=w1) { const int cxm = cimg::cut(xm,0,w1), cxM = cimg::cut(xM,0,w1); T *ptrd = data(cxm,y); const int dxmM = std::max(1,xM - xm), hdxmM = dxmM/2, dtxmM = txM - txm, dtymM = tyM - tym; for (int x = cxm; x<=cxM; ++x) { const int xxm = x - xm, tx = (txm*dxmM + dtxmM*xxm + hdxmM)/dxmM, ty = (tym*dxmM + dtymM*xxm + hdxmM)/dxmM; const tc *const color = &texture._atXY(tx,ty); cimg_forC(*this,c) { const Tfloat val = cbs<=1?color[c*twhd]*cbs:(2 - cbs)*color[c*twhd] + (cbs - 1)*_sc_maxval; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } ++ptrd; } } } return *this; } //! Draw a 2D textured triangle, with perspective correction. template<typename tc> CImg<T>& draw_triangle(int x0, int y0, const float z0, int x1, int y1, const float z1, int x2, int y2, const float z2, const CImg<tc>& texture, int tx0, int ty0, int tx1, int ty1, int tx2, int ty2, const float opacity=1, const float brightness=1) { if (is_empty() || z0<=0 || z1<=0 || z2<=0) return *this; if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_overlapped(texture)) return draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,+texture,tx0,ty0,tx1,ty1,tx2,ty2,opacity,brightness); float iz0 = 1/z0, iz1 = 1/z1, iz2 = 1/z2; if (y0>y1) cimg::swap(x0,x1,y0,y1,iz0,iz1,tx0,tx1,ty0,ty1); if (y0>y2) cimg::swap(x0,x2,y0,y2,iz0,iz2,tx0,tx2,ty0,ty2); if (y1>y2) cimg::swap(x1,x2,y1,y2,iz1,iz2,tx1,tx2,ty1,ty2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2; const float diz01 = iz1 - iz0, diz02 = iz2 - iz0, diz12 = iz2 - iz1, txz0 = tx0*iz0, txz1 = tx1*iz1, txz2 = tx2*iz2, tyz0 = ty0*iz0, tyz1 = ty1*iz1, tyz2 = ty2*iz2, dtxz01 = txz1 - txz0, dtxz02 = txz2 - txz0, dtxz12 = txz2 - txz1, dtyz01 = tyz1 - tyz0, dtyz02 = tyz2 - tyz0, dtyz12 = tyz2 - tyz1; const ulongT twhd = (ulongT)texture._width*texture._height*texture._depth; const float cbs = cimg::cut(brightness,0,2); cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02; float izm = y<y1?(iz0 + diz01*yy0/dy01):(iz1 + diz12*yy1/dy12), izM = iz0 + diz02*yy0/dy02, txzm = y<y1?(txz0 + dtxz01*yy0/dy01):(txz1 + dtxz12*yy1/dy12), txzM = txz0 + dtxz02*yy0/dy02, tyzm = y<y1?(tyz0 + dtyz01*yy0/dy01):(tyz1 + dtyz12*yy1/dy12), tyzM = tyz0 + dtyz02*yy0/dy02; if (xm>xM) cimg::swap(xm,xM,txzm,txzM,tyzm,tyzM,izm,izM); if (xM>=0 || xm<=w1) { const int cxm = cimg::cut(xm,0,w1), cxM = cimg::cut(xM,0,w1); T *ptrd = data(cxm,y); const int dxmM = std::max(1,xM - xm); const float dizmM = izM - izm, dtxzmM = txzM - txzm, dtyzmM = tyzM - tyzm; for (int x = cxm; x<cxM; ++x) { const int xxm = x - xm; const float iz = izm + dizmM*xxm/dxmM, txz = txzm + dtxzmM*xxm/dxmM, tyz = tyzm + dtyzmM*xxm/dxmM; const int tx = (int)cimg::round(txz/iz), ty = (int)cimg::round(tyz/iz); const tc *const color = &texture._atXY(tx,ty); cimg_forC(*this,c) { const Tfloat val = cbs<=1?color[c*twhd]*cbs:(2 - cbs)*color[c*twhd] + (cbs - 1)*_sc_maxval; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } ++ptrd; } } } return *this; } //! Draw a textured 2D triangle, with perspective correction and z-buffering. template<typename tz, typename tc> CImg<T>& draw_triangle(CImg<tz>& zbuffer, int x0, int y0, const float z0, int x1, int y1, const float z1, int x2, int y2, const float z2, const CImg<tc>& texture, int tx0, int ty0, int tx1, int ty1, int tx2, int ty2, const float opacity=1, const float brightness=1) { if (is_empty() || z0<=0 || z1<=0 || z2<=0) return *this; if (!is_sameXY(zbuffer)) throw CImgArgumentException(_cimg_instance "draw_triangle(): Instance and specified Z-buffer (%u,%u,%u,%u,%p) have " "different dimensions.", cimg_instance, zbuffer._width,zbuffer._height,zbuffer._depth,zbuffer._spectrum,zbuffer._data); if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_overlapped(texture)) return draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,+texture,tx0,ty0,tx1,ty1,tx2,ty2,opacity,brightness); float iz0 = 1/z0, iz1 = 1/z1, iz2 = 1/z2; if (y0>y1) cimg::swap(x0,x1,y0,y1,iz0,iz1,tx0,tx1,ty0,ty1); if (y0>y2) cimg::swap(x0,x2,y0,y2,iz0,iz2,tx0,tx2,ty0,ty2); if (y1>y2) cimg::swap(x1,x2,y1,y2,iz1,iz2,tx1,tx2,ty1,ty2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2; const float diz01 = iz1 - iz0, diz02 = iz2 - iz0, diz12 = iz2 - iz1, txz0 = tx0*iz0, txz1 = tx1*iz1, txz2 = tx2*iz2, tyz0 = ty0*iz0, tyz1 = ty1*iz1, tyz2 = ty2*iz2, dtxz01 = txz1 - txz0, dtxz02 = txz2 - txz0, dtxz12 = txz2 - txz1, dtyz01 = tyz1 - tyz0, dtyz02 = tyz2 - tyz0, dtyz12 = tyz2 - tyz1; const ulongT twhd = (ulongT)texture._width*texture._height*texture._depth; const float cbs = cimg::cut(brightness,0,2); cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02; float izm = y<y1?(iz0 + diz01*yy0/dy01):(iz1 + diz12*yy1/dy12), izM = iz0 + diz02*yy0/dy02, txzm = y<y1?(txz0 + dtxz01*yy0/dy01):(txz1 + dtxz12*yy1/dy12), txzM = txz0 + dtxz02*yy0/dy02, tyzm = y<y1?(tyz0 + dtyz01*yy0/dy01):(tyz1 + dtyz12*yy1/dy12), tyzM = tyz0 + dtyz02*yy0/dy02; if (xm>xM) cimg::swap(xm,xM,txzm,txzM,tyzm,tyzM,izm,izM); if (xM>=0 || xm<=w1) { const int cxm = cimg::cut(xm,0,w1), cxM = cimg::cut(xM,0,w1); T *ptrd = data(cxm,y); tz *ptrz = zbuffer.data(cxm,y); const int dxmM = std::max(1,xM - xm); const float dizmM = izM - izm, dtxzmM = txzM - txzm, dtyzmM = tyzM - tyzm; for (int x = cxm; x<cxM; ++x) { const int xxm = x - xm; const float iz = izm + dizmM*xxm/dxmM; if (iz>=*ptrz) { *ptrz = (tz)iz; const float txz = txzm + dtxzmM*xxm/dxmM, tyz = tyzm + dtyzmM*xxm/dxmM; const int tx = (int)cimg::round(txz/iz), ty = (int)cimg::round(tyz/iz); const tc *const color = &texture._atXY(tx,ty); cimg_forC(*this,c) { const Tfloat val = cbs<=1?color[c*twhd]*cbs:(2 - cbs)*color[c*twhd] + (cbs - 1)*_sc_maxval; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } } ++ptrd; ++ptrz; } } } return *this; } //! Draw a Phong-shaded 2D triangle. /** \param x0 X-coordinate of the first vertex in the image instance. \param y0 Y-coordinate of the first vertex in the image instance. \param x1 X-coordinate of the second vertex in the image instance. \param y1 Y-coordinate of the second vertex in the image instance. \param x2 X-coordinate of the third vertex in the image instance. \param y2 Y-coordinate of the third vertex in the image instance. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param light Light image. \param lx0 X-coordinate of the first vertex in the light image. \param ly0 Y-coordinate of the first vertex in the light image. \param lx1 X-coordinate of the second vertex in the light image. \param ly1 Y-coordinate of the second vertex in the light image. \param lx2 X-coordinate of the third vertex in the light image. \param ly2 Y-coordinate of the third vertex in the light image. \param opacity Drawing opacity. **/ template<typename tc, typename tl> CImg<T>& draw_triangle(int x0, int y0, int x1, int y1, int x2, int y2, const tc *const color, const CImg<tl>& light, int lx0, int ly0, int lx1, int ly1, int lx2, int ly2, const float opacity=1) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_triangle(): Specified color is (null).", cimg_instance); if (light._depth>1 || light._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified light texture (%u,%u,%u,%u,%p).", cimg_instance,light._width,light._height,light._depth,light._spectrum,light._data); if (y0>y1) cimg::swap(x0,x1,y0,y1,lx0,lx1,ly0,ly1); if (y0>y2) cimg::swap(x0,x2,y0,y2,lx0,lx2,ly0,ly2); if (y1>y2) cimg::swap(x1,x2,y1,y2,lx1,lx2,ly1,ly2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2, dlx01 = lx1 - lx0, dlx02 = lx2 - lx0, dlx12 = lx2 - lx1, dly01 = ly1 - ly0, dly02 = ly2 - ly0, dly12 = ly2 - ly1, hdy01lx = dy01*cimg::sign(dlx01)/2, hdy02lx = dy02*cimg::sign(dlx02)/2, hdy12lx = dy12*cimg::sign(dlx12)/2, hdy01ly = dy01*cimg::sign(dly01)/2, hdy02ly = dy02*cimg::sign(dly02)/2, hdy12ly = dy12*cimg::sign(dly12)/2; const ulongT lwhd = (ulongT)light._width*light._height*light._depth; cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02, lxm = y<y1?lx0 + (dlx01*yy0 + hdy01lx)/dy01:lx1 + (dlx12*yy1 + hdy12lx)/dy12, lxM = lx0 + (dlx02*yy0 + hdy02lx)/dy02, lym = y<y1?ly0 + (dly01*yy0 + hdy01ly)/dy01:ly1 + (dly12*yy1 + hdy12ly)/dy12, lyM = ly0 + (dly02*yy0 + hdy02ly)/dy02; if (xm>xM) cimg::swap(xm,xM,lxm,lxM,lym,lyM); if (xM>=0 || xm<=w1) { const int cxm = cimg::cut(xm,0,w1), cxM = cimg::cut(xM,0,w1); T *ptrd = data(cxm,y); const int dxmM = std::max(1,xM - xm), hdxmM = dxmM/2, dlxmM = lxM - lxm, dlymM = lyM - lym; for (int x = cxm; x<cxM; ++x) { const int xxm = x - xm, lx = (lxm*dxmM + dlxmM*xxm + hdxmM)/dxmM, ly = (lym*dxmM + dlymM*xxm + hdxmM)/dxmM; const tl *const lig = &light._atXY(lx,ly); cimg_forC(*this,c) { const tc col = color[c]; const float cbs = cimg::cut((float)lig[c*lwhd],0,2); const Tfloat val = cbs<=1?cbs*col:(2 - cbs)*col + (cbs - 1)*_sc_maxval; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } ++ptrd; } } } return *this; } //! Draw a Phong-shaded 2D triangle, with z-buffering. template<typename tz, typename tc, typename tl> CImg<T>& draw_triangle(CImg<tz>& zbuffer, int x0, int y0, const float z0, int x1, int y1, const float z1, int x2, int y2, const float z2, const tc *const color, const CImg<tl>& light, int lx0, int ly0, int lx1, int ly1, int lx2, int ly2, const float opacity=1) { if (is_empty() || z0<=0 || z1<=0 || z2<=0) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_triangle(): Specified color is (null).", cimg_instance); if (light._depth>1 || light._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified light texture (%u,%u,%u,%u,%p).", cimg_instance,light._width,light._height,light._depth,light._spectrum,light._data); if (!is_sameXY(zbuffer)) throw CImgArgumentException(_cimg_instance "draw_triangle(): Instance and specified Z-buffer (%u,%u,%u,%u,%p) have " "different dimensions.", cimg_instance, zbuffer._width,zbuffer._height,zbuffer._depth,zbuffer._spectrum,zbuffer._data); if (is_overlapped(light)) return draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color, +light,lx0,ly0,lx1,ly1,lx2,ly2,opacity); float iz0 = 1/z0, iz1 = 1/z1, iz2 = 1/z2; if (y0>y1) cimg::swap(x0,x1,y0,y1,iz0,iz1,lx0,lx1,ly0,ly1); if (y0>y2) cimg::swap(x0,x2,y0,y2,iz0,iz2,lx0,lx2,ly0,ly2); if (y1>y2) cimg::swap(x1,x2,y1,y2,iz1,iz2,lx1,lx2,ly1,ly2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2, dlx01 = lx1 - lx0, dlx02 = lx2 - lx0, dlx12 = lx2 - lx1, dly01 = ly1 - ly0, dly02 = ly2 - ly0, dly12 = ly2 - ly1, hdy01lx = dy01*cimg::sign(dlx01)/2, hdy02lx = dy02*cimg::sign(dlx02)/2, hdy12lx = dy12*cimg::sign(dlx12)/2, hdy01ly = dy01*cimg::sign(dly01)/2, hdy02ly = dy02*cimg::sign(dly02)/2, hdy12ly = dy12*cimg::sign(dly12)/2; const float diz01 = iz1 - iz0, diz02 = iz2 - iz0, diz12 = iz2 - iz1; const ulongT lwhd = (ulongT)light._width*light._height*light._depth; cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02, lxm = y<y1?lx0 + (dlx01*yy0 + hdy01lx)/dy01:lx1 + (dlx12*yy1 + hdy12lx)/dy12, lxM = lx0 + (dlx02*yy0 + hdy02lx)/dy02, lym = y<y1?ly0 + (dly01*yy0 + hdy01ly)/dy01:ly1 + (dly12*yy1 + hdy12ly)/dy12, lyM = ly0 + (dly02*yy0 + hdy02ly)/dy02; float izm = y<y1?(iz0 + diz01*yy0/dy01):(iz1 + diz12*yy1/dy12), izM = iz0 + diz02*yy0/dy02; if (xm>xM) cimg::swap(xm,xM,lxm,lxM,lym,lyM,izm,izM); if (xM>=0 || xm<=w1) { const int cxm = cimg::cut(xm,0,w1), cxM = cimg::cut(xM,0,w1); T *ptrd = data(cxm,y); tz *ptrz = zbuffer.data(cxm,y); const int dxmM = std::max(1,xM - xm), hdxmM = dxmM/2, dlxmM = lxM - lxm, dlymM = lyM - lym; const float dizmM = izM - izm; for (int x = cxm; x<cxM; ++x) { const int xxm = x - xm; const float iz = izm + dizmM*xxm/dxmM; if (iz>=*ptrz) { *ptrz = (tz)iz; const int lx = (lxm*dxmM + dlxmM*xxm + hdxmM)/dxmM, ly = (lym*dxmM + dlymM*xxm + hdxmM)/dxmM; const tl *const lig = &light._atXY(lx,ly); cimg_forC(*this,c) { const float cbs = cimg::cut((float)lig[c*lwhd],0,2); const tc col = color[c]; const Tfloat val = cbs<=1?cbs*col:(2 - cbs)*col + (cbs - 1)*_sc_maxval; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } } ++ptrd; ++ptrz; } } } return *this; } //! Draw a textured Gouraud-shaded 2D triangle. /** \param x0 X-coordinate of the first vertex in the image instance. \param y0 Y-coordinate of the first vertex in the image instance. \param x1 X-coordinate of the second vertex in the image instance. \param y1 Y-coordinate of the second vertex in the image instance. \param x2 X-coordinate of the third vertex in the image instance. \param y2 Y-coordinate of the third vertex in the image instance. \param texture Texture image used to fill the triangle. \param tx0 X-coordinate of the first vertex in the texture image. \param ty0 Y-coordinate of the first vertex in the texture image. \param tx1 X-coordinate of the second vertex in the texture image. \param ty1 Y-coordinate of the second vertex in the texture image. \param tx2 X-coordinate of the third vertex in the texture image. \param ty2 Y-coordinate of the third vertex in the texture image. \param bs0 Brightness factor of the first vertex. \param bs1 Brightness factor of the second vertex. \param bs2 Brightness factor of the third vertex. \param opacity Drawing opacity. **/ template<typename tc> CImg<T>& draw_triangle(int x0, int y0, int x1, int y1, int x2, int y2, const CImg<tc>& texture, int tx0, int ty0, int tx1, int ty1, int tx2, int ty2, float bs0, float bs1, float bs2, const float opacity=1) { if (is_empty()) return *this; if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_overlapped(texture)) return draw_triangle(x0,y0,x1,y1,x2,y2,+texture,tx0,ty0,tx1,ty1,tx2,ty2, bs0,bs1,bs2,opacity); if (y0>y1) cimg::swap(x0,x1,y0,y1,tx0,tx1,ty0,ty1,bs0,bs1); if (y0>y2) cimg::swap(x0,x2,y0,y2,tx0,tx2,ty0,ty2,bs0,bs2); if (y1>y2) cimg::swap(x1,x2,y1,y2,tx1,tx2,ty1,ty2,bs1,bs2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2, dtx01 = tx1 - tx0, dtx02 = tx2 - tx0, dtx12 = tx2 - tx1, dty01 = ty1 - ty0, dty02 = ty2 - ty0, dty12 = ty2 - ty1, hdy01tx = dy01*cimg::sign(dtx01)/2, hdy02tx = dy02*cimg::sign(dtx02)/2, hdy12tx = dy12*cimg::sign(dtx12)/2, hdy01ty = dy01*cimg::sign(dty01)/2, hdy02ty = dy02*cimg::sign(dty02)/2, hdy12ty = dy12*cimg::sign(dty12)/2; const float dbs01 = bs1 - bs0, dbs02 = bs2 - bs0, dbs12 = bs2 - bs1; const ulongT twhd = (ulongT)texture._width*texture._height*texture._depth; cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02, txm = y<y1?tx0 + (dtx01*yy0 + hdy01tx)/dy01:tx1 + (dtx12*yy1 + hdy12tx)/dy12, txM = tx0 + (dtx02*yy0 + hdy02tx)/dy02, tym = y<y1?ty0 + (dty01*yy0 + hdy01ty)/dy01:ty1 + (dty12*yy1 + hdy12ty)/dy12, tyM = ty0 + (dty02*yy0 + hdy02ty)/dy02; float bsm = y<y1?(bs0 + dbs01*yy0/dy01):(bs1 + dbs12*yy1/dy12), bsM = bs0 + dbs02*yy0/dy02; if (xm>xM) cimg::swap(xm,xM,txm,txM,tym,tyM,bsm,bsM); if (xM>=0 || xm<=w1) { const int cxm = cimg::cut(xm,0,w1), cxM = cimg::cut(xM,0,w1); T *ptrd = data(cxm,y); const int dxmM = std::max(1,xM - xm), hdxmM = dxmM/2, dtxmM = txM - txm, dtymM = tyM - tym; const float dbsmM = bsM - bsm; for (int x = cxm; x<cxM; ++x) { const int xxm = x - xm, tx = (txm*dxmM + dtxmM*xxm + hdxmM)/dxmM, ty = (tym*dxmM + dtymM*xxm + hdxmM)/dxmM; const float cbs = cimg::cut(bsm + dbsmM*xxm/dxmM,0,2); const tc *const color = &texture._atXY(tx,ty); cimg_forC(*this,c) { const tc col = color[c*twhd]; const Tfloat val = cbs<=1?cbs*col:(2 - cbs)*col + (cbs - 1)*_sc_maxval; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } ++ptrd; } } } return *this; } //! Draw a textured Gouraud-shaded 2D triangle, with perspective correction \overloading. template<typename tc> CImg<T>& draw_triangle(int x0, int y0, const float z0, int x1, int y1, const float z1, int x2, int y2, const float z2, const CImg<tc>& texture, int tx0, int ty0, int tx1, int ty1, int tx2, int ty2, float bs0, float bs1, float bs2, const float opacity=1) { if (is_empty() || z0<=0 || z1<=0 || z2<=0) return *this; if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_overlapped(texture)) return draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,+texture,tx0,ty0,tx1,ty1,tx2,ty2, bs0,bs1,bs2,opacity); float iz0 = 1/z0, iz1 = 1/z1, iz2 = 1/z2; if (y0>y1) cimg::swap(x0,x1,y0,y1,iz0,iz1,tx0,tx1,ty0,ty1,bs0,bs1); if (y0>y2) cimg::swap(x0,x2,y0,y2,iz0,iz2,tx0,tx2,ty0,ty2,bs0,bs2); if (y1>y2) cimg::swap(x1,x2,y1,y2,iz1,iz2,tx1,tx2,ty1,ty2,bs1,bs2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2; const float diz01 = iz1 - iz0, diz02 = iz2 - iz0, diz12 = iz2 - iz1, txz0 = tx0*iz0, txz1 = tx1*iz1, txz2 = tx2*iz2, tyz0 = ty0*iz0, tyz1 = ty1*iz1, tyz2 = ty2*iz2, dtxz01 = txz1 - txz0, dtxz02 = txz2 - txz0, dtxz12 = txz2 - txz1, dtyz01 = tyz1 - tyz0, dtyz02 = tyz2 - tyz0, dtyz12 = tyz2 - tyz1, dbs01 = bs1 - bs0, dbs02 = bs2 - bs0, dbs12 = bs2 - bs1; const ulongT twhd = (ulongT)texture._width*texture._height*texture._depth; cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02; float izm = y<y1?(iz0 + diz01*yy0/dy01):(iz1 + diz12*yy1/dy12), izM = iz0 + diz02*yy0/dy02, txzm = y<y1?(txz0 + dtxz01*yy0/dy01):(txz1 + dtxz12*yy1/dy12), txzM = txz0 + dtxz02*yy0/dy02, tyzm = y<y1?(tyz0 + dtyz01*yy0/dy01):(tyz1 + dtyz12*yy1/dy12), tyzM = tyz0 + dtyz02*yy0/dy02, bsm = y<y1?(bs0 + dbs01*yy0/dy01):(bs1 + dbs12*yy1/dy12), bsM = bs0 + dbs02*yy0/dy02; if (xm>xM) cimg::swap(xm,xM,txzm,txzM,tyzm,tyzM,izm,izM,bsm,bsM); if (xM>=0 || xm<=w1) { const int cxm = cimg::cut(xm,0,w1), cxM = cimg::cut(xM,0,w1); T *ptrd = data(cxm,y); const int dxmM = std::max(1,xM - xm); const float dizmM = izM - izm, dtxzmM = txzM - txzm, dtyzmM = tyzM - tyzm, dbsmM = bsM - bsm; for (int x = cxm; x<cxM; ++x) { const int xxm = x - xm; const float iz = izm + dizmM*xxm/dxmM, txz = txzm + dtxzmM*xxm/dxmM, tyz = tyzm + dtyzmM*xxm/dxmM, cbs = cimg::cut(bsm + dbsmM*xxm/dxmM,0,2); const int tx = (int)cimg::round(txz/iz), ty = (int)cimg::round(tyz/iz); const tc *const color = &texture._atXY(tx,ty); cimg_forC(*this,c) { const tc col = color[c*twhd]; const Tfloat val = cbs<=1?cbs*col:(2 - cbs)*col + (cbs - 1)*_sc_maxval; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } ++ptrd; } } } return *this; } //! Draw a textured Gouraud-shaded 2D triangle, with perspective correction and z-buffering \overloading. template<typename tz, typename tc> CImg<T>& draw_triangle(CImg<tz>& zbuffer, int x0, int y0, const float z0, int x1, int y1, const float z1, int x2, int y2, const float z2, const CImg<tc>& texture, int tx0, int ty0, int tx1, int ty1, int tx2, int ty2, float bs0, float bs1, float bs2, const float opacity=1) { if (is_empty() || z0<=0 || z1<=0 || z2<=0) return *this; if (!is_sameXY(zbuffer)) throw CImgArgumentException(_cimg_instance "draw_triangle(): Instance and specified Z-buffer (%u,%u,%u,%u,%p) have " "different dimensions.", cimg_instance, zbuffer._width,zbuffer._height,zbuffer._depth,zbuffer._spectrum,zbuffer._data); if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_overlapped(texture)) return draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,+texture,tx0,ty0,tx1,ty1,tx2,ty2,bs0,bs1,bs2,opacity); float iz0 = 1/z0, iz1 = 1/z1, iz2 = 1/z2; if (y0>y1) cimg::swap(x0,x1,y0,y1,iz0,iz1,tx0,tx1,ty0,ty1,bs0,bs1); if (y0>y2) cimg::swap(x0,x2,y0,y2,iz0,iz2,tx0,tx2,ty0,ty2,bs0,bs2); if (y1>y2) cimg::swap(x1,x2,y1,y2,iz1,iz2,tx1,tx2,ty1,ty2,bs1,bs2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2; const float diz01 = iz1 - iz0, diz02 = iz2 - iz0, diz12 = iz2 - iz1, txz0 = tx0*iz0, txz1 = tx1*iz1, txz2 = tx2*iz2, tyz0 = ty0*iz0, tyz1 = ty1*iz1, tyz2 = ty2*iz2, dtxz01 = txz1 - txz0, dtxz02 = txz2 - txz0, dtxz12 = txz2 - txz1, dtyz01 = tyz1 - tyz0, dtyz02 = tyz2 - tyz0, dtyz12 = tyz2 - tyz1, dbs01 = bs1 - bs0, dbs02 = bs2 - bs0, dbs12 = bs2 - bs1; const ulongT twhd = (ulongT)texture._width*texture._height*texture._depth; cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02; float izm = y<y1?(iz0 + diz01*yy0/dy01):(iz1 + diz12*yy1/dy12), izM = iz0 + diz02*yy0/dy02, txzm = y<y1?(txz0 + dtxz01*yy0/dy01):(txz1 + dtxz12*yy1/dy12), txzM = txz0 + dtxz02*yy0/dy02, tyzm = y<y1?(tyz0 + dtyz01*yy0/dy01):(tyz1 + dtyz12*yy1/dy12), tyzM = tyz0 + dtyz02*yy0/dy02, bsm = y<y1?(bs0 + dbs01*yy0/dy01):(bs1 + dbs12*yy1/dy12), bsM = bs0 + dbs02*yy0/dy02; if (xm>xM) cimg::swap(xm,xM,txzm,txzM,tyzm,tyzM,izm,izM,bsm,bsM); if (xM>=0 || xm<=w1) { const int cxm = cimg::cut(xm,0,w1), cxM = cimg::cut(xM,0,w1); T *ptrd = data(cxm,y); tz *ptrz = zbuffer.data(cxm,y); const int dxmM = std::max(1,xM - xm); const float dizmM = izM - izm, dtxzmM = txzM - txzm, dtyzmM = tyzM - tyzm, dbsmM = bsM - bsm; for (int x = cxm; x<cxM; ++x) { const int xxm = x - xm; const float iz = izm + dizmM*xxm/dxmM; if (iz>=*ptrz) { *ptrz = (tz)iz; const float txz = txzm + dtxzmM*xxm/dxmM, tyz = tyzm + dtyzmM*xxm/dxmM, cbs = cimg::cut(bsm + dbsmM*xxm/dxmM,0,2); const int tx = (int)cimg::round(txz/iz), ty = (int)cimg::round(tyz/iz); const tc *const color = &texture._atXY(tx,ty); cimg_forC(*this,c) { const tc col = color[c*twhd]; const Tfloat val = cbs<=1?cbs*col:(2 - cbs)*col + (cbs - 1)*_sc_maxval; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } } ++ptrd; ++ptrz; } } } return *this; } //! Draw a textured Phong-shaded 2D triangle. /** \param x0 X-coordinate of the first vertex in the image instance. \param y0 Y-coordinate of the first vertex in the image instance. \param x1 X-coordinate of the second vertex in the image instance. \param y1 Y-coordinate of the second vertex in the image instance. \param x2 X-coordinate of the third vertex in the image instance. \param y2 Y-coordinate of the third vertex in the image instance. \param texture Texture image used to fill the triangle. \param tx0 X-coordinate of the first vertex in the texture image. \param ty0 Y-coordinate of the first vertex in the texture image. \param tx1 X-coordinate of the second vertex in the texture image. \param ty1 Y-coordinate of the second vertex in the texture image. \param tx2 X-coordinate of the third vertex in the texture image. \param ty2 Y-coordinate of the third vertex in the texture image. \param light Light image. \param lx0 X-coordinate of the first vertex in the light image. \param ly0 Y-coordinate of the first vertex in the light image. \param lx1 X-coordinate of the second vertex in the light image. \param ly1 Y-coordinate of the second vertex in the light image. \param lx2 X-coordinate of the third vertex in the light image. \param ly2 Y-coordinate of the third vertex in the light image. \param opacity Drawing opacity. **/ template<typename tc, typename tl> CImg<T>& draw_triangle(int x0, int y0, int x1, int y1, int x2, int y2, const CImg<tc>& texture, int tx0, int ty0, int tx1, int ty1, int tx2, int ty2, const CImg<tl>& light, int lx0, int ly0, int lx1, int ly1, int lx2, int ly2, const float opacity=1) { if (is_empty()) return *this; if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (light._depth>1 || light._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified light texture (%u,%u,%u,%u,%p).", cimg_instance,light._width,light._height,light._depth,light._spectrum,light._data); if (is_overlapped(texture)) return draw_triangle(x0,y0,x1,y1,x2,y2,+texture,tx0,ty0,tx1,ty1,tx2,ty2,light,lx0,ly0,lx1,ly1,lx2,ly2,opacity); if (is_overlapped(light)) return draw_triangle(x0,y0,x1,y1,x2,y2,texture,tx0,ty0,tx1,ty1,tx2,ty2,+light,lx0,ly0,lx1,ly1,lx2,ly2,opacity); if (y0>y1) cimg::swap(x0,x1,y0,y1,tx0,tx1,ty0,ty1,lx0,lx1,ly0,ly1); if (y0>y2) cimg::swap(x0,x2,y0,y2,tx0,tx2,ty0,ty2,lx0,lx2,ly0,ly2); if (y1>y2) cimg::swap(x1,x2,y1,y2,tx1,tx2,ty1,ty2,lx1,lx2,ly1,ly2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2, dtx01 = tx1 - tx0, dtx02 = tx2 - tx0, dtx12 = tx2 - tx1, dty01 = ty1 - ty0, dty02 = ty2 - ty0, dty12 = ty2 - ty1, hdy01tx = dy01*cimg::sign(dtx01)/2, hdy02tx = dy02*cimg::sign(dtx02)/2, hdy12tx = dy12*cimg::sign(dtx12)/2, hdy01ty = dy01*cimg::sign(dty01)/2, hdy02ty = dy02*cimg::sign(dty02)/2, hdy12ty = dy12*cimg::sign(dty12)/2, dlx01 = lx1 - lx0, dlx02 = lx2 - lx0, dlx12 = lx2 - lx1, dly01 = ly1 - ly0, dly02 = ly2 - ly0, dly12 = ly2 - ly1, hdy01lx = dy01*cimg::sign(dlx01)/2, hdy02lx = dy02*cimg::sign(dlx02)/2, hdy12lx = dy12*cimg::sign(dlx12)/2, hdy01ly = dy01*cimg::sign(dly01)/2, hdy02ly = dy02*cimg::sign(dly02)/2, hdy12ly = dy12*cimg::sign(dly12)/2; const ulongT twhd = (ulongT)texture._width*texture._height*texture._depth, lwhd = (ulongT)light._width*light._height*light._depth; cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02, txm = y<y1?tx0 + (dtx01*yy0 + hdy01tx)/dy01:tx1 + (dtx12*yy1 + hdy12tx)/dy12, txM = tx0 + (dtx02*yy0 + hdy02tx)/dy02, tym = y<y1?ty0 + (dty01*yy0 + hdy01ty)/dy01:ty1 + (dty12*yy1 + hdy12ty)/dy12, tyM = ty0 + (dty02*yy0 + hdy02ty)/dy02, lxm = y<y1?lx0 + (dlx01*yy0 + hdy01lx)/dy01:lx1 + (dlx12*yy1 + hdy12lx)/dy12, lxM = lx0 + (dlx02*yy0 + hdy02lx)/dy02, lym = y<y1?ly0 + (dly01*yy0 + hdy01ly)/dy01:ly1 + (dly12*yy1 + hdy12ly)/dy12, lyM = ly0 + (dly02*yy0 + hdy02ly)/dy02; if (xm>xM) cimg::swap(xm,xM,txm,txM,tym,tyM,lxm,lxM,lym,lyM); if (xM>=0 || xm<=w1) { const int cxm = cimg::cut(xm,0,w1), cxM = cimg::cut(xM,0,w1); T *ptrd = data(cxm,y); const int dxmM = std::max(1,xM - xm), hdxmM = dxmM/2, dtxmM = txM - txm, dtymM = tyM - tym, dlxmM = lxM - lxm, dlymM = lyM - lym; for (int x = cxm; x<cxM; ++x) { const int xxm = x - xm, tx = (txm*dxmM + dtxmM*xxm + hdxmM)/dxmM, ty = (tym*dxmM + dtymM*xxm + hdxmM)/dxmM, lx = (lxm*dxmM + dlxmM*xxm + hdxmM)/dxmM, ly = (lym*dxmM + dlymM*xxm + hdxmM)/dxmM; const tc *const color = &texture._atXY(tx,ty); const tl *const lig = &light._atXY(lx,ly); cimg_forC(*this,c) { const tc col = color[c*twhd]; const float cbs = cimg::cut((float)lig[c*lwhd],0,2); const Tfloat val = cbs<=1?cbs*col:(2 - cbs)*col + (cbs - 1)*_sc_maxval; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } ++ptrd; } } } return *this; } //! Draw a textured Phong-shaded 2D triangle, with perspective correction. template<typename tc, typename tl> CImg<T>& draw_triangle(int x0, int y0, const float z0, int x1, int y1, const float z1, int x2, int y2, const float z2, const CImg<tc>& texture, int tx0, int ty0, int tx1, int ty1, int tx2, int ty2, const CImg<tl>& light, int lx0, int ly0, int lx1, int ly1, int lx2, int ly2, const float opacity=1) { if (is_empty() || z0<=0 || z1<=0 || z2<=0) return *this; if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (light._depth>1 || light._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified light texture (%u,%u,%u,%u,%p).", cimg_instance,light._width,light._height,light._depth,light._spectrum,light._data); if (is_overlapped(texture)) return draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,+texture,tx0,ty0,tx1,ty1,tx2,ty2, light,lx0,ly0,lx1,ly1,lx2,ly2,opacity); if (is_overlapped(light)) return draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,texture,tx0,ty0,tx1,ty1,tx2,ty2, +light,lx0,ly0,lx1,ly1,lx2,ly2,opacity); float iz0 = 1/z0, iz1 = 1/z1, iz2 = 1/z2; if (y0>y1) cimg::swap(x0,x1,y0,y1,iz0,iz1,tx0,tx1,ty0,ty1,lx0,lx1,ly0,ly1); if (y0>y2) cimg::swap(x0,x2,y0,y2,iz0,iz2,tx0,tx2,ty0,ty2,lx0,lx2,ly0,ly2); if (y1>y2) cimg::swap(x1,x2,y1,y2,iz1,iz2,tx1,tx2,ty1,ty2,lx1,lx2,ly1,ly2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2; const float diz01 = iz1 - iz0, diz02 = iz2 - iz0, diz12 = iz2 - iz1, txz0 = tx0*iz0, txz1 = tx1*iz1, txz2 = tx2*iz2, tyz0 = ty0*iz0, tyz1 = ty1*iz1, tyz2 = ty2*iz2, dtxz01 = txz1 - txz0, dtxz02 = txz2 - txz0, dtxz12 = txz2 - txz1, dtyz01 = tyz1 - tyz0, dtyz02 = tyz2 - tyz0, dtyz12 = tyz2 - tyz1, lxz0 = lx0*iz0, lxz1 = lx1*iz1, lxz2 = lx2*iz2, lyz0 = ly0*iz0, lyz1 = ly1*iz1, lyz2 = ly2*iz2, dlxz01 = lxz1 - lxz0, dlxz02 = lxz2 - lxz0, dlxz12 = lxz2 - lxz1, dlyz01 = lyz1 - lyz0, dlyz02 = lyz2 - lyz0, dlyz12 = lyz2 - lyz1; const ulongT twhd = (ulongT)texture._width*texture._height*texture._depth, lwhd = (ulongT)light._width*light._height*light._depth; cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02; float izm = y<y1?(iz0 + diz01*yy0/dy01):(iz1 + diz12*yy1/dy12), izM = iz0 + diz02*yy0/dy02, txzm = y<y1?(txz0 + dtxz01*yy0/dy01):(txz1 + dtxz12*yy1/dy12), txzM = txz0 + dtxz02*yy0/dy02, tyzm = y<y1?(tyz0 + dtyz01*yy0/dy01):(tyz1 + dtyz12*yy1/dy12), tyzM = tyz0 + dtyz02*yy0/dy02, lxzm = y<y1?(lxz0 + dlxz01*yy0/dy01):(lxz1 + dlxz12*yy1/dy12), lxzM = lxz0 + dlxz02*yy0/dy02, lyzm = y<y1?(lyz0 + dlyz01*yy0/dy01):(lyz1 + dlyz12*yy1/dy12), lyzM = lyz0 + dlyz02*yy0/dy02; if (xm>xM) cimg::swap(xm,xM,izm,izM,txzm,txzM,tyzm,tyzM,lxzm,lxzM,lyzm,lyzM); if (xM>=0 || xm<=w1) { const int cxm = cimg::cut(xm,0,w1), cxM = cimg::cut(xM,0,w1); T *ptrd = data(cxm,y); const int dxmM = std::max(1,xM - xm); const float dizmM = izM - izm, dtxzmM = txzM - txzm, dtyzmM = tyzM - tyzm, dlxzmM = lxzM - lxzm, dlyzmM = lyzM - lyzm; for (int x = cxm; x<cxM; ++x) { const int xxm = x - xm; const float iz = izm + dizmM*xxm/dxmM, txz = txzm + dtxzmM*xxm/dxmM, tyz = tyzm + dtyzmM*xxm/dxmM, lxz = lxzm + dlxzmM*xxm/dxmM, lyz = lyzm + dlyzmM*xxm/dxmM; const int tx = (int)cimg::round(txz/iz), ty = (int)cimg::round(tyz/iz), lx = (int)cimg::round(lxz/iz), ly = (int)cimg::round(lyz/iz); const tc *const color = &texture._atXY(tx,ty); const tl *const lig = &light._atXY(lx,ly); cimg_forC(*this,c) { const tc col = color[c*twhd]; const float cbs = cimg::cut((float)lig[c*lwhd],0,2); const Tfloat val = cbs<=1?cbs*col:(2 - cbs)*col + (cbs - 1)*_sc_maxval; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } ++ptrd; } } } return *this; } //! Draw a textured Phong-shaded 2D triangle, with perspective correction and z-buffering. template<typename tz, typename tc, typename tl> CImg<T>& draw_triangle(CImg<tz>& zbuffer, int x0, int y0, const float z0, int x1, int y1, const float z1, int x2, int y2, const float z2, const CImg<tc>& texture, int tx0, int ty0, int tx1, int ty1, int tx2, int ty2, const CImg<tl>& light, int lx0, int ly0, int lx1, int ly1, int lx2, int ly2, const float opacity=1) { if (is_empty() || z0<=0 || z1<=0 || z2<=0) return *this; if (!is_sameXY(zbuffer)) throw CImgArgumentException(_cimg_instance "draw_triangle(): Instance and specified Z-buffer (%u,%u,%u,%u,%p) have " "different dimensions.", cimg_instance, zbuffer._width,zbuffer._height,zbuffer._depth,zbuffer._spectrum,zbuffer._data); if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (light._depth>1 || light._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified light texture (%u,%u,%u,%u,%p).", cimg_instance,light._width,light._height,light._depth,light._spectrum,light._data); if (is_overlapped(texture)) return draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2, +texture,tx0,ty0,tx1,ty1,tx2,ty2,light,lx0,ly0,lx1,ly1,lx2,ly2,opacity); if (is_overlapped(light)) return draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2, texture,tx0,ty0,tx1,ty1,tx2,ty2,+light,lx0,ly0,lx1,ly1,lx2,ly2,opacity); float iz0 = 1/z0, iz1 = 1/z1, iz2 = 1/z2; if (y0>y1) cimg::swap(x0,x1,y0,y1,iz0,iz1,tx0,tx1,ty0,ty1,lx0,lx1,ly0,ly1); if (y0>y2) cimg::swap(x0,x2,y0,y2,iz0,iz2,tx0,tx2,ty0,ty2,lx0,lx2,ly0,ly2); if (y1>y2) cimg::swap(x1,x2,y1,y2,iz1,iz2,tx1,tx2,ty1,ty2,lx1,lx2,ly1,ly2); if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this; const int w1 = width() - 1, h1 = height() - 1, dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1, dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1), cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1), hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2; const float diz01 = iz1 - iz0, diz02 = iz2 - iz0, diz12 = iz2 - iz1, txz0 = tx0*iz0, txz1 = tx1*iz1, txz2 = tx2*iz2, tyz0 = ty0*iz0, tyz1 = ty1*iz1, tyz2 = ty2*iz2, dtxz01 = txz1 - txz0, dtxz02 = txz2 - txz0, dtxz12 = txz2 - txz1, dtyz01 = tyz1 - tyz0, dtyz02 = tyz2 - tyz0, dtyz12 = tyz2 - tyz1, lxz0 = lx0*iz0, lxz1 = lx1*iz1, lxz2 = lx2*iz2, lyz0 = ly0*iz0, lyz1 = ly1*iz1, lyz2 = ly2*iz2, dlxz01 = lxz1 - lxz0, dlxz02 = lxz2 - lxz0, dlxz12 = lxz2 - lxz1, dlyz01 = lyz1 - lyz0, dlyz02 = lyz2 - lyz0, dlyz12 = lyz2 - lyz1; const ulongT twhd = (ulongT)texture._width*texture._height*texture._depth, lwhd = (ulongT)light._width*light._height*light._depth; cimg_init_scanline(opacity); for (int y = cy0; y<=cy2; ++y) { const int yy0 = y - y0, yy1 = y - y1; int xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12, xM = x0 + (dx02*yy0 + hdy02)/dy02; float izm = y<y1?(iz0 + diz01*yy0/dy01):(iz1 + diz12*yy1/dy12), izM = iz0 + diz02*yy0/dy02, txzm = y<y1?(txz0 + dtxz01*yy0/dy01):(txz1 + dtxz12*yy1/dy12), txzM = txz0 + dtxz02*yy0/dy02, tyzm = y<y1?(tyz0 + dtyz01*yy0/dy01):(tyz1 + dtyz12*yy1/dy12), tyzM = tyz0 + dtyz02*yy0/dy02, lxzm = y<y1?(lxz0 + dlxz01*yy0/dy01):(lxz1 + dlxz12*yy1/dy12), lxzM = lxz0 + dlxz02*yy0/dy02, lyzm = y<y1?(lyz0 + dlyz01*yy0/dy01):(lyz1 + dlyz12*yy1/dy12), lyzM = lyz0 + dlyz02*yy0/dy02; if (xm>xM) cimg::swap(xm,xM,izm,izM,txzm,txzM,tyzm,tyzM,lxzm,lxzM,lyzm,lyzM); if (xM>=0 || xm<=w1) { const int cxm = cimg::cut(xm,0,w1), cxM = cimg::cut(xM,0,w1); T *ptrd = data(cxm,y); tz *ptrz = zbuffer.data(cxm,y); const int dxmM = std::max(1,xM - xm); const float dizmM = izM - izm, dtxzmM = txzM - txzm, dtyzmM = tyzM - tyzm, dlxzmM = lxzM - lxzm, dlyzmM = lyzM - lyzm; for (int x = cxm; x<cxM; ++x) { const int xxm = x - xm; const float iz = izm + dizmM*xxm/dxmM; if (iz>=*ptrz) { *ptrz = (tz)iz; const float txz = txzm + dtxzmM*xxm/dxmM, tyz = tyzm + dtyzmM*xxm/dxmM, lxz = lxzm + dlxzmM*xxm/dxmM, lyz = lyzm + dlyzmM*xxm/dxmM; const int tx = (int)cimg::round(txz/iz), ty = (int)cimg::round(tyz/iz), lx = (int)cimg::round(lxz/iz), ly = (int)cimg::round(lyz/iz); const tc *const color = &texture._atXY(tx,ty); const tl *const lig = &light._atXY(lx,ly); cimg_forC(*this,c) { const tc col = color[c*twhd]; const float cbs = cimg::cut((float)lig[c*lwhd],0,2); const Tfloat val = cbs<=1?cbs*col:(2 - cbs)*col + (cbs - 1)*_sc_maxval; ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity); } } ++ptrd; ++ptrz; } } } return *this; } //! Draw a filled 4D rectangle. /** \param x0 X-coordinate of the upper-left rectangle corner. \param y0 Y-coordinate of the upper-left rectangle corner. \param z0 Z-coordinate of the upper-left rectangle corner. \param c0 C-coordinate of the upper-left rectangle corner. \param x1 X-coordinate of the lower-right rectangle corner. \param y1 Y-coordinate of the lower-right rectangle corner. \param z1 Z-coordinate of the lower-right rectangle corner. \param c1 C-coordinate of the lower-right rectangle corner. \param val Scalar value used to fill the rectangle area. \param opacity Drawing opacity. **/ CImg<T>& draw_rectangle(const int x0, const int y0, const int z0, const int c0, const int x1, const int y1, const int z1, const int c1, const T val, const float opacity=1) { if (is_empty()) return *this; const int nx0 = x0<x1?x0:x1, nx1 = x0^x1^nx0, ny0 = y0<y1?y0:y1, ny1 = y0^y1^ny0, nz0 = z0<z1?z0:z1, nz1 = z0^z1^nz0, nc0 = c0<c1?c0:c1, nc1 = c0^c1^nc0; const int lX = (1 + nx1 - nx0) + (nx1>=width()?width() - 1 - nx1:0) + (nx0<0?nx0:0), lY = (1 + ny1 - ny0) + (ny1>=height()?height() - 1 - ny1:0) + (ny0<0?ny0:0), lZ = (1 + nz1 - nz0) + (nz1>=depth()?depth() - 1 - nz1:0) + (nz0<0?nz0:0), lC = (1 + nc1 - nc0) + (nc1>=spectrum()?spectrum() - 1 - nc1:0) + (nc0<0?nc0:0); const ulongT offX = (ulongT)_width - lX, offY = (ulongT)_width*(_height - lY), offZ = (ulongT)_width*_height*(_depth - lZ); const float nopacity = cimg::abs(opacity), copacity = 1 - std::max(opacity,0.f); T *ptrd = data(nx0<0?0:nx0,ny0<0?0:ny0,nz0<0?0:nz0,nc0<0?0:nc0); if (lX>0 && lY>0 && lZ>0 && lC>0) for (int v = 0; v<lC; ++v) { for (int z = 0; z<lZ; ++z) { for (int y = 0; y<lY; ++y) { if (opacity>=1) { if (sizeof(T)!=1) { for (int x = 0; x<lX; ++x) *(ptrd++) = val; ptrd+=offX; } else { std::memset(ptrd,(int)val,lX); ptrd+=_width; } } else { for (int x = 0; x<lX; ++x) { *ptrd = (T)(nopacity*val + *ptrd*copacity); ++ptrd; } ptrd+=offX; } } ptrd+=offY; } ptrd+=offZ; } return *this; } //! Draw a filled 3D rectangle. /** \param x0 X-coordinate of the upper-left rectangle corner. \param y0 Y-coordinate of the upper-left rectangle corner. \param z0 Z-coordinate of the upper-left rectangle corner. \param x1 X-coordinate of the lower-right rectangle corner. \param y1 Y-coordinate of the lower-right rectangle corner. \param z1 Z-coordinate of the lower-right rectangle corner. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. **/ template<typename tc> CImg<T>& draw_rectangle(const int x0, const int y0, const int z0, const int x1, const int y1, const int z1, const tc *const color, const float opacity=1) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_rectangle(): Specified color is (null).", cimg_instance); cimg_forC(*this,c) draw_rectangle(x0,y0,z0,c,x1,y1,z1,c,(T)color[c],opacity); return *this; } //! Draw a filled 2D rectangle. /** \param x0 X-coordinate of the upper-left rectangle corner. \param y0 Y-coordinate of the upper-left rectangle corner. \param x1 X-coordinate of the lower-right rectangle corner. \param y1 Y-coordinate of the lower-right rectangle corner. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. **/ template<typename tc> CImg<T>& draw_rectangle(const int x0, const int y0, const int x1, const int y1, const tc *const color, const float opacity=1) { return draw_rectangle(x0,y0,0,x1,y1,_depth - 1,color,opacity); } //! Draw a outlined 2D rectangle \overloading. template<typename tc> CImg<T>& draw_rectangle(const int x0, const int y0, const int x1, const int y1, const tc *const color, const float opacity, const unsigned int pattern) { if (is_empty()) return *this; if (y0==y1) return draw_line(x0,y0,x1,y0,color,opacity,pattern,true); if (x0==x1) return draw_line(x0,y0,x0,y1,color,opacity,pattern,true); const int nx0 = x0<x1?x0:x1, nx1 = x0^x1^nx0, ny0 = y0<y1?y0:y1, ny1 = y0^y1^ny0; if (ny1==ny0 + 1) return draw_line(nx0,ny0,nx1,ny0,color,opacity,pattern,true). draw_line(nx1,ny1,nx0,ny1,color,opacity,pattern,false); return draw_line(nx0,ny0,nx1,ny0,color,opacity,pattern,true). draw_line(nx1,ny0 + 1,nx1,ny1 - 1,color,opacity,pattern,false). draw_line(nx1,ny1,nx0,ny1,color,opacity,pattern,false). draw_line(nx0,ny1 - 1,nx0,ny0 + 1,color,opacity,pattern,false); } //! Draw a filled 2D polygon. /** \param points Set of polygon vertices. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. **/ template<typename tp, typename tc> CImg<T>& draw_polygon(const CImg<tp>& points, const tc *const color, const float opacity=1) { if (is_empty() || !points) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_polygon(): Specified color is (null).", cimg_instance); if (points.height()!=2) throw CImgArgumentException(_cimg_instance "draw_polygon(): Invalid specified point set (%u,%u,%u,%u).", cimg_instance, points._width,points._height,points._depth,points._spectrum); if (points._width==1) return draw_point(cimg::uiround(points(0,0)),cimg::uiround(points(0,1)),color,opacity); if (points._width==2) return draw_line(cimg::uiround(points(0,0)),cimg::uiround(points(0,1)), cimg::uiround(points(1,0)),cimg::uiround(points(1,1)),color,opacity); if (points._width==3) return draw_triangle(cimg::uiround(points(0,0)),cimg::uiround(points(0,1)), cimg::uiround(points(1,0)),cimg::uiround(points(1,1)), cimg::uiround(points(2,0)),cimg::uiround(points(2,1)),color,opacity); cimg_init_scanline(opacity); int xmin = 0, ymin = 0, xmax = points.get_shared_row(0).max_min(xmin), ymax = points.get_shared_row(1).max_min(ymin); if (xmax<0 || xmin>=width() || ymax<0 || ymin>=height()) return *this; if (ymin==ymax) return draw_line(xmin,ymin,xmax,ymax,color,opacity); ymin = std::max(0,ymin); ymax = std::min(height() - 1,ymax); CImg<intT> Xs(points._width,ymax - ymin + 1); CImg<uintT> count(Xs._height,1,1,1,0); unsigned int n = 0, nn = 1; bool go_on = true; while (go_on) { unsigned int an = (nn + 1)%points._width; const int x0 = cimg::uiround(points(n,0)), y0 = cimg::uiround(points(n,1)); if (points(nn,1)==y0) while (points(an,1)==y0) { nn = an; (an+=1)%=points._width; } const int x1 = cimg::uiround(points(nn,0)), y1 = cimg::uiround(points(nn,1)); unsigned int tn = an; while (points(tn,1)==y1) (tn+=1)%=points._width; if (y0!=y1) { const int y2 = cimg::uiround(points(tn,1)), x01 = x1 - x0, y01 = y1 - y0, y12 = y2 - y1, step = cimg::sign(y01), tmax = std::max(1,cimg::abs(y01)), htmax = tmax*cimg::sign(x01)/2, tend = tmax - (step==cimg::sign(y12)); unsigned int y = (unsigned int)y0 - ymin; for (int t = 0; t<=tend; ++t, y+=step) if (y<Xs._height) Xs(count[y]++,y) = x0 + (t*x01 + htmax)/tmax; } go_on = nn>n; n = nn; nn = an; } cimg_pragma_openmp(parallel for cimg_openmp_if(Xs._height>=(cimg_openmp_sizefactor)*32)) cimg_forY(Xs,y) { const CImg<intT> Xsy = Xs.get_shared_points(0,count[y] - 1,y).sort(); int px = width(); for (unsigned int k = 0; k<Xsy._width; k+=2) { int x0 = Xsy[k]; const int x1 = Xsy[k + 1]; x0+=x0==px; cimg_draw_scanline(x0,x1,y + ymin,color,opacity,1); px = x1; } } return *this; } //! Draw a outlined 2D or 3D polygon \overloading. template<typename t, typename tc> CImg<T>& draw_polygon(const CImg<t>& points, const tc *const color, const float opacity, const unsigned int pattern) { if (is_empty() || !points) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_polygon(): Specified color is (null).", cimg_instance); if (points._width==1) return draw_point((int)points(0,0),(int)points(0,1),color,opacity); if (points._width==2) return draw_line((int)points(0,0),(int)points(0,1), (int)points(1,0),(int)points(1,1),color,opacity,pattern); bool ninit_hatch = true; switch (points._height) { case 0 : case 1 : throw CImgArgumentException(_cimg_instance "draw_polygon(): Invalid specified point set (%u,%u,%u,%u).", cimg_instance, points._width,points._height,points._depth,points._spectrum); default : { CImg<intT> npoints(points._width,2); int x = npoints(0,0) = (int)points(0,0), y = npoints(0,1) = (int)points(0,1); unsigned int nb_points = 1; for (unsigned int p = 1; p<points._width; ++p) { const int nx = (int)points(p,0), ny = (int)points(p,1); if (nx!=x || ny!=y) { npoints(nb_points,0) = nx; npoints(nb_points++,1) = ny; x = nx; y = ny; } } const int x0 = (int)npoints(0,0), y0 = (int)npoints(0,1); int ox = x0, oy = y0; for (unsigned int i = 1; i<nb_points; ++i) { const int _x = (int)npoints(i,0), _y = (int)npoints(i,1); draw_line(ox,oy,_x,_y,color,opacity,pattern,ninit_hatch); ninit_hatch = false; ox = _x; oy = _y; } draw_line(ox,oy,x0,y0,color,opacity,pattern,false); } } return *this; } //! Draw a filled 2D ellipse. /** \param x0 X-coordinate of the ellipse center. \param y0 Y-coordinate of the ellipse center. \param r1 First radius of the ellipse. \param r2 Second radius of the ellipse. \param angle Angle of the first radius. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. **/ template<typename tc> CImg<T>& draw_ellipse(const int x0, const int y0, const float r1, const float r2, const float angle, const tc *const color, const float opacity=1) { return _draw_ellipse(x0,y0,r1,r2,angle,color,opacity,0U,true); } //! Draw a filled 2D ellipse \overloading. /** \param x0 X-coordinate of the ellipse center. \param y0 Y-coordinate of the ellipse center. \param tensor Diffusion tensor describing the ellipse. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. **/ template<typename t, typename tc> CImg<T>& draw_ellipse(const int x0, const int y0, const CImg<t> &tensor, const tc *const color, const float opacity=1) { CImgList<t> eig = tensor.get_symmetric_eigen(); const CImg<t> &val = eig[0], &vec = eig[1]; return draw_ellipse(x0,y0,std::sqrt(val(0)),std::sqrt(val(1)), std::atan2(vec(0,1),vec(0,0))*180/cimg::PI, color,opacity); } //! Draw an outlined 2D ellipse. /** \param x0 X-coordinate of the ellipse center. \param y0 Y-coordinate of the ellipse center. \param r1 First radius of the ellipse. \param r2 Second radius of the ellipse. \param angle Angle of the first radius. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \param pattern An integer whose bits describe the outline pattern. **/ template<typename tc> CImg<T>& draw_ellipse(const int x0, const int y0, const float r1, const float r2, const float angle, const tc *const color, const float opacity, const unsigned int pattern) { if (pattern) _draw_ellipse(x0,y0,r1,r2,angle,color,opacity,pattern,false); return *this; } //! Draw an outlined 2D ellipse \overloading. /** \param x0 X-coordinate of the ellipse center. \param y0 Y-coordinate of the ellipse center. \param tensor Diffusion tensor describing the ellipse. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \param pattern An integer whose bits describe the outline pattern. **/ template<typename t, typename tc> CImg<T>& draw_ellipse(const int x0, const int y0, const CImg<t> &tensor, const tc *const color, const float opacity, const unsigned int pattern) { CImgList<t> eig = tensor.get_symmetric_eigen(); const CImg<t> &val = eig[0], &vec = eig[1]; return draw_ellipse(x0,y0,std::sqrt(val(0)),std::sqrt(val(1)), std::atan2(vec(0,1),vec(0,0))*180/cimg::PI, color,opacity,pattern); } template<typename tc> CImg<T>& _draw_ellipse(const int x0, const int y0, const float radius1, const float radius2, const float angle, const tc *const color, const float opacity, const unsigned int pattern, const bool is_filled) { if (is_empty() || (!is_filled && !pattern)) return *this; const float radiusM = std::max(radius1,radius2); if (radius1<0 || radius2<0 || x0 - radiusM>=width() || y0 + radiusM<0 || y0 - radiusM>=height()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_ellipse(): Specified color is (null).", cimg_instance); const int iradius1 = (int)cimg::round(radius1), iradius2 = (int)cimg::round(radius2); if (!iradius1 && !iradius2) return draw_point(x0,y0,color,opacity); if (iradius1==iradius2) { if (is_filled) return draw_circle(x0,y0,iradius1,color,opacity); else return draw_circle(x0,y0,iradius1,color,opacity,pattern); } const float ang = (float)(angle*cimg::PI/180); if (!is_filled) { // Outlined const float ca = std::cos(ang), sa = std::sin(ang); CImg<int> points((unsigned int)cimg::round(6*radiusM),2); cimg_forX(points,k) { const float _ang = (float)(2*cimg::PI*k/points._width), X = (float)(radius1*std::cos(_ang)), Y = (float)(radius2*std::sin(_ang)); points(k,0) = (int)cimg::round(x0 + (X*ca - Y*sa)); points(k,1) = (int)cimg::round(y0 + (X*sa + Y*ca)); } draw_polygon(points,color,opacity,pattern); } else { // Filled cimg_init_scanline(opacity); const float ca = std::cos(ang), sa = -std::sin(ang), ca2 = ca*ca, sa2 = sa*sa, casa = ca*sa, i1 = 1/cimg::sqr(radius1), i2 = 1/cimg::sqr(radius2), t1 = i1*ca2 + i2*sa2, t2 = (i2 - i1)*casa, t3 = i2*ca2 + i1*sa2, t12 = t1*2; const int _ymin = (int)std::floor(y0 - radiusM), _ymax = (int)std::ceil(y0 + radiusM), ymin = _ymin<0?0:_ymin, ymax = _ymax>=height()?height() - 1:_ymax; for (int y = ymin; y<=ymax; ++y) { const float Y = y - y0 + 0.5f, B = 2*t2*Y, C = t3*Y*Y - 1, D = B*B - 4*t1*C; if (D>=0) { const float sD = std::sqrt(D); const int xmin = (int)(x0 + cimg::round((-B - sD)/t12)), xmax = (int)(x0 + cimg::round((-B + sD)/t12)); cimg_draw_scanline(xmin,xmax,y,color,opacity,1); } } } return *this; } //! Draw a filled 2D circle. /** \param x0 X-coordinate of the circle center. \param y0 Y-coordinate of the circle center. \param radius Circle radius. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \note - Circle version of the Bresenham's algorithm is used. **/ template<typename tc> CImg<T>& draw_circle(const int x0, const int y0, int radius, const tc *const color, const float opacity=1) { if (is_empty()) return *this; if (radius<0 || x0 - radius>=width() || y0 + radius<0 || y0 - radius>=height()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_circle(): Specified color is (null).", cimg_instance); if (!radius) return draw_point(x0,y0,color,opacity); cimg_init_scanline(opacity); if (y0>=0 && y0<height()) cimg_draw_scanline(x0 - radius,x0 + radius,y0,color,opacity,1); for (int f = 1 - radius, ddFx = 0, ddFy = -(radius<<1), x = 0, y = radius; x<y; ) { if (f>=0) { const int x1 = x0 - x, x2 = x0 + x, y1 = y0 - y, y2 = y0 + y; if (y1>=0 && y1<height()) cimg_draw_scanline(x1,x2,y1,color,opacity,1); if (y2>=0 && y2<height()) cimg_draw_scanline(x1,x2,y2,color,opacity,1); f+=(ddFy+=2); --y; } const bool no_diag = y!=(x++); ++(f+=(ddFx+=2)); const int x1 = x0 - y, x2 = x0 + y, y1 = y0 - x, y2 = y0 + x; if (no_diag) { if (y1>=0 && y1<height()) cimg_draw_scanline(x1,x2,y1,color,opacity,1); if (y2>=0 && y2<height()) cimg_draw_scanline(x1,x2,y2,color,opacity,1); } } return *this; } //! Draw an outlined 2D circle. /** \param x0 X-coordinate of the circle center. \param y0 Y-coordinate of the circle center. \param radius Circle radius. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \param pattern An integer whose bits describe the outline pattern. **/ template<typename tc> CImg<T>& draw_circle(const int x0, const int y0, int radius, const tc *const color, const float opacity, const unsigned int pattern) { if (pattern!=~0U) return draw_ellipse(x0,y0,radius,radius,0,color,opacity,pattern); if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_circle(): Specified color is (null).", cimg_instance); if (radius<0 || x0 - radius>=width() || y0 + radius<0 || y0 - radius>=height()) return *this; if (!radius) return draw_point(x0,y0,color,opacity); draw_point(x0 - radius,y0,color,opacity).draw_point(x0 + radius,y0,color,opacity). draw_point(x0,y0 - radius,color,opacity).draw_point(x0,y0 + radius,color,opacity); if (radius==1) return *this; for (int f = 1 - radius, ddFx = 0, ddFy = -(radius<<1), x = 0, y = radius; x<y; ) { if (f>=0) { f+=(ddFy+=2); --y; } ++x; ++(f+=(ddFx+=2)); if (x!=y + 1) { const int x1 = x0 - y, x2 = x0 + y, y1 = y0 - x, y2 = y0 + x, x3 = x0 - x, x4 = x0 + x, y3 = y0 - y, y4 = y0 + y; draw_point(x1,y1,color,opacity).draw_point(x1,y2,color,opacity). draw_point(x2,y1,color,opacity).draw_point(x2,y2,color,opacity); if (x!=y) draw_point(x3,y3,color,opacity).draw_point(x4,y4,color,opacity). draw_point(x4,y3,color,opacity).draw_point(x3,y4,color,opacity); } } return *this; } //! Draw an image. /** \param sprite Sprite image. \param x0 X-coordinate of the sprite position. \param y0 Y-coordinate of the sprite position. \param z0 Z-coordinate of the sprite position. \param c0 C-coordinate of the sprite position. \param opacity Drawing opacity. **/ template<typename t> CImg<T>& draw_image(const int x0, const int y0, const int z0, const int c0, const CImg<t>& sprite, const float opacity=1) { if (is_empty() || !sprite) return *this; if (is_overlapped(sprite)) return draw_image(x0,y0,z0,c0,+sprite,opacity); if (x0==0 && y0==0 && z0==0 && c0==0 && is_sameXYZC(sprite) && opacity>=1 && !is_shared()) return assign(sprite,false); const bool bx = (x0<0), by = (y0<0), bz = (z0<0), bc = (c0<0); const int lX = sprite.width() - (x0 + sprite.width()>width()?x0 + sprite.width() - width():0) + (bx?x0:0), lY = sprite.height() - (y0 + sprite.height()>height()?y0 + sprite.height() - height():0) + (by?y0:0), lZ = sprite.depth() - (z0 + sprite.depth()>depth()?z0 + sprite.depth() - depth():0) + (bz?z0:0), lC = sprite.spectrum() - (c0 + sprite.spectrum()>spectrum()?c0 + sprite.spectrum() - spectrum():0) + (bc?c0:0); const t *ptrs = sprite._data + (bx?-x0:0) + (by?-y0*(ulongT)sprite.width():0) + (bz?-z0*(ulongT)sprite.width()*sprite.height():0) + (bc?-c0*(ulongT)sprite.width()*sprite.height()*sprite.depth():0); const ulongT offX = (ulongT)_width - lX, soffX = (ulongT)sprite._width - lX, offY = (ulongT)_width*(_height - lY), soffY = (ulongT)sprite._width*(sprite._height - lY), offZ = (ulongT)_width*_height*(_depth - lZ), soffZ = (ulongT)sprite._width*sprite._height*(sprite._depth - lZ); const float nopacity = cimg::abs(opacity), copacity = 1 - std::max(opacity,0.f); if (lX>0 && lY>0 && lZ>0 && lC>0) { T *ptrd = data(x0<0?0:x0,y0<0?0:y0,z0<0?0:z0,c0<0?0:c0); for (int v = 0; v<lC; ++v) { for (int z = 0; z<lZ; ++z) { for (int y = 0; y<lY; ++y) { if (opacity>=1) for (int x = 0; x<lX; ++x) *(ptrd++) = (T)*(ptrs++); else for (int x = 0; x<lX; ++x) { *ptrd = (T)(nopacity*(*(ptrs++)) + *ptrd*copacity); ++ptrd; } ptrd+=offX; ptrs+=soffX; } ptrd+=offY; ptrs+=soffY; } ptrd+=offZ; ptrs+=soffZ; } } return *this; } //! Draw an image \specialization. CImg<T>& draw_image(const int x0, const int y0, const int z0, const int c0, const CImg<T>& sprite, const float opacity=1) { if (is_empty() || !sprite) return *this; if (is_overlapped(sprite)) return draw_image(x0,y0,z0,c0,+sprite,opacity); if (x0==0 && y0==0 && z0==0 && c0==0 && is_sameXYZC(sprite) && opacity>=1 && !is_shared()) return assign(sprite,false); const bool bx = (x0<0), by = (y0<0), bz = (z0<0), bc = (c0<0); const int lX = sprite.width() - (x0 + sprite.width()>width()?x0 + sprite.width() - width():0) + (bx?x0:0), lY = sprite.height() - (y0 + sprite.height()>height()?y0 + sprite.height() - height():0) + (by?y0:0), lZ = sprite.depth() - (z0 + sprite.depth()>depth()?z0 + sprite.depth() - depth():0) + (bz?z0:0), lC = sprite.spectrum() - (c0 + sprite.spectrum()>spectrum()?c0 + sprite.spectrum() - spectrum():0) + (bc?c0:0); const T *ptrs = sprite._data + (bx?-x0:0) + (by?-y0*(ulongT)sprite.width():0) + (bz?-z0*(ulongT)sprite.width()*sprite.height():0) + (bc?-c0*(ulongT)sprite.width()*sprite.height()*sprite.depth():0); const ulongT offX = (ulongT)_width - lX, soffX = (ulongT)sprite._width - lX, offY = (ulongT)_width*(_height - lY), soffY = (ulongT)sprite._width*(sprite._height - lY), offZ = (ulongT)_width*_height*(_depth - lZ), soffZ = (ulongT)sprite._width*sprite._height*(sprite._depth - lZ), slX = lX*sizeof(T); const float nopacity = cimg::abs(opacity), copacity = 1 - std::max(opacity,0.f); if (lX>0 && lY>0 && lZ>0 && lC>0) { T *ptrd = data(x0<0?0:x0,y0<0?0:y0,z0<0?0:z0,c0<0?0:c0); for (int v = 0; v<lC; ++v) { for (int z = 0; z<lZ; ++z) { if (opacity>=1) for (int y = 0; y<lY; ++y) { std::memcpy(ptrd,ptrs,slX); ptrd+=_width; ptrs+=sprite._width; } else for (int y = 0; y<lY; ++y) { for (int x = 0; x<lX; ++x) { *ptrd = (T)(nopacity*(*(ptrs++)) + *ptrd*copacity); ++ptrd; } ptrd+=offX; ptrs+=soffX; } ptrd+=offY; ptrs+=soffY; } ptrd+=offZ; ptrs+=soffZ; } } return *this; } //! Draw an image \overloading. template<typename t> CImg<T>& draw_image(const int x0, const int y0, const int z0, const CImg<t>& sprite, const float opacity=1) { return draw_image(x0,y0,z0,0,sprite,opacity); } //! Draw an image \overloading. template<typename t> CImg<T>& draw_image(const int x0, const int y0, const CImg<t>& sprite, const float opacity=1) { return draw_image(x0,y0,0,sprite,opacity); } //! Draw an image \overloading. template<typename t> CImg<T>& draw_image(const int x0, const CImg<t>& sprite, const float opacity=1) { return draw_image(x0,0,sprite,opacity); } //! Draw an image \overloading. template<typename t> CImg<T>& draw_image(const CImg<t>& sprite, const float opacity=1) { return draw_image(0,sprite,opacity); } //! Draw a masked image. /** \param sprite Sprite image. \param mask Mask image. \param x0 X-coordinate of the sprite position in the image instance. \param y0 Y-coordinate of the sprite position in the image instance. \param z0 Z-coordinate of the sprite position in the image instance. \param c0 C-coordinate of the sprite position in the image instance. \param mask_max_value Maximum pixel value of the mask image \c mask. \param opacity Drawing opacity. \note - Pixel values of \c mask set the opacity of the corresponding pixels in \c sprite. - Dimensions along x,y and z of \p sprite and \p mask must be the same. **/ template<typename ti, typename tm> CImg<T>& draw_image(const int x0, const int y0, const int z0, const int c0, const CImg<ti>& sprite, const CImg<tm>& mask, const float opacity=1, const float mask_max_value=1) { if (is_empty() || !sprite || !mask) return *this; if (is_overlapped(sprite)) return draw_image(x0,y0,z0,c0,+sprite,mask,opacity,mask_max_value); if (is_overlapped(mask)) return draw_image(x0,y0,z0,c0,sprite,+mask,opacity,mask_max_value); if (mask._width!=sprite._width || mask._height!=sprite._height || mask._depth!=sprite._depth) throw CImgArgumentException(_cimg_instance "draw_image(): Sprite (%u,%u,%u,%u,%p) and mask (%u,%u,%u,%u,%p) have " "incompatible dimensions.", cimg_instance, sprite._width,sprite._height,sprite._depth,sprite._spectrum,sprite._data, mask._width,mask._height,mask._depth,mask._spectrum,mask._data); const bool bx = (x0<0), by = (y0<0), bz = (z0<0), bc = (c0<0); const int lX = sprite.width() - (x0 + sprite.width()>width()?x0 + sprite.width() - width():0) + (bx?x0:0), lY = sprite.height() - (y0 + sprite.height()>height()?y0 + sprite.height() - height():0) + (by?y0:0), lZ = sprite.depth() - (z0 + sprite.depth()>depth()?z0 + sprite.depth() - depth():0) + (bz?z0:0), lC = sprite.spectrum() - (c0 + sprite.spectrum()>spectrum()?c0 + sprite.spectrum() - spectrum():0) + (bc?c0:0); const ulongT coff = (bx?-x0:0) + (by?-y0*(ulongT)mask.width():0) + (bz?-z0*(ulongT)mask.width()*mask.height():0) + (bc?-c0*(ulongT)mask.width()*mask.height()*mask.depth():0), ssize = (ulongT)mask.width()*mask.height()*mask.depth()*mask.spectrum(); const ti *ptrs = sprite._data + coff; const tm *ptrm = mask._data + coff; const ulongT offX = (ulongT)_width - lX, soffX = (ulongT)sprite._width - lX, offY = (ulongT)_width*(_height - lY), soffY = (ulongT)sprite._width*(sprite._height - lY), offZ = (ulongT)_width*_height*(_depth - lZ), soffZ = (ulongT)sprite._width*sprite._height*(sprite._depth - lZ); if (lX>0 && lY>0 && lZ>0 && lC>0) { T *ptrd = data(x0<0?0:x0,y0<0?0:y0,z0<0?0:z0,c0<0?0:c0); for (int c = 0; c<lC; ++c) { ptrm = mask._data + (ptrm - mask._data)%ssize; for (int z = 0; z<lZ; ++z) { for (int y = 0; y<lY; ++y) { for (int x = 0; x<lX; ++x) { const float mopacity = (float)(*(ptrm++)*opacity), nopacity = cimg::abs(mopacity), copacity = mask_max_value - std::max(mopacity,0.f); *ptrd = (T)((nopacity*(*(ptrs++)) + *ptrd*copacity)/mask_max_value); ++ptrd; } ptrd+=offX; ptrs+=soffX; ptrm+=soffX; } ptrd+=offY; ptrs+=soffY; ptrm+=soffY; } ptrd+=offZ; ptrs+=soffZ; ptrm+=soffZ; } } return *this; } //! Draw a masked image \overloading. template<typename ti, typename tm> CImg<T>& draw_image(const int x0, const int y0, const int z0, const CImg<ti>& sprite, const CImg<tm>& mask, const float opacity=1, const float mask_max_value=1) { return draw_image(x0,y0,z0,0,sprite,mask,opacity,mask_max_value); } //! Draw a image \overloading. template<typename ti, typename tm> CImg<T>& draw_image(const int x0, const int y0, const CImg<ti>& sprite, const CImg<tm>& mask, const float opacity=1, const float mask_max_value=1) { return draw_image(x0,y0,0,sprite,mask,opacity,mask_max_value); } //! Draw a image \overloading. template<typename ti, typename tm> CImg<T>& draw_image(const int x0, const CImg<ti>& sprite, const CImg<tm>& mask, const float opacity=1, const float mask_max_value=1) { return draw_image(x0,0,sprite,mask,opacity,mask_max_value); } //! Draw an image. template<typename ti, typename tm> CImg<T>& draw_image(const CImg<ti>& sprite, const CImg<tm>& mask, const float opacity=1, const float mask_max_value=1) { return draw_image(0,sprite,mask,opacity,mask_max_value); } //! Draw a text string. /** \param x0 X-coordinate of the text in the image instance. \param y0 Y-coordinate of the text in the image instance. \param text Format of the text ('printf'-style format string). \param foreground_color Pointer to \c spectrum() consecutive values, defining the foreground drawing color. \param background_color Pointer to \c spectrum() consecutive values, defining the background drawing color. \param opacity Drawing opacity. \param font Font used for drawing text. **/ template<typename tc1, typename tc2, typename t> CImg<T>& draw_text(const int x0, const int y0, const char *const text, const tc1 *const foreground_color, const tc2 *const background_color, const float opacity, const CImgList<t>& font, ...) { if (!font) return *this; CImg<charT> tmp(2048); std::va_list ap; va_start(ap,font); cimg_vsnprintf(tmp,tmp._width,text,ap); va_end(ap); return _draw_text(x0,y0,tmp,foreground_color,background_color,opacity,font,false); } //! Draw a text string \overloading. /** \note A transparent background is used for the text. **/ template<typename tc, typename t> CImg<T>& draw_text(const int x0, const int y0, const char *const text, const tc *const foreground_color, const int, const float opacity, const CImgList<t>& font, ...) { if (!font) return *this; CImg<charT> tmp(2048); std::va_list ap; va_start(ap,font); cimg_vsnprintf(tmp,tmp._width,text,ap); va_end(ap); return _draw_text(x0,y0,tmp,foreground_color,(tc*)0,opacity,font,false); } //! Draw a text string \overloading. /** \note A transparent foreground is used for the text. **/ template<typename tc, typename t> CImg<T>& draw_text(const int x0, const int y0, const char *const text, const int, const tc *const background_color, const float opacity, const CImgList<t>& font, ...) { if (!font) return *this; CImg<charT> tmp(2048); std::va_list ap; va_start(ap,font); cimg_vsnprintf(tmp,tmp._width,text,ap); va_end(ap); return _draw_text(x0,y0,tmp,(tc*)0,background_color,opacity,font,false); } //! Draw a text string \overloading. /** \param x0 X-coordinate of the text in the image instance. \param y0 Y-coordinate of the text in the image instance. \param text Format of the text ('printf'-style format string). \param foreground_color Array of spectrum() values of type \c T, defining the foreground color (0 means 'transparent'). \param background_color Array of spectrum() values of type \c T, defining the background color (0 means 'transparent'). \param opacity Drawing opacity. \param font_height Height of the text font (exact match for 13,23,53,103, interpolated otherwise). **/ template<typename tc1, typename tc2> CImg<T>& draw_text(const int x0, const int y0, const char *const text, const tc1 *const foreground_color, const tc2 *const background_color, const float opacity=1, const unsigned int font_height=13, ...) { if (!font_height) return *this; CImg<charT> tmp(2048); std::va_list ap; va_start(ap,font_height); cimg_vsnprintf(tmp,tmp._width,text,ap); va_end(ap); const CImgList<ucharT>& font = CImgList<ucharT>::font(font_height,true); _draw_text(x0,y0,tmp,foreground_color,background_color,opacity,font,true); return *this; } //! Draw a text string \overloading. template<typename tc> CImg<T>& draw_text(const int x0, const int y0, const char *const text, const tc *const foreground_color, const int background_color=0, const float opacity=1, const unsigned int font_height=13, ...) { if (!font_height) return *this; cimg::unused(background_color); CImg<charT> tmp(2048); std::va_list ap; va_start(ap,font_height); cimg_vsnprintf(tmp,tmp._width,text,ap); va_end(ap); return draw_text(x0,y0,"%s",foreground_color,(const tc*)0,opacity,font_height,tmp._data); } //! Draw a text string \overloading. template<typename tc> CImg<T>& draw_text(const int x0, const int y0, const char *const text, const int, const tc *const background_color, const float opacity=1, const unsigned int font_height=13, ...) { if (!font_height) return *this; CImg<charT> tmp(2048); std::va_list ap; va_start(ap,font_height); cimg_vsnprintf(tmp,tmp._width,text,ap); va_end(ap); return draw_text(x0,y0,"%s",(tc*)0,background_color,opacity,font_height,tmp._data); } template<typename tc1, typename tc2, typename t> CImg<T>& _draw_text(const int x0, const int y0, const char *const text, const tc1 *const foreground_color, const tc2 *const background_color, const float opacity, const CImgList<t>& font, const bool is_native_font) { if (!text) return *this; if (!font) throw CImgArgumentException(_cimg_instance "draw_text(): Empty specified font.", cimg_instance); const unsigned int text_length = (unsigned int)std::strlen(text); if (is_empty()) { // If needed, pre-compute necessary size of the image int x = 0, y = 0, w = 0; unsigned char c = 0; for (unsigned int i = 0; i<text_length; ++i) { c = (unsigned char)text[i]; switch (c) { case '\n' : y+=font[0]._height; if (x>w) w = x; x = 0; break; case '\t' : x+=4*font[(int)' ']._width; break; default : if (c<font._width) x+=font[c]._width; } } if (x!=0 || c=='\n') { if (x>w) w=x; y+=font[0]._height; } assign(x0 + w,y0 + y,1,is_native_font?1:font[0]._spectrum,(T)0); } int x = x0, y = y0; for (unsigned int i = 0; i<text_length; ++i) { const unsigned char ch = (unsigned char)text[i]; switch (ch) { case '\n' : y+=font[0]._height; x = x0; break; case '\t' : x+=4*font[(int)' ']._width; break; default : if (ch<font._width) { CImg<T> letter = font[ch]; if (letter) { if (is_native_font && _spectrum>letter._spectrum) letter.resize(-100,-100,1,_spectrum,0,2); const unsigned int cmin = std::min(_spectrum,letter._spectrum); if (foreground_color) for (unsigned int c = 0; c<cmin; ++c) if (foreground_color[c]!=1) letter.get_shared_channel(c)*=foreground_color[c]; if (ch + 256<font.width()) { // Letter has mask if (background_color) for (unsigned int c = 0; c<cmin; ++c) draw_rectangle(x,y,0,c,x + letter._width - 1,y + letter._height - 1,0,c, background_color[c],opacity); draw_image(x,y,letter,font[ch + 256],opacity,255.f); } else draw_image(x,y,letter,opacity); // Letter has no mask x+=letter._width; } } } } return *this; } // [internal] Version used to display text in interactive viewers. CImg<T>& __draw_text(const char *const text, const int is_down, ...) { CImg<charT> tmp(2048); std::va_list ap; va_start(ap,is_down); cimg_vsnprintf(tmp,tmp._width,text,ap); va_end(ap); CImg<ucharT> a_label, a_labelmask; const unsigned char a_labelcolor = 255; const unsigned int fsize = 14; a_label.draw_text(0,0,"%s",&a_labelcolor,0,1,fsize,tmp._data).normalize(0,255); if (a_label) { a_label+=(255 - a_label.get_dilate(3)).normalize(0,80); a_label.resize(-100,-100,1,3,1); return draw_image(0,is_down?height() - a_label.height():0,a_label,0.85f); } return *this; } //! Draw a 2D vector field. /** \param flow Image of 2D vectors used as input data. \param color Image of spectrum()-D vectors corresponding to the color of each arrow. \param opacity Drawing opacity. \param sampling Length (in pixels) between each arrow. \param factor Length factor of each arrow (if <0, computed as a percentage of the maximum length). \param is_arrow Tells if arrows must be drawn, instead of oriented segments. \param pattern Used pattern to draw lines. \note Clipping is supported. **/ template<typename t1, typename t2> CImg<T>& draw_quiver(const CImg<t1>& flow, const t2 *const color, const float opacity=1, const unsigned int sampling=25, const float factor=-20, const bool is_arrow=true, const unsigned int pattern=~0U) { return draw_quiver(flow,CImg<t2>(color,_spectrum,1,1,1,true),opacity,sampling,factor,is_arrow,pattern); } //! Draw a 2D vector field, using a field of colors. /** \param flow Image of 2D vectors used as input data. \param color Image of spectrum()-D vectors corresponding to the color of each arrow. \param opacity Opacity of the drawing. \param sampling Length (in pixels) between each arrow. \param factor Length factor of each arrow (if <0, computed as a percentage of the maximum length). \param is_arrow Tells if arrows must be drawn, instead of oriented segments. \param pattern Used pattern to draw lines. \note Clipping is supported. **/ template<typename t1, typename t2> CImg<T>& draw_quiver(const CImg<t1>& flow, const CImg<t2>& color, const float opacity=1, const unsigned int sampling=25, const float factor=-20, const bool is_arrow=true, const unsigned int pattern=~0U) { if (is_empty()) return *this; if (!flow || flow._spectrum!=2) throw CImgArgumentException(_cimg_instance "draw_quiver(): Invalid dimensions of specified flow (%u,%u,%u,%u,%p).", cimg_instance, flow._width,flow._height,flow._depth,flow._spectrum,flow._data); if (sampling<=0) throw CImgArgumentException(_cimg_instance "draw_quiver(): Invalid sampling value %g " "(should be >0)", cimg_instance, sampling); const bool colorfield = (color._width==flow._width && color._height==flow._height && color._depth==1 && color._spectrum==_spectrum); if (is_overlapped(flow)) return draw_quiver(+flow,color,opacity,sampling,factor,is_arrow,pattern); float vmax,fact; if (factor<=0) { float m, M = (float)flow.get_norm(2).max_min(m); vmax = (float)std::max(cimg::abs(m),cimg::abs(M)); if (!vmax) vmax = 1; fact = -factor; } else { fact = factor; vmax = 1; } for (unsigned int y = sampling/2; y<_height; y+=sampling) for (unsigned int x = sampling/2; x<_width; x+=sampling) { const unsigned int X = x*flow._width/_width, Y = y*flow._height/_height; float u = (float)flow(X,Y,0,0)*fact/vmax, v = (float)flow(X,Y,0,1)*fact/vmax; if (is_arrow) { const int xx = (int)(x + u), yy = (int)(y + v); if (colorfield) draw_arrow(x,y,xx,yy,color.get_vector_at(X,Y)._data,opacity,45,sampling/5.f,pattern); else draw_arrow(x,y,xx,yy,color._data,opacity,45,sampling/5.f,pattern); } else { if (colorfield) draw_line((int)(x - 0.5*u),(int)(y - 0.5*v),(int)(x + 0.5*u),(int)(y + 0.5*v), color.get_vector_at(X,Y)._data,opacity,pattern); else draw_line((int)(x - 0.5*u),(int)(y - 0.5*v),(int)(x + 0.5*u),(int)(y + 0.5*v), color._data,opacity,pattern); } } return *this; } //! Draw a labeled horizontal axis. /** \param values_x Values along the horizontal axis. \param y Y-coordinate of the horizontal axis in the image instance. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \param pattern Drawing pattern. \param font_height Height of the labels (exact match for 13,23,53,103, interpolated otherwise). \param allow_zero Enable/disable the drawing of label '0' if found. **/ template<typename t, typename tc> CImg<T>& draw_axis(const CImg<t>& values_x, const int y, const tc *const color, const float opacity=1, const unsigned int pattern=~0U, const unsigned int font_height=13, const bool allow_zero=true, const float round_x=0) { if (is_empty()) return *this; const int yt = (y + 3 + font_height)<_height?y + 3:y - 2 - (int)font_height; const int siz = (int)values_x.size() - 1; CImg<charT> txt(32); CImg<T> a_label; if (siz<=0) { // Degenerated case draw_line(0,y,_width - 1,y,color,opacity,pattern); if (!siz) { cimg_snprintf(txt,txt._width,"%g",round_x?cimg::round((double)*values_x,round_x):(double)*values_x); a_label.assign().draw_text(0,0,txt,color,(tc*)0,opacity,font_height); const int _xt = (width() - a_label.width())/2, xt = _xt<3?3:_xt + a_label.width()>=width() - 2?width() - 3 - a_label.width():_xt; draw_point(width()/2,y - 1,color,opacity).draw_point(width()/2,y + 1,color,opacity); if (allow_zero || *txt!='0' || txt[1]!=0) draw_text(xt,yt,txt,color,(tc*)0,opacity,font_height); } } else { // Regular case if (values_x[0]<values_x[siz]) draw_arrow(0,y,_width - 1,y,color,opacity,30,5,pattern); else draw_arrow(_width - 1,y,0,y,color,opacity,30,5,pattern); cimg_foroff(values_x,x) { cimg_snprintf(txt,txt._width,"%g",round_x?cimg::round((double)values_x(x),round_x):(double)values_x(x)); a_label.assign().draw_text(0,0,txt,color,(tc*)0,opacity,font_height); const int xi = (int)(x*(_width - 1)/siz), _xt = xi - a_label.width()/2, xt = _xt<3?3:_xt + a_label.width()>=width() - 2?width() - 3 - a_label.width():_xt; draw_point(xi,y - 1,color,opacity).draw_point(xi,y + 1,color,opacity); if (allow_zero || *txt!='0' || txt[1]!=0) draw_text(xt,yt,txt,color,(tc*)0,opacity,font_height); } } return *this; } //! Draw a labeled vertical axis. /** \param x X-coordinate of the vertical axis in the image instance. \param values_y Values along the Y-axis. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \param pattern Drawing pattern. \param font_height Height of the labels (exact match for 13,23,53,103, interpolated otherwise). \param allow_zero Enable/disable the drawing of label '0' if found. **/ template<typename t, typename tc> CImg<T>& draw_axis(const int x, const CImg<t>& values_y, const tc *const color, const float opacity=1, const unsigned int pattern=~0U, const unsigned int font_height=13, const bool allow_zero=true, const float round_y=0) { if (is_empty()) return *this; int siz = (int)values_y.size() - 1; CImg<charT> txt(32); CImg<T> a_label; if (siz<=0) { // Degenerated case draw_line(x,0,x,_height - 1,color,opacity,pattern); if (!siz) { cimg_snprintf(txt,txt._width,"%g",round_y?cimg::round((double)*values_y,round_y):(double)*values_y); a_label.assign().draw_text(0,0,txt,color,(tc*)0,opacity,font_height); const int _yt = (height() - a_label.height())/2, yt = _yt<0?0:_yt + a_label.height()>=height()?height() - 1 - a_label.height():_yt, _xt = x - 2 - a_label.width(), xt = _xt>=0?_xt:x + 3; draw_point(x - 1,height()/2,color,opacity).draw_point(x + 1,height()/2,color,opacity); if (allow_zero || *txt!='0' || txt[1]!=0) draw_text(xt,yt,txt,color,(tc*)0,opacity,font_height); } } else { // Regular case if (values_y[0]<values_y[siz]) draw_arrow(x,0,x,_height - 1,color,opacity,30,5,pattern); else draw_arrow(x,_height - 1,x,0,color,opacity,30,5,pattern); cimg_foroff(values_y,y) { cimg_snprintf(txt,txt._width,"%g",round_y?cimg::round((double)values_y(y),round_y):(double)values_y(y)); a_label.assign().draw_text(0,0,txt,color,(tc*)0,opacity,font_height); const int yi = (int)(y*(_height - 1)/siz), _yt = yi - a_label.height()/2, yt = _yt<0?0:_yt + a_label.height()>=height()?height() - 1 - a_label.height():_yt, _xt = x - 2 - a_label.width(), xt = _xt>=0?_xt:x + 3; draw_point(x - 1,yi,color,opacity).draw_point(x + 1,yi,color,opacity); if (allow_zero || *txt!='0' || txt[1]!=0) draw_text(xt,yt,txt,color,(tc*)0,opacity,font_height); } } return *this; } //! Draw labeled horizontal and vertical axes. /** \param values_x Values along the X-axis. \param values_y Values along the Y-axis. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \param pattern_x Drawing pattern for the X-axis. \param pattern_y Drawing pattern for the Y-axis. \param font_height Height of the labels (exact match for 13,23,53,103, interpolated otherwise). \param allow_zero Enable/disable the drawing of label '0' if found. **/ template<typename tx, typename ty, typename tc> CImg<T>& draw_axes(const CImg<tx>& values_x, const CImg<ty>& values_y, const tc *const color, const float opacity=1, const unsigned int pattern_x=~0U, const unsigned int pattern_y=~0U, const unsigned int font_height=13, const bool allow_zero=true, const float round_x=0, const float round_y=0) { if (is_empty()) return *this; const CImg<tx> nvalues_x(values_x._data,values_x.size(),1,1,1,true); const int sizx = (int)values_x.size() - 1, wm1 = width() - 1; if (sizx>=0) { float ox = (float)*nvalues_x; for (unsigned int x = sizx?1U:0U; x<_width; ++x) { const float nx = (float)nvalues_x._linear_atX((float)x*sizx/wm1); if (nx*ox<=0) { draw_axis(nx==0?x:x - 1,values_y,color,opacity,pattern_y,font_height,allow_zero,round_y); break; } ox = nx; } } const CImg<ty> nvalues_y(values_y._data,values_y.size(),1,1,1,true); const int sizy = (int)values_y.size() - 1, hm1 = height() - 1; if (sizy>0) { float oy = (float)nvalues_y[0]; for (unsigned int y = sizy?1U:0U; y<_height; ++y) { const float ny = (float)nvalues_y._linear_atX((float)y*sizy/hm1); if (ny*oy<=0) { draw_axis(values_x,ny==0?y:y - 1,color,opacity,pattern_x,font_height,allow_zero,round_x); break; } oy = ny; } } return *this; } //! Draw labeled horizontal and vertical axes \overloading. template<typename tc> CImg<T>& draw_axes(const float x0, const float x1, const float y0, const float y1, const tc *const color, const float opacity=1, const int subdivisionx=-60, const int subdivisiony=-60, const float precisionx=0, const float precisiony=0, const unsigned int pattern_x=~0U, const unsigned int pattern_y=~0U, const unsigned int font_height=13) { if (is_empty()) return *this; const bool allow_zero = (x0*x1>0) || (y0*y1>0); const float dx = cimg::abs(x1 - x0), dy = cimg::abs(y1 - y0), px = dx<=0?1:precisionx==0?(float)std::pow(10.,(int)std::log10(dx) - 2.):precisionx, py = dy<=0?1:precisiony==0?(float)std::pow(10.,(int)std::log10(dy) - 2.):precisiony; if (x0!=x1 && y0!=y1) draw_axes(CImg<floatT>::sequence(subdivisionx>0?subdivisionx:1-width()/subdivisionx,x0,x1), CImg<floatT>::sequence(subdivisiony>0?subdivisiony:1-height()/subdivisiony,y0,y1), color,opacity,pattern_x,pattern_y,font_height,allow_zero,px,py); else if (x0==x1 && y0!=y1) draw_axis((int)x0,CImg<floatT>::sequence(subdivisiony>0?subdivisiony:1-height()/subdivisiony,y0,y1), color,opacity,pattern_y,font_height,py); else if (x0!=x1 && y0==y1) draw_axis(CImg<floatT>::sequence(subdivisionx>0?subdivisionx:1-width()/subdivisionx,x0,x1),(int)y0, color,opacity,pattern_x,font_height,px); return *this; } //! Draw 2D grid. /** \param values_x X-coordinates of the vertical lines. \param values_y Y-coordinates of the horizontal lines. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \param pattern_x Drawing pattern for vertical lines. \param pattern_y Drawing pattern for horizontal lines. **/ template<typename tx, typename ty, typename tc> CImg<T>& draw_grid(const CImg<tx>& values_x, const CImg<ty>& values_y, const tc *const color, const float opacity=1, const unsigned int pattern_x=~0U, const unsigned int pattern_y=~0U) { if (is_empty()) return *this; if (values_x) cimg_foroff(values_x,x) { const int xi = (int)values_x[x]; if (xi>=0 && xi<width()) draw_line(xi,0,xi,_height - 1,color,opacity,pattern_x); } if (values_y) cimg_foroff(values_y,y) { const int yi = (int)values_y[y]; if (yi>=0 && yi<height()) draw_line(0,yi,_width - 1,yi,color,opacity,pattern_y); } return *this; } //! Draw 2D grid \simplification. template<typename tc> CImg<T>& draw_grid(const float delta_x, const float delta_y, const float offsetx, const float offsety, const bool invertx, const bool inverty, const tc *const color, const float opacity=1, const unsigned int pattern_x=~0U, const unsigned int pattern_y=~0U) { if (is_empty()) return *this; CImg<uintT> seqx, seqy; if (delta_x!=0) { const float dx = delta_x>0?delta_x:_width*-delta_x/100; const unsigned int nx = (unsigned int)(_width/dx); seqx = CImg<uintT>::sequence(1 + nx,0,(unsigned int)(dx*nx)); if (offsetx) cimg_foroff(seqx,x) seqx(x) = (unsigned int)cimg::mod(seqx(x) + offsetx,(float)_width); if (invertx) cimg_foroff(seqx,x) seqx(x) = _width - 1 - seqx(x); } if (delta_y!=0) { const float dy = delta_y>0?delta_y:_height*-delta_y/100; const unsigned int ny = (unsigned int)(_height/dy); seqy = CImg<uintT>::sequence(1 + ny,0,(unsigned int)(dy*ny)); if (offsety) cimg_foroff(seqy,y) seqy(y) = (unsigned int)cimg::mod(seqy(y) + offsety,(float)_height); if (inverty) cimg_foroff(seqy,y) seqy(y) = _height - 1 - seqy(y); } return draw_grid(seqx,seqy,color,opacity,pattern_x,pattern_y); } //! Draw 1D graph. /** \param data Image containing the graph values I = f(x). \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \param plot_type Define the type of the plot: - 0 = No plot. - 1 = Plot using segments. - 2 = Plot using cubic splines. - 3 = Plot with bars. \param vertex_type Define the type of points: - 0 = No points. - 1 = Point. - 2 = Straight cross. - 3 = Diagonal cross. - 4 = Filled circle. - 5 = Outlined circle. - 6 = Square. - 7 = Diamond. \param ymin Lower bound of the y-range. \param ymax Upper bound of the y-range. \param pattern Drawing pattern. \note - if \c ymin==ymax==0, the y-range is computed automatically from the input samples. **/ template<typename t, typename tc> CImg<T>& draw_graph(const CImg<t>& data, const tc *const color, const float opacity=1, const unsigned int plot_type=1, const int vertex_type=1, const double ymin=0, const double ymax=0, const unsigned int pattern=~0U) { if (is_empty() || _height<=1) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_graph(): Specified color is (null).", cimg_instance); // Create shaded colors for displaying bar plots. CImg<tc> color1, color2; if (plot_type==3) { color1.assign(_spectrum); color2.assign(_spectrum); cimg_forC(*this,c) { color1[c] = (tc)std::min((float)cimg::type<tc>::max(),(float)color[c]*1.2f); color2[c] = (tc)(color[c]*0.4f); } } // Compute min/max and normalization factors. const ulongT siz = data.size(), _siz1 = siz - (plot_type!=3), siz1 = _siz1?_siz1:1; const unsigned int _width1 = _width - (plot_type!=3), width1 = _width1?_width1:1; double m = ymin, M = ymax; if (ymin==ymax) m = (double)data.max_min(M); if (m==M) { --m; ++M; } const float ca = (float)(M-m)/(_height - 1); bool init_hatch = true; // Draw graph edges switch (plot_type%4) { case 1 : { // Segments int oX = 0, oY = (int)((data[0] - m)/ca); if (siz==1) { const int Y = (int)((*data - m)/ca); draw_line(0,Y,width() - 1,Y,color,opacity,pattern); } else { const float fx = (float)_width/siz1; for (ulongT off = 1; off<siz; ++off) { const int X = (int)(off*fx) - 1, Y = (int)((data[off]-m)/ca); draw_line(oX,oY,X,Y,color,opacity,pattern,init_hatch); oX = X; oY = Y; init_hatch = false; } } } break; case 2 : { // Spline const CImg<t> ndata(data._data,siz,1,1,1,true); int oY = (int)((data[0] - m)/ca); cimg_forX(*this,x) { const int Y = (int)((ndata._cubic_atX((float)x*siz1/width1)-m)/ca); if (x>0) draw_line(x,oY,x + 1,Y,color,opacity,pattern,init_hatch); init_hatch = false; oY = Y; } } break; case 3 : { // Bars const int Y0 = (int)(-m/ca); const float fx = (float)_width/siz1; int oX = 0; cimg_foroff(data,off) { const int X = (int)((off + 1)*fx) - 1, Y = (int)((data[off] - m)/ca); draw_rectangle(oX,Y0,X,Y,color,opacity). draw_line(oX,Y,oX,Y0,color2.data(),opacity). draw_line(oX,Y0,X,Y0,Y<=Y0?color2.data():color1.data(),opacity). draw_line(X,Y,X,Y0,color1.data(),opacity). draw_line(oX,Y,X,Y,Y<=Y0?color1.data():color2.data(),opacity); oX = X + 1; } } break; default : break; // No edges } // Draw graph points const unsigned int wb2 = plot_type==3?_width1/(2*siz):0; const float fx = (float)_width1/siz1; switch (vertex_type%8) { case 1 : { // Point cimg_foroff(data,off) { const int X = (int)(off*fx + wb2), Y = (int)((data[off]-m)/ca); draw_point(X,Y,color,opacity); } } break; case 2 : { // Straight Cross cimg_foroff(data,off) { const int X = (int)(off*fx + wb2), Y = (int)((data[off]-m)/ca); draw_line(X - 3,Y,X + 3,Y,color,opacity).draw_line(X,Y - 3,X,Y + 3,color,opacity); } } break; case 3 : { // Diagonal Cross cimg_foroff(data,off) { const int X = (int)(off*fx + wb2), Y = (int)((data[off]-m)/ca); draw_line(X - 3,Y - 3,X + 3,Y + 3,color,opacity).draw_line(X - 3,Y + 3,X + 3,Y - 3,color,opacity); } } break; case 4 : { // Filled Circle cimg_foroff(data,off) { const int X = (int)(off*fx + wb2), Y = (int)((data[off]-m)/ca); draw_circle(X,Y,3,color,opacity); } } break; case 5 : { // Outlined circle cimg_foroff(data,off) { const int X = (int)(off*fx + wb2), Y = (int)((data[off]-m)/ca); draw_circle(X,Y,3,color,opacity,~0U); } } break; case 6 : { // Square cimg_foroff(data,off) { const int X = (int)(off*fx + wb2), Y = (int)((data[off]-m)/ca); draw_rectangle(X - 3,Y - 3,X + 3,Y + 3,color,opacity,~0U); } } break; case 7 : { // Diamond cimg_foroff(data,off) { const int X = (int)(off*fx + wb2), Y = (int)((data[off]-m)/ca); draw_line(X,Y - 4,X + 4,Y,color,opacity). draw_line(X + 4,Y,X,Y + 4,color,opacity). draw_line(X,Y + 4,X - 4,Y,color,opacity). draw_line(X - 4,Y,X,Y - 4,color,opacity); } } break; default : break; // No points } return *this; } bool _draw_fill(const int x, const int y, const int z, const CImg<T>& ref, const float tolerance2) const { const T *ptr1 = data(x,y,z), *ptr2 = ref._data; const unsigned long off = _width*_height*_depth; float diff = 0; cimg_forC(*this,c) { diff += cimg::sqr(*ptr1 - *(ptr2++)); ptr1+=off; } return diff<=tolerance2; } //! Draw filled 3D region with the flood fill algorithm. /** \param x0 X-coordinate of the starting point of the region to fill. \param y0 Y-coordinate of the starting point of the region to fill. \param z0 Z-coordinate of the starting point of the region to fill. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param[out] region Image that will contain the mask of the filled region mask, as an output. \param tolerance Tolerance concerning neighborhood values. \param opacity Opacity of the drawing. \param is_high_connectivity Tells if 8-connexity must be used. \return \c region is initialized with the binary mask of the filled region. **/ template<typename tc, typename t> CImg<T>& draw_fill(const int x0, const int y0, const int z0, const tc *const color, const float opacity, CImg<t> &region, const float tolerance = 0, const bool is_high_connectivity = false) { #define _draw_fill_push(x,y,z) if (N>=stack._width) stack.resize(2*N + 1,1,1,3,0); \ stack[N] = x; stack(N,1) = y; stack(N++,2) = z #define _draw_fill_pop(x,y,z) x = stack[--N]; y = stack(N,1); z = stack(N,2) #define _draw_fill_is_inside(x,y,z) !_region(x,y,z) && _draw_fill(x,y,z,ref,tolerance2) if (!containsXYZC(x0,y0,z0,0)) return *this; const float nopacity = cimg::abs((float)opacity), copacity = 1 - std::max((float)opacity,0.f); const float tolerance2 = cimg::sqr(tolerance); const CImg<T> ref = get_vector_at(x0,y0,z0); CImg<uintT> stack(256,1,1,3); CImg<ucharT> _region(_width,_height,_depth,1,0); unsigned int N = 0; int x, y, z; _draw_fill_push(x0,y0,z0); while (N>0) { _draw_fill_pop(x,y,z); if (!_region(x,y,z)) { const int yp = y - 1, yn = y + 1, zp = z - 1, zn = z + 1; int xl = x, xr = x; // Using these booleans reduces the number of pushes drastically. bool is_yp = false, is_yn = false, is_zp = false, is_zn = false; for (int step = -1; step<2; step+=2) { while (x>=0 && x<width() && _draw_fill_is_inside(x,y,z)) { if (yp>=0 && _draw_fill_is_inside(x,yp,z)) { if (!is_yp) { _draw_fill_push(x,yp,z); is_yp = true; } } else is_yp = false; if (yn<height() && _draw_fill_is_inside(x,yn,z)) { if (!is_yn) { _draw_fill_push(x,yn,z); is_yn = true; } } else is_yn = false; if (depth()>1) { if (zp>=0 && _draw_fill_is_inside(x,y,zp)) { if (!is_zp) { _draw_fill_push(x,y,zp); is_zp = true; } } else is_zp = false; if (zn<depth() && _draw_fill_is_inside(x,y,zn)) { if (!is_zn) { _draw_fill_push(x,y,zn); is_zn = true; } } else is_zn = false; } if (is_high_connectivity) { const int xp = x - 1, xn = x + 1; if (yp>=0 && !is_yp) { if (xp>=0 && _draw_fill_is_inside(xp,yp,z)) { _draw_fill_push(xp,yp,z); if (step<0) is_yp = true; } if (xn<width() && _draw_fill_is_inside(xn,yp,z)) { _draw_fill_push(xn,yp,z); if (step>0) is_yp = true; } } if (yn<height() && !is_yn) { if (xp>=0 && _draw_fill_is_inside(xp,yn,z)) { _draw_fill_push(xp,yn,z); if (step<0) is_yn = true; } if (xn<width() && _draw_fill_is_inside(xn,yn,z)) { _draw_fill_push(xn,yn,z); if (step>0) is_yn = true; } } if (depth()>1) { if (zp>=0 && !is_zp) { if (xp>=0 && _draw_fill_is_inside(xp,y,zp)) { _draw_fill_push(xp,y,zp); if (step<0) is_zp = true; } if (xn<width() && _draw_fill_is_inside(xn,y,zp)) { _draw_fill_push(xn,y,zp); if (step>0) is_zp = true; } if (yp>=0 && !is_yp) { if (_draw_fill_is_inside(x,yp,zp)) { _draw_fill_push(x,yp,zp); } if (xp>=0 && _draw_fill_is_inside(xp,yp,zp)) { _draw_fill_push(xp,yp,zp); } if (xn<width() && _draw_fill_is_inside(xn,yp,zp)) { _draw_fill_push(xn,yp,zp); } } if (yn<height() && !is_yn) { if (_draw_fill_is_inside(x,yn,zp)) { _draw_fill_push(x,yn,zp); } if (xp>=0 && _draw_fill_is_inside(xp,yn,zp)) { _draw_fill_push(xp,yn,zp); } if (xn<width() && _draw_fill_is_inside(xn,yn,zp)) { _draw_fill_push(xn,yn,zp); } } } if (zn<depth() && !is_zn) { if (xp>=0 && _draw_fill_is_inside(xp,y,zn)) { _draw_fill_push(xp,y,zn); if (step<0) is_zn = true; } if (xn<width() && _draw_fill_is_inside(xn,y,zn)) { _draw_fill_push(xn,y,zn); if (step>0) is_zn = true; } if (yp>=0 && !is_yp) { if (_draw_fill_is_inside(x,yp,zn)) { _draw_fill_push(x,yp,zn); } if (xp>=0 && _draw_fill_is_inside(xp,yp,zn)) { _draw_fill_push(xp,yp,zn); } if (xn<width() && _draw_fill_is_inside(xn,yp,zn)) { _draw_fill_push(xn,yp,zn); } } if (yn<height() && !is_yn) { if (_draw_fill_is_inside(x,yn,zn)) { _draw_fill_push(x,yn,zn); } if (xp>=0 && _draw_fill_is_inside(xp,yn,zn)) { _draw_fill_push(xp,yn,zn); } if (xn<width() && _draw_fill_is_inside(xn,yn,zn)) { _draw_fill_push(xn,yn,zn); } } } } } x+=step; } if (step<0) { xl = ++x; x = xr + 1; is_yp = is_yn = is_zp = is_zn = false; } else xr = --x; } std::memset(_region.data(xl,y,z),1,xr - xl + 1); if (opacity==1) { if (sizeof(T)==1) { const int dx = xr - xl + 1; cimg_forC(*this,c) std::memset(data(xl,y,z,c),(int)color[c],dx); } else cimg_forC(*this,c) { const T val = (T)color[c]; T *ptri = data(xl,y,z,c); for (int k = xl; k<=xr; ++k) *(ptri++) = val; } } else cimg_forC(*this,c) { const T val = (T)(color[c]*nopacity); T *ptri = data(xl,y,z,c); for (int k = xl; k<=xr; ++k) { *ptri = (T)(val + *ptri*copacity); ++ptri; } } } } _region.move_to(region); return *this; } //! Draw filled 3D region with the flood fill algorithm \simplification. template<typename tc> CImg<T>& draw_fill(const int x0, const int y0, const int z0, const tc *const color, const float opacity=1, const float tolerance=0, const bool is_high_connexity=false) { CImg<ucharT> tmp; return draw_fill(x0,y0,z0,color,opacity,tmp,tolerance,is_high_connexity); } //! Draw filled 2D region with the flood fill algorithm \simplification. template<typename tc> CImg<T>& draw_fill(const int x0, const int y0, const tc *const color, const float opacity=1, const float tolerance=0, const bool is_high_connexity=false) { CImg<ucharT> tmp; return draw_fill(x0,y0,0,color,opacity,tmp,tolerance,is_high_connexity); } //! Draw a random plasma texture. /** \param alpha Alpha-parameter. \param beta Beta-parameter. \param scale Scale-parameter. \note Use the mid-point algorithm to render. **/ CImg<T>& draw_plasma(const float alpha=1, const float beta=0, const unsigned int scale=8) { if (is_empty()) return *this; const int w = width(), h = height(); const Tfloat m = (Tfloat)cimg::type<T>::min(), M = (Tfloat)cimg::type<T>::max(); ulongT rng = (cimg::_rand(),cimg::rng()); cimg_forZC(*this,z,c) { CImg<T> ref = get_shared_slice(z,c); for (int delta = 1<<std::min(scale,31U); delta>1; delta>>=1) { const int delta2 = delta>>1; const float r = alpha*delta + beta; // Square step. for (int y0 = 0; y0<h; y0+=delta) for (int x0 = 0; x0<w; x0+=delta) { const int x1 = (x0 + delta)%w, y1 = (y0 + delta)%h, xc = (x0 + delta2)%w, yc = (y0 + delta2)%h; const Tfloat val = (Tfloat)(0.25f*(ref(x0,y0) + ref(x0,y1) + ref(x0,y1) + ref(x1,y1)) + r*cimg::rand(-1,1,&rng)); ref(xc,yc) = (T)(val<m?m:val>M?M:val); } // Diamond steps. for (int y = -delta2; y<h; y+=delta) for (int x0=0; x0<w; x0+=delta) { const int y0 = cimg::mod(y,h), x1 = (x0 + delta)%w, y1 = (y + delta)%h, xc = (x0 + delta2)%w, yc = (y + delta2)%h; const Tfloat val = (Tfloat)(0.25f*(ref(xc,y0) + ref(x0,yc) + ref(xc,y1) + ref(x1,yc)) + r*cimg::rand(-1,1,&rng)); ref(xc,yc) = (T)(val<m?m:val>M?M:val); } for (int y0 = 0; y0<h; y0+=delta) for (int x = -delta2; x<w; x+=delta) { const int x0 = cimg::mod(x,w), x1 = (x + delta)%w, y1 = (y0 + delta)%h, xc = (x + delta2)%w, yc = (y0 + delta2)%h; const Tfloat val = (Tfloat)(0.25f*(ref(xc,y0) + ref(x0,yc) + ref(xc,y1) + ref(x1,yc)) + r*cimg::rand(-1,1,&rng)); ref(xc,yc) = (T)(val<m?m:val>M?M:val); } for (int y = -delta2; y<h; y+=delta) for (int x = -delta2; x<w; x+=delta) { const int x0 = cimg::mod(x,w), y0 = cimg::mod(y,h), x1 = (x + delta)%w, y1 = (y + delta)%h, xc = (x + delta2)%w, yc = (y + delta2)%h; const Tfloat val = (Tfloat)(0.25f*(ref(xc,y0) + ref(x0,yc) + ref(xc,y1) + ref(x1,yc)) + r*cimg::rand(-1,1,&rng)); ref(xc,yc) = (T)(val<m?m:val>M?M:val); } } } cimg::srand(rng); return *this; } //! Draw a quadratic Mandelbrot or Julia 2D fractal. /** \param x0 X-coordinate of the upper-left pixel. \param y0 Y-coordinate of the upper-left pixel. \param x1 X-coordinate of the lower-right pixel. \param y1 Y-coordinate of the lower-right pixel. \param colormap Colormap. \param opacity Drawing opacity. \param z0r Real part of the upper-left fractal vertex. \param z0i Imaginary part of the upper-left fractal vertex. \param z1r Real part of the lower-right fractal vertex. \param z1i Imaginary part of the lower-right fractal vertex. \param iteration_max Maximum number of iterations for each estimated point. \param is_normalized_iteration Tells if iterations are normalized. \param is_julia_set Tells if the Mandelbrot or Julia set is rendered. \param param_r Real part of the Julia set parameter. \param param_i Imaginary part of the Julia set parameter. \note Fractal rendering is done by the Escape Time Algorithm. **/ template<typename tc> CImg<T>& draw_mandelbrot(const int x0, const int y0, const int x1, const int y1, const CImg<tc>& colormap, const float opacity=1, const double z0r=-2, const double z0i=-2, const double z1r=2, const double z1i=2, const unsigned int iteration_max=255, const bool is_normalized_iteration=false, const bool is_julia_set=false, const double param_r=0, const double param_i=0) { if (is_empty()) return *this; CImg<tc> palette; if (colormap) palette.assign(colormap._data,colormap.size()/colormap._spectrum,1,1,colormap._spectrum,true); if (palette && palette._spectrum!=_spectrum) throw CImgArgumentException(_cimg_instance "draw_mandelbrot(): Instance and specified colormap (%u,%u,%u,%u,%p) have " "incompatible dimensions.", cimg_instance, colormap._width,colormap._height,colormap._depth,colormap._spectrum,colormap._data); const float nopacity = cimg::abs(opacity), copacity = 1 - std::max(opacity,0.f), ln2 = (float)std::log(2.); const int _x0 = cimg::cut(x0,0,width() - 1), _y0 = cimg::cut(y0,0,height() - 1), _x1 = cimg::cut(x1,0,width() - 1), _y1 = cimg::cut(y1,0,height() - 1); cimg_pragma_openmp(parallel for cimg_openmp_collapse(2) cimg_openmp_if((1 + _x1 - _x0)*(1 + _y1 - _y0)>=(cimg_openmp_sizefactor)*2048)) for (int q = _y0; q<=_y1; ++q) for (int p = _x0; p<=_x1; ++p) { unsigned int iteration = 0; const double x = z0r + p*(z1r-z0r)/_width, y = z0i + q*(z1i-z0i)/_height; double zr, zi, cr, ci; if (is_julia_set) { zr = x; zi = y; cr = param_r; ci = param_i; } else { zr = param_r; zi = param_i; cr = x; ci = y; } for (iteration=1; zr*zr + zi*zi<=4 && iteration<=iteration_max; ++iteration) { const double temp = zr*zr - zi*zi + cr; zi = 2*zr*zi + ci; zr = temp; } if (iteration>iteration_max) { if (palette) { if (opacity>=1) cimg_forC(*this,c) (*this)(p,q,0,c) = (T)palette(0,c); else cimg_forC(*this,c) (*this)(p,q,0,c) = (T)(palette(0,c)*nopacity + (*this)(p,q,0,c)*copacity); } else { if (opacity>=1) cimg_forC(*this,c) (*this)(p,q,0,c) = (T)0; else cimg_forC(*this,c) (*this)(p,q,0,c) = (T)((*this)(p,q,0,c)*copacity); } } else if (is_normalized_iteration) { const float normz = (float)cimg::abs(zr*zr + zi*zi), niteration = (float)(iteration + 1 - std::log(std::log(normz))/ln2); if (palette) { if (opacity>=1) cimg_forC(*this,c) (*this)(p,q,0,c) = (T)palette._linear_atX(niteration,c); else cimg_forC(*this,c) (*this)(p,q,0,c) = (T)(palette._linear_atX(niteration,c)*nopacity + (*this)(p,q,0,c)*copacity); } else { if (opacity>=1) cimg_forC(*this,c) (*this)(p,q,0,c) = (T)niteration; else cimg_forC(*this,c) (*this)(p,q,0,c) = (T)(niteration*nopacity + (*this)(p,q,0,c)*copacity); } } else { if (palette) { if (opacity>=1) cimg_forC(*this,c) (*this)(p,q,0,c) = (T)palette._atX(iteration,c); else cimg_forC(*this,c) (*this)(p,q,0,c) = (T)(palette(iteration,c)*nopacity + (*this)(p,q,0,c)*copacity); } else { if (opacity>=1) cimg_forC(*this,c) (*this)(p,q,0,c) = (T)iteration; else cimg_forC(*this,c) (*this)(p,q,0,c) = (T)(iteration*nopacity + (*this)(p,q,0,c)*copacity); } } } return *this; } //! Draw a quadratic Mandelbrot or Julia 2D fractal \overloading. template<typename tc> CImg<T>& draw_mandelbrot(const CImg<tc>& colormap, const float opacity=1, const double z0r=-2, const double z0i=-2, const double z1r=2, const double z1i=2, const unsigned int iteration_max=255, const bool is_normalized_iteration=false, const bool is_julia_set=false, const double param_r=0, const double param_i=0) { return draw_mandelbrot(0,0,_width - 1,_height - 1,colormap,opacity, z0r,z0i,z1r,z1i,iteration_max,is_normalized_iteration,is_julia_set,param_r,param_i); } //! Draw a 1D gaussian function. /** \param xc X-coordinate of the gaussian center. \param sigma Standard variation of the gaussian distribution. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. **/ template<typename tc> CImg<T>& draw_gaussian(const float xc, const float sigma, const tc *const color, const float opacity=1) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_gaussian(): Specified color is (null).", cimg_instance); const float sigma2 = 2*sigma*sigma, nopacity = cimg::abs(opacity), copacity = 1 - std::max(opacity,0.f); const ulongT whd = (ulongT)_width*_height*_depth; const tc *col = color; cimg_forX(*this,x) { const float dx = (x - xc), val = (float)std::exp(-dx*dx/sigma2); T *ptrd = data(x,0,0,0); if (opacity>=1) cimg_forC(*this,c) { *ptrd = (T)(val*(*col++)); ptrd+=whd; } else cimg_forC(*this,c) { *ptrd = (T)(nopacity*val*(*col++) + *ptrd*copacity); ptrd+=whd; } col-=_spectrum; } return *this; } //! Draw a 2D gaussian function. /** \param xc X-coordinate of the gaussian center. \param yc Y-coordinate of the gaussian center. \param tensor Covariance matrix (must be 2x2). \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. **/ template<typename t, typename tc> CImg<T>& draw_gaussian(const float xc, const float yc, const CImg<t>& tensor, const tc *const color, const float opacity=1) { if (is_empty()) return *this; if (tensor._width!=2 || tensor._height!=2 || tensor._depth!=1 || tensor._spectrum!=1) throw CImgArgumentException(_cimg_instance "draw_gaussian(): Specified tensor (%u,%u,%u,%u,%p) is not a 2x2 matrix.", cimg_instance, tensor._width,tensor._height,tensor._depth,tensor._spectrum,tensor._data); if (!color) throw CImgArgumentException(_cimg_instance "draw_gaussian(): Specified color is (null).", cimg_instance); typedef typename CImg<t>::Tfloat tfloat; const CImg<tfloat> invT = tensor.get_invert(), invT2 = (invT*invT)/=-2.; const tfloat a = invT2(0,0), b = 2*invT2(1,0), c = invT2(1,1); const float nopacity = cimg::abs(opacity), copacity = 1 - std::max(opacity,0.f); const ulongT whd = (ulongT)_width*_height*_depth; const tc *col = color; float dy = -yc; cimg_forY(*this,y) { float dx = -xc; cimg_forX(*this,x) { const float val = (float)std::exp(a*dx*dx + b*dx*dy + c*dy*dy); T *ptrd = data(x,y,0,0); if (opacity>=1) cimg_forC(*this,k) { *ptrd = (T)(val*(*col++)); ptrd+=whd; } else cimg_forC(*this,k) { *ptrd = (T)(nopacity*val*(*col++) + *ptrd*copacity); ptrd+=whd; } col-=_spectrum; ++dx; } ++dy; } return *this; } //! Draw a 2D gaussian function \overloading. template<typename tc> CImg<T>& draw_gaussian(const int xc, const int yc, const float r1, const float r2, const float ru, const float rv, const tc *const color, const float opacity=1) { const double a = r1*ru*ru + r2*rv*rv, b = (r1-r2)*ru*rv, c = r1*rv*rv + r2*ru*ru; const CImg<Tfloat> tensor(2,2,1,1, a,b,b,c); return draw_gaussian(xc,yc,tensor,color,opacity); } //! Draw a 2D gaussian function \overloading. template<typename tc> CImg<T>& draw_gaussian(const float xc, const float yc, const float sigma, const tc *const color, const float opacity=1) { return draw_gaussian(xc,yc,CImg<floatT>::diagonal(sigma,sigma),color,opacity); } //! Draw a 3D gaussian function \overloading. template<typename t, typename tc> CImg<T>& draw_gaussian(const float xc, const float yc, const float zc, const CImg<t>& tensor, const tc *const color, const float opacity=1) { if (is_empty()) return *this; typedef typename CImg<t>::Tfloat tfloat; if (tensor._width!=3 || tensor._height!=3 || tensor._depth!=1 || tensor._spectrum!=1) throw CImgArgumentException(_cimg_instance "draw_gaussian(): Specified tensor (%u,%u,%u,%u,%p) is not a 3x3 matrix.", cimg_instance, tensor._width,tensor._height,tensor._depth,tensor._spectrum,tensor._data); const CImg<tfloat> invT = tensor.get_invert(), invT2 = (invT*invT)/=-2.; const tfloat a = invT2(0,0), b = 2*invT2(1,0), c = 2*invT2(2,0), d = invT2(1,1), e = 2*invT2(2,1), f = invT2(2,2); const float nopacity = cimg::abs(opacity), copacity = 1 - std::max(opacity,0.f); const ulongT whd = (ulongT)_width*_height*_depth; const tc *col = color; cimg_forXYZ(*this,x,y,z) { const float dx = (x - xc), dy = (y - yc), dz = (z - zc), val = (float)std::exp(a*dx*dx + b*dx*dy + c*dx*dz + d*dy*dy + e*dy*dz + f*dz*dz); T *ptrd = data(x,y,z,0); if (opacity>=1) cimg_forC(*this,k) { *ptrd = (T)(val*(*col++)); ptrd+=whd; } else cimg_forC(*this,k) { *ptrd = (T)(nopacity*val*(*col++) + *ptrd*copacity); ptrd+=whd; } col-=_spectrum; } return *this; } //! Draw a 3D gaussian function \overloading. template<typename tc> CImg<T>& draw_gaussian(const float xc, const float yc, const float zc, const float sigma, const tc *const color, const float opacity=1) { return draw_gaussian(xc,yc,zc,CImg<floatT>::diagonal(sigma,sigma,sigma),color,opacity); } //! Draw a 3D object. /** \param x0 X-coordinate of the 3D object position \param y0 Y-coordinate of the 3D object position \param z0 Z-coordinate of the 3D object position \param vertices Image Nx3 describing 3D point coordinates \param primitives List of P primitives \param colors List of P color (or textures) \param opacities Image or list of P opacities \param render_type d Render type (0=Points, 1=Lines, 2=Faces (no light), 3=Faces (flat), 4=Faces(Gouraud) \param is_double_sided Tells if object faces have two sides or are oriented. \param focale length of the focale (0 for parallel projection) \param lightx X-coordinate of the light \param lighty Y-coordinate of the light \param lightz Z-coordinate of the light \param specular_lightness Amount of specular light. \param specular_shininess Shininess of the object \param g_opacity Global opacity of the object. **/ template<typename tp, typename tf, typename tc, typename to> CImg<T>& draw_object3d(const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const CImg<to>& opacities, const unsigned int render_type=4, const bool is_double_sided=false, const float focale=700, const float lightx=0, const float lighty=0, const float lightz=-5e8, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const float g_opacity=1) { return draw_object3d(x0,y0,z0,vertices,primitives,colors,opacities,render_type, is_double_sided,focale,lightx,lighty,lightz, specular_lightness,specular_shininess,g_opacity,CImg<floatT>::empty()); } //! Draw a 3D object \simplification. template<typename tp, typename tf, typename tc, typename to, typename tz> CImg<T>& draw_object3d(const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const CImg<to>& opacities, const unsigned int render_type, const bool is_double_sided, const float focale, const float lightx, const float lighty, const float lightz, const float specular_lightness, const float specular_shininess, const float g_opacity, CImg<tz>& zbuffer) { return _draw_object3d(0,zbuffer,x0,y0,z0,vertices,primitives,colors,opacities, render_type,is_double_sided,focale,lightx,lighty,lightz, specular_lightness,specular_shininess,g_opacity,1); } #ifdef cimg_use_board template<typename tp, typename tf, typename tc, typename to> CImg<T>& draw_object3d(LibBoard::Board& board, const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const CImg<to>& opacities, const unsigned int render_type=4, const bool is_double_sided=false, const float focale=700, const float lightx=0, const float lighty=0, const float lightz=-5e8, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const float g_opacity=1) { return draw_object3d(board,x0,y0,z0,vertices,primitives,colors,opacities,render_type, is_double_sided,focale,lightx,lighty,lightz, specular_lightness,specular_shininess,g_opacity,CImg<floatT>::empty()); } template<typename tp, typename tf, typename tc, typename to, typename tz> CImg<T>& draw_object3d(LibBoard::Board& board, const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const CImg<to>& opacities, const unsigned int render_type, const bool is_double_sided, const float focale, const float lightx, const float lighty, const float lightz, const float specular_lightness, const float specular_shininess, const float g_opacity, CImg<tz>& zbuffer) { return _draw_object3d((void*)&board,zbuffer,x0,y0,z0,vertices,primitives,colors,opacities, render_type,is_double_sided,focale,lightx,lighty,lightz, specular_lightness,specular_shininess,g_opacity,1); } #endif //! Draw a 3D object \simplification. template<typename tp, typename tf, typename tc, typename to> CImg<T>& draw_object3d(const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const CImgList<to>& opacities, const unsigned int render_type=4, const bool is_double_sided=false, const float focale=700, const float lightx=0, const float lighty=0, const float lightz=-5e8, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const float g_opacity=1) { return draw_object3d(x0,y0,z0,vertices,primitives,colors,opacities,render_type, is_double_sided,focale,lightx,lighty,lightz, specular_lightness,specular_shininess,g_opacity,CImg<floatT>::empty()); } //! Draw a 3D object \simplification. template<typename tp, typename tf, typename tc, typename to, typename tz> CImg<T>& draw_object3d(const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const CImgList<to>& opacities, const unsigned int render_type, const bool is_double_sided, const float focale, const float lightx, const float lighty, const float lightz, const float specular_lightness, const float specular_shininess, const float g_opacity, CImg<tz>& zbuffer) { return _draw_object3d(0,zbuffer,x0,y0,z0,vertices,primitives,colors,opacities, render_type,is_double_sided,focale,lightx,lighty,lightz, specular_lightness,specular_shininess,g_opacity,1); } #ifdef cimg_use_board template<typename tp, typename tf, typename tc, typename to> CImg<T>& draw_object3d(LibBoard::Board& board, const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const CImgList<to>& opacities, const unsigned int render_type=4, const bool is_double_sided=false, const float focale=700, const float lightx=0, const float lighty=0, const float lightz=-5e8, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const float g_opacity=1) { return draw_object3d(board,x0,y0,z0,vertices,primitives,colors,opacities,render_type, is_double_sided,focale,lightx,lighty,lightz, specular_lightness,specular_shininess,g_opacity,CImg<floatT>::empty()); } template<typename tp, typename tf, typename tc, typename to, typename tz> CImg<T>& draw_object3d(LibBoard::Board& board, const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const CImgList<to>& opacities, const unsigned int render_type, const bool is_double_sided, const float focale, const float lightx, const float lighty, const float lightz, const float specular_lightness, const float specular_shininess, const float g_opacity, CImg<tz>& zbuffer) { return _draw_object3d((void*)&board,zbuffer,x0,y0,z0,vertices,primitives,colors,opacities, render_type,is_double_sided,focale,lightx,lighty,lightz, specular_lightness,specular_shininess,g_opacity,1); } #endif //! Draw a 3D object \simplification. template<typename tp, typename tf, typename tc> CImg<T>& draw_object3d(const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const unsigned int render_type=4, const bool is_double_sided=false, const float focale=700, const float lightx=0, const float lighty=0, const float lightz=-5e8, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const float g_opacity=1) { return draw_object3d(x0,y0,z0,vertices,primitives,colors,CImg<floatT>::const_empty(), render_type,is_double_sided,focale,lightx,lighty,lightz, specular_lightness,specular_shininess,g_opacity,CImg<floatT>::empty()); } //! Draw a 3D object \simplification. template<typename tp, typename tf, typename tc, typename tz> CImg<T>& draw_object3d(const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const unsigned int render_type, const bool is_double_sided, const float focale, const float lightx, const float lighty, const float lightz, const float specular_lightness, const float specular_shininess, const float g_opacity, CImg<tz>& zbuffer) { return draw_object3d(x0,y0,z0,vertices,primitives,colors,CImg<floatT>::const_empty(), render_type,is_double_sided,focale,lightx,lighty,lightz, specular_lightness,specular_shininess,g_opacity,zbuffer); } #ifdef cimg_use_board template<typename tp, typename tf, typename tc, typename to> CImg<T>& draw_object3d(LibBoard::Board& board, const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const unsigned int render_type=4, const bool is_double_sided=false, const float focale=700, const float lightx=0, const float lighty=0, const float lightz=-5e8, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const float g_opacity=1) { return draw_object3d(x0,y0,z0,vertices,primitives,colors,CImg<floatT>::const_empty(), render_type,is_double_sided,focale,lightx,lighty,lightz, specular_lightness,specular_shininess,g_opacity,CImg<floatT>::empty()); } template<typename tp, typename tf, typename tc, typename to, typename tz> CImg<T>& draw_object3d(LibBoard::Board& board, const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const unsigned int render_type, const bool is_double_sided, const float focale, const float lightx, const float lighty, const float lightz, const float specular_lightness, const float specular_shininess, const float g_opacity, CImg<tz>& zbuffer) { return draw_object3d(x0,y0,z0,vertices,primitives,colors,CImg<floatT>::const_empty(), render_type,is_double_sided,focale,lightx,lighty,lightz, specular_lightness,specular_shininess,g_opacity,zbuffer); } #endif template<typename t, typename to> static float __draw_object3d(const CImgList<t>& opacities, const unsigned int n_primitive, CImg<to>& opacity) { if (n_primitive>=opacities._width || opacities[n_primitive].is_empty()) { opacity.assign(); return 1; } if (opacities[n_primitive].size()==1) { opacity.assign(); return opacities(n_primitive,0); } opacity.assign(opacities[n_primitive],true); return 1.f; } template<typename t, typename to> static float __draw_object3d(const CImg<t>& opacities, const unsigned int n_primitive, CImg<to>& opacity) { opacity.assign(); return n_primitive>=opacities._width?1.f:(float)opacities[n_primitive]; } template<typename t> static float ___draw_object3d(const CImgList<t>& opacities, const unsigned int n_primitive) { return n_primitive<opacities._width && opacities[n_primitive].size()==1?(float)opacities(n_primitive,0):1.f; } template<typename t> static float ___draw_object3d(const CImg<t>& opacities, const unsigned int n_primitive) { return n_primitive<opacities._width?(float)opacities[n_primitive]:1.f; } template<typename tz, typename tp, typename tf, typename tc, typename to> CImg<T>& _draw_object3d(void *const pboard, CImg<tz>& zbuffer, const float X, const float Y, const float Z, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const to& opacities, const unsigned int render_type, const bool is_double_sided, const float focale, const float lightx, const float lighty, const float lightz, const float specular_lightness, const float specular_shininess, const float g_opacity, const float sprite_scale) { typedef typename cimg::superset2<tp,tz,float>::type tpfloat; typedef typename to::value_type _to; if (is_empty() || !vertices || !primitives) return *this; CImg<char> error_message(1024); if (!vertices.is_object3d(primitives,colors,opacities,false,error_message)) throw CImgArgumentException(_cimg_instance "draw_object3d(): Invalid specified 3D object (%u,%u) (%s).", cimg_instance,vertices._width,primitives._width,error_message.data()); #ifndef cimg_use_board if (pboard) return *this; #endif if (render_type==5) cimg::mutex(10); // Static variable used in this case, breaks thread-safety const float nspec = 1 - (specular_lightness<0.f?0.f:(specular_lightness>1.f?1.f:specular_lightness)), nspec2 = 1 + (specular_shininess<0.f?0.f:specular_shininess), nsl1 = (nspec2 - 1)/cimg::sqr(nspec - 1), nsl2 = 1 - 2*nsl1*nspec, nsl3 = nspec2 - nsl1 - nsl2; // Create light texture for phong-like rendering. CImg<floatT> light_texture; if (render_type==5) { if (colors._width>primitives._width) { static CImg<floatT> default_light_texture; static const tc *lptr = 0; static tc ref_values[64] = { 0 }; const CImg<tc>& img = colors.back(); bool is_same_texture = (lptr==img._data); if (is_same_texture) for (unsigned int r = 0, j = 0; j<8; ++j) for (unsigned int i = 0; i<8; ++i) if (ref_values[r++]!=img(i*img._width/9,j*img._height/9,0,(i + j)%img._spectrum)) { is_same_texture = false; break; } if (!is_same_texture || default_light_texture._spectrum<_spectrum) { (default_light_texture.assign(img,false)/=255).resize(-100,-100,1,_spectrum); lptr = colors.back().data(); for (unsigned int r = 0, j = 0; j<8; ++j) for (unsigned int i = 0; i<8; ++i) ref_values[r++] = img(i*img._width/9,j*img._height/9,0,(i + j)%img._spectrum); } light_texture.assign(default_light_texture,true); } else { static CImg<floatT> default_light_texture; static float olightx = 0, olighty = 0, olightz = 0, ospecular_shininess = 0; if (!default_light_texture || lightx!=olightx || lighty!=olighty || lightz!=olightz || specular_shininess!=ospecular_shininess || default_light_texture._spectrum<_spectrum) { default_light_texture.assign(512,512); const float dlx = lightx - X, dly = lighty - Y, dlz = lightz - Z, nl = cimg::hypot(dlx,dly,dlz), nlx = (default_light_texture._width - 1)/2*(1 + dlx/nl), nly = (default_light_texture._height - 1)/2*(1 + dly/nl), white[] = { 1 }; default_light_texture.draw_gaussian(nlx,nly,default_light_texture._width/3.f,white); cimg_forXY(default_light_texture,x,y) { const float factor = default_light_texture(x,y); if (factor>nspec) default_light_texture(x,y) = std::min(2.f,nsl1*factor*factor + nsl2*factor + nsl3); } default_light_texture.resize(-100,-100,1,_spectrum); olightx = lightx; olighty = lighty; olightz = lightz; ospecular_shininess = specular_shininess; } light_texture.assign(default_light_texture,true); } } // Compute 3D to 2D projection. CImg<tpfloat> projections(vertices._width,2); tpfloat parallzmin = cimg::type<tpfloat>::max(); const float absfocale = focale?cimg::abs(focale):0; if (absfocale) { cimg_pragma_openmp(parallel for cimg_openmp_if_size(projections.size(),4096)) cimg_forX(projections,l) { // Perspective projection const tpfloat x = (tpfloat)vertices(l,0), y = (tpfloat)vertices(l,1), z = (tpfloat)vertices(l,2); const tpfloat projectedz = z + Z + absfocale; projections(l,1) = Y + absfocale*y/projectedz; projections(l,0) = X + absfocale*x/projectedz; } } else { cimg_pragma_openmp(parallel for cimg_openmp_if_size(projections.size(),4096)) cimg_forX(projections,l) { // Parallel projection const tpfloat x = (tpfloat)vertices(l,0), y = (tpfloat)vertices(l,1), z = (tpfloat)vertices(l,2); if (z<parallzmin) parallzmin = z; projections(l,1) = Y + y; projections(l,0) = X + x; } } const float _focale = absfocale?absfocale:(1e5f-parallzmin); float zmax = 0; if (zbuffer) zmax = vertices.get_shared_row(2).max(); // Compute visible primitives. CImg<uintT> visibles(primitives._width,1,1,1,~0U); CImg<tpfloat> zrange(primitives._width); const tpfloat zmin = absfocale?(tpfloat)(1.5f - absfocale):cimg::type<tpfloat>::min(); bool is_forward = zbuffer?true:false; cimg_pragma_openmp(parallel for cimg_openmp_if_size(primitives.size(),4096)) cimglist_for(primitives,l) { const CImg<tf>& primitive = primitives[l]; switch (primitive.size()) { case 1 : { // Point CImg<_to> _opacity; __draw_object3d(opacities,l,_opacity); if (l<=colors.width() && (colors[l].size()!=_spectrum || _opacity)) is_forward = false; const unsigned int i0 = (unsigned int)primitive(0); const tpfloat z0 = Z + vertices(i0,2); if (z0>zmin) { visibles(l) = (unsigned int)l; zrange(l) = z0; } } break; case 5 : { // Sphere const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1); const tpfloat Xc = 0.5f*((float)vertices(i0,0) + (float)vertices(i1,0)), Yc = 0.5f*((float)vertices(i0,1) + (float)vertices(i1,1)), Zc = 0.5f*((float)vertices(i0,2) + (float)vertices(i1,2)), _zc = Z + Zc, zc = _zc + _focale, xc = X + Xc*(absfocale?absfocale/zc:1), yc = Y + Yc*(absfocale?absfocale/zc:1), radius = 0.5f*cimg::hypot(vertices(i1,0) - vertices(i0,0), vertices(i1,1) - vertices(i0,1), vertices(i1,2) - vertices(i0,2))*(absfocale?absfocale/zc:1), xm = xc - radius, ym = yc - radius, xM = xc + radius, yM = yc + radius; if (xM>=0 && xm<_width && yM>=0 && ym<_height && _zc>zmin) { visibles(l) = (unsigned int)l; zrange(l) = _zc; } is_forward = false; } break; case 2 : case 6 : { // Segment const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1); const tpfloat x0 = projections(i0,0), y0 = projections(i0,1), z0 = Z + vertices(i0,2), x1 = projections(i1,0), y1 = projections(i1,1), z1 = Z + vertices(i1,2); tpfloat xm, xM, ym, yM; if (x0<x1) { xm = x0; xM = x1; } else { xm = x1; xM = x0; } if (y0<y1) { ym = y0; yM = y1; } else { ym = y1; yM = y0; } if (xM>=0 && xm<_width && yM>=0 && ym<_height && z0>zmin && z1>zmin) { visibles(l) = (unsigned int)l; zrange(l) = (z0 + z1)/2; } } break; case 3 : case 9 : { // Triangle const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1), i2 = (unsigned int)primitive(2); const tpfloat x0 = projections(i0,0), y0 = projections(i0,1), z0 = Z + vertices(i0,2), x1 = projections(i1,0), y1 = projections(i1,1), z1 = Z + vertices(i1,2), x2 = projections(i2,0), y2 = projections(i2,1), z2 = Z + vertices(i2,2); tpfloat xm, xM, ym, yM; if (x0<x1) { xm = x0; xM = x1; } else { xm = x1; xM = x0; } if (x2<xm) xm = x2; if (x2>xM) xM = x2; if (y0<y1) { ym = y0; yM = y1; } else { ym = y1; yM = y0; } if (y2<ym) ym = y2; if (y2>yM) yM = y2; if (xM>=0 && xm<_width && yM>=0 && ym<_height && z0>zmin && z1>zmin && z2>zmin) { const tpfloat d = (x1-x0)*(y2-y0) - (x2-x0)*(y1-y0); if (is_double_sided || d<0) { visibles(l) = (unsigned int)l; zrange(l) = (z0 + z1 + z2)/3; } } } break; case 4 : case 12 : { // Quadrangle const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1), i2 = (unsigned int)primitive(2), i3 = (unsigned int)primitive(3); const tpfloat x0 = projections(i0,0), y0 = projections(i0,1), z0 = Z + vertices(i0,2), x1 = projections(i1,0), y1 = projections(i1,1), z1 = Z + vertices(i1,2), x2 = projections(i2,0), y2 = projections(i2,1), z2 = Z + vertices(i2,2), x3 = projections(i3,0), y3 = projections(i3,1), z3 = Z + vertices(i3,2); tpfloat xm, xM, ym, yM; if (x0<x1) { xm = x0; xM = x1; } else { xm = x1; xM = x0; } if (x2<xm) xm = x2; if (x2>xM) xM = x2; if (x3<xm) xm = x3; if (x3>xM) xM = x3; if (y0<y1) { ym = y0; yM = y1; } else { ym = y1; yM = y0; } if (y2<ym) ym = y2; if (y2>yM) yM = y2; if (y3<ym) ym = y3; if (y3>yM) yM = y3; if (xM>=0 && xm<_width && yM>=0 && ym<_height && z0>zmin && z1>zmin && z2>zmin && z3>zmin) { const float d = (x1 - x0)*(y2 - y0) - (x2 - x0)*(y1 - y0); if (is_double_sided || d<0) { visibles(l) = (unsigned int)l; zrange(l) = (z0 + z1 + z2 + z3)/4; } } } break; default : if (render_type==5) cimg::mutex(10,0); throw CImgArgumentException(_cimg_instance "draw_object3d(): Invalid primitive[%u] with size %u " "(should have size 1,2,3,4,5,6,9 or 12).", cimg_instance, l,primitive.size()); } } // Force transparent primitives to be drawn last when zbuffer is activated // (and if object contains no spheres or sprites). if (is_forward) cimglist_for(primitives,l) if (___draw_object3d(opacities,l)!=1) zrange(l) = 2*zmax - zrange(l); // Sort only visibles primitives. unsigned int *p_visibles = visibles._data; tpfloat *p_zrange = zrange._data; const tpfloat *ptrz = p_zrange; cimg_for(visibles,ptr,unsigned int) { if (*ptr!=~0U) { *(p_visibles++) = *ptr; *(p_zrange++) = *ptrz; } ++ptrz; } const unsigned int nb_visibles = (unsigned int)(p_zrange - zrange._data); if (!nb_visibles) { if (render_type==5) cimg::mutex(10,0); return *this; } CImg<uintT> permutations; CImg<tpfloat>(zrange._data,nb_visibles,1,1,1,true).sort(permutations,is_forward); // Compute light properties CImg<floatT> lightprops; switch (render_type) { case 3 : { // Flat Shading lightprops.assign(nb_visibles); cimg_pragma_openmp(parallel for cimg_openmp_if_size(nb_visibles,4096)) cimg_forX(lightprops,l) { const CImg<tf>& primitive = primitives(visibles(permutations(l))); const unsigned int psize = (unsigned int)primitive.size(); if (psize==3 || psize==4 || psize==9 || psize==12) { const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1), i2 = (unsigned int)primitive(2); const tpfloat x0 = (tpfloat)vertices(i0,0), y0 = (tpfloat)vertices(i0,1), z0 = (tpfloat)vertices(i0,2), x1 = (tpfloat)vertices(i1,0), y1 = (tpfloat)vertices(i1,1), z1 = (tpfloat)vertices(i1,2), x2 = (tpfloat)vertices(i2,0), y2 = (tpfloat)vertices(i2,1), z2 = (tpfloat)vertices(i2,2), dx1 = x1 - x0, dy1 = y1 - y0, dz1 = z1 - z0, dx2 = x2 - x0, dy2 = y2 - y0, dz2 = z2 - z0, nx = dy1*dz2 - dz1*dy2, ny = dz1*dx2 - dx1*dz2, nz = dx1*dy2 - dy1*dx2, norm = 1e-5f + cimg::hypot(nx,ny,nz), lx = X + (x0 + x1 + x2)/3 - lightx, ly = Y + (y0 + y1 + y2)/3 - lighty, lz = Z + (z0 + z1 + z2)/3 - lightz, nl = 1e-5f + cimg::hypot(lx,ly,lz), factor = std::max(cimg::abs(-lx*nx - ly*ny - lz*nz)/(norm*nl),(tpfloat)0); lightprops[l] = factor<=nspec?factor:(nsl1*factor*factor + nsl2*factor + nsl3); } else lightprops[l] = 1; } } break; case 4 : // Gouraud Shading case 5 : { // Phong-Shading CImg<tpfloat> vertices_normals(vertices._width,6,1,1,0); cimg_pragma_openmp(parallel for cimg_openmp_if_size(nb_visibles,4096)) for (int l = 0; l<(int)nb_visibles; ++l) { const CImg<tf>& primitive = primitives[visibles(l)]; const unsigned int psize = (unsigned int)primitive.size(); const bool triangle_flag = (psize==3) || (psize==9), quadrangle_flag = (psize==4) || (psize==12); if (triangle_flag || quadrangle_flag) { const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1), i2 = (unsigned int)primitive(2), i3 = quadrangle_flag?(unsigned int)primitive(3):0; const tpfloat x0 = (tpfloat)vertices(i0,0), y0 = (tpfloat)vertices(i0,1), z0 = (tpfloat)vertices(i0,2), x1 = (tpfloat)vertices(i1,0), y1 = (tpfloat)vertices(i1,1), z1 = (tpfloat)vertices(i1,2), x2 = (tpfloat)vertices(i2,0), y2 = (tpfloat)vertices(i2,1), z2 = (tpfloat)vertices(i2,2), dx1 = x1 - x0, dy1 = y1 - y0, dz1 = z1 - z0, dx2 = x2 - x0, dy2 = y2 - y0, dz2 = z2 - z0, nnx = dy1*dz2 - dz1*dy2, nny = dz1*dx2 - dx1*dz2, nnz = dx1*dy2 - dy1*dx2, norm = 1e-5f + cimg::hypot(nnx,nny,nnz), nx = nnx/norm, ny = nny/norm, nz = nnz/norm; unsigned int ix = 0, iy = 1, iz = 2; if (is_double_sided && nz>0) { ix = 3; iy = 4; iz = 5; } vertices_normals(i0,ix)+=nx; vertices_normals(i0,iy)+=ny; vertices_normals(i0,iz)+=nz; vertices_normals(i1,ix)+=nx; vertices_normals(i1,iy)+=ny; vertices_normals(i1,iz)+=nz; vertices_normals(i2,ix)+=nx; vertices_normals(i2,iy)+=ny; vertices_normals(i2,iz)+=nz; if (quadrangle_flag) { vertices_normals(i3,ix)+=nx; vertices_normals(i3,iy)+=ny; vertices_normals(i3,iz)+=nz; } } } if (is_double_sided) cimg_forX(vertices_normals,p) { const float nx0 = vertices_normals(p,0), ny0 = vertices_normals(p,1), nz0 = vertices_normals(p,2), nx1 = vertices_normals(p,3), ny1 = vertices_normals(p,4), nz1 = vertices_normals(p,5), n0 = nx0*nx0 + ny0*ny0 + nz0*nz0, n1 = nx1*nx1 + ny1*ny1 + nz1*nz1; if (n1>n0) { vertices_normals(p,0) = -nx1; vertices_normals(p,1) = -ny1; vertices_normals(p,2) = -nz1; } } if (render_type==4) { lightprops.assign(vertices._width); cimg_pragma_openmp(parallel for cimg_openmp_if_size(nb_visibles,4096)) cimg_forX(lightprops,l) { const tpfloat nx = vertices_normals(l,0), ny = vertices_normals(l,1), nz = vertices_normals(l,2), norm = 1e-5f + cimg::hypot(nx,ny,nz), lx = X + vertices(l,0) - lightx, ly = Y + vertices(l,1) - lighty, lz = Z + vertices(l,2) - lightz, nl = 1e-5f + cimg::hypot(lx,ly,lz), factor = std::max((-lx*nx - ly*ny - lz*nz)/(norm*nl),(tpfloat)0); lightprops[l] = factor<=nspec?factor:(nsl1*factor*factor + nsl2*factor + nsl3); } } else { const unsigned int lw2 = light_texture._width/2 - 1, lh2 = light_texture._height/2 - 1; lightprops.assign(vertices._width,2); cimg_pragma_openmp(parallel for cimg_openmp_if_size(nb_visibles,4096)) cimg_forX(lightprops,l) { const tpfloat nx = vertices_normals(l,0), ny = vertices_normals(l,1), nz = vertices_normals(l,2), norm = 1e-5f + cimg::hypot(nx,ny,nz), nnx = nx/norm, nny = ny/norm; lightprops(l,0) = lw2*(1 + nnx); lightprops(l,1) = lh2*(1 + nny); } } } break; } // Draw visible primitives const CImg<tc> default_color(1,_spectrum,1,1,(tc)200); CImg<_to> _opacity; for (unsigned int l = 0; l<nb_visibles; ++l) { const unsigned int n_primitive = visibles(permutations(l)); const CImg<tf>& primitive = primitives[n_primitive]; const CImg<tc> &__color = n_primitive<colors._width?colors[n_primitive]:CImg<tc>(), _color = (__color && __color.size()!=_spectrum && __color._spectrum<_spectrum)? __color.get_resize(-100,-100,-100,_spectrum,0):CImg<tc>(), &color = _color?_color:(__color?__color:default_color); const tc *const pcolor = color._data; float opacity = __draw_object3d(opacities,n_primitive,_opacity); if (_opacity.is_empty()) opacity*=g_opacity; #ifdef cimg_use_board LibBoard::Board &board = *(LibBoard::Board*)pboard; #endif switch (primitive.size()) { case 1 : { // Colored point or sprite const unsigned int n0 = (unsigned int)primitive[0]; const int x0 = cimg::uiround(projections(n0,0)), y0 = cimg::uiround(projections(n0,1)); if (_opacity.is_empty()) { // Scalar opacity if (color.size()==_spectrum) { // Colored point draw_point(x0,y0,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawDot((float)x0,height()-(float)y0); } #endif } else { // Sprite const tpfloat z = Z + vertices(n0,2); const float factor = focale<0?1:sprite_scale*(absfocale?absfocale/(z + absfocale):1); const unsigned int _sw = (unsigned int)(color._width*factor), _sh = (unsigned int)(color._height*factor), sw = _sw?_sw:1, sh = _sh?_sh:1; const int nx0 = x0 - (int)sw/2, ny0 = y0 - (int)sh/2; if (sw<=3*_width/2 && sh<=3*_height/2 && (nx0 + (int)sw/2>=0 || nx0 - (int)sw/2<width() || ny0 + (int)sh/2>=0 || ny0 - (int)sh/2<height())) { const CImg<tc> _sprite = (sw!=color._width || sh!=color._height)? color.get_resize(sw,sh,1,-100,render_type<=3?1:3):CImg<tc>(), &sprite = _sprite?_sprite:color; draw_image(nx0,ny0,sprite,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128); board.setFillColor(LibBoard::Color::Null); board.drawRectangle((float)nx0,height() - (float)ny0,sw,sh); } #endif } } } else { // Opacity mask const tpfloat z = Z + vertices(n0,2); const float factor = focale<0?1:sprite_scale*(absfocale?absfocale/(z + absfocale):1); const unsigned int _sw = (unsigned int)(std::max(color._width,_opacity._width)*factor), _sh = (unsigned int)(std::max(color._height,_opacity._height)*factor), sw = _sw?_sw:1, sh = _sh?_sh:1; const int nx0 = x0 - (int)sw/2, ny0 = y0 - (int)sh/2; if (sw<=3*_width/2 && sh<=3*_height/2 && (nx0 + (int)sw/2>=0 || nx0 - (int)sw/2<width() || ny0 + (int)sh/2>=0 || ny0 - (int)sh/2<height())) { const CImg<tc> _sprite = (sw!=color._width || sh!=color._height)? color.get_resize(sw,sh,1,-100,render_type<=3?1:3):CImg<tc>(), &sprite = _sprite?_sprite:color; const CImg<_to> _nopacity = (sw!=_opacity._width || sh!=_opacity._height)? _opacity.get_resize(sw,sh,1,-100,render_type<=3?1:3):CImg<_to>(), &nopacity = _nopacity?_nopacity:_opacity; draw_image(nx0,ny0,sprite,nopacity,g_opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128); board.setFillColor(LibBoard::Color::Null); board.drawRectangle((float)nx0,height() - (float)ny0,sw,sh); } #endif } } } break; case 2 : { // Colored line const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1]; const int x0 = cimg::uiround(projections(n0,0)), y0 = cimg::uiround(projections(n0,1)), x1 = cimg::uiround(projections(n1,0)), y1 = cimg::uiround(projections(n1,1)); const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale; if (render_type) { if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,pcolor,opacity); else draw_line(x0,y0,x1,y1,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawLine((float)x0,height() - (float)y0,x1,height() - (float)y1); } #endif } else { draw_point(x0,y0,pcolor,opacity).draw_point(x1,y1,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawDot((float)x0,height() - (float)y0); board.drawDot((float)x1,height() - (float)y1); } #endif } } break; case 5 : { // Colored sphere const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1], is_wireframe = (unsigned int)primitive[2]; const float Xc = 0.5f*((float)vertices(n0,0) + (float)vertices(n1,0)), Yc = 0.5f*((float)vertices(n0,1) + (float)vertices(n1,1)), Zc = 0.5f*((float)vertices(n0,2) + (float)vertices(n1,2)), zc = Z + Zc + _focale, xc = X + Xc*(absfocale?absfocale/zc:1), yc = Y + Yc*(absfocale?absfocale/zc:1), radius = 0.5f*cimg::hypot(vertices(n1,0) - vertices(n0,0), vertices(n1,1) - vertices(n0,1), vertices(n1,2) - vertices(n0,2))*(absfocale?absfocale/zc:1); switch (render_type) { case 0 : draw_point((int)xc,(int)yc,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawDot(xc,height() - yc); } #endif break; case 1 : draw_circle((int)xc,(int)yc,(int)radius,pcolor,opacity,~0U); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.setFillColor(LibBoard::Color::Null); board.drawCircle(xc,height() - yc,radius); } #endif break; default : if (is_wireframe) draw_circle((int)xc,(int)yc,(int)radius,pcolor,opacity,~0U); else draw_circle((int)xc,(int)yc,(int)radius,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); if (!is_wireframe) board.fillCircle(xc,height() - yc,radius); else { board.setFillColor(LibBoard::Color::Null); board.drawCircle(xc,height() - yc,radius); } } #endif break; } } break; case 6 : { // Textured line if (!__color) { if (render_type==5) cimg::mutex(10,0); throw CImgArgumentException(_cimg_instance "draw_object3d(): Undefined texture for line primitive [%u].", cimg_instance,n_primitive); } const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1]; const int tx0 = (int)primitive[2], ty0 = (int)primitive[3], tx1 = (int)primitive[4], ty1 = (int)primitive[5], x0 = cimg::uiround(projections(n0,0)), y0 = cimg::uiround(projections(n0,1)), x1 = cimg::uiround(projections(n1,0)), y1 = cimg::uiround(projections(n1,1)); const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale; if (render_type) { if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,color,tx0,ty0,tx1,ty1,opacity); else draw_line(x0,y0,z0,x1,y1,z1,color,tx0,ty0,tx1,ty1,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.drawLine((float)x0,height() - (float)y0,(float)x1,height() - (float)y1); } #endif } else { draw_point(x0,y0,color.get_vector_at(tx0<=0?0:tx0>=color.width()?color.width() - 1:tx0, ty0<=0?0:ty0>=color.height()?color.height() - 1:ty0)._data,opacity). draw_point(x1,y1,color.get_vector_at(tx1<=0?0:tx1>=color.width()?color.width() - 1:tx1, ty1<=0?0:ty1>=color.height()?color.height() - 1:ty1)._data,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.drawDot((float)x0,height() - (float)y0); board.drawDot((float)x1,height() - (float)y1); } #endif } } break; case 3 : { // Colored triangle const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1], n2 = (unsigned int)primitive[2]; const int x0 = cimg::uiround(projections(n0,0)), y0 = cimg::uiround(projections(n0,1)), x1 = cimg::uiround(projections(n1,0)), y1 = cimg::uiround(projections(n1,1)), x2 = cimg::uiround(projections(n2,0)), y2 = cimg::uiround(projections(n2,1)); const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale, z2 = vertices(n2,2) + Z + _focale; switch (render_type) { case 0 : draw_point(x0,y0,pcolor,opacity).draw_point(x1,y1,pcolor,opacity).draw_point(x2,y2,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawDot((float)x0,height() - (float)y0); board.drawDot((float)x1,height() - (float)y1); board.drawDot((float)x2,height() - (float)y2); } #endif break; case 1 : if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,pcolor,opacity).draw_line(zbuffer,x0,y0,z0,x2,y2,z2,pcolor,opacity). draw_line(zbuffer,x1,y1,z1,x2,y2,z2,pcolor,opacity); else draw_line(x0,y0,x1,y1,pcolor,opacity).draw_line(x0,y0,x2,y2,pcolor,opacity). draw_line(x1,y1,x2,y2,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawLine((float)x0,height() - (float)y0,(float)x1,height() - (float)y1); board.drawLine((float)x0,height() - (float)y0,(float)x2,height() - (float)y2); board.drawLine((float)x1,height() - (float)y1,(float)x2,height() - (float)y2); } #endif break; case 2 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,opacity); else draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); } #endif break; case 3 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,opacity,lightprops(l)); else _draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,opacity,lightprops(l)); #ifdef cimg_use_board if (pboard) { const float lp = std::min(lightprops(l),1.f); board.setPenColorRGBi((unsigned char)(color[0]*lp), (unsigned char)(color[1]*lp), (unsigned char)(color[2]*lp), (unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); } #endif break; case 4 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor, lightprops(n0),lightprops(n1),lightprops(n2),opacity); else draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,lightprops(n0),lightprops(n1),lightprops(n2),opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi((unsigned char)(color[0]), (unsigned char)(color[1]), (unsigned char)(color[2]), (unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,lightprops(n0), (float)x1,height() - (float)y1,lightprops(n1), (float)x2,height() - (float)y2,lightprops(n2)); } #endif break; case 5 : { const unsigned int lx0 = (unsigned int)cimg::uiround(lightprops(n0,0)), ly0 = (unsigned int)cimg::uiround(lightprops(n0,1)), lx1 = (unsigned int)cimg::uiround(lightprops(n1,0)), ly1 = (unsigned int)cimg::uiround(lightprops(n1,1)), lx2 = (unsigned int)cimg::uiround(lightprops(n2,0)), ly2 = (unsigned int)cimg::uiround(lightprops(n2,1)); if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,light_texture,lx0,ly0,lx1,ly1,lx2,ly2,opacity); else draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,light_texture,lx0,ly0,lx1,ly1,lx2,ly2,opacity); #ifdef cimg_use_board if (pboard) { const float l0 = light_texture((int)(light_texture.width()/2*(1 + lightprops(n0,0))), (int)(light_texture.height()/2*(1 + lightprops(n0,1)))), l1 = light_texture((int)(light_texture.width()/2*(1 + lightprops(n1,0))), (int)(light_texture.height()/2*(1 + lightprops(n1,1)))), l2 = light_texture((int)(light_texture.width()/2*(1 + lightprops(n2,0))), (int)(light_texture.height()/2*(1 + lightprops(n2,1)))); board.setPenColorRGBi((unsigned char)(color[0]), (unsigned char)(color[1]), (unsigned char)(color[2]), (unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,l0, (float)x1,height() - (float)y1,l1, (float)x2,height() - (float)y2,l2); } #endif } break; } } break; case 4 : { // Colored quadrangle const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1], n2 = (unsigned int)primitive[2], n3 = (unsigned int)primitive[3]; const int x0 = cimg::uiround(projections(n0,0)), y0 = cimg::uiround(projections(n0,1)), x1 = cimg::uiround(projections(n1,0)), y1 = cimg::uiround(projections(n1,1)), x2 = cimg::uiround(projections(n2,0)), y2 = cimg::uiround(projections(n2,1)), x3 = cimg::uiround(projections(n3,0)), y3 = cimg::uiround(projections(n3,1)), xc = (x0 + x1 + x2 + x3)/4, yc = (y0 + y1 + y2 + y3)/4; const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale, z2 = vertices(n2,2) + Z + _focale, z3 = vertices(n3,2) + Z + _focale, zc = (z0 + z1 + z2 + z3)/4; switch (render_type) { case 0 : draw_point(x0,y0,pcolor,opacity).draw_point(x1,y1,pcolor,opacity). draw_point(x2,y2,pcolor,opacity).draw_point(x3,y3,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawDot((float)x0,height() - (float)y0); board.drawDot((float)x1,height() - (float)y1); board.drawDot((float)x2,height() - (float)y2); board.drawDot((float)x3,height() - (float)y3); } #endif break; case 1 : if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,pcolor,opacity).draw_line(zbuffer,x1,y1,z1,x2,y2,z2,pcolor,opacity). draw_line(zbuffer,x2,y2,z2,x3,y3,z3,pcolor,opacity).draw_line(zbuffer,x3,y3,z3,x0,y0,z0,pcolor,opacity); else draw_line(x0,y0,x1,y1,pcolor,opacity).draw_line(x1,y1,x2,y2,pcolor,opacity). draw_line(x2,y2,x3,y3,pcolor,opacity).draw_line(x3,y3,x0,y0,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.drawLine((float)x0,height() - (float)y0,(float)x1,height() - (float)y1); board.drawLine((float)x1,height() - (float)y1,(float)x2,height() - (float)y2); board.drawLine((float)x2,height() - (float)y2,(float)x3,height() - (float)y3); board.drawLine((float)x3,height() - (float)y3,(float)x0,height() - (float)y0); } #endif break; case 2 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,opacity). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,pcolor,opacity); else draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,opacity).draw_triangle(x0,y0,x2,y2,x3,y3,pcolor,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); board.fillTriangle((float)x0,height() - (float)y0, (float)x2,height() - (float)y2, (float)x3,height() - (float)y3); } #endif break; case 3 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,opacity,lightprops(l)). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,pcolor,opacity,lightprops(l)); else _draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,opacity,lightprops(l)). _draw_triangle(x0,y0,x2,y2,x3,y3,pcolor,opacity,lightprops(l)); #ifdef cimg_use_board if (pboard) { const float lp = std::min(lightprops(l),1.f); board.setPenColorRGBi((unsigned char)(color[0]*lp), (unsigned char)(color[1]*lp), (unsigned char)(color[2]*lp),(unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); board.fillTriangle((float)x0,height() - (float)y0, (float)x2,height() - (float)y2, (float)x3,height() - (float)y3); } #endif break; case 4 : { const float lightprop0 = lightprops(n0), lightprop1 = lightprops(n1), lightprop2 = lightprops(n2), lightprop3 = lightprops(n3), lightpropc = (lightprop0 + lightprop1 + lightprop2 + lightprop2)/4; if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,xc,yc,zc,pcolor,lightprop0,lightprop1,lightpropc,opacity). draw_triangle(zbuffer,x1,y1,z1,x2,y2,z2,xc,yc,zc,pcolor,lightprop1,lightprop2,lightpropc,opacity). draw_triangle(zbuffer,x2,y2,z2,x3,y3,z3,xc,yc,zc,pcolor,lightprop2,lightprop3,lightpropc,opacity). draw_triangle(zbuffer,x3,y3,z3,x0,y0,z0,xc,yc,zc,pcolor,lightprop3,lightprop0,lightpropc,opacity); else draw_triangle(x0,y0,x1,y1,xc,yc,pcolor,lightprop0,lightprop1,lightpropc,opacity). draw_triangle(x1,y1,x2,y2,xc,yc,pcolor,lightprop1,lightprop2,lightpropc,opacity). draw_triangle(x2,y2,x3,y3,xc,yc,pcolor,lightprop2,lightprop3,lightpropc,opacity). draw_triangle(x3,y3,x0,y0,xc,yc,pcolor,lightprop3,lightprop0,lightpropc,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi((unsigned char)(color[0]), (unsigned char)(color[1]), (unsigned char)(color[2]), (unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,lightprop0, (float)x1,height() - (float)y1,lightprop1, (float)x2,height() - (float)y2,lightprop2); board.fillGouraudTriangle((float)x0,height() - (float)y0,lightprop0, (float)x2,height() - (float)y2,lightprop2, (float)x3,height() - (float)y3,lightprop3); } #endif } break; case 5 : { const unsigned int lx0 = (unsigned int)cimg::uiround(lightprops(n0,0)), ly0 = (unsigned int)cimg::uiround(lightprops(n0,1)), lx1 = (unsigned int)cimg::uiround(lightprops(n1,0)), ly1 = (unsigned int)cimg::uiround(lightprops(n1,1)), lx2 = (unsigned int)cimg::uiround(lightprops(n2,0)), ly2 = (unsigned int)cimg::uiround(lightprops(n2,1)), lx3 = (unsigned int)cimg::uiround(lightprops(n3,0)), ly3 = (unsigned int)cimg::uiround(lightprops(n3,1)), lxc = (lx0 + lx1 + lx2 + lx3)/4, lyc = (ly0 + ly1 + ly2 + ly3)/4; if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,xc,yc,zc,pcolor,light_texture,lx0,ly0,lx1,ly1,lxc,lyc,opacity). draw_triangle(zbuffer,x1,y1,z1,x2,y2,z2,xc,yc,zc,pcolor,light_texture,lx1,ly1,lx2,ly2,lxc,lyc,opacity). draw_triangle(zbuffer,x2,y2,z2,x3,y3,z3,xc,yc,zc,pcolor,light_texture,lx2,ly2,lx3,ly3,lxc,lyc,opacity). draw_triangle(zbuffer,x3,y3,z3,x0,y0,z0,xc,yc,zc,pcolor,light_texture,lx3,ly3,lx0,ly0,lxc,lyc,opacity); else draw_triangle(x0,y0,x1,y1,xc,yc,pcolor,light_texture,lx0,ly0,lx1,ly1,lxc,lyc,opacity). draw_triangle(x1,y1,x2,y2,xc,yc,pcolor,light_texture,lx1,ly1,lx2,ly2,lxc,lyc,opacity). draw_triangle(x2,y2,x3,y3,xc,yc,pcolor,light_texture,lx2,ly2,lx3,ly3,lxc,lyc,opacity). draw_triangle(x3,y3,x0,y0,xc,yc,pcolor,light_texture,lx3,ly3,lx0,ly0,lxc,lyc,opacity); #ifdef cimg_use_board if (pboard) { const float l0 = light_texture((int)(light_texture.width()/2*(1 + lx0)), (int)(light_texture.height()/2*(1 + ly0))), l1 = light_texture((int)(light_texture.width()/2*(1 + lx1)), (int)(light_texture.height()/2*(1 + ly1))), l2 = light_texture((int)(light_texture.width()/2*(1 + lx2)), (int)(light_texture.height()/2*(1 + ly2))), l3 = light_texture((int)(light_texture.width()/2*(1 + lx3)), (int)(light_texture.height()/2*(1 + ly3))); board.setPenColorRGBi((unsigned char)(color[0]), (unsigned char)(color[1]), (unsigned char)(color[2]), (unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,l0, (float)x1,height() - (float)y1,l1, (float)x2,height() - (float)y2,l2); board.fillGouraudTriangle((float)x0,height() - (float)y0,l0, (float)x2,height() - (float)y2,l2, (float)x3,height() - (float)y3,l3); } #endif } break; } } break; case 9 : { // Textured triangle if (!__color) { if (render_type==5) cimg::mutex(10,0); throw CImgArgumentException(_cimg_instance "draw_object3d(): Undefined texture for triangle primitive [%u].", cimg_instance,n_primitive); } const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1], n2 = (unsigned int)primitive[2]; const int tx0 = (int)primitive[3], ty0 = (int)primitive[4], tx1 = (int)primitive[5], ty1 = (int)primitive[6], tx2 = (int)primitive[7], ty2 = (int)primitive[8], x0 = cimg::uiround(projections(n0,0)), y0 = cimg::uiround(projections(n0,1)), x1 = cimg::uiround(projections(n1,0)), y1 = cimg::uiround(projections(n1,1)), x2 = cimg::uiround(projections(n2,0)), y2 = cimg::uiround(projections(n2,1)); const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale, z2 = vertices(n2,2) + Z + _focale; switch (render_type) { case 0 : draw_point(x0,y0,color.get_vector_at(tx0<=0?0:tx0>=color.width()?color.width() - 1:tx0, ty0<=0?0:ty0>=color.height()?color.height() - 1:ty0)._data,opacity). draw_point(x1,y1,color.get_vector_at(tx1<=0?0:tx1>=color.width()?color.width() - 1:tx1, ty1<=0?0:ty1>=color.height()?color.height() - 1:ty1)._data,opacity). draw_point(x2,y2,color.get_vector_at(tx2<=0?0:tx2>=color.width()?color.width() - 1:tx2, ty2<=0?0:ty2>=color.height()?color.height() - 1:ty2)._data,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.drawDot((float)x0,height() - (float)y0); board.drawDot((float)x1,height() - (float)y1); board.drawDot((float)x2,height() - (float)y2); } #endif break; case 1 : if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,color,tx0,ty0,tx1,ty1,opacity). draw_line(zbuffer,x0,y0,z0,x2,y2,z2,color,tx0,ty0,tx2,ty2,opacity). draw_line(zbuffer,x1,y1,z1,x2,y2,z2,color,tx1,ty1,tx2,ty2,opacity); else draw_line(x0,y0,z0,x1,y1,z1,color,tx0,ty0,tx1,ty1,opacity). draw_line(x0,y0,z0,x2,y2,z2,color,tx0,ty0,tx2,ty2,opacity). draw_line(x1,y1,z1,x2,y2,z2,color,tx1,ty1,tx2,ty2,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.drawLine((float)x0,height() - (float)y0,(float)x1,height() - (float)y1); board.drawLine((float)x0,height() - (float)y0,(float)x2,height() - (float)y2); board.drawLine((float)x1,height() - (float)y1,(float)x2,height() - (float)y2); } #endif break; case 2 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); } #endif break; case 3 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity,lightprops(l)); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity,lightprops(l)); #ifdef cimg_use_board if (pboard) { const float lp = std::min(lightprops(l),1.f); board.setPenColorRGBi((unsigned char)(128*lp), (unsigned char)(128*lp), (unsigned char)(128*lp), (unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); } #endif break; case 4 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2, lightprops(n0),lightprops(n1),lightprops(n2),opacity); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2, lightprops(n0),lightprops(n1),lightprops(n2),opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,lightprops(n0), (float)x1,height() - (float)y1,lightprops(n1), (float)x2,height() - (float)y2,lightprops(n2)); } #endif break; case 5 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,light_texture, (unsigned int)lightprops(n0,0),(unsigned int)lightprops(n0,1), (unsigned int)lightprops(n1,0),(unsigned int)lightprops(n1,1), (unsigned int)lightprops(n2,0),(unsigned int)lightprops(n2,1), opacity); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,light_texture, (unsigned int)lightprops(n0,0),(unsigned int)lightprops(n0,1), (unsigned int)lightprops(n1,0),(unsigned int)lightprops(n1,1), (unsigned int)lightprops(n2,0),(unsigned int)lightprops(n2,1), opacity); #ifdef cimg_use_board if (pboard) { const float l0 = light_texture((int)(light_texture.width()/2*(1 + lightprops(n0,0))), (int)(light_texture.height()/2*(1 + lightprops(n0,1)))), l1 = light_texture((int)(light_texture.width()/2*(1 + lightprops(n1,0))), (int)(light_texture.height()/2*(1 + lightprops(n1,1)))), l2 = light_texture((int)(light_texture.width()/2*(1 + lightprops(n2,0))), (int)(light_texture.height()/2*(1 + lightprops(n2,1)))); board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,l0, (float)x1,height() - (float)y1,l1, (float)x2,height() - (float)y2,l2); } #endif break; } } break; case 12 : { // Textured quadrangle if (!__color) { if (render_type==5) cimg::mutex(10,0); throw CImgArgumentException(_cimg_instance "draw_object3d(): Undefined texture for quadrangle primitive [%u].", cimg_instance,n_primitive); } const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1], n2 = (unsigned int)primitive[2], n3 = (unsigned int)primitive[3]; const int tx0 = (int)primitive[4], ty0 = (int)primitive[5], tx1 = (int)primitive[6], ty1 = (int)primitive[7], tx2 = (int)primitive[8], ty2 = (int)primitive[9], tx3 = (int)primitive[10], ty3 = (int)primitive[11], x0 = cimg::uiround(projections(n0,0)), y0 = cimg::uiround(projections(n0,1)), x1 = cimg::uiround(projections(n1,0)), y1 = cimg::uiround(projections(n1,1)), x2 = cimg::uiround(projections(n2,0)), y2 = cimg::uiround(projections(n2,1)), x3 = cimg::uiround(projections(n3,0)), y3 = cimg::uiround(projections(n3,1)); const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale, z2 = vertices(n2,2) + Z + _focale, z3 = vertices(n3,2) + Z + _focale; switch (render_type) { case 0 : draw_point(x0,y0,color.get_vector_at(tx0<=0?0:tx0>=color.width()?color.width() - 1:tx0, ty0<=0?0:ty0>=color.height()?color.height() - 1:ty0)._data,opacity). draw_point(x1,y1,color.get_vector_at(tx1<=0?0:tx1>=color.width()?color.width() - 1:tx1, ty1<=0?0:ty1>=color.height()?color.height() - 1:ty1)._data,opacity). draw_point(x2,y2,color.get_vector_at(tx2<=0?0:tx2>=color.width()?color.width() - 1:tx2, ty2<=0?0:ty2>=color.height()?color.height() - 1:ty2)._data,opacity). draw_point(x3,y3,color.get_vector_at(tx3<=0?0:tx3>=color.width()?color.width() - 1:tx3, ty3<=0?0:ty3>=color.height()?color.height() - 1:ty3)._data,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.drawDot((float)x0,height() - (float)y0); board.drawDot((float)x1,height() - (float)y1); board.drawDot((float)x2,height() - (float)y2); board.drawDot((float)x3,height() - (float)y3); } #endif break; case 1 : if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,color,tx0,ty0,tx1,ty1,opacity). draw_line(zbuffer,x1,y1,z1,x2,y2,z2,color,tx1,ty1,tx2,ty2,opacity). draw_line(zbuffer,x2,y2,z2,x3,y3,z3,color,tx2,ty2,tx3,ty3,opacity). draw_line(zbuffer,x3,y3,z3,x0,y0,z0,color,tx3,ty3,tx0,ty0,opacity); else draw_line(x0,y0,z0,x1,y1,z1,color,tx0,ty0,tx1,ty1,opacity). draw_line(x1,y1,z1,x2,y2,z2,color,tx1,ty1,tx2,ty2,opacity). draw_line(x2,y2,z2,x3,y3,z3,color,tx2,ty2,tx3,ty3,opacity). draw_line(x3,y3,z3,x0,y0,z0,color,tx3,ty3,tx0,ty0,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.drawLine((float)x0,height() - (float)y0,(float)x1,height() - (float)y1); board.drawLine((float)x1,height() - (float)y1,(float)x2,height() - (float)y2); board.drawLine((float)x2,height() - (float)y2,(float)x3,height() - (float)y3); board.drawLine((float)x3,height() - (float)y3,(float)x0,height() - (float)y0); } #endif break; case 2 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3,opacity); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity). draw_triangle(x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); board.fillTriangle((float)x0,height() - (float)y0, (float)x2,height() - (float)y2, (float)x3,height() - (float)y3); } #endif break; case 3 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity,lightprops(l)). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3,opacity,lightprops(l)); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opacity,lightprops(l)). draw_triangle(x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3,opacity,lightprops(l)); #ifdef cimg_use_board if (pboard) { const float lp = std::min(lightprops(l),1.f); board.setPenColorRGBi((unsigned char)(128*lp), (unsigned char)(128*lp), (unsigned char)(128*lp), (unsigned char)(opacity*255)); board.fillTriangle((float)x0,height() - (float)y0, (float)x1,height() - (float)y1, (float)x2,height() - (float)y2); board.fillTriangle((float)x0,height() - (float)y0, (float)x2,height() - (float)y2, (float)x3,height() - (float)y3); } #endif break; case 4 : { const float lightprop0 = lightprops(n0), lightprop1 = lightprops(n1), lightprop2 = lightprops(n2), lightprop3 = lightprops(n3); if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2, lightprop0,lightprop1,lightprop2,opacity). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3, lightprop0,lightprop2,lightprop3,opacity); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2, lightprop0,lightprop1,lightprop2,opacity). draw_triangle(x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3, lightprop0,lightprop2,lightprop3,opacity); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,lightprop0, (float)x1,height() - (float)y1,lightprop1, (float)x2,height() - (float)y2,lightprop2); board.fillGouraudTriangle((float)x0,height() -(float)y0,lightprop0, (float)x2,height() - (float)y2,lightprop2, (float)x3,height() - (float)y3,lightprop3); } #endif } break; case 5 : { const unsigned int lx0 = (unsigned int)cimg::uiround(lightprops(n0,0)), ly0 = (unsigned int)cimg::uiround(lightprops(n0,1)), lx1 = (unsigned int)cimg::uiround(lightprops(n1,0)), ly1 = (unsigned int)cimg::uiround(lightprops(n1,1)), lx2 = (unsigned int)cimg::uiround(lightprops(n2,0)), ly2 = (unsigned int)cimg::uiround(lightprops(n2,1)), lx3 = (unsigned int)cimg::uiround(lightprops(n3,0)), ly3 = (unsigned int)cimg::uiround(lightprops(n3,1)); if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2, light_texture,lx0,ly0,lx1,ly1,lx2,ly2,opacity). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3, light_texture,lx0,ly0,lx2,ly2,lx3,ly3,opacity); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2, light_texture,lx0,ly0,lx1,ly1,lx2,ly2,opacity). draw_triangle(x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3, light_texture,lx0,ly0,lx2,ly2,lx3,ly3,opacity); #ifdef cimg_use_board if (pboard) { const float l0 = light_texture((int)(light_texture.width()/2*(1 + lx0)), (int)(light_texture.height()/2*(1 + ly0))), l1 = light_texture((int)(light_texture.width()/2*(1 + lx1)), (int)(light_texture.height()/2*(1 + ly1))), l2 = light_texture((int)(light_texture.width()/2*(1 + lx2)), (int)(light_texture.height()/2*(1 + ly2))), l3 = light_texture((int)(light_texture.width()/2*(1 + lx3)), (int)(light_texture.height()/2*(1 + ly3))); board.setPenColorRGBi(128,128,128,(unsigned char)(opacity*255)); board.fillGouraudTriangle((float)x0,height() - (float)y0,l0, (float)x1,height() - (float)y1,l1, (float)x2,height() - (float)y2,l2); board.fillGouraudTriangle((float)x0,height() -(float)y0,l0, (float)x2,height() - (float)y2,l2, (float)x3,height() - (float)y3,l3); } #endif } break; } } break; } } if (render_type==5) cimg::mutex(10,0); return *this; } //@} //--------------------------- // //! \name Data Input //@{ //--------------------------- //! Launch simple interface to select a shape from an image. /** \param disp Display window to use. \param feature_type Type of feature to select. Can be <tt>{ 0=point | 1=line | 2=rectangle | 3=ellipse }</tt>. \param XYZ Pointer to 3 values X,Y,Z which tells about the projection point coordinates, for volumetric images. \param exit_on_anykey Exit function when any key is pressed. **/ CImg<T>& select(CImgDisplay &disp, const unsigned int feature_type=2, unsigned int *const XYZ=0, const bool exit_on_anykey=false, const bool is_deep_selection_default=false) { return get_select(disp,feature_type,XYZ,exit_on_anykey,is_deep_selection_default).move_to(*this); } //! Simple interface to select a shape from an image \overloading. CImg<T>& select(const char *const title, const unsigned int feature_type=2, unsigned int *const XYZ=0, const bool exit_on_anykey=false, const bool is_deep_selection_default=false) { return get_select(title,feature_type,XYZ,exit_on_anykey,is_deep_selection_default).move_to(*this); } //! Simple interface to select a shape from an image \newinstance. CImg<intT> get_select(CImgDisplay &disp, const unsigned int feature_type=2, unsigned int *const XYZ=0, const bool exit_on_anykey=false, const bool is_deep_selection_default=false) const { return _select(disp,0,feature_type,XYZ,0,0,0,exit_on_anykey,true,false,is_deep_selection_default); } //! Simple interface to select a shape from an image \newinstance. CImg<intT> get_select(const char *const title, const unsigned int feature_type=2, unsigned int *const XYZ=0, const bool exit_on_anykey=false, const bool is_deep_selection_default=false) const { CImgDisplay disp; return _select(disp,title,feature_type,XYZ,0,0,0,exit_on_anykey,true,false,is_deep_selection_default); } CImg<intT> _select(CImgDisplay &disp, const char *const title, const unsigned int feature_type, unsigned int *const XYZ, const int origX, const int origY, const int origZ, const bool exit_on_anykey, const bool reset_view3d, const bool force_display_z_coord, const bool is_deep_selection_default) const { if (is_empty()) return CImg<intT>(1,feature_type==0?3:6,1,1,-1); if (!disp) { disp.assign(cimg_fitscreen(_width,_height,_depth),title?title:0,1); if (!title) disp.set_title("CImg<%s> (%ux%ux%ux%u)",pixel_type(),_width,_height,_depth,_spectrum); } else { if (title) disp.set_title("%s",title); disp.move_inside_screen(); } CImg<T> thumb; if (width()>disp.screen_width() || height()>disp.screen_height()) get_resize(cimg_fitscreen(width(),height(),depth()),depth(),-100).move_to(thumb); const unsigned int old_normalization = disp.normalization(); bool old_is_resized = disp.is_resized(); disp._normalization = 0; disp.show().set_key(0).set_wheel().show_mouse(); static const unsigned char foreground_color[] = { 255,255,255 }, background_color[] = { 0,0,0 }; int area = 0, area_started = 0, area_clicked = 0, phase = 0, X0 = (int)((XYZ?XYZ[0]:_width/2)%_width), Y0 = (int)((XYZ?XYZ[1]:_height/2)%_height), Z0 = (int)((XYZ?XYZ[2]:_depth/2)%_depth), X1 =-1, Y1 = -1, Z1 = -1, X3d = -1, Y3d = -1, oX3d = X3d, oY3d = -1, omx = -1, omy = -1; float X = -1, Y = -1, Z = -1; unsigned int key = 0; bool is_deep_selection = is_deep_selection_default, shape_selected = false, text_down = false, visible_cursor = true; static CImg<floatT> pose3d; static bool is_view3d = false, is_axes = true; if (reset_view3d) { pose3d.assign(); is_view3d = false; } CImg<floatT> points3d, opacities3d, sel_opacities3d; CImgList<uintT> primitives3d, sel_primitives3d; CImgList<ucharT> colors3d, sel_colors3d; CImg<ucharT> visu, visu0, view3d; CImg<charT> text(1024); *text = 0; while (!key && !disp.is_closed() && !shape_selected) { // Handle mouse motion and selection int mx = disp.mouse_x(), my = disp.mouse_y(); const float mX = mx<0?-1.f:(float)mx*(width() + (depth()>1?depth():0))/disp.width(), mY = my<0?-1.f:(float)my*(height() + (depth()>1?depth():0))/disp.height(); area = 0; if (mX>=0 && mY>=0 && mX<width() && mY<height()) { area = 1; X = mX; Y = mY; Z = (float)(phase?Z1:Z0); } if (mX>=0 && mX<width() && mY>=height()) { area = 2; X = mX; Z = mY - _height; Y = (float)(phase?Y1:Y0); } if (mY>=0 && mX>=width() && mY<height()) { area = 3; Y = mY; Z = mX - _width; X = (float)(phase?X1:X0); } if (mX>=width() && mY>=height()) area = 4; if (disp.button()) { if (!area_clicked) area_clicked = area; } else area_clicked = 0; CImg<charT> filename(32); switch (key = disp.key()) { #if cimg_OS!=2 case cimg::keyCTRLRIGHT : #endif case 0 : case cimg::keyCTRLLEFT : key = 0; break; case cimg::keyPAGEUP : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_wheel(1); key = 0; } break; case cimg::keyPAGEDOWN : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_wheel(-1); key = 0; } break; case cimg::keyX : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { is_axes = !is_axes; disp.set_key(key,false); key = 0; visu0.assign(); } break; case cimg::keyD : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false). resize(CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,false), CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,true),false). _is_resized = true; disp.set_key(key,false); key = 0; visu0.assign(); } break; case cimg::keyC : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false). resize(cimg_fitscreen(2*disp.width()/3,2*disp.height()/3,1),false)._is_resized = true; disp.set_key(key,false); key = 0; visu0.assign(); } break; case cimg::keyR : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false).resize(cimg_fitscreen(_width,_height,_depth),false)._is_resized = true; disp.set_key(key,false); key = 0; visu0.assign(); } break; case cimg::keyF : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.resize(disp.screen_width(),disp.screen_height(),false).toggle_fullscreen()._is_resized = true; disp.set_key(key,false); key = 0; visu0.assign(); } break; case cimg::keyV : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { is_view3d = !is_view3d; disp.set_key(key,false); key = 0; visu0.assign(); } break; case cimg::keyS : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { static unsigned int snap_number = 0; std::FILE *file; do { cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.bmp",snap_number++); if ((file=cimg::std_fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); if (visu0) { (+visu0).__draw_text(" Saving snapshot...",(int)text_down).display(disp); visu0.save(filename); (+visu0).__draw_text(" Snapshot '%s' saved. ",(int)text_down,filename._data).display(disp); } disp.set_key(key,false); key = 0; } break; case cimg::keyO : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { static unsigned int snap_number = 0; std::FILE *file; do { #ifdef cimg_use_zlib cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.cimgz",snap_number++); #else cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.cimg",snap_number++); #endif if ((file=cimg::std_fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); (+visu0).__draw_text(" Saving instance... ",(int)text_down).display(disp); save(filename); (+visu0).__draw_text(" Instance '%s' saved. ",(int)text_down,filename._data).display(disp); disp.set_key(key,false); key = 0; } break; } switch (area) { case 0 : // When mouse is out of image range mx = my = -1; X = Y = Z = -1; break; case 1 : case 2 : case 3 : { // When mouse is over the XY,XZ or YZ projections const unsigned int but = disp.button(); const bool b1 = (bool)(but&1), b2 = (bool)(but&2), b3 = (bool)(but&4); if (b1 && phase==1 && area_clicked==area) { // When selection has been started (1st step) if (_depth>1 && (X1!=(int)X || Y1!=(int)Y || Z1!=(int)Z)) visu0.assign(); X1 = (int)X; Y1 = (int)Y; Z1 = (int)Z; } if (!b1 && phase==2 && area_clicked!=area) { // When selection is at 2nd step (for volumes) switch (area_started) { case 1 : if (Z1!=(int)Z) visu0.assign(); Z1 = (int)Z; break; case 2 : if (Y1!=(int)Y) visu0.assign(); Y1 = (int)Y; break; case 3 : if (X1!=(int)X) visu0.assign(); X1 = (int)X; break; } } if (b2 && area_clicked==area) { // When moving through the image/volume if (phase) { if (_depth>1 && (X1!=(int)X || Y1!=(int)Y || Z1!=(int)Z)) visu0.assign(); X1 = (int)X; Y1 = (int)Y; Z1 = (int)Z; } else { if (_depth>1 && (X0!=(int)X || Y0!=(int)Y || Z0!=(int)Z)) visu0.assign(); X0 = (int)X; Y0 = (int)Y; Z0 = (int)Z; } } if (b3) { // Reset selection X = (float)X0; Y = (float)Y0; Z = (float)Z0; phase = area = area_clicked = area_started = 0; visu0.assign(); } if (disp.wheel()) { // When moving through the slices of the volume (with mouse wheel) if (_depth>1 && !disp.is_keyCTRLLEFT() && !disp.is_keyCTRLRIGHT() && !disp.is_keySHIFTLEFT() && !disp.is_keySHIFTRIGHT()) { switch (area) { case 1 : if (phase) Z = (float)(Z1+=disp.wheel()); else Z = (float)(Z0+=disp.wheel()); visu0.assign(); break; case 2 : if (phase) Y = (float)(Y1+=disp.wheel()); else Y = (float)(Y0+=disp.wheel()); visu0.assign(); break; case 3 : if (phase) X = (float)(X1+=disp.wheel()); else X = (float)(X0+=disp.wheel()); visu0.assign(); break; } disp.set_wheel(); } else key = ~0U; } if ((phase==0 && b1) || (phase==1 && !b1) || (phase==2 && b1)) switch (phase) { // Detect change of phase case 0 : if (area==area_clicked) { X0 = X1 = (int)X; Y0 = Y1 = (int)Y; Z0 = Z1 = (int)Z; area_started = area; ++phase; } break; case 1 : if (area==area_started) { X1 = (int)X; Y1 = (int)Y; Z1 = (int)Z; ++phase; if (_depth>1) { if (disp.is_keyCTRLLEFT()) is_deep_selection = !is_deep_selection_default; if (is_deep_selection) ++phase; } } else if (!b1) { X = (float)X0; Y = (float)Y0; Z = (float)Z0; phase = 0; visu0.assign(); } break; case 2 : ++phase; break; } } break; case 4 : // When mouse is over the 3D view if (is_view3d && points3d) { X3d = mx - width()*disp.width()/(width() + (depth()>1?depth():0)); Y3d = my - height()*disp.height()/(height() + (depth()>1?depth():0)); if (oX3d<0) { oX3d = X3d; oY3d = Y3d; } // Left + right buttons: reset. if ((disp.button()&3)==3) { pose3d.assign(); view3d.assign(); oX3d = oY3d = X3d = Y3d = -1; } else if (disp.button()&1 && pose3d && (oX3d!=X3d || oY3d!=Y3d)) { // Left button: rotate const float R = 0.45f*std::min(view3d._width,view3d._height), R2 = R*R, u0 = (float)(oX3d - view3d.width()/2), v0 = (float)(oY3d - view3d.height()/2), u1 = (float)(X3d - view3d.width()/2), v1 = (float)(Y3d - view3d.height()/2), n0 = cimg::hypot(u0,v0), n1 = cimg::hypot(u1,v1), nu0 = n0>R?(u0*R/n0):u0, nv0 = n0>R?(v0*R/n0):v0, nw0 = (float)std::sqrt(std::max(0.f,R2 - nu0*nu0 - nv0*nv0)), nu1 = n1>R?(u1*R/n1):u1, nv1 = n1>R?(v1*R/n1):v1, nw1 = (float)std::sqrt(std::max(0.f,R2 - nu1*nu1 - nv1*nv1)), u = nv0*nw1 - nw0*nv1, v = nw0*nu1 - nu0*nw1, w = nv0*nu1 - nu0*nv1, n = cimg::hypot(u,v,w), alpha = (float)std::asin(n/R2)*180/cimg::PI; pose3d.draw_image(CImg<floatT>::rotation_matrix(u,v,w,-alpha)*pose3d.get_crop(0,0,2,2)); view3d.assign(); } else if (disp.button()&2 && pose3d && oY3d!=Y3d) { // Right button: zoom pose3d(3,2)+=(Y3d - oY3d)*1.5f; view3d.assign(); } if (disp.wheel()) { // Wheel: zoom pose3d(3,2)-=disp.wheel()*15; view3d.assign(); disp.set_wheel(); } if (disp.button()&4 && pose3d && (oX3d!=X3d || oY3d!=Y3d)) { // Middle button: shift pose3d(3,0)-=oX3d - X3d; pose3d(3,1)-=oY3d - Y3d; view3d.assign(); } oX3d = X3d; oY3d = Y3d; } mx = my = -1; X = Y = Z = -1; break; } if (phase) { if (!feature_type) shape_selected = phase?true:false; else { if (_depth>1) shape_selected = (phase==3)?true:false; else shape_selected = (phase==2)?true:false; } } if (X0<0) X0 = 0; if (X0>=width()) X0 = width() - 1; if (Y0<0) Y0 = 0; if (Y0>=height()) Y0 = height() - 1; if (Z0<0) Z0 = 0; if (Z0>=depth()) Z0 = depth() - 1; if (X1<1) X1 = 0; if (X1>=width()) X1 = width() - 1; if (Y1<0) Y1 = 0; if (Y1>=height()) Y1 = height() - 1; if (Z1<0) Z1 = 0; if (Z1>=depth()) Z1 = depth() - 1; // Draw visualization image on the display if (mx!=omx || my!=omy || !visu0 || (_depth>1 && !view3d)) { if (!visu0) { // Create image of projected planes if (thumb) thumb._get_select(disp,old_normalization,phase?X1:X0,phase?Y1:Y0,phase?Z1:Z0).move_to(visu0); else _get_select(disp,old_normalization,phase?X1:X0,phase?Y1:Y0,phase?Z1:Z0).move_to(visu0); visu0.resize(disp); view3d.assign(); points3d.assign(); } if (is_view3d && _depth>1 && !view3d) { // Create 3D view for volumetric images const unsigned int _x3d = (unsigned int)cimg::round((float)_width*visu0._width/(_width + _depth),1,1), _y3d = (unsigned int)cimg::round((float)_height*visu0._height/(_height + _depth),1,1), x3d = _x3d>=visu0._width?visu0._width - 1:_x3d, y3d = _y3d>=visu0._height?visu0._height - 1:_y3d; CImg<ucharT>(1,2,1,1,64,128).resize(visu0._width - x3d,visu0._height - y3d,1,visu0._spectrum,3). move_to(view3d); if (!points3d) { get_projections3d(primitives3d,colors3d,phase?X1:X0,phase?Y1:Y0,phase?Z1:Z0,true).move_to(points3d); points3d.append(CImg<floatT>(8,3,1,1, 0,_width - 1,_width - 1,0,0,_width - 1,_width - 1,0, 0,0,_height - 1,_height - 1,0,0,_height - 1,_height - 1, 0,0,0,0,_depth - 1,_depth - 1,_depth - 1,_depth - 1),'x'); CImg<uintT>::vector(12,13).move_to(primitives3d); CImg<uintT>::vector(13,14).move_to(primitives3d); CImg<uintT>::vector(14,15).move_to(primitives3d); CImg<uintT>::vector(15,12).move_to(primitives3d); CImg<uintT>::vector(16,17).move_to(primitives3d); CImg<uintT>::vector(17,18).move_to(primitives3d); CImg<uintT>::vector(18,19).move_to(primitives3d); CImg<uintT>::vector(19,16).move_to(primitives3d); CImg<uintT>::vector(12,16).move_to(primitives3d); CImg<uintT>::vector(13,17).move_to(primitives3d); CImg<uintT>::vector(14,18).move_to(primitives3d); CImg<uintT>::vector(15,19).move_to(primitives3d); colors3d.insert(12,CImg<ucharT>::vector(255,255,255)); opacities3d.assign(primitives3d.width(),1,1,1,0.5f); if (!phase) { opacities3d[0] = opacities3d[1] = opacities3d[2] = 0.8f; sel_primitives3d.assign(); sel_colors3d.assign(); sel_opacities3d.assign(); } else { if (feature_type==2) { points3d.append(CImg<floatT>(8,3,1,1, X0,X1,X1,X0,X0,X1,X1,X0, Y0,Y0,Y1,Y1,Y0,Y0,Y1,Y1, Z0,Z0,Z0,Z0,Z1,Z1,Z1,Z1),'x'); sel_primitives3d.assign(); CImg<uintT>::vector(20,21).move_to(sel_primitives3d); CImg<uintT>::vector(21,22).move_to(sel_primitives3d); CImg<uintT>::vector(22,23).move_to(sel_primitives3d); CImg<uintT>::vector(23,20).move_to(sel_primitives3d); CImg<uintT>::vector(24,25).move_to(sel_primitives3d); CImg<uintT>::vector(25,26).move_to(sel_primitives3d); CImg<uintT>::vector(26,27).move_to(sel_primitives3d); CImg<uintT>::vector(27,24).move_to(sel_primitives3d); CImg<uintT>::vector(20,24).move_to(sel_primitives3d); CImg<uintT>::vector(21,25).move_to(sel_primitives3d); CImg<uintT>::vector(22,26).move_to(sel_primitives3d); CImg<uintT>::vector(23,27).move_to(sel_primitives3d); } else { points3d.append(CImg<floatT>(2,3,1,1, X0,X1, Y0,Y1, Z0,Z1),'x'); sel_primitives3d.assign(CImg<uintT>::vector(20,21)); } sel_colors3d.assign(sel_primitives3d._width,CImg<ucharT>::vector(255,255,255)); sel_opacities3d.assign(sel_primitives3d._width,1,1,1,0.8f); } points3d.shift_object3d(-0.5f*(_width - 1),-0.5f*(_height - 1),-0.5f*(_depth - 1)).resize_object3d(); points3d*=0.75f*std::min(view3d._width,view3d._height); } if (!pose3d) CImg<floatT>(4,3,1,1, 1,0,0,0, 0,1,0,0, 0,0,1,0).move_to(pose3d); CImg<floatT> zbuffer3d(view3d._width,view3d._height,1,1,0); const CImg<floatT> rotated_points3d = pose3d.get_crop(0,0,2,2)*points3d; if (sel_primitives3d) view3d.draw_object3d(pose3d(3,0) + 0.5f*view3d._width, pose3d(3,1) + 0.5f*view3d._height, pose3d(3,2), rotated_points3d,sel_primitives3d,sel_colors3d,sel_opacities3d, 2,true,500,0,0,0,0,0,1,zbuffer3d); view3d.draw_object3d(pose3d(3,0) + 0.5f*view3d._width, pose3d(3,1) + 0.5f*view3d._height, pose3d(3,2), rotated_points3d,primitives3d,colors3d,opacities3d, 2,true,500,0,0,0,0,0,1,zbuffer3d); visu0.draw_image(x3d,y3d,view3d); } visu = visu0; if (X<0 || Y<0 || Z<0) { if (!visible_cursor) { disp.show_mouse(); visible_cursor = true; }} else { if (is_axes) { if (visible_cursor) { disp.hide_mouse(); visible_cursor = false; }} else { if (!visible_cursor) { disp.show_mouse(); visible_cursor = true; }} const int d = (depth()>1)?depth():0; int _vX = (int)X, _vY = (int)Y, _vZ = (int)Z; if (phase>=2) { _vX = X1; _vY = Y1; _vZ = Z1; } int w = disp.width(), W = width() + d, h = disp.height(), H = height() + d, _xp = (int)(_vX*(float)w/W), xp = _xp + ((int)(_xp*(float)W/w)!=_vX), _yp = (int)(_vY*(float)h/H), yp = _yp + ((int)(_yp*(float)H/h)!=_vY), _xn = (int)((_vX + 1.f)*w/W - 1), xn = _xn + ((int)((_xn + 1.f)*W/w)!=_vX + 1), _yn = (int)((_vY + 1.f)*h/H - 1), yn = _yn + ((int)((_yn + 1.f)*H/h)!=_vY + 1), _zxp = (int)((_vZ + width())*(float)w/W), zxp = _zxp + ((int)(_zxp*(float)W/w)!=_vZ + width()), _zyp = (int)((_vZ + height())*(float)h/H), zyp = _zyp + ((int)(_zyp*(float)H/h)!=_vZ + height()), _zxn = (int)((_vZ + width() + 1.f)*w/W - 1), zxn = _zxn + ((int)((_zxn + 1.f)*W/w)!=_vZ + width() + 1), _zyn = (int)((_vZ + height() + 1.f)*h/H - 1), zyn = _zyn + ((int)((_zyn + 1.f)*H/h)!=_vZ + height() + 1), _xM = (int)(width()*(float)w/W - 1), xM = _xM + ((int)((_xM + 1.f)*W/w)!=width()), _yM = (int)(height()*(float)h/H - 1), yM = _yM + ((int)((_yM + 1.f)*H/h)!=height()), xc = (xp + xn)/2, yc = (yp + yn)/2, zxc = (zxp + zxn)/2, zyc = (zyp + zyn)/2, xf = (int)(X*w/W), yf = (int)(Y*h/H), zxf = (int)((Z + width())*w/W), zyf = (int)((Z + height())*h/H); if (is_axes) { // Draw axes visu.draw_line(0,yf,visu.width() - 1,yf,foreground_color,0.7f,0xFF00FF00). draw_line(0,yf,visu.width() - 1,yf,background_color,0.7f,0x00FF00FF). draw_line(xf,0,xf,visu.height() - 1,foreground_color,0.7f,0xFF00FF00). draw_line(xf,0,xf,visu.height() - 1,background_color,0.7f,0x00FF00FF); if (_depth>1) visu.draw_line(zxf,0,zxf,yM,foreground_color,0.7f,0xFF00FF00). draw_line(zxf,0,zxf,yM,background_color,0.7f,0x00FF00FF). draw_line(0,zyf,xM,zyf,foreground_color,0.7f,0xFF00FF00). draw_line(0,zyf,xM,zyf,background_color,0.7f,0x00FF00FF); } // Draw box cursor. if (xn - xp>=4 && yn - yp>=4) visu.draw_rectangle(xp,yp,xn,yn,foreground_color,0.2f). draw_rectangle(xp,yp,xn,yn,foreground_color,1,0xAAAAAAAA). draw_rectangle(xp,yp,xn,yn,background_color,1,0x55555555); if (_depth>1) { if (yn - yp>=4 && zxn - zxp>=4) visu.draw_rectangle(zxp,yp,zxn,yn,background_color,0.2f). draw_rectangle(zxp,yp,zxn,yn,foreground_color,1,0xAAAAAAAA). draw_rectangle(zxp,yp,zxn,yn,background_color,1,0x55555555); if (xn - xp>=4 && zyn - zyp>=4) visu.draw_rectangle(xp,zyp,xn,zyn,background_color,0.2f). draw_rectangle(xp,zyp,xn,zyn,foreground_color,1,0xAAAAAAAA). draw_rectangle(xp,zyp,xn,zyn,background_color,1,0x55555555); } // Draw selection. if (phase && (phase!=1 || area_started==area)) { const int _xp0 = (int)(X0*(float)w/W), xp0 = _xp0 + ((int)(_xp0*(float)W/w)!=X0), _yp0 = (int)(Y0*(float)h/H), yp0 = _yp0 + ((int)(_yp0*(float)H/h)!=Y0), _xn0 = (int)((X0 + 1.f)*w/W - 1), xn0 = _xn0 + ((int)((_xn0 + 1.f)*W/w)!=X0 + 1), _yn0 = (int)((Y0 + 1.f)*h/H - 1), yn0 = _yn0 + ((int)((_yn0 + 1.f)*H/h)!=Y0 + 1), _zxp0 = (int)((Z0 + width())*(float)w/W), zxp0 = _zxp0 + ((int)(_zxp0*(float)W/w)!=Z0 + width()), _zyp0 = (int)((Z0 + height())*(float)h/H), zyp0 = _zyp0 + ((int)(_zyp0*(float)H/h)!=Z0 + height()), _zxn0 = (int)((Z0 + width() + 1.f)*w/W - 1), zxn0 = _zxn0 + ((int)((_zxn0 + 1.f)*W/w)!=Z0 + width() + 1), _zyn0 = (int)((Z0 + height() + 1.f)*h/H - 1), zyn0 = _zyn0 + ((int)((_zyn0 + 1.f)*H/h)!=Z0 + height() + 1), xc0 = (xp0 + xn0)/2, yc0 = (yp0 + yn0)/2, zxc0 = (zxp0 + zxn0)/2, zyc0 = (zyp0 + zyn0)/2; switch (feature_type) { case 1 : { // Vector visu.draw_arrow(xc0,yc0,xc,yc,background_color,0.9f,30,5,0x33333333). draw_arrow(xc0,yc0,xc,yc,foreground_color,0.9f,30,5,0xCCCCCCCC); if (d) { visu.draw_arrow(zxc0,yc0,zxc,yc,background_color,0.9f,30,5,0x33333333). draw_arrow(zxc0,yc0,zxc,yc,foreground_color,0.9f,30,5,0xCCCCCCCC). draw_arrow(xc0,zyc0,xc,zyc,background_color,0.9f,30,5,0x33333333). draw_arrow(xc0,zyc0,xc,zyc,foreground_color,0.9f,30,5,0xCCCCCCCC); } } break; case 2 : { // Box visu.draw_rectangle(X0<X1?xp0:xp,Y0<Y1?yp0:yp,X0<X1?xn:xn0,Y0<Y1?yn:yn0,background_color,0.2f). draw_rectangle(X0<X1?xp0:xp,Y0<Y1?yp0:yp,X0<X1?xn:xn0,Y0<Y1?yn:yn0,background_color,0.9f,0x55555555). draw_rectangle(X0<X1?xp0:xp,Y0<Y1?yp0:yp,X0<X1?xn:xn0,Y0<Y1?yn:yn0,foreground_color,0.9f,0xAAAAAAAA); if (xc0!=xc && yc0!=yc) visu.draw_line(xc0,yc0,xc,yc,background_color,0.9f,0x33333333). draw_line(xc0,yc0,xc,yc,foreground_color,0.9f,0xCCCCCCCC); if (d) { visu.draw_rectangle(Z0<Z1?zxp0:zxp,Y0<Y1?yp0:yp,Z0<Z1?zxn:zxn0,Y0<Y1?yn:yn0,background_color,0.2f). draw_rectangle(Z0<Z1?zxp0:zxp,Y0<Y1?yp0:yp,Z0<Z1?zxn:zxn0,Y0<Y1?yn:yn0, background_color,0.9f,0x55555555). draw_rectangle(Z0<Z1?zxp0:zxp,Y0<Y1?yp0:yp,Z0<Z1?zxn:zxn0,Y0<Y1?yn:yn0, foreground_color,0.9f,0xAAAAAAAA); if (zxc0!=zxc && yc0!=yc) visu.draw_line(zxc0,yc0,zxc,yc,background_color,0.9f,0x33333333). draw_line(zxc0,yc0,zxc,yc,foreground_color,0.9f,0xCCCCCCCC); visu.draw_rectangle(X0<X1?xp0:xp,Z0<Z1?zyp0:zyp,X0<X1?xn:xn0,Z0<Z1?zyn:zyn0, background_color,0.2f). draw_rectangle(X0<X1?xp0:xp,Z0<Z1?zyp0:zyp,X0<X1?xn:xn0,Z0<Z1?zyn:zyn0, background_color,0.9f,0x55555555). draw_rectangle(X0<X1?xp0:xp,Z0<Z1?zyp0:zyp,X0<X1?xn:xn0,Z0<Z1?zyn:zyn0, foreground_color,0.9f,0xAAAAAAAA); if (xp0!=xn && zyp0!=zyn) visu.draw_line(xp0,zyp0,xn,zyn,background_color,0.9f,0x33333333). draw_line(xp0,zyp0,xn,zyn,foreground_color,0.9f,0xCCCCCCCC); } } break; case 3 : { // Ellipse visu.draw_ellipse(xc0,yc0, (float)cimg::abs(xc - xc0), (float)cimg::abs(yc - yc0),0,background_color,0.2f). draw_ellipse(xc0,yc0, (float)cimg::abs(xc - xc0), (float)cimg::abs(yc - yc0),0,foreground_color,0.9f,~0U). draw_point(xc0,yc0,foreground_color,0.9f); if (d) { visu.draw_ellipse(zxc0,yc0,(float)cimg::abs(zxc - zxc0),(float)cimg::abs(yc - yc0),0, background_color,0.2f). draw_ellipse(zxc0,yc0,(float)cimg::abs(zxc - zxc0),(float)cimg::abs(yc - yc0),0, foreground_color,0.9f,~0U). draw_point(zxc0,yc0,foreground_color,0.9f). draw_ellipse(xc0,zyc0,(float)cimg::abs(xc - xc0),(float)cimg::abs(zyc - zyc0),0, background_color,0.2f). draw_ellipse(xc0,zyc0,(float)cimg::abs(xc - xc0),(float)cimg::abs(zyc - zyc0),0, foreground_color,0.9f,~0U). draw_point(xc0,zyc0,foreground_color,0.9f); } } break; } } // Draw text info. if (my>=0 && my<13) text_down = true; else if (my>=visu.height() - 13) text_down = false; if (!feature_type || !phase) { if (X>=0 && Y>=0 && Z>=0 && X<width() && Y<height() && Z<depth()) { if (_depth>1 || force_display_z_coord) cimg_snprintf(text,text._width," Point (%d,%d,%d) = [ ",origX + (int)X,origY + (int)Y,origZ + (int)Z); else cimg_snprintf(text,text._width," Point (%d,%d) = [ ",origX + (int)X,origY + (int)Y); CImg<T> values = get_vector_at((int)X,(int)Y,(int)Z); const bool is_large_spectrum = values._height>8; if (is_large_spectrum) values.draw_image(0,4,values.get_rows(values._height - 4,values._height - 1)).resize(1,8,1,1,0); char *ctext = text._data + std::strlen(text), *const ltext = text._data + 512; for (unsigned int c = 0; c<values._height && ctext<ltext; ++c) { cimg_snprintf(ctext,24,cimg::type<T>::format_s(), cimg::type<T>::format(values[c])); ctext += std::strlen(ctext); if (c==3 && is_large_spectrum) { cimg_snprintf(ctext,24," ..."); ctext += std::strlen(ctext); } *(ctext++) = ' '; *ctext = 0; } std::strcpy(text._data + std::strlen(text),"] "); } } else switch (feature_type) { case 1 : { const double dX = (double)(X0 - X1), dY = (double)(Y0 - Y1), dZ = (double)(Z0 - Z1), length = cimg::round(cimg::hypot(dX,dY,dZ),0.1); if (_depth>1 || force_display_z_coord) cimg_snprintf(text,text._width," Vect (%d,%d,%d)-(%d,%d,%d), Length = %g ", origX + X0,origY + Y0,origZ + Z0,origX + X1,origY + Y1,origZ + Z1,length); else if (_width!=1 && _height!=1) cimg_snprintf(text,text._width," Vect (%d,%d)-(%d,%d), Length = %g, Angle = %g\260 ", origX + X0,origY + Y0,origX + X1,origY + Y1,length, cimg::round(cimg::mod(180*std::atan2(-dY,-dX)/cimg::PI,360.),0.1)); else cimg_snprintf(text,text._width," Vect (%d,%d)-(%d,%d), Length = %g ", origX + X0,origY + Y0,origX + X1,origY + Y1,length); } break; case 2 : { const double dX = (double)(X0 - X1), dY = (double)(Y0 - Y1), dZ = (double)(Z0 - Z1), length = cimg::round(cimg::hypot(dX,dY,dZ),0.1); if (_depth>1 || force_display_z_coord) cimg_snprintf(text,text._width, " Box ( %d,%d,%d ) - ( %d,%d,%d )\n Size = ( %d,%d,%d ), Length = %g ", origX + (X0<X1?X0:X1),origY + (Y0<Y1?Y0:Y1),origZ + (Z0<Z1?Z0:Z1), origX + (X0<X1?X1:X0),origY + (Y0<Y1?Y1:Y0),origZ + (Z0<Z1?Z1:Z0), 1 + cimg::abs(X0 - X1),1 + cimg::abs(Y0 - Y1),1 + cimg::abs(Z0 - Z1),length); else if (_width!=1 && _height!=1) cimg_snprintf(text,text._width, " Box ( %d,%d ) - ( %d,%d )\n Size = ( %d,%d ), Length = %g \n Angle = %g\260 ", origX + (X0<X1?X0:X1),origY + (Y0<Y1?Y0:Y1), origX + (X0<X1?X1:X0),origY + (Y0<Y1?Y1:Y0), 1 + cimg::abs(X0 - X1),1 + cimg::abs(Y0 - Y1),length, cimg::round(cimg::mod(180*std::atan2(-dY,-dX)/cimg::PI,360.),0.1)); else cimg_snprintf(text,text._width, " Box ( %d,%d ) - ( %d,%d )\n Size = (%d,%d), Length = %g ", origX + (X0<X1?X0:X1),origY + (Y0<Y1?Y0:Y1), origX + (X0<X1?X1:X0),origY + (Y0<Y1?Y1:Y0), 1 + cimg::abs(X0 - X1),1 + cimg::abs(Y0 - Y1),length); } break; default : if (_depth>1 || force_display_z_coord) cimg_snprintf(text,text._width," Ellipse ( %d,%d,%d ) - ( %d,%d,%d ), Radii = ( %d,%d,%d ) ", origX + X0,origY + Y0,origZ + Z0,origX + X1,origY + Y1,origZ + Z1, 1 + cimg::abs(X0 - X1),1 + cimg::abs(Y0 - Y1),1 + cimg::abs(Z0 - Z1)); else cimg_snprintf(text,text._width," Ellipse ( %d,%d ) - ( %d,%d ), Radii = ( %d,%d ) ", origX + X0,origY + Y0,origX + X1,origY + Y1, 1 + cimg::abs(X0 - X1),1 + cimg::abs(Y0 - Y1)); } if (phase || (mx>=0 && my>=0)) visu.__draw_text("%s",(int)text_down,text._data); } disp.display(visu); } if (!shape_selected) disp.wait(); if (disp.is_resized()) { disp.resize(false)._is_resized = false; old_is_resized = true; visu0.assign(); } omx = mx; omy = my; if (!exit_on_anykey && key && key!=cimg::keyESC && (key!=cimg::keyW || (!disp.is_keyCTRLLEFT() && !disp.is_keyCTRLRIGHT()))) { key = 0; } } // Return result. CImg<intT> res(1,feature_type==0?3:6,1,1,-1); if (XYZ) { XYZ[0] = (unsigned int)X0; XYZ[1] = (unsigned int)Y0; XYZ[2] = (unsigned int)Z0; } if (shape_selected) { if (feature_type==2) { if (is_deep_selection) switch (area_started) { case 1 : Z0 = 0; Z1 = _depth - 1; break; case 2 : Y0 = 0; Y1 = _height - 1; break; case 3 : X0 = 0; X1 = _width - 1; break; } if (X0>X1) cimg::swap(X0,X1); if (Y0>Y1) cimg::swap(Y0,Y1); if (Z0>Z1) cimg::swap(Z0,Z1); } if (X1<0 || Y1<0 || Z1<0) X0 = Y0 = Z0 = X1 = Y1 = Z1 = -1; switch (feature_type) { case 1 : case 2 : res[0] = X0; res[1] = Y0; res[2] = Z0; res[3] = X1; res[4] = Y1; res[5] = Z1; break; case 3 : res[3] = cimg::abs(X1 - X0); res[4] = cimg::abs(Y1 - Y0); res[5] = cimg::abs(Z1 - Z0); res[0] = X0; res[1] = Y0; res[2] = Z0; break; default : res[0] = X0; res[1] = Y0; res[2] = Z0; } } if (!exit_on_anykey || !(disp.button()&4)) disp.set_button(); if (!visible_cursor) disp.show_mouse(); disp._normalization = old_normalization; disp._is_resized = old_is_resized; if (key!=~0U) disp.set_key(key); return res; } // Return a visualizable uchar8 image for display routines. CImg<ucharT> _get_select(const CImgDisplay& disp, const int normalization, const int x, const int y, const int z) const { if (is_empty()) return CImg<ucharT>(1,1,1,1,0); const CImg<T> crop = get_shared_channels(0,std::min(2,spectrum() - 1)); CImg<Tuchar> img2d; if (_depth>1) { const int mdisp = std::min(disp.screen_width(),disp.screen_height()); if (depth()>mdisp) { crop.get_resize(-100,-100,mdisp,-100,0).move_to(img2d); img2d.projections2d(x,y,z*img2d._depth/_depth); } else crop.get_projections2d(x,y,z).move_to(img2d); } else CImg<Tuchar>(crop,false).move_to(img2d); // Check for inf and NaN values. if (cimg::type<T>::is_float() && normalization) { bool is_inf = false, is_nan = false; cimg_for(img2d,ptr,Tuchar) if (cimg::type<T>::is_inf(*ptr)) { is_inf = true; break; } else if (cimg::type<T>::is_nan(*ptr)) { is_nan = true; break; } if (is_inf || is_nan) { Tint m0 = (Tint)cimg::type<T>::max(), M0 = (Tint)cimg::type<T>::min(); if (!normalization) { m0 = 0; M0 = 255; } else if (normalization==2) { m0 = (Tint)disp._min; M0 = (Tint)disp._max; } else cimg_for(img2d,ptr,Tuchar) if (!cimg::type<T>::is_inf(*ptr) && !cimg::type<T>::is_nan(*ptr)) { if (*ptr<(Tuchar)m0) m0 = *ptr; if (*ptr>(Tuchar)M0) M0 = *ptr; } const T val_minf = (T)(normalization==1 || normalization==3?m0 - (M0 - m0)*20 - 1:m0), val_pinf = (T)(normalization==1 || normalization==3?M0 + (M0 - m0)*20 + 1:M0); if (is_nan) cimg_for(img2d,ptr,Tuchar) if (cimg::type<T>::is_nan(*ptr)) *ptr = val_minf; // Replace NaN values if (is_inf) cimg_for(img2d,ptr,Tuchar) if (cimg::type<T>::is_inf(*ptr)) *ptr = (float)*ptr<0?val_minf:val_pinf; // Replace +-inf values } } switch (normalization) { case 1 : img2d.normalize((ucharT)0,(ucharT)255); break; case 2 : { const float m = disp._min, M = disp._max; (img2d-=m)*=255.f/(M - m>0?M - m:1); } break; case 3 : if (cimg::type<T>::is_float()) img2d.normalize((ucharT)0,(ucharT)255); else { const float m = (float)cimg::type<T>::min(), M = (float)cimg::type<T>::max(); (img2d-=m)*=255.f/(M - m>0?M - m:1); } break; } if (img2d.spectrum()==2) img2d.channels(0,2); return img2d; } //! Select sub-graph in a graph. CImg<intT> get_select_graph(CImgDisplay &disp, const unsigned int plot_type=1, const unsigned int vertex_type=1, const char *const labelx=0, const double xmin=0, const double xmax=0, const char *const labely=0, const double ymin=0, const double ymax=0, const bool exit_on_anykey=false) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "select_graph(): Empty instance.", cimg_instance); if (!disp) disp.assign(cimg_fitscreen(CImgDisplay::screen_width()/2,CImgDisplay::screen_height()/2,1),0,0). set_title("CImg<%s>",pixel_type()); const ulongT siz = (ulongT)_width*_height*_depth; const unsigned int old_normalization = disp.normalization(); disp.show().set_button().set_wheel()._normalization = 0; double nymin = ymin, nymax = ymax, nxmin = xmin, nxmax = xmax; if (nymin==nymax) { nymin = (Tfloat)min_max(nymax); const double dy = nymax - nymin; nymin-=dy/20; nymax+=dy/20; } if (nymin==nymax) { --nymin; ++nymax; } if (nxmin==nxmax && nxmin==0) { nxmin = 0; nxmax = siz - 1.; } static const unsigned char black[] = { 0, 0, 0 }, white[] = { 255, 255, 255 }, gray[] = { 220, 220, 220 }; static const unsigned char gray2[] = { 110, 110, 110 }, ngray[] = { 35, 35, 35 }; CImg<ucharT> colormap(3,_spectrum); if (_spectrum==1) { colormap[0] = colormap[1] = 120; colormap[2] = 200; } else { colormap(0,0) = 220; colormap(1,0) = 10; colormap(2,0) = 10; if (_spectrum>1) { colormap(0,1) = 10; colormap(1,1) = 220; colormap(2,1) = 10; } if (_spectrum>2) { colormap(0,2) = 10; colormap(1,2) = 10; colormap(2,2) = 220; } if (_spectrum>3) { colormap(0,3) = 220; colormap(1,3) = 220; colormap(2,3) = 10; } if (_spectrum>4) { colormap(0,4) = 220; colormap(1,4) = 10; colormap(2,4) = 220; } if (_spectrum>5) { colormap(0,5) = 10; colormap(1,5) = 220; colormap(2,5) = 220; } if (_spectrum>6) { ulongT rng = 10; cimg_for_inY(colormap,6,colormap.height()-1,k) { colormap(0,k) = (unsigned char)(120 + cimg::rand(-100.f,100.f,&rng)); colormap(1,k) = (unsigned char)(120 + cimg::rand(-100.f,100.f,&rng)); colormap(2,k) = (unsigned char)(120 + cimg::rand(-100.f,100.f,&rng)); } } } CImg<ucharT> visu0, visu, graph, text, axes; int x0 = -1, x1 = -1, y0 = -1, y1 = -1, omouse_x = -2, omouse_y = -2; const unsigned int one = plot_type==3?0U:1U; unsigned int okey = 0, obutton = 0; CImg<charT> message(1024); CImg_3x3(I,unsigned char); for (bool selected = false; !selected && !disp.is_closed() && !okey && !disp.wheel(); ) { const int mouse_x = disp.mouse_x(), mouse_y = disp.mouse_y(); const unsigned int key = disp.key(), button = disp.button(); // Generate graph representation. if (!visu0) { visu0.assign(disp.width(),disp.height(),1,3,220); const int gdimx = disp.width() - 32, gdimy = disp.height() - 32; if (gdimx>0 && gdimy>0) { graph.assign(gdimx,gdimy,1,3,255); if (siz<32) { if (siz>1) graph.draw_grid(gdimx/(float)(siz - one),gdimy/(float)(siz - one),0,0, false,true,black,0.2f,0x33333333,0x33333333); } else graph.draw_grid(-10,-10,0,0,false,true,black,0.2f,0x33333333,0x33333333); cimg_forC(*this,c) graph.draw_graph(get_shared_channel(c),&colormap(0,c),(plot_type!=3 || _spectrum==1)?1:0.6f, plot_type,vertex_type,nymax,nymin); axes.assign(gdimx,gdimy,1,1,0); const float dx = (float)cimg::abs(nxmax - nxmin), dy = (float)cimg::abs(nymax - nymin), px = (float)std::pow(10.,(int)std::log10(dx?dx:1) - 2.), py = (float)std::pow(10.,(int)std::log10(dy?dy:1) - 2.); const CImg<Tdouble> seqx = dx<=0?CImg<Tdouble>::vector(nxmin): CImg<Tdouble>::sequence(1 + gdimx/60,nxmin,one?nxmax:nxmin + (nxmax - nxmin)*(siz + 1)/siz), seqy = CImg<Tdouble>::sequence(1 + gdimy/60,nymax,nymin); const bool allow_zero = (nxmin*nxmax>0) || (nymin*nymax>0); axes.draw_axes(seqx,seqy,white,1,~0U,~0U,13,allow_zero,px,py); if (nymin>0) axes.draw_axis(seqx,gdimy - 1,gray,1,~0U,13,allow_zero,px); if (nymax<0) axes.draw_axis(seqx,0,gray,1,~0U,13,allow_zero,px); if (nxmin>0) axes.draw_axis(0,seqy,gray,1,~0U,13,allow_zero,py); if (nxmax<0) axes.draw_axis(gdimx - 1,seqy,gray,1,~0U,13,allow_zero,py); cimg_for3x3(axes,x,y,0,0,I,unsigned char) if (Icc) { if (Icc==255) cimg_forC(graph,c) graph(x,y,c) = 0; else cimg_forC(graph,c) graph(x,y,c) = (unsigned char)(2*graph(x,y,c)/3); } else if (Ipc || Inc || Icp || Icn || Ipp || Inn || Ipn || Inp) cimg_forC(graph,c) graph(x,y,c) = (unsigned char)((graph(x,y,c) + 511)/3); visu0.draw_image(16,16,graph); visu0.draw_line(15,15,16 + gdimx,15,gray2).draw_line(16 + gdimx,15,16 + gdimx,16 + gdimy,gray2). draw_line(16 + gdimx,16 + gdimy,15,16 + gdimy,white).draw_line(15,16 + gdimy,15,15,white); } else graph.assign(); text.assign().draw_text(0,0,labelx?labelx:"X-axis",white,ngray,1,13).resize(-100,-100,1,3); visu0.draw_image((visu0.width() - text.width())/2,visu0.height() - 14,~text); text.assign().draw_text(0,0,labely?labely:"Y-axis",white,ngray,1,13).rotate(-90).resize(-100,-100,1,3); visu0.draw_image(1,(visu0.height() - text.height())/2,~text); visu.assign(); } // Generate and display current view. if (!visu) { visu.assign(visu0); if (graph && x0>=0 && x1>=0) { const int nx0 = x0<=x1?x0:x1, nx1 = x0<=x1?x1:x0, ny0 = y0<=y1?y0:y1, ny1 = y0<=y1?y1:y0, sx0 = (int)(16 + nx0*(visu.width() - 32)/std::max((ulongT)1,siz - one)), sx1 = (int)(15 + (nx1 + 1)*(visu.width() - 32)/std::max((ulongT)1,siz - one)), sy0 = 16 + ny0, sy1 = 16 + ny1; if (y0>=0 && y1>=0) visu.draw_rectangle(sx0,sy0,sx1,sy1,gray,0.5f).draw_rectangle(sx0,sy0,sx1,sy1,black,0.5f,0xCCCCCCCCU); else visu.draw_rectangle(sx0,0,sx1,visu.height() - 17,gray,0.5f). draw_line(sx0,16,sx0,visu.height() - 17,black,0.5f,0xCCCCCCCCU). draw_line(sx1,16,sx1,visu.height() - 17,black,0.5f,0xCCCCCCCCU); } if (mouse_x>=16 && mouse_y>=16 && mouse_x<visu.width() - 16 && mouse_y<visu.height() - 16) { if (graph) visu.draw_line(mouse_x,16,mouse_x,visu.height() - 17,black,0.5f,0x55555555U); const unsigned int x = (unsigned int)cimg::round((mouse_x - 16.f)*(siz - one)/(disp.width() - 32),1,one?0:-1); const double cx = nxmin + x*(nxmax - nxmin)/std::max((ulongT)1,siz - 1); if (_spectrum>=7) cimg_snprintf(message,message._width,"Value[%u:%g] = ( %g %g %g ... %g %g %g )",x,cx, (double)(*this)(x,0,0,0),(double)(*this)(x,0,0,1),(double)(*this)(x,0,0,2), (double)(*this)(x,0,0,_spectrum - 4),(double)(*this)(x,0,0,_spectrum - 3), (double)(*this)(x,0,0,_spectrum - 1)); else { cimg_snprintf(message,message._width,"Value[%u:%g] = ( ",x,cx); cimg_forC(*this,c) cimg_sprintf(message._data + std::strlen(message),"%g ",(double)(*this)(x,0,0,c)); cimg_sprintf(message._data + std::strlen(message),")"); } if (x0>=0 && x1>=0) { const unsigned int nx0 = (unsigned int)(x0<=x1?x0:x1), nx1 = (unsigned int)(x0<=x1?x1:x0), ny0 = (unsigned int)(y0<=y1?y0:y1), ny1 = (unsigned int)(y0<=y1?y1:y0); const double cx0 = nxmin + nx0*(nxmax - nxmin)/std::max((ulongT)1,siz - 1), cx1 = nxmin + (nx1 + one)*(nxmax - nxmin)/std::max((ulongT)1,siz - 1), cy0 = nymax - ny0*(nymax - nymin)/(visu._height - 32), cy1 = nymax - ny1*(nymax - nymin)/(visu._height - 32); if (y0>=0 && y1>=0) cimg_sprintf(message._data + std::strlen(message)," - Range ( %u:%g, %g ) - ( %u:%g, %g )", x0,cx0,cy0,x1 + one,cx1,cy1); else cimg_sprintf(message._data + std::strlen(message)," - Range [ %u:%g - %u:%g ]", x0,cx0,x1 + one,cx1); } text.assign().draw_text(0,0,message,white,ngray,1,13).resize(-100,-100,1,3); visu.draw_image((visu.width() - text.width())/2,1,~text); } visu.display(disp); } // Test keys. CImg<charT> filename(32); switch (okey = key) { #if cimg_OS!=2 case cimg::keyCTRLRIGHT : case cimg::keySHIFTRIGHT : #endif case cimg::keyCTRLLEFT : case cimg::keySHIFTLEFT : okey = 0; break; case cimg::keyD : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false). resize(CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,false), CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,true),false). _is_resized = true; disp.set_key(key,false); okey = 0; } break; case cimg::keyC : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false). resize(cimg_fitscreen(2*disp.width()/3,2*disp.height()/3,1),false)._is_resized = true; disp.set_key(key,false); okey = 0; } break; case cimg::keyR : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false). resize(cimg_fitscreen(CImgDisplay::screen_width()/2, CImgDisplay::screen_height()/2,1),false)._is_resized = true; disp.set_key(key,false); okey = 0; } break; case cimg::keyF : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.resize(disp.screen_width(),disp.screen_height(),false).toggle_fullscreen()._is_resized = true; disp.set_key(key,false); okey = 0; } break; case cimg::keyS : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { static unsigned int snap_number = 0; if (visu || visu0) { CImg<ucharT> &screen = visu?visu:visu0; std::FILE *file; do { cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.bmp",snap_number++); if ((file=cimg::std_fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); (+screen).__draw_text(" Saving snapshot... ",0).display(disp); screen.save(filename); (+screen).__draw_text(" Snapshot '%s' saved. ",0,filename._data).display(disp); } disp.set_key(key,false); okey = 0; } break; case cimg::keyO : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { static unsigned int snap_number = 0; if (visu || visu0) { CImg<ucharT> &screen = visu?visu:visu0; std::FILE *file; do { #ifdef cimg_use_zlib cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.cimgz",snap_number++); #else cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.cimg",snap_number++); #endif if ((file=cimg::std_fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); (+screen).__draw_text(" Saving instance... ",0).display(disp); save(filename); (+screen).__draw_text(" Instance '%s' saved. ",0,filename._data).display(disp); } disp.set_key(key,false); okey = 0; } break; } // Handle mouse motion and mouse buttons. if (obutton!=button || omouse_x!=mouse_x || omouse_y!=mouse_y) { visu.assign(); if (disp.mouse_x()>=0 && disp.mouse_y()>=0) { const int mx = (mouse_x - 16)*(int)(siz - one)/(disp.width() - 32), cx = cimg::cut(mx,0,(int)(siz - 1 - one)), my = mouse_y - 16, cy = cimg::cut(my,0,disp.height() - 32); if (button&1) { if (!obutton) { x0 = cx; y0 = -1; } else { x1 = cx; y1 = -1; } } else if (button&2) { if (!obutton) { x0 = cx; y0 = cy; } else { x1 = cx; y1 = cy; } } else if (obutton) { x1 = x1>=0?cx:-1; y1 = y1>=0?cy:-1; selected = true; } } else if (!button && obutton) selected = true; obutton = button; omouse_x = mouse_x; omouse_y = mouse_y; } if (disp.is_resized()) { disp.resize(false); visu0.assign(); } if (visu && visu0) disp.wait(); if (!exit_on_anykey && okey && okey!=cimg::keyESC && (okey!=cimg::keyW || (!disp.is_keyCTRLLEFT() && !disp.is_keyCTRLRIGHT()))) { disp.set_key(key,false); okey = 0; } } disp._normalization = old_normalization; if (x1>=0 && x1<x0) cimg::swap(x0,x1); if (y1<y0) cimg::swap(y0,y1); disp.set_key(okey); return CImg<intT>(4,1,1,1,x0,y0,x1>=0?x1 + (int)one:-1,y1); } //! Load image from a file. /** \param filename Filename, as a C-string. \note The extension of \c filename defines the file format. If no filename extension is provided, CImg<T>::get_load() will try to load the file as a .cimg or .cimgz file. **/ CImg<T>& load(const char *const filename) { if (!filename) throw CImgArgumentException(_cimg_instance "load(): Specified filename is (null).", cimg_instance); if (!cimg::strncasecmp(filename,"http://",7) || !cimg::strncasecmp(filename,"https://",8)) { CImg<charT> filename_local(256); load(cimg::load_network(filename,filename_local)); std::remove(filename_local); return *this; } const char *const ext = cimg::split_filename(filename); const unsigned int omode = cimg::exception_mode(); cimg::exception_mode(0); bool is_loaded = true; try { #ifdef cimg_load_plugin cimg_load_plugin(filename); #endif #ifdef cimg_load_plugin1 cimg_load_plugin1(filename); #endif #ifdef cimg_load_plugin2 cimg_load_plugin2(filename); #endif #ifdef cimg_load_plugin3 cimg_load_plugin3(filename); #endif #ifdef cimg_load_plugin4 cimg_load_plugin4(filename); #endif #ifdef cimg_load_plugin5 cimg_load_plugin5(filename); #endif #ifdef cimg_load_plugin6 cimg_load_plugin6(filename); #endif #ifdef cimg_load_plugin7 cimg_load_plugin7(filename); #endif #ifdef cimg_load_plugin8 cimg_load_plugin8(filename); #endif // Ascii formats if (!cimg::strcasecmp(ext,"asc")) load_ascii(filename); else if (!cimg::strcasecmp(ext,"dlm") || !cimg::strcasecmp(ext,"txt")) load_dlm(filename); // 2D binary formats else if (!cimg::strcasecmp(ext,"bmp")) load_bmp(filename); else if (!cimg::strcasecmp(ext,"jpg") || !cimg::strcasecmp(ext,"jpeg") || !cimg::strcasecmp(ext,"jpe") || !cimg::strcasecmp(ext,"jfif") || !cimg::strcasecmp(ext,"jif")) load_jpeg(filename); else if (!cimg::strcasecmp(ext,"png")) load_png(filename); else if (!cimg::strcasecmp(ext,"ppm") || !cimg::strcasecmp(ext,"pgm") || !cimg::strcasecmp(ext,"pnm") || !cimg::strcasecmp(ext,"pbm") || !cimg::strcasecmp(ext,"pnk")) load_pnm(filename); else if (!cimg::strcasecmp(ext,"pfm")) load_pfm(filename); else if (!cimg::strcasecmp(ext,"tif") || !cimg::strcasecmp(ext,"tiff")) load_tiff(filename); else if (!cimg::strcasecmp(ext,"exr")) load_exr(filename); else if (!cimg::strcasecmp(ext,"cr2") || !cimg::strcasecmp(ext,"crw") || !cimg::strcasecmp(ext,"dcr") || !cimg::strcasecmp(ext,"mrw") || !cimg::strcasecmp(ext,"nef") || !cimg::strcasecmp(ext,"orf") || !cimg::strcasecmp(ext,"pix") || !cimg::strcasecmp(ext,"ptx") || !cimg::strcasecmp(ext,"raf") || !cimg::strcasecmp(ext,"srf")) load_dcraw_external(filename); else if (!cimg::strcasecmp(ext,"gif")) load_gif_external(filename); // 3D binary formats else if (!cimg::strcasecmp(ext,"dcm") || !cimg::strcasecmp(ext,"dicom")) load_medcon_external(filename); else if (!cimg::strcasecmp(ext,"hdr") || !cimg::strcasecmp(ext,"nii")) load_analyze(filename); else if (!cimg::strcasecmp(ext,"par") || !cimg::strcasecmp(ext,"rec")) load_parrec(filename); else if (!cimg::strcasecmp(ext,"mnc")) load_minc2(filename); else if (!cimg::strcasecmp(ext,"inr")) load_inr(filename); else if (!cimg::strcasecmp(ext,"pan")) load_pandore(filename); else if (!cimg::strcasecmp(ext,"cimg") || !cimg::strcasecmp(ext,"cimgz") || !*ext) return load_cimg(filename); // Archive files else if (!cimg::strcasecmp(ext,"gz")) load_gzip_external(filename); // Image sequences else if (!cimg::strcasecmp(ext,"avi") || !cimg::strcasecmp(ext,"mov") || !cimg::strcasecmp(ext,"asf") || !cimg::strcasecmp(ext,"divx") || !cimg::strcasecmp(ext,"flv") || !cimg::strcasecmp(ext,"mpg") || !cimg::strcasecmp(ext,"m1v") || !cimg::strcasecmp(ext,"m2v") || !cimg::strcasecmp(ext,"m4v") || !cimg::strcasecmp(ext,"mjp") || !cimg::strcasecmp(ext,"mp4") || !cimg::strcasecmp(ext,"mkv") || !cimg::strcasecmp(ext,"mpe") || !cimg::strcasecmp(ext,"movie") || !cimg::strcasecmp(ext,"ogm") || !cimg::strcasecmp(ext,"ogg") || !cimg::strcasecmp(ext,"ogv") || !cimg::strcasecmp(ext,"qt") || !cimg::strcasecmp(ext,"rm") || !cimg::strcasecmp(ext,"vob") || !cimg::strcasecmp(ext,"wmv") || !cimg::strcasecmp(ext,"xvid") || !cimg::strcasecmp(ext,"mpeg")) load_video(filename); else is_loaded = false; } catch (CImgIOException&) { is_loaded = false; } // If nothing loaded, try to guess file format from magic number in file. if (!is_loaded) { std::FILE *file = cimg::std_fopen(filename,"rb"); if (!file) { cimg::exception_mode(omode); throw CImgIOException(_cimg_instance "load(): Failed to open file '%s'.", cimg_instance, filename); } const char *const f_type = cimg::ftype(file,filename); cimg::fclose(file); is_loaded = true; try { if (!cimg::strcasecmp(f_type,"pnm")) load_pnm(filename); else if (!cimg::strcasecmp(f_type,"pfm")) load_pfm(filename); else if (!cimg::strcasecmp(f_type,"bmp")) load_bmp(filename); else if (!cimg::strcasecmp(f_type,"inr")) load_inr(filename); else if (!cimg::strcasecmp(f_type,"jpg")) load_jpeg(filename); else if (!cimg::strcasecmp(f_type,"pan")) load_pandore(filename); else if (!cimg::strcasecmp(f_type,"png")) load_png(filename); else if (!cimg::strcasecmp(f_type,"tif")) load_tiff(filename); else if (!cimg::strcasecmp(f_type,"gif")) load_gif_external(filename); else if (!cimg::strcasecmp(f_type,"dcm")) load_medcon_external(filename); else is_loaded = false; } catch (CImgIOException&) { is_loaded = false; } } // If nothing loaded, try to load file with other means. if (!is_loaded) { try { load_other(filename); } catch (CImgIOException&) { cimg::exception_mode(omode); throw CImgIOException(_cimg_instance "load(): Failed to recognize format of file '%s'.", cimg_instance, filename); } } cimg::exception_mode(omode); return *this; } //! Load image from a file \newinstance. static CImg<T> get_load(const char *const filename) { return CImg<T>().load(filename); } //! Load image from an Ascii file. /** \param filename Filename, as a C -string. **/ CImg<T>& load_ascii(const char *const filename) { return _load_ascii(0,filename); } //! Load image from an Ascii file \inplace. static CImg<T> get_load_ascii(const char *const filename) { return CImg<T>().load_ascii(filename); } //! Load image from an Ascii file \overloading. CImg<T>& load_ascii(std::FILE *const file) { return _load_ascii(file,0); } //! Loadimage from an Ascii file \newinstance. static CImg<T> get_load_ascii(std::FILE *const file) { return CImg<T>().load_ascii(file); } CImg<T>& _load_ascii(std::FILE *const file, const char *const filename) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_ascii(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); CImg<charT> line(256); *line = 0; int err = std::fscanf(nfile,"%255[^\n]",line._data); unsigned int dx = 0, dy = 1, dz = 1, dc = 1; cimg_sscanf(line,"%u%*c%u%*c%u%*c%u",&dx,&dy,&dz,&dc); err = std::fscanf(nfile,"%*[^0-9.eEinfa+-]"); if (!dx || !dy || !dz || !dc) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_ascii(): Invalid Ascii header in file '%s', image dimensions are set " "to (%u,%u,%u,%u).", cimg_instance, filename?filename:"(FILE*)",dx,dy,dz,dc); } assign(dx,dy,dz,dc); const ulongT siz = size(); ulongT off = 0; double val; T *ptr = _data; for (err = 1, off = 0; off<siz && err==1; ++off) { err = std::fscanf(nfile,"%lf%*[^0-9.eEinfa+-]",&val); *(ptr++) = (T)val; } if (err!=1) cimg::warn(_cimg_instance "load_ascii(): Only %lu/%lu values read from file '%s'.", cimg_instance, off - 1,siz,filename?filename:"(FILE*)"); if (!file) cimg::fclose(nfile); return *this; } //! Load image from a DLM file. /** \param filename Filename, as a C-string. **/ CImg<T>& load_dlm(const char *const filename) { return _load_dlm(0,filename); } //! Load image from a DLM file \newinstance. static CImg<T> get_load_dlm(const char *const filename) { return CImg<T>().load_dlm(filename); } //! Load image from a DLM file \overloading. CImg<T>& load_dlm(std::FILE *const file) { return _load_dlm(file,0); } //! Load image from a DLM file \newinstance. static CImg<T> get_load_dlm(std::FILE *const file) { return CImg<T>().load_dlm(file); } CImg<T>& _load_dlm(std::FILE *const file, const char *const filename) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_dlm(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"r"); CImg<charT> delimiter(256), tmp(256); *delimiter = *tmp = 0; unsigned int cdx = 0, dx = 0, dy = 0; int err = 0; double val; assign(256,256,1,1,(T)0); while ((err = std::fscanf(nfile,"%lf%255[^0-9eEinfa.+-]",&val,delimiter._data))>0) { if (err>0) (*this)(cdx++,dy) = (T)val; if (cdx>=_width) resize(3*_width/2,_height,1,1,0); char c = 0; if (!cimg_sscanf(delimiter,"%255[^\n]%c",tmp._data,&c) || c=='\n') { dx = std::max(cdx,dx); if (++dy>=_height) resize(_width,3*_height/2,1,1,0); cdx = 0; } } if (cdx && err==1) { dx = cdx; ++dy; } if (!dx || !dy) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_dlm(): Invalid DLM file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } resize(dx,dy,1,1,0); if (!file) cimg::fclose(nfile); return *this; } //! Load image from a BMP file. /** \param filename Filename, as a C-string. **/ CImg<T>& load_bmp(const char *const filename) { return _load_bmp(0,filename); } //! Load image from a BMP file \newinstance. static CImg<T> get_load_bmp(const char *const filename) { return CImg<T>().load_bmp(filename); } //! Load image from a BMP file \overloading. CImg<T>& load_bmp(std::FILE *const file) { return _load_bmp(file,0); } //! Load image from a BMP file \newinstance. static CImg<T> get_load_bmp(std::FILE *const file) { return CImg<T>().load_bmp(file); } CImg<T>& _load_bmp(std::FILE *const file, const char *const filename) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_bmp(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); CImg<ucharT> header(54); cimg::fread(header._data,54,nfile); if (*header!='B' || header[1]!='M') { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_bmp(): Invalid BMP file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } // Read header and pixel buffer int file_size = header[0x02] + (header[0x03]<<8) + (header[0x04]<<16) + (header[0x05]<<24), offset = header[0x0A] + (header[0x0B]<<8) + (header[0x0C]<<16) + (header[0x0D]<<24), header_size = header[0x0E] + (header[0x0F]<<8) + (header[0x10]<<16) + (header[0x11]<<24), dx = header[0x12] + (header[0x13]<<8) + (header[0x14]<<16) + (header[0x15]<<24), dy = header[0x16] + (header[0x17]<<8) + (header[0x18]<<16) + (header[0x19]<<24), compression = header[0x1E] + (header[0x1F]<<8) + (header[0x20]<<16) + (header[0x21]<<24), nb_colors = header[0x2E] + (header[0x2F]<<8) + (header[0x30]<<16) + (header[0x31]<<24), bpp = header[0x1C] + (header[0x1D]<<8); if (!file_size || file_size==offset) { cimg::fseek(nfile,0,SEEK_END); file_size = (int)cimg::ftell(nfile); cimg::fseek(nfile,54,SEEK_SET); } if (header_size>40) cimg::fseek(nfile,header_size - 40,SEEK_CUR); const int dx_bytes = (bpp==1)?(dx/8 + (dx%8?1:0)):((bpp==4)?(dx/2 + (dx%2)):(int)((longT)dx*bpp/8)), align_bytes = (4 - dx_bytes%4)%4; const ulongT cimg_iobuffer = (ulongT)24*1024*1024, buf_size = std::min((ulongT)cimg::abs(dy)*(dx_bytes + align_bytes),(ulongT)file_size - offset); CImg<intT> colormap; if (bpp<16) { if (!nb_colors) nb_colors = 1<<bpp; } else nb_colors = 0; if (nb_colors) { colormap.assign(nb_colors); cimg::fread(colormap._data,nb_colors,nfile); } const int xoffset = offset - 14 - header_size - 4*nb_colors; if (xoffset>0) cimg::fseek(nfile,xoffset,SEEK_CUR); CImg<ucharT> buffer; if (buf_size<cimg_iobuffer) { // buffer.assign(cimg::abs(dy)*(dx_bytes + align_bytes),1,1,1,0); buffer.assign(buf_size,1,1,1,0); cimg::fread(buffer._data,buf_size,nfile); } else buffer.assign(dx_bytes + align_bytes); unsigned char *ptrs = buffer; // Decompress buffer (if necessary) if (compression) { if (file) throw CImgIOException(_cimg_instance "load_bmp(): Unable to load compressed data from '(*FILE)' inputs.", cimg_instance); else { if (!file) cimg::fclose(nfile); return load_other(filename); } } // Read pixel data assign(dx,cimg::abs(dy),1,3,0); switch (bpp) { case 1 : { // Monochrome if (colormap._width>=2) for (int y = height() - 1; y>=0; --y) { if (buf_size>=cimg_iobuffer) { if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break; cimg::fseek(nfile,align_bytes,SEEK_CUR); } unsigned char mask = 0x80, val = 0; cimg_forX(*this,x) { if (mask==0x80) val = *(ptrs++); const unsigned char *col = (unsigned char*)(colormap._data + (val&mask?1:0)); (*this)(x,y,2) = (T)*(col++); (*this)(x,y,1) = (T)*(col++); (*this)(x,y,0) = (T)*(col++); mask = cimg::ror(mask); } ptrs+=align_bytes; } } break; case 4 : { // 16 colors if (colormap._width>=16) for (int y = height() - 1; y>=0; --y) { if (buf_size>=cimg_iobuffer) { if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break; cimg::fseek(nfile,align_bytes,SEEK_CUR); } unsigned char mask = 0xF0, val = 0; cimg_forX(*this,x) { if (mask==0xF0) val = *(ptrs++); const unsigned char color = (unsigned char)((mask<16)?(val&mask):((val&mask)>>4)); const unsigned char *col = (unsigned char*)(colormap._data + color); (*this)(x,y,2) = (T)*(col++); (*this)(x,y,1) = (T)*(col++); (*this)(x,y,0) = (T)*(col++); mask = cimg::ror(mask,4); } ptrs+=align_bytes; } } break; case 8 : { // 256 colors if (colormap._width>=256) for (int y = height() - 1; y>=0; --y) { if (buf_size>=cimg_iobuffer) { if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break; cimg::fseek(nfile,align_bytes,SEEK_CUR); } cimg_forX(*this,x) { const unsigned char *col = (unsigned char*)(colormap._data + *(ptrs++)); (*this)(x,y,2) = (T)*(col++); (*this)(x,y,1) = (T)*(col++); (*this)(x,y,0) = (T)*(col++); } ptrs+=align_bytes; } } break; case 16 : { // 16 bits colors for (int y = height() - 1; y>=0; --y) { if (buf_size>=cimg_iobuffer) { if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break; cimg::fseek(nfile,align_bytes,SEEK_CUR); } cimg_forX(*this,x) { const unsigned char c1 = *(ptrs++), c2 = *(ptrs++); const unsigned short col = (unsigned short)(c1|(c2<<8)); (*this)(x,y,2) = (T)(col&0x1F); (*this)(x,y,1) = (T)((col>>5)&0x1F); (*this)(x,y,0) = (T)((col>>10)&0x1F); } ptrs+=align_bytes; } } break; case 24 : { // 24 bits colors for (int y = height() - 1; y>=0; --y) { if (buf_size>=cimg_iobuffer) { if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break; cimg::fseek(nfile,align_bytes,SEEK_CUR); } cimg_forX(*this,x) { (*this)(x,y,2) = (T)*(ptrs++); (*this)(x,y,1) = (T)*(ptrs++); (*this)(x,y,0) = (T)*(ptrs++); } ptrs+=align_bytes; } } break; case 32 : { // 32 bits colors for (int y = height() - 1; y>=0; --y) { if (buf_size>=cimg_iobuffer) { if (!cimg::fread(ptrs=buffer._data,dx_bytes,nfile)) break; cimg::fseek(nfile,align_bytes,SEEK_CUR); } cimg_forX(*this,x) { (*this)(x,y,2) = (T)*(ptrs++); (*this)(x,y,1) = (T)*(ptrs++); (*this)(x,y,0) = (T)*(ptrs++); ++ptrs; } ptrs+=align_bytes; } } break; } if (dy<0) mirror('y'); if (!file) cimg::fclose(nfile); return *this; } //! Load image from a JPEG file. /** \param filename Filename, as a C-string. **/ CImg<T>& load_jpeg(const char *const filename) { return _load_jpeg(0,filename); } //! Load image from a JPEG file \newinstance. static CImg<T> get_load_jpeg(const char *const filename) { return CImg<T>().load_jpeg(filename); } //! Load image from a JPEG file \overloading. CImg<T>& load_jpeg(std::FILE *const file) { return _load_jpeg(file,0); } //! Load image from a JPEG file \newinstance. static CImg<T> get_load_jpeg(std::FILE *const file) { return CImg<T>().load_jpeg(file); } // Custom error handler for libjpeg. #ifdef cimg_use_jpeg struct _cimg_error_mgr { struct jpeg_error_mgr original; jmp_buf setjmp_buffer; char message[JMSG_LENGTH_MAX]; }; typedef struct _cimg_error_mgr *_cimg_error_ptr; METHODDEF(void) _cimg_jpeg_error_exit(j_common_ptr cinfo) { _cimg_error_ptr c_err = (_cimg_error_ptr) cinfo->err; // Return control to the setjmp point (*cinfo->err->format_message)(cinfo,c_err->message); jpeg_destroy(cinfo); // Clean memory and temp files longjmp(c_err->setjmp_buffer,1); } #endif CImg<T>& _load_jpeg(std::FILE *const file, const char *const filename) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_jpeg(): Specified filename is (null).", cimg_instance); #ifndef cimg_use_jpeg if (file) throw CImgIOException(_cimg_instance "load_jpeg(): Unable to load data from '(FILE*)' unless libjpeg is enabled.", cimg_instance); else return load_other(filename); #else std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); struct jpeg_decompress_struct cinfo; struct _cimg_error_mgr jerr; cinfo.err = jpeg_std_error(&jerr.original); jerr.original.error_exit = _cimg_jpeg_error_exit; if (setjmp(jerr.setjmp_buffer)) { // JPEG error if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_jpeg(): Error message returned by libjpeg: %s.", cimg_instance,jerr.message); } jpeg_create_decompress(&cinfo); jpeg_stdio_src(&cinfo,nfile); jpeg_read_header(&cinfo,TRUE); jpeg_start_decompress(&cinfo); if (cinfo.output_components!=1 && cinfo.output_components!=3 && cinfo.output_components!=4) { if (!file) { cimg::fclose(nfile); return load_other(filename); } else throw CImgIOException(_cimg_instance "load_jpeg(): Failed to load JPEG data from file '%s'.", cimg_instance,filename?filename:"(FILE*)"); } CImg<ucharT> buffer(cinfo.output_width*cinfo.output_components); JSAMPROW row_pointer[1]; try { assign(cinfo.output_width,cinfo.output_height,1,cinfo.output_components); } catch (...) { if (!file) cimg::fclose(nfile); throw; } T *ptr_r = _data, *ptr_g = _data + 1UL*_width*_height, *ptr_b = _data + 2UL*_width*_height, *ptr_a = _data + 3UL*_width*_height; while (cinfo.output_scanline<cinfo.output_height) { *row_pointer = buffer._data; if (jpeg_read_scanlines(&cinfo,row_pointer,1)!=1) { cimg::warn(_cimg_instance "load_jpeg(): Incomplete data in file '%s'.", cimg_instance,filename?filename:"(FILE*)"); break; } const unsigned char *ptrs = buffer._data; switch (_spectrum) { case 1 : { cimg_forX(*this,x) *(ptr_r++) = (T)*(ptrs++); } break; case 3 : { cimg_forX(*this,x) { *(ptr_r++) = (T)*(ptrs++); *(ptr_g++) = (T)*(ptrs++); *(ptr_b++) = (T)*(ptrs++); } } break; case 4 : { cimg_forX(*this,x) { *(ptr_r++) = (T)*(ptrs++); *(ptr_g++) = (T)*(ptrs++); *(ptr_b++) = (T)*(ptrs++); *(ptr_a++) = (T)*(ptrs++); } } break; } } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); if (!file) cimg::fclose(nfile); return *this; #endif } //! Load image from a file, using Magick++ library. /** \param filename Filename, as a C-string. **/ // Added April/may 2006 by Christoph Hormann <chris_hormann@gmx.de> // This is experimental code, not much tested, use with care. CImg<T>& load_magick(const char *const filename) { if (!filename) throw CImgArgumentException(_cimg_instance "load_magick(): Specified filename is (null).", cimg_instance); #ifdef cimg_use_magick Magick::Image image(filename); const unsigned int W = image.size().width(), H = image.size().height(); switch (image.type()) { case Magick::PaletteMatteType : case Magick::TrueColorMatteType : case Magick::ColorSeparationType : { assign(W,H,1,4); T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2), *ptr_a = data(0,0,0,3); Magick::PixelPacket *pixels = image.getPixels(0,0,W,H); for (ulongT off = (ulongT)W*H; off; --off) { *(ptr_r++) = (T)(pixels->red); *(ptr_g++) = (T)(pixels->green); *(ptr_b++) = (T)(pixels->blue); *(ptr_a++) = (T)(pixels->opacity); ++pixels; } } break; case Magick::PaletteType : case Magick::TrueColorType : { assign(W,H,1,3); T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2); Magick::PixelPacket *pixels = image.getPixels(0,0,W,H); for (ulongT off = (ulongT)W*H; off; --off) { *(ptr_r++) = (T)(pixels->red); *(ptr_g++) = (T)(pixels->green); *(ptr_b++) = (T)(pixels->blue); ++pixels; } } break; case Magick::GrayscaleMatteType : { assign(W,H,1,2); T *ptr_r = data(0,0,0,0), *ptr_a = data(0,0,0,1); Magick::PixelPacket *pixels = image.getPixels(0,0,W,H); for (ulongT off = (ulongT)W*H; off; --off) { *(ptr_r++) = (T)(pixels->red); *(ptr_a++) = (T)(pixels->opacity); ++pixels; } } break; default : { assign(W,H,1,1); T *ptr_r = data(0,0,0,0); Magick::PixelPacket *pixels = image.getPixels(0,0,W,H); for (ulongT off = (ulongT)W*H; off; --off) { *(ptr_r++) = (T)(pixels->red); ++pixels; } } } return *this; #else throw CImgIOException(_cimg_instance "load_magick(): Unable to load file '%s' unless libMagick++ is enabled.", cimg_instance, filename); #endif } //! Load image from a file, using Magick++ library \newinstance. static CImg<T> get_load_magick(const char *const filename) { return CImg<T>().load_magick(filename); } //! Load image from a PNG file. /** \param filename Filename, as a C-string. \param[out] bits_per_pixel Number of bits per pixels used to store pixel values in the image file. **/ CImg<T>& load_png(const char *const filename, unsigned int *const bits_per_pixel=0) { return _load_png(0,filename,bits_per_pixel); } //! Load image from a PNG file \newinstance. static CImg<T> get_load_png(const char *const filename, unsigned int *const bits_per_pixel=0) { return CImg<T>().load_png(filename,bits_per_pixel); } //! Load image from a PNG file \overloading. CImg<T>& load_png(std::FILE *const file, unsigned int *const bits_per_pixel=0) { return _load_png(file,0,bits_per_pixel); } //! Load image from a PNG file \newinstance. static CImg<T> get_load_png(std::FILE *const file, unsigned int *const bits_per_pixel=0) { return CImg<T>().load_png(file,bits_per_pixel); } // (Note: Most of this function has been written by Eric Fausett) CImg<T>& _load_png(std::FILE *const file, const char *const filename, unsigned int *const bits_per_pixel) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_png(): Specified filename is (null).", cimg_instance); #ifndef cimg_use_png cimg::unused(bits_per_pixel); if (file) throw CImgIOException(_cimg_instance "load_png(): Unable to load data from '(FILE*)' unless libpng is enabled.", cimg_instance); else return load_other(filename); #else // Open file and check for PNG validity #if defined __GNUC__ const char *volatile nfilename = filename; // Use 'volatile' to avoid (wrong) g++ warning std::FILE *volatile nfile = file?file:cimg::fopen(nfilename,"rb"); #else const char *nfilename = filename; std::FILE *nfile = file?file:cimg::fopen(nfilename,"rb"); #endif unsigned char pngCheck[8] = { 0 }; cimg::fread(pngCheck,8,(std::FILE*)nfile); if (png_sig_cmp(pngCheck,0,8)) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_png(): Invalid PNG file '%s'.", cimg_instance, nfilename?nfilename:"(FILE*)"); } // Setup PNG structures for read png_voidp user_error_ptr = 0; png_error_ptr user_error_fn = 0, user_warning_fn = 0; png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,user_error_ptr,user_error_fn,user_warning_fn); if (!png_ptr) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_png(): Failed to initialize 'png_ptr' structure for file '%s'.", cimg_instance, nfilename?nfilename:"(FILE*)"); } png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { if (!file) cimg::fclose(nfile); png_destroy_read_struct(&png_ptr,(png_infopp)0,(png_infopp)0); throw CImgIOException(_cimg_instance "load_png(): Failed to initialize 'info_ptr' structure for file '%s'.", cimg_instance, nfilename?nfilename:"(FILE*)"); } png_infop end_info = png_create_info_struct(png_ptr); if (!end_info) { if (!file) cimg::fclose(nfile); png_destroy_read_struct(&png_ptr,&info_ptr,(png_infopp)0); throw CImgIOException(_cimg_instance "load_png(): Failed to initialize 'end_info' structure for file '%s'.", cimg_instance, nfilename?nfilename:"(FILE*)"); } // Error handling callback for png file reading if (setjmp(png_jmpbuf(png_ptr))) { if (!file) cimg::fclose((std::FILE*)nfile); png_destroy_read_struct(&png_ptr, &end_info, (png_infopp)0); throw CImgIOException(_cimg_instance "load_png(): Encountered unknown fatal error in libpng for file '%s'.", cimg_instance, nfilename?nfilename:"(FILE*)"); } png_init_io(png_ptr, nfile); png_set_sig_bytes(png_ptr, 8); // Get PNG Header Info up to data block png_read_info(png_ptr,info_ptr); png_uint_32 W, H; int bit_depth, color_type, interlace_type; bool is_gray = false; png_get_IHDR(png_ptr,info_ptr,&W,&H,&bit_depth,&color_type,&interlace_type,(int*)0,(int*)0); if (bits_per_pixel) *bits_per_pixel = (unsigned int)bit_depth; // Transforms to unify image data if (color_type==PNG_COLOR_TYPE_PALETTE) { png_set_palette_to_rgb(png_ptr); color_type = PNG_COLOR_TYPE_RGB; bit_depth = 8; } if (color_type==PNG_COLOR_TYPE_GRAY && bit_depth<8) { png_set_expand_gray_1_2_4_to_8(png_ptr); is_gray = true; bit_depth = 8; } if (png_get_valid(png_ptr,info_ptr,PNG_INFO_tRNS)) { png_set_tRNS_to_alpha(png_ptr); color_type |= PNG_COLOR_MASK_ALPHA; } if (color_type==PNG_COLOR_TYPE_GRAY || color_type==PNG_COLOR_TYPE_GRAY_ALPHA) { png_set_gray_to_rgb(png_ptr); color_type |= PNG_COLOR_MASK_COLOR; is_gray = true; } if (color_type==PNG_COLOR_TYPE_RGB) png_set_filler(png_ptr,0xffffU,PNG_FILLER_AFTER); png_read_update_info(png_ptr,info_ptr); if (bit_depth!=8 && bit_depth!=16) { if (!file) cimg::fclose(nfile); png_destroy_read_struct(&png_ptr,&end_info,(png_infopp)0); throw CImgIOException(_cimg_instance "load_png(): Invalid bit depth %u in file '%s'.", cimg_instance, bit_depth,nfilename?nfilename:"(FILE*)"); } const int byte_depth = bit_depth>>3; // Allocate memory for image reading png_bytep *const imgData = new png_bytep[H]; for (unsigned int row = 0; row<H; ++row) imgData[row] = new png_byte[(size_t)byte_depth*4*W]; png_read_image(png_ptr,imgData); png_read_end(png_ptr,end_info); // Read pixel data if (color_type!=PNG_COLOR_TYPE_RGB && color_type!=PNG_COLOR_TYPE_RGB_ALPHA) { if (!file) cimg::fclose(nfile); png_destroy_read_struct(&png_ptr,&end_info,(png_infopp)0); throw CImgIOException(_cimg_instance "load_png(): Invalid color coding type %u in file '%s'.", cimg_instance, color_type,nfilename?nfilename:"(FILE*)"); } const bool is_alpha = (color_type==PNG_COLOR_TYPE_RGBA); try { assign(W,H,1,(is_gray?1:3) + (is_alpha?1:0)); } catch (...) { if (!file) cimg::fclose(nfile); throw; } T *ptr_r = data(0,0,0,0), *ptr_g = is_gray?0:data(0,0,0,1), *ptr_b = is_gray?0:data(0,0,0,2), *ptr_a = !is_alpha?0:data(0,0,0,is_gray?1:3); switch (bit_depth) { case 8 : { cimg_forY(*this,y) { const unsigned char *ptrs = (unsigned char*)imgData[y]; cimg_forX(*this,x) { *(ptr_r++) = (T)*(ptrs++); if (ptr_g) *(ptr_g++) = (T)*(ptrs++); else ++ptrs; if (ptr_b) *(ptr_b++) = (T)*(ptrs++); else ++ptrs; if (ptr_a) *(ptr_a++) = (T)*(ptrs++); else ++ptrs; } } } break; case 16 : { cimg_forY(*this,y) { const unsigned short *ptrs = (unsigned short*)(imgData[y]); if (!cimg::endianness()) cimg::invert_endianness(ptrs,4*_width); cimg_forX(*this,x) { *(ptr_r++) = (T)*(ptrs++); if (ptr_g) *(ptr_g++) = (T)*(ptrs++); else ++ptrs; if (ptr_b) *(ptr_b++) = (T)*(ptrs++); else ++ptrs; if (ptr_a) *(ptr_a++) = (T)*(ptrs++); else ++ptrs; } } } break; } png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); // Deallocate image read memory cimg_forY(*this,n) delete[] imgData[n]; delete[] imgData; if (!file) cimg::fclose(nfile); return *this; #endif } //! Load image from a PNM file. /** \param filename Filename, as a C-string. **/ CImg<T>& load_pnm(const char *const filename) { return _load_pnm(0,filename); } //! Load image from a PNM file \newinstance. static CImg<T> get_load_pnm(const char *const filename) { return CImg<T>().load_pnm(filename); } //! Load image from a PNM file \overloading. CImg<T>& load_pnm(std::FILE *const file) { return _load_pnm(file,0); } //! Load image from a PNM file \newinstance. static CImg<T> get_load_pnm(std::FILE *const file) { return CImg<T>().load_pnm(file); } CImg<T>& _load_pnm(std::FILE *const file, const char *const filename) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_pnm(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); unsigned int ppm_type, W, H, D = 1, colormax = 255; CImg<charT> item(16384,1,1,1,0); int err, rval, gval, bval; const longT cimg_iobuffer = (longT)24*1024*1024; while ((err=std::fscanf(nfile,"%16383[^\n]",item.data()))!=EOF && (*item=='#' || !err)) std::fgetc(nfile); if (cimg_sscanf(item," P%u",&ppm_type)!=1) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_pnm(): PNM header not found in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } while ((err=std::fscanf(nfile," %16383[^\n]",item.data()))!=EOF && (*item=='#' || !err)) std::fgetc(nfile); if ((err=cimg_sscanf(item," %u %u %u %u",&W,&H,&D,&colormax))<2) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_pnm(): WIDTH and HEIGHT fields undefined in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } if (ppm_type!=1 && ppm_type!=4) { if (err==2 || (err==3 && (ppm_type==5 || ppm_type==7 || ppm_type==8 || ppm_type==9))) { while ((err=std::fscanf(nfile," %16383[^\n]",item.data()))!=EOF && (*item=='#' || !err)) std::fgetc(nfile); if (cimg_sscanf(item,"%u",&colormax)!=1) cimg::warn(_cimg_instance "load_pnm(): COLORMAX field is undefined in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } else { colormax = D; D = 1; } } std::fgetc(nfile); switch (ppm_type) { case 1 : { // 2D b&w Ascii assign(W,H,1,1); T* ptrd = _data; cimg_foroff(*this,off) { if (std::fscanf(nfile,"%d",&rval)>0) *(ptrd++) = (T)(rval?0:255); else break; } } break; case 2 : { // 2D grey Ascii assign(W,H,1,1); T* ptrd = _data; cimg_foroff(*this,off) { if (std::fscanf(nfile,"%d",&rval)>0) *(ptrd++) = (T)rval; else break; } } break; case 3 : { // 2D color Ascii assign(W,H,1,3); T *ptrd = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2); cimg_forXY(*this,x,y) { if (std::fscanf(nfile,"%d %d %d",&rval,&gval,&bval)==3) { *(ptrd++) = (T)rval; *(ptr_g++) = (T)gval; *(ptr_b++) = (T)bval; } else break; } } break; case 4 : { // 2D b&w binary (support 3D PINK extension) CImg<ucharT> raw; assign(W,H,D,1); T *ptrd = data(0,0,0,0); unsigned int w = 0, h = 0, d = 0; for (longT to_read = (longT)((W/8 + (W%8?1:0))*H*D); to_read>0; ) { raw.assign(std::min(to_read,cimg_iobuffer)); cimg::fread(raw._data,raw._width,nfile); to_read-=raw._width; const unsigned char *ptrs = raw._data; unsigned char mask = 0, val = 0; for (ulongT off = (ulongT)raw._width; off || mask; mask>>=1) { if (!mask) { if (off--) val = *(ptrs++); mask = 128; } *(ptrd++) = (T)((val&mask)?0:255); if (++w==W) { w = 0; mask = 0; if (++h==H) { h = 0; if (++d==D) break; }} } } } break; case 5 : case 7 : { // 2D/3D grey binary (support 3D PINK extension) if (colormax<256) { // 8 bits CImg<ucharT> raw; assign(W,H,D,1); T *ptrd = data(0,0,0,0); for (longT to_read = (longT)size(); to_read>0; ) { raw.assign(std::min(to_read,cimg_iobuffer)); cimg::fread(raw._data,raw._width,nfile); to_read-=raw._width; const unsigned char *ptrs = raw._data; for (ulongT off = (ulongT)raw._width; off; --off) *(ptrd++) = (T)*(ptrs++); } } else { // 16 bits CImg<ushortT> raw; assign(W,H,D,1); T *ptrd = data(0,0,0,0); for (longT to_read = (longT)size(); to_read>0; ) { raw.assign(std::min(to_read,cimg_iobuffer/2)); cimg::fread(raw._data,raw._width,nfile); if (!cimg::endianness()) cimg::invert_endianness(raw._data,raw._width); to_read-=raw._width; const unsigned short *ptrs = raw._data; for (ulongT off = (ulongT)raw._width; off; --off) *(ptrd++) = (T)*(ptrs++); } } } break; case 6 : { // 2D color binary if (colormax<256) { // 8 bits CImg<ucharT> raw; assign(W,H,1,3); T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2); for (longT to_read = (longT)size(); to_read>0; ) { raw.assign(std::min(to_read,cimg_iobuffer)); cimg::fread(raw._data,raw._width,nfile); to_read-=raw._width; const unsigned char *ptrs = raw._data; for (ulongT off = (ulongT)raw._width/3; off; --off) { *(ptr_r++) = (T)*(ptrs++); *(ptr_g++) = (T)*(ptrs++); *(ptr_b++) = (T)*(ptrs++); } } } else { // 16 bits CImg<ushortT> raw; assign(W,H,1,3); T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2); for (longT to_read = (longT)size(); to_read>0; ) { raw.assign(std::min(to_read,cimg_iobuffer/2)); cimg::fread(raw._data,raw._width,nfile); if (!cimg::endianness()) cimg::invert_endianness(raw._data,raw._width); to_read-=raw._width; const unsigned short *ptrs = raw._data; for (ulongT off = (ulongT)raw._width/3; off; --off) { *(ptr_r++) = (T)*(ptrs++); *(ptr_g++) = (T)*(ptrs++); *(ptr_b++) = (T)*(ptrs++); } } } } break; case 8 : { // 2D/3D grey binary with int32 integers (PINK extension) CImg<intT> raw; assign(W,H,D,1); T *ptrd = data(0,0,0,0); for (longT to_read = (longT)size(); to_read>0; ) { raw.assign(std::min(to_read,cimg_iobuffer)); cimg::fread(raw._data,raw._width,nfile); to_read-=raw._width; const int *ptrs = raw._data; for (ulongT off = (ulongT)raw._width; off; --off) *(ptrd++) = (T)*(ptrs++); } } break; case 9 : { // 2D/3D grey binary with float values (PINK extension) CImg<floatT> raw; assign(W,H,D,1); T *ptrd = data(0,0,0,0); for (longT to_read = (longT)size(); to_read>0; ) { raw.assign(std::min(to_read,cimg_iobuffer)); cimg::fread(raw._data,raw._width,nfile); to_read-=raw._width; const float *ptrs = raw._data; for (ulongT off = (ulongT)raw._width; off; --off) *(ptrd++) = (T)*(ptrs++); } } break; default : assign(); if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_pnm(): PNM type 'P%d' found, but type is not supported.", cimg_instance, filename?filename:"(FILE*)",ppm_type); } if (!file) cimg::fclose(nfile); return *this; } //! Load image from a PFM file. /** \param filename Filename, as a C-string. **/ CImg<T>& load_pfm(const char *const filename) { return _load_pfm(0,filename); } //! Load image from a PFM file \newinstance. static CImg<T> get_load_pfm(const char *const filename) { return CImg<T>().load_pfm(filename); } //! Load image from a PFM file \overloading. CImg<T>& load_pfm(std::FILE *const file) { return _load_pfm(file,0); } //! Load image from a PFM file \newinstance. static CImg<T> get_load_pfm(std::FILE *const file) { return CImg<T>().load_pfm(file); } CImg<T>& _load_pfm(std::FILE *const file, const char *const filename) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_pfm(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); char pfm_type; CImg<charT> item(16384,1,1,1,0); int W = 0, H = 0, err = 0; double scale = 0; while ((err=std::fscanf(nfile,"%16383[^\n]",item.data()))!=EOF && (*item=='#' || !err)) std::fgetc(nfile); if (cimg_sscanf(item," P%c",&pfm_type)!=1) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_pfm(): PFM header not found in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } while ((err=std::fscanf(nfile," %16383[^\n]",item.data()))!=EOF && (*item=='#' || !err)) std::fgetc(nfile); if ((err=cimg_sscanf(item," %d %d",&W,&H))<2) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_pfm(): WIDTH and HEIGHT fields are undefined in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } else if (W<=0 || H<=0) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_pfm(): WIDTH (%d) and HEIGHT (%d) fields are invalid in file '%s'.", cimg_instance,W,H, filename?filename:"(FILE*)"); } if (err==2) { while ((err=std::fscanf(nfile," %16383[^\n]",item.data()))!=EOF && (*item=='#' || !err)) std::fgetc(nfile); if (cimg_sscanf(item,"%lf",&scale)!=1) cimg::warn(_cimg_instance "load_pfm(): SCALE field is undefined in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } std::fgetc(nfile); const bool is_color = (pfm_type=='F'), is_inverted = (scale>0)!=cimg::endianness(); if (is_color) { assign(W,H,1,3,(T)0); CImg<floatT> buf(3*W); T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2); cimg_forY(*this,y) { cimg::fread(buf._data,3*W,nfile); if (is_inverted) cimg::invert_endianness(buf._data,3*W); const float *ptrs = buf._data; cimg_forX(*this,x) { *(ptr_r++) = (T)*(ptrs++); *(ptr_g++) = (T)*(ptrs++); *(ptr_b++) = (T)*(ptrs++); } } } else { assign(W,H,1,1,(T)0); CImg<floatT> buf(W); T *ptrd = data(0,0,0,0); cimg_forY(*this,y) { cimg::fread(buf._data,W,nfile); if (is_inverted) cimg::invert_endianness(buf._data,W); const float *ptrs = buf._data; cimg_forX(*this,x) *(ptrd++) = (T)*(ptrs++); } } if (!file) cimg::fclose(nfile); return mirror('y'); // Most of the .pfm files are flipped along the y-axis } //! Load image from a RGB file. /** \param filename Filename, as a C-string. \param dimw Width of the image buffer. \param dimh Height of the image buffer. **/ CImg<T>& load_rgb(const char *const filename, const unsigned int dimw, const unsigned int dimh=1) { return _load_rgb(0,filename,dimw,dimh); } //! Load image from a RGB file \newinstance. static CImg<T> get_load_rgb(const char *const filename, const unsigned int dimw, const unsigned int dimh=1) { return CImg<T>().load_rgb(filename,dimw,dimh); } //! Load image from a RGB file \overloading. CImg<T>& load_rgb(std::FILE *const file, const unsigned int dimw, const unsigned int dimh=1) { return _load_rgb(file,0,dimw,dimh); } //! Load image from a RGB file \newinstance. static CImg<T> get_load_rgb(std::FILE *const file, const unsigned int dimw, const unsigned int dimh=1) { return CImg<T>().load_rgb(file,dimw,dimh); } CImg<T>& _load_rgb(std::FILE *const file, const char *const filename, const unsigned int dimw, const unsigned int dimh) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_rgb(): Specified filename is (null).", cimg_instance); if (!dimw || !dimh) return assign(); const longT cimg_iobuffer = (longT)24*1024*1024; std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); CImg<ucharT> raw; assign(dimw,dimh,1,3); T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2); for (longT to_read = (longT)size(); to_read>0; ) { raw.assign(std::min(to_read,cimg_iobuffer)); cimg::fread(raw._data,raw._width,nfile); to_read-=raw._width; const unsigned char *ptrs = raw._data; for (ulongT off = raw._width/3UL; off; --off) { *(ptr_r++) = (T)*(ptrs++); *(ptr_g++) = (T)*(ptrs++); *(ptr_b++) = (T)*(ptrs++); } } if (!file) cimg::fclose(nfile); return *this; } //! Load image from a RGBA file. /** \param filename Filename, as a C-string. \param dimw Width of the image buffer. \param dimh Height of the image buffer. **/ CImg<T>& load_rgba(const char *const filename, const unsigned int dimw, const unsigned int dimh=1) { return _load_rgba(0,filename,dimw,dimh); } //! Load image from a RGBA file \newinstance. static CImg<T> get_load_rgba(const char *const filename, const unsigned int dimw, const unsigned int dimh=1) { return CImg<T>().load_rgba(filename,dimw,dimh); } //! Load image from a RGBA file \overloading. CImg<T>& load_rgba(std::FILE *const file, const unsigned int dimw, const unsigned int dimh=1) { return _load_rgba(file,0,dimw,dimh); } //! Load image from a RGBA file \newinstance. static CImg<T> get_load_rgba(std::FILE *const file, const unsigned int dimw, const unsigned int dimh=1) { return CImg<T>().load_rgba(file,dimw,dimh); } CImg<T>& _load_rgba(std::FILE *const file, const char *const filename, const unsigned int dimw, const unsigned int dimh) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_rgba(): Specified filename is (null).", cimg_instance); if (!dimw || !dimh) return assign(); const longT cimg_iobuffer = (longT)24*1024*1024; std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); CImg<ucharT> raw; assign(dimw,dimh,1,4); T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2), *ptr_a = data(0,0,0,3); for (longT to_read = (longT)size(); to_read>0; ) { raw.assign(std::min(to_read,cimg_iobuffer)); cimg::fread(raw._data,raw._width,nfile); to_read-=raw._width; const unsigned char *ptrs = raw._data; for (ulongT off = raw._width/4UL; off; --off) { *(ptr_r++) = (T)*(ptrs++); *(ptr_g++) = (T)*(ptrs++); *(ptr_b++) = (T)*(ptrs++); *(ptr_a++) = (T)*(ptrs++); } } if (!file) cimg::fclose(nfile); return *this; } //! Load image from a TIFF file. /** \param filename Filename, as a C-string. \param first_frame First frame to read (for multi-pages tiff). \param last_frame Last frame to read (for multi-pages tiff). \param step_frame Step value of frame reading. \param[out] voxel_size Voxel size, as stored in the filename. \param[out] description Description, as stored in the filename. \note - libtiff support is enabled by defining the precompilation directive \c cimg_use_tif. - When libtiff is enabled, 2D and 3D (multipage) several channel per pixel are supported for <tt>char,uchar,short,ushort,float</tt> and \c double pixel types. - If \c cimg_use_tif is not defined at compile time the function uses CImg<T>& load_other(const char*). **/ CImg<T>& load_tiff(const char *const filename, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, float *const voxel_size=0, CImg<charT> *const description=0) { if (!filename) throw CImgArgumentException(_cimg_instance "load_tiff(): Specified filename is (null).", cimg_instance); const unsigned int nfirst_frame = first_frame<last_frame?first_frame:last_frame, nstep_frame = step_frame?step_frame:1; unsigned int nlast_frame = first_frame<last_frame?last_frame:first_frame; #ifndef cimg_use_tiff cimg::unused(voxel_size,description); if (nfirst_frame || nlast_frame!=~0U || nstep_frame>1) throw CImgArgumentException(_cimg_instance "load_tiff(): Unable to read sub-images from file '%s' unless libtiff is enabled.", cimg_instance, filename); return load_other(filename); #else #if cimg_verbosity<3 TIFFSetWarningHandler(0); TIFFSetErrorHandler(0); #endif TIFF *tif = TIFFOpen(filename,"r"); if (tif) { unsigned int nb_images = 0; do ++nb_images; while (TIFFReadDirectory(tif)); if (nfirst_frame>=nb_images || (nlast_frame!=~0U && nlast_frame>=nb_images)) cimg::warn(_cimg_instance "load_tiff(): File '%s' contains %u image(s) while specified frame range is [%u,%u] (step %u).", cimg_instance, filename,nb_images,nfirst_frame,nlast_frame,nstep_frame); if (nfirst_frame>=nb_images) return assign(); if (nlast_frame>=nb_images) nlast_frame = nb_images - 1; TIFFSetDirectory(tif,0); CImg<T> frame; for (unsigned int l = nfirst_frame; l<=nlast_frame; l+=nstep_frame) { frame._load_tiff(tif,l,voxel_size,description); if (l==nfirst_frame) assign(frame._width,frame._height,1 + (nlast_frame - nfirst_frame)/nstep_frame,frame._spectrum); if (frame._width>_width || frame._height>_height || frame._spectrum>_spectrum) resize(std::max(frame._width,_width), std::max(frame._height,_height),-100, std::max(frame._spectrum,_spectrum),0); draw_image(0,0,(l - nfirst_frame)/nstep_frame,frame); } TIFFClose(tif); } else throw CImgIOException(_cimg_instance "load_tiff(): Failed to open file '%s'.", cimg_instance, filename); return *this; #endif } //! Load image from a TIFF file \newinstance. static CImg<T> get_load_tiff(const char *const filename, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, float *const voxel_size=0, CImg<charT> *const description=0) { return CImg<T>().load_tiff(filename,first_frame,last_frame,step_frame,voxel_size,description); } // (Original contribution by Jerome Boulanger). #ifdef cimg_use_tiff template<typename t> void _load_tiff_tiled_contig(TIFF *const tif, const uint16 samplesperpixel, const uint32 nx, const uint32 ny, const uint32 tw, const uint32 th) { t *const buf = (t*)_TIFFmalloc(TIFFTileSize(tif)); if (buf) { for (unsigned int row = 0; row<ny; row+=th) for (unsigned int col = 0; col<nx; col+=tw) { if (TIFFReadTile(tif,buf,col,row,0,0)<0) { _TIFFfree(buf); TIFFClose(tif); throw CImgIOException(_cimg_instance "load_tiff(): Invalid tile in file '%s'.", cimg_instance, TIFFFileName(tif)); } const t *ptr = buf; for (unsigned int rr = row; rr<std::min((unsigned int)(row + th),(unsigned int)ny); ++rr) for (unsigned int cc = col; cc<std::min((unsigned int)(col + tw),(unsigned int)nx); ++cc) for (unsigned int vv = 0; vv<samplesperpixel; ++vv) (*this)(cc,rr,vv) = (T)(ptr[(rr - row)*th*samplesperpixel + (cc - col)*samplesperpixel + vv]); } _TIFFfree(buf); } } template<typename t> void _load_tiff_tiled_separate(TIFF *const tif, const uint16 samplesperpixel, const uint32 nx, const uint32 ny, const uint32 tw, const uint32 th) { t *const buf = (t*)_TIFFmalloc(TIFFTileSize(tif)); if (buf) { for (unsigned int vv = 0; vv<samplesperpixel; ++vv) for (unsigned int row = 0; row<ny; row+=th) for (unsigned int col = 0; col<nx; col+=tw) { if (TIFFReadTile(tif,buf,col,row,0,vv)<0) { _TIFFfree(buf); TIFFClose(tif); throw CImgIOException(_cimg_instance "load_tiff(): Invalid tile in file '%s'.", cimg_instance, TIFFFileName(tif)); } const t *ptr = buf; for (unsigned int rr = row; rr<std::min((unsigned int)(row + th),(unsigned int)ny); ++rr) for (unsigned int cc = col; cc<std::min((unsigned int)(col + tw),(unsigned int)nx); ++cc) (*this)(cc,rr,vv) = (T)*(ptr++); } _TIFFfree(buf); } } template<typename t> void _load_tiff_contig(TIFF *const tif, const uint16 samplesperpixel, const uint32 nx, const uint32 ny) { t *const buf = (t*)_TIFFmalloc(TIFFStripSize(tif)); if (buf) { uint32 row, rowsperstrip = (uint32)-1; TIFFGetField(tif,TIFFTAG_ROWSPERSTRIP,&rowsperstrip); for (row = 0; row<ny; row+= rowsperstrip) { uint32 nrow = (row + rowsperstrip>ny?ny - row:rowsperstrip); tstrip_t strip = TIFFComputeStrip(tif, row, 0); if ((TIFFReadEncodedStrip(tif,strip,buf,-1))<0) { _TIFFfree(buf); TIFFClose(tif); throw CImgIOException(_cimg_instance "load_tiff(): Invalid strip in file '%s'.", cimg_instance, TIFFFileName(tif)); } const t *ptr = buf; for (unsigned int rr = 0; rr<nrow; ++rr) for (unsigned int cc = 0; cc<nx; ++cc) for (unsigned int vv = 0; vv<samplesperpixel; ++vv) (*this)(cc,row + rr,vv) = (T)*(ptr++); } _TIFFfree(buf); } } template<typename t> void _load_tiff_separate(TIFF *const tif, const uint16 samplesperpixel, const uint32 nx, const uint32 ny) { t *buf = (t*)_TIFFmalloc(TIFFStripSize(tif)); if (buf) { uint32 row, rowsperstrip = (uint32)-1; TIFFGetField(tif,TIFFTAG_ROWSPERSTRIP,&rowsperstrip); for (unsigned int vv = 0; vv<samplesperpixel; ++vv) for (row = 0; row<ny; row+= rowsperstrip) { uint32 nrow = (row + rowsperstrip>ny?ny - row:rowsperstrip); tstrip_t strip = TIFFComputeStrip(tif, row, vv); if ((TIFFReadEncodedStrip(tif,strip,buf,-1))<0) { _TIFFfree(buf); TIFFClose(tif); throw CImgIOException(_cimg_instance "load_tiff(): Invalid strip in file '%s'.", cimg_instance, TIFFFileName(tif)); } const t *ptr = buf; for (unsigned int rr = 0;rr<nrow; ++rr) for (unsigned int cc = 0; cc<nx; ++cc) (*this)(cc,row + rr,vv) = (T)*(ptr++); } _TIFFfree(buf); } } CImg<T>& _load_tiff(TIFF *const tif, const unsigned int directory, float *const voxel_size, CImg<charT> *const description) { if (!TIFFSetDirectory(tif,directory)) return assign(); uint16 samplesperpixel = 1, bitspersample = 8, photo = 0; uint16 sampleformat = 1; uint32 nx = 1, ny = 1; const char *const filename = TIFFFileName(tif); const bool is_spp = (bool)TIFFGetField(tif,TIFFTAG_SAMPLESPERPIXEL,&samplesperpixel); TIFFGetField(tif,TIFFTAG_IMAGEWIDTH,&nx); TIFFGetField(tif,TIFFTAG_IMAGELENGTH,&ny); TIFFGetField(tif, TIFFTAG_SAMPLEFORMAT, &sampleformat); TIFFGetFieldDefaulted(tif,TIFFTAG_BITSPERSAMPLE,&bitspersample); TIFFGetField(tif,TIFFTAG_PHOTOMETRIC,&photo); if (voxel_size) { const char *s_description = 0; float vx = 0, vy = 0, vz = 0; if (TIFFGetField(tif,TIFFTAG_IMAGEDESCRIPTION,&s_description) && s_description) { const char *s_desc = std::strstr(s_description,"VX="); if (s_desc && cimg_sscanf(s_desc,"VX=%f VY=%f VZ=%f",&vx,&vy,&vz)==3) { // CImg format voxel_size[0] = vx; voxel_size[1] = vy; voxel_size[2] = vz; } s_desc = std::strstr(s_description,"spacing="); if (s_desc && cimg_sscanf(s_desc,"spacing=%f",&vz)==1) { // Fiji format voxel_size[2] = vz; } } TIFFGetField(tif,TIFFTAG_XRESOLUTION,voxel_size); TIFFGetField(tif,TIFFTAG_YRESOLUTION,voxel_size + 1); voxel_size[0] = 1.f/voxel_size[0]; voxel_size[1] = 1.f/voxel_size[1]; } if (description) { const char *s_description = 0; if (TIFFGetField(tif,TIFFTAG_IMAGEDESCRIPTION,&s_description) && s_description) CImg<charT>::string(s_description).move_to(*description); } const unsigned int spectrum = !is_spp || photo>=3?(photo>1?3:1):samplesperpixel; assign(nx,ny,1,spectrum); if ((photo>=3 && sampleformat==1 && (bitspersample==4 || bitspersample==8) && (samplesperpixel==1 || samplesperpixel==3 || samplesperpixel==4)) || (bitspersample==1 && samplesperpixel==1)) { // Special case for unsigned color images. uint32 *const raster = (uint32*)_TIFFmalloc(nx*ny*sizeof(uint32)); if (!raster) { _TIFFfree(raster); TIFFClose(tif); throw CImgException(_cimg_instance "load_tiff(): Failed to allocate memory (%s) for file '%s'.", cimg_instance, cimg::strbuffersize(nx*ny*sizeof(uint32)),filename); } TIFFReadRGBAImage(tif,nx,ny,raster,0); switch (spectrum) { case 1 : cimg_forXY(*this,x,y) (*this)(x,y,0) = (T)(float)TIFFGetR(raster[nx*(ny - 1 -y) + x]); break; case 3 : cimg_forXY(*this,x,y) { (*this)(x,y,0) = (T)(float)TIFFGetR(raster[nx*(ny - 1 -y) + x]); (*this)(x,y,1) = (T)(float)TIFFGetG(raster[nx*(ny - 1 -y) + x]); (*this)(x,y,2) = (T)(float)TIFFGetB(raster[nx*(ny - 1 -y) + x]); } break; case 4 : cimg_forXY(*this,x,y) { (*this)(x,y,0) = (T)(float)TIFFGetR(raster[nx*(ny - 1 - y) + x]); (*this)(x,y,1) = (T)(float)TIFFGetG(raster[nx*(ny - 1 - y) + x]); (*this)(x,y,2) = (T)(float)TIFFGetB(raster[nx*(ny - 1 - y) + x]); (*this)(x,y,3) = (T)(float)TIFFGetA(raster[nx*(ny - 1 - y) + x]); } break; } _TIFFfree(raster); } else { // Other cases uint16 config; TIFFGetField(tif,TIFFTAG_PLANARCONFIG,&config); if (TIFFIsTiled(tif)) { uint32 tw = 1, th = 1; TIFFGetField(tif,TIFFTAG_TILEWIDTH,&tw); TIFFGetField(tif,TIFFTAG_TILELENGTH,&th); if (config==PLANARCONFIG_CONTIG) switch (bitspersample) { case 8 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_tiled_contig<unsigned char>(tif,samplesperpixel,nx,ny,tw,th); else _load_tiff_tiled_contig<signed char>(tif,samplesperpixel,nx,ny,tw,th); break; case 16 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_tiled_contig<unsigned short>(tif,samplesperpixel,nx,ny,tw,th); else _load_tiff_tiled_contig<short>(tif,samplesperpixel,nx,ny,tw,th); break; case 32 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_tiled_contig<unsigned int>(tif,samplesperpixel,nx,ny,tw,th); else if (sampleformat==SAMPLEFORMAT_INT) _load_tiff_tiled_contig<int>(tif,samplesperpixel,nx,ny,tw,th); else _load_tiff_tiled_contig<float>(tif,samplesperpixel,nx,ny,tw,th); break; case 64 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_tiled_contig<uint64T>(tif,samplesperpixel,nx,ny,tw,th); else if (sampleformat==SAMPLEFORMAT_INT) _load_tiff_tiled_contig<int64T>(tif,samplesperpixel,nx,ny,tw,th); else _load_tiff_tiled_contig<double>(tif,samplesperpixel,nx,ny,tw,th); break; } else switch (bitspersample) { case 8 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_tiled_separate<unsigned char>(tif,samplesperpixel,nx,ny,tw,th); else _load_tiff_tiled_separate<signed char>(tif,samplesperpixel,nx,ny,tw,th); break; case 16 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_tiled_separate<unsigned short>(tif,samplesperpixel,nx,ny,tw,th); else _load_tiff_tiled_separate<short>(tif,samplesperpixel,nx,ny,tw,th); break; case 32 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_tiled_separate<unsigned int>(tif,samplesperpixel,nx,ny,tw,th); else if (sampleformat==SAMPLEFORMAT_INT) _load_tiff_tiled_separate<int>(tif,samplesperpixel,nx,ny,tw,th); else _load_tiff_tiled_separate<float>(tif,samplesperpixel,nx,ny,tw,th); break; case 64 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_tiled_separate<uint64T>(tif,samplesperpixel,nx,ny,tw,th); else if (sampleformat==SAMPLEFORMAT_INT) _load_tiff_tiled_separate<int64T>(tif,samplesperpixel,nx,ny,tw,th); else _load_tiff_tiled_separate<double>(tif,samplesperpixel,nx,ny,tw,th); break; } } else { if (config==PLANARCONFIG_CONTIG) switch (bitspersample) { case 8 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_contig<unsigned char>(tif,samplesperpixel,nx,ny); else _load_tiff_contig<signed char>(tif,samplesperpixel,nx,ny); break; case 16 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_contig<unsigned short>(tif,samplesperpixel,nx,ny); else _load_tiff_contig<short>(tif,samplesperpixel,nx,ny); break; case 32 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_contig<unsigned int>(tif,samplesperpixel,nx,ny); else if (sampleformat==SAMPLEFORMAT_INT) _load_tiff_contig<int>(tif,samplesperpixel,nx,ny); else _load_tiff_contig<float>(tif,samplesperpixel,nx,ny); break; case 64 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_contig<uint64T>(tif,samplesperpixel,nx,ny); else if (sampleformat==SAMPLEFORMAT_INT) _load_tiff_contig<int64T>(tif,samplesperpixel,nx,ny); else _load_tiff_contig<double>(tif,samplesperpixel,nx,ny); break; } else switch (bitspersample) { case 8 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_separate<unsigned char>(tif,samplesperpixel,nx,ny); else _load_tiff_separate<signed char>(tif,samplesperpixel,nx,ny); break; case 16 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_separate<unsigned short>(tif,samplesperpixel,nx,ny); else _load_tiff_separate<short>(tif,samplesperpixel,nx,ny); break; case 32 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_separate<unsigned int>(tif,samplesperpixel,nx,ny); else if (sampleformat==SAMPLEFORMAT_INT) _load_tiff_separate<int>(tif,samplesperpixel,nx,ny); else _load_tiff_separate<float>(tif,samplesperpixel,nx,ny); break; case 64 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_separate<uint64T>(tif,samplesperpixel,nx,ny); else if (sampleformat==SAMPLEFORMAT_INT) _load_tiff_separate<int64T>(tif,samplesperpixel,nx,ny); else _load_tiff_separate<double>(tif,samplesperpixel,nx,ny); break; } } } return *this; } #endif //! Load image from a MINC2 file. /** \param filename Filename, as a C-string. **/ // (Original code by Haz-Edine Assemlal). CImg<T>& load_minc2(const char *const filename) { if (!filename) throw CImgArgumentException(_cimg_instance "load_minc2(): Specified filename is (null).", cimg_instance); #ifndef cimg_use_minc2 return load_other(filename); #else minc::minc_1_reader rdr; rdr.open(filename); assign(rdr.ndim(1)?rdr.ndim(1):1, rdr.ndim(2)?rdr.ndim(2):1, rdr.ndim(3)?rdr.ndim(3):1, rdr.ndim(4)?rdr.ndim(4):1); if (cimg::type<T>::string()==cimg::type<unsigned char>::string()) rdr.setup_read_byte(); else if (cimg::type<T>::string()==cimg::type<int>::string()) rdr.setup_read_int(); else if (cimg::type<T>::string()==cimg::type<double>::string()) rdr.setup_read_double(); else rdr.setup_read_float(); minc::load_standard_volume(rdr,this->_data); return *this; #endif } //! Load image from a MINC2 file \newinstance. static CImg<T> get_load_minc2(const char *const filename) { return CImg<T>().load_analyze(filename); } //! Load image from an ANALYZE7.5/NIFTI file. /** \param filename Filename, as a C-string. \param[out] voxel_size Pointer to the three voxel sizes read from the file. **/ CImg<T>& load_analyze(const char *const filename, float *const voxel_size=0) { return _load_analyze(0,filename,voxel_size); } //! Load image from an ANALYZE7.5/NIFTI file \newinstance. static CImg<T> get_load_analyze(const char *const filename, float *const voxel_size=0) { return CImg<T>().load_analyze(filename,voxel_size); } //! Load image from an ANALYZE7.5/NIFTI file \overloading. CImg<T>& load_analyze(std::FILE *const file, float *const voxel_size=0) { return _load_analyze(file,0,voxel_size); } //! Load image from an ANALYZE7.5/NIFTI file \newinstance. static CImg<T> get_load_analyze(std::FILE *const file, float *const voxel_size=0) { return CImg<T>().load_analyze(file,voxel_size); } CImg<T>& _load_analyze(std::FILE *const file, const char *const filename, float *const voxel_size=0) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_analyze(): Specified filename is (null).", cimg_instance); std::FILE *nfile_header = 0, *nfile = 0; if (!file) { CImg<charT> body(1024); const char *const ext = cimg::split_filename(filename,body); if (!cimg::strcasecmp(ext,"hdr")) { // File is an Analyze header file nfile_header = cimg::fopen(filename,"rb"); cimg_sprintf(body._data + std::strlen(body),".img"); nfile = cimg::fopen(body,"rb"); } else if (!cimg::strcasecmp(ext,"img")) { // File is an Analyze data file nfile = cimg::fopen(filename,"rb"); cimg_sprintf(body._data + std::strlen(body),".hdr"); nfile_header = cimg::fopen(body,"rb"); } else nfile_header = nfile = cimg::fopen(filename,"rb"); // File is a Niftii file } else nfile_header = nfile = file; // File is a Niftii file if (!nfile || !nfile_header) throw CImgIOException(_cimg_instance "load_analyze(): Invalid Analyze7.5 or NIFTI header in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); // Read header. bool endian = false; unsigned int header_size; cimg::fread(&header_size,1,nfile_header); if (!header_size) throw CImgIOException(_cimg_instance "load_analyze(): Invalid zero-size header in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); if (header_size>=4096) { endian = true; cimg::invert_endianness(header_size); } unsigned char *const header = new unsigned char[header_size]; cimg::fread(header + 4,header_size - 4,nfile_header); if (!file && nfile_header!=nfile) cimg::fclose(nfile_header); if (endian) { cimg::invert_endianness((short*)(header + 40),5); cimg::invert_endianness((short*)(header + 70),1); cimg::invert_endianness((short*)(header + 72),1); cimg::invert_endianness((float*)(header + 76),4); cimg::invert_endianness((float*)(header + 108),1); cimg::invert_endianness((float*)(header + 112),1); } if (nfile_header==nfile) { const unsigned int vox_offset = (unsigned int)*(float*)(header + 108); std::fseek(nfile,vox_offset,SEEK_SET); } unsigned short *dim = (unsigned short*)(header + 40), dimx = 1, dimy = 1, dimz = 1, dimv = 1; if (!dim[0]) cimg::warn(_cimg_instance "load_analyze(): File '%s' defines an image with zero dimensions.", cimg_instance, filename?filename:"(FILE*)"); if (dim[0]>4) cimg::warn(_cimg_instance "load_analyze(): File '%s' defines an image with %u dimensions, reading only the 4 first.", cimg_instance, filename?filename:"(FILE*)",dim[0]); if (dim[0]>=1) dimx = dim[1]; if (dim[0]>=2) dimy = dim[2]; if (dim[0]>=3) dimz = dim[3]; if (dim[0]>=4) dimv = dim[4]; float scalefactor = *(float*)(header + 112); if (scalefactor==0) scalefactor = 1; const unsigned short datatype = *(unsigned short*)(header + 70); if (voxel_size) { const float *vsize = (float*)(header + 76); voxel_size[0] = vsize[1]; voxel_size[1] = vsize[2]; voxel_size[2] = vsize[3]; } delete[] header; // Read pixel data. assign(dimx,dimy,dimz,dimv); const size_t pdim = (size_t)dimx*dimy*dimz*dimv; switch (datatype) { case 2 : { unsigned char *const buffer = new unsigned char[pdim]; cimg::fread(buffer,pdim,nfile); cimg_foroff(*this,off) _data[off] = (T)(buffer[off]*scalefactor); delete[] buffer; } break; case 4 : { short *const buffer = new short[pdim]; cimg::fread(buffer,pdim,nfile); if (endian) cimg::invert_endianness(buffer,pdim); cimg_foroff(*this,off) _data[off] = (T)(buffer[off]*scalefactor); delete[] buffer; } break; case 8 : { int *const buffer = new int[pdim]; cimg::fread(buffer,pdim,nfile); if (endian) cimg::invert_endianness(buffer,pdim); cimg_foroff(*this,off) _data[off] = (T)(buffer[off]*scalefactor); delete[] buffer; } break; case 16 : { float *const buffer = new float[pdim]; cimg::fread(buffer,pdim,nfile); if (endian) cimg::invert_endianness(buffer,pdim); cimg_foroff(*this,off) _data[off] = (T)(buffer[off]*scalefactor); delete[] buffer; } break; case 64 : { double *const buffer = new double[pdim]; cimg::fread(buffer,pdim,nfile); if (endian) cimg::invert_endianness(buffer,pdim); cimg_foroff(*this,off) _data[off] = (T)(buffer[off]*scalefactor); delete[] buffer; } break; default : if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_analyze(): Unable to load datatype %d in file '%s'", cimg_instance, datatype,filename?filename:"(FILE*)"); } if (!file) cimg::fclose(nfile); return *this; } //! Load image from a .cimg[z] file. /** \param filename Filename, as a C-string. \param axis Appending axis, if file contains multiple images. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param align Appending alignment. **/ CImg<T>& load_cimg(const char *const filename, const char axis='z', const float align=0) { CImgList<T> list; list.load_cimg(filename); if (list._width==1) return list[0].move_to(*this); return assign(list.get_append(axis,align)); } //! Load image from a .cimg[z] file \newinstance static CImg<T> get_load_cimg(const char *const filename, const char axis='z', const float align=0) { return CImg<T>().load_cimg(filename,axis,align); } //! Load image from a .cimg[z] file \overloading. CImg<T>& load_cimg(std::FILE *const file, const char axis='z', const float align=0) { CImgList<T> list; list.load_cimg(file); if (list._width==1) return list[0].move_to(*this); return assign(list.get_append(axis,align)); } //! Load image from a .cimg[z] file \newinstance static CImg<T> get_load_cimg(std::FILE *const file, const char axis='z', const float align=0) { return CImg<T>().load_cimg(file,axis,align); } //! Load sub-images of a .cimg file. /** \param filename Filename, as a C-string. \param n0 Starting frame. \param n1 Ending frame (~0U for max). \param x0 X-coordinate of the starting sub-image vertex. \param y0 Y-coordinate of the starting sub-image vertex. \param z0 Z-coordinate of the starting sub-image vertex. \param c0 C-coordinate of the starting sub-image vertex. \param x1 X-coordinate of the ending sub-image vertex (~0U for max). \param y1 Y-coordinate of the ending sub-image vertex (~0U for max). \param z1 Z-coordinate of the ending sub-image vertex (~0U for max). \param c1 C-coordinate of the ending sub-image vertex (~0U for max). \param axis Appending axis, if file contains multiple images. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param align Appending alignment. **/ CImg<T>& load_cimg(const char *const filename, const unsigned int n0, const unsigned int n1, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0, const unsigned int x1, const unsigned int y1, const unsigned int z1, const unsigned int c1, const char axis='z', const float align=0) { CImgList<T> list; list.load_cimg(filename,n0,n1,x0,y0,z0,c0,x1,y1,z1,c1); if (list._width==1) return list[0].move_to(*this); return assign(list.get_append(axis,align)); } //! Load sub-images of a .cimg file \newinstance. static CImg<T> get_load_cimg(const char *const filename, const unsigned int n0, const unsigned int n1, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0, const unsigned int x1, const unsigned int y1, const unsigned int z1, const unsigned int c1, const char axis='z', const float align=0) { return CImg<T>().load_cimg(filename,n0,n1,x0,y0,z0,c0,x1,y1,z1,c1,axis,align); } //! Load sub-images of a .cimg file \overloading. CImg<T>& load_cimg(std::FILE *const file, const unsigned int n0, const unsigned int n1, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0, const unsigned int x1, const unsigned int y1, const unsigned int z1, const unsigned int c1, const char axis='z', const float align=0) { CImgList<T> list; list.load_cimg(file,n0,n1,x0,y0,z0,c0,x1,y1,z1,c1); if (list._width==1) return list[0].move_to(*this); return assign(list.get_append(axis,align)); } //! Load sub-images of a .cimg file \newinstance. static CImg<T> get_load_cimg(std::FILE *const file, const unsigned int n0, const unsigned int n1, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0, const unsigned int x1, const unsigned int y1, const unsigned int z1, const unsigned int c1, const char axis='z', const float align=0) { return CImg<T>().load_cimg(file,n0,n1,x0,y0,z0,c0,x1,y1,z1,c1,axis,align); } //! Load image from an INRIMAGE-4 file. /** \param filename Filename, as a C-string. \param[out] voxel_size Pointer to the three voxel sizes read from the file. **/ CImg<T>& load_inr(const char *const filename, float *const voxel_size=0) { return _load_inr(0,filename,voxel_size); } //! Load image from an INRIMAGE-4 file \newinstance. static CImg<T> get_load_inr(const char *const filename, float *const voxel_size=0) { return CImg<T>().load_inr(filename,voxel_size); } //! Load image from an INRIMAGE-4 file \overloading. CImg<T>& load_inr(std::FILE *const file, float *const voxel_size=0) { return _load_inr(file,0,voxel_size); } //! Load image from an INRIMAGE-4 file \newinstance. static CImg<T> get_load_inr(std::FILE *const file, float *voxel_size=0) { return CImg<T>().load_inr(file,voxel_size); } static void _load_inr_header(std::FILE *file, int out[8], float *const voxel_size) { CImg<charT> item(1024), tmp1(64), tmp2(64); *item = *tmp1 = *tmp2 = 0; out[0] = std::fscanf(file,"%63s",item._data); out[0] = out[1] = out[2] = out[3] = out[5] = 1; out[4] = out[6] = out[7] = -1; if (cimg::strncasecmp(item,"#INRIMAGE-4#{",13)!=0) throw CImgIOException("CImg<%s>::load_inr(): INRIMAGE-4 header not found.", pixel_type()); while (std::fscanf(file," %63[^\n]%*c",item._data)!=EOF && std::strncmp(item,"##}",3)) { cimg_sscanf(item," XDIM%*[^0-9]%d",out); cimg_sscanf(item," YDIM%*[^0-9]%d",out + 1); cimg_sscanf(item," ZDIM%*[^0-9]%d",out + 2); cimg_sscanf(item," VDIM%*[^0-9]%d",out + 3); cimg_sscanf(item," PIXSIZE%*[^0-9]%d",out + 6); if (voxel_size) { cimg_sscanf(item," VX%*[^0-9.+-]%f",voxel_size); cimg_sscanf(item," VY%*[^0-9.+-]%f",voxel_size + 1); cimg_sscanf(item," VZ%*[^0-9.+-]%f",voxel_size + 2); } if (cimg_sscanf(item," CPU%*[ =]%s",tmp1._data)) out[7] = cimg::strncasecmp(tmp1,"sun",3)?0:1; switch (cimg_sscanf(item," TYPE%*[ =]%s %s",tmp1._data,tmp2._data)) { case 0 : break; case 2 : out[5] = cimg::strncasecmp(tmp1,"unsigned",8)?1:0; std::strncpy(tmp1,tmp2,tmp1._width - 1); // fallthrough case 1 : if (!cimg::strncasecmp(tmp1,"int",3) || !cimg::strncasecmp(tmp1,"fixed",5)) out[4] = 0; if (!cimg::strncasecmp(tmp1,"float",5) || !cimg::strncasecmp(tmp1,"double",6)) out[4] = 1; if (!cimg::strncasecmp(tmp1,"packed",6)) out[4] = 2; if (out[4]>=0) break; // fallthrough default : throw CImgIOException("CImg<%s>::load_inr(): Invalid pixel type '%s' defined in header.", pixel_type(), tmp2._data); } } if (out[0]<0 || out[1]<0 || out[2]<0 || out[3]<0) throw CImgIOException("CImg<%s>::load_inr(): Invalid dimensions (%d,%d,%d,%d) defined in header.", pixel_type(), out[0],out[1],out[2],out[3]); if (out[4]<0 || out[5]<0) throw CImgIOException("CImg<%s>::load_inr(): Incomplete pixel type defined in header.", pixel_type()); if (out[6]<0) throw CImgIOException("CImg<%s>::load_inr(): Incomplete PIXSIZE field defined in header.", pixel_type()); if (out[7]<0) throw CImgIOException("CImg<%s>::load_inr(): Big/Little Endian coding type undefined in header.", pixel_type()); } CImg<T>& _load_inr(std::FILE *const file, const char *const filename, float *const voxel_size) { #define _cimg_load_inr_case(Tf,sign,pixsize,Ts) \ if (!loaded && fopt[6]==pixsize && fopt[4]==Tf && fopt[5]==sign) { \ Ts *xval, *const val = new Ts[(size_t)fopt[0]*fopt[3]]; \ cimg_forYZ(*this,y,z) { \ cimg::fread(val,fopt[0]*fopt[3],nfile); \ if (fopt[7]!=endian) cimg::invert_endianness(val,fopt[0]*fopt[3]); \ xval = val; cimg_forX(*this,x) cimg_forC(*this,c) (*this)(x,y,z,c) = (T)*(xval++); \ } \ delete[] val; \ loaded = true; \ } if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_inr(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); int fopt[8], endian = cimg::endianness()?1:0; bool loaded = false; if (voxel_size) voxel_size[0] = voxel_size[1] = voxel_size[2] = 1; _load_inr_header(nfile,fopt,voxel_size); assign(fopt[0],fopt[1],fopt[2],fopt[3]); _cimg_load_inr_case(0,0,8,unsigned char); _cimg_load_inr_case(0,1,8,char); _cimg_load_inr_case(0,0,16,unsigned short); _cimg_load_inr_case(0,1,16,short); _cimg_load_inr_case(0,0,32,unsigned int); _cimg_load_inr_case(0,1,32,int); _cimg_load_inr_case(1,0,32,float); _cimg_load_inr_case(1,1,32,float); _cimg_load_inr_case(1,0,64,double); _cimg_load_inr_case(1,1,64,double); if (!loaded) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_inr(): Unknown pixel type defined in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } if (!file) cimg::fclose(nfile); return *this; } //! Load image from a EXR file. /** \param filename Filename, as a C-string. **/ CImg<T>& load_exr(const char *const filename) { if (!filename) throw CImgArgumentException(_cimg_instance "load_exr(): Specified filename is (null).", cimg_instance); #if defined(cimg_use_openexr) Imf::RgbaInputFile file(filename); Imath::Box2i dw = file.dataWindow(); const int inwidth = dw.max.x - dw.min.x + 1, inheight = dw.max.y - dw.min.y + 1; Imf::Array2D<Imf::Rgba> pixels; pixels.resizeErase(inheight,inwidth); file.setFrameBuffer(&pixels[0][0] - dw.min.x - dw.min.y*inwidth, 1, inwidth); file.readPixels(dw.min.y, dw.max.y); assign(inwidth,inheight,1,4); T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2), *ptr_a = data(0,0,0,3); cimg_forXY(*this,x,y) { *(ptr_r++) = (T)pixels[y][x].r; *(ptr_g++) = (T)pixels[y][x].g; *(ptr_b++) = (T)pixels[y][x].b; *(ptr_a++) = (T)pixels[y][x].a; } #elif defined(cimg_use_tinyexr) float *res; const char *err = 0; int width = 0, height = 0; const int ret = LoadEXR(&res,&width,&height,filename,&err); if (ret) throw CImgIOException(_cimg_instance "load_exr(): Unable to load EXR file '%s'.", cimg_instance,filename); CImg<floatT>(out,4,width,height,1,true).get_permute_axes("yzcx").move_to(*this); std::free(res); #else return load_other(filename); #endif return *this; } //! Load image from a EXR file \newinstance. static CImg<T> get_load_exr(const char *const filename) { return CImg<T>().load_exr(filename); } //! Load image from a PANDORE-5 file. /** \param filename Filename, as a C-string. **/ CImg<T>& load_pandore(const char *const filename) { return _load_pandore(0,filename); } //! Load image from a PANDORE-5 file \newinstance. static CImg<T> get_load_pandore(const char *const filename) { return CImg<T>().load_pandore(filename); } //! Load image from a PANDORE-5 file \overloading. CImg<T>& load_pandore(std::FILE *const file) { return _load_pandore(file,0); } //! Load image from a PANDORE-5 file \newinstance. static CImg<T> get_load_pandore(std::FILE *const file) { return CImg<T>().load_pandore(file); } CImg<T>& _load_pandore(std::FILE *const file, const char *const filename) { #define __cimg_load_pandore_case(nbdim,nwidth,nheight,ndepth,ndim,stype) \ cimg::fread(dims,nbdim,nfile); \ if (endian) cimg::invert_endianness(dims,nbdim); \ assign(nwidth,nheight,ndepth,ndim); \ const size_t siz = size(); \ stype *buffer = new stype[siz]; \ cimg::fread(buffer,siz,nfile); \ if (endian) cimg::invert_endianness(buffer,siz); \ T *ptrd = _data; \ cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); \ buffer-=siz; \ delete[] buffer #define _cimg_load_pandore_case(nbdim,nwidth,nheight,ndepth,dim,stype1,stype2,stype3,ltype) { \ if (sizeof(stype1)==ltype) { __cimg_load_pandore_case(nbdim,nwidth,nheight,ndepth,dim,stype1); } \ else if (sizeof(stype2)==ltype) { __cimg_load_pandore_case(nbdim,nwidth,nheight,ndepth,dim,stype2); } \ else if (sizeof(stype3)==ltype) { __cimg_load_pandore_case(nbdim,nwidth,nheight,ndepth,dim,stype3); } \ else throw CImgIOException(_cimg_instance \ "load_pandore(): Unknown pixel datatype in file '%s'.", \ cimg_instance, \ filename?filename:"(FILE*)"); } if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_pandore(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); CImg<charT> header(32); cimg::fread(header._data,12,nfile); if (cimg::strncasecmp("PANDORE",header,7)) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_pandore(): PANDORE header not found in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } unsigned int imageid, dims[8] = { 0 }; int ptbuf[4] = { 0 }; cimg::fread(&imageid,1,nfile); const bool endian = imageid>255; if (endian) cimg::invert_endianness(imageid); cimg::fread(header._data,20,nfile); switch (imageid) { case 2 : _cimg_load_pandore_case(2,dims[1],1,1,1,unsigned char,unsigned char,unsigned char,1); break; case 3 : _cimg_load_pandore_case(2,dims[1],1,1,1,long,int,short,4); break; case 4 : _cimg_load_pandore_case(2,dims[1],1,1,1,double,float,float,4); break; case 5 : _cimg_load_pandore_case(3,dims[2],dims[1],1,1,unsigned char,unsigned char,unsigned char,1); break; case 6 : _cimg_load_pandore_case(3,dims[2],dims[1],1,1,long,int,short,4); break; case 7 : _cimg_load_pandore_case(3,dims[2],dims[1],1,1,double,float,float,4); break; case 8 : _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],1,unsigned char,unsigned char,unsigned char,1); break; case 9 : _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],1,long,int,short,4); break; case 10 : _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],1,double,float,float,4); break; case 11 : { // Region 1D cimg::fread(dims,3,nfile); if (endian) cimg::invert_endianness(dims,3); assign(dims[1],1,1,1); const unsigned siz = size(); if (dims[2]<256) { unsigned char *buffer = new unsigned char[siz]; cimg::fread(buffer,siz,nfile); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } else { if (dims[2]<65536) { unsigned short *buffer = new unsigned short[siz]; cimg::fread(buffer,siz,nfile); if (endian) cimg::invert_endianness(buffer,siz); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } else { unsigned int *buffer = new unsigned int[siz]; cimg::fread(buffer,siz,nfile); if (endian) cimg::invert_endianness(buffer,siz); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } } } break; case 12 : { // Region 2D cimg::fread(dims,4,nfile); if (endian) cimg::invert_endianness(dims,4); assign(dims[2],dims[1],1,1); const size_t siz = size(); if (dims[3]<256) { unsigned char *buffer = new unsigned char[siz]; cimg::fread(buffer,siz,nfile); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } else { if (dims[3]<65536) { unsigned short *buffer = new unsigned short[siz]; cimg::fread(buffer,siz,nfile); if (endian) cimg::invert_endianness(buffer,siz); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } else { unsigned int *buffer = new unsigned int[siz]; cimg::fread(buffer,siz,nfile); if (endian) cimg::invert_endianness(buffer,siz); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } } } break; case 13 : { // Region 3D cimg::fread(dims,5,nfile); if (endian) cimg::invert_endianness(dims,5); assign(dims[3],dims[2],dims[1],1); const size_t siz = size(); if (dims[4]<256) { unsigned char *buffer = new unsigned char[siz]; cimg::fread(buffer,siz,nfile); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } else { if (dims[4]<65536) { unsigned short *buffer = new unsigned short[siz]; cimg::fread(buffer,siz,nfile); if (endian) cimg::invert_endianness(buffer,siz); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } else { unsigned int *buffer = new unsigned int[siz]; cimg::fread(buffer,siz,nfile); if (endian) cimg::invert_endianness(buffer,siz); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } } } break; case 16 : _cimg_load_pandore_case(4,dims[2],dims[1],1,3,unsigned char,unsigned char,unsigned char,1); break; case 17 : _cimg_load_pandore_case(4,dims[2],dims[1],1,3,long,int,short,4); break; case 18 : _cimg_load_pandore_case(4,dims[2],dims[1],1,3,double,float,float,4); break; case 19 : _cimg_load_pandore_case(5,dims[3],dims[2],dims[1],3,unsigned char,unsigned char,unsigned char,1); break; case 20 : _cimg_load_pandore_case(5,dims[3],dims[2],dims[1],3,long,int,short,4); break; case 21 : _cimg_load_pandore_case(5,dims[3],dims[2],dims[1],3,double,float,float,4); break; case 22 : _cimg_load_pandore_case(2,dims[1],1,1,dims[0],unsigned char,unsigned char,unsigned char,1); break; case 23 : _cimg_load_pandore_case(2,dims[1],1,1,dims[0],long,int,short,4); break; case 24 : _cimg_load_pandore_case(2,dims[1],1,1,dims[0],unsigned long,unsigned int,unsigned short,4); break; case 25 : _cimg_load_pandore_case(2,dims[1],1,1,dims[0],double,float,float,4); break; case 26 : _cimg_load_pandore_case(3,dims[2],dims[1],1,dims[0],unsigned char,unsigned char,unsigned char,1); break; case 27 : _cimg_load_pandore_case(3,dims[2],dims[1],1,dims[0],long,int,short,4); break; case 28 : _cimg_load_pandore_case(3,dims[2],dims[1],1,dims[0],unsigned long,unsigned int,unsigned short,4); break; case 29 : _cimg_load_pandore_case(3,dims[2],dims[1],1,dims[0],double,float,float,4); break; case 30 : _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],dims[0],unsigned char,unsigned char,unsigned char,1); break; case 31 : _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],dims[0],long,int,short,4); break; case 32 : _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],dims[0],unsigned long,unsigned int,unsigned short,4); break; case 33 : _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],dims[0],double,float,float,4); break; case 34 : { // Points 1D cimg::fread(ptbuf,1,nfile); if (endian) cimg::invert_endianness(ptbuf,1); assign(1); (*this)(0) = (T)ptbuf[0]; } break; case 35 : { // Points 2D cimg::fread(ptbuf,2,nfile); if (endian) cimg::invert_endianness(ptbuf,2); assign(2); (*this)(0) = (T)ptbuf[1]; (*this)(1) = (T)ptbuf[0]; } break; case 36 : { // Points 3D cimg::fread(ptbuf,3,nfile); if (endian) cimg::invert_endianness(ptbuf,3); assign(3); (*this)(0) = (T)ptbuf[2]; (*this)(1) = (T)ptbuf[1]; (*this)(2) = (T)ptbuf[0]; } break; default : if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_pandore(): Unable to load data with ID_type %u in file '%s'.", cimg_instance, imageid,filename?filename:"(FILE*)"); } if (!file) cimg::fclose(nfile); return *this; } //! Load image from a PAR-REC (Philips) file. /** \param filename Filename, as a C-string. \param axis Appending axis, if file contains multiple images. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param align Appending alignment. **/ CImg<T>& load_parrec(const char *const filename, const char axis='c', const float align=0) { CImgList<T> list; list.load_parrec(filename); if (list._width==1) return list[0].move_to(*this); return assign(list.get_append(axis,align)); } //! Load image from a PAR-REC (Philips) file \newinstance. static CImg<T> get_load_parrec(const char *const filename, const char axis='c', const float align=0) { return CImg<T>().load_parrec(filename,axis,align); } //! Load image from a raw binary file. /** \param filename Filename, as a C-string. \param size_x Width of the image buffer. \param size_y Height of the image buffer. \param size_z Depth of the image buffer. \param size_c Spectrum of the image buffer. \param is_multiplexed Tells if the image values are multiplexed along the C-axis. \param invert_endianness Tells if the endianness of the image buffer must be inverted. \param offset Starting offset of the read in the specified file. **/ CImg<T>& load_raw(const char *const filename, const unsigned int size_x=0, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1, const bool is_multiplexed=false, const bool invert_endianness=false, const ulongT offset=0) { return _load_raw(0,filename,size_x,size_y,size_z,size_c,is_multiplexed,invert_endianness,offset); } //! Load image from a raw binary file \newinstance. static CImg<T> get_load_raw(const char *const filename, const unsigned int size_x=0, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1, const bool is_multiplexed=false, const bool invert_endianness=false, const ulongT offset=0) { return CImg<T>().load_raw(filename,size_x,size_y,size_z,size_c,is_multiplexed,invert_endianness,offset); } //! Load image from a raw binary file \overloading. CImg<T>& load_raw(std::FILE *const file, const unsigned int size_x=0, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1, const bool is_multiplexed=false, const bool invert_endianness=false, const ulongT offset=0) { return _load_raw(file,0,size_x,size_y,size_z,size_c,is_multiplexed,invert_endianness,offset); } //! Load image from a raw binary file \newinstance. static CImg<T> get_load_raw(std::FILE *const file, const unsigned int size_x=0, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1, const bool is_multiplexed=false, const bool invert_endianness=false, const ulongT offset=0) { return CImg<T>().load_raw(file,size_x,size_y,size_z,size_c,is_multiplexed,invert_endianness,offset); } CImg<T>& _load_raw(std::FILE *const file, const char *const filename, const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const bool is_multiplexed, const bool invert_endianness, const ulongT offset) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_raw(): Specified filename is (null).", cimg_instance); if (cimg::is_directory(filename)) throw CImgArgumentException(_cimg_instance "load_raw(): Specified filename '%s' is a directory.", cimg_instance,filename); ulongT siz = (ulongT)size_x*size_y*size_z*size_c; unsigned int _size_x = size_x, _size_y = size_y, _size_z = size_z, _size_c = size_c; std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); if (!siz) { // Retrieve file size const longT fpos = cimg::ftell(nfile); if (fpos<0) throw CImgArgumentException(_cimg_instance "load_raw(): Cannot determine size of input file '%s'.", cimg_instance,filename?filename:"(FILE*)"); cimg::fseek(nfile,0,SEEK_END); siz = cimg::ftell(nfile)/sizeof(T); _size_y = (unsigned int)siz; _size_x = _size_z = _size_c = 1; cimg::fseek(nfile,fpos,SEEK_SET); } cimg::fseek(nfile,offset,SEEK_SET); assign(_size_x,_size_y,_size_z,_size_c,0); if (siz && (!is_multiplexed || size_c==1)) { cimg::fread(_data,siz,nfile); if (invert_endianness) cimg::invert_endianness(_data,siz); } else if (siz) { CImg<T> buf(1,1,1,_size_c); cimg_forXYZ(*this,x,y,z) { cimg::fread(buf._data,_size_c,nfile); if (invert_endianness) cimg::invert_endianness(buf._data,_size_c); set_vector_at(buf,x,y,z); } } if (!file) cimg::fclose(nfile); return *this; } //! Load image sequence from a YUV file. /** \param filename Filename, as a C-string. \param size_x Width of the frames. \param size_y Height of the frames. \param chroma_subsampling Type of chroma subsampling. Can be <tt>{ 420 | 422 | 444 }</tt>. \param first_frame Index of the first frame to read. \param last_frame Index of the last frame to read. \param step_frame Step value for frame reading. \param yuv2rgb Tells if the YUV to RGB transform must be applied. \param axis Appending axis, if file contains multiple images. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. **/ CImg<T>& load_yuv(const char *const filename, const unsigned int size_x, const unsigned int size_y=1, const unsigned int chroma_subsampling=444, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const bool yuv2rgb=true, const char axis='z') { return get_load_yuv(filename,size_x,size_y,chroma_subsampling, first_frame,last_frame,step_frame,yuv2rgb,axis).move_to(*this); } //! Load image sequence from a YUV file \newinstance. static CImg<T> get_load_yuv(const char *const filename, const unsigned int size_x, const unsigned int size_y=1, const unsigned int chroma_subsampling=444, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const bool yuv2rgb=true, const char axis='z') { return CImgList<T>().load_yuv(filename,size_x,size_y,chroma_subsampling, first_frame,last_frame,step_frame,yuv2rgb).get_append(axis); } //! Load image sequence from a YUV file \overloading. CImg<T>& load_yuv(std::FILE *const file, const unsigned int size_x, const unsigned int size_y=1, const unsigned int chroma_subsampling=444, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const bool yuv2rgb=true, const char axis='z') { return get_load_yuv(file,size_x,size_y,chroma_subsampling, first_frame,last_frame,step_frame,yuv2rgb,axis).move_to(*this); } //! Load image sequence from a YUV file \newinstance. static CImg<T> get_load_yuv(std::FILE *const file, const unsigned int size_x, const unsigned int size_y=1, const unsigned int chroma_subsampling=444, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const bool yuv2rgb=true, const char axis='z') { return CImgList<T>().load_yuv(file,size_x,size_y,chroma_subsampling, first_frame,last_frame,step_frame,yuv2rgb).get_append(axis); } //! Load 3D object from a .OFF file. /** \param[out] primitives Primitives data of the 3D object. \param[out] colors Colors data of the 3D object. \param filename Filename, as a C-string. **/ template<typename tf, typename tc> CImg<T>& load_off(CImgList<tf>& primitives, CImgList<tc>& colors, const char *const filename) { return _load_off(primitives,colors,0,filename); } //! Load 3D object from a .OFF file \newinstance. template<typename tf, typename tc> static CImg<T> get_load_off(CImgList<tf>& primitives, CImgList<tc>& colors, const char *const filename) { return CImg<T>().load_off(primitives,colors,filename); } //! Load 3D object from a .OFF file \overloading. template<typename tf, typename tc> CImg<T>& load_off(CImgList<tf>& primitives, CImgList<tc>& colors, std::FILE *const file) { return _load_off(primitives,colors,file,0); } //! Load 3D object from a .OFF file \newinstance. template<typename tf, typename tc> static CImg<T> get_load_off(CImgList<tf>& primitives, CImgList<tc>& colors, std::FILE *const file) { return CImg<T>().load_off(primitives,colors,file); } template<typename tf, typename tc> CImg<T>& _load_off(CImgList<tf>& primitives, CImgList<tc>& colors, std::FILE *const file, const char *const filename) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_off(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"r"); unsigned int nb_points = 0, nb_primitives = 0, nb_read = 0; CImg<charT> line(256); *line = 0; int err; // Skip comments, and read magic string OFF do { err = std::fscanf(nfile,"%255[^\n] ",line._data); } while (!err || (err==1 && *line=='#')); if (cimg::strncasecmp(line,"OFF",3) && cimg::strncasecmp(line,"COFF",4)) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_off(): OFF header not found in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } do { err = std::fscanf(nfile,"%255[^\n] ",line._data); } while (!err || (err==1 && *line=='#')); if ((err = cimg_sscanf(line,"%u%u%*[^\n] ",&nb_points,&nb_primitives))!=2) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_off(): Invalid number of vertices or primitives specified in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } // Read points data assign(nb_points,3); float X = 0, Y = 0, Z = 0; cimg_forX(*this,l) { do { err = std::fscanf(nfile,"%255[^\n] ",line._data); } while (!err || (err==1 && *line=='#')); if ((err = cimg_sscanf(line,"%f%f%f%*[^\n] ",&X,&Y,&Z))!=3) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_off(): Failed to read vertex %u/%u in file '%s'.", cimg_instance, l + 1,nb_points,filename?filename:"(FILE*)"); } (*this)(l,0) = (T)X; (*this)(l,1) = (T)Y; (*this)(l,2) = (T)Z; } // Read primitive data primitives.assign(); colors.assign(); bool stop_flag = false; while (!stop_flag) { float c0 = 0.7f, c1 = 0.7f, c2 = 0.7f; unsigned int prim = 0, i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0, i6 = 0, i7 = 0; *line = 0; if ((err = std::fscanf(nfile,"%u",&prim))!=1) stop_flag = true; else { ++nb_read; switch (prim) { case 1 : { if ((err = std::fscanf(nfile,"%u%255[^\n] ",&i0,line._data))<2) { cimg::warn(_cimg_instance "load_off(): Failed to read primitive %u/%u from file '%s'.", cimg_instance, nb_read,nb_primitives,filename?filename:"(FILE*)"); err = std::fscanf(nfile,"%*[^\n] "); } else { err = cimg_sscanf(line,"%f%f%f",&c0,&c1,&c2); CImg<tf>::vector(i0).move_to(primitives); CImg<tc>::vector((tc)(c0*255),(tc)(c1*255),(tc)(c2*255)).move_to(colors); } } break; case 2 : { if ((err = std::fscanf(nfile,"%u%u%255[^\n] ",&i0,&i1,line._data))<2) { cimg::warn(_cimg_instance "load_off(): Failed to read primitive %u/%u from file '%s'.", cimg_instance, nb_read,nb_primitives,filename?filename:"(FILE*)"); err = std::fscanf(nfile,"%*[^\n] "); } else { err = cimg_sscanf(line,"%f%f%f",&c0,&c1,&c2); CImg<tf>::vector(i0,i1).move_to(primitives); CImg<tc>::vector((tc)(c0*255),(tc)(c1*255),(tc)(c2*255)).move_to(colors); } } break; case 3 : { if ((err = std::fscanf(nfile,"%u%u%u%255[^\n] ",&i0,&i1,&i2,line._data))<3) { cimg::warn(_cimg_instance "load_off(): Failed to read primitive %u/%u from file '%s'.", cimg_instance, nb_read,nb_primitives,filename?filename:"(FILE*)"); err = std::fscanf(nfile,"%*[^\n] "); } else { err = cimg_sscanf(line,"%f%f%f",&c0,&c1,&c2); CImg<tf>::vector(i0,i2,i1).move_to(primitives); CImg<tc>::vector((tc)(c0*255),(tc)(c1*255),(tc)(c2*255)).move_to(colors); } } break; case 4 : { if ((err = std::fscanf(nfile,"%u%u%u%u%255[^\n] ",&i0,&i1,&i2,&i3,line._data))<4) { cimg::warn(_cimg_instance "load_off(): Failed to read primitive %u/%u from file '%s'.", cimg_instance, nb_read,nb_primitives,filename?filename:"(FILE*)"); err = std::fscanf(nfile,"%*[^\n] "); } else { err = cimg_sscanf(line,"%f%f%f",&c0,&c1,&c2); CImg<tf>::vector(i0,i3,i2,i1).move_to(primitives); CImg<tc>::vector((tc)(c0*255),(tc)(c1*255),(tc)(c2*255)).move_to(colors); } } break; case 5 : { if ((err = std::fscanf(nfile,"%u%u%u%u%u%255[^\n] ",&i0,&i1,&i2,&i3,&i4,line._data))<5) { cimg::warn(_cimg_instance "load_off(): Failed to read primitive %u/%u from file '%s'.", cimg_instance, nb_read,nb_primitives,filename?filename:"(FILE*)"); err = std::fscanf(nfile,"%*[^\n] "); } else { err = cimg_sscanf(line,"%f%f%f",&c0,&c1,&c2); CImg<tf>::vector(i0,i3,i2,i1).move_to(primitives); CImg<tf>::vector(i0,i4,i3).move_to(primitives); colors.insert(2,CImg<tc>::vector((tc)(c0*255),(tc)(c1*255),(tc)(c2*255))); ++nb_primitives; } } break; case 6 : { if ((err = std::fscanf(nfile,"%u%u%u%u%u%u%255[^\n] ",&i0,&i1,&i2,&i3,&i4,&i5,line._data))<6) { cimg::warn(_cimg_instance "load_off(): Failed to read primitive %u/%u from file '%s'.", cimg_instance, nb_read,nb_primitives,filename?filename:"(FILE*)"); err = std::fscanf(nfile,"%*[^\n] "); } else { err = cimg_sscanf(line,"%f%f%f",&c0,&c1,&c2); CImg<tf>::vector(i0,i3,i2,i1).move_to(primitives); CImg<tf>::vector(i0,i5,i4,i3).move_to(primitives); colors.insert(2,CImg<tc>::vector((tc)(c0*255),(tc)(c1*255),(tc)(c2*255))); ++nb_primitives; } } break; case 7 : { if ((err = std::fscanf(nfile,"%u%u%u%u%u%u%u%255[^\n] ",&i0,&i1,&i2,&i3,&i4,&i5,&i6,line._data))<7) { cimg::warn(_cimg_instance "load_off(): Failed to read primitive %u/%u from file '%s'.", cimg_instance, nb_read,nb_primitives,filename?filename:"(FILE*)"); err = std::fscanf(nfile,"%*[^\n] "); } else { err = cimg_sscanf(line,"%f%f%f",&c0,&c1,&c2); CImg<tf>::vector(i0,i4,i3,i1).move_to(primitives); CImg<tf>::vector(i0,i6,i5,i4).move_to(primitives); CImg<tf>::vector(i3,i2,i1).move_to(primitives); colors.insert(3,CImg<tc>::vector((tc)(c0*255),(tc)(c1*255),(tc)(c2*255))); ++(++nb_primitives); } } break; case 8 : { if ((err = std::fscanf(nfile,"%u%u%u%u%u%u%u%u%255[^\n] ",&i0,&i1,&i2,&i3,&i4,&i5,&i6,&i7,line._data))<7) { cimg::warn(_cimg_instance "load_off(): Failed to read primitive %u/%u from file '%s'.", cimg_instance, nb_read,nb_primitives,filename?filename:"(FILE*)"); err = std::fscanf(nfile,"%*[^\n] "); } else { err = cimg_sscanf(line,"%f%f%f",&c0,&c1,&c2); CImg<tf>::vector(i0,i3,i2,i1).move_to(primitives); CImg<tf>::vector(i0,i5,i4,i3).move_to(primitives); CImg<tf>::vector(i0,i7,i6,i5).move_to(primitives); colors.insert(3,CImg<tc>::vector((tc)(c0*255),(tc)(c1*255),(tc)(c2*255))); ++(++nb_primitives); } } break; default : cimg::warn(_cimg_instance "load_off(): Failed to read primitive %u/%u (%u vertices) from file '%s'.", cimg_instance, nb_read,nb_primitives,prim,filename?filename:"(FILE*)"); err = std::fscanf(nfile,"%*[^\n] "); } } } if (!file) cimg::fclose(nfile); if (primitives._width!=nb_primitives) cimg::warn(_cimg_instance "load_off(): Only %u/%u primitives read from file '%s'.", cimg_instance, primitives._width,nb_primitives,filename?filename:"(FILE*)"); return *this; } //! Load image sequence from a video file, using OpenCV library. /** \param filename Filename, as a C-string. \param first_frame Index of the first frame to read. \param last_frame Index of the last frame to read. \param step_frame Step value for frame reading. \param axis Alignment axis. \param align Apending alignment. **/ CImg<T>& load_video(const char *const filename, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const char axis='z', const float align=0) { return get_load_video(filename,first_frame,last_frame,step_frame,axis,align).move_to(*this); } //! Load image sequence from a video file, using OpenCV library \newinstance. static CImg<T> get_load_video(const char *const filename, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const char axis='z', const float align=0) { return CImgList<T>().load_video(filename,first_frame,last_frame,step_frame).get_append(axis,align); } //! Load image sequence using FFMPEG's external tool 'ffmpeg'. /** \param filename Filename, as a C-string. \param axis Appending axis, if file contains multiple images. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param align Appending alignment. **/ CImg<T>& load_ffmpeg_external(const char *const filename, const char axis='z', const float align=0) { return get_load_ffmpeg_external(filename,axis,align).move_to(*this); } //! Load image sequence using FFMPEG's external tool 'ffmpeg' \newinstance. static CImg<T> get_load_ffmpeg_external(const char *const filename, const char axis='z', const float align=0) { return CImgList<T>().load_ffmpeg_external(filename).get_append(axis,align); } //! Load gif file, using Imagemagick or GraphicsMagicks's external tools. /** \param filename Filename, as a C-string. \param axis Appending axis, if file contains multiple images. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param align Appending alignment. **/ CImg<T>& load_gif_external(const char *const filename, const char axis='z', const float align=0) { return get_load_gif_external(filename,axis,align).move_to(*this); } //! Load gif file, using ImageMagick or GraphicsMagick's external tool 'convert' \newinstance. static CImg<T> get_load_gif_external(const char *const filename, const char axis='z', const float align=0) { return CImgList<T>().load_gif_external(filename).get_append(axis,align); } //! Load image using GraphicsMagick's external tool 'gm'. /** \param filename Filename, as a C-string. **/ CImg<T>& load_graphicsmagick_external(const char *const filename) { if (!filename) throw CImgArgumentException(_cimg_instance "load_graphicsmagick_external(): Specified filename is (null).", cimg_instance); cimg::fclose(cimg::fopen(filename,"rb")); // Check if file exists CImg<charT> command(1024), filename_tmp(256); std::FILE *file = 0; const CImg<charT> s_filename = CImg<charT>::string(filename)._system_strescape(); #if cimg_OS==1 if (!cimg::system("which gm")) { cimg_snprintf(command,command._width,"%s convert \"%s\" pnm:-", cimg::graphicsmagick_path(),s_filename.data()); file = popen(command,"r"); if (file) { const unsigned int omode = cimg::exception_mode(); cimg::exception_mode(0); try { load_pnm(file); } catch (...) { pclose(file); cimg::exception_mode(omode); throw CImgIOException(_cimg_instance "load_graphicsmagick_external(): Failed to load file '%s' " "with external command 'gm'.", cimg_instance, filename); } pclose(file); return *this; } } #endif do { cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.pnm", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); if ((file=cimg::std_fopen(filename_tmp,"rb"))!=0) cimg::fclose(file); } while (file); cimg_snprintf(command,command._width,"%s convert \"%s\" \"%s\"", cimg::graphicsmagick_path(),s_filename.data(), CImg<charT>::string(filename_tmp)._system_strescape().data()); cimg::system(command,cimg::graphicsmagick_path()); if (!(file=cimg::std_fopen(filename_tmp,"rb"))) { cimg::fclose(cimg::fopen(filename,"r")); throw CImgIOException(_cimg_instance "load_graphicsmagick_external(): Failed to load file '%s' with external command 'gm'.", cimg_instance, filename); } else cimg::fclose(file); load_pnm(filename_tmp); std::remove(filename_tmp); return *this; } //! Load image using GraphicsMagick's external tool 'gm' \newinstance. static CImg<T> get_load_graphicsmagick_external(const char *const filename) { return CImg<T>().load_graphicsmagick_external(filename); } //! Load gzipped image file, using external tool 'gunzip'. /** \param filename Filename, as a C-string. **/ CImg<T>& load_gzip_external(const char *const filename) { if (!filename) throw CImgIOException(_cimg_instance "load_gzip_external(): Specified filename is (null).", cimg_instance); cimg::fclose(cimg::fopen(filename,"rb")); // Check if file exists CImg<charT> command(1024), filename_tmp(256), body(256); const char *const ext = cimg::split_filename(filename,body), *const ext2 = cimg::split_filename(body,0); std::FILE *file = 0; do { if (!cimg::strcasecmp(ext,"gz")) { if (*ext2) cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),ext2); else cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); } else { if (*ext) cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),ext); else cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); } if ((file=cimg::std_fopen(filename_tmp,"rb"))!=0) cimg::fclose(file); } while (file); cimg_snprintf(command,command._width,"%s -c \"%s\" > \"%s\"", cimg::gunzip_path(), CImg<charT>::string(filename)._system_strescape().data(), CImg<charT>::string(filename_tmp)._system_strescape().data()); cimg::system(command); if (!(file=cimg::std_fopen(filename_tmp,"rb"))) { cimg::fclose(cimg::fopen(filename,"r")); throw CImgIOException(_cimg_instance "load_gzip_external(): Failed to load file '%s' with external command 'gunzip'.", cimg_instance, filename); } else cimg::fclose(file); load(filename_tmp); std::remove(filename_tmp); return *this; } //! Load gzipped image file, using external tool 'gunzip' \newinstance. static CImg<T> get_load_gzip_external(const char *const filename) { return CImg<T>().load_gzip_external(filename); } //! Load image using ImageMagick's external tool 'convert'. /** \param filename Filename, as a C-string. **/ CImg<T>& load_imagemagick_external(const char *const filename) { if (!filename) throw CImgArgumentException(_cimg_instance "load_imagemagick_external(): Specified filename is (null).", cimg_instance); cimg::fclose(cimg::fopen(filename,"rb")); // Check if file exists CImg<charT> command(1024), filename_tmp(256); std::FILE *file = 0; const CImg<charT> s_filename = CImg<charT>::string(filename)._system_strescape(); #if cimg_OS==1 if (!cimg::system("which convert")) { cimg_snprintf(command,command._width,"%s%s \"%s\" pnm:-", cimg::imagemagick_path(), !cimg::strcasecmp(cimg::split_filename(filename),"pdf")?" -density 400x400":"", s_filename.data()); file = popen(command,"r"); if (file) { const unsigned int omode = cimg::exception_mode(); cimg::exception_mode(0); try { load_pnm(file); } catch (...) { pclose(file); cimg::exception_mode(omode); throw CImgIOException(_cimg_instance "load_imagemagick_external(): Failed to load file '%s' with " "external command 'magick/convert'.", cimg_instance, filename); } pclose(file); return *this; } } #endif do { cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.pnm", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); if ((file=cimg::std_fopen(filename_tmp,"rb"))!=0) cimg::fclose(file); } while (file); cimg_snprintf(command,command._width,"%s%s \"%s\" \"%s\"", cimg::imagemagick_path(), !cimg::strcasecmp(cimg::split_filename(filename),"pdf")?" -density 400x400":"", s_filename.data(),CImg<charT>::string(filename_tmp)._system_strescape().data()); cimg::system(command,cimg::imagemagick_path()); if (!(file=cimg::std_fopen(filename_tmp,"rb"))) { cimg::fclose(cimg::fopen(filename,"r")); throw CImgIOException(_cimg_instance "load_imagemagick_external(): Failed to load file '%s' with " "external command 'magick/convert'.", cimg_instance, filename); } else cimg::fclose(file); load_pnm(filename_tmp); std::remove(filename_tmp); return *this; } //! Load image using ImageMagick's external tool 'convert' \newinstance. static CImg<T> get_load_imagemagick_external(const char *const filename) { return CImg<T>().load_imagemagick_external(filename); } //! Load image from a DICOM file, using XMedcon's external tool 'medcon'. /** \param filename Filename, as a C-string. **/ CImg<T>& load_medcon_external(const char *const filename) { if (!filename) throw CImgArgumentException(_cimg_instance "load_medcon_external(): Specified filename is (null).", cimg_instance); cimg::fclose(cimg::fopen(filename,"rb")); // Check if file exists CImg<charT> command(1024), filename_tmp(256), body(256); cimg::fclose(cimg::fopen(filename,"r")); std::FILE *file = 0; do { cimg_snprintf(filename_tmp,filename_tmp._width,"%s.hdr",cimg::filenamerand()); if ((file=cimg::std_fopen(filename_tmp,"rb"))!=0) cimg::fclose(file); } while (file); cimg_snprintf(command,command._width,"%s -w -c anlz -o \"%s\" -f \"%s\"", cimg::medcon_path(), CImg<charT>::string(filename_tmp)._system_strescape().data(), CImg<charT>::string(filename)._system_strescape().data()); cimg::system(command); cimg::split_filename(filename_tmp,body); cimg_snprintf(command,command._width,"%s.hdr",body._data); file = cimg::std_fopen(command,"rb"); if (!file) { cimg_snprintf(command,command._width,"m000-%s.hdr",body._data); file = cimg::std_fopen(command,"rb"); if (!file) { throw CImgIOException(_cimg_instance "load_medcon_external(): Failed to load file '%s' with external command 'medcon'.", cimg_instance, filename); } } cimg::fclose(file); load_analyze(command); std::remove(command); cimg::split_filename(command,body); cimg_snprintf(command,command._width,"%s.img",body._data); std::remove(command); return *this; } //! Load image from a DICOM file, using XMedcon's external tool 'medcon' \newinstance. static CImg<T> get_load_medcon_external(const char *const filename) { return CImg<T>().load_medcon_external(filename); } //! Load image from a RAW Color Camera file, using external tool 'dcraw'. /** \param filename Filename, as a C-string. **/ CImg<T>& load_dcraw_external(const char *const filename) { if (!filename) throw CImgArgumentException(_cimg_instance "load_dcraw_external(): Specified filename is (null).", cimg_instance); cimg::fclose(cimg::fopen(filename,"rb")); // Check if file exists CImg<charT> command(1024), filename_tmp(256); std::FILE *file = 0; const CImg<charT> s_filename = CImg<charT>::string(filename)._system_strescape(); #if cimg_OS==1 cimg_snprintf(command,command._width,"%s -w -4 -c \"%s\"", cimg::dcraw_path(),s_filename.data()); file = popen(command,"r"); if (file) { const unsigned int omode = cimg::exception_mode(); cimg::exception_mode(0); try { load_pnm(file); } catch (...) { pclose(file); cimg::exception_mode(omode); throw CImgIOException(_cimg_instance "load_dcraw_external(): Failed to load file '%s' with external command 'dcraw'.", cimg_instance, filename); } pclose(file); return *this; } #endif do { cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.ppm", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); if ((file=cimg::std_fopen(filename_tmp,"rb"))!=0) cimg::fclose(file); } while (file); cimg_snprintf(command,command._width,"%s -w -4 -c \"%s\" > \"%s\"", cimg::dcraw_path(),s_filename.data(),CImg<charT>::string(filename_tmp)._system_strescape().data()); cimg::system(command,cimg::dcraw_path()); if (!(file=cimg::std_fopen(filename_tmp,"rb"))) { cimg::fclose(cimg::fopen(filename,"r")); throw CImgIOException(_cimg_instance "load_dcraw_external(): Failed to load file '%s' with external command 'dcraw'.", cimg_instance, filename); } else cimg::fclose(file); load_pnm(filename_tmp); std::remove(filename_tmp); return *this; } //! Load image from a RAW Color Camera file, using external tool 'dcraw' \newinstance. static CImg<T> get_load_dcraw_external(const char *const filename) { return CImg<T>().load_dcraw_external(filename); } #ifdef cimg_use_opencv // Convert a continuous cv::Mat<uchar> to a CImg<uchar>. static CImg<ucharT> _cvmat2cimg(const cv::Mat &src) { if (src.channels()==1) return CImg<ucharT>(src.ptr(),src.cols,src.rows,1,1); else if (src.channels()==3) { // BGR CImg<ucharT> res(src.cols,src.rows,1,src.channels()); const unsigned char *ptrs = src.ptr(); unsigned char *pR = res.data(), *pG = res.data(0,0,0,1), *pB = res.data(0,0,0,2); cimg_forXY(res,x,y) { *(pB++) = *(ptrs++); *(pG++) = *(ptrs++); *(pR++) = *(ptrs++); } return res; } return CImg<ucharT>(src.ptr(),src.channels(),src.cols,src.rows,1,true).get_permute_axes("yzcx"); } // Convert a CImg<T> to a cv::Mat. cv::Mat _cimg2cvmat() const { if (is_empty()) throw CImgInstanceException(_cimg_instance "_cimg2cvmat() : Instance image is empty.", cimg_instance); if (_spectrum==2) throw CImgInstanceException(_cimg_instance "_cimg2cvmat() : Invalid number of channels (should be '1' or '3+').", cimg_instance); if (_depth!=1) throw CImgInstanceException(_cimg_instance "_cimg2cvmat() : Invalid number of slices (should be '1').", cimg_instance); int mat_type = -1; if (cimg::type<T>::string()==cimg::type<unsigned char>::string()) mat_type = CV_8UC1; if (cimg::type<T>::string()==cimg::type<char>::string()) mat_type = CV_8SC1; if (cimg::type<T>::string()==cimg::type<unsigned short>::string()) mat_type = CV_16UC1; if (cimg::type<T>::string()==cimg::type<short>::string()) mat_type = CV_16SC1; if (cimg::type<T>::string()==cimg::type<int>::string()) mat_type = CV_32SC1; if (cimg::type<T>::string()==cimg::type<float>::string()) mat_type = CV_32FC1; if (cimg::type<T>::string()==cimg::type<double>::string()) mat_type = CV_64FC1; if (mat_type<0) throw CImgInstanceException(_cimg_instance "_cvmat2cimg() : pixel type '%s' is not supported.", cimg_instance,pixel_type()); cv::Mat res; std::vector<cv::Mat> channels(_spectrum); if (_spectrum>1) { cimg_forC(*this,c) channels[c] = cv::Mat(_height,_width,mat_type,_data + _width*_height*(_spectrum - 1 - c)); cv::merge(channels,res); } else res = cv::Mat(_height,_width,mat_type,_data).clone(); return res; } #endif //! Load image from a camera stream, using OpenCV. /** \param index Index of the camera to capture images from (from 0 to 63). \param capture_width Width of the desired image ('0' stands for default value). \param capture_height Height of the desired image ('0' stands for default value). \param skip_frames Number of frames to skip before the capture. \param release_camera Tells if the camera ressource must be released at the end of the method. **/ CImg<T>& load_camera(const unsigned int camera_index=0, const unsigned int capture_width=0, const unsigned int capture_height=0, const unsigned int skip_frames=0, const bool release_camera=true) { #ifdef cimg_use_opencv if (camera_index>=64) throw CImgArgumentException(_cimg_instance "load_camera(): Invalid request for camera #%u " "(no more than 100 cameras can be managed simultaneously).", cimg_instance, camera_index); static cv::VideoCapture *captures[64] = { 0 }; static unsigned int captures_w[64], captures_h[64]; if (release_camera) { cimg::mutex(9); if (captures[camera_index]) captures[camera_index]->release(); delete captures[camera_index]; captures[camera_index] = 0; captures_w[camera_index] = captures_h[camera_index] = 0; cimg::mutex(9,0); return *this; } if (!captures[camera_index]) { cimg::mutex(9); captures[camera_index] = new cv::VideoCapture(camera_index); captures_w[camera_index] = captures_h[camera_index] = 0; if (!captures[camera_index]->isOpened()) { delete captures[camera_index]; captures[camera_index] = 0; cimg::mutex(9,0); throw CImgIOException(_cimg_instance "load_camera(): Failed to initialize camera #%u.", cimg_instance, camera_index); } cimg::mutex(9,0); } cimg::mutex(9); if (capture_width!=captures_w[camera_index]) { captures[camera_index]->set(_cimg_cap_prop_frame_width,capture_width); captures_w[camera_index] = capture_width; } if (capture_height!=captures_h[camera_index]) { captures[camera_index]->set(_cimg_cap_prop_frame_height,capture_height); captures_h[camera_index] = capture_height; } for (unsigned int i = 0; i<skip_frames; ++i) captures[camera_index]->grab(); cv::Mat cvimg; captures[camera_index]->read(cvimg); if (cvimg.empty()) assign(); else _cvmat2cimg(cvimg).move_to(*this); cimg::mutex(9,0); return *this; #else cimg::unused(camera_index,skip_frames,release_camera,capture_width,capture_height); throw CImgIOException(_cimg_instance "load_camera(): This function requires the OpenCV library to run " "(macro 'cimg_use_opencv' must be defined).", cimg_instance); #endif } //! Load image from a camera stream, using OpenCV \newinstance. static CImg<T> get_load_camera(const unsigned int camera_index=0, const unsigned int capture_width=0, const unsigned int capture_height=0, const unsigned int skip_frames=0, const bool release_camera=true) { return CImg<T>().load_camera(camera_index,capture_width,capture_height,skip_frames,release_camera); } //! Load image using various non-native ways. /** \param filename Filename, as a C-string. **/ CImg<T>& load_other(const char *const filename) { if (!filename) throw CImgArgumentException(_cimg_instance "load_other(): Specified filename is (null).", cimg_instance); const unsigned int omode = cimg::exception_mode(); cimg::exception_mode(0); try { load_magick(filename); } catch (CImgException&) { try { load_imagemagick_external(filename); } catch (CImgException&) { try { load_graphicsmagick_external(filename); } catch (CImgException&) { try { load_cimg(filename); } catch (CImgException&) { try { cimg::fclose(cimg::fopen(filename,"rb")); } catch (CImgException&) { cimg::exception_mode(omode); throw CImgIOException(_cimg_instance "load_other(): Failed to open file '%s'.", cimg_instance, filename); } cimg::exception_mode(omode); throw CImgIOException(_cimg_instance "load_other(): Failed to recognize format of file '%s'.", cimg_instance, filename); } } } } cimg::exception_mode(omode); return *this; } //! Load image using various non-native ways \newinstance. static CImg<T> get_load_other(const char *const filename) { return CImg<T>().load_other(filename); } //@} //--------------------------- // //! \name Data Output //@{ //--------------------------- //! Display information about the image data. /** \param title Name for the considered image. \param display_stats Tells to compute and display image statistics. **/ const CImg<T>& print(const char *const title=0, const bool display_stats=true) const { int xm = 0, ym = 0, zm = 0, vm = 0, xM = 0, yM = 0, zM = 0, vM = 0; CImg<doubleT> st; if (!is_empty() && display_stats) { st = get_stats(); xm = (int)st[4]; ym = (int)st[5], zm = (int)st[6], vm = (int)st[7]; xM = (int)st[8]; yM = (int)st[9], zM = (int)st[10], vM = (int)st[11]; } const ulongT siz = size(), msiz = siz*sizeof(T), siz1 = siz - 1, mdisp = msiz<8*1024?0U:msiz<8*1024*1024?1U:2U, width1 = _width - 1; CImg<charT> _title(64); if (!title) cimg_snprintf(_title,_title._width,"CImg<%s>",pixel_type()); std::fprintf(cimg::output(),"%s%s%s%s: %sthis%s = %p, %ssize%s = (%u,%u,%u,%u) [%lu %s], %sdata%s = (%s*)%p", cimg::t_magenta,cimg::t_bold,title?title:_title._data,cimg::t_normal, cimg::t_bold,cimg::t_normal,(void*)this, cimg::t_bold,cimg::t_normal,_width,_height,_depth,_spectrum, (unsigned long)(mdisp==0?msiz:(mdisp==1?(msiz>>10):(msiz>>20))), mdisp==0?"b":(mdisp==1?"Kio":"Mio"), cimg::t_bold,cimg::t_normal,pixel_type(),(void*)begin()); if (_data) std::fprintf(cimg::output(),"..%p (%s) = [ ",(void*)((char*)end() - 1),_is_shared?"shared":"non-shared"); else std::fprintf(cimg::output()," (%s) = [ ",_is_shared?"shared":"non-shared"); if (!is_empty()) cimg_foroff(*this,off) { std::fprintf(cimg::output(),"%g",(double)_data[off]); if (off!=siz1) std::fprintf(cimg::output(),"%s",off%_width==width1?" ; ":" "); if (off==7 && siz>16) { off = siz1 - 8; std::fprintf(cimg::output(),"... "); } } if (!is_empty() && display_stats) std::fprintf(cimg::output(), " ], %smin%s = %g, %smax%s = %g, %smean%s = %g, %sstd%s = %g, %scoords_min%s = (%u,%u,%u,%u), " "%scoords_max%s = (%u,%u,%u,%u).\n", cimg::t_bold,cimg::t_normal,st[0], cimg::t_bold,cimg::t_normal,st[1], cimg::t_bold,cimg::t_normal,st[2], cimg::t_bold,cimg::t_normal,std::sqrt(st[3]), cimg::t_bold,cimg::t_normal,xm,ym,zm,vm, cimg::t_bold,cimg::t_normal,xM,yM,zM,vM); else std::fprintf(cimg::output(),"%s].\n",is_empty()?"":" "); std::fflush(cimg::output()); return *this; } //! Display image into a CImgDisplay window. /** \param disp Display window. **/ const CImg<T>& display(CImgDisplay& disp) const { disp.display(*this); return *this; } //! Display image into a CImgDisplay window, in an interactive way. /** \param disp Display window. \param display_info Tells if image information are displayed on the standard output. \param[in,out] XYZ Contains the XYZ coordinates at start / exit of the function. \param exit_on_anykey Exit function when any key is pressed. **/ const CImg<T>& display(CImgDisplay &disp, const bool display_info, unsigned int *const XYZ=0, const bool exit_on_anykey=false) const { return _display(disp,0,display_info,XYZ,exit_on_anykey,false); } //! Display image into an interactive window. /** \param title Window title \param display_info Tells if image information are displayed on the standard output. \param[in,out] XYZ Contains the XYZ coordinates at start / exit of the function. \param exit_on_anykey Exit function when any key is pressed. **/ const CImg<T>& display(const char *const title=0, const bool display_info=true, unsigned int *const XYZ=0, const bool exit_on_anykey=false) const { CImgDisplay disp; return _display(disp,title,display_info,XYZ,exit_on_anykey,false); } const CImg<T>& _display(CImgDisplay &disp, const char *const title, const bool display_info, unsigned int *const XYZ, const bool exit_on_anykey, const bool exit_on_singleclick) const { unsigned int oldw = 0, oldh = 0, _XYZ[3] = { 0 }, key = 0; int x0 = 0, y0 = 0, z0 = 0, x1 = width() - 1, y1 = height() - 1, z1 = depth() - 1, old_mouse_x = -1, old_mouse_y = -1; if (!disp) { disp.assign(cimg_fitscreen(_width,_height,_depth),title?title:0,1); if (!title) disp.set_title("CImg<%s> (%ux%ux%ux%u)",pixel_type(),_width,_height,_depth,_spectrum); else disp.set_title("%s",title); } else if (title) disp.set_title("%s",title); disp.show().flush(); const CImg<char> dtitle = CImg<char>::string(disp.title()); if (display_info) print(dtitle); CImg<T> zoom; for (bool reset_view = true, resize_disp = false, is_first_select = true; !key && !disp.is_closed(); ) { if (reset_view) { if (XYZ) { _XYZ[0] = XYZ[0]; _XYZ[1] = XYZ[1]; _XYZ[2] = XYZ[2]; } else { _XYZ[0] = (unsigned int)(x0 + x1 + 1)/2; _XYZ[1] = (unsigned int)(y0 + y1 + 1)/2; _XYZ[2] = (unsigned int)(z0 + z1 + 1)/2; } x0 = 0; y0 = 0; z0 = 0; x1 = width() - 1; y1 = height() - 1; z1 = depth() - 1; disp.resize(cimg_fitscreen(_width,_height,_depth),false); oldw = disp._width; oldh = disp._height; resize_disp = true; reset_view = false; } if (!x0 && !y0 && !z0 && x1==width() - 1 && y1==height() - 1 && z1==depth() - 1) { if (is_empty()) zoom.assign(1,1,1,1,(T)0); else zoom.assign(); } else zoom = get_crop(x0,y0,z0,x1,y1,z1); const CImg<T>& visu = zoom?zoom:*this; const unsigned int dx = 1U + x1 - x0, dy = 1U + y1 - y0, dz = 1U + z1 - z0, tw = dx + (dz>1?dz:0U), th = dy + (dz>1?dz:0U); if (!is_empty() && !disp.is_fullscreen() && resize_disp) { const float ttw = (float)tw*disp.width()/oldw, tth = (float)th*disp.height()/oldh, dM = std::max(ttw,tth), diM = (float)std::max(disp.width(),disp.height()); const unsigned int imgw = (unsigned int)(ttw*diM/dM), imgh = (unsigned int)(tth*diM/dM); disp.set_fullscreen(false).resize(cimg_fitscreen(imgw,imgh,1),false); resize_disp = false; } oldw = tw; oldh = th; bool go_up = false, go_down = false, go_left = false, go_right = false, go_inc = false, go_dec = false, go_in = false, go_out = false, go_in_center = false; disp.set_title("%s",dtitle._data); if (_width>1 && visu._width==1) disp.set_title("%s | x=%u",disp._title,x0); if (_height>1 && visu._height==1) disp.set_title("%s | y=%u",disp._title,y0); if (_depth>1 && visu._depth==1) disp.set_title("%s | z=%u",disp._title,z0); disp._mouse_x = old_mouse_x; disp._mouse_y = old_mouse_y; CImg<intT> selection = visu._select(disp,0,2,_XYZ,x0,y0,z0,true,is_first_select,_depth>1,true); old_mouse_x = disp._mouse_x; old_mouse_y = disp._mouse_y; is_first_select = false; if (disp.wheel()) { if ((disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) && (disp.is_keySHIFTLEFT() || disp.is_keySHIFTRIGHT())) { go_left = !(go_right = disp.wheel()>0); } else if (disp.is_keySHIFTLEFT() || disp.is_keySHIFTRIGHT()) { go_down = !(go_up = disp.wheel()>0); } else if (depth()==1 || disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { go_out = !(go_in = disp.wheel()>0); go_in_center = false; } disp.set_wheel(); } const int sx0 = selection(0), sy0 = selection(1), sz0 = selection(2), sx1 = selection(3), sy1 = selection(4), sz1 = selection(5); if (sx0>=0 && sy0>=0 && sz0>=0 && sx1>=0 && sy1>=0 && sz1>=0) { x1 = x0 + sx1; y1 = y0 + sy1; z1 = z0 + sz1; x0+=sx0; y0+=sy0; z0+=sz0; if ((sx0==sx1 && sy0==sy1) || (_depth>1 && sx0==sx1 && sz0==sz1) || (_depth>1 && sy0==sy1 && sz0==sz1)) { if (exit_on_singleclick && (!zoom || is_empty())) break; else reset_view = true; } resize_disp = true; } else switch (key = disp.key()) { #if cimg_OS!=2 case cimg::keyCTRLRIGHT : case cimg::keySHIFTRIGHT : #endif case 0 : case cimg::keyCTRLLEFT : case cimg::keySHIFTLEFT : key = 0; break; case cimg::keyP : if (visu._depth>1 && (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT())) { // Special mode: play stack of frames const unsigned int w1 = visu._width*disp.width()/(visu._width + (visu._depth>1?visu._depth:0)), h1 = visu._height*disp.height()/(visu._height + (visu._depth>1?visu._depth:0)); float frame_timing = 5; bool is_stopped = false; disp.set_key(key,false).set_wheel().resize(cimg_fitscreen(w1,h1,1),false); key = 0; for (unsigned int timer = 0; !key && !disp.is_closed() && !disp.button(); ) { if (disp.is_resized()) disp.resize(false); if (!timer) { visu.get_slice((int)_XYZ[2]).display(disp.set_title("%s | z=%d",dtitle.data(),_XYZ[2])); (++_XYZ[2])%=visu._depth; } if (!is_stopped) { if (++timer>(unsigned int)frame_timing) timer = 0; } else timer = ~0U; if (disp.wheel()) { frame_timing-=disp.wheel()/3.f; disp.set_wheel(); } switch (key = disp.key()) { #if cimg_OS!=2 case cimg::keyCTRLRIGHT : #endif case cimg::keyCTRLLEFT : key = 0; break; case cimg::keyPAGEUP : frame_timing-=0.3f; key = 0; break; case cimg::keyPAGEDOWN : frame_timing+=0.3f; key = 0; break; case cimg::keySPACE : is_stopped = !is_stopped; disp.set_key(key,false); key = 0; break; case cimg::keyARROWLEFT : case cimg::keyARROWUP : is_stopped = true; timer = 0; key = 0; break; case cimg::keyARROWRIGHT : case cimg::keyARROWDOWN : is_stopped = true; (_XYZ[2]+=visu._depth - 2)%=visu._depth; timer = 0; key = 0; break; case cimg::keyD : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false). resize(CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,false), CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,true),false); disp.set_key(key,false); key = 0; } break; case cimg::keyC : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false). resize(cimg_fitscreen(2*disp.width()/3,2*disp.height()/3,1),false).set_key(key,false); key = 0; } break; case cimg::keyR : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false). resize(cimg_fitscreen(_width,_height,_depth),false).set_key(key,false); key = 0; } break; case cimg::keyF : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.resize(disp.screen_width(),disp.screen_height(),false). toggle_fullscreen().set_key(key,false); key = 0; } break; } frame_timing = frame_timing<1?1:(frame_timing>39?39:frame_timing); disp.wait(20); } const unsigned int w2 = (visu._width + (visu._depth>1?visu._depth:0))*disp.width()/visu._width, h2 = (visu._height + (visu._depth>1?visu._depth:0))*disp.height()/visu._height; disp.resize(cimg_fitscreen(w2,h2,1),false).set_title(dtitle.data()).set_key().set_button().set_wheel(); key = 0; } break; case cimg::keyHOME : reset_view = resize_disp = true; key = 0; break; case cimg::keyPADADD : go_in = true; go_in_center = true; key = 0; break; case cimg::keyPADSUB : go_out = true; key = 0; break; case cimg::keyARROWLEFT : case cimg::keyPAD4: go_left = true; key = 0; break; case cimg::keyARROWRIGHT : case cimg::keyPAD6: go_right = true; key = 0; break; case cimg::keyARROWUP : case cimg::keyPAD8: go_up = true; key = 0; break; case cimg::keyARROWDOWN : case cimg::keyPAD2: go_down = true; key = 0; break; case cimg::keyPAD7 : go_up = go_left = true; key = 0; break; case cimg::keyPAD9 : go_up = go_right = true; key = 0; break; case cimg::keyPAD1 : go_down = go_left = true; key = 0; break; case cimg::keyPAD3 : go_down = go_right = true; key = 0; break; case cimg::keyPAGEUP : go_inc = true; key = 0; break; case cimg::keyPAGEDOWN : go_dec = true; key = 0; break; } if (go_in) { const int mx = go_in_center?disp.width()/2:disp.mouse_x(), my = go_in_center?disp.height()/2:disp.mouse_y(), mX = mx*(width() + (depth()>1?depth():0))/disp.width(), mY = my*(height() + (depth()>1?depth():0))/disp.height(); int X = (int)_XYZ[0], Y = (int)_XYZ[1], Z = (int)_XYZ[2]; if (mX<width() && mY<height()) { X = x0 + mX*(1 + x1 - x0)/width(); Y = y0 + mY*(1 + y1 - y0)/height(); } if (mX<width() && mY>=height()) { X = x0 + mX*(1 + x1 - x0)/width(); Z = z0 + (mY - height())*(1 + z1 - z0)/depth(); } if (mX>=width() && mY<height()) { Y = y0 + mY*(1 + y1 - y0)/height(); Z = z0 + (mX - width())*(1 + z1 - z0)/depth(); } if (x1 - x0>4) { x0 = X - 3*(X - x0)/4; x1 = X + 3*(x1 - X)/4; } if (y1 - y0>4) { y0 = Y - 3*(Y - y0)/4; y1 = Y + 3*(y1 - Y)/4; } if (z1 - z0>4) { z0 = Z - 3*(Z - z0)/4; z1 = Z + 3*(z1 - Z)/4; } } if (go_out) { const int delta_x = (x1 - x0)/8, delta_y = (y1 - y0)/8, delta_z = (z1 - z0)/8, ndelta_x = delta_x?delta_x:(_width>1), ndelta_y = delta_y?delta_y:(_height>1), ndelta_z = delta_z?delta_z:(_depth>1); x0-=ndelta_x; y0-=ndelta_y; z0-=ndelta_z; x1+=ndelta_x; y1+=ndelta_y; z1+=ndelta_z; if (x0<0) { x1-=x0; x0 = 0; if (x1>=width()) x1 = width() - 1; } if (y0<0) { y1-=y0; y0 = 0; if (y1>=height()) y1 = height() - 1; } if (z0<0) { z1-=z0; z0 = 0; if (z1>=depth()) z1 = depth() - 1; } if (x1>=width()) { x0-=(x1 - width() + 1); x1 = width() - 1; if (x0<0) x0 = 0; } if (y1>=height()) { y0-=(y1 - height() + 1); y1 = height() - 1; if (y0<0) y0 = 0; } if (z1>=depth()) { z0-=(z1 - depth() + 1); z1 = depth() - 1; if (z0<0) z0 = 0; } const float ratio = (float)(x1-x0)/(y1-y0), ratiow = (float)disp._width/disp._height, sub = std::min(cimg::abs(ratio - ratiow),cimg::abs(1/ratio-1/ratiow)); if (sub>0.01) resize_disp = true; } if (go_left) { const int delta = (x1 - x0)/4, ndelta = delta?delta:(_width>1); if (x0 - ndelta>=0) { x0-=ndelta; x1-=ndelta; } else { x1-=x0; x0 = 0; } } if (go_right) { const int delta = (x1 - x0)/4, ndelta = delta?delta:(_width>1); if (x1+ndelta<width()) { x0+=ndelta; x1+=ndelta; } else { x0+=(width() - 1 - x1); x1 = width() - 1; } } if (go_up) { const int delta = (y1 - y0)/4, ndelta = delta?delta:(_height>1); if (y0 - ndelta>=0) { y0-=ndelta; y1-=ndelta; } else { y1-=y0; y0 = 0; } } if (go_down) { const int delta = (y1 - y0)/4, ndelta = delta?delta:(_height>1); if (y1+ndelta<height()) { y0+=ndelta; y1+=ndelta; } else { y0+=(height() - 1 - y1); y1 = height() - 1; } } if (go_inc) { const int delta = (z1 - z0)/4, ndelta = delta?delta:(_depth>1); if (z0 - ndelta>=0) { z0-=ndelta; z1-=ndelta; } else { z1-=z0; z0 = 0; } } if (go_dec) { const int delta = (z1 - z0)/4, ndelta = delta?delta:(_depth>1); if (z1+ndelta<depth()) { z0+=ndelta; z1+=ndelta; } else { z0+=(depth() - 1 - z1); z1 = depth() - 1; } } disp.wait(100); if (!exit_on_anykey && key && key!=cimg::keyESC && (key!=cimg::keyW || (!disp.is_keyCTRLLEFT() && !disp.is_keyCTRLRIGHT()))) { key = 0; } } disp.set_key(key); if (XYZ) { XYZ[0] = _XYZ[0]; XYZ[1] = _XYZ[1]; XYZ[2] = _XYZ[2]; } return *this; } //! Display object 3D in an interactive window. /** \param disp Display window. \param vertices Vertices data of the 3D object. \param primitives Primitives data of the 3D object. \param colors Colors data of the 3D object. \param opacities Opacities data of the 3D object. \param centering Tells if the 3D object must be centered for the display. \param render_static Rendering mode. \param render_motion Rendering mode, when the 3D object is moved. \param is_double_sided Tells if the object primitives are double-sided. \param focale Focale \param light_x X-coordinate of the light source. \param light_y Y-coordinate of the light source. \param light_z Z-coordinate of the light source. \param specular_lightness Amount of specular light. \param specular_shininess Shininess of the object material. \param display_axes Tells if the 3D axes are displayed. \param pose_matrix Pointer to 12 values, defining a 3D pose (as a 4x3 matrix). \param exit_on_anykey Exit function when any key is pressed. **/ template<typename tp, typename tf, typename tc, typename to> const CImg<T>& display_object3d(CImgDisplay& disp, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const to& opacities, const bool centering=true, const int render_static=4, const int render_motion=1, const bool is_double_sided=true, const float focale=700, const float light_x=0, const float light_y=0, const float light_z=-5e8f, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const bool display_axes=true, float *const pose_matrix=0, const bool exit_on_anykey=false) const { return _display_object3d(disp,0,vertices,primitives,colors,opacities,centering,render_static, render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix,exit_on_anykey); } //! Display object 3D in an interactive window \simplification. template<typename tp, typename tf, typename tc, typename to> const CImg<T>& display_object3d(const char *const title, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const to& opacities, const bool centering=true, const int render_static=4, const int render_motion=1, const bool is_double_sided=true, const float focale=700, const float light_x=0, const float light_y=0, const float light_z=-5e8f, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const bool display_axes=true, float *const pose_matrix=0, const bool exit_on_anykey=false) const { CImgDisplay disp; return _display_object3d(disp,title,vertices,primitives,colors,opacities,centering,render_static, render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix,exit_on_anykey); } //! Display object 3D in an interactive window \simplification. template<typename tp, typename tf, typename tc> const CImg<T>& display_object3d(CImgDisplay &disp, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const bool centering=true, const int render_static=4, const int render_motion=1, const bool is_double_sided=true, const float focale=700, const float light_x=0, const float light_y=0, const float light_z=-5e8f, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const bool display_axes=true, float *const pose_matrix=0, const bool exit_on_anykey=false) const { return display_object3d(disp,vertices,primitives,colors,CImgList<floatT>(),centering, render_static,render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix,exit_on_anykey); } //! Display object 3D in an interactive window \simplification. template<typename tp, typename tf, typename tc> const CImg<T>& display_object3d(const char *const title, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const bool centering=true, const int render_static=4, const int render_motion=1, const bool is_double_sided=true, const float focale=700, const float light_x=0, const float light_y=0, const float light_z=-5e8f, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const bool display_axes=true, float *const pose_matrix=0, const bool exit_on_anykey=false) const { return display_object3d(title,vertices,primitives,colors,CImgList<floatT>(),centering, render_static,render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix,exit_on_anykey); } //! Display object 3D in an interactive window \simplification. template<typename tp, typename tf> const CImg<T>& display_object3d(CImgDisplay &disp, const CImg<tp>& vertices, const CImgList<tf>& primitives, const bool centering=true, const int render_static=4, const int render_motion=1, const bool is_double_sided=true, const float focale=700, const float light_x=0, const float light_y=0, const float light_z=-5e8f, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const bool display_axes=true, float *const pose_matrix=0, const bool exit_on_anykey=false) const { return display_object3d(disp,vertices,primitives,CImgList<T>(),centering, render_static,render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix,exit_on_anykey); } //! Display object 3D in an interactive window \simplification. template<typename tp, typename tf> const CImg<T>& display_object3d(const char *const title, const CImg<tp>& vertices, const CImgList<tf>& primitives, const bool centering=true, const int render_static=4, const int render_motion=1, const bool is_double_sided=true, const float focale=700, const float light_x=0, const float light_y=0, const float light_z=-5e8f, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const bool display_axes=true, float *const pose_matrix=0, const bool exit_on_anykey=false) const { return display_object3d(title,vertices,primitives,CImgList<T>(),centering, render_static,render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix,exit_on_anykey); } //! Display object 3D in an interactive window \simplification. template<typename tp> const CImg<T>& display_object3d(CImgDisplay &disp, const CImg<tp>& vertices, const bool centering=true, const int render_static=4, const int render_motion=1, const bool is_double_sided=true, const float focale=700, const float light_x=0, const float light_y=0, const float light_z=-5e8f, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const bool display_axes=true, float *const pose_matrix=0, const bool exit_on_anykey=false) const { return display_object3d(disp,vertices,CImgList<uintT>(),centering, render_static,render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix,exit_on_anykey); } //! Display object 3D in an interactive window \simplification. template<typename tp> const CImg<T>& display_object3d(const char *const title, const CImg<tp>& vertices, const bool centering=true, const int render_static=4, const int render_motion=1, const bool is_double_sided=true, const float focale=700, const float light_x=0, const float light_y=0, const float light_z=-5e8f, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const bool display_axes=true, float *const pose_matrix=0, const bool exit_on_anykey=false) const { return display_object3d(title,vertices,CImgList<uintT>(),centering, render_static,render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix,exit_on_anykey); } template<typename tp, typename tf, typename tc, typename to> const CImg<T>& _display_object3d(CImgDisplay& disp, const char *const title, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const to& opacities, const bool centering, const int render_static, const int render_motion, const bool is_double_sided, const float focale, const float light_x, const float light_y, const float light_z, const float specular_lightness, const float specular_shininess, const bool display_axes, float *const pose_matrix, const bool exit_on_anykey) const { typedef typename cimg::superset<tp,float>::type tpfloat; // Check input arguments if (is_empty()) { if (disp) return CImg<T>(disp.width(),disp.height(),1,(colors && colors[0].size()==1)?1:3,0). _display_object3d(disp,title,vertices,primitives,colors,opacities,centering, render_static,render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix,exit_on_anykey); else return CImg<T>(1,2,1,1,64,128).resize(cimg_fitscreen(CImgDisplay::screen_width()/2, CImgDisplay::screen_height()/2,1), 1,(colors && colors[0].size()==1)?1:3,3). _display_object3d(disp,title,vertices,primitives,colors,opacities,centering, render_static,render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix,exit_on_anykey); } else { if (disp) disp.resize(*this,false); } CImg<charT> error_message(1024); if (!vertices.is_object3d(primitives,colors,opacities,true,error_message)) throw CImgArgumentException(_cimg_instance "display_object3d(): Invalid specified 3D object (%u,%u) (%s).", cimg_instance,vertices._width,primitives._width,error_message.data()); if (vertices._width && !primitives) { CImgList<tf> nprimitives(vertices._width,1,1,1,1); cimglist_for(nprimitives,l) nprimitives(l,0) = (tf)l; return _display_object3d(disp,title,vertices,nprimitives,colors,opacities,centering, render_static,render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix,exit_on_anykey); } if (!disp) { disp.assign(cimg_fitscreen(_width,_height,_depth),title?title:0,3); if (!title) disp.set_title("CImg<%s> (%u vertices, %u primitives)", pixel_type(),vertices._width,primitives._width); } else if (title) disp.set_title("%s",title); // Init 3D objects and compute object statistics CImg<floatT> pose, rotated_vertices(vertices._width,3), bbox_vertices, rotated_bbox_vertices, axes_vertices, rotated_axes_vertices, bbox_opacities, axes_opacities; CImgList<uintT> bbox_primitives, axes_primitives; CImgList<tf> reverse_primitives; CImgList<T> bbox_colors, bbox_colors2, axes_colors; unsigned int ns_width = 0, ns_height = 0; int _is_double_sided = (int)is_double_sided; bool ndisplay_axes = display_axes; const CImg<T> background_color(1,1,1,_spectrum,0), foreground_color(1,1,1,_spectrum,(T)std::min((int)cimg::type<T>::max(),255)); float Xoff = 0, Yoff = 0, Zoff = 0, sprite_scale = 1, xm = 0, xM = vertices?vertices.get_shared_row(0).max_min(xm):0, ym = 0, yM = vertices?vertices.get_shared_row(1).max_min(ym):0, zm = 0, zM = vertices?vertices.get_shared_row(2).max_min(zm):0; const float delta = cimg::max(xM - xm,yM - ym,zM - zm); rotated_bbox_vertices = bbox_vertices.assign(8,3,1,1, xm,xM,xM,xm,xm,xM,xM,xm, ym,ym,yM,yM,ym,ym,yM,yM, zm,zm,zm,zm,zM,zM,zM,zM); bbox_primitives.assign(6,1,4,1,1, 0,3,2,1, 4,5,6,7, 1,2,6,5, 0,4,7,3, 0,1,5,4, 2,3,7,6); bbox_colors.assign(6,_spectrum,1,1,1,background_color[0]); bbox_colors2.assign(6,_spectrum,1,1,1,foreground_color[0]); bbox_opacities.assign(bbox_colors._width,1,1,1,0.3f); rotated_axes_vertices = axes_vertices.assign(7,3,1,1, 0,20,0,0,22,-6,-6, 0,0,20,0,-6,22,-6, 0,0,0,20,0,0,22); axes_opacities.assign(3,1,1,1,1); axes_colors.assign(3,_spectrum,1,1,1,foreground_color[0]); axes_primitives.assign(3,1,2,1,1, 0,1, 0,2, 0,3); // Begin user interaction loop CImg<T> visu0(*this,false), visu; CImg<tpfloat> zbuffer(visu0.width(),visu0.height(),1,1,0); bool init_pose = true, clicked = false, redraw = true; unsigned int key = 0; int x0 = 0, y0 = 0, x1 = 0, y1 = 0, nrender_static = render_static, nrender_motion = render_motion; disp.show().flush(); while (!disp.is_closed() && !key) { // Init object pose if (init_pose) { const float ratio = delta>0?(2.f*std::min(disp.width(),disp.height())/(3.f*delta)):1, dx = (xM + xm)/2, dy = (yM + ym)/2, dz = (zM + zm)/2; if (centering) CImg<floatT>(4,3,1,1, ratio,0.,0.,-ratio*dx, 0.,ratio,0.,-ratio*dy, 0.,0.,ratio,-ratio*dz).move_to(pose); else CImg<floatT>(4,3,1,1, 1,0,0,0, 0,1,0,0, 0,0,1,0).move_to(pose); if (pose_matrix) { CImg<floatT> pose0(pose_matrix,4,3,1,1,false); pose0.resize(4,4,1,1,0); pose.resize(4,4,1,1,0); pose0(3,3) = pose(3,3) = 1; (pose0*pose).get_crop(0,0,3,2).move_to(pose); Xoff = pose_matrix[12]; Yoff = pose_matrix[13]; Zoff = pose_matrix[14]; sprite_scale = pose_matrix[15]; } else { Xoff = Yoff = Zoff = 0; sprite_scale = 1; } init_pose = false; redraw = true; } // Rotate and draw 3D object if (redraw) { const float r00 = pose(0,0), r10 = pose(1,0), r20 = pose(2,0), r30 = pose(3,0), r01 = pose(0,1), r11 = pose(1,1), r21 = pose(2,1), r31 = pose(3,1), r02 = pose(0,2), r12 = pose(1,2), r22 = pose(2,2), r32 = pose(3,2); if ((clicked && nrender_motion>=0) || (!clicked && nrender_static>=0)) cimg_forX(vertices,l) { const float x = (float)vertices(l,0), y = (float)vertices(l,1), z = (float)vertices(l,2); rotated_vertices(l,0) = r00*x + r10*y + r20*z + r30; rotated_vertices(l,1) = r01*x + r11*y + r21*z + r31; rotated_vertices(l,2) = r02*x + r12*y + r22*z + r32; } else cimg_forX(bbox_vertices,l) { const float x = bbox_vertices(l,0), y = bbox_vertices(l,1), z = bbox_vertices(l,2); rotated_bbox_vertices(l,0) = r00*x + r10*y + r20*z + r30; rotated_bbox_vertices(l,1) = r01*x + r11*y + r21*z + r31; rotated_bbox_vertices(l,2) = r02*x + r12*y + r22*z + r32; } // Draw objects const bool render_with_zbuffer = !clicked && nrender_static>0; visu = visu0; if ((clicked && nrender_motion<0) || (!clicked && nrender_static<0)) visu.draw_object3d(Xoff + visu._width/2.f,Yoff + visu._height/2.f,Zoff, rotated_bbox_vertices,bbox_primitives,bbox_colors,bbox_opacities,2,false,focale). draw_object3d(Xoff + visu._width/2.f,Yoff + visu._height/2.f,Zoff, rotated_bbox_vertices,bbox_primitives,bbox_colors2,1,false,focale); else visu._draw_object3d((void*)0,render_with_zbuffer?zbuffer.fill(0):CImg<tpfloat>::empty(), Xoff + visu._width/2.f,Yoff + visu._height/2.f,Zoff, rotated_vertices,reverse_primitives?reverse_primitives:primitives, colors,opacities,clicked?nrender_motion:nrender_static,_is_double_sided==1,focale, width()/2.f + light_x,height()/2.f + light_y,light_z + Zoff, specular_lightness,specular_shininess,1,sprite_scale); // Draw axes if (ndisplay_axes) { const float n = 1e-8f + cimg::hypot(r00,r01,r02), _r00 = r00/n, _r10 = r10/n, _r20 = r20/n, _r01 = r01/n, _r11 = r11/n, _r21 = r21/n, _r02 = r01/n, _r12 = r12/n, _r22 = r22/n, Xaxes = 25, Yaxes = visu._height - 38.f; cimg_forX(axes_vertices,l) { const float x = axes_vertices(l,0), y = axes_vertices(l,1), z = axes_vertices(l,2); rotated_axes_vertices(l,0) = _r00*x + _r10*y + _r20*z; rotated_axes_vertices(l,1) = _r01*x + _r11*y + _r21*z; rotated_axes_vertices(l,2) = _r02*x + _r12*y + _r22*z; } axes_opacities(0,0) = (rotated_axes_vertices(1,2)>0)?0.5f:1.f; axes_opacities(1,0) = (rotated_axes_vertices(2,2)>0)?0.5f:1.f; axes_opacities(2,0) = (rotated_axes_vertices(3,2)>0)?0.5f:1.f; visu.draw_object3d(Xaxes,Yaxes,0,rotated_axes_vertices,axes_primitives, axes_colors,axes_opacities,1,false,focale). draw_text((int)(Xaxes + rotated_axes_vertices(4,0)), (int)(Yaxes + rotated_axes_vertices(4,1)), "X",axes_colors[0]._data,0,axes_opacities(0,0),13). draw_text((int)(Xaxes + rotated_axes_vertices(5,0)), (int)(Yaxes + rotated_axes_vertices(5,1)), "Y",axes_colors[1]._data,0,axes_opacities(1,0),13). draw_text((int)(Xaxes + rotated_axes_vertices(6,0)), (int)(Yaxes + rotated_axes_vertices(6,1)), "Z",axes_colors[2]._data,0,axes_opacities(2,0),13); } visu.display(disp); if (!clicked || nrender_motion==nrender_static) redraw = false; } // Handle user interaction disp.wait(); if ((disp.button() || disp.wheel()) && disp.mouse_x()>=0 && disp.mouse_y()>=0) { redraw = true; if (!clicked) { x0 = x1 = disp.mouse_x(); y0 = y1 = disp.mouse_y(); if (!disp.wheel()) clicked = true; } else { x1 = disp.mouse_x(); y1 = disp.mouse_y(); } if (disp.button()&1) { const float R = 0.45f*std::min(disp.width(),disp.height()), R2 = R*R, u0 = (float)(x0 - disp.width()/2), v0 = (float)(y0 - disp.height()/2), u1 = (float)(x1 - disp.width()/2), v1 = (float)(y1 - disp.height()/2), n0 = cimg::hypot(u0,v0), n1 = cimg::hypot(u1,v1), nu0 = n0>R?(u0*R/n0):u0, nv0 = n0>R?(v0*R/n0):v0, nw0 = (float)std::sqrt(std::max(0.f,R2 - nu0*nu0 - nv0*nv0)), nu1 = n1>R?(u1*R/n1):u1, nv1 = n1>R?(v1*R/n1):v1, nw1 = (float)std::sqrt(std::max(0.f,R2 - nu1*nu1 - nv1*nv1)), u = nv0*nw1 - nw0*nv1, v = nw0*nu1 - nu0*nw1, w = nv0*nu1 - nu0*nv1, n = cimg::hypot(u,v,w), alpha = (float)std::asin(n/R2)*180/cimg::PI; (CImg<floatT>::rotation_matrix(u,v,w,-alpha)*pose).move_to(pose); x0 = x1; y0 = y1; } if (disp.button()&2) { if (focale>0) Zoff-=(y0 - y1)*focale/400; else { const float s = std::exp((y0 - y1)/400.f); pose*=s; sprite_scale*=s; } x0 = x1; y0 = y1; } if (disp.wheel()) { if (focale>0) Zoff-=disp.wheel()*focale/20; else { const float s = std::exp(disp.wheel()/20.f); pose*=s; sprite_scale*=s; } disp.set_wheel(); } if (disp.button()&4) { Xoff+=(x1 - x0); Yoff+=(y1 - y0); x0 = x1; y0 = y1; } if ((disp.button()&1) && (disp.button()&2)) { init_pose = true; disp.set_button(); x0 = x1; y0 = y1; pose = CImg<floatT>(4,3,1,1, 1,0,0,0, 0,1,0,0, 0,0,1,0); } } else if (clicked) { x0 = x1; y0 = y1; clicked = false; redraw = true; } CImg<charT> filename(32); switch (key = disp.key()) { #if cimg_OS!=2 case cimg::keyCTRLRIGHT : #endif case 0 : case cimg::keyCTRLLEFT : key = 0; break; case cimg::keyD: if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false). resize(CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,false), CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,true),false). _is_resized = true; disp.set_key(key,false); key = 0; } break; case cimg::keyC : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false). resize(cimg_fitscreen(2*disp.width()/3,2*disp.height()/3,1),false)._is_resized = true; disp.set_key(key,false); key = 0; } break; case cimg::keyR : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false).resize(cimg_fitscreen(_width,_height,_depth),false)._is_resized = true; disp.set_key(key,false); key = 0; } break; case cimg::keyF : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { if (!ns_width || !ns_height || ns_width>(unsigned int)disp.screen_width() || ns_height>(unsigned int)disp.screen_height()) { ns_width = disp.screen_width()*3U/4; ns_height = disp.screen_height()*3U/4; } if (disp.is_fullscreen()) disp.resize(ns_width,ns_height,false); else { ns_width = disp._width; ns_height = disp._height; disp.resize(disp.screen_width(),disp.screen_height(),false); } disp.toggle_fullscreen()._is_resized = true; disp.set_key(key,false); key = 0; } break; case cimg::keyT : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Switch single/double-sided primitives. if (--_is_double_sided==-2) _is_double_sided = 1; if (_is_double_sided>=0) reverse_primitives.assign(); else primitives.get_reverse_object3d().move_to(reverse_primitives); disp.set_key(key,false); key = 0; redraw = true; } break; case cimg::keyZ : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Enable/disable Z-buffer if (zbuffer) zbuffer.assign(); else zbuffer.assign(visu0.width(),visu0.height(),1,1,0); disp.set_key(key,false); key = 0; redraw = true; } break; case cimg::keyX : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Show/hide 3D axes ndisplay_axes = !ndisplay_axes; disp.set_key(key,false); key = 0; redraw = true; } break; case cimg::keyF1 : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Set rendering mode to points nrender_motion = (nrender_static==0 && nrender_motion!=0)?0:-1; nrender_static = 0; disp.set_key(key,false); key = 0; redraw = true; } break; case cimg::keyF2 : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Set rendering mode to lines nrender_motion = (nrender_static==1 && nrender_motion!=1)?1:-1; nrender_static = 1; disp.set_key(key,false); key = 0; redraw = true; } break; case cimg::keyF3 : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Set rendering mode to flat nrender_motion = (nrender_static==2 && nrender_motion!=2)?2:-1; nrender_static = 2; disp.set_key(key,false); key = 0; redraw = true; } break; case cimg::keyF4 : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Set rendering mode to flat-shaded nrender_motion = (nrender_static==3 && nrender_motion!=3)?3:-1; nrender_static = 3; disp.set_key(key,false); key = 0; redraw = true; } break; case cimg::keyF5 : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Set rendering mode to gouraud-shaded. nrender_motion = (nrender_static==4 && nrender_motion!=4)?4:-1; nrender_static = 4; disp.set_key(key,false); key = 0; redraw = true; } break; case cimg::keyF6 : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Set rendering mode to phong-shaded nrender_motion = (nrender_static==5 && nrender_motion!=5)?5:-1; nrender_static = 5; disp.set_key(key,false); key = 0; redraw = true; } break; case cimg::keyS : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Save snapshot static unsigned int snap_number = 0; std::FILE *file; do { cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.bmp",snap_number++); if ((file=cimg::std_fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); (+visu).__draw_text(" Saving snapshot... ",0).display(disp); visu.save(filename); (+visu).__draw_text(" Snapshot '%s' saved. ",0,filename._data).display(disp); disp.set_key(key,false); key = 0; } break; case cimg::keyG : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Save object as a .off file static unsigned int snap_number = 0; std::FILE *file; do { cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.off",snap_number++); if ((file=cimg::std_fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); (+visu).__draw_text(" Saving object... ",0).display(disp); vertices.save_off(reverse_primitives?reverse_primitives:primitives,colors,filename); (+visu).__draw_text(" Object '%s' saved. ",0,filename._data).display(disp); disp.set_key(key,false); key = 0; } break; case cimg::keyO : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Save object as a .cimg file static unsigned int snap_number = 0; std::FILE *file; do { #ifdef cimg_use_zlib cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.cimgz",snap_number++); #else cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.cimg",snap_number++); #endif if ((file=cimg::std_fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); (+visu).__draw_text(" Saving object... ",0).display(disp); vertices.get_object3dtoCImg3d(reverse_primitives?reverse_primitives:primitives,colors,opacities). save(filename); (+visu).__draw_text(" Object '%s' saved. ",0,filename._data).display(disp); disp.set_key(key,false); key = 0; } break; #ifdef cimg_use_board case cimg::keyP : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Save object as a .EPS file static unsigned int snap_number = 0; std::FILE *file; do { cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.eps",snap_number++); if ((file=cimg::std_fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); (+visu).__draw_text(" Saving EPS snapshot... ",0).display(disp); LibBoard::Board board; (+visu)._draw_object3d(&board,zbuffer.fill(0), Xoff + visu._width/2.f,Yoff + visu._height/2.f,Zoff, rotated_vertices,reverse_primitives?reverse_primitives:primitives, colors,opacities,clicked?nrender_motion:nrender_static, _is_double_sided==1,focale, visu.width()/2.f + light_x,visu.height()/2.f + light_y,light_z + Zoff, specular_lightness,specular_shininess,1, sprite_scale); board.saveEPS(filename); (+visu).__draw_text(" Object '%s' saved. ",0,filename._data).display(disp); disp.set_key(key,false); key = 0; } break; case cimg::keyV : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Save object as a .SVG file static unsigned int snap_number = 0; std::FILE *file; do { cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.svg",snap_number++); if ((file=cimg::std_fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); (+visu).__draw_text(" Saving SVG snapshot... ",0,13).display(disp); LibBoard::Board board; (+visu)._draw_object3d(&board,zbuffer.fill(0), Xoff + visu._width/2.f,Yoff + visu._height/2.f,Zoff, rotated_vertices,reverse_primitives?reverse_primitives:primitives, colors,opacities,clicked?nrender_motion:nrender_static, _is_double_sided==1,focale, visu.width()/2.f + light_x,visu.height()/2.f + light_y,light_z + Zoff, specular_lightness,specular_shininess,1, sprite_scale); board.saveSVG(filename); (+visu).__draw_text(" Object '%s' saved. ",0,filename._data).display(disp); disp.set_key(key,false); key = 0; } break; #endif } if (disp.is_resized()) { disp.resize(false); visu0 = get_resize(disp,1); if (zbuffer) zbuffer.assign(disp.width(),disp.height()); redraw = true; } if (!exit_on_anykey && key && key!=cimg::keyESC && (key!=cimg::keyW || (!disp.is_keyCTRLLEFT() && !disp.is_keyCTRLRIGHT()))) { key = 0; } } if (pose_matrix) { std::memcpy(pose_matrix,pose._data,12*sizeof(float)); pose_matrix[12] = Xoff; pose_matrix[13] = Yoff; pose_matrix[14] = Zoff; pose_matrix[15] = sprite_scale; } disp.set_button().set_key(key); return *this; } //! Display 1D graph in an interactive window. /** \param disp Display window. \param plot_type Plot type. Can be <tt>{ 0=points | 1=segments | 2=splines | 3=bars }</tt>. \param vertex_type Vertex type. \param labelx Title for the horizontal axis, as a C-string. \param xmin Minimum value along the X-axis. \param xmax Maximum value along the X-axis. \param labely Title for the vertical axis, as a C-string. \param ymin Minimum value along the X-axis. \param ymax Maximum value along the X-axis. \param exit_on_anykey Exit function when any key is pressed. **/ const CImg<T>& display_graph(CImgDisplay &disp, const unsigned int plot_type=1, const unsigned int vertex_type=1, const char *const labelx=0, const double xmin=0, const double xmax=0, const char *const labely=0, const double ymin=0, const double ymax=0, const bool exit_on_anykey=false) const { return _display_graph(disp,0,plot_type,vertex_type,labelx,xmin,xmax,labely,ymin,ymax,exit_on_anykey); } //! Display 1D graph in an interactive window \overloading. const CImg<T>& display_graph(const char *const title=0, const unsigned int plot_type=1, const unsigned int vertex_type=1, const char *const labelx=0, const double xmin=0, const double xmax=0, const char *const labely=0, const double ymin=0, const double ymax=0, const bool exit_on_anykey=false) const { CImgDisplay disp; return _display_graph(disp,title,plot_type,vertex_type,labelx,xmin,xmax,labely,ymin,ymax,exit_on_anykey); } const CImg<T>& _display_graph(CImgDisplay &disp, const char *const title=0, const unsigned int plot_type=1, const unsigned int vertex_type=1, const char *const labelx=0, const double xmin=0, const double xmax=0, const char *const labely=0, const double ymin=0, const double ymax=0, const bool exit_on_anykey=false) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "display_graph(): Empty instance.", cimg_instance); if (!disp) disp.assign(cimg_fitscreen(CImgDisplay::screen_width()/2,CImgDisplay::screen_height()/2,1),0,0). set_title(title?"%s":"CImg<%s>",title?title:pixel_type()); const ulongT siz = (ulongT)_width*_height*_depth, siz1 = std::max((ulongT)1,siz - 1); const unsigned int old_normalization = disp.normalization(); disp.show().flush()._normalization = 0; double y0 = ymin, y1 = ymax, nxmin = xmin, nxmax = xmax; if (nxmin==nxmax) { nxmin = 0; nxmax = siz1; } int x0 = 0, x1 = width()*height()*depth() - 1, key = 0; for (bool reset_view = true; !key && !disp.is_closed(); ) { if (reset_view) { x0 = 0; x1 = width()*height()*depth() - 1; y0 = ymin; y1 = ymax; reset_view = false; } CImg<T> zoom(x1 - x0 + 1,1,1,spectrum()); cimg_forC(*this,c) zoom.get_shared_channel(c) = CImg<T>(data(x0,0,0,c),x1 - x0 + 1,1,1,1,true); if (y0==y1) { y0 = zoom.min_max(y1); const double dy = y1 - y0; y0-=dy/20; y1+=dy/20; } if (y0==y1) { --y0; ++y1; } const CImg<intT> selection = zoom.get_select_graph(disp,plot_type,vertex_type, labelx, nxmin + x0*(nxmax - nxmin)/siz1, nxmin + x1*(nxmax - nxmin)/siz1, labely,y0,y1,true); const int mouse_x = disp.mouse_x(), mouse_y = disp.mouse_y(); if (selection[0]>=0) { if (selection[2]<0) reset_view = true; else { x1 = x0 + selection[2]; x0+=selection[0]; if (selection[1]>=0 && selection[3]>=0) { y0 = y1 - selection[3]*(y1 - y0)/(disp.height() - 32); y1-=selection[1]*(y1 - y0)/(disp.height() - 32); } } } else { bool go_in = false, go_out = false, go_left = false, go_right = false, go_up = false, go_down = false; switch (key = (int)disp.key()) { case cimg::keyHOME : reset_view = true; key = 0; disp.set_key(); break; case cimg::keyPADADD : go_in = true; go_out = false; key = 0; disp.set_key(); break; case cimg::keyPADSUB : go_out = true; go_in = false; key = 0; disp.set_key(); break; case cimg::keyARROWLEFT : case cimg::keyPAD4 : go_left = true; go_right = false; key = 0; disp.set_key(); break; case cimg::keyARROWRIGHT : case cimg::keyPAD6 : go_right = true; go_left = false; key = 0; disp.set_key(); break; case cimg::keyARROWUP : case cimg::keyPAD8 : go_up = true; go_down = false; key = 0; disp.set_key(); break; case cimg::keyARROWDOWN : case cimg::keyPAD2 : go_down = true; go_up = false; key = 0; disp.set_key(); break; case cimg::keyPAD7 : go_left = true; go_up = true; key = 0; disp.set_key(); break; case cimg::keyPAD9 : go_right = true; go_up = true; key = 0; disp.set_key(); break; case cimg::keyPAD1 : go_left = true; go_down = true; key = 0; disp.set_key(); break; case cimg::keyPAD3 : go_right = true; go_down = true; key = 0; disp.set_key(); break; } if (disp.wheel()) { if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) go_up = !(go_down = disp.wheel()<0); else if (disp.is_keySHIFTLEFT() || disp.is_keySHIFTRIGHT()) go_left = !(go_right = disp.wheel()>0); else go_out = !(go_in = disp.wheel()>0); key = 0; } if (go_in) { const int xsiz = x1 - x0, mx = (mouse_x - 16)*xsiz/(disp.width() - 32), cx = x0 + cimg::cut(mx,0,xsiz); if (x1 - x0>4) { x0 = cx - 7*(cx - x0)/8; x1 = cx + 7*(x1 - cx)/8; if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { const double ysiz = y1 - y0, my = (mouse_y - 16)*ysiz/(disp.height() - 32), cy = y1 - cimg::cut(my,0.,ysiz); y0 = cy - 7*(cy - y0)/8; y1 = cy + 7*(y1 - cy)/8; } else y0 = y1 = 0; } } if (go_out) { if (x0>0 || x1<(int)siz1) { const int delta_x = (x1 - x0)/8, ndelta_x = delta_x?delta_x:(siz>1); const double ndelta_y = (y1 - y0)/8; x0-=ndelta_x; x1+=ndelta_x; y0-=ndelta_y; y1+=ndelta_y; if (x0<0) { x1-=x0; x0 = 0; if (x1>=(int)siz) x1 = (int)siz1; } if (x1>=(int)siz) { x0-=(x1 - siz1); x1 = (int)siz1; if (x0<0) x0 = 0; } } } if (go_left) { const int delta = (x1 - x0)/5, ndelta = delta?delta:1; if (x0 - ndelta>=0) { x0-=ndelta; x1-=ndelta; } else { x1-=x0; x0 = 0; } go_left = false; } if (go_right) { const int delta = (x1 - x0)/5, ndelta = delta?delta:1; if (x1 + ndelta<(int)siz) { x0+=ndelta; x1+=ndelta; } else { x0+=(siz1 - x1); x1 = (int)siz1; } go_right = false; } if (go_up) { const double delta = (y1 - y0)/10, ndelta = delta?delta:1; y0+=ndelta; y1+=ndelta; go_up = false; } if (go_down) { const double delta = (y1 - y0)/10, ndelta = delta?delta:1; y0-=ndelta; y1-=ndelta; go_down = false; } } if (!exit_on_anykey && key && key!=(int)cimg::keyESC && (key!=(int)cimg::keyW || (!disp.is_keyCTRLLEFT() && !disp.is_keyCTRLRIGHT()))) { disp.set_key(key,false); key = 0; } } disp._normalization = old_normalization; return *this; } //! Save image as a file. /** \param filename Filename, as a C-string. \param number When positive, represents an index added to the filename. Otherwise, no number is added. \param digits Number of digits used for adding the number to the filename. \note - The used file format is defined by the file extension in the filename \p filename. - Parameter \p number can be used to add a 6-digit number to the filename before saving. **/ const CImg<T>& save(const char *const filename, const int number=-1, const unsigned int digits=6) const { if (!filename) throw CImgArgumentException(_cimg_instance "save(): Specified filename is (null).", cimg_instance); // Do not test for empty instances, since .cimg format is able to manage empty instances. const bool is_stdout = *filename=='-' && (!filename[1] || filename[1]=='.'); const char *const ext = cimg::split_filename(filename); CImg<charT> nfilename(1024); const char *const fn = is_stdout?filename:(number>=0)?cimg::number_filename(filename,number,digits,nfilename): filename; #ifdef cimg_save_plugin cimg_save_plugin(fn); #endif #ifdef cimg_save_plugin1 cimg_save_plugin1(fn); #endif #ifdef cimg_save_plugin2 cimg_save_plugin2(fn); #endif #ifdef cimg_save_plugin3 cimg_save_plugin3(fn); #endif #ifdef cimg_save_plugin4 cimg_save_plugin4(fn); #endif #ifdef cimg_save_plugin5 cimg_save_plugin5(fn); #endif #ifdef cimg_save_plugin6 cimg_save_plugin6(fn); #endif #ifdef cimg_save_plugin7 cimg_save_plugin7(fn); #endif #ifdef cimg_save_plugin8 cimg_save_plugin8(fn); #endif // Ascii formats if (!cimg::strcasecmp(ext,"asc")) return save_ascii(fn); else if (!cimg::strcasecmp(ext,"dlm") || !cimg::strcasecmp(ext,"txt")) return save_dlm(fn); else if (!cimg::strcasecmp(ext,"cpp") || !cimg::strcasecmp(ext,"hpp") || !cimg::strcasecmp(ext,"h") || !cimg::strcasecmp(ext,"c")) return save_cpp(fn); // 2D binary formats else if (!cimg::strcasecmp(ext,"bmp")) return save_bmp(fn); else if (!cimg::strcasecmp(ext,"jpg") || !cimg::strcasecmp(ext,"jpeg") || !cimg::strcasecmp(ext,"jpe") || !cimg::strcasecmp(ext,"jfif") || !cimg::strcasecmp(ext,"jif")) return save_jpeg(fn); else if (!cimg::strcasecmp(ext,"rgb")) return save_rgb(fn); else if (!cimg::strcasecmp(ext,"rgba")) return save_rgba(fn); else if (!cimg::strcasecmp(ext,"png")) return save_png(fn); else if (!cimg::strcasecmp(ext,"pgm") || !cimg::strcasecmp(ext,"ppm") || !cimg::strcasecmp(ext,"pnm")) return save_pnm(fn); else if (!cimg::strcasecmp(ext,"pnk")) return save_pnk(fn); else if (!cimg::strcasecmp(ext,"pfm")) return save_pfm(fn); else if (!cimg::strcasecmp(ext,"exr")) return save_exr(fn); else if (!cimg::strcasecmp(ext,"tif") || !cimg::strcasecmp(ext,"tiff")) return save_tiff(fn); // 3D binary formats else if (!*ext) { #ifdef cimg_use_zlib return save_cimg(fn,true); #else return save_cimg(fn,false); #endif } else if (!cimg::strcasecmp(ext,"cimgz")) return save_cimg(fn,true); else if (!cimg::strcasecmp(ext,"cimg")) return save_cimg(fn,false); else if (!cimg::strcasecmp(ext,"dcm")) return save_medcon_external(fn); else if (!cimg::strcasecmp(ext,"hdr") || !cimg::strcasecmp(ext,"nii")) return save_analyze(fn); else if (!cimg::strcasecmp(ext,"inr")) return save_inr(fn); else if (!cimg::strcasecmp(ext,"mnc")) return save_minc2(fn); else if (!cimg::strcasecmp(ext,"pan")) return save_pandore(fn); else if (!cimg::strcasecmp(ext,"raw")) return save_raw(fn); // Archive files else if (!cimg::strcasecmp(ext,"gz")) return save_gzip_external(fn); // Image sequences else if (!cimg::strcasecmp(ext,"yuv")) return save_yuv(fn,444,true); else if (!cimg::strcasecmp(ext,"avi") || !cimg::strcasecmp(ext,"mov") || !cimg::strcasecmp(ext,"asf") || !cimg::strcasecmp(ext,"divx") || !cimg::strcasecmp(ext,"flv") || !cimg::strcasecmp(ext,"mpg") || !cimg::strcasecmp(ext,"m1v") || !cimg::strcasecmp(ext,"m2v") || !cimg::strcasecmp(ext,"m4v") || !cimg::strcasecmp(ext,"mjp") || !cimg::strcasecmp(ext,"mp4") || !cimg::strcasecmp(ext,"mkv") || !cimg::strcasecmp(ext,"mpe") || !cimg::strcasecmp(ext,"movie") || !cimg::strcasecmp(ext,"ogm") || !cimg::strcasecmp(ext,"ogg") || !cimg::strcasecmp(ext,"ogv") || !cimg::strcasecmp(ext,"qt") || !cimg::strcasecmp(ext,"rm") || !cimg::strcasecmp(ext,"vob") || !cimg::strcasecmp(ext,"wmv") || !cimg::strcasecmp(ext,"xvid") || !cimg::strcasecmp(ext,"mpeg")) return save_video(fn); return save_other(fn); } //! Save image as an Ascii file. /** \param filename Filename, as a C-string. **/ const CImg<T>& save_ascii(const char *const filename) const { return _save_ascii(0,filename); } //! Save image as an Ascii file \overloading. const CImg<T>& save_ascii(std::FILE *const file) const { return _save_ascii(file,0); } const CImg<T>& _save_ascii(std::FILE *const file, const char *const filename) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_ascii(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"w"); std::fprintf(nfile,"%u %u %u %u\n",_width,_height,_depth,_spectrum); const T* ptrs = _data; cimg_forYZC(*this,y,z,c) { cimg_forX(*this,x) std::fprintf(nfile,"%.17g ",(double)*(ptrs++)); std::fputc('\n',nfile); } if (!file) cimg::fclose(nfile); return *this; } //! Save image as a .cpp source file. /** \param filename Filename, as a C-string. **/ const CImg<T>& save_cpp(const char *const filename) const { return _save_cpp(0,filename); } //! Save image as a .cpp source file \overloading. const CImg<T>& save_cpp(std::FILE *const file) const { return _save_cpp(file,0); } const CImg<T>& _save_cpp(std::FILE *const file, const char *const filename) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_cpp(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"w"); CImg<charT> varname(1024); *varname = 0; if (filename) cimg_sscanf(cimg::basename(filename),"%1023[a-zA-Z0-9_]",varname._data); if (!*varname) cimg_snprintf(varname,varname._width,"unnamed"); std::fprintf(nfile, "/* Define image '%s' of size %ux%ux%ux%u and type '%s' */\n" "%s data_%s[] = { %s\n ", varname._data,_width,_height,_depth,_spectrum,pixel_type(),pixel_type(),varname._data, is_empty()?"};":""); if (!is_empty()) for (ulongT off = 0, siz = size() - 1; off<=siz; ++off) { std::fprintf(nfile,cimg::type<T>::format(),cimg::type<T>::format((*this)[off])); if (off==siz) std::fprintf(nfile," };\n"); else if (!((off + 1)%16)) std::fprintf(nfile,",\n "); else std::fprintf(nfile,", "); } if (!file) cimg::fclose(nfile); return *this; } //! Save image as a DLM file. /** \param filename Filename, as a C-string. **/ const CImg<T>& save_dlm(const char *const filename) const { return _save_dlm(0,filename); } //! Save image as a DLM file \overloading. const CImg<T>& save_dlm(std::FILE *const file) const { return _save_dlm(file,0); } const CImg<T>& _save_dlm(std::FILE *const file, const char *const filename) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_dlm(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(file,filename); return *this; } if (_depth>1) cimg::warn(_cimg_instance "save_dlm(): Instance is volumetric, values along Z will be unrolled in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); if (_spectrum>1) cimg::warn(_cimg_instance "save_dlm(): Instance is multispectral, values along C will be unrolled in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"w"); const T* ptrs = _data; cimg_forYZC(*this,y,z,c) { cimg_forX(*this,x) std::fprintf(nfile,"%.17g%s",(double)*(ptrs++),(x==width() - 1)?"":","); std::fputc('\n',nfile); } if (!file) cimg::fclose(nfile); return *this; } //! Save image as a BMP file. /** \param filename Filename, as a C-string. **/ const CImg<T>& save_bmp(const char *const filename) const { return _save_bmp(0,filename); } //! Save image as a BMP file \overloading. const CImg<T>& save_bmp(std::FILE *const file) const { return _save_bmp(file,0); } const CImg<T>& _save_bmp(std::FILE *const file, const char *const filename) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_bmp(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(file,filename); return *this; } if (_depth>1) cimg::warn(_cimg_instance "save_bmp(): Instance is volumetric, only the first slice will be saved in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); if (_spectrum>3) cimg::warn(_cimg_instance "save_bmp(): Instance is multispectral, only the three first channels will be saved in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); CImg<ucharT> header(54,1,1,1,0); unsigned char align_buf[4] = { 0 }; const unsigned int align = (4 - (3*_width)%4)%4, buf_size = (3*_width + align)*height(), file_size = 54 + buf_size; header[0] = 'B'; header[1] = 'M'; header[0x02] = file_size&0xFF; header[0x03] = (file_size>>8)&0xFF; header[0x04] = (file_size>>16)&0xFF; header[0x05] = (file_size>>24)&0xFF; header[0x0A] = 0x36; header[0x0E] = 0x28; header[0x12] = _width&0xFF; header[0x13] = (_width>>8)&0xFF; header[0x14] = (_width>>16)&0xFF; header[0x15] = (_width>>24)&0xFF; header[0x16] = _height&0xFF; header[0x17] = (_height>>8)&0xFF; header[0x18] = (_height>>16)&0xFF; header[0x19] = (_height>>24)&0xFF; header[0x1A] = 1; header[0x1B] = 0; header[0x1C] = 24; header[0x1D] = 0; header[0x22] = buf_size&0xFF; header[0x23] = (buf_size>>8)&0xFF; header[0x24] = (buf_size>>16)&0xFF; header[0x25] = (buf_size>>24)&0xFF; header[0x27] = 0x1; header[0x2B] = 0x1; cimg::fwrite(header._data,54,nfile); const T *ptr_r = data(0,_height - 1,0,0), *ptr_g = (_spectrum>=2)?data(0,_height - 1,0,1):0, *ptr_b = (_spectrum>=3)?data(0,_height - 1,0,2):0; switch (_spectrum) { case 1 : { cimg_forY(*this,y) { cimg_forX(*this,x) { const unsigned char val = (unsigned char)*(ptr_r++); std::fputc(val,nfile); std::fputc(val,nfile); std::fputc(val,nfile); } cimg::fwrite(align_buf,align,nfile); ptr_r-=2*_width; } } break; case 2 : { cimg_forY(*this,y) { cimg_forX(*this,x) { std::fputc(0,nfile); std::fputc((unsigned char)(*(ptr_g++)),nfile); std::fputc((unsigned char)(*(ptr_r++)),nfile); } cimg::fwrite(align_buf,align,nfile); ptr_r-=2*_width; ptr_g-=2*_width; } } break; default : { cimg_forY(*this,y) { cimg_forX(*this,x) { std::fputc((unsigned char)(*(ptr_b++)),nfile); std::fputc((unsigned char)(*(ptr_g++)),nfile); std::fputc((unsigned char)(*(ptr_r++)),nfile); } cimg::fwrite(align_buf,align,nfile); ptr_r-=2*_width; ptr_g-=2*_width; ptr_b-=2*_width; } } } if (!file) cimg::fclose(nfile); return *this; } //! Save image as a JPEG file. /** \param filename Filename, as a C-string. \param quality Image quality (in %) **/ const CImg<T>& save_jpeg(const char *const filename, const unsigned int quality=100) const { return _save_jpeg(0,filename,quality); } //! Save image as a JPEG file \overloading. const CImg<T>& save_jpeg(std::FILE *const file, const unsigned int quality=100) const { return _save_jpeg(file,0,quality); } const CImg<T>& _save_jpeg(std::FILE *const file, const char *const filename, const unsigned int quality) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_jpeg(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(file,filename); return *this; } if (_depth>1) cimg::warn(_cimg_instance "save_jpeg(): Instance is volumetric, only the first slice will be saved in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); #ifndef cimg_use_jpeg if (!file) return save_other(filename,quality); else throw CImgIOException(_cimg_instance "save_jpeg(): Unable to save data in '(*FILE)' unless libjpeg is enabled.", cimg_instance); #else unsigned int dimbuf = 0; J_COLOR_SPACE colortype = JCS_RGB; switch (_spectrum) { case 1 : dimbuf = 1; colortype = JCS_GRAYSCALE; break; case 2 : dimbuf = 3; colortype = JCS_RGB; break; case 3 : dimbuf = 3; colortype = JCS_RGB; break; default : dimbuf = 4; colortype = JCS_CMYK; break; } // Call libjpeg functions struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); jpeg_stdio_dest(&cinfo,nfile); cinfo.image_width = _width; cinfo.image_height = _height; cinfo.input_components = dimbuf; cinfo.in_color_space = colortype; jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo,quality<100?quality:100,TRUE); jpeg_start_compress(&cinfo,TRUE); JSAMPROW row_pointer[1]; CImg<ucharT> buffer(_width*dimbuf); while (cinfo.next_scanline<cinfo.image_height) { unsigned char *ptrd = buffer._data; // Fill pixel buffer switch (_spectrum) { case 1 : { // Greyscale images const T *ptr_g = data(0, cinfo.next_scanline); for (unsigned int b = 0; b<cinfo.image_width; b++) *(ptrd++) = (unsigned char)*(ptr_g++); } break; case 2 : { // RG images const T *ptr_r = data(0,cinfo.next_scanline,0,0), *ptr_g = data(0,cinfo.next_scanline,0,1); for (unsigned int b = 0; b<cinfo.image_width; ++b) { *(ptrd++) = (unsigned char)*(ptr_r++); *(ptrd++) = (unsigned char)*(ptr_g++); *(ptrd++) = 0; } } break; case 3 : { // RGB images const T *ptr_r = data(0,cinfo.next_scanline,0,0), *ptr_g = data(0,cinfo.next_scanline,0,1), *ptr_b = data(0,cinfo.next_scanline,0,2); for (unsigned int b = 0; b<cinfo.image_width; ++b) { *(ptrd++) = (unsigned char)*(ptr_r++); *(ptrd++) = (unsigned char)*(ptr_g++); *(ptrd++) = (unsigned char)*(ptr_b++); } } break; default : { // CMYK images const T *ptr_r = data(0,cinfo.next_scanline,0,0), *ptr_g = data(0,cinfo.next_scanline,0,1), *ptr_b = data(0,cinfo.next_scanline,0,2), *ptr_a = data(0,cinfo.next_scanline,0,3); for (unsigned int b = 0; b<cinfo.image_width; ++b) { *(ptrd++) = (unsigned char)*(ptr_r++); *(ptrd++) = (unsigned char)*(ptr_g++); *(ptrd++) = (unsigned char)*(ptr_b++); *(ptrd++) = (unsigned char)*(ptr_a++); } } } *row_pointer = buffer._data; jpeg_write_scanlines(&cinfo,row_pointer,1); } jpeg_finish_compress(&cinfo); if (!file) cimg::fclose(nfile); jpeg_destroy_compress(&cinfo); return *this; #endif } //! Save image, using built-in ImageMagick++ library. /** \param filename Filename, as a C-string. \param bytes_per_pixel Force the number of bytes per pixel for the saving, when possible. **/ const CImg<T>& save_magick(const char *const filename, const unsigned int bytes_per_pixel=0) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_magick(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(0,filename); return *this; } #ifdef cimg_use_magick double stmin, stmax = (double)max_min(stmin); if (_depth>1) cimg::warn(_cimg_instance "save_magick(): Instance is volumetric, only the first slice will be saved in file '%s'.", cimg_instance, filename); if (_spectrum>3) cimg::warn(_cimg_instance "save_magick(): Instance is multispectral, only the three first channels will be " "saved in file '%s'.", cimg_instance, filename); if (stmin<0 || (bytes_per_pixel==1 && stmax>=256) || stmax>=65536) cimg::warn(_cimg_instance "save_magick(): Instance has pixel values in [%g,%g], probable type overflow in file '%s'.", cimg_instance, filename,stmin,stmax); Magick::Image image(Magick::Geometry(_width,_height),"black"); image.type(Magick::TrueColorType); image.depth(bytes_per_pixel?(8*bytes_per_pixel):(stmax>=256?16:8)); const T *ptr_r = data(0,0,0,0), *ptr_g = _spectrum>1?data(0,0,0,1):0, *ptr_b = _spectrum>2?data(0,0,0,2):0; Magick::PixelPacket *pixels = image.getPixels(0,0,_width,_height); switch (_spectrum) { case 1 : // Scalar images for (ulongT off = (ulongT)_width*_height; off; --off) { pixels->red = pixels->green = pixels->blue = (Magick::Quantum)*(ptr_r++); ++pixels; } break; case 2 : // RG images for (ulongT off = (ulongT)_width*_height; off; --off) { pixels->red = (Magick::Quantum)*(ptr_r++); pixels->green = (Magick::Quantum)*(ptr_g++); pixels->blue = 0; ++pixels; } break; default : // RGB images for (ulongT off = (ulongT)_width*_height; off; --off) { pixels->red = (Magick::Quantum)*(ptr_r++); pixels->green = (Magick::Quantum)*(ptr_g++); pixels->blue = (Magick::Quantum)*(ptr_b++); ++pixels; } } image.syncPixels(); image.write(filename); return *this; #else cimg::unused(bytes_per_pixel); throw CImgIOException(_cimg_instance "save_magick(): Unable to save file '%s' unless libMagick++ is enabled.", cimg_instance, filename); #endif } //! Save image as a PNG file. /** \param filename Filename, as a C-string. \param bytes_per_pixel Force the number of bytes per pixels for the saving, when possible. **/ const CImg<T>& save_png(const char *const filename, const unsigned int bytes_per_pixel=0) const { return _save_png(0,filename,bytes_per_pixel); } //! Save image as a PNG file \overloading. const CImg<T>& save_png(std::FILE *const file, const unsigned int bytes_per_pixel=0) const { return _save_png(file,0,bytes_per_pixel); } const CImg<T>& _save_png(std::FILE *const file, const char *const filename, const unsigned int bytes_per_pixel=0) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_png(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(file,filename); return *this; } #ifndef cimg_use_png cimg::unused(bytes_per_pixel); if (!file) return save_other(filename); else throw CImgIOException(_cimg_instance "save_png(): Unable to save data in '(*FILE)' unless libpng is enabled.", cimg_instance); #else #if defined __GNUC__ const char *volatile nfilename = filename; // Use 'volatile' to avoid (wrong) g++ warning std::FILE *volatile nfile = file?file:cimg::fopen(nfilename,"wb"); volatile double stmin, stmax = (double)max_min(stmin); #else const char *nfilename = filename; std::FILE *nfile = file?file:cimg::fopen(nfilename,"wb"); double stmin, stmax = (double)max_min(stmin); #endif if (_depth>1) cimg::warn(_cimg_instance "save_png(): Instance is volumetric, only the first slice will be saved in file '%s'.", cimg_instance, filename); if (_spectrum>4) cimg::warn(_cimg_instance "save_png(): Instance is multispectral, only the three first channels will be saved in file '%s'.", cimg_instance, filename); if (stmin<0 || (bytes_per_pixel==1 && stmax>=256) || stmax>=65536) cimg::warn(_cimg_instance "save_png(): Instance has pixel values in [%g,%g], probable type overflow in file '%s'.", cimg_instance, filename,stmin,stmax); // Setup PNG structures for write png_voidp user_error_ptr = 0; png_error_ptr user_error_fn = 0, user_warning_fn = 0; png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,user_error_ptr, user_error_fn, user_warning_fn); if (!png_ptr){ if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "save_png(): Failed to initialize 'png_ptr' structure when saving file '%s'.", cimg_instance, nfilename?nfilename:"(FILE*)"); } png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_write_struct(&png_ptr,(png_infopp)0); if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "save_png(): Failed to initialize 'info_ptr' structure when saving file '%s'.", cimg_instance, nfilename?nfilename:"(FILE*)"); } if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_write_struct(&png_ptr, &info_ptr); if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "save_png(): Encountered unknown fatal error in libpng when saving file '%s'.", cimg_instance, nfilename?nfilename:"(FILE*)"); } png_init_io(png_ptr, nfile); const int bit_depth = bytes_per_pixel?(bytes_per_pixel*8):(stmax>=256?16:8); int color_type; switch (spectrum()) { case 1 : color_type = PNG_COLOR_TYPE_GRAY; break; case 2 : color_type = PNG_COLOR_TYPE_GRAY_ALPHA; break; case 3 : color_type = PNG_COLOR_TYPE_RGB; break; default : color_type = PNG_COLOR_TYPE_RGB_ALPHA; } const int interlace_type = PNG_INTERLACE_NONE; const int compression_type = PNG_COMPRESSION_TYPE_DEFAULT; const int filter_method = PNG_FILTER_TYPE_DEFAULT; png_set_IHDR(png_ptr,info_ptr,_width,_height,bit_depth,color_type,interlace_type,compression_type,filter_method); png_write_info(png_ptr,info_ptr); const int byte_depth = bit_depth>>3; const int numChan = spectrum()>4?4:spectrum(); const int pixel_bit_depth_flag = numChan * (bit_depth - 1); // Allocate Memory for Image Save and Fill pixel data png_bytep *const imgData = new png_byte*[_height]; for (unsigned int row = 0; row<_height; ++row) imgData[row] = new png_byte[byte_depth*numChan*_width]; const T *pC0 = data(0,0,0,0); switch (pixel_bit_depth_flag) { case 7 : { // Gray 8-bit cimg_forY(*this,y) { unsigned char *ptrd = imgData[y]; cimg_forX(*this,x) *(ptrd++) = (unsigned char)*(pC0++); } } break; case 14 : { // Gray w/ Alpha 8-bit const T *pC1 = data(0,0,0,1); cimg_forY(*this,y) { unsigned char *ptrd = imgData[y]; cimg_forX(*this,x) { *(ptrd++) = (unsigned char)*(pC0++); *(ptrd++) = (unsigned char)*(pC1++); } } } break; case 21 : { // RGB 8-bit const T *pC1 = data(0,0,0,1), *pC2 = data(0,0,0,2); cimg_forY(*this,y) { unsigned char *ptrd = imgData[y]; cimg_forX(*this,x) { *(ptrd++) = (unsigned char)*(pC0++); *(ptrd++) = (unsigned char)*(pC1++); *(ptrd++) = (unsigned char)*(pC2++); } } } break; case 28 : { // RGB x/ Alpha 8-bit const T *pC1 = data(0,0,0,1), *pC2 = data(0,0,0,2), *pC3 = data(0,0,0,3); cimg_forY(*this,y){ unsigned char *ptrd = imgData[y]; cimg_forX(*this,x){ *(ptrd++) = (unsigned char)*(pC0++); *(ptrd++) = (unsigned char)*(pC1++); *(ptrd++) = (unsigned char)*(pC2++); *(ptrd++) = (unsigned char)*(pC3++); } } } break; case 15 : { // Gray 16-bit cimg_forY(*this,y){ unsigned short *ptrd = (unsigned short*)(imgData[y]); cimg_forX(*this,x) *(ptrd++) = (unsigned short)*(pC0++); if (!cimg::endianness()) cimg::invert_endianness((unsigned short*)imgData[y],_width); } } break; case 30 : { // Gray w/ Alpha 16-bit const T *pC1 = data(0,0,0,1); cimg_forY(*this,y){ unsigned short *ptrd = (unsigned short*)(imgData[y]); cimg_forX(*this,x) { *(ptrd++) = (unsigned short)*(pC0++); *(ptrd++) = (unsigned short)*(pC1++); } if (!cimg::endianness()) cimg::invert_endianness((unsigned short*)imgData[y],2*_width); } } break; case 45 : { // RGB 16-bit const T *pC1 = data(0,0,0,1), *pC2 = data(0,0,0,2); cimg_forY(*this,y) { unsigned short *ptrd = (unsigned short*)(imgData[y]); cimg_forX(*this,x) { *(ptrd++) = (unsigned short)*(pC0++); *(ptrd++) = (unsigned short)*(pC1++); *(ptrd++) = (unsigned short)*(pC2++); } if (!cimg::endianness()) cimg::invert_endianness((unsigned short*)imgData[y],3*_width); } } break; case 60 : { // RGB w/ Alpha 16-bit const T *pC1 = data(0,0,0,1), *pC2 = data(0,0,0,2), *pC3 = data(0,0,0,3); cimg_forY(*this,y) { unsigned short *ptrd = (unsigned short*)(imgData[y]); cimg_forX(*this,x) { *(ptrd++) = (unsigned short)*(pC0++); *(ptrd++) = (unsigned short)*(pC1++); *(ptrd++) = (unsigned short)*(pC2++); *(ptrd++) = (unsigned short)*(pC3++); } if (!cimg::endianness()) cimg::invert_endianness((unsigned short*)imgData[y],4*_width); } } break; default : if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "save_png(): Encountered unknown fatal error in libpng when saving file '%s'.", cimg_instance, nfilename?nfilename:"(FILE*)"); } png_write_image(png_ptr,imgData); png_write_end(png_ptr,info_ptr); png_destroy_write_struct(&png_ptr, &info_ptr); // Deallocate Image Write Memory cimg_forY(*this,n) delete[] imgData[n]; delete[] imgData; if (!file) cimg::fclose(nfile); return *this; #endif } //! Save image as a PNM file. /** \param filename Filename, as a C-string. \param bytes_per_pixel Force the number of bytes per pixels for the saving. **/ const CImg<T>& save_pnm(const char *const filename, const unsigned int bytes_per_pixel=0) const { return _save_pnm(0,filename,bytes_per_pixel); } //! Save image as a PNM file \overloading. const CImg<T>& save_pnm(std::FILE *const file, const unsigned int bytes_per_pixel=0) const { return _save_pnm(file,0,bytes_per_pixel); } const CImg<T>& _save_pnm(std::FILE *const file, const char *const filename, const unsigned int bytes_per_pixel=0) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_pnm(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(file,filename); return *this; } double stmin, stmax = (double)max_min(stmin); if (_depth>1) cimg::warn(_cimg_instance "save_pnm(): Instance is volumetric, only the first slice will be saved in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); if (_spectrum>3) cimg::warn(_cimg_instance "save_pnm(): Instance is multispectral, only the three first channels will be saved in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); if (stmin<0 || (bytes_per_pixel==1 && stmax>=256) || stmax>=65536) cimg::warn(_cimg_instance "save_pnm(): Instance has pixel values in [%g,%g], probable type overflow in file '%s'.", cimg_instance, stmin,stmax,filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); const T *ptr_r = data(0,0,0,0), *ptr_g = (_spectrum>=2)?data(0,0,0,1):0, *ptr_b = (_spectrum>=3)?data(0,0,0,2):0; const ulongT buf_size = std::min((ulongT)(1024*1024),(ulongT)(_width*_height*(_spectrum==1?1UL:3UL))); std::fprintf(nfile,"P%c\n%u %u\n%u\n", (_spectrum==1?'5':'6'),_width,_height,stmax<256?255:(stmax<4096?4095:65535)); switch (_spectrum) { case 1 : { // Scalar image if (bytes_per_pixel==1 || (!bytes_per_pixel && stmax<256)) { // Binary PGM 8 bits CImg<ucharT> buf((unsigned int)buf_size); for (longT to_write = (longT)width()*height(); to_write>0; ) { const ulongT N = std::min((ulongT)to_write,buf_size); unsigned char *ptrd = buf._data; for (ulongT i = N; i>0; --i) *(ptrd++) = (unsigned char)*(ptr_r++); cimg::fwrite(buf._data,N,nfile); to_write-=N; } } else { // Binary PGM 16 bits CImg<ushortT> buf((unsigned int)buf_size); for (longT to_write = (longT)width()*height(); to_write>0; ) { const ulongT N = std::min((ulongT)to_write,buf_size); unsigned short *ptrd = buf._data; for (ulongT i = N; i>0; --i) *(ptrd++) = (unsigned short)*(ptr_r++); if (!cimg::endianness()) cimg::invert_endianness(buf._data,buf_size); cimg::fwrite(buf._data,N,nfile); to_write-=N; } } } break; case 2 : { // RG image if (bytes_per_pixel==1 || (!bytes_per_pixel && stmax<256)) { // Binary PPM 8 bits CImg<ucharT> buf((unsigned int)buf_size); for (longT to_write = (longT)width()*height(); to_write>0; ) { const ulongT N = std::min((ulongT)to_write,buf_size/3); unsigned char *ptrd = buf._data; for (ulongT i = N; i>0; --i) { *(ptrd++) = (unsigned char)*(ptr_r++); *(ptrd++) = (unsigned char)*(ptr_g++); *(ptrd++) = 0; } cimg::fwrite(buf._data,3*N,nfile); to_write-=N; } } else { // Binary PPM 16 bits CImg<ushortT> buf((unsigned int)buf_size); for (longT to_write = (longT)width()*height(); to_write>0; ) { const ulongT N = std::min((ulongT)to_write,buf_size/3); unsigned short *ptrd = buf._data; for (ulongT i = N; i>0; --i) { *(ptrd++) = (unsigned short)*(ptr_r++); *(ptrd++) = (unsigned short)*(ptr_g++); *(ptrd++) = 0; } if (!cimg::endianness()) cimg::invert_endianness(buf._data,buf_size); cimg::fwrite(buf._data,3*N,nfile); to_write-=N; } } } break; default : { // RGB image if (bytes_per_pixel==1 || (!bytes_per_pixel && stmax<256)) { // Binary PPM 8 bits CImg<ucharT> buf((unsigned int)buf_size); for (longT to_write = (longT)width()*height(); to_write>0; ) { const ulongT N = std::min((ulongT)to_write,buf_size/3); unsigned char *ptrd = buf._data; for (ulongT i = N; i>0; --i) { *(ptrd++) = (unsigned char)*(ptr_r++); *(ptrd++) = (unsigned char)*(ptr_g++); *(ptrd++) = (unsigned char)*(ptr_b++); } cimg::fwrite(buf._data,3*N,nfile); to_write-=N; } } else { // Binary PPM 16 bits CImg<ushortT> buf((unsigned int)buf_size); for (longT to_write = (longT)width()*height(); to_write>0; ) { const ulongT N = std::min((ulongT)to_write,buf_size/3); unsigned short *ptrd = buf._data; for (ulongT i = N; i>0; --i) { *(ptrd++) = (unsigned short)*(ptr_r++); *(ptrd++) = (unsigned short)*(ptr_g++); *(ptrd++) = (unsigned short)*(ptr_b++); } if (!cimg::endianness()) cimg::invert_endianness(buf._data,buf_size); cimg::fwrite(buf._data,3*N,nfile); to_write-=N; } } } } if (!file) cimg::fclose(nfile); return *this; } //! Save image as a PNK file. /** \param filename Filename, as a C-string. **/ const CImg<T>& save_pnk(const char *const filename) const { return _save_pnk(0,filename); } //! Save image as a PNK file \overloading. const CImg<T>& save_pnk(std::FILE *const file) const { return _save_pnk(file,0); } const CImg<T>& _save_pnk(std::FILE *const file, const char *const filename) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_pnk(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(file,filename); return *this; } if (_spectrum>1) cimg::warn(_cimg_instance "save_pnk(): Instance is multispectral, only the first channel will be saved in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); const ulongT buf_size = std::min((ulongT)1024*1024,(ulongT)_width*_height*_depth); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); const T *ptr = data(0,0,0,0); if (!cimg::type<T>::is_float() && sizeof(T)==1 && _depth<2) // Can be saved as regular PNM file _save_pnm(file,filename,0); else if (!cimg::type<T>::is_float() && sizeof(T)==1) { // Save as extended P5 file: Binary byte-valued 3D std::fprintf(nfile,"P5\n%u %u %u\n255\n",_width,_height,_depth); CImg<ucharT> buf((unsigned int)buf_size); for (longT to_write = (longT)width()*height()*depth(); to_write>0; ) { const ulongT N = std::min((ulongT)to_write,buf_size); unsigned char *ptrd = buf._data; for (ulongT i = N; i>0; --i) *(ptrd++) = (unsigned char)*(ptr++); cimg::fwrite(buf._data,N,nfile); to_write-=N; } } else if (!cimg::type<T>::is_float()) { // Save as P8: Binary int32-valued 3D if (_depth>1) std::fprintf(nfile,"P8\n%u %u %u\n%d\n",_width,_height,_depth,(int)max()); else std::fprintf(nfile,"P8\n%u %u\n%d\n",_width,_height,(int)max()); CImg<intT> buf((unsigned int)buf_size); for (longT to_write = (longT)width()*height()*depth(); to_write>0; ) { const ulongT N = std::min((ulongT)to_write,buf_size); int *ptrd = buf._data; for (ulongT i = N; i>0; --i) *(ptrd++) = (int)*(ptr++); cimg::fwrite(buf._data,N,nfile); to_write-=N; } } else { // Save as P9: Binary float-valued 3D if (_depth>1) std::fprintf(nfile,"P9\n%u %u %u\n%g\n",_width,_height,_depth,(double)max()); else std::fprintf(nfile,"P9\n%u %u\n%g\n",_width,_height,(double)max()); CImg<floatT> buf((unsigned int)buf_size); for (longT to_write = (longT)width()*height()*depth(); to_write>0; ) { const ulongT N = std::min((ulongT)to_write,buf_size); float *ptrd = buf._data; for (ulongT i = N; i>0; --i) *(ptrd++) = (float)*(ptr++); cimg::fwrite(buf._data,N,nfile); to_write-=N; } } if (!file) cimg::fclose(nfile); return *this; } //! Save image as a PFM file. /** \param filename Filename, as a C-string. **/ const CImg<T>& save_pfm(const char *const filename) const { get_mirror('y')._save_pfm(0,filename); return *this; } //! Save image as a PFM file \overloading. const CImg<T>& save_pfm(std::FILE *const file) const { get_mirror('y')._save_pfm(file,0); return *this; } const CImg<T>& _save_pfm(std::FILE *const file, const char *const filename) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_pfm(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(file,filename); return *this; } if (_depth>1) cimg::warn(_cimg_instance "save_pfm(): Instance is volumetric, only the first slice will be saved in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); if (_spectrum>3) cimg::warn(_cimg_instance "save_pfm(): image instance is multispectral, only the three first channels will be saved " "in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); const T *ptr_r = data(0,0,0,0), *ptr_g = (_spectrum>=2)?data(0,0,0,1):0, *ptr_b = (_spectrum>=3)?data(0,0,0,2):0; const unsigned int buf_size = std::min(1024*1024U,_width*_height*(_spectrum==1?1:3)); std::fprintf(nfile,"P%c\n%u %u\n1.0\n", (_spectrum==1?'f':'F'),_width,_height); switch (_spectrum) { case 1 : { // Scalar image CImg<floatT> buf(buf_size); for (longT to_write = (longT)width()*height(); to_write>0; ) { const ulongT N = std::min((ulongT)to_write,(ulongT)buf_size); float *ptrd = buf._data; for (ulongT i = N; i>0; --i) *(ptrd++) = (float)*(ptr_r++); if (!cimg::endianness()) cimg::invert_endianness(buf._data,buf_size); cimg::fwrite(buf._data,N,nfile); to_write-=N; } } break; case 2 : { // RG image CImg<floatT> buf(buf_size); for (longT to_write = (longT)width()*height(); to_write>0; ) { const unsigned int N = std::min((unsigned int)to_write,buf_size/3); float *ptrd = buf._data; for (ulongT i = N; i>0; --i) { *(ptrd++) = (float)*(ptr_r++); *(ptrd++) = (float)*(ptr_g++); *(ptrd++) = 0; } if (!cimg::endianness()) cimg::invert_endianness(buf._data,buf_size); cimg::fwrite(buf._data,3*N,nfile); to_write-=N; } } break; default : { // RGB image CImg<floatT> buf(buf_size); for (longT to_write = (longT)width()*height(); to_write>0; ) { const unsigned int N = std::min((unsigned int)to_write,buf_size/3); float *ptrd = buf._data; for (ulongT i = N; i>0; --i) { *(ptrd++) = (float)*(ptr_r++); *(ptrd++) = (float)*(ptr_g++); *(ptrd++) = (float)*(ptr_b++); } if (!cimg::endianness()) cimg::invert_endianness(buf._data,buf_size); cimg::fwrite(buf._data,3*N,nfile); to_write-=N; } } } if (!file) cimg::fclose(nfile); return *this; } //! Save image as a RGB file. /** \param filename Filename, as a C-string. **/ const CImg<T>& save_rgb(const char *const filename) const { return _save_rgb(0,filename); } //! Save image as a RGB file \overloading. const CImg<T>& save_rgb(std::FILE *const file) const { return _save_rgb(file,0); } const CImg<T>& _save_rgb(std::FILE *const file, const char *const filename) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_rgb(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(file,filename); return *this; } if (_spectrum!=3) cimg::warn(_cimg_instance "save_rgb(): image instance has not exactly 3 channels, for file '%s'.", cimg_instance, filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); const ulongT wh = (ulongT)_width*_height; unsigned char *const buffer = new unsigned char[3*wh], *nbuffer = buffer; const T *ptr1 = data(0,0,0,0), *ptr2 = _spectrum>1?data(0,0,0,1):0, *ptr3 = _spectrum>2?data(0,0,0,2):0; switch (_spectrum) { case 1 : { // Scalar image for (ulongT k = 0; k<wh; ++k) { const unsigned char val = (unsigned char)*(ptr1++); *(nbuffer++) = val; *(nbuffer++) = val; *(nbuffer++) = val; } } break; case 2 : { // RG image for (ulongT k = 0; k<wh; ++k) { *(nbuffer++) = (unsigned char)(*(ptr1++)); *(nbuffer++) = (unsigned char)(*(ptr2++)); *(nbuffer++) = 0; } } break; default : { // RGB image for (ulongT k = 0; k<wh; ++k) { *(nbuffer++) = (unsigned char)(*(ptr1++)); *(nbuffer++) = (unsigned char)(*(ptr2++)); *(nbuffer++) = (unsigned char)(*(ptr3++)); } } } cimg::fwrite(buffer,3*wh,nfile); if (!file) cimg::fclose(nfile); delete[] buffer; return *this; } //! Save image as a RGBA file. /** \param filename Filename, as a C-string. **/ const CImg<T>& save_rgba(const char *const filename) const { return _save_rgba(0,filename); } //! Save image as a RGBA file \overloading. const CImg<T>& save_rgba(std::FILE *const file) const { return _save_rgba(file,0); } const CImg<T>& _save_rgba(std::FILE *const file, const char *const filename) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_rgba(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(file,filename); return *this; } if (_spectrum!=4) cimg::warn(_cimg_instance "save_rgba(): image instance has not exactly 4 channels, for file '%s'.", cimg_instance, filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); const ulongT wh = (ulongT)_width*_height; unsigned char *const buffer = new unsigned char[4*wh], *nbuffer = buffer; const T *ptr1 = data(0,0,0,0), *ptr2 = _spectrum>1?data(0,0,0,1):0, *ptr3 = _spectrum>2?data(0,0,0,2):0, *ptr4 = _spectrum>3?data(0,0,0,3):0; switch (_spectrum) { case 1 : { // Scalar images for (ulongT k = 0; k<wh; ++k) { const unsigned char val = (unsigned char)*(ptr1++); *(nbuffer++) = val; *(nbuffer++) = val; *(nbuffer++) = val; *(nbuffer++) = 255; } } break; case 2 : { // RG images for (ulongT k = 0; k<wh; ++k) { *(nbuffer++) = (unsigned char)(*(ptr1++)); *(nbuffer++) = (unsigned char)(*(ptr2++)); *(nbuffer++) = 0; *(nbuffer++) = 255; } } break; case 3 : { // RGB images for (ulongT k = 0; k<wh; ++k) { *(nbuffer++) = (unsigned char)(*(ptr1++)); *(nbuffer++) = (unsigned char)(*(ptr2++)); *(nbuffer++) = (unsigned char)(*(ptr3++)); *(nbuffer++) = 255; } } break; default : { // RGBA images for (ulongT k = 0; k<wh; ++k) { *(nbuffer++) = (unsigned char)(*(ptr1++)); *(nbuffer++) = (unsigned char)(*(ptr2++)); *(nbuffer++) = (unsigned char)(*(ptr3++)); *(nbuffer++) = (unsigned char)(*(ptr4++)); } } } cimg::fwrite(buffer,4*wh,nfile); if (!file) cimg::fclose(nfile); delete[] buffer; return *this; } //! Save image as a TIFF file. /** \param filename Filename, as a C-string. \param compression_type Type of data compression. Can be <tt>{ 0=None | 1=LZW | 2=JPEG }</tt>. \param voxel_size Voxel size, to be stored in the filename. \param description Description, to be stored in the filename. \param use_bigtiff Allow to save big tiff files (>4Gb). \note - libtiff support is enabled by defining the precompilation directive \c cimg_use_tif. - When libtiff is enabled, 2D and 3D (multipage) several channel per pixel are supported for <tt>char,uchar,short,ushort,float</tt> and \c double pixel types. - If \c cimg_use_tif is not defined at compile time the function uses CImg<T>&save_other(const char*). **/ const CImg<T>& save_tiff(const char *const filename, const unsigned int compression_type=0, const float *const voxel_size=0, const char *const description=0, const bool use_bigtiff=true) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_tiff(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(0,filename); return *this; } #ifdef cimg_use_tiff const bool _use_bigtiff = use_bigtiff && sizeof(ulongT)>=8 && size()*sizeof(T)>=1UL<<31; // No bigtiff for small images TIFF *tif = TIFFOpen(filename,_use_bigtiff?"w8":"w4"); if (tif) { cimg_forZ(*this,z) _save_tiff(tif,z,z,compression_type,voxel_size,description); TIFFClose(tif); } else throw CImgIOException(_cimg_instance "save_tiff(): Failed to open file '%s' for writing.", cimg_instance, filename); return *this; #else cimg::unused(compression_type,voxel_size,description,use_bigtiff); return save_other(filename); #endif } #ifdef cimg_use_tiff #define _cimg_save_tiff(types,typed,compression_type) if (!std::strcmp(types,pixel_type())) { \ const typed foo = (typed)0; return _save_tiff(tif,directory,z,foo,compression_type,voxel_size,description); } // [internal] Save a plane into a tiff file template<typename t> const CImg<T>& _save_tiff(TIFF *tif, const unsigned int directory, const unsigned int z, const t& pixel_t, const unsigned int compression_type, const float *const voxel_size, const char *const description) const { if (is_empty() || !tif || pixel_t) return *this; const char *const filename = TIFFFileName(tif); uint32 rowsperstrip = (uint32)-1; uint16 spp = _spectrum, bpp = sizeof(t)*8, photometric; if (spp==3 || spp==4) photometric = PHOTOMETRIC_RGB; else photometric = PHOTOMETRIC_MINISBLACK; TIFFSetDirectory(tif,directory); TIFFSetField(tif,TIFFTAG_IMAGEWIDTH,_width); TIFFSetField(tif,TIFFTAG_IMAGELENGTH,_height); if (voxel_size) { const float vx = voxel_size[0], vy = voxel_size[1], vz = voxel_size[2]; TIFFSetField(tif,TIFFTAG_RESOLUTIONUNIT,RESUNIT_NONE); TIFFSetField(tif,TIFFTAG_XRESOLUTION,1.f/vx); TIFFSetField(tif,TIFFTAG_YRESOLUTION,1.f/vy); CImg<charT> s_description(256); cimg_snprintf(s_description,s_description._width,"VX=%g VY=%g VZ=%g spacing=%g",vx,vy,vz,vz); TIFFSetField(tif,TIFFTAG_IMAGEDESCRIPTION,s_description.data()); } if (description) TIFFSetField(tif,TIFFTAG_IMAGEDESCRIPTION,description); TIFFSetField(tif,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT); TIFFSetField(tif,TIFFTAG_SAMPLESPERPIXEL,spp); if (cimg::type<t>::is_float()) TIFFSetField(tif,TIFFTAG_SAMPLEFORMAT,3); else if (cimg::type<t>::min()==0) TIFFSetField(tif,TIFFTAG_SAMPLEFORMAT,1); else TIFFSetField(tif,TIFFTAG_SAMPLEFORMAT,2); double valm, valM = max_min(valm); TIFFSetField(tif,TIFFTAG_SMINSAMPLEVALUE,valm); TIFFSetField(tif,TIFFTAG_SMAXSAMPLEVALUE,valM); TIFFSetField(tif,TIFFTAG_BITSPERSAMPLE,bpp); TIFFSetField(tif,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG); TIFFSetField(tif,TIFFTAG_PHOTOMETRIC,photometric); TIFFSetField(tif,TIFFTAG_COMPRESSION,compression_type==2?COMPRESSION_JPEG: compression_type==1?COMPRESSION_LZW:COMPRESSION_NONE); rowsperstrip = TIFFDefaultStripSize(tif,rowsperstrip); TIFFSetField(tif,TIFFTAG_ROWSPERSTRIP,rowsperstrip); TIFFSetField(tif,TIFFTAG_FILLORDER,FILLORDER_MSB2LSB); TIFFSetField(tif,TIFFTAG_SOFTWARE,"CImg"); t *const buf = (t*)_TIFFmalloc(TIFFStripSize(tif)); if (buf) { for (unsigned int row = 0; row<_height; row+=rowsperstrip) { uint32 nrow = (row + rowsperstrip>_height?_height - row:rowsperstrip); tstrip_t strip = TIFFComputeStrip(tif,row,0); tsize_t i = 0; for (unsigned int rr = 0; rr<nrow; ++rr) for (unsigned int cc = 0; cc<_width; ++cc) for (unsigned int vv = 0; vv<spp; ++vv) buf[i++] = (t)(*this)(cc,row + rr,z,vv); if (TIFFWriteEncodedStrip(tif,strip,buf,i*sizeof(t))<0) throw CImgIOException(_cimg_instance "save_tiff(): Invalid strip writing when saving file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } _TIFFfree(buf); } TIFFWriteDirectory(tif); return *this; } const CImg<T>& _save_tiff(TIFF *tif, const unsigned int directory, const unsigned int z, const unsigned int compression_type, const float *const voxel_size, const char *const description) const { _cimg_save_tiff("bool",unsigned char,compression_type); _cimg_save_tiff("unsigned char",unsigned char,compression_type); _cimg_save_tiff("char",char,compression_type); _cimg_save_tiff("unsigned short",unsigned short,compression_type); _cimg_save_tiff("short",short,compression_type); _cimg_save_tiff("unsigned int",unsigned int,compression_type); _cimg_save_tiff("int",int,compression_type); _cimg_save_tiff("unsigned int64",unsigned int,compression_type); _cimg_save_tiff("int64",int,compression_type); _cimg_save_tiff("float",float,compression_type); _cimg_save_tiff("double",float,compression_type); const char *const filename = TIFFFileName(tif); throw CImgInstanceException(_cimg_instance "save_tiff(): Unsupported pixel type '%s' for file '%s'.", cimg_instance, pixel_type(),filename?filename:"(FILE*)"); return *this; } #endif //! Save image as a MINC2 file. /** \param filename Filename, as a C-string. \param imitate_file If non-zero, reference filename, as a C-string, to borrow header from. **/ const CImg<T>& save_minc2(const char *const filename, const char *const imitate_file=0) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_minc2(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(0,filename); return *this; } #ifndef cimg_use_minc2 cimg::unused(imitate_file); return save_other(filename); #else minc::minc_1_writer wtr; if (imitate_file) wtr.open(filename, imitate_file); else { minc::minc_info di; if (width()) di.push_back(minc::dim_info(width(),width()*0.5,-1,minc::dim_info::DIM_X)); if (height()) di.push_back(minc::dim_info(height(),height()*0.5,-1,minc::dim_info::DIM_Y)); if (depth()) di.push_back(minc::dim_info(depth(),depth()*0.5,-1,minc::dim_info::DIM_Z)); if (spectrum()) di.push_back(minc::dim_info(spectrum(),spectrum()*0.5,-1,minc::dim_info::DIM_TIME)); wtr.open(filename,di,1,NC_FLOAT,0); } if (cimg::type<T>::string()==cimg::type<unsigned char>::string()) wtr.setup_write_byte(); else if (cimg::type<T>::string()==cimg::type<int>::string()) wtr.setup_write_int(); else if (cimg::type<T>::string()==cimg::type<double>::string()) wtr.setup_write_double(); else wtr.setup_write_float(); minc::save_standard_volume(wtr, this->_data); return *this; #endif } //! Save image as an ANALYZE7.5 or NIFTI file. /** \param filename Filename, as a C-string. \param voxel_size Pointer to 3 consecutive values that tell about the voxel sizes along the X,Y and Z dimensions. **/ const CImg<T>& save_analyze(const char *const filename, const float *const voxel_size=0) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_analyze(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(0,filename); return *this; } std::FILE *file; CImg<charT> hname(1024), iname(1024); const char *const ext = cimg::split_filename(filename); short datatype = -1; if (!*ext) { cimg_snprintf(hname,hname._width,"%s.hdr",filename); cimg_snprintf(iname,iname._width,"%s.img",filename); } if (!cimg::strncasecmp(ext,"hdr",3)) { std::strcpy(hname,filename); std::strncpy(iname,filename,iname._width - 1); cimg_sprintf(iname._data + std::strlen(iname) - 3,"img"); } if (!cimg::strncasecmp(ext,"img",3)) { std::strcpy(hname,filename); std::strncpy(iname,filename,iname._width - 1); cimg_sprintf(hname._data + std::strlen(iname) - 3,"hdr"); } if (!cimg::strncasecmp(ext,"nii",3)) { std::strncpy(hname,filename,hname._width - 1); *iname = 0; } CImg<charT> header(*iname?348:352,1,1,1,0); int *const iheader = (int*)header._data; *iheader = 348; std::strcpy(header._data + 4,"CImg"); std::strcpy(header._data + 14," "); ((short*)&(header[36]))[0] = 4096; ((char*)&(header[38]))[0] = 114; ((short*)&(header[40]))[0] = 4; ((short*)&(header[40]))[1] = (short)_width; ((short*)&(header[40]))[2] = (short)_height; ((short*)&(header[40]))[3] = (short)_depth; ((short*)&(header[40]))[4] = (short)_spectrum; if (!cimg::strcasecmp(pixel_type(),"bool")) datatype = 2; if (!cimg::strcasecmp(pixel_type(),"unsigned char")) datatype = 2; if (!cimg::strcasecmp(pixel_type(),"char")) datatype = 2; if (!cimg::strcasecmp(pixel_type(),"unsigned short")) datatype = 4; if (!cimg::strcasecmp(pixel_type(),"short")) datatype = 4; if (!cimg::strcasecmp(pixel_type(),"unsigned int")) datatype = 8; if (!cimg::strcasecmp(pixel_type(),"int")) datatype = 8; if (!cimg::strcasecmp(pixel_type(),"unsigned int64")) datatype = 8; if (!cimg::strcasecmp(pixel_type(),"int64")) datatype = 8; if (!cimg::strcasecmp(pixel_type(),"float")) datatype = 16; if (!cimg::strcasecmp(pixel_type(),"double")) datatype = 64; if (datatype<0) throw CImgIOException(_cimg_instance "save_analyze(): Unsupported pixel type '%s' for file '%s'.", cimg_instance, pixel_type(),filename); ((short*)&(header[70]))[0] = datatype; ((short*)&(header[72]))[0] = sizeof(T); ((float*)&(header[108]))[0] = (float)(*iname?0:header.width()); ((float*)&(header[112]))[0] = 1; ((float*)&(header[76]))[0] = 0; if (voxel_size) { ((float*)&(header[76]))[1] = voxel_size[0]; ((float*)&(header[76]))[2] = voxel_size[1]; ((float*)&(header[76]))[3] = voxel_size[2]; } else ((float*)&(header[76]))[1] = ((float*)&(header[76]))[2] = ((float*)&(header[76]))[3] = 1; file = cimg::fopen(hname,"wb"); cimg::fwrite(header._data,header.width(),file); if (*iname) { cimg::fclose(file); file = cimg::fopen(iname,"wb"); } cimg::fwrite(_data,size(),file); cimg::fclose(file); return *this; } //! Save image as a .cimg file. /** \param filename Filename, as a C-string. \param is_compressed Tells if the file contains compressed image data. **/ const CImg<T>& save_cimg(const char *const filename, const bool is_compressed=false) const { CImgList<T>(*this,true).save_cimg(filename,is_compressed); return *this; } //! Save image as a .cimg file \overloading. const CImg<T>& save_cimg(std::FILE *const file, const bool is_compressed=false) const { CImgList<T>(*this,true).save_cimg(file,is_compressed); return *this; } //! Save image as a sub-image into an existing .cimg file. /** \param filename Filename, as a C-string. \param n0 Index of the image inside the file. \param x0 X-coordinate of the sub-image location. \param y0 Y-coordinate of the sub-image location. \param z0 Z-coordinate of the sub-image location. \param c0 C-coordinate of the sub-image location. **/ const CImg<T>& save_cimg(const char *const filename, const unsigned int n0, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0) const { CImgList<T>(*this,true).save_cimg(filename,n0,x0,y0,z0,c0); return *this; } //! Save image as a sub-image into an existing .cimg file \overloading. const CImg<T>& save_cimg(std::FILE *const file, const unsigned int n0, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0) const { CImgList<T>(*this,true).save_cimg(file,n0,x0,y0,z0,c0); return *this; } //! Save blank image as a .cimg file. /** \param filename Filename, as a C-string. \param dx Width of the image. \param dy Height of the image. \param dz Depth of the image. \param dc Number of channels of the image. \note - All pixel values of the saved image are set to \c 0. - Use this method to save large images without having to instanciate and allocate them. **/ static void save_empty_cimg(const char *const filename, const unsigned int dx, const unsigned int dy=1, const unsigned int dz=1, const unsigned int dc=1) { return CImgList<T>::save_empty_cimg(filename,1,dx,dy,dz,dc); } //! Save blank image as a .cimg file \overloading. /** Same as save_empty_cimg(const char *,unsigned int,unsigned int,unsigned int,unsigned int) with a file stream argument instead of a filename string. **/ static void save_empty_cimg(std::FILE *const file, const unsigned int dx, const unsigned int dy=1, const unsigned int dz=1, const unsigned int dc=1) { return CImgList<T>::save_empty_cimg(file,1,dx,dy,dz,dc); } //! Save image as an INRIMAGE-4 file. /** \param filename Filename, as a C-string. \param voxel_size Pointer to 3 values specifying the voxel sizes along the X,Y and Z dimensions. **/ const CImg<T>& save_inr(const char *const filename, const float *const voxel_size=0) const { return _save_inr(0,filename,voxel_size); } //! Save image as an INRIMAGE-4 file \overloading. const CImg<T>& save_inr(std::FILE *const file, const float *const voxel_size=0) const { return _save_inr(file,0,voxel_size); } const CImg<T>& _save_inr(std::FILE *const file, const char *const filename, const float *const voxel_size) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_inr(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(file,filename); return *this; } int inrpixsize = -1; const char *inrtype = "unsigned fixed\nPIXSIZE=8 bits\nSCALE=2**0"; if (!cimg::strcasecmp(pixel_type(),"unsigned char")) { inrtype = "unsigned fixed\nPIXSIZE=8 bits\nSCALE=2**0"; inrpixsize = 1; } if (!cimg::strcasecmp(pixel_type(),"char")) { inrtype = "fixed\nPIXSIZE=8 bits\nSCALE=2**0"; inrpixsize = 1; } if (!cimg::strcasecmp(pixel_type(),"unsigned short")) { inrtype = "unsigned fixed\nPIXSIZE=16 bits\nSCALE=2**0";inrpixsize = 2; } if (!cimg::strcasecmp(pixel_type(),"short")) { inrtype = "fixed\nPIXSIZE=16 bits\nSCALE=2**0"; inrpixsize = 2; } if (!cimg::strcasecmp(pixel_type(),"unsigned int")) { inrtype = "unsigned fixed\nPIXSIZE=32 bits\nSCALE=2**0";inrpixsize = 4; } if (!cimg::strcasecmp(pixel_type(),"int")) { inrtype = "fixed\nPIXSIZE=32 bits\nSCALE=2**0"; inrpixsize = 4; } if (!cimg::strcasecmp(pixel_type(),"float")) { inrtype = "float\nPIXSIZE=32 bits"; inrpixsize = 4; } if (!cimg::strcasecmp(pixel_type(),"double")) { inrtype = "float\nPIXSIZE=64 bits"; inrpixsize = 8; } if (inrpixsize<=0) throw CImgIOException(_cimg_instance "save_inr(): Unsupported pixel type '%s' for file '%s'", cimg_instance, pixel_type(),filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); CImg<charT> header(257); int err = cimg_snprintf(header,header._width,"#INRIMAGE-4#{\nXDIM=%u\nYDIM=%u\nZDIM=%u\nVDIM=%u\n", _width,_height,_depth,_spectrum); if (voxel_size) err+=cimg_sprintf(header._data + err,"VX=%g\nVY=%g\nVZ=%g\n", voxel_size[0],voxel_size[1],voxel_size[2]); err+=cimg_sprintf(header._data + err,"TYPE=%s\nCPU=%s\n",inrtype,cimg::endianness()?"sun":"decm"); std::memset(header._data + err,'\n',252 - err); std::memcpy(header._data + 252,"##}\n",4); cimg::fwrite(header._data,256,nfile); cimg_forXYZ(*this,x,y,z) cimg_forC(*this,c) cimg::fwrite(&((*this)(x,y,z,c)),1,nfile); if (!file) cimg::fclose(nfile); return *this; } //! Save image as an OpenEXR file. /** \param filename Filename, as a C-string. \note The OpenEXR file format is <a href="http://en.wikipedia.org/wiki/OpenEXR">described here</a>. **/ const CImg<T>& save_exr(const char *const filename) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_exr(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(0,filename); return *this; } if (_depth>1) cimg::warn(_cimg_instance "save_exr(): Instance is volumetric, only the first slice will be saved in file '%s'.", cimg_instance, filename); #ifndef cimg_use_openexr return save_other(filename); #else Imf::Rgba *const ptrd0 = new Imf::Rgba[(size_t)_width*_height], *ptrd = ptrd0, rgba; switch (_spectrum) { case 1 : { // Grayscale image for (const T *ptr_r = data(), *const ptr_e = ptr_r + (ulongT)_width*_height; ptr_r<ptr_e;) { rgba.r = rgba.g = rgba.b = (half)(*(ptr_r++)); rgba.a = (half)1; *(ptrd++) = rgba; } } break; case 2 : { // RG image for (const T *ptr_r = data(), *ptr_g = data(0,0,0,1), *const ptr_e = ptr_r + (ulongT)_width*_height; ptr_r<ptr_e; ) { rgba.r = (half)(*(ptr_r++)); rgba.g = (half)(*(ptr_g++)); rgba.b = (half)0; rgba.a = (half)1; *(ptrd++) = rgba; } } break; case 3 : { // RGB image for (const T *ptr_r = data(), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2), *const ptr_e = ptr_r + (ulongT)_width*_height; ptr_r<ptr_e;) { rgba.r = (half)(*(ptr_r++)); rgba.g = (half)(*(ptr_g++)); rgba.b = (half)(*(ptr_b++)); rgba.a = (half)1; *(ptrd++) = rgba; } } break; default : { // RGBA image for (const T *ptr_r = data(), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2), *ptr_a = data(0,0,0,3), *const ptr_e = ptr_r + (ulongT)_width*_height; ptr_r<ptr_e;) { rgba.r = (half)(*(ptr_r++)); rgba.g = (half)(*(ptr_g++)); rgba.b = (half)(*(ptr_b++)); rgba.a = (half)(*(ptr_a++)); *(ptrd++) = rgba; } } break; } Imf::RgbaOutputFile outFile(filename,_width,_height, _spectrum==1?Imf::WRITE_Y:_spectrum==2?Imf::WRITE_YA:_spectrum==3? Imf::WRITE_RGB:Imf::WRITE_RGBA); outFile.setFrameBuffer(ptrd0,1,_width); outFile.writePixels(_height); delete[] ptrd0; return *this; #endif } //! Save image as a Pandore-5 file. /** \param filename Filename, as a C-string. \param colorspace Colorspace data field in output file (see <a href="http://www.greyc.ensicaen.fr/~regis/Pandore">Pandore file specifications</a> for more information). **/ const CImg<T>& save_pandore(const char *const filename, const unsigned int colorspace=0) const { return _save_pandore(0,filename,colorspace); } //! Save image as a Pandore-5 file \overloading. /** Same as save_pandore(const char *,unsigned int) const with a file stream argument instead of a filename string. **/ const CImg<T>& save_pandore(std::FILE *const file, const unsigned int colorspace=0) const { return _save_pandore(file,0,colorspace); } unsigned int _save_pandore_header_length(unsigned int id, unsigned int *dims, const unsigned int colorspace) const { unsigned int nbdims = 0; if (id==2 || id==3 || id==4) { dims[0] = 1; dims[1] = _width; nbdims = 2; } if (id==5 || id==6 || id==7) { dims[0] = 1; dims[1] = _height; dims[2] = _width; nbdims=3; } if (id==8 || id==9 || id==10) { dims[0] = _spectrum; dims[1] = _depth; dims[2] = _height; dims[3] = _width; nbdims = 4; } if (id==16 || id==17 || id==18) { dims[0] = 3; dims[1] = _height; dims[2] = _width; dims[3] = colorspace; nbdims = 4; } if (id==19 || id==20 || id==21) { dims[0] = 3; dims[1] = _depth; dims[2] = _height; dims[3] = _width; dims[4] = colorspace; nbdims = 5; } if (id==22 || id==23 || id==25) { dims[0] = _spectrum; dims[1] = _width; nbdims = 2; } if (id==26 || id==27 || id==29) { dims[0] = _spectrum; dims[1] = _height; dims[2] = _width; nbdims=3; } if (id==30 || id==31 || id==33) { dims[0] = _spectrum; dims[1] = _depth; dims[2] = _height; dims[3] = _width; nbdims = 4; } return nbdims; } const CImg<T>& _save_pandore(std::FILE *const file, const char *const filename, const unsigned int colorspace) const { #define __cimg_save_pandore_case(dtype) \ dtype *buffer = new dtype[size()]; \ const T *ptrs = _data; \ cimg_foroff(*this,off) *(buffer++) = (dtype)(*(ptrs++)); \ buffer-=size(); \ cimg::fwrite(buffer,size(),nfile); \ delete[] buffer #define _cimg_save_pandore_case(sy,sz,sv,stype,id) \ if (!saved && (sy?(sy==_height):true) && (sz?(sz==_depth):true) && \ (sv?(sv==_spectrum):true) && !std::strcmp(stype,pixel_type())) { \ unsigned int *iheader = (unsigned int*)(header + 12); \ nbdims = _save_pandore_header_length((*iheader=id),dims,colorspace); \ cimg::fwrite(header,36,nfile); \ if (sizeof(unsigned long)==4) { CImg<ulongT> ndims(5); \ for (int d = 0; d<5; ++d) ndims[d] = (unsigned long)dims[d]; cimg::fwrite(ndims._data,nbdims,nfile); } \ else if (sizeof(unsigned int)==4) { CImg<uintT> ndims(5); \ for (int d = 0; d<5; ++d) ndims[d] = (unsigned int)dims[d]; cimg::fwrite(ndims._data,nbdims,nfile); } \ else if (sizeof(unsigned short)==4) { CImg<ushortT> ndims(5); \ for (int d = 0; d<5; ++d) ndims[d] = (unsigned short)dims[d]; cimg::fwrite(ndims._data,nbdims,nfile); } \ else throw CImgIOException(_cimg_instance \ "save_pandore(): Unsupported datatype for file '%s'.",\ cimg_instance, \ filename?filename:"(FILE*)"); \ if (id==2 || id==5 || id==8 || id==16 || id==19 || id==22 || id==26 || id==30) { \ __cimg_save_pandore_case(unsigned char); \ } else if (id==3 || id==6 || id==9 || id==17 || id==20 || id==23 || id==27 || id==31) { \ if (sizeof(unsigned long)==4) { __cimg_save_pandore_case(unsigned long); } \ else if (sizeof(unsigned int)==4) { __cimg_save_pandore_case(unsigned int); } \ else if (sizeof(unsigned short)==4) { __cimg_save_pandore_case(unsigned short); } \ else throw CImgIOException(_cimg_instance \ "save_pandore(): Unsupported datatype for file '%s'.",\ cimg_instance, \ filename?filename:"(FILE*)"); \ } else if (id==4 || id==7 || id==10 || id==18 || id==21 || id==25 || id==29 || id==33) { \ if (sizeof(double)==4) { __cimg_save_pandore_case(double); } \ else if (sizeof(float)==4) { __cimg_save_pandore_case(float); } \ else throw CImgIOException(_cimg_instance \ "save_pandore(): Unsupported datatype for file '%s'.",\ cimg_instance, \ filename?filename:"(FILE*)"); \ } \ saved = true; \ } if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_pandore(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(file,filename); return *this; } std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); unsigned char header[36] = { 'P','A','N','D','O','R','E','0','4',0,0,0, 0,0,0,0,'C','I','m','g',0,0,0,0,0, 'N','o',' ','d','a','t','e',0,0,0,0 }; unsigned int nbdims, dims[5] = { 0 }; bool saved = false; _cimg_save_pandore_case(1,1,1,"unsigned char",2); _cimg_save_pandore_case(1,1,1,"char",3); _cimg_save_pandore_case(1,1,1,"unsigned short",3); _cimg_save_pandore_case(1,1,1,"short",3); _cimg_save_pandore_case(1,1,1,"unsigned int",3); _cimg_save_pandore_case(1,1,1,"int",3); _cimg_save_pandore_case(1,1,1,"unsigned int64",3); _cimg_save_pandore_case(1,1,1,"int64",3); _cimg_save_pandore_case(1,1,1,"float",4); _cimg_save_pandore_case(1,1,1,"double",4); _cimg_save_pandore_case(0,1,1,"unsigned char",5); _cimg_save_pandore_case(0,1,1,"char",6); _cimg_save_pandore_case(0,1,1,"unsigned short",6); _cimg_save_pandore_case(0,1,1,"short",6); _cimg_save_pandore_case(0,1,1,"unsigned int",6); _cimg_save_pandore_case(0,1,1,"int",6); _cimg_save_pandore_case(0,1,1,"unsigned int64",6); _cimg_save_pandore_case(0,1,1,"int64",6); _cimg_save_pandore_case(0,1,1,"float",7); _cimg_save_pandore_case(0,1,1,"double",7); _cimg_save_pandore_case(0,0,1,"unsigned char",8); _cimg_save_pandore_case(0,0,1,"char",9); _cimg_save_pandore_case(0,0,1,"unsigned short",9); _cimg_save_pandore_case(0,0,1,"short",9); _cimg_save_pandore_case(0,0,1,"unsigned int",9); _cimg_save_pandore_case(0,0,1,"int",9); _cimg_save_pandore_case(0,0,1,"unsigned int64",9); _cimg_save_pandore_case(0,0,1,"int64",9); _cimg_save_pandore_case(0,0,1,"float",10); _cimg_save_pandore_case(0,0,1,"double",10); _cimg_save_pandore_case(0,1,3,"unsigned char",16); _cimg_save_pandore_case(0,1,3,"char",17); _cimg_save_pandore_case(0,1,3,"unsigned short",17); _cimg_save_pandore_case(0,1,3,"short",17); _cimg_save_pandore_case(0,1,3,"unsigned int",17); _cimg_save_pandore_case(0,1,3,"int",17); _cimg_save_pandore_case(0,1,3,"unsigned int64",17); _cimg_save_pandore_case(0,1,3,"int64",17); _cimg_save_pandore_case(0,1,3,"float",18); _cimg_save_pandore_case(0,1,3,"double",18); _cimg_save_pandore_case(0,0,3,"unsigned char",19); _cimg_save_pandore_case(0,0,3,"char",20); _cimg_save_pandore_case(0,0,3,"unsigned short",20); _cimg_save_pandore_case(0,0,3,"short",20); _cimg_save_pandore_case(0,0,3,"unsigned int",20); _cimg_save_pandore_case(0,0,3,"int",20); _cimg_save_pandore_case(0,0,3,"unsigned int64",20); _cimg_save_pandore_case(0,0,3,"int64",20); _cimg_save_pandore_case(0,0,3,"float",21); _cimg_save_pandore_case(0,0,3,"double",21); _cimg_save_pandore_case(1,1,0,"unsigned char",22); _cimg_save_pandore_case(1,1,0,"char",23); _cimg_save_pandore_case(1,1,0,"unsigned short",23); _cimg_save_pandore_case(1,1,0,"short",23); _cimg_save_pandore_case(1,1,0,"unsigned int",23); _cimg_save_pandore_case(1,1,0,"int",23); _cimg_save_pandore_case(1,1,0,"unsigned int64",23); _cimg_save_pandore_case(1,1,0,"int64",23); _cimg_save_pandore_case(1,1,0,"float",25); _cimg_save_pandore_case(1,1,0,"double",25); _cimg_save_pandore_case(0,1,0,"unsigned char",26); _cimg_save_pandore_case(0,1,0,"char",27); _cimg_save_pandore_case(0,1,0,"unsigned short",27); _cimg_save_pandore_case(0,1,0,"short",27); _cimg_save_pandore_case(0,1,0,"unsigned int",27); _cimg_save_pandore_case(0,1,0,"int",27); _cimg_save_pandore_case(0,1,0,"unsigned int64",27); _cimg_save_pandore_case(0,1,0,"int64",27); _cimg_save_pandore_case(0,1,0,"float",29); _cimg_save_pandore_case(0,1,0,"double",29); _cimg_save_pandore_case(0,0,0,"unsigned char",30); _cimg_save_pandore_case(0,0,0,"char",31); _cimg_save_pandore_case(0,0,0,"unsigned short",31); _cimg_save_pandore_case(0,0,0,"short",31); _cimg_save_pandore_case(0,0,0,"unsigned int",31); _cimg_save_pandore_case(0,0,0,"int",31); _cimg_save_pandore_case(0,0,0,"unsigned int64",31); _cimg_save_pandore_case(0,0,0,"int64",31); _cimg_save_pandore_case(0,0,0,"float",33); _cimg_save_pandore_case(0,0,0,"double",33); if (!file) cimg::fclose(nfile); return *this; } //! Save image as a raw data file. /** \param filename Filename, as a C-string. \param is_multiplexed Tells if the image channels are stored in a multiplexed way (\c true) or not (\c false). \note The .raw format does not store the image dimensions in the output file, so you have to keep track of them somewhere to be able to read the file correctly afterwards. **/ const CImg<T>& save_raw(const char *const filename, const bool is_multiplexed=false) const { return _save_raw(0,filename,is_multiplexed); } //! Save image as a raw data file \overloading. /** Same as save_raw(const char *,bool) const with a file stream argument instead of a filename string. **/ const CImg<T>& save_raw(std::FILE *const file, const bool is_multiplexed=false) const { return _save_raw(file,0,is_multiplexed); } const CImg<T>& _save_raw(std::FILE *const file, const char *const filename, const bool is_multiplexed) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_raw(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(file,filename); return *this; } std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); if (!is_multiplexed) cimg::fwrite(_data,size(),nfile); else { CImg<T> buf(_spectrum); cimg_forXYZ(*this,x,y,z) { cimg_forC(*this,c) buf[c] = (*this)(x,y,z,c); cimg::fwrite(buf._data,_spectrum,nfile); } } if (!file) cimg::fclose(nfile); return *this; } //! Save image as a .yuv video file. /** \param filename Filename, as a C-string. \param chroma_subsampling Type of chroma subsampling. Can be <tt>{ 420 | 422 | 444 }</tt>. \param is_rgb Tells if pixel values of the instance image are RGB-coded (\c true) or YUV-coded (\c false). \note Each slice of the instance image is considered to be a single frame of the output video file. **/ const CImg<T>& save_yuv(const char *const filename, const unsigned int chroma_subsampling=444, const bool is_rgb=true) const { CImgList<T>(*this,true).save_yuv(filename,chroma_subsampling,is_rgb); return *this; } //! Save image as a .yuv video file \overloading. /** Same as save_yuv(const char*,const unsigned int,const bool) const with a file stream argument instead of a filename string. **/ const CImg<T>& save_yuv(std::FILE *const file, const unsigned int chroma_subsampling=444, const bool is_rgb=true) const { CImgList<T>(*this,true).save_yuv(file,chroma_subsampling,is_rgb); return *this; } //! Save 3D object as an Object File Format (.off) file. /** \param filename Filename, as a C-string. \param primitives List of 3D object primitives. \param colors List of 3D object colors. \note - Instance image contains the vertices data of the 3D object. - Textured, transparent or sphere-shaped primitives cannot be managed by the .off file format. Such primitives will be lost or simplified during file saving. - The .off file format is <a href="http://people.sc.fsu.edu/~jburkardt/html/off_format.html">described here</a>. **/ template<typename tf, typename tc> const CImg<T>& save_off(const CImgList<tf>& primitives, const CImgList<tc>& colors, const char *const filename) const { return _save_off(primitives,colors,0,filename); } //! Save 3D object as an Object File Format (.off) file \overloading. /** Same as save_off(const CImgList<tf>&,const CImgList<tc>&,const char*) const with a file stream argument instead of a filename string. **/ template<typename tf, typename tc> const CImg<T>& save_off(const CImgList<tf>& primitives, const CImgList<tc>& colors, std::FILE *const file) const { return _save_off(primitives,colors,file,0); } template<typename tf, typename tc> const CImg<T>& _save_off(const CImgList<tf>& primitives, const CImgList<tc>& colors, std::FILE *const file, const char *const filename) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_off(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_off(): Empty instance, for file '%s'.", cimg_instance, filename?filename:"(FILE*)"); CImgList<T> opacities; CImg<charT> error_message(1024); if (!is_object3d(primitives,colors,opacities,true,error_message)) throw CImgInstanceException(_cimg_instance "save_off(): Invalid specified 3D object, for file '%s' (%s).", cimg_instance, filename?filename:"(FILE*)",error_message.data()); const CImg<tc> default_color(1,3,1,1,(tc)std::min((int)cimg::type<tc>::max(),200)); std::FILE *const nfile = file?file:cimg::fopen(filename,"w"); unsigned int supported_primitives = 0; cimglist_for(primitives,l) if (primitives[l].size()!=5) ++supported_primitives; std::fprintf(nfile,"OFF\n%u %u %u\n",_width,supported_primitives,3*primitives._width); cimg_forX(*this,i) std::fprintf(nfile,"%f %f %f\n", (float)((*this)(i,0)),(float)((*this)(i,1)),(float)((*this)(i,2))); cimglist_for(primitives,l) { const CImg<tc>& color = l<colors.width()?colors[l]:default_color; const unsigned int psiz = primitives[l].size(), csiz = color.size(); const float r = color[0]/255.f, g = (csiz>1?color[1]:r)/255.f, b = (csiz>2?color[2]:g)/255.f; switch (psiz) { case 1 : std::fprintf(nfile,"1 %u %f %f %f\n", (unsigned int)primitives(l,0),r,g,b); break; case 2 : std::fprintf(nfile,"2 %u %u %f %f %f\n", (unsigned int)primitives(l,0),(unsigned int)primitives(l,1),r,g,b); break; case 3 : std::fprintf(nfile,"3 %u %u %u %f %f %f\n", (unsigned int)primitives(l,0),(unsigned int)primitives(l,2), (unsigned int)primitives(l,1),r,g,b); break; case 4 : std::fprintf(nfile,"4 %u %u %u %u %f %f %f\n", (unsigned int)primitives(l,0),(unsigned int)primitives(l,3), (unsigned int)primitives(l,2),(unsigned int)primitives(l,1),r,g,b); break; case 5 : std::fprintf(nfile,"2 %u %u %f %f %f\n", (unsigned int)primitives(l,0),(unsigned int)primitives(l,1),r,g,b); break; case 6 : { const unsigned int xt = (unsigned int)primitives(l,2), yt = (unsigned int)primitives(l,3); const float rt = color.atXY(xt,yt,0)/255.f, gt = (csiz>1?color.atXY(xt,yt,1):r)/255.f, bt = (csiz>2?color.atXY(xt,yt,2):g)/255.f; std::fprintf(nfile,"2 %u %u %f %f %f\n", (unsigned int)primitives(l,0),(unsigned int)primitives(l,1),rt,gt,bt); } break; case 9 : { const unsigned int xt = (unsigned int)primitives(l,3), yt = (unsigned int)primitives(l,4); const float rt = color.atXY(xt,yt,0)/255.f, gt = (csiz>1?color.atXY(xt,yt,1):r)/255.f, bt = (csiz>2?color.atXY(xt,yt,2):g)/255.f; std::fprintf(nfile,"3 %u %u %u %f %f %f\n", (unsigned int)primitives(l,0),(unsigned int)primitives(l,2), (unsigned int)primitives(l,1),rt,gt,bt); } break; case 12 : { const unsigned int xt = (unsigned int)primitives(l,4), yt = (unsigned int)primitives(l,5); const float rt = color.atXY(xt,yt,0)/255.f, gt = (csiz>1?color.atXY(xt,yt,1):r)/255.f, bt = (csiz>2?color.atXY(xt,yt,2):g)/255.f; std::fprintf(nfile,"4 %u %u %u %u %f %f %f\n", (unsigned int)primitives(l,0),(unsigned int)primitives(l,3), (unsigned int)primitives(l,2),(unsigned int)primitives(l,1),rt,gt,bt); } break; } } if (!file) cimg::fclose(nfile); return *this; } //! Save volumetric image as a video, using the OpenCV library. /** \param filename Filename to write data to. \param fps Number of frames per second. \param codec Type of compression (See http://www.fourcc.org/codecs.php to see available codecs). \param keep_open Tells if the video writer associated to the specified filename must be kept open or not (to allow frames to be added in the same file afterwards). **/ const CImg<T>& save_video(const char *const filename, const unsigned int fps=25, const char *codec=0, const bool keep_open=false) const { if (is_empty()) { CImgList<T>().save_video(filename,fps,codec,keep_open); return *this; } CImgList<T> list; get_split('z').move_to(list); list.save_video(filename,fps,codec,keep_open); return *this; } //! Save volumetric image as a video, using ffmpeg external binary. /** \param filename Filename, as a C-string. \param fps Video framerate. \param codec Video codec, as a C-string. \param bitrate Video bitrate. \note - Each slice of the instance image is considered to be a single frame of the output video file. - This method uses \c ffmpeg, an external executable binary provided by <a href="http://www.ffmpeg.org">FFmpeg</a>. It must be installed for the method to succeed. **/ const CImg<T>& save_ffmpeg_external(const char *const filename, const unsigned int fps=25, const char *const codec=0, const unsigned int bitrate=2048) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_ffmpeg_external(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(0,filename); return *this; } CImgList<T> list; get_split('z').move_to(list); list.save_ffmpeg_external(filename,fps,codec,bitrate); return *this; } //! Save image using gzip external binary. /** \param filename Filename, as a C-string. \note This method uses \c gzip, an external executable binary provided by <a href="//http://www.gzip.org">gzip</a>. It must be installed for the method to succeed. **/ const CImg<T>& save_gzip_external(const char *const filename) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_gzip_external(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(0,filename); return *this; } CImg<charT> command(1024), filename_tmp(256), body(256); const char *ext = cimg::split_filename(filename,body), *ext2 = cimg::split_filename(body,0); std::FILE *file; do { if (!cimg::strcasecmp(ext,"gz")) { if (*ext2) cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),ext2); else cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.cimg", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); } else { if (*ext) cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),ext); else cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.cimg", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); } if ((file=cimg::std_fopen(filename_tmp,"rb"))!=0) cimg::fclose(file); } while (file); save(filename_tmp); cimg_snprintf(command,command._width,"%s -c \"%s\" > \"%s\"", cimg::gzip_path(), CImg<charT>::string(filename_tmp)._system_strescape().data(), CImg<charT>::string(filename)._system_strescape().data()); cimg::system(command); file = cimg::std_fopen(filename,"rb"); if (!file) throw CImgIOException(_cimg_instance "save_gzip_external(): Failed to save file '%s' with external command 'gzip'.", cimg_instance, filename); else cimg::fclose(file); std::remove(filename_tmp); return *this; } //! Save image using GraphicsMagick's external binary. /** \param filename Filename, as a C-string. \param quality Image quality (expressed in percent), when the file format supports it. \note This method uses \c gm, an external executable binary provided by <a href="http://www.graphicsmagick.org">GraphicsMagick</a>. It must be installed for the method to succeed. **/ const CImg<T>& save_graphicsmagick_external(const char *const filename, const unsigned int quality=100) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_graphicsmagick_external(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(0,filename); return *this; } if (_depth>1) cimg::warn(_cimg_instance "save_other(): File '%s', saving a volumetric image with an external call to " "GraphicsMagick only writes the first image slice.", cimg_instance,filename); #ifdef cimg_use_png #define _cimg_sge_ext1 "png" #define _cimg_sge_ext2 "png" #else #define _cimg_sge_ext1 "pgm" #define _cimg_sge_ext2 "ppm" #endif CImg<charT> command(1024), filename_tmp(256); std::FILE *file; do { cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(), _spectrum==1?_cimg_sge_ext1:_cimg_sge_ext2); if ((file=cimg::std_fopen(filename_tmp,"rb"))!=0) cimg::fclose(file); } while (file); #ifdef cimg_use_png save_png(filename_tmp); #else save_pnm(filename_tmp); #endif cimg_snprintf(command,command._width,"%s convert -quality %u \"%s\" \"%s\"", cimg::graphicsmagick_path(),quality, CImg<charT>::string(filename_tmp)._system_strescape().data(), CImg<charT>::string(filename)._system_strescape().data()); cimg::system(command); file = cimg::std_fopen(filename,"rb"); if (!file) throw CImgIOException(_cimg_instance "save_graphicsmagick_external(): Failed to save file '%s' with external command 'gm'.", cimg_instance, filename); if (file) cimg::fclose(file); std::remove(filename_tmp); return *this; } //! Save image using ImageMagick's external binary. /** \param filename Filename, as a C-string. \param quality Image quality (expressed in percent), when the file format supports it. \note This method uses \c convert, an external executable binary provided by <a href="http://www.imagemagick.org">ImageMagick</a>. It must be installed for the method to succeed. **/ const CImg<T>& save_imagemagick_external(const char *const filename, const unsigned int quality=100) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_imagemagick_external(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(0,filename); return *this; } if (_depth>1) cimg::warn(_cimg_instance "save_other(): File '%s', saving a volumetric image with an external call to " "ImageMagick only writes the first image slice.", cimg_instance,filename); #ifdef cimg_use_png #define _cimg_sie_ext1 "png" #define _cimg_sie_ext2 "png" #else #define _cimg_sie_ext1 "pgm" #define _cimg_sie_ext2 "ppm" #endif CImg<charT> command(1024), filename_tmp(256); std::FILE *file; do { cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.%s",cimg::temporary_path(), cimg_file_separator,cimg::filenamerand(),_spectrum==1?_cimg_sie_ext1:_cimg_sie_ext2); if ((file=cimg::std_fopen(filename_tmp,"rb"))!=0) cimg::fclose(file); } while (file); #ifdef cimg_use_png save_png(filename_tmp); #else save_pnm(filename_tmp); #endif cimg_snprintf(command,command._width,"%s -quality %u \"%s\" \"%s\"", cimg::imagemagick_path(),quality, CImg<charT>::string(filename_tmp)._system_strescape().data(), CImg<charT>::string(filename)._system_strescape().data()); cimg::system(command); file = cimg::std_fopen(filename,"rb"); if (!file) throw CImgIOException(_cimg_instance "save_imagemagick_external(): Failed to save file '%s' with " "external command 'magick/convert'.", cimg_instance, filename); if (file) cimg::fclose(file); std::remove(filename_tmp); return *this; } //! Save image as a Dicom file. /** \param filename Filename, as a C-string. \note This method uses \c medcon, an external executable binary provided by <a href="http://xmedcon.sourceforge.net">(X)Medcon</a>. It must be installed for the method to succeed. **/ const CImg<T>& save_medcon_external(const char *const filename) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_medcon_external(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(0,filename); return *this; } CImg<charT> command(1024), filename_tmp(256), body(256); std::FILE *file; do { cimg_snprintf(filename_tmp,filename_tmp._width,"%s.hdr",cimg::filenamerand()); if ((file=cimg::std_fopen(filename_tmp,"rb"))!=0) cimg::fclose(file); } while (file); save_analyze(filename_tmp); cimg_snprintf(command,command._width,"%s -w -c dicom -o \"%s\" -f \"%s\"", cimg::medcon_path(), CImg<charT>::string(filename)._system_strescape().data(), CImg<charT>::string(filename_tmp)._system_strescape().data()); cimg::system(command); std::remove(filename_tmp); cimg::split_filename(filename_tmp,body); cimg_snprintf(filename_tmp,filename_tmp._width,"%s.img",body._data); std::remove(filename_tmp); file = cimg::std_fopen(filename,"rb"); if (!file) { cimg_snprintf(command,command._width,"m000-%s",filename); file = cimg::std_fopen(command,"rb"); if (!file) { cimg::fclose(cimg::fopen(filename,"r")); throw CImgIOException(_cimg_instance "save_medcon_external(): Failed to save file '%s' with external command 'medcon'.", cimg_instance, filename); } } cimg::fclose(file); std::rename(command,filename); return *this; } // Save image for non natively supported formats. /** \param filename Filename, as a C-string. \param quality Image quality (expressed in percent), when the file format supports it. \note - The filename extension tells about the desired file format. - This method tries to save the instance image as a file, using external tools from <a href="http://www.imagemagick.org">ImageMagick</a> or <a href="http://www.graphicsmagick.org">GraphicsMagick</a>. At least one of these tool must be installed for the method to succeed. - It is recommended to use the generic method save(const char*, int) const instead, as it can handle some file formats natively. **/ const CImg<T>& save_other(const char *const filename, const unsigned int quality=100) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_other(): Specified filename is (null).", cimg_instance); if (is_empty()) { cimg::fempty(0,filename); return *this; } if (_depth>1) cimg::warn(_cimg_instance "save_other(): File '%s', saving a volumetric image with an external call to " "ImageMagick or GraphicsMagick only writes the first image slice.", cimg_instance,filename); const unsigned int omode = cimg::exception_mode(); bool is_saved = true; cimg::exception_mode(0); try { save_magick(filename); } catch (CImgException&) { try { save_imagemagick_external(filename,quality); } catch (CImgException&) { try { save_graphicsmagick_external(filename,quality); } catch (CImgException&) { is_saved = false; } } } cimg::exception_mode(omode); if (!is_saved) throw CImgIOException(_cimg_instance "save_other(): Failed to save file '%s'. Format is not natively supported, " "and no external commands succeeded.", cimg_instance, filename); return *this; } //! Serialize a CImg<T> instance into a raw CImg<unsigned char> buffer. /** \param is_compressed tells if zlib compression must be used for serialization (this requires 'cimg_use_zlib' been enabled). **/ CImg<ucharT> get_serialize(const bool is_compressed=false) const { return CImgList<T>(*this,true).get_serialize(is_compressed); } // [internal] Return a 40x38 color logo of a 'danger' item. static CImg<T> _logo40x38() { CImg<T> res(40,38,1,3); const unsigned char *ptrs = cimg::logo40x38; T *ptr1 = res.data(0,0,0,0), *ptr2 = res.data(0,0,0,1), *ptr3 = res.data(0,0,0,2); for (ulongT off = 0; off<(ulongT)res._width*res._height;) { const unsigned char n = *(ptrs++), r = *(ptrs++), g = *(ptrs++), b = *(ptrs++); for (unsigned int l = 0; l<n; ++off, ++l) { *(ptr1++) = (T)r; *(ptr2++) = (T)g; *(ptr3++) = (T)b; } } return res; } //@} }; // struct CImg { ... /* #----------------------------------------- # # # # Definition of the CImgList<T> structure # # # #------------------------------------------ */ //! Represent a list of images CImg<T>. template<typename T> struct CImgList { unsigned int _width, _allocated_width; CImg<T> *_data; //! Simple iterator type, to loop through each image of a list. /** \note - The \c CImgList<T>::iterator type is defined as a <tt>CImg<T>*</tt>. - You may use it like this: \code CImgList<> list; // Assuming this image list is not empty for (CImgList<>::iterator it = list.begin(); it<list.end(); ++it) (*it).mirror('x'); \endcode - Using the loop macro \c cimglist_for is another (more concise) alternative: \code cimglist_for(list,l) list[l].mirror('x'); \endcode **/ typedef CImg<T>* iterator; //! Simple const iterator type, to loop through each image of a \c const list instance. /** \note - The \c CImgList<T>::const_iterator type is defined to be a <tt>const CImg<T>*</tt>. - Similar to CImgList<T>::iterator, but for constant list instances. **/ typedef const CImg<T>* const_iterator; //! Pixel value type. /** Refer to the pixels value type of the images in the list. \note - The \c CImgList<T>::value_type type of a \c CImgList<T> is defined to be a \c T. It is then similar to CImg<T>::value_type. - \c CImgList<T>::value_type is actually not used in %CImg methods. It has been mainly defined for compatibility with STL naming conventions. **/ typedef T value_type; // Define common types related to template type T. typedef typename cimg::superset<T,bool>::type Tbool; typedef typename cimg::superset<T,unsigned char>::type Tuchar; typedef typename cimg::superset<T,char>::type Tchar; typedef typename cimg::superset<T,unsigned short>::type Tushort; typedef typename cimg::superset<T,short>::type Tshort; typedef typename cimg::superset<T,unsigned int>::type Tuint; typedef typename cimg::superset<T,int>::type Tint; typedef typename cimg::superset<T,cimg_ulong>::type Tulong; typedef typename cimg::superset<T,cimg_long>::type Tlong; typedef typename cimg::superset<T,float>::type Tfloat; typedef typename cimg::superset<T,double>::type Tdouble; typedef typename cimg::last<T,bool>::type boolT; typedef typename cimg::last<T,unsigned char>::type ucharT; typedef typename cimg::last<T,char>::type charT; typedef typename cimg::last<T,unsigned short>::type ushortT; typedef typename cimg::last<T,short>::type shortT; typedef typename cimg::last<T,unsigned int>::type uintT; typedef typename cimg::last<T,int>::type intT; typedef typename cimg::last<T,cimg_ulong>::type ulongT; typedef typename cimg::last<T,cimg_long>::type longT; typedef typename cimg::last<T,cimg_uint64>::type uint64T; typedef typename cimg::last<T,cimg_int64>::type int64T; typedef typename cimg::last<T,float>::type floatT; typedef typename cimg::last<T,double>::type doubleT; //@} //--------------------------- // //! \name Plugins //@{ //--------------------------- #ifdef cimglist_plugin #include cimglist_plugin #endif #ifdef cimglist_plugin1 #include cimglist_plugin1 #endif #ifdef cimglist_plugin2 #include cimglist_plugin2 #endif #ifdef cimglist_plugin3 #include cimglist_plugin3 #endif #ifdef cimglist_plugin4 #include cimglist_plugin4 #endif #ifdef cimglist_plugin5 #include cimglist_plugin5 #endif #ifdef cimglist_plugin6 #include cimglist_plugin6 #endif #ifdef cimglist_plugin7 #include cimglist_plugin7 #endif #ifdef cimglist_plugin8 #include cimglist_plugin8 #endif //@} //-------------------------------------------------------- // //! \name Constructors / Destructor / Instance Management //@{ //-------------------------------------------------------- //! Destructor. /** Destroy current list instance. \note - Any allocated buffer is deallocated. - Destroying an empty list does nothing actually. **/ ~CImgList() { delete[] _data; } //! Default constructor. /** Construct a new empty list instance. \note - An empty list has no pixel data and its dimension width() is set to \c 0, as well as its image buffer pointer data(). - An empty list may be reassigned afterwards, with the family of the assign() methods. In all cases, the type of pixels stays \c T. **/ CImgList(): _width(0),_allocated_width(0),_data(0) {} //! Construct list containing empty images. /** \param n Number of empty images. \note Useful when you know by advance the number of images you want to manage, as it will allocate the right amount of memory for the list, without needs for reallocation (that may occur when starting from an empty list and inserting several images in it). **/ explicit CImgList(const unsigned int n):_width(n) { if (n) _data = new CImg<T>[_allocated_width = std::max(16U,(unsigned int)cimg::nearest_pow2(n))]; else { _allocated_width = 0; _data = 0; } } //! Construct list containing images of specified size. /** \param n Number of images. \param width Width of images. \param height Height of images. \param depth Depth of images. \param spectrum Number of channels of images. \note Pixel values are not initialized and may probably contain garbage. **/ CImgList(const unsigned int n, const unsigned int width, const unsigned int height=1, const unsigned int depth=1, const unsigned int spectrum=1): _width(0),_allocated_width(0),_data(0) { assign(n); cimglist_apply(*this,assign)(width,height,depth,spectrum); } //! Construct list containing images of specified size, and initialize pixel values. /** \param n Number of images. \param width Width of images. \param height Height of images. \param depth Depth of images. \param spectrum Number of channels of images. \param val Initialization value for images pixels. **/ CImgList(const unsigned int n, const unsigned int width, const unsigned int height, const unsigned int depth, const unsigned int spectrum, const T& val): _width(0),_allocated_width(0),_data(0) { assign(n); cimglist_apply(*this,assign)(width,height,depth,spectrum,val); } //! Construct list containing images of specified size, and initialize pixel values from a sequence of integers. /** \param n Number of images. \param width Width of images. \param height Height of images. \param depth Depth of images. \param spectrum Number of channels of images. \param val0 First value of the initializing integers sequence. \param val1 Second value of the initializing integers sequence. \warning You must specify at least <tt>width*height*depth*spectrum</tt> values in your argument list, or you will probably segfault. **/ CImgList(const unsigned int n, const unsigned int width, const unsigned int height, const unsigned int depth, const unsigned int spectrum, const int val0, const int val1, ...): _width(0),_allocated_width(0),_data(0) { #define _CImgList_stdarg(t) { \ assign(n,width,height,depth,spectrum); \ const ulongT siz = (ulongT)width*height*depth*spectrum, nsiz = siz*n; \ T *ptrd = _data->_data; \ va_list ap; \ va_start(ap,val1); \ for (ulongT l = 0, s = 0, i = 0; i<nsiz; ++i) { \ *(ptrd++) = (T)(i==0?val0:(i==1?val1:va_arg(ap,t))); \ if ((++s)==siz) { ptrd = _data[++l]._data; s = 0; } \ } \ va_end(ap); \ } _CImgList_stdarg(int); } //! Construct list containing images of specified size, and initialize pixel values from a sequence of doubles. /** \param n Number of images. \param width Width of images. \param height Height of images. \param depth Depth of images. \param spectrum Number of channels of images. \param val0 First value of the initializing doubles sequence. \param val1 Second value of the initializing doubles sequence. \warning You must specify at least <tt>width*height*depth*spectrum</tt> values in your argument list, or you will probably segfault. **/ CImgList(const unsigned int n, const unsigned int width, const unsigned int height, const unsigned int depth, const unsigned int spectrum, const double val0, const double val1, ...): _width(0),_allocated_width(0),_data(0) { _CImgList_stdarg(double); } //! Construct list containing copies of an input image. /** \param n Number of images. \param img Input image to copy in the constructed list. \param is_shared Tells if the elements of the list are shared or non-shared copies of \c img. **/ template<typename t> CImgList(const unsigned int n, const CImg<t>& img, const bool is_shared=false): _width(0),_allocated_width(0),_data(0) { assign(n); cimglist_apply(*this,assign)(img,is_shared); } //! Construct list from one image. /** \param img Input image to copy in the constructed list. \param is_shared Tells if the element of the list is a shared or non-shared copy of \c img. **/ template<typename t> explicit CImgList(const CImg<t>& img, const bool is_shared=false): _width(0),_allocated_width(0),_data(0) { assign(1); _data[0].assign(img,is_shared); } //! Construct list from two images. /** \param img1 First input image to copy in the constructed list. \param img2 Second input image to copy in the constructed list. \param is_shared Tells if the elements of the list are shared or non-shared copies of input images. **/ template<typename t1, typename t2> CImgList(const CImg<t1>& img1, const CImg<t2>& img2, const bool is_shared=false): _width(0),_allocated_width(0),_data(0) { assign(2); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); } //! Construct list from three images. /** \param img1 First input image to copy in the constructed list. \param img2 Second input image to copy in the constructed list. \param img3 Third input image to copy in the constructed list. \param is_shared Tells if the elements of the list are shared or non-shared copies of input images. **/ template<typename t1, typename t2, typename t3> CImgList(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const bool is_shared=false): _width(0),_allocated_width(0),_data(0) { assign(3); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); } //! Construct list from four images. /** \param img1 First input image to copy in the constructed list. \param img2 Second input image to copy in the constructed list. \param img3 Third input image to copy in the constructed list. \param img4 Fourth input image to copy in the constructed list. \param is_shared Tells if the elements of the list are shared or non-shared copies of input images. **/ template<typename t1, typename t2, typename t3, typename t4> CImgList(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const bool is_shared=false): _width(0),_allocated_width(0),_data(0) { assign(4); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); } //! Construct list from five images. /** \param img1 First input image to copy in the constructed list. \param img2 Second input image to copy in the constructed list. \param img3 Third input image to copy in the constructed list. \param img4 Fourth input image to copy in the constructed list. \param img5 Fifth input image to copy in the constructed list. \param is_shared Tells if the elements of the list are shared or non-shared copies of input images. **/ template<typename t1, typename t2, typename t3, typename t4, typename t5> CImgList(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const CImg<t5>& img5, const bool is_shared=false): _width(0),_allocated_width(0),_data(0) { assign(5); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); _data[4].assign(img5,is_shared); } //! Construct list from six images. /** \param img1 First input image to copy in the constructed list. \param img2 Second input image to copy in the constructed list. \param img3 Third input image to copy in the constructed list. \param img4 Fourth input image to copy in the constructed list. \param img5 Fifth input image to copy in the constructed list. \param img6 Sixth input image to copy in the constructed list. \param is_shared Tells if the elements of the list are shared or non-shared copies of input images. **/ template<typename t1, typename t2, typename t3, typename t4, typename t5, typename t6> CImgList(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const CImg<t5>& img5, const CImg<t6>& img6, const bool is_shared=false): _width(0),_allocated_width(0),_data(0) { assign(6); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); _data[4].assign(img5,is_shared); _data[5].assign(img6,is_shared); } //! Construct list from seven images. /** \param img1 First input image to copy in the constructed list. \param img2 Second input image to copy in the constructed list. \param img3 Third input image to copy in the constructed list. \param img4 Fourth input image to copy in the constructed list. \param img5 Fifth input image to copy in the constructed list. \param img6 Sixth input image to copy in the constructed list. \param img7 Seventh input image to copy in the constructed list. \param is_shared Tells if the elements of the list are shared or non-shared copies of input images. **/ template<typename t1, typename t2, typename t3, typename t4, typename t5, typename t6, typename t7> CImgList(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const CImg<t5>& img5, const CImg<t6>& img6, const CImg<t7>& img7, const bool is_shared=false): _width(0),_allocated_width(0),_data(0) { assign(7); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); _data[4].assign(img5,is_shared); _data[5].assign(img6,is_shared); _data[6].assign(img7,is_shared); } //! Construct list from eight images. /** \param img1 First input image to copy in the constructed list. \param img2 Second input image to copy in the constructed list. \param img3 Third input image to copy in the constructed list. \param img4 Fourth input image to copy in the constructed list. \param img5 Fifth input image to copy in the constructed list. \param img6 Sixth input image to copy in the constructed list. \param img7 Seventh input image to copy in the constructed list. \param img8 Eighth input image to copy in the constructed list. \param is_shared Tells if the elements of the list are shared or non-shared copies of input images. **/ template<typename t1, typename t2, typename t3, typename t4, typename t5, typename t6, typename t7, typename t8> CImgList(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const CImg<t5>& img5, const CImg<t6>& img6, const CImg<t7>& img7, const CImg<t8>& img8, const bool is_shared=false): _width(0),_allocated_width(0),_data(0) { assign(8); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); _data[4].assign(img5,is_shared); _data[5].assign(img6,is_shared); _data[6].assign(img7,is_shared); _data[7].assign(img8,is_shared); } //! Construct list copy. /** \param list Input list to copy. \note The shared state of each element of the constructed list is kept the same as in \c list. **/ template<typename t> CImgList(const CImgList<t>& list):_width(0),_allocated_width(0),_data(0) { assign(list._width); cimglist_for(*this,l) _data[l].assign(list[l],false); } //! Construct list copy \specialization. CImgList(const CImgList<T>& list):_width(0),_allocated_width(0),_data(0) { assign(list._width); cimglist_for(*this,l) _data[l].assign(list[l],list[l]._is_shared); } //! Construct list copy, and force the shared state of the list elements. /** \param list Input list to copy. \param is_shared Tells if the elements of the list are shared or non-shared copies of input images. **/ template<typename t> CImgList(const CImgList<t>& list, const bool is_shared):_width(0),_allocated_width(0),_data(0) { assign(list._width); cimglist_for(*this,l) _data[l].assign(list[l],is_shared); } //! Construct list by reading the content of a file. /** \param filename Filename, as a C-string. **/ explicit CImgList(const char *const filename):_width(0),_allocated_width(0),_data(0) { assign(filename); } //! Construct list from the content of a display window. /** \param disp Display window to get content from. \note Constructed list contains a single image only. **/ explicit CImgList(const CImgDisplay& disp):_width(0),_allocated_width(0),_data(0) { assign(disp); } //! Return a list with elements being shared copies of images in the list instance. /** \note <tt>list2 = list1.get_shared()</tt> is equivalent to <tt>list2.assign(list1,true)</tt>. **/ CImgList<T> get_shared() { CImgList<T> res(_width); cimglist_for(*this,l) res[l].assign(_data[l],true); return res; } //! Return a list with elements being shared copies of images in the list instance \const. const CImgList<T> get_shared() const { CImgList<T> res(_width); cimglist_for(*this,l) res[l].assign(_data[l],true); return res; } //! Destructor \inplace. /** \see CImgList(). **/ CImgList<T>& assign() { delete[] _data; _width = _allocated_width = 0; _data = 0; return *this; } //! Destructor \inplace. /** Equivalent to assign(). \note Only here for compatibility with STL naming conventions. **/ CImgList<T>& clear() { return assign(); } //! Construct list containing empty images \inplace. /** \see CImgList(unsigned int). **/ CImgList<T>& assign(const unsigned int n) { if (!n) return assign(); if (_allocated_width<n || _allocated_width>(n<<2)) { delete[] _data; _data = new CImg<T>[_allocated_width = std::max(16U,(unsigned int)cimg::nearest_pow2(n))]; } _width = n; return *this; } //! Construct list containing images of specified size \inplace. /** \see CImgList(unsigned int, unsigned int, unsigned int, unsigned int, unsigned int). **/ CImgList<T>& assign(const unsigned int n, const unsigned int width, const unsigned int height=1, const unsigned int depth=1, const unsigned int spectrum=1) { assign(n); cimglist_apply(*this,assign)(width,height,depth,spectrum); return *this; } //! Construct list containing images of specified size, and initialize pixel values \inplace. /** \see CImgList(unsigned int, unsigned int, unsigned int, unsigned int, unsigned int, const T). **/ CImgList<T>& assign(const unsigned int n, const unsigned int width, const unsigned int height, const unsigned int depth, const unsigned int spectrum, const T& val) { assign(n); cimglist_apply(*this,assign)(width,height,depth,spectrum,val); return *this; } //! Construct list with images of specified size, and initialize pixel values from a sequence of integers \inplace. /** \see CImgList(unsigned int, unsigned int, unsigned int, unsigned int, unsigned int, const int, const int, ...). **/ CImgList<T>& assign(const unsigned int n, const unsigned int width, const unsigned int height, const unsigned int depth, const unsigned int spectrum, const int val0, const int val1, ...) { _CImgList_stdarg(int); return *this; } //! Construct list with images of specified size, and initialize pixel values from a sequence of doubles \inplace. /** \see CImgList(unsigned int,unsigned int,unsigned int,unsigned int,unsigned int,const double,const double,...). **/ CImgList<T>& assign(const unsigned int n, const unsigned int width, const unsigned int height, const unsigned int depth, const unsigned int spectrum, const double val0, const double val1, ...) { _CImgList_stdarg(double); return *this; } //! Construct list containing copies of an input image \inplace. /** \see CImgList(unsigned int, const CImg<t>&, bool). **/ template<typename t> CImgList<T>& assign(const unsigned int n, const CImg<t>& img, const bool is_shared=false) { assign(n); cimglist_apply(*this,assign)(img,is_shared); return *this; } //! Construct list from one image \inplace. /** \see CImgList(const CImg<t>&, bool). **/ template<typename t> CImgList<T>& assign(const CImg<t>& img, const bool is_shared=false) { assign(1); _data[0].assign(img,is_shared); return *this; } //! Construct list from two images \inplace. /** \see CImgList(const CImg<t>&, const CImg<t>&, bool). **/ template<typename t1, typename t2> CImgList<T>& assign(const CImg<t1>& img1, const CImg<t2>& img2, const bool is_shared=false) { assign(2); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); return *this; } //! Construct list from three images \inplace. /** \see CImgList(const CImg<t>&, const CImg<t>&, const CImg<t>&, bool). **/ template<typename t1, typename t2, typename t3> CImgList<T>& assign(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const bool is_shared=false) { assign(3); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); return *this; } //! Construct list from four images \inplace. /** \see CImgList(const CImg<t>&, const CImg<t>&, const CImg<t>&, const CImg<t>&, bool). **/ template<typename t1, typename t2, typename t3, typename t4> CImgList<T>& assign(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const bool is_shared=false) { assign(4); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); return *this; } //! Construct list from five images \inplace. /** \see CImgList(const CImg<t>&, const CImg<t>&, const CImg<t>&, const CImg<t>&, const CImg<t>&, bool). **/ template<typename t1, typename t2, typename t3, typename t4, typename t5> CImgList<T>& assign(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const CImg<t5>& img5, const bool is_shared=false) { assign(5); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); _data[4].assign(img5,is_shared); return *this; } //! Construct list from six images \inplace. /** \see CImgList(const CImg<t>&,const CImg<t>&,const CImg<t>&,const CImg<t>&,const CImg<t>&,const CImg<t>&, bool). **/ template<typename t1, typename t2, typename t3, typename t4, typename t5, typename t6> CImgList<T>& assign(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const CImg<t5>& img5, const CImg<t6>& img6, const bool is_shared=false) { assign(6); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); _data[4].assign(img5,is_shared); _data[5].assign(img6,is_shared); return *this; } //! Construct list from seven images \inplace. /** \see CImgList(const CImg<t>&,const CImg<t>&,const CImg<t>&,const CImg<t>&,const CImg<t>&,const CImg<t>&, const CImg<t>&, bool). **/ template<typename t1, typename t2, typename t3, typename t4, typename t5, typename t6, typename t7> CImgList<T>& assign(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const CImg<t5>& img5, const CImg<t6>& img6, const CImg<t7>& img7, const bool is_shared=false) { assign(7); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); _data[4].assign(img5,is_shared); _data[5].assign(img6,is_shared); _data[6].assign(img7,is_shared); return *this; } //! Construct list from eight images \inplace. /** \see CImgList(const CImg<t>&,const CImg<t>&,const CImg<t>&,const CImg<t>&,const CImg<t>&,const CImg<t>&, const CImg<t>&, const CImg<t>&, bool). **/ template<typename t1, typename t2, typename t3, typename t4, typename t5, typename t6, typename t7, typename t8> CImgList<T>& assign(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const CImg<t5>& img5, const CImg<t6>& img6, const CImg<t7>& img7, const CImg<t8>& img8, const bool is_shared=false) { assign(8); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); _data[4].assign(img5,is_shared); _data[5].assign(img6,is_shared); _data[6].assign(img7,is_shared); _data[7].assign(img8,is_shared); return *this; } //! Construct list as a copy of an existing list and force the shared state of the list elements \inplace. /** \see CImgList(const CImgList<t>&, bool is_shared). **/ template<typename t> CImgList<T>& assign(const CImgList<t>& list, const bool is_shared=false) { cimg::unused(is_shared); assign(list._width); cimglist_for(*this,l) _data[l].assign(list[l],false); return *this; } //! Construct list as a copy of an existing list and force shared state of elements \inplace \specialization. CImgList<T>& assign(const CImgList<T>& list, const bool is_shared=false) { if (this==&list) return *this; CImgList<T> res(list._width); cimglist_for(res,l) res[l].assign(list[l],is_shared); return res.move_to(*this); } //! Construct list by reading the content of a file \inplace. /** \see CImgList(const char *const). **/ CImgList<T>& assign(const char *const filename) { return load(filename); } //! Construct list from the content of a display window \inplace. /** \see CImgList(const CImgDisplay&). **/ CImgList<T>& assign(const CImgDisplay &disp) { return assign(CImg<T>(disp)); } //! Transfer the content of the list instance to another list. /** \param list Destination list. \note When returning, the current list instance is empty and the initial content of \c list is destroyed. **/ template<typename t> CImgList<t>& move_to(CImgList<t>& list) { list.assign(_width); bool is_one_shared_element = false; cimglist_for(*this,l) is_one_shared_element|=_data[l]._is_shared; if (is_one_shared_element) cimglist_for(*this,l) list[l].assign(_data[l]); else cimglist_for(*this,l) _data[l].move_to(list[l]); assign(); return list; } //! Transfer the content of the list instance at a specified position in another list. /** \param list Destination list. \param pos Index of the insertion in the list. \note When returning, the list instance is empty and the initial content of \c list is preserved (only images indexes may be modified). **/ template<typename t> CImgList<t>& move_to(CImgList<t>& list, const unsigned int pos) { if (is_empty()) return list; const unsigned int npos = pos>list._width?list._width:pos; list.insert(_width,npos); bool is_one_shared_element = false; cimglist_for(*this,l) is_one_shared_element|=_data[l]._is_shared; if (is_one_shared_element) cimglist_for(*this,l) list[npos + l].assign(_data[l]); else cimglist_for(*this,l) _data[l].move_to(list[npos + l]); assign(); return list; } //! Swap all fields between two list instances. /** \param list List to swap fields with. \note Can be used to exchange the content of two lists in a fast way. **/ CImgList<T>& swap(CImgList<T>& list) { cimg::swap(_width,list._width,_allocated_width,list._allocated_width); cimg::swap(_data,list._data); return list; } //! Return a reference to an empty list. /** \note Can be used to define default values in a function taking a CImgList<T> as an argument. \code void f(const CImgList<char>& list=CImgList<char>::empty()); \endcode **/ static CImgList<T>& empty() { static CImgList<T> _empty; return _empty.assign(); } //! Return a reference to an empty list \const. static const CImgList<T>& const_empty() { static const CImgList<T> _empty; return _empty; } //@} //------------------------------------------ // //! \name Overloaded Operators //@{ //------------------------------------------ //! Return a reference to one image element of the list. /** \param pos Index of the image element. **/ CImg<T>& operator()(const unsigned int pos) { #if cimg_verbosity>=3 if (pos>=_width) { cimg::warn(_cimglist_instance "operator(): Invalid image request, at position [%u].", cimglist_instance, pos); return *_data; } #endif return _data[pos]; } //! Return a reference to one image of the list. /** \param pos Index of the image element. **/ const CImg<T>& operator()(const unsigned int pos) const { return const_cast<CImgList<T>*>(this)->operator()(pos); } //! Return a reference to one pixel value of one image of the list. /** \param pos Index of the image element. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note <tt>list(n,x,y,z,c)</tt> is equivalent to <tt>list[n](x,y,z,c)</tt>. **/ T& operator()(const unsigned int pos, const unsigned int x, const unsigned int y=0, const unsigned int z=0, const unsigned int c=0) { return (*this)[pos](x,y,z,c); } //! Return a reference to one pixel value of one image of the list \const. const T& operator()(const unsigned int pos, const unsigned int x, const unsigned int y=0, const unsigned int z=0, const unsigned int c=0) const { return (*this)[pos](x,y,z,c); } //! Return pointer to the first image of the list. /** \note Images in a list are stored as a buffer of \c CImg<T>. **/ operator CImg<T>*() { return _data; } //! Return pointer to the first image of the list \const. operator const CImg<T>*() const { return _data; } //! Construct list from one image \inplace. /** \param img Input image to copy in the constructed list. \note <tt>list = img;</tt> is equivalent to <tt>list.assign(img);</tt>. **/ template<typename t> CImgList<T>& operator=(const CImg<t>& img) { return assign(img); } //! Construct list from another list. /** \param list Input list to copy. \note <tt>list1 = list2</tt> is equivalent to <tt>list1.assign(list2);</tt>. **/ template<typename t> CImgList<T>& operator=(const CImgList<t>& list) { return assign(list); } //! Construct list from another list \specialization. CImgList<T>& operator=(const CImgList<T>& list) { return assign(list); } //! Construct list by reading the content of a file \inplace. /** \see CImgList(const char *const). **/ CImgList<T>& operator=(const char *const filename) { return assign(filename); } //! Construct list from the content of a display window \inplace. /** \see CImgList(const CImgDisplay&). **/ CImgList<T>& operator=(const CImgDisplay& disp) { return assign(disp); } //! Return a non-shared copy of a list. /** \note <tt>+list</tt> is equivalent to <tt>CImgList<T>(list,false)</tt>. It forces the copy to have non-shared elements. **/ CImgList<T> operator+() const { return CImgList<T>(*this,false); } //! Return a copy of the list instance, where image \c img has been inserted at the end. /** \param img Image inserted at the end of the instance copy. \note Define a convenient way to create temporary lists of images, as in the following code: \code (img1,img2,img3,img4).display("My four images"); \endcode **/ template<typename t> CImgList<T>& operator,(const CImg<t>& img) { return insert(img); } //! Return a copy of the list instance, where image \c img has been inserted at the end \const. template<typename t> CImgList<T> operator,(const CImg<t>& img) const { return (+*this).insert(img); } //! Return a copy of the list instance, where all elements of input list \c list have been inserted at the end. /** \param list List inserted at the end of the instance copy. **/ template<typename t> CImgList<T>& operator,(const CImgList<t>& list) { return insert(list); } //! Return a copy of the list instance, where all elements of input \c list have been inserted at the end \const. template<typename t> CImgList<T>& operator,(const CImgList<t>& list) const { return (+*this).insert(list); } //! Return image corresponding to the appending of all images of the instance list along specified axis. /** \param axis Appending axis. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \note <tt>list>'x'</tt> is equivalent to <tt>list.get_append('x')</tt>. **/ CImg<T> operator>(const char axis) const { return get_append(axis,0); } //! Return list corresponding to the splitting of all images of the instance list along specified axis. /** \param axis Axis used for image splitting. \note <tt>list<'x'</tt> is equivalent to <tt>list.get_split('x')</tt>. **/ CImgList<T> operator<(const char axis) const { return get_split(axis); } //@} //------------------------------------- // //! \name Instance Characteristics //@{ //------------------------------------- //! Return the type of image pixel values as a C string. /** Return a \c char* string containing the usual type name of the image pixel values (i.e. a stringified version of the template parameter \c T). \note - The returned string may contain spaces (as in \c "unsigned char"). - If the pixel type \c T does not correspond to a registered type, the string <tt>"unknown"</tt> is returned. **/ static const char* pixel_type() { return cimg::type<T>::string(); } //! Return the size of the list, i.e. the number of images contained in it. /** \note Similar to size() but returns result as a (signed) integer. **/ int width() const { return (int)_width; } //! Return the size of the list, i.e. the number of images contained in it. /** \note Similar to width() but returns result as an unsigned integer. **/ unsigned int size() const { return _width; } //! Return pointer to the first image of the list. /** \note Images in a list are stored as a buffer of \c CImg<T>. **/ CImg<T> *data() { return _data; } //! Return pointer to the first image of the list \const. const CImg<T> *data() const { return _data; } //! Return pointer to the pos-th image of the list. /** \param pos Index of the image element to access. \note <tt>list.data(n);</tt> is equivalent to <tt>list.data + n;</tt>. **/ #if cimg_verbosity>=3 CImg<T> *data(const unsigned int pos) { if (pos>=size()) cimg::warn(_cimglist_instance "data(): Invalid pointer request, at position [%u].", cimglist_instance, pos); return _data + pos; } const CImg<T> *data(const unsigned int l) const { return const_cast<CImgList<T>*>(this)->data(l); } #else CImg<T> *data(const unsigned int l) { return _data + l; } //! Return pointer to the pos-th image of the list \const. const CImg<T> *data(const unsigned int l) const { return _data + l; } #endif //! Return iterator to the first image of the list. /** **/ iterator begin() { return _data; } //! Return iterator to the first image of the list \const. const_iterator begin() const { return _data; } //! Return iterator to one position after the last image of the list. /** **/ iterator end() { return _data + _width; } //! Return iterator to one position after the last image of the list \const. const_iterator end() const { return _data + _width; } //! Return reference to the first image of the list. /** **/ CImg<T>& front() { return *_data; } //! Return reference to the first image of the list \const. const CImg<T>& front() const { return *_data; } //! Return a reference to the last image of the list. /** **/ const CImg<T>& back() const { return *(_data + _width - 1); } //! Return a reference to the last image of the list \const. CImg<T>& back() { return *(_data + _width - 1); } //! Return pos-th image of the list. /** \param pos Index of the image element to access. **/ CImg<T>& at(const int pos) { if (is_empty()) throw CImgInstanceException(_cimglist_instance "at(): Empty instance.", cimglist_instance); return _data[cimg::cut(pos,0,width() - 1)]; } //! Access to pixel value with Dirichlet boundary conditions. /** \param pos Index of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param out_value Default value returned if \c offset is outside image bounds. \note <tt>list.atNXYZC(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZC(x,y,z,c);</tt>. **/ T& atNXYZC(const int pos, const int x, const int y, const int z, const int c, const T& out_value) { return (pos<0 || pos>=width())?(cimg::temporary(out_value)=out_value):_data[pos].atXYZC(x,y,z,c,out_value); } //! Access to pixel value with Dirichlet boundary conditions \const. T atNXYZC(const int pos, const int x, const int y, const int z, const int c, const T& out_value) const { return (pos<0 || pos>=width())?out_value:_data[pos].atXYZC(x,y,z,c,out_value); } //! Access to pixel value with Neumann boundary conditions. /** \param pos Index of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note <tt>list.atNXYZC(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZC(x,y,z,c);</tt>. **/ T& atNXYZC(const int pos, const int x, const int y, const int z, const int c) { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atNXYZC(): Empty instance.", cimglist_instance); return _atNXYZC(pos,x,y,z,c); } //! Access to pixel value with Neumann boundary conditions \const. T atNXYZC(const int pos, const int x, const int y, const int z, const int c) const { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atNXYZC(): Empty instance.", cimglist_instance); return _atNXYZC(pos,x,y,z,c); } T& _atNXYZC(const int pos, const int x, const int y, const int z, const int c) { return _data[cimg::cut(pos,0,width() - 1)].atXYZC(x,y,z,c); } T _atNXYZC(const int pos, const int x, const int y, const int z, const int c) const { return _data[cimg::cut(pos,0,width() - 1)].atXYZC(x,y,z,c); } //! Access pixel value with Dirichlet boundary conditions for the 3 coordinates (\c pos, \c x,\c y,\c z). /** \param pos Index of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param out_value Default value returned if \c offset is outside image bounds. \note <tt>list.atNXYZ(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZ(x,y,z,c);</tt>. **/ T& atNXYZ(const int pos, const int x, const int y, const int z, const int c, const T& out_value) { return (pos<0 || pos>=width())?(cimg::temporary(out_value)=out_value):_data[pos].atXYZ(x,y,z,c,out_value); } //! Access pixel value with Dirichlet boundary conditions for the 3 coordinates (\c pos, \c x,\c y,\c z) \const. T atNXYZ(const int pos, const int x, const int y, const int z, const int c, const T& out_value) const { return (pos<0 || pos>=width())?out_value:_data[pos].atXYZ(x,y,z,c,out_value); } //! Access to pixel value with Neumann boundary conditions for the 4 coordinates (\c pos, \c x,\c y,\c z). /** \param pos Index of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note <tt>list.atNXYZ(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZ(x,y,z,c);</tt>. **/ T& atNXYZ(const int pos, const int x, const int y, const int z, const int c=0) { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atNXYZ(): Empty instance.", cimglist_instance); return _atNXYZ(pos,x,y,z,c); } //! Access to pixel value with Neumann boundary conditions for the 4 coordinates (\c pos, \c x,\c y,\c z) \const. T atNXYZ(const int pos, const int x, const int y, const int z, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atNXYZ(): Empty instance.", cimglist_instance); return _atNXYZ(pos,x,y,z,c); } T& _atNXYZ(const int pos, const int x, const int y, const int z, const int c=0) { return _data[cimg::cut(pos,0,width() - 1)].atXYZ(x,y,z,c); } T _atNXYZ(const int pos, const int x, const int y, const int z, const int c=0) const { return _data[cimg::cut(pos,0,width() - 1)].atXYZ(x,y,z,c); } //! Access to pixel value with Dirichlet boundary conditions for the 3 coordinates (\c pos, \c x,\c y). /** \param pos Index of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param out_value Default value returned if \c offset is outside image bounds. \note <tt>list.atNXYZ(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZ(x,y,z,c);</tt>. **/ T& atNXY(const int pos, const int x, const int y, const int z, const int c, const T& out_value) { return (pos<0 || pos>=width())?(cimg::temporary(out_value)=out_value):_data[pos].atXY(x,y,z,c,out_value); } //! Access to pixel value with Dirichlet boundary conditions for the 3 coordinates (\c pos, \c x,\c y) \const. T atNXY(const int pos, const int x, const int y, const int z, const int c, const T& out_value) const { return (pos<0 || pos>=width())?out_value:_data[pos].atXY(x,y,z,c,out_value); } //! Access to pixel value with Neumann boundary conditions for the 3 coordinates (\c pos, \c x,\c y). /** \param pos Index of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note <tt>list.atNXYZ(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZ(x,y,z,c);</tt>. **/ T& atNXY(const int pos, const int x, const int y, const int z=0, const int c=0) { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atNXY(): Empty instance.", cimglist_instance); return _atNXY(pos,x,y,z,c); } //! Access to pixel value with Neumann boundary conditions for the 3 coordinates (\c pos, \c x,\c y) \const. T atNXY(const int pos, const int x, const int y, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atNXY(): Empty instance.", cimglist_instance); return _atNXY(pos,x,y,z,c); } T& _atNXY(const int pos, const int x, const int y, const int z=0, const int c=0) { return _data[cimg::cut(pos,0,width() - 1)].atXY(x,y,z,c); } T _atNXY(const int pos, const int x, const int y, const int z=0, const int c=0) const { return _data[cimg::cut(pos,0,width() - 1)].atXY(x,y,z,c); } //! Access to pixel value with Dirichlet boundary conditions for the 2 coordinates (\c pos,\c x). /** \param pos Index of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param out_value Default value returned if \c offset is outside image bounds. \note <tt>list.atNXYZ(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZ(x,y,z,c);</tt>. **/ T& atNX(const int pos, const int x, const int y, const int z, const int c, const T& out_value) { return (pos<0 || pos>=width())?(cimg::temporary(out_value)=out_value):_data[pos].atX(x,y,z,c,out_value); } //! Access to pixel value with Dirichlet boundary conditions for the 2 coordinates (\c pos,\c x) \const. T atNX(const int pos, const int x, const int y, const int z, const int c, const T& out_value) const { return (pos<0 || pos>=width())?out_value:_data[pos].atX(x,y,z,c,out_value); } //! Access to pixel value with Neumann boundary conditions for the 2 coordinates (\c pos, \c x). /** \param pos Index of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note <tt>list.atNXYZ(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZ(x,y,z,c);</tt>. **/ T& atNX(const int pos, const int x, const int y=0, const int z=0, const int c=0) { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atNX(): Empty instance.", cimglist_instance); return _atNX(pos,x,y,z,c); } //! Access to pixel value with Neumann boundary conditions for the 2 coordinates (\c pos, \c x) \const. T atNX(const int pos, const int x, const int y=0, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atNX(): Empty instance.", cimglist_instance); return _atNX(pos,x,y,z,c); } T& _atNX(const int pos, const int x, const int y=0, const int z=0, const int c=0) { return _data[cimg::cut(pos,0,width() - 1)].atX(x,y,z,c); } T _atNX(const int pos, const int x, const int y=0, const int z=0, const int c=0) const { return _data[cimg::cut(pos,0,width() - 1)].atX(x,y,z,c); } //! Access to pixel value with Dirichlet boundary conditions for the coordinate (\c pos). /** \param pos Index of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param out_value Default value returned if \c offset is outside image bounds. \note <tt>list.atNXYZ(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZ(x,y,z,c);</tt>. **/ T& atN(const int pos, const int x, const int y, const int z, const int c, const T& out_value) { return (pos<0 || pos>=width())?(cimg::temporary(out_value)=out_value):(*this)(pos,x,y,z,c); } //! Access to pixel value with Dirichlet boundary conditions for the coordinate (\c pos) \const. T atN(const int pos, const int x, const int y, const int z, const int c, const T& out_value) const { return (pos<0 || pos>=width())?out_value:(*this)(pos,x,y,z,c); } //! Return pixel value with Neumann boundary conditions for the coordinate (\c pos). /** \param pos Index of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note <tt>list.atNXYZ(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZ(x,y,z,c);</tt>. **/ T& atN(const int pos, const int x=0, const int y=0, const int z=0, const int c=0) { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atN(): Empty instance.", cimglist_instance); return _atN(pos,x,y,z,c); } //! Return pixel value with Neumann boundary conditions for the coordinate (\c pos) \const. T atN(const int pos, const int x=0, const int y=0, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atN(): Empty instance.", cimglist_instance); return _atN(pos,x,y,z,c); } T& _atN(const int pos, const int x=0, const int y=0, const int z=0, const int c=0) { return _data[cimg::cut(pos,0,width() - 1)](x,y,z,c); } T _atN(const int pos, const int x=0, const int y=0, const int z=0, const int c=0) const { return _data[cimg::cut(pos,0,width() - 1)](x,y,z,c); } //@} //------------------------------------- // //! \name Instance Checking //@{ //------------------------------------- //! Return \c true if list is empty. /** **/ bool is_empty() const { return (!_data || !_width); } //! Test if number of image elements is equal to specified value. /** \param size_n Number of image elements to test. **/ bool is_sameN(const unsigned int size_n) const { return _width==size_n; } //! Test if number of image elements is equal between two images lists. /** \param list Input list to compare with. **/ template<typename t> bool is_sameN(const CImgList<t>& list) const { return is_sameN(list._width); } // Define useful functions to check list dimensions. // (cannot be documented because macro-generated). #define _cimglist_def_is_same1(axis) \ bool is_same##axis(const unsigned int val) const { \ bool res = true; \ for (unsigned int l = 0; l<_width && res; ++l) res = _data[l].is_same##axis(val); return res; \ } \ bool is_sameN##axis(const unsigned int n, const unsigned int val) const { \ return is_sameN(n) && is_same##axis(val); \ } \ #define _cimglist_def_is_same2(axis1,axis2) \ bool is_same##axis1##axis2(const unsigned int val1, const unsigned int val2) const { \ bool res = true; \ for (unsigned int l = 0; l<_width && res; ++l) res = _data[l].is_same##axis1##axis2(val1,val2); return res; \ } \ bool is_sameN##axis1##axis2(const unsigned int n, const unsigned int val1, const unsigned int val2) const { \ return is_sameN(n) && is_same##axis1##axis2(val1,val2); \ } \ #define _cimglist_def_is_same3(axis1,axis2,axis3) \ bool is_same##axis1##axis2##axis3(const unsigned int val1, const unsigned int val2, \ const unsigned int val3) const { \ bool res = true; \ for (unsigned int l = 0; l<_width && res; ++l) res = _data[l].is_same##axis1##axis2##axis3(val1,val2,val3); \ return res; \ } \ bool is_sameN##axis1##axis2##axis3(const unsigned int n, const unsigned int val1, \ const unsigned int val2, const unsigned int val3) const { \ return is_sameN(n) && is_same##axis1##axis2##axis3(val1,val2,val3); \ } \ #define _cimglist_def_is_same(axis) \ template<typename t> bool is_same##axis(const CImg<t>& img) const { \ bool res = true; for (unsigned int l = 0; l<_width && res; ++l) res = _data[l].is_same##axis(img); return res; \ } \ template<typename t> bool is_same##axis(const CImgList<t>& list) const { \ const unsigned int lmin = std::min(_width,list._width); \ bool res = true; for (unsigned int l = 0; l<lmin && res; ++l) res = _data[l].is_same##axis(list[l]); return res; \ } \ template<typename t> bool is_sameN##axis(const unsigned int n, const CImg<t>& img) const { \ return (is_sameN(n) && is_same##axis(img)); \ } \ template<typename t> bool is_sameN##axis(const CImgList<t>& list) const { \ return (is_sameN(list) && is_same##axis(list)); \ } _cimglist_def_is_same(XY) _cimglist_def_is_same(XZ) _cimglist_def_is_same(XC) _cimglist_def_is_same(YZ) _cimglist_def_is_same(YC) _cimglist_def_is_same(XYZ) _cimglist_def_is_same(XYC) _cimglist_def_is_same(YZC) _cimglist_def_is_same(XYZC) _cimglist_def_is_same1(X) _cimglist_def_is_same1(Y) _cimglist_def_is_same1(Z) _cimglist_def_is_same1(C) _cimglist_def_is_same2(X,Y) _cimglist_def_is_same2(X,Z) _cimglist_def_is_same2(X,C) _cimglist_def_is_same2(Y,Z) _cimglist_def_is_same2(Y,C) _cimglist_def_is_same2(Z,C) _cimglist_def_is_same3(X,Y,Z) _cimglist_def_is_same3(X,Y,C) _cimglist_def_is_same3(X,Z,C) _cimglist_def_is_same3(Y,Z,C) //! Test if dimensions of each image of the list match specified arguments. /** \param dx Checked image width. \param dy Checked image height. \param dz Checked image depth. \param dc Checked image spectrum. **/ bool is_sameXYZC(const unsigned int dx, const unsigned int dy, const unsigned int dz, const unsigned int dc) const { bool res = true; for (unsigned int l = 0; l<_width && res; ++l) res = _data[l].is_sameXYZC(dx,dy,dz,dc); return res; } //! Test if list dimensions match specified arguments. /** \param n Number of images in the list. \param dx Checked image width. \param dy Checked image height. \param dz Checked image depth. \param dc Checked image spectrum. **/ bool is_sameNXYZC(const unsigned int n, const unsigned int dx, const unsigned int dy, const unsigned int dz, const unsigned int dc) const { return is_sameN(n) && is_sameXYZC(dx,dy,dz,dc); } //! Test if list contains one particular pixel location. /** \param n Index of the image whom checked pixel value belong to. \param x X-coordinate of the checked pixel value. \param y Y-coordinate of the checked pixel value. \param z Z-coordinate of the checked pixel value. \param c C-coordinate of the checked pixel value. **/ bool containsNXYZC(const int n, const int x=0, const int y=0, const int z=0, const int c=0) const { if (is_empty()) return false; return n>=0 && n<width() && x>=0 && x<_data[n].width() && y>=0 && y<_data[n].height() && z>=0 && z<_data[n].depth() && c>=0 && c<_data[n].spectrum(); } //! Test if list contains image with specified index. /** \param n Index of the checked image. **/ bool containsN(const int n) const { if (is_empty()) return false; return n>=0 && n<width(); } //! Test if one image of the list contains the specified referenced value. /** \param pixel Reference to pixel value to test. \param[out] n Index of image containing the pixel value, if test succeeds. \param[out] x X-coordinate of the pixel value, if test succeeds. \param[out] y Y-coordinate of the pixel value, if test succeeds. \param[out] z Z-coordinate of the pixel value, if test succeeds. \param[out] c C-coordinate of the pixel value, if test succeeds. \note If true, set coordinates (n,x,y,z,c). **/ template<typename t> bool contains(const T& pixel, t& n, t& x, t&y, t& z, t& c) const { if (is_empty()) return false; cimglist_for(*this,l) if (_data[l].contains(pixel,x,y,z,c)) { n = (t)l; return true; } return false; } //! Test if one of the image list contains the specified referenced value. /** \param pixel Reference to pixel value to test. \param[out] n Index of image containing the pixel value, if test succeeds. \param[out] x X-coordinate of the pixel value, if test succeeds. \param[out] y Y-coordinate of the pixel value, if test succeeds. \param[out] z Z-coordinate of the pixel value, if test succeeds. \note If true, set coordinates (n,x,y,z). **/ template<typename t> bool contains(const T& pixel, t& n, t& x, t&y, t& z) const { t c; return contains(pixel,n,x,y,z,c); } //! Test if one of the image list contains the specified referenced value. /** \param pixel Reference to pixel value to test. \param[out] n Index of image containing the pixel value, if test succeeds. \param[out] x X-coordinate of the pixel value, if test succeeds. \param[out] y Y-coordinate of the pixel value, if test succeeds. \note If true, set coordinates (n,x,y). **/ template<typename t> bool contains(const T& pixel, t& n, t& x, t&y) const { t z, c; return contains(pixel,n,x,y,z,c); } //! Test if one of the image list contains the specified referenced value. /** \param pixel Reference to pixel value to test. \param[out] n Index of image containing the pixel value, if test succeeds. \param[out] x X-coordinate of the pixel value, if test succeeds. \note If true, set coordinates (n,x). **/ template<typename t> bool contains(const T& pixel, t& n, t& x) const { t y, z, c; return contains(pixel,n,x,y,z,c); } //! Test if one of the image list contains the specified referenced value. /** \param pixel Reference to pixel value to test. \param[out] n Index of image containing the pixel value, if test succeeds. \note If true, set coordinates (n). **/ template<typename t> bool contains(const T& pixel, t& n) const { t x, y, z, c; return contains(pixel,n,x,y,z,c); } //! Test if one of the image list contains the specified referenced value. /** \param pixel Reference to pixel value to test. **/ bool contains(const T& pixel) const { unsigned int n, x, y, z, c; return contains(pixel,n,x,y,z,c); } //! Test if the list contains the image 'img'. /** \param img Reference to image to test. \param[out] n Index of image in the list, if test succeeds. \note If true, returns the position (n) of the image in the list. **/ template<typename t> bool contains(const CImg<T>& img, t& n) const { if (is_empty()) return false; const CImg<T> *const ptr = &img; cimglist_for(*this,i) if (_data + i==ptr) { n = (t)i; return true; } return false; } //! Test if the list contains the image img. /** \param img Reference to image to test. **/ bool contains(const CImg<T>& img) const { unsigned int n; return contains(img,n); } //@} //------------------------------------- // //! \name Mathematical Functions //@{ //------------------------------------- //! Return a reference to the minimum pixel value of the instance list. /** **/ T& min() { bool is_all_empty = true; T *ptr_min = 0; cimglist_for(*this,l) if (!_data[l].is_empty()) { ptr_min = _data[l]._data; is_all_empty = false; break; } if (is_all_empty) throw CImgInstanceException(_cimglist_instance "min(): %s.", _data?"List of empty images":"Empty instance", cimglist_instance); T min_value = *ptr_min; cimglist_for(*this,l) { const CImg<T>& img = _data[l]; cimg_for(img,ptrs,T) if (*ptrs<min_value) min_value = *(ptr_min=ptrs); } return *ptr_min; } //! Return a reference to the minimum pixel value of the instance list \const. const T& min() const { bool is_all_empty = true; T *ptr_min = 0; cimglist_for(*this,l) if (!_data[l].is_empty()) { ptr_min = _data[l]._data; is_all_empty = false; break; } if (is_all_empty) throw CImgInstanceException(_cimglist_instance "min(): %s.", _data?"List of empty images":"Empty instance", cimglist_instance); T min_value = *ptr_min; cimglist_for(*this,l) { const CImg<T>& img = _data[l]; cimg_for(img,ptrs,T) if (*ptrs<min_value) min_value = *(ptr_min=ptrs); } return *ptr_min; } //! Return a reference to the maximum pixel value of the instance list. /** **/ T& max() { bool is_all_empty = true; T *ptr_max = 0; cimglist_for(*this,l) if (!_data[l].is_empty()) { ptr_max = _data[l]._data; is_all_empty = false; break; } if (is_all_empty) throw CImgInstanceException(_cimglist_instance "max(): %s.", _data?"List of empty images":"Empty instance", cimglist_instance); T max_value = *ptr_max; cimglist_for(*this,l) { const CImg<T>& img = _data[l]; cimg_for(img,ptrs,T) if (*ptrs>max_value) max_value = *(ptr_max=ptrs); } return *ptr_max; } //! Return a reference to the maximum pixel value of the instance list \const. const T& max() const { bool is_all_empty = true; T *ptr_max = 0; cimglist_for(*this,l) if (!_data[l].is_empty()) { ptr_max = _data[l]._data; is_all_empty = false; break; } if (is_all_empty) throw CImgInstanceException(_cimglist_instance "max(): %s.", _data?"List of empty images":"Empty instance", cimglist_instance); T max_value = *ptr_max; cimglist_for(*this,l) { const CImg<T>& img = _data[l]; cimg_for(img,ptrs,T) if (*ptrs>max_value) max_value = *(ptr_max=ptrs); } return *ptr_max; } //! Return a reference to the minimum pixel value of the instance list and return the maximum vvalue as well. /** \param[out] max_val Value of the maximum value found. **/ template<typename t> T& min_max(t& max_val) { bool is_all_empty = true; T *ptr_min = 0; cimglist_for(*this,l) if (!_data[l].is_empty()) { ptr_min = _data[l]._data; is_all_empty = false; break; } if (is_all_empty) throw CImgInstanceException(_cimglist_instance "min_max(): %s.", _data?"List of empty images":"Empty instance", cimglist_instance); T min_value = *ptr_min, max_value = min_value; cimglist_for(*this,l) { const CImg<T>& img = _data[l]; cimg_for(img,ptrs,T) { const T val = *ptrs; if (val<min_value) { min_value = val; ptr_min = ptrs; } if (val>max_value) max_value = val; } } max_val = (t)max_value; return *ptr_min; } //! Return a reference to the minimum pixel value of the instance list and return the maximum vvalue as well \const. /** \param[out] max_val Value of the maximum value found. **/ template<typename t> const T& min_max(t& max_val) const { bool is_all_empty = true; T *ptr_min = 0; cimglist_for(*this,l) if (!_data[l].is_empty()) { ptr_min = _data[l]._data; is_all_empty = false; break; } if (is_all_empty) throw CImgInstanceException(_cimglist_instance "min_max(): %s.", _data?"List of empty images":"Empty instance", cimglist_instance); T min_value = *ptr_min, max_value = min_value; cimglist_for(*this,l) { const CImg<T>& img = _data[l]; cimg_for(img,ptrs,T) { const T val = *ptrs; if (val<min_value) { min_value = val; ptr_min = ptrs; } if (val>max_value) max_value = val; } } max_val = (t)max_value; return *ptr_min; } //! Return a reference to the minimum pixel value of the instance list and return the minimum value as well. /** \param[out] min_val Value of the minimum value found. **/ template<typename t> T& max_min(t& min_val) { bool is_all_empty = true; T *ptr_max = 0; cimglist_for(*this,l) if (!_data[l].is_empty()) { ptr_max = _data[l]._data; is_all_empty = false; break; } if (is_all_empty) throw CImgInstanceException(_cimglist_instance "max_min(): %s.", _data?"List of empty images":"Empty instance", cimglist_instance); T min_value = *ptr_max, max_value = min_value; cimglist_for(*this,l) { const CImg<T>& img = _data[l]; cimg_for(img,ptrs,T) { const T val = *ptrs; if (val>max_value) { max_value = val; ptr_max = ptrs; } if (val<min_value) min_value = val; } } min_val = (t)min_value; return *ptr_max; } //! Return a reference to the minimum pixel value of the instance list and return the minimum value as well \const. template<typename t> const T& max_min(t& min_val) const { bool is_all_empty = true; T *ptr_max = 0; cimglist_for(*this,l) if (!_data[l].is_empty()) { ptr_max = _data[l]._data; is_all_empty = false; break; } if (is_all_empty) throw CImgInstanceException(_cimglist_instance "max_min(): %s.", _data?"List of empty images":"Empty instance", cimglist_instance); T min_value = *ptr_max, max_value = min_value; cimglist_for(*this,l) { const CImg<T>& img = _data[l]; cimg_for(img,ptrs,T) { const T val = *ptrs; if (val>max_value) { max_value = val; ptr_max = ptrs; } if (val<min_value) min_value = val; } } min_val = (t)min_value; return *ptr_max; } //@} //--------------------------- // //! \name List Manipulation //@{ //--------------------------- //! Insert a copy of the image \c img into the current image list, at position \c pos. /** \param img Image to insert a copy to the list. \param pos Index of the insertion. \param is_shared Tells if the inserted image is a shared copy of \c img or not. **/ template<typename t> CImgList<T>& insert(const CImg<t>& img, const unsigned int pos=~0U, const bool is_shared=false) { const unsigned int npos = pos==~0U?_width:pos; if (npos>_width) throw CImgArgumentException(_cimglist_instance "insert(): Invalid insertion request of specified image (%u,%u,%u,%u,%p) " "at position %u.", cimglist_instance, img._width,img._height,img._depth,img._spectrum,img._data,npos); if (is_shared) throw CImgArgumentException(_cimglist_instance "insert(): Invalid insertion request of specified shared image " "CImg<%s>(%u,%u,%u,%u,%p) at position %u (pixel types are different).", cimglist_instance, img.pixel_type(),img._width,img._height,img._depth,img._spectrum,img._data,npos); CImg<T> *const new_data = (++_width>_allocated_width)?new CImg<T>[_allocated_width?(_allocated_width<<=1): (_allocated_width=16)]:0; if (!_data) { // Insert new element into empty list _data = new_data; *_data = img; } else { if (new_data) { // Insert with re-allocation if (npos) std::memcpy((void*)new_data,(void*)_data,sizeof(CImg<T>)*npos); if (npos!=_width - 1) std::memcpy((void*)(new_data + npos + 1),(void*)(_data + npos),sizeof(CImg<T>)*(_width - 1 - npos)); std::memset((void*)_data,0,sizeof(CImg<T>)*(_width - 1)); delete[] _data; _data = new_data; } else if (npos!=_width - 1) // Insert without re-allocation std::memmove((void*)(_data + npos + 1),(void*)(_data + npos),sizeof(CImg<T>)*(_width - 1 - npos)); _data[npos]._width = _data[npos]._height = _data[npos]._depth = _data[npos]._spectrum = 0; _data[npos]._data = 0; _data[npos] = img; } return *this; } //! Insert a copy of the image \c img into the current image list, at position \c pos \specialization. CImgList<T>& insert(const CImg<T>& img, const unsigned int pos=~0U, const bool is_shared=false) { const unsigned int npos = pos==~0U?_width:pos; if (npos>_width) throw CImgArgumentException(_cimglist_instance "insert(): Invalid insertion request of specified image (%u,%u,%u,%u,%p) " "at position %u.", cimglist_instance, img._width,img._height,img._depth,img._spectrum,img._data,npos); CImg<T> *const new_data = (++_width>_allocated_width)?new CImg<T>[_allocated_width?(_allocated_width<<=1): (_allocated_width=16)]:0; if (!_data) { // Insert new element into empty list _data = new_data; if (is_shared && img) { _data->_width = img._width; _data->_height = img._height; _data->_depth = img._depth; _data->_spectrum = img._spectrum; _data->_is_shared = true; _data->_data = img._data; } else *_data = img; } else { if (new_data) { // Insert with re-allocation if (npos) std::memcpy((void*)new_data,(void*)_data,sizeof(CImg<T>)*npos); if (npos!=_width - 1) std::memcpy((void*)(new_data + npos + 1),(void*)(_data + npos),sizeof(CImg<T>)*(_width - 1 - npos)); if (is_shared && img) { new_data[npos]._width = img._width; new_data[npos]._height = img._height; new_data[npos]._depth = img._depth; new_data[npos]._spectrum = img._spectrum; new_data[npos]._is_shared = true; new_data[npos]._data = img._data; } else { new_data[npos]._width = new_data[npos]._height = new_data[npos]._depth = new_data[npos]._spectrum = 0; new_data[npos]._data = 0; new_data[npos] = img; } std::memset((void*)_data,0,sizeof(CImg<T>)*(_width - 1)); delete[] _data; _data = new_data; } else { // Insert without re-allocation if (npos!=_width - 1) std::memmove((void*)(_data + npos + 1),(void*)(_data + npos),sizeof(CImg<T>)*(_width - 1 - npos)); if (is_shared && img) { _data[npos]._width = img._width; _data[npos]._height = img._height; _data[npos]._depth = img._depth; _data[npos]._spectrum = img._spectrum; _data[npos]._is_shared = true; _data[npos]._data = img._data; } else { _data[npos]._width = _data[npos]._height = _data[npos]._depth = _data[npos]._spectrum = 0; _data[npos]._data = 0; _data[npos] = img; } } } return *this; } //! Insert a copy of the image \c img into the current image list, at position \c pos \newinstance. template<typename t> CImgList<T> get_insert(const CImg<t>& img, const unsigned int pos=~0U, const bool is_shared=false) const { return (+*this).insert(img,pos,is_shared); } //! Insert n empty images img into the current image list, at position \p pos. /** \param n Number of empty images to insert. \param pos Index of the insertion. **/ CImgList<T>& insert(const unsigned int n, const unsigned int pos=~0U) { CImg<T> empty; if (!n) return *this; const unsigned int npos = pos==~0U?_width:pos; for (unsigned int i = 0; i<n; ++i) insert(empty,npos+i); return *this; } //! Insert n empty images img into the current image list, at position \p pos \newinstance. CImgList<T> get_insert(const unsigned int n, const unsigned int pos=~0U) const { return (+*this).insert(n,pos); } //! Insert \c n copies of the image \c img into the current image list, at position \c pos. /** \param n Number of image copies to insert. \param img Image to insert by copy. \param pos Index of the insertion. \param is_shared Tells if inserted images are shared copies of \c img or not. **/ template<typename t> CImgList<T>& insert(const unsigned int n, const CImg<t>& img, const unsigned int pos=~0U, const bool is_shared=false) { if (!n) return *this; const unsigned int npos = pos==~0U?_width:pos; insert(img,npos,is_shared); for (unsigned int i = 1; i<n; ++i) insert(_data[npos],npos + i,is_shared); return *this; } //! Insert \c n copies of the image \c img into the current image list, at position \c pos \newinstance. template<typename t> CImgList<T> get_insert(const unsigned int n, const CImg<t>& img, const unsigned int pos=~0U, const bool is_shared=false) const { return (+*this).insert(n,img,pos,is_shared); } //! Insert a copy of the image list \c list into the current image list, starting from position \c pos. /** \param list Image list to insert. \param pos Index of the insertion. \param is_shared Tells if inserted images are shared copies of images of \c list or not. **/ template<typename t> CImgList<T>& insert(const CImgList<t>& list, const unsigned int pos=~0U, const bool is_shared=false) { const unsigned int npos = pos==~0U?_width:pos; if ((void*)this!=(void*)&list) cimglist_for(list,l) insert(list[l],npos + l,is_shared); else insert(CImgList<T>(list),npos,is_shared); return *this; } //! Insert a copy of the image list \c list into the current image list, starting from position \c pos \newinstance. template<typename t> CImgList<T> get_insert(const CImgList<t>& list, const unsigned int pos=~0U, const bool is_shared=false) const { return (+*this).insert(list,pos,is_shared); } //! Insert n copies of the list \c list at position \c pos of the current list. /** \param n Number of list copies to insert. \param list Image list to insert. \param pos Index of the insertion. \param is_shared Tells if inserted images are shared copies of images of \c list or not. **/ template<typename t> CImgList<T>& insert(const unsigned int n, const CImgList<t>& list, const unsigned int pos=~0U, const bool is_shared=false) { if (!n) return *this; const unsigned int npos = pos==~0U?_width:pos; for (unsigned int i = 0; i<n; ++i) insert(list,npos,is_shared); return *this; } //! Insert n copies of the list \c list at position \c pos of the current list \newinstance. template<typename t> CImgList<T> get_insert(const unsigned int n, const CImgList<t>& list, const unsigned int pos=~0U, const bool is_shared=false) const { return (+*this).insert(n,list,pos,is_shared); } //! Remove all images between from indexes. /** \param pos1 Starting index of the removal. \param pos2 Ending index of the removal. **/ CImgList<T>& remove(const unsigned int pos1, const unsigned int pos2) { const unsigned int npos1 = pos1<pos2?pos1:pos2, tpos2 = pos1<pos2?pos2:pos1, npos2 = tpos2<_width?tpos2:_width - 1; if (npos1>=_width) throw CImgArgumentException(_cimglist_instance "remove(): Invalid remove request at positions %u->%u.", cimglist_instance, npos1,tpos2); else { if (tpos2>=_width) throw CImgArgumentException(_cimglist_instance "remove(): Invalid remove request at positions %u->%u.", cimglist_instance, npos1,tpos2); for (unsigned int k = npos1; k<=npos2; ++k) _data[k].assign(); const unsigned int nb = 1 + npos2 - npos1; if (!(_width-=nb)) return assign(); if (_width>(_allocated_width>>2) || _allocated_width<=16) { // Removing items without reallocation if (npos1!=_width) std::memmove((void*)(_data + npos1),(void*)(_data + npos2 + 1),sizeof(CImg<T>)*(_width - npos1)); std::memset((void*)(_data + _width),0,sizeof(CImg<T>)*nb); } else { // Removing items with reallocation _allocated_width>>=2; while (_allocated_width>16 && _width<(_allocated_width>>1)) _allocated_width>>=1; CImg<T> *const new_data = new CImg<T>[_allocated_width]; if (npos1) std::memcpy((void*)new_data,(void*)_data,sizeof(CImg<T>)*npos1); if (npos1!=_width) std::memcpy((void*)(new_data + npos1),(void*)(_data + npos2 + 1),sizeof(CImg<T>)*(_width - npos1)); if (_width!=_allocated_width) std::memset((void*)(new_data + _width),0,sizeof(CImg<T>)*(_allocated_width - _width)); std::memset((void*)_data,0,sizeof(CImg<T>)*(_width + nb)); delete[] _data; _data = new_data; } } return *this; } //! Remove all images between from indexes \newinstance. CImgList<T> get_remove(const unsigned int pos1, const unsigned int pos2) const { return (+*this).remove(pos1,pos2); } //! Remove image at index \c pos from the image list. /** \param pos Index of the image to remove. **/ CImgList<T>& remove(const unsigned int pos) { return remove(pos,pos); } //! Remove image at index \c pos from the image list \newinstance. CImgList<T> get_remove(const unsigned int pos) const { return (+*this).remove(pos); } //! Remove last image. /** **/ CImgList<T>& remove() { return remove(_width - 1); } //! Remove last image \newinstance. CImgList<T> get_remove() const { return (+*this).remove(); } //! Reverse list order. CImgList<T>& reverse() { for (unsigned int l = 0; l<_width/2; ++l) (*this)[l].swap((*this)[_width - 1 - l]); return *this; } //! Reverse list order \newinstance. CImgList<T> get_reverse() const { return (+*this).reverse(); } //! Return a sublist. /** \param pos0 Starting index of the sublist. \param pos1 Ending index of the sublist. **/ CImgList<T>& images(const unsigned int pos0, const unsigned int pos1) { return get_images(pos0,pos1).move_to(*this); } //! Return a sublist \newinstance. CImgList<T> get_images(const unsigned int pos0, const unsigned int pos1) const { if (pos0>pos1 || pos1>=_width) throw CImgArgumentException(_cimglist_instance "images(): Specified sub-list indices (%u->%u) are out of bounds.", cimglist_instance, pos0,pos1); CImgList<T> res(pos1 - pos0 + 1); cimglist_for(res,l) res[l].assign(_data[pos0 + l]); return res; } //! Return a shared sublist. /** \param pos0 Starting index of the sublist. \param pos1 Ending index of the sublist. **/ CImgList<T> get_shared_images(const unsigned int pos0, const unsigned int pos1) { if (pos0>pos1 || pos1>=_width) throw CImgArgumentException(_cimglist_instance "get_shared_images(): Specified sub-list indices (%u->%u) are out of bounds.", cimglist_instance, pos0,pos1); CImgList<T> res(pos1 - pos0 + 1); cimglist_for(res,l) res[l].assign(_data[pos0 + l],_data[pos0 + l]?true:false); return res; } //! Return a shared sublist \newinstance. const CImgList<T> get_shared_images(const unsigned int pos0, const unsigned int pos1) const { if (pos0>pos1 || pos1>=_width) throw CImgArgumentException(_cimglist_instance "get_shared_images(): Specified sub-list indices (%u->%u) are out of bounds.", cimglist_instance, pos0,pos1); CImgList<T> res(pos1 - pos0 + 1); cimglist_for(res,l) res[l].assign(_data[pos0 + l],_data[pos0 + l]?true:false); return res; } //! Return a single image which is the appending of all images of the current CImgList instance. /** \param axis Appending axis. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param align Appending alignment. **/ CImg<T> get_append(const char axis, const float align=0) const { if (is_empty()) return CImg<T>(); if (_width==1) return +((*this)[0]); unsigned int dx = 0, dy = 0, dz = 0, dc = 0, pos = 0; CImg<T> res; switch (cimg::lowercase(axis)) { case 'x' : { // Along the X-axis cimglist_for(*this,l) { const CImg<T>& img = (*this)[l]; if (img) { dx+=img._width; dy = std::max(dy,img._height); dz = std::max(dz,img._depth); dc = std::max(dc,img._spectrum); } } res.assign(dx,dy,dz,dc,(T)0); if (res) cimglist_for(*this,l) { const CImg<T>& img = (*this)[l]; if (img) res.draw_image(pos, (int)(align*(dy - img._height)), (int)(align*(dz - img._depth)), (int)(align*(dc - img._spectrum)), img); pos+=img._width; } } break; case 'y' : { // Along the Y-axis cimglist_for(*this,l) { const CImg<T>& img = (*this)[l]; if (img) { dx = std::max(dx,img._width); dy+=img._height; dz = std::max(dz,img._depth); dc = std::max(dc,img._spectrum); } } res.assign(dx,dy,dz,dc,(T)0); if (res) cimglist_for(*this,l) { const CImg<T>& img = (*this)[l]; if (img) res.draw_image((int)(align*(dx - img._width)), pos, (int)(align*(dz - img._depth)), (int)(align*(dc - img._spectrum)), img); pos+=img._height; } } break; case 'z' : { // Along the Z-axis cimglist_for(*this,l) { const CImg<T>& img = (*this)[l]; if (img) { dx = std::max(dx,img._width); dy = std::max(dy,img._height); dz+=img._depth; dc = std::max(dc,img._spectrum); } } res.assign(dx,dy,dz,dc,(T)0); if (res) cimglist_for(*this,l) { const CImg<T>& img = (*this)[l]; if (img) res.draw_image((int)(align*(dx - img._width)), (int)(align*(dy - img._height)), pos, (int)(align*(dc - img._spectrum)), img); pos+=img._depth; } } break; default : { // Along the C-axis cimglist_for(*this,l) { const CImg<T>& img = (*this)[l]; if (img) { dx = std::max(dx,img._width); dy = std::max(dy,img._height); dz = std::max(dz,img._depth); dc+=img._spectrum; } } res.assign(dx,dy,dz,dc,(T)0); if (res) cimglist_for(*this,l) { const CImg<T>& img = (*this)[l]; if (img) res.draw_image((int)(align*(dx - img._width)), (int)(align*(dy - img._height)), (int)(align*(dz - img._depth)), pos, img); pos+=img._spectrum; } } } return res; } //! Return a list where each image has been split along the specified axis. /** \param axis Axis to split images along. \param nb Number of spliting parts for each image. **/ CImgList<T>& split(const char axis, const int nb=-1) { return get_split(axis,nb).move_to(*this); } //! Return a list where each image has been split along the specified axis \newinstance. CImgList<T> get_split(const char axis, const int nb=-1) const { CImgList<T> res; cimglist_for(*this,l) _data[l].get_split(axis,nb).move_to(res,~0U); return res; } //! Insert image at the end of the list. /** \param img Image to insert. **/ template<typename t> CImgList<T>& push_back(const CImg<t>& img) { return insert(img); } //! Insert image at the front of the list. /** \param img Image to insert. **/ template<typename t> CImgList<T>& push_front(const CImg<t>& img) { return insert(img,0); } //! Insert list at the end of the current list. /** \param list List to insert. **/ template<typename t> CImgList<T>& push_back(const CImgList<t>& list) { return insert(list); } //! Insert list at the front of the current list. /** \param list List to insert. **/ template<typename t> CImgList<T>& push_front(const CImgList<t>& list) { return insert(list,0); } //! Remove last image. /** **/ CImgList<T>& pop_back() { return remove(_width - 1); } //! Remove first image. /** **/ CImgList<T>& pop_front() { return remove(0); } //! Remove image pointed by iterator. /** \param iter Iterator pointing to the image to remove. **/ CImgList<T>& erase(const iterator iter) { return remove(iter - _data); } //@} //---------------------------------- // //! \name Data Input //@{ //---------------------------------- //! Display a simple interactive interface to select images or sublists. /** \param disp Window instance to display selection and user interface. \param feature_type Can be \c false to select a single image, or \c true to select a sublist. \param axis Axis along whom images are appended for visualization. \param align Alignment setting when images have not all the same size. \param exit_on_anykey Exit function when any key is pressed. \return A one-column vector containing the selected image indexes. **/ CImg<intT> get_select(CImgDisplay &disp, const bool feature_type=true, const char axis='x', const float align=0, const bool exit_on_anykey=false) const { return _select(disp,0,feature_type,axis,align,exit_on_anykey,0,false,false,false); } //! Display a simple interactive interface to select images or sublists. /** \param title Title of a new window used to display selection and user interface. \param feature_type Can be \c false to select a single image, or \c true to select a sublist. \param axis Axis along whom images are appended for visualization. \param align Alignment setting when images have not all the same size. \param exit_on_anykey Exit function when any key is pressed. \return A one-column vector containing the selected image indexes. **/ CImg<intT> get_select(const char *const title, const bool feature_type=true, const char axis='x', const float align=0, const bool exit_on_anykey=false) const { CImgDisplay disp; return _select(disp,title,feature_type,axis,align,exit_on_anykey,0,false,false,false); } CImg<intT> _select(CImgDisplay &disp, const char *const title, const bool feature_type, const char axis, const float align, const bool exit_on_anykey, const unsigned int orig, const bool resize_disp, const bool exit_on_rightbutton, const bool exit_on_wheel) const { if (is_empty()) throw CImgInstanceException(_cimglist_instance "select(): Empty instance.", cimglist_instance); // Create image correspondence table and get list dimensions for visualization. CImgList<uintT> _indices; unsigned int max_width = 0, max_height = 0, sum_width = 0, sum_height = 0; cimglist_for(*this,l) { const CImg<T>& img = _data[l]; const unsigned int w = CImgDisplay::_fitscreen(img._width,img._height,img._depth,128,-85,false), h = CImgDisplay::_fitscreen(img._width,img._height,img._depth,128,-85,true); if (w>max_width) max_width = w; if (h>max_height) max_height = h; sum_width+=w; sum_height+=h; if (axis=='x') CImg<uintT>(w,1,1,1,(unsigned int)l).move_to(_indices); else CImg<uintT>(h,1,1,1,(unsigned int)l).move_to(_indices); } const CImg<uintT> indices0 = _indices>'x'; // Create display window. if (!disp) { if (axis=='x') disp.assign(cimg_fitscreen(sum_width,max_height,1),title?title:0,1); else disp.assign(cimg_fitscreen(max_width,sum_height,1),title?title:0,1); if (!title) disp.set_title("CImgList<%s> (%u)",pixel_type(),_width); } else { if (title) disp.set_title("%s",title); disp.move_inside_screen(); } if (resize_disp) { if (axis=='x') disp.resize(cimg_fitscreen(sum_width,max_height,1),false); else disp.resize(cimg_fitscreen(max_width,sum_height,1),false); } const unsigned int old_normalization = disp.normalization(); bool old_is_resized = disp.is_resized(); disp._normalization = 0; disp.show().set_key(0).show_mouse(); static const unsigned char foreground_color[] = { 255,255,255 }, background_color[] = { 0,0,0 }; // Enter event loop. CImg<ucharT> visu0, visu; CImg<uintT> indices; CImg<intT> positions(_width,4,1,1,-1); int oindex0 = -1, oindex1 = -1, index0 = -1, index1 = -1; bool is_clicked = false, is_selected = false, text_down = false, update_display = true; unsigned int key = 0; while (!is_selected && !disp.is_closed() && !key) { // Create background image. if (!visu0) { visu0.assign(disp._width,disp._height,1,3,0); visu.assign(); (indices0.get_resize(axis=='x'?visu0._width:visu0._height,1)).move_to(indices); unsigned int _ind = 0; const CImg<T> onexone(1,1,1,1,(T)0); if (axis=='x') cimg_pragma_openmp(parallel for cimg_openmp_if_size(_width,4)) cimglist_for(*this,ind) { unsigned int x0 = 0; while (x0<visu0._width && indices[x0++]!=(unsigned int)ind) {} unsigned int x1 = x0; while (x1<visu0._width && indices[x1++]==(unsigned int)ind) {} const CImg<T> &src = _data[ind]?_data[ind]:onexone; CImg<ucharT> res; src._get_select(disp,old_normalization,src._width/2,src._height/2,src._depth/2). move_to(res); const unsigned int h = CImgDisplay::_fitscreen(res._width,res._height,1,128,-85,true); res.resize(x1 - x0,std::max(32U,h*disp._height/max_height),1,res._spectrum==1?3:-100); positions(ind,0) = positions(ind,2) = (int)x0; positions(ind,1) = positions(ind,3) = (int)(align*(visu0.height() - res.height())); positions(ind,2)+=res._width; positions(ind,3)+=res._height - 1; visu0.draw_image(positions(ind,0),positions(ind,1),res); } else cimg_pragma_openmp(parallel for cimg_openmp_if_size(_width,4)) cimglist_for(*this,ind) { unsigned int y0 = 0; while (y0<visu0._height && indices[y0++]!=(unsigned int)ind) {} unsigned int y1 = y0; while (y1<visu0._height && indices[y1++]==(unsigned int)ind) {} const CImg<T> &src = _data[ind]?_data[ind]:onexone; CImg<ucharT> res; src._get_select(disp,old_normalization,(src._width - 1)/2,(src._height - 1)/2,(src._depth - 1)/2). move_to(res); const unsigned int w = CImgDisplay::_fitscreen(res._width,res._height,1,128,-85,false); res.resize(std::max(32U,w*disp._width/max_width),y1 - y0,1,res._spectrum==1?3:-100); positions(ind,0) = positions(ind,2) = (int)(align*(visu0.width() - res.width())); positions(ind,1) = positions(ind,3) = (int)y0; positions(ind,2)+=res._width - 1; positions(ind,3)+=res._height; visu0.draw_image(positions(ind,0),positions(ind,1),res); } if (axis=='x') --positions(_ind,2); else --positions(_ind,3); update_display = true; } if (!visu || oindex0!=index0 || oindex1!=index1) { if (index0>=0 && index1>=0) { visu.assign(visu0,false); const int indm = std::min(index0,index1), indM = std::max(index0,index1); for (int ind = indm; ind<=indM; ++ind) if (positions(ind,0)>=0) { visu.draw_rectangle(positions(ind,0),positions(ind,1),positions(ind,2),positions(ind,3), background_color,0.2f); if ((axis=='x' && positions(ind,2) - positions(ind,0)>=8) || (axis!='x' && positions(ind,3) - positions(ind,1)>=8)) visu.draw_rectangle(positions(ind,0),positions(ind,1),positions(ind,2),positions(ind,3), foreground_color,0.9f,0xAAAAAAAA); } if (is_clicked) visu.__draw_text(" Images #%u - #%u, Size = %u ",(int)text_down, orig + indm,orig + indM,indM - indm + 1); else visu.__draw_text(" Image #%u (%u,%u,%u,%u) ",(int)text_down, orig + index0, _data[index0]._width, _data[index0]._height, _data[index0]._depth, _data[index0]._spectrum); update_display = true; } else visu.assign(); } if (!visu) { visu.assign(visu0,true); update_display = true; } if (update_display) { visu.display(disp); update_display = false; } disp.wait(); // Manage user events. const int xm = disp.mouse_x(), ym = disp.mouse_y(); int index = -1; if (xm>=0) { index = (int)indices(axis=='x'?xm:ym); if (disp.button()&1) { if (!is_clicked) { is_clicked = true; oindex0 = index0; index0 = index; } oindex1 = index1; index1 = index; if (!feature_type) is_selected = true; } else { if (!is_clicked) { oindex0 = oindex1 = index0; index0 = index1 = index; } else is_selected = true; } } else { if (is_clicked) { if (!(disp.button()&1)) { is_clicked = is_selected = false; index0 = index1 = -1; } else index1 = -1; } else index0 = index1 = -1; } if (disp.button()&4) { is_clicked = is_selected = false; index0 = index1 = -1; } if (disp.button()&2 && exit_on_rightbutton) { is_selected = true; index1 = index0 = -1; } if (disp.wheel() && exit_on_wheel) is_selected = true; CImg<charT> filename(32); switch (key = disp.key()) { #if cimg_OS!=2 case cimg::keyCTRLRIGHT : #endif case 0 : case cimg::keyCTRLLEFT : key = 0; break; case cimg::keyD : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false). resize(CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,false), CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,true),false). _is_resized = true; disp.set_key(key,false); key = 0; visu0.assign(); } break; case cimg::keyC : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false). resize(cimg_fitscreen(2*disp.width()/3,2*disp.height()/3,1),false)._is_resized = true; disp.set_key(key,false); key = 0; visu0.assign(); } break; case cimg::keyR : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false). resize(cimg_fitscreen(axis=='x'?sum_width:max_width,axis=='x'?max_height:sum_height,1),false). _is_resized = true; disp.set_key(key,false); key = 0; visu0.assign(); } break; case cimg::keyF : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.resize(disp.screen_width(),disp.screen_height(),false).toggle_fullscreen()._is_resized = true; disp.set_key(key,false); key = 0; visu0.assign(); } break; case cimg::keyS : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { static unsigned int snap_number = 0; std::FILE *file; do { cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.bmp",snap_number++); if ((file=cimg::std_fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); if (visu0) { (+visu0).__draw_text(" Saving snapshot... ",(int)text_down).display(disp); visu0.save(filename); (+visu0).__draw_text(" Snapshot '%s' saved. ",(int)text_down,filename._data).display(disp); } disp.set_key(key,false).wait(); key = 0; } break; case cimg::keyO : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { static unsigned int snap_number = 0; std::FILE *file; do { #ifdef cimg_use_zlib cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.cimgz",snap_number++); #else cimg_snprintf(filename,filename._width,cimg_appname "_%.4u.cimg",snap_number++); #endif if ((file=cimg::std_fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); (+visu0).__draw_text(" Saving instance... ",(int)text_down).display(disp); save(filename); (+visu0).__draw_text(" Instance '%s' saved. ",(int)text_down,filename._data).display(disp); disp.set_key(key,false).wait(); key = 0; } break; } if (disp.is_resized()) { disp.resize(false); visu0.assign(); } if (ym>=0 && ym<13) { if (!text_down) { visu.assign(); text_down = true; }} else if (ym>=visu.height() - 13) { if (text_down) { visu.assign(); text_down = false; }} if (!exit_on_anykey && key && key!=cimg::keyESC && (key!=cimg::keyW || (!disp.is_keyCTRLLEFT() && !disp.is_keyCTRLRIGHT()))) { key = 0; } } CImg<intT> res(1,2,1,1,-1); if (is_selected) { if (feature_type) res.fill(std::min(index0,index1),std::max(index0,index1)); else res.fill(index0); } if (!(disp.button()&2)) disp.set_button(); disp._normalization = old_normalization; disp._is_resized = old_is_resized; disp.set_key(key); return res; } //! Load a list from a file. /** \param filename Filename to read data from. **/ CImgList<T>& load(const char *const filename) { if (!filename) throw CImgArgumentException(_cimglist_instance "load(): Specified filename is (null).", cimglist_instance); if (!cimg::strncasecmp(filename,"http://",7) || !cimg::strncasecmp(filename,"https://",8)) { CImg<charT> filename_local(256); load(cimg::load_network(filename,filename_local)); std::remove(filename_local); return *this; } const bool is_stdin = *filename=='-' && (!filename[1] || filename[1]=='.'); const char *const ext = cimg::split_filename(filename); const unsigned int omode = cimg::exception_mode(); cimg::exception_mode(0); bool is_loaded = true; try { #ifdef cimglist_load_plugin cimglist_load_plugin(filename); #endif #ifdef cimglist_load_plugin1 cimglist_load_plugin1(filename); #endif #ifdef cimglist_load_plugin2 cimglist_load_plugin2(filename); #endif #ifdef cimglist_load_plugin3 cimglist_load_plugin3(filename); #endif #ifdef cimglist_load_plugin4 cimglist_load_plugin4(filename); #endif #ifdef cimglist_load_plugin5 cimglist_load_plugin5(filename); #endif #ifdef cimglist_load_plugin6 cimglist_load_plugin6(filename); #endif #ifdef cimglist_load_plugin7 cimglist_load_plugin7(filename); #endif #ifdef cimglist_load_plugin8 cimglist_load_plugin8(filename); #endif if (!cimg::strcasecmp(ext,"tif") || !cimg::strcasecmp(ext,"tiff")) load_tiff(filename); else if (!cimg::strcasecmp(ext,"gif")) load_gif_external(filename); else if (!cimg::strcasecmp(ext,"cimg") || !cimg::strcasecmp(ext,"cimgz") || !*ext) load_cimg(filename); else if (!cimg::strcasecmp(ext,"rec") || !cimg::strcasecmp(ext,"par")) load_parrec(filename); else if (!cimg::strcasecmp(ext,"avi") || !cimg::strcasecmp(ext,"mov") || !cimg::strcasecmp(ext,"asf") || !cimg::strcasecmp(ext,"divx") || !cimg::strcasecmp(ext,"flv") || !cimg::strcasecmp(ext,"mpg") || !cimg::strcasecmp(ext,"m1v") || !cimg::strcasecmp(ext,"m2v") || !cimg::strcasecmp(ext,"m4v") || !cimg::strcasecmp(ext,"mjp") || !cimg::strcasecmp(ext,"mp4") || !cimg::strcasecmp(ext,"mkv") || !cimg::strcasecmp(ext,"mpe") || !cimg::strcasecmp(ext,"movie") || !cimg::strcasecmp(ext,"ogm") || !cimg::strcasecmp(ext,"ogg") || !cimg::strcasecmp(ext,"ogv") || !cimg::strcasecmp(ext,"qt") || !cimg::strcasecmp(ext,"rm") || !cimg::strcasecmp(ext,"vob") || !cimg::strcasecmp(ext,"wmv") || !cimg::strcasecmp(ext,"xvid") || !cimg::strcasecmp(ext,"mpeg")) load_video(filename); else if (!cimg::strcasecmp(ext,"gz")) load_gzip_external(filename); else is_loaded = false; } catch (CImgIOException&) { is_loaded = false; } // If nothing loaded, try to guess file format from magic number in file. if (!is_loaded && !is_stdin) { std::FILE *const file = cimg::std_fopen(filename,"rb"); if (!file) { cimg::exception_mode(omode); throw CImgIOException(_cimglist_instance "load(): Failed to open file '%s'.", cimglist_instance, filename); } const char *const f_type = cimg::ftype(file,filename); cimg::fclose(file); is_loaded = true; try { if (!cimg::strcasecmp(f_type,"gif")) load_gif_external(filename); else if (!cimg::strcasecmp(f_type,"tif")) load_tiff(filename); else is_loaded = false; } catch (CImgIOException&) { is_loaded = false; } } // If nothing loaded, try to load file as a single image. if (!is_loaded) { assign(1); try { _data->load(filename); } catch (CImgIOException&) { cimg::exception_mode(omode); throw CImgIOException(_cimglist_instance "load(): Failed to recognize format of file '%s'.", cimglist_instance, filename); } } cimg::exception_mode(omode); return *this; } //! Load a list from a file \newinstance. static CImgList<T> get_load(const char *const filename) { return CImgList<T>().load(filename); } //! Load a list from a .cimg file. /** \param filename Filename to read data from. **/ CImgList<T>& load_cimg(const char *const filename) { return _load_cimg(0,filename); } //! Load a list from a .cimg file \newinstance. static CImgList<T> get_load_cimg(const char *const filename) { return CImgList<T>().load_cimg(filename); } //! Load a list from a .cimg file. /** \param file File to read data from. **/ CImgList<T>& load_cimg(std::FILE *const file) { return _load_cimg(file,0); } //! Load a list from a .cimg file \newinstance. static CImgList<T> get_load_cimg(std::FILE *const file) { return CImgList<T>().load_cimg(file); } CImgList<T>& _load_cimg(std::FILE *const file, const char *const filename) { #ifdef cimg_use_zlib #define _cimgz_load_cimg_case(Tss) { \ Bytef *const cbuf = new Bytef[csiz]; \ cimg::fread(cbuf,csiz,nfile); \ raw.assign(W,H,D,C); \ uLongf destlen = (ulongT)raw.size()*sizeof(Tss); \ uncompress((Bytef*)raw._data,&destlen,cbuf,csiz); \ delete[] cbuf; \ if (endian!=cimg::endianness()) cimg::invert_endianness(raw._data,raw.size()); \ raw.move_to(img); \ } #else #define _cimgz_load_cimg_case(Tss) \ throw CImgIOException(_cimglist_instance \ "load_cimg(): Unable to load compressed data from file '%s' unless zlib is enabled.", \ cimglist_instance, \ filename?filename:"(FILE*)"); #endif #define _cimg_load_cimg_case(Ts,Tss) \ if (!loaded && !cimg::strcasecmp(Ts,str_pixeltype)) { \ for (unsigned int l = 0; l<N; ++l) { \ j = 0; while ((i=std::fgetc(nfile))!='\n' && i>=0 && j<255) tmp[j++] = (char)i; tmp[j] = 0; \ W = H = D = C = 0; csiz = 0; \ if ((err = cimg_sscanf(tmp,"%u %u %u %u #%lu",&W,&H,&D,&C,&csiz))<4) \ throw CImgIOException(_cimglist_instance \ "load_cimg(): Invalid specified size (%u,%u,%u,%u) of image %u in file '%s'.", \ cimglist_instance, \ W,H,D,C,l,filename?filename:("(FILE*)")); \ if (W*H*D*C>0) { \ CImg<Tss> raw; \ CImg<T> &img = _data[l]; \ if (err==5) _cimgz_load_cimg_case(Tss) \ else { \ img.assign(W,H,D,C); \ T *ptrd = img._data; \ for (ulongT to_read = img.size(); to_read; ) { \ raw.assign((unsigned int)std::min(to_read,cimg_iobuffer)); \ cimg::fread(raw._data,raw._width,nfile); \ if (endian!=cimg::endianness()) cimg::invert_endianness(raw._data,raw.size()); \ const Tss *ptrs = raw._data; \ for (ulongT off = (ulongT)raw._width; off; --off) *(ptrd++) = (T)*(ptrs++); \ to_read-=raw._width; \ } \ } \ } \ } \ loaded = true; \ } if (!filename && !file) throw CImgArgumentException(_cimglist_instance "load_cimg(): Specified filename is (null).", cimglist_instance); const ulongT cimg_iobuffer = (ulongT)24*1024*1024; std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); bool loaded = false, endian = cimg::endianness(); CImg<charT> tmp(256), str_pixeltype(256), str_endian(256); *tmp = *str_pixeltype = *str_endian = 0; unsigned int j, N = 0, W, H, D, C; unsigned long csiz; int i, err; do { j = 0; while ((i=std::fgetc(nfile))!='\n' && i>=0 && j<255) tmp[j++] = (char)i; tmp[j] = 0; } while (*tmp=='#' && i>=0); err = cimg_sscanf(tmp,"%u%*c%255[A-Za-z64_]%*c%255[sA-Za-z_ ]", &N,str_pixeltype._data,str_endian._data); if (err<2) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimglist_instance "load_cimg(): CImg header not found in file '%s'.", cimglist_instance, filename?filename:"(FILE*)"); } if (!cimg::strncasecmp("little",str_endian,6)) endian = false; else if (!cimg::strncasecmp("big",str_endian,3)) endian = true; assign(N); _cimg_load_cimg_case("bool",bool); _cimg_load_cimg_case("unsigned_char",unsigned char); _cimg_load_cimg_case("uchar",unsigned char); _cimg_load_cimg_case("char",char); _cimg_load_cimg_case("unsigned_short",unsigned short); _cimg_load_cimg_case("ushort",unsigned short); _cimg_load_cimg_case("short",short); _cimg_load_cimg_case("unsigned_int",unsigned int); _cimg_load_cimg_case("uint",unsigned int); _cimg_load_cimg_case("int",int); _cimg_load_cimg_case("unsigned_long",ulongT); _cimg_load_cimg_case("ulong",ulongT); _cimg_load_cimg_case("long",longT); _cimg_load_cimg_case("unsigned_int64",uint64T); _cimg_load_cimg_case("uint64",uint64T); _cimg_load_cimg_case("int64",int64T); _cimg_load_cimg_case("float",float); _cimg_load_cimg_case("double",double); if (!loaded) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimglist_instance "load_cimg(): Unsupported pixel type '%s' for file '%s'.", cimglist_instance, str_pixeltype._data,filename?filename:"(FILE*)"); } if (!file) cimg::fclose(nfile); return *this; } //! Load a sublist list from a (non compressed) .cimg file. /** \param filename Filename to read data from. \param n0 Starting index of images to read (~0U for max). \param n1 Ending index of images to read (~0U for max). \param x0 Starting X-coordinates of image regions to read. \param y0 Starting Y-coordinates of image regions to read. \param z0 Starting Z-coordinates of image regions to read. \param c0 Starting C-coordinates of image regions to read. \param x1 Ending X-coordinates of image regions to read (~0U for max). \param y1 Ending Y-coordinates of image regions to read (~0U for max). \param z1 Ending Z-coordinates of image regions to read (~0U for max). \param c1 Ending C-coordinates of image regions to read (~0U for max). **/ CImgList<T>& load_cimg(const char *const filename, const unsigned int n0, const unsigned int n1, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0, const unsigned int x1, const unsigned int y1, const unsigned int z1, const unsigned int c1) { return _load_cimg(0,filename,n0,n1,x0,y0,z0,c0,x1,y1,z1,c1); } //! Load a sublist list from a (non compressed) .cimg file \newinstance. static CImgList<T> get_load_cimg(const char *const filename, const unsigned int n0, const unsigned int n1, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0, const unsigned int x1, const unsigned int y1, const unsigned int z1, const unsigned int c1) { return CImgList<T>().load_cimg(filename,n0,n1,x0,y0,z0,c0,x1,y1,z1,c1); } //! Load a sub-image list from a (non compressed) .cimg file \overloading. CImgList<T>& load_cimg(std::FILE *const file, const unsigned int n0, const unsigned int n1, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0, const unsigned int x1, const unsigned int y1, const unsigned int z1, const unsigned int c1) { return _load_cimg(file,0,n0,n1,x0,y0,z0,c0,x1,y1,z1,c1); } //! Load a sub-image list from a (non compressed) .cimg file \newinstance. static CImgList<T> get_load_cimg(std::FILE *const file, const unsigned int n0, const unsigned int n1, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0, const unsigned int x1, const unsigned int y1, const unsigned int z1, const unsigned int c1) { return CImgList<T>().load_cimg(file,n0,n1,x0,y0,z0,c0,x1,y1,z1,c1); } CImgList<T>& _load_cimg(std::FILE *const file, const char *const filename, const unsigned int n0, const unsigned int n1, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0, const unsigned int x1, const unsigned int y1, const unsigned int z1, const unsigned int c1) { #define _cimg_load_cimg_case2(Ts,Tss) \ if (!loaded && !cimg::strcasecmp(Ts,str_pixeltype)) { \ for (unsigned int l = 0; l<=nn1; ++l) { \ j = 0; while ((i=std::fgetc(nfile))!='\n' && i>=0) tmp[j++] = (char)i; tmp[j] = 0; \ W = H = D = C = 0; \ if (cimg_sscanf(tmp,"%u %u %u %u",&W,&H,&D,&C)!=4) \ throw CImgIOException(_cimglist_instance \ "load_cimg(): Invalid specified size (%u,%u,%u,%u) of image %u in file '%s'", \ cimglist_instance, \ W,H,D,C,l,filename?filename:"(FILE*)"); \ if (W*H*D*C>0) { \ if (l<nn0 || nx0>=W || ny0>=H || nz0>=D || nc0>=C) cimg::fseek(nfile,W*H*D*C*sizeof(Tss),SEEK_CUR); \ else { \ const unsigned int \ _nx1 = nx1==~0U?W - 1:nx1, \ _ny1 = ny1==~0U?H - 1:ny1, \ _nz1 = nz1==~0U?D - 1:nz1, \ _nc1 = nc1==~0U?C - 1:nc1; \ if (_nx1>=W || _ny1>=H || _nz1>=D || _nc1>=C) \ throw CImgArgumentException(_cimglist_instance \ "load_cimg(): Invalid specified coordinates " \ "[%u](%u,%u,%u,%u) -> [%u](%u,%u,%u,%u) " \ "because image [%u] in file '%s' has size (%u,%u,%u,%u).", \ cimglist_instance, \ n0,x0,y0,z0,c0,n1,x1,y1,z1,c1,l,filename?filename:"(FILE*)",W,H,D,C); \ CImg<Tss> raw(1 + _nx1 - nx0); \ CImg<T> &img = _data[l - nn0]; \ img.assign(1 + _nx1 - nx0,1 + _ny1 - ny0,1 + _nz1 - nz0,1 + _nc1 - nc0); \ T *ptrd = img._data; \ ulongT skipvb = nc0*W*H*D*sizeof(Tss); \ if (skipvb) cimg::fseek(nfile,skipvb,SEEK_CUR); \ for (unsigned int c = 1 + _nc1 - nc0; c; --c) { \ const ulongT skipzb = nz0*W*H*sizeof(Tss); \ if (skipzb) cimg::fseek(nfile,skipzb,SEEK_CUR); \ for (unsigned int z = 1 + _nz1 - nz0; z; --z) { \ const ulongT skipyb = ny0*W*sizeof(Tss); \ if (skipyb) cimg::fseek(nfile,skipyb,SEEK_CUR); \ for (unsigned int y = 1 + _ny1 - ny0; y; --y) { \ const ulongT skipxb = nx0*sizeof(Tss); \ if (skipxb) cimg::fseek(nfile,skipxb,SEEK_CUR); \ cimg::fread(raw._data,raw._width,nfile); \ if (endian!=cimg::endianness()) cimg::invert_endianness(raw._data,raw._width); \ const Tss *ptrs = raw._data; \ for (unsigned int off = raw._width; off; --off) *(ptrd++) = (T)*(ptrs++); \ const ulongT skipxe = (W - 1 - _nx1)*sizeof(Tss); \ if (skipxe) cimg::fseek(nfile,skipxe,SEEK_CUR); \ } \ const ulongT skipye = (H - 1 - _ny1)*W*sizeof(Tss); \ if (skipye) cimg::fseek(nfile,skipye,SEEK_CUR); \ } \ const ulongT skipze = (D - 1 - _nz1)*W*H*sizeof(Tss); \ if (skipze) cimg::fseek(nfile,skipze,SEEK_CUR); \ } \ const ulongT skipve = (C - 1 - _nc1)*W*H*D*sizeof(Tss); \ if (skipve) cimg::fseek(nfile,skipve,SEEK_CUR); \ } \ } \ } \ loaded = true; \ } if (!filename && !file) throw CImgArgumentException(_cimglist_instance "load_cimg(): Specified filename is (null).", cimglist_instance); unsigned int nn0 = std::min(n0,n1), nn1 = std::max(n0,n1), nx0 = std::min(x0,x1), nx1 = std::max(x0,x1), ny0 = std::min(y0,y1), ny1 = std::max(y0,y1), nz0 = std::min(z0,z1), nz1 = std::max(z0,z1), nc0 = std::min(c0,c1), nc1 = std::max(c0,c1); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); bool loaded = false, endian = cimg::endianness(); CImg<charT> tmp(256), str_pixeltype(256), str_endian(256); *tmp = *str_pixeltype = *str_endian = 0; unsigned int j, N, W, H, D, C; int i, err; j = 0; while ((i=std::fgetc(nfile))!='\n' && i!=EOF && j<256) tmp[j++] = (char)i; tmp[j] = 0; err = cimg_sscanf(tmp,"%u%*c%255[A-Za-z64_]%*c%255[sA-Za-z_ ]", &N,str_pixeltype._data,str_endian._data); if (err<2) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimglist_instance "load_cimg(): CImg header not found in file '%s'.", cimglist_instance, filename?filename:"(FILE*)"); } if (!cimg::strncasecmp("little",str_endian,6)) endian = false; else if (!cimg::strncasecmp("big",str_endian,3)) endian = true; nn1 = n1==~0U?N - 1:n1; if (nn1>=N) throw CImgArgumentException(_cimglist_instance "load_cimg(): Invalid specified coordinates [%u](%u,%u,%u,%u) -> [%u](%u,%u,%u,%u) " "because file '%s' contains only %u images.", cimglist_instance, n0,x0,y0,z0,c0,n1,x1,y1,z1,c1,filename?filename:"(FILE*)",N); assign(1 + nn1 - n0); _cimg_load_cimg_case2("bool",bool); _cimg_load_cimg_case2("unsigned_char",unsigned char); _cimg_load_cimg_case2("uchar",unsigned char); _cimg_load_cimg_case2("char",char); _cimg_load_cimg_case2("unsigned_short",unsigned short); _cimg_load_cimg_case2("ushort",unsigned short); _cimg_load_cimg_case2("short",short); _cimg_load_cimg_case2("unsigned_int",unsigned int); _cimg_load_cimg_case2("uint",unsigned int); _cimg_load_cimg_case2("int",int); _cimg_load_cimg_case2("unsigned_long",ulongT); _cimg_load_cimg_case2("ulong",ulongT); _cimg_load_cimg_case2("long",longT); _cimg_load_cimg_case2("unsigned_int64",uint64T); _cimg_load_cimg_case2("uint64",uint64T); _cimg_load_cimg_case2("int64",int64T); _cimg_load_cimg_case2("float",float); _cimg_load_cimg_case2("double",double); if (!loaded) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimglist_instance "load_cimg(): Unsupported pixel type '%s' for file '%s'.", cimglist_instance, str_pixeltype._data,filename?filename:"(FILE*)"); } if (!file) cimg::fclose(nfile); return *this; } //! Load a list from a PAR/REC (Philips) file. /** \param filename Filename to read data from. **/ CImgList<T>& load_parrec(const char *const filename) { if (!filename) throw CImgArgumentException(_cimglist_instance "load_parrec(): Specified filename is (null).", cimglist_instance); CImg<charT> body(1024), filenamepar(1024), filenamerec(1024); *body = *filenamepar = *filenamerec = 0; const char *const ext = cimg::split_filename(filename,body); if (!std::strcmp(ext,"par")) { std::strncpy(filenamepar,filename,filenamepar._width - 1); cimg_snprintf(filenamerec,filenamerec._width,"%s.rec",body._data); } if (!std::strcmp(ext,"PAR")) { std::strncpy(filenamepar,filename,filenamepar._width - 1); cimg_snprintf(filenamerec,filenamerec._width,"%s.REC",body._data); } if (!std::strcmp(ext,"rec")) { std::strncpy(filenamerec,filename,filenamerec._width - 1); cimg_snprintf(filenamepar,filenamepar._width,"%s.par",body._data); } if (!std::strcmp(ext,"REC")) { std::strncpy(filenamerec,filename,filenamerec._width - 1); cimg_snprintf(filenamepar,filenamepar._width,"%s.PAR",body._data); } std::FILE *file = cimg::fopen(filenamepar,"r"); // Parse header file CImgList<floatT> st_slices; CImgList<uintT> st_global; CImg<charT> line(256); *line = 0; int err; do { err = std::fscanf(file,"%255[^\n]%*c",line._data); } while (err!=EOF && (*line=='#' || *line=='.')); do { unsigned int sn,size_x,size_y,pixsize; float rs,ri,ss; err = std::fscanf(file,"%u%*u%*u%*u%*u%*u%*u%u%*u%u%u%g%g%g%*[^\n]",&sn,&pixsize,&size_x,&size_y,&ri,&rs,&ss); if (err==7) { CImg<floatT>::vector((float)sn,(float)pixsize,(float)size_x,(float)size_y,ri,rs,ss,0).move_to(st_slices); unsigned int i; for (i = 0; i<st_global._width && sn<=st_global[i][2]; ++i) {} if (i==st_global._width) CImg<uintT>::vector(size_x,size_y,sn).move_to(st_global); else { CImg<uintT> &vec = st_global[i]; if (size_x>vec[0]) vec[0] = size_x; if (size_y>vec[1]) vec[1] = size_y; vec[2] = sn; } st_slices[st_slices._width - 1][7] = (float)i; } } while (err==7); // Read data std::FILE *file2 = cimg::fopen(filenamerec,"rb"); cimglist_for(st_global,l) { const CImg<uintT>& vec = st_global[l]; CImg<T>(vec[0],vec[1],vec[2]).move_to(*this); } cimglist_for(st_slices,l) { const CImg<floatT>& vec = st_slices[l]; const unsigned int sn = (unsigned int)vec[0] - 1, pixsize = (unsigned int)vec[1], size_x = (unsigned int)vec[2], size_y = (unsigned int)vec[3], imn = (unsigned int)vec[7]; const float ri = vec[4], rs = vec[5], ss = vec[6]; switch (pixsize) { case 8 : { CImg<ucharT> buf(size_x,size_y); cimg::fread(buf._data,size_x*size_y,file2); if (cimg::endianness()) cimg::invert_endianness(buf._data,size_x*size_y); CImg<T>& img = (*this)[imn]; cimg_forXY(img,x,y) img(x,y,sn) = (T)(( buf(x,y)*rs + ri )/(rs*ss)); } break; case 16 : { CImg<ushortT> buf(size_x,size_y); cimg::fread(buf._data,size_x*size_y,file2); if (cimg::endianness()) cimg::invert_endianness(buf._data,size_x*size_y); CImg<T>& img = (*this)[imn]; cimg_forXY(img,x,y) img(x,y,sn) = (T)(( buf(x,y)*rs + ri )/(rs*ss)); } break; case 32 : { CImg<uintT> buf(size_x,size_y); cimg::fread(buf._data,size_x*size_y,file2); if (cimg::endianness()) cimg::invert_endianness(buf._data,size_x*size_y); CImg<T>& img = (*this)[imn]; cimg_forXY(img,x,y) img(x,y,sn) = (T)(( buf(x,y)*rs + ri )/(rs*ss)); } break; default : cimg::fclose(file); cimg::fclose(file2); throw CImgIOException(_cimglist_instance "load_parrec(): Unsupported %d-bits pixel type for file '%s'.", cimglist_instance, pixsize,filename); } } cimg::fclose(file); cimg::fclose(file2); if (!_width) throw CImgIOException(_cimglist_instance "load_parrec(): Failed to recognize valid PAR-REC data in file '%s'.", cimglist_instance, filename); return *this; } //! Load a list from a PAR/REC (Philips) file \newinstance. static CImgList<T> get_load_parrec(const char *const filename) { return CImgList<T>().load_parrec(filename); } //! Load a list from a YUV image sequence file. /** \param filename Filename to read data from. \param size_x Width of the images. \param size_y Height of the images. \param chroma_subsampling Type of chroma subsampling. Can be <tt>{ 420 | 422 | 444 }</tt>. \param first_frame Index of first image frame to read. \param last_frame Index of last image frame to read. \param step_frame Step applied between each frame. \param yuv2rgb Apply YUV to RGB transformation during reading. **/ CImgList<T>& load_yuv(const char *const filename, const unsigned int size_x, const unsigned int size_y, const unsigned int chroma_subsampling=444, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const bool yuv2rgb=true) { return _load_yuv(0,filename,size_x,size_y,chroma_subsampling, first_frame,last_frame,step_frame,yuv2rgb); } //! Load a list from a YUV image sequence file \newinstance. static CImgList<T> get_load_yuv(const char *const filename, const unsigned int size_x, const unsigned int size_y=1, const unsigned int chroma_subsampling=444, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const bool yuv2rgb=true) { return CImgList<T>().load_yuv(filename,size_x,size_y,chroma_subsampling, first_frame,last_frame,step_frame,yuv2rgb); } //! Load a list from an image sequence YUV file \overloading. CImgList<T>& load_yuv(std::FILE *const file, const unsigned int size_x, const unsigned int size_y, const unsigned int chroma_subsampling=444, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const bool yuv2rgb=true) { return _load_yuv(file,0,size_x,size_y,chroma_subsampling, first_frame,last_frame,step_frame,yuv2rgb); } //! Load a list from an image sequence YUV file \newinstance. static CImgList<T> get_load_yuv(std::FILE *const file, const unsigned int size_x, const unsigned int size_y=1, const unsigned int chroma_subsampling=444, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const bool yuv2rgb=true) { return CImgList<T>().load_yuv(file,size_x,size_y,chroma_subsampling, first_frame,last_frame,step_frame,yuv2rgb); } CImgList<T>& _load_yuv(std::FILE *const file, const char *const filename, const unsigned int size_x, const unsigned int size_y, const unsigned int chroma_subsampling, const unsigned int first_frame, const unsigned int last_frame, const unsigned int step_frame, const bool yuv2rgb) { if (!filename && !file) throw CImgArgumentException(_cimglist_instance "load_yuv(): Specified filename is (null).", cimglist_instance); if (chroma_subsampling!=420 && chroma_subsampling!=422 && chroma_subsampling!=444) throw CImgArgumentException(_cimglist_instance "load_yuv(): Specified chroma subsampling '%u' is invalid, for file '%s'.", cimglist_instance, chroma_subsampling,filename?filename:"(FILE*)"); const unsigned int cfx = chroma_subsampling==420 || chroma_subsampling==422?2:1, cfy = chroma_subsampling==420?2:1, nfirst_frame = first_frame<last_frame?first_frame:last_frame, nlast_frame = first_frame<last_frame?last_frame:first_frame, nstep_frame = step_frame?step_frame:1; if (!size_x || !size_y || size_x%cfx || size_y%cfy) throw CImgArgumentException(_cimglist_instance "load_yuv(): Specified dimensions (%u,%u) are invalid, for file '%s'.", cimglist_instance, size_x,size_y,filename?filename:"(FILE*)"); CImg<ucharT> YUV(size_x,size_y,1,3), UV(size_x/cfx,size_y/cfy,1,2); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); bool stop_flag = false; int err; if (nfirst_frame) { err = cimg::fseek(nfile,(uint64T)nfirst_frame*(YUV._width*YUV._height + 2*UV._width*UV._height),SEEK_CUR); if (err) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimglist_instance "load_yuv(): File '%s' doesn't contain frame number %u.", cimglist_instance, filename?filename:"(FILE*)",nfirst_frame); } } unsigned int frame; for (frame = nfirst_frame; !stop_flag && frame<=nlast_frame; frame+=nstep_frame) { YUV.get_shared_channel(0).fill(0); // *TRY* to read the luminance part, do not replace by cimg::fread! err = (int)std::fread((void*)(YUV._data),1,(size_t)YUV._width*YUV._height,nfile); if (err!=(int)(YUV._width*YUV._height)) { stop_flag = true; if (err>0) cimg::warn(_cimglist_instance "load_yuv(): File '%s' contains incomplete data or given image dimensions " "(%u,%u) are incorrect.", cimglist_instance, filename?filename:"(FILE*)",size_x,size_y); } else { UV.fill(0); // *TRY* to read the luminance part, do not replace by cimg::fread! err = (int)std::fread((void*)(UV._data),1,(size_t)UV.size(),nfile); if (err!=(int)(UV.size())) { stop_flag = true; if (err>0) cimg::warn(_cimglist_instance "load_yuv(): File '%s' contains incomplete data or given image dimensions " "(%u,%u) are incorrect.", cimglist_instance, filename?filename:"(FILE*)",size_x,size_y); } else { const ucharT *ptrs1 = UV._data, *ptrs2 = UV.data(0,0,0,1); ucharT *ptrd1 = YUV.data(0,0,0,1), *ptrd2 = YUV.data(0,0,0,2); const unsigned int wd = YUV._width; switch (chroma_subsampling) { case 420 : cimg_forY(UV,y) { cimg_forX(UV,x) { const ucharT U = *(ptrs1++), V = *(ptrs2++); ptrd1[wd] = U; *(ptrd1)++ = U; ptrd1[wd] = U; *(ptrd1)++ = U; ptrd2[wd] = V; *(ptrd2)++ = V; ptrd2[wd] = V; *(ptrd2)++ = V; } ptrd1+=wd; ptrd2+=wd; } break; case 422 : cimg_forXY(UV,x,y) { const ucharT U = *(ptrs1++), V = *(ptrs2++); *(ptrd1++) = U; *(ptrd1++) = U; *(ptrd2++) = V; *(ptrd2++) = V; } break; default : YUV.draw_image(0,0,0,1,UV); } if (yuv2rgb) YUV.YCbCrtoRGB(); insert(YUV); if (nstep_frame>1) cimg::fseek(nfile,(uint64T)(nstep_frame - 1)*(size_x*size_y + size_x*size_y/2),SEEK_CUR); } } } if (is_empty()) throw CImgIOException(_cimglist_instance "load_yuv() : Missing data in file '%s'.", cimglist_instance, filename?filename:"(FILE*)"); if (stop_flag && nlast_frame!=~0U && frame!=nlast_frame) cimg::warn(_cimglist_instance "load_yuv(): Frame %d not reached since only %u frames were found in file '%s'.", cimglist_instance, nlast_frame,frame - 1,filename?filename:"(FILE*)"); if (!file) cimg::fclose(nfile); return *this; } //! Load an image from a video file, using OpenCV library. /** \param filename Filename, as a C-string. \param first_frame Index of the first frame to read. \param last_frame Index of the last frame to read (can be higher than the actual number of frames, e.g. '~0U'). \param step_frame Step value for frame reading. \note If step_frame==0, the current video stream is forced to be released (without any frames read). **/ CImgList<T>& load_video(const char *const filename, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1) { #ifndef cimg_use_opencv if (first_frame || last_frame!=~0U || step_frame>1) throw CImgArgumentException(_cimglist_instance "load_video() : File '%s', arguments 'first_frame', 'last_frame' " "and 'step_frame' can be only set when using OpenCV " "(-Dcimg_use_opencv must be enabled).", cimglist_instance,filename); return load_ffmpeg_external(filename); #else static cv::VideoCapture *captures[32] = { 0 }; static CImgList<charT> filenames(32); static CImg<uintT> positions(32,1,1,1,0); static int last_used_index = -1; // Detect if a video capture already exists for the specified filename. cimg::mutex(9); int index = -1; if (filename) { if (last_used_index>=0 && !std::strcmp(filename,filenames[last_used_index])) { index = last_used_index; } else cimglist_for(filenames,l) if (filenames[l] && !std::strcmp(filename,filenames[l])) { index = l; break; } } else index = last_used_index; cimg::mutex(9,0); // Release stream if needed. if (!step_frame || (index>=0 && positions[index]>first_frame)) { if (index>=0) { cimg::mutex(9); captures[index]->release(); delete captures[index]; captures[index] = 0; positions[index] = 0; filenames[index].assign(); if (last_used_index==index) last_used_index = -1; index = -1; cimg::mutex(9,0); } else if (filename) cimg::warn(_cimglist_instance "load_video() : File '%s', no opened video stream associated with filename found.", cimglist_instance,filename); else cimg::warn(_cimglist_instance "load_video() : No opened video stream found.", cimglist_instance,filename); if (!step_frame) return *this; } // Find empty slot for capturing video stream. if (index<0) { if (!filename) throw CImgArgumentException(_cimglist_instance "load_video(): No already open video reader found. You must specify a " "non-(null) filename argument for the first call.", cimglist_instance); else { cimg::mutex(9); cimglist_for(filenames,l) if (!filenames[l]) { index = l; break; } cimg::mutex(9,0); } if (index<0) throw CImgIOException(_cimglist_instance "load_video(): File '%s', no video reader slots available. " "You have to release some of your previously opened videos.", cimglist_instance,filename); cimg::mutex(9); captures[index] = new cv::VideoCapture(filename); positions[index] = 0; if (!captures[index]->isOpened()) { delete captures[index]; captures[index] = 0; cimg::mutex(9,0); cimg::fclose(cimg::fopen(filename,"rb")); // Check file availability throw CImgIOException(_cimglist_instance "load_video(): File '%s', unable to detect format of video file.", cimglist_instance,filename); } CImg<charT>::string(filename).move_to(filenames[index]); cimg::mutex(9,0); } cimg::mutex(9); const unsigned int nb_frames = (unsigned int)std::max(0.,captures[index]->get(_cimg_cap_prop_frame_count)); cimg::mutex(9,0); assign(); // Skip frames if requested. bool go_on = true; unsigned int &pos = positions[index]; while (pos<first_frame) { cimg::mutex(9); if (!captures[index]->grab()) { cimg::mutex(9,0); go_on = false; break; } cimg::mutex(9,0); ++pos; } // Read and convert frames. const unsigned int _last_frame = std::min(nb_frames?nb_frames - 1:~0U,last_frame); while (go_on && pos<=_last_frame) { cv::Mat cvimg; cimg::mutex(9); if (captures[index]->read(cvimg)) { CImg<T>::_cvmat2cimg(cvimg).move_to(*this); ++pos; } else go_on = false; cimg::mutex(9,0); if (go_on) for (unsigned int i = 1; go_on && i<step_frame && pos<=_last_frame; ++i, ++pos) { cimg::mutex(9); if (!captures[index]->grab()) go_on = false; cimg::mutex(9,0); } } if (!go_on || (nb_frames && pos>=nb_frames)) { // Close video stream when necessary cimg::mutex(9); captures[index]->release(); delete captures[index]; captures[index] = 0; filenames[index].assign(); positions[index] = 0; index = -1; cimg::mutex(9,0); } cimg::mutex(9); last_used_index = index; cimg::mutex(9,0); if (is_empty()) throw CImgIOException(_cimglist_instance "load_video(): File '%s', unable to locate frame %u.", cimglist_instance,filename,first_frame); return *this; #endif } //! Load an image from a video file, using OpenCV library \newinstance. static CImgList<T> get_load_video(const char *const filename, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1) { return CImgList<T>().load_video(filename,first_frame,last_frame,step_frame); } //! Load an image from a video file using the external tool 'ffmpeg'. /** \param filename Filename to read data from. **/ CImgList<T>& load_ffmpeg_external(const char *const filename) { if (!filename) throw CImgArgumentException(_cimglist_instance "load_ffmpeg_external(): Specified filename is (null).", cimglist_instance); cimg::fclose(cimg::fopen(filename,"rb")); // Check if file exists CImg<charT> command(1024), filename_tmp(256), filename_tmp2(256); std::FILE *file = 0; do { cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); cimg_snprintf(filename_tmp2,filename_tmp2._width,"%s_000001.ppm",filename_tmp._data); if ((file=cimg::std_fopen(filename_tmp2,"rb"))!=0) cimg::fclose(file); } while (file); cimg_snprintf(filename_tmp2,filename_tmp2._width,"%s_%%6d.ppm",filename_tmp._data); cimg_snprintf(command,command._width,"%s -i \"%s\" \"%s\"", cimg::ffmpeg_path(), CImg<charT>::string(filename)._system_strescape().data(), CImg<charT>::string(filename_tmp2)._system_strescape().data()); cimg::system(command,0); const unsigned int omode = cimg::exception_mode(); cimg::exception_mode(0); assign(); unsigned int i = 1; for (bool stop_flag = false; !stop_flag; ++i) { cimg_snprintf(filename_tmp2,filename_tmp2._width,"%s_%.6u.ppm",filename_tmp._data,i); CImg<T> img; try { img.load_pnm(filename_tmp2); } catch (CImgException&) { stop_flag = true; } if (img) { img.move_to(*this); std::remove(filename_tmp2); } } cimg::exception_mode(omode); if (is_empty()) throw CImgIOException(_cimglist_instance "load_ffmpeg_external(): Failed to open file '%s' with external command 'ffmpeg'.", cimglist_instance, filename); return *this; } //! Load an image from a video file using the external tool 'ffmpeg' \newinstance. static CImgList<T> get_load_ffmpeg_external(const char *const filename) { return CImgList<T>().load_ffmpeg_external(filename); } //! Load gif file, using ImageMagick or GraphicsMagick's external tools. /** \param filename Filename to read data from. **/ CImgList<T>& load_gif_external(const char *const filename) { if (!filename) throw CImgArgumentException(_cimglist_instance "load_gif_external(): Specified filename is (null).", cimglist_instance); cimg::fclose(cimg::fopen(filename,"rb")); // Check if file exists if (!_load_gif_external(filename,false)) if (!_load_gif_external(filename,true)) try { assign(CImg<T>().load_other(filename)); } catch (CImgException&) { assign(); } if (is_empty()) throw CImgIOException(_cimglist_instance "load_gif_external(): Failed to open file '%s'.", cimglist_instance,filename); return *this; } CImgList<T>& _load_gif_external(const char *const filename, const bool use_graphicsmagick=false) { CImg<charT> command(1024), filename_tmp(256), filename_tmp2(256); std::FILE *file = 0; do { cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); if (use_graphicsmagick) cimg_snprintf(filename_tmp2,filename_tmp2._width,"%s.png.0",filename_tmp._data); else cimg_snprintf(filename_tmp2,filename_tmp2._width,"%s-0.png",filename_tmp._data); if ((file=cimg::std_fopen(filename_tmp2,"rb"))!=0) cimg::fclose(file); } while (file); if (use_graphicsmagick) cimg_snprintf(command,command._width,"%s convert \"%s\" \"%s.png\"", cimg::graphicsmagick_path(), CImg<charT>::string(filename)._system_strescape().data(), CImg<charT>::string(filename_tmp)._system_strescape().data()); else cimg_snprintf(command,command._width,"%s \"%s\" \"%s.png\"", cimg::imagemagick_path(), CImg<charT>::string(filename)._system_strescape().data(), CImg<charT>::string(filename_tmp)._system_strescape().data()); cimg::system(command,0); const unsigned int omode = cimg::exception_mode(); cimg::exception_mode(0); assign(); // Try to read a single frame gif. cimg_snprintf(filename_tmp2,filename_tmp2._width,"%s.png",filename_tmp._data); CImg<T> img; try { img.load_png(filename_tmp2); } catch (CImgException&) { } if (img) { img.move_to(*this); std::remove(filename_tmp2); } else { // Try to read animated gif unsigned int i = 0; for (bool stop_flag = false; !stop_flag; ++i) { if (use_graphicsmagick) cimg_snprintf(filename_tmp2,filename_tmp2._width,"%s.png.%u",filename_tmp._data,i); else cimg_snprintf(filename_tmp2,filename_tmp2._width,"%s-%u.png",filename_tmp._data,i); try { img.load_png(filename_tmp2); } catch (CImgException&) { stop_flag = true; } if (img) { img.move_to(*this); std::remove(filename_tmp2); } } } cimg::exception_mode(omode); return *this; } //! Load gif file, using ImageMagick or GraphicsMagick's external tools \newinstance. static CImgList<T> get_load_gif_external(const char *const filename) { return CImgList<T>().load_gif_external(filename); } //! Load a gzipped list, using external tool 'gunzip'. /** \param filename Filename to read data from. **/ CImgList<T>& load_gzip_external(const char *const filename) { if (!filename) throw CImgIOException(_cimglist_instance "load_gzip_external(): Specified filename is (null).", cimglist_instance); cimg::fclose(cimg::fopen(filename,"rb")); // Check if file exists CImg<charT> command(1024), filename_tmp(256), body(256); const char *ext = cimg::split_filename(filename,body), *ext2 = cimg::split_filename(body,0); std::FILE *file = 0; do { if (!cimg::strcasecmp(ext,"gz")) { if (*ext2) cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),ext2); else cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); } else { if (*ext) cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),ext); else cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); } if ((file=cimg::std_fopen(filename_tmp,"rb"))!=0) cimg::fclose(file); } while (file); cimg_snprintf(command,command._width,"%s -c \"%s\" > \"%s\"", cimg::gunzip_path(), CImg<charT>::string(filename)._system_strescape().data(), CImg<charT>::string(filename_tmp)._system_strescape().data()); cimg::system(command); if (!(file=cimg::std_fopen(filename_tmp,"rb"))) { cimg::fclose(cimg::fopen(filename,"r")); throw CImgIOException(_cimglist_instance "load_gzip_external(): Failed to open file '%s'.", cimglist_instance, filename); } else cimg::fclose(file); load(filename_tmp); std::remove(filename_tmp); return *this; } //! Load a gzipped list, using external tool 'gunzip' \newinstance. static CImgList<T> get_load_gzip_external(const char *const filename) { return CImgList<T>().load_gzip_external(filename); } //! Load images from a TIFF file. /** \param filename Filename to read data from. \param first_frame Index of first image frame to read. \param last_frame Index of last image frame to read. \param step_frame Step applied between each frame. \param[out] voxel_size Voxel size, as stored in the filename. \param[out] description Description, as stored in the filename. **/ CImgList<T>& load_tiff(const char *const filename, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, float *const voxel_size=0, CImg<charT> *const description=0) { const unsigned int nfirst_frame = first_frame<last_frame?first_frame:last_frame, nstep_frame = step_frame?step_frame:1; unsigned int nlast_frame = first_frame<last_frame?last_frame:first_frame; #ifndef cimg_use_tiff cimg::unused(voxel_size,description); if (nfirst_frame || nlast_frame!=~0U || nstep_frame!=1) throw CImgArgumentException(_cimglist_instance "load_tiff(): Unable to load sub-images from file '%s' unless libtiff is enabled.", cimglist_instance, filename); return assign(CImg<T>::get_load_tiff(filename)); #else #if cimg_verbosity<3 TIFFSetWarningHandler(0); TIFFSetErrorHandler(0); #endif TIFF *tif = TIFFOpen(filename,"r"); if (tif) { unsigned int nb_images = 0; do ++nb_images; while (TIFFReadDirectory(tif)); if (nfirst_frame>=nb_images || (nlast_frame!=~0U && nlast_frame>=nb_images)) cimg::warn(_cimglist_instance "load_tiff(): Invalid specified frame range is [%u,%u] (step %u) since " "file '%s' contains %u image(s).", cimglist_instance, nfirst_frame,nlast_frame,nstep_frame,filename,nb_images); if (nfirst_frame>=nb_images) return assign(); if (nlast_frame>=nb_images) nlast_frame = nb_images - 1; assign(1 + (nlast_frame - nfirst_frame)/nstep_frame); TIFFSetDirectory(tif,0); cimglist_for(*this,l) _data[l]._load_tiff(tif,nfirst_frame + l*nstep_frame,voxel_size,description); TIFFClose(tif); } else throw CImgIOException(_cimglist_instance "load_tiff(): Failed to open file '%s'.", cimglist_instance, filename); return *this; #endif } //! Load a multi-page TIFF file \newinstance. static CImgList<T> get_load_tiff(const char *const filename, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, float *const voxel_size=0, CImg<charT> *const description=0) { return CImgList<T>().load_tiff(filename,first_frame,last_frame,step_frame,voxel_size,description); } //@} //---------------------------------- // //! \name Data Output //@{ //---------------------------------- //! Print information about the list on the standard output. /** \param title Label set to the information displayed. \param display_stats Tells if image statistics must be computed and displayed. **/ const CImgList<T>& print(const char *const title=0, const bool display_stats=true) const { unsigned int msiz = 0; cimglist_for(*this,l) msiz+=_data[l].size(); msiz*=sizeof(T); const unsigned int mdisp = msiz<8*1024?0U:msiz<8*1024*1024?1U:2U; CImg<charT> _title(64); if (!title) cimg_snprintf(_title,_title._width,"CImgList<%s>",pixel_type()); std::fprintf(cimg::output(),"%s%s%s%s: %sthis%s = %p, %ssize%s = %u/%u [%u %s], %sdata%s = (CImg<%s>*)%p", cimg::t_magenta,cimg::t_bold,title?title:_title._data,cimg::t_normal, cimg::t_bold,cimg::t_normal,(void*)this, cimg::t_bold,cimg::t_normal,_width,_allocated_width, mdisp==0?msiz:(mdisp==1?(msiz>>10):(msiz>>20)), mdisp==0?"b":(mdisp==1?"Kio":"Mio"), cimg::t_bold,cimg::t_normal,pixel_type(),(void*)begin()); if (_data) std::fprintf(cimg::output(),"..%p.\n",(void*)((char*)end() - 1)); else std::fprintf(cimg::output(),".\n"); char tmp[16] = { 0 }; cimglist_for(*this,ll) { cimg_snprintf(tmp,sizeof(tmp),"[%d]",ll); std::fprintf(cimg::output()," "); _data[ll].print(tmp,display_stats); if (ll==3 && width()>8) { ll = width() - 5; std::fprintf(cimg::output()," ...\n"); } } std::fflush(cimg::output()); return *this; } //! Display the current CImgList instance in an existing CImgDisplay window (by reference). /** \param disp Reference to an existing CImgDisplay instance, where the current image list will be displayed. \param axis Appending axis. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param align Appending alignmenet. \note This function displays the list images of the current CImgList instance into an existing CImgDisplay window. Images of the list are appended in a single temporarly image for visualization purposes. The function returns immediately. **/ const CImgList<T>& display(CImgDisplay &disp, const char axis='x', const float align=0) const { disp.display(*this,axis,align); return *this; } //! Display the current CImgList instance in a new display window. /** \param disp Display window. \param display_info Tells if image information are displayed on the standard output. \param axis Alignment axis for images viewing. \param align Apending alignment. \param[in,out] XYZ Contains the XYZ coordinates at start / exit of the function. \param exit_on_anykey Exit function when any key is pressed. \note This function opens a new window with a specific title and displays the list images of the current CImgList instance into it. Images of the list are appended in a single temporarly image for visualization purposes. The function returns when a key is pressed or the display window is closed by the user. **/ const CImgList<T>& display(CImgDisplay &disp, const bool display_info, const char axis='x', const float align=0, unsigned int *const XYZ=0, const bool exit_on_anykey=false) const { bool is_exit = false; return _display(disp,0,0,display_info,axis,align,XYZ,exit_on_anykey,0,true,is_exit); } //! Display the current CImgList instance in a new display window. /** \param title Title of the opening display window. \param display_info Tells if list information must be written on standard output. \param axis Appending axis. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param align Appending alignment. \param[in,out] XYZ Contains the XYZ coordinates at start / exit of the function. \param exit_on_anykey Exit function when any key is pressed. **/ const CImgList<T>& display(const char *const title=0, const bool display_info=true, const char axis='x', const float align=0, unsigned int *const XYZ=0, const bool exit_on_anykey=false) const { CImgDisplay disp; bool is_exit = false; return _display(disp,title,0,display_info,axis,align,XYZ,exit_on_anykey,0,true,is_exit); } const CImgList<T>& _display(CImgDisplay &disp, const char *const title, const CImgList<charT> *const titles, const bool display_info, const char axis, const float align, unsigned int *const XYZ, const bool exit_on_anykey, const unsigned int orig, const bool is_first_call, bool &is_exit) const { if (is_empty()) throw CImgInstanceException(_cimglist_instance "display(): Empty instance.", cimglist_instance); if (!disp) { if (axis=='x') { unsigned int sum_width = 0, max_height = 0; cimglist_for(*this,l) { const CImg<T> &img = _data[l]; const unsigned int w = CImgDisplay::_fitscreen(img._width,img._height,img._depth,128,-85,false), h = CImgDisplay::_fitscreen(img._width,img._height,img._depth,128,-85,true); sum_width+=w; if (h>max_height) max_height = h; } disp.assign(cimg_fitscreen(sum_width,max_height,1),title?title:titles?titles->__display()._data:0,1); } else { unsigned int max_width = 0, sum_height = 0; cimglist_for(*this,l) { const CImg<T> &img = _data[l]; const unsigned int w = CImgDisplay::_fitscreen(img._width,img._height,img._depth,128,-85,false), h = CImgDisplay::_fitscreen(img._width,img._height,img._depth,128,-85,true); if (w>max_width) max_width = w; sum_height+=h; } disp.assign(cimg_fitscreen(max_width,sum_height,1),title?title:titles?titles->__display()._data:0,1); } if (!title && !titles) disp.set_title("CImgList<%s> (%u)",pixel_type(),_width); } else if (title) disp.set_title("%s",title); else if (titles) disp.set_title("%s",titles->__display()._data); const CImg<char> dtitle = CImg<char>::string(disp.title()); if (display_info) print(disp.title()); disp.show().flush(); if (_width==1) { const unsigned int dw = disp._width, dh = disp._height; if (!is_first_call) disp.resize(cimg_fitscreen(_data[0]._width,_data[0]._height,_data[0]._depth),false); disp.set_title("%s (%ux%ux%ux%u)", dtitle.data(),_data[0]._width,_data[0]._height,_data[0]._depth,_data[0]._spectrum); _data[0]._display(disp,0,false,XYZ,exit_on_anykey,!is_first_call); if (disp.key()) is_exit = true; disp.resize(cimg_fitscreen(dw,dh,1),false).set_title("%s",dtitle.data()); } else { bool disp_resize = !is_first_call; while (!disp.is_closed() && !is_exit) { const CImg<intT> s = _select(disp,0,true,axis,align,exit_on_anykey,orig,disp_resize,!is_first_call,true); disp_resize = true; if (s[0]<0 && !disp.wheel()) { // No selections done if (disp.button()&2) { disp.flush(); break; } is_exit = true; } else if (disp.wheel()) { // Zoom in/out const int wheel = disp.wheel(); disp.set_wheel(); if (!is_first_call && wheel<0) break; if (wheel>0 && _width>=4) { const unsigned int delta = std::max(1U,(unsigned int)cimg::round(0.3*_width)), ind0 = (unsigned int)std::max(0,s[0] - (int)delta), ind1 = (unsigned int)std::min(width() - 1,s[0] + (int)delta); if ((ind0!=0 || ind1!=_width - 1) && ind1 - ind0>=3) { const CImgList<T> sublist = get_shared_images(ind0,ind1); CImgList<charT> t_sublist; if (titles) t_sublist = titles->get_shared_images(ind0,ind1); sublist._display(disp,0,titles?&t_sublist:0,false,axis,align,XYZ,exit_on_anykey, orig + ind0,false,is_exit); } } } else if (s[0]!=0 || s[1]!=width() - 1) { const CImgList<T> sublist = get_shared_images(s[0],s[1]); CImgList<charT> t_sublist; if (titles) t_sublist = titles->get_shared_images(s[0],s[1]); sublist._display(disp,0,titles?&t_sublist:0,false,axis,align,XYZ,exit_on_anykey, orig + s[0],false,is_exit); } disp.set_title("%s",dtitle.data()); } } return *this; } // [internal] Return string to describe display title. CImg<charT> __display() const { CImg<charT> res, str; cimglist_for(*this,l) { CImg<charT>::string((char*)_data[l]).move_to(str); if (l!=width() - 1) { str.resize(str._width + 1,1,1,1,0); str[str._width - 2] = ','; str[str._width - 1] = ' '; } res.append(str,'x'); } if (!res) return CImg<charT>(1,1,1,1,0).move_to(res); cimg::strellipsize(res,128,false); if (_width>1) { const unsigned int l = (unsigned int)std::strlen(res); if (res._width<=l + 16) res.resize(l + 16,1,1,1,0); cimg_snprintf(res._data + l,16," (#%u)",_width); } return res; } //! Save list into a file. /** \param filename Filename to write data to. \param number When positive, represents an index added to the filename. Otherwise, no number is added. \param digits Number of digits used for adding the number to the filename. **/ const CImgList<T>& save(const char *const filename, const int number=-1, const unsigned int digits=6) const { if (!filename) throw CImgArgumentException(_cimglist_instance "save(): Specified filename is (null).", cimglist_instance); // Do not test for empty instances, since .cimg format is able to manage empty instances. const bool is_stdout = *filename=='-' && (!filename[1] || filename[1]=='.'); const char *const ext = cimg::split_filename(filename); CImg<charT> nfilename(1024); const char *const fn = is_stdout?filename:number>=0?cimg::number_filename(filename,number,digits,nfilename): filename; #ifdef cimglist_save_plugin cimglist_save_plugin(fn); #endif #ifdef cimglist_save_plugin1 cimglist_save_plugin1(fn); #endif #ifdef cimglist_save_plugin2 cimglist_save_plugin2(fn); #endif #ifdef cimglist_save_plugin3 cimglist_save_plugin3(fn); #endif #ifdef cimglist_save_plugin4 cimglist_save_plugin4(fn); #endif #ifdef cimglist_save_plugin5 cimglist_save_plugin5(fn); #endif #ifdef cimglist_save_plugin6 cimglist_save_plugin6(fn); #endif #ifdef cimglist_save_plugin7 cimglist_save_plugin7(fn); #endif #ifdef cimglist_save_plugin8 cimglist_save_plugin8(fn); #endif if (!cimg::strcasecmp(ext,"cimgz")) return save_cimg(fn,true); else if (!cimg::strcasecmp(ext,"cimg") || !*ext) return save_cimg(fn,false); else if (!cimg::strcasecmp(ext,"yuv")) return save_yuv(fn,444,true); else if (!cimg::strcasecmp(ext,"avi") || !cimg::strcasecmp(ext,"mov") || !cimg::strcasecmp(ext,"asf") || !cimg::strcasecmp(ext,"divx") || !cimg::strcasecmp(ext,"flv") || !cimg::strcasecmp(ext,"mpg") || !cimg::strcasecmp(ext,"m1v") || !cimg::strcasecmp(ext,"m2v") || !cimg::strcasecmp(ext,"m4v") || !cimg::strcasecmp(ext,"mjp") || !cimg::strcasecmp(ext,"mp4") || !cimg::strcasecmp(ext,"mkv") || !cimg::strcasecmp(ext,"mpe") || !cimg::strcasecmp(ext,"movie") || !cimg::strcasecmp(ext,"ogm") || !cimg::strcasecmp(ext,"ogg") || !cimg::strcasecmp(ext,"ogv") || !cimg::strcasecmp(ext,"qt") || !cimg::strcasecmp(ext,"rm") || !cimg::strcasecmp(ext,"vob") || !cimg::strcasecmp(ext,"wmv") || !cimg::strcasecmp(ext,"xvid") || !cimg::strcasecmp(ext,"mpeg")) return save_video(fn); #ifdef cimg_use_tiff else if (!cimg::strcasecmp(ext,"tif") || !cimg::strcasecmp(ext,"tiff")) return save_tiff(fn); #endif else if (!cimg::strcasecmp(ext,"gz")) return save_gzip_external(fn); else { if (_width==1) _data[0].save(fn,-1); else cimglist_for(*this,l) { _data[l].save(fn,is_stdout?-1:l); if (is_stdout) std::fputc(EOF,cimg::_stdout()); } } return *this; } //! Tell if an image list can be saved as one single file. /** \param filename Filename, as a C-string. \return \c true if the file format supports multiple images, \c false otherwise. **/ static bool is_saveable(const char *const filename) { const char *const ext = cimg::split_filename(filename); if (!cimg::strcasecmp(ext,"cimgz") || #ifdef cimg_use_tiff !cimg::strcasecmp(ext,"tif") || !cimg::strcasecmp(ext,"tiff") || #endif !cimg::strcasecmp(ext,"yuv") || !cimg::strcasecmp(ext,"avi") || !cimg::strcasecmp(ext,"mov") || !cimg::strcasecmp(ext,"asf") || !cimg::strcasecmp(ext,"divx") || !cimg::strcasecmp(ext,"flv") || !cimg::strcasecmp(ext,"mpg") || !cimg::strcasecmp(ext,"m1v") || !cimg::strcasecmp(ext,"m2v") || !cimg::strcasecmp(ext,"m4v") || !cimg::strcasecmp(ext,"mjp") || !cimg::strcasecmp(ext,"mp4") || !cimg::strcasecmp(ext,"mkv") || !cimg::strcasecmp(ext,"mpe") || !cimg::strcasecmp(ext,"movie") || !cimg::strcasecmp(ext,"ogm") || !cimg::strcasecmp(ext,"ogg") || !cimg::strcasecmp(ext,"ogv") || !cimg::strcasecmp(ext,"qt") || !cimg::strcasecmp(ext,"rm") || !cimg::strcasecmp(ext,"vob") || !cimg::strcasecmp(ext,"wmv") || !cimg::strcasecmp(ext,"xvid") || !cimg::strcasecmp(ext,"mpeg")) return true; return false; } //! Save image sequence as a GIF animated file. /** \param filename Filename to write data to. \param fps Number of desired frames per second. \param nb_loops Number of loops (\c 0 for infinite looping). **/ const CImgList<T>& save_gif_external(const char *const filename, const float fps=25, const unsigned int nb_loops=0) { CImg<charT> command(1024), filename_tmp(256), filename_tmp2(256); CImgList<charT> filenames; std::FILE *file = 0; #ifdef cimg_use_png #define _cimg_save_gif_ext "png" #else #define _cimg_save_gif_ext "ppm" #endif do { cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); cimg_snprintf(filename_tmp2,filename_tmp2._width,"%s_000001." _cimg_save_gif_ext,filename_tmp._data); if ((file=cimg::std_fopen(filename_tmp2,"rb"))!=0) cimg::fclose(file); } while (file); cimglist_for(*this,l) { cimg_snprintf(filename_tmp2,filename_tmp2._width,"%s_%.6u." _cimg_save_gif_ext,filename_tmp._data,l + 1); CImg<charT>::string(filename_tmp2).move_to(filenames); if (_data[l]._depth>1 || _data[l]._spectrum!=3) _data[l].get_resize(-100,-100,1,3).save(filename_tmp2); else _data[l].save(filename_tmp2); } cimg_snprintf(command,command._width,"%s -delay %u -loop %u", cimg::imagemagick_path(),(unsigned int)std::max(0.f,cimg::round(100/fps)),nb_loops); CImg<ucharT>::string(command).move_to(filenames,0); cimg_snprintf(command,command._width,"\"%s\"", CImg<charT>::string(filename)._system_strescape().data()); CImg<ucharT>::string(command).move_to(filenames); CImg<charT> _command = filenames>'x'; cimg_for(_command,p,char) if (!*p) *p = ' '; _command.back() = 0; cimg::system(_command); file = cimg::std_fopen(filename,"rb"); if (!file) throw CImgIOException(_cimglist_instance "save_gif_external(): Failed to save file '%s' with external command 'magick/convert'.", cimglist_instance, filename); else cimg::fclose(file); cimglist_for_in(*this,1,filenames._width - 1,l) std::remove(filenames[l]); return *this; } //! Save list as a YUV image sequence file. /** \param filename Filename to write data to. \param chroma_subsampling Type of chroma subsampling. Can be <tt>{ 420 | 422 | 444 }</tt>. \param is_rgb Tells if the RGB to YUV conversion must be done for saving. **/ const CImgList<T>& save_yuv(const char *const filename=0, const unsigned int chroma_subsampling=444, const bool is_rgb=true) const { return _save_yuv(0,filename,chroma_subsampling,is_rgb); } //! Save image sequence into a YUV file. /** \param file File to write data to. \param chroma_subsampling Type of chroma subsampling. Can be <tt>{ 420 | 422 | 444 }</tt>. \param is_rgb Tells if the RGB to YUV conversion must be done for saving. **/ const CImgList<T>& save_yuv(std::FILE *const file, const unsigned int chroma_subsampling=444, const bool is_rgb=true) const { return _save_yuv(file,0,chroma_subsampling,is_rgb); } const CImgList<T>& _save_yuv(std::FILE *const file, const char *const filename, const unsigned int chroma_subsampling, const bool is_rgb) const { if (!file && !filename) throw CImgArgumentException(_cimglist_instance "save_yuv(): Specified filename is (null).", cimglist_instance); if (chroma_subsampling!=420 && chroma_subsampling!=422 && chroma_subsampling!=444) throw CImgArgumentException(_cimglist_instance "save_yuv(): Specified chroma subsampling %u is invalid, for file '%s'.", cimglist_instance, chroma_subsampling,filename?filename:"(FILE*)"); if (is_empty()) { cimg::fempty(file,filename); return *this; } const unsigned int cfx = chroma_subsampling==420 || chroma_subsampling==422?2:1, cfy = chroma_subsampling==420?2:1, w0 = (*this)[0]._width, h0 = (*this)[0]._height, width0 = w0 + (w0%cfx), height0 = h0 + (h0%cfy); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); cimglist_for(*this,l) { const CImg<T> &frame = (*this)[l]; cimg_forZ(frame,z) { CImg<ucharT> YUV; if (sizeof(T)==1 && !is_rgb && frame._width==width0 && frame._height==height0 && frame._depth==1 && frame._spectrum==3) YUV.assign((unsigned char*)frame._data,width0,height0,1,3,true); else { YUV = frame.get_slice(z); if (YUV._width!=width0 || YUV._height!=height0) YUV.resize(width0,height0,1,-100,0); if (YUV._spectrum!=3) YUV.resize(-100,-100,1,3,YUV._spectrum==1?1:0); if (is_rgb) YUV.RGBtoYCbCr(); } if (chroma_subsampling==444) cimg::fwrite(YUV._data,(size_t)YUV._width*YUV._height*3,nfile); else { cimg::fwrite(YUV._data,(size_t)YUV._width*YUV._height,nfile); CImg<ucharT> UV = YUV.get_channels(1,2); UV.resize(UV._width/cfx,UV._height/cfy,1,2,2); cimg::fwrite(UV._data,(size_t)UV._width*UV._height*2,nfile); } } } if (!file) cimg::fclose(nfile); return *this; } //! Save list into a .cimg file. /** \param filename Filename to write data to. \param is_compressed Tells if data compression must be enabled. **/ const CImgList<T>& save_cimg(const char *const filename, const bool is_compressed=false) const { return _save_cimg(0,filename,is_compressed); } const CImgList<T>& _save_cimg(std::FILE *const file, const char *const filename, const bool is_compressed) const { if (!file && !filename) throw CImgArgumentException(_cimglist_instance "save_cimg(): Specified filename is (null).", cimglist_instance); #ifndef cimg_use_zlib if (is_compressed) cimg::warn(_cimglist_instance "save_cimg(): Unable to save compressed data in file '%s' unless zlib is enabled, " "saving them uncompressed.", cimglist_instance, filename?filename:"(FILE*)"); #endif std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); const char *const ptype = pixel_type(), *const etype = cimg::endianness()?"big":"little"; if (std::strstr(ptype,"unsigned")==ptype) std::fprintf(nfile,"%u unsigned_%s %s_endian\n",_width,ptype + 9,etype); else std::fprintf(nfile,"%u %s %s_endian\n",_width,ptype,etype); cimglist_for(*this,l) { const CImg<T>& img = _data[l]; std::fprintf(nfile,"%u %u %u %u",img._width,img._height,img._depth,img._spectrum); if (img._data) { CImg<T> tmp; if (cimg::endianness()) { tmp = img; cimg::invert_endianness(tmp._data,tmp.size()); } const CImg<T>& ref = cimg::endianness()?tmp:img; bool failed_to_compress = true; if (is_compressed) { #ifdef cimg_use_zlib const ulongT siz = sizeof(T)*ref.size(); uLongf csiz = siz + siz/100 + 16; Bytef *const cbuf = new Bytef[csiz]; if (compress(cbuf,&csiz,(Bytef*)ref._data,siz)) cimg::warn(_cimglist_instance "save_cimg(): Failed to save compressed data for file '%s', saving them uncompressed.", cimglist_instance, filename?filename:"(FILE*)"); else { std::fprintf(nfile," #%lu\n",csiz); cimg::fwrite(cbuf,csiz,nfile); delete[] cbuf; failed_to_compress = false; } #endif } if (failed_to_compress) { // Write in a non-compressed way std::fputc('\n',nfile); cimg::fwrite(ref._data,ref.size(),nfile); } } else std::fputc('\n',nfile); } if (!file) cimg::fclose(nfile); return *this; } //! Save list into a .cimg file. /** \param file File to write data to. \param is_compressed Tells if data compression must be enabled. **/ const CImgList<T>& save_cimg(std::FILE *file, const bool is_compressed=false) const { return _save_cimg(file,0,is_compressed); } const CImgList<T>& _save_cimg(std::FILE *const file, const char *const filename, const unsigned int n0, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0) const { #define _cimg_save_cimg_case(Ts,Tss) \ if (!saved && !cimg::strcasecmp(Ts,str_pixeltype)) { \ for (unsigned int l = 0; l<lmax; ++l) { \ j = 0; while ((i=std::fgetc(nfile))!='\n') tmp[j++]=(char)i; tmp[j] = 0; \ W = H = D = C = 0; \ if (cimg_sscanf(tmp,"%u %u %u %u",&W,&H,&D,&C)!=4) \ throw CImgIOException(_cimglist_instance \ "save_cimg(): Invalid size (%u,%u,%u,%u) of image[%u], for file '%s'.", \ cimglist_instance, \ W,H,D,C,l,filename?filename:"(FILE*)"); \ if (W*H*D*C>0) { \ if (l<n0 || x0>=W || y0>=H || z0>=D || c0>=D) cimg::fseek(nfile,W*H*D*C*sizeof(Tss),SEEK_CUR); \ else { \ const CImg<T>& img = (*this)[l - n0]; \ const T *ptrs = img._data; \ const unsigned int \ x1 = x0 + img._width - 1, \ y1 = y0 + img._height - 1, \ z1 = z0 + img._depth - 1, \ c1 = c0 + img._spectrum - 1, \ nx1 = x1>=W?W - 1:x1, \ ny1 = y1>=H?H - 1:y1, \ nz1 = z1>=D?D - 1:z1, \ nc1 = c1>=C?C - 1:c1; \ CImg<Tss> raw(1 + nx1 - x0); \ const unsigned int skipvb = c0*W*H*D*sizeof(Tss); \ if (skipvb) cimg::fseek(nfile,skipvb,SEEK_CUR); \ for (unsigned int v = 1 + nc1 - c0; v; --v) { \ const unsigned int skipzb = z0*W*H*sizeof(Tss); \ if (skipzb) cimg::fseek(nfile,skipzb,SEEK_CUR); \ for (unsigned int z = 1 + nz1 - z0; z; --z) { \ const unsigned int skipyb = y0*W*sizeof(Tss); \ if (skipyb) cimg::fseek(nfile,skipyb,SEEK_CUR); \ for (unsigned int y = 1 + ny1 - y0; y; --y) { \ const unsigned int skipxb = x0*sizeof(Tss); \ if (skipxb) cimg::fseek(nfile,skipxb,SEEK_CUR); \ raw.assign(ptrs, raw._width); \ ptrs+=img._width; \ if (endian) cimg::invert_endianness(raw._data,raw._width); \ cimg::fwrite(raw._data,raw._width,nfile); \ const unsigned int skipxe = (W - 1 - nx1)*sizeof(Tss); \ if (skipxe) cimg::fseek(nfile,skipxe,SEEK_CUR); \ } \ const unsigned int skipye = (H - 1 - ny1)*W*sizeof(Tss); \ if (skipye) cimg::fseek(nfile,skipye,SEEK_CUR); \ } \ const unsigned int skipze = (D - 1 - nz1)*W*H*sizeof(Tss); \ if (skipze) cimg::fseek(nfile,skipze,SEEK_CUR); \ } \ const unsigned int skipve = (C - 1 - nc1)*W*H*D*sizeof(Tss); \ if (skipve) cimg::fseek(nfile,skipve,SEEK_CUR); \ } \ } \ } \ saved = true; \ } if (!file && !filename) throw CImgArgumentException(_cimglist_instance "save_cimg(): Specified filename is (null).", cimglist_instance); if (is_empty()) throw CImgInstanceException(_cimglist_instance "save_cimg(): Empty instance, for file '%s'.", cimglist_instance, filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb+"); bool saved = false, endian = cimg::endianness(); CImg<charT> tmp(256), str_pixeltype(256), str_endian(256); *tmp = *str_pixeltype = *str_endian = 0; unsigned int j, N, W, H, D, C; int i, err; j = 0; while ((i=std::fgetc(nfile))!='\n' && i!=EOF && j<256) tmp[j++] = (char)i; tmp[j] = 0; err = cimg_sscanf(tmp,"%u%*c%255[A-Za-z64_]%*c%255[sA-Za-z_ ]",&N,str_pixeltype._data,str_endian._data); if (err<2) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimglist_instance "save_cimg(): CImg header not found in file '%s'.", cimglist_instance, filename?filename:"(FILE*)"); } if (!cimg::strncasecmp("little",str_endian,6)) endian = false; else if (!cimg::strncasecmp("big",str_endian,3)) endian = true; const unsigned int lmax = std::min(N,n0 + _width); _cimg_save_cimg_case("bool",bool); _cimg_save_cimg_case("unsigned_char",unsigned char); _cimg_save_cimg_case("uchar",unsigned char); _cimg_save_cimg_case("char",char); _cimg_save_cimg_case("unsigned_short",unsigned short); _cimg_save_cimg_case("ushort",unsigned short); _cimg_save_cimg_case("short",short); _cimg_save_cimg_case("unsigned_int",unsigned int); _cimg_save_cimg_case("uint",unsigned int); _cimg_save_cimg_case("int",int); _cimg_save_cimg_case("unsigned_int64",uint64T); _cimg_save_cimg_case("uint64",uint64T); _cimg_save_cimg_case("int64",int64T); _cimg_save_cimg_case("float",float); _cimg_save_cimg_case("double",double); if (!saved) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimglist_instance "save_cimg(): Unsupported data type '%s' for file '%s'.", cimglist_instance, filename?filename:"(FILE*)",str_pixeltype._data); } if (!file) cimg::fclose(nfile); return *this; } //! Insert the image instance into into an existing .cimg file, at specified coordinates. /** \param filename Filename to write data to. \param n0 Starting index of images to write. \param x0 Starting X-coordinates of image regions to write. \param y0 Starting Y-coordinates of image regions to write. \param z0 Starting Z-coordinates of image regions to write. \param c0 Starting C-coordinates of image regions to write. **/ const CImgList<T>& save_cimg(const char *const filename, const unsigned int n0, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0) const { return _save_cimg(0,filename,n0,x0,y0,z0,c0); } //! Insert the image instance into into an existing .cimg file, at specified coordinates. /** \param file File to write data to. \param n0 Starting index of images to write. \param x0 Starting X-coordinates of image regions to write. \param y0 Starting Y-coordinates of image regions to write. \param z0 Starting Z-coordinates of image regions to write. \param c0 Starting C-coordinates of image regions to write. **/ const CImgList<T>& save_cimg(std::FILE *const file, const unsigned int n0, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0) const { return _save_cimg(file,0,n0,x0,y0,z0,c0); } static void _save_empty_cimg(std::FILE *const file, const char *const filename, const unsigned int nb, const unsigned int dx, const unsigned int dy, const unsigned int dz, const unsigned int dc) { std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); const ulongT siz = (ulongT)dx*dy*dz*dc*sizeof(T); std::fprintf(nfile,"%u %s\n",nb,pixel_type()); for (unsigned int i=nb; i; --i) { std::fprintf(nfile,"%u %u %u %u\n",dx,dy,dz,dc); for (ulongT off = siz; off; --off) std::fputc(0,nfile); } if (!file) cimg::fclose(nfile); } //! Save empty (non-compressed) .cimg file with specified dimensions. /** \param filename Filename to write data to. \param nb Number of images to write. \param dx Width of images in the written file. \param dy Height of images in the written file. \param dz Depth of images in the written file. \param dc Spectrum of images in the written file. **/ static void save_empty_cimg(const char *const filename, const unsigned int nb, const unsigned int dx, const unsigned int dy=1, const unsigned int dz=1, const unsigned int dc=1) { return _save_empty_cimg(0,filename,nb,dx,dy,dz,dc); } //! Save empty .cimg file with specified dimensions. /** \param file File to write data to. \param nb Number of images to write. \param dx Width of images in the written file. \param dy Height of images in the written file. \param dz Depth of images in the written file. \param dc Spectrum of images in the written file. **/ static void save_empty_cimg(std::FILE *const file, const unsigned int nb, const unsigned int dx, const unsigned int dy=1, const unsigned int dz=1, const unsigned int dc=1) { return _save_empty_cimg(file,0,nb,dx,dy,dz,dc); } //! Save list as a TIFF file. /** \param filename Filename to write data to. \param compression_type Compression mode used to write data. \param voxel_size Voxel size, to be stored in the filename. \param description Description, to be stored in the filename. \param use_bigtiff Allow to save big tiff files (>4Gb). **/ const CImgList<T>& save_tiff(const char *const filename, const unsigned int compression_type=0, const float *const voxel_size=0, const char *const description=0, const bool use_bigtiff=true) const { if (!filename) throw CImgArgumentException(_cimglist_instance "save_tiff(): Specified filename is (null).", cimglist_instance); if (is_empty()) { cimg::fempty(0,filename); return *this; } #ifndef cimg_use_tiff if (_width==1) _data[0].save_tiff(filename,compression_type,voxel_size,description,use_bigtiff); else cimglist_for(*this,l) { CImg<charT> nfilename(1024); cimg::number_filename(filename,l,6,nfilename); _data[l].save_tiff(nfilename,compression_type,voxel_size,description,use_bigtiff); } #else ulongT siz = 0; cimglist_for(*this,l) siz+=_data[l].size(); const bool _use_bigtiff = use_bigtiff && sizeof(siz)>=8 && siz*sizeof(T)>=1UL<<31; // No bigtiff for small images TIFF *tif = TIFFOpen(filename,_use_bigtiff?"w8":"w4"); if (tif) { for (unsigned int dir = 0, l = 0; l<_width; ++l) { const CImg<T>& img = (*this)[l]; cimg_forZ(img,z) img._save_tiff(tif,dir++,z,compression_type,voxel_size,description); } TIFFClose(tif); } else throw CImgIOException(_cimglist_instance "save_tiff(): Failed to open stream for file '%s'.", cimglist_instance, filename); #endif return *this; } //! Save list as a gzipped file, using external tool 'gzip'. /** \param filename Filename to write data to. **/ const CImgList<T>& save_gzip_external(const char *const filename) const { if (!filename) throw CImgIOException(_cimglist_instance "save_gzip_external(): Specified filename is (null).", cimglist_instance); CImg<charT> command(1024), filename_tmp(256), body(256); const char *ext = cimg::split_filename(filename,body), *ext2 = cimg::split_filename(body,0); std::FILE *file; do { if (!cimg::strcasecmp(ext,"gz")) { if (*ext2) cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),ext2); else cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.cimg", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); } else { if (*ext) cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),ext); else cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s.cimg", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); } if ((file=cimg::std_fopen(filename_tmp,"rb"))!=0) cimg::fclose(file); } while (file); if (is_saveable(body)) { save(filename_tmp); cimg_snprintf(command,command._width,"%s -c \"%s\" > \"%s\"", cimg::gzip_path(), CImg<charT>::string(filename_tmp)._system_strescape().data(), CImg<charT>::string(filename)._system_strescape().data()); cimg::system(command); file = cimg::std_fopen(filename,"rb"); if (!file) throw CImgIOException(_cimglist_instance "save_gzip_external(): Failed to save file '%s' with external command 'gzip'.", cimglist_instance, filename); else cimg::fclose(file); std::remove(filename_tmp); } else { CImg<charT> nfilename(1024); cimglist_for(*this,l) { cimg::number_filename(body,l,6,nfilename); if (*ext) cimg_sprintf(nfilename._data + std::strlen(nfilename),".%s",ext); _data[l].save_gzip_external(nfilename); } } return *this; } //! Save image sequence, using the OpenCV library. /** \param filename Filename to write data to. \param fps Number of frames per second. \param codec Type of compression (See http://www.fourcc.org/codecs.php to see available codecs). \param keep_open Tells if the video writer associated to the specified filename must be kept open or not (to allow frames to be added in the same file afterwards). **/ const CImgList<T>& save_video(const char *const filename, const unsigned int fps=25, const char *codec=0, const bool keep_open=false) const { #ifndef cimg_use_opencv cimg::unused(codec,keep_open); return save_ffmpeg_external(filename,fps); #else static cv::VideoWriter *writers[32] = { 0 }; static CImgList<charT> filenames(32); static CImg<intT> sizes(32,2,1,1,0); static int last_used_index = -1; // Detect if a video writer already exists for the specified filename. cimg::mutex(9); int index = -1; if (filename) { if (last_used_index>=0 && !std::strcmp(filename,filenames[last_used_index])) { index = last_used_index; } else cimglist_for(filenames,l) if (filenames[l] && !std::strcmp(filename,filenames[l])) { index = l; break; } } else index = last_used_index; cimg::mutex(9,0); // Find empty slot for capturing video stream. if (index<0) { if (!filename) throw CImgArgumentException(_cimglist_instance "save_video(): No already open video writer found. You must specify a " "non-(null) filename argument for the first call.", cimglist_instance); else { cimg::mutex(9); cimglist_for(filenames,l) if (!filenames[l]) { index = l; break; } cimg::mutex(9,0); } if (index<0) throw CImgIOException(_cimglist_instance "save_video(): File '%s', no video writer slots available. " "You have to release some of your previously opened videos.", cimglist_instance,filename); if (is_empty()) throw CImgInstanceException(_cimglist_instance "save_video(): Instance list is empty.", cimglist_instance); const unsigned int W = _data?_data[0]._width:0, H = _data?_data[0]._height:0; if (!W || !H) throw CImgInstanceException(_cimglist_instance "save_video(): Frame [0] is an empty image.", cimglist_instance); const char *const _codec = codec && *codec?codec:cimg_OS==2?"mpeg":"mp4v", codec0 = cimg::uppercase(_codec[0]), codec1 = _codec[0]?cimg::uppercase(_codec[1]):0, codec2 = _codec[1]?cimg::uppercase(_codec[2]):0, codec3 = _codec[2]?cimg::uppercase(_codec[3]):0; cimg::mutex(9); writers[index] = new cv::VideoWriter(filename,_cimg_fourcc(codec0,codec1,codec2,codec3),fps,cv::Size(W,H)); if (!writers[index]->isOpened()) { delete writers[index]; writers[index] = 0; cimg::mutex(9,0); throw CImgIOException(_cimglist_instance "save_video(): File '%s', unable to initialize video writer with codec '%c%c%c%c'.", cimglist_instance,filename, codec0,codec1,codec2,codec3); } CImg<charT>::string(filename).move_to(filenames[index]); sizes(index,0) = W; sizes(index,1) = H; cimg::mutex(9,0); } if (!is_empty()) { const unsigned int W = sizes(index,0), H = sizes(index,1); cimg::mutex(9); cimglist_for(*this,l) { CImg<T> &src = _data[l]; if (src.is_empty()) cimg::warn(_cimglist_instance "save_video(): Skip empty frame %d for file '%s'.", cimglist_instance,l,filename); if (src._depth>1 || src._spectrum>3) cimg::warn(_cimglist_instance "save_video(): Frame %u has incompatible dimension (%u,%u,%u,%u). " "Some image data may be ignored when writing frame into video file '%s'.", cimglist_instance,l,src._width,src._height,src._depth,src._spectrum,filename); if (src._width==W && src._height==H && src._spectrum==3) writers[index]->write(CImg<ucharT>(src)._cimg2cvmat()); else { CImg<ucharT> _src(src,false); _src.channels(0,std::min(_src._spectrum - 1,2U)).resize(W,H); _src.resize(W,H,1,3,_src._spectrum==1); writers[index]->write(_src._cimg2cvmat()); } } cimg::mutex(9,0); } cimg::mutex(9); if (!keep_open) { delete writers[index]; writers[index] = 0; filenames[index].assign(); sizes(index,0) = sizes(index,1) = 0; last_used_index = -1; } else last_used_index = index; cimg::mutex(9,0); return *this; #endif } //! Save image sequence, using the external tool 'ffmpeg'. /** \param filename Filename to write data to. \param fps Number of frames per second. \param codec Type of compression. \param bitrate Output bitrate **/ const CImgList<T>& save_ffmpeg_external(const char *const filename, const unsigned int fps=25, const char *const codec=0, const unsigned int bitrate=2048) const { if (!filename) throw CImgArgumentException(_cimglist_instance "save_ffmpeg_external(): Specified filename is (null).", cimglist_instance); if (is_empty()) { cimg::fempty(0,filename); return *this; } const char *const ext = cimg::split_filename(filename), *const _codec = codec?codec:!cimg::strcasecmp(ext,"flv")?"flv":"mpeg2video"; CImg<charT> command(1024), filename_tmp(256), filename_tmp2(256); CImgList<charT> filenames; std::FILE *file = 0; cimglist_for(*this,l) if (!_data[l].is_sameXYZ(_data[0])) throw CImgInstanceException(_cimglist_instance "save_ffmpeg_external(): Invalid instance dimensions for file '%s'.", cimglist_instance, filename); do { cimg_snprintf(filename_tmp,filename_tmp._width,"%s%c%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); cimg_snprintf(filename_tmp2,filename_tmp2._width,"%s_000001.ppm",filename_tmp._data); if ((file=cimg::std_fopen(filename_tmp2,"rb"))!=0) cimg::fclose(file); } while (file); cimglist_for(*this,l) { cimg_snprintf(filename_tmp2,filename_tmp2._width,"%s_%.6u.ppm",filename_tmp._data,l + 1); CImg<charT>::string(filename_tmp2).move_to(filenames); if (_data[l]._depth>1 || _data[l]._spectrum!=3) _data[l].get_resize(-100,-100,1,3).save_pnm(filename_tmp2); else _data[l].save_pnm(filename_tmp2); } cimg_snprintf(command,command._width,"%s -i \"%s_%%6d.ppm\" -vcodec %s -b %uk -r %u -y \"%s\"", cimg::ffmpeg_path(), CImg<charT>::string(filename_tmp)._system_strescape().data(), _codec,bitrate,fps, CImg<charT>::string(filename)._system_strescape().data()); cimg::system(command); file = cimg::std_fopen(filename,"rb"); if (!file) throw CImgIOException(_cimglist_instance "save_ffmpeg_external(): Failed to save file '%s' with external command 'ffmpeg'.", cimglist_instance, filename); else cimg::fclose(file); cimglist_for(*this,l) std::remove(filenames[l]); return *this; } //! Serialize a CImgList<T> instance into a raw CImg<unsigned char> buffer. /** \param is_compressed tells if zlib compression must be used for serialization (this requires 'cimg_use_zlib' been enabled). **/ CImg<ucharT> get_serialize(const bool is_compressed=false) const { #ifndef cimg_use_zlib if (is_compressed) cimg::warn(_cimglist_instance "get_serialize(): Unable to compress data unless zlib is enabled, " "storing them uncompressed.", cimglist_instance); #endif CImgList<ucharT> stream; CImg<charT> tmpstr(128); const char *const ptype = pixel_type(), *const etype = cimg::endianness()?"big":"little"; if (std::strstr(ptype,"unsigned")==ptype) cimg_snprintf(tmpstr,tmpstr._width,"%u unsigned_%s %s_endian\n",_width,ptype + 9,etype); else cimg_snprintf(tmpstr,tmpstr._width,"%u %s %s_endian\n",_width,ptype,etype); CImg<ucharT>::string(tmpstr,false).move_to(stream); cimglist_for(*this,l) { const CImg<T>& img = _data[l]; cimg_snprintf(tmpstr,tmpstr._width,"%u %u %u %u",img._width,img._height,img._depth,img._spectrum); CImg<ucharT>::string(tmpstr,false).move_to(stream); if (img._data) { CImg<T> tmp; if (cimg::endianness()) { tmp = img; cimg::invert_endianness(tmp._data,tmp.size()); } const CImg<T>& ref = cimg::endianness()?tmp:img; bool failed_to_compress = true; if (is_compressed) { #ifdef cimg_use_zlib const ulongT siz = sizeof(T)*ref.size(); uLongf csiz = (ulongT)compressBound(siz); Bytef *const cbuf = new Bytef[csiz]; if (compress(cbuf,&csiz,(Bytef*)ref._data,siz)) cimg::warn(_cimglist_instance "get_serialize(): Failed to save compressed data, saving them uncompressed.", cimglist_instance); else { cimg_snprintf(tmpstr,tmpstr._width," #%lu\n",csiz); CImg<ucharT>::string(tmpstr,false).move_to(stream); CImg<ucharT>(cbuf,csiz).move_to(stream); delete[] cbuf; failed_to_compress = false; } #endif } if (failed_to_compress) { // Write in a non-compressed way CImg<charT>::string("\n",false).move_to(stream); stream.insert(1); stream.back().assign((unsigned char*)ref._data,ref.size()*sizeof(T),1,1,1,true); } } else CImg<charT>::string("\n",false).move_to(stream); } cimglist_apply(stream,unroll)('y'); return stream>'y'; } //! Unserialize a CImg<unsigned char> serialized buffer into a CImgList<T> list. template<typename t> static CImgList<T> get_unserialize(const CImg<t>& buffer) { #ifdef cimg_use_zlib #define _cimgz_unserialize_case(Tss) { \ Bytef *cbuf = 0; \ if (sizeof(t)!=1 || cimg::type<t>::string()==cimg::type<bool>::string()) { \ cbuf = new Bytef[csiz]; Bytef *_cbuf = cbuf; \ for (ulongT k = 0; k<csiz; ++k) *(_cbuf++) = (Bytef)*(stream++); \ is_bytef = false; \ } else { cbuf = (Bytef*)stream; stream+=csiz; is_bytef = true; } \ raw.assign(W,H,D,C); \ uLongf destlen = raw.size()*sizeof(Tss); \ uncompress((Bytef*)raw._data,&destlen,cbuf,csiz); \ if (!is_bytef) delete[] cbuf; \ } #else #define _cimgz_unserialize_case(Tss) \ throw CImgArgumentException("CImgList<%s>::get_unserialize(): Unable to unserialize compressed data " \ "unless zlib is enabled.", \ pixel_type()); #endif #define _cimg_unserialize_case(Ts,Tss) \ if (!loaded && !cimg::strcasecmp(Ts,str_pixeltype)) { \ for (unsigned int l = 0; l<N; ++l) { \ j = 0; while ((i=(int)*stream)!='\n' && stream<estream && j<255) { ++stream; tmp[j++] = (char)i; } \ ++stream; tmp[j] = 0; \ W = H = D = C = 0; csiz = 0; \ if ((err = cimg_sscanf(tmp,"%u %u %u %u #" cimg_fuint64,&W,&H,&D,&C,&csiz))<4) \ throw CImgArgumentException("CImgList<%s>::unserialize(): Invalid specified size (%u,%u,%u,%u) for " \ "image #%u in serialized buffer.", \ pixel_type(),W,H,D,C,l); \ if (W*H*D*C>0) { \ CImg<Tss> raw; \ CImg<T> &img = res._data[l]; \ if (err==5) _cimgz_unserialize_case(Tss) \ else if (sizeof(Tss)==sizeof(t) && cimg::type<Tss>::is_float()==cimg::type<t>::is_float()) { \ raw.assign((Tss*)stream,W,H,D,C,true); \ stream+=raw.size(); \ } else { \ raw.assign(W,H,D,C); \ CImg<ucharT> _raw((unsigned char*)raw._data,W*sizeof(Tss),H,D,C,true); \ cimg_for(_raw,p,unsigned char) *p = (unsigned char)*(stream++); \ } \ if (endian!=cimg::endianness()) cimg::invert_endianness(raw._data,raw.size()); \ raw.move_to(img); \ } \ } \ loaded = true; \ } if (buffer.is_empty()) throw CImgArgumentException("CImgList<%s>::get_unserialize(): Specified serialized buffer is (null).", pixel_type()); CImgList<T> res; const t *stream = buffer._data, *const estream = buffer._data + buffer.size(); bool loaded = false, endian = cimg::endianness(), is_bytef = false; CImg<charT> tmp(256), str_pixeltype(256), str_endian(256); *tmp = *str_pixeltype = *str_endian = 0; unsigned int j, N = 0, W, H, D, C; uint64T csiz; int i, err; cimg::unused(is_bytef); do { j = 0; while ((i=(int)*stream)!='\n' && stream<estream && j<255) { ++stream; tmp[j++] = (char)i; } ++stream; tmp[j] = 0; } while (*tmp=='#' && stream<estream); err = cimg_sscanf(tmp,"%u%*c%255[A-Za-z64_]%*c%255[sA-Za-z_ ]", &N,str_pixeltype._data,str_endian._data); if (err<2) throw CImgArgumentException("CImgList<%s>::get_unserialize(): CImg header not found in serialized buffer.", pixel_type()); if (!cimg::strncasecmp("little",str_endian,6)) endian = false; else if (!cimg::strncasecmp("big",str_endian,3)) endian = true; res.assign(N); _cimg_unserialize_case("bool",bool); _cimg_unserialize_case("unsigned_char",unsigned char); _cimg_unserialize_case("uchar",unsigned char); _cimg_unserialize_case("char",char); _cimg_unserialize_case("unsigned_short",unsigned short); _cimg_unserialize_case("ushort",unsigned short); _cimg_unserialize_case("short",short); _cimg_unserialize_case("unsigned_int",unsigned int); _cimg_unserialize_case("uint",unsigned int); _cimg_unserialize_case("int",int); _cimg_unserialize_case("unsigned_int64",uint64T); _cimg_unserialize_case("uint64",uint64T); _cimg_unserialize_case("int64",int64T); _cimg_unserialize_case("float",float); _cimg_unserialize_case("double",double); if (!loaded) throw CImgArgumentException("CImgList<%s>::get_unserialize(): Unsupported pixel type '%s' defined " "in serialized buffer.", pixel_type(),str_pixeltype._data); return res; } //@} //---------------------------------- // //! \name Others //@{ //---------------------------------- //! Return a CImg pre-defined font with requested height. /** \param font_height Height of the desired font (exact match for 13,23,53,103). \param is_variable_width Decide if the font has a variable (\c true) or fixed (\c false) width. **/ static const CImgList<ucharT>& font(const unsigned int requested_height, const bool is_variable_width=true) { if (!requested_height) return CImgList<ucharT>::const_empty(); cimg::mutex(11); static const unsigned char font_resizemap[] = { 0, 4, 7, 9, 11, 13, 15, 17, 19, 21, 22, 24, 26, 27, 29, 30, 32, 33, 35, 36, 38, 39, 41, 42, 43, 45, 46, 47, 49, 50, 51, 52, 54, 55, 56, 58, 59, 60, 61, 62, 64, 65, 66, 67, 68, 69, 71, 72, 73, 74, 75, 76, 77, 78, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 157, 158, 159, 160, 161, 162, 163, 164, 164, 165, 166, 167, 168, 169, 170, 170, 171, 172, 173, 174, 175, 176, 176, 177, 178, 179, 180, 181, 181, 182, 183, 184, 185, 186, 186, 187, 188, 189, 190, 191, 191, 192, 193, 194, 195, 196, 196, 197, 198, 199, 200, 200, 201, 202, 203, 204, 205, 205, 206, 207, 208, 209, 209, 210, 211, 212, 213, 213, 214, 215, 216, 216, 217, 218, 219, 220, 220, 221, 222, 223, 224, 224, 225, 226, 227, 227, 228, 229, 230, 231, 231, 232, 233, 234, 234, 235, 236, 237, 238, 238, 239, 240, 241, 241, 242, 243, 244, 244, 245, 246, 247, 247, 248, 249, 250, 250, 251, 252, 253, 253, 254, 255 }; static const char *const *font_data[] = { cimg::data_font_small, cimg::data_font_normal, cimg::data_font_large, cimg::data_font_huge }; static const unsigned int font_width[] = { 10,26,52,104 }, font_height[] = { 13,32,64,128 }, font_M[] = { 86,91,91,47 }, font_chunk[] = { sizeof(cimg::data_font_small)/sizeof(char*), sizeof(cimg::data_font_normal)/sizeof(char*), sizeof(cimg::data_font_large)/sizeof(char*), sizeof(cimg::data_font_huge)/sizeof(char*) }; static const unsigned char font_is_binary[] = { 1,0,0,1 }; static CImg<ucharT> font_base[4]; unsigned int ind = requested_height<=font_height[0]?0U: requested_height<=font_height[1]?1U: requested_height<=font_height[2]?2U:3U; // Decompress nearest base font data if needed. CImg<ucharT> &basef = font_base[ind]; if (!basef) { basef.assign(256*font_width[ind],font_height[ind]); unsigned char *ptrd = basef; const unsigned char *const ptrde = basef.end(); // Recompose font data from several chunks, to deal with MS compiler limit with big strings (64 Kb). CImg<char> dataf; for (unsigned int k = 0; k<font_chunk[ind]; ++k) dataf.append(CImg<char>::string(font_data[ind][k],k==font_chunk[ind] - 1,true),'x'); // Uncompress font data (decode RLE). const unsigned int M = font_M[ind]; if (font_is_binary[ind]) for (const char *ptrs = dataf; *ptrs; ++ptrs) { const int _n = (int)(*ptrs - M - 32), v = _n>=0?255:0, n = _n>=0?_n:-_n; if (ptrd + n<=ptrde) { std::memset(ptrd,v,n); ptrd+=n; } else { std::memset(ptrd,v,ptrde - ptrd); break; } } else for (const char *ptrs = dataf; *ptrs; ++ptrs) { int n = (int)*ptrs - M - 32, v = 0; if (n>=0) { v = 85*n; n = 1; } else { n = -n; v = (int)*(++ptrs) - M - 32; if (v<0) { v = 0; --ptrs; } else v*=85; } if (ptrd + n<=ptrde) { std::memset(ptrd,v,n); ptrd+=n; } else { std::memset(ptrd,v,ptrde - ptrd); break; } } } // Find optimal font cache location to return. static CImgList<ucharT> fonts[16]; static bool is_variable_widths[16] = { 0 }; ind = ~0U; for (int i = 0; i<16; ++i) if (!fonts[i] || (is_variable_widths[i]==is_variable_width && requested_height==fonts[i][0]._height)) { ind = (unsigned int)i; break; // Found empty slot or cached font } if (ind==~0U) { // No empty slots nor existing font in cache fonts->assign(); std::memmove(fonts,fonts + 1,15*sizeof(CImgList<ucharT>)); std::memmove(is_variable_widths,is_variable_widths + 1,15*sizeof(bool)); std::memset((void*)(fonts + (ind=15)),0,sizeof(CImgList<ucharT>)); // Free a slot in cache for new font } CImgList<ucharT> &font = fonts[ind]; // Render requested font. if (!font) { const unsigned int padding_x = requested_height<=64?1U:requested_height<=128?2U:3U; is_variable_widths[ind] = is_variable_width; font = basef.get_split('x',256); if (requested_height!=font[0]._height) cimglist_for(font,l) { font[l].resize(std::max(1U,font[l]._width*requested_height/font[l]._height),requested_height,-100,-100, font[0]._height>requested_height?2:5); cimg_for(font[l],ptr,ucharT) *ptr = font_resizemap[*ptr]; } if (is_variable_width) { // Crop font cimglist_for(font,l) { CImg<ucharT>& letter = font[l]; int xmin = letter.width(), xmax = 0; cimg_forXY(letter,x,y) if (letter(x,y)) { if (x<xmin) xmin = x; if (x>xmax) xmax = x; } if (xmin<=xmax) letter.crop(xmin,0,xmax,letter._height - 1); } font[(int)' '].resize(font[(int)'f']._width,-100,-100,-100,0); if (' ' + 256<font.size()) font[' ' + 256].resize(font[(int)'f']._width,-100,-100,-100,0); cimglist_for(font,l) font[l].resize(std::max(font[(int)';']._width,font[l]._width) + padding_x, -100,1,1,0,0,0.55f); } else cimglist_for(font,l) font[l].resize(font[l]._width + padding_x,-100,1,1,0,0,0.55f); font.insert(256,0); cimglist_for_in(font,0,255,l) font[l].assign(font[l + 256]._width,font[l + 256]._height,1,3,1); } cimg::mutex(11,0); return font; } //! Compute a 1D Fast Fourier Transform, along specified axis. /** \param axis Axis along which the Fourier transform is computed. \param invert Tells if the direct (\c false) or inverse transform (\c true) is computed. **/ CImgList<T>& FFT(const char axis, const bool invert=false) { if (is_empty()) return *this; if (_width==1) insert(1); if (_width>2) cimg::warn(_cimglist_instance "FFT(): Instance has more than 2 images", cimglist_instance); CImg<T>::FFT(_data[0],_data[1],axis,invert); return *this; } //! Compute a 1-D Fast Fourier Transform, along specified axis \newinstance. CImgList<Tfloat> get_FFT(const char axis, const bool invert=false) const { return CImgList<Tfloat>(*this,false).FFT(axis,invert); } //! Compute n-D Fast Fourier Transform. /** \param invert Tells if the direct (\c false) or inverse transform (\c true) is computed. **/ CImgList<T>& FFT(const bool invert=false) { if (is_empty()) return *this; if (_width==1) insert(1); if (_width>2) cimg::warn(_cimglist_instance "FFT(): Instance has more than 2 images", cimglist_instance); CImg<T>::FFT(_data[0],_data[1],invert); return *this; } //! Compute n-D Fast Fourier Transform \newinstance. CImgList<Tfloat> get_FFT(const bool invert=false) const { return CImgList<Tfloat>(*this,false).FFT(invert); } //! Reverse primitives orientations of a 3D object. /** **/ CImgList<T>& reverse_object3d() { cimglist_for(*this,l) { CImg<T>& p = _data[l]; switch (p.size()) { case 2 : case 3: cimg::swap(p[0],p[1]); break; case 6 : cimg::swap(p[0],p[1],p[2],p[4],p[3],p[5]); break; case 9 : cimg::swap(p[0],p[1],p[3],p[5],p[4],p[6]); break; case 4 : cimg::swap(p[0],p[1],p[2],p[3]); break; case 12 : cimg::swap(p[0],p[1],p[2],p[3],p[4],p[6],p[5],p[7],p[8],p[10],p[9],p[11]); break; } } return *this; } //! Reverse primitives orientations of a 3D object \newinstance. CImgList<T> get_reverse_object3d() const { return (+*this).reverse_object3d(); } //@} }; // struct CImgList { ... // Completion of previously declared functions //-------------------------------------------- namespace cimg { // Functions to return standard streams 'stdin', 'stdout' and 'stderr'. // (throw a CImgIOException when macro 'cimg_use_r' is defined). inline FILE* _stdin(const bool throw_exception) { #ifndef cimg_use_r cimg::unused(throw_exception); return stdin; #else if (throw_exception) { cimg::exception_mode(0); throw CImgIOException("cimg::stdin(): Reference to 'stdin' stream not allowed in R mode " "('cimg_use_r' is defined)."); } return 0; #endif } inline FILE* _stdout(const bool throw_exception) { #ifndef cimg_use_r cimg::unused(throw_exception); return stdout; #else if (throw_exception) { cimg::exception_mode(0); throw CImgIOException("cimg::stdout(): Reference to 'stdout' stream not allowed in R mode " "('cimg_use_r' is defined)."); } return 0; #endif } inline FILE* _stderr(const bool throw_exception) { #ifndef cimg_use_r cimg::unused(throw_exception); return stderr; #else if (throw_exception) { cimg::exception_mode(0); throw CImgIOException("cimg::stderr(): Reference to 'stderr' stream not allowed in R mode " "('cimg_use_r' is defined)."); } return 0; #endif } // Open a file (similar to std:: fopen(), but with wide character support on Windows). inline std::FILE *std_fopen(const char *const path, const char *const mode) { std::FILE *const res = std::fopen(path,mode); if (res) return res; #if cimg_OS==2 // Try alternative method, with wide-character string. int err = MultiByteToWideChar(CP_UTF8,0,path,-1,0,0); if (err) { CImg<wchar_t> wpath(err); err = MultiByteToWideChar(CP_UTF8,0,path,-1,wpath,err); if (err) { // Convert 'mode' to a wide-character string err = MultiByteToWideChar(CP_UTF8,0,mode,-1,0,0); if (err) { CImg<wchar_t> wmode(err); if (MultiByteToWideChar(CP_UTF8,0,mode,-1,wmode,err)) return _wfopen(wpath,wmode); } } } #endif return 0; } //! Get/set path to store temporary files. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path where temporary files can be saved. **/ inline const char* temporary_path(const char *const user_path, const bool reinit_path) { #define _cimg_test_temporary_path(p) \ if (!path_found) { \ cimg_snprintf(s_path,s_path.width(),"%s",p); \ cimg_snprintf(tmp,tmp._width,"%s%c%s",s_path.data(),cimg_file_separator,filename_tmp._data); \ if ((file=cimg::std_fopen(tmp,"wb"))!=0) { cimg::fclose(file); std::remove(tmp); path_found = true; } \ } static CImg<char> s_path; cimg::mutex(7); if (reinit_path) s_path.assign(); if (user_path) { if (!s_path) s_path.assign(1024); std::strncpy(s_path,user_path,1023); } else if (!s_path) { s_path.assign(1024); bool path_found = false; CImg<char> tmp(1024), filename_tmp(256); std::FILE *file = 0; cimg_snprintf(filename_tmp,filename_tmp._width,"%s.tmp",cimg::filenamerand()); char *tmpPath = std::getenv("TMP"); if (!tmpPath) { tmpPath = std::getenv("TEMP"); winformat_string(tmpPath); } if (tmpPath) _cimg_test_temporary_path(tmpPath); #if cimg_OS==2 _cimg_test_temporary_path("C:\\WINNT\\Temp"); _cimg_test_temporary_path("C:\\WINDOWS\\Temp"); _cimg_test_temporary_path("C:\\Temp"); _cimg_test_temporary_path("C:"); _cimg_test_temporary_path("D:\\WINNT\\Temp"); _cimg_test_temporary_path("D:\\WINDOWS\\Temp"); _cimg_test_temporary_path("D:\\Temp"); _cimg_test_temporary_path("D:"); #else _cimg_test_temporary_path("/tmp"); _cimg_test_temporary_path("/var/tmp"); #endif if (!path_found) { *s_path = 0; std::strncpy(tmp,filename_tmp,tmp._width - 1); if ((file=cimg::std_fopen(tmp,"wb"))!=0) { cimg::fclose(file); std::remove(tmp); path_found = true; } } if (!path_found) { cimg::mutex(7,0); throw CImgIOException("cimg::temporary_path(): Failed to locate path for writing temporary files.\n"); } } cimg::mutex(7,0); return s_path; } //! Get/set path to the <i>Program Files/</i> directory (Windows only). /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the program files. **/ #if cimg_OS==2 inline const char* programfiles_path(const char *const user_path, const bool reinit_path) { static CImg<char> s_path; cimg::mutex(7); if (reinit_path) s_path.assign(); if (user_path) { if (!s_path) s_path.assign(1024); std::strncpy(s_path,user_path,1023); } else if (!s_path) { s_path.assign(MAX_PATH); *s_path = 0; // Note: in the following line, 0x26 = CSIDL_PROGRAM_FILES (not defined on every compiler). #if !defined(__INTEL_COMPILER) if (!SHGetSpecialFolderPathA(0,s_path,0x0026,false)) { const char *const pfPath = std::getenv("PROGRAMFILES"); if (pfPath) std::strncpy(s_path,pfPath,MAX_PATH - 1); else std::strcpy(s_path,"C:\\PROGRA~1"); } #else std::strcpy(s_path,"C:\\PROGRA~1"); #endif } cimg::mutex(7,0); return s_path; } #endif //! Get/set path to the ImageMagick's \c convert binary. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the \c convert binary. **/ inline const char* imagemagick_path(const char *const user_path, const bool reinit_path) { static CImg<char> s_path; cimg::mutex(7); if (reinit_path) s_path.assign(); if (user_path) { if (!s_path) s_path.assign(1024); std::strncpy(s_path,user_path,1023); } else if (!s_path) { s_path.assign(1024); bool path_found = false; std::FILE *file = 0; #if cimg_OS==2 const char *const pf_path = programfiles_path(); for (int l = 0; l<2 && !path_found; ++l) { const char *const s_exe = l?"convert":"magick"; cimg_snprintf(s_path,s_path._width,".\\%s.exe",s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"%s\\IMAGEM~1.%.2d-\\%s.exe",pf_path,k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"%s\\IMAGEM~1.%d-Q\\%s.exe",pf_path,k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"%s\\IMAGEM~1.%d\\%s.exe",pf_path,k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"%s\\IMAGEM~1.%.2d-\\VISUA~1\\BIN\\%s.exe",pf_path,k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"%s\\IMAGEM~1.%d-Q\\VISUA~1\\BIN\\%s.exe",pf_path,k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"%s\\IMAGEM~1.%d\\VISUA~1\\BIN\\%s.exe",pf_path,k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"C:\\IMAGEM~1.%.2d-\\%s.exe",k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"C:\\IMAGEM~1.%d-Q\\%s.exe",k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"C:\\IMAGEM~1.%d\\%s.exe",k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"C:\\IMAGEM~1.%.2d-\\VISUA~1\\BIN\\%s.exe",k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"C:\\IMAGEM~1.%d-Q\\VISUA~1\\BIN\\%s.exe",k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"C:\\IMAGEM~1.%d\\VISUA~1\\BIN\\%s.exe",k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"D:\\IMAGEM~1.%.2d-\\%s.exe",k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"D:\\IMAGEM~1.%d-Q\\%s.exe",k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"D:\\IMAGEM~1.%d\\%s.exe",k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"D:\\IMAGEM~1.%.2d-\\VISUA~1\\BIN\\%s.exe",k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"D:\\IMAGEM~1.%d-Q\\VISUA~1\\BIN\\%s.exe",k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"D:\\IMAGEM~1.%d\\VISUA~1\\BIN\\%s.exe",k,s_exe); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) cimg_snprintf(s_path,s_path._width,"%s.exe",s_exe); } #else std::strcpy(s_path,"./magick"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } if (!path_found) { std::strcpy(s_path,"./convert"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"convert"); #endif winformat_string(s_path); } cimg::mutex(7,0); return s_path; } //! Get/set path to the GraphicsMagick's \c gm binary. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the \c gm binary. **/ inline const char* graphicsmagick_path(const char *const user_path, const bool reinit_path) { static CImg<char> s_path; cimg::mutex(7); if (reinit_path) s_path.assign(); if (user_path) { if (!s_path) s_path.assign(1024); std::strncpy(s_path,user_path,1023); } else if (!s_path) { s_path.assign(1024); bool path_found = false; std::FILE *file = 0; #if cimg_OS==2 const char *const pf_path = programfiles_path(); if (!path_found) { std::strcpy(s_path,".\\gm.exe"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"%s\\GRAPHI~1.%.2d-\\gm.exe",pf_path,k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"%s\\GRAPHI~1.%d-Q\\gm.exe",pf_path,k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"%s\\GRAPHI~1.%d\\gm.exe",pf_path,k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"%s\\GRAPHI~1.%.2d-\\VISUA~1\\BIN\\gm.exe",pf_path,k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"%s\\GRAPHI~1.%d-Q\\VISUA~1\\BIN\\gm.exe",pf_path,k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"%s\\GRAPHI~1.%d\\VISUA~1\\BIN\\gm.exe",pf_path,k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"C:\\GRAPHI~1.%.2d-\\gm.exe",k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"C:\\GRAPHI~1.%d-Q\\gm.exe",k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"C:\\GRAPHI~1.%d\\gm.exe",k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"C:\\GRAPHI~1.%.2d-\\VISUA~1\\BIN\\gm.exe",k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"C:\\GRAPHI~1.%d-Q\\VISUA~1\\BIN\\gm.exe",k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"C:\\GRAPHI~1.%d\\VISUA~1\\BIN\\gm.exe",k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"D:\\GRAPHI~1.%.2d-\\gm.exe",k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"D:\\GRAPHI~1.%d-Q\\gm.exe",k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"D:\\GRAPHI~1.%d\\gm.exe",k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"D:\\GRAPHI~1.%.2d-\\VISUA~1\\BIN\\gm.exe",k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"D:\\GRAPHI~1.%d-Q\\VISUA~1\\BIN\\gm.exe",k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(s_path,s_path._width,"D:\\GRAPHI~1.%d\\VISUA~1\\BIN\\gm.exe",k); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"gm.exe"); #else if (!path_found) { std::strcpy(s_path,"./gm"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"gm"); #endif winformat_string(s_path); } cimg::mutex(7,0); return s_path; } //! Get/set path to the XMedcon's \c medcon binary. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the \c medcon binary. **/ inline const char* medcon_path(const char *const user_path, const bool reinit_path) { static CImg<char> s_path; cimg::mutex(7); if (reinit_path) s_path.assign(); if (user_path) { if (!s_path) s_path.assign(1024); std::strncpy(s_path,user_path,1023); } else if (!s_path) { s_path.assign(1024); bool path_found = false; std::FILE *file = 0; #if cimg_OS==2 const char *const pf_path = programfiles_path(); if (!path_found) { std::strcpy(s_path,".\\medcon.exe"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) { cimg_snprintf(s_path,s_path._width,"%s\\XMedCon\\bin\\medcon.bat",pf_path); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) { cimg_snprintf(s_path,s_path._width,"%s\\XMedCon\\bin\\medcon.exe",pf_path); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) { std::strcpy(s_path,"C:\\XMedCon\\bin\\medcon.exe"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"medcon.exe"); #else if (!path_found) { std::strcpy(s_path,"./medcon"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"medcon"); #endif winformat_string(s_path); } cimg::mutex(7,0); return s_path; } //! Get/set path to the FFMPEG's \c ffmpeg binary. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the \c ffmpeg binary. **/ inline const char *ffmpeg_path(const char *const user_path, const bool reinit_path) { static CImg<char> s_path; cimg::mutex(7); if (reinit_path) s_path.assign(); if (user_path) { if (!s_path) s_path.assign(1024); std::strncpy(s_path,user_path,1023); } else if (!s_path) { s_path.assign(1024); bool path_found = false; std::FILE *file = 0; #if cimg_OS==2 if (!path_found) { std::strcpy(s_path,".\\ffmpeg.exe"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"ffmpeg.exe"); #else if (!path_found) { std::strcpy(s_path,"./ffmpeg"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"ffmpeg"); #endif winformat_string(s_path); } cimg::mutex(7,0); return s_path; } //! Get/set path to the \c gzip binary. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the \c gzip binary. **/ inline const char *gzip_path(const char *const user_path, const bool reinit_path) { static CImg<char> s_path; cimg::mutex(7); if (reinit_path) s_path.assign(); if (user_path) { if (!s_path) s_path.assign(1024); std::strncpy(s_path,user_path,1023); } else if (!s_path) { s_path.assign(1024); bool path_found = false; std::FILE *file = 0; #if cimg_OS==2 if (!path_found) { std::strcpy(s_path,".\\gzip.exe"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"gzip.exe"); #else if (!path_found) { std::strcpy(s_path,"./gzip"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"gzip"); #endif winformat_string(s_path); } cimg::mutex(7,0); return s_path; } //! Get/set path to the \c gunzip binary. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the \c gunzip binary. **/ inline const char *gunzip_path(const char *const user_path, const bool reinit_path) { static CImg<char> s_path; cimg::mutex(7); if (reinit_path) s_path.assign(); if (user_path) { if (!s_path) s_path.assign(1024); std::strncpy(s_path,user_path,1023); } else if (!s_path) { s_path.assign(1024); bool path_found = false; std::FILE *file = 0; #if cimg_OS==2 if (!path_found) { std::strcpy(s_path,".\\gunzip.exe"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"gunzip.exe"); #else if (!path_found) { std::strcpy(s_path,"./gunzip"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"gunzip"); #endif winformat_string(s_path); } cimg::mutex(7,0); return s_path; } //! Get/set path to the \c dcraw binary. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the \c dcraw binary. **/ inline const char *dcraw_path(const char *const user_path, const bool reinit_path) { static CImg<char> s_path; cimg::mutex(7); if (reinit_path) s_path.assign(); if (user_path) { if (!s_path) s_path.assign(1024); std::strncpy(s_path,user_path,1023); } else if (!s_path) { s_path.assign(1024); bool path_found = false; std::FILE *file = 0; #if cimg_OS==2 if (!path_found) { std::strcpy(s_path,".\\dcraw.exe"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"dcraw.exe"); #else if (!path_found) { std::strcpy(s_path,"./dcraw"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"dcraw"); #endif winformat_string(s_path); } cimg::mutex(7,0); return s_path; } //! Get/set path to the \c wget binary. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the \c wget binary. **/ inline const char *wget_path(const char *const user_path, const bool reinit_path) { static CImg<char> s_path; cimg::mutex(7); if (reinit_path) s_path.assign(); if (user_path) { if (!s_path) s_path.assign(1024); std::strncpy(s_path,user_path,1023); } else if (!s_path) { s_path.assign(1024); bool path_found = false; std::FILE *file = 0; #if cimg_OS==2 if (!path_found) { std::strcpy(s_path,".\\wget.exe"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"wget.exe"); #else if (!path_found) { std::strcpy(s_path,"./wget"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"wget"); #endif winformat_string(s_path); } cimg::mutex(7,0); return s_path; } //! Get/set path to the \c curl binary. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the \c curl binary. **/ inline const char *curl_path(const char *const user_path, const bool reinit_path) { static CImg<char> s_path; cimg::mutex(7); if (reinit_path) s_path.assign(); if (user_path) { if (!s_path) s_path.assign(1024); std::strncpy(s_path,user_path,1023); } else if (!s_path) { s_path.assign(1024); bool path_found = false; std::FILE *file = 0; #if cimg_OS==2 if (!path_found) { std::strcpy(s_path,".\\curl.exe"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"curl.exe"); #else if (!path_found) { std::strcpy(s_path,"./curl"); if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(s_path,"curl"); #endif winformat_string(s_path); } cimg::mutex(7,0); return s_path; } // [internal] Sorting function, used by cimg::files(). inline int _sort_files(const void* a, const void* b) { const CImg<char> &sa = *(CImg<char>*)a, &sb = *(CImg<char>*)b; return std::strcmp(sa._data,sb._data); } //! Return list of files/directories in specified directory. /** \param path Path to the directory. Set to 0 for current directory. \param is_pattern Tell if specified path has a matching pattern in it. \param mode Output type, can be primary { 0=files only | 1=folders only | 2=files + folders }. \param include_path Tell if \c path must be included in resulting filenames. \return A list of filenames. **/ inline CImgList<char> files(const char *const path, const bool is_pattern=false, const unsigned int mode=2, const bool include_path=false) { if (!path || !*path) return files("*",true,mode,include_path); CImgList<char> res; // If path is a valid folder name, ignore argument 'is_pattern'. const bool _is_pattern = is_pattern && !cimg::is_directory(path); bool is_root = false, is_current = false; cimg::unused(is_root,is_current); // Clean format of input path. CImg<char> pattern, _path = CImg<char>::string(path); #if cimg_OS==2 for (char *ps = _path; *ps; ++ps) if (*ps=='\\') *ps='/'; #endif char *pd = _path; for (char *ps = pd; *ps; ++ps) { if (*ps!='/' || *ps!=*(ps+1)) *(pd++) = *ps; } *pd = 0; unsigned int lp = (unsigned int)std::strlen(_path); if (!_is_pattern && lp && _path[lp - 1]=='/') { _path[lp - 1] = 0; --lp; #if cimg_OS!=2 is_root = !*_path; #endif } // Separate folder path and matching pattern. if (_is_pattern) { const unsigned int bpos = (unsigned int)(cimg::basename(_path,'/') - _path.data()); CImg<char>::string(_path).move_to(pattern); if (bpos) { _path[bpos - 1] = 0; // End 'path' at last slash #if cimg_OS!=2 is_root = !*_path; #endif } else { // No path to folder specified, assuming current folder is_current = true; *_path = 0; } lp = (unsigned int)std::strlen(_path); } // Windows version. #if cimg_OS==2 if (!_is_pattern) { pattern.assign(lp + 3); std::memcpy(pattern,_path,lp); pattern[lp] = '/'; pattern[lp + 1] = '*'; pattern[lp + 2] = 0; } WIN32_FIND_DATAA file_data; const HANDLE dir = FindFirstFileA(pattern.data(),&file_data); if (dir==INVALID_HANDLE_VALUE) return CImgList<char>::const_empty(); do { const char *const filename = file_data.cFileName; if (*filename!='.' || (filename[1] && (filename[1]!='.' || filename[2]))) { const unsigned int lf = (unsigned int)std::strlen(filename); const bool is_directory = (file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)!=0; if ((!mode && !is_directory) || (mode==1 && is_directory) || mode>=2) { if (include_path) { CImg<char> full_filename((lp?lp+1:0) + lf + 1); if (lp) { std::memcpy(full_filename,_path,lp); full_filename[lp] = '/'; } std::memcpy(full_filename._data + (lp?lp + 1:0),filename,lf + 1); full_filename.move_to(res); } else CImg<char>(filename,lf + 1).move_to(res); } } } while (FindNextFileA(dir,&file_data)); FindClose(dir); // Unix version (posix). #elif cimg_OS == 1 DIR *const dir = opendir(is_root?"/":is_current?".":_path.data()); if (!dir) return CImgList<char>::const_empty(); struct dirent *ent; while ((ent=readdir(dir))!=0) { const char *const filename = ent->d_name; if (*filename!='.' || (filename[1] && (filename[1]!='.' || filename[2]))) { const unsigned int lf = (unsigned int)std::strlen(filename); CImg<char> full_filename(lp + lf + 2); if (!is_current) { full_filename.assign(lp + lf + 2); if (lp) std::memcpy(full_filename,_path,lp); full_filename[lp] = '/'; std::memcpy(full_filename._data + lp + 1,filename,lf + 1); } else full_filename.assign(filename,lf + 1); struct stat st; if (stat(full_filename,&st)==-1) continue; const bool is_directory = (st.st_mode & S_IFDIR)!=0; if ((!mode && !is_directory) || (mode==1 && is_directory) || mode==2) { if (include_path) { if (!_is_pattern || (_is_pattern && !fnmatch(pattern,full_filename,0))) full_filename.move_to(res); } else { if (!_is_pattern || (_is_pattern && !fnmatch(pattern,full_filename,0))) CImg<char>(filename,lf + 1).move_to(res); } } } } closedir(dir); #endif // Sort resulting list by lexicographic order. if (res._width>=2) std::qsort(res._data,res._width,sizeof(CImg<char>),_sort_files); return res; } //! Try to guess format from an image file. /** \param file Input file (can be \c 0 if \c filename is set). \param filename Filename, as a C-string (can be \c 0 if \c file is set). \return C-string containing the guessed file format, or \c 0 if nothing has been guessed. **/ inline const char *ftype(std::FILE *const file, const char *const filename) { if (!file && !filename) throw CImgArgumentException("cimg::ftype(): Specified filename is (null)."); static const char *const _pnm = "pnm", *const _pfm = "pfm", *const _bmp = "bmp", *const _gif = "gif", *const _jpg = "jpg", *const _off = "off", *const _pan = "pan", *const _png = "png", *const _tif = "tif", *const _inr = "inr", *const _dcm = "dcm"; const char *f_type = 0; CImg<char> header; const unsigned int omode = cimg::exception_mode(); cimg::exception_mode(0); try { header._load_raw(file,filename,512,1,1,1,false,false,0); const unsigned char *const uheader = (unsigned char*)header._data; if (!std::strncmp(header,"OFF\n",4)) f_type = _off; // OFF else if (!std::strncmp(header,"#INRIMAGE",9)) // INRIMAGE f_type = _inr; else if (!std::strncmp(header,"PANDORE",7)) // PANDORE f_type = _pan; else if (!std::strncmp(header.data() + 128,"DICM",4)) // DICOM f_type = _dcm; else if (uheader[0]==0xFF && uheader[1]==0xD8 && uheader[2]==0xFF) // JPEG f_type = _jpg; else if (header[0]=='B' && header[1]=='M') // BMP f_type = _bmp; else if (header[0]=='G' && header[1]=='I' && header[2]=='F' && header[3]=='8' && header[5]=='a' && (header[4]=='7' || header[4]=='9')) // GIF f_type = _gif; else if (uheader[0]==0x89 && uheader[1]==0x50 && uheader[2]==0x4E && uheader[3]==0x47 && uheader[4]==0x0D && uheader[5]==0x0A && uheader[6]==0x1A && uheader[7]==0x0A) // PNG f_type = _png; else if ((uheader[0]==0x49 && uheader[1]==0x49) || (uheader[0]==0x4D && uheader[1]==0x4D)) // TIFF f_type = _tif; else { // PNM or PFM CImgList<char> _header = header.get_split(CImg<char>::vector('\n'),0,false); cimglist_for(_header,l) { if (_header(l,0)=='#') continue; if (_header[l]._height==2 && _header(l,0)=='P') { const char c = _header(l,1); if (c=='f' || c=='F') { f_type = _pfm; break; } if (c>='1' && c<='9') { f_type = _pnm; break; } } f_type = 0; break; } } } catch (CImgIOException&) { } cimg::exception_mode(omode); return f_type; } //! Load file from network as a local temporary file. /** \param url URL of the filename, as a C-string. \param[out] filename_local C-string containing the path to a local copy of \c filename. \param timeout Maximum time (in seconds) authorized for downloading the file from the URL. \param try_fallback When using libcurl, tells using system calls as fallbacks in case of libcurl failure. \param referer Referer used, as a C-string. \return Value of \c filename_local. \note Use the \c libcurl library, or the external binaries \c wget or \c curl to perform the download. **/ inline char *load_network(const char *const url, char *const filename_local, const unsigned int timeout, const bool try_fallback, const char *const referer) { if (!url) throw CImgArgumentException("cimg::load_network(): Specified URL is (null)."); if (!filename_local) throw CImgArgumentException("cimg::load_network(): Specified destination string is (null)."); const char *const __ext = cimg::split_filename(url), *const _ext = (*__ext && __ext>url)?__ext - 1:__ext; CImg<char> ext = CImg<char>::string(_ext); std::FILE *file = 0; *filename_local = 0; if (ext._width>16 || !cimg::strncasecmp(ext,"cgi",3)) *ext = 0; else cimg::strwindows_reserved(ext); do { cimg_snprintf(filename_local,256,"%s%c%s%s", cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),ext._data); if ((file=cimg::std_fopen(filename_local,"rb"))!=0) cimg::fclose(file); } while (file); #ifdef cimg_use_curl const unsigned int omode = cimg::exception_mode(); cimg::exception_mode(0); try { CURL *curl = 0; CURLcode res; curl = curl_easy_init(); if (curl) { file = cimg::fopen(filename_local,"wb"); curl_easy_setopt(curl,CURLOPT_URL,url); curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,0); curl_easy_setopt(curl,CURLOPT_WRITEDATA,file); curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,0L); curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,0L); curl_easy_setopt(curl,CURLOPT_FOLLOWLOCATION,1L); if (timeout) curl_easy_setopt(curl,CURLOPT_TIMEOUT,(long)timeout); if (std::strchr(url,'?')) curl_easy_setopt(curl,CURLOPT_HTTPGET,1L); if (referer) curl_easy_setopt(curl,CURLOPT_REFERER,referer); res = curl_easy_perform(curl); curl_easy_cleanup(curl); cimg::fseek(file,0,SEEK_END); // Check if file size is 0 const cimg_ulong siz = cimg::ftell(file); cimg::fclose(file); if (siz>0 && res==CURLE_OK) { cimg::exception_mode(omode); return filename_local; } else std::remove(filename_local); } } catch (...) { } cimg::exception_mode(omode); if (!try_fallback) throw CImgIOException("cimg::load_network(): Failed to load file '%s' with libcurl.",url); #endif CImg<char> command((unsigned int)std::strlen(url) + 64); cimg::unused(try_fallback); // Try with 'curl' first. if (timeout) { if (referer) cimg_snprintf(command,command._width,"%s -e %s -m %u -f --silent --compressed -o \"%s\" \"%s\"", cimg::curl_path(),referer,timeout,filename_local, CImg<char>::string(url)._system_strescape().data()); else cimg_snprintf(command,command._width,"%s -m %u -f --silent --compressed -o \"%s\" \"%s\"", cimg::curl_path(),timeout,filename_local, CImg<char>::string(url)._system_strescape().data()); } else { if (referer) cimg_snprintf(command,command._width,"%s -e %s -f --silent --compressed -o \"%s\" \"%s\"", cimg::curl_path(),referer,filename_local, CImg<char>::string(url)._system_strescape().data()); else cimg_snprintf(command,command._width,"%s -f --silent --compressed -o \"%s\" \"%s\"", cimg::curl_path(),filename_local, CImg<char>::string(url)._system_strescape().data()); } cimg::system(command); if (!(file=cimg::std_fopen(filename_local,"rb"))) { // Try with 'wget' otherwise. if (timeout) { if (referer) cimg_snprintf(command,command._width,"%s --referer=%s -T %u -q -r -l 0 --no-cache -O \"%s\" \"%s\"", cimg::wget_path(),referer,timeout,filename_local, CImg<char>::string(url)._system_strescape().data()); else cimg_snprintf(command,command._width,"%s -T %u -q -r -l 0 --no-cache -O \"%s\" \"%s\"", cimg::wget_path(),timeout,filename_local, CImg<char>::string(url)._system_strescape().data()); } else { if (referer) cimg_snprintf(command,command._width,"%s --referer=%s -q -r -l 0 --no-cache -O \"%s\" \"%s\"", cimg::wget_path(),referer,filename_local, CImg<char>::string(url)._system_strescape().data()); else cimg_snprintf(command,command._width,"%s -q -r -l 0 --no-cache -O \"%s\" \"%s\"", cimg::wget_path(),filename_local, CImg<char>::string(url)._system_strescape().data()); } cimg::system(command); if (!(file=cimg::std_fopen(filename_local,"rb"))) throw CImgIOException("cimg::load_network(): Failed to load file '%s' with external commands " "'wget' or 'curl'.",url); cimg::fclose(file); // Try gunzip it. cimg_snprintf(command,command._width,"%s.gz",filename_local); std::rename(filename_local,command); cimg_snprintf(command,command._width,"%s --quiet \"%s.gz\"", gunzip_path(),filename_local); cimg::system(command); file = cimg::std_fopen(filename_local,"rb"); if (!file) { cimg_snprintf(command,command._width,"%s.gz",filename_local); std::rename(command,filename_local); file = cimg::std_fopen(filename_local,"rb"); } } cimg::fseek(file,0,SEEK_END); // Check if file size is 0 if (std::ftell(file)<=0) throw CImgIOException("cimg::load_network(): Failed to load URL '%s' with external commands " "'wget' or 'curl'.",url); cimg::fclose(file); return filename_local; } // Implement a tic/toc mechanism to display elapsed time of algorithms. inline cimg_ulong tictoc(const bool is_tic) { cimg::mutex(2); static CImg<cimg_ulong> times(64); static unsigned int pos = 0; const cimg_ulong t1 = cimg::time(); if (is_tic) { // Tic times[pos++] = t1; if (pos>=times._width) throw CImgArgumentException("cimg::tic(): Too much calls to 'cimg::tic()' without calls to 'cimg::toc()'."); cimg::mutex(2,0); return t1; } // Toc if (!pos) throw CImgArgumentException("cimg::toc(): No previous call to 'cimg::tic()' has been made."); const cimg_ulong t0 = times[--pos], dt = t1>=t0?(t1 - t0):cimg::type<cimg_ulong>::max(); const unsigned int edays = (unsigned int)(dt/86400000.), ehours = (unsigned int)((dt - edays*86400000.)/3600000.), emin = (unsigned int)((dt - edays*86400000. - ehours*3600000.)/60000.), esec = (unsigned int)((dt - edays*86400000. - ehours*3600000. - emin*60000.)/1000.), ems = (unsigned int)(dt - edays*86400000. - ehours*3600000. - emin*60000. - esec*1000.); if (!edays && !ehours && !emin && !esec) std::fprintf(cimg::output(),"%s[CImg]%*sElapsed time: %u ms%s\n", cimg::t_red,1 + 2*pos,"",ems,cimg::t_normal); else { if (!edays && !ehours && !emin) std::fprintf(cimg::output(),"%s[CImg]%*sElapsed time: %u sec %u ms%s\n", cimg::t_red,1 + 2*pos,"",esec,ems,cimg::t_normal); else { if (!edays && !ehours) std::fprintf(cimg::output(),"%s[CImg]%*sElapsed time: %u min %u sec %u ms%s\n", cimg::t_red,1 + 2*pos,"",emin,esec,ems,cimg::t_normal); else{ if (!edays) std::fprintf(cimg::output(),"%s[CImg]%*sElapsed time: %u hours %u min %u sec %u ms%s\n", cimg::t_red,1 + 2*pos,"",ehours,emin,esec,ems,cimg::t_normal); else{ std::fprintf(cimg::output(),"%s[CImg]%*sElapsed time: %u days %u hours %u min %u sec %u ms%s\n", cimg::t_red,1 + 2*pos,"",edays,ehours,emin,esec,ems,cimg::t_normal); } } } } cimg::mutex(2,0); return dt; } // Return a temporary string describing the size of a memory buffer. inline const char *strbuffersize(const cimg_ulong size) { static CImg<char> res(256); cimg::mutex(5); if (size<1024LU) cimg_snprintf(res,res._width,"%lu byte%s",(unsigned long)size,size>1?"s":""); else if (size<1024*1024LU) { const float nsize = size/1024.f; cimg_snprintf(res,res._width,"%.1f Kio",nsize); } else if (size<1024*1024*1024LU) { const float nsize = size/(1024*1024.f); cimg_snprintf(res,res._width,"%.1f Mio",nsize); } else { const float nsize = size/(1024*1024*1024.f); cimg_snprintf(res,res._width,"%.1f Gio",nsize); } cimg::mutex(5,0); return res; } //! Display a simple dialog box, and wait for the user's response. /** \param title Title of the dialog window. \param msg Main message displayed inside the dialog window. \param button1_label Label of the 1st button. \param button2_label Label of the 2nd button (\c 0 to hide button). \param button3_label Label of the 3rd button (\c 0 to hide button). \param button4_label Label of the 4th button (\c 0 to hide button). \param button5_label Label of the 5th button (\c 0 to hide button). \param button6_label Label of the 6th button (\c 0 to hide button). \param logo Image logo displayed at the left of the main message. \param is_centered Tells if the dialog window must be centered on the screen. \return Index of clicked button (from \c 0 to \c 5), or \c -1 if the dialog window has been closed by the user. \note - Up to 6 buttons can be defined in the dialog window. - The function returns when a user clicked one of the button or closed the dialog window. - If a button text is set to 0, the corresponding button (and the followings) will not appear in the dialog box. At least one button must be specified. **/ template<typename t> inline int dialog(const char *const title, const char *const msg, const char *const button1_label, const char *const button2_label, const char *const button3_label, const char *const button4_label, const char *const button5_label, const char *const button6_label, const CImg<t>& logo, const bool is_centered=false) { #if cimg_display==0 cimg::unused(title,msg,button1_label,button2_label,button3_label,button4_label,button5_label,button6_label, logo._data,is_centered); throw CImgIOException("cimg::dialog(): No display available."); #else static const unsigned char black[] = { 0,0,0 }, white[] = { 255,255,255 }, gray[] = { 200,200,200 }, gray2[] = { 150,150,150 }; // Create buttons and canvas graphics CImgList<unsigned char> buttons, cbuttons, sbuttons; if (button1_label) { CImg<unsigned char>().draw_text(0,0,button1_label,black,gray,1,13).move_to(buttons); if (button2_label) { CImg<unsigned char>().draw_text(0,0,button2_label,black,gray,1,13).move_to(buttons); if (button3_label) { CImg<unsigned char>().draw_text(0,0,button3_label,black,gray,1,13).move_to(buttons); if (button4_label) { CImg<unsigned char>().draw_text(0,0,button4_label,black,gray,1,13).move_to(buttons); if (button5_label) { CImg<unsigned char>().draw_text(0,0,button5_label,black,gray,1,13).move_to(buttons); if (button6_label) { CImg<unsigned char>().draw_text(0,0,button6_label,black,gray,1,13).move_to(buttons); }}}}}} if (!buttons._width) throw CImgArgumentException("cimg::dialog(): No buttons have been defined."); cimglist_for(buttons,l) buttons[l].resize(-100,-100,1,3); unsigned int bw = 0, bh = 0; cimglist_for(buttons,l) { bw = std::max(bw,buttons[l]._width); bh = std::max(bh,buttons[l]._height); } bw+=8; bh+=8; if (bw<64) bw = 64; if (bw>128) bw = 128; if (bh<24) bh = 24; if (bh>48) bh = 48; CImg<unsigned char> button(bw,bh,1,3); button.draw_rectangle(0,0,bw - 1,bh - 1,gray); button.draw_line(0,0,bw - 1,0,white).draw_line(0,bh - 1,0,0,white); button.draw_line(bw - 1,0,bw - 1,bh - 1,black).draw_line(bw - 1,bh - 1,0,bh - 1,black); button.draw_line(1,bh - 2,bw - 2,bh - 2,gray2).draw_line(bw - 2,bh - 2,bw - 2,1,gray2); CImg<unsigned char> sbutton(bw,bh,1,3); sbutton.draw_rectangle(0,0,bw - 1,bh - 1,gray); sbutton.draw_line(0,0,bw - 1,0,black).draw_line(bw - 1,0,bw - 1,bh - 1,black); sbutton.draw_line(bw - 1,bh - 1,0,bh - 1,black).draw_line(0,bh - 1,0,0,black); sbutton.draw_line(1,1,bw - 2,1,white).draw_line(1,bh - 2,1,1,white); sbutton.draw_line(bw - 2,1,bw - 2,bh - 2,black).draw_line(bw - 2,bh - 2,1,bh - 2,black); sbutton.draw_line(2,bh - 3,bw - 3,bh - 3,gray2).draw_line(bw - 3,bh - 3,bw - 3,2,gray2); sbutton.draw_line(4,4,bw - 5,4,black,1,0xAAAAAAAA,true). draw_line(bw - 5,4,bw - 5,bh - 5,black,1,0xAAAAAAAA,false); sbutton.draw_line(bw - 5,bh - 5,4,bh - 5,black,1,0xAAAAAAAA,false). draw_line(4,bh - 5,4,4,black,1,0xAAAAAAAA,false); CImg<unsigned char> cbutton(bw,bh,1,3); cbutton.draw_rectangle(0,0,bw - 1,bh - 1,black).draw_rectangle(1,1,bw - 2,bh - 2,gray2). draw_rectangle(2,2,bw - 3,bh - 3,gray); cbutton.draw_line(4,4,bw - 5,4,black,1,0xAAAAAAAA,true). draw_line(bw - 5,4,bw - 5,bh - 5,black,1,0xAAAAAAAA,false); cbutton.draw_line(bw - 5,bh - 5,4,bh - 5,black,1,0xAAAAAAAA,false). draw_line(4,bh - 5,4,4,black,1,0xAAAAAAAA,false); cimglist_for(buttons,ll) { CImg<unsigned char>(cbutton). draw_image(1 + (bw -buttons[ll].width())/2,1 + (bh - buttons[ll].height())/2,buttons[ll]). move_to(cbuttons); CImg<unsigned char>(sbutton). draw_image((bw - buttons[ll].width())/2,(bh - buttons[ll].height())/2,buttons[ll]). move_to(sbuttons); CImg<unsigned char>(button). draw_image((bw - buttons[ll].width())/2,(bh - buttons[ll].height())/2,buttons[ll]). move_to(buttons[ll]); } CImg<unsigned char> canvas; if (msg) ((CImg<unsigned char>().draw_text(0,0,"%s",gray,0,1,13,msg)*=-1)+=200).resize(-100,-100,1,3).move_to(canvas); const unsigned int bwall = (buttons._width - 1)*(12 + bw) + bw, w = cimg::max(196U,36 + logo._width + canvas._width,24 + bwall), h = cimg::max(96U,36 + canvas._height + bh,36 + logo._height + bh), lx = 12 + (canvas._data?0:((w - 24 - logo._width)/2)), ly = (h - 12 - bh - logo._height)/2, tx = lx + logo._width + 12, ty = (h - 12 - bh - canvas._height)/2, bx = (w - bwall)/2, by = h - 12 - bh; if (canvas._data) canvas = CImg<unsigned char>(w,h,1,3). draw_rectangle(0,0,w - 1,h - 1,gray). draw_line(0,0,w - 1,0,white).draw_line(0,h - 1,0,0,white). draw_line(w - 1,0,w - 1,h - 1,black).draw_line(w - 1,h - 1,0,h - 1,black). draw_image(tx,ty,canvas); else canvas = CImg<unsigned char>(w,h,1,3). draw_rectangle(0,0,w - 1,h - 1,gray). draw_line(0,0,w - 1,0,white).draw_line(0,h - 1,0,0,white). draw_line(w - 1,0,w - 1,h - 1,black).draw_line(w - 1,h - 1,0,h - 1,black); if (logo._data) canvas.draw_image(lx,ly,logo); unsigned int xbuttons[6] = { 0 }; cimglist_for(buttons,lll) { xbuttons[lll] = bx + (bw + 12)*lll; canvas.draw_image(xbuttons[lll],by,buttons[lll]); } // Open window and enter events loop CImgDisplay disp(canvas,title?title:" ",0,false,is_centered?true:false); if (is_centered) disp.move((CImgDisplay::screen_width() - disp.width())/2, (CImgDisplay::screen_height() - disp.height())/2); bool stop_flag = false, refresh = false; int oselected = -1, oclicked = -1, selected = -1, clicked = -1; while (!disp.is_closed() && !stop_flag) { if (refresh) { if (clicked>=0) CImg<unsigned char>(canvas).draw_image(xbuttons[clicked],by,cbuttons[clicked]).display(disp); else { if (selected>=0) CImg<unsigned char>(canvas).draw_image(xbuttons[selected],by,sbuttons[selected]).display(disp); else canvas.display(disp); } refresh = false; } disp.wait(15); if (disp.is_resized()) disp.resize(disp,false); if (disp.button()&1) { oclicked = clicked; clicked = -1; cimglist_for(buttons,l) if (disp.mouse_y()>=(int)by && disp.mouse_y()<(int)(by + bh) && disp.mouse_x()>=(int)xbuttons[l] && disp.mouse_x()<(int)(xbuttons[l] + bw)) { clicked = selected = l; refresh = true; } if (clicked!=oclicked) refresh = true; } else if (clicked>=0) stop_flag = true; if (disp.key()) { oselected = selected; switch (disp.key()) { case cimg::keyESC : selected = -1; stop_flag = true; break; case cimg::keyENTER : if (selected<0) selected = 0; stop_flag = true; break; case cimg::keyTAB : case cimg::keyARROWRIGHT : case cimg::keyARROWDOWN : selected = (selected + 1)%buttons.width(); break; case cimg::keyARROWLEFT : case cimg::keyARROWUP : selected = (selected + buttons.width() - 1)%buttons.width(); break; } disp.set_key(); if (selected!=oselected) refresh = true; } } if (!disp) selected = -1; return selected; #endif } //! Display a simple dialog box, and wait for the user's response \specialization. inline int dialog(const char *const title, const char *const msg, const char *const button1_label, const char *const button2_label, const char *const button3_label, const char *const button4_label, const char *const button5_label, const char *const button6_label, const bool is_centered) { return dialog(title,msg,button1_label,button2_label,button3_label,button4_label,button5_label,button6_label, CImg<unsigned char>::_logo40x38(),is_centered); } //! Evaluate math expression. /** \param expression C-string describing the formula to evaluate. \param x Value of the pre-defined variable \c x. \param y Value of the pre-defined variable \c y. \param z Value of the pre-defined variable \c z. \param c Value of the pre-defined variable \c c. \return Result of the formula evaluation. \note Set \c expression to \c 0 to keep evaluating the last specified \c expression. \par Example \code const double res1 = cimg::eval("cos(x)^2 + sin(y)^2",2,2), // will return '1' res2 = cimg::eval(0,1,1); // will return '1' too \endcode **/ inline double eval(const char *const expression, const double x, const double y, const double z, const double c) { static const CImg<float> empty; return empty.eval(expression,x,y,z,c); } template<typename t> inline CImg<typename cimg::superset<double,t>::type> eval(const char *const expression, const CImg<t>& xyzc) { static const CImg<float> empty; return empty.eval(expression,xyzc); } } // namespace cimg { ... } // namespace cimg_library { ... //! Short alias name. namespace cil = cimg_library_suffixed; #ifdef _cimg_redefine_False #define False 0 #endif #ifdef _cimg_redefine_True #define True 1 #endif #ifdef _cimg_redefine_Status #define Status int #endif #ifdef _cimg_redefine_Success #define Success 0 #endif #ifdef _cimg_redefine_min #define min(a,b) (((a)<(b))?(a):(b)) #endif #ifdef _cimg_redefine_max #define max(a,b) (((a)>(b))?(a):(b)) #endif #ifdef _cimg_redefine_PI #define PI 3.141592653589793238462643383 #endif #ifdef _MSC_VER #pragma warning(pop) #endif #endif // Local Variables: // mode: c++ // End:
null
131
CWE-787
CVE-2019-14323
/* SSDP responder * * Copyright (c) 2017 Joachim Nilsson <troglobit@gmail.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.a */ #include <config.h> #include <ctype.h> #include <err.h> #include <errno.h> #include <getopt.h> #include <ifaddrs.h> #include <netdb.h> #include <paths.h> #include <poll.h> #include <stdio.h> #include <signal.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include <arpa/inet.h> #include <netinet/ip.h> #include <netinet/udp.h> #include <sys/param.h> /* MIN() */ #include <sys/socket.h> #include "ssdp.h" #include "queue.h" struct ifsock { LIST_ENTRY(ifsock) link; int stale; int mod; /* * Sockets for inbound and outbound * * - The inbound is the multicast socket, shared between all ifaces * - The outbound is bound to the iface address and a random port */ int in, out; /* Interface address and netmask */ struct sockaddr_in addr; struct sockaddr_in mask; void (*cb)(int); }; LIST_HEAD(, ifsock) il = LIST_HEAD_INITIALIZER(); static char *supported_types[] = { SSDP_ST_ALL, "upnp:rootdevice", "urn:schemas-upnp-org:device:InternetGatewayDevice:1", uuid, NULL }; int debug = 0; int running = 1; char uuid[42]; char hostname[64]; char *os = NULL, *ver = NULL; char server_string[64] = "POSIX UPnP/1.0 " PACKAGE_NAME "/" PACKAGE_VERSION; /* Find interface in same subnet as sa */ static struct ifsock *find_outbound(struct sockaddr *sa) { in_addr_t cand; struct ifsock *ifs; struct sockaddr_in *addr = (struct sockaddr_in *)sa; cand = addr->sin_addr.s_addr; LIST_FOREACH(ifs, &il, link) { in_addr_t a, m; a = ifs->addr.sin_addr.s_addr; m = ifs->mask.sin_addr.s_addr; if (a == htonl(INADDR_ANY) || m == htonl(INADDR_ANY)) continue; if ((a & m) == (cand & m)) return ifs; } return NULL; } /* Exact match, must be same ifaddr as sa */ static struct ifsock *find_iface(struct sockaddr *sa) { struct ifsock *ifs; struct sockaddr_in *addr = (struct sockaddr_in *)sa; if (!sa) return NULL; LIST_FOREACH(ifs, &il, link) { if (ifs->addr.sin_addr.s_addr == addr->sin_addr.s_addr) return ifs; } return NULL; } int register_socket(int in, int out, struct sockaddr *addr, struct sockaddr *mask, void (*cb)(int sd)) { struct ifsock *ifs; struct sockaddr_in *address = (struct sockaddr_in *)addr; struct sockaddr_in *netmask = (struct sockaddr_in *)mask; ifs = calloc(1, sizeof(*ifs)); if (!ifs) { char *host = inet_ntoa(address->sin_addr); logit(LOG_ERR, "Failed registering host %s socket: %s", host, strerror(errno)); return -1; } ifs->in = in; ifs->out = out; ifs->mod = 1; ifs->cb = cb; ifs->addr = *address; if (mask) ifs->mask = *netmask; LIST_INSERT_HEAD(&il, ifs, link); return 0; } static int open_socket(char *ifname, struct sockaddr *addr, int port) { int sd, val, rc; char loop; struct ip_mreqn mreq; struct sockaddr_in sin, *address = (struct sockaddr_in *)addr; sd = socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); if (sd < 0) return -1; sin.sin_family = AF_INET; sin.sin_port = htons(port); sin.sin_addr = address->sin_addr; if (bind(sd, (struct sockaddr *)&sin, sizeof(sin)) < 0) { close(sd); logit(LOG_ERR, "Failed binding to %s:%d: %s", inet_ntoa(address->sin_addr), port, strerror(errno)); return -1; } #if 0 ENABLE_SOCKOPT(sd, SOL_SOCKET, SO_REUSEADDR); #ifdef SO_REUSEPORT ENABLE_SOCKOPT(sd, SOL_SOCKET, SO_REUSEPORT); #endif #endif memset(&mreq, 0, sizeof(mreq)); mreq.imr_address = address->sin_addr; mreq.imr_multiaddr.s_addr = inet_addr(MC_SSDP_GROUP); if (setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq))) { close(sd); logit(LOG_ERR, "Failed joining group %s: %s", MC_SSDP_GROUP, strerror(errno)); return -1; } val = 2; /* Default 2, but should be configurable */ rc = setsockopt(sd, IPPROTO_IP, IP_MULTICAST_TTL, &val, sizeof(val)); if (rc < 0) { close(sd); logit(LOG_ERR, "Failed setting multicast TTL: %s", strerror(errno)); return -1; } loop = 0; rc = setsockopt(sd, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop)); if (rc < 0) { close(sd); logit(LOG_ERR, "Failed disabing multicast loop: %s", strerror(errno)); return -1; } rc = setsockopt(sd, IPPROTO_IP, IP_MULTICAST_IF, &address->sin_addr, sizeof(address->sin_addr)); if (rc < 0) { close(sd); logit(LOG_ERR, "Failed setting multicast interface: %s", strerror(errno)); return -1; } logit(LOG_DEBUG, "Adding new interface %s with address %s", ifname, inet_ntoa(address->sin_addr)); return sd; } static int close_socket(void) { int ret = 0; struct ifsock *ifs, *tmp; LIST_FOREACH_SAFE(ifs, &il, link, tmp) { LIST_REMOVE(ifs, link); if (ifs->out != -1) ret |= close(ifs->out); else ret |= close(ifs->in); free(ifs); } return ret; } static int filter_addr(struct sockaddr *sa) { struct ifsock *ifs; struct sockaddr_in *sin = (struct sockaddr_in *)sa; if (!sa) return 1; if (sa->sa_family != AF_INET) return 1; if (sin->sin_addr.s_addr == htonl(INADDR_ANY)) return 1; if (sin->sin_addr.s_addr == htonl(INADDR_LOOPBACK)) return 1; ifs = find_outbound(sa); if (ifs) { if (ifs->addr.sin_addr.s_addr != htonl(INADDR_ANY)) return 1; } return 0; } static int filter_iface(char *ifname, char *iflist[], size_t num) { size_t i; if (!num) { logit(LOG_DEBUG, "No interfaces to filter, using all with an IP address."); return 0; } logit(LOG_DEBUG, "Filter %s? Comparing %zd entries ...", ifname, num); for (i = 0; i < num; i++) { logit(LOG_DEBUG, "Filter %s? Comparing with %s ...", ifname, iflist[i]); if (!strcmp(ifname, iflist[i])) return 0; } return 1; } static void compose_addr(struct sockaddr_in *sin, char *group, int port) { memset(sin, 0, sizeof(*sin)); sin->sin_family = AF_INET; sin->sin_port = htons(port); sin->sin_addr.s_addr = inet_addr(group); } static void compose_response(char *type, char *host, char *buf, size_t len) { char usn[256]; char date[42]; time_t now; /* RFC1123 date, as specified in RFC2616 */ now = time(NULL); strftime(date, sizeof(date), "%a, %d %b %Y %T %Z", gmtime(&now)); if (type) { if (!strcmp(type, uuid)) type = NULL; else snprintf(usn, sizeof(usn), "%s::%s", uuid, type); } if (!type) strncpy(usn, uuid, sizeof(usn)); snprintf(buf, len, "HTTP/1.1 200 OK\r\n" "Server: %s\r\n" "Date: %s\r\n" "Location: http://%s:%d%s\r\n" "ST: %s\r\n" "EXT: \r\n" "USN: %s\r\n" "Cache-Control: max-age=%d\r\n" "\r\n", server_string, date, host, LOCATION_PORT, LOCATION_DESC, type, usn, CACHE_TIMEOUT); } static void compose_search(char *type, char *buf, size_t len) { snprintf(buf, len, "M-SEARCH * HTTP/1.1\r\n" "Host: %s:%d\r\n" "MAN: \"ssdp:discover\"\r\n" "MX: 1\r\n" "ST: %s\r\n" "User-Agent: %s\r\n" "\r\n", MC_SSDP_GROUP, MC_SSDP_PORT, type, server_string); } static void compose_notify(char *type, char *host, char *buf, size_t len) { char usn[256]; if (type) { if (!strcmp(type, SSDP_ST_ALL)) type = NULL; else snprintf(usn, sizeof(usn), "%s::%s", uuid, type); } if (!type) { type = usn; strncpy(usn, uuid, sizeof(usn)); } snprintf(buf, len, "NOTIFY * HTTP/1.1\r\n" "Host: %s:%d\r\n" "Server: %s\r\n" "Location: http://%s:%d%s\r\n" "NT: %s\r\n" "NTS: ssdp:alive\r\n" "USN: %s\r\n" "Cache-Control: max-age=%d\r\n" "\r\n", MC_SSDP_GROUP, MC_SSDP_PORT, server_string, host, LOCATION_PORT, LOCATION_DESC, type, usn, CACHE_TIMEOUT); } size_t pktlen(unsigned char *buf) { size_t hdr = sizeof(struct udphdr); return strlen((char *)buf + hdr) + hdr; } static void send_search(struct ifsock *ifs, char *type) { ssize_t num; char buf[MAX_PKT_SIZE]; struct sockaddr dest; memset(buf, 0, sizeof(buf)); compose_search(type, buf, sizeof(buf)); compose_addr((struct sockaddr_in *)&dest, MC_SSDP_GROUP, MC_SSDP_PORT); logit(LOG_DEBUG, "Sending M-SEARCH ..."); num = sendto(ifs->out, buf, strlen(buf), 0, &dest, sizeof(struct sockaddr_in)); if (num < 0) logit(LOG_WARNING, "Failed sending SSDP M-SEARCH"); } static void send_message(struct ifsock *ifs, char *type, struct sockaddr *sa) { int s; size_t i, len, note = 0; ssize_t num; char host[NI_MAXHOST]; char buf[MAX_PKT_SIZE]; struct sockaddr dest; struct sockaddr_in *sin = (struct sockaddr_in *)sa; gethostname(hostname, sizeof(hostname)); s = getnameinfo((struct sockaddr *)&ifs->addr, sizeof(struct sockaddr_in), host, sizeof(host), NULL, 0, NI_NUMERICHOST); if (s) { logit(LOG_WARNING, "Failed getnameinfo(): %s", gai_strerror(s)); return; } if (ifs->addr.sin_addr.s_addr == htonl(INADDR_ANY)) return; if (ifs->out == -1) return; if (!strcmp(type, SSDP_ST_ALL)) type = NULL; memset(buf, 0, sizeof(buf)); if (sin) compose_response(type, host, buf, sizeof(buf)); else compose_notify(type, host, buf, sizeof(buf)); if (!sin) { note = 1; compose_addr((struct sockaddr_in *)&dest, MC_SSDP_GROUP, MC_SSDP_PORT); sin = (struct sockaddr_in *)&dest; } logit(LOG_DEBUG, "Sending %s from %s ...", !note ? "reply" : "notify", host); num = sendto(ifs->out, buf, strlen(buf), 0, sin, sizeof(struct sockaddr_in)); if (num < 0) logit(LOG_WARNING, "Failed sending SSDP %s, type: %s: %s", !note ? "reply" : "notify", type, strerror(errno)); } static void ssdp_recv(int sd) { ssize_t len; struct sockaddr sa; socklen_t salen; char buf[MAX_PKT_SIZE]; memset(buf, 0, sizeof(buf)); len = recvfrom(sd, buf, sizeof(buf), MSG_DONTWAIT, &sa, &salen); if (len > 0) { buf[len] = 0; if (sa.sa_family != AF_INET) return; if (strstr(buf, "M-SEARCH *")) { size_t i; char *ptr, *type; struct ifsock *ifs; struct sockaddr_in *sin = (struct sockaddr_in *)&sa; ifs = find_outbound(&sa); if (!ifs) { logit(LOG_DEBUG, "No matching socket for client %s", inet_ntoa(sin->sin_addr)); return; } logit(LOG_DEBUG, "Matching socket for client %s", inet_ntoa(sin->sin_addr)); type = strcasestr(buf, "\r\nST:"); if (!type) { logit(LOG_DEBUG, "No Search Type (ST:) found in M-SEARCH *, assuming " SSDP_ST_ALL); type = SSDP_ST_ALL; send_message(ifs, type, &sa); return; } type = strchr(type, ':'); if (!type) return; type++; while (isspace(*type)) type++; ptr = strstr(type, "\r\n"); if (!ptr) return; *ptr = 0; for (i = 0; supported_types[i]; i++) { if (!strcmp(supported_types[i], type)) { logit(LOG_DEBUG, "M-SEARCH * ST: %s from %s port %d", type, inet_ntoa(sin->sin_addr), ntohs(sin->sin_port)); send_message(ifs, type, &sa); return; } } logit(LOG_DEBUG, "M-SEARCH * for unsupported ST: %s from %s", type, inet_ntoa(sin->sin_addr)); } } } static int multicast_init(void) { int sd; struct sockaddr sa; struct sockaddr_in *sin = (struct sockaddr_in *)&sa; sd = socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); if (sd < 0) { logit(LOG_ERR, "Failed opening multicast socket: %s", strerror(errno)); return -1; } memset(&sa, 0, sizeof(sa)); sin->sin_family = AF_INET; sin->sin_addr.s_addr = inet_addr(MC_SSDP_GROUP); sin->sin_port = htons(MC_SSDP_PORT); if (bind(sd, &sa, sizeof(*sin)) < 0) { close(sd); logit(LOG_ERR, "Failed binding to %s:%d: %s", inet_ntoa(sin->sin_addr), MC_SSDP_PORT, strerror(errno)); return -1; } register_socket(sd, -1, &sa, NULL, ssdp_recv); return sd; } static int multicast_join(int sd, struct sockaddr *sa) { struct ip_mreqn mreq; struct sockaddr_in *sin = (struct sockaddr_in *)sa; memset(&mreq, 0, sizeof(mreq)); mreq.imr_address = sin->sin_addr; mreq.imr_multiaddr.s_addr = inet_addr(MC_SSDP_GROUP); if (setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq))) { if (EADDRINUSE == errno) return 0; logit(LOG_ERR, "Failed joining group %s: %s", MC_SSDP_GROUP, strerror(errno)); return -1; } return 0; } static void mark(void) { struct ifsock *ifs; LIST_FOREACH(ifs, &il, link) { if (ifs->out != -1) ifs->stale = 1; else ifs->stale = 0; } } static int sweep(void) { int modified = 0; struct ifsock *ifs, *tmp; LIST_FOREACH_SAFE(ifs, &il, link, tmp) { if (!ifs->stale) continue; modified++; logit(LOG_DEBUG, "Removing stale ifs %s", inet_ntoa(ifs->addr.sin_addr)); LIST_REMOVE(ifs, link); close(ifs->out); free(ifs); } return modified; } static int ssdp_init(int in, char *iflist[], size_t num) { int modified; size_t i; struct ifaddrs *ifaddrs, *ifa; logit(LOG_INFO, "Updating interfaces ..."); if (getifaddrs(&ifaddrs) < 0) { logit(LOG_ERR, "Failed getifaddrs(): %s", strerror(errno)); return -1; } /* Mark all outbound interfaces as stale */ mark(); /* First pass, clear stale marker from exact matches */ for (ifa = ifaddrs; ifa; ifa = ifa->ifa_next) { struct ifsock *ifs; /* Do we already have it? */ ifs = find_iface(ifa->ifa_addr); if (ifs) { ifs->stale = 0; continue; } } /* Clean out any stale interface addresses */ modified = sweep(); /* Second pass, add new ones */ for (ifa = ifaddrs; ifa; ifa = ifa->ifa_next) { int sd; /* Interface filtering, optional command line argument */ if (filter_iface(ifa->ifa_name, iflist, num)) { logit(LOG_DEBUG, "Skipping %s, not in iflist.", ifa->ifa_name); continue; } /* Do we have another in the same subnet? */ if (filter_addr(ifa->ifa_addr)) continue; sd = open_socket(ifa->ifa_name, ifa->ifa_addr, MC_SSDP_PORT); if (sd < 0) continue; multicast_join(in, ifa->ifa_addr); if (register_socket(in, sd, ifa->ifa_addr, ifa->ifa_netmask, ssdp_recv)) { close(sd); break; } modified++; } freeifaddrs(ifaddrs); return modified; } static void handle_message(int sd) { struct ifsock *ifs; LIST_FOREACH(ifs, &il, link) { if (ifs->in != sd) continue; if (ifs->cb) ifs->cb(sd); } } static void wait_message(time_t tmo) { int num = 1, timeout; size_t ifnum = 0; struct pollfd pfd[MAX_NUM_IFACES]; struct ifsock *ifs; LIST_FOREACH(ifs, &il, link) { if (ifs->out != -1) continue; pfd[ifnum].fd = ifs->in; pfd[ifnum].events = POLLIN | POLLHUP; ifnum++; } while (1) { size_t i; timeout = tmo - time(NULL); if (timeout < 0) break; num = poll(pfd, ifnum, timeout * 1000); if (num < 0) { if (EINTR == errno) break; err(1, "Unrecoverable error"); } if (num == 0) break; for (i = 0; num > 0 && i < ifnum; i++) { if (pfd[i].revents & POLLIN) { handle_message(pfd[i].fd); num--; } } } } static void announce(int mod) { struct ifsock *ifs; logit(LOG_INFO, "Sending SSDP NOTIFY new:%d ...", mod); LIST_FOREACH(ifs, &il, link) { size_t i; if (mod && !ifs->mod) continue; ifs->mod = 0; // send_search(ifs, "upnp:rootdevice"); for (i = 0; supported_types[i]; i++) { /* UUID sent in SSDP_ST_ALL, first announce */ if (!strcmp(supported_types[i], uuid)) continue; send_message(ifs, supported_types[i], NULL); } } } static void lsb_init(void) { FILE *fp; char *ptr; char line[80]; const char *file = "/etc/lsb-release"; fp = fopen(file, "r"); if (!fp) { fallback: logit(LOG_WARNING, "No %s found on system, using built-in server string.", file); return; } while (fgets(line, sizeof(line), fp)) { line[strlen(line) - 1] = 0; ptr = strstr(line, "DISTRIB_ID"); if (ptr && (ptr = strchr(ptr, '='))) os = strdup(++ptr); ptr = strstr(line, "DISTRIB_RELEASE"); if (ptr && (ptr = strchr(ptr, '='))) ver = strdup(++ptr); } fclose(fp); if (os && ver) snprintf(server_string, sizeof(server_string), "%s/%s UPnP/1.0 %s/%s", os, ver, PACKAGE_NAME, PACKAGE_VERSION); else goto fallback; logit(LOG_DEBUG, "Server: %s", server_string); } /* https://en.wikipedia.org/wiki/Universally_unique_identifier */ static void uuidgen(void) { FILE *fp; char buf[42]; const char *file = _PATH_VARDB PACKAGE_NAME ".cache"; fp = fopen(file, "r"); if (!fp) { fp = fopen(file, "w"); if (!fp) logit(LOG_WARNING, "Cannot create UUID cache, %s: %s", file, strerror(errno)); generate: srand(time(NULL)); snprintf(buf, sizeof(buf), "uuid:%8.8x-%4.4x-%4.4x-%4.4x-%6.6x%6.6x", rand() & 0xFFFFFFFF, rand() & 0xFFFF, (rand() & 0x0FFF) | 0x4000, /* M 4 MSB version => version 4 */ (rand() & 0x1FFF) | 0x8000, /* N: 3 MSB variant => variant 1 */ rand() & 0xFFFFFF, rand() & 0xFFFFFF); if (fp) { logit(LOG_DEBUG, "Creating new UUID cache file, %s", file); fprintf(fp, "%s\n", buf); fclose(fp); } } else { if (!fgets(buf, sizeof(buf), fp)) { fclose(fp); goto generate; } buf[strlen(buf) - 1] = 0; fclose(fp); } strcpy(uuid, buf); logit(LOG_DEBUG, "URN: %s", uuid); } static void exit_handler(int signo) { (void)signo; running = 0; } static void signal_init(void) { signal(SIGTERM, exit_handler); signal(SIGINT, exit_handler); signal(SIGHUP, exit_handler); signal(SIGQUIT, exit_handler); } static int usage(int code) { printf("Usage: %s [-dhv] [-i SEC] [IFACE [IFACE ...]]\n" "\n" " -d Developer debug mode\n" " -h This help text\n" " -i SEC SSDP notify interval (30-900), default %d sec\n" " -r SEC Interface refresh interval (5-1800), default %d sec\n" " -v Show program version\n" "\n" "Bug report address: %-40s\n", PACKAGE_NAME, NOTIFY_INTERVAL, REFRESH_INTERVAL, PACKAGE_BUGREPORT); return code; } int main(int argc, char *argv[]) { int i, c, sd; int log_level = LOG_NOTICE; int log_opts = LOG_CONS | LOG_PID; int interval = NOTIFY_INTERVAL; int refresh = REFRESH_INTERVAL; time_t now, rtmo = 0, itmo = 0; while ((c = getopt(argc, argv, "dhi:r:v")) != EOF) { switch (c) { case 'd': debug = 1; break; case 'h': return usage(0); case 'i': interval = atoi(optarg); if (interval < 30 || interval > 900) errx(1, "Invalid announcement interval (30-900)."); break; case 'r': refresh = atoi(optarg); if (refresh < 5 || refresh > 1800) errx(1, "Invalid refresh interval (5-1800)."); break; case 'v': puts(PACKAGE_VERSION); return 0; default: break; } } signal_init(); if (debug) { log_level = LOG_DEBUG; log_opts |= LOG_PERROR; } openlog(PACKAGE_NAME, log_opts, LOG_DAEMON); setlogmask(LOG_UPTO(log_level)); uuidgen(); lsb_init(); web_init(); sd = multicast_init(); if (sd < 0) err(1, "Failed creating multicast socket"); while (running) { now = time(NULL); if (rtmo <= now) { if (ssdp_init(sd, &argv[optind], argc - optind) > 0) announce(1); rtmo = now + refresh; } if (itmo <= now) { announce(0); itmo = now + interval; } wait_message(MIN(rtmo, itmo)); } closelog(); return close_socket(); } /** * Local Variables: * indent-tabs-mode: t * c-file-style: "linux" * End: */
null
/* SSDP responder * * Copyright (c) 2017 Joachim Nilsson <troglobit@gmail.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.a */ #include <config.h> #include <ctype.h> #include <err.h> #include <errno.h> #include <getopt.h> #include <ifaddrs.h> #include <netdb.h> #include <paths.h> #include <poll.h> #include <stdio.h> #include <signal.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include <arpa/inet.h> #include <netinet/ip.h> #include <netinet/udp.h> #include <sys/param.h> /* MIN() */ #include <sys/socket.h> #include "ssdp.h" #include "queue.h" struct ifsock { LIST_ENTRY(ifsock) link; int stale; int mod; /* * Sockets for inbound and outbound * * - The inbound is the multicast socket, shared between all ifaces * - The outbound is bound to the iface address and a random port */ int in, out; /* Interface address and netmask */ struct sockaddr_in addr; struct sockaddr_in mask; void (*cb)(int); }; LIST_HEAD(, ifsock) il = LIST_HEAD_INITIALIZER(); static char *supported_types[] = { SSDP_ST_ALL, "upnp:rootdevice", "urn:schemas-upnp-org:device:InternetGatewayDevice:1", uuid, NULL }; int debug = 0; int running = 1; char uuid[42]; char hostname[64]; char *os = NULL, *ver = NULL; char server_string[64] = "POSIX UPnP/1.0 " PACKAGE_NAME "/" PACKAGE_VERSION; /* Find interface in same subnet as sa */ static struct ifsock *find_outbound(struct sockaddr *sa) { in_addr_t cand; struct ifsock *ifs; struct sockaddr_in *addr = (struct sockaddr_in *)sa; cand = addr->sin_addr.s_addr; LIST_FOREACH(ifs, &il, link) { in_addr_t a, m; a = ifs->addr.sin_addr.s_addr; m = ifs->mask.sin_addr.s_addr; if (a == htonl(INADDR_ANY) || m == htonl(INADDR_ANY)) continue; if ((a & m) == (cand & m)) return ifs; } return NULL; } /* Exact match, must be same ifaddr as sa */ static struct ifsock *find_iface(struct sockaddr *sa) { struct ifsock *ifs; struct sockaddr_in *addr = (struct sockaddr_in *)sa; if (!sa) return NULL; LIST_FOREACH(ifs, &il, link) { if (ifs->addr.sin_addr.s_addr == addr->sin_addr.s_addr) return ifs; } return NULL; } int register_socket(int in, int out, struct sockaddr *addr, struct sockaddr *mask, void (*cb)(int sd)) { struct ifsock *ifs; struct sockaddr_in *address = (struct sockaddr_in *)addr; struct sockaddr_in *netmask = (struct sockaddr_in *)mask; ifs = calloc(1, sizeof(*ifs)); if (!ifs) { char *host = inet_ntoa(address->sin_addr); logit(LOG_ERR, "Failed registering host %s socket: %s", host, strerror(errno)); return -1; } ifs->in = in; ifs->out = out; ifs->mod = 1; ifs->cb = cb; ifs->addr = *address; if (mask) ifs->mask = *netmask; LIST_INSERT_HEAD(&il, ifs, link); return 0; } static int open_socket(char *ifname, struct sockaddr *addr, int port) { int sd, val, rc; char loop; struct ip_mreqn mreq; struct sockaddr_in sin, *address = (struct sockaddr_in *)addr; sd = socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); if (sd < 0) return -1; sin.sin_family = AF_INET; sin.sin_port = htons(port); sin.sin_addr = address->sin_addr; if (bind(sd, (struct sockaddr *)&sin, sizeof(sin)) < 0) { close(sd); logit(LOG_ERR, "Failed binding to %s:%d: %s", inet_ntoa(address->sin_addr), port, strerror(errno)); return -1; } #if 0 ENABLE_SOCKOPT(sd, SOL_SOCKET, SO_REUSEADDR); #ifdef SO_REUSEPORT ENABLE_SOCKOPT(sd, SOL_SOCKET, SO_REUSEPORT); #endif #endif memset(&mreq, 0, sizeof(mreq)); mreq.imr_address = address->sin_addr; mreq.imr_multiaddr.s_addr = inet_addr(MC_SSDP_GROUP); if (setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq))) { close(sd); logit(LOG_ERR, "Failed joining group %s: %s", MC_SSDP_GROUP, strerror(errno)); return -1; } val = 2; /* Default 2, but should be configurable */ rc = setsockopt(sd, IPPROTO_IP, IP_MULTICAST_TTL, &val, sizeof(val)); if (rc < 0) { close(sd); logit(LOG_ERR, "Failed setting multicast TTL: %s", strerror(errno)); return -1; } loop = 0; rc = setsockopt(sd, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop)); if (rc < 0) { close(sd); logit(LOG_ERR, "Failed disabing multicast loop: %s", strerror(errno)); return -1; } rc = setsockopt(sd, IPPROTO_IP, IP_MULTICAST_IF, &address->sin_addr, sizeof(address->sin_addr)); if (rc < 0) { close(sd); logit(LOG_ERR, "Failed setting multicast interface: %s", strerror(errno)); return -1; } logit(LOG_DEBUG, "Adding new interface %s with address %s", ifname, inet_ntoa(address->sin_addr)); return sd; } static int close_socket(void) { int ret = 0; struct ifsock *ifs, *tmp; LIST_FOREACH_SAFE(ifs, &il, link, tmp) { LIST_REMOVE(ifs, link); if (ifs->out != -1) ret |= close(ifs->out); else ret |= close(ifs->in); free(ifs); } return ret; } static int filter_addr(struct sockaddr *sa) { struct ifsock *ifs; struct sockaddr_in *sin = (struct sockaddr_in *)sa; if (!sa) return 1; if (sa->sa_family != AF_INET) return 1; if (sin->sin_addr.s_addr == htonl(INADDR_ANY)) return 1; if (sin->sin_addr.s_addr == htonl(INADDR_LOOPBACK)) return 1; ifs = find_outbound(sa); if (ifs) { if (ifs->addr.sin_addr.s_addr != htonl(INADDR_ANY)) return 1; } return 0; } static int filter_iface(char *ifname, char *iflist[], size_t num) { size_t i; if (!num) { logit(LOG_DEBUG, "No interfaces to filter, using all with an IP address."); return 0; } logit(LOG_DEBUG, "Filter %s? Comparing %zd entries ...", ifname, num); for (i = 0; i < num; i++) { logit(LOG_DEBUG, "Filter %s? Comparing with %s ...", ifname, iflist[i]); if (!strcmp(ifname, iflist[i])) return 0; } return 1; } static void compose_addr(struct sockaddr_in *sin, char *group, int port) { memset(sin, 0, sizeof(*sin)); sin->sin_family = AF_INET; sin->sin_port = htons(port); sin->sin_addr.s_addr = inet_addr(group); } static void compose_response(char *type, char *host, char *buf, size_t len) { char usn[256]; char date[42]; time_t now; /* RFC1123 date, as specified in RFC2616 */ now = time(NULL); strftime(date, sizeof(date), "%a, %d %b %Y %T %Z", gmtime(&now)); if (type) { if (!strcmp(type, uuid)) type = NULL; else snprintf(usn, sizeof(usn), "%s::%s", uuid, type); } if (!type) strncpy(usn, uuid, sizeof(usn)); snprintf(buf, len, "HTTP/1.1 200 OK\r\n" "Server: %s\r\n" "Date: %s\r\n" "Location: http://%s:%d%s\r\n" "ST: %s\r\n" "EXT: \r\n" "USN: %s\r\n" "Cache-Control: max-age=%d\r\n" "\r\n", server_string, date, host, LOCATION_PORT, LOCATION_DESC, type, usn, CACHE_TIMEOUT); } static void compose_search(char *type, char *buf, size_t len) { snprintf(buf, len, "M-SEARCH * HTTP/1.1\r\n" "Host: %s:%d\r\n" "MAN: \"ssdp:discover\"\r\n" "MX: 1\r\n" "ST: %s\r\n" "User-Agent: %s\r\n" "\r\n", MC_SSDP_GROUP, MC_SSDP_PORT, type, server_string); } static void compose_notify(char *type, char *host, char *buf, size_t len) { char usn[256]; if (type) { if (!strcmp(type, SSDP_ST_ALL)) type = NULL; else snprintf(usn, sizeof(usn), "%s::%s", uuid, type); } if (!type) { type = usn; strncpy(usn, uuid, sizeof(usn)); } snprintf(buf, len, "NOTIFY * HTTP/1.1\r\n" "Host: %s:%d\r\n" "Server: %s\r\n" "Location: http://%s:%d%s\r\n" "NT: %s\r\n" "NTS: ssdp:alive\r\n" "USN: %s\r\n" "Cache-Control: max-age=%d\r\n" "\r\n", MC_SSDP_GROUP, MC_SSDP_PORT, server_string, host, LOCATION_PORT, LOCATION_DESC, type, usn, CACHE_TIMEOUT); } size_t pktlen(unsigned char *buf) { size_t hdr = sizeof(struct udphdr); return strlen((char *)buf + hdr) + hdr; } static void send_search(struct ifsock *ifs, char *type) { ssize_t num; char buf[MAX_PKT_SIZE]; struct sockaddr dest; memset(buf, 0, sizeof(buf)); compose_search(type, buf, sizeof(buf)); compose_addr((struct sockaddr_in *)&dest, MC_SSDP_GROUP, MC_SSDP_PORT); logit(LOG_DEBUG, "Sending M-SEARCH ..."); num = sendto(ifs->out, buf, strlen(buf), 0, &dest, sizeof(struct sockaddr_in)); if (num < 0) logit(LOG_WARNING, "Failed sending SSDP M-SEARCH"); } static void send_message(struct ifsock *ifs, char *type, struct sockaddr *sa) { int s; size_t i, len, note = 0; ssize_t num; char host[NI_MAXHOST]; char buf[MAX_PKT_SIZE]; struct sockaddr dest; struct sockaddr_in *sin = (struct sockaddr_in *)sa; gethostname(hostname, sizeof(hostname)); s = getnameinfo((struct sockaddr *)&ifs->addr, sizeof(struct sockaddr_in), host, sizeof(host), NULL, 0, NI_NUMERICHOST); if (s) { logit(LOG_WARNING, "Failed getnameinfo(): %s", gai_strerror(s)); return; } if (ifs->addr.sin_addr.s_addr == htonl(INADDR_ANY)) return; if (ifs->out == -1) return; if (!strcmp(type, SSDP_ST_ALL)) type = NULL; memset(buf, 0, sizeof(buf)); if (sin) compose_response(type, host, buf, sizeof(buf)); else compose_notify(type, host, buf, sizeof(buf)); if (!sin) { note = 1; compose_addr((struct sockaddr_in *)&dest, MC_SSDP_GROUP, MC_SSDP_PORT); sin = (struct sockaddr_in *)&dest; } logit(LOG_DEBUG, "Sending %s from %s ...", !note ? "reply" : "notify", host); num = sendto(ifs->out, buf, strlen(buf), 0, sin, sizeof(struct sockaddr_in)); if (num < 0) logit(LOG_WARNING, "Failed sending SSDP %s, type: %s: %s", !note ? "reply" : "notify", type, strerror(errno)); } static void ssdp_recv(int sd) { ssize_t len; struct sockaddr sa; socklen_t salen; char buf[MAX_PKT_SIZE + 1]; memset(buf, 0, sizeof(buf)); len = recvfrom(sd, buf, sizeof(buf) - 1, MSG_DONTWAIT, &sa, &salen); if (len > 0) { if (sa.sa_family != AF_INET) return; if (strstr(buf, "M-SEARCH *")) { size_t i; char *ptr, *type; struct ifsock *ifs; struct sockaddr_in *sin = (struct sockaddr_in *)&sa; ifs = find_outbound(&sa); if (!ifs) { logit(LOG_DEBUG, "No matching socket for client %s", inet_ntoa(sin->sin_addr)); return; } logit(LOG_DEBUG, "Matching socket for client %s", inet_ntoa(sin->sin_addr)); type = strcasestr(buf, "\r\nST:"); if (!type) { logit(LOG_DEBUG, "No Search Type (ST:) found in M-SEARCH *, assuming " SSDP_ST_ALL); type = SSDP_ST_ALL; send_message(ifs, type, &sa); return; } type = strchr(type, ':'); if (!type) return; type++; while (isspace(*type)) type++; ptr = strstr(type, "\r\n"); if (!ptr) return; *ptr = 0; for (i = 0; supported_types[i]; i++) { if (!strcmp(supported_types[i], type)) { logit(LOG_DEBUG, "M-SEARCH * ST: %s from %s port %d", type, inet_ntoa(sin->sin_addr), ntohs(sin->sin_port)); send_message(ifs, type, &sa); return; } } logit(LOG_DEBUG, "M-SEARCH * for unsupported ST: %s from %s", type, inet_ntoa(sin->sin_addr)); } } } static int multicast_init(void) { int sd; struct sockaddr sa; struct sockaddr_in *sin = (struct sockaddr_in *)&sa; sd = socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); if (sd < 0) { logit(LOG_ERR, "Failed opening multicast socket: %s", strerror(errno)); return -1; } memset(&sa, 0, sizeof(sa)); sin->sin_family = AF_INET; sin->sin_addr.s_addr = inet_addr(MC_SSDP_GROUP); sin->sin_port = htons(MC_SSDP_PORT); if (bind(sd, &sa, sizeof(*sin)) < 0) { close(sd); logit(LOG_ERR, "Failed binding to %s:%d: %s", inet_ntoa(sin->sin_addr), MC_SSDP_PORT, strerror(errno)); return -1; } register_socket(sd, -1, &sa, NULL, ssdp_recv); return sd; } static int multicast_join(int sd, struct sockaddr *sa) { struct ip_mreqn mreq; struct sockaddr_in *sin = (struct sockaddr_in *)sa; memset(&mreq, 0, sizeof(mreq)); mreq.imr_address = sin->sin_addr; mreq.imr_multiaddr.s_addr = inet_addr(MC_SSDP_GROUP); if (setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq))) { if (EADDRINUSE == errno) return 0; logit(LOG_ERR, "Failed joining group %s: %s", MC_SSDP_GROUP, strerror(errno)); return -1; } return 0; } static void mark(void) { struct ifsock *ifs; LIST_FOREACH(ifs, &il, link) { if (ifs->out != -1) ifs->stale = 1; else ifs->stale = 0; } } static int sweep(void) { int modified = 0; struct ifsock *ifs, *tmp; LIST_FOREACH_SAFE(ifs, &il, link, tmp) { if (!ifs->stale) continue; modified++; logit(LOG_DEBUG, "Removing stale ifs %s", inet_ntoa(ifs->addr.sin_addr)); LIST_REMOVE(ifs, link); close(ifs->out); free(ifs); } return modified; } static int ssdp_init(int in, char *iflist[], size_t num) { int modified; size_t i; struct ifaddrs *ifaddrs, *ifa; logit(LOG_INFO, "Updating interfaces ..."); if (getifaddrs(&ifaddrs) < 0) { logit(LOG_ERR, "Failed getifaddrs(): %s", strerror(errno)); return -1; } /* Mark all outbound interfaces as stale */ mark(); /* First pass, clear stale marker from exact matches */ for (ifa = ifaddrs; ifa; ifa = ifa->ifa_next) { struct ifsock *ifs; /* Do we already have it? */ ifs = find_iface(ifa->ifa_addr); if (ifs) { ifs->stale = 0; continue; } } /* Clean out any stale interface addresses */ modified = sweep(); /* Second pass, add new ones */ for (ifa = ifaddrs; ifa; ifa = ifa->ifa_next) { int sd; /* Interface filtering, optional command line argument */ if (filter_iface(ifa->ifa_name, iflist, num)) { logit(LOG_DEBUG, "Skipping %s, not in iflist.", ifa->ifa_name); continue; } /* Do we have another in the same subnet? */ if (filter_addr(ifa->ifa_addr)) continue; sd = open_socket(ifa->ifa_name, ifa->ifa_addr, MC_SSDP_PORT); if (sd < 0) continue; multicast_join(in, ifa->ifa_addr); if (register_socket(in, sd, ifa->ifa_addr, ifa->ifa_netmask, ssdp_recv)) { close(sd); break; } modified++; } freeifaddrs(ifaddrs); return modified; } static void handle_message(int sd) { struct ifsock *ifs; LIST_FOREACH(ifs, &il, link) { if (ifs->in != sd) continue; if (ifs->cb) ifs->cb(sd); } } static void wait_message(time_t tmo) { int num = 1, timeout; size_t ifnum = 0; struct pollfd pfd[MAX_NUM_IFACES]; struct ifsock *ifs; LIST_FOREACH(ifs, &il, link) { if (ifs->out != -1) continue; pfd[ifnum].fd = ifs->in; pfd[ifnum].events = POLLIN | POLLHUP; ifnum++; } while (1) { size_t i; timeout = tmo - time(NULL); if (timeout < 0) break; num = poll(pfd, ifnum, timeout * 1000); if (num < 0) { if (EINTR == errno) break; err(1, "Unrecoverable error"); } if (num == 0) break; for (i = 0; num > 0 && i < ifnum; i++) { if (pfd[i].revents & POLLIN) { handle_message(pfd[i].fd); num--; } } } } static void announce(int mod) { struct ifsock *ifs; logit(LOG_INFO, "Sending SSDP NOTIFY new:%d ...", mod); LIST_FOREACH(ifs, &il, link) { size_t i; if (mod && !ifs->mod) continue; ifs->mod = 0; // send_search(ifs, "upnp:rootdevice"); for (i = 0; supported_types[i]; i++) { /* UUID sent in SSDP_ST_ALL, first announce */ if (!strcmp(supported_types[i], uuid)) continue; send_message(ifs, supported_types[i], NULL); } } } static void lsb_init(void) { FILE *fp; char *ptr; char line[80]; const char *file = "/etc/lsb-release"; fp = fopen(file, "r"); if (!fp) { fallback: logit(LOG_WARNING, "No %s found on system, using built-in server string.", file); return; } while (fgets(line, sizeof(line), fp)) { line[strlen(line) - 1] = 0; ptr = strstr(line, "DISTRIB_ID"); if (ptr && (ptr = strchr(ptr, '='))) os = strdup(++ptr); ptr = strstr(line, "DISTRIB_RELEASE"); if (ptr && (ptr = strchr(ptr, '='))) ver = strdup(++ptr); } fclose(fp); if (os && ver) snprintf(server_string, sizeof(server_string), "%s/%s UPnP/1.0 %s/%s", os, ver, PACKAGE_NAME, PACKAGE_VERSION); else goto fallback; logit(LOG_DEBUG, "Server: %s", server_string); } /* https://en.wikipedia.org/wiki/Universally_unique_identifier */ static void uuidgen(void) { FILE *fp; char buf[42]; const char *file = _PATH_VARDB PACKAGE_NAME ".cache"; fp = fopen(file, "r"); if (!fp) { fp = fopen(file, "w"); if (!fp) logit(LOG_WARNING, "Cannot create UUID cache, %s: %s", file, strerror(errno)); generate: srand(time(NULL)); snprintf(buf, sizeof(buf), "uuid:%8.8x-%4.4x-%4.4x-%4.4x-%6.6x%6.6x", rand() & 0xFFFFFFFF, rand() & 0xFFFF, (rand() & 0x0FFF) | 0x4000, /* M 4 MSB version => version 4 */ (rand() & 0x1FFF) | 0x8000, /* N: 3 MSB variant => variant 1 */ rand() & 0xFFFFFF, rand() & 0xFFFFFF); if (fp) { logit(LOG_DEBUG, "Creating new UUID cache file, %s", file); fprintf(fp, "%s\n", buf); fclose(fp); } } else { if (!fgets(buf, sizeof(buf), fp)) { fclose(fp); goto generate; } buf[strlen(buf) - 1] = 0; fclose(fp); } strcpy(uuid, buf); logit(LOG_DEBUG, "URN: %s", uuid); } static void exit_handler(int signo) { (void)signo; running = 0; } static void signal_init(void) { signal(SIGTERM, exit_handler); signal(SIGINT, exit_handler); signal(SIGHUP, exit_handler); signal(SIGQUIT, exit_handler); } static int usage(int code) { printf("Usage: %s [-dhv] [-i SEC] [IFACE [IFACE ...]]\n" "\n" " -d Developer debug mode\n" " -h This help text\n" " -i SEC SSDP notify interval (30-900), default %d sec\n" " -r SEC Interface refresh interval (5-1800), default %d sec\n" " -v Show program version\n" "\n" "Bug report address: %-40s\n", PACKAGE_NAME, NOTIFY_INTERVAL, REFRESH_INTERVAL, PACKAGE_BUGREPORT); return code; } int main(int argc, char *argv[]) { int i, c, sd; int log_level = LOG_NOTICE; int log_opts = LOG_CONS | LOG_PID; int interval = NOTIFY_INTERVAL; int refresh = REFRESH_INTERVAL; time_t now, rtmo = 0, itmo = 0; while ((c = getopt(argc, argv, "dhi:r:v")) != EOF) { switch (c) { case 'd': debug = 1; break; case 'h': return usage(0); case 'i': interval = atoi(optarg); if (interval < 30 || interval > 900) errx(1, "Invalid announcement interval (30-900)."); break; case 'r': refresh = atoi(optarg); if (refresh < 5 || refresh > 1800) errx(1, "Invalid refresh interval (5-1800)."); break; case 'v': puts(PACKAGE_VERSION); return 0; default: break; } } signal_init(); if (debug) { log_level = LOG_DEBUG; log_opts |= LOG_PERROR; } openlog(PACKAGE_NAME, log_opts, LOG_DAEMON); setlogmask(LOG_UPTO(log_level)); uuidgen(); lsb_init(); web_init(); sd = multicast_init(); if (sd < 0) err(1, "Failed creating multicast socket"); while (running) { now = time(NULL); if (rtmo <= now) { if (ssdp_init(sd, &argv[optind], argc - optind) > 0) announce(1); rtmo = now + refresh; } if (itmo <= now) { announce(0); itmo = now + interval; } wait_message(MIN(rtmo, itmo)); } closelog(); return close_socket(); } /** * Local Variables: * indent-tabs-mode: t * c-file-style: "linux" * End: */
null
132
CWE-787
CVE-2019-14495
/* 3APA3A simpliest proxy server (c) 2002-2008 by ZARAZA <3APA3A@security.nnov.ru> please read License Agreement */ #include "proxy.h" #define RETURN(xxx) { param->res = xxx; goto CLEANRET; } #define LINESIZE 2048 extern FILE *writable; FILE * confopen(); extern void decodeurl(unsigned char *s, int filter); struct printparam { char buf[1024]; int inbuf; struct clientparam *cp; }; static void stdpr(struct printparam* pp, char *buf, int inbuf){ if((pp->inbuf + inbuf > 1024) || !buf) { socksend(pp->cp->clisock, (unsigned char *)pp->buf, pp->inbuf, conf.timeouts[STRING_S]); pp->inbuf = 0; if(!buf) return; } if(inbuf >= 1000){ socksend(pp->cp->clisock, (unsigned char *)buf, inbuf, conf.timeouts[STRING_S]); } else { memcpy(pp->buf + pp->inbuf, buf, inbuf); pp->inbuf += inbuf; } } static void stdcbf(void *cb, char *buf, int inbuf){ int delay = 0; int i; for(i = 0; i < inbuf; i++){ switch(buf[i]){ case '&': if(delay){ stdpr((struct printparam*)cb, buf+i-delay, delay); delay = 0; } stdpr((struct printparam*)cb, "&amp;", 5); break; case '<': if(delay){ stdpr((struct printparam*)cb, buf+i-delay, delay); delay = 0; } stdpr((struct printparam*)cb, "&lt;", 4); break; case '>': if(delay){ stdpr((struct printparam*)cb, buf+i-delay, delay); delay = 0; } stdpr((struct printparam*)cb, "&gt;", 4); break; default: delay++; break; } } if(delay){ stdpr((struct printparam*)cb, buf+i-delay, delay); } } /* static char * templateprint(struct printparam* pp, int *level, struct dictionary *dict, char * template){ char *s, *s2; for(; template && *template; ){ if(!( s = strchr(template, '<'))){ stdpr(pp, template, (int)strlen(template)); return template + strlen(template); } if(s[1] != '%' || s[2] == '%'){ stdpr(pp, template, (int)(s - template) + 1); template = s + 1; continue; } if(s[2] == '/' && (s2 = strchr(s + 2, '>')) && *(s2 - 1) == '%'){ if(--*level < 0) return NULL; return s2 + 1; } } return template; } */ static void printstr(struct printparam* pp, char* str){ stdpr(pp, str, str?(int)strlen(str):0); } static void printval(void *value, int type, int level, struct printparam* pp){ struct node pn, cn; struct property *p; int i; pn.iteration = NULL; pn.parent = NULL; pn.type = type; pn.value = value; printstr(pp, "<item>"); for(p = datatypes[type].properties; p; ) { cn.iteration = NULL; cn.parent = &pn; cn.type = p->type; cn.value = (*p->e_f)(&pn); if(cn.value){ for(i = 0; i < level; i++) printstr(pp, "\t"); if(strcmp(p->name, "next")){ printstr(pp, "<parameter>"); printstr(pp, "<name>"); printstr(pp, p->name); printstr(pp, "</name>"); printstr(pp, "<type>"); printstr(pp, datatypes[p->type].type); printstr(pp, "</type>"); printstr(pp, "<description>"); printstr(pp, p->description); printstr(pp, "</description>"); } if(datatypes[p->type].p_f){ printstr(pp, "<value><![CDATA["); (*datatypes[p->type].p_f)(&cn, stdcbf, pp); printstr(pp, "]]></value>\n"); printstr(pp, "</parameter>"); } else { if(!strcmp(p->name, "next")){ /* printstr(pp, "<!-- -------------------- -->\n"); */ printstr(pp, "</item>\n<item>"); p = datatypes[type].properties; pn.value = value = cn.value; continue; } else { printstr(pp, "\n"); printval(cn.value, cn.type, level+1, pp); printstr(pp, "</parameter>"); } } } p=p->next; } printstr(pp, "</item>"); } char * admin_stringtable[]={ "HTTP/1.0 401 Authentication Required\r\n" "WWW-Authenticate: Basic realm=\"proxy\"\r\n" "Connection: close\r\n" "Content-type: text/html; charset=us-ascii\r\n" "\r\n" "<html><head><title>401 Authentication Required</title></head>\r\n" "<body><h2>401 Authentication Required</h2><h3>Access to requested resource disallowed by administrator or you need valid username/password to use this resource</h3></body></html>\r\n", "HTTP/1.0 200 OK\r\n" "Connection: close\r\n" "Expires: Thu, 01 Dec 1994 16:00:00 GMT\r\n" "Cache-Control: no-cache\r\n" "Content-type: text/html\r\n" "\r\n" "<http><head><title>%s configuration page</title></head>\r\n" "<table width=\'100%%\' border=\'0\'>\r\n" "<tr><td width=\'150\' valign=\'top\'>\r\n" "<h2>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</h2>\r\n" "<A HREF=\'/C'>Counters</A><br>\r\n" "<A HREF=\'/R'>Reload</A><br>\r\n" "<A HREF=\'/S'>Running Services</A><br>\r\n" "<A HREF=\'/F'>Config</A>\r\n" "</td><td>" "<h2>%s %s configuration</h2>", "HTTP/1.0 200 OK\r\n" "Connection: close\r\n" "Cache-Control: no-cache\r\n" "Content-type: text/xml\r\n" "\r\n" "<?xml version=\"1.0\"?>\r\n" "<?xml-stylesheet href=\"/SX\" type=\"text/css\"?>\r\n" "<services>\r\n" "<description>Services currently running and connected clients</description>\r\n", "</services>\r\n", "HTTP/1.0 200 OK\r\n" "Connection: close\r\n" "Cache-Control: no-cache\r\n" "Content-type: text/css\r\n" "\r\n" "services {\r\n" " display: block;\r\n" " margin: 10px auto 10px auto;\r\n" " width: 80%;\r\n" " background: black;\r\n" " font-family: sans-serif;\r\n" " font-size: small;\r\n" " color: silver;\r\n" " }\r\n" "item {\r\n" " display: block;\r\n" " margin-bottom: 10px;\r\n" " border: 2px solid #CCC;\r\n" " padding: 10px;\r\n" " spacing: 2px;\r\n" " }\r\n" "parameter {\r\n" " display: block;\r\n" " padding: 2px;\r\n" " margin-top: 10px;\r\n" " border: 1px solid grey;\r\n" " background: #EEE;\r\n" " color: black;\r\n" " }\r\n" "name {\r\n" " display: inline;\r\n" " float: left;\r\n" " margin-right: 5px;\r\n" " font-weight: bold;\r\n" " }\r\n" "type {\r\n" " display: inline;\r\n" " font-size: x-small;\r\n" " margin-right: 5px;\r\n" " color: #666;\r\n" " white-space: nowrap;\r\n" " font-style: italic;\r\n" " }\r\n" "description {\r\n" " display: inline;\r\n" " margin-right: 5px;\r\n" " white-space: nowrap;\r\n" " }\r\n" "value {\r\n" " display: block;\r\n" " margin-right: 5px;\r\n" " }\r\n", "<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />\r\n" "<pre><font size=\'-2\'><b>" COPYRIGHT "</b></font>\r\n" "</td></tr></table></body></html>", "<h3>Counters</h3>\r\n" "<table border = \'1\'>\r\n" "<tr align=\'center\'><td>Description</td><td>Active</td>" "<td>Users</td><td>Source Address</td><td>Destination Address</td>" "<td>Port</td>" "<td>Limit</td><td>Units</td><td>Value</td>" "<td>Reset</td><td>Updated</td><td>Num</td></tr>\r\n", "</table>\r\n", NULL }; #define authreq admin_stringtable[0] #define ok admin_stringtable[1] #define xml admin_stringtable[2] #define postxml admin_stringtable[3] #define style admin_stringtable[4] #define tail admin_stringtable[5] #define counters admin_stringtable[6] #define counterstail admin_stringtable[7] static int printportlist(char *buf, int bufsize, struct portlist* pl, char * delim){ int printed = 0; for(; pl; pl = pl->next){ if(printed > (bufsize - 64)) break; if(pl->startport != pl->endport) printed += sprintf(buf+printed, "%hu-%hu%s", pl->startport, pl->endport, pl->next?delim:""); else { /* struct servent *se=NULL; if(pl->startport)se = getservbyport((int)ntohs(pl->startport), NULL); printed += sprintf(buf+printed, "%hu(%s)%s", pl->startport, se?se->s_name:"unknown", pl->next?delim:""); */ printed += sprintf(buf+printed, "%hu%s", pl->startport, pl->next?delim:""); } if(printed > (bufsize - 64)) { printed += sprintf(buf+printed, "..."); break; } } return printed; } static int printuserlist(char *buf, int bufsize, struct userlist* ul, char * delim){ int printed = 0; for(; ul; ul = ul->next){ if(printed > (bufsize - 64)) break; printed += sprintf(buf+printed, "%s%s", ul->user, ul->next?delim:""); if(printed > (bufsize - 64)) { printed += sprintf(buf+printed, "..."); break; } } return printed; } int printiple(char *buf, struct iplist* ipl); static int printiplist(char *buf, int bufsize, struct iplist* ipl, char * delim){ int printed = 0; for(; ipl; ipl = ipl->next){ if(printed > (bufsize - 128)) break; printed += printiple(buf+printed, ipl); if(printed > (bufsize - 128)) { printed += sprintf(buf+printed, "..."); break; } } return printed; } void * adminchild(struct clientparam* param) { int i, res; char * buf; char username[256]; char *sb; char *req = NULL; struct printparam pp; int contentlen = 0; int isform = 0; pp.inbuf = 0; pp.cp = param; buf = myalloc(LINESIZE); if(!buf) {RETURN(555);} i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '\n', conf.timeouts[STRING_S]); if(i<5 || ((buf[0]!='G' || buf[1]!='E' || buf[2]!='T' || buf[3]!=' ' || buf[4]!='/') && (buf[0]!='P' || buf[1]!='O' || buf[2]!='S' || buf[3]!='T' || buf[4]!=' ' || buf[5]!='/'))) { RETURN(701); } buf[i] = 0; sb = strchr(buf+5, ' '); if(!sb){ RETURN(702); } *sb = 0; req = mystrdup(buf + ((*buf == 'P')? 6 : 5)); while((i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '\n', conf.timeouts[STRING_S])) > 2){ buf[i] = 0; if(i > 19 && (!strncasecmp(buf, "authorization", 13))){ sb = strchr(buf, ':'); if(!sb)continue; ++sb; while(isspace(*sb))sb++; if(!*sb || strncasecmp(sb, "basic", 5)){ continue; } sb+=5; while(isspace(*sb))sb++; i = de64((unsigned char *)sb, (unsigned char *)username, 255); if(i<=0)continue; username[i] = 0; sb = strchr((char *)username, ':'); if(sb){ *sb = 0; if(param->password)myfree(param->password); param->password = (unsigned char *)mystrdup(sb+1); } if(param->username) myfree(param->username); param->username = (unsigned char *)mystrdup(username); continue; } else if(i > 15 && (!strncasecmp(buf, "content-length:", 15))){ sb = buf + 15; while(isspace(*sb))sb++; contentlen = atoi(sb); } else if(i > 13 && (!strncasecmp(buf, "content-type:", 13))){ sb = buf + 13; while(isspace(*sb))sb++; if(!strncasecmp(sb, "x-www-form-urlencoded", 21)) isform = 1; } } param->operation = ADMIN; if(isform && contentlen) { printstr(&pp, "HTTP/1.0 100 Continue\r\n\r\n"); stdpr(&pp, NULL, 0); } res = (*param->srv->authfunc)(param); if(res && res != 10) { printstr(&pp, authreq); RETURN(res); } if(param->srv->singlepacket || param->redirected){ if(*req == 'C') req[1] = 0; else *req = 0; } sprintf(buf, ok, conf.stringtable?(char *)conf.stringtable[2]:"3proxy", conf.stringtable?(char *)conf.stringtable[2]:"3[APA3A] tiny proxy", conf.stringtable?(char *)conf.stringtable[3]:""); if(*req != 'S') printstr(&pp, buf); switch(*req){ case 'C': printstr(&pp, counters); { struct trafcount *cp; int num = 0; for(cp = conf.trafcounter; cp; cp = cp->next, num++){ int inbuf = 0; if(cp->ace && (param->srv->singlepacket || param->redirected)){ if(!ACLmatches(cp->ace, param))continue; } if(req[1] == 'S' && atoi(req+2) == num) cp->disabled=0; if(req[1] == 'D' && atoi(req+2) == num) cp->disabled=1; inbuf += sprintf(buf, "<tr>" "<td>%s</td><td><A HREF=\'/C%c%d\'>%s</A></td><td>", (cp->comment)?cp->comment:"&nbsp;", (cp->disabled)?'S':'D', num, (cp->disabled)?"NO":"YES" ); if(!cp->ace || !cp->ace->users){ inbuf += sprintf(buf+inbuf, "<center>ANY</center>"); } else { inbuf += printuserlist(buf+inbuf, LINESIZE-800, cp->ace->users, ",<br />\r\n"); } inbuf += sprintf(buf+inbuf, "</td><td>"); if(!cp->ace || !cp->ace->src){ inbuf += sprintf(buf+inbuf, "<center>ANY</center>"); } else { inbuf += printiplist(buf+inbuf, LINESIZE-512, cp->ace->src, ",<br />\r\n"); } inbuf += sprintf(buf+inbuf, "</td><td>"); if(!cp->ace || !cp->ace->dst){ inbuf += sprintf(buf+inbuf, "<center>ANY</center>"); } else { inbuf += printiplist(buf+inbuf, LINESIZE-512, cp->ace->dst, ",<br />\r\n"); } inbuf += sprintf(buf+inbuf, "</td><td>"); if(!cp->ace || !cp->ace->ports){ inbuf += sprintf(buf+inbuf, "<center>ANY</center>"); } else { inbuf += printportlist(buf+inbuf, LINESIZE-128, cp->ace->ports, ",<br />\r\n"); } if(cp->type == NONE) { inbuf += sprintf(buf+inbuf, "</td><td colspan=\'6\' align=\'center\'>exclude from limitation</td></tr>\r\n" ); } else { inbuf += sprintf(buf+inbuf, "</td><td>%"PRINTF_INT64_MODIFIER"u</td>" "<td>MB%s</td>" "<td>%"PRINTF_INT64_MODIFIER"u</td>" "<td>%s</td>", cp->traflim64 / (1024 * 1024), rotations[cp->type], cp->traf64, cp->cleared?ctime(&cp->cleared):"never" ); inbuf += sprintf(buf + inbuf, "<td>%s</td>" "<td>%i</td>" "</tr>\r\n", cp->updated?ctime(&cp->updated):"never", cp->number ); } printstr(&pp, buf); } } printstr(&pp, counterstail); break; case 'R': conf.needreload = 1; printstr(&pp, "<h3>Reload scheduled</h3>"); break; case 'S': { if(req[1] == 'X'){ printstr(&pp, style); break; } printstr(&pp, xml); printval(conf.services, TYPE_SERVER, 0, &pp); printstr(&pp, postxml); } break; case 'F': { FILE *fp; char buf[256]; fp = confopen(); if(!fp){ printstr(&pp, "<h3><font color=\"red\">Failed to open config file</font></h3>"); break; } printstr(&pp, "<h3>Please be careful editing config file remotely</h3>"); printstr(&pp, "<form method=\"POST\" action=\"/U\"><textarea cols=\"80\" rows=\"30\" name=\"conffile\">"); while(fgets(buf, 256, fp)){ printstr(&pp, buf); } if(!writable) fclose(fp); printstr(&pp, "</textarea><br><input type=\"Submit\"></form>"); break; } case 'U': { int l=0; int error = 0; if(!writable || fseek(writable, 0, 0)){ error = 1; } while((i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '+', conf.timeouts[STRING_S])) > 0){ if(i > (contentlen - l)) i = (contentlen - l); buf[i] = 0; if(!l){ if(strncasecmp(buf, "conffile=", 9)) error = 1; } if(!error){ decodeurl((unsigned char *)buf, 1); fprintf(writable, "%s", l? buf : buf + 9); } l += i; if(l >= contentlen) break; } if(writable && !error){ fflush(writable); #ifndef _WINCE ftruncate(fileno(writable), ftell(writable)); #endif } printstr(&pp, error? "<h3><font color=\"red\">Config file is not writable</font></h3>Make sure you have \"writable\" command in configuration file": "<h3>Configuration updated</h3>"); } break; default: printstr(&pp, (char *)conf.stringtable[WEBBANNERS]); break; } if(*req != 'S') printstr(&pp, tail); CLEANRET: printstr(&pp, NULL); if(buf) myfree(buf); (*param->srv->logfunc)(param, (unsigned char *)req); if(req)myfree(req); freeparam(param); return (NULL); }
null
/* 3APA3A simpliest proxy server (c) 2002-2008 by ZARAZA <3APA3A@security.nnov.ru> please read License Agreement */ #include "proxy.h" #define RETURN(xxx) { param->res = xxx; goto CLEANRET; } #define LINESIZE 65536 extern FILE *writable; FILE * confopen(); extern void decodeurl(unsigned char *s, int filter); struct printparam { char buf[1024]; int inbuf; struct clientparam *cp; }; static void stdpr(struct printparam* pp, char *buf, int inbuf){ if((pp->inbuf + inbuf > 1024) || !buf) { socksend(pp->cp->clisock, (unsigned char *)pp->buf, pp->inbuf, conf.timeouts[STRING_S]); pp->inbuf = 0; if(!buf) return; } if(inbuf >= 1000){ socksend(pp->cp->clisock, (unsigned char *)buf, inbuf, conf.timeouts[STRING_S]); } else { memcpy(pp->buf + pp->inbuf, buf, inbuf); pp->inbuf += inbuf; } } static void stdcbf(void *cb, char *buf, int inbuf){ int delay = 0; int i; for(i = 0; i < inbuf; i++){ switch(buf[i]){ case '&': if(delay){ stdpr((struct printparam*)cb, buf+i-delay, delay); delay = 0; } stdpr((struct printparam*)cb, "&amp;", 5); break; case '<': if(delay){ stdpr((struct printparam*)cb, buf+i-delay, delay); delay = 0; } stdpr((struct printparam*)cb, "&lt;", 4); break; case '>': if(delay){ stdpr((struct printparam*)cb, buf+i-delay, delay); delay = 0; } stdpr((struct printparam*)cb, "&gt;", 4); break; default: delay++; break; } } if(delay){ stdpr((struct printparam*)cb, buf+i-delay, delay); } } /* static char * templateprint(struct printparam* pp, int *level, struct dictionary *dict, char * template){ char *s, *s2; for(; template && *template; ){ if(!( s = strchr(template, '<'))){ stdpr(pp, template, (int)strlen(template)); return template + strlen(template); } if(s[1] != '%' || s[2] == '%'){ stdpr(pp, template, (int)(s - template) + 1); template = s + 1; continue; } if(s[2] == '/' && (s2 = strchr(s + 2, '>')) && *(s2 - 1) == '%'){ if(--*level < 0) return NULL; return s2 + 1; } } return template; } */ static void printstr(struct printparam* pp, char* str){ stdpr(pp, str, str?(int)strlen(str):0); } static void printval(void *value, int type, int level, struct printparam* pp){ struct node pn, cn; struct property *p; int i; pn.iteration = NULL; pn.parent = NULL; pn.type = type; pn.value = value; printstr(pp, "<item>"); for(p = datatypes[type].properties; p; ) { cn.iteration = NULL; cn.parent = &pn; cn.type = p->type; cn.value = (*p->e_f)(&pn); if(cn.value){ for(i = 0; i < level; i++) printstr(pp, "\t"); if(strcmp(p->name, "next")){ printstr(pp, "<parameter>"); printstr(pp, "<name>"); printstr(pp, p->name); printstr(pp, "</name>"); printstr(pp, "<type>"); printstr(pp, datatypes[p->type].type); printstr(pp, "</type>"); printstr(pp, "<description>"); printstr(pp, p->description); printstr(pp, "</description>"); } if(datatypes[p->type].p_f){ printstr(pp, "<value><![CDATA["); (*datatypes[p->type].p_f)(&cn, stdcbf, pp); printstr(pp, "]]></value>\n"); printstr(pp, "</parameter>"); } else { if(!strcmp(p->name, "next")){ /* printstr(pp, "<!-- -------------------- -->\n"); */ printstr(pp, "</item>\n<item>"); p = datatypes[type].properties; pn.value = value = cn.value; continue; } else { printstr(pp, "\n"); printval(cn.value, cn.type, level+1, pp); printstr(pp, "</parameter>"); } } } p=p->next; } printstr(pp, "</item>"); } char * admin_stringtable[]={ "HTTP/1.0 401 Authentication Required\r\n" "WWW-Authenticate: Basic realm=\"proxy\"\r\n" "Connection: close\r\n" "Content-type: text/html; charset=us-ascii\r\n" "\r\n" "<html><head><title>401 Authentication Required</title></head>\r\n" "<body><h2>401 Authentication Required</h2><h3>Access to requested resource disallowed by administrator or you need valid username/password to use this resource</h3></body></html>\r\n", "HTTP/1.0 200 OK\r\n" "Connection: close\r\n" "Expires: Thu, 01 Dec 1994 16:00:00 GMT\r\n" "Cache-Control: no-cache\r\n" "Content-type: text/html\r\n" "\r\n" "<http><head><title>%s configuration page</title></head>\r\n" "<table width=\'100%%\' border=\'0\'>\r\n" "<tr><td width=\'150\' valign=\'top\'>\r\n" "<h2>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</h2>\r\n" "<A HREF=\'/C'>Counters</A><br>\r\n" "<A HREF=\'/R'>Reload</A><br>\r\n" "<A HREF=\'/S'>Running Services</A><br>\r\n" "<A HREF=\'/F'>Config</A>\r\n" "</td><td>" "<h2>%s %s configuration</h2>", "HTTP/1.0 200 OK\r\n" "Connection: close\r\n" "Cache-Control: no-cache\r\n" "Content-type: text/xml\r\n" "\r\n" "<?xml version=\"1.0\"?>\r\n" "<?xml-stylesheet href=\"/SX\" type=\"text/css\"?>\r\n" "<services>\r\n" "<description>Services currently running and connected clients</description>\r\n", "</services>\r\n", "HTTP/1.0 200 OK\r\n" "Connection: close\r\n" "Cache-Control: no-cache\r\n" "Content-type: text/css\r\n" "\r\n" "services {\r\n" " display: block;\r\n" " margin: 10px auto 10px auto;\r\n" " width: 80%;\r\n" " background: black;\r\n" " font-family: sans-serif;\r\n" " font-size: small;\r\n" " color: silver;\r\n" " }\r\n" "item {\r\n" " display: block;\r\n" " margin-bottom: 10px;\r\n" " border: 2px solid #CCC;\r\n" " padding: 10px;\r\n" " spacing: 2px;\r\n" " }\r\n" "parameter {\r\n" " display: block;\r\n" " padding: 2px;\r\n" " margin-top: 10px;\r\n" " border: 1px solid grey;\r\n" " background: #EEE;\r\n" " color: black;\r\n" " }\r\n" "name {\r\n" " display: inline;\r\n" " float: left;\r\n" " margin-right: 5px;\r\n" " font-weight: bold;\r\n" " }\r\n" "type {\r\n" " display: inline;\r\n" " font-size: x-small;\r\n" " margin-right: 5px;\r\n" " color: #666;\r\n" " white-space: nowrap;\r\n" " font-style: italic;\r\n" " }\r\n" "description {\r\n" " display: inline;\r\n" " margin-right: 5px;\r\n" " white-space: nowrap;\r\n" " }\r\n" "value {\r\n" " display: block;\r\n" " margin-right: 5px;\r\n" " }\r\n", "<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />\r\n" "<pre><font size=\'-2\'><b>" COPYRIGHT "</b></font>\r\n" "</td></tr></table></body></html>", "<h3>Counters</h3>\r\n" "<table border = \'1\'>\r\n" "<tr align=\'center\'><td>Description</td><td>Active</td>" "<td>Users</td><td>Source Address</td><td>Destination Address</td>" "<td>Port</td>" "<td>Limit</td><td>Units</td><td>Value</td>" "<td>Reset</td><td>Updated</td><td>Num</td></tr>\r\n", "</table>\r\n", NULL }; #define authreq admin_stringtable[0] #define ok admin_stringtable[1] #define xml admin_stringtable[2] #define postxml admin_stringtable[3] #define style admin_stringtable[4] #define tail admin_stringtable[5] #define counters admin_stringtable[6] #define counterstail admin_stringtable[7] static int printportlist(char *buf, int bufsize, struct portlist* pl, char * delim){ int printed = 0; for(; pl; pl = pl->next){ if(printed > (bufsize - 64)) break; if(pl->startport != pl->endport) printed += sprintf(buf+printed, "%hu-%hu%s", pl->startport, pl->endport, pl->next?delim:""); else { /* struct servent *se=NULL; if(pl->startport)se = getservbyport((int)ntohs(pl->startport), NULL); printed += sprintf(buf+printed, "%hu(%s)%s", pl->startport, se?se->s_name:"unknown", pl->next?delim:""); */ printed += sprintf(buf+printed, "%hu%s", pl->startport, pl->next?delim:""); } if(printed > (bufsize - 64)) { printed += sprintf(buf+printed, "..."); break; } } return printed; } static int printuserlist(char *buf, int bufsize, struct userlist* ul, char * delim){ int printed = 0; for(; ul; ul = ul->next){ if(printed > (bufsize - 64)) break; printed += sprintf(buf+printed, "%s%s", ul->user, ul->next?delim:""); if(printed > (bufsize - 64)) { printed += sprintf(buf+printed, "..."); break; } } return printed; } int printiple(char *buf, struct iplist* ipl); static int printiplist(char *buf, int bufsize, struct iplist* ipl, char * delim){ int printed = 0; for(; ipl; ipl = ipl->next){ if(printed > (bufsize - 128)) break; printed += printiple(buf+printed, ipl); if(printed > (bufsize - 128)) { printed += sprintf(buf+printed, "..."); break; } } return printed; } void * adminchild(struct clientparam* param) { int i, res; char * buf; char username[256]; char *sb; char *req = NULL; struct printparam pp; unsigned contentlen = 0; int isform = 0; pp.inbuf = 0; pp.cp = param; buf = myalloc(LINESIZE); if(!buf) {RETURN(555);} i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '\n', conf.timeouts[STRING_S]); if(i<5 || ((buf[0]!='G' || buf[1]!='E' || buf[2]!='T' || buf[3]!=' ' || buf[4]!='/') && (buf[0]!='P' || buf[1]!='O' || buf[2]!='S' || buf[3]!='T' || buf[4]!=' ' || buf[5]!='/'))) { RETURN(701); } buf[i] = 0; sb = strchr(buf+5, ' '); if(!sb){ RETURN(702); } *sb = 0; req = mystrdup(buf + ((*buf == 'P')? 6 : 5)); while((i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '\n', conf.timeouts[STRING_S])) > 2){ buf[i] = 0; if(i > 19 && (!strncasecmp(buf, "authorization", 13))){ sb = strchr(buf, ':'); if(!sb)continue; ++sb; while(isspace(*sb))sb++; if(!*sb || strncasecmp(sb, "basic", 5)){ continue; } sb+=5; while(isspace(*sb))sb++; i = de64((unsigned char *)sb, (unsigned char *)username, 255); if(i<=0)continue; username[i] = 0; sb = strchr((char *)username, ':'); if(sb){ *sb = 0; if(param->password)myfree(param->password); param->password = (unsigned char *)mystrdup(sb+1); } if(param->username) myfree(param->username); param->username = (unsigned char *)mystrdup(username); continue; } else if(i > 15 && (!strncasecmp(buf, "content-length:", 15))){ sb = buf + 15; while(isspace(*sb))sb++; sscanf(sb, "%u", &contentlen); if(contentlen > LINESIZE*1024) contentlen = 0; } else if(i > 13 && (!strncasecmp(buf, "content-type:", 13))){ sb = buf + 13; while(isspace(*sb))sb++; if(!strncasecmp(sb, "x-www-form-urlencoded", 21)) isform = 1; } } param->operation = ADMIN; if(isform && contentlen) { printstr(&pp, "HTTP/1.0 100 Continue\r\n\r\n"); stdpr(&pp, NULL, 0); } res = (*param->srv->authfunc)(param); if(res && res != 10) { printstr(&pp, authreq); RETURN(res); } if(param->srv->singlepacket || param->redirected){ if(*req == 'C') req[1] = 0; else *req = 0; } sprintf(buf, ok, conf.stringtable?(char *)conf.stringtable[2]:"3proxy", conf.stringtable?(char *)conf.stringtable[2]:"3[APA3A] tiny proxy", conf.stringtable?(char *)conf.stringtable[3]:""); if(*req != 'S') printstr(&pp, buf); switch(*req){ case 'C': printstr(&pp, counters); { struct trafcount *cp; int num = 0; for(cp = conf.trafcounter; cp; cp = cp->next, num++){ int inbuf = 0; if(cp->ace && (param->srv->singlepacket || param->redirected)){ if(!ACLmatches(cp->ace, param))continue; } if(req[1] == 'S' && atoi(req+2) == num) cp->disabled=0; if(req[1] == 'D' && atoi(req+2) == num) cp->disabled=1; inbuf += sprintf(buf, "<tr>" "<td>%s</td><td><A HREF=\'/C%c%d\'>%s</A></td><td>", (cp->comment)?cp->comment:"&nbsp;", (cp->disabled)?'S':'D', num, (cp->disabled)?"NO":"YES" ); if(!cp->ace || !cp->ace->users){ inbuf += sprintf(buf+inbuf, "<center>ANY</center>"); } else { inbuf += printuserlist(buf+inbuf, LINESIZE-800, cp->ace->users, ",<br />\r\n"); } inbuf += sprintf(buf+inbuf, "</td><td>"); if(!cp->ace || !cp->ace->src){ inbuf += sprintf(buf+inbuf, "<center>ANY</center>"); } else { inbuf += printiplist(buf+inbuf, LINESIZE-512, cp->ace->src, ",<br />\r\n"); } inbuf += sprintf(buf+inbuf, "</td><td>"); if(!cp->ace || !cp->ace->dst){ inbuf += sprintf(buf+inbuf, "<center>ANY</center>"); } else { inbuf += printiplist(buf+inbuf, LINESIZE-512, cp->ace->dst, ",<br />\r\n"); } inbuf += sprintf(buf+inbuf, "</td><td>"); if(!cp->ace || !cp->ace->ports){ inbuf += sprintf(buf+inbuf, "<center>ANY</center>"); } else { inbuf += printportlist(buf+inbuf, LINESIZE-128, cp->ace->ports, ",<br />\r\n"); } if(cp->type == NONE) { inbuf += sprintf(buf+inbuf, "</td><td colspan=\'6\' align=\'center\'>exclude from limitation</td></tr>\r\n" ); } else { inbuf += sprintf(buf+inbuf, "</td><td>%"PRINTF_INT64_MODIFIER"u</td>" "<td>MB%s</td>" "<td>%"PRINTF_INT64_MODIFIER"u</td>" "<td>%s</td>", cp->traflim64 / (1024 * 1024), rotations[cp->type], cp->traf64, cp->cleared?ctime(&cp->cleared):"never" ); inbuf += sprintf(buf + inbuf, "<td>%s</td>" "<td>%i</td>" "</tr>\r\n", cp->updated?ctime(&cp->updated):"never", cp->number ); } printstr(&pp, buf); } } printstr(&pp, counterstail); break; case 'R': conf.needreload = 1; printstr(&pp, "<h3>Reload scheduled</h3>"); break; case 'S': { if(req[1] == 'X'){ printstr(&pp, style); break; } printstr(&pp, xml); printval(conf.services, TYPE_SERVER, 0, &pp); printstr(&pp, postxml); } break; case 'F': { FILE *fp; char buf[256]; fp = confopen(); if(!fp){ printstr(&pp, "<h3><font color=\"red\">Failed to open config file</font></h3>"); break; } printstr(&pp, "<h3>Please be careful editing config file remotely</h3>"); printstr(&pp, "<form method=\"POST\" action=\"/U\" enctype=\"application/x-www-form-urlencoded\"><textarea cols=\"80\" rows=\"30\" name=\"conffile\">"); while(fgets(buf, 256, fp)){ printstr(&pp, buf); } if(!writable) fclose(fp); printstr(&pp, "</textarea><br><input type=\"Submit\"></form>"); break; } case 'U': { unsigned l=0; int error = 0; if(!writable || !contentlen || fseek(writable, 0, 0)){ error = 1; } while(l < contentlen && (i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, (contentlen - l) > LINESIZE - 1?LINESIZE - 1:contentlen - l, '+', conf.timeouts[STRING_S])) > 0){ if(i > (contentlen - l)) i = (contentlen - l); if(!l){ if(i<9 || strncasecmp(buf, "conffile=", 9)) error = 1; } if(!error){ buf[i] = 0; decodeurl((unsigned char *)buf, 1); fprintf(writable, "%s", l? buf : buf + 9); } l += i; } if(writable && !error){ fflush(writable); #ifndef _WINCE ftruncate(fileno(writable), ftell(writable)); #endif } printstr(&pp, error? "<h3><font color=\"red\">Config file is not writable</font></h3>Make sure you have \"writable\" command in configuration file": "<h3>Configuration updated</h3>"); } break; default: printstr(&pp, (char *)conf.stringtable[WEBBANNERS]); break; } if(*req != 'S') printstr(&pp, tail); CLEANRET: printstr(&pp, NULL); if(buf) myfree(buf); (*param->srv->logfunc)(param, (unsigned char *)req); if(req)myfree(req); freeparam(param); return (NULL); }
null
133
CWE-787
CVE-2019-14814
/* * Marvell Wireless LAN device driver: AP specific command handling * * Copyright (C) 2012-2014, Marvell International Ltd. * * This software file (the "File") is distributed by Marvell International * Ltd. under the terms of the GNU General Public License Version 2, June 1991 * (the "License"). You may use, redistribute and/or modify this File in * accordance with the terms and conditions of the License, a copy of which * is available by writing to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the * worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE * IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE * ARE EXPRESSLY DISCLAIMED. The License provides additional details about * this warranty disclaimer. */ #include "main.h" #include "11ac.h" #include "11n.h" /* This function parses security related parameters from cfg80211_ap_settings * and sets into FW understandable bss_config structure. */ int mwifiex_set_secure_params(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_config, struct cfg80211_ap_settings *params) { int i; struct mwifiex_wep_key wep_key; if (!params->privacy) { bss_config->protocol = PROTOCOL_NO_SECURITY; bss_config->key_mgmt = KEY_MGMT_NONE; bss_config->wpa_cfg.length = 0; priv->sec_info.wep_enabled = 0; priv->sec_info.wpa_enabled = 0; priv->sec_info.wpa2_enabled = 0; return 0; } switch (params->auth_type) { case NL80211_AUTHTYPE_OPEN_SYSTEM: bss_config->auth_mode = WLAN_AUTH_OPEN; break; case NL80211_AUTHTYPE_SHARED_KEY: bss_config->auth_mode = WLAN_AUTH_SHARED_KEY; break; case NL80211_AUTHTYPE_NETWORK_EAP: bss_config->auth_mode = WLAN_AUTH_LEAP; break; default: bss_config->auth_mode = MWIFIEX_AUTH_MODE_AUTO; break; } bss_config->key_mgmt_operation |= KEY_MGMT_ON_HOST; for (i = 0; i < params->crypto.n_akm_suites; i++) { switch (params->crypto.akm_suites[i]) { case WLAN_AKM_SUITE_8021X: if (params->crypto.wpa_versions & NL80211_WPA_VERSION_1) { bss_config->protocol = PROTOCOL_WPA; bss_config->key_mgmt = KEY_MGMT_EAP; } if (params->crypto.wpa_versions & NL80211_WPA_VERSION_2) { bss_config->protocol |= PROTOCOL_WPA2; bss_config->key_mgmt = KEY_MGMT_EAP; } break; case WLAN_AKM_SUITE_PSK: if (params->crypto.wpa_versions & NL80211_WPA_VERSION_1) { bss_config->protocol = PROTOCOL_WPA; bss_config->key_mgmt = KEY_MGMT_PSK; } if (params->crypto.wpa_versions & NL80211_WPA_VERSION_2) { bss_config->protocol |= PROTOCOL_WPA2; bss_config->key_mgmt = KEY_MGMT_PSK; } break; default: break; } } for (i = 0; i < params->crypto.n_ciphers_pairwise; i++) { switch (params->crypto.ciphers_pairwise[i]) { case WLAN_CIPHER_SUITE_WEP40: case WLAN_CIPHER_SUITE_WEP104: break; case WLAN_CIPHER_SUITE_TKIP: if (params->crypto.wpa_versions & NL80211_WPA_VERSION_1) bss_config->wpa_cfg.pairwise_cipher_wpa |= CIPHER_TKIP; if (params->crypto.wpa_versions & NL80211_WPA_VERSION_2) bss_config->wpa_cfg.pairwise_cipher_wpa2 |= CIPHER_TKIP; break; case WLAN_CIPHER_SUITE_CCMP: if (params->crypto.wpa_versions & NL80211_WPA_VERSION_1) bss_config->wpa_cfg.pairwise_cipher_wpa |= CIPHER_AES_CCMP; if (params->crypto.wpa_versions & NL80211_WPA_VERSION_2) bss_config->wpa_cfg.pairwise_cipher_wpa2 |= CIPHER_AES_CCMP; default: break; } } switch (params->crypto.cipher_group) { case WLAN_CIPHER_SUITE_WEP40: case WLAN_CIPHER_SUITE_WEP104: if (priv->sec_info.wep_enabled) { bss_config->protocol = PROTOCOL_STATIC_WEP; bss_config->key_mgmt = KEY_MGMT_NONE; bss_config->wpa_cfg.length = 0; for (i = 0; i < NUM_WEP_KEYS; i++) { wep_key = priv->wep_key[i]; bss_config->wep_cfg[i].key_index = i; if (priv->wep_key_curr_index == i) bss_config->wep_cfg[i].is_default = 1; else bss_config->wep_cfg[i].is_default = 0; bss_config->wep_cfg[i].length = wep_key.key_length; memcpy(&bss_config->wep_cfg[i].key, &wep_key.key_material, wep_key.key_length); } } break; case WLAN_CIPHER_SUITE_TKIP: bss_config->wpa_cfg.group_cipher = CIPHER_TKIP; break; case WLAN_CIPHER_SUITE_CCMP: bss_config->wpa_cfg.group_cipher = CIPHER_AES_CCMP; break; default: break; } return 0; } /* This function updates 11n related parameters from IE and sets them into * bss_config structure. */ void mwifiex_set_ht_params(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_cfg, struct cfg80211_ap_settings *params) { const u8 *ht_ie; if (!ISSUPP_11NENABLED(priv->adapter->fw_cap_info)) return; ht_ie = cfg80211_find_ie(WLAN_EID_HT_CAPABILITY, params->beacon.tail, params->beacon.tail_len); if (ht_ie) { memcpy(&bss_cfg->ht_cap, ht_ie + 2, sizeof(struct ieee80211_ht_cap)); priv->ap_11n_enabled = 1; } else { memset(&bss_cfg->ht_cap, 0, sizeof(struct ieee80211_ht_cap)); bss_cfg->ht_cap.cap_info = cpu_to_le16(MWIFIEX_DEF_HT_CAP); bss_cfg->ht_cap.ampdu_params_info = MWIFIEX_DEF_AMPDU; } return; } /* This function updates 11ac related parameters from IE * and sets them into bss_config structure. */ void mwifiex_set_vht_params(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_cfg, struct cfg80211_ap_settings *params) { const u8 *vht_ie; vht_ie = cfg80211_find_ie(WLAN_EID_VHT_CAPABILITY, params->beacon.tail, params->beacon.tail_len); if (vht_ie) { memcpy(&bss_cfg->vht_cap, vht_ie + 2, sizeof(struct ieee80211_vht_cap)); priv->ap_11ac_enabled = 1; } else { priv->ap_11ac_enabled = 0; } return; } /* This function updates 11ac related parameters from IE * and sets them into bss_config structure. */ void mwifiex_set_tpc_params(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_cfg, struct cfg80211_ap_settings *params) { const u8 *tpc_ie; tpc_ie = cfg80211_find_ie(WLAN_EID_TPC_REQUEST, params->beacon.tail, params->beacon.tail_len); if (tpc_ie) bss_cfg->power_constraint = *(tpc_ie + 2); else bss_cfg->power_constraint = 0; } /* Enable VHT only when cfg80211_ap_settings has VHT IE. * Otherwise disable VHT. */ void mwifiex_set_vht_width(struct mwifiex_private *priv, enum nl80211_chan_width width, bool ap_11ac_enable) { struct mwifiex_adapter *adapter = priv->adapter; struct mwifiex_11ac_vht_cfg vht_cfg; vht_cfg.band_config = VHT_CFG_5GHZ; vht_cfg.cap_info = adapter->hw_dot_11ac_dev_cap; if (!ap_11ac_enable) { vht_cfg.mcs_tx_set = DISABLE_VHT_MCS_SET; vht_cfg.mcs_rx_set = DISABLE_VHT_MCS_SET; } else { vht_cfg.mcs_tx_set = DEFAULT_VHT_MCS_SET; vht_cfg.mcs_rx_set = DEFAULT_VHT_MCS_SET; } vht_cfg.misc_config = VHT_CAP_UAP_ONLY; if (ap_11ac_enable && width >= NL80211_CHAN_WIDTH_80) vht_cfg.misc_config |= VHT_BW_80_160_80P80; mwifiex_send_cmd(priv, HostCmd_CMD_11AC_CFG, HostCmd_ACT_GEN_SET, 0, &vht_cfg, true); return; } /* This function finds supported rates IE from beacon parameter and sets * these rates into bss_config structure. */ void mwifiex_set_uap_rates(struct mwifiex_uap_bss_param *bss_cfg, struct cfg80211_ap_settings *params) { struct ieee_types_header *rate_ie; int var_offset = offsetof(struct ieee80211_mgmt, u.beacon.variable); const u8 *var_pos = params->beacon.head + var_offset; int len = params->beacon.head_len - var_offset; u8 rate_len = 0; rate_ie = (void *)cfg80211_find_ie(WLAN_EID_SUPP_RATES, var_pos, len); if (rate_ie) { memcpy(bss_cfg->rates, rate_ie + 1, rate_ie->len); rate_len = rate_ie->len; } rate_ie = (void *)cfg80211_find_ie(WLAN_EID_EXT_SUPP_RATES, params->beacon.tail, params->beacon.tail_len); if (rate_ie) memcpy(bss_cfg->rates + rate_len, rate_ie + 1, rate_ie->len); return; } /* This function initializes some of mwifiex_uap_bss_param variables. * This helps FW in ignoring invalid values. These values may or may not * be get updated to valid ones at later stage. */ void mwifiex_set_sys_config_invalid_data(struct mwifiex_uap_bss_param *config) { config->bcast_ssid_ctl = 0x7F; config->radio_ctl = 0x7F; config->dtim_period = 0x7F; config->beacon_period = 0x7FFF; config->auth_mode = 0x7F; config->rts_threshold = 0x7FFF; config->frag_threshold = 0x7FFF; config->retry_limit = 0x7F; config->qos_info = 0xFF; } /* This function parses BSS related parameters from structure * and prepares TLVs specific to WPA/WPA2 security. * These TLVs are appended to command buffer. */ static void mwifiex_uap_bss_wpa(u8 **tlv_buf, void *cmd_buf, u16 *param_size) { struct host_cmd_tlv_pwk_cipher *pwk_cipher; struct host_cmd_tlv_gwk_cipher *gwk_cipher; struct host_cmd_tlv_passphrase *passphrase; struct host_cmd_tlv_akmp *tlv_akmp; struct mwifiex_uap_bss_param *bss_cfg = cmd_buf; u16 cmd_size = *param_size; u8 *tlv = *tlv_buf; tlv_akmp = (struct host_cmd_tlv_akmp *)tlv; tlv_akmp->header.type = cpu_to_le16(TLV_TYPE_UAP_AKMP); tlv_akmp->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_akmp) - sizeof(struct mwifiex_ie_types_header)); tlv_akmp->key_mgmt_operation = cpu_to_le16(bss_cfg->key_mgmt_operation); tlv_akmp->key_mgmt = cpu_to_le16(bss_cfg->key_mgmt); cmd_size += sizeof(struct host_cmd_tlv_akmp); tlv += sizeof(struct host_cmd_tlv_akmp); if (bss_cfg->wpa_cfg.pairwise_cipher_wpa & VALID_CIPHER_BITMAP) { pwk_cipher = (struct host_cmd_tlv_pwk_cipher *)tlv; pwk_cipher->header.type = cpu_to_le16(TLV_TYPE_PWK_CIPHER); pwk_cipher->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_pwk_cipher) - sizeof(struct mwifiex_ie_types_header)); pwk_cipher->proto = cpu_to_le16(PROTOCOL_WPA); pwk_cipher->cipher = bss_cfg->wpa_cfg.pairwise_cipher_wpa; cmd_size += sizeof(struct host_cmd_tlv_pwk_cipher); tlv += sizeof(struct host_cmd_tlv_pwk_cipher); } if (bss_cfg->wpa_cfg.pairwise_cipher_wpa2 & VALID_CIPHER_BITMAP) { pwk_cipher = (struct host_cmd_tlv_pwk_cipher *)tlv; pwk_cipher->header.type = cpu_to_le16(TLV_TYPE_PWK_CIPHER); pwk_cipher->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_pwk_cipher) - sizeof(struct mwifiex_ie_types_header)); pwk_cipher->proto = cpu_to_le16(PROTOCOL_WPA2); pwk_cipher->cipher = bss_cfg->wpa_cfg.pairwise_cipher_wpa2; cmd_size += sizeof(struct host_cmd_tlv_pwk_cipher); tlv += sizeof(struct host_cmd_tlv_pwk_cipher); } if (bss_cfg->wpa_cfg.group_cipher & VALID_CIPHER_BITMAP) { gwk_cipher = (struct host_cmd_tlv_gwk_cipher *)tlv; gwk_cipher->header.type = cpu_to_le16(TLV_TYPE_GWK_CIPHER); gwk_cipher->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_gwk_cipher) - sizeof(struct mwifiex_ie_types_header)); gwk_cipher->cipher = bss_cfg->wpa_cfg.group_cipher; cmd_size += sizeof(struct host_cmd_tlv_gwk_cipher); tlv += sizeof(struct host_cmd_tlv_gwk_cipher); } if (bss_cfg->wpa_cfg.length) { passphrase = (struct host_cmd_tlv_passphrase *)tlv; passphrase->header.type = cpu_to_le16(TLV_TYPE_UAP_WPA_PASSPHRASE); passphrase->header.len = cpu_to_le16(bss_cfg->wpa_cfg.length); memcpy(passphrase->passphrase, bss_cfg->wpa_cfg.passphrase, bss_cfg->wpa_cfg.length); cmd_size += sizeof(struct mwifiex_ie_types_header) + bss_cfg->wpa_cfg.length; tlv += sizeof(struct mwifiex_ie_types_header) + bss_cfg->wpa_cfg.length; } *param_size = cmd_size; *tlv_buf = tlv; return; } /* This function parses WMM related parameters from cfg80211_ap_settings * structure and updates bss_config structure. */ void mwifiex_set_wmm_params(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_cfg, struct cfg80211_ap_settings *params) { const u8 *vendor_ie; const u8 *wmm_ie; u8 wmm_oui[] = {0x00, 0x50, 0xf2, 0x02}; vendor_ie = cfg80211_find_vendor_ie(WLAN_OUI_MICROSOFT, WLAN_OUI_TYPE_MICROSOFT_WMM, params->beacon.tail, params->beacon.tail_len); if (vendor_ie) { wmm_ie = vendor_ie; memcpy(&bss_cfg->wmm_info, wmm_ie + sizeof(struct ieee_types_header), *(wmm_ie + 1)); priv->wmm_enabled = 1; } else { memset(&bss_cfg->wmm_info, 0, sizeof(bss_cfg->wmm_info)); memcpy(&bss_cfg->wmm_info.oui, wmm_oui, sizeof(wmm_oui)); bss_cfg->wmm_info.subtype = MWIFIEX_WMM_SUBTYPE; bss_cfg->wmm_info.version = MWIFIEX_WMM_VERSION; priv->wmm_enabled = 0; } bss_cfg->qos_info = 0x00; return; } /* This function parses BSS related parameters from structure * and prepares TLVs specific to WEP encryption. * These TLVs are appended to command buffer. */ static void mwifiex_uap_bss_wep(u8 **tlv_buf, void *cmd_buf, u16 *param_size) { struct host_cmd_tlv_wep_key *wep_key; u16 cmd_size = *param_size; int i; u8 *tlv = *tlv_buf; struct mwifiex_uap_bss_param *bss_cfg = cmd_buf; for (i = 0; i < NUM_WEP_KEYS; i++) { if (bss_cfg->wep_cfg[i].length && (bss_cfg->wep_cfg[i].length == WLAN_KEY_LEN_WEP40 || bss_cfg->wep_cfg[i].length == WLAN_KEY_LEN_WEP104)) { wep_key = (struct host_cmd_tlv_wep_key *)tlv; wep_key->header.type = cpu_to_le16(TLV_TYPE_UAP_WEP_KEY); wep_key->header.len = cpu_to_le16(bss_cfg->wep_cfg[i].length + 2); wep_key->key_index = bss_cfg->wep_cfg[i].key_index; wep_key->is_default = bss_cfg->wep_cfg[i].is_default; memcpy(wep_key->key, bss_cfg->wep_cfg[i].key, bss_cfg->wep_cfg[i].length); cmd_size += sizeof(struct mwifiex_ie_types_header) + 2 + bss_cfg->wep_cfg[i].length; tlv += sizeof(struct mwifiex_ie_types_header) + 2 + bss_cfg->wep_cfg[i].length; } } *param_size = cmd_size; *tlv_buf = tlv; return; } /* This function enable 11D if userspace set the country IE. */ void mwifiex_config_uap_11d(struct mwifiex_private *priv, struct cfg80211_beacon_data *beacon_data) { enum state_11d_t state_11d; const u8 *country_ie; country_ie = cfg80211_find_ie(WLAN_EID_COUNTRY, beacon_data->tail, beacon_data->tail_len); if (country_ie) { /* Send cmd to FW to enable 11D function */ state_11d = ENABLE_11D; if (mwifiex_send_cmd(priv, HostCmd_CMD_802_11_SNMP_MIB, HostCmd_ACT_GEN_SET, DOT11D_I, &state_11d, true)) { mwifiex_dbg(priv->adapter, ERROR, "11D: failed to enable 11D\n"); } } } /* This function parses BSS related parameters from structure * and prepares TLVs. These TLVs are appended to command buffer. */ static int mwifiex_uap_bss_param_prepare(u8 *tlv, void *cmd_buf, u16 *param_size) { struct host_cmd_tlv_dtim_period *dtim_period; struct host_cmd_tlv_beacon_period *beacon_period; struct host_cmd_tlv_ssid *ssid; struct host_cmd_tlv_bcast_ssid *bcast_ssid; struct host_cmd_tlv_channel_band *chan_band; struct host_cmd_tlv_frag_threshold *frag_threshold; struct host_cmd_tlv_rts_threshold *rts_threshold; struct host_cmd_tlv_retry_limit *retry_limit; struct host_cmd_tlv_encrypt_protocol *encrypt_protocol; struct host_cmd_tlv_auth_type *auth_type; struct host_cmd_tlv_rates *tlv_rates; struct host_cmd_tlv_ageout_timer *ao_timer, *ps_ao_timer; struct host_cmd_tlv_power_constraint *pwr_ct; struct mwifiex_ie_types_htcap *htcap; struct mwifiex_ie_types_wmmcap *wmm_cap; struct mwifiex_uap_bss_param *bss_cfg = cmd_buf; int i; u16 cmd_size = *param_size; if (bss_cfg->ssid.ssid_len) { ssid = (struct host_cmd_tlv_ssid *)tlv; ssid->header.type = cpu_to_le16(TLV_TYPE_UAP_SSID); ssid->header.len = cpu_to_le16((u16)bss_cfg->ssid.ssid_len); memcpy(ssid->ssid, bss_cfg->ssid.ssid, bss_cfg->ssid.ssid_len); cmd_size += sizeof(struct mwifiex_ie_types_header) + bss_cfg->ssid.ssid_len; tlv += sizeof(struct mwifiex_ie_types_header) + bss_cfg->ssid.ssid_len; bcast_ssid = (struct host_cmd_tlv_bcast_ssid *)tlv; bcast_ssid->header.type = cpu_to_le16(TLV_TYPE_UAP_BCAST_SSID); bcast_ssid->header.len = cpu_to_le16(sizeof(bcast_ssid->bcast_ctl)); bcast_ssid->bcast_ctl = bss_cfg->bcast_ssid_ctl; cmd_size += sizeof(struct host_cmd_tlv_bcast_ssid); tlv += sizeof(struct host_cmd_tlv_bcast_ssid); } if (bss_cfg->rates[0]) { tlv_rates = (struct host_cmd_tlv_rates *)tlv; tlv_rates->header.type = cpu_to_le16(TLV_TYPE_UAP_RATES); for (i = 0; i < MWIFIEX_SUPPORTED_RATES && bss_cfg->rates[i]; i++) tlv_rates->rates[i] = bss_cfg->rates[i]; tlv_rates->header.len = cpu_to_le16(i); cmd_size += sizeof(struct host_cmd_tlv_rates) + i; tlv += sizeof(struct host_cmd_tlv_rates) + i; } if (bss_cfg->channel && (((bss_cfg->band_cfg & BIT(0)) == BAND_CONFIG_BG && bss_cfg->channel <= MAX_CHANNEL_BAND_BG) || ((bss_cfg->band_cfg & BIT(0)) == BAND_CONFIG_A && bss_cfg->channel <= MAX_CHANNEL_BAND_A))) { chan_band = (struct host_cmd_tlv_channel_band *)tlv; chan_band->header.type = cpu_to_le16(TLV_TYPE_CHANNELBANDLIST); chan_band->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_channel_band) - sizeof(struct mwifiex_ie_types_header)); chan_band->band_config = bss_cfg->band_cfg; chan_band->channel = bss_cfg->channel; cmd_size += sizeof(struct host_cmd_tlv_channel_band); tlv += sizeof(struct host_cmd_tlv_channel_band); } if (bss_cfg->beacon_period >= MIN_BEACON_PERIOD && bss_cfg->beacon_period <= MAX_BEACON_PERIOD) { beacon_period = (struct host_cmd_tlv_beacon_period *)tlv; beacon_period->header.type = cpu_to_le16(TLV_TYPE_UAP_BEACON_PERIOD); beacon_period->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_beacon_period) - sizeof(struct mwifiex_ie_types_header)); beacon_period->period = cpu_to_le16(bss_cfg->beacon_period); cmd_size += sizeof(struct host_cmd_tlv_beacon_period); tlv += sizeof(struct host_cmd_tlv_beacon_period); } if (bss_cfg->dtim_period >= MIN_DTIM_PERIOD && bss_cfg->dtim_period <= MAX_DTIM_PERIOD) { dtim_period = (struct host_cmd_tlv_dtim_period *)tlv; dtim_period->header.type = cpu_to_le16(TLV_TYPE_UAP_DTIM_PERIOD); dtim_period->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_dtim_period) - sizeof(struct mwifiex_ie_types_header)); dtim_period->period = bss_cfg->dtim_period; cmd_size += sizeof(struct host_cmd_tlv_dtim_period); tlv += sizeof(struct host_cmd_tlv_dtim_period); } if (bss_cfg->rts_threshold <= MWIFIEX_RTS_MAX_VALUE) { rts_threshold = (struct host_cmd_tlv_rts_threshold *)tlv; rts_threshold->header.type = cpu_to_le16(TLV_TYPE_UAP_RTS_THRESHOLD); rts_threshold->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_rts_threshold) - sizeof(struct mwifiex_ie_types_header)); rts_threshold->rts_thr = cpu_to_le16(bss_cfg->rts_threshold); cmd_size += sizeof(struct host_cmd_tlv_frag_threshold); tlv += sizeof(struct host_cmd_tlv_frag_threshold); } if ((bss_cfg->frag_threshold >= MWIFIEX_FRAG_MIN_VALUE) && (bss_cfg->frag_threshold <= MWIFIEX_FRAG_MAX_VALUE)) { frag_threshold = (struct host_cmd_tlv_frag_threshold *)tlv; frag_threshold->header.type = cpu_to_le16(TLV_TYPE_UAP_FRAG_THRESHOLD); frag_threshold->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_frag_threshold) - sizeof(struct mwifiex_ie_types_header)); frag_threshold->frag_thr = cpu_to_le16(bss_cfg->frag_threshold); cmd_size += sizeof(struct host_cmd_tlv_frag_threshold); tlv += sizeof(struct host_cmd_tlv_frag_threshold); } if (bss_cfg->retry_limit <= MWIFIEX_RETRY_LIMIT) { retry_limit = (struct host_cmd_tlv_retry_limit *)tlv; retry_limit->header.type = cpu_to_le16(TLV_TYPE_UAP_RETRY_LIMIT); retry_limit->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_retry_limit) - sizeof(struct mwifiex_ie_types_header)); retry_limit->limit = (u8)bss_cfg->retry_limit; cmd_size += sizeof(struct host_cmd_tlv_retry_limit); tlv += sizeof(struct host_cmd_tlv_retry_limit); } if ((bss_cfg->protocol & PROTOCOL_WPA) || (bss_cfg->protocol & PROTOCOL_WPA2) || (bss_cfg->protocol & PROTOCOL_EAP)) mwifiex_uap_bss_wpa(&tlv, cmd_buf, &cmd_size); else mwifiex_uap_bss_wep(&tlv, cmd_buf, &cmd_size); if ((bss_cfg->auth_mode <= WLAN_AUTH_SHARED_KEY) || (bss_cfg->auth_mode == MWIFIEX_AUTH_MODE_AUTO)) { auth_type = (struct host_cmd_tlv_auth_type *)tlv; auth_type->header.type = cpu_to_le16(TLV_TYPE_AUTH_TYPE); auth_type->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_auth_type) - sizeof(struct mwifiex_ie_types_header)); auth_type->auth_type = (u8)bss_cfg->auth_mode; cmd_size += sizeof(struct host_cmd_tlv_auth_type); tlv += sizeof(struct host_cmd_tlv_auth_type); } if (bss_cfg->protocol) { encrypt_protocol = (struct host_cmd_tlv_encrypt_protocol *)tlv; encrypt_protocol->header.type = cpu_to_le16(TLV_TYPE_UAP_ENCRY_PROTOCOL); encrypt_protocol->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_encrypt_protocol) - sizeof(struct mwifiex_ie_types_header)); encrypt_protocol->proto = cpu_to_le16(bss_cfg->protocol); cmd_size += sizeof(struct host_cmd_tlv_encrypt_protocol); tlv += sizeof(struct host_cmd_tlv_encrypt_protocol); } if (bss_cfg->ht_cap.cap_info) { htcap = (struct mwifiex_ie_types_htcap *)tlv; htcap->header.type = cpu_to_le16(WLAN_EID_HT_CAPABILITY); htcap->header.len = cpu_to_le16(sizeof(struct ieee80211_ht_cap)); htcap->ht_cap.cap_info = bss_cfg->ht_cap.cap_info; htcap->ht_cap.ampdu_params_info = bss_cfg->ht_cap.ampdu_params_info; memcpy(&htcap->ht_cap.mcs, &bss_cfg->ht_cap.mcs, sizeof(struct ieee80211_mcs_info)); htcap->ht_cap.extended_ht_cap_info = bss_cfg->ht_cap.extended_ht_cap_info; htcap->ht_cap.tx_BF_cap_info = bss_cfg->ht_cap.tx_BF_cap_info; htcap->ht_cap.antenna_selection_info = bss_cfg->ht_cap.antenna_selection_info; cmd_size += sizeof(struct mwifiex_ie_types_htcap); tlv += sizeof(struct mwifiex_ie_types_htcap); } if (bss_cfg->wmm_info.qos_info != 0xFF) { wmm_cap = (struct mwifiex_ie_types_wmmcap *)tlv; wmm_cap->header.type = cpu_to_le16(WLAN_EID_VENDOR_SPECIFIC); wmm_cap->header.len = cpu_to_le16(sizeof(wmm_cap->wmm_info)); memcpy(&wmm_cap->wmm_info, &bss_cfg->wmm_info, sizeof(wmm_cap->wmm_info)); cmd_size += sizeof(struct mwifiex_ie_types_wmmcap); tlv += sizeof(struct mwifiex_ie_types_wmmcap); } if (bss_cfg->sta_ao_timer) { ao_timer = (struct host_cmd_tlv_ageout_timer *)tlv; ao_timer->header.type = cpu_to_le16(TLV_TYPE_UAP_AO_TIMER); ao_timer->header.len = cpu_to_le16(sizeof(*ao_timer) - sizeof(struct mwifiex_ie_types_header)); ao_timer->sta_ao_timer = cpu_to_le32(bss_cfg->sta_ao_timer); cmd_size += sizeof(*ao_timer); tlv += sizeof(*ao_timer); } if (bss_cfg->power_constraint) { pwr_ct = (void *)tlv; pwr_ct->header.type = cpu_to_le16(TLV_TYPE_PWR_CONSTRAINT); pwr_ct->header.len = cpu_to_le16(sizeof(u8)); pwr_ct->constraint = bss_cfg->power_constraint; cmd_size += sizeof(*pwr_ct); tlv += sizeof(*pwr_ct); } if (bss_cfg->ps_sta_ao_timer) { ps_ao_timer = (struct host_cmd_tlv_ageout_timer *)tlv; ps_ao_timer->header.type = cpu_to_le16(TLV_TYPE_UAP_PS_AO_TIMER); ps_ao_timer->header.len = cpu_to_le16(sizeof(*ps_ao_timer) - sizeof(struct mwifiex_ie_types_header)); ps_ao_timer->sta_ao_timer = cpu_to_le32(bss_cfg->ps_sta_ao_timer); cmd_size += sizeof(*ps_ao_timer); tlv += sizeof(*ps_ao_timer); } *param_size = cmd_size; return 0; } /* This function parses custom IEs from IE list and prepares command buffer */ static int mwifiex_uap_custom_ie_prepare(u8 *tlv, void *cmd_buf, u16 *ie_size) { struct mwifiex_ie_list *ap_ie = cmd_buf; struct mwifiex_ie_types_header *tlv_ie = (void *)tlv; if (!ap_ie || !ap_ie->len) return -1; *ie_size += le16_to_cpu(ap_ie->len) + sizeof(struct mwifiex_ie_types_header); tlv_ie->type = cpu_to_le16(TLV_TYPE_MGMT_IE); tlv_ie->len = ap_ie->len; tlv += sizeof(struct mwifiex_ie_types_header); memcpy(tlv, ap_ie->ie_list, le16_to_cpu(ap_ie->len)); return 0; } /* Parse AP config structure and prepare TLV based command structure * to be sent to FW for uAP configuration */ static int mwifiex_cmd_uap_sys_config(struct host_cmd_ds_command *cmd, u16 cmd_action, u32 type, void *cmd_buf) { u8 *tlv; u16 cmd_size, param_size, ie_size; struct host_cmd_ds_sys_config *sys_cfg; cmd->command = cpu_to_le16(HostCmd_CMD_UAP_SYS_CONFIG); cmd_size = (u16)(sizeof(struct host_cmd_ds_sys_config) + S_DS_GEN); sys_cfg = (struct host_cmd_ds_sys_config *)&cmd->params.uap_sys_config; sys_cfg->action = cpu_to_le16(cmd_action); tlv = sys_cfg->tlv; switch (type) { case UAP_BSS_PARAMS_I: param_size = cmd_size; if (mwifiex_uap_bss_param_prepare(tlv, cmd_buf, &param_size)) return -1; cmd->size = cpu_to_le16(param_size); break; case UAP_CUSTOM_IE_I: ie_size = cmd_size; if (mwifiex_uap_custom_ie_prepare(tlv, cmd_buf, &ie_size)) return -1; cmd->size = cpu_to_le16(ie_size); break; default: return -1; } return 0; } /* This function prepares AP specific deauth command with mac supplied in * function parameter. */ static int mwifiex_cmd_uap_sta_deauth(struct mwifiex_private *priv, struct host_cmd_ds_command *cmd, u8 *mac) { struct host_cmd_ds_sta_deauth *sta_deauth = &cmd->params.sta_deauth; cmd->command = cpu_to_le16(HostCmd_CMD_UAP_STA_DEAUTH); memcpy(sta_deauth->mac, mac, ETH_ALEN); sta_deauth->reason = cpu_to_le16(WLAN_REASON_DEAUTH_LEAVING); cmd->size = cpu_to_le16(sizeof(struct host_cmd_ds_sta_deauth) + S_DS_GEN); return 0; } /* This function prepares the AP specific commands before sending them * to the firmware. * This is a generic function which calls specific command preparation * routines based upon the command number. */ int mwifiex_uap_prepare_cmd(struct mwifiex_private *priv, u16 cmd_no, u16 cmd_action, u32 type, void *data_buf, void *cmd_buf) { struct host_cmd_ds_command *cmd = cmd_buf; switch (cmd_no) { case HostCmd_CMD_UAP_SYS_CONFIG: if (mwifiex_cmd_uap_sys_config(cmd, cmd_action, type, data_buf)) return -1; break; case HostCmd_CMD_UAP_BSS_START: case HostCmd_CMD_UAP_BSS_STOP: case HOST_CMD_APCMD_SYS_RESET: case HOST_CMD_APCMD_STA_LIST: cmd->command = cpu_to_le16(cmd_no); cmd->size = cpu_to_le16(S_DS_GEN); break; case HostCmd_CMD_UAP_STA_DEAUTH: if (mwifiex_cmd_uap_sta_deauth(priv, cmd, data_buf)) return -1; break; case HostCmd_CMD_CHAN_REPORT_REQUEST: if (mwifiex_cmd_issue_chan_report_request(priv, cmd_buf, data_buf)) return -1; break; default: mwifiex_dbg(priv->adapter, ERROR, "PREP_CMD: unknown cmd %#x\n", cmd_no); return -1; } return 0; } void mwifiex_uap_set_channel(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_cfg, struct cfg80211_chan_def chandef) { u8 config_bands = 0, old_bands = priv->adapter->config_bands; priv->bss_chandef = chandef; bss_cfg->channel = ieee80211_frequency_to_channel( chandef.chan->center_freq); /* Set appropriate bands */ if (chandef.chan->band == NL80211_BAND_2GHZ) { bss_cfg->band_cfg = BAND_CONFIG_BG; config_bands = BAND_B | BAND_G; if (chandef.width > NL80211_CHAN_WIDTH_20_NOHT) config_bands |= BAND_GN; } else { bss_cfg->band_cfg = BAND_CONFIG_A; config_bands = BAND_A; if (chandef.width > NL80211_CHAN_WIDTH_20_NOHT) config_bands |= BAND_AN; if (chandef.width > NL80211_CHAN_WIDTH_40) config_bands |= BAND_AAC; } switch (chandef.width) { case NL80211_CHAN_WIDTH_5: case NL80211_CHAN_WIDTH_10: case NL80211_CHAN_WIDTH_20_NOHT: case NL80211_CHAN_WIDTH_20: break; case NL80211_CHAN_WIDTH_40: if (chandef.center_freq1 < chandef.chan->center_freq) bss_cfg->band_cfg |= MWIFIEX_SEC_CHAN_BELOW; else bss_cfg->band_cfg |= MWIFIEX_SEC_CHAN_ABOVE; break; case NL80211_CHAN_WIDTH_80: case NL80211_CHAN_WIDTH_80P80: case NL80211_CHAN_WIDTH_160: bss_cfg->band_cfg |= mwifiex_get_sec_chan_offset(bss_cfg->channel) << 4; break; default: mwifiex_dbg(priv->adapter, WARN, "Unknown channel width: %d\n", chandef.width); break; } priv->adapter->config_bands = config_bands; if (old_bands != config_bands) { mwifiex_send_domain_info_cmd_fw(priv->adapter->wiphy); mwifiex_dnld_txpwr_table(priv); } } int mwifiex_config_start_uap(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_cfg) { if (mwifiex_send_cmd(priv, HostCmd_CMD_UAP_SYS_CONFIG, HostCmd_ACT_GEN_SET, UAP_BSS_PARAMS_I, bss_cfg, true)) { mwifiex_dbg(priv->adapter, ERROR, "Failed to set AP configuration\n"); return -1; } if (mwifiex_send_cmd(priv, HostCmd_CMD_UAP_BSS_START, HostCmd_ACT_GEN_SET, 0, NULL, true)) { mwifiex_dbg(priv->adapter, ERROR, "Failed to start the BSS\n"); return -1; } if (priv->sec_info.wep_enabled) priv->curr_pkt_filter |= HostCmd_ACT_MAC_WEP_ENABLE; else priv->curr_pkt_filter &= ~HostCmd_ACT_MAC_WEP_ENABLE; if (mwifiex_send_cmd(priv, HostCmd_CMD_MAC_CONTROL, HostCmd_ACT_GEN_SET, 0, &priv->curr_pkt_filter, true)) return -1; return 0; }
null
/* * Marvell Wireless LAN device driver: AP specific command handling * * Copyright (C) 2012-2014, Marvell International Ltd. * * This software file (the "File") is distributed by Marvell International * Ltd. under the terms of the GNU General Public License Version 2, June 1991 * (the "License"). You may use, redistribute and/or modify this File in * accordance with the terms and conditions of the License, a copy of which * is available by writing to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the * worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE * IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE * ARE EXPRESSLY DISCLAIMED. The License provides additional details about * this warranty disclaimer. */ #include "main.h" #include "11ac.h" #include "11n.h" /* This function parses security related parameters from cfg80211_ap_settings * and sets into FW understandable bss_config structure. */ int mwifiex_set_secure_params(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_config, struct cfg80211_ap_settings *params) { int i; struct mwifiex_wep_key wep_key; if (!params->privacy) { bss_config->protocol = PROTOCOL_NO_SECURITY; bss_config->key_mgmt = KEY_MGMT_NONE; bss_config->wpa_cfg.length = 0; priv->sec_info.wep_enabled = 0; priv->sec_info.wpa_enabled = 0; priv->sec_info.wpa2_enabled = 0; return 0; } switch (params->auth_type) { case NL80211_AUTHTYPE_OPEN_SYSTEM: bss_config->auth_mode = WLAN_AUTH_OPEN; break; case NL80211_AUTHTYPE_SHARED_KEY: bss_config->auth_mode = WLAN_AUTH_SHARED_KEY; break; case NL80211_AUTHTYPE_NETWORK_EAP: bss_config->auth_mode = WLAN_AUTH_LEAP; break; default: bss_config->auth_mode = MWIFIEX_AUTH_MODE_AUTO; break; } bss_config->key_mgmt_operation |= KEY_MGMT_ON_HOST; for (i = 0; i < params->crypto.n_akm_suites; i++) { switch (params->crypto.akm_suites[i]) { case WLAN_AKM_SUITE_8021X: if (params->crypto.wpa_versions & NL80211_WPA_VERSION_1) { bss_config->protocol = PROTOCOL_WPA; bss_config->key_mgmt = KEY_MGMT_EAP; } if (params->crypto.wpa_versions & NL80211_WPA_VERSION_2) { bss_config->protocol |= PROTOCOL_WPA2; bss_config->key_mgmt = KEY_MGMT_EAP; } break; case WLAN_AKM_SUITE_PSK: if (params->crypto.wpa_versions & NL80211_WPA_VERSION_1) { bss_config->protocol = PROTOCOL_WPA; bss_config->key_mgmt = KEY_MGMT_PSK; } if (params->crypto.wpa_versions & NL80211_WPA_VERSION_2) { bss_config->protocol |= PROTOCOL_WPA2; bss_config->key_mgmt = KEY_MGMT_PSK; } break; default: break; } } for (i = 0; i < params->crypto.n_ciphers_pairwise; i++) { switch (params->crypto.ciphers_pairwise[i]) { case WLAN_CIPHER_SUITE_WEP40: case WLAN_CIPHER_SUITE_WEP104: break; case WLAN_CIPHER_SUITE_TKIP: if (params->crypto.wpa_versions & NL80211_WPA_VERSION_1) bss_config->wpa_cfg.pairwise_cipher_wpa |= CIPHER_TKIP; if (params->crypto.wpa_versions & NL80211_WPA_VERSION_2) bss_config->wpa_cfg.pairwise_cipher_wpa2 |= CIPHER_TKIP; break; case WLAN_CIPHER_SUITE_CCMP: if (params->crypto.wpa_versions & NL80211_WPA_VERSION_1) bss_config->wpa_cfg.pairwise_cipher_wpa |= CIPHER_AES_CCMP; if (params->crypto.wpa_versions & NL80211_WPA_VERSION_2) bss_config->wpa_cfg.pairwise_cipher_wpa2 |= CIPHER_AES_CCMP; default: break; } } switch (params->crypto.cipher_group) { case WLAN_CIPHER_SUITE_WEP40: case WLAN_CIPHER_SUITE_WEP104: if (priv->sec_info.wep_enabled) { bss_config->protocol = PROTOCOL_STATIC_WEP; bss_config->key_mgmt = KEY_MGMT_NONE; bss_config->wpa_cfg.length = 0; for (i = 0; i < NUM_WEP_KEYS; i++) { wep_key = priv->wep_key[i]; bss_config->wep_cfg[i].key_index = i; if (priv->wep_key_curr_index == i) bss_config->wep_cfg[i].is_default = 1; else bss_config->wep_cfg[i].is_default = 0; bss_config->wep_cfg[i].length = wep_key.key_length; memcpy(&bss_config->wep_cfg[i].key, &wep_key.key_material, wep_key.key_length); } } break; case WLAN_CIPHER_SUITE_TKIP: bss_config->wpa_cfg.group_cipher = CIPHER_TKIP; break; case WLAN_CIPHER_SUITE_CCMP: bss_config->wpa_cfg.group_cipher = CIPHER_AES_CCMP; break; default: break; } return 0; } /* This function updates 11n related parameters from IE and sets them into * bss_config structure. */ void mwifiex_set_ht_params(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_cfg, struct cfg80211_ap_settings *params) { const u8 *ht_ie; if (!ISSUPP_11NENABLED(priv->adapter->fw_cap_info)) return; ht_ie = cfg80211_find_ie(WLAN_EID_HT_CAPABILITY, params->beacon.tail, params->beacon.tail_len); if (ht_ie) { memcpy(&bss_cfg->ht_cap, ht_ie + 2, sizeof(struct ieee80211_ht_cap)); priv->ap_11n_enabled = 1; } else { memset(&bss_cfg->ht_cap, 0, sizeof(struct ieee80211_ht_cap)); bss_cfg->ht_cap.cap_info = cpu_to_le16(MWIFIEX_DEF_HT_CAP); bss_cfg->ht_cap.ampdu_params_info = MWIFIEX_DEF_AMPDU; } return; } /* This function updates 11ac related parameters from IE * and sets them into bss_config structure. */ void mwifiex_set_vht_params(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_cfg, struct cfg80211_ap_settings *params) { const u8 *vht_ie; vht_ie = cfg80211_find_ie(WLAN_EID_VHT_CAPABILITY, params->beacon.tail, params->beacon.tail_len); if (vht_ie) { memcpy(&bss_cfg->vht_cap, vht_ie + 2, sizeof(struct ieee80211_vht_cap)); priv->ap_11ac_enabled = 1; } else { priv->ap_11ac_enabled = 0; } return; } /* This function updates 11ac related parameters from IE * and sets them into bss_config structure. */ void mwifiex_set_tpc_params(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_cfg, struct cfg80211_ap_settings *params) { const u8 *tpc_ie; tpc_ie = cfg80211_find_ie(WLAN_EID_TPC_REQUEST, params->beacon.tail, params->beacon.tail_len); if (tpc_ie) bss_cfg->power_constraint = *(tpc_ie + 2); else bss_cfg->power_constraint = 0; } /* Enable VHT only when cfg80211_ap_settings has VHT IE. * Otherwise disable VHT. */ void mwifiex_set_vht_width(struct mwifiex_private *priv, enum nl80211_chan_width width, bool ap_11ac_enable) { struct mwifiex_adapter *adapter = priv->adapter; struct mwifiex_11ac_vht_cfg vht_cfg; vht_cfg.band_config = VHT_CFG_5GHZ; vht_cfg.cap_info = adapter->hw_dot_11ac_dev_cap; if (!ap_11ac_enable) { vht_cfg.mcs_tx_set = DISABLE_VHT_MCS_SET; vht_cfg.mcs_rx_set = DISABLE_VHT_MCS_SET; } else { vht_cfg.mcs_tx_set = DEFAULT_VHT_MCS_SET; vht_cfg.mcs_rx_set = DEFAULT_VHT_MCS_SET; } vht_cfg.misc_config = VHT_CAP_UAP_ONLY; if (ap_11ac_enable && width >= NL80211_CHAN_WIDTH_80) vht_cfg.misc_config |= VHT_BW_80_160_80P80; mwifiex_send_cmd(priv, HostCmd_CMD_11AC_CFG, HostCmd_ACT_GEN_SET, 0, &vht_cfg, true); return; } /* This function finds supported rates IE from beacon parameter and sets * these rates into bss_config structure. */ void mwifiex_set_uap_rates(struct mwifiex_uap_bss_param *bss_cfg, struct cfg80211_ap_settings *params) { struct ieee_types_header *rate_ie; int var_offset = offsetof(struct ieee80211_mgmt, u.beacon.variable); const u8 *var_pos = params->beacon.head + var_offset; int len = params->beacon.head_len - var_offset; u8 rate_len = 0; rate_ie = (void *)cfg80211_find_ie(WLAN_EID_SUPP_RATES, var_pos, len); if (rate_ie) { if (rate_ie->len > MWIFIEX_SUPPORTED_RATES) return; memcpy(bss_cfg->rates, rate_ie + 1, rate_ie->len); rate_len = rate_ie->len; } rate_ie = (void *)cfg80211_find_ie(WLAN_EID_EXT_SUPP_RATES, params->beacon.tail, params->beacon.tail_len); if (rate_ie) { if (rate_ie->len > MWIFIEX_SUPPORTED_RATES - rate_len) return; memcpy(bss_cfg->rates + rate_len, rate_ie + 1, rate_ie->len); } return; } /* This function initializes some of mwifiex_uap_bss_param variables. * This helps FW in ignoring invalid values. These values may or may not * be get updated to valid ones at later stage. */ void mwifiex_set_sys_config_invalid_data(struct mwifiex_uap_bss_param *config) { config->bcast_ssid_ctl = 0x7F; config->radio_ctl = 0x7F; config->dtim_period = 0x7F; config->beacon_period = 0x7FFF; config->auth_mode = 0x7F; config->rts_threshold = 0x7FFF; config->frag_threshold = 0x7FFF; config->retry_limit = 0x7F; config->qos_info = 0xFF; } /* This function parses BSS related parameters from structure * and prepares TLVs specific to WPA/WPA2 security. * These TLVs are appended to command buffer. */ static void mwifiex_uap_bss_wpa(u8 **tlv_buf, void *cmd_buf, u16 *param_size) { struct host_cmd_tlv_pwk_cipher *pwk_cipher; struct host_cmd_tlv_gwk_cipher *gwk_cipher; struct host_cmd_tlv_passphrase *passphrase; struct host_cmd_tlv_akmp *tlv_akmp; struct mwifiex_uap_bss_param *bss_cfg = cmd_buf; u16 cmd_size = *param_size; u8 *tlv = *tlv_buf; tlv_akmp = (struct host_cmd_tlv_akmp *)tlv; tlv_akmp->header.type = cpu_to_le16(TLV_TYPE_UAP_AKMP); tlv_akmp->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_akmp) - sizeof(struct mwifiex_ie_types_header)); tlv_akmp->key_mgmt_operation = cpu_to_le16(bss_cfg->key_mgmt_operation); tlv_akmp->key_mgmt = cpu_to_le16(bss_cfg->key_mgmt); cmd_size += sizeof(struct host_cmd_tlv_akmp); tlv += sizeof(struct host_cmd_tlv_akmp); if (bss_cfg->wpa_cfg.pairwise_cipher_wpa & VALID_CIPHER_BITMAP) { pwk_cipher = (struct host_cmd_tlv_pwk_cipher *)tlv; pwk_cipher->header.type = cpu_to_le16(TLV_TYPE_PWK_CIPHER); pwk_cipher->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_pwk_cipher) - sizeof(struct mwifiex_ie_types_header)); pwk_cipher->proto = cpu_to_le16(PROTOCOL_WPA); pwk_cipher->cipher = bss_cfg->wpa_cfg.pairwise_cipher_wpa; cmd_size += sizeof(struct host_cmd_tlv_pwk_cipher); tlv += sizeof(struct host_cmd_tlv_pwk_cipher); } if (bss_cfg->wpa_cfg.pairwise_cipher_wpa2 & VALID_CIPHER_BITMAP) { pwk_cipher = (struct host_cmd_tlv_pwk_cipher *)tlv; pwk_cipher->header.type = cpu_to_le16(TLV_TYPE_PWK_CIPHER); pwk_cipher->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_pwk_cipher) - sizeof(struct mwifiex_ie_types_header)); pwk_cipher->proto = cpu_to_le16(PROTOCOL_WPA2); pwk_cipher->cipher = bss_cfg->wpa_cfg.pairwise_cipher_wpa2; cmd_size += sizeof(struct host_cmd_tlv_pwk_cipher); tlv += sizeof(struct host_cmd_tlv_pwk_cipher); } if (bss_cfg->wpa_cfg.group_cipher & VALID_CIPHER_BITMAP) { gwk_cipher = (struct host_cmd_tlv_gwk_cipher *)tlv; gwk_cipher->header.type = cpu_to_le16(TLV_TYPE_GWK_CIPHER); gwk_cipher->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_gwk_cipher) - sizeof(struct mwifiex_ie_types_header)); gwk_cipher->cipher = bss_cfg->wpa_cfg.group_cipher; cmd_size += sizeof(struct host_cmd_tlv_gwk_cipher); tlv += sizeof(struct host_cmd_tlv_gwk_cipher); } if (bss_cfg->wpa_cfg.length) { passphrase = (struct host_cmd_tlv_passphrase *)tlv; passphrase->header.type = cpu_to_le16(TLV_TYPE_UAP_WPA_PASSPHRASE); passphrase->header.len = cpu_to_le16(bss_cfg->wpa_cfg.length); memcpy(passphrase->passphrase, bss_cfg->wpa_cfg.passphrase, bss_cfg->wpa_cfg.length); cmd_size += sizeof(struct mwifiex_ie_types_header) + bss_cfg->wpa_cfg.length; tlv += sizeof(struct mwifiex_ie_types_header) + bss_cfg->wpa_cfg.length; } *param_size = cmd_size; *tlv_buf = tlv; return; } /* This function parses WMM related parameters from cfg80211_ap_settings * structure and updates bss_config structure. */ void mwifiex_set_wmm_params(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_cfg, struct cfg80211_ap_settings *params) { const u8 *vendor_ie; const u8 *wmm_ie; u8 wmm_oui[] = {0x00, 0x50, 0xf2, 0x02}; vendor_ie = cfg80211_find_vendor_ie(WLAN_OUI_MICROSOFT, WLAN_OUI_TYPE_MICROSOFT_WMM, params->beacon.tail, params->beacon.tail_len); if (vendor_ie) { wmm_ie = vendor_ie; if (*(wmm_ie + 1) > sizeof(struct mwifiex_types_wmm_info)) return; memcpy(&bss_cfg->wmm_info, wmm_ie + sizeof(struct ieee_types_header), *(wmm_ie + 1)); priv->wmm_enabled = 1; } else { memset(&bss_cfg->wmm_info, 0, sizeof(bss_cfg->wmm_info)); memcpy(&bss_cfg->wmm_info.oui, wmm_oui, sizeof(wmm_oui)); bss_cfg->wmm_info.subtype = MWIFIEX_WMM_SUBTYPE; bss_cfg->wmm_info.version = MWIFIEX_WMM_VERSION; priv->wmm_enabled = 0; } bss_cfg->qos_info = 0x00; return; } /* This function parses BSS related parameters from structure * and prepares TLVs specific to WEP encryption. * These TLVs are appended to command buffer. */ static void mwifiex_uap_bss_wep(u8 **tlv_buf, void *cmd_buf, u16 *param_size) { struct host_cmd_tlv_wep_key *wep_key; u16 cmd_size = *param_size; int i; u8 *tlv = *tlv_buf; struct mwifiex_uap_bss_param *bss_cfg = cmd_buf; for (i = 0; i < NUM_WEP_KEYS; i++) { if (bss_cfg->wep_cfg[i].length && (bss_cfg->wep_cfg[i].length == WLAN_KEY_LEN_WEP40 || bss_cfg->wep_cfg[i].length == WLAN_KEY_LEN_WEP104)) { wep_key = (struct host_cmd_tlv_wep_key *)tlv; wep_key->header.type = cpu_to_le16(TLV_TYPE_UAP_WEP_KEY); wep_key->header.len = cpu_to_le16(bss_cfg->wep_cfg[i].length + 2); wep_key->key_index = bss_cfg->wep_cfg[i].key_index; wep_key->is_default = bss_cfg->wep_cfg[i].is_default; memcpy(wep_key->key, bss_cfg->wep_cfg[i].key, bss_cfg->wep_cfg[i].length); cmd_size += sizeof(struct mwifiex_ie_types_header) + 2 + bss_cfg->wep_cfg[i].length; tlv += sizeof(struct mwifiex_ie_types_header) + 2 + bss_cfg->wep_cfg[i].length; } } *param_size = cmd_size; *tlv_buf = tlv; return; } /* This function enable 11D if userspace set the country IE. */ void mwifiex_config_uap_11d(struct mwifiex_private *priv, struct cfg80211_beacon_data *beacon_data) { enum state_11d_t state_11d; const u8 *country_ie; country_ie = cfg80211_find_ie(WLAN_EID_COUNTRY, beacon_data->tail, beacon_data->tail_len); if (country_ie) { /* Send cmd to FW to enable 11D function */ state_11d = ENABLE_11D; if (mwifiex_send_cmd(priv, HostCmd_CMD_802_11_SNMP_MIB, HostCmd_ACT_GEN_SET, DOT11D_I, &state_11d, true)) { mwifiex_dbg(priv->adapter, ERROR, "11D: failed to enable 11D\n"); } } } /* This function parses BSS related parameters from structure * and prepares TLVs. These TLVs are appended to command buffer. */ static int mwifiex_uap_bss_param_prepare(u8 *tlv, void *cmd_buf, u16 *param_size) { struct host_cmd_tlv_dtim_period *dtim_period; struct host_cmd_tlv_beacon_period *beacon_period; struct host_cmd_tlv_ssid *ssid; struct host_cmd_tlv_bcast_ssid *bcast_ssid; struct host_cmd_tlv_channel_band *chan_band; struct host_cmd_tlv_frag_threshold *frag_threshold; struct host_cmd_tlv_rts_threshold *rts_threshold; struct host_cmd_tlv_retry_limit *retry_limit; struct host_cmd_tlv_encrypt_protocol *encrypt_protocol; struct host_cmd_tlv_auth_type *auth_type; struct host_cmd_tlv_rates *tlv_rates; struct host_cmd_tlv_ageout_timer *ao_timer, *ps_ao_timer; struct host_cmd_tlv_power_constraint *pwr_ct; struct mwifiex_ie_types_htcap *htcap; struct mwifiex_ie_types_wmmcap *wmm_cap; struct mwifiex_uap_bss_param *bss_cfg = cmd_buf; int i; u16 cmd_size = *param_size; if (bss_cfg->ssid.ssid_len) { ssid = (struct host_cmd_tlv_ssid *)tlv; ssid->header.type = cpu_to_le16(TLV_TYPE_UAP_SSID); ssid->header.len = cpu_to_le16((u16)bss_cfg->ssid.ssid_len); memcpy(ssid->ssid, bss_cfg->ssid.ssid, bss_cfg->ssid.ssid_len); cmd_size += sizeof(struct mwifiex_ie_types_header) + bss_cfg->ssid.ssid_len; tlv += sizeof(struct mwifiex_ie_types_header) + bss_cfg->ssid.ssid_len; bcast_ssid = (struct host_cmd_tlv_bcast_ssid *)tlv; bcast_ssid->header.type = cpu_to_le16(TLV_TYPE_UAP_BCAST_SSID); bcast_ssid->header.len = cpu_to_le16(sizeof(bcast_ssid->bcast_ctl)); bcast_ssid->bcast_ctl = bss_cfg->bcast_ssid_ctl; cmd_size += sizeof(struct host_cmd_tlv_bcast_ssid); tlv += sizeof(struct host_cmd_tlv_bcast_ssid); } if (bss_cfg->rates[0]) { tlv_rates = (struct host_cmd_tlv_rates *)tlv; tlv_rates->header.type = cpu_to_le16(TLV_TYPE_UAP_RATES); for (i = 0; i < MWIFIEX_SUPPORTED_RATES && bss_cfg->rates[i]; i++) tlv_rates->rates[i] = bss_cfg->rates[i]; tlv_rates->header.len = cpu_to_le16(i); cmd_size += sizeof(struct host_cmd_tlv_rates) + i; tlv += sizeof(struct host_cmd_tlv_rates) + i; } if (bss_cfg->channel && (((bss_cfg->band_cfg & BIT(0)) == BAND_CONFIG_BG && bss_cfg->channel <= MAX_CHANNEL_BAND_BG) || ((bss_cfg->band_cfg & BIT(0)) == BAND_CONFIG_A && bss_cfg->channel <= MAX_CHANNEL_BAND_A))) { chan_band = (struct host_cmd_tlv_channel_band *)tlv; chan_band->header.type = cpu_to_le16(TLV_TYPE_CHANNELBANDLIST); chan_band->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_channel_band) - sizeof(struct mwifiex_ie_types_header)); chan_band->band_config = bss_cfg->band_cfg; chan_band->channel = bss_cfg->channel; cmd_size += sizeof(struct host_cmd_tlv_channel_band); tlv += sizeof(struct host_cmd_tlv_channel_band); } if (bss_cfg->beacon_period >= MIN_BEACON_PERIOD && bss_cfg->beacon_period <= MAX_BEACON_PERIOD) { beacon_period = (struct host_cmd_tlv_beacon_period *)tlv; beacon_period->header.type = cpu_to_le16(TLV_TYPE_UAP_BEACON_PERIOD); beacon_period->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_beacon_period) - sizeof(struct mwifiex_ie_types_header)); beacon_period->period = cpu_to_le16(bss_cfg->beacon_period); cmd_size += sizeof(struct host_cmd_tlv_beacon_period); tlv += sizeof(struct host_cmd_tlv_beacon_period); } if (bss_cfg->dtim_period >= MIN_DTIM_PERIOD && bss_cfg->dtim_period <= MAX_DTIM_PERIOD) { dtim_period = (struct host_cmd_tlv_dtim_period *)tlv; dtim_period->header.type = cpu_to_le16(TLV_TYPE_UAP_DTIM_PERIOD); dtim_period->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_dtim_period) - sizeof(struct mwifiex_ie_types_header)); dtim_period->period = bss_cfg->dtim_period; cmd_size += sizeof(struct host_cmd_tlv_dtim_period); tlv += sizeof(struct host_cmd_tlv_dtim_period); } if (bss_cfg->rts_threshold <= MWIFIEX_RTS_MAX_VALUE) { rts_threshold = (struct host_cmd_tlv_rts_threshold *)tlv; rts_threshold->header.type = cpu_to_le16(TLV_TYPE_UAP_RTS_THRESHOLD); rts_threshold->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_rts_threshold) - sizeof(struct mwifiex_ie_types_header)); rts_threshold->rts_thr = cpu_to_le16(bss_cfg->rts_threshold); cmd_size += sizeof(struct host_cmd_tlv_frag_threshold); tlv += sizeof(struct host_cmd_tlv_frag_threshold); } if ((bss_cfg->frag_threshold >= MWIFIEX_FRAG_MIN_VALUE) && (bss_cfg->frag_threshold <= MWIFIEX_FRAG_MAX_VALUE)) { frag_threshold = (struct host_cmd_tlv_frag_threshold *)tlv; frag_threshold->header.type = cpu_to_le16(TLV_TYPE_UAP_FRAG_THRESHOLD); frag_threshold->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_frag_threshold) - sizeof(struct mwifiex_ie_types_header)); frag_threshold->frag_thr = cpu_to_le16(bss_cfg->frag_threshold); cmd_size += sizeof(struct host_cmd_tlv_frag_threshold); tlv += sizeof(struct host_cmd_tlv_frag_threshold); } if (bss_cfg->retry_limit <= MWIFIEX_RETRY_LIMIT) { retry_limit = (struct host_cmd_tlv_retry_limit *)tlv; retry_limit->header.type = cpu_to_le16(TLV_TYPE_UAP_RETRY_LIMIT); retry_limit->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_retry_limit) - sizeof(struct mwifiex_ie_types_header)); retry_limit->limit = (u8)bss_cfg->retry_limit; cmd_size += sizeof(struct host_cmd_tlv_retry_limit); tlv += sizeof(struct host_cmd_tlv_retry_limit); } if ((bss_cfg->protocol & PROTOCOL_WPA) || (bss_cfg->protocol & PROTOCOL_WPA2) || (bss_cfg->protocol & PROTOCOL_EAP)) mwifiex_uap_bss_wpa(&tlv, cmd_buf, &cmd_size); else mwifiex_uap_bss_wep(&tlv, cmd_buf, &cmd_size); if ((bss_cfg->auth_mode <= WLAN_AUTH_SHARED_KEY) || (bss_cfg->auth_mode == MWIFIEX_AUTH_MODE_AUTO)) { auth_type = (struct host_cmd_tlv_auth_type *)tlv; auth_type->header.type = cpu_to_le16(TLV_TYPE_AUTH_TYPE); auth_type->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_auth_type) - sizeof(struct mwifiex_ie_types_header)); auth_type->auth_type = (u8)bss_cfg->auth_mode; cmd_size += sizeof(struct host_cmd_tlv_auth_type); tlv += sizeof(struct host_cmd_tlv_auth_type); } if (bss_cfg->protocol) { encrypt_protocol = (struct host_cmd_tlv_encrypt_protocol *)tlv; encrypt_protocol->header.type = cpu_to_le16(TLV_TYPE_UAP_ENCRY_PROTOCOL); encrypt_protocol->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_encrypt_protocol) - sizeof(struct mwifiex_ie_types_header)); encrypt_protocol->proto = cpu_to_le16(bss_cfg->protocol); cmd_size += sizeof(struct host_cmd_tlv_encrypt_protocol); tlv += sizeof(struct host_cmd_tlv_encrypt_protocol); } if (bss_cfg->ht_cap.cap_info) { htcap = (struct mwifiex_ie_types_htcap *)tlv; htcap->header.type = cpu_to_le16(WLAN_EID_HT_CAPABILITY); htcap->header.len = cpu_to_le16(sizeof(struct ieee80211_ht_cap)); htcap->ht_cap.cap_info = bss_cfg->ht_cap.cap_info; htcap->ht_cap.ampdu_params_info = bss_cfg->ht_cap.ampdu_params_info; memcpy(&htcap->ht_cap.mcs, &bss_cfg->ht_cap.mcs, sizeof(struct ieee80211_mcs_info)); htcap->ht_cap.extended_ht_cap_info = bss_cfg->ht_cap.extended_ht_cap_info; htcap->ht_cap.tx_BF_cap_info = bss_cfg->ht_cap.tx_BF_cap_info; htcap->ht_cap.antenna_selection_info = bss_cfg->ht_cap.antenna_selection_info; cmd_size += sizeof(struct mwifiex_ie_types_htcap); tlv += sizeof(struct mwifiex_ie_types_htcap); } if (bss_cfg->wmm_info.qos_info != 0xFF) { wmm_cap = (struct mwifiex_ie_types_wmmcap *)tlv; wmm_cap->header.type = cpu_to_le16(WLAN_EID_VENDOR_SPECIFIC); wmm_cap->header.len = cpu_to_le16(sizeof(wmm_cap->wmm_info)); memcpy(&wmm_cap->wmm_info, &bss_cfg->wmm_info, sizeof(wmm_cap->wmm_info)); cmd_size += sizeof(struct mwifiex_ie_types_wmmcap); tlv += sizeof(struct mwifiex_ie_types_wmmcap); } if (bss_cfg->sta_ao_timer) { ao_timer = (struct host_cmd_tlv_ageout_timer *)tlv; ao_timer->header.type = cpu_to_le16(TLV_TYPE_UAP_AO_TIMER); ao_timer->header.len = cpu_to_le16(sizeof(*ao_timer) - sizeof(struct mwifiex_ie_types_header)); ao_timer->sta_ao_timer = cpu_to_le32(bss_cfg->sta_ao_timer); cmd_size += sizeof(*ao_timer); tlv += sizeof(*ao_timer); } if (bss_cfg->power_constraint) { pwr_ct = (void *)tlv; pwr_ct->header.type = cpu_to_le16(TLV_TYPE_PWR_CONSTRAINT); pwr_ct->header.len = cpu_to_le16(sizeof(u8)); pwr_ct->constraint = bss_cfg->power_constraint; cmd_size += sizeof(*pwr_ct); tlv += sizeof(*pwr_ct); } if (bss_cfg->ps_sta_ao_timer) { ps_ao_timer = (struct host_cmd_tlv_ageout_timer *)tlv; ps_ao_timer->header.type = cpu_to_le16(TLV_TYPE_UAP_PS_AO_TIMER); ps_ao_timer->header.len = cpu_to_le16(sizeof(*ps_ao_timer) - sizeof(struct mwifiex_ie_types_header)); ps_ao_timer->sta_ao_timer = cpu_to_le32(bss_cfg->ps_sta_ao_timer); cmd_size += sizeof(*ps_ao_timer); tlv += sizeof(*ps_ao_timer); } *param_size = cmd_size; return 0; } /* This function parses custom IEs from IE list and prepares command buffer */ static int mwifiex_uap_custom_ie_prepare(u8 *tlv, void *cmd_buf, u16 *ie_size) { struct mwifiex_ie_list *ap_ie = cmd_buf; struct mwifiex_ie_types_header *tlv_ie = (void *)tlv; if (!ap_ie || !ap_ie->len) return -1; *ie_size += le16_to_cpu(ap_ie->len) + sizeof(struct mwifiex_ie_types_header); tlv_ie->type = cpu_to_le16(TLV_TYPE_MGMT_IE); tlv_ie->len = ap_ie->len; tlv += sizeof(struct mwifiex_ie_types_header); memcpy(tlv, ap_ie->ie_list, le16_to_cpu(ap_ie->len)); return 0; } /* Parse AP config structure and prepare TLV based command structure * to be sent to FW for uAP configuration */ static int mwifiex_cmd_uap_sys_config(struct host_cmd_ds_command *cmd, u16 cmd_action, u32 type, void *cmd_buf) { u8 *tlv; u16 cmd_size, param_size, ie_size; struct host_cmd_ds_sys_config *sys_cfg; cmd->command = cpu_to_le16(HostCmd_CMD_UAP_SYS_CONFIG); cmd_size = (u16)(sizeof(struct host_cmd_ds_sys_config) + S_DS_GEN); sys_cfg = (struct host_cmd_ds_sys_config *)&cmd->params.uap_sys_config; sys_cfg->action = cpu_to_le16(cmd_action); tlv = sys_cfg->tlv; switch (type) { case UAP_BSS_PARAMS_I: param_size = cmd_size; if (mwifiex_uap_bss_param_prepare(tlv, cmd_buf, &param_size)) return -1; cmd->size = cpu_to_le16(param_size); break; case UAP_CUSTOM_IE_I: ie_size = cmd_size; if (mwifiex_uap_custom_ie_prepare(tlv, cmd_buf, &ie_size)) return -1; cmd->size = cpu_to_le16(ie_size); break; default: return -1; } return 0; } /* This function prepares AP specific deauth command with mac supplied in * function parameter. */ static int mwifiex_cmd_uap_sta_deauth(struct mwifiex_private *priv, struct host_cmd_ds_command *cmd, u8 *mac) { struct host_cmd_ds_sta_deauth *sta_deauth = &cmd->params.sta_deauth; cmd->command = cpu_to_le16(HostCmd_CMD_UAP_STA_DEAUTH); memcpy(sta_deauth->mac, mac, ETH_ALEN); sta_deauth->reason = cpu_to_le16(WLAN_REASON_DEAUTH_LEAVING); cmd->size = cpu_to_le16(sizeof(struct host_cmd_ds_sta_deauth) + S_DS_GEN); return 0; } /* This function prepares the AP specific commands before sending them * to the firmware. * This is a generic function which calls specific command preparation * routines based upon the command number. */ int mwifiex_uap_prepare_cmd(struct mwifiex_private *priv, u16 cmd_no, u16 cmd_action, u32 type, void *data_buf, void *cmd_buf) { struct host_cmd_ds_command *cmd = cmd_buf; switch (cmd_no) { case HostCmd_CMD_UAP_SYS_CONFIG: if (mwifiex_cmd_uap_sys_config(cmd, cmd_action, type, data_buf)) return -1; break; case HostCmd_CMD_UAP_BSS_START: case HostCmd_CMD_UAP_BSS_STOP: case HOST_CMD_APCMD_SYS_RESET: case HOST_CMD_APCMD_STA_LIST: cmd->command = cpu_to_le16(cmd_no); cmd->size = cpu_to_le16(S_DS_GEN); break; case HostCmd_CMD_UAP_STA_DEAUTH: if (mwifiex_cmd_uap_sta_deauth(priv, cmd, data_buf)) return -1; break; case HostCmd_CMD_CHAN_REPORT_REQUEST: if (mwifiex_cmd_issue_chan_report_request(priv, cmd_buf, data_buf)) return -1; break; default: mwifiex_dbg(priv->adapter, ERROR, "PREP_CMD: unknown cmd %#x\n", cmd_no); return -1; } return 0; } void mwifiex_uap_set_channel(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_cfg, struct cfg80211_chan_def chandef) { u8 config_bands = 0, old_bands = priv->adapter->config_bands; priv->bss_chandef = chandef; bss_cfg->channel = ieee80211_frequency_to_channel( chandef.chan->center_freq); /* Set appropriate bands */ if (chandef.chan->band == NL80211_BAND_2GHZ) { bss_cfg->band_cfg = BAND_CONFIG_BG; config_bands = BAND_B | BAND_G; if (chandef.width > NL80211_CHAN_WIDTH_20_NOHT) config_bands |= BAND_GN; } else { bss_cfg->band_cfg = BAND_CONFIG_A; config_bands = BAND_A; if (chandef.width > NL80211_CHAN_WIDTH_20_NOHT) config_bands |= BAND_AN; if (chandef.width > NL80211_CHAN_WIDTH_40) config_bands |= BAND_AAC; } switch (chandef.width) { case NL80211_CHAN_WIDTH_5: case NL80211_CHAN_WIDTH_10: case NL80211_CHAN_WIDTH_20_NOHT: case NL80211_CHAN_WIDTH_20: break; case NL80211_CHAN_WIDTH_40: if (chandef.center_freq1 < chandef.chan->center_freq) bss_cfg->band_cfg |= MWIFIEX_SEC_CHAN_BELOW; else bss_cfg->band_cfg |= MWIFIEX_SEC_CHAN_ABOVE; break; case NL80211_CHAN_WIDTH_80: case NL80211_CHAN_WIDTH_80P80: case NL80211_CHAN_WIDTH_160: bss_cfg->band_cfg |= mwifiex_get_sec_chan_offset(bss_cfg->channel) << 4; break; default: mwifiex_dbg(priv->adapter, WARN, "Unknown channel width: %d\n", chandef.width); break; } priv->adapter->config_bands = config_bands; if (old_bands != config_bands) { mwifiex_send_domain_info_cmd_fw(priv->adapter->wiphy); mwifiex_dnld_txpwr_table(priv); } } int mwifiex_config_start_uap(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_cfg) { if (mwifiex_send_cmd(priv, HostCmd_CMD_UAP_SYS_CONFIG, HostCmd_ACT_GEN_SET, UAP_BSS_PARAMS_I, bss_cfg, true)) { mwifiex_dbg(priv->adapter, ERROR, "Failed to set AP configuration\n"); return -1; } if (mwifiex_send_cmd(priv, HostCmd_CMD_UAP_BSS_START, HostCmd_ACT_GEN_SET, 0, NULL, true)) { mwifiex_dbg(priv->adapter, ERROR, "Failed to start the BSS\n"); return -1; } if (priv->sec_info.wep_enabled) priv->curr_pkt_filter |= HostCmd_ACT_MAC_WEP_ENABLE; else priv->curr_pkt_filter &= ~HostCmd_ACT_MAC_WEP_ENABLE; if (mwifiex_send_cmd(priv, HostCmd_CMD_MAC_CONTROL, HostCmd_ACT_GEN_SET, 0, &priv->curr_pkt_filter, true)) return -1; return 0; }
null
134
CWE-787
CVE-2019-14815
/* * Marvell Wireless LAN device driver: AP specific command handling * * Copyright (C) 2012-2014, Marvell International Ltd. * * This software file (the "File") is distributed by Marvell International * Ltd. under the terms of the GNU General Public License Version 2, June 1991 * (the "License"). You may use, redistribute and/or modify this File in * accordance with the terms and conditions of the License, a copy of which * is available by writing to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the * worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE * IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE * ARE EXPRESSLY DISCLAIMED. The License provides additional details about * this warranty disclaimer. */ #include "main.h" #include "11ac.h" #include "11n.h" /* This function parses security related parameters from cfg80211_ap_settings * and sets into FW understandable bss_config structure. */ int mwifiex_set_secure_params(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_config, struct cfg80211_ap_settings *params) { int i; struct mwifiex_wep_key wep_key; if (!params->privacy) { bss_config->protocol = PROTOCOL_NO_SECURITY; bss_config->key_mgmt = KEY_MGMT_NONE; bss_config->wpa_cfg.length = 0; priv->sec_info.wep_enabled = 0; priv->sec_info.wpa_enabled = 0; priv->sec_info.wpa2_enabled = 0; return 0; } switch (params->auth_type) { case NL80211_AUTHTYPE_OPEN_SYSTEM: bss_config->auth_mode = WLAN_AUTH_OPEN; break; case NL80211_AUTHTYPE_SHARED_KEY: bss_config->auth_mode = WLAN_AUTH_SHARED_KEY; break; case NL80211_AUTHTYPE_NETWORK_EAP: bss_config->auth_mode = WLAN_AUTH_LEAP; break; default: bss_config->auth_mode = MWIFIEX_AUTH_MODE_AUTO; break; } bss_config->key_mgmt_operation |= KEY_MGMT_ON_HOST; for (i = 0; i < params->crypto.n_akm_suites; i++) { switch (params->crypto.akm_suites[i]) { case WLAN_AKM_SUITE_8021X: if (params->crypto.wpa_versions & NL80211_WPA_VERSION_1) { bss_config->protocol = PROTOCOL_WPA; bss_config->key_mgmt = KEY_MGMT_EAP; } if (params->crypto.wpa_versions & NL80211_WPA_VERSION_2) { bss_config->protocol |= PROTOCOL_WPA2; bss_config->key_mgmt = KEY_MGMT_EAP; } break; case WLAN_AKM_SUITE_PSK: if (params->crypto.wpa_versions & NL80211_WPA_VERSION_1) { bss_config->protocol = PROTOCOL_WPA; bss_config->key_mgmt = KEY_MGMT_PSK; } if (params->crypto.wpa_versions & NL80211_WPA_VERSION_2) { bss_config->protocol |= PROTOCOL_WPA2; bss_config->key_mgmt = KEY_MGMT_PSK; } break; default: break; } } for (i = 0; i < params->crypto.n_ciphers_pairwise; i++) { switch (params->crypto.ciphers_pairwise[i]) { case WLAN_CIPHER_SUITE_WEP40: case WLAN_CIPHER_SUITE_WEP104: break; case WLAN_CIPHER_SUITE_TKIP: if (params->crypto.wpa_versions & NL80211_WPA_VERSION_1) bss_config->wpa_cfg.pairwise_cipher_wpa |= CIPHER_TKIP; if (params->crypto.wpa_versions & NL80211_WPA_VERSION_2) bss_config->wpa_cfg.pairwise_cipher_wpa2 |= CIPHER_TKIP; break; case WLAN_CIPHER_SUITE_CCMP: if (params->crypto.wpa_versions & NL80211_WPA_VERSION_1) bss_config->wpa_cfg.pairwise_cipher_wpa |= CIPHER_AES_CCMP; if (params->crypto.wpa_versions & NL80211_WPA_VERSION_2) bss_config->wpa_cfg.pairwise_cipher_wpa2 |= CIPHER_AES_CCMP; default: break; } } switch (params->crypto.cipher_group) { case WLAN_CIPHER_SUITE_WEP40: case WLAN_CIPHER_SUITE_WEP104: if (priv->sec_info.wep_enabled) { bss_config->protocol = PROTOCOL_STATIC_WEP; bss_config->key_mgmt = KEY_MGMT_NONE; bss_config->wpa_cfg.length = 0; for (i = 0; i < NUM_WEP_KEYS; i++) { wep_key = priv->wep_key[i]; bss_config->wep_cfg[i].key_index = i; if (priv->wep_key_curr_index == i) bss_config->wep_cfg[i].is_default = 1; else bss_config->wep_cfg[i].is_default = 0; bss_config->wep_cfg[i].length = wep_key.key_length; memcpy(&bss_config->wep_cfg[i].key, &wep_key.key_material, wep_key.key_length); } } break; case WLAN_CIPHER_SUITE_TKIP: bss_config->wpa_cfg.group_cipher = CIPHER_TKIP; break; case WLAN_CIPHER_SUITE_CCMP: bss_config->wpa_cfg.group_cipher = CIPHER_AES_CCMP; break; default: break; } return 0; } /* This function updates 11n related parameters from IE and sets them into * bss_config structure. */ void mwifiex_set_ht_params(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_cfg, struct cfg80211_ap_settings *params) { const u8 *ht_ie; if (!ISSUPP_11NENABLED(priv->adapter->fw_cap_info)) return; ht_ie = cfg80211_find_ie(WLAN_EID_HT_CAPABILITY, params->beacon.tail, params->beacon.tail_len); if (ht_ie) { memcpy(&bss_cfg->ht_cap, ht_ie + 2, sizeof(struct ieee80211_ht_cap)); priv->ap_11n_enabled = 1; } else { memset(&bss_cfg->ht_cap, 0, sizeof(struct ieee80211_ht_cap)); bss_cfg->ht_cap.cap_info = cpu_to_le16(MWIFIEX_DEF_HT_CAP); bss_cfg->ht_cap.ampdu_params_info = MWIFIEX_DEF_AMPDU; } return; } /* This function updates 11ac related parameters from IE * and sets them into bss_config structure. */ void mwifiex_set_vht_params(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_cfg, struct cfg80211_ap_settings *params) { const u8 *vht_ie; vht_ie = cfg80211_find_ie(WLAN_EID_VHT_CAPABILITY, params->beacon.tail, params->beacon.tail_len); if (vht_ie) { memcpy(&bss_cfg->vht_cap, vht_ie + 2, sizeof(struct ieee80211_vht_cap)); priv->ap_11ac_enabled = 1; } else { priv->ap_11ac_enabled = 0; } return; } /* This function updates 11ac related parameters from IE * and sets them into bss_config structure. */ void mwifiex_set_tpc_params(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_cfg, struct cfg80211_ap_settings *params) { const u8 *tpc_ie; tpc_ie = cfg80211_find_ie(WLAN_EID_TPC_REQUEST, params->beacon.tail, params->beacon.tail_len); if (tpc_ie) bss_cfg->power_constraint = *(tpc_ie + 2); else bss_cfg->power_constraint = 0; } /* Enable VHT only when cfg80211_ap_settings has VHT IE. * Otherwise disable VHT. */ void mwifiex_set_vht_width(struct mwifiex_private *priv, enum nl80211_chan_width width, bool ap_11ac_enable) { struct mwifiex_adapter *adapter = priv->adapter; struct mwifiex_11ac_vht_cfg vht_cfg; vht_cfg.band_config = VHT_CFG_5GHZ; vht_cfg.cap_info = adapter->hw_dot_11ac_dev_cap; if (!ap_11ac_enable) { vht_cfg.mcs_tx_set = DISABLE_VHT_MCS_SET; vht_cfg.mcs_rx_set = DISABLE_VHT_MCS_SET; } else { vht_cfg.mcs_tx_set = DEFAULT_VHT_MCS_SET; vht_cfg.mcs_rx_set = DEFAULT_VHT_MCS_SET; } vht_cfg.misc_config = VHT_CAP_UAP_ONLY; if (ap_11ac_enable && width >= NL80211_CHAN_WIDTH_80) vht_cfg.misc_config |= VHT_BW_80_160_80P80; mwifiex_send_cmd(priv, HostCmd_CMD_11AC_CFG, HostCmd_ACT_GEN_SET, 0, &vht_cfg, true); return; } /* This function finds supported rates IE from beacon parameter and sets * these rates into bss_config structure. */ void mwifiex_set_uap_rates(struct mwifiex_uap_bss_param *bss_cfg, struct cfg80211_ap_settings *params) { struct ieee_types_header *rate_ie; int var_offset = offsetof(struct ieee80211_mgmt, u.beacon.variable); const u8 *var_pos = params->beacon.head + var_offset; int len = params->beacon.head_len - var_offset; u8 rate_len = 0; rate_ie = (void *)cfg80211_find_ie(WLAN_EID_SUPP_RATES, var_pos, len); if (rate_ie) { memcpy(bss_cfg->rates, rate_ie + 1, rate_ie->len); rate_len = rate_ie->len; } rate_ie = (void *)cfg80211_find_ie(WLAN_EID_EXT_SUPP_RATES, params->beacon.tail, params->beacon.tail_len); if (rate_ie) memcpy(bss_cfg->rates + rate_len, rate_ie + 1, rate_ie->len); return; } /* This function initializes some of mwifiex_uap_bss_param variables. * This helps FW in ignoring invalid values. These values may or may not * be get updated to valid ones at later stage. */ void mwifiex_set_sys_config_invalid_data(struct mwifiex_uap_bss_param *config) { config->bcast_ssid_ctl = 0x7F; config->radio_ctl = 0x7F; config->dtim_period = 0x7F; config->beacon_period = 0x7FFF; config->auth_mode = 0x7F; config->rts_threshold = 0x7FFF; config->frag_threshold = 0x7FFF; config->retry_limit = 0x7F; config->qos_info = 0xFF; } /* This function parses BSS related parameters from structure * and prepares TLVs specific to WPA/WPA2 security. * These TLVs are appended to command buffer. */ static void mwifiex_uap_bss_wpa(u8 **tlv_buf, void *cmd_buf, u16 *param_size) { struct host_cmd_tlv_pwk_cipher *pwk_cipher; struct host_cmd_tlv_gwk_cipher *gwk_cipher; struct host_cmd_tlv_passphrase *passphrase; struct host_cmd_tlv_akmp *tlv_akmp; struct mwifiex_uap_bss_param *bss_cfg = cmd_buf; u16 cmd_size = *param_size; u8 *tlv = *tlv_buf; tlv_akmp = (struct host_cmd_tlv_akmp *)tlv; tlv_akmp->header.type = cpu_to_le16(TLV_TYPE_UAP_AKMP); tlv_akmp->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_akmp) - sizeof(struct mwifiex_ie_types_header)); tlv_akmp->key_mgmt_operation = cpu_to_le16(bss_cfg->key_mgmt_operation); tlv_akmp->key_mgmt = cpu_to_le16(bss_cfg->key_mgmt); cmd_size += sizeof(struct host_cmd_tlv_akmp); tlv += sizeof(struct host_cmd_tlv_akmp); if (bss_cfg->wpa_cfg.pairwise_cipher_wpa & VALID_CIPHER_BITMAP) { pwk_cipher = (struct host_cmd_tlv_pwk_cipher *)tlv; pwk_cipher->header.type = cpu_to_le16(TLV_TYPE_PWK_CIPHER); pwk_cipher->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_pwk_cipher) - sizeof(struct mwifiex_ie_types_header)); pwk_cipher->proto = cpu_to_le16(PROTOCOL_WPA); pwk_cipher->cipher = bss_cfg->wpa_cfg.pairwise_cipher_wpa; cmd_size += sizeof(struct host_cmd_tlv_pwk_cipher); tlv += sizeof(struct host_cmd_tlv_pwk_cipher); } if (bss_cfg->wpa_cfg.pairwise_cipher_wpa2 & VALID_CIPHER_BITMAP) { pwk_cipher = (struct host_cmd_tlv_pwk_cipher *)tlv; pwk_cipher->header.type = cpu_to_le16(TLV_TYPE_PWK_CIPHER); pwk_cipher->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_pwk_cipher) - sizeof(struct mwifiex_ie_types_header)); pwk_cipher->proto = cpu_to_le16(PROTOCOL_WPA2); pwk_cipher->cipher = bss_cfg->wpa_cfg.pairwise_cipher_wpa2; cmd_size += sizeof(struct host_cmd_tlv_pwk_cipher); tlv += sizeof(struct host_cmd_tlv_pwk_cipher); } if (bss_cfg->wpa_cfg.group_cipher & VALID_CIPHER_BITMAP) { gwk_cipher = (struct host_cmd_tlv_gwk_cipher *)tlv; gwk_cipher->header.type = cpu_to_le16(TLV_TYPE_GWK_CIPHER); gwk_cipher->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_gwk_cipher) - sizeof(struct mwifiex_ie_types_header)); gwk_cipher->cipher = bss_cfg->wpa_cfg.group_cipher; cmd_size += sizeof(struct host_cmd_tlv_gwk_cipher); tlv += sizeof(struct host_cmd_tlv_gwk_cipher); } if (bss_cfg->wpa_cfg.length) { passphrase = (struct host_cmd_tlv_passphrase *)tlv; passphrase->header.type = cpu_to_le16(TLV_TYPE_UAP_WPA_PASSPHRASE); passphrase->header.len = cpu_to_le16(bss_cfg->wpa_cfg.length); memcpy(passphrase->passphrase, bss_cfg->wpa_cfg.passphrase, bss_cfg->wpa_cfg.length); cmd_size += sizeof(struct mwifiex_ie_types_header) + bss_cfg->wpa_cfg.length; tlv += sizeof(struct mwifiex_ie_types_header) + bss_cfg->wpa_cfg.length; } *param_size = cmd_size; *tlv_buf = tlv; return; } /* This function parses WMM related parameters from cfg80211_ap_settings * structure and updates bss_config structure. */ void mwifiex_set_wmm_params(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_cfg, struct cfg80211_ap_settings *params) { const u8 *vendor_ie; const u8 *wmm_ie; u8 wmm_oui[] = {0x00, 0x50, 0xf2, 0x02}; vendor_ie = cfg80211_find_vendor_ie(WLAN_OUI_MICROSOFT, WLAN_OUI_TYPE_MICROSOFT_WMM, params->beacon.tail, params->beacon.tail_len); if (vendor_ie) { wmm_ie = vendor_ie; memcpy(&bss_cfg->wmm_info, wmm_ie + sizeof(struct ieee_types_header), *(wmm_ie + 1)); priv->wmm_enabled = 1; } else { memset(&bss_cfg->wmm_info, 0, sizeof(bss_cfg->wmm_info)); memcpy(&bss_cfg->wmm_info.oui, wmm_oui, sizeof(wmm_oui)); bss_cfg->wmm_info.subtype = MWIFIEX_WMM_SUBTYPE; bss_cfg->wmm_info.version = MWIFIEX_WMM_VERSION; priv->wmm_enabled = 0; } bss_cfg->qos_info = 0x00; return; } /* This function parses BSS related parameters from structure * and prepares TLVs specific to WEP encryption. * These TLVs are appended to command buffer. */ static void mwifiex_uap_bss_wep(u8 **tlv_buf, void *cmd_buf, u16 *param_size) { struct host_cmd_tlv_wep_key *wep_key; u16 cmd_size = *param_size; int i; u8 *tlv = *tlv_buf; struct mwifiex_uap_bss_param *bss_cfg = cmd_buf; for (i = 0; i < NUM_WEP_KEYS; i++) { if (bss_cfg->wep_cfg[i].length && (bss_cfg->wep_cfg[i].length == WLAN_KEY_LEN_WEP40 || bss_cfg->wep_cfg[i].length == WLAN_KEY_LEN_WEP104)) { wep_key = (struct host_cmd_tlv_wep_key *)tlv; wep_key->header.type = cpu_to_le16(TLV_TYPE_UAP_WEP_KEY); wep_key->header.len = cpu_to_le16(bss_cfg->wep_cfg[i].length + 2); wep_key->key_index = bss_cfg->wep_cfg[i].key_index; wep_key->is_default = bss_cfg->wep_cfg[i].is_default; memcpy(wep_key->key, bss_cfg->wep_cfg[i].key, bss_cfg->wep_cfg[i].length); cmd_size += sizeof(struct mwifiex_ie_types_header) + 2 + bss_cfg->wep_cfg[i].length; tlv += sizeof(struct mwifiex_ie_types_header) + 2 + bss_cfg->wep_cfg[i].length; } } *param_size = cmd_size; *tlv_buf = tlv; return; } /* This function enable 11D if userspace set the country IE. */ void mwifiex_config_uap_11d(struct mwifiex_private *priv, struct cfg80211_beacon_data *beacon_data) { enum state_11d_t state_11d; const u8 *country_ie; country_ie = cfg80211_find_ie(WLAN_EID_COUNTRY, beacon_data->tail, beacon_data->tail_len); if (country_ie) { /* Send cmd to FW to enable 11D function */ state_11d = ENABLE_11D; if (mwifiex_send_cmd(priv, HostCmd_CMD_802_11_SNMP_MIB, HostCmd_ACT_GEN_SET, DOT11D_I, &state_11d, true)) { mwifiex_dbg(priv->adapter, ERROR, "11D: failed to enable 11D\n"); } } } /* This function parses BSS related parameters from structure * and prepares TLVs. These TLVs are appended to command buffer. */ static int mwifiex_uap_bss_param_prepare(u8 *tlv, void *cmd_buf, u16 *param_size) { struct host_cmd_tlv_dtim_period *dtim_period; struct host_cmd_tlv_beacon_period *beacon_period; struct host_cmd_tlv_ssid *ssid; struct host_cmd_tlv_bcast_ssid *bcast_ssid; struct host_cmd_tlv_channel_band *chan_band; struct host_cmd_tlv_frag_threshold *frag_threshold; struct host_cmd_tlv_rts_threshold *rts_threshold; struct host_cmd_tlv_retry_limit *retry_limit; struct host_cmd_tlv_encrypt_protocol *encrypt_protocol; struct host_cmd_tlv_auth_type *auth_type; struct host_cmd_tlv_rates *tlv_rates; struct host_cmd_tlv_ageout_timer *ao_timer, *ps_ao_timer; struct host_cmd_tlv_power_constraint *pwr_ct; struct mwifiex_ie_types_htcap *htcap; struct mwifiex_ie_types_wmmcap *wmm_cap; struct mwifiex_uap_bss_param *bss_cfg = cmd_buf; int i; u16 cmd_size = *param_size; if (bss_cfg->ssid.ssid_len) { ssid = (struct host_cmd_tlv_ssid *)tlv; ssid->header.type = cpu_to_le16(TLV_TYPE_UAP_SSID); ssid->header.len = cpu_to_le16((u16)bss_cfg->ssid.ssid_len); memcpy(ssid->ssid, bss_cfg->ssid.ssid, bss_cfg->ssid.ssid_len); cmd_size += sizeof(struct mwifiex_ie_types_header) + bss_cfg->ssid.ssid_len; tlv += sizeof(struct mwifiex_ie_types_header) + bss_cfg->ssid.ssid_len; bcast_ssid = (struct host_cmd_tlv_bcast_ssid *)tlv; bcast_ssid->header.type = cpu_to_le16(TLV_TYPE_UAP_BCAST_SSID); bcast_ssid->header.len = cpu_to_le16(sizeof(bcast_ssid->bcast_ctl)); bcast_ssid->bcast_ctl = bss_cfg->bcast_ssid_ctl; cmd_size += sizeof(struct host_cmd_tlv_bcast_ssid); tlv += sizeof(struct host_cmd_tlv_bcast_ssid); } if (bss_cfg->rates[0]) { tlv_rates = (struct host_cmd_tlv_rates *)tlv; tlv_rates->header.type = cpu_to_le16(TLV_TYPE_UAP_RATES); for (i = 0; i < MWIFIEX_SUPPORTED_RATES && bss_cfg->rates[i]; i++) tlv_rates->rates[i] = bss_cfg->rates[i]; tlv_rates->header.len = cpu_to_le16(i); cmd_size += sizeof(struct host_cmd_tlv_rates) + i; tlv += sizeof(struct host_cmd_tlv_rates) + i; } if (bss_cfg->channel && (((bss_cfg->band_cfg & BIT(0)) == BAND_CONFIG_BG && bss_cfg->channel <= MAX_CHANNEL_BAND_BG) || ((bss_cfg->band_cfg & BIT(0)) == BAND_CONFIG_A && bss_cfg->channel <= MAX_CHANNEL_BAND_A))) { chan_band = (struct host_cmd_tlv_channel_band *)tlv; chan_band->header.type = cpu_to_le16(TLV_TYPE_CHANNELBANDLIST); chan_band->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_channel_band) - sizeof(struct mwifiex_ie_types_header)); chan_band->band_config = bss_cfg->band_cfg; chan_band->channel = bss_cfg->channel; cmd_size += sizeof(struct host_cmd_tlv_channel_band); tlv += sizeof(struct host_cmd_tlv_channel_band); } if (bss_cfg->beacon_period >= MIN_BEACON_PERIOD && bss_cfg->beacon_period <= MAX_BEACON_PERIOD) { beacon_period = (struct host_cmd_tlv_beacon_period *)tlv; beacon_period->header.type = cpu_to_le16(TLV_TYPE_UAP_BEACON_PERIOD); beacon_period->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_beacon_period) - sizeof(struct mwifiex_ie_types_header)); beacon_period->period = cpu_to_le16(bss_cfg->beacon_period); cmd_size += sizeof(struct host_cmd_tlv_beacon_period); tlv += sizeof(struct host_cmd_tlv_beacon_period); } if (bss_cfg->dtim_period >= MIN_DTIM_PERIOD && bss_cfg->dtim_period <= MAX_DTIM_PERIOD) { dtim_period = (struct host_cmd_tlv_dtim_period *)tlv; dtim_period->header.type = cpu_to_le16(TLV_TYPE_UAP_DTIM_PERIOD); dtim_period->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_dtim_period) - sizeof(struct mwifiex_ie_types_header)); dtim_period->period = bss_cfg->dtim_period; cmd_size += sizeof(struct host_cmd_tlv_dtim_period); tlv += sizeof(struct host_cmd_tlv_dtim_period); } if (bss_cfg->rts_threshold <= MWIFIEX_RTS_MAX_VALUE) { rts_threshold = (struct host_cmd_tlv_rts_threshold *)tlv; rts_threshold->header.type = cpu_to_le16(TLV_TYPE_UAP_RTS_THRESHOLD); rts_threshold->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_rts_threshold) - sizeof(struct mwifiex_ie_types_header)); rts_threshold->rts_thr = cpu_to_le16(bss_cfg->rts_threshold); cmd_size += sizeof(struct host_cmd_tlv_frag_threshold); tlv += sizeof(struct host_cmd_tlv_frag_threshold); } if ((bss_cfg->frag_threshold >= MWIFIEX_FRAG_MIN_VALUE) && (bss_cfg->frag_threshold <= MWIFIEX_FRAG_MAX_VALUE)) { frag_threshold = (struct host_cmd_tlv_frag_threshold *)tlv; frag_threshold->header.type = cpu_to_le16(TLV_TYPE_UAP_FRAG_THRESHOLD); frag_threshold->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_frag_threshold) - sizeof(struct mwifiex_ie_types_header)); frag_threshold->frag_thr = cpu_to_le16(bss_cfg->frag_threshold); cmd_size += sizeof(struct host_cmd_tlv_frag_threshold); tlv += sizeof(struct host_cmd_tlv_frag_threshold); } if (bss_cfg->retry_limit <= MWIFIEX_RETRY_LIMIT) { retry_limit = (struct host_cmd_tlv_retry_limit *)tlv; retry_limit->header.type = cpu_to_le16(TLV_TYPE_UAP_RETRY_LIMIT); retry_limit->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_retry_limit) - sizeof(struct mwifiex_ie_types_header)); retry_limit->limit = (u8)bss_cfg->retry_limit; cmd_size += sizeof(struct host_cmd_tlv_retry_limit); tlv += sizeof(struct host_cmd_tlv_retry_limit); } if ((bss_cfg->protocol & PROTOCOL_WPA) || (bss_cfg->protocol & PROTOCOL_WPA2) || (bss_cfg->protocol & PROTOCOL_EAP)) mwifiex_uap_bss_wpa(&tlv, cmd_buf, &cmd_size); else mwifiex_uap_bss_wep(&tlv, cmd_buf, &cmd_size); if ((bss_cfg->auth_mode <= WLAN_AUTH_SHARED_KEY) || (bss_cfg->auth_mode == MWIFIEX_AUTH_MODE_AUTO)) { auth_type = (struct host_cmd_tlv_auth_type *)tlv; auth_type->header.type = cpu_to_le16(TLV_TYPE_AUTH_TYPE); auth_type->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_auth_type) - sizeof(struct mwifiex_ie_types_header)); auth_type->auth_type = (u8)bss_cfg->auth_mode; cmd_size += sizeof(struct host_cmd_tlv_auth_type); tlv += sizeof(struct host_cmd_tlv_auth_type); } if (bss_cfg->protocol) { encrypt_protocol = (struct host_cmd_tlv_encrypt_protocol *)tlv; encrypt_protocol->header.type = cpu_to_le16(TLV_TYPE_UAP_ENCRY_PROTOCOL); encrypt_protocol->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_encrypt_protocol) - sizeof(struct mwifiex_ie_types_header)); encrypt_protocol->proto = cpu_to_le16(bss_cfg->protocol); cmd_size += sizeof(struct host_cmd_tlv_encrypt_protocol); tlv += sizeof(struct host_cmd_tlv_encrypt_protocol); } if (bss_cfg->ht_cap.cap_info) { htcap = (struct mwifiex_ie_types_htcap *)tlv; htcap->header.type = cpu_to_le16(WLAN_EID_HT_CAPABILITY); htcap->header.len = cpu_to_le16(sizeof(struct ieee80211_ht_cap)); htcap->ht_cap.cap_info = bss_cfg->ht_cap.cap_info; htcap->ht_cap.ampdu_params_info = bss_cfg->ht_cap.ampdu_params_info; memcpy(&htcap->ht_cap.mcs, &bss_cfg->ht_cap.mcs, sizeof(struct ieee80211_mcs_info)); htcap->ht_cap.extended_ht_cap_info = bss_cfg->ht_cap.extended_ht_cap_info; htcap->ht_cap.tx_BF_cap_info = bss_cfg->ht_cap.tx_BF_cap_info; htcap->ht_cap.antenna_selection_info = bss_cfg->ht_cap.antenna_selection_info; cmd_size += sizeof(struct mwifiex_ie_types_htcap); tlv += sizeof(struct mwifiex_ie_types_htcap); } if (bss_cfg->wmm_info.qos_info != 0xFF) { wmm_cap = (struct mwifiex_ie_types_wmmcap *)tlv; wmm_cap->header.type = cpu_to_le16(WLAN_EID_VENDOR_SPECIFIC); wmm_cap->header.len = cpu_to_le16(sizeof(wmm_cap->wmm_info)); memcpy(&wmm_cap->wmm_info, &bss_cfg->wmm_info, sizeof(wmm_cap->wmm_info)); cmd_size += sizeof(struct mwifiex_ie_types_wmmcap); tlv += sizeof(struct mwifiex_ie_types_wmmcap); } if (bss_cfg->sta_ao_timer) { ao_timer = (struct host_cmd_tlv_ageout_timer *)tlv; ao_timer->header.type = cpu_to_le16(TLV_TYPE_UAP_AO_TIMER); ao_timer->header.len = cpu_to_le16(sizeof(*ao_timer) - sizeof(struct mwifiex_ie_types_header)); ao_timer->sta_ao_timer = cpu_to_le32(bss_cfg->sta_ao_timer); cmd_size += sizeof(*ao_timer); tlv += sizeof(*ao_timer); } if (bss_cfg->power_constraint) { pwr_ct = (void *)tlv; pwr_ct->header.type = cpu_to_le16(TLV_TYPE_PWR_CONSTRAINT); pwr_ct->header.len = cpu_to_le16(sizeof(u8)); pwr_ct->constraint = bss_cfg->power_constraint; cmd_size += sizeof(*pwr_ct); tlv += sizeof(*pwr_ct); } if (bss_cfg->ps_sta_ao_timer) { ps_ao_timer = (struct host_cmd_tlv_ageout_timer *)tlv; ps_ao_timer->header.type = cpu_to_le16(TLV_TYPE_UAP_PS_AO_TIMER); ps_ao_timer->header.len = cpu_to_le16(sizeof(*ps_ao_timer) - sizeof(struct mwifiex_ie_types_header)); ps_ao_timer->sta_ao_timer = cpu_to_le32(bss_cfg->ps_sta_ao_timer); cmd_size += sizeof(*ps_ao_timer); tlv += sizeof(*ps_ao_timer); } *param_size = cmd_size; return 0; } /* This function parses custom IEs from IE list and prepares command buffer */ static int mwifiex_uap_custom_ie_prepare(u8 *tlv, void *cmd_buf, u16 *ie_size) { struct mwifiex_ie_list *ap_ie = cmd_buf; struct mwifiex_ie_types_header *tlv_ie = (void *)tlv; if (!ap_ie || !ap_ie->len) return -1; *ie_size += le16_to_cpu(ap_ie->len) + sizeof(struct mwifiex_ie_types_header); tlv_ie->type = cpu_to_le16(TLV_TYPE_MGMT_IE); tlv_ie->len = ap_ie->len; tlv += sizeof(struct mwifiex_ie_types_header); memcpy(tlv, ap_ie->ie_list, le16_to_cpu(ap_ie->len)); return 0; } /* Parse AP config structure and prepare TLV based command structure * to be sent to FW for uAP configuration */ static int mwifiex_cmd_uap_sys_config(struct host_cmd_ds_command *cmd, u16 cmd_action, u32 type, void *cmd_buf) { u8 *tlv; u16 cmd_size, param_size, ie_size; struct host_cmd_ds_sys_config *sys_cfg; cmd->command = cpu_to_le16(HostCmd_CMD_UAP_SYS_CONFIG); cmd_size = (u16)(sizeof(struct host_cmd_ds_sys_config) + S_DS_GEN); sys_cfg = (struct host_cmd_ds_sys_config *)&cmd->params.uap_sys_config; sys_cfg->action = cpu_to_le16(cmd_action); tlv = sys_cfg->tlv; switch (type) { case UAP_BSS_PARAMS_I: param_size = cmd_size; if (mwifiex_uap_bss_param_prepare(tlv, cmd_buf, &param_size)) return -1; cmd->size = cpu_to_le16(param_size); break; case UAP_CUSTOM_IE_I: ie_size = cmd_size; if (mwifiex_uap_custom_ie_prepare(tlv, cmd_buf, &ie_size)) return -1; cmd->size = cpu_to_le16(ie_size); break; default: return -1; } return 0; } /* This function prepares AP specific deauth command with mac supplied in * function parameter. */ static int mwifiex_cmd_uap_sta_deauth(struct mwifiex_private *priv, struct host_cmd_ds_command *cmd, u8 *mac) { struct host_cmd_ds_sta_deauth *sta_deauth = &cmd->params.sta_deauth; cmd->command = cpu_to_le16(HostCmd_CMD_UAP_STA_DEAUTH); memcpy(sta_deauth->mac, mac, ETH_ALEN); sta_deauth->reason = cpu_to_le16(WLAN_REASON_DEAUTH_LEAVING); cmd->size = cpu_to_le16(sizeof(struct host_cmd_ds_sta_deauth) + S_DS_GEN); return 0; } /* This function prepares the AP specific commands before sending them * to the firmware. * This is a generic function which calls specific command preparation * routines based upon the command number. */ int mwifiex_uap_prepare_cmd(struct mwifiex_private *priv, u16 cmd_no, u16 cmd_action, u32 type, void *data_buf, void *cmd_buf) { struct host_cmd_ds_command *cmd = cmd_buf; switch (cmd_no) { case HostCmd_CMD_UAP_SYS_CONFIG: if (mwifiex_cmd_uap_sys_config(cmd, cmd_action, type, data_buf)) return -1; break; case HostCmd_CMD_UAP_BSS_START: case HostCmd_CMD_UAP_BSS_STOP: case HOST_CMD_APCMD_SYS_RESET: case HOST_CMD_APCMD_STA_LIST: cmd->command = cpu_to_le16(cmd_no); cmd->size = cpu_to_le16(S_DS_GEN); break; case HostCmd_CMD_UAP_STA_DEAUTH: if (mwifiex_cmd_uap_sta_deauth(priv, cmd, data_buf)) return -1; break; case HostCmd_CMD_CHAN_REPORT_REQUEST: if (mwifiex_cmd_issue_chan_report_request(priv, cmd_buf, data_buf)) return -1; break; default: mwifiex_dbg(priv->adapter, ERROR, "PREP_CMD: unknown cmd %#x\n", cmd_no); return -1; } return 0; } void mwifiex_uap_set_channel(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_cfg, struct cfg80211_chan_def chandef) { u8 config_bands = 0, old_bands = priv->adapter->config_bands; priv->bss_chandef = chandef; bss_cfg->channel = ieee80211_frequency_to_channel( chandef.chan->center_freq); /* Set appropriate bands */ if (chandef.chan->band == NL80211_BAND_2GHZ) { bss_cfg->band_cfg = BAND_CONFIG_BG; config_bands = BAND_B | BAND_G; if (chandef.width > NL80211_CHAN_WIDTH_20_NOHT) config_bands |= BAND_GN; } else { bss_cfg->band_cfg = BAND_CONFIG_A; config_bands = BAND_A; if (chandef.width > NL80211_CHAN_WIDTH_20_NOHT) config_bands |= BAND_AN; if (chandef.width > NL80211_CHAN_WIDTH_40) config_bands |= BAND_AAC; } switch (chandef.width) { case NL80211_CHAN_WIDTH_5: case NL80211_CHAN_WIDTH_10: case NL80211_CHAN_WIDTH_20_NOHT: case NL80211_CHAN_WIDTH_20: break; case NL80211_CHAN_WIDTH_40: if (chandef.center_freq1 < chandef.chan->center_freq) bss_cfg->band_cfg |= MWIFIEX_SEC_CHAN_BELOW; else bss_cfg->band_cfg |= MWIFIEX_SEC_CHAN_ABOVE; break; case NL80211_CHAN_WIDTH_80: case NL80211_CHAN_WIDTH_80P80: case NL80211_CHAN_WIDTH_160: bss_cfg->band_cfg |= mwifiex_get_sec_chan_offset(bss_cfg->channel) << 4; break; default: mwifiex_dbg(priv->adapter, WARN, "Unknown channel width: %d\n", chandef.width); break; } priv->adapter->config_bands = config_bands; if (old_bands != config_bands) { mwifiex_send_domain_info_cmd_fw(priv->adapter->wiphy); mwifiex_dnld_txpwr_table(priv); } } int mwifiex_config_start_uap(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_cfg) { if (mwifiex_send_cmd(priv, HostCmd_CMD_UAP_SYS_CONFIG, HostCmd_ACT_GEN_SET, UAP_BSS_PARAMS_I, bss_cfg, true)) { mwifiex_dbg(priv->adapter, ERROR, "Failed to set AP configuration\n"); return -1; } if (mwifiex_send_cmd(priv, HostCmd_CMD_UAP_BSS_START, HostCmd_ACT_GEN_SET, 0, NULL, true)) { mwifiex_dbg(priv->adapter, ERROR, "Failed to start the BSS\n"); return -1; } if (priv->sec_info.wep_enabled) priv->curr_pkt_filter |= HostCmd_ACT_MAC_WEP_ENABLE; else priv->curr_pkt_filter &= ~HostCmd_ACT_MAC_WEP_ENABLE; if (mwifiex_send_cmd(priv, HostCmd_CMD_MAC_CONTROL, HostCmd_ACT_GEN_SET, 0, &priv->curr_pkt_filter, true)) return -1; return 0; }
null
/* * Marvell Wireless LAN device driver: AP specific command handling * * Copyright (C) 2012-2014, Marvell International Ltd. * * This software file (the "File") is distributed by Marvell International * Ltd. under the terms of the GNU General Public License Version 2, June 1991 * (the "License"). You may use, redistribute and/or modify this File in * accordance with the terms and conditions of the License, a copy of which * is available by writing to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the * worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE * IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE * ARE EXPRESSLY DISCLAIMED. The License provides additional details about * this warranty disclaimer. */ #include "main.h" #include "11ac.h" #include "11n.h" /* This function parses security related parameters from cfg80211_ap_settings * and sets into FW understandable bss_config structure. */ int mwifiex_set_secure_params(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_config, struct cfg80211_ap_settings *params) { int i; struct mwifiex_wep_key wep_key; if (!params->privacy) { bss_config->protocol = PROTOCOL_NO_SECURITY; bss_config->key_mgmt = KEY_MGMT_NONE; bss_config->wpa_cfg.length = 0; priv->sec_info.wep_enabled = 0; priv->sec_info.wpa_enabled = 0; priv->sec_info.wpa2_enabled = 0; return 0; } switch (params->auth_type) { case NL80211_AUTHTYPE_OPEN_SYSTEM: bss_config->auth_mode = WLAN_AUTH_OPEN; break; case NL80211_AUTHTYPE_SHARED_KEY: bss_config->auth_mode = WLAN_AUTH_SHARED_KEY; break; case NL80211_AUTHTYPE_NETWORK_EAP: bss_config->auth_mode = WLAN_AUTH_LEAP; break; default: bss_config->auth_mode = MWIFIEX_AUTH_MODE_AUTO; break; } bss_config->key_mgmt_operation |= KEY_MGMT_ON_HOST; for (i = 0; i < params->crypto.n_akm_suites; i++) { switch (params->crypto.akm_suites[i]) { case WLAN_AKM_SUITE_8021X: if (params->crypto.wpa_versions & NL80211_WPA_VERSION_1) { bss_config->protocol = PROTOCOL_WPA; bss_config->key_mgmt = KEY_MGMT_EAP; } if (params->crypto.wpa_versions & NL80211_WPA_VERSION_2) { bss_config->protocol |= PROTOCOL_WPA2; bss_config->key_mgmt = KEY_MGMT_EAP; } break; case WLAN_AKM_SUITE_PSK: if (params->crypto.wpa_versions & NL80211_WPA_VERSION_1) { bss_config->protocol = PROTOCOL_WPA; bss_config->key_mgmt = KEY_MGMT_PSK; } if (params->crypto.wpa_versions & NL80211_WPA_VERSION_2) { bss_config->protocol |= PROTOCOL_WPA2; bss_config->key_mgmt = KEY_MGMT_PSK; } break; default: break; } } for (i = 0; i < params->crypto.n_ciphers_pairwise; i++) { switch (params->crypto.ciphers_pairwise[i]) { case WLAN_CIPHER_SUITE_WEP40: case WLAN_CIPHER_SUITE_WEP104: break; case WLAN_CIPHER_SUITE_TKIP: if (params->crypto.wpa_versions & NL80211_WPA_VERSION_1) bss_config->wpa_cfg.pairwise_cipher_wpa |= CIPHER_TKIP; if (params->crypto.wpa_versions & NL80211_WPA_VERSION_2) bss_config->wpa_cfg.pairwise_cipher_wpa2 |= CIPHER_TKIP; break; case WLAN_CIPHER_SUITE_CCMP: if (params->crypto.wpa_versions & NL80211_WPA_VERSION_1) bss_config->wpa_cfg.pairwise_cipher_wpa |= CIPHER_AES_CCMP; if (params->crypto.wpa_versions & NL80211_WPA_VERSION_2) bss_config->wpa_cfg.pairwise_cipher_wpa2 |= CIPHER_AES_CCMP; default: break; } } switch (params->crypto.cipher_group) { case WLAN_CIPHER_SUITE_WEP40: case WLAN_CIPHER_SUITE_WEP104: if (priv->sec_info.wep_enabled) { bss_config->protocol = PROTOCOL_STATIC_WEP; bss_config->key_mgmt = KEY_MGMT_NONE; bss_config->wpa_cfg.length = 0; for (i = 0; i < NUM_WEP_KEYS; i++) { wep_key = priv->wep_key[i]; bss_config->wep_cfg[i].key_index = i; if (priv->wep_key_curr_index == i) bss_config->wep_cfg[i].is_default = 1; else bss_config->wep_cfg[i].is_default = 0; bss_config->wep_cfg[i].length = wep_key.key_length; memcpy(&bss_config->wep_cfg[i].key, &wep_key.key_material, wep_key.key_length); } } break; case WLAN_CIPHER_SUITE_TKIP: bss_config->wpa_cfg.group_cipher = CIPHER_TKIP; break; case WLAN_CIPHER_SUITE_CCMP: bss_config->wpa_cfg.group_cipher = CIPHER_AES_CCMP; break; default: break; } return 0; } /* This function updates 11n related parameters from IE and sets them into * bss_config structure. */ void mwifiex_set_ht_params(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_cfg, struct cfg80211_ap_settings *params) { const u8 *ht_ie; if (!ISSUPP_11NENABLED(priv->adapter->fw_cap_info)) return; ht_ie = cfg80211_find_ie(WLAN_EID_HT_CAPABILITY, params->beacon.tail, params->beacon.tail_len); if (ht_ie) { memcpy(&bss_cfg->ht_cap, ht_ie + 2, sizeof(struct ieee80211_ht_cap)); priv->ap_11n_enabled = 1; } else { memset(&bss_cfg->ht_cap, 0, sizeof(struct ieee80211_ht_cap)); bss_cfg->ht_cap.cap_info = cpu_to_le16(MWIFIEX_DEF_HT_CAP); bss_cfg->ht_cap.ampdu_params_info = MWIFIEX_DEF_AMPDU; } return; } /* This function updates 11ac related parameters from IE * and sets them into bss_config structure. */ void mwifiex_set_vht_params(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_cfg, struct cfg80211_ap_settings *params) { const u8 *vht_ie; vht_ie = cfg80211_find_ie(WLAN_EID_VHT_CAPABILITY, params->beacon.tail, params->beacon.tail_len); if (vht_ie) { memcpy(&bss_cfg->vht_cap, vht_ie + 2, sizeof(struct ieee80211_vht_cap)); priv->ap_11ac_enabled = 1; } else { priv->ap_11ac_enabled = 0; } return; } /* This function updates 11ac related parameters from IE * and sets them into bss_config structure. */ void mwifiex_set_tpc_params(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_cfg, struct cfg80211_ap_settings *params) { const u8 *tpc_ie; tpc_ie = cfg80211_find_ie(WLAN_EID_TPC_REQUEST, params->beacon.tail, params->beacon.tail_len); if (tpc_ie) bss_cfg->power_constraint = *(tpc_ie + 2); else bss_cfg->power_constraint = 0; } /* Enable VHT only when cfg80211_ap_settings has VHT IE. * Otherwise disable VHT. */ void mwifiex_set_vht_width(struct mwifiex_private *priv, enum nl80211_chan_width width, bool ap_11ac_enable) { struct mwifiex_adapter *adapter = priv->adapter; struct mwifiex_11ac_vht_cfg vht_cfg; vht_cfg.band_config = VHT_CFG_5GHZ; vht_cfg.cap_info = adapter->hw_dot_11ac_dev_cap; if (!ap_11ac_enable) { vht_cfg.mcs_tx_set = DISABLE_VHT_MCS_SET; vht_cfg.mcs_rx_set = DISABLE_VHT_MCS_SET; } else { vht_cfg.mcs_tx_set = DEFAULT_VHT_MCS_SET; vht_cfg.mcs_rx_set = DEFAULT_VHT_MCS_SET; } vht_cfg.misc_config = VHT_CAP_UAP_ONLY; if (ap_11ac_enable && width >= NL80211_CHAN_WIDTH_80) vht_cfg.misc_config |= VHT_BW_80_160_80P80; mwifiex_send_cmd(priv, HostCmd_CMD_11AC_CFG, HostCmd_ACT_GEN_SET, 0, &vht_cfg, true); return; } /* This function finds supported rates IE from beacon parameter and sets * these rates into bss_config structure. */ void mwifiex_set_uap_rates(struct mwifiex_uap_bss_param *bss_cfg, struct cfg80211_ap_settings *params) { struct ieee_types_header *rate_ie; int var_offset = offsetof(struct ieee80211_mgmt, u.beacon.variable); const u8 *var_pos = params->beacon.head + var_offset; int len = params->beacon.head_len - var_offset; u8 rate_len = 0; rate_ie = (void *)cfg80211_find_ie(WLAN_EID_SUPP_RATES, var_pos, len); if (rate_ie) { if (rate_ie->len > MWIFIEX_SUPPORTED_RATES) return; memcpy(bss_cfg->rates, rate_ie + 1, rate_ie->len); rate_len = rate_ie->len; } rate_ie = (void *)cfg80211_find_ie(WLAN_EID_EXT_SUPP_RATES, params->beacon.tail, params->beacon.tail_len); if (rate_ie) { if (rate_ie->len > MWIFIEX_SUPPORTED_RATES - rate_len) return; memcpy(bss_cfg->rates + rate_len, rate_ie + 1, rate_ie->len); } return; } /* This function initializes some of mwifiex_uap_bss_param variables. * This helps FW in ignoring invalid values. These values may or may not * be get updated to valid ones at later stage. */ void mwifiex_set_sys_config_invalid_data(struct mwifiex_uap_bss_param *config) { config->bcast_ssid_ctl = 0x7F; config->radio_ctl = 0x7F; config->dtim_period = 0x7F; config->beacon_period = 0x7FFF; config->auth_mode = 0x7F; config->rts_threshold = 0x7FFF; config->frag_threshold = 0x7FFF; config->retry_limit = 0x7F; config->qos_info = 0xFF; } /* This function parses BSS related parameters from structure * and prepares TLVs specific to WPA/WPA2 security. * These TLVs are appended to command buffer. */ static void mwifiex_uap_bss_wpa(u8 **tlv_buf, void *cmd_buf, u16 *param_size) { struct host_cmd_tlv_pwk_cipher *pwk_cipher; struct host_cmd_tlv_gwk_cipher *gwk_cipher; struct host_cmd_tlv_passphrase *passphrase; struct host_cmd_tlv_akmp *tlv_akmp; struct mwifiex_uap_bss_param *bss_cfg = cmd_buf; u16 cmd_size = *param_size; u8 *tlv = *tlv_buf; tlv_akmp = (struct host_cmd_tlv_akmp *)tlv; tlv_akmp->header.type = cpu_to_le16(TLV_TYPE_UAP_AKMP); tlv_akmp->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_akmp) - sizeof(struct mwifiex_ie_types_header)); tlv_akmp->key_mgmt_operation = cpu_to_le16(bss_cfg->key_mgmt_operation); tlv_akmp->key_mgmt = cpu_to_le16(bss_cfg->key_mgmt); cmd_size += sizeof(struct host_cmd_tlv_akmp); tlv += sizeof(struct host_cmd_tlv_akmp); if (bss_cfg->wpa_cfg.pairwise_cipher_wpa & VALID_CIPHER_BITMAP) { pwk_cipher = (struct host_cmd_tlv_pwk_cipher *)tlv; pwk_cipher->header.type = cpu_to_le16(TLV_TYPE_PWK_CIPHER); pwk_cipher->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_pwk_cipher) - sizeof(struct mwifiex_ie_types_header)); pwk_cipher->proto = cpu_to_le16(PROTOCOL_WPA); pwk_cipher->cipher = bss_cfg->wpa_cfg.pairwise_cipher_wpa; cmd_size += sizeof(struct host_cmd_tlv_pwk_cipher); tlv += sizeof(struct host_cmd_tlv_pwk_cipher); } if (bss_cfg->wpa_cfg.pairwise_cipher_wpa2 & VALID_CIPHER_BITMAP) { pwk_cipher = (struct host_cmd_tlv_pwk_cipher *)tlv; pwk_cipher->header.type = cpu_to_le16(TLV_TYPE_PWK_CIPHER); pwk_cipher->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_pwk_cipher) - sizeof(struct mwifiex_ie_types_header)); pwk_cipher->proto = cpu_to_le16(PROTOCOL_WPA2); pwk_cipher->cipher = bss_cfg->wpa_cfg.pairwise_cipher_wpa2; cmd_size += sizeof(struct host_cmd_tlv_pwk_cipher); tlv += sizeof(struct host_cmd_tlv_pwk_cipher); } if (bss_cfg->wpa_cfg.group_cipher & VALID_CIPHER_BITMAP) { gwk_cipher = (struct host_cmd_tlv_gwk_cipher *)tlv; gwk_cipher->header.type = cpu_to_le16(TLV_TYPE_GWK_CIPHER); gwk_cipher->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_gwk_cipher) - sizeof(struct mwifiex_ie_types_header)); gwk_cipher->cipher = bss_cfg->wpa_cfg.group_cipher; cmd_size += sizeof(struct host_cmd_tlv_gwk_cipher); tlv += sizeof(struct host_cmd_tlv_gwk_cipher); } if (bss_cfg->wpa_cfg.length) { passphrase = (struct host_cmd_tlv_passphrase *)tlv; passphrase->header.type = cpu_to_le16(TLV_TYPE_UAP_WPA_PASSPHRASE); passphrase->header.len = cpu_to_le16(bss_cfg->wpa_cfg.length); memcpy(passphrase->passphrase, bss_cfg->wpa_cfg.passphrase, bss_cfg->wpa_cfg.length); cmd_size += sizeof(struct mwifiex_ie_types_header) + bss_cfg->wpa_cfg.length; tlv += sizeof(struct mwifiex_ie_types_header) + bss_cfg->wpa_cfg.length; } *param_size = cmd_size; *tlv_buf = tlv; return; } /* This function parses WMM related parameters from cfg80211_ap_settings * structure and updates bss_config structure. */ void mwifiex_set_wmm_params(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_cfg, struct cfg80211_ap_settings *params) { const u8 *vendor_ie; const u8 *wmm_ie; u8 wmm_oui[] = {0x00, 0x50, 0xf2, 0x02}; vendor_ie = cfg80211_find_vendor_ie(WLAN_OUI_MICROSOFT, WLAN_OUI_TYPE_MICROSOFT_WMM, params->beacon.tail, params->beacon.tail_len); if (vendor_ie) { wmm_ie = vendor_ie; if (*(wmm_ie + 1) > sizeof(struct mwifiex_types_wmm_info)) return; memcpy(&bss_cfg->wmm_info, wmm_ie + sizeof(struct ieee_types_header), *(wmm_ie + 1)); priv->wmm_enabled = 1; } else { memset(&bss_cfg->wmm_info, 0, sizeof(bss_cfg->wmm_info)); memcpy(&bss_cfg->wmm_info.oui, wmm_oui, sizeof(wmm_oui)); bss_cfg->wmm_info.subtype = MWIFIEX_WMM_SUBTYPE; bss_cfg->wmm_info.version = MWIFIEX_WMM_VERSION; priv->wmm_enabled = 0; } bss_cfg->qos_info = 0x00; return; } /* This function parses BSS related parameters from structure * and prepares TLVs specific to WEP encryption. * These TLVs are appended to command buffer. */ static void mwifiex_uap_bss_wep(u8 **tlv_buf, void *cmd_buf, u16 *param_size) { struct host_cmd_tlv_wep_key *wep_key; u16 cmd_size = *param_size; int i; u8 *tlv = *tlv_buf; struct mwifiex_uap_bss_param *bss_cfg = cmd_buf; for (i = 0; i < NUM_WEP_KEYS; i++) { if (bss_cfg->wep_cfg[i].length && (bss_cfg->wep_cfg[i].length == WLAN_KEY_LEN_WEP40 || bss_cfg->wep_cfg[i].length == WLAN_KEY_LEN_WEP104)) { wep_key = (struct host_cmd_tlv_wep_key *)tlv; wep_key->header.type = cpu_to_le16(TLV_TYPE_UAP_WEP_KEY); wep_key->header.len = cpu_to_le16(bss_cfg->wep_cfg[i].length + 2); wep_key->key_index = bss_cfg->wep_cfg[i].key_index; wep_key->is_default = bss_cfg->wep_cfg[i].is_default; memcpy(wep_key->key, bss_cfg->wep_cfg[i].key, bss_cfg->wep_cfg[i].length); cmd_size += sizeof(struct mwifiex_ie_types_header) + 2 + bss_cfg->wep_cfg[i].length; tlv += sizeof(struct mwifiex_ie_types_header) + 2 + bss_cfg->wep_cfg[i].length; } } *param_size = cmd_size; *tlv_buf = tlv; return; } /* This function enable 11D if userspace set the country IE. */ void mwifiex_config_uap_11d(struct mwifiex_private *priv, struct cfg80211_beacon_data *beacon_data) { enum state_11d_t state_11d; const u8 *country_ie; country_ie = cfg80211_find_ie(WLAN_EID_COUNTRY, beacon_data->tail, beacon_data->tail_len); if (country_ie) { /* Send cmd to FW to enable 11D function */ state_11d = ENABLE_11D; if (mwifiex_send_cmd(priv, HostCmd_CMD_802_11_SNMP_MIB, HostCmd_ACT_GEN_SET, DOT11D_I, &state_11d, true)) { mwifiex_dbg(priv->adapter, ERROR, "11D: failed to enable 11D\n"); } } } /* This function parses BSS related parameters from structure * and prepares TLVs. These TLVs are appended to command buffer. */ static int mwifiex_uap_bss_param_prepare(u8 *tlv, void *cmd_buf, u16 *param_size) { struct host_cmd_tlv_dtim_period *dtim_period; struct host_cmd_tlv_beacon_period *beacon_period; struct host_cmd_tlv_ssid *ssid; struct host_cmd_tlv_bcast_ssid *bcast_ssid; struct host_cmd_tlv_channel_band *chan_band; struct host_cmd_tlv_frag_threshold *frag_threshold; struct host_cmd_tlv_rts_threshold *rts_threshold; struct host_cmd_tlv_retry_limit *retry_limit; struct host_cmd_tlv_encrypt_protocol *encrypt_protocol; struct host_cmd_tlv_auth_type *auth_type; struct host_cmd_tlv_rates *tlv_rates; struct host_cmd_tlv_ageout_timer *ao_timer, *ps_ao_timer; struct host_cmd_tlv_power_constraint *pwr_ct; struct mwifiex_ie_types_htcap *htcap; struct mwifiex_ie_types_wmmcap *wmm_cap; struct mwifiex_uap_bss_param *bss_cfg = cmd_buf; int i; u16 cmd_size = *param_size; if (bss_cfg->ssid.ssid_len) { ssid = (struct host_cmd_tlv_ssid *)tlv; ssid->header.type = cpu_to_le16(TLV_TYPE_UAP_SSID); ssid->header.len = cpu_to_le16((u16)bss_cfg->ssid.ssid_len); memcpy(ssid->ssid, bss_cfg->ssid.ssid, bss_cfg->ssid.ssid_len); cmd_size += sizeof(struct mwifiex_ie_types_header) + bss_cfg->ssid.ssid_len; tlv += sizeof(struct mwifiex_ie_types_header) + bss_cfg->ssid.ssid_len; bcast_ssid = (struct host_cmd_tlv_bcast_ssid *)tlv; bcast_ssid->header.type = cpu_to_le16(TLV_TYPE_UAP_BCAST_SSID); bcast_ssid->header.len = cpu_to_le16(sizeof(bcast_ssid->bcast_ctl)); bcast_ssid->bcast_ctl = bss_cfg->bcast_ssid_ctl; cmd_size += sizeof(struct host_cmd_tlv_bcast_ssid); tlv += sizeof(struct host_cmd_tlv_bcast_ssid); } if (bss_cfg->rates[0]) { tlv_rates = (struct host_cmd_tlv_rates *)tlv; tlv_rates->header.type = cpu_to_le16(TLV_TYPE_UAP_RATES); for (i = 0; i < MWIFIEX_SUPPORTED_RATES && bss_cfg->rates[i]; i++) tlv_rates->rates[i] = bss_cfg->rates[i]; tlv_rates->header.len = cpu_to_le16(i); cmd_size += sizeof(struct host_cmd_tlv_rates) + i; tlv += sizeof(struct host_cmd_tlv_rates) + i; } if (bss_cfg->channel && (((bss_cfg->band_cfg & BIT(0)) == BAND_CONFIG_BG && bss_cfg->channel <= MAX_CHANNEL_BAND_BG) || ((bss_cfg->band_cfg & BIT(0)) == BAND_CONFIG_A && bss_cfg->channel <= MAX_CHANNEL_BAND_A))) { chan_band = (struct host_cmd_tlv_channel_band *)tlv; chan_band->header.type = cpu_to_le16(TLV_TYPE_CHANNELBANDLIST); chan_band->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_channel_band) - sizeof(struct mwifiex_ie_types_header)); chan_band->band_config = bss_cfg->band_cfg; chan_band->channel = bss_cfg->channel; cmd_size += sizeof(struct host_cmd_tlv_channel_band); tlv += sizeof(struct host_cmd_tlv_channel_band); } if (bss_cfg->beacon_period >= MIN_BEACON_PERIOD && bss_cfg->beacon_period <= MAX_BEACON_PERIOD) { beacon_period = (struct host_cmd_tlv_beacon_period *)tlv; beacon_period->header.type = cpu_to_le16(TLV_TYPE_UAP_BEACON_PERIOD); beacon_period->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_beacon_period) - sizeof(struct mwifiex_ie_types_header)); beacon_period->period = cpu_to_le16(bss_cfg->beacon_period); cmd_size += sizeof(struct host_cmd_tlv_beacon_period); tlv += sizeof(struct host_cmd_tlv_beacon_period); } if (bss_cfg->dtim_period >= MIN_DTIM_PERIOD && bss_cfg->dtim_period <= MAX_DTIM_PERIOD) { dtim_period = (struct host_cmd_tlv_dtim_period *)tlv; dtim_period->header.type = cpu_to_le16(TLV_TYPE_UAP_DTIM_PERIOD); dtim_period->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_dtim_period) - sizeof(struct mwifiex_ie_types_header)); dtim_period->period = bss_cfg->dtim_period; cmd_size += sizeof(struct host_cmd_tlv_dtim_period); tlv += sizeof(struct host_cmd_tlv_dtim_period); } if (bss_cfg->rts_threshold <= MWIFIEX_RTS_MAX_VALUE) { rts_threshold = (struct host_cmd_tlv_rts_threshold *)tlv; rts_threshold->header.type = cpu_to_le16(TLV_TYPE_UAP_RTS_THRESHOLD); rts_threshold->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_rts_threshold) - sizeof(struct mwifiex_ie_types_header)); rts_threshold->rts_thr = cpu_to_le16(bss_cfg->rts_threshold); cmd_size += sizeof(struct host_cmd_tlv_frag_threshold); tlv += sizeof(struct host_cmd_tlv_frag_threshold); } if ((bss_cfg->frag_threshold >= MWIFIEX_FRAG_MIN_VALUE) && (bss_cfg->frag_threshold <= MWIFIEX_FRAG_MAX_VALUE)) { frag_threshold = (struct host_cmd_tlv_frag_threshold *)tlv; frag_threshold->header.type = cpu_to_le16(TLV_TYPE_UAP_FRAG_THRESHOLD); frag_threshold->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_frag_threshold) - sizeof(struct mwifiex_ie_types_header)); frag_threshold->frag_thr = cpu_to_le16(bss_cfg->frag_threshold); cmd_size += sizeof(struct host_cmd_tlv_frag_threshold); tlv += sizeof(struct host_cmd_tlv_frag_threshold); } if (bss_cfg->retry_limit <= MWIFIEX_RETRY_LIMIT) { retry_limit = (struct host_cmd_tlv_retry_limit *)tlv; retry_limit->header.type = cpu_to_le16(TLV_TYPE_UAP_RETRY_LIMIT); retry_limit->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_retry_limit) - sizeof(struct mwifiex_ie_types_header)); retry_limit->limit = (u8)bss_cfg->retry_limit; cmd_size += sizeof(struct host_cmd_tlv_retry_limit); tlv += sizeof(struct host_cmd_tlv_retry_limit); } if ((bss_cfg->protocol & PROTOCOL_WPA) || (bss_cfg->protocol & PROTOCOL_WPA2) || (bss_cfg->protocol & PROTOCOL_EAP)) mwifiex_uap_bss_wpa(&tlv, cmd_buf, &cmd_size); else mwifiex_uap_bss_wep(&tlv, cmd_buf, &cmd_size); if ((bss_cfg->auth_mode <= WLAN_AUTH_SHARED_KEY) || (bss_cfg->auth_mode == MWIFIEX_AUTH_MODE_AUTO)) { auth_type = (struct host_cmd_tlv_auth_type *)tlv; auth_type->header.type = cpu_to_le16(TLV_TYPE_AUTH_TYPE); auth_type->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_auth_type) - sizeof(struct mwifiex_ie_types_header)); auth_type->auth_type = (u8)bss_cfg->auth_mode; cmd_size += sizeof(struct host_cmd_tlv_auth_type); tlv += sizeof(struct host_cmd_tlv_auth_type); } if (bss_cfg->protocol) { encrypt_protocol = (struct host_cmd_tlv_encrypt_protocol *)tlv; encrypt_protocol->header.type = cpu_to_le16(TLV_TYPE_UAP_ENCRY_PROTOCOL); encrypt_protocol->header.len = cpu_to_le16(sizeof(struct host_cmd_tlv_encrypt_protocol) - sizeof(struct mwifiex_ie_types_header)); encrypt_protocol->proto = cpu_to_le16(bss_cfg->protocol); cmd_size += sizeof(struct host_cmd_tlv_encrypt_protocol); tlv += sizeof(struct host_cmd_tlv_encrypt_protocol); } if (bss_cfg->ht_cap.cap_info) { htcap = (struct mwifiex_ie_types_htcap *)tlv; htcap->header.type = cpu_to_le16(WLAN_EID_HT_CAPABILITY); htcap->header.len = cpu_to_le16(sizeof(struct ieee80211_ht_cap)); htcap->ht_cap.cap_info = bss_cfg->ht_cap.cap_info; htcap->ht_cap.ampdu_params_info = bss_cfg->ht_cap.ampdu_params_info; memcpy(&htcap->ht_cap.mcs, &bss_cfg->ht_cap.mcs, sizeof(struct ieee80211_mcs_info)); htcap->ht_cap.extended_ht_cap_info = bss_cfg->ht_cap.extended_ht_cap_info; htcap->ht_cap.tx_BF_cap_info = bss_cfg->ht_cap.tx_BF_cap_info; htcap->ht_cap.antenna_selection_info = bss_cfg->ht_cap.antenna_selection_info; cmd_size += sizeof(struct mwifiex_ie_types_htcap); tlv += sizeof(struct mwifiex_ie_types_htcap); } if (bss_cfg->wmm_info.qos_info != 0xFF) { wmm_cap = (struct mwifiex_ie_types_wmmcap *)tlv; wmm_cap->header.type = cpu_to_le16(WLAN_EID_VENDOR_SPECIFIC); wmm_cap->header.len = cpu_to_le16(sizeof(wmm_cap->wmm_info)); memcpy(&wmm_cap->wmm_info, &bss_cfg->wmm_info, sizeof(wmm_cap->wmm_info)); cmd_size += sizeof(struct mwifiex_ie_types_wmmcap); tlv += sizeof(struct mwifiex_ie_types_wmmcap); } if (bss_cfg->sta_ao_timer) { ao_timer = (struct host_cmd_tlv_ageout_timer *)tlv; ao_timer->header.type = cpu_to_le16(TLV_TYPE_UAP_AO_TIMER); ao_timer->header.len = cpu_to_le16(sizeof(*ao_timer) - sizeof(struct mwifiex_ie_types_header)); ao_timer->sta_ao_timer = cpu_to_le32(bss_cfg->sta_ao_timer); cmd_size += sizeof(*ao_timer); tlv += sizeof(*ao_timer); } if (bss_cfg->power_constraint) { pwr_ct = (void *)tlv; pwr_ct->header.type = cpu_to_le16(TLV_TYPE_PWR_CONSTRAINT); pwr_ct->header.len = cpu_to_le16(sizeof(u8)); pwr_ct->constraint = bss_cfg->power_constraint; cmd_size += sizeof(*pwr_ct); tlv += sizeof(*pwr_ct); } if (bss_cfg->ps_sta_ao_timer) { ps_ao_timer = (struct host_cmd_tlv_ageout_timer *)tlv; ps_ao_timer->header.type = cpu_to_le16(TLV_TYPE_UAP_PS_AO_TIMER); ps_ao_timer->header.len = cpu_to_le16(sizeof(*ps_ao_timer) - sizeof(struct mwifiex_ie_types_header)); ps_ao_timer->sta_ao_timer = cpu_to_le32(bss_cfg->ps_sta_ao_timer); cmd_size += sizeof(*ps_ao_timer); tlv += sizeof(*ps_ao_timer); } *param_size = cmd_size; return 0; } /* This function parses custom IEs from IE list and prepares command buffer */ static int mwifiex_uap_custom_ie_prepare(u8 *tlv, void *cmd_buf, u16 *ie_size) { struct mwifiex_ie_list *ap_ie = cmd_buf; struct mwifiex_ie_types_header *tlv_ie = (void *)tlv; if (!ap_ie || !ap_ie->len) return -1; *ie_size += le16_to_cpu(ap_ie->len) + sizeof(struct mwifiex_ie_types_header); tlv_ie->type = cpu_to_le16(TLV_TYPE_MGMT_IE); tlv_ie->len = ap_ie->len; tlv += sizeof(struct mwifiex_ie_types_header); memcpy(tlv, ap_ie->ie_list, le16_to_cpu(ap_ie->len)); return 0; } /* Parse AP config structure and prepare TLV based command structure * to be sent to FW for uAP configuration */ static int mwifiex_cmd_uap_sys_config(struct host_cmd_ds_command *cmd, u16 cmd_action, u32 type, void *cmd_buf) { u8 *tlv; u16 cmd_size, param_size, ie_size; struct host_cmd_ds_sys_config *sys_cfg; cmd->command = cpu_to_le16(HostCmd_CMD_UAP_SYS_CONFIG); cmd_size = (u16)(sizeof(struct host_cmd_ds_sys_config) + S_DS_GEN); sys_cfg = (struct host_cmd_ds_sys_config *)&cmd->params.uap_sys_config; sys_cfg->action = cpu_to_le16(cmd_action); tlv = sys_cfg->tlv; switch (type) { case UAP_BSS_PARAMS_I: param_size = cmd_size; if (mwifiex_uap_bss_param_prepare(tlv, cmd_buf, &param_size)) return -1; cmd->size = cpu_to_le16(param_size); break; case UAP_CUSTOM_IE_I: ie_size = cmd_size; if (mwifiex_uap_custom_ie_prepare(tlv, cmd_buf, &ie_size)) return -1; cmd->size = cpu_to_le16(ie_size); break; default: return -1; } return 0; } /* This function prepares AP specific deauth command with mac supplied in * function parameter. */ static int mwifiex_cmd_uap_sta_deauth(struct mwifiex_private *priv, struct host_cmd_ds_command *cmd, u8 *mac) { struct host_cmd_ds_sta_deauth *sta_deauth = &cmd->params.sta_deauth; cmd->command = cpu_to_le16(HostCmd_CMD_UAP_STA_DEAUTH); memcpy(sta_deauth->mac, mac, ETH_ALEN); sta_deauth->reason = cpu_to_le16(WLAN_REASON_DEAUTH_LEAVING); cmd->size = cpu_to_le16(sizeof(struct host_cmd_ds_sta_deauth) + S_DS_GEN); return 0; } /* This function prepares the AP specific commands before sending them * to the firmware. * This is a generic function which calls specific command preparation * routines based upon the command number. */ int mwifiex_uap_prepare_cmd(struct mwifiex_private *priv, u16 cmd_no, u16 cmd_action, u32 type, void *data_buf, void *cmd_buf) { struct host_cmd_ds_command *cmd = cmd_buf; switch (cmd_no) { case HostCmd_CMD_UAP_SYS_CONFIG: if (mwifiex_cmd_uap_sys_config(cmd, cmd_action, type, data_buf)) return -1; break; case HostCmd_CMD_UAP_BSS_START: case HostCmd_CMD_UAP_BSS_STOP: case HOST_CMD_APCMD_SYS_RESET: case HOST_CMD_APCMD_STA_LIST: cmd->command = cpu_to_le16(cmd_no); cmd->size = cpu_to_le16(S_DS_GEN); break; case HostCmd_CMD_UAP_STA_DEAUTH: if (mwifiex_cmd_uap_sta_deauth(priv, cmd, data_buf)) return -1; break; case HostCmd_CMD_CHAN_REPORT_REQUEST: if (mwifiex_cmd_issue_chan_report_request(priv, cmd_buf, data_buf)) return -1; break; default: mwifiex_dbg(priv->adapter, ERROR, "PREP_CMD: unknown cmd %#x\n", cmd_no); return -1; } return 0; } void mwifiex_uap_set_channel(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_cfg, struct cfg80211_chan_def chandef) { u8 config_bands = 0, old_bands = priv->adapter->config_bands; priv->bss_chandef = chandef; bss_cfg->channel = ieee80211_frequency_to_channel( chandef.chan->center_freq); /* Set appropriate bands */ if (chandef.chan->band == NL80211_BAND_2GHZ) { bss_cfg->band_cfg = BAND_CONFIG_BG; config_bands = BAND_B | BAND_G; if (chandef.width > NL80211_CHAN_WIDTH_20_NOHT) config_bands |= BAND_GN; } else { bss_cfg->band_cfg = BAND_CONFIG_A; config_bands = BAND_A; if (chandef.width > NL80211_CHAN_WIDTH_20_NOHT) config_bands |= BAND_AN; if (chandef.width > NL80211_CHAN_WIDTH_40) config_bands |= BAND_AAC; } switch (chandef.width) { case NL80211_CHAN_WIDTH_5: case NL80211_CHAN_WIDTH_10: case NL80211_CHAN_WIDTH_20_NOHT: case NL80211_CHAN_WIDTH_20: break; case NL80211_CHAN_WIDTH_40: if (chandef.center_freq1 < chandef.chan->center_freq) bss_cfg->band_cfg |= MWIFIEX_SEC_CHAN_BELOW; else bss_cfg->band_cfg |= MWIFIEX_SEC_CHAN_ABOVE; break; case NL80211_CHAN_WIDTH_80: case NL80211_CHAN_WIDTH_80P80: case NL80211_CHAN_WIDTH_160: bss_cfg->band_cfg |= mwifiex_get_sec_chan_offset(bss_cfg->channel) << 4; break; default: mwifiex_dbg(priv->adapter, WARN, "Unknown channel width: %d\n", chandef.width); break; } priv->adapter->config_bands = config_bands; if (old_bands != config_bands) { mwifiex_send_domain_info_cmd_fw(priv->adapter->wiphy); mwifiex_dnld_txpwr_table(priv); } } int mwifiex_config_start_uap(struct mwifiex_private *priv, struct mwifiex_uap_bss_param *bss_cfg) { if (mwifiex_send_cmd(priv, HostCmd_CMD_UAP_SYS_CONFIG, HostCmd_ACT_GEN_SET, UAP_BSS_PARAMS_I, bss_cfg, true)) { mwifiex_dbg(priv->adapter, ERROR, "Failed to set AP configuration\n"); return -1; } if (mwifiex_send_cmd(priv, HostCmd_CMD_UAP_BSS_START, HostCmd_ACT_GEN_SET, 0, NULL, true)) { mwifiex_dbg(priv->adapter, ERROR, "Failed to start the BSS\n"); return -1; } if (priv->sec_info.wep_enabled) priv->curr_pkt_filter |= HostCmd_ACT_MAC_WEP_ENABLE; else priv->curr_pkt_filter &= ~HostCmd_ACT_MAC_WEP_ENABLE; if (mwifiex_send_cmd(priv, HostCmd_CMD_MAC_CONTROL, HostCmd_ACT_GEN_SET, 0, &priv->curr_pkt_filter, true)) return -1; return 0; }
null
135
CWE-787
CVE-2019-14934
/****************************************************************************** * main.h * * pdfresurrect - PDF history extraction tool * * Copyright (C) 2008, 2009, 2010, 2012, 2019 Matt Davis (enferex). * * Special thanks to all of the contributors: See AUTHORS. * * Special thanks to 757labs (757 crew), they are a great group * of people to hack on projects and brainstorm with. * * main.h is part of pdfresurrect. * pdfresurrect is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * pdfresurrect is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with pdfresurrect. If not, see <http://www.gnu.org/licenses/>. *****************************************************************************/ #ifndef MAIN_H_INCLUDE #define MAIN_H_INCLUDE #include <stdio.h> #define EXEC_NAME "pdfresurrect" #define VER_MAJOR "0" #define VER_MINOR "18b" #define VER VER_MAJOR"."VER_MINOR #define TAG "[pdfresurrect]" #define ERR(...) {fprintf(stderr, TAG" -- Error -- " __VA_ARGS__);} #endif /* MAIN_H_INCLUDE */
null
/****************************************************************************** * main.h * * pdfresurrect - PDF history extraction tool * * Copyright (C) 2008, 2009, 2010, 2012, 2019 Matt Davis (enferex). * * Special thanks to all of the contributors: See AUTHORS. * * Special thanks to 757labs (757 crew), they are a great group * of people to hack on projects and brainstorm with. * * main.h is part of pdfresurrect. * pdfresurrect is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * pdfresurrect is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with pdfresurrect. If not, see <http://www.gnu.org/licenses/>. *****************************************************************************/ #ifndef MAIN_H_INCLUDE #define MAIN_H_INCLUDE #include <stdio.h> #define EXEC_NAME "pdfresurrect" #define VER_MAJOR "0" #define VER_MINOR "18b" #define VER VER_MAJOR"."VER_MINOR #define TAG "[pdfresurrect]" #define ERR(...) {fprintf(stderr, TAG" -- Error -- " __VA_ARGS__);} /* Returns a zero'd buffer of 'size' bytes or exits in failure. */ extern void *safe_calloc(size_t bytes); #endif /* MAIN_H_INCLUDE */
null
136
CWE-787
CVE-2019-15148
/*! @file GPMF_parser.c * * @brief GPMF Parser library * * @version 1.2.1 * * (C) Copyright 2017 GoPro Inc (http://gopro.com/). * * Licensed under either: * - Apache License, Version 2.0, http://www.apache.org/licenses/LICENSE-2.0 * - MIT license, http://opensource.org/licenses/MIT * at your option. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdint.h> #include "GPMF_parser.h" #ifdef DBG #if _WINDOWS #define DBG_MSG printf #else #define DBG_MSG(...) #endif #else #define DBG_MSG(...) #endif GPMF_ERR IsValidSize(GPMF_stream *ms, uint32_t size) // size is in longs not bytes. { if (ms) { int32_t nestsize = (int32_t)ms->nest_size[ms->nest_level]; if (nestsize == 0 && ms->nest_level == 0) nestsize = ms->buffer_size_longs; if (size + 2 <= nestsize) return GPMF_OK; } return GPMF_ERROR_BAD_STRUCTURE; } GPMF_ERR GPMF_Validate(GPMF_stream *ms, GPMF_LEVELS recurse) { if (ms) { uint32_t currpos = ms->pos; int32_t nestsize = (int32_t)ms->nest_size[ms->nest_level]; if (nestsize == 0 && ms->nest_level == 0) nestsize = ms->buffer_size_longs; while (ms->pos+1 < ms->buffer_size_longs && nestsize > 0) { uint32_t key = ms->buffer[ms->pos]; if (ms->nest_level == 0 && key != GPMF_KEY_DEVICE && ms->device_count == 0 && ms->pos == 0) { DBG_MSG("ERROR: uninitized -- GPMF_ERROR_BAD_STRUCTURE\n"); return GPMF_ERROR_BAD_STRUCTURE; } if (GPMF_VALID_FOURCC(key)) { uint32_t type_size_repeat = ms->buffer[ms->pos + 1]; int32_t size = GPMF_DATA_SIZE(type_size_repeat) >> 2; uint8_t type = GPMF_SAMPLE_TYPE(type_size_repeat); if (size + 2 > nestsize) { DBG_MSG("ERROR: nest size too small within %c%c%c%c-- GPMF_ERROR_BAD_STRUCTURE\n", PRINTF_4CC(key)); return GPMF_ERROR_BAD_STRUCTURE; } if (!GPMF_VALID_FOURCC(key)) { DBG_MSG("ERROR: invalid 4CC -- GPMF_ERROR_BAD_STRUCTURE\n"); return GPMF_ERROR_BAD_STRUCTURE; } if (type == GPMF_TYPE_NEST && recurse == GPMF_RECURSE_LEVELS) { uint32_t validnest; ms->pos += 2; ms->nest_level++; if (ms->nest_level > GPMF_NEST_LIMIT) { DBG_MSG("ERROR: nest level within %c%c%c%c too deep -- GPMF_ERROR_BAD_STRUCTURE\n", PRINTF_4CC(key)); return GPMF_ERROR_BAD_STRUCTURE; } ms->nest_size[ms->nest_level] = size; validnest = GPMF_Validate(ms, recurse); ms->nest_level--; if (GPMF_OK != validnest) { DBG_MSG("ERROR: invalid nest within %c%c%c%c -- GPMF_ERROR_BAD_STRUCTURE\n", PRINTF_4CC(key)); return GPMF_ERROR_BAD_STRUCTURE; } else { if (ms->nest_level == 0) ms->device_count++; } ms->pos += size; nestsize -= 2 + size; while (ms->pos < ms->buffer_size_longs && nestsize > 0 && ms->buffer[ms->pos] == GPMF_KEY_END) { ms->pos++; nestsize--; } } else { ms->pos += 2 + size; nestsize -= 2 + size; } if (ms->pos == ms->buffer_size_longs) { ms->pos = currpos; return GPMF_OK; } } else { if (key == GPMF_KEY_END) { do { ms->pos++; nestsize--; } while (ms->pos < ms->buffer_size_longs && nestsize > 0 && ms->buffer[ms->pos] == 0); } else if (ms->nest_level == 0 && ms->device_count > 0) { ms->pos = currpos; return GPMF_OK; } else { DBG_MSG("ERROR: bad struct within %c%c%c%c -- GPMF_ERROR_BAD_STRUCTURE\n", PRINTF_4CC(key)); return GPMF_ERROR_BAD_STRUCTURE; } } } ms->pos = currpos; return GPMF_OK; } else { DBG_MSG("ERROR: Invalid handle -- GPMF_ERROR_MEMORY\n"); return GPMF_ERROR_MEMORY; } } GPMF_ERR GPMF_ResetState(GPMF_stream *ms) { if (ms) { ms->pos = 0; ms->nest_level = 0; ms->device_count = 0; ms->nest_size[ms->nest_level] = 0; ms->last_level_pos[ms->nest_level] = 0; ms->last_seek[ms->nest_level] = 0; ms->device_id = 0; ms->device_name[0] = 0; return GPMF_OK; } return GPMF_ERROR_MEMORY; } GPMF_ERR GPMF_Init(GPMF_stream *ms, uint32_t *buffer, int datasize) { if(ms) { ms->buffer = buffer; ms->buffer_size_longs = datasize >>2; GPMF_ResetState(ms); return GPMF_OK; } return GPMF_ERROR_MEMORY; } GPMF_ERR GPMF_CopyState(GPMF_stream *msrc, GPMF_stream *mdst) { if (msrc && mdst) { memcpy(mdst, msrc, sizeof(GPMF_stream)); return GPMF_OK; } return GPMF_ERROR_MEMORY; } GPMF_ERR GPMF_Next(GPMF_stream *ms, GPMF_LEVELS recurse) { if (ms) { if (ms->pos+1 < ms->buffer_size_longs) { uint32_t key, type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]); uint32_t size = (GPMF_DATA_SIZE(ms->buffer[ms->pos + 1]) >> 2); if (GPMF_OK != IsValidSize(ms, size)) return GPMF_ERROR_BAD_STRUCTURE; if (GPMF_TYPE_NEST == type && GPMF_KEY_DEVICE == ms->buffer[ms->pos] && ms->nest_level == 0) { ms->last_level_pos[ms->nest_level] = ms->pos; ms->nest_size[ms->nest_level] = size; if (recurse) ms->pos += 2; else ms->pos += 2 + size; } else { if (size + 2 > ms->nest_size[ms->nest_level]) return GPMF_ERROR_BAD_STRUCTURE; if (recurse && type == GPMF_TYPE_NEST) { ms->last_level_pos[ms->nest_level] = ms->pos; ms->pos += 2; ms->nest_size[ms->nest_level] -= size + 2; ms->nest_level++; if (ms->nest_level > GPMF_NEST_LIMIT) return GPMF_ERROR_BAD_STRUCTURE; ms->nest_size[ms->nest_level] = size; } else { if (recurse) { ms->pos += size + 2; ms->nest_size[ms->nest_level] -= size + 2; } else { if (ms->nest_size[ms->nest_level] - (size + 2) > 0) { ms->pos += size + 2; ms->nest_size[ms->nest_level] -= size + 2; } else { return GPMF_ERROR_LAST; } } } } while (ms->pos < ms->buffer_size_longs && ms->nest_size[ms->nest_level] > 0 && ms->buffer[ms->pos] == GPMF_KEY_END) { ms->pos++; ms->nest_size[ms->nest_level]--; } while (ms->nest_level > 0 && ms->nest_size[ms->nest_level] == 0) { ms->nest_level--; //if (ms->nest_level == 0) //{ // ms->device_count++; //} } if (ms->pos < ms->buffer_size_longs) { while (ms->pos < ms->buffer_size_longs && ms->nest_size[ms->nest_level] > 0 && ms->buffer[ms->pos] == GPMF_KEY_END) { ms->pos++; ms->nest_size[ms->nest_level]--; } key = ms->buffer[ms->pos]; if (!GPMF_VALID_FOURCC(key)) return GPMF_ERROR_BAD_STRUCTURE; if (key == GPMF_KEY_DEVICE_ID) ms->device_id = BYTESWAP32(ms->buffer[ms->pos + 2]); if (key == GPMF_KEY_DEVICE_NAME) { size = GPMF_DATA_SIZE(ms->buffer[ms->pos + 1]); // in bytes if (size > sizeof(ms->device_name) - 1) size = sizeof(ms->device_name) - 1; memcpy(ms->device_name, &ms->buffer[ms->pos + 2], size); ms->device_name[size] = 0; } } else { // end of buffer return GPMF_ERROR_BUFFER_END; } return GPMF_OK; } else { // end of buffer return GPMF_ERROR_BUFFER_END; } } return GPMF_ERROR_MEMORY; } GPMF_ERR GPMF_FindNext(GPMF_stream *ms, uint32_t fourcc, GPMF_LEVELS recurse) { GPMF_stream prevstate; if (ms) { memcpy(&prevstate, ms, sizeof(GPMF_stream)); if (ms->pos < ms->buffer_size_longs) { while (0 == GPMF_Next(ms, recurse)) { if (ms->buffer[ms->pos] == fourcc) { return GPMF_OK; //found match } } // restore read position memcpy(ms, &prevstate, sizeof(GPMF_stream)); return GPMF_ERROR_FIND; } } return GPMF_ERROR_FIND; } GPMF_ERR GPMF_Reserved(uint32_t key) { if(key == GPMF_KEY_DEVICE) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_DEVICE_ID) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_DEVICE_NAME) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_STREAM) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_STREAM_NAME) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_SI_UNITS) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_UNITS) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_SCALE) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_TYPE) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_TOTAL_SAMPLES) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_TICK) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_TOCK) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_EMPTY_PAYLOADS) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_REMARK) return GPMF_ERROR_RESERVED; return GPMF_OK; } uint32_t GPMF_PayloadSampleCount(GPMF_stream *ms) { uint32_t count = 0; if (ms) { uint32_t fourcc = GPMF_Key(ms); GPMF_stream find_stream; GPMF_CopyState(ms, &find_stream); if (GPMF_OK == GPMF_FindNext(&find_stream, fourcc, GPMF_CURRENT_LEVEL)) // Count the instances, not the repeats { count=2; while (GPMF_OK == GPMF_FindNext(&find_stream, fourcc, GPMF_CURRENT_LEVEL)) { count++; } } else { count = GPMF_Repeat(ms); } } return count; } GPMF_ERR GPMF_SeekToSamples(GPMF_stream *ms) { GPMF_stream prevstate; if (ms) { if (ms->pos+1 < ms->buffer_size_longs) { uint32_t type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]); memcpy(&prevstate, ms, sizeof(GPMF_stream)); if (type == GPMF_TYPE_NEST) GPMF_Next(ms, GPMF_RECURSE_LEVELS); // open STRM and recurse in while (0 == GPMF_Next(ms, GPMF_CURRENT_LEVEL)) { uint32_t size = (GPMF_DATA_SIZE(ms->buffer[ms->pos + 1]) >> 2); if (GPMF_OK != IsValidSize(ms, size)) { memcpy(ms, &prevstate, sizeof(GPMF_stream)); return GPMF_ERROR_BAD_STRUCTURE; } type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]); if (type == GPMF_TYPE_NEST) // Nest with-in nest { return GPMF_OK; //found match } if (size + 2 == ms->nest_size[ms->nest_level]) { uint32_t key = GPMF_Key(ms); if (GPMF_ERROR_RESERVED == GPMF_Reserved(key)) return GPMF_ERROR_FIND; return GPMF_OK; //found match } if (ms->buffer[ms->pos] == ms->buffer[ms->pos + size + 2]) // Matching tags { return GPMF_OK; //found match } } // restore read position memcpy(ms, &prevstate, sizeof(GPMF_stream)); return GPMF_ERROR_FIND; } } return GPMF_ERROR_FIND; } GPMF_ERR GPMF_FindPrev(GPMF_stream *ms, uint32_t fourcc, GPMF_LEVELS recurse) { GPMF_stream prevstate; if (ms) { uint32_t curr_level = ms->nest_level; memcpy(&prevstate, ms, sizeof(GPMF_stream)); if (ms->pos < ms->buffer_size_longs && curr_level > 0) { do { ms->last_seek[curr_level] = ms->pos; ms->pos = ms->last_level_pos[curr_level - 1] + 2; ms->nest_size[curr_level] += ms->last_seek[curr_level] - ms->pos; do { if (ms->last_seek[curr_level] > ms->pos && ms->buffer[ms->pos] == fourcc) { return GPMF_OK; //found match } } while (ms->last_seek[curr_level] > ms->pos && 0 == GPMF_Next(ms, GPMF_CURRENT_LEVEL)); curr_level--; } while (recurse == GPMF_RECURSE_LEVELS && curr_level > 0); // restore read position memcpy(ms, &prevstate, sizeof(GPMF_stream)); return GPMF_ERROR_FIND; } } return GPMF_ERROR_FIND; } uint32_t GPMF_Key(GPMF_stream *ms) { if (ms) { uint32_t key = ms->buffer[ms->pos]; return key; } return 0; } uint32_t GPMF_Type(GPMF_stream *ms) { if (ms && ms->pos+1 < ms->buffer_size_longs) { uint32_t type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos+1]); return type; } return 0; } uint32_t GPMF_StructSize(GPMF_stream *ms) { if (ms && ms->pos+1 < ms->buffer_size_longs) { uint32_t ssize = GPMF_SAMPLE_SIZE(ms->buffer[ms->pos + 1]); uint32_t size = (GPMF_DATA_SIZE(ms->buffer[ms->pos + 1]) >> 2); if (GPMF_OK != IsValidSize(ms, size)) return 0; // as the structure is corrupted. i.e. GPMF_ERROR_BAD_STRUCTURE; return ssize; } return 0; } uint32_t GPMF_ElementsInStruct(GPMF_stream *ms) { if (ms && ms->pos+1 < ms->buffer_size_longs) { uint32_t ssize = GPMF_StructSize(ms); GPMF_SampleType type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]); if (type != GPMF_TYPE_NEST && type != GPMF_TYPE_COMPLEX) { int32_t tsize = GPMF_SizeofType(type); if (tsize > 0) return ssize / tsize; else return 0; } if (type == GPMF_TYPE_COMPLEX) { GPMF_stream find_stream; GPMF_CopyState(ms, &find_stream); if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TYPE, GPMF_CURRENT_LEVEL)) { char tmp[64] = ""; uint32_t tmpsize = sizeof(tmp); char *data = (char *)GPMF_RawData(&find_stream); int size = GPMF_RawDataSize(&find_stream); if (GPMF_OK == GPMF_ExpandComplexTYPE(data, size, tmp, &tmpsize)) return tmpsize; } } } return 0; } uint32_t GPMF_Repeat(GPMF_stream *ms) { if (ms && ms->pos+1 < ms->buffer_size_longs) { uint32_t repeat = GPMF_SAMPLES(ms->buffer[ms->pos + 1]); return repeat; } return 0; } uint32_t GPMF_RawDataSize(GPMF_stream *ms) { if (ms && ms->pos+1 < ms->buffer_size_longs) { uint32_t size = GPMF_DATA_PACKEDSIZE(ms->buffer[ms->pos + 1]); if (GPMF_OK != IsValidSize(ms, size >> 2)) return 0; return size; } return 0; } uint32_t GPMF_NestLevel(GPMF_stream *ms) { if (ms) { return ms->nest_level; } return 0; } uint32_t GPMF_DeviceID(GPMF_stream *ms) { if (ms) { return ms->device_id; } return 0; } GPMF_ERR GPMF_DeviceName(GPMF_stream *ms, char *devicenamebuf, uint32_t devicename_buf_size) { if (ms && devicenamebuf) { uint32_t len = (uint32_t)strlen(ms->device_name); if (len >= devicename_buf_size) return GPMF_ERROR_MEMORY; memcpy(devicenamebuf, ms->device_name, len); devicenamebuf[len] = 0; return GPMF_OK; } return GPMF_ERROR_MEMORY; } void *GPMF_RawData(GPMF_stream *ms) { if (ms) { return (void *)&ms->buffer[ms->pos + 2]; } return NULL; } uint32_t GPMF_SizeofType(GPMF_SampleType type) { uint32_t ssize = 0; switch ((int)type) { case GPMF_TYPE_STRING_ASCII: ssize = 1; break; case GPMF_TYPE_SIGNED_BYTE: ssize = 1; break; case GPMF_TYPE_UNSIGNED_BYTE: ssize = 1; break; // These datatypes are always be stored in Big-Endian case GPMF_TYPE_SIGNED_SHORT: ssize = 2; break; case GPMF_TYPE_UNSIGNED_SHORT: ssize = 2; break; case GPMF_TYPE_FLOAT: ssize = 4; break; case GPMF_TYPE_FOURCC: ssize = 4; break; case GPMF_TYPE_SIGNED_LONG: ssize = 4; break; case GPMF_TYPE_UNSIGNED_LONG: ssize = 4; break; case GPMF_TYPE_Q15_16_FIXED_POINT: ssize = 4; break; case GPMF_TYPE_Q31_32_FIXED_POINT: ssize = 8; break; case GPMF_TYPE_DOUBLE: ssize = 8; break; case GPMF_TYPE_SIGNED_64BIT_INT: ssize = 8; break; case GPMF_TYPE_UNSIGNED_64BIT_INT: ssize = 8; break; //All unknown or larger than 8-bytes stored as is: case GPMF_TYPE_GUID: ssize = 16; break; case GPMF_TYPE_UTC_DATE_TIME: ssize = 16; break; } return ssize; } uint32_t GPMF_ExpandComplexTYPE(char *src, uint32_t srcsize, char *dst, uint32_t *dstsize) { uint32_t i = 0, k = 0, count = 0; while (i<srcsize && k<*dstsize) { if (src[i] == '[' && i>0) { int j = 1; count = 0; while (src[i + j] >= '0' && src[i + j] <= '9') { count *= 10; count += src[i + j] - '0'; j++; } if (count > 1) { uint32_t l; for (l = 1; l<count; l++) { dst[k] = src[i - 1]; k++; } } i += j; if (src[i] == ']') i++; } else { dst[k] = src[i]; if (dst[k] == 0) break; i++, k++; } } if (k >= *dstsize) return GPMF_ERROR_MEMORY; // bad structure formed dst[k] = 0; *dstsize = k; return GPMF_OK; } uint32_t GPMF_SizeOfComplexTYPE(char *type, uint32_t typestringlength) { char *typearray = type; uint32_t size = 0, expand = 0; uint32_t i, len = typestringlength; for (i = 0; i < len; i++) if (typearray[i] == '[') expand = 1; if (expand) { char exptypearray[64]; uint32_t dstsize = sizeof(exptypearray); if (GPMF_OK == GPMF_ExpandComplexTYPE(typearray, len, exptypearray, &dstsize)) { typearray = exptypearray; len = dstsize; } else return 0; } for (i = 0; i < len; i++) { uint32_t typesize = GPMF_SizeofType((GPMF_SampleType)typearray[i]); if (typesize < 1) return 0; size += typesize; } return size; } GPMF_ERR GPMF_FormattedData(GPMF_stream *ms, void *buffer, uint32_t buffersize, uint32_t sample_offset, uint32_t read_samples) { if (ms && buffer) { uint8_t *data = (uint8_t *)&ms->buffer[ms->pos + 2]; uint8_t *output = (uint8_t *)buffer; uint32_t sample_size = GPMF_SAMPLE_SIZE(ms->buffer[ms->pos + 1]); uint32_t remaining_sample_size = GPMF_DATA_PACKEDSIZE(ms->buffer[ms->pos + 1]); uint8_t type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]); uint32_t typesize = 1; uint32_t elements = 0; uint32_t typestringlength = 1; char complextype[64] = "L"; if (type == GPMF_TYPE_NEST) return GPMF_ERROR_BAD_STRUCTURE; if (GPMF_OK != IsValidSize(ms, remaining_sample_size>>2)) return GPMF_ERROR_BAD_STRUCTURE; if (sample_size * read_samples > buffersize) return GPMF_ERROR_MEMORY; remaining_sample_size -= sample_offset * sample_size; // skip samples data += sample_offset * sample_size; if (remaining_sample_size < sample_size * read_samples) return GPMF_ERROR_MEMORY; if (type == GPMF_TYPE_COMPLEX) { GPMF_stream find_stream; GPMF_CopyState(ms, &find_stream); if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TYPE, GPMF_RECURSE_LEVELS)) { char *data1 = (char *)GPMF_RawData(&find_stream); int size = GPMF_RawDataSize(&find_stream); typestringlength = sizeof(complextype); if (GPMF_OK == GPMF_ExpandComplexTYPE(data1, size, complextype, &typestringlength)) { elements = (uint32_t)strlen(complextype); if (sample_size != GPMF_SizeOfComplexTYPE(complextype, typestringlength)) return GPMF_ERROR_TYPE_NOT_SUPPORTED; } else return GPMF_ERROR_TYPE_NOT_SUPPORTED; } else return GPMF_ERROR_TYPE_NOT_SUPPORTED; } else { typesize = GPMF_SizeofType((GPMF_SampleType)type); if (type == GPMF_TYPE_FOURCC) typesize = 1; // Do not ByteSWAP if (typesize == 0) return GPMF_ERROR_MEMORY; elements = sample_size / typesize; } while (read_samples--) { uint32_t i,j; for (i = 0; i < elements; i++) { if (type == GPMF_TYPE_COMPLEX) { if (complextype[i] == GPMF_TYPE_FOURCC) { *output++ = *data++; *output++ = *data++; *output++ = *data++; *output++ = *data++; typesize = 0; } else typesize = GPMF_SizeofType(complextype[i]); } switch (typesize) { case 2: { uint16_t *data16 = (uint16_t *)data; uint16_t *output16 = (uint16_t *)output; *output16 = BYTESWAP16(*data16); output16++; data16++; data = (uint8_t *)data16; output = (uint8_t *)output16; } break; case 4: { uint32_t *data32 = (uint32_t *)data; uint32_t *output32 = (uint32_t *)output; *output32 = BYTESWAP32(*data32); output32++; data32++; data = (uint8_t *)data32; output = (uint8_t *)output32; } break; case 8: { uint32_t *data32 = (uint32_t *)data; uint32_t *output32 = (uint32_t *)output; *(output32+1) = BYTESWAP32(*data32); *(output32) = BYTESWAP32(*(data32+1)); data32 += 2; output32 += 2; data = (uint8_t *)data32; output = (uint8_t *)output32; } break; default: //1, 16 or more not byteswapped for (j = 0; j < typesize; j++) *output++ = *data++; break; } } } return GPMF_OK; } return GPMF_ERROR_MEMORY; } #define MACRO_CAST_SCALE_UNSIGNED_TYPE(casttype) \ { \ casttype *tmp = (casttype *)output; \ switch (scaletype) \ { \ case GPMF_TYPE_SIGNED_BYTE: *tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((int8_t *)scaledata8); break; \ case GPMF_TYPE_UNSIGNED_BYTE: *tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((uint8_t *)scaledata8); break; \ case GPMF_TYPE_SIGNED_SHORT: *tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((int16_t *)scaledata8); break; \ case GPMF_TYPE_UNSIGNED_SHORT: *tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((uint16_t *)scaledata8); break; \ case GPMF_TYPE_SIGNED_LONG: *tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((int32_t *)scaledata8); break; \ case GPMF_TYPE_UNSIGNED_LONG: *tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((uint32_t *)scaledata8); break; \ case GPMF_TYPE_FLOAT: *tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((float *)scaledata8); break; \ default: break; \ } \ output = (uint8_t *)tmp; \ } #define MACRO_CAST_SCALE_SIGNED_TYPE(casttype) \ { \ casttype *tmp = (casttype *)output; \ switch (scaletype) \ { \ case GPMF_TYPE_SIGNED_BYTE: *tmp++ = (casttype)*val / (casttype)*((int8_t *)scaledata8); break; \ case GPMF_TYPE_UNSIGNED_BYTE: *tmp++ = (casttype)*val / (casttype)*((uint8_t *)scaledata8); break; \ case GPMF_TYPE_SIGNED_SHORT: *tmp++ = (casttype)*val / (casttype)*((int16_t *)scaledata8); break; \ case GPMF_TYPE_UNSIGNED_SHORT: *tmp++ = (casttype)*val / (casttype)*((uint16_t *)scaledata8); break; \ case GPMF_TYPE_SIGNED_LONG: *tmp++ = (casttype)*val / (casttype)*((int32_t *)scaledata8); break; \ case GPMF_TYPE_UNSIGNED_LONG: *tmp++ = (casttype)*val / (casttype)*((uint32_t *)scaledata8); break; \ case GPMF_TYPE_FLOAT: *tmp++ = (casttype)*val / (casttype)*((float *)scaledata8); break; \ default: break; \ } \ output = (uint8_t *)tmp; \ } #define MACRO_CAST_SCALE \ switch (outputType) { \ case GPMF_TYPE_SIGNED_BYTE: MACRO_CAST_SCALE_SIGNED_TYPE(int8_t) break; \ case GPMF_TYPE_UNSIGNED_BYTE: MACRO_CAST_SCALE_UNSIGNED_TYPE(uint8_t) break; \ case GPMF_TYPE_SIGNED_SHORT: MACRO_CAST_SCALE_SIGNED_TYPE(int16_t) break; \ case GPMF_TYPE_UNSIGNED_SHORT: MACRO_CAST_SCALE_UNSIGNED_TYPE(uint16_t) break; \ case GPMF_TYPE_FLOAT: MACRO_CAST_SCALE_SIGNED_TYPE(float) break; \ case GPMF_TYPE_SIGNED_LONG: MACRO_CAST_SCALE_SIGNED_TYPE(int32_t) break; \ case GPMF_TYPE_UNSIGNED_LONG: MACRO_CAST_SCALE_UNSIGNED_TYPE(uint32_t) break; \ case GPMF_TYPE_DOUBLE: MACRO_CAST_SCALE_SIGNED_TYPE(double) break; \ default: break; \ } #define MACRO_BSWAP_CAST_SCALE(swap, inputcast, tempcast) \ { \ inputcast *val; \ tempcast temp, *datatemp = (tempcast *)data; \ temp = swap(*datatemp); \ val = (inputcast *)&temp; \ MACRO_CAST_SCALE \ datatemp++; \ data = (uint8_t *)datatemp; \ } GPMF_ERR GPMF_ScaledData(GPMF_stream *ms, void *buffer, uint32_t buffersize, uint32_t sample_offset, uint32_t read_samples, GPMF_SampleType outputType) { if (ms && buffer) { uint8_t *data = (uint8_t *)&ms->buffer[ms->pos + 2]; uint8_t *output = (uint8_t *)buffer; uint32_t sample_size = GPMF_SAMPLE_SIZE(ms->buffer[ms->pos + 1]); uint32_t output_sample_size = GPMF_SizeofType(outputType); uint32_t remaining_sample_size = GPMF_DATA_PACKEDSIZE(ms->buffer[ms->pos + 1]); uint8_t type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]); char complextype[64] = "L"; uint32_t inputtypesize = 0; uint32_t inputtypeelements = 0; uint8_t scaletype = 0; uint8_t scalecount = 0; uint32_t scaletypesize = 0; uint32_t *scaledata = NULL; uint32_t tmpbuffer[64]; uint32_t tmpbuffersize = sizeof(tmpbuffer); uint32_t elements = 1; type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]); if (type == GPMF_TYPE_NEST) return GPMF_ERROR_MEMORY; if (GPMF_OK != IsValidSize(ms, remaining_sample_size >> 2)) return GPMF_ERROR_BAD_STRUCTURE; remaining_sample_size -= sample_offset * sample_size; // skip samples data += sample_offset * sample_size; if (remaining_sample_size < sample_size * read_samples) return GPMF_ERROR_MEMORY; if (type == GPMF_TYPE_COMPLEX) { GPMF_stream find_stream; GPMF_CopyState(ms, &find_stream); if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TYPE, GPMF_RECURSE_LEVELS)) { char *data1 = (char *)GPMF_RawData(&find_stream); int size = GPMF_RawDataSize(&find_stream); uint32_t typestringlength = sizeof(complextype); if (GPMF_OK == GPMF_ExpandComplexTYPE(data1, size, complextype, &typestringlength)) { inputtypeelements = elements = typestringlength; if (sample_size != GPMF_SizeOfComplexTYPE(complextype, typestringlength)) return GPMF_ERROR_TYPE_NOT_SUPPORTED; } else return GPMF_ERROR_TYPE_NOT_SUPPORTED; } else return GPMF_ERROR_TYPE_NOT_SUPPORTED; } else { complextype[0] = type; inputtypesize = GPMF_SizeofType(type); if (inputtypesize == 0) return GPMF_ERROR_MEMORY; inputtypeelements = 1; elements = sample_size / inputtypesize; } if (output_sample_size * elements * read_samples > buffersize) return GPMF_ERROR_MEMORY; switch (outputType) { case GPMF_TYPE_SIGNED_BYTE: case GPMF_TYPE_UNSIGNED_BYTE: case GPMF_TYPE_SIGNED_SHORT: case GPMF_TYPE_UNSIGNED_SHORT: case GPMF_TYPE_FLOAT: case GPMF_TYPE_SIGNED_LONG: case GPMF_TYPE_UNSIGNED_LONG: case GPMF_TYPE_DOUBLE: // All supported formats. { GPMF_stream fs; GPMF_CopyState(ms, &fs); if (GPMF_OK == GPMF_FindPrev(&fs, GPMF_KEY_SCALE, GPMF_CURRENT_LEVEL)) { scaledata = (uint32_t *)GPMF_RawData(&fs); scaletype = GPMF_SAMPLE_TYPE(fs.buffer[fs.pos + 1]); switch (scaletype) { case GPMF_TYPE_SIGNED_BYTE: case GPMF_TYPE_UNSIGNED_BYTE: case GPMF_TYPE_SIGNED_SHORT: case GPMF_TYPE_UNSIGNED_SHORT: case GPMF_TYPE_SIGNED_LONG: case GPMF_TYPE_UNSIGNED_LONG: case GPMF_TYPE_FLOAT: scalecount = GPMF_SAMPLES(fs.buffer[fs.pos + 1]); scaletypesize = GPMF_SizeofType(scaletype); if (scalecount > 1) if (scalecount != elements) return GPMF_ERROR_SCALE_COUNT; GPMF_FormattedData(&fs, tmpbuffer, tmpbuffersize, 0, scalecount); scaledata = (uint32_t *)tmpbuffer; break; default: return GPMF_ERROR_TYPE_NOT_SUPPORTED; break; } } else { scaletype = 'L'; scalecount = 1; tmpbuffer[0] = 1; // set the scale to 1 is no scale was provided scaledata = (uint32_t *)tmpbuffer; } } while (read_samples--) { uint32_t i; uint8_t *scaledata8 = (uint8_t *)scaledata; for (i = 0; i < elements; i++) { switch (complextype[i % inputtypeelements]) { case GPMF_TYPE_FLOAT: MACRO_BSWAP_CAST_SCALE(BYTESWAP32, float, uint32_t) break; case GPMF_TYPE_SIGNED_BYTE: MACRO_BSWAP_CAST_SCALE(NOSWAP8, int8_t, uint8_t) break; case GPMF_TYPE_UNSIGNED_BYTE: MACRO_BSWAP_CAST_SCALE(NOSWAP8, uint8_t, uint8_t) break; case GPMF_TYPE_SIGNED_SHORT: MACRO_BSWAP_CAST_SCALE(BYTESWAP16, int16_t, uint16_t) break; case GPMF_TYPE_UNSIGNED_SHORT: MACRO_BSWAP_CAST_SCALE(BYTESWAP16, uint16_t, uint16_t) break; case GPMF_TYPE_SIGNED_LONG: MACRO_BSWAP_CAST_SCALE(BYTESWAP32, int32_t, uint32_t) break; case GPMF_TYPE_UNSIGNED_LONG: MACRO_BSWAP_CAST_SCALE(BYTESWAP32, uint32_t, uint32_t) break; case GPMF_TYPE_SIGNED_64BIT_INT: MACRO_BSWAP_CAST_SCALE(BYTESWAP64, uint64_t, uint64_t) break; case GPMF_TYPE_UNSIGNED_64BIT_INT: MACRO_BSWAP_CAST_SCALE(BYTESWAP64, uint64_t, uint64_t) break; default: return GPMF_ERROR_TYPE_NOT_SUPPORTED; break; } if (scalecount > 1) scaledata8 += scaletypesize; } } break; default: return GPMF_ERROR_TYPE_NOT_SUPPORTED; break; } return GPMF_OK; } return GPMF_ERROR_MEMORY; }
null
/*! @file GPMF_parser.c * * @brief GPMF Parser library * * @version 1.2.2 * * (C) Copyright 2017 GoPro Inc (http://gopro.com/). * * Licensed under either: * - Apache License, Version 2.0, http://www.apache.org/licenses/LICENSE-2.0 * - MIT license, http://opensource.org/licenses/MIT * at your option. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdint.h> #include "GPMF_parser.h" #ifdef DBG #if _WINDOWS #define DBG_MSG printf #else #define DBG_MSG(...) #endif #else #define DBG_MSG(...) #endif GPMF_ERR IsValidSize(GPMF_stream *ms, uint32_t size) // size is in longs not bytes. { if (ms) { uint32_t nestsize = (uint32_t)ms->nest_size[ms->nest_level]; if (nestsize == 0 && ms->nest_level == 0) nestsize = ms->buffer_size_longs; if (size + 2 <= nestsize) return GPMF_OK; } return GPMF_ERROR_BAD_STRUCTURE; } GPMF_ERR GPMF_Validate(GPMF_stream *ms, GPMF_LEVELS recurse) { if (ms) { uint32_t currpos = ms->pos; int32_t nestsize = (int32_t)ms->nest_size[ms->nest_level]; if (nestsize == 0 && ms->nest_level == 0) nestsize = ms->buffer_size_longs; while (ms->pos+1 < ms->buffer_size_longs && nestsize > 0) { uint32_t key = ms->buffer[ms->pos]; if (ms->nest_level == 0 && key != GPMF_KEY_DEVICE && ms->device_count == 0 && ms->pos == 0) { DBG_MSG("ERROR: uninitized -- GPMF_ERROR_BAD_STRUCTURE\n"); return GPMF_ERROR_BAD_STRUCTURE; } if (GPMF_VALID_FOURCC(key)) { uint32_t type_size_repeat = ms->buffer[ms->pos + 1]; int32_t size = GPMF_DATA_SIZE(type_size_repeat) >> 2; uint8_t type = GPMF_SAMPLE_TYPE(type_size_repeat); if (size + 2 > nestsize) { DBG_MSG("ERROR: nest size too small within %c%c%c%c-- GPMF_ERROR_BAD_STRUCTURE\n", PRINTF_4CC(key)); return GPMF_ERROR_BAD_STRUCTURE; } if (!GPMF_VALID_FOURCC(key)) { DBG_MSG("ERROR: invalid 4CC -- GPMF_ERROR_BAD_STRUCTURE\n"); return GPMF_ERROR_BAD_STRUCTURE; } if (type == GPMF_TYPE_NEST && recurse == GPMF_RECURSE_LEVELS) { uint32_t validnest; ms->pos += 2; ms->nest_level++; if (ms->nest_level > GPMF_NEST_LIMIT) { DBG_MSG("ERROR: nest level within %c%c%c%c too deep -- GPMF_ERROR_BAD_STRUCTURE\n", PRINTF_4CC(key)); return GPMF_ERROR_BAD_STRUCTURE; } ms->nest_size[ms->nest_level] = size; validnest = GPMF_Validate(ms, recurse); ms->nest_level--; if (GPMF_OK != validnest) { DBG_MSG("ERROR: invalid nest within %c%c%c%c -- GPMF_ERROR_BAD_STRUCTURE\n", PRINTF_4CC(key)); return GPMF_ERROR_BAD_STRUCTURE; } else { if (ms->nest_level == 0) ms->device_count++; } ms->pos += size; nestsize -= 2 + size; while (ms->pos < ms->buffer_size_longs && nestsize > 0 && ms->buffer[ms->pos] == GPMF_KEY_END) { ms->pos++; nestsize--; } } else { ms->pos += 2 + size; nestsize -= 2 + size; } if (ms->pos == ms->buffer_size_longs) { ms->pos = currpos; return GPMF_OK; } } else { if (key == GPMF_KEY_END) { do { ms->pos++; nestsize--; } while (ms->pos < ms->buffer_size_longs && nestsize > 0 && ms->buffer[ms->pos] == 0); } else if (ms->nest_level == 0 && ms->device_count > 0) { ms->pos = currpos; return GPMF_OK; } else { DBG_MSG("ERROR: bad struct within %c%c%c%c -- GPMF_ERROR_BAD_STRUCTURE\n", PRINTF_4CC(key)); return GPMF_ERROR_BAD_STRUCTURE; } } } ms->pos = currpos; return GPMF_OK; } else { DBG_MSG("ERROR: Invalid handle -- GPMF_ERROR_MEMORY\n"); return GPMF_ERROR_MEMORY; } } GPMF_ERR GPMF_ResetState(GPMF_stream *ms) { if (ms) { ms->pos = 0; ms->nest_level = 0; ms->device_count = 0; ms->nest_size[ms->nest_level] = 0; ms->last_level_pos[ms->nest_level] = 0; ms->last_seek[ms->nest_level] = 0; ms->device_id = 0; ms->device_name[0] = 0; return GPMF_OK; } return GPMF_ERROR_MEMORY; } GPMF_ERR GPMF_Init(GPMF_stream *ms, uint32_t *buffer, int datasize) { if(ms) { ms->buffer = buffer; ms->buffer_size_longs = datasize >>2; GPMF_ResetState(ms); return GPMF_OK; } return GPMF_ERROR_MEMORY; } GPMF_ERR GPMF_CopyState(GPMF_stream *msrc, GPMF_stream *mdst) { if (msrc && mdst) { memcpy(mdst, msrc, sizeof(GPMF_stream)); return GPMF_OK; } return GPMF_ERROR_MEMORY; } GPMF_ERR GPMF_Next(GPMF_stream *ms, GPMF_LEVELS recurse) { if (ms) { if (ms->pos+1 < ms->buffer_size_longs) { uint32_t key, type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]); uint32_t size = (GPMF_DATA_SIZE(ms->buffer[ms->pos + 1]) >> 2); if (GPMF_OK != IsValidSize(ms, size)) return GPMF_ERROR_BAD_STRUCTURE; if (GPMF_TYPE_NEST == type && GPMF_KEY_DEVICE == ms->buffer[ms->pos] && ms->nest_level == 0) { ms->last_level_pos[ms->nest_level] = ms->pos; ms->nest_size[ms->nest_level] = size; if (recurse) ms->pos += 2; else ms->pos += 2 + size; } else { if (size + 2 > ms->nest_size[ms->nest_level]) return GPMF_ERROR_BAD_STRUCTURE; if (recurse && type == GPMF_TYPE_NEST) { ms->last_level_pos[ms->nest_level] = ms->pos; ms->pos += 2; ms->nest_size[ms->nest_level] -= size + 2; ms->nest_level++; if (ms->nest_level > GPMF_NEST_LIMIT) return GPMF_ERROR_BAD_STRUCTURE; ms->nest_size[ms->nest_level] = size; } else { if (recurse) { ms->pos += size + 2; ms->nest_size[ms->nest_level] -= size + 2; } else { if (ms->nest_size[ms->nest_level] - (size + 2) > 0) { ms->pos += size + 2; ms->nest_size[ms->nest_level] -= size + 2; } else { return GPMF_ERROR_LAST; } } } } while (ms->pos < ms->buffer_size_longs && ms->nest_size[ms->nest_level] > 0 && ms->buffer[ms->pos] == GPMF_KEY_END) { ms->pos++; ms->nest_size[ms->nest_level]--; } while (ms->nest_level > 0 && ms->nest_size[ms->nest_level] == 0) { ms->nest_level--; //if (ms->nest_level == 0) //{ // ms->device_count++; //} } if (ms->pos < ms->buffer_size_longs) { while (ms->pos < ms->buffer_size_longs && ms->nest_size[ms->nest_level] > 0 && ms->buffer[ms->pos] == GPMF_KEY_END) { ms->pos++; ms->nest_size[ms->nest_level]--; } key = ms->buffer[ms->pos]; if (!GPMF_VALID_FOURCC(key)) return GPMF_ERROR_BAD_STRUCTURE; if (key == GPMF_KEY_DEVICE_ID) ms->device_id = BYTESWAP32(ms->buffer[ms->pos + 2]); if (key == GPMF_KEY_DEVICE_NAME) { size = GPMF_DATA_SIZE(ms->buffer[ms->pos + 1]); // in bytes if (size > sizeof(ms->device_name) - 1) size = sizeof(ms->device_name) - 1; memcpy(ms->device_name, &ms->buffer[ms->pos + 2], size); ms->device_name[size] = 0; } } else { // end of buffer return GPMF_ERROR_BUFFER_END; } return GPMF_OK; } else { // end of buffer return GPMF_ERROR_BUFFER_END; } } return GPMF_ERROR_MEMORY; } GPMF_ERR GPMF_FindNext(GPMF_stream *ms, uint32_t fourcc, GPMF_LEVELS recurse) { GPMF_stream prevstate; if (ms) { memcpy(&prevstate, ms, sizeof(GPMF_stream)); if (ms->pos < ms->buffer_size_longs) { while (0 == GPMF_Next(ms, recurse)) { if (ms->buffer[ms->pos] == fourcc) { return GPMF_OK; //found match } } // restore read position memcpy(ms, &prevstate, sizeof(GPMF_stream)); return GPMF_ERROR_FIND; } } return GPMF_ERROR_FIND; } GPMF_ERR GPMF_Reserved(uint32_t key) { if(key == GPMF_KEY_DEVICE) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_DEVICE_ID) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_DEVICE_NAME) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_STREAM) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_STREAM_NAME) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_SI_UNITS) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_UNITS) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_SCALE) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_TYPE) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_TOTAL_SAMPLES) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_TICK) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_TOCK) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_EMPTY_PAYLOADS) return GPMF_ERROR_RESERVED; if(key == GPMF_KEY_REMARK) return GPMF_ERROR_RESERVED; return GPMF_OK; } uint32_t GPMF_PayloadSampleCount(GPMF_stream *ms) { uint32_t count = 0; if (ms) { uint32_t fourcc = GPMF_Key(ms); GPMF_stream find_stream; GPMF_CopyState(ms, &find_stream); if (GPMF_OK == GPMF_FindNext(&find_stream, fourcc, GPMF_CURRENT_LEVEL)) // Count the instances, not the repeats { count=2; while (GPMF_OK == GPMF_FindNext(&find_stream, fourcc, GPMF_CURRENT_LEVEL)) { count++; } } else { count = GPMF_Repeat(ms); } } return count; } GPMF_ERR GPMF_SeekToSamples(GPMF_stream *ms) { GPMF_stream prevstate; if (ms) { if (ms->pos+1 < ms->buffer_size_longs) { uint32_t type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]); memcpy(&prevstate, ms, sizeof(GPMF_stream)); if (type == GPMF_TYPE_NEST) GPMF_Next(ms, GPMF_RECURSE_LEVELS); // open STRM and recurse in while (0 == GPMF_Next(ms, GPMF_CURRENT_LEVEL)) { uint32_t size = (GPMF_DATA_SIZE(ms->buffer[ms->pos + 1]) >> 2); if (GPMF_OK != IsValidSize(ms, size)) { memcpy(ms, &prevstate, sizeof(GPMF_stream)); return GPMF_ERROR_BAD_STRUCTURE; } type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]); if (type == GPMF_TYPE_NEST) // Nest with-in nest { return GPMF_OK; //found match } if (size + 2 == ms->nest_size[ms->nest_level]) { uint32_t key = GPMF_Key(ms); if (GPMF_ERROR_RESERVED == GPMF_Reserved(key)) return GPMF_ERROR_FIND; return GPMF_OK; //found match } if (ms->buffer[ms->pos] == ms->buffer[ms->pos + size + 2]) // Matching tags { return GPMF_OK; //found match } } // restore read position memcpy(ms, &prevstate, sizeof(GPMF_stream)); return GPMF_ERROR_FIND; } } return GPMF_ERROR_FIND; } GPMF_ERR GPMF_FindPrev(GPMF_stream *ms, uint32_t fourcc, GPMF_LEVELS recurse) { GPMF_stream prevstate; if (ms) { uint32_t curr_level = ms->nest_level; memcpy(&prevstate, ms, sizeof(GPMF_stream)); if (ms->pos < ms->buffer_size_longs && curr_level > 0) { do { ms->last_seek[curr_level] = ms->pos; ms->pos = ms->last_level_pos[curr_level - 1] + 2; ms->nest_size[curr_level] += ms->last_seek[curr_level] - ms->pos; do { if (ms->last_seek[curr_level] > ms->pos && ms->buffer[ms->pos] == fourcc) { return GPMF_OK; //found match } } while (ms->last_seek[curr_level] > ms->pos && 0 == GPMF_Next(ms, GPMF_CURRENT_LEVEL)); curr_level--; } while (recurse == GPMF_RECURSE_LEVELS && curr_level > 0); // restore read position memcpy(ms, &prevstate, sizeof(GPMF_stream)); return GPMF_ERROR_FIND; } } return GPMF_ERROR_FIND; } uint32_t GPMF_Key(GPMF_stream *ms) { if (ms) { uint32_t key = ms->buffer[ms->pos]; return key; } return 0; } uint32_t GPMF_Type(GPMF_stream *ms) { if (ms && ms->pos+1 < ms->buffer_size_longs) { uint32_t type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos+1]); return type; } return 0; } uint32_t GPMF_StructSize(GPMF_stream *ms) { if (ms && ms->pos+1 < ms->buffer_size_longs) { uint32_t ssize = GPMF_SAMPLE_SIZE(ms->buffer[ms->pos + 1]); uint32_t size = (GPMF_DATA_SIZE(ms->buffer[ms->pos + 1]) >> 2); if (GPMF_OK != IsValidSize(ms, size)) return 0; // as the structure is corrupted. i.e. GPMF_ERROR_BAD_STRUCTURE; return ssize; } return 0; } uint32_t GPMF_ElementsInStruct(GPMF_stream *ms) { if (ms && ms->pos+1 < ms->buffer_size_longs) { uint32_t ssize = GPMF_StructSize(ms); GPMF_SampleType type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]); if (type != GPMF_TYPE_NEST && type != GPMF_TYPE_COMPLEX) { int32_t tsize = GPMF_SizeofType(type); if (tsize > 0) return ssize / tsize; else return 0; } if (type == GPMF_TYPE_COMPLEX) { GPMF_stream find_stream; GPMF_CopyState(ms, &find_stream); if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TYPE, GPMF_CURRENT_LEVEL)) { char tmp[64] = ""; uint32_t tmpsize = sizeof(tmp); char *data = (char *)GPMF_RawData(&find_stream); int size = GPMF_RawDataSize(&find_stream); if (GPMF_OK == GPMF_ExpandComplexTYPE(data, size, tmp, &tmpsize)) return tmpsize; } } } return 0; } uint32_t GPMF_Repeat(GPMF_stream *ms) { if (ms && ms->pos+1 < ms->buffer_size_longs) { uint32_t repeat = GPMF_SAMPLES(ms->buffer[ms->pos + 1]); return repeat; } return 0; } uint32_t GPMF_RawDataSize(GPMF_stream *ms) { if (ms && ms->pos+1 < ms->buffer_size_longs) { uint32_t size = GPMF_DATA_PACKEDSIZE(ms->buffer[ms->pos + 1]); if (GPMF_OK != IsValidSize(ms, size >> 2)) return 0; return size; } return 0; } uint32_t GPMF_NestLevel(GPMF_stream *ms) { if (ms) { return ms->nest_level; } return 0; } uint32_t GPMF_DeviceID(GPMF_stream *ms) { if (ms) { return ms->device_id; } return 0; } GPMF_ERR GPMF_DeviceName(GPMF_stream *ms, char *devicenamebuf, uint32_t devicename_buf_size) { if (ms && devicenamebuf) { uint32_t len = (uint32_t)strlen(ms->device_name); if (len >= devicename_buf_size) return GPMF_ERROR_MEMORY; memcpy(devicenamebuf, ms->device_name, len); devicenamebuf[len] = 0; return GPMF_OK; } return GPMF_ERROR_MEMORY; } void *GPMF_RawData(GPMF_stream *ms) { if (ms) { return (void *)&ms->buffer[ms->pos + 2]; } return NULL; } uint32_t GPMF_SizeofType(GPMF_SampleType type) { uint32_t ssize = 0; switch ((int)type) { case GPMF_TYPE_STRING_ASCII: ssize = 1; break; case GPMF_TYPE_SIGNED_BYTE: ssize = 1; break; case GPMF_TYPE_UNSIGNED_BYTE: ssize = 1; break; // These datatypes are always be stored in Big-Endian case GPMF_TYPE_SIGNED_SHORT: ssize = 2; break; case GPMF_TYPE_UNSIGNED_SHORT: ssize = 2; break; case GPMF_TYPE_FLOAT: ssize = 4; break; case GPMF_TYPE_FOURCC: ssize = 4; break; case GPMF_TYPE_SIGNED_LONG: ssize = 4; break; case GPMF_TYPE_UNSIGNED_LONG: ssize = 4; break; case GPMF_TYPE_Q15_16_FIXED_POINT: ssize = 4; break; case GPMF_TYPE_Q31_32_FIXED_POINT: ssize = 8; break; case GPMF_TYPE_DOUBLE: ssize = 8; break; case GPMF_TYPE_SIGNED_64BIT_INT: ssize = 8; break; case GPMF_TYPE_UNSIGNED_64BIT_INT: ssize = 8; break; //All unknown or larger than 8-bytes stored as is: case GPMF_TYPE_GUID: ssize = 16; break; case GPMF_TYPE_UTC_DATE_TIME: ssize = 16; break; } return ssize; } uint32_t GPMF_ExpandComplexTYPE(char *src, uint32_t srcsize, char *dst, uint32_t *dstsize) { uint32_t i = 0, k = 0, count = 0; while (i<srcsize && k<*dstsize) { if (src[i] == '[' && i>0) { int j = 1; count = 0; while (src[i + j] >= '0' && src[i + j] <= '9') { count *= 10; count += src[i + j] - '0'; j++; } if (count > 1) { uint32_t l; for (l = 1; l<count; l++) { dst[k] = src[i - 1]; k++; } } i += j; if (src[i] == ']') i++; } else { dst[k] = src[i]; if (dst[k] == 0) break; i++, k++; } } if (k >= *dstsize) return GPMF_ERROR_MEMORY; // bad structure formed dst[k] = 0; *dstsize = k; return GPMF_OK; } uint32_t GPMF_SizeOfComplexTYPE(char *type, uint32_t typestringlength) { char *typearray = type; uint32_t size = 0, expand = 0; uint32_t i, len = typestringlength; for (i = 0; i < len; i++) if (typearray[i] == '[') expand = 1; if (expand) { char exptypearray[64]; uint32_t dstsize = sizeof(exptypearray); if (GPMF_OK == GPMF_ExpandComplexTYPE(typearray, len, exptypearray, &dstsize)) { typearray = exptypearray; len = dstsize; } else return 0; } for (i = 0; i < len; i++) { uint32_t typesize = GPMF_SizeofType((GPMF_SampleType)typearray[i]); if (typesize < 1) return 0; size += typesize; } return size; } GPMF_ERR GPMF_FormattedData(GPMF_stream *ms, void *buffer, uint32_t buffersize, uint32_t sample_offset, uint32_t read_samples) { if (ms && buffer) { uint8_t *data = (uint8_t *)&ms->buffer[ms->pos + 2]; uint8_t *output = (uint8_t *)buffer; uint32_t sample_size = GPMF_SAMPLE_SIZE(ms->buffer[ms->pos + 1]); uint32_t remaining_sample_size = GPMF_DATA_PACKEDSIZE(ms->buffer[ms->pos + 1]); uint8_t type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]); uint32_t typesize = 1; uint32_t elements = 0; uint32_t typestringlength = 1; char complextype[64] = "L"; if (type == GPMF_TYPE_NEST) return GPMF_ERROR_BAD_STRUCTURE; if (GPMF_OK != IsValidSize(ms, remaining_sample_size>>2)) return GPMF_ERROR_BAD_STRUCTURE; if (sample_size * read_samples > buffersize) return GPMF_ERROR_MEMORY; remaining_sample_size -= sample_offset * sample_size; // skip samples data += sample_offset * sample_size; if (remaining_sample_size < sample_size * read_samples) return GPMF_ERROR_MEMORY; if (type == GPMF_TYPE_COMPLEX) { GPMF_stream find_stream; GPMF_CopyState(ms, &find_stream); if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TYPE, GPMF_RECURSE_LEVELS)) { char *data1 = (char *)GPMF_RawData(&find_stream); int size = GPMF_RawDataSize(&find_stream); typestringlength = sizeof(complextype); if (GPMF_OK == GPMF_ExpandComplexTYPE(data1, size, complextype, &typestringlength)) { elements = (uint32_t)strlen(complextype); if (sample_size != GPMF_SizeOfComplexTYPE(complextype, typestringlength)) return GPMF_ERROR_TYPE_NOT_SUPPORTED; } else return GPMF_ERROR_TYPE_NOT_SUPPORTED; } else return GPMF_ERROR_TYPE_NOT_SUPPORTED; } else { typesize = GPMF_SizeofType((GPMF_SampleType)type); if (type == GPMF_TYPE_FOURCC) typesize = 1; // Do not ByteSWAP if (typesize == 0) return GPMF_ERROR_MEMORY; elements = sample_size / typesize; } while (read_samples--) { uint32_t i,j; for (i = 0; i < elements; i++) { if (type == GPMF_TYPE_COMPLEX) { if (complextype[i] == GPMF_TYPE_FOURCC) { *output++ = *data++; *output++ = *data++; *output++ = *data++; *output++ = *data++; typesize = 0; } else typesize = GPMF_SizeofType(complextype[i]); } switch (typesize) { case 2: { uint16_t *data16 = (uint16_t *)data; uint16_t *output16 = (uint16_t *)output; *output16 = BYTESWAP16(*data16); output16++; data16++; data = (uint8_t *)data16; output = (uint8_t *)output16; } break; case 4: { uint32_t *data32 = (uint32_t *)data; uint32_t *output32 = (uint32_t *)output; *output32 = BYTESWAP32(*data32); output32++; data32++; data = (uint8_t *)data32; output = (uint8_t *)output32; } break; case 8: { uint32_t *data32 = (uint32_t *)data; uint32_t *output32 = (uint32_t *)output; *(output32+1) = BYTESWAP32(*data32); *(output32) = BYTESWAP32(*(data32+1)); data32 += 2; output32 += 2; data = (uint8_t *)data32; output = (uint8_t *)output32; } break; default: //1, 16 or more not byteswapped for (j = 0; j < typesize; j++) *output++ = *data++; break; } } } return GPMF_OK; } return GPMF_ERROR_MEMORY; } #define MACRO_CAST_SCALE_UNSIGNED_TYPE(casttype) \ { \ casttype *tmp = (casttype *)output; \ switch (scaletype) \ { \ case GPMF_TYPE_SIGNED_BYTE: *tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((int8_t *)scaledata8); break; \ case GPMF_TYPE_UNSIGNED_BYTE: *tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((uint8_t *)scaledata8); break; \ case GPMF_TYPE_SIGNED_SHORT: *tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((int16_t *)scaledata8); break; \ case GPMF_TYPE_UNSIGNED_SHORT: *tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((uint16_t *)scaledata8); break; \ case GPMF_TYPE_SIGNED_LONG: *tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((int32_t *)scaledata8); break; \ case GPMF_TYPE_UNSIGNED_LONG: *tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((uint32_t *)scaledata8); break; \ case GPMF_TYPE_FLOAT: *tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((float *)scaledata8); break; \ default: break; \ } \ output = (uint8_t *)tmp; \ } #define MACRO_CAST_SCALE_SIGNED_TYPE(casttype) \ { \ casttype *tmp = (casttype *)output; \ switch (scaletype) \ { \ case GPMF_TYPE_SIGNED_BYTE: *tmp++ = (casttype)*val / (casttype)*((int8_t *)scaledata8); break; \ case GPMF_TYPE_UNSIGNED_BYTE: *tmp++ = (casttype)*val / (casttype)*((uint8_t *)scaledata8); break; \ case GPMF_TYPE_SIGNED_SHORT: *tmp++ = (casttype)*val / (casttype)*((int16_t *)scaledata8); break; \ case GPMF_TYPE_UNSIGNED_SHORT: *tmp++ = (casttype)*val / (casttype)*((uint16_t *)scaledata8); break; \ case GPMF_TYPE_SIGNED_LONG: *tmp++ = (casttype)*val / (casttype)*((int32_t *)scaledata8); break; \ case GPMF_TYPE_UNSIGNED_LONG: *tmp++ = (casttype)*val / (casttype)*((uint32_t *)scaledata8); break; \ case GPMF_TYPE_FLOAT: *tmp++ = (casttype)*val / (casttype)*((float *)scaledata8); break; \ default: break; \ } \ output = (uint8_t *)tmp; \ } #define MACRO_CAST_SCALE \ switch (outputType) { \ case GPMF_TYPE_SIGNED_BYTE: MACRO_CAST_SCALE_SIGNED_TYPE(int8_t) break; \ case GPMF_TYPE_UNSIGNED_BYTE: MACRO_CAST_SCALE_UNSIGNED_TYPE(uint8_t) break; \ case GPMF_TYPE_SIGNED_SHORT: MACRO_CAST_SCALE_SIGNED_TYPE(int16_t) break; \ case GPMF_TYPE_UNSIGNED_SHORT: MACRO_CAST_SCALE_UNSIGNED_TYPE(uint16_t) break; \ case GPMF_TYPE_FLOAT: MACRO_CAST_SCALE_SIGNED_TYPE(float) break; \ case GPMF_TYPE_SIGNED_LONG: MACRO_CAST_SCALE_SIGNED_TYPE(int32_t) break; \ case GPMF_TYPE_UNSIGNED_LONG: MACRO_CAST_SCALE_UNSIGNED_TYPE(uint32_t) break; \ case GPMF_TYPE_DOUBLE: MACRO_CAST_SCALE_SIGNED_TYPE(double) break; \ default: break; \ } #define MACRO_BSWAP_CAST_SCALE(swap, inputcast, tempcast) \ { \ inputcast *val; \ tempcast temp, *datatemp = (tempcast *)data; \ temp = swap(*datatemp); \ val = (inputcast *)&temp; \ MACRO_CAST_SCALE \ datatemp++; \ data = (uint8_t *)datatemp; \ } GPMF_ERR GPMF_ScaledData(GPMF_stream *ms, void *buffer, uint32_t buffersize, uint32_t sample_offset, uint32_t read_samples, GPMF_SampleType outputType) { if (ms && buffer) { uint8_t *data = (uint8_t *)&ms->buffer[ms->pos + 2]; uint8_t *output = (uint8_t *)buffer; uint32_t sample_size = GPMF_SAMPLE_SIZE(ms->buffer[ms->pos + 1]); uint32_t output_sample_size = GPMF_SizeofType(outputType); uint32_t remaining_sample_size = GPMF_DATA_PACKEDSIZE(ms->buffer[ms->pos + 1]); uint8_t type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]); char complextype[64] = "L"; uint32_t inputtypesize = 0; uint32_t inputtypeelements = 0; uint8_t scaletype = 0; uint8_t scalecount = 0; uint32_t scaletypesize = 0; uint32_t *scaledata = NULL; uint32_t tmpbuffer[64]; uint32_t tmpbuffersize = sizeof(tmpbuffer); uint32_t elements = 1; type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]); if (type == GPMF_TYPE_NEST) return GPMF_ERROR_MEMORY; if (GPMF_OK != IsValidSize(ms, remaining_sample_size >> 2)) return GPMF_ERROR_BAD_STRUCTURE; remaining_sample_size -= sample_offset * sample_size; // skip samples data += sample_offset * sample_size; if (remaining_sample_size < sample_size * read_samples) return GPMF_ERROR_MEMORY; if (type == GPMF_TYPE_COMPLEX) { GPMF_stream find_stream; GPMF_CopyState(ms, &find_stream); if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TYPE, GPMF_RECURSE_LEVELS)) { char *data1 = (char *)GPMF_RawData(&find_stream); int size = GPMF_RawDataSize(&find_stream); uint32_t typestringlength = sizeof(complextype); if (GPMF_OK == GPMF_ExpandComplexTYPE(data1, size, complextype, &typestringlength)) { inputtypeelements = elements = typestringlength; if (sample_size != GPMF_SizeOfComplexTYPE(complextype, typestringlength)) return GPMF_ERROR_TYPE_NOT_SUPPORTED; } else return GPMF_ERROR_TYPE_NOT_SUPPORTED; } else return GPMF_ERROR_TYPE_NOT_SUPPORTED; } else { complextype[0] = type; inputtypesize = GPMF_SizeofType(type); if (inputtypesize == 0) return GPMF_ERROR_MEMORY; inputtypeelements = 1; elements = sample_size / inputtypesize; } if (output_sample_size * elements * read_samples > buffersize) return GPMF_ERROR_MEMORY; switch (outputType) { case GPMF_TYPE_SIGNED_BYTE: case GPMF_TYPE_UNSIGNED_BYTE: case GPMF_TYPE_SIGNED_SHORT: case GPMF_TYPE_UNSIGNED_SHORT: case GPMF_TYPE_FLOAT: case GPMF_TYPE_SIGNED_LONG: case GPMF_TYPE_UNSIGNED_LONG: case GPMF_TYPE_DOUBLE: // All supported formats. { GPMF_stream fs; GPMF_CopyState(ms, &fs); if (GPMF_OK == GPMF_FindPrev(&fs, GPMF_KEY_SCALE, GPMF_CURRENT_LEVEL)) { scaledata = (uint32_t *)GPMF_RawData(&fs); scaletype = GPMF_SAMPLE_TYPE(fs.buffer[fs.pos + 1]); switch (scaletype) { case GPMF_TYPE_SIGNED_BYTE: case GPMF_TYPE_UNSIGNED_BYTE: case GPMF_TYPE_SIGNED_SHORT: case GPMF_TYPE_UNSIGNED_SHORT: case GPMF_TYPE_SIGNED_LONG: case GPMF_TYPE_UNSIGNED_LONG: case GPMF_TYPE_FLOAT: scalecount = GPMF_SAMPLES(fs.buffer[fs.pos + 1]); scaletypesize = GPMF_SizeofType(scaletype); if (scalecount > 1) if (scalecount != elements) return GPMF_ERROR_SCALE_COUNT; GPMF_FormattedData(&fs, tmpbuffer, tmpbuffersize, 0, scalecount); scaledata = (uint32_t *)tmpbuffer; break; default: return GPMF_ERROR_TYPE_NOT_SUPPORTED; break; } } else { scaletype = 'L'; scalecount = 1; tmpbuffer[0] = 1; // set the scale to 1 is no scale was provided scaledata = (uint32_t *)tmpbuffer; } } while (read_samples--) { uint32_t i; uint8_t *scaledata8 = (uint8_t *)scaledata; for (i = 0; i < elements; i++) { switch (complextype[i % inputtypeelements]) { case GPMF_TYPE_FLOAT: MACRO_BSWAP_CAST_SCALE(BYTESWAP32, float, uint32_t) break; case GPMF_TYPE_SIGNED_BYTE: MACRO_BSWAP_CAST_SCALE(NOSWAP8, int8_t, uint8_t) break; case GPMF_TYPE_UNSIGNED_BYTE: MACRO_BSWAP_CAST_SCALE(NOSWAP8, uint8_t, uint8_t) break; case GPMF_TYPE_SIGNED_SHORT: MACRO_BSWAP_CAST_SCALE(BYTESWAP16, int16_t, uint16_t) break; case GPMF_TYPE_UNSIGNED_SHORT: MACRO_BSWAP_CAST_SCALE(BYTESWAP16, uint16_t, uint16_t) break; case GPMF_TYPE_SIGNED_LONG: MACRO_BSWAP_CAST_SCALE(BYTESWAP32, int32_t, uint32_t) break; case GPMF_TYPE_UNSIGNED_LONG: MACRO_BSWAP_CAST_SCALE(BYTESWAP32, uint32_t, uint32_t) break; case GPMF_TYPE_SIGNED_64BIT_INT: MACRO_BSWAP_CAST_SCALE(BYTESWAP64, uint64_t, uint64_t) break; case GPMF_TYPE_UNSIGNED_64BIT_INT: MACRO_BSWAP_CAST_SCALE(BYTESWAP64, uint64_t, uint64_t) break; default: return GPMF_ERROR_TYPE_NOT_SUPPORTED; break; } if (scalecount > 1) scaledata8 += scaletypesize; } } break; default: return GPMF_ERROR_TYPE_NOT_SUPPORTED; break; } return GPMF_OK; } return GPMF_ERROR_MEMORY; }
null
137
CWE-787
CVE-2019-15683
/* * auth.c - deal with authentication. * * This file implements authentication when setting up an RFB connection. */ /* * Copyright (C) 2010, 2012-2019 D. R. Commander. All Rights Reserved. * Copyright (C) 2010 University Corporation for Atmospheric Research. * All Rights Reserved. * Copyright (C) 2003-2006 Constantin Kaplinsky. All Rights Reserved. * Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. */ #ifndef _POSIX_PTHREAD_SEMANTICS #define _POSIX_PTHREAD_SEMANTICS #endif #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <errno.h> #include "rfb.h" #include "windowstr.h" char *rfbAuthPasswdFile = NULL; static void rfbSendSecurityType(rfbClientPtr cl, int securityType); static void rfbSendSecurityTypeList(rfbClientPtr cl); static void rfbSendTunnelingCaps(rfbClientPtr cl); static void rfbSendAuthCaps(rfbClientPtr cl); static void rfbVncAuthSendChallenge(rfbClientPtr cl); static void rfbVeNCryptAuthenticate(rfbClientPtr cl); #define AUTH_DEFAULT_CONF_FILE \ CMAKE_INSTALL_FULL_SYSCONFDIR "/turbovncserver-security.conf" #ifdef XVNC_AuthPAM #define AUTH_DEFAULT_PAM_SERVICE_NAME "turbovnc" #endif #define MAX_USER_LEN 64 #define MAX_PWD_LEN 64 char *rfbAuthConfigFile = AUTH_DEFAULT_CONF_FILE; Bool rfbAuthDisableRemoteResize = FALSE; Bool rfbAuthDisableRevCon = FALSE; Bool rfbAuthDisableCBSend = FALSE; Bool rfbAuthDisableCBRecv = FALSE; Bool rfbAuthDisableHTTP = FALSE; Bool rfbAuthDisableX11TCP = FALSE; static int nSecTypesEnabled = 0; static int preferenceLimit = 1; /* Force one iteration of the loop in rfbSendAuthCaps() */ char *rfbAuthOTPValue = NULL; int rfbAuthOTPValueLen = 0; #if USETLS char *rfbAuthX509Cert = NULL; char *rfbAuthX509Key = NULL; char *rfbAuthCipherSuites = NULL; #endif static void AuthNoneStartFunc(rfbClientPtr cl) { rfbClientAuthSucceeded(cl, rfbAuthNone); } static void AuthNoneRspFunc(rfbClientPtr cl) { } #ifdef XVNC_AuthPAM #include <pwd.h> static char *pamServiceName = AUTH_DEFAULT_PAM_SERVICE_NAME; typedef struct UserList { struct UserList *next; const char *name; Bool viewOnly; } UserList; static UserList *userACL = NULL; Bool rfbAuthUserACL = FALSE; void rfbAuthAddUser(const char *name, Bool viewOnly) { UserList *p = (UserList *)rfbAlloc(sizeof(UserList)); rfbLog("Adding user '%s' to ACL with %s privileges\n", name, viewOnly ? " view-only" : "full control"); p->next = userACL; p->name = name; p->viewOnly = viewOnly; userACL = p; } void rfbAuthRevokeUser(const char *name) { UserList **prev = &userACL; UserList *p; rfbLog("Removing user '%s' from ACL\n", name); while (*prev != NULL) { p = *prev; if (!strcmp(p->name, name)) { *prev = p->next; free((void *)p->name); free(p); return; } prev = &p->next; } } static void AuthPAMUserPwdStartFunc(rfbClientPtr cl) { cl->state = RFB_AUTHENTICATION; } static void AuthPAMUserPwdRspFunc(rfbClientPtr cl) { CARD32 userLen; CARD32 pwdLen; char userBuf[MAX_USER_LEN + 1]; char pwdBuf[MAX_PWD_LEN + 1]; int n; const char *emsg; n = ReadExact(cl, (char *)&userLen, sizeof(userLen)); if (n <= 0) { if (n != 0) rfbLogPerror("AuthPAMUserPwdRspFunc: read error"); rfbCloseClient(cl); return; } userLen = Swap32IfLE(userLen); n = ReadExact(cl, (char *)&pwdLen, sizeof(pwdLen)); if (n <= 0) { if (n != 0) rfbLogPerror("AuthPAMUserPwdRspFunc: read error"); rfbCloseClient(cl); return; } pwdLen = Swap32IfLE(pwdLen); if ((userLen > MAX_USER_LEN) || (pwdLen > MAX_PWD_LEN)) { rfbLogPerror("AuthPAMUserPwdRspFunc: excessively large user name or password in response"); rfbCloseClient(cl); return; } n = ReadExact(cl, userBuf, userLen); if (n <= 0) { if (n != 0) rfbLogPerror("AuthPAMUserPwdRspFunc: error reading user name"); rfbCloseClient(cl); return; } userBuf[userLen] = '\0'; n = ReadExact(cl, pwdBuf, pwdLen); if (n <= 0) { if (n != 0) rfbLogPerror("AuthPAMUserPwdRspFunc: error reading password"); rfbCloseClient(cl); return; } pwdBuf[pwdLen] = '\0'; if (rfbAuthUserACL) { UserList *p = userACL; if (p == NULL) rfbLog("WARNING: User ACL is empty. No users will be allowed to log in with Unix Login authentication.\n"); while (p != NULL) { if (!strcmp(p->name, userBuf)) break; p = p->next; } if (p == NULL) { rfbLog("User '%s' is not in the ACL and has been denied access\n", userBuf); rfbClientAuthFailed(cl, "User denied access"); return; } cl->viewOnly = p->viewOnly; } else { struct passwd pbuf; struct passwd *pw; char buf[256]; if (getpwuid_r(getuid(), &pbuf, buf, sizeof(buf), &pw) != 0) FatalError("AuthPAMUserPwdRspFunc: getpwuid_r failed: %s", strerror(errno)); if (strcmp(pbuf.pw_name, userBuf)) { rfbLog("User '%s' denied access (not the session owner)\n", userBuf); rfbLog(" Enable user ACL to grant access to other users.\n"); rfbClientAuthFailed(cl, "User denied access"); return; } } if (rfbPAMAuthenticate(cl, pamServiceName, userBuf, pwdBuf, &emsg)) rfbClientAuthSucceeded(cl, rfbAuthUnixLogin); else rfbClientAuthFailed(cl, (char *)emsg); } #endif typedef struct { const char *name; int protocolMinorVer; Bool advertise; CARD8 securityType; } RFBSecTypeData; static RFBSecTypeData secTypeNone = { "none", 3, TRUE, rfbSecTypeNone }; static RFBSecTypeData secTypeVncAuth = { "vncauth", 3, TRUE, rfbSecTypeVncAuth }; static RFBSecTypeData secTypeTight = { "tight", 7, TRUE, rfbSecTypeTight }; static RFBSecTypeData secTypeVeNCrypt = { "vencrypt", 7, TRUE, rfbSecTypeVeNCrypt }; static RFBSecTypeData *rfbSecTypes[] = { &secTypeNone, &secTypeVncAuth, &secTypeVeNCrypt, &secTypeTight, NULL }; typedef void (*AuthFunc) (rfbClientPtr cl); typedef struct { int authType; CARD8 vendorSignature[4]; CARD8 nameSignature[8]; AuthFunc startFunc; AuthFunc rspFunc; } AuthCapData; static AuthCapData authCapNone = { rfbAuthNone, rfbStandardVendor, sig_rfbAuthNone, AuthNoneStartFunc, AuthNoneRspFunc }; static AuthCapData authCapVncAuth = { rfbAuthVNC, rfbStandardVendor, sig_rfbAuthVNC, rfbVncAuthSendChallenge, rfbVncAuthProcessResponse }; static AuthCapData authCapVeNCrypt = { rfbAuthVeNCrypt, rfbVeNCryptVendor, sig_rfbAuthVeNCrypt, rfbVeNCryptAuthenticate, AuthNoneRspFunc }; #ifdef XVNC_AuthPAM static AuthCapData authCapUnixLogin = { rfbAuthUnixLogin, rfbTightVncVendor, sig_rfbAuthUnixLogin, AuthPAMUserPwdStartFunc, AuthPAMUserPwdRspFunc }; #endif static AuthCapData *authCaps[] = { &authCapNone, &authCapVncAuth, &authCapVeNCrypt, #ifdef XVNC_AuthPAM &authCapUnixLogin, #endif NULL }; typedef struct { const char *name; Bool enabled; Bool permitted; int preference; Bool requiredData; RFBSecTypeData *rfbSecType; AuthCapData *authCap; int subType; } SecTypeData; /* * Set the "permitted" member to TRUE if you want the security type to be * available by default. The value of the "permitted-security-types" config * file option will take precedence over the defaults below. * * We permit the rfbAuthNone security type by default for backward * compatibility and only enable it when either explicitly told to do so or if * it is permitted and no other security types were specified on the command * line. */ static SecTypeData secTypes[] = { #if USETLS /* name enabled permitted preference requiredData */ { "tlsnone", FALSE, TRUE, -1, FALSE, /* secType authCap subType */ &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptTLSNone }, { "tlsvnc", TRUE, TRUE, -1, TRUE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptTLSVnc }, { "tlsotp", TRUE, TRUE, -1, TRUE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptTLSVnc }, #ifdef XVNC_AuthPAM { "tlsplain", TRUE, TRUE, -1, TRUE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptTLSPlain }, #endif { "x509none", FALSE, TRUE, -1, FALSE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptX509None }, { "x509vnc", TRUE, TRUE, -1, TRUE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptX509Vnc }, { "x509otp", TRUE, TRUE, -1, TRUE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptX509Vnc }, #ifdef XVNC_AuthPAM { "x509plain", TRUE, TRUE, -1, TRUE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptX509Plain }, #endif #endif { "none", FALSE, TRUE, -1, FALSE, &secTypeNone, &authCapNone, rfbSecTypeNone }, { "vnc", TRUE, TRUE, -1, TRUE, &secTypeVncAuth, &authCapVncAuth, rfbSecTypeVncAuth }, { "otp", TRUE, TRUE, -1, TRUE, &secTypeVncAuth, &authCapVncAuth, rfbSecTypeVncAuth }, #ifdef XVNC_AuthPAM { "unixlogin", TRUE, TRUE, -1, TRUE, &secTypeTight, &authCapUnixLogin, -1 }, { "plain", TRUE, TRUE, -1, TRUE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptPlain }, #endif { NULL } }; Bool rfbOptOtpAuth(void) { SecTypeData *s; for (s = secTypes; s->name != NULL; s++) { if (!strcmp(&s->name[strlen(s->name) - 3], "otp") && s->enabled) return TRUE; } return FALSE; } Bool rfbOptPamAuth(void) { SecTypeData *s; for (s = secTypes; s->name != NULL; s++) { if ((!strcmp(s->name, "unixlogin") || !strcmp(&s->name[strlen(s->name) - 5], "plain")) && s->enabled) return TRUE; } return FALSE; } Bool rfbOptRfbAuth(void) { SecTypeData *s; for (s = secTypes; s->name != NULL; s++) { if (!strcmp(&s->name[strlen(s->name) - 3], "vnc") && s->enabled) return TRUE; } return FALSE; } void rfbAuthParseCommandLine(char *securityTypes) { char *p1 = securityTypes, *p2 = securityTypes; SecTypeData *s; for (s = secTypes; s->name != NULL; s++) s->enabled = FALSE; do { *p2 = *p1; if (!isspace(*p2)) p2++; } while (*p1++ != 0); while (TRUE) { p1 = strtok_r(securityTypes, ",", &p2); securityTypes = NULL; if (p1 == NULL) break; for (s = secTypes; s->name != NULL; s++) { if (!strcasecmp(s->name, p1)) { s->enabled = TRUE; break; } } if (s->name == NULL) FatalError("ERROR: Unknown security type '%s'", p1); } } static void setSecTypes(char *buf, Bool backwardCompatible) { char *saveptr = NULL; char *p; SecTypeData *s; preferenceLimit = 0; for (s = secTypes; s->name != NULL; s++) { s->permitted = FALSE; s->preference = -1; s->rfbSecType->advertise = FALSE; } while (TRUE) { p = strtok_r(buf, ",", &saveptr); buf = NULL; if (p == NULL) break; for (s = secTypes; s->name != NULL; s++) { if (backwardCompatible && s->rfbSecType == &secTypeVeNCrypt) continue; if (!strcasecmp(s->name, p) || (backwardCompatible && !strcasecmp(s->name, "unixlogin") && !strcasecmp(p, "pam-userpwd"))) break; } if (s->name == NULL) FatalError("ERROR: Unknown security type name '%s'", p); s->permitted = TRUE; s->preference = preferenceLimit++; } } void rfbAuthListAvailableSecurityTypes(void) { SecTypeData *s; int chars = 23; ErrorF(" Available security types (case-insensitive):\n"); ErrorF(" "); for (s = secTypes; s->name != NULL; s++) { ErrorF("%s", s->name); chars += strlen(s->name); if ((s + 1)->name != NULL) { ErrorF(", "); chars += 2; if (chars + strlen((s + 1)->name) > 77) { ErrorF("\n "); chars = 23; } } } ErrorF("\n"); } static void ReadConfigFile(void) { FILE *fp; char buf[256], buf2[256]; int line; int len; int n, i, j; struct stat sb; if ((fp = fopen(rfbAuthConfigFile, "r")) == NULL) return; if (fstat(fileno(fp), &sb) == -1) FatalError("rfbAuthInit: ERROR: fstat %s: %s", rfbAuthConfigFile, strerror(errno)); if ((sb.st_uid != 0) && (sb.st_uid != getuid())) FatalError("ERROR: %s must be owned by you or by root", rfbAuthConfigFile); if (sb.st_mode & (S_IWGRP | S_IWOTH)) FatalError("ERROR: %s cannot have group or global write permissions", rfbAuthConfigFile); rfbLog("Using security configuration file %s\n", rfbAuthConfigFile); for (line = 0; fgets(buf, sizeof(buf), fp) != NULL; line++) { len = strlen(buf) - 1; if (buf[len] != '\n' && strlen(buf) == 256) FatalError("ERROR in %s: line %d is too long!", rfbAuthConfigFile, line + 1); buf[len] = '\0'; for (i = 0, j = 0; i < len; i++) { if (buf[i] != ' ' && buf[i] != '\t') buf2[j++] = buf[i]; } len = j; buf2[len] = '\0'; if (len < 1) continue; if (!strcmp(buf2, "no-remote-resize")) { rfbAuthDisableRemoteResize = TRUE; continue; } if (!strcmp(buf2, "no-reverse-connections")) { rfbAuthDisableRevCon = TRUE; continue; } if (!strcmp(buf2, "no-remote-connections")) { interface.s_addr = htonl(INADDR_LOOPBACK); interface6 = in6addr_loopback; continue; } if (!strcmp(buf2, "no-clipboard-send")) { rfbAuthDisableCBSend = TRUE; continue; } if (!strcmp(buf2, "no-clipboard-recv")) { rfbAuthDisableCBRecv = TRUE; continue; } if (!strcmp(buf2, "no-httpd")) { rfbAuthDisableHTTP = TRUE; continue; } if (!strcmp(buf2, "no-x11-tcp-connections")) { rfbAuthDisableX11TCP = TRUE; continue; } #ifdef XVNC_AuthPAM if (!strcmp(buf2, "no-pam-sessions")) { rfbAuthDisablePAMSession = TRUE; continue; } if (!strcmp(buf2, "enable-user-acl")) { rfbAuthUserACL = TRUE; continue; } n = 17; if (!strncmp(buf2, "pam-service-name=", n)) { if (buf2[n] == '\0') FatalError("ERROR in %s: pam-service-name is empty!", rfbAuthConfigFile); if ((pamServiceName = strdup(&buf2[n])) == NULL) FatalError("rfbAuthInit strdup: %s", strerror(errno)); continue; } #endif /* permitted-auth-methods provides backward compatibility with TurboVNC 2.0.x and earlier. It can only be used to enable non-VeNCrypt security types. */ n = 23; if (!strncmp(buf2, "permitted-auth-methods=", n)) { if (buf2[n] == '\0') FatalError("ERROR in %s: permitted-auth-methods is empty!", rfbAuthConfigFile); setSecTypes(&buf2[n], TRUE); continue; } /* permitted-security-types was introduced in TurboVNC 2.1. */ n = 25; if (!strncmp(buf2, "permitted-security-types=", n)) { if (buf2[n] == '\0') FatalError("ERROR in %s: permitted-security-types is empty!", rfbAuthConfigFile); setSecTypes(&buf2[n], FALSE); continue; } #ifdef USETLS n = 24; if (!strncmp(buf2, "permitted-cipher-suites=", n)) { if (buf2[n] == '\0') FatalError("ERROR in %s: permitted-cipher-suites is empty!", rfbAuthConfigFile); if ((rfbAuthCipherSuites = strdup(&buf2[n])) == NULL) FatalError("rfbAuthInit strdup: %s", strerror(errno)); continue; } #endif n = 17; if (!strncmp(buf2, "max-idle-timeout=", n)) { int t; if (buf2[n] == '\0') FatalError("ERROR in %s: max-idle-timeout is empty!", rfbAuthConfigFile); if (sscanf(&buf2[n], "%d", &t) < 1 || t <= 0) FatalError("ERROR in %s: max-idle-timeout value must be > 0!", rfbAuthConfigFile); rfbMaxIdleTimeout = (CARD32)t; continue; } n = 17; if (!strncmp(buf2, "max-desktop-size=", n)) { int w = -1, h = -1; if (buf2[n] == '\0') FatalError("ERROR in %s: max-desktop-size is empty!", rfbAuthConfigFile); if (sscanf(&buf2[n], "%dx%d", &w, &h) < 2 || w <= 0 || h <= 0) FatalError("ERROR in %s: max-desktop-size value is incorrect.", rfbAuthConfigFile); if (w == 0) w = MAXSHORT; if (h == 0) h = MAXSHORT; rfbMaxWidth = (CARD32)w; rfbMaxHeight = (CARD32)h; continue; } if (buf2[0] != '#') rfbLog("WARNING: unrecognized security config line '%s'\n", buf); } fclose(fp); } void rfbAuthInit(void) { SecTypeData *s; int nSelected = 0; ReadConfigFile(); for (s = secTypes; s->name != NULL; s++) { if (s->enabled) { nSelected++; if (!s->permitted) { rfbLog("WARNING: security type '%s' is not permitted\n", s->name); s->enabled = FALSE; continue; } } if (s->enabled) { nSecTypesEnabled++; rfbLog("Enabled security type '%s'\n", s->name); if (!s->rfbSecType->advertise) { s->rfbSecType->advertise = TRUE; rfbLog("Advertising security type '%s' to viewers\n", s->rfbSecType->name); } } } if (nSelected == 0) { /* No security type was selected. See if we should enable the rfbAuthNone security type. */ for (s = secTypes; s->name != NULL; s++) { if (!s->requiredData) { if (s->permitted) { nSecTypesEnabled++; s->enabled = TRUE; s->rfbSecType->advertise = TRUE; rfbLog("Enabled security type '%s'\n", s->name); rfbLog("Advertising security type '%s' to viewers\n", s->rfbSecType->name); } } else { s->rfbSecType->advertise = FALSE; } } } #ifndef XVNC_AuthPAM if (rfbOptPamAuth()) rfbLog("WARNING: PAM support is not compiled in.\n"); #endif if (nSecTypesEnabled == 0) { for (s = secTypes; s->name != NULL; s++) { if (s->permitted) rfbLog("NOTICE: %s is a permitted security type\n", s->name); } FatalError("ERROR: no security types enabled!"); } else { /* Do not advertise rfbAuthNone if any other security type is enabled */ for (s = secTypes; s->name != NULL; s++) { if (s->enabled && strcmp(s->name, "none")) secTypeNone.advertise = FALSE; } } #ifdef XVNC_AuthPAM if (rfbOptPamAuth() && rfbAuthUserACL) { struct passwd pbuf; struct passwd *pw; char buf[256]; char *n; if (getpwuid_r(getuid(), &pbuf, buf, sizeof(buf), &pw) != 0) FatalError("AuthPAMUserPwdRspFunc: limit-user enabled and getpwuid_r failed: %s", strerror(errno)); n = (char *)rfbAlloc(strlen(pbuf.pw_name)); strcpy(n, pbuf.pw_name); rfbAuthAddUser(n, FALSE); } #endif } void rfbAuthProcessResponse(rfbClientPtr cl) { AuthCapData **p; AuthCapData *c; for (p = authCaps; *p != NULL; p++) { c = *p; if (cl->selectedAuthType == c->authType) { c->rspFunc(cl); return; } } rfbLog("rfbAuthProcessResponse: authType assertion failed\n"); rfbCloseClient(cl); } /* * rfbAuthNewClient is called right after negotiating the protocol version. * Depending on the protocol version, we send either a code for the * authentication scheme to be used (protocol 3.3) or a list of possible * "security types" (protocol 3.7 and above.) */ void rfbAuthNewClient(rfbClientPtr cl) { RFBSecTypeData **p; RFBSecTypeData *r; if (rfbAuthIsBlocked()) { rfbLog("Too many authentication failures - client rejected\n"); rfbClientConnFailed(cl, "Too many authentication failures"); return; } if (cl->protocol_minor_ver >= 7) { rfbSendSecurityTypeList(cl); return; } /* Make sure we use only RFB 3.3-compatible security types */ for (p = rfbSecTypes; *p != NULL; p++) { r = *p; if (r->advertise && (r->protocolMinorVer < 7)) break; } if (*p == NULL) { rfbLog("VNC authentication disabled - RFB 3.3 client rejected\n"); rfbClientConnFailed(cl, "Your viewer cannot handle required security types"); return; } cl->selectedAuthType = r->securityType; rfbSendSecurityType(cl, r->securityType); } /* * Tell the client which security type will be used (protocol 3.3) */ static void rfbSendSecurityType(rfbClientPtr cl, int securityType) { CARD32 value32; value32 = Swap32IfLE(securityType); if (WriteExact(cl, (char *)&value32, 4) < 0) { rfbLogPerror("rfbSendSecurityType: write"); rfbCloseClient(cl); return; } switch (securityType) { case rfbSecTypeNone: /* Dispatch client input to rfbProcessClientInitMessage() */ cl->state = RFB_INITIALISATION; break; case rfbSecTypeVncAuth: /* Begin the Standard VNC authentication procedure */ rfbVncAuthSendChallenge(cl); break; default: rfbLogPerror("rfbSendSecurityType: assertion failed"); rfbCloseClient(cl); } } /* * Advertise our supported security types (protocol 3.7 and above) */ static void rfbSendSecurityTypeList(rfbClientPtr cl) { int i, j, n; SecTypeData *s; RFBSecTypeData *r; Bool tightAdvertised = FALSE; /* * When no preference order was set using "permitted-security-types", the * default value of preferenceLimit (1) will cause us to execute the * outer loop once. In this case, the s->preference members will all * be the default value (-1), and we skip the order testing. */ n = 0; for (i = 0; i < preferenceLimit; i++) { for (s = secTypes; s->name != NULL; s++) { if (((s->preference != -1) && (i != s->preference)) || !s->enabled) continue; r = s->rfbSecType; if (n > MAX_SECURITY_TYPES) FatalError("rfbSendSecurityTypeList: # enabled security types > MAX_SECURITY_TYPES"); /* * Check whether we have already advertised this security type */ for (j = 0; j < n; j++) { if (cl->securityTypes[j + 1] == r->securityType) break; } if (j < n) continue; if (r->advertise && (cl->protocol_minor_ver >= r->protocolMinorVer)) { cl->securityTypes[++n] = r->securityType; if (r->securityType == rfbSecTypeTight) tightAdvertised = TRUE; } } } if (n == 0) FatalError("rfbSendSecurityTypeList: no security types enabled! This should not have happened!"); if (!tightAdvertised) { /* * Make sure to advertise the Tight security type, in order to allow * TightVNC-compatible clients to enable other (non-auth) Tight * extensions. */ if (n > MAX_SECURITY_TYPES) FatalError("rfbSendSecurityTypeList: # enabled security types > MAX_SECURITY_TYPES"); rfbLog("rfbSendSecurityTypeList: advertise sectype tight\n"); cl->securityTypes[++n] = rfbSecTypeTight; } cl->securityTypes[0] = (CARD8)n; /* Send the list */ if (WriteExact(cl, (char *)cl->securityTypes, n + 1) < 0) { rfbLogPerror("rfbSendSecurityTypeList: write"); rfbCloseClient(cl); return; } /* Dispatch client input to rfbProcessClientSecurityType() */ cl->state = RFB_SECURITY_TYPE; } #define WRITE(data, size) \ if (WriteExact(cl, (char *)data, size) <= 0) { \ rfbLogPerror("rfbVeNCryptAuthenticate: write"); \ rfbCloseClient(cl); \ return; \ } #define READ(data, size) \ if (ReadExact(cl, (char *)data, size) <= 0) { \ rfbLogPerror("rfbVeNCryptAuthenticate: read"); \ rfbCloseClient(cl); \ return; \ } #if USETLS #define TLS_INIT(anon) \ if ((ctx = rfbssl_init(cl, anon)) == NULL) { \ reply = 0; \ WRITE(&reply, 1); \ rfbClientAuthFailed(cl, rfbssl_geterr()); \ return; \ } \ reply = 1; \ WRITE(&reply, 1); \ cl->sslctx = ctx; \ if ((ret = rfbssl_accept(cl)) < 0) { \ rfbCloseClient(cl); \ return; \ } else if (ret == 1) { \ rfbLog("Deferring TLS handshake\n"); \ cl->state = RFB_TLS_HANDSHAKE; \ return; \ } void rfbAuthTLSHandshake(rfbClientPtr cl) { int ret; if ((ret = rfbssl_accept(cl)) < 0) { rfbCloseClient(cl); return; } else if (ret == 1) return; switch (cl->selectedAuthType) { case rfbAuthNone: rfbClientAuthSucceeded(cl, rfbAuthNone); break; case rfbAuthVNC: rfbVncAuthSendChallenge(cl); break; #ifdef XVNC_AuthPAM case rfbAuthUnixLogin: AuthPAMUserPwdRspFunc(cl); break; #endif } } #endif void rfbVeNCryptAuthenticate(rfbClientPtr cl) { struct { CARD8 major, minor; } serverVersion = { 0, 2 }, clientVersion = { 0, 0 }; CARD8 reply, count = 0; int i, j; SecTypeData *s; CARD32 subTypes[MAX_VENCRYPT_SUBTYPES], chosenType = 0; #if USETLS rfbSslCtx *ctx; int ret; #endif WRITE(&serverVersion.major, 1); WRITE(&serverVersion.minor, 1); rfbUncorkSock(cl->sock); rfbCorkSock(cl->sock); READ(&clientVersion, 2); if (clientVersion.major == 0 && clientVersion.minor < 2) { reply = 0xFF; WRITE(&reply, 1); rfbCloseClient(cl); return; } else { reply = 0; WRITE(&reply, 1); } memset(subTypes, 0, sizeof(CARD32) * MAX_VENCRYPT_SUBTYPES); for (i = 0; i < preferenceLimit; i++) { for (s = secTypes; s->name != NULL; s++) { if (((s->preference != -1) && (i != s->preference)) || !s->enabled || s->subType == -1) continue; if (count > MAX_VENCRYPT_SUBTYPES) FatalError("rfbVeNCryptAuthenticate: # enabled subtypes > MAX_VENCRYPT_SUBTYPES"); /* Check whether we have already advertised this subtype */ for (j = 0; j < count; j++) { if (subTypes[j] == s->subType) break; } if (j < count) continue; subTypes[count++] = s->subType; } } WRITE(&count, 1); if (count > 0) { for (i = 0; i < count; i++) { CARD32 subType = Swap32IfLE(subTypes[i]); WRITE(&subType, sizeof(CARD32)); } } rfbUncorkSock(cl->sock); rfbCorkSock(cl->sock); READ(&chosenType, sizeof(CARD32)); chosenType = Swap32IfLE(chosenType); for (i = 0; i < count; i++) { if (chosenType == subTypes[i]) break; } rfbLog("Client requested VeNCrypt sub-type %d\n", chosenType); if (chosenType == 0 || chosenType == rfbSecTypeVeNCrypt || i >= count) { rfbLog("Requested VeNCrypt sub-type not supported\n"); rfbCloseClient(cl); return; } cl->selectedAuthType = chosenType; switch (chosenType) { case rfbAuthNone: rfbClientAuthSucceeded(cl, rfbAuthNone); break; case rfbAuthVNC: rfbVncAuthSendChallenge(cl); break; #ifdef XVNC_AuthPAM case rfbVeNCryptPlain: AuthPAMUserPwdRspFunc(cl); break; #endif #if USETLS case rfbVeNCryptTLSNone: cl->selectedAuthType = rfbAuthNone; TLS_INIT(TRUE); rfbClientAuthSucceeded(cl, rfbAuthNone); break; case rfbVeNCryptTLSVnc: cl->selectedAuthType = rfbAuthVNC; TLS_INIT(TRUE); rfbVncAuthSendChallenge(cl); break; #ifdef XVNC_AuthPAM case rfbVeNCryptTLSPlain: cl->selectedAuthType = rfbAuthUnixLogin; TLS_INIT(TRUE); AuthPAMUserPwdRspFunc(cl); break; #endif case rfbVeNCryptX509None: cl->selectedAuthType = rfbAuthNone; TLS_INIT(FALSE); rfbClientAuthSucceeded(cl, rfbAuthNone); break; case rfbVeNCryptX509Vnc: cl->selectedAuthType = rfbAuthVNC; TLS_INIT(FALSE); rfbVncAuthSendChallenge(cl); break; #ifdef XVNC_AuthPAM case rfbVeNCryptX509Plain: cl->selectedAuthType = rfbAuthUnixLogin; TLS_INIT(FALSE); AuthPAMUserPwdRspFunc(cl); break; #endif #endif default: FatalError("rfbVeNCryptAuthenticate: chosen type is invalid (this should never occur)"); } } /* * Read the security type chosen by the client (protocol 3.7 and above) */ void rfbProcessClientSecurityType(rfbClientPtr cl) { int n, count, i; CARD8 chosenType; /* Read the security type */ n = ReadExact(cl, (char *)&chosenType, 1); if (n <= 0) { if (n == 0) rfbLog("rfbProcessClientSecurityType: client gone\n"); else rfbLogPerror("rfbProcessClientSecurityType: read"); rfbCloseClient(cl); return; } /* Make sure it was present in the list sent by the server */ count = (int)cl->securityTypes[0]; for (i = 1; i <= count; i++) { if (chosenType == cl->securityTypes[i]) break; } if (i > count) { rfbLog("rfbProcessClientSecurityType: wrong security type requested\n"); rfbCloseClient(cl); return; } cl->selectedAuthType = chosenType; switch (chosenType) { case rfbSecTypeNone: /* No authentication needed */ rfbClientAuthSucceeded(cl, rfbAuthNone); break; case rfbSecTypeVncAuth: /* Begin the Standard VNC authentication procedure */ rfbVncAuthSendChallenge(cl); break; case rfbSecTypeTight: /* The viewer supports TightVNC extensions */ rfbLog("Enabling TightVNC protocol extensions\n"); /* Switch to protocol 3.7t/3.8t */ cl->protocol_tightvnc = TRUE; /* Advertise our tunneling capabilities */ rfbSendTunnelingCaps(cl); break; case rfbSecTypeVeNCrypt: /* The viewer supports VeNCrypt extensions */ rfbLog("Enabling VeNCrypt protocol extensions\n"); rfbVeNCryptAuthenticate(cl); break; default: rfbLog("rfbProcessClientSecurityType: unknown authentication scheme\n"); rfbCloseClient(cl); break; } } /* * Send the list of our tunneling capabilities (protocol 3.7t/3.8t) */ static void rfbSendTunnelingCaps(rfbClientPtr cl) { rfbTunnelingCapsMsg caps; CARD32 nTypes = 0; /* We don't support tunneling yet */ caps.nTunnelTypes = Swap32IfLE(nTypes); if (WriteExact(cl, (char *)&caps, sz_rfbTunnelingCapsMsg) < 0) { rfbLogPerror("rfbSendTunnelingCaps: write"); rfbCloseClient(cl); return; } if (nTypes) /* Dispatch client input to rfbProcessClientTunnelingType() */ cl->state = RFB_TUNNELING_TYPE; else rfbSendAuthCaps(cl); } /* * Read tunneling type requested by the client (protocol 3.7t/3.8t) * * NOTE: Currently we don't support tunneling, and this function can never be * called. */ void rfbProcessClientTunnelingType(rfbClientPtr cl) { /* If we were called, then something's really wrong. */ rfbLog("rfbProcessClientTunnelingType: not implemented\n"); rfbCloseClient(cl); } /* * Send the list of our authentication capabilities to the client * (protocol 3.7t/3.8t) */ static void rfbSendAuthCaps(rfbClientPtr cl) { rfbAuthenticationCapsMsg caps; rfbCapabilityInfo caplist[MAX_AUTH_CAPS]; int count = 0; int j; SecTypeData *s; AuthCapData *c; rfbCapabilityInfo *pcap; char tempstr[9]; if (!cl->reverseConnection) { int i; /* * When no preference order was set using "permitted-security-types", * the default value of preferenceLimit (1) will cause us to execute * the outer loop once. In this case, the s->preference members will * all be the default value (-1), and we skip the order testing. */ for (i = 0; i < preferenceLimit; i++) { for (s = secTypes; s->name != NULL; s++) { if (((s->preference != -1) && (i != s->preference)) || !s->enabled) continue; c = s->authCap; if (count > MAX_AUTH_CAPS) FatalError("rfbSendAuthCaps: # enabled security types > MAX_AUTH_CAPS"); /* * Check to see if we have already advertised this auth cap. * VNC password and OTP both use the VNC authentication cap. */ for (j = 0; j < count; j++) { if (cl->authCaps[j] == c->authType) break; } if (j < count) continue; pcap = &caplist[count]; pcap->code = Swap32IfLE(c->authType); memcpy(pcap->vendorSignature, c->vendorSignature, sz_rfbCapabilityInfoVendor); memcpy(pcap->nameSignature, c->nameSignature, sz_rfbCapabilityInfoName); cl->authCaps[count] = c->authType; strncpy(tempstr, (char *)pcap->nameSignature, 8); tempstr[8] = 0; rfbLog("Advertising Tight auth cap '%s'\n", tempstr); count++; } } if (count == 0) FatalError("rfbSendAuthCaps: authentication required but no security types enabled! This should not have happened!"); } cl->nAuthCaps = count; caps.nAuthTypes = Swap32IfLE((CARD32)count); if (WriteExact(cl, (char *)&caps, sz_rfbAuthenticationCapsMsg) < 0) { rfbLogPerror("rfbSendAuthCaps: write"); rfbCloseClient(cl); return; } if (count) { if (WriteExact(cl, (char *)&caplist[0], count *sz_rfbCapabilityInfo) < 0) { rfbLogPerror("rfbSendAuthCaps: write"); rfbCloseClient(cl); return; } /* Dispatch client input to rfbProcessClientAuthType() */ cl->state = RFB_AUTH_TYPE; } else { /* No authentication needed */ rfbClientAuthSucceeded(cl, rfbAuthNone); cl->state = RFB_INITIALISATION; } } /* * Read client's preferred authentication type (protocol 3.7t/3.8t) */ void rfbProcessClientAuthType(rfbClientPtr cl) { CARD32 auth_type; int n, i; AuthCapData **p; AuthCapData *c; /* Read authentication type selected by the client */ n = ReadExact(cl, (char *)&auth_type, sizeof(auth_type)); if (n <= 0) { if (n == 0) rfbLog("rfbProcessClientAuthType: client gone\n"); else rfbLogPerror("rfbProcessClientAuthType: read"); rfbCloseClient(cl); return; } auth_type = Swap32IfLE(auth_type); /* Make sure it was present in the list sent by the server */ for (i = 0; i < cl->nAuthCaps; i++) { if (auth_type == cl->authCaps[i]) break; } if (i >= cl->nAuthCaps) { rfbLog("rfbProcessClientAuthType: wrong authentication type requested\n"); rfbCloseClient(cl); return; } for (p = authCaps; *p != NULL; p++) { c = *p; if (auth_type == c->authType) { cl->selectedAuthType = auth_type; c->startFunc(cl); return; } } rfbLog("rfbProcessClientAuthType: unknown authentication scheme\n"); rfbCloseClient(cl); } /* * Send the authentication challenge */ static void rfbVncAuthSendChallenge(rfbClientPtr cl) { vncRandomBytes(cl->authChallenge); if (WriteExact(cl, (char *)cl->authChallenge, CHALLENGESIZE) < 0) { rfbLogPerror("rfbVncAuthSendChallenge: write"); rfbCloseClient(cl); return; } /* Dispatch client input to rfbVncAuthProcessResponse() */ cl->state = RFB_AUTHENTICATION; } static Bool CheckResponse(rfbClientPtr cl, int numPasswords, char *passwdFullControl, char *passwdViewOnly, CARD8 *response) { Bool ok = FALSE; CARD8 encryptedChallenge1[CHALLENGESIZE]; CARD8 encryptedChallenge2[CHALLENGESIZE]; memcpy(encryptedChallenge1, cl->authChallenge, CHALLENGESIZE); vncEncryptBytes(encryptedChallenge1, passwdFullControl); memcpy(encryptedChallenge2, cl->authChallenge, CHALLENGESIZE); vncEncryptBytes(encryptedChallenge2, (numPasswords == 2) ? passwdViewOnly : passwdFullControl); /* Delete the passwords from memory */ memset(passwdFullControl, 0, MAXPWLEN + 1); memset(passwdViewOnly, 0, MAXPWLEN + 1); if (memcmp(encryptedChallenge1, response, CHALLENGESIZE) == 0) { rfbLog("Full-control authentication enabled for %s\n", cl->host); ok = TRUE; cl->viewOnly = FALSE; } else if (memcmp(encryptedChallenge2, response, CHALLENGESIZE) == 0) { rfbLog("View-only authentication enabled for %s\n", cl->host); ok = TRUE; cl->viewOnly = TRUE; } return ok; } /* * rfbVncAuthProcessResponse is called when the client sends its * authentication response. */ void rfbVncAuthProcessResponse(rfbClientPtr cl) { char passwdFullControl[MAXPWLEN + 1] = "\0"; char passwdViewOnly[MAXPWLEN + 1] = "\0"; int numPasswords; Bool ok; int n; CARD8 response[CHALLENGESIZE]; n = ReadExact(cl, (char *)response, CHALLENGESIZE); if (n <= 0) { if (n != 0) rfbLogPerror("rfbVncAuthProcessResponse: read"); rfbCloseClient(cl); return; } ok = FALSE; if (rfbOptOtpAuth()) { if (rfbAuthOTPValue == NULL) { if (nSecTypesEnabled == 1) { rfbClientAuthFailed(cl, "The one-time password has not been set on the server"); return; } } else { memcpy(passwdFullControl, rfbAuthOTPValue, MAXPWLEN); passwdFullControl[MAXPWLEN] = '\0'; numPasswords = rfbAuthOTPValueLen / MAXPWLEN; if (numPasswords > 1) { memcpy(passwdViewOnly, rfbAuthOTPValue + MAXPWLEN, MAXPWLEN); passwdViewOnly[MAXPWLEN] = '\0'; } ok = CheckResponse(cl, numPasswords, passwdFullControl, passwdViewOnly, response); if (ok) { memset(rfbAuthOTPValue, 0, rfbAuthOTPValueLen); free(rfbAuthOTPValue); rfbAuthOTPValue = NULL; } } } if ((ok == FALSE) && rfbOptRfbAuth()) { if (!rfbAuthPasswdFile) { rfbClientAuthFailed(cl, "No VNC password file specified on the server (did you forget -rfbauth?)"); return; } numPasswords = vncDecryptPasswdFromFile2(rfbAuthPasswdFile, passwdFullControl, passwdViewOnly); if (numPasswords == 0) { rfbLog("rfbVncAuthProcessResponse: could not get password from %s\n", rfbAuthPasswdFile); if (nSecTypesEnabled == 1) { rfbClientAuthFailed(cl, "The server could not read the VNC password file"); return; } } ok = CheckResponse(cl, numPasswords, passwdFullControl, passwdViewOnly, response); } if (ok) { rfbAuthUnblock(); rfbClientAuthSucceeded(cl, rfbAuthVNC); } else { rfbLog("rfbVncAuthProcessResponse: authentication failed from %s\n", cl->host); if (rfbAuthConsiderBlocking()) rfbClientAuthFailed(cl, "Authentication failed. Too many tries"); else rfbClientAuthFailed(cl, "Authentication failed"); } } /* * rfbClientConnFailed is called when a client connection has failed before * the authentication stage. */ void rfbClientConnFailed(rfbClientPtr cl, char *reason) { int headerLen, reasonLen; char buf[8]; CARD32 *buf32 = (CARD32 *)buf; headerLen = (cl->protocol_minor_ver >= 7) ? 1 : 4; reasonLen = strlen(reason); buf32[0] = 0; buf32[1] = Swap32IfLE(reasonLen); if (WriteExact(cl, buf, headerLen) < 0 || WriteExact(cl, buf + 4, 4) < 0 || WriteExact(cl, reason, reasonLen) < 0) rfbLogPerror("rfbClientConnFailed: write"); rfbCloseClient(cl); } /* * rfbClientAuthFailed is called on authentication failure. Sending a reason * string is defined in RFB 3.8 and above. */ void rfbClientAuthFailed(rfbClientPtr cl, char *reason) { int reasonLen; char buf[8]; CARD32 *buf32 = (CARD32 *)buf; if (cl->protocol_minor_ver < 8) reason = NULL; /* invalidate the pointer */ reasonLen = (reason == NULL) ? 0 : strlen(reason); buf32[0] = Swap32IfLE(rfbAuthFailed); buf32[1] = Swap32IfLE(reasonLen); if (reasonLen == 0) { if (WriteExact(cl, buf, 4) < 0) rfbLogPerror("rfbClientAuthFailed: write"); } else { if (WriteExact(cl, buf, 8) < 0 || WriteExact(cl, reason, reasonLen) < 0) rfbLogPerror("rfbClientAuthFailed: write"); } rfbCloseClient(cl); } /* * rfbClientAuthSucceeded is called on successful authentication. It just * sends rfbAuthOK and dispatches client input to * rfbProcessClientInitMessage(). However, the rfbAuthOK message is not sent * if authentication was not required and the protocol version is 3.7 or lower. */ void rfbClientAuthSucceeded(rfbClientPtr cl, CARD32 authType) { CARD32 authResult; if (cl->protocol_minor_ver >= 8 || authType == rfbAuthVNC) { authResult = Swap32IfLE(rfbAuthOK); if (WriteExact(cl, (char *)&authResult, 4) < 0) { rfbLogPerror("rfbClientAuthSucceeded: write"); rfbCloseClient(cl); return; } } /* Dispatch client input to rfbProcessClientInitMessage() */ cl->state = RFB_INITIALISATION; } /********************************************************************* * Functions to prevent too many successive authentication failures. * * FIXME: This should be performed separately for each client. */ /* Maximum authentication failures before blocking connections */ #define MAX_AUTH_TRIES 5 /* Delay in ms. This doubles for each failure over MAX_AUTH_TRIES. */ #define AUTH_TOO_MANY_BASE_DELAY 10 * 1000 static int rfbAuthTries = 0; static Bool rfbAuthTooManyTries = FALSE; static OsTimerPtr timer = NULL; /* * This function should not be called directly. It is called by setting a * timer in rfbAuthConsiderBlocking(). */ static CARD32 rfbAuthReenable(OsTimerPtr timer, CARD32 now, pointer arg) { rfbAuthTooManyTries = FALSE; return 0; } /* * This function should be called after each authentication failure. The * return value will be true if there were too many failures. */ Bool rfbAuthConsiderBlocking(void) { int i; rfbAuthTries++; if (rfbAuthTries >= MAX_AUTH_TRIES) { CARD32 delay = AUTH_TOO_MANY_BASE_DELAY; for (i = MAX_AUTH_TRIES; i < rfbAuthTries; i++) delay *= 2; timer = TimerSet(timer, 0, delay, rfbAuthReenable, NULL); rfbAuthTooManyTries = TRUE; return TRUE; } return FALSE; } /* * This function should be called after a successful authentication. It * resets the counter of authentication failures. Note that it's not necessary * to clear the rfbAuthTooManyTries flag, as it will be reset by the timer * function. */ void rfbAuthUnblock(void) { rfbAuthTries = 0; } /* * This function should be called before authentication. The return value will * be true if there were too many authentication failures, and the server * should not allow another try. */ Bool rfbAuthIsBlocked(void) { return rfbAuthTooManyTries; }
null
/* * auth.c - deal with authentication. * * This file implements authentication when setting up an RFB connection. */ /* * Copyright (C) 2010, 2012-2019 D. R. Commander. All Rights Reserved. * Copyright (C) 2010 University Corporation for Atmospheric Research. * All Rights Reserved. * Copyright (C) 2003-2006 Constantin Kaplinsky. All Rights Reserved. * Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. */ #ifndef _POSIX_PTHREAD_SEMANTICS #define _POSIX_PTHREAD_SEMANTICS #endif #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <errno.h> #include "rfb.h" #include "windowstr.h" char *rfbAuthPasswdFile = NULL; static void rfbSendSecurityType(rfbClientPtr cl, int securityType); static void rfbSendSecurityTypeList(rfbClientPtr cl); static void rfbSendTunnelingCaps(rfbClientPtr cl); static void rfbSendAuthCaps(rfbClientPtr cl); static void rfbVncAuthSendChallenge(rfbClientPtr cl); static void rfbVeNCryptAuthenticate(rfbClientPtr cl); #define AUTH_DEFAULT_CONF_FILE \ CMAKE_INSTALL_FULL_SYSCONFDIR "/turbovncserver-security.conf" #ifdef XVNC_AuthPAM #define AUTH_DEFAULT_PAM_SERVICE_NAME "turbovnc" #endif #define MAX_USER_LEN 64 #define MAX_PWD_LEN 64 char *rfbAuthConfigFile = AUTH_DEFAULT_CONF_FILE; Bool rfbAuthDisableRemoteResize = FALSE; Bool rfbAuthDisableRevCon = FALSE; Bool rfbAuthDisableCBSend = FALSE; Bool rfbAuthDisableCBRecv = FALSE; Bool rfbAuthDisableHTTP = FALSE; Bool rfbAuthDisableX11TCP = FALSE; static int nSecTypesEnabled = 0; static int preferenceLimit = 1; /* Force one iteration of the loop in rfbSendAuthCaps() */ char *rfbAuthOTPValue = NULL; int rfbAuthOTPValueLen = 0; #if USETLS char *rfbAuthX509Cert = NULL; char *rfbAuthX509Key = NULL; char *rfbAuthCipherSuites = NULL; #endif static void AuthNoneStartFunc(rfbClientPtr cl) { rfbClientAuthSucceeded(cl, rfbAuthNone); } static void AuthNoneRspFunc(rfbClientPtr cl) { } #ifdef XVNC_AuthPAM #include <pwd.h> static char *pamServiceName = AUTH_DEFAULT_PAM_SERVICE_NAME; typedef struct UserList { struct UserList *next; const char *name; Bool viewOnly; } UserList; static UserList *userACL = NULL; Bool rfbAuthUserACL = FALSE; void rfbAuthAddUser(const char *name, Bool viewOnly) { UserList *p = (UserList *)rfbAlloc(sizeof(UserList)); rfbLog("Adding user '%s' to ACL with %s privileges\n", name, viewOnly ? " view-only" : "full control"); p->next = userACL; p->name = name; p->viewOnly = viewOnly; userACL = p; } void rfbAuthRevokeUser(const char *name) { UserList **prev = &userACL; UserList *p; rfbLog("Removing user '%s' from ACL\n", name); while (*prev != NULL) { p = *prev; if (!strcmp(p->name, name)) { *prev = p->next; free((void *)p->name); free(p); return; } prev = &p->next; } } static void AuthPAMUserPwdStartFunc(rfbClientPtr cl) { cl->state = RFB_AUTHENTICATION; } static void AuthPAMUserPwdRspFunc(rfbClientPtr cl) { CARD32 userLen; CARD32 pwdLen; char userBuf[MAX_USER_LEN + 1]; char pwdBuf[MAX_PWD_LEN + 1]; int n; const char *emsg; n = ReadExact(cl, (char *)&userLen, sizeof(userLen)); if (n <= 0) { if (n != 0) rfbLogPerror("AuthPAMUserPwdRspFunc: read error"); rfbCloseClient(cl); return; } userLen = Swap32IfLE(userLen); n = ReadExact(cl, (char *)&pwdLen, sizeof(pwdLen)); if (n <= 0) { if (n != 0) rfbLogPerror("AuthPAMUserPwdRspFunc: read error"); rfbCloseClient(cl); return; } pwdLen = Swap32IfLE(pwdLen); if ((userLen > MAX_USER_LEN) || (pwdLen > MAX_PWD_LEN)) { rfbLogPerror("AuthPAMUserPwdRspFunc: excessively large user name or password in response"); rfbCloseClient(cl); return; } n = ReadExact(cl, userBuf, userLen); if (n <= 0) { if (n != 0) rfbLogPerror("AuthPAMUserPwdRspFunc: error reading user name"); rfbCloseClient(cl); return; } userBuf[userLen] = '\0'; n = ReadExact(cl, pwdBuf, pwdLen); if (n <= 0) { if (n != 0) rfbLogPerror("AuthPAMUserPwdRspFunc: error reading password"); rfbCloseClient(cl); return; } pwdBuf[pwdLen] = '\0'; if (rfbAuthUserACL) { UserList *p = userACL; if (p == NULL) rfbLog("WARNING: User ACL is empty. No users will be allowed to log in with Unix Login authentication.\n"); while (p != NULL) { if (!strcmp(p->name, userBuf)) break; p = p->next; } if (p == NULL) { rfbLog("User '%s' is not in the ACL and has been denied access\n", userBuf); rfbClientAuthFailed(cl, "User denied access"); return; } cl->viewOnly = p->viewOnly; } else { struct passwd pbuf; struct passwd *pw; char buf[256]; if (getpwuid_r(getuid(), &pbuf, buf, sizeof(buf), &pw) != 0) FatalError("AuthPAMUserPwdRspFunc: getpwuid_r failed: %s", strerror(errno)); if (strcmp(pbuf.pw_name, userBuf)) { rfbLog("User '%s' denied access (not the session owner)\n", userBuf); rfbLog(" Enable user ACL to grant access to other users.\n"); rfbClientAuthFailed(cl, "User denied access"); return; } } if (rfbPAMAuthenticate(cl, pamServiceName, userBuf, pwdBuf, &emsg)) rfbClientAuthSucceeded(cl, rfbAuthUnixLogin); else rfbClientAuthFailed(cl, (char *)emsg); } #endif typedef struct { const char *name; int protocolMinorVer; Bool advertise; CARD8 securityType; } RFBSecTypeData; static RFBSecTypeData secTypeNone = { "none", 3, TRUE, rfbSecTypeNone }; static RFBSecTypeData secTypeVncAuth = { "vncauth", 3, TRUE, rfbSecTypeVncAuth }; static RFBSecTypeData secTypeTight = { "tight", 7, TRUE, rfbSecTypeTight }; static RFBSecTypeData secTypeVeNCrypt = { "vencrypt", 7, TRUE, rfbSecTypeVeNCrypt }; static RFBSecTypeData *rfbSecTypes[] = { &secTypeNone, &secTypeVncAuth, &secTypeVeNCrypt, &secTypeTight, NULL }; typedef void (*AuthFunc) (rfbClientPtr cl); typedef struct { int authType; CARD8 vendorSignature[4]; CARD8 nameSignature[8]; AuthFunc startFunc; AuthFunc rspFunc; } AuthCapData; static AuthCapData authCapNone = { rfbAuthNone, rfbStandardVendor, sig_rfbAuthNone, AuthNoneStartFunc, AuthNoneRspFunc }; static AuthCapData authCapVncAuth = { rfbAuthVNC, rfbStandardVendor, sig_rfbAuthVNC, rfbVncAuthSendChallenge, rfbVncAuthProcessResponse }; static AuthCapData authCapVeNCrypt = { rfbAuthVeNCrypt, rfbVeNCryptVendor, sig_rfbAuthVeNCrypt, rfbVeNCryptAuthenticate, AuthNoneRspFunc }; #ifdef XVNC_AuthPAM static AuthCapData authCapUnixLogin = { rfbAuthUnixLogin, rfbTightVncVendor, sig_rfbAuthUnixLogin, AuthPAMUserPwdStartFunc, AuthPAMUserPwdRspFunc }; #endif static AuthCapData *authCaps[] = { &authCapNone, &authCapVncAuth, &authCapVeNCrypt, #ifdef XVNC_AuthPAM &authCapUnixLogin, #endif NULL }; typedef struct { const char *name; Bool enabled; Bool permitted; int preference; Bool requiredData; RFBSecTypeData *rfbSecType; AuthCapData *authCap; int subType; } SecTypeData; /* * Set the "permitted" member to TRUE if you want the security type to be * available by default. The value of the "permitted-security-types" config * file option will take precedence over the defaults below. * * We permit the rfbAuthNone security type by default for backward * compatibility and only enable it when either explicitly told to do so or if * it is permitted and no other security types were specified on the command * line. */ static SecTypeData secTypes[] = { #if USETLS /* name enabled permitted preference requiredData */ { "tlsnone", FALSE, TRUE, -1, FALSE, /* secType authCap subType */ &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptTLSNone }, { "tlsvnc", TRUE, TRUE, -1, TRUE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptTLSVnc }, { "tlsotp", TRUE, TRUE, -1, TRUE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptTLSVnc }, #ifdef XVNC_AuthPAM { "tlsplain", TRUE, TRUE, -1, TRUE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptTLSPlain }, #endif { "x509none", FALSE, TRUE, -1, FALSE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptX509None }, { "x509vnc", TRUE, TRUE, -1, TRUE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptX509Vnc }, { "x509otp", TRUE, TRUE, -1, TRUE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptX509Vnc }, #ifdef XVNC_AuthPAM { "x509plain", TRUE, TRUE, -1, TRUE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptX509Plain }, #endif #endif { "none", FALSE, TRUE, -1, FALSE, &secTypeNone, &authCapNone, rfbSecTypeNone }, { "vnc", TRUE, TRUE, -1, TRUE, &secTypeVncAuth, &authCapVncAuth, rfbSecTypeVncAuth }, { "otp", TRUE, TRUE, -1, TRUE, &secTypeVncAuth, &authCapVncAuth, rfbSecTypeVncAuth }, #ifdef XVNC_AuthPAM { "unixlogin", TRUE, TRUE, -1, TRUE, &secTypeTight, &authCapUnixLogin, -1 }, { "plain", TRUE, TRUE, -1, TRUE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptPlain }, #endif { NULL } }; Bool rfbOptOtpAuth(void) { SecTypeData *s; for (s = secTypes; s->name != NULL; s++) { if (!strcmp(&s->name[strlen(s->name) - 3], "otp") && s->enabled) return TRUE; } return FALSE; } Bool rfbOptPamAuth(void) { SecTypeData *s; for (s = secTypes; s->name != NULL; s++) { if ((!strcmp(s->name, "unixlogin") || strstr(s->name, "plain")) && s->enabled) return TRUE; } return FALSE; } Bool rfbOptRfbAuth(void) { SecTypeData *s; for (s = secTypes; s->name != NULL; s++) { if (!strcmp(&s->name[strlen(s->name) - 3], "vnc") && s->enabled) return TRUE; } return FALSE; } void rfbAuthParseCommandLine(char *securityTypes) { char *p1 = securityTypes, *p2 = securityTypes; SecTypeData *s; for (s = secTypes; s->name != NULL; s++) s->enabled = FALSE; do { *p2 = *p1; if (!isspace(*p2)) p2++; } while (*p1++ != 0); while (TRUE) { p1 = strtok_r(securityTypes, ",", &p2); securityTypes = NULL; if (p1 == NULL) break; for (s = secTypes; s->name != NULL; s++) { if (!strcasecmp(s->name, p1)) { s->enabled = TRUE; break; } } if (s->name == NULL) FatalError("ERROR: Unknown security type '%s'", p1); } } static void setSecTypes(char *buf, Bool backwardCompatible) { char *saveptr = NULL; char *p; SecTypeData *s; preferenceLimit = 0; for (s = secTypes; s->name != NULL; s++) { s->permitted = FALSE; s->preference = -1; s->rfbSecType->advertise = FALSE; } while (TRUE) { p = strtok_r(buf, ",", &saveptr); buf = NULL; if (p == NULL) break; for (s = secTypes; s->name != NULL; s++) { if (backwardCompatible && s->rfbSecType == &secTypeVeNCrypt) continue; if (!strcasecmp(s->name, p) || (backwardCompatible && !strcasecmp(s->name, "unixlogin") && !strcasecmp(p, "pam-userpwd"))) break; } if (s->name == NULL) FatalError("ERROR: Unknown security type name '%s'", p); s->permitted = TRUE; s->preference = preferenceLimit++; } } void rfbAuthListAvailableSecurityTypes(void) { SecTypeData *s; int chars = 23; ErrorF(" Available security types (case-insensitive):\n"); ErrorF(" "); for (s = secTypes; s->name != NULL; s++) { ErrorF("%s", s->name); chars += strlen(s->name); if ((s + 1)->name != NULL) { ErrorF(", "); chars += 2; if (chars + strlen((s + 1)->name) > 77) { ErrorF("\n "); chars = 23; } } } ErrorF("\n"); } static void ReadConfigFile(void) { FILE *fp; char buf[256], buf2[256]; int line; int len; int n, i, j; struct stat sb; if ((fp = fopen(rfbAuthConfigFile, "r")) == NULL) return; if (fstat(fileno(fp), &sb) == -1) FatalError("rfbAuthInit: ERROR: fstat %s: %s", rfbAuthConfigFile, strerror(errno)); if ((sb.st_uid != 0) && (sb.st_uid != getuid())) FatalError("ERROR: %s must be owned by you or by root", rfbAuthConfigFile); if (sb.st_mode & (S_IWGRP | S_IWOTH)) FatalError("ERROR: %s cannot have group or global write permissions", rfbAuthConfigFile); rfbLog("Using security configuration file %s\n", rfbAuthConfigFile); for (line = 0; fgets(buf, sizeof(buf), fp) != NULL; line++) { len = strlen(buf) - 1; if (buf[len] != '\n' && strlen(buf) == 256) FatalError("ERROR in %s: line %d is too long!", rfbAuthConfigFile, line + 1); buf[len] = '\0'; for (i = 0, j = 0; i < len; i++) { if (buf[i] != ' ' && buf[i] != '\t') buf2[j++] = buf[i]; } len = j; buf2[len] = '\0'; if (len < 1) continue; if (!strcmp(buf2, "no-remote-resize")) { rfbAuthDisableRemoteResize = TRUE; continue; } if (!strcmp(buf2, "no-reverse-connections")) { rfbAuthDisableRevCon = TRUE; continue; } if (!strcmp(buf2, "no-remote-connections")) { interface.s_addr = htonl(INADDR_LOOPBACK); interface6 = in6addr_loopback; continue; } if (!strcmp(buf2, "no-clipboard-send")) { rfbAuthDisableCBSend = TRUE; continue; } if (!strcmp(buf2, "no-clipboard-recv")) { rfbAuthDisableCBRecv = TRUE; continue; } if (!strcmp(buf2, "no-httpd")) { rfbAuthDisableHTTP = TRUE; continue; } if (!strcmp(buf2, "no-x11-tcp-connections")) { rfbAuthDisableX11TCP = TRUE; continue; } #ifdef XVNC_AuthPAM if (!strcmp(buf2, "no-pam-sessions")) { rfbAuthDisablePAMSession = TRUE; continue; } if (!strcmp(buf2, "enable-user-acl")) { rfbAuthUserACL = TRUE; continue; } n = 17; if (!strncmp(buf2, "pam-service-name=", n)) { if (buf2[n] == '\0') FatalError("ERROR in %s: pam-service-name is empty!", rfbAuthConfigFile); if ((pamServiceName = strdup(&buf2[n])) == NULL) FatalError("rfbAuthInit strdup: %s", strerror(errno)); continue; } #endif /* permitted-auth-methods provides backward compatibility with TurboVNC 2.0.x and earlier. It can only be used to enable non-VeNCrypt security types. */ n = 23; if (!strncmp(buf2, "permitted-auth-methods=", n)) { if (buf2[n] == '\0') FatalError("ERROR in %s: permitted-auth-methods is empty!", rfbAuthConfigFile); setSecTypes(&buf2[n], TRUE); continue; } /* permitted-security-types was introduced in TurboVNC 2.1. */ n = 25; if (!strncmp(buf2, "permitted-security-types=", n)) { if (buf2[n] == '\0') FatalError("ERROR in %s: permitted-security-types is empty!", rfbAuthConfigFile); setSecTypes(&buf2[n], FALSE); continue; } #ifdef USETLS n = 24; if (!strncmp(buf2, "permitted-cipher-suites=", n)) { if (buf2[n] == '\0') FatalError("ERROR in %s: permitted-cipher-suites is empty!", rfbAuthConfigFile); if ((rfbAuthCipherSuites = strdup(&buf2[n])) == NULL) FatalError("rfbAuthInit strdup: %s", strerror(errno)); continue; } #endif n = 17; if (!strncmp(buf2, "max-idle-timeout=", n)) { int t; if (buf2[n] == '\0') FatalError("ERROR in %s: max-idle-timeout is empty!", rfbAuthConfigFile); if (sscanf(&buf2[n], "%d", &t) < 1 || t <= 0) FatalError("ERROR in %s: max-idle-timeout value must be > 0!", rfbAuthConfigFile); rfbMaxIdleTimeout = (CARD32)t; continue; } n = 17; if (!strncmp(buf2, "max-desktop-size=", n)) { int w = -1, h = -1; if (buf2[n] == '\0') FatalError("ERROR in %s: max-desktop-size is empty!", rfbAuthConfigFile); if (sscanf(&buf2[n], "%dx%d", &w, &h) < 2 || w <= 0 || h <= 0) FatalError("ERROR in %s: max-desktop-size value is incorrect.", rfbAuthConfigFile); if (w == 0) w = MAXSHORT; if (h == 0) h = MAXSHORT; rfbMaxWidth = (CARD32)w; rfbMaxHeight = (CARD32)h; continue; } if (buf2[0] != '#') rfbLog("WARNING: unrecognized security config line '%s'\n", buf); } fclose(fp); } void rfbAuthInit(void) { SecTypeData *s; int nSelected = 0; ReadConfigFile(); for (s = secTypes; s->name != NULL; s++) { if (s->enabled) { nSelected++; if (!s->permitted) { rfbLog("WARNING: security type '%s' is not permitted\n", s->name); s->enabled = FALSE; continue; } } if (s->enabled) { nSecTypesEnabled++; rfbLog("Enabled security type '%s'\n", s->name); if (!s->rfbSecType->advertise) { s->rfbSecType->advertise = TRUE; rfbLog("Advertising security type '%s' to viewers\n", s->rfbSecType->name); } } } if (nSelected == 0) { /* No security type was selected. See if we should enable the rfbAuthNone security type. */ for (s = secTypes; s->name != NULL; s++) { if (!s->requiredData) { if (s->permitted) { nSecTypesEnabled++; s->enabled = TRUE; s->rfbSecType->advertise = TRUE; rfbLog("Enabled security type '%s'\n", s->name); rfbLog("Advertising security type '%s' to viewers\n", s->rfbSecType->name); } } else { s->rfbSecType->advertise = FALSE; } } } #ifndef XVNC_AuthPAM if (rfbOptPamAuth()) rfbLog("WARNING: PAM support is not compiled in.\n"); #endif if (nSecTypesEnabled == 0) { for (s = secTypes; s->name != NULL; s++) { if (s->permitted) rfbLog("NOTICE: %s is a permitted security type\n", s->name); } FatalError("ERROR: no security types enabled!"); } else { /* Do not advertise rfbAuthNone if any other security type is enabled */ for (s = secTypes; s->name != NULL; s++) { if (s->enabled && strcmp(s->name, "none")) secTypeNone.advertise = FALSE; } } #ifdef XVNC_AuthPAM if (rfbOptPamAuth() && rfbAuthUserACL) { struct passwd pbuf; struct passwd *pw; char buf[256]; char *n; if (getpwuid_r(getuid(), &pbuf, buf, sizeof(buf), &pw) != 0) FatalError("AuthPAMUserPwdRspFunc: limit-user enabled and getpwuid_r failed: %s", strerror(errno)); n = (char *)rfbAlloc(strlen(pbuf.pw_name)); strcpy(n, pbuf.pw_name); rfbAuthAddUser(n, FALSE); } #endif } void rfbAuthProcessResponse(rfbClientPtr cl) { AuthCapData **p; AuthCapData *c; for (p = authCaps; *p != NULL; p++) { c = *p; if (cl->selectedAuthType == c->authType) { c->rspFunc(cl); return; } } rfbLog("rfbAuthProcessResponse: authType assertion failed\n"); rfbCloseClient(cl); } /* * rfbAuthNewClient is called right after negotiating the protocol version. * Depending on the protocol version, we send either a code for the * authentication scheme to be used (protocol 3.3) or a list of possible * "security types" (protocol 3.7 and above.) */ void rfbAuthNewClient(rfbClientPtr cl) { RFBSecTypeData **p; RFBSecTypeData *r; if (rfbAuthIsBlocked()) { rfbLog("Too many authentication failures - client rejected\n"); rfbClientConnFailed(cl, "Too many authentication failures"); return; } if (cl->protocol_minor_ver >= 7) { rfbSendSecurityTypeList(cl); return; } /* Make sure we use only RFB 3.3-compatible security types */ for (p = rfbSecTypes; *p != NULL; p++) { r = *p; if (r->advertise && (r->protocolMinorVer < 7)) break; } if (*p == NULL) { rfbLog("VNC authentication disabled - RFB 3.3 client rejected\n"); rfbClientConnFailed(cl, "Your viewer cannot handle required security types"); return; } cl->selectedAuthType = r->securityType; rfbSendSecurityType(cl, r->securityType); } /* * Tell the client which security type will be used (protocol 3.3) */ static void rfbSendSecurityType(rfbClientPtr cl, int securityType) { CARD32 value32; value32 = Swap32IfLE(securityType); if (WriteExact(cl, (char *)&value32, 4) < 0) { rfbLogPerror("rfbSendSecurityType: write"); rfbCloseClient(cl); return; } switch (securityType) { case rfbSecTypeNone: /* Dispatch client input to rfbProcessClientInitMessage() */ cl->state = RFB_INITIALISATION; break; case rfbSecTypeVncAuth: /* Begin the Standard VNC authentication procedure */ rfbVncAuthSendChallenge(cl); break; default: rfbLogPerror("rfbSendSecurityType: assertion failed"); rfbCloseClient(cl); } } /* * Advertise our supported security types (protocol 3.7 and above) */ static void rfbSendSecurityTypeList(rfbClientPtr cl) { int i, j, n; SecTypeData *s; RFBSecTypeData *r; Bool tightAdvertised = FALSE; /* * When no preference order was set using "permitted-security-types", the * default value of preferenceLimit (1) will cause us to execute the * outer loop once. In this case, the s->preference members will all * be the default value (-1), and we skip the order testing. */ n = 0; for (i = 0; i < preferenceLimit; i++) { for (s = secTypes; s->name != NULL; s++) { if (((s->preference != -1) && (i != s->preference)) || !s->enabled) continue; r = s->rfbSecType; if (n > MAX_SECURITY_TYPES) FatalError("rfbSendSecurityTypeList: # enabled security types > MAX_SECURITY_TYPES"); /* * Check whether we have already advertised this security type */ for (j = 0; j < n; j++) { if (cl->securityTypes[j + 1] == r->securityType) break; } if (j < n) continue; if (r->advertise && (cl->protocol_minor_ver >= r->protocolMinorVer)) { cl->securityTypes[++n] = r->securityType; if (r->securityType == rfbSecTypeTight) tightAdvertised = TRUE; } } } if (n == 0) FatalError("rfbSendSecurityTypeList: no security types enabled! This should not have happened!"); if (!tightAdvertised) { /* * Make sure to advertise the Tight security type, in order to allow * TightVNC-compatible clients to enable other (non-auth) Tight * extensions. */ if (n > MAX_SECURITY_TYPES) FatalError("rfbSendSecurityTypeList: # enabled security types > MAX_SECURITY_TYPES"); rfbLog("rfbSendSecurityTypeList: advertise sectype tight\n"); cl->securityTypes[++n] = rfbSecTypeTight; } cl->securityTypes[0] = (CARD8)n; /* Send the list */ if (WriteExact(cl, (char *)cl->securityTypes, n + 1) < 0) { rfbLogPerror("rfbSendSecurityTypeList: write"); rfbCloseClient(cl); return; } /* Dispatch client input to rfbProcessClientSecurityType() */ cl->state = RFB_SECURITY_TYPE; } #define WRITE(data, size) \ if (WriteExact(cl, (char *)data, size) <= 0) { \ rfbLogPerror("rfbVeNCryptAuthenticate: write"); \ rfbCloseClient(cl); \ return; \ } #define READ(data, size) \ if (ReadExact(cl, (char *)data, size) <= 0) { \ rfbLogPerror("rfbVeNCryptAuthenticate: read"); \ rfbCloseClient(cl); \ return; \ } #if USETLS #define TLS_INIT(anon) \ if ((ctx = rfbssl_init(cl, anon)) == NULL) { \ reply = 0; \ WRITE(&reply, 1); \ rfbClientAuthFailed(cl, rfbssl_geterr()); \ return; \ } \ reply = 1; \ WRITE(&reply, 1); \ cl->sslctx = ctx; \ if ((ret = rfbssl_accept(cl)) < 0) { \ rfbCloseClient(cl); \ return; \ } else if (ret == 1) { \ rfbLog("Deferring TLS handshake\n"); \ cl->state = RFB_TLS_HANDSHAKE; \ return; \ } void rfbAuthTLSHandshake(rfbClientPtr cl) { int ret; if ((ret = rfbssl_accept(cl)) < 0) { rfbCloseClient(cl); return; } else if (ret == 1) return; switch (cl->selectedAuthType) { case rfbAuthNone: rfbClientAuthSucceeded(cl, rfbAuthNone); break; case rfbAuthVNC: rfbVncAuthSendChallenge(cl); break; #ifdef XVNC_AuthPAM case rfbAuthUnixLogin: AuthPAMUserPwdRspFunc(cl); break; #endif } } #endif void rfbVeNCryptAuthenticate(rfbClientPtr cl) { struct { CARD8 major, minor; } serverVersion = { 0, 2 }, clientVersion = { 0, 0 }; CARD8 reply, count = 0; int i, j; SecTypeData *s; CARD32 subTypes[MAX_VENCRYPT_SUBTYPES], chosenType = 0; #if USETLS rfbSslCtx *ctx; int ret; #endif WRITE(&serverVersion.major, 1); WRITE(&serverVersion.minor, 1); rfbUncorkSock(cl->sock); rfbCorkSock(cl->sock); READ(&clientVersion, 2); if (clientVersion.major == 0 && clientVersion.minor < 2) { reply = 0xFF; WRITE(&reply, 1); rfbCloseClient(cl); return; } else { reply = 0; WRITE(&reply, 1); } memset(subTypes, 0, sizeof(CARD32) * MAX_VENCRYPT_SUBTYPES); for (i = 0; i < preferenceLimit; i++) { for (s = secTypes; s->name != NULL; s++) { if (((s->preference != -1) && (i != s->preference)) || !s->enabled || s->subType == -1) continue; if (count > MAX_VENCRYPT_SUBTYPES) FatalError("rfbVeNCryptAuthenticate: # enabled subtypes > MAX_VENCRYPT_SUBTYPES"); /* Check whether we have already advertised this subtype */ for (j = 0; j < count; j++) { if (subTypes[j] == s->subType) break; } if (j < count) continue; subTypes[count++] = s->subType; } } WRITE(&count, 1); if (count > 0) { for (i = 0; i < count; i++) { CARD32 subType = Swap32IfLE(subTypes[i]); WRITE(&subType, sizeof(CARD32)); } } rfbUncorkSock(cl->sock); rfbCorkSock(cl->sock); READ(&chosenType, sizeof(CARD32)); chosenType = Swap32IfLE(chosenType); for (i = 0; i < count; i++) { if (chosenType == subTypes[i]) break; } rfbLog("Client requested VeNCrypt sub-type %d\n", chosenType); if (chosenType == 0 || chosenType == rfbSecTypeVeNCrypt || i >= count) { rfbLog("Requested VeNCrypt sub-type not supported\n"); rfbCloseClient(cl); return; } cl->selectedAuthType = chosenType; switch (chosenType) { case rfbAuthNone: rfbClientAuthSucceeded(cl, rfbAuthNone); break; case rfbAuthVNC: rfbVncAuthSendChallenge(cl); break; #ifdef XVNC_AuthPAM case rfbVeNCryptPlain: AuthPAMUserPwdRspFunc(cl); break; #endif #if USETLS case rfbVeNCryptTLSNone: cl->selectedAuthType = rfbAuthNone; TLS_INIT(TRUE); rfbClientAuthSucceeded(cl, rfbAuthNone); break; case rfbVeNCryptTLSVnc: cl->selectedAuthType = rfbAuthVNC; TLS_INIT(TRUE); rfbVncAuthSendChallenge(cl); break; #ifdef XVNC_AuthPAM case rfbVeNCryptTLSPlain: cl->selectedAuthType = rfbAuthUnixLogin; TLS_INIT(TRUE); AuthPAMUserPwdRspFunc(cl); break; #endif case rfbVeNCryptX509None: cl->selectedAuthType = rfbAuthNone; TLS_INIT(FALSE); rfbClientAuthSucceeded(cl, rfbAuthNone); break; case rfbVeNCryptX509Vnc: cl->selectedAuthType = rfbAuthVNC; TLS_INIT(FALSE); rfbVncAuthSendChallenge(cl); break; #ifdef XVNC_AuthPAM case rfbVeNCryptX509Plain: cl->selectedAuthType = rfbAuthUnixLogin; TLS_INIT(FALSE); AuthPAMUserPwdRspFunc(cl); break; #endif #endif default: FatalError("rfbVeNCryptAuthenticate: chosen type is invalid (this should never occur)"); } } /* * Read the security type chosen by the client (protocol 3.7 and above) */ void rfbProcessClientSecurityType(rfbClientPtr cl) { int n, count, i; CARD8 chosenType; /* Read the security type */ n = ReadExact(cl, (char *)&chosenType, 1); if (n <= 0) { if (n == 0) rfbLog("rfbProcessClientSecurityType: client gone\n"); else rfbLogPerror("rfbProcessClientSecurityType: read"); rfbCloseClient(cl); return; } /* Make sure it was present in the list sent by the server */ count = (int)cl->securityTypes[0]; for (i = 1; i <= count; i++) { if (chosenType == cl->securityTypes[i]) break; } if (i > count) { rfbLog("rfbProcessClientSecurityType: wrong security type requested\n"); rfbCloseClient(cl); return; } cl->selectedAuthType = chosenType; switch (chosenType) { case rfbSecTypeNone: /* No authentication needed */ rfbClientAuthSucceeded(cl, rfbAuthNone); break; case rfbSecTypeVncAuth: /* Begin the Standard VNC authentication procedure */ rfbVncAuthSendChallenge(cl); break; case rfbSecTypeTight: /* The viewer supports TightVNC extensions */ rfbLog("Enabling TightVNC protocol extensions\n"); /* Switch to protocol 3.7t/3.8t */ cl->protocol_tightvnc = TRUE; /* Advertise our tunneling capabilities */ rfbSendTunnelingCaps(cl); break; case rfbSecTypeVeNCrypt: /* The viewer supports VeNCrypt extensions */ rfbLog("Enabling VeNCrypt protocol extensions\n"); rfbVeNCryptAuthenticate(cl); break; default: rfbLog("rfbProcessClientSecurityType: unknown authentication scheme\n"); rfbCloseClient(cl); break; } } /* * Send the list of our tunneling capabilities (protocol 3.7t/3.8t) */ static void rfbSendTunnelingCaps(rfbClientPtr cl) { rfbTunnelingCapsMsg caps; CARD32 nTypes = 0; /* We don't support tunneling yet */ caps.nTunnelTypes = Swap32IfLE(nTypes); if (WriteExact(cl, (char *)&caps, sz_rfbTunnelingCapsMsg) < 0) { rfbLogPerror("rfbSendTunnelingCaps: write"); rfbCloseClient(cl); return; } if (nTypes) /* Dispatch client input to rfbProcessClientTunnelingType() */ cl->state = RFB_TUNNELING_TYPE; else rfbSendAuthCaps(cl); } /* * Read tunneling type requested by the client (protocol 3.7t/3.8t) * * NOTE: Currently we don't support tunneling, and this function can never be * called. */ void rfbProcessClientTunnelingType(rfbClientPtr cl) { /* If we were called, then something's really wrong. */ rfbLog("rfbProcessClientTunnelingType: not implemented\n"); rfbCloseClient(cl); } /* * Send the list of our authentication capabilities to the client * (protocol 3.7t/3.8t) */ static void rfbSendAuthCaps(rfbClientPtr cl) { rfbAuthenticationCapsMsg caps; rfbCapabilityInfo caplist[MAX_AUTH_CAPS]; int count = 0; int j; SecTypeData *s; AuthCapData *c; rfbCapabilityInfo *pcap; char tempstr[9]; if (!cl->reverseConnection) { int i; /* * When no preference order was set using "permitted-security-types", * the default value of preferenceLimit (1) will cause us to execute * the outer loop once. In this case, the s->preference members will * all be the default value (-1), and we skip the order testing. */ for (i = 0; i < preferenceLimit; i++) { for (s = secTypes; s->name != NULL; s++) { if (((s->preference != -1) && (i != s->preference)) || !s->enabled) continue; c = s->authCap; if (count > MAX_AUTH_CAPS) FatalError("rfbSendAuthCaps: # enabled security types > MAX_AUTH_CAPS"); /* * Check to see if we have already advertised this auth cap. * VNC password and OTP both use the VNC authentication cap. */ for (j = 0; j < count; j++) { if (cl->authCaps[j] == c->authType) break; } if (j < count) continue; pcap = &caplist[count]; pcap->code = Swap32IfLE(c->authType); memcpy(pcap->vendorSignature, c->vendorSignature, sz_rfbCapabilityInfoVendor); memcpy(pcap->nameSignature, c->nameSignature, sz_rfbCapabilityInfoName); cl->authCaps[count] = c->authType; strncpy(tempstr, (char *)pcap->nameSignature, 8); tempstr[8] = 0; rfbLog("Advertising Tight auth cap '%s'\n", tempstr); count++; } } if (count == 0) FatalError("rfbSendAuthCaps: authentication required but no security types enabled! This should not have happened!"); } cl->nAuthCaps = count; caps.nAuthTypes = Swap32IfLE((CARD32)count); if (WriteExact(cl, (char *)&caps, sz_rfbAuthenticationCapsMsg) < 0) { rfbLogPerror("rfbSendAuthCaps: write"); rfbCloseClient(cl); return; } if (count) { if (WriteExact(cl, (char *)&caplist[0], count *sz_rfbCapabilityInfo) < 0) { rfbLogPerror("rfbSendAuthCaps: write"); rfbCloseClient(cl); return; } /* Dispatch client input to rfbProcessClientAuthType() */ cl->state = RFB_AUTH_TYPE; } else { /* No authentication needed */ rfbClientAuthSucceeded(cl, rfbAuthNone); cl->state = RFB_INITIALISATION; } } /* * Read client's preferred authentication type (protocol 3.7t/3.8t) */ void rfbProcessClientAuthType(rfbClientPtr cl) { CARD32 auth_type; int n, i; AuthCapData **p; AuthCapData *c; /* Read authentication type selected by the client */ n = ReadExact(cl, (char *)&auth_type, sizeof(auth_type)); if (n <= 0) { if (n == 0) rfbLog("rfbProcessClientAuthType: client gone\n"); else rfbLogPerror("rfbProcessClientAuthType: read"); rfbCloseClient(cl); return; } auth_type = Swap32IfLE(auth_type); /* Make sure it was present in the list sent by the server */ for (i = 0; i < cl->nAuthCaps; i++) { if (auth_type == cl->authCaps[i]) break; } if (i >= cl->nAuthCaps) { rfbLog("rfbProcessClientAuthType: wrong authentication type requested\n"); rfbCloseClient(cl); return; } for (p = authCaps; *p != NULL; p++) { c = *p; if (auth_type == c->authType) { cl->selectedAuthType = auth_type; c->startFunc(cl); return; } } rfbLog("rfbProcessClientAuthType: unknown authentication scheme\n"); rfbCloseClient(cl); } /* * Send the authentication challenge */ static void rfbVncAuthSendChallenge(rfbClientPtr cl) { vncRandomBytes(cl->authChallenge); if (WriteExact(cl, (char *)cl->authChallenge, CHALLENGESIZE) < 0) { rfbLogPerror("rfbVncAuthSendChallenge: write"); rfbCloseClient(cl); return; } /* Dispatch client input to rfbVncAuthProcessResponse() */ cl->state = RFB_AUTHENTICATION; } static Bool CheckResponse(rfbClientPtr cl, int numPasswords, char *passwdFullControl, char *passwdViewOnly, CARD8 *response) { Bool ok = FALSE; CARD8 encryptedChallenge1[CHALLENGESIZE]; CARD8 encryptedChallenge2[CHALLENGESIZE]; memcpy(encryptedChallenge1, cl->authChallenge, CHALLENGESIZE); vncEncryptBytes(encryptedChallenge1, passwdFullControl); memcpy(encryptedChallenge2, cl->authChallenge, CHALLENGESIZE); vncEncryptBytes(encryptedChallenge2, (numPasswords == 2) ? passwdViewOnly : passwdFullControl); /* Delete the passwords from memory */ memset(passwdFullControl, 0, MAXPWLEN + 1); memset(passwdViewOnly, 0, MAXPWLEN + 1); if (memcmp(encryptedChallenge1, response, CHALLENGESIZE) == 0) { rfbLog("Full-control authentication enabled for %s\n", cl->host); ok = TRUE; cl->viewOnly = FALSE; } else if (memcmp(encryptedChallenge2, response, CHALLENGESIZE) == 0) { rfbLog("View-only authentication enabled for %s\n", cl->host); ok = TRUE; cl->viewOnly = TRUE; } return ok; } /* * rfbVncAuthProcessResponse is called when the client sends its * authentication response. */ void rfbVncAuthProcessResponse(rfbClientPtr cl) { char passwdFullControl[MAXPWLEN + 1] = "\0"; char passwdViewOnly[MAXPWLEN + 1] = "\0"; int numPasswords; Bool ok; int n; CARD8 response[CHALLENGESIZE]; n = ReadExact(cl, (char *)response, CHALLENGESIZE); if (n <= 0) { if (n != 0) rfbLogPerror("rfbVncAuthProcessResponse: read"); rfbCloseClient(cl); return; } ok = FALSE; if (rfbOptOtpAuth()) { if (rfbAuthOTPValue == NULL) { if (nSecTypesEnabled == 1) { rfbClientAuthFailed(cl, "The one-time password has not been set on the server"); return; } } else { memcpy(passwdFullControl, rfbAuthOTPValue, MAXPWLEN); passwdFullControl[MAXPWLEN] = '\0'; numPasswords = rfbAuthOTPValueLen / MAXPWLEN; if (numPasswords > 1) { memcpy(passwdViewOnly, rfbAuthOTPValue + MAXPWLEN, MAXPWLEN); passwdViewOnly[MAXPWLEN] = '\0'; } ok = CheckResponse(cl, numPasswords, passwdFullControl, passwdViewOnly, response); if (ok) { memset(rfbAuthOTPValue, 0, rfbAuthOTPValueLen); free(rfbAuthOTPValue); rfbAuthOTPValue = NULL; } } } if ((ok == FALSE) && rfbOptRfbAuth()) { if (!rfbAuthPasswdFile) { rfbClientAuthFailed(cl, "No VNC password file specified on the server (did you forget -rfbauth?)"); return; } numPasswords = vncDecryptPasswdFromFile2(rfbAuthPasswdFile, passwdFullControl, passwdViewOnly); if (numPasswords == 0) { rfbLog("rfbVncAuthProcessResponse: could not get password from %s\n", rfbAuthPasswdFile); if (nSecTypesEnabled == 1) { rfbClientAuthFailed(cl, "The server could not read the VNC password file"); return; } } ok = CheckResponse(cl, numPasswords, passwdFullControl, passwdViewOnly, response); } if (ok) { rfbAuthUnblock(); rfbClientAuthSucceeded(cl, rfbAuthVNC); } else { rfbLog("rfbVncAuthProcessResponse: authentication failed from %s\n", cl->host); if (rfbAuthConsiderBlocking()) rfbClientAuthFailed(cl, "Authentication failed. Too many tries"); else rfbClientAuthFailed(cl, "Authentication failed"); } } /* * rfbClientConnFailed is called when a client connection has failed before * the authentication stage. */ void rfbClientConnFailed(rfbClientPtr cl, char *reason) { int headerLen, reasonLen; char buf[8]; CARD32 *buf32 = (CARD32 *)buf; headerLen = (cl->protocol_minor_ver >= 7) ? 1 : 4; reasonLen = strlen(reason); buf32[0] = 0; buf32[1] = Swap32IfLE(reasonLen); if (WriteExact(cl, buf, headerLen) < 0 || WriteExact(cl, buf + 4, 4) < 0 || WriteExact(cl, reason, reasonLen) < 0) rfbLogPerror("rfbClientConnFailed: write"); rfbCloseClient(cl); } /* * rfbClientAuthFailed is called on authentication failure. Sending a reason * string is defined in RFB 3.8 and above. */ void rfbClientAuthFailed(rfbClientPtr cl, char *reason) { int reasonLen; char buf[8]; CARD32 *buf32 = (CARD32 *)buf; if (cl->protocol_minor_ver < 8) reason = NULL; /* invalidate the pointer */ reasonLen = (reason == NULL) ? 0 : strlen(reason); buf32[0] = Swap32IfLE(rfbAuthFailed); buf32[1] = Swap32IfLE(reasonLen); if (reasonLen == 0) { if (WriteExact(cl, buf, 4) < 0) rfbLogPerror("rfbClientAuthFailed: write"); } else { if (WriteExact(cl, buf, 8) < 0 || WriteExact(cl, reason, reasonLen) < 0) rfbLogPerror("rfbClientAuthFailed: write"); } rfbCloseClient(cl); } /* * rfbClientAuthSucceeded is called on successful authentication. It just * sends rfbAuthOK and dispatches client input to * rfbProcessClientInitMessage(). However, the rfbAuthOK message is not sent * if authentication was not required and the protocol version is 3.7 or lower. */ void rfbClientAuthSucceeded(rfbClientPtr cl, CARD32 authType) { CARD32 authResult; if (cl->protocol_minor_ver >= 8 || authType == rfbAuthVNC) { authResult = Swap32IfLE(rfbAuthOK); if (WriteExact(cl, (char *)&authResult, 4) < 0) { rfbLogPerror("rfbClientAuthSucceeded: write"); rfbCloseClient(cl); return; } } /* Dispatch client input to rfbProcessClientInitMessage() */ cl->state = RFB_INITIALISATION; } /********************************************************************* * Functions to prevent too many successive authentication failures. * * FIXME: This should be performed separately for each client. */ /* Maximum authentication failures before blocking connections */ #define MAX_AUTH_TRIES 5 /* Delay in ms. This doubles for each failure over MAX_AUTH_TRIES. */ #define AUTH_TOO_MANY_BASE_DELAY 10 * 1000 static int rfbAuthTries = 0; static Bool rfbAuthTooManyTries = FALSE; static OsTimerPtr timer = NULL; /* * This function should not be called directly. It is called by setting a * timer in rfbAuthConsiderBlocking(). */ static CARD32 rfbAuthReenable(OsTimerPtr timer, CARD32 now, pointer arg) { rfbAuthTooManyTries = FALSE; return 0; } /* * This function should be called after each authentication failure. The * return value will be true if there were too many failures. */ Bool rfbAuthConsiderBlocking(void) { int i; rfbAuthTries++; if (rfbAuthTries >= MAX_AUTH_TRIES) { CARD32 delay = AUTH_TOO_MANY_BASE_DELAY; for (i = MAX_AUTH_TRIES; i < rfbAuthTries; i++) delay *= 2; timer = TimerSet(timer, 0, delay, rfbAuthReenable, NULL); rfbAuthTooManyTries = TRUE; return TRUE; } return FALSE; } /* * This function should be called after a successful authentication. It * resets the counter of authentication failures. Note that it's not necessary * to clear the rfbAuthTooManyTries flag, as it will be reset by the timer * function. */ void rfbAuthUnblock(void) { rfbAuthTries = 0; } /* * This function should be called before authentication. The return value will * be true if there were too many authentication failures, and the server * should not allow another try. */ Bool rfbAuthIsBlocked(void) { return rfbAuthTooManyTries; }
null
138
CWE-787
CVE-2019-15692
/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved. * Copyright 2014 Pierre Ossman for Cendio AB * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ // -=- PixelBuffer.cxx // // The PixelBuffer class encapsulates the PixelFormat and dimensions // of a block of pixel data. #include <rfb/Exception.h> #include <rfb/LogWriter.h> #include <rfb/PixelBuffer.h> using namespace rfb; using namespace rdr; static LogWriter vlog("PixelBuffer"); // -=- Generic pixel buffer class PixelBuffer::PixelBuffer(const PixelFormat& pf, int w, int h) : format(pf), width_(0), height_(0) { setSize(w, h); } PixelBuffer::PixelBuffer() : width_(0), height_(0) { } PixelBuffer::~PixelBuffer() {} void PixelBuffer::getImage(void* imageBuf, const Rect& r, int outStride) const { int inStride; const U8* data; int bytesPerPixel, inBytesPerRow, outBytesPerRow, bytesPerMemCpy; U8* imageBufPos; const U8* end; if (!r.enclosed_by(getRect())) throw rfb::Exception("Source rect %dx%d at %d,%d exceeds framebuffer %dx%d", r.width(), r.height(), r.tl.x, r.tl.y, width(), height()); data = getBuffer(r, &inStride); bytesPerPixel = format.bpp/8; inBytesPerRow = inStride * bytesPerPixel; if (!outStride) outStride = r.width(); outBytesPerRow = outStride * bytesPerPixel; bytesPerMemCpy = r.width() * bytesPerPixel; imageBufPos = (U8*)imageBuf; end = data + (inBytesPerRow * r.height()); while (data < end) { memcpy(imageBufPos, data, bytesPerMemCpy); imageBufPos += outBytesPerRow; data += inBytesPerRow; } } void PixelBuffer::getImage(const PixelFormat& pf, void* imageBuf, const Rect& r, int stride) const { const rdr::U8* srcBuffer; int srcStride; if (format.equal(pf)) { getImage(imageBuf, r, stride); return; } if (!r.enclosed_by(getRect())) throw rfb::Exception("Source rect %dx%d at %d,%d exceeds framebuffer %dx%d", r.width(), r.height(), r.tl.x, r.tl.y, width(), height()); if (stride == 0) stride = r.width(); srcBuffer = getBuffer(r, &srcStride); pf.bufferFromBuffer((U8*)imageBuf, format, srcBuffer, r.width(), r.height(), stride, srcStride); } void PixelBuffer::setSize(int width, int height) { width_ = width; height_ = height; } // -=- Modifiable generic pixel buffer class ModifiablePixelBuffer::ModifiablePixelBuffer(const PixelFormat& pf, int w, int h) : PixelBuffer(pf, w, h) { } ModifiablePixelBuffer::ModifiablePixelBuffer() { } ModifiablePixelBuffer::~ModifiablePixelBuffer() { } void ModifiablePixelBuffer::fillRect(const Rect& r, const void* pix) { int stride; U8 *buf; int w, h, b; if (!r.enclosed_by(getRect())) throw rfb::Exception("Destination rect %dx%d at %d,%d exceeds framebuffer %dx%d", r.width(), r.height(), r.tl.x, r.tl.y, width(), height()); w = r.width(); h = r.height(); b = format.bpp/8; if (h == 0) return; buf = getBufferRW(r, &stride); if (b == 1) { while (h--) { memset(buf, *(const U8*)pix, w); buf += stride * b; } } else { U8 *start; int w1; start = buf; w1 = w; while (w1--) { memcpy(buf, pix, b); buf += b; } buf += (stride - w) * b; h--; while (h--) { memcpy(buf, start, w * b); buf += stride * b; } } commitBufferRW(r); } void ModifiablePixelBuffer::imageRect(const Rect& r, const void* pixels, int srcStride) { U8* dest; int destStride; int bytesPerPixel, bytesPerDestRow, bytesPerSrcRow, bytesPerFill; const U8* src; U8* end; if (!r.enclosed_by(getRect())) throw rfb::Exception("Destination rect %dx%d at %d,%d exceeds framebuffer %dx%d", r.width(), r.height(), r.tl.x, r.tl.y, width(), height()); bytesPerPixel = getPF().bpp/8; dest = getBufferRW(r, &destStride); bytesPerDestRow = bytesPerPixel * destStride; if (!srcStride) srcStride = r.width(); bytesPerSrcRow = bytesPerPixel * srcStride; bytesPerFill = bytesPerPixel * r.width(); src = (const U8*)pixels; end = dest + (bytesPerDestRow * r.height()); while (dest < end) { memcpy(dest, src, bytesPerFill); dest += bytesPerDestRow; src += bytesPerSrcRow; } commitBufferRW(r); } void ModifiablePixelBuffer::copyRect(const Rect &rect, const Point &move_by_delta) { int srcStride, dstStride; int bytesPerPixel; const U8* srcData; U8* dstData; Rect drect, srect; drect = rect; if (!drect.enclosed_by(getRect())) throw rfb::Exception("Destination rect %dx%d at %d,%d exceeds framebuffer %dx%d", drect.width(), drect.height(), drect.tl.x, drect.tl.y, width(), height()); srect = drect.translate(move_by_delta.negate()); if (!srect.enclosed_by(getRect())) throw rfb::Exception("Source rect %dx%d at %d,%d exceeds framebuffer %dx%d", srect.width(), srect.height(), srect.tl.x, srect.tl.y, width(), height()); bytesPerPixel = format.bpp/8; srcData = getBuffer(srect, &srcStride); dstData = getBufferRW(drect, &dstStride); if (move_by_delta.y == 0) { // Possible overlap. Be careful and use memmove(). int h = drect.height(); while (h--) { memmove(dstData, srcData, drect.width() * bytesPerPixel); dstData += dstStride * bytesPerPixel; srcData += srcStride * bytesPerPixel; } } else if (move_by_delta.y < 0) { // The data shifted upwards. Copy from top to bottom. int h = drect.height(); while (h--) { memcpy(dstData, srcData, drect.width() * bytesPerPixel); dstData += dstStride * bytesPerPixel; srcData += srcStride * bytesPerPixel; } } else { // The data shifted downwards. Copy from bottom to top. int h = drect.height(); dstData += (h-1) * dstStride * bytesPerPixel; srcData += (h-1) * srcStride * bytesPerPixel; while (h--) { memcpy(dstData, srcData, drect.width() * bytesPerPixel); dstData -= dstStride * bytesPerPixel; srcData -= srcStride * bytesPerPixel; } } commitBufferRW(drect); } void ModifiablePixelBuffer::fillRect(const PixelFormat& pf, const Rect &dest, const void* pix) { rdr::U8 buf[4]; format.bufferFromBuffer(buf, pf, (const rdr::U8*)pix, 1); fillRect(dest, buf); } void ModifiablePixelBuffer::imageRect(const PixelFormat& pf, const Rect &dest, const void* pixels, int stride) { rdr::U8* dstBuffer; int dstStride; if (!dest.enclosed_by(getRect())) throw rfb::Exception("Destination rect %dx%d at %d,%d exceeds framebuffer %dx%d", dest.width(), dest.height(), dest.tl.x, dest.tl.y, width(), height()); if (stride == 0) stride = dest.width(); dstBuffer = getBufferRW(dest, &dstStride); format.bufferFromBuffer(dstBuffer, pf, (const rdr::U8*)pixels, dest.width(), dest.height(), dstStride, stride); commitBufferRW(dest); } // -=- Simple pixel buffer with a continuous block of memory FullFramePixelBuffer::FullFramePixelBuffer(const PixelFormat& pf, int w, int h, rdr::U8* data_, int stride_) : ModifiablePixelBuffer(pf, w, h), data(data_), stride(stride_) { } FullFramePixelBuffer::FullFramePixelBuffer() : data(0) {} FullFramePixelBuffer::~FullFramePixelBuffer() {} rdr::U8* FullFramePixelBuffer::getBufferRW(const Rect& r, int* stride_) { if (!r.enclosed_by(getRect())) throw rfb::Exception("Pixel buffer request %dx%d at %d,%d exceeds framebuffer %dx%d", r.width(), r.height(), r.tl.x, r.tl.y, width(), height()); *stride_ = stride; return &data[(r.tl.x + (r.tl.y * stride)) * (format.bpp/8)]; } void FullFramePixelBuffer::commitBufferRW(const Rect& r) { } const rdr::U8* FullFramePixelBuffer::getBuffer(const Rect& r, int* stride_) const { if (!r.enclosed_by(getRect())) throw rfb::Exception("Pixel buffer request %dx%d at %d,%d exceeds framebuffer %dx%d", r.width(), r.height(), r.tl.x, r.tl.y, width(), height()); *stride_ = stride; return &data[(r.tl.x + (r.tl.y * stride)) * (format.bpp/8)]; } void FullFramePixelBuffer::setBuffer(int width, int height, rdr::U8* data_, int stride_) { ModifiablePixelBuffer::setSize(width, height); stride = stride_; data = data_; } void FullFramePixelBuffer::setSize(int w, int h) { // setBuffer() should be used throw rfb::Exception("Invalid call to FullFramePixelBuffer::setSize()"); } // -=- Managed pixel buffer class // Automatically allocates enough space for the specified format & area ManagedPixelBuffer::ManagedPixelBuffer() : data_(NULL), datasize(0) { } ManagedPixelBuffer::ManagedPixelBuffer(const PixelFormat& pf, int w, int h) : FullFramePixelBuffer(pf, 0, 0, NULL, 0), data_(NULL), datasize(0) { setSize(w, h); } ManagedPixelBuffer::~ManagedPixelBuffer() { if (data_) delete [] data_; } void ManagedPixelBuffer::setPF(const PixelFormat &pf) { format = pf; setSize(width(), height()); } void ManagedPixelBuffer::setSize(int w, int h) { unsigned long new_datasize = w * h * (format.bpp/8); new_datasize = w * h * (format.bpp/8); if (datasize < new_datasize) { if (data_) { delete [] data_; data_ = NULL; datasize = 0; } if (new_datasize) { data_ = new U8[new_datasize]; datasize = new_datasize; } } setBuffer(w, h, data_, w); }
null
/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved. * Copyright 2014 Pierre Ossman for Cendio AB * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ // -=- PixelBuffer.cxx // // The PixelBuffer class encapsulates the PixelFormat and dimensions // of a block of pixel data. #include <rfb/Exception.h> #include <rfb/LogWriter.h> #include <rfb/PixelBuffer.h> using namespace rfb; using namespace rdr; static LogWriter vlog("PixelBuffer"); // We do a lot of byte offset calculations that assume the result fits // inside a signed 32 bit integer. Limit the maximum size of pixel // buffers so that these calculations never overflow. const int maxPixelBufferWidth = 16384; const int maxPixelBufferHeight = 16384; const int maxPixelBufferStride = 16384; // -=- Generic pixel buffer class PixelBuffer::PixelBuffer(const PixelFormat& pf, int w, int h) : format(pf), width_(0), height_(0) { setSize(w, h); } PixelBuffer::PixelBuffer() : width_(0), height_(0) { } PixelBuffer::~PixelBuffer() {} void PixelBuffer::getImage(void* imageBuf, const Rect& r, int outStride) const { int inStride; const U8* data; int bytesPerPixel, inBytesPerRow, outBytesPerRow, bytesPerMemCpy; U8* imageBufPos; const U8* end; if (!r.enclosed_by(getRect())) throw rfb::Exception("Source rect %dx%d at %d,%d exceeds framebuffer %dx%d", r.width(), r.height(), r.tl.x, r.tl.y, width(), height()); data = getBuffer(r, &inStride); bytesPerPixel = format.bpp/8; inBytesPerRow = inStride * bytesPerPixel; if (!outStride) outStride = r.width(); outBytesPerRow = outStride * bytesPerPixel; bytesPerMemCpy = r.width() * bytesPerPixel; imageBufPos = (U8*)imageBuf; end = data + (inBytesPerRow * r.height()); while (data < end) { memcpy(imageBufPos, data, bytesPerMemCpy); imageBufPos += outBytesPerRow; data += inBytesPerRow; } } void PixelBuffer::getImage(const PixelFormat& pf, void* imageBuf, const Rect& r, int stride) const { const rdr::U8* srcBuffer; int srcStride; if (format.equal(pf)) { getImage(imageBuf, r, stride); return; } if (!r.enclosed_by(getRect())) throw rfb::Exception("Source rect %dx%d at %d,%d exceeds framebuffer %dx%d", r.width(), r.height(), r.tl.x, r.tl.y, width(), height()); if (stride == 0) stride = r.width(); srcBuffer = getBuffer(r, &srcStride); pf.bufferFromBuffer((U8*)imageBuf, format, srcBuffer, r.width(), r.height(), stride, srcStride); } void PixelBuffer::setSize(int width, int height) { if ((width < 0) || (width > maxPixelBufferWidth)) throw rfb::Exception("Invalid PixelBuffer width of %d pixels requested", width); if ((height < 0) || (height > maxPixelBufferHeight)) throw rfb::Exception("Invalid PixelBuffer height of %d pixels requested", height); width_ = width; height_ = height; } // -=- Modifiable generic pixel buffer class ModifiablePixelBuffer::ModifiablePixelBuffer(const PixelFormat& pf, int w, int h) : PixelBuffer(pf, w, h) { } ModifiablePixelBuffer::ModifiablePixelBuffer() { } ModifiablePixelBuffer::~ModifiablePixelBuffer() { } void ModifiablePixelBuffer::fillRect(const Rect& r, const void* pix) { int stride; U8 *buf; int w, h, b; if (!r.enclosed_by(getRect())) throw rfb::Exception("Destination rect %dx%d at %d,%d exceeds framebuffer %dx%d", r.width(), r.height(), r.tl.x, r.tl.y, width(), height()); w = r.width(); h = r.height(); b = format.bpp/8; if (h == 0) return; buf = getBufferRW(r, &stride); if (b == 1) { while (h--) { memset(buf, *(const U8*)pix, w); buf += stride * b; } } else { U8 *start; int w1; start = buf; w1 = w; while (w1--) { memcpy(buf, pix, b); buf += b; } buf += (stride - w) * b; h--; while (h--) { memcpy(buf, start, w * b); buf += stride * b; } } commitBufferRW(r); } void ModifiablePixelBuffer::imageRect(const Rect& r, const void* pixels, int srcStride) { U8* dest; int destStride; int bytesPerPixel, bytesPerDestRow, bytesPerSrcRow, bytesPerFill; const U8* src; U8* end; if (!r.enclosed_by(getRect())) throw rfb::Exception("Destination rect %dx%d at %d,%d exceeds framebuffer %dx%d", r.width(), r.height(), r.tl.x, r.tl.y, width(), height()); bytesPerPixel = getPF().bpp/8; dest = getBufferRW(r, &destStride); bytesPerDestRow = bytesPerPixel * destStride; if (!srcStride) srcStride = r.width(); bytesPerSrcRow = bytesPerPixel * srcStride; bytesPerFill = bytesPerPixel * r.width(); src = (const U8*)pixels; end = dest + (bytesPerDestRow * r.height()); while (dest < end) { memcpy(dest, src, bytesPerFill); dest += bytesPerDestRow; src += bytesPerSrcRow; } commitBufferRW(r); } void ModifiablePixelBuffer::copyRect(const Rect &rect, const Point &move_by_delta) { int srcStride, dstStride; int bytesPerPixel; const U8* srcData; U8* dstData; Rect drect, srect; drect = rect; if (!drect.enclosed_by(getRect())) throw rfb::Exception("Destination rect %dx%d at %d,%d exceeds framebuffer %dx%d", drect.width(), drect.height(), drect.tl.x, drect.tl.y, width(), height()); srect = drect.translate(move_by_delta.negate()); if (!srect.enclosed_by(getRect())) throw rfb::Exception("Source rect %dx%d at %d,%d exceeds framebuffer %dx%d", srect.width(), srect.height(), srect.tl.x, srect.tl.y, width(), height()); bytesPerPixel = format.bpp/8; srcData = getBuffer(srect, &srcStride); dstData = getBufferRW(drect, &dstStride); if (move_by_delta.y == 0) { // Possible overlap. Be careful and use memmove(). int h = drect.height(); while (h--) { memmove(dstData, srcData, drect.width() * bytesPerPixel); dstData += dstStride * bytesPerPixel; srcData += srcStride * bytesPerPixel; } } else if (move_by_delta.y < 0) { // The data shifted upwards. Copy from top to bottom. int h = drect.height(); while (h--) { memcpy(dstData, srcData, drect.width() * bytesPerPixel); dstData += dstStride * bytesPerPixel; srcData += srcStride * bytesPerPixel; } } else { // The data shifted downwards. Copy from bottom to top. int h = drect.height(); dstData += (h-1) * dstStride * bytesPerPixel; srcData += (h-1) * srcStride * bytesPerPixel; while (h--) { memcpy(dstData, srcData, drect.width() * bytesPerPixel); dstData -= dstStride * bytesPerPixel; srcData -= srcStride * bytesPerPixel; } } commitBufferRW(drect); } void ModifiablePixelBuffer::fillRect(const PixelFormat& pf, const Rect &dest, const void* pix) { rdr::U8 buf[4]; format.bufferFromBuffer(buf, pf, (const rdr::U8*)pix, 1); fillRect(dest, buf); } void ModifiablePixelBuffer::imageRect(const PixelFormat& pf, const Rect &dest, const void* pixels, int stride) { rdr::U8* dstBuffer; int dstStride; if (!dest.enclosed_by(getRect())) throw rfb::Exception("Destination rect %dx%d at %d,%d exceeds framebuffer %dx%d", dest.width(), dest.height(), dest.tl.x, dest.tl.y, width(), height()); if (stride == 0) stride = dest.width(); dstBuffer = getBufferRW(dest, &dstStride); format.bufferFromBuffer(dstBuffer, pf, (const rdr::U8*)pixels, dest.width(), dest.height(), dstStride, stride); commitBufferRW(dest); } // -=- Simple pixel buffer with a continuous block of memory FullFramePixelBuffer::FullFramePixelBuffer(const PixelFormat& pf, int w, int h, rdr::U8* data_, int stride_) : ModifiablePixelBuffer(pf, w, h), data(data_), stride(stride_) { } FullFramePixelBuffer::FullFramePixelBuffer() : data(0) {} FullFramePixelBuffer::~FullFramePixelBuffer() {} rdr::U8* FullFramePixelBuffer::getBufferRW(const Rect& r, int* stride_) { if (!r.enclosed_by(getRect())) throw rfb::Exception("Pixel buffer request %dx%d at %d,%d exceeds framebuffer %dx%d", r.width(), r.height(), r.tl.x, r.tl.y, width(), height()); *stride_ = stride; return &data[(r.tl.x + (r.tl.y * stride)) * (format.bpp/8)]; } void FullFramePixelBuffer::commitBufferRW(const Rect& r) { } const rdr::U8* FullFramePixelBuffer::getBuffer(const Rect& r, int* stride_) const { if (!r.enclosed_by(getRect())) throw rfb::Exception("Pixel buffer request %dx%d at %d,%d exceeds framebuffer %dx%d", r.width(), r.height(), r.tl.x, r.tl.y, width(), height()); *stride_ = stride; return &data[(r.tl.x + (r.tl.y * stride)) * (format.bpp/8)]; } void FullFramePixelBuffer::setBuffer(int width, int height, rdr::U8* data_, int stride_) { if ((width < 0) || (width > maxPixelBufferWidth)) throw rfb::Exception("Invalid PixelBuffer width of %d pixels requested", width); if ((height < 0) || (height > maxPixelBufferHeight)) throw rfb::Exception("Invalid PixelBuffer height of %d pixels requested", height); if ((stride_ < 0) || (stride_ > maxPixelBufferStride) || (stride_ < width)) throw rfb::Exception("Invalid PixelBuffer stride of %d pixels requested", stride_); if ((width != 0) && (height != 0) && (data_ == NULL)) throw rfb::Exception("PixelBuffer requested without a valid memory area"); ModifiablePixelBuffer::setSize(width, height); stride = stride_; data = data_; } void FullFramePixelBuffer::setSize(int w, int h) { // setBuffer() should be used throw rfb::Exception("Invalid call to FullFramePixelBuffer::setSize()"); } // -=- Managed pixel buffer class // Automatically allocates enough space for the specified format & area ManagedPixelBuffer::ManagedPixelBuffer() : data_(NULL), datasize(0) { } ManagedPixelBuffer::ManagedPixelBuffer(const PixelFormat& pf, int w, int h) : FullFramePixelBuffer(pf, 0, 0, NULL, 0), data_(NULL), datasize(0) { setSize(w, h); } ManagedPixelBuffer::~ManagedPixelBuffer() { if (data_) delete [] data_; } void ManagedPixelBuffer::setPF(const PixelFormat &pf) { format = pf; setSize(width(), height()); } void ManagedPixelBuffer::setSize(int w, int h) { unsigned long new_datasize = w * h * (format.bpp/8); new_datasize = w * h * (format.bpp/8); if (datasize < new_datasize) { if (data_) { delete [] data_; data_ = NULL; datasize = 0; } if (new_datasize) { data_ = new U8[new_datasize]; datasize = new_datasize; } } setBuffer(w, h, data_, w); }
null
139
CWE-787
CVE-2019-15693
/* Copyright (C) 2000-2003 Constantin Kaplinsky. All Rights Reserved. * Copyright 2004-2005 Cendio AB. * Copyright 2009-2015 Pierre Ossman for Cendio AB * Copyright (C) 2011 D. R. Commander. All Rights Reserved. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ // // Tight decoding functions. // // This file is #included after having set the following macro: // BPP - 8, 16 or 32 namespace rfb { // CONCAT2E concatenates its arguments, expanding them if they are macros #ifndef CONCAT2E #define CONCAT2(a,b) a##b #define CONCAT2E(a,b) CONCAT2(a,b) #endif #define PIXEL_T rdr::CONCAT2E(U,BPP) #if BPP == 32 void TightDecoder::FilterGradient24(const rdr::U8 *inbuf, const PixelFormat& pf, PIXEL_T* outbuf, int stride, const Rect& r) { int x, y, c; rdr::U8 prevRow[TIGHT_MAX_WIDTH*3]; rdr::U8 thisRow[TIGHT_MAX_WIDTH*3]; rdr::U8 pix[3]; int est[3]; memset(prevRow, 0, sizeof(prevRow)); // Set up shortcut variables int rectHeight = r.height(); int rectWidth = r.width(); for (y = 0; y < rectHeight; y++) { /* First pixel in a row */ for (c = 0; c < 3; c++) { pix[c] = inbuf[y*rectWidth*3+c] + prevRow[c]; thisRow[c] = pix[c]; } pf.bufferFromRGB((rdr::U8*)&outbuf[y*stride], pix, 1); /* Remaining pixels of a row */ for (x = 1; x < rectWidth; x++) { for (c = 0; c < 3; c++) { est[c] = prevRow[x*3+c] + pix[c] - prevRow[(x-1)*3+c]; if (est[c] > 0xff) { est[c] = 0xff; } else if (est[c] < 0) { est[c] = 0; } pix[c] = inbuf[(y*rectWidth+x)*3+c] + est[c]; thisRow[x*3+c] = pix[c]; } pf.bufferFromRGB((rdr::U8*)&outbuf[y*stride+x], pix, 1); } memcpy(prevRow, thisRow, sizeof(prevRow)); } } #endif #if BPP != 8 void TightDecoder::FilterGradient(const rdr::U8* inbuf, const PixelFormat& pf, PIXEL_T* outbuf, int stride, const Rect& r) { int x, y, c; static rdr::U8 prevRow[TIGHT_MAX_WIDTH*3]; static rdr::U8 thisRow[TIGHT_MAX_WIDTH*3]; rdr::U8 pix[3]; int est[3]; memset(prevRow, 0, sizeof(prevRow)); // Set up shortcut variables int rectHeight = r.height(); int rectWidth = r.width(); for (y = 0; y < rectHeight; y++) { /* First pixel in a row */ pf.rgbFromBuffer(pix, &inbuf[y*rectWidth], 1); for (c = 0; c < 3; c++) pix[c] += prevRow[c]; memcpy(thisRow, pix, sizeof(pix)); pf.bufferFromRGB((rdr::U8*)&outbuf[y*stride], pix, 1); /* Remaining pixels of a row */ for (x = 1; x < rectWidth; x++) { for (c = 0; c < 3; c++) { est[c] = prevRow[x*3+c] + pix[c] - prevRow[(x-1)*3+c]; if (est[c] > 255) { est[c] = 255; } else if (est[c] < 0) { est[c] = 0; } } pf.rgbFromBuffer(pix, &inbuf[y*rectWidth+x], 1); for (c = 0; c < 3; c++) pix[c] += est[c]; memcpy(&thisRow[x*3], pix, sizeof(pix)); pf.bufferFromRGB((rdr::U8*)&outbuf[y*stride+x], pix, 1); } memcpy(prevRow, thisRow, sizeof(prevRow)); } } #endif void TightDecoder::FilterPalette(const PIXEL_T* palette, int palSize, const rdr::U8* inbuf, PIXEL_T* outbuf, int stride, const Rect& r) { // Indexed color int x, h = r.height(), w = r.width(), b, pad = stride - w; PIXEL_T* ptr = outbuf; rdr::U8 bits; const rdr::U8* srcPtr = inbuf; if (palSize <= 2) { // 2-color palette while (h > 0) { for (x = 0; x < w / 8; x++) { bits = *srcPtr++; for (b = 7; b >= 0; b--) { *ptr++ = palette[bits >> b & 1]; } } if (w % 8 != 0) { bits = *srcPtr++; for (b = 7; b >= 8 - w % 8; b--) { *ptr++ = palette[bits >> b & 1]; } } ptr += pad; h--; } } else { // 256-color palette while (h > 0) { PIXEL_T *endOfRow = ptr + w; while (ptr < endOfRow) { *ptr++ = palette[*srcPtr++]; } ptr += pad; h--; } } } #undef PIXEL_T }
null
/* Copyright (C) 2000-2003 Constantin Kaplinsky. All Rights Reserved. * Copyright 2004-2005 Cendio AB. * Copyright 2009-2015 Pierre Ossman for Cendio AB * Copyright (C) 2011 D. R. Commander. All Rights Reserved. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ // // Tight decoding functions. // // This file is #included after having set the following macro: // BPP - 8, 16 or 32 namespace rfb { // CONCAT2E concatenates its arguments, expanding them if they are macros #ifndef CONCAT2E #define CONCAT2(a,b) a##b #define CONCAT2E(a,b) CONCAT2(a,b) #endif #define PIXEL_T rdr::CONCAT2E(U,BPP) #if BPP == 32 void TightDecoder::FilterGradient24(const rdr::U8 *inbuf, const PixelFormat& pf, PIXEL_T* outbuf, int stride, const Rect& r) { int x, y, c; rdr::U8 prevRow[TIGHT_MAX_WIDTH*3]; rdr::U8 thisRow[TIGHT_MAX_WIDTH*3]; rdr::U8 pix[3]; int est[3]; memset(prevRow, 0, sizeof(prevRow)); // Set up shortcut variables int rectHeight = r.height(); int rectWidth = r.width(); for (y = 0; y < rectHeight; y++) { for (x = 0; x < rectWidth; x++) { /* First pixel in a row */ if (x == 0) { for (c = 0; c < 3; c++) { pix[c] = inbuf[y*rectWidth*3+c] + prevRow[c]; thisRow[c] = pix[c]; } pf.bufferFromRGB((rdr::U8*)&outbuf[y*stride], pix, 1); continue; } for (c = 0; c < 3; c++) { est[c] = prevRow[x*3+c] + pix[c] - prevRow[(x-1)*3+c]; if (est[c] > 0xff) { est[c] = 0xff; } else if (est[c] < 0) { est[c] = 0; } pix[c] = inbuf[(y*rectWidth+x)*3+c] + est[c]; thisRow[x*3+c] = pix[c]; } pf.bufferFromRGB((rdr::U8*)&outbuf[y*stride+x], pix, 1); } memcpy(prevRow, thisRow, sizeof(prevRow)); } } #endif #if BPP != 8 void TightDecoder::FilterGradient(const rdr::U8* inbuf, const PixelFormat& pf, PIXEL_T* outbuf, int stride, const Rect& r) { int x, y, c; static rdr::U8 prevRow[TIGHT_MAX_WIDTH*3]; static rdr::U8 thisRow[TIGHT_MAX_WIDTH*3]; rdr::U8 pix[3]; int est[3]; memset(prevRow, 0, sizeof(prevRow)); // Set up shortcut variables int rectHeight = r.height(); int rectWidth = r.width(); for (y = 0; y < rectHeight; y++) { for (x = 0; x < rectWidth; x++) { /* First pixel in a row */ if (x == 0) { pf.rgbFromBuffer(pix, &inbuf[y*rectWidth], 1); for (c = 0; c < 3; c++) pix[c] += prevRow[c]; memcpy(thisRow, pix, sizeof(pix)); pf.bufferFromRGB((rdr::U8*)&outbuf[y*stride], pix, 1); continue; } for (c = 0; c < 3; c++) { est[c] = prevRow[x*3+c] + pix[c] - prevRow[(x-1)*3+c]; if (est[c] > 255) { est[c] = 255; } else if (est[c] < 0) { est[c] = 0; } } pf.rgbFromBuffer(pix, &inbuf[y*rectWidth+x], 1); for (c = 0; c < 3; c++) pix[c] += est[c]; memcpy(&thisRow[x*3], pix, sizeof(pix)); pf.bufferFromRGB((rdr::U8*)&outbuf[y*stride+x], pix, 1); } memcpy(prevRow, thisRow, sizeof(prevRow)); } } #endif void TightDecoder::FilterPalette(const PIXEL_T* palette, int palSize, const rdr::U8* inbuf, PIXEL_T* outbuf, int stride, const Rect& r) { // Indexed color int x, h = r.height(), w = r.width(), b, pad = stride - w; PIXEL_T* ptr = outbuf; rdr::U8 bits; const rdr::U8* srcPtr = inbuf; if (palSize <= 2) { // 2-color palette while (h > 0) { for (x = 0; x < w / 8; x++) { bits = *srcPtr++; for (b = 7; b >= 0; b--) { *ptr++ = palette[bits >> b & 1]; } } if (w % 8 != 0) { bits = *srcPtr++; for (b = 7; b >= 8 - w % 8; b--) { *ptr++ = palette[bits >> b & 1]; } } ptr += pad; h--; } } else { // 256-color palette while (h > 0) { PIXEL_T *endOfRow = ptr + w; while (ptr < endOfRow) { *ptr++ = palette[*srcPtr++]; } ptr += pad; h--; } } } #undef PIXEL_T }
null
140
CWE-787
CVE-2019-15694
/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ #ifndef __RFB_PASSWORD_H__ #define __RFB_PASSWORD_H__ #include <rfb/util.h> namespace rfb { class ObfuscatedPasswd; class PlainPasswd : public CharArray { public: PlainPasswd(); PlainPasswd(char* pwd); PlainPasswd(int len); PlainPasswd(const ObfuscatedPasswd& obfPwd); ~PlainPasswd(); void replaceBuf(char* b); }; class ObfuscatedPasswd : public CharArray { public: ObfuscatedPasswd(); ObfuscatedPasswd(int l); ObfuscatedPasswd(const PlainPasswd& plainPwd); ~ObfuscatedPasswd(); int length; }; } #endif
null
/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ #ifndef __RFB_PASSWORD_H__ #define __RFB_PASSWORD_H__ #include <rfb/util.h> namespace rfb { class ObfuscatedPasswd; class PlainPasswd : public CharArray { public: PlainPasswd(); PlainPasswd(char* pwd); PlainPasswd(size_t len); PlainPasswd(const ObfuscatedPasswd& obfPwd); ~PlainPasswd(); void replaceBuf(char* b); }; class ObfuscatedPasswd : public CharArray { public: ObfuscatedPasswd(); ObfuscatedPasswd(size_t l); ObfuscatedPasswd(const PlainPasswd& plainPwd); ~ObfuscatedPasswd(); size_t length; }; } #endif
null
141
CWE-787
CVE-2019-15695
/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved. * Copyright (C) 2011 D. R. Commander. All Rights Reserved. * Copyright 2009-2014 Pierre Ossman for Cendio AB * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ #include <assert.h> #include <stdio.h> #include <stdint.h> #include <string.h> #include <rdr/InStream.h> #include <rdr/OutStream.h> #include <rfb/Exception.h> #include <rfb/PixelFormat.h> #include <rfb/util.h> #ifdef _WIN32 #define strcasecmp _stricmp #endif using namespace rfb; rdr::U8 PixelFormat::upconvTable[256*8]; rdr::U8 PixelFormat::downconvTable[256*8]; class PixelFormat::Init { public: Init(); }; PixelFormat::Init PixelFormat::_init; PixelFormat::Init::Init() { int bits; // Shifting bits is almost perfect, but not quite. And // a lookup table is still quicker when there is a large // difference between the source and destination depth. for (bits = 1;bits <= 8;bits++) { int i, maxVal; rdr::U8 *subUpTable; rdr::U8 *subDownTable; maxVal = (1 << bits) - 1; subUpTable = &upconvTable[(bits-1)*256]; subDownTable = &downconvTable[(bits-1)*256]; for (i = 0;i <= maxVal;i++) subUpTable[i] = i * 255 / maxVal; // Duplicate the up table so that we don't have to care about // the upper bits when doing a lookup for (;i < 256;i += maxVal+1) memcpy(&subUpTable[i], &subUpTable[0], maxVal+1); for (i = 0;i <= 255;i++) subDownTable[i] = (i * maxVal + 128) / 255; } } PixelFormat::PixelFormat(int b, int d, bool e, bool t, int rm, int gm, int bm, int rs, int gs, int bs) : bpp(b), depth(d), trueColour(t), bigEndian(e), redMax(rm), greenMax(gm), blueMax(bm), redShift(rs), greenShift(gs), blueShift(bs) { if (!isSane()) throw Exception("invalid pixel format"); updateState(); } PixelFormat::PixelFormat() : bpp(8), depth(8), trueColour(true), bigEndian(false), redMax(7), greenMax(7), blueMax(3), redShift(0), greenShift(3), blueShift(6) { updateState(); } bool PixelFormat::equal(const PixelFormat& other) const { if (bpp != other.bpp || depth != other.depth) return false; if (redMax != other.redMax) return false; if (greenMax != other.greenMax) return false; if (blueMax != other.blueMax) return false; // Endianness requires more care to determine compatibility if (bigEndian == other.bigEndian || bpp == 8) { if (redShift != other.redShift) return false; if (greenShift != other.greenShift) return false; if (blueShift != other.blueShift) return false; } else { // Has to be the same byte for each channel if (redShift/8 != (3 - other.redShift/8)) return false; if (greenShift/8 != (3 - other.greenShift/8)) return false; if (blueShift/8 != (3 - other.blueShift/8)) return false; // And the same bit offset within the byte if (redShift%8 != other.redShift%8) return false; if (greenShift%8 != other.greenShift%8) return false; if (blueShift%8 != other.blueShift%8) return false; // And not cross a byte boundary if (redShift/8 != (redShift + redBits - 1)/8) return false; if (greenShift/8 != (greenShift + greenBits - 1)/8) return false; if (blueShift/8 != (blueShift + blueBits - 1)/8) return false; } return true; } void PixelFormat::read(rdr::InStream* is) { bpp = is->readU8(); depth = is->readU8(); bigEndian = is->readU8(); trueColour = is->readU8(); redMax = is->readU16(); greenMax = is->readU16(); blueMax = is->readU16(); redShift = is->readU8(); greenShift = is->readU8(); blueShift = is->readU8(); is->skip(3); // We have no real support for colour maps. If the client // wants one, then we force a 8-bit true colour format and // pretend it's a colour map. if (!trueColour) { redMax = 7; greenMax = 7; blueMax = 3; redShift = 0; greenShift = 3; blueShift = 6; } if (!isSane()) throw Exception("invalid pixel format"); updateState(); } void PixelFormat::write(rdr::OutStream* os) const { os->writeU8(bpp); os->writeU8(depth); os->writeU8(bigEndian); os->writeU8(trueColour); os->writeU16(redMax); os->writeU16(greenMax); os->writeU16(blueMax); os->writeU8(redShift); os->writeU8(greenShift); os->writeU8(blueShift); os->pad(3); } bool PixelFormat::is888(void) const { if (!trueColour) return false; if (bpp != 32) return false; if (depth != 24) return false; if (redMax != 255) return false; if (greenMax != 255) return false; if (blueMax != 255) return false; return true; } bool PixelFormat::isBigEndian(void) const { return bigEndian; } bool PixelFormat::isLittleEndian(void) const { return ! bigEndian; } void PixelFormat::bufferFromRGB(rdr::U8 *dst, const rdr::U8* src, int pixels) const { bufferFromRGB(dst, src, pixels, pixels, 1); } void PixelFormat::bufferFromRGB(rdr::U8 *dst, const rdr::U8* src, int w, int stride, int h) const { if (is888()) { // Optimised common case rdr::U8 *r, *g, *b, *x; if (bigEndian) { r = dst + (24 - redShift)/8; g = dst + (24 - greenShift)/8; b = dst + (24 - blueShift)/8; x = dst + (24 - (48 - redShift - greenShift - blueShift))/8; } else { r = dst + redShift/8; g = dst + greenShift/8; b = dst + blueShift/8; x = dst + (48 - redShift - greenShift - blueShift)/8; } int dstPad = (stride - w) * 4; while (h--) { int w_ = w; while (w_--) { *r = *(src++); *g = *(src++); *b = *(src++); *x = 0; r += 4; g += 4; b += 4; x += 4; } r += dstPad; g += dstPad; b += dstPad; x += dstPad; } } else { // Generic code int dstPad = (stride - w) * bpp/8; while (h--) { int w_ = w; while (w_--) { Pixel p; rdr::U8 r, g, b; r = *(src++); g = *(src++); b = *(src++); p = pixelFromRGB(r, g, b); bufferFromPixel(dst, p); dst += bpp/8; } dst += dstPad; } } } void PixelFormat::rgbFromBuffer(rdr::U8* dst, const rdr::U8* src, int pixels) const { rgbFromBuffer(dst, src, pixels, pixels, 1); } void PixelFormat::rgbFromBuffer(rdr::U8* dst, const rdr::U8* src, int w, int stride, int h) const { if (is888()) { // Optimised common case const rdr::U8 *r, *g, *b; if (bigEndian) { r = src + (24 - redShift)/8; g = src + (24 - greenShift)/8; b = src + (24 - blueShift)/8; } else { r = src + redShift/8; g = src + greenShift/8; b = src + blueShift/8; } int srcPad = (stride - w) * 4; while (h--) { int w_ = w; while (w_--) { *(dst++) = *r; *(dst++) = *g; *(dst++) = *b; r += 4; g += 4; b += 4; } r += srcPad; g += srcPad; b += srcPad; } } else { // Generic code int srcPad = (stride - w) * bpp/8; while (h--) { int w_ = w; while (w_--) { Pixel p; rdr::U8 r, g, b; p = pixelFromBuffer(src); rgbFromPixel(p, &r, &g, &b); *(dst++) = r; *(dst++) = g; *(dst++) = b; src += bpp/8; } src += srcPad; } } } Pixel PixelFormat::pixelFromPixel(const PixelFormat &srcPF, Pixel src) const { rdr::U16 r, g, b; srcPF.rgbFromPixel(src, &r, &g, &b); return pixelFromRGB(r, g, b); } void PixelFormat::bufferFromBuffer(rdr::U8* dst, const PixelFormat &srcPF, const rdr::U8* src, int pixels) const { bufferFromBuffer(dst, srcPF, src, pixels, 1, pixels, pixels); } #define IS_ALIGNED(v, a) (((intptr_t)v & (a-1)) == 0) void PixelFormat::bufferFromBuffer(rdr::U8* dst, const PixelFormat &srcPF, const rdr::U8* src, int w, int h, int dstStride, int srcStride) const { if (equal(srcPF)) { // Trivial case while (h--) { memcpy(dst, src, w * bpp/8); dst += dstStride * bpp/8; src += srcStride * srcPF.bpp/8; } } else if (is888() && srcPF.is888()) { // Optimised common case A: byte shuffling (e.g. endian conversion) rdr::U8 *d[4], *s[4]; int dstPad, srcPad; if (bigEndian) { s[0] = dst + (24 - redShift)/8; s[1] = dst + (24 - greenShift)/8; s[2] = dst + (24 - blueShift)/8; s[3] = dst + (24 - (48 - redShift - greenShift - blueShift))/8; } else { s[0] = dst + redShift/8; s[1] = dst + greenShift/8; s[2] = dst + blueShift/8; s[3] = dst + (48 - redShift - greenShift - blueShift)/8; } if (srcPF.bigEndian) { d[(24 - srcPF.redShift)/8] = s[0]; d[(24 - srcPF.greenShift)/8] = s[1]; d[(24 - srcPF.blueShift)/8] = s[2]; d[(24 - (48 - srcPF.redShift - srcPF.greenShift - srcPF.blueShift))/8] = s[3]; } else { d[srcPF.redShift/8] = s[0]; d[srcPF.greenShift/8] = s[1]; d[srcPF.blueShift/8] = s[2]; d[(48 - srcPF.redShift - srcPF.greenShift - srcPF.blueShift)/8] = s[3]; } dstPad = (dstStride - w) * 4; srcPad = (srcStride - w) * 4; while (h--) { int w_ = w; while (w_--) { *d[0] = *(src++); *d[1] = *(src++); *d[2] = *(src++); *d[3] = *(src++); d[0] += 4; d[1] += 4; d[2] += 4; d[3] += 4; } d[0] += dstPad; d[1] += dstPad; d[2] += dstPad; d[3] += dstPad; src += srcPad; } } else if (IS_ALIGNED(dst, bpp/8) && srcPF.is888()) { // Optimised common case B: 888 source switch (bpp) { case 8: directBufferFromBufferFrom888((rdr::U8*)dst, srcPF, src, w, h, dstStride, srcStride); break; case 16: directBufferFromBufferFrom888((rdr::U16*)dst, srcPF, src, w, h, dstStride, srcStride); break; case 32: directBufferFromBufferFrom888((rdr::U32*)dst, srcPF, src, w, h, dstStride, srcStride); break; } } else if (IS_ALIGNED(src, srcPF.bpp/8) && is888()) { // Optimised common case C: 888 destination switch (srcPF.bpp) { case 8: directBufferFromBufferTo888(dst, srcPF, (rdr::U8*)src, w, h, dstStride, srcStride); break; case 16: directBufferFromBufferTo888(dst, srcPF, (rdr::U16*)src, w, h, dstStride, srcStride); break; case 32: directBufferFromBufferTo888(dst, srcPF, (rdr::U32*)src, w, h, dstStride, srcStride); break; } } else { // Generic code int dstPad = (dstStride - w) * bpp/8; int srcPad = (srcStride - w) * srcPF.bpp/8; while (h--) { int w_ = w; while (w_--) { Pixel p; rdr::U8 r, g, b; p = srcPF.pixelFromBuffer(src); srcPF.rgbFromPixel(p, &r, &g, &b); p = pixelFromRGB(r, g, b); bufferFromPixel(dst, p); dst += bpp/8; src += srcPF.bpp/8; } dst += dstPad; src += srcPad; } } } void PixelFormat::print(char* str, int len) const { // Unfortunately snprintf is not widely available so we build the string up // using strncat - not pretty, but should be safe against buffer overruns. char num[20]; if (len < 1) return; str[0] = 0; strncat(str, "depth ", len-1-strlen(str)); sprintf(num,"%d",depth); strncat(str, num, len-1-strlen(str)); strncat(str, " (", len-1-strlen(str)); sprintf(num,"%d",bpp); strncat(str, num, len-1-strlen(str)); strncat(str, "bpp)", len-1-strlen(str)); if (bpp != 8) { if (bigEndian) strncat(str, " big-endian", len-1-strlen(str)); else strncat(str, " little-endian", len-1-strlen(str)); } if (!trueColour) { strncat(str, " color-map", len-1-strlen(str)); return; } if (blueShift == 0 && greenShift > blueShift && redShift > greenShift && blueMax == (1 << greenShift) - 1 && greenMax == (1 << (redShift-greenShift)) - 1 && redMax == (1 << (depth-redShift)) - 1) { strncat(str, " rgb", len-1-strlen(str)); sprintf(num,"%d",depth-redShift); strncat(str, num, len-1-strlen(str)); sprintf(num,"%d",redShift-greenShift); strncat(str, num, len-1-strlen(str)); sprintf(num,"%d",greenShift); strncat(str, num, len-1-strlen(str)); return; } if (redShift == 0 && greenShift > redShift && blueShift > greenShift && redMax == (1 << greenShift) - 1 && greenMax == (1 << (blueShift-greenShift)) - 1 && blueMax == (1 << (depth-blueShift)) - 1) { strncat(str, " bgr", len-1-strlen(str)); sprintf(num,"%d",depth-blueShift); strncat(str, num, len-1-strlen(str)); sprintf(num,"%d",blueShift-greenShift); strncat(str, num, len-1-strlen(str)); sprintf(num,"%d",greenShift); strncat(str, num, len-1-strlen(str)); return; } strncat(str, " rgb max ", len-1-strlen(str)); sprintf(num,"%d,",redMax); strncat(str, num, len-1-strlen(str)); sprintf(num,"%d,",greenMax); strncat(str, num, len-1-strlen(str)); sprintf(num,"%d",blueMax); strncat(str, num, len-1-strlen(str)); strncat(str, " shift ", len-1-strlen(str)); sprintf(num,"%d,",redShift); strncat(str, num, len-1-strlen(str)); sprintf(num,"%d,",greenShift); strncat(str, num, len-1-strlen(str)); sprintf(num,"%d",blueShift); strncat(str, num, len-1-strlen(str)); } bool PixelFormat::parse(const char* str) { char rgbbgr[4]; int bits1, bits2, bits3; if (sscanf(str, "%3s%1d%1d%1d", rgbbgr, &bits1, &bits2, &bits3) < 4) return false; depth = bits1 + bits2 + bits3; bpp = depth <= 8 ? 8 : ((depth <= 16) ? 16 : 32); trueColour = true; rdr::U32 endianTest = 1; bigEndian = (*(rdr::U8*)&endianTest == 0); greenShift = bits3; greenMax = (1 << bits2) - 1; if (strcasecmp(rgbbgr, "bgr") == 0) { redShift = 0; redMax = (1 << bits3) - 1; blueShift = bits3 + bits2; blueMax = (1 << bits1) - 1; } else if (strcasecmp(rgbbgr, "rgb") == 0) { blueShift = 0; blueMax = (1 << bits3) - 1; redShift = bits3 + bits2; redMax = (1 << bits1) - 1; } else { return false; } assert(isSane()); updateState(); return true; } static int bits(rdr::U16 value) { int bits; bits = 16; if (!(value & 0xff00)) { bits -= 8; value <<= 8; } if (!(value & 0xf000)) { bits -= 4; value <<= 4; } if (!(value & 0xc000)) { bits -= 2; value <<= 2; } if (!(value & 0x8000)) { bits -= 1; value <<= 1; } return bits; } void PixelFormat::updateState(void) { int endianTest = 1; redBits = bits(redMax); greenBits = bits(greenMax); blueBits = bits(blueMax); maxBits = redBits; if (greenBits > maxBits) maxBits = greenBits; if (blueBits > maxBits) maxBits = blueBits; minBits = redBits; if (greenBits < minBits) minBits = greenBits; if (blueBits < minBits) minBits = blueBits; if (((*(char*)&endianTest) == 0) != bigEndian) endianMismatch = true; else endianMismatch = false; } bool PixelFormat::isSane(void) { int totalBits; if ((bpp != 8) && (bpp != 16) && (bpp != 32)) return false; if (depth > bpp) return false; if (!trueColour && (depth != 8)) return false; if ((redMax & (redMax + 1)) != 0) return false; if ((greenMax & (greenMax + 1)) != 0) return false; if ((blueMax & (blueMax + 1)) != 0) return false; /* * We don't allow individual channels > 8 bits in order to keep our * conversions simple. */ if (redMax >= (1 << 8)) return false; if (greenMax >= (1 << 8)) return false; if (blueMax >= (1 << 8)) return false; totalBits = bits(redMax) + bits(greenMax) + bits(blueMax); if (totalBits > depth) return false; if ((bits(redMax) + redShift) > bpp) return false; if ((bits(greenMax) + greenShift) > bpp) return false; if ((bits(blueMax) + blueShift) > bpp) return false; if (((redMax << redShift) & (greenMax << greenShift)) != 0) return false; if (((redMax << redShift) & (blueMax << blueShift)) != 0) return false; if (((greenMax << greenShift) & (blueMax << blueShift)) != 0) return false; return true; } // Preprocessor generated, optimised methods #define INBPP 8 #define OUTBPP 8 #include "PixelFormatBPP.cxx" #undef OUTBPP #define OUTBPP 16 #include "PixelFormatBPP.cxx" #undef OUTBPP #define OUTBPP 32 #include "PixelFormatBPP.cxx" #undef OUTBPP #undef INBPP #define INBPP 16 #define OUTBPP 8 #include "PixelFormatBPP.cxx" #undef OUTBPP #define OUTBPP 16 #include "PixelFormatBPP.cxx" #undef OUTBPP #define OUTBPP 32 #include "PixelFormatBPP.cxx" #undef OUTBPP #undef INBPP #define INBPP 32 #define OUTBPP 8 #include "PixelFormatBPP.cxx" #undef OUTBPP #define OUTBPP 16 #include "PixelFormatBPP.cxx" #undef OUTBPP #define OUTBPP 32 #include "PixelFormatBPP.cxx" #undef OUTBPP #undef INBPP
null
/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved. * Copyright (C) 2011 D. R. Commander. All Rights Reserved. * Copyright 2009-2014 Pierre Ossman for Cendio AB * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ #include <assert.h> #include <stdio.h> #include <stdint.h> #include <string.h> #include <rdr/InStream.h> #include <rdr/OutStream.h> #include <rfb/Exception.h> #include <rfb/PixelFormat.h> #include <rfb/util.h> #ifdef _WIN32 #define strcasecmp _stricmp #endif using namespace rfb; rdr::U8 PixelFormat::upconvTable[256*8]; rdr::U8 PixelFormat::downconvTable[256*8]; class PixelFormat::Init { public: Init(); }; PixelFormat::Init PixelFormat::_init; PixelFormat::Init::Init() { int bits; // Shifting bits is almost perfect, but not quite. And // a lookup table is still quicker when there is a large // difference between the source and destination depth. for (bits = 1;bits <= 8;bits++) { int i, maxVal; rdr::U8 *subUpTable; rdr::U8 *subDownTable; maxVal = (1 << bits) - 1; subUpTable = &upconvTable[(bits-1)*256]; subDownTable = &downconvTable[(bits-1)*256]; for (i = 0;i <= maxVal;i++) subUpTable[i] = i * 255 / maxVal; // Duplicate the up table so that we don't have to care about // the upper bits when doing a lookup for (;i < 256;i += maxVal+1) memcpy(&subUpTable[i], &subUpTable[0], maxVal+1); for (i = 0;i <= 255;i++) subDownTable[i] = (i * maxVal + 128) / 255; } } PixelFormat::PixelFormat(int b, int d, bool e, bool t, int rm, int gm, int bm, int rs, int gs, int bs) : bpp(b), depth(d), trueColour(t), bigEndian(e), redMax(rm), greenMax(gm), blueMax(bm), redShift(rs), greenShift(gs), blueShift(bs) { if (!isSane()) throw Exception("invalid pixel format"); updateState(); } PixelFormat::PixelFormat() : bpp(8), depth(8), trueColour(true), bigEndian(false), redMax(7), greenMax(7), blueMax(3), redShift(0), greenShift(3), blueShift(6) { updateState(); } bool PixelFormat::equal(const PixelFormat& other) const { if (bpp != other.bpp || depth != other.depth) return false; if (redMax != other.redMax) return false; if (greenMax != other.greenMax) return false; if (blueMax != other.blueMax) return false; // Endianness requires more care to determine compatibility if (bigEndian == other.bigEndian || bpp == 8) { if (redShift != other.redShift) return false; if (greenShift != other.greenShift) return false; if (blueShift != other.blueShift) return false; } else { // Has to be the same byte for each channel if (redShift/8 != (3 - other.redShift/8)) return false; if (greenShift/8 != (3 - other.greenShift/8)) return false; if (blueShift/8 != (3 - other.blueShift/8)) return false; // And the same bit offset within the byte if (redShift%8 != other.redShift%8) return false; if (greenShift%8 != other.greenShift%8) return false; if (blueShift%8 != other.blueShift%8) return false; // And not cross a byte boundary if (redShift/8 != (redShift + redBits - 1)/8) return false; if (greenShift/8 != (greenShift + greenBits - 1)/8) return false; if (blueShift/8 != (blueShift + blueBits - 1)/8) return false; } return true; } void PixelFormat::read(rdr::InStream* is) { bpp = is->readU8(); depth = is->readU8(); bigEndian = is->readU8(); trueColour = is->readU8(); redMax = is->readU16(); greenMax = is->readU16(); blueMax = is->readU16(); redShift = is->readU8(); greenShift = is->readU8(); blueShift = is->readU8(); is->skip(3); // We have no real support for colour maps. If the client // wants one, then we force a 8-bit true colour format and // pretend it's a colour map. if (!trueColour) { redMax = 7; greenMax = 7; blueMax = 3; redShift = 0; greenShift = 3; blueShift = 6; } if (!isSane()) throw Exception("invalid pixel format"); updateState(); } void PixelFormat::write(rdr::OutStream* os) const { os->writeU8(bpp); os->writeU8(depth); os->writeU8(bigEndian); os->writeU8(trueColour); os->writeU16(redMax); os->writeU16(greenMax); os->writeU16(blueMax); os->writeU8(redShift); os->writeU8(greenShift); os->writeU8(blueShift); os->pad(3); } bool PixelFormat::is888(void) const { if (!trueColour) return false; if (bpp != 32) return false; if (depth != 24) return false; if (redMax != 255) return false; if (greenMax != 255) return false; if (blueMax != 255) return false; if ((redShift & 0x7) != 0) return false; if ((greenShift & 0x7) != 0) return false; if ((blueShift & 0x7) != 0) return false; return true; } bool PixelFormat::isBigEndian(void) const { return bigEndian; } bool PixelFormat::isLittleEndian(void) const { return ! bigEndian; } void PixelFormat::bufferFromRGB(rdr::U8 *dst, const rdr::U8* src, int pixels) const { bufferFromRGB(dst, src, pixels, pixels, 1); } void PixelFormat::bufferFromRGB(rdr::U8 *dst, const rdr::U8* src, int w, int stride, int h) const { if (is888()) { // Optimised common case rdr::U8 *r, *g, *b, *x; if (bigEndian) { r = dst + (24 - redShift)/8; g = dst + (24 - greenShift)/8; b = dst + (24 - blueShift)/8; x = dst + (24 - (48 - redShift - greenShift - blueShift))/8; } else { r = dst + redShift/8; g = dst + greenShift/8; b = dst + blueShift/8; x = dst + (48 - redShift - greenShift - blueShift)/8; } int dstPad = (stride - w) * 4; while (h--) { int w_ = w; while (w_--) { *r = *(src++); *g = *(src++); *b = *(src++); *x = 0; r += 4; g += 4; b += 4; x += 4; } r += dstPad; g += dstPad; b += dstPad; x += dstPad; } } else { // Generic code int dstPad = (stride - w) * bpp/8; while (h--) { int w_ = w; while (w_--) { Pixel p; rdr::U8 r, g, b; r = *(src++); g = *(src++); b = *(src++); p = pixelFromRGB(r, g, b); bufferFromPixel(dst, p); dst += bpp/8; } dst += dstPad; } } } void PixelFormat::rgbFromBuffer(rdr::U8* dst, const rdr::U8* src, int pixels) const { rgbFromBuffer(dst, src, pixels, pixels, 1); } void PixelFormat::rgbFromBuffer(rdr::U8* dst, const rdr::U8* src, int w, int stride, int h) const { if (is888()) { // Optimised common case const rdr::U8 *r, *g, *b; if (bigEndian) { r = src + (24 - redShift)/8; g = src + (24 - greenShift)/8; b = src + (24 - blueShift)/8; } else { r = src + redShift/8; g = src + greenShift/8; b = src + blueShift/8; } int srcPad = (stride - w) * 4; while (h--) { int w_ = w; while (w_--) { *(dst++) = *r; *(dst++) = *g; *(dst++) = *b; r += 4; g += 4; b += 4; } r += srcPad; g += srcPad; b += srcPad; } } else { // Generic code int srcPad = (stride - w) * bpp/8; while (h--) { int w_ = w; while (w_--) { Pixel p; rdr::U8 r, g, b; p = pixelFromBuffer(src); rgbFromPixel(p, &r, &g, &b); *(dst++) = r; *(dst++) = g; *(dst++) = b; src += bpp/8; } src += srcPad; } } } Pixel PixelFormat::pixelFromPixel(const PixelFormat &srcPF, Pixel src) const { rdr::U16 r, g, b; srcPF.rgbFromPixel(src, &r, &g, &b); return pixelFromRGB(r, g, b); } void PixelFormat::bufferFromBuffer(rdr::U8* dst, const PixelFormat &srcPF, const rdr::U8* src, int pixels) const { bufferFromBuffer(dst, srcPF, src, pixels, 1, pixels, pixels); } #define IS_ALIGNED(v, a) (((intptr_t)v & (a-1)) == 0) void PixelFormat::bufferFromBuffer(rdr::U8* dst, const PixelFormat &srcPF, const rdr::U8* src, int w, int h, int dstStride, int srcStride) const { if (equal(srcPF)) { // Trivial case while (h--) { memcpy(dst, src, w * bpp/8); dst += dstStride * bpp/8; src += srcStride * srcPF.bpp/8; } } else if (is888() && srcPF.is888()) { // Optimised common case A: byte shuffling (e.g. endian conversion) rdr::U8 *d[4], *s[4]; int dstPad, srcPad; if (bigEndian) { s[0] = dst + (24 - redShift)/8; s[1] = dst + (24 - greenShift)/8; s[2] = dst + (24 - blueShift)/8; s[3] = dst + (24 - (48 - redShift - greenShift - blueShift))/8; } else { s[0] = dst + redShift/8; s[1] = dst + greenShift/8; s[2] = dst + blueShift/8; s[3] = dst + (48 - redShift - greenShift - blueShift)/8; } if (srcPF.bigEndian) { d[(24 - srcPF.redShift)/8] = s[0]; d[(24 - srcPF.greenShift)/8] = s[1]; d[(24 - srcPF.blueShift)/8] = s[2]; d[(24 - (48 - srcPF.redShift - srcPF.greenShift - srcPF.blueShift))/8] = s[3]; } else { d[srcPF.redShift/8] = s[0]; d[srcPF.greenShift/8] = s[1]; d[srcPF.blueShift/8] = s[2]; d[(48 - srcPF.redShift - srcPF.greenShift - srcPF.blueShift)/8] = s[3]; } dstPad = (dstStride - w) * 4; srcPad = (srcStride - w) * 4; while (h--) { int w_ = w; while (w_--) { *d[0] = *(src++); *d[1] = *(src++); *d[2] = *(src++); *d[3] = *(src++); d[0] += 4; d[1] += 4; d[2] += 4; d[3] += 4; } d[0] += dstPad; d[1] += dstPad; d[2] += dstPad; d[3] += dstPad; src += srcPad; } } else if (IS_ALIGNED(dst, bpp/8) && srcPF.is888()) { // Optimised common case B: 888 source switch (bpp) { case 8: directBufferFromBufferFrom888((rdr::U8*)dst, srcPF, src, w, h, dstStride, srcStride); break; case 16: directBufferFromBufferFrom888((rdr::U16*)dst, srcPF, src, w, h, dstStride, srcStride); break; case 32: directBufferFromBufferFrom888((rdr::U32*)dst, srcPF, src, w, h, dstStride, srcStride); break; } } else if (IS_ALIGNED(src, srcPF.bpp/8) && is888()) { // Optimised common case C: 888 destination switch (srcPF.bpp) { case 8: directBufferFromBufferTo888(dst, srcPF, (rdr::U8*)src, w, h, dstStride, srcStride); break; case 16: directBufferFromBufferTo888(dst, srcPF, (rdr::U16*)src, w, h, dstStride, srcStride); break; case 32: directBufferFromBufferTo888(dst, srcPF, (rdr::U32*)src, w, h, dstStride, srcStride); break; } } else { // Generic code int dstPad = (dstStride - w) * bpp/8; int srcPad = (srcStride - w) * srcPF.bpp/8; while (h--) { int w_ = w; while (w_--) { Pixel p; rdr::U8 r, g, b; p = srcPF.pixelFromBuffer(src); srcPF.rgbFromPixel(p, &r, &g, &b); p = pixelFromRGB(r, g, b); bufferFromPixel(dst, p); dst += bpp/8; src += srcPF.bpp/8; } dst += dstPad; src += srcPad; } } } void PixelFormat::print(char* str, int len) const { // Unfortunately snprintf is not widely available so we build the string up // using strncat - not pretty, but should be safe against buffer overruns. char num[20]; if (len < 1) return; str[0] = 0; strncat(str, "depth ", len-1-strlen(str)); sprintf(num,"%d",depth); strncat(str, num, len-1-strlen(str)); strncat(str, " (", len-1-strlen(str)); sprintf(num,"%d",bpp); strncat(str, num, len-1-strlen(str)); strncat(str, "bpp)", len-1-strlen(str)); if (bpp != 8) { if (bigEndian) strncat(str, " big-endian", len-1-strlen(str)); else strncat(str, " little-endian", len-1-strlen(str)); } if (!trueColour) { strncat(str, " color-map", len-1-strlen(str)); return; } if (blueShift == 0 && greenShift > blueShift && redShift > greenShift && blueMax == (1 << greenShift) - 1 && greenMax == (1 << (redShift-greenShift)) - 1 && redMax == (1 << (depth-redShift)) - 1) { strncat(str, " rgb", len-1-strlen(str)); sprintf(num,"%d",depth-redShift); strncat(str, num, len-1-strlen(str)); sprintf(num,"%d",redShift-greenShift); strncat(str, num, len-1-strlen(str)); sprintf(num,"%d",greenShift); strncat(str, num, len-1-strlen(str)); return; } if (redShift == 0 && greenShift > redShift && blueShift > greenShift && redMax == (1 << greenShift) - 1 && greenMax == (1 << (blueShift-greenShift)) - 1 && blueMax == (1 << (depth-blueShift)) - 1) { strncat(str, " bgr", len-1-strlen(str)); sprintf(num,"%d",depth-blueShift); strncat(str, num, len-1-strlen(str)); sprintf(num,"%d",blueShift-greenShift); strncat(str, num, len-1-strlen(str)); sprintf(num,"%d",greenShift); strncat(str, num, len-1-strlen(str)); return; } strncat(str, " rgb max ", len-1-strlen(str)); sprintf(num,"%d,",redMax); strncat(str, num, len-1-strlen(str)); sprintf(num,"%d,",greenMax); strncat(str, num, len-1-strlen(str)); sprintf(num,"%d",blueMax); strncat(str, num, len-1-strlen(str)); strncat(str, " shift ", len-1-strlen(str)); sprintf(num,"%d,",redShift); strncat(str, num, len-1-strlen(str)); sprintf(num,"%d,",greenShift); strncat(str, num, len-1-strlen(str)); sprintf(num,"%d",blueShift); strncat(str, num, len-1-strlen(str)); } bool PixelFormat::parse(const char* str) { char rgbbgr[4]; int bits1, bits2, bits3; if (sscanf(str, "%3s%1d%1d%1d", rgbbgr, &bits1, &bits2, &bits3) < 4) return false; depth = bits1 + bits2 + bits3; bpp = depth <= 8 ? 8 : ((depth <= 16) ? 16 : 32); trueColour = true; rdr::U32 endianTest = 1; bigEndian = (*(rdr::U8*)&endianTest == 0); greenShift = bits3; greenMax = (1 << bits2) - 1; if (strcasecmp(rgbbgr, "bgr") == 0) { redShift = 0; redMax = (1 << bits3) - 1; blueShift = bits3 + bits2; blueMax = (1 << bits1) - 1; } else if (strcasecmp(rgbbgr, "rgb") == 0) { blueShift = 0; blueMax = (1 << bits3) - 1; redShift = bits3 + bits2; redMax = (1 << bits1) - 1; } else { return false; } assert(isSane()); updateState(); return true; } static int bits(rdr::U16 value) { int bits; bits = 16; if (!(value & 0xff00)) { bits -= 8; value <<= 8; } if (!(value & 0xf000)) { bits -= 4; value <<= 4; } if (!(value & 0xc000)) { bits -= 2; value <<= 2; } if (!(value & 0x8000)) { bits -= 1; value <<= 1; } return bits; } void PixelFormat::updateState(void) { int endianTest = 1; redBits = bits(redMax); greenBits = bits(greenMax); blueBits = bits(blueMax); maxBits = redBits; if (greenBits > maxBits) maxBits = greenBits; if (blueBits > maxBits) maxBits = blueBits; minBits = redBits; if (greenBits < minBits) minBits = greenBits; if (blueBits < minBits) minBits = blueBits; if (((*(char*)&endianTest) == 0) != bigEndian) endianMismatch = true; else endianMismatch = false; } bool PixelFormat::isSane(void) { int totalBits; if ((bpp != 8) && (bpp != 16) && (bpp != 32)) return false; if (depth > bpp) return false; if (!trueColour && (depth != 8)) return false; if ((redMax & (redMax + 1)) != 0) return false; if ((greenMax & (greenMax + 1)) != 0) return false; if ((blueMax & (blueMax + 1)) != 0) return false; /* * We don't allow individual channels > 8 bits in order to keep our * conversions simple. */ if (redMax >= (1 << 8)) return false; if (greenMax >= (1 << 8)) return false; if (blueMax >= (1 << 8)) return false; totalBits = bits(redMax) + bits(greenMax) + bits(blueMax); if (totalBits > depth) return false; if ((bits(redMax) + redShift) > bpp) return false; if ((bits(greenMax) + greenShift) > bpp) return false; if ((bits(blueMax) + blueShift) > bpp) return false; if (((redMax << redShift) & (greenMax << greenShift)) != 0) return false; if (((redMax << redShift) & (blueMax << blueShift)) != 0) return false; if (((greenMax << greenShift) & (blueMax << blueShift)) != 0) return false; return true; } // Preprocessor generated, optimised methods #define INBPP 8 #define OUTBPP 8 #include "PixelFormatBPP.cxx" #undef OUTBPP #define OUTBPP 16 #include "PixelFormatBPP.cxx" #undef OUTBPP #define OUTBPP 32 #include "PixelFormatBPP.cxx" #undef OUTBPP #undef INBPP #define INBPP 16 #define OUTBPP 8 #include "PixelFormatBPP.cxx" #undef OUTBPP #define OUTBPP 16 #include "PixelFormatBPP.cxx" #undef OUTBPP #define OUTBPP 32 #include "PixelFormatBPP.cxx" #undef OUTBPP #undef INBPP #define INBPP 32 #define OUTBPP 8 #include "PixelFormatBPP.cxx" #undef OUTBPP #define OUTBPP 16 #include "PixelFormatBPP.cxx" #undef OUTBPP #define OUTBPP 32 #include "PixelFormatBPP.cxx" #undef OUTBPP #undef INBPP
null
142
CWE-787
CVE-2019-16346
#ifndef NGIFLIB_NO_FILE #include <stdio.h> #endif /* NGIFLIB_NO_FILE */ #include "ngiflib.h" /* decodeur GIF en C portable (pas de pb big/little endian) * Thomas BERNARD. janvier 2004. * (c) 2004-2017 Thomas Bernard. All rights reserved */ /* Fonction de debug */ #ifdef DEBUG void fprintf_ngiflib_img(FILE * f, struct ngiflib_img * i) { fprintf(f, " * ngiflib_img @ %p\n", i); fprintf(f, " next = %p\n", i->next); fprintf(f, " parent = %p\n", i->parent); fprintf(f, " palette = %p\n", i->palette); fprintf(f, " %3d couleurs", i->ncolors); if(i->interlaced) fprintf(f, " interlaced"); fprintf(f, "\n taille : %dx%d, pos (%d,%d)\n", i->width, i->height, i->posX, i->posY); fprintf(f, " sort_flag=%x localpalbits=%d\n", i->sort_flag, i->localpalbits); } #endif /* DEBUG */ void GifImgDestroy(struct ngiflib_img * i) { if(i==NULL) return; if(i->next) GifImgDestroy(i->next); if(i->palette && (i->palette != i->parent->palette)) ngiflib_free(i->palette); ngiflib_free(i); } /* Fonction de debug */ #ifdef DEBUG void fprintf_ngiflib_gif(FILE * f, struct ngiflib_gif * g) { struct ngiflib_img * i; fprintf(f, "* ngiflib_gif @ %p %s\n", g, g->signature); fprintf(f, " %dx%d, %d bits, %d couleurs\n", g->width, g->height, g->imgbits, g->ncolors); fprintf(f, " palette = %p, backgroundcolorindex %d\n", g->palette, g->backgroundindex); fprintf(f, " pixelaspectratio = %d\n", g->pixaspectratio); fprintf(f, " frbuff = %p\n", g->frbuff.p8); fprintf(f, " cur_img = %p\n", g->cur_img); fprintf(f, " %d images :\n", g->nimg); i = g->first_img; while(i) { fprintf_ngiflib_img(f, i); i = i->next; } } #endif /* DEBUG */ void GifDestroy(struct ngiflib_gif * g) { if(g==NULL) return; GifImgDestroy(g->first_img); if(g->palette) ngiflib_free(g->palette); if(g->frbuff.p8) ngiflib_free(g->frbuff.p8); ngiflib_free(g); } /* u8 GetByte(struct ngiflib_gif * g); * fonction qui renvoie un octet du fichier .gif * on pourait optimiser en faisant 2 fonctions. */ static u8 GetByte(struct ngiflib_gif * g) { #ifndef NGIFLIB_NO_FILE if(g->mode & NGIFLIB_MODE_FROM_MEM) { #endif /* NGIFLIB_NO_FILE */ return *(g->input.bytes++); #ifndef NGIFLIB_NO_FILE } else { return (u8)(getc(g->input.file)); } #endif /* NGIFLIB_NO_FILE */ } /* u16 GetWord() * Renvoie un mot de 16bits * N'est pas influencee par l'endianess du CPU ! */ static u16 GetWord(struct ngiflib_gif * g) { u16 r = (u16)GetByte(g); r |= ((u16)GetByte(g) << 8); return r; } /* int GetByteStr(struct ngiflib_gif * g, u8 * p, int n); * prend en argument un pointeur sur la destination * et le nombre d'octet a lire. * Renvoie 0 si l'operation a reussi, -1 sinon. */ static int GetByteStr(struct ngiflib_gif * g, u8 * p, int n) { if(!p) return -1; #ifndef NGIFLIB_NO_FILE if(g->mode & NGIFLIB_MODE_FROM_MEM) { #endif /* NGIFLIB_NO_FILE */ ngiflib_memcpy(p, g->input.bytes, n); g->input.bytes += n; return 0; #ifndef NGIFLIB_NO_FILE } else { size_t read; read = fread(p, 1, n, g->input.file); return ((int)read == n) ? 0 : -1; } #endif /* NGIFLIB_NO_FILE */ } /* void WritePixel(struct ngiflib_img * i, u8 v); * ecrit le pixel de valeur v dans le frame buffer */ static void WritePixel(struct ngiflib_img * i, struct ngiflib_decode_context * context, u8 v) { struct ngiflib_gif * p = i->parent; if(v!=i->gce.transparent_color || !i->gce.transparent_flag) { #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ *context->frbuff_p.p8 = v; #ifndef NGIFLIB_INDEXED_ONLY } else *context->frbuff_p.p32 = GifIndexToTrueColor(i->palette, v); #endif /* NGIFLIB_INDEXED_ONLY */ } if(--(context->Xtogo) <= 0) { #ifdef NGIFLIB_ENABLE_CALLBACKS if(p->line_cb) p->line_cb(p, context->line_p, context->curY); #endif /* NGIFLIB_ENABLE_CALLBACKS */ context->Xtogo = i->width; switch(context->pass) { case 0: context->curY++; break; case 1: /* 1st pass : every eighth row starting from 0 */ context->curY += 8; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 4; } break; case 2: /* 2nd pass : every eighth row starting from 4 */ context->curY += 8; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 2; } break; case 3: /* 3rd pass : every fourth row starting from 2 */ context->curY += 4; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 1; } break; case 4: /* 4th pass : every odd row */ context->curY += 2; break; } #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width; context->frbuff_p.p8 = context->line_p.p8 + i->posX; #else context->frbuff_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ #ifndef NGIFLIB_INDEXED_ONLY } else { #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width; context->frbuff_p.p32 = context->line_p.p32 + i->posX; #else context->frbuff_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } #endif /* NGIFLIB_INDEXED_ONLY */ } else { #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ context->frbuff_p.p8++; #ifndef NGIFLIB_INDEXED_ONLY } else { context->frbuff_p.p32++; } #endif /* NGIFLIB_INDEXED_ONLY */ } } /* void WritePixels(struct ngiflib_img * i, const u8 * pixels, u16 n); * ecrit les pixels dans le frame buffer */ static void WritePixels(struct ngiflib_img * i, struct ngiflib_decode_context * context, const u8 * pixels, u16 n) { u16 tocopy; struct ngiflib_gif * p = i->parent; while(n > 0) { tocopy = (context->Xtogo < n) ? context->Xtogo : n; if(!i->gce.transparent_flag) { #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ ngiflib_memcpy(context->frbuff_p.p8, pixels, tocopy); pixels += tocopy; context->frbuff_p.p8 += tocopy; #ifndef NGIFLIB_INDEXED_ONLY } else { int j; for(j = (int)tocopy; j > 0; j--) { *(context->frbuff_p.p32++) = GifIndexToTrueColor(i->palette, *pixels++); } } #endif /* NGIFLIB_INDEXED_ONLY */ } else { int j; #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ for(j = (int)tocopy; j > 0; j--) { if(*pixels != i->gce.transparent_color) *context->frbuff_p.p8 = *pixels; pixels++; context->frbuff_p.p8++; } #ifndef NGIFLIB_INDEXED_ONLY } else { for(j = (int)tocopy; j > 0; j--) { if(*pixels != i->gce.transparent_color) { *context->frbuff_p.p32 = GifIndexToTrueColor(i->palette, *pixels); } pixels++; context->frbuff_p.p32++; } } #endif /* NGIFLIB_INDEXED_ONLY */ } context->Xtogo -= tocopy; if(context->Xtogo == 0) { #ifdef NGIFLIB_ENABLE_CALLBACKS if(p->line_cb) p->line_cb(p, context->line_p, context->curY); #endif /* NGIFLIB_ENABLE_CALLBACKS */ context->Xtogo = i->width; switch(context->pass) { case 0: context->curY++; break; case 1: /* 1st pass : every eighth row starting from 0 */ context->curY += 8; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 4; } break; case 2: /* 2nd pass : every eighth row starting from 4 */ context->curY += 8; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 2; } break; case 3: /* 3rd pass : every fourth row starting from 2 */ context->curY += 4; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 1; } break; case 4: /* 4th pass : every odd row */ context->curY += 2; break; } #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width; context->frbuff_p.p8 = context->line_p.p8 + i->posX; #else context->frbuff_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ #ifndef NGIFLIB_INDEXED_ONLY } else { #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width; context->frbuff_p.p32 = context->line_p.p32 + i->posX; #else context->frbuff_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } #endif /* NGIFLIB_INDEXED_ONLY */ } n -= tocopy; } } /* * u16 GetGifWord(struct ngiflib_img * i); * Renvoie un code LZW (taille variable) */ static u16 GetGifWord(struct ngiflib_img * i, struct ngiflib_decode_context * context) { u16 r; int bits_todo; u16 newbyte; bits_todo = (int)context->nbbit - (int)context->restbits; if( bits_todo <= 0) { /* nbbit <= restbits */ r = context->lbyte; context->restbits -= context->nbbit; context->lbyte >>= context->nbbit; } else if( bits_todo > 8 ) { /* nbbit > restbits + 8 */ if(context->restbyte >= 2) { context->restbyte -= 2; r = *context->srcbyte++; } else { if(context->restbyte == 0) { context->restbyte = GetByte(i->parent); #if defined(DEBUG) && !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "restbyte = %02X\n", context->restbyte); #endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */ GetByteStr(i->parent, context->byte_buffer, context->restbyte); context->srcbyte = context->byte_buffer; } r = *context->srcbyte++; if(--context->restbyte == 0) { context->restbyte = GetByte(i->parent); #if defined(DEBUG) && !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "restbyte = %02X\n", context->restbyte); #endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */ GetByteStr(i->parent, context->byte_buffer, context->restbyte); context->srcbyte = context->byte_buffer; } context->restbyte--; } newbyte = *context->srcbyte++; r |= newbyte << 8; r = (r << context->restbits) | context->lbyte; context->restbits = 16 - bits_todo; context->lbyte = newbyte >> (bits_todo - 8); } else /*if( bits_todo > 0 )*/ { /* nbbit > restbits */ if(context->restbyte == 0) { context->restbyte = GetByte(i->parent); #if defined(DEBUG) && !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "restbyte = %02X\n", context->restbyte); #endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */ GetByteStr(i->parent, context->byte_buffer, context->restbyte); context->srcbyte = context->byte_buffer; } newbyte = *context->srcbyte++; context->restbyte--; r = (newbyte << context->restbits) | context->lbyte; context->restbits = 8 - bits_todo; context->lbyte = newbyte >> bits_todo; } return (r & context->max); /* applique le bon masque pour eliminer les bits en trop */ } /* ------------------------------------------------ */ static void FillGifBackGround(struct ngiflib_gif * g) { long n = (long)g->width*g->height; #ifndef NGIFLIB_INDEXED_ONLY u32 bg_truecolor; #endif /* NGIFLIB_INDEXED_ONLY */ if((g->frbuff.p8==NULL)||(g->palette==NULL)) return; #ifndef NGIFLIB_INDEXED_ONLY if(g->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ ngiflib_memset(g->frbuff.p8, g->backgroundindex, n); #ifndef NGIFLIB_INDEXED_ONLY } else { u32 * p = g->frbuff.p32; bg_truecolor = GifIndexToTrueColor(g->palette, g->backgroundindex); while(n-->0) *p++ = bg_truecolor; } #endif /* NGIFLIB_INDEXED_ONLY */ } /* ------------------------------------------------ */ int CheckGif(u8 * b) { return (b[0]=='G')&&(b[1]=='I')&&(b[2]=='F')&&(b[3]=='8'); } /* ------------------------------------------------ */ static int DecodeGifImg(struct ngiflib_img * i) { struct ngiflib_decode_context context; long npix; u8 * stackp; u8 * stack_top; u16 clr; u16 eof; u16 free; u16 act_code = 0; u16 old_code = 0; u16 read_byt; u16 ab_prfx[4096]; u8 ab_suffx[4096]; u8 ab_stack[4096]; u8 flags; u8 casspecial = 0; if(!i) return -1; i->posX = GetWord(i->parent); /* offsetX */ i->posY = GetWord(i->parent); /* offsetY */ i->width = GetWord(i->parent); /* SizeX */ i->height = GetWord(i->parent); /* SizeY */ if((i->width > i->parent->width) || (i->height > i->parent->height)) { #if !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "*** ERROR *** Image bigger than global GIF canvas !\n"); #endif return -1; } if((i->posX + i->width) > i->parent->width) { #if !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "*** WARNING *** Adjusting X position\n"); #endif i->posX = i->parent->width - i->width; } if((i->posY + i->height) > i->parent->height) { #if !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "*** WARNING *** Adjusting Y position\n"); #endif i->posY = i->parent->height - i->height; } context.Xtogo = i->width; context.curY = i->posY; #ifdef NGIFLIB_INDEXED_ONLY #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width; context.frbuff_p.p8 = context.line_p.p8 + i->posX; #else context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ #else if(i->parent->mode & NGIFLIB_MODE_INDEXED) { #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width; context.frbuff_p.p8 = context.line_p.p8 + i->posX; #else context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } else { #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width; context.frbuff_p.p32 = context.line_p.p32 + i->posX; #else context.frbuff_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } #endif /* NGIFLIB_INDEXED_ONLY */ npix = (long)i->width * i->height; flags = GetByte(i->parent); i->interlaced = (flags & 64) >> 6; context.pass = i->interlaced ? 1 : 0; i->sort_flag = (flags & 32) >> 5; /* is local palette sorted by color frequency ? */ i->localpalbits = (flags & 7) + 1; if(flags&128) { /* palette locale */ int k; int localpalsize = 1 << i->localpalbits; #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "Local palette\n"); #endif /* !defined(NGIFLIB_NO_FILE) */ i->palette = (struct ngiflib_rgb *)ngiflib_malloc(sizeof(struct ngiflib_rgb)*localpalsize); for(k=0; k<localpalsize; k++) { i->palette[k].r = GetByte(i->parent); i->palette[k].g = GetByte(i->parent); i->palette[k].b = GetByte(i->parent); } #ifdef NGIFLIB_ENABLE_CALLBACKS if(i->parent->palette_cb) i->parent->palette_cb(i->parent, i->palette, localpalsize); #endif /* NGIFLIB_ENABLE_CALLBACKS */ } else { i->palette = i->parent->palette; i->localpalbits = i->parent->imgbits; } i->ncolors = 1 << i->localpalbits; i->imgbits = GetByte(i->parent); /* LZW Minimum Code Size */ if (i->imgbits > 11) { #if !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "*** ERROR *** Invalid LZW Minimum Code Size : %d\n", (int)i->imgbits); #endif return -1; } #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) { if(i->interlaced) fprintf(i->parent->log, "interlaced "); fprintf(i->parent->log, "img pos(%hu,%hu) size %hux%hu palbits=%hhu imgbits=%hhu ncolors=%hu\n", i->posX, i->posY, i->width, i->height, i->localpalbits, i->imgbits, i->ncolors); } #endif /* !defined(NGIFLIB_NO_FILE) */ if(i->imgbits==1) { /* fix for 1bit images ? */ i->imgbits = 2; } clr = 1 << i->imgbits; eof = clr + 1; free = clr + 2; context.nbbit = i->imgbits + 1; context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */ stackp = stack_top = ab_stack + 4096; context.restbits = 0; /* initialise le "buffer" de lecture */ context.restbyte = 0; /* des codes LZW */ context.lbyte = 0; for(;;) { act_code = GetGifWord(i, &context); if(act_code==eof) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "End of image code\n"); #endif /* !defined(NGIFLIB_NO_FILE) */ return 0; } if(npix==0) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "assez de pixels, On se casse !\n"); #endif /* !defined(NGIFLIB_NO_FILE) */ return 1; } if(act_code==clr) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "Code clear (%hu) (free=%hu) npix=%ld\n", clr, free, npix); #endif /* !defined(NGIFLIB_NO_FILE) */ /* clear */ free = clr + 2; context.nbbit = i->imgbits + 1; context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */ act_code = GetGifWord(i, &context); /* the first code after the clear code is concrete */ if (act_code >= clr) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "Invalid code %hu just after clear(%hu) !\n", act_code, clr); #endif /* !defined(NGIFLIB_NO_FILE) */ return -1; } casspecial = (u8)act_code; old_code = act_code; if(npix > 0) WritePixel(i, &context, casspecial); npix--; } else if(act_code > free) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "Invalid code %hu (free=%hu) !\n", act_code, free); #endif /* !defined(NGIFLIB_NO_FILE) */ return -1; } else { read_byt = act_code; if(act_code == free) { /* code pas encore dans alphabet */ /* printf("Code pas dans alphabet : %d>=%d push %d\n", act_code, free, casspecial); */ *(--stackp) = casspecial; /* dernier debut de chaine ! */ act_code = old_code; } /* printf("actcode=%d\n", act_code); */ while(act_code > clr) { /* code non concret */ /* fillstackloop empile les suffixes ! */ *(--stackp) = ab_suffx[act_code]; act_code = ab_prfx[act_code]; /* prefixe */ } /* act_code est concret */ casspecial = (u8)act_code; /* dernier debut de chaine ! */ *(--stackp) = casspecial; /* push on stack */ if(npix >= (stack_top - stackp)) { WritePixels(i, &context, stackp, stack_top - stackp); /* unstack all pixels at once */ } else if(npix > 0) { /* "pixel overflow" */ WritePixels(i, &context, stackp, npix); } npix -= (stack_top - stackp); stackp = stack_top; /* putchar('\n'); */ if(free < 4096) { /* la taille du dico est 4096 max ! */ ab_prfx[free] = old_code; ab_suffx[free] = (u8)act_code; free++; if((free > context.max) && (context.nbbit < 12)) { context.nbbit++; /* 1 bit de plus pour les codes LZW */ context.max += context.max + 1; } } old_code = read_byt; } } return 0; } /* ------------------------------------------------ * int LoadGif(struct ngiflib_gif *); * s'assurer que nimg=0 au depart ! * retourne : * 0 si GIF termin * un nombre negatif si ERREUR * 1 si image Decode * rappeler pour decoder les images suivantes * ------------------------------------------------ */ int LoadGif(struct ngiflib_gif * g) { struct ngiflib_gce gce; u8 sign; u8 tmp; int i; if(!g) return -1; gce.gce_present = 0; if(g->nimg==0) { GetByteStr(g, g->signature, 6); g->signature[6] = '\0'; if( g->signature[0] != 'G' || g->signature[1] != 'I' || g->signature[2] != 'F' || g->signature[3] != '8') { return -1; } #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "%s\n", g->signature); #endif /* !defined(NGIFLIB_NO_FILE) */ g->width = GetWord(g); g->height = GetWord(g); /* allocate frame buffer */ #ifndef NGIFLIB_INDEXED_ONLY if((g->mode & NGIFLIB_MODE_INDEXED)==0) g->frbuff.p32 = ngiflib_malloc(4*(long)g->height*(long)g->width); else #endif /* NGIFLIB_INDEXED_ONLY */ g->frbuff.p8 = ngiflib_malloc((long)g->height*(long)g->width); tmp = GetByte(g);/* <Packed Fields> = Global Color Table Flag 1 Bit Color Resolution 3 Bits Sort Flag 1 Bit Size of Global Color Table 3 Bits */ g->colorresolution = ((tmp & 0x70) >> 4) + 1; g->sort_flag = (tmp & 8) >> 3; g->imgbits = (tmp & 7) + 1; /* Global Palette color resolution */ g->ncolors = 1 << g->imgbits; g->backgroundindex = GetByte(g); #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "%hux%hu %hhubits %hu couleurs bg=%hhu\n", g->width, g->height, g->imgbits, g->ncolors, g->backgroundindex); #endif /* NGIFLIB_INDEXED_ONLY */ g->pixaspectratio = GetByte(g); /* pixel aspect ratio (0 : unspecified) */ if(tmp&0x80) { /* la palette globale suit. */ g->palette = (struct ngiflib_rgb *)ngiflib_malloc(sizeof(struct ngiflib_rgb)*g->ncolors); for(i=0; i<g->ncolors; i++) { g->palette[i].r = GetByte(g); g->palette[i].g = GetByte(g); g->palette[i].b = GetByte(g); #if defined(DEBUG) && !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "%3d %02X %02X %02X\n", i, g->palette[i].r,g->palette[i].g,g->palette[i].b); #endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */ } #ifdef NGIFLIB_ENABLE_CALLBACKS if(g->palette_cb) g->palette_cb(g, g->palette, g->ncolors); #endif /* NGIFLIB_ENABLE_CALLBACKS */ } else { g->palette = NULL; } g->netscape_loop_count = -1; } for(;;) { char appid_auth[11]; u8 id,size; int blockindex; sign = GetByte(g); /* signature du prochain bloc */ #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "BLOCK SIGNATURE 0x%02X '%c'\n", sign, (sign >= 32) ? sign : '.'); #endif /* NGIFLIB_INDEXED_ONLY */ switch(sign) { case 0x3B: /* END OF GIF */ return 0; case '!': /* Extension introducer 0x21 */ id = GetByte(g); blockindex = 0; #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "extension (id=0x%02hhx)\n", id); #endif /* NGIFLIB_NO_FILE */ while( (size = GetByte(g)) ) { u8 ext[256]; GetByteStr(g, ext, size); switch(id) { case 0xF9: /* Graphic Control Extension */ /* The scope of this extension is the first graphic * rendering block to follow. */ gce.gce_present = 1; gce.disposal_method = (ext[0] >> 2) & 7; gce.transparent_flag = ext[0] & 1; gce.user_input_flag = (ext[0] >> 1) & 1; gce.delay_time = ext[1] | (ext[2]<<8); gce.transparent_color = ext[3]; #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "disposal_method=%hhu delay_time=%hu (transp=%hhu)transparent_color=0x%02hhX\n", gce.disposal_method, gce.delay_time, gce.transparent_flag, gce.transparent_color); #endif /* NGIFLIB_INDEXED_ONLY */ /* this propably should be adjusted depending on the disposal_method * of the _previous_ image. */ if(gce.transparent_flag && ((g->nimg == 0) || gce.disposal_method == 2)) { FillGifBackGround(g); } break; case 0xFE: /* Comment Extension. */ #if !defined(NGIFLIB_NO_FILE) if(g->log) { if(blockindex==0) fprintf(g->log, "-------------------- Comment extension --------------------\n"); ext[size] = '\0'; fputs((char *)ext, g->log); } #endif /* NGIFLIB_NO_FILE */ break; case 0xFF: /* application extension */ /* NETSCAPE2.0 extension : * http://www.vurdalakov.net/misc/gif/netscape-looping-application-extension */ if(blockindex==0) { ngiflib_memcpy(appid_auth, ext, 11); #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "---------------- Application extension ---------------\n"); fprintf(g->log, "Application identifier : '%.8s', auth code : %02X %02X %02X (", appid_auth, ext[8], ext[9], ext[10]); fputc((ext[8]<32)?' ':ext[8], g->log); fputc((ext[9]<32)?' ':ext[9], g->log); fputc((ext[10]<32)?' ':ext[10], g->log); fprintf(g->log, ")\n"); } #endif /* NGIFLIB_INDEXED_ONLY */ } else { #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "Datas (as hex) : "); for(i=0; i<size; i++) { fprintf(g->log, "%02x ", ext[i]); } fprintf(g->log, "\nDatas (as text) : '"); for(i=0; i<size; i++) { putc((ext[i]<32)?' ':ext[i], g->log); } fprintf(g->log, "'\n"); } #endif /* NGIFLIB_INDEXED_ONLY */ if(0 == ngiflib_memcmp(appid_auth, "NETSCAPE2.0", 11)) { /* ext[0] : Sub-block ID */ if(ext[0] == 1) { /* 1 : Netscape Looping Extension. */ g->netscape_loop_count = (int)ext[1] | ((int)ext[2] << 8); #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "NETSCAPE loop_count = %d\n", g->netscape_loop_count); } #endif /* NGIFLIB_NO_FILE */ } } } break; case 0x01: /* plain text extension */ #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "Plain text extension blockindex=%d\n", blockindex); for(i=0; i<size; i++) { putc((ext[i]<32)?' ':ext[i], g->log); } putc('\n', g->log); } #endif /* NGIFLIB_INDEXED_ONLY */ break; } blockindex++; } switch(id) { case 0x01: /* plain text extension */ case 0xFE: /* Comment Extension. */ case 0xFF: /* application extension */ #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "-----------------------------------------------------------\n"); } #endif /* NGIFLIB_NO_FILE */ break; } break; case 0x2C: /* Image separator */ if(g->nimg==0) { g->cur_img = ngiflib_malloc(sizeof(struct ngiflib_img)); if(g->cur_img == NULL) return -2; /* memory error */ g->first_img = g->cur_img; } else { g->cur_img->next = ngiflib_malloc(sizeof(struct ngiflib_img)); if(g->cur_img->next == NULL) return -2; /* memory error */ g->cur_img = g->cur_img->next; } ngiflib_memset(g->cur_img, 0, sizeof(struct ngiflib_img)); g->cur_img->parent = g; if(gce.gce_present) { ngiflib_memcpy(&g->cur_img->gce, &gce, sizeof(struct ngiflib_gce)); } else { ngiflib_memset(&g->cur_img->gce, 0, sizeof(struct ngiflib_gce)); } if (DecodeGifImg(g->cur_img) < 0) return -1; g->nimg++; tmp = GetByte(g);/* 0 final */ #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "ZERO TERMINATOR 0x%02X\n", tmp); #endif /* NGIFLIB_INDEXED_ONLY */ return 1; /* image decode */ default: /* unexpected byte */ #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "unexpected signature 0x%02X\n", sign); #endif /* NGIFLIB_INDEXED_ONLY */ return -1; } } } u32 GifIndexToTrueColor(struct ngiflib_rgb * palette, u8 v) { return palette[v].b | (palette[v].g << 8) | (palette[v].r << 16); }
null
#ifndef NGIFLIB_NO_FILE #include <stdio.h> #endif /* NGIFLIB_NO_FILE */ #include "ngiflib.h" /* decodeur GIF en C portable (pas de pb big/little endian) * Thomas BERNARD. janvier 2004. * (c) 2004-2019 Thomas Bernard. All rights reserved */ /* Fonction de debug */ #ifdef DEBUG void fprintf_ngiflib_img(FILE * f, struct ngiflib_img * i) { fprintf(f, " * ngiflib_img @ %p\n", i); fprintf(f, " next = %p\n", i->next); fprintf(f, " parent = %p\n", i->parent); fprintf(f, " palette = %p\n", i->palette); fprintf(f, " %3d couleurs", i->ncolors); if(i->interlaced) fprintf(f, " interlaced"); fprintf(f, "\n taille : %dx%d, pos (%d,%d)\n", i->width, i->height, i->posX, i->posY); fprintf(f, " sort_flag=%x localpalbits=%d\n", i->sort_flag, i->localpalbits); } #endif /* DEBUG */ void GifImgDestroy(struct ngiflib_img * i) { if(i==NULL) return; if(i->next) GifImgDestroy(i->next); if(i->palette && (i->palette != i->parent->palette)) ngiflib_free(i->palette); ngiflib_free(i); } /* Fonction de debug */ #ifdef DEBUG void fprintf_ngiflib_gif(FILE * f, struct ngiflib_gif * g) { struct ngiflib_img * i; fprintf(f, "* ngiflib_gif @ %p %s\n", g, g->signature); fprintf(f, " %dx%d, %d bits, %d couleurs\n", g->width, g->height, g->imgbits, g->ncolors); fprintf(f, " palette = %p, backgroundcolorindex %d\n", g->palette, g->backgroundindex); fprintf(f, " pixelaspectratio = %d\n", g->pixaspectratio); fprintf(f, " frbuff = %p\n", g->frbuff.p8); fprintf(f, " cur_img = %p\n", g->cur_img); fprintf(f, " %d images :\n", g->nimg); i = g->first_img; while(i) { fprintf_ngiflib_img(f, i); i = i->next; } } #endif /* DEBUG */ void GifDestroy(struct ngiflib_gif * g) { if(g==NULL) return; GifImgDestroy(g->first_img); if(g->palette) ngiflib_free(g->palette); if(g->frbuff.p8) ngiflib_free(g->frbuff.p8); ngiflib_free(g); } /* u8 GetByte(struct ngiflib_gif * g); * fonction qui renvoie un octet du fichier .gif * on pourait optimiser en faisant 2 fonctions. */ static u8 GetByte(struct ngiflib_gif * g) { #ifndef NGIFLIB_NO_FILE if(g->mode & NGIFLIB_MODE_FROM_MEM) { #endif /* NGIFLIB_NO_FILE */ return *(g->input.bytes++); #ifndef NGIFLIB_NO_FILE } else { return (u8)(getc(g->input.file)); } #endif /* NGIFLIB_NO_FILE */ } /* u16 GetWord() * Renvoie un mot de 16bits * N'est pas influencee par l'endianess du CPU ! */ static u16 GetWord(struct ngiflib_gif * g) { u16 r = (u16)GetByte(g); r |= ((u16)GetByte(g) << 8); return r; } /* int GetByteStr(struct ngiflib_gif * g, u8 * p, int n); * prend en argument un pointeur sur la destination * et le nombre d'octet a lire. * Renvoie 0 si l'operation a reussi, -1 sinon. */ static int GetByteStr(struct ngiflib_gif * g, u8 * p, int n) { if(!p) return -1; #ifndef NGIFLIB_NO_FILE if(g->mode & NGIFLIB_MODE_FROM_MEM) { #endif /* NGIFLIB_NO_FILE */ ngiflib_memcpy(p, g->input.bytes, n); g->input.bytes += n; return 0; #ifndef NGIFLIB_NO_FILE } else { size_t read; read = fread(p, 1, n, g->input.file); return ((int)read == n) ? 0 : -1; } #endif /* NGIFLIB_NO_FILE */ } /* void WritePixel(struct ngiflib_img * i, u8 v); * ecrit le pixel de valeur v dans le frame buffer */ static void WritePixel(struct ngiflib_img * i, struct ngiflib_decode_context * context, u8 v) { struct ngiflib_gif * p = i->parent; if(v!=i->gce.transparent_color || !i->gce.transparent_flag) { #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ *context->frbuff_p.p8 = v; #ifndef NGIFLIB_INDEXED_ONLY } else *context->frbuff_p.p32 = GifIndexToTrueColor(i->palette, v); #endif /* NGIFLIB_INDEXED_ONLY */ } if(--(context->Xtogo) <= 0) { #ifdef NGIFLIB_ENABLE_CALLBACKS if(p->line_cb) p->line_cb(p, context->line_p, context->curY); #endif /* NGIFLIB_ENABLE_CALLBACKS */ context->Xtogo = i->width; switch(context->pass) { case 0: context->curY++; break; case 1: /* 1st pass : every eighth row starting from 0 */ context->curY += 8; break; case 2: /* 2nd pass : every eighth row starting from 4 */ context->curY += 8; break; case 3: /* 3rd pass : every fourth row starting from 2 */ context->curY += 4; break; case 4: /* 4th pass : every odd row */ context->curY += 2; break; } while(context->pass > 0 && context->pass < 4 && context->curY >= p->height) { switch(++context->pass) { case 2: /* 2nd pass : every eighth row starting from 4 */ context->curY = i->posY + 4; break; case 3: /* 3rd pass : every fourth row starting from 2 */ context->curY = i->posY + 2; break; case 4: /* 4th pass : every odd row */ context->curY = i->posY + 1; break; } } #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width; context->frbuff_p.p8 = context->line_p.p8 + i->posX; #else context->frbuff_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ #ifndef NGIFLIB_INDEXED_ONLY } else { #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width; context->frbuff_p.p32 = context->line_p.p32 + i->posX; #else context->frbuff_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } #endif /* NGIFLIB_INDEXED_ONLY */ } else { #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ context->frbuff_p.p8++; #ifndef NGIFLIB_INDEXED_ONLY } else { context->frbuff_p.p32++; } #endif /* NGIFLIB_INDEXED_ONLY */ } } /* void WritePixels(struct ngiflib_img * i, const u8 * pixels, u16 n); * ecrit les pixels dans le frame buffer */ static void WritePixels(struct ngiflib_img * i, struct ngiflib_decode_context * context, const u8 * pixels, u16 n) { u16 tocopy; struct ngiflib_gif * p = i->parent; while(n > 0) { tocopy = (context->Xtogo < n) ? context->Xtogo : n; if(!i->gce.transparent_flag) { #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ ngiflib_memcpy(context->frbuff_p.p8, pixels, tocopy); pixels += tocopy; context->frbuff_p.p8 += tocopy; #ifndef NGIFLIB_INDEXED_ONLY } else { int j; for(j = (int)tocopy; j > 0; j--) { *(context->frbuff_p.p32++) = GifIndexToTrueColor(i->palette, *pixels++); } } #endif /* NGIFLIB_INDEXED_ONLY */ } else { int j; #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ for(j = (int)tocopy; j > 0; j--) { if(*pixels != i->gce.transparent_color) *context->frbuff_p.p8 = *pixels; pixels++; context->frbuff_p.p8++; } #ifndef NGIFLIB_INDEXED_ONLY } else { for(j = (int)tocopy; j > 0; j--) { if(*pixels != i->gce.transparent_color) { *context->frbuff_p.p32 = GifIndexToTrueColor(i->palette, *pixels); } pixels++; context->frbuff_p.p32++; } } #endif /* NGIFLIB_INDEXED_ONLY */ } context->Xtogo -= tocopy; if(context->Xtogo == 0) { #ifdef NGIFLIB_ENABLE_CALLBACKS if(p->line_cb) p->line_cb(p, context->line_p, context->curY); #endif /* NGIFLIB_ENABLE_CALLBACKS */ context->Xtogo = i->width; switch(context->pass) { case 0: context->curY++; break; case 1: /* 1st pass : every eighth row starting from 0 */ context->curY += 8; break; case 2: /* 2nd pass : every eighth row starting from 4 */ context->curY += 8; break; case 3: /* 3rd pass : every fourth row starting from 2 */ context->curY += 4; break; case 4: /* 4th pass : every odd row */ context->curY += 2; break; } while(context->pass > 0 && context->pass < 4 && context->curY >= p->height) { switch(++context->pass) { case 2: /* 2nd pass : every eighth row starting from 4 */ context->curY = i->posY + 4; break; case 3: /* 3rd pass : every fourth row starting from 2 */ context->curY = i->posY + 2; break; case 4: /* 4th pass : every odd row */ context->curY = i->posY + 1; break; } } #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width; context->frbuff_p.p8 = context->line_p.p8 + i->posX; #else context->frbuff_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ #ifndef NGIFLIB_INDEXED_ONLY } else { #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width; context->frbuff_p.p32 = context->line_p.p32 + i->posX; #else context->frbuff_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } #endif /* NGIFLIB_INDEXED_ONLY */ } n -= tocopy; } } /* * u16 GetGifWord(struct ngiflib_img * i); * Renvoie un code LZW (taille variable) */ static u16 GetGifWord(struct ngiflib_img * i, struct ngiflib_decode_context * context) { u16 r; int bits_todo; u16 newbyte; bits_todo = (int)context->nbbit - (int)context->restbits; if( bits_todo <= 0) { /* nbbit <= restbits */ r = context->lbyte; context->restbits -= context->nbbit; context->lbyte >>= context->nbbit; } else if( bits_todo > 8 ) { /* nbbit > restbits + 8 */ if(context->restbyte >= 2) { context->restbyte -= 2; r = *context->srcbyte++; } else { if(context->restbyte == 0) { context->restbyte = GetByte(i->parent); #if defined(DEBUG) && !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "restbyte = %02X\n", context->restbyte); #endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */ GetByteStr(i->parent, context->byte_buffer, context->restbyte); context->srcbyte = context->byte_buffer; } r = *context->srcbyte++; if(--context->restbyte == 0) { context->restbyte = GetByte(i->parent); #if defined(DEBUG) && !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "restbyte = %02X\n", context->restbyte); #endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */ GetByteStr(i->parent, context->byte_buffer, context->restbyte); context->srcbyte = context->byte_buffer; } context->restbyte--; } newbyte = *context->srcbyte++; r |= newbyte << 8; r = (r << context->restbits) | context->lbyte; context->restbits = 16 - bits_todo; context->lbyte = newbyte >> (bits_todo - 8); } else /*if( bits_todo > 0 )*/ { /* nbbit > restbits */ if(context->restbyte == 0) { context->restbyte = GetByte(i->parent); #if defined(DEBUG) && !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "restbyte = %02X\n", context->restbyte); #endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */ GetByteStr(i->parent, context->byte_buffer, context->restbyte); context->srcbyte = context->byte_buffer; } newbyte = *context->srcbyte++; context->restbyte--; r = (newbyte << context->restbits) | context->lbyte; context->restbits = 8 - bits_todo; context->lbyte = newbyte >> bits_todo; } return (r & context->max); /* applique le bon masque pour eliminer les bits en trop */ } /* ------------------------------------------------ */ static void FillGifBackGround(struct ngiflib_gif * g) { long n = (long)g->width*g->height; #ifndef NGIFLIB_INDEXED_ONLY u32 bg_truecolor; #endif /* NGIFLIB_INDEXED_ONLY */ if((g->frbuff.p8==NULL)||(g->palette==NULL)) return; #ifndef NGIFLIB_INDEXED_ONLY if(g->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ ngiflib_memset(g->frbuff.p8, g->backgroundindex, n); #ifndef NGIFLIB_INDEXED_ONLY } else { u32 * p = g->frbuff.p32; bg_truecolor = GifIndexToTrueColor(g->palette, g->backgroundindex); while(n-->0) *p++ = bg_truecolor; } #endif /* NGIFLIB_INDEXED_ONLY */ } /* ------------------------------------------------ */ int CheckGif(u8 * b) { return (b[0]=='G')&&(b[1]=='I')&&(b[2]=='F')&&(b[3]=='8'); } /* ------------------------------------------------ */ static int DecodeGifImg(struct ngiflib_img * i) { struct ngiflib_decode_context context; long npix; u8 * stackp; u8 * stack_top; u16 clr; u16 eof; u16 free; u16 act_code = 0; u16 old_code = 0; u16 read_byt; u16 ab_prfx[4096]; u8 ab_suffx[4096]; u8 ab_stack[4096]; u8 flags; u8 casspecial = 0; if(!i) return -1; i->posX = GetWord(i->parent); /* offsetX */ i->posY = GetWord(i->parent); /* offsetY */ i->width = GetWord(i->parent); /* SizeX */ i->height = GetWord(i->parent); /* SizeY */ if((i->width > i->parent->width) || (i->height > i->parent->height)) { #if !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "*** ERROR *** Image bigger than global GIF canvas !\n"); #endif return -1; } if((i->posX + i->width) > i->parent->width) { #if !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "*** WARNING *** Adjusting X position\n"); #endif i->posX = i->parent->width - i->width; } if((i->posY + i->height) > i->parent->height) { #if !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "*** WARNING *** Adjusting Y position\n"); #endif i->posY = i->parent->height - i->height; } context.Xtogo = i->width; context.curY = i->posY; #ifdef NGIFLIB_INDEXED_ONLY #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width; context.frbuff_p.p8 = context.line_p.p8 + i->posX; #else context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ #else if(i->parent->mode & NGIFLIB_MODE_INDEXED) { #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width; context.frbuff_p.p8 = context.line_p.p8 + i->posX; #else context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } else { #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width; context.frbuff_p.p32 = context.line_p.p32 + i->posX; #else context.frbuff_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } #endif /* NGIFLIB_INDEXED_ONLY */ npix = (long)i->width * i->height; flags = GetByte(i->parent); i->interlaced = (flags & 64) >> 6; context.pass = i->interlaced ? 1 : 0; i->sort_flag = (flags & 32) >> 5; /* is local palette sorted by color frequency ? */ i->localpalbits = (flags & 7) + 1; if(flags&128) { /* palette locale */ int k; int localpalsize = 1 << i->localpalbits; #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "Local palette\n"); #endif /* !defined(NGIFLIB_NO_FILE) */ i->palette = (struct ngiflib_rgb *)ngiflib_malloc(sizeof(struct ngiflib_rgb)*localpalsize); for(k=0; k<localpalsize; k++) { i->palette[k].r = GetByte(i->parent); i->palette[k].g = GetByte(i->parent); i->palette[k].b = GetByte(i->parent); } #ifdef NGIFLIB_ENABLE_CALLBACKS if(i->parent->palette_cb) i->parent->palette_cb(i->parent, i->palette, localpalsize); #endif /* NGIFLIB_ENABLE_CALLBACKS */ } else { i->palette = i->parent->palette; i->localpalbits = i->parent->imgbits; } i->ncolors = 1 << i->localpalbits; i->imgbits = GetByte(i->parent); /* LZW Minimum Code Size */ if (i->imgbits > 11) { #if !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "*** ERROR *** Invalid LZW Minimum Code Size : %d\n", (int)i->imgbits); #endif return -1; } #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) { if(i->interlaced) fprintf(i->parent->log, "interlaced "); fprintf(i->parent->log, "img pos(%hu,%hu) size %hux%hu palbits=%hhu imgbits=%hhu ncolors=%hu\n", i->posX, i->posY, i->width, i->height, i->localpalbits, i->imgbits, i->ncolors); } #endif /* !defined(NGIFLIB_NO_FILE) */ if(i->imgbits==1) { /* fix for 1bit images ? */ i->imgbits = 2; } clr = 1 << i->imgbits; eof = clr + 1; free = clr + 2; context.nbbit = i->imgbits + 1; context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */ stackp = stack_top = ab_stack + 4096; context.restbits = 0; /* initialise le "buffer" de lecture */ context.restbyte = 0; /* des codes LZW */ context.lbyte = 0; for(;;) { act_code = GetGifWord(i, &context); if(act_code==eof) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "End of image code\n"); #endif /* !defined(NGIFLIB_NO_FILE) */ return 0; } if(npix==0) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "assez de pixels, On se casse !\n"); #endif /* !defined(NGIFLIB_NO_FILE) */ return 1; } if(act_code==clr) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "Code clear (%hu) (free=%hu) npix=%ld\n", clr, free, npix); #endif /* !defined(NGIFLIB_NO_FILE) */ /* clear */ free = clr + 2; context.nbbit = i->imgbits + 1; context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */ act_code = GetGifWord(i, &context); /* the first code after the clear code is concrete */ if (act_code >= clr) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "Invalid code %hu just after clear(%hu) !\n", act_code, clr); #endif /* !defined(NGIFLIB_NO_FILE) */ return -1; } casspecial = (u8)act_code; old_code = act_code; if(npix > 0) WritePixel(i, &context, casspecial); npix--; } else if(act_code > free) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "Invalid code %hu (free=%hu) !\n", act_code, free); #endif /* !defined(NGIFLIB_NO_FILE) */ return -1; } else { read_byt = act_code; if(act_code == free) { /* code pas encore dans alphabet */ /* printf("Code pas dans alphabet : %d>=%d push %d\n", act_code, free, casspecial); */ *(--stackp) = casspecial; /* dernier debut de chaine ! */ act_code = old_code; } /* printf("actcode=%d\n", act_code); */ while(act_code > clr) { /* code non concret */ /* fillstackloop empile les suffixes ! */ *(--stackp) = ab_suffx[act_code]; act_code = ab_prfx[act_code]; /* prefixe */ } /* act_code est concret */ casspecial = (u8)act_code; /* dernier debut de chaine ! */ *(--stackp) = casspecial; /* push on stack */ if(npix >= (stack_top - stackp)) { WritePixels(i, &context, stackp, stack_top - stackp); /* unstack all pixels at once */ } else if(npix > 0) { /* "pixel overflow" */ WritePixels(i, &context, stackp, npix); } npix -= (stack_top - stackp); stackp = stack_top; /* putchar('\n'); */ if(free < 4096) { /* la taille du dico est 4096 max ! */ ab_prfx[free] = old_code; ab_suffx[free] = (u8)act_code; free++; if((free > context.max) && (context.nbbit < 12)) { context.nbbit++; /* 1 bit de plus pour les codes LZW */ context.max += context.max + 1; } } old_code = read_byt; } } return 0; } /* ------------------------------------------------ * int LoadGif(struct ngiflib_gif *); * s'assurer que nimg=0 au depart ! * retourne : * 0 si GIF termin * un nombre negatif si ERREUR * 1 si image Decode * rappeler pour decoder les images suivantes * ------------------------------------------------ */ int LoadGif(struct ngiflib_gif * g) { struct ngiflib_gce gce; u8 sign; u8 tmp; int i; if(!g) return -1; gce.gce_present = 0; if(g->nimg==0) { GetByteStr(g, g->signature, 6); g->signature[6] = '\0'; if( g->signature[0] != 'G' || g->signature[1] != 'I' || g->signature[2] != 'F' || g->signature[3] != '8') { return -1; } #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "%s\n", g->signature); #endif /* !defined(NGIFLIB_NO_FILE) */ g->width = GetWord(g); g->height = GetWord(g); /* allocate frame buffer */ #ifndef NGIFLIB_INDEXED_ONLY if((g->mode & NGIFLIB_MODE_INDEXED)==0) g->frbuff.p32 = ngiflib_malloc(4*(long)g->height*(long)g->width); else #endif /* NGIFLIB_INDEXED_ONLY */ g->frbuff.p8 = ngiflib_malloc((long)g->height*(long)g->width); tmp = GetByte(g);/* <Packed Fields> = Global Color Table Flag 1 Bit Color Resolution 3 Bits Sort Flag 1 Bit Size of Global Color Table 3 Bits */ g->colorresolution = ((tmp & 0x70) >> 4) + 1; g->sort_flag = (tmp & 8) >> 3; g->imgbits = (tmp & 7) + 1; /* Global Palette color resolution */ g->ncolors = 1 << g->imgbits; g->backgroundindex = GetByte(g); #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "%hux%hu %hhubits %hu couleurs bg=%hhu\n", g->width, g->height, g->imgbits, g->ncolors, g->backgroundindex); #endif /* NGIFLIB_INDEXED_ONLY */ g->pixaspectratio = GetByte(g); /* pixel aspect ratio (0 : unspecified) */ if(tmp&0x80) { /* la palette globale suit. */ g->palette = (struct ngiflib_rgb *)ngiflib_malloc(sizeof(struct ngiflib_rgb)*g->ncolors); for(i=0; i<g->ncolors; i++) { g->palette[i].r = GetByte(g); g->palette[i].g = GetByte(g); g->palette[i].b = GetByte(g); #if defined(DEBUG) && !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "%3d %02X %02X %02X\n", i, g->palette[i].r,g->palette[i].g,g->palette[i].b); #endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */ } #ifdef NGIFLIB_ENABLE_CALLBACKS if(g->palette_cb) g->palette_cb(g, g->palette, g->ncolors); #endif /* NGIFLIB_ENABLE_CALLBACKS */ } else { g->palette = NULL; } g->netscape_loop_count = -1; } for(;;) { char appid_auth[11]; u8 id,size; int blockindex; sign = GetByte(g); /* signature du prochain bloc */ #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "BLOCK SIGNATURE 0x%02X '%c'\n", sign, (sign >= 32) ? sign : '.'); #endif /* NGIFLIB_INDEXED_ONLY */ switch(sign) { case 0x3B: /* END OF GIF */ return 0; case '!': /* Extension introducer 0x21 */ id = GetByte(g); blockindex = 0; #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "extension (id=0x%02hhx)\n", id); #endif /* NGIFLIB_NO_FILE */ while( (size = GetByte(g)) ) { u8 ext[256]; GetByteStr(g, ext, size); switch(id) { case 0xF9: /* Graphic Control Extension */ /* The scope of this extension is the first graphic * rendering block to follow. */ gce.gce_present = 1; gce.disposal_method = (ext[0] >> 2) & 7; gce.transparent_flag = ext[0] & 1; gce.user_input_flag = (ext[0] >> 1) & 1; gce.delay_time = ext[1] | (ext[2]<<8); gce.transparent_color = ext[3]; #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "disposal_method=%hhu delay_time=%hu (transp=%hhu)transparent_color=0x%02hhX\n", gce.disposal_method, gce.delay_time, gce.transparent_flag, gce.transparent_color); #endif /* NGIFLIB_INDEXED_ONLY */ /* this propably should be adjusted depending on the disposal_method * of the _previous_ image. */ if(gce.transparent_flag && ((g->nimg == 0) || gce.disposal_method == 2)) { FillGifBackGround(g); } break; case 0xFE: /* Comment Extension. */ #if !defined(NGIFLIB_NO_FILE) if(g->log) { if(blockindex==0) fprintf(g->log, "-------------------- Comment extension --------------------\n"); ext[size] = '\0'; fputs((char *)ext, g->log); } #endif /* NGIFLIB_NO_FILE */ break; case 0xFF: /* application extension */ /* NETSCAPE2.0 extension : * http://www.vurdalakov.net/misc/gif/netscape-looping-application-extension */ if(blockindex==0) { ngiflib_memcpy(appid_auth, ext, 11); #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "---------------- Application extension ---------------\n"); fprintf(g->log, "Application identifier : '%.8s', auth code : %02X %02X %02X (", appid_auth, ext[8], ext[9], ext[10]); fputc((ext[8]<32)?' ':ext[8], g->log); fputc((ext[9]<32)?' ':ext[9], g->log); fputc((ext[10]<32)?' ':ext[10], g->log); fprintf(g->log, ")\n"); } #endif /* NGIFLIB_INDEXED_ONLY */ } else { #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "Datas (as hex) : "); for(i=0; i<size; i++) { fprintf(g->log, "%02x ", ext[i]); } fprintf(g->log, "\nDatas (as text) : '"); for(i=0; i<size; i++) { putc((ext[i]<32)?' ':ext[i], g->log); } fprintf(g->log, "'\n"); } #endif /* NGIFLIB_INDEXED_ONLY */ if(0 == ngiflib_memcmp(appid_auth, "NETSCAPE2.0", 11)) { /* ext[0] : Sub-block ID */ if(ext[0] == 1) { /* 1 : Netscape Looping Extension. */ g->netscape_loop_count = (int)ext[1] | ((int)ext[2] << 8); #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "NETSCAPE loop_count = %d\n", g->netscape_loop_count); } #endif /* NGIFLIB_NO_FILE */ } } } break; case 0x01: /* plain text extension */ #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "Plain text extension blockindex=%d\n", blockindex); for(i=0; i<size; i++) { putc((ext[i]<32)?' ':ext[i], g->log); } putc('\n', g->log); } #endif /* NGIFLIB_INDEXED_ONLY */ break; } blockindex++; } switch(id) { case 0x01: /* plain text extension */ case 0xFE: /* Comment Extension. */ case 0xFF: /* application extension */ #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "-----------------------------------------------------------\n"); } #endif /* NGIFLIB_NO_FILE */ break; } break; case 0x2C: /* Image separator */ if(g->nimg==0) { g->cur_img = ngiflib_malloc(sizeof(struct ngiflib_img)); if(g->cur_img == NULL) return -2; /* memory error */ g->first_img = g->cur_img; } else { g->cur_img->next = ngiflib_malloc(sizeof(struct ngiflib_img)); if(g->cur_img->next == NULL) return -2; /* memory error */ g->cur_img = g->cur_img->next; } ngiflib_memset(g->cur_img, 0, sizeof(struct ngiflib_img)); g->cur_img->parent = g; if(gce.gce_present) { ngiflib_memcpy(&g->cur_img->gce, &gce, sizeof(struct ngiflib_gce)); } else { ngiflib_memset(&g->cur_img->gce, 0, sizeof(struct ngiflib_gce)); } if (DecodeGifImg(g->cur_img) < 0) return -1; g->nimg++; tmp = GetByte(g);/* 0 final */ #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "ZERO TERMINATOR 0x%02X\n", tmp); #endif /* NGIFLIB_INDEXED_ONLY */ return 1; /* image decode */ default: /* unexpected byte */ #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "unexpected signature 0x%02X\n", sign); #endif /* NGIFLIB_INDEXED_ONLY */ return -1; } } } u32 GifIndexToTrueColor(struct ngiflib_rgb * palette, u8 v) { return palette[v].b | (palette[v].g << 8) | (palette[v].r << 16); }
null
143
CWE-787
CVE-2019-16347
#ifndef NGIFLIB_NO_FILE #include <stdio.h> #endif /* NGIFLIB_NO_FILE */ #include "ngiflib.h" /* decodeur GIF en C portable (pas de pb big/little endian) * Thomas BERNARD. janvier 2004. * (c) 2004-2017 Thomas Bernard. All rights reserved */ /* Fonction de debug */ #ifdef DEBUG void fprintf_ngiflib_img(FILE * f, struct ngiflib_img * i) { fprintf(f, " * ngiflib_img @ %p\n", i); fprintf(f, " next = %p\n", i->next); fprintf(f, " parent = %p\n", i->parent); fprintf(f, " palette = %p\n", i->palette); fprintf(f, " %3d couleurs", i->ncolors); if(i->interlaced) fprintf(f, " interlaced"); fprintf(f, "\n taille : %dx%d, pos (%d,%d)\n", i->width, i->height, i->posX, i->posY); fprintf(f, " sort_flag=%x localpalbits=%d\n", i->sort_flag, i->localpalbits); } #endif /* DEBUG */ void GifImgDestroy(struct ngiflib_img * i) { if(i==NULL) return; if(i->next) GifImgDestroy(i->next); if(i->palette && (i->palette != i->parent->palette)) ngiflib_free(i->palette); ngiflib_free(i); } /* Fonction de debug */ #ifdef DEBUG void fprintf_ngiflib_gif(FILE * f, struct ngiflib_gif * g) { struct ngiflib_img * i; fprintf(f, "* ngiflib_gif @ %p %s\n", g, g->signature); fprintf(f, " %dx%d, %d bits, %d couleurs\n", g->width, g->height, g->imgbits, g->ncolors); fprintf(f, " palette = %p, backgroundcolorindex %d\n", g->palette, g->backgroundindex); fprintf(f, " pixelaspectratio = %d\n", g->pixaspectratio); fprintf(f, " frbuff = %p\n", g->frbuff.p8); fprintf(f, " cur_img = %p\n", g->cur_img); fprintf(f, " %d images :\n", g->nimg); i = g->first_img; while(i) { fprintf_ngiflib_img(f, i); i = i->next; } } #endif /* DEBUG */ void GifDestroy(struct ngiflib_gif * g) { if(g==NULL) return; GifImgDestroy(g->first_img); if(g->palette) ngiflib_free(g->palette); if(g->frbuff.p8) ngiflib_free(g->frbuff.p8); ngiflib_free(g); } /* u8 GetByte(struct ngiflib_gif * g); * fonction qui renvoie un octet du fichier .gif * on pourait optimiser en faisant 2 fonctions. */ static u8 GetByte(struct ngiflib_gif * g) { #ifndef NGIFLIB_NO_FILE if(g->mode & NGIFLIB_MODE_FROM_MEM) { #endif /* NGIFLIB_NO_FILE */ return *(g->input.bytes++); #ifndef NGIFLIB_NO_FILE } else { return (u8)(getc(g->input.file)); } #endif /* NGIFLIB_NO_FILE */ } /* u16 GetWord() * Renvoie un mot de 16bits * N'est pas influencee par l'endianess du CPU ! */ static u16 GetWord(struct ngiflib_gif * g) { u16 r = (u16)GetByte(g); r |= ((u16)GetByte(g) << 8); return r; } /* int GetByteStr(struct ngiflib_gif * g, u8 * p, int n); * prend en argument un pointeur sur la destination * et le nombre d'octet a lire. * Renvoie 0 si l'operation a reussi, -1 sinon. */ static int GetByteStr(struct ngiflib_gif * g, u8 * p, int n) { if(!p) return -1; #ifndef NGIFLIB_NO_FILE if(g->mode & NGIFLIB_MODE_FROM_MEM) { #endif /* NGIFLIB_NO_FILE */ ngiflib_memcpy(p, g->input.bytes, n); g->input.bytes += n; return 0; #ifndef NGIFLIB_NO_FILE } else { size_t read; read = fread(p, 1, n, g->input.file); return ((int)read == n) ? 0 : -1; } #endif /* NGIFLIB_NO_FILE */ } /* void WritePixel(struct ngiflib_img * i, u8 v); * ecrit le pixel de valeur v dans le frame buffer */ static void WritePixel(struct ngiflib_img * i, struct ngiflib_decode_context * context, u8 v) { struct ngiflib_gif * p = i->parent; if(v!=i->gce.transparent_color || !i->gce.transparent_flag) { #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ *context->frbuff_p.p8 = v; #ifndef NGIFLIB_INDEXED_ONLY } else *context->frbuff_p.p32 = GifIndexToTrueColor(i->palette, v); #endif /* NGIFLIB_INDEXED_ONLY */ } if(--(context->Xtogo) <= 0) { #ifdef NGIFLIB_ENABLE_CALLBACKS if(p->line_cb) p->line_cb(p, context->line_p, context->curY); #endif /* NGIFLIB_ENABLE_CALLBACKS */ context->Xtogo = i->width; switch(context->pass) { case 0: context->curY++; break; case 1: /* 1st pass : every eighth row starting from 0 */ context->curY += 8; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 4; } break; case 2: /* 2nd pass : every eighth row starting from 4 */ context->curY += 8; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 2; } break; case 3: /* 3rd pass : every fourth row starting from 2 */ context->curY += 4; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 1; } break; case 4: /* 4th pass : every odd row */ context->curY += 2; break; } #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width; context->frbuff_p.p8 = context->line_p.p8 + i->posX; #else context->frbuff_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ #ifndef NGIFLIB_INDEXED_ONLY } else { #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width; context->frbuff_p.p32 = context->line_p.p32 + i->posX; #else context->frbuff_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } #endif /* NGIFLIB_INDEXED_ONLY */ } else { #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ context->frbuff_p.p8++; #ifndef NGIFLIB_INDEXED_ONLY } else { context->frbuff_p.p32++; } #endif /* NGIFLIB_INDEXED_ONLY */ } } /* void WritePixels(struct ngiflib_img * i, const u8 * pixels, u16 n); * ecrit les pixels dans le frame buffer */ static void WritePixels(struct ngiflib_img * i, struct ngiflib_decode_context * context, const u8 * pixels, u16 n) { u16 tocopy; struct ngiflib_gif * p = i->parent; while(n > 0) { tocopy = (context->Xtogo < n) ? context->Xtogo : n; if(!i->gce.transparent_flag) { #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ ngiflib_memcpy(context->frbuff_p.p8, pixels, tocopy); pixels += tocopy; context->frbuff_p.p8 += tocopy; #ifndef NGIFLIB_INDEXED_ONLY } else { int j; for(j = (int)tocopy; j > 0; j--) { *(context->frbuff_p.p32++) = GifIndexToTrueColor(i->palette, *pixels++); } } #endif /* NGIFLIB_INDEXED_ONLY */ } else { int j; #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ for(j = (int)tocopy; j > 0; j--) { if(*pixels != i->gce.transparent_color) *context->frbuff_p.p8 = *pixels; pixels++; context->frbuff_p.p8++; } #ifndef NGIFLIB_INDEXED_ONLY } else { for(j = (int)tocopy; j > 0; j--) { if(*pixels != i->gce.transparent_color) { *context->frbuff_p.p32 = GifIndexToTrueColor(i->palette, *pixels); } pixels++; context->frbuff_p.p32++; } } #endif /* NGIFLIB_INDEXED_ONLY */ } context->Xtogo -= tocopy; if(context->Xtogo == 0) { #ifdef NGIFLIB_ENABLE_CALLBACKS if(p->line_cb) p->line_cb(p, context->line_p, context->curY); #endif /* NGIFLIB_ENABLE_CALLBACKS */ context->Xtogo = i->width; switch(context->pass) { case 0: context->curY++; break; case 1: /* 1st pass : every eighth row starting from 0 */ context->curY += 8; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 4; } break; case 2: /* 2nd pass : every eighth row starting from 4 */ context->curY += 8; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 2; } break; case 3: /* 3rd pass : every fourth row starting from 2 */ context->curY += 4; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 1; } break; case 4: /* 4th pass : every odd row */ context->curY += 2; break; } #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width; context->frbuff_p.p8 = context->line_p.p8 + i->posX; #else context->frbuff_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ #ifndef NGIFLIB_INDEXED_ONLY } else { #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width; context->frbuff_p.p32 = context->line_p.p32 + i->posX; #else context->frbuff_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } #endif /* NGIFLIB_INDEXED_ONLY */ } n -= tocopy; } } /* * u16 GetGifWord(struct ngiflib_img * i); * Renvoie un code LZW (taille variable) */ static u16 GetGifWord(struct ngiflib_img * i, struct ngiflib_decode_context * context) { u16 r; int bits_todo; u16 newbyte; bits_todo = (int)context->nbbit - (int)context->restbits; if( bits_todo <= 0) { /* nbbit <= restbits */ r = context->lbyte; context->restbits -= context->nbbit; context->lbyte >>= context->nbbit; } else if( bits_todo > 8 ) { /* nbbit > restbits + 8 */ if(context->restbyte >= 2) { context->restbyte -= 2; r = *context->srcbyte++; } else { if(context->restbyte == 0) { context->restbyte = GetByte(i->parent); #if defined(DEBUG) && !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "restbyte = %02X\n", context->restbyte); #endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */ GetByteStr(i->parent, context->byte_buffer, context->restbyte); context->srcbyte = context->byte_buffer; } r = *context->srcbyte++; if(--context->restbyte == 0) { context->restbyte = GetByte(i->parent); #if defined(DEBUG) && !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "restbyte = %02X\n", context->restbyte); #endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */ GetByteStr(i->parent, context->byte_buffer, context->restbyte); context->srcbyte = context->byte_buffer; } context->restbyte--; } newbyte = *context->srcbyte++; r |= newbyte << 8; r = (r << context->restbits) | context->lbyte; context->restbits = 16 - bits_todo; context->lbyte = newbyte >> (bits_todo - 8); } else /*if( bits_todo > 0 )*/ { /* nbbit > restbits */ if(context->restbyte == 0) { context->restbyte = GetByte(i->parent); #if defined(DEBUG) && !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "restbyte = %02X\n", context->restbyte); #endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */ GetByteStr(i->parent, context->byte_buffer, context->restbyte); context->srcbyte = context->byte_buffer; } newbyte = *context->srcbyte++; context->restbyte--; r = (newbyte << context->restbits) | context->lbyte; context->restbits = 8 - bits_todo; context->lbyte = newbyte >> bits_todo; } return (r & context->max); /* applique le bon masque pour eliminer les bits en trop */ } /* ------------------------------------------------ */ static void FillGifBackGround(struct ngiflib_gif * g) { long n = (long)g->width*g->height; #ifndef NGIFLIB_INDEXED_ONLY u32 bg_truecolor; #endif /* NGIFLIB_INDEXED_ONLY */ if((g->frbuff.p8==NULL)||(g->palette==NULL)) return; #ifndef NGIFLIB_INDEXED_ONLY if(g->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ ngiflib_memset(g->frbuff.p8, g->backgroundindex, n); #ifndef NGIFLIB_INDEXED_ONLY } else { u32 * p = g->frbuff.p32; bg_truecolor = GifIndexToTrueColor(g->palette, g->backgroundindex); while(n-->0) *p++ = bg_truecolor; } #endif /* NGIFLIB_INDEXED_ONLY */ } /* ------------------------------------------------ */ int CheckGif(u8 * b) { return (b[0]=='G')&&(b[1]=='I')&&(b[2]=='F')&&(b[3]=='8'); } /* ------------------------------------------------ */ static int DecodeGifImg(struct ngiflib_img * i) { struct ngiflib_decode_context context; long npix; u8 * stackp; u8 * stack_top; u16 clr; u16 eof; u16 free; u16 act_code = 0; u16 old_code = 0; u16 read_byt; u16 ab_prfx[4096]; u8 ab_suffx[4096]; u8 ab_stack[4096]; u8 flags; u8 casspecial = 0; if(!i) return -1; i->posX = GetWord(i->parent); /* offsetX */ i->posY = GetWord(i->parent); /* offsetY */ i->width = GetWord(i->parent); /* SizeX */ i->height = GetWord(i->parent); /* SizeY */ if((i->width > i->parent->width) || (i->height > i->parent->height)) { #if !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "*** ERROR *** Image bigger than global GIF canvas !\n"); #endif return -1; } if((i->posX + i->width) > i->parent->width) { #if !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "*** WARNING *** Adjusting X position\n"); #endif i->posX = i->parent->width - i->width; } if((i->posY + i->height) > i->parent->height) { #if !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "*** WARNING *** Adjusting Y position\n"); #endif i->posY = i->parent->height - i->height; } context.Xtogo = i->width; context.curY = i->posY; #ifdef NGIFLIB_INDEXED_ONLY #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width; context.frbuff_p.p8 = context.line_p.p8 + i->posX; #else context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ #else if(i->parent->mode & NGIFLIB_MODE_INDEXED) { #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width; context.frbuff_p.p8 = context.line_p.p8 + i->posX; #else context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } else { #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width; context.frbuff_p.p32 = context.line_p.p32 + i->posX; #else context.frbuff_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } #endif /* NGIFLIB_INDEXED_ONLY */ npix = (long)i->width * i->height; flags = GetByte(i->parent); i->interlaced = (flags & 64) >> 6; context.pass = i->interlaced ? 1 : 0; i->sort_flag = (flags & 32) >> 5; /* is local palette sorted by color frequency ? */ i->localpalbits = (flags & 7) + 1; if(flags&128) { /* palette locale */ int k; int localpalsize = 1 << i->localpalbits; #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "Local palette\n"); #endif /* !defined(NGIFLIB_NO_FILE) */ i->palette = (struct ngiflib_rgb *)ngiflib_malloc(sizeof(struct ngiflib_rgb)*localpalsize); for(k=0; k<localpalsize; k++) { i->palette[k].r = GetByte(i->parent); i->palette[k].g = GetByte(i->parent); i->palette[k].b = GetByte(i->parent); } #ifdef NGIFLIB_ENABLE_CALLBACKS if(i->parent->palette_cb) i->parent->palette_cb(i->parent, i->palette, localpalsize); #endif /* NGIFLIB_ENABLE_CALLBACKS */ } else { i->palette = i->parent->palette; i->localpalbits = i->parent->imgbits; } i->ncolors = 1 << i->localpalbits; i->imgbits = GetByte(i->parent); /* LZW Minimum Code Size */ if (i->imgbits > 11) { #if !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "*** ERROR *** Invalid LZW Minimum Code Size : %d\n", (int)i->imgbits); #endif return -1; } #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) { if(i->interlaced) fprintf(i->parent->log, "interlaced "); fprintf(i->parent->log, "img pos(%hu,%hu) size %hux%hu palbits=%hhu imgbits=%hhu ncolors=%hu\n", i->posX, i->posY, i->width, i->height, i->localpalbits, i->imgbits, i->ncolors); } #endif /* !defined(NGIFLIB_NO_FILE) */ if(i->imgbits==1) { /* fix for 1bit images ? */ i->imgbits = 2; } clr = 1 << i->imgbits; eof = clr + 1; free = clr + 2; context.nbbit = i->imgbits + 1; context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */ stackp = stack_top = ab_stack + 4096; context.restbits = 0; /* initialise le "buffer" de lecture */ context.restbyte = 0; /* des codes LZW */ context.lbyte = 0; for(;;) { act_code = GetGifWord(i, &context); if(act_code==eof) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "End of image code\n"); #endif /* !defined(NGIFLIB_NO_FILE) */ return 0; } if(npix==0) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "assez de pixels, On se casse !\n"); #endif /* !defined(NGIFLIB_NO_FILE) */ return 1; } if(act_code==clr) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "Code clear (%hu) (free=%hu) npix=%ld\n", clr, free, npix); #endif /* !defined(NGIFLIB_NO_FILE) */ /* clear */ free = clr + 2; context.nbbit = i->imgbits + 1; context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */ act_code = GetGifWord(i, &context); /* the first code after the clear code is concrete */ if (act_code >= clr) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "Invalid code %hu just after clear(%hu) !\n", act_code, clr); #endif /* !defined(NGIFLIB_NO_FILE) */ return -1; } casspecial = (u8)act_code; old_code = act_code; if(npix > 0) WritePixel(i, &context, casspecial); npix--; } else if(act_code > free) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "Invalid code %hu (free=%hu) !\n", act_code, free); #endif /* !defined(NGIFLIB_NO_FILE) */ return -1; } else { read_byt = act_code; if(act_code == free) { /* code pas encore dans alphabet */ /* printf("Code pas dans alphabet : %d>=%d push %d\n", act_code, free, casspecial); */ *(--stackp) = casspecial; /* dernier debut de chaine ! */ act_code = old_code; } /* printf("actcode=%d\n", act_code); */ while(act_code > clr) { /* code non concret */ /* fillstackloop empile les suffixes ! */ *(--stackp) = ab_suffx[act_code]; act_code = ab_prfx[act_code]; /* prefixe */ } /* act_code est concret */ casspecial = (u8)act_code; /* dernier debut de chaine ! */ *(--stackp) = casspecial; /* push on stack */ if(npix >= (stack_top - stackp)) { WritePixels(i, &context, stackp, stack_top - stackp); /* unstack all pixels at once */ } else if(npix > 0) { /* "pixel overflow" */ WritePixels(i, &context, stackp, npix); } npix -= (stack_top - stackp); stackp = stack_top; /* putchar('\n'); */ if(free < 4096) { /* la taille du dico est 4096 max ! */ ab_prfx[free] = old_code; ab_suffx[free] = (u8)act_code; free++; if((free > context.max) && (context.nbbit < 12)) { context.nbbit++; /* 1 bit de plus pour les codes LZW */ context.max += context.max + 1; } } old_code = read_byt; } } return 0; } /* ------------------------------------------------ * int LoadGif(struct ngiflib_gif *); * s'assurer que nimg=0 au depart ! * retourne : * 0 si GIF termin * un nombre negatif si ERREUR * 1 si image Decode * rappeler pour decoder les images suivantes * ------------------------------------------------ */ int LoadGif(struct ngiflib_gif * g) { struct ngiflib_gce gce; u8 sign; u8 tmp; int i; if(!g) return -1; gce.gce_present = 0; if(g->nimg==0) { GetByteStr(g, g->signature, 6); g->signature[6] = '\0'; if( g->signature[0] != 'G' || g->signature[1] != 'I' || g->signature[2] != 'F' || g->signature[3] != '8') { return -1; } #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "%s\n", g->signature); #endif /* !defined(NGIFLIB_NO_FILE) */ g->width = GetWord(g); g->height = GetWord(g); /* allocate frame buffer */ #ifndef NGIFLIB_INDEXED_ONLY if((g->mode & NGIFLIB_MODE_INDEXED)==0) g->frbuff.p32 = ngiflib_malloc(4*(long)g->height*(long)g->width); else #endif /* NGIFLIB_INDEXED_ONLY */ g->frbuff.p8 = ngiflib_malloc((long)g->height*(long)g->width); tmp = GetByte(g);/* <Packed Fields> = Global Color Table Flag 1 Bit Color Resolution 3 Bits Sort Flag 1 Bit Size of Global Color Table 3 Bits */ g->colorresolution = ((tmp & 0x70) >> 4) + 1; g->sort_flag = (tmp & 8) >> 3; g->imgbits = (tmp & 7) + 1; /* Global Palette color resolution */ g->ncolors = 1 << g->imgbits; g->backgroundindex = GetByte(g); #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "%hux%hu %hhubits %hu couleurs bg=%hhu\n", g->width, g->height, g->imgbits, g->ncolors, g->backgroundindex); #endif /* NGIFLIB_INDEXED_ONLY */ g->pixaspectratio = GetByte(g); /* pixel aspect ratio (0 : unspecified) */ if(tmp&0x80) { /* la palette globale suit. */ g->palette = (struct ngiflib_rgb *)ngiflib_malloc(sizeof(struct ngiflib_rgb)*g->ncolors); for(i=0; i<g->ncolors; i++) { g->palette[i].r = GetByte(g); g->palette[i].g = GetByte(g); g->palette[i].b = GetByte(g); #if defined(DEBUG) && !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "%3d %02X %02X %02X\n", i, g->palette[i].r,g->palette[i].g,g->palette[i].b); #endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */ } #ifdef NGIFLIB_ENABLE_CALLBACKS if(g->palette_cb) g->palette_cb(g, g->palette, g->ncolors); #endif /* NGIFLIB_ENABLE_CALLBACKS */ } else { g->palette = NULL; } g->netscape_loop_count = -1; } for(;;) { char appid_auth[11]; u8 id,size; int blockindex; sign = GetByte(g); /* signature du prochain bloc */ #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "BLOCK SIGNATURE 0x%02X '%c'\n", sign, (sign >= 32) ? sign : '.'); #endif /* NGIFLIB_INDEXED_ONLY */ switch(sign) { case 0x3B: /* END OF GIF */ return 0; case '!': /* Extension introducer 0x21 */ id = GetByte(g); blockindex = 0; #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "extension (id=0x%02hhx)\n", id); #endif /* NGIFLIB_NO_FILE */ while( (size = GetByte(g)) ) { u8 ext[256]; GetByteStr(g, ext, size); switch(id) { case 0xF9: /* Graphic Control Extension */ /* The scope of this extension is the first graphic * rendering block to follow. */ gce.gce_present = 1; gce.disposal_method = (ext[0] >> 2) & 7; gce.transparent_flag = ext[0] & 1; gce.user_input_flag = (ext[0] >> 1) & 1; gce.delay_time = ext[1] | (ext[2]<<8); gce.transparent_color = ext[3]; #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "disposal_method=%hhu delay_time=%hu (transp=%hhu)transparent_color=0x%02hhX\n", gce.disposal_method, gce.delay_time, gce.transparent_flag, gce.transparent_color); #endif /* NGIFLIB_INDEXED_ONLY */ /* this propably should be adjusted depending on the disposal_method * of the _previous_ image. */ if(gce.transparent_flag && ((g->nimg == 0) || gce.disposal_method == 2)) { FillGifBackGround(g); } break; case 0xFE: /* Comment Extension. */ #if !defined(NGIFLIB_NO_FILE) if(g->log) { if(blockindex==0) fprintf(g->log, "-------------------- Comment extension --------------------\n"); ext[size] = '\0'; fputs((char *)ext, g->log); } #endif /* NGIFLIB_NO_FILE */ break; case 0xFF: /* application extension */ /* NETSCAPE2.0 extension : * http://www.vurdalakov.net/misc/gif/netscape-looping-application-extension */ if(blockindex==0) { ngiflib_memcpy(appid_auth, ext, 11); #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "---------------- Application extension ---------------\n"); fprintf(g->log, "Application identifier : '%.8s', auth code : %02X %02X %02X (", appid_auth, ext[8], ext[9], ext[10]); fputc((ext[8]<32)?' ':ext[8], g->log); fputc((ext[9]<32)?' ':ext[9], g->log); fputc((ext[10]<32)?' ':ext[10], g->log); fprintf(g->log, ")\n"); } #endif /* NGIFLIB_INDEXED_ONLY */ } else { #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "Datas (as hex) : "); for(i=0; i<size; i++) { fprintf(g->log, "%02x ", ext[i]); } fprintf(g->log, "\nDatas (as text) : '"); for(i=0; i<size; i++) { putc((ext[i]<32)?' ':ext[i], g->log); } fprintf(g->log, "'\n"); } #endif /* NGIFLIB_INDEXED_ONLY */ if(0 == ngiflib_memcmp(appid_auth, "NETSCAPE2.0", 11)) { /* ext[0] : Sub-block ID */ if(ext[0] == 1) { /* 1 : Netscape Looping Extension. */ g->netscape_loop_count = (int)ext[1] | ((int)ext[2] << 8); #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "NETSCAPE loop_count = %d\n", g->netscape_loop_count); } #endif /* NGIFLIB_NO_FILE */ } } } break; case 0x01: /* plain text extension */ #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "Plain text extension blockindex=%d\n", blockindex); for(i=0; i<size; i++) { putc((ext[i]<32)?' ':ext[i], g->log); } putc('\n', g->log); } #endif /* NGIFLIB_INDEXED_ONLY */ break; } blockindex++; } switch(id) { case 0x01: /* plain text extension */ case 0xFE: /* Comment Extension. */ case 0xFF: /* application extension */ #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "-----------------------------------------------------------\n"); } #endif /* NGIFLIB_NO_FILE */ break; } break; case 0x2C: /* Image separator */ if(g->nimg==0) { g->cur_img = ngiflib_malloc(sizeof(struct ngiflib_img)); if(g->cur_img == NULL) return -2; /* memory error */ g->first_img = g->cur_img; } else { g->cur_img->next = ngiflib_malloc(sizeof(struct ngiflib_img)); if(g->cur_img->next == NULL) return -2; /* memory error */ g->cur_img = g->cur_img->next; } ngiflib_memset(g->cur_img, 0, sizeof(struct ngiflib_img)); g->cur_img->parent = g; if(gce.gce_present) { ngiflib_memcpy(&g->cur_img->gce, &gce, sizeof(struct ngiflib_gce)); } else { ngiflib_memset(&g->cur_img->gce, 0, sizeof(struct ngiflib_gce)); } if (DecodeGifImg(g->cur_img) < 0) return -1; g->nimg++; tmp = GetByte(g);/* 0 final */ #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "ZERO TERMINATOR 0x%02X\n", tmp); #endif /* NGIFLIB_INDEXED_ONLY */ return 1; /* image decode */ default: /* unexpected byte */ #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "unexpected signature 0x%02X\n", sign); #endif /* NGIFLIB_INDEXED_ONLY */ return -1; } } } u32 GifIndexToTrueColor(struct ngiflib_rgb * palette, u8 v) { return palette[v].b | (palette[v].g << 8) | (palette[v].r << 16); }
null
#ifndef NGIFLIB_NO_FILE #include <stdio.h> #endif /* NGIFLIB_NO_FILE */ #include "ngiflib.h" /* decodeur GIF en C portable (pas de pb big/little endian) * Thomas BERNARD. janvier 2004. * (c) 2004-2019 Thomas Bernard. All rights reserved */ /* Fonction de debug */ #ifdef DEBUG void fprintf_ngiflib_img(FILE * f, struct ngiflib_img * i) { fprintf(f, " * ngiflib_img @ %p\n", i); fprintf(f, " next = %p\n", i->next); fprintf(f, " parent = %p\n", i->parent); fprintf(f, " palette = %p\n", i->palette); fprintf(f, " %3d couleurs", i->ncolors); if(i->interlaced) fprintf(f, " interlaced"); fprintf(f, "\n taille : %dx%d, pos (%d,%d)\n", i->width, i->height, i->posX, i->posY); fprintf(f, " sort_flag=%x localpalbits=%d\n", i->sort_flag, i->localpalbits); } #endif /* DEBUG */ void GifImgDestroy(struct ngiflib_img * i) { if(i==NULL) return; if(i->next) GifImgDestroy(i->next); if(i->palette && (i->palette != i->parent->palette)) ngiflib_free(i->palette); ngiflib_free(i); } /* Fonction de debug */ #ifdef DEBUG void fprintf_ngiflib_gif(FILE * f, struct ngiflib_gif * g) { struct ngiflib_img * i; fprintf(f, "* ngiflib_gif @ %p %s\n", g, g->signature); fprintf(f, " %dx%d, %d bits, %d couleurs\n", g->width, g->height, g->imgbits, g->ncolors); fprintf(f, " palette = %p, backgroundcolorindex %d\n", g->palette, g->backgroundindex); fprintf(f, " pixelaspectratio = %d\n", g->pixaspectratio); fprintf(f, " frbuff = %p\n", g->frbuff.p8); fprintf(f, " cur_img = %p\n", g->cur_img); fprintf(f, " %d images :\n", g->nimg); i = g->first_img; while(i) { fprintf_ngiflib_img(f, i); i = i->next; } } #endif /* DEBUG */ void GifDestroy(struct ngiflib_gif * g) { if(g==NULL) return; GifImgDestroy(g->first_img); if(g->palette) ngiflib_free(g->palette); if(g->frbuff.p8) ngiflib_free(g->frbuff.p8); ngiflib_free(g); } /* u8 GetByte(struct ngiflib_gif * g); * fonction qui renvoie un octet du fichier .gif * on pourait optimiser en faisant 2 fonctions. */ static u8 GetByte(struct ngiflib_gif * g) { #ifndef NGIFLIB_NO_FILE if(g->mode & NGIFLIB_MODE_FROM_MEM) { #endif /* NGIFLIB_NO_FILE */ return *(g->input.bytes++); #ifndef NGIFLIB_NO_FILE } else { return (u8)(getc(g->input.file)); } #endif /* NGIFLIB_NO_FILE */ } /* u16 GetWord() * Renvoie un mot de 16bits * N'est pas influencee par l'endianess du CPU ! */ static u16 GetWord(struct ngiflib_gif * g) { u16 r = (u16)GetByte(g); r |= ((u16)GetByte(g) << 8); return r; } /* int GetByteStr(struct ngiflib_gif * g, u8 * p, int n); * prend en argument un pointeur sur la destination * et le nombre d'octet a lire. * Renvoie 0 si l'operation a reussi, -1 sinon. */ static int GetByteStr(struct ngiflib_gif * g, u8 * p, int n) { if(!p) return -1; #ifndef NGIFLIB_NO_FILE if(g->mode & NGIFLIB_MODE_FROM_MEM) { #endif /* NGIFLIB_NO_FILE */ ngiflib_memcpy(p, g->input.bytes, n); g->input.bytes += n; return 0; #ifndef NGIFLIB_NO_FILE } else { size_t read; read = fread(p, 1, n, g->input.file); return ((int)read == n) ? 0 : -1; } #endif /* NGIFLIB_NO_FILE */ } /* void WritePixel(struct ngiflib_img * i, u8 v); * ecrit le pixel de valeur v dans le frame buffer */ static void WritePixel(struct ngiflib_img * i, struct ngiflib_decode_context * context, u8 v) { struct ngiflib_gif * p = i->parent; if(v!=i->gce.transparent_color || !i->gce.transparent_flag) { #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ *context->frbuff_p.p8 = v; #ifndef NGIFLIB_INDEXED_ONLY } else *context->frbuff_p.p32 = GifIndexToTrueColor(i->palette, v); #endif /* NGIFLIB_INDEXED_ONLY */ } if(--(context->Xtogo) <= 0) { #ifdef NGIFLIB_ENABLE_CALLBACKS if(p->line_cb) p->line_cb(p, context->line_p, context->curY); #endif /* NGIFLIB_ENABLE_CALLBACKS */ context->Xtogo = i->width; switch(context->pass) { case 0: context->curY++; break; case 1: /* 1st pass : every eighth row starting from 0 */ context->curY += 8; break; case 2: /* 2nd pass : every eighth row starting from 4 */ context->curY += 8; break; case 3: /* 3rd pass : every fourth row starting from 2 */ context->curY += 4; break; case 4: /* 4th pass : every odd row */ context->curY += 2; break; } while(context->pass > 0 && context->pass < 4 && context->curY >= p->height) { switch(++context->pass) { case 2: /* 2nd pass : every eighth row starting from 4 */ context->curY = i->posY + 4; break; case 3: /* 3rd pass : every fourth row starting from 2 */ context->curY = i->posY + 2; break; case 4: /* 4th pass : every odd row */ context->curY = i->posY + 1; break; } } #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width; context->frbuff_p.p8 = context->line_p.p8 + i->posX; #else context->frbuff_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ #ifndef NGIFLIB_INDEXED_ONLY } else { #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width; context->frbuff_p.p32 = context->line_p.p32 + i->posX; #else context->frbuff_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } #endif /* NGIFLIB_INDEXED_ONLY */ } else { #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ context->frbuff_p.p8++; #ifndef NGIFLIB_INDEXED_ONLY } else { context->frbuff_p.p32++; } #endif /* NGIFLIB_INDEXED_ONLY */ } } /* void WritePixels(struct ngiflib_img * i, const u8 * pixels, u16 n); * ecrit les pixels dans le frame buffer */ static void WritePixels(struct ngiflib_img * i, struct ngiflib_decode_context * context, const u8 * pixels, u16 n) { u16 tocopy; struct ngiflib_gif * p = i->parent; while(n > 0) { tocopy = (context->Xtogo < n) ? context->Xtogo : n; if(!i->gce.transparent_flag) { #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ ngiflib_memcpy(context->frbuff_p.p8, pixels, tocopy); pixels += tocopy; context->frbuff_p.p8 += tocopy; #ifndef NGIFLIB_INDEXED_ONLY } else { int j; for(j = (int)tocopy; j > 0; j--) { *(context->frbuff_p.p32++) = GifIndexToTrueColor(i->palette, *pixels++); } } #endif /* NGIFLIB_INDEXED_ONLY */ } else { int j; #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ for(j = (int)tocopy; j > 0; j--) { if(*pixels != i->gce.transparent_color) *context->frbuff_p.p8 = *pixels; pixels++; context->frbuff_p.p8++; } #ifndef NGIFLIB_INDEXED_ONLY } else { for(j = (int)tocopy; j > 0; j--) { if(*pixels != i->gce.transparent_color) { *context->frbuff_p.p32 = GifIndexToTrueColor(i->palette, *pixels); } pixels++; context->frbuff_p.p32++; } } #endif /* NGIFLIB_INDEXED_ONLY */ } context->Xtogo -= tocopy; if(context->Xtogo == 0) { #ifdef NGIFLIB_ENABLE_CALLBACKS if(p->line_cb) p->line_cb(p, context->line_p, context->curY); #endif /* NGIFLIB_ENABLE_CALLBACKS */ context->Xtogo = i->width; switch(context->pass) { case 0: context->curY++; break; case 1: /* 1st pass : every eighth row starting from 0 */ context->curY += 8; break; case 2: /* 2nd pass : every eighth row starting from 4 */ context->curY += 8; break; case 3: /* 3rd pass : every fourth row starting from 2 */ context->curY += 4; break; case 4: /* 4th pass : every odd row */ context->curY += 2; break; } while(context->pass > 0 && context->pass < 4 && context->curY >= p->height) { switch(++context->pass) { case 2: /* 2nd pass : every eighth row starting from 4 */ context->curY = i->posY + 4; break; case 3: /* 3rd pass : every fourth row starting from 2 */ context->curY = i->posY + 2; break; case 4: /* 4th pass : every odd row */ context->curY = i->posY + 1; break; } } #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width; context->frbuff_p.p8 = context->line_p.p8 + i->posX; #else context->frbuff_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ #ifndef NGIFLIB_INDEXED_ONLY } else { #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width; context->frbuff_p.p32 = context->line_p.p32 + i->posX; #else context->frbuff_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } #endif /* NGIFLIB_INDEXED_ONLY */ } n -= tocopy; } } /* * u16 GetGifWord(struct ngiflib_img * i); * Renvoie un code LZW (taille variable) */ static u16 GetGifWord(struct ngiflib_img * i, struct ngiflib_decode_context * context) { u16 r; int bits_todo; u16 newbyte; bits_todo = (int)context->nbbit - (int)context->restbits; if( bits_todo <= 0) { /* nbbit <= restbits */ r = context->lbyte; context->restbits -= context->nbbit; context->lbyte >>= context->nbbit; } else if( bits_todo > 8 ) { /* nbbit > restbits + 8 */ if(context->restbyte >= 2) { context->restbyte -= 2; r = *context->srcbyte++; } else { if(context->restbyte == 0) { context->restbyte = GetByte(i->parent); #if defined(DEBUG) && !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "restbyte = %02X\n", context->restbyte); #endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */ GetByteStr(i->parent, context->byte_buffer, context->restbyte); context->srcbyte = context->byte_buffer; } r = *context->srcbyte++; if(--context->restbyte == 0) { context->restbyte = GetByte(i->parent); #if defined(DEBUG) && !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "restbyte = %02X\n", context->restbyte); #endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */ GetByteStr(i->parent, context->byte_buffer, context->restbyte); context->srcbyte = context->byte_buffer; } context->restbyte--; } newbyte = *context->srcbyte++; r |= newbyte << 8; r = (r << context->restbits) | context->lbyte; context->restbits = 16 - bits_todo; context->lbyte = newbyte >> (bits_todo - 8); } else /*if( bits_todo > 0 )*/ { /* nbbit > restbits */ if(context->restbyte == 0) { context->restbyte = GetByte(i->parent); #if defined(DEBUG) && !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "restbyte = %02X\n", context->restbyte); #endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */ GetByteStr(i->parent, context->byte_buffer, context->restbyte); context->srcbyte = context->byte_buffer; } newbyte = *context->srcbyte++; context->restbyte--; r = (newbyte << context->restbits) | context->lbyte; context->restbits = 8 - bits_todo; context->lbyte = newbyte >> bits_todo; } return (r & context->max); /* applique le bon masque pour eliminer les bits en trop */ } /* ------------------------------------------------ */ static void FillGifBackGround(struct ngiflib_gif * g) { long n = (long)g->width*g->height; #ifndef NGIFLIB_INDEXED_ONLY u32 bg_truecolor; #endif /* NGIFLIB_INDEXED_ONLY */ if((g->frbuff.p8==NULL)||(g->palette==NULL)) return; #ifndef NGIFLIB_INDEXED_ONLY if(g->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ ngiflib_memset(g->frbuff.p8, g->backgroundindex, n); #ifndef NGIFLIB_INDEXED_ONLY } else { u32 * p = g->frbuff.p32; bg_truecolor = GifIndexToTrueColor(g->palette, g->backgroundindex); while(n-->0) *p++ = bg_truecolor; } #endif /* NGIFLIB_INDEXED_ONLY */ } /* ------------------------------------------------ */ int CheckGif(u8 * b) { return (b[0]=='G')&&(b[1]=='I')&&(b[2]=='F')&&(b[3]=='8'); } /* ------------------------------------------------ */ static int DecodeGifImg(struct ngiflib_img * i) { struct ngiflib_decode_context context; long npix; u8 * stackp; u8 * stack_top; u16 clr; u16 eof; u16 free; u16 act_code = 0; u16 old_code = 0; u16 read_byt; u16 ab_prfx[4096]; u8 ab_suffx[4096]; u8 ab_stack[4096]; u8 flags; u8 casspecial = 0; if(!i) return -1; i->posX = GetWord(i->parent); /* offsetX */ i->posY = GetWord(i->parent); /* offsetY */ i->width = GetWord(i->parent); /* SizeX */ i->height = GetWord(i->parent); /* SizeY */ if((i->width > i->parent->width) || (i->height > i->parent->height)) { #if !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "*** ERROR *** Image bigger than global GIF canvas !\n"); #endif return -1; } if((i->posX + i->width) > i->parent->width) { #if !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "*** WARNING *** Adjusting X position\n"); #endif i->posX = i->parent->width - i->width; } if((i->posY + i->height) > i->parent->height) { #if !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "*** WARNING *** Adjusting Y position\n"); #endif i->posY = i->parent->height - i->height; } context.Xtogo = i->width; context.curY = i->posY; #ifdef NGIFLIB_INDEXED_ONLY #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width; context.frbuff_p.p8 = context.line_p.p8 + i->posX; #else context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ #else if(i->parent->mode & NGIFLIB_MODE_INDEXED) { #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width; context.frbuff_p.p8 = context.line_p.p8 + i->posX; #else context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } else { #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width; context.frbuff_p.p32 = context.line_p.p32 + i->posX; #else context.frbuff_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } #endif /* NGIFLIB_INDEXED_ONLY */ npix = (long)i->width * i->height; flags = GetByte(i->parent); i->interlaced = (flags & 64) >> 6; context.pass = i->interlaced ? 1 : 0; i->sort_flag = (flags & 32) >> 5; /* is local palette sorted by color frequency ? */ i->localpalbits = (flags & 7) + 1; if(flags&128) { /* palette locale */ int k; int localpalsize = 1 << i->localpalbits; #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "Local palette\n"); #endif /* !defined(NGIFLIB_NO_FILE) */ i->palette = (struct ngiflib_rgb *)ngiflib_malloc(sizeof(struct ngiflib_rgb)*localpalsize); for(k=0; k<localpalsize; k++) { i->palette[k].r = GetByte(i->parent); i->palette[k].g = GetByte(i->parent); i->palette[k].b = GetByte(i->parent); } #ifdef NGIFLIB_ENABLE_CALLBACKS if(i->parent->palette_cb) i->parent->palette_cb(i->parent, i->palette, localpalsize); #endif /* NGIFLIB_ENABLE_CALLBACKS */ } else { i->palette = i->parent->palette; i->localpalbits = i->parent->imgbits; } i->ncolors = 1 << i->localpalbits; i->imgbits = GetByte(i->parent); /* LZW Minimum Code Size */ if (i->imgbits > 11) { #if !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, "*** ERROR *** Invalid LZW Minimum Code Size : %d\n", (int)i->imgbits); #endif return -1; } #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) { if(i->interlaced) fprintf(i->parent->log, "interlaced "); fprintf(i->parent->log, "img pos(%hu,%hu) size %hux%hu palbits=%hhu imgbits=%hhu ncolors=%hu\n", i->posX, i->posY, i->width, i->height, i->localpalbits, i->imgbits, i->ncolors); } #endif /* !defined(NGIFLIB_NO_FILE) */ if(i->imgbits==1) { /* fix for 1bit images ? */ i->imgbits = 2; } clr = 1 << i->imgbits; eof = clr + 1; free = clr + 2; context.nbbit = i->imgbits + 1; context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */ stackp = stack_top = ab_stack + 4096; context.restbits = 0; /* initialise le "buffer" de lecture */ context.restbyte = 0; /* des codes LZW */ context.lbyte = 0; for(;;) { act_code = GetGifWord(i, &context); if(act_code==eof) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "End of image code\n"); #endif /* !defined(NGIFLIB_NO_FILE) */ return 0; } if(npix==0) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "assez de pixels, On se casse !\n"); #endif /* !defined(NGIFLIB_NO_FILE) */ return 1; } if(act_code==clr) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "Code clear (%hu) (free=%hu) npix=%ld\n", clr, free, npix); #endif /* !defined(NGIFLIB_NO_FILE) */ /* clear */ free = clr + 2; context.nbbit = i->imgbits + 1; context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */ act_code = GetGifWord(i, &context); /* the first code after the clear code is concrete */ if (act_code >= clr) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "Invalid code %hu just after clear(%hu) !\n", act_code, clr); #endif /* !defined(NGIFLIB_NO_FILE) */ return -1; } casspecial = (u8)act_code; old_code = act_code; if(npix > 0) WritePixel(i, &context, casspecial); npix--; } else if(act_code > free) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, "Invalid code %hu (free=%hu) !\n", act_code, free); #endif /* !defined(NGIFLIB_NO_FILE) */ return -1; } else { read_byt = act_code; if(act_code == free) { /* code pas encore dans alphabet */ /* printf("Code pas dans alphabet : %d>=%d push %d\n", act_code, free, casspecial); */ *(--stackp) = casspecial; /* dernier debut de chaine ! */ act_code = old_code; } /* printf("actcode=%d\n", act_code); */ while(act_code > clr) { /* code non concret */ /* fillstackloop empile les suffixes ! */ *(--stackp) = ab_suffx[act_code]; act_code = ab_prfx[act_code]; /* prefixe */ } /* act_code est concret */ casspecial = (u8)act_code; /* dernier debut de chaine ! */ *(--stackp) = casspecial; /* push on stack */ if(npix >= (stack_top - stackp)) { WritePixels(i, &context, stackp, stack_top - stackp); /* unstack all pixels at once */ } else if(npix > 0) { /* "pixel overflow" */ WritePixels(i, &context, stackp, npix); } npix -= (stack_top - stackp); stackp = stack_top; /* putchar('\n'); */ if(free < 4096) { /* la taille du dico est 4096 max ! */ ab_prfx[free] = old_code; ab_suffx[free] = (u8)act_code; free++; if((free > context.max) && (context.nbbit < 12)) { context.nbbit++; /* 1 bit de plus pour les codes LZW */ context.max += context.max + 1; } } old_code = read_byt; } } return 0; } /* ------------------------------------------------ * int LoadGif(struct ngiflib_gif *); * s'assurer que nimg=0 au depart ! * retourne : * 0 si GIF termin * un nombre negatif si ERREUR * 1 si image Decode * rappeler pour decoder les images suivantes * ------------------------------------------------ */ int LoadGif(struct ngiflib_gif * g) { struct ngiflib_gce gce; u8 sign; u8 tmp; int i; if(!g) return -1; gce.gce_present = 0; if(g->nimg==0) { GetByteStr(g, g->signature, 6); g->signature[6] = '\0'; if( g->signature[0] != 'G' || g->signature[1] != 'I' || g->signature[2] != 'F' || g->signature[3] != '8') { return -1; } #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "%s\n", g->signature); #endif /* !defined(NGIFLIB_NO_FILE) */ g->width = GetWord(g); g->height = GetWord(g); /* allocate frame buffer */ #ifndef NGIFLIB_INDEXED_ONLY if((g->mode & NGIFLIB_MODE_INDEXED)==0) g->frbuff.p32 = ngiflib_malloc(4*(long)g->height*(long)g->width); else #endif /* NGIFLIB_INDEXED_ONLY */ g->frbuff.p8 = ngiflib_malloc((long)g->height*(long)g->width); tmp = GetByte(g);/* <Packed Fields> = Global Color Table Flag 1 Bit Color Resolution 3 Bits Sort Flag 1 Bit Size of Global Color Table 3 Bits */ g->colorresolution = ((tmp & 0x70) >> 4) + 1; g->sort_flag = (tmp & 8) >> 3; g->imgbits = (tmp & 7) + 1; /* Global Palette color resolution */ g->ncolors = 1 << g->imgbits; g->backgroundindex = GetByte(g); #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "%hux%hu %hhubits %hu couleurs bg=%hhu\n", g->width, g->height, g->imgbits, g->ncolors, g->backgroundindex); #endif /* NGIFLIB_INDEXED_ONLY */ g->pixaspectratio = GetByte(g); /* pixel aspect ratio (0 : unspecified) */ if(tmp&0x80) { /* la palette globale suit. */ g->palette = (struct ngiflib_rgb *)ngiflib_malloc(sizeof(struct ngiflib_rgb)*g->ncolors); for(i=0; i<g->ncolors; i++) { g->palette[i].r = GetByte(g); g->palette[i].g = GetByte(g); g->palette[i].b = GetByte(g); #if defined(DEBUG) && !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "%3d %02X %02X %02X\n", i, g->palette[i].r,g->palette[i].g,g->palette[i].b); #endif /* defined(DEBUG) && !defined(NGIFLIB_NO_FILE) */ } #ifdef NGIFLIB_ENABLE_CALLBACKS if(g->palette_cb) g->palette_cb(g, g->palette, g->ncolors); #endif /* NGIFLIB_ENABLE_CALLBACKS */ } else { g->palette = NULL; } g->netscape_loop_count = -1; } for(;;) { char appid_auth[11]; u8 id,size; int blockindex; sign = GetByte(g); /* signature du prochain bloc */ #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "BLOCK SIGNATURE 0x%02X '%c'\n", sign, (sign >= 32) ? sign : '.'); #endif /* NGIFLIB_INDEXED_ONLY */ switch(sign) { case 0x3B: /* END OF GIF */ return 0; case '!': /* Extension introducer 0x21 */ id = GetByte(g); blockindex = 0; #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "extension (id=0x%02hhx)\n", id); #endif /* NGIFLIB_NO_FILE */ while( (size = GetByte(g)) ) { u8 ext[256]; GetByteStr(g, ext, size); switch(id) { case 0xF9: /* Graphic Control Extension */ /* The scope of this extension is the first graphic * rendering block to follow. */ gce.gce_present = 1; gce.disposal_method = (ext[0] >> 2) & 7; gce.transparent_flag = ext[0] & 1; gce.user_input_flag = (ext[0] >> 1) & 1; gce.delay_time = ext[1] | (ext[2]<<8); gce.transparent_color = ext[3]; #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "disposal_method=%hhu delay_time=%hu (transp=%hhu)transparent_color=0x%02hhX\n", gce.disposal_method, gce.delay_time, gce.transparent_flag, gce.transparent_color); #endif /* NGIFLIB_INDEXED_ONLY */ /* this propably should be adjusted depending on the disposal_method * of the _previous_ image. */ if(gce.transparent_flag && ((g->nimg == 0) || gce.disposal_method == 2)) { FillGifBackGround(g); } break; case 0xFE: /* Comment Extension. */ #if !defined(NGIFLIB_NO_FILE) if(g->log) { if(blockindex==0) fprintf(g->log, "-------------------- Comment extension --------------------\n"); ext[size] = '\0'; fputs((char *)ext, g->log); } #endif /* NGIFLIB_NO_FILE */ break; case 0xFF: /* application extension */ /* NETSCAPE2.0 extension : * http://www.vurdalakov.net/misc/gif/netscape-looping-application-extension */ if(blockindex==0) { ngiflib_memcpy(appid_auth, ext, 11); #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "---------------- Application extension ---------------\n"); fprintf(g->log, "Application identifier : '%.8s', auth code : %02X %02X %02X (", appid_auth, ext[8], ext[9], ext[10]); fputc((ext[8]<32)?' ':ext[8], g->log); fputc((ext[9]<32)?' ':ext[9], g->log); fputc((ext[10]<32)?' ':ext[10], g->log); fprintf(g->log, ")\n"); } #endif /* NGIFLIB_INDEXED_ONLY */ } else { #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "Datas (as hex) : "); for(i=0; i<size; i++) { fprintf(g->log, "%02x ", ext[i]); } fprintf(g->log, "\nDatas (as text) : '"); for(i=0; i<size; i++) { putc((ext[i]<32)?' ':ext[i], g->log); } fprintf(g->log, "'\n"); } #endif /* NGIFLIB_INDEXED_ONLY */ if(0 == ngiflib_memcmp(appid_auth, "NETSCAPE2.0", 11)) { /* ext[0] : Sub-block ID */ if(ext[0] == 1) { /* 1 : Netscape Looping Extension. */ g->netscape_loop_count = (int)ext[1] | ((int)ext[2] << 8); #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "NETSCAPE loop_count = %d\n", g->netscape_loop_count); } #endif /* NGIFLIB_NO_FILE */ } } } break; case 0x01: /* plain text extension */ #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "Plain text extension blockindex=%d\n", blockindex); for(i=0; i<size; i++) { putc((ext[i]<32)?' ':ext[i], g->log); } putc('\n', g->log); } #endif /* NGIFLIB_INDEXED_ONLY */ break; } blockindex++; } switch(id) { case 0x01: /* plain text extension */ case 0xFE: /* Comment Extension. */ case 0xFF: /* application extension */ #if !defined(NGIFLIB_NO_FILE) if(g->log) { fprintf(g->log, "-----------------------------------------------------------\n"); } #endif /* NGIFLIB_NO_FILE */ break; } break; case 0x2C: /* Image separator */ if(g->nimg==0) { g->cur_img = ngiflib_malloc(sizeof(struct ngiflib_img)); if(g->cur_img == NULL) return -2; /* memory error */ g->first_img = g->cur_img; } else { g->cur_img->next = ngiflib_malloc(sizeof(struct ngiflib_img)); if(g->cur_img->next == NULL) return -2; /* memory error */ g->cur_img = g->cur_img->next; } ngiflib_memset(g->cur_img, 0, sizeof(struct ngiflib_img)); g->cur_img->parent = g; if(gce.gce_present) { ngiflib_memcpy(&g->cur_img->gce, &gce, sizeof(struct ngiflib_gce)); } else { ngiflib_memset(&g->cur_img->gce, 0, sizeof(struct ngiflib_gce)); } if (DecodeGifImg(g->cur_img) < 0) return -1; g->nimg++; tmp = GetByte(g);/* 0 final */ #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "ZERO TERMINATOR 0x%02X\n", tmp); #endif /* NGIFLIB_INDEXED_ONLY */ return 1; /* image decode */ default: /* unexpected byte */ #if !defined(NGIFLIB_NO_FILE) if(g->log) fprintf(g->log, "unexpected signature 0x%02X\n", sign); #endif /* NGIFLIB_INDEXED_ONLY */ return -1; } } } u32 GifIndexToTrueColor(struct ngiflib_rgb * palette, u8 v) { return palette[v].b | (palette[v].g << 8) | (palette[v].r << 16); }
null
144
CWE-787
CVE-2019-17358
<?php /* +-------------------------------------------------------------------------+ | Copyright (C) 2004-2019 The Cacti Group | | | | This program is free software; you can redistribute it and/or | | modify it under the terms of the GNU General Public License | | as published by the Free Software Foundation; either version 2 | | of the License, or (at your option) any later version. | | | | This program is distributed in the hope that it will be useful, | | but WITHOUT ANY WARRANTY; without even the implied warranty of | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | | GNU General Public License for more details. | +-------------------------------------------------------------------------+ | Cacti: The Complete RRDtool-based Graphing Solution | +-------------------------------------------------------------------------+ | This code is designed, written, and maintained by the Cacti Group. See | | about.php and/or the AUTHORS file for specific developer information. | +-------------------------------------------------------------------------+ | http://www.cacti.net/ | +-------------------------------------------------------------------------+ */ /* title_trim - takes a string of text, truncates it to $max_length and appends three periods onto the end @arg $text - the string to evaluate @arg $max_length - the maximum number of characters the string can contain before it is truncated @returns - the truncated string if len($text) is greater than $max_length, else the original string */ function title_trim($text, $max_length) { if (strlen($text) > $max_length) { return mb_substr($text, 0, $max_length) . '...'; } else { return $text; } } /* filter_value - a quick way to highlight text in a table from general filtering @arg $text - the string to filter @arg $filter - the search term to filter for @arg $href - the href if you wish to have an anchor returned @returns - the filtered string */ function filter_value($value, $filter, $href = '') { static $charset; if ($charset == '') { $charset = ini_get('default_charset'); } if ($charset == '') { $charset = 'UTF-8'; } $value = htmlspecialchars($value, ENT_QUOTES, $charset, false); if ($filter != '') { $value = preg_replace('#(' . $filter . ')#i', "<span class='filteredValue'>\\1</span>", $value); } if ($href != '') { $value = '<a class="linkEditMain" href="' . htmlspecialchars($href, ENT_QUOTES, $charset, false) . '">' . $value . '</a>'; } return $value; } /* set_graph_config_option - deprecated - wrapper to set_user_setting(). @arg $config_name - the name of the configuration setting as specified $settings array @arg $value - the values to be saved @arg $user - the user id, otherwise the session user @returns - void */ function set_graph_config_option($config_name, $value, $user = -1) { set_user_setting($config_name, $value, $user); } /* graph_config_value_exists - deprecated - wrapper to user_setting_exists @arg $config_name - the name of the configuration setting as specified $settings_user array in 'include/global_settings.php' @arg $user_id - the id of the user to check the configuration value for @returns (bool) - true if a value exists, false if a value does not exist */ function graph_config_value_exists($config_name, $user_id) { return user_setting_exists($config_name, $user_id); } /* read_default_graph_config_option - deprecated - wrapper to read_default_user_setting @arg $config_name - the name of the configuration setting as specified $settings array in 'include/global_settings.php' @returns - the default value of the configuration option */ function read_default_graph_config_option($config_name) { return read_default_user_setting($config_name); } /* read_graph_config_option - deprecated - finds the current value of a graph configuration setting @arg $config_name - the name of the configuration setting as specified $settings_user array in 'include/global_settings.php' @returns - the current value of the graph configuration option */ function read_graph_config_option($config_name, $force = false) { return read_user_setting($config_name, false, $force); } /* save_user_setting - sets/updates aLL user settings @arg $config_name - the name of the configuration setting as specified $settings array @arg $value - the values to be saved @arg $user - the user id, otherwise the session user @returns - void */ function save_user_settings($user = -1) { global $settings_user; if ($user == -1 || empty($user)) { $user = $_SESSION['sess_user_id']; } foreach ($settings_user as $tab_short_name => $tab_fields) { foreach ($tab_fields as $field_name => $field_array) { /* Check every field with a numeric default value and reset it to default if the inputted value is not numeric */ if (isset($field_array['default']) && is_numeric($field_array['default']) && !is_numeric(get_nfilter_request_var($field_name))) { set_request_var($field_name, $field_array['default']); } if (isset($field_array['method'])) { if ($field_array['method'] == 'checkbox') { set_user_setting($field_name, (isset_request_var($field_name) ? 'on' : ''), $user); } elseif ($field_array['method'] == 'checkbox_group') { foreach ($field_array['items'] as $sub_field_name => $sub_field_array) { set_user_setting($sub_field_name, (isset_request_var($sub_field_name) ? 'on' : ''), $user); } } elseif ($field_array['method'] == 'textbox_password') { if (get_nfilter_request_var($field_name) != get_nfilter_request_var($field_name.'_confirm')) { $_SESSION['sess_error_fields'][$field_name] = $field_name; $_SESSION['sess_field_values'][$field_name] = get_nfilter_request_var($field_name); $errors[4] = 4; } elseif (isset_request_var($field_name)) { set_user_setting($field_name, get_nfilter_request_var($field_name), $user); } } elseif ((isset($field_array['items'])) && (is_array($field_array['items']))) { foreach ($field_array['items'] as $sub_field_name => $sub_field_array) { if (isset_request_var($sub_field_name)) { set_user_setting($sub_field_name, get_nfilter_request_var($sub_field_name), $user); } } } elseif (isset_request_var($field_name)) { set_user_setting($field_name, get_nfilter_request_var($field_name), $user); } } } } } /* set_user_setting - sets/updates a user setting with the given value. @arg $config_name - the name of the configuration setting as specified $settings array @arg $value - the values to be saved @arg $user - the user id, otherwise the session user @returns - void */ function set_user_setting($config_name, $value, $user = -1) { global $settings_user; if ($user == -1 && isset($_SESSION['sess_user_id'])) { $user = $_SESSION['sess_user_id']; } if ($user == -1) { cacti_log('Attempt to set user setting \'' . $config_name . '\', with no user id: ' . cacti_debug_backtrace('', false, false, 0, 1), false, 'WARNING:'); } elseif (db_table_exists('settings_user')) { db_execute_prepared('REPLACE INTO settings_user SET user_id = ?, name = ?, value = ?', array($user, $config_name, $value)); unset($_SESSION['sess_user_config_array']); $settings_user[$config_name]['value'] = $value; } } /* user_setting_exists - determines if a value exists for the current user/setting specified @arg $config_name - the name of the configuration setting as specified $settings_user array in 'include/global_settings.php' @arg $user_id - the id of the user to check the configuration value for @returns (bool) - true if a value exists, false if a value does not exist */ function user_setting_exists($config_name, $user_id) { static $user_setting_values = array(); if (!isset($user_setting_values[$config_name])) { $value = 0; if (db_table_exists('settings_user')) { $value = db_fetch_cell_prepared('SELECT COUNT(*) FROM settings_user WHERE name = ? AND user_id = ?', array($config_name, $user_id)); } if ($value !== false && $value > 0) { $user_setting_values[$config_name] = true; } else { $user_setting_values[$config_name] = false; } } return $user_setting_values[$config_name]; } /* clear_user_setting - if a value exists for the current user/setting specified, removes it @arg $config_name - the name of the configuration setting as specified $settings_user array in 'include/global_settings.php' @arg $user_id - the id of the user to remove the configuration value for */ function clear_user_setting($config_name, $user = -1) { global $settings_user; if ($user == -1) { $user = $_SESSION['sess_user_id']; } if (db_table_exists('settings_user')) { db_execute_prepared('DELETE FROM settings_user WHERE name = ? AND user_id = ?', array($config_name, $user)); } unset($_SESSION['sess_user_config_array']); } /* read_default_user_setting - finds the default value of a user configuration setting @arg $config_name - the name of the configuration setting as specified $settings array in 'include/global_settings.php' @returns - the default value of the configuration option */ function read_default_user_setting($config_name) { global $config, $settings_user; foreach ($settings_user as $tab_array) { if (isset($tab_array[$config_name]) && isset($tab_array[$config_name]['default'])) { return $tab_array[$config_name]['default']; } else { foreach ($tab_array as $field_array) { if (isset($field_array['items']) && isset($field_array['items'][$config_name]) && isset($field_array['items'][$config_name]['default'])) { return $field_array['items'][$config_name]['default']; } } } } } /* read_user_setting - finds the current value of a graph configuration setting @arg $config_name - the name of the configuration setting as specified $settings_user array in 'include/global_settings.php' @arg $default - the default value is none is set @arg $force - pull the data from the database if true ignoring session @arg $user - assume this user's identity @returns - the current value of the user setting */ function read_user_setting($config_name, $default = false, $force = false, $user = 0) { global $config; /* users must have cacti user auth turned on to use this, or the guest account must be active */ if ($user == 0 && isset($_SESSION['sess_user_id'])) { $effective_uid = $_SESSION['sess_user_id']; } elseif (read_config_option('auth_method') == 0 || $user > 0) { /* first attempt to get the db setting for guest */ if ($user == 0) { $effective_uid = db_fetch_cell("SELECT user_auth.id FROM settings INNER JOIN user_auth ON user_auth.username = settings.value WHERE settings.name = 'guest_user'"); if ($effective_uid == '') { $effective_uid = 0; } } else { $effective_uid = $user; } $db_setting = false; if (db_table_exists('settings_user')) { $db_setting = db_fetch_row_prepared('SELECT value FROM settings_user WHERE name = ? AND user_id = ?', array($config_name, $effective_uid)); } if (cacti_sizeof($db_setting)) { return $db_setting['value']; } elseif ($default !== false) { return $default; } else { return read_default_user_setting($config_name); } } else { $effective_uid = 0; } if (!$force) { if (isset($_SESSION['sess_user_config_array'])) { $user_config_array = $_SESSION['sess_user_config_array']; } } if (!isset($user_config_array[$config_name])) { $db_setting = false; if (db_table_exists('settings_user')) { $db_setting = db_fetch_row_prepared('SELECT value FROM settings_user WHERE name = ? AND user_id = ?', array($config_name, $effective_uid)); } if (cacti_sizeof($db_setting)) { $user_config_array[$config_name] = $db_setting['value']; } elseif ($default !== false) { $user_config_array[$config_name] = $default; } else { $user_config_array[$config_name] = read_default_user_setting($config_name); } if (isset($_SESSION)) { $_SESSION['sess_user_config_array'] = $user_config_array; } else { $config['config_user_settings_array'] = $user_config_array; } } return $user_config_array[$config_name]; } /* set_config_option - sets/updates a cacti config option with the given value. @arg $config_name - the name of the configuration setting as specified $settings array @arg $value - the values to be saved @returns - void */ function set_config_option($config_name, $value) { global $config; db_execute_prepared('REPLACE INTO settings SET name = ?, value = ?', array($config_name, $value)); $config_array = array(); if (isset($_SESSION['sess_config_array'])) { $config_array = $_SESSION['sess_config_array']; } elseif (isset($config['config_options_array'])) { $config_array = $config['config_options_array']; } $config_array[$config_name] = $value; // Store the array back for later retrieval if (isset($_SESSION)) { $_SESSION['sess_config_array'] = $config_array; } else { $config['config_options_array'] = $config_array; } if (!empty($config['DEBUG_SET_CONFIG_OPTION'])) { file_put_contents(sys_get_temp_dir() . '/cacti-option.log', get_debug_prefix() . cacti_debug_backtrace($config_name, false, false, 0, 1) . "\n", FILE_APPEND); } } /* config_value_exists - determines if a value exists for the current user/setting specified @arg $config_name - the name of the configuration setting as specified $settings array in 'include/global_settings.php' @returns (bool) - true if a value exists, false if a value does not exist */ function config_value_exists($config_name) { static $config_values = array(); if (!isset($config_values[$config_name])) { $value = db_fetch_cell_prepared('SELECT COUNT(*) FROM settings WHERE name = ?', array($config_name)); if ($value > 0) { $config_values[$config_name] = true; } else { $config_values[$config_name] = false; } } return $config_values[$config_name]; } /* read_default_config_option - finds the default value of a Cacti configuration setting @arg $config_name - the name of the configuration setting as specified $settings array in 'include/global_settings.php' @returns - the default value of the configuration option */ function read_default_config_option($config_name) { global $config, $settings; if (is_array($settings)) { foreach ($settings as $tab_array) { if (isset($tab_array[$config_name]) && isset($tab_array[$config_name]['default'])) { return $tab_array[$config_name]['default']; } else { foreach ($tab_array as $field_array) { if (isset($field_array['items']) && isset($field_array['items'][$config_name]) && isset($field_array['items'][$config_name]['default'])) { return $field_array['items'][$config_name]['default']; } } } } } } /* read_config_option - finds the current value of a Cacti configuration setting @arg $config_name - the name of the configuration setting as specified $settings array in 'include/global_settings.php' @returns - the current value of the configuration option */ function read_config_option($config_name, $force = false) { global $config, $database_hostname, $database_default, $database_port, $database_sessions; $config_array = array(); if (isset($_SESSION['sess_config_array'])) { $config_array = $_SESSION['sess_config_array']; } elseif (isset($config['config_options_array'])) { $config_array = $config['config_options_array']; } if (!empty($config['DEBUG_READ_CONFIG_OPTION'])) { file_put_contents(sys_get_temp_dir() . '/cacti-option.log', get_debug_prefix() . cacti_debug_backtrace($config_name, false, false, 0, 1) . "\n", FILE_APPEND); } // Do we have a value already stored in the array, or // do we want to make sure we have the latest value // from the database? if (!array_key_exists($config_name, $config_array) || ($force)) { // We need to check against the DB, but lets assume default value // unless we can actually read the DB $value = read_default_config_option($config_name); if (!empty($config['DEBUG_READ_CONFIG_OPTION'])) { file_put_contents(sys_get_temp_dir() . '/cacti-option.log', get_debug_prefix() . " $config_name: " . ' dh: ' . isset($database_hostname) . ' dp: ' . isset($database_port) . ' dd: ' . isset($database_default) . ' ds: ' . isset($database_sessions["$database_hostname:$database_port:$database_default"]) . "\n", FILE_APPEND); if (isset($database_hostname) && isset($database_port) && isset($database_default)) { file_put_contents(sys_get_temp_dir() . '/cacti-option.log', get_debug_prefix() . " $config_name: [$database_hostname:$database_port:$database_default]\n", FILE_APPEND); } } // Are the database variables set, and do we have a connection?? // If we don't, we'll only use the default value without storing // so that we can read the database version later. if (isset($database_hostname) && isset($database_port) && isset($database_default) && isset($database_sessions["$database_hostname:$database_port:$database_default"])) { // Get the database setting $db_setting = db_fetch_row_prepared('SELECT value FROM settings WHERE name = ?', array($config_name), false); // Does the settings exist in the database? if (isset($db_setting['value'])) { // It does? lets use it $value = $db_setting['value']; } // Store whatever value we have in the array $config_array[$config_name] = $value; // Store the array back for later retrieval if (isset($_SESSION)) { $_SESSION['sess_config_array'] = $config_array; } else { $config['config_options_array'] = $config_array; } } } else { // We already have the value stored in the array and // we don't want to force a db read, so use the cached // version $value = $config_array[$config_name]; } return $value; } /* * get_selected_theme - checks the user settings and if the user selected * theme is set, returns it otherwise returns the system default. * * @return - the theme name */ function get_selected_theme() { global $config, $themes; // shortcut if theme is set in session if (isset($_SESSION['selected_theme'])) { if (file_exists($config['base_path'] . '/include/themes/' . $_SESSION['selected_theme'] . '/main.css')) { return $_SESSION['selected_theme']; } } // default to system selected theme $theme = read_config_option('selected_theme'); // check for a pre-1.x cacti being upgraded if ($theme == '' && !db_table_exists('settings_user')) { return 'modern'; } // figure out user defined theme if (isset($_SESSION['sess_user_id'])) { // fetch user defined theme $user_theme = db_fetch_cell_prepared("SELECT value FROM settings_user WHERE name='selected_theme' AND user_id = ?", array($_SESSION['sess_user_id']), '', false); // user has a theme if (! empty($user_theme)) { $theme = $user_theme;; } } if (!file_exists($config['base_path'] . '/include/themes/' . $theme . '/main.css')) { foreach($themes as $t => $name) { if (file_exists($config['base_path'] . '/include/themes/' . $t . '/main.css')) { $theme = $t; db_execute_prepared('UPDATE settings_user SET value = ? WHERE user_id = ? AND name="selected_theme"', array($theme, $_SESSION['sess_user_id'])); break; } } } // update session $_SESSION['selected_theme'] = $theme; return $theme; } /* form_input_validate - validates the value of a form field and Takes the appropriate action if the input is not valid @arg $field_value - the value of the form field @arg $field_name - the name of the $_POST field as specified in the HTML @arg $regexp_match - (optionally) enter a regular expression to match the value against @arg $allow_nulls - (bool) whether to allow an empty string as a value or not @arg $custom_message - (int) the ID of the message to raise upon an error which is defined in the $messages array in 'include/global_arrays.php' @returns - the original $field_value */ function form_input_validate($field_value, $field_name, $regexp_match, $allow_nulls, $custom_message = 3) { global $messages; /* write current values to the "field_values" array so we can retain them */ $_SESSION['sess_field_values'][$field_name] = $field_value; if (($allow_nulls == true) && ($field_value == '')) { return $field_value; } if ($allow_nulls == false && $field_value == '') { if (read_config_option('log_validation') == 'on') { cacti_log("Form Validation Failed: Variable '$field_name' does not allow nulls and variable is null", false); } raise_message($custom_message); $_SESSION['sess_error_fields'][$field_name] = $field_name; } elseif ($regexp_match != '' && !preg_match('/' . $regexp_match . '/', $field_value)) { if (read_config_option('log_validation') == 'on') { cacti_log("Form Validation Failed: Variable '$field_name' with Value '$field_value' Failed REGEX '$regexp_match'", false); } raise_message($custom_message); $_SESSION['sess_error_fields'][$field_name] = $field_name; } return $field_value; } /* check_changed - determines if a request variable has changed between page loads @returns - (bool) true if the value changed between loads */ function check_changed($request, $session) { if ((isset_request_var($request)) && (isset($_SESSION[$session]))) { if (get_nfilter_request_var($request) != $_SESSION[$session]) { return 1; } } } /* is_error_message - finds whether an error message has been raised and has not been outputted to the user @returns - (bool) whether the messages array contains an error or not */ function is_error_message() { global $config, $messages; if (isset($_SESSION['sess_error_fields']) && sizeof($_SESSION['sess_error_fields'])) { return true; } else { return false; } } function get_message_level($current_message) { $current_level = MESSAGE_LEVEL_NONE; if (isset($current_message['level'])) { $current_level = $current_message['level']; } elseif (isset($current_message['type'])) { switch ($current_message['type']) { case 'error': $current_level = MESSAGE_LEVEL_ERROR; break; case 'info': $current_level = MESSAGE_LEVEL_INFO; break; } } return $current_level; } /* get_format_message_instance - finds the level of the current message instance * @arg message array the message instance * @returns - (string) a formatted message */ function get_format_message_instance($current_message) { if (is_array($current_message)) { $fmessage = isset($current_message['message']) ? $current_message['message'] : __esc('Message Not Found.'); } else { $fmessage = $current_message; } $level = get_message_level($current_message); switch ($level) { case MESSAGE_LEVEL_NONE: $message = '<span>' . $fmessage . '</span>'; break; case MESSAGE_LEVEL_INFO: $message = '<span class="deviceUp">' . $fmessage . '</span>'; break; case MESSAGE_LEVEL_WARN: $message = '<span class="deviceWarning">' . $fmessage . '</span>'; break; case MESSAGE_LEVEL_ERROR: $message = '<span class="deviceDown">' . $fmessage . '</span>'; break; case MESSAGE_LEVEL_CSRF: $message = '<span class="deviceDown">' . $fmessage . '</span>'; break; default; $message = '<span class="deviceUnknown">' . $fmessage . '</span>'; break; } return $message; } /* get_message_max_type - finds the message and returns its type @returns - (string) the message type 'info', 'warn', 'error' or 'csrf' */ function get_message_max_type() { global $messages; $level = MESSAGE_LEVEL_NONE; if (isset($_SESSION['sess_messages'])) { if (is_array($_SESSION['sess_messages'])) { foreach ($_SESSION['sess_messages'] as $current_message_id => $current_message) { $current_level = get_message_level($current_message); if ($current_level == MESSAGE_LEVEL_NONE && isset($messages[$current_message_id])) { $current_level = get_message_level($messages[$current_message_id]); } if ($current_level != $level && $level != MESSAGE_LEVEL_NONE) { $level = MESSAGE_LEVEL_MIXED; } else { $level = $current_level; } } } } return $level; } /* raise_message - mark a message to be displayed to the user once display_output_messages() is called @arg $message_id - the ID of the message to raise as defined in $messages in 'include/global_arrays.php' */ function raise_message($message_id, $message = '', $message_level = MESSAGE_LEVEL_NONE) { global $messages, $no_http_headers; // This function should always exist, if not its an invalid install if (function_exists('session_status')) { $need_session = (session_status() == PHP_SESSION_NONE) && (!isset($no_http_headers)); } else { return false; } if (empty($message)) { if (array_key_exists($message_id, $messages)) { $predefined = $messages[$message_id]; if (isset($predefined['message'])) { $message = $predefined['message']; } else { $message = $predefined; } if ($message_level == MESSAGE_LEVEL_NONE) { $message_level = get_message_level($predefined); } } elseif (isset($_SESSION[$message_id])) { $message = $_SESSION[$message_id]; $message_level = MESSAGE_LEVEL_ERROR; } else { $message = __('Message Not Found.'); $message_level = MESSAGE_LEVEL_ERROR; } } if ($need_session) { session_start(); } if (!isset($_SESSION['sess_messages'])) { $_SESSION['sess_messages'] = array(); } $_SESSION['sess_messages'][$message_id] = array('message' => $message, 'level' => $message_level); if ($need_session) { session_write_close(); } } /* display_output_messages - displays all of the cached messages from the raise_message() function and clears the message cache */ function display_output_messages() { global $messages; $omessage = array(); $debug_message = debug_log_return('new_graphs'); if ($debug_message != '') { $omessage['level'] = MESSAGE_LEVEL_NONE; $omessage['message'] = $debug_message; debug_log_clear('new_graphs'); } elseif (isset($_SESSION['sess_messages'])) { if (!is_array($_SESSION['sess_messages'])) { $_SESSION['sess_messages'] = array('custom_error' => array('level' => 3, 'message' => $_SESSION['sess_messages'])); } $omessage['level'] = get_message_max_type(); foreach ($_SESSION['sess_messages'] as $current_message_id => $current_message) { $message = get_format_message_instance($current_message); if (!empty($message)) { $omessage['message'] = (isset($omessage['message']) && $omessage['message'] != '' ? $omessage['message'] . '<br>':'') . $message; } else { cacti_log("ERROR: Cacti Error Message Id '$current_message_id' Not Defined", false, 'WEBUI'); } } } clear_messages(); return json_encode($omessage); } function display_custom_error_message($message) { raise_message('custom_error', $message); } /* clear_messages - clears the message cache */ function clear_messages() { // This function should always exist, if not its an invalid install if (function_exists('session_status')) { $need_session = (session_status() == PHP_SESSION_NONE) && (!isset($no_http_headers)); } else { return false; } if ($need_session) { session_start(); } kill_session_var('sess_messages'); if ($need_session) { session_write_close(); } } /* kill_session_var - kills a session variable using unset() */ function kill_session_var($var_name) { /* register_global = on: reset local settings cache so the user sees the new settings */ unset($_SESSION[$var_name]); /* register_global = off: reset local settings cache so the user sees the new settings */ /* session_unregister is deprecated in PHP 5.3.0, unset is sufficient */ if (version_compare(PHP_VERSION, '5.3.0', '<')) { session_unregister($var_name); } else { unset($var_name); } } /* force_session_data - forces session data into the session if the session was closed for some reason */ function force_session_data() { // This function should always exist, if not its an invalid install if (!function_exists('session_status')) { return false; } elseif (session_status() == PHP_SESSION_NONE) { $data = $_SESSION; session_start(); $_SESSION = $data; session_write_close(); } } /* array_rekey - changes an array in the form: '$arr[0] = array('id' => 23, 'name' => 'blah')' to the form '$arr = array(23 => 'blah')' @arg $array - (array) the original array to manipulate @arg $key - the name of the key @arg $key_value - the name of the key value @returns - the modified array */ function array_rekey($array, $key, $key_value) { $ret_array = array(); if (is_array($array)) { foreach ($array as $item) { $item_key = $item[$key]; if (is_array($key_value)) { foreach ($key_value as $value) { $ret_array[$item_key][$value] = $item[$value]; } } else { $ret_array[$item_key] = $item[$key_value]; } } } return $ret_array; } /* cacti_log_file - returns the log filename */ function cacti_log_file() { global $config; $logfile = read_config_option('path_cactilog'); if ($logfile == '') { $logfile = $config['base_path'] . '/log/cacti.log'; } $config['log_path'] = $logfile; return $logfile; } /* cacti_log - logs a string to Cacti's log file or optionally to the browser @arg $string - the string to append to the log file @arg $output - (bool) whether to output the log line to the browser using print() or not @arg $environ - (string) tells from where the script was called from @arg $level - (int) only log if above the specified log level */ function cacti_log($string, $output = false, $environ = 'CMDPHP', $level = '') { global $config, $database_log; if (!isset($database_log)) { $database_log = false; } $last_log = $database_log; $database_log = false; if (isset($_SERVER['PHP_SELF'])) { $current_file = basename($_SERVER['PHP_SELF']); $dir_name = dirname($_SERVER['PHP_SELF']); } elseif (isset($_SERVER['SCRIPT_NAME'])) { $current_file = basename($_SERVER['SCRIPT_NAME']); $dir_name = dirname($_SERVER['SCRIPT_NAME']); } elseif (isset($_SERVER['SCRIPT_FILENAME'])) { $current_file = basename($_SERVER['SCRIPT_FILENAME']); $dir_name = dirname($_SERVER['SCRIPT_FILENAME']); } else { $current_file = basename(__FILE__); $dir_name = dirname(__FILE__); } $force_level = ''; $debug_files = read_config_option('selective_debug'); if ($debug_files != '') { $files = explode(',', $debug_files); if (array_search($current_file, $files) !== false) { $force_level = POLLER_VERBOSITY_DEBUG; } } if (strpos($dir_name, 'plugins') !== false) { $debug_plugins = read_config_option('selective_plugin_debug'); if ($debug_plugins != '') { $debug_plugins = explode(',', $debug_plugins); foreach($debug_plugins as $myplugin) { if (strpos($dir_name, DIRECTORY_SEPARATOR . $myplugin) !== false) { $force_level = POLLER_VERBOSITY_DEBUG; break; } } } } /* only log if the specific level is reached, developer debug is special low + specific devdbg calls */ if ($force_level == '') { if ($level != '') { $logVerbosity = read_config_option('log_verbosity'); if ($logVerbosity == POLLER_VERBOSITY_DEVDBG) { if ($level != POLLER_VERBOSITY_DEVDBG) { if ($level > POLLER_VERBOSITY_LOW) { $database_log = $last_log; return; } } } elseif ($level > $logVerbosity) { $database_log = $last_log; return; } } } /* fill in the current date for printing in the log */ if (defined('CACTI_DATE_TIME_FORMAT')) { $date = date(CACTI_DATE_TIME_FORMAT); } else { $date = date('Y-m-d H:i:s'); } /* determine how to log data */ $logdestination = read_config_option('log_destination'); $logfile = cacti_log_file(); /* format the message */ if ($environ == 'POLLER') { $prefix = "$date - " . $environ . ': Poller[' . $config['poller_id'] . '] '; } else { $prefix = "$date - " . $environ . ' '; } /* Log to Logfile */ $message = clean_up_lines($string) . PHP_EOL; if (($logdestination == 1 || $logdestination == 2) && read_config_option('log_verbosity') != POLLER_VERBOSITY_NONE) { /* echo the data to the log (append) */ $fp = @fopen($logfile, 'a'); if ($fp) { $message = $prefix . $message; @fwrite($fp, $message); fclose($fp); } } /* Log to Syslog/Eventlog */ /* Syslog is currently Unstable in Win32 */ if ($logdestination == 2 || $logdestination == 3) { $log_type = ''; if (strpos($string, 'ERROR:') !== false) { $log_type = 'err'; } elseif (strpos($string, 'WARNING:') !== false) { $log_type = 'warn'; } elseif (strpos($string, 'STATS:') !== false) { $log_type = 'stat'; } elseif (strpos($string, 'NOTICE:') !== false) { $log_type = 'note'; } if ($log_type != '') { if ($config['cacti_server_os'] == 'win32') { openlog('Cacti', LOG_NDELAY | LOG_PID, LOG_USER); } else { openlog('Cacti', LOG_NDELAY | LOG_PID, LOG_SYSLOG); } if ($log_type == 'err' && read_config_option('log_perror')) { syslog(LOG_CRIT, $environ . ': ' . $string); } elseif ($log_type == 'warn' && read_config_option('log_pwarn')) { syslog(LOG_WARNING, $environ . ': ' . $string); } elseif (($log_type == 'stat' || $log_type == 'note') && read_config_option('log_pstats')) { syslog(LOG_INFO, $environ . ': ' . $string); } closelog(); } } /* print output to standard out if required */ if ($output == true && isset($_SERVER['argv'][0])) { print $message; } $database_log = $last_log; } /* tail_file - Emulates the tail function with PHP native functions. It is used in 0.8.6 to speed the viewing of the Cacti log file, which can be problematic in the 0.8.6 branch. @arg $file_name - (char constant) the name of the file to tail $line_cnt - (int constant) the number of lines to count $message_type - (int constant) the type of message to return $filter - (char) the filtering expression to search for $page_nr - (int) the page we want to show rows for $total_rows - (int) the total number of rows in the logfile */ function tail_file($file_name, $number_of_lines, $message_type = -1, $filter = '', &$page_nr = 1, &$total_rows) { if (!file_exists($file_name)) { touch($file_name); return array(); } if (!is_readable($file_name)) { echo __('Error %s is not readable', $file_name); return array(); } $filter = strtolower($filter); $fp = fopen($file_name, 'r'); /* Count all lines in the logfile */ $total_rows = 0; while (($line = fgets($fp)) !== false) { if (determine_display_log_entry($message_type, $line, $filter)) { ++$total_rows; } } // Reset the page count to 1 if the number of lines is exceeded if (($page_nr - 1) * $number_of_lines > $total_rows) { set_request_var('page', 1); $page_nr = 1; } /* rewind file pointer, to start all over */ rewind($fp); $start = $total_rows - ($page_nr * $number_of_lines); $end = $start + $number_of_lines; if ($start < 0) { $start = 0; } /* load up the lines into an array */ $file_array = array(); $i = 0; while (($line = fgets($fp)) !== false) { $display = determine_display_log_entry($message_type, $line, $filter); if ($display === false) { continue; } if ($i < $start) { ++$i; continue; } if ($i >= $end) { break; } ++$i; $file_array[$i] = $line; } fclose($fp); return $file_array; } /** * Function to determine if we display the line * * @param int $message_type * @param string $line * @param string $filter * @return bool */ function determine_display_log_entry($message_type, $line, $filter) { /* determine if we are to display the line */ switch ($message_type) { case 1: /* stats */ $display = (strpos($line, 'STATS') !== false); break; case 2: /* warnings */ $display = (strpos($line, 'WARN') !== false); break; case 3: /* errors */ $display = (strpos($line, 'ERROR') !== false); break; case 4: /* debug */ $display = (strpos($line, 'DEBUG') !== false && strpos($line, ' SQL ') === false); break; case 5: /* sql calls */ $display = (strpos($line, ' SQL ') !== false); break; default: /* all other lines */ case -1: /* all */ $display = true; break; } /* match any lines that match the search string */ if ($display === true && $filter != '') { if (stripos($line, $filter) !== false) { return $line; } elseif (validate_is_regex($filter) && preg_match('/' . $filter . '/i', $line)) { return $line; } return false; } return $display; } /* update_host_status - updates the host table with information about its status. It will also output to the appropriate log file when an event occurs. @arg $status - (int constant) the status of the host (Up/Down) $host_id - (int) the host ID for the results $hosts - (array) a memory resident host table for speed $ping - (class array) results of the ping command */ function update_host_status($status, $host_id, &$hosts, &$ping, $ping_availability, $print_data_to_stdout) { $issue_log_message = false; $ping_failure_count = read_config_option('ping_failure_count'); $ping_recovery_count = read_config_option('ping_recovery_count'); /* initialize fail and recovery dates correctly */ if ($hosts[$host_id]['status_fail_date'] == ''){ $hosts[$host_id]['status_fail_date'] = '0000-00-00 00:00:00'; } if ($hosts[$host_id]['status_rec_date'] == ''){ $hosts[$host_id]['status_rec_date'] = '0000-00-00 00:00:00'; } if ($status == HOST_DOWN) { /* Set initial date down. BUGFIX */ if (empty($hosts[$host_id]['status_fail_date'])) { $hosts[$host_id]['status_fail_date'] = date('Y-m-d H:i:s'); } /* update total polls, failed polls and availability */ $hosts[$host_id]['failed_polls']++; $hosts[$host_id]['total_polls']++; $hosts[$host_id]['availability'] = 100 * ($hosts[$host_id]['total_polls'] - $hosts[$host_id]['failed_polls']) / $hosts[$host_id]['total_polls']; /* determine the error message to display */ if (($ping_availability == AVAIL_SNMP_AND_PING) || ($ping_availability == AVAIL_SNMP_OR_PING)) { if (($hosts[$host_id]['snmp_community'] == '') && ($hosts[$host_id]['snmp_version'] != 3)) { /* snmp version 1/2 without community string assume SNMP test to be successful due to backward compatibility issues */ $hosts[$host_id]['status_last_error'] = $ping->ping_response; }else { $hosts[$host_id]['status_last_error'] = $ping->snmp_response . ', ' . $ping->ping_response; } } elseif ($ping_availability == AVAIL_SNMP) { if (($hosts[$host_id]['snmp_community'] == '') && ($hosts[$host_id]['snmp_version'] != 3)) { $hosts[$host_id]['status_last_error'] = 'Device does not require SNMP'; }else { $hosts[$host_id]['status_last_error'] = $ping->snmp_response; } }else { $hosts[$host_id]['status_last_error'] = $ping->ping_response; } /* determine if to send an alert and update remainder of statistics */ if ($hosts[$host_id]['status'] == HOST_UP) { /* increment the event failure count */ $hosts[$host_id]['status_event_count']++; /* if it's time to issue an error message, indicate so */ if ($hosts[$host_id]['status_event_count'] >= $ping_failure_count) { /* host is now down, flag it that way */ $hosts[$host_id]['status'] = HOST_DOWN; $issue_log_message = true; /* update the failure date only if the failure count is 1 */ if ($hosts[$host_id]['status_event_count'] == $ping_failure_count) { $hosts[$host_id]['status_fail_date'] = date('Y-m-d H:i:s'); } /* host is down, but not ready to issue log message */ } else { /* host down for the first time, set event date */ if ($hosts[$host_id]['status_event_count'] == $ping_failure_count) { $hosts[$host_id]['status_fail_date'] = date('Y-m-d H:i:s'); } } /* host is recovering, put back in failed state */ } elseif ($hosts[$host_id]['status'] == HOST_RECOVERING) { $hosts[$host_id]['status_event_count'] = 1; $hosts[$host_id]['status'] = HOST_DOWN; /* host was unknown and now is down */ } elseif ($hosts[$host_id]['status'] == HOST_UNKNOWN) { $hosts[$host_id]['status'] = HOST_DOWN; $hosts[$host_id]['status_event_count'] = 0; } else { $hosts[$host_id]['status_event_count']++; } /* host is up!! */ } else { /* update total polls and availability */ $hosts[$host_id]['total_polls']++; $hosts[$host_id]['availability'] = 100 * ($hosts[$host_id]['total_polls'] - $hosts[$host_id]['failed_polls']) / $hosts[$host_id]['total_polls']; if ((($ping_availability == AVAIL_SNMP_AND_PING) || ($ping_availability == AVAIL_SNMP_OR_PING) || ($ping_availability == AVAIL_SNMP)) && (!is_numeric($ping->snmp_status))) { $ping->snmp_status = 0.000; } if ((($ping_availability == AVAIL_SNMP_AND_PING) || ($ping_availability == AVAIL_SNMP_OR_PING) || ($ping_availability == AVAIL_PING)) && (!is_numeric($ping->ping_status))) { $ping->ping_status = 0.000; } /* determine the ping statistic to set and do so */ if (($ping_availability == AVAIL_SNMP_AND_PING) || ($ping_availability == AVAIL_SNMP_OR_PING)) { if (($hosts[$host_id]['snmp_community'] == '') && ($hosts[$host_id]['snmp_version'] != 3)) { $ping_time = 0.000; }else { /* calculate the average of the two times */ $ping_time = ($ping->snmp_status + $ping->ping_status) / 2; } } elseif ($ping_availability == AVAIL_SNMP) { if (($hosts[$host_id]['snmp_community'] == '') && ($hosts[$host_id]['snmp_version'] != 3)) { $ping_time = 0.000; }else { $ping_time = $ping->snmp_status; } } elseif ($ping_availability == AVAIL_NONE) { $ping_time = 0.000; } else { $ping_time = $ping->ping_status; } /* update times as required */ if (is_numeric($ping_time)) { $hosts[$host_id]['cur_time'] = $ping_time; /* maximum time */ if ($ping_time > $hosts[$host_id]['max_time']) { $hosts[$host_id]['max_time'] = $ping_time; } /* minimum time */ if ($ping_time < $hosts[$host_id]['min_time']) { $hosts[$host_id]['min_time'] = $ping_time; } /* average time */ $hosts[$host_id]['avg_time'] = (($hosts[$host_id]['total_polls']-1-$hosts[$host_id]['failed_polls']) * $hosts[$host_id]['avg_time'] + $ping_time) / ($hosts[$host_id]['total_polls']-$hosts[$host_id]['failed_polls']); } /* the host was down, now it's recovering */ if (($hosts[$host_id]['status'] == HOST_DOWN) || ($hosts[$host_id]['status'] == HOST_RECOVERING )) { /* just up, change to recovering */ if ($hosts[$host_id]['status'] == HOST_DOWN) { $hosts[$host_id]['status'] = HOST_RECOVERING; $hosts[$host_id]['status_event_count'] = 1; } else { $hosts[$host_id]['status_event_count']++; } /* if it's time to issue a recovery message, indicate so */ if ($hosts[$host_id]['status_event_count'] >= $ping_recovery_count) { /* host is up, flag it that way */ $hosts[$host_id]['status'] = HOST_UP; $issue_log_message = true; /* update the recovery date only if the recovery count is 1 */ if ($hosts[$host_id]['status_event_count'] == $ping_recovery_count) { $hosts[$host_id]['status_rec_date'] = date('Y-m-d H:i:s'); } /* reset the event counter */ $hosts[$host_id]['status_event_count'] = 0; /* host is recovering, but not ready to issue log message */ } else { /* host recovering for the first time, set event date */ if ($hosts[$host_id]['status_event_count'] == $ping_recovery_count) { $hosts[$host_id]['status_rec_date'] = date('Y-m-d H:i:s'); } } } else { /* host was unknown and now is up */ $hosts[$host_id]['status'] = HOST_UP; $hosts[$host_id]['status_event_count'] = 0; } } /* if the user wants a flood of information then flood them */ if (($hosts[$host_id]['status'] == HOST_UP) || ($hosts[$host_id]['status'] == HOST_RECOVERING)) { /* log ping result if we are to use a ping for reachability testing */ if ($ping_availability == AVAIL_SNMP_AND_PING) { cacti_log("Device[$host_id] PING: " . $ping->ping_response, $print_data_to_stdout, 'PING', POLLER_VERBOSITY_HIGH); cacti_log("Device[$host_id] SNMP: " . $ping->snmp_response, $print_data_to_stdout, 'PING', POLLER_VERBOSITY_HIGH); } elseif ($ping_availability == AVAIL_SNMP) { if (($hosts[$host_id]['snmp_community'] == '') && ($hosts[$host_id]['snmp_version'] != 3)) { cacti_log("Device[$host_id] SNMP: Device does not require SNMP", $print_data_to_stdout, 'PING', POLLER_VERBOSITY_HIGH); } else { cacti_log("Device[$host_id] SNMP: " . $ping->snmp_response, $print_data_to_stdout, 'PING', POLLER_VERBOSITY_HIGH); } } else { cacti_log("Device[$host_id] PING: " . $ping->ping_response, $print_data_to_stdout, 'PING', POLLER_VERBOSITY_HIGH); } } else { if ($ping_availability == AVAIL_SNMP_AND_PING) { cacti_log("Device[$host_id] PING: " . $ping->ping_response, $print_data_to_stdout, 'PING', POLLER_VERBOSITY_HIGH); cacti_log("Device[$host_id] SNMP: " . $ping->snmp_response, $print_data_to_stdout, 'PING', POLLER_VERBOSITY_HIGH); } elseif ($ping_availability == AVAIL_SNMP) { cacti_log("Device[$host_id] SNMP: " . $ping->snmp_response, $print_data_to_stdout, 'PING', POLLER_VERBOSITY_HIGH); } else { cacti_log("Device[$host_id] PING: " . $ping->ping_response, $print_data_to_stdout, 'PING', POLLER_VERBOSITY_HIGH); } } /* if there is supposed to be an event generated, do it */ if ($issue_log_message) { if ($hosts[$host_id]['status'] == HOST_DOWN) { cacti_log("Device[$host_id] ERROR: HOST EVENT: Device is DOWN Message: " . $hosts[$host_id]['status_last_error'], $print_data_to_stdout); } else { cacti_log("Device[$host_id] NOTICE: HOST EVENT: Device Returned FROM DOWN State: ", $print_data_to_stdout); } } db_execute_prepared('UPDATE host SET status = ?, status_event_count = ?, status_fail_date = ?, status_rec_date = ?, status_last_error = ?, min_time = ?, max_time = ?, cur_time = ?, avg_time = ?, total_polls = ?, failed_polls = ?, availability = ? WHERE hostname = ?', array( $hosts[$host_id]['status'], $hosts[$host_id]['status_event_count'], $hosts[$host_id]['status_fail_date'], $hosts[$host_id]['status_rec_date'], $hosts[$host_id]['status_last_error'], $hosts[$host_id]['min_time'], $hosts[$host_id]['max_time'], $hosts[$host_id]['cur_time'], $hosts[$host_id]['avg_time'], $hosts[$host_id]['total_polls'], $hosts[$host_id]['failed_polls'], $hosts[$host_id]['availability'], $hosts[$host_id]['hostname'] ) ); } /* is_hexadecimal - test whether a string represents a hexadecimal number, ignoring space and tab, and case insensitive. @arg $result - the string to test @arg 1 if the argument is hex, 0 otherwise, and false on error */ function is_hexadecimal($result) { $hexstr = str_replace(array(' ', '-'), ':', trim($result)); $parts = explode(':', $hexstr); foreach($parts as $part) { if (strlen($part) != 2) { return false; } if (ctype_xdigit($part) == false) { return false; } } return true; } /* is_mac_address - determines if the result value is a mac address @arg $result - (string) some string to be evaluated @returns - (bool) either to result is a mac address of not */ function is_mac_address($result) { if (!defined('FILTER_VALIDATE_MAC')) { if (preg_match('/^([0-9a-f]{1,2}[\.:-]){5}([0-9a-f]{1,2})$/i', $result)) { return true; } else { return false; } } else { return filter_var($result, FILTER_VALIDATE_MAC); } } function is_hex_string(&$result) { if ($result == '') { return false; } $compare = strtolower($result); /* strip off the 'Hex:, Hex-, and Hex-STRING:' * Hex- is considered due to the stripping of 'String:' in * lib/snmp.php */ if (substr($compare, 0, 4) == 'hex-') { $check = trim(str_ireplace('hex-', '', $result)); } elseif (substr($compare, 0, 11) == 'hex-string:') { $check = trim(str_ireplace('hex-string:', '', $result)); } else { return false; } $parts = explode(' ', $check); /* assume if something is a hex string it will have a length > 1 */ if (cacti_sizeof($parts) == 1) { return false; } foreach($parts as $part) { if (strlen($part) != 2) { return false; } if (ctype_xdigit($part) == false) { return false; } } $result = $check; return true; } /* prepare_validate_result - determines if the result value is valid or not. If not valid returns a "U" @arg $result - (string) the result from the poll, the result can be modified in the call @returns - (bool) either to result is valid or not */ function prepare_validate_result(&$result) { /* first trim the string */ $result = trim($result, "'\"\n\r"); /* clean off ugly non-numeric data */ if (is_numeric($result)) { return true; } elseif ($result == 'U') { return true; } elseif (is_hexadecimal($result)) { return hexdec($result); } elseif (substr_count($result, ':') || substr_count($result, '!')) { /* looking for name value pairs */ if (substr_count($result, ' ') == 0) { return true; } else { $delim_cnt = 0; if (substr_count($result, ':')) { $delim_cnt = substr_count($result, ':'); } elseif (strstr($result, '!')) { $delim_cnt = substr_count($result, '!'); } $space_cnt = substr_count($result, ' '); return ($space_cnt+1 == $delim_cnt); } } else { $result = strip_alpha($result); if ($result === false) { $result = 'U'; return false; } else { return true; } } } /** strip_alpha - remove non-numeric data from a string and return the numeric part * @arg $string - (char) the string to be evaluated * @returns - either the numeric value or false if not numeric */ function strip_alpha($string) { /* strip all non numeric data */ $string = trim(preg_replace('/[^0-9,.+-]/', '', $string)); /* check the easy cases first */ /* it has no delimiters, and no space, therefore, must be numeric */ if (is_numeric($string) || is_float($string)) { return $string; } else { return false; } } /** get_full_script_path - gets the full path to the script to execute to obtain data for a * given data source. this function does not work on SNMP actions, only script-based actions * @arg $local_data_id - (int) the ID of the data source * @returns - the full script path or (bool) false for an error */ function get_full_script_path($local_data_id) { global $config; $data_source = db_fetch_row_prepared('SELECT ' . SQL_NO_CACHE . ' data_template_data.id, data_template_data.data_input_id, data_input.type_id, data_input.input_string FROM (data_template_data, data_input) WHERE data_template_data.data_input_id = data_input.id AND data_template_data.local_data_id = ?', array($local_data_id)); /* snmp-actions don't have paths */ if (($data_source['type_id'] == DATA_INPUT_TYPE_SNMP) || ($data_source['type_id'] == DATA_INPUT_TYPE_SNMP_QUERY)) { return false; } $data = db_fetch_assoc_prepared("SELECT " . SQL_NO_CACHE . " data_input_fields.data_name, data_input_data.value FROM data_input_fields LEFT JOIN data_input_data ON (data_input_fields.id = data_input_data.data_input_field_id) WHERE data_input_fields.data_input_id = ? AND data_input_data.data_template_data_id = ? AND data_input_fields.input_output = 'in'", array($data_source['data_input_id'], $data_source['id'])); $full_path = $data_source['input_string']; if (cacti_sizeof($data)) { foreach ($data as $item) { $full_path = str_replace('<' . $item['data_name'] . '>', cacti_escapeshellarg($item['value']), $full_path); } } $search = array('<path_cacti>', '<path_snmpget>', '<path_php_binary>'); $replace = array($config['base_path'], read_config_option('path_snmpget'), read_config_option('path_php_binary')); $full_path = str_replace($search, $replace, $full_path); /* sometimes a certain input value will not have anything entered... null out these fields in the input string so we don't mess up the script */ return preg_replace('/(<[A-Za-z0-9_]+>)+/', '', $full_path); } /* get_data_source_item_name - gets the name of a data source item or generates a new one if one does not already exist @arg $data_template_rrd_id - (int) the ID of the data source item @returns - the name of the data source item or an empty string for an error */ function get_data_source_item_name($data_template_rrd_id) { if (empty($data_template_rrd_id)) { return ''; } $data_source = db_fetch_row_prepared('SELECT ' . SQL_NO_CACHE . ' dtr.data_source_name, dtd.name FROM data_template_rrd AS dtr INNER JOIN data_template_data AS dtd ON dtr.local_data_id = dtd.local_data_id WHERE dtr.id = ?', array($data_template_rrd_id) ); /* use the cacti ds name by default or the user defined one, if entered */ if (empty($data_source['data_source_name'])) { /* limit input to 19 characters */ $data_source_name = clean_up_name($data_source['name']); $data_source_name = substr(strtolower($data_source_name), 0, (19-strlen($data_template_rrd_id))) . $data_template_rrd_id; return $data_source_name; } else { return $data_source['data_source_name']; } } /* get_data_source_path - gets the full path to the .rrd file associated with a given data source @arg $local_data_id - (int) the ID of the data source @arg $expand_paths - (bool) whether to expand the <path_rra> variable into its full path or not @returns - the full path to the data source or an empty string for an error */ function get_data_source_path($local_data_id, $expand_paths) { global $config; static $data_source_path_cache = array(); if (empty($local_data_id)) { return ''; } if (isset($data_source_path_cache[$local_data_id])) { return $data_source_path_cache[$local_data_id]; } $data_source = db_fetch_row_prepared('SELECT ' . SQL_NO_CACHE . ' name, data_source_path FROM data_template_data WHERE local_data_id = ?', array($local_data_id)); if (cacti_sizeof($data_source) > 0) { if (empty($data_source['data_source_path'])) { /* no custom path was specified */ $data_source_path = generate_data_source_path($local_data_id); } elseif (!strstr($data_source['data_source_path'], '/')) { $data_source_path = '<path_rra>/' . $data_source['data_source_path']; } else { $data_source_path = $data_source['data_source_path']; } /* whether to show the "actual" path or the <path_rra> variable name (for edit boxes) */ if ($expand_paths == true) { $data_source_path = str_replace('<path_rra>/', $config['rra_path'] . '/', $data_source_path); } $data_source_path_cache[$local_data_id] = $data_source_path; return $data_source_path; } } /* stri_replace - a case insensitive string replace @arg $find - needle @arg $replace - replace needle with this @arg $string - haystack @returns - the original string with '$find' replaced by '$replace' */ function stri_replace($find, $replace, $string) { $parts = explode(strtolower($find), strtolower($string)); $pos = 0; $findLength = strlen($find); foreach ($parts as $key => $part) { $partLength = strlen($part); $parts[$key] = substr($string, $pos, $partLength); $pos += $partLength + $findLength; } return (join($replace, $parts)); } /* clean_up_lines - runs a string through a regular expression designed to remove new lines and the spaces around them @arg $string - the string to modify/clean @returns - the modified string */ function clean_up_lines($string) { return preg_replace('/\s*[\r\n]+\s*/',' ', $string); } /* clean_up_name - runs a string through a series of regular expressions designed to eliminate "bad" characters @arg $string - the string to modify/clean @returns - the modified string */ function clean_up_name($string) { $string = preg_replace('/[\s\.]+/', '_', $string); $string = preg_replace('/[^a-zA-Z0-9_]+/', '', $string); $string = preg_replace('/_{2,}/', '_', $string); return $string; } /* clean_up_file name - runs a string through a series of regular expressions designed to eliminate "bad" characters @arg $string - the string to modify/clean @returns - the modified string */ function clean_up_file_name($string) { $string = preg_replace('/[\s\.]+/', '_', $string); $string = preg_replace('/[^a-zA-Z0-9_-]+/', '', $string); $string = preg_replace('/_{2,}/', '_', $string); return $string; } /* clean_up_path - takes any path and makes sure it contains the correct directory separators based on the current operating system @arg $path - the path to modify @returns - the modified path */ function clean_up_path($path) { global $config; if ($config['cacti_server_os'] == 'win32') { return str_replace('/', "\\", $path); } elseif ($config['cacti_server_os'] == 'unix' || read_config_option('using_cygwin') == 'on' || read_config_option('storage_location')) { return str_replace("\\", '/', $path); } else { return $path; } } /* get_data_source_title - returns the title of a data source without using the title cache @arg $local_data_id - (int) the ID of the data source to get a title for @returns - the data source title */ function get_data_source_title($local_data_id) { $data = db_fetch_row_prepared('SELECT dl.host_id, dl.snmp_query_id, dl.snmp_index, dtd.name FROM data_local AS dl INNER JOIN data_template_data AS dtd ON dtd.local_data_id = dl.id WHERE dl.id = ?', array($local_data_id)); if (cacti_sizeof($data)) { if (strstr($data['name'], '|') !== false && $data['host_id'] > 0) { $data['name'] = substitute_data_input_data($data['name'], '', $local_data_id); return expand_title($data['host_id'], $data['snmp_query_id'], $data['snmp_index'], $data['name']); } else { return $data['name']; } } else { return 'Missing Datasource ' . $local_data_id; } } /* get_device_name - returns the description of the device in cacti host table @arg $host_id - (int) the ID of the device to get a description for @returns - the device name */ function get_device_name($host_id) { return db_fetch_cell_prepared('SELECT description FROM host WHERE id = ?', array($host_id)); } /* get_color - returns the hex color value from the cacti colors table @arg $color_id - (int) the ID of the cacti color @returns - the hex color value */ function get_color($color_id) { return db_fetch_cell_prepared('SELECT hex FROM colors WHERE id = ?', array($color_id)); } /* get_graph_title - returns the title of a graph without using the title cache @arg $local_graph_id - (int) the ID of the graph to get a title for @returns - the graph title */ function get_graph_title($local_graph_id) { $graph = db_fetch_row_prepared('SELECT gl.host_id, gl.snmp_query_id, gl.snmp_index, gtg.local_graph_id, gtg.t_title, gtg.title FROM graph_templates_graph AS gtg INNER JOIN graph_local AS gl ON gtg.local_graph_id = gl.id WHERE gl.id = ?', array($local_graph_id)); if (cacti_sizeof($graph)) { if (strstr($graph['title'], '|') !== false && $graph['host_id'] > 0 && empty($graph['t_title'])) { $graph['title'] = substitute_data_input_data($graph['title'], $graph, 0); return expand_title($graph['host_id'], $graph['snmp_query_id'], $graph['snmp_index'], $graph['title']); } else { return $graph['title']; } } else { return ''; } } /* get_username - returns the username for the selected user @arg $user_id - (int) the ID of the user @returns - the username */ function get_username($user_id) { return db_fetch_cell_prepared('SELECT username FROM user_auth WHERE id = ?', array($user_id)); } /* get_execution_user - returns the username of the running process @returns - the username */ function get_execution_user() { if (function_exists('posix_getpwuid')) { $user_info = posix_getpwuid(posix_geteuid()); return $user_info['name']; } else { return exec('whoami'); } } /* generate_data_source_path - creates a new data source path from scratch using the first data source item name and updates the database with the new value @arg $local_data_id - (int) the ID of the data source to generate a new path for @returns - the new generated path */ function generate_data_source_path($local_data_id) { global $config; /* try any prepend the name with the host description */ $host = db_fetch_row_prepared('SELECT host.id, host.description FROM (host, data_local) WHERE data_local.host_id = host.id AND data_local.id = ? LIMIT 1', array($local_data_id)); $host_name = $host['description']; $host_id = $host['id']; /* put it all together using the local_data_id at the end */ if (read_config_option('extended_paths') == 'on') { $new_path = "<path_rra>/$host_id/$local_data_id.rrd"; } else { if (!empty($host_name)) { $host_part = strtolower(clean_up_file_name($host_name)) . '_'; } /* then try and use the internal DS name to identify it */ $data_source_rrd_name = db_fetch_cell_prepared('SELECT data_source_name FROM data_template_rrd WHERE local_data_id = ? ORDER BY id LIMIT 1', array($local_data_id) ); if (!empty($data_source_rrd_name)) { $ds_part = strtolower(clean_up_file_name($data_source_rrd_name)); } else { $ds_part = 'ds'; } $new_path = "<path_rra>/$host_part$ds_part" . '_' . "$local_data_id.rrd"; } /* update our changes to the db */ db_execute_prepared('UPDATE data_template_data SET data_source_path = ? WHERE local_data_id = ?', array($new_path, $local_data_id)); return $new_path; } /* generate graph_best_cf - takes the requested consolidation function and maps against the list of available consolidation functions for the consolidation functions and returns the most appropriate. Typically, this will be the requested value @arg $data_template_id @arg $requested_cf @arg $ds_step @returns - the best cf to use */ function generate_graph_best_cf($local_data_id, $requested_cf, $ds_step = 60) { static $best_cf; if ($local_data_id > 0) { $first_step = db_fetch_cell_prepared('SELECT rrd_step FROM data_template_data WHERE local_data_id = ?', array($local_data_id)); $avail_cf_functions = get_rrd_cfs($local_data_id); /* hack for odd RRDtool behavior in first RRA */ if ($ds_step == $first_step && isset($avail_cf_functions[1])) { $best_cf = '3'; } elseif (cacti_sizeof($avail_cf_functions)) { /* workaround until we have RRA presets in 0.8.8 */ /* check through the cf's and get the best */ /* if none was found, take the first */ $best_cf = $avail_cf_functions[1]; foreach($avail_cf_functions as $cf) { if ($cf == $requested_cf) { $best_cf = $requested_cf; } } } else { $best_cf = '1'; } } /* if you can not figure it out return average */ return $best_cf; } /* get_rrd_cfs - reads the RRDfile and gets the RRAs stored in it. @arg $local_data_id @returns - array of the CF functions */ function get_rrd_cfs($local_data_id) { global $consolidation_functions; static $rrd_cfs = array(); if (array_key_exists($local_data_id, $rrd_cfs)) { return $rrd_cfs[$local_data_id]; } $cfs = array(); $rrdfile = get_data_source_path($local_data_id, true); $output = @rrdtool_execute("info $rrdfile", false, RRDTOOL_OUTPUT_STDOUT); /* search for * rra[0].cf = 'LAST' * or similar */ if ($output != '') { $output = explode("\n", $output); if (cacti_sizeof($output)) { foreach($output as $line) { if (substr_count($line, '.cf')) { $values = explode('=',$line); if (!in_array(trim($values[1], '" '), $cfs)) { $cfs[] = trim($values[1], '" '); } } } } } $new_cfs = array(); if (cacti_sizeof($cfs)) { foreach($cfs as $cf) { switch($cf) { case 'AVG': case 'AVERAGE': $new_cfs[1] = array_search('AVERAGE', $consolidation_functions); break; case 'MIN': $new_cfs[2] = array_search('MIN', $consolidation_functions); break; case 'MAX': $new_cfs[3] = array_search('MAX', $consolidation_functions); break; case 'LAST': $new_cfs[4] = array_search('LAST', $consolidation_functions); break; } } } $rrd_cfs[$local_data_id] = $new_cfs; return $new_cfs; } /* generate_graph_def_name - takes a number and turns each digit into its letter-based counterpart for RRDtool DEF names (ex 1 -> a, 2 -> b, etc) @arg $graph_item_id - (int) the ID to generate a letter-based representation of @returns - a letter-based representation of the input argument */ function generate_graph_def_name($graph_item_id) { $lookup_table = array('a','b','c','d','e','f','g','h','i','j'); $result = ''; $strValGII = strval($graph_item_id); for ($i=0; $i<strlen($strValGII); $i++) { $result .= $lookup_table{substr($strValGII, $i, 1)}; } if (preg_match('/^(cf|cdef|def)$/', $result)) { return 'zz' . $result; } else { return $result; } } /* generate_data_input_field_sequences - re-numbers the sequences of each field associated with a particular data input method based on its position within the input string @arg $string - the input string that contains the field variables in a certain order @arg $data_input_id - (int) the ID of the data input method */ function generate_data_input_field_sequences($string, $data_input_id) { global $config, $registered_cacti_names; if (preg_match_all('/<([_a-zA-Z0-9]+)>/', $string, $matches)) { $j = 0; for ($i=0; ($i < cacti_count($matches[1])); $i++) { if (in_array($matches[1][$i], $registered_cacti_names) == false) { $j++; db_execute_prepared("UPDATE data_input_fields SET sequence = ? WHERE data_input_id = ? AND input_output IN ('in') AND data_name = ?", array($j, $data_input_id, $matches[1][$i])); } } update_replication_crc(0, 'poller_replicate_data_input_fields_crc'); } } /* move_graph_group - takes a graph group (parent+children) and swaps it with another graph group @arg $graph_template_item_id - (int) the ID of the (parent) graph item that was clicked @arg $graph_group_array - (array) an array containing the graph group to be moved @arg $target_id - (int) the ID of the (parent) graph item of the target group @arg $direction - ('next' or 'previous') whether the graph group is to be swapped with group above or below the current group */ function move_graph_group($graph_template_item_id, $graph_group_array, $target_id, $direction) { $graph_item = db_fetch_row_prepared('SELECT local_graph_id, graph_template_id FROM graph_templates_item WHERE id = ?', array($graph_template_item_id)); if (empty($graph_item['local_graph_id'])) { $sql_where = 'graph_template_id = ' . $graph_item['graph_template_id'] . ' AND local_graph_id = 0'; } else { $sql_where = 'local_graph_id = ' . $graph_item['local_graph_id']; } /* get a list of parent+children of our target group */ $target_graph_group_array = get_graph_group($target_id); /* if this "parent" item has no children, then treat it like a regular gprint */ if (cacti_sizeof($target_graph_group_array) == 0) { if ($direction == 'next') { move_item_down('graph_templates_item', $graph_template_item_id, $sql_where); } elseif ($direction == 'previous') { move_item_up('graph_templates_item', $graph_template_item_id, $sql_where); } return; } /* start the sequence at '1' */ $sequence_counter = 1; $graph_items = db_fetch_assoc_prepared("SELECT id, sequence FROM graph_templates_item WHERE $sql_where ORDER BY sequence"); if (cacti_sizeof($graph_items)) { foreach ($graph_items as $item) { /* check to see if we are at the "target" spot in the loop; if we are, update the sequences and move on */ if ($target_id == $item['id']) { if ($direction == 'next') { $group_array1 = $target_graph_group_array; $group_array2 = $graph_group_array; } elseif ($direction == 'previous') { $group_array1 = $graph_group_array; $group_array2 = $target_graph_group_array; } foreach ($group_array1 as $graph_template_item_id) { db_execute_prepared('UPDATE graph_templates_item SET sequence = ? WHERE id = ?', array($sequence_counter, $graph_template_item_id)); /* propagate to ALL graphs using this template */ if (empty($graph_item['local_graph_id'])) { db_execute_prepared('UPDATE graph_templates_item SET sequence = ? WHERE local_graph_template_item_id = ?', array($sequence_counter, $graph_template_item_id)); } $sequence_counter++; } foreach ($group_array2 as $graph_template_item_id) { db_execute_prepared('UPDATE graph_templates_item SET sequence = ? WHERE id = ?', array($sequence_counter, $graph_template_item_id)); /* propagate to ALL graphs using this template */ if (empty($graph_item['local_graph_id'])) { db_execute_prepared('UPDATE graph_templates_item SET sequence = ? WHERE local_graph_template_item_id = ?', array($sequence_counter, $graph_template_item_id)); } $sequence_counter++; } } /* make sure to "ignore" the items that we handled above */ if ((!isset($graph_group_array[$item['id']])) && (!isset($target_graph_group_array[$item['id']]))) { db_execute_prepared('UPDATE graph_templates_item SET sequence = ? WHERE id = ?', array($sequence_counter, $item['id'])); $sequence_counter++; } } } } /* get_graph_group - returns an array containing each item in the graph group given a single graph item in that group @arg $graph_template_item_id - (int) the ID of the graph item to return the group of @returns - (array) an array containing each item in the graph group */ function get_graph_group($graph_template_item_id) { global $graph_item_types; $graph_item = db_fetch_row_prepared('SELECT graph_type_id, sequence, local_graph_id, graph_template_id FROM graph_templates_item WHERE id = ?', array($graph_template_item_id)); if (empty($graph_item['local_graph_id'])) { $sql_where = 'graph_template_id = ' . $graph_item['graph_template_id'] . ' AND local_graph_id = 0'; } else { $sql_where = 'local_graph_id = ' . $graph_item['local_graph_id']; } /* parents are LINE%, AREA%, and STACK%. If not return */ if (!preg_match('/(LINE|AREA|STACK)/', $graph_item_types[$graph_item['graph_type_id']])) { return array(); } $graph_item_children_array = array(); /* put the parent item in the array as well */ $graph_item_children_array[$graph_template_item_id] = $graph_template_item_id; $graph_items = db_fetch_assoc("SELECT id, graph_type_id, text_format, hard_return FROM graph_templates_item WHERE sequence > " . $graph_item['sequence'] . " AND $sql_where ORDER BY sequence"); $is_hard = false; if (cacti_sizeof($graph_items)) { foreach ($graph_items as $item) { if ($is_hard) { return $graph_item_children_array; } elseif (strstr($graph_item_types[$item['graph_type_id']], 'GPRINT') !== false) { /* a child must be a GPRINT */ $graph_item_children_array[$item['id']] = $item['id']; if ($item['hard_return'] == 'on') { $is_hard = true; } } elseif (strstr($graph_item_types[$item['graph_type_id']], 'COMMENT') !== false) { if (preg_match_all('/\|([0-9]{1,2}):(bits|bytes):(\d):(current|total|max|total_peak|all_max_current|all_max_peak|aggregate_max|aggregate_sum|aggregate_current|aggregate):(\d)?\|/', $item['text_format'], $matches, PREG_SET_ORDER)) { $graph_item_children_array[$item['id']] = $item['id']; } elseif (preg_match_all('/\|sum:(\d|auto):(current|total|atomic):(\d):(\d+|auto)\|/', $item['text_format'], $matches, PREG_SET_ORDER)) { $graph_item_children_array[$item['id']] = $item['id']; } else { /* if not a GPRINT or special COMMENT then get out */ return $graph_item_children_array; } } else { /* if not a GPRINT or special COMMENT then get out */ return $graph_item_children_array; } } } return $graph_item_children_array; } /* get_graph_parent - returns the ID of the next or previous parent graph item id @arg $graph_template_item_id - (int) the ID of the current graph item @arg $direction - ('next' or 'previous') whether to find the next or previous parent @returns - (int) the ID of the next or previous parent graph item id */ function get_graph_parent($graph_template_item_id, $direction) { $graph_item = db_fetch_row_prepared('SELECT sequence, local_graph_id, graph_template_id FROM graph_templates_item WHERE id = ?', array($graph_template_item_id)); if (empty($graph_item['local_graph_id'])) { $sql_where = 'graph_template_id = ' . $graph_item['graph_template_id'] . ' AND local_graph_id = 0'; } else { $sql_where = 'local_graph_id = ' . $graph_item['local_graph_id']; } if ($direction == 'next') { $sql_operator = '>'; $sql_order = 'ASC'; } elseif ($direction == 'previous') { $sql_operator = '<'; $sql_order = 'DESC'; } $next_parent_id = db_fetch_cell("SELECT id FROM graph_templates_item WHERE sequence $sql_operator " . $graph_item['sequence'] . " AND graph_type_id IN (4, 5, 6, 7, 8, 20) AND $sql_where ORDER BY sequence $sql_order LIMIT 1"); if (empty($next_parent_id)) { return 0; } else { return $next_parent_id; } } /* get_item - returns the ID of the next or previous item id @arg $tblname - the table name that contains the target id @arg $field - the field name that contains the target id @arg $startid - (int) the current id @arg $lmt_query - an SQL "where" clause to limit the query @arg $direction - ('next' or 'previous') whether to find the next or previous item id @returns - (int) the ID of the next or previous item id */ function get_item($tblname, $field, $startid, $lmt_query, $direction) { if ($direction == 'next') { $sql_operator = '>'; $sql_order = 'ASC'; } elseif ($direction == 'previous') { $sql_operator = '<'; $sql_order = 'DESC'; } $current_sequence = db_fetch_cell_prepared("SELECT $field FROM $tblname WHERE id = ?", array($startid)); $new_item_id = db_fetch_cell("SELECT id FROM $tblname WHERE $field $sql_operator $current_sequence " . ($lmt_query != '' ? " AND $lmt_query":"") . " ORDER BY $field $sql_order LIMIT 1"); if (empty($new_item_id)) { return $startid; } else { return $new_item_id; } } /* get_sequence - returns the next available sequence id @arg $id - (int) the current id @arg $field - the field name that contains the target id @arg $table_name - the table name that contains the target id @arg $group_query - an SQL "where" clause to limit the query @returns - (int) the next available sequence id */ function get_sequence($id, $field, $table_name, $group_query) { if (empty($id)) { $data = db_fetch_row("SELECT max($field)+1 AS seq FROM $table_name WHERE $group_query"); if ($data['seq'] == '') { return 1; } else { return $data['seq']; } } else { $data = db_fetch_row_prepared("SELECT $field FROM $table_name WHERE id = ?", array($id)); return $data[$field]; } } /* move_item_down - moves an item down by swapping it with the item below it @arg $table_name - the table name that contains the target id @arg $current_id - (int) the current id @arg $group_query - an SQL "where" clause to limit the query */ function move_item_down($table_name, $current_id, $group_query = '') { $next_item = get_item($table_name, 'sequence', $current_id, $group_query, 'next'); $sequence = db_fetch_cell_prepared("SELECT sequence FROM $table_name WHERE id = ?", array($current_id)); $sequence_next = db_fetch_cell_prepared("SELECT sequence FROM $table_name WHERE id = ?", array($next_item)); db_execute_prepared("UPDATE $table_name SET sequence = ? WHERE id = ?", array($sequence_next, $current_id)); db_execute_prepared("UPDATE $table_name SET sequence = ? WHERE id = ?", array($sequence, $next_item)); } /* move_item_up - moves an item down by swapping it with the item above it @arg $table_name - the table name that contains the target id @arg $current_id - (int) the current id @arg $group_query - an SQL "where" clause to limit the query */ function move_item_up($table_name, $current_id, $group_query = '') { $last_item = get_item($table_name, 'sequence', $current_id, $group_query, 'previous'); $sequence = db_fetch_cell_prepared("SELECT sequence FROM $table_name WHERE id = ?", array($current_id)); $sequence_last = db_fetch_cell_prepared("SELECT sequence FROM $table_name WHERE id = ?", array($last_item)); db_execute_prepared("UPDATE $table_name SET sequence = ? WHERE id = ?", array($sequence_last, $current_id)); db_execute_prepared("UPDATE $table_name SET sequence = ? WHERE id = ?", array($sequence, $last_item)); } /* exec_into_array - executes a command and puts each line of its output into an array @arg $command_line - the command to execute @returns - (array) an array containing the command output */ function exec_into_array($command_line) { $out = array(); $err = 0; exec($command_line,$out,$err); return array_values($out); } /* get_web_browser - determines the current web browser in use by the client @returns - ('ie' or 'moz' or 'other') */ function get_web_browser() { if (!empty($_SERVER['HTTP_USER_AGENT'])) { if (stristr($_SERVER['HTTP_USER_AGENT'], 'Mozilla') && (!(stristr($_SERVER['HTTP_USER_AGENT'], 'compatible')))) { return 'moz'; } elseif (stristr($_SERVER['HTTP_USER_AGENT'], 'MSIE')) { return 'ie'; } else { return 'other'; } } else { return 'other'; } } function get_guest_account() { return db_fetch_cell_prepared('SELECT id FROM user_auth WHERE username = ? OR id = ?', array(read_config_option('guest_user'), read_config_option('guest_user'))); } function get_template_account() { return db_fetch_cell_prepared('SELECT id FROM user_auth WHERE username = ? OR id = ?', array(read_config_option('user_template'), read_config_option('user_template'))); } /* draw_login_status - provides a consistent login status page for all pages that use it */ function draw_login_status($using_guest_account = false) { global $config; $guest_account = get_guest_account(); $auth_method = read_config_option('auth_method'); if (isset($_SESSION['sess_user_id']) && $_SESSION['sess_user_id'] == $guest_account) { api_plugin_hook('nav_login_before'); print __('Logged in as') . " <span id='user' class='user usermenuup'>". __('guest') . "</span></div><div><ul class='menuoptions' style='display:none;'><li><a href='" . $config['url_path'] . "index.php'>" . __('Login as Regular User') . "</a></li>\n"; print "<li class='menuHr'><hr class='menu'></li>"; print "<li id='userCommunity'><a href='https://forums.cacti.net' target='_blank'>" . __('User Community') . "</a></li>"; print "<li id='userDocumentation'><a href='https://github.com/Cacti/documentation/blob/develop/README.md' target='_blank'>" . __('Documentation') . "</a></li>"; print "</ul>"; api_plugin_hook('nav_login_after'); } elseif (isset($_SESSION['sess_user_id']) && $using_guest_account == false) { $user = db_fetch_row_prepared('SELECT username, password_change, realm FROM user_auth WHERE id = ?', array($_SESSION['sess_user_id'])); api_plugin_hook('nav_login_before'); print __('Logged in as') . " <span id='user' class='user usermenuup'>" . html_escape($user['username']) . "</span></div><div><ul class='menuoptions' style='display:none;'>"; print (is_realm_allowed(20) ? "<li><a href='" . $config['url_path'] . "auth_profile.php?action=edit'>" . __('Edit Profile') . "</a></li>":""); print ($user['password_change'] == 'on' && $user['realm'] == 0 ? "<li><a href='" . $config['url_path'] . "auth_changepassword.php'>" . __('Change Password') . "</a></li>":''); print "<li class='menuHr'><hr class='menu'></li>"; print "<li id='userCommunity'><a href='https://forums.cacti.net' target='_blank'>" . __('User Community') . "</a></li>"; print "<li id='userDocumentation'><a href='https://github.com/Cacti/documentation/blob/develop/README.md' target='_blank'>" . __('Documentation') . "</a></li>"; print "<li class='menuHr'><hr class='menu'></li>"; print ($auth_method > 0 ? "<li><a href='" . $config['url_path'] . "logout.php'>" . __('Logout') . "</a></li>":""); print "</ul>\n"; api_plugin_hook('nav_login_after'); } } /* * draw_navigation_text - determines the top header navigation text for the current page and displays it to * * @arg $type - (string) Either 'url' or 'title' * @return (string) Either the navigation text or title */ function draw_navigation_text($type = 'url') { global $config, $navigation; $nav_level_cache = (isset($_SESSION['sess_nav_level_cache']) ? $_SESSION['sess_nav_level_cache'] : array()); $navigation = api_plugin_hook_function('draw_navigation_text', $navigation); $current_page = get_current_page(); // Do an error check here for bad plugins manipulating the cache if (!is_array($nav_level_cache)) { $nav_level_cache = array(); } if (!isempty_request_var('action')) { get_filter_request_var('action', FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => '/^([-a-zA-Z0-9_\s]+)$/'))); } $current_action = (isset_request_var('action') ? get_request_var('action') : ''); // find the current page in the big array if (isset($navigation[$current_page . ':' . $current_action])) { $current_array = $navigation[$current_page . ':' . $current_action]; } else { $current_array = array( 'mapping' => 'index.php:', 'title' => ucwords(str_replace('_', ' ', basename(get_current_page(), '.php'))), 'level' => 1 ); } if (isset($current_array['mapping'])) { $current_mappings = explode(',', $current_array['mapping']); } else { $current_mappings = array(); } $current_nav = "<ul id='breadcrumbs'>"; $title = ''; $nav_count = 0; // resolve all mappings to build the navigation string for ($i=0; ($i < cacti_count($current_mappings)); $i++) { if (empty($current_mappings[$i])) { continue; } if ($i == 0) { // always use the default for level == 0 $url = $navigation{basename($current_mappings[$i])}['url']; if (basename($url) == 'graph_view.php') continue; } elseif (isset($nav_level_cache[$i]) && !empty($nav_level_cache[$i]['url'])) { // found a match in the url cache for this level $url = $nav_level_cache[$i]['url']; } elseif (isset($current_array['url'])) { // found a default url in the above array $url = $current_array['url']; } else { // default to no url $url = ''; } if ($current_mappings[$i] == '?') { // '?' tells us to pull title from the cache at this level if (isset($nav_level_cache[$i])) { $current_nav .= (empty($url) ? '' : "<li><a id='nav_$i' href='" . html_escape($url) . "'>"); $current_nav .= html_escape(resolve_navigation_variables($navigation[$nav_level_cache[$i]['id']]['title'])); $current_nav .= (empty($url) ? '' : '</a>' . (get_selected_theme() == 'classic' ? ' -> ':'') . '</li>'); $title .= html_escape(resolve_navigation_variables($navigation[$nav_level_cache[$i]['id']]['title'])) . ' -> '; } } else { // there is no '?' - pull from the above array $current_nav .= (empty($url) ? '' : "<li><a id='nav_$i' href='" . html_escape($url) . "'>"); $current_nav .= html_escape(resolve_navigation_variables($navigation{basename($current_mappings[$i])}['title'])); $current_nav .= (empty($url) ? '' : '</a>' . (get_selected_theme() == 'classic' ? ' -> ':'') . '</li>'); $title .= html_escape(resolve_navigation_variables($navigation{basename($current_mappings[$i])}['title'])) . ' -> '; } $nav_count++; } if ($nav_count) { if (isset($current_array['title'])) { $current_nav .= "<li><a id='nav_$i' href=#>" . html_escape(resolve_navigation_variables($current_array['title'])) . '</a></li>'; } } else { $current_array = $navigation[$current_page . ':' . $current_action]; $url = (isset($current_array['url']) ? $current_array['url']:''); if (isset($current_array['title'])) { $current_nav .= "<li><a id='nav_$i' href='$url'>" . html_escape(resolve_navigation_variables($current_array['title'])) . '</a></li>'; } } if (isset_request_var('action') || get_nfilter_request_var('action') == 'tree_content') { $tree_id = 0; $leaf_id = 0; if (isset_request_var('node')) { $parts = explode('-', get_request_var('node')); // Check for tree anchor if (strpos(get_request_var('node'), 'tree_anchor') !== false) { $tree_id = $parts[1]; $leaf_id = 0; } elseif (strpos(get_request_var('node'), 'tbranch') !== false) { // Check for branch $leaf_id = $parts[1]; $tree_id = db_fetch_cell_prepared('SELECT graph_tree_id FROM graph_tree_items WHERE id = ?', array($leaf_id)); } } if ($leaf_id > 0) { $leaf = db_fetch_row_prepared('SELECT host_id, title, graph_tree_id FROM graph_tree_items WHERE id = ?', array($leaf_id)); if (cacti_sizeof($leaf)) { if ($leaf['host_id'] > 0) { $leaf_name = db_fetch_cell_prepared('SELECT description FROM host WHERE id = ?', array($leaf['host_id'])); } else { $leaf_name = $leaf['title']; } $tree_name = db_fetch_cell_prepared('SELECT name FROM graph_tree WHERE id = ?', array($leaf['graph_tree_id'])); } else { $leaf_name = __('Leaf'); $tree_name = ''; } if (isset_request_var('hgd') && get_nfilter_request_var('hgd') != '') { $parts = explode(':', get_nfilter_request_var('hgd')); input_validate_input_number($parts[1]); if ($parts[0] == 'gt') { $leaf_sub = db_fetch_cell_prepared('SELECT name FROM graph_templates WHERE id = ?', array($parts[1])); } else { if ($parts[1] > 0) { $leaf_sub = db_fetch_cell_prepared('SELECT name FROM snmp_query WHERE id = ?', array($parts[1])); } else { $leaf_sub = __('Non Query Based'); } } } else { $leaf_sub = ''; } } else { $leaf_name = ''; $leaf_sub = ''; if ($tree_id > 0) { $tree_name = db_fetch_cell_prepared('SELECT name FROM graph_tree WHERE id = ?', array($tree_id)); } else { $tree_name = ''; } } $tree_title = $tree_name . ($leaf_name != '' ? ' (' . trim($leaf_name):'') . ($leaf_sub != '' ? ':' . trim($leaf_sub) . ')':($leaf_name != '' ? ')':'')); if ($tree_title != '') { $current_nav .= "<li><a id='nav_title' href=#>" . html_escape($tree_title) . '</a></li>'; } } elseif (preg_match('#link.php\?id=(\d+)#', $_SERVER['REQUEST_URI'], $matches)) { $externalLinks = db_fetch_row_prepared('SELECT title, style FROM external_links WHERE id = ?', array($matches[1])); $title = $externalLinks['title']; $style = $externalLinks['style']; if ($style == 'CONSOLE') { $current_nav = "<ul id='breadcrumbs'><li><a id='nav_0' href='" . $config['url_path'] . "index.php'>" . __('Console') . '</a>' . (get_selected_theme() == 'classic' ? ' -> ':'') . '</li>'; $current_nav .= "<li><a id='nav_1' href='#'>" . __('Link %s', html_escape($title)) . '</a></li>'; } else { $current_nav = "<ul id='breadcrumbs'><li><a id='nav_0'>" . html_escape($title) . '</a></li>'; } $tree_title = ''; } else { $tree_title = ''; } if (isset($current_array['title'])) { $title .= html_escape(resolve_navigation_variables($current_array['title']) . ' ' . $tree_title); } // keep a cache for each level we encounter $hasNavError = false; if (is_array($current_page)) { cacti_log('WARNING: Navigation item suppressed - current page is not a string: ' . var_export($current_page,true)); $hasNavError = true; } if (is_array($current_action)) { cacti_log('WARNING: Navigation item suppressed - current action is not a string: '. var_export($current_action,true)); $hasNavError = true; } if (is_array($current_array['level'])) { cacti_log('WARNING: Navigation item suppressed - current level is not a string: ' . var_export($current_array['level'],true)); $hasNavError = true; } if (!$hasNavError) { $nav_level_cache[$current_array['level']] = array( 'id' => $current_page . ':' . $current_action, 'url' => get_browser_query_string() ); } $current_nav .= '</ul>'; $_SESSION['sess_nav_level_cache'] = $nav_level_cache; if ($type == 'url') { return $current_nav; } else { return $title; } } /* resolve_navigation_variables - substitute any variables contained in the navigation text @arg $text - the text to substitute in @returns - the original navigation text with all substitutions made */ function resolve_navigation_variables($text) { $graphTitle = get_graph_title(get_filter_request_var('local_graph_id')); if (preg_match_all("/\|([a-zA-Z0-9_]+)\|/", $text, $matches)) { for ($i=0; $i<cacti_count($matches[1]); $i++) { switch ($matches[1][$i]) { case 'current_graph_title': $text = str_replace('|' . $matches[1][$i] . '|', $graphTitle, $text); break; } } } return $text; } /* get_associated_rras - returns a list of all RRAs referenced by a particular graph @arg $local_graph_id - (int) the ID of the graph to retrieve a list of RRAs for @returns - (array) an array containing the name and id of each RRA found */ function get_associated_rras($local_graph_id, $sql_where = '') { return db_fetch_assoc_prepared('SELECT DISTINCT ' . SQL_NO_CACHE . " dspr.id, dsp.step, dspr.steps, dspr.rows, dspr.name, dtd.rrd_step, dspr.timespan FROM graph_templates_item AS gti LEFT JOIN data_template_rrd AS dtr ON gti.task_item_id=dtr.id LEFT JOIN data_template_data AS dtd ON dtr.local_data_id = dtd.local_data_id LEFT JOIN data_source_profiles AS dsp ON dtd.data_source_profile_id=dsp.id LEFT JOIN data_source_profiles_rra AS dspr ON dsp.id=dspr.data_source_profile_id AND dtd.local_data_id != 0 WHERE gti.local_graph_id = ? $sql_where ORDER BY dspr.steps", array($local_graph_id) ); } /* get_nearest_timespan - returns the nearest defined timespan. Used for adding a default graph timespan for data source profile rras. @arg $timespan - (int) the timespan to fine a default for @returns - (int) the timespan to apply for the data source profile rra value */ function get_nearest_timespan($timespan) { global $timespans; $last = end($timespans); foreach($timespans as $index => $name) { if ($timespan > $index) { $last = $index; continue; } elseif ($timespan == $index) { return $index; } else { return $last; } } return $last; } /* get_browser_query_string - returns the full url, including args requested by the browser @returns - the url requested by the browser */ function get_browser_query_string() { if (!empty($_SERVER['REQUEST_URI'])) { return sanitize_uri($_SERVER['REQUEST_URI']); } else { return sanitize_uri(get_current_page() . (empty($_SERVER['QUERY_STRING']) ? '' : '?' . $_SERVER['QUERY_STRING'])); } } /* get_current_page - returns the basename of the current page in a web server friendly way @returns - the basename of the current script file */ function get_current_page($basename = true) { if (isset($_SERVER['SCRIPT_NAME']) && $_SERVER['SCRIPT_NAME'] != '') { if ($basename) { return basename($_SERVER['SCRIPT_NAME']); } else { return $_SERVER['SCRIPT_NAME']; } } elseif (isset($_SERVER['SCRIPT_FILENAME']) && $_SERVER['SCRIPT_FILENAME'] != '') { if ($basename) { return basename($_SERVER['SCRIPT_FILENAME']); } else { return $_SERVER['SCRIPT_FILENAME']; } } else { cacti_log('ERROR: unable to determine current_page'); } return false; } /* get_hash_graph_template - returns the current unique hash for a graph template @arg $graph_template_id - (int) the ID of the graph template to return a hash for @arg $sub_type (optional) return the hash for a particular subtype of this type @returns - a 128-bit, hexadecimal hash */ function get_hash_graph_template($graph_template_id, $sub_type = 'graph_template') { switch ($sub_type) { case 'graph_template': $hash = db_fetch_cell_prepared('SELECT hash FROM graph_templates WHERE id = ?', array($graph_template_id)); break; case 'graph_template_item': $hash = db_fetch_cell_prepared('SELECT hash FROM graph_templates_item WHERE id = ?', array($graph_template_id)); break; case 'graph_template_input': $hash = db_fetch_cell_prepared('SELECT hash FROM graph_template_input WHERE id = ?', array($graph_template_id)); break; default: return generate_hash(); break; } if (preg_match('/[a-fA-F0-9]{32}/', $hash)) { return $hash; } else { return generate_hash(); } } /* get_hash_data_template - returns the current unique hash for a data template @arg $graph_template_id - (int) the ID of the data template to return a hash for @arg $sub_type (optional) return the hash for a particular subtype of this type @returns - a 128-bit, hexadecimal hash */ function get_hash_data_template($data_template_id, $sub_type = 'data_template') { switch ($sub_type) { case 'data_template': $hash = db_fetch_cell_prepared('SELECT hash FROM data_template WHERE id = ?', array($data_template_id)); break; case 'data_template_item': $hash = db_fetch_cell_prepared('SELECT hash FROM data_template_rrd WHERE id = ?', array($data_template_id)); break; default: return generate_hash(); break; } if (preg_match('/[a-fA-F0-9]{32}/', $hash)) { return $hash; } else { return generate_hash(); } } /* get_hash_data_input - returns the current unique hash for a data input method @arg $graph_template_id - (int) the ID of the data input method to return a hash for @arg $sub_type (optional) return the hash for a particular subtype of this type @returns - a 128-bit, hexadecimal hash */ function get_hash_data_input($data_input_id, $sub_type = 'data_input_method') { switch ($sub_type) { case 'data_input_method': $hash = db_fetch_cell_prepared('SELECT hash FROM data_input WHERE id = ?', array($data_input_id)); break; case 'data_input_field': $hash = db_fetch_cell_prepared('SELECT hash FROM data_input_fields WHERE id = ?', array($data_input_id)); break; default: return generate_hash(); break; } if (preg_match('/[a-fA-F0-9]{32}/', $hash)) { return $hash; } else { return generate_hash(); } } /* get_hash_cdef - returns the current unique hash for a cdef @arg $graph_template_id - (int) the ID of the cdef to return a hash for @arg $sub_type (optional) return the hash for a particular subtype of this type @returns - a 128-bit, hexadecimal hash */ function get_hash_cdef($cdef_id, $sub_type = 'cdef') { if (!is_numeric($cdef_id)) { return generate_hash(); } switch ($sub_type) { case 'cdef': $hash = db_fetch_cell_prepared('SELECT hash FROM cdef WHERE id = ?', array($cdef_id)); break; case 'cdef_item': $hash = db_fetch_cell_prepared('SELECT hash FROM cdef_items WHERE id = ?', array($cdef_id)); break; default: return generate_hash(); break; } if (strlen($hash) == 32 && ctype_xdigit($hash)) { return $hash; } else { return generate_hash(); } } /* get_hash_gprint - returns the current unique hash for a gprint preset @arg $graph_template_id - (int) the ID of the gprint preset to return a hash for @returns - a 128-bit, hexadecimal hash */ function get_hash_gprint($gprint_id) { $hash = db_fetch_cell_prepared('SELECT hash FROM graph_templates_gprint WHERE id = ?', array($gprint_id)); if (strlen($hash) == 32 && ctype_xdigit($hash)) { return $hash; } else { return generate_hash(); } } /** * returns the current unique hash for a vdef * @param $graph_template_id - (int) the ID of the vdef to return a hash for * @param $sub_type (optional) return the hash for a particular subtype of this type * @returns - a 128-bit, hexadecimal hash */ function get_hash_vdef($vdef_id, $sub_type = "vdef") { switch ($sub_type) { case 'vdef': $hash = db_fetch_cell_prepared('SELECT hash FROM vdef WHERE id = ?', array($vdef_id)); break; case 'vdef_item': $hash = db_fetch_cell_prepared('SELECT hash FROM vdef_items WHERE id = ?', array($vdef_id)); break; default: return generate_hash(); break; } if (strlen($hash) == 32 && ctype_xdigit($hash)) { return $hash; } else { return generate_hash(); } } /** * returns the current unique hash for a vdef * @param $data_source_profile_id - (int) the ID of the data_source_profile to return a hash for * @returns - a 128-bit, hexadecimal hash */ function get_hash_data_source_profile($data_source_profile_id) { $hash = db_fetch_cell_prepared('SELECT hash FROM data_source_profiles WHERE id = ?', array($data_source_profile_id)); if (strlen($hash) == 32 && ctype_xdigit($hash)) { return $hash; } else { return generate_hash(); } } /* get_hash_host_template - returns the current unique hash for a gprint preset @arg $host_template_id - (int) the ID of the host template to return a hash for @returns - a 128-bit, hexadecimal hash */ function get_hash_host_template($host_template_id) { $hash = db_fetch_cell_prepared('SELECT hash FROM host_template WHERE id = ?', array($host_template_id)); if (strlen($hash) == 32 && ctype_xdigit($hash)) { return $hash; } else { return generate_hash(); } } /* get_hash_data_query - returns the current unique hash for a data query @arg $graph_template_id - (int) the ID of the data query to return a hash for @arg $sub_type (optional) return the hash for a particular subtype of this type @returns - a 128-bit, hexadecimal hash */ function get_hash_data_query($data_query_id, $sub_type = 'data_query') { switch ($sub_type) { case 'data_query': $hash = db_fetch_cell_prepared('SELECT hash FROM snmp_query WHERE id = ?', array($data_query_id)); break; case 'data_query_graph': $hash = db_fetch_cell_prepared('SELECT hash FROM snmp_query_graph WHERE id = ?', array($data_query_id)); break; case 'data_query_sv_data_source': $hash = db_fetch_cell_prepared('SELECT hash FROM snmp_query_graph_rrd_sv WHERE id = ?', array($data_query_id)); break; case 'data_query_sv_graph': $hash = db_fetch_cell_prepared('SELECT hash FROM snmp_query_graph_sv WHERE id = ?', array($data_query_id)); break; default: return generate_hash(); break; } if (strlen($hash) == 32 && ctype_xdigit($hash)) { return $hash; } else { return generate_hash(); } } /* get_hash_version - returns the item type and cacti version in a hash format @arg $type - the type of item to represent ('graph_template','data_template', 'data_input_method','cdef','vdef','gprint_preset','data_query','host_template') @returns - a 24-bit hexadecimal hash (8-bits for type, 16-bits for version) */ function get_hash_version($type) { global $hash_type_codes, $cacti_version_codes, $config; return $hash_type_codes[$type] . $cacti_version_codes[CACTI_VERSION]; } /* generate_hash - generates a new unique hash @returns - a 128-bit, hexadecimal hash */ function generate_hash() { return md5(session_id() . microtime() . rand(0,1000)); } /* debug_log_insert_section_start - creates a header item for breaking down the debug log @arg $type - the 'category' or type of debug message @arg $text - section header */ function debug_log_insert_section_start($type, $text, $allowcopy = false) { $copy_prefix = ''; $copy_dataid = ''; if ($allowcopy) { $uid = generate_hash(); $copy_prefix = '<div class=\'cactiTableButton debug\'><span><a class=\'linkCopyDark cactiTableCopy\' id=\'copyToClipboard' . $uid . '\'>' . __esc('Copy') . '</a></span></div>'; $copy_dataid = ' id=\'clipboardData'.$uid.'\''; $copy_headerid = ' id=\'clipboardHeader'.$uid.'\''; } debug_log_insert($type, '<table class=\'cactiTable debug\'' . $copy_headerid . '><tr class=\'tableHeader\'><td>' . html_escape($text) . $copy_prefix . '</td></tr><tr><td style=\'padding:0px;\'><table style=\'display:none;\'' . $copy_dataid . '><tr><td><div style=\'font-family: monospace;\'>'); } /* debug_log_insert_section_end - finalizes the header started with the start function @arg $type - the 'category' or type of debug message */ function debug_log_insert_section_end($type) { debug_log_insert($type, "</div></td></tr></table></td></tr></td></table>"); } /* debug_log_insert - inserts a line of text into the debug log @arg $type - the 'category' or type of debug message @arg $text - the actual debug message */ function debug_log_insert($type, $text) { global $config; if ($config['poller_id'] == 1 || isset($_SESSION)) { if (!isset($_SESSION['debug_log'][$type])) { $_SESSION['debug_log'][$type] = array(); } array_push($_SESSION['debug_log'][$type], $text); } else { if (!isset($config['debug_log'][$type])) { $config['debug_log'][$type] = array(); } array_push($config['debug_log'][$type], $text); } } /* debug_log_clear - clears the debug log for a particular category @arg $type - the 'category' to clear the debug log for. omitting this argument implies all categories */ function debug_log_clear($type = '') { if ($type == '') { kill_session_var('debug_log'); } else { if (isset($_SESSION['debug_log'])) { unset($_SESSION['debug_log'][$type]); } } } /* debug_log_return - returns the debug log for a particular category @arg $type - the 'category' to return the debug log for. @returns - the full debug log for a particular category */ function debug_log_return($type) { $log_text = ''; if ($type == 'new_graphs') { if (isset($_SESSION['debug_log'][$type])) { $log_text .= "<table style='width:100%;'>"; for ($i=0; $i<cacti_count($_SESSION['debug_log'][$type]); $i++) { $log_text .= '<tr><td>' . $_SESSION['debug_log'][$type][$i] . '</td></tr>'; } $log_text .= '</table>'; } } else { if (isset($_SESSION['debug_log'][$type])) { $log_text .= "<table style='width:100%;'>"; foreach($_SESSION['debug_log'][$type] as $key => $val) { $log_text .= "<tr><td>$val</td></tr>\n"; unset($_SESSION['debug_log'][$type][$key]); } $log_text .= '</table>'; } } return $log_text; } /* sanitize_search_string - cleans up a search string submitted by the user to be passed to the database. NOTE: some of the code for this function came from the phpBB project. @arg $string - the original raw search string @returns - the sanitized search string */ function sanitize_search_string($string) { static $drop_char_match = array('(',')','^', '$', '<', '>', '`', '\'', '"', '|', ',', '?', '+', '[', ']', '{', '}', '#', ';', '!', '=', '*'); static $drop_char_replace = array('','',' ', ' ', ' ', ' ', '', '', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '); /* Replace line endings by a space */ $string = preg_replace('/[\n\r]/is', ' ', $string); /* HTML entities like &nbsp; */ $string = preg_replace('/\b&[a-z]+;\b/', ' ', $string); /* Remove URL's */ $string = preg_replace('/\b[a-z0-9]+:\/\/[a-z0-9\.\-]+(\/[a-z0-9\?\.%_\-\+=&\/]+)?/', ' ', $string); /* Filter out strange characters like ^, $, &, change "it's" to "its" */ for($i = 0; $i < cacti_count($drop_char_match); $i++) { $string = str_replace($drop_char_match[$i], $drop_char_replace[$i], $string); } return $string; } /** cleans up a URI, e.g. from REQUEST_URI and/or QUERY_STRING * in case of XSS attack, expect the result to be broken * we do NOT sanitize in a way, that attacks are converted to valid HTML * it is ok, when the result is broken but the application stays alive * @arg string $uri - the uri to be sanitized * @returns string - the sanitized uri */ function sanitize_uri($uri) { static $drop_char_match = array('^', '$', '<', '>', '`', "'", '"', '|', '+', '[', ']', '{', '}', ';', '!', '(', ')'); static $drop_char_replace = array( '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''); if (strpos($uri, 'graph_view.php')) { if (!strpos($uri, 'action=')) { $uri = $uri . (strpos($uri, '?') ? '&':'?') . 'action=' . get_request_var('action'); } } return str_replace($drop_char_match, $drop_char_replace, strip_tags(urldecode($uri))); } /** Checks to see if a string is base64 encoded * @arg string $data - the string to be validated * @returns boolean - true is the string is base64 otherwise false */ function is_base64_encoded($data) { // Perform a simple check first if (!preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $data)) { return false; } // Now test with the built-in function $ndata = base64_decode($data, true); if ($ndata === false) { return false; } // Do a re-encode test and compare if (base64_encode($ndata) != $data) { return false; } return true; } /** cleans up a CDEF/VDEF string * the CDEF/VDEF must have passed all magic string replacements beforehand * @arg string $cdef - the CDEF/VDEF to be sanitized * @returns string - the sanitized CDEF/VDEF */ function sanitize_cdef($cdef) { static $drop_char_match = array('^', '$', '<', '>', '`', '\'', '"', '|', '[', ']', '{', '}', ';', '!'); static $drop_char_replace = array( '', '', '', '', '', '', '', '', '', '', '', '', '', ''); return str_replace($drop_char_match, $drop_char_replace, $cdef); } /** verifies all selected items are numeric to guard against injection * @arg array $items - an array of serialized items from a post * @returns array - the sanitized selected items array */ function sanitize_unserialize_selected_items($items) { if ($items != '') { $items = unserialize(stripslashes($items)); if (is_array($items)) { foreach ($items as $item) { if (is_array($item)) { return false; } elseif (!is_numeric($item) && ($item != '')) { return false; } } } else { return false; } } else { return false; } return $items; } function cacti_escapeshellcmd($string) { global $config; if ($config['cacti_server_os'] == 'unix') { return escapeshellcmd($string); } else { $replacements = "#&;`|*?<>^()[]{}$\\"; for ($i=0; $i < strlen($replacements); $i++) { $string = str_replace($replacements[$i], ' ', $string); } return $string; } } /** * mimics escapeshellarg, even for windows * @param $string - the string to be escaped * @param $quote - true: do NOT remove quotes from result; false: do remove quotes * @return - the escaped [quoted|unquoted] string */ function cacti_escapeshellarg($string, $quote = true) { global $config; if ($string == '') { return $string; } /* we must use an apostrophe to escape community names under Unix in case the user uses characters that the shell might interpret. the ucd-snmp binaries on Windows flip out when you do this, but are perfectly happy with a quotation mark. */ if ($config['cacti_server_os'] == 'unix') { $string = escapeshellarg($string); if ($quote) { return $string; } else { # remove first and last char return substr($string, 1, (strlen($string)-2)); } } else { /* escapeshellarg takes care of different quotation for both linux and windows, * but unfortunately, it blanks out percent signs * we want to keep them, e.g. for GPRINT format strings * so we need to create our own escapeshellarg * on windows, command injection requires to close any open quotation first * so we have to escape any quotation here */ if (substr_count($string, CACTI_ESCAPE_CHARACTER)) { $string = str_replace(CACTI_ESCAPE_CHARACTER, "\\" . CACTI_ESCAPE_CHARACTER, $string); } /* ... before we add our own quotation */ if ($quote) { return CACTI_ESCAPE_CHARACTER . $string . CACTI_ESCAPE_CHARACTER; } else { return $string; } } } /** * set a page refresh in Cacti through a callback * @param $refresh - an array containing the page, seconds, and logout * @return - nill */ function set_page_refresh($refresh) { if (isset($refresh['seconds'])) { $_SESSION['refresh']['seconds'] = $refresh['seconds']; } if (isset($refresh['logout'])) { if ($refresh['logout'] == 'true' || $refresh['logout'] === true) { $_SESSION['refresh']['logout'] = 'true'; } else { $_SESSION['refresh']['logout'] = 'false'; } } else { $_SESSION['refresh']['logout'] = 'true'; } if (isset($refresh['page'])) { $_SESSION['refresh']['page'] = $refresh['page']; } } function bottom_footer() { global $config, $no_session_write; include_once($config['base_path'] . '/include/global_session.php'); if (!isset_request_var('header') || get_nfilter_request_var('header') == 'true') { include_once($config['base_path'] . '/include/bottom_footer.php'); } /* we use this session var to store field values for when a save fails, this way we can restore the field's previous values. we reset it here, because they only need to be stored for a single page */ kill_session_var('sess_field_values'); /* make sure the debug log doesn't get too big */ debug_log_clear(); /* close the session */ if (array_search(get_current_page(), $no_session_write) === false) { session_write_close(); } /* close the database connection */ db_close(); } function top_header() { global $config; if (!isset_request_var('header') || get_nfilter_request_var('header') == 'true') { include_once($config['base_path'] . '/include/top_header.php'); } } function top_graph_header() { global $config; html_validate_tree_vars(); if (!isset_request_var('header') || get_nfilter_request_var('header') == 'true') { include_once($config['base_path'] . '/include/top_graph_header.php'); } } function general_header() { global $config; if (!isset_request_var('header') || get_nfilter_request_var('header') == 'true') { include_once($config['base_path'] . '/include/top_general_header.php'); } } function appendHeaderSuppression($url) { if (strpos($url, 'header=false') < 0) { return $url . (strpos($url, '?') ? '&':'?') . 'header=false'; } return $url; } function admin_email($subject, $message) { if (read_config_option('admin_user')) { if (read_config_option('notify_admin')) { $admin_details = db_fetch_row_prepared('SELECT full_name, email_address FROM user_auth WHERE id = ?', array(read_config_option('admin_user'))); if (cacti_sizeof($admin_details)) { $email = read_config_option('settings_from_email'); $name = read_config_option('settings_from_name'); if ($name != '') { $from = '"' . $name . '" <' . $email . '>'; } else { $from = $email; } if ($admin_details['email_address'] != '') { if ($admin_details['full_name'] != '') { $to = '"' . $admin_details['full_name'] . '" <' . $admin_details['email_address'] . '>'; } else { $to = $admin_details['email_address']; } send_mail($to, $from, $subject, $message, '', '', true); } else { cacti_log('WARNING: Primary Admin account does not have an email address! Unable to send administrative Email.', false, 'SYSTEM'); } } else { cacti_log('WARNING: Primary Admin account set to an invalid user! Unable to send administrative Email.', false, 'SYSTEM'); } } else { cacti_log('WARNING: Primary Admin account notifications disabled! Unable to send administrative Email.', false, 'SYSTEM'); } } else { cacti_log('WARNING: Primary Admin account not set! Unable to send administrative Email.', false, 'SYSTEM'); } } function send_mail($to, $from, $subject, $body, $attachments = '', $headers = '', $html = false) { $fromname = ''; if (is_array($from)) { $fromname = $from[1]; $from = $from[0]; } if ($from == '') { $from = read_config_option('settings_from_email'); $fromname = read_config_option('settings_from_name'); } elseif ($fromname == '') { $full_name = db_fetch_cell_prepared('SELECT full_name FROM user_auth WHERE email_address = ?', array($from)); if (empty($full_name)) { $fromname = $from; } else { $fromname = $full_name; } } $from = array(0 => $from, 1 => $fromname); return mailer($from, $to, '', '', '', $subject, $body, '', $attachments, $headers, $html); } /** mailer - function to send mails to users * @arg $from - single contact (see below) * @arg $to - single or multiple contacts (see below) * @arg $cc - none, single or multiple contacts (see below) * @arg $bcc - none, single or multiple contacts (see below) * @arg $replyto - none, single or multiple contacts (see below) * note that this value is used when hitting reply (overriding the default of using from) * @arg $subject - the email subject * @arg $body - the email body, in HTML format. If content_text is not set, the function will attempt to extract * from the HTML format. * @arg $body_text - the email body in TEXT format. If set, it will override the stripping tags method * @arg $attachments - the emails attachments as an array * @arg $headers - an array of name value pairs representing custom headers. * @arg $html - if set to true, html is the default, otherwise text format will be used * * For contact parameters, they can accept arrays containing zero or more values in the forms of: * 'email@email.com,email2@email.com,email3@email.com' * array('email1@email.com' => 'My email', 'email2@email.com' => 'Your email', 'email3@email.com' => 'Whose email') * array(array('email' => 'email1@email.com', 'name' => 'My email'), array('email' => 'email2@email.com', * 'name' => 'Your email'), array('email' => 'email3@email.com', 'name' => 'Whose email')) * * The $from field will only use the first contact specified. If no contact is provided for $replyto * then $from is used for that too. If $from is empty, it will default to cacti@<server> or if no server name can * be found, it will use cacti@cacti.net * * The $attachments parameter may either be a single string, or a list of attachments * either as strings or an array. The array can have the following keys: * * filename : name of the file to attach (display name for graphs) * display : displayed name of the attachment * mime_type : MIME type to be set against the attachment. If blank or missing mailer will attempt to auto detect * attachment : String containing attachment for image-based attachments (<GRAPH> or <GRAPH:#> activates graph mode * and requires $body parameter is HTML containing one of those values) * inline : Whether to attach 'inline' (default for graph mode) or as 'attachment' (default for all others) * encoding : Encoding type, normally base64 */ function mailer($from, $to, $cc, $bcc, $replyto, $subject, $body, $body_text = '', $attachments = '', $headers = '', $html = true) { global $config, $cacti_locale, $mail_methods; require_once($config['include_path'] . '/vendor/phpmailer/src/Exception.php'); require_once($config['include_path'] . '/vendor/phpmailer/src/PHPMailer.php'); require_once($config['include_path'] . '/vendor/phpmailer/src/SMTP.php'); // Create the PHPMailer instance $mail = new PHPMailer\PHPMailer\PHPMailer; // Set a reasonable timeout of 5 seconds $timeout = read_config_option('settings_smtp_timeout'); if (empty($timeout) || $timeout < 0 || $timeout > 300) { $mail->Timeout = 5; } else { $mail->Timeout = $timeout; } $langparts = explode('-', $cacti_locale); if (file_exists($config['include_path'] . '/vendor/phpmailer/language/phpmailer.lang-' . $langparts[0] . '.php')) { $mail->setLanguage($langparts[0], $config['include_path'] . '/vendor/phpmailer/language/'); } $how = read_config_option('settings_how'); if ($how < 0 || $how > 2) { $how = 0; } if ($how == 0) { $mail->isMail(); } elseif ($how == 1) { $mail->Sendmail = read_config_option('settings_sendmail_path'); $mail->isSendmail(); } elseif ($how == 2) { $mail->isSMTP(); $mail->Host = read_config_option('settings_smtp_host'); $mail->Port = read_config_option('settings_smtp_port'); if (read_config_option('settings_smtp_username') != '') { $mail->SMTPAuth = true; $mail->Username = read_config_option('settings_smtp_username'); if (read_config_option('settings_smtp_password') != '') { $mail->Password = read_config_option('settings_smtp_password'); } } else { $mail->SMTPAuth = false; } $secure = read_config_option('settings_smtp_secure'); if (!empty($secure) && $secure != 'none') { $mail->SMTPSecure = true; if (substr_count($mail->Host, ':') == 0) { $mail->Host = $secure . '://' . $mail->Host; } } else { $mail->SMTPAutoTLS = false; $mail->SMTPSecure = false; } } /* perform data substitution */ if (strpos($subject, '|date_time|') !== false) { $date = read_config_option('date'); if (!empty($date)) { $time = strtotime($date); } else { $time = time(); } $subject = str_replace('|date_time|', date(CACTI_DATE_TIME_FORMAT, $time), $subject); } /* * Set the from details using the variable passed in * - if name is blank, use setting's name * - if email is blank, use setting's email, otherwise default to * cacti@<server> or cacti@cacti.net if no known server name */ $from = parse_email_details($from, 1); // from name was empty, use value in settings if (empty($from['name'])) { $from['name'] = read_config_option('settings_from_name'); } // from email was empty, use email in settings if (empty($from['email'])) { $from['email'] = read_config_option('settings_from_email'); } if (empty($from['email'])) { if (isset($_SERVER['HOSTNAME'])) { $from['email'] = 'Cacti@' . $_SERVER['HOSTNAME']; } else { $from['email'] = 'Cacti@cacti.net'; } if (empty($from['name'])) { $from['name'] = 'Cacti'; } } $fromText = add_email_details(array($from), $result, array($mail, 'setFrom')); if ($result == false) { return record_mailer_error($fromText, $mail->ErrorInfo); } // Convert $to variable to proper array structure $to = parse_email_details($to); $toText = add_email_details($to, $result, array($mail, 'addAddress')); if ($result == false) { return record_mailer_error($toText, $mail->ErrorInfo); } $cc = parse_email_details($cc); $ccText = add_email_details($cc, $result, array($mail, 'addCC')); if ($result == false) { return record_mailer_error($ccText, $mail->ErrorInfo); } $bcc = parse_email_details($bcc); $bccText = add_email_details($bcc, $result, array($mail, 'addBCC')); if ($result == false) { return record_mailer_error($bccText, $mail->ErrorInfo); } // This is a failsafe, should never happen now if (!(cacti_sizeof($to) || cacti_sizeof($cc) || cacti_sizeof($bcc))) { cacti_log('ERROR: No recipient address set!!', false, 'MAILER'); cacti_debug_backtrace('MAILER ERROR'); return __('Mailer Error: No recipient address set!!<br>If using the <i>Test Mail</i> link, please set the <b>Alert e-mail</b> setting.'); } $replyto = parse_email_details($replyto); $replyText = add_email_details($replyto, $result, array($mail, 'addReplyTo')); if ($result == false) { return record_mailer_error($replyText, $mail->ErrorInfo); } $body = str_replace('<SUBJECT>', $subject, $body); $body = str_replace('<TO>', $toText, $body); $body = str_replace('<CC>', $ccText, $body); $body = str_replace('<FROM>', $fromText, $body); $body = str_replace('<REPLYTO>', $replyText, $body); $body_text = str_replace('<SUBJECT>', $subject, $body_text); $body_text = str_replace('<TO>', $toText, $body_text); $body_text = str_replace('<CC>', $ccText, $body_text); $body_text = str_replace('<FROM>', $fromText, $body_text); $body_text = str_replace('<REPLYTO>', $replyText, $body_text); // Set the subject $mail->Subject = $subject; // Support i18n $mail->CharSet = 'UTF-8'; $mail->Encoding = 'base64'; // Set the wordwrap limits $wordwrap = read_config_option('settings_wordwrap'); if ($wordwrap == '') { $wordwrap = 76; } elseif ($wordwrap > 9999) { $wordwrap = 9999; } elseif ($wordwrap < 0) { $wordwrap = 76; } $mail->WordWrap = $wordwrap; $mail->setWordWrap(); if (!$html) { $mail->ContentType = 'text/plain'; } else { $mail->ContentType = 'text/html'; } $i = 0; // Handle Graph Attachments if (!empty($attachments) && !is_array($attachments)) { $attachments = array('attachment' => $attachments); } if (is_array($attachments) && cacti_sizeof($attachments)) { $graph_mode = (substr_count($body, '<GRAPH>') > 0); $graph_ids = (substr_count($body, '<GRAPH:') > 0); $default_opts = array( // MIME type to be set against the attachment 'mime_type' => '', // Display name of the attachment 'filename' => '', // String containing attachment for image-based attachments 'attachment' => '', // Whether to attach inline or as attachment 'inline' => ($graph_mode || $graph_ids) ? 'inline' : 'attachment', // Encoding type, normally base64 'encoding' => 'base64', ); foreach($attachments as $attachment) { if (!is_array($attachment)) { $attachment = array('attachment' => $attachment); } foreach ($default_opts as $opt_name => $opt_default) { if (!array_key_exists($opt_name, $attachment)) { $attachment[$opt_name] = $opt_default; } } if (!empty($attachment['attachment'])) { /* get content id and create attachment */ $cid = getmypid() . '_' . $i . '@' . 'localhost'; if (empty($attachment['filename'])) { $attachment['filename'] = basename($attachment['attachment']); } /* attempt to attach */ if (!($graph_mode || $graph_ids)) { $result = $mail->addAttachment($attachment['attachment'], $attachment['filename'], $attachment['encoding'], $attachment['mime_type'], $attachment['inline']); } else { $result = $mail->addStringEmbeddedImage($attachment['attachment'], $cid, $attachment['filename'], 'base64', $attachment['mime_type'], $attachment['inline']); } if ($result == false) { cacti_log('ERROR: ' . $mail->ErrorInfo, false, 'MAILER'); return $mail->ErrorInfo; } $i++; if ($graph_mode) { $body = str_replace('<GRAPH>', "<br><br><img src='cid:$cid'>", $body); } else if ($graph_ids) { /* handle the body text */ switch ($attachment['inline']) { case 'inline': $body = str_replace('<GRAPH:' . $attachment['local_graph_id'] . ':' . $attachment['timespan'] . '>', "<img src='cid:$cid' >", $body); break; case 'attachment': $body = str_replace('<GRAPH:' . $attachment['local_graph_id'] . ':' . $attachment['timespan'] . '>', '', $body); break; } } } } } /* process custom headers */ if (is_array($headers) && cacti_sizeof($headers)) { foreach($headers as $name => $value) { $mail->addCustomHeader($name, $value); } } // Set both html and non-html bodies $brs = array('<br>', '<br />', '</br>'); if ($html) { $body = $body . '<br>'; } if ($body_text == '') { $body_text = strip_tags(str_ireplace($brs, "\n", $body)); } $mail->isHTML($html); $mail->Body = ($html ? $body : $body_text); if ($html && $body_text != '') { $mail->AltBody = $body_text; } $result = $mail->send(); $error = $mail->ErrorInfo; //$result ? '' : $mail->ErrorInfo; $method = $mail_methods[intval(read_config_option('settings_how'))]; $rtype = $result ? 'INFO' : 'WARNING'; $rmsg = $result ? 'successfully sent' : 'failed'; if ($error != '') { $message = sprintf("%s: Mail %s via %s from '%s', to '%s', cc '%s', Subject '%s'%s", $rtype, $rmsg, $method, $fromText, $toText, $ccText, $subject, ", Error: $error"); } else { $message = sprintf("%s: Mail %s via %s from '%s', to '%s', cc '%s', Subject '%s'", $rtype, $rmsg, $method, $fromText, $toText, $ccText, $subject); } cacti_log($message, false, 'MAILER'); if ($result == false) { cacti_log(cacti_debug_backtrace($rtype), false, 'MAILER'); } return $error; } function record_mailer_error($retError, $mailError) { $errorInfo = empty($retError) ? $mailError : $retError; cacti_log('ERROR: ' . $errorInfo, false, 'CMDPHP MAILER'); cacti_debug_backtrace('MAILER ERROR'); return $errorInfo; } function add_email_details($emails, &$result, callable $addFunc) { $arrText = array(); foreach ($emails as $e) { if (!empty($e['email'])) { //if (is_callable($addFunc)) { if (!empty($addFunc)) { $result = $addFunc($e['email'], $e['name']); if (!$result) { return ''; } } $arrText[] = create_emailtext($e); } else if (!empty($e['name'])) { $result = false; return 'Bad email format, name but no address: ' . $e['name']; } } $text = implode(',', $arrText); //echo "add_email_sw_details(): $text\n"; return $text; } function parse_email_details($emails, $max_records = 0, $details = array()) { if (!is_array($emails)) { $emails = array($emails); } $update = array(); foreach ($emails as $check_email) { if (!empty($check_email)) { if (!is_array($check_email)) { $emails = explode(',', $check_email); foreach($emails as $email) { $email_array = split_emaildetail($email); $details[] = $email_array; } } else { $has_name = array_key_exists('name', $check_email); $has_email = array_key_exists('email', $check_email); if ($has_name || $has_email) { $name = $has_name ? $check_email['name'] : ''; $email = $has_email ? $check_email['email'] : ''; } else { $name = array_key_exists(1, $check_email) ? $check_email[1] : ''; $email = array_key_exists(0, $check_email) ? $check_email[0] : ''; } $details[] = array('name' => trim($name), 'email' => trim($email)); } } } if ($max_records == 1) { $results = count($details) ? $details[0] : array(); } elseif ($max_records != 0 && $max_records < count($details)) { $results = array(); foreach ($details as $d) { $results[] = $d; $max_records--; if ($max_records == 0) { break; } } } else { $results = $details; } return $results; } function split_emaildetail($email) { $rname = ''; $rmail = ''; if (!is_array($email)) { $email = trim($email); $sPattern = '/(?:"?([^"]*)"?\s)?(?:<?(.+@[^>]+)>?)/i'; preg_match($sPattern, $email, $aMatch); if (isset($aMatch[1])) { $rname = trim($aMatch[1]); } if (isset($aMatch[2])) { $rmail = trim($aMatch[2]); } } else { $rmail = $email[0]; $rname = $email[1]; } return array('name' => $rname, 'email' => $rmail); } function create_emailtext($e) { if (empty($e['email'])) { $text = ''; } else { if (empty($e['name'])) { $text = $e['email']; } else { $text = $e['name'] . ' <' . $e['email'] . '>'; } } return $text; } function ping_mail_server($host, $port, $user, $password, $timeout = 10, $secure = 'none') { global $config; require_once($config['include_path'] . '/vendor/phpmailer/src/Exception.php'); require_once($config['include_path'] . '/vendor/phpmailer/src/PHPMailer.php'); require_once($config['include_path'] . '/vendor/phpmailer/src/SMTP.php'); //Create a new SMTP instance $smtp = new PHPMailer\PHPMailer\SMTP; if (!empty($secure) && $secure != 'none') { $smtp->SMTPSecure = $secure; if (substr_count($host, ':') == 0) { $host = $secure . '://' . $host; } } else { $smtp->SMTPAutoTLS = false; $smtp->SMTPSecure = false; } //Enable connection-level debug output $smtp->do_debug = 0; //$smtp->do_debug = SMTP::DEBUG_LOWLEVEL; $results = true; try { //Connect to an SMTP server if ($smtp->connect($host, $port, $timeout)) { //Say hello if ($smtp->hello(gethostbyname(gethostname()))) { //Put your host name in here //Authenticate if ($user != '') { if ($smtp->authenticate($user, $password)) { $results = true; } else { throw new Exception(__('Authentication failed: %s', $smtp->getLastReply())); } } } else { throw new Exception(__('HELO failed: %s', $smtp->getLastReply())); } } else { throw new Exception(__('Connect failed: %s', $smtp->getLastReply())); } } catch (Exception $e) { $results = __('SMTP error: ') . $e->getMessage(); cacti_log($results); } //Whatever happened, close the connection. $smtp->quit(true); return $results; } function email_test() { global $config; $message = __('This is a test message generated from Cacti. This message was sent to test the configuration of your Mail Settings.') . '<br><br>'; $message .= __('Your email settings are currently set as follows') . '<br><br>'; $message .= '<b>' . __('Method') . '</b>: '; print __('Checking Configuration...<br>'); $ping_results = true; $how = read_config_option('settings_how'); if ($how < 0 || $how > 2) $how = 0; if ($how == 0) { $mail = __('PHP\'s Mailer Class'); } elseif ($how == 1) { $mail = __('Sendmail') . '<br><b>' . __('Sendmail Path'). '</b>: '; $sendmail = read_config_option('settings_sendmail_path'); $mail .= $sendmail; } elseif ($how == 2) { print __('Method: SMTP') . '<br>'; $mail = __('SMTP') . '<br>'; $smtp_host = read_config_option('settings_smtp_host'); $smtp_port = read_config_option('settings_smtp_port'); $smtp_username = read_config_option('settings_smtp_username'); $smtp_password = read_config_option('settings_smtp_password'); $smtp_secure = read_config_option('settings_smtp_secure'); $smtp_timeout = read_config_option('settings_smtp_timeout'); $mail .= "<b>" . __('Device') . "</b>: $smtp_host<br>"; $mail .= "<b>" . __('Port') . "</b>: $smtp_port<br>"; if ($smtp_username != '' && $smtp_password != '') { $mail .= '<b>' . __('Authentication') . '</b>: true<br>'; $mail .= '<b>' . __('Username') . "</b>: $smtp_username<br>"; $mail .= '<b>' . __('Password') . '</b>: (' . __('Not Shown for Security Reasons') . ')<br>'; $mail .= '<b>' . __('Security') . "</b>: $smtp_secure<br>"; } else { $mail .= '<b>' . __('Authentication') . '</b>: false<br>'; } if (read_config_option('settings_ping_mail') == 0) { $ping_results = ping_mail_server($smtp_host, $smtp_port, $smtp_username, $smtp_password, $smtp_timeout, $smtp_secure); print __('Ping Results:') . ' ' . ($ping_results == 1 ? __('Success'):$ping_results) . '<br>'; if ($ping_results != 1) { $mail .= '<b>' . __('Ping Results') . '</b>: ' . $ping_results . '<br>'; } else { $mail .= '<b>' . __('Ping Results') . '</b>: ' . __('Success') . '<br>'; } } else { $ping_results = 1; $mail .= '<b>' . __('Ping Results') . '</b>: ' . __('Bypassed') . '<br>'; } } $message .= $mail; $message .= '<br>'; $errors = ''; if ($ping_results == 1) { print __('Creating Message Text...') . '<br><br>'; print "<center><table><tr><td>"; print "<table style='width:100%;'><tr><td>$message</td><tr></table></table></center><br>"; print __('Sending Message...') . '<br><br>'; $global_alert_address = read_config_option('settings_test_email'); $errors = send_mail($global_alert_address, '', __('Cacti Test Message'), $message, '', '', true); if ($errors == '') { $errors = __('Success!'); } } else { print __('Message Not Sent due to ping failure.'). '<br><br>'; } print "<center><table><tr><td>"; print "<table><tr><td>$errors</td><tr></table></table></center>"; } /* gethostbyaddr_wtimeout - This function provides a good method of performing a rapid lookup of a DNS entry for a host so long as you don't have to look far. */ function get_dns_from_ip ($ip, $dns, $timeout = 1000) { /* random transaction number (for routers etc to get the reply back) */ $data = rand(10, 99); /* trim it to 2 bytes */ $data = substr($data, 0, 2); /* create request header */ $data .= "\1\0\0\1\0\0\0\0\0\0"; /* split IP into octets */ $octets = explode('.', $ip); /* perform a quick error check */ if (cacti_count($octets) != 4) return 'ERROR'; /* needs a byte to indicate the length of each segment of the request */ for ($x=3; $x>=0; $x--) { switch (strlen($octets[$x])) { case 1: // 1 byte long segment $data .= "\1"; break; case 2: // 2 byte long segment $data .= "\2"; break; case 3: // 3 byte long segment $data .= "\3"; break; default: // segment is too big, invalid IP return 'ERROR'; } /* and the segment itself */ $data .= $octets[$x]; } /* and the final bit of the request */ $data .= "\7in-addr\4arpa\0\0\x0C\0\1"; /* create UDP socket */ $handle = @fsockopen("udp://$dns", 53); @stream_set_timeout($handle, floor($timeout/1000), ($timeout*1000)%1000000); @stream_set_blocking($handle, 1); /* send our request (and store request size so we can cheat later) */ $requestsize = @fwrite($handle, $data); /* get the response */ $response = @fread($handle, 1000); /* check to see if it timed out */ $info = @stream_get_meta_data($handle); /* close the socket */ @fclose($handle); if ($info['timed_out']) { return 'timed_out'; } /* more error handling */ if ($response == '') { return $ip; } /* parse the response and find the response type */ $type = @unpack('s', substr($response, $requestsize+2)); if (isset($type[1]) && $type[1] == 0x0C00) { /* set up our variables */ $host = ''; $len = 0; /* set our pointer at the beginning of the hostname uses the request size from earlier rather than work it out. */ $position = $requestsize + 12; /* reconstruct the hostname */ do { /* get segment size */ $len = unpack('c', substr($response, $position)); /* null terminated string, so length 0 = finished */ if ($len[1] == 0) { /* return the hostname, without the trailing '.' */ return strtoupper(substr($host, 0, strlen($host) -1)); } /* add the next segment to our host */ $host .= substr($response, $position+1, $len[1]) . '.'; /* move pointer on to the next segment */ $position += $len[1] + 1; } while ($len != 0); /* error - return the hostname we constructed (without the . on the end) */ return strtoupper($ip); } /* error - return the hostname */ return strtoupper($ip); } function poller_maintenance () { global $config; $command_string = cacti_escapeshellcmd(read_config_option('path_php_binary')); // If its not set, just assume its in the path if (trim($command_string) == '') { $command_string = 'php'; } $extra_args = ' -q ' . cacti_escapeshellarg($config['base_path'] . '/poller_maintenance.php'); exec_background($command_string, $extra_args); } function clog_admin() { if (!isset($_SESSION['sess_clog_level'])) { clog_authorized(); } if ($_SESSION["sess_clog_level"] == CLOG_PERM_ADMIN) { return true; } else { return false; } } function clog_authorized() { if (!isset($_SESSION['sess_clog_level'])) { if (isset($_SESSION['sess_user_id'])) { if (is_realm_allowed(18)) { $_SESSION['sess_clog_level'] = CLOG_PERM_ADMIN; } else { if (is_realm_allowed(19)) { $_SESSION['sess_clog_level'] = CLOG_PERM_USER; }else { $_SESSION['sess_clog_level'] = CLOG_PERM_NONE; } } } else { $_SESSION['sess_clog_level'] = CLOG_PERM_NONE; } } if ($_SESSION['sess_clog_level'] == CLOG_PERM_USER) { return true; } elseif ($_SESSION['sess_clog_level'] == CLOG_PERM_ADMIN) { return true; } else { return false; } } function update_system_mibs($host_id) { global $sessions; $system_mibs = array( 'snmp_sysDescr' => '.1.3.6.1.2.1.1.1.0', 'snmp_sysObjectID' => '.1.3.6.1.2.1.1.2.0', 'snmp_sysUpTimeInstance' => '.1.3.6.1.2.1.1.3.0', 'snmp_sysContact' => '.1.3.6.1.2.1.1.4.0', 'snmp_sysName' => '.1.3.6.1.2.1.1.5.0', 'snmp_sysLocation' => '.1.3.6.1.2.1.1.6.0' ); $h = db_fetch_row_prepared('SELECT * FROM host WHERE id = ?', array($host_id)); if (cacti_sizeof($h)) { open_snmp_session($host_id, $h); if (isset($sessions[$host_id . '_' . $h['snmp_version'] . '_' . $h['snmp_port']])) { foreach($system_mibs as $name => $oid) { $value = cacti_snmp_session_get($sessions[$host_id . '_' . $h['snmp_version'] . '_' . $h['snmp_port']], $oid); if (!empty($value)) { db_execute_prepared("UPDATE host SET $name = ? WHERE id = ?", array($value, $host_id)); } } } else { cacti_log("WARNING: Unable to open session for System Mib collection for Device[$host_id]", false, 'POLLER'); } } } function cacti_debug_backtrace($entry = '', $html = false, $record = true, $limit = 0, $skip = 0) { global $config; $skip = $skip >= 0 ? $skip : 1; $limit = $limit > 0 ? ($limit + $skip) : 0; $callers = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, $limit); while ($skip > 0) { array_shift($callers); $skip--; } $s=''; foreach ($callers as $c) { if (isset($c['line'])) { $line = '[' . $c['line'] . ']'; } else { $line = ''; } if (isset($c['file'])) { $file = str_replace($config['base_path'], '', $c['file']) . $line; } else { $file = $line; } $func = $c['function'].'()'; if (isset($c['class'])) { $func = $c['class'] . $c['type'] . $func; } $s = ($file != '' ? $file . ':':'') . "$func" . (empty($s) ? '' : ', ') . $s; } if (!empty($s)) { $s = ' (' . $s . ')'; } if ($record) { if ($html) { echo "<table style='width:100%;text-align:center;'><tr><td>$s</td></tr></table>\n"; } cacti_log(trim("$entry Backtrace: " . clean_up_lines($s)), false); } else { if (!empty($entry)) { return trim("$entry Backtrace: " . clean_up_lines($s)); } else { return trim(clean_up_lines($s)); } } } /* calculate_percentiles - Given and array of numbers, calculate the Nth percentile, * optionally, return an array of numbers containing elements required for * a whisker chart. * * @arg $data - an array of data * @arg $percentile - the Nth percentile to calculate. By default 95th. * #arg $whisker - if whisker is true, an array of values will be returned * including 25th, median, 75th, and 90th percentiles. * * @returns - either the Nth percentile, the elements for a whisker chart, * or false if there is insufficient data to determine. */ function calculate_percentiles($data, $percentile = 95, $whisker = false) { if ($percentile > 0 && $percentile < 1) { $p = $percentile; } elseif ($percentile > 1 && $percentile <= 100) { $p = $percentile * .01; }else { return false; } if ($whisker) { $tiles = array( '25th' => 0.25, '50th' => 0.50, '75th' => 0.75, '90th' => 0.90, '95th' => 0.95, ); } else { $tiles = array( 'custom' => $p ); } $results = array(); $elements = cacti_sizeof($data); /* sort the array to return */ sort($data); foreach($tiles as $index => $p) { /* calculate offsets into the array */ $allindex = ($elements - 1) * $p; $intvalindex = intval($allindex); $floatval = $allindex - $intvalindex; if (!is_float($floatval)) { $ptile = $data[$intvalindex]; } else { if ($elements > $intvalindex + 1) { $ptile = $floatval * ($data[$intvalindex + 1] - $data[$intvalindex]) + $data[$intvalindex]; } else { $ptile = $data[$intvalindex]; } } if ($index == 'custom') { return $ptile; } else { $results[$index] = $ptile; } } return $results; } function get_timeinstate($host) { $interval = read_config_option('poller_interval'); if ($host['availability_method'] == 0) { $time = 0; } elseif (isset($host['instate'])) { $time = $host['instate']; } elseif ($host['status_event_count'] > 0 && ($host['status'] == 1 || $host['status'] == 2)) { $time = $host['status_event_count'] * $interval; } elseif (strtotime($host['status_rec_date']) < 943916400 && ($host['status'] == 0 || $host['status'] == 3)) { $time = $host['total_polls'] * $interval; } elseif (strtotime($host['status_rec_date']) > 943916400) { $time = time() - strtotime($host['status_rec_date']); } elseif ($host['snmp_sysUpTimeInstance'] > 0) { $time = $host['snmp_sysUpTimeInstance']/100; } else { $time = 0; } return ($time > 0) ? get_daysfromtime($time) : __('N/A'); } function get_uptime($host) { return ($host['snmp_sysUpTimeInstance'] > 0) ? get_daysfromtime($host['snmp_sysUpTimeInstance']/100) : __('N/A'); } function get_daysfromtime($time, $secs = false, $pad = '', $format = DAYS_FORMAT_SHORT, $all = false) { global $days_from_time_settings; // Ensure we use an existing format or we'll end up with no text at all if (!isset($days_from_time_settings['text'][$format])) { $format = DAYS_FORMAT_SHORT; } $mods = $days_from_time_settings['mods']; $text = $days_from_time_settings['text'][$format]; $result = ''; foreach ($mods as $index => $mod) { if ($mod > 0 || $secs) { if ($time >= $mod) { if ($mod < 1) { $mod = 1; } $val = floor($time/$mod); $time %= $mod; } else { $val = 0; } if ($all || $val > 0) { $result .= padleft($pad, $val, 2) . $text['prefix'] . $text[$index] . $text['suffix']; $all = true; } } } return trim($result,$text['suffix']); } function padleft($pad = '', $value, $min = 2) { $result = "$value"; if (strlen($result) < $min && $pad != '') { $padded = $pad . $result; while ($padded != $result && strlen($result) < $min) { $padded = $pad . $result; } $result = $padded; } return $result; } function get_classic_tabimage($text, $down = false) { global $config; $images = array( false => 'tab_template_blue.gif', true => 'tab_template_red.gif' ); if ($text == '') return false; $text = strtolower($text); $possibles = array( array('DejaVuSans-Bold.ttf', 9, true), array('DejaVuSansCondensed-Bold.ttf', 9, false), array('DejaVuSans-Bold.ttf', 9, false), array('DejaVuSansCondensed-Bold.ttf', 9, false), array('DejaVuSans-Bold.ttf', 8, false), array('DejaVuSansCondensed-Bold.ttf', 8, false), array('DejaVuSans-Bold.ttf', 7, false), array('DejaVuSansCondensed-Bold.ttf', 7, true), ); $y = 30; $x = 44; $wlimit = 72; $wrapsize = 12; if (file_exists($config['base_path'] . '/images/' . $images[$down])) { $originalpath = getenv('GDFONTPATH'); putenv('GDFONTPATH=' . $config['base_path'] . '/include/fonts/'); $template = imagecreatefromgif($config['base_path'] . '/images/' . $images[$down]); $w = imagesx($template); $h = imagesy($template); $tab = imagecreatetruecolor($w, $h); imagecopy($tab, $template, 0, 0, 0, 0, $w, $h); $txcol = imagecolorat($tab, 0, 0); imagecolortransparent($tab,$txcol); $white = imagecolorallocate($tab, 255, 255, 255); $ttf_functions = function_exists('imagettftext') && function_exists('imagettfbbox'); if ($ttf_functions) { foreach ($possibles as $variation) { $font = $variation[0]; $fontsize = $variation[1]; $lines = array(); // if no wrapping is requested, or no wrapping is possible... if((!$variation[2]) || ($variation[2] && strpos($text,' ') === false)) { $bounds = imagettfbbox($fontsize, 0, $font, $text); $w = $bounds[4] - $bounds[0]; $h = $bounds[1] - $bounds[5]; $realx = $x - $w/2 -1; $lines[] = array($text, $font, $fontsize, $realx, $y); $maxw = $w; } else { $texts = explode("\n", wordwrap($text, $wrapsize), 2); $line = 1; $maxw = 0; foreach ($texts as $txt) { $bounds = imagettfbbox($fontsize, 0, $font, $txt); $w = $bounds[4] - $bounds[0]; $h = $bounds[1] - $bounds[5]; $realx = $x - $w/2 -1; $realy = $y - $h * $line + 3; $lines[] = array($txt, $font, $fontsize, $realx, $realy); if ($maxw < $w) { $maxw = $w; } $line--; } } if($maxw<$wlimit) break; } } else { while ($text > '') { for ($fontid = 5; $fontid>0; $fontid--) { $fontw = imagefontwidth($fontid); $fonth = imagefontheight($fontid); $realx = ($w - ($fontw * strlen($text)))/2; $realy = ($h - $fonth - 5); // Since we can't use FreeType, lets use a fixed location $lines = array(); $lines[] = array($text, $fontid, 0, $realx, $realy); if ($realx > 10 && $realy > 0) break; } if ($fontid == 0) { $spacer = strrpos($text,' '); if ($spacer === FALSE) { $spacer = strlen($text) - 1; } $text = substr($text,0,$spacer); // $lines[] = array(substr($text,0,$maxtext).'.'.$w.'.'.$maxtext.'.'.$fontw, $fontid, 0, $realx, $realy); } else { break; } } } foreach ($lines as $line) { if ($ttf_functions) { imagettftext($tab, $line[2], 0, $line[3], $line[4], $white, $line[1], $line[0]); }else{ imagestring($tab, $line[1], $line[3], $line[4], $line[0], $white); } } putenv('GDFONTPATH=' . $originalpath); imagetruecolortopalette($tab, true, 256); // generate the image an return the data directly ob_start(); imagegif($tab); $image = ob_get_contents(); ob_end_clean(); return("data:image/gif;base64," . base64_encode($image)); } else { return false; } } function cacti_oid_numeric_format() { if (function_exists('snmp_set_oid_output_format')) { snmp_set_oid_output_format(SNMP_OID_OUTPUT_NUMERIC); } elseif (function_exists("snmp_set_oid_numeric_print")) { snmp_set_oid_numeric_print(true); } } function IgnoreErrorHandler($message) { global $snmp_error; $snmp_ignore = array( 'No response from', 'noSuchName', 'No Such Object', 'Error in packet', 'This name does not exist', 'End of MIB', 'Timeout', 'Unknown host', 'Invalid object identifier', 'Name or service not known' ); foreach ($snmp_ignore as $i) { if (strpos($message, $i)) { $snmp_error = trim($message, "\\\n\t "); return true; } } $ignore = array( 'unable to read from socket' # ping.php line 387 socket refusal ); foreach ($ignore as $i) { if (strpos($message, $i)) { return true; } } return false; } function CactiErrorHandler($level, $message, $file, $line, $context) { global $phperrors; if (defined('IN_CACTI_INSTALL')) { return true; } if (IgnoreErrorHandler($message)) { return true; } if (error_reporting() == 0) { return true; } preg_match("/.*\/plugins\/([\w-]*)\/.*/", $file, $output_array); $plugin = (isset($output_array[1]) ? $output_array[1] : ''); $error = 'PHP ' . $phperrors[$level] . ($plugin != '' ? " in Plugin '$plugin'" : '') . ": $message in file: $file on line: $line"; switch ($level) { case E_COMPILE_ERROR: case E_CORE_ERROR: case E_ERROR: case E_PARSE: cacti_log($error, false, 'ERROR'); cacti_debug_backtrace('PHP ERROR PARSE', false, true, 0, 1); if ($plugin != '') { api_plugin_disable_all($plugin); cacti_log("ERRORS DETECTED - DISABLING PLUGIN '$plugin'"); admin_email(__('Cacti System Warning'), __('Cacti disabled plugin %s due to the following error: %s! See the Cacti logfile for more details.', $plugin, $error)); } break; case E_RECOVERABLE_ERROR: case E_USER_ERROR: cacti_log($error, false, 'ERROR'); cacti_debug_backtrace('PHP ERROR', false, true, 0, 1); break; case E_COMPILE_WARNING: case E_CORE_WARNING: case E_USER_WARNING: case E_WARNING: cacti_log($error, false, 'ERROR'); cacti_debug_backtrace('PHP ERROR WARNING', false, true, 0, 1); break; case E_NOTICE: case E_USER_NOTICE: cacti_log($error, false, 'ERROR'); cacti_debug_backtrace('PHP ERROR NOTICE', false, true, 0, 1); break; case E_STRICT: cacti_log($error, false, 'ERROR'); cacti_debug_backtrace('PHP ERROR STRICT', false, true, 0, 1); break; default: cacti_log($error, false, 'ERROR'); cacti_debug_backtrace('PHP ERROR', false, true, 0, 1); } return false; } function CactiShutdownHandler () { global $phperrors; $error = error_get_last(); if (IgnoreErrorHandler($error['message'])) { return true; } switch ($error['type']) { case E_ERROR: case E_CORE_ERROR: case E_COMPILE_ERROR: case E_CORE_WARNING: case E_COMPILE_WARNING: case E_PARSE: preg_match('/.*\/plugins\/([\w-]*)\/.*/', $error['file'], $output_array); $plugin = (isset($output_array[1]) ? $output_array[1] : '' ); $message = 'PHP ' . $phperrors[$error['type']] . ($plugin != '' ? " in Plugin '$plugin'" : '') . ': ' . $error['message'] . ' in file: ' . $error['file'] . ' on line: ' . $error['line']; cacti_log($message, false, 'ERROR'); cacti_debug_backtrace('PHP ERROR', false, true, 0, 1); if ($plugin != '') { api_plugin_disable_all($plugin); cacti_log("ERRORS DETECTED - DISABLING PLUGIN '$plugin'"); admin_email(__('Cacti System Warning'), __('Cacti disabled plugin %s due to the following error: %s! See the Cacti logfile for more details.', $plugin, $message)); } } } /** enable_device_debug - Enables device debug for a device * if it is disabled. * * @arg $host_id - the device id to search for * * @returns - void */ function enable_device_debug($host_id) { $device_debug = read_config_option('selective_device_debug', true); if ($device_debug != '') { $devices = explode(',', $device_debug); if (array_search($host_id, $devices) === false) { set_config_option('selective_device_debug', $device_debug . ',' . $host_id); } } else { set_config_option('selective_device_debug', $host_id); } } /** disable_device_debug - Disables device debug for a device * if it is enabled. * * @arg $host_id - the device id to search for * * @returns - void */ function disable_device_debug($host_id) { $device_debug = read_config_option('selective_device_debug', true); if ($device_debug != '') { $devices = explode(',', $device_debug); foreach($devices as $key => $device) { if ($device == $host_id) { unset($devices[$key]); break; } } set_config_option('selective_device_debug', implode(',', $devices)); } } /** is_device_debug_enabled - Determines if device debug is enabled * for a device. * * @arg $host_id - the device id to search for * * @returns - boolean true or false */ function is_device_debug_enabled($host_id) { $device_debug = read_config_option('selective_device_debug', true); if ($device_debug != '') { $devices = explode(',', $device_debug); if (array_search($host_id, $devices) !== false) { return true; } } return false; } /** get_url_type - Determines if remote communications are over * http or https for remote services. * * @returns - http or https */ function get_url_type() { if (read_config_option('force_https') == 'on') { return 'https'; } else { return 'http'; } } /** get_default_contextoption - Sets default context options for self-signed SSL * related protocols if necessary. Allows plugins to add additional header information * to fulfill system setup related requirements like the usage of Web Single Login * cookies for example. * * @returns - an array of stream context options or false */ function get_default_contextoption($timeout = '') { $fgc_contextoption = false; if ($timeout == '') { $timeout = read_config_option('remote_agent_timeout'); } if (!is_numeric($timeout)) { $timeout = 5; } $protocol = get_url_type(); if (in_array($protocol, array('ssl', 'https', 'ftps'))) { $fgc_contextoption = array( 'ssl' => array( 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true, ) ); } if ($protocol == 'https') { $fgc_contextoption['https'] = array( 'timeout' => $timeout, 'ignore_errors' => true ); } elseif ($protocol == 'http') { $fgc_contextoption['http'] = array( 'timeout' => $timeout, 'ignore_errors' => true ); } $fgc_contextoption = api_plugin_hook_function('fgc_contextoption', $fgc_contextoption); return $fgc_contextoption; } /** repair_system_data_input_methods - This utility will repair * system data input methods when they are detected on the system * * @returns - null */ function repair_system_data_input_methods($step = 'import') { $system_hashes = array( '3eb92bb845b9660a7445cf9740726522', // Get SNMP Data 'bf566c869ac6443b0c75d1c32b5a350e', // Get SNMP Data (Indexed) '80e9e4c4191a5da189ae26d0e237f015', // Get Script Data (Indexed) '332111d8b54ac8ce939af87a7eac0c06', // Get Script Server Data (Indexed) ); $good_field_hashes = array( '3eb92bb845b9660a7445cf9740726522' => array( // Get SNMP Data (1) '92f5906c8dc0f964b41f4253df582c38', // IP Address '012ccb1d3687d3edb29c002ea66e72da', // SNMP Version '32285d5bf16e56c478f5e83f32cda9ef', // SNMP Community 'fc64b99742ec417cc424dbf8c7692d36', // SNMP Port 'ad14ac90641aed388139f6ba86a2e48b', // SNMP Username '9c55a74bd571b4f00a96fd4b793278c6', // SNMP Password '20832ce12f099c8e54140793a091af90', // SNMP Authentication Protocol 'c60c9aac1e1b3555ea0620b8bbfd82cb', // SNMP Privacy Passphrase 'feda162701240101bc74148415ef415a', // SNMP Privacy Protocol '4276a5ec6e3fe33995129041b1909762' // SNMP OID ), 'bf566c869ac6443b0c75d1c32b5a350e' => array( // Get SNMP Data (Indexed) (2) '617cdc8a230615e59f06f361ef6e7728', // IP Address 'b5c23f246559df38662c255f4aa21d6b', // SNMP Version 'acb449d1451e8a2a655c2c99d31142c7', // SNMP Community 'c1f36ee60c3dc98945556d57f26e475b', // SNMP Port 'f4facc5e2ca7ebee621f09bc6d9fc792', // SNMP Username '1cc1493a6781af2c478fa4de971531cf', // SNMP Password '2cf7129ad3ff819a7a7ac189bee48ce8', // SNMP Authentication Protocol '6b13ac0a0194e171d241d4b06f913158', // SNMP Privacy Passphrase '3a33d4fc65b8329ab2ac46a36da26b72', // SNMP Privacy Protocol '6027a919c7c7731fbe095b6f53ab127b', // Index Type 'cbbe5c1ddfb264a6e5d509ce1c78c95f', // Index Value 'e6deda7be0f391399c5130e7c4a48b28' // Output Type ID ), '80e9e4c4191a5da189ae26d0e237f015' => array( // Get Script Data (Indexed) 11 'd39556ecad6166701bfb0e28c5a11108', // Index Type '3b7caa46eb809fc238de6ef18b6e10d5', // Index Value '74af2e42dc12956c4817c2ef5d9983f9', // Output Type ID '8ae57f09f787656bf4ac541e8bd12537' // Output Value ), '332111d8b54ac8ce939af87a7eac0c06' => array( // Get Script Server Data (Indexed) 12 '172b4b0eacee4948c6479f587b62e512', // Index Type '30fb5d5bcf3d66bb5abe88596f357c26', // Index Value '31112c85ae4ff821d3b288336288818c', // Output Type ID '5be8fa85472d89c621790b43510b5043' // Output Value ) ); foreach($good_field_hashes as $hash => $field_hashes) { $data_input_id = db_fetch_cell_prepared('SELECT id FROM data_input WHERE hash = ?', array($hash)); if (!empty($data_input_id)) { $bad_hashes = db_fetch_assoc_prepared('SELECT * FROM data_input_fields WHERE hash NOT IN ("' . implode('","', $field_hashes) . '") AND hash != "" AND data_input_id = ?', array($data_input_id)); if (cacti_sizeof($bad_hashes)) { cacti_log(strtoupper($step) . ' NOTE: Repairing ' . cacti_sizeof($bad_hashes) . ' Damaged data_input_fields', false); foreach($bad_hashes as $bhash) { $good_field_id = db_fetch_cell_prepared('SELECT id FROM data_input_fields WHERE hash != ? AND data_input_id = ? AND data_name = ?', array($bhash['hash'], $data_input_id, $bhash['data_name'])); if (!empty($good_field_id)) { cacti_log("Data Input ID $data_input_id Bad Field ID is " . $bhash['id'] . ", Good Field ID: " . $good_field_id, false, 'WEBUI', POLLER_VERBOSITY_DEVDBG); cacti_log('Executing Data Input Data Check', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG); // Data Input Data $bad_mappings = db_fetch_assoc_prepared('SELECT * FROM data_input_data WHERE data_input_field_id = ?', array($bhash['id'])); if (cacti_sizeof($bad_mappings)) { cacti_log(strtoupper($step) . ' NOTE: Found ' . cacti_sizeof($bad_mappings) . ' Damaged data_input_fields', false); foreach($bad_mappings as $mfid) { $good_found = db_fetch_cell_prepared('SELECT COUNT(*) FROM data_input_data WHERE data_input_field_id = ? AND data_template_data_id = ?', array($good_field_id, $mfid['data_template_data_id'])); if ($good_found > 0) { cacti_log('Good Found for ' . $mfid['data_input_field_id'] . ', Fixing', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG); db_execute_prepared('DELETE FROM data_input_data WHERE data_input_field_id = ? AND data_template_data_id = ?', array($mfid['data_input_field_id'], $mfid['data_template_data_id'])); } else { cacti_log('Good NOT Found for ' . $mfid['data_input_field_id'] . ', Fixing', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG); db_execute_prepared('UPDATE data_input_data SET data_input_field_id = ? WHERE data_input_field_id = ? AND data_template_data_id = ?', array($good_field_id, $mfid['data_input_field_id'], $mfid['data_template_data_id'])); } } } else { cacti_log('No Bad Data Input Data Records', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG); } // Data Template RRD cacti_log('Executing Data Template RRD Check', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);; $bad_mappings = db_fetch_assoc_prepared('SELECT * FROM data_template_rrd WHERE data_input_field_id = ?', array($bhash['id'])); if (cacti_sizeof($bad_mappings)) { cacti_log(strtoupper($step) . ' NOTE: Found ' . cacti_sizeof($bad_mappings) . ' Damaged data_template_rrd', false); foreach($bad_mappings as $mfid) { $good_found = db_fetch_cell_prepared('SELECT COUNT(*) FROM data_template_rrd WHERE data_input_field_id = ? AND id = ?', array($good_field_id, $mfid['id'])); if ($good_found > 0) { cacti_log('Good Found for ' . $mfid['data_input_field_id'] . ', Fixing', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG); db_execute_prepared('DELETE FROM data_template_rrd WHERE data_input_field_id = ? AND id = ?', array($mfid['data_input_field_id'], $mfid['id'])); } else { cacti_log('Good NOT Found for ' . $mfid['data_input_field_id'] . ', Fixing', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG); db_execute_prepared('UPDATE data_template_rrd SET data_input_field_id = ? WHERE data_input_field_id = ? AND id = ?', array($good_field_id, $mfid['data_input_field_id'], $mfid['id'])); } } } else { cacti_log('No Bad Data Template RRD Records', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG); } db_execute_prepared('DELETE FROM data_input_fields WHERE hash = ?', array($bhash['hash'])); } else { cacti_log('WARNING: Could not find Cacti default matching hash for unknown system hash "' . $bhash['hash'] . '" for ' . $data_input_id . '. No repair performed.'); } } } } else { cacti_log("Could not find hash '" . $hash . "' for Data Input", false, 'WEBUI', POLLER_VERBOSITY_DEVDBG); } } } if (isset($config['cacti_server_os']) && $config['cacti_server_os'] == 'win32' && !function_exists('posix_kill')) { function posix_kill($pid, $signal = SIGTERM) { $wmi = new COM("winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\cimv2"); $procs = $wmi->ExecQuery("SELECT ProcessId FROM Win32_Process WHERE ProcessId='" . $pid . "'"); if (cacti_sizeof($procs)) { if ($signal == SIGTERM) { foreach($procs as $proc) { $proc->Terminate(); } } else { return true; } } else { return false; } } } function is_ipaddress($ip_address = '') { /* check for ipv4/v6 */ if (function_exists('filter_var')) { if (filter_var($ip_address, FILTER_VALIDATE_IP) !== false) { return true; } else { return false; } } elseif (inet_pton($ip_address) !== false) { return true; } else { return false; } } /** date_time_format create a format string for date/time * @return string returns date time format */ function date_time_format() { $datechar = array( GDC_HYPHEN => '-', GDC_SLASH => '/', GDC_DOT => '.' ); /* setup date format */ $date_fmt = read_config_option('default_date_format'); $dateCharSetting = read_config_option('default_datechar'); if (!isset($datechar[$dateCharSetting])) { $dateCharSetting = GDC_SLASH; } $datecharacter = $datechar[$dateCharSetting]; switch ($date_fmt) { case GD_MO_D_Y: return 'm' . $datecharacter . 'd' . $datecharacter . 'Y H:i:s'; case GD_MN_D_Y: return 'M' . $datecharacter . 'd' . $datecharacter . 'Y H:i:s'; case GD_D_MO_Y: return 'd' . $datecharacter . 'm' . $datecharacter . 'Y H:i:s'; case GD_D_MN_Y: return 'd' . $datecharacter . 'M' . $datecharacter . 'Y H:i:s'; case GD_Y_MO_D: return 'Y' . $datecharacter . 'm' . $datecharacter . 'd H:i:s'; case GD_Y_MN_D: return 'Y' . $datecharacter . 'M' . $datecharacter . 'd H:i:s'; default: return 'Y' . $datecharacter . 'm' . $datecharacter . 'd H:i:s'; } } /** * get_cacti_version Generic function to get the cacti version */ function get_cacti_version() { static $version = ''; if ($version == '') { $version = trim(db_fetch_cell('SELECT cacti FROM version LIMIT 1')); } return $version; } /** * get_cacti_version_text Return the cacti version text including beta moniker */ function get_cacti_version_text($include_version = true) { if ($include_version) { return trim(__('Version %s %s', CACTI_VERSION, (defined('CACTI_VERSION_BETA') ? __('- Beta %s', CACTI_VERSION_BETA):''))); } else { return trim(__('%s %s', CACTI_VERSION, (defined('CACTI_VERSION_BETA') ? __('- Beta %s', CACTI_VERSION_BETA):''))); } } /** * get_cacti_cli_version() { */ function get_cacti_cli_version() { $dbversion = get_cacti_version(); $version = get_cacti_version_text(false); return $version . ' (DB: ' . $dbversion . ')'; } /** * cacti_version_compare - Compare Cacti version numbers */ function cacti_version_compare($version1, $version2, $operator = '>') { $length = max(cacti_sizeof(explode('.', $version1)), cacti_sizeof(explode('.', $version2))); $version1 = version_to_decimal($version1, $length); $version2 = version_to_decimal($version2, $length); switch ($operator) { case '<': if ($version1 < $version2) { return true; } break; case '<=': if ($version1 <= $version2) { return true; } break; case '>=': if ($version1 >= $version2) { return true; } break; case '>': if ($version1 > $version2) { return true; } break; case '==': if ($version1 == $version2) { return true; } break; default: return version_compare($version1, $version2, $operator); } return false; } /** * version_to_decimal - convert version string to decimal */ function version_to_decimal($version, $length = 1) { $newver = ''; $minor = ''; $parts = explode('.', $version); foreach($parts as $part) { if (is_numeric($part)) { $part = substr('00' . $part, -2); $newver .= $part; } else { $minor = substr($part, -1); $major = substr($part, 0, strlen($part)-1); $major = substr('00' . $major, -2); $newver .= $major; } } if (cacti_sizeof($parts) < $length) { $i = cacti_sizeof($parts); while($i < $length) { $newver .= '00'; $i++; } } if ($minor != '') { $int = ord($minor); } else { $int = 0; } return hexdec($newver) * 1000 + $int; } /** * cacti_gethostinfo - obtains the dns information for a host */ function cacti_gethostinfo($hostname, $type = DNS_ALL) { return dns_get_record($hostname, $type); } /** * cacti_gethostbyname - a ip/ipv6 replacement for php's gethostbyname function */ function cacti_gethostbyname($hostname, $type = '') { if ($type == '') { $type = DNS_A + DNS_AAAA; } if ($type != DNS_AAAA) { $host = gethostbyname($hostname); if ($host !== $hostname) { return $host; } } $return = cacti_gethostinfo($hostname, $type); if (cacti_sizeof($return)) { foreach($return as $record) { switch($record['type']) { case 'A': return $record['ip']; break; case 'AAAA': return $record['ipv6']; break; } } } return $hostname; } function get_nonsystem_data_input($data_input_id) { global $hash_system_data_inputs; $diid = db_fetch_cell_prepared('SELECT id FROM data_input WHERE hash NOT IN ("' . implode('","', $hash_system_data_inputs) . '") AND id = ?', array($data_input_id)); return $diid; } function get_rrdtool_version() { return str_replace('rrd-', '', str_replace('.x', '.0', read_config_option('rrdtool_version', true))); } function get_installed_rrdtool_version() { global $config; if ($config['cacti_server_os'] == 'win32') { $shell = shell_exec(cacti_escapeshellcmd(read_config_option('path_rrdtool')) . ' -v'); } else { $shell = shell_exec(cacti_escapeshellcmd(read_config_option('path_rrdtool')) . ' -v 2>&1'); } $version = false; if (preg_match('/^RRDtool ([0-9.]+) /', $shell, $matches)) { global $rrdtool_versions; foreach ($rrdtool_versions as $rrdtool_version => $rrdtool_version_text) { if (cacti_version_compare($rrdtool_version, $matches[1], '<=')) { $version = $rrdtool_version; } } } return $version; } function get_md5_hash($path) { $md5 = 0; if (db_table_exists('poller_resource_cache')) { $md5 = db_fetch_cell_prepared('SELECT md5sum FROM poller_resource_cache WHERE `path` = ?', array($path)); } if (empty($md5)) { if (file_exists($path)) { $md5 = md5_file($path); } else { $md5 = md5_file(dirname(__FILE__) . '/../' . $path); } } return $md5; } function get_md5_include_js($path) { global $config; if (file_exists($path)) { $npath = str_replace($config['base_path'] . '/', '', $path); } else { $npath = $path; } return '<script type=\'text/javascript\' src=\'' . $config['url_path'] . $npath . '?' . get_md5_hash($path) . '\'></script>' . PHP_EOL; } function get_md5_include_css($path) { global $config; return '<link href=\''. $config['url_path'] . $path . '?' . get_md5_hash($path) . '\' type=\'text/css\' rel=\'stylesheet\'>' . PHP_EOL; } function is_resource_writable($path) { if (empty($path)) { return false; } if ($path{strlen($path)-1}=='/') { return is_resource_writable($path.uniqid(mt_rand()).'.tmp'); } if (file_exists($path)) { if (($f = @fopen($path, 'a'))) { fclose($f); return true; } return false; } if (($f = @fopen($path, 'w'))) { fclose($f); unlink($path); return true; } return false; } function get_validated_theme($theme, $defaultTheme) { global $config; if (isset($theme) && strlen($theme)) { $themePath = $config['base_path'] . '/include/themes/' . $theme . '/main.css'; if (file_exists($themePath)) { return $theme; } } return $defaultTheme; } function get_validated_language($language, $defaultLanguage) { if (isset($language) && strlen($language)) { return $language; } return $defaultLanguage; } function get_running_user() { global $config; // Easy way first $user = get_current_user(); if ($user != '') { return $user; } $user = getenv('USERNAME') ?: getenv('USER'); if ($user != '') { return $user; } // Falback method if ($config['cacti_server_os'] == 'win32') { return getenv('username'); } else { $tmp_user = ''; $tmp_file = tempnam(sys_get_temp_dir(), 'uid'); $f_owner = ''; if (is_resource_writable($tmp_file)) { if (file_exists($tmp_file)) { unlink($tmp_file); } file_put_contents($tmp_file, 'cacti'); $f_owner = fileowner($tmp_file); $f_source = 'file'; if (file_exists($tmp_file)) { unlink($tmp_file); } } if (empty($f_owner) && function_exists('posix_getuid')) { $f_owner = posix_getuid(); $f_source = 'posix'; } if (!empty($f_owner) && function_exists('posix_getpwuid1')) { $f_array = posix_getpwuid($f_owner); if (isset($f_array['name'])) { $tmp_user = $f_array['name']; } } if (empty($tmp_user)) { exec('id -nu', $o, $r); if ($r == 0) { $tmp_user = trim($o['0']); } } /*** Code left here for future development, don't think it is right *** * if (empty($tmp_user) && !empty($f_owner) && is_readable('/etc/passwd')) { exec(sprintf('grep :%s: /etc/passwd | cut -d: -f1', (int) $uid), $o, $r); if ($r == 0) { $tmp_user = 'passwd-' . trim($o['0']); } } */ return (empty($tmp_user) ? 'apache' : $tmp_user); } } function get_debug_prefix() { $dateTime = new DateTime('NOW'); $dateTime = $dateTime->format('Y-m-d H:i:s.u'); return sprintf('<[ %s | %7d ]> -- ', $dateTime, getmypid()); } function get_client_addr($client_addr = false) { if (isset($_SERVER['X-Forwarded-For'])) { $client_addr = $_SERVER['X-Forwarded-For']; } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $client_addr = $_SERVER['HTTP_X_FORWARDED_FOR']; } elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) { $client_addr = $_SERVER['HTTP_FORWARDED_FOR']; } elseif (isset($_SERVER['HTTP_FORWARDED'])) { $client_addr = $_SERVER['HTTP_FORWARDED']; } elseif (isset($_SERVER['REMOTE_ADDR'])) { $client_addr = $_SERVER['REMOTE_ADDR']; } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { $client_addr = $_SERVER['HTTP_CLIENT_IP']; } return $client_addr; } function cacti_pton($ipaddr) { // Strip out the netmask, if there is one. $subnet_pos = strpos($ipaddr, '/'); if ($subnet_pos) { $subnet = substr($ipaddr, $subnet_pos+1); $ipaddr = substr($ipaddr, 0, $subnet_pos); } else { $subnet = null; // No netmask present } // Convert address to packed format $addr = @inet_pton($ipaddr); if ($addr === false) { return false; } // Maximum netmask length = same as packed address $len = 8*strlen($addr); if (!empty($subnet)) { if (!is_numeric($subnet)) { return false; } elseif ($subnet > $len) { return false; } } if (!is_numeric($subnet)){ $subnet=$len; } else { $subnet=(int)$subnet; } // Create a hex expression of the subnet mask $mask=str_repeat('f',$subnet>>2); switch($subnet&3) { case 3: $mask.='e'; break; case 2: $mask.='c'; break; case 1: $mask.='8'; break; } $mask=str_pad($mask,$len>>2,'0'); // Packed representation of netmask $mask=pack('H*',$mask); $result = array('ip' => $addr, 'subnet' => $mask); return $result; } function cacti_ntop($addr) { if (empty($addr)) { return false; } if (is_array($addr)) { foreach ($addr as $ip) { $addr = $ip; break; } } return @inet_ntop($addr); } function cacti_ntoc($subnet, $ipv6 = false) { $result = false; $count = 0; foreach(str_split($subnet) as $char) { $i = ord($char); while (($i & 128) == 128) { $count++; $i = ($i << 1) % 256; } } return $count; } function cacti_ptoa($title, $addr) { // Let's display it as hexadecimal format foreach(str_split($addr) as $char) { print str_pad(dechex(ord($char)),2,'0',STR_PAD_LEFT); } } function cacti_sizeof($array) { return ($array === false || !is_array($array)) ? 0 : sizeof($array); } function cacti_count($array) { return ($array === false || !is_array($array)) ? 0 : count($array); } function is_function_enabled($name) { return function_exists($name) && !in_array($name, array_map('trim', explode(', ', ini_get('disable_functions')))) && strtolower(ini_get('safe_mode')) != 1; } function is_page_ajax() { if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' ) { return true; } return false; } function raise_ajax_permission_denied() { if (is_page_ajax()) { header('HTTP/1.1 401 ' . __('Permission Denied')); print __('You are not permitted to access this section of Cacti.') . ' ' . __('If you feel that this is an error. Please contact your Cacti Administrator.'); exit; } }
null
<?php /* +-------------------------------------------------------------------------+ | Copyright (C) 2004-2019 The Cacti Group | | | | This program is free software; you can redistribute it and/or | | modify it under the terms of the GNU General Public License | | as published by the Free Software Foundation; either version 2 | | of the License, or (at your option) any later version. | | | | This program is distributed in the hope that it will be useful, | | but WITHOUT ANY WARRANTY; without even the implied warranty of | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | | GNU General Public License for more details. | +-------------------------------------------------------------------------+ | Cacti: The Complete RRDtool-based Graphing Solution | +-------------------------------------------------------------------------+ | This code is designed, written, and maintained by the Cacti Group. See | | about.php and/or the AUTHORS file for specific developer information. | +-------------------------------------------------------------------------+ | http://www.cacti.net/ | +-------------------------------------------------------------------------+ */ /* title_trim - takes a string of text, truncates it to $max_length and appends three periods onto the end @arg $text - the string to evaluate @arg $max_length - the maximum number of characters the string can contain before it is truncated @returns - the truncated string if len($text) is greater than $max_length, else the original string */ function title_trim($text, $max_length) { if (strlen($text) > $max_length) { return mb_substr($text, 0, $max_length) . '...'; } else { return $text; } } /* filter_value - a quick way to highlight text in a table from general filtering @arg $text - the string to filter @arg $filter - the search term to filter for @arg $href - the href if you wish to have an anchor returned @returns - the filtered string */ function filter_value($value, $filter, $href = '') { static $charset; if ($charset == '') { $charset = ini_get('default_charset'); } if ($charset == '') { $charset = 'UTF-8'; } $value = htmlspecialchars($value, ENT_QUOTES, $charset, false); if ($filter != '') { $value = preg_replace('#(' . $filter . ')#i', "<span class='filteredValue'>\\1</span>", $value); } if ($href != '') { $value = '<a class="linkEditMain" href="' . htmlspecialchars($href, ENT_QUOTES, $charset, false) . '">' . $value . '</a>'; } return $value; } /* set_graph_config_option - deprecated - wrapper to set_user_setting(). @arg $config_name - the name of the configuration setting as specified $settings array @arg $value - the values to be saved @arg $user - the user id, otherwise the session user @returns - void */ function set_graph_config_option($config_name, $value, $user = -1) { set_user_setting($config_name, $value, $user); } /* graph_config_value_exists - deprecated - wrapper to user_setting_exists @arg $config_name - the name of the configuration setting as specified $settings_user array in 'include/global_settings.php' @arg $user_id - the id of the user to check the configuration value for @returns (bool) - true if a value exists, false if a value does not exist */ function graph_config_value_exists($config_name, $user_id) { return user_setting_exists($config_name, $user_id); } /* read_default_graph_config_option - deprecated - wrapper to read_default_user_setting @arg $config_name - the name of the configuration setting as specified $settings array in 'include/global_settings.php' @returns - the default value of the configuration option */ function read_default_graph_config_option($config_name) { return read_default_user_setting($config_name); } /* read_graph_config_option - deprecated - finds the current value of a graph configuration setting @arg $config_name - the name of the configuration setting as specified $settings_user array in 'include/global_settings.php' @returns - the current value of the graph configuration option */ function read_graph_config_option($config_name, $force = false) { return read_user_setting($config_name, false, $force); } /* save_user_setting - sets/updates aLL user settings @arg $config_name - the name of the configuration setting as specified $settings array @arg $value - the values to be saved @arg $user - the user id, otherwise the session user @returns - void */ function save_user_settings($user = -1) { global $settings_user; if ($user == -1 || empty($user)) { $user = $_SESSION['sess_user_id']; } foreach ($settings_user as $tab_short_name => $tab_fields) { foreach ($tab_fields as $field_name => $field_array) { /* Check every field with a numeric default value and reset it to default if the inputted value is not numeric */ if (isset($field_array['default']) && is_numeric($field_array['default']) && !is_numeric(get_nfilter_request_var($field_name))) { set_request_var($field_name, $field_array['default']); } if (isset($field_array['method'])) { if ($field_array['method'] == 'checkbox') { set_user_setting($field_name, (isset_request_var($field_name) ? 'on' : ''), $user); } elseif ($field_array['method'] == 'checkbox_group') { foreach ($field_array['items'] as $sub_field_name => $sub_field_array) { set_user_setting($sub_field_name, (isset_request_var($sub_field_name) ? 'on' : ''), $user); } } elseif ($field_array['method'] == 'textbox_password') { if (get_nfilter_request_var($field_name) != get_nfilter_request_var($field_name.'_confirm')) { $_SESSION['sess_error_fields'][$field_name] = $field_name; $_SESSION['sess_field_values'][$field_name] = get_nfilter_request_var($field_name); $errors[4] = 4; } elseif (isset_request_var($field_name)) { set_user_setting($field_name, get_nfilter_request_var($field_name), $user); } } elseif ((isset($field_array['items'])) && (is_array($field_array['items']))) { foreach ($field_array['items'] as $sub_field_name => $sub_field_array) { if (isset_request_var($sub_field_name)) { set_user_setting($sub_field_name, get_nfilter_request_var($sub_field_name), $user); } } } elseif (isset_request_var($field_name)) { set_user_setting($field_name, get_nfilter_request_var($field_name), $user); } } } } } /* set_user_setting - sets/updates a user setting with the given value. @arg $config_name - the name of the configuration setting as specified $settings array @arg $value - the values to be saved @arg $user - the user id, otherwise the session user @returns - void */ function set_user_setting($config_name, $value, $user = -1) { global $settings_user; if ($user == -1 && isset($_SESSION['sess_user_id'])) { $user = $_SESSION['sess_user_id']; } if ($user == -1) { cacti_log('Attempt to set user setting \'' . $config_name . '\', with no user id: ' . cacti_debug_backtrace('', false, false, 0, 1), false, 'WARNING:'); } elseif (db_table_exists('settings_user')) { db_execute_prepared('REPLACE INTO settings_user SET user_id = ?, name = ?, value = ?', array($user, $config_name, $value)); unset($_SESSION['sess_user_config_array']); $settings_user[$config_name]['value'] = $value; } } /* user_setting_exists - determines if a value exists for the current user/setting specified @arg $config_name - the name of the configuration setting as specified $settings_user array in 'include/global_settings.php' @arg $user_id - the id of the user to check the configuration value for @returns (bool) - true if a value exists, false if a value does not exist */ function user_setting_exists($config_name, $user_id) { static $user_setting_values = array(); if (!isset($user_setting_values[$config_name])) { $value = 0; if (db_table_exists('settings_user')) { $value = db_fetch_cell_prepared('SELECT COUNT(*) FROM settings_user WHERE name = ? AND user_id = ?', array($config_name, $user_id)); } if ($value !== false && $value > 0) { $user_setting_values[$config_name] = true; } else { $user_setting_values[$config_name] = false; } } return $user_setting_values[$config_name]; } /* clear_user_setting - if a value exists for the current user/setting specified, removes it @arg $config_name - the name of the configuration setting as specified $settings_user array in 'include/global_settings.php' @arg $user_id - the id of the user to remove the configuration value for */ function clear_user_setting($config_name, $user = -1) { global $settings_user; if ($user == -1) { $user = $_SESSION['sess_user_id']; } if (db_table_exists('settings_user')) { db_execute_prepared('DELETE FROM settings_user WHERE name = ? AND user_id = ?', array($config_name, $user)); } unset($_SESSION['sess_user_config_array']); } /* read_default_user_setting - finds the default value of a user configuration setting @arg $config_name - the name of the configuration setting as specified $settings array in 'include/global_settings.php' @returns - the default value of the configuration option */ function read_default_user_setting($config_name) { global $config, $settings_user; foreach ($settings_user as $tab_array) { if (isset($tab_array[$config_name]) && isset($tab_array[$config_name]['default'])) { return $tab_array[$config_name]['default']; } else { foreach ($tab_array as $field_array) { if (isset($field_array['items']) && isset($field_array['items'][$config_name]) && isset($field_array['items'][$config_name]['default'])) { return $field_array['items'][$config_name]['default']; } } } } } /* read_user_setting - finds the current value of a graph configuration setting @arg $config_name - the name of the configuration setting as specified $settings_user array in 'include/global_settings.php' @arg $default - the default value is none is set @arg $force - pull the data from the database if true ignoring session @arg $user - assume this user's identity @returns - the current value of the user setting */ function read_user_setting($config_name, $default = false, $force = false, $user = 0) { global $config; /* users must have cacti user auth turned on to use this, or the guest account must be active */ if ($user == 0 && isset($_SESSION['sess_user_id'])) { $effective_uid = $_SESSION['sess_user_id']; } elseif (read_config_option('auth_method') == 0 || $user > 0) { /* first attempt to get the db setting for guest */ if ($user == 0) { $effective_uid = db_fetch_cell("SELECT user_auth.id FROM settings INNER JOIN user_auth ON user_auth.username = settings.value WHERE settings.name = 'guest_user'"); if ($effective_uid == '') { $effective_uid = 0; } } else { $effective_uid = $user; } $db_setting = false; if (db_table_exists('settings_user')) { $db_setting = db_fetch_row_prepared('SELECT value FROM settings_user WHERE name = ? AND user_id = ?', array($config_name, $effective_uid)); } if (cacti_sizeof($db_setting)) { return $db_setting['value']; } elseif ($default !== false) { return $default; } else { return read_default_user_setting($config_name); } } else { $effective_uid = 0; } if (!$force) { if (isset($_SESSION['sess_user_config_array'])) { $user_config_array = $_SESSION['sess_user_config_array']; } } if (!isset($user_config_array[$config_name])) { $db_setting = false; if (db_table_exists('settings_user')) { $db_setting = db_fetch_row_prepared('SELECT value FROM settings_user WHERE name = ? AND user_id = ?', array($config_name, $effective_uid)); } if (cacti_sizeof($db_setting)) { $user_config_array[$config_name] = $db_setting['value']; } elseif ($default !== false) { $user_config_array[$config_name] = $default; } else { $user_config_array[$config_name] = read_default_user_setting($config_name); } if (isset($_SESSION)) { $_SESSION['sess_user_config_array'] = $user_config_array; } else { $config['config_user_settings_array'] = $user_config_array; } } return $user_config_array[$config_name]; } /* set_config_option - sets/updates a cacti config option with the given value. @arg $config_name - the name of the configuration setting as specified $settings array @arg $value - the values to be saved @returns - void */ function set_config_option($config_name, $value) { global $config; db_execute_prepared('REPLACE INTO settings SET name = ?, value = ?', array($config_name, $value)); $config_array = array(); if (isset($_SESSION['sess_config_array'])) { $config_array = $_SESSION['sess_config_array']; } elseif (isset($config['config_options_array'])) { $config_array = $config['config_options_array']; } $config_array[$config_name] = $value; // Store the array back for later retrieval if (isset($_SESSION)) { $_SESSION['sess_config_array'] = $config_array; } else { $config['config_options_array'] = $config_array; } if (!empty($config['DEBUG_SET_CONFIG_OPTION'])) { file_put_contents(sys_get_temp_dir() . '/cacti-option.log', get_debug_prefix() . cacti_debug_backtrace($config_name, false, false, 0, 1) . "\n", FILE_APPEND); } } /* config_value_exists - determines if a value exists for the current user/setting specified @arg $config_name - the name of the configuration setting as specified $settings array in 'include/global_settings.php' @returns (bool) - true if a value exists, false if a value does not exist */ function config_value_exists($config_name) { static $config_values = array(); if (!isset($config_values[$config_name])) { $value = db_fetch_cell_prepared('SELECT COUNT(*) FROM settings WHERE name = ?', array($config_name)); if ($value > 0) { $config_values[$config_name] = true; } else { $config_values[$config_name] = false; } } return $config_values[$config_name]; } /* read_default_config_option - finds the default value of a Cacti configuration setting @arg $config_name - the name of the configuration setting as specified $settings array in 'include/global_settings.php' @returns - the default value of the configuration option */ function read_default_config_option($config_name) { global $config, $settings; if (is_array($settings)) { foreach ($settings as $tab_array) { if (isset($tab_array[$config_name]) && isset($tab_array[$config_name]['default'])) { return $tab_array[$config_name]['default']; } else { foreach ($tab_array as $field_array) { if (isset($field_array['items']) && isset($field_array['items'][$config_name]) && isset($field_array['items'][$config_name]['default'])) { return $field_array['items'][$config_name]['default']; } } } } } } /* read_config_option - finds the current value of a Cacti configuration setting @arg $config_name - the name of the configuration setting as specified $settings array in 'include/global_settings.php' @returns - the current value of the configuration option */ function read_config_option($config_name, $force = false) { global $config, $database_hostname, $database_default, $database_port, $database_sessions; $config_array = array(); if (isset($_SESSION['sess_config_array'])) { $config_array = $_SESSION['sess_config_array']; } elseif (isset($config['config_options_array'])) { $config_array = $config['config_options_array']; } if (!empty($config['DEBUG_READ_CONFIG_OPTION'])) { file_put_contents(sys_get_temp_dir() . '/cacti-option.log', get_debug_prefix() . cacti_debug_backtrace($config_name, false, false, 0, 1) . "\n", FILE_APPEND); } // Do we have a value already stored in the array, or // do we want to make sure we have the latest value // from the database? if (!array_key_exists($config_name, $config_array) || ($force)) { // We need to check against the DB, but lets assume default value // unless we can actually read the DB $value = read_default_config_option($config_name); if (!empty($config['DEBUG_READ_CONFIG_OPTION'])) { file_put_contents(sys_get_temp_dir() . '/cacti-option.log', get_debug_prefix() . " $config_name: " . ' dh: ' . isset($database_hostname) . ' dp: ' . isset($database_port) . ' dd: ' . isset($database_default) . ' ds: ' . isset($database_sessions["$database_hostname:$database_port:$database_default"]) . "\n", FILE_APPEND); if (isset($database_hostname) && isset($database_port) && isset($database_default)) { file_put_contents(sys_get_temp_dir() . '/cacti-option.log', get_debug_prefix() . " $config_name: [$database_hostname:$database_port:$database_default]\n", FILE_APPEND); } } // Are the database variables set, and do we have a connection?? // If we don't, we'll only use the default value without storing // so that we can read the database version later. if (isset($database_hostname) && isset($database_port) && isset($database_default) && isset($database_sessions["$database_hostname:$database_port:$database_default"])) { // Get the database setting $db_setting = db_fetch_row_prepared('SELECT value FROM settings WHERE name = ?', array($config_name), false); // Does the settings exist in the database? if (isset($db_setting['value'])) { // It does? lets use it $value = $db_setting['value']; } // Store whatever value we have in the array $config_array[$config_name] = $value; // Store the array back for later retrieval if (isset($_SESSION)) { $_SESSION['sess_config_array'] = $config_array; } else { $config['config_options_array'] = $config_array; } } } else { // We already have the value stored in the array and // we don't want to force a db read, so use the cached // version $value = $config_array[$config_name]; } return $value; } /* * get_selected_theme - checks the user settings and if the user selected * theme is set, returns it otherwise returns the system default. * * @return - the theme name */ function get_selected_theme() { global $config, $themes; // shortcut if theme is set in session if (isset($_SESSION['selected_theme'])) { if (file_exists($config['base_path'] . '/include/themes/' . $_SESSION['selected_theme'] . '/main.css')) { return $_SESSION['selected_theme']; } } // default to system selected theme $theme = read_config_option('selected_theme'); // check for a pre-1.x cacti being upgraded if ($theme == '' && !db_table_exists('settings_user')) { return 'modern'; } // figure out user defined theme if (isset($_SESSION['sess_user_id'])) { // fetch user defined theme $user_theme = db_fetch_cell_prepared("SELECT value FROM settings_user WHERE name='selected_theme' AND user_id = ?", array($_SESSION['sess_user_id']), '', false); // user has a theme if (! empty($user_theme)) { $theme = $user_theme;; } } if (!file_exists($config['base_path'] . '/include/themes/' . $theme . '/main.css')) { foreach($themes as $t => $name) { if (file_exists($config['base_path'] . '/include/themes/' . $t . '/main.css')) { $theme = $t; db_execute_prepared('UPDATE settings_user SET value = ? WHERE user_id = ? AND name="selected_theme"', array($theme, $_SESSION['sess_user_id'])); break; } } } // update session $_SESSION['selected_theme'] = $theme; return $theme; } /* form_input_validate - validates the value of a form field and Takes the appropriate action if the input is not valid @arg $field_value - the value of the form field @arg $field_name - the name of the $_POST field as specified in the HTML @arg $regexp_match - (optionally) enter a regular expression to match the value against @arg $allow_nulls - (bool) whether to allow an empty string as a value or not @arg $custom_message - (int) the ID of the message to raise upon an error which is defined in the $messages array in 'include/global_arrays.php' @returns - the original $field_value */ function form_input_validate($field_value, $field_name, $regexp_match, $allow_nulls, $custom_message = 3) { global $messages; /* write current values to the "field_values" array so we can retain them */ $_SESSION['sess_field_values'][$field_name] = $field_value; if (($allow_nulls == true) && ($field_value == '')) { return $field_value; } if ($allow_nulls == false && $field_value == '') { if (read_config_option('log_validation') == 'on') { cacti_log("Form Validation Failed: Variable '$field_name' does not allow nulls and variable is null", false); } raise_message($custom_message); $_SESSION['sess_error_fields'][$field_name] = $field_name; } elseif ($regexp_match != '' && !preg_match('/' . $regexp_match . '/', $field_value)) { if (read_config_option('log_validation') == 'on') { cacti_log("Form Validation Failed: Variable '$field_name' with Value '$field_value' Failed REGEX '$regexp_match'", false); } raise_message($custom_message); $_SESSION['sess_error_fields'][$field_name] = $field_name; } return $field_value; } /* check_changed - determines if a request variable has changed between page loads @returns - (bool) true if the value changed between loads */ function check_changed($request, $session) { if ((isset_request_var($request)) && (isset($_SESSION[$session]))) { if (get_nfilter_request_var($request) != $_SESSION[$session]) { return 1; } } } /* is_error_message - finds whether an error message has been raised and has not been outputted to the user @returns - (bool) whether the messages array contains an error or not */ function is_error_message() { global $config, $messages; if (isset($_SESSION['sess_error_fields']) && sizeof($_SESSION['sess_error_fields'])) { return true; } else { return false; } } function get_message_level($current_message) { $current_level = MESSAGE_LEVEL_NONE; if (isset($current_message['level'])) { $current_level = $current_message['level']; } elseif (isset($current_message['type'])) { switch ($current_message['type']) { case 'error': $current_level = MESSAGE_LEVEL_ERROR; break; case 'info': $current_level = MESSAGE_LEVEL_INFO; break; } } return $current_level; } /* get_format_message_instance - finds the level of the current message instance * @arg message array the message instance * @returns - (string) a formatted message */ function get_format_message_instance($current_message) { if (is_array($current_message)) { $fmessage = isset($current_message['message']) ? $current_message['message'] : __esc('Message Not Found.'); } else { $fmessage = $current_message; } $level = get_message_level($current_message); switch ($level) { case MESSAGE_LEVEL_NONE: $message = '<span>' . $fmessage . '</span>'; break; case MESSAGE_LEVEL_INFO: $message = '<span class="deviceUp">' . $fmessage . '</span>'; break; case MESSAGE_LEVEL_WARN: $message = '<span class="deviceWarning">' . $fmessage . '</span>'; break; case MESSAGE_LEVEL_ERROR: $message = '<span class="deviceDown">' . $fmessage . '</span>'; break; case MESSAGE_LEVEL_CSRF: $message = '<span class="deviceDown">' . $fmessage . '</span>'; break; default; $message = '<span class="deviceUnknown">' . $fmessage . '</span>'; break; } return $message; } /* get_message_max_type - finds the message and returns its type @returns - (string) the message type 'info', 'warn', 'error' or 'csrf' */ function get_message_max_type() { global $messages; $level = MESSAGE_LEVEL_NONE; if (isset($_SESSION['sess_messages'])) { if (is_array($_SESSION['sess_messages'])) { foreach ($_SESSION['sess_messages'] as $current_message_id => $current_message) { $current_level = get_message_level($current_message); if ($current_level == MESSAGE_LEVEL_NONE && isset($messages[$current_message_id])) { $current_level = get_message_level($messages[$current_message_id]); } if ($current_level != $level && $level != MESSAGE_LEVEL_NONE) { $level = MESSAGE_LEVEL_MIXED; } else { $level = $current_level; } } } } return $level; } /* raise_message - mark a message to be displayed to the user once display_output_messages() is called @arg $message_id - the ID of the message to raise as defined in $messages in 'include/global_arrays.php' */ function raise_message($message_id, $message = '', $message_level = MESSAGE_LEVEL_NONE) { global $messages, $no_http_headers; // This function should always exist, if not its an invalid install if (function_exists('session_status')) { $need_session = (session_status() == PHP_SESSION_NONE) && (!isset($no_http_headers)); } else { return false; } if (empty($message)) { if (array_key_exists($message_id, $messages)) { $predefined = $messages[$message_id]; if (isset($predefined['message'])) { $message = $predefined['message']; } else { $message = $predefined; } if ($message_level == MESSAGE_LEVEL_NONE) { $message_level = get_message_level($predefined); } } elseif (isset($_SESSION[$message_id])) { $message = $_SESSION[$message_id]; $message_level = MESSAGE_LEVEL_ERROR; } else { $message = __('Message Not Found.'); $message_level = MESSAGE_LEVEL_ERROR; } } if ($need_session) { session_start(); } if (!isset($_SESSION['sess_messages'])) { $_SESSION['sess_messages'] = array(); } $_SESSION['sess_messages'][$message_id] = array('message' => $message, 'level' => $message_level); if ($need_session) { session_write_close(); } } /* display_output_messages - displays all of the cached messages from the raise_message() function and clears the message cache */ function display_output_messages() { global $messages; $omessage = array(); $debug_message = debug_log_return('new_graphs'); if ($debug_message != '') { $omessage['level'] = MESSAGE_LEVEL_NONE; $omessage['message'] = $debug_message; debug_log_clear('new_graphs'); } elseif (isset($_SESSION['sess_messages'])) { if (!is_array($_SESSION['sess_messages'])) { $_SESSION['sess_messages'] = array('custom_error' => array('level' => 3, 'message' => $_SESSION['sess_messages'])); } $omessage['level'] = get_message_max_type(); foreach ($_SESSION['sess_messages'] as $current_message_id => $current_message) { $message = get_format_message_instance($current_message); if (!empty($message)) { $omessage['message'] = (isset($omessage['message']) && $omessage['message'] != '' ? $omessage['message'] . '<br>':'') . $message; } else { cacti_log("ERROR: Cacti Error Message Id '$current_message_id' Not Defined", false, 'WEBUI'); } } } clear_messages(); return json_encode($omessage); } function display_custom_error_message($message) { raise_message('custom_error', $message); } /* clear_messages - clears the message cache */ function clear_messages() { // This function should always exist, if not its an invalid install if (function_exists('session_status')) { $need_session = (session_status() == PHP_SESSION_NONE) && (!isset($no_http_headers)); } else { return false; } if ($need_session) { session_start(); } kill_session_var('sess_messages'); if ($need_session) { session_write_close(); } } /* kill_session_var - kills a session variable using unset() */ function kill_session_var($var_name) { /* register_global = on: reset local settings cache so the user sees the new settings */ unset($_SESSION[$var_name]); /* register_global = off: reset local settings cache so the user sees the new settings */ /* session_unregister is deprecated in PHP 5.3.0, unset is sufficient */ if (version_compare(PHP_VERSION, '5.3.0', '<')) { session_unregister($var_name); } else { unset($var_name); } } /* force_session_data - forces session data into the session if the session was closed for some reason */ function force_session_data() { // This function should always exist, if not its an invalid install if (!function_exists('session_status')) { return false; } elseif (session_status() == PHP_SESSION_NONE) { $data = $_SESSION; session_start(); $_SESSION = $data; session_write_close(); } } /* array_rekey - changes an array in the form: '$arr[0] = array('id' => 23, 'name' => 'blah')' to the form '$arr = array(23 => 'blah')' @arg $array - (array) the original array to manipulate @arg $key - the name of the key @arg $key_value - the name of the key value @returns - the modified array */ function array_rekey($array, $key, $key_value) { $ret_array = array(); if (is_array($array)) { foreach ($array as $item) { $item_key = $item[$key]; if (is_array($key_value)) { foreach ($key_value as $value) { $ret_array[$item_key][$value] = $item[$value]; } } else { $ret_array[$item_key] = $item[$key_value]; } } } return $ret_array; } /* cacti_log_file - returns the log filename */ function cacti_log_file() { global $config; $logfile = read_config_option('path_cactilog'); if ($logfile == '') { $logfile = $config['base_path'] . '/log/cacti.log'; } $config['log_path'] = $logfile; return $logfile; } /* cacti_log - logs a string to Cacti's log file or optionally to the browser @arg $string - the string to append to the log file @arg $output - (bool) whether to output the log line to the browser using print() or not @arg $environ - (string) tells from where the script was called from @arg $level - (int) only log if above the specified log level */ function cacti_log($string, $output = false, $environ = 'CMDPHP', $level = '') { global $config, $database_log; if (!isset($database_log)) { $database_log = false; } $last_log = $database_log; $database_log = false; if (isset($_SERVER['PHP_SELF'])) { $current_file = basename($_SERVER['PHP_SELF']); $dir_name = dirname($_SERVER['PHP_SELF']); } elseif (isset($_SERVER['SCRIPT_NAME'])) { $current_file = basename($_SERVER['SCRIPT_NAME']); $dir_name = dirname($_SERVER['SCRIPT_NAME']); } elseif (isset($_SERVER['SCRIPT_FILENAME'])) { $current_file = basename($_SERVER['SCRIPT_FILENAME']); $dir_name = dirname($_SERVER['SCRIPT_FILENAME']); } else { $current_file = basename(__FILE__); $dir_name = dirname(__FILE__); } $force_level = ''; $debug_files = read_config_option('selective_debug'); if ($debug_files != '') { $files = explode(',', $debug_files); if (array_search($current_file, $files) !== false) { $force_level = POLLER_VERBOSITY_DEBUG; } } if (strpos($dir_name, 'plugins') !== false) { $debug_plugins = read_config_option('selective_plugin_debug'); if ($debug_plugins != '') { $debug_plugins = explode(',', $debug_plugins); foreach($debug_plugins as $myplugin) { if (strpos($dir_name, DIRECTORY_SEPARATOR . $myplugin) !== false) { $force_level = POLLER_VERBOSITY_DEBUG; break; } } } } /* only log if the specific level is reached, developer debug is special low + specific devdbg calls */ if ($force_level == '') { if ($level != '') { $logVerbosity = read_config_option('log_verbosity'); if ($logVerbosity == POLLER_VERBOSITY_DEVDBG) { if ($level != POLLER_VERBOSITY_DEVDBG) { if ($level > POLLER_VERBOSITY_LOW) { $database_log = $last_log; return; } } } elseif ($level > $logVerbosity) { $database_log = $last_log; return; } } } /* fill in the current date for printing in the log */ if (defined('CACTI_DATE_TIME_FORMAT')) { $date = date(CACTI_DATE_TIME_FORMAT); } else { $date = date('Y-m-d H:i:s'); } /* determine how to log data */ $logdestination = read_config_option('log_destination'); $logfile = cacti_log_file(); /* format the message */ if ($environ == 'POLLER') { $prefix = "$date - " . $environ . ': Poller[' . $config['poller_id'] . '] '; } else { $prefix = "$date - " . $environ . ' '; } /* Log to Logfile */ $message = clean_up_lines($string) . PHP_EOL; if (($logdestination == 1 || $logdestination == 2) && read_config_option('log_verbosity') != POLLER_VERBOSITY_NONE) { /* echo the data to the log (append) */ $fp = @fopen($logfile, 'a'); if ($fp) { $message = $prefix . $message; @fwrite($fp, $message); fclose($fp); } } /* Log to Syslog/Eventlog */ /* Syslog is currently Unstable in Win32 */ if ($logdestination == 2 || $logdestination == 3) { $log_type = ''; if (strpos($string, 'ERROR:') !== false) { $log_type = 'err'; } elseif (strpos($string, 'WARNING:') !== false) { $log_type = 'warn'; } elseif (strpos($string, 'STATS:') !== false) { $log_type = 'stat'; } elseif (strpos($string, 'NOTICE:') !== false) { $log_type = 'note'; } if ($log_type != '') { if ($config['cacti_server_os'] == 'win32') { openlog('Cacti', LOG_NDELAY | LOG_PID, LOG_USER); } else { openlog('Cacti', LOG_NDELAY | LOG_PID, LOG_SYSLOG); } if ($log_type == 'err' && read_config_option('log_perror')) { syslog(LOG_CRIT, $environ . ': ' . $string); } elseif ($log_type == 'warn' && read_config_option('log_pwarn')) { syslog(LOG_WARNING, $environ . ': ' . $string); } elseif (($log_type == 'stat' || $log_type == 'note') && read_config_option('log_pstats')) { syslog(LOG_INFO, $environ . ': ' . $string); } closelog(); } } /* print output to standard out if required */ if ($output == true && isset($_SERVER['argv'][0])) { print $message; } $database_log = $last_log; } /* tail_file - Emulates the tail function with PHP native functions. It is used in 0.8.6 to speed the viewing of the Cacti log file, which can be problematic in the 0.8.6 branch. @arg $file_name - (char constant) the name of the file to tail $line_cnt - (int constant) the number of lines to count $message_type - (int constant) the type of message to return $filter - (char) the filtering expression to search for $page_nr - (int) the page we want to show rows for $total_rows - (int) the total number of rows in the logfile */ function tail_file($file_name, $number_of_lines, $message_type = -1, $filter = '', &$page_nr = 1, &$total_rows) { if (!file_exists($file_name)) { touch($file_name); return array(); } if (!is_readable($file_name)) { echo __('Error %s is not readable', $file_name); return array(); } $filter = strtolower($filter); $fp = fopen($file_name, 'r'); /* Count all lines in the logfile */ $total_rows = 0; while (($line = fgets($fp)) !== false) { if (determine_display_log_entry($message_type, $line, $filter)) { ++$total_rows; } } // Reset the page count to 1 if the number of lines is exceeded if (($page_nr - 1) * $number_of_lines > $total_rows) { set_request_var('page', 1); $page_nr = 1; } /* rewind file pointer, to start all over */ rewind($fp); $start = $total_rows - ($page_nr * $number_of_lines); $end = $start + $number_of_lines; if ($start < 0) { $start = 0; } /* load up the lines into an array */ $file_array = array(); $i = 0; while (($line = fgets($fp)) !== false) { $display = determine_display_log_entry($message_type, $line, $filter); if ($display === false) { continue; } if ($i < $start) { ++$i; continue; } if ($i >= $end) { break; } ++$i; $file_array[$i] = $line; } fclose($fp); return $file_array; } /** * Function to determine if we display the line * * @param int $message_type * @param string $line * @param string $filter * @return bool */ function determine_display_log_entry($message_type, $line, $filter) { /* determine if we are to display the line */ switch ($message_type) { case 1: /* stats */ $display = (strpos($line, 'STATS') !== false); break; case 2: /* warnings */ $display = (strpos($line, 'WARN') !== false); break; case 3: /* errors */ $display = (strpos($line, 'ERROR') !== false); break; case 4: /* debug */ $display = (strpos($line, 'DEBUG') !== false && strpos($line, ' SQL ') === false); break; case 5: /* sql calls */ $display = (strpos($line, ' SQL ') !== false); break; default: /* all other lines */ case -1: /* all */ $display = true; break; } /* match any lines that match the search string */ if ($display === true && $filter != '') { if (stripos($line, $filter) !== false) { return $line; } elseif (validate_is_regex($filter) && preg_match('/' . $filter . '/i', $line)) { return $line; } return false; } return $display; } /* update_host_status - updates the host table with information about its status. It will also output to the appropriate log file when an event occurs. @arg $status - (int constant) the status of the host (Up/Down) $host_id - (int) the host ID for the results $hosts - (array) a memory resident host table for speed $ping - (class array) results of the ping command */ function update_host_status($status, $host_id, &$hosts, &$ping, $ping_availability, $print_data_to_stdout) { $issue_log_message = false; $ping_failure_count = read_config_option('ping_failure_count'); $ping_recovery_count = read_config_option('ping_recovery_count'); /* initialize fail and recovery dates correctly */ if ($hosts[$host_id]['status_fail_date'] == ''){ $hosts[$host_id]['status_fail_date'] = '0000-00-00 00:00:00'; } if ($hosts[$host_id]['status_rec_date'] == ''){ $hosts[$host_id]['status_rec_date'] = '0000-00-00 00:00:00'; } if ($status == HOST_DOWN) { /* Set initial date down. BUGFIX */ if (empty($hosts[$host_id]['status_fail_date'])) { $hosts[$host_id]['status_fail_date'] = date('Y-m-d H:i:s'); } /* update total polls, failed polls and availability */ $hosts[$host_id]['failed_polls']++; $hosts[$host_id]['total_polls']++; $hosts[$host_id]['availability'] = 100 * ($hosts[$host_id]['total_polls'] - $hosts[$host_id]['failed_polls']) / $hosts[$host_id]['total_polls']; /* determine the error message to display */ if (($ping_availability == AVAIL_SNMP_AND_PING) || ($ping_availability == AVAIL_SNMP_OR_PING)) { if (($hosts[$host_id]['snmp_community'] == '') && ($hosts[$host_id]['snmp_version'] != 3)) { /* snmp version 1/2 without community string assume SNMP test to be successful due to backward compatibility issues */ $hosts[$host_id]['status_last_error'] = $ping->ping_response; }else { $hosts[$host_id]['status_last_error'] = $ping->snmp_response . ', ' . $ping->ping_response; } } elseif ($ping_availability == AVAIL_SNMP) { if (($hosts[$host_id]['snmp_community'] == '') && ($hosts[$host_id]['snmp_version'] != 3)) { $hosts[$host_id]['status_last_error'] = 'Device does not require SNMP'; }else { $hosts[$host_id]['status_last_error'] = $ping->snmp_response; } }else { $hosts[$host_id]['status_last_error'] = $ping->ping_response; } /* determine if to send an alert and update remainder of statistics */ if ($hosts[$host_id]['status'] == HOST_UP) { /* increment the event failure count */ $hosts[$host_id]['status_event_count']++; /* if it's time to issue an error message, indicate so */ if ($hosts[$host_id]['status_event_count'] >= $ping_failure_count) { /* host is now down, flag it that way */ $hosts[$host_id]['status'] = HOST_DOWN; $issue_log_message = true; /* update the failure date only if the failure count is 1 */ if ($hosts[$host_id]['status_event_count'] == $ping_failure_count) { $hosts[$host_id]['status_fail_date'] = date('Y-m-d H:i:s'); } /* host is down, but not ready to issue log message */ } else { /* host down for the first time, set event date */ if ($hosts[$host_id]['status_event_count'] == $ping_failure_count) { $hosts[$host_id]['status_fail_date'] = date('Y-m-d H:i:s'); } } /* host is recovering, put back in failed state */ } elseif ($hosts[$host_id]['status'] == HOST_RECOVERING) { $hosts[$host_id]['status_event_count'] = 1; $hosts[$host_id]['status'] = HOST_DOWN; /* host was unknown and now is down */ } elseif ($hosts[$host_id]['status'] == HOST_UNKNOWN) { $hosts[$host_id]['status'] = HOST_DOWN; $hosts[$host_id]['status_event_count'] = 0; } else { $hosts[$host_id]['status_event_count']++; } /* host is up!! */ } else { /* update total polls and availability */ $hosts[$host_id]['total_polls']++; $hosts[$host_id]['availability'] = 100 * ($hosts[$host_id]['total_polls'] - $hosts[$host_id]['failed_polls']) / $hosts[$host_id]['total_polls']; if ((($ping_availability == AVAIL_SNMP_AND_PING) || ($ping_availability == AVAIL_SNMP_OR_PING) || ($ping_availability == AVAIL_SNMP)) && (!is_numeric($ping->snmp_status))) { $ping->snmp_status = 0.000; } if ((($ping_availability == AVAIL_SNMP_AND_PING) || ($ping_availability == AVAIL_SNMP_OR_PING) || ($ping_availability == AVAIL_PING)) && (!is_numeric($ping->ping_status))) { $ping->ping_status = 0.000; } /* determine the ping statistic to set and do so */ if (($ping_availability == AVAIL_SNMP_AND_PING) || ($ping_availability == AVAIL_SNMP_OR_PING)) { if (($hosts[$host_id]['snmp_community'] == '') && ($hosts[$host_id]['snmp_version'] != 3)) { $ping_time = 0.000; }else { /* calculate the average of the two times */ $ping_time = ($ping->snmp_status + $ping->ping_status) / 2; } } elseif ($ping_availability == AVAIL_SNMP) { if (($hosts[$host_id]['snmp_community'] == '') && ($hosts[$host_id]['snmp_version'] != 3)) { $ping_time = 0.000; }else { $ping_time = $ping->snmp_status; } } elseif ($ping_availability == AVAIL_NONE) { $ping_time = 0.000; } else { $ping_time = $ping->ping_status; } /* update times as required */ if (is_numeric($ping_time)) { $hosts[$host_id]['cur_time'] = $ping_time; /* maximum time */ if ($ping_time > $hosts[$host_id]['max_time']) { $hosts[$host_id]['max_time'] = $ping_time; } /* minimum time */ if ($ping_time < $hosts[$host_id]['min_time']) { $hosts[$host_id]['min_time'] = $ping_time; } /* average time */ $hosts[$host_id]['avg_time'] = (($hosts[$host_id]['total_polls']-1-$hosts[$host_id]['failed_polls']) * $hosts[$host_id]['avg_time'] + $ping_time) / ($hosts[$host_id]['total_polls']-$hosts[$host_id]['failed_polls']); } /* the host was down, now it's recovering */ if (($hosts[$host_id]['status'] == HOST_DOWN) || ($hosts[$host_id]['status'] == HOST_RECOVERING )) { /* just up, change to recovering */ if ($hosts[$host_id]['status'] == HOST_DOWN) { $hosts[$host_id]['status'] = HOST_RECOVERING; $hosts[$host_id]['status_event_count'] = 1; } else { $hosts[$host_id]['status_event_count']++; } /* if it's time to issue a recovery message, indicate so */ if ($hosts[$host_id]['status_event_count'] >= $ping_recovery_count) { /* host is up, flag it that way */ $hosts[$host_id]['status'] = HOST_UP; $issue_log_message = true; /* update the recovery date only if the recovery count is 1 */ if ($hosts[$host_id]['status_event_count'] == $ping_recovery_count) { $hosts[$host_id]['status_rec_date'] = date('Y-m-d H:i:s'); } /* reset the event counter */ $hosts[$host_id]['status_event_count'] = 0; /* host is recovering, but not ready to issue log message */ } else { /* host recovering for the first time, set event date */ if ($hosts[$host_id]['status_event_count'] == $ping_recovery_count) { $hosts[$host_id]['status_rec_date'] = date('Y-m-d H:i:s'); } } } else { /* host was unknown and now is up */ $hosts[$host_id]['status'] = HOST_UP; $hosts[$host_id]['status_event_count'] = 0; } } /* if the user wants a flood of information then flood them */ if (($hosts[$host_id]['status'] == HOST_UP) || ($hosts[$host_id]['status'] == HOST_RECOVERING)) { /* log ping result if we are to use a ping for reachability testing */ if ($ping_availability == AVAIL_SNMP_AND_PING) { cacti_log("Device[$host_id] PING: " . $ping->ping_response, $print_data_to_stdout, 'PING', POLLER_VERBOSITY_HIGH); cacti_log("Device[$host_id] SNMP: " . $ping->snmp_response, $print_data_to_stdout, 'PING', POLLER_VERBOSITY_HIGH); } elseif ($ping_availability == AVAIL_SNMP) { if (($hosts[$host_id]['snmp_community'] == '') && ($hosts[$host_id]['snmp_version'] != 3)) { cacti_log("Device[$host_id] SNMP: Device does not require SNMP", $print_data_to_stdout, 'PING', POLLER_VERBOSITY_HIGH); } else { cacti_log("Device[$host_id] SNMP: " . $ping->snmp_response, $print_data_to_stdout, 'PING', POLLER_VERBOSITY_HIGH); } } else { cacti_log("Device[$host_id] PING: " . $ping->ping_response, $print_data_to_stdout, 'PING', POLLER_VERBOSITY_HIGH); } } else { if ($ping_availability == AVAIL_SNMP_AND_PING) { cacti_log("Device[$host_id] PING: " . $ping->ping_response, $print_data_to_stdout, 'PING', POLLER_VERBOSITY_HIGH); cacti_log("Device[$host_id] SNMP: " . $ping->snmp_response, $print_data_to_stdout, 'PING', POLLER_VERBOSITY_HIGH); } elseif ($ping_availability == AVAIL_SNMP) { cacti_log("Device[$host_id] SNMP: " . $ping->snmp_response, $print_data_to_stdout, 'PING', POLLER_VERBOSITY_HIGH); } else { cacti_log("Device[$host_id] PING: " . $ping->ping_response, $print_data_to_stdout, 'PING', POLLER_VERBOSITY_HIGH); } } /* if there is supposed to be an event generated, do it */ if ($issue_log_message) { if ($hosts[$host_id]['status'] == HOST_DOWN) { cacti_log("Device[$host_id] ERROR: HOST EVENT: Device is DOWN Message: " . $hosts[$host_id]['status_last_error'], $print_data_to_stdout); } else { cacti_log("Device[$host_id] NOTICE: HOST EVENT: Device Returned FROM DOWN State: ", $print_data_to_stdout); } } db_execute_prepared('UPDATE host SET status = ?, status_event_count = ?, status_fail_date = ?, status_rec_date = ?, status_last_error = ?, min_time = ?, max_time = ?, cur_time = ?, avg_time = ?, total_polls = ?, failed_polls = ?, availability = ? WHERE hostname = ?', array( $hosts[$host_id]['status'], $hosts[$host_id]['status_event_count'], $hosts[$host_id]['status_fail_date'], $hosts[$host_id]['status_rec_date'], $hosts[$host_id]['status_last_error'], $hosts[$host_id]['min_time'], $hosts[$host_id]['max_time'], $hosts[$host_id]['cur_time'], $hosts[$host_id]['avg_time'], $hosts[$host_id]['total_polls'], $hosts[$host_id]['failed_polls'], $hosts[$host_id]['availability'], $hosts[$host_id]['hostname'] ) ); } /* is_hexadecimal - test whether a string represents a hexadecimal number, ignoring space and tab, and case insensitive. @arg $result - the string to test @arg 1 if the argument is hex, 0 otherwise, and false on error */ function is_hexadecimal($result) { $hexstr = str_replace(array(' ', '-'), ':', trim($result)); $parts = explode(':', $hexstr); foreach($parts as $part) { if (strlen($part) != 2) { return false; } if (ctype_xdigit($part) == false) { return false; } } return true; } /* is_mac_address - determines if the result value is a mac address @arg $result - (string) some string to be evaluated @returns - (bool) either to result is a mac address of not */ function is_mac_address($result) { if (!defined('FILTER_VALIDATE_MAC')) { if (preg_match('/^([0-9a-f]{1,2}[\.:-]){5}([0-9a-f]{1,2})$/i', $result)) { return true; } else { return false; } } else { return filter_var($result, FILTER_VALIDATE_MAC); } } function is_hex_string(&$result) { if ($result == '') { return false; } $compare = strtolower($result); /* strip off the 'Hex:, Hex-, and Hex-STRING:' * Hex- is considered due to the stripping of 'String:' in * lib/snmp.php */ if (substr($compare, 0, 4) == 'hex-') { $check = trim(str_ireplace('hex-', '', $result)); } elseif (substr($compare, 0, 11) == 'hex-string:') { $check = trim(str_ireplace('hex-string:', '', $result)); } else { return false; } $parts = explode(' ', $check); /* assume if something is a hex string it will have a length > 1 */ if (cacti_sizeof($parts) == 1) { return false; } foreach($parts as $part) { if (strlen($part) != 2) { return false; } if (ctype_xdigit($part) == false) { return false; } } $result = $check; return true; } /* prepare_validate_result - determines if the result value is valid or not. If not valid returns a "U" @arg $result - (string) the result from the poll, the result can be modified in the call @returns - (bool) either to result is valid or not */ function prepare_validate_result(&$result) { /* first trim the string */ $result = trim($result, "'\"\n\r"); /* clean off ugly non-numeric data */ if (is_numeric($result)) { return true; } elseif ($result == 'U') { return true; } elseif (is_hexadecimal($result)) { return hexdec($result); } elseif (substr_count($result, ':') || substr_count($result, '!')) { /* looking for name value pairs */ if (substr_count($result, ' ') == 0) { return true; } else { $delim_cnt = 0; if (substr_count($result, ':')) { $delim_cnt = substr_count($result, ':'); } elseif (strstr($result, '!')) { $delim_cnt = substr_count($result, '!'); } $space_cnt = substr_count($result, ' '); return ($space_cnt+1 == $delim_cnt); } } else { $result = strip_alpha($result); if ($result === false) { $result = 'U'; return false; } else { return true; } } } /** strip_alpha - remove non-numeric data from a string and return the numeric part * @arg $string - (char) the string to be evaluated * @returns - either the numeric value or false if not numeric */ function strip_alpha($string) { /* strip all non numeric data */ $string = trim(preg_replace('/[^0-9,.+-]/', '', $string)); /* check the easy cases first */ /* it has no delimiters, and no space, therefore, must be numeric */ if (is_numeric($string) || is_float($string)) { return $string; } else { return false; } } /** get_full_script_path - gets the full path to the script to execute to obtain data for a * given data source. this function does not work on SNMP actions, only script-based actions * @arg $local_data_id - (int) the ID of the data source * @returns - the full script path or (bool) false for an error */ function get_full_script_path($local_data_id) { global $config; $data_source = db_fetch_row_prepared('SELECT ' . SQL_NO_CACHE . ' data_template_data.id, data_template_data.data_input_id, data_input.type_id, data_input.input_string FROM (data_template_data, data_input) WHERE data_template_data.data_input_id = data_input.id AND data_template_data.local_data_id = ?', array($local_data_id)); /* snmp-actions don't have paths */ if (($data_source['type_id'] == DATA_INPUT_TYPE_SNMP) || ($data_source['type_id'] == DATA_INPUT_TYPE_SNMP_QUERY)) { return false; } $data = db_fetch_assoc_prepared("SELECT " . SQL_NO_CACHE . " data_input_fields.data_name, data_input_data.value FROM data_input_fields LEFT JOIN data_input_data ON (data_input_fields.id = data_input_data.data_input_field_id) WHERE data_input_fields.data_input_id = ? AND data_input_data.data_template_data_id = ? AND data_input_fields.input_output = 'in'", array($data_source['data_input_id'], $data_source['id'])); $full_path = $data_source['input_string']; if (cacti_sizeof($data)) { foreach ($data as $item) { $full_path = str_replace('<' . $item['data_name'] . '>', cacti_escapeshellarg($item['value']), $full_path); } } $search = array('<path_cacti>', '<path_snmpget>', '<path_php_binary>'); $replace = array($config['base_path'], read_config_option('path_snmpget'), read_config_option('path_php_binary')); $full_path = str_replace($search, $replace, $full_path); /* sometimes a certain input value will not have anything entered... null out these fields in the input string so we don't mess up the script */ return preg_replace('/(<[A-Za-z0-9_]+>)+/', '', $full_path); } /* get_data_source_item_name - gets the name of a data source item or generates a new one if one does not already exist @arg $data_template_rrd_id - (int) the ID of the data source item @returns - the name of the data source item or an empty string for an error */ function get_data_source_item_name($data_template_rrd_id) { if (empty($data_template_rrd_id)) { return ''; } $data_source = db_fetch_row_prepared('SELECT ' . SQL_NO_CACHE . ' dtr.data_source_name, dtd.name FROM data_template_rrd AS dtr INNER JOIN data_template_data AS dtd ON dtr.local_data_id = dtd.local_data_id WHERE dtr.id = ?', array($data_template_rrd_id) ); /* use the cacti ds name by default or the user defined one, if entered */ if (empty($data_source['data_source_name'])) { /* limit input to 19 characters */ $data_source_name = clean_up_name($data_source['name']); $data_source_name = substr(strtolower($data_source_name), 0, (19-strlen($data_template_rrd_id))) . $data_template_rrd_id; return $data_source_name; } else { return $data_source['data_source_name']; } } /* get_data_source_path - gets the full path to the .rrd file associated with a given data source @arg $local_data_id - (int) the ID of the data source @arg $expand_paths - (bool) whether to expand the <path_rra> variable into its full path or not @returns - the full path to the data source or an empty string for an error */ function get_data_source_path($local_data_id, $expand_paths) { global $config; static $data_source_path_cache = array(); if (empty($local_data_id)) { return ''; } if (isset($data_source_path_cache[$local_data_id])) { return $data_source_path_cache[$local_data_id]; } $data_source = db_fetch_row_prepared('SELECT ' . SQL_NO_CACHE . ' name, data_source_path FROM data_template_data WHERE local_data_id = ?', array($local_data_id)); if (cacti_sizeof($data_source) > 0) { if (empty($data_source['data_source_path'])) { /* no custom path was specified */ $data_source_path = generate_data_source_path($local_data_id); } elseif (!strstr($data_source['data_source_path'], '/')) { $data_source_path = '<path_rra>/' . $data_source['data_source_path']; } else { $data_source_path = $data_source['data_source_path']; } /* whether to show the "actual" path or the <path_rra> variable name (for edit boxes) */ if ($expand_paths == true) { $data_source_path = str_replace('<path_rra>/', $config['rra_path'] . '/', $data_source_path); } $data_source_path_cache[$local_data_id] = $data_source_path; return $data_source_path; } } /* stri_replace - a case insensitive string replace @arg $find - needle @arg $replace - replace needle with this @arg $string - haystack @returns - the original string with '$find' replaced by '$replace' */ function stri_replace($find, $replace, $string) { $parts = explode(strtolower($find), strtolower($string)); $pos = 0; $findLength = strlen($find); foreach ($parts as $key => $part) { $partLength = strlen($part); $parts[$key] = substr($string, $pos, $partLength); $pos += $partLength + $findLength; } return (join($replace, $parts)); } /* clean_up_lines - runs a string through a regular expression designed to remove new lines and the spaces around them @arg $string - the string to modify/clean @returns - the modified string */ function clean_up_lines($string) { return preg_replace('/\s*[\r\n]+\s*/',' ', $string); } /* clean_up_name - runs a string through a series of regular expressions designed to eliminate "bad" characters @arg $string - the string to modify/clean @returns - the modified string */ function clean_up_name($string) { $string = preg_replace('/[\s\.]+/', '_', $string); $string = preg_replace('/[^a-zA-Z0-9_]+/', '', $string); $string = preg_replace('/_{2,}/', '_', $string); return $string; } /* clean_up_file name - runs a string through a series of regular expressions designed to eliminate "bad" characters @arg $string - the string to modify/clean @returns - the modified string */ function clean_up_file_name($string) { $string = preg_replace('/[\s\.]+/', '_', $string); $string = preg_replace('/[^a-zA-Z0-9_-]+/', '', $string); $string = preg_replace('/_{2,}/', '_', $string); return $string; } /* clean_up_path - takes any path and makes sure it contains the correct directory separators based on the current operating system @arg $path - the path to modify @returns - the modified path */ function clean_up_path($path) { global $config; if ($config['cacti_server_os'] == 'win32') { return str_replace('/', "\\", $path); } elseif ($config['cacti_server_os'] == 'unix' || read_config_option('using_cygwin') == 'on' || read_config_option('storage_location')) { return str_replace("\\", '/', $path); } else { return $path; } } /* get_data_source_title - returns the title of a data source without using the title cache @arg $local_data_id - (int) the ID of the data source to get a title for @returns - the data source title */ function get_data_source_title($local_data_id) { $data = db_fetch_row_prepared('SELECT dl.host_id, dl.snmp_query_id, dl.snmp_index, dtd.name FROM data_local AS dl INNER JOIN data_template_data AS dtd ON dtd.local_data_id = dl.id WHERE dl.id = ?', array($local_data_id)); if (cacti_sizeof($data)) { if (strstr($data['name'], '|') !== false && $data['host_id'] > 0) { $data['name'] = substitute_data_input_data($data['name'], '', $local_data_id); return expand_title($data['host_id'], $data['snmp_query_id'], $data['snmp_index'], $data['name']); } else { return $data['name']; } } else { return 'Missing Datasource ' . $local_data_id; } } /* get_device_name - returns the description of the device in cacti host table @arg $host_id - (int) the ID of the device to get a description for @returns - the device name */ function get_device_name($host_id) { return db_fetch_cell_prepared('SELECT description FROM host WHERE id = ?', array($host_id)); } /* get_color - returns the hex color value from the cacti colors table @arg $color_id - (int) the ID of the cacti color @returns - the hex color value */ function get_color($color_id) { return db_fetch_cell_prepared('SELECT hex FROM colors WHERE id = ?', array($color_id)); } /* get_graph_title - returns the title of a graph without using the title cache @arg $local_graph_id - (int) the ID of the graph to get a title for @returns - the graph title */ function get_graph_title($local_graph_id) { $graph = db_fetch_row_prepared('SELECT gl.host_id, gl.snmp_query_id, gl.snmp_index, gtg.local_graph_id, gtg.t_title, gtg.title FROM graph_templates_graph AS gtg INNER JOIN graph_local AS gl ON gtg.local_graph_id = gl.id WHERE gl.id = ?', array($local_graph_id)); if (cacti_sizeof($graph)) { if (strstr($graph['title'], '|') !== false && $graph['host_id'] > 0 && empty($graph['t_title'])) { $graph['title'] = substitute_data_input_data($graph['title'], $graph, 0); return expand_title($graph['host_id'], $graph['snmp_query_id'], $graph['snmp_index'], $graph['title']); } else { return $graph['title']; } } else { return ''; } } /* get_username - returns the username for the selected user @arg $user_id - (int) the ID of the user @returns - the username */ function get_username($user_id) { return db_fetch_cell_prepared('SELECT username FROM user_auth WHERE id = ?', array($user_id)); } /* get_execution_user - returns the username of the running process @returns - the username */ function get_execution_user() { if (function_exists('posix_getpwuid')) { $user_info = posix_getpwuid(posix_geteuid()); return $user_info['name']; } else { return exec('whoami'); } } /* generate_data_source_path - creates a new data source path from scratch using the first data source item name and updates the database with the new value @arg $local_data_id - (int) the ID of the data source to generate a new path for @returns - the new generated path */ function generate_data_source_path($local_data_id) { global $config; /* try any prepend the name with the host description */ $host = db_fetch_row_prepared('SELECT host.id, host.description FROM (host, data_local) WHERE data_local.host_id = host.id AND data_local.id = ? LIMIT 1', array($local_data_id)); $host_name = $host['description']; $host_id = $host['id']; /* put it all together using the local_data_id at the end */ if (read_config_option('extended_paths') == 'on') { $new_path = "<path_rra>/$host_id/$local_data_id.rrd"; } else { if (!empty($host_name)) { $host_part = strtolower(clean_up_file_name($host_name)) . '_'; } /* then try and use the internal DS name to identify it */ $data_source_rrd_name = db_fetch_cell_prepared('SELECT data_source_name FROM data_template_rrd WHERE local_data_id = ? ORDER BY id LIMIT 1', array($local_data_id) ); if (!empty($data_source_rrd_name)) { $ds_part = strtolower(clean_up_file_name($data_source_rrd_name)); } else { $ds_part = 'ds'; } $new_path = "<path_rra>/$host_part$ds_part" . '_' . "$local_data_id.rrd"; } /* update our changes to the db */ db_execute_prepared('UPDATE data_template_data SET data_source_path = ? WHERE local_data_id = ?', array($new_path, $local_data_id)); return $new_path; } /* generate graph_best_cf - takes the requested consolidation function and maps against the list of available consolidation functions for the consolidation functions and returns the most appropriate. Typically, this will be the requested value @arg $data_template_id @arg $requested_cf @arg $ds_step @returns - the best cf to use */ function generate_graph_best_cf($local_data_id, $requested_cf, $ds_step = 60) { static $best_cf; if ($local_data_id > 0) { $first_step = db_fetch_cell_prepared('SELECT rrd_step FROM data_template_data WHERE local_data_id = ?', array($local_data_id)); $avail_cf_functions = get_rrd_cfs($local_data_id); /* hack for odd RRDtool behavior in first RRA */ if ($ds_step == $first_step && isset($avail_cf_functions[1])) { $best_cf = '3'; } elseif (cacti_sizeof($avail_cf_functions)) { /* workaround until we have RRA presets in 0.8.8 */ /* check through the cf's and get the best */ /* if none was found, take the first */ $best_cf = $avail_cf_functions[1]; foreach($avail_cf_functions as $cf) { if ($cf == $requested_cf) { $best_cf = $requested_cf; } } } else { $best_cf = '1'; } } /* if you can not figure it out return average */ return $best_cf; } /* get_rrd_cfs - reads the RRDfile and gets the RRAs stored in it. @arg $local_data_id @returns - array of the CF functions */ function get_rrd_cfs($local_data_id) { global $consolidation_functions; static $rrd_cfs = array(); if (array_key_exists($local_data_id, $rrd_cfs)) { return $rrd_cfs[$local_data_id]; } $cfs = array(); $rrdfile = get_data_source_path($local_data_id, true); $output = @rrdtool_execute("info $rrdfile", false, RRDTOOL_OUTPUT_STDOUT); /* search for * rra[0].cf = 'LAST' * or similar */ if ($output != '') { $output = explode("\n", $output); if (cacti_sizeof($output)) { foreach($output as $line) { if (substr_count($line, '.cf')) { $values = explode('=',$line); if (!in_array(trim($values[1], '" '), $cfs)) { $cfs[] = trim($values[1], '" '); } } } } } $new_cfs = array(); if (cacti_sizeof($cfs)) { foreach($cfs as $cf) { switch($cf) { case 'AVG': case 'AVERAGE': $new_cfs[1] = array_search('AVERAGE', $consolidation_functions); break; case 'MIN': $new_cfs[2] = array_search('MIN', $consolidation_functions); break; case 'MAX': $new_cfs[3] = array_search('MAX', $consolidation_functions); break; case 'LAST': $new_cfs[4] = array_search('LAST', $consolidation_functions); break; } } } $rrd_cfs[$local_data_id] = $new_cfs; return $new_cfs; } /* generate_graph_def_name - takes a number and turns each digit into its letter-based counterpart for RRDtool DEF names (ex 1 -> a, 2 -> b, etc) @arg $graph_item_id - (int) the ID to generate a letter-based representation of @returns - a letter-based representation of the input argument */ function generate_graph_def_name($graph_item_id) { $lookup_table = array('a','b','c','d','e','f','g','h','i','j'); $result = ''; $strValGII = strval($graph_item_id); for ($i=0; $i<strlen($strValGII); $i++) { $result .= $lookup_table{substr($strValGII, $i, 1)}; } if (preg_match('/^(cf|cdef|def)$/', $result)) { return 'zz' . $result; } else { return $result; } } /* generate_data_input_field_sequences - re-numbers the sequences of each field associated with a particular data input method based on its position within the input string @arg $string - the input string that contains the field variables in a certain order @arg $data_input_id - (int) the ID of the data input method */ function generate_data_input_field_sequences($string, $data_input_id) { global $config, $registered_cacti_names; if (preg_match_all('/<([_a-zA-Z0-9]+)>/', $string, $matches)) { $j = 0; for ($i=0; ($i < cacti_count($matches[1])); $i++) { if (in_array($matches[1][$i], $registered_cacti_names) == false) { $j++; db_execute_prepared("UPDATE data_input_fields SET sequence = ? WHERE data_input_id = ? AND input_output IN ('in') AND data_name = ?", array($j, $data_input_id, $matches[1][$i])); } } update_replication_crc(0, 'poller_replicate_data_input_fields_crc'); } } /* move_graph_group - takes a graph group (parent+children) and swaps it with another graph group @arg $graph_template_item_id - (int) the ID of the (parent) graph item that was clicked @arg $graph_group_array - (array) an array containing the graph group to be moved @arg $target_id - (int) the ID of the (parent) graph item of the target group @arg $direction - ('next' or 'previous') whether the graph group is to be swapped with group above or below the current group */ function move_graph_group($graph_template_item_id, $graph_group_array, $target_id, $direction) { $graph_item = db_fetch_row_prepared('SELECT local_graph_id, graph_template_id FROM graph_templates_item WHERE id = ?', array($graph_template_item_id)); if (empty($graph_item['local_graph_id'])) { $sql_where = 'graph_template_id = ' . $graph_item['graph_template_id'] . ' AND local_graph_id = 0'; } else { $sql_where = 'local_graph_id = ' . $graph_item['local_graph_id']; } /* get a list of parent+children of our target group */ $target_graph_group_array = get_graph_group($target_id); /* if this "parent" item has no children, then treat it like a regular gprint */ if (cacti_sizeof($target_graph_group_array) == 0) { if ($direction == 'next') { move_item_down('graph_templates_item', $graph_template_item_id, $sql_where); } elseif ($direction == 'previous') { move_item_up('graph_templates_item', $graph_template_item_id, $sql_where); } return; } /* start the sequence at '1' */ $sequence_counter = 1; $graph_items = db_fetch_assoc_prepared("SELECT id, sequence FROM graph_templates_item WHERE $sql_where ORDER BY sequence"); if (cacti_sizeof($graph_items)) { foreach ($graph_items as $item) { /* check to see if we are at the "target" spot in the loop; if we are, update the sequences and move on */ if ($target_id == $item['id']) { if ($direction == 'next') { $group_array1 = $target_graph_group_array; $group_array2 = $graph_group_array; } elseif ($direction == 'previous') { $group_array1 = $graph_group_array; $group_array2 = $target_graph_group_array; } foreach ($group_array1 as $graph_template_item_id) { db_execute_prepared('UPDATE graph_templates_item SET sequence = ? WHERE id = ?', array($sequence_counter, $graph_template_item_id)); /* propagate to ALL graphs using this template */ if (empty($graph_item['local_graph_id'])) { db_execute_prepared('UPDATE graph_templates_item SET sequence = ? WHERE local_graph_template_item_id = ?', array($sequence_counter, $graph_template_item_id)); } $sequence_counter++; } foreach ($group_array2 as $graph_template_item_id) { db_execute_prepared('UPDATE graph_templates_item SET sequence = ? WHERE id = ?', array($sequence_counter, $graph_template_item_id)); /* propagate to ALL graphs using this template */ if (empty($graph_item['local_graph_id'])) { db_execute_prepared('UPDATE graph_templates_item SET sequence = ? WHERE local_graph_template_item_id = ?', array($sequence_counter, $graph_template_item_id)); } $sequence_counter++; } } /* make sure to "ignore" the items that we handled above */ if ((!isset($graph_group_array[$item['id']])) && (!isset($target_graph_group_array[$item['id']]))) { db_execute_prepared('UPDATE graph_templates_item SET sequence = ? WHERE id = ?', array($sequence_counter, $item['id'])); $sequence_counter++; } } } } /* get_graph_group - returns an array containing each item in the graph group given a single graph item in that group @arg $graph_template_item_id - (int) the ID of the graph item to return the group of @returns - (array) an array containing each item in the graph group */ function get_graph_group($graph_template_item_id) { global $graph_item_types; $graph_item = db_fetch_row_prepared('SELECT graph_type_id, sequence, local_graph_id, graph_template_id FROM graph_templates_item WHERE id = ?', array($graph_template_item_id)); if (empty($graph_item['local_graph_id'])) { $sql_where = 'graph_template_id = ' . $graph_item['graph_template_id'] . ' AND local_graph_id = 0'; } else { $sql_where = 'local_graph_id = ' . $graph_item['local_graph_id']; } /* parents are LINE%, AREA%, and STACK%. If not return */ if (!preg_match('/(LINE|AREA|STACK)/', $graph_item_types[$graph_item['graph_type_id']])) { return array(); } $graph_item_children_array = array(); /* put the parent item in the array as well */ $graph_item_children_array[$graph_template_item_id] = $graph_template_item_id; $graph_items = db_fetch_assoc("SELECT id, graph_type_id, text_format, hard_return FROM graph_templates_item WHERE sequence > " . $graph_item['sequence'] . " AND $sql_where ORDER BY sequence"); $is_hard = false; if (cacti_sizeof($graph_items)) { foreach ($graph_items as $item) { if ($is_hard) { return $graph_item_children_array; } elseif (strstr($graph_item_types[$item['graph_type_id']], 'GPRINT') !== false) { /* a child must be a GPRINT */ $graph_item_children_array[$item['id']] = $item['id']; if ($item['hard_return'] == 'on') { $is_hard = true; } } elseif (strstr($graph_item_types[$item['graph_type_id']], 'COMMENT') !== false) { if (preg_match_all('/\|([0-9]{1,2}):(bits|bytes):(\d):(current|total|max|total_peak|all_max_current|all_max_peak|aggregate_max|aggregate_sum|aggregate_current|aggregate):(\d)?\|/', $item['text_format'], $matches, PREG_SET_ORDER)) { $graph_item_children_array[$item['id']] = $item['id']; } elseif (preg_match_all('/\|sum:(\d|auto):(current|total|atomic):(\d):(\d+|auto)\|/', $item['text_format'], $matches, PREG_SET_ORDER)) { $graph_item_children_array[$item['id']] = $item['id']; } else { /* if not a GPRINT or special COMMENT then get out */ return $graph_item_children_array; } } else { /* if not a GPRINT or special COMMENT then get out */ return $graph_item_children_array; } } } return $graph_item_children_array; } /* get_graph_parent - returns the ID of the next or previous parent graph item id @arg $graph_template_item_id - (int) the ID of the current graph item @arg $direction - ('next' or 'previous') whether to find the next or previous parent @returns - (int) the ID of the next or previous parent graph item id */ function get_graph_parent($graph_template_item_id, $direction) { $graph_item = db_fetch_row_prepared('SELECT sequence, local_graph_id, graph_template_id FROM graph_templates_item WHERE id = ?', array($graph_template_item_id)); if (empty($graph_item['local_graph_id'])) { $sql_where = 'graph_template_id = ' . $graph_item['graph_template_id'] . ' AND local_graph_id = 0'; } else { $sql_where = 'local_graph_id = ' . $graph_item['local_graph_id']; } if ($direction == 'next') { $sql_operator = '>'; $sql_order = 'ASC'; } elseif ($direction == 'previous') { $sql_operator = '<'; $sql_order = 'DESC'; } $next_parent_id = db_fetch_cell("SELECT id FROM graph_templates_item WHERE sequence $sql_operator " . $graph_item['sequence'] . " AND graph_type_id IN (4, 5, 6, 7, 8, 20) AND $sql_where ORDER BY sequence $sql_order LIMIT 1"); if (empty($next_parent_id)) { return 0; } else { return $next_parent_id; } } /* get_item - returns the ID of the next or previous item id @arg $tblname - the table name that contains the target id @arg $field - the field name that contains the target id @arg $startid - (int) the current id @arg $lmt_query - an SQL "where" clause to limit the query @arg $direction - ('next' or 'previous') whether to find the next or previous item id @returns - (int) the ID of the next or previous item id */ function get_item($tblname, $field, $startid, $lmt_query, $direction) { if ($direction == 'next') { $sql_operator = '>'; $sql_order = 'ASC'; } elseif ($direction == 'previous') { $sql_operator = '<'; $sql_order = 'DESC'; } $current_sequence = db_fetch_cell_prepared("SELECT $field FROM $tblname WHERE id = ?", array($startid)); $new_item_id = db_fetch_cell("SELECT id FROM $tblname WHERE $field $sql_operator $current_sequence " . ($lmt_query != '' ? " AND $lmt_query":"") . " ORDER BY $field $sql_order LIMIT 1"); if (empty($new_item_id)) { return $startid; } else { return $new_item_id; } } /* get_sequence - returns the next available sequence id @arg $id - (int) the current id @arg $field - the field name that contains the target id @arg $table_name - the table name that contains the target id @arg $group_query - an SQL "where" clause to limit the query @returns - (int) the next available sequence id */ function get_sequence($id, $field, $table_name, $group_query) { if (empty($id)) { $data = db_fetch_row("SELECT max($field)+1 AS seq FROM $table_name WHERE $group_query"); if ($data['seq'] == '') { return 1; } else { return $data['seq']; } } else { $data = db_fetch_row_prepared("SELECT $field FROM $table_name WHERE id = ?", array($id)); return $data[$field]; } } /* move_item_down - moves an item down by swapping it with the item below it @arg $table_name - the table name that contains the target id @arg $current_id - (int) the current id @arg $group_query - an SQL "where" clause to limit the query */ function move_item_down($table_name, $current_id, $group_query = '') { $next_item = get_item($table_name, 'sequence', $current_id, $group_query, 'next'); $sequence = db_fetch_cell_prepared("SELECT sequence FROM $table_name WHERE id = ?", array($current_id)); $sequence_next = db_fetch_cell_prepared("SELECT sequence FROM $table_name WHERE id = ?", array($next_item)); db_execute_prepared("UPDATE $table_name SET sequence = ? WHERE id = ?", array($sequence_next, $current_id)); db_execute_prepared("UPDATE $table_name SET sequence = ? WHERE id = ?", array($sequence, $next_item)); } /* move_item_up - moves an item down by swapping it with the item above it @arg $table_name - the table name that contains the target id @arg $current_id - (int) the current id @arg $group_query - an SQL "where" clause to limit the query */ function move_item_up($table_name, $current_id, $group_query = '') { $last_item = get_item($table_name, 'sequence', $current_id, $group_query, 'previous'); $sequence = db_fetch_cell_prepared("SELECT sequence FROM $table_name WHERE id = ?", array($current_id)); $sequence_last = db_fetch_cell_prepared("SELECT sequence FROM $table_name WHERE id = ?", array($last_item)); db_execute_prepared("UPDATE $table_name SET sequence = ? WHERE id = ?", array($sequence_last, $current_id)); db_execute_prepared("UPDATE $table_name SET sequence = ? WHERE id = ?", array($sequence, $last_item)); } /* exec_into_array - executes a command and puts each line of its output into an array @arg $command_line - the command to execute @returns - (array) an array containing the command output */ function exec_into_array($command_line) { $out = array(); $err = 0; exec($command_line,$out,$err); return array_values($out); } /* get_web_browser - determines the current web browser in use by the client @returns - ('ie' or 'moz' or 'other') */ function get_web_browser() { if (!empty($_SERVER['HTTP_USER_AGENT'])) { if (stristr($_SERVER['HTTP_USER_AGENT'], 'Mozilla') && (!(stristr($_SERVER['HTTP_USER_AGENT'], 'compatible')))) { return 'moz'; } elseif (stristr($_SERVER['HTTP_USER_AGENT'], 'MSIE')) { return 'ie'; } else { return 'other'; } } else { return 'other'; } } function get_guest_account() { return db_fetch_cell_prepared('SELECT id FROM user_auth WHERE username = ? OR id = ?', array(read_config_option('guest_user'), read_config_option('guest_user'))); } function get_template_account() { return db_fetch_cell_prepared('SELECT id FROM user_auth WHERE username = ? OR id = ?', array(read_config_option('user_template'), read_config_option('user_template'))); } /* draw_login_status - provides a consistent login status page for all pages that use it */ function draw_login_status($using_guest_account = false) { global $config; $guest_account = get_guest_account(); $auth_method = read_config_option('auth_method'); if (isset($_SESSION['sess_user_id']) && $_SESSION['sess_user_id'] == $guest_account) { api_plugin_hook('nav_login_before'); print __('Logged in as') . " <span id='user' class='user usermenuup'>". __('guest') . "</span></div><div><ul class='menuoptions' style='display:none;'><li><a href='" . $config['url_path'] . "index.php'>" . __('Login as Regular User') . "</a></li>\n"; print "<li class='menuHr'><hr class='menu'></li>"; print "<li id='userCommunity'><a href='https://forums.cacti.net' target='_blank'>" . __('User Community') . "</a></li>"; print "<li id='userDocumentation'><a href='https://github.com/Cacti/documentation/blob/develop/README.md' target='_blank'>" . __('Documentation') . "</a></li>"; print "</ul>"; api_plugin_hook('nav_login_after'); } elseif (isset($_SESSION['sess_user_id']) && $using_guest_account == false) { $user = db_fetch_row_prepared('SELECT username, password_change, realm FROM user_auth WHERE id = ?', array($_SESSION['sess_user_id'])); api_plugin_hook('nav_login_before'); print __('Logged in as') . " <span id='user' class='user usermenuup'>" . html_escape($user['username']) . "</span></div><div><ul class='menuoptions' style='display:none;'>"; print (is_realm_allowed(20) ? "<li><a href='" . $config['url_path'] . "auth_profile.php?action=edit'>" . __('Edit Profile') . "</a></li>":""); print ($user['password_change'] == 'on' && $user['realm'] == 0 ? "<li><a href='" . $config['url_path'] . "auth_changepassword.php'>" . __('Change Password') . "</a></li>":''); print "<li class='menuHr'><hr class='menu'></li>"; print "<li id='userCommunity'><a href='https://forums.cacti.net' target='_blank'>" . __('User Community') . "</a></li>"; print "<li id='userDocumentation'><a href='https://github.com/Cacti/documentation/blob/develop/README.md' target='_blank'>" . __('Documentation') . "</a></li>"; print "<li class='menuHr'><hr class='menu'></li>"; print ($auth_method > 0 ? "<li><a href='" . $config['url_path'] . "logout.php'>" . __('Logout') . "</a></li>":""); print "</ul>\n"; api_plugin_hook('nav_login_after'); } } /* * draw_navigation_text - determines the top header navigation text for the current page and displays it to * * @arg $type - (string) Either 'url' or 'title' * @return (string) Either the navigation text or title */ function draw_navigation_text($type = 'url') { global $config, $navigation; $nav_level_cache = (isset($_SESSION['sess_nav_level_cache']) ? $_SESSION['sess_nav_level_cache'] : array()); $navigation = api_plugin_hook_function('draw_navigation_text', $navigation); $current_page = get_current_page(); // Do an error check here for bad plugins manipulating the cache if (!is_array($nav_level_cache)) { $nav_level_cache = array(); } if (!isempty_request_var('action')) { get_filter_request_var('action', FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => '/^([-a-zA-Z0-9_\s]+)$/'))); } $current_action = (isset_request_var('action') ? get_request_var('action') : ''); // find the current page in the big array if (isset($navigation[$current_page . ':' . $current_action])) { $current_array = $navigation[$current_page . ':' . $current_action]; } else { $current_array = array( 'mapping' => 'index.php:', 'title' => ucwords(str_replace('_', ' ', basename(get_current_page(), '.php'))), 'level' => 1 ); } if (isset($current_array['mapping'])) { $current_mappings = explode(',', $current_array['mapping']); } else { $current_mappings = array(); } $current_nav = "<ul id='breadcrumbs'>"; $title = ''; $nav_count = 0; // resolve all mappings to build the navigation string for ($i=0; ($i < cacti_count($current_mappings)); $i++) { if (empty($current_mappings[$i])) { continue; } if ($i == 0) { // always use the default for level == 0 $url = $navigation{basename($current_mappings[$i])}['url']; if (basename($url) == 'graph_view.php') continue; } elseif (isset($nav_level_cache[$i]) && !empty($nav_level_cache[$i]['url'])) { // found a match in the url cache for this level $url = $nav_level_cache[$i]['url']; } elseif (isset($current_array['url'])) { // found a default url in the above array $url = $current_array['url']; } else { // default to no url $url = ''; } if ($current_mappings[$i] == '?') { // '?' tells us to pull title from the cache at this level if (isset($nav_level_cache[$i])) { $current_nav .= (empty($url) ? '' : "<li><a id='nav_$i' href='" . html_escape($url) . "'>"); $current_nav .= html_escape(resolve_navigation_variables($navigation[$nav_level_cache[$i]['id']]['title'])); $current_nav .= (empty($url) ? '' : '</a>' . (get_selected_theme() == 'classic' ? ' -> ':'') . '</li>'); $title .= html_escape(resolve_navigation_variables($navigation[$nav_level_cache[$i]['id']]['title'])) . ' -> '; } } else { // there is no '?' - pull from the above array $current_nav .= (empty($url) ? '' : "<li><a id='nav_$i' href='" . html_escape($url) . "'>"); $current_nav .= html_escape(resolve_navigation_variables($navigation{basename($current_mappings[$i])}['title'])); $current_nav .= (empty($url) ? '' : '</a>' . (get_selected_theme() == 'classic' ? ' -> ':'') . '</li>'); $title .= html_escape(resolve_navigation_variables($navigation{basename($current_mappings[$i])}['title'])) . ' -> '; } $nav_count++; } if ($nav_count) { if (isset($current_array['title'])) { $current_nav .= "<li><a id='nav_$i' href=#>" . html_escape(resolve_navigation_variables($current_array['title'])) . '</a></li>'; } } else { $current_array = $navigation[$current_page . ':' . $current_action]; $url = (isset($current_array['url']) ? $current_array['url']:''); if (isset($current_array['title'])) { $current_nav .= "<li><a id='nav_$i' href='$url'>" . html_escape(resolve_navigation_variables($current_array['title'])) . '</a></li>'; } } if (isset_request_var('action') || get_nfilter_request_var('action') == 'tree_content') { $tree_id = 0; $leaf_id = 0; if (isset_request_var('node')) { $parts = explode('-', get_request_var('node')); // Check for tree anchor if (strpos(get_request_var('node'), 'tree_anchor') !== false) { $tree_id = $parts[1]; $leaf_id = 0; } elseif (strpos(get_request_var('node'), 'tbranch') !== false) { // Check for branch $leaf_id = $parts[1]; $tree_id = db_fetch_cell_prepared('SELECT graph_tree_id FROM graph_tree_items WHERE id = ?', array($leaf_id)); } } if ($leaf_id > 0) { $leaf = db_fetch_row_prepared('SELECT host_id, title, graph_tree_id FROM graph_tree_items WHERE id = ?', array($leaf_id)); if (cacti_sizeof($leaf)) { if ($leaf['host_id'] > 0) { $leaf_name = db_fetch_cell_prepared('SELECT description FROM host WHERE id = ?', array($leaf['host_id'])); } else { $leaf_name = $leaf['title']; } $tree_name = db_fetch_cell_prepared('SELECT name FROM graph_tree WHERE id = ?', array($leaf['graph_tree_id'])); } else { $leaf_name = __('Leaf'); $tree_name = ''; } if (isset_request_var('hgd') && get_nfilter_request_var('hgd') != '') { $parts = explode(':', get_nfilter_request_var('hgd')); input_validate_input_number($parts[1]); if ($parts[0] == 'gt') { $leaf_sub = db_fetch_cell_prepared('SELECT name FROM graph_templates WHERE id = ?', array($parts[1])); } else { if ($parts[1] > 0) { $leaf_sub = db_fetch_cell_prepared('SELECT name FROM snmp_query WHERE id = ?', array($parts[1])); } else { $leaf_sub = __('Non Query Based'); } } } else { $leaf_sub = ''; } } else { $leaf_name = ''; $leaf_sub = ''; if ($tree_id > 0) { $tree_name = db_fetch_cell_prepared('SELECT name FROM graph_tree WHERE id = ?', array($tree_id)); } else { $tree_name = ''; } } $tree_title = $tree_name . ($leaf_name != '' ? ' (' . trim($leaf_name):'') . ($leaf_sub != '' ? ':' . trim($leaf_sub) . ')':($leaf_name != '' ? ')':'')); if ($tree_title != '') { $current_nav .= "<li><a id='nav_title' href=#>" . html_escape($tree_title) . '</a></li>'; } } elseif (preg_match('#link.php\?id=(\d+)#', $_SERVER['REQUEST_URI'], $matches)) { $externalLinks = db_fetch_row_prepared('SELECT title, style FROM external_links WHERE id = ?', array($matches[1])); $title = $externalLinks['title']; $style = $externalLinks['style']; if ($style == 'CONSOLE') { $current_nav = "<ul id='breadcrumbs'><li><a id='nav_0' href='" . $config['url_path'] . "index.php'>" . __('Console') . '</a>' . (get_selected_theme() == 'classic' ? ' -> ':'') . '</li>'; $current_nav .= "<li><a id='nav_1' href='#'>" . __('Link %s', html_escape($title)) . '</a></li>'; } else { $current_nav = "<ul id='breadcrumbs'><li><a id='nav_0'>" . html_escape($title) . '</a></li>'; } $tree_title = ''; } else { $tree_title = ''; } if (isset($current_array['title'])) { $title .= html_escape(resolve_navigation_variables($current_array['title']) . ' ' . $tree_title); } // keep a cache for each level we encounter $hasNavError = false; if (is_array($current_page)) { cacti_log('WARNING: Navigation item suppressed - current page is not a string: ' . var_export($current_page,true)); $hasNavError = true; } if (is_array($current_action)) { cacti_log('WARNING: Navigation item suppressed - current action is not a string: '. var_export($current_action,true)); $hasNavError = true; } if (is_array($current_array['level'])) { cacti_log('WARNING: Navigation item suppressed - current level is not a string: ' . var_export($current_array['level'],true)); $hasNavError = true; } if (!$hasNavError) { $nav_level_cache[$current_array['level']] = array( 'id' => $current_page . ':' . $current_action, 'url' => get_browser_query_string() ); } $current_nav .= '</ul>'; $_SESSION['sess_nav_level_cache'] = $nav_level_cache; if ($type == 'url') { return $current_nav; } else { return $title; } } /* resolve_navigation_variables - substitute any variables contained in the navigation text @arg $text - the text to substitute in @returns - the original navigation text with all substitutions made */ function resolve_navigation_variables($text) { $graphTitle = get_graph_title(get_filter_request_var('local_graph_id')); if (preg_match_all("/\|([a-zA-Z0-9_]+)\|/", $text, $matches)) { for ($i=0; $i<cacti_count($matches[1]); $i++) { switch ($matches[1][$i]) { case 'current_graph_title': $text = str_replace('|' . $matches[1][$i] . '|', $graphTitle, $text); break; } } } return $text; } /* get_associated_rras - returns a list of all RRAs referenced by a particular graph @arg $local_graph_id - (int) the ID of the graph to retrieve a list of RRAs for @returns - (array) an array containing the name and id of each RRA found */ function get_associated_rras($local_graph_id, $sql_where = '') { return db_fetch_assoc_prepared('SELECT DISTINCT ' . SQL_NO_CACHE . " dspr.id, dsp.step, dspr.steps, dspr.rows, dspr.name, dtd.rrd_step, dspr.timespan FROM graph_templates_item AS gti LEFT JOIN data_template_rrd AS dtr ON gti.task_item_id=dtr.id LEFT JOIN data_template_data AS dtd ON dtr.local_data_id = dtd.local_data_id LEFT JOIN data_source_profiles AS dsp ON dtd.data_source_profile_id=dsp.id LEFT JOIN data_source_profiles_rra AS dspr ON dsp.id=dspr.data_source_profile_id AND dtd.local_data_id != 0 WHERE gti.local_graph_id = ? $sql_where ORDER BY dspr.steps", array($local_graph_id) ); } /* get_nearest_timespan - returns the nearest defined timespan. Used for adding a default graph timespan for data source profile rras. @arg $timespan - (int) the timespan to fine a default for @returns - (int) the timespan to apply for the data source profile rra value */ function get_nearest_timespan($timespan) { global $timespans; $last = end($timespans); foreach($timespans as $index => $name) { if ($timespan > $index) { $last = $index; continue; } elseif ($timespan == $index) { return $index; } else { return $last; } } return $last; } /* get_browser_query_string - returns the full url, including args requested by the browser @returns - the url requested by the browser */ function get_browser_query_string() { if (!empty($_SERVER['REQUEST_URI'])) { return sanitize_uri($_SERVER['REQUEST_URI']); } else { return sanitize_uri(get_current_page() . (empty($_SERVER['QUERY_STRING']) ? '' : '?' . $_SERVER['QUERY_STRING'])); } } /* get_current_page - returns the basename of the current page in a web server friendly way @returns - the basename of the current script file */ function get_current_page($basename = true) { if (isset($_SERVER['SCRIPT_NAME']) && $_SERVER['SCRIPT_NAME'] != '') { if ($basename) { return basename($_SERVER['SCRIPT_NAME']); } else { return $_SERVER['SCRIPT_NAME']; } } elseif (isset($_SERVER['SCRIPT_FILENAME']) && $_SERVER['SCRIPT_FILENAME'] != '') { if ($basename) { return basename($_SERVER['SCRIPT_FILENAME']); } else { return $_SERVER['SCRIPT_FILENAME']; } } else { cacti_log('ERROR: unable to determine current_page'); } return false; } /* get_hash_graph_template - returns the current unique hash for a graph template @arg $graph_template_id - (int) the ID of the graph template to return a hash for @arg $sub_type (optional) return the hash for a particular subtype of this type @returns - a 128-bit, hexadecimal hash */ function get_hash_graph_template($graph_template_id, $sub_type = 'graph_template') { switch ($sub_type) { case 'graph_template': $hash = db_fetch_cell_prepared('SELECT hash FROM graph_templates WHERE id = ?', array($graph_template_id)); break; case 'graph_template_item': $hash = db_fetch_cell_prepared('SELECT hash FROM graph_templates_item WHERE id = ?', array($graph_template_id)); break; case 'graph_template_input': $hash = db_fetch_cell_prepared('SELECT hash FROM graph_template_input WHERE id = ?', array($graph_template_id)); break; default: return generate_hash(); break; } if (preg_match('/[a-fA-F0-9]{32}/', $hash)) { return $hash; } else { return generate_hash(); } } /* get_hash_data_template - returns the current unique hash for a data template @arg $graph_template_id - (int) the ID of the data template to return a hash for @arg $sub_type (optional) return the hash for a particular subtype of this type @returns - a 128-bit, hexadecimal hash */ function get_hash_data_template($data_template_id, $sub_type = 'data_template') { switch ($sub_type) { case 'data_template': $hash = db_fetch_cell_prepared('SELECT hash FROM data_template WHERE id = ?', array($data_template_id)); break; case 'data_template_item': $hash = db_fetch_cell_prepared('SELECT hash FROM data_template_rrd WHERE id = ?', array($data_template_id)); break; default: return generate_hash(); break; } if (preg_match('/[a-fA-F0-9]{32}/', $hash)) { return $hash; } else { return generate_hash(); } } /* get_hash_data_input - returns the current unique hash for a data input method @arg $graph_template_id - (int) the ID of the data input method to return a hash for @arg $sub_type (optional) return the hash for a particular subtype of this type @returns - a 128-bit, hexadecimal hash */ function get_hash_data_input($data_input_id, $sub_type = 'data_input_method') { switch ($sub_type) { case 'data_input_method': $hash = db_fetch_cell_prepared('SELECT hash FROM data_input WHERE id = ?', array($data_input_id)); break; case 'data_input_field': $hash = db_fetch_cell_prepared('SELECT hash FROM data_input_fields WHERE id = ?', array($data_input_id)); break; default: return generate_hash(); break; } if (preg_match('/[a-fA-F0-9]{32}/', $hash)) { return $hash; } else { return generate_hash(); } } /* get_hash_cdef - returns the current unique hash for a cdef @arg $graph_template_id - (int) the ID of the cdef to return a hash for @arg $sub_type (optional) return the hash for a particular subtype of this type @returns - a 128-bit, hexadecimal hash */ function get_hash_cdef($cdef_id, $sub_type = 'cdef') { if (!is_numeric($cdef_id)) { return generate_hash(); } switch ($sub_type) { case 'cdef': $hash = db_fetch_cell_prepared('SELECT hash FROM cdef WHERE id = ?', array($cdef_id)); break; case 'cdef_item': $hash = db_fetch_cell_prepared('SELECT hash FROM cdef_items WHERE id = ?', array($cdef_id)); break; default: return generate_hash(); break; } if (strlen($hash) == 32 && ctype_xdigit($hash)) { return $hash; } else { return generate_hash(); } } /* get_hash_gprint - returns the current unique hash for a gprint preset @arg $graph_template_id - (int) the ID of the gprint preset to return a hash for @returns - a 128-bit, hexadecimal hash */ function get_hash_gprint($gprint_id) { $hash = db_fetch_cell_prepared('SELECT hash FROM graph_templates_gprint WHERE id = ?', array($gprint_id)); if (strlen($hash) == 32 && ctype_xdigit($hash)) { return $hash; } else { return generate_hash(); } } /** * returns the current unique hash for a vdef * @param $graph_template_id - (int) the ID of the vdef to return a hash for * @param $sub_type (optional) return the hash for a particular subtype of this type * @returns - a 128-bit, hexadecimal hash */ function get_hash_vdef($vdef_id, $sub_type = "vdef") { switch ($sub_type) { case 'vdef': $hash = db_fetch_cell_prepared('SELECT hash FROM vdef WHERE id = ?', array($vdef_id)); break; case 'vdef_item': $hash = db_fetch_cell_prepared('SELECT hash FROM vdef_items WHERE id = ?', array($vdef_id)); break; default: return generate_hash(); break; } if (strlen($hash) == 32 && ctype_xdigit($hash)) { return $hash; } else { return generate_hash(); } } /** * returns the current unique hash for a vdef * @param $data_source_profile_id - (int) the ID of the data_source_profile to return a hash for * @returns - a 128-bit, hexadecimal hash */ function get_hash_data_source_profile($data_source_profile_id) { $hash = db_fetch_cell_prepared('SELECT hash FROM data_source_profiles WHERE id = ?', array($data_source_profile_id)); if (strlen($hash) == 32 && ctype_xdigit($hash)) { return $hash; } else { return generate_hash(); } } /* get_hash_host_template - returns the current unique hash for a gprint preset @arg $host_template_id - (int) the ID of the host template to return a hash for @returns - a 128-bit, hexadecimal hash */ function get_hash_host_template($host_template_id) { $hash = db_fetch_cell_prepared('SELECT hash FROM host_template WHERE id = ?', array($host_template_id)); if (strlen($hash) == 32 && ctype_xdigit($hash)) { return $hash; } else { return generate_hash(); } } /* get_hash_data_query - returns the current unique hash for a data query @arg $graph_template_id - (int) the ID of the data query to return a hash for @arg $sub_type (optional) return the hash for a particular subtype of this type @returns - a 128-bit, hexadecimal hash */ function get_hash_data_query($data_query_id, $sub_type = 'data_query') { switch ($sub_type) { case 'data_query': $hash = db_fetch_cell_prepared('SELECT hash FROM snmp_query WHERE id = ?', array($data_query_id)); break; case 'data_query_graph': $hash = db_fetch_cell_prepared('SELECT hash FROM snmp_query_graph WHERE id = ?', array($data_query_id)); break; case 'data_query_sv_data_source': $hash = db_fetch_cell_prepared('SELECT hash FROM snmp_query_graph_rrd_sv WHERE id = ?', array($data_query_id)); break; case 'data_query_sv_graph': $hash = db_fetch_cell_prepared('SELECT hash FROM snmp_query_graph_sv WHERE id = ?', array($data_query_id)); break; default: return generate_hash(); break; } if (strlen($hash) == 32 && ctype_xdigit($hash)) { return $hash; } else { return generate_hash(); } } /* get_hash_version - returns the item type and cacti version in a hash format @arg $type - the type of item to represent ('graph_template','data_template', 'data_input_method','cdef','vdef','gprint_preset','data_query','host_template') @returns - a 24-bit hexadecimal hash (8-bits for type, 16-bits for version) */ function get_hash_version($type) { global $hash_type_codes, $cacti_version_codes, $config; return $hash_type_codes[$type] . $cacti_version_codes[CACTI_VERSION]; } /* generate_hash - generates a new unique hash @returns - a 128-bit, hexadecimal hash */ function generate_hash() { return md5(session_id() . microtime() . rand(0,1000)); } /* debug_log_insert_section_start - creates a header item for breaking down the debug log @arg $type - the 'category' or type of debug message @arg $text - section header */ function debug_log_insert_section_start($type, $text, $allowcopy = false) { $copy_prefix = ''; $copy_dataid = ''; if ($allowcopy) { $uid = generate_hash(); $copy_prefix = '<div class=\'cactiTableButton debug\'><span><a class=\'linkCopyDark cactiTableCopy\' id=\'copyToClipboard' . $uid . '\'>' . __esc('Copy') . '</a></span></div>'; $copy_dataid = ' id=\'clipboardData'.$uid.'\''; $copy_headerid = ' id=\'clipboardHeader'.$uid.'\''; } debug_log_insert($type, '<table class=\'cactiTable debug\'' . $copy_headerid . '><tr class=\'tableHeader\'><td>' . html_escape($text) . $copy_prefix . '</td></tr><tr><td style=\'padding:0px;\'><table style=\'display:none;\'' . $copy_dataid . '><tr><td><div style=\'font-family: monospace;\'>'); } /* debug_log_insert_section_end - finalizes the header started with the start function @arg $type - the 'category' or type of debug message */ function debug_log_insert_section_end($type) { debug_log_insert($type, "</div></td></tr></table></td></tr></td></table>"); } /* debug_log_insert - inserts a line of text into the debug log @arg $type - the 'category' or type of debug message @arg $text - the actual debug message */ function debug_log_insert($type, $text) { global $config; if ($config['poller_id'] == 1 || isset($_SESSION)) { if (!isset($_SESSION['debug_log'][$type])) { $_SESSION['debug_log'][$type] = array(); } array_push($_SESSION['debug_log'][$type], $text); } else { if (!isset($config['debug_log'][$type])) { $config['debug_log'][$type] = array(); } array_push($config['debug_log'][$type], $text); } } /* debug_log_clear - clears the debug log for a particular category @arg $type - the 'category' to clear the debug log for. omitting this argument implies all categories */ function debug_log_clear($type = '') { if ($type == '') { kill_session_var('debug_log'); } else { if (isset($_SESSION['debug_log'])) { unset($_SESSION['debug_log'][$type]); } } } /* debug_log_return - returns the debug log for a particular category @arg $type - the 'category' to return the debug log for. @returns - the full debug log for a particular category */ function debug_log_return($type) { $log_text = ''; if ($type == 'new_graphs') { if (isset($_SESSION['debug_log'][$type])) { $log_text .= "<table style='width:100%;'>"; for ($i=0; $i<cacti_count($_SESSION['debug_log'][$type]); $i++) { $log_text .= '<tr><td>' . $_SESSION['debug_log'][$type][$i] . '</td></tr>'; } $log_text .= '</table>'; } } else { if (isset($_SESSION['debug_log'][$type])) { $log_text .= "<table style='width:100%;'>"; foreach($_SESSION['debug_log'][$type] as $key => $val) { $log_text .= "<tr><td>$val</td></tr>\n"; unset($_SESSION['debug_log'][$type][$key]); } $log_text .= '</table>'; } } return $log_text; } /* sanitize_search_string - cleans up a search string submitted by the user to be passed to the database. NOTE: some of the code for this function came from the phpBB project. @arg $string - the original raw search string @returns - the sanitized search string */ function sanitize_search_string($string) { static $drop_char_match = array('(',')','^', '$', '<', '>', '`', '\'', '"', '|', ',', '?', '+', '[', ']', '{', '}', '#', ';', '!', '=', '*'); static $drop_char_replace = array('','',' ', ' ', ' ', ' ', '', '', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '); /* Replace line endings by a space */ $string = preg_replace('/[\n\r]/is', ' ', $string); /* HTML entities like &nbsp; */ $string = preg_replace('/\b&[a-z]+;\b/', ' ', $string); /* Remove URL's */ $string = preg_replace('/\b[a-z0-9]+:\/\/[a-z0-9\.\-]+(\/[a-z0-9\?\.%_\-\+=&\/]+)?/', ' ', $string); /* Filter out strange characters like ^, $, &, change "it's" to "its" */ for($i = 0; $i < cacti_count($drop_char_match); $i++) { $string = str_replace($drop_char_match[$i], $drop_char_replace[$i], $string); } return $string; } /** cleans up a URI, e.g. from REQUEST_URI and/or QUERY_STRING * in case of XSS attack, expect the result to be broken * we do NOT sanitize in a way, that attacks are converted to valid HTML * it is ok, when the result is broken but the application stays alive * @arg string $uri - the uri to be sanitized * @returns string - the sanitized uri */ function sanitize_uri($uri) { static $drop_char_match = array('^', '$', '<', '>', '`', "'", '"', '|', '+', '[', ']', '{', '}', ';', '!', '(', ')'); static $drop_char_replace = array( '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''); if (strpos($uri, 'graph_view.php')) { if (!strpos($uri, 'action=')) { $uri = $uri . (strpos($uri, '?') ? '&':'?') . 'action=' . get_request_var('action'); } } return str_replace($drop_char_match, $drop_char_replace, strip_tags(urldecode($uri))); } /** Checks to see if a string is base64 encoded * @arg string $data - the string to be validated * @returns boolean - true is the string is base64 otherwise false */ function is_base64_encoded($data) { // Perform a simple check first if (!preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $data)) { return false; } // Now test with the built-in function $ndata = base64_decode($data, true); if ($ndata === false) { return false; } // Do a re-encode test and compare if (base64_encode($ndata) != $data) { return false; } return true; } /** cleans up a CDEF/VDEF string * the CDEF/VDEF must have passed all magic string replacements beforehand * @arg string $cdef - the CDEF/VDEF to be sanitized * @returns string - the sanitized CDEF/VDEF */ function sanitize_cdef($cdef) { static $drop_char_match = array('^', '$', '<', '>', '`', '\'', '"', '|', '[', ']', '{', '}', ';', '!'); static $drop_char_replace = array( '', '', '', '', '', '', '', '', '', '', '', '', '', ''); return str_replace($drop_char_match, $drop_char_replace, $cdef); } /** verifies all selected items are numeric to guard against injection * @arg array $items - an array of serialized items from a post * @returns array - the sanitized selected items array */ function sanitize_unserialize_selected_items($items) { if ($items != '') { $unstripped = stripslashes($items); // validate that sanitized string is correctly formatted if (preg_match('/^a:[0-9]+:{/', $unstripped) && !preg_match('/(^|;|{|})O:\+?[0-9]+:"/', $unstripped)) { $items = unserialize($unstripped); if (is_array($items)) { foreach ($items as $item) { if (is_array($item)) { return false; } elseif (!is_numeric($item) && ($item != '')) { return false; } } } else { return false; } } else { return false; } } else { return false; } return $items; } function cacti_escapeshellcmd($string) { global $config; if ($config['cacti_server_os'] == 'unix') { return escapeshellcmd($string); } else { $replacements = "#&;`|*?<>^()[]{}$\\"; for ($i=0; $i < strlen($replacements); $i++) { $string = str_replace($replacements[$i], ' ', $string); } return $string; } } /** * mimics escapeshellarg, even for windows * @param $string - the string to be escaped * @param $quote - true: do NOT remove quotes from result; false: do remove quotes * @return - the escaped [quoted|unquoted] string */ function cacti_escapeshellarg($string, $quote = true) { global $config; if ($string == '') { return $string; } /* we must use an apostrophe to escape community names under Unix in case the user uses characters that the shell might interpret. the ucd-snmp binaries on Windows flip out when you do this, but are perfectly happy with a quotation mark. */ if ($config['cacti_server_os'] == 'unix') { $string = escapeshellarg($string); if ($quote) { return $string; } else { # remove first and last char return substr($string, 1, (strlen($string)-2)); } } else { /* escapeshellarg takes care of different quotation for both linux and windows, * but unfortunately, it blanks out percent signs * we want to keep them, e.g. for GPRINT format strings * so we need to create our own escapeshellarg * on windows, command injection requires to close any open quotation first * so we have to escape any quotation here */ if (substr_count($string, CACTI_ESCAPE_CHARACTER)) { $string = str_replace(CACTI_ESCAPE_CHARACTER, "\\" . CACTI_ESCAPE_CHARACTER, $string); } /* ... before we add our own quotation */ if ($quote) { return CACTI_ESCAPE_CHARACTER . $string . CACTI_ESCAPE_CHARACTER; } else { return $string; } } } /** * set a page refresh in Cacti through a callback * @param $refresh - an array containing the page, seconds, and logout * @return - nill */ function set_page_refresh($refresh) { if (isset($refresh['seconds'])) { $_SESSION['refresh']['seconds'] = $refresh['seconds']; } if (isset($refresh['logout'])) { if ($refresh['logout'] == 'true' || $refresh['logout'] === true) { $_SESSION['refresh']['logout'] = 'true'; } else { $_SESSION['refresh']['logout'] = 'false'; } } else { $_SESSION['refresh']['logout'] = 'true'; } if (isset($refresh['page'])) { $_SESSION['refresh']['page'] = $refresh['page']; } } function bottom_footer() { global $config, $no_session_write; include_once($config['base_path'] . '/include/global_session.php'); if (!isset_request_var('header') || get_nfilter_request_var('header') == 'true') { include_once($config['base_path'] . '/include/bottom_footer.php'); } /* we use this session var to store field values for when a save fails, this way we can restore the field's previous values. we reset it here, because they only need to be stored for a single page */ kill_session_var('sess_field_values'); /* make sure the debug log doesn't get too big */ debug_log_clear(); /* close the session */ if (array_search(get_current_page(), $no_session_write) === false) { session_write_close(); } /* close the database connection */ db_close(); } function top_header() { global $config; if (!isset_request_var('header') || get_nfilter_request_var('header') == 'true') { include_once($config['base_path'] . '/include/top_header.php'); } } function top_graph_header() { global $config; html_validate_tree_vars(); if (!isset_request_var('header') || get_nfilter_request_var('header') == 'true') { include_once($config['base_path'] . '/include/top_graph_header.php'); } } function general_header() { global $config; if (!isset_request_var('header') || get_nfilter_request_var('header') == 'true') { include_once($config['base_path'] . '/include/top_general_header.php'); } } function appendHeaderSuppression($url) { if (strpos($url, 'header=false') < 0) { return $url . (strpos($url, '?') ? '&':'?') . 'header=false'; } return $url; } function admin_email($subject, $message) { if (read_config_option('admin_user')) { if (read_config_option('notify_admin')) { $admin_details = db_fetch_row_prepared('SELECT full_name, email_address FROM user_auth WHERE id = ?', array(read_config_option('admin_user'))); if (cacti_sizeof($admin_details)) { $email = read_config_option('settings_from_email'); $name = read_config_option('settings_from_name'); if ($name != '') { $from = '"' . $name . '" <' . $email . '>'; } else { $from = $email; } if ($admin_details['email_address'] != '') { if ($admin_details['full_name'] != '') { $to = '"' . $admin_details['full_name'] . '" <' . $admin_details['email_address'] . '>'; } else { $to = $admin_details['email_address']; } send_mail($to, $from, $subject, $message, '', '', true); } else { cacti_log('WARNING: Primary Admin account does not have an email address! Unable to send administrative Email.', false, 'SYSTEM'); } } else { cacti_log('WARNING: Primary Admin account set to an invalid user! Unable to send administrative Email.', false, 'SYSTEM'); } } else { cacti_log('WARNING: Primary Admin account notifications disabled! Unable to send administrative Email.', false, 'SYSTEM'); } } else { cacti_log('WARNING: Primary Admin account not set! Unable to send administrative Email.', false, 'SYSTEM'); } } function send_mail($to, $from, $subject, $body, $attachments = '', $headers = '', $html = false) { $fromname = ''; if (is_array($from)) { $fromname = $from[1]; $from = $from[0]; } if ($from == '') { $from = read_config_option('settings_from_email'); $fromname = read_config_option('settings_from_name'); } elseif ($fromname == '') { $full_name = db_fetch_cell_prepared('SELECT full_name FROM user_auth WHERE email_address = ?', array($from)); if (empty($full_name)) { $fromname = $from; } else { $fromname = $full_name; } } $from = array(0 => $from, 1 => $fromname); return mailer($from, $to, '', '', '', $subject, $body, '', $attachments, $headers, $html); } /** mailer - function to send mails to users * @arg $from - single contact (see below) * @arg $to - single or multiple contacts (see below) * @arg $cc - none, single or multiple contacts (see below) * @arg $bcc - none, single or multiple contacts (see below) * @arg $replyto - none, single or multiple contacts (see below) * note that this value is used when hitting reply (overriding the default of using from) * @arg $subject - the email subject * @arg $body - the email body, in HTML format. If content_text is not set, the function will attempt to extract * from the HTML format. * @arg $body_text - the email body in TEXT format. If set, it will override the stripping tags method * @arg $attachments - the emails attachments as an array * @arg $headers - an array of name value pairs representing custom headers. * @arg $html - if set to true, html is the default, otherwise text format will be used * * For contact parameters, they can accept arrays containing zero or more values in the forms of: * 'email@email.com,email2@email.com,email3@email.com' * array('email1@email.com' => 'My email', 'email2@email.com' => 'Your email', 'email3@email.com' => 'Whose email') * array(array('email' => 'email1@email.com', 'name' => 'My email'), array('email' => 'email2@email.com', * 'name' => 'Your email'), array('email' => 'email3@email.com', 'name' => 'Whose email')) * * The $from field will only use the first contact specified. If no contact is provided for $replyto * then $from is used for that too. If $from is empty, it will default to cacti@<server> or if no server name can * be found, it will use cacti@cacti.net * * The $attachments parameter may either be a single string, or a list of attachments * either as strings or an array. The array can have the following keys: * * filename : name of the file to attach (display name for graphs) * display : displayed name of the attachment * mime_type : MIME type to be set against the attachment. If blank or missing mailer will attempt to auto detect * attachment : String containing attachment for image-based attachments (<GRAPH> or <GRAPH:#> activates graph mode * and requires $body parameter is HTML containing one of those values) * inline : Whether to attach 'inline' (default for graph mode) or as 'attachment' (default for all others) * encoding : Encoding type, normally base64 */ function mailer($from, $to, $cc, $bcc, $replyto, $subject, $body, $body_text = '', $attachments = '', $headers = '', $html = true) { global $config, $cacti_locale, $mail_methods; require_once($config['include_path'] . '/vendor/phpmailer/src/Exception.php'); require_once($config['include_path'] . '/vendor/phpmailer/src/PHPMailer.php'); require_once($config['include_path'] . '/vendor/phpmailer/src/SMTP.php'); // Create the PHPMailer instance $mail = new PHPMailer\PHPMailer\PHPMailer; // Set a reasonable timeout of 5 seconds $timeout = read_config_option('settings_smtp_timeout'); if (empty($timeout) || $timeout < 0 || $timeout > 300) { $mail->Timeout = 5; } else { $mail->Timeout = $timeout; } $langparts = explode('-', $cacti_locale); if (file_exists($config['include_path'] . '/vendor/phpmailer/language/phpmailer.lang-' . $langparts[0] . '.php')) { $mail->setLanguage($langparts[0], $config['include_path'] . '/vendor/phpmailer/language/'); } $how = read_config_option('settings_how'); if ($how < 0 || $how > 2) { $how = 0; } if ($how == 0) { $mail->isMail(); } elseif ($how == 1) { $mail->Sendmail = read_config_option('settings_sendmail_path'); $mail->isSendmail(); } elseif ($how == 2) { $mail->isSMTP(); $mail->Host = read_config_option('settings_smtp_host'); $mail->Port = read_config_option('settings_smtp_port'); if (read_config_option('settings_smtp_username') != '') { $mail->SMTPAuth = true; $mail->Username = read_config_option('settings_smtp_username'); if (read_config_option('settings_smtp_password') != '') { $mail->Password = read_config_option('settings_smtp_password'); } } else { $mail->SMTPAuth = false; } $secure = read_config_option('settings_smtp_secure'); if (!empty($secure) && $secure != 'none') { $mail->SMTPSecure = true; if (substr_count($mail->Host, ':') == 0) { $mail->Host = $secure . '://' . $mail->Host; } } else { $mail->SMTPAutoTLS = false; $mail->SMTPSecure = false; } } /* perform data substitution */ if (strpos($subject, '|date_time|') !== false) { $date = read_config_option('date'); if (!empty($date)) { $time = strtotime($date); } else { $time = time(); } $subject = str_replace('|date_time|', date(CACTI_DATE_TIME_FORMAT, $time), $subject); } /* * Set the from details using the variable passed in * - if name is blank, use setting's name * - if email is blank, use setting's email, otherwise default to * cacti@<server> or cacti@cacti.net if no known server name */ $from = parse_email_details($from, 1); // from name was empty, use value in settings if (empty($from['name'])) { $from['name'] = read_config_option('settings_from_name'); } // from email was empty, use email in settings if (empty($from['email'])) { $from['email'] = read_config_option('settings_from_email'); } if (empty($from['email'])) { if (isset($_SERVER['HOSTNAME'])) { $from['email'] = 'Cacti@' . $_SERVER['HOSTNAME']; } else { $from['email'] = 'Cacti@cacti.net'; } if (empty($from['name'])) { $from['name'] = 'Cacti'; } } $fromText = add_email_details(array($from), $result, array($mail, 'setFrom')); if ($result == false) { return record_mailer_error($fromText, $mail->ErrorInfo); } // Convert $to variable to proper array structure $to = parse_email_details($to); $toText = add_email_details($to, $result, array($mail, 'addAddress')); if ($result == false) { return record_mailer_error($toText, $mail->ErrorInfo); } $cc = parse_email_details($cc); $ccText = add_email_details($cc, $result, array($mail, 'addCC')); if ($result == false) { return record_mailer_error($ccText, $mail->ErrorInfo); } $bcc = parse_email_details($bcc); $bccText = add_email_details($bcc, $result, array($mail, 'addBCC')); if ($result == false) { return record_mailer_error($bccText, $mail->ErrorInfo); } // This is a failsafe, should never happen now if (!(cacti_sizeof($to) || cacti_sizeof($cc) || cacti_sizeof($bcc))) { cacti_log('ERROR: No recipient address set!!', false, 'MAILER'); cacti_debug_backtrace('MAILER ERROR'); return __('Mailer Error: No recipient address set!!<br>If using the <i>Test Mail</i> link, please set the <b>Alert e-mail</b> setting.'); } $replyto = parse_email_details($replyto); $replyText = add_email_details($replyto, $result, array($mail, 'addReplyTo')); if ($result == false) { return record_mailer_error($replyText, $mail->ErrorInfo); } $body = str_replace('<SUBJECT>', $subject, $body); $body = str_replace('<TO>', $toText, $body); $body = str_replace('<CC>', $ccText, $body); $body = str_replace('<FROM>', $fromText, $body); $body = str_replace('<REPLYTO>', $replyText, $body); $body_text = str_replace('<SUBJECT>', $subject, $body_text); $body_text = str_replace('<TO>', $toText, $body_text); $body_text = str_replace('<CC>', $ccText, $body_text); $body_text = str_replace('<FROM>', $fromText, $body_text); $body_text = str_replace('<REPLYTO>', $replyText, $body_text); // Set the subject $mail->Subject = $subject; // Support i18n $mail->CharSet = 'UTF-8'; $mail->Encoding = 'base64'; // Set the wordwrap limits $wordwrap = read_config_option('settings_wordwrap'); if ($wordwrap == '') { $wordwrap = 76; } elseif ($wordwrap > 9999) { $wordwrap = 9999; } elseif ($wordwrap < 0) { $wordwrap = 76; } $mail->WordWrap = $wordwrap; $mail->setWordWrap(); if (!$html) { $mail->ContentType = 'text/plain'; } else { $mail->ContentType = 'text/html'; } $i = 0; // Handle Graph Attachments if (!empty($attachments) && !is_array($attachments)) { $attachments = array('attachment' => $attachments); } if (is_array($attachments) && cacti_sizeof($attachments)) { $graph_mode = (substr_count($body, '<GRAPH>') > 0); $graph_ids = (substr_count($body, '<GRAPH:') > 0); $default_opts = array( // MIME type to be set against the attachment 'mime_type' => '', // Display name of the attachment 'filename' => '', // String containing attachment for image-based attachments 'attachment' => '', // Whether to attach inline or as attachment 'inline' => ($graph_mode || $graph_ids) ? 'inline' : 'attachment', // Encoding type, normally base64 'encoding' => 'base64', ); foreach($attachments as $attachment) { if (!is_array($attachment)) { $attachment = array('attachment' => $attachment); } foreach ($default_opts as $opt_name => $opt_default) { if (!array_key_exists($opt_name, $attachment)) { $attachment[$opt_name] = $opt_default; } } if (!empty($attachment['attachment'])) { /* get content id and create attachment */ $cid = getmypid() . '_' . $i . '@' . 'localhost'; if (empty($attachment['filename'])) { $attachment['filename'] = basename($attachment['attachment']); } /* attempt to attach */ if (!($graph_mode || $graph_ids)) { $result = $mail->addAttachment($attachment['attachment'], $attachment['filename'], $attachment['encoding'], $attachment['mime_type'], $attachment['inline']); } else { $result = $mail->addStringEmbeddedImage($attachment['attachment'], $cid, $attachment['filename'], 'base64', $attachment['mime_type'], $attachment['inline']); } if ($result == false) { cacti_log('ERROR: ' . $mail->ErrorInfo, false, 'MAILER'); return $mail->ErrorInfo; } $i++; if ($graph_mode) { $body = str_replace('<GRAPH>', "<br><br><img src='cid:$cid'>", $body); } else if ($graph_ids) { /* handle the body text */ switch ($attachment['inline']) { case 'inline': $body = str_replace('<GRAPH:' . $attachment['local_graph_id'] . ':' . $attachment['timespan'] . '>', "<img src='cid:$cid' >", $body); break; case 'attachment': $body = str_replace('<GRAPH:' . $attachment['local_graph_id'] . ':' . $attachment['timespan'] . '>', '', $body); break; } } } } } /* process custom headers */ if (is_array($headers) && cacti_sizeof($headers)) { foreach($headers as $name => $value) { $mail->addCustomHeader($name, $value); } } // Set both html and non-html bodies $brs = array('<br>', '<br />', '</br>'); if ($html) { $body = $body . '<br>'; } if ($body_text == '') { $body_text = strip_tags(str_ireplace($brs, "\n", $body)); } $mail->isHTML($html); $mail->Body = ($html ? $body : $body_text); if ($html && $body_text != '') { $mail->AltBody = $body_text; } $result = $mail->send(); $error = $mail->ErrorInfo; //$result ? '' : $mail->ErrorInfo; $method = $mail_methods[intval(read_config_option('settings_how'))]; $rtype = $result ? 'INFO' : 'WARNING'; $rmsg = $result ? 'successfully sent' : 'failed'; if ($error != '') { $message = sprintf("%s: Mail %s via %s from '%s', to '%s', cc '%s', Subject '%s'%s", $rtype, $rmsg, $method, $fromText, $toText, $ccText, $subject, ", Error: $error"); } else { $message = sprintf("%s: Mail %s via %s from '%s', to '%s', cc '%s', Subject '%s'", $rtype, $rmsg, $method, $fromText, $toText, $ccText, $subject); } cacti_log($message, false, 'MAILER'); if ($result == false) { cacti_log(cacti_debug_backtrace($rtype), false, 'MAILER'); } return $error; } function record_mailer_error($retError, $mailError) { $errorInfo = empty($retError) ? $mailError : $retError; cacti_log('ERROR: ' . $errorInfo, false, 'CMDPHP MAILER'); cacti_debug_backtrace('MAILER ERROR'); return $errorInfo; } function add_email_details($emails, &$result, callable $addFunc) { $arrText = array(); foreach ($emails as $e) { if (!empty($e['email'])) { //if (is_callable($addFunc)) { if (!empty($addFunc)) { $result = $addFunc($e['email'], $e['name']); if (!$result) { return ''; } } $arrText[] = create_emailtext($e); } else if (!empty($e['name'])) { $result = false; return 'Bad email format, name but no address: ' . $e['name']; } } $text = implode(',', $arrText); //echo "add_email_sw_details(): $text\n"; return $text; } function parse_email_details($emails, $max_records = 0, $details = array()) { if (!is_array($emails)) { $emails = array($emails); } $update = array(); foreach ($emails as $check_email) { if (!empty($check_email)) { if (!is_array($check_email)) { $emails = explode(',', $check_email); foreach($emails as $email) { $email_array = split_emaildetail($email); $details[] = $email_array; } } else { $has_name = array_key_exists('name', $check_email); $has_email = array_key_exists('email', $check_email); if ($has_name || $has_email) { $name = $has_name ? $check_email['name'] : ''; $email = $has_email ? $check_email['email'] : ''; } else { $name = array_key_exists(1, $check_email) ? $check_email[1] : ''; $email = array_key_exists(0, $check_email) ? $check_email[0] : ''; } $details[] = array('name' => trim($name), 'email' => trim($email)); } } } if ($max_records == 1) { $results = count($details) ? $details[0] : array(); } elseif ($max_records != 0 && $max_records < count($details)) { $results = array(); foreach ($details as $d) { $results[] = $d; $max_records--; if ($max_records == 0) { break; } } } else { $results = $details; } return $results; } function split_emaildetail($email) { $rname = ''; $rmail = ''; if (!is_array($email)) { $email = trim($email); $sPattern = '/(?:"?([^"]*)"?\s)?(?:<?(.+@[^>]+)>?)/i'; preg_match($sPattern, $email, $aMatch); if (isset($aMatch[1])) { $rname = trim($aMatch[1]); } if (isset($aMatch[2])) { $rmail = trim($aMatch[2]); } } else { $rmail = $email[0]; $rname = $email[1]; } return array('name' => $rname, 'email' => $rmail); } function create_emailtext($e) { if (empty($e['email'])) { $text = ''; } else { if (empty($e['name'])) { $text = $e['email']; } else { $text = $e['name'] . ' <' . $e['email'] . '>'; } } return $text; } function ping_mail_server($host, $port, $user, $password, $timeout = 10, $secure = 'none') { global $config; require_once($config['include_path'] . '/vendor/phpmailer/src/Exception.php'); require_once($config['include_path'] . '/vendor/phpmailer/src/PHPMailer.php'); require_once($config['include_path'] . '/vendor/phpmailer/src/SMTP.php'); //Create a new SMTP instance $smtp = new PHPMailer\PHPMailer\SMTP; if (!empty($secure) && $secure != 'none') { $smtp->SMTPSecure = $secure; if (substr_count($host, ':') == 0) { $host = $secure . '://' . $host; } } else { $smtp->SMTPAutoTLS = false; $smtp->SMTPSecure = false; } //Enable connection-level debug output $smtp->do_debug = 0; //$smtp->do_debug = SMTP::DEBUG_LOWLEVEL; $results = true; try { //Connect to an SMTP server if ($smtp->connect($host, $port, $timeout)) { //Say hello if ($smtp->hello(gethostbyname(gethostname()))) { //Put your host name in here //Authenticate if ($user != '') { if ($smtp->authenticate($user, $password)) { $results = true; } else { throw new Exception(__('Authentication failed: %s', $smtp->getLastReply())); } } } else { throw new Exception(__('HELO failed: %s', $smtp->getLastReply())); } } else { throw new Exception(__('Connect failed: %s', $smtp->getLastReply())); } } catch (Exception $e) { $results = __('SMTP error: ') . $e->getMessage(); cacti_log($results); } //Whatever happened, close the connection. $smtp->quit(true); return $results; } function email_test() { global $config; $message = __('This is a test message generated from Cacti. This message was sent to test the configuration of your Mail Settings.') . '<br><br>'; $message .= __('Your email settings are currently set as follows') . '<br><br>'; $message .= '<b>' . __('Method') . '</b>: '; print __('Checking Configuration...<br>'); $ping_results = true; $how = read_config_option('settings_how'); if ($how < 0 || $how > 2) $how = 0; if ($how == 0) { $mail = __('PHP\'s Mailer Class'); } elseif ($how == 1) { $mail = __('Sendmail') . '<br><b>' . __('Sendmail Path'). '</b>: '; $sendmail = read_config_option('settings_sendmail_path'); $mail .= $sendmail; } elseif ($how == 2) { print __('Method: SMTP') . '<br>'; $mail = __('SMTP') . '<br>'; $smtp_host = read_config_option('settings_smtp_host'); $smtp_port = read_config_option('settings_smtp_port'); $smtp_username = read_config_option('settings_smtp_username'); $smtp_password = read_config_option('settings_smtp_password'); $smtp_secure = read_config_option('settings_smtp_secure'); $smtp_timeout = read_config_option('settings_smtp_timeout'); $mail .= "<b>" . __('Device') . "</b>: $smtp_host<br>"; $mail .= "<b>" . __('Port') . "</b>: $smtp_port<br>"; if ($smtp_username != '' && $smtp_password != '') { $mail .= '<b>' . __('Authentication') . '</b>: true<br>'; $mail .= '<b>' . __('Username') . "</b>: $smtp_username<br>"; $mail .= '<b>' . __('Password') . '</b>: (' . __('Not Shown for Security Reasons') . ')<br>'; $mail .= '<b>' . __('Security') . "</b>: $smtp_secure<br>"; } else { $mail .= '<b>' . __('Authentication') . '</b>: false<br>'; } if (read_config_option('settings_ping_mail') == 0) { $ping_results = ping_mail_server($smtp_host, $smtp_port, $smtp_username, $smtp_password, $smtp_timeout, $smtp_secure); print __('Ping Results:') . ' ' . ($ping_results == 1 ? __('Success'):$ping_results) . '<br>'; if ($ping_results != 1) { $mail .= '<b>' . __('Ping Results') . '</b>: ' . $ping_results . '<br>'; } else { $mail .= '<b>' . __('Ping Results') . '</b>: ' . __('Success') . '<br>'; } } else { $ping_results = 1; $mail .= '<b>' . __('Ping Results') . '</b>: ' . __('Bypassed') . '<br>'; } } $message .= $mail; $message .= '<br>'; $errors = ''; if ($ping_results == 1) { print __('Creating Message Text...') . '<br><br>'; print "<center><table><tr><td>"; print "<table style='width:100%;'><tr><td>$message</td><tr></table></table></center><br>"; print __('Sending Message...') . '<br><br>'; $global_alert_address = read_config_option('settings_test_email'); $errors = send_mail($global_alert_address, '', __('Cacti Test Message'), $message, '', '', true); if ($errors == '') { $errors = __('Success!'); } } else { print __('Message Not Sent due to ping failure.'). '<br><br>'; } print "<center><table><tr><td>"; print "<table><tr><td>$errors</td><tr></table></table></center>"; } /* gethostbyaddr_wtimeout - This function provides a good method of performing a rapid lookup of a DNS entry for a host so long as you don't have to look far. */ function get_dns_from_ip ($ip, $dns, $timeout = 1000) { /* random transaction number (for routers etc to get the reply back) */ $data = rand(10, 99); /* trim it to 2 bytes */ $data = substr($data, 0, 2); /* create request header */ $data .= "\1\0\0\1\0\0\0\0\0\0"; /* split IP into octets */ $octets = explode('.', $ip); /* perform a quick error check */ if (cacti_count($octets) != 4) return 'ERROR'; /* needs a byte to indicate the length of each segment of the request */ for ($x=3; $x>=0; $x--) { switch (strlen($octets[$x])) { case 1: // 1 byte long segment $data .= "\1"; break; case 2: // 2 byte long segment $data .= "\2"; break; case 3: // 3 byte long segment $data .= "\3"; break; default: // segment is too big, invalid IP return 'ERROR'; } /* and the segment itself */ $data .= $octets[$x]; } /* and the final bit of the request */ $data .= "\7in-addr\4arpa\0\0\x0C\0\1"; /* create UDP socket */ $handle = @fsockopen("udp://$dns", 53); @stream_set_timeout($handle, floor($timeout/1000), ($timeout*1000)%1000000); @stream_set_blocking($handle, 1); /* send our request (and store request size so we can cheat later) */ $requestsize = @fwrite($handle, $data); /* get the response */ $response = @fread($handle, 1000); /* check to see if it timed out */ $info = @stream_get_meta_data($handle); /* close the socket */ @fclose($handle); if ($info['timed_out']) { return 'timed_out'; } /* more error handling */ if ($response == '') { return $ip; } /* parse the response and find the response type */ $type = @unpack('s', substr($response, $requestsize+2)); if (isset($type[1]) && $type[1] == 0x0C00) { /* set up our variables */ $host = ''; $len = 0; /* set our pointer at the beginning of the hostname uses the request size from earlier rather than work it out. */ $position = $requestsize + 12; /* reconstruct the hostname */ do { /* get segment size */ $len = unpack('c', substr($response, $position)); /* null terminated string, so length 0 = finished */ if ($len[1] == 0) { /* return the hostname, without the trailing '.' */ return strtoupper(substr($host, 0, strlen($host) -1)); } /* add the next segment to our host */ $host .= substr($response, $position+1, $len[1]) . '.'; /* move pointer on to the next segment */ $position += $len[1] + 1; } while ($len != 0); /* error - return the hostname we constructed (without the . on the end) */ return strtoupper($ip); } /* error - return the hostname */ return strtoupper($ip); } function poller_maintenance () { global $config; $command_string = cacti_escapeshellcmd(read_config_option('path_php_binary')); // If its not set, just assume its in the path if (trim($command_string) == '') { $command_string = 'php'; } $extra_args = ' -q ' . cacti_escapeshellarg($config['base_path'] . '/poller_maintenance.php'); exec_background($command_string, $extra_args); } function clog_admin() { if (!isset($_SESSION['sess_clog_level'])) { clog_authorized(); } if ($_SESSION["sess_clog_level"] == CLOG_PERM_ADMIN) { return true; } else { return false; } } function clog_authorized() { if (!isset($_SESSION['sess_clog_level'])) { if (isset($_SESSION['sess_user_id'])) { if (is_realm_allowed(18)) { $_SESSION['sess_clog_level'] = CLOG_PERM_ADMIN; } else { if (is_realm_allowed(19)) { $_SESSION['sess_clog_level'] = CLOG_PERM_USER; }else { $_SESSION['sess_clog_level'] = CLOG_PERM_NONE; } } } else { $_SESSION['sess_clog_level'] = CLOG_PERM_NONE; } } if ($_SESSION['sess_clog_level'] == CLOG_PERM_USER) { return true; } elseif ($_SESSION['sess_clog_level'] == CLOG_PERM_ADMIN) { return true; } else { return false; } } function update_system_mibs($host_id) { global $sessions; $system_mibs = array( 'snmp_sysDescr' => '.1.3.6.1.2.1.1.1.0', 'snmp_sysObjectID' => '.1.3.6.1.2.1.1.2.0', 'snmp_sysUpTimeInstance' => '.1.3.6.1.2.1.1.3.0', 'snmp_sysContact' => '.1.3.6.1.2.1.1.4.0', 'snmp_sysName' => '.1.3.6.1.2.1.1.5.0', 'snmp_sysLocation' => '.1.3.6.1.2.1.1.6.0' ); $h = db_fetch_row_prepared('SELECT * FROM host WHERE id = ?', array($host_id)); if (cacti_sizeof($h)) { open_snmp_session($host_id, $h); if (isset($sessions[$host_id . '_' . $h['snmp_version'] . '_' . $h['snmp_port']])) { foreach($system_mibs as $name => $oid) { $value = cacti_snmp_session_get($sessions[$host_id . '_' . $h['snmp_version'] . '_' . $h['snmp_port']], $oid); if (!empty($value)) { db_execute_prepared("UPDATE host SET $name = ? WHERE id = ?", array($value, $host_id)); } } } else { cacti_log("WARNING: Unable to open session for System Mib collection for Device[$host_id]", false, 'POLLER'); } } } function cacti_debug_backtrace($entry = '', $html = false, $record = true, $limit = 0, $skip = 0) { global $config; $skip = $skip >= 0 ? $skip : 1; $limit = $limit > 0 ? ($limit + $skip) : 0; $callers = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, $limit); while ($skip > 0) { array_shift($callers); $skip--; } $s=''; foreach ($callers as $c) { if (isset($c['line'])) { $line = '[' . $c['line'] . ']'; } else { $line = ''; } if (isset($c['file'])) { $file = str_replace($config['base_path'], '', $c['file']) . $line; } else { $file = $line; } $func = $c['function'].'()'; if (isset($c['class'])) { $func = $c['class'] . $c['type'] . $func; } $s = ($file != '' ? $file . ':':'') . "$func" . (empty($s) ? '' : ', ') . $s; } if (!empty($s)) { $s = ' (' . $s . ')'; } if ($record) { if ($html) { echo "<table style='width:100%;text-align:center;'><tr><td>$s</td></tr></table>\n"; } cacti_log(trim("$entry Backtrace: " . clean_up_lines($s)), false); } else { if (!empty($entry)) { return trim("$entry Backtrace: " . clean_up_lines($s)); } else { return trim(clean_up_lines($s)); } } } /* calculate_percentiles - Given and array of numbers, calculate the Nth percentile, * optionally, return an array of numbers containing elements required for * a whisker chart. * * @arg $data - an array of data * @arg $percentile - the Nth percentile to calculate. By default 95th. * #arg $whisker - if whisker is true, an array of values will be returned * including 25th, median, 75th, and 90th percentiles. * * @returns - either the Nth percentile, the elements for a whisker chart, * or false if there is insufficient data to determine. */ function calculate_percentiles($data, $percentile = 95, $whisker = false) { if ($percentile > 0 && $percentile < 1) { $p = $percentile; } elseif ($percentile > 1 && $percentile <= 100) { $p = $percentile * .01; }else { return false; } if ($whisker) { $tiles = array( '25th' => 0.25, '50th' => 0.50, '75th' => 0.75, '90th' => 0.90, '95th' => 0.95, ); } else { $tiles = array( 'custom' => $p ); } $results = array(); $elements = cacti_sizeof($data); /* sort the array to return */ sort($data); foreach($tiles as $index => $p) { /* calculate offsets into the array */ $allindex = ($elements - 1) * $p; $intvalindex = intval($allindex); $floatval = $allindex - $intvalindex; if (!is_float($floatval)) { $ptile = $data[$intvalindex]; } else { if ($elements > $intvalindex + 1) { $ptile = $floatval * ($data[$intvalindex + 1] - $data[$intvalindex]) + $data[$intvalindex]; } else { $ptile = $data[$intvalindex]; } } if ($index == 'custom') { return $ptile; } else { $results[$index] = $ptile; } } return $results; } function get_timeinstate($host) { $interval = read_config_option('poller_interval'); if ($host['availability_method'] == 0) { $time = 0; } elseif (isset($host['instate'])) { $time = $host['instate']; } elseif ($host['status_event_count'] > 0 && ($host['status'] == 1 || $host['status'] == 2)) { $time = $host['status_event_count'] * $interval; } elseif (strtotime($host['status_rec_date']) < 943916400 && ($host['status'] == 0 || $host['status'] == 3)) { $time = $host['total_polls'] * $interval; } elseif (strtotime($host['status_rec_date']) > 943916400) { $time = time() - strtotime($host['status_rec_date']); } elseif ($host['snmp_sysUpTimeInstance'] > 0) { $time = $host['snmp_sysUpTimeInstance']/100; } else { $time = 0; } return ($time > 0) ? get_daysfromtime($time) : __('N/A'); } function get_uptime($host) { return ($host['snmp_sysUpTimeInstance'] > 0) ? get_daysfromtime($host['snmp_sysUpTimeInstance']/100) : __('N/A'); } function get_daysfromtime($time, $secs = false, $pad = '', $format = DAYS_FORMAT_SHORT, $all = false) { global $days_from_time_settings; // Ensure we use an existing format or we'll end up with no text at all if (!isset($days_from_time_settings['text'][$format])) { $format = DAYS_FORMAT_SHORT; } $mods = $days_from_time_settings['mods']; $text = $days_from_time_settings['text'][$format]; $result = ''; foreach ($mods as $index => $mod) { if ($mod > 0 || $secs) { if ($time >= $mod) { if ($mod < 1) { $mod = 1; } $val = floor($time/$mod); $time %= $mod; } else { $val = 0; } if ($all || $val > 0) { $result .= padleft($pad, $val, 2) . $text['prefix'] . $text[$index] . $text['suffix']; $all = true; } } } return trim($result,$text['suffix']); } function padleft($pad = '', $value, $min = 2) { $result = "$value"; if (strlen($result) < $min && $pad != '') { $padded = $pad . $result; while ($padded != $result && strlen($result) < $min) { $padded = $pad . $result; } $result = $padded; } return $result; } function get_classic_tabimage($text, $down = false) { global $config; $images = array( false => 'tab_template_blue.gif', true => 'tab_template_red.gif' ); if ($text == '') return false; $text = strtolower($text); $possibles = array( array('DejaVuSans-Bold.ttf', 9, true), array('DejaVuSansCondensed-Bold.ttf', 9, false), array('DejaVuSans-Bold.ttf', 9, false), array('DejaVuSansCondensed-Bold.ttf', 9, false), array('DejaVuSans-Bold.ttf', 8, false), array('DejaVuSansCondensed-Bold.ttf', 8, false), array('DejaVuSans-Bold.ttf', 7, false), array('DejaVuSansCondensed-Bold.ttf', 7, true), ); $y = 30; $x = 44; $wlimit = 72; $wrapsize = 12; if (file_exists($config['base_path'] . '/images/' . $images[$down])) { $originalpath = getenv('GDFONTPATH'); putenv('GDFONTPATH=' . $config['base_path'] . '/include/fonts/'); $template = imagecreatefromgif($config['base_path'] . '/images/' . $images[$down]); $w = imagesx($template); $h = imagesy($template); $tab = imagecreatetruecolor($w, $h); imagecopy($tab, $template, 0, 0, 0, 0, $w, $h); $txcol = imagecolorat($tab, 0, 0); imagecolortransparent($tab,$txcol); $white = imagecolorallocate($tab, 255, 255, 255); $ttf_functions = function_exists('imagettftext') && function_exists('imagettfbbox'); if ($ttf_functions) { foreach ($possibles as $variation) { $font = $variation[0]; $fontsize = $variation[1]; $lines = array(); // if no wrapping is requested, or no wrapping is possible... if((!$variation[2]) || ($variation[2] && strpos($text,' ') === false)) { $bounds = imagettfbbox($fontsize, 0, $font, $text); $w = $bounds[4] - $bounds[0]; $h = $bounds[1] - $bounds[5]; $realx = $x - $w/2 -1; $lines[] = array($text, $font, $fontsize, $realx, $y); $maxw = $w; } else { $texts = explode("\n", wordwrap($text, $wrapsize), 2); $line = 1; $maxw = 0; foreach ($texts as $txt) { $bounds = imagettfbbox($fontsize, 0, $font, $txt); $w = $bounds[4] - $bounds[0]; $h = $bounds[1] - $bounds[5]; $realx = $x - $w/2 -1; $realy = $y - $h * $line + 3; $lines[] = array($txt, $font, $fontsize, $realx, $realy); if ($maxw < $w) { $maxw = $w; } $line--; } } if($maxw<$wlimit) break; } } else { while ($text > '') { for ($fontid = 5; $fontid>0; $fontid--) { $fontw = imagefontwidth($fontid); $fonth = imagefontheight($fontid); $realx = ($w - ($fontw * strlen($text)))/2; $realy = ($h - $fonth - 5); // Since we can't use FreeType, lets use a fixed location $lines = array(); $lines[] = array($text, $fontid, 0, $realx, $realy); if ($realx > 10 && $realy > 0) break; } if ($fontid == 0) { $spacer = strrpos($text,' '); if ($spacer === FALSE) { $spacer = strlen($text) - 1; } $text = substr($text,0,$spacer); // $lines[] = array(substr($text,0,$maxtext).'.'.$w.'.'.$maxtext.'.'.$fontw, $fontid, 0, $realx, $realy); } else { break; } } } foreach ($lines as $line) { if ($ttf_functions) { imagettftext($tab, $line[2], 0, $line[3], $line[4], $white, $line[1], $line[0]); }else{ imagestring($tab, $line[1], $line[3], $line[4], $line[0], $white); } } putenv('GDFONTPATH=' . $originalpath); imagetruecolortopalette($tab, true, 256); // generate the image an return the data directly ob_start(); imagegif($tab); $image = ob_get_contents(); ob_end_clean(); return("data:image/gif;base64," . base64_encode($image)); } else { return false; } } function cacti_oid_numeric_format() { if (function_exists('snmp_set_oid_output_format')) { snmp_set_oid_output_format(SNMP_OID_OUTPUT_NUMERIC); } elseif (function_exists("snmp_set_oid_numeric_print")) { snmp_set_oid_numeric_print(true); } } function IgnoreErrorHandler($message) { global $snmp_error; $snmp_ignore = array( 'No response from', 'noSuchName', 'No Such Object', 'Error in packet', 'This name does not exist', 'End of MIB', 'Timeout', 'Unknown host', 'Invalid object identifier', 'Name or service not known' ); foreach ($snmp_ignore as $i) { if (strpos($message, $i)) { $snmp_error = trim($message, "\\\n\t "); return true; } } $ignore = array( 'unable to read from socket' # ping.php line 387 socket refusal ); foreach ($ignore as $i) { if (strpos($message, $i)) { return true; } } return false; } function CactiErrorHandler($level, $message, $file, $line, $context) { global $phperrors; if (defined('IN_CACTI_INSTALL')) { return true; } if (IgnoreErrorHandler($message)) { return true; } if (error_reporting() == 0) { return true; } preg_match("/.*\/plugins\/([\w-]*)\/.*/", $file, $output_array); $plugin = (isset($output_array[1]) ? $output_array[1] : ''); $error = 'PHP ' . $phperrors[$level] . ($plugin != '' ? " in Plugin '$plugin'" : '') . ": $message in file: $file on line: $line"; switch ($level) { case E_COMPILE_ERROR: case E_CORE_ERROR: case E_ERROR: case E_PARSE: cacti_log($error, false, 'ERROR'); cacti_debug_backtrace('PHP ERROR PARSE', false, true, 0, 1); if ($plugin != '') { api_plugin_disable_all($plugin); cacti_log("ERRORS DETECTED - DISABLING PLUGIN '$plugin'"); admin_email(__('Cacti System Warning'), __('Cacti disabled plugin %s due to the following error: %s! See the Cacti logfile for more details.', $plugin, $error)); } break; case E_RECOVERABLE_ERROR: case E_USER_ERROR: cacti_log($error, false, 'ERROR'); cacti_debug_backtrace('PHP ERROR', false, true, 0, 1); break; case E_COMPILE_WARNING: case E_CORE_WARNING: case E_USER_WARNING: case E_WARNING: cacti_log($error, false, 'ERROR'); cacti_debug_backtrace('PHP ERROR WARNING', false, true, 0, 1); break; case E_NOTICE: case E_USER_NOTICE: cacti_log($error, false, 'ERROR'); cacti_debug_backtrace('PHP ERROR NOTICE', false, true, 0, 1); break; case E_STRICT: cacti_log($error, false, 'ERROR'); cacti_debug_backtrace('PHP ERROR STRICT', false, true, 0, 1); break; default: cacti_log($error, false, 'ERROR'); cacti_debug_backtrace('PHP ERROR', false, true, 0, 1); } return false; } function CactiShutdownHandler () { global $phperrors; $error = error_get_last(); if (IgnoreErrorHandler($error['message'])) { return true; } switch ($error['type']) { case E_ERROR: case E_CORE_ERROR: case E_COMPILE_ERROR: case E_CORE_WARNING: case E_COMPILE_WARNING: case E_PARSE: preg_match('/.*\/plugins\/([\w-]*)\/.*/', $error['file'], $output_array); $plugin = (isset($output_array[1]) ? $output_array[1] : '' ); $message = 'PHP ' . $phperrors[$error['type']] . ($plugin != '' ? " in Plugin '$plugin'" : '') . ': ' . $error['message'] . ' in file: ' . $error['file'] . ' on line: ' . $error['line']; cacti_log($message, false, 'ERROR'); cacti_debug_backtrace('PHP ERROR', false, true, 0, 1); if ($plugin != '') { api_plugin_disable_all($plugin); cacti_log("ERRORS DETECTED - DISABLING PLUGIN '$plugin'"); admin_email(__('Cacti System Warning'), __('Cacti disabled plugin %s due to the following error: %s! See the Cacti logfile for more details.', $plugin, $message)); } } } /** enable_device_debug - Enables device debug for a device * if it is disabled. * * @arg $host_id - the device id to search for * * @returns - void */ function enable_device_debug($host_id) { $device_debug = read_config_option('selective_device_debug', true); if ($device_debug != '') { $devices = explode(',', $device_debug); if (array_search($host_id, $devices) === false) { set_config_option('selective_device_debug', $device_debug . ',' . $host_id); } } else { set_config_option('selective_device_debug', $host_id); } } /** disable_device_debug - Disables device debug for a device * if it is enabled. * * @arg $host_id - the device id to search for * * @returns - void */ function disable_device_debug($host_id) { $device_debug = read_config_option('selective_device_debug', true); if ($device_debug != '') { $devices = explode(',', $device_debug); foreach($devices as $key => $device) { if ($device == $host_id) { unset($devices[$key]); break; } } set_config_option('selective_device_debug', implode(',', $devices)); } } /** is_device_debug_enabled - Determines if device debug is enabled * for a device. * * @arg $host_id - the device id to search for * * @returns - boolean true or false */ function is_device_debug_enabled($host_id) { $device_debug = read_config_option('selective_device_debug', true); if ($device_debug != '') { $devices = explode(',', $device_debug); if (array_search($host_id, $devices) !== false) { return true; } } return false; } /** get_url_type - Determines if remote communications are over * http or https for remote services. * * @returns - http or https */ function get_url_type() { if (read_config_option('force_https') == 'on') { return 'https'; } else { return 'http'; } } /** get_default_contextoption - Sets default context options for self-signed SSL * related protocols if necessary. Allows plugins to add additional header information * to fulfill system setup related requirements like the usage of Web Single Login * cookies for example. * * @returns - an array of stream context options or false */ function get_default_contextoption($timeout = '') { $fgc_contextoption = false; if ($timeout == '') { $timeout = read_config_option('remote_agent_timeout'); } if (!is_numeric($timeout)) { $timeout = 5; } $protocol = get_url_type(); if (in_array($protocol, array('ssl', 'https', 'ftps'))) { $fgc_contextoption = array( 'ssl' => array( 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true, ) ); } if ($protocol == 'https') { $fgc_contextoption['https'] = array( 'timeout' => $timeout, 'ignore_errors' => true ); } elseif ($protocol == 'http') { $fgc_contextoption['http'] = array( 'timeout' => $timeout, 'ignore_errors' => true ); } $fgc_contextoption = api_plugin_hook_function('fgc_contextoption', $fgc_contextoption); return $fgc_contextoption; } /** repair_system_data_input_methods - This utility will repair * system data input methods when they are detected on the system * * @returns - null */ function repair_system_data_input_methods($step = 'import') { $system_hashes = array( '3eb92bb845b9660a7445cf9740726522', // Get SNMP Data 'bf566c869ac6443b0c75d1c32b5a350e', // Get SNMP Data (Indexed) '80e9e4c4191a5da189ae26d0e237f015', // Get Script Data (Indexed) '332111d8b54ac8ce939af87a7eac0c06', // Get Script Server Data (Indexed) ); $good_field_hashes = array( '3eb92bb845b9660a7445cf9740726522' => array( // Get SNMP Data (1) '92f5906c8dc0f964b41f4253df582c38', // IP Address '012ccb1d3687d3edb29c002ea66e72da', // SNMP Version '32285d5bf16e56c478f5e83f32cda9ef', // SNMP Community 'fc64b99742ec417cc424dbf8c7692d36', // SNMP Port 'ad14ac90641aed388139f6ba86a2e48b', // SNMP Username '9c55a74bd571b4f00a96fd4b793278c6', // SNMP Password '20832ce12f099c8e54140793a091af90', // SNMP Authentication Protocol 'c60c9aac1e1b3555ea0620b8bbfd82cb', // SNMP Privacy Passphrase 'feda162701240101bc74148415ef415a', // SNMP Privacy Protocol '4276a5ec6e3fe33995129041b1909762' // SNMP OID ), 'bf566c869ac6443b0c75d1c32b5a350e' => array( // Get SNMP Data (Indexed) (2) '617cdc8a230615e59f06f361ef6e7728', // IP Address 'b5c23f246559df38662c255f4aa21d6b', // SNMP Version 'acb449d1451e8a2a655c2c99d31142c7', // SNMP Community 'c1f36ee60c3dc98945556d57f26e475b', // SNMP Port 'f4facc5e2ca7ebee621f09bc6d9fc792', // SNMP Username '1cc1493a6781af2c478fa4de971531cf', // SNMP Password '2cf7129ad3ff819a7a7ac189bee48ce8', // SNMP Authentication Protocol '6b13ac0a0194e171d241d4b06f913158', // SNMP Privacy Passphrase '3a33d4fc65b8329ab2ac46a36da26b72', // SNMP Privacy Protocol '6027a919c7c7731fbe095b6f53ab127b', // Index Type 'cbbe5c1ddfb264a6e5d509ce1c78c95f', // Index Value 'e6deda7be0f391399c5130e7c4a48b28' // Output Type ID ), '80e9e4c4191a5da189ae26d0e237f015' => array( // Get Script Data (Indexed) 11 'd39556ecad6166701bfb0e28c5a11108', // Index Type '3b7caa46eb809fc238de6ef18b6e10d5', // Index Value '74af2e42dc12956c4817c2ef5d9983f9', // Output Type ID '8ae57f09f787656bf4ac541e8bd12537' // Output Value ), '332111d8b54ac8ce939af87a7eac0c06' => array( // Get Script Server Data (Indexed) 12 '172b4b0eacee4948c6479f587b62e512', // Index Type '30fb5d5bcf3d66bb5abe88596f357c26', // Index Value '31112c85ae4ff821d3b288336288818c', // Output Type ID '5be8fa85472d89c621790b43510b5043' // Output Value ) ); foreach($good_field_hashes as $hash => $field_hashes) { $data_input_id = db_fetch_cell_prepared('SELECT id FROM data_input WHERE hash = ?', array($hash)); if (!empty($data_input_id)) { $bad_hashes = db_fetch_assoc_prepared('SELECT * FROM data_input_fields WHERE hash NOT IN ("' . implode('","', $field_hashes) . '") AND hash != "" AND data_input_id = ?', array($data_input_id)); if (cacti_sizeof($bad_hashes)) { cacti_log(strtoupper($step) . ' NOTE: Repairing ' . cacti_sizeof($bad_hashes) . ' Damaged data_input_fields', false); foreach($bad_hashes as $bhash) { $good_field_id = db_fetch_cell_prepared('SELECT id FROM data_input_fields WHERE hash != ? AND data_input_id = ? AND data_name = ?', array($bhash['hash'], $data_input_id, $bhash['data_name'])); if (!empty($good_field_id)) { cacti_log("Data Input ID $data_input_id Bad Field ID is " . $bhash['id'] . ", Good Field ID: " . $good_field_id, false, 'WEBUI', POLLER_VERBOSITY_DEVDBG); cacti_log('Executing Data Input Data Check', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG); // Data Input Data $bad_mappings = db_fetch_assoc_prepared('SELECT * FROM data_input_data WHERE data_input_field_id = ?', array($bhash['id'])); if (cacti_sizeof($bad_mappings)) { cacti_log(strtoupper($step) . ' NOTE: Found ' . cacti_sizeof($bad_mappings) . ' Damaged data_input_fields', false); foreach($bad_mappings as $mfid) { $good_found = db_fetch_cell_prepared('SELECT COUNT(*) FROM data_input_data WHERE data_input_field_id = ? AND data_template_data_id = ?', array($good_field_id, $mfid['data_template_data_id'])); if ($good_found > 0) { cacti_log('Good Found for ' . $mfid['data_input_field_id'] . ', Fixing', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG); db_execute_prepared('DELETE FROM data_input_data WHERE data_input_field_id = ? AND data_template_data_id = ?', array($mfid['data_input_field_id'], $mfid['data_template_data_id'])); } else { cacti_log('Good NOT Found for ' . $mfid['data_input_field_id'] . ', Fixing', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG); db_execute_prepared('UPDATE data_input_data SET data_input_field_id = ? WHERE data_input_field_id = ? AND data_template_data_id = ?', array($good_field_id, $mfid['data_input_field_id'], $mfid['data_template_data_id'])); } } } else { cacti_log('No Bad Data Input Data Records', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG); } // Data Template RRD cacti_log('Executing Data Template RRD Check', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);; $bad_mappings = db_fetch_assoc_prepared('SELECT * FROM data_template_rrd WHERE data_input_field_id = ?', array($bhash['id'])); if (cacti_sizeof($bad_mappings)) { cacti_log(strtoupper($step) . ' NOTE: Found ' . cacti_sizeof($bad_mappings) . ' Damaged data_template_rrd', false); foreach($bad_mappings as $mfid) { $good_found = db_fetch_cell_prepared('SELECT COUNT(*) FROM data_template_rrd WHERE data_input_field_id = ? AND id = ?', array($good_field_id, $mfid['id'])); if ($good_found > 0) { cacti_log('Good Found for ' . $mfid['data_input_field_id'] . ', Fixing', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG); db_execute_prepared('DELETE FROM data_template_rrd WHERE data_input_field_id = ? AND id = ?', array($mfid['data_input_field_id'], $mfid['id'])); } else { cacti_log('Good NOT Found for ' . $mfid['data_input_field_id'] . ', Fixing', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG); db_execute_prepared('UPDATE data_template_rrd SET data_input_field_id = ? WHERE data_input_field_id = ? AND id = ?', array($good_field_id, $mfid['data_input_field_id'], $mfid['id'])); } } } else { cacti_log('No Bad Data Template RRD Records', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG); } db_execute_prepared('DELETE FROM data_input_fields WHERE hash = ?', array($bhash['hash'])); } else { cacti_log('WARNING: Could not find Cacti default matching hash for unknown system hash "' . $bhash['hash'] . '" for ' . $data_input_id . '. No repair performed.'); } } } } else { cacti_log("Could not find hash '" . $hash . "' for Data Input", false, 'WEBUI', POLLER_VERBOSITY_DEVDBG); } } } if (isset($config['cacti_server_os']) && $config['cacti_server_os'] == 'win32' && !function_exists('posix_kill')) { function posix_kill($pid, $signal = SIGTERM) { $wmi = new COM("winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\cimv2"); $procs = $wmi->ExecQuery("SELECT ProcessId FROM Win32_Process WHERE ProcessId='" . $pid . "'"); if (cacti_sizeof($procs)) { if ($signal == SIGTERM) { foreach($procs as $proc) { $proc->Terminate(); } } else { return true; } } else { return false; } } } function is_ipaddress($ip_address = '') { /* check for ipv4/v6 */ if (function_exists('filter_var')) { if (filter_var($ip_address, FILTER_VALIDATE_IP) !== false) { return true; } else { return false; } } elseif (inet_pton($ip_address) !== false) { return true; } else { return false; } } /** date_time_format create a format string for date/time * @return string returns date time format */ function date_time_format() { $datechar = array( GDC_HYPHEN => '-', GDC_SLASH => '/', GDC_DOT => '.' ); /* setup date format */ $date_fmt = read_config_option('default_date_format'); $dateCharSetting = read_config_option('default_datechar'); if (!isset($datechar[$dateCharSetting])) { $dateCharSetting = GDC_SLASH; } $datecharacter = $datechar[$dateCharSetting]; switch ($date_fmt) { case GD_MO_D_Y: return 'm' . $datecharacter . 'd' . $datecharacter . 'Y H:i:s'; case GD_MN_D_Y: return 'M' . $datecharacter . 'd' . $datecharacter . 'Y H:i:s'; case GD_D_MO_Y: return 'd' . $datecharacter . 'm' . $datecharacter . 'Y H:i:s'; case GD_D_MN_Y: return 'd' . $datecharacter . 'M' . $datecharacter . 'Y H:i:s'; case GD_Y_MO_D: return 'Y' . $datecharacter . 'm' . $datecharacter . 'd H:i:s'; case GD_Y_MN_D: return 'Y' . $datecharacter . 'M' . $datecharacter . 'd H:i:s'; default: return 'Y' . $datecharacter . 'm' . $datecharacter . 'd H:i:s'; } } /** * get_cacti_version Generic function to get the cacti version */ function get_cacti_version() { static $version = ''; if ($version == '') { $version = trim(db_fetch_cell('SELECT cacti FROM version LIMIT 1')); } return $version; } /** * get_cacti_version_text Return the cacti version text including beta moniker */ function get_cacti_version_text($include_version = true) { if ($include_version) { return trim(__('Version %s %s', CACTI_VERSION, (defined('CACTI_VERSION_BETA') ? __('- Beta %s', CACTI_VERSION_BETA):''))); } else { return trim(__('%s %s', CACTI_VERSION, (defined('CACTI_VERSION_BETA') ? __('- Beta %s', CACTI_VERSION_BETA):''))); } } /** * get_cacti_cli_version() { */ function get_cacti_cli_version() { $dbversion = get_cacti_version(); $version = get_cacti_version_text(false); return $version . ' (DB: ' . $dbversion . ')'; } /** * cacti_version_compare - Compare Cacti version numbers */ function cacti_version_compare($version1, $version2, $operator = '>') { $length = max(cacti_sizeof(explode('.', $version1)), cacti_sizeof(explode('.', $version2))); $version1 = version_to_decimal($version1, $length); $version2 = version_to_decimal($version2, $length); switch ($operator) { case '<': if ($version1 < $version2) { return true; } break; case '<=': if ($version1 <= $version2) { return true; } break; case '>=': if ($version1 >= $version2) { return true; } break; case '>': if ($version1 > $version2) { return true; } break; case '==': if ($version1 == $version2) { return true; } break; default: return version_compare($version1, $version2, $operator); } return false; } /** * version_to_decimal - convert version string to decimal */ function version_to_decimal($version, $length = 1) { $newver = ''; $minor = ''; $parts = explode('.', $version); foreach($parts as $part) { if (is_numeric($part)) { $part = substr('00' . $part, -2); $newver .= $part; } else { $minor = substr($part, -1); $major = substr($part, 0, strlen($part)-1); $major = substr('00' . $major, -2); $newver .= $major; } } if (cacti_sizeof($parts) < $length) { $i = cacti_sizeof($parts); while($i < $length) { $newver .= '00'; $i++; } } if ($minor != '') { $int = ord($minor); } else { $int = 0; } return hexdec($newver) * 1000 + $int; } /** * cacti_gethostinfo - obtains the dns information for a host */ function cacti_gethostinfo($hostname, $type = DNS_ALL) { return dns_get_record($hostname, $type); } /** * cacti_gethostbyname - a ip/ipv6 replacement for php's gethostbyname function */ function cacti_gethostbyname($hostname, $type = '') { if ($type == '') { $type = DNS_A + DNS_AAAA; } if ($type != DNS_AAAA) { $host = gethostbyname($hostname); if ($host !== $hostname) { return $host; } } $return = cacti_gethostinfo($hostname, $type); if (cacti_sizeof($return)) { foreach($return as $record) { switch($record['type']) { case 'A': return $record['ip']; break; case 'AAAA': return $record['ipv6']; break; } } } return $hostname; } function get_nonsystem_data_input($data_input_id) { global $hash_system_data_inputs; $diid = db_fetch_cell_prepared('SELECT id FROM data_input WHERE hash NOT IN ("' . implode('","', $hash_system_data_inputs) . '") AND id = ?', array($data_input_id)); return $diid; } function get_rrdtool_version() { return str_replace('rrd-', '', str_replace('.x', '.0', read_config_option('rrdtool_version', true))); } function get_installed_rrdtool_version() { global $config; if ($config['cacti_server_os'] == 'win32') { $shell = shell_exec(cacti_escapeshellcmd(read_config_option('path_rrdtool')) . ' -v'); } else { $shell = shell_exec(cacti_escapeshellcmd(read_config_option('path_rrdtool')) . ' -v 2>&1'); } $version = false; if (preg_match('/^RRDtool ([0-9.]+) /', $shell, $matches)) { global $rrdtool_versions; foreach ($rrdtool_versions as $rrdtool_version => $rrdtool_version_text) { if (cacti_version_compare($rrdtool_version, $matches[1], '<=')) { $version = $rrdtool_version; } } } return $version; } function get_md5_hash($path) { $md5 = 0; if (db_table_exists('poller_resource_cache')) { $md5 = db_fetch_cell_prepared('SELECT md5sum FROM poller_resource_cache WHERE `path` = ?', array($path)); } if (empty($md5)) { if (file_exists($path)) { $md5 = md5_file($path); } else { $md5 = md5_file(dirname(__FILE__) . '/../' . $path); } } return $md5; } function get_md5_include_js($path) { global $config; if (file_exists($path)) { $npath = str_replace($config['base_path'] . '/', '', $path); } else { $npath = $path; } return '<script type=\'text/javascript\' src=\'' . $config['url_path'] . $npath . '?' . get_md5_hash($path) . '\'></script>' . PHP_EOL; } function get_md5_include_css($path) { global $config; return '<link href=\''. $config['url_path'] . $path . '?' . get_md5_hash($path) . '\' type=\'text/css\' rel=\'stylesheet\'>' . PHP_EOL; } function is_resource_writable($path) { if (empty($path)) { return false; } if ($path{strlen($path)-1}=='/') { return is_resource_writable($path.uniqid(mt_rand()).'.tmp'); } if (file_exists($path)) { if (($f = @fopen($path, 'a'))) { fclose($f); return true; } return false; } if (($f = @fopen($path, 'w'))) { fclose($f); unlink($path); return true; } return false; } function get_validated_theme($theme, $defaultTheme) { global $config; if (isset($theme) && strlen($theme)) { $themePath = $config['base_path'] . '/include/themes/' . $theme . '/main.css'; if (file_exists($themePath)) { return $theme; } } return $defaultTheme; } function get_validated_language($language, $defaultLanguage) { if (isset($language) && strlen($language)) { return $language; } return $defaultLanguage; } function get_running_user() { global $config; // Easy way first $user = get_current_user(); if ($user != '') { return $user; } $user = getenv('USERNAME') ?: getenv('USER'); if ($user != '') { return $user; } // Falback method if ($config['cacti_server_os'] == 'win32') { return getenv('username'); } else { $tmp_user = ''; $tmp_file = tempnam(sys_get_temp_dir(), 'uid'); $f_owner = ''; if (is_resource_writable($tmp_file)) { if (file_exists($tmp_file)) { unlink($tmp_file); } file_put_contents($tmp_file, 'cacti'); $f_owner = fileowner($tmp_file); $f_source = 'file'; if (file_exists($tmp_file)) { unlink($tmp_file); } } if (empty($f_owner) && function_exists('posix_getuid')) { $f_owner = posix_getuid(); $f_source = 'posix'; } if (!empty($f_owner) && function_exists('posix_getpwuid1')) { $f_array = posix_getpwuid($f_owner); if (isset($f_array['name'])) { $tmp_user = $f_array['name']; } } if (empty($tmp_user)) { exec('id -nu', $o, $r); if ($r == 0) { $tmp_user = trim($o['0']); } } /*** Code left here for future development, don't think it is right *** * if (empty($tmp_user) && !empty($f_owner) && is_readable('/etc/passwd')) { exec(sprintf('grep :%s: /etc/passwd | cut -d: -f1', (int) $uid), $o, $r); if ($r == 0) { $tmp_user = 'passwd-' . trim($o['0']); } } */ return (empty($tmp_user) ? 'apache' : $tmp_user); } } function get_debug_prefix() { $dateTime = new DateTime('NOW'); $dateTime = $dateTime->format('Y-m-d H:i:s.u'); return sprintf('<[ %s | %7d ]> -- ', $dateTime, getmypid()); } function get_client_addr($client_addr = false) { if (isset($_SERVER['X-Forwarded-For'])) { $client_addr = $_SERVER['X-Forwarded-For']; } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $client_addr = $_SERVER['HTTP_X_FORWARDED_FOR']; } elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) { $client_addr = $_SERVER['HTTP_FORWARDED_FOR']; } elseif (isset($_SERVER['HTTP_FORWARDED'])) { $client_addr = $_SERVER['HTTP_FORWARDED']; } elseif (isset($_SERVER['REMOTE_ADDR'])) { $client_addr = $_SERVER['REMOTE_ADDR']; } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { $client_addr = $_SERVER['HTTP_CLIENT_IP']; } return $client_addr; } function cacti_pton($ipaddr) { // Strip out the netmask, if there is one. $subnet_pos = strpos($ipaddr, '/'); if ($subnet_pos) { $subnet = substr($ipaddr, $subnet_pos+1); $ipaddr = substr($ipaddr, 0, $subnet_pos); } else { $subnet = null; // No netmask present } // Convert address to packed format $addr = @inet_pton($ipaddr); if ($addr === false) { return false; } // Maximum netmask length = same as packed address $len = 8*strlen($addr); if (!empty($subnet)) { if (!is_numeric($subnet)) { return false; } elseif ($subnet > $len) { return false; } } if (!is_numeric($subnet)){ $subnet=$len; } else { $subnet=(int)$subnet; } // Create a hex expression of the subnet mask $mask=str_repeat('f',$subnet>>2); switch($subnet&3) { case 3: $mask.='e'; break; case 2: $mask.='c'; break; case 1: $mask.='8'; break; } $mask=str_pad($mask,$len>>2,'0'); // Packed representation of netmask $mask=pack('H*',$mask); $result = array('ip' => $addr, 'subnet' => $mask); return $result; } function cacti_ntop($addr) { if (empty($addr)) { return false; } if (is_array($addr)) { foreach ($addr as $ip) { $addr = $ip; break; } } return @inet_ntop($addr); } function cacti_ntoc($subnet, $ipv6 = false) { $result = false; $count = 0; foreach(str_split($subnet) as $char) { $i = ord($char); while (($i & 128) == 128) { $count++; $i = ($i << 1) % 256; } } return $count; } function cacti_ptoa($title, $addr) { // Let's display it as hexadecimal format foreach(str_split($addr) as $char) { print str_pad(dechex(ord($char)),2,'0',STR_PAD_LEFT); } } function cacti_sizeof($array) { return ($array === false || !is_array($array)) ? 0 : sizeof($array); } function cacti_count($array) { return ($array === false || !is_array($array)) ? 0 : count($array); } function is_function_enabled($name) { return function_exists($name) && !in_array($name, array_map('trim', explode(', ', ini_get('disable_functions')))) && strtolower(ini_get('safe_mode')) != 1; } function is_page_ajax() { if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' ) { return true; } return false; } function raise_ajax_permission_denied() { if (is_page_ajax()) { header('HTTP/1.1 401 ' . __('Permission Denied')); print __('You are not permitted to access this section of Cacti.') . ' ' . __('If you feel that this is an error. Please contact your Cacti Administrator.'); exit; } }
null
145
CWE-787
CVE-2019-17542
/* * Westwood Studios VQA Video Decoder * Copyright (C) 2003 The FFmpeg project * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * VQA Video Decoder * @author Mike Melanson (melanson@pcisys.net) * @see http://wiki.multimedia.cx/index.php?title=VQA * * The VQA video decoder outputs PAL8 or RGB555 colorspace data, depending * on the type of data in the file. * * This decoder needs the 42-byte VQHD header from the beginning * of the VQA file passed through the extradata field. The VQHD header * is laid out as: * * bytes 0-3 chunk fourcc: 'VQHD' * bytes 4-7 chunk size in big-endian format, should be 0x0000002A * bytes 8-49 VQHD chunk data * * Bytes 8-49 are what this decoder expects to see. * * Briefly, VQA is a vector quantized animation format that operates in a * VGA palettized colorspace. It operates on pixel vectors (blocks) * of either 4x2 or 4x4 in size. Compressed VQA chunks can contain vector * codebooks, palette information, and code maps for rendering vectors onto * frames. Any of these components can also be compressed with a run-length * encoding (RLE) algorithm commonly referred to as "format80". * * VQA takes a novel approach to rate control. Each group of n frames * (usually, n = 8) relies on a different vector codebook. Rather than * transporting an entire codebook every 8th frame, the new codebook is * broken up into 8 pieces and sent along with the compressed video chunks * for each of the 8 frames preceding the 8 frames which require the * codebook. A full codebook is also sent on the very first frame of a * file. This is an interesting technique, although it makes random file * seeking difficult despite the fact that the frames are all intracoded. * * V1,2 VQA uses 12-bit codebook indexes. If the 12-bit indexes were * packed into bytes and then RLE compressed, bytewise, the results would * be poor. That is why the coding method divides each index into 2 parts, * the top 4 bits and the bottom 8 bits, then RL encodes the 4-bit pieces * together and the 8-bit pieces together. If most of the vectors are * clustered into one group of 256 vectors, most of the 4-bit index pieces * should be the same. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "libavutil/intreadwrite.h" #include "libavutil/imgutils.h" #include "avcodec.h" #include "bytestream.h" #include "internal.h" #define PALETTE_COUNT 256 #define VQA_HEADER_SIZE 0x2A /* allocate the maximum vector space, regardless of the file version: * (0xFF00 codebook vectors + 0x100 solid pixel vectors) * (4x4 pixels/block) */ #define MAX_CODEBOOK_VECTORS 0xFF00 #define SOLID_PIXEL_VECTORS 0x100 #define MAX_VECTORS (MAX_CODEBOOK_VECTORS + SOLID_PIXEL_VECTORS) #define MAX_CODEBOOK_SIZE (MAX_VECTORS * 4 * 4) #define CBF0_TAG MKBETAG('C', 'B', 'F', '0') #define CBFZ_TAG MKBETAG('C', 'B', 'F', 'Z') #define CBP0_TAG MKBETAG('C', 'B', 'P', '0') #define CBPZ_TAG MKBETAG('C', 'B', 'P', 'Z') #define CPL0_TAG MKBETAG('C', 'P', 'L', '0') #define CPLZ_TAG MKBETAG('C', 'P', 'L', 'Z') #define VPTZ_TAG MKBETAG('V', 'P', 'T', 'Z') typedef struct VqaContext { AVCodecContext *avctx; GetByteContext gb; uint32_t palette[PALETTE_COUNT]; int width; /* width of a frame */ int height; /* height of a frame */ int vector_width; /* width of individual vector */ int vector_height; /* height of individual vector */ int vqa_version; /* this should be either 1, 2 or 3 */ unsigned char *codebook; /* the current codebook */ int codebook_size; unsigned char *next_codebook_buffer; /* accumulator for next codebook */ int next_codebook_buffer_index; unsigned char *decode_buffer; int decode_buffer_size; /* number of frames to go before replacing codebook */ int partial_countdown; int partial_count; } VqaContext; static av_cold int vqa_decode_init(AVCodecContext *avctx) { VqaContext *s = avctx->priv_data; int i, j, codebook_index, ret; s->avctx = avctx; avctx->pix_fmt = AV_PIX_FMT_PAL8; /* make sure the extradata made it */ if (s->avctx->extradata_size != VQA_HEADER_SIZE) { av_log(s->avctx, AV_LOG_ERROR, "expected extradata size of %d\n", VQA_HEADER_SIZE); return AVERROR(EINVAL); } /* load up the VQA parameters from the header */ s->vqa_version = s->avctx->extradata[0]; switch (s->vqa_version) { case 1: case 2: break; case 3: avpriv_report_missing_feature(avctx, "VQA Version %d", s->vqa_version); return AVERROR_PATCHWELCOME; default: avpriv_request_sample(avctx, "VQA Version %i", s->vqa_version); return AVERROR_PATCHWELCOME; } s->width = AV_RL16(&s->avctx->extradata[6]); s->height = AV_RL16(&s->avctx->extradata[8]); if ((ret = av_image_check_size(s->width, s->height, 0, avctx)) < 0) { s->width= s->height= 0; return ret; } s->vector_width = s->avctx->extradata[10]; s->vector_height = s->avctx->extradata[11]; s->partial_count = s->partial_countdown = s->avctx->extradata[13]; /* the vector dimensions have to meet very stringent requirements */ if ((s->vector_width != 4) || ((s->vector_height != 2) && (s->vector_height != 4))) { /* return without further initialization */ return AVERROR_INVALIDDATA; } if (s->width % s->vector_width || s->height % s->vector_height) { av_log(avctx, AV_LOG_ERROR, "Image size not multiple of block size\n"); return AVERROR_INVALIDDATA; } /* allocate codebooks */ s->codebook_size = MAX_CODEBOOK_SIZE; s->codebook = av_malloc(s->codebook_size); if (!s->codebook) goto fail; s->next_codebook_buffer = av_malloc(s->codebook_size); if (!s->next_codebook_buffer) goto fail; /* allocate decode buffer */ s->decode_buffer_size = (s->width / s->vector_width) * (s->height / s->vector_height) * 2; s->decode_buffer = av_mallocz(s->decode_buffer_size); if (!s->decode_buffer) goto fail; /* initialize the solid-color vectors */ if (s->vector_height == 4) { codebook_index = 0xFF00 * 16; for (i = 0; i < 256; i++) for (j = 0; j < 16; j++) s->codebook[codebook_index++] = i; } else { codebook_index = 0xF00 * 8; for (i = 0; i < 256; i++) for (j = 0; j < 8; j++) s->codebook[codebook_index++] = i; } s->next_codebook_buffer_index = 0; return 0; fail: av_freep(&s->codebook); av_freep(&s->next_codebook_buffer); av_freep(&s->decode_buffer); return AVERROR(ENOMEM); } #define CHECK_COUNT() \ if (dest_index + count > dest_size) { \ av_log(s->avctx, AV_LOG_ERROR, "decode_format80 problem: next op would overflow dest_index\n"); \ av_log(s->avctx, AV_LOG_ERROR, "current dest_index = %d, count = %d, dest_size = %d\n", \ dest_index, count, dest_size); \ return AVERROR_INVALIDDATA; \ } #define CHECK_COPY(idx) \ if (idx < 0 || idx + count > dest_size) { \ av_log(s->avctx, AV_LOG_ERROR, "decode_format80 problem: next op would overflow dest_index\n"); \ av_log(s->avctx, AV_LOG_ERROR, "current src_pos = %d, count = %d, dest_size = %d\n", \ src_pos, count, dest_size); \ return AVERROR_INVALIDDATA; \ } static int decode_format80(VqaContext *s, int src_size, unsigned char *dest, int dest_size, int check_size) { int dest_index = 0; int count, opcode, start; int src_pos; unsigned char color; int i; if (src_size < 0 || src_size > bytestream2_get_bytes_left(&s->gb)) { av_log(s->avctx, AV_LOG_ERROR, "Chunk size %d is out of range\n", src_size); return AVERROR_INVALIDDATA; } start = bytestream2_tell(&s->gb); while (bytestream2_tell(&s->gb) - start < src_size) { opcode = bytestream2_get_byte(&s->gb); ff_tlog(s->avctx, "opcode %02X: ", opcode); /* 0x80 means that frame is finished */ if (opcode == 0x80) break; if (dest_index >= dest_size) { av_log(s->avctx, AV_LOG_ERROR, "decode_format80 problem: dest_index (%d) exceeded dest_size (%d)\n", dest_index, dest_size); return AVERROR_INVALIDDATA; } if (opcode == 0xFF) { count = bytestream2_get_le16(&s->gb); src_pos = bytestream2_get_le16(&s->gb); ff_tlog(s->avctx, "(1) copy %X bytes from absolute pos %X\n", count, src_pos); CHECK_COUNT(); CHECK_COPY(src_pos); for (i = 0; i < count; i++) dest[dest_index + i] = dest[src_pos + i]; dest_index += count; } else if (opcode == 0xFE) { count = bytestream2_get_le16(&s->gb); color = bytestream2_get_byte(&s->gb); ff_tlog(s->avctx, "(2) set %X bytes to %02X\n", count, color); CHECK_COUNT(); memset(&dest[dest_index], color, count); dest_index += count; } else if ((opcode & 0xC0) == 0xC0) { count = (opcode & 0x3F) + 3; src_pos = bytestream2_get_le16(&s->gb); ff_tlog(s->avctx, "(3) copy %X bytes from absolute pos %X\n", count, src_pos); CHECK_COUNT(); CHECK_COPY(src_pos); for (i = 0; i < count; i++) dest[dest_index + i] = dest[src_pos + i]; dest_index += count; } else if (opcode > 0x80) { count = opcode & 0x3F; ff_tlog(s->avctx, "(4) copy %X bytes from source to dest\n", count); CHECK_COUNT(); bytestream2_get_buffer(&s->gb, &dest[dest_index], count); dest_index += count; } else { count = ((opcode & 0x70) >> 4) + 3; src_pos = bytestream2_get_byte(&s->gb) | ((opcode & 0x0F) << 8); ff_tlog(s->avctx, "(5) copy %X bytes from relpos %X\n", count, src_pos); CHECK_COUNT(); CHECK_COPY(dest_index - src_pos); for (i = 0; i < count; i++) dest[dest_index + i] = dest[dest_index - src_pos + i]; dest_index += count; } } /* validate that the entire destination buffer was filled; this is * important for decoding frame maps since each vector needs to have a * codebook entry; it is not important for compressed codebooks because * not every entry needs to be filled */ if (check_size) if (dest_index < dest_size) { av_log(s->avctx, AV_LOG_ERROR, "decode_format80 problem: decode finished with dest_index (%d) < dest_size (%d)\n", dest_index, dest_size); memset(dest + dest_index, 0, dest_size - dest_index); } return 0; // let's display what we decoded anyway } static int vqa_decode_chunk(VqaContext *s, AVFrame *frame) { unsigned int chunk_type; unsigned int chunk_size; int byte_skip; unsigned int index = 0; int i; unsigned char r, g, b; int index_shift; int res; int cbf0_chunk = -1; int cbfz_chunk = -1; int cbp0_chunk = -1; int cbpz_chunk = -1; int cpl0_chunk = -1; int cplz_chunk = -1; int vptz_chunk = -1; int x, y; int lines = 0; int pixel_ptr; int vector_index = 0; int lobyte = 0; int hibyte = 0; int lobytes = 0; int hibytes = s->decode_buffer_size / 2; /* first, traverse through the frame and find the subchunks */ while (bytestream2_get_bytes_left(&s->gb) >= 8) { chunk_type = bytestream2_get_be32u(&s->gb); index = bytestream2_tell(&s->gb); chunk_size = bytestream2_get_be32u(&s->gb); switch (chunk_type) { case CBF0_TAG: cbf0_chunk = index; break; case CBFZ_TAG: cbfz_chunk = index; break; case CBP0_TAG: cbp0_chunk = index; break; case CBPZ_TAG: cbpz_chunk = index; break; case CPL0_TAG: cpl0_chunk = index; break; case CPLZ_TAG: cplz_chunk = index; break; case VPTZ_TAG: vptz_chunk = index; break; default: av_log(s->avctx, AV_LOG_ERROR, "Found unknown chunk type: %s (%08X)\n", av_fourcc2str(av_bswap32(chunk_type)), chunk_type); break; } byte_skip = chunk_size & 0x01; bytestream2_skip(&s->gb, chunk_size + byte_skip); } /* next, deal with the palette */ if ((cpl0_chunk != -1) && (cplz_chunk != -1)) { /* a chunk should not have both chunk types */ av_log(s->avctx, AV_LOG_ERROR, "problem: found both CPL0 and CPLZ chunks\n"); return AVERROR_INVALIDDATA; } /* decompress the palette chunk */ if (cplz_chunk != -1) { /* yet to be handled */ } /* convert the RGB palette into the machine's endian format */ if (cpl0_chunk != -1) { bytestream2_seek(&s->gb, cpl0_chunk, SEEK_SET); chunk_size = bytestream2_get_be32(&s->gb); /* sanity check the palette size */ if (chunk_size / 3 > 256 || chunk_size > bytestream2_get_bytes_left(&s->gb)) { av_log(s->avctx, AV_LOG_ERROR, "problem: found a palette chunk with %d colors\n", chunk_size / 3); return AVERROR_INVALIDDATA; } for (i = 0; i < chunk_size / 3; i++) { /* scale by 4 to transform 6-bit palette -> 8-bit */ r = bytestream2_get_byteu(&s->gb) * 4; g = bytestream2_get_byteu(&s->gb) * 4; b = bytestream2_get_byteu(&s->gb) * 4; s->palette[i] = 0xFFU << 24 | r << 16 | g << 8 | b; s->palette[i] |= s->palette[i] >> 6 & 0x30303; } } /* next, look for a full codebook */ if ((cbf0_chunk != -1) && (cbfz_chunk != -1)) { /* a chunk should not have both chunk types */ av_log(s->avctx, AV_LOG_ERROR, "problem: found both CBF0 and CBFZ chunks\n"); return AVERROR_INVALIDDATA; } /* decompress the full codebook chunk */ if (cbfz_chunk != -1) { bytestream2_seek(&s->gb, cbfz_chunk, SEEK_SET); chunk_size = bytestream2_get_be32(&s->gb); if ((res = decode_format80(s, chunk_size, s->codebook, s->codebook_size, 0)) < 0) return res; } /* copy a full codebook */ if (cbf0_chunk != -1) { bytestream2_seek(&s->gb, cbf0_chunk, SEEK_SET); chunk_size = bytestream2_get_be32(&s->gb); /* sanity check the full codebook size */ if (chunk_size > MAX_CODEBOOK_SIZE) { av_log(s->avctx, AV_LOG_ERROR, "problem: CBF0 chunk too large (0x%X bytes)\n", chunk_size); return AVERROR_INVALIDDATA; } bytestream2_get_buffer(&s->gb, s->codebook, chunk_size); } /* decode the frame */ if (vptz_chunk == -1) { /* something is wrong if there is no VPTZ chunk */ av_log(s->avctx, AV_LOG_ERROR, "problem: no VPTZ chunk found\n"); return AVERROR_INVALIDDATA; } bytestream2_seek(&s->gb, vptz_chunk, SEEK_SET); chunk_size = bytestream2_get_be32(&s->gb); if ((res = decode_format80(s, chunk_size, s->decode_buffer, s->decode_buffer_size, 1)) < 0) return res; /* render the final PAL8 frame */ if (s->vector_height == 4) index_shift = 4; else index_shift = 3; for (y = 0; y < s->height; y += s->vector_height) { for (x = 0; x < s->width; x += 4, lobytes++, hibytes++) { pixel_ptr = y * frame->linesize[0] + x; /* get the vector index, the method for which varies according to * VQA file version */ switch (s->vqa_version) { case 1: lobyte = s->decode_buffer[lobytes * 2]; hibyte = s->decode_buffer[(lobytes * 2) + 1]; vector_index = ((hibyte << 8) | lobyte) >> 3; vector_index <<= index_shift; lines = s->vector_height; /* uniform color fill - a quick hack */ if (hibyte == 0xFF) { while (lines--) { frame->data[0][pixel_ptr + 0] = 255 - lobyte; frame->data[0][pixel_ptr + 1] = 255 - lobyte; frame->data[0][pixel_ptr + 2] = 255 - lobyte; frame->data[0][pixel_ptr + 3] = 255 - lobyte; pixel_ptr += frame->linesize[0]; } lines=0; } break; case 2: lobyte = s->decode_buffer[lobytes]; hibyte = s->decode_buffer[hibytes]; vector_index = (hibyte << 8) | lobyte; vector_index <<= index_shift; lines = s->vector_height; break; case 3: /* not implemented yet */ lines = 0; break; } while (lines--) { frame->data[0][pixel_ptr + 0] = s->codebook[vector_index++]; frame->data[0][pixel_ptr + 1] = s->codebook[vector_index++]; frame->data[0][pixel_ptr + 2] = s->codebook[vector_index++]; frame->data[0][pixel_ptr + 3] = s->codebook[vector_index++]; pixel_ptr += frame->linesize[0]; } } } /* handle partial codebook */ if ((cbp0_chunk != -1) && (cbpz_chunk != -1)) { /* a chunk should not have both chunk types */ av_log(s->avctx, AV_LOG_ERROR, "problem: found both CBP0 and CBPZ chunks\n"); return AVERROR_INVALIDDATA; } if (cbp0_chunk != -1) { bytestream2_seek(&s->gb, cbp0_chunk, SEEK_SET); chunk_size = bytestream2_get_be32(&s->gb); if (chunk_size > MAX_CODEBOOK_SIZE - s->next_codebook_buffer_index) { av_log(s->avctx, AV_LOG_ERROR, "cbp0 chunk too large (%u bytes)\n", chunk_size); return AVERROR_INVALIDDATA; } /* accumulate partial codebook */ bytestream2_get_buffer(&s->gb, &s->next_codebook_buffer[s->next_codebook_buffer_index], chunk_size); s->next_codebook_buffer_index += chunk_size; s->partial_countdown--; if (s->partial_countdown <= 0) { /* time to replace codebook */ memcpy(s->codebook, s->next_codebook_buffer, s->next_codebook_buffer_index); /* reset accounting */ s->next_codebook_buffer_index = 0; s->partial_countdown = s->partial_count; } } if (cbpz_chunk != -1) { bytestream2_seek(&s->gb, cbpz_chunk, SEEK_SET); chunk_size = bytestream2_get_be32(&s->gb); if (chunk_size > MAX_CODEBOOK_SIZE - s->next_codebook_buffer_index) { av_log(s->avctx, AV_LOG_ERROR, "cbpz chunk too large (%u bytes)\n", chunk_size); return AVERROR_INVALIDDATA; } /* accumulate partial codebook */ bytestream2_get_buffer(&s->gb, &s->next_codebook_buffer[s->next_codebook_buffer_index], chunk_size); s->next_codebook_buffer_index += chunk_size; s->partial_countdown--; if (s->partial_countdown <= 0) { bytestream2_init(&s->gb, s->next_codebook_buffer, s->next_codebook_buffer_index); /* decompress codebook */ if ((res = decode_format80(s, s->next_codebook_buffer_index, s->codebook, s->codebook_size, 0)) < 0) return res; /* reset accounting */ s->next_codebook_buffer_index = 0; s->partial_countdown = s->partial_count; } } return 0; } static int vqa_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { VqaContext *s = avctx->priv_data; AVFrame *frame = data; int res; if ((res = ff_get_buffer(avctx, frame, 0)) < 0) return res; bytestream2_init(&s->gb, avpkt->data, avpkt->size); if ((res = vqa_decode_chunk(s, frame)) < 0) return res; /* make the palette available on the way out */ memcpy(frame->data[1], s->palette, PALETTE_COUNT * 4); frame->palette_has_changed = 1; *got_frame = 1; /* report that the buffer was completely consumed */ return avpkt->size; } static av_cold int vqa_decode_end(AVCodecContext *avctx) { VqaContext *s = avctx->priv_data; av_freep(&s->codebook); av_freep(&s->next_codebook_buffer); av_freep(&s->decode_buffer); return 0; } AVCodec ff_vqa_decoder = { .name = "vqavideo", .long_name = NULL_IF_CONFIG_SMALL("Westwood Studios VQA (Vector Quantized Animation) video"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_WS_VQA, .priv_data_size = sizeof(VqaContext), .init = vqa_decode_init, .close = vqa_decode_end, .decode = vqa_decode_frame, .capabilities = AV_CODEC_CAP_DR1, };
null
/* * Westwood Studios VQA Video Decoder * Copyright (C) 2003 The FFmpeg project * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * VQA Video Decoder * @author Mike Melanson (melanson@pcisys.net) * @see http://wiki.multimedia.cx/index.php?title=VQA * * The VQA video decoder outputs PAL8 or RGB555 colorspace data, depending * on the type of data in the file. * * This decoder needs the 42-byte VQHD header from the beginning * of the VQA file passed through the extradata field. The VQHD header * is laid out as: * * bytes 0-3 chunk fourcc: 'VQHD' * bytes 4-7 chunk size in big-endian format, should be 0x0000002A * bytes 8-49 VQHD chunk data * * Bytes 8-49 are what this decoder expects to see. * * Briefly, VQA is a vector quantized animation format that operates in a * VGA palettized colorspace. It operates on pixel vectors (blocks) * of either 4x2 or 4x4 in size. Compressed VQA chunks can contain vector * codebooks, palette information, and code maps for rendering vectors onto * frames. Any of these components can also be compressed with a run-length * encoding (RLE) algorithm commonly referred to as "format80". * * VQA takes a novel approach to rate control. Each group of n frames * (usually, n = 8) relies on a different vector codebook. Rather than * transporting an entire codebook every 8th frame, the new codebook is * broken up into 8 pieces and sent along with the compressed video chunks * for each of the 8 frames preceding the 8 frames which require the * codebook. A full codebook is also sent on the very first frame of a * file. This is an interesting technique, although it makes random file * seeking difficult despite the fact that the frames are all intracoded. * * V1,2 VQA uses 12-bit codebook indexes. If the 12-bit indexes were * packed into bytes and then RLE compressed, bytewise, the results would * be poor. That is why the coding method divides each index into 2 parts, * the top 4 bits and the bottom 8 bits, then RL encodes the 4-bit pieces * together and the 8-bit pieces together. If most of the vectors are * clustered into one group of 256 vectors, most of the 4-bit index pieces * should be the same. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "libavutil/intreadwrite.h" #include "libavutil/imgutils.h" #include "avcodec.h" #include "bytestream.h" #include "internal.h" #define PALETTE_COUNT 256 #define VQA_HEADER_SIZE 0x2A /* allocate the maximum vector space, regardless of the file version: * (0xFF00 codebook vectors + 0x100 solid pixel vectors) * (4x4 pixels/block) */ #define MAX_CODEBOOK_VECTORS 0xFF00 #define SOLID_PIXEL_VECTORS 0x100 #define MAX_VECTORS (MAX_CODEBOOK_VECTORS + SOLID_PIXEL_VECTORS) #define MAX_CODEBOOK_SIZE (MAX_VECTORS * 4 * 4) #define CBF0_TAG MKBETAG('C', 'B', 'F', '0') #define CBFZ_TAG MKBETAG('C', 'B', 'F', 'Z') #define CBP0_TAG MKBETAG('C', 'B', 'P', '0') #define CBPZ_TAG MKBETAG('C', 'B', 'P', 'Z') #define CPL0_TAG MKBETAG('C', 'P', 'L', '0') #define CPLZ_TAG MKBETAG('C', 'P', 'L', 'Z') #define VPTZ_TAG MKBETAG('V', 'P', 'T', 'Z') typedef struct VqaContext { AVCodecContext *avctx; GetByteContext gb; uint32_t palette[PALETTE_COUNT]; int width; /* width of a frame */ int height; /* height of a frame */ int vector_width; /* width of individual vector */ int vector_height; /* height of individual vector */ int vqa_version; /* this should be either 1, 2 or 3 */ unsigned char *codebook; /* the current codebook */ int codebook_size; unsigned char *next_codebook_buffer; /* accumulator for next codebook */ int next_codebook_buffer_index; unsigned char *decode_buffer; int decode_buffer_size; /* number of frames to go before replacing codebook */ int partial_countdown; int partial_count; } VqaContext; static av_cold int vqa_decode_init(AVCodecContext *avctx) { VqaContext *s = avctx->priv_data; int i, j, codebook_index, ret; s->avctx = avctx; avctx->pix_fmt = AV_PIX_FMT_PAL8; /* make sure the extradata made it */ if (s->avctx->extradata_size != VQA_HEADER_SIZE) { av_log(s->avctx, AV_LOG_ERROR, "expected extradata size of %d\n", VQA_HEADER_SIZE); return AVERROR(EINVAL); } /* load up the VQA parameters from the header */ s->vqa_version = s->avctx->extradata[0]; switch (s->vqa_version) { case 1: case 2: break; case 3: avpriv_report_missing_feature(avctx, "VQA Version %d", s->vqa_version); return AVERROR_PATCHWELCOME; default: avpriv_request_sample(avctx, "VQA Version %i", s->vqa_version); return AVERROR_PATCHWELCOME; } s->width = AV_RL16(&s->avctx->extradata[6]); s->height = AV_RL16(&s->avctx->extradata[8]); if ((ret = ff_set_dimensions(avctx, s->width, s->height)) < 0) { s->width= s->height= 0; return ret; } s->vector_width = s->avctx->extradata[10]; s->vector_height = s->avctx->extradata[11]; s->partial_count = s->partial_countdown = s->avctx->extradata[13]; /* the vector dimensions have to meet very stringent requirements */ if ((s->vector_width != 4) || ((s->vector_height != 2) && (s->vector_height != 4))) { /* return without further initialization */ return AVERROR_INVALIDDATA; } if (s->width % s->vector_width || s->height % s->vector_height) { av_log(avctx, AV_LOG_ERROR, "Image size not multiple of block size\n"); return AVERROR_INVALIDDATA; } /* allocate codebooks */ s->codebook_size = MAX_CODEBOOK_SIZE; s->codebook = av_malloc(s->codebook_size); if (!s->codebook) goto fail; s->next_codebook_buffer = av_malloc(s->codebook_size); if (!s->next_codebook_buffer) goto fail; /* allocate decode buffer */ s->decode_buffer_size = (s->width / s->vector_width) * (s->height / s->vector_height) * 2; s->decode_buffer = av_mallocz(s->decode_buffer_size); if (!s->decode_buffer) goto fail; /* initialize the solid-color vectors */ if (s->vector_height == 4) { codebook_index = 0xFF00 * 16; for (i = 0; i < 256; i++) for (j = 0; j < 16; j++) s->codebook[codebook_index++] = i; } else { codebook_index = 0xF00 * 8; for (i = 0; i < 256; i++) for (j = 0; j < 8; j++) s->codebook[codebook_index++] = i; } s->next_codebook_buffer_index = 0; return 0; fail: av_freep(&s->codebook); av_freep(&s->next_codebook_buffer); av_freep(&s->decode_buffer); return AVERROR(ENOMEM); } #define CHECK_COUNT() \ if (dest_index + count > dest_size) { \ av_log(s->avctx, AV_LOG_ERROR, "decode_format80 problem: next op would overflow dest_index\n"); \ av_log(s->avctx, AV_LOG_ERROR, "current dest_index = %d, count = %d, dest_size = %d\n", \ dest_index, count, dest_size); \ return AVERROR_INVALIDDATA; \ } #define CHECK_COPY(idx) \ if (idx < 0 || idx + count > dest_size) { \ av_log(s->avctx, AV_LOG_ERROR, "decode_format80 problem: next op would overflow dest_index\n"); \ av_log(s->avctx, AV_LOG_ERROR, "current src_pos = %d, count = %d, dest_size = %d\n", \ src_pos, count, dest_size); \ return AVERROR_INVALIDDATA; \ } static int decode_format80(VqaContext *s, int src_size, unsigned char *dest, int dest_size, int check_size) { int dest_index = 0; int count, opcode, start; int src_pos; unsigned char color; int i; if (src_size < 0 || src_size > bytestream2_get_bytes_left(&s->gb)) { av_log(s->avctx, AV_LOG_ERROR, "Chunk size %d is out of range\n", src_size); return AVERROR_INVALIDDATA; } start = bytestream2_tell(&s->gb); while (bytestream2_tell(&s->gb) - start < src_size) { opcode = bytestream2_get_byte(&s->gb); ff_tlog(s->avctx, "opcode %02X: ", opcode); /* 0x80 means that frame is finished */ if (opcode == 0x80) break; if (dest_index >= dest_size) { av_log(s->avctx, AV_LOG_ERROR, "decode_format80 problem: dest_index (%d) exceeded dest_size (%d)\n", dest_index, dest_size); return AVERROR_INVALIDDATA; } if (opcode == 0xFF) { count = bytestream2_get_le16(&s->gb); src_pos = bytestream2_get_le16(&s->gb); ff_tlog(s->avctx, "(1) copy %X bytes from absolute pos %X\n", count, src_pos); CHECK_COUNT(); CHECK_COPY(src_pos); for (i = 0; i < count; i++) dest[dest_index + i] = dest[src_pos + i]; dest_index += count; } else if (opcode == 0xFE) { count = bytestream2_get_le16(&s->gb); color = bytestream2_get_byte(&s->gb); ff_tlog(s->avctx, "(2) set %X bytes to %02X\n", count, color); CHECK_COUNT(); memset(&dest[dest_index], color, count); dest_index += count; } else if ((opcode & 0xC0) == 0xC0) { count = (opcode & 0x3F) + 3; src_pos = bytestream2_get_le16(&s->gb); ff_tlog(s->avctx, "(3) copy %X bytes from absolute pos %X\n", count, src_pos); CHECK_COUNT(); CHECK_COPY(src_pos); for (i = 0; i < count; i++) dest[dest_index + i] = dest[src_pos + i]; dest_index += count; } else if (opcode > 0x80) { count = opcode & 0x3F; ff_tlog(s->avctx, "(4) copy %X bytes from source to dest\n", count); CHECK_COUNT(); bytestream2_get_buffer(&s->gb, &dest[dest_index], count); dest_index += count; } else { count = ((opcode & 0x70) >> 4) + 3; src_pos = bytestream2_get_byte(&s->gb) | ((opcode & 0x0F) << 8); ff_tlog(s->avctx, "(5) copy %X bytes from relpos %X\n", count, src_pos); CHECK_COUNT(); CHECK_COPY(dest_index - src_pos); for (i = 0; i < count; i++) dest[dest_index + i] = dest[dest_index - src_pos + i]; dest_index += count; } } /* validate that the entire destination buffer was filled; this is * important for decoding frame maps since each vector needs to have a * codebook entry; it is not important for compressed codebooks because * not every entry needs to be filled */ if (check_size) if (dest_index < dest_size) { av_log(s->avctx, AV_LOG_ERROR, "decode_format80 problem: decode finished with dest_index (%d) < dest_size (%d)\n", dest_index, dest_size); memset(dest + dest_index, 0, dest_size - dest_index); } return 0; // let's display what we decoded anyway } static int vqa_decode_chunk(VqaContext *s, AVFrame *frame) { unsigned int chunk_type; unsigned int chunk_size; int byte_skip; unsigned int index = 0; int i; unsigned char r, g, b; int index_shift; int res; int cbf0_chunk = -1; int cbfz_chunk = -1; int cbp0_chunk = -1; int cbpz_chunk = -1; int cpl0_chunk = -1; int cplz_chunk = -1; int vptz_chunk = -1; int x, y; int lines = 0; int pixel_ptr; int vector_index = 0; int lobyte = 0; int hibyte = 0; int lobytes = 0; int hibytes = s->decode_buffer_size / 2; /* first, traverse through the frame and find the subchunks */ while (bytestream2_get_bytes_left(&s->gb) >= 8) { chunk_type = bytestream2_get_be32u(&s->gb); index = bytestream2_tell(&s->gb); chunk_size = bytestream2_get_be32u(&s->gb); switch (chunk_type) { case CBF0_TAG: cbf0_chunk = index; break; case CBFZ_TAG: cbfz_chunk = index; break; case CBP0_TAG: cbp0_chunk = index; break; case CBPZ_TAG: cbpz_chunk = index; break; case CPL0_TAG: cpl0_chunk = index; break; case CPLZ_TAG: cplz_chunk = index; break; case VPTZ_TAG: vptz_chunk = index; break; default: av_log(s->avctx, AV_LOG_ERROR, "Found unknown chunk type: %s (%08X)\n", av_fourcc2str(av_bswap32(chunk_type)), chunk_type); break; } byte_skip = chunk_size & 0x01; bytestream2_skip(&s->gb, chunk_size + byte_skip); } /* next, deal with the palette */ if ((cpl0_chunk != -1) && (cplz_chunk != -1)) { /* a chunk should not have both chunk types */ av_log(s->avctx, AV_LOG_ERROR, "problem: found both CPL0 and CPLZ chunks\n"); return AVERROR_INVALIDDATA; } /* decompress the palette chunk */ if (cplz_chunk != -1) { /* yet to be handled */ } /* convert the RGB palette into the machine's endian format */ if (cpl0_chunk != -1) { bytestream2_seek(&s->gb, cpl0_chunk, SEEK_SET); chunk_size = bytestream2_get_be32(&s->gb); /* sanity check the palette size */ if (chunk_size / 3 > 256 || chunk_size > bytestream2_get_bytes_left(&s->gb)) { av_log(s->avctx, AV_LOG_ERROR, "problem: found a palette chunk with %d colors\n", chunk_size / 3); return AVERROR_INVALIDDATA; } for (i = 0; i < chunk_size / 3; i++) { /* scale by 4 to transform 6-bit palette -> 8-bit */ r = bytestream2_get_byteu(&s->gb) * 4; g = bytestream2_get_byteu(&s->gb) * 4; b = bytestream2_get_byteu(&s->gb) * 4; s->palette[i] = 0xFFU << 24 | r << 16 | g << 8 | b; s->palette[i] |= s->palette[i] >> 6 & 0x30303; } } /* next, look for a full codebook */ if ((cbf0_chunk != -1) && (cbfz_chunk != -1)) { /* a chunk should not have both chunk types */ av_log(s->avctx, AV_LOG_ERROR, "problem: found both CBF0 and CBFZ chunks\n"); return AVERROR_INVALIDDATA; } /* decompress the full codebook chunk */ if (cbfz_chunk != -1) { bytestream2_seek(&s->gb, cbfz_chunk, SEEK_SET); chunk_size = bytestream2_get_be32(&s->gb); if ((res = decode_format80(s, chunk_size, s->codebook, s->codebook_size, 0)) < 0) return res; } /* copy a full codebook */ if (cbf0_chunk != -1) { bytestream2_seek(&s->gb, cbf0_chunk, SEEK_SET); chunk_size = bytestream2_get_be32(&s->gb); /* sanity check the full codebook size */ if (chunk_size > MAX_CODEBOOK_SIZE) { av_log(s->avctx, AV_LOG_ERROR, "problem: CBF0 chunk too large (0x%X bytes)\n", chunk_size); return AVERROR_INVALIDDATA; } bytestream2_get_buffer(&s->gb, s->codebook, chunk_size); } /* decode the frame */ if (vptz_chunk == -1) { /* something is wrong if there is no VPTZ chunk */ av_log(s->avctx, AV_LOG_ERROR, "problem: no VPTZ chunk found\n"); return AVERROR_INVALIDDATA; } bytestream2_seek(&s->gb, vptz_chunk, SEEK_SET); chunk_size = bytestream2_get_be32(&s->gb); if ((res = decode_format80(s, chunk_size, s->decode_buffer, s->decode_buffer_size, 1)) < 0) return res; /* render the final PAL8 frame */ if (s->vector_height == 4) index_shift = 4; else index_shift = 3; for (y = 0; y < s->height; y += s->vector_height) { for (x = 0; x < s->width; x += 4, lobytes++, hibytes++) { pixel_ptr = y * frame->linesize[0] + x; /* get the vector index, the method for which varies according to * VQA file version */ switch (s->vqa_version) { case 1: lobyte = s->decode_buffer[lobytes * 2]; hibyte = s->decode_buffer[(lobytes * 2) + 1]; vector_index = ((hibyte << 8) | lobyte) >> 3; vector_index <<= index_shift; lines = s->vector_height; /* uniform color fill - a quick hack */ if (hibyte == 0xFF) { while (lines--) { frame->data[0][pixel_ptr + 0] = 255 - lobyte; frame->data[0][pixel_ptr + 1] = 255 - lobyte; frame->data[0][pixel_ptr + 2] = 255 - lobyte; frame->data[0][pixel_ptr + 3] = 255 - lobyte; pixel_ptr += frame->linesize[0]; } lines=0; } break; case 2: lobyte = s->decode_buffer[lobytes]; hibyte = s->decode_buffer[hibytes]; vector_index = (hibyte << 8) | lobyte; vector_index <<= index_shift; lines = s->vector_height; break; case 3: /* not implemented yet */ lines = 0; break; } while (lines--) { frame->data[0][pixel_ptr + 0] = s->codebook[vector_index++]; frame->data[0][pixel_ptr + 1] = s->codebook[vector_index++]; frame->data[0][pixel_ptr + 2] = s->codebook[vector_index++]; frame->data[0][pixel_ptr + 3] = s->codebook[vector_index++]; pixel_ptr += frame->linesize[0]; } } } /* handle partial codebook */ if ((cbp0_chunk != -1) && (cbpz_chunk != -1)) { /* a chunk should not have both chunk types */ av_log(s->avctx, AV_LOG_ERROR, "problem: found both CBP0 and CBPZ chunks\n"); return AVERROR_INVALIDDATA; } if (cbp0_chunk != -1) { bytestream2_seek(&s->gb, cbp0_chunk, SEEK_SET); chunk_size = bytestream2_get_be32(&s->gb); if (chunk_size > MAX_CODEBOOK_SIZE - s->next_codebook_buffer_index) { av_log(s->avctx, AV_LOG_ERROR, "cbp0 chunk too large (%u bytes)\n", chunk_size); return AVERROR_INVALIDDATA; } /* accumulate partial codebook */ bytestream2_get_buffer(&s->gb, &s->next_codebook_buffer[s->next_codebook_buffer_index], chunk_size); s->next_codebook_buffer_index += chunk_size; s->partial_countdown--; if (s->partial_countdown <= 0) { /* time to replace codebook */ memcpy(s->codebook, s->next_codebook_buffer, s->next_codebook_buffer_index); /* reset accounting */ s->next_codebook_buffer_index = 0; s->partial_countdown = s->partial_count; } } if (cbpz_chunk != -1) { bytestream2_seek(&s->gb, cbpz_chunk, SEEK_SET); chunk_size = bytestream2_get_be32(&s->gb); if (chunk_size > MAX_CODEBOOK_SIZE - s->next_codebook_buffer_index) { av_log(s->avctx, AV_LOG_ERROR, "cbpz chunk too large (%u bytes)\n", chunk_size); return AVERROR_INVALIDDATA; } /* accumulate partial codebook */ bytestream2_get_buffer(&s->gb, &s->next_codebook_buffer[s->next_codebook_buffer_index], chunk_size); s->next_codebook_buffer_index += chunk_size; s->partial_countdown--; if (s->partial_countdown <= 0) { bytestream2_init(&s->gb, s->next_codebook_buffer, s->next_codebook_buffer_index); /* decompress codebook */ if ((res = decode_format80(s, s->next_codebook_buffer_index, s->codebook, s->codebook_size, 0)) < 0) return res; /* reset accounting */ s->next_codebook_buffer_index = 0; s->partial_countdown = s->partial_count; } } return 0; } static int vqa_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { VqaContext *s = avctx->priv_data; AVFrame *frame = data; int res; if ((res = ff_get_buffer(avctx, frame, 0)) < 0) return res; bytestream2_init(&s->gb, avpkt->data, avpkt->size); if ((res = vqa_decode_chunk(s, frame)) < 0) return res; /* make the palette available on the way out */ memcpy(frame->data[1], s->palette, PALETTE_COUNT * 4); frame->palette_has_changed = 1; *got_frame = 1; /* report that the buffer was completely consumed */ return avpkt->size; } static av_cold int vqa_decode_end(AVCodecContext *avctx) { VqaContext *s = avctx->priv_data; av_freep(&s->codebook); av_freep(&s->next_codebook_buffer); av_freep(&s->decode_buffer); return 0; } AVCodec ff_vqa_decoder = { .name = "vqavideo", .long_name = NULL_IF_CONFIG_SMALL("Westwood Studios VQA (Vector Quantized Animation) video"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_WS_VQA, .priv_data_size = sizeof(VqaContext), .init = vqa_decode_init, .close = vqa_decode_end, .decode = vqa_decode_frame, .capabilities = AV_CODEC_CAP_DR1, };
null
146
CWE-787
CVE-2019-17546
/* * Copyright (c) 1991-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library * * Read and return a packed RGBA image. */ #include "tiffiop.h" #include <stdio.h> static int gtTileContig(TIFFRGBAImage*, uint32*, uint32, uint32); static int gtTileSeparate(TIFFRGBAImage*, uint32*, uint32, uint32); static int gtStripContig(TIFFRGBAImage*, uint32*, uint32, uint32); static int gtStripSeparate(TIFFRGBAImage*, uint32*, uint32, uint32); static int PickContigCase(TIFFRGBAImage*); static int PickSeparateCase(TIFFRGBAImage*); static int BuildMapUaToAa(TIFFRGBAImage* img); static int BuildMapBitdepth16To8(TIFFRGBAImage* img); static const char photoTag[] = "PhotometricInterpretation"; /* * Helper constants used in Orientation tag handling */ #define FLIP_VERTICALLY 0x01 #define FLIP_HORIZONTALLY 0x02 /* * Color conversion constants. We will define display types here. */ static const TIFFDisplay display_sRGB = { { /* XYZ -> luminance matrix */ { 3.2410F, -1.5374F, -0.4986F }, { -0.9692F, 1.8760F, 0.0416F }, { 0.0556F, -0.2040F, 1.0570F } }, 100.0F, 100.0F, 100.0F, /* Light o/p for reference white */ 255, 255, 255, /* Pixel values for ref. white */ 1.0F, 1.0F, 1.0F, /* Residual light o/p for black pixel */ 2.4F, 2.4F, 2.4F, /* Gamma values for the three guns */ }; /* * Check the image to see if TIFFReadRGBAImage can deal with it. * 1/0 is returned according to whether or not the image can * be handled. If 0 is returned, emsg contains the reason * why it is being rejected. */ int TIFFRGBAImageOK(TIFF* tif, char emsg[1024]) { TIFFDirectory* td = &tif->tif_dir; uint16 photometric; int colorchannels; if (!tif->tif_decodestatus) { sprintf(emsg, "Sorry, requested compression method is not configured"); return (0); } switch (td->td_bitspersample) { case 1: case 2: case 4: case 8: case 16: break; default: sprintf(emsg, "Sorry, can not handle images with %d-bit samples", td->td_bitspersample); return (0); } if (td->td_sampleformat == SAMPLEFORMAT_IEEEFP) { sprintf(emsg, "Sorry, can not handle images with IEEE floating-point samples"); return (0); } colorchannels = td->td_samplesperpixel - td->td_extrasamples; if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometric)) { switch (colorchannels) { case 1: photometric = PHOTOMETRIC_MINISBLACK; break; case 3: photometric = PHOTOMETRIC_RGB; break; default: sprintf(emsg, "Missing needed %s tag", photoTag); return (0); } } switch (photometric) { case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: case PHOTOMETRIC_PALETTE: if (td->td_planarconfig == PLANARCONFIG_CONTIG && td->td_samplesperpixel != 1 && td->td_bitspersample < 8 ) { sprintf(emsg, "Sorry, can not handle contiguous data with %s=%d, " "and %s=%d and Bits/Sample=%d", photoTag, photometric, "Samples/pixel", td->td_samplesperpixel, td->td_bitspersample); return (0); } /* * We should likely validate that any extra samples are either * to be ignored, or are alpha, and if alpha we should try to use * them. But for now we won't bother with this. */ break; case PHOTOMETRIC_YCBCR: /* * TODO: if at all meaningful and useful, make more complete * support check here, or better still, refactor to let supporting * code decide whether there is support and what meaningful * error to return */ break; case PHOTOMETRIC_RGB: if (colorchannels < 3) { sprintf(emsg, "Sorry, can not handle RGB image with %s=%d", "Color channels", colorchannels); return (0); } break; case PHOTOMETRIC_SEPARATED: { uint16 inkset; TIFFGetFieldDefaulted(tif, TIFFTAG_INKSET, &inkset); if (inkset != INKSET_CMYK) { sprintf(emsg, "Sorry, can not handle separated image with %s=%d", "InkSet", inkset); return 0; } if (td->td_samplesperpixel < 4) { sprintf(emsg, "Sorry, can not handle separated image with %s=%d", "Samples/pixel", td->td_samplesperpixel); return 0; } break; } case PHOTOMETRIC_LOGL: if (td->td_compression != COMPRESSION_SGILOG) { sprintf(emsg, "Sorry, LogL data must have %s=%d", "Compression", COMPRESSION_SGILOG); return (0); } break; case PHOTOMETRIC_LOGLUV: if (td->td_compression != COMPRESSION_SGILOG && td->td_compression != COMPRESSION_SGILOG24) { sprintf(emsg, "Sorry, LogLuv data must have %s=%d or %d", "Compression", COMPRESSION_SGILOG, COMPRESSION_SGILOG24); return (0); } if (td->td_planarconfig != PLANARCONFIG_CONTIG) { sprintf(emsg, "Sorry, can not handle LogLuv images with %s=%d", "Planarconfiguration", td->td_planarconfig); return (0); } if ( td->td_samplesperpixel != 3 || colorchannels != 3 ) { sprintf(emsg, "Sorry, can not handle image with %s=%d, %s=%d", "Samples/pixel", td->td_samplesperpixel, "colorchannels", colorchannels); return 0; } break; case PHOTOMETRIC_CIELAB: if ( td->td_samplesperpixel != 3 || colorchannels != 3 || td->td_bitspersample != 8 ) { sprintf(emsg, "Sorry, can not handle image with %s=%d, %s=%d and %s=%d", "Samples/pixel", td->td_samplesperpixel, "colorchannels", colorchannels, "Bits/sample", td->td_bitspersample); return 0; } break; default: sprintf(emsg, "Sorry, can not handle image with %s=%d", photoTag, photometric); return (0); } return (1); } void TIFFRGBAImageEnd(TIFFRGBAImage* img) { if (img->Map) { _TIFFfree(img->Map); img->Map = NULL; } if (img->BWmap) { _TIFFfree(img->BWmap); img->BWmap = NULL; } if (img->PALmap) { _TIFFfree(img->PALmap); img->PALmap = NULL; } if (img->ycbcr) { _TIFFfree(img->ycbcr); img->ycbcr = NULL; } if (img->cielab) { _TIFFfree(img->cielab); img->cielab = NULL; } if (img->UaToAa) { _TIFFfree(img->UaToAa); img->UaToAa = NULL; } if (img->Bitdepth16To8) { _TIFFfree(img->Bitdepth16To8); img->Bitdepth16To8 = NULL; } if( img->redcmap ) { _TIFFfree( img->redcmap ); _TIFFfree( img->greencmap ); _TIFFfree( img->bluecmap ); img->redcmap = img->greencmap = img->bluecmap = NULL; } } static int isCCITTCompression(TIFF* tif) { uint16 compress; TIFFGetField(tif, TIFFTAG_COMPRESSION, &compress); return (compress == COMPRESSION_CCITTFAX3 || compress == COMPRESSION_CCITTFAX4 || compress == COMPRESSION_CCITTRLE || compress == COMPRESSION_CCITTRLEW); } int TIFFRGBAImageBegin(TIFFRGBAImage* img, TIFF* tif, int stop, char emsg[1024]) { uint16* sampleinfo; uint16 extrasamples; uint16 planarconfig; uint16 compress; int colorchannels; uint16 *red_orig, *green_orig, *blue_orig; int n_color; if( !TIFFRGBAImageOK(tif, emsg) ) return 0; /* Initialize to normal values */ img->row_offset = 0; img->col_offset = 0; img->redcmap = NULL; img->greencmap = NULL; img->bluecmap = NULL; img->Map = NULL; img->BWmap = NULL; img->PALmap = NULL; img->ycbcr = NULL; img->cielab = NULL; img->UaToAa = NULL; img->Bitdepth16To8 = NULL; img->req_orientation = ORIENTATION_BOTLEFT; /* It is the default */ img->tif = tif; img->stoponerr = stop; TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &img->bitspersample); switch (img->bitspersample) { case 1: case 2: case 4: case 8: case 16: break; default: sprintf(emsg, "Sorry, can not handle images with %d-bit samples", img->bitspersample); goto fail_return; } img->alpha = 0; TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &img->samplesperpixel); TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES, &extrasamples, &sampleinfo); if (extrasamples >= 1) { switch (sampleinfo[0]) { case EXTRASAMPLE_UNSPECIFIED: /* Workaround for some images without */ if (img->samplesperpixel > 3) /* correct info about alpha channel */ img->alpha = EXTRASAMPLE_ASSOCALPHA; break; case EXTRASAMPLE_ASSOCALPHA: /* data is pre-multiplied */ case EXTRASAMPLE_UNASSALPHA: /* data is not pre-multiplied */ img->alpha = sampleinfo[0]; break; } } #ifdef DEFAULT_EXTRASAMPLE_AS_ALPHA if( !TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &img->photometric)) img->photometric = PHOTOMETRIC_MINISWHITE; if( extrasamples == 0 && img->samplesperpixel == 4 && img->photometric == PHOTOMETRIC_RGB ) { img->alpha = EXTRASAMPLE_ASSOCALPHA; extrasamples = 1; } #endif colorchannels = img->samplesperpixel - extrasamples; TIFFGetFieldDefaulted(tif, TIFFTAG_COMPRESSION, &compress); TIFFGetFieldDefaulted(tif, TIFFTAG_PLANARCONFIG, &planarconfig); if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &img->photometric)) { switch (colorchannels) { case 1: if (isCCITTCompression(tif)) img->photometric = PHOTOMETRIC_MINISWHITE; else img->photometric = PHOTOMETRIC_MINISBLACK; break; case 3: img->photometric = PHOTOMETRIC_RGB; break; default: sprintf(emsg, "Missing needed %s tag", photoTag); goto fail_return; } } switch (img->photometric) { case PHOTOMETRIC_PALETTE: if (!TIFFGetField(tif, TIFFTAG_COLORMAP, &red_orig, &green_orig, &blue_orig)) { sprintf(emsg, "Missing required \"Colormap\" tag"); goto fail_return; } /* copy the colormaps so we can modify them */ n_color = (1U << img->bitspersample); img->redcmap = (uint16 *) _TIFFmalloc(sizeof(uint16)*n_color); img->greencmap = (uint16 *) _TIFFmalloc(sizeof(uint16)*n_color); img->bluecmap = (uint16 *) _TIFFmalloc(sizeof(uint16)*n_color); if( !img->redcmap || !img->greencmap || !img->bluecmap ) { sprintf(emsg, "Out of memory for colormap copy"); goto fail_return; } _TIFFmemcpy( img->redcmap, red_orig, n_color * 2 ); _TIFFmemcpy( img->greencmap, green_orig, n_color * 2 ); _TIFFmemcpy( img->bluecmap, blue_orig, n_color * 2 ); /* fall through... */ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: if (planarconfig == PLANARCONFIG_CONTIG && img->samplesperpixel != 1 && img->bitspersample < 8 ) { sprintf(emsg, "Sorry, can not handle contiguous data with %s=%d, " "and %s=%d and Bits/Sample=%d", photoTag, img->photometric, "Samples/pixel", img->samplesperpixel, img->bitspersample); goto fail_return; } break; case PHOTOMETRIC_YCBCR: /* It would probably be nice to have a reality check here. */ if (planarconfig == PLANARCONFIG_CONTIG) /* can rely on libjpeg to convert to RGB */ /* XXX should restore current state on exit */ switch (compress) { case COMPRESSION_JPEG: /* * TODO: when complete tests verify complete desubsampling * and YCbCr handling, remove use of TIFFTAG_JPEGCOLORMODE in * favor of tif_getimage.c native handling */ TIFFSetField(tif, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); img->photometric = PHOTOMETRIC_RGB; break; default: /* do nothing */; break; } /* * TODO: if at all meaningful and useful, make more complete * support check here, or better still, refactor to let supporting * code decide whether there is support and what meaningful * error to return */ break; case PHOTOMETRIC_RGB: if (colorchannels < 3) { sprintf(emsg, "Sorry, can not handle RGB image with %s=%d", "Color channels", colorchannels); goto fail_return; } break; case PHOTOMETRIC_SEPARATED: { uint16 inkset; TIFFGetFieldDefaulted(tif, TIFFTAG_INKSET, &inkset); if (inkset != INKSET_CMYK) { sprintf(emsg, "Sorry, can not handle separated image with %s=%d", "InkSet", inkset); goto fail_return; } if (img->samplesperpixel < 4) { sprintf(emsg, "Sorry, can not handle separated image with %s=%d", "Samples/pixel", img->samplesperpixel); goto fail_return; } } break; case PHOTOMETRIC_LOGL: if (compress != COMPRESSION_SGILOG) { sprintf(emsg, "Sorry, LogL data must have %s=%d", "Compression", COMPRESSION_SGILOG); goto fail_return; } TIFFSetField(tif, TIFFTAG_SGILOGDATAFMT, SGILOGDATAFMT_8BIT); img->photometric = PHOTOMETRIC_MINISBLACK; /* little white lie */ img->bitspersample = 8; break; case PHOTOMETRIC_LOGLUV: if (compress != COMPRESSION_SGILOG && compress != COMPRESSION_SGILOG24) { sprintf(emsg, "Sorry, LogLuv data must have %s=%d or %d", "Compression", COMPRESSION_SGILOG, COMPRESSION_SGILOG24); goto fail_return; } if (planarconfig != PLANARCONFIG_CONTIG) { sprintf(emsg, "Sorry, can not handle LogLuv images with %s=%d", "Planarconfiguration", planarconfig); return (0); } TIFFSetField(tif, TIFFTAG_SGILOGDATAFMT, SGILOGDATAFMT_8BIT); img->photometric = PHOTOMETRIC_RGB; /* little white lie */ img->bitspersample = 8; break; case PHOTOMETRIC_CIELAB: break; default: sprintf(emsg, "Sorry, can not handle image with %s=%d", photoTag, img->photometric); goto fail_return; } TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &img->width); TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &img->height); TIFFGetFieldDefaulted(tif, TIFFTAG_ORIENTATION, &img->orientation); img->isContig = !(planarconfig == PLANARCONFIG_SEPARATE && img->samplesperpixel > 1); if (img->isContig) { if (!PickContigCase(img)) { sprintf(emsg, "Sorry, can not handle image"); goto fail_return; } } else { if (!PickSeparateCase(img)) { sprintf(emsg, "Sorry, can not handle image"); goto fail_return; } } return 1; fail_return: TIFFRGBAImageEnd( img ); return 0; } int TIFFRGBAImageGet(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h) { if (img->get == NULL) { TIFFErrorExt(img->tif->tif_clientdata, TIFFFileName(img->tif), "No \"get\" routine setup"); return (0); } if (img->put.any == NULL) { TIFFErrorExt(img->tif->tif_clientdata, TIFFFileName(img->tif), "No \"put\" routine setupl; probably can not handle image format"); return (0); } return (*img->get)(img, raster, w, h); } /* * Read the specified image into an ABGR-format rastertaking in account * specified orientation. */ int TIFFReadRGBAImageOriented(TIFF* tif, uint32 rwidth, uint32 rheight, uint32* raster, int orientation, int stop) { char emsg[1024] = ""; TIFFRGBAImage img; int ok; if (TIFFRGBAImageOK(tif, emsg) && TIFFRGBAImageBegin(&img, tif, stop, emsg)) { img.req_orientation = (uint16)orientation; /* XXX verify rwidth and rheight against width and height */ ok = TIFFRGBAImageGet(&img, raster+(rheight-img.height)*rwidth, rwidth, img.height); TIFFRGBAImageEnd(&img); } else { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "%s", emsg); ok = 0; } return (ok); } /* * Read the specified image into an ABGR-format raster. Use bottom left * origin for raster by default. */ int TIFFReadRGBAImage(TIFF* tif, uint32 rwidth, uint32 rheight, uint32* raster, int stop) { return TIFFReadRGBAImageOriented(tif, rwidth, rheight, raster, ORIENTATION_BOTLEFT, stop); } static int setorientation(TIFFRGBAImage* img) { switch (img->orientation) { case ORIENTATION_TOPLEFT: case ORIENTATION_LEFTTOP: if (img->req_orientation == ORIENTATION_TOPRIGHT || img->req_orientation == ORIENTATION_RIGHTTOP) return FLIP_HORIZONTALLY; else if (img->req_orientation == ORIENTATION_BOTRIGHT || img->req_orientation == ORIENTATION_RIGHTBOT) return FLIP_HORIZONTALLY | FLIP_VERTICALLY; else if (img->req_orientation == ORIENTATION_BOTLEFT || img->req_orientation == ORIENTATION_LEFTBOT) return FLIP_VERTICALLY; else return 0; case ORIENTATION_TOPRIGHT: case ORIENTATION_RIGHTTOP: if (img->req_orientation == ORIENTATION_TOPLEFT || img->req_orientation == ORIENTATION_LEFTTOP) return FLIP_HORIZONTALLY; else if (img->req_orientation == ORIENTATION_BOTRIGHT || img->req_orientation == ORIENTATION_RIGHTBOT) return FLIP_VERTICALLY; else if (img->req_orientation == ORIENTATION_BOTLEFT || img->req_orientation == ORIENTATION_LEFTBOT) return FLIP_HORIZONTALLY | FLIP_VERTICALLY; else return 0; case ORIENTATION_BOTRIGHT: case ORIENTATION_RIGHTBOT: if (img->req_orientation == ORIENTATION_TOPLEFT || img->req_orientation == ORIENTATION_LEFTTOP) return FLIP_HORIZONTALLY | FLIP_VERTICALLY; else if (img->req_orientation == ORIENTATION_TOPRIGHT || img->req_orientation == ORIENTATION_RIGHTTOP) return FLIP_VERTICALLY; else if (img->req_orientation == ORIENTATION_BOTLEFT || img->req_orientation == ORIENTATION_LEFTBOT) return FLIP_HORIZONTALLY; else return 0; case ORIENTATION_BOTLEFT: case ORIENTATION_LEFTBOT: if (img->req_orientation == ORIENTATION_TOPLEFT || img->req_orientation == ORIENTATION_LEFTTOP) return FLIP_VERTICALLY; else if (img->req_orientation == ORIENTATION_TOPRIGHT || img->req_orientation == ORIENTATION_RIGHTTOP) return FLIP_HORIZONTALLY | FLIP_VERTICALLY; else if (img->req_orientation == ORIENTATION_BOTRIGHT || img->req_orientation == ORIENTATION_RIGHTBOT) return FLIP_HORIZONTALLY; else return 0; default: /* NOTREACHED */ return 0; } } /* * Get an tile-organized image that has * PlanarConfiguration contiguous if SamplesPerPixel > 1 * or * SamplesPerPixel == 1 */ static int gtTileContig(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h) { TIFF* tif = img->tif; tileContigRoutine put = img->put.contig; uint32 col, row, y, rowstoread; tmsize_t pos; uint32 tw, th; unsigned char* buf = NULL; int32 fromskew, toskew; uint32 nrow; int ret = 1, flip; uint32 this_tw, tocol; int32 this_toskew, leftmost_toskew; int32 leftmost_fromskew; uint32 leftmost_tw; tmsize_t bufsize; bufsize = TIFFTileSize(tif); if (bufsize == 0) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "%s", "No space for tile buffer"); return (0); } TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(tif, TIFFTAG_TILELENGTH, &th); flip = setorientation(img); if (flip & FLIP_VERTICALLY) { y = h - 1; toskew = -(int32)(tw + w); } else { y = 0; toskew = -(int32)(tw - w); } /* * Leftmost tile is clipped on left side if col_offset > 0. */ leftmost_fromskew = img->col_offset % tw; leftmost_tw = tw - leftmost_fromskew; leftmost_toskew = toskew + leftmost_fromskew; for (row = 0; ret != 0 && row < h; row += nrow) { rowstoread = th - (row + img->row_offset) % th; nrow = (row + rowstoread > h ? h - row : rowstoread); fromskew = leftmost_fromskew; this_tw = leftmost_tw; this_toskew = leftmost_toskew; tocol = 0; col = img->col_offset; while (tocol < w) { if (_TIFFReadTileAndAllocBuffer(tif, (void**) &buf, bufsize, col, row+img->row_offset, 0, 0)==(tmsize_t)(-1) && (buf == NULL || img->stoponerr)) { ret = 0; break; } pos = ((row+img->row_offset) % th) * TIFFTileRowSize(tif) + \ ((tmsize_t) fromskew * img->samplesperpixel); if (tocol + this_tw > w) { /* * Rightmost tile is clipped on right side. */ fromskew = tw - (w - tocol); this_tw = tw - fromskew; this_toskew = toskew + fromskew; } (*put)(img, raster+y*w+tocol, tocol, y, this_tw, nrow, fromskew, this_toskew, buf + pos); tocol += this_tw; col += this_tw; /* * After the leftmost tile, tiles are no longer clipped on left side. */ fromskew = 0; this_tw = tw; this_toskew = toskew; } y += ((flip & FLIP_VERTICALLY) ? -(int32) nrow : (int32) nrow); } _TIFFfree(buf); if (flip & FLIP_HORIZONTALLY) { uint32 line; for (line = 0; line < h; line++) { uint32 *left = raster + (line * w); uint32 *right = left + w - 1; while ( left < right ) { uint32 temp = *left; *left = *right; *right = temp; left++; right--; } } } return (ret); } /* * Get an tile-organized image that has * SamplesPerPixel > 1 * PlanarConfiguration separated * We assume that all such images are RGB. */ static int gtTileSeparate(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h) { TIFF* tif = img->tif; tileSeparateRoutine put = img->put.separate; uint32 col, row, y, rowstoread; tmsize_t pos; uint32 tw, th; unsigned char* buf = NULL; unsigned char* p0 = NULL; unsigned char* p1 = NULL; unsigned char* p2 = NULL; unsigned char* pa = NULL; tmsize_t tilesize; tmsize_t bufsize; int32 fromskew, toskew; int alpha = img->alpha; uint32 nrow; int ret = 1, flip; uint16 colorchannels; uint32 this_tw, tocol; int32 this_toskew, leftmost_toskew; int32 leftmost_fromskew; uint32 leftmost_tw; tilesize = TIFFTileSize(tif); bufsize = _TIFFMultiplySSize(tif, alpha?4:3,tilesize, "gtTileSeparate"); if (bufsize == 0) { return (0); } TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(tif, TIFFTAG_TILELENGTH, &th); flip = setorientation(img); if (flip & FLIP_VERTICALLY) { y = h - 1; toskew = -(int32)(tw + w); } else { y = 0; toskew = -(int32)(tw - w); } switch( img->photometric ) { case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: case PHOTOMETRIC_PALETTE: colorchannels = 1; break; default: colorchannels = 3; break; } /* * Leftmost tile is clipped on left side if col_offset > 0. */ leftmost_fromskew = img->col_offset % tw; leftmost_tw = tw - leftmost_fromskew; leftmost_toskew = toskew + leftmost_fromskew; for (row = 0; ret != 0 && row < h; row += nrow) { rowstoread = th - (row + img->row_offset) % th; nrow = (row + rowstoread > h ? h - row : rowstoread); fromskew = leftmost_fromskew; this_tw = leftmost_tw; this_toskew = leftmost_toskew; tocol = 0; col = img->col_offset; while (tocol < w) { if( buf == NULL ) { if (_TIFFReadTileAndAllocBuffer( tif, (void**) &buf, bufsize, col, row+img->row_offset,0,0)==(tmsize_t)(-1) && (buf == NULL || img->stoponerr)) { ret = 0; break; } p0 = buf; if( colorchannels == 1 ) { p2 = p1 = p0; pa = (alpha?(p0+3*tilesize):NULL); } else { p1 = p0 + tilesize; p2 = p1 + tilesize; pa = (alpha?(p2+tilesize):NULL); } } else if (TIFFReadTile(tif, p0, col, row+img->row_offset,0,0)==(tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } if (colorchannels > 1 && TIFFReadTile(tif, p1, col, row+img->row_offset,0,1) == (tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } if (colorchannels > 1 && TIFFReadTile(tif, p2, col, row+img->row_offset,0,2) == (tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } if (alpha && TIFFReadTile(tif,pa,col, row+img->row_offset,0,colorchannels) == (tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } pos = ((row+img->row_offset) % th) * TIFFTileRowSize(tif) + \ ((tmsize_t) fromskew * img->samplesperpixel); if (tocol + this_tw > w) { /* * Rightmost tile is clipped on right side. */ fromskew = tw - (w - tocol); this_tw = tw - fromskew; this_toskew = toskew + fromskew; } (*put)(img, raster+y*w+tocol, tocol, y, this_tw, nrow, fromskew, this_toskew, \ p0 + pos, p1 + pos, p2 + pos, (alpha?(pa+pos):NULL)); tocol += this_tw; col += this_tw; /* * After the leftmost tile, tiles are no longer clipped on left side. */ fromskew = 0; this_tw = tw; this_toskew = toskew; } y += ((flip & FLIP_VERTICALLY) ?-(int32) nrow : (int32) nrow); } if (flip & FLIP_HORIZONTALLY) { uint32 line; for (line = 0; line < h; line++) { uint32 *left = raster + (line * w); uint32 *right = left + w - 1; while ( left < right ) { uint32 temp = *left; *left = *right; *right = temp; left++; right--; } } } _TIFFfree(buf); return (ret); } /* * Get a strip-organized image that has * PlanarConfiguration contiguous if SamplesPerPixel > 1 * or * SamplesPerPixel == 1 */ static int gtStripContig(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h) { TIFF* tif = img->tif; tileContigRoutine put = img->put.contig; uint32 row, y, nrow, nrowsub, rowstoread; tmsize_t pos; unsigned char* buf = NULL; uint32 rowsperstrip; uint16 subsamplinghor,subsamplingver; uint32 imagewidth = img->width; tmsize_t scanline; int32 fromskew, toskew; int ret = 1, flip; tmsize_t maxstripsize; TIFFGetFieldDefaulted(tif, TIFFTAG_YCBCRSUBSAMPLING, &subsamplinghor, &subsamplingver); if( subsamplingver == 0 ) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "Invalid vertical YCbCr subsampling"); return (0); } maxstripsize = TIFFStripSize(tif); flip = setorientation(img); if (flip & FLIP_VERTICALLY) { y = h - 1; toskew = -(int32)(w + w); } else { y = 0; toskew = -(int32)(w - w); } TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); scanline = TIFFScanlineSize(tif); fromskew = (w < imagewidth ? imagewidth - w : 0); for (row = 0; row < h; row += nrow) { rowstoread = rowsperstrip - (row + img->row_offset) % rowsperstrip; nrow = (row + rowstoread > h ? h - row : rowstoread); nrowsub = nrow; if ((nrowsub%subsamplingver)!=0) nrowsub+=subsamplingver-nrowsub%subsamplingver; if (_TIFFReadEncodedStripAndAllocBuffer(tif, TIFFComputeStrip(tif,row+img->row_offset, 0), (void**)(&buf), maxstripsize, ((row + img->row_offset)%rowsperstrip + nrowsub) * scanline)==(tmsize_t)(-1) && (buf == NULL || img->stoponerr)) { ret = 0; break; } pos = ((row + img->row_offset) % rowsperstrip) * scanline + \ ((tmsize_t) img->col_offset * img->samplesperpixel); (*put)(img, raster+y*w, 0, y, w, nrow, fromskew, toskew, buf + pos); y += ((flip & FLIP_VERTICALLY) ? -(int32) nrow : (int32) nrow); } if (flip & FLIP_HORIZONTALLY) { uint32 line; for (line = 0; line < h; line++) { uint32 *left = raster + (line * w); uint32 *right = left + w - 1; while ( left < right ) { uint32 temp = *left; *left = *right; *right = temp; left++; right--; } } } _TIFFfree(buf); return (ret); } /* * Get a strip-organized image with * SamplesPerPixel > 1 * PlanarConfiguration separated * We assume that all such images are RGB. */ static int gtStripSeparate(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h) { TIFF* tif = img->tif; tileSeparateRoutine put = img->put.separate; unsigned char *buf = NULL; unsigned char *p0 = NULL, *p1 = NULL, *p2 = NULL, *pa = NULL; uint32 row, y, nrow, rowstoread; tmsize_t pos; tmsize_t scanline; uint32 rowsperstrip, offset_row; uint32 imagewidth = img->width; tmsize_t stripsize; tmsize_t bufsize; int32 fromskew, toskew; int alpha = img->alpha; int ret = 1, flip; uint16 colorchannels; stripsize = TIFFStripSize(tif); bufsize = _TIFFMultiplySSize(tif,alpha?4:3,stripsize, "gtStripSeparate"); if (bufsize == 0) { return (0); } flip = setorientation(img); if (flip & FLIP_VERTICALLY) { y = h - 1; toskew = -(int32)(w + w); } else { y = 0; toskew = -(int32)(w - w); } switch( img->photometric ) { case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: case PHOTOMETRIC_PALETTE: colorchannels = 1; break; default: colorchannels = 3; break; } TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); scanline = TIFFScanlineSize(tif); fromskew = (w < imagewidth ? imagewidth - w : 0); for (row = 0; row < h; row += nrow) { rowstoread = rowsperstrip - (row + img->row_offset) % rowsperstrip; nrow = (row + rowstoread > h ? h - row : rowstoread); offset_row = row + img->row_offset; if( buf == NULL ) { if (_TIFFReadEncodedStripAndAllocBuffer( tif, TIFFComputeStrip(tif, offset_row, 0), (void**) &buf, bufsize, ((row + img->row_offset)%rowsperstrip + nrow) * scanline)==(tmsize_t)(-1) && (buf == NULL || img->stoponerr)) { ret = 0; break; } p0 = buf; if( colorchannels == 1 ) { p2 = p1 = p0; pa = (alpha?(p0+3*stripsize):NULL); } else { p1 = p0 + stripsize; p2 = p1 + stripsize; pa = (alpha?(p2+stripsize):NULL); } } else if (TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, offset_row, 0), p0, ((row + img->row_offset)%rowsperstrip + nrow) * scanline)==(tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } if (colorchannels > 1 && TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, offset_row, 1), p1, ((row + img->row_offset)%rowsperstrip + nrow) * scanline) == (tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } if (colorchannels > 1 && TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, offset_row, 2), p2, ((row + img->row_offset)%rowsperstrip + nrow) * scanline) == (tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } if (alpha) { if (TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, offset_row, colorchannels), pa, ((row + img->row_offset)%rowsperstrip + nrow) * scanline)==(tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } } pos = ((row + img->row_offset) % rowsperstrip) * scanline + \ ((tmsize_t) img->col_offset * img->samplesperpixel); (*put)(img, raster+y*w, 0, y, w, nrow, fromskew, toskew, p0 + pos, p1 + pos, p2 + pos, (alpha?(pa+pos):NULL)); y += ((flip & FLIP_VERTICALLY) ? -(int32) nrow : (int32) nrow); } if (flip & FLIP_HORIZONTALLY) { uint32 line; for (line = 0; line < h; line++) { uint32 *left = raster + (line * w); uint32 *right = left + w - 1; while ( left < right ) { uint32 temp = *left; *left = *right; *right = temp; left++; right--; } } } _TIFFfree(buf); return (ret); } /* * The following routines move decoded data returned * from the TIFF library into rasters filled with packed * ABGR pixels (i.e. suitable for passing to lrecwrite.) * * The routines have been created according to the most * important cases and optimized. PickContigCase and * PickSeparateCase analyze the parameters and select * the appropriate "get" and "put" routine to use. */ #define REPEAT8(op) REPEAT4(op); REPEAT4(op) #define REPEAT4(op) REPEAT2(op); REPEAT2(op) #define REPEAT2(op) op; op #define CASE8(x,op) \ switch (x) { \ case 7: op; /*-fallthrough*/ \ case 6: op; /*-fallthrough*/ \ case 5: op; /*-fallthrough*/ \ case 4: op; /*-fallthrough*/ \ case 3: op; /*-fallthrough*/ \ case 2: op; /*-fallthrough*/ \ case 1: op; \ } #define CASE4(x,op) switch (x) { case 3: op; /*-fallthrough*/ case 2: op; /*-fallthrough*/ case 1: op; } #define NOP #define UNROLL8(w, op1, op2) { \ uint32 _x; \ for (_x = w; _x >= 8; _x -= 8) { \ op1; \ REPEAT8(op2); \ } \ if (_x > 0) { \ op1; \ CASE8(_x,op2); \ } \ } #define UNROLL4(w, op1, op2) { \ uint32 _x; \ for (_x = w; _x >= 4; _x -= 4) { \ op1; \ REPEAT4(op2); \ } \ if (_x > 0) { \ op1; \ CASE4(_x,op2); \ } \ } #define UNROLL2(w, op1, op2) { \ uint32 _x; \ for (_x = w; _x >= 2; _x -= 2) { \ op1; \ REPEAT2(op2); \ } \ if (_x) { \ op1; \ op2; \ } \ } #define SKEW(r,g,b,skew) { r += skew; g += skew; b += skew; } #define SKEW4(r,g,b,a,skew) { r += skew; g += skew; b += skew; a+= skew; } #define A1 (((uint32)0xffL)<<24) #define PACK(r,g,b) \ ((uint32)(r)|((uint32)(g)<<8)|((uint32)(b)<<16)|A1) #define PACK4(r,g,b,a) \ ((uint32)(r)|((uint32)(g)<<8)|((uint32)(b)<<16)|((uint32)(a)<<24)) #define W2B(v) (((v)>>8)&0xff) /* TODO: PACKW should have be made redundant in favor of Bitdepth16To8 LUT */ #define PACKW(r,g,b) \ ((uint32)W2B(r)|((uint32)W2B(g)<<8)|((uint32)W2B(b)<<16)|A1) #define PACKW4(r,g,b,a) \ ((uint32)W2B(r)|((uint32)W2B(g)<<8)|((uint32)W2B(b)<<16)|((uint32)W2B(a)<<24)) #define DECLAREContigPutFunc(name) \ static void name(\ TIFFRGBAImage* img, \ uint32* cp, \ uint32 x, uint32 y, \ uint32 w, uint32 h, \ int32 fromskew, int32 toskew, \ unsigned char* pp \ ) /* * 8-bit palette => colormap/RGB */ DECLAREContigPutFunc(put8bitcmaptile) { uint32** PALmap = img->PALmap; int samplesperpixel = img->samplesperpixel; (void) y; for( ; h > 0; --h) { for (x = w; x > 0; --x) { *cp++ = PALmap[*pp][0]; pp += samplesperpixel; } cp += toskew; pp += fromskew; } } /* * 4-bit palette => colormap/RGB */ DECLAREContigPutFunc(put4bitcmaptile) { uint32** PALmap = img->PALmap; (void) x; (void) y; fromskew /= 2; for( ; h > 0; --h) { uint32* bw; UNROLL2(w, bw = PALmap[*pp++], *cp++ = *bw++); cp += toskew; pp += fromskew; } } /* * 2-bit palette => colormap/RGB */ DECLAREContigPutFunc(put2bitcmaptile) { uint32** PALmap = img->PALmap; (void) x; (void) y; fromskew /= 4; for( ; h > 0; --h) { uint32* bw; UNROLL4(w, bw = PALmap[*pp++], *cp++ = *bw++); cp += toskew; pp += fromskew; } } /* * 1-bit palette => colormap/RGB */ DECLAREContigPutFunc(put1bitcmaptile) { uint32** PALmap = img->PALmap; (void) x; (void) y; fromskew /= 8; for( ; h > 0; --h) { uint32* bw; UNROLL8(w, bw = PALmap[*pp++], *cp++ = *bw++); cp += toskew; pp += fromskew; } } /* * 8-bit greyscale => colormap/RGB */ DECLAREContigPutFunc(putgreytile) { int samplesperpixel = img->samplesperpixel; uint32** BWmap = img->BWmap; (void) y; for( ; h > 0; --h) { for (x = w; x > 0; --x) { *cp++ = BWmap[*pp][0]; pp += samplesperpixel; } cp += toskew; pp += fromskew; } } /* * 8-bit greyscale with associated alpha => colormap/RGBA */ DECLAREContigPutFunc(putagreytile) { int samplesperpixel = img->samplesperpixel; uint32** BWmap = img->BWmap; (void) y; for( ; h > 0; --h) { for (x = w; x > 0; --x) { *cp++ = BWmap[*pp][0] & ((uint32)*(pp+1) << 24 | ~A1); pp += samplesperpixel; } cp += toskew; pp += fromskew; } } /* * 16-bit greyscale => colormap/RGB */ DECLAREContigPutFunc(put16bitbwtile) { int samplesperpixel = img->samplesperpixel; uint32** BWmap = img->BWmap; (void) y; for( ; h > 0; --h) { uint16 *wp = (uint16 *) pp; for (x = w; x > 0; --x) { /* use high order byte of 16bit value */ *cp++ = BWmap[*wp >> 8][0]; pp += 2 * samplesperpixel; wp += samplesperpixel; } cp += toskew; pp += fromskew; } } /* * 1-bit bilevel => colormap/RGB */ DECLAREContigPutFunc(put1bitbwtile) { uint32** BWmap = img->BWmap; (void) x; (void) y; fromskew /= 8; for( ; h > 0; --h) { uint32* bw; UNROLL8(w, bw = BWmap[*pp++], *cp++ = *bw++); cp += toskew; pp += fromskew; } } /* * 2-bit greyscale => colormap/RGB */ DECLAREContigPutFunc(put2bitbwtile) { uint32** BWmap = img->BWmap; (void) x; (void) y; fromskew /= 4; for( ; h > 0; --h) { uint32* bw; UNROLL4(w, bw = BWmap[*pp++], *cp++ = *bw++); cp += toskew; pp += fromskew; } } /* * 4-bit greyscale => colormap/RGB */ DECLAREContigPutFunc(put4bitbwtile) { uint32** BWmap = img->BWmap; (void) x; (void) y; fromskew /= 2; for( ; h > 0; --h) { uint32* bw; UNROLL2(w, bw = BWmap[*pp++], *cp++ = *bw++); cp += toskew; pp += fromskew; } } /* * 8-bit packed samples, no Map => RGB */ DECLAREContigPutFunc(putRGBcontig8bittile) { int samplesperpixel = img->samplesperpixel; (void) x; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { UNROLL8(w, NOP, *cp++ = PACK(pp[0], pp[1], pp[2]); pp += samplesperpixel); cp += toskew; pp += fromskew; } } /* * 8-bit packed samples => RGBA w/ associated alpha * (known to have Map == NULL) */ DECLAREContigPutFunc(putRGBAAcontig8bittile) { int samplesperpixel = img->samplesperpixel; (void) x; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { UNROLL8(w, NOP, *cp++ = PACK4(pp[0], pp[1], pp[2], pp[3]); pp += samplesperpixel); cp += toskew; pp += fromskew; } } /* * 8-bit packed samples => RGBA w/ unassociated alpha * (known to have Map == NULL) */ DECLAREContigPutFunc(putRGBUAcontig8bittile) { int samplesperpixel = img->samplesperpixel; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { uint32 r, g, b, a; uint8* m; for (x = w; x > 0; --x) { a = pp[3]; m = img->UaToAa+((size_t) a<<8); r = m[pp[0]]; g = m[pp[1]]; b = m[pp[2]]; *cp++ = PACK4(r,g,b,a); pp += samplesperpixel; } cp += toskew; pp += fromskew; } } /* * 16-bit packed samples => RGB */ DECLAREContigPutFunc(putRGBcontig16bittile) { int samplesperpixel = img->samplesperpixel; uint16 *wp = (uint16 *)pp; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { for (x = w; x > 0; --x) { *cp++ = PACK(img->Bitdepth16To8[wp[0]], img->Bitdepth16To8[wp[1]], img->Bitdepth16To8[wp[2]]); wp += samplesperpixel; } cp += toskew; wp += fromskew; } } /* * 16-bit packed samples => RGBA w/ associated alpha * (known to have Map == NULL) */ DECLAREContigPutFunc(putRGBAAcontig16bittile) { int samplesperpixel = img->samplesperpixel; uint16 *wp = (uint16 *)pp; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { for (x = w; x > 0; --x) { *cp++ = PACK4(img->Bitdepth16To8[wp[0]], img->Bitdepth16To8[wp[1]], img->Bitdepth16To8[wp[2]], img->Bitdepth16To8[wp[3]]); wp += samplesperpixel; } cp += toskew; wp += fromskew; } } /* * 16-bit packed samples => RGBA w/ unassociated alpha * (known to have Map == NULL) */ DECLAREContigPutFunc(putRGBUAcontig16bittile) { int samplesperpixel = img->samplesperpixel; uint16 *wp = (uint16 *)pp; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { uint32 r,g,b,a; uint8* m; for (x = w; x > 0; --x) { a = img->Bitdepth16To8[wp[3]]; m = img->UaToAa+((size_t) a<<8); r = m[img->Bitdepth16To8[wp[0]]]; g = m[img->Bitdepth16To8[wp[1]]]; b = m[img->Bitdepth16To8[wp[2]]]; *cp++ = PACK4(r,g,b,a); wp += samplesperpixel; } cp += toskew; wp += fromskew; } } /* * 8-bit packed CMYK samples w/o Map => RGB * * NB: The conversion of CMYK->RGB is *very* crude. */ DECLAREContigPutFunc(putRGBcontig8bitCMYKtile) { int samplesperpixel = img->samplesperpixel; uint16 r, g, b, k; (void) x; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { UNROLL8(w, NOP, k = 255 - pp[3]; r = (k*(255-pp[0]))/255; g = (k*(255-pp[1]))/255; b = (k*(255-pp[2]))/255; *cp++ = PACK(r, g, b); pp += samplesperpixel); cp += toskew; pp += fromskew; } } /* * 8-bit packed CMYK samples w/Map => RGB * * NB: The conversion of CMYK->RGB is *very* crude. */ DECLAREContigPutFunc(putRGBcontig8bitCMYKMaptile) { int samplesperpixel = img->samplesperpixel; TIFFRGBValue* Map = img->Map; uint16 r, g, b, k; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { for (x = w; x > 0; --x) { k = 255 - pp[3]; r = (k*(255-pp[0]))/255; g = (k*(255-pp[1]))/255; b = (k*(255-pp[2]))/255; *cp++ = PACK(Map[r], Map[g], Map[b]); pp += samplesperpixel; } pp += fromskew; cp += toskew; } } #define DECLARESepPutFunc(name) \ static void name(\ TIFFRGBAImage* img,\ uint32* cp,\ uint32 x, uint32 y, \ uint32 w, uint32 h,\ int32 fromskew, int32 toskew,\ unsigned char* r, unsigned char* g, unsigned char* b, unsigned char* a\ ) /* * 8-bit unpacked samples => RGB */ DECLARESepPutFunc(putRGBseparate8bittile) { (void) img; (void) x; (void) y; (void) a; for( ; h > 0; --h) { UNROLL8(w, NOP, *cp++ = PACK(*r++, *g++, *b++)); SKEW(r, g, b, fromskew); cp += toskew; } } /* * 8-bit unpacked samples => RGBA w/ associated alpha */ DECLARESepPutFunc(putRGBAAseparate8bittile) { (void) img; (void) x; (void) y; for( ; h > 0; --h) { UNROLL8(w, NOP, *cp++ = PACK4(*r++, *g++, *b++, *a++)); SKEW4(r, g, b, a, fromskew); cp += toskew; } } /* * 8-bit unpacked CMYK samples => RGBA */ DECLARESepPutFunc(putCMYKseparate8bittile) { (void) img; (void) y; for( ; h > 0; --h) { uint32 rv, gv, bv, kv; for (x = w; x > 0; --x) { kv = 255 - *a++; rv = (kv*(255-*r++))/255; gv = (kv*(255-*g++))/255; bv = (kv*(255-*b++))/255; *cp++ = PACK4(rv,gv,bv,255); } SKEW4(r, g, b, a, fromskew); cp += toskew; } } /* * 8-bit unpacked samples => RGBA w/ unassociated alpha */ DECLARESepPutFunc(putRGBUAseparate8bittile) { (void) img; (void) y; for( ; h > 0; --h) { uint32 rv, gv, bv, av; uint8* m; for (x = w; x > 0; --x) { av = *a++; m = img->UaToAa+((size_t) av<<8); rv = m[*r++]; gv = m[*g++]; bv = m[*b++]; *cp++ = PACK4(rv,gv,bv,av); } SKEW4(r, g, b, a, fromskew); cp += toskew; } } /* * 16-bit unpacked samples => RGB */ DECLARESepPutFunc(putRGBseparate16bittile) { uint16 *wr = (uint16*) r; uint16 *wg = (uint16*) g; uint16 *wb = (uint16*) b; (void) img; (void) y; (void) a; for( ; h > 0; --h) { for (x = 0; x < w; x++) *cp++ = PACK(img->Bitdepth16To8[*wr++], img->Bitdepth16To8[*wg++], img->Bitdepth16To8[*wb++]); SKEW(wr, wg, wb, fromskew); cp += toskew; } } /* * 16-bit unpacked samples => RGBA w/ associated alpha */ DECLARESepPutFunc(putRGBAAseparate16bittile) { uint16 *wr = (uint16*) r; uint16 *wg = (uint16*) g; uint16 *wb = (uint16*) b; uint16 *wa = (uint16*) a; (void) img; (void) y; for( ; h > 0; --h) { for (x = 0; x < w; x++) *cp++ = PACK4(img->Bitdepth16To8[*wr++], img->Bitdepth16To8[*wg++], img->Bitdepth16To8[*wb++], img->Bitdepth16To8[*wa++]); SKEW4(wr, wg, wb, wa, fromskew); cp += toskew; } } /* * 16-bit unpacked samples => RGBA w/ unassociated alpha */ DECLARESepPutFunc(putRGBUAseparate16bittile) { uint16 *wr = (uint16*) r; uint16 *wg = (uint16*) g; uint16 *wb = (uint16*) b; uint16 *wa = (uint16*) a; (void) img; (void) y; for( ; h > 0; --h) { uint32 r2,g2,b2,a2; uint8* m; for (x = w; x > 0; --x) { a2 = img->Bitdepth16To8[*wa++]; m = img->UaToAa+((size_t) a2<<8); r2 = m[img->Bitdepth16To8[*wr++]]; g2 = m[img->Bitdepth16To8[*wg++]]; b2 = m[img->Bitdepth16To8[*wb++]]; *cp++ = PACK4(r2,g2,b2,a2); } SKEW4(wr, wg, wb, wa, fromskew); cp += toskew; } } /* * 8-bit packed CIE L*a*b 1976 samples => RGB */ DECLAREContigPutFunc(putcontig8bitCIELab) { float X, Y, Z; uint32 r, g, b; (void) y; fromskew *= 3; for( ; h > 0; --h) { for (x = w; x > 0; --x) { TIFFCIELabToXYZ(img->cielab, (unsigned char)pp[0], (signed char)pp[1], (signed char)pp[2], &X, &Y, &Z); TIFFXYZToRGB(img->cielab, X, Y, Z, &r, &g, &b); *cp++ = PACK(r, g, b); pp += 3; } cp += toskew; pp += fromskew; } } /* * YCbCr -> RGB conversion and packing routines. */ #define YCbCrtoRGB(dst, Y) { \ uint32 r, g, b; \ TIFFYCbCrtoRGB(img->ycbcr, (Y), Cb, Cr, &r, &g, &b); \ dst = PACK(r, g, b); \ } /* * 8-bit packed YCbCr samples => RGB * This function is generic for different sampling sizes, * and can handle blocks sizes that aren't multiples of the * sampling size. However, it is substantially less optimized * than the specific sampling cases. It is used as a fallback * for difficult blocks. */ #ifdef notdef static void putcontig8bitYCbCrGenericTile( TIFFRGBAImage* img, uint32* cp, uint32 x, uint32 y, uint32 w, uint32 h, int32 fromskew, int32 toskew, unsigned char* pp, int h_group, int v_group ) { uint32* cp1 = cp+w+toskew; uint32* cp2 = cp1+w+toskew; uint32* cp3 = cp2+w+toskew; int32 incr = 3*w+4*toskew; int32 Cb, Cr; int group_size = v_group * h_group + 2; (void) y; fromskew = (fromskew * group_size) / h_group; for( yy = 0; yy < h; yy++ ) { unsigned char *pp_line; int y_line_group = yy / v_group; int y_remainder = yy - y_line_group * v_group; pp_line = pp + v_line_group * for( xx = 0; xx < w; xx++ ) { Cb = pp } } for (; h >= 4; h -= 4) { x = w>>2; do { Cb = pp[16]; Cr = pp[17]; YCbCrtoRGB(cp [0], pp[ 0]); YCbCrtoRGB(cp [1], pp[ 1]); YCbCrtoRGB(cp [2], pp[ 2]); YCbCrtoRGB(cp [3], pp[ 3]); YCbCrtoRGB(cp1[0], pp[ 4]); YCbCrtoRGB(cp1[1], pp[ 5]); YCbCrtoRGB(cp1[2], pp[ 6]); YCbCrtoRGB(cp1[3], pp[ 7]); YCbCrtoRGB(cp2[0], pp[ 8]); YCbCrtoRGB(cp2[1], pp[ 9]); YCbCrtoRGB(cp2[2], pp[10]); YCbCrtoRGB(cp2[3], pp[11]); YCbCrtoRGB(cp3[0], pp[12]); YCbCrtoRGB(cp3[1], pp[13]); YCbCrtoRGB(cp3[2], pp[14]); YCbCrtoRGB(cp3[3], pp[15]); cp += 4, cp1 += 4, cp2 += 4, cp3 += 4; pp += 18; } while (--x); cp += incr, cp1 += incr, cp2 += incr, cp3 += incr; pp += fromskew; } } #endif /* * 8-bit packed YCbCr samples w/ 4,4 subsampling => RGB */ DECLAREContigPutFunc(putcontig8bitYCbCr44tile) { uint32* cp1 = cp+w+toskew; uint32* cp2 = cp1+w+toskew; uint32* cp3 = cp2+w+toskew; int32 incr = 3*w+4*toskew; (void) y; /* adjust fromskew */ fromskew = (fromskew / 4) * (4*2+2); if ((h & 3) == 0 && (w & 3) == 0) { for (; h >= 4; h -= 4) { x = w>>2; do { int32 Cb = pp[16]; int32 Cr = pp[17]; YCbCrtoRGB(cp [0], pp[ 0]); YCbCrtoRGB(cp [1], pp[ 1]); YCbCrtoRGB(cp [2], pp[ 2]); YCbCrtoRGB(cp [3], pp[ 3]); YCbCrtoRGB(cp1[0], pp[ 4]); YCbCrtoRGB(cp1[1], pp[ 5]); YCbCrtoRGB(cp1[2], pp[ 6]); YCbCrtoRGB(cp1[3], pp[ 7]); YCbCrtoRGB(cp2[0], pp[ 8]); YCbCrtoRGB(cp2[1], pp[ 9]); YCbCrtoRGB(cp2[2], pp[10]); YCbCrtoRGB(cp2[3], pp[11]); YCbCrtoRGB(cp3[0], pp[12]); YCbCrtoRGB(cp3[1], pp[13]); YCbCrtoRGB(cp3[2], pp[14]); YCbCrtoRGB(cp3[3], pp[15]); cp += 4; cp1 += 4; cp2 += 4; cp3 += 4; pp += 18; } while (--x); cp += incr; cp1 += incr; cp2 += incr; cp3 += incr; pp += fromskew; } } else { while (h > 0) { for (x = w; x > 0;) { int32 Cb = pp[16]; int32 Cr = pp[17]; switch (x) { default: switch (h) { default: YCbCrtoRGB(cp3[3], pp[15]); /* FALLTHROUGH */ case 3: YCbCrtoRGB(cp2[3], pp[11]); /* FALLTHROUGH */ case 2: YCbCrtoRGB(cp1[3], pp[ 7]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [3], pp[ 3]); /* FALLTHROUGH */ } /* FALLTHROUGH */ case 3: switch (h) { default: YCbCrtoRGB(cp3[2], pp[14]); /* FALLTHROUGH */ case 3: YCbCrtoRGB(cp2[2], pp[10]); /* FALLTHROUGH */ case 2: YCbCrtoRGB(cp1[2], pp[ 6]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [2], pp[ 2]); /* FALLTHROUGH */ } /* FALLTHROUGH */ case 2: switch (h) { default: YCbCrtoRGB(cp3[1], pp[13]); /* FALLTHROUGH */ case 3: YCbCrtoRGB(cp2[1], pp[ 9]); /* FALLTHROUGH */ case 2: YCbCrtoRGB(cp1[1], pp[ 5]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [1], pp[ 1]); /* FALLTHROUGH */ } /* FALLTHROUGH */ case 1: switch (h) { default: YCbCrtoRGB(cp3[0], pp[12]); /* FALLTHROUGH */ case 3: YCbCrtoRGB(cp2[0], pp[ 8]); /* FALLTHROUGH */ case 2: YCbCrtoRGB(cp1[0], pp[ 4]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [0], pp[ 0]); /* FALLTHROUGH */ } /* FALLTHROUGH */ } if (x < 4) { cp += x; cp1 += x; cp2 += x; cp3 += x; x = 0; } else { cp += 4; cp1 += 4; cp2 += 4; cp3 += 4; x -= 4; } pp += 18; } if (h <= 4) break; h -= 4; cp += incr; cp1 += incr; cp2 += incr; cp3 += incr; pp += fromskew; } } } /* * 8-bit packed YCbCr samples w/ 4,2 subsampling => RGB */ DECLAREContigPutFunc(putcontig8bitYCbCr42tile) { uint32* cp1 = cp+w+toskew; int32 incr = 2*toskew+w; (void) y; fromskew = (fromskew / 4) * (4*2+2); if ((w & 3) == 0 && (h & 1) == 0) { for (; h >= 2; h -= 2) { x = w>>2; do { int32 Cb = pp[8]; int32 Cr = pp[9]; YCbCrtoRGB(cp [0], pp[0]); YCbCrtoRGB(cp [1], pp[1]); YCbCrtoRGB(cp [2], pp[2]); YCbCrtoRGB(cp [3], pp[3]); YCbCrtoRGB(cp1[0], pp[4]); YCbCrtoRGB(cp1[1], pp[5]); YCbCrtoRGB(cp1[2], pp[6]); YCbCrtoRGB(cp1[3], pp[7]); cp += 4; cp1 += 4; pp += 10; } while (--x); cp += incr; cp1 += incr; pp += fromskew; } } else { while (h > 0) { for (x = w; x > 0;) { int32 Cb = pp[8]; int32 Cr = pp[9]; switch (x) { default: switch (h) { default: YCbCrtoRGB(cp1[3], pp[ 7]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [3], pp[ 3]); /* FALLTHROUGH */ } /* FALLTHROUGH */ case 3: switch (h) { default: YCbCrtoRGB(cp1[2], pp[ 6]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [2], pp[ 2]); /* FALLTHROUGH */ } /* FALLTHROUGH */ case 2: switch (h) { default: YCbCrtoRGB(cp1[1], pp[ 5]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [1], pp[ 1]); /* FALLTHROUGH */ } /* FALLTHROUGH */ case 1: switch (h) { default: YCbCrtoRGB(cp1[0], pp[ 4]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [0], pp[ 0]); /* FALLTHROUGH */ } /* FALLTHROUGH */ } if (x < 4) { cp += x; cp1 += x; x = 0; } else { cp += 4; cp1 += 4; x -= 4; } pp += 10; } if (h <= 2) break; h -= 2; cp += incr; cp1 += incr; pp += fromskew; } } } /* * 8-bit packed YCbCr samples w/ 4,1 subsampling => RGB */ DECLAREContigPutFunc(putcontig8bitYCbCr41tile) { (void) y; fromskew = (fromskew / 4) * (4*1+2); do { x = w>>2; while(x>0) { int32 Cb = pp[4]; int32 Cr = pp[5]; YCbCrtoRGB(cp [0], pp[0]); YCbCrtoRGB(cp [1], pp[1]); YCbCrtoRGB(cp [2], pp[2]); YCbCrtoRGB(cp [3], pp[3]); cp += 4; pp += 6; x--; } if( (w&3) != 0 ) { int32 Cb = pp[4]; int32 Cr = pp[5]; switch( (w&3) ) { case 3: YCbCrtoRGB(cp [2], pp[2]); /*-fallthrough*/ case 2: YCbCrtoRGB(cp [1], pp[1]); /*-fallthrough*/ case 1: YCbCrtoRGB(cp [0], pp[0]); /*-fallthrough*/ case 0: break; } cp += (w&3); pp += 6; } cp += toskew; pp += fromskew; } while (--h); } /* * 8-bit packed YCbCr samples w/ 2,2 subsampling => RGB */ DECLAREContigPutFunc(putcontig8bitYCbCr22tile) { uint32* cp2; int32 incr = 2*toskew+w; (void) y; fromskew = (fromskew / 2) * (2*2+2); cp2 = cp+w+toskew; while (h>=2) { x = w; while (x>=2) { uint32 Cb = pp[4]; uint32 Cr = pp[5]; YCbCrtoRGB(cp[0], pp[0]); YCbCrtoRGB(cp[1], pp[1]); YCbCrtoRGB(cp2[0], pp[2]); YCbCrtoRGB(cp2[1], pp[3]); cp += 2; cp2 += 2; pp += 6; x -= 2; } if (x==1) { uint32 Cb = pp[4]; uint32 Cr = pp[5]; YCbCrtoRGB(cp[0], pp[0]); YCbCrtoRGB(cp2[0], pp[2]); cp ++ ; cp2 ++ ; pp += 6; } cp += incr; cp2 += incr; pp += fromskew; h-=2; } if (h==1) { x = w; while (x>=2) { uint32 Cb = pp[4]; uint32 Cr = pp[5]; YCbCrtoRGB(cp[0], pp[0]); YCbCrtoRGB(cp[1], pp[1]); cp += 2; cp2 += 2; pp += 6; x -= 2; } if (x==1) { uint32 Cb = pp[4]; uint32 Cr = pp[5]; YCbCrtoRGB(cp[0], pp[0]); } } } /* * 8-bit packed YCbCr samples w/ 2,1 subsampling => RGB */ DECLAREContigPutFunc(putcontig8bitYCbCr21tile) { (void) y; fromskew = (fromskew / 2) * (2*1+2); do { x = w>>1; while(x>0) { int32 Cb = pp[2]; int32 Cr = pp[3]; YCbCrtoRGB(cp[0], pp[0]); YCbCrtoRGB(cp[1], pp[1]); cp += 2; pp += 4; x --; } if( (w&1) != 0 ) { int32 Cb = pp[2]; int32 Cr = pp[3]; YCbCrtoRGB(cp[0], pp[0]); cp += 1; pp += 4; } cp += toskew; pp += fromskew; } while (--h); } /* * 8-bit packed YCbCr samples w/ 1,2 subsampling => RGB */ DECLAREContigPutFunc(putcontig8bitYCbCr12tile) { uint32* cp2; int32 incr = 2*toskew+w; (void) y; fromskew = (fromskew / 1) * (1 * 2 + 2); cp2 = cp+w+toskew; while (h>=2) { x = w; do { uint32 Cb = pp[2]; uint32 Cr = pp[3]; YCbCrtoRGB(cp[0], pp[0]); YCbCrtoRGB(cp2[0], pp[1]); cp ++; cp2 ++; pp += 4; } while (--x); cp += incr; cp2 += incr; pp += fromskew; h-=2; } if (h==1) { x = w; do { uint32 Cb = pp[2]; uint32 Cr = pp[3]; YCbCrtoRGB(cp[0], pp[0]); cp ++; pp += 4; } while (--x); } } /* * 8-bit packed YCbCr samples w/ no subsampling => RGB */ DECLAREContigPutFunc(putcontig8bitYCbCr11tile) { (void) y; fromskew = (fromskew / 1) * (1 * 1 + 2); do { x = w; /* was x = w>>1; patched 2000/09/25 warmerda@home.com */ do { int32 Cb = pp[1]; int32 Cr = pp[2]; YCbCrtoRGB(*cp++, pp[0]); pp += 3; } while (--x); cp += toskew; pp += fromskew; } while (--h); } /* * 8-bit packed YCbCr samples w/ no subsampling => RGB */ DECLARESepPutFunc(putseparate8bitYCbCr11tile) { (void) y; (void) a; /* TODO: naming of input vars is still off, change obfuscating declaration inside define, or resolve obfuscation */ for( ; h > 0; --h) { x = w; do { uint32 dr, dg, db; TIFFYCbCrtoRGB(img->ycbcr,*r++,*g++,*b++,&dr,&dg,&db); *cp++ = PACK(dr,dg,db); } while (--x); SKEW(r, g, b, fromskew); cp += toskew; } } #undef YCbCrtoRGB static int isInRefBlackWhiteRange(float f) { return f > (float)(-0x7FFFFFFF + 128) && f < (float)0x7FFFFFFF; } static int initYCbCrConversion(TIFFRGBAImage* img) { static const char module[] = "initYCbCrConversion"; float *luma, *refBlackWhite; if (img->ycbcr == NULL) { img->ycbcr = (TIFFYCbCrToRGB*) _TIFFmalloc( TIFFroundup_32(sizeof (TIFFYCbCrToRGB), sizeof (long)) + 4*256*sizeof (TIFFRGBValue) + 2*256*sizeof (int) + 3*256*sizeof (int32) ); if (img->ycbcr == NULL) { TIFFErrorExt(img->tif->tif_clientdata, module, "No space for YCbCr->RGB conversion state"); return (0); } } TIFFGetFieldDefaulted(img->tif, TIFFTAG_YCBCRCOEFFICIENTS, &luma); TIFFGetFieldDefaulted(img->tif, TIFFTAG_REFERENCEBLACKWHITE, &refBlackWhite); /* Do some validation to avoid later issues. Detect NaN for now */ /* and also if lumaGreen is zero since we divide by it later */ if( luma[0] != luma[0] || luma[1] != luma[1] || luma[1] == 0.0 || luma[2] != luma[2] ) { TIFFErrorExt(img->tif->tif_clientdata, module, "Invalid values for YCbCrCoefficients tag"); return (0); } if( !isInRefBlackWhiteRange(refBlackWhite[0]) || !isInRefBlackWhiteRange(refBlackWhite[1]) || !isInRefBlackWhiteRange(refBlackWhite[2]) || !isInRefBlackWhiteRange(refBlackWhite[3]) || !isInRefBlackWhiteRange(refBlackWhite[4]) || !isInRefBlackWhiteRange(refBlackWhite[5]) ) { TIFFErrorExt(img->tif->tif_clientdata, module, "Invalid values for ReferenceBlackWhite tag"); return (0); } if (TIFFYCbCrToRGBInit(img->ycbcr, luma, refBlackWhite) < 0) return(0); return (1); } static tileContigRoutine initCIELabConversion(TIFFRGBAImage* img) { static const char module[] = "initCIELabConversion"; float *whitePoint; float refWhite[3]; TIFFGetFieldDefaulted(img->tif, TIFFTAG_WHITEPOINT, &whitePoint); if (whitePoint[1] == 0.0f ) { TIFFErrorExt(img->tif->tif_clientdata, module, "Invalid value for WhitePoint tag."); return NULL; } if (!img->cielab) { img->cielab = (TIFFCIELabToRGB *) _TIFFmalloc(sizeof(TIFFCIELabToRGB)); if (!img->cielab) { TIFFErrorExt(img->tif->tif_clientdata, module, "No space for CIE L*a*b*->RGB conversion state."); return NULL; } } refWhite[1] = 100.0F; refWhite[0] = whitePoint[0] / whitePoint[1] * refWhite[1]; refWhite[2] = (1.0F - whitePoint[0] - whitePoint[1]) / whitePoint[1] * refWhite[1]; if (TIFFCIELabToRGBInit(img->cielab, &display_sRGB, refWhite) < 0) { TIFFErrorExt(img->tif->tif_clientdata, module, "Failed to initialize CIE L*a*b*->RGB conversion state."); _TIFFfree(img->cielab); return NULL; } return putcontig8bitCIELab; } /* * Greyscale images with less than 8 bits/sample are handled * with a table to avoid lots of shifts and masks. The table * is setup so that put*bwtile (below) can retrieve 8/bitspersample * pixel values simply by indexing into the table with one * number. */ static int makebwmap(TIFFRGBAImage* img) { TIFFRGBValue* Map = img->Map; int bitspersample = img->bitspersample; int nsamples = 8 / bitspersample; int i; uint32* p; if( nsamples == 0 ) nsamples = 1; img->BWmap = (uint32**) _TIFFmalloc( 256*sizeof (uint32 *)+(256*nsamples*sizeof(uint32))); if (img->BWmap == NULL) { TIFFErrorExt(img->tif->tif_clientdata, TIFFFileName(img->tif), "No space for B&W mapping table"); return (0); } p = (uint32*)(img->BWmap + 256); for (i = 0; i < 256; i++) { TIFFRGBValue c; img->BWmap[i] = p; switch (bitspersample) { #define GREY(x) c = Map[x]; *p++ = PACK(c,c,c); case 1: GREY(i>>7); GREY((i>>6)&1); GREY((i>>5)&1); GREY((i>>4)&1); GREY((i>>3)&1); GREY((i>>2)&1); GREY((i>>1)&1); GREY(i&1); break; case 2: GREY(i>>6); GREY((i>>4)&3); GREY((i>>2)&3); GREY(i&3); break; case 4: GREY(i>>4); GREY(i&0xf); break; case 8: case 16: GREY(i); break; } #undef GREY } return (1); } /* * Construct a mapping table to convert from the range * of the data samples to [0,255] --for display. This * process also handles inverting B&W images when needed. */ static int setupMap(TIFFRGBAImage* img) { int32 x, range; range = (int32)((1L<<img->bitspersample)-1); /* treat 16 bit the same as eight bit */ if( img->bitspersample == 16 ) range = (int32) 255; img->Map = (TIFFRGBValue*) _TIFFmalloc((range+1) * sizeof (TIFFRGBValue)); if (img->Map == NULL) { TIFFErrorExt(img->tif->tif_clientdata, TIFFFileName(img->tif), "No space for photometric conversion table"); return (0); } if (img->photometric == PHOTOMETRIC_MINISWHITE) { for (x = 0; x <= range; x++) img->Map[x] = (TIFFRGBValue) (((range - x) * 255) / range); } else { for (x = 0; x <= range; x++) img->Map[x] = (TIFFRGBValue) ((x * 255) / range); } if (img->bitspersample <= 16 && (img->photometric == PHOTOMETRIC_MINISBLACK || img->photometric == PHOTOMETRIC_MINISWHITE)) { /* * Use photometric mapping table to construct * unpacking tables for samples <= 8 bits. */ if (!makebwmap(img)) return (0); /* no longer need Map, free it */ _TIFFfree(img->Map); img->Map = NULL; } return (1); } static int checkcmap(TIFFRGBAImage* img) { uint16* r = img->redcmap; uint16* g = img->greencmap; uint16* b = img->bluecmap; long n = 1L<<img->bitspersample; while (n-- > 0) if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256) return (16); return (8); } static void cvtcmap(TIFFRGBAImage* img) { uint16* r = img->redcmap; uint16* g = img->greencmap; uint16* b = img->bluecmap; long i; for (i = (1L<<img->bitspersample)-1; i >= 0; i--) { #define CVT(x) ((uint16)((x)>>8)) r[i] = CVT(r[i]); g[i] = CVT(g[i]); b[i] = CVT(b[i]); #undef CVT } } /* * Palette images with <= 8 bits/sample are handled * with a table to avoid lots of shifts and masks. The table * is setup so that put*cmaptile (below) can retrieve 8/bitspersample * pixel values simply by indexing into the table with one * number. */ static int makecmap(TIFFRGBAImage* img) { int bitspersample = img->bitspersample; int nsamples = 8 / bitspersample; uint16* r = img->redcmap; uint16* g = img->greencmap; uint16* b = img->bluecmap; uint32 *p; int i; img->PALmap = (uint32**) _TIFFmalloc( 256*sizeof (uint32 *)+(256*nsamples*sizeof(uint32))); if (img->PALmap == NULL) { TIFFErrorExt(img->tif->tif_clientdata, TIFFFileName(img->tif), "No space for Palette mapping table"); return (0); } p = (uint32*)(img->PALmap + 256); for (i = 0; i < 256; i++) { TIFFRGBValue c; img->PALmap[i] = p; #define CMAP(x) c = (TIFFRGBValue) x; *p++ = PACK(r[c]&0xff, g[c]&0xff, b[c]&0xff); switch (bitspersample) { case 1: CMAP(i>>7); CMAP((i>>6)&1); CMAP((i>>5)&1); CMAP((i>>4)&1); CMAP((i>>3)&1); CMAP((i>>2)&1); CMAP((i>>1)&1); CMAP(i&1); break; case 2: CMAP(i>>6); CMAP((i>>4)&3); CMAP((i>>2)&3); CMAP(i&3); break; case 4: CMAP(i>>4); CMAP(i&0xf); break; case 8: CMAP(i); break; } #undef CMAP } return (1); } /* * Construct any mapping table used * by the associated put routine. */ static int buildMap(TIFFRGBAImage* img) { switch (img->photometric) { case PHOTOMETRIC_RGB: case PHOTOMETRIC_YCBCR: case PHOTOMETRIC_SEPARATED: if (img->bitspersample == 8) break; /* fall through... */ case PHOTOMETRIC_MINISBLACK: case PHOTOMETRIC_MINISWHITE: if (!setupMap(img)) return (0); break; case PHOTOMETRIC_PALETTE: /* * Convert 16-bit colormap to 8-bit (unless it looks * like an old-style 8-bit colormap). */ if (checkcmap(img) == 16) cvtcmap(img); else TIFFWarningExt(img->tif->tif_clientdata, TIFFFileName(img->tif), "Assuming 8-bit colormap"); /* * Use mapping table and colormap to construct * unpacking tables for samples < 8 bits. */ if (img->bitspersample <= 8 && !makecmap(img)) return (0); break; } return (1); } /* * Select the appropriate conversion routine for packed data. */ static int PickContigCase(TIFFRGBAImage* img) { img->get = TIFFIsTiled(img->tif) ? gtTileContig : gtStripContig; img->put.contig = NULL; switch (img->photometric) { case PHOTOMETRIC_RGB: switch (img->bitspersample) { case 8: if (img->alpha == EXTRASAMPLE_ASSOCALPHA && img->samplesperpixel >= 4) img->put.contig = putRGBAAcontig8bittile; else if (img->alpha == EXTRASAMPLE_UNASSALPHA && img->samplesperpixel >= 4) { if (BuildMapUaToAa(img)) img->put.contig = putRGBUAcontig8bittile; } else if( img->samplesperpixel >= 3 ) img->put.contig = putRGBcontig8bittile; break; case 16: if (img->alpha == EXTRASAMPLE_ASSOCALPHA && img->samplesperpixel >=4 ) { if (BuildMapBitdepth16To8(img)) img->put.contig = putRGBAAcontig16bittile; } else if (img->alpha == EXTRASAMPLE_UNASSALPHA && img->samplesperpixel >=4 ) { if (BuildMapBitdepth16To8(img) && BuildMapUaToAa(img)) img->put.contig = putRGBUAcontig16bittile; } else if( img->samplesperpixel >=3 ) { if (BuildMapBitdepth16To8(img)) img->put.contig = putRGBcontig16bittile; } break; } break; case PHOTOMETRIC_SEPARATED: if (img->samplesperpixel >=4 && buildMap(img)) { if (img->bitspersample == 8) { if (!img->Map) img->put.contig = putRGBcontig8bitCMYKtile; else img->put.contig = putRGBcontig8bitCMYKMaptile; } } break; case PHOTOMETRIC_PALETTE: if (buildMap(img)) { switch (img->bitspersample) { case 8: img->put.contig = put8bitcmaptile; break; case 4: img->put.contig = put4bitcmaptile; break; case 2: img->put.contig = put2bitcmaptile; break; case 1: img->put.contig = put1bitcmaptile; break; } } break; case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: if (buildMap(img)) { switch (img->bitspersample) { case 16: img->put.contig = put16bitbwtile; break; case 8: if (img->alpha && img->samplesperpixel == 2) img->put.contig = putagreytile; else img->put.contig = putgreytile; break; case 4: img->put.contig = put4bitbwtile; break; case 2: img->put.contig = put2bitbwtile; break; case 1: img->put.contig = put1bitbwtile; break; } } break; case PHOTOMETRIC_YCBCR: if ((img->bitspersample==8) && (img->samplesperpixel==3)) { if (initYCbCrConversion(img)!=0) { /* * The 6.0 spec says that subsampling must be * one of 1, 2, or 4, and that vertical subsampling * must always be <= horizontal subsampling; so * there are only a few possibilities and we just * enumerate the cases. * Joris: added support for the [1,2] case, nonetheless, to accommodate * some OJPEG files */ uint16 SubsamplingHor; uint16 SubsamplingVer; TIFFGetFieldDefaulted(img->tif, TIFFTAG_YCBCRSUBSAMPLING, &SubsamplingHor, &SubsamplingVer); switch ((SubsamplingHor<<4)|SubsamplingVer) { case 0x44: img->put.contig = putcontig8bitYCbCr44tile; break; case 0x42: img->put.contig = putcontig8bitYCbCr42tile; break; case 0x41: img->put.contig = putcontig8bitYCbCr41tile; break; case 0x22: img->put.contig = putcontig8bitYCbCr22tile; break; case 0x21: img->put.contig = putcontig8bitYCbCr21tile; break; case 0x12: img->put.contig = putcontig8bitYCbCr12tile; break; case 0x11: img->put.contig = putcontig8bitYCbCr11tile; break; } } } break; case PHOTOMETRIC_CIELAB: if (img->samplesperpixel == 3 && buildMap(img)) { if (img->bitspersample == 8) img->put.contig = initCIELabConversion(img); break; } } return ((img->get!=NULL) && (img->put.contig!=NULL)); } /* * Select the appropriate conversion routine for unpacked data. * * NB: we assume that unpacked single channel data is directed * to the "packed routines. */ static int PickSeparateCase(TIFFRGBAImage* img) { img->get = TIFFIsTiled(img->tif) ? gtTileSeparate : gtStripSeparate; img->put.separate = NULL; switch (img->photometric) { case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: /* greyscale images processed pretty much as RGB by gtTileSeparate */ case PHOTOMETRIC_RGB: switch (img->bitspersample) { case 8: if (img->alpha == EXTRASAMPLE_ASSOCALPHA) img->put.separate = putRGBAAseparate8bittile; else if (img->alpha == EXTRASAMPLE_UNASSALPHA) { if (BuildMapUaToAa(img)) img->put.separate = putRGBUAseparate8bittile; } else img->put.separate = putRGBseparate8bittile; break; case 16: if (img->alpha == EXTRASAMPLE_ASSOCALPHA) { if (BuildMapBitdepth16To8(img)) img->put.separate = putRGBAAseparate16bittile; } else if (img->alpha == EXTRASAMPLE_UNASSALPHA) { if (BuildMapBitdepth16To8(img) && BuildMapUaToAa(img)) img->put.separate = putRGBUAseparate16bittile; } else { if (BuildMapBitdepth16To8(img)) img->put.separate = putRGBseparate16bittile; } break; } break; case PHOTOMETRIC_SEPARATED: if (img->bitspersample == 8 && img->samplesperpixel == 4) { img->alpha = 1; // Not alpha, but seems like the only way to get 4th band img->put.separate = putCMYKseparate8bittile; } break; case PHOTOMETRIC_YCBCR: if ((img->bitspersample==8) && (img->samplesperpixel==3)) { if (initYCbCrConversion(img)!=0) { uint16 hs, vs; TIFFGetFieldDefaulted(img->tif, TIFFTAG_YCBCRSUBSAMPLING, &hs, &vs); switch ((hs<<4)|vs) { case 0x11: img->put.separate = putseparate8bitYCbCr11tile; break; /* TODO: add other cases here */ } } } break; } return ((img->get!=NULL) && (img->put.separate!=NULL)); } static int BuildMapUaToAa(TIFFRGBAImage* img) { static const char module[]="BuildMapUaToAa"; uint8* m; uint16 na,nv; assert(img->UaToAa==NULL); img->UaToAa=_TIFFmalloc(65536); if (img->UaToAa==NULL) { TIFFErrorExt(img->tif->tif_clientdata,module,"Out of memory"); return(0); } m=img->UaToAa; for (na=0; na<256; na++) { for (nv=0; nv<256; nv++) *m++=(uint8)((nv*na+127)/255); } return(1); } static int BuildMapBitdepth16To8(TIFFRGBAImage* img) { static const char module[]="BuildMapBitdepth16To8"; uint8* m; uint32 n; assert(img->Bitdepth16To8==NULL); img->Bitdepth16To8=_TIFFmalloc(65536); if (img->Bitdepth16To8==NULL) { TIFFErrorExt(img->tif->tif_clientdata,module,"Out of memory"); return(0); } m=img->Bitdepth16To8; for (n=0; n<65536; n++) *m++=(uint8)((n+128)/257); return(1); } /* * Read a whole strip off data from the file, and convert to RGBA form. * If this is the last strip, then it will only contain the portion of * the strip that is actually within the image space. The result is * organized in bottom to top form. */ int TIFFReadRGBAStrip(TIFF* tif, uint32 row, uint32 * raster ) { return TIFFReadRGBAStripExt(tif, row, raster, 0 ); } int TIFFReadRGBAStripExt(TIFF* tif, uint32 row, uint32 * raster, int stop_on_error) { char emsg[1024] = ""; TIFFRGBAImage img; int ok; uint32 rowsperstrip, rows_to_read; if( TIFFIsTiled( tif ) ) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "Can't use TIFFReadRGBAStrip() with tiled file."); return (0); } TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); if( (row % rowsperstrip) != 0 ) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "Row passed to TIFFReadRGBAStrip() must be first in a strip."); return (0); } if (TIFFRGBAImageOK(tif, emsg) && TIFFRGBAImageBegin(&img, tif, stop_on_error, emsg)) { img.row_offset = row; img.col_offset = 0; if( row + rowsperstrip > img.height ) rows_to_read = img.height - row; else rows_to_read = rowsperstrip; ok = TIFFRGBAImageGet(&img, raster, img.width, rows_to_read ); TIFFRGBAImageEnd(&img); } else { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "%s", emsg); ok = 0; } return (ok); } /* * Read a whole tile off data from the file, and convert to RGBA form. * The returned RGBA data is organized from bottom to top of tile, * and may include zeroed areas if the tile extends off the image. */ int TIFFReadRGBATile(TIFF* tif, uint32 col, uint32 row, uint32 * raster) { return TIFFReadRGBATileExt(tif, col, row, raster, 0 ); } int TIFFReadRGBATileExt(TIFF* tif, uint32 col, uint32 row, uint32 * raster, int stop_on_error ) { char emsg[1024] = ""; TIFFRGBAImage img; int ok; uint32 tile_xsize, tile_ysize; uint32 read_xsize, read_ysize; uint32 i_row; /* * Verify that our request is legal - on a tile file, and on a * tile boundary. */ if( !TIFFIsTiled( tif ) ) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "Can't use TIFFReadRGBATile() with striped file."); return (0); } TIFFGetFieldDefaulted(tif, TIFFTAG_TILEWIDTH, &tile_xsize); TIFFGetFieldDefaulted(tif, TIFFTAG_TILELENGTH, &tile_ysize); if( (col % tile_xsize) != 0 || (row % tile_ysize) != 0 ) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "Row/col passed to TIFFReadRGBATile() must be top" "left corner of a tile."); return (0); } /* * Setup the RGBA reader. */ if (!TIFFRGBAImageOK(tif, emsg) || !TIFFRGBAImageBegin(&img, tif, stop_on_error, emsg)) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "%s", emsg); return( 0 ); } /* * The TIFFRGBAImageGet() function doesn't allow us to get off the * edge of the image, even to fill an otherwise valid tile. So we * figure out how much we can read, and fix up the tile buffer to * a full tile configuration afterwards. */ if( row + tile_ysize > img.height ) read_ysize = img.height - row; else read_ysize = tile_ysize; if( col + tile_xsize > img.width ) read_xsize = img.width - col; else read_xsize = tile_xsize; /* * Read the chunk of imagery. */ img.row_offset = row; img.col_offset = col; ok = TIFFRGBAImageGet(&img, raster, read_xsize, read_ysize ); TIFFRGBAImageEnd(&img); /* * If our read was incomplete we will need to fix up the tile by * shifting the data around as if a full tile of data is being returned. * * This is all the more complicated because the image is organized in * bottom to top format. */ if( read_xsize == tile_xsize && read_ysize == tile_ysize ) return( ok ); for( i_row = 0; i_row < read_ysize; i_row++ ) { memmove( raster + (tile_ysize - i_row - 1) * tile_xsize, raster + (read_ysize - i_row - 1) * read_xsize, read_xsize * sizeof(uint32) ); _TIFFmemset( raster + (tile_ysize - i_row - 1) * tile_xsize+read_xsize, 0, sizeof(uint32) * (tile_xsize - read_xsize) ); } for( i_row = read_ysize; i_row < tile_ysize; i_row++ ) { _TIFFmemset( raster + (tile_ysize - i_row - 1) * tile_xsize, 0, sizeof(uint32) * tile_xsize ); } return (ok); } /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
null
/* * Copyright (c) 1991-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library * * Read and return a packed RGBA image. */ #include "tiffiop.h" #include <stdio.h> static int gtTileContig(TIFFRGBAImage*, uint32*, uint32, uint32); static int gtTileSeparate(TIFFRGBAImage*, uint32*, uint32, uint32); static int gtStripContig(TIFFRGBAImage*, uint32*, uint32, uint32); static int gtStripSeparate(TIFFRGBAImage*, uint32*, uint32, uint32); static int PickContigCase(TIFFRGBAImage*); static int PickSeparateCase(TIFFRGBAImage*); static int BuildMapUaToAa(TIFFRGBAImage* img); static int BuildMapBitdepth16To8(TIFFRGBAImage* img); static const char photoTag[] = "PhotometricInterpretation"; /* * Helper constants used in Orientation tag handling */ #define FLIP_VERTICALLY 0x01 #define FLIP_HORIZONTALLY 0x02 /* * Color conversion constants. We will define display types here. */ static const TIFFDisplay display_sRGB = { { /* XYZ -> luminance matrix */ { 3.2410F, -1.5374F, -0.4986F }, { -0.9692F, 1.8760F, 0.0416F }, { 0.0556F, -0.2040F, 1.0570F } }, 100.0F, 100.0F, 100.0F, /* Light o/p for reference white */ 255, 255, 255, /* Pixel values for ref. white */ 1.0F, 1.0F, 1.0F, /* Residual light o/p for black pixel */ 2.4F, 2.4F, 2.4F, /* Gamma values for the three guns */ }; /* * Check the image to see if TIFFReadRGBAImage can deal with it. * 1/0 is returned according to whether or not the image can * be handled. If 0 is returned, emsg contains the reason * why it is being rejected. */ int TIFFRGBAImageOK(TIFF* tif, char emsg[1024]) { TIFFDirectory* td = &tif->tif_dir; uint16 photometric; int colorchannels; if (!tif->tif_decodestatus) { sprintf(emsg, "Sorry, requested compression method is not configured"); return (0); } switch (td->td_bitspersample) { case 1: case 2: case 4: case 8: case 16: break; default: sprintf(emsg, "Sorry, can not handle images with %d-bit samples", td->td_bitspersample); return (0); } if (td->td_sampleformat == SAMPLEFORMAT_IEEEFP) { sprintf(emsg, "Sorry, can not handle images with IEEE floating-point samples"); return (0); } colorchannels = td->td_samplesperpixel - td->td_extrasamples; if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometric)) { switch (colorchannels) { case 1: photometric = PHOTOMETRIC_MINISBLACK; break; case 3: photometric = PHOTOMETRIC_RGB; break; default: sprintf(emsg, "Missing needed %s tag", photoTag); return (0); } } switch (photometric) { case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: case PHOTOMETRIC_PALETTE: if (td->td_planarconfig == PLANARCONFIG_CONTIG && td->td_samplesperpixel != 1 && td->td_bitspersample < 8 ) { sprintf(emsg, "Sorry, can not handle contiguous data with %s=%d, " "and %s=%d and Bits/Sample=%d", photoTag, photometric, "Samples/pixel", td->td_samplesperpixel, td->td_bitspersample); return (0); } /* * We should likely validate that any extra samples are either * to be ignored, or are alpha, and if alpha we should try to use * them. But for now we won't bother with this. */ break; case PHOTOMETRIC_YCBCR: /* * TODO: if at all meaningful and useful, make more complete * support check here, or better still, refactor to let supporting * code decide whether there is support and what meaningful * error to return */ break; case PHOTOMETRIC_RGB: if (colorchannels < 3) { sprintf(emsg, "Sorry, can not handle RGB image with %s=%d", "Color channels", colorchannels); return (0); } break; case PHOTOMETRIC_SEPARATED: { uint16 inkset; TIFFGetFieldDefaulted(tif, TIFFTAG_INKSET, &inkset); if (inkset != INKSET_CMYK) { sprintf(emsg, "Sorry, can not handle separated image with %s=%d", "InkSet", inkset); return 0; } if (td->td_samplesperpixel < 4) { sprintf(emsg, "Sorry, can not handle separated image with %s=%d", "Samples/pixel", td->td_samplesperpixel); return 0; } break; } case PHOTOMETRIC_LOGL: if (td->td_compression != COMPRESSION_SGILOG) { sprintf(emsg, "Sorry, LogL data must have %s=%d", "Compression", COMPRESSION_SGILOG); return (0); } break; case PHOTOMETRIC_LOGLUV: if (td->td_compression != COMPRESSION_SGILOG && td->td_compression != COMPRESSION_SGILOG24) { sprintf(emsg, "Sorry, LogLuv data must have %s=%d or %d", "Compression", COMPRESSION_SGILOG, COMPRESSION_SGILOG24); return (0); } if (td->td_planarconfig != PLANARCONFIG_CONTIG) { sprintf(emsg, "Sorry, can not handle LogLuv images with %s=%d", "Planarconfiguration", td->td_planarconfig); return (0); } if ( td->td_samplesperpixel != 3 || colorchannels != 3 ) { sprintf(emsg, "Sorry, can not handle image with %s=%d, %s=%d", "Samples/pixel", td->td_samplesperpixel, "colorchannels", colorchannels); return 0; } break; case PHOTOMETRIC_CIELAB: if ( td->td_samplesperpixel != 3 || colorchannels != 3 || td->td_bitspersample != 8 ) { sprintf(emsg, "Sorry, can not handle image with %s=%d, %s=%d and %s=%d", "Samples/pixel", td->td_samplesperpixel, "colorchannels", colorchannels, "Bits/sample", td->td_bitspersample); return 0; } break; default: sprintf(emsg, "Sorry, can not handle image with %s=%d", photoTag, photometric); return (0); } return (1); } void TIFFRGBAImageEnd(TIFFRGBAImage* img) { if (img->Map) { _TIFFfree(img->Map); img->Map = NULL; } if (img->BWmap) { _TIFFfree(img->BWmap); img->BWmap = NULL; } if (img->PALmap) { _TIFFfree(img->PALmap); img->PALmap = NULL; } if (img->ycbcr) { _TIFFfree(img->ycbcr); img->ycbcr = NULL; } if (img->cielab) { _TIFFfree(img->cielab); img->cielab = NULL; } if (img->UaToAa) { _TIFFfree(img->UaToAa); img->UaToAa = NULL; } if (img->Bitdepth16To8) { _TIFFfree(img->Bitdepth16To8); img->Bitdepth16To8 = NULL; } if( img->redcmap ) { _TIFFfree( img->redcmap ); _TIFFfree( img->greencmap ); _TIFFfree( img->bluecmap ); img->redcmap = img->greencmap = img->bluecmap = NULL; } } static int isCCITTCompression(TIFF* tif) { uint16 compress; TIFFGetField(tif, TIFFTAG_COMPRESSION, &compress); return (compress == COMPRESSION_CCITTFAX3 || compress == COMPRESSION_CCITTFAX4 || compress == COMPRESSION_CCITTRLE || compress == COMPRESSION_CCITTRLEW); } int TIFFRGBAImageBegin(TIFFRGBAImage* img, TIFF* tif, int stop, char emsg[1024]) { uint16* sampleinfo; uint16 extrasamples; uint16 planarconfig; uint16 compress; int colorchannels; uint16 *red_orig, *green_orig, *blue_orig; int n_color; if( !TIFFRGBAImageOK(tif, emsg) ) return 0; /* Initialize to normal values */ img->row_offset = 0; img->col_offset = 0; img->redcmap = NULL; img->greencmap = NULL; img->bluecmap = NULL; img->Map = NULL; img->BWmap = NULL; img->PALmap = NULL; img->ycbcr = NULL; img->cielab = NULL; img->UaToAa = NULL; img->Bitdepth16To8 = NULL; img->req_orientation = ORIENTATION_BOTLEFT; /* It is the default */ img->tif = tif; img->stoponerr = stop; TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &img->bitspersample); switch (img->bitspersample) { case 1: case 2: case 4: case 8: case 16: break; default: sprintf(emsg, "Sorry, can not handle images with %d-bit samples", img->bitspersample); goto fail_return; } img->alpha = 0; TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &img->samplesperpixel); TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES, &extrasamples, &sampleinfo); if (extrasamples >= 1) { switch (sampleinfo[0]) { case EXTRASAMPLE_UNSPECIFIED: /* Workaround for some images without */ if (img->samplesperpixel > 3) /* correct info about alpha channel */ img->alpha = EXTRASAMPLE_ASSOCALPHA; break; case EXTRASAMPLE_ASSOCALPHA: /* data is pre-multiplied */ case EXTRASAMPLE_UNASSALPHA: /* data is not pre-multiplied */ img->alpha = sampleinfo[0]; break; } } #ifdef DEFAULT_EXTRASAMPLE_AS_ALPHA if( !TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &img->photometric)) img->photometric = PHOTOMETRIC_MINISWHITE; if( extrasamples == 0 && img->samplesperpixel == 4 && img->photometric == PHOTOMETRIC_RGB ) { img->alpha = EXTRASAMPLE_ASSOCALPHA; extrasamples = 1; } #endif colorchannels = img->samplesperpixel - extrasamples; TIFFGetFieldDefaulted(tif, TIFFTAG_COMPRESSION, &compress); TIFFGetFieldDefaulted(tif, TIFFTAG_PLANARCONFIG, &planarconfig); if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &img->photometric)) { switch (colorchannels) { case 1: if (isCCITTCompression(tif)) img->photometric = PHOTOMETRIC_MINISWHITE; else img->photometric = PHOTOMETRIC_MINISBLACK; break; case 3: img->photometric = PHOTOMETRIC_RGB; break; default: sprintf(emsg, "Missing needed %s tag", photoTag); goto fail_return; } } switch (img->photometric) { case PHOTOMETRIC_PALETTE: if (!TIFFGetField(tif, TIFFTAG_COLORMAP, &red_orig, &green_orig, &blue_orig)) { sprintf(emsg, "Missing required \"Colormap\" tag"); goto fail_return; } /* copy the colormaps so we can modify them */ n_color = (1U << img->bitspersample); img->redcmap = (uint16 *) _TIFFmalloc(sizeof(uint16)*n_color); img->greencmap = (uint16 *) _TIFFmalloc(sizeof(uint16)*n_color); img->bluecmap = (uint16 *) _TIFFmalloc(sizeof(uint16)*n_color); if( !img->redcmap || !img->greencmap || !img->bluecmap ) { sprintf(emsg, "Out of memory for colormap copy"); goto fail_return; } _TIFFmemcpy( img->redcmap, red_orig, n_color * 2 ); _TIFFmemcpy( img->greencmap, green_orig, n_color * 2 ); _TIFFmemcpy( img->bluecmap, blue_orig, n_color * 2 ); /* fall through... */ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: if (planarconfig == PLANARCONFIG_CONTIG && img->samplesperpixel != 1 && img->bitspersample < 8 ) { sprintf(emsg, "Sorry, can not handle contiguous data with %s=%d, " "and %s=%d and Bits/Sample=%d", photoTag, img->photometric, "Samples/pixel", img->samplesperpixel, img->bitspersample); goto fail_return; } break; case PHOTOMETRIC_YCBCR: /* It would probably be nice to have a reality check here. */ if (planarconfig == PLANARCONFIG_CONTIG) /* can rely on libjpeg to convert to RGB */ /* XXX should restore current state on exit */ switch (compress) { case COMPRESSION_JPEG: /* * TODO: when complete tests verify complete desubsampling * and YCbCr handling, remove use of TIFFTAG_JPEGCOLORMODE in * favor of tif_getimage.c native handling */ TIFFSetField(tif, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); img->photometric = PHOTOMETRIC_RGB; break; default: /* do nothing */; break; } /* * TODO: if at all meaningful and useful, make more complete * support check here, or better still, refactor to let supporting * code decide whether there is support and what meaningful * error to return */ break; case PHOTOMETRIC_RGB: if (colorchannels < 3) { sprintf(emsg, "Sorry, can not handle RGB image with %s=%d", "Color channels", colorchannels); goto fail_return; } break; case PHOTOMETRIC_SEPARATED: { uint16 inkset; TIFFGetFieldDefaulted(tif, TIFFTAG_INKSET, &inkset); if (inkset != INKSET_CMYK) { sprintf(emsg, "Sorry, can not handle separated image with %s=%d", "InkSet", inkset); goto fail_return; } if (img->samplesperpixel < 4) { sprintf(emsg, "Sorry, can not handle separated image with %s=%d", "Samples/pixel", img->samplesperpixel); goto fail_return; } } break; case PHOTOMETRIC_LOGL: if (compress != COMPRESSION_SGILOG) { sprintf(emsg, "Sorry, LogL data must have %s=%d", "Compression", COMPRESSION_SGILOG); goto fail_return; } TIFFSetField(tif, TIFFTAG_SGILOGDATAFMT, SGILOGDATAFMT_8BIT); img->photometric = PHOTOMETRIC_MINISBLACK; /* little white lie */ img->bitspersample = 8; break; case PHOTOMETRIC_LOGLUV: if (compress != COMPRESSION_SGILOG && compress != COMPRESSION_SGILOG24) { sprintf(emsg, "Sorry, LogLuv data must have %s=%d or %d", "Compression", COMPRESSION_SGILOG, COMPRESSION_SGILOG24); goto fail_return; } if (planarconfig != PLANARCONFIG_CONTIG) { sprintf(emsg, "Sorry, can not handle LogLuv images with %s=%d", "Planarconfiguration", planarconfig); return (0); } TIFFSetField(tif, TIFFTAG_SGILOGDATAFMT, SGILOGDATAFMT_8BIT); img->photometric = PHOTOMETRIC_RGB; /* little white lie */ img->bitspersample = 8; break; case PHOTOMETRIC_CIELAB: break; default: sprintf(emsg, "Sorry, can not handle image with %s=%d", photoTag, img->photometric); goto fail_return; } TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &img->width); TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &img->height); TIFFGetFieldDefaulted(tif, TIFFTAG_ORIENTATION, &img->orientation); img->isContig = !(planarconfig == PLANARCONFIG_SEPARATE && img->samplesperpixel > 1); if (img->isContig) { if (!PickContigCase(img)) { sprintf(emsg, "Sorry, can not handle image"); goto fail_return; } } else { if (!PickSeparateCase(img)) { sprintf(emsg, "Sorry, can not handle image"); goto fail_return; } } return 1; fail_return: TIFFRGBAImageEnd( img ); return 0; } int TIFFRGBAImageGet(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h) { if (img->get == NULL) { TIFFErrorExt(img->tif->tif_clientdata, TIFFFileName(img->tif), "No \"get\" routine setup"); return (0); } if (img->put.any == NULL) { TIFFErrorExt(img->tif->tif_clientdata, TIFFFileName(img->tif), "No \"put\" routine setupl; probably can not handle image format"); return (0); } return (*img->get)(img, raster, w, h); } /* * Read the specified image into an ABGR-format rastertaking in account * specified orientation. */ int TIFFReadRGBAImageOriented(TIFF* tif, uint32 rwidth, uint32 rheight, uint32* raster, int orientation, int stop) { char emsg[1024] = ""; TIFFRGBAImage img; int ok; if (TIFFRGBAImageOK(tif, emsg) && TIFFRGBAImageBegin(&img, tif, stop, emsg)) { img.req_orientation = (uint16)orientation; /* XXX verify rwidth and rheight against width and height */ ok = TIFFRGBAImageGet(&img, raster+(rheight-img.height)*rwidth, rwidth, img.height); TIFFRGBAImageEnd(&img); } else { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "%s", emsg); ok = 0; } return (ok); } /* * Read the specified image into an ABGR-format raster. Use bottom left * origin for raster by default. */ int TIFFReadRGBAImage(TIFF* tif, uint32 rwidth, uint32 rheight, uint32* raster, int stop) { return TIFFReadRGBAImageOriented(tif, rwidth, rheight, raster, ORIENTATION_BOTLEFT, stop); } static int setorientation(TIFFRGBAImage* img) { switch (img->orientation) { case ORIENTATION_TOPLEFT: case ORIENTATION_LEFTTOP: if (img->req_orientation == ORIENTATION_TOPRIGHT || img->req_orientation == ORIENTATION_RIGHTTOP) return FLIP_HORIZONTALLY; else if (img->req_orientation == ORIENTATION_BOTRIGHT || img->req_orientation == ORIENTATION_RIGHTBOT) return FLIP_HORIZONTALLY | FLIP_VERTICALLY; else if (img->req_orientation == ORIENTATION_BOTLEFT || img->req_orientation == ORIENTATION_LEFTBOT) return FLIP_VERTICALLY; else return 0; case ORIENTATION_TOPRIGHT: case ORIENTATION_RIGHTTOP: if (img->req_orientation == ORIENTATION_TOPLEFT || img->req_orientation == ORIENTATION_LEFTTOP) return FLIP_HORIZONTALLY; else if (img->req_orientation == ORIENTATION_BOTRIGHT || img->req_orientation == ORIENTATION_RIGHTBOT) return FLIP_VERTICALLY; else if (img->req_orientation == ORIENTATION_BOTLEFT || img->req_orientation == ORIENTATION_LEFTBOT) return FLIP_HORIZONTALLY | FLIP_VERTICALLY; else return 0; case ORIENTATION_BOTRIGHT: case ORIENTATION_RIGHTBOT: if (img->req_orientation == ORIENTATION_TOPLEFT || img->req_orientation == ORIENTATION_LEFTTOP) return FLIP_HORIZONTALLY | FLIP_VERTICALLY; else if (img->req_orientation == ORIENTATION_TOPRIGHT || img->req_orientation == ORIENTATION_RIGHTTOP) return FLIP_VERTICALLY; else if (img->req_orientation == ORIENTATION_BOTLEFT || img->req_orientation == ORIENTATION_LEFTBOT) return FLIP_HORIZONTALLY; else return 0; case ORIENTATION_BOTLEFT: case ORIENTATION_LEFTBOT: if (img->req_orientation == ORIENTATION_TOPLEFT || img->req_orientation == ORIENTATION_LEFTTOP) return FLIP_VERTICALLY; else if (img->req_orientation == ORIENTATION_TOPRIGHT || img->req_orientation == ORIENTATION_RIGHTTOP) return FLIP_HORIZONTALLY | FLIP_VERTICALLY; else if (img->req_orientation == ORIENTATION_BOTRIGHT || img->req_orientation == ORIENTATION_RIGHTBOT) return FLIP_HORIZONTALLY; else return 0; default: /* NOTREACHED */ return 0; } } /* * Get an tile-organized image that has * PlanarConfiguration contiguous if SamplesPerPixel > 1 * or * SamplesPerPixel == 1 */ static int gtTileContig(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h) { TIFF* tif = img->tif; tileContigRoutine put = img->put.contig; uint32 col, row, y, rowstoread; tmsize_t pos; uint32 tw, th; unsigned char* buf = NULL; int32 fromskew, toskew; uint32 nrow; int ret = 1, flip; uint32 this_tw, tocol; int32 this_toskew, leftmost_toskew; int32 leftmost_fromskew; uint32 leftmost_tw; tmsize_t bufsize; bufsize = TIFFTileSize(tif); if (bufsize == 0) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "%s", "No space for tile buffer"); return (0); } TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(tif, TIFFTAG_TILELENGTH, &th); flip = setorientation(img); if (flip & FLIP_VERTICALLY) { y = h - 1; toskew = -(int32)(tw + w); } else { y = 0; toskew = -(int32)(tw - w); } /* * Leftmost tile is clipped on left side if col_offset > 0. */ leftmost_fromskew = img->col_offset % tw; leftmost_tw = tw - leftmost_fromskew; leftmost_toskew = toskew + leftmost_fromskew; for (row = 0; ret != 0 && row < h; row += nrow) { rowstoread = th - (row + img->row_offset) % th; nrow = (row + rowstoread > h ? h - row : rowstoread); fromskew = leftmost_fromskew; this_tw = leftmost_tw; this_toskew = leftmost_toskew; tocol = 0; col = img->col_offset; while (tocol < w) { if (_TIFFReadTileAndAllocBuffer(tif, (void**) &buf, bufsize, col, row+img->row_offset, 0, 0)==(tmsize_t)(-1) && (buf == NULL || img->stoponerr)) { ret = 0; break; } pos = ((row+img->row_offset) % th) * TIFFTileRowSize(tif) + \ ((tmsize_t) fromskew * img->samplesperpixel); if (tocol + this_tw > w) { /* * Rightmost tile is clipped on right side. */ fromskew = tw - (w - tocol); this_tw = tw - fromskew; this_toskew = toskew + fromskew; } (*put)(img, raster+y*w+tocol, tocol, y, this_tw, nrow, fromskew, this_toskew, buf + pos); tocol += this_tw; col += this_tw; /* * After the leftmost tile, tiles are no longer clipped on left side. */ fromskew = 0; this_tw = tw; this_toskew = toskew; } y += ((flip & FLIP_VERTICALLY) ? -(int32) nrow : (int32) nrow); } _TIFFfree(buf); if (flip & FLIP_HORIZONTALLY) { uint32 line; for (line = 0; line < h; line++) { uint32 *left = raster + (line * w); uint32 *right = left + w - 1; while ( left < right ) { uint32 temp = *left; *left = *right; *right = temp; left++; right--; } } } return (ret); } /* * Get an tile-organized image that has * SamplesPerPixel > 1 * PlanarConfiguration separated * We assume that all such images are RGB. */ static int gtTileSeparate(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h) { TIFF* tif = img->tif; tileSeparateRoutine put = img->put.separate; uint32 col, row, y, rowstoread; tmsize_t pos; uint32 tw, th; unsigned char* buf = NULL; unsigned char* p0 = NULL; unsigned char* p1 = NULL; unsigned char* p2 = NULL; unsigned char* pa = NULL; tmsize_t tilesize; tmsize_t bufsize; int32 fromskew, toskew; int alpha = img->alpha; uint32 nrow; int ret = 1, flip; uint16 colorchannels; uint32 this_tw, tocol; int32 this_toskew, leftmost_toskew; int32 leftmost_fromskew; uint32 leftmost_tw; tilesize = TIFFTileSize(tif); bufsize = _TIFFMultiplySSize(tif, alpha?4:3,tilesize, "gtTileSeparate"); if (bufsize == 0) { return (0); } TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(tif, TIFFTAG_TILELENGTH, &th); flip = setorientation(img); if (flip & FLIP_VERTICALLY) { y = h - 1; toskew = -(int32)(tw + w); } else { y = 0; toskew = -(int32)(tw - w); } switch( img->photometric ) { case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: case PHOTOMETRIC_PALETTE: colorchannels = 1; break; default: colorchannels = 3; break; } /* * Leftmost tile is clipped on left side if col_offset > 0. */ leftmost_fromskew = img->col_offset % tw; leftmost_tw = tw - leftmost_fromskew; leftmost_toskew = toskew + leftmost_fromskew; for (row = 0; ret != 0 && row < h; row += nrow) { rowstoread = th - (row + img->row_offset) % th; nrow = (row + rowstoread > h ? h - row : rowstoread); fromskew = leftmost_fromskew; this_tw = leftmost_tw; this_toskew = leftmost_toskew; tocol = 0; col = img->col_offset; while (tocol < w) { if( buf == NULL ) { if (_TIFFReadTileAndAllocBuffer( tif, (void**) &buf, bufsize, col, row+img->row_offset,0,0)==(tmsize_t)(-1) && (buf == NULL || img->stoponerr)) { ret = 0; break; } p0 = buf; if( colorchannels == 1 ) { p2 = p1 = p0; pa = (alpha?(p0+3*tilesize):NULL); } else { p1 = p0 + tilesize; p2 = p1 + tilesize; pa = (alpha?(p2+tilesize):NULL); } } else if (TIFFReadTile(tif, p0, col, row+img->row_offset,0,0)==(tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } if (colorchannels > 1 && TIFFReadTile(tif, p1, col, row+img->row_offset,0,1) == (tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } if (colorchannels > 1 && TIFFReadTile(tif, p2, col, row+img->row_offset,0,2) == (tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } if (alpha && TIFFReadTile(tif,pa,col, row+img->row_offset,0,colorchannels) == (tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } pos = ((row+img->row_offset) % th) * TIFFTileRowSize(tif) + \ ((tmsize_t) fromskew * img->samplesperpixel); if (tocol + this_tw > w) { /* * Rightmost tile is clipped on right side. */ fromskew = tw - (w - tocol); this_tw = tw - fromskew; this_toskew = toskew + fromskew; } (*put)(img, raster+y*w+tocol, tocol, y, this_tw, nrow, fromskew, this_toskew, \ p0 + pos, p1 + pos, p2 + pos, (alpha?(pa+pos):NULL)); tocol += this_tw; col += this_tw; /* * After the leftmost tile, tiles are no longer clipped on left side. */ fromskew = 0; this_tw = tw; this_toskew = toskew; } y += ((flip & FLIP_VERTICALLY) ?-(int32) nrow : (int32) nrow); } if (flip & FLIP_HORIZONTALLY) { uint32 line; for (line = 0; line < h; line++) { uint32 *left = raster + (line * w); uint32 *right = left + w - 1; while ( left < right ) { uint32 temp = *left; *left = *right; *right = temp; left++; right--; } } } _TIFFfree(buf); return (ret); } /* * Get a strip-organized image that has * PlanarConfiguration contiguous if SamplesPerPixel > 1 * or * SamplesPerPixel == 1 */ static int gtStripContig(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h) { TIFF* tif = img->tif; tileContigRoutine put = img->put.contig; uint32 row, y, nrow, nrowsub, rowstoread; tmsize_t pos; unsigned char* buf = NULL; uint32 rowsperstrip; uint16 subsamplinghor,subsamplingver; uint32 imagewidth = img->width; tmsize_t scanline; int32 fromskew, toskew; int ret = 1, flip; tmsize_t maxstripsize; TIFFGetFieldDefaulted(tif, TIFFTAG_YCBCRSUBSAMPLING, &subsamplinghor, &subsamplingver); if( subsamplingver == 0 ) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "Invalid vertical YCbCr subsampling"); return (0); } maxstripsize = TIFFStripSize(tif); flip = setorientation(img); if (flip & FLIP_VERTICALLY) { y = h - 1; toskew = -(int32)(w + w); } else { y = 0; toskew = -(int32)(w - w); } TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); scanline = TIFFScanlineSize(tif); fromskew = (w < imagewidth ? imagewidth - w : 0); for (row = 0; row < h; row += nrow) { uint32 temp; rowstoread = rowsperstrip - (row + img->row_offset) % rowsperstrip; nrow = (row + rowstoread > h ? h - row : rowstoread); nrowsub = nrow; if ((nrowsub%subsamplingver)!=0) nrowsub+=subsamplingver-nrowsub%subsamplingver; temp = (row + img->row_offset)%rowsperstrip + nrowsub; if( scanline > 0 && temp > (size_t)(TIFF_TMSIZE_T_MAX / scanline) ) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "Integer overflow in gtStripContig"); return 0; } if (_TIFFReadEncodedStripAndAllocBuffer(tif, TIFFComputeStrip(tif,row+img->row_offset, 0), (void**)(&buf), maxstripsize, temp * scanline)==(tmsize_t)(-1) && (buf == NULL || img->stoponerr)) { ret = 0; break; } pos = ((row + img->row_offset) % rowsperstrip) * scanline + \ ((tmsize_t) img->col_offset * img->samplesperpixel); (*put)(img, raster+y*w, 0, y, w, nrow, fromskew, toskew, buf + pos); y += ((flip & FLIP_VERTICALLY) ? -(int32) nrow : (int32) nrow); } if (flip & FLIP_HORIZONTALLY) { uint32 line; for (line = 0; line < h; line++) { uint32 *left = raster + (line * w); uint32 *right = left + w - 1; while ( left < right ) { uint32 temp = *left; *left = *right; *right = temp; left++; right--; } } } _TIFFfree(buf); return (ret); } /* * Get a strip-organized image with * SamplesPerPixel > 1 * PlanarConfiguration separated * We assume that all such images are RGB. */ static int gtStripSeparate(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h) { TIFF* tif = img->tif; tileSeparateRoutine put = img->put.separate; unsigned char *buf = NULL; unsigned char *p0 = NULL, *p1 = NULL, *p2 = NULL, *pa = NULL; uint32 row, y, nrow, rowstoread; tmsize_t pos; tmsize_t scanline; uint32 rowsperstrip, offset_row; uint32 imagewidth = img->width; tmsize_t stripsize; tmsize_t bufsize; int32 fromskew, toskew; int alpha = img->alpha; int ret = 1, flip; uint16 colorchannels; stripsize = TIFFStripSize(tif); bufsize = _TIFFMultiplySSize(tif,alpha?4:3,stripsize, "gtStripSeparate"); if (bufsize == 0) { return (0); } flip = setorientation(img); if (flip & FLIP_VERTICALLY) { y = h - 1; toskew = -(int32)(w + w); } else { y = 0; toskew = -(int32)(w - w); } switch( img->photometric ) { case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: case PHOTOMETRIC_PALETTE: colorchannels = 1; break; default: colorchannels = 3; break; } TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); scanline = TIFFScanlineSize(tif); fromskew = (w < imagewidth ? imagewidth - w : 0); for (row = 0; row < h; row += nrow) { uint32 temp; rowstoread = rowsperstrip - (row + img->row_offset) % rowsperstrip; nrow = (row + rowstoread > h ? h - row : rowstoread); offset_row = row + img->row_offset; temp = (row + img->row_offset)%rowsperstrip + nrow; if( scanline > 0 && temp > (size_t)(TIFF_TMSIZE_T_MAX / scanline) ) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "Integer overflow in gtStripSeparate"); return 0; } if( buf == NULL ) { if (_TIFFReadEncodedStripAndAllocBuffer( tif, TIFFComputeStrip(tif, offset_row, 0), (void**) &buf, bufsize, temp * scanline)==(tmsize_t)(-1) && (buf == NULL || img->stoponerr)) { ret = 0; break; } p0 = buf; if( colorchannels == 1 ) { p2 = p1 = p0; pa = (alpha?(p0+3*stripsize):NULL); } else { p1 = p0 + stripsize; p2 = p1 + stripsize; pa = (alpha?(p2+stripsize):NULL); } } else if (TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, offset_row, 0), p0, temp * scanline)==(tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } if (colorchannels > 1 && TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, offset_row, 1), p1, temp * scanline) == (tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } if (colorchannels > 1 && TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, offset_row, 2), p2, temp * scanline) == (tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } if (alpha) { if (TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, offset_row, colorchannels), pa, temp * scanline)==(tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } } pos = ((row + img->row_offset) % rowsperstrip) * scanline + \ ((tmsize_t) img->col_offset * img->samplesperpixel); (*put)(img, raster+y*w, 0, y, w, nrow, fromskew, toskew, p0 + pos, p1 + pos, p2 + pos, (alpha?(pa+pos):NULL)); y += ((flip & FLIP_VERTICALLY) ? -(int32) nrow : (int32) nrow); } if (flip & FLIP_HORIZONTALLY) { uint32 line; for (line = 0; line < h; line++) { uint32 *left = raster + (line * w); uint32 *right = left + w - 1; while ( left < right ) { uint32 temp = *left; *left = *right; *right = temp; left++; right--; } } } _TIFFfree(buf); return (ret); } /* * The following routines move decoded data returned * from the TIFF library into rasters filled with packed * ABGR pixels (i.e. suitable for passing to lrecwrite.) * * The routines have been created according to the most * important cases and optimized. PickContigCase and * PickSeparateCase analyze the parameters and select * the appropriate "get" and "put" routine to use. */ #define REPEAT8(op) REPEAT4(op); REPEAT4(op) #define REPEAT4(op) REPEAT2(op); REPEAT2(op) #define REPEAT2(op) op; op #define CASE8(x,op) \ switch (x) { \ case 7: op; /*-fallthrough*/ \ case 6: op; /*-fallthrough*/ \ case 5: op; /*-fallthrough*/ \ case 4: op; /*-fallthrough*/ \ case 3: op; /*-fallthrough*/ \ case 2: op; /*-fallthrough*/ \ case 1: op; \ } #define CASE4(x,op) switch (x) { case 3: op; /*-fallthrough*/ case 2: op; /*-fallthrough*/ case 1: op; } #define NOP #define UNROLL8(w, op1, op2) { \ uint32 _x; \ for (_x = w; _x >= 8; _x -= 8) { \ op1; \ REPEAT8(op2); \ } \ if (_x > 0) { \ op1; \ CASE8(_x,op2); \ } \ } #define UNROLL4(w, op1, op2) { \ uint32 _x; \ for (_x = w; _x >= 4; _x -= 4) { \ op1; \ REPEAT4(op2); \ } \ if (_x > 0) { \ op1; \ CASE4(_x,op2); \ } \ } #define UNROLL2(w, op1, op2) { \ uint32 _x; \ for (_x = w; _x >= 2; _x -= 2) { \ op1; \ REPEAT2(op2); \ } \ if (_x) { \ op1; \ op2; \ } \ } #define SKEW(r,g,b,skew) { r += skew; g += skew; b += skew; } #define SKEW4(r,g,b,a,skew) { r += skew; g += skew; b += skew; a+= skew; } #define A1 (((uint32)0xffL)<<24) #define PACK(r,g,b) \ ((uint32)(r)|((uint32)(g)<<8)|((uint32)(b)<<16)|A1) #define PACK4(r,g,b,a) \ ((uint32)(r)|((uint32)(g)<<8)|((uint32)(b)<<16)|((uint32)(a)<<24)) #define W2B(v) (((v)>>8)&0xff) /* TODO: PACKW should have be made redundant in favor of Bitdepth16To8 LUT */ #define PACKW(r,g,b) \ ((uint32)W2B(r)|((uint32)W2B(g)<<8)|((uint32)W2B(b)<<16)|A1) #define PACKW4(r,g,b,a) \ ((uint32)W2B(r)|((uint32)W2B(g)<<8)|((uint32)W2B(b)<<16)|((uint32)W2B(a)<<24)) #define DECLAREContigPutFunc(name) \ static void name(\ TIFFRGBAImage* img, \ uint32* cp, \ uint32 x, uint32 y, \ uint32 w, uint32 h, \ int32 fromskew, int32 toskew, \ unsigned char* pp \ ) /* * 8-bit palette => colormap/RGB */ DECLAREContigPutFunc(put8bitcmaptile) { uint32** PALmap = img->PALmap; int samplesperpixel = img->samplesperpixel; (void) y; for( ; h > 0; --h) { for (x = w; x > 0; --x) { *cp++ = PALmap[*pp][0]; pp += samplesperpixel; } cp += toskew; pp += fromskew; } } /* * 4-bit palette => colormap/RGB */ DECLAREContigPutFunc(put4bitcmaptile) { uint32** PALmap = img->PALmap; (void) x; (void) y; fromskew /= 2; for( ; h > 0; --h) { uint32* bw; UNROLL2(w, bw = PALmap[*pp++], *cp++ = *bw++); cp += toskew; pp += fromskew; } } /* * 2-bit palette => colormap/RGB */ DECLAREContigPutFunc(put2bitcmaptile) { uint32** PALmap = img->PALmap; (void) x; (void) y; fromskew /= 4; for( ; h > 0; --h) { uint32* bw; UNROLL4(w, bw = PALmap[*pp++], *cp++ = *bw++); cp += toskew; pp += fromskew; } } /* * 1-bit palette => colormap/RGB */ DECLAREContigPutFunc(put1bitcmaptile) { uint32** PALmap = img->PALmap; (void) x; (void) y; fromskew /= 8; for( ; h > 0; --h) { uint32* bw; UNROLL8(w, bw = PALmap[*pp++], *cp++ = *bw++); cp += toskew; pp += fromskew; } } /* * 8-bit greyscale => colormap/RGB */ DECLAREContigPutFunc(putgreytile) { int samplesperpixel = img->samplesperpixel; uint32** BWmap = img->BWmap; (void) y; for( ; h > 0; --h) { for (x = w; x > 0; --x) { *cp++ = BWmap[*pp][0]; pp += samplesperpixel; } cp += toskew; pp += fromskew; } } /* * 8-bit greyscale with associated alpha => colormap/RGBA */ DECLAREContigPutFunc(putagreytile) { int samplesperpixel = img->samplesperpixel; uint32** BWmap = img->BWmap; (void) y; for( ; h > 0; --h) { for (x = w; x > 0; --x) { *cp++ = BWmap[*pp][0] & ((uint32)*(pp+1) << 24 | ~A1); pp += samplesperpixel; } cp += toskew; pp += fromskew; } } /* * 16-bit greyscale => colormap/RGB */ DECLAREContigPutFunc(put16bitbwtile) { int samplesperpixel = img->samplesperpixel; uint32** BWmap = img->BWmap; (void) y; for( ; h > 0; --h) { uint16 *wp = (uint16 *) pp; for (x = w; x > 0; --x) { /* use high order byte of 16bit value */ *cp++ = BWmap[*wp >> 8][0]; pp += 2 * samplesperpixel; wp += samplesperpixel; } cp += toskew; pp += fromskew; } } /* * 1-bit bilevel => colormap/RGB */ DECLAREContigPutFunc(put1bitbwtile) { uint32** BWmap = img->BWmap; (void) x; (void) y; fromskew /= 8; for( ; h > 0; --h) { uint32* bw; UNROLL8(w, bw = BWmap[*pp++], *cp++ = *bw++); cp += toskew; pp += fromskew; } } /* * 2-bit greyscale => colormap/RGB */ DECLAREContigPutFunc(put2bitbwtile) { uint32** BWmap = img->BWmap; (void) x; (void) y; fromskew /= 4; for( ; h > 0; --h) { uint32* bw; UNROLL4(w, bw = BWmap[*pp++], *cp++ = *bw++); cp += toskew; pp += fromskew; } } /* * 4-bit greyscale => colormap/RGB */ DECLAREContigPutFunc(put4bitbwtile) { uint32** BWmap = img->BWmap; (void) x; (void) y; fromskew /= 2; for( ; h > 0; --h) { uint32* bw; UNROLL2(w, bw = BWmap[*pp++], *cp++ = *bw++); cp += toskew; pp += fromskew; } } /* * 8-bit packed samples, no Map => RGB */ DECLAREContigPutFunc(putRGBcontig8bittile) { int samplesperpixel = img->samplesperpixel; (void) x; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { UNROLL8(w, NOP, *cp++ = PACK(pp[0], pp[1], pp[2]); pp += samplesperpixel); cp += toskew; pp += fromskew; } } /* * 8-bit packed samples => RGBA w/ associated alpha * (known to have Map == NULL) */ DECLAREContigPutFunc(putRGBAAcontig8bittile) { int samplesperpixel = img->samplesperpixel; (void) x; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { UNROLL8(w, NOP, *cp++ = PACK4(pp[0], pp[1], pp[2], pp[3]); pp += samplesperpixel); cp += toskew; pp += fromskew; } } /* * 8-bit packed samples => RGBA w/ unassociated alpha * (known to have Map == NULL) */ DECLAREContigPutFunc(putRGBUAcontig8bittile) { int samplesperpixel = img->samplesperpixel; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { uint32 r, g, b, a; uint8* m; for (x = w; x > 0; --x) { a = pp[3]; m = img->UaToAa+((size_t) a<<8); r = m[pp[0]]; g = m[pp[1]]; b = m[pp[2]]; *cp++ = PACK4(r,g,b,a); pp += samplesperpixel; } cp += toskew; pp += fromskew; } } /* * 16-bit packed samples => RGB */ DECLAREContigPutFunc(putRGBcontig16bittile) { int samplesperpixel = img->samplesperpixel; uint16 *wp = (uint16 *)pp; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { for (x = w; x > 0; --x) { *cp++ = PACK(img->Bitdepth16To8[wp[0]], img->Bitdepth16To8[wp[1]], img->Bitdepth16To8[wp[2]]); wp += samplesperpixel; } cp += toskew; wp += fromskew; } } /* * 16-bit packed samples => RGBA w/ associated alpha * (known to have Map == NULL) */ DECLAREContigPutFunc(putRGBAAcontig16bittile) { int samplesperpixel = img->samplesperpixel; uint16 *wp = (uint16 *)pp; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { for (x = w; x > 0; --x) { *cp++ = PACK4(img->Bitdepth16To8[wp[0]], img->Bitdepth16To8[wp[1]], img->Bitdepth16To8[wp[2]], img->Bitdepth16To8[wp[3]]); wp += samplesperpixel; } cp += toskew; wp += fromskew; } } /* * 16-bit packed samples => RGBA w/ unassociated alpha * (known to have Map == NULL) */ DECLAREContigPutFunc(putRGBUAcontig16bittile) { int samplesperpixel = img->samplesperpixel; uint16 *wp = (uint16 *)pp; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { uint32 r,g,b,a; uint8* m; for (x = w; x > 0; --x) { a = img->Bitdepth16To8[wp[3]]; m = img->UaToAa+((size_t) a<<8); r = m[img->Bitdepth16To8[wp[0]]]; g = m[img->Bitdepth16To8[wp[1]]]; b = m[img->Bitdepth16To8[wp[2]]]; *cp++ = PACK4(r,g,b,a); wp += samplesperpixel; } cp += toskew; wp += fromskew; } } /* * 8-bit packed CMYK samples w/o Map => RGB * * NB: The conversion of CMYK->RGB is *very* crude. */ DECLAREContigPutFunc(putRGBcontig8bitCMYKtile) { int samplesperpixel = img->samplesperpixel; uint16 r, g, b, k; (void) x; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { UNROLL8(w, NOP, k = 255 - pp[3]; r = (k*(255-pp[0]))/255; g = (k*(255-pp[1]))/255; b = (k*(255-pp[2]))/255; *cp++ = PACK(r, g, b); pp += samplesperpixel); cp += toskew; pp += fromskew; } } /* * 8-bit packed CMYK samples w/Map => RGB * * NB: The conversion of CMYK->RGB is *very* crude. */ DECLAREContigPutFunc(putRGBcontig8bitCMYKMaptile) { int samplesperpixel = img->samplesperpixel; TIFFRGBValue* Map = img->Map; uint16 r, g, b, k; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { for (x = w; x > 0; --x) { k = 255 - pp[3]; r = (k*(255-pp[0]))/255; g = (k*(255-pp[1]))/255; b = (k*(255-pp[2]))/255; *cp++ = PACK(Map[r], Map[g], Map[b]); pp += samplesperpixel; } pp += fromskew; cp += toskew; } } #define DECLARESepPutFunc(name) \ static void name(\ TIFFRGBAImage* img,\ uint32* cp,\ uint32 x, uint32 y, \ uint32 w, uint32 h,\ int32 fromskew, int32 toskew,\ unsigned char* r, unsigned char* g, unsigned char* b, unsigned char* a\ ) /* * 8-bit unpacked samples => RGB */ DECLARESepPutFunc(putRGBseparate8bittile) { (void) img; (void) x; (void) y; (void) a; for( ; h > 0; --h) { UNROLL8(w, NOP, *cp++ = PACK(*r++, *g++, *b++)); SKEW(r, g, b, fromskew); cp += toskew; } } /* * 8-bit unpacked samples => RGBA w/ associated alpha */ DECLARESepPutFunc(putRGBAAseparate8bittile) { (void) img; (void) x; (void) y; for( ; h > 0; --h) { UNROLL8(w, NOP, *cp++ = PACK4(*r++, *g++, *b++, *a++)); SKEW4(r, g, b, a, fromskew); cp += toskew; } } /* * 8-bit unpacked CMYK samples => RGBA */ DECLARESepPutFunc(putCMYKseparate8bittile) { (void) img; (void) y; for( ; h > 0; --h) { uint32 rv, gv, bv, kv; for (x = w; x > 0; --x) { kv = 255 - *a++; rv = (kv*(255-*r++))/255; gv = (kv*(255-*g++))/255; bv = (kv*(255-*b++))/255; *cp++ = PACK4(rv,gv,bv,255); } SKEW4(r, g, b, a, fromskew); cp += toskew; } } /* * 8-bit unpacked samples => RGBA w/ unassociated alpha */ DECLARESepPutFunc(putRGBUAseparate8bittile) { (void) img; (void) y; for( ; h > 0; --h) { uint32 rv, gv, bv, av; uint8* m; for (x = w; x > 0; --x) { av = *a++; m = img->UaToAa+((size_t) av<<8); rv = m[*r++]; gv = m[*g++]; bv = m[*b++]; *cp++ = PACK4(rv,gv,bv,av); } SKEW4(r, g, b, a, fromskew); cp += toskew; } } /* * 16-bit unpacked samples => RGB */ DECLARESepPutFunc(putRGBseparate16bittile) { uint16 *wr = (uint16*) r; uint16 *wg = (uint16*) g; uint16 *wb = (uint16*) b; (void) img; (void) y; (void) a; for( ; h > 0; --h) { for (x = 0; x < w; x++) *cp++ = PACK(img->Bitdepth16To8[*wr++], img->Bitdepth16To8[*wg++], img->Bitdepth16To8[*wb++]); SKEW(wr, wg, wb, fromskew); cp += toskew; } } /* * 16-bit unpacked samples => RGBA w/ associated alpha */ DECLARESepPutFunc(putRGBAAseparate16bittile) { uint16 *wr = (uint16*) r; uint16 *wg = (uint16*) g; uint16 *wb = (uint16*) b; uint16 *wa = (uint16*) a; (void) img; (void) y; for( ; h > 0; --h) { for (x = 0; x < w; x++) *cp++ = PACK4(img->Bitdepth16To8[*wr++], img->Bitdepth16To8[*wg++], img->Bitdepth16To8[*wb++], img->Bitdepth16To8[*wa++]); SKEW4(wr, wg, wb, wa, fromskew); cp += toskew; } } /* * 16-bit unpacked samples => RGBA w/ unassociated alpha */ DECLARESepPutFunc(putRGBUAseparate16bittile) { uint16 *wr = (uint16*) r; uint16 *wg = (uint16*) g; uint16 *wb = (uint16*) b; uint16 *wa = (uint16*) a; (void) img; (void) y; for( ; h > 0; --h) { uint32 r2,g2,b2,a2; uint8* m; for (x = w; x > 0; --x) { a2 = img->Bitdepth16To8[*wa++]; m = img->UaToAa+((size_t) a2<<8); r2 = m[img->Bitdepth16To8[*wr++]]; g2 = m[img->Bitdepth16To8[*wg++]]; b2 = m[img->Bitdepth16To8[*wb++]]; *cp++ = PACK4(r2,g2,b2,a2); } SKEW4(wr, wg, wb, wa, fromskew); cp += toskew; } } /* * 8-bit packed CIE L*a*b 1976 samples => RGB */ DECLAREContigPutFunc(putcontig8bitCIELab) { float X, Y, Z; uint32 r, g, b; (void) y; fromskew *= 3; for( ; h > 0; --h) { for (x = w; x > 0; --x) { TIFFCIELabToXYZ(img->cielab, (unsigned char)pp[0], (signed char)pp[1], (signed char)pp[2], &X, &Y, &Z); TIFFXYZToRGB(img->cielab, X, Y, Z, &r, &g, &b); *cp++ = PACK(r, g, b); pp += 3; } cp += toskew; pp += fromskew; } } /* * YCbCr -> RGB conversion and packing routines. */ #define YCbCrtoRGB(dst, Y) { \ uint32 r, g, b; \ TIFFYCbCrtoRGB(img->ycbcr, (Y), Cb, Cr, &r, &g, &b); \ dst = PACK(r, g, b); \ } /* * 8-bit packed YCbCr samples => RGB * This function is generic for different sampling sizes, * and can handle blocks sizes that aren't multiples of the * sampling size. However, it is substantially less optimized * than the specific sampling cases. It is used as a fallback * for difficult blocks. */ #ifdef notdef static void putcontig8bitYCbCrGenericTile( TIFFRGBAImage* img, uint32* cp, uint32 x, uint32 y, uint32 w, uint32 h, int32 fromskew, int32 toskew, unsigned char* pp, int h_group, int v_group ) { uint32* cp1 = cp+w+toskew; uint32* cp2 = cp1+w+toskew; uint32* cp3 = cp2+w+toskew; int32 incr = 3*w+4*toskew; int32 Cb, Cr; int group_size = v_group * h_group + 2; (void) y; fromskew = (fromskew * group_size) / h_group; for( yy = 0; yy < h; yy++ ) { unsigned char *pp_line; int y_line_group = yy / v_group; int y_remainder = yy - y_line_group * v_group; pp_line = pp + v_line_group * for( xx = 0; xx < w; xx++ ) { Cb = pp } } for (; h >= 4; h -= 4) { x = w>>2; do { Cb = pp[16]; Cr = pp[17]; YCbCrtoRGB(cp [0], pp[ 0]); YCbCrtoRGB(cp [1], pp[ 1]); YCbCrtoRGB(cp [2], pp[ 2]); YCbCrtoRGB(cp [3], pp[ 3]); YCbCrtoRGB(cp1[0], pp[ 4]); YCbCrtoRGB(cp1[1], pp[ 5]); YCbCrtoRGB(cp1[2], pp[ 6]); YCbCrtoRGB(cp1[3], pp[ 7]); YCbCrtoRGB(cp2[0], pp[ 8]); YCbCrtoRGB(cp2[1], pp[ 9]); YCbCrtoRGB(cp2[2], pp[10]); YCbCrtoRGB(cp2[3], pp[11]); YCbCrtoRGB(cp3[0], pp[12]); YCbCrtoRGB(cp3[1], pp[13]); YCbCrtoRGB(cp3[2], pp[14]); YCbCrtoRGB(cp3[3], pp[15]); cp += 4, cp1 += 4, cp2 += 4, cp3 += 4; pp += 18; } while (--x); cp += incr, cp1 += incr, cp2 += incr, cp3 += incr; pp += fromskew; } } #endif /* * 8-bit packed YCbCr samples w/ 4,4 subsampling => RGB */ DECLAREContigPutFunc(putcontig8bitYCbCr44tile) { uint32* cp1 = cp+w+toskew; uint32* cp2 = cp1+w+toskew; uint32* cp3 = cp2+w+toskew; int32 incr = 3*w+4*toskew; (void) y; /* adjust fromskew */ fromskew = (fromskew / 4) * (4*2+2); if ((h & 3) == 0 && (w & 3) == 0) { for (; h >= 4; h -= 4) { x = w>>2; do { int32 Cb = pp[16]; int32 Cr = pp[17]; YCbCrtoRGB(cp [0], pp[ 0]); YCbCrtoRGB(cp [1], pp[ 1]); YCbCrtoRGB(cp [2], pp[ 2]); YCbCrtoRGB(cp [3], pp[ 3]); YCbCrtoRGB(cp1[0], pp[ 4]); YCbCrtoRGB(cp1[1], pp[ 5]); YCbCrtoRGB(cp1[2], pp[ 6]); YCbCrtoRGB(cp1[3], pp[ 7]); YCbCrtoRGB(cp2[0], pp[ 8]); YCbCrtoRGB(cp2[1], pp[ 9]); YCbCrtoRGB(cp2[2], pp[10]); YCbCrtoRGB(cp2[3], pp[11]); YCbCrtoRGB(cp3[0], pp[12]); YCbCrtoRGB(cp3[1], pp[13]); YCbCrtoRGB(cp3[2], pp[14]); YCbCrtoRGB(cp3[3], pp[15]); cp += 4; cp1 += 4; cp2 += 4; cp3 += 4; pp += 18; } while (--x); cp += incr; cp1 += incr; cp2 += incr; cp3 += incr; pp += fromskew; } } else { while (h > 0) { for (x = w; x > 0;) { int32 Cb = pp[16]; int32 Cr = pp[17]; switch (x) { default: switch (h) { default: YCbCrtoRGB(cp3[3], pp[15]); /* FALLTHROUGH */ case 3: YCbCrtoRGB(cp2[3], pp[11]); /* FALLTHROUGH */ case 2: YCbCrtoRGB(cp1[3], pp[ 7]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [3], pp[ 3]); /* FALLTHROUGH */ } /* FALLTHROUGH */ case 3: switch (h) { default: YCbCrtoRGB(cp3[2], pp[14]); /* FALLTHROUGH */ case 3: YCbCrtoRGB(cp2[2], pp[10]); /* FALLTHROUGH */ case 2: YCbCrtoRGB(cp1[2], pp[ 6]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [2], pp[ 2]); /* FALLTHROUGH */ } /* FALLTHROUGH */ case 2: switch (h) { default: YCbCrtoRGB(cp3[1], pp[13]); /* FALLTHROUGH */ case 3: YCbCrtoRGB(cp2[1], pp[ 9]); /* FALLTHROUGH */ case 2: YCbCrtoRGB(cp1[1], pp[ 5]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [1], pp[ 1]); /* FALLTHROUGH */ } /* FALLTHROUGH */ case 1: switch (h) { default: YCbCrtoRGB(cp3[0], pp[12]); /* FALLTHROUGH */ case 3: YCbCrtoRGB(cp2[0], pp[ 8]); /* FALLTHROUGH */ case 2: YCbCrtoRGB(cp1[0], pp[ 4]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [0], pp[ 0]); /* FALLTHROUGH */ } /* FALLTHROUGH */ } if (x < 4) { cp += x; cp1 += x; cp2 += x; cp3 += x; x = 0; } else { cp += 4; cp1 += 4; cp2 += 4; cp3 += 4; x -= 4; } pp += 18; } if (h <= 4) break; h -= 4; cp += incr; cp1 += incr; cp2 += incr; cp3 += incr; pp += fromskew; } } } /* * 8-bit packed YCbCr samples w/ 4,2 subsampling => RGB */ DECLAREContigPutFunc(putcontig8bitYCbCr42tile) { uint32* cp1 = cp+w+toskew; int32 incr = 2*toskew+w; (void) y; fromskew = (fromskew / 4) * (4*2+2); if ((w & 3) == 0 && (h & 1) == 0) { for (; h >= 2; h -= 2) { x = w>>2; do { int32 Cb = pp[8]; int32 Cr = pp[9]; YCbCrtoRGB(cp [0], pp[0]); YCbCrtoRGB(cp [1], pp[1]); YCbCrtoRGB(cp [2], pp[2]); YCbCrtoRGB(cp [3], pp[3]); YCbCrtoRGB(cp1[0], pp[4]); YCbCrtoRGB(cp1[1], pp[5]); YCbCrtoRGB(cp1[2], pp[6]); YCbCrtoRGB(cp1[3], pp[7]); cp += 4; cp1 += 4; pp += 10; } while (--x); cp += incr; cp1 += incr; pp += fromskew; } } else { while (h > 0) { for (x = w; x > 0;) { int32 Cb = pp[8]; int32 Cr = pp[9]; switch (x) { default: switch (h) { default: YCbCrtoRGB(cp1[3], pp[ 7]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [3], pp[ 3]); /* FALLTHROUGH */ } /* FALLTHROUGH */ case 3: switch (h) { default: YCbCrtoRGB(cp1[2], pp[ 6]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [2], pp[ 2]); /* FALLTHROUGH */ } /* FALLTHROUGH */ case 2: switch (h) { default: YCbCrtoRGB(cp1[1], pp[ 5]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [1], pp[ 1]); /* FALLTHROUGH */ } /* FALLTHROUGH */ case 1: switch (h) { default: YCbCrtoRGB(cp1[0], pp[ 4]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [0], pp[ 0]); /* FALLTHROUGH */ } /* FALLTHROUGH */ } if (x < 4) { cp += x; cp1 += x; x = 0; } else { cp += 4; cp1 += 4; x -= 4; } pp += 10; } if (h <= 2) break; h -= 2; cp += incr; cp1 += incr; pp += fromskew; } } } /* * 8-bit packed YCbCr samples w/ 4,1 subsampling => RGB */ DECLAREContigPutFunc(putcontig8bitYCbCr41tile) { (void) y; fromskew = (fromskew / 4) * (4*1+2); do { x = w>>2; while(x>0) { int32 Cb = pp[4]; int32 Cr = pp[5]; YCbCrtoRGB(cp [0], pp[0]); YCbCrtoRGB(cp [1], pp[1]); YCbCrtoRGB(cp [2], pp[2]); YCbCrtoRGB(cp [3], pp[3]); cp += 4; pp += 6; x--; } if( (w&3) != 0 ) { int32 Cb = pp[4]; int32 Cr = pp[5]; switch( (w&3) ) { case 3: YCbCrtoRGB(cp [2], pp[2]); /*-fallthrough*/ case 2: YCbCrtoRGB(cp [1], pp[1]); /*-fallthrough*/ case 1: YCbCrtoRGB(cp [0], pp[0]); /*-fallthrough*/ case 0: break; } cp += (w&3); pp += 6; } cp += toskew; pp += fromskew; } while (--h); } /* * 8-bit packed YCbCr samples w/ 2,2 subsampling => RGB */ DECLAREContigPutFunc(putcontig8bitYCbCr22tile) { uint32* cp2; int32 incr = 2*toskew+w; (void) y; fromskew = (fromskew / 2) * (2*2+2); cp2 = cp+w+toskew; while (h>=2) { x = w; while (x>=2) { uint32 Cb = pp[4]; uint32 Cr = pp[5]; YCbCrtoRGB(cp[0], pp[0]); YCbCrtoRGB(cp[1], pp[1]); YCbCrtoRGB(cp2[0], pp[2]); YCbCrtoRGB(cp2[1], pp[3]); cp += 2; cp2 += 2; pp += 6; x -= 2; } if (x==1) { uint32 Cb = pp[4]; uint32 Cr = pp[5]; YCbCrtoRGB(cp[0], pp[0]); YCbCrtoRGB(cp2[0], pp[2]); cp ++ ; cp2 ++ ; pp += 6; } cp += incr; cp2 += incr; pp += fromskew; h-=2; } if (h==1) { x = w; while (x>=2) { uint32 Cb = pp[4]; uint32 Cr = pp[5]; YCbCrtoRGB(cp[0], pp[0]); YCbCrtoRGB(cp[1], pp[1]); cp += 2; cp2 += 2; pp += 6; x -= 2; } if (x==1) { uint32 Cb = pp[4]; uint32 Cr = pp[5]; YCbCrtoRGB(cp[0], pp[0]); } } } /* * 8-bit packed YCbCr samples w/ 2,1 subsampling => RGB */ DECLAREContigPutFunc(putcontig8bitYCbCr21tile) { (void) y; fromskew = (fromskew / 2) * (2*1+2); do { x = w>>1; while(x>0) { int32 Cb = pp[2]; int32 Cr = pp[3]; YCbCrtoRGB(cp[0], pp[0]); YCbCrtoRGB(cp[1], pp[1]); cp += 2; pp += 4; x --; } if( (w&1) != 0 ) { int32 Cb = pp[2]; int32 Cr = pp[3]; YCbCrtoRGB(cp[0], pp[0]); cp += 1; pp += 4; } cp += toskew; pp += fromskew; } while (--h); } /* * 8-bit packed YCbCr samples w/ 1,2 subsampling => RGB */ DECLAREContigPutFunc(putcontig8bitYCbCr12tile) { uint32* cp2; int32 incr = 2*toskew+w; (void) y; fromskew = (fromskew / 1) * (1 * 2 + 2); cp2 = cp+w+toskew; while (h>=2) { x = w; do { uint32 Cb = pp[2]; uint32 Cr = pp[3]; YCbCrtoRGB(cp[0], pp[0]); YCbCrtoRGB(cp2[0], pp[1]); cp ++; cp2 ++; pp += 4; } while (--x); cp += incr; cp2 += incr; pp += fromskew; h-=2; } if (h==1) { x = w; do { uint32 Cb = pp[2]; uint32 Cr = pp[3]; YCbCrtoRGB(cp[0], pp[0]); cp ++; pp += 4; } while (--x); } } /* * 8-bit packed YCbCr samples w/ no subsampling => RGB */ DECLAREContigPutFunc(putcontig8bitYCbCr11tile) { (void) y; fromskew = (fromskew / 1) * (1 * 1 + 2); do { x = w; /* was x = w>>1; patched 2000/09/25 warmerda@home.com */ do { int32 Cb = pp[1]; int32 Cr = pp[2]; YCbCrtoRGB(*cp++, pp[0]); pp += 3; } while (--x); cp += toskew; pp += fromskew; } while (--h); } /* * 8-bit packed YCbCr samples w/ no subsampling => RGB */ DECLARESepPutFunc(putseparate8bitYCbCr11tile) { (void) y; (void) a; /* TODO: naming of input vars is still off, change obfuscating declaration inside define, or resolve obfuscation */ for( ; h > 0; --h) { x = w; do { uint32 dr, dg, db; TIFFYCbCrtoRGB(img->ycbcr,*r++,*g++,*b++,&dr,&dg,&db); *cp++ = PACK(dr,dg,db); } while (--x); SKEW(r, g, b, fromskew); cp += toskew; } } #undef YCbCrtoRGB static int isInRefBlackWhiteRange(float f) { return f > (float)(-0x7FFFFFFF + 128) && f < (float)0x7FFFFFFF; } static int initYCbCrConversion(TIFFRGBAImage* img) { static const char module[] = "initYCbCrConversion"; float *luma, *refBlackWhite; if (img->ycbcr == NULL) { img->ycbcr = (TIFFYCbCrToRGB*) _TIFFmalloc( TIFFroundup_32(sizeof (TIFFYCbCrToRGB), sizeof (long)) + 4*256*sizeof (TIFFRGBValue) + 2*256*sizeof (int) + 3*256*sizeof (int32) ); if (img->ycbcr == NULL) { TIFFErrorExt(img->tif->tif_clientdata, module, "No space for YCbCr->RGB conversion state"); return (0); } } TIFFGetFieldDefaulted(img->tif, TIFFTAG_YCBCRCOEFFICIENTS, &luma); TIFFGetFieldDefaulted(img->tif, TIFFTAG_REFERENCEBLACKWHITE, &refBlackWhite); /* Do some validation to avoid later issues. Detect NaN for now */ /* and also if lumaGreen is zero since we divide by it later */ if( luma[0] != luma[0] || luma[1] != luma[1] || luma[1] == 0.0 || luma[2] != luma[2] ) { TIFFErrorExt(img->tif->tif_clientdata, module, "Invalid values for YCbCrCoefficients tag"); return (0); } if( !isInRefBlackWhiteRange(refBlackWhite[0]) || !isInRefBlackWhiteRange(refBlackWhite[1]) || !isInRefBlackWhiteRange(refBlackWhite[2]) || !isInRefBlackWhiteRange(refBlackWhite[3]) || !isInRefBlackWhiteRange(refBlackWhite[4]) || !isInRefBlackWhiteRange(refBlackWhite[5]) ) { TIFFErrorExt(img->tif->tif_clientdata, module, "Invalid values for ReferenceBlackWhite tag"); return (0); } if (TIFFYCbCrToRGBInit(img->ycbcr, luma, refBlackWhite) < 0) return(0); return (1); } static tileContigRoutine initCIELabConversion(TIFFRGBAImage* img) { static const char module[] = "initCIELabConversion"; float *whitePoint; float refWhite[3]; TIFFGetFieldDefaulted(img->tif, TIFFTAG_WHITEPOINT, &whitePoint); if (whitePoint[1] == 0.0f ) { TIFFErrorExt(img->tif->tif_clientdata, module, "Invalid value for WhitePoint tag."); return NULL; } if (!img->cielab) { img->cielab = (TIFFCIELabToRGB *) _TIFFmalloc(sizeof(TIFFCIELabToRGB)); if (!img->cielab) { TIFFErrorExt(img->tif->tif_clientdata, module, "No space for CIE L*a*b*->RGB conversion state."); return NULL; } } refWhite[1] = 100.0F; refWhite[0] = whitePoint[0] / whitePoint[1] * refWhite[1]; refWhite[2] = (1.0F - whitePoint[0] - whitePoint[1]) / whitePoint[1] * refWhite[1]; if (TIFFCIELabToRGBInit(img->cielab, &display_sRGB, refWhite) < 0) { TIFFErrorExt(img->tif->tif_clientdata, module, "Failed to initialize CIE L*a*b*->RGB conversion state."); _TIFFfree(img->cielab); return NULL; } return putcontig8bitCIELab; } /* * Greyscale images with less than 8 bits/sample are handled * with a table to avoid lots of shifts and masks. The table * is setup so that put*bwtile (below) can retrieve 8/bitspersample * pixel values simply by indexing into the table with one * number. */ static int makebwmap(TIFFRGBAImage* img) { TIFFRGBValue* Map = img->Map; int bitspersample = img->bitspersample; int nsamples = 8 / bitspersample; int i; uint32* p; if( nsamples == 0 ) nsamples = 1; img->BWmap = (uint32**) _TIFFmalloc( 256*sizeof (uint32 *)+(256*nsamples*sizeof(uint32))); if (img->BWmap == NULL) { TIFFErrorExt(img->tif->tif_clientdata, TIFFFileName(img->tif), "No space for B&W mapping table"); return (0); } p = (uint32*)(img->BWmap + 256); for (i = 0; i < 256; i++) { TIFFRGBValue c; img->BWmap[i] = p; switch (bitspersample) { #define GREY(x) c = Map[x]; *p++ = PACK(c,c,c); case 1: GREY(i>>7); GREY((i>>6)&1); GREY((i>>5)&1); GREY((i>>4)&1); GREY((i>>3)&1); GREY((i>>2)&1); GREY((i>>1)&1); GREY(i&1); break; case 2: GREY(i>>6); GREY((i>>4)&3); GREY((i>>2)&3); GREY(i&3); break; case 4: GREY(i>>4); GREY(i&0xf); break; case 8: case 16: GREY(i); break; } #undef GREY } return (1); } /* * Construct a mapping table to convert from the range * of the data samples to [0,255] --for display. This * process also handles inverting B&W images when needed. */ static int setupMap(TIFFRGBAImage* img) { int32 x, range; range = (int32)((1L<<img->bitspersample)-1); /* treat 16 bit the same as eight bit */ if( img->bitspersample == 16 ) range = (int32) 255; img->Map = (TIFFRGBValue*) _TIFFmalloc((range+1) * sizeof (TIFFRGBValue)); if (img->Map == NULL) { TIFFErrorExt(img->tif->tif_clientdata, TIFFFileName(img->tif), "No space for photometric conversion table"); return (0); } if (img->photometric == PHOTOMETRIC_MINISWHITE) { for (x = 0; x <= range; x++) img->Map[x] = (TIFFRGBValue) (((range - x) * 255) / range); } else { for (x = 0; x <= range; x++) img->Map[x] = (TIFFRGBValue) ((x * 255) / range); } if (img->bitspersample <= 16 && (img->photometric == PHOTOMETRIC_MINISBLACK || img->photometric == PHOTOMETRIC_MINISWHITE)) { /* * Use photometric mapping table to construct * unpacking tables for samples <= 8 bits. */ if (!makebwmap(img)) return (0); /* no longer need Map, free it */ _TIFFfree(img->Map); img->Map = NULL; } return (1); } static int checkcmap(TIFFRGBAImage* img) { uint16* r = img->redcmap; uint16* g = img->greencmap; uint16* b = img->bluecmap; long n = 1L<<img->bitspersample; while (n-- > 0) if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256) return (16); return (8); } static void cvtcmap(TIFFRGBAImage* img) { uint16* r = img->redcmap; uint16* g = img->greencmap; uint16* b = img->bluecmap; long i; for (i = (1L<<img->bitspersample)-1; i >= 0; i--) { #define CVT(x) ((uint16)((x)>>8)) r[i] = CVT(r[i]); g[i] = CVT(g[i]); b[i] = CVT(b[i]); #undef CVT } } /* * Palette images with <= 8 bits/sample are handled * with a table to avoid lots of shifts and masks. The table * is setup so that put*cmaptile (below) can retrieve 8/bitspersample * pixel values simply by indexing into the table with one * number. */ static int makecmap(TIFFRGBAImage* img) { int bitspersample = img->bitspersample; int nsamples = 8 / bitspersample; uint16* r = img->redcmap; uint16* g = img->greencmap; uint16* b = img->bluecmap; uint32 *p; int i; img->PALmap = (uint32**) _TIFFmalloc( 256*sizeof (uint32 *)+(256*nsamples*sizeof(uint32))); if (img->PALmap == NULL) { TIFFErrorExt(img->tif->tif_clientdata, TIFFFileName(img->tif), "No space for Palette mapping table"); return (0); } p = (uint32*)(img->PALmap + 256); for (i = 0; i < 256; i++) { TIFFRGBValue c; img->PALmap[i] = p; #define CMAP(x) c = (TIFFRGBValue) x; *p++ = PACK(r[c]&0xff, g[c]&0xff, b[c]&0xff); switch (bitspersample) { case 1: CMAP(i>>7); CMAP((i>>6)&1); CMAP((i>>5)&1); CMAP((i>>4)&1); CMAP((i>>3)&1); CMAP((i>>2)&1); CMAP((i>>1)&1); CMAP(i&1); break; case 2: CMAP(i>>6); CMAP((i>>4)&3); CMAP((i>>2)&3); CMAP(i&3); break; case 4: CMAP(i>>4); CMAP(i&0xf); break; case 8: CMAP(i); break; } #undef CMAP } return (1); } /* * Construct any mapping table used * by the associated put routine. */ static int buildMap(TIFFRGBAImage* img) { switch (img->photometric) { case PHOTOMETRIC_RGB: case PHOTOMETRIC_YCBCR: case PHOTOMETRIC_SEPARATED: if (img->bitspersample == 8) break; /* fall through... */ case PHOTOMETRIC_MINISBLACK: case PHOTOMETRIC_MINISWHITE: if (!setupMap(img)) return (0); break; case PHOTOMETRIC_PALETTE: /* * Convert 16-bit colormap to 8-bit (unless it looks * like an old-style 8-bit colormap). */ if (checkcmap(img) == 16) cvtcmap(img); else TIFFWarningExt(img->tif->tif_clientdata, TIFFFileName(img->tif), "Assuming 8-bit colormap"); /* * Use mapping table and colormap to construct * unpacking tables for samples < 8 bits. */ if (img->bitspersample <= 8 && !makecmap(img)) return (0); break; } return (1); } /* * Select the appropriate conversion routine for packed data. */ static int PickContigCase(TIFFRGBAImage* img) { img->get = TIFFIsTiled(img->tif) ? gtTileContig : gtStripContig; img->put.contig = NULL; switch (img->photometric) { case PHOTOMETRIC_RGB: switch (img->bitspersample) { case 8: if (img->alpha == EXTRASAMPLE_ASSOCALPHA && img->samplesperpixel >= 4) img->put.contig = putRGBAAcontig8bittile; else if (img->alpha == EXTRASAMPLE_UNASSALPHA && img->samplesperpixel >= 4) { if (BuildMapUaToAa(img)) img->put.contig = putRGBUAcontig8bittile; } else if( img->samplesperpixel >= 3 ) img->put.contig = putRGBcontig8bittile; break; case 16: if (img->alpha == EXTRASAMPLE_ASSOCALPHA && img->samplesperpixel >=4 ) { if (BuildMapBitdepth16To8(img)) img->put.contig = putRGBAAcontig16bittile; } else if (img->alpha == EXTRASAMPLE_UNASSALPHA && img->samplesperpixel >=4 ) { if (BuildMapBitdepth16To8(img) && BuildMapUaToAa(img)) img->put.contig = putRGBUAcontig16bittile; } else if( img->samplesperpixel >=3 ) { if (BuildMapBitdepth16To8(img)) img->put.contig = putRGBcontig16bittile; } break; } break; case PHOTOMETRIC_SEPARATED: if (img->samplesperpixel >=4 && buildMap(img)) { if (img->bitspersample == 8) { if (!img->Map) img->put.contig = putRGBcontig8bitCMYKtile; else img->put.contig = putRGBcontig8bitCMYKMaptile; } } break; case PHOTOMETRIC_PALETTE: if (buildMap(img)) { switch (img->bitspersample) { case 8: img->put.contig = put8bitcmaptile; break; case 4: img->put.contig = put4bitcmaptile; break; case 2: img->put.contig = put2bitcmaptile; break; case 1: img->put.contig = put1bitcmaptile; break; } } break; case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: if (buildMap(img)) { switch (img->bitspersample) { case 16: img->put.contig = put16bitbwtile; break; case 8: if (img->alpha && img->samplesperpixel == 2) img->put.contig = putagreytile; else img->put.contig = putgreytile; break; case 4: img->put.contig = put4bitbwtile; break; case 2: img->put.contig = put2bitbwtile; break; case 1: img->put.contig = put1bitbwtile; break; } } break; case PHOTOMETRIC_YCBCR: if ((img->bitspersample==8) && (img->samplesperpixel==3)) { if (initYCbCrConversion(img)!=0) { /* * The 6.0 spec says that subsampling must be * one of 1, 2, or 4, and that vertical subsampling * must always be <= horizontal subsampling; so * there are only a few possibilities and we just * enumerate the cases. * Joris: added support for the [1,2] case, nonetheless, to accommodate * some OJPEG files */ uint16 SubsamplingHor; uint16 SubsamplingVer; TIFFGetFieldDefaulted(img->tif, TIFFTAG_YCBCRSUBSAMPLING, &SubsamplingHor, &SubsamplingVer); switch ((SubsamplingHor<<4)|SubsamplingVer) { case 0x44: img->put.contig = putcontig8bitYCbCr44tile; break; case 0x42: img->put.contig = putcontig8bitYCbCr42tile; break; case 0x41: img->put.contig = putcontig8bitYCbCr41tile; break; case 0x22: img->put.contig = putcontig8bitYCbCr22tile; break; case 0x21: img->put.contig = putcontig8bitYCbCr21tile; break; case 0x12: img->put.contig = putcontig8bitYCbCr12tile; break; case 0x11: img->put.contig = putcontig8bitYCbCr11tile; break; } } } break; case PHOTOMETRIC_CIELAB: if (img->samplesperpixel == 3 && buildMap(img)) { if (img->bitspersample == 8) img->put.contig = initCIELabConversion(img); break; } } return ((img->get!=NULL) && (img->put.contig!=NULL)); } /* * Select the appropriate conversion routine for unpacked data. * * NB: we assume that unpacked single channel data is directed * to the "packed routines. */ static int PickSeparateCase(TIFFRGBAImage* img) { img->get = TIFFIsTiled(img->tif) ? gtTileSeparate : gtStripSeparate; img->put.separate = NULL; switch (img->photometric) { case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: /* greyscale images processed pretty much as RGB by gtTileSeparate */ case PHOTOMETRIC_RGB: switch (img->bitspersample) { case 8: if (img->alpha == EXTRASAMPLE_ASSOCALPHA) img->put.separate = putRGBAAseparate8bittile; else if (img->alpha == EXTRASAMPLE_UNASSALPHA) { if (BuildMapUaToAa(img)) img->put.separate = putRGBUAseparate8bittile; } else img->put.separate = putRGBseparate8bittile; break; case 16: if (img->alpha == EXTRASAMPLE_ASSOCALPHA) { if (BuildMapBitdepth16To8(img)) img->put.separate = putRGBAAseparate16bittile; } else if (img->alpha == EXTRASAMPLE_UNASSALPHA) { if (BuildMapBitdepth16To8(img) && BuildMapUaToAa(img)) img->put.separate = putRGBUAseparate16bittile; } else { if (BuildMapBitdepth16To8(img)) img->put.separate = putRGBseparate16bittile; } break; } break; case PHOTOMETRIC_SEPARATED: if (img->bitspersample == 8 && img->samplesperpixel == 4) { img->alpha = 1; // Not alpha, but seems like the only way to get 4th band img->put.separate = putCMYKseparate8bittile; } break; case PHOTOMETRIC_YCBCR: if ((img->bitspersample==8) && (img->samplesperpixel==3)) { if (initYCbCrConversion(img)!=0) { uint16 hs, vs; TIFFGetFieldDefaulted(img->tif, TIFFTAG_YCBCRSUBSAMPLING, &hs, &vs); switch ((hs<<4)|vs) { case 0x11: img->put.separate = putseparate8bitYCbCr11tile; break; /* TODO: add other cases here */ } } } break; } return ((img->get!=NULL) && (img->put.separate!=NULL)); } static int BuildMapUaToAa(TIFFRGBAImage* img) { static const char module[]="BuildMapUaToAa"; uint8* m; uint16 na,nv; assert(img->UaToAa==NULL); img->UaToAa=_TIFFmalloc(65536); if (img->UaToAa==NULL) { TIFFErrorExt(img->tif->tif_clientdata,module,"Out of memory"); return(0); } m=img->UaToAa; for (na=0; na<256; na++) { for (nv=0; nv<256; nv++) *m++=(uint8)((nv*na+127)/255); } return(1); } static int BuildMapBitdepth16To8(TIFFRGBAImage* img) { static const char module[]="BuildMapBitdepth16To8"; uint8* m; uint32 n; assert(img->Bitdepth16To8==NULL); img->Bitdepth16To8=_TIFFmalloc(65536); if (img->Bitdepth16To8==NULL) { TIFFErrorExt(img->tif->tif_clientdata,module,"Out of memory"); return(0); } m=img->Bitdepth16To8; for (n=0; n<65536; n++) *m++=(uint8)((n+128)/257); return(1); } /* * Read a whole strip off data from the file, and convert to RGBA form. * If this is the last strip, then it will only contain the portion of * the strip that is actually within the image space. The result is * organized in bottom to top form. */ int TIFFReadRGBAStrip(TIFF* tif, uint32 row, uint32 * raster ) { return TIFFReadRGBAStripExt(tif, row, raster, 0 ); } int TIFFReadRGBAStripExt(TIFF* tif, uint32 row, uint32 * raster, int stop_on_error) { char emsg[1024] = ""; TIFFRGBAImage img; int ok; uint32 rowsperstrip, rows_to_read; if( TIFFIsTiled( tif ) ) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "Can't use TIFFReadRGBAStrip() with tiled file."); return (0); } TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); if( (row % rowsperstrip) != 0 ) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "Row passed to TIFFReadRGBAStrip() must be first in a strip."); return (0); } if (TIFFRGBAImageOK(tif, emsg) && TIFFRGBAImageBegin(&img, tif, stop_on_error, emsg)) { img.row_offset = row; img.col_offset = 0; if( row + rowsperstrip > img.height ) rows_to_read = img.height - row; else rows_to_read = rowsperstrip; ok = TIFFRGBAImageGet(&img, raster, img.width, rows_to_read ); TIFFRGBAImageEnd(&img); } else { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "%s", emsg); ok = 0; } return (ok); } /* * Read a whole tile off data from the file, and convert to RGBA form. * The returned RGBA data is organized from bottom to top of tile, * and may include zeroed areas if the tile extends off the image. */ int TIFFReadRGBATile(TIFF* tif, uint32 col, uint32 row, uint32 * raster) { return TIFFReadRGBATileExt(tif, col, row, raster, 0 ); } int TIFFReadRGBATileExt(TIFF* tif, uint32 col, uint32 row, uint32 * raster, int stop_on_error ) { char emsg[1024] = ""; TIFFRGBAImage img; int ok; uint32 tile_xsize, tile_ysize; uint32 read_xsize, read_ysize; uint32 i_row; /* * Verify that our request is legal - on a tile file, and on a * tile boundary. */ if( !TIFFIsTiled( tif ) ) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "Can't use TIFFReadRGBATile() with striped file."); return (0); } TIFFGetFieldDefaulted(tif, TIFFTAG_TILEWIDTH, &tile_xsize); TIFFGetFieldDefaulted(tif, TIFFTAG_TILELENGTH, &tile_ysize); if( (col % tile_xsize) != 0 || (row % tile_ysize) != 0 ) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "Row/col passed to TIFFReadRGBATile() must be top" "left corner of a tile."); return (0); } /* * Setup the RGBA reader. */ if (!TIFFRGBAImageOK(tif, emsg) || !TIFFRGBAImageBegin(&img, tif, stop_on_error, emsg)) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "%s", emsg); return( 0 ); } /* * The TIFFRGBAImageGet() function doesn't allow us to get off the * edge of the image, even to fill an otherwise valid tile. So we * figure out how much we can read, and fix up the tile buffer to * a full tile configuration afterwards. */ if( row + tile_ysize > img.height ) read_ysize = img.height - row; else read_ysize = tile_ysize; if( col + tile_xsize > img.width ) read_xsize = img.width - col; else read_xsize = tile_xsize; /* * Read the chunk of imagery. */ img.row_offset = row; img.col_offset = col; ok = TIFFRGBAImageGet(&img, raster, read_xsize, read_ysize ); TIFFRGBAImageEnd(&img); /* * If our read was incomplete we will need to fix up the tile by * shifting the data around as if a full tile of data is being returned. * * This is all the more complicated because the image is organized in * bottom to top format. */ if( read_xsize == tile_xsize && read_ysize == tile_ysize ) return( ok ); for( i_row = 0; i_row < read_ysize; i_row++ ) { memmove( raster + (tile_ysize - i_row - 1) * tile_xsize, raster + (read_ysize - i_row - 1) * read_xsize, read_xsize * sizeof(uint32) ); _TIFFmemset( raster + (tile_ysize - i_row - 1) * tile_xsize+read_xsize, 0, sizeof(uint32) * (tile_xsize - read_xsize) ); } for( i_row = read_ysize; i_row < tile_ysize; i_row++ ) { _TIFFmemset( raster + (tile_ysize - i_row - 1) * tile_xsize, 0, sizeof(uint32) * tile_xsize ); } return (ok); } /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
null
147
CWE-787
CVE-2019-18218
/*- * Copyright (c) 2008 Christos Zoulas * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Parse Composite Document Files, the format used in Microsoft Office * document files before they switched to zipped XML. * Info from: http://sc.openoffice.org/compdocfileformat.pdf * * N.B. This is the "Composite Document File" format, and not the * "Compound Document Format", nor the "Channel Definition Format". */ #include "file.h" #ifndef lint FILE_RCSID("@(#)$File: cdf.c,v 1.115 2019/08/23 14:29:14 christos Exp $") #endif #include <assert.h> #ifdef CDF_DEBUG #include <err.h> #endif #include <stdlib.h> #include <unistd.h> #include <string.h> #include <time.h> #include <ctype.h> #include <limits.h> #ifndef EFTYPE #define EFTYPE EINVAL #endif #ifndef SIZE_T_MAX #define SIZE_T_MAX CAST(size_t, ~0ULL) #endif #include "cdf.h" #ifdef CDF_DEBUG #define DPRINTF(a) printf a, fflush(stdout) #else #define DPRINTF(a) #endif static union { char s[4]; uint32_t u; } cdf_bo; #define NEED_SWAP (cdf_bo.u == CAST(uint32_t, 0x01020304)) #define CDF_TOLE8(x) \ (CAST(uint64_t, NEED_SWAP ? _cdf_tole8(x) : CAST(uint64_t, x))) #define CDF_TOLE4(x) \ (CAST(uint32_t, NEED_SWAP ? _cdf_tole4(x) : CAST(uint32_t, x))) #define CDF_TOLE2(x) \ (CAST(uint16_t, NEED_SWAP ? _cdf_tole2(x) : CAST(uint16_t, x))) #define CDF_TOLE(x) (/*CONSTCOND*/sizeof(x) == 2 ? \ CDF_TOLE2(CAST(uint16_t, x)) : \ (/*CONSTCOND*/sizeof(x) == 4 ? \ CDF_TOLE4(CAST(uint32_t, x)) : \ CDF_TOLE8(CAST(uint64_t, x)))) #define CDF_GETUINT32(x, y) cdf_getuint32(x, y) #define CDF_MALLOC(n) cdf_malloc(__FILE__, __LINE__, (n)) #define CDF_REALLOC(p, n) cdf_realloc(__FILE__, __LINE__, (p), (n)) #define CDF_CALLOC(n, u) cdf_calloc(__FILE__, __LINE__, (n), (u)) /*ARGSUSED*/ static void * cdf_malloc(const char *file __attribute__((__unused__)), size_t line __attribute__((__unused__)), size_t n) { DPRINTF(("%s,%" SIZE_T_FORMAT "u: %s %" SIZE_T_FORMAT "u\n", file, line, __func__, n)); return malloc(n); } /*ARGSUSED*/ static void * cdf_realloc(const char *file __attribute__((__unused__)), size_t line __attribute__((__unused__)), void *p, size_t n) { DPRINTF(("%s,%" SIZE_T_FORMAT "u: %s %" SIZE_T_FORMAT "u\n", file, line, __func__, n)); return realloc(p, n); } /*ARGSUSED*/ static void * cdf_calloc(const char *file __attribute__((__unused__)), size_t line __attribute__((__unused__)), size_t n, size_t u) { DPRINTF(("%s,%" SIZE_T_FORMAT "u: %s %" SIZE_T_FORMAT "u %" SIZE_T_FORMAT "u\n", file, line, __func__, n, u)); return calloc(n, u); } /* * swap a short */ static uint16_t _cdf_tole2(uint16_t sv) { uint16_t rv; uint8_t *s = RCAST(uint8_t *, RCAST(void *, &sv)); uint8_t *d = RCAST(uint8_t *, RCAST(void *, &rv)); d[0] = s[1]; d[1] = s[0]; return rv; } /* * swap an int */ static uint32_t _cdf_tole4(uint32_t sv) { uint32_t rv; uint8_t *s = RCAST(uint8_t *, RCAST(void *, &sv)); uint8_t *d = RCAST(uint8_t *, RCAST(void *, &rv)); d[0] = s[3]; d[1] = s[2]; d[2] = s[1]; d[3] = s[0]; return rv; } /* * swap a quad */ static uint64_t _cdf_tole8(uint64_t sv) { uint64_t rv; uint8_t *s = RCAST(uint8_t *, RCAST(void *, &sv)); uint8_t *d = RCAST(uint8_t *, RCAST(void *, &rv)); d[0] = s[7]; d[1] = s[6]; d[2] = s[5]; d[3] = s[4]; d[4] = s[3]; d[5] = s[2]; d[6] = s[1]; d[7] = s[0]; return rv; } /* * grab a uint32_t from a possibly unaligned address, and return it in * the native host order. */ static uint32_t cdf_getuint32(const uint8_t *p, size_t offs) { uint32_t rv; (void)memcpy(&rv, p + offs * sizeof(uint32_t), sizeof(rv)); return CDF_TOLE4(rv); } #define CDF_UNPACK(a) \ (void)memcpy(&(a), &buf[len], sizeof(a)), len += sizeof(a) #define CDF_UNPACKA(a) \ (void)memcpy((a), &buf[len], sizeof(a)), len += sizeof(a) uint16_t cdf_tole2(uint16_t sv) { return CDF_TOLE2(sv); } uint32_t cdf_tole4(uint32_t sv) { return CDF_TOLE4(sv); } uint64_t cdf_tole8(uint64_t sv) { return CDF_TOLE8(sv); } void cdf_swap_header(cdf_header_t *h) { size_t i; h->h_magic = CDF_TOLE8(h->h_magic); h->h_uuid[0] = CDF_TOLE8(h->h_uuid[0]); h->h_uuid[1] = CDF_TOLE8(h->h_uuid[1]); h->h_revision = CDF_TOLE2(h->h_revision); h->h_version = CDF_TOLE2(h->h_version); h->h_byte_order = CDF_TOLE2(h->h_byte_order); h->h_sec_size_p2 = CDF_TOLE2(h->h_sec_size_p2); h->h_short_sec_size_p2 = CDF_TOLE2(h->h_short_sec_size_p2); h->h_num_sectors_in_sat = CDF_TOLE4(h->h_num_sectors_in_sat); h->h_secid_first_directory = CDF_TOLE4(h->h_secid_first_directory); h->h_min_size_standard_stream = CDF_TOLE4(h->h_min_size_standard_stream); h->h_secid_first_sector_in_short_sat = CDF_TOLE4(CAST(uint32_t, h->h_secid_first_sector_in_short_sat)); h->h_num_sectors_in_short_sat = CDF_TOLE4(h->h_num_sectors_in_short_sat); h->h_secid_first_sector_in_master_sat = CDF_TOLE4(CAST(uint32_t, h->h_secid_first_sector_in_master_sat)); h->h_num_sectors_in_master_sat = CDF_TOLE4(h->h_num_sectors_in_master_sat); for (i = 0; i < __arraycount(h->h_master_sat); i++) { h->h_master_sat[i] = CDF_TOLE4(CAST(uint32_t, h->h_master_sat[i])); } } void cdf_unpack_header(cdf_header_t *h, char *buf) { size_t i; size_t len = 0; CDF_UNPACK(h->h_magic); CDF_UNPACKA(h->h_uuid); CDF_UNPACK(h->h_revision); CDF_UNPACK(h->h_version); CDF_UNPACK(h->h_byte_order); CDF_UNPACK(h->h_sec_size_p2); CDF_UNPACK(h->h_short_sec_size_p2); CDF_UNPACKA(h->h_unused0); CDF_UNPACK(h->h_num_sectors_in_sat); CDF_UNPACK(h->h_secid_first_directory); CDF_UNPACKA(h->h_unused1); CDF_UNPACK(h->h_min_size_standard_stream); CDF_UNPACK(h->h_secid_first_sector_in_short_sat); CDF_UNPACK(h->h_num_sectors_in_short_sat); CDF_UNPACK(h->h_secid_first_sector_in_master_sat); CDF_UNPACK(h->h_num_sectors_in_master_sat); for (i = 0; i < __arraycount(h->h_master_sat); i++) CDF_UNPACK(h->h_master_sat[i]); } void cdf_swap_dir(cdf_directory_t *d) { d->d_namelen = CDF_TOLE2(d->d_namelen); d->d_left_child = CDF_TOLE4(CAST(uint32_t, d->d_left_child)); d->d_right_child = CDF_TOLE4(CAST(uint32_t, d->d_right_child)); d->d_storage = CDF_TOLE4(CAST(uint32_t, d->d_storage)); d->d_storage_uuid[0] = CDF_TOLE8(d->d_storage_uuid[0]); d->d_storage_uuid[1] = CDF_TOLE8(d->d_storage_uuid[1]); d->d_flags = CDF_TOLE4(d->d_flags); d->d_created = CDF_TOLE8(CAST(uint64_t, d->d_created)); d->d_modified = CDF_TOLE8(CAST(uint64_t, d->d_modified)); d->d_stream_first_sector = CDF_TOLE4( CAST(uint32_t, d->d_stream_first_sector)); d->d_size = CDF_TOLE4(d->d_size); } void cdf_swap_class(cdf_classid_t *d) { d->cl_dword = CDF_TOLE4(d->cl_dword); d->cl_word[0] = CDF_TOLE2(d->cl_word[0]); d->cl_word[1] = CDF_TOLE2(d->cl_word[1]); } void cdf_unpack_dir(cdf_directory_t *d, char *buf) { size_t len = 0; CDF_UNPACKA(d->d_name); CDF_UNPACK(d->d_namelen); CDF_UNPACK(d->d_type); CDF_UNPACK(d->d_color); CDF_UNPACK(d->d_left_child); CDF_UNPACK(d->d_right_child); CDF_UNPACK(d->d_storage); CDF_UNPACKA(d->d_storage_uuid); CDF_UNPACK(d->d_flags); CDF_UNPACK(d->d_created); CDF_UNPACK(d->d_modified); CDF_UNPACK(d->d_stream_first_sector); CDF_UNPACK(d->d_size); CDF_UNPACK(d->d_unused0); } int cdf_zero_stream(cdf_stream_t *scn) { scn->sst_len = 0; scn->sst_dirlen = 0; scn->sst_ss = 0; free(scn->sst_tab); scn->sst_tab = NULL; return -1; } static size_t cdf_check_stream(const cdf_stream_t *sst, const cdf_header_t *h) { size_t ss = sst->sst_dirlen < h->h_min_size_standard_stream ? CDF_SHORT_SEC_SIZE(h) : CDF_SEC_SIZE(h); assert(ss == sst->sst_ss); return sst->sst_ss; } static int cdf_check_stream_offset(const cdf_stream_t *sst, const cdf_header_t *h, const void *p, size_t tail, int line) { const char *b = RCAST(const char *, sst->sst_tab); const char *e = RCAST(const char *, p) + tail; size_t ss = cdf_check_stream(sst, h); /*LINTED*/(void)&line; if (e >= b && CAST(size_t, e - b) <= ss * sst->sst_len) return 0; DPRINTF(("%d: offset begin %p < end %p || %" SIZE_T_FORMAT "u" " > %" SIZE_T_FORMAT "u [%" SIZE_T_FORMAT "u %" SIZE_T_FORMAT "u]\n", line, b, e, (size_t)(e - b), ss * sst->sst_len, ss, sst->sst_len)); errno = EFTYPE; return -1; } static ssize_t cdf_read(const cdf_info_t *info, off_t off, void *buf, size_t len) { size_t siz = CAST(size_t, off + len); if (CAST(off_t, off + len) != CAST(off_t, siz)) goto out; if (info->i_buf != NULL && info->i_len >= siz) { (void)memcpy(buf, &info->i_buf[off], len); return CAST(ssize_t, len); } if (info->i_fd == -1) goto out; if (pread(info->i_fd, buf, len, off) != CAST(ssize_t, len)) return -1; return CAST(ssize_t, len); out: errno = EINVAL; return -1; } int cdf_read_header(const cdf_info_t *info, cdf_header_t *h) { char buf[512]; (void)memcpy(cdf_bo.s, "\01\02\03\04", 4); if (cdf_read(info, CAST(off_t, 0), buf, sizeof(buf)) == -1) return -1; cdf_unpack_header(h, buf); cdf_swap_header(h); if (h->h_magic != CDF_MAGIC) { DPRINTF(("Bad magic %#" INT64_T_FORMAT "x != %#" INT64_T_FORMAT "x\n", (unsigned long long)h->h_magic, (unsigned long long)CDF_MAGIC)); goto out; } if (h->h_sec_size_p2 > 20) { DPRINTF(("Bad sector size %hu\n", h->h_sec_size_p2)); goto out; } if (h->h_short_sec_size_p2 > 20) { DPRINTF(("Bad short sector size %hu\n", h->h_short_sec_size_p2)); goto out; } return 0; out: errno = EFTYPE; return -1; } ssize_t cdf_read_sector(const cdf_info_t *info, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { size_t ss = CDF_SEC_SIZE(h); size_t pos; if (SIZE_T_MAX / ss < CAST(size_t, id)) return -1; pos = CDF_SEC_POS(h, id); assert(ss == len); return cdf_read(info, CAST(off_t, pos), RCAST(char *, buf) + offs, len); } ssize_t cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { size_t ss = CDF_SHORT_SEC_SIZE(h); size_t pos; if (SIZE_T_MAX / ss < CAST(size_t, id)) return -1; pos = CDF_SHORT_SEC_POS(h, id); assert(ss == len); if (pos + len > CDF_SEC_SIZE(h) * sst->sst_len) { DPRINTF(("Out of bounds read %" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", pos + len, CDF_SEC_SIZE(h) * sst->sst_len)); goto out; } (void)memcpy(RCAST(char *, buf) + offs, RCAST(const char *, sst->sst_tab) + pos, len); return len; out: errno = EFTYPE; return -1; } /* * Read the sector allocation table. */ int cdf_read_sat(const cdf_info_t *info, cdf_header_t *h, cdf_sat_t *sat) { size_t i, j, k; size_t ss = CDF_SEC_SIZE(h); cdf_secid_t *msa, mid, sec; size_t nsatpersec = (ss / sizeof(mid)) - 1; for (i = 0; i < __arraycount(h->h_master_sat); i++) if (h->h_master_sat[i] == CDF_SECID_FREE) break; #define CDF_SEC_LIMIT (UINT32_MAX / (64 * ss)) if ((nsatpersec > 0 && h->h_num_sectors_in_master_sat > CDF_SEC_LIMIT / nsatpersec) || i > CDF_SEC_LIMIT) { DPRINTF(("Number of sectors in master SAT too big %u %" SIZE_T_FORMAT "u\n", h->h_num_sectors_in_master_sat, i)); errno = EFTYPE; return -1; } sat->sat_len = h->h_num_sectors_in_master_sat * nsatpersec + i; DPRINTF(("sat_len = %" SIZE_T_FORMAT "u ss = %" SIZE_T_FORMAT "u\n", sat->sat_len, ss)); if ((sat->sat_tab = CAST(cdf_secid_t *, CDF_CALLOC(sat->sat_len, ss))) == NULL) return -1; for (i = 0; i < __arraycount(h->h_master_sat); i++) { if (h->h_master_sat[i] < 0) break; if (cdf_read_sector(info, sat->sat_tab, ss * i, ss, h, h->h_master_sat[i]) != CAST(ssize_t, ss)) { DPRINTF(("Reading sector %d", h->h_master_sat[i])); goto out1; } } if ((msa = CAST(cdf_secid_t *, CDF_CALLOC(1, ss))) == NULL) goto out1; mid = h->h_secid_first_sector_in_master_sat; for (j = 0; j < h->h_num_sectors_in_master_sat; j++) { if (mid < 0) goto out; if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Reading master sector loop limit")); goto out3; } if (cdf_read_sector(info, msa, 0, ss, h, mid) != CAST(ssize_t, ss)) { DPRINTF(("Reading master sector %d", mid)); goto out2; } for (k = 0; k < nsatpersec; k++, i++) { sec = CDF_TOLE4(CAST(uint32_t, msa[k])); if (sec < 0) goto out; if (i >= sat->sat_len) { DPRINTF(("Out of bounds reading MSA %" SIZE_T_FORMAT "u >= %" SIZE_T_FORMAT "u", i, sat->sat_len)); goto out3; } if (cdf_read_sector(info, sat->sat_tab, ss * i, ss, h, sec) != CAST(ssize_t, ss)) { DPRINTF(("Reading sector %d", CDF_TOLE4(msa[k]))); goto out2; } } mid = CDF_TOLE4(CAST(uint32_t, msa[nsatpersec])); } out: sat->sat_len = i; free(msa); return 0; out3: errno = EFTYPE; out2: free(msa); out1: free(sat->sat_tab); return -1; } size_t cdf_count_chain(const cdf_sat_t *sat, cdf_secid_t sid, size_t size) { size_t i, j; cdf_secid_t maxsector = CAST(cdf_secid_t, (sat->sat_len * size) / sizeof(maxsector)); DPRINTF(("Chain:")); if (sid == CDF_SECID_END_OF_CHAIN) { /* 0-length chain. */ DPRINTF((" empty\n")); return 0; } for (j = i = 0; sid >= 0; i++, j++) { DPRINTF((" %d", sid)); if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Counting chain loop limit")); goto out; } if (sid >= maxsector) { DPRINTF(("Sector %d >= %d\n", sid, maxsector)); goto out; } sid = CDF_TOLE4(CAST(uint32_t, sat->sat_tab[sid])); } if (i == 0) { DPRINTF((" none, sid: %d\n", sid)); goto out; } DPRINTF(("\n")); return i; out: errno = EFTYPE; return CAST(size_t, -1); } int cdf_read_long_sector_chain(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { size_t ss = CDF_SEC_SIZE(h), i, j; ssize_t nr; scn->sst_tab = NULL; scn->sst_len = cdf_count_chain(sat, sid, ss); scn->sst_dirlen = MAX(h->h_min_size_standard_stream, len); scn->sst_ss = ss; if (sid == CDF_SECID_END_OF_CHAIN || len == 0) return cdf_zero_stream(scn); if (scn->sst_len == CAST(size_t, -1)) goto out; scn->sst_tab = CDF_CALLOC(scn->sst_len, ss); if (scn->sst_tab == NULL) return cdf_zero_stream(scn); for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read long sector chain loop limit")); goto out; } if (i >= scn->sst_len) { DPRINTF(("Out of bounds reading long sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, scn->sst_len)); goto out; } if ((nr = cdf_read_sector(info, scn->sst_tab, i * ss, ss, h, sid)) != CAST(ssize_t, ss)) { if (i == scn->sst_len - 1 && nr > 0) { /* Last sector might be truncated */ return 0; } DPRINTF(("Reading long sector chain %d", sid)); goto out; } sid = CDF_TOLE4(CAST(uint32_t, sat->sat_tab[sid])); } return 0; out: errno = EFTYPE; return cdf_zero_stream(scn); } int cdf_read_short_sector_chain(const cdf_header_t *h, const cdf_sat_t *ssat, const cdf_stream_t *sst, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { size_t ss = CDF_SHORT_SEC_SIZE(h), i, j; scn->sst_tab = NULL; scn->sst_len = cdf_count_chain(ssat, sid, CDF_SEC_SIZE(h)); scn->sst_dirlen = len; scn->sst_ss = ss; if (scn->sst_len == CAST(size_t, -1)) goto out; scn->sst_tab = CDF_CALLOC(scn->sst_len, ss); if (scn->sst_tab == NULL) return cdf_zero_stream(scn); for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read short sector chain loop limit")); goto out; } if (i >= scn->sst_len) { DPRINTF(("Out of bounds reading short sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, scn->sst_len)); goto out; } if (cdf_read_short_sector(sst, scn->sst_tab, i * ss, ss, h, sid) != CAST(ssize_t, ss)) { DPRINTF(("Reading short sector chain %d", sid)); goto out; } sid = CDF_TOLE4(CAST(uint32_t, ssat->sat_tab[sid])); } return 0; out: errno = EFTYPE; return cdf_zero_stream(scn); } int cdf_read_sector_chain(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { if (len < h->h_min_size_standard_stream && sst->sst_tab != NULL) return cdf_read_short_sector_chain(h, ssat, sst, sid, len, scn); else return cdf_read_long_sector_chain(info, h, sat, sid, len, scn); } int cdf_read_dir(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, cdf_dir_t *dir) { size_t i, j; size_t ss = CDF_SEC_SIZE(h), ns, nd; char *buf; cdf_secid_t sid = h->h_secid_first_directory; ns = cdf_count_chain(sat, sid, ss); if (ns == CAST(size_t, -1)) return -1; nd = ss / CDF_DIRECTORY_SIZE; dir->dir_len = ns * nd; dir->dir_tab = CAST(cdf_directory_t *, CDF_CALLOC(dir->dir_len, sizeof(dir->dir_tab[0]))); if (dir->dir_tab == NULL) return -1; if ((buf = CAST(char *, CDF_MALLOC(ss))) == NULL) { free(dir->dir_tab); return -1; } for (j = i = 0; i < ns; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read dir loop limit")); goto out; } if (cdf_read_sector(info, buf, 0, ss, h, sid) != CAST(ssize_t, ss)) { DPRINTF(("Reading directory sector %d", sid)); goto out; } for (j = 0; j < nd; j++) { cdf_unpack_dir(&dir->dir_tab[i * nd + j], &buf[j * CDF_DIRECTORY_SIZE]); } sid = CDF_TOLE4(CAST(uint32_t, sat->sat_tab[sid])); } if (NEED_SWAP) for (i = 0; i < dir->dir_len; i++) cdf_swap_dir(&dir->dir_tab[i]); free(buf); return 0; out: free(dir->dir_tab); free(buf); errno = EFTYPE; return -1; } int cdf_read_ssat(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, cdf_sat_t *ssat) { size_t i, j; size_t ss = CDF_SEC_SIZE(h); cdf_secid_t sid = h->h_secid_first_sector_in_short_sat; ssat->sat_tab = NULL; ssat->sat_len = cdf_count_chain(sat, sid, ss); if (ssat->sat_len == CAST(size_t, -1)) goto out; ssat->sat_tab = CAST(cdf_secid_t *, CDF_CALLOC(ssat->sat_len, ss)); if (ssat->sat_tab == NULL) goto out1; for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read short sat sector loop limit")); goto out; } if (i >= ssat->sat_len) { DPRINTF(("Out of bounds reading short sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, ssat->sat_len)); goto out; } if (cdf_read_sector(info, ssat->sat_tab, i * ss, ss, h, sid) != CAST(ssize_t, ss)) { DPRINTF(("Reading short sat sector %d", sid)); goto out1; } sid = CDF_TOLE4(CAST(uint32_t, sat->sat_tab[sid])); } return 0; out: errno = EFTYPE; out1: free(ssat->sat_tab); return -1; } int cdf_read_short_stream(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_dir_t *dir, cdf_stream_t *scn, const cdf_directory_t **root) { size_t i; const cdf_directory_t *d; *root = NULL; for (i = 0; i < dir->dir_len; i++) if (dir->dir_tab[i].d_type == CDF_DIR_TYPE_ROOT_STORAGE) break; /* If the it is not there, just fake it; some docs don't have it */ if (i == dir->dir_len) { DPRINTF(("Cannot find root storage dir\n")); goto out; } d = &dir->dir_tab[i]; *root = d; /* If the it is not there, just fake it; some docs don't have it */ if (d->d_stream_first_sector < 0) { DPRINTF(("No first secror in dir\n")); goto out; } return cdf_read_long_sector_chain(info, h, sat, d->d_stream_first_sector, d->d_size, scn); out: scn->sst_tab = NULL; (void)cdf_zero_stream(scn); return 0; } static int cdf_namecmp(const char *d, const uint16_t *s, size_t l) { for (; l--; d++, s++) if (*d != CDF_TOLE2(*s)) return CAST(unsigned char, *d) - CDF_TOLE2(*s); return 0; } int cdf_read_doc_summary_info(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir, cdf_stream_t *scn) { return cdf_read_user_stream(info, h, sat, ssat, sst, dir, "\05DocumentSummaryInformation", scn); } int cdf_read_summary_info(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir, cdf_stream_t *scn) { return cdf_read_user_stream(info, h, sat, ssat, sst, dir, "\05SummaryInformation", scn); } int cdf_read_user_stream(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir, const char *name, cdf_stream_t *scn) { const cdf_directory_t *d; int i = cdf_find_stream(dir, name, CDF_DIR_TYPE_USER_STREAM); if (i <= 0) { memset(scn, 0, sizeof(*scn)); return -1; } d = &dir->dir_tab[i - 1]; return cdf_read_sector_chain(info, h, sat, ssat, sst, d->d_stream_first_sector, d->d_size, scn); } int cdf_find_stream(const cdf_dir_t *dir, const char *name, int type) { size_t i, name_len = strlen(name) + 1; for (i = dir->dir_len; i > 0; i--) if (dir->dir_tab[i - 1].d_type == type && cdf_namecmp(name, dir->dir_tab[i - 1].d_name, name_len) == 0) break; if (i > 0) return CAST(int, i); DPRINTF(("Cannot find type %d `%s'\n", type, name)); errno = ESRCH; return 0; } #define CDF_SHLEN_LIMIT (UINT32_MAX / 64) #define CDF_PROP_LIMIT (UINT32_MAX / (64 * sizeof(cdf_property_info_t))) static const void * cdf_offset(const void *p, size_t l) { return CAST(const void *, CAST(const uint8_t *, p) + l); } static const uint8_t * cdf_get_property_info_pos(const cdf_stream_t *sst, const cdf_header_t *h, const uint8_t *p, const uint8_t *e, size_t i) { size_t tail = (i << 1) + 1; size_t ofs; const uint8_t *q; if (p >= e) { DPRINTF(("Past end %p < %p\n", e, p)); return NULL; } if (cdf_check_stream_offset(sst, h, p, (tail + 1) * sizeof(uint32_t), __LINE__) == -1) return NULL; ofs = CDF_GETUINT32(p, tail); q = CAST(const uint8_t *, cdf_offset(CAST(const void *, p), ofs - 2 * sizeof(uint32_t))); if (q < p) { DPRINTF(("Wrapped around %p < %p\n", q, p)); return NULL; } if (q >= e) { DPRINTF(("Ran off the end %p >= %p\n", q, e)); return NULL; } return q; } static cdf_property_info_t * cdf_grow_info(cdf_property_info_t **info, size_t *maxcount, size_t incr) { cdf_property_info_t *inp; size_t newcount = *maxcount + incr; if (newcount > CDF_PROP_LIMIT) { DPRINTF(("exceeded property limit %" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", newcount, CDF_PROP_LIMIT)); goto out; } inp = CAST(cdf_property_info_t *, CDF_REALLOC(*info, newcount * sizeof(*inp))); if (inp == NULL) goto out; *info = inp; *maxcount = newcount; return inp; out: free(*info); *maxcount = 0; *info = NULL; return NULL; } static int cdf_copy_info(cdf_property_info_t *inp, const void *p, const void *e, size_t len) { if (inp->pi_type & CDF_VECTOR) return 0; if (CAST(size_t, CAST(const char *, e) - CAST(const char *, p)) < len) return 0; (void)memcpy(&inp->pi_val, p, len); switch (len) { case 2: inp->pi_u16 = CDF_TOLE2(inp->pi_u16); break; case 4: inp->pi_u32 = CDF_TOLE4(inp->pi_u32); break; case 8: inp->pi_u64 = CDF_TOLE8(inp->pi_u64); break; default: abort(); } return 1; } int cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h, uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount) { const cdf_section_header_t *shp; cdf_section_header_t sh; const uint8_t *p, *q, *e; size_t i, o4, nelements, j, slen, left; cdf_property_info_t *inp; if (offs > UINT32_MAX / 4) { errno = EFTYPE; goto out; } shp = CAST(const cdf_section_header_t *, cdf_offset(sst->sst_tab, offs)); if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1) goto out; sh.sh_len = CDF_TOLE4(shp->sh_len); if (sh.sh_len > CDF_SHLEN_LIMIT) { errno = EFTYPE; goto out; } if (cdf_check_stream_offset(sst, h, shp, sh.sh_len, __LINE__) == -1) goto out; sh.sh_properties = CDF_TOLE4(shp->sh_properties); DPRINTF(("section len: %u properties %u\n", sh.sh_len, sh.sh_properties)); if (sh.sh_properties > CDF_PROP_LIMIT) goto out; inp = cdf_grow_info(info, maxcount, sh.sh_properties); if (inp == NULL) goto out; inp += *count; *count += sh.sh_properties; p = CAST(const uint8_t *, cdf_offset(sst->sst_tab, offs + sizeof(sh))); e = CAST(const uint8_t *, cdf_offset(shp, sh.sh_len)); if (p >= e || cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1) goto out; for (i = 0; i < sh.sh_properties; i++) { if ((q = cdf_get_property_info_pos(sst, h, p, e, i)) == NULL) goto out; inp[i].pi_id = CDF_GETUINT32(p, i << 1); left = CAST(size_t, e - q); if (left < sizeof(uint32_t)) { DPRINTF(("short info (no type)_\n")); goto out; } inp[i].pi_type = CDF_GETUINT32(q, 0); DPRINTF(("%" SIZE_T_FORMAT "u) id=%#x type=%#x offs=%#tx,%#x\n", i, inp[i].pi_id, inp[i].pi_type, q - p, offs)); if (inp[i].pi_type & CDF_VECTOR) { if (left < sizeof(uint32_t) * 2) { DPRINTF(("missing CDF_VECTOR length\n")); goto out; } nelements = CDF_GETUINT32(q, 1); if (nelements == 0) { DPRINTF(("CDF_VECTOR with nelements == 0\n")); goto out; } slen = 2; } else { nelements = 1; slen = 1; } o4 = slen * sizeof(uint32_t); if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED)) goto unknown; switch (inp[i].pi_type & CDF_TYPEMASK) { case CDF_NULL: case CDF_EMPTY: break; case CDF_SIGNED16: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int16_t))) goto unknown; break; case CDF_SIGNED32: case CDF_BOOL: case CDF_UNSIGNED32: case CDF_FLOAT: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int32_t))) goto unknown; break; case CDF_SIGNED64: case CDF_UNSIGNED64: case CDF_DOUBLE: case CDF_FILETIME: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int64_t))) goto unknown; break; case CDF_LENGTH32_STRING: case CDF_LENGTH32_WSTRING: if (nelements > 1) { size_t nelem = inp - *info; inp = cdf_grow_info(info, maxcount, nelements); if (inp == NULL) goto out; inp += nelem; } DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n", nelements)); for (j = 0; j < nelements && i < sh.sh_properties; j++, i++) { uint32_t l; if (o4 + sizeof(uint32_t) > left) goto out; l = CDF_GETUINT32(q, slen); o4 += sizeof(uint32_t); if (o4 + l > left) goto out; inp[i].pi_str.s_len = l; inp[i].pi_str.s_buf = CAST(const char *, CAST(const void *, &q[o4])); DPRINTF(("o=%" SIZE_T_FORMAT "u l=%d(%" SIZE_T_FORMAT "u), t=%" SIZE_T_FORMAT "u s=%s\n", o4, l, CDF_ROUND(l, sizeof(l)), left, inp[i].pi_str.s_buf)); if (l & 1) l++; slen += l >> 1; o4 = slen * sizeof(uint32_t); } i--; break; case CDF_CLIPBOARD: if (inp[i].pi_type & CDF_VECTOR) goto unknown; break; default: unknown: memset(&inp[i].pi_val, 0, sizeof(inp[i].pi_val)); DPRINTF(("Don't know how to deal with %#x\n", inp[i].pi_type)); break; } } return 0; out: free(*info); *info = NULL; *count = 0; *maxcount = 0; errno = EFTYPE; return -1; } int cdf_unpack_summary_info(const cdf_stream_t *sst, const cdf_header_t *h, cdf_summary_info_header_t *ssi, cdf_property_info_t **info, size_t *count) { size_t maxcount; const cdf_summary_info_header_t *si = CAST(const cdf_summary_info_header_t *, sst->sst_tab); const cdf_section_declaration_t *sd = CAST(const cdf_section_declaration_t *, RCAST(const void *, RCAST(const char *, sst->sst_tab) + CDF_SECTION_DECLARATION_OFFSET)); if (cdf_check_stream_offset(sst, h, si, sizeof(*si), __LINE__) == -1 || cdf_check_stream_offset(sst, h, sd, sizeof(*sd), __LINE__) == -1) return -1; ssi->si_byte_order = CDF_TOLE2(si->si_byte_order); ssi->si_os_version = CDF_TOLE2(si->si_os_version); ssi->si_os = CDF_TOLE2(si->si_os); ssi->si_class = si->si_class; cdf_swap_class(&ssi->si_class); ssi->si_count = CDF_TOLE4(si->si_count); *count = 0; maxcount = 0; *info = NULL; if (cdf_read_property_info(sst, h, CDF_TOLE4(sd->sd_offset), info, count, &maxcount) == -1) return -1; return 0; } #define extract_catalog_field(t, f, l) \ if (b + l + sizeof(cep->f) > eb) { \ cep->ce_namlen = 0; \ break; \ } \ memcpy(&cep->f, b + (l), sizeof(cep->f)); \ ce[i].f = CAST(t, CDF_TOLE(cep->f)) int cdf_unpack_catalog(const cdf_header_t *h, const cdf_stream_t *sst, cdf_catalog_t **cat) { size_t ss = cdf_check_stream(sst, h); const char *b = CAST(const char *, sst->sst_tab); const char *nb, *eb = b + ss * sst->sst_len; size_t nr, i, j, k; cdf_catalog_entry_t *ce; uint16_t reclen; const uint16_t *np; for (nr = 0;; nr++) { memcpy(&reclen, b, sizeof(reclen)); reclen = CDF_TOLE2(reclen); if (reclen == 0) break; b += reclen; if (b > eb) break; } if (nr == 0) return -1; nr--; *cat = CAST(cdf_catalog_t *, CDF_MALLOC(sizeof(cdf_catalog_t) + nr * sizeof(*ce))); if (*cat == NULL) return -1; ce = (*cat)->cat_e; memset(ce, 0, nr * sizeof(*ce)); b = CAST(const char *, sst->sst_tab); for (j = i = 0; i < nr; b += reclen) { cdf_catalog_entry_t *cep = &ce[j]; uint16_t rlen; extract_catalog_field(uint16_t, ce_namlen, 0); extract_catalog_field(uint16_t, ce_num, 4); extract_catalog_field(uint64_t, ce_timestamp, 8); reclen = cep->ce_namlen; if (reclen < 14) { cep->ce_namlen = 0; continue; } cep->ce_namlen = __arraycount(cep->ce_name) - 1; rlen = reclen - 14; if (cep->ce_namlen > rlen) cep->ce_namlen = rlen; np = CAST(const uint16_t *, CAST(const void *, (b + 16))); nb = CAST(const char *, CAST(const void *, (np + cep->ce_namlen))); if (nb > eb) { cep->ce_namlen = 0; break; } for (k = 0; k < cep->ce_namlen; k++) cep->ce_name[k] = np[k]; /* XXX: CDF_TOLE2? */ cep->ce_name[cep->ce_namlen] = 0; j = i; i++; } (*cat)->cat_num = j; return 0; } int cdf_print_classid(char *buf, size_t buflen, const cdf_classid_t *id) { return snprintf(buf, buflen, "%.8x-%.4x-%.4x-%.2x%.2x-" "%.2x%.2x%.2x%.2x%.2x%.2x", id->cl_dword, id->cl_word[0], id->cl_word[1], id->cl_two[0], id->cl_two[1], id->cl_six[0], id->cl_six[1], id->cl_six[2], id->cl_six[3], id->cl_six[4], id->cl_six[5]); } static const struct { uint32_t v; const char *n; } vn[] = { { CDF_PROPERTY_CODE_PAGE, "Code page" }, { CDF_PROPERTY_TITLE, "Title" }, { CDF_PROPERTY_SUBJECT, "Subject" }, { CDF_PROPERTY_AUTHOR, "Author" }, { CDF_PROPERTY_KEYWORDS, "Keywords" }, { CDF_PROPERTY_COMMENTS, "Comments" }, { CDF_PROPERTY_TEMPLATE, "Template" }, { CDF_PROPERTY_LAST_SAVED_BY, "Last Saved By" }, { CDF_PROPERTY_REVISION_NUMBER, "Revision Number" }, { CDF_PROPERTY_TOTAL_EDITING_TIME, "Total Editing Time" }, { CDF_PROPERTY_LAST_PRINTED, "Last Printed" }, { CDF_PROPERTY_CREATE_TIME, "Create Time/Date" }, { CDF_PROPERTY_LAST_SAVED_TIME, "Last Saved Time/Date" }, { CDF_PROPERTY_NUMBER_OF_PAGES, "Number of Pages" }, { CDF_PROPERTY_NUMBER_OF_WORDS, "Number of Words" }, { CDF_PROPERTY_NUMBER_OF_CHARACTERS, "Number of Characters" }, { CDF_PROPERTY_THUMBNAIL, "Thumbnail" }, { CDF_PROPERTY_NAME_OF_APPLICATION, "Name of Creating Application" }, { CDF_PROPERTY_SECURITY, "Security" }, { CDF_PROPERTY_LOCALE_ID, "Locale ID" }, }; int cdf_print_property_name(char *buf, size_t bufsiz, uint32_t p) { size_t i; for (i = 0; i < __arraycount(vn); i++) if (vn[i].v == p) return snprintf(buf, bufsiz, "%s", vn[i].n); return snprintf(buf, bufsiz, "%#x", p); } int cdf_print_elapsed_time(char *buf, size_t bufsiz, cdf_timestamp_t ts) { int len = 0; int days, hours, mins, secs; ts /= CDF_TIME_PREC; secs = CAST(int, ts % 60); ts /= 60; mins = CAST(int, ts % 60); ts /= 60; hours = CAST(int, ts % 24); ts /= 24; days = CAST(int, ts); if (days) { len += snprintf(buf + len, bufsiz - len, "%dd+", days); if (CAST(size_t, len) >= bufsiz) return len; } if (days || hours) { len += snprintf(buf + len, bufsiz - len, "%.2d:", hours); if (CAST(size_t, len) >= bufsiz) return len; } len += snprintf(buf + len, bufsiz - len, "%.2d:", mins); if (CAST(size_t, len) >= bufsiz) return len; len += snprintf(buf + len, bufsiz - len, "%.2d", secs); return len; } char * cdf_u16tos8(char *buf, size_t len, const uint16_t *p) { size_t i; for (i = 0; i < len && p[i]; i++) buf[i] = CAST(char, p[i]); buf[i] = '\0'; return buf; } #ifdef CDF_DEBUG void cdf_dump_header(const cdf_header_t *h) { size_t i; #define DUMP(a, b) (void)fprintf(stderr, "%40.40s = " a "\n", # b, h->h_ ## b) #define DUMP2(a, b) (void)fprintf(stderr, "%40.40s = " a " (" a ")\n", # b, \ h->h_ ## b, 1 << h->h_ ## b) DUMP("%d", revision); DUMP("%d", version); DUMP("%#x", byte_order); DUMP2("%d", sec_size_p2); DUMP2("%d", short_sec_size_p2); DUMP("%d", num_sectors_in_sat); DUMP("%d", secid_first_directory); DUMP("%d", min_size_standard_stream); DUMP("%d", secid_first_sector_in_short_sat); DUMP("%d", num_sectors_in_short_sat); DUMP("%d", secid_first_sector_in_master_sat); DUMP("%d", num_sectors_in_master_sat); for (i = 0; i < __arraycount(h->h_master_sat); i++) { if (h->h_master_sat[i] == CDF_SECID_FREE) break; (void)fprintf(stderr, "%35.35s[%.3" SIZE_T_FORMAT "u] = %d\n", "master_sat", i, h->h_master_sat[i]); } } void cdf_dump_sat(const char *prefix, const cdf_sat_t *sat, size_t size) { size_t i, j, s = size / sizeof(cdf_secid_t); for (i = 0; i < sat->sat_len; i++) { (void)fprintf(stderr, "%s[%" SIZE_T_FORMAT "u]:\n%.6" SIZE_T_FORMAT "u: ", prefix, i, i * s); for (j = 0; j < s; j++) { (void)fprintf(stderr, "%5d, ", CDF_TOLE4(sat->sat_tab[s * i + j])); if ((j + 1) % 10 == 0) (void)fprintf(stderr, "\n%.6" SIZE_T_FORMAT "u: ", i * s + j + 1); } (void)fprintf(stderr, "\n"); } } void cdf_dump(const void *v, size_t len) { size_t i, j; const unsigned char *p = v; char abuf[16]; (void)fprintf(stderr, "%.4x: ", 0); for (i = 0, j = 0; i < len; i++, p++) { (void)fprintf(stderr, "%.2x ", *p); abuf[j++] = isprint(*p) ? *p : '.'; if (j == 16) { j = 0; abuf[15] = '\0'; (void)fprintf(stderr, "%s\n%.4" SIZE_T_FORMAT "x: ", abuf, i + 1); } } (void)fprintf(stderr, "\n"); } void cdf_dump_stream(const cdf_stream_t *sst) { size_t ss = sst->sst_ss; cdf_dump(sst->sst_tab, ss * sst->sst_len); } void cdf_dump_dir(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir) { size_t i, j; cdf_directory_t *d; char name[__arraycount(d->d_name)]; cdf_stream_t scn; struct timespec ts; static const char *types[] = { "empty", "user storage", "user stream", "lockbytes", "property", "root storage" }; for (i = 0; i < dir->dir_len; i++) { char buf[26]; d = &dir->dir_tab[i]; for (j = 0; j < sizeof(name); j++) name[j] = (char)CDF_TOLE2(d->d_name[j]); (void)fprintf(stderr, "Directory %" SIZE_T_FORMAT "u: %s\n", i, name); if (d->d_type < __arraycount(types)) (void)fprintf(stderr, "Type: %s\n", types[d->d_type]); else (void)fprintf(stderr, "Type: %d\n", d->d_type); (void)fprintf(stderr, "Color: %s\n", d->d_color ? "black" : "red"); (void)fprintf(stderr, "Left child: %d\n", d->d_left_child); (void)fprintf(stderr, "Right child: %d\n", d->d_right_child); (void)fprintf(stderr, "Flags: %#x\n", d->d_flags); cdf_timestamp_to_timespec(&ts, d->d_created); (void)fprintf(stderr, "Created %s", cdf_ctime(&ts.tv_sec, buf)); cdf_timestamp_to_timespec(&ts, d->d_modified); (void)fprintf(stderr, "Modified %s", cdf_ctime(&ts.tv_sec, buf)); (void)fprintf(stderr, "Stream %d\n", d->d_stream_first_sector); (void)fprintf(stderr, "Size %d\n", d->d_size); switch (d->d_type) { case CDF_DIR_TYPE_USER_STORAGE: (void)fprintf(stderr, "Storage: %d\n", d->d_storage); break; case CDF_DIR_TYPE_USER_STREAM: if (sst == NULL) break; if (cdf_read_sector_chain(info, h, sat, ssat, sst, d->d_stream_first_sector, d->d_size, &scn) == -1) { warn("Can't read stream for %s at %d len %d", name, d->d_stream_first_sector, d->d_size); break; } cdf_dump_stream(&scn); free(scn.sst_tab); break; default: break; } } } void cdf_dump_property_info(const cdf_property_info_t *info, size_t count) { cdf_timestamp_t tp; struct timespec ts; char buf[64]; size_t i, j; for (i = 0; i < count; i++) { cdf_print_property_name(buf, sizeof(buf), info[i].pi_id); (void)fprintf(stderr, "%" SIZE_T_FORMAT "u) %s: ", i, buf); switch (info[i].pi_type) { case CDF_NULL: break; case CDF_SIGNED16: (void)fprintf(stderr, "signed 16 [%hd]\n", info[i].pi_s16); break; case CDF_SIGNED32: (void)fprintf(stderr, "signed 32 [%d]\n", info[i].pi_s32); break; case CDF_UNSIGNED32: (void)fprintf(stderr, "unsigned 32 [%u]\n", info[i].pi_u32); break; case CDF_FLOAT: (void)fprintf(stderr, "float [%g]\n", info[i].pi_f); break; case CDF_DOUBLE: (void)fprintf(stderr, "double [%g]\n", info[i].pi_d); break; case CDF_LENGTH32_STRING: (void)fprintf(stderr, "string %u [%.*s]\n", info[i].pi_str.s_len, info[i].pi_str.s_len, info[i].pi_str.s_buf); break; case CDF_LENGTH32_WSTRING: (void)fprintf(stderr, "string %u [", info[i].pi_str.s_len); for (j = 0; j < info[i].pi_str.s_len - 1; j++) (void)fputc(info[i].pi_str.s_buf[j << 1], stderr); (void)fprintf(stderr, "]\n"); break; case CDF_FILETIME: tp = info[i].pi_tp; if (tp < 1000000000000000LL) { cdf_print_elapsed_time(buf, sizeof(buf), tp); (void)fprintf(stderr, "timestamp %s\n", buf); } else { char tbuf[26]; cdf_timestamp_to_timespec(&ts, tp); (void)fprintf(stderr, "timestamp %s", cdf_ctime(&ts.tv_sec, tbuf)); } break; case CDF_CLIPBOARD: (void)fprintf(stderr, "CLIPBOARD %u\n", info[i].pi_u32); break; default: DPRINTF(("Don't know how to deal with %#x\n", info[i].pi_type)); break; } } } void cdf_dump_summary_info(const cdf_header_t *h, const cdf_stream_t *sst) { char buf[128]; cdf_summary_info_header_t ssi; cdf_property_info_t *info; size_t count; (void)&h; if (cdf_unpack_summary_info(sst, h, &ssi, &info, &count) == -1) return; (void)fprintf(stderr, "Endian: %#x\n", ssi.si_byte_order); (void)fprintf(stderr, "Os Version %d.%d\n", ssi.si_os_version & 0xff, ssi.si_os_version >> 8); (void)fprintf(stderr, "Os %d\n", ssi.si_os); cdf_print_classid(buf, sizeof(buf), &ssi.si_class); (void)fprintf(stderr, "Class %s\n", buf); (void)fprintf(stderr, "Count %d\n", ssi.si_count); cdf_dump_property_info(info, count); free(info); } void cdf_dump_catalog(const cdf_header_t *h, const cdf_stream_t *sst) { cdf_catalog_t *cat; cdf_unpack_catalog(h, sst, &cat); const cdf_catalog_entry_t *ce = cat->cat_e; struct timespec ts; char tbuf[64], sbuf[256]; size_t i; printf("Catalog:\n"); for (i = 0; i < cat->cat_num; i++) { cdf_timestamp_to_timespec(&ts, ce[i].ce_timestamp); printf("\t%d %s %s", ce[i].ce_num, cdf_u16tos8(sbuf, ce[i].ce_namlen, ce[i].ce_name), cdf_ctime(&ts.tv_sec, tbuf)); } free(cat); } #endif #ifdef TEST int main(int argc, char *argv[]) { int i; cdf_header_t h; cdf_sat_t sat, ssat; cdf_stream_t sst, scn; cdf_dir_t dir; cdf_info_t info; const cdf_directory_t *root; #ifdef __linux__ #define getprogname() __progname extern char *__progname; #endif if (argc < 2) { (void)fprintf(stderr, "Usage: %s <filename>\n", getprogname()); return -1; } info.i_buf = NULL; info.i_len = 0; for (i = 1; i < argc; i++) { if ((info.i_fd = open(argv[1], O_RDONLY)) == -1) err(EXIT_FAILURE, "Cannot open `%s'", argv[1]); if (cdf_read_header(&info, &h) == -1) err(EXIT_FAILURE, "Cannot read header"); #ifdef CDF_DEBUG cdf_dump_header(&h); #endif if (cdf_read_sat(&info, &h, &sat) == -1) err(EXIT_FAILURE, "Cannot read sat"); #ifdef CDF_DEBUG cdf_dump_sat("SAT", &sat, CDF_SEC_SIZE(&h)); #endif if (cdf_read_ssat(&info, &h, &sat, &ssat) == -1) err(EXIT_FAILURE, "Cannot read ssat"); #ifdef CDF_DEBUG cdf_dump_sat("SSAT", &ssat, CDF_SHORT_SEC_SIZE(&h)); #endif if (cdf_read_dir(&info, &h, &sat, &dir) == -1) err(EXIT_FAILURE, "Cannot read dir"); if (cdf_read_short_stream(&info, &h, &sat, &dir, &sst, &root) == -1) err(EXIT_FAILURE, "Cannot read short stream"); #ifdef CDF_DEBUG cdf_dump_stream(&sst); #endif #ifdef CDF_DEBUG cdf_dump_dir(&info, &h, &sat, &ssat, &sst, &dir); #endif if (cdf_read_summary_info(&info, &h, &sat, &ssat, &sst, &dir, &scn) == -1) warn("Cannot read summary info"); #ifdef CDF_DEBUG else cdf_dump_summary_info(&h, &scn); #endif if (cdf_read_user_stream(&info, &h, &sat, &ssat, &sst, &dir, "Catalog", &scn) == -1) warn("Cannot read catalog"); #ifdef CDF_DEBUG else cdf_dump_catalog(&h, &scn); #endif (void)close(info.i_fd); } return 0; } #endif
null
/*- * Copyright (c) 2008 Christos Zoulas * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Parse Composite Document Files, the format used in Microsoft Office * document files before they switched to zipped XML. * Info from: http://sc.openoffice.org/compdocfileformat.pdf * * N.B. This is the "Composite Document File" format, and not the * "Compound Document Format", nor the "Channel Definition Format". */ #include "file.h" #ifndef lint FILE_RCSID("@(#)$File: cdf.c,v 1.116 2019/08/26 14:31:39 christos Exp $") #endif #include <assert.h> #ifdef CDF_DEBUG #include <err.h> #endif #include <stdlib.h> #include <unistd.h> #include <string.h> #include <time.h> #include <ctype.h> #include <limits.h> #ifndef EFTYPE #define EFTYPE EINVAL #endif #ifndef SIZE_T_MAX #define SIZE_T_MAX CAST(size_t, ~0ULL) #endif #include "cdf.h" #ifdef CDF_DEBUG #define DPRINTF(a) printf a, fflush(stdout) #else #define DPRINTF(a) #endif static union { char s[4]; uint32_t u; } cdf_bo; #define NEED_SWAP (cdf_bo.u == CAST(uint32_t, 0x01020304)) #define CDF_TOLE8(x) \ (CAST(uint64_t, NEED_SWAP ? _cdf_tole8(x) : CAST(uint64_t, x))) #define CDF_TOLE4(x) \ (CAST(uint32_t, NEED_SWAP ? _cdf_tole4(x) : CAST(uint32_t, x))) #define CDF_TOLE2(x) \ (CAST(uint16_t, NEED_SWAP ? _cdf_tole2(x) : CAST(uint16_t, x))) #define CDF_TOLE(x) (/*CONSTCOND*/sizeof(x) == 2 ? \ CDF_TOLE2(CAST(uint16_t, x)) : \ (/*CONSTCOND*/sizeof(x) == 4 ? \ CDF_TOLE4(CAST(uint32_t, x)) : \ CDF_TOLE8(CAST(uint64_t, x)))) #define CDF_GETUINT32(x, y) cdf_getuint32(x, y) #define CDF_MALLOC(n) cdf_malloc(__FILE__, __LINE__, (n)) #define CDF_REALLOC(p, n) cdf_realloc(__FILE__, __LINE__, (p), (n)) #define CDF_CALLOC(n, u) cdf_calloc(__FILE__, __LINE__, (n), (u)) /*ARGSUSED*/ static void * cdf_malloc(const char *file __attribute__((__unused__)), size_t line __attribute__((__unused__)), size_t n) { DPRINTF(("%s,%" SIZE_T_FORMAT "u: %s %" SIZE_T_FORMAT "u\n", file, line, __func__, n)); return malloc(n); } /*ARGSUSED*/ static void * cdf_realloc(const char *file __attribute__((__unused__)), size_t line __attribute__((__unused__)), void *p, size_t n) { DPRINTF(("%s,%" SIZE_T_FORMAT "u: %s %" SIZE_T_FORMAT "u\n", file, line, __func__, n)); return realloc(p, n); } /*ARGSUSED*/ static void * cdf_calloc(const char *file __attribute__((__unused__)), size_t line __attribute__((__unused__)), size_t n, size_t u) { DPRINTF(("%s,%" SIZE_T_FORMAT "u: %s %" SIZE_T_FORMAT "u %" SIZE_T_FORMAT "u\n", file, line, __func__, n, u)); return calloc(n, u); } /* * swap a short */ static uint16_t _cdf_tole2(uint16_t sv) { uint16_t rv; uint8_t *s = RCAST(uint8_t *, RCAST(void *, &sv)); uint8_t *d = RCAST(uint8_t *, RCAST(void *, &rv)); d[0] = s[1]; d[1] = s[0]; return rv; } /* * swap an int */ static uint32_t _cdf_tole4(uint32_t sv) { uint32_t rv; uint8_t *s = RCAST(uint8_t *, RCAST(void *, &sv)); uint8_t *d = RCAST(uint8_t *, RCAST(void *, &rv)); d[0] = s[3]; d[1] = s[2]; d[2] = s[1]; d[3] = s[0]; return rv; } /* * swap a quad */ static uint64_t _cdf_tole8(uint64_t sv) { uint64_t rv; uint8_t *s = RCAST(uint8_t *, RCAST(void *, &sv)); uint8_t *d = RCAST(uint8_t *, RCAST(void *, &rv)); d[0] = s[7]; d[1] = s[6]; d[2] = s[5]; d[3] = s[4]; d[4] = s[3]; d[5] = s[2]; d[6] = s[1]; d[7] = s[0]; return rv; } /* * grab a uint32_t from a possibly unaligned address, and return it in * the native host order. */ static uint32_t cdf_getuint32(const uint8_t *p, size_t offs) { uint32_t rv; (void)memcpy(&rv, p + offs * sizeof(uint32_t), sizeof(rv)); return CDF_TOLE4(rv); } #define CDF_UNPACK(a) \ (void)memcpy(&(a), &buf[len], sizeof(a)), len += sizeof(a) #define CDF_UNPACKA(a) \ (void)memcpy((a), &buf[len], sizeof(a)), len += sizeof(a) uint16_t cdf_tole2(uint16_t sv) { return CDF_TOLE2(sv); } uint32_t cdf_tole4(uint32_t sv) { return CDF_TOLE4(sv); } uint64_t cdf_tole8(uint64_t sv) { return CDF_TOLE8(sv); } void cdf_swap_header(cdf_header_t *h) { size_t i; h->h_magic = CDF_TOLE8(h->h_magic); h->h_uuid[0] = CDF_TOLE8(h->h_uuid[0]); h->h_uuid[1] = CDF_TOLE8(h->h_uuid[1]); h->h_revision = CDF_TOLE2(h->h_revision); h->h_version = CDF_TOLE2(h->h_version); h->h_byte_order = CDF_TOLE2(h->h_byte_order); h->h_sec_size_p2 = CDF_TOLE2(h->h_sec_size_p2); h->h_short_sec_size_p2 = CDF_TOLE2(h->h_short_sec_size_p2); h->h_num_sectors_in_sat = CDF_TOLE4(h->h_num_sectors_in_sat); h->h_secid_first_directory = CDF_TOLE4(h->h_secid_first_directory); h->h_min_size_standard_stream = CDF_TOLE4(h->h_min_size_standard_stream); h->h_secid_first_sector_in_short_sat = CDF_TOLE4(CAST(uint32_t, h->h_secid_first_sector_in_short_sat)); h->h_num_sectors_in_short_sat = CDF_TOLE4(h->h_num_sectors_in_short_sat); h->h_secid_first_sector_in_master_sat = CDF_TOLE4(CAST(uint32_t, h->h_secid_first_sector_in_master_sat)); h->h_num_sectors_in_master_sat = CDF_TOLE4(h->h_num_sectors_in_master_sat); for (i = 0; i < __arraycount(h->h_master_sat); i++) { h->h_master_sat[i] = CDF_TOLE4(CAST(uint32_t, h->h_master_sat[i])); } } void cdf_unpack_header(cdf_header_t *h, char *buf) { size_t i; size_t len = 0; CDF_UNPACK(h->h_magic); CDF_UNPACKA(h->h_uuid); CDF_UNPACK(h->h_revision); CDF_UNPACK(h->h_version); CDF_UNPACK(h->h_byte_order); CDF_UNPACK(h->h_sec_size_p2); CDF_UNPACK(h->h_short_sec_size_p2); CDF_UNPACKA(h->h_unused0); CDF_UNPACK(h->h_num_sectors_in_sat); CDF_UNPACK(h->h_secid_first_directory); CDF_UNPACKA(h->h_unused1); CDF_UNPACK(h->h_min_size_standard_stream); CDF_UNPACK(h->h_secid_first_sector_in_short_sat); CDF_UNPACK(h->h_num_sectors_in_short_sat); CDF_UNPACK(h->h_secid_first_sector_in_master_sat); CDF_UNPACK(h->h_num_sectors_in_master_sat); for (i = 0; i < __arraycount(h->h_master_sat); i++) CDF_UNPACK(h->h_master_sat[i]); } void cdf_swap_dir(cdf_directory_t *d) { d->d_namelen = CDF_TOLE2(d->d_namelen); d->d_left_child = CDF_TOLE4(CAST(uint32_t, d->d_left_child)); d->d_right_child = CDF_TOLE4(CAST(uint32_t, d->d_right_child)); d->d_storage = CDF_TOLE4(CAST(uint32_t, d->d_storage)); d->d_storage_uuid[0] = CDF_TOLE8(d->d_storage_uuid[0]); d->d_storage_uuid[1] = CDF_TOLE8(d->d_storage_uuid[1]); d->d_flags = CDF_TOLE4(d->d_flags); d->d_created = CDF_TOLE8(CAST(uint64_t, d->d_created)); d->d_modified = CDF_TOLE8(CAST(uint64_t, d->d_modified)); d->d_stream_first_sector = CDF_TOLE4( CAST(uint32_t, d->d_stream_first_sector)); d->d_size = CDF_TOLE4(d->d_size); } void cdf_swap_class(cdf_classid_t *d) { d->cl_dword = CDF_TOLE4(d->cl_dword); d->cl_word[0] = CDF_TOLE2(d->cl_word[0]); d->cl_word[1] = CDF_TOLE2(d->cl_word[1]); } void cdf_unpack_dir(cdf_directory_t *d, char *buf) { size_t len = 0; CDF_UNPACKA(d->d_name); CDF_UNPACK(d->d_namelen); CDF_UNPACK(d->d_type); CDF_UNPACK(d->d_color); CDF_UNPACK(d->d_left_child); CDF_UNPACK(d->d_right_child); CDF_UNPACK(d->d_storage); CDF_UNPACKA(d->d_storage_uuid); CDF_UNPACK(d->d_flags); CDF_UNPACK(d->d_created); CDF_UNPACK(d->d_modified); CDF_UNPACK(d->d_stream_first_sector); CDF_UNPACK(d->d_size); CDF_UNPACK(d->d_unused0); } int cdf_zero_stream(cdf_stream_t *scn) { scn->sst_len = 0; scn->sst_dirlen = 0; scn->sst_ss = 0; free(scn->sst_tab); scn->sst_tab = NULL; return -1; } static size_t cdf_check_stream(const cdf_stream_t *sst, const cdf_header_t *h) { size_t ss = sst->sst_dirlen < h->h_min_size_standard_stream ? CDF_SHORT_SEC_SIZE(h) : CDF_SEC_SIZE(h); assert(ss == sst->sst_ss); return sst->sst_ss; } static int cdf_check_stream_offset(const cdf_stream_t *sst, const cdf_header_t *h, const void *p, size_t tail, int line) { const char *b = RCAST(const char *, sst->sst_tab); const char *e = RCAST(const char *, p) + tail; size_t ss = cdf_check_stream(sst, h); /*LINTED*/(void)&line; if (e >= b && CAST(size_t, e - b) <= ss * sst->sst_len) return 0; DPRINTF(("%d: offset begin %p < end %p || %" SIZE_T_FORMAT "u" " > %" SIZE_T_FORMAT "u [%" SIZE_T_FORMAT "u %" SIZE_T_FORMAT "u]\n", line, b, e, (size_t)(e - b), ss * sst->sst_len, ss, sst->sst_len)); errno = EFTYPE; return -1; } static ssize_t cdf_read(const cdf_info_t *info, off_t off, void *buf, size_t len) { size_t siz = CAST(size_t, off + len); if (CAST(off_t, off + len) != CAST(off_t, siz)) goto out; if (info->i_buf != NULL && info->i_len >= siz) { (void)memcpy(buf, &info->i_buf[off], len); return CAST(ssize_t, len); } if (info->i_fd == -1) goto out; if (pread(info->i_fd, buf, len, off) != CAST(ssize_t, len)) return -1; return CAST(ssize_t, len); out: errno = EINVAL; return -1; } int cdf_read_header(const cdf_info_t *info, cdf_header_t *h) { char buf[512]; (void)memcpy(cdf_bo.s, "\01\02\03\04", 4); if (cdf_read(info, CAST(off_t, 0), buf, sizeof(buf)) == -1) return -1; cdf_unpack_header(h, buf); cdf_swap_header(h); if (h->h_magic != CDF_MAGIC) { DPRINTF(("Bad magic %#" INT64_T_FORMAT "x != %#" INT64_T_FORMAT "x\n", (unsigned long long)h->h_magic, (unsigned long long)CDF_MAGIC)); goto out; } if (h->h_sec_size_p2 > 20) { DPRINTF(("Bad sector size %hu\n", h->h_sec_size_p2)); goto out; } if (h->h_short_sec_size_p2 > 20) { DPRINTF(("Bad short sector size %hu\n", h->h_short_sec_size_p2)); goto out; } return 0; out: errno = EFTYPE; return -1; } ssize_t cdf_read_sector(const cdf_info_t *info, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { size_t ss = CDF_SEC_SIZE(h); size_t pos; if (SIZE_T_MAX / ss < CAST(size_t, id)) return -1; pos = CDF_SEC_POS(h, id); assert(ss == len); return cdf_read(info, CAST(off_t, pos), RCAST(char *, buf) + offs, len); } ssize_t cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { size_t ss = CDF_SHORT_SEC_SIZE(h); size_t pos; if (SIZE_T_MAX / ss < CAST(size_t, id)) return -1; pos = CDF_SHORT_SEC_POS(h, id); assert(ss == len); if (pos + len > CDF_SEC_SIZE(h) * sst->sst_len) { DPRINTF(("Out of bounds read %" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", pos + len, CDF_SEC_SIZE(h) * sst->sst_len)); goto out; } (void)memcpy(RCAST(char *, buf) + offs, RCAST(const char *, sst->sst_tab) + pos, len); return len; out: errno = EFTYPE; return -1; } /* * Read the sector allocation table. */ int cdf_read_sat(const cdf_info_t *info, cdf_header_t *h, cdf_sat_t *sat) { size_t i, j, k; size_t ss = CDF_SEC_SIZE(h); cdf_secid_t *msa, mid, sec; size_t nsatpersec = (ss / sizeof(mid)) - 1; for (i = 0; i < __arraycount(h->h_master_sat); i++) if (h->h_master_sat[i] == CDF_SECID_FREE) break; #define CDF_SEC_LIMIT (UINT32_MAX / (64 * ss)) if ((nsatpersec > 0 && h->h_num_sectors_in_master_sat > CDF_SEC_LIMIT / nsatpersec) || i > CDF_SEC_LIMIT) { DPRINTF(("Number of sectors in master SAT too big %u %" SIZE_T_FORMAT "u\n", h->h_num_sectors_in_master_sat, i)); errno = EFTYPE; return -1; } sat->sat_len = h->h_num_sectors_in_master_sat * nsatpersec + i; DPRINTF(("sat_len = %" SIZE_T_FORMAT "u ss = %" SIZE_T_FORMAT "u\n", sat->sat_len, ss)); if ((sat->sat_tab = CAST(cdf_secid_t *, CDF_CALLOC(sat->sat_len, ss))) == NULL) return -1; for (i = 0; i < __arraycount(h->h_master_sat); i++) { if (h->h_master_sat[i] < 0) break; if (cdf_read_sector(info, sat->sat_tab, ss * i, ss, h, h->h_master_sat[i]) != CAST(ssize_t, ss)) { DPRINTF(("Reading sector %d", h->h_master_sat[i])); goto out1; } } if ((msa = CAST(cdf_secid_t *, CDF_CALLOC(1, ss))) == NULL) goto out1; mid = h->h_secid_first_sector_in_master_sat; for (j = 0; j < h->h_num_sectors_in_master_sat; j++) { if (mid < 0) goto out; if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Reading master sector loop limit")); goto out3; } if (cdf_read_sector(info, msa, 0, ss, h, mid) != CAST(ssize_t, ss)) { DPRINTF(("Reading master sector %d", mid)); goto out2; } for (k = 0; k < nsatpersec; k++, i++) { sec = CDF_TOLE4(CAST(uint32_t, msa[k])); if (sec < 0) goto out; if (i >= sat->sat_len) { DPRINTF(("Out of bounds reading MSA %" SIZE_T_FORMAT "u >= %" SIZE_T_FORMAT "u", i, sat->sat_len)); goto out3; } if (cdf_read_sector(info, sat->sat_tab, ss * i, ss, h, sec) != CAST(ssize_t, ss)) { DPRINTF(("Reading sector %d", CDF_TOLE4(msa[k]))); goto out2; } } mid = CDF_TOLE4(CAST(uint32_t, msa[nsatpersec])); } out: sat->sat_len = i; free(msa); return 0; out3: errno = EFTYPE; out2: free(msa); out1: free(sat->sat_tab); return -1; } size_t cdf_count_chain(const cdf_sat_t *sat, cdf_secid_t sid, size_t size) { size_t i, j; cdf_secid_t maxsector = CAST(cdf_secid_t, (sat->sat_len * size) / sizeof(maxsector)); DPRINTF(("Chain:")); if (sid == CDF_SECID_END_OF_CHAIN) { /* 0-length chain. */ DPRINTF((" empty\n")); return 0; } for (j = i = 0; sid >= 0; i++, j++) { DPRINTF((" %d", sid)); if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Counting chain loop limit")); goto out; } if (sid >= maxsector) { DPRINTF(("Sector %d >= %d\n", sid, maxsector)); goto out; } sid = CDF_TOLE4(CAST(uint32_t, sat->sat_tab[sid])); } if (i == 0) { DPRINTF((" none, sid: %d\n", sid)); goto out; } DPRINTF(("\n")); return i; out: errno = EFTYPE; return CAST(size_t, -1); } int cdf_read_long_sector_chain(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { size_t ss = CDF_SEC_SIZE(h), i, j; ssize_t nr; scn->sst_tab = NULL; scn->sst_len = cdf_count_chain(sat, sid, ss); scn->sst_dirlen = MAX(h->h_min_size_standard_stream, len); scn->sst_ss = ss; if (sid == CDF_SECID_END_OF_CHAIN || len == 0) return cdf_zero_stream(scn); if (scn->sst_len == CAST(size_t, -1)) goto out; scn->sst_tab = CDF_CALLOC(scn->sst_len, ss); if (scn->sst_tab == NULL) return cdf_zero_stream(scn); for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read long sector chain loop limit")); goto out; } if (i >= scn->sst_len) { DPRINTF(("Out of bounds reading long sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, scn->sst_len)); goto out; } if ((nr = cdf_read_sector(info, scn->sst_tab, i * ss, ss, h, sid)) != CAST(ssize_t, ss)) { if (i == scn->sst_len - 1 && nr > 0) { /* Last sector might be truncated */ return 0; } DPRINTF(("Reading long sector chain %d", sid)); goto out; } sid = CDF_TOLE4(CAST(uint32_t, sat->sat_tab[sid])); } return 0; out: errno = EFTYPE; return cdf_zero_stream(scn); } int cdf_read_short_sector_chain(const cdf_header_t *h, const cdf_sat_t *ssat, const cdf_stream_t *sst, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { size_t ss = CDF_SHORT_SEC_SIZE(h), i, j; scn->sst_tab = NULL; scn->sst_len = cdf_count_chain(ssat, sid, CDF_SEC_SIZE(h)); scn->sst_dirlen = len; scn->sst_ss = ss; if (scn->sst_len == CAST(size_t, -1)) goto out; scn->sst_tab = CDF_CALLOC(scn->sst_len, ss); if (scn->sst_tab == NULL) return cdf_zero_stream(scn); for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read short sector chain loop limit")); goto out; } if (i >= scn->sst_len) { DPRINTF(("Out of bounds reading short sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, scn->sst_len)); goto out; } if (cdf_read_short_sector(sst, scn->sst_tab, i * ss, ss, h, sid) != CAST(ssize_t, ss)) { DPRINTF(("Reading short sector chain %d", sid)); goto out; } sid = CDF_TOLE4(CAST(uint32_t, ssat->sat_tab[sid])); } return 0; out: errno = EFTYPE; return cdf_zero_stream(scn); } int cdf_read_sector_chain(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { if (len < h->h_min_size_standard_stream && sst->sst_tab != NULL) return cdf_read_short_sector_chain(h, ssat, sst, sid, len, scn); else return cdf_read_long_sector_chain(info, h, sat, sid, len, scn); } int cdf_read_dir(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, cdf_dir_t *dir) { size_t i, j; size_t ss = CDF_SEC_SIZE(h), ns, nd; char *buf; cdf_secid_t sid = h->h_secid_first_directory; ns = cdf_count_chain(sat, sid, ss); if (ns == CAST(size_t, -1)) return -1; nd = ss / CDF_DIRECTORY_SIZE; dir->dir_len = ns * nd; dir->dir_tab = CAST(cdf_directory_t *, CDF_CALLOC(dir->dir_len, sizeof(dir->dir_tab[0]))); if (dir->dir_tab == NULL) return -1; if ((buf = CAST(char *, CDF_MALLOC(ss))) == NULL) { free(dir->dir_tab); return -1; } for (j = i = 0; i < ns; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read dir loop limit")); goto out; } if (cdf_read_sector(info, buf, 0, ss, h, sid) != CAST(ssize_t, ss)) { DPRINTF(("Reading directory sector %d", sid)); goto out; } for (j = 0; j < nd; j++) { cdf_unpack_dir(&dir->dir_tab[i * nd + j], &buf[j * CDF_DIRECTORY_SIZE]); } sid = CDF_TOLE4(CAST(uint32_t, sat->sat_tab[sid])); } if (NEED_SWAP) for (i = 0; i < dir->dir_len; i++) cdf_swap_dir(&dir->dir_tab[i]); free(buf); return 0; out: free(dir->dir_tab); free(buf); errno = EFTYPE; return -1; } int cdf_read_ssat(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, cdf_sat_t *ssat) { size_t i, j; size_t ss = CDF_SEC_SIZE(h); cdf_secid_t sid = h->h_secid_first_sector_in_short_sat; ssat->sat_tab = NULL; ssat->sat_len = cdf_count_chain(sat, sid, ss); if (ssat->sat_len == CAST(size_t, -1)) goto out; ssat->sat_tab = CAST(cdf_secid_t *, CDF_CALLOC(ssat->sat_len, ss)); if (ssat->sat_tab == NULL) goto out1; for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read short sat sector loop limit")); goto out; } if (i >= ssat->sat_len) { DPRINTF(("Out of bounds reading short sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, ssat->sat_len)); goto out; } if (cdf_read_sector(info, ssat->sat_tab, i * ss, ss, h, sid) != CAST(ssize_t, ss)) { DPRINTF(("Reading short sat sector %d", sid)); goto out1; } sid = CDF_TOLE4(CAST(uint32_t, sat->sat_tab[sid])); } return 0; out: errno = EFTYPE; out1: free(ssat->sat_tab); return -1; } int cdf_read_short_stream(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_dir_t *dir, cdf_stream_t *scn, const cdf_directory_t **root) { size_t i; const cdf_directory_t *d; *root = NULL; for (i = 0; i < dir->dir_len; i++) if (dir->dir_tab[i].d_type == CDF_DIR_TYPE_ROOT_STORAGE) break; /* If the it is not there, just fake it; some docs don't have it */ if (i == dir->dir_len) { DPRINTF(("Cannot find root storage dir\n")); goto out; } d = &dir->dir_tab[i]; *root = d; /* If the it is not there, just fake it; some docs don't have it */ if (d->d_stream_first_sector < 0) { DPRINTF(("No first secror in dir\n")); goto out; } return cdf_read_long_sector_chain(info, h, sat, d->d_stream_first_sector, d->d_size, scn); out: scn->sst_tab = NULL; (void)cdf_zero_stream(scn); return 0; } static int cdf_namecmp(const char *d, const uint16_t *s, size_t l) { for (; l--; d++, s++) if (*d != CDF_TOLE2(*s)) return CAST(unsigned char, *d) - CDF_TOLE2(*s); return 0; } int cdf_read_doc_summary_info(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir, cdf_stream_t *scn) { return cdf_read_user_stream(info, h, sat, ssat, sst, dir, "\05DocumentSummaryInformation", scn); } int cdf_read_summary_info(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir, cdf_stream_t *scn) { return cdf_read_user_stream(info, h, sat, ssat, sst, dir, "\05SummaryInformation", scn); } int cdf_read_user_stream(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir, const char *name, cdf_stream_t *scn) { const cdf_directory_t *d; int i = cdf_find_stream(dir, name, CDF_DIR_TYPE_USER_STREAM); if (i <= 0) { memset(scn, 0, sizeof(*scn)); return -1; } d = &dir->dir_tab[i - 1]; return cdf_read_sector_chain(info, h, sat, ssat, sst, d->d_stream_first_sector, d->d_size, scn); } int cdf_find_stream(const cdf_dir_t *dir, const char *name, int type) { size_t i, name_len = strlen(name) + 1; for (i = dir->dir_len; i > 0; i--) if (dir->dir_tab[i - 1].d_type == type && cdf_namecmp(name, dir->dir_tab[i - 1].d_name, name_len) == 0) break; if (i > 0) return CAST(int, i); DPRINTF(("Cannot find type %d `%s'\n", type, name)); errno = ESRCH; return 0; } #define CDF_SHLEN_LIMIT (UINT32_MAX / 64) #define CDF_PROP_LIMIT (UINT32_MAX / (64 * sizeof(cdf_property_info_t))) static const void * cdf_offset(const void *p, size_t l) { return CAST(const void *, CAST(const uint8_t *, p) + l); } static const uint8_t * cdf_get_property_info_pos(const cdf_stream_t *sst, const cdf_header_t *h, const uint8_t *p, const uint8_t *e, size_t i) { size_t tail = (i << 1) + 1; size_t ofs; const uint8_t *q; if (p >= e) { DPRINTF(("Past end %p < %p\n", e, p)); return NULL; } if (cdf_check_stream_offset(sst, h, p, (tail + 1) * sizeof(uint32_t), __LINE__) == -1) return NULL; ofs = CDF_GETUINT32(p, tail); q = CAST(const uint8_t *, cdf_offset(CAST(const void *, p), ofs - 2 * sizeof(uint32_t))); if (q < p) { DPRINTF(("Wrapped around %p < %p\n", q, p)); return NULL; } if (q >= e) { DPRINTF(("Ran off the end %p >= %p\n", q, e)); return NULL; } return q; } static cdf_property_info_t * cdf_grow_info(cdf_property_info_t **info, size_t *maxcount, size_t incr) { cdf_property_info_t *inp; size_t newcount = *maxcount + incr; if (newcount > CDF_PROP_LIMIT) { DPRINTF(("exceeded property limit %" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", newcount, CDF_PROP_LIMIT)); goto out; } inp = CAST(cdf_property_info_t *, CDF_REALLOC(*info, newcount * sizeof(*inp))); if (inp == NULL) goto out; *info = inp; *maxcount = newcount; return inp; out: free(*info); *maxcount = 0; *info = NULL; return NULL; } static int cdf_copy_info(cdf_property_info_t *inp, const void *p, const void *e, size_t len) { if (inp->pi_type & CDF_VECTOR) return 0; if (CAST(size_t, CAST(const char *, e) - CAST(const char *, p)) < len) return 0; (void)memcpy(&inp->pi_val, p, len); switch (len) { case 2: inp->pi_u16 = CDF_TOLE2(inp->pi_u16); break; case 4: inp->pi_u32 = CDF_TOLE4(inp->pi_u32); break; case 8: inp->pi_u64 = CDF_TOLE8(inp->pi_u64); break; default: abort(); } return 1; } int cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h, uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount) { const cdf_section_header_t *shp; cdf_section_header_t sh; const uint8_t *p, *q, *e; size_t i, o4, nelements, j, slen, left; cdf_property_info_t *inp; if (offs > UINT32_MAX / 4) { errno = EFTYPE; goto out; } shp = CAST(const cdf_section_header_t *, cdf_offset(sst->sst_tab, offs)); if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1) goto out; sh.sh_len = CDF_TOLE4(shp->sh_len); if (sh.sh_len > CDF_SHLEN_LIMIT) { errno = EFTYPE; goto out; } if (cdf_check_stream_offset(sst, h, shp, sh.sh_len, __LINE__) == -1) goto out; sh.sh_properties = CDF_TOLE4(shp->sh_properties); DPRINTF(("section len: %u properties %u\n", sh.sh_len, sh.sh_properties)); if (sh.sh_properties > CDF_PROP_LIMIT) goto out; inp = cdf_grow_info(info, maxcount, sh.sh_properties); if (inp == NULL) goto out; inp += *count; *count += sh.sh_properties; p = CAST(const uint8_t *, cdf_offset(sst->sst_tab, offs + sizeof(sh))); e = CAST(const uint8_t *, cdf_offset(shp, sh.sh_len)); if (p >= e || cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1) goto out; for (i = 0; i < sh.sh_properties; i++) { if ((q = cdf_get_property_info_pos(sst, h, p, e, i)) == NULL) goto out; inp[i].pi_id = CDF_GETUINT32(p, i << 1); left = CAST(size_t, e - q); if (left < sizeof(uint32_t)) { DPRINTF(("short info (no type)_\n")); goto out; } inp[i].pi_type = CDF_GETUINT32(q, 0); DPRINTF(("%" SIZE_T_FORMAT "u) id=%#x type=%#x offs=%#tx,%#x\n", i, inp[i].pi_id, inp[i].pi_type, q - p, offs)); if (inp[i].pi_type & CDF_VECTOR) { if (left < sizeof(uint32_t) * 2) { DPRINTF(("missing CDF_VECTOR length\n")); goto out; } nelements = CDF_GETUINT32(q, 1); if (nelements > CDF_ELEMENT_LIMIT || nelements == 0) { DPRINTF(("CDF_VECTOR with nelements == %" SIZE_T_FORMAT "u\n", nelements)); goto out; } slen = 2; } else { nelements = 1; slen = 1; } o4 = slen * sizeof(uint32_t); if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED)) goto unknown; switch (inp[i].pi_type & CDF_TYPEMASK) { case CDF_NULL: case CDF_EMPTY: break; case CDF_SIGNED16: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int16_t))) goto unknown; break; case CDF_SIGNED32: case CDF_BOOL: case CDF_UNSIGNED32: case CDF_FLOAT: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int32_t))) goto unknown; break; case CDF_SIGNED64: case CDF_UNSIGNED64: case CDF_DOUBLE: case CDF_FILETIME: if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int64_t))) goto unknown; break; case CDF_LENGTH32_STRING: case CDF_LENGTH32_WSTRING: if (nelements > 1) { size_t nelem = inp - *info; inp = cdf_grow_info(info, maxcount, nelements); if (inp == NULL) goto out; inp += nelem; } for (j = 0; j < nelements && i < sh.sh_properties; j++, i++) { uint32_t l; if (o4 + sizeof(uint32_t) > left) goto out; l = CDF_GETUINT32(q, slen); o4 += sizeof(uint32_t); if (o4 + l > left) goto out; inp[i].pi_str.s_len = l; inp[i].pi_str.s_buf = CAST(const char *, CAST(const void *, &q[o4])); DPRINTF(("o=%" SIZE_T_FORMAT "u l=%d(%" SIZE_T_FORMAT "u), t=%" SIZE_T_FORMAT "u s=%s\n", o4, l, CDF_ROUND(l, sizeof(l)), left, inp[i].pi_str.s_buf)); if (l & 1) l++; slen += l >> 1; o4 = slen * sizeof(uint32_t); } i--; break; case CDF_CLIPBOARD: if (inp[i].pi_type & CDF_VECTOR) goto unknown; break; default: unknown: memset(&inp[i].pi_val, 0, sizeof(inp[i].pi_val)); DPRINTF(("Don't know how to deal with %#x\n", inp[i].pi_type)); break; } } return 0; out: free(*info); *info = NULL; *count = 0; *maxcount = 0; errno = EFTYPE; return -1; } int cdf_unpack_summary_info(const cdf_stream_t *sst, const cdf_header_t *h, cdf_summary_info_header_t *ssi, cdf_property_info_t **info, size_t *count) { size_t maxcount; const cdf_summary_info_header_t *si = CAST(const cdf_summary_info_header_t *, sst->sst_tab); const cdf_section_declaration_t *sd = CAST(const cdf_section_declaration_t *, RCAST(const void *, RCAST(const char *, sst->sst_tab) + CDF_SECTION_DECLARATION_OFFSET)); if (cdf_check_stream_offset(sst, h, si, sizeof(*si), __LINE__) == -1 || cdf_check_stream_offset(sst, h, sd, sizeof(*sd), __LINE__) == -1) return -1; ssi->si_byte_order = CDF_TOLE2(si->si_byte_order); ssi->si_os_version = CDF_TOLE2(si->si_os_version); ssi->si_os = CDF_TOLE2(si->si_os); ssi->si_class = si->si_class; cdf_swap_class(&ssi->si_class); ssi->si_count = CDF_TOLE4(si->si_count); *count = 0; maxcount = 0; *info = NULL; if (cdf_read_property_info(sst, h, CDF_TOLE4(sd->sd_offset), info, count, &maxcount) == -1) return -1; return 0; } #define extract_catalog_field(t, f, l) \ if (b + l + sizeof(cep->f) > eb) { \ cep->ce_namlen = 0; \ break; \ } \ memcpy(&cep->f, b + (l), sizeof(cep->f)); \ ce[i].f = CAST(t, CDF_TOLE(cep->f)) int cdf_unpack_catalog(const cdf_header_t *h, const cdf_stream_t *sst, cdf_catalog_t **cat) { size_t ss = cdf_check_stream(sst, h); const char *b = CAST(const char *, sst->sst_tab); const char *nb, *eb = b + ss * sst->sst_len; size_t nr, i, j, k; cdf_catalog_entry_t *ce; uint16_t reclen; const uint16_t *np; for (nr = 0;; nr++) { memcpy(&reclen, b, sizeof(reclen)); reclen = CDF_TOLE2(reclen); if (reclen == 0) break; b += reclen; if (b > eb) break; } if (nr == 0) return -1; nr--; *cat = CAST(cdf_catalog_t *, CDF_MALLOC(sizeof(cdf_catalog_t) + nr * sizeof(*ce))); if (*cat == NULL) return -1; ce = (*cat)->cat_e; memset(ce, 0, nr * sizeof(*ce)); b = CAST(const char *, sst->sst_tab); for (j = i = 0; i < nr; b += reclen) { cdf_catalog_entry_t *cep = &ce[j]; uint16_t rlen; extract_catalog_field(uint16_t, ce_namlen, 0); extract_catalog_field(uint16_t, ce_num, 4); extract_catalog_field(uint64_t, ce_timestamp, 8); reclen = cep->ce_namlen; if (reclen < 14) { cep->ce_namlen = 0; continue; } cep->ce_namlen = __arraycount(cep->ce_name) - 1; rlen = reclen - 14; if (cep->ce_namlen > rlen) cep->ce_namlen = rlen; np = CAST(const uint16_t *, CAST(const void *, (b + 16))); nb = CAST(const char *, CAST(const void *, (np + cep->ce_namlen))); if (nb > eb) { cep->ce_namlen = 0; break; } for (k = 0; k < cep->ce_namlen; k++) cep->ce_name[k] = np[k]; /* XXX: CDF_TOLE2? */ cep->ce_name[cep->ce_namlen] = 0; j = i; i++; } (*cat)->cat_num = j; return 0; } int cdf_print_classid(char *buf, size_t buflen, const cdf_classid_t *id) { return snprintf(buf, buflen, "%.8x-%.4x-%.4x-%.2x%.2x-" "%.2x%.2x%.2x%.2x%.2x%.2x", id->cl_dword, id->cl_word[0], id->cl_word[1], id->cl_two[0], id->cl_two[1], id->cl_six[0], id->cl_six[1], id->cl_six[2], id->cl_six[3], id->cl_six[4], id->cl_six[5]); } static const struct { uint32_t v; const char *n; } vn[] = { { CDF_PROPERTY_CODE_PAGE, "Code page" }, { CDF_PROPERTY_TITLE, "Title" }, { CDF_PROPERTY_SUBJECT, "Subject" }, { CDF_PROPERTY_AUTHOR, "Author" }, { CDF_PROPERTY_KEYWORDS, "Keywords" }, { CDF_PROPERTY_COMMENTS, "Comments" }, { CDF_PROPERTY_TEMPLATE, "Template" }, { CDF_PROPERTY_LAST_SAVED_BY, "Last Saved By" }, { CDF_PROPERTY_REVISION_NUMBER, "Revision Number" }, { CDF_PROPERTY_TOTAL_EDITING_TIME, "Total Editing Time" }, { CDF_PROPERTY_LAST_PRINTED, "Last Printed" }, { CDF_PROPERTY_CREATE_TIME, "Create Time/Date" }, { CDF_PROPERTY_LAST_SAVED_TIME, "Last Saved Time/Date" }, { CDF_PROPERTY_NUMBER_OF_PAGES, "Number of Pages" }, { CDF_PROPERTY_NUMBER_OF_WORDS, "Number of Words" }, { CDF_PROPERTY_NUMBER_OF_CHARACTERS, "Number of Characters" }, { CDF_PROPERTY_THUMBNAIL, "Thumbnail" }, { CDF_PROPERTY_NAME_OF_APPLICATION, "Name of Creating Application" }, { CDF_PROPERTY_SECURITY, "Security" }, { CDF_PROPERTY_LOCALE_ID, "Locale ID" }, }; int cdf_print_property_name(char *buf, size_t bufsiz, uint32_t p) { size_t i; for (i = 0; i < __arraycount(vn); i++) if (vn[i].v == p) return snprintf(buf, bufsiz, "%s", vn[i].n); return snprintf(buf, bufsiz, "%#x", p); } int cdf_print_elapsed_time(char *buf, size_t bufsiz, cdf_timestamp_t ts) { int len = 0; int days, hours, mins, secs; ts /= CDF_TIME_PREC; secs = CAST(int, ts % 60); ts /= 60; mins = CAST(int, ts % 60); ts /= 60; hours = CAST(int, ts % 24); ts /= 24; days = CAST(int, ts); if (days) { len += snprintf(buf + len, bufsiz - len, "%dd+", days); if (CAST(size_t, len) >= bufsiz) return len; } if (days || hours) { len += snprintf(buf + len, bufsiz - len, "%.2d:", hours); if (CAST(size_t, len) >= bufsiz) return len; } len += snprintf(buf + len, bufsiz - len, "%.2d:", mins); if (CAST(size_t, len) >= bufsiz) return len; len += snprintf(buf + len, bufsiz - len, "%.2d", secs); return len; } char * cdf_u16tos8(char *buf, size_t len, const uint16_t *p) { size_t i; for (i = 0; i < len && p[i]; i++) buf[i] = CAST(char, p[i]); buf[i] = '\0'; return buf; } #ifdef CDF_DEBUG void cdf_dump_header(const cdf_header_t *h) { size_t i; #define DUMP(a, b) (void)fprintf(stderr, "%40.40s = " a "\n", # b, h->h_ ## b) #define DUMP2(a, b) (void)fprintf(stderr, "%40.40s = " a " (" a ")\n", # b, \ h->h_ ## b, 1 << h->h_ ## b) DUMP("%d", revision); DUMP("%d", version); DUMP("%#x", byte_order); DUMP2("%d", sec_size_p2); DUMP2("%d", short_sec_size_p2); DUMP("%d", num_sectors_in_sat); DUMP("%d", secid_first_directory); DUMP("%d", min_size_standard_stream); DUMP("%d", secid_first_sector_in_short_sat); DUMP("%d", num_sectors_in_short_sat); DUMP("%d", secid_first_sector_in_master_sat); DUMP("%d", num_sectors_in_master_sat); for (i = 0; i < __arraycount(h->h_master_sat); i++) { if (h->h_master_sat[i] == CDF_SECID_FREE) break; (void)fprintf(stderr, "%35.35s[%.3" SIZE_T_FORMAT "u] = %d\n", "master_sat", i, h->h_master_sat[i]); } } void cdf_dump_sat(const char *prefix, const cdf_sat_t *sat, size_t size) { size_t i, j, s = size / sizeof(cdf_secid_t); for (i = 0; i < sat->sat_len; i++) { (void)fprintf(stderr, "%s[%" SIZE_T_FORMAT "u]:\n%.6" SIZE_T_FORMAT "u: ", prefix, i, i * s); for (j = 0; j < s; j++) { (void)fprintf(stderr, "%5d, ", CDF_TOLE4(sat->sat_tab[s * i + j])); if ((j + 1) % 10 == 0) (void)fprintf(stderr, "\n%.6" SIZE_T_FORMAT "u: ", i * s + j + 1); } (void)fprintf(stderr, "\n"); } } void cdf_dump(const void *v, size_t len) { size_t i, j; const unsigned char *p = v; char abuf[16]; (void)fprintf(stderr, "%.4x: ", 0); for (i = 0, j = 0; i < len; i++, p++) { (void)fprintf(stderr, "%.2x ", *p); abuf[j++] = isprint(*p) ? *p : '.'; if (j == 16) { j = 0; abuf[15] = '\0'; (void)fprintf(stderr, "%s\n%.4" SIZE_T_FORMAT "x: ", abuf, i + 1); } } (void)fprintf(stderr, "\n"); } void cdf_dump_stream(const cdf_stream_t *sst) { size_t ss = sst->sst_ss; cdf_dump(sst->sst_tab, ss * sst->sst_len); } void cdf_dump_dir(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst, const cdf_dir_t *dir) { size_t i, j; cdf_directory_t *d; char name[__arraycount(d->d_name)]; cdf_stream_t scn; struct timespec ts; static const char *types[] = { "empty", "user storage", "user stream", "lockbytes", "property", "root storage" }; for (i = 0; i < dir->dir_len; i++) { char buf[26]; d = &dir->dir_tab[i]; for (j = 0; j < sizeof(name); j++) name[j] = (char)CDF_TOLE2(d->d_name[j]); (void)fprintf(stderr, "Directory %" SIZE_T_FORMAT "u: %s\n", i, name); if (d->d_type < __arraycount(types)) (void)fprintf(stderr, "Type: %s\n", types[d->d_type]); else (void)fprintf(stderr, "Type: %d\n", d->d_type); (void)fprintf(stderr, "Color: %s\n", d->d_color ? "black" : "red"); (void)fprintf(stderr, "Left child: %d\n", d->d_left_child); (void)fprintf(stderr, "Right child: %d\n", d->d_right_child); (void)fprintf(stderr, "Flags: %#x\n", d->d_flags); cdf_timestamp_to_timespec(&ts, d->d_created); (void)fprintf(stderr, "Created %s", cdf_ctime(&ts.tv_sec, buf)); cdf_timestamp_to_timespec(&ts, d->d_modified); (void)fprintf(stderr, "Modified %s", cdf_ctime(&ts.tv_sec, buf)); (void)fprintf(stderr, "Stream %d\n", d->d_stream_first_sector); (void)fprintf(stderr, "Size %d\n", d->d_size); switch (d->d_type) { case CDF_DIR_TYPE_USER_STORAGE: (void)fprintf(stderr, "Storage: %d\n", d->d_storage); break; case CDF_DIR_TYPE_USER_STREAM: if (sst == NULL) break; if (cdf_read_sector_chain(info, h, sat, ssat, sst, d->d_stream_first_sector, d->d_size, &scn) == -1) { warn("Can't read stream for %s at %d len %d", name, d->d_stream_first_sector, d->d_size); break; } cdf_dump_stream(&scn); free(scn.sst_tab); break; default: break; } } } void cdf_dump_property_info(const cdf_property_info_t *info, size_t count) { cdf_timestamp_t tp; struct timespec ts; char buf[64]; size_t i, j; for (i = 0; i < count; i++) { cdf_print_property_name(buf, sizeof(buf), info[i].pi_id); (void)fprintf(stderr, "%" SIZE_T_FORMAT "u) %s: ", i, buf); switch (info[i].pi_type) { case CDF_NULL: break; case CDF_SIGNED16: (void)fprintf(stderr, "signed 16 [%hd]\n", info[i].pi_s16); break; case CDF_SIGNED32: (void)fprintf(stderr, "signed 32 [%d]\n", info[i].pi_s32); break; case CDF_UNSIGNED32: (void)fprintf(stderr, "unsigned 32 [%u]\n", info[i].pi_u32); break; case CDF_FLOAT: (void)fprintf(stderr, "float [%g]\n", info[i].pi_f); break; case CDF_DOUBLE: (void)fprintf(stderr, "double [%g]\n", info[i].pi_d); break; case CDF_LENGTH32_STRING: (void)fprintf(stderr, "string %u [%.*s]\n", info[i].pi_str.s_len, info[i].pi_str.s_len, info[i].pi_str.s_buf); break; case CDF_LENGTH32_WSTRING: (void)fprintf(stderr, "string %u [", info[i].pi_str.s_len); for (j = 0; j < info[i].pi_str.s_len - 1; j++) (void)fputc(info[i].pi_str.s_buf[j << 1], stderr); (void)fprintf(stderr, "]\n"); break; case CDF_FILETIME: tp = info[i].pi_tp; if (tp < 1000000000000000LL) { cdf_print_elapsed_time(buf, sizeof(buf), tp); (void)fprintf(stderr, "timestamp %s\n", buf); } else { char tbuf[26]; cdf_timestamp_to_timespec(&ts, tp); (void)fprintf(stderr, "timestamp %s", cdf_ctime(&ts.tv_sec, tbuf)); } break; case CDF_CLIPBOARD: (void)fprintf(stderr, "CLIPBOARD %u\n", info[i].pi_u32); break; default: DPRINTF(("Don't know how to deal with %#x\n", info[i].pi_type)); break; } } } void cdf_dump_summary_info(const cdf_header_t *h, const cdf_stream_t *sst) { char buf[128]; cdf_summary_info_header_t ssi; cdf_property_info_t *info; size_t count; (void)&h; if (cdf_unpack_summary_info(sst, h, &ssi, &info, &count) == -1) return; (void)fprintf(stderr, "Endian: %#x\n", ssi.si_byte_order); (void)fprintf(stderr, "Os Version %d.%d\n", ssi.si_os_version & 0xff, ssi.si_os_version >> 8); (void)fprintf(stderr, "Os %d\n", ssi.si_os); cdf_print_classid(buf, sizeof(buf), &ssi.si_class); (void)fprintf(stderr, "Class %s\n", buf); (void)fprintf(stderr, "Count %d\n", ssi.si_count); cdf_dump_property_info(info, count); free(info); } void cdf_dump_catalog(const cdf_header_t *h, const cdf_stream_t *sst) { cdf_catalog_t *cat; cdf_unpack_catalog(h, sst, &cat); const cdf_catalog_entry_t *ce = cat->cat_e; struct timespec ts; char tbuf[64], sbuf[256]; size_t i; printf("Catalog:\n"); for (i = 0; i < cat->cat_num; i++) { cdf_timestamp_to_timespec(&ts, ce[i].ce_timestamp); printf("\t%d %s %s", ce[i].ce_num, cdf_u16tos8(sbuf, ce[i].ce_namlen, ce[i].ce_name), cdf_ctime(&ts.tv_sec, tbuf)); } free(cat); } #endif #ifdef TEST int main(int argc, char *argv[]) { int i; cdf_header_t h; cdf_sat_t sat, ssat; cdf_stream_t sst, scn; cdf_dir_t dir; cdf_info_t info; const cdf_directory_t *root; #ifdef __linux__ #define getprogname() __progname extern char *__progname; #endif if (argc < 2) { (void)fprintf(stderr, "Usage: %s <filename>\n", getprogname()); return -1; } info.i_buf = NULL; info.i_len = 0; for (i = 1; i < argc; i++) { if ((info.i_fd = open(argv[1], O_RDONLY)) == -1) err(EXIT_FAILURE, "Cannot open `%s'", argv[1]); if (cdf_read_header(&info, &h) == -1) err(EXIT_FAILURE, "Cannot read header"); #ifdef CDF_DEBUG cdf_dump_header(&h); #endif if (cdf_read_sat(&info, &h, &sat) == -1) err(EXIT_FAILURE, "Cannot read sat"); #ifdef CDF_DEBUG cdf_dump_sat("SAT", &sat, CDF_SEC_SIZE(&h)); #endif if (cdf_read_ssat(&info, &h, &sat, &ssat) == -1) err(EXIT_FAILURE, "Cannot read ssat"); #ifdef CDF_DEBUG cdf_dump_sat("SSAT", &ssat, CDF_SHORT_SEC_SIZE(&h)); #endif if (cdf_read_dir(&info, &h, &sat, &dir) == -1) err(EXIT_FAILURE, "Cannot read dir"); if (cdf_read_short_stream(&info, &h, &sat, &dir, &sst, &root) == -1) err(EXIT_FAILURE, "Cannot read short stream"); #ifdef CDF_DEBUG cdf_dump_stream(&sst); #endif #ifdef CDF_DEBUG cdf_dump_dir(&info, &h, &sat, &ssat, &sst, &dir); #endif if (cdf_read_summary_info(&info, &h, &sat, &ssat, &sst, &dir, &scn) == -1) warn("Cannot read summary info"); #ifdef CDF_DEBUG else cdf_dump_summary_info(&h, &scn); #endif if (cdf_read_user_stream(&info, &h, &sat, &ssat, &sst, &dir, "Catalog", &scn) == -1) warn("Cannot read catalog"); #ifdef CDF_DEBUG else cdf_dump_catalog(&h, &scn); #endif (void)close(info.i_fd); } return 0; } #endif
null
148
CWE-787
CVE-2019-18224
/* lookup.c - implementation of IDNA2008 lookup functions Copyright (C) 2011-2017 Simon Josefsson Libidn2 is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <config.h> #include "idn2.h" #include <errno.h> /* errno */ #include <stdlib.h> /* malloc, free */ #include "punycode.h" #include <unitypes.h> #include <uniconv.h> /* u8_strconv_from_locale */ #include <uninorm.h> /* u32_normalize */ #include <unistr.h> /* u8_to_u32 */ #include "idna.h" /* _idn2_label_test */ #include "tr46map.h" /* definition for tr46map.c */ static int set_default_flags(int *flags) { if (((*flags) & IDN2_TRANSITIONAL) && ((*flags) & IDN2_NONTRANSITIONAL)) return IDN2_INVALID_FLAGS; if (((*flags) & (IDN2_TRANSITIONAL|IDN2_NONTRANSITIONAL)) && ((*flags) & IDN2_NO_TR46)) return IDN2_INVALID_FLAGS; if (!((*flags) & (IDN2_NO_TR46|IDN2_TRANSITIONAL))) *flags |= IDN2_NONTRANSITIONAL; return IDN2_OK; } static int label (const uint8_t * src, size_t srclen, uint8_t * dst, size_t * dstlen, int flags) { size_t plen; uint32_t *p; int rc; size_t tmpl; if (_idn2_ascii_p (src, srclen)) { if (flags & IDN2_ALABEL_ROUNDTRIP) /* FIXME implement this MAY: If the input to this procedure appears to be an A-label (i.e., it starts in "xn--", interpreted case-insensitively), the lookup application MAY attempt to convert it to a U-label, first ensuring that the A-label is entirely in lowercase (converting it to lowercase if necessary), and apply the tests of Section 5.4 and the conversion of Section 5.5 to that form. */ return IDN2_INVALID_FLAGS; if (srclen > IDN2_LABEL_MAX_LENGTH) return IDN2_TOO_BIG_LABEL; if (srclen > *dstlen) return IDN2_TOO_BIG_DOMAIN; memcpy (dst, src, srclen); *dstlen = srclen; return IDN2_OK; } rc = _idn2_u8_to_u32_nfc (src, srclen, &p, &plen, flags & IDN2_NFC_INPUT); if (rc != IDN2_OK) return rc; if (!(flags & IDN2_TRANSITIONAL)) { rc = _idn2_label_test( TEST_NFC | TEST_2HYPHEN | TEST_LEADING_COMBINING | TEST_DISALLOWED | TEST_CONTEXTJ_RULE | TEST_CONTEXTO_WITH_RULE | TEST_UNASSIGNED | TEST_BIDI | ((flags & IDN2_NONTRANSITIONAL) ? TEST_NONTRANSITIONAL : 0) | ((flags & IDN2_USE_STD3_ASCII_RULES) ? 0 : TEST_ALLOW_STD3_DISALLOWED), p, plen); if (rc != IDN2_OK) { free(p); return rc; } } dst[0] = 'x'; dst[1] = 'n'; dst[2] = '-'; dst[3] = '-'; tmpl = *dstlen - 4; rc = _idn2_punycode_encode (plen, p, &tmpl, (char *) dst + 4); free (p); if (rc != IDN2_OK) return rc; *dstlen = 4 + tmpl; return IDN2_OK; } #define TR46_TRANSITIONAL_CHECK \ (TEST_NFC | TEST_2HYPHEN | TEST_HYPHEN_STARTEND | TEST_LEADING_COMBINING | TEST_TRANSITIONAL) #define TR46_NONTRANSITIONAL_CHECK \ (TEST_NFC | TEST_2HYPHEN | TEST_HYPHEN_STARTEND | TEST_LEADING_COMBINING | TEST_NONTRANSITIONAL) static int _tr46 (const uint8_t * domain_u8, uint8_t ** out, int flags) { size_t len, it; uint32_t *domain_u32; int err = IDN2_OK, rc; int transitional = 0; int test_flags; if (flags & IDN2_TRANSITIONAL) transitional = 1; /* convert UTF-8 to UTF-32 */ if (!(domain_u32 = u8_to_u32 (domain_u8, u8_strlen (domain_u8) + 1, NULL, &len))) { if (errno == ENOMEM) return IDN2_MALLOC; return IDN2_ENCODING_ERROR; } size_t len2 = 0; for (it = 0; it < len - 1; it++) { IDNAMap map; get_idna_map (domain_u32[it], &map); if (map_is (&map, TR46_FLG_DISALLOWED)) { if (domain_u32[it]) { free (domain_u32); return IDN2_DISALLOWED; } len2++; } else if (map_is (&map, TR46_FLG_MAPPED)) { len2 += map.nmappings; } else if (map_is (&map, TR46_FLG_VALID)) { len2++; } else if (map_is (&map, TR46_FLG_IGNORED)) { continue; } else if (map_is (&map, TR46_FLG_DEVIATION)) { if (transitional) { len2 += map.nmappings; } else len2++; } else if (!(flags & IDN2_USE_STD3_ASCII_RULES)) { if (map_is (&map, TR46_FLG_DISALLOWED_STD3_VALID)) { /* valid because UseSTD3ASCIIRules=false, see #TR46 5 */ len2++; } else if (map_is (&map, TR46_FLG_DISALLOWED_STD3_MAPPED)) { /* mapped because UseSTD3ASCIIRules=false, see #TR46 5 */ len2 += map.nmappings; } } } uint32_t *tmp = (uint32_t *) malloc ((len2 + 1) * sizeof (uint32_t)); if (!tmp) { free (domain_u32); return IDN2_MALLOC; } len2 = 0; for (it = 0; it < len - 1; it++) { uint32_t c = domain_u32[it]; IDNAMap map; get_idna_map (c, &map); if (map_is (&map, TR46_FLG_DISALLOWED)) { tmp[len2++] = c; } else if (map_is (&map, TR46_FLG_MAPPED)) { len2 += get_map_data (tmp + len2, &map); } else if (map_is (&map, TR46_FLG_VALID)) { tmp[len2++] = c; } else if (map_is (&map, TR46_FLG_IGNORED)) { continue; } else if (map_is (&map, TR46_FLG_DEVIATION)) { if (transitional) { len2 += get_map_data (tmp + len2, &map); } else tmp[len2++] = c; } else if (!(flags & IDN2_USE_STD3_ASCII_RULES)) { if (map_is (&map, TR46_FLG_DISALLOWED_STD3_VALID)) { tmp[len2++] = c; } else if (map_is (&map, TR46_FLG_DISALLOWED_STD3_MAPPED)) { len2 += get_map_data (tmp + len2, &map); } } } free (domain_u32); /* Normalize to NFC */ tmp[len2] = 0; domain_u32 = u32_normalize (UNINORM_NFC, tmp, len2 + 1, NULL, &len); free (tmp); tmp = NULL; if (!domain_u32) { if (errno == ENOMEM) return IDN2_MALLOC; return IDN2_ENCODING_ERROR; } /* split into labels and check */ uint32_t *e, *s; for (e = s = domain_u32; *e; s = e) { while (*e && *e != '.') e++; if (e - s >= 4 && s[0] == 'x' && s[1] == 'n' && s[2] == '-' && s[3] == '-') { /* decode punycode and check result non-transitional */ size_t ace_len; uint32_t name_u32[IDN2_LABEL_MAX_LENGTH]; size_t name_len = IDN2_LABEL_MAX_LENGTH; uint8_t *ace; ace = u32_to_u8 (s + 4, e - s - 4, NULL, &ace_len); if (!ace) { free (domain_u32); if (errno == ENOMEM) return IDN2_MALLOC; return IDN2_ENCODING_ERROR; } rc = _idn2_punycode_decode (ace_len, (char *) ace, &name_len, name_u32); free (ace); if (rc) { free (domain_u32); return rc; } test_flags = TR46_NONTRANSITIONAL_CHECK; if (!(flags & IDN2_USE_STD3_ASCII_RULES)) test_flags |= TEST_ALLOW_STD3_DISALLOWED; if ((rc = _idn2_label_test (test_flags, name_u32, name_len))) err = rc; } else { test_flags = transitional ? TR46_TRANSITIONAL_CHECK : TR46_NONTRANSITIONAL_CHECK; if (!(flags & IDN2_USE_STD3_ASCII_RULES)) test_flags |= TEST_ALLOW_STD3_DISALLOWED; if ((rc = _idn2_label_test (test_flags, s, e - s))) err = rc; } if (*e) e++; } if (err == IDN2_OK && out) { uint8_t *_out = u32_to_u8 (domain_u32, len, NULL, &len); free (domain_u32); if (!_out) { if (errno == ENOMEM) return IDN2_MALLOC; return IDN2_ENCODING_ERROR; } *out = _out; } else free (domain_u32); return err; } /** * idn2_lookup_u8: * @src: input zero-terminated UTF-8 string in Unicode NFC normalized form. * @lookupname: newly allocated output variable with name to lookup in DNS. * @flags: optional #idn2_flags to modify behaviour. * * Perform IDNA2008 lookup string conversion on domain name @src, as * described in section 5 of RFC 5891. Note that the input string * must be encoded in UTF-8 and be in Unicode NFC form. * * Pass %IDN2_NFC_INPUT in @flags to convert input to NFC form before * further processing. %IDN2_TRANSITIONAL and %IDN2_NONTRANSITIONAL * do already imply %IDN2_NFC_INPUT. * Pass %IDN2_ALABEL_ROUNDTRIP in @flags to * convert any input A-labels to U-labels and perform additional * testing (not implemented yet). * Pass %IDN2_TRANSITIONAL to enable Unicode TR46 * transitional processing, and %IDN2_NONTRANSITIONAL to enable * Unicode TR46 non-transitional processing. Multiple flags may be * specified by binary or:ing them together. * * After version 2.0.3: %IDN2_USE_STD3_ASCII_RULES disabled by default. * Previously we were eliminating non-STD3 characters from domain strings * such as _443._tcp.example.com, or IPs 1.2.3.4/24 provided to libidn2 * functions. That was an unexpected regression for applications switching * from libidn and thus it is no longer applied by default. * Use %IDN2_USE_STD3_ASCII_RULES to enable that behavior again. * * After version 0.11: @lookupname may be NULL to test lookup of @src * without allocating memory. * * Returns: On successful conversion %IDN2_OK is returned, if the * output domain or any label would have been too long * %IDN2_TOO_BIG_DOMAIN or %IDN2_TOO_BIG_LABEL is returned, or * another error code is returned. * * Since: 0.1 **/ int idn2_lookup_u8 (const uint8_t * src, uint8_t ** lookupname, int flags) { size_t lookupnamelen = 0; uint8_t _lookupname[IDN2_DOMAIN_MAX_LENGTH + 1]; uint8_t _mapped[IDN2_DOMAIN_MAX_LENGTH + 1]; int rc; if (src == NULL) { if (lookupname) *lookupname = NULL; return IDN2_OK; } rc = set_default_flags(&flags); if (rc != IDN2_OK) return rc; if (!(flags & IDN2_NO_TR46)) { uint8_t *out; size_t outlen; rc = _tr46 (src, &out, flags); if (rc != IDN2_OK) return rc; outlen = u8_strlen (out); if (outlen >= sizeof (_mapped)) { free (out); return IDN2_TOO_BIG_DOMAIN; } memcpy (_mapped, out, outlen + 1); src = _mapped; free (out); } do { const uint8_t *end = (uint8_t *) strchrnul ((const char *) src, '.'); /* XXX Do we care about non-U+002E dots such as U+3002, U+FF0E and U+FF61 here? Perhaps when IDN2_NFC_INPUT? */ size_t labellen = end - src; uint8_t tmp[IDN2_LABEL_MAX_LENGTH]; size_t tmplen = IDN2_LABEL_MAX_LENGTH; rc = label (src, labellen, tmp, &tmplen, flags); if (rc != IDN2_OK) return rc; if (lookupnamelen + tmplen > IDN2_DOMAIN_MAX_LENGTH - (tmplen == 0 && *end == '\0' ? 1 : 2)) return IDN2_TOO_BIG_DOMAIN; memcpy (_lookupname + lookupnamelen, tmp, tmplen); lookupnamelen += tmplen; if (*end == '.') { if (lookupnamelen + 1 > IDN2_DOMAIN_MAX_LENGTH) return IDN2_TOO_BIG_DOMAIN; _lookupname[lookupnamelen] = '.'; lookupnamelen++; } _lookupname[lookupnamelen] = '\0'; src = end; } while (*src++); if (lookupname) { uint8_t *tmp = (uint8_t *) malloc (lookupnamelen + 1); if (tmp == NULL) return IDN2_MALLOC; memcpy (tmp, _lookupname, lookupnamelen + 1); *lookupname = tmp; } return IDN2_OK; } /** * idn2_lookup_ul: * @src: input zero-terminated locale encoded string. * @lookupname: newly allocated output variable with name to lookup in DNS. * @flags: optional #idn2_flags to modify behaviour. * * Perform IDNA2008 lookup string conversion on domain name @src, as * described in section 5 of RFC 5891. Note that the input is assumed * to be encoded in the locale's default coding system, and will be * transcoded to UTF-8 and NFC normalized by this function. * * Pass %IDN2_ALABEL_ROUNDTRIP in @flags to convert any input A-labels * to U-labels and perform additional testing. Pass * %IDN2_TRANSITIONAL to enable Unicode TR46 transitional processing, * and %IDN2_NONTRANSITIONAL to enable Unicode TR46 non-transitional * processing. Multiple flags may be specified by binary or:ing them * together, for example %IDN2_ALABEL_ROUNDTRIP | * %IDN2_NONTRANSITIONAL. The %IDN2_NFC_INPUT in @flags is always * enabled in this function. * * After version 0.11: @lookupname may be NULL to test lookup of @src * without allocating memory. * * Returns: On successful conversion %IDN2_OK is returned, if * conversion from locale to UTF-8 fails then %IDN2_ICONV_FAIL is * returned, if the output domain or any label would have been too * long %IDN2_TOO_BIG_DOMAIN or %IDN2_TOO_BIG_LABEL is returned, or * another error code is returned. * * Since: 0.1 **/ int idn2_lookup_ul (const char * src, char ** lookupname, int flags) { uint8_t *utf8src = NULL; int rc; if (src) { const char *encoding = locale_charset (); utf8src = u8_strconv_from_encoding (src, encoding, iconveh_error); if (!utf8src) { if (errno == ENOMEM) return IDN2_MALLOC; return IDN2_ICONV_FAIL; } } rc = idn2_lookup_u8 (utf8src, (uint8_t **) lookupname, flags | IDN2_NFC_INPUT); free (utf8src); return rc; } /** * idn2_to_ascii_4i: * @input: zero terminated input Unicode (UCS-4) string. * @inlen: number of elements in @input. * @output: pointer to newly allocated zero-terminated output string. * @flags: optional #idn2_flags to modify behaviour. * * The ToASCII operation takes a sequence of Unicode code points that make * up one domain label and transforms it into a sequence of code points in * the ASCII range (0..7F). If ToASCII succeeds, the original sequence and * the resulting sequence are equivalent labels. * * It is important to note that the ToASCII operation can fail. * ToASCII fails if any step of it fails. If any step of the * ToASCII operation fails on any label in a domain name, that domain * name MUST NOT be used as an internationalized domain name. * The method for dealing with this failure is application-specific. * * The inputs to ToASCII are a sequence of code points. * * ToASCII never alters a sequence of code points that are all in the ASCII * range to begin with (although it could fail). Applying the ToASCII operation multiple * effect as applying it just once. * * The default behavior of this function (when flags are zero) is to apply * the IDNA2008 rules without the TR46 amendments. As the TR46 * non-transitional processing is nowadays ubiquitous, when unsure, it is * recommended to call this function with the %IDN2_NONTRANSITIONAL * and the %IDN2_NFC_INPUT flags for compatibility with other software. * * Return value: Returns %IDN2_OK on success, or error code. * * Since: 2.0.0 **/ int idn2_to_ascii_4i (const uint32_t * input, size_t inlen, char * output, int flags) { uint32_t *input_u32; uint8_t *input_u8, *output_u8; size_t length; int rc; if (!input) { if (output) *output = 0; return IDN2_OK; } input_u32 = (uint32_t *) malloc ((inlen + 1) * sizeof(uint32_t)); if (!input_u32) return IDN2_MALLOC; u32_cpy (input_u32, input, inlen); input_u32[inlen] = 0; input_u8 = u32_to_u8 (input_u32, inlen + 1, NULL, &length); free (input_u32); if (!input_u8) { if (errno == ENOMEM) return IDN2_MALLOC; return IDN2_ENCODING_ERROR; } rc = idn2_lookup_u8 (input_u8, &output_u8, flags); free (input_u8); if (rc == IDN2_OK) { /* wow, this is ugly, but libidn manpage states: * char * out output zero terminated string that must have room for at * least 63 characters plus the terminating zero. */ if (output) strcpy (output, (const char *) output_u8); free(output_u8); } return rc; } /** * idn2_to_ascii_4z: * @input: zero terminated input Unicode (UCS-4) string. * @output: pointer to newly allocated zero-terminated output string. * @flags: optional #idn2_flags to modify behaviour. * * Convert UCS-4 domain name to ASCII string using the IDNA2008 * rules. The domain name may contain several labels, separated by dots. * The output buffer must be deallocated by the caller. * * The default behavior of this function (when flags are zero) is to apply * the IDNA2008 rules without the TR46 amendments. As the TR46 * non-transitional processing is nowadays ubiquitous, when unsure, it is * recommended to call this function with the %IDN2_NONTRANSITIONAL * and the %IDN2_NFC_INPUT flags for compatibility with other software. * * Return value: Returns %IDN2_OK on success, or error code. * * Since: 2.0.0 **/ int idn2_to_ascii_4z (const uint32_t * input, char ** output, int flags) { uint8_t *input_u8; size_t length; int rc; if (!input) { if (output) *output = NULL; return IDN2_OK; } input_u8 = u32_to_u8 (input, u32_strlen(input) + 1, NULL, &length); if (!input_u8) { if (errno == ENOMEM) return IDN2_MALLOC; return IDN2_ENCODING_ERROR; } rc = idn2_lookup_u8 (input_u8, (uint8_t **) output, flags); free (input_u8); return rc; } /** * idn2_to_ascii_8z: * @input: zero terminated input UTF-8 string. * @output: pointer to newly allocated output string. * @flags: optional #idn2_flags to modify behaviour. * * Convert UTF-8 domain name to ASCII string using the IDNA2008 * rules. The domain name may contain several labels, separated by dots. * The output buffer must be deallocated by the caller. * * The default behavior of this function (when flags are zero) is to apply * the IDNA2008 rules without the TR46 amendments. As the TR46 * non-transitional processing is nowadays ubiquitous, when unsure, it is * recommended to call this function with the %IDN2_NONTRANSITIONAL * and the %IDN2_NFC_INPUT flags for compatibility with other software. * * Return value: Returns %IDN2_OK on success, or error code. * * Since: 2.0.0 **/ int idn2_to_ascii_8z (const char * input, char ** output, int flags) { return idn2_lookup_u8 ((const uint8_t *) input, (uint8_t **) output, flags); } /** * idn2_to_ascii_lz: * @input: zero terminated input UTF-8 string. * @output: pointer to newly allocated output string. * @flags: optional #idn2_flags to modify behaviour. * * Convert a domain name in locale's encoding to ASCII string using the IDNA2008 * rules. The domain name may contain several labels, separated by dots. * The output buffer must be deallocated by the caller. * * The default behavior of this function (when flags are zero) is to apply * the IDNA2008 rules without the TR46 amendments. As the TR46 * non-transitional processing is nowadays ubiquitous, when unsure, it is * recommended to call this function with the %IDN2_NONTRANSITIONAL * and the %IDN2_NFC_INPUT flags for compatibility with other software. * * Returns: %IDN2_OK on success, or error code. * Same as described in idn2_lookup_ul() documentation. * * Since: 2.0.0 **/ int idn2_to_ascii_lz (const char * input, char ** output, int flags) { return idn2_lookup_ul (input, output, flags); }
null
/* lookup.c - implementation of IDNA2008 lookup functions Copyright (C) 2011-2017 Simon Josefsson Libidn2 is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <config.h> #include "idn2.h" #include <errno.h> /* errno */ #include <stdlib.h> /* malloc, free */ #include "punycode.h" #include <unitypes.h> #include <uniconv.h> /* u8_strconv_from_locale */ #include <uninorm.h> /* u32_normalize */ #include <unistr.h> /* u8_to_u32 */ #include "idna.h" /* _idn2_label_test */ #include "tr46map.h" /* definition for tr46map.c */ static int set_default_flags(int *flags) { if (((*flags) & IDN2_TRANSITIONAL) && ((*flags) & IDN2_NONTRANSITIONAL)) return IDN2_INVALID_FLAGS; if (((*flags) & (IDN2_TRANSITIONAL|IDN2_NONTRANSITIONAL)) && ((*flags) & IDN2_NO_TR46)) return IDN2_INVALID_FLAGS; if (!((*flags) & (IDN2_NO_TR46|IDN2_TRANSITIONAL))) *flags |= IDN2_NONTRANSITIONAL; return IDN2_OK; } static int label (const uint8_t * src, size_t srclen, uint8_t * dst, size_t * dstlen, int flags) { size_t plen; uint32_t *p; int rc; size_t tmpl; if (_idn2_ascii_p (src, srclen)) { if (flags & IDN2_ALABEL_ROUNDTRIP) /* FIXME implement this MAY: If the input to this procedure appears to be an A-label (i.e., it starts in "xn--", interpreted case-insensitively), the lookup application MAY attempt to convert it to a U-label, first ensuring that the A-label is entirely in lowercase (converting it to lowercase if necessary), and apply the tests of Section 5.4 and the conversion of Section 5.5 to that form. */ return IDN2_INVALID_FLAGS; if (srclen > IDN2_LABEL_MAX_LENGTH) return IDN2_TOO_BIG_LABEL; if (srclen > *dstlen) return IDN2_TOO_BIG_DOMAIN; memcpy (dst, src, srclen); *dstlen = srclen; return IDN2_OK; } rc = _idn2_u8_to_u32_nfc (src, srclen, &p, &plen, flags & IDN2_NFC_INPUT); if (rc != IDN2_OK) return rc; if (!(flags & IDN2_TRANSITIONAL)) { rc = _idn2_label_test( TEST_NFC | TEST_2HYPHEN | TEST_LEADING_COMBINING | TEST_DISALLOWED | TEST_CONTEXTJ_RULE | TEST_CONTEXTO_WITH_RULE | TEST_UNASSIGNED | TEST_BIDI | ((flags & IDN2_NONTRANSITIONAL) ? TEST_NONTRANSITIONAL : 0) | ((flags & IDN2_USE_STD3_ASCII_RULES) ? 0 : TEST_ALLOW_STD3_DISALLOWED), p, plen); if (rc != IDN2_OK) { free(p); return rc; } } dst[0] = 'x'; dst[1] = 'n'; dst[2] = '-'; dst[3] = '-'; tmpl = *dstlen - 4; rc = _idn2_punycode_encode (plen, p, &tmpl, (char *) dst + 4); free (p); if (rc != IDN2_OK) return rc; *dstlen = 4 + tmpl; return IDN2_OK; } #define TR46_TRANSITIONAL_CHECK \ (TEST_NFC | TEST_2HYPHEN | TEST_HYPHEN_STARTEND | TEST_LEADING_COMBINING | TEST_TRANSITIONAL) #define TR46_NONTRANSITIONAL_CHECK \ (TEST_NFC | TEST_2HYPHEN | TEST_HYPHEN_STARTEND | TEST_LEADING_COMBINING | TEST_NONTRANSITIONAL) static int _tr46 (const uint8_t * domain_u8, uint8_t ** out, int flags) { size_t len, it; uint32_t *domain_u32; int err = IDN2_OK, rc; int transitional = 0; int test_flags; if (flags & IDN2_TRANSITIONAL) transitional = 1; /* convert UTF-8 to UTF-32 */ if (!(domain_u32 = u8_to_u32 (domain_u8, u8_strlen (domain_u8) + 1, NULL, &len))) { if (errno == ENOMEM) return IDN2_MALLOC; return IDN2_ENCODING_ERROR; } size_t len2 = 0; for (it = 0; it < len - 1; it++) { IDNAMap map; get_idna_map (domain_u32[it], &map); if (map_is (&map, TR46_FLG_DISALLOWED)) { if (domain_u32[it]) { free (domain_u32); return IDN2_DISALLOWED; } len2++; } else if (map_is (&map, TR46_FLG_MAPPED)) { len2 += map.nmappings; } else if (map_is (&map, TR46_FLG_VALID)) { len2++; } else if (map_is (&map, TR46_FLG_IGNORED)) { continue; } else if (map_is (&map, TR46_FLG_DEVIATION)) { if (transitional) { len2 += map.nmappings; } else len2++; } else if (!(flags & IDN2_USE_STD3_ASCII_RULES)) { if (map_is (&map, TR46_FLG_DISALLOWED_STD3_VALID)) { /* valid because UseSTD3ASCIIRules=false, see #TR46 5 */ len2++; } else if (map_is (&map, TR46_FLG_DISALLOWED_STD3_MAPPED)) { /* mapped because UseSTD3ASCIIRules=false, see #TR46 5 */ len2 += map.nmappings; } } } uint32_t *tmp = (uint32_t *) malloc ((len2 + 1) * sizeof (uint32_t)); if (!tmp) { free (domain_u32); return IDN2_MALLOC; } len2 = 0; for (it = 0; it < len - 1; it++) { uint32_t c = domain_u32[it]; IDNAMap map; get_idna_map (c, &map); if (map_is (&map, TR46_FLG_DISALLOWED)) { tmp[len2++] = c; } else if (map_is (&map, TR46_FLG_MAPPED)) { len2 += get_map_data (tmp + len2, &map); } else if (map_is (&map, TR46_FLG_VALID)) { tmp[len2++] = c; } else if (map_is (&map, TR46_FLG_IGNORED)) { continue; } else if (map_is (&map, TR46_FLG_DEVIATION)) { if (transitional) { len2 += get_map_data (tmp + len2, &map); } else tmp[len2++] = c; } else if (!(flags & IDN2_USE_STD3_ASCII_RULES)) { if (map_is (&map, TR46_FLG_DISALLOWED_STD3_VALID)) { tmp[len2++] = c; } else if (map_is (&map, TR46_FLG_DISALLOWED_STD3_MAPPED)) { len2 += get_map_data (tmp + len2, &map); } } } free (domain_u32); /* Normalize to NFC */ tmp[len2] = 0; domain_u32 = u32_normalize (UNINORM_NFC, tmp, len2 + 1, NULL, &len); free (tmp); tmp = NULL; if (!domain_u32) { if (errno == ENOMEM) return IDN2_MALLOC; return IDN2_ENCODING_ERROR; } /* split into labels and check */ uint32_t *e, *s; for (e = s = domain_u32; *e; s = e) { while (*e && *e != '.') e++; if (e - s >= 4 && s[0] == 'x' && s[1] == 'n' && s[2] == '-' && s[3] == '-') { /* decode punycode and check result non-transitional */ size_t ace_len; uint32_t name_u32[IDN2_LABEL_MAX_LENGTH]; size_t name_len = IDN2_LABEL_MAX_LENGTH; uint8_t *ace; ace = u32_to_u8 (s + 4, e - s - 4, NULL, &ace_len); if (!ace) { free (domain_u32); if (errno == ENOMEM) return IDN2_MALLOC; return IDN2_ENCODING_ERROR; } rc = _idn2_punycode_decode (ace_len, (char *) ace, &name_len, name_u32); free (ace); if (rc) { free (domain_u32); return rc; } test_flags = TR46_NONTRANSITIONAL_CHECK; if (!(flags & IDN2_USE_STD3_ASCII_RULES)) test_flags |= TEST_ALLOW_STD3_DISALLOWED; if ((rc = _idn2_label_test (test_flags, name_u32, name_len))) err = rc; } else { test_flags = transitional ? TR46_TRANSITIONAL_CHECK : TR46_NONTRANSITIONAL_CHECK; if (!(flags & IDN2_USE_STD3_ASCII_RULES)) test_flags |= TEST_ALLOW_STD3_DISALLOWED; if ((rc = _idn2_label_test (test_flags, s, e - s))) err = rc; } if (*e) e++; } if (err == IDN2_OK && out) { uint8_t *_out = u32_to_u8 (domain_u32, len, NULL, &len); free (domain_u32); if (!_out) { if (errno == ENOMEM) return IDN2_MALLOC; return IDN2_ENCODING_ERROR; } *out = _out; } else free (domain_u32); return err; } /** * idn2_lookup_u8: * @src: input zero-terminated UTF-8 string in Unicode NFC normalized form. * @lookupname: newly allocated output variable with name to lookup in DNS. * @flags: optional #idn2_flags to modify behaviour. * * Perform IDNA2008 lookup string conversion on domain name @src, as * described in section 5 of RFC 5891. Note that the input string * must be encoded in UTF-8 and be in Unicode NFC form. * * Pass %IDN2_NFC_INPUT in @flags to convert input to NFC form before * further processing. %IDN2_TRANSITIONAL and %IDN2_NONTRANSITIONAL * do already imply %IDN2_NFC_INPUT. * Pass %IDN2_ALABEL_ROUNDTRIP in @flags to * convert any input A-labels to U-labels and perform additional * testing (not implemented yet). * Pass %IDN2_TRANSITIONAL to enable Unicode TR46 * transitional processing, and %IDN2_NONTRANSITIONAL to enable * Unicode TR46 non-transitional processing. Multiple flags may be * specified by binary or:ing them together. * * After version 2.0.3: %IDN2_USE_STD3_ASCII_RULES disabled by default. * Previously we were eliminating non-STD3 characters from domain strings * such as _443._tcp.example.com, or IPs 1.2.3.4/24 provided to libidn2 * functions. That was an unexpected regression for applications switching * from libidn and thus it is no longer applied by default. * Use %IDN2_USE_STD3_ASCII_RULES to enable that behavior again. * * After version 0.11: @lookupname may be NULL to test lookup of @src * without allocating memory. * * Returns: On successful conversion %IDN2_OK is returned, if the * output domain or any label would have been too long * %IDN2_TOO_BIG_DOMAIN or %IDN2_TOO_BIG_LABEL is returned, or * another error code is returned. * * Since: 0.1 **/ int idn2_lookup_u8 (const uint8_t * src, uint8_t ** lookupname, int flags) { size_t lookupnamelen = 0; uint8_t _lookupname[IDN2_DOMAIN_MAX_LENGTH + 1]; uint8_t _mapped[IDN2_DOMAIN_MAX_LENGTH + 1]; int rc; if (src == NULL) { if (lookupname) *lookupname = NULL; return IDN2_OK; } rc = set_default_flags(&flags); if (rc != IDN2_OK) return rc; if (!(flags & IDN2_NO_TR46)) { uint8_t *out; size_t outlen; rc = _tr46 (src, &out, flags); if (rc != IDN2_OK) return rc; outlen = u8_strlen (out); if (outlen >= sizeof (_mapped)) { free (out); return IDN2_TOO_BIG_DOMAIN; } memcpy (_mapped, out, outlen + 1); src = _mapped; free (out); } do { const uint8_t *end = (uint8_t *) strchrnul ((const char *) src, '.'); /* XXX Do we care about non-U+002E dots such as U+3002, U+FF0E and U+FF61 here? Perhaps when IDN2_NFC_INPUT? */ size_t labellen = end - src; uint8_t tmp[IDN2_LABEL_MAX_LENGTH]; size_t tmplen = IDN2_LABEL_MAX_LENGTH; rc = label (src, labellen, tmp, &tmplen, flags); if (rc != IDN2_OK) return rc; if (lookupnamelen + tmplen > IDN2_DOMAIN_MAX_LENGTH - (tmplen == 0 && *end == '\0' ? 1 : 2)) return IDN2_TOO_BIG_DOMAIN; memcpy (_lookupname + lookupnamelen, tmp, tmplen); lookupnamelen += tmplen; if (*end == '.') { if (lookupnamelen + 1 > IDN2_DOMAIN_MAX_LENGTH) return IDN2_TOO_BIG_DOMAIN; _lookupname[lookupnamelen] = '.'; lookupnamelen++; } _lookupname[lookupnamelen] = '\0'; src = end; } while (*src++); if (lookupname) { uint8_t *tmp = (uint8_t *) malloc (lookupnamelen + 1); if (tmp == NULL) return IDN2_MALLOC; memcpy (tmp, _lookupname, lookupnamelen + 1); *lookupname = tmp; } return IDN2_OK; } /** * idn2_lookup_ul: * @src: input zero-terminated locale encoded string. * @lookupname: newly allocated output variable with name to lookup in DNS. * @flags: optional #idn2_flags to modify behaviour. * * Perform IDNA2008 lookup string conversion on domain name @src, as * described in section 5 of RFC 5891. Note that the input is assumed * to be encoded in the locale's default coding system, and will be * transcoded to UTF-8 and NFC normalized by this function. * * Pass %IDN2_ALABEL_ROUNDTRIP in @flags to convert any input A-labels * to U-labels and perform additional testing. Pass * %IDN2_TRANSITIONAL to enable Unicode TR46 transitional processing, * and %IDN2_NONTRANSITIONAL to enable Unicode TR46 non-transitional * processing. Multiple flags may be specified by binary or:ing them * together, for example %IDN2_ALABEL_ROUNDTRIP | * %IDN2_NONTRANSITIONAL. The %IDN2_NFC_INPUT in @flags is always * enabled in this function. * * After version 0.11: @lookupname may be NULL to test lookup of @src * without allocating memory. * * Returns: On successful conversion %IDN2_OK is returned, if * conversion from locale to UTF-8 fails then %IDN2_ICONV_FAIL is * returned, if the output domain or any label would have been too * long %IDN2_TOO_BIG_DOMAIN or %IDN2_TOO_BIG_LABEL is returned, or * another error code is returned. * * Since: 0.1 **/ int idn2_lookup_ul (const char * src, char ** lookupname, int flags) { uint8_t *utf8src = NULL; int rc; if (src) { const char *encoding = locale_charset (); utf8src = u8_strconv_from_encoding (src, encoding, iconveh_error); if (!utf8src) { if (errno == ENOMEM) return IDN2_MALLOC; return IDN2_ICONV_FAIL; } } rc = idn2_lookup_u8 (utf8src, (uint8_t **) lookupname, flags | IDN2_NFC_INPUT); free (utf8src); return rc; } /** * idn2_to_ascii_4i: * @input: zero terminated input Unicode (UCS-4) string. * @inlen: number of elements in @input. * @output: pointer to newly allocated zero-terminated output string. * @flags: optional #idn2_flags to modify behaviour. * * The ToASCII operation takes a sequence of Unicode code points that make * up one domain label and transforms it into a sequence of code points in * the ASCII range (0..7F). If ToASCII succeeds, the original sequence and * the resulting sequence are equivalent labels. * * It is important to note that the ToASCII operation can fail. * ToASCII fails if any step of it fails. If any step of the * ToASCII operation fails on any label in a domain name, that domain * name MUST NOT be used as an internationalized domain name. * The method for dealing with this failure is application-specific. * * The inputs to ToASCII are a sequence of code points. * * ToASCII never alters a sequence of code points that are all in the ASCII * range to begin with (although it could fail). Applying the ToASCII operation multiple * effect as applying it just once. * * The default behavior of this function (when flags are zero) is to apply * the IDNA2008 rules without the TR46 amendments. As the TR46 * non-transitional processing is nowadays ubiquitous, when unsure, it is * recommended to call this function with the %IDN2_NONTRANSITIONAL * and the %IDN2_NFC_INPUT flags for compatibility with other software. * * Return value: Returns %IDN2_OK on success, or error code. * * Since: 2.0.0 **/ int idn2_to_ascii_4i (const uint32_t * input, size_t inlen, char * output, int flags) { uint32_t *input_u32; uint8_t *input_u8, *output_u8; size_t length; int rc; if (!input) { if (output) *output = 0; return IDN2_OK; } input_u32 = (uint32_t *) malloc ((inlen + 1) * sizeof(uint32_t)); if (!input_u32) return IDN2_MALLOC; u32_cpy (input_u32, input, inlen); input_u32[inlen] = 0; input_u8 = u32_to_u8 (input_u32, inlen + 1, NULL, &length); free (input_u32); if (!input_u8) { if (errno == ENOMEM) return IDN2_MALLOC; return IDN2_ENCODING_ERROR; } rc = idn2_lookup_u8 (input_u8, &output_u8, flags); free (input_u8); if (rc == IDN2_OK) { /* wow, this is ugly, but libidn manpage states: * char * out output zero terminated string that must have room for at * least 63 characters plus the terminating zero. */ size_t len = strlen ((char *) output_u8); if (len > 63) { free (output_u8); return IDN2_TOO_BIG_DOMAIN; } if (output) strcpy (output, (char *) output_u8); free (output_u8); } return rc; } /** * idn2_to_ascii_4z: * @input: zero terminated input Unicode (UCS-4) string. * @output: pointer to newly allocated zero-terminated output string. * @flags: optional #idn2_flags to modify behaviour. * * Convert UCS-4 domain name to ASCII string using the IDNA2008 * rules. The domain name may contain several labels, separated by dots. * The output buffer must be deallocated by the caller. * * The default behavior of this function (when flags are zero) is to apply * the IDNA2008 rules without the TR46 amendments. As the TR46 * non-transitional processing is nowadays ubiquitous, when unsure, it is * recommended to call this function with the %IDN2_NONTRANSITIONAL * and the %IDN2_NFC_INPUT flags for compatibility with other software. * * Return value: Returns %IDN2_OK on success, or error code. * * Since: 2.0.0 **/ int idn2_to_ascii_4z (const uint32_t * input, char ** output, int flags) { uint8_t *input_u8; size_t length; int rc; if (!input) { if (output) *output = NULL; return IDN2_OK; } input_u8 = u32_to_u8 (input, u32_strlen(input) + 1, NULL, &length); if (!input_u8) { if (errno == ENOMEM) return IDN2_MALLOC; return IDN2_ENCODING_ERROR; } rc = idn2_lookup_u8 (input_u8, (uint8_t **) output, flags); free (input_u8); return rc; } /** * idn2_to_ascii_8z: * @input: zero terminated input UTF-8 string. * @output: pointer to newly allocated output string. * @flags: optional #idn2_flags to modify behaviour. * * Convert UTF-8 domain name to ASCII string using the IDNA2008 * rules. The domain name may contain several labels, separated by dots. * The output buffer must be deallocated by the caller. * * The default behavior of this function (when flags are zero) is to apply * the IDNA2008 rules without the TR46 amendments. As the TR46 * non-transitional processing is nowadays ubiquitous, when unsure, it is * recommended to call this function with the %IDN2_NONTRANSITIONAL * and the %IDN2_NFC_INPUT flags for compatibility with other software. * * Return value: Returns %IDN2_OK on success, or error code. * * Since: 2.0.0 **/ int idn2_to_ascii_8z (const char * input, char ** output, int flags) { return idn2_lookup_u8 ((const uint8_t *) input, (uint8_t **) output, flags); } /** * idn2_to_ascii_lz: * @input: zero terminated input UTF-8 string. * @output: pointer to newly allocated output string. * @flags: optional #idn2_flags to modify behaviour. * * Convert a domain name in locale's encoding to ASCII string using the IDNA2008 * rules. The domain name may contain several labels, separated by dots. * The output buffer must be deallocated by the caller. * * The default behavior of this function (when flags are zero) is to apply * the IDNA2008 rules without the TR46 amendments. As the TR46 * non-transitional processing is nowadays ubiquitous, when unsure, it is * recommended to call this function with the %IDN2_NONTRANSITIONAL * and the %IDN2_NFC_INPUT flags for compatibility with other software. * * Returns: %IDN2_OK on success, or error code. * Same as described in idn2_lookup_ul() documentation. * * Since: 2.0.0 **/ int idn2_to_ascii_lz (const char * input, char ** output, int flags) { return idn2_lookup_ul (input, output, flags); }
null
149
CWE-787
CVE-2019-18609
/* * ***** BEGIN LICENSE BLOCK ***** * Version: MIT * * Portions created by Alan Antonuk are Copyright (c) 2012-2014 * Alan Antonuk. All Rights Reserved. * * Portions created by VMware are Copyright (c) 2007-2012 VMware, Inc. * All Rights Reserved. * * Portions created by Tony Garnock-Jones are Copyright (c) 2009-2010 * VMware, Inc. and Tony Garnock-Jones. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * ***** END LICENSE BLOCK ***** */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef _MSC_VER #define _CRT_SECURE_NO_WARNINGS #endif #include "amqp_private.h" #include "amqp_tcp_socket.h" #include "amqp_time.h" #include <errno.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifndef AMQP_INITIAL_FRAME_POOL_PAGE_SIZE #define AMQP_INITIAL_FRAME_POOL_PAGE_SIZE 65536 #endif #ifndef AMQP_INITIAL_INBOUND_SOCK_BUFFER_SIZE #define AMQP_INITIAL_INBOUND_SOCK_BUFFER_SIZE 131072 #endif #ifndef AMQP_DEFAULT_LOGIN_TIMEOUT_SEC #define AMQP_DEFAULT_LOGIN_TIMEOUT_SEC 12 #endif #define ENFORCE_STATE(statevec, statenum) \ { \ amqp_connection_state_t _check_state = (statevec); \ amqp_connection_state_enum _wanted_state = (statenum); \ if (_check_state->state != _wanted_state) \ amqp_abort( \ "Programming error: invalid AMQP connection state: expected %d, " \ "got %d", \ _wanted_state, _check_state->state); \ } amqp_connection_state_t amqp_new_connection(void) { int res; amqp_connection_state_t state = (amqp_connection_state_t)calloc( 1, sizeof(struct amqp_connection_state_t_)); if (state == NULL) { return NULL; } res = amqp_tune_connection(state, 0, AMQP_INITIAL_FRAME_POOL_PAGE_SIZE, 0); if (0 != res) { goto out_nomem; } state->inbound_buffer.bytes = state->header_buffer; state->inbound_buffer.len = sizeof(state->header_buffer); state->state = CONNECTION_STATE_INITIAL; /* the server protocol version response is 8 bytes, which conveniently is also the minimum frame size */ state->target_size = 8; state->sock_inbound_buffer.len = AMQP_INITIAL_INBOUND_SOCK_BUFFER_SIZE; state->sock_inbound_buffer.bytes = malloc(AMQP_INITIAL_INBOUND_SOCK_BUFFER_SIZE); if (state->sock_inbound_buffer.bytes == NULL) { goto out_nomem; } init_amqp_pool(&state->properties_pool, 512); /* Use address of the internal_handshake_timeout object by default. */ state->internal_handshake_timeout.tv_sec = AMQP_DEFAULT_LOGIN_TIMEOUT_SEC; state->internal_handshake_timeout.tv_usec = 0; state->handshake_timeout = &state->internal_handshake_timeout; return state; out_nomem: free(state->sock_inbound_buffer.bytes); free(state); return NULL; } int amqp_get_sockfd(amqp_connection_state_t state) { return state->socket ? amqp_socket_get_sockfd(state->socket) : -1; } void amqp_set_sockfd(amqp_connection_state_t state, int sockfd) { amqp_socket_t *socket = amqp_tcp_socket_new(state); if (!socket) { amqp_abort("%s", strerror(errno)); } amqp_tcp_socket_set_sockfd(socket, sockfd); } void amqp_set_socket(amqp_connection_state_t state, amqp_socket_t *socket) { amqp_socket_delete(state->socket); state->socket = socket; } amqp_socket_t *amqp_get_socket(amqp_connection_state_t state) { return state->socket; } int amqp_tune_connection(amqp_connection_state_t state, int channel_max, int frame_max, int heartbeat) { void *newbuf; int res; ENFORCE_STATE(state, CONNECTION_STATE_IDLE); state->channel_max = channel_max; state->frame_max = frame_max; state->heartbeat = heartbeat; if (0 > state->heartbeat) { state->heartbeat = 0; } res = amqp_time_s_from_now(&state->next_send_heartbeat, amqp_heartbeat_send(state)); if (AMQP_STATUS_OK != res) { return res; } res = amqp_time_s_from_now(&state->next_recv_heartbeat, amqp_heartbeat_recv(state)); if (AMQP_STATUS_OK != res) { return res; } state->outbound_buffer.len = frame_max; newbuf = realloc(state->outbound_buffer.bytes, frame_max); if (newbuf == NULL) { return AMQP_STATUS_NO_MEMORY; } state->outbound_buffer.bytes = newbuf; return AMQP_STATUS_OK; } int amqp_get_channel_max(amqp_connection_state_t state) { return state->channel_max; } int amqp_get_frame_max(amqp_connection_state_t state) { return state->frame_max; } int amqp_get_heartbeat(amqp_connection_state_t state) { return state->heartbeat; } int amqp_destroy_connection(amqp_connection_state_t state) { int status = AMQP_STATUS_OK; if (state) { int i; for (i = 0; i < POOL_TABLE_SIZE; ++i) { amqp_pool_table_entry_t *entry = state->pool_table[i]; while (NULL != entry) { amqp_pool_table_entry_t *todelete = entry; empty_amqp_pool(&entry->pool); entry = entry->next; free(todelete); } } free(state->outbound_buffer.bytes); free(state->sock_inbound_buffer.bytes); amqp_socket_delete(state->socket); empty_amqp_pool(&state->properties_pool); free(state); } return status; } static void return_to_idle(amqp_connection_state_t state) { state->inbound_buffer.len = sizeof(state->header_buffer); state->inbound_buffer.bytes = state->header_buffer; state->inbound_offset = 0; state->target_size = HEADER_SIZE; state->state = CONNECTION_STATE_IDLE; } static size_t consume_data(amqp_connection_state_t state, amqp_bytes_t *received_data) { /* how much data is available and will fit? */ size_t bytes_consumed = state->target_size - state->inbound_offset; if (received_data->len < bytes_consumed) { bytes_consumed = received_data->len; } memcpy(amqp_offset(state->inbound_buffer.bytes, state->inbound_offset), received_data->bytes, bytes_consumed); state->inbound_offset += bytes_consumed; received_data->bytes = amqp_offset(received_data->bytes, bytes_consumed); received_data->len -= bytes_consumed; return bytes_consumed; } int amqp_handle_input(amqp_connection_state_t state, amqp_bytes_t received_data, amqp_frame_t *decoded_frame) { size_t bytes_consumed; void *raw_frame; /* Returning frame_type of zero indicates either insufficient input, or a complete, ignored frame was read. */ decoded_frame->frame_type = 0; if (received_data.len == 0) { return AMQP_STATUS_OK; } if (state->state == CONNECTION_STATE_IDLE) { state->state = CONNECTION_STATE_HEADER; } bytes_consumed = consume_data(state, &received_data); /* do we have target_size data yet? if not, return with the expectation that more will arrive */ if (state->inbound_offset < state->target_size) { return (int)bytes_consumed; } raw_frame = state->inbound_buffer.bytes; switch (state->state) { case CONNECTION_STATE_INITIAL: /* check for a protocol header from the server */ if (memcmp(raw_frame, "AMQP", 4) == 0) { decoded_frame->frame_type = AMQP_PSEUDOFRAME_PROTOCOL_HEADER; decoded_frame->channel = 0; decoded_frame->payload.protocol_header.transport_high = amqp_d8(amqp_offset(raw_frame, 4)); decoded_frame->payload.protocol_header.transport_low = amqp_d8(amqp_offset(raw_frame, 5)); decoded_frame->payload.protocol_header.protocol_version_major = amqp_d8(amqp_offset(raw_frame, 6)); decoded_frame->payload.protocol_header.protocol_version_minor = amqp_d8(amqp_offset(raw_frame, 7)); return_to_idle(state); return (int)bytes_consumed; } /* it's not a protocol header; fall through to process it as a regular frame header */ case CONNECTION_STATE_HEADER: { amqp_channel_t channel; amqp_pool_t *channel_pool; /* frame length is 3 bytes in */ channel = amqp_d16(amqp_offset(raw_frame, 1)); state->target_size = amqp_d32(amqp_offset(raw_frame, 3)) + HEADER_SIZE + FOOTER_SIZE; if ((size_t)state->frame_max < state->target_size) { return AMQP_STATUS_BAD_AMQP_DATA; } channel_pool = amqp_get_or_create_channel_pool(state, channel); if (NULL == channel_pool) { return AMQP_STATUS_NO_MEMORY; } amqp_pool_alloc_bytes(channel_pool, state->target_size, &state->inbound_buffer); if (NULL == state->inbound_buffer.bytes) { return AMQP_STATUS_NO_MEMORY; } memcpy(state->inbound_buffer.bytes, state->header_buffer, HEADER_SIZE); raw_frame = state->inbound_buffer.bytes; state->state = CONNECTION_STATE_BODY; bytes_consumed += consume_data(state, &received_data); /* do we have target_size data yet? if not, return with the expectation that more will arrive */ if (state->inbound_offset < state->target_size) { return (int)bytes_consumed; } } /* fall through to process body */ case CONNECTION_STATE_BODY: { amqp_bytes_t encoded; int res; amqp_pool_t *channel_pool; /* Check frame end marker (footer) */ if (amqp_d8(amqp_offset(raw_frame, state->target_size - 1)) != AMQP_FRAME_END) { return AMQP_STATUS_BAD_AMQP_DATA; } decoded_frame->frame_type = amqp_d8(amqp_offset(raw_frame, 0)); decoded_frame->channel = amqp_d16(amqp_offset(raw_frame, 1)); channel_pool = amqp_get_or_create_channel_pool(state, decoded_frame->channel); if (NULL == channel_pool) { return AMQP_STATUS_NO_MEMORY; } switch (decoded_frame->frame_type) { case AMQP_FRAME_METHOD: decoded_frame->payload.method.id = amqp_d32(amqp_offset(raw_frame, HEADER_SIZE)); encoded.bytes = amqp_offset(raw_frame, HEADER_SIZE + 4); encoded.len = state->target_size - HEADER_SIZE - 4 - FOOTER_SIZE; res = amqp_decode_method(decoded_frame->payload.method.id, channel_pool, encoded, &decoded_frame->payload.method.decoded); if (res < 0) { return res; } break; case AMQP_FRAME_HEADER: decoded_frame->payload.properties.class_id = amqp_d16(amqp_offset(raw_frame, HEADER_SIZE)); /* unused 2-byte weight field goes here */ decoded_frame->payload.properties.body_size = amqp_d64(amqp_offset(raw_frame, HEADER_SIZE + 4)); encoded.bytes = amqp_offset(raw_frame, HEADER_SIZE + 12); encoded.len = state->target_size - HEADER_SIZE - 12 - FOOTER_SIZE; decoded_frame->payload.properties.raw = encoded; res = amqp_decode_properties( decoded_frame->payload.properties.class_id, channel_pool, encoded, &decoded_frame->payload.properties.decoded); if (res < 0) { return res; } break; case AMQP_FRAME_BODY: decoded_frame->payload.body_fragment.len = state->target_size - HEADER_SIZE - FOOTER_SIZE; decoded_frame->payload.body_fragment.bytes = amqp_offset(raw_frame, HEADER_SIZE); break; case AMQP_FRAME_HEARTBEAT: break; default: /* Ignore the frame */ decoded_frame->frame_type = 0; break; } return_to_idle(state); return (int)bytes_consumed; } default: amqp_abort("Internal error: invalid amqp_connection_state_t->state %d", state->state); } } amqp_boolean_t amqp_release_buffers_ok(amqp_connection_state_t state) { return (state->state == CONNECTION_STATE_IDLE); } void amqp_release_buffers(amqp_connection_state_t state) { int i; ENFORCE_STATE(state, CONNECTION_STATE_IDLE); for (i = 0; i < POOL_TABLE_SIZE; ++i) { amqp_pool_table_entry_t *entry = state->pool_table[i]; for (; NULL != entry; entry = entry->next) { amqp_maybe_release_buffers_on_channel(state, entry->channel); } } } void amqp_maybe_release_buffers(amqp_connection_state_t state) { if (amqp_release_buffers_ok(state)) { amqp_release_buffers(state); } } void amqp_maybe_release_buffers_on_channel(amqp_connection_state_t state, amqp_channel_t channel) { amqp_link_t *queued_link; amqp_pool_t *pool; if (CONNECTION_STATE_IDLE != state->state) { return; } queued_link = state->first_queued_frame; while (NULL != queued_link) { amqp_frame_t *frame = queued_link->data; if (channel == frame->channel) { return; } queued_link = queued_link->next; } pool = amqp_get_channel_pool(state, channel); if (pool != NULL) { recycle_amqp_pool(pool); } } static int amqp_frame_to_bytes(const amqp_frame_t *frame, amqp_bytes_t buffer, amqp_bytes_t *encoded) { void *out_frame = buffer.bytes; size_t out_frame_len; int res; amqp_e8(frame->frame_type, amqp_offset(out_frame, 0)); amqp_e16(frame->channel, amqp_offset(out_frame, 1)); switch (frame->frame_type) { case AMQP_FRAME_BODY: { const amqp_bytes_t *body = &frame->payload.body_fragment; memcpy(amqp_offset(out_frame, HEADER_SIZE), body->bytes, body->len); out_frame_len = body->len; break; } case AMQP_FRAME_METHOD: { amqp_bytes_t method_encoded; amqp_e32(frame->payload.method.id, amqp_offset(out_frame, HEADER_SIZE)); method_encoded.bytes = amqp_offset(out_frame, HEADER_SIZE + 4); method_encoded.len = buffer.len - HEADER_SIZE - 4 - FOOTER_SIZE; res = amqp_encode_method(frame->payload.method.id, frame->payload.method.decoded, method_encoded); if (res < 0) { return res; } out_frame_len = res + 4; break; } case AMQP_FRAME_HEADER: { amqp_bytes_t properties_encoded; amqp_e16(frame->payload.properties.class_id, amqp_offset(out_frame, HEADER_SIZE)); amqp_e16(0, amqp_offset(out_frame, HEADER_SIZE + 2)); /* "weight" */ amqp_e64(frame->payload.properties.body_size, amqp_offset(out_frame, HEADER_SIZE + 4)); properties_encoded.bytes = amqp_offset(out_frame, HEADER_SIZE + 12); properties_encoded.len = buffer.len - HEADER_SIZE - 12 - FOOTER_SIZE; res = amqp_encode_properties(frame->payload.properties.class_id, frame->payload.properties.decoded, properties_encoded); if (res < 0) { return res; } out_frame_len = res + 12; break; } case AMQP_FRAME_HEARTBEAT: out_frame_len = 0; break; default: return AMQP_STATUS_INVALID_PARAMETER; } amqp_e32((uint32_t)out_frame_len, amqp_offset(out_frame, 3)); amqp_e8(AMQP_FRAME_END, amqp_offset(out_frame, HEADER_SIZE + out_frame_len)); encoded->bytes = out_frame; encoded->len = out_frame_len + HEADER_SIZE + FOOTER_SIZE; return AMQP_STATUS_OK; } int amqp_send_frame(amqp_connection_state_t state, const amqp_frame_t *frame) { return amqp_send_frame_inner(state, frame, AMQP_SF_NONE, amqp_time_infinite()); } int amqp_send_frame_inner(amqp_connection_state_t state, const amqp_frame_t *frame, int flags, amqp_time_t deadline) { int res; ssize_t sent; amqp_bytes_t encoded; amqp_time_t next_timeout; /* TODO: if the AMQP_SF_MORE socket optimization can be shown to work * correctly, then this could be un-done so that body-frames are sent as 3 * send calls, getting rid of the copy of the body content, some testing * would need to be done to see if this would actually a win for performance. * */ res = amqp_frame_to_bytes(frame, state->outbound_buffer, &encoded); if (AMQP_STATUS_OK != res) { return res; } start_send: next_timeout = amqp_time_first(deadline, state->next_recv_heartbeat); sent = amqp_try_send(state, encoded.bytes, encoded.len, next_timeout, flags); if (0 > sent) { return (int)sent; } /* A partial send has occurred, because of a heartbeat timeout (so try recv * something) or common timeout (so return AMQP_STATUS_TIMEOUT) */ if ((ssize_t)encoded.len != sent) { if (amqp_time_equal(next_timeout, deadline)) { /* timeout of method was received, so return from method*/ return AMQP_STATUS_TIMEOUT; } res = amqp_try_recv(state); if (AMQP_STATUS_TIMEOUT == res) { return AMQP_STATUS_HEARTBEAT_TIMEOUT; } else if (AMQP_STATUS_OK != res) { return res; } encoded.bytes = (uint8_t *)encoded.bytes + sent; encoded.len -= sent; goto start_send; } res = amqp_time_s_from_now(&state->next_send_heartbeat, amqp_heartbeat_send(state)); return res; } amqp_table_t *amqp_get_server_properties(amqp_connection_state_t state) { return &state->server_properties; } amqp_table_t *amqp_get_client_properties(amqp_connection_state_t state) { return &state->client_properties; }
null
/* * ***** BEGIN LICENSE BLOCK ***** * Version: MIT * * Portions created by Alan Antonuk are Copyright (c) 2012-2014 * Alan Antonuk. All Rights Reserved. * * Portions created by VMware are Copyright (c) 2007-2012 VMware, Inc. * All Rights Reserved. * * Portions created by Tony Garnock-Jones are Copyright (c) 2009-2010 * VMware, Inc. and Tony Garnock-Jones. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * ***** END LICENSE BLOCK ***** */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef _MSC_VER #define _CRT_SECURE_NO_WARNINGS #endif #include "amqp_private.h" #include "amqp_tcp_socket.h" #include "amqp_time.h" #include <errno.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifndef AMQP_INITIAL_FRAME_POOL_PAGE_SIZE #define AMQP_INITIAL_FRAME_POOL_PAGE_SIZE 65536 #endif #ifndef AMQP_INITIAL_INBOUND_SOCK_BUFFER_SIZE #define AMQP_INITIAL_INBOUND_SOCK_BUFFER_SIZE 131072 #endif #ifndef AMQP_DEFAULT_LOGIN_TIMEOUT_SEC #define AMQP_DEFAULT_LOGIN_TIMEOUT_SEC 12 #endif #define ENFORCE_STATE(statevec, statenum) \ { \ amqp_connection_state_t _check_state = (statevec); \ amqp_connection_state_enum _wanted_state = (statenum); \ if (_check_state->state != _wanted_state) \ amqp_abort( \ "Programming error: invalid AMQP connection state: expected %d, " \ "got %d", \ _wanted_state, _check_state->state); \ } amqp_connection_state_t amqp_new_connection(void) { int res; amqp_connection_state_t state = (amqp_connection_state_t)calloc( 1, sizeof(struct amqp_connection_state_t_)); if (state == NULL) { return NULL; } res = amqp_tune_connection(state, 0, AMQP_INITIAL_FRAME_POOL_PAGE_SIZE, 0); if (0 != res) { goto out_nomem; } state->inbound_buffer.bytes = state->header_buffer; state->inbound_buffer.len = sizeof(state->header_buffer); state->state = CONNECTION_STATE_INITIAL; /* the server protocol version response is 8 bytes, which conveniently is also the minimum frame size */ state->target_size = 8; state->sock_inbound_buffer.len = AMQP_INITIAL_INBOUND_SOCK_BUFFER_SIZE; state->sock_inbound_buffer.bytes = malloc(AMQP_INITIAL_INBOUND_SOCK_BUFFER_SIZE); if (state->sock_inbound_buffer.bytes == NULL) { goto out_nomem; } init_amqp_pool(&state->properties_pool, 512); /* Use address of the internal_handshake_timeout object by default. */ state->internal_handshake_timeout.tv_sec = AMQP_DEFAULT_LOGIN_TIMEOUT_SEC; state->internal_handshake_timeout.tv_usec = 0; state->handshake_timeout = &state->internal_handshake_timeout; return state; out_nomem: free(state->sock_inbound_buffer.bytes); free(state); return NULL; } int amqp_get_sockfd(amqp_connection_state_t state) { return state->socket ? amqp_socket_get_sockfd(state->socket) : -1; } void amqp_set_sockfd(amqp_connection_state_t state, int sockfd) { amqp_socket_t *socket = amqp_tcp_socket_new(state); if (!socket) { amqp_abort("%s", strerror(errno)); } amqp_tcp_socket_set_sockfd(socket, sockfd); } void amqp_set_socket(amqp_connection_state_t state, amqp_socket_t *socket) { amqp_socket_delete(state->socket); state->socket = socket; } amqp_socket_t *amqp_get_socket(amqp_connection_state_t state) { return state->socket; } int amqp_tune_connection(amqp_connection_state_t state, int channel_max, int frame_max, int heartbeat) { void *newbuf; int res; ENFORCE_STATE(state, CONNECTION_STATE_IDLE); state->channel_max = channel_max; state->frame_max = frame_max; state->heartbeat = heartbeat; if (0 > state->heartbeat) { state->heartbeat = 0; } res = amqp_time_s_from_now(&state->next_send_heartbeat, amqp_heartbeat_send(state)); if (AMQP_STATUS_OK != res) { return res; } res = amqp_time_s_from_now(&state->next_recv_heartbeat, amqp_heartbeat_recv(state)); if (AMQP_STATUS_OK != res) { return res; } state->outbound_buffer.len = frame_max; newbuf = realloc(state->outbound_buffer.bytes, frame_max); if (newbuf == NULL) { return AMQP_STATUS_NO_MEMORY; } state->outbound_buffer.bytes = newbuf; return AMQP_STATUS_OK; } int amqp_get_channel_max(amqp_connection_state_t state) { return state->channel_max; } int amqp_get_frame_max(amqp_connection_state_t state) { return state->frame_max; } int amqp_get_heartbeat(amqp_connection_state_t state) { return state->heartbeat; } int amqp_destroy_connection(amqp_connection_state_t state) { int status = AMQP_STATUS_OK; if (state) { int i; for (i = 0; i < POOL_TABLE_SIZE; ++i) { amqp_pool_table_entry_t *entry = state->pool_table[i]; while (NULL != entry) { amqp_pool_table_entry_t *todelete = entry; empty_amqp_pool(&entry->pool); entry = entry->next; free(todelete); } } free(state->outbound_buffer.bytes); free(state->sock_inbound_buffer.bytes); amqp_socket_delete(state->socket); empty_amqp_pool(&state->properties_pool); free(state); } return status; } static void return_to_idle(amqp_connection_state_t state) { state->inbound_buffer.len = sizeof(state->header_buffer); state->inbound_buffer.bytes = state->header_buffer; state->inbound_offset = 0; state->target_size = HEADER_SIZE; state->state = CONNECTION_STATE_IDLE; } static size_t consume_data(amqp_connection_state_t state, amqp_bytes_t *received_data) { /* how much data is available and will fit? */ size_t bytes_consumed = state->target_size - state->inbound_offset; if (received_data->len < bytes_consumed) { bytes_consumed = received_data->len; } memcpy(amqp_offset(state->inbound_buffer.bytes, state->inbound_offset), received_data->bytes, bytes_consumed); state->inbound_offset += bytes_consumed; received_data->bytes = amqp_offset(received_data->bytes, bytes_consumed); received_data->len -= bytes_consumed; return bytes_consumed; } int amqp_handle_input(amqp_connection_state_t state, amqp_bytes_t received_data, amqp_frame_t *decoded_frame) { size_t bytes_consumed; void *raw_frame; /* Returning frame_type of zero indicates either insufficient input, or a complete, ignored frame was read. */ decoded_frame->frame_type = 0; if (received_data.len == 0) { return AMQP_STATUS_OK; } if (state->state == CONNECTION_STATE_IDLE) { state->state = CONNECTION_STATE_HEADER; } bytes_consumed = consume_data(state, &received_data); /* do we have target_size data yet? if not, return with the expectation that more will arrive */ if (state->inbound_offset < state->target_size) { return (int)bytes_consumed; } raw_frame = state->inbound_buffer.bytes; switch (state->state) { case CONNECTION_STATE_INITIAL: /* check for a protocol header from the server */ if (memcmp(raw_frame, "AMQP", 4) == 0) { decoded_frame->frame_type = AMQP_PSEUDOFRAME_PROTOCOL_HEADER; decoded_frame->channel = 0; decoded_frame->payload.protocol_header.transport_high = amqp_d8(amqp_offset(raw_frame, 4)); decoded_frame->payload.protocol_header.transport_low = amqp_d8(amqp_offset(raw_frame, 5)); decoded_frame->payload.protocol_header.protocol_version_major = amqp_d8(amqp_offset(raw_frame, 6)); decoded_frame->payload.protocol_header.protocol_version_minor = amqp_d8(amqp_offset(raw_frame, 7)); return_to_idle(state); return (int)bytes_consumed; } /* it's not a protocol header; fall through to process it as a regular frame header */ case CONNECTION_STATE_HEADER: { amqp_channel_t channel; amqp_pool_t *channel_pool; uint32_t frame_size; channel = amqp_d16(amqp_offset(raw_frame, 1)); /* frame length is 3 bytes in */ frame_size = amqp_d32(amqp_offset(raw_frame, 3)); /* To prevent the target_size calculation below from overflowing, check * that the stated frame_size is smaller than a signed 32-bit. Given * the library only allows configuring frame_max as an int32_t, and * frame_size is uint32_t, the math below is safe from overflow. */ if (frame_size >= INT32_MAX) { return AMQP_STATUS_BAD_AMQP_DATA; } state->target_size = frame_size + HEADER_SIZE + FOOTER_SIZE; if ((size_t)state->frame_max < state->target_size) { return AMQP_STATUS_BAD_AMQP_DATA; } channel_pool = amqp_get_or_create_channel_pool(state, channel); if (NULL == channel_pool) { return AMQP_STATUS_NO_MEMORY; } amqp_pool_alloc_bytes(channel_pool, state->target_size, &state->inbound_buffer); if (NULL == state->inbound_buffer.bytes) { return AMQP_STATUS_NO_MEMORY; } memcpy(state->inbound_buffer.bytes, state->header_buffer, HEADER_SIZE); raw_frame = state->inbound_buffer.bytes; state->state = CONNECTION_STATE_BODY; bytes_consumed += consume_data(state, &received_data); /* do we have target_size data yet? if not, return with the expectation that more will arrive */ if (state->inbound_offset < state->target_size) { return (int)bytes_consumed; } } /* fall through to process body */ case CONNECTION_STATE_BODY: { amqp_bytes_t encoded; int res; amqp_pool_t *channel_pool; /* Check frame end marker (footer) */ if (amqp_d8(amqp_offset(raw_frame, state->target_size - 1)) != AMQP_FRAME_END) { return AMQP_STATUS_BAD_AMQP_DATA; } decoded_frame->frame_type = amqp_d8(amqp_offset(raw_frame, 0)); decoded_frame->channel = amqp_d16(amqp_offset(raw_frame, 1)); channel_pool = amqp_get_or_create_channel_pool(state, decoded_frame->channel); if (NULL == channel_pool) { return AMQP_STATUS_NO_MEMORY; } switch (decoded_frame->frame_type) { case AMQP_FRAME_METHOD: decoded_frame->payload.method.id = amqp_d32(amqp_offset(raw_frame, HEADER_SIZE)); encoded.bytes = amqp_offset(raw_frame, HEADER_SIZE + 4); encoded.len = state->target_size - HEADER_SIZE - 4 - FOOTER_SIZE; res = amqp_decode_method(decoded_frame->payload.method.id, channel_pool, encoded, &decoded_frame->payload.method.decoded); if (res < 0) { return res; } break; case AMQP_FRAME_HEADER: decoded_frame->payload.properties.class_id = amqp_d16(amqp_offset(raw_frame, HEADER_SIZE)); /* unused 2-byte weight field goes here */ decoded_frame->payload.properties.body_size = amqp_d64(amqp_offset(raw_frame, HEADER_SIZE + 4)); encoded.bytes = amqp_offset(raw_frame, HEADER_SIZE + 12); encoded.len = state->target_size - HEADER_SIZE - 12 - FOOTER_SIZE; decoded_frame->payload.properties.raw = encoded; res = amqp_decode_properties( decoded_frame->payload.properties.class_id, channel_pool, encoded, &decoded_frame->payload.properties.decoded); if (res < 0) { return res; } break; case AMQP_FRAME_BODY: decoded_frame->payload.body_fragment.len = state->target_size - HEADER_SIZE - FOOTER_SIZE; decoded_frame->payload.body_fragment.bytes = amqp_offset(raw_frame, HEADER_SIZE); break; case AMQP_FRAME_HEARTBEAT: break; default: /* Ignore the frame */ decoded_frame->frame_type = 0; break; } return_to_idle(state); return (int)bytes_consumed; } default: amqp_abort("Internal error: invalid amqp_connection_state_t->state %d", state->state); } } amqp_boolean_t amqp_release_buffers_ok(amqp_connection_state_t state) { return (state->state == CONNECTION_STATE_IDLE); } void amqp_release_buffers(amqp_connection_state_t state) { int i; ENFORCE_STATE(state, CONNECTION_STATE_IDLE); for (i = 0; i < POOL_TABLE_SIZE; ++i) { amqp_pool_table_entry_t *entry = state->pool_table[i]; for (; NULL != entry; entry = entry->next) { amqp_maybe_release_buffers_on_channel(state, entry->channel); } } } void amqp_maybe_release_buffers(amqp_connection_state_t state) { if (amqp_release_buffers_ok(state)) { amqp_release_buffers(state); } } void amqp_maybe_release_buffers_on_channel(amqp_connection_state_t state, amqp_channel_t channel) { amqp_link_t *queued_link; amqp_pool_t *pool; if (CONNECTION_STATE_IDLE != state->state) { return; } queued_link = state->first_queued_frame; while (NULL != queued_link) { amqp_frame_t *frame = queued_link->data; if (channel == frame->channel) { return; } queued_link = queued_link->next; } pool = amqp_get_channel_pool(state, channel); if (pool != NULL) { recycle_amqp_pool(pool); } } static int amqp_frame_to_bytes(const amqp_frame_t *frame, amqp_bytes_t buffer, amqp_bytes_t *encoded) { void *out_frame = buffer.bytes; size_t out_frame_len; int res; amqp_e8(frame->frame_type, amqp_offset(out_frame, 0)); amqp_e16(frame->channel, amqp_offset(out_frame, 1)); switch (frame->frame_type) { case AMQP_FRAME_BODY: { const amqp_bytes_t *body = &frame->payload.body_fragment; memcpy(amqp_offset(out_frame, HEADER_SIZE), body->bytes, body->len); out_frame_len = body->len; break; } case AMQP_FRAME_METHOD: { amqp_bytes_t method_encoded; amqp_e32(frame->payload.method.id, amqp_offset(out_frame, HEADER_SIZE)); method_encoded.bytes = amqp_offset(out_frame, HEADER_SIZE + 4); method_encoded.len = buffer.len - HEADER_SIZE - 4 - FOOTER_SIZE; res = amqp_encode_method(frame->payload.method.id, frame->payload.method.decoded, method_encoded); if (res < 0) { return res; } out_frame_len = res + 4; break; } case AMQP_FRAME_HEADER: { amqp_bytes_t properties_encoded; amqp_e16(frame->payload.properties.class_id, amqp_offset(out_frame, HEADER_SIZE)); amqp_e16(0, amqp_offset(out_frame, HEADER_SIZE + 2)); /* "weight" */ amqp_e64(frame->payload.properties.body_size, amqp_offset(out_frame, HEADER_SIZE + 4)); properties_encoded.bytes = amqp_offset(out_frame, HEADER_SIZE + 12); properties_encoded.len = buffer.len - HEADER_SIZE - 12 - FOOTER_SIZE; res = amqp_encode_properties(frame->payload.properties.class_id, frame->payload.properties.decoded, properties_encoded); if (res < 0) { return res; } out_frame_len = res + 12; break; } case AMQP_FRAME_HEARTBEAT: out_frame_len = 0; break; default: return AMQP_STATUS_INVALID_PARAMETER; } amqp_e32((uint32_t)out_frame_len, amqp_offset(out_frame, 3)); amqp_e8(AMQP_FRAME_END, amqp_offset(out_frame, HEADER_SIZE + out_frame_len)); encoded->bytes = out_frame; encoded->len = out_frame_len + HEADER_SIZE + FOOTER_SIZE; return AMQP_STATUS_OK; } int amqp_send_frame(amqp_connection_state_t state, const amqp_frame_t *frame) { return amqp_send_frame_inner(state, frame, AMQP_SF_NONE, amqp_time_infinite()); } int amqp_send_frame_inner(amqp_connection_state_t state, const amqp_frame_t *frame, int flags, amqp_time_t deadline) { int res; ssize_t sent; amqp_bytes_t encoded; amqp_time_t next_timeout; /* TODO: if the AMQP_SF_MORE socket optimization can be shown to work * correctly, then this could be un-done so that body-frames are sent as 3 * send calls, getting rid of the copy of the body content, some testing * would need to be done to see if this would actually a win for performance. * */ res = amqp_frame_to_bytes(frame, state->outbound_buffer, &encoded); if (AMQP_STATUS_OK != res) { return res; } start_send: next_timeout = amqp_time_first(deadline, state->next_recv_heartbeat); sent = amqp_try_send(state, encoded.bytes, encoded.len, next_timeout, flags); if (0 > sent) { return (int)sent; } /* A partial send has occurred, because of a heartbeat timeout (so try recv * something) or common timeout (so return AMQP_STATUS_TIMEOUT) */ if ((ssize_t)encoded.len != sent) { if (amqp_time_equal(next_timeout, deadline)) { /* timeout of method was received, so return from method*/ return AMQP_STATUS_TIMEOUT; } res = amqp_try_recv(state); if (AMQP_STATUS_TIMEOUT == res) { return AMQP_STATUS_HEARTBEAT_TIMEOUT; } else if (AMQP_STATUS_OK != res) { return res; } encoded.bytes = (uint8_t *)encoded.bytes + sent; encoded.len -= sent; goto start_send; } res = amqp_time_s_from_now(&state->next_send_heartbeat, amqp_heartbeat_send(state)); return res; } amqp_table_t *amqp_get_server_properties(amqp_connection_state_t state) { return &state->server_properties; } amqp_table_t *amqp_get_client_properties(amqp_connection_state_t state) { return &state->client_properties; }
null
150
CWE-787
CVE-2019-18671
/* * This file is part of the KeepKey project. * * Copyright (C) 2015 KeepKey LLC * * This library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "keepkey/board/usb.h" #include "keepkey/board/messages.h" #include "keepkey/board/variant.h" #include "keepkey/board/timer.h" #include "keepkey/board/layout.h" #include "keepkey/board/util.h" #include <nanopb.h> #include <assert.h> #include <string.h> static const MessagesMap_t *MessagesMap = NULL; static size_t map_size = 0; static msg_failure_t msg_failure; #if DEBUG_LINK static msg_debug_link_get_state_t msg_debug_link_get_state; #endif /* Tiny messages */ static bool msg_tiny_flag = false; static CONFIDENTIAL uint8_t msg_tiny[MSG_TINY_BFR_SZ]; static uint16_t msg_tiny_id = MSG_TINY_TYPE_ERROR; /* Default to error type */ /* Allow mapped messages to reset message stack. This variable by itself doesn't * do much but messages down the line can use it to determine for to gracefully * exit from a message should the message stack been reset */ bool reset_msg_stack = false; /* * message_map_entry() - Finds a requested message map entry * * INPUT * - type: type of message (normal or debug) * - msg_id: message id * - dir: direction of message * OUTPUT * entry if found */ static const MessagesMap_t *message_map_entry(MessageMapType type, MessageType msg_id, MessageMapDirection dir) { const MessagesMap_t *m = MessagesMap; if (map_size > msg_id && m[msg_id].msg_id == msg_id && m[msg_id].type == type && m[msg_id].dir == dir) { return &m[msg_id]; } return NULL; } /* * message_fields() - Get protocol buffer for requested message map entry * * INPUT * - type: type of message (normal or debug) * - msg_id: message id * - dir: direction of message * OUTPUT * protocol buffer */ const pb_field_t *message_fields(MessageMapType type, MessageType msg_id, MessageMapDirection dir) { assert(MessagesMap != NULL); const MessagesMap_t *m = MessagesMap; if(map_size > msg_id && m[msg_id].msg_id == msg_id && m[msg_id].type == type && m[msg_id].dir == dir) { return m[msg_id].fields; } return NULL; } /* * pb_parse() - Process USB message by protocol buffer * * INPUT * - entry: pointer to message entry * - msg: pointer to received message buffer * - msg_size: size of message * - buf: pointer to destination buffer * OUTPUT * true/false whether protocol buffers were parsed successfully */ static bool pb_parse(const MessagesMap_t *entry, uint8_t *msg, uint32_t msg_size, uint8_t *buf) { pb_istream_t stream = pb_istream_from_buffer(msg, msg_size); return pb_decode(&stream, entry->fields, buf); } /* * dispatch() - Process received message and jump to corresponding process function * * INPUT * - entry: pointer to message entry * - msg: pointer to received message buffer * - msg_size: size of message * OUTPUT * none * */ static void dispatch(const MessagesMap_t *entry, uint8_t *msg, uint32_t msg_size) { static uint8_t decode_buffer[MAX_DECODE_SIZE] __attribute__((aligned(4))); memset(decode_buffer, 0, sizeof(decode_buffer)); if (!pb_parse(entry, msg, msg_size, decode_buffer)) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Could not parse protocol buffer message"); return; } if (!entry->process_func) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Unexpected message"); return; } entry->process_func(decode_buffer); } /* * tiny_dispatch() - Process received tiny messages * * INPUT * - entry: pointer to message entry * - msg: pointer to received message buffer * - msg_size: size of message * OUTPUT * none * */ static void tiny_dispatch(const MessagesMap_t *entry, uint8_t *msg, uint32_t msg_size) { if (!pb_parse(entry, msg, msg_size, msg_tiny)) { call_msg_failure_handler(FailureType_Failure_UnexpectedMessage, "Could not parse tiny protocol buffer message"); return; } msg_tiny_id = entry->msg_id; } /* * raw_dispatch() - Process messages that will not be parsed by protocol buffers * and should be manually parsed at message function * * INPUT * - entry: pointer to message entry * - msg: pointer to received message buffer * - msg_size: size of message * - frame_length: total expected size * OUTPUT * none */ static void raw_dispatch(const MessagesMap_t *entry, const uint8_t *msg, uint32_t msg_size, uint32_t frame_length) { static RawMessage raw_msg; raw_msg.buffer = msg; raw_msg.length = msg_size; if(entry->process_func) { ((raw_msg_handler_t)entry->process_func)(&raw_msg, frame_length); } } #if !defined(__has_builtin) # define __has_builtin(X) 0 #endif #if __has_builtin(__builtin_add_overflow) # define check_uadd_overflow(A, B, R) \ ({ \ typeof(A) __a = (A); \ typeof(B) __b = (B); \ typeof(R) __r = (R); \ (void)(&__a == &__b && "types must match"); \ (void)(&__a == __r && "types must match"); \ _Static_assert(0 < (typeof(A))-1, "types must be unsigned"); \ __builtin_add_overflow((A), (B), (R)); \ }) #else # define check_uadd_overflow(A, B, R) \ ({ \ typeof(A) __a = (A); \ typeof(B) __b = (B); \ typeof(R) __r = (R); \ (void)(&__a == &__b); \ (void)(&__a == __r); \ (void)(&__a == &__b && "types must match"); \ (void)(&__a == __r && "types must match"); \ _Static_assert(0 < (typeof(A))-1, "types must be unsigned"); \ *__r = __a + __b; \ *__r < __a; \ }) #endif /// Common helper that handles USB messages from host void usb_rx_helper(const uint8_t *buf, size_t length, MessageMapType type) { static bool firstFrame = true; static uint16_t msgId; static uint32_t msgSize; static uint8_t msg[MAX_FRAME_SIZE]; static size_t cursor; //< Index into msg where the current frame is to be written. static const MessagesMap_t *entry; if (firstFrame) { msgId = 0xffff; msgSize = 0; memset(msg, 0, sizeof(msg)); cursor = 0; entry = NULL; } assert(buf != NULL); if (length < 1 + 2 + 2 + 4) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Buffer too small"); goto reset; } if (buf[0] != '?') { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Malformed packet"); goto reset; } if (firstFrame && (buf[1] != '#' || buf[2] != '#')) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Malformed packet"); goto reset; } // Details of the chunk being copied out of the current frame. const uint8_t *frame; size_t frameSize; if (firstFrame) { // Reset the buffer that we're writing fragments into. memset(msg, 0, sizeof(msg)); // Then fish out the id / size, which are big-endian uint16 / // uint32's respectively. msgId = buf[4] | ((uint16_t)buf[3]) << 8; msgSize = buf[8] | ((uint32_t)buf[7]) << 8 | ((uint32_t)buf[6]) << 16 | ((uint32_t)buf[5]) << 24; // Determine callback handler and message map type. entry = message_map_entry(type, msgId, IN_MSG); // And reset the cursor. cursor = 0; // Then take note of the fragment boundaries. frame = &buf[9]; frameSize = MIN(length - 9, msgSize); } else { // Otherwise it's a continuation/fragment. frame = &buf[1]; frameSize = length - 1; } // If the msgId wasn't in our map, bail. if (!entry) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Unknown message"); goto reset; } if (entry->dispatch == RAW) { /* Call dispatch for every segment since we are not buffering and parsing, and * assume the raw dispatched callbacks will handle their own state and * buffering internally */ raw_dispatch(entry, frame, frameSize, msgSize); firstFrame = false; return; } size_t end; if (check_uadd_overflow(cursor, frameSize, &end) || sizeof(msg) < end) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Malformed message"); goto reset; } // Copy content to frame buffer. memcpy(&msg[cursor], frame, frameSize); // Advance the cursor. cursor = end; // Only parse and message map if all segments have been buffered. bool last_segment = cursor >= msgSize; if (!last_segment) { firstFrame = false; return; } dispatch(entry, msg, msgSize); reset: msgId = 0xffff; msgSize = 0; memset(msg, 0, sizeof(msg)); cursor = 0; firstFrame = true; entry = NULL; } void handle_usb_rx(const void *msg, size_t len) { if (msg_tiny_flag) { uint8_t buf[64]; memcpy(buf, msg, sizeof(buf)); uint16_t msgId = buf[4] | ((uint16_t)buf[3]) << 8; uint32_t msgSize = buf[8] | ((uint32_t)buf[7]) << 8 | ((uint32_t)buf[6]) << 16 | ((uint32_t)buf[5]) << 24; if (msgSize > 64 - 9) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Malformed tiny packet"); return; } // Determine callback handler and message map type. const MessagesMap_t *entry = message_map_entry(NORMAL_MSG, msgId, IN_MSG); if (!entry) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Unknown message"); return; } tiny_dispatch(entry, buf + 9, msgSize); } else { usb_rx_helper(msg, len, NORMAL_MSG); } } #if DEBUG_LINK void handle_debug_usb_rx(const void *msg, size_t len) { if (msg_tiny_flag) { uint8_t buf[64]; memcpy(buf, msg, sizeof(buf)); uint16_t msgId = buf[4] | ((uint16_t)buf[3]) << 8; uint32_t msgSize = buf[8] | ((uint32_t)buf[7]) << 8 | ((uint32_t)buf[6]) << 16 | ((uint32_t)buf[5]) << 24; if (msgSize > 64 - 9) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Malformed tiny packet"); return; } // Determine callback handler and message map type. const MessagesMap_t *entry = message_map_entry(DEBUG_MSG, msgId, IN_MSG); if (!entry) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Unknown message"); return; } tiny_dispatch(entry, buf + 9, msgSize); } else { usb_rx_helper(msg, len, DEBUG_MSG); } } #endif /* * tiny_msg_poll_and_buffer() - Poll usb port to check for tiny message from host * * INPUT * - block: flag to continually poll usb until tiny message is received * - buf: pointer to destination buffer * OUTPUT * message type * */ static MessageType tiny_msg_poll_and_buffer(bool block, uint8_t *buf) { msg_tiny_id = MSG_TINY_TYPE_ERROR; msg_tiny_flag = true; while(msg_tiny_id == MSG_TINY_TYPE_ERROR) { usbPoll(); if(!block) { break; } } msg_tiny_flag = false; if(msg_tiny_id != MSG_TINY_TYPE_ERROR) { memcpy(buf, msg_tiny, sizeof(msg_tiny)); } return msg_tiny_id; } /* * msg_map_init() - Setup message map with corresping message type * * INPUT * - map: pointer message map array * - size: size of message map * OUTPUT * */ void msg_map_init(const void *map, const size_t size) { assert(map != NULL); MessagesMap = map; map_size = size; } /* * set_msg_failure_handler() - Setup usb message failure handler * * INPUT * - failure_func: message failure handler * OUTPUT * none */ void set_msg_failure_handler(msg_failure_t failure_func) { msg_failure = failure_func; } /* * set_msg_debug_link_get_state_handler() - Setup usb message debug link get state handler * * INPUT * - debug_link_get_state_func: message initialization handler * OUTPUT * none */ #if DEBUG_LINK void set_msg_debug_link_get_state_handler(msg_debug_link_get_state_t debug_link_get_state_func) { msg_debug_link_get_state = debug_link_get_state_func; } #endif /* * call_msg_failure_handler() - Call message failure handler * * INPUT * - code: failure code * - text: pinter to function arguments * OUTPUT * none */ void call_msg_failure_handler(FailureType code, const char *text) { if(msg_failure) { (*msg_failure)(code, text); } } /* * call_msg_debug_link_get_state_handler() - Call message debug link get state handler * * INPUT * none * OUTPUT * none */ #if DEBUG_LINK void call_msg_debug_link_get_state_handler(DebugLinkGetState *msg) { if(msg_debug_link_get_state) { (*msg_debug_link_get_state)(msg); } } #endif /* * msg_init() - Setup usb receive callback handler * * INPUT * none * OUTPUT * none */ void msg_init(void) { usb_set_rx_callback(handle_usb_rx); #if DEBUG_LINK usb_set_debug_rx_callback(handle_debug_usb_rx); #endif } /* * wait_for_tiny_msg() - Wait for usb tiny message type from host * * INPUT * - buf: pointer to destination buffer * OUTPUT * message tiny type * */ MessageType wait_for_tiny_msg(uint8_t *buf) { return tiny_msg_poll_and_buffer(true, buf); } /* * check_for_tiny_msg() - Check for usb tiny message type from host * * INPUT * - buf: pointer to destination buffer * OUTPUT * message tiny type * */ MessageType check_for_tiny_msg(uint8_t *buf) { return tiny_msg_poll_and_buffer(false, buf); } /* * parse_pb_varint() - Parses varints off of raw messages * * INPUT * - msg: pointer to raw message * - varint_count: how many varints to remove * OUTPUT * bytes that were skipped */ uint32_t parse_pb_varint(RawMessage *msg, uint8_t varint_count) { uint32_t skip; uint8_t i; uint64_t pb_varint; pb_istream_t stream; /* * Parse varints */ stream = pb_istream_from_buffer((uint8_t*)msg->buffer, msg->length); skip = stream.bytes_left; for(i = 0; i < varint_count; ++i) { pb_decode_varint(&stream, &pb_varint); } skip = skip - stream.bytes_left; /* * Increment skip over message */ msg->length -= skip; msg->buffer = (uint8_t *)(msg->buffer + skip); return skip; } /* * encode_pb() - convert to raw pb data * * INPUT * - source_ptr : pointer to struct * - fields: pointer pb fields * - *buffer: pointer to destination buffer * - len: size of buffer * OUTPUT * bytes written to buffer */ int encode_pb(const void *source_ptr, const pb_field_t *fields, uint8_t *buffer, uint32_t len ) { pb_ostream_t os = pb_ostream_from_buffer(buffer, len); if (!pb_encode(&os, fields, source_ptr)) return 0; return os.bytes_written; }
null
/* * This file is part of the KeepKey project. * * Copyright (C) 2015 KeepKey LLC * * This library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "keepkey/board/usb.h" #include "keepkey/board/messages.h" #include "keepkey/board/variant.h" #include "keepkey/board/timer.h" #include "keepkey/board/layout.h" #include "keepkey/board/util.h" #include <nanopb.h> #include <assert.h> #include <string.h> static const MessagesMap_t *MessagesMap = NULL; static size_t map_size = 0; static msg_failure_t msg_failure; #if DEBUG_LINK static msg_debug_link_get_state_t msg_debug_link_get_state; #endif /* Allow mapped messages to reset message stack. This variable by itself doesn't * do much but messages down the line can use it to determine for to gracefully * exit from a message should the message stack been reset */ bool reset_msg_stack = false; /* * message_map_entry() - Finds a requested message map entry * * INPUT * - type: type of message (normal or debug) * - msg_id: message id * - dir: direction of message * OUTPUT * entry if found */ static const MessagesMap_t *message_map_entry(MessageMapType type, MessageType msg_id, MessageMapDirection dir) { const MessagesMap_t *m = MessagesMap; if (map_size > msg_id && m[msg_id].msg_id == msg_id && m[msg_id].type == type && m[msg_id].dir == dir) { return &m[msg_id]; } return NULL; } /* * message_fields() - Get protocol buffer for requested message map entry * * INPUT * - type: type of message (normal or debug) * - msg_id: message id * - dir: direction of message * OUTPUT * protocol buffer */ const pb_field_t *message_fields(MessageMapType type, MessageType msg_id, MessageMapDirection dir) { assert(MessagesMap != NULL); const MessagesMap_t *m = MessagesMap; if(map_size > msg_id && m[msg_id].msg_id == msg_id && m[msg_id].type == type && m[msg_id].dir == dir) { return m[msg_id].fields; } return NULL; } /* * pb_parse() - Process USB message by protocol buffer * * INPUT * - entry: pointer to message entry * - msg: pointer to received message buffer * - msg_size: size of message * - buf: pointer to destination buffer * OUTPUT * true/false whether protocol buffers were parsed successfully */ static bool pb_parse(const MessagesMap_t *entry, uint8_t *msg, uint32_t msg_size, uint8_t *buf) { pb_istream_t stream = pb_istream_from_buffer(msg, msg_size); return pb_decode(&stream, entry->fields, buf); } /* * dispatch() - Process received message and jump to corresponding process function * * INPUT * - entry: pointer to message entry * - msg: pointer to received message buffer * - msg_size: size of message * OUTPUT * none * */ static void dispatch(const MessagesMap_t *entry, uint8_t *msg, uint32_t msg_size) { static uint8_t decode_buffer[MAX_DECODE_SIZE] __attribute__((aligned(4))); memset(decode_buffer, 0, sizeof(decode_buffer)); if (!pb_parse(entry, msg, msg_size, decode_buffer)) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Could not parse protocol buffer message"); return; } if (!entry->process_func) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Unexpected message"); return; } entry->process_func(decode_buffer); } /* * raw_dispatch() - Process messages that will not be parsed by protocol buffers * and should be manually parsed at message function * * INPUT * - entry: pointer to message entry * - msg: pointer to received message buffer * - msg_size: size of message * - frame_length: total expected size * OUTPUT * none */ static void raw_dispatch(const MessagesMap_t *entry, const uint8_t *msg, uint32_t msg_size, uint32_t frame_length) { static RawMessage raw_msg; raw_msg.buffer = msg; raw_msg.length = msg_size; if(entry->process_func) { ((raw_msg_handler_t)entry->process_func)(&raw_msg, frame_length); } } #if !defined(__has_builtin) # define __has_builtin(X) 0 #endif #if __has_builtin(__builtin_add_overflow) # define check_uadd_overflow(A, B, R) \ ({ \ typeof(A) __a = (A); \ typeof(B) __b = (B); \ typeof(R) __r = (R); \ (void)(&__a == &__b && "types must match"); \ (void)(&__a == __r && "types must match"); \ _Static_assert(0 < (typeof(A))-1, "types must be unsigned"); \ __builtin_add_overflow((A), (B), (R)); \ }) #else # define check_uadd_overflow(A, B, R) \ ({ \ typeof(A) __a = (A); \ typeof(B) __b = (B); \ typeof(R) __r = (R); \ (void)(&__a == &__b); \ (void)(&__a == __r); \ (void)(&__a == &__b && "types must match"); \ (void)(&__a == __r && "types must match"); \ _Static_assert(0 < (typeof(A))-1, "types must be unsigned"); \ *__r = __a + __b; \ *__r < __a; \ }) #endif /// Common helper that handles USB messages from host void usb_rx_helper(const uint8_t *buf, size_t length, MessageMapType type) { static bool firstFrame = true; static uint16_t msgId; static uint32_t msgSize; static uint8_t msg[MAX_FRAME_SIZE]; static size_t cursor; //< Index into msg where the current frame is to be written. static const MessagesMap_t *entry; if (firstFrame) { msgId = 0xffff; msgSize = 0; memset(msg, 0, sizeof(msg)); cursor = 0; entry = NULL; } assert(buf != NULL); if (length < 1 + 2 + 2 + 4) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Buffer too small"); goto reset; } if (buf[0] != '?') { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Malformed packet"); goto reset; } if (firstFrame && (buf[1] != '#' || buf[2] != '#')) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Malformed packet"); goto reset; } // Details of the chunk being copied out of the current frame. const uint8_t *frame; size_t frameSize; if (firstFrame) { // Reset the buffer that we're writing fragments into. memset(msg, 0, sizeof(msg)); // Then fish out the id / size, which are big-endian uint16 / // uint32's respectively. msgId = buf[4] | ((uint16_t)buf[3]) << 8; msgSize = buf[8] | ((uint32_t)buf[7]) << 8 | ((uint32_t)buf[6]) << 16 | ((uint32_t)buf[5]) << 24; // Determine callback handler and message map type. entry = message_map_entry(type, msgId, IN_MSG); // And reset the cursor. cursor = 0; // Then take note of the fragment boundaries. frame = &buf[9]; frameSize = MIN(length - 9, msgSize); } else { // Otherwise it's a continuation/fragment. frame = &buf[1]; frameSize = length - 1; } // If the msgId wasn't in our map, bail. if (!entry) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Unknown message"); goto reset; } if (entry->dispatch == RAW) { /* Call dispatch for every segment since we are not buffering and parsing, and * assume the raw dispatched callbacks will handle their own state and * buffering internally */ raw_dispatch(entry, frame, frameSize, msgSize); firstFrame = false; return; } size_t end; if (check_uadd_overflow(cursor, frameSize, &end) || sizeof(msg) < end) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Malformed message"); goto reset; } // Copy content to frame buffer. memcpy(&msg[cursor], frame, frameSize); // Advance the cursor. cursor = end; // Only parse and message map if all segments have been buffered. bool last_segment = cursor >= msgSize; if (!last_segment) { firstFrame = false; return; } dispatch(entry, msg, msgSize); reset: msgId = 0xffff; msgSize = 0; memset(msg, 0, sizeof(msg)); cursor = 0; firstFrame = true; entry = NULL; } /* Tiny messages */ static bool msg_tiny_flag = false; static CONFIDENTIAL uint8_t msg_tiny[MSG_TINY_BFR_SZ]; static uint16_t msg_tiny_id = MSG_TINY_TYPE_ERROR; /* Default to error type */ _Static_assert(sizeof(msg_tiny) >= sizeof(Cancel), "msg_tiny too tiny"); _Static_assert(sizeof(msg_tiny) >= sizeof(Initialize), "msg_tiny too tiny"); _Static_assert(sizeof(msg_tiny) >= sizeof(PassphraseAck), "msg_tiny too tiny"); _Static_assert(sizeof(msg_tiny) >= sizeof(ButtonAck), "msg_tiny too tiny"); _Static_assert(sizeof(msg_tiny) >= sizeof(PinMatrixAck), "msg_tiny too tiny"); #if DEBUG_LINK _Static_assert(sizeof(msg_tiny) >= sizeof(DebugLinkDecision), "msg_tiny too tiny"); _Static_assert(sizeof(msg_tiny) >= sizeof(DebugLinkGetState), "msg_tiny too tiny"); #endif static void msg_read_tiny(const uint8_t *msg, size_t len) { if (len != 64) return; uint8_t buf[64]; memcpy(buf, msg, sizeof(buf)); if (buf[0] != '?' || buf[1] != '#' || buf[2] != '#') { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Malformed tiny packet"); return; } uint16_t msgId = buf[4] | ((uint16_t)buf[3]) << 8; uint32_t msgSize = buf[8] | ((uint32_t)buf[7]) << 8 | ((uint32_t)buf[6]) << 16 | ((uint32_t)buf[5]) << 24; if (msgSize > 64 - 9) { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Malformed tiny packet"); return; } const pb_field_t *fields = NULL; pb_istream_t stream = pb_istream_from_buffer(buf + 9, msgSize); switch (msgId) { case MessageType_MessageType_PinMatrixAck: fields = PinMatrixAck_fields; break; case MessageType_MessageType_ButtonAck: fields = ButtonAck_fields; break; case MessageType_MessageType_PassphraseAck: fields = PassphraseAck_fields; break; case MessageType_MessageType_Cancel: fields = Cancel_fields; break; case MessageType_MessageType_Initialize: fields = Initialize_fields; break; #if DEBUG_LINK case MessageType_MessageType_DebugLinkDecision: fields = DebugLinkDecision_fields; break; case MessageType_MessageType_DebugLinkGetState: fields = DebugLinkGetState_fields; break; #endif } if (fields) { bool status = pb_decode(&stream, fields, msg_tiny); if (status) { msg_tiny_id = msgId; } else { (*msg_failure)(FailureType_Failure_SyntaxError, stream.errmsg); msg_tiny_id = 0xffff; } } else { (*msg_failure)(FailureType_Failure_UnexpectedMessage, "Unknown message"); msg_tiny_id = 0xffff; } } void handle_usb_rx(const void *msg, size_t len) { if (msg_tiny_flag) { msg_read_tiny(msg, len); } else { usb_rx_helper(msg, len, NORMAL_MSG); } } #if DEBUG_LINK void handle_debug_usb_rx(const void *msg, size_t len) { if (msg_tiny_flag) { msg_read_tiny(msg, len); } else { usb_rx_helper(msg, len, DEBUG_MSG); } } #endif /* * tiny_msg_poll_and_buffer() - Poll usb port to check for tiny message from host * * INPUT * - block: flag to continually poll usb until tiny message is received * - buf: pointer to destination buffer * OUTPUT * message type * */ static MessageType tiny_msg_poll_and_buffer(bool block, uint8_t *buf) { msg_tiny_id = MSG_TINY_TYPE_ERROR; msg_tiny_flag = true; while(msg_tiny_id == MSG_TINY_TYPE_ERROR) { usbPoll(); if(!block) { break; } } msg_tiny_flag = false; if(msg_tiny_id != MSG_TINY_TYPE_ERROR) { memcpy(buf, msg_tiny, sizeof(msg_tiny)); } return msg_tiny_id; } /* * msg_map_init() - Setup message map with corresping message type * * INPUT * - map: pointer message map array * - size: size of message map * OUTPUT * */ void msg_map_init(const void *map, const size_t size) { assert(map != NULL); MessagesMap = map; map_size = size; } /* * set_msg_failure_handler() - Setup usb message failure handler * * INPUT * - failure_func: message failure handler * OUTPUT * none */ void set_msg_failure_handler(msg_failure_t failure_func) { msg_failure = failure_func; } /* * set_msg_debug_link_get_state_handler() - Setup usb message debug link get state handler * * INPUT * - debug_link_get_state_func: message initialization handler * OUTPUT * none */ #if DEBUG_LINK void set_msg_debug_link_get_state_handler(msg_debug_link_get_state_t debug_link_get_state_func) { msg_debug_link_get_state = debug_link_get_state_func; } #endif /* * call_msg_failure_handler() - Call message failure handler * * INPUT * - code: failure code * - text: pinter to function arguments * OUTPUT * none */ void call_msg_failure_handler(FailureType code, const char *text) { if(msg_failure) { (*msg_failure)(code, text); } } /* * call_msg_debug_link_get_state_handler() - Call message debug link get state handler * * INPUT * none * OUTPUT * none */ #if DEBUG_LINK void call_msg_debug_link_get_state_handler(DebugLinkGetState *msg) { if(msg_debug_link_get_state) { (*msg_debug_link_get_state)(msg); } } #endif /* * msg_init() - Setup usb receive callback handler * * INPUT * none * OUTPUT * none */ void msg_init(void) { usb_set_rx_callback(handle_usb_rx); #if DEBUG_LINK usb_set_debug_rx_callback(handle_debug_usb_rx); #endif } /* * wait_for_tiny_msg() - Wait for usb tiny message type from host * * INPUT * - buf: pointer to destination buffer * OUTPUT * message tiny type * */ MessageType wait_for_tiny_msg(uint8_t *buf) { return tiny_msg_poll_and_buffer(true, buf); } /* * check_for_tiny_msg() - Check for usb tiny message type from host * * INPUT * - buf: pointer to destination buffer * OUTPUT * message tiny type * */ MessageType check_for_tiny_msg(uint8_t *buf) { return tiny_msg_poll_and_buffer(false, buf); } /* * parse_pb_varint() - Parses varints off of raw messages * * INPUT * - msg: pointer to raw message * - varint_count: how many varints to remove * OUTPUT * bytes that were skipped */ uint32_t parse_pb_varint(RawMessage *msg, uint8_t varint_count) { uint32_t skip; uint8_t i; uint64_t pb_varint; pb_istream_t stream; /* * Parse varints */ stream = pb_istream_from_buffer((uint8_t*)msg->buffer, msg->length); skip = stream.bytes_left; for(i = 0; i < varint_count; ++i) { pb_decode_varint(&stream, &pb_varint); } skip = skip - stream.bytes_left; /* * Increment skip over message */ msg->length -= skip; msg->buffer = (uint8_t *)(msg->buffer + skip); return skip; } /* * encode_pb() - convert to raw pb data * * INPUT * - source_ptr : pointer to struct * - fields: pointer pb fields * - *buffer: pointer to destination buffer * - len: size of buffer * OUTPUT * bytes written to buffer */ int encode_pb(const void *source_ptr, const pb_field_t *fields, uint8_t *buffer, uint32_t len ) { pb_ostream_t os = pb_ostream_from_buffer(buffer, len); if (!pb_encode(&os, fields, source_ptr)) return 0; return os.bytes_written; }
null
151
CWE-787
CVE-2019-20016
/* Copyright 2016 Christian Hoene, Symonics GmbH */ #include <errno.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "mysofa_export.h" #include "mysofa.h" #include "../hdf/reader.h" #include "../config.h" /* checks file address. * NULL is an invalid address indicating a invalid field */ int validAddress(struct READER *reader, uint64_t address) { return address > 0 && address < reader->superblock.end_of_file_address; } /* little endian */ uint64_t readValue(struct READER *reader, int size) { int i, c; uint64_t value; c = fgetc(reader->fhd); if (c < 0) return 0xffffffffffffffffLL; value = (uint8_t) c; for (i = 1; i < size; i++) { c = fgetc(reader->fhd); if (c < 0) return 0xffffffffffffffffLL; value |= ((uint64_t) c) << (i * 8); } return value; } static int mystrcmp(char *s1, char *s2) { if (s1 == NULL && s2 == NULL) return 0; if (s1 == NULL) return -1; if (s2 == NULL) return 1; return strcmp(s1, s2); } static int checkAttribute(struct MYSOFA_ATTRIBUTE *attribute, char *name, char *value) { while (attribute) { if (!mystrcmp(attribute->name, name) && !mystrcmp(attribute->value, value)) return MYSOFA_OK; attribute = attribute->next; } return MYSOFA_INVALID_FORMAT; } static int getDimension(unsigned *dim, struct DATAOBJECT *dataobject) { int err; struct MYSOFA_ATTRIBUTE *attr = dataobject->attributes; if (!!(err = checkAttribute(dataobject->attributes, "CLASS", "DIMENSION_SCALE"))) return err; while (attr) { log(" %s=%s\n",attr->name,attr->value); if (!strcmp(attr->name, "NAME") && attr->value && !strncmp(attr->value, "This is a netCDF dimension but not a netCDF variable.", 53)) { char *p = attr->value + strlen(attr->value) - 1; while (isdigit(*p)) { p--; } p++; *dim = atoi(p); log("NETCDF DIM %u\n",*dim); return MYSOFA_OK; } attr = attr->next; } return MYSOFA_INVALID_FORMAT; } static int getArray(struct MYSOFA_ARRAY *array, struct DATAOBJECT *dataobject) { float *p1; double *p2; int i; struct MYSOFA_ATTRIBUTE *attr = dataobject->attributes; while (attr) { log(" %s=%s\n",attr->name,attr->value); attr = attr->next; } if (dataobject->dt.u.f.bit_precision != 64) return MYSOFA_UNSUPPORTED_FORMAT; array->attributes = dataobject->attributes; dataobject->attributes = NULL; array->elements = dataobject->data_len / 8; p1 = dataobject->data; p2 = dataobject->data; for (i = 0; i < array->elements; i++) *p1++ = *p2++; array->values = realloc(dataobject->data, array->elements * sizeof(float)); dataobject->data = NULL; return MYSOFA_OK; } static struct MYSOFA_HRTF *getHrtf(struct READER *reader, int *err) { int dimensionflags = 0; struct DIR *dir = reader->superblock.dataobject.directory; struct MYSOFA_HRTF *hrtf = malloc(sizeof(struct MYSOFA_HRTF)); if (!hrtf) { *err = errno; return NULL; } memset(hrtf, 0, sizeof(struct MYSOFA_HRTF)); /* copy SOFA file attributes */ hrtf->attributes = reader->superblock.dataobject.attributes; reader->superblock.dataobject.attributes = NULL; /* check SOFA file attributes */ if (!!(*err = checkAttribute(hrtf->attributes, "Conventions", "SOFA"))) goto error; /* read dimensions */ while (dir) { if (dir->dataobject.name && dir->dataobject.name[0] && dir->dataobject.name[1] == 0) { switch (dir->dataobject.name[0]) { case 'I': *err = getDimension(&hrtf->I, &dir->dataobject); dimensionflags |= 1; break; case 'C': *err = getDimension(&hrtf->C, &dir->dataobject); dimensionflags |= 2; break; case 'R': *err = getDimension(&hrtf->R, &dir->dataobject); dimensionflags |= 4; break; case 'E': *err = getDimension(&hrtf->E, &dir->dataobject); dimensionflags |= 8; break; case 'N': *err = getDimension(&hrtf->N, &dir->dataobject); dimensionflags |= 0x10; break; case 'M': *err = getDimension(&hrtf->M, &dir->dataobject); dimensionflags |= 0x20; break; case 'S': break; /* be graceful, some issues with API version 0.4.4 */ default: log("UNKNOWN SOFA VARIABLE %s", dir->dataobject.name); goto error; } if (*err) goto error; } dir = dir->next; } if (dimensionflags != 0x3f || hrtf->I != 1 || hrtf->C != 3) { log("dimensions are missing or wrong\n"); goto error; } dir = reader->superblock.dataobject.directory; while (dir) { if(!dir->dataobject.name) { log("SOFA VARIABLE IS NULL.\n"); } else if (!strcmp(dir->dataobject.name, "ListenerPosition")) { *err = getArray(&hrtf->ListenerPosition, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "ReceiverPosition")) { *err = getArray(&hrtf->ReceiverPosition, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "SourcePosition")) { *err = getArray(&hrtf->SourcePosition, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "EmitterPosition")) { *err = getArray(&hrtf->EmitterPosition, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "ListenerUp")) { *err = getArray(&hrtf->ListenerUp, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "ListenerView")) { *err = getArray(&hrtf->ListenerView, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "Data.IR")) { *err = getArray(&hrtf->DataIR, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "Data.SamplingRate")) { *err = getArray(&hrtf->DataSamplingRate, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "Data.Delay")) { *err = getArray(&hrtf->DataDelay, &dir->dataobject); } else { if (!(dir->dataobject.name[0] && !dir->dataobject.name[1])) log("UNKNOWN SOFA VARIABLE %s.\n", dir->dataobject.name); } dir = dir->next; } return hrtf; error: free(hrtf); if (!*err) *err = MYSOFA_INVALID_FORMAT; return NULL; } MYSOFA_EXPORT struct MYSOFA_HRTF* mysofa_load(const char *filename, int *err) { struct READER reader; struct MYSOFA_HRTF *hrtf = NULL; if (filename == NULL) filename = CMAKE_INSTALL_PREFIX "/share/libmysofa/default.sofa"; if (strcmp(filename, "-")) reader.fhd = fopen(filename, "rb"); else reader.fhd = stdin; if (!reader.fhd) { log("cannot open file %s\n", filename); *err = errno; return NULL; } reader.gcol = NULL; reader.all = NULL; *err = superblockRead(&reader, &reader.superblock); if (!*err) { hrtf = getHrtf(&reader, err); } superblockFree(&reader, &reader.superblock); gcolFree(reader.gcol); if (strcmp(filename, "-")) fclose(reader.fhd); return hrtf; } static void arrayFree(struct MYSOFA_ARRAY *array) { while (array->attributes) { struct MYSOFA_ATTRIBUTE *next = array->attributes->next; free(array->attributes->name); free(array->attributes->value); free(array->attributes); array->attributes = next; } free(array->values); } MYSOFA_EXPORT void mysofa_free(struct MYSOFA_HRTF *hrtf) { if (!hrtf) return; while (hrtf->attributes) { struct MYSOFA_ATTRIBUTE *next = hrtf->attributes->next; free(hrtf->attributes->name); free(hrtf->attributes->value); free(hrtf->attributes); hrtf->attributes = next; } arrayFree(&hrtf->ListenerPosition); arrayFree(&hrtf->ReceiverPosition); arrayFree(&hrtf->SourcePosition); arrayFree(&hrtf->EmitterPosition); arrayFree(&hrtf->ListenerUp); arrayFree(&hrtf->ListenerView); arrayFree(&hrtf->DataIR); arrayFree(&hrtf->DataSamplingRate); arrayFree(&hrtf->DataDelay); free(hrtf); } MYSOFA_EXPORT void mysofa_getversion(int *major, int *minor, int *patch) { *major = CPACK_PACKAGE_VERSION_MAJOR; *minor = CPACK_PACKAGE_VERSION_MINOR; *patch = CPACK_PACKAGE_VERSION_PATCH; }
null
/* Copyright 2016 Christian Hoene, Symonics GmbH */ #include <errno.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "mysofa_export.h" #include "mysofa.h" #include "../hdf/reader.h" #include "../config.h" /* checks file address. * NULL is an invalid address indicating a invalid field */ int validAddress(struct READER *reader, uint64_t address) { return address > 0 && address < reader->superblock.end_of_file_address; } /* little endian */ uint64_t readValue(struct READER *reader, int size) { int i, c; uint64_t value; c = fgetc(reader->fhd); if (c < 0) return 0xffffffffffffffffLL; value = (uint8_t) c; for (i = 1; i < size; i++) { c = fgetc(reader->fhd); if (c < 0) return 0xffffffffffffffffLL; value |= ((uint64_t) c) << (i * 8); } return value; } static int mystrcmp(char *s1, char *s2) { if (s1 == NULL && s2 == NULL) return 0; if (s1 == NULL) return -1; if (s2 == NULL) return 1; return strcmp(s1, s2); } static int checkAttribute(struct MYSOFA_ATTRIBUTE *attribute, char *name, char *value) { while (attribute) { if (!mystrcmp(attribute->name, name) && !mystrcmp(attribute->value, value)) return MYSOFA_OK; attribute = attribute->next; } return MYSOFA_INVALID_FORMAT; } static int getDimension(unsigned *dim, struct DATAOBJECT *dataobject) { int err; struct MYSOFA_ATTRIBUTE *attr = dataobject->attributes; if (!!(err = checkAttribute(dataobject->attributes, "CLASS", "DIMENSION_SCALE"))) return err; while (attr) { log(" %s=%s\n",attr->name,attr->value); if (!strcmp(attr->name, "NAME") && attr->value && !strncmp(attr->value, "This is a netCDF dimension but not a netCDF variable.", 53)) { char *p = attr->value + strlen(attr->value) - 1; while (isdigit(*p)) { p--; } p++; *dim = atoi(p); log("NETCDF DIM %u\n",*dim); return MYSOFA_OK; } attr = attr->next; } return MYSOFA_INVALID_FORMAT; } static int getArray(struct MYSOFA_ARRAY *array, struct DATAOBJECT *dataobject) { float *p1; double *p2; int i; struct MYSOFA_ATTRIBUTE *attr = dataobject->attributes; while (attr) { log(" %s=%s\n",attr->name,attr->value); attr = attr->next; } if (dataobject->dt.u.f.bit_precision != 64) return MYSOFA_UNSUPPORTED_FORMAT; array->attributes = dataobject->attributes; dataobject->attributes = NULL; array->elements = dataobject->data_len / 8; p1 = dataobject->data; p2 = dataobject->data; for (i = 0; i < array->elements; i++) *p1++ = *p2++; array->values = realloc(dataobject->data, array->elements * sizeof(float)); dataobject->data = NULL; return MYSOFA_OK; } static struct MYSOFA_HRTF *getHrtf(struct READER *reader, int *err) { int dimensionflags = 0; struct DIR *dir = reader->superblock.dataobject.directory; struct MYSOFA_HRTF *hrtf = malloc(sizeof(struct MYSOFA_HRTF)); if (!hrtf) { *err = errno; return NULL; } memset(hrtf, 0, sizeof(struct MYSOFA_HRTF)); /* copy SOFA file attributes */ hrtf->attributes = reader->superblock.dataobject.attributes; reader->superblock.dataobject.attributes = NULL; /* check SOFA file attributes */ if (!!(*err = checkAttribute(hrtf->attributes, "Conventions", "SOFA"))) goto error; /* read dimensions */ while (dir) { if (dir->dataobject.name && dir->dataobject.name[0] && dir->dataobject.name[1] == 0) { switch (dir->dataobject.name[0]) { case 'I': *err = getDimension(&hrtf->I, &dir->dataobject); dimensionflags |= 1; break; case 'C': *err = getDimension(&hrtf->C, &dir->dataobject); dimensionflags |= 2; break; case 'R': *err = getDimension(&hrtf->R, &dir->dataobject); dimensionflags |= 4; break; case 'E': *err = getDimension(&hrtf->E, &dir->dataobject); dimensionflags |= 8; break; case 'N': *err = getDimension(&hrtf->N, &dir->dataobject); dimensionflags |= 0x10; break; case 'M': *err = getDimension(&hrtf->M, &dir->dataobject); dimensionflags |= 0x20; break; case 'S': break; /* be graceful, some issues with API version 0.4.4 */ default: log("UNKNOWN SOFA VARIABLE %s", dir->dataobject.name); goto error; } if (*err) goto error; } dir = dir->next; } if (dimensionflags != 0x3f || hrtf->I != 1 || hrtf->C != 3) { log("dimensions are missing or wrong\n"); goto error; } dir = reader->superblock.dataobject.directory; while (dir) { if(!dir->dataobject.name) { log("SOFA VARIABLE IS NULL.\n"); } else if (!strcmp(dir->dataobject.name, "ListenerPosition")) { *err = getArray(&hrtf->ListenerPosition, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "ReceiverPosition")) { *err = getArray(&hrtf->ReceiverPosition, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "SourcePosition")) { *err = getArray(&hrtf->SourcePosition, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "EmitterPosition")) { *err = getArray(&hrtf->EmitterPosition, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "ListenerUp")) { *err = getArray(&hrtf->ListenerUp, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "ListenerView")) { *err = getArray(&hrtf->ListenerView, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "Data.IR")) { *err = getArray(&hrtf->DataIR, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "Data.SamplingRate")) { *err = getArray(&hrtf->DataSamplingRate, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "Data.Delay")) { *err = getArray(&hrtf->DataDelay, &dir->dataobject); } else { if (!(dir->dataobject.name[0] && !dir->dataobject.name[1])) log("UNKNOWN SOFA VARIABLE %s.\n", dir->dataobject.name); } dir = dir->next; } return hrtf; error: free(hrtf); if (!*err) *err = MYSOFA_INVALID_FORMAT; return NULL; } MYSOFA_EXPORT struct MYSOFA_HRTF* mysofa_load(const char *filename, int *err) { struct READER reader; struct MYSOFA_HRTF *hrtf = NULL; if (filename == NULL) filename = CMAKE_INSTALL_PREFIX "/share/libmysofa/default.sofa"; if (strcmp(filename, "-")) reader.fhd = fopen(filename, "rb"); else reader.fhd = stdin; if (!reader.fhd) { log("cannot open file %s\n", filename); *err = errno; return NULL; } reader.gcol = NULL; reader.all = NULL; reader.recursive_counter = 0; *err = superblockRead(&reader, &reader.superblock); if (!*err) { hrtf = getHrtf(&reader, err); } superblockFree(&reader, &reader.superblock); gcolFree(reader.gcol); if (strcmp(filename, "-")) fclose(reader.fhd); return hrtf; } static void arrayFree(struct MYSOFA_ARRAY *array) { while (array->attributes) { struct MYSOFA_ATTRIBUTE *next = array->attributes->next; free(array->attributes->name); free(array->attributes->value); free(array->attributes); array->attributes = next; } free(array->values); } MYSOFA_EXPORT void mysofa_free(struct MYSOFA_HRTF *hrtf) { if (!hrtf) return; while (hrtf->attributes) { struct MYSOFA_ATTRIBUTE *next = hrtf->attributes->next; free(hrtf->attributes->name); free(hrtf->attributes->value); free(hrtf->attributes); hrtf->attributes = next; } arrayFree(&hrtf->ListenerPosition); arrayFree(&hrtf->ReceiverPosition); arrayFree(&hrtf->SourcePosition); arrayFree(&hrtf->EmitterPosition); arrayFree(&hrtf->ListenerUp); arrayFree(&hrtf->ListenerView); arrayFree(&hrtf->DataIR); arrayFree(&hrtf->DataSamplingRate); arrayFree(&hrtf->DataDelay); free(hrtf); } MYSOFA_EXPORT void mysofa_getversion(int *major, int *minor, int *patch) { *major = CPACK_PACKAGE_VERSION_MAJOR; *minor = CPACK_PACKAGE_VERSION_MINOR; *patch = CPACK_PACKAGE_VERSION_PATCH; }
null
152
CWE-787
CVE-2019-20636
// SPDX-License-Identifier: GPL-2.0-only /* * The input core * * Copyright (c) 1999-2002 Vojtech Pavlik */ #define pr_fmt(fmt) KBUILD_BASENAME ": " fmt #include <linux/init.h> #include <linux/types.h> #include <linux/idr.h> #include <linux/input/mt.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/random.h> #include <linux/major.h> #include <linux/proc_fs.h> #include <linux/sched.h> #include <linux/seq_file.h> #include <linux/poll.h> #include <linux/device.h> #include <linux/mutex.h> #include <linux/rcupdate.h> #include "input-compat.h" #include "input-poller.h" MODULE_AUTHOR("Vojtech Pavlik <vojtech@suse.cz>"); MODULE_DESCRIPTION("Input core"); MODULE_LICENSE("GPL"); #define INPUT_MAX_CHAR_DEVICES 1024 #define INPUT_FIRST_DYNAMIC_DEV 256 static DEFINE_IDA(input_ida); static LIST_HEAD(input_dev_list); static LIST_HEAD(input_handler_list); /* * input_mutex protects access to both input_dev_list and input_handler_list. * This also causes input_[un]register_device and input_[un]register_handler * be mutually exclusive which simplifies locking in drivers implementing * input handlers. */ static DEFINE_MUTEX(input_mutex); static const struct input_value input_value_sync = { EV_SYN, SYN_REPORT, 1 }; static inline int is_event_supported(unsigned int code, unsigned long *bm, unsigned int max) { return code <= max && test_bit(code, bm); } static int input_defuzz_abs_event(int value, int old_val, int fuzz) { if (fuzz) { if (value > old_val - fuzz / 2 && value < old_val + fuzz / 2) return old_val; if (value > old_val - fuzz && value < old_val + fuzz) return (old_val * 3 + value) / 4; if (value > old_val - fuzz * 2 && value < old_val + fuzz * 2) return (old_val + value) / 2; } return value; } static void input_start_autorepeat(struct input_dev *dev, int code) { if (test_bit(EV_REP, dev->evbit) && dev->rep[REP_PERIOD] && dev->rep[REP_DELAY] && dev->timer.function) { dev->repeat_key = code; mod_timer(&dev->timer, jiffies + msecs_to_jiffies(dev->rep[REP_DELAY])); } } static void input_stop_autorepeat(struct input_dev *dev) { del_timer(&dev->timer); } /* * Pass event first through all filters and then, if event has not been * filtered out, through all open handles. This function is called with * dev->event_lock held and interrupts disabled. */ static unsigned int input_to_handler(struct input_handle *handle, struct input_value *vals, unsigned int count) { struct input_handler *handler = handle->handler; struct input_value *end = vals; struct input_value *v; if (handler->filter) { for (v = vals; v != vals + count; v++) { if (handler->filter(handle, v->type, v->code, v->value)) continue; if (end != v) *end = *v; end++; } count = end - vals; } if (!count) return 0; if (handler->events) handler->events(handle, vals, count); else if (handler->event) for (v = vals; v != vals + count; v++) handler->event(handle, v->type, v->code, v->value); return count; } /* * Pass values first through all filters and then, if event has not been * filtered out, through all open handles. This function is called with * dev->event_lock held and interrupts disabled. */ static void input_pass_values(struct input_dev *dev, struct input_value *vals, unsigned int count) { struct input_handle *handle; struct input_value *v; if (!count) return; rcu_read_lock(); handle = rcu_dereference(dev->grab); if (handle) { count = input_to_handler(handle, vals, count); } else { list_for_each_entry_rcu(handle, &dev->h_list, d_node) if (handle->open) { count = input_to_handler(handle, vals, count); if (!count) break; } } rcu_read_unlock(); /* trigger auto repeat for key events */ if (test_bit(EV_REP, dev->evbit) && test_bit(EV_KEY, dev->evbit)) { for (v = vals; v != vals + count; v++) { if (v->type == EV_KEY && v->value != 2) { if (v->value) input_start_autorepeat(dev, v->code); else input_stop_autorepeat(dev); } } } } static void input_pass_event(struct input_dev *dev, unsigned int type, unsigned int code, int value) { struct input_value vals[] = { { type, code, value } }; input_pass_values(dev, vals, ARRAY_SIZE(vals)); } /* * Generate software autorepeat event. Note that we take * dev->event_lock here to avoid racing with input_event * which may cause keys get "stuck". */ static void input_repeat_key(struct timer_list *t) { struct input_dev *dev = from_timer(dev, t, timer); unsigned long flags; spin_lock_irqsave(&dev->event_lock, flags); if (test_bit(dev->repeat_key, dev->key) && is_event_supported(dev->repeat_key, dev->keybit, KEY_MAX)) { struct input_value vals[] = { { EV_KEY, dev->repeat_key, 2 }, input_value_sync }; input_pass_values(dev, vals, ARRAY_SIZE(vals)); if (dev->rep[REP_PERIOD]) mod_timer(&dev->timer, jiffies + msecs_to_jiffies(dev->rep[REP_PERIOD])); } spin_unlock_irqrestore(&dev->event_lock, flags); } #define INPUT_IGNORE_EVENT 0 #define INPUT_PASS_TO_HANDLERS 1 #define INPUT_PASS_TO_DEVICE 2 #define INPUT_SLOT 4 #define INPUT_FLUSH 8 #define INPUT_PASS_TO_ALL (INPUT_PASS_TO_HANDLERS | INPUT_PASS_TO_DEVICE) static int input_handle_abs_event(struct input_dev *dev, unsigned int code, int *pval) { struct input_mt *mt = dev->mt; bool is_mt_event; int *pold; if (code == ABS_MT_SLOT) { /* * "Stage" the event; we'll flush it later, when we * get actual touch data. */ if (mt && *pval >= 0 && *pval < mt->num_slots) mt->slot = *pval; return INPUT_IGNORE_EVENT; } is_mt_event = input_is_mt_value(code); if (!is_mt_event) { pold = &dev->absinfo[code].value; } else if (mt) { pold = &mt->slots[mt->slot].abs[code - ABS_MT_FIRST]; } else { /* * Bypass filtering for multi-touch events when * not employing slots. */ pold = NULL; } if (pold) { *pval = input_defuzz_abs_event(*pval, *pold, dev->absinfo[code].fuzz); if (*pold == *pval) return INPUT_IGNORE_EVENT; *pold = *pval; } /* Flush pending "slot" event */ if (is_mt_event && mt && mt->slot != input_abs_get_val(dev, ABS_MT_SLOT)) { input_abs_set_val(dev, ABS_MT_SLOT, mt->slot); return INPUT_PASS_TO_HANDLERS | INPUT_SLOT; } return INPUT_PASS_TO_HANDLERS; } static int input_get_disposition(struct input_dev *dev, unsigned int type, unsigned int code, int *pval) { int disposition = INPUT_IGNORE_EVENT; int value = *pval; switch (type) { case EV_SYN: switch (code) { case SYN_CONFIG: disposition = INPUT_PASS_TO_ALL; break; case SYN_REPORT: disposition = INPUT_PASS_TO_HANDLERS | INPUT_FLUSH; break; case SYN_MT_REPORT: disposition = INPUT_PASS_TO_HANDLERS; break; } break; case EV_KEY: if (is_event_supported(code, dev->keybit, KEY_MAX)) { /* auto-repeat bypasses state updates */ if (value == 2) { disposition = INPUT_PASS_TO_HANDLERS; break; } if (!!test_bit(code, dev->key) != !!value) { __change_bit(code, dev->key); disposition = INPUT_PASS_TO_HANDLERS; } } break; case EV_SW: if (is_event_supported(code, dev->swbit, SW_MAX) && !!test_bit(code, dev->sw) != !!value) { __change_bit(code, dev->sw); disposition = INPUT_PASS_TO_HANDLERS; } break; case EV_ABS: if (is_event_supported(code, dev->absbit, ABS_MAX)) disposition = input_handle_abs_event(dev, code, &value); break; case EV_REL: if (is_event_supported(code, dev->relbit, REL_MAX) && value) disposition = INPUT_PASS_TO_HANDLERS; break; case EV_MSC: if (is_event_supported(code, dev->mscbit, MSC_MAX)) disposition = INPUT_PASS_TO_ALL; break; case EV_LED: if (is_event_supported(code, dev->ledbit, LED_MAX) && !!test_bit(code, dev->led) != !!value) { __change_bit(code, dev->led); disposition = INPUT_PASS_TO_ALL; } break; case EV_SND: if (is_event_supported(code, dev->sndbit, SND_MAX)) { if (!!test_bit(code, dev->snd) != !!value) __change_bit(code, dev->snd); disposition = INPUT_PASS_TO_ALL; } break; case EV_REP: if (code <= REP_MAX && value >= 0 && dev->rep[code] != value) { dev->rep[code] = value; disposition = INPUT_PASS_TO_ALL; } break; case EV_FF: if (value >= 0) disposition = INPUT_PASS_TO_ALL; break; case EV_PWR: disposition = INPUT_PASS_TO_ALL; break; } *pval = value; return disposition; } static void input_handle_event(struct input_dev *dev, unsigned int type, unsigned int code, int value) { int disposition = input_get_disposition(dev, type, code, &value); if (disposition != INPUT_IGNORE_EVENT && type != EV_SYN) add_input_randomness(type, code, value); if ((disposition & INPUT_PASS_TO_DEVICE) && dev->event) dev->event(dev, type, code, value); if (!dev->vals) return; if (disposition & INPUT_PASS_TO_HANDLERS) { struct input_value *v; if (disposition & INPUT_SLOT) { v = &dev->vals[dev->num_vals++]; v->type = EV_ABS; v->code = ABS_MT_SLOT; v->value = dev->mt->slot; } v = &dev->vals[dev->num_vals++]; v->type = type; v->code = code; v->value = value; } if (disposition & INPUT_FLUSH) { if (dev->num_vals >= 2) input_pass_values(dev, dev->vals, dev->num_vals); dev->num_vals = 0; /* * Reset the timestamp on flush so we won't end up * with a stale one. Note we only need to reset the * monolithic one as we use its presence when deciding * whether to generate a synthetic timestamp. */ dev->timestamp[INPUT_CLK_MONO] = ktime_set(0, 0); } else if (dev->num_vals >= dev->max_vals - 2) { dev->vals[dev->num_vals++] = input_value_sync; input_pass_values(dev, dev->vals, dev->num_vals); dev->num_vals = 0; } } /** * input_event() - report new input event * @dev: device that generated the event * @type: type of the event * @code: event code * @value: value of the event * * This function should be used by drivers implementing various input * devices to report input events. See also input_inject_event(). * * NOTE: input_event() may be safely used right after input device was * allocated with input_allocate_device(), even before it is registered * with input_register_device(), but the event will not reach any of the * input handlers. Such early invocation of input_event() may be used * to 'seed' initial state of a switch or initial position of absolute * axis, etc. */ void input_event(struct input_dev *dev, unsigned int type, unsigned int code, int value) { unsigned long flags; if (is_event_supported(type, dev->evbit, EV_MAX)) { spin_lock_irqsave(&dev->event_lock, flags); input_handle_event(dev, type, code, value); spin_unlock_irqrestore(&dev->event_lock, flags); } } EXPORT_SYMBOL(input_event); /** * input_inject_event() - send input event from input handler * @handle: input handle to send event through * @type: type of the event * @code: event code * @value: value of the event * * Similar to input_event() but will ignore event if device is * "grabbed" and handle injecting event is not the one that owns * the device. */ void input_inject_event(struct input_handle *handle, unsigned int type, unsigned int code, int value) { struct input_dev *dev = handle->dev; struct input_handle *grab; unsigned long flags; if (is_event_supported(type, dev->evbit, EV_MAX)) { spin_lock_irqsave(&dev->event_lock, flags); rcu_read_lock(); grab = rcu_dereference(dev->grab); if (!grab || grab == handle) input_handle_event(dev, type, code, value); rcu_read_unlock(); spin_unlock_irqrestore(&dev->event_lock, flags); } } EXPORT_SYMBOL(input_inject_event); /** * input_alloc_absinfo - allocates array of input_absinfo structs * @dev: the input device emitting absolute events * * If the absinfo struct the caller asked for is already allocated, this * functions will not do anything. */ void input_alloc_absinfo(struct input_dev *dev) { if (dev->absinfo) return; dev->absinfo = kcalloc(ABS_CNT, sizeof(*dev->absinfo), GFP_KERNEL); if (!dev->absinfo) { dev_err(dev->dev.parent ?: &dev->dev, "%s: unable to allocate memory\n", __func__); /* * We will handle this allocation failure in * input_register_device() when we refuse to register input * device with ABS bits but without absinfo. */ } } EXPORT_SYMBOL(input_alloc_absinfo); void input_set_abs_params(struct input_dev *dev, unsigned int axis, int min, int max, int fuzz, int flat) { struct input_absinfo *absinfo; input_alloc_absinfo(dev); if (!dev->absinfo) return; absinfo = &dev->absinfo[axis]; absinfo->minimum = min; absinfo->maximum = max; absinfo->fuzz = fuzz; absinfo->flat = flat; __set_bit(EV_ABS, dev->evbit); __set_bit(axis, dev->absbit); } EXPORT_SYMBOL(input_set_abs_params); /** * input_grab_device - grabs device for exclusive use * @handle: input handle that wants to own the device * * When a device is grabbed by an input handle all events generated by * the device are delivered only to this handle. Also events injected * by other input handles are ignored while device is grabbed. */ int input_grab_device(struct input_handle *handle) { struct input_dev *dev = handle->dev; int retval; retval = mutex_lock_interruptible(&dev->mutex); if (retval) return retval; if (dev->grab) { retval = -EBUSY; goto out; } rcu_assign_pointer(dev->grab, handle); out: mutex_unlock(&dev->mutex); return retval; } EXPORT_SYMBOL(input_grab_device); static void __input_release_device(struct input_handle *handle) { struct input_dev *dev = handle->dev; struct input_handle *grabber; grabber = rcu_dereference_protected(dev->grab, lockdep_is_held(&dev->mutex)); if (grabber == handle) { rcu_assign_pointer(dev->grab, NULL); /* Make sure input_pass_event() notices that grab is gone */ synchronize_rcu(); list_for_each_entry(handle, &dev->h_list, d_node) if (handle->open && handle->handler->start) handle->handler->start(handle); } } /** * input_release_device - release previously grabbed device * @handle: input handle that owns the device * * Releases previously grabbed device so that other input handles can * start receiving input events. Upon release all handlers attached * to the device have their start() method called so they have a change * to synchronize device state with the rest of the system. */ void input_release_device(struct input_handle *handle) { struct input_dev *dev = handle->dev; mutex_lock(&dev->mutex); __input_release_device(handle); mutex_unlock(&dev->mutex); } EXPORT_SYMBOL(input_release_device); /** * input_open_device - open input device * @handle: handle through which device is being accessed * * This function should be called by input handlers when they * want to start receive events from given input device. */ int input_open_device(struct input_handle *handle) { struct input_dev *dev = handle->dev; int retval; retval = mutex_lock_interruptible(&dev->mutex); if (retval) return retval; if (dev->going_away) { retval = -ENODEV; goto out; } handle->open++; if (dev->users++) { /* * Device is already opened, so we can exit immediately and * report success. */ goto out; } if (dev->open) { retval = dev->open(dev); if (retval) { dev->users--; handle->open--; /* * Make sure we are not delivering any more events * through this handle */ synchronize_rcu(); goto out; } } if (dev->poller) input_dev_poller_start(dev->poller); out: mutex_unlock(&dev->mutex); return retval; } EXPORT_SYMBOL(input_open_device); int input_flush_device(struct input_handle *handle, struct file *file) { struct input_dev *dev = handle->dev; int retval; retval = mutex_lock_interruptible(&dev->mutex); if (retval) return retval; if (dev->flush) retval = dev->flush(dev, file); mutex_unlock(&dev->mutex); return retval; } EXPORT_SYMBOL(input_flush_device); /** * input_close_device - close input device * @handle: handle through which device is being accessed * * This function should be called by input handlers when they * want to stop receive events from given input device. */ void input_close_device(struct input_handle *handle) { struct input_dev *dev = handle->dev; mutex_lock(&dev->mutex); __input_release_device(handle); if (!--dev->users) { if (dev->poller) input_dev_poller_stop(dev->poller); if (dev->close) dev->close(dev); } if (!--handle->open) { /* * synchronize_rcu() makes sure that input_pass_event() * completed and that no more input events are delivered * through this handle */ synchronize_rcu(); } mutex_unlock(&dev->mutex); } EXPORT_SYMBOL(input_close_device); /* * Simulate keyup events for all keys that are marked as pressed. * The function must be called with dev->event_lock held. */ static void input_dev_release_keys(struct input_dev *dev) { bool need_sync = false; int code; if (is_event_supported(EV_KEY, dev->evbit, EV_MAX)) { for_each_set_bit(code, dev->key, KEY_CNT) { input_pass_event(dev, EV_KEY, code, 0); need_sync = true; } if (need_sync) input_pass_event(dev, EV_SYN, SYN_REPORT, 1); memset(dev->key, 0, sizeof(dev->key)); } } /* * Prepare device for unregistering */ static void input_disconnect_device(struct input_dev *dev) { struct input_handle *handle; /* * Mark device as going away. Note that we take dev->mutex here * not to protect access to dev->going_away but rather to ensure * that there are no threads in the middle of input_open_device() */ mutex_lock(&dev->mutex); dev->going_away = true; mutex_unlock(&dev->mutex); spin_lock_irq(&dev->event_lock); /* * Simulate keyup events for all pressed keys so that handlers * are not left with "stuck" keys. The driver may continue * generate events even after we done here but they will not * reach any handlers. */ input_dev_release_keys(dev); list_for_each_entry(handle, &dev->h_list, d_node) handle->open = 0; spin_unlock_irq(&dev->event_lock); } /** * input_scancode_to_scalar() - converts scancode in &struct input_keymap_entry * @ke: keymap entry containing scancode to be converted. * @scancode: pointer to the location where converted scancode should * be stored. * * This function is used to convert scancode stored in &struct keymap_entry * into scalar form understood by legacy keymap handling methods. These * methods expect scancodes to be represented as 'unsigned int'. */ int input_scancode_to_scalar(const struct input_keymap_entry *ke, unsigned int *scancode) { switch (ke->len) { case 1: *scancode = *((u8 *)ke->scancode); break; case 2: *scancode = *((u16 *)ke->scancode); break; case 4: *scancode = *((u32 *)ke->scancode); break; default: return -EINVAL; } return 0; } EXPORT_SYMBOL(input_scancode_to_scalar); /* * Those routines handle the default case where no [gs]etkeycode() is * defined. In this case, an array indexed by the scancode is used. */ static unsigned int input_fetch_keycode(struct input_dev *dev, unsigned int index) { switch (dev->keycodesize) { case 1: return ((u8 *)dev->keycode)[index]; case 2: return ((u16 *)dev->keycode)[index]; default: return ((u32 *)dev->keycode)[index]; } } static int input_default_getkeycode(struct input_dev *dev, struct input_keymap_entry *ke) { unsigned int index; int error; if (!dev->keycodesize) return -EINVAL; if (ke->flags & INPUT_KEYMAP_BY_INDEX) index = ke->index; else { error = input_scancode_to_scalar(ke, &index); if (error) return error; } if (index >= dev->keycodemax) return -EINVAL; ke->keycode = input_fetch_keycode(dev, index); ke->index = index; ke->len = sizeof(index); memcpy(ke->scancode, &index, sizeof(index)); return 0; } static int input_default_setkeycode(struct input_dev *dev, const struct input_keymap_entry *ke, unsigned int *old_keycode) { unsigned int index; int error; int i; if (!dev->keycodesize) return -EINVAL; if (ke->flags & INPUT_KEYMAP_BY_INDEX) { index = ke->index; } else { error = input_scancode_to_scalar(ke, &index); if (error) return error; } if (index >= dev->keycodemax) return -EINVAL; if (dev->keycodesize < sizeof(ke->keycode) && (ke->keycode >> (dev->keycodesize * 8))) return -EINVAL; switch (dev->keycodesize) { case 1: { u8 *k = (u8 *)dev->keycode; *old_keycode = k[index]; k[index] = ke->keycode; break; } case 2: { u16 *k = (u16 *)dev->keycode; *old_keycode = k[index]; k[index] = ke->keycode; break; } default: { u32 *k = (u32 *)dev->keycode; *old_keycode = k[index]; k[index] = ke->keycode; break; } } __clear_bit(*old_keycode, dev->keybit); __set_bit(ke->keycode, dev->keybit); for (i = 0; i < dev->keycodemax; i++) { if (input_fetch_keycode(dev, i) == *old_keycode) { __set_bit(*old_keycode, dev->keybit); break; /* Setting the bit twice is useless, so break */ } } return 0; } /** * input_get_keycode - retrieve keycode currently mapped to a given scancode * @dev: input device which keymap is being queried * @ke: keymap entry * * This function should be called by anyone interested in retrieving current * keymap. Presently evdev handlers use it. */ int input_get_keycode(struct input_dev *dev, struct input_keymap_entry *ke) { unsigned long flags; int retval; spin_lock_irqsave(&dev->event_lock, flags); retval = dev->getkeycode(dev, ke); spin_unlock_irqrestore(&dev->event_lock, flags); return retval; } EXPORT_SYMBOL(input_get_keycode); /** * input_set_keycode - attribute a keycode to a given scancode * @dev: input device which keymap is being updated * @ke: new keymap entry * * This function should be called by anyone needing to update current * keymap. Presently keyboard and evdev handlers use it. */ int input_set_keycode(struct input_dev *dev, const struct input_keymap_entry *ke) { unsigned long flags; unsigned int old_keycode; int retval; if (ke->keycode > KEY_MAX) return -EINVAL; spin_lock_irqsave(&dev->event_lock, flags); retval = dev->setkeycode(dev, ke, &old_keycode); if (retval) goto out; /* Make sure KEY_RESERVED did not get enabled. */ __clear_bit(KEY_RESERVED, dev->keybit); /* * Simulate keyup event if keycode is not present * in the keymap anymore */ if (test_bit(EV_KEY, dev->evbit) && !is_event_supported(old_keycode, dev->keybit, KEY_MAX) && __test_and_clear_bit(old_keycode, dev->key)) { struct input_value vals[] = { { EV_KEY, old_keycode, 0 }, input_value_sync }; input_pass_values(dev, vals, ARRAY_SIZE(vals)); } out: spin_unlock_irqrestore(&dev->event_lock, flags); return retval; } EXPORT_SYMBOL(input_set_keycode); bool input_match_device_id(const struct input_dev *dev, const struct input_device_id *id) { if (id->flags & INPUT_DEVICE_ID_MATCH_BUS) if (id->bustype != dev->id.bustype) return false; if (id->flags & INPUT_DEVICE_ID_MATCH_VENDOR) if (id->vendor != dev->id.vendor) return false; if (id->flags & INPUT_DEVICE_ID_MATCH_PRODUCT) if (id->product != dev->id.product) return false; if (id->flags & INPUT_DEVICE_ID_MATCH_VERSION) if (id->version != dev->id.version) return false; if (!bitmap_subset(id->evbit, dev->evbit, EV_MAX) || !bitmap_subset(id->keybit, dev->keybit, KEY_MAX) || !bitmap_subset(id->relbit, dev->relbit, REL_MAX) || !bitmap_subset(id->absbit, dev->absbit, ABS_MAX) || !bitmap_subset(id->mscbit, dev->mscbit, MSC_MAX) || !bitmap_subset(id->ledbit, dev->ledbit, LED_MAX) || !bitmap_subset(id->sndbit, dev->sndbit, SND_MAX) || !bitmap_subset(id->ffbit, dev->ffbit, FF_MAX) || !bitmap_subset(id->swbit, dev->swbit, SW_MAX) || !bitmap_subset(id->propbit, dev->propbit, INPUT_PROP_MAX)) { return false; } return true; } EXPORT_SYMBOL(input_match_device_id); static const struct input_device_id *input_match_device(struct input_handler *handler, struct input_dev *dev) { const struct input_device_id *id; for (id = handler->id_table; id->flags || id->driver_info; id++) { if (input_match_device_id(dev, id) && (!handler->match || handler->match(handler, dev))) { return id; } } return NULL; } static int input_attach_handler(struct input_dev *dev, struct input_handler *handler) { const struct input_device_id *id; int error; id = input_match_device(handler, dev); if (!id) return -ENODEV; error = handler->connect(handler, dev, id); if (error && error != -ENODEV) pr_err("failed to attach handler %s to device %s, error: %d\n", handler->name, kobject_name(&dev->dev.kobj), error); return error; } #ifdef CONFIG_COMPAT static int input_bits_to_string(char *buf, int buf_size, unsigned long bits, bool skip_empty) { int len = 0; if (in_compat_syscall()) { u32 dword = bits >> 32; if (dword || !skip_empty) len += snprintf(buf, buf_size, "%x ", dword); dword = bits & 0xffffffffUL; if (dword || !skip_empty || len) len += snprintf(buf + len, max(buf_size - len, 0), "%x", dword); } else { if (bits || !skip_empty) len += snprintf(buf, buf_size, "%lx", bits); } return len; } #else /* !CONFIG_COMPAT */ static int input_bits_to_string(char *buf, int buf_size, unsigned long bits, bool skip_empty) { return bits || !skip_empty ? snprintf(buf, buf_size, "%lx", bits) : 0; } #endif #ifdef CONFIG_PROC_FS static struct proc_dir_entry *proc_bus_input_dir; static DECLARE_WAIT_QUEUE_HEAD(input_devices_poll_wait); static int input_devices_state; static inline void input_wakeup_procfs_readers(void) { input_devices_state++; wake_up(&input_devices_poll_wait); } static __poll_t input_proc_devices_poll(struct file *file, poll_table *wait) { poll_wait(file, &input_devices_poll_wait, wait); if (file->f_version != input_devices_state) { file->f_version = input_devices_state; return EPOLLIN | EPOLLRDNORM; } return 0; } union input_seq_state { struct { unsigned short pos; bool mutex_acquired; }; void *p; }; static void *input_devices_seq_start(struct seq_file *seq, loff_t *pos) { union input_seq_state *state = (union input_seq_state *)&seq->private; int error; /* We need to fit into seq->private pointer */ BUILD_BUG_ON(sizeof(union input_seq_state) != sizeof(seq->private)); error = mutex_lock_interruptible(&input_mutex); if (error) { state->mutex_acquired = false; return ERR_PTR(error); } state->mutex_acquired = true; return seq_list_start(&input_dev_list, *pos); } static void *input_devices_seq_next(struct seq_file *seq, void *v, loff_t *pos) { return seq_list_next(v, &input_dev_list, pos); } static void input_seq_stop(struct seq_file *seq, void *v) { union input_seq_state *state = (union input_seq_state *)&seq->private; if (state->mutex_acquired) mutex_unlock(&input_mutex); } static void input_seq_print_bitmap(struct seq_file *seq, const char *name, unsigned long *bitmap, int max) { int i; bool skip_empty = true; char buf[18]; seq_printf(seq, "B: %s=", name); for (i = BITS_TO_LONGS(max) - 1; i >= 0; i--) { if (input_bits_to_string(buf, sizeof(buf), bitmap[i], skip_empty)) { skip_empty = false; seq_printf(seq, "%s%s", buf, i > 0 ? " " : ""); } } /* * If no output was produced print a single 0. */ if (skip_empty) seq_putc(seq, '0'); seq_putc(seq, '\n'); } static int input_devices_seq_show(struct seq_file *seq, void *v) { struct input_dev *dev = container_of(v, struct input_dev, node); const char *path = kobject_get_path(&dev->dev.kobj, GFP_KERNEL); struct input_handle *handle; seq_printf(seq, "I: Bus=%04x Vendor=%04x Product=%04x Version=%04x\n", dev->id.bustype, dev->id.vendor, dev->id.product, dev->id.version); seq_printf(seq, "N: Name=\"%s\"\n", dev->name ? dev->name : ""); seq_printf(seq, "P: Phys=%s\n", dev->phys ? dev->phys : ""); seq_printf(seq, "S: Sysfs=%s\n", path ? path : ""); seq_printf(seq, "U: Uniq=%s\n", dev->uniq ? dev->uniq : ""); seq_puts(seq, "H: Handlers="); list_for_each_entry(handle, &dev->h_list, d_node) seq_printf(seq, "%s ", handle->name); seq_putc(seq, '\n'); input_seq_print_bitmap(seq, "PROP", dev->propbit, INPUT_PROP_MAX); input_seq_print_bitmap(seq, "EV", dev->evbit, EV_MAX); if (test_bit(EV_KEY, dev->evbit)) input_seq_print_bitmap(seq, "KEY", dev->keybit, KEY_MAX); if (test_bit(EV_REL, dev->evbit)) input_seq_print_bitmap(seq, "REL", dev->relbit, REL_MAX); if (test_bit(EV_ABS, dev->evbit)) input_seq_print_bitmap(seq, "ABS", dev->absbit, ABS_MAX); if (test_bit(EV_MSC, dev->evbit)) input_seq_print_bitmap(seq, "MSC", dev->mscbit, MSC_MAX); if (test_bit(EV_LED, dev->evbit)) input_seq_print_bitmap(seq, "LED", dev->ledbit, LED_MAX); if (test_bit(EV_SND, dev->evbit)) input_seq_print_bitmap(seq, "SND", dev->sndbit, SND_MAX); if (test_bit(EV_FF, dev->evbit)) input_seq_print_bitmap(seq, "FF", dev->ffbit, FF_MAX); if (test_bit(EV_SW, dev->evbit)) input_seq_print_bitmap(seq, "SW", dev->swbit, SW_MAX); seq_putc(seq, '\n'); kfree(path); return 0; } static const struct seq_operations input_devices_seq_ops = { .start = input_devices_seq_start, .next = input_devices_seq_next, .stop = input_seq_stop, .show = input_devices_seq_show, }; static int input_proc_devices_open(struct inode *inode, struct file *file) { return seq_open(file, &input_devices_seq_ops); } static const struct file_operations input_devices_fileops = { .owner = THIS_MODULE, .open = input_proc_devices_open, .poll = input_proc_devices_poll, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static void *input_handlers_seq_start(struct seq_file *seq, loff_t *pos) { union input_seq_state *state = (union input_seq_state *)&seq->private; int error; /* We need to fit into seq->private pointer */ BUILD_BUG_ON(sizeof(union input_seq_state) != sizeof(seq->private)); error = mutex_lock_interruptible(&input_mutex); if (error) { state->mutex_acquired = false; return ERR_PTR(error); } state->mutex_acquired = true; state->pos = *pos; return seq_list_start(&input_handler_list, *pos); } static void *input_handlers_seq_next(struct seq_file *seq, void *v, loff_t *pos) { union input_seq_state *state = (union input_seq_state *)&seq->private; state->pos = *pos + 1; return seq_list_next(v, &input_handler_list, pos); } static int input_handlers_seq_show(struct seq_file *seq, void *v) { struct input_handler *handler = container_of(v, struct input_handler, node); union input_seq_state *state = (union input_seq_state *)&seq->private; seq_printf(seq, "N: Number=%u Name=%s", state->pos, handler->name); if (handler->filter) seq_puts(seq, " (filter)"); if (handler->legacy_minors) seq_printf(seq, " Minor=%d", handler->minor); seq_putc(seq, '\n'); return 0; } static const struct seq_operations input_handlers_seq_ops = { .start = input_handlers_seq_start, .next = input_handlers_seq_next, .stop = input_seq_stop, .show = input_handlers_seq_show, }; static int input_proc_handlers_open(struct inode *inode, struct file *file) { return seq_open(file, &input_handlers_seq_ops); } static const struct file_operations input_handlers_fileops = { .owner = THIS_MODULE, .open = input_proc_handlers_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static int __init input_proc_init(void) { struct proc_dir_entry *entry; proc_bus_input_dir = proc_mkdir("bus/input", NULL); if (!proc_bus_input_dir) return -ENOMEM; entry = proc_create("devices", 0, proc_bus_input_dir, &input_devices_fileops); if (!entry) goto fail1; entry = proc_create("handlers", 0, proc_bus_input_dir, &input_handlers_fileops); if (!entry) goto fail2; return 0; fail2: remove_proc_entry("devices", proc_bus_input_dir); fail1: remove_proc_entry("bus/input", NULL); return -ENOMEM; } static void input_proc_exit(void) { remove_proc_entry("devices", proc_bus_input_dir); remove_proc_entry("handlers", proc_bus_input_dir); remove_proc_entry("bus/input", NULL); } #else /* !CONFIG_PROC_FS */ static inline void input_wakeup_procfs_readers(void) { } static inline int input_proc_init(void) { return 0; } static inline void input_proc_exit(void) { } #endif #define INPUT_DEV_STRING_ATTR_SHOW(name) \ static ssize_t input_dev_show_##name(struct device *dev, \ struct device_attribute *attr, \ char *buf) \ { \ struct input_dev *input_dev = to_input_dev(dev); \ \ return scnprintf(buf, PAGE_SIZE, "%s\n", \ input_dev->name ? input_dev->name : ""); \ } \ static DEVICE_ATTR(name, S_IRUGO, input_dev_show_##name, NULL) INPUT_DEV_STRING_ATTR_SHOW(name); INPUT_DEV_STRING_ATTR_SHOW(phys); INPUT_DEV_STRING_ATTR_SHOW(uniq); static int input_print_modalias_bits(char *buf, int size, char name, unsigned long *bm, unsigned int min_bit, unsigned int max_bit) { int len = 0, i; len += snprintf(buf, max(size, 0), "%c", name); for (i = min_bit; i < max_bit; i++) if (bm[BIT_WORD(i)] & BIT_MASK(i)) len += snprintf(buf + len, max(size - len, 0), "%X,", i); return len; } static int input_print_modalias(char *buf, int size, struct input_dev *id, int add_cr) { int len; len = snprintf(buf, max(size, 0), "input:b%04Xv%04Xp%04Xe%04X-", id->id.bustype, id->id.vendor, id->id.product, id->id.version); len += input_print_modalias_bits(buf + len, size - len, 'e', id->evbit, 0, EV_MAX); len += input_print_modalias_bits(buf + len, size - len, 'k', id->keybit, KEY_MIN_INTERESTING, KEY_MAX); len += input_print_modalias_bits(buf + len, size - len, 'r', id->relbit, 0, REL_MAX); len += input_print_modalias_bits(buf + len, size - len, 'a', id->absbit, 0, ABS_MAX); len += input_print_modalias_bits(buf + len, size - len, 'm', id->mscbit, 0, MSC_MAX); len += input_print_modalias_bits(buf + len, size - len, 'l', id->ledbit, 0, LED_MAX); len += input_print_modalias_bits(buf + len, size - len, 's', id->sndbit, 0, SND_MAX); len += input_print_modalias_bits(buf + len, size - len, 'f', id->ffbit, 0, FF_MAX); len += input_print_modalias_bits(buf + len, size - len, 'w', id->swbit, 0, SW_MAX); if (add_cr) len += snprintf(buf + len, max(size - len, 0), "\n"); return len; } static ssize_t input_dev_show_modalias(struct device *dev, struct device_attribute *attr, char *buf) { struct input_dev *id = to_input_dev(dev); ssize_t len; len = input_print_modalias(buf, PAGE_SIZE, id, 1); return min_t(int, len, PAGE_SIZE); } static DEVICE_ATTR(modalias, S_IRUGO, input_dev_show_modalias, NULL); static int input_print_bitmap(char *buf, int buf_size, unsigned long *bitmap, int max, int add_cr); static ssize_t input_dev_show_properties(struct device *dev, struct device_attribute *attr, char *buf) { struct input_dev *input_dev = to_input_dev(dev); int len = input_print_bitmap(buf, PAGE_SIZE, input_dev->propbit, INPUT_PROP_MAX, true); return min_t(int, len, PAGE_SIZE); } static DEVICE_ATTR(properties, S_IRUGO, input_dev_show_properties, NULL); static struct attribute *input_dev_attrs[] = { &dev_attr_name.attr, &dev_attr_phys.attr, &dev_attr_uniq.attr, &dev_attr_modalias.attr, &dev_attr_properties.attr, NULL }; static const struct attribute_group input_dev_attr_group = { .attrs = input_dev_attrs, }; #define INPUT_DEV_ID_ATTR(name) \ static ssize_t input_dev_show_id_##name(struct device *dev, \ struct device_attribute *attr, \ char *buf) \ { \ struct input_dev *input_dev = to_input_dev(dev); \ return scnprintf(buf, PAGE_SIZE, "%04x\n", input_dev->id.name); \ } \ static DEVICE_ATTR(name, S_IRUGO, input_dev_show_id_##name, NULL) INPUT_DEV_ID_ATTR(bustype); INPUT_DEV_ID_ATTR(vendor); INPUT_DEV_ID_ATTR(product); INPUT_DEV_ID_ATTR(version); static struct attribute *input_dev_id_attrs[] = { &dev_attr_bustype.attr, &dev_attr_vendor.attr, &dev_attr_product.attr, &dev_attr_version.attr, NULL }; static const struct attribute_group input_dev_id_attr_group = { .name = "id", .attrs = input_dev_id_attrs, }; static int input_print_bitmap(char *buf, int buf_size, unsigned long *bitmap, int max, int add_cr) { int i; int len = 0; bool skip_empty = true; for (i = BITS_TO_LONGS(max) - 1; i >= 0; i--) { len += input_bits_to_string(buf + len, max(buf_size - len, 0), bitmap[i], skip_empty); if (len) { skip_empty = false; if (i > 0) len += snprintf(buf + len, max(buf_size - len, 0), " "); } } /* * If no output was produced print a single 0. */ if (len == 0) len = snprintf(buf, buf_size, "%d", 0); if (add_cr) len += snprintf(buf + len, max(buf_size - len, 0), "\n"); return len; } #define INPUT_DEV_CAP_ATTR(ev, bm) \ static ssize_t input_dev_show_cap_##bm(struct device *dev, \ struct device_attribute *attr, \ char *buf) \ { \ struct input_dev *input_dev = to_input_dev(dev); \ int len = input_print_bitmap(buf, PAGE_SIZE, \ input_dev->bm##bit, ev##_MAX, \ true); \ return min_t(int, len, PAGE_SIZE); \ } \ static DEVICE_ATTR(bm, S_IRUGO, input_dev_show_cap_##bm, NULL) INPUT_DEV_CAP_ATTR(EV, ev); INPUT_DEV_CAP_ATTR(KEY, key); INPUT_DEV_CAP_ATTR(REL, rel); INPUT_DEV_CAP_ATTR(ABS, abs); INPUT_DEV_CAP_ATTR(MSC, msc); INPUT_DEV_CAP_ATTR(LED, led); INPUT_DEV_CAP_ATTR(SND, snd); INPUT_DEV_CAP_ATTR(FF, ff); INPUT_DEV_CAP_ATTR(SW, sw); static struct attribute *input_dev_caps_attrs[] = { &dev_attr_ev.attr, &dev_attr_key.attr, &dev_attr_rel.attr, &dev_attr_abs.attr, &dev_attr_msc.attr, &dev_attr_led.attr, &dev_attr_snd.attr, &dev_attr_ff.attr, &dev_attr_sw.attr, NULL }; static const struct attribute_group input_dev_caps_attr_group = { .name = "capabilities", .attrs = input_dev_caps_attrs, }; static const struct attribute_group *input_dev_attr_groups[] = { &input_dev_attr_group, &input_dev_id_attr_group, &input_dev_caps_attr_group, &input_poller_attribute_group, NULL }; static void input_dev_release(struct device *device) { struct input_dev *dev = to_input_dev(device); input_ff_destroy(dev); input_mt_destroy_slots(dev); kfree(dev->poller); kfree(dev->absinfo); kfree(dev->vals); kfree(dev); module_put(THIS_MODULE); } /* * Input uevent interface - loading event handlers based on * device bitfields. */ static int input_add_uevent_bm_var(struct kobj_uevent_env *env, const char *name, unsigned long *bitmap, int max) { int len; if (add_uevent_var(env, "%s", name)) return -ENOMEM; len = input_print_bitmap(&env->buf[env->buflen - 1], sizeof(env->buf) - env->buflen, bitmap, max, false); if (len >= (sizeof(env->buf) - env->buflen)) return -ENOMEM; env->buflen += len; return 0; } static int input_add_uevent_modalias_var(struct kobj_uevent_env *env, struct input_dev *dev) { int len; if (add_uevent_var(env, "MODALIAS=")) return -ENOMEM; len = input_print_modalias(&env->buf[env->buflen - 1], sizeof(env->buf) - env->buflen, dev, 0); if (len >= (sizeof(env->buf) - env->buflen)) return -ENOMEM; env->buflen += len; return 0; } #define INPUT_ADD_HOTPLUG_VAR(fmt, val...) \ do { \ int err = add_uevent_var(env, fmt, val); \ if (err) \ return err; \ } while (0) #define INPUT_ADD_HOTPLUG_BM_VAR(name, bm, max) \ do { \ int err = input_add_uevent_bm_var(env, name, bm, max); \ if (err) \ return err; \ } while (0) #define INPUT_ADD_HOTPLUG_MODALIAS_VAR(dev) \ do { \ int err = input_add_uevent_modalias_var(env, dev); \ if (err) \ return err; \ } while (0) static int input_dev_uevent(struct device *device, struct kobj_uevent_env *env) { struct input_dev *dev = to_input_dev(device); INPUT_ADD_HOTPLUG_VAR("PRODUCT=%x/%x/%x/%x", dev->id.bustype, dev->id.vendor, dev->id.product, dev->id.version); if (dev->name) INPUT_ADD_HOTPLUG_VAR("NAME=\"%s\"", dev->name); if (dev->phys) INPUT_ADD_HOTPLUG_VAR("PHYS=\"%s\"", dev->phys); if (dev->uniq) INPUT_ADD_HOTPLUG_VAR("UNIQ=\"%s\"", dev->uniq); INPUT_ADD_HOTPLUG_BM_VAR("PROP=", dev->propbit, INPUT_PROP_MAX); INPUT_ADD_HOTPLUG_BM_VAR("EV=", dev->evbit, EV_MAX); if (test_bit(EV_KEY, dev->evbit)) INPUT_ADD_HOTPLUG_BM_VAR("KEY=", dev->keybit, KEY_MAX); if (test_bit(EV_REL, dev->evbit)) INPUT_ADD_HOTPLUG_BM_VAR("REL=", dev->relbit, REL_MAX); if (test_bit(EV_ABS, dev->evbit)) INPUT_ADD_HOTPLUG_BM_VAR("ABS=", dev->absbit, ABS_MAX); if (test_bit(EV_MSC, dev->evbit)) INPUT_ADD_HOTPLUG_BM_VAR("MSC=", dev->mscbit, MSC_MAX); if (test_bit(EV_LED, dev->evbit)) INPUT_ADD_HOTPLUG_BM_VAR("LED=", dev->ledbit, LED_MAX); if (test_bit(EV_SND, dev->evbit)) INPUT_ADD_HOTPLUG_BM_VAR("SND=", dev->sndbit, SND_MAX); if (test_bit(EV_FF, dev->evbit)) INPUT_ADD_HOTPLUG_BM_VAR("FF=", dev->ffbit, FF_MAX); if (test_bit(EV_SW, dev->evbit)) INPUT_ADD_HOTPLUG_BM_VAR("SW=", dev->swbit, SW_MAX); INPUT_ADD_HOTPLUG_MODALIAS_VAR(dev); return 0; } #define INPUT_DO_TOGGLE(dev, type, bits, on) \ do { \ int i; \ bool active; \ \ if (!test_bit(EV_##type, dev->evbit)) \ break; \ \ for_each_set_bit(i, dev->bits##bit, type##_CNT) { \ active = test_bit(i, dev->bits); \ if (!active && !on) \ continue; \ \ dev->event(dev, EV_##type, i, on ? active : 0); \ } \ } while (0) static void input_dev_toggle(struct input_dev *dev, bool activate) { if (!dev->event) return; INPUT_DO_TOGGLE(dev, LED, led, activate); INPUT_DO_TOGGLE(dev, SND, snd, activate); if (activate && test_bit(EV_REP, dev->evbit)) { dev->event(dev, EV_REP, REP_PERIOD, dev->rep[REP_PERIOD]); dev->event(dev, EV_REP, REP_DELAY, dev->rep[REP_DELAY]); } } /** * input_reset_device() - reset/restore the state of input device * @dev: input device whose state needs to be reset * * This function tries to reset the state of an opened input device and * bring internal state and state if the hardware in sync with each other. * We mark all keys as released, restore LED state, repeat rate, etc. */ void input_reset_device(struct input_dev *dev) { unsigned long flags; mutex_lock(&dev->mutex); spin_lock_irqsave(&dev->event_lock, flags); input_dev_toggle(dev, true); input_dev_release_keys(dev); spin_unlock_irqrestore(&dev->event_lock, flags); mutex_unlock(&dev->mutex); } EXPORT_SYMBOL(input_reset_device); #ifdef CONFIG_PM_SLEEP static int input_dev_suspend(struct device *dev) { struct input_dev *input_dev = to_input_dev(dev); spin_lock_irq(&input_dev->event_lock); /* * Keys that are pressed now are unlikely to be * still pressed when we resume. */ input_dev_release_keys(input_dev); /* Turn off LEDs and sounds, if any are active. */ input_dev_toggle(input_dev, false); spin_unlock_irq(&input_dev->event_lock); return 0; } static int input_dev_resume(struct device *dev) { struct input_dev *input_dev = to_input_dev(dev); spin_lock_irq(&input_dev->event_lock); /* Restore state of LEDs and sounds, if any were active. */ input_dev_toggle(input_dev, true); spin_unlock_irq(&input_dev->event_lock); return 0; } static int input_dev_freeze(struct device *dev) { struct input_dev *input_dev = to_input_dev(dev); spin_lock_irq(&input_dev->event_lock); /* * Keys that are pressed now are unlikely to be * still pressed when we resume. */ input_dev_release_keys(input_dev); spin_unlock_irq(&input_dev->event_lock); return 0; } static int input_dev_poweroff(struct device *dev) { struct input_dev *input_dev = to_input_dev(dev); spin_lock_irq(&input_dev->event_lock); /* Turn off LEDs and sounds, if any are active. */ input_dev_toggle(input_dev, false); spin_unlock_irq(&input_dev->event_lock); return 0; } static const struct dev_pm_ops input_dev_pm_ops = { .suspend = input_dev_suspend, .resume = input_dev_resume, .freeze = input_dev_freeze, .poweroff = input_dev_poweroff, .restore = input_dev_resume, }; #endif /* CONFIG_PM */ static const struct device_type input_dev_type = { .groups = input_dev_attr_groups, .release = input_dev_release, .uevent = input_dev_uevent, #ifdef CONFIG_PM_SLEEP .pm = &input_dev_pm_ops, #endif }; static char *input_devnode(struct device *dev, umode_t *mode) { return kasprintf(GFP_KERNEL, "input/%s", dev_name(dev)); } struct class input_class = { .name = "input", .devnode = input_devnode, }; EXPORT_SYMBOL_GPL(input_class); /** * input_allocate_device - allocate memory for new input device * * Returns prepared struct input_dev or %NULL. * * NOTE: Use input_free_device() to free devices that have not been * registered; input_unregister_device() should be used for already * registered devices. */ struct input_dev *input_allocate_device(void) { static atomic_t input_no = ATOMIC_INIT(-1); struct input_dev *dev; dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (dev) { dev->dev.type = &input_dev_type; dev->dev.class = &input_class; device_initialize(&dev->dev); mutex_init(&dev->mutex); spin_lock_init(&dev->event_lock); timer_setup(&dev->timer, NULL, 0); INIT_LIST_HEAD(&dev->h_list); INIT_LIST_HEAD(&dev->node); dev_set_name(&dev->dev, "input%lu", (unsigned long)atomic_inc_return(&input_no)); __module_get(THIS_MODULE); } return dev; } EXPORT_SYMBOL(input_allocate_device); struct input_devres { struct input_dev *input; }; static int devm_input_device_match(struct device *dev, void *res, void *data) { struct input_devres *devres = res; return devres->input == data; } static void devm_input_device_release(struct device *dev, void *res) { struct input_devres *devres = res; struct input_dev *input = devres->input; dev_dbg(dev, "%s: dropping reference to %s\n", __func__, dev_name(&input->dev)); input_put_device(input); } /** * devm_input_allocate_device - allocate managed input device * @dev: device owning the input device being created * * Returns prepared struct input_dev or %NULL. * * Managed input devices do not need to be explicitly unregistered or * freed as it will be done automatically when owner device unbinds from * its driver (or binding fails). Once managed input device is allocated, * it is ready to be set up and registered in the same fashion as regular * input device. There are no special devm_input_device_[un]register() * variants, regular ones work with both managed and unmanaged devices, * should you need them. In most cases however, managed input device need * not be explicitly unregistered or freed. * * NOTE: the owner device is set up as parent of input device and users * should not override it. */ struct input_dev *devm_input_allocate_device(struct device *dev) { struct input_dev *input; struct input_devres *devres; devres = devres_alloc(devm_input_device_release, sizeof(*devres), GFP_KERNEL); if (!devres) return NULL; input = input_allocate_device(); if (!input) { devres_free(devres); return NULL; } input->dev.parent = dev; input->devres_managed = true; devres->input = input; devres_add(dev, devres); return input; } EXPORT_SYMBOL(devm_input_allocate_device); /** * input_free_device - free memory occupied by input_dev structure * @dev: input device to free * * This function should only be used if input_register_device() * was not called yet or if it failed. Once device was registered * use input_unregister_device() and memory will be freed once last * reference to the device is dropped. * * Device should be allocated by input_allocate_device(). * * NOTE: If there are references to the input device then memory * will not be freed until last reference is dropped. */ void input_free_device(struct input_dev *dev) { if (dev) { if (dev->devres_managed) WARN_ON(devres_destroy(dev->dev.parent, devm_input_device_release, devm_input_device_match, dev)); input_put_device(dev); } } EXPORT_SYMBOL(input_free_device); /** * input_set_timestamp - set timestamp for input events * @dev: input device to set timestamp for * @timestamp: the time at which the event has occurred * in CLOCK_MONOTONIC * * This function is intended to provide to the input system a more * accurate time of when an event actually occurred. The driver should * call this function as soon as a timestamp is acquired ensuring * clock conversions in input_set_timestamp are done correctly. * * The system entering suspend state between timestamp acquisition and * calling input_set_timestamp can result in inaccurate conversions. */ void input_set_timestamp(struct input_dev *dev, ktime_t timestamp) { dev->timestamp[INPUT_CLK_MONO] = timestamp; dev->timestamp[INPUT_CLK_REAL] = ktime_mono_to_real(timestamp); dev->timestamp[INPUT_CLK_BOOT] = ktime_mono_to_any(timestamp, TK_OFFS_BOOT); } EXPORT_SYMBOL(input_set_timestamp); /** * input_get_timestamp - get timestamp for input events * @dev: input device to get timestamp from * * A valid timestamp is a timestamp of non-zero value. */ ktime_t *input_get_timestamp(struct input_dev *dev) { const ktime_t invalid_timestamp = ktime_set(0, 0); if (!ktime_compare(dev->timestamp[INPUT_CLK_MONO], invalid_timestamp)) input_set_timestamp(dev, ktime_get()); return dev->timestamp; } EXPORT_SYMBOL(input_get_timestamp); /** * input_set_capability - mark device as capable of a certain event * @dev: device that is capable of emitting or accepting event * @type: type of the event (EV_KEY, EV_REL, etc...) * @code: event code * * In addition to setting up corresponding bit in appropriate capability * bitmap the function also adjusts dev->evbit. */ void input_set_capability(struct input_dev *dev, unsigned int type, unsigned int code) { switch (type) { case EV_KEY: __set_bit(code, dev->keybit); break; case EV_REL: __set_bit(code, dev->relbit); break; case EV_ABS: input_alloc_absinfo(dev); if (!dev->absinfo) return; __set_bit(code, dev->absbit); break; case EV_MSC: __set_bit(code, dev->mscbit); break; case EV_SW: __set_bit(code, dev->swbit); break; case EV_LED: __set_bit(code, dev->ledbit); break; case EV_SND: __set_bit(code, dev->sndbit); break; case EV_FF: __set_bit(code, dev->ffbit); break; case EV_PWR: /* do nothing */ break; default: pr_err("%s: unknown type %u (code %u)\n", __func__, type, code); dump_stack(); return; } __set_bit(type, dev->evbit); } EXPORT_SYMBOL(input_set_capability); static unsigned int input_estimate_events_per_packet(struct input_dev *dev) { int mt_slots; int i; unsigned int events; if (dev->mt) { mt_slots = dev->mt->num_slots; } else if (test_bit(ABS_MT_TRACKING_ID, dev->absbit)) { mt_slots = dev->absinfo[ABS_MT_TRACKING_ID].maximum - dev->absinfo[ABS_MT_TRACKING_ID].minimum + 1, mt_slots = clamp(mt_slots, 2, 32); } else if (test_bit(ABS_MT_POSITION_X, dev->absbit)) { mt_slots = 2; } else { mt_slots = 0; } events = mt_slots + 1; /* count SYN_MT_REPORT and SYN_REPORT */ if (test_bit(EV_ABS, dev->evbit)) for_each_set_bit(i, dev->absbit, ABS_CNT) events += input_is_mt_axis(i) ? mt_slots : 1; if (test_bit(EV_REL, dev->evbit)) events += bitmap_weight(dev->relbit, REL_CNT); /* Make room for KEY and MSC events */ events += 7; return events; } #define INPUT_CLEANSE_BITMASK(dev, type, bits) \ do { \ if (!test_bit(EV_##type, dev->evbit)) \ memset(dev->bits##bit, 0, \ sizeof(dev->bits##bit)); \ } while (0) static void input_cleanse_bitmasks(struct input_dev *dev) { INPUT_CLEANSE_BITMASK(dev, KEY, key); INPUT_CLEANSE_BITMASK(dev, REL, rel); INPUT_CLEANSE_BITMASK(dev, ABS, abs); INPUT_CLEANSE_BITMASK(dev, MSC, msc); INPUT_CLEANSE_BITMASK(dev, LED, led); INPUT_CLEANSE_BITMASK(dev, SND, snd); INPUT_CLEANSE_BITMASK(dev, FF, ff); INPUT_CLEANSE_BITMASK(dev, SW, sw); } static void __input_unregister_device(struct input_dev *dev) { struct input_handle *handle, *next; input_disconnect_device(dev); mutex_lock(&input_mutex); list_for_each_entry_safe(handle, next, &dev->h_list, d_node) handle->handler->disconnect(handle); WARN_ON(!list_empty(&dev->h_list)); del_timer_sync(&dev->timer); list_del_init(&dev->node); input_wakeup_procfs_readers(); mutex_unlock(&input_mutex); device_del(&dev->dev); } static void devm_input_device_unregister(struct device *dev, void *res) { struct input_devres *devres = res; struct input_dev *input = devres->input; dev_dbg(dev, "%s: unregistering device %s\n", __func__, dev_name(&input->dev)); __input_unregister_device(input); } /** * input_enable_softrepeat - enable software autorepeat * @dev: input device * @delay: repeat delay * @period: repeat period * * Enable software autorepeat on the input device. */ void input_enable_softrepeat(struct input_dev *dev, int delay, int period) { dev->timer.function = input_repeat_key; dev->rep[REP_DELAY] = delay; dev->rep[REP_PERIOD] = period; } EXPORT_SYMBOL(input_enable_softrepeat); /** * input_register_device - register device with input core * @dev: device to be registered * * This function registers device with input core. The device must be * allocated with input_allocate_device() and all it's capabilities * set up before registering. * If function fails the device must be freed with input_free_device(). * Once device has been successfully registered it can be unregistered * with input_unregister_device(); input_free_device() should not be * called in this case. * * Note that this function is also used to register managed input devices * (ones allocated with devm_input_allocate_device()). Such managed input * devices need not be explicitly unregistered or freed, their tear down * is controlled by the devres infrastructure. It is also worth noting * that tear down of managed input devices is internally a 2-step process: * registered managed input device is first unregistered, but stays in * memory and can still handle input_event() calls (although events will * not be delivered anywhere). The freeing of managed input device will * happen later, when devres stack is unwound to the point where device * allocation was made. */ int input_register_device(struct input_dev *dev) { struct input_devres *devres = NULL; struct input_handler *handler; unsigned int packet_size; const char *path; int error; if (test_bit(EV_ABS, dev->evbit) && !dev->absinfo) { dev_err(&dev->dev, "Absolute device without dev->absinfo, refusing to register\n"); return -EINVAL; } if (dev->devres_managed) { devres = devres_alloc(devm_input_device_unregister, sizeof(*devres), GFP_KERNEL); if (!devres) return -ENOMEM; devres->input = dev; } /* Every input device generates EV_SYN/SYN_REPORT events. */ __set_bit(EV_SYN, dev->evbit); /* KEY_RESERVED is not supposed to be transmitted to userspace. */ __clear_bit(KEY_RESERVED, dev->keybit); /* Make sure that bitmasks not mentioned in dev->evbit are clean. */ input_cleanse_bitmasks(dev); packet_size = input_estimate_events_per_packet(dev); if (dev->hint_events_per_packet < packet_size) dev->hint_events_per_packet = packet_size; dev->max_vals = dev->hint_events_per_packet + 2; dev->vals = kcalloc(dev->max_vals, sizeof(*dev->vals), GFP_KERNEL); if (!dev->vals) { error = -ENOMEM; goto err_devres_free; } /* * If delay and period are pre-set by the driver, then autorepeating * is handled by the driver itself and we don't do it in input.c. */ if (!dev->rep[REP_DELAY] && !dev->rep[REP_PERIOD]) input_enable_softrepeat(dev, 250, 33); if (!dev->getkeycode) dev->getkeycode = input_default_getkeycode; if (!dev->setkeycode) dev->setkeycode = input_default_setkeycode; if (dev->poller) input_dev_poller_finalize(dev->poller); error = device_add(&dev->dev); if (error) goto err_free_vals; path = kobject_get_path(&dev->dev.kobj, GFP_KERNEL); pr_info("%s as %s\n", dev->name ? dev->name : "Unspecified device", path ? path : "N/A"); kfree(path); error = mutex_lock_interruptible(&input_mutex); if (error) goto err_device_del; list_add_tail(&dev->node, &input_dev_list); list_for_each_entry(handler, &input_handler_list, node) input_attach_handler(dev, handler); input_wakeup_procfs_readers(); mutex_unlock(&input_mutex); if (dev->devres_managed) { dev_dbg(dev->dev.parent, "%s: registering %s with devres.\n", __func__, dev_name(&dev->dev)); devres_add(dev->dev.parent, devres); } return 0; err_device_del: device_del(&dev->dev); err_free_vals: kfree(dev->vals); dev->vals = NULL; err_devres_free: devres_free(devres); return error; } EXPORT_SYMBOL(input_register_device); /** * input_unregister_device - unregister previously registered device * @dev: device to be unregistered * * This function unregisters an input device. Once device is unregistered * the caller should not try to access it as it may get freed at any moment. */ void input_unregister_device(struct input_dev *dev) { if (dev->devres_managed) { WARN_ON(devres_destroy(dev->dev.parent, devm_input_device_unregister, devm_input_device_match, dev)); __input_unregister_device(dev); /* * We do not do input_put_device() here because it will be done * when 2nd devres fires up. */ } else { __input_unregister_device(dev); input_put_device(dev); } } EXPORT_SYMBOL(input_unregister_device); /** * input_register_handler - register a new input handler * @handler: handler to be registered * * This function registers a new input handler (interface) for input * devices in the system and attaches it to all input devices that * are compatible with the handler. */ int input_register_handler(struct input_handler *handler) { struct input_dev *dev; int error; error = mutex_lock_interruptible(&input_mutex); if (error) return error; INIT_LIST_HEAD(&handler->h_list); list_add_tail(&handler->node, &input_handler_list); list_for_each_entry(dev, &input_dev_list, node) input_attach_handler(dev, handler); input_wakeup_procfs_readers(); mutex_unlock(&input_mutex); return 0; } EXPORT_SYMBOL(input_register_handler); /** * input_unregister_handler - unregisters an input handler * @handler: handler to be unregistered * * This function disconnects a handler from its input devices and * removes it from lists of known handlers. */ void input_unregister_handler(struct input_handler *handler) { struct input_handle *handle, *next; mutex_lock(&input_mutex); list_for_each_entry_safe(handle, next, &handler->h_list, h_node) handler->disconnect(handle); WARN_ON(!list_empty(&handler->h_list)); list_del_init(&handler->node); input_wakeup_procfs_readers(); mutex_unlock(&input_mutex); } EXPORT_SYMBOL(input_unregister_handler); /** * input_handler_for_each_handle - handle iterator * @handler: input handler to iterate * @data: data for the callback * @fn: function to be called for each handle * * Iterate over @bus's list of devices, and call @fn for each, passing * it @data and stop when @fn returns a non-zero value. The function is * using RCU to traverse the list and therefore may be using in atomic * contexts. The @fn callback is invoked from RCU critical section and * thus must not sleep. */ int input_handler_for_each_handle(struct input_handler *handler, void *data, int (*fn)(struct input_handle *, void *)) { struct input_handle *handle; int retval = 0; rcu_read_lock(); list_for_each_entry_rcu(handle, &handler->h_list, h_node) { retval = fn(handle, data); if (retval) break; } rcu_read_unlock(); return retval; } EXPORT_SYMBOL(input_handler_for_each_handle); /** * input_register_handle - register a new input handle * @handle: handle to register * * This function puts a new input handle onto device's * and handler's lists so that events can flow through * it once it is opened using input_open_device(). * * This function is supposed to be called from handler's * connect() method. */ int input_register_handle(struct input_handle *handle) { struct input_handler *handler = handle->handler; struct input_dev *dev = handle->dev; int error; /* * We take dev->mutex here to prevent race with * input_release_device(). */ error = mutex_lock_interruptible(&dev->mutex); if (error) return error; /* * Filters go to the head of the list, normal handlers * to the tail. */ if (handler->filter) list_add_rcu(&handle->d_node, &dev->h_list); else list_add_tail_rcu(&handle->d_node, &dev->h_list); mutex_unlock(&dev->mutex); /* * Since we are supposed to be called from ->connect() * which is mutually exclusive with ->disconnect() * we can't be racing with input_unregister_handle() * and so separate lock is not needed here. */ list_add_tail_rcu(&handle->h_node, &handler->h_list); if (handler->start) handler->start(handle); return 0; } EXPORT_SYMBOL(input_register_handle); /** * input_unregister_handle - unregister an input handle * @handle: handle to unregister * * This function removes input handle from device's * and handler's lists. * * This function is supposed to be called from handler's * disconnect() method. */ void input_unregister_handle(struct input_handle *handle) { struct input_dev *dev = handle->dev; list_del_rcu(&handle->h_node); /* * Take dev->mutex to prevent race with input_release_device(). */ mutex_lock(&dev->mutex); list_del_rcu(&handle->d_node); mutex_unlock(&dev->mutex); synchronize_rcu(); } EXPORT_SYMBOL(input_unregister_handle); /** * input_get_new_minor - allocates a new input minor number * @legacy_base: beginning or the legacy range to be searched * @legacy_num: size of legacy range * @allow_dynamic: whether we can also take ID from the dynamic range * * This function allocates a new device minor for from input major namespace. * Caller can request legacy minor by specifying @legacy_base and @legacy_num * parameters and whether ID can be allocated from dynamic range if there are * no free IDs in legacy range. */ int input_get_new_minor(int legacy_base, unsigned int legacy_num, bool allow_dynamic) { /* * This function should be called from input handler's ->connect() * methods, which are serialized with input_mutex, so no additional * locking is needed here. */ if (legacy_base >= 0) { int minor = ida_simple_get(&input_ida, legacy_base, legacy_base + legacy_num, GFP_KERNEL); if (minor >= 0 || !allow_dynamic) return minor; } return ida_simple_get(&input_ida, INPUT_FIRST_DYNAMIC_DEV, INPUT_MAX_CHAR_DEVICES, GFP_KERNEL); } EXPORT_SYMBOL(input_get_new_minor); /** * input_free_minor - release previously allocated minor * @minor: minor to be released * * This function releases previously allocated input minor so that it can be * reused later. */ void input_free_minor(unsigned int minor) { ida_simple_remove(&input_ida, minor); } EXPORT_SYMBOL(input_free_minor); static int __init input_init(void) { int err; err = class_register(&input_class); if (err) { pr_err("unable to register input_dev class\n"); return err; } err = input_proc_init(); if (err) goto fail1; err = register_chrdev_region(MKDEV(INPUT_MAJOR, 0), INPUT_MAX_CHAR_DEVICES, "input"); if (err) { pr_err("unable to register char major %d", INPUT_MAJOR); goto fail2; } return 0; fail2: input_proc_exit(); fail1: class_unregister(&input_class); return err; } static void __exit input_exit(void) { input_proc_exit(); unregister_chrdev_region(MKDEV(INPUT_MAJOR, 0), INPUT_MAX_CHAR_DEVICES); class_unregister(&input_class); } subsys_initcall(input_init); module_exit(input_exit);
null
// SPDX-License-Identifier: GPL-2.0-only /* * The input core * * Copyright (c) 1999-2002 Vojtech Pavlik */ #define pr_fmt(fmt) KBUILD_BASENAME ": " fmt #include <linux/init.h> #include <linux/types.h> #include <linux/idr.h> #include <linux/input/mt.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/random.h> #include <linux/major.h> #include <linux/proc_fs.h> #include <linux/sched.h> #include <linux/seq_file.h> #include <linux/poll.h> #include <linux/device.h> #include <linux/mutex.h> #include <linux/rcupdate.h> #include "input-compat.h" #include "input-poller.h" MODULE_AUTHOR("Vojtech Pavlik <vojtech@suse.cz>"); MODULE_DESCRIPTION("Input core"); MODULE_LICENSE("GPL"); #define INPUT_MAX_CHAR_DEVICES 1024 #define INPUT_FIRST_DYNAMIC_DEV 256 static DEFINE_IDA(input_ida); static LIST_HEAD(input_dev_list); static LIST_HEAD(input_handler_list); /* * input_mutex protects access to both input_dev_list and input_handler_list. * This also causes input_[un]register_device and input_[un]register_handler * be mutually exclusive which simplifies locking in drivers implementing * input handlers. */ static DEFINE_MUTEX(input_mutex); static const struct input_value input_value_sync = { EV_SYN, SYN_REPORT, 1 }; static inline int is_event_supported(unsigned int code, unsigned long *bm, unsigned int max) { return code <= max && test_bit(code, bm); } static int input_defuzz_abs_event(int value, int old_val, int fuzz) { if (fuzz) { if (value > old_val - fuzz / 2 && value < old_val + fuzz / 2) return old_val; if (value > old_val - fuzz && value < old_val + fuzz) return (old_val * 3 + value) / 4; if (value > old_val - fuzz * 2 && value < old_val + fuzz * 2) return (old_val + value) / 2; } return value; } static void input_start_autorepeat(struct input_dev *dev, int code) { if (test_bit(EV_REP, dev->evbit) && dev->rep[REP_PERIOD] && dev->rep[REP_DELAY] && dev->timer.function) { dev->repeat_key = code; mod_timer(&dev->timer, jiffies + msecs_to_jiffies(dev->rep[REP_DELAY])); } } static void input_stop_autorepeat(struct input_dev *dev) { del_timer(&dev->timer); } /* * Pass event first through all filters and then, if event has not been * filtered out, through all open handles. This function is called with * dev->event_lock held and interrupts disabled. */ static unsigned int input_to_handler(struct input_handle *handle, struct input_value *vals, unsigned int count) { struct input_handler *handler = handle->handler; struct input_value *end = vals; struct input_value *v; if (handler->filter) { for (v = vals; v != vals + count; v++) { if (handler->filter(handle, v->type, v->code, v->value)) continue; if (end != v) *end = *v; end++; } count = end - vals; } if (!count) return 0; if (handler->events) handler->events(handle, vals, count); else if (handler->event) for (v = vals; v != vals + count; v++) handler->event(handle, v->type, v->code, v->value); return count; } /* * Pass values first through all filters and then, if event has not been * filtered out, through all open handles. This function is called with * dev->event_lock held and interrupts disabled. */ static void input_pass_values(struct input_dev *dev, struct input_value *vals, unsigned int count) { struct input_handle *handle; struct input_value *v; if (!count) return; rcu_read_lock(); handle = rcu_dereference(dev->grab); if (handle) { count = input_to_handler(handle, vals, count); } else { list_for_each_entry_rcu(handle, &dev->h_list, d_node) if (handle->open) { count = input_to_handler(handle, vals, count); if (!count) break; } } rcu_read_unlock(); /* trigger auto repeat for key events */ if (test_bit(EV_REP, dev->evbit) && test_bit(EV_KEY, dev->evbit)) { for (v = vals; v != vals + count; v++) { if (v->type == EV_KEY && v->value != 2) { if (v->value) input_start_autorepeat(dev, v->code); else input_stop_autorepeat(dev); } } } } static void input_pass_event(struct input_dev *dev, unsigned int type, unsigned int code, int value) { struct input_value vals[] = { { type, code, value } }; input_pass_values(dev, vals, ARRAY_SIZE(vals)); } /* * Generate software autorepeat event. Note that we take * dev->event_lock here to avoid racing with input_event * which may cause keys get "stuck". */ static void input_repeat_key(struct timer_list *t) { struct input_dev *dev = from_timer(dev, t, timer); unsigned long flags; spin_lock_irqsave(&dev->event_lock, flags); if (test_bit(dev->repeat_key, dev->key) && is_event_supported(dev->repeat_key, dev->keybit, KEY_MAX)) { struct input_value vals[] = { { EV_KEY, dev->repeat_key, 2 }, input_value_sync }; input_pass_values(dev, vals, ARRAY_SIZE(vals)); if (dev->rep[REP_PERIOD]) mod_timer(&dev->timer, jiffies + msecs_to_jiffies(dev->rep[REP_PERIOD])); } spin_unlock_irqrestore(&dev->event_lock, flags); } #define INPUT_IGNORE_EVENT 0 #define INPUT_PASS_TO_HANDLERS 1 #define INPUT_PASS_TO_DEVICE 2 #define INPUT_SLOT 4 #define INPUT_FLUSH 8 #define INPUT_PASS_TO_ALL (INPUT_PASS_TO_HANDLERS | INPUT_PASS_TO_DEVICE) static int input_handle_abs_event(struct input_dev *dev, unsigned int code, int *pval) { struct input_mt *mt = dev->mt; bool is_mt_event; int *pold; if (code == ABS_MT_SLOT) { /* * "Stage" the event; we'll flush it later, when we * get actual touch data. */ if (mt && *pval >= 0 && *pval < mt->num_slots) mt->slot = *pval; return INPUT_IGNORE_EVENT; } is_mt_event = input_is_mt_value(code); if (!is_mt_event) { pold = &dev->absinfo[code].value; } else if (mt) { pold = &mt->slots[mt->slot].abs[code - ABS_MT_FIRST]; } else { /* * Bypass filtering for multi-touch events when * not employing slots. */ pold = NULL; } if (pold) { *pval = input_defuzz_abs_event(*pval, *pold, dev->absinfo[code].fuzz); if (*pold == *pval) return INPUT_IGNORE_EVENT; *pold = *pval; } /* Flush pending "slot" event */ if (is_mt_event && mt && mt->slot != input_abs_get_val(dev, ABS_MT_SLOT)) { input_abs_set_val(dev, ABS_MT_SLOT, mt->slot); return INPUT_PASS_TO_HANDLERS | INPUT_SLOT; } return INPUT_PASS_TO_HANDLERS; } static int input_get_disposition(struct input_dev *dev, unsigned int type, unsigned int code, int *pval) { int disposition = INPUT_IGNORE_EVENT; int value = *pval; switch (type) { case EV_SYN: switch (code) { case SYN_CONFIG: disposition = INPUT_PASS_TO_ALL; break; case SYN_REPORT: disposition = INPUT_PASS_TO_HANDLERS | INPUT_FLUSH; break; case SYN_MT_REPORT: disposition = INPUT_PASS_TO_HANDLERS; break; } break; case EV_KEY: if (is_event_supported(code, dev->keybit, KEY_MAX)) { /* auto-repeat bypasses state updates */ if (value == 2) { disposition = INPUT_PASS_TO_HANDLERS; break; } if (!!test_bit(code, dev->key) != !!value) { __change_bit(code, dev->key); disposition = INPUT_PASS_TO_HANDLERS; } } break; case EV_SW: if (is_event_supported(code, dev->swbit, SW_MAX) && !!test_bit(code, dev->sw) != !!value) { __change_bit(code, dev->sw); disposition = INPUT_PASS_TO_HANDLERS; } break; case EV_ABS: if (is_event_supported(code, dev->absbit, ABS_MAX)) disposition = input_handle_abs_event(dev, code, &value); break; case EV_REL: if (is_event_supported(code, dev->relbit, REL_MAX) && value) disposition = INPUT_PASS_TO_HANDLERS; break; case EV_MSC: if (is_event_supported(code, dev->mscbit, MSC_MAX)) disposition = INPUT_PASS_TO_ALL; break; case EV_LED: if (is_event_supported(code, dev->ledbit, LED_MAX) && !!test_bit(code, dev->led) != !!value) { __change_bit(code, dev->led); disposition = INPUT_PASS_TO_ALL; } break; case EV_SND: if (is_event_supported(code, dev->sndbit, SND_MAX)) { if (!!test_bit(code, dev->snd) != !!value) __change_bit(code, dev->snd); disposition = INPUT_PASS_TO_ALL; } break; case EV_REP: if (code <= REP_MAX && value >= 0 && dev->rep[code] != value) { dev->rep[code] = value; disposition = INPUT_PASS_TO_ALL; } break; case EV_FF: if (value >= 0) disposition = INPUT_PASS_TO_ALL; break; case EV_PWR: disposition = INPUT_PASS_TO_ALL; break; } *pval = value; return disposition; } static void input_handle_event(struct input_dev *dev, unsigned int type, unsigned int code, int value) { int disposition = input_get_disposition(dev, type, code, &value); if (disposition != INPUT_IGNORE_EVENT && type != EV_SYN) add_input_randomness(type, code, value); if ((disposition & INPUT_PASS_TO_DEVICE) && dev->event) dev->event(dev, type, code, value); if (!dev->vals) return; if (disposition & INPUT_PASS_TO_HANDLERS) { struct input_value *v; if (disposition & INPUT_SLOT) { v = &dev->vals[dev->num_vals++]; v->type = EV_ABS; v->code = ABS_MT_SLOT; v->value = dev->mt->slot; } v = &dev->vals[dev->num_vals++]; v->type = type; v->code = code; v->value = value; } if (disposition & INPUT_FLUSH) { if (dev->num_vals >= 2) input_pass_values(dev, dev->vals, dev->num_vals); dev->num_vals = 0; /* * Reset the timestamp on flush so we won't end up * with a stale one. Note we only need to reset the * monolithic one as we use its presence when deciding * whether to generate a synthetic timestamp. */ dev->timestamp[INPUT_CLK_MONO] = ktime_set(0, 0); } else if (dev->num_vals >= dev->max_vals - 2) { dev->vals[dev->num_vals++] = input_value_sync; input_pass_values(dev, dev->vals, dev->num_vals); dev->num_vals = 0; } } /** * input_event() - report new input event * @dev: device that generated the event * @type: type of the event * @code: event code * @value: value of the event * * This function should be used by drivers implementing various input * devices to report input events. See also input_inject_event(). * * NOTE: input_event() may be safely used right after input device was * allocated with input_allocate_device(), even before it is registered * with input_register_device(), but the event will not reach any of the * input handlers. Such early invocation of input_event() may be used * to 'seed' initial state of a switch or initial position of absolute * axis, etc. */ void input_event(struct input_dev *dev, unsigned int type, unsigned int code, int value) { unsigned long flags; if (is_event_supported(type, dev->evbit, EV_MAX)) { spin_lock_irqsave(&dev->event_lock, flags); input_handle_event(dev, type, code, value); spin_unlock_irqrestore(&dev->event_lock, flags); } } EXPORT_SYMBOL(input_event); /** * input_inject_event() - send input event from input handler * @handle: input handle to send event through * @type: type of the event * @code: event code * @value: value of the event * * Similar to input_event() but will ignore event if device is * "grabbed" and handle injecting event is not the one that owns * the device. */ void input_inject_event(struct input_handle *handle, unsigned int type, unsigned int code, int value) { struct input_dev *dev = handle->dev; struct input_handle *grab; unsigned long flags; if (is_event_supported(type, dev->evbit, EV_MAX)) { spin_lock_irqsave(&dev->event_lock, flags); rcu_read_lock(); grab = rcu_dereference(dev->grab); if (!grab || grab == handle) input_handle_event(dev, type, code, value); rcu_read_unlock(); spin_unlock_irqrestore(&dev->event_lock, flags); } } EXPORT_SYMBOL(input_inject_event); /** * input_alloc_absinfo - allocates array of input_absinfo structs * @dev: the input device emitting absolute events * * If the absinfo struct the caller asked for is already allocated, this * functions will not do anything. */ void input_alloc_absinfo(struct input_dev *dev) { if (dev->absinfo) return; dev->absinfo = kcalloc(ABS_CNT, sizeof(*dev->absinfo), GFP_KERNEL); if (!dev->absinfo) { dev_err(dev->dev.parent ?: &dev->dev, "%s: unable to allocate memory\n", __func__); /* * We will handle this allocation failure in * input_register_device() when we refuse to register input * device with ABS bits but without absinfo. */ } } EXPORT_SYMBOL(input_alloc_absinfo); void input_set_abs_params(struct input_dev *dev, unsigned int axis, int min, int max, int fuzz, int flat) { struct input_absinfo *absinfo; input_alloc_absinfo(dev); if (!dev->absinfo) return; absinfo = &dev->absinfo[axis]; absinfo->minimum = min; absinfo->maximum = max; absinfo->fuzz = fuzz; absinfo->flat = flat; __set_bit(EV_ABS, dev->evbit); __set_bit(axis, dev->absbit); } EXPORT_SYMBOL(input_set_abs_params); /** * input_grab_device - grabs device for exclusive use * @handle: input handle that wants to own the device * * When a device is grabbed by an input handle all events generated by * the device are delivered only to this handle. Also events injected * by other input handles are ignored while device is grabbed. */ int input_grab_device(struct input_handle *handle) { struct input_dev *dev = handle->dev; int retval; retval = mutex_lock_interruptible(&dev->mutex); if (retval) return retval; if (dev->grab) { retval = -EBUSY; goto out; } rcu_assign_pointer(dev->grab, handle); out: mutex_unlock(&dev->mutex); return retval; } EXPORT_SYMBOL(input_grab_device); static void __input_release_device(struct input_handle *handle) { struct input_dev *dev = handle->dev; struct input_handle *grabber; grabber = rcu_dereference_protected(dev->grab, lockdep_is_held(&dev->mutex)); if (grabber == handle) { rcu_assign_pointer(dev->grab, NULL); /* Make sure input_pass_event() notices that grab is gone */ synchronize_rcu(); list_for_each_entry(handle, &dev->h_list, d_node) if (handle->open && handle->handler->start) handle->handler->start(handle); } } /** * input_release_device - release previously grabbed device * @handle: input handle that owns the device * * Releases previously grabbed device so that other input handles can * start receiving input events. Upon release all handlers attached * to the device have their start() method called so they have a change * to synchronize device state with the rest of the system. */ void input_release_device(struct input_handle *handle) { struct input_dev *dev = handle->dev; mutex_lock(&dev->mutex); __input_release_device(handle); mutex_unlock(&dev->mutex); } EXPORT_SYMBOL(input_release_device); /** * input_open_device - open input device * @handle: handle through which device is being accessed * * This function should be called by input handlers when they * want to start receive events from given input device. */ int input_open_device(struct input_handle *handle) { struct input_dev *dev = handle->dev; int retval; retval = mutex_lock_interruptible(&dev->mutex); if (retval) return retval; if (dev->going_away) { retval = -ENODEV; goto out; } handle->open++; if (dev->users++) { /* * Device is already opened, so we can exit immediately and * report success. */ goto out; } if (dev->open) { retval = dev->open(dev); if (retval) { dev->users--; handle->open--; /* * Make sure we are not delivering any more events * through this handle */ synchronize_rcu(); goto out; } } if (dev->poller) input_dev_poller_start(dev->poller); out: mutex_unlock(&dev->mutex); return retval; } EXPORT_SYMBOL(input_open_device); int input_flush_device(struct input_handle *handle, struct file *file) { struct input_dev *dev = handle->dev; int retval; retval = mutex_lock_interruptible(&dev->mutex); if (retval) return retval; if (dev->flush) retval = dev->flush(dev, file); mutex_unlock(&dev->mutex); return retval; } EXPORT_SYMBOL(input_flush_device); /** * input_close_device - close input device * @handle: handle through which device is being accessed * * This function should be called by input handlers when they * want to stop receive events from given input device. */ void input_close_device(struct input_handle *handle) { struct input_dev *dev = handle->dev; mutex_lock(&dev->mutex); __input_release_device(handle); if (!--dev->users) { if (dev->poller) input_dev_poller_stop(dev->poller); if (dev->close) dev->close(dev); } if (!--handle->open) { /* * synchronize_rcu() makes sure that input_pass_event() * completed and that no more input events are delivered * through this handle */ synchronize_rcu(); } mutex_unlock(&dev->mutex); } EXPORT_SYMBOL(input_close_device); /* * Simulate keyup events for all keys that are marked as pressed. * The function must be called with dev->event_lock held. */ static void input_dev_release_keys(struct input_dev *dev) { bool need_sync = false; int code; if (is_event_supported(EV_KEY, dev->evbit, EV_MAX)) { for_each_set_bit(code, dev->key, KEY_CNT) { input_pass_event(dev, EV_KEY, code, 0); need_sync = true; } if (need_sync) input_pass_event(dev, EV_SYN, SYN_REPORT, 1); memset(dev->key, 0, sizeof(dev->key)); } } /* * Prepare device for unregistering */ static void input_disconnect_device(struct input_dev *dev) { struct input_handle *handle; /* * Mark device as going away. Note that we take dev->mutex here * not to protect access to dev->going_away but rather to ensure * that there are no threads in the middle of input_open_device() */ mutex_lock(&dev->mutex); dev->going_away = true; mutex_unlock(&dev->mutex); spin_lock_irq(&dev->event_lock); /* * Simulate keyup events for all pressed keys so that handlers * are not left with "stuck" keys. The driver may continue * generate events even after we done here but they will not * reach any handlers. */ input_dev_release_keys(dev); list_for_each_entry(handle, &dev->h_list, d_node) handle->open = 0; spin_unlock_irq(&dev->event_lock); } /** * input_scancode_to_scalar() - converts scancode in &struct input_keymap_entry * @ke: keymap entry containing scancode to be converted. * @scancode: pointer to the location where converted scancode should * be stored. * * This function is used to convert scancode stored in &struct keymap_entry * into scalar form understood by legacy keymap handling methods. These * methods expect scancodes to be represented as 'unsigned int'. */ int input_scancode_to_scalar(const struct input_keymap_entry *ke, unsigned int *scancode) { switch (ke->len) { case 1: *scancode = *((u8 *)ke->scancode); break; case 2: *scancode = *((u16 *)ke->scancode); break; case 4: *scancode = *((u32 *)ke->scancode); break; default: return -EINVAL; } return 0; } EXPORT_SYMBOL(input_scancode_to_scalar); /* * Those routines handle the default case where no [gs]etkeycode() is * defined. In this case, an array indexed by the scancode is used. */ static unsigned int input_fetch_keycode(struct input_dev *dev, unsigned int index) { switch (dev->keycodesize) { case 1: return ((u8 *)dev->keycode)[index]; case 2: return ((u16 *)dev->keycode)[index]; default: return ((u32 *)dev->keycode)[index]; } } static int input_default_getkeycode(struct input_dev *dev, struct input_keymap_entry *ke) { unsigned int index; int error; if (!dev->keycodesize) return -EINVAL; if (ke->flags & INPUT_KEYMAP_BY_INDEX) index = ke->index; else { error = input_scancode_to_scalar(ke, &index); if (error) return error; } if (index >= dev->keycodemax) return -EINVAL; ke->keycode = input_fetch_keycode(dev, index); ke->index = index; ke->len = sizeof(index); memcpy(ke->scancode, &index, sizeof(index)); return 0; } static int input_default_setkeycode(struct input_dev *dev, const struct input_keymap_entry *ke, unsigned int *old_keycode) { unsigned int index; int error; int i; if (!dev->keycodesize) return -EINVAL; if (ke->flags & INPUT_KEYMAP_BY_INDEX) { index = ke->index; } else { error = input_scancode_to_scalar(ke, &index); if (error) return error; } if (index >= dev->keycodemax) return -EINVAL; if (dev->keycodesize < sizeof(ke->keycode) && (ke->keycode >> (dev->keycodesize * 8))) return -EINVAL; switch (dev->keycodesize) { case 1: { u8 *k = (u8 *)dev->keycode; *old_keycode = k[index]; k[index] = ke->keycode; break; } case 2: { u16 *k = (u16 *)dev->keycode; *old_keycode = k[index]; k[index] = ke->keycode; break; } default: { u32 *k = (u32 *)dev->keycode; *old_keycode = k[index]; k[index] = ke->keycode; break; } } if (*old_keycode <= KEY_MAX) { __clear_bit(*old_keycode, dev->keybit); for (i = 0; i < dev->keycodemax; i++) { if (input_fetch_keycode(dev, i) == *old_keycode) { __set_bit(*old_keycode, dev->keybit); /* Setting the bit twice is useless, so break */ break; } } } __set_bit(ke->keycode, dev->keybit); return 0; } /** * input_get_keycode - retrieve keycode currently mapped to a given scancode * @dev: input device which keymap is being queried * @ke: keymap entry * * This function should be called by anyone interested in retrieving current * keymap. Presently evdev handlers use it. */ int input_get_keycode(struct input_dev *dev, struct input_keymap_entry *ke) { unsigned long flags; int retval; spin_lock_irqsave(&dev->event_lock, flags); retval = dev->getkeycode(dev, ke); spin_unlock_irqrestore(&dev->event_lock, flags); return retval; } EXPORT_SYMBOL(input_get_keycode); /** * input_set_keycode - attribute a keycode to a given scancode * @dev: input device which keymap is being updated * @ke: new keymap entry * * This function should be called by anyone needing to update current * keymap. Presently keyboard and evdev handlers use it. */ int input_set_keycode(struct input_dev *dev, const struct input_keymap_entry *ke) { unsigned long flags; unsigned int old_keycode; int retval; if (ke->keycode > KEY_MAX) return -EINVAL; spin_lock_irqsave(&dev->event_lock, flags); retval = dev->setkeycode(dev, ke, &old_keycode); if (retval) goto out; /* Make sure KEY_RESERVED did not get enabled. */ __clear_bit(KEY_RESERVED, dev->keybit); /* * Simulate keyup event if keycode is not present * in the keymap anymore */ if (old_keycode > KEY_MAX) { dev_warn(dev->dev.parent ?: &dev->dev, "%s: got too big old keycode %#x\n", __func__, old_keycode); } else if (test_bit(EV_KEY, dev->evbit) && !is_event_supported(old_keycode, dev->keybit, KEY_MAX) && __test_and_clear_bit(old_keycode, dev->key)) { struct input_value vals[] = { { EV_KEY, old_keycode, 0 }, input_value_sync }; input_pass_values(dev, vals, ARRAY_SIZE(vals)); } out: spin_unlock_irqrestore(&dev->event_lock, flags); return retval; } EXPORT_SYMBOL(input_set_keycode); bool input_match_device_id(const struct input_dev *dev, const struct input_device_id *id) { if (id->flags & INPUT_DEVICE_ID_MATCH_BUS) if (id->bustype != dev->id.bustype) return false; if (id->flags & INPUT_DEVICE_ID_MATCH_VENDOR) if (id->vendor != dev->id.vendor) return false; if (id->flags & INPUT_DEVICE_ID_MATCH_PRODUCT) if (id->product != dev->id.product) return false; if (id->flags & INPUT_DEVICE_ID_MATCH_VERSION) if (id->version != dev->id.version) return false; if (!bitmap_subset(id->evbit, dev->evbit, EV_MAX) || !bitmap_subset(id->keybit, dev->keybit, KEY_MAX) || !bitmap_subset(id->relbit, dev->relbit, REL_MAX) || !bitmap_subset(id->absbit, dev->absbit, ABS_MAX) || !bitmap_subset(id->mscbit, dev->mscbit, MSC_MAX) || !bitmap_subset(id->ledbit, dev->ledbit, LED_MAX) || !bitmap_subset(id->sndbit, dev->sndbit, SND_MAX) || !bitmap_subset(id->ffbit, dev->ffbit, FF_MAX) || !bitmap_subset(id->swbit, dev->swbit, SW_MAX) || !bitmap_subset(id->propbit, dev->propbit, INPUT_PROP_MAX)) { return false; } return true; } EXPORT_SYMBOL(input_match_device_id); static const struct input_device_id *input_match_device(struct input_handler *handler, struct input_dev *dev) { const struct input_device_id *id; for (id = handler->id_table; id->flags || id->driver_info; id++) { if (input_match_device_id(dev, id) && (!handler->match || handler->match(handler, dev))) { return id; } } return NULL; } static int input_attach_handler(struct input_dev *dev, struct input_handler *handler) { const struct input_device_id *id; int error; id = input_match_device(handler, dev); if (!id) return -ENODEV; error = handler->connect(handler, dev, id); if (error && error != -ENODEV) pr_err("failed to attach handler %s to device %s, error: %d\n", handler->name, kobject_name(&dev->dev.kobj), error); return error; } #ifdef CONFIG_COMPAT static int input_bits_to_string(char *buf, int buf_size, unsigned long bits, bool skip_empty) { int len = 0; if (in_compat_syscall()) { u32 dword = bits >> 32; if (dword || !skip_empty) len += snprintf(buf, buf_size, "%x ", dword); dword = bits & 0xffffffffUL; if (dword || !skip_empty || len) len += snprintf(buf + len, max(buf_size - len, 0), "%x", dword); } else { if (bits || !skip_empty) len += snprintf(buf, buf_size, "%lx", bits); } return len; } #else /* !CONFIG_COMPAT */ static int input_bits_to_string(char *buf, int buf_size, unsigned long bits, bool skip_empty) { return bits || !skip_empty ? snprintf(buf, buf_size, "%lx", bits) : 0; } #endif #ifdef CONFIG_PROC_FS static struct proc_dir_entry *proc_bus_input_dir; static DECLARE_WAIT_QUEUE_HEAD(input_devices_poll_wait); static int input_devices_state; static inline void input_wakeup_procfs_readers(void) { input_devices_state++; wake_up(&input_devices_poll_wait); } static __poll_t input_proc_devices_poll(struct file *file, poll_table *wait) { poll_wait(file, &input_devices_poll_wait, wait); if (file->f_version != input_devices_state) { file->f_version = input_devices_state; return EPOLLIN | EPOLLRDNORM; } return 0; } union input_seq_state { struct { unsigned short pos; bool mutex_acquired; }; void *p; }; static void *input_devices_seq_start(struct seq_file *seq, loff_t *pos) { union input_seq_state *state = (union input_seq_state *)&seq->private; int error; /* We need to fit into seq->private pointer */ BUILD_BUG_ON(sizeof(union input_seq_state) != sizeof(seq->private)); error = mutex_lock_interruptible(&input_mutex); if (error) { state->mutex_acquired = false; return ERR_PTR(error); } state->mutex_acquired = true; return seq_list_start(&input_dev_list, *pos); } static void *input_devices_seq_next(struct seq_file *seq, void *v, loff_t *pos) { return seq_list_next(v, &input_dev_list, pos); } static void input_seq_stop(struct seq_file *seq, void *v) { union input_seq_state *state = (union input_seq_state *)&seq->private; if (state->mutex_acquired) mutex_unlock(&input_mutex); } static void input_seq_print_bitmap(struct seq_file *seq, const char *name, unsigned long *bitmap, int max) { int i; bool skip_empty = true; char buf[18]; seq_printf(seq, "B: %s=", name); for (i = BITS_TO_LONGS(max) - 1; i >= 0; i--) { if (input_bits_to_string(buf, sizeof(buf), bitmap[i], skip_empty)) { skip_empty = false; seq_printf(seq, "%s%s", buf, i > 0 ? " " : ""); } } /* * If no output was produced print a single 0. */ if (skip_empty) seq_putc(seq, '0'); seq_putc(seq, '\n'); } static int input_devices_seq_show(struct seq_file *seq, void *v) { struct input_dev *dev = container_of(v, struct input_dev, node); const char *path = kobject_get_path(&dev->dev.kobj, GFP_KERNEL); struct input_handle *handle; seq_printf(seq, "I: Bus=%04x Vendor=%04x Product=%04x Version=%04x\n", dev->id.bustype, dev->id.vendor, dev->id.product, dev->id.version); seq_printf(seq, "N: Name=\"%s\"\n", dev->name ? dev->name : ""); seq_printf(seq, "P: Phys=%s\n", dev->phys ? dev->phys : ""); seq_printf(seq, "S: Sysfs=%s\n", path ? path : ""); seq_printf(seq, "U: Uniq=%s\n", dev->uniq ? dev->uniq : ""); seq_puts(seq, "H: Handlers="); list_for_each_entry(handle, &dev->h_list, d_node) seq_printf(seq, "%s ", handle->name); seq_putc(seq, '\n'); input_seq_print_bitmap(seq, "PROP", dev->propbit, INPUT_PROP_MAX); input_seq_print_bitmap(seq, "EV", dev->evbit, EV_MAX); if (test_bit(EV_KEY, dev->evbit)) input_seq_print_bitmap(seq, "KEY", dev->keybit, KEY_MAX); if (test_bit(EV_REL, dev->evbit)) input_seq_print_bitmap(seq, "REL", dev->relbit, REL_MAX); if (test_bit(EV_ABS, dev->evbit)) input_seq_print_bitmap(seq, "ABS", dev->absbit, ABS_MAX); if (test_bit(EV_MSC, dev->evbit)) input_seq_print_bitmap(seq, "MSC", dev->mscbit, MSC_MAX); if (test_bit(EV_LED, dev->evbit)) input_seq_print_bitmap(seq, "LED", dev->ledbit, LED_MAX); if (test_bit(EV_SND, dev->evbit)) input_seq_print_bitmap(seq, "SND", dev->sndbit, SND_MAX); if (test_bit(EV_FF, dev->evbit)) input_seq_print_bitmap(seq, "FF", dev->ffbit, FF_MAX); if (test_bit(EV_SW, dev->evbit)) input_seq_print_bitmap(seq, "SW", dev->swbit, SW_MAX); seq_putc(seq, '\n'); kfree(path); return 0; } static const struct seq_operations input_devices_seq_ops = { .start = input_devices_seq_start, .next = input_devices_seq_next, .stop = input_seq_stop, .show = input_devices_seq_show, }; static int input_proc_devices_open(struct inode *inode, struct file *file) { return seq_open(file, &input_devices_seq_ops); } static const struct file_operations input_devices_fileops = { .owner = THIS_MODULE, .open = input_proc_devices_open, .poll = input_proc_devices_poll, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static void *input_handlers_seq_start(struct seq_file *seq, loff_t *pos) { union input_seq_state *state = (union input_seq_state *)&seq->private; int error; /* We need to fit into seq->private pointer */ BUILD_BUG_ON(sizeof(union input_seq_state) != sizeof(seq->private)); error = mutex_lock_interruptible(&input_mutex); if (error) { state->mutex_acquired = false; return ERR_PTR(error); } state->mutex_acquired = true; state->pos = *pos; return seq_list_start(&input_handler_list, *pos); } static void *input_handlers_seq_next(struct seq_file *seq, void *v, loff_t *pos) { union input_seq_state *state = (union input_seq_state *)&seq->private; state->pos = *pos + 1; return seq_list_next(v, &input_handler_list, pos); } static int input_handlers_seq_show(struct seq_file *seq, void *v) { struct input_handler *handler = container_of(v, struct input_handler, node); union input_seq_state *state = (union input_seq_state *)&seq->private; seq_printf(seq, "N: Number=%u Name=%s", state->pos, handler->name); if (handler->filter) seq_puts(seq, " (filter)"); if (handler->legacy_minors) seq_printf(seq, " Minor=%d", handler->minor); seq_putc(seq, '\n'); return 0; } static const struct seq_operations input_handlers_seq_ops = { .start = input_handlers_seq_start, .next = input_handlers_seq_next, .stop = input_seq_stop, .show = input_handlers_seq_show, }; static int input_proc_handlers_open(struct inode *inode, struct file *file) { return seq_open(file, &input_handlers_seq_ops); } static const struct file_operations input_handlers_fileops = { .owner = THIS_MODULE, .open = input_proc_handlers_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static int __init input_proc_init(void) { struct proc_dir_entry *entry; proc_bus_input_dir = proc_mkdir("bus/input", NULL); if (!proc_bus_input_dir) return -ENOMEM; entry = proc_create("devices", 0, proc_bus_input_dir, &input_devices_fileops); if (!entry) goto fail1; entry = proc_create("handlers", 0, proc_bus_input_dir, &input_handlers_fileops); if (!entry) goto fail2; return 0; fail2: remove_proc_entry("devices", proc_bus_input_dir); fail1: remove_proc_entry("bus/input", NULL); return -ENOMEM; } static void input_proc_exit(void) { remove_proc_entry("devices", proc_bus_input_dir); remove_proc_entry("handlers", proc_bus_input_dir); remove_proc_entry("bus/input", NULL); } #else /* !CONFIG_PROC_FS */ static inline void input_wakeup_procfs_readers(void) { } static inline int input_proc_init(void) { return 0; } static inline void input_proc_exit(void) { } #endif #define INPUT_DEV_STRING_ATTR_SHOW(name) \ static ssize_t input_dev_show_##name(struct device *dev, \ struct device_attribute *attr, \ char *buf) \ { \ struct input_dev *input_dev = to_input_dev(dev); \ \ return scnprintf(buf, PAGE_SIZE, "%s\n", \ input_dev->name ? input_dev->name : ""); \ } \ static DEVICE_ATTR(name, S_IRUGO, input_dev_show_##name, NULL) INPUT_DEV_STRING_ATTR_SHOW(name); INPUT_DEV_STRING_ATTR_SHOW(phys); INPUT_DEV_STRING_ATTR_SHOW(uniq); static int input_print_modalias_bits(char *buf, int size, char name, unsigned long *bm, unsigned int min_bit, unsigned int max_bit) { int len = 0, i; len += snprintf(buf, max(size, 0), "%c", name); for (i = min_bit; i < max_bit; i++) if (bm[BIT_WORD(i)] & BIT_MASK(i)) len += snprintf(buf + len, max(size - len, 0), "%X,", i); return len; } static int input_print_modalias(char *buf, int size, struct input_dev *id, int add_cr) { int len; len = snprintf(buf, max(size, 0), "input:b%04Xv%04Xp%04Xe%04X-", id->id.bustype, id->id.vendor, id->id.product, id->id.version); len += input_print_modalias_bits(buf + len, size - len, 'e', id->evbit, 0, EV_MAX); len += input_print_modalias_bits(buf + len, size - len, 'k', id->keybit, KEY_MIN_INTERESTING, KEY_MAX); len += input_print_modalias_bits(buf + len, size - len, 'r', id->relbit, 0, REL_MAX); len += input_print_modalias_bits(buf + len, size - len, 'a', id->absbit, 0, ABS_MAX); len += input_print_modalias_bits(buf + len, size - len, 'm', id->mscbit, 0, MSC_MAX); len += input_print_modalias_bits(buf + len, size - len, 'l', id->ledbit, 0, LED_MAX); len += input_print_modalias_bits(buf + len, size - len, 's', id->sndbit, 0, SND_MAX); len += input_print_modalias_bits(buf + len, size - len, 'f', id->ffbit, 0, FF_MAX); len += input_print_modalias_bits(buf + len, size - len, 'w', id->swbit, 0, SW_MAX); if (add_cr) len += snprintf(buf + len, max(size - len, 0), "\n"); return len; } static ssize_t input_dev_show_modalias(struct device *dev, struct device_attribute *attr, char *buf) { struct input_dev *id = to_input_dev(dev); ssize_t len; len = input_print_modalias(buf, PAGE_SIZE, id, 1); return min_t(int, len, PAGE_SIZE); } static DEVICE_ATTR(modalias, S_IRUGO, input_dev_show_modalias, NULL); static int input_print_bitmap(char *buf, int buf_size, unsigned long *bitmap, int max, int add_cr); static ssize_t input_dev_show_properties(struct device *dev, struct device_attribute *attr, char *buf) { struct input_dev *input_dev = to_input_dev(dev); int len = input_print_bitmap(buf, PAGE_SIZE, input_dev->propbit, INPUT_PROP_MAX, true); return min_t(int, len, PAGE_SIZE); } static DEVICE_ATTR(properties, S_IRUGO, input_dev_show_properties, NULL); static struct attribute *input_dev_attrs[] = { &dev_attr_name.attr, &dev_attr_phys.attr, &dev_attr_uniq.attr, &dev_attr_modalias.attr, &dev_attr_properties.attr, NULL }; static const struct attribute_group input_dev_attr_group = { .attrs = input_dev_attrs, }; #define INPUT_DEV_ID_ATTR(name) \ static ssize_t input_dev_show_id_##name(struct device *dev, \ struct device_attribute *attr, \ char *buf) \ { \ struct input_dev *input_dev = to_input_dev(dev); \ return scnprintf(buf, PAGE_SIZE, "%04x\n", input_dev->id.name); \ } \ static DEVICE_ATTR(name, S_IRUGO, input_dev_show_id_##name, NULL) INPUT_DEV_ID_ATTR(bustype); INPUT_DEV_ID_ATTR(vendor); INPUT_DEV_ID_ATTR(product); INPUT_DEV_ID_ATTR(version); static struct attribute *input_dev_id_attrs[] = { &dev_attr_bustype.attr, &dev_attr_vendor.attr, &dev_attr_product.attr, &dev_attr_version.attr, NULL }; static const struct attribute_group input_dev_id_attr_group = { .name = "id", .attrs = input_dev_id_attrs, }; static int input_print_bitmap(char *buf, int buf_size, unsigned long *bitmap, int max, int add_cr) { int i; int len = 0; bool skip_empty = true; for (i = BITS_TO_LONGS(max) - 1; i >= 0; i--) { len += input_bits_to_string(buf + len, max(buf_size - len, 0), bitmap[i], skip_empty); if (len) { skip_empty = false; if (i > 0) len += snprintf(buf + len, max(buf_size - len, 0), " "); } } /* * If no output was produced print a single 0. */ if (len == 0) len = snprintf(buf, buf_size, "%d", 0); if (add_cr) len += snprintf(buf + len, max(buf_size - len, 0), "\n"); return len; } #define INPUT_DEV_CAP_ATTR(ev, bm) \ static ssize_t input_dev_show_cap_##bm(struct device *dev, \ struct device_attribute *attr, \ char *buf) \ { \ struct input_dev *input_dev = to_input_dev(dev); \ int len = input_print_bitmap(buf, PAGE_SIZE, \ input_dev->bm##bit, ev##_MAX, \ true); \ return min_t(int, len, PAGE_SIZE); \ } \ static DEVICE_ATTR(bm, S_IRUGO, input_dev_show_cap_##bm, NULL) INPUT_DEV_CAP_ATTR(EV, ev); INPUT_DEV_CAP_ATTR(KEY, key); INPUT_DEV_CAP_ATTR(REL, rel); INPUT_DEV_CAP_ATTR(ABS, abs); INPUT_DEV_CAP_ATTR(MSC, msc); INPUT_DEV_CAP_ATTR(LED, led); INPUT_DEV_CAP_ATTR(SND, snd); INPUT_DEV_CAP_ATTR(FF, ff); INPUT_DEV_CAP_ATTR(SW, sw); static struct attribute *input_dev_caps_attrs[] = { &dev_attr_ev.attr, &dev_attr_key.attr, &dev_attr_rel.attr, &dev_attr_abs.attr, &dev_attr_msc.attr, &dev_attr_led.attr, &dev_attr_snd.attr, &dev_attr_ff.attr, &dev_attr_sw.attr, NULL }; static const struct attribute_group input_dev_caps_attr_group = { .name = "capabilities", .attrs = input_dev_caps_attrs, }; static const struct attribute_group *input_dev_attr_groups[] = { &input_dev_attr_group, &input_dev_id_attr_group, &input_dev_caps_attr_group, &input_poller_attribute_group, NULL }; static void input_dev_release(struct device *device) { struct input_dev *dev = to_input_dev(device); input_ff_destroy(dev); input_mt_destroy_slots(dev); kfree(dev->poller); kfree(dev->absinfo); kfree(dev->vals); kfree(dev); module_put(THIS_MODULE); } /* * Input uevent interface - loading event handlers based on * device bitfields. */ static int input_add_uevent_bm_var(struct kobj_uevent_env *env, const char *name, unsigned long *bitmap, int max) { int len; if (add_uevent_var(env, "%s", name)) return -ENOMEM; len = input_print_bitmap(&env->buf[env->buflen - 1], sizeof(env->buf) - env->buflen, bitmap, max, false); if (len >= (sizeof(env->buf) - env->buflen)) return -ENOMEM; env->buflen += len; return 0; } static int input_add_uevent_modalias_var(struct kobj_uevent_env *env, struct input_dev *dev) { int len; if (add_uevent_var(env, "MODALIAS=")) return -ENOMEM; len = input_print_modalias(&env->buf[env->buflen - 1], sizeof(env->buf) - env->buflen, dev, 0); if (len >= (sizeof(env->buf) - env->buflen)) return -ENOMEM; env->buflen += len; return 0; } #define INPUT_ADD_HOTPLUG_VAR(fmt, val...) \ do { \ int err = add_uevent_var(env, fmt, val); \ if (err) \ return err; \ } while (0) #define INPUT_ADD_HOTPLUG_BM_VAR(name, bm, max) \ do { \ int err = input_add_uevent_bm_var(env, name, bm, max); \ if (err) \ return err; \ } while (0) #define INPUT_ADD_HOTPLUG_MODALIAS_VAR(dev) \ do { \ int err = input_add_uevent_modalias_var(env, dev); \ if (err) \ return err; \ } while (0) static int input_dev_uevent(struct device *device, struct kobj_uevent_env *env) { struct input_dev *dev = to_input_dev(device); INPUT_ADD_HOTPLUG_VAR("PRODUCT=%x/%x/%x/%x", dev->id.bustype, dev->id.vendor, dev->id.product, dev->id.version); if (dev->name) INPUT_ADD_HOTPLUG_VAR("NAME=\"%s\"", dev->name); if (dev->phys) INPUT_ADD_HOTPLUG_VAR("PHYS=\"%s\"", dev->phys); if (dev->uniq) INPUT_ADD_HOTPLUG_VAR("UNIQ=\"%s\"", dev->uniq); INPUT_ADD_HOTPLUG_BM_VAR("PROP=", dev->propbit, INPUT_PROP_MAX); INPUT_ADD_HOTPLUG_BM_VAR("EV=", dev->evbit, EV_MAX); if (test_bit(EV_KEY, dev->evbit)) INPUT_ADD_HOTPLUG_BM_VAR("KEY=", dev->keybit, KEY_MAX); if (test_bit(EV_REL, dev->evbit)) INPUT_ADD_HOTPLUG_BM_VAR("REL=", dev->relbit, REL_MAX); if (test_bit(EV_ABS, dev->evbit)) INPUT_ADD_HOTPLUG_BM_VAR("ABS=", dev->absbit, ABS_MAX); if (test_bit(EV_MSC, dev->evbit)) INPUT_ADD_HOTPLUG_BM_VAR("MSC=", dev->mscbit, MSC_MAX); if (test_bit(EV_LED, dev->evbit)) INPUT_ADD_HOTPLUG_BM_VAR("LED=", dev->ledbit, LED_MAX); if (test_bit(EV_SND, dev->evbit)) INPUT_ADD_HOTPLUG_BM_VAR("SND=", dev->sndbit, SND_MAX); if (test_bit(EV_FF, dev->evbit)) INPUT_ADD_HOTPLUG_BM_VAR("FF=", dev->ffbit, FF_MAX); if (test_bit(EV_SW, dev->evbit)) INPUT_ADD_HOTPLUG_BM_VAR("SW=", dev->swbit, SW_MAX); INPUT_ADD_HOTPLUG_MODALIAS_VAR(dev); return 0; } #define INPUT_DO_TOGGLE(dev, type, bits, on) \ do { \ int i; \ bool active; \ \ if (!test_bit(EV_##type, dev->evbit)) \ break; \ \ for_each_set_bit(i, dev->bits##bit, type##_CNT) { \ active = test_bit(i, dev->bits); \ if (!active && !on) \ continue; \ \ dev->event(dev, EV_##type, i, on ? active : 0); \ } \ } while (0) static void input_dev_toggle(struct input_dev *dev, bool activate) { if (!dev->event) return; INPUT_DO_TOGGLE(dev, LED, led, activate); INPUT_DO_TOGGLE(dev, SND, snd, activate); if (activate && test_bit(EV_REP, dev->evbit)) { dev->event(dev, EV_REP, REP_PERIOD, dev->rep[REP_PERIOD]); dev->event(dev, EV_REP, REP_DELAY, dev->rep[REP_DELAY]); } } /** * input_reset_device() - reset/restore the state of input device * @dev: input device whose state needs to be reset * * This function tries to reset the state of an opened input device and * bring internal state and state if the hardware in sync with each other. * We mark all keys as released, restore LED state, repeat rate, etc. */ void input_reset_device(struct input_dev *dev) { unsigned long flags; mutex_lock(&dev->mutex); spin_lock_irqsave(&dev->event_lock, flags); input_dev_toggle(dev, true); input_dev_release_keys(dev); spin_unlock_irqrestore(&dev->event_lock, flags); mutex_unlock(&dev->mutex); } EXPORT_SYMBOL(input_reset_device); #ifdef CONFIG_PM_SLEEP static int input_dev_suspend(struct device *dev) { struct input_dev *input_dev = to_input_dev(dev); spin_lock_irq(&input_dev->event_lock); /* * Keys that are pressed now are unlikely to be * still pressed when we resume. */ input_dev_release_keys(input_dev); /* Turn off LEDs and sounds, if any are active. */ input_dev_toggle(input_dev, false); spin_unlock_irq(&input_dev->event_lock); return 0; } static int input_dev_resume(struct device *dev) { struct input_dev *input_dev = to_input_dev(dev); spin_lock_irq(&input_dev->event_lock); /* Restore state of LEDs and sounds, if any were active. */ input_dev_toggle(input_dev, true); spin_unlock_irq(&input_dev->event_lock); return 0; } static int input_dev_freeze(struct device *dev) { struct input_dev *input_dev = to_input_dev(dev); spin_lock_irq(&input_dev->event_lock); /* * Keys that are pressed now are unlikely to be * still pressed when we resume. */ input_dev_release_keys(input_dev); spin_unlock_irq(&input_dev->event_lock); return 0; } static int input_dev_poweroff(struct device *dev) { struct input_dev *input_dev = to_input_dev(dev); spin_lock_irq(&input_dev->event_lock); /* Turn off LEDs and sounds, if any are active. */ input_dev_toggle(input_dev, false); spin_unlock_irq(&input_dev->event_lock); return 0; } static const struct dev_pm_ops input_dev_pm_ops = { .suspend = input_dev_suspend, .resume = input_dev_resume, .freeze = input_dev_freeze, .poweroff = input_dev_poweroff, .restore = input_dev_resume, }; #endif /* CONFIG_PM */ static const struct device_type input_dev_type = { .groups = input_dev_attr_groups, .release = input_dev_release, .uevent = input_dev_uevent, #ifdef CONFIG_PM_SLEEP .pm = &input_dev_pm_ops, #endif }; static char *input_devnode(struct device *dev, umode_t *mode) { return kasprintf(GFP_KERNEL, "input/%s", dev_name(dev)); } struct class input_class = { .name = "input", .devnode = input_devnode, }; EXPORT_SYMBOL_GPL(input_class); /** * input_allocate_device - allocate memory for new input device * * Returns prepared struct input_dev or %NULL. * * NOTE: Use input_free_device() to free devices that have not been * registered; input_unregister_device() should be used for already * registered devices. */ struct input_dev *input_allocate_device(void) { static atomic_t input_no = ATOMIC_INIT(-1); struct input_dev *dev; dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (dev) { dev->dev.type = &input_dev_type; dev->dev.class = &input_class; device_initialize(&dev->dev); mutex_init(&dev->mutex); spin_lock_init(&dev->event_lock); timer_setup(&dev->timer, NULL, 0); INIT_LIST_HEAD(&dev->h_list); INIT_LIST_HEAD(&dev->node); dev_set_name(&dev->dev, "input%lu", (unsigned long)atomic_inc_return(&input_no)); __module_get(THIS_MODULE); } return dev; } EXPORT_SYMBOL(input_allocate_device); struct input_devres { struct input_dev *input; }; static int devm_input_device_match(struct device *dev, void *res, void *data) { struct input_devres *devres = res; return devres->input == data; } static void devm_input_device_release(struct device *dev, void *res) { struct input_devres *devres = res; struct input_dev *input = devres->input; dev_dbg(dev, "%s: dropping reference to %s\n", __func__, dev_name(&input->dev)); input_put_device(input); } /** * devm_input_allocate_device - allocate managed input device * @dev: device owning the input device being created * * Returns prepared struct input_dev or %NULL. * * Managed input devices do not need to be explicitly unregistered or * freed as it will be done automatically when owner device unbinds from * its driver (or binding fails). Once managed input device is allocated, * it is ready to be set up and registered in the same fashion as regular * input device. There are no special devm_input_device_[un]register() * variants, regular ones work with both managed and unmanaged devices, * should you need them. In most cases however, managed input device need * not be explicitly unregistered or freed. * * NOTE: the owner device is set up as parent of input device and users * should not override it. */ struct input_dev *devm_input_allocate_device(struct device *dev) { struct input_dev *input; struct input_devres *devres; devres = devres_alloc(devm_input_device_release, sizeof(*devres), GFP_KERNEL); if (!devres) return NULL; input = input_allocate_device(); if (!input) { devres_free(devres); return NULL; } input->dev.parent = dev; input->devres_managed = true; devres->input = input; devres_add(dev, devres); return input; } EXPORT_SYMBOL(devm_input_allocate_device); /** * input_free_device - free memory occupied by input_dev structure * @dev: input device to free * * This function should only be used if input_register_device() * was not called yet or if it failed. Once device was registered * use input_unregister_device() and memory will be freed once last * reference to the device is dropped. * * Device should be allocated by input_allocate_device(). * * NOTE: If there are references to the input device then memory * will not be freed until last reference is dropped. */ void input_free_device(struct input_dev *dev) { if (dev) { if (dev->devres_managed) WARN_ON(devres_destroy(dev->dev.parent, devm_input_device_release, devm_input_device_match, dev)); input_put_device(dev); } } EXPORT_SYMBOL(input_free_device); /** * input_set_timestamp - set timestamp for input events * @dev: input device to set timestamp for * @timestamp: the time at which the event has occurred * in CLOCK_MONOTONIC * * This function is intended to provide to the input system a more * accurate time of when an event actually occurred. The driver should * call this function as soon as a timestamp is acquired ensuring * clock conversions in input_set_timestamp are done correctly. * * The system entering suspend state between timestamp acquisition and * calling input_set_timestamp can result in inaccurate conversions. */ void input_set_timestamp(struct input_dev *dev, ktime_t timestamp) { dev->timestamp[INPUT_CLK_MONO] = timestamp; dev->timestamp[INPUT_CLK_REAL] = ktime_mono_to_real(timestamp); dev->timestamp[INPUT_CLK_BOOT] = ktime_mono_to_any(timestamp, TK_OFFS_BOOT); } EXPORT_SYMBOL(input_set_timestamp); /** * input_get_timestamp - get timestamp for input events * @dev: input device to get timestamp from * * A valid timestamp is a timestamp of non-zero value. */ ktime_t *input_get_timestamp(struct input_dev *dev) { const ktime_t invalid_timestamp = ktime_set(0, 0); if (!ktime_compare(dev->timestamp[INPUT_CLK_MONO], invalid_timestamp)) input_set_timestamp(dev, ktime_get()); return dev->timestamp; } EXPORT_SYMBOL(input_get_timestamp); /** * input_set_capability - mark device as capable of a certain event * @dev: device that is capable of emitting or accepting event * @type: type of the event (EV_KEY, EV_REL, etc...) * @code: event code * * In addition to setting up corresponding bit in appropriate capability * bitmap the function also adjusts dev->evbit. */ void input_set_capability(struct input_dev *dev, unsigned int type, unsigned int code) { switch (type) { case EV_KEY: __set_bit(code, dev->keybit); break; case EV_REL: __set_bit(code, dev->relbit); break; case EV_ABS: input_alloc_absinfo(dev); if (!dev->absinfo) return; __set_bit(code, dev->absbit); break; case EV_MSC: __set_bit(code, dev->mscbit); break; case EV_SW: __set_bit(code, dev->swbit); break; case EV_LED: __set_bit(code, dev->ledbit); break; case EV_SND: __set_bit(code, dev->sndbit); break; case EV_FF: __set_bit(code, dev->ffbit); break; case EV_PWR: /* do nothing */ break; default: pr_err("%s: unknown type %u (code %u)\n", __func__, type, code); dump_stack(); return; } __set_bit(type, dev->evbit); } EXPORT_SYMBOL(input_set_capability); static unsigned int input_estimate_events_per_packet(struct input_dev *dev) { int mt_slots; int i; unsigned int events; if (dev->mt) { mt_slots = dev->mt->num_slots; } else if (test_bit(ABS_MT_TRACKING_ID, dev->absbit)) { mt_slots = dev->absinfo[ABS_MT_TRACKING_ID].maximum - dev->absinfo[ABS_MT_TRACKING_ID].minimum + 1, mt_slots = clamp(mt_slots, 2, 32); } else if (test_bit(ABS_MT_POSITION_X, dev->absbit)) { mt_slots = 2; } else { mt_slots = 0; } events = mt_slots + 1; /* count SYN_MT_REPORT and SYN_REPORT */ if (test_bit(EV_ABS, dev->evbit)) for_each_set_bit(i, dev->absbit, ABS_CNT) events += input_is_mt_axis(i) ? mt_slots : 1; if (test_bit(EV_REL, dev->evbit)) events += bitmap_weight(dev->relbit, REL_CNT); /* Make room for KEY and MSC events */ events += 7; return events; } #define INPUT_CLEANSE_BITMASK(dev, type, bits) \ do { \ if (!test_bit(EV_##type, dev->evbit)) \ memset(dev->bits##bit, 0, \ sizeof(dev->bits##bit)); \ } while (0) static void input_cleanse_bitmasks(struct input_dev *dev) { INPUT_CLEANSE_BITMASK(dev, KEY, key); INPUT_CLEANSE_BITMASK(dev, REL, rel); INPUT_CLEANSE_BITMASK(dev, ABS, abs); INPUT_CLEANSE_BITMASK(dev, MSC, msc); INPUT_CLEANSE_BITMASK(dev, LED, led); INPUT_CLEANSE_BITMASK(dev, SND, snd); INPUT_CLEANSE_BITMASK(dev, FF, ff); INPUT_CLEANSE_BITMASK(dev, SW, sw); } static void __input_unregister_device(struct input_dev *dev) { struct input_handle *handle, *next; input_disconnect_device(dev); mutex_lock(&input_mutex); list_for_each_entry_safe(handle, next, &dev->h_list, d_node) handle->handler->disconnect(handle); WARN_ON(!list_empty(&dev->h_list)); del_timer_sync(&dev->timer); list_del_init(&dev->node); input_wakeup_procfs_readers(); mutex_unlock(&input_mutex); device_del(&dev->dev); } static void devm_input_device_unregister(struct device *dev, void *res) { struct input_devres *devres = res; struct input_dev *input = devres->input; dev_dbg(dev, "%s: unregistering device %s\n", __func__, dev_name(&input->dev)); __input_unregister_device(input); } /** * input_enable_softrepeat - enable software autorepeat * @dev: input device * @delay: repeat delay * @period: repeat period * * Enable software autorepeat on the input device. */ void input_enable_softrepeat(struct input_dev *dev, int delay, int period) { dev->timer.function = input_repeat_key; dev->rep[REP_DELAY] = delay; dev->rep[REP_PERIOD] = period; } EXPORT_SYMBOL(input_enable_softrepeat); /** * input_register_device - register device with input core * @dev: device to be registered * * This function registers device with input core. The device must be * allocated with input_allocate_device() and all it's capabilities * set up before registering. * If function fails the device must be freed with input_free_device(). * Once device has been successfully registered it can be unregistered * with input_unregister_device(); input_free_device() should not be * called in this case. * * Note that this function is also used to register managed input devices * (ones allocated with devm_input_allocate_device()). Such managed input * devices need not be explicitly unregistered or freed, their tear down * is controlled by the devres infrastructure. It is also worth noting * that tear down of managed input devices is internally a 2-step process: * registered managed input device is first unregistered, but stays in * memory and can still handle input_event() calls (although events will * not be delivered anywhere). The freeing of managed input device will * happen later, when devres stack is unwound to the point where device * allocation was made. */ int input_register_device(struct input_dev *dev) { struct input_devres *devres = NULL; struct input_handler *handler; unsigned int packet_size; const char *path; int error; if (test_bit(EV_ABS, dev->evbit) && !dev->absinfo) { dev_err(&dev->dev, "Absolute device without dev->absinfo, refusing to register\n"); return -EINVAL; } if (dev->devres_managed) { devres = devres_alloc(devm_input_device_unregister, sizeof(*devres), GFP_KERNEL); if (!devres) return -ENOMEM; devres->input = dev; } /* Every input device generates EV_SYN/SYN_REPORT events. */ __set_bit(EV_SYN, dev->evbit); /* KEY_RESERVED is not supposed to be transmitted to userspace. */ __clear_bit(KEY_RESERVED, dev->keybit); /* Make sure that bitmasks not mentioned in dev->evbit are clean. */ input_cleanse_bitmasks(dev); packet_size = input_estimate_events_per_packet(dev); if (dev->hint_events_per_packet < packet_size) dev->hint_events_per_packet = packet_size; dev->max_vals = dev->hint_events_per_packet + 2; dev->vals = kcalloc(dev->max_vals, sizeof(*dev->vals), GFP_KERNEL); if (!dev->vals) { error = -ENOMEM; goto err_devres_free; } /* * If delay and period are pre-set by the driver, then autorepeating * is handled by the driver itself and we don't do it in input.c. */ if (!dev->rep[REP_DELAY] && !dev->rep[REP_PERIOD]) input_enable_softrepeat(dev, 250, 33); if (!dev->getkeycode) dev->getkeycode = input_default_getkeycode; if (!dev->setkeycode) dev->setkeycode = input_default_setkeycode; if (dev->poller) input_dev_poller_finalize(dev->poller); error = device_add(&dev->dev); if (error) goto err_free_vals; path = kobject_get_path(&dev->dev.kobj, GFP_KERNEL); pr_info("%s as %s\n", dev->name ? dev->name : "Unspecified device", path ? path : "N/A"); kfree(path); error = mutex_lock_interruptible(&input_mutex); if (error) goto err_device_del; list_add_tail(&dev->node, &input_dev_list); list_for_each_entry(handler, &input_handler_list, node) input_attach_handler(dev, handler); input_wakeup_procfs_readers(); mutex_unlock(&input_mutex); if (dev->devres_managed) { dev_dbg(dev->dev.parent, "%s: registering %s with devres.\n", __func__, dev_name(&dev->dev)); devres_add(dev->dev.parent, devres); } return 0; err_device_del: device_del(&dev->dev); err_free_vals: kfree(dev->vals); dev->vals = NULL; err_devres_free: devres_free(devres); return error; } EXPORT_SYMBOL(input_register_device); /** * input_unregister_device - unregister previously registered device * @dev: device to be unregistered * * This function unregisters an input device. Once device is unregistered * the caller should not try to access it as it may get freed at any moment. */ void input_unregister_device(struct input_dev *dev) { if (dev->devres_managed) { WARN_ON(devres_destroy(dev->dev.parent, devm_input_device_unregister, devm_input_device_match, dev)); __input_unregister_device(dev); /* * We do not do input_put_device() here because it will be done * when 2nd devres fires up. */ } else { __input_unregister_device(dev); input_put_device(dev); } } EXPORT_SYMBOL(input_unregister_device); /** * input_register_handler - register a new input handler * @handler: handler to be registered * * This function registers a new input handler (interface) for input * devices in the system and attaches it to all input devices that * are compatible with the handler. */ int input_register_handler(struct input_handler *handler) { struct input_dev *dev; int error; error = mutex_lock_interruptible(&input_mutex); if (error) return error; INIT_LIST_HEAD(&handler->h_list); list_add_tail(&handler->node, &input_handler_list); list_for_each_entry(dev, &input_dev_list, node) input_attach_handler(dev, handler); input_wakeup_procfs_readers(); mutex_unlock(&input_mutex); return 0; } EXPORT_SYMBOL(input_register_handler); /** * input_unregister_handler - unregisters an input handler * @handler: handler to be unregistered * * This function disconnects a handler from its input devices and * removes it from lists of known handlers. */ void input_unregister_handler(struct input_handler *handler) { struct input_handle *handle, *next; mutex_lock(&input_mutex); list_for_each_entry_safe(handle, next, &handler->h_list, h_node) handler->disconnect(handle); WARN_ON(!list_empty(&handler->h_list)); list_del_init(&handler->node); input_wakeup_procfs_readers(); mutex_unlock(&input_mutex); } EXPORT_SYMBOL(input_unregister_handler); /** * input_handler_for_each_handle - handle iterator * @handler: input handler to iterate * @data: data for the callback * @fn: function to be called for each handle * * Iterate over @bus's list of devices, and call @fn for each, passing * it @data and stop when @fn returns a non-zero value. The function is * using RCU to traverse the list and therefore may be using in atomic * contexts. The @fn callback is invoked from RCU critical section and * thus must not sleep. */ int input_handler_for_each_handle(struct input_handler *handler, void *data, int (*fn)(struct input_handle *, void *)) { struct input_handle *handle; int retval = 0; rcu_read_lock(); list_for_each_entry_rcu(handle, &handler->h_list, h_node) { retval = fn(handle, data); if (retval) break; } rcu_read_unlock(); return retval; } EXPORT_SYMBOL(input_handler_for_each_handle); /** * input_register_handle - register a new input handle * @handle: handle to register * * This function puts a new input handle onto device's * and handler's lists so that events can flow through * it once it is opened using input_open_device(). * * This function is supposed to be called from handler's * connect() method. */ int input_register_handle(struct input_handle *handle) { struct input_handler *handler = handle->handler; struct input_dev *dev = handle->dev; int error; /* * We take dev->mutex here to prevent race with * input_release_device(). */ error = mutex_lock_interruptible(&dev->mutex); if (error) return error; /* * Filters go to the head of the list, normal handlers * to the tail. */ if (handler->filter) list_add_rcu(&handle->d_node, &dev->h_list); else list_add_tail_rcu(&handle->d_node, &dev->h_list); mutex_unlock(&dev->mutex); /* * Since we are supposed to be called from ->connect() * which is mutually exclusive with ->disconnect() * we can't be racing with input_unregister_handle() * and so separate lock is not needed here. */ list_add_tail_rcu(&handle->h_node, &handler->h_list); if (handler->start) handler->start(handle); return 0; } EXPORT_SYMBOL(input_register_handle); /** * input_unregister_handle - unregister an input handle * @handle: handle to unregister * * This function removes input handle from device's * and handler's lists. * * This function is supposed to be called from handler's * disconnect() method. */ void input_unregister_handle(struct input_handle *handle) { struct input_dev *dev = handle->dev; list_del_rcu(&handle->h_node); /* * Take dev->mutex to prevent race with input_release_device(). */ mutex_lock(&dev->mutex); list_del_rcu(&handle->d_node); mutex_unlock(&dev->mutex); synchronize_rcu(); } EXPORT_SYMBOL(input_unregister_handle); /** * input_get_new_minor - allocates a new input minor number * @legacy_base: beginning or the legacy range to be searched * @legacy_num: size of legacy range * @allow_dynamic: whether we can also take ID from the dynamic range * * This function allocates a new device minor for from input major namespace. * Caller can request legacy minor by specifying @legacy_base and @legacy_num * parameters and whether ID can be allocated from dynamic range if there are * no free IDs in legacy range. */ int input_get_new_minor(int legacy_base, unsigned int legacy_num, bool allow_dynamic) { /* * This function should be called from input handler's ->connect() * methods, which are serialized with input_mutex, so no additional * locking is needed here. */ if (legacy_base >= 0) { int minor = ida_simple_get(&input_ida, legacy_base, legacy_base + legacy_num, GFP_KERNEL); if (minor >= 0 || !allow_dynamic) return minor; } return ida_simple_get(&input_ida, INPUT_FIRST_DYNAMIC_DEV, INPUT_MAX_CHAR_DEVICES, GFP_KERNEL); } EXPORT_SYMBOL(input_get_new_minor); /** * input_free_minor - release previously allocated minor * @minor: minor to be released * * This function releases previously allocated input minor so that it can be * reused later. */ void input_free_minor(unsigned int minor) { ida_simple_remove(&input_ida, minor); } EXPORT_SYMBOL(input_free_minor); static int __init input_init(void) { int err; err = class_register(&input_class); if (err) { pr_err("unable to register input_dev class\n"); return err; } err = input_proc_init(); if (err) goto fail1; err = register_chrdev_region(MKDEV(INPUT_MAJOR, 0), INPUT_MAX_CHAR_DEVICES, "input"); if (err) { pr_err("unable to register char major %d", INPUT_MAJOR); goto fail2; } return 0; fail2: input_proc_exit(); fail1: class_unregister(&input_class); return err; } static void __exit input_exit(void) { input_proc_exit(); unregister_chrdev_region(MKDEV(INPUT_MAJOR, 0), INPUT_MAX_CHAR_DEVICES); class_unregister(&input_class); } subsys_initcall(input_init); module_exit(input_exit);
null
153
CWE-787
CVE-2019-20788
/* * Copyright (C) 2001,2002 Constantin Kaplinsky. All Rights Reserved. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ /* * cursor.c - code to support cursor shape updates (XCursor and * RichCursor preudo-encodings). */ #include <rfb/rfbclient.h> #define OPER_SAVE 0 #define OPER_RESTORE 1 #define RGB24_TO_PIXEL(bpp,r,g,b) \ ((((uint##bpp##_t)(r) & 0xFF) * client->format.redMax + 127) / 255 \ << client->format.redShift | \ (((uint##bpp##_t)(g) & 0xFF) * client->format.greenMax + 127) / 255 \ << client->format.greenShift | \ (((uint##bpp##_t)(b) & 0xFF) * client->format.blueMax + 127) / 255 \ << client->format.blueShift) rfbBool HandleCursorShape(rfbClient* client,int xhot, int yhot, int width, int height, uint32_t enc) { int bytesPerPixel; size_t bytesPerRow, bytesMaskData; rfbXCursorColors rgb; uint32_t colors[2]; char *buf; uint8_t *ptr; int x, y, b; bytesPerPixel = client->format.bitsPerPixel / 8; bytesPerRow = (width + 7) / 8; bytesMaskData = bytesPerRow * height; if (width * height == 0) return TRUE; /* Allocate memory for pixel data and temporary mask data. */ if(client->rcSource) free(client->rcSource); client->rcSource = malloc(width * height * bytesPerPixel); if (client->rcSource == NULL) return FALSE; buf = malloc(bytesMaskData); if (buf == NULL) { free(client->rcSource); client->rcSource = NULL; return FALSE; } /* Read and decode cursor pixel data, depending on the encoding type. */ if (enc == rfbEncodingXCursor) { /* Read and convert background and foreground colors. */ if (!ReadFromRFBServer(client, (char *)&rgb, sz_rfbXCursorColors)) { free(client->rcSource); client->rcSource = NULL; free(buf); return FALSE; } colors[0] = RGB24_TO_PIXEL(32, rgb.backRed, rgb.backGreen, rgb.backBlue); colors[1] = RGB24_TO_PIXEL(32, rgb.foreRed, rgb.foreGreen, rgb.foreBlue); /* Read 1bpp pixel data into a temporary buffer. */ if (!ReadFromRFBServer(client, buf, bytesMaskData)) { free(client->rcSource); client->rcSource = NULL; free(buf); return FALSE; } /* Convert 1bpp data to byte-wide color indices. */ ptr = client->rcSource; for (y = 0; y < height; y++) { for (x = 0; x < width / 8; x++) { for (b = 7; b >= 0; b--) { *ptr = buf[y * bytesPerRow + x] >> b & 1; ptr += bytesPerPixel; } } for (b = 7; b > 7 - width % 8; b--) { *ptr = buf[y * bytesPerRow + x] >> b & 1; ptr += bytesPerPixel; } } /* Convert indices into the actual pixel values. */ switch (bytesPerPixel) { case 1: for (x = 0; x < width * height; x++) client->rcSource[x] = (uint8_t)colors[client->rcSource[x]]; break; case 2: for (x = 0; x < width * height; x++) ((uint16_t *)client->rcSource)[x] = (uint16_t)colors[client->rcSource[x * 2]]; break; case 4: for (x = 0; x < width * height; x++) ((uint32_t *)client->rcSource)[x] = colors[client->rcSource[x * 4]]; break; } } else { /* enc == rfbEncodingRichCursor */ if (!ReadFromRFBServer(client, (char *)client->rcSource, width * height * bytesPerPixel)) { free(client->rcSource); client->rcSource = NULL; free(buf); return FALSE; } } /* Read and decode mask data. */ if (!ReadFromRFBServer(client, buf, bytesMaskData)) { free(client->rcSource); client->rcSource = NULL; free(buf); return FALSE; } client->rcMask = malloc(width * height); if (client->rcMask == NULL) { free(client->rcSource); client->rcSource = NULL; free(buf); return FALSE; } ptr = client->rcMask; for (y = 0; y < height; y++) { for (x = 0; x < width / 8; x++) { for (b = 7; b >= 0; b--) { *ptr++ = buf[y * bytesPerRow + x] >> b & 1; } } for (b = 7; b > 7 - width % 8; b--) { *ptr++ = buf[y * bytesPerRow + x] >> b & 1; } } if (client->GotCursorShape != NULL) { client->GotCursorShape(client, xhot, yhot, width, height, bytesPerPixel); } free(buf); return TRUE; }
null
/* * Copyright (C) 2001,2002 Constantin Kaplinsky. All Rights Reserved. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ /* * cursor.c - code to support cursor shape updates (XCursor and * RichCursor preudo-encodings). */ #include <rfb/rfbclient.h> #define OPER_SAVE 0 #define OPER_RESTORE 1 #define MAX_CURSOR_SIZE 1024 #define RGB24_TO_PIXEL(bpp,r,g,b) \ ((((uint##bpp##_t)(r) & 0xFF) * client->format.redMax + 127) / 255 \ << client->format.redShift | \ (((uint##bpp##_t)(g) & 0xFF) * client->format.greenMax + 127) / 255 \ << client->format.greenShift | \ (((uint##bpp##_t)(b) & 0xFF) * client->format.blueMax + 127) / 255 \ << client->format.blueShift) rfbBool HandleCursorShape(rfbClient* client,int xhot, int yhot, int width, int height, uint32_t enc) { int bytesPerPixel; size_t bytesPerRow, bytesMaskData; rfbXCursorColors rgb; uint32_t colors[2]; char *buf; uint8_t *ptr; int x, y, b; bytesPerPixel = client->format.bitsPerPixel / 8; bytesPerRow = (width + 7) / 8; bytesMaskData = bytesPerRow * height; if (width * height == 0) return TRUE; if (width >= MAX_CURSOR_SIZE || height >= MAX_CURSOR_SIZE) return FALSE; /* Allocate memory for pixel data and temporary mask data. */ if(client->rcSource) free(client->rcSource); client->rcSource = malloc(width * height * bytesPerPixel); if (client->rcSource == NULL) return FALSE; buf = malloc(bytesMaskData); if (buf == NULL) { free(client->rcSource); client->rcSource = NULL; return FALSE; } /* Read and decode cursor pixel data, depending on the encoding type. */ if (enc == rfbEncodingXCursor) { /* Read and convert background and foreground colors. */ if (!ReadFromRFBServer(client, (char *)&rgb, sz_rfbXCursorColors)) { free(client->rcSource); client->rcSource = NULL; free(buf); return FALSE; } colors[0] = RGB24_TO_PIXEL(32, rgb.backRed, rgb.backGreen, rgb.backBlue); colors[1] = RGB24_TO_PIXEL(32, rgb.foreRed, rgb.foreGreen, rgb.foreBlue); /* Read 1bpp pixel data into a temporary buffer. */ if (!ReadFromRFBServer(client, buf, bytesMaskData)) { free(client->rcSource); client->rcSource = NULL; free(buf); return FALSE; } /* Convert 1bpp data to byte-wide color indices. */ ptr = client->rcSource; for (y = 0; y < height; y++) { for (x = 0; x < width / 8; x++) { for (b = 7; b >= 0; b--) { *ptr = buf[y * bytesPerRow + x] >> b & 1; ptr += bytesPerPixel; } } for (b = 7; b > 7 - width % 8; b--) { *ptr = buf[y * bytesPerRow + x] >> b & 1; ptr += bytesPerPixel; } } /* Convert indices into the actual pixel values. */ switch (bytesPerPixel) { case 1: for (x = 0; x < width * height; x++) client->rcSource[x] = (uint8_t)colors[client->rcSource[x]]; break; case 2: for (x = 0; x < width * height; x++) ((uint16_t *)client->rcSource)[x] = (uint16_t)colors[client->rcSource[x * 2]]; break; case 4: for (x = 0; x < width * height; x++) ((uint32_t *)client->rcSource)[x] = colors[client->rcSource[x * 4]]; break; } } else { /* enc == rfbEncodingRichCursor */ if (!ReadFromRFBServer(client, (char *)client->rcSource, width * height * bytesPerPixel)) { free(client->rcSource); client->rcSource = NULL; free(buf); return FALSE; } } /* Read and decode mask data. */ if (!ReadFromRFBServer(client, buf, bytesMaskData)) { free(client->rcSource); client->rcSource = NULL; free(buf); return FALSE; } client->rcMask = malloc(width * height); if (client->rcMask == NULL) { free(client->rcSource); client->rcSource = NULL; free(buf); return FALSE; } ptr = client->rcMask; for (y = 0; y < height; y++) { for (x = 0; x < width / 8; x++) { for (b = 7; b >= 0; b--) { *ptr++ = buf[y * bytesPerRow + x] >> b & 1; } } for (b = 7; b > 7 - width % 8; b--) { *ptr++ = buf[y * bytesPerRow + x] >> b & 1; } } if (client->GotCursorShape != NULL) { client->GotCursorShape(client, xhot, yhot, width, height, bytesPerPixel); } free(buf); return TRUE; }
null
154
CWE-787
CVE-2019-20791
/* * Copyright (c) 2016, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * This file implements a Commissioner role. */ #include "commissioner.hpp" #include <stdio.h> #include "utils/wrap_string.h" #include "coap/coap_message.hpp" #include "common/encoding.hpp" #include "common/instance.hpp" #include "common/locator-getters.hpp" #include "common/logging.hpp" #include "crypto/pbkdf2_cmac.h" #include "meshcop/joiner_router.hpp" #include "meshcop/meshcop.hpp" #include "meshcop/meshcop_tlvs.hpp" #include "thread/thread_netif.hpp" #include "thread/thread_tlvs.hpp" #include "thread/thread_uri_paths.hpp" #if OPENTHREAD_FTD && OPENTHREAD_CONFIG_COMMISSIONER_ENABLE namespace ot { namespace MeshCoP { Commissioner::Commissioner(Instance &aInstance) : InstanceLocator(aInstance) , mJoinerPort(0) , mJoinerRloc(0) , mSessionId(0) , mJoinerIndex(0) , mTransmitAttempts(0) , mJoinerExpirationTimer(aInstance, HandleJoinerExpirationTimer, this) , mTimer(aInstance, HandleTimer, this) , mRelayReceive(OT_URI_PATH_RELAY_RX, &Commissioner::HandleRelayReceive, this) , mDatasetChanged(OT_URI_PATH_DATASET_CHANGED, &Commissioner::HandleDatasetChanged, this) , mJoinerFinalize(OT_URI_PATH_JOINER_FINALIZE, &Commissioner::HandleJoinerFinalize, this) , mAnnounceBegin(aInstance) , mEnergyScan(aInstance) , mPanIdQuery(aInstance) , mStateCallback(NULL) , mJoinerCallback(NULL) , mCallbackContext(NULL) , mState(OT_COMMISSIONER_STATE_DISABLED) { memset(mJoiners, 0, sizeof(mJoiners)); mCommissionerAloc.Clear(); mCommissionerAloc.mPrefixLength = 64; mCommissionerAloc.mPreferred = true; mCommissionerAloc.mValid = true; mCommissionerAloc.mScopeOverride = Ip6::Address::kRealmLocalScope; mCommissionerAloc.mScopeOverrideValid = true; mProvisioningUrl[0] = '\0'; } void Commissioner::SetState(otCommissionerState aState) { VerifyOrExit(mState != aState); otLogInfoMeshCoP("Commissioner State: %s -> %s", StateToString(mState), StateToString(aState)); mState = aState; if (mStateCallback) { mStateCallback(mState, mCallbackContext); } exit: return; } void Commissioner::SignalJoinerEvent(otCommissionerJoinerEvent aEvent, const Mac::ExtAddress &aJoinerId) { if (mJoinerCallback) { mJoinerCallback(aEvent, &aJoinerId, mCallbackContext); } } void Commissioner::AddCoapResources(void) { Get<Coap::Coap>().AddResource(mRelayReceive); Get<Coap::Coap>().AddResource(mDatasetChanged); Get<Coap::CoapSecure>().AddResource(mJoinerFinalize); } void Commissioner::RemoveCoapResources(void) { Get<Coap::Coap>().RemoveResource(mRelayReceive); Get<Coap::Coap>().RemoveResource(mDatasetChanged); Get<Coap::CoapSecure>().RemoveResource(mJoinerFinalize); } void Commissioner::HandleCoapsConnected(bool aConnected, void *aContext) { static_cast<Commissioner *>(aContext)->HandleCoapsConnected(aConnected); } void Commissioner::HandleCoapsConnected(bool aConnected) { otCommissionerJoinerEvent event; Mac::ExtAddress joinerId; event = aConnected ? OT_COMMISSIONER_JOINER_CONNECTED : OT_COMMISSIONER_JOINER_END; joinerId.Set(mJoinerIid); joinerId.ToggleLocal(); SignalJoinerEvent(event, joinerId); } otError Commissioner::Start(otCommissionerStateCallback aStateCallback, otCommissionerJoinerCallback aJoinerCallback, void * aCallbackContext) { otError error = OT_ERROR_NONE; VerifyOrExit(Get<Mle::MleRouter>().IsAttached(), error = OT_ERROR_INVALID_STATE); VerifyOrExit(mState == OT_COMMISSIONER_STATE_DISABLED, error = OT_ERROR_INVALID_STATE); SuccessOrExit(error = Get<Coap::CoapSecure>().Start(SendRelayTransmit, this)); Get<Coap::CoapSecure>().SetConnectedCallback(&Commissioner::HandleCoapsConnected, this); mStateCallback = aStateCallback; mJoinerCallback = aJoinerCallback; mCallbackContext = aCallbackContext; mTransmitAttempts = 0; SuccessOrExit(error = SendPetition()); SetState(OT_COMMISSIONER_STATE_PETITION); exit: return error; } otError Commissioner::Stop(void) { otError error = OT_ERROR_NONE; VerifyOrExit(mState != OT_COMMISSIONER_STATE_DISABLED, error = OT_ERROR_INVALID_STATE); Get<Coap::CoapSecure>().Stop(); Get<ThreadNetif>().RemoveUnicastAddress(mCommissionerAloc); RemoveCoapResources(); ClearJoiners(); mTransmitAttempts = 0; mTimer.Stop(); Get<Coap::CoapSecure>().Stop(); SetState(OT_COMMISSIONER_STATE_DISABLED); SendKeepAlive(); exit: return error; } otError Commissioner::SendCommissionerSet(void) { otError error; otCommissioningDataset dataset; SteeringDataTlv steeringData; Mac::ExtAddress joinerId; VerifyOrExit(mState == OT_COMMISSIONER_STATE_ACTIVE, error = OT_ERROR_INVALID_STATE); memset(&dataset, 0, sizeof(dataset)); // session id dataset.mSessionId = mSessionId; dataset.mIsSessionIdSet = true; // compute bloom filter steeringData.Init(); steeringData.Clear(); for (Joiner *joiner = &mJoiners[0]; joiner < OT_ARRAY_END(mJoiners); joiner++) { if (!joiner->mValid) { continue; } if (joiner->mAny) { steeringData.SetLength(1); steeringData.Set(); break; } ComputeJoinerId(joiner->mEui64, joinerId); steeringData.ComputeBloomFilter(joinerId); } // set bloom filter dataset.mSteeringData.mLength = steeringData.GetSteeringDataLength(); memcpy(dataset.mSteeringData.m8, steeringData.GetValue(), dataset.mSteeringData.mLength); dataset.mIsSteeringDataSet = true; SuccessOrExit(error = SendMgmtCommissionerSetRequest(dataset, NULL, 0)); exit: return error; } void Commissioner::ClearJoiners(void) { for (Joiner *joiner = &mJoiners[0]; joiner < OT_ARRAY_END(mJoiners); joiner++) { joiner->mValid = false; } SendCommissionerSet(); } otError Commissioner::AddJoiner(const Mac::ExtAddress *aEui64, const char *aPskd, uint32_t aTimeout) { otError error = OT_ERROR_NO_BUFS; VerifyOrExit(mState == OT_COMMISSIONER_STATE_ACTIVE, error = OT_ERROR_INVALID_STATE); VerifyOrExit(strlen(aPskd) <= Dtls::kPskMaxLength, error = OT_ERROR_INVALID_ARGS); RemoveJoiner(aEui64, 0); // remove immediately for (Joiner *joiner = &mJoiners[0]; joiner < OT_ARRAY_END(mJoiners); joiner++) { if (joiner->mValid) { continue; } if (aEui64 != NULL) { joiner->mEui64 = *aEui64; joiner->mAny = false; } else { joiner->mAny = true; } (void)strlcpy(joiner->mPsk, aPskd, sizeof(joiner->mPsk)); joiner->mValid = true; joiner->mExpirationTime = TimerMilli::GetNow() + Time::SecToMsec(aTimeout); UpdateJoinerExpirationTimer(); SendCommissionerSet(); otLogInfoMeshCoP("Added Joiner (%s, %s)", (aEui64 != NULL) ? aEui64->ToString().AsCString() : "*", aPskd); ExitNow(error = OT_ERROR_NONE); } exit: return error; } otError Commissioner::GetNextJoinerInfo(uint16_t &aIterator, otJoinerInfo &aJoiner) const { otError error = OT_ERROR_NONE; size_t index; for (index = aIterator; index < OT_ARRAY_LENGTH(mJoiners); index++) { if (!mJoiners[index].mValid) { continue; } memset(&aJoiner, 0, sizeof(aJoiner)); aJoiner.mAny = mJoiners[index].mAny; aJoiner.mEui64 = mJoiners[index].mEui64; strlcpy(aJoiner.mPsk, mJoiners[index].mPsk, sizeof(aJoiner.mPsk)); aJoiner.mExpirationTime = mJoiners[index].mExpirationTime - TimerMilli::GetNow(); aIterator = static_cast<uint16_t>(index) + 1; ExitNow(); } error = OT_ERROR_NOT_FOUND; exit: return error; } otError Commissioner::RemoveJoiner(const Mac::ExtAddress *aEui64, uint32_t aDelay) { otError error = OT_ERROR_NOT_FOUND; VerifyOrExit(mState == OT_COMMISSIONER_STATE_ACTIVE, error = OT_ERROR_INVALID_STATE); for (Joiner *joiner = &mJoiners[0]; joiner < OT_ARRAY_END(mJoiners); joiner++) { if (!joiner->mValid) { continue; } if (aEui64 != NULL) { if (joiner->mEui64 != *aEui64) { continue; } } else if (!joiner->mAny) { continue; } if (aDelay > 0) { TimeMilli now = TimerMilli::GetNow(); if ((joiner->mExpirationTime > now) && (joiner->mExpirationTime - now > Time::SecToMsec(aDelay))) { joiner->mExpirationTime = now + Time::SecToMsec(aDelay); UpdateJoinerExpirationTimer(); } } else { Mac::ExtAddress joinerId; joiner->mValid = false; UpdateJoinerExpirationTimer(); SendCommissionerSet(); otLogInfoMeshCoP("Removed Joiner (%s)", (aEui64 != NULL) ? aEui64->ToString().AsCString() : "*"); ComputeJoinerId(joiner->mEui64, joinerId); SignalJoinerEvent(OT_COMMISSIONER_JOINER_REMOVED, joinerId); } ExitNow(error = OT_ERROR_NONE); } exit: return error; } otError Commissioner::SetProvisioningUrl(const char *aProvisioningUrl) { otError error = OT_ERROR_NONE; uint8_t len; if (aProvisioningUrl == NULL) { mProvisioningUrl[0] = '\0'; ExitNow(); } len = static_cast<uint8_t>(strnlen(aProvisioningUrl, sizeof(mProvisioningUrl))); VerifyOrExit(len < sizeof(mProvisioningUrl), error = OT_ERROR_INVALID_ARGS); memcpy(mProvisioningUrl, aProvisioningUrl, len); mProvisioningUrl[len] = '\0'; exit: return error; } void Commissioner::HandleTimer(Timer &aTimer) { aTimer.GetOwner<Commissioner>().HandleTimer(); } void Commissioner::HandleTimer(void) { switch (mState) { case OT_COMMISSIONER_STATE_DISABLED: break; case OT_COMMISSIONER_STATE_PETITION: SendPetition(); break; case OT_COMMISSIONER_STATE_ACTIVE: SendKeepAlive(); break; } } void Commissioner::HandleJoinerExpirationTimer(Timer &aTimer) { aTimer.GetOwner<Commissioner>().HandleJoinerExpirationTimer(); } void Commissioner::HandleJoinerExpirationTimer(void) { TimeMilli now = TimerMilli::GetNow(); // Remove Joiners. for (Joiner *joiner = &mJoiners[0]; joiner < OT_ARRAY_END(mJoiners); joiner++) { if (!joiner->mValid) { continue; } if (now >= joiner->mExpirationTime) { otLogDebgMeshCoP("removing joiner due to timeout or successfully joined"); RemoveJoiner(&joiner->mEui64, 0); // remove immediately } } UpdateJoinerExpirationTimer(); } void Commissioner::UpdateJoinerExpirationTimer(void) { TimeMilli now = TimerMilli::GetNow(); uint32_t nextTimeout = TimeMilli::kMaxDuration; // Check if timer should be set for next Joiner. for (Joiner *joiner = &mJoiners[0]; joiner < OT_ARRAY_END(mJoiners); joiner++) { uint32_t diff; if (!joiner->mValid) { continue; } if (now >= joiner->mExpirationTime) { nextTimeout = 0; break; } diff = joiner->mExpirationTime - now; if (diff < nextTimeout) { nextTimeout = diff; } } if (nextTimeout != TimeMilli::kMaxDuration) { // Update the timer to the timeout of the next Joiner. mJoinerExpirationTimer.Start(nextTimeout); } else { // No Joiners, stop the timer. mJoinerExpirationTimer.Stop(); } } otError Commissioner::SendMgmtCommissionerGetRequest(const uint8_t *aTlvs, uint8_t aLength) { otError error = OT_ERROR_NONE; Coap::Message * message; Ip6::MessageInfo messageInfo; MeshCoP::Tlv tlv; VerifyOrExit((message = NewMeshCoPMessage(Get<Coap::Coap>())) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = message->Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST, OT_URI_PATH_COMMISSIONER_GET)); if (aLength > 0) { SuccessOrExit(error = message->SetPayloadMarker()); } if (aLength > 0) { tlv.SetType(MeshCoP::Tlv::kGet); tlv.SetLength(aLength); SuccessOrExit(error = message->Append(&tlv, sizeof(tlv))); SuccessOrExit(error = message->Append(aTlvs, aLength)); } messageInfo.SetSockAddr(Get<Mle::MleRouter>().GetMeshLocal16()); SuccessOrExit(error = Get<Mle::MleRouter>().GetLeaderAloc(messageInfo.GetPeerAddr())); messageInfo.SetPeerPort(kCoapUdpPort); SuccessOrExit(error = Get<Coap::Coap>().SendMessage(*message, messageInfo, Commissioner::HandleMgmtCommissionerGetResponse, this)); otLogInfoMeshCoP("sent MGMT_COMMISSIONER_GET.req to leader"); exit: if (error != OT_ERROR_NONE && message != NULL) { message->Free(); } return error; } void Commissioner::HandleMgmtCommissionerGetResponse(void * aContext, otMessage * aMessage, const otMessageInfo *aMessageInfo, otError aResult) { static_cast<Commissioner *>(aContext)->HandleMgmtCommissionerGetResponse( static_cast<Coap::Message *>(aMessage), static_cast<const Ip6::MessageInfo *>(aMessageInfo), aResult); } void Commissioner::HandleMgmtCommissionerGetResponse(Coap::Message * aMessage, const Ip6::MessageInfo *aMessageInfo, otError aResult) { OT_UNUSED_VARIABLE(aMessageInfo); VerifyOrExit(aResult == OT_ERROR_NONE && aMessage->GetCode() == OT_COAP_CODE_CHANGED); otLogInfoMeshCoP("received MGMT_COMMISSIONER_GET response"); exit: return; } otError Commissioner::SendMgmtCommissionerSetRequest(const otCommissioningDataset &aDataset, const uint8_t * aTlvs, uint8_t aLength) { otError error = OT_ERROR_NONE; Coap::Message * message; Ip6::MessageInfo messageInfo; VerifyOrExit((message = NewMeshCoPMessage(Get<Coap::Coap>())) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = message->Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST, OT_URI_PATH_COMMISSIONER_SET)); SuccessOrExit(error = message->SetPayloadMarker()); if (aDataset.mIsLocatorSet) { MeshCoP::BorderAgentLocatorTlv locator; locator.Init(); locator.SetBorderAgentLocator(aDataset.mLocator); SuccessOrExit(error = message->AppendTlv(locator)); } if (aDataset.mIsSessionIdSet) { MeshCoP::CommissionerSessionIdTlv sessionId; sessionId.Init(); sessionId.SetCommissionerSessionId(aDataset.mSessionId); SuccessOrExit(error = message->AppendTlv(sessionId)); } if (aDataset.mIsSteeringDataSet) { MeshCoP::SteeringDataTlv steeringData; steeringData.Init(); steeringData.SetLength(aDataset.mSteeringData.mLength); SuccessOrExit(error = message->Append(&steeringData, sizeof(MeshCoP::Tlv))); SuccessOrExit(error = message->Append(&aDataset.mSteeringData.m8, aDataset.mSteeringData.mLength)); } if (aDataset.mIsJoinerUdpPortSet) { MeshCoP::JoinerUdpPortTlv joinerUdpPort; joinerUdpPort.Init(); joinerUdpPort.SetUdpPort(aDataset.mJoinerUdpPort); SuccessOrExit(error = message->AppendTlv(joinerUdpPort)); } if (aLength > 0) { SuccessOrExit(error = message->Append(aTlvs, aLength)); } if (message->GetLength() == message->GetOffset()) { // no payload, remove coap payload marker message->SetLength(message->GetLength() - 1); } messageInfo.SetSockAddr(Get<Mle::MleRouter>().GetMeshLocal16()); SuccessOrExit(error = Get<Mle::MleRouter>().GetLeaderAloc(messageInfo.GetPeerAddr())); messageInfo.SetPeerPort(kCoapUdpPort); SuccessOrExit(error = Get<Coap::Coap>().SendMessage(*message, messageInfo, Commissioner::HandleMgmtCommissionerSetResponse, this)); otLogInfoMeshCoP("sent MGMT_COMMISSIONER_SET.req to leader"); exit: if (error != OT_ERROR_NONE && message != NULL) { message->Free(); } return error; } void Commissioner::HandleMgmtCommissionerSetResponse(void * aContext, otMessage * aMessage, const otMessageInfo *aMessageInfo, otError aResult) { static_cast<Commissioner *>(aContext)->HandleMgmtCommissionerSetResponse( static_cast<Coap::Message *>(aMessage), static_cast<const Ip6::MessageInfo *>(aMessageInfo), aResult); } void Commissioner::HandleMgmtCommissionerSetResponse(Coap::Message * aMessage, const Ip6::MessageInfo *aMessageInfo, otError aResult) { OT_UNUSED_VARIABLE(aMessageInfo); VerifyOrExit(aResult == OT_ERROR_NONE && aMessage->GetCode() == OT_COAP_CODE_CHANGED); otLogInfoMeshCoP("received MGMT_COMMISSIONER_SET response"); exit: return; } otError Commissioner::SendPetition(void) { otError error = OT_ERROR_NONE; Coap::Message * message = NULL; Ip6::MessageInfo messageInfo; CommissionerIdTlv commissionerId; mTransmitAttempts++; VerifyOrExit((message = NewMeshCoPMessage(Get<Coap::Coap>())) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = message->Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST, OT_URI_PATH_LEADER_PETITION)); SuccessOrExit(error = message->SetPayloadMarker()); commissionerId.Init(); commissionerId.SetCommissionerId("OpenThread Commissioner"); SuccessOrExit(error = message->AppendTlv(commissionerId)); SuccessOrExit(error = Get<Mle::MleRouter>().GetLeaderAloc(messageInfo.GetPeerAddr())); messageInfo.SetPeerPort(kCoapUdpPort); messageInfo.SetSockAddr(Get<Mle::MleRouter>().GetMeshLocal16()); SuccessOrExit( error = Get<Coap::Coap>().SendMessage(*message, messageInfo, Commissioner::HandleLeaderPetitionResponse, this)); otLogInfoMeshCoP("sent petition"); exit: if (error != OT_ERROR_NONE && message != NULL) { message->Free(); } return error; } void Commissioner::HandleLeaderPetitionResponse(void * aContext, otMessage * aMessage, const otMessageInfo *aMessageInfo, otError aResult) { static_cast<Commissioner *>(aContext)->HandleLeaderPetitionResponse( static_cast<Coap::Message *>(aMessage), static_cast<const Ip6::MessageInfo *>(aMessageInfo), aResult); } void Commissioner::HandleLeaderPetitionResponse(Coap::Message * aMessage, const Ip6::MessageInfo *aMessageInfo, otError aResult) { OT_UNUSED_VARIABLE(aMessageInfo); StateTlv state; CommissionerSessionIdTlv sessionId; bool retransmit = false; VerifyOrExit(mState == OT_COMMISSIONER_STATE_PETITION, SetState(OT_COMMISSIONER_STATE_DISABLED)); VerifyOrExit(aResult == OT_ERROR_NONE && aMessage->GetCode() == OT_COAP_CODE_CHANGED, retransmit = true); otLogInfoMeshCoP("received Leader Petition response"); SuccessOrExit(Tlv::GetTlv(*aMessage, Tlv::kState, sizeof(state), state)); VerifyOrExit(state.IsValid()); VerifyOrExit(state.GetState() == StateTlv::kAccept, SetState(OT_COMMISSIONER_STATE_DISABLED)); SuccessOrExit(Tlv::GetTlv(*aMessage, Tlv::kCommissionerSessionId, sizeof(sessionId), sessionId)); VerifyOrExit(sessionId.IsValid()); mSessionId = sessionId.GetCommissionerSessionId(); Get<Mle::MleRouter>().GetCommissionerAloc(mCommissionerAloc.GetAddress(), mSessionId); Get<ThreadNetif>().AddUnicastAddress(mCommissionerAloc); AddCoapResources(); SetState(OT_COMMISSIONER_STATE_ACTIVE); mTransmitAttempts = 0; mTimer.Start(Time::SecToMsec(kKeepAliveTimeout) / 2); exit: if (retransmit) { if (mTransmitAttempts >= kPetitionRetryCount) { SetState(OT_COMMISSIONER_STATE_DISABLED); } else { mTimer.Start(Time::SecToMsec(kPetitionRetryDelay)); } } } otError Commissioner::SendKeepAlive(void) { otError error = OT_ERROR_NONE; Coap::Message * message = NULL; Ip6::MessageInfo messageInfo; StateTlv state; CommissionerSessionIdTlv sessionId; VerifyOrExit((message = NewMeshCoPMessage(Get<Coap::Coap>())) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = message->Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST, OT_URI_PATH_LEADER_KEEP_ALIVE)); SuccessOrExit(error = message->SetPayloadMarker()); state.Init(); state.SetState(mState == OT_COMMISSIONER_STATE_ACTIVE ? StateTlv::kAccept : StateTlv::kReject); SuccessOrExit(error = message->AppendTlv(state)); sessionId.Init(); sessionId.SetCommissionerSessionId(mSessionId); SuccessOrExit(error = message->AppendTlv(sessionId)); messageInfo.SetSockAddr(Get<Mle::MleRouter>().GetMeshLocal16()); SuccessOrExit(error = Get<Mle::MleRouter>().GetLeaderAloc(messageInfo.GetPeerAddr())); messageInfo.SetPeerPort(kCoapUdpPort); SuccessOrExit(error = Get<Coap::Coap>().SendMessage(*message, messageInfo, Commissioner::HandleLeaderKeepAliveResponse, this)); otLogInfoMeshCoP("sent keep alive"); exit: if (error != OT_ERROR_NONE && message != NULL) { message->Free(); } return error; } void Commissioner::HandleLeaderKeepAliveResponse(void * aContext, otMessage * aMessage, const otMessageInfo *aMessageInfo, otError aResult) { static_cast<Commissioner *>(aContext)->HandleLeaderKeepAliveResponse( static_cast<Coap::Message *>(aMessage), static_cast<const Ip6::MessageInfo *>(aMessageInfo), aResult); } void Commissioner::HandleLeaderKeepAliveResponse(Coap::Message * aMessage, const Ip6::MessageInfo *aMessageInfo, otError aResult) { OT_UNUSED_VARIABLE(aMessageInfo); StateTlv state; VerifyOrExit(mState == OT_COMMISSIONER_STATE_ACTIVE, SetState(OT_COMMISSIONER_STATE_DISABLED)); VerifyOrExit(aResult == OT_ERROR_NONE && aMessage->GetCode() == OT_COAP_CODE_CHANGED, SetState(OT_COMMISSIONER_STATE_DISABLED)); otLogInfoMeshCoP("received Leader keep-alive response"); SuccessOrExit(Tlv::GetTlv(*aMessage, Tlv::kState, sizeof(state), state)); VerifyOrExit(state.IsValid()); VerifyOrExit(state.GetState() == StateTlv::kAccept, SetState(OT_COMMISSIONER_STATE_DISABLED)); mTimer.Start(Time::SecToMsec(kKeepAliveTimeout) / 2); exit: if (mState != OT_COMMISSIONER_STATE_ACTIVE) { Get<ThreadNetif>().RemoveUnicastAddress(mCommissionerAloc); RemoveCoapResources(); } } void Commissioner::HandleRelayReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo) { static_cast<Commissioner *>(aContext)->HandleRelayReceive(*static_cast<Coap::Message *>(aMessage), *static_cast<const Ip6::MessageInfo *>(aMessageInfo)); } void Commissioner::HandleRelayReceive(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { OT_UNUSED_VARIABLE(aMessageInfo); otError error; JoinerUdpPortTlv joinerPort; JoinerIidTlv joinerIid; JoinerRouterLocatorTlv joinerRloc; Ip6::MessageInfo joinerMessageInfo; uint16_t offset; uint16_t length; bool enableJoiner = false; Mac::ExtAddress receivedId; Mac::ExtAddress joinerId; VerifyOrExit(mState == OT_COMMISSIONER_STATE_ACTIVE, error = OT_ERROR_INVALID_STATE); VerifyOrExit(aMessage.GetType() == OT_COAP_TYPE_NON_CONFIRMABLE && aMessage.GetCode() == OT_COAP_CODE_POST); SuccessOrExit(error = Tlv::GetTlv(aMessage, Tlv::kJoinerUdpPort, sizeof(joinerPort), joinerPort)); VerifyOrExit(joinerPort.IsValid(), error = OT_ERROR_PARSE); SuccessOrExit(error = Tlv::GetTlv(aMessage, Tlv::kJoinerIid, sizeof(joinerIid), joinerIid)); VerifyOrExit(joinerIid.IsValid(), error = OT_ERROR_PARSE); SuccessOrExit(error = Tlv::GetTlv(aMessage, Tlv::kJoinerRouterLocator, sizeof(joinerRloc), joinerRloc)); VerifyOrExit(joinerRloc.IsValid(), error = OT_ERROR_PARSE); SuccessOrExit(error = Tlv::GetValueOffset(aMessage, Tlv::kJoinerDtlsEncapsulation, offset, length)); VerifyOrExit(length <= aMessage.GetLength() - offset, error = OT_ERROR_PARSE); if (!Get<Coap::CoapSecure>().IsConnectionActive()) { memcpy(mJoinerIid, joinerIid.GetIid(), sizeof(mJoinerIid)); receivedId.Set(mJoinerIid); receivedId.ToggleLocal(); for (Joiner *joiner = &mJoiners[0]; joiner < OT_ARRAY_END(mJoiners); joiner++) { if (!joiner->mValid) { continue; } ComputeJoinerId(joiner->mEui64, joinerId); if (joiner->mAny || (joinerId == receivedId)) { error = Get<Coap::CoapSecure>().SetPsk(reinterpret_cast<const uint8_t *>(joiner->mPsk), static_cast<uint8_t>(strlen(joiner->mPsk))); SuccessOrExit(error); mJoinerIndex = static_cast<uint8_t>(joiner - mJoiners); enableJoiner = true; otLogInfoMeshCoP("found joiner, starting new session"); SignalJoinerEvent(OT_COMMISSIONER_JOINER_START, joinerId); break; } } } else { enableJoiner = (memcmp(mJoinerIid, joinerIid.GetIid(), sizeof(mJoinerIid)) == 0); } VerifyOrExit(enableJoiner); mJoinerPort = joinerPort.GetUdpPort(); mJoinerRloc = joinerRloc.GetJoinerRouterLocator(); otLogInfoMeshCoP("Remove Relay Receive (%02x%02x%02x%02x%02x%02x%02x%02x, 0x%04x)", mJoinerIid[0], mJoinerIid[1], mJoinerIid[2], mJoinerIid[3], mJoinerIid[4], mJoinerIid[5], mJoinerIid[6], mJoinerIid[7], mJoinerRloc); aMessage.SetOffset(offset); SuccessOrExit(error = aMessage.SetLength(offset + length)); joinerMessageInfo.SetPeerAddr(Get<Mle::MleRouter>().GetMeshLocal64()); joinerMessageInfo.GetPeerAddr().SetIid(mJoinerIid); joinerMessageInfo.SetPeerPort(mJoinerPort); Get<Coap::CoapSecure>().HandleUdpReceive(aMessage, joinerMessageInfo); exit: return; } void Commissioner::HandleDatasetChanged(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo) { static_cast<Commissioner *>(aContext)->HandleDatasetChanged(*static_cast<Coap::Message *>(aMessage), *static_cast<const Ip6::MessageInfo *>(aMessageInfo)); } void Commissioner::HandleDatasetChanged(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { VerifyOrExit(aMessage.GetType() == OT_COAP_TYPE_CONFIRMABLE && aMessage.GetCode() == OT_COAP_CODE_POST); otLogInfoMeshCoP("received dataset changed"); SuccessOrExit(Get<Coap::Coap>().SendEmptyAck(aMessage, aMessageInfo)); otLogInfoMeshCoP("sent dataset changed acknowledgment"); exit: return; } void Commissioner::HandleJoinerFinalize(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo) { static_cast<Commissioner *>(aContext)->HandleJoinerFinalize(*static_cast<Coap::Message *>(aMessage), *static_cast<const Ip6::MessageInfo *>(aMessageInfo)); } void Commissioner::HandleJoinerFinalize(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { OT_UNUSED_VARIABLE(aMessageInfo); StateTlv::State state = StateTlv::kAccept; ProvisioningUrlTlv provisioningUrl; otLogInfoMeshCoP("received joiner finalize"); if (Tlv::GetTlv(aMessage, Tlv::kProvisioningUrl, sizeof(provisioningUrl), provisioningUrl) == OT_ERROR_NONE) { uint8_t len = static_cast<uint8_t>(strnlen(mProvisioningUrl, sizeof(mProvisioningUrl))); if ((provisioningUrl.GetProvisioningUrlLength() != len) || !memcmp(provisioningUrl.GetProvisioningUrl(), mProvisioningUrl, len)) { state = StateTlv::kReject; } } #if OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE if (aMessage.GetLength() <= OPENTHREAD_CONFIG_MESSAGE_BUFFER_SIZE) { uint8_t buf[OPENTHREAD_CONFIG_MESSAGE_BUFFER_SIZE]; aMessage.Read(aMessage.GetOffset(), aMessage.GetLength() - aMessage.GetOffset(), buf); otDumpCertMeshCoP("[THCI] direction=recv | type=JOIN_FIN.req |", buf, aMessage.GetLength() - aMessage.GetOffset()); } #endif SendJoinFinalizeResponse(aMessage, state); } void Commissioner::SendJoinFinalizeResponse(const Coap::Message &aRequest, StateTlv::State aState) { otError error = OT_ERROR_NONE; Ip6::MessageInfo joinerMessageInfo; MeshCoP::StateTlv stateTlv; Coap::Message * message; Mac::ExtAddress joinerId; VerifyOrExit((message = NewMeshCoPMessage(Get<Coap::CoapSecure>())) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = message->SetDefaultResponseHeader(aRequest)); SuccessOrExit(error = message->SetPayloadMarker()); message->SetOffset(message->GetLength()); message->SetSubType(Message::kSubTypeJoinerFinalizeResponse); stateTlv.Init(); stateTlv.SetState(aState); SuccessOrExit(error = message->AppendTlv(stateTlv)); joinerMessageInfo.SetPeerAddr(Get<Mle::MleRouter>().GetMeshLocal64()); joinerMessageInfo.GetPeerAddr().SetIid(mJoinerIid); joinerMessageInfo.SetPeerPort(mJoinerPort); #if OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE uint8_t buf[OPENTHREAD_CONFIG_MESSAGE_BUFFER_SIZE]; VerifyOrExit(message->GetLength() <= sizeof(buf)); message->Read(message->GetOffset(), message->GetLength() - message->GetOffset(), buf); otDumpCertMeshCoP("[THCI] direction=send | type=JOIN_FIN.rsp |", buf, message->GetLength() - message->GetOffset()); #endif SuccessOrExit(error = Get<Coap::CoapSecure>().SendMessage(*message, joinerMessageInfo)); joinerId.Set(mJoinerIid); joinerId.ToggleLocal(); SignalJoinerEvent(OT_COMMISSIONER_JOINER_FINALIZE, joinerId); if (!mJoiners[mJoinerIndex].mAny) { // remove after kRemoveJoinerDelay (seconds) RemoveJoiner(&mJoiners[mJoinerIndex].mEui64, kRemoveJoinerDelay); } otLogInfoMeshCoP("sent joiner finalize response"); exit: if (error != OT_ERROR_NONE && message != NULL) { message->Free(); } } otError Commissioner::SendRelayTransmit(void *aContext, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { return static_cast<Commissioner *>(aContext)->SendRelayTransmit(aMessage, aMessageInfo); } otError Commissioner::SendRelayTransmit(Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { OT_UNUSED_VARIABLE(aMessageInfo); otError error = OT_ERROR_NONE; JoinerUdpPortTlv udpPort; JoinerIidTlv iid; JoinerRouterLocatorTlv rloc; ExtendedTlv tlv; Coap::Message * message; uint16_t offset; Ip6::MessageInfo messageInfo; VerifyOrExit((message = NewMeshCoPMessage(Get<Coap::Coap>())) != NULL, error = OT_ERROR_NO_BUFS); message->Init(OT_COAP_TYPE_NON_CONFIRMABLE, OT_COAP_CODE_POST); SuccessOrExit(error = message->AppendUriPathOptions(OT_URI_PATH_RELAY_TX)); SuccessOrExit(error = message->SetPayloadMarker()); udpPort.Init(); udpPort.SetUdpPort(mJoinerPort); SuccessOrExit(error = message->AppendTlv(udpPort)); iid.Init(); iid.SetIid(mJoinerIid); SuccessOrExit(error = message->AppendTlv(iid)); rloc.Init(); rloc.SetJoinerRouterLocator(mJoinerRloc); SuccessOrExit(error = message->AppendTlv(rloc)); if (aMessage.GetSubType() == Message::kSubTypeJoinerFinalizeResponse) { JoinerRouterKekTlv kek; kek.Init(); kek.SetKek(Get<KeyManager>().GetKek()); SuccessOrExit(error = message->AppendTlv(kek)); } tlv.SetType(Tlv::kJoinerDtlsEncapsulation); tlv.SetLength(aMessage.GetLength()); SuccessOrExit(error = message->Append(&tlv, sizeof(tlv))); offset = message->GetLength(); SuccessOrExit(error = message->SetLength(offset + aMessage.GetLength())); aMessage.CopyTo(0, offset, aMessage.GetLength(), *message); messageInfo.SetPeerAddr(Get<Mle::MleRouter>().GetMeshLocal16()); messageInfo.GetPeerAddr().mFields.m16[7] = HostSwap16(mJoinerRloc); messageInfo.SetPeerPort(kCoapUdpPort); SuccessOrExit(error = Get<Coap::Coap>().SendMessage(*message, messageInfo)); aMessage.Free(); exit: if (error != OT_ERROR_NONE && message != NULL) { message->Free(); } return error; } otError Commissioner::GeneratePskc(const char * aPassPhrase, const char * aNetworkName, const Mac::ExtendedPanId &aExtPanId, Pskc & aPskc) { otError error = OT_ERROR_NONE; const char *saltPrefix = "Thread"; uint8_t salt[OT_PBKDF2_SALT_MAX_LEN]; uint16_t saltLen = 0; VerifyOrExit((strlen(aPassPhrase) >= OT_COMMISSIONING_PASSPHRASE_MIN_SIZE) && (strlen(aPassPhrase) <= OT_COMMISSIONING_PASSPHRASE_MAX_SIZE) && (strlen(aNetworkName) <= OT_NETWORK_NAME_MAX_SIZE), error = OT_ERROR_INVALID_ARGS); memset(salt, 0, sizeof(salt)); memcpy(salt, saltPrefix, strlen(saltPrefix)); saltLen += static_cast<uint16_t>(strlen(saltPrefix)); memcpy(salt + saltLen, aExtPanId.m8, sizeof(aExtPanId)); saltLen += OT_EXT_PAN_ID_SIZE; memcpy(salt + saltLen, aNetworkName, strlen(aNetworkName)); saltLen += static_cast<uint16_t>(strlen(aNetworkName)); otPbkdf2Cmac(reinterpret_cast<const uint8_t *>(aPassPhrase), static_cast<uint16_t>(strlen(aPassPhrase)), reinterpret_cast<const uint8_t *>(salt), saltLen, 16384, OT_PSKC_MAX_SIZE, aPskc.m8); exit: return error; } // LCOV_EXCL_START #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MLE == 1) const char *Commissioner::StateToString(otCommissionerState aState) { const char *str = "Unknown"; switch (aState) { case OT_COMMISSIONER_STATE_DISABLED: str = "disabled"; break; case OT_COMMISSIONER_STATE_PETITION: str = "petition"; break; case OT_COMMISSIONER_STATE_ACTIVE: str = "active"; break; default: break; } return str; } #endif // (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MLE == 1) // LCOV_EXCL_STOP } // namespace MeshCoP } // namespace ot #endif // OPENTHREAD_FTD && OPENTHREAD_CONFIG_COMMISSIONER_ENABLE
null
/* * Copyright (c) 2016, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * This file implements a Commissioner role. */ #include "commissioner.hpp" #include <stdio.h> #include "utils/wrap_string.h" #include "coap/coap_message.hpp" #include "common/encoding.hpp" #include "common/instance.hpp" #include "common/locator-getters.hpp" #include "common/logging.hpp" #include "crypto/pbkdf2_cmac.h" #include "meshcop/joiner_router.hpp" #include "meshcop/meshcop.hpp" #include "meshcop/meshcop_tlvs.hpp" #include "thread/thread_netif.hpp" #include "thread/thread_tlvs.hpp" #include "thread/thread_uri_paths.hpp" #if OPENTHREAD_FTD && OPENTHREAD_CONFIG_COMMISSIONER_ENABLE namespace ot { namespace MeshCoP { Commissioner::Commissioner(Instance &aInstance) : InstanceLocator(aInstance) , mJoinerPort(0) , mJoinerRloc(0) , mSessionId(0) , mJoinerIndex(0) , mTransmitAttempts(0) , mJoinerExpirationTimer(aInstance, HandleJoinerExpirationTimer, this) , mTimer(aInstance, HandleTimer, this) , mRelayReceive(OT_URI_PATH_RELAY_RX, &Commissioner::HandleRelayReceive, this) , mDatasetChanged(OT_URI_PATH_DATASET_CHANGED, &Commissioner::HandleDatasetChanged, this) , mJoinerFinalize(OT_URI_PATH_JOINER_FINALIZE, &Commissioner::HandleJoinerFinalize, this) , mAnnounceBegin(aInstance) , mEnergyScan(aInstance) , mPanIdQuery(aInstance) , mStateCallback(NULL) , mJoinerCallback(NULL) , mCallbackContext(NULL) , mState(OT_COMMISSIONER_STATE_DISABLED) { memset(mJoiners, 0, sizeof(mJoiners)); mCommissionerAloc.Clear(); mCommissionerAloc.mPrefixLength = 64; mCommissionerAloc.mPreferred = true; mCommissionerAloc.mValid = true; mCommissionerAloc.mScopeOverride = Ip6::Address::kRealmLocalScope; mCommissionerAloc.mScopeOverrideValid = true; mProvisioningUrl[0] = '\0'; } void Commissioner::SetState(otCommissionerState aState) { VerifyOrExit(mState != aState); otLogInfoMeshCoP("Commissioner State: %s -> %s", StateToString(mState), StateToString(aState)); mState = aState; if (mStateCallback) { mStateCallback(mState, mCallbackContext); } exit: return; } void Commissioner::SignalJoinerEvent(otCommissionerJoinerEvent aEvent, const Mac::ExtAddress &aJoinerId) { if (mJoinerCallback) { mJoinerCallback(aEvent, &aJoinerId, mCallbackContext); } } void Commissioner::AddCoapResources(void) { Get<Coap::Coap>().AddResource(mRelayReceive); Get<Coap::Coap>().AddResource(mDatasetChanged); Get<Coap::CoapSecure>().AddResource(mJoinerFinalize); } void Commissioner::RemoveCoapResources(void) { Get<Coap::Coap>().RemoveResource(mRelayReceive); Get<Coap::Coap>().RemoveResource(mDatasetChanged); Get<Coap::CoapSecure>().RemoveResource(mJoinerFinalize); } void Commissioner::HandleCoapsConnected(bool aConnected, void *aContext) { static_cast<Commissioner *>(aContext)->HandleCoapsConnected(aConnected); } void Commissioner::HandleCoapsConnected(bool aConnected) { otCommissionerJoinerEvent event; Mac::ExtAddress joinerId; event = aConnected ? OT_COMMISSIONER_JOINER_CONNECTED : OT_COMMISSIONER_JOINER_END; joinerId.Set(mJoinerIid); joinerId.ToggleLocal(); SignalJoinerEvent(event, joinerId); } otError Commissioner::Start(otCommissionerStateCallback aStateCallback, otCommissionerJoinerCallback aJoinerCallback, void * aCallbackContext) { otError error = OT_ERROR_NONE; VerifyOrExit(Get<Mle::MleRouter>().IsAttached(), error = OT_ERROR_INVALID_STATE); VerifyOrExit(mState == OT_COMMISSIONER_STATE_DISABLED, error = OT_ERROR_INVALID_STATE); SuccessOrExit(error = Get<Coap::CoapSecure>().Start(SendRelayTransmit, this)); Get<Coap::CoapSecure>().SetConnectedCallback(&Commissioner::HandleCoapsConnected, this); mStateCallback = aStateCallback; mJoinerCallback = aJoinerCallback; mCallbackContext = aCallbackContext; mTransmitAttempts = 0; SuccessOrExit(error = SendPetition()); SetState(OT_COMMISSIONER_STATE_PETITION); exit: return error; } otError Commissioner::Stop(void) { otError error = OT_ERROR_NONE; VerifyOrExit(mState != OT_COMMISSIONER_STATE_DISABLED, error = OT_ERROR_INVALID_STATE); Get<Coap::CoapSecure>().Stop(); Get<ThreadNetif>().RemoveUnicastAddress(mCommissionerAloc); RemoveCoapResources(); ClearJoiners(); mTransmitAttempts = 0; mTimer.Stop(); Get<Coap::CoapSecure>().Stop(); SetState(OT_COMMISSIONER_STATE_DISABLED); SendKeepAlive(); exit: return error; } otError Commissioner::SendCommissionerSet(void) { otError error; otCommissioningDataset dataset; SteeringDataTlv steeringData; Mac::ExtAddress joinerId; VerifyOrExit(mState == OT_COMMISSIONER_STATE_ACTIVE, error = OT_ERROR_INVALID_STATE); memset(&dataset, 0, sizeof(dataset)); // session id dataset.mSessionId = mSessionId; dataset.mIsSessionIdSet = true; // compute bloom filter steeringData.Init(); steeringData.Clear(); for (Joiner *joiner = &mJoiners[0]; joiner < OT_ARRAY_END(mJoiners); joiner++) { if (!joiner->mValid) { continue; } if (joiner->mAny) { steeringData.SetLength(1); steeringData.Set(); break; } ComputeJoinerId(joiner->mEui64, joinerId); steeringData.ComputeBloomFilter(joinerId); } // set bloom filter dataset.mSteeringData.mLength = steeringData.GetSteeringDataLength(); memcpy(dataset.mSteeringData.m8, steeringData.GetValue(), dataset.mSteeringData.mLength); dataset.mIsSteeringDataSet = true; SuccessOrExit(error = SendMgmtCommissionerSetRequest(dataset, NULL, 0)); exit: return error; } void Commissioner::ClearJoiners(void) { for (Joiner *joiner = &mJoiners[0]; joiner < OT_ARRAY_END(mJoiners); joiner++) { joiner->mValid = false; } SendCommissionerSet(); } otError Commissioner::AddJoiner(const Mac::ExtAddress *aEui64, const char *aPskd, uint32_t aTimeout) { otError error = OT_ERROR_NO_BUFS; VerifyOrExit(mState == OT_COMMISSIONER_STATE_ACTIVE, error = OT_ERROR_INVALID_STATE); VerifyOrExit(strnlen(aPskd, Dtls::kPskMaxLength + 1) <= Dtls::kPskMaxLength, error = OT_ERROR_INVALID_ARGS); RemoveJoiner(aEui64, 0); // remove immediately for (Joiner *joiner = &mJoiners[0]; joiner < OT_ARRAY_END(mJoiners); joiner++) { if (joiner->mValid) { continue; } if (aEui64 != NULL) { joiner->mEui64 = *aEui64; joiner->mAny = false; } else { joiner->mAny = true; } (void)strlcpy(joiner->mPsk, aPskd, sizeof(joiner->mPsk)); joiner->mValid = true; joiner->mExpirationTime = TimerMilli::GetNow() + Time::SecToMsec(aTimeout); UpdateJoinerExpirationTimer(); SendCommissionerSet(); otLogInfoMeshCoP("Added Joiner (%s, %s)", (aEui64 != NULL) ? aEui64->ToString().AsCString() : "*", aPskd); ExitNow(error = OT_ERROR_NONE); } exit: return error; } otError Commissioner::GetNextJoinerInfo(uint16_t &aIterator, otJoinerInfo &aJoiner) const { otError error = OT_ERROR_NONE; size_t index; for (index = aIterator; index < OT_ARRAY_LENGTH(mJoiners); index++) { if (!mJoiners[index].mValid) { continue; } memset(&aJoiner, 0, sizeof(aJoiner)); aJoiner.mAny = mJoiners[index].mAny; aJoiner.mEui64 = mJoiners[index].mEui64; strlcpy(aJoiner.mPsk, mJoiners[index].mPsk, sizeof(aJoiner.mPsk)); aJoiner.mExpirationTime = mJoiners[index].mExpirationTime - TimerMilli::GetNow(); aIterator = static_cast<uint16_t>(index) + 1; ExitNow(); } error = OT_ERROR_NOT_FOUND; exit: return error; } otError Commissioner::RemoveJoiner(const Mac::ExtAddress *aEui64, uint32_t aDelay) { otError error = OT_ERROR_NOT_FOUND; VerifyOrExit(mState == OT_COMMISSIONER_STATE_ACTIVE, error = OT_ERROR_INVALID_STATE); for (Joiner *joiner = &mJoiners[0]; joiner < OT_ARRAY_END(mJoiners); joiner++) { if (!joiner->mValid) { continue; } if (aEui64 != NULL) { if (joiner->mEui64 != *aEui64) { continue; } } else if (!joiner->mAny) { continue; } if (aDelay > 0) { TimeMilli now = TimerMilli::GetNow(); if ((joiner->mExpirationTime > now) && (joiner->mExpirationTime - now > Time::SecToMsec(aDelay))) { joiner->mExpirationTime = now + Time::SecToMsec(aDelay); UpdateJoinerExpirationTimer(); } } else { Mac::ExtAddress joinerId; joiner->mValid = false; UpdateJoinerExpirationTimer(); SendCommissionerSet(); otLogInfoMeshCoP("Removed Joiner (%s)", (aEui64 != NULL) ? aEui64->ToString().AsCString() : "*"); ComputeJoinerId(joiner->mEui64, joinerId); SignalJoinerEvent(OT_COMMISSIONER_JOINER_REMOVED, joinerId); } ExitNow(error = OT_ERROR_NONE); } exit: return error; } otError Commissioner::SetProvisioningUrl(const char *aProvisioningUrl) { otError error = OT_ERROR_NONE; uint8_t len; if (aProvisioningUrl == NULL) { mProvisioningUrl[0] = '\0'; ExitNow(); } len = static_cast<uint8_t>(strnlen(aProvisioningUrl, sizeof(mProvisioningUrl))); VerifyOrExit(len < sizeof(mProvisioningUrl), error = OT_ERROR_INVALID_ARGS); memcpy(mProvisioningUrl, aProvisioningUrl, len); mProvisioningUrl[len] = '\0'; exit: return error; } void Commissioner::HandleTimer(Timer &aTimer) { aTimer.GetOwner<Commissioner>().HandleTimer(); } void Commissioner::HandleTimer(void) { switch (mState) { case OT_COMMISSIONER_STATE_DISABLED: break; case OT_COMMISSIONER_STATE_PETITION: SendPetition(); break; case OT_COMMISSIONER_STATE_ACTIVE: SendKeepAlive(); break; } } void Commissioner::HandleJoinerExpirationTimer(Timer &aTimer) { aTimer.GetOwner<Commissioner>().HandleJoinerExpirationTimer(); } void Commissioner::HandleJoinerExpirationTimer(void) { TimeMilli now = TimerMilli::GetNow(); // Remove Joiners. for (Joiner *joiner = &mJoiners[0]; joiner < OT_ARRAY_END(mJoiners); joiner++) { if (!joiner->mValid) { continue; } if (now >= joiner->mExpirationTime) { otLogDebgMeshCoP("removing joiner due to timeout or successfully joined"); RemoveJoiner(&joiner->mEui64, 0); // remove immediately } } UpdateJoinerExpirationTimer(); } void Commissioner::UpdateJoinerExpirationTimer(void) { TimeMilli now = TimerMilli::GetNow(); uint32_t nextTimeout = TimeMilli::kMaxDuration; // Check if timer should be set for next Joiner. for (Joiner *joiner = &mJoiners[0]; joiner < OT_ARRAY_END(mJoiners); joiner++) { uint32_t diff; if (!joiner->mValid) { continue; } if (now >= joiner->mExpirationTime) { nextTimeout = 0; break; } diff = joiner->mExpirationTime - now; if (diff < nextTimeout) { nextTimeout = diff; } } if (nextTimeout != TimeMilli::kMaxDuration) { // Update the timer to the timeout of the next Joiner. mJoinerExpirationTimer.Start(nextTimeout); } else { // No Joiners, stop the timer. mJoinerExpirationTimer.Stop(); } } otError Commissioner::SendMgmtCommissionerGetRequest(const uint8_t *aTlvs, uint8_t aLength) { otError error = OT_ERROR_NONE; Coap::Message * message; Ip6::MessageInfo messageInfo; MeshCoP::Tlv tlv; VerifyOrExit((message = NewMeshCoPMessage(Get<Coap::Coap>())) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = message->Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST, OT_URI_PATH_COMMISSIONER_GET)); if (aLength > 0) { SuccessOrExit(error = message->SetPayloadMarker()); } if (aLength > 0) { tlv.SetType(MeshCoP::Tlv::kGet); tlv.SetLength(aLength); SuccessOrExit(error = message->Append(&tlv, sizeof(tlv))); SuccessOrExit(error = message->Append(aTlvs, aLength)); } messageInfo.SetSockAddr(Get<Mle::MleRouter>().GetMeshLocal16()); SuccessOrExit(error = Get<Mle::MleRouter>().GetLeaderAloc(messageInfo.GetPeerAddr())); messageInfo.SetPeerPort(kCoapUdpPort); SuccessOrExit(error = Get<Coap::Coap>().SendMessage(*message, messageInfo, Commissioner::HandleMgmtCommissionerGetResponse, this)); otLogInfoMeshCoP("sent MGMT_COMMISSIONER_GET.req to leader"); exit: if (error != OT_ERROR_NONE && message != NULL) { message->Free(); } return error; } void Commissioner::HandleMgmtCommissionerGetResponse(void * aContext, otMessage * aMessage, const otMessageInfo *aMessageInfo, otError aResult) { static_cast<Commissioner *>(aContext)->HandleMgmtCommissionerGetResponse( static_cast<Coap::Message *>(aMessage), static_cast<const Ip6::MessageInfo *>(aMessageInfo), aResult); } void Commissioner::HandleMgmtCommissionerGetResponse(Coap::Message * aMessage, const Ip6::MessageInfo *aMessageInfo, otError aResult) { OT_UNUSED_VARIABLE(aMessageInfo); VerifyOrExit(aResult == OT_ERROR_NONE && aMessage->GetCode() == OT_COAP_CODE_CHANGED); otLogInfoMeshCoP("received MGMT_COMMISSIONER_GET response"); exit: return; } otError Commissioner::SendMgmtCommissionerSetRequest(const otCommissioningDataset &aDataset, const uint8_t * aTlvs, uint8_t aLength) { otError error = OT_ERROR_NONE; Coap::Message * message; Ip6::MessageInfo messageInfo; VerifyOrExit((message = NewMeshCoPMessage(Get<Coap::Coap>())) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = message->Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST, OT_URI_PATH_COMMISSIONER_SET)); SuccessOrExit(error = message->SetPayloadMarker()); if (aDataset.mIsLocatorSet) { MeshCoP::BorderAgentLocatorTlv locator; locator.Init(); locator.SetBorderAgentLocator(aDataset.mLocator); SuccessOrExit(error = message->AppendTlv(locator)); } if (aDataset.mIsSessionIdSet) { MeshCoP::CommissionerSessionIdTlv sessionId; sessionId.Init(); sessionId.SetCommissionerSessionId(aDataset.mSessionId); SuccessOrExit(error = message->AppendTlv(sessionId)); } if (aDataset.mIsSteeringDataSet) { MeshCoP::SteeringDataTlv steeringData; steeringData.Init(); steeringData.SetLength(aDataset.mSteeringData.mLength); SuccessOrExit(error = message->Append(&steeringData, sizeof(MeshCoP::Tlv))); SuccessOrExit(error = message->Append(&aDataset.mSteeringData.m8, aDataset.mSteeringData.mLength)); } if (aDataset.mIsJoinerUdpPortSet) { MeshCoP::JoinerUdpPortTlv joinerUdpPort; joinerUdpPort.Init(); joinerUdpPort.SetUdpPort(aDataset.mJoinerUdpPort); SuccessOrExit(error = message->AppendTlv(joinerUdpPort)); } if (aLength > 0) { SuccessOrExit(error = message->Append(aTlvs, aLength)); } if (message->GetLength() == message->GetOffset()) { // no payload, remove coap payload marker message->SetLength(message->GetLength() - 1); } messageInfo.SetSockAddr(Get<Mle::MleRouter>().GetMeshLocal16()); SuccessOrExit(error = Get<Mle::MleRouter>().GetLeaderAloc(messageInfo.GetPeerAddr())); messageInfo.SetPeerPort(kCoapUdpPort); SuccessOrExit(error = Get<Coap::Coap>().SendMessage(*message, messageInfo, Commissioner::HandleMgmtCommissionerSetResponse, this)); otLogInfoMeshCoP("sent MGMT_COMMISSIONER_SET.req to leader"); exit: if (error != OT_ERROR_NONE && message != NULL) { message->Free(); } return error; } void Commissioner::HandleMgmtCommissionerSetResponse(void * aContext, otMessage * aMessage, const otMessageInfo *aMessageInfo, otError aResult) { static_cast<Commissioner *>(aContext)->HandleMgmtCommissionerSetResponse( static_cast<Coap::Message *>(aMessage), static_cast<const Ip6::MessageInfo *>(aMessageInfo), aResult); } void Commissioner::HandleMgmtCommissionerSetResponse(Coap::Message * aMessage, const Ip6::MessageInfo *aMessageInfo, otError aResult) { OT_UNUSED_VARIABLE(aMessageInfo); VerifyOrExit(aResult == OT_ERROR_NONE && aMessage->GetCode() == OT_COAP_CODE_CHANGED); otLogInfoMeshCoP("received MGMT_COMMISSIONER_SET response"); exit: return; } otError Commissioner::SendPetition(void) { otError error = OT_ERROR_NONE; Coap::Message * message = NULL; Ip6::MessageInfo messageInfo; CommissionerIdTlv commissionerId; mTransmitAttempts++; VerifyOrExit((message = NewMeshCoPMessage(Get<Coap::Coap>())) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = message->Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST, OT_URI_PATH_LEADER_PETITION)); SuccessOrExit(error = message->SetPayloadMarker()); commissionerId.Init(); commissionerId.SetCommissionerId("OpenThread Commissioner"); SuccessOrExit(error = message->AppendTlv(commissionerId)); SuccessOrExit(error = Get<Mle::MleRouter>().GetLeaderAloc(messageInfo.GetPeerAddr())); messageInfo.SetPeerPort(kCoapUdpPort); messageInfo.SetSockAddr(Get<Mle::MleRouter>().GetMeshLocal16()); SuccessOrExit( error = Get<Coap::Coap>().SendMessage(*message, messageInfo, Commissioner::HandleLeaderPetitionResponse, this)); otLogInfoMeshCoP("sent petition"); exit: if (error != OT_ERROR_NONE && message != NULL) { message->Free(); } return error; } void Commissioner::HandleLeaderPetitionResponse(void * aContext, otMessage * aMessage, const otMessageInfo *aMessageInfo, otError aResult) { static_cast<Commissioner *>(aContext)->HandleLeaderPetitionResponse( static_cast<Coap::Message *>(aMessage), static_cast<const Ip6::MessageInfo *>(aMessageInfo), aResult); } void Commissioner::HandleLeaderPetitionResponse(Coap::Message * aMessage, const Ip6::MessageInfo *aMessageInfo, otError aResult) { OT_UNUSED_VARIABLE(aMessageInfo); StateTlv state; CommissionerSessionIdTlv sessionId; bool retransmit = false; VerifyOrExit(mState == OT_COMMISSIONER_STATE_PETITION, SetState(OT_COMMISSIONER_STATE_DISABLED)); VerifyOrExit(aResult == OT_ERROR_NONE && aMessage->GetCode() == OT_COAP_CODE_CHANGED, retransmit = true); otLogInfoMeshCoP("received Leader Petition response"); SuccessOrExit(Tlv::GetTlv(*aMessage, Tlv::kState, sizeof(state), state)); VerifyOrExit(state.IsValid()); VerifyOrExit(state.GetState() == StateTlv::kAccept, SetState(OT_COMMISSIONER_STATE_DISABLED)); SuccessOrExit(Tlv::GetTlv(*aMessage, Tlv::kCommissionerSessionId, sizeof(sessionId), sessionId)); VerifyOrExit(sessionId.IsValid()); mSessionId = sessionId.GetCommissionerSessionId(); Get<Mle::MleRouter>().GetCommissionerAloc(mCommissionerAloc.GetAddress(), mSessionId); Get<ThreadNetif>().AddUnicastAddress(mCommissionerAloc); AddCoapResources(); SetState(OT_COMMISSIONER_STATE_ACTIVE); mTransmitAttempts = 0; mTimer.Start(Time::SecToMsec(kKeepAliveTimeout) / 2); exit: if (retransmit) { if (mTransmitAttempts >= kPetitionRetryCount) { SetState(OT_COMMISSIONER_STATE_DISABLED); } else { mTimer.Start(Time::SecToMsec(kPetitionRetryDelay)); } } } otError Commissioner::SendKeepAlive(void) { otError error = OT_ERROR_NONE; Coap::Message * message = NULL; Ip6::MessageInfo messageInfo; StateTlv state; CommissionerSessionIdTlv sessionId; VerifyOrExit((message = NewMeshCoPMessage(Get<Coap::Coap>())) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = message->Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST, OT_URI_PATH_LEADER_KEEP_ALIVE)); SuccessOrExit(error = message->SetPayloadMarker()); state.Init(); state.SetState(mState == OT_COMMISSIONER_STATE_ACTIVE ? StateTlv::kAccept : StateTlv::kReject); SuccessOrExit(error = message->AppendTlv(state)); sessionId.Init(); sessionId.SetCommissionerSessionId(mSessionId); SuccessOrExit(error = message->AppendTlv(sessionId)); messageInfo.SetSockAddr(Get<Mle::MleRouter>().GetMeshLocal16()); SuccessOrExit(error = Get<Mle::MleRouter>().GetLeaderAloc(messageInfo.GetPeerAddr())); messageInfo.SetPeerPort(kCoapUdpPort); SuccessOrExit(error = Get<Coap::Coap>().SendMessage(*message, messageInfo, Commissioner::HandleLeaderKeepAliveResponse, this)); otLogInfoMeshCoP("sent keep alive"); exit: if (error != OT_ERROR_NONE && message != NULL) { message->Free(); } return error; } void Commissioner::HandleLeaderKeepAliveResponse(void * aContext, otMessage * aMessage, const otMessageInfo *aMessageInfo, otError aResult) { static_cast<Commissioner *>(aContext)->HandleLeaderKeepAliveResponse( static_cast<Coap::Message *>(aMessage), static_cast<const Ip6::MessageInfo *>(aMessageInfo), aResult); } void Commissioner::HandleLeaderKeepAliveResponse(Coap::Message * aMessage, const Ip6::MessageInfo *aMessageInfo, otError aResult) { OT_UNUSED_VARIABLE(aMessageInfo); StateTlv state; VerifyOrExit(mState == OT_COMMISSIONER_STATE_ACTIVE, SetState(OT_COMMISSIONER_STATE_DISABLED)); VerifyOrExit(aResult == OT_ERROR_NONE && aMessage->GetCode() == OT_COAP_CODE_CHANGED, SetState(OT_COMMISSIONER_STATE_DISABLED)); otLogInfoMeshCoP("received Leader keep-alive response"); SuccessOrExit(Tlv::GetTlv(*aMessage, Tlv::kState, sizeof(state), state)); VerifyOrExit(state.IsValid()); VerifyOrExit(state.GetState() == StateTlv::kAccept, SetState(OT_COMMISSIONER_STATE_DISABLED)); mTimer.Start(Time::SecToMsec(kKeepAliveTimeout) / 2); exit: if (mState != OT_COMMISSIONER_STATE_ACTIVE) { Get<ThreadNetif>().RemoveUnicastAddress(mCommissionerAloc); RemoveCoapResources(); } } void Commissioner::HandleRelayReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo) { static_cast<Commissioner *>(aContext)->HandleRelayReceive(*static_cast<Coap::Message *>(aMessage), *static_cast<const Ip6::MessageInfo *>(aMessageInfo)); } void Commissioner::HandleRelayReceive(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { OT_UNUSED_VARIABLE(aMessageInfo); otError error; JoinerUdpPortTlv joinerPort; JoinerIidTlv joinerIid; JoinerRouterLocatorTlv joinerRloc; Ip6::MessageInfo joinerMessageInfo; uint16_t offset; uint16_t length; bool enableJoiner = false; Mac::ExtAddress receivedId; Mac::ExtAddress joinerId; VerifyOrExit(mState == OT_COMMISSIONER_STATE_ACTIVE, error = OT_ERROR_INVALID_STATE); VerifyOrExit(aMessage.GetType() == OT_COAP_TYPE_NON_CONFIRMABLE && aMessage.GetCode() == OT_COAP_CODE_POST); SuccessOrExit(error = Tlv::GetTlv(aMessage, Tlv::kJoinerUdpPort, sizeof(joinerPort), joinerPort)); VerifyOrExit(joinerPort.IsValid(), error = OT_ERROR_PARSE); SuccessOrExit(error = Tlv::GetTlv(aMessage, Tlv::kJoinerIid, sizeof(joinerIid), joinerIid)); VerifyOrExit(joinerIid.IsValid(), error = OT_ERROR_PARSE); SuccessOrExit(error = Tlv::GetTlv(aMessage, Tlv::kJoinerRouterLocator, sizeof(joinerRloc), joinerRloc)); VerifyOrExit(joinerRloc.IsValid(), error = OT_ERROR_PARSE); SuccessOrExit(error = Tlv::GetValueOffset(aMessage, Tlv::kJoinerDtlsEncapsulation, offset, length)); VerifyOrExit(length <= aMessage.GetLength() - offset, error = OT_ERROR_PARSE); if (!Get<Coap::CoapSecure>().IsConnectionActive()) { memcpy(mJoinerIid, joinerIid.GetIid(), sizeof(mJoinerIid)); receivedId.Set(mJoinerIid); receivedId.ToggleLocal(); for (Joiner *joiner = &mJoiners[0]; joiner < OT_ARRAY_END(mJoiners); joiner++) { if (!joiner->mValid) { continue; } ComputeJoinerId(joiner->mEui64, joinerId); if (joiner->mAny || (joinerId == receivedId)) { error = Get<Coap::CoapSecure>().SetPsk(reinterpret_cast<const uint8_t *>(joiner->mPsk), static_cast<uint8_t>(strlen(joiner->mPsk))); SuccessOrExit(error); mJoinerIndex = static_cast<uint8_t>(joiner - mJoiners); enableJoiner = true; otLogInfoMeshCoP("found joiner, starting new session"); SignalJoinerEvent(OT_COMMISSIONER_JOINER_START, joinerId); break; } } } else { enableJoiner = (memcmp(mJoinerIid, joinerIid.GetIid(), sizeof(mJoinerIid)) == 0); } VerifyOrExit(enableJoiner); mJoinerPort = joinerPort.GetUdpPort(); mJoinerRloc = joinerRloc.GetJoinerRouterLocator(); otLogInfoMeshCoP("Remove Relay Receive (%02x%02x%02x%02x%02x%02x%02x%02x, 0x%04x)", mJoinerIid[0], mJoinerIid[1], mJoinerIid[2], mJoinerIid[3], mJoinerIid[4], mJoinerIid[5], mJoinerIid[6], mJoinerIid[7], mJoinerRloc); aMessage.SetOffset(offset); SuccessOrExit(error = aMessage.SetLength(offset + length)); joinerMessageInfo.SetPeerAddr(Get<Mle::MleRouter>().GetMeshLocal64()); joinerMessageInfo.GetPeerAddr().SetIid(mJoinerIid); joinerMessageInfo.SetPeerPort(mJoinerPort); Get<Coap::CoapSecure>().HandleUdpReceive(aMessage, joinerMessageInfo); exit: return; } void Commissioner::HandleDatasetChanged(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo) { static_cast<Commissioner *>(aContext)->HandleDatasetChanged(*static_cast<Coap::Message *>(aMessage), *static_cast<const Ip6::MessageInfo *>(aMessageInfo)); } void Commissioner::HandleDatasetChanged(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { VerifyOrExit(aMessage.GetType() == OT_COAP_TYPE_CONFIRMABLE && aMessage.GetCode() == OT_COAP_CODE_POST); otLogInfoMeshCoP("received dataset changed"); SuccessOrExit(Get<Coap::Coap>().SendEmptyAck(aMessage, aMessageInfo)); otLogInfoMeshCoP("sent dataset changed acknowledgment"); exit: return; } void Commissioner::HandleJoinerFinalize(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo) { static_cast<Commissioner *>(aContext)->HandleJoinerFinalize(*static_cast<Coap::Message *>(aMessage), *static_cast<const Ip6::MessageInfo *>(aMessageInfo)); } void Commissioner::HandleJoinerFinalize(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { OT_UNUSED_VARIABLE(aMessageInfo); StateTlv::State state = StateTlv::kAccept; ProvisioningUrlTlv provisioningUrl; otLogInfoMeshCoP("received joiner finalize"); if (Tlv::GetTlv(aMessage, Tlv::kProvisioningUrl, sizeof(provisioningUrl), provisioningUrl) == OT_ERROR_NONE) { uint8_t len = static_cast<uint8_t>(strnlen(mProvisioningUrl, sizeof(mProvisioningUrl))); if ((provisioningUrl.GetProvisioningUrlLength() != len) || !memcmp(provisioningUrl.GetProvisioningUrl(), mProvisioningUrl, len)) { state = StateTlv::kReject; } } #if OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE if (aMessage.GetLength() <= OPENTHREAD_CONFIG_MESSAGE_BUFFER_SIZE) { uint8_t buf[OPENTHREAD_CONFIG_MESSAGE_BUFFER_SIZE]; aMessage.Read(aMessage.GetOffset(), aMessage.GetLength() - aMessage.GetOffset(), buf); otDumpCertMeshCoP("[THCI] direction=recv | type=JOIN_FIN.req |", buf, aMessage.GetLength() - aMessage.GetOffset()); } #endif SendJoinFinalizeResponse(aMessage, state); } void Commissioner::SendJoinFinalizeResponse(const Coap::Message &aRequest, StateTlv::State aState) { otError error = OT_ERROR_NONE; Ip6::MessageInfo joinerMessageInfo; MeshCoP::StateTlv stateTlv; Coap::Message * message; Mac::ExtAddress joinerId; VerifyOrExit((message = NewMeshCoPMessage(Get<Coap::CoapSecure>())) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = message->SetDefaultResponseHeader(aRequest)); SuccessOrExit(error = message->SetPayloadMarker()); message->SetOffset(message->GetLength()); message->SetSubType(Message::kSubTypeJoinerFinalizeResponse); stateTlv.Init(); stateTlv.SetState(aState); SuccessOrExit(error = message->AppendTlv(stateTlv)); joinerMessageInfo.SetPeerAddr(Get<Mle::MleRouter>().GetMeshLocal64()); joinerMessageInfo.GetPeerAddr().SetIid(mJoinerIid); joinerMessageInfo.SetPeerPort(mJoinerPort); #if OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE uint8_t buf[OPENTHREAD_CONFIG_MESSAGE_BUFFER_SIZE]; VerifyOrExit(message->GetLength() <= sizeof(buf)); message->Read(message->GetOffset(), message->GetLength() - message->GetOffset(), buf); otDumpCertMeshCoP("[THCI] direction=send | type=JOIN_FIN.rsp |", buf, message->GetLength() - message->GetOffset()); #endif SuccessOrExit(error = Get<Coap::CoapSecure>().SendMessage(*message, joinerMessageInfo)); joinerId.Set(mJoinerIid); joinerId.ToggleLocal(); SignalJoinerEvent(OT_COMMISSIONER_JOINER_FINALIZE, joinerId); if (!mJoiners[mJoinerIndex].mAny) { // remove after kRemoveJoinerDelay (seconds) RemoveJoiner(&mJoiners[mJoinerIndex].mEui64, kRemoveJoinerDelay); } otLogInfoMeshCoP("sent joiner finalize response"); exit: if (error != OT_ERROR_NONE && message != NULL) { message->Free(); } } otError Commissioner::SendRelayTransmit(void *aContext, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { return static_cast<Commissioner *>(aContext)->SendRelayTransmit(aMessage, aMessageInfo); } otError Commissioner::SendRelayTransmit(Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { OT_UNUSED_VARIABLE(aMessageInfo); otError error = OT_ERROR_NONE; JoinerUdpPortTlv udpPort; JoinerIidTlv iid; JoinerRouterLocatorTlv rloc; ExtendedTlv tlv; Coap::Message * message; uint16_t offset; Ip6::MessageInfo messageInfo; VerifyOrExit((message = NewMeshCoPMessage(Get<Coap::Coap>())) != NULL, error = OT_ERROR_NO_BUFS); message->Init(OT_COAP_TYPE_NON_CONFIRMABLE, OT_COAP_CODE_POST); SuccessOrExit(error = message->AppendUriPathOptions(OT_URI_PATH_RELAY_TX)); SuccessOrExit(error = message->SetPayloadMarker()); udpPort.Init(); udpPort.SetUdpPort(mJoinerPort); SuccessOrExit(error = message->AppendTlv(udpPort)); iid.Init(); iid.SetIid(mJoinerIid); SuccessOrExit(error = message->AppendTlv(iid)); rloc.Init(); rloc.SetJoinerRouterLocator(mJoinerRloc); SuccessOrExit(error = message->AppendTlv(rloc)); if (aMessage.GetSubType() == Message::kSubTypeJoinerFinalizeResponse) { JoinerRouterKekTlv kek; kek.Init(); kek.SetKek(Get<KeyManager>().GetKek()); SuccessOrExit(error = message->AppendTlv(kek)); } tlv.SetType(Tlv::kJoinerDtlsEncapsulation); tlv.SetLength(aMessage.GetLength()); SuccessOrExit(error = message->Append(&tlv, sizeof(tlv))); offset = message->GetLength(); SuccessOrExit(error = message->SetLength(offset + aMessage.GetLength())); aMessage.CopyTo(0, offset, aMessage.GetLength(), *message); messageInfo.SetPeerAddr(Get<Mle::MleRouter>().GetMeshLocal16()); messageInfo.GetPeerAddr().mFields.m16[7] = HostSwap16(mJoinerRloc); messageInfo.SetPeerPort(kCoapUdpPort); SuccessOrExit(error = Get<Coap::Coap>().SendMessage(*message, messageInfo)); aMessage.Free(); exit: if (error != OT_ERROR_NONE && message != NULL) { message->Free(); } return error; } otError Commissioner::GeneratePskc(const char * aPassPhrase, const char * aNetworkName, const Mac::ExtendedPanId &aExtPanId, Pskc & aPskc) { otError error = OT_ERROR_NONE; const char saltPrefix[] = "Thread"; uint8_t salt[OT_PBKDF2_SALT_MAX_LEN]; uint16_t saltLen = 0; uint16_t passphraseLen; uint8_t networkNameLen; passphraseLen = static_cast<uint16_t>(strnlen(aPassPhrase, OT_COMMISSIONING_PASSPHRASE_MAX_SIZE + 1)); networkNameLen = static_cast<uint8_t>(strnlen(aNetworkName, OT_NETWORK_NAME_MAX_SIZE + 1)); VerifyOrExit((passphraseLen >= OT_COMMISSIONING_PASSPHRASE_MIN_SIZE) && (passphraseLen <= OT_COMMISSIONING_PASSPHRASE_MAX_SIZE) && (networkNameLen <= OT_NETWORK_NAME_MAX_SIZE), error = OT_ERROR_INVALID_ARGS); memset(salt, 0, sizeof(salt)); memcpy(salt, saltPrefix, sizeof(saltPrefix) - 1); saltLen += static_cast<uint16_t>(sizeof(saltPrefix) - 1); memcpy(salt + saltLen, aExtPanId.m8, sizeof(aExtPanId)); saltLen += OT_EXT_PAN_ID_SIZE; memcpy(salt + saltLen, aNetworkName, networkNameLen); saltLen += networkNameLen; otPbkdf2Cmac(reinterpret_cast<const uint8_t *>(aPassPhrase), passphraseLen, reinterpret_cast<const uint8_t *>(salt), saltLen, 16384, OT_PSKC_MAX_SIZE, aPskc.m8); exit: return error; } // LCOV_EXCL_START #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MLE == 1) const char *Commissioner::StateToString(otCommissionerState aState) { const char *str = "Unknown"; switch (aState) { case OT_COMMISSIONER_STATE_DISABLED: str = "disabled"; break; case OT_COMMISSIONER_STATE_PETITION: str = "petition"; break; case OT_COMMISSIONER_STATE_ACTIVE: str = "active"; break; default: break; } return str; } #endif // (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MLE == 1) // LCOV_EXCL_STOP } // namespace MeshCoP } // namespace ot #endif // OPENTHREAD_FTD && OPENTHREAD_CONFIG_COMMISSIONER_ENABLE
null
155
CWE-787
CVE-2019-20840
#include "ws_decode.h" #include "base64.h" #include <string.h> #include <errno.h> #define WS_HYBI_MASK_LEN 4 #define WS_HYBI_HEADER_LEN_SHORT 2 + WS_HYBI_MASK_LEN #define WS_HYBI_HEADER_LEN_EXTENDED 4 + WS_HYBI_MASK_LEN #define WS_HYBI_HEADER_LEN_LONG 10 + WS_HYBI_MASK_LEN #undef WS_DECODE_DEBUG /* set to 1 to produce very fine debugging output */ #define WS_DECODE_DEBUG 0 #if WS_DECODE_DEBUG == 1 #define ws_dbg(fmt, ...) rfbLog((fmt), ##__VA_ARGS) #else #define ws_dbg(fmt, ...) #endif static inline int isControlFrame(ws_ctx_t *wsctx) { return 0 != (wsctx->header.opcode & 0x08); } static uint64_t hybiRemaining(ws_ctx_t *wsctx) { return wsctx->header.payloadLen - wsctx->nReadPayload; } static void hybiDecodeCleanupBasics(ws_ctx_t *wsctx) { /* keep opcode, cleanup rest */ wsctx->header.opcode = WS_OPCODE_INVALID; wsctx->header.payloadLen = 0; wsctx->header.mask.u = 0; wsctx->header.headerLen = 0; wsctx->header.data = NULL; wsctx->header.nRead = 0; wsctx->nReadPayload = 0; wsctx->carrylen = 0; wsctx->readPos = (unsigned char *)wsctx->codeBufDecode; wsctx->readlen = 0; wsctx->hybiDecodeState = WS_HYBI_STATE_HEADER_PENDING; wsctx->writePos = NULL; } static void hybiDecodeCleanupForContinuation(ws_ctx_t *wsctx) { hybiDecodeCleanupBasics(wsctx); ws_dbg("clean up frame, but expect continuation with opcode %d\n", wsctx->continuation_opcode); } void hybiDecodeCleanupComplete(ws_ctx_t *wsctx) { hybiDecodeCleanupBasics(wsctx); wsctx->continuation_opcode = WS_OPCODE_INVALID; ws_dbg("cleaned up wsctx completely\n"); } /** * Return payload data that has been decoded/unmasked from * a websocket frame. * * @param[out] dst destination buffer * @param[in] len bytes to copy to destination buffer * @param[in,out] wsctx internal state of decoding procedure * @param[out] number of bytes actually written to dst buffer * @return next hybi decoding state */ static int hybiReturnData(char *dst, int len, ws_ctx_t *wsctx, int *nWritten) { int nextState = WS_HYBI_STATE_ERR; /* if we have something already decoded copy and return */ if (wsctx->readlen > 0) { /* simply return what we have */ if (wsctx->readlen > len) { ws_dbg("copy to %d bytes to dst buffer; readPos=%p, readLen=%d\n", len, wsctx->readPos, wsctx->readlen); memcpy(dst, wsctx->readPos, len); *nWritten = len; wsctx->readlen -= len; wsctx->readPos += len; nextState = WS_HYBI_STATE_DATA_AVAILABLE; } else { ws_dbg("copy to %d bytes to dst buffer; readPos=%p, readLen=%d\n", wsctx->readlen, wsctx->readPos, wsctx->readlen); memcpy(dst, wsctx->readPos, wsctx->readlen); *nWritten = wsctx->readlen; wsctx->readlen = 0; wsctx->readPos = NULL; if (hybiRemaining(wsctx) == 0) { nextState = WS_HYBI_STATE_FRAME_COMPLETE; } else { nextState = WS_HYBI_STATE_DATA_NEEDED; } } ws_dbg("after copy: readPos=%p, readLen=%d\n", wsctx->readPos, wsctx->readlen); } else { /* it may happen that we read some bytes but could not decode them, * in that case, set errno to EAGAIN and return -1 */ nextState = wsctx->hybiDecodeState; errno = EAGAIN; *nWritten = -1; } return nextState; } /** * Read an RFC 6455 websocket frame (IETF hybi working group). * * Internal state is updated according to bytes received and the * decoding of header information. * * @param[in] cl client ptr with ptr to raw socket and ws_ctx_t ptr * @param[out] sockRet emulated recv return value * @param[out] nPayload number of payload bytes already read * @return next hybi decoding state; WS_HYBI_STATE_HEADER_PENDING indicates * that the header was not received completely. */ static int hybiReadHeader(ws_ctx_t *wsctx, int *sockRet, int *nPayload) { int ret; char *headerDst = wsctx->codeBufDecode + wsctx->header.nRead; int n = ((uint64_t)WSHLENMAX) - wsctx->header.nRead; ws_dbg("header_read to %p with len=%d\n", headerDst, n); ret = wsctx->ctxInfo.readFunc(wsctx->ctxInfo.ctxPtr, headerDst, n); ws_dbg("read %d bytes from socket\n", ret); if (ret <= 0) { if (-1 == ret) { /* save errno because rfbErr() will tamper it */ int olderrno = errno; rfbErr("%s: read; %s\n", __func__, strerror(errno)); errno = olderrno; goto err_cleanup_state; } else { *sockRet = 0; goto err_cleanup_state_sock_closed; } } wsctx->header.nRead += ret; if (wsctx->header.nRead < 2) { /* cannot decode header with less than two bytes */ goto ret_header_pending; } /* first two header bytes received; interpret header data and get rest */ wsctx->header.data = (ws_header_t *)wsctx->codeBufDecode; wsctx->header.opcode = wsctx->header.data->b0 & 0x0f; wsctx->header.fin = (wsctx->header.data->b0 & 0x80) >> 7; if (isControlFrame(wsctx)) { ws_dbg("is control frame\n"); /* is a control frame, leave remembered continuation opcode unchanged; * just check if there is a wrong fragmentation */ if (wsctx->header.fin == 0) { /* we only accept text/binary continuation frames; RFC6455: * Control frames (see Section 5.5) MAY be injected in the middle of * a fragmented message. Control frames themselves MUST NOT be * fragmented. */ rfbErr("control frame with FIN bit cleared received, aborting\n"); errno = EPROTO; goto err_cleanup_state; } } else { ws_dbg("not a control frame\n"); /* not a control frame, check for continuation opcode */ if (wsctx->header.opcode == WS_OPCODE_CONTINUATION) { ws_dbg("cont_frame\n"); /* do we have state (i.e., opcode) for continuation frame? */ if (wsctx->continuation_opcode == WS_OPCODE_INVALID) { rfbErr("no continuation state\n"); errno = EPROTO; goto err_cleanup_state; } /* otherwise, set opcode = continuation_opcode */ wsctx->header.opcode = wsctx->continuation_opcode; ws_dbg("set opcode to continuation_opcode: %d\n", wsctx->header.opcode); } else { if (wsctx->header.fin == 0) { wsctx->continuation_opcode = wsctx->header.opcode; } else { wsctx->continuation_opcode = WS_OPCODE_INVALID; } ws_dbg("set continuation_opcode to %d\n", wsctx->continuation_opcode); } } wsctx->header.payloadLen = (uint64_t)(wsctx->header.data->b1 & 0x7f); ws_dbg("first header bytes received; opcode=%d lenbyte=%d fin=%d\n", wsctx->header.opcode, wsctx->header.payloadLen, wsctx->header.fin); /* * 4.3. Client-to-Server Masking * * The client MUST mask all frames sent to the server. A server MUST * close the connection upon receiving a frame with the MASK bit set to 0. **/ if (!(wsctx->header.data->b1 & 0x80)) { rfbErr("%s: got frame without mask; ret=%d\n", __func__, ret); errno = EPROTO; goto err_cleanup_state; } if (wsctx->header.payloadLen < 126 && wsctx->header.nRead >= 6) { wsctx->header.headerLen = WS_HYBI_HEADER_LEN_SHORT; wsctx->header.mask = wsctx->header.data->u.m; } else if (wsctx->header.payloadLen == 126 && 8 <= wsctx->header.nRead) { wsctx->header.headerLen = WS_HYBI_HEADER_LEN_EXTENDED; wsctx->header.payloadLen = WS_NTOH16(wsctx->header.data->u.s16.l16); wsctx->header.mask = wsctx->header.data->u.s16.m16; } else if (wsctx->header.payloadLen == 127 && 14 <= wsctx->header.nRead) { wsctx->header.headerLen = WS_HYBI_HEADER_LEN_LONG; wsctx->header.payloadLen = WS_NTOH64(wsctx->header.data->u.s64.l64); wsctx->header.mask = wsctx->header.data->u.s64.m64; } else { /* Incomplete frame header, try again */ rfbErr("%s: incomplete frame header; ret=%d\n", __func__, ret); goto ret_header_pending; } char *h = wsctx->codeBufDecode; int i; ws_dbg("Header:\n"); for (i=0; i <10; i++) { ws_dbg("0x%02X\n", (unsigned char)h[i]); } ws_dbg("\n"); /* while RFC 6455 mandates that lengths MUST be encoded with the minimum * number of bytes, it does not specify for the server how to react on * 'wrongly' encoded frames --- this implementation rejects them*/ if ((wsctx->header.headerLen > WS_HYBI_HEADER_LEN_SHORT && wsctx->header.payloadLen < (uint64_t)126) || (wsctx->header.headerLen > WS_HYBI_HEADER_LEN_EXTENDED && wsctx->header.payloadLen < (uint64_t)65536)) { rfbErr("%s: invalid length field; headerLen=%d payloadLen=%llu\n", __func__, wsctx->header.headerLen, wsctx->header.payloadLen); errno = EPROTO; goto err_cleanup_state; } /* update write position for next bytes */ wsctx->writePos = wsctx->codeBufDecode + wsctx->header.nRead; /* set payload pointer just after header */ wsctx->readPos = (unsigned char *)(wsctx->codeBufDecode + wsctx->header.headerLen); *nPayload = wsctx->header.nRead - wsctx->header.headerLen; wsctx->nReadPayload = *nPayload; ws_dbg("header complete: state=%d headerlen=%d payloadlen=%llu writeTo=%p nPayload=%d\n", wsctx->hybiDecodeState, wsctx->header.headerLen, wsctx->header.payloadLen, wsctx->writePos, *nPayload); return WS_HYBI_STATE_DATA_NEEDED; ret_header_pending: errno = EAGAIN; *sockRet = -1; return WS_HYBI_STATE_HEADER_PENDING; err_cleanup_state: *sockRet = -1; err_cleanup_state_sock_closed: hybiDecodeCleanupComplete(wsctx); return WS_HYBI_STATE_ERR; } static int hybiWsFrameComplete(ws_ctx_t *wsctx) { return wsctx != NULL && hybiRemaining(wsctx) == 0; } static char * hybiPayloadStart(ws_ctx_t *wsctx) { return wsctx->codeBufDecode + wsctx->header.headerLen; } /** * Read the remaining payload bytes from associated raw socket. * * - try to read remaining bytes from socket * - unmask all multiples of 4 * - if frame incomplete but some bytes are left, these are copied to * the carry buffer * - if opcode is TEXT: Base64-decode all unmasked received bytes * - set state for reading decoded data * - reset write position to begin of buffer (+ header) * --> before we retrieve more data we let the caller clear all bytes * from the reception buffer * - execute return data routine * * Sets errno corresponding to what it gets from the underlying * socket or EPROTO if some invalid data is in the received frame * or ECONNRESET if a close reason + message is received. EIO is used if * an internal sanity check fails. * * @param[in] cl client ptr with raw socket reference * @param[out] dst destination buffer * @param[in] len size of destination buffer * @param[out] sockRet emulated recv return value * @param[in] nInBuf number of undecoded bytes before writePos from header read * @return next hybi decode state */ static int hybiReadAndDecode(ws_ctx_t *wsctx, char *dst, int len, int *sockRet, int nInBuf) { int n; int i; int toReturn; /* number of data bytes to return */ int toDecode; /* number of bytes to decode starting at wsctx->writePos */ int bufsize; int nextRead; unsigned char *data; uint32_t *data32; /* if data was carried over, copy to start of buffer */ memcpy(wsctx->writePos, wsctx->carryBuf, wsctx->carrylen); wsctx->writePos += wsctx->carrylen; /* -1 accounts for potential '\0' terminator for base64 decoding */ bufsize = wsctx->codeBufDecode + ARRAYSIZE(wsctx->codeBufDecode) - wsctx->writePos - 1; ws_dbg("bufsize=%d\n", bufsize); if (hybiRemaining(wsctx) > bufsize) { nextRead = bufsize; } else { nextRead = hybiRemaining(wsctx); } ws_dbg("calling read with buf=%p and len=%d (decodebuf=%p headerLen=%d)\n", wsctx->writePos, nextRead, wsctx->codeBufDecode, wsctx->header.headerLen); if (nextRead > 0) { /* decode more data */ if (-1 == (n = wsctx->ctxInfo.readFunc(wsctx->ctxInfo.ctxPtr, wsctx->writePos, nextRead))) { int olderrno = errno; rfbErr("%s: read; %s", __func__, strerror(errno)); errno = olderrno; *sockRet = -1; return WS_HYBI_STATE_ERR; } else if (n == 0) { *sockRet = 0; return WS_HYBI_STATE_ERR; } else { ws_dbg("read %d bytes from socket; nRead=%d\n", n, wsctx->nReadPayload); } } else { n = 0; } wsctx->nReadPayload += n; wsctx->writePos += n; if (hybiRemaining(wsctx) == 0) { wsctx->hybiDecodeState = WS_HYBI_STATE_FRAME_COMPLETE; } /* number of not yet unmasked payload bytes: what we read here + what was * carried over + what was read with the header */ toDecode = n + wsctx->carrylen + nInBuf; ws_dbg("toDecode=%d from n=%d carrylen=%d headerLen=%d\n", toDecode, n, wsctx->carrylen, wsctx->header.headerLen); if (toDecode < 0) { rfbErr("%s: internal error; negative number of bytes to decode: %d", __func__, toDecode); errno=EIO; *sockRet = -1; return WS_HYBI_STATE_ERR; } /* for a possible base64 decoding, we decode multiples of 4 bytes until * the whole frame is received and carry over any remaining bytes in the carry buf*/ data = (unsigned char *)(wsctx->writePos - toDecode); data32= (uint32_t *)data; for (i = 0; i < (toDecode >> 2); i++) { data32[i] ^= wsctx->header.mask.u; } ws_dbg("mask decoding; i=%d toDecode=%d\n", i, toDecode); if (wsctx->hybiDecodeState == WS_HYBI_STATE_FRAME_COMPLETE) { /* process the remaining bytes (if any) */ for (i*=4; i < toDecode; i++) { data[i] ^= wsctx->header.mask.c[i % 4]; } /* all data is here, no carrying */ wsctx->carrylen = 0; } else { /* carry over remaining, non-multiple-of-four bytes */ wsctx->carrylen = toDecode - (i * 4); if (wsctx->carrylen < 0 || wsctx->carrylen > ARRAYSIZE(wsctx->carryBuf)) { rfbErr("%s: internal error, invalid carry over size: carrylen=%d, toDecode=%d, i=%d", __func__, wsctx->carrylen, toDecode, i); *sockRet = -1; errno = EIO; return WS_HYBI_STATE_ERR; } ws_dbg("carrying over %d bytes from %p to %p\n", wsctx->carrylen, wsctx->writePos + (i * 4), wsctx->carryBuf); memcpy(wsctx->carryBuf, data + (i * 4), wsctx->carrylen); wsctx->writePos -= wsctx->carrylen; } toReturn = toDecode - wsctx->carrylen; switch (wsctx->header.opcode) { case WS_OPCODE_CLOSE: /* this data is not returned as payload data */ if (hybiWsFrameComplete(wsctx)) { *(wsctx->writePos) = '\0'; ws_dbg("got close cmd %d, reason %d: %s\n", (int)(wsctx->writePos - hybiPayloadStart(wsctx)), WS_NTOH16(((uint16_t *)hybiPayloadStart(wsctx))[0]), &hybiPayloadStart(wsctx)[2]); errno = ECONNRESET; *sockRet = -1; return WS_HYBI_STATE_FRAME_COMPLETE; } else { ws_dbg("got close cmd; waiting for %d more bytes to arrive\n", hybiRemaining(wsctx)); *sockRet = -1; errno = EAGAIN; return WS_HYBI_STATE_CLOSE_REASON_PENDING; } break; case WS_OPCODE_TEXT_FRAME: data[toReturn] = '\0'; ws_dbg("Initiate Base64 decoding in %p with max size %d and '\\0' at %p\n", data, bufsize, data + toReturn); if (-1 == (wsctx->readlen = rfbBase64PtoN((char *)data, data, bufsize))) { rfbErr("%s: Base64 decode error; %s\n", __func__, strerror(errno)); } wsctx->writePos = hybiPayloadStart(wsctx); break; case WS_OPCODE_BINARY_FRAME: wsctx->readlen = toReturn; wsctx->writePos = hybiPayloadStart(wsctx); ws_dbg("set readlen=%d writePos=%p\n", wsctx->readlen, wsctx->writePos); break; default: rfbErr("%s: unhandled opcode %d, b0: %02x, b1: %02x\n", __func__, (int)wsctx->header.opcode, wsctx->header.data->b0, wsctx->header.data->b1); } wsctx->readPos = data; return hybiReturnData(dst, len, wsctx, sockRet); } /** * Read function for websocket-socket emulation. * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-------+-+-------------+-------------------------------+ * |F|R|R|R| opcode|M| Payload len | Extended payload length | * |I|S|S|S| (4) |A| (7) | (16/64) | * |N|V|V|V| |S| | (if payload len==126/127) | * | |1|2|3| |K| | | * +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + * | Extended payload length continued, if payload len == 127 | * + - - - - - - - - - - - - - - - +-------------------------------+ * | |Masking-key, if MASK set to 1 | * +-------------------------------+-------------------------------+ * | Masking-key (continued) | Payload Data | * +-------------------------------- - - - - - - - - - - - - - - - + * : Payload Data continued ... : * + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + * | Payload Data continued ... | * +---------------------------------------------------------------+ * * Using the decode buffer, this function: * - reads the complete header from the underlying socket * - reads any remaining data bytes * - unmasks the payload data using the provided mask * - decodes Base64 encoded text data * - copies len bytes of decoded payload data into dst * * Emulates a read call on a socket. */ int webSocketsDecodeHybi(ws_ctx_t *wsctx, char *dst, int len) { int result = -1; /* int fin; */ /* not used atm */ ws_dbg("%s_enter: len=%d; " "CTX: readlen=%d readPos=%p " "writeTo=%p " "state=%d payloadtoRead=%d payloadRemaining=%llu " " nReadPayload=%d carrylen=%d carryBuf=%p\n", __func__, len, wsctx->readlen, wsctx->readPos, wsctx->writePos, wsctx->hybiDecodeState, wsctx->header.payloadLen, hybiRemaining(wsctx), wsctx->nReadPayload, wsctx->carrylen, wsctx->carryBuf); switch (wsctx->hybiDecodeState){ int nInBuf; case WS_HYBI_STATE_HEADER_PENDING: wsctx->hybiDecodeState = hybiReadHeader(wsctx, &result, &nInBuf); if (wsctx->hybiDecodeState == WS_HYBI_STATE_ERR) { goto spor; } if (wsctx->hybiDecodeState != WS_HYBI_STATE_HEADER_PENDING) { /* when header is complete, try to read some more data */ wsctx->hybiDecodeState = hybiReadAndDecode(wsctx, dst, len, &result, nInBuf); } break; case WS_HYBI_STATE_DATA_AVAILABLE: wsctx->hybiDecodeState = hybiReturnData(dst, len, wsctx, &result); break; case WS_HYBI_STATE_DATA_NEEDED: wsctx->hybiDecodeState = hybiReadAndDecode(wsctx, dst, len, &result, 0); break; case WS_HYBI_STATE_CLOSE_REASON_PENDING: wsctx->hybiDecodeState = hybiReadAndDecode(wsctx, dst, len, &result, 0); break; default: /* invalid state */ rfbErr("%s: called with invalid state %d\n", wsctx->hybiDecodeState); result = -1; errno = EIO; wsctx->hybiDecodeState = WS_HYBI_STATE_ERR; } /* single point of return, if someone has questions :-) */ spor: if (wsctx->hybiDecodeState == WS_HYBI_STATE_FRAME_COMPLETE) { ws_dbg("frame received successfully, cleaning up: read=%d hlen=%d plen=%d\n", wsctx->header.nRead, wsctx->header.headerLen, wsctx->header.payloadLen); if (wsctx->header.fin && !isControlFrame(wsctx)) { /* frame finished, cleanup state */ hybiDecodeCleanupComplete(wsctx); } else { /* always retain continuation opcode for unfinished data frames * or control frames, which may interleave with data frames */ hybiDecodeCleanupForContinuation(wsctx); } } else if (wsctx->hybiDecodeState == WS_HYBI_STATE_ERR) { hybiDecodeCleanupComplete(wsctx); } ws_dbg("%s_exit: len=%d; " "CTX: readlen=%d readPos=%p " "writePos=%p " "state=%d payloadtoRead=%d payloadRemaining=%d " "nRead=%d carrylen=%d carryBuf=%p " "result=%d " "errno=%d\n", __func__, len, wsctx->readlen, wsctx->readPos, wsctx->writePos, wsctx->hybiDecodeState, wsctx->header.payloadLen, hybiRemaining(wsctx), wsctx->nReadPayload, wsctx->carrylen, wsctx->carryBuf, result, errno); return result; }
null
#include "ws_decode.h" #include "base64.h" #include <string.h> #include <errno.h> #define WS_HYBI_MASK_LEN 4 #define WS_HYBI_HEADER_LEN_SHORT 2 + WS_HYBI_MASK_LEN #define WS_HYBI_HEADER_LEN_EXTENDED 4 + WS_HYBI_MASK_LEN #define WS_HYBI_HEADER_LEN_LONG 10 + WS_HYBI_MASK_LEN #undef WS_DECODE_DEBUG /* set to 1 to produce very fine debugging output */ #define WS_DECODE_DEBUG 0 #if WS_DECODE_DEBUG == 1 #define ws_dbg(fmt, ...) rfbLog((fmt), ##__VA_ARGS) #else #define ws_dbg(fmt, ...) #endif static inline int isControlFrame(ws_ctx_t *wsctx) { return 0 != (wsctx->header.opcode & 0x08); } static uint64_t hybiRemaining(ws_ctx_t *wsctx) { return wsctx->header.payloadLen - wsctx->nReadPayload; } static void hybiDecodeCleanupBasics(ws_ctx_t *wsctx) { /* keep opcode, cleanup rest */ wsctx->header.opcode = WS_OPCODE_INVALID; wsctx->header.payloadLen = 0; wsctx->header.mask.u = 0; wsctx->header.headerLen = 0; wsctx->header.data = NULL; wsctx->header.nRead = 0; wsctx->nReadPayload = 0; wsctx->carrylen = 0; wsctx->readPos = (unsigned char *)wsctx->codeBufDecode; wsctx->readlen = 0; wsctx->hybiDecodeState = WS_HYBI_STATE_HEADER_PENDING; wsctx->writePos = NULL; } static void hybiDecodeCleanupForContinuation(ws_ctx_t *wsctx) { hybiDecodeCleanupBasics(wsctx); ws_dbg("clean up frame, but expect continuation with opcode %d\n", wsctx->continuation_opcode); } void hybiDecodeCleanupComplete(ws_ctx_t *wsctx) { hybiDecodeCleanupBasics(wsctx); wsctx->continuation_opcode = WS_OPCODE_INVALID; ws_dbg("cleaned up wsctx completely\n"); } /** * Return payload data that has been decoded/unmasked from * a websocket frame. * * @param[out] dst destination buffer * @param[in] len bytes to copy to destination buffer * @param[in,out] wsctx internal state of decoding procedure * @param[out] number of bytes actually written to dst buffer * @return next hybi decoding state */ static int hybiReturnData(char *dst, int len, ws_ctx_t *wsctx, int *nWritten) { int nextState = WS_HYBI_STATE_ERR; /* if we have something already decoded copy and return */ if (wsctx->readlen > 0) { /* simply return what we have */ if (wsctx->readlen > len) { ws_dbg("copy to %d bytes to dst buffer; readPos=%p, readLen=%d\n", len, wsctx->readPos, wsctx->readlen); memcpy(dst, wsctx->readPos, len); *nWritten = len; wsctx->readlen -= len; wsctx->readPos += len; nextState = WS_HYBI_STATE_DATA_AVAILABLE; } else { ws_dbg("copy to %d bytes to dst buffer; readPos=%p, readLen=%d\n", wsctx->readlen, wsctx->readPos, wsctx->readlen); memcpy(dst, wsctx->readPos, wsctx->readlen); *nWritten = wsctx->readlen; wsctx->readlen = 0; wsctx->readPos = NULL; if (hybiRemaining(wsctx) == 0) { nextState = WS_HYBI_STATE_FRAME_COMPLETE; } else { nextState = WS_HYBI_STATE_DATA_NEEDED; } } ws_dbg("after copy: readPos=%p, readLen=%d\n", wsctx->readPos, wsctx->readlen); } else { /* it may happen that we read some bytes but could not decode them, * in that case, set errno to EAGAIN and return -1 */ nextState = wsctx->hybiDecodeState; errno = EAGAIN; *nWritten = -1; } return nextState; } /** * Read an RFC 6455 websocket frame (IETF hybi working group). * * Internal state is updated according to bytes received and the * decoding of header information. * * @param[in] cl client ptr with ptr to raw socket and ws_ctx_t ptr * @param[out] sockRet emulated recv return value * @param[out] nPayload number of payload bytes already read * @return next hybi decoding state; WS_HYBI_STATE_HEADER_PENDING indicates * that the header was not received completely. */ static int hybiReadHeader(ws_ctx_t *wsctx, int *sockRet, int *nPayload) { int ret; char *headerDst = wsctx->codeBufDecode + wsctx->header.nRead; int n = ((uint64_t)WSHLENMAX) - wsctx->header.nRead; ws_dbg("header_read to %p with len=%d\n", headerDst, n); ret = wsctx->ctxInfo.readFunc(wsctx->ctxInfo.ctxPtr, headerDst, n); ws_dbg("read %d bytes from socket\n", ret); if (ret <= 0) { if (-1 == ret) { /* save errno because rfbErr() will tamper it */ int olderrno = errno; rfbErr("%s: read; %s\n", __func__, strerror(errno)); errno = olderrno; goto err_cleanup_state; } else { *sockRet = 0; goto err_cleanup_state_sock_closed; } } wsctx->header.nRead += ret; if (wsctx->header.nRead < 2) { /* cannot decode header with less than two bytes */ goto ret_header_pending; } /* first two header bytes received; interpret header data and get rest */ wsctx->header.data = (ws_header_t *)wsctx->codeBufDecode; wsctx->header.opcode = wsctx->header.data->b0 & 0x0f; wsctx->header.fin = (wsctx->header.data->b0 & 0x80) >> 7; if (isControlFrame(wsctx)) { ws_dbg("is control frame\n"); /* is a control frame, leave remembered continuation opcode unchanged; * just check if there is a wrong fragmentation */ if (wsctx->header.fin == 0) { /* we only accept text/binary continuation frames; RFC6455: * Control frames (see Section 5.5) MAY be injected in the middle of * a fragmented message. Control frames themselves MUST NOT be * fragmented. */ rfbErr("control frame with FIN bit cleared received, aborting\n"); errno = EPROTO; goto err_cleanup_state; } } else { ws_dbg("not a control frame\n"); /* not a control frame, check for continuation opcode */ if (wsctx->header.opcode == WS_OPCODE_CONTINUATION) { ws_dbg("cont_frame\n"); /* do we have state (i.e., opcode) for continuation frame? */ if (wsctx->continuation_opcode == WS_OPCODE_INVALID) { rfbErr("no continuation state\n"); errno = EPROTO; goto err_cleanup_state; } /* otherwise, set opcode = continuation_opcode */ wsctx->header.opcode = wsctx->continuation_opcode; ws_dbg("set opcode to continuation_opcode: %d\n", wsctx->header.opcode); } else { if (wsctx->header.fin == 0) { wsctx->continuation_opcode = wsctx->header.opcode; } else { wsctx->continuation_opcode = WS_OPCODE_INVALID; } ws_dbg("set continuation_opcode to %d\n", wsctx->continuation_opcode); } } wsctx->header.payloadLen = (uint64_t)(wsctx->header.data->b1 & 0x7f); ws_dbg("first header bytes received; opcode=%d lenbyte=%d fin=%d\n", wsctx->header.opcode, wsctx->header.payloadLen, wsctx->header.fin); /* * 4.3. Client-to-Server Masking * * The client MUST mask all frames sent to the server. A server MUST * close the connection upon receiving a frame with the MASK bit set to 0. **/ if (!(wsctx->header.data->b1 & 0x80)) { rfbErr("%s: got frame without mask; ret=%d\n", __func__, ret); errno = EPROTO; goto err_cleanup_state; } if (wsctx->header.payloadLen < 126 && wsctx->header.nRead >= 6) { wsctx->header.headerLen = WS_HYBI_HEADER_LEN_SHORT; wsctx->header.mask = wsctx->header.data->u.m; } else if (wsctx->header.payloadLen == 126 && 8 <= wsctx->header.nRead) { wsctx->header.headerLen = WS_HYBI_HEADER_LEN_EXTENDED; wsctx->header.payloadLen = WS_NTOH16(wsctx->header.data->u.s16.l16); wsctx->header.mask = wsctx->header.data->u.s16.m16; } else if (wsctx->header.payloadLen == 127 && 14 <= wsctx->header.nRead) { wsctx->header.headerLen = WS_HYBI_HEADER_LEN_LONG; wsctx->header.payloadLen = WS_NTOH64(wsctx->header.data->u.s64.l64); wsctx->header.mask = wsctx->header.data->u.s64.m64; } else { /* Incomplete frame header, try again */ rfbErr("%s: incomplete frame header; ret=%d\n", __func__, ret); goto ret_header_pending; } char *h = wsctx->codeBufDecode; int i; ws_dbg("Header:\n"); for (i=0; i <10; i++) { ws_dbg("0x%02X\n", (unsigned char)h[i]); } ws_dbg("\n"); /* while RFC 6455 mandates that lengths MUST be encoded with the minimum * number of bytes, it does not specify for the server how to react on * 'wrongly' encoded frames --- this implementation rejects them*/ if ((wsctx->header.headerLen > WS_HYBI_HEADER_LEN_SHORT && wsctx->header.payloadLen < (uint64_t)126) || (wsctx->header.headerLen > WS_HYBI_HEADER_LEN_EXTENDED && wsctx->header.payloadLen < (uint64_t)65536)) { rfbErr("%s: invalid length field; headerLen=%d payloadLen=%llu\n", __func__, wsctx->header.headerLen, wsctx->header.payloadLen); errno = EPROTO; goto err_cleanup_state; } /* update write position for next bytes */ wsctx->writePos = wsctx->codeBufDecode + wsctx->header.nRead; /* set payload pointer just after header */ wsctx->readPos = (unsigned char *)(wsctx->codeBufDecode + wsctx->header.headerLen); *nPayload = wsctx->header.nRead - wsctx->header.headerLen; wsctx->nReadPayload = *nPayload; ws_dbg("header complete: state=%d headerlen=%d payloadlen=%llu writeTo=%p nPayload=%d\n", wsctx->hybiDecodeState, wsctx->header.headerLen, wsctx->header.payloadLen, wsctx->writePos, *nPayload); return WS_HYBI_STATE_DATA_NEEDED; ret_header_pending: errno = EAGAIN; *sockRet = -1; return WS_HYBI_STATE_HEADER_PENDING; err_cleanup_state: *sockRet = -1; err_cleanup_state_sock_closed: hybiDecodeCleanupComplete(wsctx); return WS_HYBI_STATE_ERR; } static int hybiWsFrameComplete(ws_ctx_t *wsctx) { return wsctx != NULL && hybiRemaining(wsctx) == 0; } static char * hybiPayloadStart(ws_ctx_t *wsctx) { return wsctx->codeBufDecode + wsctx->header.headerLen; } /** * Read the remaining payload bytes from associated raw socket. * * - try to read remaining bytes from socket * - unmask all multiples of 4 * - if frame incomplete but some bytes are left, these are copied to * the carry buffer * - if opcode is TEXT: Base64-decode all unmasked received bytes * - set state for reading decoded data * - reset write position to begin of buffer (+ header) * --> before we retrieve more data we let the caller clear all bytes * from the reception buffer * - execute return data routine * * Sets errno corresponding to what it gets from the underlying * socket or EPROTO if some invalid data is in the received frame * or ECONNRESET if a close reason + message is received. EIO is used if * an internal sanity check fails. * * @param[in] cl client ptr with raw socket reference * @param[out] dst destination buffer * @param[in] len size of destination buffer * @param[out] sockRet emulated recv return value * @param[in] nInBuf number of undecoded bytes before writePos from header read * @return next hybi decode state */ static int hybiReadAndDecode(ws_ctx_t *wsctx, char *dst, int len, int *sockRet, int nInBuf) { int n; int i; int toReturn; /* number of data bytes to return */ int toDecode; /* number of bytes to decode starting at wsctx->writePos */ int bufsize; int nextRead; unsigned char *data; /* if data was carried over, copy to start of buffer */ memcpy(wsctx->writePos, wsctx->carryBuf, wsctx->carrylen); wsctx->writePos += wsctx->carrylen; /* -1 accounts for potential '\0' terminator for base64 decoding */ bufsize = wsctx->codeBufDecode + ARRAYSIZE(wsctx->codeBufDecode) - wsctx->writePos - 1; ws_dbg("bufsize=%d\n", bufsize); if (hybiRemaining(wsctx) > bufsize) { nextRead = bufsize; } else { nextRead = hybiRemaining(wsctx); } ws_dbg("calling read with buf=%p and len=%d (decodebuf=%p headerLen=%d)\n", wsctx->writePos, nextRead, wsctx->codeBufDecode, wsctx->header.headerLen); if (nextRead > 0) { /* decode more data */ if (-1 == (n = wsctx->ctxInfo.readFunc(wsctx->ctxInfo.ctxPtr, wsctx->writePos, nextRead))) { int olderrno = errno; rfbErr("%s: read; %s", __func__, strerror(errno)); errno = olderrno; *sockRet = -1; return WS_HYBI_STATE_ERR; } else if (n == 0) { *sockRet = 0; return WS_HYBI_STATE_ERR; } else { ws_dbg("read %d bytes from socket; nRead=%d\n", n, wsctx->nReadPayload); } } else { n = 0; } wsctx->nReadPayload += n; wsctx->writePos += n; if (hybiRemaining(wsctx) == 0) { wsctx->hybiDecodeState = WS_HYBI_STATE_FRAME_COMPLETE; } /* number of not yet unmasked payload bytes: what we read here + what was * carried over + what was read with the header */ toDecode = n + wsctx->carrylen + nInBuf; ws_dbg("toDecode=%d from n=%d carrylen=%d headerLen=%d\n", toDecode, n, wsctx->carrylen, wsctx->header.headerLen); if (toDecode < 0) { rfbErr("%s: internal error; negative number of bytes to decode: %d", __func__, toDecode); errno=EIO; *sockRet = -1; return WS_HYBI_STATE_ERR; } /* for a possible base64 decoding, we decode multiples of 4 bytes until * the whole frame is received and carry over any remaining bytes in the carry buf*/ data = (unsigned char *)(wsctx->writePos - toDecode); for (i = 0; i < (toDecode >> 2); i++) { uint32_t tmp; memcpy(&tmp, data + i * sizeof(tmp), sizeof(tmp)); tmp ^= wsctx->header.mask.u; memcpy(data + i * sizeof(tmp), &tmp, sizeof(tmp)); } ws_dbg("mask decoding; i=%d toDecode=%d\n", i, toDecode); if (wsctx->hybiDecodeState == WS_HYBI_STATE_FRAME_COMPLETE) { /* process the remaining bytes (if any) */ for (i*=4; i < toDecode; i++) { data[i] ^= wsctx->header.mask.c[i % 4]; } /* all data is here, no carrying */ wsctx->carrylen = 0; } else { /* carry over remaining, non-multiple-of-four bytes */ wsctx->carrylen = toDecode - (i * 4); if (wsctx->carrylen < 0 || wsctx->carrylen > ARRAYSIZE(wsctx->carryBuf)) { rfbErr("%s: internal error, invalid carry over size: carrylen=%d, toDecode=%d, i=%d", __func__, wsctx->carrylen, toDecode, i); *sockRet = -1; errno = EIO; return WS_HYBI_STATE_ERR; } ws_dbg("carrying over %d bytes from %p to %p\n", wsctx->carrylen, wsctx->writePos + (i * 4), wsctx->carryBuf); memcpy(wsctx->carryBuf, data + (i * 4), wsctx->carrylen); wsctx->writePos -= wsctx->carrylen; } toReturn = toDecode - wsctx->carrylen; switch (wsctx->header.opcode) { case WS_OPCODE_CLOSE: /* this data is not returned as payload data */ if (hybiWsFrameComplete(wsctx)) { *(wsctx->writePos) = '\0'; ws_dbg("got close cmd %d, reason %d: %s\n", (int)(wsctx->writePos - hybiPayloadStart(wsctx)), WS_NTOH16(((uint16_t *)hybiPayloadStart(wsctx))[0]), &hybiPayloadStart(wsctx)[2]); errno = ECONNRESET; *sockRet = -1; return WS_HYBI_STATE_FRAME_COMPLETE; } else { ws_dbg("got close cmd; waiting for %d more bytes to arrive\n", hybiRemaining(wsctx)); *sockRet = -1; errno = EAGAIN; return WS_HYBI_STATE_CLOSE_REASON_PENDING; } break; case WS_OPCODE_TEXT_FRAME: data[toReturn] = '\0'; ws_dbg("Initiate Base64 decoding in %p with max size %d and '\\0' at %p\n", data, bufsize, data + toReturn); if (-1 == (wsctx->readlen = rfbBase64PtoN((char *)data, data, bufsize))) { rfbErr("%s: Base64 decode error; %s\n", __func__, strerror(errno)); } wsctx->writePos = hybiPayloadStart(wsctx); break; case WS_OPCODE_BINARY_FRAME: wsctx->readlen = toReturn; wsctx->writePos = hybiPayloadStart(wsctx); ws_dbg("set readlen=%d writePos=%p\n", wsctx->readlen, wsctx->writePos); break; default: rfbErr("%s: unhandled opcode %d, b0: %02x, b1: %02x\n", __func__, (int)wsctx->header.opcode, wsctx->header.data->b0, wsctx->header.data->b1); } wsctx->readPos = data; return hybiReturnData(dst, len, wsctx, sockRet); } /** * Read function for websocket-socket emulation. * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-------+-+-------------+-------------------------------+ * |F|R|R|R| opcode|M| Payload len | Extended payload length | * |I|S|S|S| (4) |A| (7) | (16/64) | * |N|V|V|V| |S| | (if payload len==126/127) | * | |1|2|3| |K| | | * +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + * | Extended payload length continued, if payload len == 127 | * + - - - - - - - - - - - - - - - +-------------------------------+ * | |Masking-key, if MASK set to 1 | * +-------------------------------+-------------------------------+ * | Masking-key (continued) | Payload Data | * +-------------------------------- - - - - - - - - - - - - - - - + * : Payload Data continued ... : * + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + * | Payload Data continued ... | * +---------------------------------------------------------------+ * * Using the decode buffer, this function: * - reads the complete header from the underlying socket * - reads any remaining data bytes * - unmasks the payload data using the provided mask * - decodes Base64 encoded text data * - copies len bytes of decoded payload data into dst * * Emulates a read call on a socket. */ int webSocketsDecodeHybi(ws_ctx_t *wsctx, char *dst, int len) { int result = -1; /* int fin; */ /* not used atm */ ws_dbg("%s_enter: len=%d; " "CTX: readlen=%d readPos=%p " "writeTo=%p " "state=%d payloadtoRead=%d payloadRemaining=%llu " " nReadPayload=%d carrylen=%d carryBuf=%p\n", __func__, len, wsctx->readlen, wsctx->readPos, wsctx->writePos, wsctx->hybiDecodeState, wsctx->header.payloadLen, hybiRemaining(wsctx), wsctx->nReadPayload, wsctx->carrylen, wsctx->carryBuf); switch (wsctx->hybiDecodeState){ int nInBuf; case WS_HYBI_STATE_HEADER_PENDING: wsctx->hybiDecodeState = hybiReadHeader(wsctx, &result, &nInBuf); if (wsctx->hybiDecodeState == WS_HYBI_STATE_ERR) { goto spor; } if (wsctx->hybiDecodeState != WS_HYBI_STATE_HEADER_PENDING) { /* when header is complete, try to read some more data */ wsctx->hybiDecodeState = hybiReadAndDecode(wsctx, dst, len, &result, nInBuf); } break; case WS_HYBI_STATE_DATA_AVAILABLE: wsctx->hybiDecodeState = hybiReturnData(dst, len, wsctx, &result); break; case WS_HYBI_STATE_DATA_NEEDED: wsctx->hybiDecodeState = hybiReadAndDecode(wsctx, dst, len, &result, 0); break; case WS_HYBI_STATE_CLOSE_REASON_PENDING: wsctx->hybiDecodeState = hybiReadAndDecode(wsctx, dst, len, &result, 0); break; default: /* invalid state */ rfbErr("%s: called with invalid state %d\n", wsctx->hybiDecodeState); result = -1; errno = EIO; wsctx->hybiDecodeState = WS_HYBI_STATE_ERR; } /* single point of return, if someone has questions :-) */ spor: if (wsctx->hybiDecodeState == WS_HYBI_STATE_FRAME_COMPLETE) { ws_dbg("frame received successfully, cleaning up: read=%d hlen=%d plen=%d\n", wsctx->header.nRead, wsctx->header.headerLen, wsctx->header.payloadLen); if (wsctx->header.fin && !isControlFrame(wsctx)) { /* frame finished, cleanup state */ hybiDecodeCleanupComplete(wsctx); } else { /* always retain continuation opcode for unfinished data frames * or control frames, which may interleave with data frames */ hybiDecodeCleanupForContinuation(wsctx); } } else if (wsctx->hybiDecodeState == WS_HYBI_STATE_ERR) { hybiDecodeCleanupComplete(wsctx); } ws_dbg("%s_exit: len=%d; " "CTX: readlen=%d readPos=%p " "writePos=%p " "state=%d payloadtoRead=%d payloadRemaining=%d " "nRead=%d carrylen=%d carryBuf=%p " "result=%d " "errno=%d\n", __func__, len, wsctx->readlen, wsctx->readPos, wsctx->writePos, wsctx->hybiDecodeState, wsctx->header.payloadLen, hybiRemaining(wsctx), wsctx->nReadPayload, wsctx->carrylen, wsctx->carryBuf, result, errno); return result; }
null
156
CWE-787
CVE-2019-25050
/****************************************************************************** * * Project: netCDF read/write Driver * Purpose: GDAL bindings over netCDF library. * Author: Winor Chen <wchen329 at wisc.edu> * ****************************************************************************** * Copyright (c) 2019, Winor Chen <wchen329 at wisc.edu> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include <cstdio> #include <cstring> #include <vector> #include "netcdf.h" #include "netcdfdataset.h" #include "netcdfsg.h" namespace nccfdriver { /* Re-implementation of mempcpy * but compatible with libraries which only implement memcpy */ static void* memcpy_jump(void *dest, const void *src, size_t n) { memcpy(dest, src, n); int8_t * byte_pointer = static_cast<int8_t*>(dest); return static_cast<void*>(byte_pointer + n); } /* Attribute Fetch * - * A function which makes it a bit easier to fetch single text attribute values * ncid: as used in netcdf.h * varID: variable id in which to look for the attribute * attrName: name of attribute to fine * alloc: a reference to a string that will be filled with the attribute (i.e. truncated and filled with the return value) * Returns: a reference to the string to fill (a.k.a. string pointed to by alloc reference) */ std::string& attrf(int ncid, int varId, const char * attrName, std::string& alloc) { alloc = ""; size_t len = 0; nc_inq_attlen(ncid, varId, attrName, &len); if(len < 1) { return alloc; } char attr_vals[NC_MAX_NAME + 1]; memset(attr_vals, 0, NC_MAX_NAME + 1); // Now look through this variable for the attribute if(nc_get_att_text(ncid, varId, attrName, attr_vals) != NC_NOERR) { return alloc; } alloc = std::string(attr_vals); return alloc; } /* SGeometry * (implementations) * */ SGeometry::SGeometry(int ncId, int geoVarId) : gc_varId(geoVarId), touple_order(0), current_vert_ind(0), cur_geometry_ind(0), cur_part_ind(0) { char container_name[NC_MAX_NAME + 1]; memset(container_name, 0, NC_MAX_NAME + 1); // Get geometry container name if(nc_inq_varname(ncId, geoVarId, container_name) != NC_NOERR) { throw SG_Exception_Existential("new geometry container", "the variable of the given ID"); } // Establish string version of container_name container_name_s = std::string(container_name); // Find geometry type this->type = nccfdriver::getGeometryType(ncId, geoVarId); if(this->type == NONE) { throw SG_Exception_Existential(static_cast<const char*>(container_name), CF_SG_GEOMETRY_TYPE); } // Get grid mapping variable, if it exists this->gm_varId = INVALID_VAR_ID; if(attrf(ncId, geoVarId, CF_GRD_MAPPING, gm_name_s) != "") { const char * gm_name = gm_name_s.c_str(); int gmVID; if(nc_inq_varid(ncId, gm_name, &gmVID) == NC_NOERR) { this->gm_varId = gmVID; } } // Find a list of node counts and part node count std::string nc_name_s; std::string pnc_name_s; std::string ir_name_s; int pnc_vid = INVALID_VAR_ID; int nc_vid = INVALID_VAR_ID; int ir_vid = INVALID_VAR_ID; int buf; size_t bound = 0; size_t total_node_count = 0; // used in error checks later if(attrf(ncId, geoVarId, CF_SG_NODE_COUNT, nc_name_s) != "") { const char * nc_name = nc_name_s.c_str(); nc_inq_varid(ncId, nc_name, &nc_vid); while(nc_get_var1_int(ncId, nc_vid, &bound, &buf) == NC_NOERR) { this->node_counts.push_back(buf); total_node_count += buf; bound++; } } if(attrf(ncId, geoVarId, CF_SG_PART_NODE_COUNT, pnc_name_s) != "") { const char * pnc_name = pnc_name_s.c_str(); bound = 0; nc_inq_varid(ncId, pnc_name, &pnc_vid); while(nc_get_var1_int(ncId, pnc_vid, &bound, &buf) == NC_NOERR) { this->pnode_counts.push_back(buf); bound++; } } if(attrf(ncId, geoVarId, CF_SG_INTERIOR_RING, ir_name_s) != "") { const char * ir_name = ir_name_s.c_str(); bound = 0; nc_inq_varid(ncId, ir_name, &ir_vid); while(nc_get_var1_int(ncId, ir_vid, &bound, &buf) == NC_NOERR) { bool store = buf == 0 ? false : true; this->int_rings.push_back(store); bound++; } } /* Enforcement of well formed CF files * If these are not met then the dataset is malformed and will halt further processing of * simple geometries. */ // part node count exists only when node count exists if(pnode_counts.size() > 0 && node_counts.size() == 0) { throw SG_Exception_Dep(static_cast<const char *>(container_name), CF_SG_PART_NODE_COUNT, CF_SG_NODE_COUNT); } // interior rings only exist when part node counts exist if(int_rings.size() > 0 && pnode_counts.size() == 0) { throw SG_Exception_Dep(static_cast<const char *>(container_name), CF_SG_INTERIOR_RING, CF_SG_PART_NODE_COUNT); } // cardinality of part_node_counts == cardinality of interior_ring (if interior ring > 0) if(int_rings.size() > 0) { if(int_rings.size() != pnode_counts.size()) { throw SG_Exception_Dim_MM(static_cast<const char *>(container_name), CF_SG_INTERIOR_RING, CF_SG_PART_NODE_COUNT); } } // lines and polygons require node_counts, multipolygons are checked with part_node_count if(this->type == POLYGON || this->type == LINE) { if(node_counts.size() < 1) { throw SG_Exception_Existential(static_cast<const char*>(container_name), CF_SG_NODE_COUNT); } } /* Basic Safety checks End */ // Create bound list size_t rc = 0; bound_list.push_back(0);// start with 0 if(node_counts.size() > 0) { for(size_t i = 0; i < node_counts.size() - 1; i++) { rc = rc + node_counts[i]; bound_list.push_back(rc); } } std::string cart_s; // Node Coordinates if(attrf(ncId, geoVarId, CF_SG_NODE_COORDINATES, cart_s) == "") { throw SG_Exception_Existential(container_name, CF_SG_NODE_COORDINATES); } // Create parts count list and an offset list for parts indexing if(this->node_counts.size() > 0) { int ind = 0; int parts = 0; int prog = 0; int c = 0; for(size_t pcnt = 0; pcnt < pnode_counts.size() ; pcnt++) { if(prog == 0) pnc_bl.push_back(pcnt); if(int_rings.size() > 0 && !int_rings[pcnt]) c++; prog = prog + pnode_counts[pcnt]; parts++; if(prog == node_counts[ind]) { ind++; this->parts_count.push_back(parts); if(int_rings.size() > 0) this->poly_count.push_back(c); c = 0; prog = 0; parts = 0; } else if(prog > node_counts[ind]) { throw SG_Exception_BadSum(container_name, CF_SG_PART_NODE_COUNT, CF_SG_NODE_COUNT); } } } // (1) the touple order for a single point // (2) the variable ids with the relevant coordinate values int X = INVALID_VAR_ID; int Y = INVALID_VAR_ID; int Z = INVALID_VAR_ID; char cart[NC_MAX_NAME + 1]; memset(cart, 0, NC_MAX_NAME + 1); strncpy(cart, cart_s.c_str(), NC_MAX_NAME); char * dim = strtok(cart, " "); int axis_id = 0; while(dim != nullptr) { if(nc_inq_varid(ncId, dim, &axis_id) == NC_NOERR) { // Check axis signature std::string a_sig; attrf(ncId, axis_id, CF_AXIS, a_sig); // If valid signify axis correctly if(a_sig == "X") { X = axis_id; } else if(a_sig == "Y") { Y = axis_id; } else if(a_sig == "Z") { Z = axis_id; } else { throw SG_Exception_Dep(container_name, "A node_coordinates variable", CF_AXIS); } this->touple_order++; } else { throw SG_Exception_Existential(container_name, dim); } dim = strtok(nullptr, " "); } // Write axis in X, Y, Z order if(X != INVALID_VAR_ID) this->nodec_varIds.push_back(X); else { throw SG_Exception_Existential(container_name, "node_coordinates: X-axis"); } if(Y != INVALID_VAR_ID) this->nodec_varIds.push_back(Y); else { throw SG_Exception_Existential(container_name, "node_coordinates: Y-axis"); } if(Z != INVALID_VAR_ID) this->nodec_varIds.push_back(Z); /* Final Checks for node coordinates * (1) Each axis has one and only one dimension, dim length of each node coordinates are all equal * (2) total node count == dim length of each node coordinates (if node_counts not empty) * (3) there are at least two node coordinate variable ids */ int all_dim = INVALID_VAR_ID; bool dim_set = false; int dimC = 0; //(1) one dimension check, each node_coordinates have same dimension for(size_t nvitr = 0; nvitr < nodec_varIds.size(); nvitr++) { dimC = 0; nc_inq_varndims(ncId, nodec_varIds[nvitr], &dimC); if(dimC != 1) { throw SG_Exception_Not1D(); } // check that all have same dimension int inter_dim[1]; if(nc_inq_vardimid(ncId, nodec_varIds[nvitr], inter_dim) != NC_NOERR) { throw SG_Exception_Existential(container_name, "one or more node_coordinate dimensions"); } if(!dim_set) { all_dim = inter_dim[0]; } else { if (inter_dim[0] != all_dim) throw SG_Exception_Dim_MM(container_name, "X, Y", "in general all node coordinate axes"); } } // (2) check equality one if(node_counts.size() > 0) { size_t diml = 0; nc_inq_dimlen(ncId, all_dim, &diml); if(diml != total_node_count) throw SG_Exception_BadSum(container_name, "node_count", "node coordinate dimension length"); } // (3) check touple order if(this->touple_order < 2) { throw SG_Exception_Existential(container_name, "insufficent node coordinates must have at least two axis"); } /* Investigate for instance dimension * The procedure is as follows * * (1) if there's node_count, use the dimension used to index node count * (2) otherwise it's point (singleton) data, in this case use the node coordinate dimension */ size_t instance_dim_len = 0; if(node_counts.size() >= 1) { int nc_dims = 0; nc_inq_varndims(ncId, nc_vid, &nc_dims); if(nc_dims != 1) throw SG_Exception_Not1D(); int nc_dim_id[1]; if(nc_inq_vardimid(ncId, nc_vid, nc_dim_id) != NC_NOERR) { throw SG_Exception_Existential(container_name, "node_count dimension"); } this->inst_dimId = nc_dim_id[0]; } else { this->inst_dimId = all_dim; } nc_inq_dimlen(ncId, this->inst_dimId, &instance_dim_len); if(instance_dim_len == 0) throw SG_Exception_EmptyDim(); // Set values accordingly this->inst_dimLen = instance_dim_len; this->pt_buffer = std::unique_ptr<Point>(new Point(this->touple_order)); this->gc_varId = geoVarId; this->current_vert_ind = 0; this->ncid = ncId; } Point& SGeometry::next_pt() { if(!this->has_next_pt()) { throw SG_Exception_BadPoint(); } // Fill pt // New pt now for(int order = 0; order < touple_order; order++) { Point& pt = *(this->pt_buffer); double data; size_t full_ind = bound_list[cur_geometry_ind] + current_vert_ind; // Read a single coord int err = nc_get_var1_double(ncid, nodec_varIds[order], &full_ind, &data); // To do: optimize through multiple reads at once, instead of one datum if(err != NC_NOERR) { throw SG_Exception_BadPoint(); } pt[order] = data; } this->current_vert_ind++; return *(this->pt_buffer); } bool SGeometry::has_next_pt() { if(this->current_vert_ind < node_counts[cur_geometry_ind]) { return true; } else return false; } void SGeometry::next_geometry() { // to do: maybe implement except. and such on error conds. this->cur_geometry_ind++; this->cur_part_ind = 0; this->current_vert_ind = 0; } bool SGeometry::has_next_geometry() { if(this->cur_geometry_ind < node_counts.size()) { return true; } else return false; } Point& SGeometry::operator[](size_t index) { for(int order = 0; order < touple_order; order++) { Point& pt = *(this->pt_buffer); double data; size_t real_ind = index; // Read a single coord int err = nc_get_var1_double(ncid, nodec_varIds[order], &real_ind, &data); if(err != NC_NOERR) { throw SG_Exception_BadPoint(); } pt[order] = data; } return *(this->pt_buffer); } size_t SGeometry::get_geometry_count() { if(type == POINT) { // If nodes global attribute is available, use that // Otherwise, don't fail- use dimension length of one of x if(this->nodec_varIds.size() < 1) return 0; // If more than one dim, then error. Otherwise inquire its length and return that int dims; if(nc_inq_varndims(this->ncid, nodec_varIds[0], &dims) != NC_NOERR) return 0; if(dims != 1) return 0; // Find which dimension is used for x int index; if(nc_inq_vardimid(this->ncid, nodec_varIds[0], &index) != NC_NOERR) { return 0; } // Finally find the length size_t len; if(nc_inq_dimlen(this->ncid, index, &len) != NC_NOERR) { return 0; } return len; } else return this->node_counts.size(); } /* serializeToWKB(SGeometry * sg) * Takes the geometry in SGeometry at a given index and converts it into WKB format. * Converting SGeometry into WKB automatically allocates the required buffer space * and returns a buffer that MUST be free'd */ unsigned char * SGeometry::serializeToWKB(size_t featureInd, int& wkbSize) { unsigned char * ret = nullptr; int nc = 0; size_t sb = 0; // Points don't have node_count entry... only inspect and set node_counts if not a point if(this->getGeometryType() != POINT) { nc = node_counts[featureInd]; sb = bound_list[featureInd]; } // Serialization occurs differently depending on geometry // The memory requirements also differ between geometries switch(this->getGeometryType()) { case POINT: wkbSize = 1 + 4 + this->touple_order * 8; ret = new uint8_t[wkbSize]; inPlaceSerialize_Point(this, featureInd, ret); break; case LINE: wkbSize = 1 + 4 + 4 + this->touple_order * 8 * nc; ret = new uint8_t[wkbSize]; inPlaceSerialize_LineString(this, nc, sb, ret); break; case POLYGON: // A polygon has: // 1 byte header // 4 byte Type // 4 byte ring count (1 (exterior)) [assume only exterior rings, otherwise multipolygon] // For each ring: // 4 byte point count, 8 byte double x point count x # dimension // (This is equivalent to requesting enough for all points and a point count header for each point) // (Or 8 byte double x node count x # dimension + 4 byte point count x part_count) // if interior ring, then assume that it will be a multipolygon (maybe future work?) wkbSize = 1 + 4 + 4 + 4 + this->touple_order * 8 * nc; ret = new uint8_t[wkbSize]; inPlaceSerialize_PolygonExtOnly(this, nc, sb, ret); break; case MULTIPOINT: { wkbSize = 1 + 4 + 4 + nc * (1 + 4 + this->touple_order * 8); ret = new uint8_t[wkbSize]; void * worker = ret; int8_t header = PLATFORM_HEADER; uint32_t t = this->touple_order == 2 ? wkbMultiPoint : this->touple_order == 3 ? wkbMultiPoint25D : wkbNone; if(t == wkbNone) throw SG_Exception_BadFeature(); // Add metadata worker = memcpy_jump(worker, &header, 1); worker = memcpy_jump(worker, &t, 4); worker = memcpy_jump(worker, &nc, 4); // Add points for(int pts = 0; pts < nc; pts++) { worker = inPlaceSerialize_Point(this, static_cast<size_t>(sb + pts), worker); } } break; case MULTILINE: { int8_t header = PLATFORM_HEADER; uint32_t t = this->touple_order == 2 ? wkbMultiLineString : this->touple_order == 3 ? wkbMultiLineString25D : wkbNone; if(t == wkbNone) throw SG_Exception_BadFeature(); int32_t lc = parts_count[featureInd]; size_t seek_begin = sb; size_t pc_begin = pnc_bl[featureInd]; // initialize with first part count, list of part counts is contiguous wkbSize = 1 + 4 + 4; std::vector<int> pnc; // Build sub vector for part_node_counts // + Calculate wkbSize for(int itr = 0; itr < lc; itr++) { pnc.push_back(pnode_counts[pc_begin + itr]); wkbSize += this->touple_order * 8 * pnc[itr] + 1 + 4 + 4; } size_t cur_point = seek_begin; size_t pcount = pnc.size(); // Allocate and set pointers ret = new uint8_t[wkbSize]; void * worker = ret; // Begin Writing worker = memcpy_jump(worker, &header, 1); worker = memcpy_jump(worker, &t, 4); worker = memcpy_jump(worker, &pcount, 4); for(size_t itr = 0; itr < pcount; itr++) { worker = inPlaceSerialize_LineString(this, pnc[itr], cur_point, worker); cur_point = pnc[itr] + cur_point; } } break; case MULTIPOLYGON: { int8_t header = PLATFORM_HEADER; uint32_t t = this->touple_order == 2 ? wkbMultiPolygon: this->touple_order == 3 ? wkbMultiPolygon25D: wkbNone; if(t == wkbNone) throw SG_Exception_BadFeature(); bool noInteriors = this->int_rings.size() == 0 ? true : false; int32_t rc = parts_count[featureInd]; size_t seek_begin = sb; size_t pc_begin = pnc_bl[featureInd]; // initialize with first part count, list of part counts is contiguous wkbSize = 1 + 4 + 4; std::vector<int> pnc; // Build sub vector for part_node_counts for(int itr = 0; itr < rc; itr++) { pnc.push_back(pnode_counts[pc_begin + itr]); } // Figure out each Polygon's space requirements if(noInteriors) { for(int ss = 0; ss < rc; ss++) { wkbSize += 8 * this->touple_order * pnc[ss] + 1 + 4 + 4 + 4; } } else { // Total space requirements for Polygons: // (1 + 4 + 4) * number of Polygons // 4 * number of Rings Total // 8 * touple_order * number of Points // Each ring collection corresponds to a polygon wkbSize += (1 + 4 + 4) * poly_count[featureInd]; // (headers) // Add header requirements for rings wkbSize += 4 * parts_count[featureInd]; // Add requirements for number of points wkbSize += 8 * this->touple_order * nc; } // Now allocate and serialize ret = new uint8_t[wkbSize]; // Create Multipolygon headers void * worker = (void*)ret; worker = memcpy_jump(worker, &header, 1); worker = memcpy_jump(worker, &t, 4); if(noInteriors) { size_t cur_point = seek_begin; size_t pcount = pnc.size(); worker = memcpy_jump(worker, &pcount, 4); for(size_t itr = 0; itr < pcount; itr++) { worker = inPlaceSerialize_PolygonExtOnly(this, pnc[itr], cur_point, worker); cur_point = pnc[itr] + cur_point; } } else { int32_t polys = poly_count[featureInd]; worker = memcpy_jump(worker, &polys, 4); size_t base = pnc_bl[featureInd]; // beginning of parts_count for this multigeometry size_t seek = seek_begin; // beginning of node range for this multigeometry size_t ir_base = base + 1; int rc_m = 1; // has interior rings, for(int32_t itr = 0; itr < polys; itr++) { rc_m = 1; // count how many parts belong to each Polygon while(ir_base < int_rings.size() && int_rings[ir_base]) { rc_m++; ir_base++; } if(rc_m == 1) ir_base++; // single polygon case std::vector<int> poly_parts; // Make part node count sub vector for(int itr_2 = 0; itr_2 < rc_m; itr_2++) { poly_parts.push_back(pnode_counts[base + itr_2]); } worker = inPlaceSerialize_Polygon(this, poly_parts, rc_m, seek, worker); // Update seek position for(size_t itr_3 = 0; itr_3 < poly_parts.size(); itr_3++) { seek += poly_parts[itr_3]; } } } } break; default: throw SG_Exception_BadFeature(); break; } return ret; } void SGeometry_PropertyScanner::open(int container_id) { // First check for container_id, if variable doesn't exist error out if(nc_inq_var(this->nc, container_id, nullptr, nullptr, nullptr, nullptr, nullptr) != NC_NOERR) { return; // change to exception } // Now exists, see what variables refer to this one // First get name of this container char contname[NC_MAX_NAME + 1]; memset(contname, 0, NC_MAX_NAME + 1); if(nc_inq_varname(this->nc, container_id, contname) != NC_NOERR) { return; } // Then scan throughout the netcdfDataset if those variables geometry_container // atrribute matches the container int varCount = 0; if(nc_inq_nvars(this->nc, &varCount) != NC_NOERR) { return; } for(int curr = 0; curr < varCount; curr++) { size_t contname2_len = 0; // First find container length, and make buf that size in chars if(nc_inq_attlen(this->nc, curr, CF_SG_GEOMETRY, &contname2_len) != NC_NOERR) { // not a geometry variable, continue continue; } // Also if present but empty, go on if(contname2_len == 0) continue; // Otherwise, geometry: see what container it has char buf[NC_MAX_CHAR + 1]; memset(buf, 0, NC_MAX_CHAR + 1); if(nc_get_att_text(this->nc, curr, CF_SG_GEOMETRY, buf)!= NC_NOERR) { continue; } // If matches, then establish a reference by placing this variable's data in both vectors if(!strcmp(contname, buf)) { char property_name[NC_MAX_NAME]; nc_inq_varname(this->nc, curr, property_name); std::string n(property_name); v_ids.push_back(curr); v_headers.push_back(n); } } } // Exception Class Implementations SG_Exception_Dim_MM::SG_Exception_Dim_MM(const char* container_name, const char* field_1, const char* field_2) { std::string cn_s(container_name); std::string field1_s(field_1); std::string field2_s(field_2); this -> err_msg = "[" + cn_s + "] One or more dimensions of " + field1_s + " and " + field2_s + " do not match but must match."; } SG_Exception_Existential::SG_Exception_Existential(const char* container_name, const char* missing_name) { std::string cn_s(container_name); std::string mn_s(missing_name); this -> err_msg = "[" + cn_s + "] The property or the variable associated with " + mn_s + " is missing."; } SG_Exception_Dep::SG_Exception_Dep(const char* container_name, const char* arg1, const char* arg2) { std::string cn_s(container_name); std::string arg1_s(arg1); std::string arg2_s(arg2); this -> err_msg = "[" + cn_s + "] The attribute " + arg1_s + " may not exist without the attribute " + arg2_s + " existing."; } SG_Exception_BadSum::SG_Exception_BadSum(const char* container_name, const char* arg1, const char* arg2) { std::string cn_s(container_name); std::string arg1_s(arg1); std::string arg2_s(arg2); this -> err_msg = "[" + cn_s + "]" + " The sum of all values in " + arg1_s + " and " + arg2_s + " do not match."; } SG_Exception_General_Malformed ::SG_Exception_General_Malformed(const char * arg) { std::string arg1_s(arg); this -> err_msg = "Corruption or malformed formatting has been detected in: " + arg1_s; } // to get past linker SG_Exception::~SG_Exception() {} // Helpers // following is a short hand for a clean up and exit, since goto isn't allowed double getCFVersion(int ncid) { double ver = -1.0; std::string attrVal; // Fetch the CF attribute if(attrf(ncid, NC_GLOBAL, NCDF_CONVENTIONS, attrVal) == "") { return ver; } if(sscanf(attrVal.c_str(), "CF-%lf", &ver) != 1) { return -1.0; } return ver; } geom_t getGeometryType(int ncid, int varid) { geom_t ret = UNSUPPORTED; std::string gt_name_s; const char * gt_name= attrf(ncid, varid, CF_SG_GEOMETRY_TYPE, gt_name_s).c_str(); if(gt_name == nullptr) { return NONE; } // Points if(!strcmp(gt_name, CF_SG_TYPE_POINT)) { // Node Count not present? Assume that it is a multipoint. if(nc_inq_att(ncid, varid, CF_SG_NODE_COUNT, nullptr, nullptr) == NC_ENOTATT) { ret = POINT; } else ret = MULTIPOINT; } // Lines else if(!strcmp(gt_name, CF_SG_TYPE_LINE)) { // Part Node Count present? Assume multiline if(nc_inq_att(ncid, varid, CF_SG_PART_NODE_COUNT, nullptr, nullptr) == NC_ENOTATT) { ret = LINE; } else ret = MULTILINE; } // Polygons else if(!strcmp(gt_name, CF_SG_TYPE_POLY)) { /* Polygons versus MultiPolygons, slightly ambiguous * Part Node Count & no Interior Ring - MultiPolygon * no Part Node Count & no Interior Ring - Polygon * Part Node Count & Interior Ring - assume that it is a MultiPolygon */ int pnc_present = nc_inq_att(ncid, varid, CF_SG_PART_NODE_COUNT, nullptr, nullptr); int ir_present = nc_inq_att(ncid, varid, CF_SG_INTERIOR_RING, nullptr, nullptr); if(pnc_present == NC_ENOTATT && ir_present == NC_ENOTATT) { ret = POLYGON; } else ret = MULTIPOLYGON; } return ret; } void* inPlaceSerialize_Point(SGeometry * ge, size_t seek_pos, void * serializeBegin) { uint8_t order = 1; uint32_t t = ge->get_axisCount() == 2 ? wkbPoint: ge->get_axisCount() == 3 ? wkbPoint25D: wkbNone; if(t == wkbNone) throw SG_Exception_BadFeature(); serializeBegin = memcpy_jump(serializeBegin, &order, 1); serializeBegin = memcpy_jump(serializeBegin, &t, 4); // Now get point data; Point & p = (*ge)[seek_pos]; double x = p[0]; double y = p[1]; serializeBegin = memcpy_jump(serializeBegin, &x, 8); serializeBegin = memcpy_jump(serializeBegin, &y, 8); if(ge->get_axisCount() >= 3) { double z = p[2]; serializeBegin = memcpy_jump(serializeBegin, &z, 8); } return serializeBegin; } void* inPlaceSerialize_LineString(SGeometry * ge, int node_count, size_t seek_begin, void * serializeBegin) { uint8_t order = PLATFORM_HEADER; uint32_t t = ge->get_axisCount() == 2 ? wkbLineString: ge->get_axisCount() == 3 ? wkbLineString25D: wkbNone; if(t == wkbNone) throw SG_Exception_BadFeature(); uint32_t nc = (uint32_t) node_count; serializeBegin = memcpy_jump(serializeBegin, &order, 1); serializeBegin = memcpy_jump(serializeBegin, &t, 4); serializeBegin = memcpy_jump(serializeBegin, &nc, 4); // Now serialize points for(int ind = 0; ind < node_count; ind++) { Point & p = (*ge)[seek_begin + ind]; double x = p[0]; double y = p[1]; serializeBegin = memcpy_jump(serializeBegin, &x, 8); serializeBegin = memcpy_jump(serializeBegin, &y, 8); if(ge->get_axisCount() >= 3) { double z = p[2]; serializeBegin = memcpy_jump(serializeBegin, &z, 8); } } return serializeBegin; } void* inPlaceSerialize_PolygonExtOnly(SGeometry * ge, int node_count, size_t seek_begin, void * serializeBegin) { int8_t header = PLATFORM_HEADER; uint32_t t = ge->get_axisCount() == 2 ? wkbPolygon: ge->get_axisCount() == 3 ? wkbPolygon25D: wkbNone; if(t == wkbNone) throw SG_Exception_BadFeature(); int32_t rc = 1; void * writer = serializeBegin; writer = memcpy_jump(writer, &header, 1); writer = memcpy_jump(writer, &t, 4); writer = memcpy_jump(writer, &rc, 4); int32_t nc = (int32_t)node_count; writer = memcpy_jump(writer, &node_count, 4); for(int pind = 0; pind < nc; pind++) { Point & pt= (*ge)[seek_begin + pind]; double x = pt[0]; double y = pt[1]; writer = memcpy_jump(writer, &x, 8); writer = memcpy_jump(writer, &y, 8); if(ge->get_axisCount() >= 3) { double z = pt[2]; writer = memcpy_jump(writer, &z, 8); } } return writer; } void* inPlaceSerialize_Polygon(SGeometry * ge, std::vector<int>& pnc, int ring_count, size_t seek_begin, void * serializeBegin) { int8_t header = PLATFORM_HEADER; uint32_t t = ge->get_axisCount() == 2 ? wkbPolygon: ge->get_axisCount() == 3 ? wkbPolygon25D: wkbNone; if(t == wkbNone) throw SG_Exception_BadFeature(); int32_t rc = static_cast<int32_t>(ring_count); void * writer = serializeBegin; writer = memcpy_jump(writer, &header, 1); writer = memcpy_jump(writer, &t, 4); writer = memcpy_jump(writer, &rc, 4); int cmoffset = 0; for(int ring_c = 0; ring_c < ring_count; ring_c++) { int32_t node_count = pnc[ring_c]; writer = memcpy_jump(writer, &node_count, 4); int pind = 0; for(pind = 0; pind < pnc[ring_c]; pind++) { Point & pt= (*ge)[seek_begin + cmoffset + pind]; double x = pt[0]; double y = pt[1]; writer = memcpy_jump(writer, &x, 8); writer = memcpy_jump(writer, &y, 8); if(ge->get_axisCount() >= 3) { double z = pt[2]; writer = memcpy_jump(writer, &z, 8); } } cmoffset += pind; } return writer; } int scanForGeometryContainers(int ncid, std::vector<int> & r_ids) { int nvars; if(nc_inq_nvars(ncid, &nvars) != NC_NOERR) { return -1; } r_ids.clear(); // For each variable check for geometry attribute // If has geometry attribute, then check the associated variable ID for(int itr = 0; itr < nvars; itr++) { char c[NC_MAX_CHAR]; memset(c, 0, NC_MAX_CHAR); if(nc_get_att_text(ncid, itr, CF_SG_GEOMETRY, c) != NC_NOERR) { continue; } int varID; if(nc_inq_varid(ncid, c, &varID) != NC_NOERR) { continue; } // Now have variable ID. See if vector contains it, and if not // insert bool contains = false; for(size_t itr_1 = 0; itr_1 < r_ids.size(); itr_1++) { if(r_ids[itr_1] == varID) contains = true; } if(!contains) { r_ids.push_back(varID); } } return 0 ; } SGeometry* getGeometryRef(int ncid, const char * varName ) { int varId = 0; nc_inq_varid(ncid, varName, &varId); return new SGeometry(ncid, varId); } }
null
/****************************************************************************** * * Project: netCDF read/write Driver * Purpose: GDAL bindings over netCDF library. * Author: Winor Chen <wchen329 at wisc.edu> * ****************************************************************************** * Copyright (c) 2019, Winor Chen <wchen329 at wisc.edu> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include <cstdio> #include <cstring> #include <vector> #include "netcdf.h" #include "netcdfdataset.h" #include "netcdfsg.h" namespace nccfdriver { /* Re-implementation of mempcpy * but compatible with libraries which only implement memcpy */ static void* memcpy_jump(void *dest, const void *src, size_t n) { memcpy(dest, src, n); int8_t * byte_pointer = static_cast<int8_t*>(dest); return static_cast<void*>(byte_pointer + n); } /* Attribute Fetch * - * A function which makes it a bit easier to fetch single text attribute values * ncid: as used in netcdf.h * varID: variable id in which to look for the attribute * attrName: name of attribute to fine * alloc: a reference to a string that will be filled with the attribute (i.e. truncated and filled with the return value) * Returns: a reference to the string to fill (a.k.a. string pointed to by alloc reference) */ std::string& attrf(int ncid, int varId, const char * attrName, std::string& alloc) { size_t len = 0; nc_inq_attlen(ncid, varId, attrName, &len); if(len < 1) { alloc.clear(); return alloc; } alloc.resize(len); memset(&alloc[0], 0, len); // Now look through this variable for the attribute nc_get_att_text(ncid, varId, attrName, &alloc[0]); return alloc; } /* SGeometry * (implementations) * */ SGeometry::SGeometry(int ncId, int geoVarId) : gc_varId(geoVarId), touple_order(0), current_vert_ind(0), cur_geometry_ind(0), cur_part_ind(0) { char container_name[NC_MAX_NAME + 1]; memset(container_name, 0, NC_MAX_NAME + 1); // Get geometry container name if(nc_inq_varname(ncId, geoVarId, container_name) != NC_NOERR) { throw SG_Exception_Existential("new geometry container", "the variable of the given ID"); } // Establish string version of container_name container_name_s = std::string(container_name); // Find geometry type this->type = nccfdriver::getGeometryType(ncId, geoVarId); if(this->type == NONE) { throw SG_Exception_Existential(static_cast<const char*>(container_name), CF_SG_GEOMETRY_TYPE); } // Get grid mapping variable, if it exists this->gm_varId = INVALID_VAR_ID; if(attrf(ncId, geoVarId, CF_GRD_MAPPING, gm_name_s) != "") { const char * gm_name = gm_name_s.c_str(); int gmVID; if(nc_inq_varid(ncId, gm_name, &gmVID) == NC_NOERR) { this->gm_varId = gmVID; } } // Find a list of node counts and part node count std::string nc_name_s; std::string pnc_name_s; std::string ir_name_s; int pnc_vid = INVALID_VAR_ID; int nc_vid = INVALID_VAR_ID; int ir_vid = INVALID_VAR_ID; int buf; size_t bound = 0; size_t total_node_count = 0; // used in error checks later if(attrf(ncId, geoVarId, CF_SG_NODE_COUNT, nc_name_s) != "") { const char * nc_name = nc_name_s.c_str(); nc_inq_varid(ncId, nc_name, &nc_vid); while(nc_get_var1_int(ncId, nc_vid, &bound, &buf) == NC_NOERR) { this->node_counts.push_back(buf); total_node_count += buf; bound++; } } if(attrf(ncId, geoVarId, CF_SG_PART_NODE_COUNT, pnc_name_s) != "") { const char * pnc_name = pnc_name_s.c_str(); bound = 0; nc_inq_varid(ncId, pnc_name, &pnc_vid); while(nc_get_var1_int(ncId, pnc_vid, &bound, &buf) == NC_NOERR) { this->pnode_counts.push_back(buf); bound++; } } if(attrf(ncId, geoVarId, CF_SG_INTERIOR_RING, ir_name_s) != "") { const char * ir_name = ir_name_s.c_str(); bound = 0; nc_inq_varid(ncId, ir_name, &ir_vid); while(nc_get_var1_int(ncId, ir_vid, &bound, &buf) == NC_NOERR) { bool store = buf == 0 ? false : true; this->int_rings.push_back(store); bound++; } } /* Enforcement of well formed CF files * If these are not met then the dataset is malformed and will halt further processing of * simple geometries. */ // part node count exists only when node count exists if(pnode_counts.size() > 0 && node_counts.size() == 0) { throw SG_Exception_Dep(static_cast<const char *>(container_name), CF_SG_PART_NODE_COUNT, CF_SG_NODE_COUNT); } // interior rings only exist when part node counts exist if(int_rings.size() > 0 && pnode_counts.size() == 0) { throw SG_Exception_Dep(static_cast<const char *>(container_name), CF_SG_INTERIOR_RING, CF_SG_PART_NODE_COUNT); } // cardinality of part_node_counts == cardinality of interior_ring (if interior ring > 0) if(int_rings.size() > 0) { if(int_rings.size() != pnode_counts.size()) { throw SG_Exception_Dim_MM(static_cast<const char *>(container_name), CF_SG_INTERIOR_RING, CF_SG_PART_NODE_COUNT); } } // lines and polygons require node_counts, multipolygons are checked with part_node_count if(this->type == POLYGON || this->type == LINE) { if(node_counts.size() < 1) { throw SG_Exception_Existential(static_cast<const char*>(container_name), CF_SG_NODE_COUNT); } } /* Basic Safety checks End */ // Create bound list size_t rc = 0; bound_list.push_back(0);// start with 0 if(node_counts.size() > 0) { for(size_t i = 0; i < node_counts.size() - 1; i++) { rc = rc + node_counts[i]; bound_list.push_back(rc); } } std::string cart_s; // Node Coordinates if(attrf(ncId, geoVarId, CF_SG_NODE_COORDINATES, cart_s) == "") { throw SG_Exception_Existential(container_name, CF_SG_NODE_COORDINATES); } // Create parts count list and an offset list for parts indexing if(this->node_counts.size() > 0) { int ind = 0; int parts = 0; int prog = 0; int c = 0; for(size_t pcnt = 0; pcnt < pnode_counts.size() ; pcnt++) { if(prog == 0) pnc_bl.push_back(pcnt); if(int_rings.size() > 0 && !int_rings[pcnt]) c++; prog = prog + pnode_counts[pcnt]; parts++; if(prog == node_counts[ind]) { ind++; this->parts_count.push_back(parts); if(int_rings.size() > 0) this->poly_count.push_back(c); c = 0; prog = 0; parts = 0; } else if(prog > node_counts[ind]) { throw SG_Exception_BadSum(container_name, CF_SG_PART_NODE_COUNT, CF_SG_NODE_COUNT); } } } // (1) the touple order for a single point // (2) the variable ids with the relevant coordinate values int X = INVALID_VAR_ID; int Y = INVALID_VAR_ID; int Z = INVALID_VAR_ID; char cart[NC_MAX_NAME + 1]; memset(cart, 0, NC_MAX_NAME + 1); strncpy(cart, cart_s.c_str(), NC_MAX_NAME); char * dim = strtok(cart, " "); int axis_id = 0; while(dim != nullptr) { if(nc_inq_varid(ncId, dim, &axis_id) == NC_NOERR) { // Check axis signature std::string a_sig; attrf(ncId, axis_id, CF_AXIS, a_sig); // If valid signify axis correctly if(a_sig == "X") { X = axis_id; } else if(a_sig == "Y") { Y = axis_id; } else if(a_sig == "Z") { Z = axis_id; } else { throw SG_Exception_Dep(container_name, "A node_coordinates variable", CF_AXIS); } this->touple_order++; } else { throw SG_Exception_Existential(container_name, dim); } dim = strtok(nullptr, " "); } // Write axis in X, Y, Z order if(X != INVALID_VAR_ID) this->nodec_varIds.push_back(X); else { throw SG_Exception_Existential(container_name, "node_coordinates: X-axis"); } if(Y != INVALID_VAR_ID) this->nodec_varIds.push_back(Y); else { throw SG_Exception_Existential(container_name, "node_coordinates: Y-axis"); } if(Z != INVALID_VAR_ID) this->nodec_varIds.push_back(Z); /* Final Checks for node coordinates * (1) Each axis has one and only one dimension, dim length of each node coordinates are all equal * (2) total node count == dim length of each node coordinates (if node_counts not empty) * (3) there are at least two node coordinate variable ids */ int all_dim = INVALID_VAR_ID; bool dim_set = false; int dimC = 0; //(1) one dimension check, each node_coordinates have same dimension for(size_t nvitr = 0; nvitr < nodec_varIds.size(); nvitr++) { dimC = 0; nc_inq_varndims(ncId, nodec_varIds[nvitr], &dimC); if(dimC != 1) { throw SG_Exception_Not1D(); } // check that all have same dimension int inter_dim[1]; if(nc_inq_vardimid(ncId, nodec_varIds[nvitr], inter_dim) != NC_NOERR) { throw SG_Exception_Existential(container_name, "one or more node_coordinate dimensions"); } if(!dim_set) { all_dim = inter_dim[0]; } else { if (inter_dim[0] != all_dim) throw SG_Exception_Dim_MM(container_name, "X, Y", "in general all node coordinate axes"); } } // (2) check equality one if(node_counts.size() > 0) { size_t diml = 0; nc_inq_dimlen(ncId, all_dim, &diml); if(diml != total_node_count) throw SG_Exception_BadSum(container_name, "node_count", "node coordinate dimension length"); } // (3) check touple order if(this->touple_order < 2) { throw SG_Exception_Existential(container_name, "insufficent node coordinates must have at least two axis"); } /* Investigate for instance dimension * The procedure is as follows * * (1) if there's node_count, use the dimension used to index node count * (2) otherwise it's point (singleton) data, in this case use the node coordinate dimension */ size_t instance_dim_len = 0; if(node_counts.size() >= 1) { int nc_dims = 0; nc_inq_varndims(ncId, nc_vid, &nc_dims); if(nc_dims != 1) throw SG_Exception_Not1D(); int nc_dim_id[1]; if(nc_inq_vardimid(ncId, nc_vid, nc_dim_id) != NC_NOERR) { throw SG_Exception_Existential(container_name, "node_count dimension"); } this->inst_dimId = nc_dim_id[0]; } else { this->inst_dimId = all_dim; } nc_inq_dimlen(ncId, this->inst_dimId, &instance_dim_len); if(instance_dim_len == 0) throw SG_Exception_EmptyDim(); // Set values accordingly this->inst_dimLen = instance_dim_len; this->pt_buffer = std::unique_ptr<Point>(new Point(this->touple_order)); this->gc_varId = geoVarId; this->current_vert_ind = 0; this->ncid = ncId; } Point& SGeometry::next_pt() { if(!this->has_next_pt()) { throw SG_Exception_BadPoint(); } // Fill pt // New pt now for(int order = 0; order < touple_order; order++) { Point& pt = *(this->pt_buffer); double data; size_t full_ind = bound_list[cur_geometry_ind] + current_vert_ind; // Read a single coord int err = nc_get_var1_double(ncid, nodec_varIds[order], &full_ind, &data); // To do: optimize through multiple reads at once, instead of one datum if(err != NC_NOERR) { throw SG_Exception_BadPoint(); } pt[order] = data; } this->current_vert_ind++; return *(this->pt_buffer); } bool SGeometry::has_next_pt() { if(this->current_vert_ind < node_counts[cur_geometry_ind]) { return true; } else return false; } void SGeometry::next_geometry() { // to do: maybe implement except. and such on error conds. this->cur_geometry_ind++; this->cur_part_ind = 0; this->current_vert_ind = 0; } bool SGeometry::has_next_geometry() { if(this->cur_geometry_ind < node_counts.size()) { return true; } else return false; } Point& SGeometry::operator[](size_t index) { for(int order = 0; order < touple_order; order++) { Point& pt = *(this->pt_buffer); double data; size_t real_ind = index; // Read a single coord int err = nc_get_var1_double(ncid, nodec_varIds[order], &real_ind, &data); if(err != NC_NOERR) { throw SG_Exception_BadPoint(); } pt[order] = data; } return *(this->pt_buffer); } size_t SGeometry::get_geometry_count() { if(type == POINT) { // If nodes global attribute is available, use that // Otherwise, don't fail- use dimension length of one of x if(this->nodec_varIds.size() < 1) return 0; // If more than one dim, then error. Otherwise inquire its length and return that int dims; if(nc_inq_varndims(this->ncid, nodec_varIds[0], &dims) != NC_NOERR) return 0; if(dims != 1) return 0; // Find which dimension is used for x int index; if(nc_inq_vardimid(this->ncid, nodec_varIds[0], &index) != NC_NOERR) { return 0; } // Finally find the length size_t len; if(nc_inq_dimlen(this->ncid, index, &len) != NC_NOERR) { return 0; } return len; } else return this->node_counts.size(); } /* serializeToWKB(SGeometry * sg) * Takes the geometry in SGeometry at a given index and converts it into WKB format. * Converting SGeometry into WKB automatically allocates the required buffer space * and returns a buffer that MUST be free'd */ unsigned char * SGeometry::serializeToWKB(size_t featureInd, int& wkbSize) { unsigned char * ret = nullptr; int nc = 0; size_t sb = 0; // Points don't have node_count entry... only inspect and set node_counts if not a point if(this->getGeometryType() != POINT) { nc = node_counts[featureInd]; sb = bound_list[featureInd]; } // Serialization occurs differently depending on geometry // The memory requirements also differ between geometries switch(this->getGeometryType()) { case POINT: wkbSize = 1 + 4 + this->touple_order * 8; ret = new uint8_t[wkbSize]; inPlaceSerialize_Point(this, featureInd, ret); break; case LINE: wkbSize = 1 + 4 + 4 + this->touple_order * 8 * nc; ret = new uint8_t[wkbSize]; inPlaceSerialize_LineString(this, nc, sb, ret); break; case POLYGON: // A polygon has: // 1 byte header // 4 byte Type // 4 byte ring count (1 (exterior)) [assume only exterior rings, otherwise multipolygon] // For each ring: // 4 byte point count, 8 byte double x point count x # dimension // (This is equivalent to requesting enough for all points and a point count header for each point) // (Or 8 byte double x node count x # dimension + 4 byte point count x part_count) // if interior ring, then assume that it will be a multipolygon (maybe future work?) wkbSize = 1 + 4 + 4 + 4 + this->touple_order * 8 * nc; ret = new uint8_t[wkbSize]; inPlaceSerialize_PolygonExtOnly(this, nc, sb, ret); break; case MULTIPOINT: { wkbSize = 1 + 4 + 4 + nc * (1 + 4 + this->touple_order * 8); ret = new uint8_t[wkbSize]; void * worker = ret; int8_t header = PLATFORM_HEADER; uint32_t t = this->touple_order == 2 ? wkbMultiPoint : this->touple_order == 3 ? wkbMultiPoint25D : wkbNone; if(t == wkbNone) throw SG_Exception_BadFeature(); // Add metadata worker = memcpy_jump(worker, &header, 1); worker = memcpy_jump(worker, &t, 4); worker = memcpy_jump(worker, &nc, 4); // Add points for(int pts = 0; pts < nc; pts++) { worker = inPlaceSerialize_Point(this, static_cast<size_t>(sb + pts), worker); } } break; case MULTILINE: { int8_t header = PLATFORM_HEADER; uint32_t t = this->touple_order == 2 ? wkbMultiLineString : this->touple_order == 3 ? wkbMultiLineString25D : wkbNone; if(t == wkbNone) throw SG_Exception_BadFeature(); int32_t lc = parts_count[featureInd]; size_t seek_begin = sb; size_t pc_begin = pnc_bl[featureInd]; // initialize with first part count, list of part counts is contiguous wkbSize = 1 + 4 + 4; std::vector<int> pnc; // Build sub vector for part_node_counts // + Calculate wkbSize for(int itr = 0; itr < lc; itr++) { pnc.push_back(pnode_counts[pc_begin + itr]); wkbSize += this->touple_order * 8 * pnc[itr] + 1 + 4 + 4; } size_t cur_point = seek_begin; size_t pcount = pnc.size(); // Allocate and set pointers ret = new uint8_t[wkbSize]; void * worker = ret; // Begin Writing worker = memcpy_jump(worker, &header, 1); worker = memcpy_jump(worker, &t, 4); worker = memcpy_jump(worker, &pcount, 4); for(size_t itr = 0; itr < pcount; itr++) { worker = inPlaceSerialize_LineString(this, pnc[itr], cur_point, worker); cur_point = pnc[itr] + cur_point; } } break; case MULTIPOLYGON: { int8_t header = PLATFORM_HEADER; uint32_t t = this->touple_order == 2 ? wkbMultiPolygon: this->touple_order == 3 ? wkbMultiPolygon25D: wkbNone; if(t == wkbNone) throw SG_Exception_BadFeature(); bool noInteriors = this->int_rings.size() == 0 ? true : false; int32_t rc = parts_count[featureInd]; size_t seek_begin = sb; size_t pc_begin = pnc_bl[featureInd]; // initialize with first part count, list of part counts is contiguous wkbSize = 1 + 4 + 4; std::vector<int> pnc; // Build sub vector for part_node_counts for(int itr = 0; itr < rc; itr++) { pnc.push_back(pnode_counts[pc_begin + itr]); } // Figure out each Polygon's space requirements if(noInteriors) { for(int ss = 0; ss < rc; ss++) { wkbSize += 8 * this->touple_order * pnc[ss] + 1 + 4 + 4 + 4; } } else { // Total space requirements for Polygons: // (1 + 4 + 4) * number of Polygons // 4 * number of Rings Total // 8 * touple_order * number of Points // Each ring collection corresponds to a polygon wkbSize += (1 + 4 + 4) * poly_count[featureInd]; // (headers) // Add header requirements for rings wkbSize += 4 * parts_count[featureInd]; // Add requirements for number of points wkbSize += 8 * this->touple_order * nc; } // Now allocate and serialize ret = new uint8_t[wkbSize]; // Create Multipolygon headers void * worker = (void*)ret; worker = memcpy_jump(worker, &header, 1); worker = memcpy_jump(worker, &t, 4); if(noInteriors) { size_t cur_point = seek_begin; size_t pcount = pnc.size(); worker = memcpy_jump(worker, &pcount, 4); for(size_t itr = 0; itr < pcount; itr++) { worker = inPlaceSerialize_PolygonExtOnly(this, pnc[itr], cur_point, worker); cur_point = pnc[itr] + cur_point; } } else { int32_t polys = poly_count[featureInd]; worker = memcpy_jump(worker, &polys, 4); size_t base = pnc_bl[featureInd]; // beginning of parts_count for this multigeometry size_t seek = seek_begin; // beginning of node range for this multigeometry size_t ir_base = base + 1; int rc_m = 1; // has interior rings, for(int32_t itr = 0; itr < polys; itr++) { rc_m = 1; // count how many parts belong to each Polygon while(ir_base < int_rings.size() && int_rings[ir_base]) { rc_m++; ir_base++; } if(rc_m == 1) ir_base++; // single polygon case std::vector<int> poly_parts; // Make part node count sub vector for(int itr_2 = 0; itr_2 < rc_m; itr_2++) { poly_parts.push_back(pnode_counts[base + itr_2]); } worker = inPlaceSerialize_Polygon(this, poly_parts, rc_m, seek, worker); // Update seek position for(size_t itr_3 = 0; itr_3 < poly_parts.size(); itr_3++) { seek += poly_parts[itr_3]; } } } } break; default: throw SG_Exception_BadFeature(); break; } return ret; } void SGeometry_PropertyScanner::open(int container_id) { // First check for container_id, if variable doesn't exist error out if(nc_inq_var(this->nc, container_id, nullptr, nullptr, nullptr, nullptr, nullptr) != NC_NOERR) { return; // change to exception } // Now exists, see what variables refer to this one // First get name of this container char contname[NC_MAX_NAME + 1]; memset(contname, 0, NC_MAX_NAME + 1); if(nc_inq_varname(this->nc, container_id, contname) != NC_NOERR) { return; } // Then scan throughout the netcdfDataset if those variables geometry_container // atrribute matches the container int varCount = 0; if(nc_inq_nvars(this->nc, &varCount) != NC_NOERR) { return; } for(int curr = 0; curr < varCount; curr++) { size_t contname2_len = 0; // First find container length, and make buf that size in chars if(nc_inq_attlen(this->nc, curr, CF_SG_GEOMETRY, &contname2_len) != NC_NOERR) { // not a geometry variable, continue continue; } // Also if present but empty, go on if(contname2_len == 0) continue; // Otherwise, geometry: see what container it has char buf[NC_MAX_CHAR + 1]; memset(buf, 0, NC_MAX_CHAR + 1); if(nc_get_att_text(this->nc, curr, CF_SG_GEOMETRY, buf)!= NC_NOERR) { continue; } // If matches, then establish a reference by placing this variable's data in both vectors if(!strcmp(contname, buf)) { char property_name[NC_MAX_NAME]; nc_inq_varname(this->nc, curr, property_name); std::string n(property_name); v_ids.push_back(curr); v_headers.push_back(n); } } } // Exception Class Implementations SG_Exception_Dim_MM::SG_Exception_Dim_MM(const char* container_name, const char* field_1, const char* field_2) { std::string cn_s(container_name); std::string field1_s(field_1); std::string field2_s(field_2); this -> err_msg = "[" + cn_s + "] One or more dimensions of " + field1_s + " and " + field2_s + " do not match but must match."; } SG_Exception_Existential::SG_Exception_Existential(const char* container_name, const char* missing_name) { std::string cn_s(container_name); std::string mn_s(missing_name); this -> err_msg = "[" + cn_s + "] The property or the variable associated with " + mn_s + " is missing."; } SG_Exception_Dep::SG_Exception_Dep(const char* container_name, const char* arg1, const char* arg2) { std::string cn_s(container_name); std::string arg1_s(arg1); std::string arg2_s(arg2); this -> err_msg = "[" + cn_s + "] The attribute " + arg1_s + " may not exist without the attribute " + arg2_s + " existing."; } SG_Exception_BadSum::SG_Exception_BadSum(const char* container_name, const char* arg1, const char* arg2) { std::string cn_s(container_name); std::string arg1_s(arg1); std::string arg2_s(arg2); this -> err_msg = "[" + cn_s + "]" + " The sum of all values in " + arg1_s + " and " + arg2_s + " do not match."; } SG_Exception_General_Malformed ::SG_Exception_General_Malformed(const char * arg) { std::string arg1_s(arg); this -> err_msg = "Corruption or malformed formatting has been detected in: " + arg1_s; } // to get past linker SG_Exception::~SG_Exception() {} // Helpers // following is a short hand for a clean up and exit, since goto isn't allowed double getCFVersion(int ncid) { double ver = -1.0; std::string attrVal; // Fetch the CF attribute if(attrf(ncid, NC_GLOBAL, NCDF_CONVENTIONS, attrVal) == "") { return ver; } if(sscanf(attrVal.c_str(), "CF-%lf", &ver) != 1) { return -1.0; } return ver; } geom_t getGeometryType(int ncid, int varid) { geom_t ret = UNSUPPORTED; std::string gt_name_s; const char * gt_name= attrf(ncid, varid, CF_SG_GEOMETRY_TYPE, gt_name_s).c_str(); if(gt_name == nullptr) { return NONE; } // Points if(!strcmp(gt_name, CF_SG_TYPE_POINT)) { // Node Count not present? Assume that it is a multipoint. if(nc_inq_att(ncid, varid, CF_SG_NODE_COUNT, nullptr, nullptr) == NC_ENOTATT) { ret = POINT; } else ret = MULTIPOINT; } // Lines else if(!strcmp(gt_name, CF_SG_TYPE_LINE)) { // Part Node Count present? Assume multiline if(nc_inq_att(ncid, varid, CF_SG_PART_NODE_COUNT, nullptr, nullptr) == NC_ENOTATT) { ret = LINE; } else ret = MULTILINE; } // Polygons else if(!strcmp(gt_name, CF_SG_TYPE_POLY)) { /* Polygons versus MultiPolygons, slightly ambiguous * Part Node Count & no Interior Ring - MultiPolygon * no Part Node Count & no Interior Ring - Polygon * Part Node Count & Interior Ring - assume that it is a MultiPolygon */ int pnc_present = nc_inq_att(ncid, varid, CF_SG_PART_NODE_COUNT, nullptr, nullptr); int ir_present = nc_inq_att(ncid, varid, CF_SG_INTERIOR_RING, nullptr, nullptr); if(pnc_present == NC_ENOTATT && ir_present == NC_ENOTATT) { ret = POLYGON; } else ret = MULTIPOLYGON; } return ret; } void* inPlaceSerialize_Point(SGeometry * ge, size_t seek_pos, void * serializeBegin) { uint8_t order = 1; uint32_t t = ge->get_axisCount() == 2 ? wkbPoint: ge->get_axisCount() == 3 ? wkbPoint25D: wkbNone; if(t == wkbNone) throw SG_Exception_BadFeature(); serializeBegin = memcpy_jump(serializeBegin, &order, 1); serializeBegin = memcpy_jump(serializeBegin, &t, 4); // Now get point data; Point & p = (*ge)[seek_pos]; double x = p[0]; double y = p[1]; serializeBegin = memcpy_jump(serializeBegin, &x, 8); serializeBegin = memcpy_jump(serializeBegin, &y, 8); if(ge->get_axisCount() >= 3) { double z = p[2]; serializeBegin = memcpy_jump(serializeBegin, &z, 8); } return serializeBegin; } void* inPlaceSerialize_LineString(SGeometry * ge, int node_count, size_t seek_begin, void * serializeBegin) { uint8_t order = PLATFORM_HEADER; uint32_t t = ge->get_axisCount() == 2 ? wkbLineString: ge->get_axisCount() == 3 ? wkbLineString25D: wkbNone; if(t == wkbNone) throw SG_Exception_BadFeature(); uint32_t nc = (uint32_t) node_count; serializeBegin = memcpy_jump(serializeBegin, &order, 1); serializeBegin = memcpy_jump(serializeBegin, &t, 4); serializeBegin = memcpy_jump(serializeBegin, &nc, 4); // Now serialize points for(int ind = 0; ind < node_count; ind++) { Point & p = (*ge)[seek_begin + ind]; double x = p[0]; double y = p[1]; serializeBegin = memcpy_jump(serializeBegin, &x, 8); serializeBegin = memcpy_jump(serializeBegin, &y, 8); if(ge->get_axisCount() >= 3) { double z = p[2]; serializeBegin = memcpy_jump(serializeBegin, &z, 8); } } return serializeBegin; } void* inPlaceSerialize_PolygonExtOnly(SGeometry * ge, int node_count, size_t seek_begin, void * serializeBegin) { int8_t header = PLATFORM_HEADER; uint32_t t = ge->get_axisCount() == 2 ? wkbPolygon: ge->get_axisCount() == 3 ? wkbPolygon25D: wkbNone; if(t == wkbNone) throw SG_Exception_BadFeature(); int32_t rc = 1; void * writer = serializeBegin; writer = memcpy_jump(writer, &header, 1); writer = memcpy_jump(writer, &t, 4); writer = memcpy_jump(writer, &rc, 4); int32_t nc = (int32_t)node_count; writer = memcpy_jump(writer, &node_count, 4); for(int pind = 0; pind < nc; pind++) { Point & pt= (*ge)[seek_begin + pind]; double x = pt[0]; double y = pt[1]; writer = memcpy_jump(writer, &x, 8); writer = memcpy_jump(writer, &y, 8); if(ge->get_axisCount() >= 3) { double z = pt[2]; writer = memcpy_jump(writer, &z, 8); } } return writer; } void* inPlaceSerialize_Polygon(SGeometry * ge, std::vector<int>& pnc, int ring_count, size_t seek_begin, void * serializeBegin) { int8_t header = PLATFORM_HEADER; uint32_t t = ge->get_axisCount() == 2 ? wkbPolygon: ge->get_axisCount() == 3 ? wkbPolygon25D: wkbNone; if(t == wkbNone) throw SG_Exception_BadFeature(); int32_t rc = static_cast<int32_t>(ring_count); void * writer = serializeBegin; writer = memcpy_jump(writer, &header, 1); writer = memcpy_jump(writer, &t, 4); writer = memcpy_jump(writer, &rc, 4); int cmoffset = 0; for(int ring_c = 0; ring_c < ring_count; ring_c++) { int32_t node_count = pnc[ring_c]; writer = memcpy_jump(writer, &node_count, 4); int pind = 0; for(pind = 0; pind < pnc[ring_c]; pind++) { Point & pt= (*ge)[seek_begin + cmoffset + pind]; double x = pt[0]; double y = pt[1]; writer = memcpy_jump(writer, &x, 8); writer = memcpy_jump(writer, &y, 8); if(ge->get_axisCount() >= 3) { double z = pt[2]; writer = memcpy_jump(writer, &z, 8); } } cmoffset += pind; } return writer; } int scanForGeometryContainers(int ncid, std::vector<int> & r_ids) { int nvars; if(nc_inq_nvars(ncid, &nvars) != NC_NOERR) { return -1; } r_ids.clear(); // For each variable check for geometry attribute // If has geometry attribute, then check the associated variable ID for(int itr = 0; itr < nvars; itr++) { char c[NC_MAX_CHAR]; memset(c, 0, NC_MAX_CHAR); if(nc_get_att_text(ncid, itr, CF_SG_GEOMETRY, c) != NC_NOERR) { continue; } int varID; if(nc_inq_varid(ncid, c, &varID) != NC_NOERR) { continue; } // Now have variable ID. See if vector contains it, and if not // insert bool contains = false; for(size_t itr_1 = 0; itr_1 < r_ids.size(); itr_1++) { if(r_ids[itr_1] == varID) contains = true; } if(!contains) { r_ids.push_back(varID); } } return 0 ; } SGeometry* getGeometryRef(int ncid, const char * varName ) { int varId = 0; nc_inq_varid(ncid, varName, &varId); return new SGeometry(ncid, varId); } }
null
157
CWE-787
CVE-2019-25051
#ifndef ACOMMON_OBJSTACK__HPP #define ACOMMON_OBJSTACK__HPP #include "parm_string.hpp" #include <stdlib.h> #include <assert.h> namespace acommon { class ObjStack { typedef unsigned char byte; struct Node { Node * next; byte data[1]; // hack for data[] }; size_t chunk_size; size_t min_align; Node * first; Node * first_free; Node * reserve; byte * top; byte * bottom; byte * temp_end; void setup_chunk(); void new_chunk(); ObjStack(const ObjStack &); void operator=(const ObjStack &); void align_bottom(size_t align) { size_t a = (size_t)bottom % align; if (a != 0) bottom += align - a; } void align_top(size_t align) { top -= (size_t)top % align; } public: // The alignment here is the guaranteed alignment that memory in // new chunks will be aligned to. It does NOT guarantee that // every object is aligned as such unless all objects inserted // are a multiple of align. ObjStack(size_t chunk_s = 1024, size_t align = sizeof(void *)); ~ObjStack(); size_t calc_size(); void reset(); void trim(); // This alloc_bottom does NOT check alignment. However, if you always // insert objects with a multiple of min_align than it will always // me aligned as such. void * alloc_bottom(size_t size) { byte * tmp = bottom; bottom += size; if (bottom > top) {new_chunk(); tmp = bottom; bottom += size;} return tmp; } // This alloc_bottom will insure that the object is aligned based on the // alignment given. void * alloc_bottom(size_t size, size_t align) {loop: align_bottom(align); byte * tmp = bottom; bottom += size; if (bottom > top) {new_chunk(); goto loop;} return tmp; } char * dup_bottom(ParmString str) { return (char *)memcpy(alloc_bottom(str.size() + 1), str.str(), str.size() + 1); } // This alloc_bottom does NOT check alignment. However, if you // always insert objects with a multiple of min_align than it will // always be aligned as such. void * alloc_top(size_t size) { top -= size; if (top < bottom) {new_chunk(); top -= size;} return top; } // This alloc_top will insure that the object is aligned based on // the alignment given. void * alloc_top(size_t size, size_t align) {loop: top -= size; align_top(align); if (top < bottom) {new_chunk(); goto loop;} return top; } char * dup_top(ParmString str) { return (char *)memcpy(alloc_top(str.size() + 1), str.str(), str.size() + 1); } // By default objects are allocated from the top since that is sligtly // more efficient void * alloc(size_t size) {return alloc_top(size);} void * alloc(size_t size, size_t align) {return alloc_top(size,align);} char * dup(ParmString str) {return dup_top(str);} // alloc_temp allocates an object from the bottom which can be // resized until it is committed. If the resizing will involve // moving the object than the data will be copied in the same way // realloc does. Any previously allocated objects are aborted when // alloc_temp is called. void * temp_ptr() { if (temp_end) return bottom; else return 0; } unsigned temp_size() { return temp_end - bottom; } void * alloc_temp(size_t size) { temp_end = bottom + size; if (temp_end > top) { new_chunk(); temp_end = bottom + size; } return bottom; } // returns a pointer the the new beginning of the temp memory void * resize_temp(size_t size) { if (temp_end == 0) return alloc_temp(size); if (bottom + size <= top) { temp_end = bottom + size; } else { size_t s = temp_end - bottom; byte * p = bottom; new_chunk(); memcpy(bottom, p, s); temp_end = bottom + size; } return bottom; } // returns a pointer to the beginning of the new memory (in // otherwords the END of the temp memory BEFORE the call to grow // temp) NOT the beginning if the temp memory void * grow_temp(size_t s) { if (temp_end == 0) return alloc_temp(s); unsigned old_size = temp_end - bottom; unsigned size = old_size + s; if (bottom + size <= top) { temp_end = bottom + size; } else { size_t s = temp_end - bottom; byte * p = bottom; new_chunk(); memcpy(bottom, p, s); temp_end = bottom + size; } return bottom + old_size; } void abort_temp() { temp_end = 0;} void commit_temp() { bottom = temp_end; temp_end = 0;} typedef Node Memory; Memory * freeze(); static void dealloc(Memory *); }; typedef ObjStack StringBuffer; } #endif
null
#ifndef ACOMMON_OBJSTACK__HPP #define ACOMMON_OBJSTACK__HPP #include "parm_string.hpp" #include <stdlib.h> #include <assert.h> #include <stddef.h> namespace acommon { class ObjStack { typedef unsigned char byte; struct Node { Node * next; byte data[1]; // hack for data[] }; size_t chunk_size; size_t min_align; Node * first; Node * first_free; Node * reserve; byte * top; byte * bottom; byte * temp_end; void setup_chunk(); void new_chunk(); bool will_overflow(size_t sz) const { return offsetof(Node,data) + sz > chunk_size; } void check_size(size_t sz) { assert(!will_overflow(sz)); } ObjStack(const ObjStack &); void operator=(const ObjStack &); void align_bottom(size_t align) { size_t a = (size_t)bottom % align; if (a != 0) bottom += align - a; } void align_top(size_t align) { top -= (size_t)top % align; } public: // The alignment here is the guaranteed alignment that memory in // new chunks will be aligned to. It does NOT guarantee that // every object is aligned as such unless all objects inserted // are a multiple of align. ObjStack(size_t chunk_s = 1024, size_t align = sizeof(void *)); ~ObjStack(); size_t calc_size(); void reset(); void trim(); // This alloc_bottom does NOT check alignment. However, if you always // insert objects with a multiple of min_align than it will always // me aligned as such. void * alloc_bottom(size_t size) { byte * tmp = bottom; bottom += size; if (bottom > top) {check_size(size); new_chunk(); tmp = bottom; bottom += size;} return tmp; } // This alloc_bottom will insure that the object is aligned based on the // alignment given. void * alloc_bottom(size_t size, size_t align) {loop: align_bottom(align); byte * tmp = bottom; bottom += size; if (bottom > top) {check_size(size); new_chunk(); goto loop;} return tmp; } char * dup_bottom(ParmString str) { return (char *)memcpy(alloc_bottom(str.size() + 1), str.str(), str.size() + 1); } // This alloc_bottom does NOT check alignment. However, if you // always insert objects with a multiple of min_align than it will // always be aligned as such. void * alloc_top(size_t size) { top -= size; if (top < bottom) {check_size(size); new_chunk(); top -= size;} return top; } // This alloc_top will insure that the object is aligned based on // the alignment given. void * alloc_top(size_t size, size_t align) {loop: top -= size; align_top(align); if (top < bottom) {check_size(size); new_chunk(); goto loop;} return top; } char * dup_top(ParmString str) { return (char *)memcpy(alloc_top(str.size() + 1), str.str(), str.size() + 1); } // By default objects are allocated from the top since that is sligtly // more efficient void * alloc(size_t size) {return alloc_top(size);} void * alloc(size_t size, size_t align) {return alloc_top(size,align);} char * dup(ParmString str) {return dup_top(str);} // alloc_temp allocates an object from the bottom which can be // resized until it is committed. If the resizing will involve // moving the object than the data will be copied in the same way // realloc does. Any previously allocated objects are aborted when // alloc_temp is called. void * temp_ptr() { if (temp_end) return bottom; else return 0; } unsigned temp_size() { return temp_end - bottom; } void * alloc_temp(size_t size) { temp_end = bottom + size; if (temp_end > top) { check_size(size); new_chunk(); temp_end = bottom + size; } return bottom; } // returns a pointer the the new beginning of the temp memory void * resize_temp(size_t size) { if (temp_end == 0) return alloc_temp(size); if (bottom + size <= top) { temp_end = bottom + size; } else { size_t s = temp_end - bottom; byte * p = bottom; check_size(size); new_chunk(); memcpy(bottom, p, s); temp_end = bottom + size; } return bottom; } // returns a pointer to the beginning of the new memory (in // otherwords the END of the temp memory BEFORE the call to grow // temp) NOT the beginning if the temp memory void * grow_temp(size_t s) { if (temp_end == 0) return alloc_temp(s); unsigned old_size = temp_end - bottom; unsigned size = old_size + s; if (bottom + size <= top) { temp_end = bottom + size; } else { size_t s = temp_end - bottom; byte * p = bottom; check_size(size); new_chunk(); memcpy(bottom, p, s); temp_end = bottom + size; } return bottom + old_size; } void abort_temp() { temp_end = 0;} void commit_temp() { bottom = temp_end; temp_end = 0;} typedef Node Memory; Memory * freeze(); static void dealloc(Memory *); }; typedef ObjStack StringBuffer; } #endif
null
158
CWE-787
CVE-2019-3563
/* * Copyright 2017-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/portability/GTest.h> #include <wangle/codec/FixedLengthFrameDecoder.h> #include <wangle/codec/LengthFieldBasedFrameDecoder.h> #include <wangle/codec/LengthFieldPrepender.h> #include <wangle/codec/LineBasedFrameDecoder.h> #include <wangle/codec/test/CodecTestUtils.h> using namespace folly; using namespace wangle; using namespace folly::io; namespace { auto createZeroedBuffer(size_t size) { auto ret = IOBuf::create(size); ret->append(size); std::memset(ret->writableData(), 0x00, size); return ret; } } TEST(FixedLengthFrameDecoder, FailWhenLengthFieldEndOffset) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(FixedLengthFrameDecoder(10)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 10); })) .finalize(); auto buf3 = createZeroedBuffer(3); auto buf11 = createZeroedBuffer(11); auto buf16 = createZeroedBuffer(16); IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(buf3)); pipeline->read(q); EXPECT_EQ(called, 0); q.append(std::move(buf11)); pipeline->read(q); EXPECT_EQ(called, 1); q.append(std::move(buf16)); pipeline->read(q); EXPECT_EQ(called, 3); } TEST(LengthFieldFramePipeline, SimpleTest) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(test::BytesReflector()) .addBack(LengthFieldPrepender()) .addBack(LengthFieldBasedFrameDecoder()) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 2); })) .finalize(); auto buf = createZeroedBuffer(2); pipeline->write(std::move(buf)); EXPECT_EQ(called, 1); } TEST(LengthFieldFramePipeline, LittleEndian) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(test::BytesReflector()) .addBack(LengthFieldBasedFrameDecoder(4, 100, 0, 0, 4, false)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 1); })) .addBack(LengthFieldPrepender(4, 0, false, false)) .finalize(); auto buf = createZeroedBuffer(1); pipeline->write(std::move(buf)); EXPECT_EQ(called, 1); } TEST(LengthFieldFrameDecoder, Simple) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LengthFieldBasedFrameDecoder()) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 1); })) .finalize(); auto bufFrame = createZeroedBuffer(4); RWPrivateCursor c(bufFrame.get()); c.writeBE((uint32_t)1); auto bufData = createZeroedBuffer(1); IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(bufFrame)); pipeline->read(q); EXPECT_EQ(called, 0); q.append(std::move(bufData)); pipeline->read(q); EXPECT_EQ(called, 1); } TEST(LengthFieldFrameDecoder, NoStrip) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LengthFieldBasedFrameDecoder(2, 10, 0, 0, 0)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 3); })) .finalize(); auto bufFrame = createZeroedBuffer(2); RWPrivateCursor c(bufFrame.get()); c.writeBE((uint16_t)1); auto bufData = createZeroedBuffer(1); IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(bufFrame)); pipeline->read(q); EXPECT_EQ(called, 0); q.append(std::move(bufData)); pipeline->read(q); EXPECT_EQ(called, 1); } TEST(LengthFieldFrameDecoder, Adjustment) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LengthFieldBasedFrameDecoder(2, 10, 0, -2, 0)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 3); })) .finalize(); auto bufFrame = createZeroedBuffer(2); RWPrivateCursor c(bufFrame.get()); c.writeBE((uint16_t)3); // includes frame size auto bufData = createZeroedBuffer(1); IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(bufFrame)); pipeline->read(q); EXPECT_EQ(called, 0); q.append(std::move(bufData)); pipeline->read(q); EXPECT_EQ(called, 1); } TEST(LengthFieldFrameDecoder, PreHeader) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LengthFieldBasedFrameDecoder(2, 10, 2, 0, 0)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 5); })) .finalize(); auto bufFrame = createZeroedBuffer(4); RWPrivateCursor c(bufFrame.get()); c.write((uint16_t)100); // header c.writeBE((uint16_t)1); // frame size auto bufData = createZeroedBuffer(1); IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(bufFrame)); pipeline->read(q); EXPECT_EQ(called, 0); q.append(std::move(bufData)); pipeline->read(q); EXPECT_EQ(called, 1); } TEST(LengthFieldFrameDecoder, PostHeader) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LengthFieldBasedFrameDecoder(2, 10, 0, 2, 0)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 5); })) .finalize(); auto bufFrame = createZeroedBuffer(4); RWPrivateCursor c(bufFrame.get()); c.writeBE((uint16_t)1); // frame size c.write((uint16_t)100); // header auto bufData = createZeroedBuffer(1); IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(bufFrame)); pipeline->read(q); EXPECT_EQ(called, 0); q.append(std::move(bufData)); pipeline->read(q); EXPECT_EQ(called, 1); } TEST(LengthFieldFrameDecoderStrip, PrePostHeader) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LengthFieldBasedFrameDecoder(2, 10, 2, 2, 4)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 3); })) .finalize(); auto bufFrame = createZeroedBuffer(6); RWPrivateCursor c(bufFrame.get()); c.write((uint16_t)100); // pre header c.writeBE((uint16_t)1); // frame size c.write((uint16_t)100); // post header auto bufData = createZeroedBuffer(1); IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(bufFrame)); pipeline->read(q); EXPECT_EQ(called, 0); q.append(std::move(bufData)); pipeline->read(q); EXPECT_EQ(called, 1); } TEST(LengthFieldFrameDecoder, StripPrePostHeaderFrameInclHeader) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LengthFieldBasedFrameDecoder(2, 10, 2, -2, 4)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 3); })) .finalize(); auto bufFrame = createZeroedBuffer(6); RWPrivateCursor c(bufFrame.get()); c.write((uint16_t)100); // pre header c.writeBE((uint16_t)5); // frame size c.write((uint16_t)100); // post header auto bufData = createZeroedBuffer(1); IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(bufFrame)); pipeline->read(q); EXPECT_EQ(called, 0); q.append(std::move(bufData)); pipeline->read(q); EXPECT_EQ(called, 1); } TEST(LengthFieldFrameDecoder, FailTestLengthFieldEndOffset) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LengthFieldBasedFrameDecoder(4, 10, 4, -2, 4)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { ASSERT_EQ(nullptr, buf); called++; })) .finalize(); auto bufFrame = createZeroedBuffer(8); RWPrivateCursor c(bufFrame.get()); c.writeBE((uint32_t)0); // frame size c.write((uint32_t)0); // crap IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(bufFrame)); pipeline->read(q); EXPECT_EQ(called, 1); } TEST(LengthFieldFrameDecoder, FailTestLengthFieldFrameSize) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LengthFieldBasedFrameDecoder(4, 10, 0, 0, 4)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { ASSERT_EQ(nullptr, buf); called++; })) .finalize(); auto bufFrame = createZeroedBuffer(16); RWPrivateCursor c(bufFrame.get()); c.writeBE((uint32_t)12); // frame size c.write((uint32_t)0); // nothing c.write((uint32_t)0); // nothing c.write((uint32_t)0); // nothing IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(bufFrame)); pipeline->read(q); EXPECT_EQ(called, 1); } TEST(LengthFieldFrameDecoder, FailTestLengthFieldInitialBytes) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LengthFieldBasedFrameDecoder(4, 10, 0, 0, 10)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { ASSERT_EQ(nullptr, buf); called++; })) .finalize(); auto bufFrame = createZeroedBuffer(16); RWPrivateCursor c(bufFrame.get()); c.writeBE((uint32_t)4); // frame size c.write((uint32_t)0); // nothing c.write((uint32_t)0); // nothing c.write((uint32_t)0); // nothing IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(bufFrame)); pipeline->read(q); EXPECT_EQ(called, 1); } TEST(LengthFieldFrameDecoder, FailTestNotEnoughBytes) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LengthFieldBasedFrameDecoder(4, 10, 0, 0, 0)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { ASSERT_EQ(nullptr, buf); called++; })) .finalize(); auto bufFrame = createZeroedBuffer(16); RWPrivateCursor c(bufFrame.get()); c.writeBE((uint32_t)7); // frame size - 1 byte too large (7 > 10 - 4) c.write((uint32_t)0); // nothing c.write((uint32_t)0); // nothing c.write((uint32_t)0); // nothing IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(bufFrame)); pipeline->read(q); EXPECT_EQ(called, 1); } TEST(LineBasedFrameDecoder, Simple) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LineBasedFrameDecoder(10)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 3); })) .finalize(); auto buf = createZeroedBuffer(3); IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(buf)); pipeline->read(q); EXPECT_EQ(called, 0); buf = createZeroedBuffer(1); RWPrivateCursor c(buf.get()); c.write<char>('\n'); q.append(std::move(buf)); pipeline->read(q); EXPECT_EQ(called, 1); buf = createZeroedBuffer(4); RWPrivateCursor c1(buf.get()); c1.write(' '); c1.write(' '); c1.write(' '); c1.write('\r'); q.append(std::move(buf)); pipeline->read(q); EXPECT_EQ(called, 1); buf = createZeroedBuffer(1); RWPrivateCursor c2(buf.get()); c2.write('\n'); q.append(std::move(buf)); pipeline->read(q); EXPECT_EQ(called, 2); } TEST(LineBasedFrameDecoder, SaveDelimiter) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LineBasedFrameDecoder(10, false)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 4); })) .finalize(); auto buf = createZeroedBuffer(3); IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(buf)); pipeline->read(q); EXPECT_EQ(called, 0); buf = createZeroedBuffer(1); RWPrivateCursor c(buf.get()); c.write<char>('\n'); q.append(std::move(buf)); pipeline->read(q); EXPECT_EQ(called, 1); buf = createZeroedBuffer(3); RWPrivateCursor c1(buf.get()); c1.write(' '); c1.write(' '); c1.write('\r'); q.append(std::move(buf)); pipeline->read(q); EXPECT_EQ(called, 1); buf = createZeroedBuffer(1); RWPrivateCursor c2(buf.get()); c2.write('\n'); q.append(std::move(buf)); pipeline->read(q); EXPECT_EQ(called, 2); } TEST(LineBasedFrameDecoder, Fail) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LineBasedFrameDecoder(10)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { ASSERT_EQ(nullptr, buf); called++; })) .finalize(); auto buf = createZeroedBuffer(11); IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(buf)); pipeline->read(q); EXPECT_EQ(called, 1); buf = createZeroedBuffer(1); q.append(std::move(buf)); pipeline->read(q); EXPECT_EQ(called, 1); buf = createZeroedBuffer(2); RWPrivateCursor c(buf.get()); c.write(' '); c.write<char>('\n'); q.append(std::move(buf)); pipeline->read(q); EXPECT_EQ(called, 1); buf = createZeroedBuffer(12); RWPrivateCursor c2(buf.get()); for (int i = 0; i < 11; i++) { c2.write(' '); } c2.write<char>('\n'); q.append(std::move(buf)); pipeline->read(q); EXPECT_EQ(called, 2); } TEST(LineBasedFrameDecoder, NewLineOnly) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LineBasedFrameDecoder( 10, true, LineBasedFrameDecoder::TerminatorType::NEWLINE)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 1); })) .finalize(); auto buf = createZeroedBuffer(2); RWPrivateCursor c(buf.get()); c.write<char>('\r'); c.write<char>('\n'); IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(buf)); pipeline->read(q); EXPECT_EQ(called, 1); } TEST(LineBasedFrameDecoder, CarriageNewLineOnly) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LineBasedFrameDecoder( 10, true, LineBasedFrameDecoder::TerminatorType::CARRIAGENEWLINE)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 1); })) .finalize(); auto buf = createZeroedBuffer(3); RWPrivateCursor c(buf.get()); c.write<char>('\n'); c.write<char>('\r'); c.write<char>('\n'); IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(buf)); pipeline->read(q); EXPECT_EQ(called, 1); }
null
/* * Copyright 2017-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/portability/GTest.h> #include <wangle/codec/FixedLengthFrameDecoder.h> #include <wangle/codec/LengthFieldBasedFrameDecoder.h> #include <wangle/codec/LengthFieldPrepender.h> #include <wangle/codec/LineBasedFrameDecoder.h> #include <wangle/codec/test/CodecTestUtils.h> using namespace folly; using namespace wangle; using namespace folly::io; namespace { auto createZeroedBuffer(size_t size) { auto ret = IOBuf::create(size); ret->append(size); std::memset(ret->writableData(), 0x00, size); return ret; } } TEST(FixedLengthFrameDecoder, FailWhenLengthFieldEndOffset) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(FixedLengthFrameDecoder(10)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 10); })) .finalize(); auto buf3 = createZeroedBuffer(3); auto buf11 = createZeroedBuffer(11); auto buf16 = createZeroedBuffer(16); IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(buf3)); pipeline->read(q); EXPECT_EQ(called, 0); q.append(std::move(buf11)); pipeline->read(q); EXPECT_EQ(called, 1); q.append(std::move(buf16)); pipeline->read(q); EXPECT_EQ(called, 3); } TEST(LengthFieldFramePipeline, SimpleTest) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(test::BytesReflector()) .addBack(LengthFieldPrepender()) .addBack(LengthFieldBasedFrameDecoder()) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 2); })) .finalize(); auto buf = createZeroedBuffer(2); pipeline->write(std::move(buf)); EXPECT_EQ(called, 1); } TEST(LengthFieldFramePipeline, LittleEndian) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(test::BytesReflector()) .addBack(LengthFieldBasedFrameDecoder(4, 100, 0, 0, 4, false)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 1); })) .addBack(LengthFieldPrepender(4, 0, false, false)) .finalize(); auto buf = createZeroedBuffer(1); pipeline->write(std::move(buf)); EXPECT_EQ(called, 1); } TEST(LengthFieldFrameDecoder, Simple) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LengthFieldBasedFrameDecoder()) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 1); })) .finalize(); auto bufFrame = createZeroedBuffer(4); RWPrivateCursor c(bufFrame.get()); c.writeBE((uint32_t)1); auto bufData = createZeroedBuffer(1); IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(bufFrame)); pipeline->read(q); EXPECT_EQ(called, 0); q.append(std::move(bufData)); pipeline->read(q); EXPECT_EQ(called, 1); } TEST(LengthFieldFrameDecoder, NoStrip) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LengthFieldBasedFrameDecoder(2, 10, 0, 0, 0)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 3); })) .finalize(); auto bufFrame = createZeroedBuffer(2); RWPrivateCursor c(bufFrame.get()); c.writeBE((uint16_t)1); auto bufData = createZeroedBuffer(1); IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(bufFrame)); pipeline->read(q); EXPECT_EQ(called, 0); q.append(std::move(bufData)); pipeline->read(q); EXPECT_EQ(called, 1); } TEST(LengthFieldFrameDecoder, Adjustment) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LengthFieldBasedFrameDecoder(2, 10, 0, -2, 0)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 3); })) .finalize(); auto bufFrame = createZeroedBuffer(2); RWPrivateCursor c(bufFrame.get()); c.writeBE((uint16_t)3); // includes frame size auto bufData = createZeroedBuffer(1); IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(bufFrame)); pipeline->read(q); EXPECT_EQ(called, 0); q.append(std::move(bufData)); pipeline->read(q); EXPECT_EQ(called, 1); } TEST(LengthFieldFrameDecoder, PreHeader) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LengthFieldBasedFrameDecoder(2, 10, 2, 0, 0)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 5); })) .finalize(); auto bufFrame = createZeroedBuffer(4); RWPrivateCursor c(bufFrame.get()); c.write((uint16_t)100); // header c.writeBE((uint16_t)1); // frame size auto bufData = createZeroedBuffer(1); IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(bufFrame)); pipeline->read(q); EXPECT_EQ(called, 0); q.append(std::move(bufData)); pipeline->read(q); EXPECT_EQ(called, 1); } TEST(LengthFieldFrameDecoder, PostHeader) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LengthFieldBasedFrameDecoder(2, 10, 0, 2, 0)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 5); })) .finalize(); auto bufFrame = createZeroedBuffer(4); RWPrivateCursor c(bufFrame.get()); c.writeBE((uint16_t)1); // frame size c.write((uint16_t)100); // header auto bufData = createZeroedBuffer(1); IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(bufFrame)); pipeline->read(q); EXPECT_EQ(called, 0); q.append(std::move(bufData)); pipeline->read(q); EXPECT_EQ(called, 1); } TEST(LengthFieldFrameDecoderStrip, PrePostHeader) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LengthFieldBasedFrameDecoder(2, 10, 2, 2, 4)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 3); })) .finalize(); auto bufFrame = createZeroedBuffer(6); RWPrivateCursor c(bufFrame.get()); c.write((uint16_t)100); // pre header c.writeBE((uint16_t)1); // frame size c.write((uint16_t)100); // post header auto bufData = createZeroedBuffer(1); IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(bufFrame)); pipeline->read(q); EXPECT_EQ(called, 0); q.append(std::move(bufData)); pipeline->read(q); EXPECT_EQ(called, 1); } TEST(LengthFieldFrameDecoder, StripPrePostHeaderFrameInclHeader) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LengthFieldBasedFrameDecoder(2, 10, 2, -2, 4)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 3); })) .finalize(); auto bufFrame = createZeroedBuffer(6); RWPrivateCursor c(bufFrame.get()); c.write((uint16_t)100); // pre header c.writeBE((uint16_t)5); // frame size c.write((uint16_t)100); // post header auto bufData = createZeroedBuffer(1); IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(bufFrame)); pipeline->read(q); EXPECT_EQ(called, 0); q.append(std::move(bufData)); pipeline->read(q); EXPECT_EQ(called, 1); } TEST(LengthFieldFrameDecoder, FailTestLengthFieldEndOffset) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LengthFieldBasedFrameDecoder(4, 10, 4, -2, 4)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { ASSERT_EQ(nullptr, buf); called++; })) .finalize(); auto bufFrame = createZeroedBuffer(8); RWPrivateCursor c(bufFrame.get()); c.writeBE((uint32_t)0); // frame size c.write((uint32_t)0); // crap IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(bufFrame)); pipeline->read(q); EXPECT_EQ(called, 1); } TEST(LengthFieldFrameDecoder, FailTestLengthFieldFrameSize) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LengthFieldBasedFrameDecoder(4, 10, 0, 0, 4)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { ASSERT_EQ(nullptr, buf); called++; })) .finalize(); auto bufFrame = createZeroedBuffer(16); RWPrivateCursor c(bufFrame.get()); c.writeBE((uint32_t)12); // frame size c.write((uint32_t)0); // nothing c.write((uint32_t)0); // nothing c.write((uint32_t)0); // nothing IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(bufFrame)); pipeline->read(q); EXPECT_EQ(called, 1); } TEST(LengthFieldFrameDecoder, FailTestLengthFieldInitialBytes) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LengthFieldBasedFrameDecoder(4, 10, 0, 0, 10)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { ASSERT_EQ(nullptr, buf); called++; })) .finalize(); auto bufFrame = createZeroedBuffer(16); RWPrivateCursor c(bufFrame.get()); c.writeBE((uint32_t)4); // frame size c.write((uint32_t)0); // nothing c.write((uint32_t)0); // nothing c.write((uint32_t)0); // nothing IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(bufFrame)); pipeline->read(q); EXPECT_EQ(called, 1); } TEST(LengthFieldFrameDecoder, FailTestNotEnoughBytes) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LengthFieldBasedFrameDecoder(4, 10, 0, 0, 0)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { ASSERT_EQ(nullptr, buf); called++; })) .finalize(); auto bufFrame = createZeroedBuffer(16); RWPrivateCursor c(bufFrame.get()); c.writeBE((uint32_t)7); // frame size - 1 byte too large (7 > 10 - 4) c.write((uint32_t)0); // nothing c.write((uint32_t)0); // nothing c.write((uint32_t)0); // nothing IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(bufFrame)); pipeline->read(q); EXPECT_EQ(called, 1); } TEST(LineBasedFrameDecoder, Simple) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LineBasedFrameDecoder(10)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 3); })) .finalize(); auto buf = createZeroedBuffer(3); IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(buf)); pipeline->read(q); EXPECT_EQ(called, 0); buf = createZeroedBuffer(1); RWPrivateCursor c(buf.get()); c.write<char>('\n'); q.append(std::move(buf)); pipeline->read(q); EXPECT_EQ(called, 1); buf = createZeroedBuffer(4); RWPrivateCursor c1(buf.get()); c1.write(' '); c1.write(' '); c1.write(' '); c1.write('\r'); q.append(std::move(buf)); pipeline->read(q); EXPECT_EQ(called, 1); buf = createZeroedBuffer(1); RWPrivateCursor c2(buf.get()); c2.write('\n'); q.append(std::move(buf)); pipeline->read(q); EXPECT_EQ(called, 2); } TEST(LineBasedFrameDecoder, SaveDelimiter) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LineBasedFrameDecoder(10, false)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 4); })) .finalize(); auto buf = createZeroedBuffer(3); IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(buf)); pipeline->read(q); EXPECT_EQ(called, 0); buf = createZeroedBuffer(1); RWPrivateCursor c(buf.get()); c.write<char>('\n'); q.append(std::move(buf)); pipeline->read(q); EXPECT_EQ(called, 1); buf = createZeroedBuffer(3); RWPrivateCursor c1(buf.get()); c1.write(' '); c1.write(' '); c1.write('\r'); q.append(std::move(buf)); pipeline->read(q); EXPECT_EQ(called, 1); buf = createZeroedBuffer(1); RWPrivateCursor c2(buf.get()); c2.write('\n'); q.append(std::move(buf)); pipeline->read(q); EXPECT_EQ(called, 2); } TEST(LineBasedFrameDecoder, Fail) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LineBasedFrameDecoder(10)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { ASSERT_EQ(nullptr, buf); called++; })) .finalize(); auto buf = createZeroedBuffer(11); IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(buf)); pipeline->read(q); EXPECT_EQ(called, 1); buf = createZeroedBuffer(1); q.append(std::move(buf)); pipeline->read(q); EXPECT_EQ(called, 1); buf = createZeroedBuffer(2); RWPrivateCursor c(buf.get()); c.write(' '); c.write<char>('\n'); q.append(std::move(buf)); pipeline->read(q); EXPECT_EQ(called, 1); buf = createZeroedBuffer(12); RWPrivateCursor c2(buf.get()); for (int i = 0; i < 11; i++) { c2.write(' '); } c2.write<char>('\n'); q.append(std::move(buf)); pipeline->read(q); EXPECT_EQ(called, 2); } TEST(LineBasedFrameDecoder, NewLineOnly) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LineBasedFrameDecoder( 10, true, LineBasedFrameDecoder::TerminatorType::NEWLINE)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 1); })) .finalize(); auto buf = createZeroedBuffer(2); RWPrivateCursor c(buf.get()); c.write<char>('\r'); c.write<char>('\n'); IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(buf)); pipeline->read(q); EXPECT_EQ(called, 1); } TEST(LineBasedFrameDecoder, CarriageNewLineOnly) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LineBasedFrameDecoder( 10, true, LineBasedFrameDecoder::TerminatorType::CARRIAGENEWLINE)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 1); })) .finalize(); auto buf = createZeroedBuffer(3); RWPrivateCursor c(buf.get()); c.write<char>('\n'); c.write<char>('\r'); c.write<char>('\n'); IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(std::move(buf)); pipeline->read(q); EXPECT_EQ(called, 1); } TEST(LineBasedFrameDecoder, CarriageOnly) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); (*pipeline) .addBack(LineBasedFrameDecoder( 10, true, LineBasedFrameDecoder::TerminatorType::CARRIAGENEWLINE)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf>) { FAIL(); })) .finalize(); IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(IOBuf::copyBuffer("\raa")); pipeline->read(q); } TEST(LineBasedFrameDecoder, DoubleCarriage) { auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create(); int called = 0; (*pipeline) .addBack(LineBasedFrameDecoder( 10, true, LineBasedFrameDecoder::TerminatorType::CARRIAGENEWLINE)) .addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) { auto sz = buf->computeChainDataLength(); called++; EXPECT_EQ(sz, 1); })) .finalize(); IOBufQueue q(IOBufQueue::cacheChainLength()); q.append(IOBuf::copyBuffer("\r\r\na\r\n")); pipeline->read(q); EXPECT_EQ(called, 2); }
null
159
CWE-787
CVE-2019-3570
/*- * Copyright 2005,2007,2009 Colin Percival * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/lib/libmd/sha256.h,v 1.2 2006/01/17 15:35:56 phk Exp $ */ #ifndef _SHA256_H_ #define _SHA256_H_ #include <sys/types.h> #include <stdint.h> struct SHA256_CTX { uint32_t state[8]; uint32_t count[2]; unsigned char buf[64]; }; struct HMAC_SHA256_CTX { SHA256_CTX ictx; SHA256_CTX octx; }; void SHA256_Init(struct SHA256_CTX *); void scrypt_SHA256_Update(struct SHA256_CTX *, const void *, size_t); void scrypt_SHA256_Final(unsigned char [32], struct SHA256_CTX *); void HMAC_SHA256_Init(struct HMAC_SHA256_CTX *, const void *, size_t); void HMAC_SHA256_Update(struct HMAC_SHA256_CTX *, const void *, size_t); void HMAC_SHA256_Final(unsigned char [32], struct HMAC_SHA256_CTX *); /** * PBKDF2_SHA256(passwd, passwdlen, salt, saltlen, c, buf, dkLen): * Compute PBKDF2(passwd, salt, c, dkLen) using HMAC-SHA256 as the PRF, and * write the output to buf. The value dkLen must be at most 32 * (2^32 - 1). */ void PBKDF2_SHA256(const uint8_t *, size_t, const uint8_t *, size_t, uint64_t, uint8_t *, size_t); #endif /* !_SHA256_H_ */
null
null
null
160
CWE-787
CVE-2019-9162
/* * nf_nat_snmp_basic.c * * Basic SNMP Application Layer Gateway * * This IP NAT module is intended for use with SNMP network * discovery and monitoring applications where target networks use * conflicting private address realms. * * Static NAT is used to remap the networks from the view of the network * management system at the IP layer, and this module remaps some application * layer addresses to match. * * The simplest form of ALG is performed, where only tagged IP addresses * are modified. The module does not need to be MIB aware and only scans * messages at the ASN.1/BER level. * * Currently, only SNMPv1 and SNMPv2 are supported. * * More information on ALG and associated issues can be found in * RFC 2962 * * The ASB.1/BER parsing code is derived from the gxsnmp package by Gregory * McLean & Jochen Friedrich, stripped down for use in the kernel. * * Copyright (c) 2000 RP Internet (www.rpi.net.au). * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. * * Author: James Morris <jmorris@intercode.com.au> * * Copyright (c) 2006-2010 Patrick McHardy <kaber@trash.net> */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/in.h> #include <linux/ip.h> #include <linux/udp.h> #include <net/checksum.h> #include <net/udp.h> #include <net/netfilter/nf_nat.h> #include <net/netfilter/nf_conntrack_expect.h> #include <net/netfilter/nf_conntrack_helper.h> #include <linux/netfilter/nf_conntrack_snmp.h> #include "nf_nat_snmp_basic.asn1.h" MODULE_LICENSE("GPL"); MODULE_AUTHOR("James Morris <jmorris@intercode.com.au>"); MODULE_DESCRIPTION("Basic SNMP Application Layer Gateway"); MODULE_ALIAS("ip_nat_snmp_basic"); MODULE_ALIAS_NFCT_HELPER("snmp_trap"); #define SNMP_PORT 161 #define SNMP_TRAP_PORT 162 static DEFINE_SPINLOCK(snmp_lock); struct snmp_ctx { unsigned char *begin; __sum16 *check; __be32 from; __be32 to; }; static void fast_csum(struct snmp_ctx *ctx, unsigned char offset) { unsigned char s[12] = {0,}; int size; if (offset & 1) { memcpy(&s[1], &ctx->from, 4); memcpy(&s[7], &ctx->to, 4); s[0] = ~0; s[1] = ~s[1]; s[2] = ~s[2]; s[3] = ~s[3]; s[4] = ~s[4]; s[5] = ~0; size = 12; } else { memcpy(&s[0], &ctx->from, 4); memcpy(&s[4], &ctx->to, 4); s[0] = ~s[0]; s[1] = ~s[1]; s[2] = ~s[2]; s[3] = ~s[3]; size = 8; } *ctx->check = csum_fold(csum_partial(s, size, ~csum_unfold(*ctx->check))); } int snmp_version(void *context, size_t hdrlen, unsigned char tag, const void *data, size_t datalen) { if (*(unsigned char *)data > 1) return -ENOTSUPP; return 1; } int snmp_helper(void *context, size_t hdrlen, unsigned char tag, const void *data, size_t datalen) { struct snmp_ctx *ctx = (struct snmp_ctx *)context; __be32 *pdata = (__be32 *)data; if (*pdata == ctx->from) { pr_debug("%s: %pI4 to %pI4\n", __func__, (void *)&ctx->from, (void *)&ctx->to); if (*ctx->check) fast_csum(ctx, (unsigned char *)data - ctx->begin); *pdata = ctx->to; } return 1; } static int snmp_translate(struct nf_conn *ct, int dir, struct sk_buff *skb) { struct iphdr *iph = ip_hdr(skb); struct udphdr *udph = (struct udphdr *)((__be32 *)iph + iph->ihl); u16 datalen = ntohs(udph->len) - sizeof(struct udphdr); char *data = (unsigned char *)udph + sizeof(struct udphdr); struct snmp_ctx ctx; int ret; if (dir == IP_CT_DIR_ORIGINAL) { ctx.from = ct->tuplehash[dir].tuple.src.u3.ip; ctx.to = ct->tuplehash[!dir].tuple.dst.u3.ip; } else { ctx.from = ct->tuplehash[!dir].tuple.src.u3.ip; ctx.to = ct->tuplehash[dir].tuple.dst.u3.ip; } if (ctx.from == ctx.to) return NF_ACCEPT; ctx.begin = (unsigned char *)udph + sizeof(struct udphdr); ctx.check = &udph->check; ret = asn1_ber_decoder(&nf_nat_snmp_basic_decoder, &ctx, data, datalen); if (ret < 0) { nf_ct_helper_log(skb, ct, "parser failed\n"); return NF_DROP; } return NF_ACCEPT; } /* We don't actually set up expectations, just adjust internal IP * addresses if this is being NATted */ static int help(struct sk_buff *skb, unsigned int protoff, struct nf_conn *ct, enum ip_conntrack_info ctinfo) { int dir = CTINFO2DIR(ctinfo); unsigned int ret; const struct iphdr *iph = ip_hdr(skb); const struct udphdr *udph = (struct udphdr *)((__be32 *)iph + iph->ihl); /* SNMP replies and originating SNMP traps get mangled */ if (udph->source == htons(SNMP_PORT) && dir != IP_CT_DIR_REPLY) return NF_ACCEPT; if (udph->dest == htons(SNMP_TRAP_PORT) && dir != IP_CT_DIR_ORIGINAL) return NF_ACCEPT; /* No NAT? */ if (!(ct->status & IPS_NAT_MASK)) return NF_ACCEPT; /* Make sure the packet length is ok. So far, we were only guaranteed * to have a valid length IP header plus 8 bytes, which means we have * enough room for a UDP header. Just verify the UDP length field so we * can mess around with the payload. */ if (ntohs(udph->len) != skb->len - (iph->ihl << 2)) { nf_ct_helper_log(skb, ct, "dropping malformed packet\n"); return NF_DROP; } if (!skb_make_writable(skb, skb->len)) { nf_ct_helper_log(skb, ct, "cannot mangle packet"); return NF_DROP; } spin_lock_bh(&snmp_lock); ret = snmp_translate(ct, dir, skb); spin_unlock_bh(&snmp_lock); return ret; } static const struct nf_conntrack_expect_policy snmp_exp_policy = { .max_expected = 0, .timeout = 180, }; static struct nf_conntrack_helper snmp_trap_helper __read_mostly = { .me = THIS_MODULE, .help = help, .expect_policy = &snmp_exp_policy, .name = "snmp_trap", .tuple.src.l3num = AF_INET, .tuple.src.u.udp.port = cpu_to_be16(SNMP_TRAP_PORT), .tuple.dst.protonum = IPPROTO_UDP, }; static int __init nf_nat_snmp_basic_init(void) { BUG_ON(nf_nat_snmp_hook != NULL); RCU_INIT_POINTER(nf_nat_snmp_hook, help); return nf_conntrack_helper_register(&snmp_trap_helper); } static void __exit nf_nat_snmp_basic_fini(void) { RCU_INIT_POINTER(nf_nat_snmp_hook, NULL); synchronize_rcu(); nf_conntrack_helper_unregister(&snmp_trap_helper); } module_init(nf_nat_snmp_basic_init); module_exit(nf_nat_snmp_basic_fini);
null
/* * nf_nat_snmp_basic.c * * Basic SNMP Application Layer Gateway * * This IP NAT module is intended for use with SNMP network * discovery and monitoring applications where target networks use * conflicting private address realms. * * Static NAT is used to remap the networks from the view of the network * management system at the IP layer, and this module remaps some application * layer addresses to match. * * The simplest form of ALG is performed, where only tagged IP addresses * are modified. The module does not need to be MIB aware and only scans * messages at the ASN.1/BER level. * * Currently, only SNMPv1 and SNMPv2 are supported. * * More information on ALG and associated issues can be found in * RFC 2962 * * The ASB.1/BER parsing code is derived from the gxsnmp package by Gregory * McLean & Jochen Friedrich, stripped down for use in the kernel. * * Copyright (c) 2000 RP Internet (www.rpi.net.au). * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. * * Author: James Morris <jmorris@intercode.com.au> * * Copyright (c) 2006-2010 Patrick McHardy <kaber@trash.net> */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/in.h> #include <linux/ip.h> #include <linux/udp.h> #include <net/checksum.h> #include <net/udp.h> #include <net/netfilter/nf_nat.h> #include <net/netfilter/nf_conntrack_expect.h> #include <net/netfilter/nf_conntrack_helper.h> #include <linux/netfilter/nf_conntrack_snmp.h> #include "nf_nat_snmp_basic.asn1.h" MODULE_LICENSE("GPL"); MODULE_AUTHOR("James Morris <jmorris@intercode.com.au>"); MODULE_DESCRIPTION("Basic SNMP Application Layer Gateway"); MODULE_ALIAS("ip_nat_snmp_basic"); MODULE_ALIAS_NFCT_HELPER("snmp_trap"); #define SNMP_PORT 161 #define SNMP_TRAP_PORT 162 static DEFINE_SPINLOCK(snmp_lock); struct snmp_ctx { unsigned char *begin; __sum16 *check; __be32 from; __be32 to; }; static void fast_csum(struct snmp_ctx *ctx, unsigned char offset) { unsigned char s[12] = {0,}; int size; if (offset & 1) { memcpy(&s[1], &ctx->from, 4); memcpy(&s[7], &ctx->to, 4); s[0] = ~0; s[1] = ~s[1]; s[2] = ~s[2]; s[3] = ~s[3]; s[4] = ~s[4]; s[5] = ~0; size = 12; } else { memcpy(&s[0], &ctx->from, 4); memcpy(&s[4], &ctx->to, 4); s[0] = ~s[0]; s[1] = ~s[1]; s[2] = ~s[2]; s[3] = ~s[3]; size = 8; } *ctx->check = csum_fold(csum_partial(s, size, ~csum_unfold(*ctx->check))); } int snmp_version(void *context, size_t hdrlen, unsigned char tag, const void *data, size_t datalen) { if (datalen != 1) return -EINVAL; if (*(unsigned char *)data > 1) return -ENOTSUPP; return 1; } int snmp_helper(void *context, size_t hdrlen, unsigned char tag, const void *data, size_t datalen) { struct snmp_ctx *ctx = (struct snmp_ctx *)context; __be32 *pdata; if (datalen != 4) return -EINVAL; pdata = (__be32 *)data; if (*pdata == ctx->from) { pr_debug("%s: %pI4 to %pI4\n", __func__, (void *)&ctx->from, (void *)&ctx->to); if (*ctx->check) fast_csum(ctx, (unsigned char *)data - ctx->begin); *pdata = ctx->to; } return 1; } static int snmp_translate(struct nf_conn *ct, int dir, struct sk_buff *skb) { struct iphdr *iph = ip_hdr(skb); struct udphdr *udph = (struct udphdr *)((__be32 *)iph + iph->ihl); u16 datalen = ntohs(udph->len) - sizeof(struct udphdr); char *data = (unsigned char *)udph + sizeof(struct udphdr); struct snmp_ctx ctx; int ret; if (dir == IP_CT_DIR_ORIGINAL) { ctx.from = ct->tuplehash[dir].tuple.src.u3.ip; ctx.to = ct->tuplehash[!dir].tuple.dst.u3.ip; } else { ctx.from = ct->tuplehash[!dir].tuple.src.u3.ip; ctx.to = ct->tuplehash[dir].tuple.dst.u3.ip; } if (ctx.from == ctx.to) return NF_ACCEPT; ctx.begin = (unsigned char *)udph + sizeof(struct udphdr); ctx.check = &udph->check; ret = asn1_ber_decoder(&nf_nat_snmp_basic_decoder, &ctx, data, datalen); if (ret < 0) { nf_ct_helper_log(skb, ct, "parser failed\n"); return NF_DROP; } return NF_ACCEPT; } /* We don't actually set up expectations, just adjust internal IP * addresses if this is being NATted */ static int help(struct sk_buff *skb, unsigned int protoff, struct nf_conn *ct, enum ip_conntrack_info ctinfo) { int dir = CTINFO2DIR(ctinfo); unsigned int ret; const struct iphdr *iph = ip_hdr(skb); const struct udphdr *udph = (struct udphdr *)((__be32 *)iph + iph->ihl); /* SNMP replies and originating SNMP traps get mangled */ if (udph->source == htons(SNMP_PORT) && dir != IP_CT_DIR_REPLY) return NF_ACCEPT; if (udph->dest == htons(SNMP_TRAP_PORT) && dir != IP_CT_DIR_ORIGINAL) return NF_ACCEPT; /* No NAT? */ if (!(ct->status & IPS_NAT_MASK)) return NF_ACCEPT; /* Make sure the packet length is ok. So far, we were only guaranteed * to have a valid length IP header plus 8 bytes, which means we have * enough room for a UDP header. Just verify the UDP length field so we * can mess around with the payload. */ if (ntohs(udph->len) != skb->len - (iph->ihl << 2)) { nf_ct_helper_log(skb, ct, "dropping malformed packet\n"); return NF_DROP; } if (!skb_make_writable(skb, skb->len)) { nf_ct_helper_log(skb, ct, "cannot mangle packet"); return NF_DROP; } spin_lock_bh(&snmp_lock); ret = snmp_translate(ct, dir, skb); spin_unlock_bh(&snmp_lock); return ret; } static const struct nf_conntrack_expect_policy snmp_exp_policy = { .max_expected = 0, .timeout = 180, }; static struct nf_conntrack_helper snmp_trap_helper __read_mostly = { .me = THIS_MODULE, .help = help, .expect_policy = &snmp_exp_policy, .name = "snmp_trap", .tuple.src.l3num = AF_INET, .tuple.src.u.udp.port = cpu_to_be16(SNMP_TRAP_PORT), .tuple.dst.protonum = IPPROTO_UDP, }; static int __init nf_nat_snmp_basic_init(void) { BUG_ON(nf_nat_snmp_hook != NULL); RCU_INIT_POINTER(nf_nat_snmp_hook, help); return nf_conntrack_helper_register(&snmp_trap_helper); } static void __exit nf_nat_snmp_basic_fini(void) { RCU_INIT_POINTER(nf_nat_snmp_hook, NULL); synchronize_rcu(); nf_conntrack_helper_unregister(&snmp_trap_helper); } module_init(nf_nat_snmp_basic_init); module_exit(nf_nat_snmp_basic_fini);
null
161
CWE-787
CVE-2019-9278
/* exif-data.c * * Copyright (c) 2001 Lutz Mueller <lutz@users.sourceforge.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. */ #include <config.h> #include <libexif/exif-mnote-data.h> #include <libexif/exif-data.h> #include <libexif/exif-ifd.h> #include <libexif/exif-mnote-data-priv.h> #include <libexif/exif-utils.h> #include <libexif/exif-loader.h> #include <libexif/exif-log.h> #include <libexif/i18n.h> #include <libexif/exif-system.h> #include <libexif/canon/exif-mnote-data-canon.h> #include <libexif/fuji/exif-mnote-data-fuji.h> #include <libexif/olympus/exif-mnote-data-olympus.h> #include <libexif/pentax/exif-mnote-data-pentax.h> #include <math.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #undef JPEG_MARKER_SOI #define JPEG_MARKER_SOI 0xd8 #undef JPEG_MARKER_APP0 #define JPEG_MARKER_APP0 0xe0 #undef JPEG_MARKER_APP1 #define JPEG_MARKER_APP1 0xe1 static const unsigned char ExifHeader[] = {0x45, 0x78, 0x69, 0x66, 0x00, 0x00}; struct _ExifDataPrivate { ExifByteOrder order; ExifMnoteData *md; ExifLog *log; ExifMem *mem; unsigned int ref_count; /* Temporarily used while loading data */ unsigned int offset_mnote; ExifDataOption options; ExifDataType data_type; }; static void * exif_data_alloc (ExifData *data, unsigned int i) { void *d; if (!data || !i) return NULL; d = exif_mem_alloc (data->priv->mem, i); if (d) return d; EXIF_LOG_NO_MEMORY (data->priv->log, "ExifData", i); return NULL; } ExifMnoteData * exif_data_get_mnote_data (ExifData *d) { return (d && d->priv) ? d->priv->md : NULL; } ExifData * exif_data_new (void) { ExifMem *mem = exif_mem_new_default (); ExifData *d = exif_data_new_mem (mem); exif_mem_unref (mem); return d; } ExifData * exif_data_new_mem (ExifMem *mem) { ExifData *data; unsigned int i; if (!mem) return NULL; data = exif_mem_alloc (mem, sizeof (ExifData)); if (!data) return (NULL); data->priv = exif_mem_alloc (mem, sizeof (ExifDataPrivate)); if (!data->priv) { exif_mem_free (mem, data); return (NULL); } data->priv->ref_count = 1; data->priv->mem = mem; exif_mem_ref (mem); for (i = 0; i < EXIF_IFD_COUNT; i++) { data->ifd[i] = exif_content_new_mem (data->priv->mem); if (!data->ifd[i]) { exif_data_free (data); return (NULL); } data->ifd[i]->parent = data; } /* Default options */ #ifndef NO_VERBOSE_TAG_STRINGS /* * When the tag list is compiled away, setting this option prevents * any tags from being loaded */ exif_data_set_option (data, EXIF_DATA_OPTION_IGNORE_UNKNOWN_TAGS); #endif exif_data_set_option (data, EXIF_DATA_OPTION_FOLLOW_SPECIFICATION); /* Default data type: none */ exif_data_set_data_type (data, EXIF_DATA_TYPE_COUNT); return (data); } ExifData * exif_data_new_from_data (const unsigned char *data, unsigned int size) { ExifData *edata; edata = exif_data_new (); exif_data_load_data (edata, data, size); return (edata); } static int exif_data_load_data_entry (ExifData *data, ExifEntry *entry, const unsigned char *d, unsigned int size, unsigned int offset) { unsigned int s, doff; entry->tag = exif_get_short (d + offset + 0, data->priv->order); entry->format = exif_get_short (d + offset + 2, data->priv->order); entry->components = exif_get_long (d + offset + 4, data->priv->order); /* FIXME: should use exif_tag_get_name_in_ifd here but entry->parent * has not been set yet */ exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Loading entry 0x%x ('%s')...", entry->tag, exif_tag_get_name (entry->tag)); /* {0,1,2,4,8} x { 0x00000000 .. 0xffffffff } * -> { 0x000000000 .. 0x7fffffff8 } */ s = exif_format_get_size(entry->format) * entry->components; if ((s < entry->components) || (s == 0)){ return 0; } /* * Size? If bigger than 4 bytes, the actual data is not * in the entry but somewhere else (offset). */ if (s > 4) doff = exif_get_long (d + offset + 8, data->priv->order); else doff = offset + 8; /* Sanity checks */ if ((doff + s < doff) || (doff + s < s) || (doff + s > size)) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Tag data past end of buffer (%u > %u)", doff+s, size); return 0; } entry->data = exif_data_alloc (data, s); if (entry->data) { entry->size = s; memcpy (entry->data, d + doff, s); } else { EXIF_LOG_NO_MEMORY(data->priv->log, "ExifData", s); return 0; } /* If this is the MakerNote, remember the offset */ if (entry->tag == EXIF_TAG_MAKER_NOTE) { if (!entry->data) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "MakerNote found with empty data"); } else if (entry->size > 6) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "MakerNote found (%02x %02x %02x %02x " "%02x %02x %02x...).", entry->data[0], entry->data[1], entry->data[2], entry->data[3], entry->data[4], entry->data[5], entry->data[6]); } data->priv->offset_mnote = doff; } return 1; } static void exif_data_save_data_entry (ExifData *data, ExifEntry *e, unsigned char **d, unsigned int *ds, unsigned int offset) { unsigned int doff, s; unsigned int ts; if (!data || !data->priv) return; /* * Each entry is 12 bytes long. The memory for the entry has * already been allocated. */ exif_set_short (*d + 6 + offset + 0, data->priv->order, (ExifShort) e->tag); exif_set_short (*d + 6 + offset + 2, data->priv->order, (ExifShort) e->format); if (!(data->priv->options & EXIF_DATA_OPTION_DONT_CHANGE_MAKER_NOTE)) { /* If this is the maker note tag, update it. */ if ((e->tag == EXIF_TAG_MAKER_NOTE) && data->priv->md) { /* TODO: this is using the wrong ExifMem to free e->data */ exif_mem_free (data->priv->mem, e->data); e->data = NULL; e->size = 0; exif_mnote_data_set_offset (data->priv->md, *ds - 6); exif_mnote_data_save (data->priv->md, &e->data, &e->size); e->components = e->size; if (exif_format_get_size (e->format) != 1) { /* e->format is taken from input code, * but we need to make sure it is a 1 byte * entity due to the multiplication below. */ e->format = EXIF_FORMAT_UNDEFINED; } } } exif_set_long (*d + 6 + offset + 4, data->priv->order, e->components); /* * Size? If bigger than 4 bytes, the actual data is not in * the entry but somewhere else. */ s = exif_format_get_size (e->format) * e->components; if (s > 4) { unsigned char *t; doff = *ds - 6; ts = *ds + s; /* * According to the TIFF specification, * the offset must be an even number. If we need to introduce * a padding byte, we set it to 0. */ if (s & 1) ts++; t = exif_mem_realloc (data->priv->mem, *d, ts); if (!t) { EXIF_LOG_NO_MEMORY (data->priv->log, "ExifData", ts); return; } *d = t; *ds = ts; exif_set_long (*d + 6 + offset + 8, data->priv->order, doff); if (s & 1) *(*d + *ds - 1) = '\0'; } else doff = offset + 8; /* Write the data. Fill unneeded bytes with 0. Do not crash with * e->data is NULL */ if (e->data) { memcpy (*d + 6 + doff, e->data, s); } else { memset (*d + 6 + doff, 0, s); } if (s < 4) memset (*d + 6 + doff + s, 0, (4 - s)); } static void exif_data_load_data_thumbnail (ExifData *data, const unsigned char *d, unsigned int ds, ExifLong o, ExifLong s) { /* Sanity checks */ if ((o + s < o) || (o + s < s) || (o + s > ds) || (o > ds)) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Bogus thumbnail offset (%u) or size (%u).", o, s); return; } if (data->data) exif_mem_free (data->priv->mem, data->data); if (!(data->data = exif_data_alloc (data, s))) { EXIF_LOG_NO_MEMORY (data->priv->log, "ExifData", s); data->size = 0; return; } data->size = s; memcpy (data->data, d + o, s); } #undef CHECK_REC #define CHECK_REC(i) \ if ((i) == ifd) { \ exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \ "ExifData", "Recursive entry in IFD " \ "'%s' detected. Skipping...", \ exif_ifd_get_name (i)); \ break; \ } \ if (data->ifd[(i)]->count) { \ exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \ "ExifData", "Attempt to load IFD " \ "'%s' multiple times detected. " \ "Skipping...", \ exif_ifd_get_name (i)); \ break; \ } /*! Calculate the recursion cost added by one level of IFD loading. * * The work performed is related to the cost in the exponential relation * work=1.1**cost */ static unsigned int level_cost(unsigned int n) { static const double log_1_1 = 0.09531017980432493; /* Adding 0.1 protects against the case where n==1 */ return ceil(log(n + 0.1)/log_1_1); } /*! Load data for an IFD. * * \param[in,out] data #ExifData * \param[in] ifd IFD to load * \param[in] d pointer to buffer containing raw IFD data * \param[in] ds size of raw data in buffer at \c d * \param[in] offset offset into buffer at \c d at which IFD starts * \param[in] recursion_cost factor indicating how expensive this recursive * call could be */ static void exif_data_load_data_content (ExifData *data, ExifIfd ifd, const unsigned char *d, unsigned int ds, unsigned int offset, unsigned int recursion_cost) { ExifLong o, thumbnail_offset = 0, thumbnail_length = 0; ExifShort n; ExifEntry *entry; unsigned int i; ExifTag tag; if (!data || !data->priv) return; /* check for valid ExifIfd enum range */ if ((((int)ifd) < 0) || ( ((int)ifd) >= EXIF_IFD_COUNT)) return; if (recursion_cost > 170) { /* * recursion_cost is a logarithmic-scale indicator of how expensive this * recursive call might end up being. It is an indicator of the depth of * recursion as well as the potential for worst-case future recursive * calls. Since it's difficult to tell ahead of time how often recursion * will occur, this assumes the worst by assuming every tag could end up * causing recursion. * The value of 170 was chosen to limit typical EXIF structures to a * recursive depth of about 6, but pathological ones (those with very * many tags) to only 2. */ exif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifData", "Deep/expensive recursion detected!"); return; } /* Read the number of entries */ if ((offset + 2 < offset) || (offset + 2 < 2) || (offset + 2 > ds)) { exif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifData", "Tag data past end of buffer (%u > %u)", offset+2, ds); return; } n = exif_get_short (d + offset, data->priv->order); exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Loading %hu entries...", n); offset += 2; /* Check if we have enough data. */ if (offset + 12 * n > ds) { n = (ds - offset) / 12; exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Short data; only loading %hu entries...", n); } for (i = 0; i < n; i++) { tag = exif_get_short (d + offset + 12 * i, data->priv->order); switch (tag) { case EXIF_TAG_EXIF_IFD_POINTER: case EXIF_TAG_GPS_INFO_IFD_POINTER: case EXIF_TAG_INTEROPERABILITY_IFD_POINTER: case EXIF_TAG_JPEG_INTERCHANGE_FORMAT_LENGTH: case EXIF_TAG_JPEG_INTERCHANGE_FORMAT: o = exif_get_long (d + offset + 12 * i + 8, data->priv->order); /* FIXME: IFD_POINTER tags aren't marked as being in a * specific IFD, so exif_tag_get_name_in_ifd won't work */ exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Sub-IFD entry 0x%x ('%s') at %u.", tag, exif_tag_get_name(tag), o); switch (tag) { case EXIF_TAG_EXIF_IFD_POINTER: CHECK_REC (EXIF_IFD_EXIF); exif_data_load_data_content (data, EXIF_IFD_EXIF, d, ds, o, recursion_cost + level_cost(n)); break; case EXIF_TAG_GPS_INFO_IFD_POINTER: CHECK_REC (EXIF_IFD_GPS); exif_data_load_data_content (data, EXIF_IFD_GPS, d, ds, o, recursion_cost + level_cost(n)); break; case EXIF_TAG_INTEROPERABILITY_IFD_POINTER: CHECK_REC (EXIF_IFD_INTEROPERABILITY); exif_data_load_data_content (data, EXIF_IFD_INTEROPERABILITY, d, ds, o, recursion_cost + level_cost(n)); break; case EXIF_TAG_JPEG_INTERCHANGE_FORMAT: thumbnail_offset = o; if (thumbnail_offset && thumbnail_length) exif_data_load_data_thumbnail (data, d, ds, thumbnail_offset, thumbnail_length); break; case EXIF_TAG_JPEG_INTERCHANGE_FORMAT_LENGTH: thumbnail_length = o; if (thumbnail_offset && thumbnail_length) exif_data_load_data_thumbnail (data, d, ds, thumbnail_offset, thumbnail_length); break; default: return; } break; default: /* * If we don't know the tag, don't fail. It could be that new * versions of the standard have defined additional tags. Note that * 0 is a valid tag in the GPS IFD. */ if (!exif_tag_get_name_in_ifd (tag, ifd)) { /* * Special case: Tag and format 0. That's against specification * (at least up to 2.2). But Photoshop writes it anyways. */ if (!memcmp (d + offset + 12 * i, "\0\0\0\0", 4)) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Skipping empty entry at position %u in '%s'.", i, exif_ifd_get_name (ifd)); break; } exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Unknown tag 0x%04x (entry %u in '%s'). Please report this tag " "to <libexif-devel@lists.sourceforge.net>.", tag, i, exif_ifd_get_name (ifd)); if (data->priv->options & EXIF_DATA_OPTION_IGNORE_UNKNOWN_TAGS) break; } entry = exif_entry_new_mem (data->priv->mem); if (!entry) { exif_log (data->priv->log, EXIF_LOG_CODE_NO_MEMORY, "ExifData", "Could not allocate memory"); return; } if (exif_data_load_data_entry (data, entry, d, ds, offset + 12 * i)) exif_content_add_entry (data->ifd[ifd], entry); exif_entry_unref (entry); break; } } } static int cmp_func (const unsigned char *p1, const unsigned char *p2, ExifByteOrder o) { ExifShort tag1 = exif_get_short (p1, o); ExifShort tag2 = exif_get_short (p2, o); return (tag1 < tag2) ? -1 : (tag1 > tag2) ? 1 : 0; } static int cmp_func_intel (const void *elem1, const void *elem2) { return cmp_func ((const unsigned char *) elem1, (const unsigned char *) elem2, EXIF_BYTE_ORDER_INTEL); } static int cmp_func_motorola (const void *elem1, const void *elem2) { return cmp_func ((const unsigned char *) elem1, (const unsigned char *) elem2, EXIF_BYTE_ORDER_MOTOROLA); } static void exif_data_save_data_content (ExifData *data, ExifContent *ifd, unsigned char **d, unsigned int *ds, unsigned int offset) { unsigned int j, n_ptr = 0, n_thumb = 0; ExifIfd i; unsigned char *t; unsigned int ts; if (!data || !data->priv || !ifd || !d || !ds) return; for (i = 0; i < EXIF_IFD_COUNT; i++) if (ifd == data->ifd[i]) break; if (i == EXIF_IFD_COUNT) return; /* error */ /* * Check if we need some extra entries for pointers or the thumbnail. */ switch (i) { case EXIF_IFD_0: /* * The pointer to IFD_EXIF is in IFD_0. The pointer to * IFD_INTEROPERABILITY is in IFD_EXIF. */ if (data->ifd[EXIF_IFD_EXIF]->count || data->ifd[EXIF_IFD_INTEROPERABILITY]->count) n_ptr++; /* The pointer to IFD_GPS is in IFD_0. */ if (data->ifd[EXIF_IFD_GPS]->count) n_ptr++; break; case EXIF_IFD_1: if (data->size) n_thumb = 2; break; case EXIF_IFD_EXIF: if (data->ifd[EXIF_IFD_INTEROPERABILITY]->count) n_ptr++; default: break; } /* * Allocate enough memory for all entries * and the number of entries. */ ts = *ds + (2 + (ifd->count + n_ptr + n_thumb) * 12 + 4); t = exif_mem_realloc (data->priv->mem, *d, ts); if (!t) { EXIF_LOG_NO_MEMORY (data->priv->log, "ExifData", ts); return; } *d = t; *ds = ts; /* Save the number of entries */ exif_set_short (*d + 6 + offset, data->priv->order, (ExifShort) (ifd->count + n_ptr + n_thumb)); offset += 2; /* * Save each entry. Make sure that no memcpys from NULL pointers are * performed */ exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Saving %i entries (IFD '%s', offset: %i)...", ifd->count, exif_ifd_get_name (i), offset); for (j = 0; j < ifd->count; j++) { if (ifd->entries[j]) { exif_data_save_data_entry (data, ifd->entries[j], d, ds, offset + 12 * j); } } offset += 12 * ifd->count; /* Now save special entries. */ switch (i) { case EXIF_IFD_0: /* * The pointer to IFD_EXIF is in IFD_0. * However, the pointer to IFD_INTEROPERABILITY is in IFD_EXIF, * therefore, if IFD_INTEROPERABILITY is not empty, we need * IFD_EXIF even if latter is empty. */ if (data->ifd[EXIF_IFD_EXIF]->count || data->ifd[EXIF_IFD_INTEROPERABILITY]->count) { exif_set_short (*d + 6 + offset + 0, data->priv->order, EXIF_TAG_EXIF_IFD_POINTER); exif_set_short (*d + 6 + offset + 2, data->priv->order, EXIF_FORMAT_LONG); exif_set_long (*d + 6 + offset + 4, data->priv->order, 1); exif_set_long (*d + 6 + offset + 8, data->priv->order, *ds - 6); exif_data_save_data_content (data, data->ifd[EXIF_IFD_EXIF], d, ds, *ds - 6); offset += 12; } /* The pointer to IFD_GPS is in IFD_0, too. */ if (data->ifd[EXIF_IFD_GPS]->count) { exif_set_short (*d + 6 + offset + 0, data->priv->order, EXIF_TAG_GPS_INFO_IFD_POINTER); exif_set_short (*d + 6 + offset + 2, data->priv->order, EXIF_FORMAT_LONG); exif_set_long (*d + 6 + offset + 4, data->priv->order, 1); exif_set_long (*d + 6 + offset + 8, data->priv->order, *ds - 6); exif_data_save_data_content (data, data->ifd[EXIF_IFD_GPS], d, ds, *ds - 6); offset += 12; } break; case EXIF_IFD_EXIF: /* * The pointer to IFD_INTEROPERABILITY is in IFD_EXIF. * See note above. */ if (data->ifd[EXIF_IFD_INTEROPERABILITY]->count) { exif_set_short (*d + 6 + offset + 0, data->priv->order, EXIF_TAG_INTEROPERABILITY_IFD_POINTER); exif_set_short (*d + 6 + offset + 2, data->priv->order, EXIF_FORMAT_LONG); exif_set_long (*d + 6 + offset + 4, data->priv->order, 1); exif_set_long (*d + 6 + offset + 8, data->priv->order, *ds - 6); exif_data_save_data_content (data, data->ifd[EXIF_IFD_INTEROPERABILITY], d, ds, *ds - 6); offset += 12; } break; case EXIF_IFD_1: /* * Information about the thumbnail (if any) is saved in * IFD_1. */ if (data->size) { /* EXIF_TAG_JPEG_INTERCHANGE_FORMAT */ exif_set_short (*d + 6 + offset + 0, data->priv->order, EXIF_TAG_JPEG_INTERCHANGE_FORMAT); exif_set_short (*d + 6 + offset + 2, data->priv->order, EXIF_FORMAT_LONG); exif_set_long (*d + 6 + offset + 4, data->priv->order, 1); exif_set_long (*d + 6 + offset + 8, data->priv->order, *ds - 6); ts = *ds + data->size; t = exif_mem_realloc (data->priv->mem, *d, ts); if (!t) { EXIF_LOG_NO_MEMORY (data->priv->log, "ExifData", ts); return; } *d = t; *ds = ts; memcpy (*d + *ds - data->size, data->data, data->size); offset += 12; /* EXIF_TAG_JPEG_INTERCHANGE_FORMAT_LENGTH */ exif_set_short (*d + 6 + offset + 0, data->priv->order, EXIF_TAG_JPEG_INTERCHANGE_FORMAT_LENGTH); exif_set_short (*d + 6 + offset + 2, data->priv->order, EXIF_FORMAT_LONG); exif_set_long (*d + 6 + offset + 4, data->priv->order, 1); exif_set_long (*d + 6 + offset + 8, data->priv->order, data->size); offset += 12; } break; default: break; } /* Sort the directory according to TIFF specification */ qsort (*d + 6 + offset - (ifd->count + n_ptr + n_thumb) * 12, (ifd->count + n_ptr + n_thumb), 12, (data->priv->order == EXIF_BYTE_ORDER_INTEL) ? cmp_func_intel : cmp_func_motorola); /* Correctly terminate the directory */ if (i == EXIF_IFD_0 && (data->ifd[EXIF_IFD_1]->count || data->size)) { /* * We are saving IFD 0. Tell where IFD 1 starts and save * IFD 1. */ exif_set_long (*d + 6 + offset, data->priv->order, *ds - 6); exif_data_save_data_content (data, data->ifd[EXIF_IFD_1], d, ds, *ds - 6); } else exif_set_long (*d + 6 + offset, data->priv->order, 0); } typedef enum { EXIF_DATA_TYPE_MAKER_NOTE_NONE = 0, EXIF_DATA_TYPE_MAKER_NOTE_CANON = 1, EXIF_DATA_TYPE_MAKER_NOTE_OLYMPUS = 2, EXIF_DATA_TYPE_MAKER_NOTE_PENTAX = 3, EXIF_DATA_TYPE_MAKER_NOTE_NIKON = 4, EXIF_DATA_TYPE_MAKER_NOTE_CASIO = 5, EXIF_DATA_TYPE_MAKER_NOTE_FUJI = 6 } ExifDataTypeMakerNote; /*! If MakerNote is recognized, load it. * * \param[in,out] data #ExifData * \param[in] d pointer to raw EXIF data * \param[in] ds length of data at d */ static void interpret_maker_note(ExifData *data, const unsigned char *d, unsigned int ds) { int mnoteid; ExifEntry* e = exif_data_get_entry (data, EXIF_TAG_MAKER_NOTE); if (!e) return; if ((mnoteid = exif_mnote_data_olympus_identify (data, e)) != 0) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Olympus MakerNote variant type %d", mnoteid); data->priv->md = exif_mnote_data_olympus_new (data->priv->mem); } else if ((mnoteid = exif_mnote_data_canon_identify (data, e)) != 0) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Canon MakerNote variant type %d", mnoteid); data->priv->md = exif_mnote_data_canon_new (data->priv->mem, data->priv->options); } else if ((mnoteid = exif_mnote_data_fuji_identify (data, e)) != 0) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Fuji MakerNote variant type %d", mnoteid); data->priv->md = exif_mnote_data_fuji_new (data->priv->mem); /* NOTE: Must do Pentax detection last because some of the * heuristics are pretty general. */ } else if ((mnoteid = exif_mnote_data_pentax_identify (data, e)) != 0) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Pentax MakerNote variant type %d", mnoteid); data->priv->md = exif_mnote_data_pentax_new (data->priv->mem); } /* * If we are able to interpret the maker note, do so. */ if (data->priv->md) { exif_mnote_data_log (data->priv->md, data->priv->log); exif_mnote_data_set_byte_order (data->priv->md, data->priv->order); exif_mnote_data_set_offset (data->priv->md, data->priv->offset_mnote); exif_mnote_data_load (data->priv->md, d, ds); } } #define LOG_TOO_SMALL \ exif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifData", \ _("Size of data too small to allow for EXIF data.")); void exif_data_load_data (ExifData *data, const unsigned char *d_orig, unsigned int ds) { unsigned int l; ExifLong offset; ExifShort n; const unsigned char *d = d_orig; unsigned int len, fullds; if (!data || !data->priv || !d || !ds) return; exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Parsing %i byte(s) EXIF data...\n", ds); /* * It can be that the data starts with the EXIF header. If it does * not, search the EXIF marker. */ if (ds < 6) { LOG_TOO_SMALL; return; } if (!memcmp (d, ExifHeader, 6)) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Found EXIF header at start."); } else { while (ds >= 3) { while (ds && (d[0] == 0xff)) { d++; ds--; } /* JPEG_MARKER_SOI */ if (ds && d[0] == JPEG_MARKER_SOI) { d++; ds--; continue; } /* JPEG_MARKER_APP1 */ if (ds && d[0] == JPEG_MARKER_APP1) break; /* Skip irrelevant APP markers. The branch for APP1 must come before this, otherwise this code block will cause APP1 to be skipped. This code path is only relevant for files that are nonconformant to the EXIF specification. For conformant files, the APP1 code path above will be taken. */ if (ds >= 3 && d[0] >= 0xe0 && d[0] <= 0xef) { /* JPEG_MARKER_APPn */ d++; ds--; l = (d[0] << 8) | d[1]; if (l > ds) return; d += l; ds -= l; continue; } /* Unknown marker or data. Give up. */ exif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifData", _("EXIF marker not found.")); return; } if (ds < 3) { LOG_TOO_SMALL; return; } d++; ds--; len = (d[0] << 8) | d[1]; exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "We have to deal with %i byte(s) of EXIF data.", len); d += 2; ds -= 2; } /* * Verify the exif header * (offset 2, length 6). */ if (ds < 6) { LOG_TOO_SMALL; return; } if (memcmp (d, ExifHeader, 6)) { exif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifData", _("EXIF header not found.")); return; } exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Found EXIF header."); /* Sanity check the data length */ if (ds < 14) return; /* The JPEG APP1 section can be no longer than 64 KiB (including a 16-bit length), so cap the data length to protect against overflow in future offset calculations */ fullds = ds; if (ds > 0xfffe) ds = 0xfffe; /* Byte order (offset 6, length 2) */ if (!memcmp (d + 6, "II", 2)) data->priv->order = EXIF_BYTE_ORDER_INTEL; else if (!memcmp (d + 6, "MM", 2)) data->priv->order = EXIF_BYTE_ORDER_MOTOROLA; else { exif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifData", _("Unknown encoding.")); return; } /* Fixed value */ if (exif_get_short (d + 8, data->priv->order) != 0x002a) return; /* IFD 0 offset */ offset = exif_get_long (d + 10, data->priv->order); exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "IFD 0 at %i.", (int) offset); /* Sanity check the offset, being careful about overflow */ if (offset > ds || offset + 6 + 2 > ds) return; /* Parse the actual exif data (usually offset 14 from start) */ exif_data_load_data_content (data, EXIF_IFD_0, d + 6, ds - 6, offset, 0); /* IFD 1 offset */ n = exif_get_short (d + 6 + offset, data->priv->order); if (offset + 6 + 2 + 12 * n + 4 > ds) return; offset = exif_get_long (d + 6 + offset + 2 + 12 * n, data->priv->order); if (offset) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "IFD 1 at %i.", (int) offset); /* Sanity check. */ if (offset > ds || offset + 6 > ds) { exif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifData", "Bogus offset of IFD1."); } else { exif_data_load_data_content (data, EXIF_IFD_1, d + 6, ds - 6, offset, 0); } } /* * If we got an EXIF_TAG_MAKER_NOTE, try to interpret it. Some * cameras use pointers in the maker note tag that point to the * space between IFDs. Here is the only place where we have access * to that data. */ interpret_maker_note(data, d, fullds); /* Fixup tags if requested */ if (data->priv->options & EXIF_DATA_OPTION_FOLLOW_SPECIFICATION) exif_data_fix (data); } void exif_data_save_data (ExifData *data, unsigned char **d, unsigned int *ds) { if (ds) *ds = 0; /* This means something went wrong */ if (!data || !d || !ds) return; /* Header */ *ds = 14; *d = exif_data_alloc (data, *ds); if (!*d) { *ds = 0; return; } memcpy (*d, ExifHeader, 6); /* Order (offset 6) */ if (data->priv->order == EXIF_BYTE_ORDER_INTEL) { memcpy (*d + 6, "II", 2); } else { memcpy (*d + 6, "MM", 2); } /* Fixed value (2 bytes, offset 8) */ exif_set_short (*d + 8, data->priv->order, 0x002a); /* * IFD 0 offset (4 bytes, offset 10). * We will start 8 bytes after the * EXIF header (2 bytes for order, another 2 for the test, and * 4 bytes for the IFD 0 offset make 8 bytes together). */ exif_set_long (*d + 10, data->priv->order, 8); /* Now save IFD 0. IFD 1 will be saved automatically. */ exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Saving IFDs..."); exif_data_save_data_content (data, data->ifd[EXIF_IFD_0], d, ds, *ds - 6); exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Saved %i byte(s) EXIF data.", *ds); } ExifData * exif_data_new_from_file (const char *path) { ExifData *edata; ExifLoader *loader; loader = exif_loader_new (); exif_loader_write_file (loader, path); edata = exif_loader_get_data (loader); exif_loader_unref (loader); return (edata); } void exif_data_ref (ExifData *data) { if (!data) return; data->priv->ref_count++; } void exif_data_unref (ExifData *data) { if (!data) return; data->priv->ref_count--; if (!data->priv->ref_count) exif_data_free (data); } void exif_data_free (ExifData *data) { unsigned int i; ExifMem *mem = (data && data->priv) ? data->priv->mem : NULL; if (!data) return; for (i = 0; i < EXIF_IFD_COUNT; i++) { if (data->ifd[i]) { exif_content_unref (data->ifd[i]); data->ifd[i] = NULL; } } if (data->data) { exif_mem_free (mem, data->data); data->data = NULL; } if (data->priv) { if (data->priv->log) { exif_log_unref (data->priv->log); data->priv->log = NULL; } if (data->priv->md) { exif_mnote_data_unref (data->priv->md); data->priv->md = NULL; } exif_mem_free (mem, data->priv); exif_mem_free (mem, data); } exif_mem_unref (mem); } void exif_data_dump (ExifData *data) { unsigned int i; if (!data) return; for (i = 0; i < EXIF_IFD_COUNT; i++) { if (data->ifd[i] && data->ifd[i]->count) { printf ("Dumping IFD '%s'...\n", exif_ifd_get_name (i)); exif_content_dump (data->ifd[i], 0); } } if (data->data) { printf ("%i byte(s) thumbnail data available: ", data->size); if (data->size >= 4) { printf ("0x%02x 0x%02x ... 0x%02x 0x%02x\n", data->data[0], data->data[1], data->data[data->size - 2], data->data[data->size - 1]); } } } ExifByteOrder exif_data_get_byte_order (ExifData *data) { if (!data) return (0); return (data->priv->order); } void exif_data_foreach_content (ExifData *data, ExifDataForeachContentFunc func, void *user_data) { unsigned int i; if (!data || !func) return; for (i = 0; i < EXIF_IFD_COUNT; i++) func (data->ifd[i], user_data); } typedef struct _ByteOrderChangeData ByteOrderChangeData; struct _ByteOrderChangeData { ExifByteOrder old, new; }; static void entry_set_byte_order (ExifEntry *e, void *data) { ByteOrderChangeData *d = data; if (!e) return; exif_array_set_byte_order (e->format, e->data, e->components, d->old, d->new); } static void content_set_byte_order (ExifContent *content, void *data) { exif_content_foreach_entry (content, entry_set_byte_order, data); } void exif_data_set_byte_order (ExifData *data, ExifByteOrder order) { ByteOrderChangeData d; if (!data || (order == data->priv->order)) return; d.old = data->priv->order; d.new = order; exif_data_foreach_content (data, content_set_byte_order, &d); data->priv->order = order; if (data->priv->md) exif_mnote_data_set_byte_order (data->priv->md, order); } void exif_data_log (ExifData *data, ExifLog *log) { unsigned int i; if (!data || !data->priv) return; exif_log_unref (data->priv->log); data->priv->log = log; exif_log_ref (log); for (i = 0; i < EXIF_IFD_COUNT; i++) exif_content_log (data->ifd[i], log); } /* Used internally within libexif */ ExifLog *exif_data_get_log (ExifData *); ExifLog * exif_data_get_log (ExifData *data) { if (!data || !data->priv) return NULL; return data->priv->log; } static const struct { ExifDataOption option; const char *name; const char *description; } exif_data_option[] = { {EXIF_DATA_OPTION_IGNORE_UNKNOWN_TAGS, N_("Ignore unknown tags"), N_("Ignore unknown tags when loading EXIF data.")}, {EXIF_DATA_OPTION_FOLLOW_SPECIFICATION, N_("Follow specification"), N_("Add, correct and remove entries to get EXIF data that follows " "the specification.")}, {EXIF_DATA_OPTION_DONT_CHANGE_MAKER_NOTE, N_("Do not change maker note"), N_("When loading and resaving Exif data, save the maker note unmodified." " Be aware that the maker note can get corrupted.")}, {0, NULL, NULL} }; const char * exif_data_option_get_name (ExifDataOption o) { unsigned int i; for (i = 0; exif_data_option[i].name; i++) if (exif_data_option[i].option == o) break; return _(exif_data_option[i].name); } const char * exif_data_option_get_description (ExifDataOption o) { unsigned int i; for (i = 0; exif_data_option[i].description; i++) if (exif_data_option[i].option == o) break; return _(exif_data_option[i].description); } void exif_data_set_option (ExifData *d, ExifDataOption o) { if (!d) return; d->priv->options |= o; } void exif_data_unset_option (ExifData *d, ExifDataOption o) { if (!d) return; d->priv->options &= ~o; } static void fix_func (ExifContent *c, void *UNUSED(data)) { switch (exif_content_get_ifd (c)) { case EXIF_IFD_1: if (c->parent->data) exif_content_fix (c); else if (c->count) { exif_log (c->parent->priv->log, EXIF_LOG_CODE_DEBUG, "exif-data", "No thumbnail but entries on thumbnail. These entries have been " "removed."); while (c->count) { unsigned int cnt = c->count; exif_content_remove_entry (c, c->entries[c->count - 1]); if (cnt == c->count) { /* safety net */ exif_log (c->parent->priv->log, EXIF_LOG_CODE_DEBUG, "exif-data", "failed to remove last entry from entries."); c->count--; } } } break; default: exif_content_fix (c); } } void exif_data_fix (ExifData *d) { exif_data_foreach_content (d, fix_func, NULL); } void exif_data_set_data_type (ExifData *d, ExifDataType dt) { if (!d || !d->priv) return; d->priv->data_type = dt; } ExifDataType exif_data_get_data_type (ExifData *d) { return (d && d->priv) ? d->priv->data_type : EXIF_DATA_TYPE_UNKNOWN; }
null
/* exif-data.c * * Copyright (c) 2001 Lutz Mueller <lutz@users.sourceforge.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. */ #include <config.h> #include <libexif/exif-mnote-data.h> #include <libexif/exif-data.h> #include <libexif/exif-ifd.h> #include <libexif/exif-mnote-data-priv.h> #include <libexif/exif-utils.h> #include <libexif/exif-loader.h> #include <libexif/exif-log.h> #include <libexif/i18n.h> #include <libexif/exif-system.h> #include <libexif/canon/exif-mnote-data-canon.h> #include <libexif/fuji/exif-mnote-data-fuji.h> #include <libexif/olympus/exif-mnote-data-olympus.h> #include <libexif/pentax/exif-mnote-data-pentax.h> #include <math.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #undef JPEG_MARKER_SOI #define JPEG_MARKER_SOI 0xd8 #undef JPEG_MARKER_APP0 #define JPEG_MARKER_APP0 0xe0 #undef JPEG_MARKER_APP1 #define JPEG_MARKER_APP1 0xe1 static const unsigned char ExifHeader[] = {0x45, 0x78, 0x69, 0x66, 0x00, 0x00}; struct _ExifDataPrivate { ExifByteOrder order; ExifMnoteData *md; ExifLog *log; ExifMem *mem; unsigned int ref_count; /* Temporarily used while loading data */ unsigned int offset_mnote; ExifDataOption options; ExifDataType data_type; }; static void * exif_data_alloc (ExifData *data, unsigned int i) { void *d; if (!data || !i) return NULL; d = exif_mem_alloc (data->priv->mem, i); if (d) return d; EXIF_LOG_NO_MEMORY (data->priv->log, "ExifData", i); return NULL; } ExifMnoteData * exif_data_get_mnote_data (ExifData *d) { return (d && d->priv) ? d->priv->md : NULL; } ExifData * exif_data_new (void) { ExifMem *mem = exif_mem_new_default (); ExifData *d = exif_data_new_mem (mem); exif_mem_unref (mem); return d; } ExifData * exif_data_new_mem (ExifMem *mem) { ExifData *data; unsigned int i; if (!mem) return NULL; data = exif_mem_alloc (mem, sizeof (ExifData)); if (!data) return (NULL); data->priv = exif_mem_alloc (mem, sizeof (ExifDataPrivate)); if (!data->priv) { exif_mem_free (mem, data); return (NULL); } data->priv->ref_count = 1; data->priv->mem = mem; exif_mem_ref (mem); for (i = 0; i < EXIF_IFD_COUNT; i++) { data->ifd[i] = exif_content_new_mem (data->priv->mem); if (!data->ifd[i]) { exif_data_free (data); return (NULL); } data->ifd[i]->parent = data; } /* Default options */ #ifndef NO_VERBOSE_TAG_STRINGS /* * When the tag list is compiled away, setting this option prevents * any tags from being loaded */ exif_data_set_option (data, EXIF_DATA_OPTION_IGNORE_UNKNOWN_TAGS); #endif exif_data_set_option (data, EXIF_DATA_OPTION_FOLLOW_SPECIFICATION); /* Default data type: none */ exif_data_set_data_type (data, EXIF_DATA_TYPE_COUNT); return (data); } ExifData * exif_data_new_from_data (const unsigned char *data, unsigned int size) { ExifData *edata; edata = exif_data_new (); exif_data_load_data (edata, data, size); return (edata); } static int exif_data_load_data_entry (ExifData *data, ExifEntry *entry, const unsigned char *d, unsigned int size, unsigned int offset) { unsigned int s, doff; entry->tag = exif_get_short (d + offset + 0, data->priv->order); entry->format = exif_get_short (d + offset + 2, data->priv->order); entry->components = exif_get_long (d + offset + 4, data->priv->order); /* FIXME: should use exif_tag_get_name_in_ifd here but entry->parent * has not been set yet */ exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Loading entry 0x%x ('%s')...", entry->tag, exif_tag_get_name (entry->tag)); /* {0,1,2,4,8} x { 0x00000000 .. 0xffffffff } * -> { 0x000000000 .. 0x7fffffff8 } */ s = exif_format_get_size(entry->format) * entry->components; if ((s < entry->components) || (s == 0)){ return 0; } /* * Size? If bigger than 4 bytes, the actual data is not * in the entry but somewhere else (offset). */ if (s > 4) doff = exif_get_long (d + offset + 8, data->priv->order); else doff = offset + 8; /* Sanity checks */ if (doff >= size) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Tag starts past end of buffer (%u > %u)", doff, size); return 0; } if (s > size - doff) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Tag data goes past end of buffer (%u > %u)", doff+s, size); return 0; } entry->data = exif_data_alloc (data, s); if (entry->data) { entry->size = s; memcpy (entry->data, d + doff, s); } else { EXIF_LOG_NO_MEMORY(data->priv->log, "ExifData", s); return 0; } /* If this is the MakerNote, remember the offset */ if (entry->tag == EXIF_TAG_MAKER_NOTE) { if (!entry->data) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "MakerNote found with empty data"); } else if (entry->size > 6) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "MakerNote found (%02x %02x %02x %02x " "%02x %02x %02x...).", entry->data[0], entry->data[1], entry->data[2], entry->data[3], entry->data[4], entry->data[5], entry->data[6]); } data->priv->offset_mnote = doff; } return 1; } static void exif_data_save_data_entry (ExifData *data, ExifEntry *e, unsigned char **d, unsigned int *ds, unsigned int offset) { unsigned int doff, s; unsigned int ts; if (!data || !data->priv) return; /* * Each entry is 12 bytes long. The memory for the entry has * already been allocated. */ exif_set_short (*d + 6 + offset + 0, data->priv->order, (ExifShort) e->tag); exif_set_short (*d + 6 + offset + 2, data->priv->order, (ExifShort) e->format); if (!(data->priv->options & EXIF_DATA_OPTION_DONT_CHANGE_MAKER_NOTE)) { /* If this is the maker note tag, update it. */ if ((e->tag == EXIF_TAG_MAKER_NOTE) && data->priv->md) { /* TODO: this is using the wrong ExifMem to free e->data */ exif_mem_free (data->priv->mem, e->data); e->data = NULL; e->size = 0; exif_mnote_data_set_offset (data->priv->md, *ds - 6); exif_mnote_data_save (data->priv->md, &e->data, &e->size); e->components = e->size; if (exif_format_get_size (e->format) != 1) { /* e->format is taken from input code, * but we need to make sure it is a 1 byte * entity due to the multiplication below. */ e->format = EXIF_FORMAT_UNDEFINED; } } } exif_set_long (*d + 6 + offset + 4, data->priv->order, e->components); /* * Size? If bigger than 4 bytes, the actual data is not in * the entry but somewhere else. */ s = exif_format_get_size (e->format) * e->components; if (s > 4) { unsigned char *t; doff = *ds - 6; ts = *ds + s; /* * According to the TIFF specification, * the offset must be an even number. If we need to introduce * a padding byte, we set it to 0. */ if (s & 1) ts++; t = exif_mem_realloc (data->priv->mem, *d, ts); if (!t) { EXIF_LOG_NO_MEMORY (data->priv->log, "ExifData", ts); return; } *d = t; *ds = ts; exif_set_long (*d + 6 + offset + 8, data->priv->order, doff); if (s & 1) *(*d + *ds - 1) = '\0'; } else doff = offset + 8; /* Write the data. Fill unneeded bytes with 0. Do not crash with * e->data is NULL */ if (e->data) { memcpy (*d + 6 + doff, e->data, s); } else { memset (*d + 6 + doff, 0, s); } if (s < 4) memset (*d + 6 + doff + s, 0, (4 - s)); } static void exif_data_load_data_thumbnail (ExifData *data, const unsigned char *d, unsigned int ds, ExifLong o, ExifLong s) { /* Sanity checks */ if (o >= ds) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Bogus thumbnail offset (%u).", o); return; } if (s > ds - o) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Bogus thumbnail size (%u), max would be %u.", s, ds-o); return; } if (data->data) exif_mem_free (data->priv->mem, data->data); if (!(data->data = exif_data_alloc (data, s))) { EXIF_LOG_NO_MEMORY (data->priv->log, "ExifData", s); data->size = 0; return; } data->size = s; memcpy (data->data, d + o, s); } #undef CHECK_REC #define CHECK_REC(i) \ if ((i) == ifd) { \ exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \ "ExifData", "Recursive entry in IFD " \ "'%s' detected. Skipping...", \ exif_ifd_get_name (i)); \ break; \ } \ if (data->ifd[(i)]->count) { \ exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \ "ExifData", "Attempt to load IFD " \ "'%s' multiple times detected. " \ "Skipping...", \ exif_ifd_get_name (i)); \ break; \ } /*! Calculate the recursion cost added by one level of IFD loading. * * The work performed is related to the cost in the exponential relation * work=1.1**cost */ static unsigned int level_cost(unsigned int n) { static const double log_1_1 = 0.09531017980432493; /* Adding 0.1 protects against the case where n==1 */ return ceil(log(n + 0.1)/log_1_1); } /*! Load data for an IFD. * * \param[in,out] data #ExifData * \param[in] ifd IFD to load * \param[in] d pointer to buffer containing raw IFD data * \param[in] ds size of raw data in buffer at \c d * \param[in] offset offset into buffer at \c d at which IFD starts * \param[in] recursion_cost factor indicating how expensive this recursive * call could be */ static void exif_data_load_data_content (ExifData *data, ExifIfd ifd, const unsigned char *d, unsigned int ds, unsigned int offset, unsigned int recursion_cost) { ExifLong o, thumbnail_offset = 0, thumbnail_length = 0; ExifShort n; ExifEntry *entry; unsigned int i; ExifTag tag; if (!data || !data->priv) return; /* check for valid ExifIfd enum range */ if ((((int)ifd) < 0) || ( ((int)ifd) >= EXIF_IFD_COUNT)) return; if (recursion_cost > 170) { /* * recursion_cost is a logarithmic-scale indicator of how expensive this * recursive call might end up being. It is an indicator of the depth of * recursion as well as the potential for worst-case future recursive * calls. Since it's difficult to tell ahead of time how often recursion * will occur, this assumes the worst by assuming every tag could end up * causing recursion. * The value of 170 was chosen to limit typical EXIF structures to a * recursive depth of about 6, but pathological ones (those with very * many tags) to only 2. */ exif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifData", "Deep/expensive recursion detected!"); return; } /* Read the number of entries */ if ((offset + 2 < offset) || (offset + 2 < 2) || (offset + 2 > ds)) { exif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifData", "Tag data past end of buffer (%u > %u)", offset+2, ds); return; } n = exif_get_short (d + offset, data->priv->order); exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Loading %hu entries...", n); offset += 2; /* Check if we have enough data. */ if (offset + 12 * n > ds) { n = (ds - offset) / 12; exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Short data; only loading %hu entries...", n); } for (i = 0; i < n; i++) { tag = exif_get_short (d + offset + 12 * i, data->priv->order); switch (tag) { case EXIF_TAG_EXIF_IFD_POINTER: case EXIF_TAG_GPS_INFO_IFD_POINTER: case EXIF_TAG_INTEROPERABILITY_IFD_POINTER: case EXIF_TAG_JPEG_INTERCHANGE_FORMAT_LENGTH: case EXIF_TAG_JPEG_INTERCHANGE_FORMAT: o = exif_get_long (d + offset + 12 * i + 8, data->priv->order); /* FIXME: IFD_POINTER tags aren't marked as being in a * specific IFD, so exif_tag_get_name_in_ifd won't work */ exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Sub-IFD entry 0x%x ('%s') at %u.", tag, exif_tag_get_name(tag), o); switch (tag) { case EXIF_TAG_EXIF_IFD_POINTER: CHECK_REC (EXIF_IFD_EXIF); exif_data_load_data_content (data, EXIF_IFD_EXIF, d, ds, o, recursion_cost + level_cost(n)); break; case EXIF_TAG_GPS_INFO_IFD_POINTER: CHECK_REC (EXIF_IFD_GPS); exif_data_load_data_content (data, EXIF_IFD_GPS, d, ds, o, recursion_cost + level_cost(n)); break; case EXIF_TAG_INTEROPERABILITY_IFD_POINTER: CHECK_REC (EXIF_IFD_INTEROPERABILITY); exif_data_load_data_content (data, EXIF_IFD_INTEROPERABILITY, d, ds, o, recursion_cost + level_cost(n)); break; case EXIF_TAG_JPEG_INTERCHANGE_FORMAT: thumbnail_offset = o; if (thumbnail_offset && thumbnail_length) exif_data_load_data_thumbnail (data, d, ds, thumbnail_offset, thumbnail_length); break; case EXIF_TAG_JPEG_INTERCHANGE_FORMAT_LENGTH: thumbnail_length = o; if (thumbnail_offset && thumbnail_length) exif_data_load_data_thumbnail (data, d, ds, thumbnail_offset, thumbnail_length); break; default: return; } break; default: /* * If we don't know the tag, don't fail. It could be that new * versions of the standard have defined additional tags. Note that * 0 is a valid tag in the GPS IFD. */ if (!exif_tag_get_name_in_ifd (tag, ifd)) { /* * Special case: Tag and format 0. That's against specification * (at least up to 2.2). But Photoshop writes it anyways. */ if (!memcmp (d + offset + 12 * i, "\0\0\0\0", 4)) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Skipping empty entry at position %u in '%s'.", i, exif_ifd_get_name (ifd)); break; } exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Unknown tag 0x%04x (entry %u in '%s'). Please report this tag " "to <libexif-devel@lists.sourceforge.net>.", tag, i, exif_ifd_get_name (ifd)); if (data->priv->options & EXIF_DATA_OPTION_IGNORE_UNKNOWN_TAGS) break; } entry = exif_entry_new_mem (data->priv->mem); if (!entry) { exif_log (data->priv->log, EXIF_LOG_CODE_NO_MEMORY, "ExifData", "Could not allocate memory"); return; } if (exif_data_load_data_entry (data, entry, d, ds, offset + 12 * i)) exif_content_add_entry (data->ifd[ifd], entry); exif_entry_unref (entry); break; } } } static int cmp_func (const unsigned char *p1, const unsigned char *p2, ExifByteOrder o) { ExifShort tag1 = exif_get_short (p1, o); ExifShort tag2 = exif_get_short (p2, o); return (tag1 < tag2) ? -1 : (tag1 > tag2) ? 1 : 0; } static int cmp_func_intel (const void *elem1, const void *elem2) { return cmp_func ((const unsigned char *) elem1, (const unsigned char *) elem2, EXIF_BYTE_ORDER_INTEL); } static int cmp_func_motorola (const void *elem1, const void *elem2) { return cmp_func ((const unsigned char *) elem1, (const unsigned char *) elem2, EXIF_BYTE_ORDER_MOTOROLA); } static void exif_data_save_data_content (ExifData *data, ExifContent *ifd, unsigned char **d, unsigned int *ds, unsigned int offset) { unsigned int j, n_ptr = 0, n_thumb = 0; ExifIfd i; unsigned char *t; unsigned int ts; if (!data || !data->priv || !ifd || !d || !ds) return; for (i = 0; i < EXIF_IFD_COUNT; i++) if (ifd == data->ifd[i]) break; if (i == EXIF_IFD_COUNT) return; /* error */ /* * Check if we need some extra entries for pointers or the thumbnail. */ switch (i) { case EXIF_IFD_0: /* * The pointer to IFD_EXIF is in IFD_0. The pointer to * IFD_INTEROPERABILITY is in IFD_EXIF. */ if (data->ifd[EXIF_IFD_EXIF]->count || data->ifd[EXIF_IFD_INTEROPERABILITY]->count) n_ptr++; /* The pointer to IFD_GPS is in IFD_0. */ if (data->ifd[EXIF_IFD_GPS]->count) n_ptr++; break; case EXIF_IFD_1: if (data->size) n_thumb = 2; break; case EXIF_IFD_EXIF: if (data->ifd[EXIF_IFD_INTEROPERABILITY]->count) n_ptr++; default: break; } /* * Allocate enough memory for all entries * and the number of entries. */ ts = *ds + (2 + (ifd->count + n_ptr + n_thumb) * 12 + 4); t = exif_mem_realloc (data->priv->mem, *d, ts); if (!t) { EXIF_LOG_NO_MEMORY (data->priv->log, "ExifData", ts); return; } *d = t; *ds = ts; /* Save the number of entries */ exif_set_short (*d + 6 + offset, data->priv->order, (ExifShort) (ifd->count + n_ptr + n_thumb)); offset += 2; /* * Save each entry. Make sure that no memcpys from NULL pointers are * performed */ exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Saving %i entries (IFD '%s', offset: %i)...", ifd->count, exif_ifd_get_name (i), offset); for (j = 0; j < ifd->count; j++) { if (ifd->entries[j]) { exif_data_save_data_entry (data, ifd->entries[j], d, ds, offset + 12 * j); } } offset += 12 * ifd->count; /* Now save special entries. */ switch (i) { case EXIF_IFD_0: /* * The pointer to IFD_EXIF is in IFD_0. * However, the pointer to IFD_INTEROPERABILITY is in IFD_EXIF, * therefore, if IFD_INTEROPERABILITY is not empty, we need * IFD_EXIF even if latter is empty. */ if (data->ifd[EXIF_IFD_EXIF]->count || data->ifd[EXIF_IFD_INTEROPERABILITY]->count) { exif_set_short (*d + 6 + offset + 0, data->priv->order, EXIF_TAG_EXIF_IFD_POINTER); exif_set_short (*d + 6 + offset + 2, data->priv->order, EXIF_FORMAT_LONG); exif_set_long (*d + 6 + offset + 4, data->priv->order, 1); exif_set_long (*d + 6 + offset + 8, data->priv->order, *ds - 6); exif_data_save_data_content (data, data->ifd[EXIF_IFD_EXIF], d, ds, *ds - 6); offset += 12; } /* The pointer to IFD_GPS is in IFD_0, too. */ if (data->ifd[EXIF_IFD_GPS]->count) { exif_set_short (*d + 6 + offset + 0, data->priv->order, EXIF_TAG_GPS_INFO_IFD_POINTER); exif_set_short (*d + 6 + offset + 2, data->priv->order, EXIF_FORMAT_LONG); exif_set_long (*d + 6 + offset + 4, data->priv->order, 1); exif_set_long (*d + 6 + offset + 8, data->priv->order, *ds - 6); exif_data_save_data_content (data, data->ifd[EXIF_IFD_GPS], d, ds, *ds - 6); offset += 12; } break; case EXIF_IFD_EXIF: /* * The pointer to IFD_INTEROPERABILITY is in IFD_EXIF. * See note above. */ if (data->ifd[EXIF_IFD_INTEROPERABILITY]->count) { exif_set_short (*d + 6 + offset + 0, data->priv->order, EXIF_TAG_INTEROPERABILITY_IFD_POINTER); exif_set_short (*d + 6 + offset + 2, data->priv->order, EXIF_FORMAT_LONG); exif_set_long (*d + 6 + offset + 4, data->priv->order, 1); exif_set_long (*d + 6 + offset + 8, data->priv->order, *ds - 6); exif_data_save_data_content (data, data->ifd[EXIF_IFD_INTEROPERABILITY], d, ds, *ds - 6); offset += 12; } break; case EXIF_IFD_1: /* * Information about the thumbnail (if any) is saved in * IFD_1. */ if (data->size) { /* EXIF_TAG_JPEG_INTERCHANGE_FORMAT */ exif_set_short (*d + 6 + offset + 0, data->priv->order, EXIF_TAG_JPEG_INTERCHANGE_FORMAT); exif_set_short (*d + 6 + offset + 2, data->priv->order, EXIF_FORMAT_LONG); exif_set_long (*d + 6 + offset + 4, data->priv->order, 1); exif_set_long (*d + 6 + offset + 8, data->priv->order, *ds - 6); ts = *ds + data->size; t = exif_mem_realloc (data->priv->mem, *d, ts); if (!t) { EXIF_LOG_NO_MEMORY (data->priv->log, "ExifData", ts); return; } *d = t; *ds = ts; memcpy (*d + *ds - data->size, data->data, data->size); offset += 12; /* EXIF_TAG_JPEG_INTERCHANGE_FORMAT_LENGTH */ exif_set_short (*d + 6 + offset + 0, data->priv->order, EXIF_TAG_JPEG_INTERCHANGE_FORMAT_LENGTH); exif_set_short (*d + 6 + offset + 2, data->priv->order, EXIF_FORMAT_LONG); exif_set_long (*d + 6 + offset + 4, data->priv->order, 1); exif_set_long (*d + 6 + offset + 8, data->priv->order, data->size); offset += 12; } break; default: break; } /* Sort the directory according to TIFF specification */ qsort (*d + 6 + offset - (ifd->count + n_ptr + n_thumb) * 12, (ifd->count + n_ptr + n_thumb), 12, (data->priv->order == EXIF_BYTE_ORDER_INTEL) ? cmp_func_intel : cmp_func_motorola); /* Correctly terminate the directory */ if (i == EXIF_IFD_0 && (data->ifd[EXIF_IFD_1]->count || data->size)) { /* * We are saving IFD 0. Tell where IFD 1 starts and save * IFD 1. */ exif_set_long (*d + 6 + offset, data->priv->order, *ds - 6); exif_data_save_data_content (data, data->ifd[EXIF_IFD_1], d, ds, *ds - 6); } else exif_set_long (*d + 6 + offset, data->priv->order, 0); } typedef enum { EXIF_DATA_TYPE_MAKER_NOTE_NONE = 0, EXIF_DATA_TYPE_MAKER_NOTE_CANON = 1, EXIF_DATA_TYPE_MAKER_NOTE_OLYMPUS = 2, EXIF_DATA_TYPE_MAKER_NOTE_PENTAX = 3, EXIF_DATA_TYPE_MAKER_NOTE_NIKON = 4, EXIF_DATA_TYPE_MAKER_NOTE_CASIO = 5, EXIF_DATA_TYPE_MAKER_NOTE_FUJI = 6 } ExifDataTypeMakerNote; /*! If MakerNote is recognized, load it. * * \param[in,out] data #ExifData * \param[in] d pointer to raw EXIF data * \param[in] ds length of data at d */ static void interpret_maker_note(ExifData *data, const unsigned char *d, unsigned int ds) { int mnoteid; ExifEntry* e = exif_data_get_entry (data, EXIF_TAG_MAKER_NOTE); if (!e) return; if ((mnoteid = exif_mnote_data_olympus_identify (data, e)) != 0) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Olympus MakerNote variant type %d", mnoteid); data->priv->md = exif_mnote_data_olympus_new (data->priv->mem); } else if ((mnoteid = exif_mnote_data_canon_identify (data, e)) != 0) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Canon MakerNote variant type %d", mnoteid); data->priv->md = exif_mnote_data_canon_new (data->priv->mem, data->priv->options); } else if ((mnoteid = exif_mnote_data_fuji_identify (data, e)) != 0) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Fuji MakerNote variant type %d", mnoteid); data->priv->md = exif_mnote_data_fuji_new (data->priv->mem); /* NOTE: Must do Pentax detection last because some of the * heuristics are pretty general. */ } else if ((mnoteid = exif_mnote_data_pentax_identify (data, e)) != 0) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Pentax MakerNote variant type %d", mnoteid); data->priv->md = exif_mnote_data_pentax_new (data->priv->mem); } /* * If we are able to interpret the maker note, do so. */ if (data->priv->md) { exif_mnote_data_log (data->priv->md, data->priv->log); exif_mnote_data_set_byte_order (data->priv->md, data->priv->order); exif_mnote_data_set_offset (data->priv->md, data->priv->offset_mnote); exif_mnote_data_load (data->priv->md, d, ds); } } #define LOG_TOO_SMALL \ exif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifData", \ _("Size of data too small to allow for EXIF data.")); void exif_data_load_data (ExifData *data, const unsigned char *d_orig, unsigned int ds) { unsigned int l; ExifLong offset; ExifShort n; const unsigned char *d = d_orig; unsigned int len, fullds; if (!data || !data->priv || !d || !ds) return; exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Parsing %i byte(s) EXIF data...\n", ds); /* * It can be that the data starts with the EXIF header. If it does * not, search the EXIF marker. */ if (ds < 6) { LOG_TOO_SMALL; return; } if (!memcmp (d, ExifHeader, 6)) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Found EXIF header at start."); } else { while (ds >= 3) { while (ds && (d[0] == 0xff)) { d++; ds--; } /* JPEG_MARKER_SOI */ if (ds && d[0] == JPEG_MARKER_SOI) { d++; ds--; continue; } /* JPEG_MARKER_APP1 */ if (ds && d[0] == JPEG_MARKER_APP1) break; /* Skip irrelevant APP markers. The branch for APP1 must come before this, otherwise this code block will cause APP1 to be skipped. This code path is only relevant for files that are nonconformant to the EXIF specification. For conformant files, the APP1 code path above will be taken. */ if (ds >= 3 && d[0] >= 0xe0 && d[0] <= 0xef) { /* JPEG_MARKER_APPn */ d++; ds--; l = (d[0] << 8) | d[1]; if (l > ds) return; d += l; ds -= l; continue; } /* Unknown marker or data. Give up. */ exif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifData", _("EXIF marker not found.")); return; } if (ds < 3) { LOG_TOO_SMALL; return; } d++; ds--; len = (d[0] << 8) | d[1]; exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "We have to deal with %i byte(s) of EXIF data.", len); d += 2; ds -= 2; } /* * Verify the exif header * (offset 2, length 6). */ if (ds < 6) { LOG_TOO_SMALL; return; } if (memcmp (d, ExifHeader, 6)) { exif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifData", _("EXIF header not found.")); return; } exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Found EXIF header."); /* Sanity check the data length */ if (ds < 14) return; /* The JPEG APP1 section can be no longer than 64 KiB (including a 16-bit length), so cap the data length to protect against overflow in future offset calculations */ fullds = ds; if (ds > 0xfffe) ds = 0xfffe; /* Byte order (offset 6, length 2) */ if (!memcmp (d + 6, "II", 2)) data->priv->order = EXIF_BYTE_ORDER_INTEL; else if (!memcmp (d + 6, "MM", 2)) data->priv->order = EXIF_BYTE_ORDER_MOTOROLA; else { exif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifData", _("Unknown encoding.")); return; } /* Fixed value */ if (exif_get_short (d + 8, data->priv->order) != 0x002a) return; /* IFD 0 offset */ offset = exif_get_long (d + 10, data->priv->order); exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "IFD 0 at %i.", (int) offset); /* ds is restricted to 16 bit above, so offset is restricted too, and offset+8 should not overflow. */ if (offset > ds || offset + 6 + 2 > ds) return; /* Parse the actual exif data (usually offset 14 from start) */ exif_data_load_data_content (data, EXIF_IFD_0, d + 6, ds - 6, offset, 0); /* IFD 1 offset */ n = exif_get_short (d + 6 + offset, data->priv->order); /* offset < 2<<16, n is 16 bit at most, so this op will not overflow */ if (offset + 6 + 2 + 12 * n + 4 > ds) return; offset = exif_get_long (d + 6 + offset + 2 + 12 * n, data->priv->order); if (offset) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "IFD 1 at %i.", (int) offset); /* Sanity check. ds is ensured to be above 6 above, offset is 16bit */ if (offset > ds - 6) { exif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifData", "Bogus offset of IFD1."); } else { exif_data_load_data_content (data, EXIF_IFD_1, d + 6, ds - 6, offset, 0); } } /* * If we got an EXIF_TAG_MAKER_NOTE, try to interpret it. Some * cameras use pointers in the maker note tag that point to the * space between IFDs. Here is the only place where we have access * to that data. */ interpret_maker_note(data, d, fullds); /* Fixup tags if requested */ if (data->priv->options & EXIF_DATA_OPTION_FOLLOW_SPECIFICATION) exif_data_fix (data); } void exif_data_save_data (ExifData *data, unsigned char **d, unsigned int *ds) { if (ds) *ds = 0; /* This means something went wrong */ if (!data || !d || !ds) return; /* Header */ *ds = 14; *d = exif_data_alloc (data, *ds); if (!*d) { *ds = 0; return; } memcpy (*d, ExifHeader, 6); /* Order (offset 6) */ if (data->priv->order == EXIF_BYTE_ORDER_INTEL) { memcpy (*d + 6, "II", 2); } else { memcpy (*d + 6, "MM", 2); } /* Fixed value (2 bytes, offset 8) */ exif_set_short (*d + 8, data->priv->order, 0x002a); /* * IFD 0 offset (4 bytes, offset 10). * We will start 8 bytes after the * EXIF header (2 bytes for order, another 2 for the test, and * 4 bytes for the IFD 0 offset make 8 bytes together). */ exif_set_long (*d + 10, data->priv->order, 8); /* Now save IFD 0. IFD 1 will be saved automatically. */ exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Saving IFDs..."); exif_data_save_data_content (data, data->ifd[EXIF_IFD_0], d, ds, *ds - 6); exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Saved %i byte(s) EXIF data.", *ds); } ExifData * exif_data_new_from_file (const char *path) { ExifData *edata; ExifLoader *loader; loader = exif_loader_new (); exif_loader_write_file (loader, path); edata = exif_loader_get_data (loader); exif_loader_unref (loader); return (edata); } void exif_data_ref (ExifData *data) { if (!data) return; data->priv->ref_count++; } void exif_data_unref (ExifData *data) { if (!data) return; data->priv->ref_count--; if (!data->priv->ref_count) exif_data_free (data); } void exif_data_free (ExifData *data) { unsigned int i; ExifMem *mem = (data && data->priv) ? data->priv->mem : NULL; if (!data) return; for (i = 0; i < EXIF_IFD_COUNT; i++) { if (data->ifd[i]) { exif_content_unref (data->ifd[i]); data->ifd[i] = NULL; } } if (data->data) { exif_mem_free (mem, data->data); data->data = NULL; } if (data->priv) { if (data->priv->log) { exif_log_unref (data->priv->log); data->priv->log = NULL; } if (data->priv->md) { exif_mnote_data_unref (data->priv->md); data->priv->md = NULL; } exif_mem_free (mem, data->priv); exif_mem_free (mem, data); } exif_mem_unref (mem); } void exif_data_dump (ExifData *data) { unsigned int i; if (!data) return; for (i = 0; i < EXIF_IFD_COUNT; i++) { if (data->ifd[i] && data->ifd[i]->count) { printf ("Dumping IFD '%s'...\n", exif_ifd_get_name (i)); exif_content_dump (data->ifd[i], 0); } } if (data->data) { printf ("%i byte(s) thumbnail data available: ", data->size); if (data->size >= 4) { printf ("0x%02x 0x%02x ... 0x%02x 0x%02x\n", data->data[0], data->data[1], data->data[data->size - 2], data->data[data->size - 1]); } } } ExifByteOrder exif_data_get_byte_order (ExifData *data) { if (!data) return (0); return (data->priv->order); } void exif_data_foreach_content (ExifData *data, ExifDataForeachContentFunc func, void *user_data) { unsigned int i; if (!data || !func) return; for (i = 0; i < EXIF_IFD_COUNT; i++) func (data->ifd[i], user_data); } typedef struct _ByteOrderChangeData ByteOrderChangeData; struct _ByteOrderChangeData { ExifByteOrder old, new; }; static void entry_set_byte_order (ExifEntry *e, void *data) { ByteOrderChangeData *d = data; if (!e) return; exif_array_set_byte_order (e->format, e->data, e->components, d->old, d->new); } static void content_set_byte_order (ExifContent *content, void *data) { exif_content_foreach_entry (content, entry_set_byte_order, data); } void exif_data_set_byte_order (ExifData *data, ExifByteOrder order) { ByteOrderChangeData d; if (!data || (order == data->priv->order)) return; d.old = data->priv->order; d.new = order; exif_data_foreach_content (data, content_set_byte_order, &d); data->priv->order = order; if (data->priv->md) exif_mnote_data_set_byte_order (data->priv->md, order); } void exif_data_log (ExifData *data, ExifLog *log) { unsigned int i; if (!data || !data->priv) return; exif_log_unref (data->priv->log); data->priv->log = log; exif_log_ref (log); for (i = 0; i < EXIF_IFD_COUNT; i++) exif_content_log (data->ifd[i], log); } /* Used internally within libexif */ ExifLog *exif_data_get_log (ExifData *); ExifLog * exif_data_get_log (ExifData *data) { if (!data || !data->priv) return NULL; return data->priv->log; } static const struct { ExifDataOption option; const char *name; const char *description; } exif_data_option[] = { {EXIF_DATA_OPTION_IGNORE_UNKNOWN_TAGS, N_("Ignore unknown tags"), N_("Ignore unknown tags when loading EXIF data.")}, {EXIF_DATA_OPTION_FOLLOW_SPECIFICATION, N_("Follow specification"), N_("Add, correct and remove entries to get EXIF data that follows " "the specification.")}, {EXIF_DATA_OPTION_DONT_CHANGE_MAKER_NOTE, N_("Do not change maker note"), N_("When loading and resaving Exif data, save the maker note unmodified." " Be aware that the maker note can get corrupted.")}, {0, NULL, NULL} }; const char * exif_data_option_get_name (ExifDataOption o) { unsigned int i; for (i = 0; exif_data_option[i].name; i++) if (exif_data_option[i].option == o) break; return _(exif_data_option[i].name); } const char * exif_data_option_get_description (ExifDataOption o) { unsigned int i; for (i = 0; exif_data_option[i].description; i++) if (exif_data_option[i].option == o) break; return _(exif_data_option[i].description); } void exif_data_set_option (ExifData *d, ExifDataOption o) { if (!d) return; d->priv->options |= o; } void exif_data_unset_option (ExifData *d, ExifDataOption o) { if (!d) return; d->priv->options &= ~o; } static void fix_func (ExifContent *c, void *UNUSED(data)) { switch (exif_content_get_ifd (c)) { case EXIF_IFD_1: if (c->parent->data) exif_content_fix (c); else if (c->count) { exif_log (c->parent->priv->log, EXIF_LOG_CODE_DEBUG, "exif-data", "No thumbnail but entries on thumbnail. These entries have been " "removed."); while (c->count) { unsigned int cnt = c->count; exif_content_remove_entry (c, c->entries[c->count - 1]); if (cnt == c->count) { /* safety net */ exif_log (c->parent->priv->log, EXIF_LOG_CODE_DEBUG, "exif-data", "failed to remove last entry from entries."); c->count--; } } } break; default: exif_content_fix (c); } } void exif_data_fix (ExifData *d) { exif_data_foreach_content (d, fix_func, NULL); } void exif_data_set_data_type (ExifData *d, ExifDataType dt) { if (!d || !d->priv) return; d->priv->data_type = dt; } ExifDataType exif_data_get_data_type (ExifData *d) { return (d && d->priv) ? d->priv->data_type : EXIF_DATA_TYPE_UNKNOWN; }
null
162
CWE-787
CVE-2020-10232
/* ** The Sleuth Kit ** ** Brian Carrier [carrier <at> sleuthkit [dot] org] ** Copyright (c) 2006-2011 Brian Carrier, Basis Technology. All Rights reserved ** Copyright (c) 2003-2005 Brian Carrier. All rights reserved ** ** TASK v** Copyright (c) 2002-2003 Brian Carrier, @stake Inc. All rights reserved ** ** Copyright (c) 1997,1998,1999, International Business Machines ** Corporation and others. All Rights Reserved. */ /** *\file yaffs.cpp * Contains the internal TSK YAFFS2 file system functions. */ /* TCT * LICENSE * This software is distributed under the IBM Public License. * AUTHOR(S) * Wietse Venema * IBM T.J. Watson Research * P.O. Box 704 * Yorktown Heights, NY 10598, USA --*/ #include <vector> #include <map> #include <algorithm> #include <string> #include <set> #include <string.h> #include "tsk_fs_i.h" #include "tsk_yaffs.h" #include "tsk_fs.h" /* * Implementation Notes: * - As inode, we use object id and a version number derived from the * number of unique sequence ids for the object still left in the * file system. * * - The version numbers start at 1 and increase as they get closer to * the the latest version. Version number 0 is a special version * that is equivalent to the latest version (without having to know * the latest version number.) * * - Since inodes are composed using the object id in the least * significant bits and the version up higher, requesting the * inode that matches the object id you are looking for will * retrieve the latest version of this object. * * - Files always exist in the latest version of their parent directory * only. * * - Filenames are not unique even with attached version numbers, since * version numbers are namespaced by inode. * * - The cache stores a lot of info via the structure. As this is * used for investigations, we assume these decisions will be updated * to expose the most useful view of this log based file system. TSK * doesn't seem have a real way to expose a versioned view of a log * based file system like this. Shoehorning it into the framework * ends up dropping some information. I looked at using resource * streams as versions, but the abstraction breaks quickly. * */ static const int TWELVE_BITS_MASK = 0xFFF; // Only keep 12 bits static uint8_t yaffsfs_read_header(YAFFSFS_INFO *yfs, YaffsHeader ** header, TSK_OFF_T offset); static uint8_t yaffsfs_load_attrs(TSK_FS_FILE *file); /** * Generate an inode number based on the file's object and version numbers */ static TSK_RETVAL_ENUM yaffscache_obj_id_and_version_to_inode(uint32_t obj_id, uint32_t version_num, TSK_INUM_T *inode) { if ((obj_id & ~YAFFS_OBJECT_ID_MASK) != 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffsfs_parse_image_load_cache: Max object ID %" PRIu32 " is invalid", obj_id); return TSK_ERR; } if ((version_num & ~YAFFS_VERSION_NUM_MASK) != 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffsfs_parse_image_load_cache: Max version number %" PRIu32 " is invalid", version_num); return TSK_ERR; } *inode = obj_id | (version_num << YAFFS_VERSION_NUM_SHIFT); return TSK_OK; } /** * Given the TSK-generated inode address, extract the object id and version number from it */ static TSK_RETVAL_ENUM yaffscache_inode_to_obj_id_and_version(TSK_INUM_T inode, uint32_t *obj_id, uint32_t *version_num) { *obj_id = inode & YAFFS_OBJECT_ID_MASK; *version_num = (inode >> YAFFS_VERSION_NUM_SHIFT) & YAFFS_VERSION_NUM_MASK; return TSK_OK; } /* * Order it like yaffs2.git does -- sort by (seq_num, offset/block) */ static int yaffscache_chunk_compare(YaffsCacheChunk *curr, uint32_t addee_obj_id, TSK_OFF_T addee_offset, uint32_t addee_seq_number) { if (curr->ycc_obj_id == addee_obj_id) { if (curr->ycc_seq_number == addee_seq_number) { if (curr->ycc_offset == addee_offset) { return 0; } else if (curr->ycc_offset < addee_offset) { return -1; } else { return 1; } } else if (curr->ycc_seq_number < addee_seq_number) { return -1; } else { return 1; } } else if (curr->ycc_obj_id < addee_obj_id) { return -1; } else { return 1; } } static TSK_RETVAL_ENUM yaffscache_chunk_find_insertion_point(YAFFSFS_INFO *yfs, uint32_t obj_id, TSK_OFF_T offset, uint32_t seq_number, YaffsCacheChunk **chunk) { YaffsCacheChunk *curr, *prev; // Have we seen this obj_id? If not, add an entry for it if(yfs->chunkMap->find(obj_id) == yfs->chunkMap->end()){ fflush(stderr); YaffsCacheChunkGroup chunkGroup; chunkGroup.cache_chunks_head = NULL; chunkGroup.cache_chunks_tail = NULL; yfs->chunkMap->insert(std::make_pair(obj_id, chunkGroup)); } curr = yfs->chunkMap->operator[](obj_id).cache_chunks_head; prev = NULL; if (chunk == NULL) { return TSK_ERR; } while(curr != NULL) { // Compares obj id, then seq num, then offset. -1 => current < new int cmp = yaffscache_chunk_compare(curr, obj_id, offset, seq_number); if (cmp == 0) { *chunk = curr; return TSK_OK; } else if (cmp == 1) { *chunk = prev; return TSK_STOP; } prev = curr; curr = curr->ycc_next; } *chunk = prev; return TSK_STOP; } /** * Add a chunk to the cache. * @param yfs * @param offset Byte offset this chunk was found in (in the disk image) * @param seq_number Sequence number of this chunk * @param obj_id Object Id this chunk is associated with * @param parent_id Parent object ID that this chunk/object is associated with */ static TSK_RETVAL_ENUM yaffscache_chunk_add(YAFFSFS_INFO *yfs, TSK_OFF_T offset, uint32_t seq_number, uint32_t obj_id, uint32_t chunk_id, uint32_t parent_id) { TSK_RETVAL_ENUM result; YaffsCacheChunk *prev; YaffsCacheChunk *chunk; if ((chunk = (YaffsCacheChunk*)tsk_malloc(sizeof(YaffsCacheChunk))) == NULL) { return TSK_ERR; } chunk->ycc_offset = offset; chunk->ycc_seq_number = seq_number; chunk->ycc_obj_id = obj_id; chunk->ycc_chunk_id = chunk_id; chunk->ycc_parent_id = parent_id; // Bit of a hack here. In some images, the root directory (obj_id = 1) lists iself as its parent // directory, which can cause issues later when we get directory contents. To prevent this, // if a chunk comes in with obj_id = 1 and parent_id = 1, manually set the parent ID to zero. if((obj_id == 1) && (parent_id == 1)){ chunk->ycc_parent_id = 0; } // Find the chunk that should go right before the new chunk result = yaffscache_chunk_find_insertion_point(yfs, obj_id, offset, seq_number, &prev); if (result == TSK_ERR) { return TSK_ERR; } if (prev == NULL) { // No previous chunk - new chunk is the lowest we've seen and the new start of the list chunk->ycc_prev = NULL; chunk->ycc_next = yfs->chunkMap->operator[](obj_id).cache_chunks_head; } else { chunk->ycc_prev = prev; chunk->ycc_next = prev->ycc_next; } if (chunk->ycc_next != NULL) { // If we're not at the end, set the prev pointer on the next chunk to point to our new one chunk->ycc_next->ycc_prev = chunk; } else { yfs->chunkMap->operator[](obj_id).cache_chunks_tail = chunk; } if (chunk->ycc_prev != NULL) { // If we're not at the beginning, set the next pointer on the previous chunk to point at our new one chunk->ycc_prev->ycc_next = chunk; } else { yfs->chunkMap->operator[](obj_id).cache_chunks_head = chunk; } return TSK_OK; } /** * Get the file object from the cache. * @returns TSK_OK if it was found and TSK_STOP if we did not find it */ static TSK_RETVAL_ENUM yaffscache_object_find(YAFFSFS_INFO *yfs, uint32_t obj_id, YaffsCacheObject **obj) { YaffsCacheObject *curr, *prev; curr = yfs->cache_objects; prev = NULL; if (obj == NULL) { return TSK_ERR; } while(curr != NULL) { if (curr->yco_obj_id == obj_id) { *obj = curr; return TSK_OK; } else if (curr->yco_obj_id > obj_id) { *obj = prev; return TSK_STOP; } prev = curr; curr = curr->yco_next; } *obj = prev; return TSK_STOP; } /** * Add an object to the cache if it does not already exist in there. * @returns TSK_ERR on error, TSK_OK otherwise. */ static TSK_RETVAL_ENUM yaffscache_object_find_or_add(YAFFSFS_INFO *yfs, uint32_t obj_id, YaffsCacheObject **obj) { YaffsCacheObject *prev; TSK_RETVAL_ENUM result; if (obj == NULL) { return TSK_ERR; } // Look for this obj_id in yfs->cache_objects // If not found, add it in the correct spot // yaffscache_object_find returns the last object with obj_id less than the one // we were searching for, so use that to insert the new one in the list result = yaffscache_object_find(yfs, obj_id, &prev); if (result == TSK_OK) { *obj = prev; return TSK_OK; } else if (result == TSK_STOP) { *obj = (YaffsCacheObject *) tsk_malloc(sizeof(YaffsCacheObject)); (*obj)->yco_obj_id = obj_id; if (prev == NULL) { (*obj)->yco_next = yfs->cache_objects; yfs->cache_objects = *obj; } else { (*obj)->yco_next = prev->yco_next; prev->yco_next = (*obj); } return TSK_OK; } else { *obj = NULL; return TSK_ERR; } } static TSK_RETVAL_ENUM yaffscache_object_add_version(YaffsCacheObject *obj, YaffsCacheChunk *chunk) { uint32_t ver_number; YaffsCacheChunk *header_chunk = NULL; YaffsCacheVersion *version; // Going to try ignoring unlinked/deleted headers (objID 3 and 4) if ((chunk->ycc_chunk_id == 0) && (chunk->ycc_parent_id != YAFFS_OBJECT_UNLINKED) &&(chunk->ycc_parent_id != YAFFS_OBJECT_DELETED)) { header_chunk = chunk; } /* If this is the second version (since last header_chunk is not NULL) and no * header was added, get rid of this incomplete old version -- can't be * reasonably recovered. * * TODO: These chunks are still in the structure and can be walked, * but I'm not sure how to represent this set of data chunks * with no metadata under TSK. This is rare and we don't have * a testcase for it now. Punting right now. * * Edit: Shouldn't get to this point anymore. Changes to * yaffscache_versions_insert_chunk make a version continue until it * has a header block. */ if (obj->yco_latest != NULL) { if (obj->yco_latest->ycv_header_chunk == NULL) { YaffsCacheVersion *incomplete = obj->yco_latest; if (tsk_verbose) tsk_fprintf(stderr, "yaffscache_object_add_version: " "removed an incomplete first version (no header)\n"); obj->yco_latest = obj->yco_latest->ycv_prior; free(incomplete); } } if (obj->yco_latest != NULL) { ver_number = obj->yco_latest->ycv_version + 1; /* Until a new header is given, use the last seen header. */ if (header_chunk == NULL) { header_chunk = obj->yco_latest->ycv_header_chunk; // If we haven't seen a good header yet and we have a deleted/unlinked one, use it if((header_chunk == NULL) && (chunk->ycc_chunk_id == 0)){ header_chunk = chunk; } } } else { ver_number = 1; } if ((version = (YaffsCacheVersion *) tsk_malloc(sizeof(YaffsCacheVersion))) == NULL) { return TSK_ERR; } version->ycv_prior = obj->yco_latest; version->ycv_version = ver_number; version->ycv_seq_number = chunk->ycc_seq_number; version->ycv_header_chunk = header_chunk; version->ycv_first_chunk = chunk; version->ycv_last_chunk = chunk; obj->yco_latest = version; return TSK_OK; } /** * Add a chunk to its corresponding object in the cache. */ static TSK_RETVAL_ENUM yaffscache_versions_insert_chunk(YAFFSFS_INFO *yfs, YaffsCacheChunk *chunk) { YaffsCacheObject *obj; TSK_RETVAL_ENUM result; YaffsCacheVersion *version; // Building a list in yfs->cache_objects, sorted by obj_id result = yaffscache_object_find_or_add(yfs, chunk->ycc_obj_id, &obj); if (result != TSK_OK) { return TSK_ERR; } version = obj->yco_latest; /* First chunk in this object? */ if (version == NULL) { yaffscache_object_add_version(obj, chunk); } else { /* Chunk in the same update? */ if (chunk->ycc_seq_number == version->ycv_seq_number) { version->ycv_last_chunk = chunk; if ((chunk->ycc_chunk_id == 0) && (chunk->ycc_parent_id != YAFFS_OBJECT_UNLINKED) &&(chunk->ycc_parent_id != YAFFS_OBJECT_DELETED)) { version->ycv_header_chunk = chunk; } else if((chunk->ycc_chunk_id == 0) && (version->ycv_header_chunk == NULL)){ version->ycv_header_chunk = chunk; } } // If there was no header for the last version, continue adding to it instead // of starting a new version. else if(version->ycv_header_chunk == NULL){ version->ycv_seq_number = chunk->ycc_seq_number; version->ycv_last_chunk = chunk; if ((chunk->ycc_chunk_id == 0) && (chunk->ycc_parent_id != YAFFS_OBJECT_UNLINKED) &&(chunk->ycc_parent_id != YAFFS_OBJECT_DELETED)) { version->ycv_header_chunk = chunk; } else if((chunk->ycc_chunk_id == 0) && (version->ycv_header_chunk == NULL)){ version->ycv_header_chunk = chunk; } } else if(chunk->ycc_chunk_id == 0){ // Directories only have a header block // If we're looking at a new version of a directory where the previous version had the same name, // leave everything in the same version. Multiple versions of the same directory aren't really giving us // any information. YaffsHeader * newHeader; yaffsfs_read_header(yfs, &newHeader, chunk->ycc_offset); if((newHeader != NULL) && (newHeader->obj_type == YAFFS_TYPE_DIRECTORY)){ // Read in the old header YaffsHeader * oldHeader; yaffsfs_read_header(yfs, &oldHeader, version->ycv_header_chunk->ycc_offset); if((oldHeader != NULL) && (oldHeader->obj_type == YAFFS_TYPE_DIRECTORY) && (0 == strncmp(oldHeader->name, newHeader->name, YAFFS_HEADER_NAME_LENGTH))){ version->ycv_seq_number = chunk->ycc_seq_number; version->ycv_last_chunk = chunk; version->ycv_header_chunk = chunk; } else{ // The older header either isn't a directory or it doesn't have the same name, so leave it // as its own version yaffscache_object_add_version(obj, chunk); } } else{ // Not a directory yaffscache_object_add_version(obj, chunk); } } else{ // Otherwise, add this chunk as the start of a new version yaffscache_object_add_version(obj, chunk); } } return TSK_OK; } static TSK_RETVAL_ENUM yaffscache_versions_compute(YAFFSFS_INFO *yfs) { std::map<unsigned int,YaffsCacheChunkGroup>::iterator iter; for( iter = yfs->chunkMap->begin(); iter != yfs->chunkMap->end(); ++iter ) { YaffsCacheChunk *chunk_curr = yfs->chunkMap->operator[](iter->first).cache_chunks_head; while(chunk_curr != NULL) { if (yaffscache_versions_insert_chunk(yfs, chunk_curr) != TSK_OK) { return TSK_ERR; } chunk_curr = chunk_curr->ycc_next; } } return TSK_OK; } /** * Callback for yaffscache_find_children() * @param obj Object that is a child * @param version Version of the object * @param args Pointer to what was passed into yaffscache_find_children */ typedef TSK_RETVAL_ENUM yc_find_children_cb(YaffsCacheObject *obj, YaffsCacheVersion *version, void *args); /** * Search the cache for objects that are children of the given address. * @param yfs * @param parent_inode Inode of folder/directory * @param cb Call back to call for each found child * @param args Pointer to structure that will be passed to cb * @returns TSK_ERR on error */ static TSK_RETVAL_ENUM yaffscache_find_children(YAFFSFS_INFO *yfs, TSK_INUM_T parent_inode, yc_find_children_cb cb, void *args) { YaffsCacheObject *obj; uint32_t parent_id, version_num; if (yaffscache_inode_to_obj_id_and_version(parent_inode, &parent_id, &version_num) != TSK_OK) { return TSK_ERR; } /* Iterate over all objects and all versions of the objects to see if one is the child * of the given parent. */ for (obj = yfs->cache_objects; obj != NULL; obj = obj->yco_next) { YaffsCacheVersion *version; for (version = obj->yco_latest; version != NULL; version = version->ycv_prior) { /* Is this an incomplete version? */ if (version->ycv_header_chunk == NULL) { continue; } if (version->ycv_header_chunk->ycc_parent_id == parent_id) { TSK_RETVAL_ENUM result = cb(obj, version, args); if (result != TSK_OK) return result; } } } return TSK_OK; } /** * Lookup an object based on its inode. * @param yfs * @param inode * @param version [out] Pointer to store version of the object that was found (if inode had a version of 0) * @param obj_ret [out] Pointer to store found object into * @returns TSK_ERR on error. */ static TSK_RETVAL_ENUM yaffscache_version_find_by_inode(YAFFSFS_INFO *yfs, TSK_INUM_T inode, YaffsCacheVersion **version, YaffsCacheObject **obj_ret) { uint32_t obj_id, version_num; YaffsCacheObject *obj; YaffsCacheVersion *curr; if (version == NULL) { return TSK_ERR; } // convert inode to obj and version and find it in cache if (yaffscache_inode_to_obj_id_and_version(inode, &obj_id, &version_num) != TSK_OK) { *version = NULL; return TSK_ERR; } if (yaffscache_object_find(yfs, obj_id, &obj) != TSK_OK) { *version = NULL; return TSK_ERR; } if (version_num == 0) { if (obj_ret != NULL) { *obj_ret = obj; } *version = obj->yco_latest; return TSK_OK; } // Find the requested version in the list. for(curr = obj->yco_latest; curr != NULL; curr = curr->ycv_prior) { if (curr->ycv_version == version_num) { if (obj_ret != NULL) { *obj_ret = obj; } *version = curr; return TSK_OK; } } if (obj_ret != NULL) { *obj_ret = NULL; } *version = NULL; return TSK_ERR; } static void yaffscache_object_dump(FILE *fp, YaffsCacheObject *obj) { YaffsCacheVersion *next_version = obj->yco_latest; YaffsCacheChunk *chunk = next_version->ycv_last_chunk; fprintf(fp, "Object %d\n", obj->yco_obj_id); while(chunk != NULL && chunk->ycc_obj_id == obj->yco_obj_id) { if (next_version != NULL && chunk == next_version->ycv_last_chunk) { fprintf(fp, " @%d: %p %p %p\n", next_version->ycv_version, (void*) next_version->ycv_header_chunk, (void*) next_version->ycv_first_chunk, (void*)next_version->ycv_last_chunk); next_version = next_version->ycv_prior; } fprintf(fp, " + %p %08x %08x %0" PRIxOFF "\n", (void*) chunk, chunk->ycc_chunk_id, chunk->ycc_seq_number, chunk->ycc_offset); chunk = chunk->ycc_prev; } } /* static void yaffscache_objects_dump(FILE *fp, YAFFSFS_INFO *yfs) { YaffsCacheObject *obj; for(obj = yfs->cache_objects; obj != NULL; obj = obj->yco_next) yaffscache_object_dump(fp, obj); } */ static void yaffscache_objects_stats(YAFFSFS_INFO *yfs, unsigned int *obj_count, uint32_t *obj_first, uint32_t *obj_last, uint32_t *version_count, uint32_t *version_first, uint32_t *version_last) { YaffsCacheObject *obj; YaffsCacheVersion *ver; /* deleted and unlinked special objects don't have headers */ *obj_count = 2; *obj_first = 0xffffffff; *obj_last = 0; *version_count = 0; *version_first = 0xffffffff; *version_last = 0; for(obj = yfs->cache_objects; obj != NULL; obj = obj->yco_next) { *obj_count += 1; if (obj->yco_obj_id < *obj_first) *obj_first = obj->yco_obj_id; if (obj->yco_obj_id > *obj_last) *obj_last = obj->yco_obj_id; for(ver = obj->yco_latest; ver != NULL; ver = ver->ycv_prior) { *version_count += 1; if (ver->ycv_seq_number < *version_first) *version_first = ver->ycv_seq_number; if (ver->ycv_seq_number > *version_last) *version_last = ver->ycv_seq_number; } } } static void yaffscache_objects_free(YAFFSFS_INFO *yfs) { if((yfs != NULL) && (yfs->cache_objects != NULL)){ YaffsCacheObject *obj = yfs->cache_objects; while(obj != NULL) { YaffsCacheObject *to_free = obj; YaffsCacheVersion *ver = obj->yco_latest; while(ver != NULL) { YaffsCacheVersion *v_to_free = ver; ver = ver->ycv_prior; free(v_to_free); } obj = obj->yco_next; free(to_free); } } } static void yaffscache_chunks_free(YAFFSFS_INFO *yfs) { if((yfs != NULL) && (yfs->chunkMap != NULL)){ // Free the YaffsCacheChunks in each ChunkGroup std::map<unsigned int,YaffsCacheChunkGroup>::iterator iter; for( iter = yfs->chunkMap->begin(); iter != yfs->chunkMap->end(); ++iter ) { YaffsCacheChunk *chunk = yfs->chunkMap->operator[](iter->first).cache_chunks_head; while(chunk != NULL) { YaffsCacheChunk *to_free = chunk; chunk = chunk->ycc_next; free(to_free); } } // Free the map yfs->chunkMap->clear(); delete yfs->chunkMap; } } /* * Parsing and helper functions * * */ /* Function to parse config file * * @param img_info Image info for this image * @param map<string, int> Stores values from config file indexed on parameter name * @returns YAFFS_CONFIG_STATUS One of YAFFS_CONFIG_OK, YAFFS_CONFIG_FILE_NOT_FOUND, or YAFFS_CONFIG_ERROR */ static YAFFS_CONFIG_STATUS yaffs_load_config_file(TSK_IMG_INFO * a_img_info, std::map<std::string, std::string> & results){ size_t config_file_name_len; TSK_TCHAR * config_file_name; FILE* config_file; char buf[1001]; // Ensure there is at least one image name if(a_img_info->num_img < 1){ return YAFFS_CONFIG_ERROR; } // Construct the name of the config file from the first image name config_file_name_len = TSTRLEN(a_img_info->images[0]); config_file_name_len += TSTRLEN(YAFFS_CONFIG_FILE_SUFFIX); config_file_name = (TSK_TCHAR *) tsk_malloc(sizeof(TSK_TCHAR) * (config_file_name_len + 1)); TSTRNCPY(config_file_name, a_img_info->images[0], TSTRLEN(a_img_info->images[0]) + 1); TSTRNCAT(config_file_name, YAFFS_CONFIG_FILE_SUFFIX, TSTRLEN(YAFFS_CONFIG_FILE_SUFFIX) + 1); #ifdef TSK_WIN32 HANDLE hWin; if ((hWin = CreateFile(config_file_name, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0)) == INVALID_HANDLE_VALUE) { // For the moment, assume that the file just doesn't exist, which isn't an error free(config_file_name); return YAFFS_CONFIG_FILE_NOT_FOUND; } config_file = _fdopen(_open_osfhandle((intptr_t) hWin, _O_RDONLY), "r"); if (config_file == NULL) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffs_load_config: Error converting Windows handle to C handle"); free(config_file_name); CloseHandle(hWin); return YAFFS_CONFIG_ERROR; } #else if (NULL == (config_file = fopen(config_file_name, "r"))) { free(config_file_name); return YAFFS_CONFIG_FILE_NOT_FOUND; } #endif while(fgets(buf, 1000, config_file) != NULL){ // Is it a comment? if((buf[0] == '#') || (buf[0] == ';')){ continue; } // Is there a '=' ? if(strchr(buf, '=') == NULL){ continue; } // Copy to strings while removing whitespace and converting to lower case std::string paramName(""); std::string paramVal(""); const char * paramNamePtr = strtok(buf, "="); while(*paramNamePtr != '\0'){ if(! isspace((char)(*paramNamePtr))){ paramName += tolower((char)(*paramNamePtr)); } paramNamePtr++; } const char * paramValPtr = strtok(NULL, "="); while(*paramValPtr != '\0'){ if(! isspace(*paramValPtr)){ paramVal += tolower((char)(*paramValPtr)); } paramValPtr++; } // Make sure this parameter is not already in the map if(results.find(paramName) != results.end()){ // Duplicate parameter - return an error tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffs_load_config: Duplicate parameter name in config file (\"%s\"). %s", paramName.c_str(), YAFFS_HELP_MESSAGE); fclose(config_file); free(config_file_name); return YAFFS_CONFIG_ERROR; } // Add this entry to the map results[paramName] = paramVal; } fclose(config_file); free(config_file_name); return YAFFS_CONFIG_OK; } /* * Helper function for yaffs_validate_config * Tests that a string consists only of digits and has at least one digit * (Can modify later if we want negative fields to be valid) * * @param numStr String to test * @returns 1 on error, 0 on success */ static int yaffs_validate_integer_field(std::string numStr){ unsigned int i; // Test if empty if(numStr.length() == 0){ return 1; } // Test each character for(i = 0;i < numStr.length();i++){ if(isdigit(numStr[i]) == 0){ return 1; } } return 0; } /* * Function to validate the contents of the config file * Currently testing: * All YAFFS_CONFIG fields should be integers (if they exist) * Either need all three of YAFFS_CONFIG_SEQ_NUM_STR, YAFFS_CONFIG_OBJ_ID_STR, YAFFS_CONFIG_CHUNK_ID_STR * or none of them * * @param paramMap Holds mapping of parameter name to parameter value * @returns 1 on error (invalid parameters), 0 on success */ static int yaffs_validate_config_file(std::map<std::string, std::string> & paramMap){ int offset_field_count; // Make a list of all fields to test std::set<std::string> integerParams; integerParams.insert(YAFFS_CONFIG_SEQ_NUM_STR); integerParams.insert(YAFFS_CONFIG_OBJ_ID_STR); integerParams.insert(YAFFS_CONFIG_CHUNK_ID_STR); integerParams.insert(YAFFS_CONFIG_PAGE_SIZE_STR); integerParams.insert(YAFFS_CONFIG_SPARE_SIZE_STR); integerParams.insert(YAFFS_CONFIG_CHUNKS_PER_BLOCK_STR); // If the parameter is set, verify that the value is an int for(std::set<std::string>::iterator it = integerParams.begin();it != integerParams.end();it++){ if((paramMap.find(*it) != paramMap.end()) && (0 != yaffs_validate_integer_field(paramMap[*it]))){ tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffs_validate_config_file: Empty or non-integer value for Yaffs2 parameter \"%s\". %s", (*it).c_str(), YAFFS_HELP_MESSAGE); return 1; } } // Check that we have all three spare offset fields, or none of the three offset_field_count = 0; if(paramMap.find(YAFFS_CONFIG_SEQ_NUM_STR) != paramMap.end()){ offset_field_count++; } if(paramMap.find(YAFFS_CONFIG_OBJ_ID_STR) != paramMap.end()){ offset_field_count++; } if(paramMap.find(YAFFS_CONFIG_CHUNK_ID_STR) != paramMap.end()){ offset_field_count++; } if(! ((offset_field_count == 0) || (offset_field_count == 3))){ tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffs_validate_config_file: Require either all three spare offset fields or none. %s", YAFFS_HELP_MESSAGE); return 1; } // Make sure there aren't any unexpected fields present for(std::map<std::string, std::string>::iterator it = paramMap.begin(); it != paramMap.end();it++){ if(integerParams.find(it->first) == integerParams.end()){ tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffs_validate_config_file: Found unexpected field in config file (\"%s\"). %s", it->first.c_str(), YAFFS_HELP_MESSAGE); return 1; } } return 0; } /* * Function to attempt to determine the layout of the yaffs spare area. * Results of the analysis (if the format could be determined) will be stored * in yfs variables. * * @param yfs File system being analyzed * @param maxBlocksToTest Number of block groups to scan to detect spare area or 0 if there is no limit. * @returns TSK_ERR if format could not be detected and TSK_OK if it could be. */ static TSK_RETVAL_ENUM yaffs_initialize_spare_format(YAFFSFS_INFO * yfs, TSK_OFF_T maxBlocksToTest){ // Testing parameters - can all be changed unsigned int blocksToTest = 10; // Number of blocks (64 chunks) to test unsigned int chunksToTest = 10; // Number of chunks to test in each block unsigned int minChunksRead = 10; // Minimum number of chunks we require to run the test (we might not get the full number we want to test for a very small file) unsigned int chunkSize = yfs->page_size + yfs->spare_size; unsigned int blockSize = yfs->chunks_per_block * chunkSize; TSK_FS_INFO *fs = &(yfs->fs_info); unsigned char *spareBuffer; unsigned int blockIndex; unsigned int chunkIndex; unsigned int currentOffset; unsigned char * allSpares; unsigned int allSparesLength; TSK_OFF_T maxBlocks; bool skipBlock; int goodOffset; unsigned int nGoodSpares; unsigned int nBlocksTested; int okOffsetFound = 0; // Used as a flag for if we've found an offset that sort of works but doesn't seem great int goodOffsetFound = 0; // Flag to mark that we've found an offset that also passed secondary testing int bestOffset = 0; bool allSameByte; // Used in test that the spare area fields not be one repeated byte unsigned int i; int thisChunkBase; int lastChunkBase; // The spare area needs to be at least 16 bytes to run the test if(yfs->spare_size < 16){ if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format failed - given spare size (%d) is not large enough to contain needed fields\n", yfs->spare_size); } return TSK_ERR; } if ((spareBuffer = (unsigned char*) tsk_malloc(yfs->spare_size)) == NULL) { return TSK_ERR; } allSparesLength = yfs->spare_size * blocksToTest * chunksToTest; if ((allSpares = (unsigned char*) tsk_malloc(allSparesLength)) == NULL) { free(spareBuffer); return TSK_ERR; } // Initialize the pointers to one of the configurations we've seen (thought these defaults should not get used) yfs->spare_seq_offset = 0; yfs->spare_obj_id_offset = 4; yfs->spare_chunk_id_offset = 8; yfs->spare_nbytes_offset = 12; // Assume the data we want is 16 consecutive bytes in the order: // seq num, obj id, chunk id, byte count // (not sure we're guaranteed this but we wouldn't be able to deal with the alternative anyway) // Seq num is the important one. This number is constant in each block (block = 64 chunks), meaning // all chunks in a block will share the same sequence number. The YAFFS2 descriptions would seem to // indicate it should be different for each block, but this doesn't seem to always be the case. // In particular we frequently see the 0x1000 seq number used over multiple blocks, but this isn't the only // observed exception. // Calculate the number of blocks in the image maxBlocks = yfs->fs_info.img_info->size / (yfs->chunks_per_block * chunkSize); // If maxBlocksToTest = 0 (unlimited), set it to the total number of blocks // Also reduce the number of blocks to test if it is larger than the total number of blocks if ((maxBlocksToTest == 0) || (maxBlocksToTest > maxBlocks)){ maxBlocksToTest = maxBlocks; } nGoodSpares = 0; nBlocksTested = 0; for (TSK_OFF_T blockIndex = 0;blockIndex < maxBlocksToTest;blockIndex++){ // Read the last spare area that we want to test first TSK_OFF_T offset = (TSK_OFF_T)blockIndex * blockSize + (chunksToTest - 1) * chunkSize + yfs->page_size; ssize_t cnt = tsk_img_read(fs->img_info, offset, (char *) spareBuffer, yfs->spare_size); if ((cnt < 0) || ((unsigned int)cnt < yfs->spare_size)) { break; } // Is the spare all 0xff / 0x00? // If not, we know we should have all allocated chunks since YAFFS2 writes sequentially in a block // - can't have an unallocated chunk followed by an allocated one // We occasionally see almost all null spare area with a few 0xff, which is not a valid spare. skipBlock = true; for (i = 0;i < yfs->spare_size;i++){ if((spareBuffer[i] != 0xff) && (spareBuffer[i] != 0x00)){ skipBlock = false; break; } } if (skipBlock){ continue; } // If this block is potentialy valid (i.e., the spare contains something besides 0x00 and 0xff), copy all the spares into // the big array of extracted spare areas // Copy this spare area nGoodSpares++; for (i = 0;i < yfs->spare_size;i++){ allSpares[nBlocksTested * yfs->spare_size * chunksToTest + (chunksToTest - 1) * yfs->spare_size + i] = spareBuffer[i]; } // Copy all earlier spare areas in the block for (chunkIndex = 0;chunkIndex < chunksToTest - 1;chunkIndex++){ offset = blockIndex * blockSize + chunkIndex * chunkSize + yfs->page_size; cnt = tsk_img_read(fs->img_info, offset, (char *) spareBuffer, yfs->spare_size); if ((cnt < 0) || ((unsigned int)cnt < yfs->spare_size)) { // We really shouldn't run out of data here since we already read in the furthest entry break; // Break out of chunksToTest loop } nGoodSpares++; for(i = 0;i < yfs->spare_size;i++){ allSpares[nBlocksTested * yfs->spare_size * chunksToTest + chunkIndex * yfs->spare_size + i] = spareBuffer[i]; } } // Record that we've found a potentially valid block nBlocksTested++; // If we've found enough potentailly valid blocks, break if (nBlocksTested >= blocksToTest){ break; } } // Make sure we read enough data to reasonably perform the testing if (nGoodSpares < minChunksRead){ if (tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format failed - not enough potentially valid data could be read\n"); } free(spareBuffer); free(allSpares); return TSK_ERR; } if (tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Testing potential offsets for the sequence number in the spare area\n"); } // Print out the collected spare areas if we're in verbose mode if(tsk_verbose && (! yfs->autoDetect)){ for(blockIndex = 0;blockIndex < nBlocksTested;blockIndex++){ for(chunkIndex = 0;chunkIndex < chunksToTest;chunkIndex++){ for(i = 0;i < yfs->spare_size;i++){ fprintf(stderr, "%02x", allSpares[blockIndex * yfs->spare_size * chunksToTest + chunkIndex * yfs->spare_size + i]); } fprintf(stderr, "\n"); } } } // Test all indices into the spare area (that leave enough space for all 16 bytes) for(currentOffset = 0;currentOffset <= yfs->spare_size - 16;currentOffset++){ goodOffset = 1; for(blockIndex = 0;blockIndex < nBlocksTested;blockIndex++){ for(chunkIndex = 1;chunkIndex < chunksToTest;chunkIndex++){ lastChunkBase = blockIndex * yfs->spare_size * chunksToTest + (chunkIndex - 1) * yfs->spare_size; thisChunkBase = lastChunkBase + yfs->spare_size; // Seq num should not be all 0xff (we tested earlier that the chunk has been initialized) if((0xff == allSpares[thisChunkBase + currentOffset]) && (0xff == allSpares[thisChunkBase + currentOffset + 1]) && (0xff == allSpares[thisChunkBase + currentOffset + 2]) && (0xff == allSpares[thisChunkBase + currentOffset + 3])){ if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Eliminating offset %d - invalid sequence number 0xffffffff\n", currentOffset); } goodOffset = 0; break; } // Seq num should not be zero if((0 == allSpares[thisChunkBase + currentOffset]) && (0 == allSpares[thisChunkBase + currentOffset + 1]) && (0 == allSpares[thisChunkBase + currentOffset + 2]) && (0 == allSpares[thisChunkBase + currentOffset + 3])){ if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Eliminating offset %d - invalid sequence number 0\n", currentOffset); } goodOffset = 0; break; } // Seq num should match the previous one in the block if((allSpares[lastChunkBase + currentOffset] != allSpares[thisChunkBase + currentOffset]) || (allSpares[lastChunkBase + currentOffset + 1] != allSpares[thisChunkBase + currentOffset + 1]) || (allSpares[lastChunkBase + currentOffset + 2] != allSpares[thisChunkBase + currentOffset + 2]) || (allSpares[lastChunkBase + currentOffset + 3] != allSpares[thisChunkBase + currentOffset + 3])){ if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Eliminating offset %d - did not match previous chunk sequence number\n", currentOffset); } goodOffset = 0; break; } // Obj id should not be zero if((0 == allSpares[thisChunkBase + currentOffset + 4]) && (0 == allSpares[thisChunkBase + currentOffset + 5]) && (0 == allSpares[thisChunkBase + currentOffset + 6]) && (0 == allSpares[thisChunkBase + currentOffset + 7])){ if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Eliminating offset %d - invalid object id 0\n", currentOffset); } goodOffset = 0; break; } // All 16 bytes should not be the same // (It is theoretically possible that this could be valid, but incredibly unlikely) allSameByte = true; for(i = 1;i < 16;i++){ if(allSpares[thisChunkBase + currentOffset] != allSpares[thisChunkBase + currentOffset + i]){ allSameByte = false; break; } } if(allSameByte){ if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Eliminating offset %d - all repeated bytes\n", currentOffset); } goodOffset = 0; break; } } // End of loop over chunks if(!goodOffset){ // Break out of loop over blocks break; } } if(goodOffset){ // Note that we've found an offset that is at least promising if((! goodOffsetFound) && (! okOffsetFound)){ bestOffset = currentOffset; } okOffsetFound = 1; if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Found potential spare offsets: %d (sequence number), %d (object id), %d (chunk id), %d (n bytes)\n", currentOffset, currentOffset+4, currentOffset+8, currentOffset+12); } // Now do some more tests // Really need some more real-world test data to do this right. int possibleError = 0; // We probably don't want the first byte to always be 0xff int firstByteFF = 1; for(blockIndex = 0;blockIndex < nBlocksTested;blockIndex++){ for(chunkIndex = 1;chunkIndex < chunksToTest;chunkIndex++){ if(allSpares[blockIndex * yfs->spare_size * chunksToTest + chunkIndex * yfs->spare_size + currentOffset] != 0xff){ firstByteFF = 0; } } } if(firstByteFF){ if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Previous data starts with all 0xff bytes. Looking for better offsets.\n"); } possibleError = 1; } if(! possibleError){ // If we already have a good offset, print this one out but don't record it if(! goodOffsetFound){ goodOffsetFound = 1; bestOffset = currentOffset; // Offset passed additional testing and we haven't seen an earlier good one, so go ahead and use it if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Previous offsets appear good - will use as final offsets\n"); } } else{ // Keep using the old one if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Previous offsets appear good but staying with earlier valid ones\n"); } } } } } free(spareBuffer); free(allSpares); if(okOffsetFound || goodOffsetFound){ // Record everything yfs->spare_seq_offset = bestOffset; yfs->spare_obj_id_offset = bestOffset + 4; yfs->spare_chunk_id_offset = bestOffset + 8; yfs->spare_nbytes_offset = bestOffset + 12; if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Final offsets: %d (sequence number), %d (object id), %d (chunk id), %d (n bytes)\n", bestOffset, bestOffset+4, bestOffset+8, bestOffset+12); tsk_fprintf(stderr, "If these do not seem valid: %s\n", YAFFS_HELP_MESSAGE); } return TSK_OK; } else{ return TSK_ERR; } } /** * yaffsfs_read_header( ... ) * */ static uint8_t yaffsfs_read_header(YAFFSFS_INFO *yfs, YaffsHeader ** header, TSK_OFF_T offset) { unsigned char *hdr; ssize_t cnt; YaffsHeader *head; TSK_FS_INFO *fs = &(yfs->fs_info); if ((hdr = (unsigned char*) tsk_malloc(yfs->page_size)) == NULL) { return 1; } cnt = tsk_img_read(fs->img_info, offset, (char *) hdr, yfs->page_size); if ((cnt < 0) || ((unsigned int)cnt < yfs->page_size)) { free(hdr); return 1; } if ((head = (YaffsHeader*) tsk_malloc( sizeof(YaffsHeader))) == NULL) { free(hdr); return 1; } memcpy(&head->obj_type, hdr, 4); memcpy(&head->parent_id, &hdr[4], 4); memcpy(head->name, (char*) &hdr[0xA], YAFFS_HEADER_NAME_LENGTH); memcpy(&head->file_mode, &hdr[0x10C], 4); memcpy(&head->user_id, &hdr[0x110], 4); memcpy(&head->group_id, &hdr[0x114], 4); memcpy(&head->atime, &hdr[0x118], 4); memcpy(&head->mtime, &hdr[0x11C], 4); memcpy(&head->ctime, &hdr[0x120], 4); memcpy(&head->file_size, &hdr[0x124], 4); memcpy(&head->equivalent_id, &hdr[0x128], 4); memcpy(head->alias, (char*) &hdr[0x12C], YAFFS_HEADER_ALIAS_LENGTH); //memcpy(&head->rdev_mode, &hdr[0x1CC], 4); //memcpy(&head->win_ctime, &hdr[0x1D0], 8); //memcpy(&head->win_atime, &hdr[0x1D8], 8); //memcpy(&head->win_mtime, &hdr[0x1E0], 8); //memcpy(&head->inband_obj_id, &hdr[0x1E8], 4); //memcpy(&head->inband_is_shrink, &hdr[0x1EC], 4); // NOTE: This isn't in Android 3.3 kernel but is in YAFFS2 git //memcpy(&head->file_size_high, &hdr[0x1F0], 4); free(hdr); *header = head; return 0; } /** * Read and parse the YAFFS2 tags in the NAND spare bytes. * * @param info is a YAFFS fs handle * @param spare YaffsSpare object to be populated * @param offset, offset to read from * * @returns 0 on success and 1 on error */ static uint8_t yaffsfs_read_spare(YAFFSFS_INFO *yfs, YaffsSpare ** spare, TSK_OFF_T offset) { unsigned char *spr; ssize_t cnt; YaffsSpare *sp; TSK_FS_INFO *fs = &(yfs->fs_info); uint32_t seq_number; uint32_t object_id; uint32_t chunk_id; // Should have checked this by now, but just in case if((yfs->spare_seq_offset + 4 > yfs->spare_size) || (yfs->spare_obj_id_offset + 4 > yfs->spare_size) || (yfs->spare_chunk_id_offset + 4 > yfs->spare_size)){ return 1; } if ((spr = (unsigned char*) tsk_malloc(yfs->spare_size)) == NULL) { return 1; } if (yfs->spare_size < 46) { // Why is this 46? tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr("yaffsfs_read_spare: spare size is too small"); free(spr); return 1; } cnt = tsk_img_read(fs->img_info, offset, (char*) spr, yfs->spare_size); if ((cnt < 0) || ((unsigned int)cnt < yfs->spare_size)) { // couldn't read sufficient bytes... if (spare) { free(spr); *spare = NULL; } return 1; } if ((sp = (YaffsSpare*) tsk_malloc(sizeof(YaffsSpare))) == NULL) { return 1; } memset(sp, 0, sizeof(YaffsSpare)); /* * Complete read of the YAFFS2 spare */ // The format of the spare area should have been determined earlier memcpy(&seq_number, &spr[yfs->spare_seq_offset], 4); memcpy(&object_id, &spr[yfs->spare_obj_id_offset], 4); memcpy(&chunk_id, &spr[yfs->spare_chunk_id_offset], 4); if ((YAFFS_SPARE_FLAGS_IS_HEADER & chunk_id) != 0) { sp->seq_number = seq_number; sp->object_id = object_id & ~YAFFS_SPARE_OBJECT_TYPE_MASK; sp->chunk_id = 0; sp->has_extra_fields = 1; sp->extra_parent_id = chunk_id & YAFFS_SPARE_PARENT_ID_MASK; sp->extra_object_type = (object_id & YAFFS_SPARE_OBJECT_TYPE_MASK) >> YAFFS_SPARE_OBJECT_TYPE_SHIFT; } else { sp->seq_number = seq_number; sp->object_id = object_id; sp->chunk_id = chunk_id; sp->has_extra_fields = 0; } free(spr); *spare = sp; return 0; } static uint8_t yaffsfs_is_spare_valid(YAFFSFS_INFO * /*yfs*/, YaffsSpare *spare) { if (spare == NULL) { return 1; } if ((spare->object_id > YAFFS_MAX_OBJECT_ID) || (spare->seq_number < YAFFS_LOWEST_SEQUENCE_NUMBER) || (spare->seq_number > YAFFS_HIGHEST_SEQUENCE_NUMBER)) { return 1; } return 0; } static uint8_t yaffsfs_read_chunk(YAFFSFS_INFO *yfs, YaffsHeader **header, YaffsSpare **spare, TSK_OFF_T offset) { TSK_OFF_T header_offset = offset; TSK_OFF_T spare_offset = offset + yfs->page_size; if (header == NULL || spare == NULL) { return 1; } if (yaffsfs_read_header(yfs, header, header_offset) != 0) { return 1; } if (yaffsfs_read_spare(yfs, spare, spare_offset) != 0) { free(*header); *header = NULL; return 1; } return 0; } /** * Cycle through the entire image and populate the cache with objects as they are found. */ static uint8_t yaffsfs_parse_image_load_cache(YAFFSFS_INFO * yfs) { uint8_t status = TSK_OK; uint32_t nentries = 0; YaffsSpare *spare = NULL; uint8_t tempBuf[8]; uint32_t parentID; if (yfs->cache_objects) return 0; for(TSK_OFF_T offset = 0;offset < yfs->fs_info.img_info->size;offset += yfs->page_size + yfs->spare_size){ status = yaffsfs_read_spare( yfs, &spare, offset + yfs->page_size); if (status != TSK_OK) { break; } if (yaffsfs_is_spare_valid(yfs, spare) == TSK_OK) { if((spare->has_extra_fields) || (spare->chunk_id != 0)){ yaffscache_chunk_add(yfs, offset, spare->seq_number, spare->object_id, spare->chunk_id, spare->extra_parent_id); } else{ // If we have a header block and didn't extract it already from the spare, get the parent ID from // the non-spare data if(8 == tsk_img_read(yfs->fs_info.img_info, offset, (char*) tempBuf, 8)){ memcpy(&parentID, &tempBuf[4], 4); yaffscache_chunk_add(yfs, offset, spare->seq_number, spare->object_id, spare->chunk_id, parentID); } else{ // Really shouldn't happen fprintf(stderr, "Error reading header to get parent id at offset %" PRIxOFF "\n", offset); yaffscache_chunk_add(yfs, offset, spare->seq_number, spare->object_id, spare->chunk_id, 0); } } } free(spare); spare = NULL; ++nentries; } if (tsk_verbose) fprintf(stderr, "yaffsfs_parse_image_load_cache: read %d entries\n", nentries); if (tsk_verbose) fprintf(stderr, "yaffsfs_parse_image_load_cache: started processing chunks for version cache...\n"); fflush(stderr); // At this point, we have a list of chunks sorted by obj id, seq number, and offset // This makes the list of objects in cache_objects, which link to different versions yaffscache_versions_compute(yfs); if (tsk_verbose) fprintf(stderr, "yaffsfs_parse_image_load_cache: done version cache!\n"); fflush(stderr); // Having multiple inodes point to the same object seems to cause trouble in TSK, especially in orphan file detection, // so set the version number of the final one to zero. // While we're at it, find the highest obj_id and the highest version (before resetting to zero) YaffsCacheObject * currObj = yfs->cache_objects; YaffsCacheVersion * currVer; while(currObj != NULL){ if(currObj->yco_obj_id > yfs->max_obj_id){ yfs->max_obj_id = currObj->yco_obj_id; } currVer = currObj->yco_latest; if(currVer->ycv_version > yfs->max_version){ yfs->max_version = currVer->ycv_version; } currVer->ycv_version = 0; currObj = currObj->yco_next; } // Use the max object id and version number to construct an upper bound on the inode TSK_INUM_T max_inum = 0; if (TSK_OK != yaffscache_obj_id_and_version_to_inode(yfs->max_obj_id, yfs->max_version, &max_inum)) { return TSK_ERR; } yfs->fs_info.last_inum = max_inum + 1; // One more for the orphan dir // Make sure the orphan dir is greater than the root dir if (yfs->fs_info.last_inum <= yfs->fs_info.root_inum) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffsfs_parse_image_load_cache: Maximum inum %" PRIuINUM " is not greater than the root inum", yfs->fs_info.last_inum); return TSK_ERR; } return TSK_OK; } // A version is allocated if: // 1. This version is pointed to by yco_latest // 2. This version didn't have a delete/unlinked header after the most recent copy of the normal header static uint8_t yaffs_is_version_allocated(YAFFSFS_INFO * yfs, TSK_INUM_T inode){ YaffsCacheObject * obj; YaffsCacheVersion * version; YaffsCacheChunk * curr; TSK_RETVAL_ENUM result = yaffscache_version_find_by_inode(yfs, inode, &version, &obj); if (result != TSK_OK) { if (tsk_verbose) tsk_fprintf(stderr, "yaffs_is_version_allocated: yaffscache_version_find_by_inode failed! (inode: %d)\n", inode); return 0; } if(obj->yco_latest == version){ curr = obj->yco_latest->ycv_header_chunk; while(curr != NULL){ // We're looking for a newer unlinked or deleted header. If one exists, then this object should be considered unallocated if((curr->ycc_parent_id == YAFFS_OBJECT_UNLINKED) || (curr->ycc_parent_id == YAFFS_OBJECT_DELETED)){ return 0; } curr = curr ->ycc_next; } return 1; } else{ return 0; } } /* * TSK integration * * */ static uint8_t yaffs_make_directory(YAFFSFS_INFO *yaffsfs, TSK_FS_FILE *a_fs_file, TSK_INUM_T inode, const char *name) { TSK_FS_FILE *fs_file = a_fs_file; fs_file->meta->type = TSK_FS_META_TYPE_DIR; fs_file->meta->mode = (TSK_FS_META_MODE_ENUM)0; fs_file->meta->nlink = 1; if((inode == YAFFS_OBJECT_UNLINKED) || (inode == YAFFS_OBJECT_DELETED) || (inode == yaffsfs->fs_info.last_inum)){ fs_file->meta->flags = (TSK_FS_META_FLAG_ENUM)(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_ALLOC); } else{ if(yaffs_is_version_allocated(yaffsfs, inode)){ fs_file->meta->flags = (TSK_FS_META_FLAG_ENUM)(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_ALLOC); } else{ fs_file->meta->flags = (TSK_FS_META_FLAG_ENUM)(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_UNALLOC); } } fs_file->meta->uid = fs_file->meta->gid = 0; fs_file->meta->mtime = fs_file->meta->atime = fs_file->meta->ctime = fs_file->meta->crtime = 0; fs_file->meta->mtime_nano = fs_file->meta->atime_nano = fs_file->meta->ctime_nano = fs_file->meta->crtime_nano = 0; if (fs_file->meta->name2 == NULL) { if ((fs_file->meta->name2 = (TSK_FS_META_NAME_LIST *) tsk_malloc(sizeof(TSK_FS_META_NAME_LIST))) == NULL) { return 1; } fs_file->meta->name2->next = NULL; } if (fs_file->meta->attr != NULL) { tsk_fs_attrlist_markunused(fs_file->meta->attr); } else { fs_file->meta->attr = tsk_fs_attrlist_alloc(); } strncpy(fs_file->meta->name2->name, name, TSK_FS_META_NAME_LIST_NSIZE); fs_file->meta->size = 0; fs_file->meta->attr_state = TSK_FS_META_ATTR_EMPTY; fs_file->meta->addr = inode; return 0; } static uint8_t yaffs_make_regularfile( YAFFSFS_INFO * yaffsfs, TSK_FS_FILE * a_fs_file, TSK_INUM_T inode, const char * name ) { TSK_FS_FILE *fs_file = a_fs_file; fs_file->meta->type = TSK_FS_META_TYPE_REG; fs_file->meta->mode = (TSK_FS_META_MODE_ENUM)0; fs_file->meta->nlink =1; if(yaffs_is_version_allocated(yaffsfs, inode)){ fs_file->meta->flags = (TSK_FS_META_FLAG_ENUM)(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_ALLOC); } else{ fs_file->meta->flags = (TSK_FS_META_FLAG_ENUM)(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_UNALLOC); } fs_file->meta->uid = fs_file->meta->gid = 0; fs_file->meta->mtime = fs_file->meta->atime = fs_file->meta->ctime = fs_file->meta->crtime = 0; fs_file->meta->mtime_nano = fs_file->meta->atime_nano = fs_file->meta->ctime_nano = fs_file->meta->crtime_nano = 0; if (fs_file->meta->name2 == NULL) { if ((fs_file->meta->name2 = (TSK_FS_META_NAME_LIST *) tsk_malloc(sizeof(TSK_FS_META_NAME_LIST))) == NULL) return 1; fs_file->meta->name2->next = NULL; } if (fs_file->meta->attr != NULL) { tsk_fs_attrlist_markunused(fs_file->meta->attr); } else { fs_file->meta->attr = tsk_fs_attrlist_alloc(); } fs_file->meta->addr = inode; strncpy(fs_file->meta->name2->name, name, TSK_FS_META_NAME_LIST_NSIZE); fs_file->meta->size = 0; fs_file->meta->attr_state = TSK_FS_META_ATTR_EMPTY; return 0; } /** * \internal * Create YAFFS2 Deleted Object * * @ param yaffs file system * fs_file to copy file information to * return 1 on error, 0 on success */ static uint8_t yaffs_make_deleted( YAFFSFS_INFO * yaffsfs, TSK_FS_FILE * a_fs_file ) { TSK_FS_FILE *fs_file = a_fs_file; if (tsk_verbose) tsk_fprintf(stderr, "yaffs_make_deleted: Making virtual deleted node\n"); if (yaffs_make_directory(yaffsfs, fs_file, YAFFS_OBJECT_DELETED, YAFFS_OBJECT_DELETED_NAME)) return 1; return 0; } /** * \internal * Create YAFFS2 Unlinked object * * @ param yaffs file system * fs_file to copy file information to * return 1 on error, 0 on success */ static uint8_t yaffs_make_unlinked( YAFFSFS_INFO * yaffsfs, TSK_FS_FILE * a_fs_file ) { TSK_FS_FILE * fs_file = a_fs_file; if (tsk_verbose) tsk_fprintf(stderr, "yaffs_make_unlinked: Making virtual unlinked node\n"); if (yaffs_make_directory(yaffsfs, fs_file, YAFFS_OBJECT_UNLINKED, YAFFS_OBJECT_UNLINKED_NAME)) return 1; return 0; } /** * \internal * Create YAFFS2 orphan object * * @ param yaffs file system * fs_file to copy file information to * return 1 on error, 0 on success */ static uint8_t yaffs_make_orphan_dir( YAFFSFS_INFO * yaffsfs, TSK_FS_FILE * a_fs_file ) { TSK_FS_FILE * fs_file = a_fs_file; TSK_FS_NAME *fs_name = tsk_fs_name_alloc(256, 0); if (fs_name == NULL) return TSK_ERR; if (tsk_verbose) tsk_fprintf(stderr, "yaffs_make_orphan_dir: Making orphan dir node\n"); if (tsk_fs_dir_make_orphan_dir_name(&(yaffsfs->fs_info), fs_name)) { tsk_fs_name_free(fs_name); return TSK_ERR; } if (yaffs_make_directory(yaffsfs, fs_file, yaffsfs->fs_info.last_inum, (char *)fs_name)){ tsk_fs_name_free(fs_name); return 1; } tsk_fs_name_free(fs_name); return 0; } /* yaffsfs_inode_lookup - lookup inode, external interface * * Returns 1 on error and 0 on success * */ static uint8_t yaffs_inode_lookup(TSK_FS_INFO *a_fs, TSK_FS_FILE * a_fs_file, TSK_INUM_T inum) { YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)a_fs; YaffsCacheObject *obj; YaffsCacheVersion *version; YaffsHeader *header = NULL; YaffsSpare *spare = NULL; TSK_RETVAL_ENUM result; uint8_t type; const char *real_name; if (a_fs_file == NULL) { tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr("yaffsfs_inode_lookup: fs_file is NULL"); return 1; } if (a_fs_file->meta == NULL) { if ((a_fs_file->meta = tsk_fs_meta_alloc(YAFFS_FILE_CONTENT_LEN)) == NULL) return 1; } else { tsk_fs_meta_reset(a_fs_file->meta); } if (tsk_verbose) tsk_fprintf(stderr, "yaffs_inode_lookup: looking up %" PRIuINUM "\n",inum); switch(inum) { case YAFFS_OBJECT_UNLINKED: yaffs_make_unlinked(yfs, a_fs_file); return 0; case YAFFS_OBJECT_DELETED: yaffs_make_deleted(yfs, a_fs_file); return 0; } if(inum == yfs->fs_info.last_inum){ yaffs_make_orphan_dir(yfs, a_fs_file); return 0; } result = yaffscache_version_find_by_inode(yfs, inum, &version, &obj); if (result != TSK_OK) { if (tsk_verbose) tsk_fprintf(stderr, "yaffs_inode_lookup: yaffscache_version_find_by_inode failed! (inode = %d)\n", inum); return 1; } if(version->ycv_header_chunk == NULL){ return 1; } if (yaffsfs_read_chunk(yfs, &header, &spare, version->ycv_header_chunk->ycc_offset) != TSK_OK) { if (tsk_verbose) tsk_fprintf(stderr, "yaffs_inode_lookup: yaffsfs_read_chunk failed!\n"); return 1; } type = header->obj_type; switch(inum) { case YAFFS_OBJECT_LOSTNFOUND: real_name = YAFFS_OBJECT_LOSTNFOUND_NAME; break; case YAFFS_OBJECT_UNLINKED: real_name = YAFFS_OBJECT_UNLINKED_NAME; break; case YAFFS_OBJECT_DELETED: real_name = YAFFS_OBJECT_DELETED_NAME; break; default: real_name = header->name; break; } switch(type) { case YAFFS_TYPE_FILE: if (tsk_verbose) tsk_fprintf(stderr, "yaffs_inode_lookup: is a file\n"); yaffs_make_regularfile(yfs, a_fs_file, inum, real_name); break; case YAFFS_TYPE_DIRECTORY: if (tsk_verbose) tsk_fprintf(stderr, "yaffs_inode_lookup: is a directory\n"); yaffs_make_directory(yfs, a_fs_file, inum, real_name); break; case YAFFS_TYPE_SOFTLINK: if (tsk_verbose) tsk_fprintf(stderr, "yaffs_inode_lookup: is a symbolic link\n"); yaffs_make_regularfile(yfs, a_fs_file, inum, real_name); a_fs_file->meta->type = TSK_FS_META_TYPE_LNK; break; case YAFFS_TYPE_HARDLINK: case YAFFS_TYPE_UNKNOWN: default: if (tsk_verbose) tsk_fprintf(stderr, "yaffs_inode_lookup: is *** UNHANDLED *** (type %d, header at 0x%x)\n", type, version->ycv_header_chunk->ycc_offset); // We can still set a few things a_fs_file->meta->type = TSK_FS_META_TYPE_UNDEF; a_fs_file->meta->addr = inum; if(yaffs_is_version_allocated(yfs, inum)){ a_fs_file->meta->flags = (TSK_FS_META_FLAG_ENUM)(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_ALLOC); } else{ a_fs_file->meta->flags = (TSK_FS_META_FLAG_ENUM)(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_UNALLOC); } if (a_fs_file->meta->name2 == NULL) { if ((a_fs_file->meta->name2 = (TSK_FS_META_NAME_LIST *) tsk_malloc(sizeof(TSK_FS_META_NAME_LIST))) == NULL){ return 1; } a_fs_file->meta->name2->next = NULL; } strncpy(a_fs_file->meta->name2->name, real_name, TSK_FS_META_NAME_LIST_NSIZE); break; } /* Who owns this? I'm following the way FATFS does it by freeing + NULLing * this and mallocing if used. */ free(a_fs_file->meta->link); a_fs_file->meta->link = NULL; if (type != YAFFS_TYPE_HARDLINK) { a_fs_file->meta->mode = (TSK_FS_META_MODE_ENUM)(header->file_mode & TWELVE_BITS_MASK); // chop at 12 bits; a_fs_file->meta->uid = header->user_id; a_fs_file->meta->gid = header->group_id; a_fs_file->meta->mtime = header->mtime; a_fs_file->meta->atime = header->atime; a_fs_file->meta->ctime = header->ctime; } if (type == YAFFS_TYPE_FILE) { a_fs_file->meta->size = header->file_size; // NOTE: This isn't in Android 3.3 kernel but is in YAFFS2 git //a_fs_file->meta->size |= ((TSK_OFF_T) header->file_size_high) << 32; } if (type == YAFFS_TYPE_HARDLINK) { // TODO: Store equivalent_id somewhere? */ } if (type == YAFFS_TYPE_SOFTLINK) { a_fs_file->meta->link = (char*)tsk_malloc(YAFFS_HEADER_ALIAS_LENGTH); if (a_fs_file->meta->link == NULL) { free(header); free(spare); return 1; } memcpy(a_fs_file->meta->link, header->alias, YAFFS_HEADER_ALIAS_LENGTH); } free(header); free(spare); return 0; } /* yaffsfs_inode_walk - inode iterator * * flags used: TSK_FS_META_FLAG_USED, TSK_FS_META_FLAG_UNUSED, * TSK_FS_META_FLAG_ALLOC, TSK_FS_META_FLAG_UNALLOC, TSK_FS_META_FLAG_ORPHAN * * Return 1 on error and 0 on success */ static uint8_t yaffsfs_inode_walk(TSK_FS_INFO *fs, TSK_INUM_T start_inum, TSK_INUM_T end_inum, TSK_FS_META_FLAG_ENUM flags, TSK_FS_META_WALK_CB a_action, void *a_ptr) { YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)fs; TSK_FS_FILE *fs_file; TSK_RETVAL_ENUM result; uint32_t start_obj_id; uint32_t start_ver_number; uint32_t end_obj_id; uint32_t end_ver_number; uint32_t obj_id; YaffsCacheObject *curr_obj; YaffsCacheVersion *curr_version; result = yaffscache_inode_to_obj_id_and_version(start_inum, &start_obj_id, &start_ver_number); result = yaffscache_inode_to_obj_id_and_version(end_inum, &end_obj_id, &end_ver_number); if (end_obj_id < start_obj_id) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_WALK_RNG); tsk_error_set_errstr("yaffsfs_inode_walk: end object id must be >= start object id: " "%" PRIx32 " must be >= %" PRIx32 "", end_obj_id, start_obj_id); return 1; } /* The ORPHAN flag is unsupported for YAFFS2 */ if (flags & TSK_FS_META_FLAG_ORPHAN) { if (tsk_verbose){ tsk_fprintf(stderr, "yaffsfs_inode_walk: ORPHAN flag unsupported by YAFFS2"); } } if (((flags & TSK_FS_META_FLAG_ALLOC) == 0) && ((flags & TSK_FS_META_FLAG_UNALLOC) == 0)) { flags = (TSK_FS_META_FLAG_ENUM)(flags | TSK_FS_META_FLAG_ALLOC | TSK_FS_META_FLAG_UNALLOC); } /* If neither of the USED or UNUSED flags are set, then set them * both */ if (((flags & TSK_FS_META_FLAG_USED) == 0) && ((flags & TSK_FS_META_FLAG_UNUSED) == 0)) { flags = (TSK_FS_META_FLAG_ENUM)(flags | TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_UNUSED); } if ((fs_file = tsk_fs_file_alloc(fs)) == NULL) return 1; if ((fs_file->meta = tsk_fs_meta_alloc(YAFFS_FILE_CONTENT_LEN)) == NULL) return 1; for (obj_id = start_obj_id; obj_id <= end_obj_id; obj_id++) { int retval; result = yaffscache_version_find_by_inode(yfs, obj_id, &curr_version, &curr_obj); if (result == TSK_OK) { TSK_INUM_T curr_inode; YaffsCacheVersion *version; // ALLOC, UNALLOC, or both are set at this point if (flags & TSK_FS_META_FLAG_ALLOC) { // Allocated only - just look at current version if (yaffscache_obj_id_and_version_to_inode(obj_id, curr_obj->yco_latest->ycv_version, &curr_inode) != TSK_OK) { tsk_fs_file_close(fs_file); return 1; } // It's possible for the current version to be unallocated if the last header was a deleted or unlinked header if(yaffs_is_version_allocated(yfs, curr_inode)){ if (yaffs_inode_lookup(fs, fs_file, curr_inode) != TSK_OK) { tsk_fs_file_close(fs_file); return 1; } retval = a_action(fs_file, a_ptr); if (retval == TSK_WALK_STOP) { tsk_fs_file_close(fs_file); return 0; } else if (retval == TSK_WALK_ERROR) { tsk_fs_file_close(fs_file); return 1; } } } if (flags & TSK_FS_META_FLAG_UNALLOC){ for (version = curr_obj->yco_latest; version != NULL; version = version->ycv_prior) { if (yaffscache_obj_id_and_version_to_inode(obj_id, version->ycv_version, &curr_inode) != TSK_OK) { tsk_fs_file_close(fs_file); return 1; } if(! yaffs_is_version_allocated(yfs, curr_inode)){ if (yaffs_inode_lookup(fs, fs_file, curr_inode) != TSK_OK) { tsk_fs_file_close(fs_file); return 1; } retval = a_action(fs_file, a_ptr); if (retval == TSK_WALK_STOP) { tsk_fs_file_close(fs_file); return 0; } else if (retval == TSK_WALK_ERROR) { tsk_fs_file_close(fs_file); return 1; } } } } curr_obj = curr_obj->yco_next; } } /* * Cleanup. */ tsk_fs_file_close(fs_file); return 0; } static TSK_FS_BLOCK_FLAG_ENUM yaffsfs_block_getflags(TSK_FS_INFO *fs, TSK_DADDR_T a_addr) { YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)fs; TSK_FS_BLOCK_FLAG_ENUM flags = TSK_FS_BLOCK_FLAG_UNUSED; TSK_OFF_T offset = (a_addr * (fs->block_pre_size + fs->block_size + fs->block_post_size)) + yfs->page_size; YaffsSpare *spare = NULL; YaffsHeader *header = NULL; if (yaffsfs_read_spare(yfs, &spare, offset) != TSK_OK) { /* NOTE: Uh, how do we signal error? */ return flags; } if (yaffsfs_is_spare_valid(yfs, spare) == TSK_OK) { /* XXX: Do we count blocks of older versions unallocated? * If so, we need a smarter way to do this :/ * * Walk the object from this block and see if this * block is used in the latest version. Could pre- * calculate this at cache time as well. */ if (spare->chunk_id == 0) { flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_META); } else { flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_CONT); } // Have obj id and offset // 1. Is the current version of this object allocated? // 2. If this is a header, is it the header of the current version? // 3. Is the chunk id too big given the current header? // 4. Is there a more recent version of this chunk id? YaffsCacheObject * obj = NULL; yaffscache_object_find(yfs, spare->object_id, &obj); // The result really shouldn't be NULL since we loaded every chunk if(obj != NULL){ if(! yaffs_is_version_allocated(yfs, spare->object_id)){ // If the current version isn't allocated, then no chunks in it are flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_UNALLOC); } else if (obj->yco_latest == NULL || obj->yco_latest->ycv_header_chunk == NULL) { flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_UNALLOC); } else if(spare->chunk_id == 0){ if(obj->yco_latest->ycv_header_chunk->ycc_offset == offset - yfs->page_size){ // Have header chunk and it's the most recent header chunk flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_ALLOC); } else{ // Have header chunk but isn't the most recent flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_UNALLOC); } } else{ // Read in the full header yaffsfs_read_header(yfs, &header, obj->yco_latest->ycv_header_chunk->ycc_offset); // chunk_id is 1-based, so for example chunk id 2 would be too big for a file // 500 bytes long if(header->file_size <= ((spare->chunk_id - 1) * (fs->block_size))){ flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_UNALLOC); } else{ // Since at this point we know there should be a chunk with this chunk id in the file, if // this is the most recent version of the chunk assume it's part of the current version of the object. YaffsCacheChunk * curr = obj->yco_latest->ycv_last_chunk; while(curr != NULL){ // curr should really never make it to the beginning of the list // Did we find our chunk? if(curr->ycc_offset == offset - yfs->page_size){ flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_ALLOC); break; } // Did we find a different chunk with our chunk id? if(curr->ycc_chunk_id == spare->chunk_id){ flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_UNALLOC); break; } curr = curr->ycc_prev; } } } } } else { flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_UNUSED | TSK_FS_BLOCK_FLAG_UNALLOC); } free(spare); free(header); return flags; } /* yaffsfs_block_walk - block iterator * * flags: TSK_FS_BLOCK_FLAG_ALLOC, TSK_FS_BLOCK_FLAG_UNALLOC, TSK_FS_BLOCK_FLAG_CONT, * TSK_FS_BLOCK_FLAG_META * * Return 1 on error and 0 on success */ static uint8_t yaffsfs_block_walk(TSK_FS_INFO *a_fs, TSK_DADDR_T a_start_blk, TSK_DADDR_T a_end_blk, TSK_FS_BLOCK_WALK_FLAG_ENUM a_flags, TSK_FS_BLOCK_WALK_CB a_action, void *a_ptr) { TSK_FS_BLOCK *fs_block; TSK_DADDR_T addr; // clean up any error messages that are lying around tsk_error_reset(); /* * Sanity checks. */ if (a_start_blk < a_fs->first_block || a_start_blk > a_fs->last_block) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_WALK_RNG); tsk_error_set_errstr("yaffsfs_block_walk: start block: %" PRIuDADDR, a_start_blk); return 1; } if (a_end_blk < a_fs->first_block || a_end_blk > a_fs->last_block || a_end_blk < a_start_blk) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_WALK_RNG); tsk_error_set_errstr("yaffsfs_block_walk: end block: %" PRIuDADDR , a_end_blk); return 1; } /* Sanity check on a_flags -- make sure at least one ALLOC is set */ if (((a_flags & TSK_FS_BLOCK_WALK_FLAG_ALLOC) == 0) && ((a_flags & TSK_FS_BLOCK_WALK_FLAG_UNALLOC) == 0)) { a_flags = (TSK_FS_BLOCK_WALK_FLAG_ENUM) (a_flags | TSK_FS_BLOCK_WALK_FLAG_ALLOC | TSK_FS_BLOCK_WALK_FLAG_UNALLOC); } if (((a_flags & TSK_FS_BLOCK_WALK_FLAG_META) == 0) && ((a_flags & TSK_FS_BLOCK_WALK_FLAG_CONT) == 0)) { a_flags = (TSK_FS_BLOCK_WALK_FLAG_ENUM) (a_flags | TSK_FS_BLOCK_WALK_FLAG_CONT | TSK_FS_BLOCK_WALK_FLAG_META); } if ((fs_block = tsk_fs_block_alloc(a_fs)) == NULL) { return 1; } for (addr = a_start_blk; addr <= a_end_blk; addr++) { int retval; int myflags; myflags = yaffsfs_block_getflags(a_fs, addr); // test if we should call the callback with this one if ((myflags & TSK_FS_BLOCK_FLAG_META) && (!(a_flags & TSK_FS_BLOCK_WALK_FLAG_META))) continue; else if ((myflags & TSK_FS_BLOCK_FLAG_CONT) && (!(a_flags & TSK_FS_BLOCK_WALK_FLAG_CONT))) continue; else if ((myflags & TSK_FS_BLOCK_FLAG_ALLOC) && (!(a_flags & TSK_FS_BLOCK_WALK_FLAG_ALLOC))) continue; else if ((myflags & TSK_FS_BLOCK_FLAG_UNALLOC) && (!(a_flags & TSK_FS_BLOCK_WALK_FLAG_UNALLOC))) continue; if (tsk_fs_block_get(a_fs, fs_block, addr) == NULL) { tsk_error_set_errstr2("yaffsfs_block_walk: block %" PRIuDADDR, addr); tsk_fs_block_free(fs_block); return 1; } retval = a_action(fs_block, a_ptr); if (retval == TSK_WALK_STOP) { break; } else if (retval == TSK_WALK_ERROR) { tsk_fs_block_free(fs_block); return 1; } } /* * Cleanup. */ tsk_fs_block_free(fs_block); return 0; } static uint8_t yaffsfs_fscheck(TSK_FS_INFO * /*fs*/, FILE * /*hFile*/) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_UNSUPFUNC); tsk_error_set_errstr("fscheck not implemented yet for YAFFS"); return 1; } /** * Print details about the file system to a file handle. * * @param fs File system to print details on * @param hFile File handle to print text to * * @returns 1 on error and 0 on success */ static uint8_t yaffsfs_fsstat(TSK_FS_INFO * fs, FILE * hFile) { YAFFSFS_INFO *yfs = (YAFFSFS_INFO *) fs; unsigned int obj_count, version_count; uint32_t obj_first, obj_last, version_first, version_last; // clean up any error messages that are lying around tsk_error_reset(); tsk_fprintf(hFile, "FILE SYSTEM INFORMATION\n"); tsk_fprintf(hFile, "--------------------------------------------\n"); tsk_fprintf(hFile, "File System Type: YAFFS2\n"); tsk_fprintf(hFile, "Page Size: %u\n", yfs->page_size); tsk_fprintf(hFile, "Spare Size: %u\n", yfs->spare_size); tsk_fprintf(hFile, "Spare Offsets: Sequence number: %d, Object ID: %d, Chunk ID: %d, nBytes: %d\n", yfs->spare_seq_offset, yfs->spare_obj_id_offset, yfs->spare_chunk_id_offset, yfs->spare_nbytes_offset); tsk_fprintf(hFile, "\nMETADATA INFORMATION\n"); tsk_fprintf(hFile, "--------------------------------------------\n"); yaffscache_objects_stats(yfs, &obj_count, &obj_first, &obj_last, &version_count, &version_first, &version_last); tsk_fprintf(hFile, "Number of Allocated Objects: %u\n", obj_count); tsk_fprintf(hFile, "Object Id Range: %" PRIu32 " - %" PRIu32 "\n", obj_first, obj_last); tsk_fprintf(hFile, "Number of Total Object Versions: %u\n", version_count); tsk_fprintf(hFile, "Object Version Range: %" PRIu32 " - %" PRIu32 "\n", version_first, version_last); return 0; } /************************* istat *******************************/ typedef struct { FILE *hFile; int idx; } YAFFSFS_PRINT_ADDR; /* Callback for istat to print the block addresses */ static TSK_WALK_RET_ENUM print_addr_act(YAFFSFS_INFO * /*fs_file*/, TSK_OFF_T /*a_off*/, TSK_DADDR_T addr, char * /*buf*/, size_t /*size*/, TSK_FS_BLOCK_FLAG_ENUM flags, void *a_ptr) { YAFFSFS_PRINT_ADDR *print = (YAFFSFS_PRINT_ADDR *) a_ptr; if (flags & TSK_FS_BLOCK_FLAG_CONT) { tsk_fprintf(print->hFile, "%" PRIuDADDR " ", addr); if (++(print->idx) == 8) { tsk_fprintf(print->hFile, "\n"); print->idx = 0; } } return TSK_WALK_CONT; } /** * Print details on a specific file to a file handle. * * @param fs File system file is located in * @param hFile File handle to print text to * @param inum Address of file in file system * @param numblock The number of blocks in file to force print (can go beyond file size) * @param sec_skew Clock skew in seconds to also print times in * * @returns 1 on error and 0 on success */ static uint8_t yaffsfs_istat(TSK_FS_INFO *fs, TSK_FS_ISTAT_FLAG_ENUM flags, FILE * hFile, TSK_INUM_T inum, TSK_DADDR_T numblock, int32_t sec_skew) { TSK_FS_META *fs_meta; TSK_FS_FILE *fs_file; YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)fs; char ls[12]; YAFFSFS_PRINT_ADDR print; char timeBuf[32]; YaffsCacheObject * obj = NULL; YaffsCacheVersion * version = NULL; YaffsHeader * header = NULL; yaffscache_version_find_by_inode(yfs, inum, &version, &obj); if ((fs_file = tsk_fs_file_open_meta(fs, NULL, inum)) == NULL) { return 1; } fs_meta = fs_file->meta; tsk_fprintf(hFile, "inode: %" PRIuINUM "\n", inum); tsk_fprintf(hFile, "%sAllocated\n", (fs_meta->flags & TSK_FS_META_FLAG_ALLOC) ? "" : "Not "); if (fs_meta->link) tsk_fprintf(hFile, "symbolic link to: %s\n", fs_meta->link); tsk_fprintf(hFile, "uid / gid: %" PRIuUID " / %" PRIuGID "\n", fs_meta->uid, fs_meta->gid); tsk_fs_meta_make_ls(fs_meta, ls, sizeof(ls)); tsk_fprintf(hFile, "mode: %s\n", ls); tsk_fprintf(hFile, "size: %" PRIdOFF "\n", fs_meta->size); tsk_fprintf(hFile, "num of links: %d\n", fs_meta->nlink); if(version != NULL){ yaffsfs_read_header(yfs, &header, version->ycv_header_chunk->ycc_offset); if(header != NULL){ tsk_fprintf(hFile, "Name: %s\n", header->name); } } if (sec_skew != 0) { tsk_fprintf(hFile, "\nAdjusted Inode Times:\n"); fs_meta->mtime -= sec_skew; fs_meta->atime -= sec_skew; fs_meta->ctime -= sec_skew; tsk_fprintf(hFile, "Accessed:\t%s\n", tsk_fs_time_to_str(fs_meta->atime, timeBuf)); tsk_fprintf(hFile, "File Modified:\t%s\n", tsk_fs_time_to_str(fs_meta->mtime, timeBuf)); tsk_fprintf(hFile, "Inode Modified:\t%s\n", tsk_fs_time_to_str(fs_meta->ctime, timeBuf)); fs_meta->mtime += sec_skew; fs_meta->atime += sec_skew; fs_meta->ctime += sec_skew; tsk_fprintf(hFile, "\nOriginal Inode Times:\n"); } else { tsk_fprintf(hFile, "\nInode Times:\n"); } tsk_fprintf(hFile, "Accessed:\t%s\n", tsk_fs_time_to_str(fs_meta->atime, timeBuf)); tsk_fprintf(hFile, "File Modified:\t%s\n", tsk_fs_time_to_str(fs_meta->mtime, timeBuf)); tsk_fprintf(hFile, "Inode Modified:\t%s\n", tsk_fs_time_to_str(fs_meta->ctime, timeBuf)); if(version != NULL){ tsk_fprintf(hFile, "\nHeader Chunk:\n"); tsk_fprintf(hFile, "%" PRIuDADDR "\n", (version->ycv_header_chunk->ycc_offset / (yfs->page_size + yfs->spare_size))); } if (numblock > 0) { TSK_OFF_T lower_size = numblock * fs->block_size; fs_meta->size = (lower_size < fs_meta->size)?(lower_size):(fs_meta->size); } tsk_fprintf(hFile, "\nData Chunks:\n"); if (flags & TSK_FS_ISTAT_RUNLIST){ const TSK_FS_ATTR *fs_attr_default = tsk_fs_file_attr_get_type(fs_file, TSK_FS_ATTR_TYPE_DEFAULT, 0, 0); if (fs_attr_default && (fs_attr_default->flags & TSK_FS_ATTR_NONRES)) { if (tsk_fs_attr_print(fs_attr_default, hFile)) { tsk_fprintf(hFile, "\nError creating run lists "); tsk_error_print(hFile); tsk_error_reset(); } } } else { print.idx = 0; print.hFile = hFile; if (tsk_fs_file_walk(fs_file, TSK_FS_FILE_WALK_FLAG_AONLY, (TSK_FS_FILE_WALK_CB)print_addr_act, (void *)&print)) { tsk_fprintf(hFile, "\nError reading file: "); tsk_error_print(hFile); tsk_error_reset(); } else if (print.idx != 0) { tsk_fprintf(hFile, "\n"); } } tsk_fs_file_close(fs_file); return 0; } /* yaffsfs_close - close an yaffsfs file system */ static void yaffsfs_close(TSK_FS_INFO *fs) { if(fs != NULL){ YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)fs; fs->tag = 0; // Walk and free the cache structures yaffscache_objects_free(yfs); yaffscache_chunks_free(yfs); //tsk_deinit_lock(&yaffsfs->lock); tsk_fs_free(fs); } } typedef struct _dir_open_cb_args { YAFFSFS_INFO *yfs; TSK_FS_DIR *dir; TSK_INUM_T parent_addr; } dir_open_cb_args; static TSK_RETVAL_ENUM yaffs_dir_open_meta_cb(YaffsCacheObject * /*obj*/, YaffsCacheVersion *version, void *args) { dir_open_cb_args *cb_args = (dir_open_cb_args *) args; YaffsCacheChunk *chunk = version->ycv_header_chunk; TSK_INUM_T curr_inode = 0; uint32_t obj_id = chunk->ycc_obj_id; uint32_t chunk_id = chunk->ycc_chunk_id; uint32_t vnum = version->ycv_version; YaffsHeader *header = NULL; TSK_FS_NAME * fs_name; char *file_ext; char version_string[64]; // Allow a max of 64 bytes in the version string yaffscache_obj_id_and_version_to_inode(obj_id, vnum, &curr_inode); if (chunk_id != 0) { return TSK_ERR; } if (tsk_verbose) fprintf(stderr, "dir_open_find_children_cb: %08" PRIxINUM " -> %08" PRIx32 ":%d\n", cb_args->parent_addr, obj_id, vnum); if (yaffsfs_read_header(cb_args->yfs, &header, chunk->ycc_offset) != TSK_OK) { return TSK_ERR; } if ((fs_name = tsk_fs_name_alloc(YAFFSFS_MAXNAMLEN + 64, 0)) == NULL) { free(header); return TSK_ERR; } switch (obj_id) { case YAFFS_OBJECT_LOSTNFOUND: strncpy(fs_name->name, YAFFS_OBJECT_LOSTNFOUND_NAME, fs_name->name_size - 64); break; case YAFFS_OBJECT_UNLINKED: strncpy(fs_name->name, YAFFS_OBJECT_UNLINKED_NAME, fs_name->name_size - 64); break; case YAFFS_OBJECT_DELETED: strncpy(fs_name->name, YAFFS_OBJECT_DELETED_NAME, fs_name->name_size - 64); break; default: strncpy(fs_name->name, header->name, fs_name->name_size - 64); break; } fs_name->name[fs_name->name_size - 65] = 0; // Only put object/version string onto unallocated versions if(! yaffs_is_version_allocated(cb_args->yfs, curr_inode)){ // Also copy the extension so that it also shows up after the version string, which allows // easier searching by file extension. Max extension length is 5 characters after the dot, // and require at least one character before the dot file_ext = strrchr(fs_name->name, '.'); if((file_ext != NULL) && (file_ext != fs_name->name) && (strlen(file_ext) < 7)){ snprintf(version_string, 64, "#%d,%d%s", obj_id, vnum, file_ext); } else{ snprintf(version_string, 64, "#%d,%d", obj_id, vnum); } strncat(fs_name->name, version_string, 64); fs_name->flags = TSK_FS_NAME_FLAG_UNALLOC; } else{ fs_name->flags = TSK_FS_NAME_FLAG_ALLOC; } fs_name->meta_addr = curr_inode; switch (header->obj_type) { case YAFFS_TYPE_FILE: fs_name->type = TSK_FS_NAME_TYPE_REG; break; case YAFFS_TYPE_DIRECTORY: fs_name->type = TSK_FS_NAME_TYPE_DIR; break; case YAFFS_TYPE_SOFTLINK: case YAFFS_TYPE_HARDLINK: fs_name->type = TSK_FS_NAME_TYPE_LNK; break; case YAFFS_TYPE_SPECIAL: fs_name->type = TSK_FS_NAME_TYPE_UNDEF; // Could be a socket break; default: if (tsk_verbose) fprintf(stderr, "yaffs_dir_open_meta_cb: unhandled object type\n"); fs_name->type = TSK_FS_NAME_TYPE_UNDEF; break; } free(header); if (tsk_fs_dir_add(cb_args->dir, fs_name)) { tsk_fs_name_free(fs_name); return TSK_ERR; } /* A copy is made in tsk_fs_dir_add, so we can free this one */ tsk_fs_name_free(fs_name); return TSK_OK; } static TSK_RETVAL_ENUM yaffsfs_dir_open_meta(TSK_FS_INFO *a_fs, TSK_FS_DIR ** a_fs_dir, TSK_INUM_T a_addr) { TSK_FS_DIR *fs_dir; TSK_FS_NAME *fs_name; YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)a_fs; int should_walk_children = 0; uint32_t obj_id; uint32_t ver_number; if (a_addr < a_fs->first_inum || a_addr > a_fs->last_inum) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_WALK_RNG); tsk_error_set_errstr("yaffs_dir_open_meta: Invalid inode value: %" PRIuINUM, a_addr); return TSK_ERR; } else if (a_fs_dir == NULL) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr("yaffs_dir_open_meta: NULL fs_dir argument given"); return TSK_ERR; } fs_dir = *a_fs_dir; if (fs_dir) { tsk_fs_dir_reset(fs_dir); fs_dir->addr = a_addr; } else if ((*a_fs_dir = fs_dir = tsk_fs_dir_alloc(a_fs, a_addr, 128)) == NULL) { return TSK_ERR; } if (tsk_verbose) fprintf(stderr,"yaffs_dir_open_meta: called for directory %" PRIu32 "\n", (uint32_t) a_addr); // handle the orphan directory if its contents were requested if (a_addr == TSK_FS_ORPHANDIR_INUM(a_fs)) { return tsk_fs_dir_find_orphans(a_fs, fs_dir); } if ((fs_name = tsk_fs_name_alloc(YAFFSFS_MAXNAMLEN, 0)) == NULL) { return TSK_ERR; } if ((fs_dir->fs_file = tsk_fs_file_open_meta(a_fs, NULL, a_addr)) == NULL) { tsk_error_errstr2_concat(" - yaffs_dir_open_meta"); tsk_fs_name_free(fs_name); return TSK_ERR; } // extract obj_id and ver_number from inum yaffscache_inode_to_obj_id_and_version(a_addr, &obj_id, &ver_number); // Decide if we should walk the directory structure if (obj_id == YAFFS_OBJECT_DELETED || obj_id == YAFFS_OBJECT_UNLINKED) { should_walk_children = 1; } else { YaffsCacheObject *obj; YaffsCacheVersion *versionFound; TSK_RETVAL_ENUM result = yaffscache_version_find_by_inode(yfs, a_addr, &versionFound, &obj); if (result != TSK_OK) { if (tsk_verbose) tsk_fprintf(stderr, "yaffsfs_dir_open_meta: yaffscache_version_find_by_inode failed! (inode: %d\n", a_addr); tsk_fs_name_free(fs_name); return TSK_ERR; } /* Only attach files onto the latest version of the directory */ should_walk_children = (obj->yco_latest == versionFound); } // Search the cache for the children of this object and add them to fs_dir if (should_walk_children) { dir_open_cb_args args; args.yfs = yfs; args.dir = fs_dir; args.parent_addr = a_addr; yaffscache_find_children(yfs, a_addr, yaffs_dir_open_meta_cb, &args); } // add special entries to root directory if (obj_id == YAFFS_OBJECT_ROOT) { strncpy(fs_name->name, YAFFS_OBJECT_UNLINKED_NAME, fs_name->name_size); fs_name->meta_addr = YAFFS_OBJECT_UNLINKED; fs_name->type = TSK_FS_NAME_TYPE_DIR; fs_name->flags = TSK_FS_NAME_FLAG_ALLOC; if (tsk_fs_dir_add(fs_dir, fs_name)) { tsk_fs_name_free(fs_name); return TSK_ERR; } strncpy(fs_name->name, YAFFS_OBJECT_DELETED_NAME, fs_name->name_size); fs_name->meta_addr = YAFFS_OBJECT_DELETED; fs_name->type = TSK_FS_NAME_TYPE_DIR; fs_name->flags = TSK_FS_NAME_FLAG_ALLOC; if (tsk_fs_dir_add(fs_dir, fs_name)) { tsk_fs_name_free(fs_name); return TSK_ERR; } // orphan directory if (tsk_fs_dir_make_orphan_dir_name(a_fs, fs_name)) { tsk_fs_name_free(fs_name); return TSK_ERR; } fs_name->meta_addr = yfs->fs_info.last_inum; fs_name->type = TSK_FS_NAME_TYPE_DIR; fs_name->flags = TSK_FS_NAME_FLAG_ALLOC; if (tsk_fs_dir_add(fs_dir, fs_name)) { tsk_fs_name_free(fs_name); return TSK_ERR; } } tsk_fs_name_free(fs_name); return TSK_OK; } static TSK_FS_ATTR_TYPE_ENUM yaffsfs_get_default_attr_type(const TSK_FS_FILE * /*a_file*/) { return TSK_FS_ATTR_TYPE_DEFAULT; } static uint8_t yaffsfs_load_attrs(TSK_FS_FILE *file) { TSK_FS_ATTR *attr; TSK_FS_META *meta; TSK_FS_INFO *fs; YAFFSFS_INFO *yfs; TSK_FS_ATTR_RUN *data_run; TSK_DADDR_T file_block_count; YaffsCacheObject *obj; YaffsCacheVersion *version; TSK_RETVAL_ENUM result; TSK_LIST *chunks_seen = NULL; YaffsCacheChunk *curr; TSK_FS_ATTR_RUN *data_run_new; if (file == NULL || file->meta == NULL || file->fs_info == NULL) { tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr ("yaffsfs_load_attrs: called with NULL pointers"); return 1; } meta = file->meta; yfs = (YAFFSFS_INFO *)file->fs_info; fs = &yfs->fs_info; // see if we have already loaded the runs if ((meta->attr != NULL) && (meta->attr_state == TSK_FS_META_ATTR_STUDIED)) { return 0; } else if (meta->attr_state == TSK_FS_META_ATTR_ERROR) { return 1; } // not sure why this would ever happen, but... else if (meta->attr != NULL) { tsk_fs_attrlist_markunused(meta->attr); } else if (meta->attr == NULL) { meta->attr = tsk_fs_attrlist_alloc(); } attr = tsk_fs_attrlist_getnew(meta->attr, TSK_FS_ATTR_NONRES); if (attr == NULL) { meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } if (meta->size == 0) { data_run = NULL; } else { /* BC: I'm not entirely sure this is needed. My guess is that * this was done instead of maintaining the head of the list of * runs. In theory, the tsk_fs_attr_add_run() method should handle * the fillers. */ data_run = tsk_fs_attr_run_alloc(); if (data_run == NULL) { tsk_fs_attr_run_free(data_run); meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } data_run->offset = 0; data_run->addr = 0; data_run->len = (meta->size + fs->block_size - 1) / fs->block_size; data_run->flags = TSK_FS_ATTR_RUN_FLAG_FILLER; } // initialize the data run if (tsk_fs_attr_set_run(file, attr, data_run, NULL, TSK_FS_ATTR_TYPE_DEFAULT, TSK_FS_ATTR_ID_DEFAULT, meta->size, meta->size, roundup(meta->size, fs->block_size), (TSK_FS_ATTR_FLAG_ENUM)0, 0)) { meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } // If the file has size zero, return now if(meta->size == 0){ meta->attr_state = TSK_FS_META_ATTR_STUDIED; return 0; } /* Get the version for the given object. */ result = yaffscache_version_find_by_inode(yfs, meta->addr, &version, &obj); if (result != TSK_OK || version == NULL) { if (tsk_verbose) tsk_fprintf(stderr, "yaffsfs_load_attrs: yaffscache_version_find_by_inode failed!\n"); meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } if (tsk_verbose) yaffscache_object_dump(stderr, obj); file_block_count = data_run->len; /* Cycle through the chunks for this version of this object */ curr = version->ycv_last_chunk; while (curr != NULL && curr->ycc_obj_id == obj->yco_obj_id) { if (curr->ycc_chunk_id == 0) { if (tsk_verbose) tsk_fprintf(stderr, "yaffsfs_load_attrs: skipping header chunk\n"); } else if (tsk_list_find(chunks_seen, curr->ycc_chunk_id)) { if (tsk_verbose) tsk_fprintf(stderr, "yaffsfs_load_attrs: skipping duplicate chunk\n"); } else if (curr->ycc_chunk_id > file_block_count) { if (tsk_verbose) tsk_fprintf(stderr, "yaffsfs_load_attrs: skipping chunk past end\n"); } /* We like this chunk */ else { // add it to our internal list if (tsk_list_add(&chunks_seen, curr->ycc_chunk_id)) { meta->attr_state = TSK_FS_META_ATTR_ERROR; tsk_list_free(chunks_seen); chunks_seen = NULL; return 1; } data_run_new = tsk_fs_attr_run_alloc(); if (data_run_new == NULL) { tsk_fs_attr_run_free(data_run_new); meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } data_run_new->offset = (curr->ycc_chunk_id - 1); data_run_new->addr = curr->ycc_offset / (fs->block_pre_size + fs->block_size + fs->block_post_size); data_run_new->len = 1; data_run_new->flags = TSK_FS_ATTR_RUN_FLAG_NONE; if (tsk_verbose) tsk_fprintf(stderr, "yaffsfs_load_attrs: @@@ Chunk %d : %08x is at offset 0x%016llx\n", curr->ycc_chunk_id, curr->ycc_seq_number, curr->ycc_offset); tsk_fs_attr_add_run(fs, attr, data_run_new); } curr = curr->ycc_prev; } tsk_list_free(chunks_seen); meta->attr_state = TSK_FS_META_ATTR_STUDIED; return 0; } static uint8_t yaffsfs_jentry_walk(TSK_FS_INFO * /*info*/, int /*entry*/, TSK_FS_JENTRY_WALK_CB /*cb*/, void * /*fn*/) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_UNSUPFUNC); tsk_error_set_errstr("Journal support for YAFFS is not implemented"); return 1; } static uint8_t yaffsfs_jblk_walk(TSK_FS_INFO * /*info*/, TSK_DADDR_T /*daddr*/, TSK_DADDR_T /*daddrt*/, int /*entry*/, TSK_FS_JBLK_WALK_CB /*cb*/, void * /*fn*/) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_UNSUPFUNC); tsk_error_set_errstr("Journal support for YAFFS is not implemented"); return 1; } static uint8_t yaffsfs_jopen(TSK_FS_INFO * /*info*/, TSK_INUM_T /*inum*/) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_UNSUPFUNC); tsk_error_set_errstr("Journal support for YAFFS is not implemented"); return 1; } /** * \internal * Open part of a disk image as a Yaffs/2 file system. * * @param img_info Disk image to analyze * @param offset Byte offset where file system starts * @param ftype Specific type of file system * @param test Going to use this - 1 if we're doing auto-detect, 0 if not (display more verbose messages if the user specified YAFFS2) * @returns NULL on error or if data is not an Yaffs/3 file system */ TSK_FS_INFO * yaffs2_open(TSK_IMG_INFO * img_info, TSK_OFF_T offset, TSK_FS_TYPE_ENUM ftype, uint8_t test) { YAFFSFS_INFO *yaffsfs = NULL; TSK_FS_INFO *fs = NULL; const unsigned int psize = img_info->page_size; const unsigned int ssize = img_info->spare_size; YaffsHeader * first_header = NULL; TSK_FS_DIR *test_dir; std::map<std::string, std::string> configParams; YAFFS_CONFIG_STATUS config_file_status; // clean up any error messages that are lying around tsk_error_reset(); if (TSK_FS_TYPE_ISYAFFS2(ftype) == 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr("Invalid FS Type in yaffsfs_open"); return NULL; } if (img_info->sector_size == 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr("yaffs2_open: sector size is 0"); return NULL; } if ((yaffsfs = (YAFFSFS_INFO *) tsk_fs_malloc(sizeof(YAFFSFS_INFO))) == NULL) return NULL; yaffsfs->cache_objects = NULL; yaffsfs->chunkMap = NULL; fs = &(yaffsfs->fs_info); fs->tag = TSK_FS_INFO_TAG; fs->ftype = ftype; fs->flags = (TSK_FS_INFO_FLAG_ENUM)0; fs->img_info = img_info; fs->offset = offset; fs->endian = TSK_LIT_ENDIAN; // Read config file (if it exists) config_file_status = yaffs_load_config_file(img_info, configParams); // BL-6929(JTS): When using external readers, this call will fail. // Not having a config should not be a fatal error. /*if(config_file_status == YAFFS_CONFIG_ERROR){ // tsk_error was set by yaffs_load_config goto on_error; } else*/ if(config_file_status == YAFFS_CONFIG_OK){ // Validate the input // If it fails validation, return (tsk_error will be set up already) if(1 == yaffs_validate_config_file(configParams)){ goto on_error; } } // If we read these fields from the config file, use those values. Otherwise use the defaults if(configParams.find(YAFFS_CONFIG_PAGE_SIZE_STR) != configParams.end()){ yaffsfs->page_size = atoi(configParams[YAFFS_CONFIG_PAGE_SIZE_STR].c_str()); } else{ yaffsfs->page_size = psize == 0 ? YAFFS_DEFAULT_PAGE_SIZE : psize; } if(configParams.find(YAFFS_CONFIG_SPARE_SIZE_STR) != configParams.end()){ yaffsfs->spare_size = atoi(configParams[YAFFS_CONFIG_SPARE_SIZE_STR].c_str()); } else{ yaffsfs->spare_size = ssize == 0 ? YAFFS_DEFAULT_SPARE_SIZE : ssize; } if(configParams.find(YAFFS_CONFIG_CHUNKS_PER_BLOCK_STR) != configParams.end()){ yaffsfs->chunks_per_block = atoi(configParams[YAFFS_CONFIG_CHUNKS_PER_BLOCK_STR].c_str()); } else{ yaffsfs->chunks_per_block = 64; } // TODO: Why are 2 different memory allocation methods used in the same code? // This makes things unnecessary complex. yaffsfs->max_obj_id = 1; yaffsfs->max_version = 0; // Keep track of whether we're doing auto-detection of the file system if(test){ yaffsfs->autoDetect = 1; } else{ yaffsfs->autoDetect = 0; } // Determine the layout of the spare area // If it was specified in the config file, use those values. Otherwise do the auto-detection if(configParams.find(YAFFS_CONFIG_SEQ_NUM_STR) != configParams.end()){ // In the validation step, we ensured that if one of the offsets was set, we have all of them yaffsfs->spare_seq_offset = atoi(configParams[YAFFS_CONFIG_SEQ_NUM_STR].c_str()); yaffsfs->spare_obj_id_offset = atoi(configParams[YAFFS_CONFIG_OBJ_ID_STR].c_str()); yaffsfs->spare_chunk_id_offset = atoi(configParams[YAFFS_CONFIG_CHUNK_ID_STR].c_str()); // Check that the offsets are valid for the given spare area size (fields are 4 bytes long) if((yaffsfs->spare_seq_offset + 4 > yaffsfs->spare_size) || (yaffsfs->spare_obj_id_offset + 4 > yaffsfs->spare_size) || (yaffsfs->spare_chunk_id_offset + 4 > yaffsfs->spare_size)){ tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr("yaffs2_open: Offset(s) in config file too large for spare area (size %d). %s", yaffsfs->spare_size, YAFFS_HELP_MESSAGE); goto on_error; } // nBytes isn't currently used, so just set to zero yaffsfs->spare_nbytes_offset = 0; } else{ // Decide how many blocks to test. If we're not doing auto-detection, set to zero (no limit) unsigned int maxBlocksToTest; if(yaffsfs->autoDetect){ maxBlocksToTest = YAFFS_DEFAULT_MAX_TEST_BLOCKS; } else{ maxBlocksToTest = 0; } if(yaffs_initialize_spare_format(yaffsfs, maxBlocksToTest) != TSK_OK){ tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_MAGIC); tsk_error_set_errstr("not a YAFFS file system (bad spare format). %s", YAFFS_HELP_MESSAGE); if (tsk_verbose) fprintf(stderr, "yaffsfs_open: could not find valid spare area format\n%s\n", YAFFS_HELP_MESSAGE); goto on_error; } } /* * Read the first record, make sure it's a valid header... * * Used for verification and autodetection of * the FS type. */ if (yaffsfs_read_header(yaffsfs, &first_header, 0)) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_MAGIC); tsk_error_set_errstr("not a YAFFS file system (first record). %s", YAFFS_HELP_MESSAGE); if (tsk_verbose) fprintf(stderr, "yaffsfs_open: invalid first record\n%s\n", YAFFS_HELP_MESSAGE); goto on_error; } free(first_header); first_header = NULL; fs->duname = "Chunk"; /* * Calculate the meta data info */ //fs->last_inum = 0xffffffff; // Will update this as we go fs->last_inum = 0; fs->root_inum = YAFFS_OBJECT_ROOT; fs->first_inum = YAFFS_OBJECT_FIRST; //fs->inum_count = fs->last_inum; // For now this will be the last_inum - 1 (after we calculate it) /* * Calculate the block info */ fs->dev_bsize = img_info->sector_size; fs->block_size = yaffsfs->page_size; fs->block_pre_size = 0; fs->block_post_size = yaffsfs->spare_size; fs->block_count = img_info->size / (fs->block_pre_size + fs->block_size + fs->block_post_size); fs->first_block = 0; fs->last_block_act = fs->last_block = fs->block_count ? fs->block_count - 1 : 0; /* Set the generic function pointers */ fs->inode_walk = yaffsfs_inode_walk; fs->block_walk = yaffsfs_block_walk; fs->block_getflags = yaffsfs_block_getflags; fs->get_default_attr_type = yaffsfs_get_default_attr_type; fs->load_attrs = yaffsfs_load_attrs; fs->file_add_meta = yaffs_inode_lookup; fs->dir_open_meta = yaffsfs_dir_open_meta; fs->fsstat = yaffsfs_fsstat; fs->fscheck = yaffsfs_fscheck; fs->istat = yaffsfs_istat; fs->name_cmp = tsk_fs_unix_name_cmp; fs->close = yaffsfs_close; /* Journal */ fs->jblk_walk = yaffsfs_jblk_walk; fs->jentry_walk = yaffsfs_jentry_walk; fs->jopen = yaffsfs_jopen; /* Initialize the caches */ if (tsk_verbose) fprintf(stderr, "yaffsfs_open: building cache...\n"); /* Build cache */ /* NOTE: The only modifications to the cache happen here, during at * the open. Should be fine with no lock, even if access to the * cache is shared among threads. */ //tsk_init_lock(&yaffsfs->lock); yaffsfs->chunkMap = new std::map<uint32_t, YaffsCacheChunkGroup>; if (TSK_OK != yaffsfs_parse_image_load_cache(yaffsfs)) { goto on_error; } if (tsk_verbose) { fprintf(stderr, "yaffsfs_open: done building cache!\n"); //yaffscache_objects_dump(yaffsfs, stderr); } // Update the number of inums now that we've read in the file system fs->inum_count = fs->last_inum - 1; test_dir = tsk_fs_dir_open_meta(fs, fs->root_inum); if (test_dir == NULL) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_MAGIC); tsk_error_set_errstr("not a YAFFS file system (no root directory). %s", YAFFS_HELP_MESSAGE); if (tsk_verbose) fprintf(stderr, "yaffsfs_open: invalid file system\n%s\n", YAFFS_HELP_MESSAGE); goto on_error; } tsk_fs_dir_close(test_dir); return fs; on_error: // yaffsfs_close frees all the cache objects yaffsfs_close(fs); return NULL; }
null
/* ** The Sleuth Kit ** ** Brian Carrier [carrier <at> sleuthkit [dot] org] ** Copyright (c) 2006-2011 Brian Carrier, Basis Technology. All Rights reserved ** Copyright (c) 2003-2005 Brian Carrier. All rights reserved ** ** TASK v** Copyright (c) 2002-2003 Brian Carrier, @stake Inc. All rights reserved ** ** Copyright (c) 1997,1998,1999, International Business Machines ** Corporation and others. All Rights Reserved. */ /** *\file yaffs.cpp * Contains the internal TSK YAFFS2 file system functions. */ /* TCT * LICENSE * This software is distributed under the IBM Public License. * AUTHOR(S) * Wietse Venema * IBM T.J. Watson Research * P.O. Box 704 * Yorktown Heights, NY 10598, USA --*/ #include <vector> #include <map> #include <algorithm> #include <string> #include <set> #include <string.h> #include "tsk_fs_i.h" #include "tsk_yaffs.h" #include "tsk_fs.h" /* * Implementation Notes: * - As inode, we use object id and a version number derived from the * number of unique sequence ids for the object still left in the * file system. * * - The version numbers start at 1 and increase as they get closer to * the the latest version. Version number 0 is a special version * that is equivalent to the latest version (without having to know * the latest version number.) * * - Since inodes are composed using the object id in the least * significant bits and the version up higher, requesting the * inode that matches the object id you are looking for will * retrieve the latest version of this object. * * - Files always exist in the latest version of their parent directory * only. * * - Filenames are not unique even with attached version numbers, since * version numbers are namespaced by inode. * * - The cache stores a lot of info via the structure. As this is * used for investigations, we assume these decisions will be updated * to expose the most useful view of this log based file system. TSK * doesn't seem have a real way to expose a versioned view of a log * based file system like this. Shoehorning it into the framework * ends up dropping some information. I looked at using resource * streams as versions, but the abstraction breaks quickly. * */ static const int TWELVE_BITS_MASK = 0xFFF; // Only keep 12 bits static uint8_t yaffsfs_read_header(YAFFSFS_INFO *yfs, YaffsHeader ** header, TSK_OFF_T offset); static uint8_t yaffsfs_load_attrs(TSK_FS_FILE *file); /** * Generate an inode number based on the file's object and version numbers */ static TSK_RETVAL_ENUM yaffscache_obj_id_and_version_to_inode(uint32_t obj_id, uint32_t version_num, TSK_INUM_T *inode) { if ((obj_id & ~YAFFS_OBJECT_ID_MASK) != 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffsfs_parse_image_load_cache: Max object ID %" PRIu32 " is invalid", obj_id); return TSK_ERR; } if ((version_num & ~YAFFS_VERSION_NUM_MASK) != 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffsfs_parse_image_load_cache: Max version number %" PRIu32 " is invalid", version_num); return TSK_ERR; } *inode = obj_id | (version_num << YAFFS_VERSION_NUM_SHIFT); return TSK_OK; } /** * Given the TSK-generated inode address, extract the object id and version number from it */ static TSK_RETVAL_ENUM yaffscache_inode_to_obj_id_and_version(TSK_INUM_T inode, uint32_t *obj_id, uint32_t *version_num) { *obj_id = inode & YAFFS_OBJECT_ID_MASK; *version_num = (inode >> YAFFS_VERSION_NUM_SHIFT) & YAFFS_VERSION_NUM_MASK; return TSK_OK; } /* * Order it like yaffs2.git does -- sort by (seq_num, offset/block) */ static int yaffscache_chunk_compare(YaffsCacheChunk *curr, uint32_t addee_obj_id, TSK_OFF_T addee_offset, uint32_t addee_seq_number) { if (curr->ycc_obj_id == addee_obj_id) { if (curr->ycc_seq_number == addee_seq_number) { if (curr->ycc_offset == addee_offset) { return 0; } else if (curr->ycc_offset < addee_offset) { return -1; } else { return 1; } } else if (curr->ycc_seq_number < addee_seq_number) { return -1; } else { return 1; } } else if (curr->ycc_obj_id < addee_obj_id) { return -1; } else { return 1; } } static TSK_RETVAL_ENUM yaffscache_chunk_find_insertion_point(YAFFSFS_INFO *yfs, uint32_t obj_id, TSK_OFF_T offset, uint32_t seq_number, YaffsCacheChunk **chunk) { YaffsCacheChunk *curr, *prev; // Have we seen this obj_id? If not, add an entry for it if(yfs->chunkMap->find(obj_id) == yfs->chunkMap->end()){ fflush(stderr); YaffsCacheChunkGroup chunkGroup; chunkGroup.cache_chunks_head = NULL; chunkGroup.cache_chunks_tail = NULL; yfs->chunkMap->insert(std::make_pair(obj_id, chunkGroup)); } curr = yfs->chunkMap->operator[](obj_id).cache_chunks_head; prev = NULL; if (chunk == NULL) { return TSK_ERR; } while(curr != NULL) { // Compares obj id, then seq num, then offset. -1 => current < new int cmp = yaffscache_chunk_compare(curr, obj_id, offset, seq_number); if (cmp == 0) { *chunk = curr; return TSK_OK; } else if (cmp == 1) { *chunk = prev; return TSK_STOP; } prev = curr; curr = curr->ycc_next; } *chunk = prev; return TSK_STOP; } /** * Add a chunk to the cache. * @param yfs * @param offset Byte offset this chunk was found in (in the disk image) * @param seq_number Sequence number of this chunk * @param obj_id Object Id this chunk is associated with * @param parent_id Parent object ID that this chunk/object is associated with */ static TSK_RETVAL_ENUM yaffscache_chunk_add(YAFFSFS_INFO *yfs, TSK_OFF_T offset, uint32_t seq_number, uint32_t obj_id, uint32_t chunk_id, uint32_t parent_id) { TSK_RETVAL_ENUM result; YaffsCacheChunk *prev; YaffsCacheChunk *chunk; if ((chunk = (YaffsCacheChunk*)tsk_malloc(sizeof(YaffsCacheChunk))) == NULL) { return TSK_ERR; } chunk->ycc_offset = offset; chunk->ycc_seq_number = seq_number; chunk->ycc_obj_id = obj_id; chunk->ycc_chunk_id = chunk_id; chunk->ycc_parent_id = parent_id; // Bit of a hack here. In some images, the root directory (obj_id = 1) lists iself as its parent // directory, which can cause issues later when we get directory contents. To prevent this, // if a chunk comes in with obj_id = 1 and parent_id = 1, manually set the parent ID to zero. if((obj_id == 1) && (parent_id == 1)){ chunk->ycc_parent_id = 0; } // Find the chunk that should go right before the new chunk result = yaffscache_chunk_find_insertion_point(yfs, obj_id, offset, seq_number, &prev); if (result == TSK_ERR) { return TSK_ERR; } if (prev == NULL) { // No previous chunk - new chunk is the lowest we've seen and the new start of the list chunk->ycc_prev = NULL; chunk->ycc_next = yfs->chunkMap->operator[](obj_id).cache_chunks_head; } else { chunk->ycc_prev = prev; chunk->ycc_next = prev->ycc_next; } if (chunk->ycc_next != NULL) { // If we're not at the end, set the prev pointer on the next chunk to point to our new one chunk->ycc_next->ycc_prev = chunk; } else { yfs->chunkMap->operator[](obj_id).cache_chunks_tail = chunk; } if (chunk->ycc_prev != NULL) { // If we're not at the beginning, set the next pointer on the previous chunk to point at our new one chunk->ycc_prev->ycc_next = chunk; } else { yfs->chunkMap->operator[](obj_id).cache_chunks_head = chunk; } return TSK_OK; } /** * Get the file object from the cache. * @returns TSK_OK if it was found and TSK_STOP if we did not find it */ static TSK_RETVAL_ENUM yaffscache_object_find(YAFFSFS_INFO *yfs, uint32_t obj_id, YaffsCacheObject **obj) { YaffsCacheObject *curr, *prev; curr = yfs->cache_objects; prev = NULL; if (obj == NULL) { return TSK_ERR; } while(curr != NULL) { if (curr->yco_obj_id == obj_id) { *obj = curr; return TSK_OK; } else if (curr->yco_obj_id > obj_id) { *obj = prev; return TSK_STOP; } prev = curr; curr = curr->yco_next; } *obj = prev; return TSK_STOP; } /** * Add an object to the cache if it does not already exist in there. * @returns TSK_ERR on error, TSK_OK otherwise. */ static TSK_RETVAL_ENUM yaffscache_object_find_or_add(YAFFSFS_INFO *yfs, uint32_t obj_id, YaffsCacheObject **obj) { YaffsCacheObject *prev; TSK_RETVAL_ENUM result; if (obj == NULL) { return TSK_ERR; } // Look for this obj_id in yfs->cache_objects // If not found, add it in the correct spot // yaffscache_object_find returns the last object with obj_id less than the one // we were searching for, so use that to insert the new one in the list result = yaffscache_object_find(yfs, obj_id, &prev); if (result == TSK_OK) { *obj = prev; return TSK_OK; } else if (result == TSK_STOP) { *obj = (YaffsCacheObject *) tsk_malloc(sizeof(YaffsCacheObject)); (*obj)->yco_obj_id = obj_id; if (prev == NULL) { (*obj)->yco_next = yfs->cache_objects; yfs->cache_objects = *obj; } else { (*obj)->yco_next = prev->yco_next; prev->yco_next = (*obj); } return TSK_OK; } else { *obj = NULL; return TSK_ERR; } } static TSK_RETVAL_ENUM yaffscache_object_add_version(YaffsCacheObject *obj, YaffsCacheChunk *chunk) { uint32_t ver_number; YaffsCacheChunk *header_chunk = NULL; YaffsCacheVersion *version; // Going to try ignoring unlinked/deleted headers (objID 3 and 4) if ((chunk->ycc_chunk_id == 0) && (chunk->ycc_parent_id != YAFFS_OBJECT_UNLINKED) &&(chunk->ycc_parent_id != YAFFS_OBJECT_DELETED)) { header_chunk = chunk; } /* If this is the second version (since last header_chunk is not NULL) and no * header was added, get rid of this incomplete old version -- can't be * reasonably recovered. * * TODO: These chunks are still in the structure and can be walked, * but I'm not sure how to represent this set of data chunks * with no metadata under TSK. This is rare and we don't have * a testcase for it now. Punting right now. * * Edit: Shouldn't get to this point anymore. Changes to * yaffscache_versions_insert_chunk make a version continue until it * has a header block. */ if (obj->yco_latest != NULL) { if (obj->yco_latest->ycv_header_chunk == NULL) { YaffsCacheVersion *incomplete = obj->yco_latest; if (tsk_verbose) tsk_fprintf(stderr, "yaffscache_object_add_version: " "removed an incomplete first version (no header)\n"); obj->yco_latest = obj->yco_latest->ycv_prior; free(incomplete); } } if (obj->yco_latest != NULL) { ver_number = obj->yco_latest->ycv_version + 1; /* Until a new header is given, use the last seen header. */ if (header_chunk == NULL) { header_chunk = obj->yco_latest->ycv_header_chunk; // If we haven't seen a good header yet and we have a deleted/unlinked one, use it if((header_chunk == NULL) && (chunk->ycc_chunk_id == 0)){ header_chunk = chunk; } } } else { ver_number = 1; } if ((version = (YaffsCacheVersion *) tsk_malloc(sizeof(YaffsCacheVersion))) == NULL) { return TSK_ERR; } version->ycv_prior = obj->yco_latest; version->ycv_version = ver_number; version->ycv_seq_number = chunk->ycc_seq_number; version->ycv_header_chunk = header_chunk; version->ycv_first_chunk = chunk; version->ycv_last_chunk = chunk; obj->yco_latest = version; return TSK_OK; } /** * Add a chunk to its corresponding object in the cache. */ static TSK_RETVAL_ENUM yaffscache_versions_insert_chunk(YAFFSFS_INFO *yfs, YaffsCacheChunk *chunk) { YaffsCacheObject *obj; TSK_RETVAL_ENUM result; YaffsCacheVersion *version; // Building a list in yfs->cache_objects, sorted by obj_id result = yaffscache_object_find_or_add(yfs, chunk->ycc_obj_id, &obj); if (result != TSK_OK) { return TSK_ERR; } version = obj->yco_latest; /* First chunk in this object? */ if (version == NULL) { yaffscache_object_add_version(obj, chunk); } else { /* Chunk in the same update? */ if (chunk->ycc_seq_number == version->ycv_seq_number) { version->ycv_last_chunk = chunk; if ((chunk->ycc_chunk_id == 0) && (chunk->ycc_parent_id != YAFFS_OBJECT_UNLINKED) &&(chunk->ycc_parent_id != YAFFS_OBJECT_DELETED)) { version->ycv_header_chunk = chunk; } else if((chunk->ycc_chunk_id == 0) && (version->ycv_header_chunk == NULL)){ version->ycv_header_chunk = chunk; } } // If there was no header for the last version, continue adding to it instead // of starting a new version. else if(version->ycv_header_chunk == NULL){ version->ycv_seq_number = chunk->ycc_seq_number; version->ycv_last_chunk = chunk; if ((chunk->ycc_chunk_id == 0) && (chunk->ycc_parent_id != YAFFS_OBJECT_UNLINKED) &&(chunk->ycc_parent_id != YAFFS_OBJECT_DELETED)) { version->ycv_header_chunk = chunk; } else if((chunk->ycc_chunk_id == 0) && (version->ycv_header_chunk == NULL)){ version->ycv_header_chunk = chunk; } } else if(chunk->ycc_chunk_id == 0){ // Directories only have a header block // If we're looking at a new version of a directory where the previous version had the same name, // leave everything in the same version. Multiple versions of the same directory aren't really giving us // any information. YaffsHeader * newHeader; yaffsfs_read_header(yfs, &newHeader, chunk->ycc_offset); if((newHeader != NULL) && (newHeader->obj_type == YAFFS_TYPE_DIRECTORY)){ // Read in the old header YaffsHeader * oldHeader; yaffsfs_read_header(yfs, &oldHeader, version->ycv_header_chunk->ycc_offset); if((oldHeader != NULL) && (oldHeader->obj_type == YAFFS_TYPE_DIRECTORY) && (0 == strncmp(oldHeader->name, newHeader->name, YAFFS_HEADER_NAME_LENGTH))){ version->ycv_seq_number = chunk->ycc_seq_number; version->ycv_last_chunk = chunk; version->ycv_header_chunk = chunk; } else{ // The older header either isn't a directory or it doesn't have the same name, so leave it // as its own version yaffscache_object_add_version(obj, chunk); } } else{ // Not a directory yaffscache_object_add_version(obj, chunk); } } else{ // Otherwise, add this chunk as the start of a new version yaffscache_object_add_version(obj, chunk); } } return TSK_OK; } static TSK_RETVAL_ENUM yaffscache_versions_compute(YAFFSFS_INFO *yfs) { std::map<unsigned int,YaffsCacheChunkGroup>::iterator iter; for( iter = yfs->chunkMap->begin(); iter != yfs->chunkMap->end(); ++iter ) { YaffsCacheChunk *chunk_curr = yfs->chunkMap->operator[](iter->first).cache_chunks_head; while(chunk_curr != NULL) { if (yaffscache_versions_insert_chunk(yfs, chunk_curr) != TSK_OK) { return TSK_ERR; } chunk_curr = chunk_curr->ycc_next; } } return TSK_OK; } /** * Callback for yaffscache_find_children() * @param obj Object that is a child * @param version Version of the object * @param args Pointer to what was passed into yaffscache_find_children */ typedef TSK_RETVAL_ENUM yc_find_children_cb(YaffsCacheObject *obj, YaffsCacheVersion *version, void *args); /** * Search the cache for objects that are children of the given address. * @param yfs * @param parent_inode Inode of folder/directory * @param cb Call back to call for each found child * @param args Pointer to structure that will be passed to cb * @returns TSK_ERR on error */ static TSK_RETVAL_ENUM yaffscache_find_children(YAFFSFS_INFO *yfs, TSK_INUM_T parent_inode, yc_find_children_cb cb, void *args) { YaffsCacheObject *obj; uint32_t parent_id, version_num; if (yaffscache_inode_to_obj_id_and_version(parent_inode, &parent_id, &version_num) != TSK_OK) { return TSK_ERR; } /* Iterate over all objects and all versions of the objects to see if one is the child * of the given parent. */ for (obj = yfs->cache_objects; obj != NULL; obj = obj->yco_next) { YaffsCacheVersion *version; for (version = obj->yco_latest; version != NULL; version = version->ycv_prior) { /* Is this an incomplete version? */ if (version->ycv_header_chunk == NULL) { continue; } if (version->ycv_header_chunk->ycc_parent_id == parent_id) { TSK_RETVAL_ENUM result = cb(obj, version, args); if (result != TSK_OK) return result; } } } return TSK_OK; } /** * Lookup an object based on its inode. * @param yfs * @param inode * @param version [out] Pointer to store version of the object that was found (if inode had a version of 0) * @param obj_ret [out] Pointer to store found object into * @returns TSK_ERR on error. */ static TSK_RETVAL_ENUM yaffscache_version_find_by_inode(YAFFSFS_INFO *yfs, TSK_INUM_T inode, YaffsCacheVersion **version, YaffsCacheObject **obj_ret) { uint32_t obj_id, version_num; YaffsCacheObject *obj; YaffsCacheVersion *curr; if (version == NULL) { return TSK_ERR; } // convert inode to obj and version and find it in cache if (yaffscache_inode_to_obj_id_and_version(inode, &obj_id, &version_num) != TSK_OK) { *version = NULL; return TSK_ERR; } if (yaffscache_object_find(yfs, obj_id, &obj) != TSK_OK) { *version = NULL; return TSK_ERR; } if (version_num == 0) { if (obj_ret != NULL) { *obj_ret = obj; } *version = obj->yco_latest; return TSK_OK; } // Find the requested version in the list. for(curr = obj->yco_latest; curr != NULL; curr = curr->ycv_prior) { if (curr->ycv_version == version_num) { if (obj_ret != NULL) { *obj_ret = obj; } *version = curr; return TSK_OK; } } if (obj_ret != NULL) { *obj_ret = NULL; } *version = NULL; return TSK_ERR; } static void yaffscache_object_dump(FILE *fp, YaffsCacheObject *obj) { YaffsCacheVersion *next_version = obj->yco_latest; YaffsCacheChunk *chunk = next_version->ycv_last_chunk; fprintf(fp, "Object %d\n", obj->yco_obj_id); while(chunk != NULL && chunk->ycc_obj_id == obj->yco_obj_id) { if (next_version != NULL && chunk == next_version->ycv_last_chunk) { fprintf(fp, " @%d: %p %p %p\n", next_version->ycv_version, (void*) next_version->ycv_header_chunk, (void*) next_version->ycv_first_chunk, (void*)next_version->ycv_last_chunk); next_version = next_version->ycv_prior; } fprintf(fp, " + %p %08x %08x %0" PRIxOFF "\n", (void*) chunk, chunk->ycc_chunk_id, chunk->ycc_seq_number, chunk->ycc_offset); chunk = chunk->ycc_prev; } } /* static void yaffscache_objects_dump(FILE *fp, YAFFSFS_INFO *yfs) { YaffsCacheObject *obj; for(obj = yfs->cache_objects; obj != NULL; obj = obj->yco_next) yaffscache_object_dump(fp, obj); } */ static void yaffscache_objects_stats(YAFFSFS_INFO *yfs, unsigned int *obj_count, uint32_t *obj_first, uint32_t *obj_last, uint32_t *version_count, uint32_t *version_first, uint32_t *version_last) { YaffsCacheObject *obj; YaffsCacheVersion *ver; /* deleted and unlinked special objects don't have headers */ *obj_count = 2; *obj_first = 0xffffffff; *obj_last = 0; *version_count = 0; *version_first = 0xffffffff; *version_last = 0; for(obj = yfs->cache_objects; obj != NULL; obj = obj->yco_next) { *obj_count += 1; if (obj->yco_obj_id < *obj_first) *obj_first = obj->yco_obj_id; if (obj->yco_obj_id > *obj_last) *obj_last = obj->yco_obj_id; for(ver = obj->yco_latest; ver != NULL; ver = ver->ycv_prior) { *version_count += 1; if (ver->ycv_seq_number < *version_first) *version_first = ver->ycv_seq_number; if (ver->ycv_seq_number > *version_last) *version_last = ver->ycv_seq_number; } } } static void yaffscache_objects_free(YAFFSFS_INFO *yfs) { if((yfs != NULL) && (yfs->cache_objects != NULL)){ YaffsCacheObject *obj = yfs->cache_objects; while(obj != NULL) { YaffsCacheObject *to_free = obj; YaffsCacheVersion *ver = obj->yco_latest; while(ver != NULL) { YaffsCacheVersion *v_to_free = ver; ver = ver->ycv_prior; free(v_to_free); } obj = obj->yco_next; free(to_free); } } } static void yaffscache_chunks_free(YAFFSFS_INFO *yfs) { if((yfs != NULL) && (yfs->chunkMap != NULL)){ // Free the YaffsCacheChunks in each ChunkGroup std::map<unsigned int,YaffsCacheChunkGroup>::iterator iter; for( iter = yfs->chunkMap->begin(); iter != yfs->chunkMap->end(); ++iter ) { YaffsCacheChunk *chunk = yfs->chunkMap->operator[](iter->first).cache_chunks_head; while(chunk != NULL) { YaffsCacheChunk *to_free = chunk; chunk = chunk->ycc_next; free(to_free); } } // Free the map yfs->chunkMap->clear(); delete yfs->chunkMap; } } /* * Parsing and helper functions * * */ /* Function to parse config file * * @param img_info Image info for this image * @param map<string, int> Stores values from config file indexed on parameter name * @returns YAFFS_CONFIG_STATUS One of YAFFS_CONFIG_OK, YAFFS_CONFIG_FILE_NOT_FOUND, or YAFFS_CONFIG_ERROR */ static YAFFS_CONFIG_STATUS yaffs_load_config_file(TSK_IMG_INFO * a_img_info, std::map<std::string, std::string> & results){ size_t config_file_name_len; TSK_TCHAR * config_file_name; FILE* config_file; char buf[1001]; // Ensure there is at least one image name if(a_img_info->num_img < 1){ return YAFFS_CONFIG_ERROR; } // Construct the name of the config file from the first image name config_file_name_len = TSTRLEN(a_img_info->images[0]); config_file_name_len += TSTRLEN(YAFFS_CONFIG_FILE_SUFFIX); config_file_name = (TSK_TCHAR *) tsk_malloc(sizeof(TSK_TCHAR) * (config_file_name_len + 1)); TSTRNCPY(config_file_name, a_img_info->images[0], TSTRLEN(a_img_info->images[0]) + 1); TSTRNCAT(config_file_name, YAFFS_CONFIG_FILE_SUFFIX, TSTRLEN(YAFFS_CONFIG_FILE_SUFFIX) + 1); #ifdef TSK_WIN32 HANDLE hWin; if ((hWin = CreateFile(config_file_name, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0)) == INVALID_HANDLE_VALUE) { // For the moment, assume that the file just doesn't exist, which isn't an error free(config_file_name); return YAFFS_CONFIG_FILE_NOT_FOUND; } config_file = _fdopen(_open_osfhandle((intptr_t) hWin, _O_RDONLY), "r"); if (config_file == NULL) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffs_load_config: Error converting Windows handle to C handle"); free(config_file_name); CloseHandle(hWin); return YAFFS_CONFIG_ERROR; } #else if (NULL == (config_file = fopen(config_file_name, "r"))) { free(config_file_name); return YAFFS_CONFIG_FILE_NOT_FOUND; } #endif while(fgets(buf, 1000, config_file) != NULL){ // Is it a comment? if((buf[0] == '#') || (buf[0] == ';')){ continue; } // Is there a '=' ? if(strchr(buf, '=') == NULL){ continue; } // Copy to strings while removing whitespace and converting to lower case std::string paramName(""); std::string paramVal(""); const char * paramNamePtr = strtok(buf, "="); while(*paramNamePtr != '\0'){ if(! isspace((char)(*paramNamePtr))){ paramName += tolower((char)(*paramNamePtr)); } paramNamePtr++; } const char * paramValPtr = strtok(NULL, "="); while(*paramValPtr != '\0'){ if(! isspace(*paramValPtr)){ paramVal += tolower((char)(*paramValPtr)); } paramValPtr++; } // Make sure this parameter is not already in the map if(results.find(paramName) != results.end()){ // Duplicate parameter - return an error tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffs_load_config: Duplicate parameter name in config file (\"%s\"). %s", paramName.c_str(), YAFFS_HELP_MESSAGE); fclose(config_file); free(config_file_name); return YAFFS_CONFIG_ERROR; } // Add this entry to the map results[paramName] = paramVal; } fclose(config_file); free(config_file_name); return YAFFS_CONFIG_OK; } /* * Helper function for yaffs_validate_config * Tests that a string consists only of digits and has at least one digit * (Can modify later if we want negative fields to be valid) * * @param numStr String to test * @returns 1 on error, 0 on success */ static int yaffs_validate_integer_field(std::string numStr){ unsigned int i; // Test if empty if(numStr.length() == 0){ return 1; } // Test each character for(i = 0;i < numStr.length();i++){ if(isdigit(numStr[i]) == 0){ return 1; } } return 0; } /* * Function to validate the contents of the config file * Currently testing: * All YAFFS_CONFIG fields should be integers (if they exist) * Either need all three of YAFFS_CONFIG_SEQ_NUM_STR, YAFFS_CONFIG_OBJ_ID_STR, YAFFS_CONFIG_CHUNK_ID_STR * or none of them * * @param paramMap Holds mapping of parameter name to parameter value * @returns 1 on error (invalid parameters), 0 on success */ static int yaffs_validate_config_file(std::map<std::string, std::string> & paramMap){ int offset_field_count; // Make a list of all fields to test std::set<std::string> integerParams; integerParams.insert(YAFFS_CONFIG_SEQ_NUM_STR); integerParams.insert(YAFFS_CONFIG_OBJ_ID_STR); integerParams.insert(YAFFS_CONFIG_CHUNK_ID_STR); integerParams.insert(YAFFS_CONFIG_PAGE_SIZE_STR); integerParams.insert(YAFFS_CONFIG_SPARE_SIZE_STR); integerParams.insert(YAFFS_CONFIG_CHUNKS_PER_BLOCK_STR); // If the parameter is set, verify that the value is an int for(std::set<std::string>::iterator it = integerParams.begin();it != integerParams.end();it++){ if((paramMap.find(*it) != paramMap.end()) && (0 != yaffs_validate_integer_field(paramMap[*it]))){ tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffs_validate_config_file: Empty or non-integer value for Yaffs2 parameter \"%s\". %s", (*it).c_str(), YAFFS_HELP_MESSAGE); return 1; } } // Check that we have all three spare offset fields, or none of the three offset_field_count = 0; if(paramMap.find(YAFFS_CONFIG_SEQ_NUM_STR) != paramMap.end()){ offset_field_count++; } if(paramMap.find(YAFFS_CONFIG_OBJ_ID_STR) != paramMap.end()){ offset_field_count++; } if(paramMap.find(YAFFS_CONFIG_CHUNK_ID_STR) != paramMap.end()){ offset_field_count++; } if(! ((offset_field_count == 0) || (offset_field_count == 3))){ tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffs_validate_config_file: Require either all three spare offset fields or none. %s", YAFFS_HELP_MESSAGE); return 1; } // Make sure there aren't any unexpected fields present for(std::map<std::string, std::string>::iterator it = paramMap.begin(); it != paramMap.end();it++){ if(integerParams.find(it->first) == integerParams.end()){ tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffs_validate_config_file: Found unexpected field in config file (\"%s\"). %s", it->first.c_str(), YAFFS_HELP_MESSAGE); return 1; } } return 0; } /* * Function to attempt to determine the layout of the yaffs spare area. * Results of the analysis (if the format could be determined) will be stored * in yfs variables. * * @param yfs File system being analyzed * @param maxBlocksToTest Number of block groups to scan to detect spare area or 0 if there is no limit. * @returns TSK_ERR if format could not be detected and TSK_OK if it could be. */ static TSK_RETVAL_ENUM yaffs_initialize_spare_format(YAFFSFS_INFO * yfs, TSK_OFF_T maxBlocksToTest){ // Testing parameters - can all be changed unsigned int blocksToTest = 10; // Number of blocks (64 chunks) to test unsigned int chunksToTest = 10; // Number of chunks to test in each block unsigned int minChunksRead = 10; // Minimum number of chunks we require to run the test (we might not get the full number we want to test for a very small file) unsigned int chunkSize = yfs->page_size + yfs->spare_size; unsigned int blockSize = yfs->chunks_per_block * chunkSize; TSK_FS_INFO *fs = &(yfs->fs_info); unsigned char *spareBuffer; unsigned int blockIndex; unsigned int chunkIndex; unsigned int currentOffset; unsigned char * allSpares; unsigned int allSparesLength; TSK_OFF_T maxBlocks; bool skipBlock; int goodOffset; unsigned int nGoodSpares; unsigned int nBlocksTested; int okOffsetFound = 0; // Used as a flag for if we've found an offset that sort of works but doesn't seem great int goodOffsetFound = 0; // Flag to mark that we've found an offset that also passed secondary testing int bestOffset = 0; bool allSameByte; // Used in test that the spare area fields not be one repeated byte unsigned int i; int thisChunkBase; int lastChunkBase; // The spare area needs to be at least 16 bytes to run the test if(yfs->spare_size < 16){ if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format failed - given spare size (%d) is not large enough to contain needed fields\n", yfs->spare_size); } return TSK_ERR; } if ((spareBuffer = (unsigned char*) tsk_malloc(yfs->spare_size)) == NULL) { return TSK_ERR; } allSparesLength = yfs->spare_size * blocksToTest * chunksToTest; if ((allSpares = (unsigned char*) tsk_malloc(allSparesLength)) == NULL) { free(spareBuffer); return TSK_ERR; } // Initialize the pointers to one of the configurations we've seen (thought these defaults should not get used) yfs->spare_seq_offset = 0; yfs->spare_obj_id_offset = 4; yfs->spare_chunk_id_offset = 8; yfs->spare_nbytes_offset = 12; // Assume the data we want is 16 consecutive bytes in the order: // seq num, obj id, chunk id, byte count // (not sure we're guaranteed this but we wouldn't be able to deal with the alternative anyway) // Seq num is the important one. This number is constant in each block (block = 64 chunks), meaning // all chunks in a block will share the same sequence number. The YAFFS2 descriptions would seem to // indicate it should be different for each block, but this doesn't seem to always be the case. // In particular we frequently see the 0x1000 seq number used over multiple blocks, but this isn't the only // observed exception. // Calculate the number of blocks in the image maxBlocks = yfs->fs_info.img_info->size / (yfs->chunks_per_block * chunkSize); // If maxBlocksToTest = 0 (unlimited), set it to the total number of blocks // Also reduce the number of blocks to test if it is larger than the total number of blocks if ((maxBlocksToTest == 0) || (maxBlocksToTest > maxBlocks)){ maxBlocksToTest = maxBlocks; } nGoodSpares = 0; nBlocksTested = 0; for (TSK_OFF_T blockIndex = 0;blockIndex < maxBlocksToTest;blockIndex++){ // Read the last spare area that we want to test first TSK_OFF_T offset = (TSK_OFF_T)blockIndex * blockSize + (chunksToTest - 1) * chunkSize + yfs->page_size; ssize_t cnt = tsk_img_read(fs->img_info, offset, (char *) spareBuffer, yfs->spare_size); if ((cnt < 0) || ((unsigned int)cnt < yfs->spare_size)) { break; } // Is the spare all 0xff / 0x00? // If not, we know we should have all allocated chunks since YAFFS2 writes sequentially in a block // - can't have an unallocated chunk followed by an allocated one // We occasionally see almost all null spare area with a few 0xff, which is not a valid spare. skipBlock = true; for (i = 0;i < yfs->spare_size;i++){ if((spareBuffer[i] != 0xff) && (spareBuffer[i] != 0x00)){ skipBlock = false; break; } } if (skipBlock){ continue; } // If this block is potentialy valid (i.e., the spare contains something besides 0x00 and 0xff), copy all the spares into // the big array of extracted spare areas // Copy this spare area nGoodSpares++; for (i = 0;i < yfs->spare_size;i++){ allSpares[nBlocksTested * yfs->spare_size * chunksToTest + (chunksToTest - 1) * yfs->spare_size + i] = spareBuffer[i]; } // Copy all earlier spare areas in the block for (chunkIndex = 0;chunkIndex < chunksToTest - 1;chunkIndex++){ offset = blockIndex * blockSize + chunkIndex * chunkSize + yfs->page_size; cnt = tsk_img_read(fs->img_info, offset, (char *) spareBuffer, yfs->spare_size); if ((cnt < 0) || ((unsigned int)cnt < yfs->spare_size)) { // We really shouldn't run out of data here since we already read in the furthest entry break; // Break out of chunksToTest loop } nGoodSpares++; for(i = 0;i < yfs->spare_size;i++){ allSpares[nBlocksTested * yfs->spare_size * chunksToTest + chunkIndex * yfs->spare_size + i] = spareBuffer[i]; } } // Record that we've found a potentially valid block nBlocksTested++; // If we've found enough potentailly valid blocks, break if (nBlocksTested >= blocksToTest){ break; } } // Make sure we read enough data to reasonably perform the testing if (nGoodSpares < minChunksRead){ if (tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format failed - not enough potentially valid data could be read\n"); } free(spareBuffer); free(allSpares); return TSK_ERR; } if (tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Testing potential offsets for the sequence number in the spare area\n"); } // Print out the collected spare areas if we're in verbose mode if(tsk_verbose && (! yfs->autoDetect)){ for(blockIndex = 0;blockIndex < nBlocksTested;blockIndex++){ for(chunkIndex = 0;chunkIndex < chunksToTest;chunkIndex++){ for(i = 0;i < yfs->spare_size;i++){ fprintf(stderr, "%02x", allSpares[blockIndex * yfs->spare_size * chunksToTest + chunkIndex * yfs->spare_size + i]); } fprintf(stderr, "\n"); } } } // Test all indices into the spare area (that leave enough space for all 16 bytes) for(currentOffset = 0;currentOffset <= yfs->spare_size - 16;currentOffset++){ goodOffset = 1; for(blockIndex = 0;blockIndex < nBlocksTested;blockIndex++){ for(chunkIndex = 1;chunkIndex < chunksToTest;chunkIndex++){ lastChunkBase = blockIndex * yfs->spare_size * chunksToTest + (chunkIndex - 1) * yfs->spare_size; thisChunkBase = lastChunkBase + yfs->spare_size; // Seq num should not be all 0xff (we tested earlier that the chunk has been initialized) if((0xff == allSpares[thisChunkBase + currentOffset]) && (0xff == allSpares[thisChunkBase + currentOffset + 1]) && (0xff == allSpares[thisChunkBase + currentOffset + 2]) && (0xff == allSpares[thisChunkBase + currentOffset + 3])){ if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Eliminating offset %d - invalid sequence number 0xffffffff\n", currentOffset); } goodOffset = 0; break; } // Seq num should not be zero if((0 == allSpares[thisChunkBase + currentOffset]) && (0 == allSpares[thisChunkBase + currentOffset + 1]) && (0 == allSpares[thisChunkBase + currentOffset + 2]) && (0 == allSpares[thisChunkBase + currentOffset + 3])){ if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Eliminating offset %d - invalid sequence number 0\n", currentOffset); } goodOffset = 0; break; } // Seq num should match the previous one in the block if((allSpares[lastChunkBase + currentOffset] != allSpares[thisChunkBase + currentOffset]) || (allSpares[lastChunkBase + currentOffset + 1] != allSpares[thisChunkBase + currentOffset + 1]) || (allSpares[lastChunkBase + currentOffset + 2] != allSpares[thisChunkBase + currentOffset + 2]) || (allSpares[lastChunkBase + currentOffset + 3] != allSpares[thisChunkBase + currentOffset + 3])){ if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Eliminating offset %d - did not match previous chunk sequence number\n", currentOffset); } goodOffset = 0; break; } // Obj id should not be zero if((0 == allSpares[thisChunkBase + currentOffset + 4]) && (0 == allSpares[thisChunkBase + currentOffset + 5]) && (0 == allSpares[thisChunkBase + currentOffset + 6]) && (0 == allSpares[thisChunkBase + currentOffset + 7])){ if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Eliminating offset %d - invalid object id 0\n", currentOffset); } goodOffset = 0; break; } // All 16 bytes should not be the same // (It is theoretically possible that this could be valid, but incredibly unlikely) allSameByte = true; for(i = 1;i < 16;i++){ if(allSpares[thisChunkBase + currentOffset] != allSpares[thisChunkBase + currentOffset + i]){ allSameByte = false; break; } } if(allSameByte){ if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Eliminating offset %d - all repeated bytes\n", currentOffset); } goodOffset = 0; break; } } // End of loop over chunks if(!goodOffset){ // Break out of loop over blocks break; } } if(goodOffset){ // Note that we've found an offset that is at least promising if((! goodOffsetFound) && (! okOffsetFound)){ bestOffset = currentOffset; } okOffsetFound = 1; if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Found potential spare offsets: %d (sequence number), %d (object id), %d (chunk id), %d (n bytes)\n", currentOffset, currentOffset+4, currentOffset+8, currentOffset+12); } // Now do some more tests // Really need some more real-world test data to do this right. int possibleError = 0; // We probably don't want the first byte to always be 0xff int firstByteFF = 1; for(blockIndex = 0;blockIndex < nBlocksTested;blockIndex++){ for(chunkIndex = 1;chunkIndex < chunksToTest;chunkIndex++){ if(allSpares[blockIndex * yfs->spare_size * chunksToTest + chunkIndex * yfs->spare_size + currentOffset] != 0xff){ firstByteFF = 0; } } } if(firstByteFF){ if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Previous data starts with all 0xff bytes. Looking for better offsets.\n"); } possibleError = 1; } if(! possibleError){ // If we already have a good offset, print this one out but don't record it if(! goodOffsetFound){ goodOffsetFound = 1; bestOffset = currentOffset; // Offset passed additional testing and we haven't seen an earlier good one, so go ahead and use it if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Previous offsets appear good - will use as final offsets\n"); } } else{ // Keep using the old one if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Previous offsets appear good but staying with earlier valid ones\n"); } } } } } free(spareBuffer); free(allSpares); if(okOffsetFound || goodOffsetFound){ // Record everything yfs->spare_seq_offset = bestOffset; yfs->spare_obj_id_offset = bestOffset + 4; yfs->spare_chunk_id_offset = bestOffset + 8; yfs->spare_nbytes_offset = bestOffset + 12; if(tsk_verbose && (! yfs->autoDetect)){ tsk_fprintf(stderr, "yaffs_initialize_spare_format: Final offsets: %d (sequence number), %d (object id), %d (chunk id), %d (n bytes)\n", bestOffset, bestOffset+4, bestOffset+8, bestOffset+12); tsk_fprintf(stderr, "If these do not seem valid: %s\n", YAFFS_HELP_MESSAGE); } return TSK_OK; } else{ return TSK_ERR; } } /** * yaffsfs_read_header( ... ) * */ static uint8_t yaffsfs_read_header(YAFFSFS_INFO *yfs, YaffsHeader ** header, TSK_OFF_T offset) { unsigned char *hdr; ssize_t cnt; YaffsHeader *head; TSK_FS_INFO *fs = &(yfs->fs_info); if ((hdr = (unsigned char*) tsk_malloc(yfs->page_size)) == NULL) { return 1; } cnt = tsk_img_read(fs->img_info, offset, (char *) hdr, yfs->page_size); if ((cnt < 0) || ((unsigned int)cnt < yfs->page_size)) { free(hdr); return 1; } if ((head = (YaffsHeader*) tsk_malloc( sizeof(YaffsHeader))) == NULL) { free(hdr); return 1; } memcpy(&head->obj_type, hdr, 4); memcpy(&head->parent_id, &hdr[4], 4); memcpy(head->name, (char*) &hdr[0xA], YAFFS_HEADER_NAME_LENGTH); memcpy(&head->file_mode, &hdr[0x10C], 4); memcpy(&head->user_id, &hdr[0x110], 4); memcpy(&head->group_id, &hdr[0x114], 4); memcpy(&head->atime, &hdr[0x118], 4); memcpy(&head->mtime, &hdr[0x11C], 4); memcpy(&head->ctime, &hdr[0x120], 4); memcpy(&head->file_size, &hdr[0x124], 4); memcpy(&head->equivalent_id, &hdr[0x128], 4); memcpy(head->alias, (char*) &hdr[0x12C], YAFFS_HEADER_ALIAS_LENGTH); //memcpy(&head->rdev_mode, &hdr[0x1CC], 4); //memcpy(&head->win_ctime, &hdr[0x1D0], 8); //memcpy(&head->win_atime, &hdr[0x1D8], 8); //memcpy(&head->win_mtime, &hdr[0x1E0], 8); //memcpy(&head->inband_obj_id, &hdr[0x1E8], 4); //memcpy(&head->inband_is_shrink, &hdr[0x1EC], 4); // NOTE: This isn't in Android 3.3 kernel but is in YAFFS2 git //memcpy(&head->file_size_high, &hdr[0x1F0], 4); free(hdr); *header = head; return 0; } /** * Read and parse the YAFFS2 tags in the NAND spare bytes. * * @param info is a YAFFS fs handle * @param spare YaffsSpare object to be populated * @param offset, offset to read from * * @returns 0 on success and 1 on error */ static uint8_t yaffsfs_read_spare(YAFFSFS_INFO *yfs, YaffsSpare ** spare, TSK_OFF_T offset) { unsigned char *spr; ssize_t cnt; YaffsSpare *sp; TSK_FS_INFO *fs = &(yfs->fs_info); uint32_t seq_number; uint32_t object_id; uint32_t chunk_id; // Should have checked this by now, but just in case if((yfs->spare_seq_offset + 4 > yfs->spare_size) || (yfs->spare_obj_id_offset + 4 > yfs->spare_size) || (yfs->spare_chunk_id_offset + 4 > yfs->spare_size)){ return 1; } if ((spr = (unsigned char*) tsk_malloc(yfs->spare_size)) == NULL) { return 1; } if (yfs->spare_size < 46) { // Why is this 46? tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr("yaffsfs_read_spare: spare size is too small"); free(spr); return 1; } cnt = tsk_img_read(fs->img_info, offset, (char*) spr, yfs->spare_size); if ((cnt < 0) || ((unsigned int)cnt < yfs->spare_size)) { // couldn't read sufficient bytes... if (spare) { free(spr); *spare = NULL; } return 1; } if ((sp = (YaffsSpare*) tsk_malloc(sizeof(YaffsSpare))) == NULL) { return 1; } memset(sp, 0, sizeof(YaffsSpare)); /* * Complete read of the YAFFS2 spare */ // The format of the spare area should have been determined earlier memcpy(&seq_number, &spr[yfs->spare_seq_offset], 4); memcpy(&object_id, &spr[yfs->spare_obj_id_offset], 4); memcpy(&chunk_id, &spr[yfs->spare_chunk_id_offset], 4); if ((YAFFS_SPARE_FLAGS_IS_HEADER & chunk_id) != 0) { sp->seq_number = seq_number; sp->object_id = object_id & ~YAFFS_SPARE_OBJECT_TYPE_MASK; sp->chunk_id = 0; sp->has_extra_fields = 1; sp->extra_parent_id = chunk_id & YAFFS_SPARE_PARENT_ID_MASK; sp->extra_object_type = (object_id & YAFFS_SPARE_OBJECT_TYPE_MASK) >> YAFFS_SPARE_OBJECT_TYPE_SHIFT; } else { sp->seq_number = seq_number; sp->object_id = object_id; sp->chunk_id = chunk_id; sp->has_extra_fields = 0; } free(spr); *spare = sp; return 0; } static uint8_t yaffsfs_is_spare_valid(YAFFSFS_INFO * /*yfs*/, YaffsSpare *spare) { if (spare == NULL) { return 1; } if ((spare->object_id > YAFFS_MAX_OBJECT_ID) || (spare->seq_number < YAFFS_LOWEST_SEQUENCE_NUMBER) || (spare->seq_number > YAFFS_HIGHEST_SEQUENCE_NUMBER)) { return 1; } return 0; } static uint8_t yaffsfs_read_chunk(YAFFSFS_INFO *yfs, YaffsHeader **header, YaffsSpare **spare, TSK_OFF_T offset) { TSK_OFF_T header_offset = offset; TSK_OFF_T spare_offset = offset + yfs->page_size; if (header == NULL || spare == NULL) { return 1; } if (yaffsfs_read_header(yfs, header, header_offset) != 0) { return 1; } if (yaffsfs_read_spare(yfs, spare, spare_offset) != 0) { free(*header); *header = NULL; return 1; } return 0; } /** * Cycle through the entire image and populate the cache with objects as they are found. */ static uint8_t yaffsfs_parse_image_load_cache(YAFFSFS_INFO * yfs) { uint8_t status = TSK_OK; uint32_t nentries = 0; YaffsSpare *spare = NULL; uint8_t tempBuf[8]; uint32_t parentID; if (yfs->cache_objects) return 0; for(TSK_OFF_T offset = 0;offset < yfs->fs_info.img_info->size;offset += yfs->page_size + yfs->spare_size){ status = yaffsfs_read_spare( yfs, &spare, offset + yfs->page_size); if (status != TSK_OK) { break; } if (yaffsfs_is_spare_valid(yfs, spare) == TSK_OK) { if((spare->has_extra_fields) || (spare->chunk_id != 0)){ yaffscache_chunk_add(yfs, offset, spare->seq_number, spare->object_id, spare->chunk_id, spare->extra_parent_id); } else{ // If we have a header block and didn't extract it already from the spare, get the parent ID from // the non-spare data if(8 == tsk_img_read(yfs->fs_info.img_info, offset, (char*) tempBuf, 8)){ memcpy(&parentID, &tempBuf[4], 4); yaffscache_chunk_add(yfs, offset, spare->seq_number, spare->object_id, spare->chunk_id, parentID); } else{ // Really shouldn't happen fprintf(stderr, "Error reading header to get parent id at offset %" PRIxOFF "\n", offset); yaffscache_chunk_add(yfs, offset, spare->seq_number, spare->object_id, spare->chunk_id, 0); } } } free(spare); spare = NULL; ++nentries; } if (tsk_verbose) fprintf(stderr, "yaffsfs_parse_image_load_cache: read %d entries\n", nentries); if (tsk_verbose) fprintf(stderr, "yaffsfs_parse_image_load_cache: started processing chunks for version cache...\n"); fflush(stderr); // At this point, we have a list of chunks sorted by obj id, seq number, and offset // This makes the list of objects in cache_objects, which link to different versions yaffscache_versions_compute(yfs); if (tsk_verbose) fprintf(stderr, "yaffsfs_parse_image_load_cache: done version cache!\n"); fflush(stderr); // Having multiple inodes point to the same object seems to cause trouble in TSK, especially in orphan file detection, // so set the version number of the final one to zero. // While we're at it, find the highest obj_id and the highest version (before resetting to zero) YaffsCacheObject * currObj = yfs->cache_objects; YaffsCacheVersion * currVer; while(currObj != NULL){ if(currObj->yco_obj_id > yfs->max_obj_id){ yfs->max_obj_id = currObj->yco_obj_id; } currVer = currObj->yco_latest; if(currVer->ycv_version > yfs->max_version){ yfs->max_version = currVer->ycv_version; } currVer->ycv_version = 0; currObj = currObj->yco_next; } // Use the max object id and version number to construct an upper bound on the inode TSK_INUM_T max_inum = 0; if (TSK_OK != yaffscache_obj_id_and_version_to_inode(yfs->max_obj_id, yfs->max_version, &max_inum)) { return TSK_ERR; } yfs->fs_info.last_inum = max_inum + 1; // One more for the orphan dir // Make sure the orphan dir is greater than the root dir if (yfs->fs_info.last_inum <= yfs->fs_info.root_inum) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr( "yaffsfs_parse_image_load_cache: Maximum inum %" PRIuINUM " is not greater than the root inum", yfs->fs_info.last_inum); return TSK_ERR; } return TSK_OK; } // A version is allocated if: // 1. This version is pointed to by yco_latest // 2. This version didn't have a delete/unlinked header after the most recent copy of the normal header static uint8_t yaffs_is_version_allocated(YAFFSFS_INFO * yfs, TSK_INUM_T inode){ YaffsCacheObject * obj; YaffsCacheVersion * version; YaffsCacheChunk * curr; TSK_RETVAL_ENUM result = yaffscache_version_find_by_inode(yfs, inode, &version, &obj); if (result != TSK_OK) { if (tsk_verbose) tsk_fprintf(stderr, "yaffs_is_version_allocated: yaffscache_version_find_by_inode failed! (inode: %d)\n", inode); return 0; } if(obj->yco_latest == version){ curr = obj->yco_latest->ycv_header_chunk; while(curr != NULL){ // We're looking for a newer unlinked or deleted header. If one exists, then this object should be considered unallocated if((curr->ycc_parent_id == YAFFS_OBJECT_UNLINKED) || (curr->ycc_parent_id == YAFFS_OBJECT_DELETED)){ return 0; } curr = curr ->ycc_next; } return 1; } else{ return 0; } } /* * TSK integration * * */ static uint8_t yaffs_make_directory(YAFFSFS_INFO *yaffsfs, TSK_FS_FILE *a_fs_file, TSK_INUM_T inode, const char *name) { TSK_FS_FILE *fs_file = a_fs_file; fs_file->meta->type = TSK_FS_META_TYPE_DIR; fs_file->meta->mode = (TSK_FS_META_MODE_ENUM)0; fs_file->meta->nlink = 1; if((inode == YAFFS_OBJECT_UNLINKED) || (inode == YAFFS_OBJECT_DELETED) || (inode == yaffsfs->fs_info.last_inum)){ fs_file->meta->flags = (TSK_FS_META_FLAG_ENUM)(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_ALLOC); } else{ if(yaffs_is_version_allocated(yaffsfs, inode)){ fs_file->meta->flags = (TSK_FS_META_FLAG_ENUM)(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_ALLOC); } else{ fs_file->meta->flags = (TSK_FS_META_FLAG_ENUM)(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_UNALLOC); } } fs_file->meta->uid = fs_file->meta->gid = 0; fs_file->meta->mtime = fs_file->meta->atime = fs_file->meta->ctime = fs_file->meta->crtime = 0; fs_file->meta->mtime_nano = fs_file->meta->atime_nano = fs_file->meta->ctime_nano = fs_file->meta->crtime_nano = 0; if (fs_file->meta->name2 == NULL) { if ((fs_file->meta->name2 = (TSK_FS_META_NAME_LIST *) tsk_malloc(sizeof(TSK_FS_META_NAME_LIST))) == NULL) { return 1; } fs_file->meta->name2->next = NULL; } if (fs_file->meta->attr != NULL) { tsk_fs_attrlist_markunused(fs_file->meta->attr); } else { fs_file->meta->attr = tsk_fs_attrlist_alloc(); } strncpy(fs_file->meta->name2->name, name, TSK_FS_META_NAME_LIST_NSIZE); fs_file->meta->size = 0; fs_file->meta->attr_state = TSK_FS_META_ATTR_EMPTY; fs_file->meta->addr = inode; return 0; } static uint8_t yaffs_make_regularfile( YAFFSFS_INFO * yaffsfs, TSK_FS_FILE * a_fs_file, TSK_INUM_T inode, const char * name ) { TSK_FS_FILE *fs_file = a_fs_file; fs_file->meta->type = TSK_FS_META_TYPE_REG; fs_file->meta->mode = (TSK_FS_META_MODE_ENUM)0; fs_file->meta->nlink =1; if(yaffs_is_version_allocated(yaffsfs, inode)){ fs_file->meta->flags = (TSK_FS_META_FLAG_ENUM)(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_ALLOC); } else{ fs_file->meta->flags = (TSK_FS_META_FLAG_ENUM)(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_UNALLOC); } fs_file->meta->uid = fs_file->meta->gid = 0; fs_file->meta->mtime = fs_file->meta->atime = fs_file->meta->ctime = fs_file->meta->crtime = 0; fs_file->meta->mtime_nano = fs_file->meta->atime_nano = fs_file->meta->ctime_nano = fs_file->meta->crtime_nano = 0; if (fs_file->meta->name2 == NULL) { if ((fs_file->meta->name2 = (TSK_FS_META_NAME_LIST *) tsk_malloc(sizeof(TSK_FS_META_NAME_LIST))) == NULL) return 1; fs_file->meta->name2->next = NULL; } if (fs_file->meta->attr != NULL) { tsk_fs_attrlist_markunused(fs_file->meta->attr); } else { fs_file->meta->attr = tsk_fs_attrlist_alloc(); } fs_file->meta->addr = inode; strncpy(fs_file->meta->name2->name, name, TSK_FS_META_NAME_LIST_NSIZE); fs_file->meta->size = 0; fs_file->meta->attr_state = TSK_FS_META_ATTR_EMPTY; return 0; } /** * \internal * Create YAFFS2 Deleted Object * * @ param yaffs file system * fs_file to copy file information to * return 1 on error, 0 on success */ static uint8_t yaffs_make_deleted( YAFFSFS_INFO * yaffsfs, TSK_FS_FILE * a_fs_file ) { TSK_FS_FILE *fs_file = a_fs_file; if (tsk_verbose) tsk_fprintf(stderr, "yaffs_make_deleted: Making virtual deleted node\n"); if (yaffs_make_directory(yaffsfs, fs_file, YAFFS_OBJECT_DELETED, YAFFS_OBJECT_DELETED_NAME)) return 1; return 0; } /** * \internal * Create YAFFS2 Unlinked object * * @ param yaffs file system * fs_file to copy file information to * return 1 on error, 0 on success */ static uint8_t yaffs_make_unlinked( YAFFSFS_INFO * yaffsfs, TSK_FS_FILE * a_fs_file ) { TSK_FS_FILE * fs_file = a_fs_file; if (tsk_verbose) tsk_fprintf(stderr, "yaffs_make_unlinked: Making virtual unlinked node\n"); if (yaffs_make_directory(yaffsfs, fs_file, YAFFS_OBJECT_UNLINKED, YAFFS_OBJECT_UNLINKED_NAME)) return 1; return 0; } /** * \internal * Create YAFFS2 orphan object * * @ param yaffs file system * fs_file to copy file information to * return 1 on error, 0 on success */ static uint8_t yaffs_make_orphan_dir( YAFFSFS_INFO * yaffsfs, TSK_FS_FILE * a_fs_file ) { TSK_FS_FILE * fs_file = a_fs_file; TSK_FS_NAME *fs_name = tsk_fs_name_alloc(256, 0); if (fs_name == NULL) return TSK_ERR; if (tsk_verbose) tsk_fprintf(stderr, "yaffs_make_orphan_dir: Making orphan dir node\n"); if (tsk_fs_dir_make_orphan_dir_name(&(yaffsfs->fs_info), fs_name)) { tsk_fs_name_free(fs_name); return TSK_ERR; } if (yaffs_make_directory(yaffsfs, fs_file, yaffsfs->fs_info.last_inum, (char *)fs_name)){ tsk_fs_name_free(fs_name); return 1; } tsk_fs_name_free(fs_name); return 0; } /* yaffsfs_inode_lookup - lookup inode, external interface * * Returns 1 on error and 0 on success * */ static uint8_t yaffs_inode_lookup(TSK_FS_INFO *a_fs, TSK_FS_FILE * a_fs_file, TSK_INUM_T inum) { YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)a_fs; YaffsCacheObject *obj; YaffsCacheVersion *version; YaffsHeader *header = NULL; YaffsSpare *spare = NULL; TSK_RETVAL_ENUM result; uint8_t type; const char *real_name; if (a_fs_file == NULL) { tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr("yaffsfs_inode_lookup: fs_file is NULL"); return 1; } if (a_fs_file->meta == NULL) { if ((a_fs_file->meta = tsk_fs_meta_alloc(YAFFS_FILE_CONTENT_LEN)) == NULL) return 1; } else { tsk_fs_meta_reset(a_fs_file->meta); } if (tsk_verbose) tsk_fprintf(stderr, "yaffs_inode_lookup: looking up %" PRIuINUM "\n",inum); switch(inum) { case YAFFS_OBJECT_UNLINKED: yaffs_make_unlinked(yfs, a_fs_file); return 0; case YAFFS_OBJECT_DELETED: yaffs_make_deleted(yfs, a_fs_file); return 0; } if(inum == yfs->fs_info.last_inum){ yaffs_make_orphan_dir(yfs, a_fs_file); return 0; } result = yaffscache_version_find_by_inode(yfs, inum, &version, &obj); if (result != TSK_OK) { if (tsk_verbose) tsk_fprintf(stderr, "yaffs_inode_lookup: yaffscache_version_find_by_inode failed! (inode = %d)\n", inum); return 1; } if(version->ycv_header_chunk == NULL){ return 1; } if (yaffsfs_read_chunk(yfs, &header, &spare, version->ycv_header_chunk->ycc_offset) != TSK_OK) { if (tsk_verbose) tsk_fprintf(stderr, "yaffs_inode_lookup: yaffsfs_read_chunk failed!\n"); return 1; } type = header->obj_type; switch(inum) { case YAFFS_OBJECT_LOSTNFOUND: real_name = YAFFS_OBJECT_LOSTNFOUND_NAME; break; case YAFFS_OBJECT_UNLINKED: real_name = YAFFS_OBJECT_UNLINKED_NAME; break; case YAFFS_OBJECT_DELETED: real_name = YAFFS_OBJECT_DELETED_NAME; break; default: real_name = header->name; break; } switch(type) { case YAFFS_TYPE_FILE: if (tsk_verbose) tsk_fprintf(stderr, "yaffs_inode_lookup: is a file\n"); yaffs_make_regularfile(yfs, a_fs_file, inum, real_name); break; case YAFFS_TYPE_DIRECTORY: if (tsk_verbose) tsk_fprintf(stderr, "yaffs_inode_lookup: is a directory\n"); yaffs_make_directory(yfs, a_fs_file, inum, real_name); break; case YAFFS_TYPE_SOFTLINK: if (tsk_verbose) tsk_fprintf(stderr, "yaffs_inode_lookup: is a symbolic link\n"); yaffs_make_regularfile(yfs, a_fs_file, inum, real_name); a_fs_file->meta->type = TSK_FS_META_TYPE_LNK; break; case YAFFS_TYPE_HARDLINK: case YAFFS_TYPE_UNKNOWN: default: if (tsk_verbose) tsk_fprintf(stderr, "yaffs_inode_lookup: is *** UNHANDLED *** (type %d, header at 0x%x)\n", type, version->ycv_header_chunk->ycc_offset); // We can still set a few things a_fs_file->meta->type = TSK_FS_META_TYPE_UNDEF; a_fs_file->meta->addr = inum; if(yaffs_is_version_allocated(yfs, inum)){ a_fs_file->meta->flags = (TSK_FS_META_FLAG_ENUM)(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_ALLOC); } else{ a_fs_file->meta->flags = (TSK_FS_META_FLAG_ENUM)(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_UNALLOC); } if (a_fs_file->meta->name2 == NULL) { if ((a_fs_file->meta->name2 = (TSK_FS_META_NAME_LIST *) tsk_malloc(sizeof(TSK_FS_META_NAME_LIST))) == NULL){ return 1; } a_fs_file->meta->name2->next = NULL; } strncpy(a_fs_file->meta->name2->name, real_name, TSK_FS_META_NAME_LIST_NSIZE); break; } /* Who owns this? I'm following the way FATFS does it by freeing + NULLing * this and mallocing if used. */ free(a_fs_file->meta->link); a_fs_file->meta->link = NULL; if (type != YAFFS_TYPE_HARDLINK) { a_fs_file->meta->mode = (TSK_FS_META_MODE_ENUM)(header->file_mode & TWELVE_BITS_MASK); // chop at 12 bits; a_fs_file->meta->uid = header->user_id; a_fs_file->meta->gid = header->group_id; a_fs_file->meta->mtime = header->mtime; a_fs_file->meta->atime = header->atime; a_fs_file->meta->ctime = header->ctime; } if (type == YAFFS_TYPE_FILE) { a_fs_file->meta->size = header->file_size; // NOTE: This isn't in Android 3.3 kernel but is in YAFFS2 git //a_fs_file->meta->size |= ((TSK_OFF_T) header->file_size_high) << 32; } if (type == YAFFS_TYPE_HARDLINK) { // TODO: Store equivalent_id somewhere? */ } if (type == YAFFS_TYPE_SOFTLINK) { a_fs_file->meta->link = (char*)tsk_malloc(YAFFS_HEADER_ALIAS_LENGTH); if (a_fs_file->meta->link == NULL) { free(header); free(spare); return 1; } memcpy(a_fs_file->meta->link, header->alias, YAFFS_HEADER_ALIAS_LENGTH); } free(header); free(spare); return 0; } /* yaffsfs_inode_walk - inode iterator * * flags used: TSK_FS_META_FLAG_USED, TSK_FS_META_FLAG_UNUSED, * TSK_FS_META_FLAG_ALLOC, TSK_FS_META_FLAG_UNALLOC, TSK_FS_META_FLAG_ORPHAN * * Return 1 on error and 0 on success */ static uint8_t yaffsfs_inode_walk(TSK_FS_INFO *fs, TSK_INUM_T start_inum, TSK_INUM_T end_inum, TSK_FS_META_FLAG_ENUM flags, TSK_FS_META_WALK_CB a_action, void *a_ptr) { YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)fs; TSK_FS_FILE *fs_file; TSK_RETVAL_ENUM result; uint32_t start_obj_id; uint32_t start_ver_number; uint32_t end_obj_id; uint32_t end_ver_number; uint32_t obj_id; YaffsCacheObject *curr_obj; YaffsCacheVersion *curr_version; result = yaffscache_inode_to_obj_id_and_version(start_inum, &start_obj_id, &start_ver_number); result = yaffscache_inode_to_obj_id_and_version(end_inum, &end_obj_id, &end_ver_number); if (end_obj_id < start_obj_id) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_WALK_RNG); tsk_error_set_errstr("yaffsfs_inode_walk: end object id must be >= start object id: " "%" PRIx32 " must be >= %" PRIx32 "", end_obj_id, start_obj_id); return 1; } /* The ORPHAN flag is unsupported for YAFFS2 */ if (flags & TSK_FS_META_FLAG_ORPHAN) { if (tsk_verbose){ tsk_fprintf(stderr, "yaffsfs_inode_walk: ORPHAN flag unsupported by YAFFS2"); } } if (((flags & TSK_FS_META_FLAG_ALLOC) == 0) && ((flags & TSK_FS_META_FLAG_UNALLOC) == 0)) { flags = (TSK_FS_META_FLAG_ENUM)(flags | TSK_FS_META_FLAG_ALLOC | TSK_FS_META_FLAG_UNALLOC); } /* If neither of the USED or UNUSED flags are set, then set them * both */ if (((flags & TSK_FS_META_FLAG_USED) == 0) && ((flags & TSK_FS_META_FLAG_UNUSED) == 0)) { flags = (TSK_FS_META_FLAG_ENUM)(flags | TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_UNUSED); } if ((fs_file = tsk_fs_file_alloc(fs)) == NULL) return 1; if ((fs_file->meta = tsk_fs_meta_alloc(YAFFS_FILE_CONTENT_LEN)) == NULL) return 1; for (obj_id = start_obj_id; obj_id <= end_obj_id; obj_id++) { int retval; result = yaffscache_version_find_by_inode(yfs, obj_id, &curr_version, &curr_obj); if (result == TSK_OK) { TSK_INUM_T curr_inode; YaffsCacheVersion *version; // ALLOC, UNALLOC, or both are set at this point if (flags & TSK_FS_META_FLAG_ALLOC) { // Allocated only - just look at current version if (yaffscache_obj_id_and_version_to_inode(obj_id, curr_obj->yco_latest->ycv_version, &curr_inode) != TSK_OK) { tsk_fs_file_close(fs_file); return 1; } // It's possible for the current version to be unallocated if the last header was a deleted or unlinked header if(yaffs_is_version_allocated(yfs, curr_inode)){ if (yaffs_inode_lookup(fs, fs_file, curr_inode) != TSK_OK) { tsk_fs_file_close(fs_file); return 1; } retval = a_action(fs_file, a_ptr); if (retval == TSK_WALK_STOP) { tsk_fs_file_close(fs_file); return 0; } else if (retval == TSK_WALK_ERROR) { tsk_fs_file_close(fs_file); return 1; } } } if (flags & TSK_FS_META_FLAG_UNALLOC){ for (version = curr_obj->yco_latest; version != NULL; version = version->ycv_prior) { if (yaffscache_obj_id_and_version_to_inode(obj_id, version->ycv_version, &curr_inode) != TSK_OK) { tsk_fs_file_close(fs_file); return 1; } if(! yaffs_is_version_allocated(yfs, curr_inode)){ if (yaffs_inode_lookup(fs, fs_file, curr_inode) != TSK_OK) { tsk_fs_file_close(fs_file); return 1; } retval = a_action(fs_file, a_ptr); if (retval == TSK_WALK_STOP) { tsk_fs_file_close(fs_file); return 0; } else if (retval == TSK_WALK_ERROR) { tsk_fs_file_close(fs_file); return 1; } } } } curr_obj = curr_obj->yco_next; } } /* * Cleanup. */ tsk_fs_file_close(fs_file); return 0; } static TSK_FS_BLOCK_FLAG_ENUM yaffsfs_block_getflags(TSK_FS_INFO *fs, TSK_DADDR_T a_addr) { YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)fs; TSK_FS_BLOCK_FLAG_ENUM flags = TSK_FS_BLOCK_FLAG_UNUSED; TSK_OFF_T offset = (a_addr * (fs->block_pre_size + fs->block_size + fs->block_post_size)) + yfs->page_size; YaffsSpare *spare = NULL; YaffsHeader *header = NULL; if (yaffsfs_read_spare(yfs, &spare, offset) != TSK_OK) { /* NOTE: Uh, how do we signal error? */ return flags; } if (yaffsfs_is_spare_valid(yfs, spare) == TSK_OK) { /* XXX: Do we count blocks of older versions unallocated? * If so, we need a smarter way to do this :/ * * Walk the object from this block and see if this * block is used in the latest version. Could pre- * calculate this at cache time as well. */ if (spare->chunk_id == 0) { flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_META); } else { flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_CONT); } // Have obj id and offset // 1. Is the current version of this object allocated? // 2. If this is a header, is it the header of the current version? // 3. Is the chunk id too big given the current header? // 4. Is there a more recent version of this chunk id? YaffsCacheObject * obj = NULL; yaffscache_object_find(yfs, spare->object_id, &obj); // The result really shouldn't be NULL since we loaded every chunk if(obj != NULL){ if(! yaffs_is_version_allocated(yfs, spare->object_id)){ // If the current version isn't allocated, then no chunks in it are flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_UNALLOC); } else if (obj->yco_latest == NULL || obj->yco_latest->ycv_header_chunk == NULL) { flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_UNALLOC); } else if(spare->chunk_id == 0){ if(obj->yco_latest->ycv_header_chunk->ycc_offset == offset - yfs->page_size){ // Have header chunk and it's the most recent header chunk flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_ALLOC); } else{ // Have header chunk but isn't the most recent flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_UNALLOC); } } else{ // Read in the full header yaffsfs_read_header(yfs, &header, obj->yco_latest->ycv_header_chunk->ycc_offset); // chunk_id is 1-based, so for example chunk id 2 would be too big for a file // 500 bytes long if(header->file_size <= ((spare->chunk_id - 1) * (fs->block_size))){ flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_UNALLOC); } else{ // Since at this point we know there should be a chunk with this chunk id in the file, if // this is the most recent version of the chunk assume it's part of the current version of the object. YaffsCacheChunk * curr = obj->yco_latest->ycv_last_chunk; while(curr != NULL){ // curr should really never make it to the beginning of the list // Did we find our chunk? if(curr->ycc_offset == offset - yfs->page_size){ flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_ALLOC); break; } // Did we find a different chunk with our chunk id? if(curr->ycc_chunk_id == spare->chunk_id){ flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_UNALLOC); break; } curr = curr->ycc_prev; } } } } } else { flags = (TSK_FS_BLOCK_FLAG_ENUM)(flags | TSK_FS_BLOCK_FLAG_UNUSED | TSK_FS_BLOCK_FLAG_UNALLOC); } free(spare); free(header); return flags; } /* yaffsfs_block_walk - block iterator * * flags: TSK_FS_BLOCK_FLAG_ALLOC, TSK_FS_BLOCK_FLAG_UNALLOC, TSK_FS_BLOCK_FLAG_CONT, * TSK_FS_BLOCK_FLAG_META * * Return 1 on error and 0 on success */ static uint8_t yaffsfs_block_walk(TSK_FS_INFO *a_fs, TSK_DADDR_T a_start_blk, TSK_DADDR_T a_end_blk, TSK_FS_BLOCK_WALK_FLAG_ENUM a_flags, TSK_FS_BLOCK_WALK_CB a_action, void *a_ptr) { TSK_FS_BLOCK *fs_block; TSK_DADDR_T addr; // clean up any error messages that are lying around tsk_error_reset(); /* * Sanity checks. */ if (a_start_blk < a_fs->first_block || a_start_blk > a_fs->last_block) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_WALK_RNG); tsk_error_set_errstr("yaffsfs_block_walk: start block: %" PRIuDADDR, a_start_blk); return 1; } if (a_end_blk < a_fs->first_block || a_end_blk > a_fs->last_block || a_end_blk < a_start_blk) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_WALK_RNG); tsk_error_set_errstr("yaffsfs_block_walk: end block: %" PRIuDADDR , a_end_blk); return 1; } /* Sanity check on a_flags -- make sure at least one ALLOC is set */ if (((a_flags & TSK_FS_BLOCK_WALK_FLAG_ALLOC) == 0) && ((a_flags & TSK_FS_BLOCK_WALK_FLAG_UNALLOC) == 0)) { a_flags = (TSK_FS_BLOCK_WALK_FLAG_ENUM) (a_flags | TSK_FS_BLOCK_WALK_FLAG_ALLOC | TSK_FS_BLOCK_WALK_FLAG_UNALLOC); } if (((a_flags & TSK_FS_BLOCK_WALK_FLAG_META) == 0) && ((a_flags & TSK_FS_BLOCK_WALK_FLAG_CONT) == 0)) { a_flags = (TSK_FS_BLOCK_WALK_FLAG_ENUM) (a_flags | TSK_FS_BLOCK_WALK_FLAG_CONT | TSK_FS_BLOCK_WALK_FLAG_META); } if ((fs_block = tsk_fs_block_alloc(a_fs)) == NULL) { return 1; } for (addr = a_start_blk; addr <= a_end_blk; addr++) { int retval; int myflags; myflags = yaffsfs_block_getflags(a_fs, addr); // test if we should call the callback with this one if ((myflags & TSK_FS_BLOCK_FLAG_META) && (!(a_flags & TSK_FS_BLOCK_WALK_FLAG_META))) continue; else if ((myflags & TSK_FS_BLOCK_FLAG_CONT) && (!(a_flags & TSK_FS_BLOCK_WALK_FLAG_CONT))) continue; else if ((myflags & TSK_FS_BLOCK_FLAG_ALLOC) && (!(a_flags & TSK_FS_BLOCK_WALK_FLAG_ALLOC))) continue; else if ((myflags & TSK_FS_BLOCK_FLAG_UNALLOC) && (!(a_flags & TSK_FS_BLOCK_WALK_FLAG_UNALLOC))) continue; if (tsk_fs_block_get(a_fs, fs_block, addr) == NULL) { tsk_error_set_errstr2("yaffsfs_block_walk: block %" PRIuDADDR, addr); tsk_fs_block_free(fs_block); return 1; } retval = a_action(fs_block, a_ptr); if (retval == TSK_WALK_STOP) { break; } else if (retval == TSK_WALK_ERROR) { tsk_fs_block_free(fs_block); return 1; } } /* * Cleanup. */ tsk_fs_block_free(fs_block); return 0; } static uint8_t yaffsfs_fscheck(TSK_FS_INFO * /*fs*/, FILE * /*hFile*/) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_UNSUPFUNC); tsk_error_set_errstr("fscheck not implemented yet for YAFFS"); return 1; } /** * Print details about the file system to a file handle. * * @param fs File system to print details on * @param hFile File handle to print text to * * @returns 1 on error and 0 on success */ static uint8_t yaffsfs_fsstat(TSK_FS_INFO * fs, FILE * hFile) { YAFFSFS_INFO *yfs = (YAFFSFS_INFO *) fs; unsigned int obj_count, version_count; uint32_t obj_first, obj_last, version_first, version_last; // clean up any error messages that are lying around tsk_error_reset(); tsk_fprintf(hFile, "FILE SYSTEM INFORMATION\n"); tsk_fprintf(hFile, "--------------------------------------------\n"); tsk_fprintf(hFile, "File System Type: YAFFS2\n"); tsk_fprintf(hFile, "Page Size: %u\n", yfs->page_size); tsk_fprintf(hFile, "Spare Size: %u\n", yfs->spare_size); tsk_fprintf(hFile, "Spare Offsets: Sequence number: %d, Object ID: %d, Chunk ID: %d, nBytes: %d\n", yfs->spare_seq_offset, yfs->spare_obj_id_offset, yfs->spare_chunk_id_offset, yfs->spare_nbytes_offset); tsk_fprintf(hFile, "\nMETADATA INFORMATION\n"); tsk_fprintf(hFile, "--------------------------------------------\n"); yaffscache_objects_stats(yfs, &obj_count, &obj_first, &obj_last, &version_count, &version_first, &version_last); tsk_fprintf(hFile, "Number of Allocated Objects: %u\n", obj_count); tsk_fprintf(hFile, "Object Id Range: %" PRIu32 " - %" PRIu32 "\n", obj_first, obj_last); tsk_fprintf(hFile, "Number of Total Object Versions: %u\n", version_count); tsk_fprintf(hFile, "Object Version Range: %" PRIu32 " - %" PRIu32 "\n", version_first, version_last); return 0; } /************************* istat *******************************/ typedef struct { FILE *hFile; int idx; } YAFFSFS_PRINT_ADDR; /* Callback for istat to print the block addresses */ static TSK_WALK_RET_ENUM print_addr_act(YAFFSFS_INFO * /*fs_file*/, TSK_OFF_T /*a_off*/, TSK_DADDR_T addr, char * /*buf*/, size_t /*size*/, TSK_FS_BLOCK_FLAG_ENUM flags, void *a_ptr) { YAFFSFS_PRINT_ADDR *print = (YAFFSFS_PRINT_ADDR *) a_ptr; if (flags & TSK_FS_BLOCK_FLAG_CONT) { tsk_fprintf(print->hFile, "%" PRIuDADDR " ", addr); if (++(print->idx) == 8) { tsk_fprintf(print->hFile, "\n"); print->idx = 0; } } return TSK_WALK_CONT; } /** * Print details on a specific file to a file handle. * * @param fs File system file is located in * @param hFile File handle to print text to * @param inum Address of file in file system * @param numblock The number of blocks in file to force print (can go beyond file size) * @param sec_skew Clock skew in seconds to also print times in * * @returns 1 on error and 0 on success */ static uint8_t yaffsfs_istat(TSK_FS_INFO *fs, TSK_FS_ISTAT_FLAG_ENUM flags, FILE * hFile, TSK_INUM_T inum, TSK_DADDR_T numblock, int32_t sec_skew) { TSK_FS_META *fs_meta; TSK_FS_FILE *fs_file; YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)fs; char ls[12]; YAFFSFS_PRINT_ADDR print; char timeBuf[128]; YaffsCacheObject * obj = NULL; YaffsCacheVersion * version = NULL; YaffsHeader * header = NULL; yaffscache_version_find_by_inode(yfs, inum, &version, &obj); if ((fs_file = tsk_fs_file_open_meta(fs, NULL, inum)) == NULL) { return 1; } fs_meta = fs_file->meta; tsk_fprintf(hFile, "inode: %" PRIuINUM "\n", inum); tsk_fprintf(hFile, "%sAllocated\n", (fs_meta->flags & TSK_FS_META_FLAG_ALLOC) ? "" : "Not "); if (fs_meta->link) tsk_fprintf(hFile, "symbolic link to: %s\n", fs_meta->link); tsk_fprintf(hFile, "uid / gid: %" PRIuUID " / %" PRIuGID "\n", fs_meta->uid, fs_meta->gid); tsk_fs_meta_make_ls(fs_meta, ls, sizeof(ls)); tsk_fprintf(hFile, "mode: %s\n", ls); tsk_fprintf(hFile, "size: %" PRIdOFF "\n", fs_meta->size); tsk_fprintf(hFile, "num of links: %d\n", fs_meta->nlink); if(version != NULL){ yaffsfs_read_header(yfs, &header, version->ycv_header_chunk->ycc_offset); if(header != NULL){ tsk_fprintf(hFile, "Name: %s\n", header->name); } } if (sec_skew != 0) { tsk_fprintf(hFile, "\nAdjusted Inode Times:\n"); fs_meta->mtime -= sec_skew; fs_meta->atime -= sec_skew; fs_meta->ctime -= sec_skew; tsk_fprintf(hFile, "Accessed:\t%s\n", tsk_fs_time_to_str(fs_meta->atime, timeBuf)); tsk_fprintf(hFile, "File Modified:\t%s\n", tsk_fs_time_to_str(fs_meta->mtime, timeBuf)); tsk_fprintf(hFile, "Inode Modified:\t%s\n", tsk_fs_time_to_str(fs_meta->ctime, timeBuf)); fs_meta->mtime += sec_skew; fs_meta->atime += sec_skew; fs_meta->ctime += sec_skew; tsk_fprintf(hFile, "\nOriginal Inode Times:\n"); } else { tsk_fprintf(hFile, "\nInode Times:\n"); } tsk_fprintf(hFile, "Accessed:\t%s\n", tsk_fs_time_to_str(fs_meta->atime, timeBuf)); tsk_fprintf(hFile, "File Modified:\t%s\n", tsk_fs_time_to_str(fs_meta->mtime, timeBuf)); tsk_fprintf(hFile, "Inode Modified:\t%s\n", tsk_fs_time_to_str(fs_meta->ctime, timeBuf)); if(version != NULL){ tsk_fprintf(hFile, "\nHeader Chunk:\n"); tsk_fprintf(hFile, "%" PRIuDADDR "\n", (version->ycv_header_chunk->ycc_offset / (yfs->page_size + yfs->spare_size))); } if (numblock > 0) { TSK_OFF_T lower_size = numblock * fs->block_size; fs_meta->size = (lower_size < fs_meta->size)?(lower_size):(fs_meta->size); } tsk_fprintf(hFile, "\nData Chunks:\n"); if (flags & TSK_FS_ISTAT_RUNLIST){ const TSK_FS_ATTR *fs_attr_default = tsk_fs_file_attr_get_type(fs_file, TSK_FS_ATTR_TYPE_DEFAULT, 0, 0); if (fs_attr_default && (fs_attr_default->flags & TSK_FS_ATTR_NONRES)) { if (tsk_fs_attr_print(fs_attr_default, hFile)) { tsk_fprintf(hFile, "\nError creating run lists "); tsk_error_print(hFile); tsk_error_reset(); } } } else { print.idx = 0; print.hFile = hFile; if (tsk_fs_file_walk(fs_file, TSK_FS_FILE_WALK_FLAG_AONLY, (TSK_FS_FILE_WALK_CB)print_addr_act, (void *)&print)) { tsk_fprintf(hFile, "\nError reading file: "); tsk_error_print(hFile); tsk_error_reset(); } else if (print.idx != 0) { tsk_fprintf(hFile, "\n"); } } tsk_fs_file_close(fs_file); return 0; } /* yaffsfs_close - close an yaffsfs file system */ static void yaffsfs_close(TSK_FS_INFO *fs) { if(fs != NULL){ YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)fs; fs->tag = 0; // Walk and free the cache structures yaffscache_objects_free(yfs); yaffscache_chunks_free(yfs); //tsk_deinit_lock(&yaffsfs->lock); tsk_fs_free(fs); } } typedef struct _dir_open_cb_args { YAFFSFS_INFO *yfs; TSK_FS_DIR *dir; TSK_INUM_T parent_addr; } dir_open_cb_args; static TSK_RETVAL_ENUM yaffs_dir_open_meta_cb(YaffsCacheObject * /*obj*/, YaffsCacheVersion *version, void *args) { dir_open_cb_args *cb_args = (dir_open_cb_args *) args; YaffsCacheChunk *chunk = version->ycv_header_chunk; TSK_INUM_T curr_inode = 0; uint32_t obj_id = chunk->ycc_obj_id; uint32_t chunk_id = chunk->ycc_chunk_id; uint32_t vnum = version->ycv_version; YaffsHeader *header = NULL; TSK_FS_NAME * fs_name; char *file_ext; char version_string[64]; // Allow a max of 64 bytes in the version string yaffscache_obj_id_and_version_to_inode(obj_id, vnum, &curr_inode); if (chunk_id != 0) { return TSK_ERR; } if (tsk_verbose) fprintf(stderr, "dir_open_find_children_cb: %08" PRIxINUM " -> %08" PRIx32 ":%d\n", cb_args->parent_addr, obj_id, vnum); if (yaffsfs_read_header(cb_args->yfs, &header, chunk->ycc_offset) != TSK_OK) { return TSK_ERR; } if ((fs_name = tsk_fs_name_alloc(YAFFSFS_MAXNAMLEN + 64, 0)) == NULL) { free(header); return TSK_ERR; } switch (obj_id) { case YAFFS_OBJECT_LOSTNFOUND: strncpy(fs_name->name, YAFFS_OBJECT_LOSTNFOUND_NAME, fs_name->name_size - 64); break; case YAFFS_OBJECT_UNLINKED: strncpy(fs_name->name, YAFFS_OBJECT_UNLINKED_NAME, fs_name->name_size - 64); break; case YAFFS_OBJECT_DELETED: strncpy(fs_name->name, YAFFS_OBJECT_DELETED_NAME, fs_name->name_size - 64); break; default: strncpy(fs_name->name, header->name, fs_name->name_size - 64); break; } fs_name->name[fs_name->name_size - 65] = 0; // Only put object/version string onto unallocated versions if(! yaffs_is_version_allocated(cb_args->yfs, curr_inode)){ // Also copy the extension so that it also shows up after the version string, which allows // easier searching by file extension. Max extension length is 5 characters after the dot, // and require at least one character before the dot file_ext = strrchr(fs_name->name, '.'); if((file_ext != NULL) && (file_ext != fs_name->name) && (strlen(file_ext) < 7)){ snprintf(version_string, 64, "#%d,%d%s", obj_id, vnum, file_ext); } else{ snprintf(version_string, 64, "#%d,%d", obj_id, vnum); } strncat(fs_name->name, version_string, 64); fs_name->flags = TSK_FS_NAME_FLAG_UNALLOC; } else{ fs_name->flags = TSK_FS_NAME_FLAG_ALLOC; } fs_name->meta_addr = curr_inode; switch (header->obj_type) { case YAFFS_TYPE_FILE: fs_name->type = TSK_FS_NAME_TYPE_REG; break; case YAFFS_TYPE_DIRECTORY: fs_name->type = TSK_FS_NAME_TYPE_DIR; break; case YAFFS_TYPE_SOFTLINK: case YAFFS_TYPE_HARDLINK: fs_name->type = TSK_FS_NAME_TYPE_LNK; break; case YAFFS_TYPE_SPECIAL: fs_name->type = TSK_FS_NAME_TYPE_UNDEF; // Could be a socket break; default: if (tsk_verbose) fprintf(stderr, "yaffs_dir_open_meta_cb: unhandled object type\n"); fs_name->type = TSK_FS_NAME_TYPE_UNDEF; break; } free(header); if (tsk_fs_dir_add(cb_args->dir, fs_name)) { tsk_fs_name_free(fs_name); return TSK_ERR; } /* A copy is made in tsk_fs_dir_add, so we can free this one */ tsk_fs_name_free(fs_name); return TSK_OK; } static TSK_RETVAL_ENUM yaffsfs_dir_open_meta(TSK_FS_INFO *a_fs, TSK_FS_DIR ** a_fs_dir, TSK_INUM_T a_addr) { TSK_FS_DIR *fs_dir; TSK_FS_NAME *fs_name; YAFFSFS_INFO *yfs = (YAFFSFS_INFO *)a_fs; int should_walk_children = 0; uint32_t obj_id; uint32_t ver_number; if (a_addr < a_fs->first_inum || a_addr > a_fs->last_inum) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_WALK_RNG); tsk_error_set_errstr("yaffs_dir_open_meta: Invalid inode value: %" PRIuINUM, a_addr); return TSK_ERR; } else if (a_fs_dir == NULL) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr("yaffs_dir_open_meta: NULL fs_dir argument given"); return TSK_ERR; } fs_dir = *a_fs_dir; if (fs_dir) { tsk_fs_dir_reset(fs_dir); fs_dir->addr = a_addr; } else if ((*a_fs_dir = fs_dir = tsk_fs_dir_alloc(a_fs, a_addr, 128)) == NULL) { return TSK_ERR; } if (tsk_verbose) fprintf(stderr,"yaffs_dir_open_meta: called for directory %" PRIu32 "\n", (uint32_t) a_addr); // handle the orphan directory if its contents were requested if (a_addr == TSK_FS_ORPHANDIR_INUM(a_fs)) { return tsk_fs_dir_find_orphans(a_fs, fs_dir); } if ((fs_name = tsk_fs_name_alloc(YAFFSFS_MAXNAMLEN, 0)) == NULL) { return TSK_ERR; } if ((fs_dir->fs_file = tsk_fs_file_open_meta(a_fs, NULL, a_addr)) == NULL) { tsk_error_errstr2_concat(" - yaffs_dir_open_meta"); tsk_fs_name_free(fs_name); return TSK_ERR; } // extract obj_id and ver_number from inum yaffscache_inode_to_obj_id_and_version(a_addr, &obj_id, &ver_number); // Decide if we should walk the directory structure if (obj_id == YAFFS_OBJECT_DELETED || obj_id == YAFFS_OBJECT_UNLINKED) { should_walk_children = 1; } else { YaffsCacheObject *obj; YaffsCacheVersion *versionFound; TSK_RETVAL_ENUM result = yaffscache_version_find_by_inode(yfs, a_addr, &versionFound, &obj); if (result != TSK_OK) { if (tsk_verbose) tsk_fprintf(stderr, "yaffsfs_dir_open_meta: yaffscache_version_find_by_inode failed! (inode: %d\n", a_addr); tsk_fs_name_free(fs_name); return TSK_ERR; } /* Only attach files onto the latest version of the directory */ should_walk_children = (obj->yco_latest == versionFound); } // Search the cache for the children of this object and add them to fs_dir if (should_walk_children) { dir_open_cb_args args; args.yfs = yfs; args.dir = fs_dir; args.parent_addr = a_addr; yaffscache_find_children(yfs, a_addr, yaffs_dir_open_meta_cb, &args); } // add special entries to root directory if (obj_id == YAFFS_OBJECT_ROOT) { strncpy(fs_name->name, YAFFS_OBJECT_UNLINKED_NAME, fs_name->name_size); fs_name->meta_addr = YAFFS_OBJECT_UNLINKED; fs_name->type = TSK_FS_NAME_TYPE_DIR; fs_name->flags = TSK_FS_NAME_FLAG_ALLOC; if (tsk_fs_dir_add(fs_dir, fs_name)) { tsk_fs_name_free(fs_name); return TSK_ERR; } strncpy(fs_name->name, YAFFS_OBJECT_DELETED_NAME, fs_name->name_size); fs_name->meta_addr = YAFFS_OBJECT_DELETED; fs_name->type = TSK_FS_NAME_TYPE_DIR; fs_name->flags = TSK_FS_NAME_FLAG_ALLOC; if (tsk_fs_dir_add(fs_dir, fs_name)) { tsk_fs_name_free(fs_name); return TSK_ERR; } // orphan directory if (tsk_fs_dir_make_orphan_dir_name(a_fs, fs_name)) { tsk_fs_name_free(fs_name); return TSK_ERR; } fs_name->meta_addr = yfs->fs_info.last_inum; fs_name->type = TSK_FS_NAME_TYPE_DIR; fs_name->flags = TSK_FS_NAME_FLAG_ALLOC; if (tsk_fs_dir_add(fs_dir, fs_name)) { tsk_fs_name_free(fs_name); return TSK_ERR; } } tsk_fs_name_free(fs_name); return TSK_OK; } static TSK_FS_ATTR_TYPE_ENUM yaffsfs_get_default_attr_type(const TSK_FS_FILE * /*a_file*/) { return TSK_FS_ATTR_TYPE_DEFAULT; } static uint8_t yaffsfs_load_attrs(TSK_FS_FILE *file) { TSK_FS_ATTR *attr; TSK_FS_META *meta; TSK_FS_INFO *fs; YAFFSFS_INFO *yfs; TSK_FS_ATTR_RUN *data_run; TSK_DADDR_T file_block_count; YaffsCacheObject *obj; YaffsCacheVersion *version; TSK_RETVAL_ENUM result; TSK_LIST *chunks_seen = NULL; YaffsCacheChunk *curr; TSK_FS_ATTR_RUN *data_run_new; if (file == NULL || file->meta == NULL || file->fs_info == NULL) { tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr ("yaffsfs_load_attrs: called with NULL pointers"); return 1; } meta = file->meta; yfs = (YAFFSFS_INFO *)file->fs_info; fs = &yfs->fs_info; // see if we have already loaded the runs if ((meta->attr != NULL) && (meta->attr_state == TSK_FS_META_ATTR_STUDIED)) { return 0; } else if (meta->attr_state == TSK_FS_META_ATTR_ERROR) { return 1; } // not sure why this would ever happen, but... else if (meta->attr != NULL) { tsk_fs_attrlist_markunused(meta->attr); } else if (meta->attr == NULL) { meta->attr = tsk_fs_attrlist_alloc(); } attr = tsk_fs_attrlist_getnew(meta->attr, TSK_FS_ATTR_NONRES); if (attr == NULL) { meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } if (meta->size == 0) { data_run = NULL; } else { /* BC: I'm not entirely sure this is needed. My guess is that * this was done instead of maintaining the head of the list of * runs. In theory, the tsk_fs_attr_add_run() method should handle * the fillers. */ data_run = tsk_fs_attr_run_alloc(); if (data_run == NULL) { tsk_fs_attr_run_free(data_run); meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } data_run->offset = 0; data_run->addr = 0; data_run->len = (meta->size + fs->block_size - 1) / fs->block_size; data_run->flags = TSK_FS_ATTR_RUN_FLAG_FILLER; } // initialize the data run if (tsk_fs_attr_set_run(file, attr, data_run, NULL, TSK_FS_ATTR_TYPE_DEFAULT, TSK_FS_ATTR_ID_DEFAULT, meta->size, meta->size, roundup(meta->size, fs->block_size), (TSK_FS_ATTR_FLAG_ENUM)0, 0)) { meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } // If the file has size zero, return now if(meta->size == 0){ meta->attr_state = TSK_FS_META_ATTR_STUDIED; return 0; } /* Get the version for the given object. */ result = yaffscache_version_find_by_inode(yfs, meta->addr, &version, &obj); if (result != TSK_OK || version == NULL) { if (tsk_verbose) tsk_fprintf(stderr, "yaffsfs_load_attrs: yaffscache_version_find_by_inode failed!\n"); meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } if (tsk_verbose) yaffscache_object_dump(stderr, obj); file_block_count = data_run->len; /* Cycle through the chunks for this version of this object */ curr = version->ycv_last_chunk; while (curr != NULL && curr->ycc_obj_id == obj->yco_obj_id) { if (curr->ycc_chunk_id == 0) { if (tsk_verbose) tsk_fprintf(stderr, "yaffsfs_load_attrs: skipping header chunk\n"); } else if (tsk_list_find(chunks_seen, curr->ycc_chunk_id)) { if (tsk_verbose) tsk_fprintf(stderr, "yaffsfs_load_attrs: skipping duplicate chunk\n"); } else if (curr->ycc_chunk_id > file_block_count) { if (tsk_verbose) tsk_fprintf(stderr, "yaffsfs_load_attrs: skipping chunk past end\n"); } /* We like this chunk */ else { // add it to our internal list if (tsk_list_add(&chunks_seen, curr->ycc_chunk_id)) { meta->attr_state = TSK_FS_META_ATTR_ERROR; tsk_list_free(chunks_seen); chunks_seen = NULL; return 1; } data_run_new = tsk_fs_attr_run_alloc(); if (data_run_new == NULL) { tsk_fs_attr_run_free(data_run_new); meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } data_run_new->offset = (curr->ycc_chunk_id - 1); data_run_new->addr = curr->ycc_offset / (fs->block_pre_size + fs->block_size + fs->block_post_size); data_run_new->len = 1; data_run_new->flags = TSK_FS_ATTR_RUN_FLAG_NONE; if (tsk_verbose) tsk_fprintf(stderr, "yaffsfs_load_attrs: @@@ Chunk %d : %08x is at offset 0x%016llx\n", curr->ycc_chunk_id, curr->ycc_seq_number, curr->ycc_offset); tsk_fs_attr_add_run(fs, attr, data_run_new); } curr = curr->ycc_prev; } tsk_list_free(chunks_seen); meta->attr_state = TSK_FS_META_ATTR_STUDIED; return 0; } static uint8_t yaffsfs_jentry_walk(TSK_FS_INFO * /*info*/, int /*entry*/, TSK_FS_JENTRY_WALK_CB /*cb*/, void * /*fn*/) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_UNSUPFUNC); tsk_error_set_errstr("Journal support for YAFFS is not implemented"); return 1; } static uint8_t yaffsfs_jblk_walk(TSK_FS_INFO * /*info*/, TSK_DADDR_T /*daddr*/, TSK_DADDR_T /*daddrt*/, int /*entry*/, TSK_FS_JBLK_WALK_CB /*cb*/, void * /*fn*/) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_UNSUPFUNC); tsk_error_set_errstr("Journal support for YAFFS is not implemented"); return 1; } static uint8_t yaffsfs_jopen(TSK_FS_INFO * /*info*/, TSK_INUM_T /*inum*/) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_UNSUPFUNC); tsk_error_set_errstr("Journal support for YAFFS is not implemented"); return 1; } /** * \internal * Open part of a disk image as a Yaffs/2 file system. * * @param img_info Disk image to analyze * @param offset Byte offset where file system starts * @param ftype Specific type of file system * @param test Going to use this - 1 if we're doing auto-detect, 0 if not (display more verbose messages if the user specified YAFFS2) * @returns NULL on error or if data is not an Yaffs/3 file system */ TSK_FS_INFO * yaffs2_open(TSK_IMG_INFO * img_info, TSK_OFF_T offset, TSK_FS_TYPE_ENUM ftype, uint8_t test) { YAFFSFS_INFO *yaffsfs = NULL; TSK_FS_INFO *fs = NULL; const unsigned int psize = img_info->page_size; const unsigned int ssize = img_info->spare_size; YaffsHeader * first_header = NULL; TSK_FS_DIR *test_dir; std::map<std::string, std::string> configParams; YAFFS_CONFIG_STATUS config_file_status; // clean up any error messages that are lying around tsk_error_reset(); if (TSK_FS_TYPE_ISYAFFS2(ftype) == 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr("Invalid FS Type in yaffsfs_open"); return NULL; } if (img_info->sector_size == 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr("yaffs2_open: sector size is 0"); return NULL; } if ((yaffsfs = (YAFFSFS_INFO *) tsk_fs_malloc(sizeof(YAFFSFS_INFO))) == NULL) return NULL; yaffsfs->cache_objects = NULL; yaffsfs->chunkMap = NULL; fs = &(yaffsfs->fs_info); fs->tag = TSK_FS_INFO_TAG; fs->ftype = ftype; fs->flags = (TSK_FS_INFO_FLAG_ENUM)0; fs->img_info = img_info; fs->offset = offset; fs->endian = TSK_LIT_ENDIAN; // Read config file (if it exists) config_file_status = yaffs_load_config_file(img_info, configParams); // BL-6929(JTS): When using external readers, this call will fail. // Not having a config should not be a fatal error. /*if(config_file_status == YAFFS_CONFIG_ERROR){ // tsk_error was set by yaffs_load_config goto on_error; } else*/ if(config_file_status == YAFFS_CONFIG_OK){ // Validate the input // If it fails validation, return (tsk_error will be set up already) if(1 == yaffs_validate_config_file(configParams)){ goto on_error; } } // If we read these fields from the config file, use those values. Otherwise use the defaults if(configParams.find(YAFFS_CONFIG_PAGE_SIZE_STR) != configParams.end()){ yaffsfs->page_size = atoi(configParams[YAFFS_CONFIG_PAGE_SIZE_STR].c_str()); } else{ yaffsfs->page_size = psize == 0 ? YAFFS_DEFAULT_PAGE_SIZE : psize; } if(configParams.find(YAFFS_CONFIG_SPARE_SIZE_STR) != configParams.end()){ yaffsfs->spare_size = atoi(configParams[YAFFS_CONFIG_SPARE_SIZE_STR].c_str()); } else{ yaffsfs->spare_size = ssize == 0 ? YAFFS_DEFAULT_SPARE_SIZE : ssize; } if(configParams.find(YAFFS_CONFIG_CHUNKS_PER_BLOCK_STR) != configParams.end()){ yaffsfs->chunks_per_block = atoi(configParams[YAFFS_CONFIG_CHUNKS_PER_BLOCK_STR].c_str()); } else{ yaffsfs->chunks_per_block = 64; } // TODO: Why are 2 different memory allocation methods used in the same code? // This makes things unnecessary complex. yaffsfs->max_obj_id = 1; yaffsfs->max_version = 0; // Keep track of whether we're doing auto-detection of the file system if(test){ yaffsfs->autoDetect = 1; } else{ yaffsfs->autoDetect = 0; } // Determine the layout of the spare area // If it was specified in the config file, use those values. Otherwise do the auto-detection if(configParams.find(YAFFS_CONFIG_SEQ_NUM_STR) != configParams.end()){ // In the validation step, we ensured that if one of the offsets was set, we have all of them yaffsfs->spare_seq_offset = atoi(configParams[YAFFS_CONFIG_SEQ_NUM_STR].c_str()); yaffsfs->spare_obj_id_offset = atoi(configParams[YAFFS_CONFIG_OBJ_ID_STR].c_str()); yaffsfs->spare_chunk_id_offset = atoi(configParams[YAFFS_CONFIG_CHUNK_ID_STR].c_str()); // Check that the offsets are valid for the given spare area size (fields are 4 bytes long) if((yaffsfs->spare_seq_offset + 4 > yaffsfs->spare_size) || (yaffsfs->spare_obj_id_offset + 4 > yaffsfs->spare_size) || (yaffsfs->spare_chunk_id_offset + 4 > yaffsfs->spare_size)){ tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr("yaffs2_open: Offset(s) in config file too large for spare area (size %d). %s", yaffsfs->spare_size, YAFFS_HELP_MESSAGE); goto on_error; } // nBytes isn't currently used, so just set to zero yaffsfs->spare_nbytes_offset = 0; } else{ // Decide how many blocks to test. If we're not doing auto-detection, set to zero (no limit) unsigned int maxBlocksToTest; if(yaffsfs->autoDetect){ maxBlocksToTest = YAFFS_DEFAULT_MAX_TEST_BLOCKS; } else{ maxBlocksToTest = 0; } if(yaffs_initialize_spare_format(yaffsfs, maxBlocksToTest) != TSK_OK){ tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_MAGIC); tsk_error_set_errstr("not a YAFFS file system (bad spare format). %s", YAFFS_HELP_MESSAGE); if (tsk_verbose) fprintf(stderr, "yaffsfs_open: could not find valid spare area format\n%s\n", YAFFS_HELP_MESSAGE); goto on_error; } } /* * Read the first record, make sure it's a valid header... * * Used for verification and autodetection of * the FS type. */ if (yaffsfs_read_header(yaffsfs, &first_header, 0)) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_MAGIC); tsk_error_set_errstr("not a YAFFS file system (first record). %s", YAFFS_HELP_MESSAGE); if (tsk_verbose) fprintf(stderr, "yaffsfs_open: invalid first record\n%s\n", YAFFS_HELP_MESSAGE); goto on_error; } free(first_header); first_header = NULL; fs->duname = "Chunk"; /* * Calculate the meta data info */ //fs->last_inum = 0xffffffff; // Will update this as we go fs->last_inum = 0; fs->root_inum = YAFFS_OBJECT_ROOT; fs->first_inum = YAFFS_OBJECT_FIRST; //fs->inum_count = fs->last_inum; // For now this will be the last_inum - 1 (after we calculate it) /* * Calculate the block info */ fs->dev_bsize = img_info->sector_size; fs->block_size = yaffsfs->page_size; fs->block_pre_size = 0; fs->block_post_size = yaffsfs->spare_size; fs->block_count = img_info->size / (fs->block_pre_size + fs->block_size + fs->block_post_size); fs->first_block = 0; fs->last_block_act = fs->last_block = fs->block_count ? fs->block_count - 1 : 0; /* Set the generic function pointers */ fs->inode_walk = yaffsfs_inode_walk; fs->block_walk = yaffsfs_block_walk; fs->block_getflags = yaffsfs_block_getflags; fs->get_default_attr_type = yaffsfs_get_default_attr_type; fs->load_attrs = yaffsfs_load_attrs; fs->file_add_meta = yaffs_inode_lookup; fs->dir_open_meta = yaffsfs_dir_open_meta; fs->fsstat = yaffsfs_fsstat; fs->fscheck = yaffsfs_fscheck; fs->istat = yaffsfs_istat; fs->name_cmp = tsk_fs_unix_name_cmp; fs->close = yaffsfs_close; /* Journal */ fs->jblk_walk = yaffsfs_jblk_walk; fs->jentry_walk = yaffsfs_jentry_walk; fs->jopen = yaffsfs_jopen; /* Initialize the caches */ if (tsk_verbose) fprintf(stderr, "yaffsfs_open: building cache...\n"); /* Build cache */ /* NOTE: The only modifications to the cache happen here, during at * the open. Should be fine with no lock, even if access to the * cache is shared among threads. */ //tsk_init_lock(&yaffsfs->lock); yaffsfs->chunkMap = new std::map<uint32_t, YaffsCacheChunkGroup>; if (TSK_OK != yaffsfs_parse_image_load_cache(yaffsfs)) { goto on_error; } if (tsk_verbose) { fprintf(stderr, "yaffsfs_open: done building cache!\n"); //yaffscache_objects_dump(yaffsfs, stderr); } // Update the number of inums now that we've read in the file system fs->inum_count = fs->last_inum - 1; test_dir = tsk_fs_dir_open_meta(fs, fs->root_inum); if (test_dir == NULL) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_MAGIC); tsk_error_set_errstr("not a YAFFS file system (no root directory). %s", YAFFS_HELP_MESSAGE); if (tsk_verbose) fprintf(stderr, "yaffsfs_open: invalid file system\n%s\n", YAFFS_HELP_MESSAGE); goto on_error; } tsk_fs_dir_close(test_dir); return fs; on_error: // yaffsfs_close frees all the cache objects yaffsfs_close(fs); return NULL; }
null
163
CWE-787
CVE-2020-10531
// © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /* ****************************************************************************** * Copyright (C) 1999-2016, International Business Machines Corporation and * others. All Rights Reserved. ****************************************************************************** * * File unistr.cpp * * Modification History: * * Date Name Description * 09/25/98 stephen Creation. * 04/20/99 stephen Overhauled per 4/16 code review. * 07/09/99 stephen Renamed {hi,lo},{byte,word} to icu_X for HP/UX * 11/18/99 aliu Added handleReplaceBetween() to make inherit from * Replaceable. * 06/25/01 grhoten Removed the dependency on iostream ****************************************************************************** */ #include "unicode/utypes.h" #include "unicode/appendable.h" #include "unicode/putil.h" #include "cstring.h" #include "cmemory.h" #include "unicode/ustring.h" #include "unicode/unistr.h" #include "unicode/utf.h" #include "unicode/utf16.h" #include "uelement.h" #include "ustr_imp.h" #include "umutex.h" #include "uassert.h" #if 0 #include <iostream> using namespace std; //DEBUGGING void print(const UnicodeString& s, const char *name) { UChar c; cout << name << ":|"; for(int i = 0; i < s.length(); ++i) { c = s[i]; if(c>= 0x007E || c < 0x0020) cout << "[0x" << hex << s[i] << "]"; else cout << (char) s[i]; } cout << '|' << endl; } void print(const UChar *s, int32_t len, const char *name) { UChar c; cout << name << ":|"; for(int i = 0; i < len; ++i) { c = s[i]; if(c>= 0x007E || c < 0x0020) cout << "[0x" << hex << s[i] << "]"; else cout << (char) s[i]; } cout << '|' << endl; } // END DEBUGGING #endif // Local function definitions for now // need to copy areas that may overlap static inline void us_arrayCopy(const UChar *src, int32_t srcStart, UChar *dst, int32_t dstStart, int32_t count) { if(count>0) { uprv_memmove(dst+dstStart, src+srcStart, (size_t)count*sizeof(*src)); } } // u_unescapeAt() callback to get a UChar from a UnicodeString U_CDECL_BEGIN static UChar U_CALLCONV UnicodeString_charAt(int32_t offset, void *context) { return ((icu::UnicodeString*) context)->charAt(offset); } U_CDECL_END U_NAMESPACE_BEGIN /* The Replaceable virtual destructor can't be defined in the header due to how AIX works with multiple definitions of virtual functions. */ Replaceable::~Replaceable() {} UOBJECT_DEFINE_RTTI_IMPLEMENTATION(UnicodeString) UnicodeString U_EXPORT2 operator+ (const UnicodeString &s1, const UnicodeString &s2) { return UnicodeString(s1.length()+s2.length()+1, (UChar32)0, 0). append(s1). append(s2); } //======================================== // Reference Counting functions, put at top of file so that optimizing compilers // have a chance to automatically inline. //======================================== void UnicodeString::addRef() { umtx_atomic_inc((u_atomic_int32_t *)fUnion.fFields.fArray - 1); } int32_t UnicodeString::removeRef() { return umtx_atomic_dec((u_atomic_int32_t *)fUnion.fFields.fArray - 1); } int32_t UnicodeString::refCount() const { return umtx_loadAcquire(*((u_atomic_int32_t *)fUnion.fFields.fArray - 1)); } void UnicodeString::releaseArray() { if((fUnion.fFields.fLengthAndFlags & kRefCounted) && removeRef() == 0) { uprv_free((int32_t *)fUnion.fFields.fArray - 1); } } //======================================== // Constructors //======================================== // The default constructor is inline in unistr.h. UnicodeString::UnicodeString(int32_t capacity, UChar32 c, int32_t count) { fUnion.fFields.fLengthAndFlags = 0; if(count <= 0 || (uint32_t)c > 0x10ffff) { // just allocate and do not do anything else allocate(capacity); } else if(c <= 0xffff) { int32_t length = count; if(capacity < length) { capacity = length; } if(allocate(capacity)) { UChar *array = getArrayStart(); UChar unit = (UChar)c; for(int32_t i = 0; i < length; ++i) { array[i] = unit; } setLength(length); } } else { // supplementary code point, write surrogate pairs if(count > (INT32_MAX / 2)) { // We would get more than 2G UChars. allocate(capacity); return; } int32_t length = count * 2; if(capacity < length) { capacity = length; } if(allocate(capacity)) { UChar *array = getArrayStart(); UChar lead = U16_LEAD(c); UChar trail = U16_TRAIL(c); for(int32_t i = 0; i < length; i += 2) { array[i] = lead; array[i + 1] = trail; } setLength(length); } } } UnicodeString::UnicodeString(UChar ch) { fUnion.fFields.fLengthAndFlags = kLength1 | kShortString; fUnion.fStackFields.fBuffer[0] = ch; } UnicodeString::UnicodeString(UChar32 ch) { fUnion.fFields.fLengthAndFlags = kShortString; int32_t i = 0; UBool isError = FALSE; U16_APPEND(fUnion.fStackFields.fBuffer, i, US_STACKBUF_SIZE, ch, isError); // We test isError so that the compiler does not complain that we don't. // If isError then i==0 which is what we want anyway. if(!isError) { setShortLength(i); } } UnicodeString::UnicodeString(const UChar *text) { fUnion.fFields.fLengthAndFlags = kShortString; doAppend(text, 0, -1); } UnicodeString::UnicodeString(const UChar *text, int32_t textLength) { fUnion.fFields.fLengthAndFlags = kShortString; doAppend(text, 0, textLength); } UnicodeString::UnicodeString(UBool isTerminated, ConstChar16Ptr textPtr, int32_t textLength) { fUnion.fFields.fLengthAndFlags = kReadonlyAlias; const UChar *text = textPtr; if(text == NULL) { // treat as an empty string, do not alias setToEmpty(); } else if(textLength < -1 || (textLength == -1 && !isTerminated) || (textLength >= 0 && isTerminated && text[textLength] != 0) ) { setToBogus(); } else { if(textLength == -1) { // text is terminated, or else it would have failed the above test textLength = u_strlen(text); } setArray(const_cast<UChar *>(text), textLength, isTerminated ? textLength + 1 : textLength); } } UnicodeString::UnicodeString(UChar *buff, int32_t buffLength, int32_t buffCapacity) { fUnion.fFields.fLengthAndFlags = kWritableAlias; if(buff == NULL) { // treat as an empty string, do not alias setToEmpty(); } else if(buffLength < -1 || buffCapacity < 0 || buffLength > buffCapacity) { setToBogus(); } else { if(buffLength == -1) { // fLength = u_strlen(buff); but do not look beyond buffCapacity const UChar *p = buff, *limit = buff + buffCapacity; while(p != limit && *p != 0) { ++p; } buffLength = (int32_t)(p - buff); } setArray(buff, buffLength, buffCapacity); } } UnicodeString::UnicodeString(const char *src, int32_t length, EInvariant) { fUnion.fFields.fLengthAndFlags = kShortString; if(src==NULL) { // treat as an empty string } else { if(length<0) { length=(int32_t)uprv_strlen(src); } if(cloneArrayIfNeeded(length, length, FALSE)) { u_charsToUChars(src, getArrayStart(), length); setLength(length); } else { setToBogus(); } } } #if U_CHARSET_IS_UTF8 UnicodeString::UnicodeString(const char *codepageData) { fUnion.fFields.fLengthAndFlags = kShortString; if(codepageData != 0) { setToUTF8(codepageData); } } UnicodeString::UnicodeString(const char *codepageData, int32_t dataLength) { fUnion.fFields.fLengthAndFlags = kShortString; // if there's nothing to convert, do nothing if(codepageData == 0 || dataLength == 0 || dataLength < -1) { return; } if(dataLength == -1) { dataLength = (int32_t)uprv_strlen(codepageData); } setToUTF8(StringPiece(codepageData, dataLength)); } // else see unistr_cnv.cpp #endif UnicodeString::UnicodeString(const UnicodeString& that) { fUnion.fFields.fLengthAndFlags = kShortString; copyFrom(that); } UnicodeString::UnicodeString(UnicodeString &&src) U_NOEXCEPT { copyFieldsFrom(src, TRUE); } UnicodeString::UnicodeString(const UnicodeString& that, int32_t srcStart) { fUnion.fFields.fLengthAndFlags = kShortString; setTo(that, srcStart); } UnicodeString::UnicodeString(const UnicodeString& that, int32_t srcStart, int32_t srcLength) { fUnion.fFields.fLengthAndFlags = kShortString; setTo(that, srcStart, srcLength); } // Replaceable base class clone() default implementation, does not clone Replaceable * Replaceable::clone() const { return NULL; } // UnicodeString overrides clone() with a real implementation UnicodeString * UnicodeString::clone() const { return new UnicodeString(*this); } //======================================== // array allocation //======================================== namespace { const int32_t kGrowSize = 128; // The number of bytes for one int32_t reference counter and capacity UChars // must fit into a 32-bit size_t (at least when on a 32-bit platform). // We also add one for the NUL terminator, to avoid reallocation in getTerminatedBuffer(), // and round up to a multiple of 16 bytes. // This means that capacity must be at most (0xfffffff0 - 4) / 2 - 1 = 0x7ffffff5. // (With more complicated checks we could go up to 0x7ffffffd without rounding up, // but that does not seem worth it.) const int32_t kMaxCapacity = 0x7ffffff5; int32_t getGrowCapacity(int32_t newLength) { int32_t growSize = (newLength >> 2) + kGrowSize; if(growSize <= (kMaxCapacity - newLength)) { return newLength + growSize; } else { return kMaxCapacity; } } } // namespace UBool UnicodeString::allocate(int32_t capacity) { if(capacity <= US_STACKBUF_SIZE) { fUnion.fFields.fLengthAndFlags = kShortString; return TRUE; } if(capacity <= kMaxCapacity) { ++capacity; // for the NUL // Switch to size_t which is unsigned so that we can allocate up to 4GB. // Reference counter + UChars. size_t numBytes = sizeof(int32_t) + (size_t)capacity * U_SIZEOF_UCHAR; // Round up to a multiple of 16. numBytes = (numBytes + 15) & ~15; int32_t *array = (int32_t *) uprv_malloc(numBytes); if(array != NULL) { // set initial refCount and point behind the refCount *array++ = 1; numBytes -= sizeof(int32_t); // have fArray point to the first UChar fUnion.fFields.fArray = (UChar *)array; fUnion.fFields.fCapacity = (int32_t)(numBytes / U_SIZEOF_UCHAR); fUnion.fFields.fLengthAndFlags = kLongString; return TRUE; } } fUnion.fFields.fLengthAndFlags = kIsBogus; fUnion.fFields.fArray = 0; fUnion.fFields.fCapacity = 0; return FALSE; } //======================================== // Destructor //======================================== #ifdef UNISTR_COUNT_FINAL_STRING_LENGTHS static u_atomic_int32_t finalLengthCounts[0x400]; // UnicodeString::kMaxShortLength+1 static u_atomic_int32_t beyondCount(0); U_CAPI void unistr_printLengths() { int32_t i; for(i = 0; i <= 59; ++i) { printf("%2d, %9d\n", i, (int32_t)finalLengthCounts[i]); } int32_t beyond = beyondCount; for(; i < UPRV_LENGTHOF(finalLengthCounts); ++i) { beyond += finalLengthCounts[i]; } printf(">59, %9d\n", beyond); } #endif UnicodeString::~UnicodeString() { #ifdef UNISTR_COUNT_FINAL_STRING_LENGTHS // Count lengths of strings at the end of their lifetime. // Useful for discussion of a desirable stack buffer size. // Count the contents length, not the optional NUL terminator nor further capacity. // Ignore open-buffer strings and strings which alias external storage. if((fUnion.fFields.fLengthAndFlags&(kOpenGetBuffer|kReadonlyAlias|kWritableAlias)) == 0) { if(hasShortLength()) { umtx_atomic_inc(finalLengthCounts + getShortLength()); } else { umtx_atomic_inc(&beyondCount); } } #endif releaseArray(); } //======================================== // Factory methods //======================================== UnicodeString UnicodeString::fromUTF8(StringPiece utf8) { UnicodeString result; result.setToUTF8(utf8); return result; } UnicodeString UnicodeString::fromUTF32(const UChar32 *utf32, int32_t length) { UnicodeString result; int32_t capacity; // Most UTF-32 strings will be BMP-only and result in a same-length // UTF-16 string. We overestimate the capacity just slightly, // just in case there are a few supplementary characters. if(length <= US_STACKBUF_SIZE) { capacity = US_STACKBUF_SIZE; } else { capacity = length + (length >> 4) + 4; } do { UChar *utf16 = result.getBuffer(capacity); int32_t length16; UErrorCode errorCode = U_ZERO_ERROR; u_strFromUTF32WithSub(utf16, result.getCapacity(), &length16, utf32, length, 0xfffd, // Substitution character. NULL, // Don't care about number of substitutions. &errorCode); result.releaseBuffer(length16); if(errorCode == U_BUFFER_OVERFLOW_ERROR) { capacity = length16 + 1; // +1 for the terminating NUL. continue; } else if(U_FAILURE(errorCode)) { result.setToBogus(); } break; } while(TRUE); return result; } //======================================== // Assignment //======================================== UnicodeString & UnicodeString::operator=(const UnicodeString &src) { return copyFrom(src); } UnicodeString & UnicodeString::fastCopyFrom(const UnicodeString &src) { return copyFrom(src, TRUE); } UnicodeString & UnicodeString::copyFrom(const UnicodeString &src, UBool fastCopy) { // if assigning to ourselves, do nothing if(this == &src) { return *this; } // is the right side bogus? if(src.isBogus()) { setToBogus(); return *this; } // delete the current contents releaseArray(); if(src.isEmpty()) { // empty string - use the stack buffer setToEmpty(); return *this; } // fLength>0 and not an "open" src.getBuffer(minCapacity) fUnion.fFields.fLengthAndFlags = src.fUnion.fFields.fLengthAndFlags; switch(src.fUnion.fFields.fLengthAndFlags & kAllStorageFlags) { case kShortString: // short string using the stack buffer, do the same uprv_memcpy(fUnion.fStackFields.fBuffer, src.fUnion.fStackFields.fBuffer, getShortLength() * U_SIZEOF_UCHAR); break; case kLongString: // src uses a refCounted string buffer, use that buffer with refCount // src is const, use a cast - we don't actually change it ((UnicodeString &)src).addRef(); // copy all fields, share the reference-counted buffer fUnion.fFields.fArray = src.fUnion.fFields.fArray; fUnion.fFields.fCapacity = src.fUnion.fFields.fCapacity; if(!hasShortLength()) { fUnion.fFields.fLength = src.fUnion.fFields.fLength; } break; case kReadonlyAlias: if(fastCopy) { // src is a readonly alias, do the same // -> maintain the readonly alias as such fUnion.fFields.fArray = src.fUnion.fFields.fArray; fUnion.fFields.fCapacity = src.fUnion.fFields.fCapacity; if(!hasShortLength()) { fUnion.fFields.fLength = src.fUnion.fFields.fLength; } break; } // else if(!fastCopy) fall through to case kWritableAlias // -> allocate a new buffer and copy the contents U_FALLTHROUGH; case kWritableAlias: { // src is a writable alias; we make a copy of that instead int32_t srcLength = src.length(); if(allocate(srcLength)) { u_memcpy(getArrayStart(), src.getArrayStart(), srcLength); setLength(srcLength); break; } // if there is not enough memory, then fall through to setting to bogus U_FALLTHROUGH; } default: // if src is bogus, set ourselves to bogus // do not call setToBogus() here because fArray and flags are not consistent here fUnion.fFields.fLengthAndFlags = kIsBogus; fUnion.fFields.fArray = 0; fUnion.fFields.fCapacity = 0; break; } return *this; } UnicodeString &UnicodeString::operator=(UnicodeString &&src) U_NOEXCEPT { // No explicit check for self move assignment, consistent with standard library. // Self move assignment causes no crash nor leak but might make the object bogus. releaseArray(); copyFieldsFrom(src, TRUE); return *this; } // Same as move assignment except without memory management. void UnicodeString::copyFieldsFrom(UnicodeString &src, UBool setSrcToBogus) U_NOEXCEPT { int16_t lengthAndFlags = fUnion.fFields.fLengthAndFlags = src.fUnion.fFields.fLengthAndFlags; if(lengthAndFlags & kUsingStackBuffer) { // Short string using the stack buffer, copy the contents. // Check for self assignment to prevent "overlap in memcpy" warnings, // although it should be harmless to copy a buffer to itself exactly. if(this != &src) { uprv_memcpy(fUnion.fStackFields.fBuffer, src.fUnion.fStackFields.fBuffer, getShortLength() * U_SIZEOF_UCHAR); } } else { // In all other cases, copy all fields. fUnion.fFields.fArray = src.fUnion.fFields.fArray; fUnion.fFields.fCapacity = src.fUnion.fFields.fCapacity; if(!hasShortLength()) { fUnion.fFields.fLength = src.fUnion.fFields.fLength; } if(setSrcToBogus) { // Set src to bogus without releasing any memory. src.fUnion.fFields.fLengthAndFlags = kIsBogus; src.fUnion.fFields.fArray = NULL; src.fUnion.fFields.fCapacity = 0; } } } void UnicodeString::swap(UnicodeString &other) U_NOEXCEPT { UnicodeString temp; // Empty short string: Known not to need releaseArray(). // Copy fields without resetting source values in between. temp.copyFieldsFrom(*this, FALSE); this->copyFieldsFrom(other, FALSE); other.copyFieldsFrom(temp, FALSE); // Set temp to an empty string so that other's memory is not released twice. temp.fUnion.fFields.fLengthAndFlags = kShortString; } //======================================== // Miscellaneous operations //======================================== UnicodeString UnicodeString::unescape() const { UnicodeString result(length(), (UChar32)0, (int32_t)0); // construct with capacity if (result.isBogus()) { return result; } const UChar *array = getBuffer(); int32_t len = length(); int32_t prev = 0; for (int32_t i=0;;) { if (i == len) { result.append(array, prev, len - prev); break; } if (array[i++] == 0x5C /*'\\'*/) { result.append(array, prev, (i - 1) - prev); UChar32 c = unescapeAt(i); // advances i if (c < 0) { result.remove(); // return empty string break; // invalid escape sequence } result.append(c); prev = i; } } return result; } UChar32 UnicodeString::unescapeAt(int32_t &offset) const { return u_unescapeAt(UnicodeString_charAt, &offset, length(), (void*)this); } //======================================== // Read-only implementation //======================================== UBool UnicodeString::doEquals(const UnicodeString &text, int32_t len) const { // Requires: this & text not bogus and have same lengths. // Byte-wise comparison works for equality regardless of endianness. return uprv_memcmp(getArrayStart(), text.getArrayStart(), len * U_SIZEOF_UCHAR) == 0; } int8_t UnicodeString::doCompare( int32_t start, int32_t length, const UChar *srcChars, int32_t srcStart, int32_t srcLength) const { // compare illegal string values if(isBogus()) { return -1; } // pin indices to legal values pinIndices(start, length); if(srcChars == NULL) { // treat const UChar *srcChars==NULL as an empty string return length == 0 ? 0 : 1; } // get the correct pointer const UChar *chars = getArrayStart(); chars += start; srcChars += srcStart; int32_t minLength; int8_t lengthResult; // get the srcLength if necessary if(srcLength < 0) { srcLength = u_strlen(srcChars + srcStart); } // are we comparing different lengths? if(length != srcLength) { if(length < srcLength) { minLength = length; lengthResult = -1; } else { minLength = srcLength; lengthResult = 1; } } else { minLength = length; lengthResult = 0; } /* * note that uprv_memcmp() returns an int but we return an int8_t; * we need to take care not to truncate the result - * one way to do this is to right-shift the value to * move the sign bit into the lower 8 bits and making sure that this * does not become 0 itself */ if(minLength > 0 && chars != srcChars) { int32_t result; # if U_IS_BIG_ENDIAN // big-endian: byte comparison works result = uprv_memcmp(chars, srcChars, minLength * sizeof(UChar)); if(result != 0) { return (int8_t)(result >> 15 | 1); } # else // little-endian: compare UChar units do { result = ((int32_t)*(chars++) - (int32_t)*(srcChars++)); if(result != 0) { return (int8_t)(result >> 15 | 1); } } while(--minLength > 0); # endif } return lengthResult; } /* String compare in code point order - doCompare() compares in code unit order. */ int8_t UnicodeString::doCompareCodePointOrder(int32_t start, int32_t length, const UChar *srcChars, int32_t srcStart, int32_t srcLength) const { // compare illegal string values // treat const UChar *srcChars==NULL as an empty string if(isBogus()) { return -1; } // pin indices to legal values pinIndices(start, length); if(srcChars == NULL) { srcStart = srcLength = 0; } int32_t diff = uprv_strCompare(getArrayStart() + start, length, (srcChars!=NULL)?(srcChars + srcStart):NULL, srcLength, FALSE, TRUE); /* translate the 32-bit result into an 8-bit one */ if(diff!=0) { return (int8_t)(diff >> 15 | 1); } else { return 0; } } int32_t UnicodeString::getLength() const { return length(); } UChar UnicodeString::getCharAt(int32_t offset) const { return charAt(offset); } UChar32 UnicodeString::getChar32At(int32_t offset) const { return char32At(offset); } UChar32 UnicodeString::char32At(int32_t offset) const { int32_t len = length(); if((uint32_t)offset < (uint32_t)len) { const UChar *array = getArrayStart(); UChar32 c; U16_GET(array, 0, offset, len, c); return c; } else { return kInvalidUChar; } } int32_t UnicodeString::getChar32Start(int32_t offset) const { if((uint32_t)offset < (uint32_t)length()) { const UChar *array = getArrayStart(); U16_SET_CP_START(array, 0, offset); return offset; } else { return 0; } } int32_t UnicodeString::getChar32Limit(int32_t offset) const { int32_t len = length(); if((uint32_t)offset < (uint32_t)len) { const UChar *array = getArrayStart(); U16_SET_CP_LIMIT(array, 0, offset, len); return offset; } else { return len; } } int32_t UnicodeString::countChar32(int32_t start, int32_t length) const { pinIndices(start, length); // if(isBogus()) then fArray==0 and start==0 - u_countChar32() checks for NULL return u_countChar32(getArrayStart()+start, length); } UBool UnicodeString::hasMoreChar32Than(int32_t start, int32_t length, int32_t number) const { pinIndices(start, length); // if(isBogus()) then fArray==0 and start==0 - u_strHasMoreChar32Than() checks for NULL return u_strHasMoreChar32Than(getArrayStart()+start, length, number); } int32_t UnicodeString::moveIndex32(int32_t index, int32_t delta) const { // pin index int32_t len = length(); if(index<0) { index=0; } else if(index>len) { index=len; } const UChar *array = getArrayStart(); if(delta>0) { U16_FWD_N(array, index, len, delta); } else { U16_BACK_N(array, 0, index, -delta); } return index; } void UnicodeString::doExtract(int32_t start, int32_t length, UChar *dst, int32_t dstStart) const { // pin indices to legal values pinIndices(start, length); // do not copy anything if we alias dst itself const UChar *array = getArrayStart(); if(array + start != dst + dstStart) { us_arrayCopy(array, start, dst, dstStart, length); } } int32_t UnicodeString::extract(Char16Ptr dest, int32_t destCapacity, UErrorCode &errorCode) const { int32_t len = length(); if(U_SUCCESS(errorCode)) { if(isBogus() || destCapacity<0 || (destCapacity>0 && dest==0)) { errorCode=U_ILLEGAL_ARGUMENT_ERROR; } else { const UChar *array = getArrayStart(); if(len>0 && len<=destCapacity && array!=dest) { u_memcpy(dest, array, len); } return u_terminateUChars(dest, destCapacity, len, &errorCode); } } return len; } int32_t UnicodeString::extract(int32_t start, int32_t length, char *target, int32_t targetCapacity, enum EInvariant) const { // if the arguments are illegal, then do nothing if(targetCapacity < 0 || (targetCapacity > 0 && target == NULL)) { return 0; } // pin the indices to legal values pinIndices(start, length); if(length <= targetCapacity) { u_UCharsToChars(getArrayStart() + start, target, length); } UErrorCode status = U_ZERO_ERROR; return u_terminateChars(target, targetCapacity, length, &status); } UnicodeString UnicodeString::tempSubString(int32_t start, int32_t len) const { pinIndices(start, len); const UChar *array = getBuffer(); // not getArrayStart() to check kIsBogus & kOpenGetBuffer if(array==NULL) { array=fUnion.fStackFields.fBuffer; // anything not NULL because that would make an empty string len=-2; // bogus result string } return UnicodeString(FALSE, array + start, len); } int32_t UnicodeString::toUTF8(int32_t start, int32_t len, char *target, int32_t capacity) const { pinIndices(start, len); int32_t length8; UErrorCode errorCode = U_ZERO_ERROR; u_strToUTF8WithSub(target, capacity, &length8, getBuffer() + start, len, 0xFFFD, // Standard substitution character. NULL, // Don't care about number of substitutions. &errorCode); return length8; } #if U_CHARSET_IS_UTF8 int32_t UnicodeString::extract(int32_t start, int32_t len, char *target, uint32_t dstSize) const { // if the arguments are illegal, then do nothing if(/*dstSize < 0 || */(dstSize > 0 && target == 0)) { return 0; } return toUTF8(start, len, target, dstSize <= 0x7fffffff ? (int32_t)dstSize : 0x7fffffff); } // else see unistr_cnv.cpp #endif void UnicodeString::extractBetween(int32_t start, int32_t limit, UnicodeString& target) const { pinIndex(start); pinIndex(limit); doExtract(start, limit - start, target); } // When converting from UTF-16 to UTF-8, the result will have at most 3 times // as many bytes as the source has UChars. // The "worst cases" are writing systems like Indic, Thai and CJK with // 3:1 bytes:UChars. void UnicodeString::toUTF8(ByteSink &sink) const { int32_t length16 = length(); if(length16 != 0) { char stackBuffer[1024]; int32_t capacity = (int32_t)sizeof(stackBuffer); UBool utf8IsOwned = FALSE; char *utf8 = sink.GetAppendBuffer(length16 < capacity ? length16 : capacity, 3*length16, stackBuffer, capacity, &capacity); int32_t length8 = 0; UErrorCode errorCode = U_ZERO_ERROR; u_strToUTF8WithSub(utf8, capacity, &length8, getBuffer(), length16, 0xFFFD, // Standard substitution character. NULL, // Don't care about number of substitutions. &errorCode); if(errorCode == U_BUFFER_OVERFLOW_ERROR) { utf8 = (char *)uprv_malloc(length8); if(utf8 != NULL) { utf8IsOwned = TRUE; errorCode = U_ZERO_ERROR; u_strToUTF8WithSub(utf8, length8, &length8, getBuffer(), length16, 0xFFFD, // Standard substitution character. NULL, // Don't care about number of substitutions. &errorCode); } else { errorCode = U_MEMORY_ALLOCATION_ERROR; } } if(U_SUCCESS(errorCode)) { sink.Append(utf8, length8); sink.Flush(); } if(utf8IsOwned) { uprv_free(utf8); } } } int32_t UnicodeString::toUTF32(UChar32 *utf32, int32_t capacity, UErrorCode &errorCode) const { int32_t length32=0; if(U_SUCCESS(errorCode)) { // getBuffer() and u_strToUTF32WithSub() check for illegal arguments. u_strToUTF32WithSub(utf32, capacity, &length32, getBuffer(), length(), 0xfffd, // Substitution character. NULL, // Don't care about number of substitutions. &errorCode); } return length32; } int32_t UnicodeString::indexOf(const UChar *srcChars, int32_t srcStart, int32_t srcLength, int32_t start, int32_t length) const { if(isBogus() || srcChars == 0 || srcStart < 0 || srcLength == 0) { return -1; } // UnicodeString does not find empty substrings if(srcLength < 0 && srcChars[srcStart] == 0) { return -1; } // get the indices within bounds pinIndices(start, length); // find the first occurrence of the substring const UChar *array = getArrayStart(); const UChar *match = u_strFindFirst(array + start, length, srcChars + srcStart, srcLength); if(match == NULL) { return -1; } else { return (int32_t)(match - array); } } int32_t UnicodeString::doIndexOf(UChar c, int32_t start, int32_t length) const { // pin indices pinIndices(start, length); // find the first occurrence of c const UChar *array = getArrayStart(); const UChar *match = u_memchr(array + start, c, length); if(match == NULL) { return -1; } else { return (int32_t)(match - array); } } int32_t UnicodeString::doIndexOf(UChar32 c, int32_t start, int32_t length) const { // pin indices pinIndices(start, length); // find the first occurrence of c const UChar *array = getArrayStart(); const UChar *match = u_memchr32(array + start, c, length); if(match == NULL) { return -1; } else { return (int32_t)(match - array); } } int32_t UnicodeString::lastIndexOf(const UChar *srcChars, int32_t srcStart, int32_t srcLength, int32_t start, int32_t length) const { if(isBogus() || srcChars == 0 || srcStart < 0 || srcLength == 0) { return -1; } // UnicodeString does not find empty substrings if(srcLength < 0 && srcChars[srcStart] == 0) { return -1; } // get the indices within bounds pinIndices(start, length); // find the last occurrence of the substring const UChar *array = getArrayStart(); const UChar *match = u_strFindLast(array + start, length, srcChars + srcStart, srcLength); if(match == NULL) { return -1; } else { return (int32_t)(match - array); } } int32_t UnicodeString::doLastIndexOf(UChar c, int32_t start, int32_t length) const { if(isBogus()) { return -1; } // pin indices pinIndices(start, length); // find the last occurrence of c const UChar *array = getArrayStart(); const UChar *match = u_memrchr(array + start, c, length); if(match == NULL) { return -1; } else { return (int32_t)(match - array); } } int32_t UnicodeString::doLastIndexOf(UChar32 c, int32_t start, int32_t length) const { // pin indices pinIndices(start, length); // find the last occurrence of c const UChar *array = getArrayStart(); const UChar *match = u_memrchr32(array + start, c, length); if(match == NULL) { return -1; } else { return (int32_t)(match - array); } } //======================================== // Write implementation //======================================== UnicodeString& UnicodeString::findAndReplace(int32_t start, int32_t length, const UnicodeString& oldText, int32_t oldStart, int32_t oldLength, const UnicodeString& newText, int32_t newStart, int32_t newLength) { if(isBogus() || oldText.isBogus() || newText.isBogus()) { return *this; } pinIndices(start, length); oldText.pinIndices(oldStart, oldLength); newText.pinIndices(newStart, newLength); if(oldLength == 0) { return *this; } while(length > 0 && length >= oldLength) { int32_t pos = indexOf(oldText, oldStart, oldLength, start, length); if(pos < 0) { // no more oldText's here: done break; } else { // we found oldText, replace it by newText and go beyond it replace(pos, oldLength, newText, newStart, newLength); length -= pos + oldLength - start; start = pos + newLength; } } return *this; } void UnicodeString::setToBogus() { releaseArray(); fUnion.fFields.fLengthAndFlags = kIsBogus; fUnion.fFields.fArray = 0; fUnion.fFields.fCapacity = 0; } // turn a bogus string into an empty one void UnicodeString::unBogus() { if(fUnion.fFields.fLengthAndFlags & kIsBogus) { setToEmpty(); } } const char16_t * UnicodeString::getTerminatedBuffer() { if(!isWritable()) { return nullptr; } UChar *array = getArrayStart(); int32_t len = length(); if(len < getCapacity()) { if(fUnion.fFields.fLengthAndFlags & kBufferIsReadonly) { // If len<capacity on a read-only alias, then array[len] is // either the original NUL (if constructed with (TRUE, s, length)) // or one of the original string contents characters (if later truncated), // therefore we can assume that array[len] is initialized memory. if(array[len] == 0) { return array; } } else if(((fUnion.fFields.fLengthAndFlags & kRefCounted) == 0 || refCount() == 1)) { // kRefCounted: Do not write the NUL if the buffer is shared. // That is mostly safe, except when the length of one copy was modified // without copy-on-write, e.g., via truncate(newLength) or remove(void). // Then the NUL would be written into the middle of another copy's string. // Otherwise, the buffer is fully writable and it is anyway safe to write the NUL. // Do not test if there is a NUL already because it might be uninitialized memory. // (That would be safe, but tools like valgrind & Purify would complain.) array[len] = 0; return array; } } if(len<INT32_MAX && cloneArrayIfNeeded(len+1)) { array = getArrayStart(); array[len] = 0; return array; } else { return nullptr; } } // setTo() analogous to the readonly-aliasing constructor with the same signature UnicodeString & UnicodeString::setTo(UBool isTerminated, ConstChar16Ptr textPtr, int32_t textLength) { if(fUnion.fFields.fLengthAndFlags & kOpenGetBuffer) { // do not modify a string that has an "open" getBuffer(minCapacity) return *this; } const UChar *text = textPtr; if(text == NULL) { // treat as an empty string, do not alias releaseArray(); setToEmpty(); return *this; } if( textLength < -1 || (textLength == -1 && !isTerminated) || (textLength >= 0 && isTerminated && text[textLength] != 0) ) { setToBogus(); return *this; } releaseArray(); if(textLength == -1) { // text is terminated, or else it would have failed the above test textLength = u_strlen(text); } fUnion.fFields.fLengthAndFlags = kReadonlyAlias; setArray((UChar *)text, textLength, isTerminated ? textLength + 1 : textLength); return *this; } // setTo() analogous to the writable-aliasing constructor with the same signature UnicodeString & UnicodeString::setTo(UChar *buffer, int32_t buffLength, int32_t buffCapacity) { if(fUnion.fFields.fLengthAndFlags & kOpenGetBuffer) { // do not modify a string that has an "open" getBuffer(minCapacity) return *this; } if(buffer == NULL) { // treat as an empty string, do not alias releaseArray(); setToEmpty(); return *this; } if(buffLength < -1 || buffCapacity < 0 || buffLength > buffCapacity) { setToBogus(); return *this; } else if(buffLength == -1) { // buffLength = u_strlen(buff); but do not look beyond buffCapacity const UChar *p = buffer, *limit = buffer + buffCapacity; while(p != limit && *p != 0) { ++p; } buffLength = (int32_t)(p - buffer); } releaseArray(); fUnion.fFields.fLengthAndFlags = kWritableAlias; setArray(buffer, buffLength, buffCapacity); return *this; } UnicodeString &UnicodeString::setToUTF8(StringPiece utf8) { unBogus(); int32_t length = utf8.length(); int32_t capacity; // The UTF-16 string will be at most as long as the UTF-8 string. if(length <= US_STACKBUF_SIZE) { capacity = US_STACKBUF_SIZE; } else { capacity = length + 1; // +1 for the terminating NUL. } UChar *utf16 = getBuffer(capacity); int32_t length16; UErrorCode errorCode = U_ZERO_ERROR; u_strFromUTF8WithSub(utf16, getCapacity(), &length16, utf8.data(), length, 0xfffd, // Substitution character. NULL, // Don't care about number of substitutions. &errorCode); releaseBuffer(length16); if(U_FAILURE(errorCode)) { setToBogus(); } return *this; } UnicodeString& UnicodeString::setCharAt(int32_t offset, UChar c) { int32_t len = length(); if(cloneArrayIfNeeded() && len > 0) { if(offset < 0) { offset = 0; } else if(offset >= len) { offset = len - 1; } getArrayStart()[offset] = c; } return *this; } UnicodeString& UnicodeString::replace(int32_t start, int32_t _length, UChar32 srcChar) { UChar buffer[U16_MAX_LENGTH]; int32_t count = 0; UBool isError = FALSE; U16_APPEND(buffer, count, U16_MAX_LENGTH, srcChar, isError); // We test isError so that the compiler does not complain that we don't. // If isError (srcChar is not a valid code point) then count==0 which means // we remove the source segment rather than replacing it with srcChar. return doReplace(start, _length, buffer, 0, isError ? 0 : count); } UnicodeString& UnicodeString::append(UChar32 srcChar) { UChar buffer[U16_MAX_LENGTH]; int32_t _length = 0; UBool isError = FALSE; U16_APPEND(buffer, _length, U16_MAX_LENGTH, srcChar, isError); // We test isError so that the compiler does not complain that we don't. // If isError then _length==0 which turns the doAppend() into a no-op anyway. return isError ? *this : doAppend(buffer, 0, _length); } UnicodeString& UnicodeString::doReplace( int32_t start, int32_t length, const UnicodeString& src, int32_t srcStart, int32_t srcLength) { // pin the indices to legal values src.pinIndices(srcStart, srcLength); // get the characters from src // and replace the range in ourselves with them return doReplace(start, length, src.getArrayStart(), srcStart, srcLength); } UnicodeString& UnicodeString::doReplace(int32_t start, int32_t length, const UChar *srcChars, int32_t srcStart, int32_t srcLength) { if(!isWritable()) { return *this; } int32_t oldLength = this->length(); // optimize (read-only alias).remove(0, start) and .remove(start, end) if((fUnion.fFields.fLengthAndFlags&kBufferIsReadonly) && srcLength == 0) { if(start == 0) { // remove prefix by adjusting the array pointer pinIndex(length); fUnion.fFields.fArray += length; fUnion.fFields.fCapacity -= length; setLength(oldLength - length); return *this; } else { pinIndex(start); if(length >= (oldLength - start)) { // remove suffix by reducing the length (like truncate()) setLength(start); fUnion.fFields.fCapacity = start; // not NUL-terminated any more return *this; } } } if(start == oldLength) { return doAppend(srcChars, srcStart, srcLength); } if(srcChars == 0) { srcLength = 0; } else { // Perform all remaining operations relative to srcChars + srcStart. // From this point forward, do not use srcStart. srcChars += srcStart; if (srcLength < 0) { // get the srcLength if necessary srcLength = u_strlen(srcChars); } } // pin the indices to legal values pinIndices(start, length); // Calculate the size of the string after the replace. // Avoid int32_t overflow. int32_t newLength = oldLength - length; if(srcLength > (INT32_MAX - newLength)) { setToBogus(); return *this; } newLength += srcLength; // Check for insertion into ourself const UChar *oldArray = getArrayStart(); if (isBufferWritable() && oldArray < srcChars + srcLength && srcChars < oldArray + oldLength) { // Copy into a new UnicodeString and start over UnicodeString copy(srcChars, srcLength); if (copy.isBogus()) { setToBogus(); return *this; } return doReplace(start, length, copy.getArrayStart(), 0, srcLength); } // cloneArrayIfNeeded(doCopyArray=FALSE) may change fArray but will not copy the current contents; // therefore we need to keep the current fArray UChar oldStackBuffer[US_STACKBUF_SIZE]; if((fUnion.fFields.fLengthAndFlags&kUsingStackBuffer) && (newLength > US_STACKBUF_SIZE)) { // copy the stack buffer contents because it will be overwritten with // fUnion.fFields values u_memcpy(oldStackBuffer, oldArray, oldLength); oldArray = oldStackBuffer; } // clone our array and allocate a bigger array if needed int32_t *bufferToDelete = 0; if(!cloneArrayIfNeeded(newLength, getGrowCapacity(newLength), FALSE, &bufferToDelete) ) { return *this; } // now do the replace UChar *newArray = getArrayStart(); if(newArray != oldArray) { // if fArray changed, then we need to copy everything except what will change us_arrayCopy(oldArray, 0, newArray, 0, start); us_arrayCopy(oldArray, start + length, newArray, start + srcLength, oldLength - (start + length)); } else if(length != srcLength) { // fArray did not change; copy only the portion that isn't changing, leaving a hole us_arrayCopy(oldArray, start + length, newArray, start + srcLength, oldLength - (start + length)); } // now fill in the hole with the new string us_arrayCopy(srcChars, 0, newArray, start, srcLength); setLength(newLength); // delayed delete in case srcChars == fArray when we started, and // to keep oldArray alive for the above operations if (bufferToDelete) { uprv_free(bufferToDelete); } return *this; } // Versions of doReplace() only for append() variants. // doReplace() and doAppend() optimize for different cases. UnicodeString& UnicodeString::doAppend(const UnicodeString& src, int32_t srcStart, int32_t srcLength) { if(srcLength == 0) { return *this; } // pin the indices to legal values src.pinIndices(srcStart, srcLength); return doAppend(src.getArrayStart(), srcStart, srcLength); } UnicodeString& UnicodeString::doAppend(const UChar *srcChars, int32_t srcStart, int32_t srcLength) { if(!isWritable() || srcLength == 0 || srcChars == NULL) { return *this; } // Perform all remaining operations relative to srcChars + srcStart. // From this point forward, do not use srcStart. srcChars += srcStart; if(srcLength < 0) { // get the srcLength if necessary if((srcLength = u_strlen(srcChars)) == 0) { return *this; } } int32_t oldLength = length(); int32_t newLength = oldLength + srcLength; // Check for append onto ourself const UChar* oldArray = getArrayStart(); if (isBufferWritable() && oldArray < srcChars + srcLength && srcChars < oldArray + oldLength) { // Copy into a new UnicodeString and start over UnicodeString copy(srcChars, srcLength); if (copy.isBogus()) { setToBogus(); return *this; } return doAppend(copy.getArrayStart(), 0, srcLength); } // optimize append() onto a large-enough, owned string if((newLength <= getCapacity() && isBufferWritable()) || cloneArrayIfNeeded(newLength, getGrowCapacity(newLength))) { UChar *newArray = getArrayStart(); // Do not copy characters when // UChar *buffer=str.getAppendBuffer(...); // is followed by // str.append(buffer, length); // or // str.appendString(buffer, length) // or similar. if(srcChars != newArray + oldLength) { us_arrayCopy(srcChars, 0, newArray, oldLength, srcLength); } setLength(newLength); } return *this; } /** * Replaceable API */ void UnicodeString::handleReplaceBetween(int32_t start, int32_t limit, const UnicodeString& text) { replaceBetween(start, limit, text); } /** * Replaceable API */ void UnicodeString::copy(int32_t start, int32_t limit, int32_t dest) { if (limit <= start) { return; // Nothing to do; avoid bogus malloc call } UChar* text = (UChar*) uprv_malloc( sizeof(UChar) * (limit - start) ); // Check to make sure text is not null. if (text != NULL) { extractBetween(start, limit, text, 0); insert(dest, text, 0, limit - start); uprv_free(text); } } /** * Replaceable API * * NOTE: This is for the Replaceable class. There is no rep.cpp, * so we implement this function here. */ UBool Replaceable::hasMetaData() const { return TRUE; } /** * Replaceable API */ UBool UnicodeString::hasMetaData() const { return FALSE; } UnicodeString& UnicodeString::doReverse(int32_t start, int32_t length) { if(length <= 1 || !cloneArrayIfNeeded()) { return *this; } // pin the indices to legal values pinIndices(start, length); if(length <= 1) { // pinIndices() might have shrunk the length return *this; } UChar *left = getArrayStart() + start; UChar *right = left + length - 1; // -1 for inclusive boundary (length>=2) UChar swap; UBool hasSupplementary = FALSE; // Before the loop we know left<right because length>=2. do { hasSupplementary |= (UBool)U16_IS_LEAD(swap = *left); hasSupplementary |= (UBool)U16_IS_LEAD(*left++ = *right); *right-- = swap; } while(left < right); // Make sure to test the middle code unit of an odd-length string. // Redundant if the length is even. hasSupplementary |= (UBool)U16_IS_LEAD(*left); /* if there are supplementary code points in the reversed range, then re-swap their surrogates */ if(hasSupplementary) { UChar swap2; left = getArrayStart() + start; right = left + length - 1; // -1 so that we can look at *(left+1) if left<right while(left < right) { if(U16_IS_TRAIL(swap = *left) && U16_IS_LEAD(swap2 = *(left + 1))) { *left++ = swap2; *left++ = swap; } else { ++left; } } } return *this; } UBool UnicodeString::padLeading(int32_t targetLength, UChar padChar) { int32_t oldLength = length(); if(oldLength >= targetLength || !cloneArrayIfNeeded(targetLength)) { return FALSE; } else { // move contents up by padding width UChar *array = getArrayStart(); int32_t start = targetLength - oldLength; us_arrayCopy(array, 0, array, start, oldLength); // fill in padding character while(--start >= 0) { array[start] = padChar; } setLength(targetLength); return TRUE; } } UBool UnicodeString::padTrailing(int32_t targetLength, UChar padChar) { int32_t oldLength = length(); if(oldLength >= targetLength || !cloneArrayIfNeeded(targetLength)) { return FALSE; } else { // fill in padding character UChar *array = getArrayStart(); int32_t length = targetLength; while(--length >= oldLength) { array[length] = padChar; } setLength(targetLength); return TRUE; } } //======================================== // Hashing //======================================== int32_t UnicodeString::doHashCode() const { /* Delegate hash computation to uhash. This makes UnicodeString * hashing consistent with UChar* hashing. */ int32_t hashCode = ustr_hashUCharsN(getArrayStart(), length()); if (hashCode == kInvalidHashCode) { hashCode = kEmptyHashCode; } return hashCode; } //======================================== // External Buffer //======================================== char16_t * UnicodeString::getBuffer(int32_t minCapacity) { if(minCapacity>=-1 && cloneArrayIfNeeded(minCapacity)) { fUnion.fFields.fLengthAndFlags|=kOpenGetBuffer; setZeroLength(); return getArrayStart(); } else { return nullptr; } } void UnicodeString::releaseBuffer(int32_t newLength) { if(fUnion.fFields.fLengthAndFlags&kOpenGetBuffer && newLength>=-1) { // set the new fLength int32_t capacity=getCapacity(); if(newLength==-1) { // the new length is the string length, capped by fCapacity const UChar *array=getArrayStart(), *p=array, *limit=array+capacity; while(p<limit && *p!=0) { ++p; } newLength=(int32_t)(p-array); } else if(newLength>capacity) { newLength=capacity; } setLength(newLength); fUnion.fFields.fLengthAndFlags&=~kOpenGetBuffer; } } //======================================== // Miscellaneous //======================================== UBool UnicodeString::cloneArrayIfNeeded(int32_t newCapacity, int32_t growCapacity, UBool doCopyArray, int32_t **pBufferToDelete, UBool forceClone) { // default parameters need to be static, therefore // the defaults are -1 to have convenience defaults if(newCapacity == -1) { newCapacity = getCapacity(); } // while a getBuffer(minCapacity) is "open", // prevent any modifications of the string by returning FALSE here // if the string is bogus, then only an assignment or similar can revive it if(!isWritable()) { return FALSE; } /* * We need to make a copy of the array if * the buffer is read-only, or * the buffer is refCounted (shared), and refCount>1, or * the buffer is too small. * Return FALSE if memory could not be allocated. */ if(forceClone || fUnion.fFields.fLengthAndFlags & kBufferIsReadonly || (fUnion.fFields.fLengthAndFlags & kRefCounted && refCount() > 1) || newCapacity > getCapacity() ) { // check growCapacity for default value and use of the stack buffer if(growCapacity < 0) { growCapacity = newCapacity; } else if(newCapacity <= US_STACKBUF_SIZE && growCapacity > US_STACKBUF_SIZE) { growCapacity = US_STACKBUF_SIZE; } // save old values UChar oldStackBuffer[US_STACKBUF_SIZE]; UChar *oldArray; int32_t oldLength = length(); int16_t flags = fUnion.fFields.fLengthAndFlags; if(flags&kUsingStackBuffer) { U_ASSERT(!(flags&kRefCounted)); /* kRefCounted and kUsingStackBuffer are mutally exclusive */ if(doCopyArray && growCapacity > US_STACKBUF_SIZE) { // copy the stack buffer contents because it will be overwritten with // fUnion.fFields values us_arrayCopy(fUnion.fStackFields.fBuffer, 0, oldStackBuffer, 0, oldLength); oldArray = oldStackBuffer; } else { oldArray = NULL; // no need to copy from the stack buffer to itself } } else { oldArray = fUnion.fFields.fArray; U_ASSERT(oldArray!=NULL); /* when stack buffer is not used, oldArray must have a non-NULL reference */ } // allocate a new array if(allocate(growCapacity) || (newCapacity < growCapacity && allocate(newCapacity)) ) { if(doCopyArray) { // copy the contents // do not copy more than what fits - it may be smaller than before int32_t minLength = oldLength; newCapacity = getCapacity(); if(newCapacity < minLength) { minLength = newCapacity; } if(oldArray != NULL) { us_arrayCopy(oldArray, 0, getArrayStart(), 0, minLength); } setLength(minLength); } else { setZeroLength(); } // release the old array if(flags & kRefCounted) { // the array is refCounted; decrement and release if 0 u_atomic_int32_t *pRefCount = ((u_atomic_int32_t *)oldArray - 1); if(umtx_atomic_dec(pRefCount) == 0) { if(pBufferToDelete == 0) { // Note: cast to (void *) is needed with MSVC, where u_atomic_int32_t // is defined as volatile. (Volatile has useful non-standard behavior // with this compiler.) uprv_free((void *)pRefCount); } else { // the caller requested to delete it himself *pBufferToDelete = (int32_t *)pRefCount; } } } } else { // not enough memory for growCapacity and not even for the smaller newCapacity // reset the old values for setToBogus() to release the array if(!(flags&kUsingStackBuffer)) { fUnion.fFields.fArray = oldArray; } fUnion.fFields.fLengthAndFlags = flags; setToBogus(); return FALSE; } } return TRUE; } // UnicodeStringAppendable ------------------------------------------------- *** UnicodeStringAppendable::~UnicodeStringAppendable() {} UBool UnicodeStringAppendable::appendCodeUnit(UChar c) { return str.doAppend(&c, 0, 1).isWritable(); } UBool UnicodeStringAppendable::appendCodePoint(UChar32 c) { UChar buffer[U16_MAX_LENGTH]; int32_t cLength = 0; UBool isError = FALSE; U16_APPEND(buffer, cLength, U16_MAX_LENGTH, c, isError); return !isError && str.doAppend(buffer, 0, cLength).isWritable(); } UBool UnicodeStringAppendable::appendString(const UChar *s, int32_t length) { return str.doAppend(s, 0, length).isWritable(); } UBool UnicodeStringAppendable::reserveAppendCapacity(int32_t appendCapacity) { return str.cloneArrayIfNeeded(str.length() + appendCapacity); } UChar * UnicodeStringAppendable::getAppendBuffer(int32_t minCapacity, int32_t desiredCapacityHint, UChar *scratch, int32_t scratchCapacity, int32_t *resultCapacity) { if(minCapacity < 1 || scratchCapacity < minCapacity) { *resultCapacity = 0; return NULL; } int32_t oldLength = str.length(); if(minCapacity <= (kMaxCapacity - oldLength) && desiredCapacityHint <= (kMaxCapacity - oldLength) && str.cloneArrayIfNeeded(oldLength + minCapacity, oldLength + desiredCapacityHint)) { *resultCapacity = str.getCapacity() - oldLength; return str.getArrayStart() + oldLength; } *resultCapacity = scratchCapacity; return scratch; } U_NAMESPACE_END U_NAMESPACE_USE U_CAPI int32_t U_EXPORT2 uhash_hashUnicodeString(const UElement key) { const UnicodeString *str = (const UnicodeString*) key.pointer; return (str == NULL) ? 0 : str->hashCode(); } // Moved here from uhash_us.cpp so that using a UVector of UnicodeString* // does not depend on hashtable code. U_CAPI UBool U_EXPORT2 uhash_compareUnicodeString(const UElement key1, const UElement key2) { const UnicodeString *str1 = (const UnicodeString*) key1.pointer; const UnicodeString *str2 = (const UnicodeString*) key2.pointer; if (str1 == str2) { return TRUE; } if (str1 == NULL || str2 == NULL) { return FALSE; } return *str1 == *str2; } #ifdef U_STATIC_IMPLEMENTATION /* This should never be called. It is defined here to make sure that the virtual vector deleting destructor is defined within unistr.cpp. The vector deleting destructor is already a part of UObject, but defining it here makes sure that it is included with this object file. This makes sure that static library dependencies are kept to a minimum. */ static void uprv_UnicodeStringDummy(void) { delete [] (new UnicodeString[2]); } #endif
null
// © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /* ****************************************************************************** * Copyright (C) 1999-2016, International Business Machines Corporation and * others. All Rights Reserved. ****************************************************************************** * * File unistr.cpp * * Modification History: * * Date Name Description * 09/25/98 stephen Creation. * 04/20/99 stephen Overhauled per 4/16 code review. * 07/09/99 stephen Renamed {hi,lo},{byte,word} to icu_X for HP/UX * 11/18/99 aliu Added handleReplaceBetween() to make inherit from * Replaceable. * 06/25/01 grhoten Removed the dependency on iostream ****************************************************************************** */ #include "unicode/utypes.h" #include "unicode/appendable.h" #include "unicode/putil.h" #include "cstring.h" #include "cmemory.h" #include "unicode/ustring.h" #include "unicode/unistr.h" #include "unicode/utf.h" #include "unicode/utf16.h" #include "uelement.h" #include "ustr_imp.h" #include "umutex.h" #include "uassert.h" #if 0 #include <iostream> using namespace std; //DEBUGGING void print(const UnicodeString& s, const char *name) { UChar c; cout << name << ":|"; for(int i = 0; i < s.length(); ++i) { c = s[i]; if(c>= 0x007E || c < 0x0020) cout << "[0x" << hex << s[i] << "]"; else cout << (char) s[i]; } cout << '|' << endl; } void print(const UChar *s, int32_t len, const char *name) { UChar c; cout << name << ":|"; for(int i = 0; i < len; ++i) { c = s[i]; if(c>= 0x007E || c < 0x0020) cout << "[0x" << hex << s[i] << "]"; else cout << (char) s[i]; } cout << '|' << endl; } // END DEBUGGING #endif // Local function definitions for now // need to copy areas that may overlap static inline void us_arrayCopy(const UChar *src, int32_t srcStart, UChar *dst, int32_t dstStart, int32_t count) { if(count>0) { uprv_memmove(dst+dstStart, src+srcStart, (size_t)count*sizeof(*src)); } } // u_unescapeAt() callback to get a UChar from a UnicodeString U_CDECL_BEGIN static UChar U_CALLCONV UnicodeString_charAt(int32_t offset, void *context) { return ((icu::UnicodeString*) context)->charAt(offset); } U_CDECL_END U_NAMESPACE_BEGIN /* The Replaceable virtual destructor can't be defined in the header due to how AIX works with multiple definitions of virtual functions. */ Replaceable::~Replaceable() {} UOBJECT_DEFINE_RTTI_IMPLEMENTATION(UnicodeString) UnicodeString U_EXPORT2 operator+ (const UnicodeString &s1, const UnicodeString &s2) { return UnicodeString(s1.length()+s2.length()+1, (UChar32)0, 0). append(s1). append(s2); } //======================================== // Reference Counting functions, put at top of file so that optimizing compilers // have a chance to automatically inline. //======================================== void UnicodeString::addRef() { umtx_atomic_inc((u_atomic_int32_t *)fUnion.fFields.fArray - 1); } int32_t UnicodeString::removeRef() { return umtx_atomic_dec((u_atomic_int32_t *)fUnion.fFields.fArray - 1); } int32_t UnicodeString::refCount() const { return umtx_loadAcquire(*((u_atomic_int32_t *)fUnion.fFields.fArray - 1)); } void UnicodeString::releaseArray() { if((fUnion.fFields.fLengthAndFlags & kRefCounted) && removeRef() == 0) { uprv_free((int32_t *)fUnion.fFields.fArray - 1); } } //======================================== // Constructors //======================================== // The default constructor is inline in unistr.h. UnicodeString::UnicodeString(int32_t capacity, UChar32 c, int32_t count) { fUnion.fFields.fLengthAndFlags = 0; if(count <= 0 || (uint32_t)c > 0x10ffff) { // just allocate and do not do anything else allocate(capacity); } else if(c <= 0xffff) { int32_t length = count; if(capacity < length) { capacity = length; } if(allocate(capacity)) { UChar *array = getArrayStart(); UChar unit = (UChar)c; for(int32_t i = 0; i < length; ++i) { array[i] = unit; } setLength(length); } } else { // supplementary code point, write surrogate pairs if(count > (INT32_MAX / 2)) { // We would get more than 2G UChars. allocate(capacity); return; } int32_t length = count * 2; if(capacity < length) { capacity = length; } if(allocate(capacity)) { UChar *array = getArrayStart(); UChar lead = U16_LEAD(c); UChar trail = U16_TRAIL(c); for(int32_t i = 0; i < length; i += 2) { array[i] = lead; array[i + 1] = trail; } setLength(length); } } } UnicodeString::UnicodeString(UChar ch) { fUnion.fFields.fLengthAndFlags = kLength1 | kShortString; fUnion.fStackFields.fBuffer[0] = ch; } UnicodeString::UnicodeString(UChar32 ch) { fUnion.fFields.fLengthAndFlags = kShortString; int32_t i = 0; UBool isError = FALSE; U16_APPEND(fUnion.fStackFields.fBuffer, i, US_STACKBUF_SIZE, ch, isError); // We test isError so that the compiler does not complain that we don't. // If isError then i==0 which is what we want anyway. if(!isError) { setShortLength(i); } } UnicodeString::UnicodeString(const UChar *text) { fUnion.fFields.fLengthAndFlags = kShortString; doAppend(text, 0, -1); } UnicodeString::UnicodeString(const UChar *text, int32_t textLength) { fUnion.fFields.fLengthAndFlags = kShortString; doAppend(text, 0, textLength); } UnicodeString::UnicodeString(UBool isTerminated, ConstChar16Ptr textPtr, int32_t textLength) { fUnion.fFields.fLengthAndFlags = kReadonlyAlias; const UChar *text = textPtr; if(text == NULL) { // treat as an empty string, do not alias setToEmpty(); } else if(textLength < -1 || (textLength == -1 && !isTerminated) || (textLength >= 0 && isTerminated && text[textLength] != 0) ) { setToBogus(); } else { if(textLength == -1) { // text is terminated, or else it would have failed the above test textLength = u_strlen(text); } setArray(const_cast<UChar *>(text), textLength, isTerminated ? textLength + 1 : textLength); } } UnicodeString::UnicodeString(UChar *buff, int32_t buffLength, int32_t buffCapacity) { fUnion.fFields.fLengthAndFlags = kWritableAlias; if(buff == NULL) { // treat as an empty string, do not alias setToEmpty(); } else if(buffLength < -1 || buffCapacity < 0 || buffLength > buffCapacity) { setToBogus(); } else { if(buffLength == -1) { // fLength = u_strlen(buff); but do not look beyond buffCapacity const UChar *p = buff, *limit = buff + buffCapacity; while(p != limit && *p != 0) { ++p; } buffLength = (int32_t)(p - buff); } setArray(buff, buffLength, buffCapacity); } } UnicodeString::UnicodeString(const char *src, int32_t length, EInvariant) { fUnion.fFields.fLengthAndFlags = kShortString; if(src==NULL) { // treat as an empty string } else { if(length<0) { length=(int32_t)uprv_strlen(src); } if(cloneArrayIfNeeded(length, length, FALSE)) { u_charsToUChars(src, getArrayStart(), length); setLength(length); } else { setToBogus(); } } } #if U_CHARSET_IS_UTF8 UnicodeString::UnicodeString(const char *codepageData) { fUnion.fFields.fLengthAndFlags = kShortString; if(codepageData != 0) { setToUTF8(codepageData); } } UnicodeString::UnicodeString(const char *codepageData, int32_t dataLength) { fUnion.fFields.fLengthAndFlags = kShortString; // if there's nothing to convert, do nothing if(codepageData == 0 || dataLength == 0 || dataLength < -1) { return; } if(dataLength == -1) { dataLength = (int32_t)uprv_strlen(codepageData); } setToUTF8(StringPiece(codepageData, dataLength)); } // else see unistr_cnv.cpp #endif UnicodeString::UnicodeString(const UnicodeString& that) { fUnion.fFields.fLengthAndFlags = kShortString; copyFrom(that); } UnicodeString::UnicodeString(UnicodeString &&src) U_NOEXCEPT { copyFieldsFrom(src, TRUE); } UnicodeString::UnicodeString(const UnicodeString& that, int32_t srcStart) { fUnion.fFields.fLengthAndFlags = kShortString; setTo(that, srcStart); } UnicodeString::UnicodeString(const UnicodeString& that, int32_t srcStart, int32_t srcLength) { fUnion.fFields.fLengthAndFlags = kShortString; setTo(that, srcStart, srcLength); } // Replaceable base class clone() default implementation, does not clone Replaceable * Replaceable::clone() const { return NULL; } // UnicodeString overrides clone() with a real implementation UnicodeString * UnicodeString::clone() const { return new UnicodeString(*this); } //======================================== // array allocation //======================================== namespace { const int32_t kGrowSize = 128; // The number of bytes for one int32_t reference counter and capacity UChars // must fit into a 32-bit size_t (at least when on a 32-bit platform). // We also add one for the NUL terminator, to avoid reallocation in getTerminatedBuffer(), // and round up to a multiple of 16 bytes. // This means that capacity must be at most (0xfffffff0 - 4) / 2 - 1 = 0x7ffffff5. // (With more complicated checks we could go up to 0x7ffffffd without rounding up, // but that does not seem worth it.) const int32_t kMaxCapacity = 0x7ffffff5; int32_t getGrowCapacity(int32_t newLength) { int32_t growSize = (newLength >> 2) + kGrowSize; if(growSize <= (kMaxCapacity - newLength)) { return newLength + growSize; } else { return kMaxCapacity; } } } // namespace UBool UnicodeString::allocate(int32_t capacity) { if(capacity <= US_STACKBUF_SIZE) { fUnion.fFields.fLengthAndFlags = kShortString; return TRUE; } if(capacity <= kMaxCapacity) { ++capacity; // for the NUL // Switch to size_t which is unsigned so that we can allocate up to 4GB. // Reference counter + UChars. size_t numBytes = sizeof(int32_t) + (size_t)capacity * U_SIZEOF_UCHAR; // Round up to a multiple of 16. numBytes = (numBytes + 15) & ~15; int32_t *array = (int32_t *) uprv_malloc(numBytes); if(array != NULL) { // set initial refCount and point behind the refCount *array++ = 1; numBytes -= sizeof(int32_t); // have fArray point to the first UChar fUnion.fFields.fArray = (UChar *)array; fUnion.fFields.fCapacity = (int32_t)(numBytes / U_SIZEOF_UCHAR); fUnion.fFields.fLengthAndFlags = kLongString; return TRUE; } } fUnion.fFields.fLengthAndFlags = kIsBogus; fUnion.fFields.fArray = 0; fUnion.fFields.fCapacity = 0; return FALSE; } //======================================== // Destructor //======================================== #ifdef UNISTR_COUNT_FINAL_STRING_LENGTHS static u_atomic_int32_t finalLengthCounts[0x400]; // UnicodeString::kMaxShortLength+1 static u_atomic_int32_t beyondCount(0); U_CAPI void unistr_printLengths() { int32_t i; for(i = 0; i <= 59; ++i) { printf("%2d, %9d\n", i, (int32_t)finalLengthCounts[i]); } int32_t beyond = beyondCount; for(; i < UPRV_LENGTHOF(finalLengthCounts); ++i) { beyond += finalLengthCounts[i]; } printf(">59, %9d\n", beyond); } #endif UnicodeString::~UnicodeString() { #ifdef UNISTR_COUNT_FINAL_STRING_LENGTHS // Count lengths of strings at the end of their lifetime. // Useful for discussion of a desirable stack buffer size. // Count the contents length, not the optional NUL terminator nor further capacity. // Ignore open-buffer strings and strings which alias external storage. if((fUnion.fFields.fLengthAndFlags&(kOpenGetBuffer|kReadonlyAlias|kWritableAlias)) == 0) { if(hasShortLength()) { umtx_atomic_inc(finalLengthCounts + getShortLength()); } else { umtx_atomic_inc(&beyondCount); } } #endif releaseArray(); } //======================================== // Factory methods //======================================== UnicodeString UnicodeString::fromUTF8(StringPiece utf8) { UnicodeString result; result.setToUTF8(utf8); return result; } UnicodeString UnicodeString::fromUTF32(const UChar32 *utf32, int32_t length) { UnicodeString result; int32_t capacity; // Most UTF-32 strings will be BMP-only and result in a same-length // UTF-16 string. We overestimate the capacity just slightly, // just in case there are a few supplementary characters. if(length <= US_STACKBUF_SIZE) { capacity = US_STACKBUF_SIZE; } else { capacity = length + (length >> 4) + 4; } do { UChar *utf16 = result.getBuffer(capacity); int32_t length16; UErrorCode errorCode = U_ZERO_ERROR; u_strFromUTF32WithSub(utf16, result.getCapacity(), &length16, utf32, length, 0xfffd, // Substitution character. NULL, // Don't care about number of substitutions. &errorCode); result.releaseBuffer(length16); if(errorCode == U_BUFFER_OVERFLOW_ERROR) { capacity = length16 + 1; // +1 for the terminating NUL. continue; } else if(U_FAILURE(errorCode)) { result.setToBogus(); } break; } while(TRUE); return result; } //======================================== // Assignment //======================================== UnicodeString & UnicodeString::operator=(const UnicodeString &src) { return copyFrom(src); } UnicodeString & UnicodeString::fastCopyFrom(const UnicodeString &src) { return copyFrom(src, TRUE); } UnicodeString & UnicodeString::copyFrom(const UnicodeString &src, UBool fastCopy) { // if assigning to ourselves, do nothing if(this == &src) { return *this; } // is the right side bogus? if(src.isBogus()) { setToBogus(); return *this; } // delete the current contents releaseArray(); if(src.isEmpty()) { // empty string - use the stack buffer setToEmpty(); return *this; } // fLength>0 and not an "open" src.getBuffer(minCapacity) fUnion.fFields.fLengthAndFlags = src.fUnion.fFields.fLengthAndFlags; switch(src.fUnion.fFields.fLengthAndFlags & kAllStorageFlags) { case kShortString: // short string using the stack buffer, do the same uprv_memcpy(fUnion.fStackFields.fBuffer, src.fUnion.fStackFields.fBuffer, getShortLength() * U_SIZEOF_UCHAR); break; case kLongString: // src uses a refCounted string buffer, use that buffer with refCount // src is const, use a cast - we don't actually change it ((UnicodeString &)src).addRef(); // copy all fields, share the reference-counted buffer fUnion.fFields.fArray = src.fUnion.fFields.fArray; fUnion.fFields.fCapacity = src.fUnion.fFields.fCapacity; if(!hasShortLength()) { fUnion.fFields.fLength = src.fUnion.fFields.fLength; } break; case kReadonlyAlias: if(fastCopy) { // src is a readonly alias, do the same // -> maintain the readonly alias as such fUnion.fFields.fArray = src.fUnion.fFields.fArray; fUnion.fFields.fCapacity = src.fUnion.fFields.fCapacity; if(!hasShortLength()) { fUnion.fFields.fLength = src.fUnion.fFields.fLength; } break; } // else if(!fastCopy) fall through to case kWritableAlias // -> allocate a new buffer and copy the contents U_FALLTHROUGH; case kWritableAlias: { // src is a writable alias; we make a copy of that instead int32_t srcLength = src.length(); if(allocate(srcLength)) { u_memcpy(getArrayStart(), src.getArrayStart(), srcLength); setLength(srcLength); break; } // if there is not enough memory, then fall through to setting to bogus U_FALLTHROUGH; } default: // if src is bogus, set ourselves to bogus // do not call setToBogus() here because fArray and flags are not consistent here fUnion.fFields.fLengthAndFlags = kIsBogus; fUnion.fFields.fArray = 0; fUnion.fFields.fCapacity = 0; break; } return *this; } UnicodeString &UnicodeString::operator=(UnicodeString &&src) U_NOEXCEPT { // No explicit check for self move assignment, consistent with standard library. // Self move assignment causes no crash nor leak but might make the object bogus. releaseArray(); copyFieldsFrom(src, TRUE); return *this; } // Same as move assignment except without memory management. void UnicodeString::copyFieldsFrom(UnicodeString &src, UBool setSrcToBogus) U_NOEXCEPT { int16_t lengthAndFlags = fUnion.fFields.fLengthAndFlags = src.fUnion.fFields.fLengthAndFlags; if(lengthAndFlags & kUsingStackBuffer) { // Short string using the stack buffer, copy the contents. // Check for self assignment to prevent "overlap in memcpy" warnings, // although it should be harmless to copy a buffer to itself exactly. if(this != &src) { uprv_memcpy(fUnion.fStackFields.fBuffer, src.fUnion.fStackFields.fBuffer, getShortLength() * U_SIZEOF_UCHAR); } } else { // In all other cases, copy all fields. fUnion.fFields.fArray = src.fUnion.fFields.fArray; fUnion.fFields.fCapacity = src.fUnion.fFields.fCapacity; if(!hasShortLength()) { fUnion.fFields.fLength = src.fUnion.fFields.fLength; } if(setSrcToBogus) { // Set src to bogus without releasing any memory. src.fUnion.fFields.fLengthAndFlags = kIsBogus; src.fUnion.fFields.fArray = NULL; src.fUnion.fFields.fCapacity = 0; } } } void UnicodeString::swap(UnicodeString &other) U_NOEXCEPT { UnicodeString temp; // Empty short string: Known not to need releaseArray(). // Copy fields without resetting source values in between. temp.copyFieldsFrom(*this, FALSE); this->copyFieldsFrom(other, FALSE); other.copyFieldsFrom(temp, FALSE); // Set temp to an empty string so that other's memory is not released twice. temp.fUnion.fFields.fLengthAndFlags = kShortString; } //======================================== // Miscellaneous operations //======================================== UnicodeString UnicodeString::unescape() const { UnicodeString result(length(), (UChar32)0, (int32_t)0); // construct with capacity if (result.isBogus()) { return result; } const UChar *array = getBuffer(); int32_t len = length(); int32_t prev = 0; for (int32_t i=0;;) { if (i == len) { result.append(array, prev, len - prev); break; } if (array[i++] == 0x5C /*'\\'*/) { result.append(array, prev, (i - 1) - prev); UChar32 c = unescapeAt(i); // advances i if (c < 0) { result.remove(); // return empty string break; // invalid escape sequence } result.append(c); prev = i; } } return result; } UChar32 UnicodeString::unescapeAt(int32_t &offset) const { return u_unescapeAt(UnicodeString_charAt, &offset, length(), (void*)this); } //======================================== // Read-only implementation //======================================== UBool UnicodeString::doEquals(const UnicodeString &text, int32_t len) const { // Requires: this & text not bogus and have same lengths. // Byte-wise comparison works for equality regardless of endianness. return uprv_memcmp(getArrayStart(), text.getArrayStart(), len * U_SIZEOF_UCHAR) == 0; } int8_t UnicodeString::doCompare( int32_t start, int32_t length, const UChar *srcChars, int32_t srcStart, int32_t srcLength) const { // compare illegal string values if(isBogus()) { return -1; } // pin indices to legal values pinIndices(start, length); if(srcChars == NULL) { // treat const UChar *srcChars==NULL as an empty string return length == 0 ? 0 : 1; } // get the correct pointer const UChar *chars = getArrayStart(); chars += start; srcChars += srcStart; int32_t minLength; int8_t lengthResult; // get the srcLength if necessary if(srcLength < 0) { srcLength = u_strlen(srcChars + srcStart); } // are we comparing different lengths? if(length != srcLength) { if(length < srcLength) { minLength = length; lengthResult = -1; } else { minLength = srcLength; lengthResult = 1; } } else { minLength = length; lengthResult = 0; } /* * note that uprv_memcmp() returns an int but we return an int8_t; * we need to take care not to truncate the result - * one way to do this is to right-shift the value to * move the sign bit into the lower 8 bits and making sure that this * does not become 0 itself */ if(minLength > 0 && chars != srcChars) { int32_t result; # if U_IS_BIG_ENDIAN // big-endian: byte comparison works result = uprv_memcmp(chars, srcChars, minLength * sizeof(UChar)); if(result != 0) { return (int8_t)(result >> 15 | 1); } # else // little-endian: compare UChar units do { result = ((int32_t)*(chars++) - (int32_t)*(srcChars++)); if(result != 0) { return (int8_t)(result >> 15 | 1); } } while(--minLength > 0); # endif } return lengthResult; } /* String compare in code point order - doCompare() compares in code unit order. */ int8_t UnicodeString::doCompareCodePointOrder(int32_t start, int32_t length, const UChar *srcChars, int32_t srcStart, int32_t srcLength) const { // compare illegal string values // treat const UChar *srcChars==NULL as an empty string if(isBogus()) { return -1; } // pin indices to legal values pinIndices(start, length); if(srcChars == NULL) { srcStart = srcLength = 0; } int32_t diff = uprv_strCompare(getArrayStart() + start, length, (srcChars!=NULL)?(srcChars + srcStart):NULL, srcLength, FALSE, TRUE); /* translate the 32-bit result into an 8-bit one */ if(diff!=0) { return (int8_t)(diff >> 15 | 1); } else { return 0; } } int32_t UnicodeString::getLength() const { return length(); } UChar UnicodeString::getCharAt(int32_t offset) const { return charAt(offset); } UChar32 UnicodeString::getChar32At(int32_t offset) const { return char32At(offset); } UChar32 UnicodeString::char32At(int32_t offset) const { int32_t len = length(); if((uint32_t)offset < (uint32_t)len) { const UChar *array = getArrayStart(); UChar32 c; U16_GET(array, 0, offset, len, c); return c; } else { return kInvalidUChar; } } int32_t UnicodeString::getChar32Start(int32_t offset) const { if((uint32_t)offset < (uint32_t)length()) { const UChar *array = getArrayStart(); U16_SET_CP_START(array, 0, offset); return offset; } else { return 0; } } int32_t UnicodeString::getChar32Limit(int32_t offset) const { int32_t len = length(); if((uint32_t)offset < (uint32_t)len) { const UChar *array = getArrayStart(); U16_SET_CP_LIMIT(array, 0, offset, len); return offset; } else { return len; } } int32_t UnicodeString::countChar32(int32_t start, int32_t length) const { pinIndices(start, length); // if(isBogus()) then fArray==0 and start==0 - u_countChar32() checks for NULL return u_countChar32(getArrayStart()+start, length); } UBool UnicodeString::hasMoreChar32Than(int32_t start, int32_t length, int32_t number) const { pinIndices(start, length); // if(isBogus()) then fArray==0 and start==0 - u_strHasMoreChar32Than() checks for NULL return u_strHasMoreChar32Than(getArrayStart()+start, length, number); } int32_t UnicodeString::moveIndex32(int32_t index, int32_t delta) const { // pin index int32_t len = length(); if(index<0) { index=0; } else if(index>len) { index=len; } const UChar *array = getArrayStart(); if(delta>0) { U16_FWD_N(array, index, len, delta); } else { U16_BACK_N(array, 0, index, -delta); } return index; } void UnicodeString::doExtract(int32_t start, int32_t length, UChar *dst, int32_t dstStart) const { // pin indices to legal values pinIndices(start, length); // do not copy anything if we alias dst itself const UChar *array = getArrayStart(); if(array + start != dst + dstStart) { us_arrayCopy(array, start, dst, dstStart, length); } } int32_t UnicodeString::extract(Char16Ptr dest, int32_t destCapacity, UErrorCode &errorCode) const { int32_t len = length(); if(U_SUCCESS(errorCode)) { if(isBogus() || destCapacity<0 || (destCapacity>0 && dest==0)) { errorCode=U_ILLEGAL_ARGUMENT_ERROR; } else { const UChar *array = getArrayStart(); if(len>0 && len<=destCapacity && array!=dest) { u_memcpy(dest, array, len); } return u_terminateUChars(dest, destCapacity, len, &errorCode); } } return len; } int32_t UnicodeString::extract(int32_t start, int32_t length, char *target, int32_t targetCapacity, enum EInvariant) const { // if the arguments are illegal, then do nothing if(targetCapacity < 0 || (targetCapacity > 0 && target == NULL)) { return 0; } // pin the indices to legal values pinIndices(start, length); if(length <= targetCapacity) { u_UCharsToChars(getArrayStart() + start, target, length); } UErrorCode status = U_ZERO_ERROR; return u_terminateChars(target, targetCapacity, length, &status); } UnicodeString UnicodeString::tempSubString(int32_t start, int32_t len) const { pinIndices(start, len); const UChar *array = getBuffer(); // not getArrayStart() to check kIsBogus & kOpenGetBuffer if(array==NULL) { array=fUnion.fStackFields.fBuffer; // anything not NULL because that would make an empty string len=-2; // bogus result string } return UnicodeString(FALSE, array + start, len); } int32_t UnicodeString::toUTF8(int32_t start, int32_t len, char *target, int32_t capacity) const { pinIndices(start, len); int32_t length8; UErrorCode errorCode = U_ZERO_ERROR; u_strToUTF8WithSub(target, capacity, &length8, getBuffer() + start, len, 0xFFFD, // Standard substitution character. NULL, // Don't care about number of substitutions. &errorCode); return length8; } #if U_CHARSET_IS_UTF8 int32_t UnicodeString::extract(int32_t start, int32_t len, char *target, uint32_t dstSize) const { // if the arguments are illegal, then do nothing if(/*dstSize < 0 || */(dstSize > 0 && target == 0)) { return 0; } return toUTF8(start, len, target, dstSize <= 0x7fffffff ? (int32_t)dstSize : 0x7fffffff); } // else see unistr_cnv.cpp #endif void UnicodeString::extractBetween(int32_t start, int32_t limit, UnicodeString& target) const { pinIndex(start); pinIndex(limit); doExtract(start, limit - start, target); } // When converting from UTF-16 to UTF-8, the result will have at most 3 times // as many bytes as the source has UChars. // The "worst cases" are writing systems like Indic, Thai and CJK with // 3:1 bytes:UChars. void UnicodeString::toUTF8(ByteSink &sink) const { int32_t length16 = length(); if(length16 != 0) { char stackBuffer[1024]; int32_t capacity = (int32_t)sizeof(stackBuffer); UBool utf8IsOwned = FALSE; char *utf8 = sink.GetAppendBuffer(length16 < capacity ? length16 : capacity, 3*length16, stackBuffer, capacity, &capacity); int32_t length8 = 0; UErrorCode errorCode = U_ZERO_ERROR; u_strToUTF8WithSub(utf8, capacity, &length8, getBuffer(), length16, 0xFFFD, // Standard substitution character. NULL, // Don't care about number of substitutions. &errorCode); if(errorCode == U_BUFFER_OVERFLOW_ERROR) { utf8 = (char *)uprv_malloc(length8); if(utf8 != NULL) { utf8IsOwned = TRUE; errorCode = U_ZERO_ERROR; u_strToUTF8WithSub(utf8, length8, &length8, getBuffer(), length16, 0xFFFD, // Standard substitution character. NULL, // Don't care about number of substitutions. &errorCode); } else { errorCode = U_MEMORY_ALLOCATION_ERROR; } } if(U_SUCCESS(errorCode)) { sink.Append(utf8, length8); sink.Flush(); } if(utf8IsOwned) { uprv_free(utf8); } } } int32_t UnicodeString::toUTF32(UChar32 *utf32, int32_t capacity, UErrorCode &errorCode) const { int32_t length32=0; if(U_SUCCESS(errorCode)) { // getBuffer() and u_strToUTF32WithSub() check for illegal arguments. u_strToUTF32WithSub(utf32, capacity, &length32, getBuffer(), length(), 0xfffd, // Substitution character. NULL, // Don't care about number of substitutions. &errorCode); } return length32; } int32_t UnicodeString::indexOf(const UChar *srcChars, int32_t srcStart, int32_t srcLength, int32_t start, int32_t length) const { if(isBogus() || srcChars == 0 || srcStart < 0 || srcLength == 0) { return -1; } // UnicodeString does not find empty substrings if(srcLength < 0 && srcChars[srcStart] == 0) { return -1; } // get the indices within bounds pinIndices(start, length); // find the first occurrence of the substring const UChar *array = getArrayStart(); const UChar *match = u_strFindFirst(array + start, length, srcChars + srcStart, srcLength); if(match == NULL) { return -1; } else { return (int32_t)(match - array); } } int32_t UnicodeString::doIndexOf(UChar c, int32_t start, int32_t length) const { // pin indices pinIndices(start, length); // find the first occurrence of c const UChar *array = getArrayStart(); const UChar *match = u_memchr(array + start, c, length); if(match == NULL) { return -1; } else { return (int32_t)(match - array); } } int32_t UnicodeString::doIndexOf(UChar32 c, int32_t start, int32_t length) const { // pin indices pinIndices(start, length); // find the first occurrence of c const UChar *array = getArrayStart(); const UChar *match = u_memchr32(array + start, c, length); if(match == NULL) { return -1; } else { return (int32_t)(match - array); } } int32_t UnicodeString::lastIndexOf(const UChar *srcChars, int32_t srcStart, int32_t srcLength, int32_t start, int32_t length) const { if(isBogus() || srcChars == 0 || srcStart < 0 || srcLength == 0) { return -1; } // UnicodeString does not find empty substrings if(srcLength < 0 && srcChars[srcStart] == 0) { return -1; } // get the indices within bounds pinIndices(start, length); // find the last occurrence of the substring const UChar *array = getArrayStart(); const UChar *match = u_strFindLast(array + start, length, srcChars + srcStart, srcLength); if(match == NULL) { return -1; } else { return (int32_t)(match - array); } } int32_t UnicodeString::doLastIndexOf(UChar c, int32_t start, int32_t length) const { if(isBogus()) { return -1; } // pin indices pinIndices(start, length); // find the last occurrence of c const UChar *array = getArrayStart(); const UChar *match = u_memrchr(array + start, c, length); if(match == NULL) { return -1; } else { return (int32_t)(match - array); } } int32_t UnicodeString::doLastIndexOf(UChar32 c, int32_t start, int32_t length) const { // pin indices pinIndices(start, length); // find the last occurrence of c const UChar *array = getArrayStart(); const UChar *match = u_memrchr32(array + start, c, length); if(match == NULL) { return -1; } else { return (int32_t)(match - array); } } //======================================== // Write implementation //======================================== UnicodeString& UnicodeString::findAndReplace(int32_t start, int32_t length, const UnicodeString& oldText, int32_t oldStart, int32_t oldLength, const UnicodeString& newText, int32_t newStart, int32_t newLength) { if(isBogus() || oldText.isBogus() || newText.isBogus()) { return *this; } pinIndices(start, length); oldText.pinIndices(oldStart, oldLength); newText.pinIndices(newStart, newLength); if(oldLength == 0) { return *this; } while(length > 0 && length >= oldLength) { int32_t pos = indexOf(oldText, oldStart, oldLength, start, length); if(pos < 0) { // no more oldText's here: done break; } else { // we found oldText, replace it by newText and go beyond it replace(pos, oldLength, newText, newStart, newLength); length -= pos + oldLength - start; start = pos + newLength; } } return *this; } void UnicodeString::setToBogus() { releaseArray(); fUnion.fFields.fLengthAndFlags = kIsBogus; fUnion.fFields.fArray = 0; fUnion.fFields.fCapacity = 0; } // turn a bogus string into an empty one void UnicodeString::unBogus() { if(fUnion.fFields.fLengthAndFlags & kIsBogus) { setToEmpty(); } } const char16_t * UnicodeString::getTerminatedBuffer() { if(!isWritable()) { return nullptr; } UChar *array = getArrayStart(); int32_t len = length(); if(len < getCapacity()) { if(fUnion.fFields.fLengthAndFlags & kBufferIsReadonly) { // If len<capacity on a read-only alias, then array[len] is // either the original NUL (if constructed with (TRUE, s, length)) // or one of the original string contents characters (if later truncated), // therefore we can assume that array[len] is initialized memory. if(array[len] == 0) { return array; } } else if(((fUnion.fFields.fLengthAndFlags & kRefCounted) == 0 || refCount() == 1)) { // kRefCounted: Do not write the NUL if the buffer is shared. // That is mostly safe, except when the length of one copy was modified // without copy-on-write, e.g., via truncate(newLength) or remove(void). // Then the NUL would be written into the middle of another copy's string. // Otherwise, the buffer is fully writable and it is anyway safe to write the NUL. // Do not test if there is a NUL already because it might be uninitialized memory. // (That would be safe, but tools like valgrind & Purify would complain.) array[len] = 0; return array; } } if(len<INT32_MAX && cloneArrayIfNeeded(len+1)) { array = getArrayStart(); array[len] = 0; return array; } else { return nullptr; } } // setTo() analogous to the readonly-aliasing constructor with the same signature UnicodeString & UnicodeString::setTo(UBool isTerminated, ConstChar16Ptr textPtr, int32_t textLength) { if(fUnion.fFields.fLengthAndFlags & kOpenGetBuffer) { // do not modify a string that has an "open" getBuffer(minCapacity) return *this; } const UChar *text = textPtr; if(text == NULL) { // treat as an empty string, do not alias releaseArray(); setToEmpty(); return *this; } if( textLength < -1 || (textLength == -1 && !isTerminated) || (textLength >= 0 && isTerminated && text[textLength] != 0) ) { setToBogus(); return *this; } releaseArray(); if(textLength == -1) { // text is terminated, or else it would have failed the above test textLength = u_strlen(text); } fUnion.fFields.fLengthAndFlags = kReadonlyAlias; setArray((UChar *)text, textLength, isTerminated ? textLength + 1 : textLength); return *this; } // setTo() analogous to the writable-aliasing constructor with the same signature UnicodeString & UnicodeString::setTo(UChar *buffer, int32_t buffLength, int32_t buffCapacity) { if(fUnion.fFields.fLengthAndFlags & kOpenGetBuffer) { // do not modify a string that has an "open" getBuffer(minCapacity) return *this; } if(buffer == NULL) { // treat as an empty string, do not alias releaseArray(); setToEmpty(); return *this; } if(buffLength < -1 || buffCapacity < 0 || buffLength > buffCapacity) { setToBogus(); return *this; } else if(buffLength == -1) { // buffLength = u_strlen(buff); but do not look beyond buffCapacity const UChar *p = buffer, *limit = buffer + buffCapacity; while(p != limit && *p != 0) { ++p; } buffLength = (int32_t)(p - buffer); } releaseArray(); fUnion.fFields.fLengthAndFlags = kWritableAlias; setArray(buffer, buffLength, buffCapacity); return *this; } UnicodeString &UnicodeString::setToUTF8(StringPiece utf8) { unBogus(); int32_t length = utf8.length(); int32_t capacity; // The UTF-16 string will be at most as long as the UTF-8 string. if(length <= US_STACKBUF_SIZE) { capacity = US_STACKBUF_SIZE; } else { capacity = length + 1; // +1 for the terminating NUL. } UChar *utf16 = getBuffer(capacity); int32_t length16; UErrorCode errorCode = U_ZERO_ERROR; u_strFromUTF8WithSub(utf16, getCapacity(), &length16, utf8.data(), length, 0xfffd, // Substitution character. NULL, // Don't care about number of substitutions. &errorCode); releaseBuffer(length16); if(U_FAILURE(errorCode)) { setToBogus(); } return *this; } UnicodeString& UnicodeString::setCharAt(int32_t offset, UChar c) { int32_t len = length(); if(cloneArrayIfNeeded() && len > 0) { if(offset < 0) { offset = 0; } else if(offset >= len) { offset = len - 1; } getArrayStart()[offset] = c; } return *this; } UnicodeString& UnicodeString::replace(int32_t start, int32_t _length, UChar32 srcChar) { UChar buffer[U16_MAX_LENGTH]; int32_t count = 0; UBool isError = FALSE; U16_APPEND(buffer, count, U16_MAX_LENGTH, srcChar, isError); // We test isError so that the compiler does not complain that we don't. // If isError (srcChar is not a valid code point) then count==0 which means // we remove the source segment rather than replacing it with srcChar. return doReplace(start, _length, buffer, 0, isError ? 0 : count); } UnicodeString& UnicodeString::append(UChar32 srcChar) { UChar buffer[U16_MAX_LENGTH]; int32_t _length = 0; UBool isError = FALSE; U16_APPEND(buffer, _length, U16_MAX_LENGTH, srcChar, isError); // We test isError so that the compiler does not complain that we don't. // If isError then _length==0 which turns the doAppend() into a no-op anyway. return isError ? *this : doAppend(buffer, 0, _length); } UnicodeString& UnicodeString::doReplace( int32_t start, int32_t length, const UnicodeString& src, int32_t srcStart, int32_t srcLength) { // pin the indices to legal values src.pinIndices(srcStart, srcLength); // get the characters from src // and replace the range in ourselves with them return doReplace(start, length, src.getArrayStart(), srcStart, srcLength); } UnicodeString& UnicodeString::doReplace(int32_t start, int32_t length, const UChar *srcChars, int32_t srcStart, int32_t srcLength) { if(!isWritable()) { return *this; } int32_t oldLength = this->length(); // optimize (read-only alias).remove(0, start) and .remove(start, end) if((fUnion.fFields.fLengthAndFlags&kBufferIsReadonly) && srcLength == 0) { if(start == 0) { // remove prefix by adjusting the array pointer pinIndex(length); fUnion.fFields.fArray += length; fUnion.fFields.fCapacity -= length; setLength(oldLength - length); return *this; } else { pinIndex(start); if(length >= (oldLength - start)) { // remove suffix by reducing the length (like truncate()) setLength(start); fUnion.fFields.fCapacity = start; // not NUL-terminated any more return *this; } } } if(start == oldLength) { return doAppend(srcChars, srcStart, srcLength); } if(srcChars == 0) { srcLength = 0; } else { // Perform all remaining operations relative to srcChars + srcStart. // From this point forward, do not use srcStart. srcChars += srcStart; if (srcLength < 0) { // get the srcLength if necessary srcLength = u_strlen(srcChars); } } // pin the indices to legal values pinIndices(start, length); // Calculate the size of the string after the replace. // Avoid int32_t overflow. int32_t newLength = oldLength - length; if(srcLength > (INT32_MAX - newLength)) { setToBogus(); return *this; } newLength += srcLength; // Check for insertion into ourself const UChar *oldArray = getArrayStart(); if (isBufferWritable() && oldArray < srcChars + srcLength && srcChars < oldArray + oldLength) { // Copy into a new UnicodeString and start over UnicodeString copy(srcChars, srcLength); if (copy.isBogus()) { setToBogus(); return *this; } return doReplace(start, length, copy.getArrayStart(), 0, srcLength); } // cloneArrayIfNeeded(doCopyArray=FALSE) may change fArray but will not copy the current contents; // therefore we need to keep the current fArray UChar oldStackBuffer[US_STACKBUF_SIZE]; if((fUnion.fFields.fLengthAndFlags&kUsingStackBuffer) && (newLength > US_STACKBUF_SIZE)) { // copy the stack buffer contents because it will be overwritten with // fUnion.fFields values u_memcpy(oldStackBuffer, oldArray, oldLength); oldArray = oldStackBuffer; } // clone our array and allocate a bigger array if needed int32_t *bufferToDelete = 0; if(!cloneArrayIfNeeded(newLength, getGrowCapacity(newLength), FALSE, &bufferToDelete) ) { return *this; } // now do the replace UChar *newArray = getArrayStart(); if(newArray != oldArray) { // if fArray changed, then we need to copy everything except what will change us_arrayCopy(oldArray, 0, newArray, 0, start); us_arrayCopy(oldArray, start + length, newArray, start + srcLength, oldLength - (start + length)); } else if(length != srcLength) { // fArray did not change; copy only the portion that isn't changing, leaving a hole us_arrayCopy(oldArray, start + length, newArray, start + srcLength, oldLength - (start + length)); } // now fill in the hole with the new string us_arrayCopy(srcChars, 0, newArray, start, srcLength); setLength(newLength); // delayed delete in case srcChars == fArray when we started, and // to keep oldArray alive for the above operations if (bufferToDelete) { uprv_free(bufferToDelete); } return *this; } // Versions of doReplace() only for append() variants. // doReplace() and doAppend() optimize for different cases. UnicodeString& UnicodeString::doAppend(const UnicodeString& src, int32_t srcStart, int32_t srcLength) { if(srcLength == 0) { return *this; } // pin the indices to legal values src.pinIndices(srcStart, srcLength); return doAppend(src.getArrayStart(), srcStart, srcLength); } UnicodeString& UnicodeString::doAppend(const UChar *srcChars, int32_t srcStart, int32_t srcLength) { if(!isWritable() || srcLength == 0 || srcChars == NULL) { return *this; } // Perform all remaining operations relative to srcChars + srcStart. // From this point forward, do not use srcStart. srcChars += srcStart; if(srcLength < 0) { // get the srcLength if necessary if((srcLength = u_strlen(srcChars)) == 0) { return *this; } } int32_t oldLength = length(); int32_t newLength; if (uprv_add32_overflow(oldLength, srcLength, &newLength)) { setToBogus(); return *this; } // Check for append onto ourself const UChar* oldArray = getArrayStart(); if (isBufferWritable() && oldArray < srcChars + srcLength && srcChars < oldArray + oldLength) { // Copy into a new UnicodeString and start over UnicodeString copy(srcChars, srcLength); if (copy.isBogus()) { setToBogus(); return *this; } return doAppend(copy.getArrayStart(), 0, srcLength); } // optimize append() onto a large-enough, owned string if((newLength <= getCapacity() && isBufferWritable()) || cloneArrayIfNeeded(newLength, getGrowCapacity(newLength))) { UChar *newArray = getArrayStart(); // Do not copy characters when // UChar *buffer=str.getAppendBuffer(...); // is followed by // str.append(buffer, length); // or // str.appendString(buffer, length) // or similar. if(srcChars != newArray + oldLength) { us_arrayCopy(srcChars, 0, newArray, oldLength, srcLength); } setLength(newLength); } return *this; } /** * Replaceable API */ void UnicodeString::handleReplaceBetween(int32_t start, int32_t limit, const UnicodeString& text) { replaceBetween(start, limit, text); } /** * Replaceable API */ void UnicodeString::copy(int32_t start, int32_t limit, int32_t dest) { if (limit <= start) { return; // Nothing to do; avoid bogus malloc call } UChar* text = (UChar*) uprv_malloc( sizeof(UChar) * (limit - start) ); // Check to make sure text is not null. if (text != NULL) { extractBetween(start, limit, text, 0); insert(dest, text, 0, limit - start); uprv_free(text); } } /** * Replaceable API * * NOTE: This is for the Replaceable class. There is no rep.cpp, * so we implement this function here. */ UBool Replaceable::hasMetaData() const { return TRUE; } /** * Replaceable API */ UBool UnicodeString::hasMetaData() const { return FALSE; } UnicodeString& UnicodeString::doReverse(int32_t start, int32_t length) { if(length <= 1 || !cloneArrayIfNeeded()) { return *this; } // pin the indices to legal values pinIndices(start, length); if(length <= 1) { // pinIndices() might have shrunk the length return *this; } UChar *left = getArrayStart() + start; UChar *right = left + length - 1; // -1 for inclusive boundary (length>=2) UChar swap; UBool hasSupplementary = FALSE; // Before the loop we know left<right because length>=2. do { hasSupplementary |= (UBool)U16_IS_LEAD(swap = *left); hasSupplementary |= (UBool)U16_IS_LEAD(*left++ = *right); *right-- = swap; } while(left < right); // Make sure to test the middle code unit of an odd-length string. // Redundant if the length is even. hasSupplementary |= (UBool)U16_IS_LEAD(*left); /* if there are supplementary code points in the reversed range, then re-swap their surrogates */ if(hasSupplementary) { UChar swap2; left = getArrayStart() + start; right = left + length - 1; // -1 so that we can look at *(left+1) if left<right while(left < right) { if(U16_IS_TRAIL(swap = *left) && U16_IS_LEAD(swap2 = *(left + 1))) { *left++ = swap2; *left++ = swap; } else { ++left; } } } return *this; } UBool UnicodeString::padLeading(int32_t targetLength, UChar padChar) { int32_t oldLength = length(); if(oldLength >= targetLength || !cloneArrayIfNeeded(targetLength)) { return FALSE; } else { // move contents up by padding width UChar *array = getArrayStart(); int32_t start = targetLength - oldLength; us_arrayCopy(array, 0, array, start, oldLength); // fill in padding character while(--start >= 0) { array[start] = padChar; } setLength(targetLength); return TRUE; } } UBool UnicodeString::padTrailing(int32_t targetLength, UChar padChar) { int32_t oldLength = length(); if(oldLength >= targetLength || !cloneArrayIfNeeded(targetLength)) { return FALSE; } else { // fill in padding character UChar *array = getArrayStart(); int32_t length = targetLength; while(--length >= oldLength) { array[length] = padChar; } setLength(targetLength); return TRUE; } } //======================================== // Hashing //======================================== int32_t UnicodeString::doHashCode() const { /* Delegate hash computation to uhash. This makes UnicodeString * hashing consistent with UChar* hashing. */ int32_t hashCode = ustr_hashUCharsN(getArrayStart(), length()); if (hashCode == kInvalidHashCode) { hashCode = kEmptyHashCode; } return hashCode; } //======================================== // External Buffer //======================================== char16_t * UnicodeString::getBuffer(int32_t minCapacity) { if(minCapacity>=-1 && cloneArrayIfNeeded(minCapacity)) { fUnion.fFields.fLengthAndFlags|=kOpenGetBuffer; setZeroLength(); return getArrayStart(); } else { return nullptr; } } void UnicodeString::releaseBuffer(int32_t newLength) { if(fUnion.fFields.fLengthAndFlags&kOpenGetBuffer && newLength>=-1) { // set the new fLength int32_t capacity=getCapacity(); if(newLength==-1) { // the new length is the string length, capped by fCapacity const UChar *array=getArrayStart(), *p=array, *limit=array+capacity; while(p<limit && *p!=0) { ++p; } newLength=(int32_t)(p-array); } else if(newLength>capacity) { newLength=capacity; } setLength(newLength); fUnion.fFields.fLengthAndFlags&=~kOpenGetBuffer; } } //======================================== // Miscellaneous //======================================== UBool UnicodeString::cloneArrayIfNeeded(int32_t newCapacity, int32_t growCapacity, UBool doCopyArray, int32_t **pBufferToDelete, UBool forceClone) { // default parameters need to be static, therefore // the defaults are -1 to have convenience defaults if(newCapacity == -1) { newCapacity = getCapacity(); } // while a getBuffer(minCapacity) is "open", // prevent any modifications of the string by returning FALSE here // if the string is bogus, then only an assignment or similar can revive it if(!isWritable()) { return FALSE; } /* * We need to make a copy of the array if * the buffer is read-only, or * the buffer is refCounted (shared), and refCount>1, or * the buffer is too small. * Return FALSE if memory could not be allocated. */ if(forceClone || fUnion.fFields.fLengthAndFlags & kBufferIsReadonly || (fUnion.fFields.fLengthAndFlags & kRefCounted && refCount() > 1) || newCapacity > getCapacity() ) { // check growCapacity for default value and use of the stack buffer if(growCapacity < 0) { growCapacity = newCapacity; } else if(newCapacity <= US_STACKBUF_SIZE && growCapacity > US_STACKBUF_SIZE) { growCapacity = US_STACKBUF_SIZE; } // save old values UChar oldStackBuffer[US_STACKBUF_SIZE]; UChar *oldArray; int32_t oldLength = length(); int16_t flags = fUnion.fFields.fLengthAndFlags; if(flags&kUsingStackBuffer) { U_ASSERT(!(flags&kRefCounted)); /* kRefCounted and kUsingStackBuffer are mutally exclusive */ if(doCopyArray && growCapacity > US_STACKBUF_SIZE) { // copy the stack buffer contents because it will be overwritten with // fUnion.fFields values us_arrayCopy(fUnion.fStackFields.fBuffer, 0, oldStackBuffer, 0, oldLength); oldArray = oldStackBuffer; } else { oldArray = NULL; // no need to copy from the stack buffer to itself } } else { oldArray = fUnion.fFields.fArray; U_ASSERT(oldArray!=NULL); /* when stack buffer is not used, oldArray must have a non-NULL reference */ } // allocate a new array if(allocate(growCapacity) || (newCapacity < growCapacity && allocate(newCapacity)) ) { if(doCopyArray) { // copy the contents // do not copy more than what fits - it may be smaller than before int32_t minLength = oldLength; newCapacity = getCapacity(); if(newCapacity < minLength) { minLength = newCapacity; } if(oldArray != NULL) { us_arrayCopy(oldArray, 0, getArrayStart(), 0, minLength); } setLength(minLength); } else { setZeroLength(); } // release the old array if(flags & kRefCounted) { // the array is refCounted; decrement and release if 0 u_atomic_int32_t *pRefCount = ((u_atomic_int32_t *)oldArray - 1); if(umtx_atomic_dec(pRefCount) == 0) { if(pBufferToDelete == 0) { // Note: cast to (void *) is needed with MSVC, where u_atomic_int32_t // is defined as volatile. (Volatile has useful non-standard behavior // with this compiler.) uprv_free((void *)pRefCount); } else { // the caller requested to delete it himself *pBufferToDelete = (int32_t *)pRefCount; } } } } else { // not enough memory for growCapacity and not even for the smaller newCapacity // reset the old values for setToBogus() to release the array if(!(flags&kUsingStackBuffer)) { fUnion.fFields.fArray = oldArray; } fUnion.fFields.fLengthAndFlags = flags; setToBogus(); return FALSE; } } return TRUE; } // UnicodeStringAppendable ------------------------------------------------- *** UnicodeStringAppendable::~UnicodeStringAppendable() {} UBool UnicodeStringAppendable::appendCodeUnit(UChar c) { return str.doAppend(&c, 0, 1).isWritable(); } UBool UnicodeStringAppendable::appendCodePoint(UChar32 c) { UChar buffer[U16_MAX_LENGTH]; int32_t cLength = 0; UBool isError = FALSE; U16_APPEND(buffer, cLength, U16_MAX_LENGTH, c, isError); return !isError && str.doAppend(buffer, 0, cLength).isWritable(); } UBool UnicodeStringAppendable::appendString(const UChar *s, int32_t length) { return str.doAppend(s, 0, length).isWritable(); } UBool UnicodeStringAppendable::reserveAppendCapacity(int32_t appendCapacity) { return str.cloneArrayIfNeeded(str.length() + appendCapacity); } UChar * UnicodeStringAppendable::getAppendBuffer(int32_t minCapacity, int32_t desiredCapacityHint, UChar *scratch, int32_t scratchCapacity, int32_t *resultCapacity) { if(minCapacity < 1 || scratchCapacity < minCapacity) { *resultCapacity = 0; return NULL; } int32_t oldLength = str.length(); if(minCapacity <= (kMaxCapacity - oldLength) && desiredCapacityHint <= (kMaxCapacity - oldLength) && str.cloneArrayIfNeeded(oldLength + minCapacity, oldLength + desiredCapacityHint)) { *resultCapacity = str.getCapacity() - oldLength; return str.getArrayStart() + oldLength; } *resultCapacity = scratchCapacity; return scratch; } U_NAMESPACE_END U_NAMESPACE_USE U_CAPI int32_t U_EXPORT2 uhash_hashUnicodeString(const UElement key) { const UnicodeString *str = (const UnicodeString*) key.pointer; return (str == NULL) ? 0 : str->hashCode(); } // Moved here from uhash_us.cpp so that using a UVector of UnicodeString* // does not depend on hashtable code. U_CAPI UBool U_EXPORT2 uhash_compareUnicodeString(const UElement key1, const UElement key2) { const UnicodeString *str1 = (const UnicodeString*) key1.pointer; const UnicodeString *str2 = (const UnicodeString*) key2.pointer; if (str1 == str2) { return TRUE; } if (str1 == NULL || str2 == NULL) { return FALSE; } return *str1 == *str2; } #ifdef U_STATIC_IMPLEMENTATION /* This should never be called. It is defined here to make sure that the virtual vector deleting destructor is defined within unistr.cpp. The vector deleting destructor is already a part of UObject, but defining it here makes sure that it is included with this object file. This makes sure that static library dependencies are kept to a minimum. */ static void uprv_UnicodeStringDummy(void) { delete [] (new UnicodeString[2]); } #endif
null
164
CWE-787
CVE-2020-11565
// SPDX-License-Identifier: GPL-2.0-only /* * Simple NUMA memory policy for the Linux kernel. * * Copyright 2003,2004 Andi Kleen, SuSE Labs. * (C) Copyright 2005 Christoph Lameter, Silicon Graphics, Inc. * * NUMA policy allows the user to give hints in which node(s) memory should * be allocated. * * Support four policies per VMA and per process: * * The VMA policy has priority over the process policy for a page fault. * * interleave Allocate memory interleaved over a set of nodes, * with normal fallback if it fails. * For VMA based allocations this interleaves based on the * offset into the backing object or offset into the mapping * for anonymous memory. For process policy an process counter * is used. * * bind Only allocate memory on a specific set of nodes, * no fallback. * FIXME: memory is allocated starting with the first node * to the last. It would be better if bind would truly restrict * the allocation to memory nodes instead * * preferred Try a specific node first before normal fallback. * As a special case NUMA_NO_NODE here means do the allocation * on the local CPU. This is normally identical to default, * but useful to set in a VMA when you have a non default * process policy. * * default Allocate on the local node first, or when on a VMA * use the process policy. This is what Linux always did * in a NUMA aware kernel and still does by, ahem, default. * * The process policy is applied for most non interrupt memory allocations * in that process' context. Interrupts ignore the policies and always * try to allocate on the local CPU. The VMA policy is only applied for memory * allocations for a VMA in the VM. * * Currently there are a few corner cases in swapping where the policy * is not applied, but the majority should be handled. When process policy * is used it is not remembered over swap outs/swap ins. * * Only the highest zone in the zone hierarchy gets policied. Allocations * requesting a lower zone just use default policy. This implies that * on systems with highmem kernel lowmem allocation don't get policied. * Same with GFP_DMA allocations. * * For shmfs/tmpfs/hugetlbfs shared memory the policy is shared between * all users and remembered even when nobody has memory mapped. */ /* Notebook: fix mmap readahead to honour policy and enable policy for any page cache object statistics for bigpages global policy for page cache? currently it uses process policy. Requires first item above. handle mremap for shared memory (currently ignored for the policy) grows down? make bind policy root only? It can trigger oom much faster and the kernel is not always grateful with that. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/mempolicy.h> #include <linux/pagewalk.h> #include <linux/highmem.h> #include <linux/hugetlb.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/sched/mm.h> #include <linux/sched/numa_balancing.h> #include <linux/sched/task.h> #include <linux/nodemask.h> #include <linux/cpuset.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/export.h> #include <linux/nsproxy.h> #include <linux/interrupt.h> #include <linux/init.h> #include <linux/compat.h> #include <linux/ptrace.h> #include <linux/swap.h> #include <linux/seq_file.h> #include <linux/proc_fs.h> #include <linux/migrate.h> #include <linux/ksm.h> #include <linux/rmap.h> #include <linux/security.h> #include <linux/syscalls.h> #include <linux/ctype.h> #include <linux/mm_inline.h> #include <linux/mmu_notifier.h> #include <linux/printk.h> #include <linux/swapops.h> #include <asm/tlbflush.h> #include <linux/uaccess.h> #include "internal.h" /* Internal flags */ #define MPOL_MF_DISCONTIG_OK (MPOL_MF_INTERNAL << 0) /* Skip checks for continuous vmas */ #define MPOL_MF_INVERT (MPOL_MF_INTERNAL << 1) /* Invert check for nodemask */ static struct kmem_cache *policy_cache; static struct kmem_cache *sn_cache; /* Highest zone. An specific allocation for a zone below that is not policied. */ enum zone_type policy_zone = 0; /* * run-time system-wide default policy => local allocation */ static struct mempolicy default_policy = { .refcnt = ATOMIC_INIT(1), /* never free it */ .mode = MPOL_PREFERRED, .flags = MPOL_F_LOCAL, }; static struct mempolicy preferred_node_policy[MAX_NUMNODES]; struct mempolicy *get_task_policy(struct task_struct *p) { struct mempolicy *pol = p->mempolicy; int node; if (pol) return pol; node = numa_node_id(); if (node != NUMA_NO_NODE) { pol = &preferred_node_policy[node]; /* preferred_node_policy is not initialised early in boot */ if (pol->mode) return pol; } return &default_policy; } static const struct mempolicy_operations { int (*create)(struct mempolicy *pol, const nodemask_t *nodes); void (*rebind)(struct mempolicy *pol, const nodemask_t *nodes); } mpol_ops[MPOL_MAX]; static inline int mpol_store_user_nodemask(const struct mempolicy *pol) { return pol->flags & MPOL_MODE_FLAGS; } static void mpol_relative_nodemask(nodemask_t *ret, const nodemask_t *orig, const nodemask_t *rel) { nodemask_t tmp; nodes_fold(tmp, *orig, nodes_weight(*rel)); nodes_onto(*ret, tmp, *rel); } static int mpol_new_interleave(struct mempolicy *pol, const nodemask_t *nodes) { if (nodes_empty(*nodes)) return -EINVAL; pol->v.nodes = *nodes; return 0; } static int mpol_new_preferred(struct mempolicy *pol, const nodemask_t *nodes) { if (!nodes) pol->flags |= MPOL_F_LOCAL; /* local allocation */ else if (nodes_empty(*nodes)) return -EINVAL; /* no allowed nodes */ else pol->v.preferred_node = first_node(*nodes); return 0; } static int mpol_new_bind(struct mempolicy *pol, const nodemask_t *nodes) { if (nodes_empty(*nodes)) return -EINVAL; pol->v.nodes = *nodes; return 0; } /* * mpol_set_nodemask is called after mpol_new() to set up the nodemask, if * any, for the new policy. mpol_new() has already validated the nodes * parameter with respect to the policy mode and flags. But, we need to * handle an empty nodemask with MPOL_PREFERRED here. * * Must be called holding task's alloc_lock to protect task's mems_allowed * and mempolicy. May also be called holding the mmap_semaphore for write. */ static int mpol_set_nodemask(struct mempolicy *pol, const nodemask_t *nodes, struct nodemask_scratch *nsc) { int ret; /* if mode is MPOL_DEFAULT, pol is NULL. This is right. */ if (pol == NULL) return 0; /* Check N_MEMORY */ nodes_and(nsc->mask1, cpuset_current_mems_allowed, node_states[N_MEMORY]); VM_BUG_ON(!nodes); if (pol->mode == MPOL_PREFERRED && nodes_empty(*nodes)) nodes = NULL; /* explicit local allocation */ else { if (pol->flags & MPOL_F_RELATIVE_NODES) mpol_relative_nodemask(&nsc->mask2, nodes, &nsc->mask1); else nodes_and(nsc->mask2, *nodes, nsc->mask1); if (mpol_store_user_nodemask(pol)) pol->w.user_nodemask = *nodes; else pol->w.cpuset_mems_allowed = cpuset_current_mems_allowed; } if (nodes) ret = mpol_ops[pol->mode].create(pol, &nsc->mask2); else ret = mpol_ops[pol->mode].create(pol, NULL); return ret; } /* * This function just creates a new policy, does some check and simple * initialization. You must invoke mpol_set_nodemask() to set nodes. */ static struct mempolicy *mpol_new(unsigned short mode, unsigned short flags, nodemask_t *nodes) { struct mempolicy *policy; pr_debug("setting mode %d flags %d nodes[0] %lx\n", mode, flags, nodes ? nodes_addr(*nodes)[0] : NUMA_NO_NODE); if (mode == MPOL_DEFAULT) { if (nodes && !nodes_empty(*nodes)) return ERR_PTR(-EINVAL); return NULL; } VM_BUG_ON(!nodes); /* * MPOL_PREFERRED cannot be used with MPOL_F_STATIC_NODES or * MPOL_F_RELATIVE_NODES if the nodemask is empty (local allocation). * All other modes require a valid pointer to a non-empty nodemask. */ if (mode == MPOL_PREFERRED) { if (nodes_empty(*nodes)) { if (((flags & MPOL_F_STATIC_NODES) || (flags & MPOL_F_RELATIVE_NODES))) return ERR_PTR(-EINVAL); } } else if (mode == MPOL_LOCAL) { if (!nodes_empty(*nodes) || (flags & MPOL_F_STATIC_NODES) || (flags & MPOL_F_RELATIVE_NODES)) return ERR_PTR(-EINVAL); mode = MPOL_PREFERRED; } else if (nodes_empty(*nodes)) return ERR_PTR(-EINVAL); policy = kmem_cache_alloc(policy_cache, GFP_KERNEL); if (!policy) return ERR_PTR(-ENOMEM); atomic_set(&policy->refcnt, 1); policy->mode = mode; policy->flags = flags; return policy; } /* Slow path of a mpol destructor. */ void __mpol_put(struct mempolicy *p) { if (!atomic_dec_and_test(&p->refcnt)) return; kmem_cache_free(policy_cache, p); } static void mpol_rebind_default(struct mempolicy *pol, const nodemask_t *nodes) { } static void mpol_rebind_nodemask(struct mempolicy *pol, const nodemask_t *nodes) { nodemask_t tmp; if (pol->flags & MPOL_F_STATIC_NODES) nodes_and(tmp, pol->w.user_nodemask, *nodes); else if (pol->flags & MPOL_F_RELATIVE_NODES) mpol_relative_nodemask(&tmp, &pol->w.user_nodemask, nodes); else { nodes_remap(tmp, pol->v.nodes,pol->w.cpuset_mems_allowed, *nodes); pol->w.cpuset_mems_allowed = *nodes; } if (nodes_empty(tmp)) tmp = *nodes; pol->v.nodes = tmp; } static void mpol_rebind_preferred(struct mempolicy *pol, const nodemask_t *nodes) { nodemask_t tmp; if (pol->flags & MPOL_F_STATIC_NODES) { int node = first_node(pol->w.user_nodemask); if (node_isset(node, *nodes)) { pol->v.preferred_node = node; pol->flags &= ~MPOL_F_LOCAL; } else pol->flags |= MPOL_F_LOCAL; } else if (pol->flags & MPOL_F_RELATIVE_NODES) { mpol_relative_nodemask(&tmp, &pol->w.user_nodemask, nodes); pol->v.preferred_node = first_node(tmp); } else if (!(pol->flags & MPOL_F_LOCAL)) { pol->v.preferred_node = node_remap(pol->v.preferred_node, pol->w.cpuset_mems_allowed, *nodes); pol->w.cpuset_mems_allowed = *nodes; } } /* * mpol_rebind_policy - Migrate a policy to a different set of nodes * * Per-vma policies are protected by mmap_sem. Allocations using per-task * policies are protected by task->mems_allowed_seq to prevent a premature * OOM/allocation failure due to parallel nodemask modification. */ static void mpol_rebind_policy(struct mempolicy *pol, const nodemask_t *newmask) { if (!pol) return; if (!mpol_store_user_nodemask(pol) && !(pol->flags & MPOL_F_LOCAL) && nodes_equal(pol->w.cpuset_mems_allowed, *newmask)) return; mpol_ops[pol->mode].rebind(pol, newmask); } /* * Wrapper for mpol_rebind_policy() that just requires task * pointer, and updates task mempolicy. * * Called with task's alloc_lock held. */ void mpol_rebind_task(struct task_struct *tsk, const nodemask_t *new) { mpol_rebind_policy(tsk->mempolicy, new); } /* * Rebind each vma in mm to new nodemask. * * Call holding a reference to mm. Takes mm->mmap_sem during call. */ void mpol_rebind_mm(struct mm_struct *mm, nodemask_t *new) { struct vm_area_struct *vma; down_write(&mm->mmap_sem); for (vma = mm->mmap; vma; vma = vma->vm_next) mpol_rebind_policy(vma->vm_policy, new); up_write(&mm->mmap_sem); } static const struct mempolicy_operations mpol_ops[MPOL_MAX] = { [MPOL_DEFAULT] = { .rebind = mpol_rebind_default, }, [MPOL_INTERLEAVE] = { .create = mpol_new_interleave, .rebind = mpol_rebind_nodemask, }, [MPOL_PREFERRED] = { .create = mpol_new_preferred, .rebind = mpol_rebind_preferred, }, [MPOL_BIND] = { .create = mpol_new_bind, .rebind = mpol_rebind_nodemask, }, }; static int migrate_page_add(struct page *page, struct list_head *pagelist, unsigned long flags); struct queue_pages { struct list_head *pagelist; unsigned long flags; nodemask_t *nmask; unsigned long start; unsigned long end; struct vm_area_struct *first; }; /* * Check if the page's nid is in qp->nmask. * * If MPOL_MF_INVERT is set in qp->flags, check if the nid is * in the invert of qp->nmask. */ static inline bool queue_pages_required(struct page *page, struct queue_pages *qp) { int nid = page_to_nid(page); unsigned long flags = qp->flags; return node_isset(nid, *qp->nmask) == !(flags & MPOL_MF_INVERT); } /* * queue_pages_pmd() has four possible return values: * 0 - pages are placed on the right node or queued successfully. * 1 - there is unmovable page, and MPOL_MF_MOVE* & MPOL_MF_STRICT were * specified. * 2 - THP was split. * -EIO - is migration entry or only MPOL_MF_STRICT was specified and an * existing page was already on a node that does not follow the * policy. */ static int queue_pages_pmd(pmd_t *pmd, spinlock_t *ptl, unsigned long addr, unsigned long end, struct mm_walk *walk) { int ret = 0; struct page *page; struct queue_pages *qp = walk->private; unsigned long flags; if (unlikely(is_pmd_migration_entry(*pmd))) { ret = -EIO; goto unlock; } page = pmd_page(*pmd); if (is_huge_zero_page(page)) { spin_unlock(ptl); __split_huge_pmd(walk->vma, pmd, addr, false, NULL); ret = 2; goto out; } if (!queue_pages_required(page, qp)) goto unlock; flags = qp->flags; /* go to thp migration */ if (flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)) { if (!vma_migratable(walk->vma) || migrate_page_add(page, qp->pagelist, flags)) { ret = 1; goto unlock; } } else ret = -EIO; unlock: spin_unlock(ptl); out: return ret; } /* * Scan through pages checking if pages follow certain conditions, * and move them to the pagelist if they do. * * queue_pages_pte_range() has three possible return values: * 0 - pages are placed on the right node or queued successfully. * 1 - there is unmovable page, and MPOL_MF_MOVE* & MPOL_MF_STRICT were * specified. * -EIO - only MPOL_MF_STRICT was specified and an existing page was already * on a node that does not follow the policy. */ static int queue_pages_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end, struct mm_walk *walk) { struct vm_area_struct *vma = walk->vma; struct page *page; struct queue_pages *qp = walk->private; unsigned long flags = qp->flags; int ret; bool has_unmovable = false; pte_t *pte; spinlock_t *ptl; ptl = pmd_trans_huge_lock(pmd, vma); if (ptl) { ret = queue_pages_pmd(pmd, ptl, addr, end, walk); if (ret != 2) return ret; } /* THP was split, fall through to pte walk */ if (pmd_trans_unstable(pmd)) return 0; pte = pte_offset_map_lock(walk->mm, pmd, addr, &ptl); for (; addr != end; pte++, addr += PAGE_SIZE) { if (!pte_present(*pte)) continue; page = vm_normal_page(vma, addr, *pte); if (!page) continue; /* * vm_normal_page() filters out zero pages, but there might * still be PageReserved pages to skip, perhaps in a VDSO. */ if (PageReserved(page)) continue; if (!queue_pages_required(page, qp)) continue; if (flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)) { /* MPOL_MF_STRICT must be specified if we get here */ if (!vma_migratable(vma)) { has_unmovable = true; break; } /* * Do not abort immediately since there may be * temporary off LRU pages in the range. Still * need migrate other LRU pages. */ if (migrate_page_add(page, qp->pagelist, flags)) has_unmovable = true; } else break; } pte_unmap_unlock(pte - 1, ptl); cond_resched(); if (has_unmovable) return 1; return addr != end ? -EIO : 0; } static int queue_pages_hugetlb(pte_t *pte, unsigned long hmask, unsigned long addr, unsigned long end, struct mm_walk *walk) { int ret = 0; #ifdef CONFIG_HUGETLB_PAGE struct queue_pages *qp = walk->private; unsigned long flags = (qp->flags & MPOL_MF_VALID); struct page *page; spinlock_t *ptl; pte_t entry; ptl = huge_pte_lock(hstate_vma(walk->vma), walk->mm, pte); entry = huge_ptep_get(pte); if (!pte_present(entry)) goto unlock; page = pte_page(entry); if (!queue_pages_required(page, qp)) goto unlock; if (flags == MPOL_MF_STRICT) { /* * STRICT alone means only detecting misplaced page and no * need to further check other vma. */ ret = -EIO; goto unlock; } if (!vma_migratable(walk->vma)) { /* * Must be STRICT with MOVE*, otherwise .test_walk() have * stopped walking current vma. * Detecting misplaced page but allow migrating pages which * have been queued. */ ret = 1; goto unlock; } /* With MPOL_MF_MOVE, we migrate only unshared hugepage. */ if (flags & (MPOL_MF_MOVE_ALL) || (flags & MPOL_MF_MOVE && page_mapcount(page) == 1)) { if (!isolate_huge_page(page, qp->pagelist) && (flags & MPOL_MF_STRICT)) /* * Failed to isolate page but allow migrating pages * which have been queued. */ ret = 1; } unlock: spin_unlock(ptl); #else BUG(); #endif return ret; } #ifdef CONFIG_NUMA_BALANCING /* * This is used to mark a range of virtual addresses to be inaccessible. * These are later cleared by a NUMA hinting fault. Depending on these * faults, pages may be migrated for better NUMA placement. * * This is assuming that NUMA faults are handled using PROT_NONE. If * an architecture makes a different choice, it will need further * changes to the core. */ unsigned long change_prot_numa(struct vm_area_struct *vma, unsigned long addr, unsigned long end) { int nr_updated; nr_updated = change_protection(vma, addr, end, PAGE_NONE, 0, 1); if (nr_updated) count_vm_numa_events(NUMA_PTE_UPDATES, nr_updated); return nr_updated; } #else static unsigned long change_prot_numa(struct vm_area_struct *vma, unsigned long addr, unsigned long end) { return 0; } #endif /* CONFIG_NUMA_BALANCING */ static int queue_pages_test_walk(unsigned long start, unsigned long end, struct mm_walk *walk) { struct vm_area_struct *vma = walk->vma; struct queue_pages *qp = walk->private; unsigned long endvma = vma->vm_end; unsigned long flags = qp->flags; /* range check first */ VM_BUG_ON_VMA((vma->vm_start > start) || (vma->vm_end < end), vma); if (!qp->first) { qp->first = vma; if (!(flags & MPOL_MF_DISCONTIG_OK) && (qp->start < vma->vm_start)) /* hole at head side of range */ return -EFAULT; } if (!(flags & MPOL_MF_DISCONTIG_OK) && ((vma->vm_end < qp->end) && (!vma->vm_next || vma->vm_end < vma->vm_next->vm_start))) /* hole at middle or tail of range */ return -EFAULT; /* * Need check MPOL_MF_STRICT to return -EIO if possible * regardless of vma_migratable */ if (!vma_migratable(vma) && !(flags & MPOL_MF_STRICT)) return 1; if (endvma > end) endvma = end; if (flags & MPOL_MF_LAZY) { /* Similar to task_numa_work, skip inaccessible VMAs */ if (!is_vm_hugetlb_page(vma) && (vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE)) && !(vma->vm_flags & VM_MIXEDMAP)) change_prot_numa(vma, start, endvma); return 1; } /* queue pages from current vma */ if (flags & MPOL_MF_VALID) return 0; return 1; } static const struct mm_walk_ops queue_pages_walk_ops = { .hugetlb_entry = queue_pages_hugetlb, .pmd_entry = queue_pages_pte_range, .test_walk = queue_pages_test_walk, }; /* * Walk through page tables and collect pages to be migrated. * * If pages found in a given range are on a set of nodes (determined by * @nodes and @flags,) it's isolated and queued to the pagelist which is * passed via @private. * * queue_pages_range() has three possible return values: * 1 - there is unmovable page, but MPOL_MF_MOVE* & MPOL_MF_STRICT were * specified. * 0 - queue pages successfully or no misplaced page. * errno - i.e. misplaced pages with MPOL_MF_STRICT specified (-EIO) or * memory range specified by nodemask and maxnode points outside * your accessible address space (-EFAULT) */ static int queue_pages_range(struct mm_struct *mm, unsigned long start, unsigned long end, nodemask_t *nodes, unsigned long flags, struct list_head *pagelist) { int err; struct queue_pages qp = { .pagelist = pagelist, .flags = flags, .nmask = nodes, .start = start, .end = end, .first = NULL, }; err = walk_page_range(mm, start, end, &queue_pages_walk_ops, &qp); if (!qp.first) /* whole range in hole */ err = -EFAULT; return err; } /* * Apply policy to a single VMA * This must be called with the mmap_sem held for writing. */ static int vma_replace_policy(struct vm_area_struct *vma, struct mempolicy *pol) { int err; struct mempolicy *old; struct mempolicy *new; pr_debug("vma %lx-%lx/%lx vm_ops %p vm_file %p set_policy %p\n", vma->vm_start, vma->vm_end, vma->vm_pgoff, vma->vm_ops, vma->vm_file, vma->vm_ops ? vma->vm_ops->set_policy : NULL); new = mpol_dup(pol); if (IS_ERR(new)) return PTR_ERR(new); if (vma->vm_ops && vma->vm_ops->set_policy) { err = vma->vm_ops->set_policy(vma, new); if (err) goto err_out; } old = vma->vm_policy; vma->vm_policy = new; /* protected by mmap_sem */ mpol_put(old); return 0; err_out: mpol_put(new); return err; } /* Step 2: apply policy to a range and do splits. */ static int mbind_range(struct mm_struct *mm, unsigned long start, unsigned long end, struct mempolicy *new_pol) { struct vm_area_struct *next; struct vm_area_struct *prev; struct vm_area_struct *vma; int err = 0; pgoff_t pgoff; unsigned long vmstart; unsigned long vmend; vma = find_vma(mm, start); VM_BUG_ON(!vma); prev = vma->vm_prev; if (start > vma->vm_start) prev = vma; for (; vma && vma->vm_start < end; prev = vma, vma = next) { next = vma->vm_next; vmstart = max(start, vma->vm_start); vmend = min(end, vma->vm_end); if (mpol_equal(vma_policy(vma), new_pol)) continue; pgoff = vma->vm_pgoff + ((vmstart - vma->vm_start) >> PAGE_SHIFT); prev = vma_merge(mm, prev, vmstart, vmend, vma->vm_flags, vma->anon_vma, vma->vm_file, pgoff, new_pol, vma->vm_userfaultfd_ctx); if (prev) { vma = prev; next = vma->vm_next; if (mpol_equal(vma_policy(vma), new_pol)) continue; /* vma_merge() joined vma && vma->next, case 8 */ goto replace; } if (vma->vm_start != vmstart) { err = split_vma(vma->vm_mm, vma, vmstart, 1); if (err) goto out; } if (vma->vm_end != vmend) { err = split_vma(vma->vm_mm, vma, vmend, 0); if (err) goto out; } replace: err = vma_replace_policy(vma, new_pol); if (err) goto out; } out: return err; } /* Set the process memory policy */ static long do_set_mempolicy(unsigned short mode, unsigned short flags, nodemask_t *nodes) { struct mempolicy *new, *old; NODEMASK_SCRATCH(scratch); int ret; if (!scratch) return -ENOMEM; new = mpol_new(mode, flags, nodes); if (IS_ERR(new)) { ret = PTR_ERR(new); goto out; } task_lock(current); ret = mpol_set_nodemask(new, nodes, scratch); if (ret) { task_unlock(current); mpol_put(new); goto out; } old = current->mempolicy; current->mempolicy = new; if (new && new->mode == MPOL_INTERLEAVE) current->il_prev = MAX_NUMNODES-1; task_unlock(current); mpol_put(old); ret = 0; out: NODEMASK_SCRATCH_FREE(scratch); return ret; } /* * Return nodemask for policy for get_mempolicy() query * * Called with task's alloc_lock held */ static void get_policy_nodemask(struct mempolicy *p, nodemask_t *nodes) { nodes_clear(*nodes); if (p == &default_policy) return; switch (p->mode) { case MPOL_BIND: /* Fall through */ case MPOL_INTERLEAVE: *nodes = p->v.nodes; break; case MPOL_PREFERRED: if (!(p->flags & MPOL_F_LOCAL)) node_set(p->v.preferred_node, *nodes); /* else return empty node mask for local allocation */ break; default: BUG(); } } static int lookup_node(struct mm_struct *mm, unsigned long addr) { struct page *p; int err; int locked = 1; err = get_user_pages_locked(addr & PAGE_MASK, 1, 0, &p, &locked); if (err >= 0) { err = page_to_nid(p); put_page(p); } if (locked) up_read(&mm->mmap_sem); return err; } /* Retrieve NUMA policy */ static long do_get_mempolicy(int *policy, nodemask_t *nmask, unsigned long addr, unsigned long flags) { int err; struct mm_struct *mm = current->mm; struct vm_area_struct *vma = NULL; struct mempolicy *pol = current->mempolicy, *pol_refcount = NULL; if (flags & ~(unsigned long)(MPOL_F_NODE|MPOL_F_ADDR|MPOL_F_MEMS_ALLOWED)) return -EINVAL; if (flags & MPOL_F_MEMS_ALLOWED) { if (flags & (MPOL_F_NODE|MPOL_F_ADDR)) return -EINVAL; *policy = 0; /* just so it's initialized */ task_lock(current); *nmask = cpuset_current_mems_allowed; task_unlock(current); return 0; } if (flags & MPOL_F_ADDR) { /* * Do NOT fall back to task policy if the * vma/shared policy at addr is NULL. We * want to return MPOL_DEFAULT in this case. */ down_read(&mm->mmap_sem); vma = find_vma_intersection(mm, addr, addr+1); if (!vma) { up_read(&mm->mmap_sem); return -EFAULT; } if (vma->vm_ops && vma->vm_ops->get_policy) pol = vma->vm_ops->get_policy(vma, addr); else pol = vma->vm_policy; } else if (addr) return -EINVAL; if (!pol) pol = &default_policy; /* indicates default behavior */ if (flags & MPOL_F_NODE) { if (flags & MPOL_F_ADDR) { /* * Take a refcount on the mpol, lookup_node() * wil drop the mmap_sem, so after calling * lookup_node() only "pol" remains valid, "vma" * is stale. */ pol_refcount = pol; vma = NULL; mpol_get(pol); err = lookup_node(mm, addr); if (err < 0) goto out; *policy = err; } else if (pol == current->mempolicy && pol->mode == MPOL_INTERLEAVE) { *policy = next_node_in(current->il_prev, pol->v.nodes); } else { err = -EINVAL; goto out; } } else { *policy = pol == &default_policy ? MPOL_DEFAULT : pol->mode; /* * Internal mempolicy flags must be masked off before exposing * the policy to userspace. */ *policy |= (pol->flags & MPOL_MODE_FLAGS); } err = 0; if (nmask) { if (mpol_store_user_nodemask(pol)) { *nmask = pol->w.user_nodemask; } else { task_lock(current); get_policy_nodemask(pol, nmask); task_unlock(current); } } out: mpol_cond_put(pol); if (vma) up_read(&mm->mmap_sem); if (pol_refcount) mpol_put(pol_refcount); return err; } #ifdef CONFIG_MIGRATION /* * page migration, thp tail pages can be passed. */ static int migrate_page_add(struct page *page, struct list_head *pagelist, unsigned long flags) { struct page *head = compound_head(page); /* * Avoid migrating a page that is shared with others. */ if ((flags & MPOL_MF_MOVE_ALL) || page_mapcount(head) == 1) { if (!isolate_lru_page(head)) { list_add_tail(&head->lru, pagelist); mod_node_page_state(page_pgdat(head), NR_ISOLATED_ANON + page_is_file_cache(head), hpage_nr_pages(head)); } else if (flags & MPOL_MF_STRICT) { /* * Non-movable page may reach here. And, there may be * temporary off LRU pages or non-LRU movable pages. * Treat them as unmovable pages since they can't be * isolated, so they can't be moved at the moment. It * should return -EIO for this case too. */ return -EIO; } } return 0; } /* page allocation callback for NUMA node migration */ struct page *alloc_new_node_page(struct page *page, unsigned long node) { if (PageHuge(page)) return alloc_huge_page_node(page_hstate(compound_head(page)), node); else if (PageTransHuge(page)) { struct page *thp; thp = alloc_pages_node(node, (GFP_TRANSHUGE | __GFP_THISNODE), HPAGE_PMD_ORDER); if (!thp) return NULL; prep_transhuge_page(thp); return thp; } else return __alloc_pages_node(node, GFP_HIGHUSER_MOVABLE | __GFP_THISNODE, 0); } /* * Migrate pages from one node to a target node. * Returns error or the number of pages not migrated. */ static int migrate_to_node(struct mm_struct *mm, int source, int dest, int flags) { nodemask_t nmask; LIST_HEAD(pagelist); int err = 0; nodes_clear(nmask); node_set(source, nmask); /* * This does not "check" the range but isolates all pages that * need migration. Between passing in the full user address * space range and MPOL_MF_DISCONTIG_OK, this call can not fail. */ VM_BUG_ON(!(flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL))); queue_pages_range(mm, mm->mmap->vm_start, mm->task_size, &nmask, flags | MPOL_MF_DISCONTIG_OK, &pagelist); if (!list_empty(&pagelist)) { err = migrate_pages(&pagelist, alloc_new_node_page, NULL, dest, MIGRATE_SYNC, MR_SYSCALL); if (err) putback_movable_pages(&pagelist); } return err; } /* * Move pages between the two nodesets so as to preserve the physical * layout as much as possible. * * Returns the number of page that could not be moved. */ int do_migrate_pages(struct mm_struct *mm, const nodemask_t *from, const nodemask_t *to, int flags) { int busy = 0; int err; nodemask_t tmp; err = migrate_prep(); if (err) return err; down_read(&mm->mmap_sem); /* * Find a 'source' bit set in 'tmp' whose corresponding 'dest' * bit in 'to' is not also set in 'tmp'. Clear the found 'source' * bit in 'tmp', and return that <source, dest> pair for migration. * The pair of nodemasks 'to' and 'from' define the map. * * If no pair of bits is found that way, fallback to picking some * pair of 'source' and 'dest' bits that are not the same. If the * 'source' and 'dest' bits are the same, this represents a node * that will be migrating to itself, so no pages need move. * * If no bits are left in 'tmp', or if all remaining bits left * in 'tmp' correspond to the same bit in 'to', return false * (nothing left to migrate). * * This lets us pick a pair of nodes to migrate between, such that * if possible the dest node is not already occupied by some other * source node, minimizing the risk of overloading the memory on a * node that would happen if we migrated incoming memory to a node * before migrating outgoing memory source that same node. * * A single scan of tmp is sufficient. As we go, we remember the * most recent <s, d> pair that moved (s != d). If we find a pair * that not only moved, but what's better, moved to an empty slot * (d is not set in tmp), then we break out then, with that pair. * Otherwise when we finish scanning from_tmp, we at least have the * most recent <s, d> pair that moved. If we get all the way through * the scan of tmp without finding any node that moved, much less * moved to an empty node, then there is nothing left worth migrating. */ tmp = *from; while (!nodes_empty(tmp)) { int s,d; int source = NUMA_NO_NODE; int dest = 0; for_each_node_mask(s, tmp) { /* * do_migrate_pages() tries to maintain the relative * node relationship of the pages established between * threads and memory areas. * * However if the number of source nodes is not equal to * the number of destination nodes we can not preserve * this node relative relationship. In that case, skip * copying memory from a node that is in the destination * mask. * * Example: [2,3,4] -> [3,4,5] moves everything. * [0-7] - > [3,4,5] moves only 0,1,2,6,7. */ if ((nodes_weight(*from) != nodes_weight(*to)) && (node_isset(s, *to))) continue; d = node_remap(s, *from, *to); if (s == d) continue; source = s; /* Node moved. Memorize */ dest = d; /* dest not in remaining from nodes? */ if (!node_isset(dest, tmp)) break; } if (source == NUMA_NO_NODE) break; node_clear(source, tmp); err = migrate_to_node(mm, source, dest, flags); if (err > 0) busy += err; if (err < 0) break; } up_read(&mm->mmap_sem); if (err < 0) return err; return busy; } /* * Allocate a new page for page migration based on vma policy. * Start by assuming the page is mapped by the same vma as contains @start. * Search forward from there, if not. N.B., this assumes that the * list of pages handed to migrate_pages()--which is how we get here-- * is in virtual address order. */ static struct page *new_page(struct page *page, unsigned long start) { struct vm_area_struct *vma; unsigned long uninitialized_var(address); vma = find_vma(current->mm, start); while (vma) { address = page_address_in_vma(page, vma); if (address != -EFAULT) break; vma = vma->vm_next; } if (PageHuge(page)) { return alloc_huge_page_vma(page_hstate(compound_head(page)), vma, address); } else if (PageTransHuge(page)) { struct page *thp; thp = alloc_hugepage_vma(GFP_TRANSHUGE, vma, address, HPAGE_PMD_ORDER); if (!thp) return NULL; prep_transhuge_page(thp); return thp; } /* * if !vma, alloc_page_vma() will use task or system default policy */ return alloc_page_vma(GFP_HIGHUSER_MOVABLE | __GFP_RETRY_MAYFAIL, vma, address); } #else static int migrate_page_add(struct page *page, struct list_head *pagelist, unsigned long flags) { return -EIO; } int do_migrate_pages(struct mm_struct *mm, const nodemask_t *from, const nodemask_t *to, int flags) { return -ENOSYS; } static struct page *new_page(struct page *page, unsigned long start) { return NULL; } #endif static long do_mbind(unsigned long start, unsigned long len, unsigned short mode, unsigned short mode_flags, nodemask_t *nmask, unsigned long flags) { struct mm_struct *mm = current->mm; struct mempolicy *new; unsigned long end; int err; int ret; LIST_HEAD(pagelist); if (flags & ~(unsigned long)MPOL_MF_VALID) return -EINVAL; if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE)) return -EPERM; if (start & ~PAGE_MASK) return -EINVAL; if (mode == MPOL_DEFAULT) flags &= ~MPOL_MF_STRICT; len = (len + PAGE_SIZE - 1) & PAGE_MASK; end = start + len; if (end < start) return -EINVAL; if (end == start) return 0; new = mpol_new(mode, mode_flags, nmask); if (IS_ERR(new)) return PTR_ERR(new); if (flags & MPOL_MF_LAZY) new->flags |= MPOL_F_MOF; /* * If we are using the default policy then operation * on discontinuous address spaces is okay after all */ if (!new) flags |= MPOL_MF_DISCONTIG_OK; pr_debug("mbind %lx-%lx mode:%d flags:%d nodes:%lx\n", start, start + len, mode, mode_flags, nmask ? nodes_addr(*nmask)[0] : NUMA_NO_NODE); if (flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)) { err = migrate_prep(); if (err) goto mpol_out; } { NODEMASK_SCRATCH(scratch); if (scratch) { down_write(&mm->mmap_sem); task_lock(current); err = mpol_set_nodemask(new, nmask, scratch); task_unlock(current); if (err) up_write(&mm->mmap_sem); } else err = -ENOMEM; NODEMASK_SCRATCH_FREE(scratch); } if (err) goto mpol_out; ret = queue_pages_range(mm, start, end, nmask, flags | MPOL_MF_INVERT, &pagelist); if (ret < 0) { err = ret; goto up_out; } err = mbind_range(mm, start, end, new); if (!err) { int nr_failed = 0; if (!list_empty(&pagelist)) { WARN_ON_ONCE(flags & MPOL_MF_LAZY); nr_failed = migrate_pages(&pagelist, new_page, NULL, start, MIGRATE_SYNC, MR_MEMPOLICY_MBIND); if (nr_failed) putback_movable_pages(&pagelist); } if ((ret > 0) || (nr_failed && (flags & MPOL_MF_STRICT))) err = -EIO; } else { up_out: if (!list_empty(&pagelist)) putback_movable_pages(&pagelist); } up_write(&mm->mmap_sem); mpol_out: mpol_put(new); return err; } /* * User space interface with variable sized bitmaps for nodelists. */ /* Copy a node mask from user space. */ static int get_nodes(nodemask_t *nodes, const unsigned long __user *nmask, unsigned long maxnode) { unsigned long k; unsigned long t; unsigned long nlongs; unsigned long endmask; --maxnode; nodes_clear(*nodes); if (maxnode == 0 || !nmask) return 0; if (maxnode > PAGE_SIZE*BITS_PER_BYTE) return -EINVAL; nlongs = BITS_TO_LONGS(maxnode); if ((maxnode % BITS_PER_LONG) == 0) endmask = ~0UL; else endmask = (1UL << (maxnode % BITS_PER_LONG)) - 1; /* * When the user specified more nodes than supported just check * if the non supported part is all zero. * * If maxnode have more longs than MAX_NUMNODES, check * the bits in that area first. And then go through to * check the rest bits which equal or bigger than MAX_NUMNODES. * Otherwise, just check bits [MAX_NUMNODES, maxnode). */ if (nlongs > BITS_TO_LONGS(MAX_NUMNODES)) { for (k = BITS_TO_LONGS(MAX_NUMNODES); k < nlongs; k++) { if (get_user(t, nmask + k)) return -EFAULT; if (k == nlongs - 1) { if (t & endmask) return -EINVAL; } else if (t) return -EINVAL; } nlongs = BITS_TO_LONGS(MAX_NUMNODES); endmask = ~0UL; } if (maxnode > MAX_NUMNODES && MAX_NUMNODES % BITS_PER_LONG != 0) { unsigned long valid_mask = endmask; valid_mask &= ~((1UL << (MAX_NUMNODES % BITS_PER_LONG)) - 1); if (get_user(t, nmask + nlongs - 1)) return -EFAULT; if (t & valid_mask) return -EINVAL; } if (copy_from_user(nodes_addr(*nodes), nmask, nlongs*sizeof(unsigned long))) return -EFAULT; nodes_addr(*nodes)[nlongs-1] &= endmask; return 0; } /* Copy a kernel node mask to user space */ static int copy_nodes_to_user(unsigned long __user *mask, unsigned long maxnode, nodemask_t *nodes) { unsigned long copy = ALIGN(maxnode-1, 64) / 8; unsigned int nbytes = BITS_TO_LONGS(nr_node_ids) * sizeof(long); if (copy > nbytes) { if (copy > PAGE_SIZE) return -EINVAL; if (clear_user((char __user *)mask + nbytes, copy - nbytes)) return -EFAULT; copy = nbytes; } return copy_to_user(mask, nodes_addr(*nodes), copy) ? -EFAULT : 0; } static long kernel_mbind(unsigned long start, unsigned long len, unsigned long mode, const unsigned long __user *nmask, unsigned long maxnode, unsigned int flags) { nodemask_t nodes; int err; unsigned short mode_flags; start = untagged_addr(start); mode_flags = mode & MPOL_MODE_FLAGS; mode &= ~MPOL_MODE_FLAGS; if (mode >= MPOL_MAX) return -EINVAL; if ((mode_flags & MPOL_F_STATIC_NODES) && (mode_flags & MPOL_F_RELATIVE_NODES)) return -EINVAL; err = get_nodes(&nodes, nmask, maxnode); if (err) return err; return do_mbind(start, len, mode, mode_flags, &nodes, flags); } SYSCALL_DEFINE6(mbind, unsigned long, start, unsigned long, len, unsigned long, mode, const unsigned long __user *, nmask, unsigned long, maxnode, unsigned int, flags) { return kernel_mbind(start, len, mode, nmask, maxnode, flags); } /* Set the process memory policy */ static long kernel_set_mempolicy(int mode, const unsigned long __user *nmask, unsigned long maxnode) { int err; nodemask_t nodes; unsigned short flags; flags = mode & MPOL_MODE_FLAGS; mode &= ~MPOL_MODE_FLAGS; if ((unsigned int)mode >= MPOL_MAX) return -EINVAL; if ((flags & MPOL_F_STATIC_NODES) && (flags & MPOL_F_RELATIVE_NODES)) return -EINVAL; err = get_nodes(&nodes, nmask, maxnode); if (err) return err; return do_set_mempolicy(mode, flags, &nodes); } SYSCALL_DEFINE3(set_mempolicy, int, mode, const unsigned long __user *, nmask, unsigned long, maxnode) { return kernel_set_mempolicy(mode, nmask, maxnode); } static int kernel_migrate_pages(pid_t pid, unsigned long maxnode, const unsigned long __user *old_nodes, const unsigned long __user *new_nodes) { struct mm_struct *mm = NULL; struct task_struct *task; nodemask_t task_nodes; int err; nodemask_t *old; nodemask_t *new; NODEMASK_SCRATCH(scratch); if (!scratch) return -ENOMEM; old = &scratch->mask1; new = &scratch->mask2; err = get_nodes(old, old_nodes, maxnode); if (err) goto out; err = get_nodes(new, new_nodes, maxnode); if (err) goto out; /* Find the mm_struct */ rcu_read_lock(); task = pid ? find_task_by_vpid(pid) : current; if (!task) { rcu_read_unlock(); err = -ESRCH; goto out; } get_task_struct(task); err = -EINVAL; /* * Check if this process has the right to modify the specified process. * Use the regular "ptrace_may_access()" checks. */ if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) { rcu_read_unlock(); err = -EPERM; goto out_put; } rcu_read_unlock(); task_nodes = cpuset_mems_allowed(task); /* Is the user allowed to access the target nodes? */ if (!nodes_subset(*new, task_nodes) && !capable(CAP_SYS_NICE)) { err = -EPERM; goto out_put; } task_nodes = cpuset_mems_allowed(current); nodes_and(*new, *new, task_nodes); if (nodes_empty(*new)) goto out_put; err = security_task_movememory(task); if (err) goto out_put; mm = get_task_mm(task); put_task_struct(task); if (!mm) { err = -EINVAL; goto out; } err = do_migrate_pages(mm, old, new, capable(CAP_SYS_NICE) ? MPOL_MF_MOVE_ALL : MPOL_MF_MOVE); mmput(mm); out: NODEMASK_SCRATCH_FREE(scratch); return err; out_put: put_task_struct(task); goto out; } SYSCALL_DEFINE4(migrate_pages, pid_t, pid, unsigned long, maxnode, const unsigned long __user *, old_nodes, const unsigned long __user *, new_nodes) { return kernel_migrate_pages(pid, maxnode, old_nodes, new_nodes); } /* Retrieve NUMA policy */ static int kernel_get_mempolicy(int __user *policy, unsigned long __user *nmask, unsigned long maxnode, unsigned long addr, unsigned long flags) { int err; int uninitialized_var(pval); nodemask_t nodes; addr = untagged_addr(addr); if (nmask != NULL && maxnode < nr_node_ids) return -EINVAL; err = do_get_mempolicy(&pval, &nodes, addr, flags); if (err) return err; if (policy && put_user(pval, policy)) return -EFAULT; if (nmask) err = copy_nodes_to_user(nmask, maxnode, &nodes); return err; } SYSCALL_DEFINE5(get_mempolicy, int __user *, policy, unsigned long __user *, nmask, unsigned long, maxnode, unsigned long, addr, unsigned long, flags) { return kernel_get_mempolicy(policy, nmask, maxnode, addr, flags); } #ifdef CONFIG_COMPAT COMPAT_SYSCALL_DEFINE5(get_mempolicy, int __user *, policy, compat_ulong_t __user *, nmask, compat_ulong_t, maxnode, compat_ulong_t, addr, compat_ulong_t, flags) { long err; unsigned long __user *nm = NULL; unsigned long nr_bits, alloc_size; DECLARE_BITMAP(bm, MAX_NUMNODES); nr_bits = min_t(unsigned long, maxnode-1, nr_node_ids); alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8; if (nmask) nm = compat_alloc_user_space(alloc_size); err = kernel_get_mempolicy(policy, nm, nr_bits+1, addr, flags); if (!err && nmask) { unsigned long copy_size; copy_size = min_t(unsigned long, sizeof(bm), alloc_size); err = copy_from_user(bm, nm, copy_size); /* ensure entire bitmap is zeroed */ err |= clear_user(nmask, ALIGN(maxnode-1, 8) / 8); err |= compat_put_bitmap(nmask, bm, nr_bits); } return err; } COMPAT_SYSCALL_DEFINE3(set_mempolicy, int, mode, compat_ulong_t __user *, nmask, compat_ulong_t, maxnode) { unsigned long __user *nm = NULL; unsigned long nr_bits, alloc_size; DECLARE_BITMAP(bm, MAX_NUMNODES); nr_bits = min_t(unsigned long, maxnode-1, MAX_NUMNODES); alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8; if (nmask) { if (compat_get_bitmap(bm, nmask, nr_bits)) return -EFAULT; nm = compat_alloc_user_space(alloc_size); if (copy_to_user(nm, bm, alloc_size)) return -EFAULT; } return kernel_set_mempolicy(mode, nm, nr_bits+1); } COMPAT_SYSCALL_DEFINE6(mbind, compat_ulong_t, start, compat_ulong_t, len, compat_ulong_t, mode, compat_ulong_t __user *, nmask, compat_ulong_t, maxnode, compat_ulong_t, flags) { unsigned long __user *nm = NULL; unsigned long nr_bits, alloc_size; nodemask_t bm; nr_bits = min_t(unsigned long, maxnode-1, MAX_NUMNODES); alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8; if (nmask) { if (compat_get_bitmap(nodes_addr(bm), nmask, nr_bits)) return -EFAULT; nm = compat_alloc_user_space(alloc_size); if (copy_to_user(nm, nodes_addr(bm), alloc_size)) return -EFAULT; } return kernel_mbind(start, len, mode, nm, nr_bits+1, flags); } COMPAT_SYSCALL_DEFINE4(migrate_pages, compat_pid_t, pid, compat_ulong_t, maxnode, const compat_ulong_t __user *, old_nodes, const compat_ulong_t __user *, new_nodes) { unsigned long __user *old = NULL; unsigned long __user *new = NULL; nodemask_t tmp_mask; unsigned long nr_bits; unsigned long size; nr_bits = min_t(unsigned long, maxnode - 1, MAX_NUMNODES); size = ALIGN(nr_bits, BITS_PER_LONG) / 8; if (old_nodes) { if (compat_get_bitmap(nodes_addr(tmp_mask), old_nodes, nr_bits)) return -EFAULT; old = compat_alloc_user_space(new_nodes ? size * 2 : size); if (new_nodes) new = old + size / sizeof(unsigned long); if (copy_to_user(old, nodes_addr(tmp_mask), size)) return -EFAULT; } if (new_nodes) { if (compat_get_bitmap(nodes_addr(tmp_mask), new_nodes, nr_bits)) return -EFAULT; if (new == NULL) new = compat_alloc_user_space(size); if (copy_to_user(new, nodes_addr(tmp_mask), size)) return -EFAULT; } return kernel_migrate_pages(pid, nr_bits + 1, old, new); } #endif /* CONFIG_COMPAT */ bool vma_migratable(struct vm_area_struct *vma) { if (vma->vm_flags & (VM_IO | VM_PFNMAP)) return false; /* * DAX device mappings require predictable access latency, so avoid * incurring periodic faults. */ if (vma_is_dax(vma)) return false; if (is_vm_hugetlb_page(vma) && !hugepage_migration_supported(hstate_vma(vma))) return false; /* * Migration allocates pages in the highest zone. If we cannot * do so then migration (at least from node to node) is not * possible. */ if (vma->vm_file && gfp_zone(mapping_gfp_mask(vma->vm_file->f_mapping)) < policy_zone) return false; return true; } struct mempolicy *__get_vma_policy(struct vm_area_struct *vma, unsigned long addr) { struct mempolicy *pol = NULL; if (vma) { if (vma->vm_ops && vma->vm_ops->get_policy) { pol = vma->vm_ops->get_policy(vma, addr); } else if (vma->vm_policy) { pol = vma->vm_policy; /* * shmem_alloc_page() passes MPOL_F_SHARED policy with * a pseudo vma whose vma->vm_ops=NULL. Take a reference * count on these policies which will be dropped by * mpol_cond_put() later */ if (mpol_needs_cond_ref(pol)) mpol_get(pol); } } return pol; } /* * get_vma_policy(@vma, @addr) * @vma: virtual memory area whose policy is sought * @addr: address in @vma for shared policy lookup * * Returns effective policy for a VMA at specified address. * Falls back to current->mempolicy or system default policy, as necessary. * Shared policies [those marked as MPOL_F_SHARED] require an extra reference * count--added by the get_policy() vm_op, as appropriate--to protect against * freeing by another task. It is the caller's responsibility to free the * extra reference for shared policies. */ static struct mempolicy *get_vma_policy(struct vm_area_struct *vma, unsigned long addr) { struct mempolicy *pol = __get_vma_policy(vma, addr); if (!pol) pol = get_task_policy(current); return pol; } bool vma_policy_mof(struct vm_area_struct *vma) { struct mempolicy *pol; if (vma->vm_ops && vma->vm_ops->get_policy) { bool ret = false; pol = vma->vm_ops->get_policy(vma, vma->vm_start); if (pol && (pol->flags & MPOL_F_MOF)) ret = true; mpol_cond_put(pol); return ret; } pol = vma->vm_policy; if (!pol) pol = get_task_policy(current); return pol->flags & MPOL_F_MOF; } static int apply_policy_zone(struct mempolicy *policy, enum zone_type zone) { enum zone_type dynamic_policy_zone = policy_zone; BUG_ON(dynamic_policy_zone == ZONE_MOVABLE); /* * if policy->v.nodes has movable memory only, * we apply policy when gfp_zone(gfp) = ZONE_MOVABLE only. * * policy->v.nodes is intersect with node_states[N_MEMORY]. * so if the following test faile, it implies * policy->v.nodes has movable memory only. */ if (!nodes_intersects(policy->v.nodes, node_states[N_HIGH_MEMORY])) dynamic_policy_zone = ZONE_MOVABLE; return zone >= dynamic_policy_zone; } /* * Return a nodemask representing a mempolicy for filtering nodes for * page allocation */ static nodemask_t *policy_nodemask(gfp_t gfp, struct mempolicy *policy) { /* Lower zones don't get a nodemask applied for MPOL_BIND */ if (unlikely(policy->mode == MPOL_BIND) && apply_policy_zone(policy, gfp_zone(gfp)) && cpuset_nodemask_valid_mems_allowed(&policy->v.nodes)) return &policy->v.nodes; return NULL; } /* Return the node id preferred by the given mempolicy, or the given id */ static int policy_node(gfp_t gfp, struct mempolicy *policy, int nd) { if (policy->mode == MPOL_PREFERRED && !(policy->flags & MPOL_F_LOCAL)) nd = policy->v.preferred_node; else { /* * __GFP_THISNODE shouldn't even be used with the bind policy * because we might easily break the expectation to stay on the * requested node and not break the policy. */ WARN_ON_ONCE(policy->mode == MPOL_BIND && (gfp & __GFP_THISNODE)); } return nd; } /* Do dynamic interleaving for a process */ static unsigned interleave_nodes(struct mempolicy *policy) { unsigned next; struct task_struct *me = current; next = next_node_in(me->il_prev, policy->v.nodes); if (next < MAX_NUMNODES) me->il_prev = next; return next; } /* * Depending on the memory policy provide a node from which to allocate the * next slab entry. */ unsigned int mempolicy_slab_node(void) { struct mempolicy *policy; int node = numa_mem_id(); if (in_interrupt()) return node; policy = current->mempolicy; if (!policy || policy->flags & MPOL_F_LOCAL) return node; switch (policy->mode) { case MPOL_PREFERRED: /* * handled MPOL_F_LOCAL above */ return policy->v.preferred_node; case MPOL_INTERLEAVE: return interleave_nodes(policy); case MPOL_BIND: { struct zoneref *z; /* * Follow bind policy behavior and start allocation at the * first node. */ struct zonelist *zonelist; enum zone_type highest_zoneidx = gfp_zone(GFP_KERNEL); zonelist = &NODE_DATA(node)->node_zonelists[ZONELIST_FALLBACK]; z = first_zones_zonelist(zonelist, highest_zoneidx, &policy->v.nodes); return z->zone ? zone_to_nid(z->zone) : node; } default: BUG(); } } /* * Do static interleaving for a VMA with known offset @n. Returns the n'th * node in pol->v.nodes (starting from n=0), wrapping around if n exceeds the * number of present nodes. */ static unsigned offset_il_node(struct mempolicy *pol, unsigned long n) { unsigned nnodes = nodes_weight(pol->v.nodes); unsigned target; int i; int nid; if (!nnodes) return numa_node_id(); target = (unsigned int)n % nnodes; nid = first_node(pol->v.nodes); for (i = 0; i < target; i++) nid = next_node(nid, pol->v.nodes); return nid; } /* Determine a node number for interleave */ static inline unsigned interleave_nid(struct mempolicy *pol, struct vm_area_struct *vma, unsigned long addr, int shift) { if (vma) { unsigned long off; /* * for small pages, there is no difference between * shift and PAGE_SHIFT, so the bit-shift is safe. * for huge pages, since vm_pgoff is in units of small * pages, we need to shift off the always 0 bits to get * a useful offset. */ BUG_ON(shift < PAGE_SHIFT); off = vma->vm_pgoff >> (shift - PAGE_SHIFT); off += (addr - vma->vm_start) >> shift; return offset_il_node(pol, off); } else return interleave_nodes(pol); } #ifdef CONFIG_HUGETLBFS /* * huge_node(@vma, @addr, @gfp_flags, @mpol) * @vma: virtual memory area whose policy is sought * @addr: address in @vma for shared policy lookup and interleave policy * @gfp_flags: for requested zone * @mpol: pointer to mempolicy pointer for reference counted mempolicy * @nodemask: pointer to nodemask pointer for MPOL_BIND nodemask * * Returns a nid suitable for a huge page allocation and a pointer * to the struct mempolicy for conditional unref after allocation. * If the effective policy is 'BIND, returns a pointer to the mempolicy's * @nodemask for filtering the zonelist. * * Must be protected by read_mems_allowed_begin() */ int huge_node(struct vm_area_struct *vma, unsigned long addr, gfp_t gfp_flags, struct mempolicy **mpol, nodemask_t **nodemask) { int nid; *mpol = get_vma_policy(vma, addr); *nodemask = NULL; /* assume !MPOL_BIND */ if (unlikely((*mpol)->mode == MPOL_INTERLEAVE)) { nid = interleave_nid(*mpol, vma, addr, huge_page_shift(hstate_vma(vma))); } else { nid = policy_node(gfp_flags, *mpol, numa_node_id()); if ((*mpol)->mode == MPOL_BIND) *nodemask = &(*mpol)->v.nodes; } return nid; } /* * init_nodemask_of_mempolicy * * If the current task's mempolicy is "default" [NULL], return 'false' * to indicate default policy. Otherwise, extract the policy nodemask * for 'bind' or 'interleave' policy into the argument nodemask, or * initialize the argument nodemask to contain the single node for * 'preferred' or 'local' policy and return 'true' to indicate presence * of non-default mempolicy. * * We don't bother with reference counting the mempolicy [mpol_get/put] * because the current task is examining it's own mempolicy and a task's * mempolicy is only ever changed by the task itself. * * N.B., it is the caller's responsibility to free a returned nodemask. */ bool init_nodemask_of_mempolicy(nodemask_t *mask) { struct mempolicy *mempolicy; int nid; if (!(mask && current->mempolicy)) return false; task_lock(current); mempolicy = current->mempolicy; switch (mempolicy->mode) { case MPOL_PREFERRED: if (mempolicy->flags & MPOL_F_LOCAL) nid = numa_node_id(); else nid = mempolicy->v.preferred_node; init_nodemask_of_node(mask, nid); break; case MPOL_BIND: /* Fall through */ case MPOL_INTERLEAVE: *mask = mempolicy->v.nodes; break; default: BUG(); } task_unlock(current); return true; } #endif /* * mempolicy_nodemask_intersects * * If tsk's mempolicy is "default" [NULL], return 'true' to indicate default * policy. Otherwise, check for intersection between mask and the policy * nodemask for 'bind' or 'interleave' policy. For 'perferred' or 'local' * policy, always return true since it may allocate elsewhere on fallback. * * Takes task_lock(tsk) to prevent freeing of its mempolicy. */ bool mempolicy_nodemask_intersects(struct task_struct *tsk, const nodemask_t *mask) { struct mempolicy *mempolicy; bool ret = true; if (!mask) return ret; task_lock(tsk); mempolicy = tsk->mempolicy; if (!mempolicy) goto out; switch (mempolicy->mode) { case MPOL_PREFERRED: /* * MPOL_PREFERRED and MPOL_F_LOCAL are only preferred nodes to * allocate from, they may fallback to other nodes when oom. * Thus, it's possible for tsk to have allocated memory from * nodes in mask. */ break; case MPOL_BIND: case MPOL_INTERLEAVE: ret = nodes_intersects(mempolicy->v.nodes, *mask); break; default: BUG(); } out: task_unlock(tsk); return ret; } /* Allocate a page in interleaved policy. Own path because it needs to do special accounting. */ static struct page *alloc_page_interleave(gfp_t gfp, unsigned order, unsigned nid) { struct page *page; page = __alloc_pages(gfp, order, nid); /* skip NUMA_INTERLEAVE_HIT counter update if numa stats is disabled */ if (!static_branch_likely(&vm_numa_stat_key)) return page; if (page && page_to_nid(page) == nid) { preempt_disable(); __inc_numa_state(page_zone(page), NUMA_INTERLEAVE_HIT); preempt_enable(); } return page; } /** * alloc_pages_vma - Allocate a page for a VMA. * * @gfp: * %GFP_USER user allocation. * %GFP_KERNEL kernel allocations, * %GFP_HIGHMEM highmem/user allocations, * %GFP_FS allocation should not call back into a file system. * %GFP_ATOMIC don't sleep. * * @order:Order of the GFP allocation. * @vma: Pointer to VMA or NULL if not available. * @addr: Virtual Address of the allocation. Must be inside the VMA. * @node: Which node to prefer for allocation (modulo policy). * @hugepage: for hugepages try only the preferred node if possible * * This function allocates a page from the kernel page pool and applies * a NUMA policy associated with the VMA or the current process. * When VMA is not NULL caller must hold down_read on the mmap_sem of the * mm_struct of the VMA to prevent it from going away. Should be used for * all allocations for pages that will be mapped into user space. Returns * NULL when no page can be allocated. */ struct page * alloc_pages_vma(gfp_t gfp, int order, struct vm_area_struct *vma, unsigned long addr, int node, bool hugepage) { struct mempolicy *pol; struct page *page; int preferred_nid; nodemask_t *nmask; pol = get_vma_policy(vma, addr); if (pol->mode == MPOL_INTERLEAVE) { unsigned nid; nid = interleave_nid(pol, vma, addr, PAGE_SHIFT + order); mpol_cond_put(pol); page = alloc_page_interleave(gfp, order, nid); goto out; } if (unlikely(IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) && hugepage)) { int hpage_node = node; /* * For hugepage allocation and non-interleave policy which * allows the current node (or other explicitly preferred * node) we only try to allocate from the current/preferred * node and don't fall back to other nodes, as the cost of * remote accesses would likely offset THP benefits. * * If the policy is interleave, or does not allow the current * node in its nodemask, we allocate the standard way. */ if (pol->mode == MPOL_PREFERRED && !(pol->flags & MPOL_F_LOCAL)) hpage_node = pol->v.preferred_node; nmask = policy_nodemask(gfp, pol); if (!nmask || node_isset(hpage_node, *nmask)) { mpol_cond_put(pol); /* * First, try to allocate THP only on local node, but * don't reclaim unnecessarily, just compact. */ page = __alloc_pages_node(hpage_node, gfp | __GFP_THISNODE | __GFP_NORETRY, order); /* * If hugepage allocations are configured to always * synchronous compact or the vma has been madvised * to prefer hugepage backing, retry allowing remote * memory with both reclaim and compact as well. */ if (!page && (gfp & __GFP_DIRECT_RECLAIM)) page = __alloc_pages_node(hpage_node, gfp, order); goto out; } } nmask = policy_nodemask(gfp, pol); preferred_nid = policy_node(gfp, pol, node); page = __alloc_pages_nodemask(gfp, order, preferred_nid, nmask); mpol_cond_put(pol); out: return page; } EXPORT_SYMBOL(alloc_pages_vma); /** * alloc_pages_current - Allocate pages. * * @gfp: * %GFP_USER user allocation, * %GFP_KERNEL kernel allocation, * %GFP_HIGHMEM highmem allocation, * %GFP_FS don't call back into a file system. * %GFP_ATOMIC don't sleep. * @order: Power of two of allocation size in pages. 0 is a single page. * * Allocate a page from the kernel page pool. When not in * interrupt context and apply the current process NUMA policy. * Returns NULL when no page can be allocated. */ struct page *alloc_pages_current(gfp_t gfp, unsigned order) { struct mempolicy *pol = &default_policy; struct page *page; if (!in_interrupt() && !(gfp & __GFP_THISNODE)) pol = get_task_policy(current); /* * No reference counting needed for current->mempolicy * nor system default_policy */ if (pol->mode == MPOL_INTERLEAVE) page = alloc_page_interleave(gfp, order, interleave_nodes(pol)); else page = __alloc_pages_nodemask(gfp, order, policy_node(gfp, pol, numa_node_id()), policy_nodemask(gfp, pol)); return page; } EXPORT_SYMBOL(alloc_pages_current); int vma_dup_policy(struct vm_area_struct *src, struct vm_area_struct *dst) { struct mempolicy *pol = mpol_dup(vma_policy(src)); if (IS_ERR(pol)) return PTR_ERR(pol); dst->vm_policy = pol; return 0; } /* * If mpol_dup() sees current->cpuset == cpuset_being_rebound, then it * rebinds the mempolicy its copying by calling mpol_rebind_policy() * with the mems_allowed returned by cpuset_mems_allowed(). This * keeps mempolicies cpuset relative after its cpuset moves. See * further kernel/cpuset.c update_nodemask(). * * current's mempolicy may be rebinded by the other task(the task that changes * cpuset's mems), so we needn't do rebind work for current task. */ /* Slow path of a mempolicy duplicate */ struct mempolicy *__mpol_dup(struct mempolicy *old) { struct mempolicy *new = kmem_cache_alloc(policy_cache, GFP_KERNEL); if (!new) return ERR_PTR(-ENOMEM); /* task's mempolicy is protected by alloc_lock */ if (old == current->mempolicy) { task_lock(current); *new = *old; task_unlock(current); } else *new = *old; if (current_cpuset_is_being_rebound()) { nodemask_t mems = cpuset_mems_allowed(current); mpol_rebind_policy(new, &mems); } atomic_set(&new->refcnt, 1); return new; } /* Slow path of a mempolicy comparison */ bool __mpol_equal(struct mempolicy *a, struct mempolicy *b) { if (!a || !b) return false; if (a->mode != b->mode) return false; if (a->flags != b->flags) return false; if (mpol_store_user_nodemask(a)) if (!nodes_equal(a->w.user_nodemask, b->w.user_nodemask)) return false; switch (a->mode) { case MPOL_BIND: /* Fall through */ case MPOL_INTERLEAVE: return !!nodes_equal(a->v.nodes, b->v.nodes); case MPOL_PREFERRED: /* a's ->flags is the same as b's */ if (a->flags & MPOL_F_LOCAL) return true; return a->v.preferred_node == b->v.preferred_node; default: BUG(); return false; } } /* * Shared memory backing store policy support. * * Remember policies even when nobody has shared memory mapped. * The policies are kept in Red-Black tree linked from the inode. * They are protected by the sp->lock rwlock, which should be held * for any accesses to the tree. */ /* * lookup first element intersecting start-end. Caller holds sp->lock for * reading or for writing */ static struct sp_node * sp_lookup(struct shared_policy *sp, unsigned long start, unsigned long end) { struct rb_node *n = sp->root.rb_node; while (n) { struct sp_node *p = rb_entry(n, struct sp_node, nd); if (start >= p->end) n = n->rb_right; else if (end <= p->start) n = n->rb_left; else break; } if (!n) return NULL; for (;;) { struct sp_node *w = NULL; struct rb_node *prev = rb_prev(n); if (!prev) break; w = rb_entry(prev, struct sp_node, nd); if (w->end <= start) break; n = prev; } return rb_entry(n, struct sp_node, nd); } /* * Insert a new shared policy into the list. Caller holds sp->lock for * writing. */ static void sp_insert(struct shared_policy *sp, struct sp_node *new) { struct rb_node **p = &sp->root.rb_node; struct rb_node *parent = NULL; struct sp_node *nd; while (*p) { parent = *p; nd = rb_entry(parent, struct sp_node, nd); if (new->start < nd->start) p = &(*p)->rb_left; else if (new->end > nd->end) p = &(*p)->rb_right; else BUG(); } rb_link_node(&new->nd, parent, p); rb_insert_color(&new->nd, &sp->root); pr_debug("inserting %lx-%lx: %d\n", new->start, new->end, new->policy ? new->policy->mode : 0); } /* Find shared policy intersecting idx */ struct mempolicy * mpol_shared_policy_lookup(struct shared_policy *sp, unsigned long idx) { struct mempolicy *pol = NULL; struct sp_node *sn; if (!sp->root.rb_node) return NULL; read_lock(&sp->lock); sn = sp_lookup(sp, idx, idx+1); if (sn) { mpol_get(sn->policy); pol = sn->policy; } read_unlock(&sp->lock); return pol; } static void sp_free(struct sp_node *n) { mpol_put(n->policy); kmem_cache_free(sn_cache, n); } /** * mpol_misplaced - check whether current page node is valid in policy * * @page: page to be checked * @vma: vm area where page mapped * @addr: virtual address where page mapped * * Lookup current policy node id for vma,addr and "compare to" page's * node id. * * Returns: * -1 - not misplaced, page is in the right node * node - node id where the page should be * * Policy determination "mimics" alloc_page_vma(). * Called from fault path where we know the vma and faulting address. */ int mpol_misplaced(struct page *page, struct vm_area_struct *vma, unsigned long addr) { struct mempolicy *pol; struct zoneref *z; int curnid = page_to_nid(page); unsigned long pgoff; int thiscpu = raw_smp_processor_id(); int thisnid = cpu_to_node(thiscpu); int polnid = NUMA_NO_NODE; int ret = -1; pol = get_vma_policy(vma, addr); if (!(pol->flags & MPOL_F_MOF)) goto out; switch (pol->mode) { case MPOL_INTERLEAVE: pgoff = vma->vm_pgoff; pgoff += (addr - vma->vm_start) >> PAGE_SHIFT; polnid = offset_il_node(pol, pgoff); break; case MPOL_PREFERRED: if (pol->flags & MPOL_F_LOCAL) polnid = numa_node_id(); else polnid = pol->v.preferred_node; break; case MPOL_BIND: /* * allows binding to multiple nodes. * use current page if in policy nodemask, * else select nearest allowed node, if any. * If no allowed nodes, use current [!misplaced]. */ if (node_isset(curnid, pol->v.nodes)) goto out; z = first_zones_zonelist( node_zonelist(numa_node_id(), GFP_HIGHUSER), gfp_zone(GFP_HIGHUSER), &pol->v.nodes); polnid = zone_to_nid(z->zone); break; default: BUG(); } /* Migrate the page towards the node whose CPU is referencing it */ if (pol->flags & MPOL_F_MORON) { polnid = thisnid; if (!should_numa_migrate_memory(current, page, curnid, thiscpu)) goto out; } if (curnid != polnid) ret = polnid; out: mpol_cond_put(pol); return ret; } /* * Drop the (possibly final) reference to task->mempolicy. It needs to be * dropped after task->mempolicy is set to NULL so that any allocation done as * part of its kmem_cache_free(), such as by KASAN, doesn't reference a freed * policy. */ void mpol_put_task_policy(struct task_struct *task) { struct mempolicy *pol; task_lock(task); pol = task->mempolicy; task->mempolicy = NULL; task_unlock(task); mpol_put(pol); } static void sp_delete(struct shared_policy *sp, struct sp_node *n) { pr_debug("deleting %lx-l%lx\n", n->start, n->end); rb_erase(&n->nd, &sp->root); sp_free(n); } static void sp_node_init(struct sp_node *node, unsigned long start, unsigned long end, struct mempolicy *pol) { node->start = start; node->end = end; node->policy = pol; } static struct sp_node *sp_alloc(unsigned long start, unsigned long end, struct mempolicy *pol) { struct sp_node *n; struct mempolicy *newpol; n = kmem_cache_alloc(sn_cache, GFP_KERNEL); if (!n) return NULL; newpol = mpol_dup(pol); if (IS_ERR(newpol)) { kmem_cache_free(sn_cache, n); return NULL; } newpol->flags |= MPOL_F_SHARED; sp_node_init(n, start, end, newpol); return n; } /* Replace a policy range. */ static int shared_policy_replace(struct shared_policy *sp, unsigned long start, unsigned long end, struct sp_node *new) { struct sp_node *n; struct sp_node *n_new = NULL; struct mempolicy *mpol_new = NULL; int ret = 0; restart: write_lock(&sp->lock); n = sp_lookup(sp, start, end); /* Take care of old policies in the same range. */ while (n && n->start < end) { struct rb_node *next = rb_next(&n->nd); if (n->start >= start) { if (n->end <= end) sp_delete(sp, n); else n->start = end; } else { /* Old policy spanning whole new range. */ if (n->end > end) { if (!n_new) goto alloc_new; *mpol_new = *n->policy; atomic_set(&mpol_new->refcnt, 1); sp_node_init(n_new, end, n->end, mpol_new); n->end = start; sp_insert(sp, n_new); n_new = NULL; mpol_new = NULL; break; } else n->end = start; } if (!next) break; n = rb_entry(next, struct sp_node, nd); } if (new) sp_insert(sp, new); write_unlock(&sp->lock); ret = 0; err_out: if (mpol_new) mpol_put(mpol_new); if (n_new) kmem_cache_free(sn_cache, n_new); return ret; alloc_new: write_unlock(&sp->lock); ret = -ENOMEM; n_new = kmem_cache_alloc(sn_cache, GFP_KERNEL); if (!n_new) goto err_out; mpol_new = kmem_cache_alloc(policy_cache, GFP_KERNEL); if (!mpol_new) goto err_out; goto restart; } /** * mpol_shared_policy_init - initialize shared policy for inode * @sp: pointer to inode shared policy * @mpol: struct mempolicy to install * * Install non-NULL @mpol in inode's shared policy rb-tree. * On entry, the current task has a reference on a non-NULL @mpol. * This must be released on exit. * This is called at get_inode() calls and we can use GFP_KERNEL. */ void mpol_shared_policy_init(struct shared_policy *sp, struct mempolicy *mpol) { int ret; sp->root = RB_ROOT; /* empty tree == default mempolicy */ rwlock_init(&sp->lock); if (mpol) { struct vm_area_struct pvma; struct mempolicy *new; NODEMASK_SCRATCH(scratch); if (!scratch) goto put_mpol; /* contextualize the tmpfs mount point mempolicy */ new = mpol_new(mpol->mode, mpol->flags, &mpol->w.user_nodemask); if (IS_ERR(new)) goto free_scratch; /* no valid nodemask intersection */ task_lock(current); ret = mpol_set_nodemask(new, &mpol->w.user_nodemask, scratch); task_unlock(current); if (ret) goto put_new; /* Create pseudo-vma that contains just the policy */ vma_init(&pvma, NULL); pvma.vm_end = TASK_SIZE; /* policy covers entire file */ mpol_set_shared_policy(sp, &pvma, new); /* adds ref */ put_new: mpol_put(new); /* drop initial ref */ free_scratch: NODEMASK_SCRATCH_FREE(scratch); put_mpol: mpol_put(mpol); /* drop our incoming ref on sb mpol */ } } int mpol_set_shared_policy(struct shared_policy *info, struct vm_area_struct *vma, struct mempolicy *npol) { int err; struct sp_node *new = NULL; unsigned long sz = vma_pages(vma); pr_debug("set_shared_policy %lx sz %lu %d %d %lx\n", vma->vm_pgoff, sz, npol ? npol->mode : -1, npol ? npol->flags : -1, npol ? nodes_addr(npol->v.nodes)[0] : NUMA_NO_NODE); if (npol) { new = sp_alloc(vma->vm_pgoff, vma->vm_pgoff + sz, npol); if (!new) return -ENOMEM; } err = shared_policy_replace(info, vma->vm_pgoff, vma->vm_pgoff+sz, new); if (err && new) sp_free(new); return err; } /* Free a backing policy store on inode delete. */ void mpol_free_shared_policy(struct shared_policy *p) { struct sp_node *n; struct rb_node *next; if (!p->root.rb_node) return; write_lock(&p->lock); next = rb_first(&p->root); while (next) { n = rb_entry(next, struct sp_node, nd); next = rb_next(&n->nd); sp_delete(p, n); } write_unlock(&p->lock); } #ifdef CONFIG_NUMA_BALANCING static int __initdata numabalancing_override; static void __init check_numabalancing_enable(void) { bool numabalancing_default = false; if (IS_ENABLED(CONFIG_NUMA_BALANCING_DEFAULT_ENABLED)) numabalancing_default = true; /* Parsed by setup_numabalancing. override == 1 enables, -1 disables */ if (numabalancing_override) set_numabalancing_state(numabalancing_override == 1); if (num_online_nodes() > 1 && !numabalancing_override) { pr_info("%s automatic NUMA balancing. Configure with numa_balancing= or the kernel.numa_balancing sysctl\n", numabalancing_default ? "Enabling" : "Disabling"); set_numabalancing_state(numabalancing_default); } } static int __init setup_numabalancing(char *str) { int ret = 0; if (!str) goto out; if (!strcmp(str, "enable")) { numabalancing_override = 1; ret = 1; } else if (!strcmp(str, "disable")) { numabalancing_override = -1; ret = 1; } out: if (!ret) pr_warn("Unable to parse numa_balancing=\n"); return ret; } __setup("numa_balancing=", setup_numabalancing); #else static inline void __init check_numabalancing_enable(void) { } #endif /* CONFIG_NUMA_BALANCING */ /* assumes fs == KERNEL_DS */ void __init numa_policy_init(void) { nodemask_t interleave_nodes; unsigned long largest = 0; int nid, prefer = 0; policy_cache = kmem_cache_create("numa_policy", sizeof(struct mempolicy), 0, SLAB_PANIC, NULL); sn_cache = kmem_cache_create("shared_policy_node", sizeof(struct sp_node), 0, SLAB_PANIC, NULL); for_each_node(nid) { preferred_node_policy[nid] = (struct mempolicy) { .refcnt = ATOMIC_INIT(1), .mode = MPOL_PREFERRED, .flags = MPOL_F_MOF | MPOL_F_MORON, .v = { .preferred_node = nid, }, }; } /* * Set interleaving policy for system init. Interleaving is only * enabled across suitably sized nodes (default is >= 16MB), or * fall back to the largest node if they're all smaller. */ nodes_clear(interleave_nodes); for_each_node_state(nid, N_MEMORY) { unsigned long total_pages = node_present_pages(nid); /* Preserve the largest node */ if (largest < total_pages) { largest = total_pages; prefer = nid; } /* Interleave this node? */ if ((total_pages << PAGE_SHIFT) >= (16 << 20)) node_set(nid, interleave_nodes); } /* All too small, use the largest */ if (unlikely(nodes_empty(interleave_nodes))) node_set(prefer, interleave_nodes); if (do_set_mempolicy(MPOL_INTERLEAVE, 0, &interleave_nodes)) pr_err("%s: interleaving failed\n", __func__); check_numabalancing_enable(); } /* Reset policy of current process to default */ void numa_default_policy(void) { do_set_mempolicy(MPOL_DEFAULT, 0, NULL); } /* * Parse and format mempolicy from/to strings */ /* * "local" is implemented internally by MPOL_PREFERRED with MPOL_F_LOCAL flag. */ static const char * const policy_modes[] = { [MPOL_DEFAULT] = "default", [MPOL_PREFERRED] = "prefer", [MPOL_BIND] = "bind", [MPOL_INTERLEAVE] = "interleave", [MPOL_LOCAL] = "local", }; #ifdef CONFIG_TMPFS /** * mpol_parse_str - parse string to mempolicy, for tmpfs mpol mount option. * @str: string containing mempolicy to parse * @mpol: pointer to struct mempolicy pointer, returned on success. * * Format of input: * <mode>[=<flags>][:<nodelist>] * * On success, returns 0, else 1 */ int mpol_parse_str(char *str, struct mempolicy **mpol) { struct mempolicy *new = NULL; unsigned short mode_flags; nodemask_t nodes; char *nodelist = strchr(str, ':'); char *flags = strchr(str, '='); int err = 1, mode; if (flags) *flags++ = '\0'; /* terminate mode string */ if (nodelist) { /* NUL-terminate mode or flags string */ *nodelist++ = '\0'; if (nodelist_parse(nodelist, nodes)) goto out; if (!nodes_subset(nodes, node_states[N_MEMORY])) goto out; } else nodes_clear(nodes); mode = match_string(policy_modes, MPOL_MAX, str); if (mode < 0) goto out; switch (mode) { case MPOL_PREFERRED: /* * Insist on a nodelist of one node only */ if (nodelist) { char *rest = nodelist; while (isdigit(*rest)) rest++; if (*rest) goto out; } break; case MPOL_INTERLEAVE: /* * Default to online nodes with memory if no nodelist */ if (!nodelist) nodes = node_states[N_MEMORY]; break; case MPOL_LOCAL: /* * Don't allow a nodelist; mpol_new() checks flags */ if (nodelist) goto out; mode = MPOL_PREFERRED; break; case MPOL_DEFAULT: /* * Insist on a empty nodelist */ if (!nodelist) err = 0; goto out; case MPOL_BIND: /* * Insist on a nodelist */ if (!nodelist) goto out; } mode_flags = 0; if (flags) { /* * Currently, we only support two mutually exclusive * mode flags. */ if (!strcmp(flags, "static")) mode_flags |= MPOL_F_STATIC_NODES; else if (!strcmp(flags, "relative")) mode_flags |= MPOL_F_RELATIVE_NODES; else goto out; } new = mpol_new(mode, mode_flags, &nodes); if (IS_ERR(new)) goto out; /* * Save nodes for mpol_to_str() to show the tmpfs mount options * for /proc/mounts, /proc/pid/mounts and /proc/pid/mountinfo. */ if (mode != MPOL_PREFERRED) new->v.nodes = nodes; else if (nodelist) new->v.preferred_node = first_node(nodes); else new->flags |= MPOL_F_LOCAL; /* * Save nodes for contextualization: this will be used to "clone" * the mempolicy in a specific context [cpuset] at a later time. */ new->w.user_nodemask = nodes; err = 0; out: /* Restore string for error message */ if (nodelist) *--nodelist = ':'; if (flags) *--flags = '='; if (!err) *mpol = new; return err; } #endif /* CONFIG_TMPFS */ /** * mpol_to_str - format a mempolicy structure for printing * @buffer: to contain formatted mempolicy string * @maxlen: length of @buffer * @pol: pointer to mempolicy to be formatted * * Convert @pol into a string. If @buffer is too short, truncate the string. * Recommend a @maxlen of at least 32 for the longest mode, "interleave", the * longest flag, "relative", and to display at least a few node ids. */ void mpol_to_str(char *buffer, int maxlen, struct mempolicy *pol) { char *p = buffer; nodemask_t nodes = NODE_MASK_NONE; unsigned short mode = MPOL_DEFAULT; unsigned short flags = 0; if (pol && pol != &default_policy && !(pol->flags & MPOL_F_MORON)) { mode = pol->mode; flags = pol->flags; } switch (mode) { case MPOL_DEFAULT: break; case MPOL_PREFERRED: if (flags & MPOL_F_LOCAL) mode = MPOL_LOCAL; else node_set(pol->v.preferred_node, nodes); break; case MPOL_BIND: case MPOL_INTERLEAVE: nodes = pol->v.nodes; break; default: WARN_ON_ONCE(1); snprintf(p, maxlen, "unknown"); return; } p += snprintf(p, maxlen, "%s", policy_modes[mode]); if (flags & MPOL_MODE_FLAGS) { p += snprintf(p, buffer + maxlen - p, "="); /* * Currently, the only defined flags are mutually exclusive */ if (flags & MPOL_F_STATIC_NODES) p += snprintf(p, buffer + maxlen - p, "static"); else if (flags & MPOL_F_RELATIVE_NODES) p += snprintf(p, buffer + maxlen - p, "relative"); } if (!nodes_empty(nodes)) p += scnprintf(p, buffer + maxlen - p, ":%*pbl", nodemask_pr_args(&nodes)); }
null
// SPDX-License-Identifier: GPL-2.0-only /* * Simple NUMA memory policy for the Linux kernel. * * Copyright 2003,2004 Andi Kleen, SuSE Labs. * (C) Copyright 2005 Christoph Lameter, Silicon Graphics, Inc. * * NUMA policy allows the user to give hints in which node(s) memory should * be allocated. * * Support four policies per VMA and per process: * * The VMA policy has priority over the process policy for a page fault. * * interleave Allocate memory interleaved over a set of nodes, * with normal fallback if it fails. * For VMA based allocations this interleaves based on the * offset into the backing object or offset into the mapping * for anonymous memory. For process policy an process counter * is used. * * bind Only allocate memory on a specific set of nodes, * no fallback. * FIXME: memory is allocated starting with the first node * to the last. It would be better if bind would truly restrict * the allocation to memory nodes instead * * preferred Try a specific node first before normal fallback. * As a special case NUMA_NO_NODE here means do the allocation * on the local CPU. This is normally identical to default, * but useful to set in a VMA when you have a non default * process policy. * * default Allocate on the local node first, or when on a VMA * use the process policy. This is what Linux always did * in a NUMA aware kernel and still does by, ahem, default. * * The process policy is applied for most non interrupt memory allocations * in that process' context. Interrupts ignore the policies and always * try to allocate on the local CPU. The VMA policy is only applied for memory * allocations for a VMA in the VM. * * Currently there are a few corner cases in swapping where the policy * is not applied, but the majority should be handled. When process policy * is used it is not remembered over swap outs/swap ins. * * Only the highest zone in the zone hierarchy gets policied. Allocations * requesting a lower zone just use default policy. This implies that * on systems with highmem kernel lowmem allocation don't get policied. * Same with GFP_DMA allocations. * * For shmfs/tmpfs/hugetlbfs shared memory the policy is shared between * all users and remembered even when nobody has memory mapped. */ /* Notebook: fix mmap readahead to honour policy and enable policy for any page cache object statistics for bigpages global policy for page cache? currently it uses process policy. Requires first item above. handle mremap for shared memory (currently ignored for the policy) grows down? make bind policy root only? It can trigger oom much faster and the kernel is not always grateful with that. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/mempolicy.h> #include <linux/pagewalk.h> #include <linux/highmem.h> #include <linux/hugetlb.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/sched/mm.h> #include <linux/sched/numa_balancing.h> #include <linux/sched/task.h> #include <linux/nodemask.h> #include <linux/cpuset.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/export.h> #include <linux/nsproxy.h> #include <linux/interrupt.h> #include <linux/init.h> #include <linux/compat.h> #include <linux/ptrace.h> #include <linux/swap.h> #include <linux/seq_file.h> #include <linux/proc_fs.h> #include <linux/migrate.h> #include <linux/ksm.h> #include <linux/rmap.h> #include <linux/security.h> #include <linux/syscalls.h> #include <linux/ctype.h> #include <linux/mm_inline.h> #include <linux/mmu_notifier.h> #include <linux/printk.h> #include <linux/swapops.h> #include <asm/tlbflush.h> #include <linux/uaccess.h> #include "internal.h" /* Internal flags */ #define MPOL_MF_DISCONTIG_OK (MPOL_MF_INTERNAL << 0) /* Skip checks for continuous vmas */ #define MPOL_MF_INVERT (MPOL_MF_INTERNAL << 1) /* Invert check for nodemask */ static struct kmem_cache *policy_cache; static struct kmem_cache *sn_cache; /* Highest zone. An specific allocation for a zone below that is not policied. */ enum zone_type policy_zone = 0; /* * run-time system-wide default policy => local allocation */ static struct mempolicy default_policy = { .refcnt = ATOMIC_INIT(1), /* never free it */ .mode = MPOL_PREFERRED, .flags = MPOL_F_LOCAL, }; static struct mempolicy preferred_node_policy[MAX_NUMNODES]; struct mempolicy *get_task_policy(struct task_struct *p) { struct mempolicy *pol = p->mempolicy; int node; if (pol) return pol; node = numa_node_id(); if (node != NUMA_NO_NODE) { pol = &preferred_node_policy[node]; /* preferred_node_policy is not initialised early in boot */ if (pol->mode) return pol; } return &default_policy; } static const struct mempolicy_operations { int (*create)(struct mempolicy *pol, const nodemask_t *nodes); void (*rebind)(struct mempolicy *pol, const nodemask_t *nodes); } mpol_ops[MPOL_MAX]; static inline int mpol_store_user_nodemask(const struct mempolicy *pol) { return pol->flags & MPOL_MODE_FLAGS; } static void mpol_relative_nodemask(nodemask_t *ret, const nodemask_t *orig, const nodemask_t *rel) { nodemask_t tmp; nodes_fold(tmp, *orig, nodes_weight(*rel)); nodes_onto(*ret, tmp, *rel); } static int mpol_new_interleave(struct mempolicy *pol, const nodemask_t *nodes) { if (nodes_empty(*nodes)) return -EINVAL; pol->v.nodes = *nodes; return 0; } static int mpol_new_preferred(struct mempolicy *pol, const nodemask_t *nodes) { if (!nodes) pol->flags |= MPOL_F_LOCAL; /* local allocation */ else if (nodes_empty(*nodes)) return -EINVAL; /* no allowed nodes */ else pol->v.preferred_node = first_node(*nodes); return 0; } static int mpol_new_bind(struct mempolicy *pol, const nodemask_t *nodes) { if (nodes_empty(*nodes)) return -EINVAL; pol->v.nodes = *nodes; return 0; } /* * mpol_set_nodemask is called after mpol_new() to set up the nodemask, if * any, for the new policy. mpol_new() has already validated the nodes * parameter with respect to the policy mode and flags. But, we need to * handle an empty nodemask with MPOL_PREFERRED here. * * Must be called holding task's alloc_lock to protect task's mems_allowed * and mempolicy. May also be called holding the mmap_semaphore for write. */ static int mpol_set_nodemask(struct mempolicy *pol, const nodemask_t *nodes, struct nodemask_scratch *nsc) { int ret; /* if mode is MPOL_DEFAULT, pol is NULL. This is right. */ if (pol == NULL) return 0; /* Check N_MEMORY */ nodes_and(nsc->mask1, cpuset_current_mems_allowed, node_states[N_MEMORY]); VM_BUG_ON(!nodes); if (pol->mode == MPOL_PREFERRED && nodes_empty(*nodes)) nodes = NULL; /* explicit local allocation */ else { if (pol->flags & MPOL_F_RELATIVE_NODES) mpol_relative_nodemask(&nsc->mask2, nodes, &nsc->mask1); else nodes_and(nsc->mask2, *nodes, nsc->mask1); if (mpol_store_user_nodemask(pol)) pol->w.user_nodemask = *nodes; else pol->w.cpuset_mems_allowed = cpuset_current_mems_allowed; } if (nodes) ret = mpol_ops[pol->mode].create(pol, &nsc->mask2); else ret = mpol_ops[pol->mode].create(pol, NULL); return ret; } /* * This function just creates a new policy, does some check and simple * initialization. You must invoke mpol_set_nodemask() to set nodes. */ static struct mempolicy *mpol_new(unsigned short mode, unsigned short flags, nodemask_t *nodes) { struct mempolicy *policy; pr_debug("setting mode %d flags %d nodes[0] %lx\n", mode, flags, nodes ? nodes_addr(*nodes)[0] : NUMA_NO_NODE); if (mode == MPOL_DEFAULT) { if (nodes && !nodes_empty(*nodes)) return ERR_PTR(-EINVAL); return NULL; } VM_BUG_ON(!nodes); /* * MPOL_PREFERRED cannot be used with MPOL_F_STATIC_NODES or * MPOL_F_RELATIVE_NODES if the nodemask is empty (local allocation). * All other modes require a valid pointer to a non-empty nodemask. */ if (mode == MPOL_PREFERRED) { if (nodes_empty(*nodes)) { if (((flags & MPOL_F_STATIC_NODES) || (flags & MPOL_F_RELATIVE_NODES))) return ERR_PTR(-EINVAL); } } else if (mode == MPOL_LOCAL) { if (!nodes_empty(*nodes) || (flags & MPOL_F_STATIC_NODES) || (flags & MPOL_F_RELATIVE_NODES)) return ERR_PTR(-EINVAL); mode = MPOL_PREFERRED; } else if (nodes_empty(*nodes)) return ERR_PTR(-EINVAL); policy = kmem_cache_alloc(policy_cache, GFP_KERNEL); if (!policy) return ERR_PTR(-ENOMEM); atomic_set(&policy->refcnt, 1); policy->mode = mode; policy->flags = flags; return policy; } /* Slow path of a mpol destructor. */ void __mpol_put(struct mempolicy *p) { if (!atomic_dec_and_test(&p->refcnt)) return; kmem_cache_free(policy_cache, p); } static void mpol_rebind_default(struct mempolicy *pol, const nodemask_t *nodes) { } static void mpol_rebind_nodemask(struct mempolicy *pol, const nodemask_t *nodes) { nodemask_t tmp; if (pol->flags & MPOL_F_STATIC_NODES) nodes_and(tmp, pol->w.user_nodemask, *nodes); else if (pol->flags & MPOL_F_RELATIVE_NODES) mpol_relative_nodemask(&tmp, &pol->w.user_nodemask, nodes); else { nodes_remap(tmp, pol->v.nodes,pol->w.cpuset_mems_allowed, *nodes); pol->w.cpuset_mems_allowed = *nodes; } if (nodes_empty(tmp)) tmp = *nodes; pol->v.nodes = tmp; } static void mpol_rebind_preferred(struct mempolicy *pol, const nodemask_t *nodes) { nodemask_t tmp; if (pol->flags & MPOL_F_STATIC_NODES) { int node = first_node(pol->w.user_nodemask); if (node_isset(node, *nodes)) { pol->v.preferred_node = node; pol->flags &= ~MPOL_F_LOCAL; } else pol->flags |= MPOL_F_LOCAL; } else if (pol->flags & MPOL_F_RELATIVE_NODES) { mpol_relative_nodemask(&tmp, &pol->w.user_nodemask, nodes); pol->v.preferred_node = first_node(tmp); } else if (!(pol->flags & MPOL_F_LOCAL)) { pol->v.preferred_node = node_remap(pol->v.preferred_node, pol->w.cpuset_mems_allowed, *nodes); pol->w.cpuset_mems_allowed = *nodes; } } /* * mpol_rebind_policy - Migrate a policy to a different set of nodes * * Per-vma policies are protected by mmap_sem. Allocations using per-task * policies are protected by task->mems_allowed_seq to prevent a premature * OOM/allocation failure due to parallel nodemask modification. */ static void mpol_rebind_policy(struct mempolicy *pol, const nodemask_t *newmask) { if (!pol) return; if (!mpol_store_user_nodemask(pol) && !(pol->flags & MPOL_F_LOCAL) && nodes_equal(pol->w.cpuset_mems_allowed, *newmask)) return; mpol_ops[pol->mode].rebind(pol, newmask); } /* * Wrapper for mpol_rebind_policy() that just requires task * pointer, and updates task mempolicy. * * Called with task's alloc_lock held. */ void mpol_rebind_task(struct task_struct *tsk, const nodemask_t *new) { mpol_rebind_policy(tsk->mempolicy, new); } /* * Rebind each vma in mm to new nodemask. * * Call holding a reference to mm. Takes mm->mmap_sem during call. */ void mpol_rebind_mm(struct mm_struct *mm, nodemask_t *new) { struct vm_area_struct *vma; down_write(&mm->mmap_sem); for (vma = mm->mmap; vma; vma = vma->vm_next) mpol_rebind_policy(vma->vm_policy, new); up_write(&mm->mmap_sem); } static const struct mempolicy_operations mpol_ops[MPOL_MAX] = { [MPOL_DEFAULT] = { .rebind = mpol_rebind_default, }, [MPOL_INTERLEAVE] = { .create = mpol_new_interleave, .rebind = mpol_rebind_nodemask, }, [MPOL_PREFERRED] = { .create = mpol_new_preferred, .rebind = mpol_rebind_preferred, }, [MPOL_BIND] = { .create = mpol_new_bind, .rebind = mpol_rebind_nodemask, }, }; static int migrate_page_add(struct page *page, struct list_head *pagelist, unsigned long flags); struct queue_pages { struct list_head *pagelist; unsigned long flags; nodemask_t *nmask; unsigned long start; unsigned long end; struct vm_area_struct *first; }; /* * Check if the page's nid is in qp->nmask. * * If MPOL_MF_INVERT is set in qp->flags, check if the nid is * in the invert of qp->nmask. */ static inline bool queue_pages_required(struct page *page, struct queue_pages *qp) { int nid = page_to_nid(page); unsigned long flags = qp->flags; return node_isset(nid, *qp->nmask) == !(flags & MPOL_MF_INVERT); } /* * queue_pages_pmd() has four possible return values: * 0 - pages are placed on the right node or queued successfully. * 1 - there is unmovable page, and MPOL_MF_MOVE* & MPOL_MF_STRICT were * specified. * 2 - THP was split. * -EIO - is migration entry or only MPOL_MF_STRICT was specified and an * existing page was already on a node that does not follow the * policy. */ static int queue_pages_pmd(pmd_t *pmd, spinlock_t *ptl, unsigned long addr, unsigned long end, struct mm_walk *walk) { int ret = 0; struct page *page; struct queue_pages *qp = walk->private; unsigned long flags; if (unlikely(is_pmd_migration_entry(*pmd))) { ret = -EIO; goto unlock; } page = pmd_page(*pmd); if (is_huge_zero_page(page)) { spin_unlock(ptl); __split_huge_pmd(walk->vma, pmd, addr, false, NULL); ret = 2; goto out; } if (!queue_pages_required(page, qp)) goto unlock; flags = qp->flags; /* go to thp migration */ if (flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)) { if (!vma_migratable(walk->vma) || migrate_page_add(page, qp->pagelist, flags)) { ret = 1; goto unlock; } } else ret = -EIO; unlock: spin_unlock(ptl); out: return ret; } /* * Scan through pages checking if pages follow certain conditions, * and move them to the pagelist if they do. * * queue_pages_pte_range() has three possible return values: * 0 - pages are placed on the right node or queued successfully. * 1 - there is unmovable page, and MPOL_MF_MOVE* & MPOL_MF_STRICT were * specified. * -EIO - only MPOL_MF_STRICT was specified and an existing page was already * on a node that does not follow the policy. */ static int queue_pages_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end, struct mm_walk *walk) { struct vm_area_struct *vma = walk->vma; struct page *page; struct queue_pages *qp = walk->private; unsigned long flags = qp->flags; int ret; bool has_unmovable = false; pte_t *pte; spinlock_t *ptl; ptl = pmd_trans_huge_lock(pmd, vma); if (ptl) { ret = queue_pages_pmd(pmd, ptl, addr, end, walk); if (ret != 2) return ret; } /* THP was split, fall through to pte walk */ if (pmd_trans_unstable(pmd)) return 0; pte = pte_offset_map_lock(walk->mm, pmd, addr, &ptl); for (; addr != end; pte++, addr += PAGE_SIZE) { if (!pte_present(*pte)) continue; page = vm_normal_page(vma, addr, *pte); if (!page) continue; /* * vm_normal_page() filters out zero pages, but there might * still be PageReserved pages to skip, perhaps in a VDSO. */ if (PageReserved(page)) continue; if (!queue_pages_required(page, qp)) continue; if (flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)) { /* MPOL_MF_STRICT must be specified if we get here */ if (!vma_migratable(vma)) { has_unmovable = true; break; } /* * Do not abort immediately since there may be * temporary off LRU pages in the range. Still * need migrate other LRU pages. */ if (migrate_page_add(page, qp->pagelist, flags)) has_unmovable = true; } else break; } pte_unmap_unlock(pte - 1, ptl); cond_resched(); if (has_unmovable) return 1; return addr != end ? -EIO : 0; } static int queue_pages_hugetlb(pte_t *pte, unsigned long hmask, unsigned long addr, unsigned long end, struct mm_walk *walk) { int ret = 0; #ifdef CONFIG_HUGETLB_PAGE struct queue_pages *qp = walk->private; unsigned long flags = (qp->flags & MPOL_MF_VALID); struct page *page; spinlock_t *ptl; pte_t entry; ptl = huge_pte_lock(hstate_vma(walk->vma), walk->mm, pte); entry = huge_ptep_get(pte); if (!pte_present(entry)) goto unlock; page = pte_page(entry); if (!queue_pages_required(page, qp)) goto unlock; if (flags == MPOL_MF_STRICT) { /* * STRICT alone means only detecting misplaced page and no * need to further check other vma. */ ret = -EIO; goto unlock; } if (!vma_migratable(walk->vma)) { /* * Must be STRICT with MOVE*, otherwise .test_walk() have * stopped walking current vma. * Detecting misplaced page but allow migrating pages which * have been queued. */ ret = 1; goto unlock; } /* With MPOL_MF_MOVE, we migrate only unshared hugepage. */ if (flags & (MPOL_MF_MOVE_ALL) || (flags & MPOL_MF_MOVE && page_mapcount(page) == 1)) { if (!isolate_huge_page(page, qp->pagelist) && (flags & MPOL_MF_STRICT)) /* * Failed to isolate page but allow migrating pages * which have been queued. */ ret = 1; } unlock: spin_unlock(ptl); #else BUG(); #endif return ret; } #ifdef CONFIG_NUMA_BALANCING /* * This is used to mark a range of virtual addresses to be inaccessible. * These are later cleared by a NUMA hinting fault. Depending on these * faults, pages may be migrated for better NUMA placement. * * This is assuming that NUMA faults are handled using PROT_NONE. If * an architecture makes a different choice, it will need further * changes to the core. */ unsigned long change_prot_numa(struct vm_area_struct *vma, unsigned long addr, unsigned long end) { int nr_updated; nr_updated = change_protection(vma, addr, end, PAGE_NONE, 0, 1); if (nr_updated) count_vm_numa_events(NUMA_PTE_UPDATES, nr_updated); return nr_updated; } #else static unsigned long change_prot_numa(struct vm_area_struct *vma, unsigned long addr, unsigned long end) { return 0; } #endif /* CONFIG_NUMA_BALANCING */ static int queue_pages_test_walk(unsigned long start, unsigned long end, struct mm_walk *walk) { struct vm_area_struct *vma = walk->vma; struct queue_pages *qp = walk->private; unsigned long endvma = vma->vm_end; unsigned long flags = qp->flags; /* range check first */ VM_BUG_ON_VMA((vma->vm_start > start) || (vma->vm_end < end), vma); if (!qp->first) { qp->first = vma; if (!(flags & MPOL_MF_DISCONTIG_OK) && (qp->start < vma->vm_start)) /* hole at head side of range */ return -EFAULT; } if (!(flags & MPOL_MF_DISCONTIG_OK) && ((vma->vm_end < qp->end) && (!vma->vm_next || vma->vm_end < vma->vm_next->vm_start))) /* hole at middle or tail of range */ return -EFAULT; /* * Need check MPOL_MF_STRICT to return -EIO if possible * regardless of vma_migratable */ if (!vma_migratable(vma) && !(flags & MPOL_MF_STRICT)) return 1; if (endvma > end) endvma = end; if (flags & MPOL_MF_LAZY) { /* Similar to task_numa_work, skip inaccessible VMAs */ if (!is_vm_hugetlb_page(vma) && (vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE)) && !(vma->vm_flags & VM_MIXEDMAP)) change_prot_numa(vma, start, endvma); return 1; } /* queue pages from current vma */ if (flags & MPOL_MF_VALID) return 0; return 1; } static const struct mm_walk_ops queue_pages_walk_ops = { .hugetlb_entry = queue_pages_hugetlb, .pmd_entry = queue_pages_pte_range, .test_walk = queue_pages_test_walk, }; /* * Walk through page tables and collect pages to be migrated. * * If pages found in a given range are on a set of nodes (determined by * @nodes and @flags,) it's isolated and queued to the pagelist which is * passed via @private. * * queue_pages_range() has three possible return values: * 1 - there is unmovable page, but MPOL_MF_MOVE* & MPOL_MF_STRICT were * specified. * 0 - queue pages successfully or no misplaced page. * errno - i.e. misplaced pages with MPOL_MF_STRICT specified (-EIO) or * memory range specified by nodemask and maxnode points outside * your accessible address space (-EFAULT) */ static int queue_pages_range(struct mm_struct *mm, unsigned long start, unsigned long end, nodemask_t *nodes, unsigned long flags, struct list_head *pagelist) { int err; struct queue_pages qp = { .pagelist = pagelist, .flags = flags, .nmask = nodes, .start = start, .end = end, .first = NULL, }; err = walk_page_range(mm, start, end, &queue_pages_walk_ops, &qp); if (!qp.first) /* whole range in hole */ err = -EFAULT; return err; } /* * Apply policy to a single VMA * This must be called with the mmap_sem held for writing. */ static int vma_replace_policy(struct vm_area_struct *vma, struct mempolicy *pol) { int err; struct mempolicy *old; struct mempolicy *new; pr_debug("vma %lx-%lx/%lx vm_ops %p vm_file %p set_policy %p\n", vma->vm_start, vma->vm_end, vma->vm_pgoff, vma->vm_ops, vma->vm_file, vma->vm_ops ? vma->vm_ops->set_policy : NULL); new = mpol_dup(pol); if (IS_ERR(new)) return PTR_ERR(new); if (vma->vm_ops && vma->vm_ops->set_policy) { err = vma->vm_ops->set_policy(vma, new); if (err) goto err_out; } old = vma->vm_policy; vma->vm_policy = new; /* protected by mmap_sem */ mpol_put(old); return 0; err_out: mpol_put(new); return err; } /* Step 2: apply policy to a range and do splits. */ static int mbind_range(struct mm_struct *mm, unsigned long start, unsigned long end, struct mempolicy *new_pol) { struct vm_area_struct *next; struct vm_area_struct *prev; struct vm_area_struct *vma; int err = 0; pgoff_t pgoff; unsigned long vmstart; unsigned long vmend; vma = find_vma(mm, start); VM_BUG_ON(!vma); prev = vma->vm_prev; if (start > vma->vm_start) prev = vma; for (; vma && vma->vm_start < end; prev = vma, vma = next) { next = vma->vm_next; vmstart = max(start, vma->vm_start); vmend = min(end, vma->vm_end); if (mpol_equal(vma_policy(vma), new_pol)) continue; pgoff = vma->vm_pgoff + ((vmstart - vma->vm_start) >> PAGE_SHIFT); prev = vma_merge(mm, prev, vmstart, vmend, vma->vm_flags, vma->anon_vma, vma->vm_file, pgoff, new_pol, vma->vm_userfaultfd_ctx); if (prev) { vma = prev; next = vma->vm_next; if (mpol_equal(vma_policy(vma), new_pol)) continue; /* vma_merge() joined vma && vma->next, case 8 */ goto replace; } if (vma->vm_start != vmstart) { err = split_vma(vma->vm_mm, vma, vmstart, 1); if (err) goto out; } if (vma->vm_end != vmend) { err = split_vma(vma->vm_mm, vma, vmend, 0); if (err) goto out; } replace: err = vma_replace_policy(vma, new_pol); if (err) goto out; } out: return err; } /* Set the process memory policy */ static long do_set_mempolicy(unsigned short mode, unsigned short flags, nodemask_t *nodes) { struct mempolicy *new, *old; NODEMASK_SCRATCH(scratch); int ret; if (!scratch) return -ENOMEM; new = mpol_new(mode, flags, nodes); if (IS_ERR(new)) { ret = PTR_ERR(new); goto out; } task_lock(current); ret = mpol_set_nodemask(new, nodes, scratch); if (ret) { task_unlock(current); mpol_put(new); goto out; } old = current->mempolicy; current->mempolicy = new; if (new && new->mode == MPOL_INTERLEAVE) current->il_prev = MAX_NUMNODES-1; task_unlock(current); mpol_put(old); ret = 0; out: NODEMASK_SCRATCH_FREE(scratch); return ret; } /* * Return nodemask for policy for get_mempolicy() query * * Called with task's alloc_lock held */ static void get_policy_nodemask(struct mempolicy *p, nodemask_t *nodes) { nodes_clear(*nodes); if (p == &default_policy) return; switch (p->mode) { case MPOL_BIND: /* Fall through */ case MPOL_INTERLEAVE: *nodes = p->v.nodes; break; case MPOL_PREFERRED: if (!(p->flags & MPOL_F_LOCAL)) node_set(p->v.preferred_node, *nodes); /* else return empty node mask for local allocation */ break; default: BUG(); } } static int lookup_node(struct mm_struct *mm, unsigned long addr) { struct page *p; int err; int locked = 1; err = get_user_pages_locked(addr & PAGE_MASK, 1, 0, &p, &locked); if (err >= 0) { err = page_to_nid(p); put_page(p); } if (locked) up_read(&mm->mmap_sem); return err; } /* Retrieve NUMA policy */ static long do_get_mempolicy(int *policy, nodemask_t *nmask, unsigned long addr, unsigned long flags) { int err; struct mm_struct *mm = current->mm; struct vm_area_struct *vma = NULL; struct mempolicy *pol = current->mempolicy, *pol_refcount = NULL; if (flags & ~(unsigned long)(MPOL_F_NODE|MPOL_F_ADDR|MPOL_F_MEMS_ALLOWED)) return -EINVAL; if (flags & MPOL_F_MEMS_ALLOWED) { if (flags & (MPOL_F_NODE|MPOL_F_ADDR)) return -EINVAL; *policy = 0; /* just so it's initialized */ task_lock(current); *nmask = cpuset_current_mems_allowed; task_unlock(current); return 0; } if (flags & MPOL_F_ADDR) { /* * Do NOT fall back to task policy if the * vma/shared policy at addr is NULL. We * want to return MPOL_DEFAULT in this case. */ down_read(&mm->mmap_sem); vma = find_vma_intersection(mm, addr, addr+1); if (!vma) { up_read(&mm->mmap_sem); return -EFAULT; } if (vma->vm_ops && vma->vm_ops->get_policy) pol = vma->vm_ops->get_policy(vma, addr); else pol = vma->vm_policy; } else if (addr) return -EINVAL; if (!pol) pol = &default_policy; /* indicates default behavior */ if (flags & MPOL_F_NODE) { if (flags & MPOL_F_ADDR) { /* * Take a refcount on the mpol, lookup_node() * wil drop the mmap_sem, so after calling * lookup_node() only "pol" remains valid, "vma" * is stale. */ pol_refcount = pol; vma = NULL; mpol_get(pol); err = lookup_node(mm, addr); if (err < 0) goto out; *policy = err; } else if (pol == current->mempolicy && pol->mode == MPOL_INTERLEAVE) { *policy = next_node_in(current->il_prev, pol->v.nodes); } else { err = -EINVAL; goto out; } } else { *policy = pol == &default_policy ? MPOL_DEFAULT : pol->mode; /* * Internal mempolicy flags must be masked off before exposing * the policy to userspace. */ *policy |= (pol->flags & MPOL_MODE_FLAGS); } err = 0; if (nmask) { if (mpol_store_user_nodemask(pol)) { *nmask = pol->w.user_nodemask; } else { task_lock(current); get_policy_nodemask(pol, nmask); task_unlock(current); } } out: mpol_cond_put(pol); if (vma) up_read(&mm->mmap_sem); if (pol_refcount) mpol_put(pol_refcount); return err; } #ifdef CONFIG_MIGRATION /* * page migration, thp tail pages can be passed. */ static int migrate_page_add(struct page *page, struct list_head *pagelist, unsigned long flags) { struct page *head = compound_head(page); /* * Avoid migrating a page that is shared with others. */ if ((flags & MPOL_MF_MOVE_ALL) || page_mapcount(head) == 1) { if (!isolate_lru_page(head)) { list_add_tail(&head->lru, pagelist); mod_node_page_state(page_pgdat(head), NR_ISOLATED_ANON + page_is_file_cache(head), hpage_nr_pages(head)); } else if (flags & MPOL_MF_STRICT) { /* * Non-movable page may reach here. And, there may be * temporary off LRU pages or non-LRU movable pages. * Treat them as unmovable pages since they can't be * isolated, so they can't be moved at the moment. It * should return -EIO for this case too. */ return -EIO; } } return 0; } /* page allocation callback for NUMA node migration */ struct page *alloc_new_node_page(struct page *page, unsigned long node) { if (PageHuge(page)) return alloc_huge_page_node(page_hstate(compound_head(page)), node); else if (PageTransHuge(page)) { struct page *thp; thp = alloc_pages_node(node, (GFP_TRANSHUGE | __GFP_THISNODE), HPAGE_PMD_ORDER); if (!thp) return NULL; prep_transhuge_page(thp); return thp; } else return __alloc_pages_node(node, GFP_HIGHUSER_MOVABLE | __GFP_THISNODE, 0); } /* * Migrate pages from one node to a target node. * Returns error or the number of pages not migrated. */ static int migrate_to_node(struct mm_struct *mm, int source, int dest, int flags) { nodemask_t nmask; LIST_HEAD(pagelist); int err = 0; nodes_clear(nmask); node_set(source, nmask); /* * This does not "check" the range but isolates all pages that * need migration. Between passing in the full user address * space range and MPOL_MF_DISCONTIG_OK, this call can not fail. */ VM_BUG_ON(!(flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL))); queue_pages_range(mm, mm->mmap->vm_start, mm->task_size, &nmask, flags | MPOL_MF_DISCONTIG_OK, &pagelist); if (!list_empty(&pagelist)) { err = migrate_pages(&pagelist, alloc_new_node_page, NULL, dest, MIGRATE_SYNC, MR_SYSCALL); if (err) putback_movable_pages(&pagelist); } return err; } /* * Move pages between the two nodesets so as to preserve the physical * layout as much as possible. * * Returns the number of page that could not be moved. */ int do_migrate_pages(struct mm_struct *mm, const nodemask_t *from, const nodemask_t *to, int flags) { int busy = 0; int err; nodemask_t tmp; err = migrate_prep(); if (err) return err; down_read(&mm->mmap_sem); /* * Find a 'source' bit set in 'tmp' whose corresponding 'dest' * bit in 'to' is not also set in 'tmp'. Clear the found 'source' * bit in 'tmp', and return that <source, dest> pair for migration. * The pair of nodemasks 'to' and 'from' define the map. * * If no pair of bits is found that way, fallback to picking some * pair of 'source' and 'dest' bits that are not the same. If the * 'source' and 'dest' bits are the same, this represents a node * that will be migrating to itself, so no pages need move. * * If no bits are left in 'tmp', or if all remaining bits left * in 'tmp' correspond to the same bit in 'to', return false * (nothing left to migrate). * * This lets us pick a pair of nodes to migrate between, such that * if possible the dest node is not already occupied by some other * source node, minimizing the risk of overloading the memory on a * node that would happen if we migrated incoming memory to a node * before migrating outgoing memory source that same node. * * A single scan of tmp is sufficient. As we go, we remember the * most recent <s, d> pair that moved (s != d). If we find a pair * that not only moved, but what's better, moved to an empty slot * (d is not set in tmp), then we break out then, with that pair. * Otherwise when we finish scanning from_tmp, we at least have the * most recent <s, d> pair that moved. If we get all the way through * the scan of tmp without finding any node that moved, much less * moved to an empty node, then there is nothing left worth migrating. */ tmp = *from; while (!nodes_empty(tmp)) { int s,d; int source = NUMA_NO_NODE; int dest = 0; for_each_node_mask(s, tmp) { /* * do_migrate_pages() tries to maintain the relative * node relationship of the pages established between * threads and memory areas. * * However if the number of source nodes is not equal to * the number of destination nodes we can not preserve * this node relative relationship. In that case, skip * copying memory from a node that is in the destination * mask. * * Example: [2,3,4] -> [3,4,5] moves everything. * [0-7] - > [3,4,5] moves only 0,1,2,6,7. */ if ((nodes_weight(*from) != nodes_weight(*to)) && (node_isset(s, *to))) continue; d = node_remap(s, *from, *to); if (s == d) continue; source = s; /* Node moved. Memorize */ dest = d; /* dest not in remaining from nodes? */ if (!node_isset(dest, tmp)) break; } if (source == NUMA_NO_NODE) break; node_clear(source, tmp); err = migrate_to_node(mm, source, dest, flags); if (err > 0) busy += err; if (err < 0) break; } up_read(&mm->mmap_sem); if (err < 0) return err; return busy; } /* * Allocate a new page for page migration based on vma policy. * Start by assuming the page is mapped by the same vma as contains @start. * Search forward from there, if not. N.B., this assumes that the * list of pages handed to migrate_pages()--which is how we get here-- * is in virtual address order. */ static struct page *new_page(struct page *page, unsigned long start) { struct vm_area_struct *vma; unsigned long uninitialized_var(address); vma = find_vma(current->mm, start); while (vma) { address = page_address_in_vma(page, vma); if (address != -EFAULT) break; vma = vma->vm_next; } if (PageHuge(page)) { return alloc_huge_page_vma(page_hstate(compound_head(page)), vma, address); } else if (PageTransHuge(page)) { struct page *thp; thp = alloc_hugepage_vma(GFP_TRANSHUGE, vma, address, HPAGE_PMD_ORDER); if (!thp) return NULL; prep_transhuge_page(thp); return thp; } /* * if !vma, alloc_page_vma() will use task or system default policy */ return alloc_page_vma(GFP_HIGHUSER_MOVABLE | __GFP_RETRY_MAYFAIL, vma, address); } #else static int migrate_page_add(struct page *page, struct list_head *pagelist, unsigned long flags) { return -EIO; } int do_migrate_pages(struct mm_struct *mm, const nodemask_t *from, const nodemask_t *to, int flags) { return -ENOSYS; } static struct page *new_page(struct page *page, unsigned long start) { return NULL; } #endif static long do_mbind(unsigned long start, unsigned long len, unsigned short mode, unsigned short mode_flags, nodemask_t *nmask, unsigned long flags) { struct mm_struct *mm = current->mm; struct mempolicy *new; unsigned long end; int err; int ret; LIST_HEAD(pagelist); if (flags & ~(unsigned long)MPOL_MF_VALID) return -EINVAL; if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE)) return -EPERM; if (start & ~PAGE_MASK) return -EINVAL; if (mode == MPOL_DEFAULT) flags &= ~MPOL_MF_STRICT; len = (len + PAGE_SIZE - 1) & PAGE_MASK; end = start + len; if (end < start) return -EINVAL; if (end == start) return 0; new = mpol_new(mode, mode_flags, nmask); if (IS_ERR(new)) return PTR_ERR(new); if (flags & MPOL_MF_LAZY) new->flags |= MPOL_F_MOF; /* * If we are using the default policy then operation * on discontinuous address spaces is okay after all */ if (!new) flags |= MPOL_MF_DISCONTIG_OK; pr_debug("mbind %lx-%lx mode:%d flags:%d nodes:%lx\n", start, start + len, mode, mode_flags, nmask ? nodes_addr(*nmask)[0] : NUMA_NO_NODE); if (flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)) { err = migrate_prep(); if (err) goto mpol_out; } { NODEMASK_SCRATCH(scratch); if (scratch) { down_write(&mm->mmap_sem); task_lock(current); err = mpol_set_nodemask(new, nmask, scratch); task_unlock(current); if (err) up_write(&mm->mmap_sem); } else err = -ENOMEM; NODEMASK_SCRATCH_FREE(scratch); } if (err) goto mpol_out; ret = queue_pages_range(mm, start, end, nmask, flags | MPOL_MF_INVERT, &pagelist); if (ret < 0) { err = ret; goto up_out; } err = mbind_range(mm, start, end, new); if (!err) { int nr_failed = 0; if (!list_empty(&pagelist)) { WARN_ON_ONCE(flags & MPOL_MF_LAZY); nr_failed = migrate_pages(&pagelist, new_page, NULL, start, MIGRATE_SYNC, MR_MEMPOLICY_MBIND); if (nr_failed) putback_movable_pages(&pagelist); } if ((ret > 0) || (nr_failed && (flags & MPOL_MF_STRICT))) err = -EIO; } else { up_out: if (!list_empty(&pagelist)) putback_movable_pages(&pagelist); } up_write(&mm->mmap_sem); mpol_out: mpol_put(new); return err; } /* * User space interface with variable sized bitmaps for nodelists. */ /* Copy a node mask from user space. */ static int get_nodes(nodemask_t *nodes, const unsigned long __user *nmask, unsigned long maxnode) { unsigned long k; unsigned long t; unsigned long nlongs; unsigned long endmask; --maxnode; nodes_clear(*nodes); if (maxnode == 0 || !nmask) return 0; if (maxnode > PAGE_SIZE*BITS_PER_BYTE) return -EINVAL; nlongs = BITS_TO_LONGS(maxnode); if ((maxnode % BITS_PER_LONG) == 0) endmask = ~0UL; else endmask = (1UL << (maxnode % BITS_PER_LONG)) - 1; /* * When the user specified more nodes than supported just check * if the non supported part is all zero. * * If maxnode have more longs than MAX_NUMNODES, check * the bits in that area first. And then go through to * check the rest bits which equal or bigger than MAX_NUMNODES. * Otherwise, just check bits [MAX_NUMNODES, maxnode). */ if (nlongs > BITS_TO_LONGS(MAX_NUMNODES)) { for (k = BITS_TO_LONGS(MAX_NUMNODES); k < nlongs; k++) { if (get_user(t, nmask + k)) return -EFAULT; if (k == nlongs - 1) { if (t & endmask) return -EINVAL; } else if (t) return -EINVAL; } nlongs = BITS_TO_LONGS(MAX_NUMNODES); endmask = ~0UL; } if (maxnode > MAX_NUMNODES && MAX_NUMNODES % BITS_PER_LONG != 0) { unsigned long valid_mask = endmask; valid_mask &= ~((1UL << (MAX_NUMNODES % BITS_PER_LONG)) - 1); if (get_user(t, nmask + nlongs - 1)) return -EFAULT; if (t & valid_mask) return -EINVAL; } if (copy_from_user(nodes_addr(*nodes), nmask, nlongs*sizeof(unsigned long))) return -EFAULT; nodes_addr(*nodes)[nlongs-1] &= endmask; return 0; } /* Copy a kernel node mask to user space */ static int copy_nodes_to_user(unsigned long __user *mask, unsigned long maxnode, nodemask_t *nodes) { unsigned long copy = ALIGN(maxnode-1, 64) / 8; unsigned int nbytes = BITS_TO_LONGS(nr_node_ids) * sizeof(long); if (copy > nbytes) { if (copy > PAGE_SIZE) return -EINVAL; if (clear_user((char __user *)mask + nbytes, copy - nbytes)) return -EFAULT; copy = nbytes; } return copy_to_user(mask, nodes_addr(*nodes), copy) ? -EFAULT : 0; } static long kernel_mbind(unsigned long start, unsigned long len, unsigned long mode, const unsigned long __user *nmask, unsigned long maxnode, unsigned int flags) { nodemask_t nodes; int err; unsigned short mode_flags; start = untagged_addr(start); mode_flags = mode & MPOL_MODE_FLAGS; mode &= ~MPOL_MODE_FLAGS; if (mode >= MPOL_MAX) return -EINVAL; if ((mode_flags & MPOL_F_STATIC_NODES) && (mode_flags & MPOL_F_RELATIVE_NODES)) return -EINVAL; err = get_nodes(&nodes, nmask, maxnode); if (err) return err; return do_mbind(start, len, mode, mode_flags, &nodes, flags); } SYSCALL_DEFINE6(mbind, unsigned long, start, unsigned long, len, unsigned long, mode, const unsigned long __user *, nmask, unsigned long, maxnode, unsigned int, flags) { return kernel_mbind(start, len, mode, nmask, maxnode, flags); } /* Set the process memory policy */ static long kernel_set_mempolicy(int mode, const unsigned long __user *nmask, unsigned long maxnode) { int err; nodemask_t nodes; unsigned short flags; flags = mode & MPOL_MODE_FLAGS; mode &= ~MPOL_MODE_FLAGS; if ((unsigned int)mode >= MPOL_MAX) return -EINVAL; if ((flags & MPOL_F_STATIC_NODES) && (flags & MPOL_F_RELATIVE_NODES)) return -EINVAL; err = get_nodes(&nodes, nmask, maxnode); if (err) return err; return do_set_mempolicy(mode, flags, &nodes); } SYSCALL_DEFINE3(set_mempolicy, int, mode, const unsigned long __user *, nmask, unsigned long, maxnode) { return kernel_set_mempolicy(mode, nmask, maxnode); } static int kernel_migrate_pages(pid_t pid, unsigned long maxnode, const unsigned long __user *old_nodes, const unsigned long __user *new_nodes) { struct mm_struct *mm = NULL; struct task_struct *task; nodemask_t task_nodes; int err; nodemask_t *old; nodemask_t *new; NODEMASK_SCRATCH(scratch); if (!scratch) return -ENOMEM; old = &scratch->mask1; new = &scratch->mask2; err = get_nodes(old, old_nodes, maxnode); if (err) goto out; err = get_nodes(new, new_nodes, maxnode); if (err) goto out; /* Find the mm_struct */ rcu_read_lock(); task = pid ? find_task_by_vpid(pid) : current; if (!task) { rcu_read_unlock(); err = -ESRCH; goto out; } get_task_struct(task); err = -EINVAL; /* * Check if this process has the right to modify the specified process. * Use the regular "ptrace_may_access()" checks. */ if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) { rcu_read_unlock(); err = -EPERM; goto out_put; } rcu_read_unlock(); task_nodes = cpuset_mems_allowed(task); /* Is the user allowed to access the target nodes? */ if (!nodes_subset(*new, task_nodes) && !capable(CAP_SYS_NICE)) { err = -EPERM; goto out_put; } task_nodes = cpuset_mems_allowed(current); nodes_and(*new, *new, task_nodes); if (nodes_empty(*new)) goto out_put; err = security_task_movememory(task); if (err) goto out_put; mm = get_task_mm(task); put_task_struct(task); if (!mm) { err = -EINVAL; goto out; } err = do_migrate_pages(mm, old, new, capable(CAP_SYS_NICE) ? MPOL_MF_MOVE_ALL : MPOL_MF_MOVE); mmput(mm); out: NODEMASK_SCRATCH_FREE(scratch); return err; out_put: put_task_struct(task); goto out; } SYSCALL_DEFINE4(migrate_pages, pid_t, pid, unsigned long, maxnode, const unsigned long __user *, old_nodes, const unsigned long __user *, new_nodes) { return kernel_migrate_pages(pid, maxnode, old_nodes, new_nodes); } /* Retrieve NUMA policy */ static int kernel_get_mempolicy(int __user *policy, unsigned long __user *nmask, unsigned long maxnode, unsigned long addr, unsigned long flags) { int err; int uninitialized_var(pval); nodemask_t nodes; addr = untagged_addr(addr); if (nmask != NULL && maxnode < nr_node_ids) return -EINVAL; err = do_get_mempolicy(&pval, &nodes, addr, flags); if (err) return err; if (policy && put_user(pval, policy)) return -EFAULT; if (nmask) err = copy_nodes_to_user(nmask, maxnode, &nodes); return err; } SYSCALL_DEFINE5(get_mempolicy, int __user *, policy, unsigned long __user *, nmask, unsigned long, maxnode, unsigned long, addr, unsigned long, flags) { return kernel_get_mempolicy(policy, nmask, maxnode, addr, flags); } #ifdef CONFIG_COMPAT COMPAT_SYSCALL_DEFINE5(get_mempolicy, int __user *, policy, compat_ulong_t __user *, nmask, compat_ulong_t, maxnode, compat_ulong_t, addr, compat_ulong_t, flags) { long err; unsigned long __user *nm = NULL; unsigned long nr_bits, alloc_size; DECLARE_BITMAP(bm, MAX_NUMNODES); nr_bits = min_t(unsigned long, maxnode-1, nr_node_ids); alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8; if (nmask) nm = compat_alloc_user_space(alloc_size); err = kernel_get_mempolicy(policy, nm, nr_bits+1, addr, flags); if (!err && nmask) { unsigned long copy_size; copy_size = min_t(unsigned long, sizeof(bm), alloc_size); err = copy_from_user(bm, nm, copy_size); /* ensure entire bitmap is zeroed */ err |= clear_user(nmask, ALIGN(maxnode-1, 8) / 8); err |= compat_put_bitmap(nmask, bm, nr_bits); } return err; } COMPAT_SYSCALL_DEFINE3(set_mempolicy, int, mode, compat_ulong_t __user *, nmask, compat_ulong_t, maxnode) { unsigned long __user *nm = NULL; unsigned long nr_bits, alloc_size; DECLARE_BITMAP(bm, MAX_NUMNODES); nr_bits = min_t(unsigned long, maxnode-1, MAX_NUMNODES); alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8; if (nmask) { if (compat_get_bitmap(bm, nmask, nr_bits)) return -EFAULT; nm = compat_alloc_user_space(alloc_size); if (copy_to_user(nm, bm, alloc_size)) return -EFAULT; } return kernel_set_mempolicy(mode, nm, nr_bits+1); } COMPAT_SYSCALL_DEFINE6(mbind, compat_ulong_t, start, compat_ulong_t, len, compat_ulong_t, mode, compat_ulong_t __user *, nmask, compat_ulong_t, maxnode, compat_ulong_t, flags) { unsigned long __user *nm = NULL; unsigned long nr_bits, alloc_size; nodemask_t bm; nr_bits = min_t(unsigned long, maxnode-1, MAX_NUMNODES); alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8; if (nmask) { if (compat_get_bitmap(nodes_addr(bm), nmask, nr_bits)) return -EFAULT; nm = compat_alloc_user_space(alloc_size); if (copy_to_user(nm, nodes_addr(bm), alloc_size)) return -EFAULT; } return kernel_mbind(start, len, mode, nm, nr_bits+1, flags); } COMPAT_SYSCALL_DEFINE4(migrate_pages, compat_pid_t, pid, compat_ulong_t, maxnode, const compat_ulong_t __user *, old_nodes, const compat_ulong_t __user *, new_nodes) { unsigned long __user *old = NULL; unsigned long __user *new = NULL; nodemask_t tmp_mask; unsigned long nr_bits; unsigned long size; nr_bits = min_t(unsigned long, maxnode - 1, MAX_NUMNODES); size = ALIGN(nr_bits, BITS_PER_LONG) / 8; if (old_nodes) { if (compat_get_bitmap(nodes_addr(tmp_mask), old_nodes, nr_bits)) return -EFAULT; old = compat_alloc_user_space(new_nodes ? size * 2 : size); if (new_nodes) new = old + size / sizeof(unsigned long); if (copy_to_user(old, nodes_addr(tmp_mask), size)) return -EFAULT; } if (new_nodes) { if (compat_get_bitmap(nodes_addr(tmp_mask), new_nodes, nr_bits)) return -EFAULT; if (new == NULL) new = compat_alloc_user_space(size); if (copy_to_user(new, nodes_addr(tmp_mask), size)) return -EFAULT; } return kernel_migrate_pages(pid, nr_bits + 1, old, new); } #endif /* CONFIG_COMPAT */ bool vma_migratable(struct vm_area_struct *vma) { if (vma->vm_flags & (VM_IO | VM_PFNMAP)) return false; /* * DAX device mappings require predictable access latency, so avoid * incurring periodic faults. */ if (vma_is_dax(vma)) return false; if (is_vm_hugetlb_page(vma) && !hugepage_migration_supported(hstate_vma(vma))) return false; /* * Migration allocates pages in the highest zone. If we cannot * do so then migration (at least from node to node) is not * possible. */ if (vma->vm_file && gfp_zone(mapping_gfp_mask(vma->vm_file->f_mapping)) < policy_zone) return false; return true; } struct mempolicy *__get_vma_policy(struct vm_area_struct *vma, unsigned long addr) { struct mempolicy *pol = NULL; if (vma) { if (vma->vm_ops && vma->vm_ops->get_policy) { pol = vma->vm_ops->get_policy(vma, addr); } else if (vma->vm_policy) { pol = vma->vm_policy; /* * shmem_alloc_page() passes MPOL_F_SHARED policy with * a pseudo vma whose vma->vm_ops=NULL. Take a reference * count on these policies which will be dropped by * mpol_cond_put() later */ if (mpol_needs_cond_ref(pol)) mpol_get(pol); } } return pol; } /* * get_vma_policy(@vma, @addr) * @vma: virtual memory area whose policy is sought * @addr: address in @vma for shared policy lookup * * Returns effective policy for a VMA at specified address. * Falls back to current->mempolicy or system default policy, as necessary. * Shared policies [those marked as MPOL_F_SHARED] require an extra reference * count--added by the get_policy() vm_op, as appropriate--to protect against * freeing by another task. It is the caller's responsibility to free the * extra reference for shared policies. */ static struct mempolicy *get_vma_policy(struct vm_area_struct *vma, unsigned long addr) { struct mempolicy *pol = __get_vma_policy(vma, addr); if (!pol) pol = get_task_policy(current); return pol; } bool vma_policy_mof(struct vm_area_struct *vma) { struct mempolicy *pol; if (vma->vm_ops && vma->vm_ops->get_policy) { bool ret = false; pol = vma->vm_ops->get_policy(vma, vma->vm_start); if (pol && (pol->flags & MPOL_F_MOF)) ret = true; mpol_cond_put(pol); return ret; } pol = vma->vm_policy; if (!pol) pol = get_task_policy(current); return pol->flags & MPOL_F_MOF; } static int apply_policy_zone(struct mempolicy *policy, enum zone_type zone) { enum zone_type dynamic_policy_zone = policy_zone; BUG_ON(dynamic_policy_zone == ZONE_MOVABLE); /* * if policy->v.nodes has movable memory only, * we apply policy when gfp_zone(gfp) = ZONE_MOVABLE only. * * policy->v.nodes is intersect with node_states[N_MEMORY]. * so if the following test faile, it implies * policy->v.nodes has movable memory only. */ if (!nodes_intersects(policy->v.nodes, node_states[N_HIGH_MEMORY])) dynamic_policy_zone = ZONE_MOVABLE; return zone >= dynamic_policy_zone; } /* * Return a nodemask representing a mempolicy for filtering nodes for * page allocation */ static nodemask_t *policy_nodemask(gfp_t gfp, struct mempolicy *policy) { /* Lower zones don't get a nodemask applied for MPOL_BIND */ if (unlikely(policy->mode == MPOL_BIND) && apply_policy_zone(policy, gfp_zone(gfp)) && cpuset_nodemask_valid_mems_allowed(&policy->v.nodes)) return &policy->v.nodes; return NULL; } /* Return the node id preferred by the given mempolicy, or the given id */ static int policy_node(gfp_t gfp, struct mempolicy *policy, int nd) { if (policy->mode == MPOL_PREFERRED && !(policy->flags & MPOL_F_LOCAL)) nd = policy->v.preferred_node; else { /* * __GFP_THISNODE shouldn't even be used with the bind policy * because we might easily break the expectation to stay on the * requested node and not break the policy. */ WARN_ON_ONCE(policy->mode == MPOL_BIND && (gfp & __GFP_THISNODE)); } return nd; } /* Do dynamic interleaving for a process */ static unsigned interleave_nodes(struct mempolicy *policy) { unsigned next; struct task_struct *me = current; next = next_node_in(me->il_prev, policy->v.nodes); if (next < MAX_NUMNODES) me->il_prev = next; return next; } /* * Depending on the memory policy provide a node from which to allocate the * next slab entry. */ unsigned int mempolicy_slab_node(void) { struct mempolicy *policy; int node = numa_mem_id(); if (in_interrupt()) return node; policy = current->mempolicy; if (!policy || policy->flags & MPOL_F_LOCAL) return node; switch (policy->mode) { case MPOL_PREFERRED: /* * handled MPOL_F_LOCAL above */ return policy->v.preferred_node; case MPOL_INTERLEAVE: return interleave_nodes(policy); case MPOL_BIND: { struct zoneref *z; /* * Follow bind policy behavior and start allocation at the * first node. */ struct zonelist *zonelist; enum zone_type highest_zoneidx = gfp_zone(GFP_KERNEL); zonelist = &NODE_DATA(node)->node_zonelists[ZONELIST_FALLBACK]; z = first_zones_zonelist(zonelist, highest_zoneidx, &policy->v.nodes); return z->zone ? zone_to_nid(z->zone) : node; } default: BUG(); } } /* * Do static interleaving for a VMA with known offset @n. Returns the n'th * node in pol->v.nodes (starting from n=0), wrapping around if n exceeds the * number of present nodes. */ static unsigned offset_il_node(struct mempolicy *pol, unsigned long n) { unsigned nnodes = nodes_weight(pol->v.nodes); unsigned target; int i; int nid; if (!nnodes) return numa_node_id(); target = (unsigned int)n % nnodes; nid = first_node(pol->v.nodes); for (i = 0; i < target; i++) nid = next_node(nid, pol->v.nodes); return nid; } /* Determine a node number for interleave */ static inline unsigned interleave_nid(struct mempolicy *pol, struct vm_area_struct *vma, unsigned long addr, int shift) { if (vma) { unsigned long off; /* * for small pages, there is no difference between * shift and PAGE_SHIFT, so the bit-shift is safe. * for huge pages, since vm_pgoff is in units of small * pages, we need to shift off the always 0 bits to get * a useful offset. */ BUG_ON(shift < PAGE_SHIFT); off = vma->vm_pgoff >> (shift - PAGE_SHIFT); off += (addr - vma->vm_start) >> shift; return offset_il_node(pol, off); } else return interleave_nodes(pol); } #ifdef CONFIG_HUGETLBFS /* * huge_node(@vma, @addr, @gfp_flags, @mpol) * @vma: virtual memory area whose policy is sought * @addr: address in @vma for shared policy lookup and interleave policy * @gfp_flags: for requested zone * @mpol: pointer to mempolicy pointer for reference counted mempolicy * @nodemask: pointer to nodemask pointer for MPOL_BIND nodemask * * Returns a nid suitable for a huge page allocation and a pointer * to the struct mempolicy for conditional unref after allocation. * If the effective policy is 'BIND, returns a pointer to the mempolicy's * @nodemask for filtering the zonelist. * * Must be protected by read_mems_allowed_begin() */ int huge_node(struct vm_area_struct *vma, unsigned long addr, gfp_t gfp_flags, struct mempolicy **mpol, nodemask_t **nodemask) { int nid; *mpol = get_vma_policy(vma, addr); *nodemask = NULL; /* assume !MPOL_BIND */ if (unlikely((*mpol)->mode == MPOL_INTERLEAVE)) { nid = interleave_nid(*mpol, vma, addr, huge_page_shift(hstate_vma(vma))); } else { nid = policy_node(gfp_flags, *mpol, numa_node_id()); if ((*mpol)->mode == MPOL_BIND) *nodemask = &(*mpol)->v.nodes; } return nid; } /* * init_nodemask_of_mempolicy * * If the current task's mempolicy is "default" [NULL], return 'false' * to indicate default policy. Otherwise, extract the policy nodemask * for 'bind' or 'interleave' policy into the argument nodemask, or * initialize the argument nodemask to contain the single node for * 'preferred' or 'local' policy and return 'true' to indicate presence * of non-default mempolicy. * * We don't bother with reference counting the mempolicy [mpol_get/put] * because the current task is examining it's own mempolicy and a task's * mempolicy is only ever changed by the task itself. * * N.B., it is the caller's responsibility to free a returned nodemask. */ bool init_nodemask_of_mempolicy(nodemask_t *mask) { struct mempolicy *mempolicy; int nid; if (!(mask && current->mempolicy)) return false; task_lock(current); mempolicy = current->mempolicy; switch (mempolicy->mode) { case MPOL_PREFERRED: if (mempolicy->flags & MPOL_F_LOCAL) nid = numa_node_id(); else nid = mempolicy->v.preferred_node; init_nodemask_of_node(mask, nid); break; case MPOL_BIND: /* Fall through */ case MPOL_INTERLEAVE: *mask = mempolicy->v.nodes; break; default: BUG(); } task_unlock(current); return true; } #endif /* * mempolicy_nodemask_intersects * * If tsk's mempolicy is "default" [NULL], return 'true' to indicate default * policy. Otherwise, check for intersection between mask and the policy * nodemask for 'bind' or 'interleave' policy. For 'perferred' or 'local' * policy, always return true since it may allocate elsewhere on fallback. * * Takes task_lock(tsk) to prevent freeing of its mempolicy. */ bool mempolicy_nodemask_intersects(struct task_struct *tsk, const nodemask_t *mask) { struct mempolicy *mempolicy; bool ret = true; if (!mask) return ret; task_lock(tsk); mempolicy = tsk->mempolicy; if (!mempolicy) goto out; switch (mempolicy->mode) { case MPOL_PREFERRED: /* * MPOL_PREFERRED and MPOL_F_LOCAL are only preferred nodes to * allocate from, they may fallback to other nodes when oom. * Thus, it's possible for tsk to have allocated memory from * nodes in mask. */ break; case MPOL_BIND: case MPOL_INTERLEAVE: ret = nodes_intersects(mempolicy->v.nodes, *mask); break; default: BUG(); } out: task_unlock(tsk); return ret; } /* Allocate a page in interleaved policy. Own path because it needs to do special accounting. */ static struct page *alloc_page_interleave(gfp_t gfp, unsigned order, unsigned nid) { struct page *page; page = __alloc_pages(gfp, order, nid); /* skip NUMA_INTERLEAVE_HIT counter update if numa stats is disabled */ if (!static_branch_likely(&vm_numa_stat_key)) return page; if (page && page_to_nid(page) == nid) { preempt_disable(); __inc_numa_state(page_zone(page), NUMA_INTERLEAVE_HIT); preempt_enable(); } return page; } /** * alloc_pages_vma - Allocate a page for a VMA. * * @gfp: * %GFP_USER user allocation. * %GFP_KERNEL kernel allocations, * %GFP_HIGHMEM highmem/user allocations, * %GFP_FS allocation should not call back into a file system. * %GFP_ATOMIC don't sleep. * * @order:Order of the GFP allocation. * @vma: Pointer to VMA or NULL if not available. * @addr: Virtual Address of the allocation. Must be inside the VMA. * @node: Which node to prefer for allocation (modulo policy). * @hugepage: for hugepages try only the preferred node if possible * * This function allocates a page from the kernel page pool and applies * a NUMA policy associated with the VMA or the current process. * When VMA is not NULL caller must hold down_read on the mmap_sem of the * mm_struct of the VMA to prevent it from going away. Should be used for * all allocations for pages that will be mapped into user space. Returns * NULL when no page can be allocated. */ struct page * alloc_pages_vma(gfp_t gfp, int order, struct vm_area_struct *vma, unsigned long addr, int node, bool hugepage) { struct mempolicy *pol; struct page *page; int preferred_nid; nodemask_t *nmask; pol = get_vma_policy(vma, addr); if (pol->mode == MPOL_INTERLEAVE) { unsigned nid; nid = interleave_nid(pol, vma, addr, PAGE_SHIFT + order); mpol_cond_put(pol); page = alloc_page_interleave(gfp, order, nid); goto out; } if (unlikely(IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) && hugepage)) { int hpage_node = node; /* * For hugepage allocation and non-interleave policy which * allows the current node (or other explicitly preferred * node) we only try to allocate from the current/preferred * node and don't fall back to other nodes, as the cost of * remote accesses would likely offset THP benefits. * * If the policy is interleave, or does not allow the current * node in its nodemask, we allocate the standard way. */ if (pol->mode == MPOL_PREFERRED && !(pol->flags & MPOL_F_LOCAL)) hpage_node = pol->v.preferred_node; nmask = policy_nodemask(gfp, pol); if (!nmask || node_isset(hpage_node, *nmask)) { mpol_cond_put(pol); /* * First, try to allocate THP only on local node, but * don't reclaim unnecessarily, just compact. */ page = __alloc_pages_node(hpage_node, gfp | __GFP_THISNODE | __GFP_NORETRY, order); /* * If hugepage allocations are configured to always * synchronous compact or the vma has been madvised * to prefer hugepage backing, retry allowing remote * memory with both reclaim and compact as well. */ if (!page && (gfp & __GFP_DIRECT_RECLAIM)) page = __alloc_pages_node(hpage_node, gfp, order); goto out; } } nmask = policy_nodemask(gfp, pol); preferred_nid = policy_node(gfp, pol, node); page = __alloc_pages_nodemask(gfp, order, preferred_nid, nmask); mpol_cond_put(pol); out: return page; } EXPORT_SYMBOL(alloc_pages_vma); /** * alloc_pages_current - Allocate pages. * * @gfp: * %GFP_USER user allocation, * %GFP_KERNEL kernel allocation, * %GFP_HIGHMEM highmem allocation, * %GFP_FS don't call back into a file system. * %GFP_ATOMIC don't sleep. * @order: Power of two of allocation size in pages. 0 is a single page. * * Allocate a page from the kernel page pool. When not in * interrupt context and apply the current process NUMA policy. * Returns NULL when no page can be allocated. */ struct page *alloc_pages_current(gfp_t gfp, unsigned order) { struct mempolicy *pol = &default_policy; struct page *page; if (!in_interrupt() && !(gfp & __GFP_THISNODE)) pol = get_task_policy(current); /* * No reference counting needed for current->mempolicy * nor system default_policy */ if (pol->mode == MPOL_INTERLEAVE) page = alloc_page_interleave(gfp, order, interleave_nodes(pol)); else page = __alloc_pages_nodemask(gfp, order, policy_node(gfp, pol, numa_node_id()), policy_nodemask(gfp, pol)); return page; } EXPORT_SYMBOL(alloc_pages_current); int vma_dup_policy(struct vm_area_struct *src, struct vm_area_struct *dst) { struct mempolicy *pol = mpol_dup(vma_policy(src)); if (IS_ERR(pol)) return PTR_ERR(pol); dst->vm_policy = pol; return 0; } /* * If mpol_dup() sees current->cpuset == cpuset_being_rebound, then it * rebinds the mempolicy its copying by calling mpol_rebind_policy() * with the mems_allowed returned by cpuset_mems_allowed(). This * keeps mempolicies cpuset relative after its cpuset moves. See * further kernel/cpuset.c update_nodemask(). * * current's mempolicy may be rebinded by the other task(the task that changes * cpuset's mems), so we needn't do rebind work for current task. */ /* Slow path of a mempolicy duplicate */ struct mempolicy *__mpol_dup(struct mempolicy *old) { struct mempolicy *new = kmem_cache_alloc(policy_cache, GFP_KERNEL); if (!new) return ERR_PTR(-ENOMEM); /* task's mempolicy is protected by alloc_lock */ if (old == current->mempolicy) { task_lock(current); *new = *old; task_unlock(current); } else *new = *old; if (current_cpuset_is_being_rebound()) { nodemask_t mems = cpuset_mems_allowed(current); mpol_rebind_policy(new, &mems); } atomic_set(&new->refcnt, 1); return new; } /* Slow path of a mempolicy comparison */ bool __mpol_equal(struct mempolicy *a, struct mempolicy *b) { if (!a || !b) return false; if (a->mode != b->mode) return false; if (a->flags != b->flags) return false; if (mpol_store_user_nodemask(a)) if (!nodes_equal(a->w.user_nodemask, b->w.user_nodemask)) return false; switch (a->mode) { case MPOL_BIND: /* Fall through */ case MPOL_INTERLEAVE: return !!nodes_equal(a->v.nodes, b->v.nodes); case MPOL_PREFERRED: /* a's ->flags is the same as b's */ if (a->flags & MPOL_F_LOCAL) return true; return a->v.preferred_node == b->v.preferred_node; default: BUG(); return false; } } /* * Shared memory backing store policy support. * * Remember policies even when nobody has shared memory mapped. * The policies are kept in Red-Black tree linked from the inode. * They are protected by the sp->lock rwlock, which should be held * for any accesses to the tree. */ /* * lookup first element intersecting start-end. Caller holds sp->lock for * reading or for writing */ static struct sp_node * sp_lookup(struct shared_policy *sp, unsigned long start, unsigned long end) { struct rb_node *n = sp->root.rb_node; while (n) { struct sp_node *p = rb_entry(n, struct sp_node, nd); if (start >= p->end) n = n->rb_right; else if (end <= p->start) n = n->rb_left; else break; } if (!n) return NULL; for (;;) { struct sp_node *w = NULL; struct rb_node *prev = rb_prev(n); if (!prev) break; w = rb_entry(prev, struct sp_node, nd); if (w->end <= start) break; n = prev; } return rb_entry(n, struct sp_node, nd); } /* * Insert a new shared policy into the list. Caller holds sp->lock for * writing. */ static void sp_insert(struct shared_policy *sp, struct sp_node *new) { struct rb_node **p = &sp->root.rb_node; struct rb_node *parent = NULL; struct sp_node *nd; while (*p) { parent = *p; nd = rb_entry(parent, struct sp_node, nd); if (new->start < nd->start) p = &(*p)->rb_left; else if (new->end > nd->end) p = &(*p)->rb_right; else BUG(); } rb_link_node(&new->nd, parent, p); rb_insert_color(&new->nd, &sp->root); pr_debug("inserting %lx-%lx: %d\n", new->start, new->end, new->policy ? new->policy->mode : 0); } /* Find shared policy intersecting idx */ struct mempolicy * mpol_shared_policy_lookup(struct shared_policy *sp, unsigned long idx) { struct mempolicy *pol = NULL; struct sp_node *sn; if (!sp->root.rb_node) return NULL; read_lock(&sp->lock); sn = sp_lookup(sp, idx, idx+1); if (sn) { mpol_get(sn->policy); pol = sn->policy; } read_unlock(&sp->lock); return pol; } static void sp_free(struct sp_node *n) { mpol_put(n->policy); kmem_cache_free(sn_cache, n); } /** * mpol_misplaced - check whether current page node is valid in policy * * @page: page to be checked * @vma: vm area where page mapped * @addr: virtual address where page mapped * * Lookup current policy node id for vma,addr and "compare to" page's * node id. * * Returns: * -1 - not misplaced, page is in the right node * node - node id where the page should be * * Policy determination "mimics" alloc_page_vma(). * Called from fault path where we know the vma and faulting address. */ int mpol_misplaced(struct page *page, struct vm_area_struct *vma, unsigned long addr) { struct mempolicy *pol; struct zoneref *z; int curnid = page_to_nid(page); unsigned long pgoff; int thiscpu = raw_smp_processor_id(); int thisnid = cpu_to_node(thiscpu); int polnid = NUMA_NO_NODE; int ret = -1; pol = get_vma_policy(vma, addr); if (!(pol->flags & MPOL_F_MOF)) goto out; switch (pol->mode) { case MPOL_INTERLEAVE: pgoff = vma->vm_pgoff; pgoff += (addr - vma->vm_start) >> PAGE_SHIFT; polnid = offset_il_node(pol, pgoff); break; case MPOL_PREFERRED: if (pol->flags & MPOL_F_LOCAL) polnid = numa_node_id(); else polnid = pol->v.preferred_node; break; case MPOL_BIND: /* * allows binding to multiple nodes. * use current page if in policy nodemask, * else select nearest allowed node, if any. * If no allowed nodes, use current [!misplaced]. */ if (node_isset(curnid, pol->v.nodes)) goto out; z = first_zones_zonelist( node_zonelist(numa_node_id(), GFP_HIGHUSER), gfp_zone(GFP_HIGHUSER), &pol->v.nodes); polnid = zone_to_nid(z->zone); break; default: BUG(); } /* Migrate the page towards the node whose CPU is referencing it */ if (pol->flags & MPOL_F_MORON) { polnid = thisnid; if (!should_numa_migrate_memory(current, page, curnid, thiscpu)) goto out; } if (curnid != polnid) ret = polnid; out: mpol_cond_put(pol); return ret; } /* * Drop the (possibly final) reference to task->mempolicy. It needs to be * dropped after task->mempolicy is set to NULL so that any allocation done as * part of its kmem_cache_free(), such as by KASAN, doesn't reference a freed * policy. */ void mpol_put_task_policy(struct task_struct *task) { struct mempolicy *pol; task_lock(task); pol = task->mempolicy; task->mempolicy = NULL; task_unlock(task); mpol_put(pol); } static void sp_delete(struct shared_policy *sp, struct sp_node *n) { pr_debug("deleting %lx-l%lx\n", n->start, n->end); rb_erase(&n->nd, &sp->root); sp_free(n); } static void sp_node_init(struct sp_node *node, unsigned long start, unsigned long end, struct mempolicy *pol) { node->start = start; node->end = end; node->policy = pol; } static struct sp_node *sp_alloc(unsigned long start, unsigned long end, struct mempolicy *pol) { struct sp_node *n; struct mempolicy *newpol; n = kmem_cache_alloc(sn_cache, GFP_KERNEL); if (!n) return NULL; newpol = mpol_dup(pol); if (IS_ERR(newpol)) { kmem_cache_free(sn_cache, n); return NULL; } newpol->flags |= MPOL_F_SHARED; sp_node_init(n, start, end, newpol); return n; } /* Replace a policy range. */ static int shared_policy_replace(struct shared_policy *sp, unsigned long start, unsigned long end, struct sp_node *new) { struct sp_node *n; struct sp_node *n_new = NULL; struct mempolicy *mpol_new = NULL; int ret = 0; restart: write_lock(&sp->lock); n = sp_lookup(sp, start, end); /* Take care of old policies in the same range. */ while (n && n->start < end) { struct rb_node *next = rb_next(&n->nd); if (n->start >= start) { if (n->end <= end) sp_delete(sp, n); else n->start = end; } else { /* Old policy spanning whole new range. */ if (n->end > end) { if (!n_new) goto alloc_new; *mpol_new = *n->policy; atomic_set(&mpol_new->refcnt, 1); sp_node_init(n_new, end, n->end, mpol_new); n->end = start; sp_insert(sp, n_new); n_new = NULL; mpol_new = NULL; break; } else n->end = start; } if (!next) break; n = rb_entry(next, struct sp_node, nd); } if (new) sp_insert(sp, new); write_unlock(&sp->lock); ret = 0; err_out: if (mpol_new) mpol_put(mpol_new); if (n_new) kmem_cache_free(sn_cache, n_new); return ret; alloc_new: write_unlock(&sp->lock); ret = -ENOMEM; n_new = kmem_cache_alloc(sn_cache, GFP_KERNEL); if (!n_new) goto err_out; mpol_new = kmem_cache_alloc(policy_cache, GFP_KERNEL); if (!mpol_new) goto err_out; goto restart; } /** * mpol_shared_policy_init - initialize shared policy for inode * @sp: pointer to inode shared policy * @mpol: struct mempolicy to install * * Install non-NULL @mpol in inode's shared policy rb-tree. * On entry, the current task has a reference on a non-NULL @mpol. * This must be released on exit. * This is called at get_inode() calls and we can use GFP_KERNEL. */ void mpol_shared_policy_init(struct shared_policy *sp, struct mempolicy *mpol) { int ret; sp->root = RB_ROOT; /* empty tree == default mempolicy */ rwlock_init(&sp->lock); if (mpol) { struct vm_area_struct pvma; struct mempolicy *new; NODEMASK_SCRATCH(scratch); if (!scratch) goto put_mpol; /* contextualize the tmpfs mount point mempolicy */ new = mpol_new(mpol->mode, mpol->flags, &mpol->w.user_nodemask); if (IS_ERR(new)) goto free_scratch; /* no valid nodemask intersection */ task_lock(current); ret = mpol_set_nodemask(new, &mpol->w.user_nodemask, scratch); task_unlock(current); if (ret) goto put_new; /* Create pseudo-vma that contains just the policy */ vma_init(&pvma, NULL); pvma.vm_end = TASK_SIZE; /* policy covers entire file */ mpol_set_shared_policy(sp, &pvma, new); /* adds ref */ put_new: mpol_put(new); /* drop initial ref */ free_scratch: NODEMASK_SCRATCH_FREE(scratch); put_mpol: mpol_put(mpol); /* drop our incoming ref on sb mpol */ } } int mpol_set_shared_policy(struct shared_policy *info, struct vm_area_struct *vma, struct mempolicy *npol) { int err; struct sp_node *new = NULL; unsigned long sz = vma_pages(vma); pr_debug("set_shared_policy %lx sz %lu %d %d %lx\n", vma->vm_pgoff, sz, npol ? npol->mode : -1, npol ? npol->flags : -1, npol ? nodes_addr(npol->v.nodes)[0] : NUMA_NO_NODE); if (npol) { new = sp_alloc(vma->vm_pgoff, vma->vm_pgoff + sz, npol); if (!new) return -ENOMEM; } err = shared_policy_replace(info, vma->vm_pgoff, vma->vm_pgoff+sz, new); if (err && new) sp_free(new); return err; } /* Free a backing policy store on inode delete. */ void mpol_free_shared_policy(struct shared_policy *p) { struct sp_node *n; struct rb_node *next; if (!p->root.rb_node) return; write_lock(&p->lock); next = rb_first(&p->root); while (next) { n = rb_entry(next, struct sp_node, nd); next = rb_next(&n->nd); sp_delete(p, n); } write_unlock(&p->lock); } #ifdef CONFIG_NUMA_BALANCING static int __initdata numabalancing_override; static void __init check_numabalancing_enable(void) { bool numabalancing_default = false; if (IS_ENABLED(CONFIG_NUMA_BALANCING_DEFAULT_ENABLED)) numabalancing_default = true; /* Parsed by setup_numabalancing. override == 1 enables, -1 disables */ if (numabalancing_override) set_numabalancing_state(numabalancing_override == 1); if (num_online_nodes() > 1 && !numabalancing_override) { pr_info("%s automatic NUMA balancing. Configure with numa_balancing= or the kernel.numa_balancing sysctl\n", numabalancing_default ? "Enabling" : "Disabling"); set_numabalancing_state(numabalancing_default); } } static int __init setup_numabalancing(char *str) { int ret = 0; if (!str) goto out; if (!strcmp(str, "enable")) { numabalancing_override = 1; ret = 1; } else if (!strcmp(str, "disable")) { numabalancing_override = -1; ret = 1; } out: if (!ret) pr_warn("Unable to parse numa_balancing=\n"); return ret; } __setup("numa_balancing=", setup_numabalancing); #else static inline void __init check_numabalancing_enable(void) { } #endif /* CONFIG_NUMA_BALANCING */ /* assumes fs == KERNEL_DS */ void __init numa_policy_init(void) { nodemask_t interleave_nodes; unsigned long largest = 0; int nid, prefer = 0; policy_cache = kmem_cache_create("numa_policy", sizeof(struct mempolicy), 0, SLAB_PANIC, NULL); sn_cache = kmem_cache_create("shared_policy_node", sizeof(struct sp_node), 0, SLAB_PANIC, NULL); for_each_node(nid) { preferred_node_policy[nid] = (struct mempolicy) { .refcnt = ATOMIC_INIT(1), .mode = MPOL_PREFERRED, .flags = MPOL_F_MOF | MPOL_F_MORON, .v = { .preferred_node = nid, }, }; } /* * Set interleaving policy for system init. Interleaving is only * enabled across suitably sized nodes (default is >= 16MB), or * fall back to the largest node if they're all smaller. */ nodes_clear(interleave_nodes); for_each_node_state(nid, N_MEMORY) { unsigned long total_pages = node_present_pages(nid); /* Preserve the largest node */ if (largest < total_pages) { largest = total_pages; prefer = nid; } /* Interleave this node? */ if ((total_pages << PAGE_SHIFT) >= (16 << 20)) node_set(nid, interleave_nodes); } /* All too small, use the largest */ if (unlikely(nodes_empty(interleave_nodes))) node_set(prefer, interleave_nodes); if (do_set_mempolicy(MPOL_INTERLEAVE, 0, &interleave_nodes)) pr_err("%s: interleaving failed\n", __func__); check_numabalancing_enable(); } /* Reset policy of current process to default */ void numa_default_policy(void) { do_set_mempolicy(MPOL_DEFAULT, 0, NULL); } /* * Parse and format mempolicy from/to strings */ /* * "local" is implemented internally by MPOL_PREFERRED with MPOL_F_LOCAL flag. */ static const char * const policy_modes[] = { [MPOL_DEFAULT] = "default", [MPOL_PREFERRED] = "prefer", [MPOL_BIND] = "bind", [MPOL_INTERLEAVE] = "interleave", [MPOL_LOCAL] = "local", }; #ifdef CONFIG_TMPFS /** * mpol_parse_str - parse string to mempolicy, for tmpfs mpol mount option. * @str: string containing mempolicy to parse * @mpol: pointer to struct mempolicy pointer, returned on success. * * Format of input: * <mode>[=<flags>][:<nodelist>] * * On success, returns 0, else 1 */ int mpol_parse_str(char *str, struct mempolicy **mpol) { struct mempolicy *new = NULL; unsigned short mode_flags; nodemask_t nodes; char *nodelist = strchr(str, ':'); char *flags = strchr(str, '='); int err = 1, mode; if (flags) *flags++ = '\0'; /* terminate mode string */ if (nodelist) { /* NUL-terminate mode or flags string */ *nodelist++ = '\0'; if (nodelist_parse(nodelist, nodes)) goto out; if (!nodes_subset(nodes, node_states[N_MEMORY])) goto out; } else nodes_clear(nodes); mode = match_string(policy_modes, MPOL_MAX, str); if (mode < 0) goto out; switch (mode) { case MPOL_PREFERRED: /* * Insist on a nodelist of one node only, although later * we use first_node(nodes) to grab a single node, so here * nodelist (or nodes) cannot be empty. */ if (nodelist) { char *rest = nodelist; while (isdigit(*rest)) rest++; if (*rest) goto out; if (nodes_empty(nodes)) goto out; } break; case MPOL_INTERLEAVE: /* * Default to online nodes with memory if no nodelist */ if (!nodelist) nodes = node_states[N_MEMORY]; break; case MPOL_LOCAL: /* * Don't allow a nodelist; mpol_new() checks flags */ if (nodelist) goto out; mode = MPOL_PREFERRED; break; case MPOL_DEFAULT: /* * Insist on a empty nodelist */ if (!nodelist) err = 0; goto out; case MPOL_BIND: /* * Insist on a nodelist */ if (!nodelist) goto out; } mode_flags = 0; if (flags) { /* * Currently, we only support two mutually exclusive * mode flags. */ if (!strcmp(flags, "static")) mode_flags |= MPOL_F_STATIC_NODES; else if (!strcmp(flags, "relative")) mode_flags |= MPOL_F_RELATIVE_NODES; else goto out; } new = mpol_new(mode, mode_flags, &nodes); if (IS_ERR(new)) goto out; /* * Save nodes for mpol_to_str() to show the tmpfs mount options * for /proc/mounts, /proc/pid/mounts and /proc/pid/mountinfo. */ if (mode != MPOL_PREFERRED) new->v.nodes = nodes; else if (nodelist) new->v.preferred_node = first_node(nodes); else new->flags |= MPOL_F_LOCAL; /* * Save nodes for contextualization: this will be used to "clone" * the mempolicy in a specific context [cpuset] at a later time. */ new->w.user_nodemask = nodes; err = 0; out: /* Restore string for error message */ if (nodelist) *--nodelist = ':'; if (flags) *--flags = '='; if (!err) *mpol = new; return err; } #endif /* CONFIG_TMPFS */ /** * mpol_to_str - format a mempolicy structure for printing * @buffer: to contain formatted mempolicy string * @maxlen: length of @buffer * @pol: pointer to mempolicy to be formatted * * Convert @pol into a string. If @buffer is too short, truncate the string. * Recommend a @maxlen of at least 32 for the longest mode, "interleave", the * longest flag, "relative", and to display at least a few node ids. */ void mpol_to_str(char *buffer, int maxlen, struct mempolicy *pol) { char *p = buffer; nodemask_t nodes = NODE_MASK_NONE; unsigned short mode = MPOL_DEFAULT; unsigned short flags = 0; if (pol && pol != &default_policy && !(pol->flags & MPOL_F_MORON)) { mode = pol->mode; flags = pol->flags; } switch (mode) { case MPOL_DEFAULT: break; case MPOL_PREFERRED: if (flags & MPOL_F_LOCAL) mode = MPOL_LOCAL; else node_set(pol->v.preferred_node, nodes); break; case MPOL_BIND: case MPOL_INTERLEAVE: nodes = pol->v.nodes; break; default: WARN_ON_ONCE(1); snprintf(p, maxlen, "unknown"); return; } p += snprintf(p, maxlen, "%s", policy_modes[mode]); if (flags & MPOL_MODE_FLAGS) { p += snprintf(p, buffer + maxlen - p, "="); /* * Currently, the only defined flags are mutually exclusive */ if (flags & MPOL_F_STATIC_NODES) p += snprintf(p, buffer + maxlen - p, "static"); else if (flags & MPOL_F_RELATIVE_NODES) p += snprintf(p, buffer + maxlen - p, "relative"); } if (!nodes_empty(nodes)) p += scnprintf(p, buffer + maxlen - p, ":%*pbl", nodemask_pr_args(&nodes)); }
null
165
CWE-787
CVE-2020-11939
/* * ssh.c * * Copyright (C) 2009-2011 by ipoque GmbH * Copyright (C) 2011-20 - ntop.org * * This file is part of nDPI, an open source deep packet inspection * library based on the OpenDPI and PACE technology by ipoque GmbH * * nDPI is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * nDPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with nDPI. If not, see <http://www.gnu.org/licenses/>. * */ #include "ndpi_protocol_ids.h" #define NDPI_CURRENT_PROTO NDPI_PROTOCOL_SSH #include "ndpi_api.h" #include "ndpi_md5.h" /* HASSH - https://github.com/salesforce/hassh https://github.com/salesforce/hassh/blob/master/python/hassh.py [server] skex = packet.ssh.kex_algorithms seastc = packet.ssh.encryption_algorithms_server_to_client smastc = packet.ssh.mac_algorithms_server_to_client scastc = packet.ssh.compression_algorithms_server_to_client hasshs_str = ';'.join([skex, seastc, smastc, scastc]) [client] ckex = packet.ssh.kex_algorithms ceacts = packet.ssh.encryption_algorithms_client_to_server cmacts = packet.ssh.mac_algorithms_client_to_server ccacts = packet.ssh.compression_algorithms_client_to_server hassh_str = ';'.join([ckex, ceacts, cmacts, ccacts]) NOTE THe ECDSA key fingerprint is SHA256 -> ssh.kex.h_sig (wireshark) is in the Message Code: Diffie-Hellman Key Exchange Reply (31) that usually is packet 14 */ /* #define SSH_DEBUG 1 */ static void ndpi_search_ssh_tcp(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow); /* ************************************************************************ */ static int search_ssh_again(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { ndpi_search_ssh_tcp(ndpi_struct, flow); if((flow->protos.ssh.hassh_client[0] != '\0') && (flow->protos.ssh.hassh_server[0] != '\0')) { /* stop extra processing */ flow->extra_packets_func = NULL; /* We're good now */ return(0); } /* Possibly more processing */ return(1); } /* ************************************************************************ */ static void ndpi_int_ssh_add_connection(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { if(flow->extra_packets_func != NULL) return; flow->guessed_host_protocol_id = flow->guessed_protocol_id = NDPI_PROTOCOL_SSH; /* This is necessary to inform the core to call this dissector again */ flow->check_extra_packets = 1; flow->max_extra_packets_to_check = 12; flow->extra_packets_func = search_ssh_again; ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_SSH, NDPI_PROTOCOL_UNKNOWN); } /* ************************************************************************ */ static u_int16_t concat_hash_string(struct ndpi_packet_struct *packet, char *buf, u_int8_t client_hash) { u_int16_t offset = 22, buf_out_len = 0; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; u_int32_t len = ntohl(*(u_int32_t*)&packet->payload[offset]); offset += 4; /* -1 for ';' */ if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; /* ssh.kex_algorithms [C/S] */ strncpy(buf, (const char *)&packet->payload[offset], buf_out_len = len); buf[buf_out_len++] = ';'; offset += len; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; /* ssh.server_host_key_algorithms [None] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); offset += 4 + len; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; /* ssh.encryption_algorithms_client_to_server [C] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; buf[buf_out_len++] = ';'; offset += len; } else offset += 4 + len; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; /* ssh.encryption_algorithms_server_to_client [S] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(!client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; buf[buf_out_len++] = ';'; offset += len; } else offset += 4 + len; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; /* ssh.mac_algorithms_client_to_server [C] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; buf[buf_out_len++] = ';'; offset += len; } else offset += 4 + len; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; /* ssh.mac_algorithms_server_to_client [S] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(!client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; buf[buf_out_len++] = ';'; offset += len; } else offset += 4 + len; /* ssh.compression_algorithms_client_to_server [C] */ if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; offset += len; } else offset += 4 + len; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; /* ssh.compression_algorithms_server_to_client [S] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); if(!client_hash) { offset += 4; if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; offset += len; } else offset += 4 + len; /* ssh.languages_client_to_server [None] */ /* ssh.languages_server_to_client [None] */ #ifdef SSH_DEBUG printf("[SSH] %s\n", buf); #endif return(buf_out_len); invalid_payload: #ifdef SSH_DEBUG printf("[SSH] Invalid packet payload\n"); #endif return(0); } /* ************************************************************************ */ static void ndpi_ssh_zap_cr(char *str, int len) { len--; while(len > 0) { if((str[len] == '\n') || (str[len] == '\r')) { str[len] = '\0'; len--; } else break; } } /* ************************************************************************ */ static void ndpi_search_ssh_tcp(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; #ifdef SSH_DEBUG printf("[SSH] %s()\n", __FUNCTION__); #endif if(flow->l4.tcp.ssh_stage == 0) { if(packet->payload_packet_len > 7 && packet->payload_packet_len < 100 && memcmp(packet->payload, "SSH-", 4) == 0) { int len = ndpi_min(sizeof(flow->protos.ssh.client_signature)-1, packet->payload_packet_len); strncpy(flow->protos.ssh.client_signature, (const char *)packet->payload, len); flow->protos.ssh.client_signature[len] = '\0'; ndpi_ssh_zap_cr(flow->protos.ssh.client_signature, len); #ifdef SSH_DEBUG printf("[SSH] [client_signature: %s]\n", flow->protos.ssh.client_signature); #endif NDPI_LOG_DBG2(ndpi_struct, "ssh stage 0 passed\n"); flow->l4.tcp.ssh_stage = 1 + packet->packet_direction; ndpi_int_ssh_add_connection(ndpi_struct, flow); return; } } else if(flow->l4.tcp.ssh_stage == (2 - packet->packet_direction)) { if(packet->payload_packet_len > 7 && packet->payload_packet_len < 500 && memcmp(packet->payload, "SSH-", 4) == 0) { int len = ndpi_min(sizeof(flow->protos.ssh.server_signature)-1, packet->payload_packet_len); strncpy(flow->protos.ssh.server_signature, (const char *)packet->payload, len); flow->protos.ssh.server_signature[len] = '\0'; ndpi_ssh_zap_cr(flow->protos.ssh.server_signature, len); #ifdef SSH_DEBUG printf("[SSH] [server_signature: %s]\n", flow->protos.ssh.server_signature); #endif NDPI_LOG_DBG2(ndpi_struct, "ssh stage 1 passed\n"); flow->guessed_host_protocol_id = flow->guessed_protocol_id = NDPI_PROTOCOL_SSH; #ifdef SSH_DEBUG printf("[SSH] [completed stage: %u]\n", flow->l4.tcp.ssh_stage); #endif flow->l4.tcp.ssh_stage = 3; return; } } else if(packet->payload_packet_len > 5) { u_int8_t msgcode = *(packet->payload + 5); ndpi_MD5_CTX ctx; if(msgcode == 20 /* key exchange init */) { char *hassh_buf = ndpi_calloc(packet->payload_packet_len, sizeof(char)); u_int i, len; #ifdef SSH_DEBUG printf("[SSH] [stage: %u][msg: %u][direction: %u][key exchange init]\n", flow->l4.tcp.ssh_stage, msgcode, packet->packet_direction); #endif if(hassh_buf) { if(packet->packet_direction == 0 /* client */) { u_char fingerprint_client[16]; len = concat_hash_string(packet, hassh_buf, 1 /* client */); ndpi_MD5Init(&ctx); ndpi_MD5Update(&ctx, (const unsigned char *)hassh_buf, len); ndpi_MD5Final(fingerprint_client, &ctx); #ifdef SSH_DEBUG { printf("[SSH] [client][%s][", hassh_buf); for(i=0; i<16; i++) printf("%02X", fingerprint_client[i]); printf("]\n"); } #endif for(i=0; i<16; i++) sprintf(&flow->protos.ssh.hassh_client[i*2], "%02X", fingerprint_client[i] & 0xFF); flow->protos.ssh.hassh_client[32] = '\0'; } else { u_char fingerprint_server[16]; len = concat_hash_string(packet, hassh_buf, 0 /* server */); ndpi_MD5Init(&ctx); ndpi_MD5Update(&ctx, (const unsigned char *)hassh_buf, len); ndpi_MD5Final(fingerprint_server, &ctx); #ifdef SSH_DEBUG { printf("[SSH] [server][%s][", hassh_buf); for(i=0; i<16; i++) printf("%02X", fingerprint_server[i]); printf("]\n"); } #endif for(i=0; i<16; i++) sprintf(&flow->protos.ssh.hassh_server[i*2], "%02X", fingerprint_server[i] & 0xFF); flow->protos.ssh.hassh_server[32] = '\0'; } ndpi_free(hassh_buf); } ndpi_int_ssh_add_connection(ndpi_struct, flow); } if((flow->protos.ssh.hassh_client[0] != '\0') && (flow->protos.ssh.hassh_server[0] != '\0')) { #ifdef SSH_DEBUG printf("[SSH] Dissection completed\n"); #endif flow->extra_packets_func = NULL; /* We're good now */ } return; } #ifdef SSH_DEBUG printf("[SSH] Excluding SSH"); #endif NDPI_LOG_DBG(ndpi_struct, "excluding ssh at stage %d\n", flow->l4.tcp.ssh_stage); NDPI_ADD_PROTOCOL_TO_BITMASK(flow->excluded_protocol_bitmask, NDPI_PROTOCOL_SSH); } /* ************************************************************************ */ void init_ssh_dissector(struct ndpi_detection_module_struct *ndpi_struct, u_int32_t *id, NDPI_PROTOCOL_BITMASK *detection_bitmask) { ndpi_set_bitmask_protocol_detection("SSH", ndpi_struct, detection_bitmask, *id, NDPI_PROTOCOL_SSH, ndpi_search_ssh_tcp, NDPI_SELECTION_BITMASK_PROTOCOL_V4_V6_TCP_WITH_PAYLOAD_WITHOUT_RETRANSMISSION, SAVE_DETECTION_BITMASK_AS_UNKNOWN, ADD_TO_DETECTION_BITMASK); *id += 1; }
null
/* * ssh.c * * Copyright (C) 2009-2011 by ipoque GmbH * Copyright (C) 2011-20 - ntop.org * * This file is part of nDPI, an open source deep packet inspection * library based on the OpenDPI and PACE technology by ipoque GmbH * * nDPI is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * nDPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with nDPI. If not, see <http://www.gnu.org/licenses/>. * */ #include "ndpi_protocol_ids.h" #define NDPI_CURRENT_PROTO NDPI_PROTOCOL_SSH #include "ndpi_api.h" #include "ndpi_md5.h" /* HASSH - https://github.com/salesforce/hassh https://github.com/salesforce/hassh/blob/master/python/hassh.py [server] skex = packet.ssh.kex_algorithms seastc = packet.ssh.encryption_algorithms_server_to_client smastc = packet.ssh.mac_algorithms_server_to_client scastc = packet.ssh.compression_algorithms_server_to_client hasshs_str = ';'.join([skex, seastc, smastc, scastc]) [client] ckex = packet.ssh.kex_algorithms ceacts = packet.ssh.encryption_algorithms_client_to_server cmacts = packet.ssh.mac_algorithms_client_to_server ccacts = packet.ssh.compression_algorithms_client_to_server hassh_str = ';'.join([ckex, ceacts, cmacts, ccacts]) NOTE THe ECDSA key fingerprint is SHA256 -> ssh.kex.h_sig (wireshark) is in the Message Code: Diffie-Hellman Key Exchange Reply (31) that usually is packet 14 */ /* #define SSH_DEBUG 1 */ static void ndpi_search_ssh_tcp(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow); /* ************************************************************************ */ static int search_ssh_again(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { ndpi_search_ssh_tcp(ndpi_struct, flow); if((flow->protos.ssh.hassh_client[0] != '\0') && (flow->protos.ssh.hassh_server[0] != '\0')) { /* stop extra processing */ flow->extra_packets_func = NULL; /* We're good now */ return(0); } /* Possibly more processing */ return(1); } /* ************************************************************************ */ static void ndpi_int_ssh_add_connection(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { if(flow->extra_packets_func != NULL) return; flow->guessed_host_protocol_id = flow->guessed_protocol_id = NDPI_PROTOCOL_SSH; /* This is necessary to inform the core to call this dissector again */ flow->check_extra_packets = 1; flow->max_extra_packets_to_check = 12; flow->extra_packets_func = search_ssh_again; ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_SSH, NDPI_PROTOCOL_UNKNOWN); } /* ************************************************************************ */ static u_int16_t concat_hash_string(struct ndpi_packet_struct *packet, char *buf, u_int8_t client_hash) { u_int32_t offset = 22, buf_out_len = 0; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; u_int32_t len = ntohl(*(u_int32_t*)&packet->payload[offset]); offset += 4; /* -1 for ';' */ if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; /* ssh.kex_algorithms [C/S] */ strncpy(buf, (const char *)&packet->payload[offset], buf_out_len = len); buf[buf_out_len++] = ';'; offset += len; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; /* ssh.server_host_key_algorithms [None] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); if (len > UINT32_MAX - 4 - offset) goto invalid_payload; offset += 4 + len; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; /* ssh.encryption_algorithms_client_to_server [C] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); offset += 4; if(client_hash) { if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; buf[buf_out_len++] = ';'; } if (len > UINT32_MAX - offset) goto invalid_payload; offset += len; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; /* ssh.encryption_algorithms_server_to_client [S] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); offset += 4; if(!client_hash) { if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; buf[buf_out_len++] = ';'; } if (len > UINT32_MAX - offset) goto invalid_payload; offset += len; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; /* ssh.mac_algorithms_client_to_server [C] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); offset += 4; if(client_hash) { if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; buf[buf_out_len++] = ';'; } if (len > UINT32_MAX - offset) goto invalid_payload; offset += len; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; /* ssh.mac_algorithms_server_to_client [S] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); offset += 4; if(!client_hash) { if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; buf[buf_out_len++] = ';'; } if (len > UINT32_MAX - offset) goto invalid_payload; offset += len; /* ssh.compression_algorithms_client_to_server [C] */ if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; len = ntohl(*(u_int32_t*)&packet->payload[offset]); offset += 4; if(client_hash) { if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; } if (len > UINT32_MAX - offset) goto invalid_payload; offset += len; if(offset+sizeof(u_int32_t) >= packet->payload_packet_len) goto invalid_payload; /* ssh.compression_algorithms_server_to_client [S] */ len = ntohl(*(u_int32_t*)&packet->payload[offset]); offset += 4; if(!client_hash) { if((offset >= packet->payload_packet_len) || (len >= packet->payload_packet_len-offset-1)) goto invalid_payload; strncpy(&buf[buf_out_len], (const char *)&packet->payload[offset], len); buf_out_len += len; } if (len > UINT32_MAX - offset) goto invalid_payload; offset += len; /* ssh.languages_client_to_server [None] */ /* ssh.languages_server_to_client [None] */ #ifdef SSH_DEBUG printf("[SSH] %s\n", buf); #endif return(buf_out_len); invalid_payload: #ifdef SSH_DEBUG printf("[SSH] Invalid packet payload\n"); #endif return(0); } /* ************************************************************************ */ static void ndpi_ssh_zap_cr(char *str, int len) { len--; while(len > 0) { if((str[len] == '\n') || (str[len] == '\r')) { str[len] = '\0'; len--; } else break; } } /* ************************************************************************ */ static void ndpi_search_ssh_tcp(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; #ifdef SSH_DEBUG printf("[SSH] %s()\n", __FUNCTION__); #endif if(flow->l4.tcp.ssh_stage == 0) { if(packet->payload_packet_len > 7 && packet->payload_packet_len < 100 && memcmp(packet->payload, "SSH-", 4) == 0) { int len = ndpi_min(sizeof(flow->protos.ssh.client_signature)-1, packet->payload_packet_len); strncpy(flow->protos.ssh.client_signature, (const char *)packet->payload, len); flow->protos.ssh.client_signature[len] = '\0'; ndpi_ssh_zap_cr(flow->protos.ssh.client_signature, len); #ifdef SSH_DEBUG printf("[SSH] [client_signature: %s]\n", flow->protos.ssh.client_signature); #endif NDPI_LOG_DBG2(ndpi_struct, "ssh stage 0 passed\n"); flow->l4.tcp.ssh_stage = 1 + packet->packet_direction; ndpi_int_ssh_add_connection(ndpi_struct, flow); return; } } else if(flow->l4.tcp.ssh_stage == (2 - packet->packet_direction)) { if(packet->payload_packet_len > 7 && packet->payload_packet_len < 500 && memcmp(packet->payload, "SSH-", 4) == 0) { int len = ndpi_min(sizeof(flow->protos.ssh.server_signature)-1, packet->payload_packet_len); strncpy(flow->protos.ssh.server_signature, (const char *)packet->payload, len); flow->protos.ssh.server_signature[len] = '\0'; ndpi_ssh_zap_cr(flow->protos.ssh.server_signature, len); #ifdef SSH_DEBUG printf("[SSH] [server_signature: %s]\n", flow->protos.ssh.server_signature); #endif NDPI_LOG_DBG2(ndpi_struct, "ssh stage 1 passed\n"); flow->guessed_host_protocol_id = flow->guessed_protocol_id = NDPI_PROTOCOL_SSH; #ifdef SSH_DEBUG printf("[SSH] [completed stage: %u]\n", flow->l4.tcp.ssh_stage); #endif flow->l4.tcp.ssh_stage = 3; return; } } else if(packet->payload_packet_len > 5) { u_int8_t msgcode = *(packet->payload + 5); ndpi_MD5_CTX ctx; if(msgcode == 20 /* key exchange init */) { char *hassh_buf = ndpi_calloc(packet->payload_packet_len, sizeof(char)); u_int i, len; #ifdef SSH_DEBUG printf("[SSH] [stage: %u][msg: %u][direction: %u][key exchange init]\n", flow->l4.tcp.ssh_stage, msgcode, packet->packet_direction); #endif if(hassh_buf) { if(packet->packet_direction == 0 /* client */) { u_char fingerprint_client[16]; len = concat_hash_string(packet, hassh_buf, 1 /* client */); ndpi_MD5Init(&ctx); ndpi_MD5Update(&ctx, (const unsigned char *)hassh_buf, len); ndpi_MD5Final(fingerprint_client, &ctx); #ifdef SSH_DEBUG { printf("[SSH] [client][%s][", hassh_buf); for(i=0; i<16; i++) printf("%02X", fingerprint_client[i]); printf("]\n"); } #endif for(i=0; i<16; i++) sprintf(&flow->protos.ssh.hassh_client[i*2], "%02X", fingerprint_client[i] & 0xFF); flow->protos.ssh.hassh_client[32] = '\0'; } else { u_char fingerprint_server[16]; len = concat_hash_string(packet, hassh_buf, 0 /* server */); ndpi_MD5Init(&ctx); ndpi_MD5Update(&ctx, (const unsigned char *)hassh_buf, len); ndpi_MD5Final(fingerprint_server, &ctx); #ifdef SSH_DEBUG { printf("[SSH] [server][%s][", hassh_buf); for(i=0; i<16; i++) printf("%02X", fingerprint_server[i]); printf("]\n"); } #endif for(i=0; i<16; i++) sprintf(&flow->protos.ssh.hassh_server[i*2], "%02X", fingerprint_server[i] & 0xFF); flow->protos.ssh.hassh_server[32] = '\0'; } ndpi_free(hassh_buf); } ndpi_int_ssh_add_connection(ndpi_struct, flow); } if((flow->protos.ssh.hassh_client[0] != '\0') && (flow->protos.ssh.hassh_server[0] != '\0')) { #ifdef SSH_DEBUG printf("[SSH] Dissection completed\n"); #endif flow->extra_packets_func = NULL; /* We're good now */ } return; } #ifdef SSH_DEBUG printf("[SSH] Excluding SSH"); #endif NDPI_LOG_DBG(ndpi_struct, "excluding ssh at stage %d\n", flow->l4.tcp.ssh_stage); NDPI_ADD_PROTOCOL_TO_BITMASK(flow->excluded_protocol_bitmask, NDPI_PROTOCOL_SSH); } /* ************************************************************************ */ void init_ssh_dissector(struct ndpi_detection_module_struct *ndpi_struct, u_int32_t *id, NDPI_PROTOCOL_BITMASK *detection_bitmask) { ndpi_set_bitmask_protocol_detection("SSH", ndpi_struct, detection_bitmask, *id, NDPI_PROTOCOL_SSH, ndpi_search_ssh_tcp, NDPI_SELECTION_BITMASK_PROTOCOL_V4_V6_TCP_WITH_PAYLOAD_WITHOUT_RETRANSMISSION, SAVE_DETECTION_BITMASK_AS_UNKNOWN, ADD_TO_DETECTION_BITMASK); *id += 1; }
null
166
CWE-787
CVE-2020-11958
#include <stdio.h> #include <algorithm> #include "src/util/c99_stdint.h" #include <limits> #include <string.h> #include "src/msg/msg.h" #include "src/parse/scanner.h" #include "src/debug/debug.h" namespace re2c { const char *const Scanner::ENDPOS = (const char*) std::numeric_limits<uint64_t>::max(); Scanner::~Scanner() { for (size_t i = files.size(); i --> 0; ) { delete files[i]; } } size_t Scanner::get_input_index() const { // Find index of the current input file: the one corresponding to // buffer fragment that contains cursor. size_t i = files.size(); DASSERT(i > 0); for (;;) { --i; Input *in = files[i]; if (i == 0 || (cur >= in->so && cur <= in->eo)) break; } return i; } bool Scanner::open(const std::string &filename, const std::string *parent) { Input *in = new Input(msg.filenames.size()); files.push_back(in); if (!in->open(filename, parent, globopts->incpaths)) { return false; } msg.filenames.push_back(in->escaped_name); return true; } bool Scanner::include(const std::string &filename) { // get name of the current file (before unreading) DASSERT(!files.empty()); const std::string &parent = files.back()->escaped_name; // unread buffer tail: we'll return to it later // In the buffer nested files go before outer files. In the file stack, // however, outer files go before nested files (nested are at the top). // We want to break from the unreading cycle early, therefore we go in // reverse order of file offsets in buffer and break as soon as the end // offset is less than cursor (current position). for (size_t i = 0; i < files.size(); ++i) { Input *in = files[i]; if (in->so >= cur) { // unread whole fragment fseek(in->file, in->so - in->eo, SEEK_CUR); in->so = in->eo = ENDPOS; } else if (in->eo >= cur) { // fragment on the boundary, unread partially fseek(in->file, cur - in->eo, SEEK_CUR); in->eo = cur - 1; } else { // the rest has been consumed already break; } } // open new file and place place at the top of stack if (!open(filename, &parent)) { return false; } // refill buffer (discard everything up to cursor, clear EOF) lim = cur = mar = ctx = tok = ptr = pos = bot + BSIZE; eof = NULL; return fill(BSIZE); } bool Scanner::read(size_t want) { DASSERT(!files.empty()); for (size_t i = files.size(); i --> 0; ) { Input *in = files[i]; const size_t have = fread(lim, 1, want, in->file); in->so = lim; lim += have; in->eo = lim; want -= have; // buffer filled if (want == 0) return true; } return false; } void Scanner::shift_ptrs_and_fpos(ptrdiff_t offs) { // shift buffer pointers shift_ptrs(offs); // shift file pointers for (size_t i = files.size(); i --> 0; ) { Input *in = files[i]; if (in->so == ENDPOS && in->eo == ENDPOS) break; DASSERT(in->so != ENDPOS && in->eo != ENDPOS); in->so += offs; in->eo += offs; } } void Scanner::pop_finished_files() { // Pop all files that have been fully processed (file upper bound // in buffer points before the first character of current lexeme), // except for the first (main) file which must always remain at the // bottom of the stack. size_t i = files.size(); DASSERT(i > 0); for (;;) { --i; Input *in = files[i]; if (i == 0 || in->eo >= tok) break; files.pop_back(); delete in; } } bool Scanner::fill(size_t need) { if (eof) return false; pop_finished_files(); DASSERT(bot <= tok && tok <= lim); size_t free = static_cast<size_t>(tok - bot); size_t copy = static_cast<size_t>(lim - tok); if (free >= need) { memmove(bot, tok, copy); shift_ptrs_and_fpos(-static_cast<ptrdiff_t>(free)); } else { BSIZE += std::max(BSIZE, need); char * buf = new char[BSIZE + YYMAXFILL]; if (!buf) fatal("out of memory"); memmove(buf, tok, copy); shift_ptrs_and_fpos(buf - bot); delete [] bot; bot = buf; free = BSIZE - copy; } if (!read(free)) { eof = lim; memset(lim, 0, YYMAXFILL); lim += YYMAXFILL; } return true; } } // namespace re2c
null
#include <stdio.h> #include <algorithm> #include "src/util/c99_stdint.h" #include <limits> #include <string.h> #include "src/msg/msg.h" #include "src/parse/scanner.h" #include "src/debug/debug.h" namespace re2c { const char *const Scanner::ENDPOS = (const char*) std::numeric_limits<uint64_t>::max(); Scanner::~Scanner() { for (size_t i = files.size(); i --> 0; ) { delete files[i]; } } size_t Scanner::get_input_index() const { // Find index of the current input file: the one corresponding to // buffer fragment that contains cursor. size_t i = files.size(); DASSERT(i > 0); for (;;) { --i; Input *in = files[i]; if (i == 0 || (cur >= in->so && cur <= in->eo)) break; } return i; } bool Scanner::open(const std::string &filename, const std::string *parent) { Input *in = new Input(msg.filenames.size()); files.push_back(in); if (!in->open(filename, parent, globopts->incpaths)) { return false; } msg.filenames.push_back(in->escaped_name); return true; } bool Scanner::include(const std::string &filename) { // get name of the current file (before unreading) DASSERT(!files.empty()); const std::string &parent = files.back()->escaped_name; // unread buffer tail: we'll return to it later // In the buffer nested files go before outer files. In the file stack, // however, outer files go before nested files (nested are at the top). // We want to break from the unreading cycle early, therefore we go in // reverse order of file offsets in buffer and break as soon as the end // offset is less than cursor (current position). for (size_t i = 0; i < files.size(); ++i) { Input *in = files[i]; if (in->so >= cur) { // unread whole fragment fseek(in->file, in->so - in->eo, SEEK_CUR); in->so = in->eo = ENDPOS; } else if (in->eo >= cur) { // fragment on the boundary, unread partially fseek(in->file, cur - in->eo, SEEK_CUR); in->eo = cur - 1; } else { // the rest has been consumed already break; } } // open new file and place place at the top of stack if (!open(filename, &parent)) { return false; } // refill buffer (discard everything up to cursor, clear EOF) lim = cur = mar = ctx = tok = ptr = pos = bot + BSIZE; eof = NULL; return fill(BSIZE); } bool Scanner::read(size_t want) { DASSERT(!files.empty()); for (size_t i = files.size(); i --> 0; ) { Input *in = files[i]; const size_t have = fread(lim, 1, want, in->file); in->so = lim; lim += have; in->eo = lim; want -= have; // buffer filled if (want == 0) return true; } return false; } void Scanner::shift_ptrs_and_fpos(ptrdiff_t offs) { // shift buffer pointers shift_ptrs(offs); // shift file pointers for (size_t i = files.size(); i --> 0; ) { Input *in = files[i]; if (in->so == ENDPOS && in->eo == ENDPOS) break; DASSERT(in->so != ENDPOS && in->eo != ENDPOS); in->so += offs; in->eo += offs; } } void Scanner::pop_finished_files() { // Pop all files that have been fully processed (file upper bound // in buffer points before the first character of current lexeme), // except for the first (main) file which must always remain at the // bottom of the stack. size_t i = files.size(); DASSERT(i > 0); for (;;) { --i; Input *in = files[i]; if (i == 0 || in->eo >= tok) break; files.pop_back(); delete in; } } bool Scanner::fill(size_t need) { if (eof) return false; pop_finished_files(); DASSERT(bot <= tok && tok <= lim); size_t free = static_cast<size_t>(tok - bot); size_t copy = static_cast<size_t>(lim - tok); if (free >= need) { memmove(bot, tok, copy); shift_ptrs_and_fpos(-static_cast<ptrdiff_t>(free)); } else { BSIZE += std::max(BSIZE, need); char * buf = new char[BSIZE + YYMAXFILL]; if (!buf) fatal("out of memory"); memmove(buf, tok, copy); shift_ptrs_and_fpos(buf - tok); delete [] bot; bot = buf; free = BSIZE - copy; } DASSERT(lim + free <= bot + BSIZE); if (!read(free)) { eof = lim; memset(lim, 0, YYMAXFILL); lim += YYMAXFILL; } return true; } } // namespace re2c
null
167
CWE-787
CVE-2020-12268
/* Copyright (C) 2001-2019 Artifex Software, Inc. All Rights Reserved. This software is provided AS-IS with no warranty, either express or implied. This software is distributed under license and may not be copied, modified or distributed except as expressly authorized under the terms of the license contained in the file LICENSE in this distribution. Refer to licensing information at http://www.artifex.com or contact Artifex Software, Inc., 1305 Grant Avenue - Suite 200, Novato, CA 94945, U.S.A., +1(415)492-9861, for further information. */ /* jbig2dec */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "os_types.h" #include <stdio.h> #include <stdlib.h> #include <string.h> /* memcpy() */ #include "jbig2.h" #include "jbig2_priv.h" #include "jbig2_image.h" #if !defined (INT32_MAX) #define INT32_MAX 0x7fffffff #endif /* allocate a Jbig2Image structure and its associated bitmap */ Jbig2Image * jbig2_image_new(Jbig2Ctx *ctx, uint32_t width, uint32_t height) { Jbig2Image *image; uint32_t stride; if (width == 0 || height == 0) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "failed to create zero sized image"); return NULL; } image = jbig2_new(ctx, Jbig2Image, 1); if (image == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "failed to allocate image"); return NULL; } stride = ((width - 1) >> 3) + 1; /* generate a byte-aligned stride */ /* check for integer multiplication overflow */ if (height > (INT32_MAX / stride)) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "integer multiplication overflow (stride=%u, height=%u)", stride, height); jbig2_free(ctx->allocator, image); return NULL; } image->data = jbig2_new(ctx, uint8_t, (size_t) height * stride); if (image->data == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "failed to allocate image data buffer (stride=%u, height=%u)", stride, height); jbig2_free(ctx->allocator, image); return NULL; } image->width = width; image->height = height; image->stride = stride; image->refcount = 1; return image; } /* bump the reference count for an image pointer */ Jbig2Image * jbig2_image_reference(Jbig2Ctx *ctx, Jbig2Image *image) { if (image) image->refcount++; return image; } /* release an image pointer, freeing it it appropriate */ void jbig2_image_release(Jbig2Ctx *ctx, Jbig2Image *image) { if (image == NULL) return; image->refcount--; if (image->refcount == 0) jbig2_image_free(ctx, image); } /* free a Jbig2Image structure and its associated memory */ void jbig2_image_free(Jbig2Ctx *ctx, Jbig2Image *image) { if (image != NULL) { jbig2_free(ctx->allocator, image->data); jbig2_free(ctx->allocator, image); } } /* resize a Jbig2Image */ Jbig2Image * jbig2_image_resize(Jbig2Ctx *ctx, Jbig2Image *image, uint32_t width, uint32_t height, int value) { if (width == image->width) { uint8_t *data; /* check for integer multiplication overflow */ if (image->height > (INT32_MAX / image->stride)) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "integer multiplication overflow during resize (stride=%u, height=%u)", image->stride, height); return NULL; } /* use the same stride, just change the length */ data = jbig2_renew(ctx, image->data, uint8_t, (size_t) height * image->stride); if (data == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "failed to reallocate image"); return NULL; } image->data = data; if (height > image->height) { const uint8_t fill = value ? 0xFF : 0x00; memset(image->data + (size_t) image->height * image->stride, fill, ((size_t) height - image->height) * image->stride); } image->height = height; } else { Jbig2Image *newimage; int code; /* Unoptimized implementation, but it works. */ newimage = jbig2_image_new(ctx, width, height); if (newimage == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "failed to allocate resized image"); return NULL; } jbig2_image_clear(ctx, newimage, value); code = jbig2_image_compose(ctx, newimage, image, 0, 0, JBIG2_COMPOSE_REPLACE); if (code < 0) { jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "failed to compose image buffers when resizing"); jbig2_image_release(ctx, newimage); return NULL; } /* if refcount > 1 the original image, its pointer must be kept, so simply replaces its innards, and throw away the empty new image shell. */ jbig2_free(ctx->allocator, image->data); image->width = newimage->width; image->height = newimage->height; image->stride = newimage->stride; image->data = newimage->data; jbig2_free(ctx->allocator, newimage); } return image; } static inline void template_image_compose_opt(const uint8_t * JBIG2_RESTRICT ss, uint8_t * JBIG2_RESTRICT dd, int early, int late, uint8_t leftmask, uint8_t rightmask, uint32_t bytewidth_, uint32_t h, uint32_t shift, uint32_t dstride, uint32_t sstride, Jbig2ComposeOp op) { int i; uint32_t j; int bytewidth = (int)bytewidth_; if (bytewidth == 1) { for (j = 0; j < h; j++) { /* Only 1 byte! */ uint8_t v = (((early ? 0 : ss[0]<<8) | (late ? 0 : ss[1]))>>shift); if (op == JBIG2_COMPOSE_OR) *dd |= v & leftmask; else if (op == JBIG2_COMPOSE_AND) *dd &= (v & leftmask) | ~leftmask; else if (op == JBIG2_COMPOSE_XOR) *dd ^= v & leftmask; else if (op == JBIG2_COMPOSE_XNOR) *dd ^= (~v) & leftmask; else /* Replace */ *dd = (v & leftmask) | (*dd & ~leftmask); dd += dstride; ss += sstride; } return; } bytewidth -= 2; if (shift == 0) { ss++; for (j = 0; j < h; j++) { /* Left byte */ const uint8_t * JBIG2_RESTRICT s = ss; uint8_t * JBIG2_RESTRICT d = dd; if (op == JBIG2_COMPOSE_OR) *d++ |= *s++ & leftmask; else if (op == JBIG2_COMPOSE_AND) *d++ &= (*s++ & leftmask) | ~leftmask; else if (op == JBIG2_COMPOSE_XOR) *d++ ^= *s++ & leftmask; else if (op == JBIG2_COMPOSE_XNOR) *d++ ^= (~*s++) & leftmask; else /* Replace */ *d = (*s++ & leftmask) | (*d & ~leftmask), d++; /* Central run */ for (i = bytewidth; i != 0; i--) { if (op == JBIG2_COMPOSE_OR) *d++ |= *s++; else if (op == JBIG2_COMPOSE_AND) *d++ &= *s++; else if (op == JBIG2_COMPOSE_XOR) *d++ ^= *s++; else if (op == JBIG2_COMPOSE_XNOR) *d++ ^= ~*s++; else /* Replace */ *d++ = *s++; } /* Right byte */ if (op == JBIG2_COMPOSE_OR) *d |= *s & rightmask; else if (op == JBIG2_COMPOSE_AND) *d &= (*s & rightmask) | ~rightmask; else if (op == JBIG2_COMPOSE_XOR) *d ^= *s & rightmask; else if (op == JBIG2_COMPOSE_XNOR) *d ^= (~*s) & rightmask; else /* Replace */ *d = (*s & rightmask) | (*d & ~rightmask); dd += dstride; ss += sstride; } } else { for (j = 0; j < h; j++) { /* Left byte */ const uint8_t * JBIG2_RESTRICT s = ss; uint8_t * JBIG2_RESTRICT d = dd; uint8_t s0, s1, v; s0 = early ? 0 : *s; s++; s1 = *s++; v = ((s0<<8) | s1)>>shift; if (op == JBIG2_COMPOSE_OR) *d++ |= v & leftmask; else if (op == JBIG2_COMPOSE_AND) *d++ &= (v & leftmask) | ~leftmask; else if (op == JBIG2_COMPOSE_XOR) *d++ ^= v & leftmask; else if (op == JBIG2_COMPOSE_XNOR) *d++ ^= (~v) & leftmask; else /* Replace */ *d = (v & leftmask) | (*d & ~leftmask), d++; /* Central run */ for (i = bytewidth; i > 0; i--) { s0 = s1; s1 = *s++; v = ((s0<<8) | s1)>>shift; if (op == JBIG2_COMPOSE_OR) *d++ |= v; else if (op == JBIG2_COMPOSE_AND) *d++ &= v; else if (op == JBIG2_COMPOSE_XOR) *d++ ^= v; else if (op == JBIG2_COMPOSE_XNOR) *d++ ^= ~v; else /* Replace */ *d++ = v; } /* Right byte */ s0 = s1; s1 = (late ? 0 : *s); v = (((s0<<8) | s1)>>shift); if (op == JBIG2_COMPOSE_OR) *d |= v & rightmask; else if (op == JBIG2_COMPOSE_AND) *d &= (v & rightmask) | ~rightmask; else if (op == JBIG2_COMPOSE_XOR) *d ^= v & rightmask; else if (op == JBIG2_COMPOSE_XNOR) *d ^= ~v & rightmask; else /* Replace */ *d = (v & rightmask) | (*d & ~rightmask); dd += dstride; ss += sstride; } } } static void jbig2_image_compose_opt_OR(const uint8_t *s, uint8_t *d, int early, int late, uint8_t mask, uint8_t rightmask, uint32_t bytewidth, uint32_t h, uint32_t shift, uint32_t dstride, uint32_t sstride) { if (early || late) template_image_compose_opt(s, d, early, late, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_OR); else template_image_compose_opt(s, d, 0, 0, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_OR); } static void jbig2_image_compose_opt_AND(const uint8_t *s, uint8_t *d, int early, int late, uint8_t mask, uint8_t rightmask, uint32_t bytewidth, uint32_t h, uint32_t shift, uint32_t dstride, uint32_t sstride) { if (early || late) template_image_compose_opt(s, d, early, late, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_AND); else template_image_compose_opt(s, d, 0, 0, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_AND); } static void jbig2_image_compose_opt_XOR(const uint8_t *s, uint8_t *d, int early, int late, uint8_t mask, uint8_t rightmask, uint32_t bytewidth, uint32_t h, uint32_t shift, uint32_t dstride, uint32_t sstride) { if (early || late) template_image_compose_opt(s, d, early, late, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_XOR); else template_image_compose_opt(s, d, 0, 0, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_XOR); } static void jbig2_image_compose_opt_XNOR(const uint8_t *s, uint8_t *d, int early, int late, uint8_t mask, uint8_t rightmask, uint32_t bytewidth, uint32_t h, uint32_t shift, uint32_t dstride, uint32_t sstride) { if (early || late) template_image_compose_opt(s, d, early, late, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_XNOR); else template_image_compose_opt(s, d, 0, 0, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_XNOR); } static void jbig2_image_compose_opt_REPLACE(const uint8_t *s, uint8_t *d, int early, int late, uint8_t mask, uint8_t rightmask, uint32_t bytewidth, uint32_t h, uint32_t shift, uint32_t dstride, uint32_t sstride) { if (early || late) template_image_compose_opt(s, d, early, late, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_REPLACE); else template_image_compose_opt(s, d, 0, 0, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_REPLACE); } /* composite one jbig2_image onto another */ int jbig2_image_compose(Jbig2Ctx *ctx, Jbig2Image *dst, Jbig2Image *src, int x, int y, Jbig2ComposeOp op) { uint32_t w, h; uint32_t shift; uint32_t leftbyte; uint8_t *ss; uint8_t *dd; uint8_t leftmask, rightmask; int early = x >= 0; int late; uint32_t bytewidth; uint32_t syoffset = 0; if (src == NULL) return 0; /* This code takes a src image and combines it onto dst at offset (x,y), with operation op. */ /* Data is packed msb first within a byte, so with bits numbered: 01234567. * Second byte is: 89abcdef. So to combine into a run, we use: * (s[0]<<8) | s[1] == 0123456789abcdef. * To read from src into dst at offset 3, we need to read: * read: 0123456789abcdef... * write: 0123456798abcdef... * In general, to read from src and write into dst at offset x, we need to shift * down by (x&7) bits to allow for bit alignment. So shift = x&7. * So the 'central' part of our runs will see us doing: * *d++ op= ((s[0]<<8)|s[1])>>shift; * with special cases on the left and right edges of the run to mask. * With the left hand edge, we have to be careful not to 'underread' the start of * the src image; this is what the early flag is about. Similarly we have to be * careful not to read off the right hand edge; this is what the late flag is for. */ /* clip */ w = src->width; h = src->height; shift = (x & 7); ss = src->data - early; if (x < 0) { if (w < (uint32_t) -x) w = 0; else w += x; ss += (-x-1)>>3; x = 0; } if (y < 0) { if (h < (uint32_t) -y) h = 0; else h += y; syoffset = -y * src->stride; y = 0; } if ((uint32_t)x + w > dst->width) { if (dst->width < (uint32_t)x) w = 0; else w = dst->width - x; } if ((uint32_t)y + h > dst->height) { if (dst->height < (uint32_t)y) h = 0; else h = dst->height - y; } #ifdef JBIG2_DEBUG jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "compositing %dx%d at (%d, %d) after clipping", w, h, x, y); #endif /* check for zero clipping region */ if ((w <= 0) || (h <= 0)) { #ifdef JBIG2_DEBUG jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "zero clipping region"); #endif return 0; } leftbyte = (uint32_t) x >> 3; dd = dst->data + y * dst->stride + leftbyte; bytewidth = (((uint32_t) x + w - 1) >> 3) - leftbyte + 1; leftmask = 255>>(x&7); rightmask = (((x+w)&7) == 0) ? 255 : ~(255>>((x+w)&7)); if (bytewidth == 1) leftmask &= rightmask; late = (ss + bytewidth >= src->data + ((src->width+7)>>3)); ss += syoffset; switch(op) { case JBIG2_COMPOSE_OR: jbig2_image_compose_opt_OR(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride); break; case JBIG2_COMPOSE_AND: jbig2_image_compose_opt_AND(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride); break; case JBIG2_COMPOSE_XOR: jbig2_image_compose_opt_XOR(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride); break; case JBIG2_COMPOSE_XNOR: jbig2_image_compose_opt_XNOR(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride); break; case JBIG2_COMPOSE_REPLACE: jbig2_image_compose_opt_REPLACE(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride); break; } return 0; } /* initialize an image bitmap to a constant value */ void jbig2_image_clear(Jbig2Ctx *ctx, Jbig2Image *image, int value) { const uint8_t fill = value ? 0xFF : 0x00; memset(image->data, fill, image->stride * image->height); } /* look up a pixel value in an image. returns 0 outside the image frame for the convenience of the template code */ int jbig2_image_get_pixel(Jbig2Image *image, int x, int y) { const int w = image->width; const int h = image->height; const int byte = (x >> 3) + y * image->stride; const int bit = 7 - (x & 7); if ((x < 0) || (x >= w)) return 0; if ((y < 0) || (y >= h)) return 0; return ((image->data[byte] >> bit) & 1); } /* set an individual pixel value in an image */ void jbig2_image_set_pixel(Jbig2Image *image, int x, int y, bool value) { const int w = image->width; const int h = image->height; int scratch, mask; int bit, byte; if ((x < 0) || (x >= w)) return; if ((y < 0) || (y >= h)) return; byte = (x >> 3) + y * image->stride; bit = 7 - (x & 7); mask = (1 << bit) ^ 0xff; scratch = image->data[byte] & mask; image->data[byte] = scratch | (value << bit); }
null
/* Copyright (C) 2001-2019 Artifex Software, Inc. All Rights Reserved. This software is provided AS-IS with no warranty, either express or implied. This software is distributed under license and may not be copied, modified or distributed except as expressly authorized under the terms of the license contained in the file LICENSE in this distribution. Refer to licensing information at http://www.artifex.com or contact Artifex Software, Inc., 1305 Grant Avenue - Suite 200, Novato, CA 94945, U.S.A., +1(415)492-9861, for further information. */ /* jbig2dec */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "os_types.h" #include <stdio.h> #include <stdlib.h> #include <string.h> /* memcpy() */ #include "jbig2.h" #include "jbig2_priv.h" #include "jbig2_image.h" #if !defined (INT32_MAX) #define INT32_MAX 0x7fffffff #endif #if !defined (UINT32_MAX) #define UINT32_MAX 0xffffffffu #endif /* allocate a Jbig2Image structure and its associated bitmap */ Jbig2Image * jbig2_image_new(Jbig2Ctx *ctx, uint32_t width, uint32_t height) { Jbig2Image *image; uint32_t stride; if (width == 0 || height == 0) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "failed to create zero sized image"); return NULL; } image = jbig2_new(ctx, Jbig2Image, 1); if (image == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "failed to allocate image"); return NULL; } stride = ((width - 1) >> 3) + 1; /* generate a byte-aligned stride */ /* check for integer multiplication overflow */ if (height > (INT32_MAX / stride)) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "integer multiplication overflow (stride=%u, height=%u)", stride, height); jbig2_free(ctx->allocator, image); return NULL; } image->data = jbig2_new(ctx, uint8_t, (size_t) height * stride); if (image->data == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "failed to allocate image data buffer (stride=%u, height=%u)", stride, height); jbig2_free(ctx->allocator, image); return NULL; } image->width = width; image->height = height; image->stride = stride; image->refcount = 1; return image; } /* bump the reference count for an image pointer */ Jbig2Image * jbig2_image_reference(Jbig2Ctx *ctx, Jbig2Image *image) { if (image) image->refcount++; return image; } /* release an image pointer, freeing it it appropriate */ void jbig2_image_release(Jbig2Ctx *ctx, Jbig2Image *image) { if (image == NULL) return; image->refcount--; if (image->refcount == 0) jbig2_image_free(ctx, image); } /* free a Jbig2Image structure and its associated memory */ void jbig2_image_free(Jbig2Ctx *ctx, Jbig2Image *image) { if (image != NULL) { jbig2_free(ctx->allocator, image->data); jbig2_free(ctx->allocator, image); } } /* resize a Jbig2Image */ Jbig2Image * jbig2_image_resize(Jbig2Ctx *ctx, Jbig2Image *image, uint32_t width, uint32_t height, int value) { if (width == image->width) { uint8_t *data; /* check for integer multiplication overflow */ if (image->height > (INT32_MAX / image->stride)) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "integer multiplication overflow during resize (stride=%u, height=%u)", image->stride, height); return NULL; } /* use the same stride, just change the length */ data = jbig2_renew(ctx, image->data, uint8_t, (size_t) height * image->stride); if (data == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "failed to reallocate image"); return NULL; } image->data = data; if (height > image->height) { const uint8_t fill = value ? 0xFF : 0x00; memset(image->data + (size_t) image->height * image->stride, fill, ((size_t) height - image->height) * image->stride); } image->height = height; } else { Jbig2Image *newimage; int code; /* Unoptimized implementation, but it works. */ newimage = jbig2_image_new(ctx, width, height); if (newimage == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "failed to allocate resized image"); return NULL; } jbig2_image_clear(ctx, newimage, value); code = jbig2_image_compose(ctx, newimage, image, 0, 0, JBIG2_COMPOSE_REPLACE); if (code < 0) { jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "failed to compose image buffers when resizing"); jbig2_image_release(ctx, newimage); return NULL; } /* if refcount > 1 the original image, its pointer must be kept, so simply replaces its innards, and throw away the empty new image shell. */ jbig2_free(ctx->allocator, image->data); image->width = newimage->width; image->height = newimage->height; image->stride = newimage->stride; image->data = newimage->data; jbig2_free(ctx->allocator, newimage); } return image; } static inline void template_image_compose_opt(const uint8_t * JBIG2_RESTRICT ss, uint8_t * JBIG2_RESTRICT dd, int early, int late, uint8_t leftmask, uint8_t rightmask, uint32_t bytewidth_, uint32_t h, uint32_t shift, uint32_t dstride, uint32_t sstride, Jbig2ComposeOp op) { int i; uint32_t j; int bytewidth = (int)bytewidth_; if (bytewidth == 1) { for (j = 0; j < h; j++) { /* Only 1 byte! */ uint8_t v = (((early ? 0 : ss[0]<<8) | (late ? 0 : ss[1]))>>shift); if (op == JBIG2_COMPOSE_OR) *dd |= v & leftmask; else if (op == JBIG2_COMPOSE_AND) *dd &= (v & leftmask) | ~leftmask; else if (op == JBIG2_COMPOSE_XOR) *dd ^= v & leftmask; else if (op == JBIG2_COMPOSE_XNOR) *dd ^= (~v) & leftmask; else /* Replace */ *dd = (v & leftmask) | (*dd & ~leftmask); dd += dstride; ss += sstride; } return; } bytewidth -= 2; if (shift == 0) { ss++; for (j = 0; j < h; j++) { /* Left byte */ const uint8_t * JBIG2_RESTRICT s = ss; uint8_t * JBIG2_RESTRICT d = dd; if (op == JBIG2_COMPOSE_OR) *d++ |= *s++ & leftmask; else if (op == JBIG2_COMPOSE_AND) *d++ &= (*s++ & leftmask) | ~leftmask; else if (op == JBIG2_COMPOSE_XOR) *d++ ^= *s++ & leftmask; else if (op == JBIG2_COMPOSE_XNOR) *d++ ^= (~*s++) & leftmask; else /* Replace */ *d = (*s++ & leftmask) | (*d & ~leftmask), d++; /* Central run */ for (i = bytewidth; i != 0; i--) { if (op == JBIG2_COMPOSE_OR) *d++ |= *s++; else if (op == JBIG2_COMPOSE_AND) *d++ &= *s++; else if (op == JBIG2_COMPOSE_XOR) *d++ ^= *s++; else if (op == JBIG2_COMPOSE_XNOR) *d++ ^= ~*s++; else /* Replace */ *d++ = *s++; } /* Right byte */ if (op == JBIG2_COMPOSE_OR) *d |= *s & rightmask; else if (op == JBIG2_COMPOSE_AND) *d &= (*s & rightmask) | ~rightmask; else if (op == JBIG2_COMPOSE_XOR) *d ^= *s & rightmask; else if (op == JBIG2_COMPOSE_XNOR) *d ^= (~*s) & rightmask; else /* Replace */ *d = (*s & rightmask) | (*d & ~rightmask); dd += dstride; ss += sstride; } } else { for (j = 0; j < h; j++) { /* Left byte */ const uint8_t * JBIG2_RESTRICT s = ss; uint8_t * JBIG2_RESTRICT d = dd; uint8_t s0, s1, v; s0 = early ? 0 : *s; s++; s1 = *s++; v = ((s0<<8) | s1)>>shift; if (op == JBIG2_COMPOSE_OR) *d++ |= v & leftmask; else if (op == JBIG2_COMPOSE_AND) *d++ &= (v & leftmask) | ~leftmask; else if (op == JBIG2_COMPOSE_XOR) *d++ ^= v & leftmask; else if (op == JBIG2_COMPOSE_XNOR) *d++ ^= (~v) & leftmask; else /* Replace */ *d = (v & leftmask) | (*d & ~leftmask), d++; /* Central run */ for (i = bytewidth; i > 0; i--) { s0 = s1; s1 = *s++; v = ((s0<<8) | s1)>>shift; if (op == JBIG2_COMPOSE_OR) *d++ |= v; else if (op == JBIG2_COMPOSE_AND) *d++ &= v; else if (op == JBIG2_COMPOSE_XOR) *d++ ^= v; else if (op == JBIG2_COMPOSE_XNOR) *d++ ^= ~v; else /* Replace */ *d++ = v; } /* Right byte */ s0 = s1; s1 = (late ? 0 : *s); v = (((s0<<8) | s1)>>shift); if (op == JBIG2_COMPOSE_OR) *d |= v & rightmask; else if (op == JBIG2_COMPOSE_AND) *d &= (v & rightmask) | ~rightmask; else if (op == JBIG2_COMPOSE_XOR) *d ^= v & rightmask; else if (op == JBIG2_COMPOSE_XNOR) *d ^= ~v & rightmask; else /* Replace */ *d = (v & rightmask) | (*d & ~rightmask); dd += dstride; ss += sstride; } } } static void jbig2_image_compose_opt_OR(const uint8_t *s, uint8_t *d, int early, int late, uint8_t mask, uint8_t rightmask, uint32_t bytewidth, uint32_t h, uint32_t shift, uint32_t dstride, uint32_t sstride) { if (early || late) template_image_compose_opt(s, d, early, late, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_OR); else template_image_compose_opt(s, d, 0, 0, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_OR); } static void jbig2_image_compose_opt_AND(const uint8_t *s, uint8_t *d, int early, int late, uint8_t mask, uint8_t rightmask, uint32_t bytewidth, uint32_t h, uint32_t shift, uint32_t dstride, uint32_t sstride) { if (early || late) template_image_compose_opt(s, d, early, late, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_AND); else template_image_compose_opt(s, d, 0, 0, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_AND); } static void jbig2_image_compose_opt_XOR(const uint8_t *s, uint8_t *d, int early, int late, uint8_t mask, uint8_t rightmask, uint32_t bytewidth, uint32_t h, uint32_t shift, uint32_t dstride, uint32_t sstride) { if (early || late) template_image_compose_opt(s, d, early, late, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_XOR); else template_image_compose_opt(s, d, 0, 0, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_XOR); } static void jbig2_image_compose_opt_XNOR(const uint8_t *s, uint8_t *d, int early, int late, uint8_t mask, uint8_t rightmask, uint32_t bytewidth, uint32_t h, uint32_t shift, uint32_t dstride, uint32_t sstride) { if (early || late) template_image_compose_opt(s, d, early, late, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_XNOR); else template_image_compose_opt(s, d, 0, 0, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_XNOR); } static void jbig2_image_compose_opt_REPLACE(const uint8_t *s, uint8_t *d, int early, int late, uint8_t mask, uint8_t rightmask, uint32_t bytewidth, uint32_t h, uint32_t shift, uint32_t dstride, uint32_t sstride) { if (early || late) template_image_compose_opt(s, d, early, late, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_REPLACE); else template_image_compose_opt(s, d, 0, 0, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_REPLACE); } /* composite one jbig2_image onto another */ int jbig2_image_compose(Jbig2Ctx *ctx, Jbig2Image *dst, Jbig2Image *src, int x, int y, Jbig2ComposeOp op) { uint32_t w, h; uint32_t shift; uint32_t leftbyte; uint8_t *ss; uint8_t *dd; uint8_t leftmask, rightmask; int early = x >= 0; int late; uint32_t bytewidth; uint32_t syoffset = 0; if (src == NULL) return 0; if ((UINT32_MAX - src->width < (x > 0 ? x : -x)) || (UINT32_MAX - src->height < (y > 0 ? y : -y))) { #ifdef JBIG2_DEBUG jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "overflow in compose_image"); #endif return 0; } /* This code takes a src image and combines it onto dst at offset (x,y), with operation op. */ /* Data is packed msb first within a byte, so with bits numbered: 01234567. * Second byte is: 89abcdef. So to combine into a run, we use: * (s[0]<<8) | s[1] == 0123456789abcdef. * To read from src into dst at offset 3, we need to read: * read: 0123456789abcdef... * write: 0123456798abcdef... * In general, to read from src and write into dst at offset x, we need to shift * down by (x&7) bits to allow for bit alignment. So shift = x&7. * So the 'central' part of our runs will see us doing: * *d++ op= ((s[0]<<8)|s[1])>>shift; * with special cases on the left and right edges of the run to mask. * With the left hand edge, we have to be careful not to 'underread' the start of * the src image; this is what the early flag is about. Similarly we have to be * careful not to read off the right hand edge; this is what the late flag is for. */ /* clip */ w = src->width; h = src->height; shift = (x & 7); ss = src->data - early; if (x < 0) { if (w < (uint32_t) -x) w = 0; else w += x; ss += (-x-1)>>3; x = 0; } if (y < 0) { if (h < (uint32_t) -y) h = 0; else h += y; syoffset = -y * src->stride; y = 0; } if ((uint32_t)x + w > dst->width) { if (dst->width < (uint32_t)x) w = 0; else w = dst->width - x; } if ((uint32_t)y + h > dst->height) { if (dst->height < (uint32_t)y) h = 0; else h = dst->height - y; } #ifdef JBIG2_DEBUG jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "compositing %dx%d at (%d, %d) after clipping", w, h, x, y); #endif /* check for zero clipping region */ if ((w <= 0) || (h <= 0)) { #ifdef JBIG2_DEBUG jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "zero clipping region"); #endif return 0; } leftbyte = (uint32_t) x >> 3; dd = dst->data + y * dst->stride + leftbyte; bytewidth = (((uint32_t) x + w - 1) >> 3) - leftbyte + 1; leftmask = 255>>(x&7); rightmask = (((x+w)&7) == 0) ? 255 : ~(255>>((x+w)&7)); if (bytewidth == 1) leftmask &= rightmask; late = (ss + bytewidth >= src->data + ((src->width+7)>>3)); ss += syoffset; switch(op) { case JBIG2_COMPOSE_OR: jbig2_image_compose_opt_OR(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride); break; case JBIG2_COMPOSE_AND: jbig2_image_compose_opt_AND(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride); break; case JBIG2_COMPOSE_XOR: jbig2_image_compose_opt_XOR(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride); break; case JBIG2_COMPOSE_XNOR: jbig2_image_compose_opt_XNOR(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride); break; case JBIG2_COMPOSE_REPLACE: jbig2_image_compose_opt_REPLACE(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride); break; } return 0; } /* initialize an image bitmap to a constant value */ void jbig2_image_clear(Jbig2Ctx *ctx, Jbig2Image *image, int value) { const uint8_t fill = value ? 0xFF : 0x00; memset(image->data, fill, image->stride * image->height); } /* look up a pixel value in an image. returns 0 outside the image frame for the convenience of the template code */ int jbig2_image_get_pixel(Jbig2Image *image, int x, int y) { const int w = image->width; const int h = image->height; const int byte = (x >> 3) + y * image->stride; const int bit = 7 - (x & 7); if ((x < 0) || (x >= w)) return 0; if ((y < 0) || (y >= h)) return 0; return ((image->data[byte] >> bit) & 1); } /* set an individual pixel value in an image */ void jbig2_image_set_pixel(Jbig2Image *image, int x, int y, bool value) { const int w = image->width; const int h = image->height; int scratch, mask; int bit, byte; if ((x < 0) || (x >= w)) return; if ((y < 0) || (y >= h)) return; byte = (x >> 3) + y * image->stride; bit = 7 - (x & 7); mask = (1 << bit) ^ 0xff; scratch = image->data[byte] & mask; image->data[byte] = scratch | (value << bit); }
null
168
CWE-787
CVE-2020-12284
/* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cbs.h" #include "cbs_internal.h" #include "cbs_jpeg.h" #define HEADER(name) do { \ ff_cbs_trace_header(ctx, name); \ } while (0) #define CHECK(call) do { \ err = (call); \ if (err < 0) \ return err; \ } while (0) #define SUBSCRIPTS(subs, ...) (subs > 0 ? ((int[subs + 1]){ subs, __VA_ARGS__ }) : NULL) #define u(width, name, range_min, range_max) \ xu(width, name, range_min, range_max, 0) #define us(width, name, sub, range_min, range_max) \ xu(width, name, range_min, range_max, 1, sub) #define READ #define READWRITE read #define RWContext GetBitContext #define FUNC(name) cbs_jpeg_read_ ## name #define xu(width, name, range_min, range_max, subs, ...) do { \ uint32_t value; \ CHECK(ff_cbs_read_unsigned(ctx, rw, width, #name, \ SUBSCRIPTS(subs, __VA_ARGS__), \ &value, range_min, range_max)); \ current->name = value; \ } while (0) #include "cbs_jpeg_syntax_template.c" #undef READ #undef READWRITE #undef RWContext #undef FUNC #undef xu #define WRITE #define READWRITE write #define RWContext PutBitContext #define FUNC(name) cbs_jpeg_write_ ## name #define xu(width, name, range_min, range_max, subs, ...) do { \ uint32_t value = current->name; \ CHECK(ff_cbs_write_unsigned(ctx, rw, width, #name, \ SUBSCRIPTS(subs, __VA_ARGS__), \ value, range_min, range_max)); \ } while (0) #include "cbs_jpeg_syntax_template.c" #undef WRITE #undef READWRITE #undef RWContext #undef FUNC #undef xu static void cbs_jpeg_free_application_data(void *opaque, uint8_t *content) { JPEGRawApplicationData *ad = (JPEGRawApplicationData*)content; av_buffer_unref(&ad->Ap_ref); av_freep(&content); } static void cbs_jpeg_free_comment(void *opaque, uint8_t *content) { JPEGRawComment *comment = (JPEGRawComment*)content; av_buffer_unref(&comment->Cm_ref); av_freep(&content); } static void cbs_jpeg_free_scan(void *opaque, uint8_t *content) { JPEGRawScan *scan = (JPEGRawScan*)content; av_buffer_unref(&scan->data_ref); av_freep(&content); } static int cbs_jpeg_split_fragment(CodedBitstreamContext *ctx, CodedBitstreamFragment *frag, int header) { AVBufferRef *data_ref; uint8_t *data; size_t data_size; int unit, start, end, marker, next_start, next_marker; int err, i, j, length; if (frag->data_size < 4) { // Definitely too short to be meaningful. return AVERROR_INVALIDDATA; } for (i = 0; i + 1 < frag->data_size && frag->data[i] != 0xff; i++); if (i > 0) { av_log(ctx->log_ctx, AV_LOG_WARNING, "Discarding %d bytes at " "beginning of image.\n", i); } for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size && frag->data[i]) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: " "no SOI marker found.\n"); return AVERROR_INVALIDDATA; } marker = frag->data[i]; if (marker != JPEG_MARKER_SOI) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: first " "marker is %02x, should be SOI.\n", marker); return AVERROR_INVALIDDATA; } for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: " "no image content found.\n"); return AVERROR_INVALIDDATA; } marker = frag->data[i]; start = i + 1; for (unit = 0;; unit++) { if (marker == JPEG_MARKER_EOI) { break; } else if (marker == JPEG_MARKER_SOS) { for (i = start; i + 1 < frag->data_size; i++) { if (frag->data[i] != 0xff) continue; end = i; for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size) { next_marker = -1; } else { if (frag->data[i] == 0x00) continue; next_marker = frag->data[i]; next_start = i + 1; } break; } } else { i = start; if (i + 2 > frag->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: " "truncated at %02x marker.\n", marker); return AVERROR_INVALIDDATA; } length = AV_RB16(frag->data + i); if (i + length > frag->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: " "truncated at %02x marker segment.\n", marker); return AVERROR_INVALIDDATA; } end = start + length; i = end; if (frag->data[i] != 0xff) { next_marker = -1; } else { for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size) { next_marker = -1; } else { next_marker = frag->data[i]; next_start = i + 1; } } } if (marker == JPEG_MARKER_SOS) { length = AV_RB16(frag->data + start); data_ref = NULL; data = av_malloc(end - start + AV_INPUT_BUFFER_PADDING_SIZE); if (!data) return AVERROR(ENOMEM); memcpy(data, frag->data + start, length); for (i = start + length, j = length; i < end; i++, j++) { if (frag->data[i] == 0xff) { while (frag->data[i] == 0xff) ++i; data[j] = 0xff; } else { data[j] = frag->data[i]; } } data_size = j; memset(data + data_size, 0, AV_INPUT_BUFFER_PADDING_SIZE); } else { data = frag->data + start; data_size = end - start; data_ref = frag->data_ref; } err = ff_cbs_insert_unit_data(ctx, frag, unit, marker, data, data_size, data_ref); if (err < 0) return err; if (next_marker == -1) break; marker = next_marker; start = next_start; } return 0; } static int cbs_jpeg_read_unit(CodedBitstreamContext *ctx, CodedBitstreamUnit *unit) { GetBitContext gbc; int err; err = init_get_bits(&gbc, unit->data, 8 * unit->data_size); if (err < 0) return err; if (unit->type >= JPEG_MARKER_SOF0 && unit->type <= JPEG_MARKER_SOF3) { err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(JPEGRawFrameHeader), NULL); if (err < 0) return err; err = cbs_jpeg_read_frame_header(ctx, &gbc, unit->content); if (err < 0) return err; } else if (unit->type >= JPEG_MARKER_APPN && unit->type <= JPEG_MARKER_APPN + 15) { err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(JPEGRawApplicationData), &cbs_jpeg_free_application_data); if (err < 0) return err; err = cbs_jpeg_read_application_data(ctx, &gbc, unit->content); if (err < 0) return err; } else if (unit->type == JPEG_MARKER_SOS) { JPEGRawScan *scan; int pos; err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(JPEGRawScan), &cbs_jpeg_free_scan); if (err < 0) return err; scan = unit->content; err = cbs_jpeg_read_scan_header(ctx, &gbc, &scan->header); if (err < 0) return err; pos = get_bits_count(&gbc); av_assert0(pos % 8 == 0); if (pos > 0) { scan->data_size = unit->data_size - pos / 8; scan->data_ref = av_buffer_ref(unit->data_ref); if (!scan->data_ref) return AVERROR(ENOMEM); scan->data = unit->data + pos / 8; } } else { switch (unit->type) { #define SEGMENT(marker, type, func, free) \ case JPEG_MARKER_ ## marker: \ { \ err = ff_cbs_alloc_unit_content(ctx, unit, \ sizeof(type), free); \ if (err < 0) \ return err; \ err = cbs_jpeg_read_ ## func(ctx, &gbc, unit->content); \ if (err < 0) \ return err; \ } \ break SEGMENT(DQT, JPEGRawQuantisationTableSpecification, dqt, NULL); SEGMENT(DHT, JPEGRawHuffmanTableSpecification, dht, NULL); SEGMENT(COM, JPEGRawComment, comment, &cbs_jpeg_free_comment); #undef SEGMENT default: return AVERROR(ENOSYS); } } return 0; } static int cbs_jpeg_write_scan(CodedBitstreamContext *ctx, CodedBitstreamUnit *unit, PutBitContext *pbc) { JPEGRawScan *scan = unit->content; int err; err = cbs_jpeg_write_scan_header(ctx, pbc, &scan->header); if (err < 0) return err; if (scan->data) { if (scan->data_size * 8 > put_bits_left(pbc)) return AVERROR(ENOSPC); av_assert0(put_bits_count(pbc) % 8 == 0); flush_put_bits(pbc); memcpy(put_bits_ptr(pbc), scan->data, scan->data_size); skip_put_bytes(pbc, scan->data_size); } return 0; } static int cbs_jpeg_write_segment(CodedBitstreamContext *ctx, CodedBitstreamUnit *unit, PutBitContext *pbc) { int err; if (unit->type >= JPEG_MARKER_SOF0 && unit->type <= JPEG_MARKER_SOF3) { err = cbs_jpeg_write_frame_header(ctx, pbc, unit->content); } else if (unit->type >= JPEG_MARKER_APPN && unit->type <= JPEG_MARKER_APPN + 15) { err = cbs_jpeg_write_application_data(ctx, pbc, unit->content); } else { switch (unit->type) { #define SEGMENT(marker, func) \ case JPEG_MARKER_ ## marker: \ err = cbs_jpeg_write_ ## func(ctx, pbc, unit->content); \ break; SEGMENT(DQT, dqt); SEGMENT(DHT, dht); SEGMENT(COM, comment); default: return AVERROR_PATCHWELCOME; } } return err; } static int cbs_jpeg_write_unit(CodedBitstreamContext *ctx, CodedBitstreamUnit *unit, PutBitContext *pbc) { if (unit->type == JPEG_MARKER_SOS) return cbs_jpeg_write_scan (ctx, unit, pbc); else return cbs_jpeg_write_segment(ctx, unit, pbc); } static int cbs_jpeg_assemble_fragment(CodedBitstreamContext *ctx, CodedBitstreamFragment *frag) { const CodedBitstreamUnit *unit; uint8_t *data; size_t size, dp, sp; int i; size = 4; // SOI + EOI. for (i = 0; i < frag->nb_units; i++) { unit = &frag->units[i]; size += 2 + unit->data_size; if (unit->type == JPEG_MARKER_SOS) { for (sp = 0; sp < unit->data_size; sp++) { if (unit->data[sp] == 0xff) ++size; } } } frag->data_ref = av_buffer_alloc(size + AV_INPUT_BUFFER_PADDING_SIZE); if (!frag->data_ref) return AVERROR(ENOMEM); data = frag->data_ref->data; dp = 0; data[dp++] = 0xff; data[dp++] = JPEG_MARKER_SOI; for (i = 0; i < frag->nb_units; i++) { unit = &frag->units[i]; data[dp++] = 0xff; data[dp++] = unit->type; if (unit->type != JPEG_MARKER_SOS) { memcpy(data + dp, unit->data, unit->data_size); dp += unit->data_size; } else { sp = AV_RB16(unit->data); av_assert0(sp <= unit->data_size); memcpy(data + dp, unit->data, sp); dp += sp; for (; sp < unit->data_size; sp++) { if (unit->data[sp] == 0xff) { data[dp++] = 0xff; data[dp++] = 0x00; } else { data[dp++] = unit->data[sp]; } } } } data[dp++] = 0xff; data[dp++] = JPEG_MARKER_EOI; av_assert0(dp == size); memset(data + size, 0, AV_INPUT_BUFFER_PADDING_SIZE); frag->data = data; frag->data_size = size; return 0; } const CodedBitstreamType ff_cbs_type_jpeg = { .codec_id = AV_CODEC_ID_MJPEG, .split_fragment = &cbs_jpeg_split_fragment, .read_unit = &cbs_jpeg_read_unit, .write_unit = &cbs_jpeg_write_unit, .assemble_fragment = &cbs_jpeg_assemble_fragment, };
null
/* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cbs.h" #include "cbs_internal.h" #include "cbs_jpeg.h" #define HEADER(name) do { \ ff_cbs_trace_header(ctx, name); \ } while (0) #define CHECK(call) do { \ err = (call); \ if (err < 0) \ return err; \ } while (0) #define SUBSCRIPTS(subs, ...) (subs > 0 ? ((int[subs + 1]){ subs, __VA_ARGS__ }) : NULL) #define u(width, name, range_min, range_max) \ xu(width, name, range_min, range_max, 0) #define us(width, name, sub, range_min, range_max) \ xu(width, name, range_min, range_max, 1, sub) #define READ #define READWRITE read #define RWContext GetBitContext #define FUNC(name) cbs_jpeg_read_ ## name #define xu(width, name, range_min, range_max, subs, ...) do { \ uint32_t value; \ CHECK(ff_cbs_read_unsigned(ctx, rw, width, #name, \ SUBSCRIPTS(subs, __VA_ARGS__), \ &value, range_min, range_max)); \ current->name = value; \ } while (0) #include "cbs_jpeg_syntax_template.c" #undef READ #undef READWRITE #undef RWContext #undef FUNC #undef xu #define WRITE #define READWRITE write #define RWContext PutBitContext #define FUNC(name) cbs_jpeg_write_ ## name #define xu(width, name, range_min, range_max, subs, ...) do { \ uint32_t value = current->name; \ CHECK(ff_cbs_write_unsigned(ctx, rw, width, #name, \ SUBSCRIPTS(subs, __VA_ARGS__), \ value, range_min, range_max)); \ } while (0) #include "cbs_jpeg_syntax_template.c" #undef WRITE #undef READWRITE #undef RWContext #undef FUNC #undef xu static void cbs_jpeg_free_application_data(void *opaque, uint8_t *content) { JPEGRawApplicationData *ad = (JPEGRawApplicationData*)content; av_buffer_unref(&ad->Ap_ref); av_freep(&content); } static void cbs_jpeg_free_comment(void *opaque, uint8_t *content) { JPEGRawComment *comment = (JPEGRawComment*)content; av_buffer_unref(&comment->Cm_ref); av_freep(&content); } static void cbs_jpeg_free_scan(void *opaque, uint8_t *content) { JPEGRawScan *scan = (JPEGRawScan*)content; av_buffer_unref(&scan->data_ref); av_freep(&content); } static int cbs_jpeg_split_fragment(CodedBitstreamContext *ctx, CodedBitstreamFragment *frag, int header) { AVBufferRef *data_ref; uint8_t *data; size_t data_size; int unit, start, end, marker, next_start, next_marker; int err, i, j, length; if (frag->data_size < 4) { // Definitely too short to be meaningful. return AVERROR_INVALIDDATA; } for (i = 0; i + 1 < frag->data_size && frag->data[i] != 0xff; i++); if (i > 0) { av_log(ctx->log_ctx, AV_LOG_WARNING, "Discarding %d bytes at " "beginning of image.\n", i); } for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size && frag->data[i]) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: " "no SOI marker found.\n"); return AVERROR_INVALIDDATA; } marker = frag->data[i]; if (marker != JPEG_MARKER_SOI) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: first " "marker is %02x, should be SOI.\n", marker); return AVERROR_INVALIDDATA; } for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: " "no image content found.\n"); return AVERROR_INVALIDDATA; } marker = frag->data[i]; start = i + 1; for (unit = 0;; unit++) { if (marker == JPEG_MARKER_EOI) { break; } else if (marker == JPEG_MARKER_SOS) { for (i = start; i + 1 < frag->data_size; i++) { if (frag->data[i] != 0xff) continue; end = i; for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size) { next_marker = -1; } else { if (frag->data[i] == 0x00) continue; next_marker = frag->data[i]; next_start = i + 1; } break; } } else { i = start; if (i + 2 > frag->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: " "truncated at %02x marker.\n", marker); return AVERROR_INVALIDDATA; } length = AV_RB16(frag->data + i); if (i + length > frag->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: " "truncated at %02x marker segment.\n", marker); return AVERROR_INVALIDDATA; } end = start + length; i = end; if (frag->data[i] != 0xff) { next_marker = -1; } else { for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size) { next_marker = -1; } else { next_marker = frag->data[i]; next_start = i + 1; } } } if (marker == JPEG_MARKER_SOS) { length = AV_RB16(frag->data + start); if (length > end - start) return AVERROR_INVALIDDATA; data_ref = NULL; data = av_malloc(end - start + AV_INPUT_BUFFER_PADDING_SIZE); if (!data) return AVERROR(ENOMEM); memcpy(data, frag->data + start, length); for (i = start + length, j = length; i < end; i++, j++) { if (frag->data[i] == 0xff) { while (frag->data[i] == 0xff) ++i; data[j] = 0xff; } else { data[j] = frag->data[i]; } } data_size = j; memset(data + data_size, 0, AV_INPUT_BUFFER_PADDING_SIZE); } else { data = frag->data + start; data_size = end - start; data_ref = frag->data_ref; } err = ff_cbs_insert_unit_data(ctx, frag, unit, marker, data, data_size, data_ref); if (err < 0) return err; if (next_marker == -1) break; marker = next_marker; start = next_start; } return 0; } static int cbs_jpeg_read_unit(CodedBitstreamContext *ctx, CodedBitstreamUnit *unit) { GetBitContext gbc; int err; err = init_get_bits(&gbc, unit->data, 8 * unit->data_size); if (err < 0) return err; if (unit->type >= JPEG_MARKER_SOF0 && unit->type <= JPEG_MARKER_SOF3) { err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(JPEGRawFrameHeader), NULL); if (err < 0) return err; err = cbs_jpeg_read_frame_header(ctx, &gbc, unit->content); if (err < 0) return err; } else if (unit->type >= JPEG_MARKER_APPN && unit->type <= JPEG_MARKER_APPN + 15) { err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(JPEGRawApplicationData), &cbs_jpeg_free_application_data); if (err < 0) return err; err = cbs_jpeg_read_application_data(ctx, &gbc, unit->content); if (err < 0) return err; } else if (unit->type == JPEG_MARKER_SOS) { JPEGRawScan *scan; int pos; err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(JPEGRawScan), &cbs_jpeg_free_scan); if (err < 0) return err; scan = unit->content; err = cbs_jpeg_read_scan_header(ctx, &gbc, &scan->header); if (err < 0) return err; pos = get_bits_count(&gbc); av_assert0(pos % 8 == 0); if (pos > 0) { scan->data_size = unit->data_size - pos / 8; scan->data_ref = av_buffer_ref(unit->data_ref); if (!scan->data_ref) return AVERROR(ENOMEM); scan->data = unit->data + pos / 8; } } else { switch (unit->type) { #define SEGMENT(marker, type, func, free) \ case JPEG_MARKER_ ## marker: \ { \ err = ff_cbs_alloc_unit_content(ctx, unit, \ sizeof(type), free); \ if (err < 0) \ return err; \ err = cbs_jpeg_read_ ## func(ctx, &gbc, unit->content); \ if (err < 0) \ return err; \ } \ break SEGMENT(DQT, JPEGRawQuantisationTableSpecification, dqt, NULL); SEGMENT(DHT, JPEGRawHuffmanTableSpecification, dht, NULL); SEGMENT(COM, JPEGRawComment, comment, &cbs_jpeg_free_comment); #undef SEGMENT default: return AVERROR(ENOSYS); } } return 0; } static int cbs_jpeg_write_scan(CodedBitstreamContext *ctx, CodedBitstreamUnit *unit, PutBitContext *pbc) { JPEGRawScan *scan = unit->content; int err; err = cbs_jpeg_write_scan_header(ctx, pbc, &scan->header); if (err < 0) return err; if (scan->data) { if (scan->data_size * 8 > put_bits_left(pbc)) return AVERROR(ENOSPC); av_assert0(put_bits_count(pbc) % 8 == 0); flush_put_bits(pbc); memcpy(put_bits_ptr(pbc), scan->data, scan->data_size); skip_put_bytes(pbc, scan->data_size); } return 0; } static int cbs_jpeg_write_segment(CodedBitstreamContext *ctx, CodedBitstreamUnit *unit, PutBitContext *pbc) { int err; if (unit->type >= JPEG_MARKER_SOF0 && unit->type <= JPEG_MARKER_SOF3) { err = cbs_jpeg_write_frame_header(ctx, pbc, unit->content); } else if (unit->type >= JPEG_MARKER_APPN && unit->type <= JPEG_MARKER_APPN + 15) { err = cbs_jpeg_write_application_data(ctx, pbc, unit->content); } else { switch (unit->type) { #define SEGMENT(marker, func) \ case JPEG_MARKER_ ## marker: \ err = cbs_jpeg_write_ ## func(ctx, pbc, unit->content); \ break; SEGMENT(DQT, dqt); SEGMENT(DHT, dht); SEGMENT(COM, comment); default: return AVERROR_PATCHWELCOME; } } return err; } static int cbs_jpeg_write_unit(CodedBitstreamContext *ctx, CodedBitstreamUnit *unit, PutBitContext *pbc) { if (unit->type == JPEG_MARKER_SOS) return cbs_jpeg_write_scan (ctx, unit, pbc); else return cbs_jpeg_write_segment(ctx, unit, pbc); } static int cbs_jpeg_assemble_fragment(CodedBitstreamContext *ctx, CodedBitstreamFragment *frag) { const CodedBitstreamUnit *unit; uint8_t *data; size_t size, dp, sp; int i; size = 4; // SOI + EOI. for (i = 0; i < frag->nb_units; i++) { unit = &frag->units[i]; size += 2 + unit->data_size; if (unit->type == JPEG_MARKER_SOS) { for (sp = 0; sp < unit->data_size; sp++) { if (unit->data[sp] == 0xff) ++size; } } } frag->data_ref = av_buffer_alloc(size + AV_INPUT_BUFFER_PADDING_SIZE); if (!frag->data_ref) return AVERROR(ENOMEM); data = frag->data_ref->data; dp = 0; data[dp++] = 0xff; data[dp++] = JPEG_MARKER_SOI; for (i = 0; i < frag->nb_units; i++) { unit = &frag->units[i]; data[dp++] = 0xff; data[dp++] = unit->type; if (unit->type != JPEG_MARKER_SOS) { memcpy(data + dp, unit->data, unit->data_size); dp += unit->data_size; } else { sp = AV_RB16(unit->data); av_assert0(sp <= unit->data_size); memcpy(data + dp, unit->data, sp); dp += sp; for (; sp < unit->data_size; sp++) { if (unit->data[sp] == 0xff) { data[dp++] = 0xff; data[dp++] = 0x00; } else { data[dp++] = unit->data[sp]; } } } } data[dp++] = 0xff; data[dp++] = JPEG_MARKER_EOI; av_assert0(dp == size); memset(data + size, 0, AV_INPUT_BUFFER_PADDING_SIZE); frag->data = data; frag->data_size = size; return 0; } const CodedBitstreamType ff_cbs_type_jpeg = { .codec_id = AV_CODEC_ID_MJPEG, .split_fragment = &cbs_jpeg_split_fragment, .read_unit = &cbs_jpeg_read_unit, .write_unit = &cbs_jpeg_write_unit, .assemble_fragment = &cbs_jpeg_assemble_fragment, };
null
169
CWE-787
CVE-2020-12653
/* * Marvell Wireless LAN device driver: scan ioctl and command handling * * Copyright (C) 2011-2014, Marvell International Ltd. * * This software file (the "File") is distributed by Marvell International * Ltd. under the terms of the GNU General Public License Version 2, June 1991 * (the "License"). You may use, redistribute and/or modify this File in * accordance with the terms and conditions of the License, a copy of which * is available by writing to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the * worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE * IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE * ARE EXPRESSLY DISCLAIMED. The License provides additional details about * this warranty disclaimer. */ #include "decl.h" #include "ioctl.h" #include "util.h" #include "fw.h" #include "main.h" #include "11n.h" #include "cfg80211.h" /* The maximum number of channels the firmware can scan per command */ #define MWIFIEX_MAX_CHANNELS_PER_SPECIFIC_SCAN 14 #define MWIFIEX_DEF_CHANNELS_PER_SCAN_CMD 4 /* Memory needed to store a max sized Channel List TLV for a firmware scan */ #define CHAN_TLV_MAX_SIZE (sizeof(struct mwifiex_ie_types_header) \ + (MWIFIEX_MAX_CHANNELS_PER_SPECIFIC_SCAN \ *sizeof(struct mwifiex_chan_scan_param_set))) /* Memory needed to store supported rate */ #define RATE_TLV_MAX_SIZE (sizeof(struct mwifiex_ie_types_rates_param_set) \ + HOSTCMD_SUPPORTED_RATES) /* Memory needed to store a max number/size WildCard SSID TLV for a firmware scan */ #define WILDCARD_SSID_TLV_MAX_SIZE \ (MWIFIEX_MAX_SSID_LIST_LENGTH * \ (sizeof(struct mwifiex_ie_types_wildcard_ssid_params) \ + IEEE80211_MAX_SSID_LEN)) /* Maximum memory needed for a mwifiex_scan_cmd_config with all TLVs at max */ #define MAX_SCAN_CFG_ALLOC (sizeof(struct mwifiex_scan_cmd_config) \ + sizeof(struct mwifiex_ie_types_num_probes) \ + sizeof(struct mwifiex_ie_types_htcap) \ + CHAN_TLV_MAX_SIZE \ + RATE_TLV_MAX_SIZE \ + WILDCARD_SSID_TLV_MAX_SIZE) union mwifiex_scan_cmd_config_tlv { /* Scan configuration (variable length) */ struct mwifiex_scan_cmd_config config; /* Max allocated block */ u8 config_alloc_buf[MAX_SCAN_CFG_ALLOC]; }; enum cipher_suite { CIPHER_SUITE_TKIP, CIPHER_SUITE_CCMP, CIPHER_SUITE_MAX }; static u8 mwifiex_wpa_oui[CIPHER_SUITE_MAX][4] = { { 0x00, 0x50, 0xf2, 0x02 }, /* TKIP */ { 0x00, 0x50, 0xf2, 0x04 }, /* AES */ }; static u8 mwifiex_rsn_oui[CIPHER_SUITE_MAX][4] = { { 0x00, 0x0f, 0xac, 0x02 }, /* TKIP */ { 0x00, 0x0f, 0xac, 0x04 }, /* AES */ }; static void _dbg_security_flags(int log_level, const char *func, const char *desc, struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc) { _mwifiex_dbg(priv->adapter, log_level, "info: %s: %s:\twpa_ie=%#x wpa2_ie=%#x WEP=%s WPA=%s WPA2=%s\tEncMode=%#x privacy=%#x\n", func, desc, bss_desc->bcn_wpa_ie ? bss_desc->bcn_wpa_ie->vend_hdr.element_id : 0, bss_desc->bcn_rsn_ie ? bss_desc->bcn_rsn_ie->ieee_hdr.element_id : 0, priv->sec_info.wep_enabled ? "e" : "d", priv->sec_info.wpa_enabled ? "e" : "d", priv->sec_info.wpa2_enabled ? "e" : "d", priv->sec_info.encryption_mode, bss_desc->privacy); } #define dbg_security_flags(mask, desc, priv, bss_desc) \ _dbg_security_flags(MWIFIEX_DBG_##mask, desc, __func__, priv, bss_desc) static bool has_ieee_hdr(struct ieee_types_generic *ie, u8 key) { return (ie && ie->ieee_hdr.element_id == key); } static bool has_vendor_hdr(struct ieee_types_vendor_specific *ie, u8 key) { return (ie && ie->vend_hdr.element_id == key); } /* * This function parses a given IE for a given OUI. * * This is used to parse a WPA/RSN IE to find if it has * a given oui in PTK. */ static u8 mwifiex_search_oui_in_ie(struct ie_body *iebody, u8 *oui) { u8 count; count = iebody->ptk_cnt[0]; /* There could be multiple OUIs for PTK hence 1) Take the length. 2) Check all the OUIs for AES. 3) If one of them is AES then pass success. */ while (count) { if (!memcmp(iebody->ptk_body, oui, sizeof(iebody->ptk_body))) return MWIFIEX_OUI_PRESENT; --count; if (count) iebody = (struct ie_body *) ((u8 *) iebody + sizeof(iebody->ptk_body)); } pr_debug("info: %s: OUI is not found in PTK\n", __func__); return MWIFIEX_OUI_NOT_PRESENT; } /* * This function checks if a given OUI is present in a RSN IE. * * The function first checks if a RSN IE is present or not in the * BSS descriptor. It tries to locate the OUI only if such an IE is * present. */ static u8 mwifiex_is_rsn_oui_present(struct mwifiex_bssdescriptor *bss_desc, u32 cipher) { u8 *oui; struct ie_body *iebody; u8 ret = MWIFIEX_OUI_NOT_PRESENT; if (has_ieee_hdr(bss_desc->bcn_rsn_ie, WLAN_EID_RSN)) { iebody = (struct ie_body *) (((u8 *) bss_desc->bcn_rsn_ie->data) + RSN_GTK_OUI_OFFSET); oui = &mwifiex_rsn_oui[cipher][0]; ret = mwifiex_search_oui_in_ie(iebody, oui); if (ret) return ret; } return ret; } /* * This function checks if a given OUI is present in a WPA IE. * * The function first checks if a WPA IE is present or not in the * BSS descriptor. It tries to locate the OUI only if such an IE is * present. */ static u8 mwifiex_is_wpa_oui_present(struct mwifiex_bssdescriptor *bss_desc, u32 cipher) { u8 *oui; struct ie_body *iebody; u8 ret = MWIFIEX_OUI_NOT_PRESENT; if (has_vendor_hdr(bss_desc->bcn_wpa_ie, WLAN_EID_VENDOR_SPECIFIC)) { iebody = (struct ie_body *)((u8 *)bss_desc->bcn_wpa_ie->data + WPA_GTK_OUI_OFFSET); oui = &mwifiex_wpa_oui[cipher][0]; ret = mwifiex_search_oui_in_ie(iebody, oui); if (ret) return ret; } return ret; } /* * This function compares two SSIDs and checks if they match. */ s32 mwifiex_ssid_cmp(struct cfg80211_ssid *ssid1, struct cfg80211_ssid *ssid2) { if (!ssid1 || !ssid2 || (ssid1->ssid_len != ssid2->ssid_len)) return -1; return memcmp(ssid1->ssid, ssid2->ssid, ssid1->ssid_len); } /* * This function checks if wapi is enabled in driver and scanned network is * compatible with it. */ static bool mwifiex_is_bss_wapi(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc) { if (priv->sec_info.wapi_enabled && has_ieee_hdr(bss_desc->bcn_wapi_ie, WLAN_EID_BSS_AC_ACCESS_DELAY)) return true; return false; } /* * This function checks if driver is configured with no security mode and * scanned network is compatible with it. */ static bool mwifiex_is_bss_no_sec(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc) { if (!priv->sec_info.wep_enabled && !priv->sec_info.wpa_enabled && !priv->sec_info.wpa2_enabled && !has_vendor_hdr(bss_desc->bcn_wpa_ie, WLAN_EID_VENDOR_SPECIFIC) && !has_ieee_hdr(bss_desc->bcn_rsn_ie, WLAN_EID_RSN) && !priv->sec_info.encryption_mode && !bss_desc->privacy) { return true; } return false; } /* * This function checks if static WEP is enabled in driver and scanned network * is compatible with it. */ static bool mwifiex_is_bss_static_wep(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc) { if (priv->sec_info.wep_enabled && !priv->sec_info.wpa_enabled && !priv->sec_info.wpa2_enabled && bss_desc->privacy) { return true; } return false; } /* * This function checks if wpa is enabled in driver and scanned network is * compatible with it. */ static bool mwifiex_is_bss_wpa(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc) { if (!priv->sec_info.wep_enabled && priv->sec_info.wpa_enabled && !priv->sec_info.wpa2_enabled && has_vendor_hdr(bss_desc->bcn_wpa_ie, WLAN_EID_VENDOR_SPECIFIC) /* * Privacy bit may NOT be set in some APs like * LinkSys WRT54G && bss_desc->privacy */ ) { dbg_security_flags(INFO, "WPA", priv, bss_desc); return true; } return false; } /* * This function checks if wpa2 is enabled in driver and scanned network is * compatible with it. */ static bool mwifiex_is_bss_wpa2(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc) { if (!priv->sec_info.wep_enabled && !priv->sec_info.wpa_enabled && priv->sec_info.wpa2_enabled && has_ieee_hdr(bss_desc->bcn_rsn_ie, WLAN_EID_RSN)) { /* * Privacy bit may NOT be set in some APs like * LinkSys WRT54G && bss_desc->privacy */ dbg_security_flags(INFO, "WAP2", priv, bss_desc); return true; } return false; } /* * This function checks if adhoc AES is enabled in driver and scanned network is * compatible with it. */ static bool mwifiex_is_bss_adhoc_aes(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc) { if (!priv->sec_info.wep_enabled && !priv->sec_info.wpa_enabled && !priv->sec_info.wpa2_enabled && !has_vendor_hdr(bss_desc->bcn_wpa_ie, WLAN_EID_VENDOR_SPECIFIC) && !has_ieee_hdr(bss_desc->bcn_rsn_ie, WLAN_EID_RSN) && !priv->sec_info.encryption_mode && bss_desc->privacy) { return true; } return false; } /* * This function checks if dynamic WEP is enabled in driver and scanned network * is compatible with it. */ static bool mwifiex_is_bss_dynamic_wep(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc) { if (!priv->sec_info.wep_enabled && !priv->sec_info.wpa_enabled && !priv->sec_info.wpa2_enabled && !has_vendor_hdr(bss_desc->bcn_wpa_ie, WLAN_EID_VENDOR_SPECIFIC) && !has_ieee_hdr(bss_desc->bcn_rsn_ie, WLAN_EID_RSN) && priv->sec_info.encryption_mode && bss_desc->privacy) { dbg_security_flags(INFO, "dynamic", priv, bss_desc); return true; } return false; } /* * This function checks if a scanned network is compatible with the driver * settings. * * WEP WPA WPA2 ad-hoc encrypt Network * enabled enabled enabled AES mode Privacy WPA WPA2 Compatible * 0 0 0 0 NONE 0 0 0 yes No security * 0 1 0 0 x 1x 1 x yes WPA (disable * HT if no AES) * 0 0 1 0 x 1x x 1 yes WPA2 (disable * HT if no AES) * 0 0 0 1 NONE 1 0 0 yes Ad-hoc AES * 1 0 0 0 NONE 1 0 0 yes Static WEP * (disable HT) * 0 0 0 0 !=NONE 1 0 0 yes Dynamic WEP * * Compatibility is not matched while roaming, except for mode. */ static s32 mwifiex_is_network_compatible(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc, u32 mode) { struct mwifiex_adapter *adapter = priv->adapter; bss_desc->disable_11n = false; /* Don't check for compatibility if roaming */ if (priv->media_connected && (priv->bss_mode == NL80211_IFTYPE_STATION) && (bss_desc->bss_mode == NL80211_IFTYPE_STATION)) return 0; if (priv->wps.session_enable) { mwifiex_dbg(adapter, IOCTL, "info: return success directly in WPS period\n"); return 0; } if (bss_desc->chan_sw_ie_present) { mwifiex_dbg(adapter, INFO, "Don't connect to AP with WLAN_EID_CHANNEL_SWITCH\n"); return -1; } if (mwifiex_is_bss_wapi(priv, bss_desc)) { mwifiex_dbg(adapter, INFO, "info: return success for WAPI AP\n"); return 0; } if (bss_desc->bss_mode == mode) { if (mwifiex_is_bss_no_sec(priv, bss_desc)) { /* No security */ return 0; } else if (mwifiex_is_bss_static_wep(priv, bss_desc)) { /* Static WEP enabled */ mwifiex_dbg(adapter, INFO, "info: Disable 11n in WEP mode.\n"); bss_desc->disable_11n = true; return 0; } else if (mwifiex_is_bss_wpa(priv, bss_desc)) { /* WPA enabled */ if (((priv->adapter->config_bands & BAND_GN || priv->adapter->config_bands & BAND_AN) && bss_desc->bcn_ht_cap) && !mwifiex_is_wpa_oui_present(bss_desc, CIPHER_SUITE_CCMP)) { if (mwifiex_is_wpa_oui_present (bss_desc, CIPHER_SUITE_TKIP)) { mwifiex_dbg(adapter, INFO, "info: Disable 11n if AES\t" "is not supported by AP\n"); bss_desc->disable_11n = true; } else { return -1; } } return 0; } else if (mwifiex_is_bss_wpa2(priv, bss_desc)) { /* WPA2 enabled */ if (((priv->adapter->config_bands & BAND_GN || priv->adapter->config_bands & BAND_AN) && bss_desc->bcn_ht_cap) && !mwifiex_is_rsn_oui_present(bss_desc, CIPHER_SUITE_CCMP)) { if (mwifiex_is_rsn_oui_present (bss_desc, CIPHER_SUITE_TKIP)) { mwifiex_dbg(adapter, INFO, "info: Disable 11n if AES\t" "is not supported by AP\n"); bss_desc->disable_11n = true; } else { return -1; } } return 0; } else if (mwifiex_is_bss_adhoc_aes(priv, bss_desc)) { /* Ad-hoc AES enabled */ return 0; } else if (mwifiex_is_bss_dynamic_wep(priv, bss_desc)) { /* Dynamic WEP enabled */ return 0; } /* Security doesn't match */ dbg_security_flags(ERROR, "failed", priv, bss_desc); return -1; } /* Mode doesn't match */ return -1; } /* * This function creates a channel list for the driver to scan, based * on region/band information. * * This routine is used for any scan that is not provided with a * specific channel list to scan. */ static int mwifiex_scan_create_channel_list(struct mwifiex_private *priv, const struct mwifiex_user_scan_cfg *user_scan_in, struct mwifiex_chan_scan_param_set *scan_chan_list, u8 filtered_scan) { enum nl80211_band band; struct ieee80211_supported_band *sband; struct ieee80211_channel *ch; struct mwifiex_adapter *adapter = priv->adapter; int chan_idx = 0, i; for (band = 0; (band < NUM_NL80211_BANDS) ; band++) { if (!priv->wdev.wiphy->bands[band]) continue; sband = priv->wdev.wiphy->bands[band]; for (i = 0; (i < sband->n_channels) ; i++) { ch = &sband->channels[i]; if (ch->flags & IEEE80211_CHAN_DISABLED) continue; scan_chan_list[chan_idx].radio_type = band; if (user_scan_in && user_scan_in->chan_list[0].scan_time) scan_chan_list[chan_idx].max_scan_time = cpu_to_le16((u16) user_scan_in-> chan_list[0].scan_time); else if ((ch->flags & IEEE80211_CHAN_NO_IR) || (ch->flags & IEEE80211_CHAN_RADAR)) scan_chan_list[chan_idx].max_scan_time = cpu_to_le16(adapter->passive_scan_time); else scan_chan_list[chan_idx].max_scan_time = cpu_to_le16(adapter->active_scan_time); if (ch->flags & IEEE80211_CHAN_NO_IR) scan_chan_list[chan_idx].chan_scan_mode_bitmap |= (MWIFIEX_PASSIVE_SCAN | MWIFIEX_HIDDEN_SSID_REPORT); else scan_chan_list[chan_idx].chan_scan_mode_bitmap &= ~MWIFIEX_PASSIVE_SCAN; scan_chan_list[chan_idx].chan_number = (u32) ch->hw_value; scan_chan_list[chan_idx].chan_scan_mode_bitmap |= MWIFIEX_DISABLE_CHAN_FILT; if (filtered_scan && !((ch->flags & IEEE80211_CHAN_NO_IR) || (ch->flags & IEEE80211_CHAN_RADAR))) scan_chan_list[chan_idx].max_scan_time = cpu_to_le16(adapter->specific_scan_time); chan_idx++; } } return chan_idx; } /* This function creates a channel list tlv for bgscan config, based * on region/band information. */ static int mwifiex_bgscan_create_channel_list(struct mwifiex_private *priv, const struct mwifiex_bg_scan_cfg *bgscan_cfg_in, struct mwifiex_chan_scan_param_set *scan_chan_list) { enum nl80211_band band; struct ieee80211_supported_band *sband; struct ieee80211_channel *ch; struct mwifiex_adapter *adapter = priv->adapter; int chan_idx = 0, i; for (band = 0; (band < NUM_NL80211_BANDS); band++) { if (!priv->wdev.wiphy->bands[band]) continue; sband = priv->wdev.wiphy->bands[band]; for (i = 0; (i < sband->n_channels) ; i++) { ch = &sband->channels[i]; if (ch->flags & IEEE80211_CHAN_DISABLED) continue; scan_chan_list[chan_idx].radio_type = band; if (bgscan_cfg_in->chan_list[0].scan_time) scan_chan_list[chan_idx].max_scan_time = cpu_to_le16((u16)bgscan_cfg_in-> chan_list[0].scan_time); else if (ch->flags & IEEE80211_CHAN_NO_IR) scan_chan_list[chan_idx].max_scan_time = cpu_to_le16(adapter->passive_scan_time); else scan_chan_list[chan_idx].max_scan_time = cpu_to_le16(adapter-> specific_scan_time); if (ch->flags & IEEE80211_CHAN_NO_IR) scan_chan_list[chan_idx].chan_scan_mode_bitmap |= MWIFIEX_PASSIVE_SCAN; else scan_chan_list[chan_idx].chan_scan_mode_bitmap &= ~MWIFIEX_PASSIVE_SCAN; scan_chan_list[chan_idx].chan_number = (u32)ch->hw_value; chan_idx++; } } return chan_idx; } /* This function appends rate TLV to scan config command. */ static int mwifiex_append_rate_tlv(struct mwifiex_private *priv, struct mwifiex_scan_cmd_config *scan_cfg_out, u8 radio) { struct mwifiex_ie_types_rates_param_set *rates_tlv; u8 rates[MWIFIEX_SUPPORTED_RATES], *tlv_pos; u32 rates_size; memset(rates, 0, sizeof(rates)); tlv_pos = (u8 *)scan_cfg_out->tlv_buf + scan_cfg_out->tlv_buf_len; if (priv->scan_request) rates_size = mwifiex_get_rates_from_cfg80211(priv, rates, radio); else rates_size = mwifiex_get_supported_rates(priv, rates); mwifiex_dbg(priv->adapter, CMD, "info: SCAN_CMD: Rates size = %d\n", rates_size); rates_tlv = (struct mwifiex_ie_types_rates_param_set *)tlv_pos; rates_tlv->header.type = cpu_to_le16(WLAN_EID_SUPP_RATES); rates_tlv->header.len = cpu_to_le16((u16) rates_size); memcpy(rates_tlv->rates, rates, rates_size); scan_cfg_out->tlv_buf_len += sizeof(rates_tlv->header) + rates_size; return rates_size; } /* * This function constructs and sends multiple scan config commands to * the firmware. * * Previous routines in the code flow have created a scan command configuration * with any requested TLVs. This function splits the channel TLV into maximum * channels supported per scan lists and sends the portion of the channel TLV, * along with the other TLVs, to the firmware. */ static int mwifiex_scan_channel_list(struct mwifiex_private *priv, u32 max_chan_per_scan, u8 filtered_scan, struct mwifiex_scan_cmd_config *scan_cfg_out, struct mwifiex_ie_types_chan_list_param_set *chan_tlv_out, struct mwifiex_chan_scan_param_set *scan_chan_list) { struct mwifiex_adapter *adapter = priv->adapter; int ret = 0; struct mwifiex_chan_scan_param_set *tmp_chan_list; struct mwifiex_chan_scan_param_set *start_chan; u32 tlv_idx, rates_size, cmd_no; u32 total_scan_time; u32 done_early; u8 radio_type; if (!scan_cfg_out || !chan_tlv_out || !scan_chan_list) { mwifiex_dbg(priv->adapter, ERROR, "info: Scan: Null detect: %p, %p, %p\n", scan_cfg_out, chan_tlv_out, scan_chan_list); return -1; } /* Check csa channel expiry before preparing scan list */ mwifiex_11h_get_csa_closed_channel(priv); chan_tlv_out->header.type = cpu_to_le16(TLV_TYPE_CHANLIST); /* Set the temp channel struct pointer to the start of the desired list */ tmp_chan_list = scan_chan_list; /* Loop through the desired channel list, sending a new firmware scan commands for each max_chan_per_scan channels (or for 1,6,11 individually if configured accordingly) */ while (tmp_chan_list->chan_number) { tlv_idx = 0; total_scan_time = 0; radio_type = 0; chan_tlv_out->header.len = 0; start_chan = tmp_chan_list; done_early = false; /* * Construct the Channel TLV for the scan command. Continue to * insert channel TLVs until: * - the tlv_idx hits the maximum configured per scan command * - the next channel to insert is 0 (end of desired channel * list) * - done_early is set (controlling individual scanning of * 1,6,11) */ while (tlv_idx < max_chan_per_scan && tmp_chan_list->chan_number && !done_early) { if (tmp_chan_list->chan_number == priv->csa_chan) { tmp_chan_list++; continue; } radio_type = tmp_chan_list->radio_type; mwifiex_dbg(priv->adapter, INFO, "info: Scan: Chan(%3d), Radio(%d),\t" "Mode(%d, %d), Dur(%d)\n", tmp_chan_list->chan_number, tmp_chan_list->radio_type, tmp_chan_list->chan_scan_mode_bitmap & MWIFIEX_PASSIVE_SCAN, (tmp_chan_list->chan_scan_mode_bitmap & MWIFIEX_DISABLE_CHAN_FILT) >> 1, le16_to_cpu(tmp_chan_list->max_scan_time)); /* Copy the current channel TLV to the command being prepared */ memcpy(chan_tlv_out->chan_scan_param + tlv_idx, tmp_chan_list, sizeof(chan_tlv_out->chan_scan_param)); /* Increment the TLV header length by the size appended */ le16_unaligned_add_cpu(&chan_tlv_out->header.len, sizeof( chan_tlv_out->chan_scan_param)); /* * The tlv buffer length is set to the number of bytes * of the between the channel tlv pointer and the start * of the tlv buffer. This compensates for any TLVs * that were appended before the channel list. */ scan_cfg_out->tlv_buf_len = (u32) ((u8 *) chan_tlv_out - scan_cfg_out->tlv_buf); /* Add the size of the channel tlv header and the data length */ scan_cfg_out->tlv_buf_len += (sizeof(chan_tlv_out->header) + le16_to_cpu(chan_tlv_out->header.len)); /* Increment the index to the channel tlv we are constructing */ tlv_idx++; /* Count the total scan time per command */ total_scan_time += le16_to_cpu(tmp_chan_list->max_scan_time); done_early = false; /* Stop the loop if the *current* channel is in the 1,6,11 set and we are not filtering on a BSSID or SSID. */ if (!filtered_scan && (tmp_chan_list->chan_number == 1 || tmp_chan_list->chan_number == 6 || tmp_chan_list->chan_number == 11)) done_early = true; /* Increment the tmp pointer to the next channel to be scanned */ tmp_chan_list++; /* Stop the loop if the *next* channel is in the 1,6,11 set. This will cause it to be the only channel scanned on the next interation */ if (!filtered_scan && (tmp_chan_list->chan_number == 1 || tmp_chan_list->chan_number == 6 || tmp_chan_list->chan_number == 11)) done_early = true; } /* The total scan time should be less than scan command timeout value */ if (total_scan_time > MWIFIEX_MAX_TOTAL_SCAN_TIME) { mwifiex_dbg(priv->adapter, ERROR, "total scan time %dms\t" "is over limit (%dms), scan skipped\n", total_scan_time, MWIFIEX_MAX_TOTAL_SCAN_TIME); ret = -1; break; } rates_size = mwifiex_append_rate_tlv(priv, scan_cfg_out, radio_type); priv->adapter->scan_channels = start_chan; /* Send the scan command to the firmware with the specified cfg */ if (priv->adapter->ext_scan) cmd_no = HostCmd_CMD_802_11_SCAN_EXT; else cmd_no = HostCmd_CMD_802_11_SCAN; ret = mwifiex_send_cmd(priv, cmd_no, HostCmd_ACT_GEN_SET, 0, scan_cfg_out, false); /* rate IE is updated per scan command but same starting * pointer is used each time so that rate IE from earlier * scan_cfg_out->buf is overwritten with new one. */ scan_cfg_out->tlv_buf_len -= sizeof(struct mwifiex_ie_types_header) + rates_size; if (ret) { mwifiex_cancel_pending_scan_cmd(adapter); break; } } if (ret) return -1; return 0; } /* * This function constructs a scan command configuration structure to use * in scan commands. * * Application layer or other functions can invoke network scanning * with a scan configuration supplied in a user scan configuration structure. * This structure is used as the basis of one or many scan command configuration * commands that are sent to the command processing module and eventually to the * firmware. * * This function creates a scan command configuration structure based on the * following user supplied parameters (if present): * - SSID filter * - BSSID filter * - Number of Probes to be sent * - Channel list * * If the SSID or BSSID filter is not present, the filter is disabled/cleared. * If the number of probes is not set, adapter default setting is used. */ static void mwifiex_config_scan(struct mwifiex_private *priv, const struct mwifiex_user_scan_cfg *user_scan_in, struct mwifiex_scan_cmd_config *scan_cfg_out, struct mwifiex_ie_types_chan_list_param_set **chan_list_out, struct mwifiex_chan_scan_param_set *scan_chan_list, u8 *max_chan_per_scan, u8 *filtered_scan, u8 *scan_current_only) { struct mwifiex_adapter *adapter = priv->adapter; struct mwifiex_ie_types_num_probes *num_probes_tlv; struct mwifiex_ie_types_scan_chan_gap *chan_gap_tlv; struct mwifiex_ie_types_random_mac *random_mac_tlv; struct mwifiex_ie_types_wildcard_ssid_params *wildcard_ssid_tlv; struct mwifiex_ie_types_bssid_list *bssid_tlv; u8 *tlv_pos; u32 num_probes; u32 ssid_len; u32 chan_idx; u32 scan_type; u16 scan_dur; u8 channel; u8 radio_type; int i; u8 ssid_filter; struct mwifiex_ie_types_htcap *ht_cap; struct mwifiex_ie_types_bss_mode *bss_mode; const u8 zero_mac[6] = {0, 0, 0, 0, 0, 0}; /* The tlv_buf_len is calculated for each scan command. The TLVs added in this routine will be preserved since the routine that sends the command will append channelTLVs at *chan_list_out. The difference between the *chan_list_out and the tlv_buf start will be used to calculate the size of anything we add in this routine. */ scan_cfg_out->tlv_buf_len = 0; /* Running tlv pointer. Assigned to chan_list_out at end of function so later routines know where channels can be added to the command buf */ tlv_pos = scan_cfg_out->tlv_buf; /* Initialize the scan as un-filtered; the flag is later set to TRUE below if a SSID or BSSID filter is sent in the command */ *filtered_scan = false; /* Initialize the scan as not being only on the current channel. If the channel list is customized, only contains one channel, and is the active channel, this is set true and data flow is not halted. */ *scan_current_only = false; if (user_scan_in) { u8 tmpaddr[ETH_ALEN]; /* Default the ssid_filter flag to TRUE, set false under certain wildcard conditions and qualified by the existence of an SSID list before marking the scan as filtered */ ssid_filter = true; /* Set the BSS type scan filter, use Adapter setting if unset */ scan_cfg_out->bss_mode = (u8)(user_scan_in->bss_mode ?: adapter->scan_mode); /* Set the number of probes to send, use Adapter setting if unset */ num_probes = user_scan_in->num_probes ?: adapter->scan_probes; /* * Set the BSSID filter to the incoming configuration, * if non-zero. If not set, it will remain disabled * (all zeros). */ memcpy(scan_cfg_out->specific_bssid, user_scan_in->specific_bssid, sizeof(scan_cfg_out->specific_bssid)); memcpy(tmpaddr, scan_cfg_out->specific_bssid, ETH_ALEN); if (adapter->ext_scan && !is_zero_ether_addr(tmpaddr)) { bssid_tlv = (struct mwifiex_ie_types_bssid_list *)tlv_pos; bssid_tlv->header.type = cpu_to_le16(TLV_TYPE_BSSID); bssid_tlv->header.len = cpu_to_le16(ETH_ALEN); memcpy(bssid_tlv->bssid, user_scan_in->specific_bssid, ETH_ALEN); tlv_pos += sizeof(struct mwifiex_ie_types_bssid_list); } for (i = 0; i < user_scan_in->num_ssids; i++) { ssid_len = user_scan_in->ssid_list[i].ssid_len; wildcard_ssid_tlv = (struct mwifiex_ie_types_wildcard_ssid_params *) tlv_pos; wildcard_ssid_tlv->header.type = cpu_to_le16(TLV_TYPE_WILDCARDSSID); wildcard_ssid_tlv->header.len = cpu_to_le16( (u16) (ssid_len + sizeof(wildcard_ssid_tlv-> max_ssid_length))); /* * max_ssid_length = 0 tells firmware to perform * specific scan for the SSID filled, whereas * max_ssid_length = IEEE80211_MAX_SSID_LEN is for * wildcard scan. */ if (ssid_len) wildcard_ssid_tlv->max_ssid_length = 0; else wildcard_ssid_tlv->max_ssid_length = IEEE80211_MAX_SSID_LEN; if (!memcmp(user_scan_in->ssid_list[i].ssid, "DIRECT-", 7)) wildcard_ssid_tlv->max_ssid_length = 0xfe; memcpy(wildcard_ssid_tlv->ssid, user_scan_in->ssid_list[i].ssid, ssid_len); tlv_pos += (sizeof(wildcard_ssid_tlv->header) + le16_to_cpu(wildcard_ssid_tlv->header.len)); mwifiex_dbg(adapter, INFO, "info: scan: ssid[%d]: %s, %d\n", i, wildcard_ssid_tlv->ssid, wildcard_ssid_tlv->max_ssid_length); /* Empty wildcard ssid with a maxlen will match many or potentially all SSIDs (maxlen == 32), therefore do not treat the scan as filtered. */ if (!ssid_len && wildcard_ssid_tlv->max_ssid_length) ssid_filter = false; } /* * The default number of channels sent in the command is low to * ensure the response buffer from the firmware does not * truncate scan results. That is not an issue with an SSID * or BSSID filter applied to the scan results in the firmware. */ memcpy(tmpaddr, scan_cfg_out->specific_bssid, ETH_ALEN); if ((i && ssid_filter) || !is_zero_ether_addr(tmpaddr)) *filtered_scan = true; if (user_scan_in->scan_chan_gap) { mwifiex_dbg(adapter, INFO, "info: scan: channel gap = %d\n", user_scan_in->scan_chan_gap); *max_chan_per_scan = MWIFIEX_MAX_CHANNELS_PER_SPECIFIC_SCAN; chan_gap_tlv = (void *)tlv_pos; chan_gap_tlv->header.type = cpu_to_le16(TLV_TYPE_SCAN_CHANNEL_GAP); chan_gap_tlv->header.len = cpu_to_le16(sizeof(chan_gap_tlv->chan_gap)); chan_gap_tlv->chan_gap = cpu_to_le16((user_scan_in->scan_chan_gap)); tlv_pos += sizeof(struct mwifiex_ie_types_scan_chan_gap); } if (!ether_addr_equal(user_scan_in->random_mac, zero_mac)) { random_mac_tlv = (void *)tlv_pos; random_mac_tlv->header.type = cpu_to_le16(TLV_TYPE_RANDOM_MAC); random_mac_tlv->header.len = cpu_to_le16(sizeof(random_mac_tlv->mac)); ether_addr_copy(random_mac_tlv->mac, user_scan_in->random_mac); tlv_pos += sizeof(struct mwifiex_ie_types_random_mac); } } else { scan_cfg_out->bss_mode = (u8) adapter->scan_mode; num_probes = adapter->scan_probes; } /* * If a specific BSSID or SSID is used, the number of channels in the * scan command will be increased to the absolute maximum. */ if (*filtered_scan) { *max_chan_per_scan = MWIFIEX_MAX_CHANNELS_PER_SPECIFIC_SCAN; } else { if (!priv->media_connected) *max_chan_per_scan = MWIFIEX_DEF_CHANNELS_PER_SCAN_CMD; else *max_chan_per_scan = MWIFIEX_DEF_CHANNELS_PER_SCAN_CMD / 2; } if (adapter->ext_scan) { bss_mode = (struct mwifiex_ie_types_bss_mode *)tlv_pos; bss_mode->header.type = cpu_to_le16(TLV_TYPE_BSS_MODE); bss_mode->header.len = cpu_to_le16(sizeof(bss_mode->bss_mode)); bss_mode->bss_mode = scan_cfg_out->bss_mode; tlv_pos += sizeof(bss_mode->header) + le16_to_cpu(bss_mode->header.len); } /* If the input config or adapter has the number of Probes set, add tlv */ if (num_probes) { mwifiex_dbg(adapter, INFO, "info: scan: num_probes = %d\n", num_probes); num_probes_tlv = (struct mwifiex_ie_types_num_probes *) tlv_pos; num_probes_tlv->header.type = cpu_to_le16(TLV_TYPE_NUMPROBES); num_probes_tlv->header.len = cpu_to_le16(sizeof(num_probes_tlv->num_probes)); num_probes_tlv->num_probes = cpu_to_le16((u16) num_probes); tlv_pos += sizeof(num_probes_tlv->header) + le16_to_cpu(num_probes_tlv->header.len); } if (ISSUPP_11NENABLED(priv->adapter->fw_cap_info) && (priv->adapter->config_bands & BAND_GN || priv->adapter->config_bands & BAND_AN)) { ht_cap = (struct mwifiex_ie_types_htcap *) tlv_pos; memset(ht_cap, 0, sizeof(struct mwifiex_ie_types_htcap)); ht_cap->header.type = cpu_to_le16(WLAN_EID_HT_CAPABILITY); ht_cap->header.len = cpu_to_le16(sizeof(struct ieee80211_ht_cap)); radio_type = mwifiex_band_to_radio_type(priv->adapter->config_bands); mwifiex_fill_cap_info(priv, radio_type, &ht_cap->ht_cap); tlv_pos += sizeof(struct mwifiex_ie_types_htcap); } /* Append vendor specific IE TLV */ mwifiex_cmd_append_vsie_tlv(priv, MWIFIEX_VSIE_MASK_SCAN, &tlv_pos); /* * Set the output for the channel TLV to the address in the tlv buffer * past any TLVs that were added in this function (SSID, num_probes). * Channel TLVs will be added past this for each scan command, * preserving the TLVs that were previously added. */ *chan_list_out = (struct mwifiex_ie_types_chan_list_param_set *) tlv_pos; if (user_scan_in && user_scan_in->chan_list[0].chan_number) { mwifiex_dbg(adapter, INFO, "info: Scan: Using supplied channel list\n"); for (chan_idx = 0; chan_idx < MWIFIEX_USER_SCAN_CHAN_MAX && user_scan_in->chan_list[chan_idx].chan_number; chan_idx++) { channel = user_scan_in->chan_list[chan_idx].chan_number; scan_chan_list[chan_idx].chan_number = channel; radio_type = user_scan_in->chan_list[chan_idx].radio_type; scan_chan_list[chan_idx].radio_type = radio_type; scan_type = user_scan_in->chan_list[chan_idx].scan_type; if (scan_type == MWIFIEX_SCAN_TYPE_PASSIVE) scan_chan_list[chan_idx].chan_scan_mode_bitmap |= (MWIFIEX_PASSIVE_SCAN | MWIFIEX_HIDDEN_SSID_REPORT); else scan_chan_list[chan_idx].chan_scan_mode_bitmap &= ~MWIFIEX_PASSIVE_SCAN; scan_chan_list[chan_idx].chan_scan_mode_bitmap |= MWIFIEX_DISABLE_CHAN_FILT; if (user_scan_in->chan_list[chan_idx].scan_time) { scan_dur = (u16) user_scan_in-> chan_list[chan_idx].scan_time; } else { if (scan_type == MWIFIEX_SCAN_TYPE_PASSIVE) scan_dur = adapter->passive_scan_time; else if (*filtered_scan) scan_dur = adapter->specific_scan_time; else scan_dur = adapter->active_scan_time; } scan_chan_list[chan_idx].min_scan_time = cpu_to_le16(scan_dur); scan_chan_list[chan_idx].max_scan_time = cpu_to_le16(scan_dur); } /* Check if we are only scanning the current channel */ if ((chan_idx == 1) && (user_scan_in->chan_list[0].chan_number == priv->curr_bss_params.bss_descriptor.channel)) { *scan_current_only = true; mwifiex_dbg(adapter, INFO, "info: Scan: Scanning current channel only\n"); } } else { mwifiex_dbg(adapter, INFO, "info: Scan: Creating full region channel list\n"); mwifiex_scan_create_channel_list(priv, user_scan_in, scan_chan_list, *filtered_scan); } } /* * This function inspects the scan response buffer for pointers to * expected TLVs. * * TLVs can be included at the end of the scan response BSS information. * * Data in the buffer is parsed pointers to TLVs that can potentially * be passed back in the response. */ static void mwifiex_ret_802_11_scan_get_tlv_ptrs(struct mwifiex_adapter *adapter, struct mwifiex_ie_types_data *tlv, u32 tlv_buf_size, u32 req_tlv_type, struct mwifiex_ie_types_data **tlv_data) { struct mwifiex_ie_types_data *current_tlv; u32 tlv_buf_left; u32 tlv_type; u32 tlv_len; current_tlv = tlv; tlv_buf_left = tlv_buf_size; *tlv_data = NULL; mwifiex_dbg(adapter, INFO, "info: SCAN_RESP: tlv_buf_size = %d\n", tlv_buf_size); while (tlv_buf_left >= sizeof(struct mwifiex_ie_types_header)) { tlv_type = le16_to_cpu(current_tlv->header.type); tlv_len = le16_to_cpu(current_tlv->header.len); if (sizeof(tlv->header) + tlv_len > tlv_buf_left) { mwifiex_dbg(adapter, ERROR, "SCAN_RESP: TLV buffer corrupt\n"); break; } if (req_tlv_type == tlv_type) { switch (tlv_type) { case TLV_TYPE_TSFTIMESTAMP: mwifiex_dbg(adapter, INFO, "info: SCAN_RESP: TSF\t" "timestamp TLV, len = %d\n", tlv_len); *tlv_data = current_tlv; break; case TLV_TYPE_CHANNELBANDLIST: mwifiex_dbg(adapter, INFO, "info: SCAN_RESP: channel\t" "band list TLV, len = %d\n", tlv_len); *tlv_data = current_tlv; break; default: mwifiex_dbg(adapter, ERROR, "SCAN_RESP: unhandled TLV = %d\n", tlv_type); /* Give up, this seems corrupted */ return; } } if (*tlv_data) break; tlv_buf_left -= (sizeof(tlv->header) + tlv_len); current_tlv = (struct mwifiex_ie_types_data *) (current_tlv->data + tlv_len); } /* while */ } /* * This function parses provided beacon buffer and updates * respective fields in bss descriptor structure. */ int mwifiex_update_bss_desc_with_ie(struct mwifiex_adapter *adapter, struct mwifiex_bssdescriptor *bss_entry) { int ret = 0; u8 element_id; struct ieee_types_fh_param_set *fh_param_set; struct ieee_types_ds_param_set *ds_param_set; struct ieee_types_cf_param_set *cf_param_set; struct ieee_types_ibss_param_set *ibss_param_set; u8 *current_ptr; u8 *rate; u8 element_len; u16 total_ie_len; u8 bytes_to_copy; u8 rate_size; u8 found_data_rate_ie; u32 bytes_left; struct ieee_types_vendor_specific *vendor_ie; const u8 wpa_oui[4] = { 0x00, 0x50, 0xf2, 0x01 }; const u8 wmm_oui[4] = { 0x00, 0x50, 0xf2, 0x02 }; found_data_rate_ie = false; rate_size = 0; current_ptr = bss_entry->beacon_buf; bytes_left = bss_entry->beacon_buf_size; /* Process variable IE */ while (bytes_left >= 2) { element_id = *current_ptr; element_len = *(current_ptr + 1); total_ie_len = element_len + sizeof(struct ieee_types_header); if (bytes_left < total_ie_len) { mwifiex_dbg(adapter, ERROR, "err: InterpretIE: in processing\t" "IE, bytes left < IE length\n"); return -EINVAL; } switch (element_id) { case WLAN_EID_SSID: if (element_len > IEEE80211_MAX_SSID_LEN) return -EINVAL; bss_entry->ssid.ssid_len = element_len; memcpy(bss_entry->ssid.ssid, (current_ptr + 2), element_len); mwifiex_dbg(adapter, INFO, "info: InterpretIE: ssid: %-32s\n", bss_entry->ssid.ssid); break; case WLAN_EID_SUPP_RATES: if (element_len > MWIFIEX_SUPPORTED_RATES) return -EINVAL; memcpy(bss_entry->data_rates, current_ptr + 2, element_len); memcpy(bss_entry->supported_rates, current_ptr + 2, element_len); rate_size = element_len; found_data_rate_ie = true; break; case WLAN_EID_FH_PARAMS: if (total_ie_len < sizeof(*fh_param_set)) return -EINVAL; fh_param_set = (struct ieee_types_fh_param_set *) current_ptr; memcpy(&bss_entry->phy_param_set.fh_param_set, fh_param_set, sizeof(struct ieee_types_fh_param_set)); break; case WLAN_EID_DS_PARAMS: if (total_ie_len < sizeof(*ds_param_set)) return -EINVAL; ds_param_set = (struct ieee_types_ds_param_set *) current_ptr; bss_entry->channel = ds_param_set->current_chan; memcpy(&bss_entry->phy_param_set.ds_param_set, ds_param_set, sizeof(struct ieee_types_ds_param_set)); break; case WLAN_EID_CF_PARAMS: if (total_ie_len < sizeof(*cf_param_set)) return -EINVAL; cf_param_set = (struct ieee_types_cf_param_set *) current_ptr; memcpy(&bss_entry->ss_param_set.cf_param_set, cf_param_set, sizeof(struct ieee_types_cf_param_set)); break; case WLAN_EID_IBSS_PARAMS: if (total_ie_len < sizeof(*ibss_param_set)) return -EINVAL; ibss_param_set = (struct ieee_types_ibss_param_set *) current_ptr; memcpy(&bss_entry->ss_param_set.ibss_param_set, ibss_param_set, sizeof(struct ieee_types_ibss_param_set)); break; case WLAN_EID_ERP_INFO: if (!element_len) return -EINVAL; bss_entry->erp_flags = *(current_ptr + 2); break; case WLAN_EID_PWR_CONSTRAINT: if (!element_len) return -EINVAL; bss_entry->local_constraint = *(current_ptr + 2); bss_entry->sensed_11h = true; break; case WLAN_EID_CHANNEL_SWITCH: bss_entry->chan_sw_ie_present = true; /* fall through */ case WLAN_EID_PWR_CAPABILITY: case WLAN_EID_TPC_REPORT: case WLAN_EID_QUIET: bss_entry->sensed_11h = true; break; case WLAN_EID_EXT_SUPP_RATES: /* * Only process extended supported rate * if data rate is already found. * Data rate IE should come before * extended supported rate IE */ if (found_data_rate_ie) { if ((element_len + rate_size) > MWIFIEX_SUPPORTED_RATES) bytes_to_copy = (MWIFIEX_SUPPORTED_RATES - rate_size); else bytes_to_copy = element_len; rate = (u8 *) bss_entry->data_rates; rate += rate_size; memcpy(rate, current_ptr + 2, bytes_to_copy); rate = (u8 *) bss_entry->supported_rates; rate += rate_size; memcpy(rate, current_ptr + 2, bytes_to_copy); } break; case WLAN_EID_VENDOR_SPECIFIC: vendor_ie = (struct ieee_types_vendor_specific *) current_ptr; /* 802.11 requires at least 3-byte OUI. */ if (element_len < sizeof(vendor_ie->vend_hdr.oui.oui)) return -EINVAL; /* Not long enough for a match? Skip it. */ if (element_len < sizeof(wpa_oui)) break; if (!memcmp(&vendor_ie->vend_hdr.oui, wpa_oui, sizeof(wpa_oui))) { bss_entry->bcn_wpa_ie = (struct ieee_types_vendor_specific *) current_ptr; bss_entry->wpa_offset = (u16) (current_ptr - bss_entry->beacon_buf); } else if (!memcmp(&vendor_ie->vend_hdr.oui, wmm_oui, sizeof(wmm_oui))) { if (total_ie_len == sizeof(struct ieee_types_wmm_parameter) || total_ie_len == sizeof(struct ieee_types_wmm_info)) /* * Only accept and copy the WMM IE if * it matches the size expected for the * WMM Info IE or the WMM Parameter IE. */ memcpy((u8 *) &bss_entry->wmm_ie, current_ptr, total_ie_len); } break; case WLAN_EID_RSN: bss_entry->bcn_rsn_ie = (struct ieee_types_generic *) current_ptr; bss_entry->rsn_offset = (u16) (current_ptr - bss_entry->beacon_buf); break; case WLAN_EID_BSS_AC_ACCESS_DELAY: bss_entry->bcn_wapi_ie = (struct ieee_types_generic *) current_ptr; bss_entry->wapi_offset = (u16) (current_ptr - bss_entry->beacon_buf); break; case WLAN_EID_HT_CAPABILITY: bss_entry->bcn_ht_cap = (struct ieee80211_ht_cap *) (current_ptr + sizeof(struct ieee_types_header)); bss_entry->ht_cap_offset = (u16) (current_ptr + sizeof(struct ieee_types_header) - bss_entry->beacon_buf); break; case WLAN_EID_HT_OPERATION: bss_entry->bcn_ht_oper = (struct ieee80211_ht_operation *)(current_ptr + sizeof(struct ieee_types_header)); bss_entry->ht_info_offset = (u16) (current_ptr + sizeof(struct ieee_types_header) - bss_entry->beacon_buf); break; case WLAN_EID_VHT_CAPABILITY: bss_entry->disable_11ac = false; bss_entry->bcn_vht_cap = (void *)(current_ptr + sizeof(struct ieee_types_header)); bss_entry->vht_cap_offset = (u16)((u8 *)bss_entry->bcn_vht_cap - bss_entry->beacon_buf); break; case WLAN_EID_VHT_OPERATION: bss_entry->bcn_vht_oper = (void *)(current_ptr + sizeof(struct ieee_types_header)); bss_entry->vht_info_offset = (u16)((u8 *)bss_entry->bcn_vht_oper - bss_entry->beacon_buf); break; case WLAN_EID_BSS_COEX_2040: bss_entry->bcn_bss_co_2040 = current_ptr; bss_entry->bss_co_2040_offset = (u16) (current_ptr - bss_entry->beacon_buf); break; case WLAN_EID_EXT_CAPABILITY: bss_entry->bcn_ext_cap = current_ptr; bss_entry->ext_cap_offset = (u16) (current_ptr - bss_entry->beacon_buf); break; case WLAN_EID_OPMODE_NOTIF: bss_entry->oper_mode = (void *)current_ptr; bss_entry->oper_mode_offset = (u16)((u8 *)bss_entry->oper_mode - bss_entry->beacon_buf); break; default: break; } current_ptr += total_ie_len; bytes_left -= total_ie_len; } /* while (bytes_left > 2) */ return ret; } /* * This function converts radio type scan parameter to a band configuration * to be used in join command. */ static u8 mwifiex_radio_type_to_band(u8 radio_type) { switch (radio_type) { case HostCmd_SCAN_RADIO_TYPE_A: return BAND_A; case HostCmd_SCAN_RADIO_TYPE_BG: default: return BAND_G; } } /* * This is an internal function used to start a scan based on an input * configuration. * * This uses the input user scan configuration information when provided in * order to send the appropriate scan commands to firmware to populate or * update the internal driver scan table. */ int mwifiex_scan_networks(struct mwifiex_private *priv, const struct mwifiex_user_scan_cfg *user_scan_in) { int ret; struct mwifiex_adapter *adapter = priv->adapter; struct cmd_ctrl_node *cmd_node; union mwifiex_scan_cmd_config_tlv *scan_cfg_out; struct mwifiex_ie_types_chan_list_param_set *chan_list_out; struct mwifiex_chan_scan_param_set *scan_chan_list; u8 filtered_scan; u8 scan_current_chan_only; u8 max_chan_per_scan; if (adapter->scan_processing) { mwifiex_dbg(adapter, WARN, "cmd: Scan already in process...\n"); return -EBUSY; } if (priv->scan_block) { mwifiex_dbg(adapter, WARN, "cmd: Scan is blocked during association...\n"); return -EBUSY; } if (test_bit(MWIFIEX_SURPRISE_REMOVED, &adapter->work_flags) || test_bit(MWIFIEX_IS_CMD_TIMEDOUT, &adapter->work_flags)) { mwifiex_dbg(adapter, ERROR, "Ignore scan. Card removed or firmware in bad state\n"); return -EFAULT; } spin_lock_bh(&adapter->mwifiex_cmd_lock); adapter->scan_processing = true; spin_unlock_bh(&adapter->mwifiex_cmd_lock); scan_cfg_out = kzalloc(sizeof(union mwifiex_scan_cmd_config_tlv), GFP_KERNEL); if (!scan_cfg_out) { ret = -ENOMEM; goto done; } scan_chan_list = kcalloc(MWIFIEX_USER_SCAN_CHAN_MAX, sizeof(struct mwifiex_chan_scan_param_set), GFP_KERNEL); if (!scan_chan_list) { kfree(scan_cfg_out); ret = -ENOMEM; goto done; } mwifiex_config_scan(priv, user_scan_in, &scan_cfg_out->config, &chan_list_out, scan_chan_list, &max_chan_per_scan, &filtered_scan, &scan_current_chan_only); ret = mwifiex_scan_channel_list(priv, max_chan_per_scan, filtered_scan, &scan_cfg_out->config, chan_list_out, scan_chan_list); /* Get scan command from scan_pending_q and put to cmd_pending_q */ if (!ret) { spin_lock_bh(&adapter->scan_pending_q_lock); if (!list_empty(&adapter->scan_pending_q)) { cmd_node = list_first_entry(&adapter->scan_pending_q, struct cmd_ctrl_node, list); list_del(&cmd_node->list); spin_unlock_bh(&adapter->scan_pending_q_lock); mwifiex_insert_cmd_to_pending_q(adapter, cmd_node); queue_work(adapter->workqueue, &adapter->main_work); /* Perform internal scan synchronously */ if (!priv->scan_request) { mwifiex_dbg(adapter, INFO, "wait internal scan\n"); mwifiex_wait_queue_complete(adapter, cmd_node); } } else { spin_unlock_bh(&adapter->scan_pending_q_lock); } } kfree(scan_cfg_out); kfree(scan_chan_list); done: if (ret) { spin_lock_bh(&adapter->mwifiex_cmd_lock); adapter->scan_processing = false; spin_unlock_bh(&adapter->mwifiex_cmd_lock); } return ret; } /* * This function prepares a scan command to be sent to the firmware. * * This uses the scan command configuration sent to the command processing * module in command preparation stage to configure a scan command structure * to send to firmware. * * The fixed fields specifying the BSS type and BSSID filters as well as a * variable number/length of TLVs are sent in the command to firmware. * * Preparation also includes - * - Setting command ID, and proper size * - Ensuring correct endian-ness */ int mwifiex_cmd_802_11_scan(struct host_cmd_ds_command *cmd, struct mwifiex_scan_cmd_config *scan_cfg) { struct host_cmd_ds_802_11_scan *scan_cmd = &cmd->params.scan; /* Set fixed field variables in scan command */ scan_cmd->bss_mode = scan_cfg->bss_mode; memcpy(scan_cmd->bssid, scan_cfg->specific_bssid, sizeof(scan_cmd->bssid)); memcpy(scan_cmd->tlv_buffer, scan_cfg->tlv_buf, scan_cfg->tlv_buf_len); cmd->command = cpu_to_le16(HostCmd_CMD_802_11_SCAN); /* Size is equal to the sizeof(fixed portions) + the TLV len + header */ cmd->size = cpu_to_le16((u16) (sizeof(scan_cmd->bss_mode) + sizeof(scan_cmd->bssid) + scan_cfg->tlv_buf_len + S_DS_GEN)); return 0; } /* * This function checks compatibility of requested network with current * driver settings. */ int mwifiex_check_network_compatibility(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc) { int ret = -1; if (!bss_desc) return -1; if ((mwifiex_get_cfp(priv, (u8) bss_desc->bss_band, (u16) bss_desc->channel, 0))) { switch (priv->bss_mode) { case NL80211_IFTYPE_STATION: case NL80211_IFTYPE_ADHOC: ret = mwifiex_is_network_compatible(priv, bss_desc, priv->bss_mode); if (ret) mwifiex_dbg(priv->adapter, ERROR, "Incompatible network settings\n"); break; default: ret = 0; } } return ret; } /* This function checks if SSID string contains all zeroes or length is zero */ static bool mwifiex_is_hidden_ssid(struct cfg80211_ssid *ssid) { int idx; for (idx = 0; idx < ssid->ssid_len; idx++) { if (ssid->ssid[idx]) return false; } return true; } /* This function checks if any hidden SSID found in passive scan channels * and save those channels for specific SSID active scan */ static int mwifiex_save_hidden_ssid_channels(struct mwifiex_private *priv, struct cfg80211_bss *bss) { struct mwifiex_bssdescriptor *bss_desc; int ret; int chid; /* Allocate and fill new bss descriptor */ bss_desc = kzalloc(sizeof(*bss_desc), GFP_KERNEL); if (!bss_desc) return -ENOMEM; ret = mwifiex_fill_new_bss_desc(priv, bss, bss_desc); if (ret) goto done; if (mwifiex_is_hidden_ssid(&bss_desc->ssid)) { mwifiex_dbg(priv->adapter, INFO, "found hidden SSID\n"); for (chid = 0 ; chid < MWIFIEX_USER_SCAN_CHAN_MAX; chid++) { if (priv->hidden_chan[chid].chan_number == bss->channel->hw_value) break; if (!priv->hidden_chan[chid].chan_number) { priv->hidden_chan[chid].chan_number = bss->channel->hw_value; priv->hidden_chan[chid].radio_type = bss->channel->band; priv->hidden_chan[chid].scan_type = MWIFIEX_SCAN_TYPE_ACTIVE; break; } } } done: /* beacon_ie buffer was allocated in function * mwifiex_fill_new_bss_desc(). Free it now. */ kfree(bss_desc->beacon_buf); kfree(bss_desc); return 0; } static int mwifiex_update_curr_bss_params(struct mwifiex_private *priv, struct cfg80211_bss *bss) { struct mwifiex_bssdescriptor *bss_desc; int ret; /* Allocate and fill new bss descriptor */ bss_desc = kzalloc(sizeof(struct mwifiex_bssdescriptor), GFP_KERNEL); if (!bss_desc) return -ENOMEM; ret = mwifiex_fill_new_bss_desc(priv, bss, bss_desc); if (ret) goto done; ret = mwifiex_check_network_compatibility(priv, bss_desc); if (ret) goto done; spin_lock_bh(&priv->curr_bcn_buf_lock); /* Make a copy of current BSSID descriptor */ memcpy(&priv->curr_bss_params.bss_descriptor, bss_desc, sizeof(priv->curr_bss_params.bss_descriptor)); /* The contents of beacon_ie will be copied to its own buffer * in mwifiex_save_curr_bcn() */ mwifiex_save_curr_bcn(priv); spin_unlock_bh(&priv->curr_bcn_buf_lock); done: /* beacon_ie buffer was allocated in function * mwifiex_fill_new_bss_desc(). Free it now. */ kfree(bss_desc->beacon_buf); kfree(bss_desc); return 0; } static int mwifiex_parse_single_response_buf(struct mwifiex_private *priv, u8 **bss_info, u32 *bytes_left, u64 fw_tsf, u8 *radio_type, bool ext_scan, s32 rssi_val) { struct mwifiex_adapter *adapter = priv->adapter; struct mwifiex_chan_freq_power *cfp; struct cfg80211_bss *bss; u8 bssid[ETH_ALEN]; s32 rssi; const u8 *ie_buf; size_t ie_len; u16 channel = 0; u16 beacon_size = 0; u32 curr_bcn_bytes; u32 freq; u16 beacon_period; u16 cap_info_bitmap; u8 *current_ptr; u64 timestamp; struct mwifiex_fixed_bcn_param *bcn_param; struct mwifiex_bss_priv *bss_priv; if (*bytes_left >= sizeof(beacon_size)) { /* Extract & convert beacon size from command buffer */ beacon_size = get_unaligned_le16((*bss_info)); *bytes_left -= sizeof(beacon_size); *bss_info += sizeof(beacon_size); } if (!beacon_size || beacon_size > *bytes_left) { *bss_info += *bytes_left; *bytes_left = 0; return -EFAULT; } /* Initialize the current working beacon pointer for this BSS * iteration */ current_ptr = *bss_info; /* Advance the return beacon pointer past the current beacon */ *bss_info += beacon_size; *bytes_left -= beacon_size; curr_bcn_bytes = beacon_size; /* First 5 fields are bssid, RSSI(for legacy scan only), * time stamp, beacon interval, and capability information */ if (curr_bcn_bytes < ETH_ALEN + sizeof(u8) + sizeof(struct mwifiex_fixed_bcn_param)) { mwifiex_dbg(adapter, ERROR, "InterpretIE: not enough bytes left\n"); return -EFAULT; } memcpy(bssid, current_ptr, ETH_ALEN); current_ptr += ETH_ALEN; curr_bcn_bytes -= ETH_ALEN; if (!ext_scan) { rssi = (s32) *current_ptr; rssi = (-rssi) * 100; /* Convert dBm to mBm */ current_ptr += sizeof(u8); curr_bcn_bytes -= sizeof(u8); mwifiex_dbg(adapter, INFO, "info: InterpretIE: RSSI=%d\n", rssi); } else { rssi = rssi_val; } bcn_param = (struct mwifiex_fixed_bcn_param *)current_ptr; current_ptr += sizeof(*bcn_param); curr_bcn_bytes -= sizeof(*bcn_param); timestamp = le64_to_cpu(bcn_param->timestamp); beacon_period = le16_to_cpu(bcn_param->beacon_period); cap_info_bitmap = le16_to_cpu(bcn_param->cap_info_bitmap); mwifiex_dbg(adapter, INFO, "info: InterpretIE: capabilities=0x%X\n", cap_info_bitmap); /* Rest of the current buffer are IE's */ ie_buf = current_ptr; ie_len = curr_bcn_bytes; mwifiex_dbg(adapter, INFO, "info: InterpretIE: IELength for this AP = %d\n", curr_bcn_bytes); while (curr_bcn_bytes >= sizeof(struct ieee_types_header)) { u8 element_id, element_len; element_id = *current_ptr; element_len = *(current_ptr + 1); if (curr_bcn_bytes < element_len + sizeof(struct ieee_types_header)) { mwifiex_dbg(adapter, ERROR, "%s: bytes left < IE length\n", __func__); return -EFAULT; } if (element_id == WLAN_EID_DS_PARAMS) { channel = *(current_ptr + sizeof(struct ieee_types_header)); break; } current_ptr += element_len + sizeof(struct ieee_types_header); curr_bcn_bytes -= element_len + sizeof(struct ieee_types_header); } if (channel) { struct ieee80211_channel *chan; u8 band; /* Skip entry if on csa closed channel */ if (channel == priv->csa_chan) { mwifiex_dbg(adapter, WARN, "Dropping entry on csa closed channel\n"); return 0; } band = BAND_G; if (radio_type) band = mwifiex_radio_type_to_band(*radio_type & (BIT(0) | BIT(1))); cfp = mwifiex_get_cfp(priv, band, channel, 0); freq = cfp ? cfp->freq : 0; chan = ieee80211_get_channel(priv->wdev.wiphy, freq); if (chan && !(chan->flags & IEEE80211_CHAN_DISABLED)) { bss = cfg80211_inform_bss(priv->wdev.wiphy, chan, CFG80211_BSS_FTYPE_UNKNOWN, bssid, timestamp, cap_info_bitmap, beacon_period, ie_buf, ie_len, rssi, GFP_KERNEL); if (bss) { bss_priv = (struct mwifiex_bss_priv *)bss->priv; bss_priv->band = band; bss_priv->fw_tsf = fw_tsf; if (priv->media_connected && !memcmp(bssid, priv->curr_bss_params. bss_descriptor.mac_address, ETH_ALEN)) mwifiex_update_curr_bss_params(priv, bss); if ((chan->flags & IEEE80211_CHAN_RADAR) || (chan->flags & IEEE80211_CHAN_NO_IR)) { mwifiex_dbg(adapter, INFO, "radar or passive channel %d\n", channel); mwifiex_save_hidden_ssid_channels(priv, bss); } cfg80211_put_bss(priv->wdev.wiphy, bss); } } } else { mwifiex_dbg(adapter, WARN, "missing BSS channel IE\n"); } return 0; } static void mwifiex_complete_scan(struct mwifiex_private *priv) { struct mwifiex_adapter *adapter = priv->adapter; adapter->survey_idx = 0; if (adapter->curr_cmd->wait_q_enabled) { adapter->cmd_wait_q.status = 0; if (!priv->scan_request) { mwifiex_dbg(adapter, INFO, "complete internal scan\n"); mwifiex_complete_cmd(adapter, adapter->curr_cmd); } } } /* This function checks if any hidden SSID found in passive scan channels * and do specific SSID active scan for those channels */ static int mwifiex_active_scan_req_for_passive_chan(struct mwifiex_private *priv) { int ret; struct mwifiex_adapter *adapter = priv->adapter; u8 id = 0; struct mwifiex_user_scan_cfg *user_scan_cfg; if (adapter->active_scan_triggered || !priv->scan_request || priv->scan_aborting) { adapter->active_scan_triggered = false; return 0; } if (!priv->hidden_chan[0].chan_number) { mwifiex_dbg(adapter, INFO, "No BSS with hidden SSID found on DFS channels\n"); return 0; } user_scan_cfg = kzalloc(sizeof(*user_scan_cfg), GFP_KERNEL); if (!user_scan_cfg) return -ENOMEM; for (id = 0; id < MWIFIEX_USER_SCAN_CHAN_MAX; id++) { if (!priv->hidden_chan[id].chan_number) break; memcpy(&user_scan_cfg->chan_list[id], &priv->hidden_chan[id], sizeof(struct mwifiex_user_scan_chan)); } adapter->active_scan_triggered = true; if (priv->scan_request->flags & NL80211_SCAN_FLAG_RANDOM_ADDR) ether_addr_copy(user_scan_cfg->random_mac, priv->scan_request->mac_addr); user_scan_cfg->num_ssids = priv->scan_request->n_ssids; user_scan_cfg->ssid_list = priv->scan_request->ssids; ret = mwifiex_scan_networks(priv, user_scan_cfg); kfree(user_scan_cfg); memset(&priv->hidden_chan, 0, sizeof(priv->hidden_chan)); if (ret) { dev_err(priv->adapter->dev, "scan failed: %d\n", ret); return ret; } return 0; } static void mwifiex_check_next_scan_command(struct mwifiex_private *priv) { struct mwifiex_adapter *adapter = priv->adapter; struct cmd_ctrl_node *cmd_node; spin_lock_bh(&adapter->scan_pending_q_lock); if (list_empty(&adapter->scan_pending_q)) { spin_unlock_bh(&adapter->scan_pending_q_lock); spin_lock_bh(&adapter->mwifiex_cmd_lock); adapter->scan_processing = false; spin_unlock_bh(&adapter->mwifiex_cmd_lock); mwifiex_active_scan_req_for_passive_chan(priv); if (!adapter->ext_scan) mwifiex_complete_scan(priv); if (priv->scan_request) { struct cfg80211_scan_info info = { .aborted = false, }; mwifiex_dbg(adapter, INFO, "info: notifying scan done\n"); cfg80211_scan_done(priv->scan_request, &info); priv->scan_request = NULL; priv->scan_aborting = false; } else { priv->scan_aborting = false; mwifiex_dbg(adapter, INFO, "info: scan already aborted\n"); } } else if ((priv->scan_aborting && !priv->scan_request) || priv->scan_block) { spin_unlock_bh(&adapter->scan_pending_q_lock); mwifiex_cancel_pending_scan_cmd(adapter); spin_lock_bh(&adapter->mwifiex_cmd_lock); adapter->scan_processing = false; spin_unlock_bh(&adapter->mwifiex_cmd_lock); if (!adapter->active_scan_triggered) { if (priv->scan_request) { struct cfg80211_scan_info info = { .aborted = true, }; mwifiex_dbg(adapter, INFO, "info: aborting scan\n"); cfg80211_scan_done(priv->scan_request, &info); priv->scan_request = NULL; priv->scan_aborting = false; } else { priv->scan_aborting = false; mwifiex_dbg(adapter, INFO, "info: scan already aborted\n"); } } } else { /* Get scan command from scan_pending_q and put to * cmd_pending_q */ cmd_node = list_first_entry(&adapter->scan_pending_q, struct cmd_ctrl_node, list); list_del(&cmd_node->list); spin_unlock_bh(&adapter->scan_pending_q_lock); mwifiex_insert_cmd_to_pending_q(adapter, cmd_node); } return; } void mwifiex_cancel_scan(struct mwifiex_adapter *adapter) { struct mwifiex_private *priv; int i; mwifiex_cancel_pending_scan_cmd(adapter); if (adapter->scan_processing) { spin_lock_bh(&adapter->mwifiex_cmd_lock); adapter->scan_processing = false; spin_unlock_bh(&adapter->mwifiex_cmd_lock); for (i = 0; i < adapter->priv_num; i++) { priv = adapter->priv[i]; if (!priv) continue; if (priv->scan_request) { struct cfg80211_scan_info info = { .aborted = true, }; mwifiex_dbg(adapter, INFO, "info: aborting scan\n"); cfg80211_scan_done(priv->scan_request, &info); priv->scan_request = NULL; priv->scan_aborting = false; } } } } /* * This function handles the command response of scan. * * The response buffer for the scan command has the following * memory layout: * * .-------------------------------------------------------------. * | Header (4 * sizeof(t_u16)): Standard command response hdr | * .-------------------------------------------------------------. * | BufSize (t_u16) : sizeof the BSS Description data | * .-------------------------------------------------------------. * | NumOfSet (t_u8) : Number of BSS Descs returned | * .-------------------------------------------------------------. * | BSSDescription data (variable, size given in BufSize) | * .-------------------------------------------------------------. * | TLV data (variable, size calculated using Header->Size, | * | BufSize and sizeof the fixed fields above) | * .-------------------------------------------------------------. */ int mwifiex_ret_802_11_scan(struct mwifiex_private *priv, struct host_cmd_ds_command *resp) { int ret = 0; struct mwifiex_adapter *adapter = priv->adapter; struct host_cmd_ds_802_11_scan_rsp *scan_rsp; struct mwifiex_ie_types_data *tlv_data; struct mwifiex_ie_types_tsf_timestamp *tsf_tlv; u8 *bss_info; u32 scan_resp_size; u32 bytes_left; u32 idx; u32 tlv_buf_size; struct mwifiex_ie_types_chan_band_list_param_set *chan_band_tlv; struct chan_band_param_set *chan_band; u8 is_bgscan_resp; __le64 fw_tsf = 0; u8 *radio_type; struct cfg80211_wowlan_nd_match *pmatch; struct cfg80211_sched_scan_request *nd_config = NULL; is_bgscan_resp = (le16_to_cpu(resp->command) == HostCmd_CMD_802_11_BG_SCAN_QUERY); if (is_bgscan_resp) scan_rsp = &resp->params.bg_scan_query_resp.scan_resp; else scan_rsp = &resp->params.scan_resp; if (scan_rsp->number_of_sets > MWIFIEX_MAX_AP) { mwifiex_dbg(adapter, ERROR, "SCAN_RESP: too many AP returned (%d)\n", scan_rsp->number_of_sets); ret = -1; goto check_next_scan; } /* Check csa channel expiry before parsing scan response */ mwifiex_11h_get_csa_closed_channel(priv); bytes_left = le16_to_cpu(scan_rsp->bss_descript_size); mwifiex_dbg(adapter, INFO, "info: SCAN_RESP: bss_descript_size %d\n", bytes_left); scan_resp_size = le16_to_cpu(resp->size); mwifiex_dbg(adapter, INFO, "info: SCAN_RESP: returned %d APs before parsing\n", scan_rsp->number_of_sets); bss_info = scan_rsp->bss_desc_and_tlv_buffer; /* * The size of the TLV buffer is equal to the entire command response * size (scan_resp_size) minus the fixed fields (sizeof()'s), the * BSS Descriptions (bss_descript_size as bytesLef) and the command * response header (S_DS_GEN) */ tlv_buf_size = scan_resp_size - (bytes_left + sizeof(scan_rsp->bss_descript_size) + sizeof(scan_rsp->number_of_sets) + S_DS_GEN); tlv_data = (struct mwifiex_ie_types_data *) (scan_rsp-> bss_desc_and_tlv_buffer + bytes_left); /* Search the TLV buffer space in the scan response for any valid TLVs */ mwifiex_ret_802_11_scan_get_tlv_ptrs(adapter, tlv_data, tlv_buf_size, TLV_TYPE_TSFTIMESTAMP, (struct mwifiex_ie_types_data **) &tsf_tlv); /* Search the TLV buffer space in the scan response for any valid TLVs */ mwifiex_ret_802_11_scan_get_tlv_ptrs(adapter, tlv_data, tlv_buf_size, TLV_TYPE_CHANNELBANDLIST, (struct mwifiex_ie_types_data **) &chan_band_tlv); #ifdef CONFIG_PM if (priv->wdev.wiphy->wowlan_config) nd_config = priv->wdev.wiphy->wowlan_config->nd_config; #endif if (nd_config) { adapter->nd_info = kzalloc(sizeof(struct cfg80211_wowlan_nd_match) + sizeof(struct cfg80211_wowlan_nd_match *) * scan_rsp->number_of_sets, GFP_ATOMIC); if (adapter->nd_info) adapter->nd_info->n_matches = scan_rsp->number_of_sets; } for (idx = 0; idx < scan_rsp->number_of_sets && bytes_left; idx++) { /* * If the TSF TLV was appended to the scan results, save this * entry's TSF value in the fw_tsf field. It is the firmware's * TSF value at the time the beacon or probe response was * received. */ if (tsf_tlv) memcpy(&fw_tsf, &tsf_tlv->tsf_data[idx * TSF_DATA_SIZE], sizeof(fw_tsf)); if (chan_band_tlv) { chan_band = &chan_band_tlv->chan_band_param[idx]; radio_type = &chan_band->radio_type; } else { radio_type = NULL; } if (chan_band_tlv && adapter->nd_info) { adapter->nd_info->matches[idx] = kzalloc(sizeof(*pmatch) + sizeof(u32), GFP_ATOMIC); pmatch = adapter->nd_info->matches[idx]; if (pmatch) { pmatch->n_channels = 1; pmatch->channels[0] = chan_band->chan_number; } } ret = mwifiex_parse_single_response_buf(priv, &bss_info, &bytes_left, le64_to_cpu(fw_tsf), radio_type, false, 0); if (ret) goto check_next_scan; } check_next_scan: mwifiex_check_next_scan_command(priv); return ret; } /* * This function prepares an extended scan command to be sent to the firmware * * This uses the scan command configuration sent to the command processing * module in command preparation stage to configure a extended scan command * structure to send to firmware. */ int mwifiex_cmd_802_11_scan_ext(struct mwifiex_private *priv, struct host_cmd_ds_command *cmd, void *data_buf) { struct host_cmd_ds_802_11_scan_ext *ext_scan = &cmd->params.ext_scan; struct mwifiex_scan_cmd_config *scan_cfg = data_buf; memcpy(ext_scan->tlv_buffer, scan_cfg->tlv_buf, scan_cfg->tlv_buf_len); cmd->command = cpu_to_le16(HostCmd_CMD_802_11_SCAN_EXT); /* Size is equal to the sizeof(fixed portions) + the TLV len + header */ cmd->size = cpu_to_le16((u16)(sizeof(ext_scan->reserved) + scan_cfg->tlv_buf_len + S_DS_GEN)); return 0; } /* This function prepares an background scan config command to be sent * to the firmware */ int mwifiex_cmd_802_11_bg_scan_config(struct mwifiex_private *priv, struct host_cmd_ds_command *cmd, void *data_buf) { struct host_cmd_ds_802_11_bg_scan_config *bgscan_config = &cmd->params.bg_scan_config; struct mwifiex_bg_scan_cfg *bgscan_cfg_in = data_buf; u8 *tlv_pos = bgscan_config->tlv; u8 num_probes; u32 ssid_len, chan_idx, scan_type, scan_dur, chan_num; int i; struct mwifiex_ie_types_num_probes *num_probes_tlv; struct mwifiex_ie_types_repeat_count *repeat_count_tlv; struct mwifiex_ie_types_min_rssi_threshold *rssi_threshold_tlv; struct mwifiex_ie_types_bgscan_start_later *start_later_tlv; struct mwifiex_ie_types_wildcard_ssid_params *wildcard_ssid_tlv; struct mwifiex_ie_types_chan_list_param_set *chan_list_tlv; struct mwifiex_chan_scan_param_set *temp_chan; cmd->command = cpu_to_le16(HostCmd_CMD_802_11_BG_SCAN_CONFIG); cmd->size = cpu_to_le16(sizeof(*bgscan_config) + S_DS_GEN); bgscan_config->action = cpu_to_le16(bgscan_cfg_in->action); bgscan_config->enable = bgscan_cfg_in->enable; bgscan_config->bss_type = bgscan_cfg_in->bss_type; bgscan_config->scan_interval = cpu_to_le32(bgscan_cfg_in->scan_interval); bgscan_config->report_condition = cpu_to_le32(bgscan_cfg_in->report_condition); /* stop sched scan */ if (!bgscan_config->enable) return 0; bgscan_config->chan_per_scan = bgscan_cfg_in->chan_per_scan; num_probes = (bgscan_cfg_in->num_probes ? bgscan_cfg_in-> num_probes : priv->adapter->scan_probes); if (num_probes) { num_probes_tlv = (struct mwifiex_ie_types_num_probes *)tlv_pos; num_probes_tlv->header.type = cpu_to_le16(TLV_TYPE_NUMPROBES); num_probes_tlv->header.len = cpu_to_le16(sizeof(num_probes_tlv->num_probes)); num_probes_tlv->num_probes = cpu_to_le16((u16)num_probes); tlv_pos += sizeof(num_probes_tlv->header) + le16_to_cpu(num_probes_tlv->header.len); } if (bgscan_cfg_in->repeat_count) { repeat_count_tlv = (struct mwifiex_ie_types_repeat_count *)tlv_pos; repeat_count_tlv->header.type = cpu_to_le16(TLV_TYPE_REPEAT_COUNT); repeat_count_tlv->header.len = cpu_to_le16(sizeof(repeat_count_tlv->repeat_count)); repeat_count_tlv->repeat_count = cpu_to_le16(bgscan_cfg_in->repeat_count); tlv_pos += sizeof(repeat_count_tlv->header) + le16_to_cpu(repeat_count_tlv->header.len); } if (bgscan_cfg_in->rssi_threshold) { rssi_threshold_tlv = (struct mwifiex_ie_types_min_rssi_threshold *)tlv_pos; rssi_threshold_tlv->header.type = cpu_to_le16(TLV_TYPE_RSSI_LOW); rssi_threshold_tlv->header.len = cpu_to_le16(sizeof(rssi_threshold_tlv->rssi_threshold)); rssi_threshold_tlv->rssi_threshold = cpu_to_le16(bgscan_cfg_in->rssi_threshold); tlv_pos += sizeof(rssi_threshold_tlv->header) + le16_to_cpu(rssi_threshold_tlv->header.len); } for (i = 0; i < bgscan_cfg_in->num_ssids; i++) { ssid_len = bgscan_cfg_in->ssid_list[i].ssid.ssid_len; wildcard_ssid_tlv = (struct mwifiex_ie_types_wildcard_ssid_params *)tlv_pos; wildcard_ssid_tlv->header.type = cpu_to_le16(TLV_TYPE_WILDCARDSSID); wildcard_ssid_tlv->header.len = cpu_to_le16( (u16)(ssid_len + sizeof(wildcard_ssid_tlv-> max_ssid_length))); /* max_ssid_length = 0 tells firmware to perform * specific scan for the SSID filled, whereas * max_ssid_length = IEEE80211_MAX_SSID_LEN is for * wildcard scan. */ if (ssid_len) wildcard_ssid_tlv->max_ssid_length = 0; else wildcard_ssid_tlv->max_ssid_length = IEEE80211_MAX_SSID_LEN; memcpy(wildcard_ssid_tlv->ssid, bgscan_cfg_in->ssid_list[i].ssid.ssid, ssid_len); tlv_pos += (sizeof(wildcard_ssid_tlv->header) + le16_to_cpu(wildcard_ssid_tlv->header.len)); } chan_list_tlv = (struct mwifiex_ie_types_chan_list_param_set *)tlv_pos; if (bgscan_cfg_in->chan_list[0].chan_number) { dev_dbg(priv->adapter->dev, "info: bgscan: Using supplied channel list\n"); chan_list_tlv->header.type = cpu_to_le16(TLV_TYPE_CHANLIST); for (chan_idx = 0; chan_idx < MWIFIEX_BG_SCAN_CHAN_MAX && bgscan_cfg_in->chan_list[chan_idx].chan_number; chan_idx++) { temp_chan = chan_list_tlv->chan_scan_param + chan_idx; /* Increment the TLV header length by size appended */ le16_unaligned_add_cpu(&chan_list_tlv->header.len, sizeof( chan_list_tlv->chan_scan_param)); temp_chan->chan_number = bgscan_cfg_in->chan_list[chan_idx].chan_number; temp_chan->radio_type = bgscan_cfg_in->chan_list[chan_idx].radio_type; scan_type = bgscan_cfg_in->chan_list[chan_idx].scan_type; if (scan_type == MWIFIEX_SCAN_TYPE_PASSIVE) temp_chan->chan_scan_mode_bitmap |= MWIFIEX_PASSIVE_SCAN; else temp_chan->chan_scan_mode_bitmap &= ~MWIFIEX_PASSIVE_SCAN; if (bgscan_cfg_in->chan_list[chan_idx].scan_time) { scan_dur = (u16)bgscan_cfg_in-> chan_list[chan_idx].scan_time; } else { scan_dur = (scan_type == MWIFIEX_SCAN_TYPE_PASSIVE) ? priv->adapter->passive_scan_time : priv->adapter->specific_scan_time; } temp_chan->min_scan_time = cpu_to_le16(scan_dur); temp_chan->max_scan_time = cpu_to_le16(scan_dur); } } else { dev_dbg(priv->adapter->dev, "info: bgscan: Creating full region channel list\n"); chan_num = mwifiex_bgscan_create_channel_list(priv, bgscan_cfg_in, chan_list_tlv-> chan_scan_param); le16_unaligned_add_cpu(&chan_list_tlv->header.len, chan_num * sizeof(chan_list_tlv->chan_scan_param[0])); } tlv_pos += (sizeof(chan_list_tlv->header) + le16_to_cpu(chan_list_tlv->header.len)); if (bgscan_cfg_in->start_later) { start_later_tlv = (struct mwifiex_ie_types_bgscan_start_later *)tlv_pos; start_later_tlv->header.type = cpu_to_le16(TLV_TYPE_BGSCAN_START_LATER); start_later_tlv->header.len = cpu_to_le16(sizeof(start_later_tlv->start_later)); start_later_tlv->start_later = cpu_to_le16(bgscan_cfg_in->start_later); tlv_pos += sizeof(start_later_tlv->header) + le16_to_cpu(start_later_tlv->header.len); } /* Append vendor specific IE TLV */ mwifiex_cmd_append_vsie_tlv(priv, MWIFIEX_VSIE_MASK_BGSCAN, &tlv_pos); le16_unaligned_add_cpu(&cmd->size, tlv_pos - bgscan_config->tlv); return 0; } int mwifiex_stop_bg_scan(struct mwifiex_private *priv) { struct mwifiex_bg_scan_cfg *bgscan_cfg; if (!priv->sched_scanning) { dev_dbg(priv->adapter->dev, "bgscan already stopped!\n"); return 0; } bgscan_cfg = kzalloc(sizeof(*bgscan_cfg), GFP_KERNEL); if (!bgscan_cfg) return -ENOMEM; bgscan_cfg->bss_type = MWIFIEX_BSS_MODE_INFRA; bgscan_cfg->action = MWIFIEX_BGSCAN_ACT_SET; bgscan_cfg->enable = false; if (mwifiex_send_cmd(priv, HostCmd_CMD_802_11_BG_SCAN_CONFIG, HostCmd_ACT_GEN_SET, 0, bgscan_cfg, true)) { kfree(bgscan_cfg); return -EFAULT; } kfree(bgscan_cfg); priv->sched_scanning = false; return 0; } static void mwifiex_update_chan_statistics(struct mwifiex_private *priv, struct mwifiex_ietypes_chanstats *tlv_stat) { struct mwifiex_adapter *adapter = priv->adapter; u8 i, num_chan; struct mwifiex_fw_chan_stats *fw_chan_stats; struct mwifiex_chan_stats chan_stats; fw_chan_stats = (void *)((u8 *)tlv_stat + sizeof(struct mwifiex_ie_types_header)); num_chan = le16_to_cpu(tlv_stat->header.len) / sizeof(struct mwifiex_chan_stats); for (i = 0 ; i < num_chan; i++) { if (adapter->survey_idx >= adapter->num_in_chan_stats) { mwifiex_dbg(adapter, WARN, "FW reported too many channel results (max %d)\n", adapter->num_in_chan_stats); return; } chan_stats.chan_num = fw_chan_stats->chan_num; chan_stats.bandcfg = fw_chan_stats->bandcfg; chan_stats.flags = fw_chan_stats->flags; chan_stats.noise = fw_chan_stats->noise; chan_stats.total_bss = le16_to_cpu(fw_chan_stats->total_bss); chan_stats.cca_scan_dur = le16_to_cpu(fw_chan_stats->cca_scan_dur); chan_stats.cca_busy_dur = le16_to_cpu(fw_chan_stats->cca_busy_dur); mwifiex_dbg(adapter, INFO, "chan=%d, noise=%d, total_network=%d scan_duration=%d, busy_duration=%d\n", chan_stats.chan_num, chan_stats.noise, chan_stats.total_bss, chan_stats.cca_scan_dur, chan_stats.cca_busy_dur); memcpy(&adapter->chan_stats[adapter->survey_idx++], &chan_stats, sizeof(struct mwifiex_chan_stats)); fw_chan_stats++; } } /* This function handles the command response of extended scan */ int mwifiex_ret_802_11_scan_ext(struct mwifiex_private *priv, struct host_cmd_ds_command *resp) { struct mwifiex_adapter *adapter = priv->adapter; struct host_cmd_ds_802_11_scan_ext *ext_scan_resp; struct mwifiex_ie_types_header *tlv; struct mwifiex_ietypes_chanstats *tlv_stat; u16 buf_left, type, len; struct host_cmd_ds_command *cmd_ptr; struct cmd_ctrl_node *cmd_node; bool complete_scan = false; mwifiex_dbg(adapter, INFO, "info: EXT scan returns successfully\n"); ext_scan_resp = &resp->params.ext_scan; tlv = (void *)ext_scan_resp->tlv_buffer; buf_left = le16_to_cpu(resp->size) - (sizeof(*ext_scan_resp) + S_DS_GEN - 1); while (buf_left >= sizeof(struct mwifiex_ie_types_header)) { type = le16_to_cpu(tlv->type); len = le16_to_cpu(tlv->len); if (buf_left < (sizeof(struct mwifiex_ie_types_header) + len)) { mwifiex_dbg(adapter, ERROR, "error processing scan response TLVs"); break; } switch (type) { case TLV_TYPE_CHANNEL_STATS: tlv_stat = (void *)tlv; mwifiex_update_chan_statistics(priv, tlv_stat); break; default: break; } buf_left -= len + sizeof(struct mwifiex_ie_types_header); tlv = (void *)((u8 *)tlv + len + sizeof(struct mwifiex_ie_types_header)); } spin_lock_bh(&adapter->cmd_pending_q_lock); spin_lock_bh(&adapter->scan_pending_q_lock); if (list_empty(&adapter->scan_pending_q)) { complete_scan = true; list_for_each_entry(cmd_node, &adapter->cmd_pending_q, list) { cmd_ptr = (void *)cmd_node->cmd_skb->data; if (le16_to_cpu(cmd_ptr->command) == HostCmd_CMD_802_11_SCAN_EXT) { mwifiex_dbg(adapter, INFO, "Scan pending in command pending list"); complete_scan = false; break; } } } spin_unlock_bh(&adapter->scan_pending_q_lock); spin_unlock_bh(&adapter->cmd_pending_q_lock); if (complete_scan) mwifiex_complete_scan(priv); return 0; } /* This function This function handles the event extended scan report. It * parses extended scan results and informs to cfg80211 stack. */ int mwifiex_handle_event_ext_scan_report(struct mwifiex_private *priv, void *buf) { int ret = 0; struct mwifiex_adapter *adapter = priv->adapter; u8 *bss_info; u32 bytes_left, bytes_left_for_tlv, idx; u16 type, len; struct mwifiex_ie_types_data *tlv; struct mwifiex_ie_types_bss_scan_rsp *scan_rsp_tlv; struct mwifiex_ie_types_bss_scan_info *scan_info_tlv; u8 *radio_type; u64 fw_tsf = 0; s32 rssi = 0; struct mwifiex_event_scan_result *event_scan = buf; u8 num_of_set = event_scan->num_of_set; u8 *scan_resp = buf + sizeof(struct mwifiex_event_scan_result); u16 scan_resp_size = le16_to_cpu(event_scan->buf_size); if (num_of_set > MWIFIEX_MAX_AP) { mwifiex_dbg(adapter, ERROR, "EXT_SCAN: Invalid number of AP returned (%d)!!\n", num_of_set); ret = -1; goto check_next_scan; } bytes_left = scan_resp_size; mwifiex_dbg(adapter, INFO, "EXT_SCAN: size %d, returned %d APs...", scan_resp_size, num_of_set); mwifiex_dbg_dump(adapter, CMD_D, "EXT_SCAN buffer:", buf, scan_resp_size + sizeof(struct mwifiex_event_scan_result)); tlv = (struct mwifiex_ie_types_data *)scan_resp; for (idx = 0; idx < num_of_set && bytes_left; idx++) { type = le16_to_cpu(tlv->header.type); len = le16_to_cpu(tlv->header.len); if (bytes_left < sizeof(struct mwifiex_ie_types_header) + len) { mwifiex_dbg(adapter, ERROR, "EXT_SCAN: Error bytes left < TLV length\n"); break; } scan_rsp_tlv = NULL; scan_info_tlv = NULL; bytes_left_for_tlv = bytes_left; /* BSS response TLV with beacon or probe response buffer * at the initial position of each descriptor */ if (type != TLV_TYPE_BSS_SCAN_RSP) break; bss_info = (u8 *)tlv; scan_rsp_tlv = (struct mwifiex_ie_types_bss_scan_rsp *)tlv; tlv = (struct mwifiex_ie_types_data *)(tlv->data + len); bytes_left_for_tlv -= (len + sizeof(struct mwifiex_ie_types_header)); while (bytes_left_for_tlv >= sizeof(struct mwifiex_ie_types_header) && le16_to_cpu(tlv->header.type) != TLV_TYPE_BSS_SCAN_RSP) { type = le16_to_cpu(tlv->header.type); len = le16_to_cpu(tlv->header.len); if (bytes_left_for_tlv < sizeof(struct mwifiex_ie_types_header) + len) { mwifiex_dbg(adapter, ERROR, "EXT_SCAN: Error in processing TLV,\t" "bytes left < TLV length\n"); scan_rsp_tlv = NULL; bytes_left_for_tlv = 0; continue; } switch (type) { case TLV_TYPE_BSS_SCAN_INFO: scan_info_tlv = (struct mwifiex_ie_types_bss_scan_info *)tlv; if (len != sizeof(struct mwifiex_ie_types_bss_scan_info) - sizeof(struct mwifiex_ie_types_header)) { bytes_left_for_tlv = 0; continue; } break; default: break; } tlv = (struct mwifiex_ie_types_data *)(tlv->data + len); bytes_left -= (len + sizeof(struct mwifiex_ie_types_header)); bytes_left_for_tlv -= (len + sizeof(struct mwifiex_ie_types_header)); } if (!scan_rsp_tlv) break; /* Advance pointer to the beacon buffer length and * update the bytes count so that the function * wlan_interpret_bss_desc_with_ie() can handle the * scan buffer withut any change */ bss_info += sizeof(u16); bytes_left -= sizeof(u16); if (scan_info_tlv) { rssi = (s32)(s16)(le16_to_cpu(scan_info_tlv->rssi)); rssi *= 100; /* Convert dBm to mBm */ mwifiex_dbg(adapter, INFO, "info: InterpretIE: RSSI=%d\n", rssi); fw_tsf = le64_to_cpu(scan_info_tlv->tsf); radio_type = &scan_info_tlv->radio_type; } else { radio_type = NULL; } ret = mwifiex_parse_single_response_buf(priv, &bss_info, &bytes_left, fw_tsf, radio_type, true, rssi); if (ret) goto check_next_scan; } check_next_scan: if (!event_scan->more_event) mwifiex_check_next_scan_command(priv); return ret; } /* * This function prepares command for background scan query. * * Preparation includes - * - Setting command ID and proper size * - Setting background scan flush parameter * - Ensuring correct endian-ness */ int mwifiex_cmd_802_11_bg_scan_query(struct host_cmd_ds_command *cmd) { struct host_cmd_ds_802_11_bg_scan_query *bg_query = &cmd->params.bg_scan_query; cmd->command = cpu_to_le16(HostCmd_CMD_802_11_BG_SCAN_QUERY); cmd->size = cpu_to_le16(sizeof(struct host_cmd_ds_802_11_bg_scan_query) + S_DS_GEN); bg_query->flush = 1; return 0; } /* * This function inserts scan command node to the scan pending queue. */ void mwifiex_queue_scan_cmd(struct mwifiex_private *priv, struct cmd_ctrl_node *cmd_node) { struct mwifiex_adapter *adapter = priv->adapter; cmd_node->wait_q_enabled = true; cmd_node->condition = &adapter->scan_wait_q_woken; spin_lock_bh(&adapter->scan_pending_q_lock); list_add_tail(&cmd_node->list, &adapter->scan_pending_q); spin_unlock_bh(&adapter->scan_pending_q_lock); } /* * This function sends a scan command for all available channels to the * firmware, filtered on a specific SSID. */ static int mwifiex_scan_specific_ssid(struct mwifiex_private *priv, struct cfg80211_ssid *req_ssid) { struct mwifiex_adapter *adapter = priv->adapter; int ret; struct mwifiex_user_scan_cfg *scan_cfg; if (adapter->scan_processing) { mwifiex_dbg(adapter, WARN, "cmd: Scan already in process...\n"); return -EBUSY; } if (priv->scan_block) { mwifiex_dbg(adapter, WARN, "cmd: Scan is blocked during association...\n"); return -EBUSY; } scan_cfg = kzalloc(sizeof(struct mwifiex_user_scan_cfg), GFP_KERNEL); if (!scan_cfg) return -ENOMEM; scan_cfg->ssid_list = req_ssid; scan_cfg->num_ssids = 1; ret = mwifiex_scan_networks(priv, scan_cfg); kfree(scan_cfg); return ret; } /* * Sends IOCTL request to start a scan. * * This function allocates the IOCTL request buffer, fills it * with requisite parameters and calls the IOCTL handler. * * Scan command can be issued for both normal scan and specific SSID * scan, depending upon whether an SSID is provided or not. */ int mwifiex_request_scan(struct mwifiex_private *priv, struct cfg80211_ssid *req_ssid) { int ret; if (mutex_lock_interruptible(&priv->async_mutex)) { mwifiex_dbg(priv->adapter, ERROR, "%s: acquire semaphore fail\n", __func__); return -1; } priv->adapter->scan_wait_q_woken = false; if (req_ssid && req_ssid->ssid_len != 0) /* Specific SSID scan */ ret = mwifiex_scan_specific_ssid(priv, req_ssid); else /* Normal scan */ ret = mwifiex_scan_networks(priv, NULL); mutex_unlock(&priv->async_mutex); return ret; } /* * This function appends the vendor specific IE TLV to a buffer. */ int mwifiex_cmd_append_vsie_tlv(struct mwifiex_private *priv, u16 vsie_mask, u8 **buffer) { int id, ret_len = 0; struct mwifiex_ie_types_vendor_param_set *vs_param_set; if (!buffer) return 0; if (!(*buffer)) return 0; /* * Traverse through the saved vendor specific IE array and append * the selected(scan/assoc/adhoc) IE as TLV to the command */ for (id = 0; id < MWIFIEX_MAX_VSIE_NUM; id++) { if (priv->vs_ie[id].mask & vsie_mask) { vs_param_set = (struct mwifiex_ie_types_vendor_param_set *) *buffer; vs_param_set->header.type = cpu_to_le16(TLV_TYPE_PASSTHROUGH); vs_param_set->header.len = cpu_to_le16((((u16) priv->vs_ie[id].ie[1]) & 0x00FF) + 2); memcpy(vs_param_set->ie, priv->vs_ie[id].ie, le16_to_cpu(vs_param_set->header.len)); *buffer += le16_to_cpu(vs_param_set->header.len) + sizeof(struct mwifiex_ie_types_header); ret_len += le16_to_cpu(vs_param_set->header.len) + sizeof(struct mwifiex_ie_types_header); } } return ret_len; } /* * This function saves a beacon buffer of the current BSS descriptor. * * The current beacon buffer is saved so that it can be restored in the * following cases that makes the beacon buffer not to contain the current * ssid's beacon buffer. * - The current ssid was not found somehow in the last scan. * - The current ssid was the last entry of the scan table and overloaded. */ void mwifiex_save_curr_bcn(struct mwifiex_private *priv) { struct mwifiex_bssdescriptor *curr_bss = &priv->curr_bss_params.bss_descriptor; if (!curr_bss->beacon_buf_size) return; /* allocate beacon buffer at 1st time; or if it's size has changed */ if (!priv->curr_bcn_buf || priv->curr_bcn_size != curr_bss->beacon_buf_size) { priv->curr_bcn_size = curr_bss->beacon_buf_size; kfree(priv->curr_bcn_buf); priv->curr_bcn_buf = kmalloc(curr_bss->beacon_buf_size, GFP_ATOMIC); if (!priv->curr_bcn_buf) return; } memcpy(priv->curr_bcn_buf, curr_bss->beacon_buf, curr_bss->beacon_buf_size); mwifiex_dbg(priv->adapter, INFO, "info: current beacon saved %d\n", priv->curr_bcn_size); curr_bss->beacon_buf = priv->curr_bcn_buf; /* adjust the pointers in the current BSS descriptor */ if (curr_bss->bcn_wpa_ie) curr_bss->bcn_wpa_ie = (struct ieee_types_vendor_specific *) (curr_bss->beacon_buf + curr_bss->wpa_offset); if (curr_bss->bcn_rsn_ie) curr_bss->bcn_rsn_ie = (struct ieee_types_generic *) (curr_bss->beacon_buf + curr_bss->rsn_offset); if (curr_bss->bcn_ht_cap) curr_bss->bcn_ht_cap = (struct ieee80211_ht_cap *) (curr_bss->beacon_buf + curr_bss->ht_cap_offset); if (curr_bss->bcn_ht_oper) curr_bss->bcn_ht_oper = (struct ieee80211_ht_operation *) (curr_bss->beacon_buf + curr_bss->ht_info_offset); if (curr_bss->bcn_vht_cap) curr_bss->bcn_vht_cap = (void *)(curr_bss->beacon_buf + curr_bss->vht_cap_offset); if (curr_bss->bcn_vht_oper) curr_bss->bcn_vht_oper = (void *)(curr_bss->beacon_buf + curr_bss->vht_info_offset); if (curr_bss->bcn_bss_co_2040) curr_bss->bcn_bss_co_2040 = (curr_bss->beacon_buf + curr_bss->bss_co_2040_offset); if (curr_bss->bcn_ext_cap) curr_bss->bcn_ext_cap = curr_bss->beacon_buf + curr_bss->ext_cap_offset; if (curr_bss->oper_mode) curr_bss->oper_mode = (void *)(curr_bss->beacon_buf + curr_bss->oper_mode_offset); } /* * This function frees the current BSS descriptor beacon buffer. */ void mwifiex_free_curr_bcn(struct mwifiex_private *priv) { kfree(priv->curr_bcn_buf); priv->curr_bcn_buf = NULL; }
null
/* * Marvell Wireless LAN device driver: scan ioctl and command handling * * Copyright (C) 2011-2014, Marvell International Ltd. * * This software file (the "File") is distributed by Marvell International * Ltd. under the terms of the GNU General Public License Version 2, June 1991 * (the "License"). You may use, redistribute and/or modify this File in * accordance with the terms and conditions of the License, a copy of which * is available by writing to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the * worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE * IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE * ARE EXPRESSLY DISCLAIMED. The License provides additional details about * this warranty disclaimer. */ #include "decl.h" #include "ioctl.h" #include "util.h" #include "fw.h" #include "main.h" #include "11n.h" #include "cfg80211.h" /* The maximum number of channels the firmware can scan per command */ #define MWIFIEX_MAX_CHANNELS_PER_SPECIFIC_SCAN 14 #define MWIFIEX_DEF_CHANNELS_PER_SCAN_CMD 4 /* Memory needed to store a max sized Channel List TLV for a firmware scan */ #define CHAN_TLV_MAX_SIZE (sizeof(struct mwifiex_ie_types_header) \ + (MWIFIEX_MAX_CHANNELS_PER_SPECIFIC_SCAN \ *sizeof(struct mwifiex_chan_scan_param_set))) /* Memory needed to store supported rate */ #define RATE_TLV_MAX_SIZE (sizeof(struct mwifiex_ie_types_rates_param_set) \ + HOSTCMD_SUPPORTED_RATES) /* Memory needed to store a max number/size WildCard SSID TLV for a firmware scan */ #define WILDCARD_SSID_TLV_MAX_SIZE \ (MWIFIEX_MAX_SSID_LIST_LENGTH * \ (sizeof(struct mwifiex_ie_types_wildcard_ssid_params) \ + IEEE80211_MAX_SSID_LEN)) /* Maximum memory needed for a mwifiex_scan_cmd_config with all TLVs at max */ #define MAX_SCAN_CFG_ALLOC (sizeof(struct mwifiex_scan_cmd_config) \ + sizeof(struct mwifiex_ie_types_num_probes) \ + sizeof(struct mwifiex_ie_types_htcap) \ + CHAN_TLV_MAX_SIZE \ + RATE_TLV_MAX_SIZE \ + WILDCARD_SSID_TLV_MAX_SIZE) union mwifiex_scan_cmd_config_tlv { /* Scan configuration (variable length) */ struct mwifiex_scan_cmd_config config; /* Max allocated block */ u8 config_alloc_buf[MAX_SCAN_CFG_ALLOC]; }; enum cipher_suite { CIPHER_SUITE_TKIP, CIPHER_SUITE_CCMP, CIPHER_SUITE_MAX }; static u8 mwifiex_wpa_oui[CIPHER_SUITE_MAX][4] = { { 0x00, 0x50, 0xf2, 0x02 }, /* TKIP */ { 0x00, 0x50, 0xf2, 0x04 }, /* AES */ }; static u8 mwifiex_rsn_oui[CIPHER_SUITE_MAX][4] = { { 0x00, 0x0f, 0xac, 0x02 }, /* TKIP */ { 0x00, 0x0f, 0xac, 0x04 }, /* AES */ }; static void _dbg_security_flags(int log_level, const char *func, const char *desc, struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc) { _mwifiex_dbg(priv->adapter, log_level, "info: %s: %s:\twpa_ie=%#x wpa2_ie=%#x WEP=%s WPA=%s WPA2=%s\tEncMode=%#x privacy=%#x\n", func, desc, bss_desc->bcn_wpa_ie ? bss_desc->bcn_wpa_ie->vend_hdr.element_id : 0, bss_desc->bcn_rsn_ie ? bss_desc->bcn_rsn_ie->ieee_hdr.element_id : 0, priv->sec_info.wep_enabled ? "e" : "d", priv->sec_info.wpa_enabled ? "e" : "d", priv->sec_info.wpa2_enabled ? "e" : "d", priv->sec_info.encryption_mode, bss_desc->privacy); } #define dbg_security_flags(mask, desc, priv, bss_desc) \ _dbg_security_flags(MWIFIEX_DBG_##mask, desc, __func__, priv, bss_desc) static bool has_ieee_hdr(struct ieee_types_generic *ie, u8 key) { return (ie && ie->ieee_hdr.element_id == key); } static bool has_vendor_hdr(struct ieee_types_vendor_specific *ie, u8 key) { return (ie && ie->vend_hdr.element_id == key); } /* * This function parses a given IE for a given OUI. * * This is used to parse a WPA/RSN IE to find if it has * a given oui in PTK. */ static u8 mwifiex_search_oui_in_ie(struct ie_body *iebody, u8 *oui) { u8 count; count = iebody->ptk_cnt[0]; /* There could be multiple OUIs for PTK hence 1) Take the length. 2) Check all the OUIs for AES. 3) If one of them is AES then pass success. */ while (count) { if (!memcmp(iebody->ptk_body, oui, sizeof(iebody->ptk_body))) return MWIFIEX_OUI_PRESENT; --count; if (count) iebody = (struct ie_body *) ((u8 *) iebody + sizeof(iebody->ptk_body)); } pr_debug("info: %s: OUI is not found in PTK\n", __func__); return MWIFIEX_OUI_NOT_PRESENT; } /* * This function checks if a given OUI is present in a RSN IE. * * The function first checks if a RSN IE is present or not in the * BSS descriptor. It tries to locate the OUI only if such an IE is * present. */ static u8 mwifiex_is_rsn_oui_present(struct mwifiex_bssdescriptor *bss_desc, u32 cipher) { u8 *oui; struct ie_body *iebody; u8 ret = MWIFIEX_OUI_NOT_PRESENT; if (has_ieee_hdr(bss_desc->bcn_rsn_ie, WLAN_EID_RSN)) { iebody = (struct ie_body *) (((u8 *) bss_desc->bcn_rsn_ie->data) + RSN_GTK_OUI_OFFSET); oui = &mwifiex_rsn_oui[cipher][0]; ret = mwifiex_search_oui_in_ie(iebody, oui); if (ret) return ret; } return ret; } /* * This function checks if a given OUI is present in a WPA IE. * * The function first checks if a WPA IE is present or not in the * BSS descriptor. It tries to locate the OUI only if such an IE is * present. */ static u8 mwifiex_is_wpa_oui_present(struct mwifiex_bssdescriptor *bss_desc, u32 cipher) { u8 *oui; struct ie_body *iebody; u8 ret = MWIFIEX_OUI_NOT_PRESENT; if (has_vendor_hdr(bss_desc->bcn_wpa_ie, WLAN_EID_VENDOR_SPECIFIC)) { iebody = (struct ie_body *)((u8 *)bss_desc->bcn_wpa_ie->data + WPA_GTK_OUI_OFFSET); oui = &mwifiex_wpa_oui[cipher][0]; ret = mwifiex_search_oui_in_ie(iebody, oui); if (ret) return ret; } return ret; } /* * This function compares two SSIDs and checks if they match. */ s32 mwifiex_ssid_cmp(struct cfg80211_ssid *ssid1, struct cfg80211_ssid *ssid2) { if (!ssid1 || !ssid2 || (ssid1->ssid_len != ssid2->ssid_len)) return -1; return memcmp(ssid1->ssid, ssid2->ssid, ssid1->ssid_len); } /* * This function checks if wapi is enabled in driver and scanned network is * compatible with it. */ static bool mwifiex_is_bss_wapi(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc) { if (priv->sec_info.wapi_enabled && has_ieee_hdr(bss_desc->bcn_wapi_ie, WLAN_EID_BSS_AC_ACCESS_DELAY)) return true; return false; } /* * This function checks if driver is configured with no security mode and * scanned network is compatible with it. */ static bool mwifiex_is_bss_no_sec(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc) { if (!priv->sec_info.wep_enabled && !priv->sec_info.wpa_enabled && !priv->sec_info.wpa2_enabled && !has_vendor_hdr(bss_desc->bcn_wpa_ie, WLAN_EID_VENDOR_SPECIFIC) && !has_ieee_hdr(bss_desc->bcn_rsn_ie, WLAN_EID_RSN) && !priv->sec_info.encryption_mode && !bss_desc->privacy) { return true; } return false; } /* * This function checks if static WEP is enabled in driver and scanned network * is compatible with it. */ static bool mwifiex_is_bss_static_wep(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc) { if (priv->sec_info.wep_enabled && !priv->sec_info.wpa_enabled && !priv->sec_info.wpa2_enabled && bss_desc->privacy) { return true; } return false; } /* * This function checks if wpa is enabled in driver and scanned network is * compatible with it. */ static bool mwifiex_is_bss_wpa(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc) { if (!priv->sec_info.wep_enabled && priv->sec_info.wpa_enabled && !priv->sec_info.wpa2_enabled && has_vendor_hdr(bss_desc->bcn_wpa_ie, WLAN_EID_VENDOR_SPECIFIC) /* * Privacy bit may NOT be set in some APs like * LinkSys WRT54G && bss_desc->privacy */ ) { dbg_security_flags(INFO, "WPA", priv, bss_desc); return true; } return false; } /* * This function checks if wpa2 is enabled in driver and scanned network is * compatible with it. */ static bool mwifiex_is_bss_wpa2(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc) { if (!priv->sec_info.wep_enabled && !priv->sec_info.wpa_enabled && priv->sec_info.wpa2_enabled && has_ieee_hdr(bss_desc->bcn_rsn_ie, WLAN_EID_RSN)) { /* * Privacy bit may NOT be set in some APs like * LinkSys WRT54G && bss_desc->privacy */ dbg_security_flags(INFO, "WAP2", priv, bss_desc); return true; } return false; } /* * This function checks if adhoc AES is enabled in driver and scanned network is * compatible with it. */ static bool mwifiex_is_bss_adhoc_aes(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc) { if (!priv->sec_info.wep_enabled && !priv->sec_info.wpa_enabled && !priv->sec_info.wpa2_enabled && !has_vendor_hdr(bss_desc->bcn_wpa_ie, WLAN_EID_VENDOR_SPECIFIC) && !has_ieee_hdr(bss_desc->bcn_rsn_ie, WLAN_EID_RSN) && !priv->sec_info.encryption_mode && bss_desc->privacy) { return true; } return false; } /* * This function checks if dynamic WEP is enabled in driver and scanned network * is compatible with it. */ static bool mwifiex_is_bss_dynamic_wep(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc) { if (!priv->sec_info.wep_enabled && !priv->sec_info.wpa_enabled && !priv->sec_info.wpa2_enabled && !has_vendor_hdr(bss_desc->bcn_wpa_ie, WLAN_EID_VENDOR_SPECIFIC) && !has_ieee_hdr(bss_desc->bcn_rsn_ie, WLAN_EID_RSN) && priv->sec_info.encryption_mode && bss_desc->privacy) { dbg_security_flags(INFO, "dynamic", priv, bss_desc); return true; } return false; } /* * This function checks if a scanned network is compatible with the driver * settings. * * WEP WPA WPA2 ad-hoc encrypt Network * enabled enabled enabled AES mode Privacy WPA WPA2 Compatible * 0 0 0 0 NONE 0 0 0 yes No security * 0 1 0 0 x 1x 1 x yes WPA (disable * HT if no AES) * 0 0 1 0 x 1x x 1 yes WPA2 (disable * HT if no AES) * 0 0 0 1 NONE 1 0 0 yes Ad-hoc AES * 1 0 0 0 NONE 1 0 0 yes Static WEP * (disable HT) * 0 0 0 0 !=NONE 1 0 0 yes Dynamic WEP * * Compatibility is not matched while roaming, except for mode. */ static s32 mwifiex_is_network_compatible(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc, u32 mode) { struct mwifiex_adapter *adapter = priv->adapter; bss_desc->disable_11n = false; /* Don't check for compatibility if roaming */ if (priv->media_connected && (priv->bss_mode == NL80211_IFTYPE_STATION) && (bss_desc->bss_mode == NL80211_IFTYPE_STATION)) return 0; if (priv->wps.session_enable) { mwifiex_dbg(adapter, IOCTL, "info: return success directly in WPS period\n"); return 0; } if (bss_desc->chan_sw_ie_present) { mwifiex_dbg(adapter, INFO, "Don't connect to AP with WLAN_EID_CHANNEL_SWITCH\n"); return -1; } if (mwifiex_is_bss_wapi(priv, bss_desc)) { mwifiex_dbg(adapter, INFO, "info: return success for WAPI AP\n"); return 0; } if (bss_desc->bss_mode == mode) { if (mwifiex_is_bss_no_sec(priv, bss_desc)) { /* No security */ return 0; } else if (mwifiex_is_bss_static_wep(priv, bss_desc)) { /* Static WEP enabled */ mwifiex_dbg(adapter, INFO, "info: Disable 11n in WEP mode.\n"); bss_desc->disable_11n = true; return 0; } else if (mwifiex_is_bss_wpa(priv, bss_desc)) { /* WPA enabled */ if (((priv->adapter->config_bands & BAND_GN || priv->adapter->config_bands & BAND_AN) && bss_desc->bcn_ht_cap) && !mwifiex_is_wpa_oui_present(bss_desc, CIPHER_SUITE_CCMP)) { if (mwifiex_is_wpa_oui_present (bss_desc, CIPHER_SUITE_TKIP)) { mwifiex_dbg(adapter, INFO, "info: Disable 11n if AES\t" "is not supported by AP\n"); bss_desc->disable_11n = true; } else { return -1; } } return 0; } else if (mwifiex_is_bss_wpa2(priv, bss_desc)) { /* WPA2 enabled */ if (((priv->adapter->config_bands & BAND_GN || priv->adapter->config_bands & BAND_AN) && bss_desc->bcn_ht_cap) && !mwifiex_is_rsn_oui_present(bss_desc, CIPHER_SUITE_CCMP)) { if (mwifiex_is_rsn_oui_present (bss_desc, CIPHER_SUITE_TKIP)) { mwifiex_dbg(adapter, INFO, "info: Disable 11n if AES\t" "is not supported by AP\n"); bss_desc->disable_11n = true; } else { return -1; } } return 0; } else if (mwifiex_is_bss_adhoc_aes(priv, bss_desc)) { /* Ad-hoc AES enabled */ return 0; } else if (mwifiex_is_bss_dynamic_wep(priv, bss_desc)) { /* Dynamic WEP enabled */ return 0; } /* Security doesn't match */ dbg_security_flags(ERROR, "failed", priv, bss_desc); return -1; } /* Mode doesn't match */ return -1; } /* * This function creates a channel list for the driver to scan, based * on region/band information. * * This routine is used for any scan that is not provided with a * specific channel list to scan. */ static int mwifiex_scan_create_channel_list(struct mwifiex_private *priv, const struct mwifiex_user_scan_cfg *user_scan_in, struct mwifiex_chan_scan_param_set *scan_chan_list, u8 filtered_scan) { enum nl80211_band band; struct ieee80211_supported_band *sband; struct ieee80211_channel *ch; struct mwifiex_adapter *adapter = priv->adapter; int chan_idx = 0, i; for (band = 0; (band < NUM_NL80211_BANDS) ; band++) { if (!priv->wdev.wiphy->bands[band]) continue; sband = priv->wdev.wiphy->bands[band]; for (i = 0; (i < sband->n_channels) ; i++) { ch = &sband->channels[i]; if (ch->flags & IEEE80211_CHAN_DISABLED) continue; scan_chan_list[chan_idx].radio_type = band; if (user_scan_in && user_scan_in->chan_list[0].scan_time) scan_chan_list[chan_idx].max_scan_time = cpu_to_le16((u16) user_scan_in-> chan_list[0].scan_time); else if ((ch->flags & IEEE80211_CHAN_NO_IR) || (ch->flags & IEEE80211_CHAN_RADAR)) scan_chan_list[chan_idx].max_scan_time = cpu_to_le16(adapter->passive_scan_time); else scan_chan_list[chan_idx].max_scan_time = cpu_to_le16(adapter->active_scan_time); if (ch->flags & IEEE80211_CHAN_NO_IR) scan_chan_list[chan_idx].chan_scan_mode_bitmap |= (MWIFIEX_PASSIVE_SCAN | MWIFIEX_HIDDEN_SSID_REPORT); else scan_chan_list[chan_idx].chan_scan_mode_bitmap &= ~MWIFIEX_PASSIVE_SCAN; scan_chan_list[chan_idx].chan_number = (u32) ch->hw_value; scan_chan_list[chan_idx].chan_scan_mode_bitmap |= MWIFIEX_DISABLE_CHAN_FILT; if (filtered_scan && !((ch->flags & IEEE80211_CHAN_NO_IR) || (ch->flags & IEEE80211_CHAN_RADAR))) scan_chan_list[chan_idx].max_scan_time = cpu_to_le16(adapter->specific_scan_time); chan_idx++; } } return chan_idx; } /* This function creates a channel list tlv for bgscan config, based * on region/band information. */ static int mwifiex_bgscan_create_channel_list(struct mwifiex_private *priv, const struct mwifiex_bg_scan_cfg *bgscan_cfg_in, struct mwifiex_chan_scan_param_set *scan_chan_list) { enum nl80211_band band; struct ieee80211_supported_band *sband; struct ieee80211_channel *ch; struct mwifiex_adapter *adapter = priv->adapter; int chan_idx = 0, i; for (band = 0; (band < NUM_NL80211_BANDS); band++) { if (!priv->wdev.wiphy->bands[band]) continue; sband = priv->wdev.wiphy->bands[band]; for (i = 0; (i < sband->n_channels) ; i++) { ch = &sband->channels[i]; if (ch->flags & IEEE80211_CHAN_DISABLED) continue; scan_chan_list[chan_idx].radio_type = band; if (bgscan_cfg_in->chan_list[0].scan_time) scan_chan_list[chan_idx].max_scan_time = cpu_to_le16((u16)bgscan_cfg_in-> chan_list[0].scan_time); else if (ch->flags & IEEE80211_CHAN_NO_IR) scan_chan_list[chan_idx].max_scan_time = cpu_to_le16(adapter->passive_scan_time); else scan_chan_list[chan_idx].max_scan_time = cpu_to_le16(adapter-> specific_scan_time); if (ch->flags & IEEE80211_CHAN_NO_IR) scan_chan_list[chan_idx].chan_scan_mode_bitmap |= MWIFIEX_PASSIVE_SCAN; else scan_chan_list[chan_idx].chan_scan_mode_bitmap &= ~MWIFIEX_PASSIVE_SCAN; scan_chan_list[chan_idx].chan_number = (u32)ch->hw_value; chan_idx++; } } return chan_idx; } /* This function appends rate TLV to scan config command. */ static int mwifiex_append_rate_tlv(struct mwifiex_private *priv, struct mwifiex_scan_cmd_config *scan_cfg_out, u8 radio) { struct mwifiex_ie_types_rates_param_set *rates_tlv; u8 rates[MWIFIEX_SUPPORTED_RATES], *tlv_pos; u32 rates_size; memset(rates, 0, sizeof(rates)); tlv_pos = (u8 *)scan_cfg_out->tlv_buf + scan_cfg_out->tlv_buf_len; if (priv->scan_request) rates_size = mwifiex_get_rates_from_cfg80211(priv, rates, radio); else rates_size = mwifiex_get_supported_rates(priv, rates); mwifiex_dbg(priv->adapter, CMD, "info: SCAN_CMD: Rates size = %d\n", rates_size); rates_tlv = (struct mwifiex_ie_types_rates_param_set *)tlv_pos; rates_tlv->header.type = cpu_to_le16(WLAN_EID_SUPP_RATES); rates_tlv->header.len = cpu_to_le16((u16) rates_size); memcpy(rates_tlv->rates, rates, rates_size); scan_cfg_out->tlv_buf_len += sizeof(rates_tlv->header) + rates_size; return rates_size; } /* * This function constructs and sends multiple scan config commands to * the firmware. * * Previous routines in the code flow have created a scan command configuration * with any requested TLVs. This function splits the channel TLV into maximum * channels supported per scan lists and sends the portion of the channel TLV, * along with the other TLVs, to the firmware. */ static int mwifiex_scan_channel_list(struct mwifiex_private *priv, u32 max_chan_per_scan, u8 filtered_scan, struct mwifiex_scan_cmd_config *scan_cfg_out, struct mwifiex_ie_types_chan_list_param_set *chan_tlv_out, struct mwifiex_chan_scan_param_set *scan_chan_list) { struct mwifiex_adapter *adapter = priv->adapter; int ret = 0; struct mwifiex_chan_scan_param_set *tmp_chan_list; struct mwifiex_chan_scan_param_set *start_chan; u32 tlv_idx, rates_size, cmd_no; u32 total_scan_time; u32 done_early; u8 radio_type; if (!scan_cfg_out || !chan_tlv_out || !scan_chan_list) { mwifiex_dbg(priv->adapter, ERROR, "info: Scan: Null detect: %p, %p, %p\n", scan_cfg_out, chan_tlv_out, scan_chan_list); return -1; } /* Check csa channel expiry before preparing scan list */ mwifiex_11h_get_csa_closed_channel(priv); chan_tlv_out->header.type = cpu_to_le16(TLV_TYPE_CHANLIST); /* Set the temp channel struct pointer to the start of the desired list */ tmp_chan_list = scan_chan_list; /* Loop through the desired channel list, sending a new firmware scan commands for each max_chan_per_scan channels (or for 1,6,11 individually if configured accordingly) */ while (tmp_chan_list->chan_number) { tlv_idx = 0; total_scan_time = 0; radio_type = 0; chan_tlv_out->header.len = 0; start_chan = tmp_chan_list; done_early = false; /* * Construct the Channel TLV for the scan command. Continue to * insert channel TLVs until: * - the tlv_idx hits the maximum configured per scan command * - the next channel to insert is 0 (end of desired channel * list) * - done_early is set (controlling individual scanning of * 1,6,11) */ while (tlv_idx < max_chan_per_scan && tmp_chan_list->chan_number && !done_early) { if (tmp_chan_list->chan_number == priv->csa_chan) { tmp_chan_list++; continue; } radio_type = tmp_chan_list->radio_type; mwifiex_dbg(priv->adapter, INFO, "info: Scan: Chan(%3d), Radio(%d),\t" "Mode(%d, %d), Dur(%d)\n", tmp_chan_list->chan_number, tmp_chan_list->radio_type, tmp_chan_list->chan_scan_mode_bitmap & MWIFIEX_PASSIVE_SCAN, (tmp_chan_list->chan_scan_mode_bitmap & MWIFIEX_DISABLE_CHAN_FILT) >> 1, le16_to_cpu(tmp_chan_list->max_scan_time)); /* Copy the current channel TLV to the command being prepared */ memcpy(chan_tlv_out->chan_scan_param + tlv_idx, tmp_chan_list, sizeof(chan_tlv_out->chan_scan_param)); /* Increment the TLV header length by the size appended */ le16_unaligned_add_cpu(&chan_tlv_out->header.len, sizeof( chan_tlv_out->chan_scan_param)); /* * The tlv buffer length is set to the number of bytes * of the between the channel tlv pointer and the start * of the tlv buffer. This compensates for any TLVs * that were appended before the channel list. */ scan_cfg_out->tlv_buf_len = (u32) ((u8 *) chan_tlv_out - scan_cfg_out->tlv_buf); /* Add the size of the channel tlv header and the data length */ scan_cfg_out->tlv_buf_len += (sizeof(chan_tlv_out->header) + le16_to_cpu(chan_tlv_out->header.len)); /* Increment the index to the channel tlv we are constructing */ tlv_idx++; /* Count the total scan time per command */ total_scan_time += le16_to_cpu(tmp_chan_list->max_scan_time); done_early = false; /* Stop the loop if the *current* channel is in the 1,6,11 set and we are not filtering on a BSSID or SSID. */ if (!filtered_scan && (tmp_chan_list->chan_number == 1 || tmp_chan_list->chan_number == 6 || tmp_chan_list->chan_number == 11)) done_early = true; /* Increment the tmp pointer to the next channel to be scanned */ tmp_chan_list++; /* Stop the loop if the *next* channel is in the 1,6,11 set. This will cause it to be the only channel scanned on the next interation */ if (!filtered_scan && (tmp_chan_list->chan_number == 1 || tmp_chan_list->chan_number == 6 || tmp_chan_list->chan_number == 11)) done_early = true; } /* The total scan time should be less than scan command timeout value */ if (total_scan_time > MWIFIEX_MAX_TOTAL_SCAN_TIME) { mwifiex_dbg(priv->adapter, ERROR, "total scan time %dms\t" "is over limit (%dms), scan skipped\n", total_scan_time, MWIFIEX_MAX_TOTAL_SCAN_TIME); ret = -1; break; } rates_size = mwifiex_append_rate_tlv(priv, scan_cfg_out, radio_type); priv->adapter->scan_channels = start_chan; /* Send the scan command to the firmware with the specified cfg */ if (priv->adapter->ext_scan) cmd_no = HostCmd_CMD_802_11_SCAN_EXT; else cmd_no = HostCmd_CMD_802_11_SCAN; ret = mwifiex_send_cmd(priv, cmd_no, HostCmd_ACT_GEN_SET, 0, scan_cfg_out, false); /* rate IE is updated per scan command but same starting * pointer is used each time so that rate IE from earlier * scan_cfg_out->buf is overwritten with new one. */ scan_cfg_out->tlv_buf_len -= sizeof(struct mwifiex_ie_types_header) + rates_size; if (ret) { mwifiex_cancel_pending_scan_cmd(adapter); break; } } if (ret) return -1; return 0; } /* * This function constructs a scan command configuration structure to use * in scan commands. * * Application layer or other functions can invoke network scanning * with a scan configuration supplied in a user scan configuration structure. * This structure is used as the basis of one or many scan command configuration * commands that are sent to the command processing module and eventually to the * firmware. * * This function creates a scan command configuration structure based on the * following user supplied parameters (if present): * - SSID filter * - BSSID filter * - Number of Probes to be sent * - Channel list * * If the SSID or BSSID filter is not present, the filter is disabled/cleared. * If the number of probes is not set, adapter default setting is used. */ static void mwifiex_config_scan(struct mwifiex_private *priv, const struct mwifiex_user_scan_cfg *user_scan_in, struct mwifiex_scan_cmd_config *scan_cfg_out, struct mwifiex_ie_types_chan_list_param_set **chan_list_out, struct mwifiex_chan_scan_param_set *scan_chan_list, u8 *max_chan_per_scan, u8 *filtered_scan, u8 *scan_current_only) { struct mwifiex_adapter *adapter = priv->adapter; struct mwifiex_ie_types_num_probes *num_probes_tlv; struct mwifiex_ie_types_scan_chan_gap *chan_gap_tlv; struct mwifiex_ie_types_random_mac *random_mac_tlv; struct mwifiex_ie_types_wildcard_ssid_params *wildcard_ssid_tlv; struct mwifiex_ie_types_bssid_list *bssid_tlv; u8 *tlv_pos; u32 num_probes; u32 ssid_len; u32 chan_idx; u32 scan_type; u16 scan_dur; u8 channel; u8 radio_type; int i; u8 ssid_filter; struct mwifiex_ie_types_htcap *ht_cap; struct mwifiex_ie_types_bss_mode *bss_mode; const u8 zero_mac[6] = {0, 0, 0, 0, 0, 0}; /* The tlv_buf_len is calculated for each scan command. The TLVs added in this routine will be preserved since the routine that sends the command will append channelTLVs at *chan_list_out. The difference between the *chan_list_out and the tlv_buf start will be used to calculate the size of anything we add in this routine. */ scan_cfg_out->tlv_buf_len = 0; /* Running tlv pointer. Assigned to chan_list_out at end of function so later routines know where channels can be added to the command buf */ tlv_pos = scan_cfg_out->tlv_buf; /* Initialize the scan as un-filtered; the flag is later set to TRUE below if a SSID or BSSID filter is sent in the command */ *filtered_scan = false; /* Initialize the scan as not being only on the current channel. If the channel list is customized, only contains one channel, and is the active channel, this is set true and data flow is not halted. */ *scan_current_only = false; if (user_scan_in) { u8 tmpaddr[ETH_ALEN]; /* Default the ssid_filter flag to TRUE, set false under certain wildcard conditions and qualified by the existence of an SSID list before marking the scan as filtered */ ssid_filter = true; /* Set the BSS type scan filter, use Adapter setting if unset */ scan_cfg_out->bss_mode = (u8)(user_scan_in->bss_mode ?: adapter->scan_mode); /* Set the number of probes to send, use Adapter setting if unset */ num_probes = user_scan_in->num_probes ?: adapter->scan_probes; /* * Set the BSSID filter to the incoming configuration, * if non-zero. If not set, it will remain disabled * (all zeros). */ memcpy(scan_cfg_out->specific_bssid, user_scan_in->specific_bssid, sizeof(scan_cfg_out->specific_bssid)); memcpy(tmpaddr, scan_cfg_out->specific_bssid, ETH_ALEN); if (adapter->ext_scan && !is_zero_ether_addr(tmpaddr)) { bssid_tlv = (struct mwifiex_ie_types_bssid_list *)tlv_pos; bssid_tlv->header.type = cpu_to_le16(TLV_TYPE_BSSID); bssid_tlv->header.len = cpu_to_le16(ETH_ALEN); memcpy(bssid_tlv->bssid, user_scan_in->specific_bssid, ETH_ALEN); tlv_pos += sizeof(struct mwifiex_ie_types_bssid_list); } for (i = 0; i < user_scan_in->num_ssids; i++) { ssid_len = user_scan_in->ssid_list[i].ssid_len; wildcard_ssid_tlv = (struct mwifiex_ie_types_wildcard_ssid_params *) tlv_pos; wildcard_ssid_tlv->header.type = cpu_to_le16(TLV_TYPE_WILDCARDSSID); wildcard_ssid_tlv->header.len = cpu_to_le16( (u16) (ssid_len + sizeof(wildcard_ssid_tlv-> max_ssid_length))); /* * max_ssid_length = 0 tells firmware to perform * specific scan for the SSID filled, whereas * max_ssid_length = IEEE80211_MAX_SSID_LEN is for * wildcard scan. */ if (ssid_len) wildcard_ssid_tlv->max_ssid_length = 0; else wildcard_ssid_tlv->max_ssid_length = IEEE80211_MAX_SSID_LEN; if (!memcmp(user_scan_in->ssid_list[i].ssid, "DIRECT-", 7)) wildcard_ssid_tlv->max_ssid_length = 0xfe; memcpy(wildcard_ssid_tlv->ssid, user_scan_in->ssid_list[i].ssid, ssid_len); tlv_pos += (sizeof(wildcard_ssid_tlv->header) + le16_to_cpu(wildcard_ssid_tlv->header.len)); mwifiex_dbg(adapter, INFO, "info: scan: ssid[%d]: %s, %d\n", i, wildcard_ssid_tlv->ssid, wildcard_ssid_tlv->max_ssid_length); /* Empty wildcard ssid with a maxlen will match many or potentially all SSIDs (maxlen == 32), therefore do not treat the scan as filtered. */ if (!ssid_len && wildcard_ssid_tlv->max_ssid_length) ssid_filter = false; } /* * The default number of channels sent in the command is low to * ensure the response buffer from the firmware does not * truncate scan results. That is not an issue with an SSID * or BSSID filter applied to the scan results in the firmware. */ memcpy(tmpaddr, scan_cfg_out->specific_bssid, ETH_ALEN); if ((i && ssid_filter) || !is_zero_ether_addr(tmpaddr)) *filtered_scan = true; if (user_scan_in->scan_chan_gap) { mwifiex_dbg(adapter, INFO, "info: scan: channel gap = %d\n", user_scan_in->scan_chan_gap); *max_chan_per_scan = MWIFIEX_MAX_CHANNELS_PER_SPECIFIC_SCAN; chan_gap_tlv = (void *)tlv_pos; chan_gap_tlv->header.type = cpu_to_le16(TLV_TYPE_SCAN_CHANNEL_GAP); chan_gap_tlv->header.len = cpu_to_le16(sizeof(chan_gap_tlv->chan_gap)); chan_gap_tlv->chan_gap = cpu_to_le16((user_scan_in->scan_chan_gap)); tlv_pos += sizeof(struct mwifiex_ie_types_scan_chan_gap); } if (!ether_addr_equal(user_scan_in->random_mac, zero_mac)) { random_mac_tlv = (void *)tlv_pos; random_mac_tlv->header.type = cpu_to_le16(TLV_TYPE_RANDOM_MAC); random_mac_tlv->header.len = cpu_to_le16(sizeof(random_mac_tlv->mac)); ether_addr_copy(random_mac_tlv->mac, user_scan_in->random_mac); tlv_pos += sizeof(struct mwifiex_ie_types_random_mac); } } else { scan_cfg_out->bss_mode = (u8) adapter->scan_mode; num_probes = adapter->scan_probes; } /* * If a specific BSSID or SSID is used, the number of channels in the * scan command will be increased to the absolute maximum. */ if (*filtered_scan) { *max_chan_per_scan = MWIFIEX_MAX_CHANNELS_PER_SPECIFIC_SCAN; } else { if (!priv->media_connected) *max_chan_per_scan = MWIFIEX_DEF_CHANNELS_PER_SCAN_CMD; else *max_chan_per_scan = MWIFIEX_DEF_CHANNELS_PER_SCAN_CMD / 2; } if (adapter->ext_scan) { bss_mode = (struct mwifiex_ie_types_bss_mode *)tlv_pos; bss_mode->header.type = cpu_to_le16(TLV_TYPE_BSS_MODE); bss_mode->header.len = cpu_to_le16(sizeof(bss_mode->bss_mode)); bss_mode->bss_mode = scan_cfg_out->bss_mode; tlv_pos += sizeof(bss_mode->header) + le16_to_cpu(bss_mode->header.len); } /* If the input config or adapter has the number of Probes set, add tlv */ if (num_probes) { mwifiex_dbg(adapter, INFO, "info: scan: num_probes = %d\n", num_probes); num_probes_tlv = (struct mwifiex_ie_types_num_probes *) tlv_pos; num_probes_tlv->header.type = cpu_to_le16(TLV_TYPE_NUMPROBES); num_probes_tlv->header.len = cpu_to_le16(sizeof(num_probes_tlv->num_probes)); num_probes_tlv->num_probes = cpu_to_le16((u16) num_probes); tlv_pos += sizeof(num_probes_tlv->header) + le16_to_cpu(num_probes_tlv->header.len); } if (ISSUPP_11NENABLED(priv->adapter->fw_cap_info) && (priv->adapter->config_bands & BAND_GN || priv->adapter->config_bands & BAND_AN)) { ht_cap = (struct mwifiex_ie_types_htcap *) tlv_pos; memset(ht_cap, 0, sizeof(struct mwifiex_ie_types_htcap)); ht_cap->header.type = cpu_to_le16(WLAN_EID_HT_CAPABILITY); ht_cap->header.len = cpu_to_le16(sizeof(struct ieee80211_ht_cap)); radio_type = mwifiex_band_to_radio_type(priv->adapter->config_bands); mwifiex_fill_cap_info(priv, radio_type, &ht_cap->ht_cap); tlv_pos += sizeof(struct mwifiex_ie_types_htcap); } /* Append vendor specific IE TLV */ mwifiex_cmd_append_vsie_tlv(priv, MWIFIEX_VSIE_MASK_SCAN, &tlv_pos); /* * Set the output for the channel TLV to the address in the tlv buffer * past any TLVs that were added in this function (SSID, num_probes). * Channel TLVs will be added past this for each scan command, * preserving the TLVs that were previously added. */ *chan_list_out = (struct mwifiex_ie_types_chan_list_param_set *) tlv_pos; if (user_scan_in && user_scan_in->chan_list[0].chan_number) { mwifiex_dbg(adapter, INFO, "info: Scan: Using supplied channel list\n"); for (chan_idx = 0; chan_idx < MWIFIEX_USER_SCAN_CHAN_MAX && user_scan_in->chan_list[chan_idx].chan_number; chan_idx++) { channel = user_scan_in->chan_list[chan_idx].chan_number; scan_chan_list[chan_idx].chan_number = channel; radio_type = user_scan_in->chan_list[chan_idx].radio_type; scan_chan_list[chan_idx].radio_type = radio_type; scan_type = user_scan_in->chan_list[chan_idx].scan_type; if (scan_type == MWIFIEX_SCAN_TYPE_PASSIVE) scan_chan_list[chan_idx].chan_scan_mode_bitmap |= (MWIFIEX_PASSIVE_SCAN | MWIFIEX_HIDDEN_SSID_REPORT); else scan_chan_list[chan_idx].chan_scan_mode_bitmap &= ~MWIFIEX_PASSIVE_SCAN; scan_chan_list[chan_idx].chan_scan_mode_bitmap |= MWIFIEX_DISABLE_CHAN_FILT; if (user_scan_in->chan_list[chan_idx].scan_time) { scan_dur = (u16) user_scan_in-> chan_list[chan_idx].scan_time; } else { if (scan_type == MWIFIEX_SCAN_TYPE_PASSIVE) scan_dur = adapter->passive_scan_time; else if (*filtered_scan) scan_dur = adapter->specific_scan_time; else scan_dur = adapter->active_scan_time; } scan_chan_list[chan_idx].min_scan_time = cpu_to_le16(scan_dur); scan_chan_list[chan_idx].max_scan_time = cpu_to_le16(scan_dur); } /* Check if we are only scanning the current channel */ if ((chan_idx == 1) && (user_scan_in->chan_list[0].chan_number == priv->curr_bss_params.bss_descriptor.channel)) { *scan_current_only = true; mwifiex_dbg(adapter, INFO, "info: Scan: Scanning current channel only\n"); } } else { mwifiex_dbg(adapter, INFO, "info: Scan: Creating full region channel list\n"); mwifiex_scan_create_channel_list(priv, user_scan_in, scan_chan_list, *filtered_scan); } } /* * This function inspects the scan response buffer for pointers to * expected TLVs. * * TLVs can be included at the end of the scan response BSS information. * * Data in the buffer is parsed pointers to TLVs that can potentially * be passed back in the response. */ static void mwifiex_ret_802_11_scan_get_tlv_ptrs(struct mwifiex_adapter *adapter, struct mwifiex_ie_types_data *tlv, u32 tlv_buf_size, u32 req_tlv_type, struct mwifiex_ie_types_data **tlv_data) { struct mwifiex_ie_types_data *current_tlv; u32 tlv_buf_left; u32 tlv_type; u32 tlv_len; current_tlv = tlv; tlv_buf_left = tlv_buf_size; *tlv_data = NULL; mwifiex_dbg(adapter, INFO, "info: SCAN_RESP: tlv_buf_size = %d\n", tlv_buf_size); while (tlv_buf_left >= sizeof(struct mwifiex_ie_types_header)) { tlv_type = le16_to_cpu(current_tlv->header.type); tlv_len = le16_to_cpu(current_tlv->header.len); if (sizeof(tlv->header) + tlv_len > tlv_buf_left) { mwifiex_dbg(adapter, ERROR, "SCAN_RESP: TLV buffer corrupt\n"); break; } if (req_tlv_type == tlv_type) { switch (tlv_type) { case TLV_TYPE_TSFTIMESTAMP: mwifiex_dbg(adapter, INFO, "info: SCAN_RESP: TSF\t" "timestamp TLV, len = %d\n", tlv_len); *tlv_data = current_tlv; break; case TLV_TYPE_CHANNELBANDLIST: mwifiex_dbg(adapter, INFO, "info: SCAN_RESP: channel\t" "band list TLV, len = %d\n", tlv_len); *tlv_data = current_tlv; break; default: mwifiex_dbg(adapter, ERROR, "SCAN_RESP: unhandled TLV = %d\n", tlv_type); /* Give up, this seems corrupted */ return; } } if (*tlv_data) break; tlv_buf_left -= (sizeof(tlv->header) + tlv_len); current_tlv = (struct mwifiex_ie_types_data *) (current_tlv->data + tlv_len); } /* while */ } /* * This function parses provided beacon buffer and updates * respective fields in bss descriptor structure. */ int mwifiex_update_bss_desc_with_ie(struct mwifiex_adapter *adapter, struct mwifiex_bssdescriptor *bss_entry) { int ret = 0; u8 element_id; struct ieee_types_fh_param_set *fh_param_set; struct ieee_types_ds_param_set *ds_param_set; struct ieee_types_cf_param_set *cf_param_set; struct ieee_types_ibss_param_set *ibss_param_set; u8 *current_ptr; u8 *rate; u8 element_len; u16 total_ie_len; u8 bytes_to_copy; u8 rate_size; u8 found_data_rate_ie; u32 bytes_left; struct ieee_types_vendor_specific *vendor_ie; const u8 wpa_oui[4] = { 0x00, 0x50, 0xf2, 0x01 }; const u8 wmm_oui[4] = { 0x00, 0x50, 0xf2, 0x02 }; found_data_rate_ie = false; rate_size = 0; current_ptr = bss_entry->beacon_buf; bytes_left = bss_entry->beacon_buf_size; /* Process variable IE */ while (bytes_left >= 2) { element_id = *current_ptr; element_len = *(current_ptr + 1); total_ie_len = element_len + sizeof(struct ieee_types_header); if (bytes_left < total_ie_len) { mwifiex_dbg(adapter, ERROR, "err: InterpretIE: in processing\t" "IE, bytes left < IE length\n"); return -EINVAL; } switch (element_id) { case WLAN_EID_SSID: if (element_len > IEEE80211_MAX_SSID_LEN) return -EINVAL; bss_entry->ssid.ssid_len = element_len; memcpy(bss_entry->ssid.ssid, (current_ptr + 2), element_len); mwifiex_dbg(adapter, INFO, "info: InterpretIE: ssid: %-32s\n", bss_entry->ssid.ssid); break; case WLAN_EID_SUPP_RATES: if (element_len > MWIFIEX_SUPPORTED_RATES) return -EINVAL; memcpy(bss_entry->data_rates, current_ptr + 2, element_len); memcpy(bss_entry->supported_rates, current_ptr + 2, element_len); rate_size = element_len; found_data_rate_ie = true; break; case WLAN_EID_FH_PARAMS: if (total_ie_len < sizeof(*fh_param_set)) return -EINVAL; fh_param_set = (struct ieee_types_fh_param_set *) current_ptr; memcpy(&bss_entry->phy_param_set.fh_param_set, fh_param_set, sizeof(struct ieee_types_fh_param_set)); break; case WLAN_EID_DS_PARAMS: if (total_ie_len < sizeof(*ds_param_set)) return -EINVAL; ds_param_set = (struct ieee_types_ds_param_set *) current_ptr; bss_entry->channel = ds_param_set->current_chan; memcpy(&bss_entry->phy_param_set.ds_param_set, ds_param_set, sizeof(struct ieee_types_ds_param_set)); break; case WLAN_EID_CF_PARAMS: if (total_ie_len < sizeof(*cf_param_set)) return -EINVAL; cf_param_set = (struct ieee_types_cf_param_set *) current_ptr; memcpy(&bss_entry->ss_param_set.cf_param_set, cf_param_set, sizeof(struct ieee_types_cf_param_set)); break; case WLAN_EID_IBSS_PARAMS: if (total_ie_len < sizeof(*ibss_param_set)) return -EINVAL; ibss_param_set = (struct ieee_types_ibss_param_set *) current_ptr; memcpy(&bss_entry->ss_param_set.ibss_param_set, ibss_param_set, sizeof(struct ieee_types_ibss_param_set)); break; case WLAN_EID_ERP_INFO: if (!element_len) return -EINVAL; bss_entry->erp_flags = *(current_ptr + 2); break; case WLAN_EID_PWR_CONSTRAINT: if (!element_len) return -EINVAL; bss_entry->local_constraint = *(current_ptr + 2); bss_entry->sensed_11h = true; break; case WLAN_EID_CHANNEL_SWITCH: bss_entry->chan_sw_ie_present = true; /* fall through */ case WLAN_EID_PWR_CAPABILITY: case WLAN_EID_TPC_REPORT: case WLAN_EID_QUIET: bss_entry->sensed_11h = true; break; case WLAN_EID_EXT_SUPP_RATES: /* * Only process extended supported rate * if data rate is already found. * Data rate IE should come before * extended supported rate IE */ if (found_data_rate_ie) { if ((element_len + rate_size) > MWIFIEX_SUPPORTED_RATES) bytes_to_copy = (MWIFIEX_SUPPORTED_RATES - rate_size); else bytes_to_copy = element_len; rate = (u8 *) bss_entry->data_rates; rate += rate_size; memcpy(rate, current_ptr + 2, bytes_to_copy); rate = (u8 *) bss_entry->supported_rates; rate += rate_size; memcpy(rate, current_ptr + 2, bytes_to_copy); } break; case WLAN_EID_VENDOR_SPECIFIC: vendor_ie = (struct ieee_types_vendor_specific *) current_ptr; /* 802.11 requires at least 3-byte OUI. */ if (element_len < sizeof(vendor_ie->vend_hdr.oui.oui)) return -EINVAL; /* Not long enough for a match? Skip it. */ if (element_len < sizeof(wpa_oui)) break; if (!memcmp(&vendor_ie->vend_hdr.oui, wpa_oui, sizeof(wpa_oui))) { bss_entry->bcn_wpa_ie = (struct ieee_types_vendor_specific *) current_ptr; bss_entry->wpa_offset = (u16) (current_ptr - bss_entry->beacon_buf); } else if (!memcmp(&vendor_ie->vend_hdr.oui, wmm_oui, sizeof(wmm_oui))) { if (total_ie_len == sizeof(struct ieee_types_wmm_parameter) || total_ie_len == sizeof(struct ieee_types_wmm_info)) /* * Only accept and copy the WMM IE if * it matches the size expected for the * WMM Info IE or the WMM Parameter IE. */ memcpy((u8 *) &bss_entry->wmm_ie, current_ptr, total_ie_len); } break; case WLAN_EID_RSN: bss_entry->bcn_rsn_ie = (struct ieee_types_generic *) current_ptr; bss_entry->rsn_offset = (u16) (current_ptr - bss_entry->beacon_buf); break; case WLAN_EID_BSS_AC_ACCESS_DELAY: bss_entry->bcn_wapi_ie = (struct ieee_types_generic *) current_ptr; bss_entry->wapi_offset = (u16) (current_ptr - bss_entry->beacon_buf); break; case WLAN_EID_HT_CAPABILITY: bss_entry->bcn_ht_cap = (struct ieee80211_ht_cap *) (current_ptr + sizeof(struct ieee_types_header)); bss_entry->ht_cap_offset = (u16) (current_ptr + sizeof(struct ieee_types_header) - bss_entry->beacon_buf); break; case WLAN_EID_HT_OPERATION: bss_entry->bcn_ht_oper = (struct ieee80211_ht_operation *)(current_ptr + sizeof(struct ieee_types_header)); bss_entry->ht_info_offset = (u16) (current_ptr + sizeof(struct ieee_types_header) - bss_entry->beacon_buf); break; case WLAN_EID_VHT_CAPABILITY: bss_entry->disable_11ac = false; bss_entry->bcn_vht_cap = (void *)(current_ptr + sizeof(struct ieee_types_header)); bss_entry->vht_cap_offset = (u16)((u8 *)bss_entry->bcn_vht_cap - bss_entry->beacon_buf); break; case WLAN_EID_VHT_OPERATION: bss_entry->bcn_vht_oper = (void *)(current_ptr + sizeof(struct ieee_types_header)); bss_entry->vht_info_offset = (u16)((u8 *)bss_entry->bcn_vht_oper - bss_entry->beacon_buf); break; case WLAN_EID_BSS_COEX_2040: bss_entry->bcn_bss_co_2040 = current_ptr; bss_entry->bss_co_2040_offset = (u16) (current_ptr - bss_entry->beacon_buf); break; case WLAN_EID_EXT_CAPABILITY: bss_entry->bcn_ext_cap = current_ptr; bss_entry->ext_cap_offset = (u16) (current_ptr - bss_entry->beacon_buf); break; case WLAN_EID_OPMODE_NOTIF: bss_entry->oper_mode = (void *)current_ptr; bss_entry->oper_mode_offset = (u16)((u8 *)bss_entry->oper_mode - bss_entry->beacon_buf); break; default: break; } current_ptr += total_ie_len; bytes_left -= total_ie_len; } /* while (bytes_left > 2) */ return ret; } /* * This function converts radio type scan parameter to a band configuration * to be used in join command. */ static u8 mwifiex_radio_type_to_band(u8 radio_type) { switch (radio_type) { case HostCmd_SCAN_RADIO_TYPE_A: return BAND_A; case HostCmd_SCAN_RADIO_TYPE_BG: default: return BAND_G; } } /* * This is an internal function used to start a scan based on an input * configuration. * * This uses the input user scan configuration information when provided in * order to send the appropriate scan commands to firmware to populate or * update the internal driver scan table. */ int mwifiex_scan_networks(struct mwifiex_private *priv, const struct mwifiex_user_scan_cfg *user_scan_in) { int ret; struct mwifiex_adapter *adapter = priv->adapter; struct cmd_ctrl_node *cmd_node; union mwifiex_scan_cmd_config_tlv *scan_cfg_out; struct mwifiex_ie_types_chan_list_param_set *chan_list_out; struct mwifiex_chan_scan_param_set *scan_chan_list; u8 filtered_scan; u8 scan_current_chan_only; u8 max_chan_per_scan; if (adapter->scan_processing) { mwifiex_dbg(adapter, WARN, "cmd: Scan already in process...\n"); return -EBUSY; } if (priv->scan_block) { mwifiex_dbg(adapter, WARN, "cmd: Scan is blocked during association...\n"); return -EBUSY; } if (test_bit(MWIFIEX_SURPRISE_REMOVED, &adapter->work_flags) || test_bit(MWIFIEX_IS_CMD_TIMEDOUT, &adapter->work_flags)) { mwifiex_dbg(adapter, ERROR, "Ignore scan. Card removed or firmware in bad state\n"); return -EFAULT; } spin_lock_bh(&adapter->mwifiex_cmd_lock); adapter->scan_processing = true; spin_unlock_bh(&adapter->mwifiex_cmd_lock); scan_cfg_out = kzalloc(sizeof(union mwifiex_scan_cmd_config_tlv), GFP_KERNEL); if (!scan_cfg_out) { ret = -ENOMEM; goto done; } scan_chan_list = kcalloc(MWIFIEX_USER_SCAN_CHAN_MAX, sizeof(struct mwifiex_chan_scan_param_set), GFP_KERNEL); if (!scan_chan_list) { kfree(scan_cfg_out); ret = -ENOMEM; goto done; } mwifiex_config_scan(priv, user_scan_in, &scan_cfg_out->config, &chan_list_out, scan_chan_list, &max_chan_per_scan, &filtered_scan, &scan_current_chan_only); ret = mwifiex_scan_channel_list(priv, max_chan_per_scan, filtered_scan, &scan_cfg_out->config, chan_list_out, scan_chan_list); /* Get scan command from scan_pending_q and put to cmd_pending_q */ if (!ret) { spin_lock_bh(&adapter->scan_pending_q_lock); if (!list_empty(&adapter->scan_pending_q)) { cmd_node = list_first_entry(&adapter->scan_pending_q, struct cmd_ctrl_node, list); list_del(&cmd_node->list); spin_unlock_bh(&adapter->scan_pending_q_lock); mwifiex_insert_cmd_to_pending_q(adapter, cmd_node); queue_work(adapter->workqueue, &adapter->main_work); /* Perform internal scan synchronously */ if (!priv->scan_request) { mwifiex_dbg(adapter, INFO, "wait internal scan\n"); mwifiex_wait_queue_complete(adapter, cmd_node); } } else { spin_unlock_bh(&adapter->scan_pending_q_lock); } } kfree(scan_cfg_out); kfree(scan_chan_list); done: if (ret) { spin_lock_bh(&adapter->mwifiex_cmd_lock); adapter->scan_processing = false; spin_unlock_bh(&adapter->mwifiex_cmd_lock); } return ret; } /* * This function prepares a scan command to be sent to the firmware. * * This uses the scan command configuration sent to the command processing * module in command preparation stage to configure a scan command structure * to send to firmware. * * The fixed fields specifying the BSS type and BSSID filters as well as a * variable number/length of TLVs are sent in the command to firmware. * * Preparation also includes - * - Setting command ID, and proper size * - Ensuring correct endian-ness */ int mwifiex_cmd_802_11_scan(struct host_cmd_ds_command *cmd, struct mwifiex_scan_cmd_config *scan_cfg) { struct host_cmd_ds_802_11_scan *scan_cmd = &cmd->params.scan; /* Set fixed field variables in scan command */ scan_cmd->bss_mode = scan_cfg->bss_mode; memcpy(scan_cmd->bssid, scan_cfg->specific_bssid, sizeof(scan_cmd->bssid)); memcpy(scan_cmd->tlv_buffer, scan_cfg->tlv_buf, scan_cfg->tlv_buf_len); cmd->command = cpu_to_le16(HostCmd_CMD_802_11_SCAN); /* Size is equal to the sizeof(fixed portions) + the TLV len + header */ cmd->size = cpu_to_le16((u16) (sizeof(scan_cmd->bss_mode) + sizeof(scan_cmd->bssid) + scan_cfg->tlv_buf_len + S_DS_GEN)); return 0; } /* * This function checks compatibility of requested network with current * driver settings. */ int mwifiex_check_network_compatibility(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc) { int ret = -1; if (!bss_desc) return -1; if ((mwifiex_get_cfp(priv, (u8) bss_desc->bss_band, (u16) bss_desc->channel, 0))) { switch (priv->bss_mode) { case NL80211_IFTYPE_STATION: case NL80211_IFTYPE_ADHOC: ret = mwifiex_is_network_compatible(priv, bss_desc, priv->bss_mode); if (ret) mwifiex_dbg(priv->adapter, ERROR, "Incompatible network settings\n"); break; default: ret = 0; } } return ret; } /* This function checks if SSID string contains all zeroes or length is zero */ static bool mwifiex_is_hidden_ssid(struct cfg80211_ssid *ssid) { int idx; for (idx = 0; idx < ssid->ssid_len; idx++) { if (ssid->ssid[idx]) return false; } return true; } /* This function checks if any hidden SSID found in passive scan channels * and save those channels for specific SSID active scan */ static int mwifiex_save_hidden_ssid_channels(struct mwifiex_private *priv, struct cfg80211_bss *bss) { struct mwifiex_bssdescriptor *bss_desc; int ret; int chid; /* Allocate and fill new bss descriptor */ bss_desc = kzalloc(sizeof(*bss_desc), GFP_KERNEL); if (!bss_desc) return -ENOMEM; ret = mwifiex_fill_new_bss_desc(priv, bss, bss_desc); if (ret) goto done; if (mwifiex_is_hidden_ssid(&bss_desc->ssid)) { mwifiex_dbg(priv->adapter, INFO, "found hidden SSID\n"); for (chid = 0 ; chid < MWIFIEX_USER_SCAN_CHAN_MAX; chid++) { if (priv->hidden_chan[chid].chan_number == bss->channel->hw_value) break; if (!priv->hidden_chan[chid].chan_number) { priv->hidden_chan[chid].chan_number = bss->channel->hw_value; priv->hidden_chan[chid].radio_type = bss->channel->band; priv->hidden_chan[chid].scan_type = MWIFIEX_SCAN_TYPE_ACTIVE; break; } } } done: /* beacon_ie buffer was allocated in function * mwifiex_fill_new_bss_desc(). Free it now. */ kfree(bss_desc->beacon_buf); kfree(bss_desc); return 0; } static int mwifiex_update_curr_bss_params(struct mwifiex_private *priv, struct cfg80211_bss *bss) { struct mwifiex_bssdescriptor *bss_desc; int ret; /* Allocate and fill new bss descriptor */ bss_desc = kzalloc(sizeof(struct mwifiex_bssdescriptor), GFP_KERNEL); if (!bss_desc) return -ENOMEM; ret = mwifiex_fill_new_bss_desc(priv, bss, bss_desc); if (ret) goto done; ret = mwifiex_check_network_compatibility(priv, bss_desc); if (ret) goto done; spin_lock_bh(&priv->curr_bcn_buf_lock); /* Make a copy of current BSSID descriptor */ memcpy(&priv->curr_bss_params.bss_descriptor, bss_desc, sizeof(priv->curr_bss_params.bss_descriptor)); /* The contents of beacon_ie will be copied to its own buffer * in mwifiex_save_curr_bcn() */ mwifiex_save_curr_bcn(priv); spin_unlock_bh(&priv->curr_bcn_buf_lock); done: /* beacon_ie buffer was allocated in function * mwifiex_fill_new_bss_desc(). Free it now. */ kfree(bss_desc->beacon_buf); kfree(bss_desc); return 0; } static int mwifiex_parse_single_response_buf(struct mwifiex_private *priv, u8 **bss_info, u32 *bytes_left, u64 fw_tsf, u8 *radio_type, bool ext_scan, s32 rssi_val) { struct mwifiex_adapter *adapter = priv->adapter; struct mwifiex_chan_freq_power *cfp; struct cfg80211_bss *bss; u8 bssid[ETH_ALEN]; s32 rssi; const u8 *ie_buf; size_t ie_len; u16 channel = 0; u16 beacon_size = 0; u32 curr_bcn_bytes; u32 freq; u16 beacon_period; u16 cap_info_bitmap; u8 *current_ptr; u64 timestamp; struct mwifiex_fixed_bcn_param *bcn_param; struct mwifiex_bss_priv *bss_priv; if (*bytes_left >= sizeof(beacon_size)) { /* Extract & convert beacon size from command buffer */ beacon_size = get_unaligned_le16((*bss_info)); *bytes_left -= sizeof(beacon_size); *bss_info += sizeof(beacon_size); } if (!beacon_size || beacon_size > *bytes_left) { *bss_info += *bytes_left; *bytes_left = 0; return -EFAULT; } /* Initialize the current working beacon pointer for this BSS * iteration */ current_ptr = *bss_info; /* Advance the return beacon pointer past the current beacon */ *bss_info += beacon_size; *bytes_left -= beacon_size; curr_bcn_bytes = beacon_size; /* First 5 fields are bssid, RSSI(for legacy scan only), * time stamp, beacon interval, and capability information */ if (curr_bcn_bytes < ETH_ALEN + sizeof(u8) + sizeof(struct mwifiex_fixed_bcn_param)) { mwifiex_dbg(adapter, ERROR, "InterpretIE: not enough bytes left\n"); return -EFAULT; } memcpy(bssid, current_ptr, ETH_ALEN); current_ptr += ETH_ALEN; curr_bcn_bytes -= ETH_ALEN; if (!ext_scan) { rssi = (s32) *current_ptr; rssi = (-rssi) * 100; /* Convert dBm to mBm */ current_ptr += sizeof(u8); curr_bcn_bytes -= sizeof(u8); mwifiex_dbg(adapter, INFO, "info: InterpretIE: RSSI=%d\n", rssi); } else { rssi = rssi_val; } bcn_param = (struct mwifiex_fixed_bcn_param *)current_ptr; current_ptr += sizeof(*bcn_param); curr_bcn_bytes -= sizeof(*bcn_param); timestamp = le64_to_cpu(bcn_param->timestamp); beacon_period = le16_to_cpu(bcn_param->beacon_period); cap_info_bitmap = le16_to_cpu(bcn_param->cap_info_bitmap); mwifiex_dbg(adapter, INFO, "info: InterpretIE: capabilities=0x%X\n", cap_info_bitmap); /* Rest of the current buffer are IE's */ ie_buf = current_ptr; ie_len = curr_bcn_bytes; mwifiex_dbg(adapter, INFO, "info: InterpretIE: IELength for this AP = %d\n", curr_bcn_bytes); while (curr_bcn_bytes >= sizeof(struct ieee_types_header)) { u8 element_id, element_len; element_id = *current_ptr; element_len = *(current_ptr + 1); if (curr_bcn_bytes < element_len + sizeof(struct ieee_types_header)) { mwifiex_dbg(adapter, ERROR, "%s: bytes left < IE length\n", __func__); return -EFAULT; } if (element_id == WLAN_EID_DS_PARAMS) { channel = *(current_ptr + sizeof(struct ieee_types_header)); break; } current_ptr += element_len + sizeof(struct ieee_types_header); curr_bcn_bytes -= element_len + sizeof(struct ieee_types_header); } if (channel) { struct ieee80211_channel *chan; u8 band; /* Skip entry if on csa closed channel */ if (channel == priv->csa_chan) { mwifiex_dbg(adapter, WARN, "Dropping entry on csa closed channel\n"); return 0; } band = BAND_G; if (radio_type) band = mwifiex_radio_type_to_band(*radio_type & (BIT(0) | BIT(1))); cfp = mwifiex_get_cfp(priv, band, channel, 0); freq = cfp ? cfp->freq : 0; chan = ieee80211_get_channel(priv->wdev.wiphy, freq); if (chan && !(chan->flags & IEEE80211_CHAN_DISABLED)) { bss = cfg80211_inform_bss(priv->wdev.wiphy, chan, CFG80211_BSS_FTYPE_UNKNOWN, bssid, timestamp, cap_info_bitmap, beacon_period, ie_buf, ie_len, rssi, GFP_KERNEL); if (bss) { bss_priv = (struct mwifiex_bss_priv *)bss->priv; bss_priv->band = band; bss_priv->fw_tsf = fw_tsf; if (priv->media_connected && !memcmp(bssid, priv->curr_bss_params. bss_descriptor.mac_address, ETH_ALEN)) mwifiex_update_curr_bss_params(priv, bss); if ((chan->flags & IEEE80211_CHAN_RADAR) || (chan->flags & IEEE80211_CHAN_NO_IR)) { mwifiex_dbg(adapter, INFO, "radar or passive channel %d\n", channel); mwifiex_save_hidden_ssid_channels(priv, bss); } cfg80211_put_bss(priv->wdev.wiphy, bss); } } } else { mwifiex_dbg(adapter, WARN, "missing BSS channel IE\n"); } return 0; } static void mwifiex_complete_scan(struct mwifiex_private *priv) { struct mwifiex_adapter *adapter = priv->adapter; adapter->survey_idx = 0; if (adapter->curr_cmd->wait_q_enabled) { adapter->cmd_wait_q.status = 0; if (!priv->scan_request) { mwifiex_dbg(adapter, INFO, "complete internal scan\n"); mwifiex_complete_cmd(adapter, adapter->curr_cmd); } } } /* This function checks if any hidden SSID found in passive scan channels * and do specific SSID active scan for those channels */ static int mwifiex_active_scan_req_for_passive_chan(struct mwifiex_private *priv) { int ret; struct mwifiex_adapter *adapter = priv->adapter; u8 id = 0; struct mwifiex_user_scan_cfg *user_scan_cfg; if (adapter->active_scan_triggered || !priv->scan_request || priv->scan_aborting) { adapter->active_scan_triggered = false; return 0; } if (!priv->hidden_chan[0].chan_number) { mwifiex_dbg(adapter, INFO, "No BSS with hidden SSID found on DFS channels\n"); return 0; } user_scan_cfg = kzalloc(sizeof(*user_scan_cfg), GFP_KERNEL); if (!user_scan_cfg) return -ENOMEM; for (id = 0; id < MWIFIEX_USER_SCAN_CHAN_MAX; id++) { if (!priv->hidden_chan[id].chan_number) break; memcpy(&user_scan_cfg->chan_list[id], &priv->hidden_chan[id], sizeof(struct mwifiex_user_scan_chan)); } adapter->active_scan_triggered = true; if (priv->scan_request->flags & NL80211_SCAN_FLAG_RANDOM_ADDR) ether_addr_copy(user_scan_cfg->random_mac, priv->scan_request->mac_addr); user_scan_cfg->num_ssids = priv->scan_request->n_ssids; user_scan_cfg->ssid_list = priv->scan_request->ssids; ret = mwifiex_scan_networks(priv, user_scan_cfg); kfree(user_scan_cfg); memset(&priv->hidden_chan, 0, sizeof(priv->hidden_chan)); if (ret) { dev_err(priv->adapter->dev, "scan failed: %d\n", ret); return ret; } return 0; } static void mwifiex_check_next_scan_command(struct mwifiex_private *priv) { struct mwifiex_adapter *adapter = priv->adapter; struct cmd_ctrl_node *cmd_node; spin_lock_bh(&adapter->scan_pending_q_lock); if (list_empty(&adapter->scan_pending_q)) { spin_unlock_bh(&adapter->scan_pending_q_lock); spin_lock_bh(&adapter->mwifiex_cmd_lock); adapter->scan_processing = false; spin_unlock_bh(&adapter->mwifiex_cmd_lock); mwifiex_active_scan_req_for_passive_chan(priv); if (!adapter->ext_scan) mwifiex_complete_scan(priv); if (priv->scan_request) { struct cfg80211_scan_info info = { .aborted = false, }; mwifiex_dbg(adapter, INFO, "info: notifying scan done\n"); cfg80211_scan_done(priv->scan_request, &info); priv->scan_request = NULL; priv->scan_aborting = false; } else { priv->scan_aborting = false; mwifiex_dbg(adapter, INFO, "info: scan already aborted\n"); } } else if ((priv->scan_aborting && !priv->scan_request) || priv->scan_block) { spin_unlock_bh(&adapter->scan_pending_q_lock); mwifiex_cancel_pending_scan_cmd(adapter); spin_lock_bh(&adapter->mwifiex_cmd_lock); adapter->scan_processing = false; spin_unlock_bh(&adapter->mwifiex_cmd_lock); if (!adapter->active_scan_triggered) { if (priv->scan_request) { struct cfg80211_scan_info info = { .aborted = true, }; mwifiex_dbg(adapter, INFO, "info: aborting scan\n"); cfg80211_scan_done(priv->scan_request, &info); priv->scan_request = NULL; priv->scan_aborting = false; } else { priv->scan_aborting = false; mwifiex_dbg(adapter, INFO, "info: scan already aborted\n"); } } } else { /* Get scan command from scan_pending_q and put to * cmd_pending_q */ cmd_node = list_first_entry(&adapter->scan_pending_q, struct cmd_ctrl_node, list); list_del(&cmd_node->list); spin_unlock_bh(&adapter->scan_pending_q_lock); mwifiex_insert_cmd_to_pending_q(adapter, cmd_node); } return; } void mwifiex_cancel_scan(struct mwifiex_adapter *adapter) { struct mwifiex_private *priv; int i; mwifiex_cancel_pending_scan_cmd(adapter); if (adapter->scan_processing) { spin_lock_bh(&adapter->mwifiex_cmd_lock); adapter->scan_processing = false; spin_unlock_bh(&adapter->mwifiex_cmd_lock); for (i = 0; i < adapter->priv_num; i++) { priv = adapter->priv[i]; if (!priv) continue; if (priv->scan_request) { struct cfg80211_scan_info info = { .aborted = true, }; mwifiex_dbg(adapter, INFO, "info: aborting scan\n"); cfg80211_scan_done(priv->scan_request, &info); priv->scan_request = NULL; priv->scan_aborting = false; } } } } /* * This function handles the command response of scan. * * The response buffer for the scan command has the following * memory layout: * * .-------------------------------------------------------------. * | Header (4 * sizeof(t_u16)): Standard command response hdr | * .-------------------------------------------------------------. * | BufSize (t_u16) : sizeof the BSS Description data | * .-------------------------------------------------------------. * | NumOfSet (t_u8) : Number of BSS Descs returned | * .-------------------------------------------------------------. * | BSSDescription data (variable, size given in BufSize) | * .-------------------------------------------------------------. * | TLV data (variable, size calculated using Header->Size, | * | BufSize and sizeof the fixed fields above) | * .-------------------------------------------------------------. */ int mwifiex_ret_802_11_scan(struct mwifiex_private *priv, struct host_cmd_ds_command *resp) { int ret = 0; struct mwifiex_adapter *adapter = priv->adapter; struct host_cmd_ds_802_11_scan_rsp *scan_rsp; struct mwifiex_ie_types_data *tlv_data; struct mwifiex_ie_types_tsf_timestamp *tsf_tlv; u8 *bss_info; u32 scan_resp_size; u32 bytes_left; u32 idx; u32 tlv_buf_size; struct mwifiex_ie_types_chan_band_list_param_set *chan_band_tlv; struct chan_band_param_set *chan_band; u8 is_bgscan_resp; __le64 fw_tsf = 0; u8 *radio_type; struct cfg80211_wowlan_nd_match *pmatch; struct cfg80211_sched_scan_request *nd_config = NULL; is_bgscan_resp = (le16_to_cpu(resp->command) == HostCmd_CMD_802_11_BG_SCAN_QUERY); if (is_bgscan_resp) scan_rsp = &resp->params.bg_scan_query_resp.scan_resp; else scan_rsp = &resp->params.scan_resp; if (scan_rsp->number_of_sets > MWIFIEX_MAX_AP) { mwifiex_dbg(adapter, ERROR, "SCAN_RESP: too many AP returned (%d)\n", scan_rsp->number_of_sets); ret = -1; goto check_next_scan; } /* Check csa channel expiry before parsing scan response */ mwifiex_11h_get_csa_closed_channel(priv); bytes_left = le16_to_cpu(scan_rsp->bss_descript_size); mwifiex_dbg(adapter, INFO, "info: SCAN_RESP: bss_descript_size %d\n", bytes_left); scan_resp_size = le16_to_cpu(resp->size); mwifiex_dbg(adapter, INFO, "info: SCAN_RESP: returned %d APs before parsing\n", scan_rsp->number_of_sets); bss_info = scan_rsp->bss_desc_and_tlv_buffer; /* * The size of the TLV buffer is equal to the entire command response * size (scan_resp_size) minus the fixed fields (sizeof()'s), the * BSS Descriptions (bss_descript_size as bytesLef) and the command * response header (S_DS_GEN) */ tlv_buf_size = scan_resp_size - (bytes_left + sizeof(scan_rsp->bss_descript_size) + sizeof(scan_rsp->number_of_sets) + S_DS_GEN); tlv_data = (struct mwifiex_ie_types_data *) (scan_rsp-> bss_desc_and_tlv_buffer + bytes_left); /* Search the TLV buffer space in the scan response for any valid TLVs */ mwifiex_ret_802_11_scan_get_tlv_ptrs(adapter, tlv_data, tlv_buf_size, TLV_TYPE_TSFTIMESTAMP, (struct mwifiex_ie_types_data **) &tsf_tlv); /* Search the TLV buffer space in the scan response for any valid TLVs */ mwifiex_ret_802_11_scan_get_tlv_ptrs(adapter, tlv_data, tlv_buf_size, TLV_TYPE_CHANNELBANDLIST, (struct mwifiex_ie_types_data **) &chan_band_tlv); #ifdef CONFIG_PM if (priv->wdev.wiphy->wowlan_config) nd_config = priv->wdev.wiphy->wowlan_config->nd_config; #endif if (nd_config) { adapter->nd_info = kzalloc(sizeof(struct cfg80211_wowlan_nd_match) + sizeof(struct cfg80211_wowlan_nd_match *) * scan_rsp->number_of_sets, GFP_ATOMIC); if (adapter->nd_info) adapter->nd_info->n_matches = scan_rsp->number_of_sets; } for (idx = 0; idx < scan_rsp->number_of_sets && bytes_left; idx++) { /* * If the TSF TLV was appended to the scan results, save this * entry's TSF value in the fw_tsf field. It is the firmware's * TSF value at the time the beacon or probe response was * received. */ if (tsf_tlv) memcpy(&fw_tsf, &tsf_tlv->tsf_data[idx * TSF_DATA_SIZE], sizeof(fw_tsf)); if (chan_band_tlv) { chan_band = &chan_band_tlv->chan_band_param[idx]; radio_type = &chan_band->radio_type; } else { radio_type = NULL; } if (chan_band_tlv && adapter->nd_info) { adapter->nd_info->matches[idx] = kzalloc(sizeof(*pmatch) + sizeof(u32), GFP_ATOMIC); pmatch = adapter->nd_info->matches[idx]; if (pmatch) { pmatch->n_channels = 1; pmatch->channels[0] = chan_band->chan_number; } } ret = mwifiex_parse_single_response_buf(priv, &bss_info, &bytes_left, le64_to_cpu(fw_tsf), radio_type, false, 0); if (ret) goto check_next_scan; } check_next_scan: mwifiex_check_next_scan_command(priv); return ret; } /* * This function prepares an extended scan command to be sent to the firmware * * This uses the scan command configuration sent to the command processing * module in command preparation stage to configure a extended scan command * structure to send to firmware. */ int mwifiex_cmd_802_11_scan_ext(struct mwifiex_private *priv, struct host_cmd_ds_command *cmd, void *data_buf) { struct host_cmd_ds_802_11_scan_ext *ext_scan = &cmd->params.ext_scan; struct mwifiex_scan_cmd_config *scan_cfg = data_buf; memcpy(ext_scan->tlv_buffer, scan_cfg->tlv_buf, scan_cfg->tlv_buf_len); cmd->command = cpu_to_le16(HostCmd_CMD_802_11_SCAN_EXT); /* Size is equal to the sizeof(fixed portions) + the TLV len + header */ cmd->size = cpu_to_le16((u16)(sizeof(ext_scan->reserved) + scan_cfg->tlv_buf_len + S_DS_GEN)); return 0; } /* This function prepares an background scan config command to be sent * to the firmware */ int mwifiex_cmd_802_11_bg_scan_config(struct mwifiex_private *priv, struct host_cmd_ds_command *cmd, void *data_buf) { struct host_cmd_ds_802_11_bg_scan_config *bgscan_config = &cmd->params.bg_scan_config; struct mwifiex_bg_scan_cfg *bgscan_cfg_in = data_buf; u8 *tlv_pos = bgscan_config->tlv; u8 num_probes; u32 ssid_len, chan_idx, scan_type, scan_dur, chan_num; int i; struct mwifiex_ie_types_num_probes *num_probes_tlv; struct mwifiex_ie_types_repeat_count *repeat_count_tlv; struct mwifiex_ie_types_min_rssi_threshold *rssi_threshold_tlv; struct mwifiex_ie_types_bgscan_start_later *start_later_tlv; struct mwifiex_ie_types_wildcard_ssid_params *wildcard_ssid_tlv; struct mwifiex_ie_types_chan_list_param_set *chan_list_tlv; struct mwifiex_chan_scan_param_set *temp_chan; cmd->command = cpu_to_le16(HostCmd_CMD_802_11_BG_SCAN_CONFIG); cmd->size = cpu_to_le16(sizeof(*bgscan_config) + S_DS_GEN); bgscan_config->action = cpu_to_le16(bgscan_cfg_in->action); bgscan_config->enable = bgscan_cfg_in->enable; bgscan_config->bss_type = bgscan_cfg_in->bss_type; bgscan_config->scan_interval = cpu_to_le32(bgscan_cfg_in->scan_interval); bgscan_config->report_condition = cpu_to_le32(bgscan_cfg_in->report_condition); /* stop sched scan */ if (!bgscan_config->enable) return 0; bgscan_config->chan_per_scan = bgscan_cfg_in->chan_per_scan; num_probes = (bgscan_cfg_in->num_probes ? bgscan_cfg_in-> num_probes : priv->adapter->scan_probes); if (num_probes) { num_probes_tlv = (struct mwifiex_ie_types_num_probes *)tlv_pos; num_probes_tlv->header.type = cpu_to_le16(TLV_TYPE_NUMPROBES); num_probes_tlv->header.len = cpu_to_le16(sizeof(num_probes_tlv->num_probes)); num_probes_tlv->num_probes = cpu_to_le16((u16)num_probes); tlv_pos += sizeof(num_probes_tlv->header) + le16_to_cpu(num_probes_tlv->header.len); } if (bgscan_cfg_in->repeat_count) { repeat_count_tlv = (struct mwifiex_ie_types_repeat_count *)tlv_pos; repeat_count_tlv->header.type = cpu_to_le16(TLV_TYPE_REPEAT_COUNT); repeat_count_tlv->header.len = cpu_to_le16(sizeof(repeat_count_tlv->repeat_count)); repeat_count_tlv->repeat_count = cpu_to_le16(bgscan_cfg_in->repeat_count); tlv_pos += sizeof(repeat_count_tlv->header) + le16_to_cpu(repeat_count_tlv->header.len); } if (bgscan_cfg_in->rssi_threshold) { rssi_threshold_tlv = (struct mwifiex_ie_types_min_rssi_threshold *)tlv_pos; rssi_threshold_tlv->header.type = cpu_to_le16(TLV_TYPE_RSSI_LOW); rssi_threshold_tlv->header.len = cpu_to_le16(sizeof(rssi_threshold_tlv->rssi_threshold)); rssi_threshold_tlv->rssi_threshold = cpu_to_le16(bgscan_cfg_in->rssi_threshold); tlv_pos += sizeof(rssi_threshold_tlv->header) + le16_to_cpu(rssi_threshold_tlv->header.len); } for (i = 0; i < bgscan_cfg_in->num_ssids; i++) { ssid_len = bgscan_cfg_in->ssid_list[i].ssid.ssid_len; wildcard_ssid_tlv = (struct mwifiex_ie_types_wildcard_ssid_params *)tlv_pos; wildcard_ssid_tlv->header.type = cpu_to_le16(TLV_TYPE_WILDCARDSSID); wildcard_ssid_tlv->header.len = cpu_to_le16( (u16)(ssid_len + sizeof(wildcard_ssid_tlv-> max_ssid_length))); /* max_ssid_length = 0 tells firmware to perform * specific scan for the SSID filled, whereas * max_ssid_length = IEEE80211_MAX_SSID_LEN is for * wildcard scan. */ if (ssid_len) wildcard_ssid_tlv->max_ssid_length = 0; else wildcard_ssid_tlv->max_ssid_length = IEEE80211_MAX_SSID_LEN; memcpy(wildcard_ssid_tlv->ssid, bgscan_cfg_in->ssid_list[i].ssid.ssid, ssid_len); tlv_pos += (sizeof(wildcard_ssid_tlv->header) + le16_to_cpu(wildcard_ssid_tlv->header.len)); } chan_list_tlv = (struct mwifiex_ie_types_chan_list_param_set *)tlv_pos; if (bgscan_cfg_in->chan_list[0].chan_number) { dev_dbg(priv->adapter->dev, "info: bgscan: Using supplied channel list\n"); chan_list_tlv->header.type = cpu_to_le16(TLV_TYPE_CHANLIST); for (chan_idx = 0; chan_idx < MWIFIEX_BG_SCAN_CHAN_MAX && bgscan_cfg_in->chan_list[chan_idx].chan_number; chan_idx++) { temp_chan = chan_list_tlv->chan_scan_param + chan_idx; /* Increment the TLV header length by size appended */ le16_unaligned_add_cpu(&chan_list_tlv->header.len, sizeof( chan_list_tlv->chan_scan_param)); temp_chan->chan_number = bgscan_cfg_in->chan_list[chan_idx].chan_number; temp_chan->radio_type = bgscan_cfg_in->chan_list[chan_idx].radio_type; scan_type = bgscan_cfg_in->chan_list[chan_idx].scan_type; if (scan_type == MWIFIEX_SCAN_TYPE_PASSIVE) temp_chan->chan_scan_mode_bitmap |= MWIFIEX_PASSIVE_SCAN; else temp_chan->chan_scan_mode_bitmap &= ~MWIFIEX_PASSIVE_SCAN; if (bgscan_cfg_in->chan_list[chan_idx].scan_time) { scan_dur = (u16)bgscan_cfg_in-> chan_list[chan_idx].scan_time; } else { scan_dur = (scan_type == MWIFIEX_SCAN_TYPE_PASSIVE) ? priv->adapter->passive_scan_time : priv->adapter->specific_scan_time; } temp_chan->min_scan_time = cpu_to_le16(scan_dur); temp_chan->max_scan_time = cpu_to_le16(scan_dur); } } else { dev_dbg(priv->adapter->dev, "info: bgscan: Creating full region channel list\n"); chan_num = mwifiex_bgscan_create_channel_list(priv, bgscan_cfg_in, chan_list_tlv-> chan_scan_param); le16_unaligned_add_cpu(&chan_list_tlv->header.len, chan_num * sizeof(chan_list_tlv->chan_scan_param[0])); } tlv_pos += (sizeof(chan_list_tlv->header) + le16_to_cpu(chan_list_tlv->header.len)); if (bgscan_cfg_in->start_later) { start_later_tlv = (struct mwifiex_ie_types_bgscan_start_later *)tlv_pos; start_later_tlv->header.type = cpu_to_le16(TLV_TYPE_BGSCAN_START_LATER); start_later_tlv->header.len = cpu_to_le16(sizeof(start_later_tlv->start_later)); start_later_tlv->start_later = cpu_to_le16(bgscan_cfg_in->start_later); tlv_pos += sizeof(start_later_tlv->header) + le16_to_cpu(start_later_tlv->header.len); } /* Append vendor specific IE TLV */ mwifiex_cmd_append_vsie_tlv(priv, MWIFIEX_VSIE_MASK_BGSCAN, &tlv_pos); le16_unaligned_add_cpu(&cmd->size, tlv_pos - bgscan_config->tlv); return 0; } int mwifiex_stop_bg_scan(struct mwifiex_private *priv) { struct mwifiex_bg_scan_cfg *bgscan_cfg; if (!priv->sched_scanning) { dev_dbg(priv->adapter->dev, "bgscan already stopped!\n"); return 0; } bgscan_cfg = kzalloc(sizeof(*bgscan_cfg), GFP_KERNEL); if (!bgscan_cfg) return -ENOMEM; bgscan_cfg->bss_type = MWIFIEX_BSS_MODE_INFRA; bgscan_cfg->action = MWIFIEX_BGSCAN_ACT_SET; bgscan_cfg->enable = false; if (mwifiex_send_cmd(priv, HostCmd_CMD_802_11_BG_SCAN_CONFIG, HostCmd_ACT_GEN_SET, 0, bgscan_cfg, true)) { kfree(bgscan_cfg); return -EFAULT; } kfree(bgscan_cfg); priv->sched_scanning = false; return 0; } static void mwifiex_update_chan_statistics(struct mwifiex_private *priv, struct mwifiex_ietypes_chanstats *tlv_stat) { struct mwifiex_adapter *adapter = priv->adapter; u8 i, num_chan; struct mwifiex_fw_chan_stats *fw_chan_stats; struct mwifiex_chan_stats chan_stats; fw_chan_stats = (void *)((u8 *)tlv_stat + sizeof(struct mwifiex_ie_types_header)); num_chan = le16_to_cpu(tlv_stat->header.len) / sizeof(struct mwifiex_chan_stats); for (i = 0 ; i < num_chan; i++) { if (adapter->survey_idx >= adapter->num_in_chan_stats) { mwifiex_dbg(adapter, WARN, "FW reported too many channel results (max %d)\n", adapter->num_in_chan_stats); return; } chan_stats.chan_num = fw_chan_stats->chan_num; chan_stats.bandcfg = fw_chan_stats->bandcfg; chan_stats.flags = fw_chan_stats->flags; chan_stats.noise = fw_chan_stats->noise; chan_stats.total_bss = le16_to_cpu(fw_chan_stats->total_bss); chan_stats.cca_scan_dur = le16_to_cpu(fw_chan_stats->cca_scan_dur); chan_stats.cca_busy_dur = le16_to_cpu(fw_chan_stats->cca_busy_dur); mwifiex_dbg(adapter, INFO, "chan=%d, noise=%d, total_network=%d scan_duration=%d, busy_duration=%d\n", chan_stats.chan_num, chan_stats.noise, chan_stats.total_bss, chan_stats.cca_scan_dur, chan_stats.cca_busy_dur); memcpy(&adapter->chan_stats[adapter->survey_idx++], &chan_stats, sizeof(struct mwifiex_chan_stats)); fw_chan_stats++; } } /* This function handles the command response of extended scan */ int mwifiex_ret_802_11_scan_ext(struct mwifiex_private *priv, struct host_cmd_ds_command *resp) { struct mwifiex_adapter *adapter = priv->adapter; struct host_cmd_ds_802_11_scan_ext *ext_scan_resp; struct mwifiex_ie_types_header *tlv; struct mwifiex_ietypes_chanstats *tlv_stat; u16 buf_left, type, len; struct host_cmd_ds_command *cmd_ptr; struct cmd_ctrl_node *cmd_node; bool complete_scan = false; mwifiex_dbg(adapter, INFO, "info: EXT scan returns successfully\n"); ext_scan_resp = &resp->params.ext_scan; tlv = (void *)ext_scan_resp->tlv_buffer; buf_left = le16_to_cpu(resp->size) - (sizeof(*ext_scan_resp) + S_DS_GEN - 1); while (buf_left >= sizeof(struct mwifiex_ie_types_header)) { type = le16_to_cpu(tlv->type); len = le16_to_cpu(tlv->len); if (buf_left < (sizeof(struct mwifiex_ie_types_header) + len)) { mwifiex_dbg(adapter, ERROR, "error processing scan response TLVs"); break; } switch (type) { case TLV_TYPE_CHANNEL_STATS: tlv_stat = (void *)tlv; mwifiex_update_chan_statistics(priv, tlv_stat); break; default: break; } buf_left -= len + sizeof(struct mwifiex_ie_types_header); tlv = (void *)((u8 *)tlv + len + sizeof(struct mwifiex_ie_types_header)); } spin_lock_bh(&adapter->cmd_pending_q_lock); spin_lock_bh(&adapter->scan_pending_q_lock); if (list_empty(&adapter->scan_pending_q)) { complete_scan = true; list_for_each_entry(cmd_node, &adapter->cmd_pending_q, list) { cmd_ptr = (void *)cmd_node->cmd_skb->data; if (le16_to_cpu(cmd_ptr->command) == HostCmd_CMD_802_11_SCAN_EXT) { mwifiex_dbg(adapter, INFO, "Scan pending in command pending list"); complete_scan = false; break; } } } spin_unlock_bh(&adapter->scan_pending_q_lock); spin_unlock_bh(&adapter->cmd_pending_q_lock); if (complete_scan) mwifiex_complete_scan(priv); return 0; } /* This function This function handles the event extended scan report. It * parses extended scan results and informs to cfg80211 stack. */ int mwifiex_handle_event_ext_scan_report(struct mwifiex_private *priv, void *buf) { int ret = 0; struct mwifiex_adapter *adapter = priv->adapter; u8 *bss_info; u32 bytes_left, bytes_left_for_tlv, idx; u16 type, len; struct mwifiex_ie_types_data *tlv; struct mwifiex_ie_types_bss_scan_rsp *scan_rsp_tlv; struct mwifiex_ie_types_bss_scan_info *scan_info_tlv; u8 *radio_type; u64 fw_tsf = 0; s32 rssi = 0; struct mwifiex_event_scan_result *event_scan = buf; u8 num_of_set = event_scan->num_of_set; u8 *scan_resp = buf + sizeof(struct mwifiex_event_scan_result); u16 scan_resp_size = le16_to_cpu(event_scan->buf_size); if (num_of_set > MWIFIEX_MAX_AP) { mwifiex_dbg(adapter, ERROR, "EXT_SCAN: Invalid number of AP returned (%d)!!\n", num_of_set); ret = -1; goto check_next_scan; } bytes_left = scan_resp_size; mwifiex_dbg(adapter, INFO, "EXT_SCAN: size %d, returned %d APs...", scan_resp_size, num_of_set); mwifiex_dbg_dump(adapter, CMD_D, "EXT_SCAN buffer:", buf, scan_resp_size + sizeof(struct mwifiex_event_scan_result)); tlv = (struct mwifiex_ie_types_data *)scan_resp; for (idx = 0; idx < num_of_set && bytes_left; idx++) { type = le16_to_cpu(tlv->header.type); len = le16_to_cpu(tlv->header.len); if (bytes_left < sizeof(struct mwifiex_ie_types_header) + len) { mwifiex_dbg(adapter, ERROR, "EXT_SCAN: Error bytes left < TLV length\n"); break; } scan_rsp_tlv = NULL; scan_info_tlv = NULL; bytes_left_for_tlv = bytes_left; /* BSS response TLV with beacon or probe response buffer * at the initial position of each descriptor */ if (type != TLV_TYPE_BSS_SCAN_RSP) break; bss_info = (u8 *)tlv; scan_rsp_tlv = (struct mwifiex_ie_types_bss_scan_rsp *)tlv; tlv = (struct mwifiex_ie_types_data *)(tlv->data + len); bytes_left_for_tlv -= (len + sizeof(struct mwifiex_ie_types_header)); while (bytes_left_for_tlv >= sizeof(struct mwifiex_ie_types_header) && le16_to_cpu(tlv->header.type) != TLV_TYPE_BSS_SCAN_RSP) { type = le16_to_cpu(tlv->header.type); len = le16_to_cpu(tlv->header.len); if (bytes_left_for_tlv < sizeof(struct mwifiex_ie_types_header) + len) { mwifiex_dbg(adapter, ERROR, "EXT_SCAN: Error in processing TLV,\t" "bytes left < TLV length\n"); scan_rsp_tlv = NULL; bytes_left_for_tlv = 0; continue; } switch (type) { case TLV_TYPE_BSS_SCAN_INFO: scan_info_tlv = (struct mwifiex_ie_types_bss_scan_info *)tlv; if (len != sizeof(struct mwifiex_ie_types_bss_scan_info) - sizeof(struct mwifiex_ie_types_header)) { bytes_left_for_tlv = 0; continue; } break; default: break; } tlv = (struct mwifiex_ie_types_data *)(tlv->data + len); bytes_left -= (len + sizeof(struct mwifiex_ie_types_header)); bytes_left_for_tlv -= (len + sizeof(struct mwifiex_ie_types_header)); } if (!scan_rsp_tlv) break; /* Advance pointer to the beacon buffer length and * update the bytes count so that the function * wlan_interpret_bss_desc_with_ie() can handle the * scan buffer withut any change */ bss_info += sizeof(u16); bytes_left -= sizeof(u16); if (scan_info_tlv) { rssi = (s32)(s16)(le16_to_cpu(scan_info_tlv->rssi)); rssi *= 100; /* Convert dBm to mBm */ mwifiex_dbg(adapter, INFO, "info: InterpretIE: RSSI=%d\n", rssi); fw_tsf = le64_to_cpu(scan_info_tlv->tsf); radio_type = &scan_info_tlv->radio_type; } else { radio_type = NULL; } ret = mwifiex_parse_single_response_buf(priv, &bss_info, &bytes_left, fw_tsf, radio_type, true, rssi); if (ret) goto check_next_scan; } check_next_scan: if (!event_scan->more_event) mwifiex_check_next_scan_command(priv); return ret; } /* * This function prepares command for background scan query. * * Preparation includes - * - Setting command ID and proper size * - Setting background scan flush parameter * - Ensuring correct endian-ness */ int mwifiex_cmd_802_11_bg_scan_query(struct host_cmd_ds_command *cmd) { struct host_cmd_ds_802_11_bg_scan_query *bg_query = &cmd->params.bg_scan_query; cmd->command = cpu_to_le16(HostCmd_CMD_802_11_BG_SCAN_QUERY); cmd->size = cpu_to_le16(sizeof(struct host_cmd_ds_802_11_bg_scan_query) + S_DS_GEN); bg_query->flush = 1; return 0; } /* * This function inserts scan command node to the scan pending queue. */ void mwifiex_queue_scan_cmd(struct mwifiex_private *priv, struct cmd_ctrl_node *cmd_node) { struct mwifiex_adapter *adapter = priv->adapter; cmd_node->wait_q_enabled = true; cmd_node->condition = &adapter->scan_wait_q_woken; spin_lock_bh(&adapter->scan_pending_q_lock); list_add_tail(&cmd_node->list, &adapter->scan_pending_q); spin_unlock_bh(&adapter->scan_pending_q_lock); } /* * This function sends a scan command for all available channels to the * firmware, filtered on a specific SSID. */ static int mwifiex_scan_specific_ssid(struct mwifiex_private *priv, struct cfg80211_ssid *req_ssid) { struct mwifiex_adapter *adapter = priv->adapter; int ret; struct mwifiex_user_scan_cfg *scan_cfg; if (adapter->scan_processing) { mwifiex_dbg(adapter, WARN, "cmd: Scan already in process...\n"); return -EBUSY; } if (priv->scan_block) { mwifiex_dbg(adapter, WARN, "cmd: Scan is blocked during association...\n"); return -EBUSY; } scan_cfg = kzalloc(sizeof(struct mwifiex_user_scan_cfg), GFP_KERNEL); if (!scan_cfg) return -ENOMEM; scan_cfg->ssid_list = req_ssid; scan_cfg->num_ssids = 1; ret = mwifiex_scan_networks(priv, scan_cfg); kfree(scan_cfg); return ret; } /* * Sends IOCTL request to start a scan. * * This function allocates the IOCTL request buffer, fills it * with requisite parameters and calls the IOCTL handler. * * Scan command can be issued for both normal scan and specific SSID * scan, depending upon whether an SSID is provided or not. */ int mwifiex_request_scan(struct mwifiex_private *priv, struct cfg80211_ssid *req_ssid) { int ret; if (mutex_lock_interruptible(&priv->async_mutex)) { mwifiex_dbg(priv->adapter, ERROR, "%s: acquire semaphore fail\n", __func__); return -1; } priv->adapter->scan_wait_q_woken = false; if (req_ssid && req_ssid->ssid_len != 0) /* Specific SSID scan */ ret = mwifiex_scan_specific_ssid(priv, req_ssid); else /* Normal scan */ ret = mwifiex_scan_networks(priv, NULL); mutex_unlock(&priv->async_mutex); return ret; } /* * This function appends the vendor specific IE TLV to a buffer. */ int mwifiex_cmd_append_vsie_tlv(struct mwifiex_private *priv, u16 vsie_mask, u8 **buffer) { int id, ret_len = 0; struct mwifiex_ie_types_vendor_param_set *vs_param_set; if (!buffer) return 0; if (!(*buffer)) return 0; /* * Traverse through the saved vendor specific IE array and append * the selected(scan/assoc/adhoc) IE as TLV to the command */ for (id = 0; id < MWIFIEX_MAX_VSIE_NUM; id++) { if (priv->vs_ie[id].mask & vsie_mask) { vs_param_set = (struct mwifiex_ie_types_vendor_param_set *) *buffer; vs_param_set->header.type = cpu_to_le16(TLV_TYPE_PASSTHROUGH); vs_param_set->header.len = cpu_to_le16((((u16) priv->vs_ie[id].ie[1]) & 0x00FF) + 2); if (le16_to_cpu(vs_param_set->header.len) > MWIFIEX_MAX_VSIE_LEN) { mwifiex_dbg(priv->adapter, ERROR, "Invalid param length!\n"); break; } memcpy(vs_param_set->ie, priv->vs_ie[id].ie, le16_to_cpu(vs_param_set->header.len)); *buffer += le16_to_cpu(vs_param_set->header.len) + sizeof(struct mwifiex_ie_types_header); ret_len += le16_to_cpu(vs_param_set->header.len) + sizeof(struct mwifiex_ie_types_header); } } return ret_len; } /* * This function saves a beacon buffer of the current BSS descriptor. * * The current beacon buffer is saved so that it can be restored in the * following cases that makes the beacon buffer not to contain the current * ssid's beacon buffer. * - The current ssid was not found somehow in the last scan. * - The current ssid was the last entry of the scan table and overloaded. */ void mwifiex_save_curr_bcn(struct mwifiex_private *priv) { struct mwifiex_bssdescriptor *curr_bss = &priv->curr_bss_params.bss_descriptor; if (!curr_bss->beacon_buf_size) return; /* allocate beacon buffer at 1st time; or if it's size has changed */ if (!priv->curr_bcn_buf || priv->curr_bcn_size != curr_bss->beacon_buf_size) { priv->curr_bcn_size = curr_bss->beacon_buf_size; kfree(priv->curr_bcn_buf); priv->curr_bcn_buf = kmalloc(curr_bss->beacon_buf_size, GFP_ATOMIC); if (!priv->curr_bcn_buf) return; } memcpy(priv->curr_bcn_buf, curr_bss->beacon_buf, curr_bss->beacon_buf_size); mwifiex_dbg(priv->adapter, INFO, "info: current beacon saved %d\n", priv->curr_bcn_size); curr_bss->beacon_buf = priv->curr_bcn_buf; /* adjust the pointers in the current BSS descriptor */ if (curr_bss->bcn_wpa_ie) curr_bss->bcn_wpa_ie = (struct ieee_types_vendor_specific *) (curr_bss->beacon_buf + curr_bss->wpa_offset); if (curr_bss->bcn_rsn_ie) curr_bss->bcn_rsn_ie = (struct ieee_types_generic *) (curr_bss->beacon_buf + curr_bss->rsn_offset); if (curr_bss->bcn_ht_cap) curr_bss->bcn_ht_cap = (struct ieee80211_ht_cap *) (curr_bss->beacon_buf + curr_bss->ht_cap_offset); if (curr_bss->bcn_ht_oper) curr_bss->bcn_ht_oper = (struct ieee80211_ht_operation *) (curr_bss->beacon_buf + curr_bss->ht_info_offset); if (curr_bss->bcn_vht_cap) curr_bss->bcn_vht_cap = (void *)(curr_bss->beacon_buf + curr_bss->vht_cap_offset); if (curr_bss->bcn_vht_oper) curr_bss->bcn_vht_oper = (void *)(curr_bss->beacon_buf + curr_bss->vht_info_offset); if (curr_bss->bcn_bss_co_2040) curr_bss->bcn_bss_co_2040 = (curr_bss->beacon_buf + curr_bss->bss_co_2040_offset); if (curr_bss->bcn_ext_cap) curr_bss->bcn_ext_cap = curr_bss->beacon_buf + curr_bss->ext_cap_offset; if (curr_bss->oper_mode) curr_bss->oper_mode = (void *)(curr_bss->beacon_buf + curr_bss->oper_mode_offset); } /* * This function frees the current BSS descriptor beacon buffer. */ void mwifiex_free_curr_bcn(struct mwifiex_private *priv) { kfree(priv->curr_bcn_buf); priv->curr_bcn_buf = NULL; }
null
170
CWE-787
CVE-2020-12654
/* * Marvell Wireless LAN device driver: WMM * * Copyright (C) 2011-2014, Marvell International Ltd. * * This software file (the "File") is distributed by Marvell International * Ltd. under the terms of the GNU General Public License Version 2, June 1991 * (the "License"). You may use, redistribute and/or modify this File in * accordance with the terms and conditions of the License, a copy of which * is available by writing to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the * worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE * IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE * ARE EXPRESSLY DISCLAIMED. The License provides additional details about * this warranty disclaimer. */ #include "decl.h" #include "ioctl.h" #include "util.h" #include "fw.h" #include "main.h" #include "wmm.h" #include "11n.h" /* Maximum value FW can accept for driver delay in packet transmission */ #define DRV_PKT_DELAY_TO_FW_MAX 512 #define WMM_QUEUED_PACKET_LOWER_LIMIT 180 #define WMM_QUEUED_PACKET_UPPER_LIMIT 200 /* Offset for TOS field in the IP header */ #define IPTOS_OFFSET 5 static bool disable_tx_amsdu; module_param(disable_tx_amsdu, bool, 0644); /* WMM information IE */ static const u8 wmm_info_ie[] = { WLAN_EID_VENDOR_SPECIFIC, 0x07, 0x00, 0x50, 0xf2, 0x02, 0x00, 0x01, 0x00 }; static const u8 wmm_aci_to_qidx_map[] = { WMM_AC_BE, WMM_AC_BK, WMM_AC_VI, WMM_AC_VO }; static u8 tos_to_tid[] = { /* TID DSCP_P2 DSCP_P1 DSCP_P0 WMM_AC */ 0x01, /* 0 1 0 AC_BK */ 0x02, /* 0 0 0 AC_BK */ 0x00, /* 0 0 1 AC_BE */ 0x03, /* 0 1 1 AC_BE */ 0x04, /* 1 0 0 AC_VI */ 0x05, /* 1 0 1 AC_VI */ 0x06, /* 1 1 0 AC_VO */ 0x07 /* 1 1 1 AC_VO */ }; static u8 ac_to_tid[4][2] = { {1, 2}, {0, 3}, {4, 5}, {6, 7} }; /* * This function debug prints the priority parameters for a WMM AC. */ static void mwifiex_wmm_ac_debug_print(const struct ieee_types_wmm_ac_parameters *ac_param) { const char *ac_str[] = { "BK", "BE", "VI", "VO" }; pr_debug("info: WMM AC_%s: ACI=%d, ACM=%d, Aifsn=%d, " "EcwMin=%d, EcwMax=%d, TxopLimit=%d\n", ac_str[wmm_aci_to_qidx_map[(ac_param->aci_aifsn_bitmap & MWIFIEX_ACI) >> 5]], (ac_param->aci_aifsn_bitmap & MWIFIEX_ACI) >> 5, (ac_param->aci_aifsn_bitmap & MWIFIEX_ACM) >> 4, ac_param->aci_aifsn_bitmap & MWIFIEX_AIFSN, ac_param->ecw_bitmap & MWIFIEX_ECW_MIN, (ac_param->ecw_bitmap & MWIFIEX_ECW_MAX) >> 4, le16_to_cpu(ac_param->tx_op_limit)); } /* * This function allocates a route address list. * * The function also initializes the list with the provided RA. */ static struct mwifiex_ra_list_tbl * mwifiex_wmm_allocate_ralist_node(struct mwifiex_adapter *adapter, const u8 *ra) { struct mwifiex_ra_list_tbl *ra_list; ra_list = kzalloc(sizeof(struct mwifiex_ra_list_tbl), GFP_ATOMIC); if (!ra_list) return NULL; INIT_LIST_HEAD(&ra_list->list); skb_queue_head_init(&ra_list->skb_head); memcpy(ra_list->ra, ra, ETH_ALEN); ra_list->total_pkt_count = 0; mwifiex_dbg(adapter, INFO, "info: allocated ra_list %p\n", ra_list); return ra_list; } /* This function returns random no between 16 and 32 to be used as threshold * for no of packets after which BA setup is initiated. */ static u8 mwifiex_get_random_ba_threshold(void) { u64 ns; /* setup ba_packet_threshold here random number between * [BA_SETUP_PACKET_OFFSET, * BA_SETUP_PACKET_OFFSET+BA_SETUP_MAX_PACKET_THRESHOLD-1] */ ns = ktime_get_ns(); ns += (ns >> 32) + (ns >> 16); return ((u8)ns % BA_SETUP_MAX_PACKET_THRESHOLD) + BA_SETUP_PACKET_OFFSET; } /* * This function allocates and adds a RA list for all TIDs * with the given RA. */ void mwifiex_ralist_add(struct mwifiex_private *priv, const u8 *ra) { int i; struct mwifiex_ra_list_tbl *ra_list; struct mwifiex_adapter *adapter = priv->adapter; struct mwifiex_sta_node *node; for (i = 0; i < MAX_NUM_TID; ++i) { ra_list = mwifiex_wmm_allocate_ralist_node(adapter, ra); mwifiex_dbg(adapter, INFO, "info: created ra_list %p\n", ra_list); if (!ra_list) break; ra_list->is_11n_enabled = 0; ra_list->tdls_link = false; ra_list->ba_status = BA_SETUP_NONE; ra_list->amsdu_in_ampdu = false; if (!mwifiex_queuing_ra_based(priv)) { if (mwifiex_is_tdls_link_setup (mwifiex_get_tdls_link_status(priv, ra))) { ra_list->tdls_link = true; ra_list->is_11n_enabled = mwifiex_tdls_peer_11n_enabled(priv, ra); } else { ra_list->is_11n_enabled = IS_11N_ENABLED(priv); } } else { spin_lock_bh(&priv->sta_list_spinlock); node = mwifiex_get_sta_entry(priv, ra); if (node) ra_list->tx_paused = node->tx_pause; ra_list->is_11n_enabled = mwifiex_is_sta_11n_enabled(priv, node); if (ra_list->is_11n_enabled) ra_list->max_amsdu = node->max_amsdu; spin_unlock_bh(&priv->sta_list_spinlock); } mwifiex_dbg(adapter, DATA, "data: ralist %p: is_11n_enabled=%d\n", ra_list, ra_list->is_11n_enabled); if (ra_list->is_11n_enabled) { ra_list->ba_pkt_count = 0; ra_list->ba_packet_thr = mwifiex_get_random_ba_threshold(); } list_add_tail(&ra_list->list, &priv->wmm.tid_tbl_ptr[i].ra_list); } } /* * This function sets the WMM queue priorities to their default values. */ static void mwifiex_wmm_default_queue_priorities(struct mwifiex_private *priv) { /* Default queue priorities: VO->VI->BE->BK */ priv->wmm.queue_priority[0] = WMM_AC_VO; priv->wmm.queue_priority[1] = WMM_AC_VI; priv->wmm.queue_priority[2] = WMM_AC_BE; priv->wmm.queue_priority[3] = WMM_AC_BK; } /* * This function map ACs to TIDs. */ static void mwifiex_wmm_queue_priorities_tid(struct mwifiex_private *priv) { struct mwifiex_wmm_desc *wmm = &priv->wmm; u8 *queue_priority = wmm->queue_priority; int i; for (i = 0; i < 4; ++i) { tos_to_tid[7 - (i * 2)] = ac_to_tid[queue_priority[i]][1]; tos_to_tid[6 - (i * 2)] = ac_to_tid[queue_priority[i]][0]; } for (i = 0; i < MAX_NUM_TID; ++i) priv->tos_to_tid_inv[tos_to_tid[i]] = (u8)i; atomic_set(&wmm->highest_queued_prio, HIGH_PRIO_TID); } /* * This function initializes WMM priority queues. */ void mwifiex_wmm_setup_queue_priorities(struct mwifiex_private *priv, struct ieee_types_wmm_parameter *wmm_ie) { u16 cw_min, avg_back_off, tmp[4]; u32 i, j, num_ac; u8 ac_idx; if (!wmm_ie || !priv->wmm_enabled) { /* WMM is not enabled, just set the defaults and return */ mwifiex_wmm_default_queue_priorities(priv); return; } mwifiex_dbg(priv->adapter, INFO, "info: WMM Parameter IE: version=%d,\t" "qos_info Parameter Set Count=%d, Reserved=%#x\n", wmm_ie->version, wmm_ie->qos_info_bitmap & IEEE80211_WMM_IE_AP_QOSINFO_PARAM_SET_CNT_MASK, wmm_ie->reserved); for (num_ac = 0; num_ac < ARRAY_SIZE(wmm_ie->ac_params); num_ac++) { u8 ecw = wmm_ie->ac_params[num_ac].ecw_bitmap; u8 aci_aifsn = wmm_ie->ac_params[num_ac].aci_aifsn_bitmap; cw_min = (1 << (ecw & MWIFIEX_ECW_MIN)) - 1; avg_back_off = (cw_min >> 1) + (aci_aifsn & MWIFIEX_AIFSN); ac_idx = wmm_aci_to_qidx_map[(aci_aifsn & MWIFIEX_ACI) >> 5]; priv->wmm.queue_priority[ac_idx] = ac_idx; tmp[ac_idx] = avg_back_off; mwifiex_dbg(priv->adapter, INFO, "info: WMM: CWmax=%d CWmin=%d Avg Back-off=%d\n", (1 << ((ecw & MWIFIEX_ECW_MAX) >> 4)) - 1, cw_min, avg_back_off); mwifiex_wmm_ac_debug_print(&wmm_ie->ac_params[num_ac]); } /* Bubble sort */ for (i = 0; i < num_ac; i++) { for (j = 1; j < num_ac - i; j++) { if (tmp[j - 1] > tmp[j]) { swap(tmp[j - 1], tmp[j]); swap(priv->wmm.queue_priority[j - 1], priv->wmm.queue_priority[j]); } else if (tmp[j - 1] == tmp[j]) { if (priv->wmm.queue_priority[j - 1] < priv->wmm.queue_priority[j]) swap(priv->wmm.queue_priority[j - 1], priv->wmm.queue_priority[j]); } } } mwifiex_wmm_queue_priorities_tid(priv); } /* * This function evaluates whether or not an AC is to be downgraded. * * In case the AC is not enabled, the highest AC is returned that is * enabled and does not require admission control. */ static enum mwifiex_wmm_ac_e mwifiex_wmm_eval_downgrade_ac(struct mwifiex_private *priv, enum mwifiex_wmm_ac_e eval_ac) { int down_ac; enum mwifiex_wmm_ac_e ret_ac; struct mwifiex_wmm_ac_status *ac_status; ac_status = &priv->wmm.ac_status[eval_ac]; if (!ac_status->disabled) /* Okay to use this AC, its enabled */ return eval_ac; /* Setup a default return value of the lowest priority */ ret_ac = WMM_AC_BK; /* * Find the highest AC that is enabled and does not require * admission control. The spec disallows downgrading to an AC, * which is enabled due to a completed admission control. * Unadmitted traffic is not to be sent on an AC with admitted * traffic. */ for (down_ac = WMM_AC_BK; down_ac < eval_ac; down_ac++) { ac_status = &priv->wmm.ac_status[down_ac]; if (!ac_status->disabled && !ac_status->flow_required) /* AC is enabled and does not require admission control */ ret_ac = (enum mwifiex_wmm_ac_e) down_ac; } return ret_ac; } /* * This function downgrades WMM priority queue. */ void mwifiex_wmm_setup_ac_downgrade(struct mwifiex_private *priv) { int ac_val; mwifiex_dbg(priv->adapter, INFO, "info: WMM: AC Priorities:\t" "BK(0), BE(1), VI(2), VO(3)\n"); if (!priv->wmm_enabled) { /* WMM is not enabled, default priorities */ for (ac_val = WMM_AC_BK; ac_val <= WMM_AC_VO; ac_val++) priv->wmm.ac_down_graded_vals[ac_val] = (enum mwifiex_wmm_ac_e) ac_val; } else { for (ac_val = WMM_AC_BK; ac_val <= WMM_AC_VO; ac_val++) { priv->wmm.ac_down_graded_vals[ac_val] = mwifiex_wmm_eval_downgrade_ac(priv, (enum mwifiex_wmm_ac_e) ac_val); mwifiex_dbg(priv->adapter, INFO, "info: WMM: AC PRIO %d maps to %d\n", ac_val, priv->wmm.ac_down_graded_vals[ac_val]); } } } /* * This function converts the IP TOS field to an WMM AC * Queue assignment. */ static enum mwifiex_wmm_ac_e mwifiex_wmm_convert_tos_to_ac(struct mwifiex_adapter *adapter, u32 tos) { /* Map of TOS UP values to WMM AC */ static const enum mwifiex_wmm_ac_e tos_to_ac[] = { WMM_AC_BE, WMM_AC_BK, WMM_AC_BK, WMM_AC_BE, WMM_AC_VI, WMM_AC_VI, WMM_AC_VO, WMM_AC_VO }; if (tos >= ARRAY_SIZE(tos_to_ac)) return WMM_AC_BE; return tos_to_ac[tos]; } /* * This function evaluates a given TID and downgrades it to a lower * TID if the WMM Parameter IE received from the AP indicates that the * AP is disabled (due to call admission control (ACM bit). Mapping * of TID to AC is taken care of internally. */ u8 mwifiex_wmm_downgrade_tid(struct mwifiex_private *priv, u32 tid) { enum mwifiex_wmm_ac_e ac, ac_down; u8 new_tid; ac = mwifiex_wmm_convert_tos_to_ac(priv->adapter, tid); ac_down = priv->wmm.ac_down_graded_vals[ac]; /* Send the index to tid array, picking from the array will be * taken care by dequeuing function */ new_tid = ac_to_tid[ac_down][tid % 2]; return new_tid; } /* * This function initializes the WMM state information and the * WMM data path queues. */ void mwifiex_wmm_init(struct mwifiex_adapter *adapter) { int i, j; struct mwifiex_private *priv; for (j = 0; j < adapter->priv_num; ++j) { priv = adapter->priv[j]; if (!priv) continue; for (i = 0; i < MAX_NUM_TID; ++i) { if (!disable_tx_amsdu && adapter->tx_buf_size > MWIFIEX_TX_DATA_BUF_SIZE_2K) priv->aggr_prio_tbl[i].amsdu = priv->tos_to_tid_inv[i]; else priv->aggr_prio_tbl[i].amsdu = BA_STREAM_NOT_ALLOWED; priv->aggr_prio_tbl[i].ampdu_ap = priv->tos_to_tid_inv[i]; priv->aggr_prio_tbl[i].ampdu_user = priv->tos_to_tid_inv[i]; } priv->aggr_prio_tbl[6].amsdu = priv->aggr_prio_tbl[6].ampdu_ap = priv->aggr_prio_tbl[6].ampdu_user = BA_STREAM_NOT_ALLOWED; priv->aggr_prio_tbl[7].amsdu = priv->aggr_prio_tbl[7].ampdu_ap = priv->aggr_prio_tbl[7].ampdu_user = BA_STREAM_NOT_ALLOWED; mwifiex_set_ba_params(priv); mwifiex_reset_11n_rx_seq_num(priv); priv->wmm.drv_pkt_delay_max = MWIFIEX_WMM_DRV_DELAY_MAX; atomic_set(&priv->wmm.tx_pkts_queued, 0); atomic_set(&priv->wmm.highest_queued_prio, HIGH_PRIO_TID); } } int mwifiex_bypass_txlist_empty(struct mwifiex_adapter *adapter) { struct mwifiex_private *priv; int i; for (i = 0; i < adapter->priv_num; i++) { priv = adapter->priv[i]; if (!priv) continue; if (adapter->if_ops.is_port_ready && !adapter->if_ops.is_port_ready(priv)) continue; if (!skb_queue_empty(&priv->bypass_txq)) return false; } return true; } /* * This function checks if WMM Tx queue is empty. */ int mwifiex_wmm_lists_empty(struct mwifiex_adapter *adapter) { int i; struct mwifiex_private *priv; for (i = 0; i < adapter->priv_num; ++i) { priv = adapter->priv[i]; if (!priv) continue; if (!priv->port_open && (priv->bss_mode != NL80211_IFTYPE_ADHOC)) continue; if (adapter->if_ops.is_port_ready && !adapter->if_ops.is_port_ready(priv)) continue; if (atomic_read(&priv->wmm.tx_pkts_queued)) return false; } return true; } /* * This function deletes all packets in an RA list node. * * The packet sent completion callback handler are called with * status failure, after they are dequeued to ensure proper * cleanup. The RA list node itself is freed at the end. */ static void mwifiex_wmm_del_pkts_in_ralist_node(struct mwifiex_private *priv, struct mwifiex_ra_list_tbl *ra_list) { struct mwifiex_adapter *adapter = priv->adapter; struct sk_buff *skb, *tmp; skb_queue_walk_safe(&ra_list->skb_head, skb, tmp) { skb_unlink(skb, &ra_list->skb_head); mwifiex_write_data_complete(adapter, skb, 0, -1); } } /* * This function deletes all packets in an RA list. * * Each nodes in the RA list are freed individually first, and then * the RA list itself is freed. */ static void mwifiex_wmm_del_pkts_in_ralist(struct mwifiex_private *priv, struct list_head *ra_list_head) { struct mwifiex_ra_list_tbl *ra_list; list_for_each_entry(ra_list, ra_list_head, list) mwifiex_wmm_del_pkts_in_ralist_node(priv, ra_list); } /* * This function deletes all packets in all RA lists. */ static void mwifiex_wmm_cleanup_queues(struct mwifiex_private *priv) { int i; for (i = 0; i < MAX_NUM_TID; i++) mwifiex_wmm_del_pkts_in_ralist(priv, &priv->wmm.tid_tbl_ptr[i]. ra_list); atomic_set(&priv->wmm.tx_pkts_queued, 0); atomic_set(&priv->wmm.highest_queued_prio, HIGH_PRIO_TID); } /* * This function deletes all route addresses from all RA lists. */ static void mwifiex_wmm_delete_all_ralist(struct mwifiex_private *priv) { struct mwifiex_ra_list_tbl *ra_list, *tmp_node; int i; for (i = 0; i < MAX_NUM_TID; ++i) { mwifiex_dbg(priv->adapter, INFO, "info: ra_list: freeing buf for tid %d\n", i); list_for_each_entry_safe(ra_list, tmp_node, &priv->wmm.tid_tbl_ptr[i].ra_list, list) { list_del(&ra_list->list); kfree(ra_list); } INIT_LIST_HEAD(&priv->wmm.tid_tbl_ptr[i].ra_list); } } static int mwifiex_free_ack_frame(int id, void *p, void *data) { pr_warn("Have pending ack frames!\n"); kfree_skb(p); return 0; } /* * This function cleans up the Tx and Rx queues. * * Cleanup includes - * - All packets in RA lists * - All entries in Rx reorder table * - All entries in Tx BA stream table * - MPA buffer (if required) * - All RA lists */ void mwifiex_clean_txrx(struct mwifiex_private *priv) { struct sk_buff *skb, *tmp; mwifiex_11n_cleanup_reorder_tbl(priv); spin_lock_bh(&priv->wmm.ra_list_spinlock); mwifiex_wmm_cleanup_queues(priv); mwifiex_11n_delete_all_tx_ba_stream_tbl(priv); if (priv->adapter->if_ops.cleanup_mpa_buf) priv->adapter->if_ops.cleanup_mpa_buf(priv->adapter); mwifiex_wmm_delete_all_ralist(priv); memcpy(tos_to_tid, ac_to_tid, sizeof(tos_to_tid)); if (priv->adapter->if_ops.clean_pcie_ring && !test_bit(MWIFIEX_SURPRISE_REMOVED, &priv->adapter->work_flags)) priv->adapter->if_ops.clean_pcie_ring(priv->adapter); spin_unlock_bh(&priv->wmm.ra_list_spinlock); skb_queue_walk_safe(&priv->tdls_txq, skb, tmp) { skb_unlink(skb, &priv->tdls_txq); mwifiex_write_data_complete(priv->adapter, skb, 0, -1); } skb_queue_walk_safe(&priv->bypass_txq, skb, tmp) { skb_unlink(skb, &priv->bypass_txq); mwifiex_write_data_complete(priv->adapter, skb, 0, -1); } atomic_set(&priv->adapter->bypass_tx_pending, 0); idr_for_each(&priv->ack_status_frames, mwifiex_free_ack_frame, NULL); idr_destroy(&priv->ack_status_frames); } /* * This function retrieves a particular RA list node, matching with the * given TID and RA address. */ struct mwifiex_ra_list_tbl * mwifiex_wmm_get_ralist_node(struct mwifiex_private *priv, u8 tid, const u8 *ra_addr) { struct mwifiex_ra_list_tbl *ra_list; list_for_each_entry(ra_list, &priv->wmm.tid_tbl_ptr[tid].ra_list, list) { if (!memcmp(ra_list->ra, ra_addr, ETH_ALEN)) return ra_list; } return NULL; } void mwifiex_update_ralist_tx_pause(struct mwifiex_private *priv, u8 *mac, u8 tx_pause) { struct mwifiex_ra_list_tbl *ra_list; u32 pkt_cnt = 0, tx_pkts_queued; int i; spin_lock_bh(&priv->wmm.ra_list_spinlock); for (i = 0; i < MAX_NUM_TID; ++i) { ra_list = mwifiex_wmm_get_ralist_node(priv, i, mac); if (ra_list && ra_list->tx_paused != tx_pause) { pkt_cnt += ra_list->total_pkt_count; ra_list->tx_paused = tx_pause; if (tx_pause) priv->wmm.pkts_paused[i] += ra_list->total_pkt_count; else priv->wmm.pkts_paused[i] -= ra_list->total_pkt_count; } } if (pkt_cnt) { tx_pkts_queued = atomic_read(&priv->wmm.tx_pkts_queued); if (tx_pause) tx_pkts_queued -= pkt_cnt; else tx_pkts_queued += pkt_cnt; atomic_set(&priv->wmm.tx_pkts_queued, tx_pkts_queued); atomic_set(&priv->wmm.highest_queued_prio, HIGH_PRIO_TID); } spin_unlock_bh(&priv->wmm.ra_list_spinlock); } /* This function updates non-tdls peer ralist tx_pause while * tdls channel switching */ void mwifiex_update_ralist_tx_pause_in_tdls_cs(struct mwifiex_private *priv, u8 *mac, u8 tx_pause) { struct mwifiex_ra_list_tbl *ra_list; u32 pkt_cnt = 0, tx_pkts_queued; int i; spin_lock_bh(&priv->wmm.ra_list_spinlock); for (i = 0; i < MAX_NUM_TID; ++i) { list_for_each_entry(ra_list, &priv->wmm.tid_tbl_ptr[i].ra_list, list) { if (!memcmp(ra_list->ra, mac, ETH_ALEN)) continue; if (ra_list->tx_paused != tx_pause) { pkt_cnt += ra_list->total_pkt_count; ra_list->tx_paused = tx_pause; if (tx_pause) priv->wmm.pkts_paused[i] += ra_list->total_pkt_count; else priv->wmm.pkts_paused[i] -= ra_list->total_pkt_count; } } } if (pkt_cnt) { tx_pkts_queued = atomic_read(&priv->wmm.tx_pkts_queued); if (tx_pause) tx_pkts_queued -= pkt_cnt; else tx_pkts_queued += pkt_cnt; atomic_set(&priv->wmm.tx_pkts_queued, tx_pkts_queued); atomic_set(&priv->wmm.highest_queued_prio, HIGH_PRIO_TID); } spin_unlock_bh(&priv->wmm.ra_list_spinlock); } /* * This function retrieves an RA list node for a given TID and * RA address pair. * * If no such node is found, a new node is added first and then * retrieved. */ struct mwifiex_ra_list_tbl * mwifiex_wmm_get_queue_raptr(struct mwifiex_private *priv, u8 tid, const u8 *ra_addr) { struct mwifiex_ra_list_tbl *ra_list; ra_list = mwifiex_wmm_get_ralist_node(priv, tid, ra_addr); if (ra_list) return ra_list; mwifiex_ralist_add(priv, ra_addr); return mwifiex_wmm_get_ralist_node(priv, tid, ra_addr); } /* * This function deletes RA list nodes for given mac for all TIDs. * Function also decrements TX pending count accordingly. */ void mwifiex_wmm_del_peer_ra_list(struct mwifiex_private *priv, const u8 *ra_addr) { struct mwifiex_ra_list_tbl *ra_list; int i; spin_lock_bh(&priv->wmm.ra_list_spinlock); for (i = 0; i < MAX_NUM_TID; ++i) { ra_list = mwifiex_wmm_get_ralist_node(priv, i, ra_addr); if (!ra_list) continue; mwifiex_wmm_del_pkts_in_ralist_node(priv, ra_list); if (ra_list->tx_paused) priv->wmm.pkts_paused[i] -= ra_list->total_pkt_count; else atomic_sub(ra_list->total_pkt_count, &priv->wmm.tx_pkts_queued); list_del(&ra_list->list); kfree(ra_list); } spin_unlock_bh(&priv->wmm.ra_list_spinlock); } /* * This function checks if a particular RA list node exists in a given TID * table index. */ int mwifiex_is_ralist_valid(struct mwifiex_private *priv, struct mwifiex_ra_list_tbl *ra_list, int ptr_index) { struct mwifiex_ra_list_tbl *rlist; list_for_each_entry(rlist, &priv->wmm.tid_tbl_ptr[ptr_index].ra_list, list) { if (rlist == ra_list) return true; } return false; } /* * This function adds a packet to bypass TX queue. * This is special TX queue for packets which can be sent even when port_open * is false. */ void mwifiex_wmm_add_buf_bypass_txqueue(struct mwifiex_private *priv, struct sk_buff *skb) { skb_queue_tail(&priv->bypass_txq, skb); } /* * This function adds a packet to WMM queue. * * In disconnected state the packet is immediately dropped and the * packet send completion callback is called with status failure. * * Otherwise, the correct RA list node is located and the packet * is queued at the list tail. */ void mwifiex_wmm_add_buf_txqueue(struct mwifiex_private *priv, struct sk_buff *skb) { struct mwifiex_adapter *adapter = priv->adapter; u32 tid; struct mwifiex_ra_list_tbl *ra_list; u8 ra[ETH_ALEN], tid_down; struct list_head list_head; int tdls_status = TDLS_NOT_SETUP; struct ethhdr *eth_hdr = (struct ethhdr *)skb->data; struct mwifiex_txinfo *tx_info = MWIFIEX_SKB_TXCB(skb); memcpy(ra, eth_hdr->h_dest, ETH_ALEN); if (GET_BSS_ROLE(priv) == MWIFIEX_BSS_ROLE_STA && ISSUPP_TDLS_ENABLED(adapter->fw_cap_info)) { if (ntohs(eth_hdr->h_proto) == ETH_P_TDLS) mwifiex_dbg(adapter, DATA, "TDLS setup packet for %pM.\t" "Don't block\n", ra); else if (memcmp(priv->cfg_bssid, ra, ETH_ALEN)) tdls_status = mwifiex_get_tdls_link_status(priv, ra); } if (!priv->media_connected && !mwifiex_is_skb_mgmt_frame(skb)) { mwifiex_dbg(adapter, DATA, "data: drop packet in disconnect\n"); mwifiex_write_data_complete(adapter, skb, 0, -1); return; } tid = skb->priority; spin_lock_bh(&priv->wmm.ra_list_spinlock); tid_down = mwifiex_wmm_downgrade_tid(priv, tid); /* In case of infra as we have already created the list during association we just don't have to call get_queue_raptr, we will have only 1 raptr for a tid in case of infra */ if (!mwifiex_queuing_ra_based(priv) && !mwifiex_is_skb_mgmt_frame(skb)) { switch (tdls_status) { case TDLS_SETUP_COMPLETE: case TDLS_CHAN_SWITCHING: case TDLS_IN_BASE_CHAN: case TDLS_IN_OFF_CHAN: ra_list = mwifiex_wmm_get_queue_raptr(priv, tid_down, ra); tx_info->flags |= MWIFIEX_BUF_FLAG_TDLS_PKT; break; case TDLS_SETUP_INPROGRESS: skb_queue_tail(&priv->tdls_txq, skb); spin_unlock_bh(&priv->wmm.ra_list_spinlock); return; default: list_head = priv->wmm.tid_tbl_ptr[tid_down].ra_list; ra_list = list_first_entry_or_null(&list_head, struct mwifiex_ra_list_tbl, list); break; } } else { memcpy(ra, skb->data, ETH_ALEN); if (ra[0] & 0x01 || mwifiex_is_skb_mgmt_frame(skb)) eth_broadcast_addr(ra); ra_list = mwifiex_wmm_get_queue_raptr(priv, tid_down, ra); } if (!ra_list) { spin_unlock_bh(&priv->wmm.ra_list_spinlock); mwifiex_write_data_complete(adapter, skb, 0, -1); return; } skb_queue_tail(&ra_list->skb_head, skb); ra_list->ba_pkt_count++; ra_list->total_pkt_count++; if (atomic_read(&priv->wmm.highest_queued_prio) < priv->tos_to_tid_inv[tid_down]) atomic_set(&priv->wmm.highest_queued_prio, priv->tos_to_tid_inv[tid_down]); if (ra_list->tx_paused) priv->wmm.pkts_paused[tid_down]++; else atomic_inc(&priv->wmm.tx_pkts_queued); spin_unlock_bh(&priv->wmm.ra_list_spinlock); } /* * This function processes the get WMM status command response from firmware. * * The response may contain multiple TLVs - * - AC Queue status TLVs * - Current WMM Parameter IE TLV * - Admission Control action frame TLVs * * This function parses the TLVs and then calls further specific functions * to process any changes in the queue prioritize or state. */ int mwifiex_ret_wmm_get_status(struct mwifiex_private *priv, const struct host_cmd_ds_command *resp) { u8 *curr = (u8 *) &resp->params.get_wmm_status; uint16_t resp_len = le16_to_cpu(resp->size), tlv_len; int mask = IEEE80211_WMM_IE_AP_QOSINFO_PARAM_SET_CNT_MASK; bool valid = true; struct mwifiex_ie_types_data *tlv_hdr; struct mwifiex_ie_types_wmm_queue_status *tlv_wmm_qstatus; struct ieee_types_wmm_parameter *wmm_param_ie = NULL; struct mwifiex_wmm_ac_status *ac_status; mwifiex_dbg(priv->adapter, INFO, "info: WMM: WMM_GET_STATUS cmdresp received: %d\n", resp_len); while ((resp_len >= sizeof(tlv_hdr->header)) && valid) { tlv_hdr = (struct mwifiex_ie_types_data *) curr; tlv_len = le16_to_cpu(tlv_hdr->header.len); if (resp_len < tlv_len + sizeof(tlv_hdr->header)) break; switch (le16_to_cpu(tlv_hdr->header.type)) { case TLV_TYPE_WMMQSTATUS: tlv_wmm_qstatus = (struct mwifiex_ie_types_wmm_queue_status *) tlv_hdr; mwifiex_dbg(priv->adapter, CMD, "info: CMD_RESP: WMM_GET_STATUS:\t" "QSTATUS TLV: %d, %d, %d\n", tlv_wmm_qstatus->queue_index, tlv_wmm_qstatus->flow_required, tlv_wmm_qstatus->disabled); ac_status = &priv->wmm.ac_status[tlv_wmm_qstatus-> queue_index]; ac_status->disabled = tlv_wmm_qstatus->disabled; ac_status->flow_required = tlv_wmm_qstatus->flow_required; ac_status->flow_created = tlv_wmm_qstatus->flow_created; break; case WLAN_EID_VENDOR_SPECIFIC: /* * Point the regular IEEE IE 2 bytes into the Marvell IE * and setup the IEEE IE type and length byte fields */ wmm_param_ie = (struct ieee_types_wmm_parameter *) (curr + 2); wmm_param_ie->vend_hdr.len = (u8) tlv_len; wmm_param_ie->vend_hdr.element_id = WLAN_EID_VENDOR_SPECIFIC; mwifiex_dbg(priv->adapter, CMD, "info: CMD_RESP: WMM_GET_STATUS:\t" "WMM Parameter Set Count: %d\n", wmm_param_ie->qos_info_bitmap & mask); memcpy((u8 *) &priv->curr_bss_params.bss_descriptor. wmm_ie, wmm_param_ie, wmm_param_ie->vend_hdr.len + 2); break; default: valid = false; break; } curr += (tlv_len + sizeof(tlv_hdr->header)); resp_len -= (tlv_len + sizeof(tlv_hdr->header)); } mwifiex_wmm_setup_queue_priorities(priv, wmm_param_ie); mwifiex_wmm_setup_ac_downgrade(priv); return 0; } /* * Callback handler from the command module to allow insertion of a WMM TLV. * * If the BSS we are associating to supports WMM, this function adds the * required WMM Information IE to the association request command buffer in * the form of a Marvell extended IEEE IE. */ u32 mwifiex_wmm_process_association_req(struct mwifiex_private *priv, u8 **assoc_buf, struct ieee_types_wmm_parameter *wmm_ie, struct ieee80211_ht_cap *ht_cap) { struct mwifiex_ie_types_wmm_param_set *wmm_tlv; u32 ret_len = 0; /* Null checks */ if (!assoc_buf) return 0; if (!(*assoc_buf)) return 0; if (!wmm_ie) return 0; mwifiex_dbg(priv->adapter, INFO, "info: WMM: process assoc req: bss->wmm_ie=%#x\n", wmm_ie->vend_hdr.element_id); if ((priv->wmm_required || (ht_cap && (priv->adapter->config_bands & BAND_GN || priv->adapter->config_bands & BAND_AN))) && wmm_ie->vend_hdr.element_id == WLAN_EID_VENDOR_SPECIFIC) { wmm_tlv = (struct mwifiex_ie_types_wmm_param_set *) *assoc_buf; wmm_tlv->header.type = cpu_to_le16((u16) wmm_info_ie[0]); wmm_tlv->header.len = cpu_to_le16((u16) wmm_info_ie[1]); memcpy(wmm_tlv->wmm_ie, &wmm_info_ie[2], le16_to_cpu(wmm_tlv->header.len)); if (wmm_ie->qos_info_bitmap & IEEE80211_WMM_IE_AP_QOSINFO_UAPSD) memcpy((u8 *) (wmm_tlv->wmm_ie + le16_to_cpu(wmm_tlv->header.len) - sizeof(priv->wmm_qosinfo)), &priv->wmm_qosinfo, sizeof(priv->wmm_qosinfo)); ret_len = sizeof(wmm_tlv->header) + le16_to_cpu(wmm_tlv->header.len); *assoc_buf += ret_len; } return ret_len; } /* * This function computes the time delay in the driver queues for a * given packet. * * When the packet is received at the OS/Driver interface, the current * time is set in the packet structure. The difference between the present * time and that received time is computed in this function and limited * based on pre-compiled limits in the driver. */ u8 mwifiex_wmm_compute_drv_pkt_delay(struct mwifiex_private *priv, const struct sk_buff *skb) { u32 queue_delay = ktime_to_ms(net_timedelta(skb->tstamp)); u8 ret_val; /* * Queue delay is passed as a uint8 in units of 2ms (ms shifted * by 1). Min value (other than 0) is therefore 2ms, max is 510ms. * * Pass max value if queue_delay is beyond the uint8 range */ ret_val = (u8) (min(queue_delay, priv->wmm.drv_pkt_delay_max) >> 1); mwifiex_dbg(priv->adapter, DATA, "data: WMM: Pkt Delay: %d ms,\t" "%d ms sent to FW\n", queue_delay, ret_val); return ret_val; } /* * This function retrieves the highest priority RA list table pointer. */ static struct mwifiex_ra_list_tbl * mwifiex_wmm_get_highest_priolist_ptr(struct mwifiex_adapter *adapter, struct mwifiex_private **priv, int *tid) { struct mwifiex_private *priv_tmp; struct mwifiex_ra_list_tbl *ptr; struct mwifiex_tid_tbl *tid_ptr; atomic_t *hqp; int i, j; /* check the BSS with highest priority first */ for (j = adapter->priv_num - 1; j >= 0; --j) { /* iterate over BSS with the equal priority */ list_for_each_entry(adapter->bss_prio_tbl[j].bss_prio_cur, &adapter->bss_prio_tbl[j].bss_prio_head, list) { try_again: priv_tmp = adapter->bss_prio_tbl[j].bss_prio_cur->priv; if (((priv_tmp->bss_mode != NL80211_IFTYPE_ADHOC) && !priv_tmp->port_open) || (atomic_read(&priv_tmp->wmm.tx_pkts_queued) == 0)) continue; if (adapter->if_ops.is_port_ready && !adapter->if_ops.is_port_ready(priv_tmp)) continue; /* iterate over the WMM queues of the BSS */ hqp = &priv_tmp->wmm.highest_queued_prio; for (i = atomic_read(hqp); i >= LOW_PRIO_TID; --i) { spin_lock_bh(&priv_tmp->wmm.ra_list_spinlock); tid_ptr = &(priv_tmp)->wmm. tid_tbl_ptr[tos_to_tid[i]]; /* iterate over receiver addresses */ list_for_each_entry(ptr, &tid_ptr->ra_list, list) { if (!ptr->tx_paused && !skb_queue_empty(&ptr->skb_head)) /* holds both locks */ goto found; } spin_unlock_bh(&priv_tmp->wmm.ra_list_spinlock); } if (atomic_read(&priv_tmp->wmm.tx_pkts_queued) != 0) { atomic_set(&priv_tmp->wmm.highest_queued_prio, HIGH_PRIO_TID); /* Iterate current private once more, since * there still exist packets in data queue */ goto try_again; } else atomic_set(&priv_tmp->wmm.highest_queued_prio, NO_PKT_PRIO_TID); } } return NULL; found: /* holds ra_list_spinlock */ if (atomic_read(hqp) > i) atomic_set(hqp, i); spin_unlock_bh(&priv_tmp->wmm.ra_list_spinlock); *priv = priv_tmp; *tid = tos_to_tid[i]; return ptr; } /* This functions rotates ra and bss lists so packets are picked round robin. * * After a packet is successfully transmitted, rotate the ra list, so the ra * next to the one transmitted, will come first in the list. This way we pick * the ra' in a round robin fashion. Same applies to bss nodes of equal * priority. * * Function also increments wmm.packets_out counter. */ void mwifiex_rotate_priolists(struct mwifiex_private *priv, struct mwifiex_ra_list_tbl *ra, int tid) { struct mwifiex_adapter *adapter = priv->adapter; struct mwifiex_bss_prio_tbl *tbl = adapter->bss_prio_tbl; struct mwifiex_tid_tbl *tid_ptr = &priv->wmm.tid_tbl_ptr[tid]; spin_lock_bh(&tbl[priv->bss_priority].bss_prio_lock); /* * dirty trick: we remove 'head' temporarily and reinsert it after * curr bss node. imagine list to stay fixed while head is moved */ list_move(&tbl[priv->bss_priority].bss_prio_head, &tbl[priv->bss_priority].bss_prio_cur->list); spin_unlock_bh(&tbl[priv->bss_priority].bss_prio_lock); spin_lock_bh(&priv->wmm.ra_list_spinlock); if (mwifiex_is_ralist_valid(priv, ra, tid)) { priv->wmm.packets_out[tid]++; /* same as above */ list_move(&tid_ptr->ra_list, &ra->list); } spin_unlock_bh(&priv->wmm.ra_list_spinlock); } /* * This function checks if 11n aggregation is possible. */ static int mwifiex_is_11n_aggragation_possible(struct mwifiex_private *priv, struct mwifiex_ra_list_tbl *ptr, int max_buf_size) { int count = 0, total_size = 0; struct sk_buff *skb, *tmp; int max_amsdu_size; if (priv->bss_role == MWIFIEX_BSS_ROLE_UAP && priv->ap_11n_enabled && ptr->is_11n_enabled) max_amsdu_size = min_t(int, ptr->max_amsdu, max_buf_size); else max_amsdu_size = max_buf_size; skb_queue_walk_safe(&ptr->skb_head, skb, tmp) { total_size += skb->len; if (total_size >= max_amsdu_size) break; if (++count >= MIN_NUM_AMSDU) return true; } return false; } /* * This function sends a single packet to firmware for transmission. */ static void mwifiex_send_single_packet(struct mwifiex_private *priv, struct mwifiex_ra_list_tbl *ptr, int ptr_index) __releases(&priv->wmm.ra_list_spinlock) { struct sk_buff *skb, *skb_next; struct mwifiex_tx_param tx_param; struct mwifiex_adapter *adapter = priv->adapter; struct mwifiex_txinfo *tx_info; if (skb_queue_empty(&ptr->skb_head)) { spin_unlock_bh(&priv->wmm.ra_list_spinlock); mwifiex_dbg(adapter, DATA, "data: nothing to send\n"); return; } skb = skb_dequeue(&ptr->skb_head); tx_info = MWIFIEX_SKB_TXCB(skb); mwifiex_dbg(adapter, DATA, "data: dequeuing the packet %p %p\n", ptr, skb); ptr->total_pkt_count--; if (!skb_queue_empty(&ptr->skb_head)) skb_next = skb_peek(&ptr->skb_head); else skb_next = NULL; spin_unlock_bh(&priv->wmm.ra_list_spinlock); tx_param.next_pkt_len = ((skb_next) ? skb_next->len + sizeof(struct txpd) : 0); if (mwifiex_process_tx(priv, skb, &tx_param) == -EBUSY) { /* Queue the packet back at the head */ spin_lock_bh(&priv->wmm.ra_list_spinlock); if (!mwifiex_is_ralist_valid(priv, ptr, ptr_index)) { spin_unlock_bh(&priv->wmm.ra_list_spinlock); mwifiex_write_data_complete(adapter, skb, 0, -1); return; } skb_queue_tail(&ptr->skb_head, skb); ptr->total_pkt_count++; ptr->ba_pkt_count++; tx_info->flags |= MWIFIEX_BUF_FLAG_REQUEUED_PKT; spin_unlock_bh(&priv->wmm.ra_list_spinlock); } else { mwifiex_rotate_priolists(priv, ptr, ptr_index); atomic_dec(&priv->wmm.tx_pkts_queued); } } /* * This function checks if the first packet in the given RA list * is already processed or not. */ static int mwifiex_is_ptr_processed(struct mwifiex_private *priv, struct mwifiex_ra_list_tbl *ptr) { struct sk_buff *skb; struct mwifiex_txinfo *tx_info; if (skb_queue_empty(&ptr->skb_head)) return false; skb = skb_peek(&ptr->skb_head); tx_info = MWIFIEX_SKB_TXCB(skb); if (tx_info->flags & MWIFIEX_BUF_FLAG_REQUEUED_PKT) return true; return false; } /* * This function sends a single processed packet to firmware for * transmission. */ static void mwifiex_send_processed_packet(struct mwifiex_private *priv, struct mwifiex_ra_list_tbl *ptr, int ptr_index) __releases(&priv->wmm.ra_list_spinlock) { struct mwifiex_tx_param tx_param; struct mwifiex_adapter *adapter = priv->adapter; int ret = -1; struct sk_buff *skb, *skb_next; struct mwifiex_txinfo *tx_info; if (skb_queue_empty(&ptr->skb_head)) { spin_unlock_bh(&priv->wmm.ra_list_spinlock); return; } skb = skb_dequeue(&ptr->skb_head); if (adapter->data_sent || adapter->tx_lock_flag) { ptr->total_pkt_count--; spin_unlock_bh(&priv->wmm.ra_list_spinlock); skb_queue_tail(&adapter->tx_data_q, skb); atomic_dec(&priv->wmm.tx_pkts_queued); atomic_inc(&adapter->tx_queued); return; } if (!skb_queue_empty(&ptr->skb_head)) skb_next = skb_peek(&ptr->skb_head); else skb_next = NULL; tx_info = MWIFIEX_SKB_TXCB(skb); spin_unlock_bh(&priv->wmm.ra_list_spinlock); tx_param.next_pkt_len = ((skb_next) ? skb_next->len + sizeof(struct txpd) : 0); if (adapter->iface_type == MWIFIEX_USB) { ret = adapter->if_ops.host_to_card(adapter, priv->usb_port, skb, &tx_param); } else { ret = adapter->if_ops.host_to_card(adapter, MWIFIEX_TYPE_DATA, skb, &tx_param); } switch (ret) { case -EBUSY: mwifiex_dbg(adapter, ERROR, "data: -EBUSY is returned\n"); spin_lock_bh(&priv->wmm.ra_list_spinlock); if (!mwifiex_is_ralist_valid(priv, ptr, ptr_index)) { spin_unlock_bh(&priv->wmm.ra_list_spinlock); mwifiex_write_data_complete(adapter, skb, 0, -1); return; } skb_queue_tail(&ptr->skb_head, skb); tx_info->flags |= MWIFIEX_BUF_FLAG_REQUEUED_PKT; spin_unlock_bh(&priv->wmm.ra_list_spinlock); break; case -1: mwifiex_dbg(adapter, ERROR, "host_to_card failed: %#x\n", ret); adapter->dbg.num_tx_host_to_card_failure++; mwifiex_write_data_complete(adapter, skb, 0, ret); break; case -EINPROGRESS: break; case 0: mwifiex_write_data_complete(adapter, skb, 0, ret); default: break; } if (ret != -EBUSY) { mwifiex_rotate_priolists(priv, ptr, ptr_index); atomic_dec(&priv->wmm.tx_pkts_queued); spin_lock_bh(&priv->wmm.ra_list_spinlock); ptr->total_pkt_count--; spin_unlock_bh(&priv->wmm.ra_list_spinlock); } } /* * This function dequeues a packet from the highest priority list * and transmits it. */ static int mwifiex_dequeue_tx_packet(struct mwifiex_adapter *adapter) { struct mwifiex_ra_list_tbl *ptr; struct mwifiex_private *priv = NULL; int ptr_index = 0; u8 ra[ETH_ALEN]; int tid_del = 0, tid = 0; ptr = mwifiex_wmm_get_highest_priolist_ptr(adapter, &priv, &ptr_index); if (!ptr) return -1; tid = mwifiex_get_tid(ptr); mwifiex_dbg(adapter, DATA, "data: tid=%d\n", tid); spin_lock_bh(&priv->wmm.ra_list_spinlock); if (!mwifiex_is_ralist_valid(priv, ptr, ptr_index)) { spin_unlock_bh(&priv->wmm.ra_list_spinlock); return -1; } if (mwifiex_is_ptr_processed(priv, ptr)) { mwifiex_send_processed_packet(priv, ptr, ptr_index); /* ra_list_spinlock has been freed in mwifiex_send_processed_packet() */ return 0; } if (!ptr->is_11n_enabled || ptr->ba_status || priv->wps.session_enable) { if (ptr->is_11n_enabled && ptr->ba_status && ptr->amsdu_in_ampdu && mwifiex_is_amsdu_allowed(priv, tid) && mwifiex_is_11n_aggragation_possible(priv, ptr, adapter->tx_buf_size)) mwifiex_11n_aggregate_pkt(priv, ptr, ptr_index); /* ra_list_spinlock has been freed in * mwifiex_11n_aggregate_pkt() */ else mwifiex_send_single_packet(priv, ptr, ptr_index); /* ra_list_spinlock has been freed in * mwifiex_send_single_packet() */ } else { if (mwifiex_is_ampdu_allowed(priv, ptr, tid) && ptr->ba_pkt_count > ptr->ba_packet_thr) { if (mwifiex_space_avail_for_new_ba_stream(adapter)) { mwifiex_create_ba_tbl(priv, ptr->ra, tid, BA_SETUP_INPROGRESS); mwifiex_send_addba(priv, tid, ptr->ra); } else if (mwifiex_find_stream_to_delete (priv, tid, &tid_del, ra)) { mwifiex_create_ba_tbl(priv, ptr->ra, tid, BA_SETUP_INPROGRESS); mwifiex_send_delba(priv, tid_del, ra, 1); } } if (mwifiex_is_amsdu_allowed(priv, tid) && mwifiex_is_11n_aggragation_possible(priv, ptr, adapter->tx_buf_size)) mwifiex_11n_aggregate_pkt(priv, ptr, ptr_index); /* ra_list_spinlock has been freed in mwifiex_11n_aggregate_pkt() */ else mwifiex_send_single_packet(priv, ptr, ptr_index); /* ra_list_spinlock has been freed in mwifiex_send_single_packet() */ } return 0; } void mwifiex_process_bypass_tx(struct mwifiex_adapter *adapter) { struct mwifiex_tx_param tx_param; struct sk_buff *skb; struct mwifiex_txinfo *tx_info; struct mwifiex_private *priv; int i; if (adapter->data_sent || adapter->tx_lock_flag) return; for (i = 0; i < adapter->priv_num; ++i) { priv = adapter->priv[i]; if (!priv) continue; if (adapter->if_ops.is_port_ready && !adapter->if_ops.is_port_ready(priv)) continue; if (skb_queue_empty(&priv->bypass_txq)) continue; skb = skb_dequeue(&priv->bypass_txq); tx_info = MWIFIEX_SKB_TXCB(skb); /* no aggregation for bypass packets */ tx_param.next_pkt_len = 0; if (mwifiex_process_tx(priv, skb, &tx_param) == -EBUSY) { skb_queue_head(&priv->bypass_txq, skb); tx_info->flags |= MWIFIEX_BUF_FLAG_REQUEUED_PKT; } else { atomic_dec(&adapter->bypass_tx_pending); } } } /* * This function transmits the highest priority packet awaiting in the * WMM Queues. */ void mwifiex_wmm_process_tx(struct mwifiex_adapter *adapter) { do { if (mwifiex_dequeue_tx_packet(adapter)) break; if (adapter->iface_type != MWIFIEX_SDIO) { if (adapter->data_sent || adapter->tx_lock_flag) break; } else { if (atomic_read(&adapter->tx_queued) >= MWIFIEX_MAX_PKTS_TXQ) break; } } while (!mwifiex_wmm_lists_empty(adapter)); }
null
/* * Marvell Wireless LAN device driver: WMM * * Copyright (C) 2011-2014, Marvell International Ltd. * * This software file (the "File") is distributed by Marvell International * Ltd. under the terms of the GNU General Public License Version 2, June 1991 * (the "License"). You may use, redistribute and/or modify this File in * accordance with the terms and conditions of the License, a copy of which * is available by writing to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the * worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE * IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE * ARE EXPRESSLY DISCLAIMED. The License provides additional details about * this warranty disclaimer. */ #include "decl.h" #include "ioctl.h" #include "util.h" #include "fw.h" #include "main.h" #include "wmm.h" #include "11n.h" /* Maximum value FW can accept for driver delay in packet transmission */ #define DRV_PKT_DELAY_TO_FW_MAX 512 #define WMM_QUEUED_PACKET_LOWER_LIMIT 180 #define WMM_QUEUED_PACKET_UPPER_LIMIT 200 /* Offset for TOS field in the IP header */ #define IPTOS_OFFSET 5 static bool disable_tx_amsdu; module_param(disable_tx_amsdu, bool, 0644); /* WMM information IE */ static const u8 wmm_info_ie[] = { WLAN_EID_VENDOR_SPECIFIC, 0x07, 0x00, 0x50, 0xf2, 0x02, 0x00, 0x01, 0x00 }; static const u8 wmm_aci_to_qidx_map[] = { WMM_AC_BE, WMM_AC_BK, WMM_AC_VI, WMM_AC_VO }; static u8 tos_to_tid[] = { /* TID DSCP_P2 DSCP_P1 DSCP_P0 WMM_AC */ 0x01, /* 0 1 0 AC_BK */ 0x02, /* 0 0 0 AC_BK */ 0x00, /* 0 0 1 AC_BE */ 0x03, /* 0 1 1 AC_BE */ 0x04, /* 1 0 0 AC_VI */ 0x05, /* 1 0 1 AC_VI */ 0x06, /* 1 1 0 AC_VO */ 0x07 /* 1 1 1 AC_VO */ }; static u8 ac_to_tid[4][2] = { {1, 2}, {0, 3}, {4, 5}, {6, 7} }; /* * This function debug prints the priority parameters for a WMM AC. */ static void mwifiex_wmm_ac_debug_print(const struct ieee_types_wmm_ac_parameters *ac_param) { const char *ac_str[] = { "BK", "BE", "VI", "VO" }; pr_debug("info: WMM AC_%s: ACI=%d, ACM=%d, Aifsn=%d, " "EcwMin=%d, EcwMax=%d, TxopLimit=%d\n", ac_str[wmm_aci_to_qidx_map[(ac_param->aci_aifsn_bitmap & MWIFIEX_ACI) >> 5]], (ac_param->aci_aifsn_bitmap & MWIFIEX_ACI) >> 5, (ac_param->aci_aifsn_bitmap & MWIFIEX_ACM) >> 4, ac_param->aci_aifsn_bitmap & MWIFIEX_AIFSN, ac_param->ecw_bitmap & MWIFIEX_ECW_MIN, (ac_param->ecw_bitmap & MWIFIEX_ECW_MAX) >> 4, le16_to_cpu(ac_param->tx_op_limit)); } /* * This function allocates a route address list. * * The function also initializes the list with the provided RA. */ static struct mwifiex_ra_list_tbl * mwifiex_wmm_allocate_ralist_node(struct mwifiex_adapter *adapter, const u8 *ra) { struct mwifiex_ra_list_tbl *ra_list; ra_list = kzalloc(sizeof(struct mwifiex_ra_list_tbl), GFP_ATOMIC); if (!ra_list) return NULL; INIT_LIST_HEAD(&ra_list->list); skb_queue_head_init(&ra_list->skb_head); memcpy(ra_list->ra, ra, ETH_ALEN); ra_list->total_pkt_count = 0; mwifiex_dbg(adapter, INFO, "info: allocated ra_list %p\n", ra_list); return ra_list; } /* This function returns random no between 16 and 32 to be used as threshold * for no of packets after which BA setup is initiated. */ static u8 mwifiex_get_random_ba_threshold(void) { u64 ns; /* setup ba_packet_threshold here random number between * [BA_SETUP_PACKET_OFFSET, * BA_SETUP_PACKET_OFFSET+BA_SETUP_MAX_PACKET_THRESHOLD-1] */ ns = ktime_get_ns(); ns += (ns >> 32) + (ns >> 16); return ((u8)ns % BA_SETUP_MAX_PACKET_THRESHOLD) + BA_SETUP_PACKET_OFFSET; } /* * This function allocates and adds a RA list for all TIDs * with the given RA. */ void mwifiex_ralist_add(struct mwifiex_private *priv, const u8 *ra) { int i; struct mwifiex_ra_list_tbl *ra_list; struct mwifiex_adapter *adapter = priv->adapter; struct mwifiex_sta_node *node; for (i = 0; i < MAX_NUM_TID; ++i) { ra_list = mwifiex_wmm_allocate_ralist_node(adapter, ra); mwifiex_dbg(adapter, INFO, "info: created ra_list %p\n", ra_list); if (!ra_list) break; ra_list->is_11n_enabled = 0; ra_list->tdls_link = false; ra_list->ba_status = BA_SETUP_NONE; ra_list->amsdu_in_ampdu = false; if (!mwifiex_queuing_ra_based(priv)) { if (mwifiex_is_tdls_link_setup (mwifiex_get_tdls_link_status(priv, ra))) { ra_list->tdls_link = true; ra_list->is_11n_enabled = mwifiex_tdls_peer_11n_enabled(priv, ra); } else { ra_list->is_11n_enabled = IS_11N_ENABLED(priv); } } else { spin_lock_bh(&priv->sta_list_spinlock); node = mwifiex_get_sta_entry(priv, ra); if (node) ra_list->tx_paused = node->tx_pause; ra_list->is_11n_enabled = mwifiex_is_sta_11n_enabled(priv, node); if (ra_list->is_11n_enabled) ra_list->max_amsdu = node->max_amsdu; spin_unlock_bh(&priv->sta_list_spinlock); } mwifiex_dbg(adapter, DATA, "data: ralist %p: is_11n_enabled=%d\n", ra_list, ra_list->is_11n_enabled); if (ra_list->is_11n_enabled) { ra_list->ba_pkt_count = 0; ra_list->ba_packet_thr = mwifiex_get_random_ba_threshold(); } list_add_tail(&ra_list->list, &priv->wmm.tid_tbl_ptr[i].ra_list); } } /* * This function sets the WMM queue priorities to their default values. */ static void mwifiex_wmm_default_queue_priorities(struct mwifiex_private *priv) { /* Default queue priorities: VO->VI->BE->BK */ priv->wmm.queue_priority[0] = WMM_AC_VO; priv->wmm.queue_priority[1] = WMM_AC_VI; priv->wmm.queue_priority[2] = WMM_AC_BE; priv->wmm.queue_priority[3] = WMM_AC_BK; } /* * This function map ACs to TIDs. */ static void mwifiex_wmm_queue_priorities_tid(struct mwifiex_private *priv) { struct mwifiex_wmm_desc *wmm = &priv->wmm; u8 *queue_priority = wmm->queue_priority; int i; for (i = 0; i < 4; ++i) { tos_to_tid[7 - (i * 2)] = ac_to_tid[queue_priority[i]][1]; tos_to_tid[6 - (i * 2)] = ac_to_tid[queue_priority[i]][0]; } for (i = 0; i < MAX_NUM_TID; ++i) priv->tos_to_tid_inv[tos_to_tid[i]] = (u8)i; atomic_set(&wmm->highest_queued_prio, HIGH_PRIO_TID); } /* * This function initializes WMM priority queues. */ void mwifiex_wmm_setup_queue_priorities(struct mwifiex_private *priv, struct ieee_types_wmm_parameter *wmm_ie) { u16 cw_min, avg_back_off, tmp[4]; u32 i, j, num_ac; u8 ac_idx; if (!wmm_ie || !priv->wmm_enabled) { /* WMM is not enabled, just set the defaults and return */ mwifiex_wmm_default_queue_priorities(priv); return; } mwifiex_dbg(priv->adapter, INFO, "info: WMM Parameter IE: version=%d,\t" "qos_info Parameter Set Count=%d, Reserved=%#x\n", wmm_ie->version, wmm_ie->qos_info_bitmap & IEEE80211_WMM_IE_AP_QOSINFO_PARAM_SET_CNT_MASK, wmm_ie->reserved); for (num_ac = 0; num_ac < ARRAY_SIZE(wmm_ie->ac_params); num_ac++) { u8 ecw = wmm_ie->ac_params[num_ac].ecw_bitmap; u8 aci_aifsn = wmm_ie->ac_params[num_ac].aci_aifsn_bitmap; cw_min = (1 << (ecw & MWIFIEX_ECW_MIN)) - 1; avg_back_off = (cw_min >> 1) + (aci_aifsn & MWIFIEX_AIFSN); ac_idx = wmm_aci_to_qidx_map[(aci_aifsn & MWIFIEX_ACI) >> 5]; priv->wmm.queue_priority[ac_idx] = ac_idx; tmp[ac_idx] = avg_back_off; mwifiex_dbg(priv->adapter, INFO, "info: WMM: CWmax=%d CWmin=%d Avg Back-off=%d\n", (1 << ((ecw & MWIFIEX_ECW_MAX) >> 4)) - 1, cw_min, avg_back_off); mwifiex_wmm_ac_debug_print(&wmm_ie->ac_params[num_ac]); } /* Bubble sort */ for (i = 0; i < num_ac; i++) { for (j = 1; j < num_ac - i; j++) { if (tmp[j - 1] > tmp[j]) { swap(tmp[j - 1], tmp[j]); swap(priv->wmm.queue_priority[j - 1], priv->wmm.queue_priority[j]); } else if (tmp[j - 1] == tmp[j]) { if (priv->wmm.queue_priority[j - 1] < priv->wmm.queue_priority[j]) swap(priv->wmm.queue_priority[j - 1], priv->wmm.queue_priority[j]); } } } mwifiex_wmm_queue_priorities_tid(priv); } /* * This function evaluates whether or not an AC is to be downgraded. * * In case the AC is not enabled, the highest AC is returned that is * enabled and does not require admission control. */ static enum mwifiex_wmm_ac_e mwifiex_wmm_eval_downgrade_ac(struct mwifiex_private *priv, enum mwifiex_wmm_ac_e eval_ac) { int down_ac; enum mwifiex_wmm_ac_e ret_ac; struct mwifiex_wmm_ac_status *ac_status; ac_status = &priv->wmm.ac_status[eval_ac]; if (!ac_status->disabled) /* Okay to use this AC, its enabled */ return eval_ac; /* Setup a default return value of the lowest priority */ ret_ac = WMM_AC_BK; /* * Find the highest AC that is enabled and does not require * admission control. The spec disallows downgrading to an AC, * which is enabled due to a completed admission control. * Unadmitted traffic is not to be sent on an AC with admitted * traffic. */ for (down_ac = WMM_AC_BK; down_ac < eval_ac; down_ac++) { ac_status = &priv->wmm.ac_status[down_ac]; if (!ac_status->disabled && !ac_status->flow_required) /* AC is enabled and does not require admission control */ ret_ac = (enum mwifiex_wmm_ac_e) down_ac; } return ret_ac; } /* * This function downgrades WMM priority queue. */ void mwifiex_wmm_setup_ac_downgrade(struct mwifiex_private *priv) { int ac_val; mwifiex_dbg(priv->adapter, INFO, "info: WMM: AC Priorities:\t" "BK(0), BE(1), VI(2), VO(3)\n"); if (!priv->wmm_enabled) { /* WMM is not enabled, default priorities */ for (ac_val = WMM_AC_BK; ac_val <= WMM_AC_VO; ac_val++) priv->wmm.ac_down_graded_vals[ac_val] = (enum mwifiex_wmm_ac_e) ac_val; } else { for (ac_val = WMM_AC_BK; ac_val <= WMM_AC_VO; ac_val++) { priv->wmm.ac_down_graded_vals[ac_val] = mwifiex_wmm_eval_downgrade_ac(priv, (enum mwifiex_wmm_ac_e) ac_val); mwifiex_dbg(priv->adapter, INFO, "info: WMM: AC PRIO %d maps to %d\n", ac_val, priv->wmm.ac_down_graded_vals[ac_val]); } } } /* * This function converts the IP TOS field to an WMM AC * Queue assignment. */ static enum mwifiex_wmm_ac_e mwifiex_wmm_convert_tos_to_ac(struct mwifiex_adapter *adapter, u32 tos) { /* Map of TOS UP values to WMM AC */ static const enum mwifiex_wmm_ac_e tos_to_ac[] = { WMM_AC_BE, WMM_AC_BK, WMM_AC_BK, WMM_AC_BE, WMM_AC_VI, WMM_AC_VI, WMM_AC_VO, WMM_AC_VO }; if (tos >= ARRAY_SIZE(tos_to_ac)) return WMM_AC_BE; return tos_to_ac[tos]; } /* * This function evaluates a given TID and downgrades it to a lower * TID if the WMM Parameter IE received from the AP indicates that the * AP is disabled (due to call admission control (ACM bit). Mapping * of TID to AC is taken care of internally. */ u8 mwifiex_wmm_downgrade_tid(struct mwifiex_private *priv, u32 tid) { enum mwifiex_wmm_ac_e ac, ac_down; u8 new_tid; ac = mwifiex_wmm_convert_tos_to_ac(priv->adapter, tid); ac_down = priv->wmm.ac_down_graded_vals[ac]; /* Send the index to tid array, picking from the array will be * taken care by dequeuing function */ new_tid = ac_to_tid[ac_down][tid % 2]; return new_tid; } /* * This function initializes the WMM state information and the * WMM data path queues. */ void mwifiex_wmm_init(struct mwifiex_adapter *adapter) { int i, j; struct mwifiex_private *priv; for (j = 0; j < adapter->priv_num; ++j) { priv = adapter->priv[j]; if (!priv) continue; for (i = 0; i < MAX_NUM_TID; ++i) { if (!disable_tx_amsdu && adapter->tx_buf_size > MWIFIEX_TX_DATA_BUF_SIZE_2K) priv->aggr_prio_tbl[i].amsdu = priv->tos_to_tid_inv[i]; else priv->aggr_prio_tbl[i].amsdu = BA_STREAM_NOT_ALLOWED; priv->aggr_prio_tbl[i].ampdu_ap = priv->tos_to_tid_inv[i]; priv->aggr_prio_tbl[i].ampdu_user = priv->tos_to_tid_inv[i]; } priv->aggr_prio_tbl[6].amsdu = priv->aggr_prio_tbl[6].ampdu_ap = priv->aggr_prio_tbl[6].ampdu_user = BA_STREAM_NOT_ALLOWED; priv->aggr_prio_tbl[7].amsdu = priv->aggr_prio_tbl[7].ampdu_ap = priv->aggr_prio_tbl[7].ampdu_user = BA_STREAM_NOT_ALLOWED; mwifiex_set_ba_params(priv); mwifiex_reset_11n_rx_seq_num(priv); priv->wmm.drv_pkt_delay_max = MWIFIEX_WMM_DRV_DELAY_MAX; atomic_set(&priv->wmm.tx_pkts_queued, 0); atomic_set(&priv->wmm.highest_queued_prio, HIGH_PRIO_TID); } } int mwifiex_bypass_txlist_empty(struct mwifiex_adapter *adapter) { struct mwifiex_private *priv; int i; for (i = 0; i < adapter->priv_num; i++) { priv = adapter->priv[i]; if (!priv) continue; if (adapter->if_ops.is_port_ready && !adapter->if_ops.is_port_ready(priv)) continue; if (!skb_queue_empty(&priv->bypass_txq)) return false; } return true; } /* * This function checks if WMM Tx queue is empty. */ int mwifiex_wmm_lists_empty(struct mwifiex_adapter *adapter) { int i; struct mwifiex_private *priv; for (i = 0; i < adapter->priv_num; ++i) { priv = adapter->priv[i]; if (!priv) continue; if (!priv->port_open && (priv->bss_mode != NL80211_IFTYPE_ADHOC)) continue; if (adapter->if_ops.is_port_ready && !adapter->if_ops.is_port_ready(priv)) continue; if (atomic_read(&priv->wmm.tx_pkts_queued)) return false; } return true; } /* * This function deletes all packets in an RA list node. * * The packet sent completion callback handler are called with * status failure, after they are dequeued to ensure proper * cleanup. The RA list node itself is freed at the end. */ static void mwifiex_wmm_del_pkts_in_ralist_node(struct mwifiex_private *priv, struct mwifiex_ra_list_tbl *ra_list) { struct mwifiex_adapter *adapter = priv->adapter; struct sk_buff *skb, *tmp; skb_queue_walk_safe(&ra_list->skb_head, skb, tmp) { skb_unlink(skb, &ra_list->skb_head); mwifiex_write_data_complete(adapter, skb, 0, -1); } } /* * This function deletes all packets in an RA list. * * Each nodes in the RA list are freed individually first, and then * the RA list itself is freed. */ static void mwifiex_wmm_del_pkts_in_ralist(struct mwifiex_private *priv, struct list_head *ra_list_head) { struct mwifiex_ra_list_tbl *ra_list; list_for_each_entry(ra_list, ra_list_head, list) mwifiex_wmm_del_pkts_in_ralist_node(priv, ra_list); } /* * This function deletes all packets in all RA lists. */ static void mwifiex_wmm_cleanup_queues(struct mwifiex_private *priv) { int i; for (i = 0; i < MAX_NUM_TID; i++) mwifiex_wmm_del_pkts_in_ralist(priv, &priv->wmm.tid_tbl_ptr[i]. ra_list); atomic_set(&priv->wmm.tx_pkts_queued, 0); atomic_set(&priv->wmm.highest_queued_prio, HIGH_PRIO_TID); } /* * This function deletes all route addresses from all RA lists. */ static void mwifiex_wmm_delete_all_ralist(struct mwifiex_private *priv) { struct mwifiex_ra_list_tbl *ra_list, *tmp_node; int i; for (i = 0; i < MAX_NUM_TID; ++i) { mwifiex_dbg(priv->adapter, INFO, "info: ra_list: freeing buf for tid %d\n", i); list_for_each_entry_safe(ra_list, tmp_node, &priv->wmm.tid_tbl_ptr[i].ra_list, list) { list_del(&ra_list->list); kfree(ra_list); } INIT_LIST_HEAD(&priv->wmm.tid_tbl_ptr[i].ra_list); } } static int mwifiex_free_ack_frame(int id, void *p, void *data) { pr_warn("Have pending ack frames!\n"); kfree_skb(p); return 0; } /* * This function cleans up the Tx and Rx queues. * * Cleanup includes - * - All packets in RA lists * - All entries in Rx reorder table * - All entries in Tx BA stream table * - MPA buffer (if required) * - All RA lists */ void mwifiex_clean_txrx(struct mwifiex_private *priv) { struct sk_buff *skb, *tmp; mwifiex_11n_cleanup_reorder_tbl(priv); spin_lock_bh(&priv->wmm.ra_list_spinlock); mwifiex_wmm_cleanup_queues(priv); mwifiex_11n_delete_all_tx_ba_stream_tbl(priv); if (priv->adapter->if_ops.cleanup_mpa_buf) priv->adapter->if_ops.cleanup_mpa_buf(priv->adapter); mwifiex_wmm_delete_all_ralist(priv); memcpy(tos_to_tid, ac_to_tid, sizeof(tos_to_tid)); if (priv->adapter->if_ops.clean_pcie_ring && !test_bit(MWIFIEX_SURPRISE_REMOVED, &priv->adapter->work_flags)) priv->adapter->if_ops.clean_pcie_ring(priv->adapter); spin_unlock_bh(&priv->wmm.ra_list_spinlock); skb_queue_walk_safe(&priv->tdls_txq, skb, tmp) { skb_unlink(skb, &priv->tdls_txq); mwifiex_write_data_complete(priv->adapter, skb, 0, -1); } skb_queue_walk_safe(&priv->bypass_txq, skb, tmp) { skb_unlink(skb, &priv->bypass_txq); mwifiex_write_data_complete(priv->adapter, skb, 0, -1); } atomic_set(&priv->adapter->bypass_tx_pending, 0); idr_for_each(&priv->ack_status_frames, mwifiex_free_ack_frame, NULL); idr_destroy(&priv->ack_status_frames); } /* * This function retrieves a particular RA list node, matching with the * given TID and RA address. */ struct mwifiex_ra_list_tbl * mwifiex_wmm_get_ralist_node(struct mwifiex_private *priv, u8 tid, const u8 *ra_addr) { struct mwifiex_ra_list_tbl *ra_list; list_for_each_entry(ra_list, &priv->wmm.tid_tbl_ptr[tid].ra_list, list) { if (!memcmp(ra_list->ra, ra_addr, ETH_ALEN)) return ra_list; } return NULL; } void mwifiex_update_ralist_tx_pause(struct mwifiex_private *priv, u8 *mac, u8 tx_pause) { struct mwifiex_ra_list_tbl *ra_list; u32 pkt_cnt = 0, tx_pkts_queued; int i; spin_lock_bh(&priv->wmm.ra_list_spinlock); for (i = 0; i < MAX_NUM_TID; ++i) { ra_list = mwifiex_wmm_get_ralist_node(priv, i, mac); if (ra_list && ra_list->tx_paused != tx_pause) { pkt_cnt += ra_list->total_pkt_count; ra_list->tx_paused = tx_pause; if (tx_pause) priv->wmm.pkts_paused[i] += ra_list->total_pkt_count; else priv->wmm.pkts_paused[i] -= ra_list->total_pkt_count; } } if (pkt_cnt) { tx_pkts_queued = atomic_read(&priv->wmm.tx_pkts_queued); if (tx_pause) tx_pkts_queued -= pkt_cnt; else tx_pkts_queued += pkt_cnt; atomic_set(&priv->wmm.tx_pkts_queued, tx_pkts_queued); atomic_set(&priv->wmm.highest_queued_prio, HIGH_PRIO_TID); } spin_unlock_bh(&priv->wmm.ra_list_spinlock); } /* This function updates non-tdls peer ralist tx_pause while * tdls channel switching */ void mwifiex_update_ralist_tx_pause_in_tdls_cs(struct mwifiex_private *priv, u8 *mac, u8 tx_pause) { struct mwifiex_ra_list_tbl *ra_list; u32 pkt_cnt = 0, tx_pkts_queued; int i; spin_lock_bh(&priv->wmm.ra_list_spinlock); for (i = 0; i < MAX_NUM_TID; ++i) { list_for_each_entry(ra_list, &priv->wmm.tid_tbl_ptr[i].ra_list, list) { if (!memcmp(ra_list->ra, mac, ETH_ALEN)) continue; if (ra_list->tx_paused != tx_pause) { pkt_cnt += ra_list->total_pkt_count; ra_list->tx_paused = tx_pause; if (tx_pause) priv->wmm.pkts_paused[i] += ra_list->total_pkt_count; else priv->wmm.pkts_paused[i] -= ra_list->total_pkt_count; } } } if (pkt_cnt) { tx_pkts_queued = atomic_read(&priv->wmm.tx_pkts_queued); if (tx_pause) tx_pkts_queued -= pkt_cnt; else tx_pkts_queued += pkt_cnt; atomic_set(&priv->wmm.tx_pkts_queued, tx_pkts_queued); atomic_set(&priv->wmm.highest_queued_prio, HIGH_PRIO_TID); } spin_unlock_bh(&priv->wmm.ra_list_spinlock); } /* * This function retrieves an RA list node for a given TID and * RA address pair. * * If no such node is found, a new node is added first and then * retrieved. */ struct mwifiex_ra_list_tbl * mwifiex_wmm_get_queue_raptr(struct mwifiex_private *priv, u8 tid, const u8 *ra_addr) { struct mwifiex_ra_list_tbl *ra_list; ra_list = mwifiex_wmm_get_ralist_node(priv, tid, ra_addr); if (ra_list) return ra_list; mwifiex_ralist_add(priv, ra_addr); return mwifiex_wmm_get_ralist_node(priv, tid, ra_addr); } /* * This function deletes RA list nodes for given mac for all TIDs. * Function also decrements TX pending count accordingly. */ void mwifiex_wmm_del_peer_ra_list(struct mwifiex_private *priv, const u8 *ra_addr) { struct mwifiex_ra_list_tbl *ra_list; int i; spin_lock_bh(&priv->wmm.ra_list_spinlock); for (i = 0; i < MAX_NUM_TID; ++i) { ra_list = mwifiex_wmm_get_ralist_node(priv, i, ra_addr); if (!ra_list) continue; mwifiex_wmm_del_pkts_in_ralist_node(priv, ra_list); if (ra_list->tx_paused) priv->wmm.pkts_paused[i] -= ra_list->total_pkt_count; else atomic_sub(ra_list->total_pkt_count, &priv->wmm.tx_pkts_queued); list_del(&ra_list->list); kfree(ra_list); } spin_unlock_bh(&priv->wmm.ra_list_spinlock); } /* * This function checks if a particular RA list node exists in a given TID * table index. */ int mwifiex_is_ralist_valid(struct mwifiex_private *priv, struct mwifiex_ra_list_tbl *ra_list, int ptr_index) { struct mwifiex_ra_list_tbl *rlist; list_for_each_entry(rlist, &priv->wmm.tid_tbl_ptr[ptr_index].ra_list, list) { if (rlist == ra_list) return true; } return false; } /* * This function adds a packet to bypass TX queue. * This is special TX queue for packets which can be sent even when port_open * is false. */ void mwifiex_wmm_add_buf_bypass_txqueue(struct mwifiex_private *priv, struct sk_buff *skb) { skb_queue_tail(&priv->bypass_txq, skb); } /* * This function adds a packet to WMM queue. * * In disconnected state the packet is immediately dropped and the * packet send completion callback is called with status failure. * * Otherwise, the correct RA list node is located and the packet * is queued at the list tail. */ void mwifiex_wmm_add_buf_txqueue(struct mwifiex_private *priv, struct sk_buff *skb) { struct mwifiex_adapter *adapter = priv->adapter; u32 tid; struct mwifiex_ra_list_tbl *ra_list; u8 ra[ETH_ALEN], tid_down; struct list_head list_head; int tdls_status = TDLS_NOT_SETUP; struct ethhdr *eth_hdr = (struct ethhdr *)skb->data; struct mwifiex_txinfo *tx_info = MWIFIEX_SKB_TXCB(skb); memcpy(ra, eth_hdr->h_dest, ETH_ALEN); if (GET_BSS_ROLE(priv) == MWIFIEX_BSS_ROLE_STA && ISSUPP_TDLS_ENABLED(adapter->fw_cap_info)) { if (ntohs(eth_hdr->h_proto) == ETH_P_TDLS) mwifiex_dbg(adapter, DATA, "TDLS setup packet for %pM.\t" "Don't block\n", ra); else if (memcmp(priv->cfg_bssid, ra, ETH_ALEN)) tdls_status = mwifiex_get_tdls_link_status(priv, ra); } if (!priv->media_connected && !mwifiex_is_skb_mgmt_frame(skb)) { mwifiex_dbg(adapter, DATA, "data: drop packet in disconnect\n"); mwifiex_write_data_complete(adapter, skb, 0, -1); return; } tid = skb->priority; spin_lock_bh(&priv->wmm.ra_list_spinlock); tid_down = mwifiex_wmm_downgrade_tid(priv, tid); /* In case of infra as we have already created the list during association we just don't have to call get_queue_raptr, we will have only 1 raptr for a tid in case of infra */ if (!mwifiex_queuing_ra_based(priv) && !mwifiex_is_skb_mgmt_frame(skb)) { switch (tdls_status) { case TDLS_SETUP_COMPLETE: case TDLS_CHAN_SWITCHING: case TDLS_IN_BASE_CHAN: case TDLS_IN_OFF_CHAN: ra_list = mwifiex_wmm_get_queue_raptr(priv, tid_down, ra); tx_info->flags |= MWIFIEX_BUF_FLAG_TDLS_PKT; break; case TDLS_SETUP_INPROGRESS: skb_queue_tail(&priv->tdls_txq, skb); spin_unlock_bh(&priv->wmm.ra_list_spinlock); return; default: list_head = priv->wmm.tid_tbl_ptr[tid_down].ra_list; ra_list = list_first_entry_or_null(&list_head, struct mwifiex_ra_list_tbl, list); break; } } else { memcpy(ra, skb->data, ETH_ALEN); if (ra[0] & 0x01 || mwifiex_is_skb_mgmt_frame(skb)) eth_broadcast_addr(ra); ra_list = mwifiex_wmm_get_queue_raptr(priv, tid_down, ra); } if (!ra_list) { spin_unlock_bh(&priv->wmm.ra_list_spinlock); mwifiex_write_data_complete(adapter, skb, 0, -1); return; } skb_queue_tail(&ra_list->skb_head, skb); ra_list->ba_pkt_count++; ra_list->total_pkt_count++; if (atomic_read(&priv->wmm.highest_queued_prio) < priv->tos_to_tid_inv[tid_down]) atomic_set(&priv->wmm.highest_queued_prio, priv->tos_to_tid_inv[tid_down]); if (ra_list->tx_paused) priv->wmm.pkts_paused[tid_down]++; else atomic_inc(&priv->wmm.tx_pkts_queued); spin_unlock_bh(&priv->wmm.ra_list_spinlock); } /* * This function processes the get WMM status command response from firmware. * * The response may contain multiple TLVs - * - AC Queue status TLVs * - Current WMM Parameter IE TLV * - Admission Control action frame TLVs * * This function parses the TLVs and then calls further specific functions * to process any changes in the queue prioritize or state. */ int mwifiex_ret_wmm_get_status(struct mwifiex_private *priv, const struct host_cmd_ds_command *resp) { u8 *curr = (u8 *) &resp->params.get_wmm_status; uint16_t resp_len = le16_to_cpu(resp->size), tlv_len; int mask = IEEE80211_WMM_IE_AP_QOSINFO_PARAM_SET_CNT_MASK; bool valid = true; struct mwifiex_ie_types_data *tlv_hdr; struct mwifiex_ie_types_wmm_queue_status *tlv_wmm_qstatus; struct ieee_types_wmm_parameter *wmm_param_ie = NULL; struct mwifiex_wmm_ac_status *ac_status; mwifiex_dbg(priv->adapter, INFO, "info: WMM: WMM_GET_STATUS cmdresp received: %d\n", resp_len); while ((resp_len >= sizeof(tlv_hdr->header)) && valid) { tlv_hdr = (struct mwifiex_ie_types_data *) curr; tlv_len = le16_to_cpu(tlv_hdr->header.len); if (resp_len < tlv_len + sizeof(tlv_hdr->header)) break; switch (le16_to_cpu(tlv_hdr->header.type)) { case TLV_TYPE_WMMQSTATUS: tlv_wmm_qstatus = (struct mwifiex_ie_types_wmm_queue_status *) tlv_hdr; mwifiex_dbg(priv->adapter, CMD, "info: CMD_RESP: WMM_GET_STATUS:\t" "QSTATUS TLV: %d, %d, %d\n", tlv_wmm_qstatus->queue_index, tlv_wmm_qstatus->flow_required, tlv_wmm_qstatus->disabled); ac_status = &priv->wmm.ac_status[tlv_wmm_qstatus-> queue_index]; ac_status->disabled = tlv_wmm_qstatus->disabled; ac_status->flow_required = tlv_wmm_qstatus->flow_required; ac_status->flow_created = tlv_wmm_qstatus->flow_created; break; case WLAN_EID_VENDOR_SPECIFIC: /* * Point the regular IEEE IE 2 bytes into the Marvell IE * and setup the IEEE IE type and length byte fields */ wmm_param_ie = (struct ieee_types_wmm_parameter *) (curr + 2); wmm_param_ie->vend_hdr.len = (u8) tlv_len; wmm_param_ie->vend_hdr.element_id = WLAN_EID_VENDOR_SPECIFIC; mwifiex_dbg(priv->adapter, CMD, "info: CMD_RESP: WMM_GET_STATUS:\t" "WMM Parameter Set Count: %d\n", wmm_param_ie->qos_info_bitmap & mask); if (wmm_param_ie->vend_hdr.len + 2 > sizeof(struct ieee_types_wmm_parameter)) break; memcpy((u8 *) &priv->curr_bss_params.bss_descriptor. wmm_ie, wmm_param_ie, wmm_param_ie->vend_hdr.len + 2); break; default: valid = false; break; } curr += (tlv_len + sizeof(tlv_hdr->header)); resp_len -= (tlv_len + sizeof(tlv_hdr->header)); } mwifiex_wmm_setup_queue_priorities(priv, wmm_param_ie); mwifiex_wmm_setup_ac_downgrade(priv); return 0; } /* * Callback handler from the command module to allow insertion of a WMM TLV. * * If the BSS we are associating to supports WMM, this function adds the * required WMM Information IE to the association request command buffer in * the form of a Marvell extended IEEE IE. */ u32 mwifiex_wmm_process_association_req(struct mwifiex_private *priv, u8 **assoc_buf, struct ieee_types_wmm_parameter *wmm_ie, struct ieee80211_ht_cap *ht_cap) { struct mwifiex_ie_types_wmm_param_set *wmm_tlv; u32 ret_len = 0; /* Null checks */ if (!assoc_buf) return 0; if (!(*assoc_buf)) return 0; if (!wmm_ie) return 0; mwifiex_dbg(priv->adapter, INFO, "info: WMM: process assoc req: bss->wmm_ie=%#x\n", wmm_ie->vend_hdr.element_id); if ((priv->wmm_required || (ht_cap && (priv->adapter->config_bands & BAND_GN || priv->adapter->config_bands & BAND_AN))) && wmm_ie->vend_hdr.element_id == WLAN_EID_VENDOR_SPECIFIC) { wmm_tlv = (struct mwifiex_ie_types_wmm_param_set *) *assoc_buf; wmm_tlv->header.type = cpu_to_le16((u16) wmm_info_ie[0]); wmm_tlv->header.len = cpu_to_le16((u16) wmm_info_ie[1]); memcpy(wmm_tlv->wmm_ie, &wmm_info_ie[2], le16_to_cpu(wmm_tlv->header.len)); if (wmm_ie->qos_info_bitmap & IEEE80211_WMM_IE_AP_QOSINFO_UAPSD) memcpy((u8 *) (wmm_tlv->wmm_ie + le16_to_cpu(wmm_tlv->header.len) - sizeof(priv->wmm_qosinfo)), &priv->wmm_qosinfo, sizeof(priv->wmm_qosinfo)); ret_len = sizeof(wmm_tlv->header) + le16_to_cpu(wmm_tlv->header.len); *assoc_buf += ret_len; } return ret_len; } /* * This function computes the time delay in the driver queues for a * given packet. * * When the packet is received at the OS/Driver interface, the current * time is set in the packet structure. The difference between the present * time and that received time is computed in this function and limited * based on pre-compiled limits in the driver. */ u8 mwifiex_wmm_compute_drv_pkt_delay(struct mwifiex_private *priv, const struct sk_buff *skb) { u32 queue_delay = ktime_to_ms(net_timedelta(skb->tstamp)); u8 ret_val; /* * Queue delay is passed as a uint8 in units of 2ms (ms shifted * by 1). Min value (other than 0) is therefore 2ms, max is 510ms. * * Pass max value if queue_delay is beyond the uint8 range */ ret_val = (u8) (min(queue_delay, priv->wmm.drv_pkt_delay_max) >> 1); mwifiex_dbg(priv->adapter, DATA, "data: WMM: Pkt Delay: %d ms,\t" "%d ms sent to FW\n", queue_delay, ret_val); return ret_val; } /* * This function retrieves the highest priority RA list table pointer. */ static struct mwifiex_ra_list_tbl * mwifiex_wmm_get_highest_priolist_ptr(struct mwifiex_adapter *adapter, struct mwifiex_private **priv, int *tid) { struct mwifiex_private *priv_tmp; struct mwifiex_ra_list_tbl *ptr; struct mwifiex_tid_tbl *tid_ptr; atomic_t *hqp; int i, j; /* check the BSS with highest priority first */ for (j = adapter->priv_num - 1; j >= 0; --j) { /* iterate over BSS with the equal priority */ list_for_each_entry(adapter->bss_prio_tbl[j].bss_prio_cur, &adapter->bss_prio_tbl[j].bss_prio_head, list) { try_again: priv_tmp = adapter->bss_prio_tbl[j].bss_prio_cur->priv; if (((priv_tmp->bss_mode != NL80211_IFTYPE_ADHOC) && !priv_tmp->port_open) || (atomic_read(&priv_tmp->wmm.tx_pkts_queued) == 0)) continue; if (adapter->if_ops.is_port_ready && !adapter->if_ops.is_port_ready(priv_tmp)) continue; /* iterate over the WMM queues of the BSS */ hqp = &priv_tmp->wmm.highest_queued_prio; for (i = atomic_read(hqp); i >= LOW_PRIO_TID; --i) { spin_lock_bh(&priv_tmp->wmm.ra_list_spinlock); tid_ptr = &(priv_tmp)->wmm. tid_tbl_ptr[tos_to_tid[i]]; /* iterate over receiver addresses */ list_for_each_entry(ptr, &tid_ptr->ra_list, list) { if (!ptr->tx_paused && !skb_queue_empty(&ptr->skb_head)) /* holds both locks */ goto found; } spin_unlock_bh(&priv_tmp->wmm.ra_list_spinlock); } if (atomic_read(&priv_tmp->wmm.tx_pkts_queued) != 0) { atomic_set(&priv_tmp->wmm.highest_queued_prio, HIGH_PRIO_TID); /* Iterate current private once more, since * there still exist packets in data queue */ goto try_again; } else atomic_set(&priv_tmp->wmm.highest_queued_prio, NO_PKT_PRIO_TID); } } return NULL; found: /* holds ra_list_spinlock */ if (atomic_read(hqp) > i) atomic_set(hqp, i); spin_unlock_bh(&priv_tmp->wmm.ra_list_spinlock); *priv = priv_tmp; *tid = tos_to_tid[i]; return ptr; } /* This functions rotates ra and bss lists so packets are picked round robin. * * After a packet is successfully transmitted, rotate the ra list, so the ra * next to the one transmitted, will come first in the list. This way we pick * the ra' in a round robin fashion. Same applies to bss nodes of equal * priority. * * Function also increments wmm.packets_out counter. */ void mwifiex_rotate_priolists(struct mwifiex_private *priv, struct mwifiex_ra_list_tbl *ra, int tid) { struct mwifiex_adapter *adapter = priv->adapter; struct mwifiex_bss_prio_tbl *tbl = adapter->bss_prio_tbl; struct mwifiex_tid_tbl *tid_ptr = &priv->wmm.tid_tbl_ptr[tid]; spin_lock_bh(&tbl[priv->bss_priority].bss_prio_lock); /* * dirty trick: we remove 'head' temporarily and reinsert it after * curr bss node. imagine list to stay fixed while head is moved */ list_move(&tbl[priv->bss_priority].bss_prio_head, &tbl[priv->bss_priority].bss_prio_cur->list); spin_unlock_bh(&tbl[priv->bss_priority].bss_prio_lock); spin_lock_bh(&priv->wmm.ra_list_spinlock); if (mwifiex_is_ralist_valid(priv, ra, tid)) { priv->wmm.packets_out[tid]++; /* same as above */ list_move(&tid_ptr->ra_list, &ra->list); } spin_unlock_bh(&priv->wmm.ra_list_spinlock); } /* * This function checks if 11n aggregation is possible. */ static int mwifiex_is_11n_aggragation_possible(struct mwifiex_private *priv, struct mwifiex_ra_list_tbl *ptr, int max_buf_size) { int count = 0, total_size = 0; struct sk_buff *skb, *tmp; int max_amsdu_size; if (priv->bss_role == MWIFIEX_BSS_ROLE_UAP && priv->ap_11n_enabled && ptr->is_11n_enabled) max_amsdu_size = min_t(int, ptr->max_amsdu, max_buf_size); else max_amsdu_size = max_buf_size; skb_queue_walk_safe(&ptr->skb_head, skb, tmp) { total_size += skb->len; if (total_size >= max_amsdu_size) break; if (++count >= MIN_NUM_AMSDU) return true; } return false; } /* * This function sends a single packet to firmware for transmission. */ static void mwifiex_send_single_packet(struct mwifiex_private *priv, struct mwifiex_ra_list_tbl *ptr, int ptr_index) __releases(&priv->wmm.ra_list_spinlock) { struct sk_buff *skb, *skb_next; struct mwifiex_tx_param tx_param; struct mwifiex_adapter *adapter = priv->adapter; struct mwifiex_txinfo *tx_info; if (skb_queue_empty(&ptr->skb_head)) { spin_unlock_bh(&priv->wmm.ra_list_spinlock); mwifiex_dbg(adapter, DATA, "data: nothing to send\n"); return; } skb = skb_dequeue(&ptr->skb_head); tx_info = MWIFIEX_SKB_TXCB(skb); mwifiex_dbg(adapter, DATA, "data: dequeuing the packet %p %p\n", ptr, skb); ptr->total_pkt_count--; if (!skb_queue_empty(&ptr->skb_head)) skb_next = skb_peek(&ptr->skb_head); else skb_next = NULL; spin_unlock_bh(&priv->wmm.ra_list_spinlock); tx_param.next_pkt_len = ((skb_next) ? skb_next->len + sizeof(struct txpd) : 0); if (mwifiex_process_tx(priv, skb, &tx_param) == -EBUSY) { /* Queue the packet back at the head */ spin_lock_bh(&priv->wmm.ra_list_spinlock); if (!mwifiex_is_ralist_valid(priv, ptr, ptr_index)) { spin_unlock_bh(&priv->wmm.ra_list_spinlock); mwifiex_write_data_complete(adapter, skb, 0, -1); return; } skb_queue_tail(&ptr->skb_head, skb); ptr->total_pkt_count++; ptr->ba_pkt_count++; tx_info->flags |= MWIFIEX_BUF_FLAG_REQUEUED_PKT; spin_unlock_bh(&priv->wmm.ra_list_spinlock); } else { mwifiex_rotate_priolists(priv, ptr, ptr_index); atomic_dec(&priv->wmm.tx_pkts_queued); } } /* * This function checks if the first packet in the given RA list * is already processed or not. */ static int mwifiex_is_ptr_processed(struct mwifiex_private *priv, struct mwifiex_ra_list_tbl *ptr) { struct sk_buff *skb; struct mwifiex_txinfo *tx_info; if (skb_queue_empty(&ptr->skb_head)) return false; skb = skb_peek(&ptr->skb_head); tx_info = MWIFIEX_SKB_TXCB(skb); if (tx_info->flags & MWIFIEX_BUF_FLAG_REQUEUED_PKT) return true; return false; } /* * This function sends a single processed packet to firmware for * transmission. */ static void mwifiex_send_processed_packet(struct mwifiex_private *priv, struct mwifiex_ra_list_tbl *ptr, int ptr_index) __releases(&priv->wmm.ra_list_spinlock) { struct mwifiex_tx_param tx_param; struct mwifiex_adapter *adapter = priv->adapter; int ret = -1; struct sk_buff *skb, *skb_next; struct mwifiex_txinfo *tx_info; if (skb_queue_empty(&ptr->skb_head)) { spin_unlock_bh(&priv->wmm.ra_list_spinlock); return; } skb = skb_dequeue(&ptr->skb_head); if (adapter->data_sent || adapter->tx_lock_flag) { ptr->total_pkt_count--; spin_unlock_bh(&priv->wmm.ra_list_spinlock); skb_queue_tail(&adapter->tx_data_q, skb); atomic_dec(&priv->wmm.tx_pkts_queued); atomic_inc(&adapter->tx_queued); return; } if (!skb_queue_empty(&ptr->skb_head)) skb_next = skb_peek(&ptr->skb_head); else skb_next = NULL; tx_info = MWIFIEX_SKB_TXCB(skb); spin_unlock_bh(&priv->wmm.ra_list_spinlock); tx_param.next_pkt_len = ((skb_next) ? skb_next->len + sizeof(struct txpd) : 0); if (adapter->iface_type == MWIFIEX_USB) { ret = adapter->if_ops.host_to_card(adapter, priv->usb_port, skb, &tx_param); } else { ret = adapter->if_ops.host_to_card(adapter, MWIFIEX_TYPE_DATA, skb, &tx_param); } switch (ret) { case -EBUSY: mwifiex_dbg(adapter, ERROR, "data: -EBUSY is returned\n"); spin_lock_bh(&priv->wmm.ra_list_spinlock); if (!mwifiex_is_ralist_valid(priv, ptr, ptr_index)) { spin_unlock_bh(&priv->wmm.ra_list_spinlock); mwifiex_write_data_complete(adapter, skb, 0, -1); return; } skb_queue_tail(&ptr->skb_head, skb); tx_info->flags |= MWIFIEX_BUF_FLAG_REQUEUED_PKT; spin_unlock_bh(&priv->wmm.ra_list_spinlock); break; case -1: mwifiex_dbg(adapter, ERROR, "host_to_card failed: %#x\n", ret); adapter->dbg.num_tx_host_to_card_failure++; mwifiex_write_data_complete(adapter, skb, 0, ret); break; case -EINPROGRESS: break; case 0: mwifiex_write_data_complete(adapter, skb, 0, ret); default: break; } if (ret != -EBUSY) { mwifiex_rotate_priolists(priv, ptr, ptr_index); atomic_dec(&priv->wmm.tx_pkts_queued); spin_lock_bh(&priv->wmm.ra_list_spinlock); ptr->total_pkt_count--; spin_unlock_bh(&priv->wmm.ra_list_spinlock); } } /* * This function dequeues a packet from the highest priority list * and transmits it. */ static int mwifiex_dequeue_tx_packet(struct mwifiex_adapter *adapter) { struct mwifiex_ra_list_tbl *ptr; struct mwifiex_private *priv = NULL; int ptr_index = 0; u8 ra[ETH_ALEN]; int tid_del = 0, tid = 0; ptr = mwifiex_wmm_get_highest_priolist_ptr(adapter, &priv, &ptr_index); if (!ptr) return -1; tid = mwifiex_get_tid(ptr); mwifiex_dbg(adapter, DATA, "data: tid=%d\n", tid); spin_lock_bh(&priv->wmm.ra_list_spinlock); if (!mwifiex_is_ralist_valid(priv, ptr, ptr_index)) { spin_unlock_bh(&priv->wmm.ra_list_spinlock); return -1; } if (mwifiex_is_ptr_processed(priv, ptr)) { mwifiex_send_processed_packet(priv, ptr, ptr_index); /* ra_list_spinlock has been freed in mwifiex_send_processed_packet() */ return 0; } if (!ptr->is_11n_enabled || ptr->ba_status || priv->wps.session_enable) { if (ptr->is_11n_enabled && ptr->ba_status && ptr->amsdu_in_ampdu && mwifiex_is_amsdu_allowed(priv, tid) && mwifiex_is_11n_aggragation_possible(priv, ptr, adapter->tx_buf_size)) mwifiex_11n_aggregate_pkt(priv, ptr, ptr_index); /* ra_list_spinlock has been freed in * mwifiex_11n_aggregate_pkt() */ else mwifiex_send_single_packet(priv, ptr, ptr_index); /* ra_list_spinlock has been freed in * mwifiex_send_single_packet() */ } else { if (mwifiex_is_ampdu_allowed(priv, ptr, tid) && ptr->ba_pkt_count > ptr->ba_packet_thr) { if (mwifiex_space_avail_for_new_ba_stream(adapter)) { mwifiex_create_ba_tbl(priv, ptr->ra, tid, BA_SETUP_INPROGRESS); mwifiex_send_addba(priv, tid, ptr->ra); } else if (mwifiex_find_stream_to_delete (priv, tid, &tid_del, ra)) { mwifiex_create_ba_tbl(priv, ptr->ra, tid, BA_SETUP_INPROGRESS); mwifiex_send_delba(priv, tid_del, ra, 1); } } if (mwifiex_is_amsdu_allowed(priv, tid) && mwifiex_is_11n_aggragation_possible(priv, ptr, adapter->tx_buf_size)) mwifiex_11n_aggregate_pkt(priv, ptr, ptr_index); /* ra_list_spinlock has been freed in mwifiex_11n_aggregate_pkt() */ else mwifiex_send_single_packet(priv, ptr, ptr_index); /* ra_list_spinlock has been freed in mwifiex_send_single_packet() */ } return 0; } void mwifiex_process_bypass_tx(struct mwifiex_adapter *adapter) { struct mwifiex_tx_param tx_param; struct sk_buff *skb; struct mwifiex_txinfo *tx_info; struct mwifiex_private *priv; int i; if (adapter->data_sent || adapter->tx_lock_flag) return; for (i = 0; i < adapter->priv_num; ++i) { priv = adapter->priv[i]; if (!priv) continue; if (adapter->if_ops.is_port_ready && !adapter->if_ops.is_port_ready(priv)) continue; if (skb_queue_empty(&priv->bypass_txq)) continue; skb = skb_dequeue(&priv->bypass_txq); tx_info = MWIFIEX_SKB_TXCB(skb); /* no aggregation for bypass packets */ tx_param.next_pkt_len = 0; if (mwifiex_process_tx(priv, skb, &tx_param) == -EBUSY) { skb_queue_head(&priv->bypass_txq, skb); tx_info->flags |= MWIFIEX_BUF_FLAG_REQUEUED_PKT; } else { atomic_dec(&adapter->bypass_tx_pending); } } } /* * This function transmits the highest priority packet awaiting in the * WMM Queues. */ void mwifiex_wmm_process_tx(struct mwifiex_adapter *adapter) { do { if (mwifiex_dequeue_tx_packet(adapter)) break; if (adapter->iface_type != MWIFIEX_SDIO) { if (adapter->data_sent || adapter->tx_lock_flag) break; } else { if (atomic_read(&adapter->tx_queued) >= MWIFIEX_MAX_PKTS_TXQ) break; } } while (!mwifiex_wmm_lists_empty(adapter)); }
null
171
CWE-787
CVE-2020-12659
// SPDX-License-Identifier: GPL-2.0 /* XDP user-space packet buffer * Copyright(c) 2018 Intel Corporation. */ #include <linux/init.h> #include <linux/sched/mm.h> #include <linux/sched/signal.h> #include <linux/sched/task.h> #include <linux/uaccess.h> #include <linux/slab.h> #include <linux/bpf.h> #include <linux/mm.h> #include <linux/netdevice.h> #include <linux/rtnetlink.h> #include <linux/idr.h> #include <linux/vmalloc.h> #include "xdp_umem.h" #include "xsk_queue.h" #define XDP_UMEM_MIN_CHUNK_SIZE 2048 static DEFINE_IDA(umem_ida); void xdp_add_sk_umem(struct xdp_umem *umem, struct xdp_sock *xs) { unsigned long flags; if (!xs->tx) return; spin_lock_irqsave(&umem->xsk_list_lock, flags); list_add_rcu(&xs->list, &umem->xsk_list); spin_unlock_irqrestore(&umem->xsk_list_lock, flags); } void xdp_del_sk_umem(struct xdp_umem *umem, struct xdp_sock *xs) { unsigned long flags; if (!xs->tx) return; spin_lock_irqsave(&umem->xsk_list_lock, flags); list_del_rcu(&xs->list); spin_unlock_irqrestore(&umem->xsk_list_lock, flags); } /* The umem is stored both in the _rx struct and the _tx struct as we do * not know if the device has more tx queues than rx, or the opposite. * This might also change during run time. */ static int xdp_reg_umem_at_qid(struct net_device *dev, struct xdp_umem *umem, u16 queue_id) { if (queue_id >= max_t(unsigned int, dev->real_num_rx_queues, dev->real_num_tx_queues)) return -EINVAL; if (queue_id < dev->real_num_rx_queues) dev->_rx[queue_id].umem = umem; if (queue_id < dev->real_num_tx_queues) dev->_tx[queue_id].umem = umem; return 0; } struct xdp_umem *xdp_get_umem_from_qid(struct net_device *dev, u16 queue_id) { if (queue_id < dev->real_num_rx_queues) return dev->_rx[queue_id].umem; if (queue_id < dev->real_num_tx_queues) return dev->_tx[queue_id].umem; return NULL; } EXPORT_SYMBOL(xdp_get_umem_from_qid); static void xdp_clear_umem_at_qid(struct net_device *dev, u16 queue_id) { if (queue_id < dev->real_num_rx_queues) dev->_rx[queue_id].umem = NULL; if (queue_id < dev->real_num_tx_queues) dev->_tx[queue_id].umem = NULL; } int xdp_umem_assign_dev(struct xdp_umem *umem, struct net_device *dev, u16 queue_id, u16 flags) { bool force_zc, force_copy; struct netdev_bpf bpf; int err = 0; ASSERT_RTNL(); force_zc = flags & XDP_ZEROCOPY; force_copy = flags & XDP_COPY; if (force_zc && force_copy) return -EINVAL; if (xdp_get_umem_from_qid(dev, queue_id)) return -EBUSY; err = xdp_reg_umem_at_qid(dev, umem, queue_id); if (err) return err; umem->dev = dev; umem->queue_id = queue_id; if (flags & XDP_USE_NEED_WAKEUP) { umem->flags |= XDP_UMEM_USES_NEED_WAKEUP; /* Tx needs to be explicitly woken up the first time. * Also for supporting drivers that do not implement this * feature. They will always have to call sendto(). */ xsk_set_tx_need_wakeup(umem); } dev_hold(dev); if (force_copy) /* For copy-mode, we are done. */ return 0; if (!dev->netdev_ops->ndo_bpf || !dev->netdev_ops->ndo_xsk_wakeup) { err = -EOPNOTSUPP; goto err_unreg_umem; } bpf.command = XDP_SETUP_XSK_UMEM; bpf.xsk.umem = umem; bpf.xsk.queue_id = queue_id; err = dev->netdev_ops->ndo_bpf(dev, &bpf); if (err) goto err_unreg_umem; umem->zc = true; return 0; err_unreg_umem: if (!force_zc) err = 0; /* fallback to copy mode */ if (err) xdp_clear_umem_at_qid(dev, queue_id); return err; } void xdp_umem_clear_dev(struct xdp_umem *umem) { struct netdev_bpf bpf; int err; ASSERT_RTNL(); if (!umem->dev) return; if (umem->zc) { bpf.command = XDP_SETUP_XSK_UMEM; bpf.xsk.umem = NULL; bpf.xsk.queue_id = umem->queue_id; err = umem->dev->netdev_ops->ndo_bpf(umem->dev, &bpf); if (err) WARN(1, "failed to disable umem!\n"); } xdp_clear_umem_at_qid(umem->dev, umem->queue_id); dev_put(umem->dev); umem->dev = NULL; umem->zc = false; } static void xdp_umem_unmap_pages(struct xdp_umem *umem) { unsigned int i; for (i = 0; i < umem->npgs; i++) if (PageHighMem(umem->pgs[i])) vunmap(umem->pages[i].addr); } static int xdp_umem_map_pages(struct xdp_umem *umem) { unsigned int i; void *addr; for (i = 0; i < umem->npgs; i++) { if (PageHighMem(umem->pgs[i])) addr = vmap(&umem->pgs[i], 1, VM_MAP, PAGE_KERNEL); else addr = page_address(umem->pgs[i]); if (!addr) { xdp_umem_unmap_pages(umem); return -ENOMEM; } umem->pages[i].addr = addr; } return 0; } static void xdp_umem_unpin_pages(struct xdp_umem *umem) { unpin_user_pages_dirty_lock(umem->pgs, umem->npgs, true); kfree(umem->pgs); umem->pgs = NULL; } static void xdp_umem_unaccount_pages(struct xdp_umem *umem) { if (umem->user) { atomic_long_sub(umem->npgs, &umem->user->locked_vm); free_uid(umem->user); } } static void xdp_umem_release(struct xdp_umem *umem) { rtnl_lock(); xdp_umem_clear_dev(umem); rtnl_unlock(); ida_simple_remove(&umem_ida, umem->id); if (umem->fq) { xskq_destroy(umem->fq); umem->fq = NULL; } if (umem->cq) { xskq_destroy(umem->cq); umem->cq = NULL; } xsk_reuseq_destroy(umem); xdp_umem_unmap_pages(umem); xdp_umem_unpin_pages(umem); kvfree(umem->pages); umem->pages = NULL; xdp_umem_unaccount_pages(umem); kfree(umem); } static void xdp_umem_release_deferred(struct work_struct *work) { struct xdp_umem *umem = container_of(work, struct xdp_umem, work); xdp_umem_release(umem); } void xdp_get_umem(struct xdp_umem *umem) { refcount_inc(&umem->users); } void xdp_put_umem(struct xdp_umem *umem) { if (!umem) return; if (refcount_dec_and_test(&umem->users)) { INIT_WORK(&umem->work, xdp_umem_release_deferred); schedule_work(&umem->work); } } static int xdp_umem_pin_pages(struct xdp_umem *umem) { unsigned int gup_flags = FOLL_WRITE; long npgs; int err; umem->pgs = kcalloc(umem->npgs, sizeof(*umem->pgs), GFP_KERNEL | __GFP_NOWARN); if (!umem->pgs) return -ENOMEM; down_read(&current->mm->mmap_sem); npgs = pin_user_pages(umem->address, umem->npgs, gup_flags | FOLL_LONGTERM, &umem->pgs[0], NULL); up_read(&current->mm->mmap_sem); if (npgs != umem->npgs) { if (npgs >= 0) { umem->npgs = npgs; err = -ENOMEM; goto out_pin; } err = npgs; goto out_pgs; } return 0; out_pin: xdp_umem_unpin_pages(umem); out_pgs: kfree(umem->pgs); umem->pgs = NULL; return err; } static int xdp_umem_account_pages(struct xdp_umem *umem) { unsigned long lock_limit, new_npgs, old_npgs; if (capable(CAP_IPC_LOCK)) return 0; lock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT; umem->user = get_uid(current_user()); do { old_npgs = atomic_long_read(&umem->user->locked_vm); new_npgs = old_npgs + umem->npgs; if (new_npgs > lock_limit) { free_uid(umem->user); umem->user = NULL; return -ENOBUFS; } } while (atomic_long_cmpxchg(&umem->user->locked_vm, old_npgs, new_npgs) != old_npgs); return 0; } static int xdp_umem_reg(struct xdp_umem *umem, struct xdp_umem_reg *mr) { bool unaligned_chunks = mr->flags & XDP_UMEM_UNALIGNED_CHUNK_FLAG; u32 chunk_size = mr->chunk_size, headroom = mr->headroom; unsigned int chunks, chunks_per_page; u64 addr = mr->addr, size = mr->len; int size_chk, err; if (chunk_size < XDP_UMEM_MIN_CHUNK_SIZE || chunk_size > PAGE_SIZE) { /* Strictly speaking we could support this, if: * - huge pages, or* * - using an IOMMU, or * - making sure the memory area is consecutive * but for now, we simply say "computer says no". */ return -EINVAL; } if (mr->flags & ~(XDP_UMEM_UNALIGNED_CHUNK_FLAG | XDP_UMEM_USES_NEED_WAKEUP)) return -EINVAL; if (!unaligned_chunks && !is_power_of_2(chunk_size)) return -EINVAL; if (!PAGE_ALIGNED(addr)) { /* Memory area has to be page size aligned. For * simplicity, this might change. */ return -EINVAL; } if ((addr + size) < addr) return -EINVAL; chunks = (unsigned int)div_u64(size, chunk_size); if (chunks == 0) return -EINVAL; if (!unaligned_chunks) { chunks_per_page = PAGE_SIZE / chunk_size; if (chunks < chunks_per_page || chunks % chunks_per_page) return -EINVAL; } size_chk = chunk_size - headroom - XDP_PACKET_HEADROOM; if (size_chk < 0) return -EINVAL; umem->address = (unsigned long)addr; umem->chunk_mask = unaligned_chunks ? XSK_UNALIGNED_BUF_ADDR_MASK : ~((u64)chunk_size - 1); umem->size = size; umem->headroom = headroom; umem->chunk_size_nohr = chunk_size - headroom; umem->npgs = size / PAGE_SIZE; umem->pgs = NULL; umem->user = NULL; umem->flags = mr->flags; INIT_LIST_HEAD(&umem->xsk_list); spin_lock_init(&umem->xsk_list_lock); refcount_set(&umem->users, 1); err = xdp_umem_account_pages(umem); if (err) return err; err = xdp_umem_pin_pages(umem); if (err) goto out_account; umem->pages = kvcalloc(umem->npgs, sizeof(*umem->pages), GFP_KERNEL_ACCOUNT); if (!umem->pages) { err = -ENOMEM; goto out_pin; } err = xdp_umem_map_pages(umem); if (!err) return 0; kvfree(umem->pages); out_pin: xdp_umem_unpin_pages(umem); out_account: xdp_umem_unaccount_pages(umem); return err; } struct xdp_umem *xdp_umem_create(struct xdp_umem_reg *mr) { struct xdp_umem *umem; int err; umem = kzalloc(sizeof(*umem), GFP_KERNEL); if (!umem) return ERR_PTR(-ENOMEM); err = ida_simple_get(&umem_ida, 0, 0, GFP_KERNEL); if (err < 0) { kfree(umem); return ERR_PTR(err); } umem->id = err; err = xdp_umem_reg(umem, mr); if (err) { ida_simple_remove(&umem_ida, umem->id); kfree(umem); return ERR_PTR(err); } return umem; } bool xdp_umem_validate_queues(struct xdp_umem *umem) { return umem->fq && umem->cq; }
null
// SPDX-License-Identifier: GPL-2.0 /* XDP user-space packet buffer * Copyright(c) 2018 Intel Corporation. */ #include <linux/init.h> #include <linux/sched/mm.h> #include <linux/sched/signal.h> #include <linux/sched/task.h> #include <linux/uaccess.h> #include <linux/slab.h> #include <linux/bpf.h> #include <linux/mm.h> #include <linux/netdevice.h> #include <linux/rtnetlink.h> #include <linux/idr.h> #include <linux/vmalloc.h> #include "xdp_umem.h" #include "xsk_queue.h" #define XDP_UMEM_MIN_CHUNK_SIZE 2048 static DEFINE_IDA(umem_ida); void xdp_add_sk_umem(struct xdp_umem *umem, struct xdp_sock *xs) { unsigned long flags; if (!xs->tx) return; spin_lock_irqsave(&umem->xsk_list_lock, flags); list_add_rcu(&xs->list, &umem->xsk_list); spin_unlock_irqrestore(&umem->xsk_list_lock, flags); } void xdp_del_sk_umem(struct xdp_umem *umem, struct xdp_sock *xs) { unsigned long flags; if (!xs->tx) return; spin_lock_irqsave(&umem->xsk_list_lock, flags); list_del_rcu(&xs->list); spin_unlock_irqrestore(&umem->xsk_list_lock, flags); } /* The umem is stored both in the _rx struct and the _tx struct as we do * not know if the device has more tx queues than rx, or the opposite. * This might also change during run time. */ static int xdp_reg_umem_at_qid(struct net_device *dev, struct xdp_umem *umem, u16 queue_id) { if (queue_id >= max_t(unsigned int, dev->real_num_rx_queues, dev->real_num_tx_queues)) return -EINVAL; if (queue_id < dev->real_num_rx_queues) dev->_rx[queue_id].umem = umem; if (queue_id < dev->real_num_tx_queues) dev->_tx[queue_id].umem = umem; return 0; } struct xdp_umem *xdp_get_umem_from_qid(struct net_device *dev, u16 queue_id) { if (queue_id < dev->real_num_rx_queues) return dev->_rx[queue_id].umem; if (queue_id < dev->real_num_tx_queues) return dev->_tx[queue_id].umem; return NULL; } EXPORT_SYMBOL(xdp_get_umem_from_qid); static void xdp_clear_umem_at_qid(struct net_device *dev, u16 queue_id) { if (queue_id < dev->real_num_rx_queues) dev->_rx[queue_id].umem = NULL; if (queue_id < dev->real_num_tx_queues) dev->_tx[queue_id].umem = NULL; } int xdp_umem_assign_dev(struct xdp_umem *umem, struct net_device *dev, u16 queue_id, u16 flags) { bool force_zc, force_copy; struct netdev_bpf bpf; int err = 0; ASSERT_RTNL(); force_zc = flags & XDP_ZEROCOPY; force_copy = flags & XDP_COPY; if (force_zc && force_copy) return -EINVAL; if (xdp_get_umem_from_qid(dev, queue_id)) return -EBUSY; err = xdp_reg_umem_at_qid(dev, umem, queue_id); if (err) return err; umem->dev = dev; umem->queue_id = queue_id; if (flags & XDP_USE_NEED_WAKEUP) { umem->flags |= XDP_UMEM_USES_NEED_WAKEUP; /* Tx needs to be explicitly woken up the first time. * Also for supporting drivers that do not implement this * feature. They will always have to call sendto(). */ xsk_set_tx_need_wakeup(umem); } dev_hold(dev); if (force_copy) /* For copy-mode, we are done. */ return 0; if (!dev->netdev_ops->ndo_bpf || !dev->netdev_ops->ndo_xsk_wakeup) { err = -EOPNOTSUPP; goto err_unreg_umem; } bpf.command = XDP_SETUP_XSK_UMEM; bpf.xsk.umem = umem; bpf.xsk.queue_id = queue_id; err = dev->netdev_ops->ndo_bpf(dev, &bpf); if (err) goto err_unreg_umem; umem->zc = true; return 0; err_unreg_umem: if (!force_zc) err = 0; /* fallback to copy mode */ if (err) xdp_clear_umem_at_qid(dev, queue_id); return err; } void xdp_umem_clear_dev(struct xdp_umem *umem) { struct netdev_bpf bpf; int err; ASSERT_RTNL(); if (!umem->dev) return; if (umem->zc) { bpf.command = XDP_SETUP_XSK_UMEM; bpf.xsk.umem = NULL; bpf.xsk.queue_id = umem->queue_id; err = umem->dev->netdev_ops->ndo_bpf(umem->dev, &bpf); if (err) WARN(1, "failed to disable umem!\n"); } xdp_clear_umem_at_qid(umem->dev, umem->queue_id); dev_put(umem->dev); umem->dev = NULL; umem->zc = false; } static void xdp_umem_unmap_pages(struct xdp_umem *umem) { unsigned int i; for (i = 0; i < umem->npgs; i++) if (PageHighMem(umem->pgs[i])) vunmap(umem->pages[i].addr); } static int xdp_umem_map_pages(struct xdp_umem *umem) { unsigned int i; void *addr; for (i = 0; i < umem->npgs; i++) { if (PageHighMem(umem->pgs[i])) addr = vmap(&umem->pgs[i], 1, VM_MAP, PAGE_KERNEL); else addr = page_address(umem->pgs[i]); if (!addr) { xdp_umem_unmap_pages(umem); return -ENOMEM; } umem->pages[i].addr = addr; } return 0; } static void xdp_umem_unpin_pages(struct xdp_umem *umem) { unpin_user_pages_dirty_lock(umem->pgs, umem->npgs, true); kfree(umem->pgs); umem->pgs = NULL; } static void xdp_umem_unaccount_pages(struct xdp_umem *umem) { if (umem->user) { atomic_long_sub(umem->npgs, &umem->user->locked_vm); free_uid(umem->user); } } static void xdp_umem_release(struct xdp_umem *umem) { rtnl_lock(); xdp_umem_clear_dev(umem); rtnl_unlock(); ida_simple_remove(&umem_ida, umem->id); if (umem->fq) { xskq_destroy(umem->fq); umem->fq = NULL; } if (umem->cq) { xskq_destroy(umem->cq); umem->cq = NULL; } xsk_reuseq_destroy(umem); xdp_umem_unmap_pages(umem); xdp_umem_unpin_pages(umem); kvfree(umem->pages); umem->pages = NULL; xdp_umem_unaccount_pages(umem); kfree(umem); } static void xdp_umem_release_deferred(struct work_struct *work) { struct xdp_umem *umem = container_of(work, struct xdp_umem, work); xdp_umem_release(umem); } void xdp_get_umem(struct xdp_umem *umem) { refcount_inc(&umem->users); } void xdp_put_umem(struct xdp_umem *umem) { if (!umem) return; if (refcount_dec_and_test(&umem->users)) { INIT_WORK(&umem->work, xdp_umem_release_deferred); schedule_work(&umem->work); } } static int xdp_umem_pin_pages(struct xdp_umem *umem) { unsigned int gup_flags = FOLL_WRITE; long npgs; int err; umem->pgs = kcalloc(umem->npgs, sizeof(*umem->pgs), GFP_KERNEL | __GFP_NOWARN); if (!umem->pgs) return -ENOMEM; down_read(&current->mm->mmap_sem); npgs = pin_user_pages(umem->address, umem->npgs, gup_flags | FOLL_LONGTERM, &umem->pgs[0], NULL); up_read(&current->mm->mmap_sem); if (npgs != umem->npgs) { if (npgs >= 0) { umem->npgs = npgs; err = -ENOMEM; goto out_pin; } err = npgs; goto out_pgs; } return 0; out_pin: xdp_umem_unpin_pages(umem); out_pgs: kfree(umem->pgs); umem->pgs = NULL; return err; } static int xdp_umem_account_pages(struct xdp_umem *umem) { unsigned long lock_limit, new_npgs, old_npgs; if (capable(CAP_IPC_LOCK)) return 0; lock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT; umem->user = get_uid(current_user()); do { old_npgs = atomic_long_read(&umem->user->locked_vm); new_npgs = old_npgs + umem->npgs; if (new_npgs > lock_limit) { free_uid(umem->user); umem->user = NULL; return -ENOBUFS; } } while (atomic_long_cmpxchg(&umem->user->locked_vm, old_npgs, new_npgs) != old_npgs); return 0; } static int xdp_umem_reg(struct xdp_umem *umem, struct xdp_umem_reg *mr) { bool unaligned_chunks = mr->flags & XDP_UMEM_UNALIGNED_CHUNK_FLAG; u32 chunk_size = mr->chunk_size, headroom = mr->headroom; unsigned int chunks, chunks_per_page; u64 addr = mr->addr, size = mr->len; int err; if (chunk_size < XDP_UMEM_MIN_CHUNK_SIZE || chunk_size > PAGE_SIZE) { /* Strictly speaking we could support this, if: * - huge pages, or* * - using an IOMMU, or * - making sure the memory area is consecutive * but for now, we simply say "computer says no". */ return -EINVAL; } if (mr->flags & ~(XDP_UMEM_UNALIGNED_CHUNK_FLAG | XDP_UMEM_USES_NEED_WAKEUP)) return -EINVAL; if (!unaligned_chunks && !is_power_of_2(chunk_size)) return -EINVAL; if (!PAGE_ALIGNED(addr)) { /* Memory area has to be page size aligned. For * simplicity, this might change. */ return -EINVAL; } if ((addr + size) < addr) return -EINVAL; chunks = (unsigned int)div_u64(size, chunk_size); if (chunks == 0) return -EINVAL; if (!unaligned_chunks) { chunks_per_page = PAGE_SIZE / chunk_size; if (chunks < chunks_per_page || chunks % chunks_per_page) return -EINVAL; } if (headroom >= chunk_size - XDP_PACKET_HEADROOM) return -EINVAL; umem->address = (unsigned long)addr; umem->chunk_mask = unaligned_chunks ? XSK_UNALIGNED_BUF_ADDR_MASK : ~((u64)chunk_size - 1); umem->size = size; umem->headroom = headroom; umem->chunk_size_nohr = chunk_size - headroom; umem->npgs = size / PAGE_SIZE; umem->pgs = NULL; umem->user = NULL; umem->flags = mr->flags; INIT_LIST_HEAD(&umem->xsk_list); spin_lock_init(&umem->xsk_list_lock); refcount_set(&umem->users, 1); err = xdp_umem_account_pages(umem); if (err) return err; err = xdp_umem_pin_pages(umem); if (err) goto out_account; umem->pages = kvcalloc(umem->npgs, sizeof(*umem->pages), GFP_KERNEL_ACCOUNT); if (!umem->pages) { err = -ENOMEM; goto out_pin; } err = xdp_umem_map_pages(umem); if (!err) return 0; kvfree(umem->pages); out_pin: xdp_umem_unpin_pages(umem); out_account: xdp_umem_unaccount_pages(umem); return err; } struct xdp_umem *xdp_umem_create(struct xdp_umem_reg *mr) { struct xdp_umem *umem; int err; umem = kzalloc(sizeof(*umem), GFP_KERNEL); if (!umem) return ERR_PTR(-ENOMEM); err = ida_simple_get(&umem_ida, 0, 0, GFP_KERNEL); if (err < 0) { kfree(umem); return ERR_PTR(err); } umem->id = err; err = xdp_umem_reg(umem, mr); if (err) { ida_simple_remove(&umem_ida, umem->id); kfree(umem); return ERR_PTR(err); } return umem; } bool xdp_umem_validate_queues(struct xdp_umem *umem) { return umem->fq && umem->cq; }
null
172
CWE-787
CVE-2020-13111
/* * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://mozilla.org/. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See * the License for the specific language governing rights and limitations * under the License. * * The Original Code is AOLserver Code and related documentation * distributed by AOL. * * The Initial Developer of the Original Code is America Online, * Inc. Portions created by AOL are Copyright (C) 1999 America Online, * Inc. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms * of the GNU General Public License (the "GPL"), in which case the * provisions of GPL are applicable instead of those above. If you wish * to allow use of your version of this file only under the terms of the * GPL and not to allow others to use your version of this file under the * License, indicate your decision by deleting the provisions above and * replace them with the notice and other provisions required by the GPL. * If you do not delete the provisions above, a recipient may use your * version of this file under either the License or the GPL. */ /* * driver.c -- * * Connection I/O for loadable socket drivers. */ #include "nsd.h" /* * The following are valid driver state flags. */ #define DRIVER_STARTED 1u #define DRIVER_STOPPED 2u #define DRIVER_SHUTDOWN 4u #define DRIVER_FAILED 8u /* * Constants for SockState return and reason codes. */ typedef enum { SOCK_READY = 0, SOCK_MORE = 1, SOCK_SPOOL = 2, SOCK_ERROR = -1, SOCK_CLOSE = -2, SOCK_CLOSETIMEOUT = -3, SOCK_READTIMEOUT = -4, SOCK_WRITETIMEOUT = -5, SOCK_READERROR = -6, SOCK_WRITEERROR = -7, SOCK_SHUTERROR = -8, SOCK_BADREQUEST = -9, SOCK_ENTITYTOOLARGE = -10, SOCK_BADHEADER = -11, SOCK_TOOMANYHEADERS = -12 } SockState; /* * Subset for spooler states */ typedef enum { SPOOLER_CLOSE = SOCK_CLOSE, SPOOLER_OK = SOCK_READY, SPOOLER_READERROR = SOCK_READERROR, SPOOLER_WRITEERROR = SOCK_WRITEERROR, SPOOLER_CLOSETIMEOUT = SOCK_CLOSETIMEOUT } SpoolerState; typedef struct { SpoolerState spoolerState; SockState sockState; } SpoolerStateMap; /* * ServerMap maintains Host header to server mappings. */ typedef struct ServerMap { NsServer *servPtr; char location[1]; } ServerMap; /* * The following maintains the spooler state mapping */ static const SpoolerStateMap spoolerStateMap[] = { {SPOOLER_CLOSE, SOCK_CLOSE}, {SPOOLER_READERROR, SOCK_READERROR}, {SPOOLER_WRITEERROR, SOCK_WRITEERROR}, {SPOOLER_CLOSETIMEOUT, SOCK_CLOSETIMEOUT}, {SPOOLER_OK, SOCK_READY} }; /* * The following structure manages polling. The PollIn macro is * used for the common case of checking for readability. */ typedef struct PollData { unsigned int nfds; /* Number of fds being monitored. */ unsigned int maxfds; /* Max fds (will grow as needed). */ struct pollfd *pfds; /* Dynamic array of poll structs. */ Ns_Time timeout; /* Min timeout, if any, for next spin. */ } PollData; #define PollIn(ppd, i) (((ppd)->pfds[(i)].revents & POLLIN) == POLLIN ) #define PollOut(ppd, i) (((ppd)->pfds[(i)].revents & POLLOUT) == POLLOUT) #define PollHup(ppd, i) (((ppd)->pfds[(i)].revents & POLLHUP) == POLLHUP) /* * Collected informationof writer threads for per pool rates, necessary for * per pool bandwidth management. */ typedef struct ConnPoolInfo { size_t threadSlot; int currentPoolRate; int deltaPercentage; } ConnPoolInfo; /* * The following structure maintains writer socket */ typedef struct WriterSock { struct WriterSock *nextPtr; struct Sock *sockPtr; struct SpoolerQueue *queuePtr; struct Conn *connPtr; SpoolerState status; int err; int refCount; unsigned int flags; Tcl_WideInt nsent; size_t size; NsWriterStreamState doStream; int fd; char *headerString; struct ConnPool *poolPtr; union { struct { struct iovec *bufs; /* incoming bufs to be sent */ int nbufs; int bufIdx; struct iovec sbufs[UIO_SMALLIOV]; /* scratch bufs for handling partial sends */ int nsbufs; int sbufIdx; struct iovec preallocated_bufs[UIO_SMALLIOV]; struct FileMap fmap; } mem; struct { size_t maxsize; size_t bufsize; off_t bufoffset; size_t toRead; unsigned char *buf; Ns_FileVec *bufs; int nbufs; int currentbuf; Ns_Mutex fdlock; } file; } c; char *clientData; Ns_Time startTime; int rateLimit; int currentRate; ConnPoolInfo *infoPtr; bool keep; } WriterSock; /* * Async writer definitions */ typedef struct AsyncWriter { Ns_Mutex lock; /* Lock around writer queues */ SpoolerQueue *firstPtr; /* List of writer threads */ } AsyncWriter; /* * AsyncWriteData is similar to WriterSock */ typedef struct AsyncWriteData { struct AsyncWriteData *nextPtr; char *data; int fd; Tcl_WideInt nsent; size_t size; size_t bufsize; const char *buf; } AsyncWriteData; static AsyncWriter *asyncWriter = NULL; /* * Static functions defined in this file. */ static Ns_ThreadProc DriverThread; static Ns_ThreadProc SpoolerThread; static Ns_ThreadProc WriterThread; static Ns_ThreadProc AsyncWriterThread; static Tcl_ObjCmdProc WriterListObjCmd; static Tcl_ObjCmdProc WriterSizeObjCmd; static Tcl_ObjCmdProc WriterStreamingObjCmd; static Tcl_ObjCmdProc WriterSubmitObjCmd; static Tcl_ObjCmdProc WriterSubmitFileObjCmd; static Tcl_ObjCmdProc AsyncLogfileWriteObjCmd; static Tcl_ObjCmdProc AsyncLogfileOpenObjCmd; static Tcl_ObjCmdProc AsyncLogfileCloseObjCmd; static Ns_ReturnCode DriverWriterFromObj(Tcl_Interp *interp, Tcl_Obj *driverObj, Ns_Conn *conn, DrvWriter **wrPtrPtr) NS_GNUC_NONNULL(1) NS_GNUC_NONNULL(4); static NS_SOCKET DriverListen(Driver *drvPtr, const char *bindaddr) NS_GNUC_NONNULL(1) NS_GNUC_NONNULL(2); static NS_DRIVER_ACCEPT_STATUS DriverAccept(Sock *sockPtr, NS_SOCKET sock) NS_GNUC_NONNULL(1); static bool DriverKeep(Sock *sockPtr) NS_GNUC_NONNULL(1); static void DriverClose(Sock *sockPtr) NS_GNUC_NONNULL(1); static Ns_ReturnCode DriverInit(const char *server, const char *moduleName, const char *threadName, const Ns_DriverInitData *init, NsServer *servPtr, const char *path, const char *bindaddrs, const char *defserver, const char *host) NS_GNUC_NONNULL(2) NS_GNUC_NONNULL(3) NS_GNUC_NONNULL(4) NS_GNUC_NONNULL(6) NS_GNUC_NONNULL(7) NS_GNUC_NONNULL(9); static bool DriverModuleInitialized(const char *module) NS_GNUC_NONNULL(1); static void SockSetServer(Sock *sockPtr) NS_GNUC_NONNULL(1); static SockState SockAccept(Driver *drvPtr, NS_SOCKET sock, Sock **sockPtrPtr, const Ns_Time *nowPtr) NS_GNUC_NONNULL(1); static Ns_ReturnCode SockQueue(Sock *sockPtr, const Ns_Time *timePtr) NS_GNUC_NONNULL(1); static Sock *SockNew(Driver *drvPtr) NS_GNUC_NONNULL(1) NS_GNUC_RETURNS_NONNULL; static void SockRelease(Sock *sockPtr, SockState reason, int err) NS_GNUC_NONNULL(1); static void SockError(Sock *sockPtr, SockState reason, int err) NS_GNUC_NONNULL(1); static void SockSendResponse(Sock *sockPtr, int code, const char *errMsg) NS_GNUC_NONNULL(1) NS_GNUC_NONNULL(3); static void SockTrigger(NS_SOCKET sock); static void SockTimeout(Sock *sockPtr, const Ns_Time *nowPtr, const Ns_Time *timeout) NS_GNUC_NONNULL(1); static void SockClose(Sock *sockPtr, int keep) NS_GNUC_NONNULL(1); static SockState SockRead(Sock *sockPtr, int spooler, const Ns_Time *timePtr) NS_GNUC_NONNULL(1); static SockState SockParse(Sock *sockPtr) NS_GNUC_NONNULL(1); static void SockPoll(Sock *sockPtr, short type, PollData *pdata) NS_GNUC_NONNULL(1) NS_GNUC_NONNULL(3); static int SockSpoolerQueue(Driver *drvPtr, Sock *sockPtr) NS_GNUC_NONNULL(1) NS_GNUC_NONNULL(2); static void SpoolerQueueStart(SpoolerQueue *queuePtr, Ns_ThreadProc *proc) NS_GNUC_NONNULL(2); static void SpoolerQueueStop(SpoolerQueue *queuePtr, const Ns_Time *timeoutPtr, const char *name) NS_GNUC_NONNULL(2) NS_GNUC_NONNULL(3); static void PollCreate(PollData *pdata) NS_GNUC_NONNULL(1); static void PollFree(PollData *pdata) NS_GNUC_NONNULL(1); static void PollReset(PollData *pdata) NS_GNUC_NONNULL(1); static NS_POLL_NFDS_TYPE PollSet(PollData *pdata, NS_SOCKET sock, short type, const Ns_Time *timeoutPtr) NS_GNUC_NONNULL(1); static int PollWait(const PollData *pdata, int timeout) NS_GNUC_NONNULL(1); static bool ChunkedDecode(Request *reqPtr, bool update) NS_GNUC_NONNULL(1); static WriterSock *WriterSockRequire(const Conn *connPtr) NS_GNUC_NONNULL(1); static void WriterSockRelease(WriterSock *wrSockPtr) NS_GNUC_NONNULL(1); static SpoolerState WriterReadFromSpool(WriterSock *curPtr) NS_GNUC_NONNULL(1); static SpoolerState WriterSend(WriterSock *curPtr, int *err) NS_GNUC_NONNULL(1) NS_GNUC_NONNULL(2); static Ns_ReturnCode WriterSetupStreamingMode(Conn *connPtr, struct iovec *bufs, int nbufs, int *fdPtr) NS_GNUC_NONNULL(1) NS_GNUC_NONNULL(2) NS_GNUC_NONNULL(4); static void WriterSockFileVecCleanup(WriterSock *wrSockPtr) NS_GNUC_NONNULL(1); static int WriterGetMemunitFromDict(Tcl_Interp *interp, Tcl_Obj *dictObj, Tcl_Obj *keyObj, Ns_ObjvValueRange *rangePtr, Tcl_WideInt *valuePtr) NS_GNUC_NONNULL(1) NS_GNUC_NONNULL(2) NS_GNUC_NONNULL(3) NS_GNUC_NONNULL(5); static void AsyncWriterRelease(AsyncWriteData *wdPtr) NS_GNUC_NONNULL(1); static void WriteWarningRaw(const char *msg, int fd, size_t wantWrite, ssize_t written) NS_GNUC_NONNULL(1); static const char *GetSockStateName(SockState sockState); static size_t EndOfHeader(Sock *sockPtr) NS_GNUC_NONNULL(1); static void RequestNew(Sock *sockPtr) NS_GNUC_NONNULL(1); static void RequestFree(Sock *sockPtr) NS_GNUC_NONNULL(1); static void LogBuffer(Ns_LogSeverity severity, const char *msg, const char *buffer, size_t len) NS_GNUC_NONNULL(2) NS_GNUC_NONNULL(3); static void ServerMapEntryAdd(Tcl_DString *dsPtr, const char *host, NsServer *servPtr, Driver *drvPtr, bool addDefaultMapEntry) NS_GNUC_NONNULL(1) NS_GNUC_NONNULL(2) NS_GNUC_NONNULL(3) NS_GNUC_NONNULL(4); static Driver *LookupDriver(Tcl_Interp *interp, const char* protocol, const char *driverName) NS_GNUC_NONNULL(1) NS_GNUC_NONNULL(2); static void WriterPerPoolRates(WriterSock *writePtr, Tcl_HashTable *pools) NS_GNUC_NONNULL(1) NS_GNUC_NONNULL(2); static ConnPoolInfo *WriterGetInfoPtr(WriterSock *curPtr, Tcl_HashTable *pools) NS_GNUC_NONNULL(1) NS_GNUC_NONNULL(2); /* * Global variables defined in this file. */ //NS_EXTERN Ns_LogSeverity Ns_LogAccessDebug; Ns_LogSeverity Ns_LogTaskDebug; Ns_LogSeverity Ns_LogRequestDebug; Ns_LogSeverity Ns_LogConnchanDebug; Ns_LogSeverity Ns_LogUrlspaceDebug; Ns_LogSeverity Ns_LogAccessDebug; Ns_LogSeverity Ns_LogTimeoutDebug; NS_EXPORT Ns_LogSeverity Ns_LogAccessDebug; bool NsWriterBandwidthManagement = NS_FALSE; static Ns_LogSeverity WriterDebug; /* Severity at which to log verbose debugging. */ static Ns_LogSeverity DriverDebug; /* Severity at which to log verbose debugging. */ static Ns_Mutex reqLock = NULL; /* Lock for allocated Request structure pool */ static Ns_Mutex writerlock = NULL; /* Lock updating streaming information in the writer */ static Request *firstReqPtr = NULL; /* Allocated request structures kept in a pool */ static Driver *firstDrvPtr = NULL; /* First in list of all drivers */ #define Push(x, xs) ((x)->nextPtr = (xs), (xs) = (x)) /* *---------------------------------------------------------------------- * * WriteWarningRaw -- * * Write a warning message to stderr. This function is for cases, where * writing to Ns_Log can't be used (e.g. in the AsyncWriter, which is * used for writing also to the system log). * * Results: * None. * * Side effects: * Line to stderr. * *---------------------------------------------------------------------- */ static void WriteWarningRaw(const char *msg, int fd, size_t wantWrite, ssize_t written) { fprintf(stderr, "%s: Warning: wanted to write %" PRIuz " bytes, wrote %ld to file descriptor %d\n", msg, wantWrite, (long)written, fd); } /* *---------------------------------------------------------------------- * * GetSockStateName -- * * Return human readable names for StockState values. * * Results: * string * * Side effects: * None. * *---------------------------------------------------------------------- */ static const char * GetSockStateName(SockState sockState) { int sockStateInt = (int)sockState; static const char *sockStateStrings[] = { "SOCK_READY", "SOCK_MORE", "SOCK_SPOOL", "SOCK_ERROR", "SOCK_CLOSE", "SOCK_CLOSETIMEOUT", "SOCK_READTIMEOUT", "SOCK_WRITETIMEOUT", "SOCK_READERROR", "SOCK_WRITEERROR", "SOCK_SHUTERROR", "SOCK_BADREQUEST", "SOCK_ENTITYTOOLARGE", "SOCK_BADHEADER", "SOCK_TOOMANYHEADERS", NULL }; if (sockStateInt < 0) { sockStateInt = (- sockStateInt) + 2; } assert(sockStateInt < Ns_NrElements(sockStateStrings)); return sockStateStrings[sockStateInt]; } /* *---------------------------------------------------------------------- * * NsInitDrivers -- * * Init drivers system. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------- */ void NsInitDrivers(void) { DriverDebug = Ns_CreateLogSeverity("Debug(ns:driver)"); WriterDebug = Ns_CreateLogSeverity("Debug(writer)"); Ns_LogTaskDebug = Ns_CreateLogSeverity("Debug(task)"); Ns_LogRequestDebug = Ns_CreateLogSeverity("Debug(request)"); Ns_LogConnchanDebug = Ns_CreateLogSeverity("Debug(connchan)"); Ns_LogUrlspaceDebug = Ns_CreateLogSeverity("Debug(urlspace)"); Ns_LogAccessDebug = Ns_CreateLogSeverity("Debug(access)"); Ns_LogTimeoutDebug = Ns_CreateLogSeverity("Debug(timeout)"); Ns_MutexInit(&reqLock); Ns_MutexInit(&writerlock); Ns_MutexSetName2(&reqLock, "ns:driver", "requestpool"); Ns_MutexSetName2(&writerlock, "ns:writer", "stream"); } /* *---------------------------------------------------------------------- * * DriverModuleInitialized -- * * Check if a driver with the specified name is already initialized. * * Results: * Boolean * * Side effects: * None. * *---------------------------------------------------------------------- */ static bool DriverModuleInitialized(const char *module) { Driver *drvPtr; bool found = NS_FALSE; NS_NONNULL_ASSERT(module != NULL); for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) { if (strcmp(drvPtr->moduleName, module) == 0) { found = NS_TRUE; Ns_Log(Notice, "Driver %s is already initialized", module); break; } } return found; } /* *---------------------------------------------------------------------- * * Ns_DriverInit -- * * Initialize a driver. * * Results: * NS_OK if initialized, NS_ERROR if config or other error. * * Side effects: * Listen socket will be opened later in NsStartDrivers. * *---------------------------------------------------------------------- */ Ns_ReturnCode Ns_DriverInit(const char *server, const char *module, const Ns_DriverInitData *init) { Ns_ReturnCode status = NS_OK; NsServer *servPtr = NULL; bool alreadyInitialized = NS_FALSE; NS_NONNULL_ASSERT(module != NULL); NS_NONNULL_ASSERT(init != NULL); /* * If a server is provided, servPtr must be set. */ if (server != NULL) { servPtr = NsGetServer(server); if (unlikely(servPtr == NULL)) { Ns_Log(Bug, "cannot lookup server structure for server: %s", module); status = NS_ERROR; } } else { alreadyInitialized = DriverModuleInitialized(module); } /* * Check versions of drivers. */ if (status == NS_OK && init->version < NS_DRIVER_VERSION_4) { Ns_Log(Warning, "%s: driver version is too old (version %d), Version 4 is recommended", module, init->version); } #ifdef HAVE_IPV6 if (status == NS_OK && init->version < NS_DRIVER_VERSION_3) { Ns_Log(Error, "%s: driver version is too old (version %d) and does not support IPv6", module, init->version); status = NS_ERROR; } #endif if (status == NS_OK && init->version < NS_DRIVER_VERSION_2) { Ns_Log(Error, "%s: version field of driver is invalid: %d", module, init->version); status = NS_ERROR; } if (!alreadyInitialized && status == NS_OK) { const char *path, *host, *address, *defserver; bool noHostNameGiven; int nrDrivers, nrBindaddrs = 0, result; Ns_Set *set; Tcl_Obj *bindaddrsObj, **objv; path = ((init->path != NULL) ? init->path : Ns_ConfigGetPath(server, module, (char *)0L)); set = Ns_ConfigCreateSection(path); /* * Determine the "defaultserver" the "hostname" / "address" for * binding to and/or the HTTP location string. */ defserver = Ns_ConfigGetValue(path, "defaultserver"); address = Ns_ConfigGetValue(path, "address"); host = Ns_ConfigGetValue(path, "hostname"); noHostNameGiven = (host == NULL); /* * If the listen address was not specified, attempt to determine it * through a DNS lookup of the specified hostname or the server's * primary hostname. */ if (address == NULL) { Tcl_DString ds; Tcl_DStringInit(&ds); if (noHostNameGiven) { host = Ns_InfoHostname(); } if (Ns_GetAllAddrByHost(&ds, host) == NS_TRUE) { address = ns_strdup(Tcl_DStringValue(&ds)); if (path != NULL) { Ns_SetUpdate(set, "address", address); } Ns_Log(Notice, "no address given, obtained address '%s' from host name %s", address, host); } Tcl_DStringFree(&ds); } if (address == NULL) { address = NS_IP_UNSPECIFIED; Ns_Log(Notice, "no address given, set address to unspecified address %s", address); } bindaddrsObj = Tcl_NewStringObj(address, -1); result = Tcl_ListObjGetElements(NULL, bindaddrsObj, &nrBindaddrs, &objv); if (result != TCL_OK || nrBindaddrs < 1 || nrBindaddrs >= MAX_LISTEN_ADDR_PER_DRIVER) { Ns_Fatal("%s: bindaddrs '%s' is not a valid Tcl list containing addresses (max %d)", module, address, MAX_LISTEN_ADDR_PER_DRIVER); } Tcl_IncrRefCount(bindaddrsObj); /* * If the hostname was not specified and not determined by the lookup * above, set it to the first specified or derived IP address string. */ if (host == NULL) { host = ns_strdup(Tcl_GetString(objv[0])); } if (noHostNameGiven && host != NULL && path != NULL) { Ns_SetUpdate(set, "hostname", host); } Tcl_DecrRefCount(bindaddrsObj); /* * Get configured number of driver threads. */ nrDrivers = Ns_ConfigIntRange(path, "driverthreads", 1, 1, 64); if (nrDrivers > 1) { #if !defined(SO_REUSEPORT) Ns_Log(Warning, "server %s module %s requests %d driverthreads, but is not supported by the operating system", server, module, nrDrivers); Ns_SetUpdate(set, "driverthreads", "1"); nrDrivers = 1; #endif } /* * The common parameters are determined, create the driver thread(s) */ { size_t maxModuleNameLength = strlen(module) + (size_t)TCL_INTEGER_SPACE + 1u; char *moduleName = ns_malloc(maxModuleNameLength); int i; if (host == NULL) { host = Ns_InfoHostname(); } for (i = 0; i < nrDrivers; i++) { snprintf(moduleName, maxModuleNameLength, "%s:%d", module, i); status = DriverInit(server, module, moduleName, init, servPtr, path, address, defserver, host); if (status != NS_OK) { break; } } ns_free(moduleName); } } return status; } /* *---------------------------------------------------------------------- * * ServerMapEntryAdd -- * * Add an entry to the virtual server map. The entry consists of the * value as provided by the host header field and location string, * containing as well the protocol. * * Results: * None * * Side effects: * Potentially adding an entry to the virtual server map. * *---------------------------------------------------------------------- */ static void ServerMapEntryAdd(Tcl_DString *dsPtr, const char *host, NsServer *servPtr, Driver *drvPtr, bool addDefaultMapEntry) { Tcl_HashEntry *hPtr; int isNew; NS_NONNULL_ASSERT(dsPtr != NULL); NS_NONNULL_ASSERT(host != NULL); NS_NONNULL_ASSERT(servPtr != NULL); NS_NONNULL_ASSERT(drvPtr != NULL); hPtr = Tcl_CreateHashEntry(&drvPtr->hosts, host, &isNew); if (isNew != 0) { ServerMap *mapPtr; (void) Ns_DStringVarAppend(dsPtr, drvPtr->protocol, "://", host, (char *)0L); mapPtr = ns_malloc(sizeof(ServerMap) + (size_t)dsPtr->length); mapPtr->servPtr = servPtr; memcpy(mapPtr->location, dsPtr->string, (size_t)dsPtr->length + 1u); Tcl_SetHashValue(hPtr, mapPtr); Ns_Log(Notice, "%s: adding virtual host entry for host <%s> location: %s mapped to server: %s", drvPtr->threadName, host, mapPtr->location, servPtr->server); if (addDefaultMapEntry) { drvPtr->defMapPtr = mapPtr; } /* * Always reset the Tcl_DString */ Ns_DStringSetLength(dsPtr, 0); } else { Ns_Log(Notice, "%s: ignore duplicate virtual host entry: %s", drvPtr->threadName, host); } } /* *---------------------------------------------------------------------- * * NsDriverMapVirtualServers -- * * Map "Host:" headers for drivers not bound to physical servers. This * function has to be called a time, when all servers are already defined * such that NsGetServer(server) can succeed. * * Results: * None. * * Side effects: * Add an entry to the virtual server map via ServerMapEntryAdd() * *---------------------------------------------------------------------- */ void NsDriverMapVirtualServers(void) { Driver *drvPtr; for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) { const Ns_Set *lset; size_t j; Tcl_DString ds, *dsPtr = &ds; const char *path, *defserver, *moduleName; moduleName = drvPtr->moduleName; defserver = drvPtr->defserver; /* * Check for a "/servers" section for this driver module. */ path = Ns_ConfigGetPath(NULL, moduleName, "servers", (char *)0L); lset = Ns_ConfigGetSection(path); if (lset == NULL || Ns_SetSize(lset) == 0u) { /* * The driver module has no (or empty) ".../servers" section. * There is no mapping from host name to virtual server defined. */ if (drvPtr->server == NULL) { /* * We have a global driver module. If there is at least a * default server configured, we can use this for the mapping * to the default server. */ if (defserver != NULL) { NsServer *servPtr = NsGetServer(defserver); Tcl_DStringInit(dsPtr); ServerMapEntryAdd(dsPtr, Ns_InfoHostname(), servPtr, drvPtr, NS_TRUE); Tcl_DStringFree(dsPtr); Ns_Log(Notice, "Global driver has no mapping from host to server (section '%s' missing)", moduleName); } else { /* * Global driver, which has no default server, and no servers section. */ Ns_Fatal("%s: virtual servers configured," " but '%s' has no defaultserver defined", moduleName, path); } } continue; } /* * We have a ".../servers" section, the driver might be global or * local. It is not clear, why we need the server map for the local * driver, but for compatibility, we keep this. * */ if (defserver == NULL) { if (drvPtr->server != NULL) { /* * We have a local (server specific) driver. Since the code * below assumes that we have a "defserver" set, we take the * actual server as defserver. */ defserver = drvPtr->server; } else { /* * We have a global driver, but no defserver. */ Ns_Fatal("%s: virtual servers configured," " but '%s' has no defaultserver defined", moduleName, path); } } assert(defserver != NULL); drvPtr->defMapPtr = NULL; Ns_DStringInit(dsPtr); for (j = 0u; j < Ns_SetSize(lset); ++j) { const char *server = Ns_SetKey(lset, j); const char *host = Ns_SetValue(lset, j); NsServer *servPtr; /* * Perform an explicit lookup of the server. */ servPtr = NsGetServer(server); if (servPtr == NULL) { Ns_Log(Error, "%s: no such server: %s", moduleName, server); } else { char *writableHost, *hostName, *portStart; writableHost = ns_strdup(host); Ns_HttpParseHost(writableHost, &hostName, &portStart); if (portStart == NULL) { Tcl_DString hostDString; /* * The provided host entry does NOT contain a port. * * Add the provided entry to the virtual server map only, * when the configured port is the default port for the * protocol. */ if (drvPtr->port == drvPtr->defport) { ServerMapEntryAdd(dsPtr, host, servPtr, drvPtr, STREQ(defserver, server)); } /* * Auto-add configured port: Add always an entry with the * explicitly configured port of the driver. */ Tcl_DStringInit(&hostDString); Tcl_DStringAppend(&hostDString, host, -1); (void) Ns_DStringPrintf(&hostDString, ":%hu", drvPtr->port); ServerMapEntryAdd(dsPtr, hostDString.string, servPtr, drvPtr, STREQ(defserver, server)); Tcl_DStringFree(&hostDString); } else { /* * The provided host entry does contain a port. * * In case, the provided port is equal to the configured port * of the driver, add an entry. */ unsigned short providedPort = (unsigned short)strtol(portStart+1, NULL, 10); if (providedPort == drvPtr->port) { ServerMapEntryAdd(dsPtr, host, servPtr, drvPtr, STREQ(defserver, server)); /* * In case, the provided port is equal to the default * port of the driver, make sure that we have an entry * without the port. */ if (providedPort == drvPtr->defport) { ServerMapEntryAdd(dsPtr, hostName, servPtr, drvPtr, STREQ(defserver, server)); } } else { Ns_Log(Warning, "%s: driver is listening on port %hu; " "virtual host entry %s ignored", moduleName, drvPtr->port, host); } } ns_free(writableHost); } } Ns_DStringFree(dsPtr); if (drvPtr->defMapPtr == NULL) { fprintf(stderr, "--- Server Map: ---\n"); Ns_SetPrint(lset); Ns_Fatal("%s: default server '%s' not defined in '%s'", moduleName, defserver, path); } } } /* *---------------------------------------------------------------------- * * DriverInit -- * * Helper function of Ns_DriverInit. This function actually allocates and * initialized the driver structure. * * Results: * NS_OK if initialized, NS_ERROR if config or other error. * * Side effects: * Listen socket will be opened later in NsStartDrivers. * *---------------------------------------------------------------------- */ static Ns_ReturnCode DriverInit(const char *server, const char *moduleName, const char *threadName, const Ns_DriverInitData *init, NsServer *servPtr, const char *path, const char *bindaddrs, const char *defserver, const char *host) { const char *defproto; Driver *drvPtr; DrvWriter *wrPtr; DrvSpooler *spPtr; int i; unsigned short defport; NS_NONNULL_ASSERT(threadName != NULL); NS_NONNULL_ASSERT(init != NULL); NS_NONNULL_ASSERT(path != NULL); NS_NONNULL_ASSERT(bindaddrs != NULL); NS_NONNULL_ASSERT(host != NULL); /* * Set the protocol and port defaults. */ if (init->protocol != NULL) { defproto = init->protocol; defport = init->defaultPort; } else { defproto = "unknown"; defport = 0u; } Ns_Log(DriverDebug, "DriverInit server <%s> threadName %s proto %s port %hu", server, threadName, defproto, defport); /* * Allocate a new driver instance and set configurable parameters. */ drvPtr = ns_calloc(1u, sizeof(Driver)); Ns_MutexInit(&drvPtr->lock); Ns_MutexSetName2(&drvPtr->lock, "ns:drv", threadName); Ns_MutexInit(&drvPtr->spooler.lock); Ns_MutexSetName2(&drvPtr->spooler.lock, "ns:drv:spool", threadName); Ns_MutexInit(&drvPtr->writer.lock); Ns_MutexSetName2(&drvPtr->writer.lock, "ns:drv:writer", threadName); if (ns_sockpair(drvPtr->trigger) != 0) { Ns_Fatal("ns_sockpair() failed: %s", ns_sockstrerror(ns_sockerrno)); } drvPtr->server = server; drvPtr->type = init->name; drvPtr->moduleName = ns_strdup(moduleName); drvPtr->threadName = ns_strdup(threadName); drvPtr->defserver = defserver; drvPtr->listenProc = init->listenProc; drvPtr->acceptProc = init->acceptProc; drvPtr->recvProc = init->recvProc; drvPtr->sendProc = init->sendProc; drvPtr->sendFileProc = init->sendFileProc; drvPtr->keepProc = init->keepProc; drvPtr->requestProc = init->requestProc; drvPtr->closeProc = init->closeProc; drvPtr->clientInitProc = init->clientInitProc; drvPtr->arg = init->arg; drvPtr->opts = init->opts; drvPtr->servPtr = servPtr; drvPtr->defport = defport; drvPtr->bufsize = (size_t)Ns_ConfigMemUnitRange(path, "bufsize", 16384, 1024, INT_MAX); drvPtr->maxinput = Ns_ConfigMemUnitRange(path, "maxinput", 1024*1024, 1024, LLONG_MAX); drvPtr->maxupload = Ns_ConfigMemUnitRange(path, "maxupload", 0, 0, (Tcl_WideInt)drvPtr->maxinput); drvPtr->readahead = Ns_ConfigMemUnitRange(path, "readahead", (Tcl_WideInt)drvPtr->bufsize, (Tcl_WideInt)drvPtr->bufsize, drvPtr->maxinput); drvPtr->maxline = Ns_ConfigIntRange(path, "maxline", 8192, 256, INT_MAX); drvPtr->maxheaders = Ns_ConfigIntRange(path, "maxheaders", 128, 8, INT_MAX); drvPtr->maxqueuesize = Ns_ConfigIntRange(path, "maxqueuesize", 1024, 1, INT_MAX); Ns_ConfigTimeUnitRange(path, "sendwait", "30s", 1, 0, INT_MAX, 0, &drvPtr->sendwait); Ns_ConfigTimeUnitRange(path, "recvwait", "30s", 1, 0, INT_MAX, 0, &drvPtr->recvwait); Ns_ConfigTimeUnitRange(path, "closewait", "2s", 0, 0, INT_MAX, 0, &drvPtr->closewait); Ns_ConfigTimeUnitRange(path, "keepwait", "5s", 0, 0, INT_MAX, 0, &drvPtr->keepwait); drvPtr->backlog = Ns_ConfigIntRange(path, "backlog", 256, 1, INT_MAX); drvPtr->driverthreads = Ns_ConfigIntRange(path, "driverthreads", 1, 1, 32); drvPtr->reuseport = Ns_ConfigBool(path, "reuseport", NS_FALSE); drvPtr->acceptsize = Ns_ConfigIntRange(path, "acceptsize", drvPtr->backlog, 1, INT_MAX); drvPtr->keepmaxuploadsize = (size_t)Ns_ConfigMemUnitRange(path, "keepalivemaxuploadsize", 0, 0, INT_MAX); drvPtr->keepmaxdownloadsize = (size_t)Ns_ConfigMemUnitRange(path, "keepalivemaxdownloadsize", 0, 0, INT_MAX); drvPtr->recvTimeout = drvPtr->recvwait; Tcl_InitHashTable(&drvPtr->hosts, TCL_STRING_KEYS); if (drvPtr->driverthreads > 1) { #if !defined(SO_REUSEPORT) drvPtr->driverthreads = 1; drvPtr->reuseport = NS_FALSE; #else /* * When driver threads > 1, "reuseport" has to be active. */ drvPtr->reuseport = NS_TRUE; #endif } if (drvPtr->reuseport) { /* * Reuseport was specified */ #if !defined(SO_REUSEPORT) Ns_Log(Warning, "parameter %s reuseport was specified, but is not supported by the operating system", path); drvPtr->reuseport = NS_FALSE; #endif } drvPtr->uploadpath = ns_strdup(Ns_ConfigString(path, "uploadpath", nsconf.tmpDir)); /* * If activated, "maxupload" has to be at least "readahead" bytes. Tell * the user in case the config values are overruled. */ if ((drvPtr->maxupload > 0) && (drvPtr->maxupload < drvPtr->readahead)) { Ns_Log(Warning, "parameter %s maxupload % " TCL_LL_MODIFIER "d invalid; can be either 0 or must be >= %" TCL_LL_MODIFIER "d (size of readahead)", path, drvPtr->maxupload, drvPtr->readahead); drvPtr->maxupload = drvPtr->readahead; } /* * Determine the port and then set the HTTP location string either * as specified in the config file or constructed from the * protocol, hostname and port. */ drvPtr->protocol = ns_strdup(defproto); drvPtr->address = ns_strdup(bindaddrs); drvPtr->port = (unsigned short)Ns_ConfigIntRange(path, "port", (int)defport, 0, 65535); drvPtr->location = Ns_ConfigGetValue(path, "location"); if (drvPtr->location != NULL && (strstr(drvPtr->location, "://") != NULL)) { drvPtr->location = ns_strdup(drvPtr->location); } else { Tcl_DString ds, *dsPtr = &ds; Ns_DStringInit(dsPtr); Ns_HttpLocationString(dsPtr, drvPtr->protocol, host, drvPtr->port, defport); drvPtr->location = Ns_DStringExport(dsPtr); } drvPtr->nextPtr = firstDrvPtr; firstDrvPtr = drvPtr; /* * Add driver specific extra headers. */ drvPtr->extraHeaders = Ns_ConfigSet(path, "extraheaders"); /* * Check if upload spooler are enabled */ spPtr = &drvPtr->spooler; spPtr->threads = Ns_ConfigIntRange(path, "spoolerthreads", 0, 0, 32); if (spPtr->threads > 0) { Ns_Log(Notice, "%s: enable %d spooler thread(s) " "for uploads >= %" TCL_LL_MODIFIER "d bytes", threadName, spPtr->threads, drvPtr->readahead); for (i = 0; i < spPtr->threads; i++) { SpoolerQueue *queuePtr = ns_calloc(1u, sizeof(SpoolerQueue)); char buffer[100]; snprintf(buffer, sizeof(buffer), "ns:driver:spooler:%d", i); Ns_MutexSetName2(&queuePtr->lock, buffer, "queue"); queuePtr->id = i; Push(queuePtr, spPtr->firstPtr); } } else { Ns_Log(Notice, "%s: enable %d spooler thread(s) ", threadName, spPtr->threads); } /* * Enable writer threads */ wrPtr = &drvPtr->writer; wrPtr->threads = Ns_ConfigIntRange(path, "writerthreads", 0, 0, 32); if (wrPtr->threads > 0) { wrPtr->writersize = (size_t)Ns_ConfigMemUnitRange(path, "writersize", 1024*1024, 1024, INT_MAX); wrPtr->bufsize = (size_t)Ns_ConfigMemUnitRange(path, "writerbufsize", 8192, 512, INT_MAX); wrPtr->rateLimit = Ns_ConfigIntRange(path, "writerratelimit", 0, 0, INT_MAX); wrPtr->doStream = Ns_ConfigBool(path, "writerstreaming", NS_FALSE) ? NS_WRITER_STREAM_ACTIVE : NS_WRITER_STREAM_NONE; Ns_Log(Notice, "%s: enable %d writer thread(s) " "for downloads >= %" PRIdz " bytes, bufsize=%" PRIdz " bytes, HTML streaming %d", threadName, wrPtr->threads, wrPtr->writersize, wrPtr->bufsize, wrPtr->doStream); for (i = 0; i < wrPtr->threads; i++) { SpoolerQueue *queuePtr = ns_calloc(1u, sizeof(SpoolerQueue)); char buffer[100]; snprintf(buffer, sizeof(buffer), "ns:driver:writer:%d", i); Ns_MutexSetName2(&queuePtr->lock, buffer, "queue"); queuePtr->id = i; Push(queuePtr, wrPtr->firstPtr); } } else { Ns_Log(Notice, "%s: enable %d writer thread(s) ", threadName, wrPtr->threads); } return NS_OK; } /* *---------------------------------------------------------------------- * * NsStartDrivers -- * * Listen on all driver address/ports and start the DriverThread. * * Results: * None. * * Side effects: * See DriverThread. * *---------------------------------------------------------------------- */ void NsStartDrivers(void) { Driver *drvPtr; /* * Signal and wait for each driver to start. */ for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) { if (drvPtr->port == 0u) { /* * Don't start a driver having port zero. */ continue; } Ns_ThreadCreate(DriverThread, drvPtr, 0, &drvPtr->thread); Ns_MutexLock(&drvPtr->lock); while ((drvPtr->flags & DRIVER_STARTED) == 0u) { Ns_CondWait(&drvPtr->cond, &drvPtr->lock); } /*if ((drvPtr->flags & DRIVER_FAILED)) { status = NS_ERROR; }*/ Ns_MutexUnlock(&drvPtr->lock); } } /* *---------------------------------------------------------------------- * * NsStopDrivers -- * * Trigger the DriverThread to begin shutdown. * * Results: * None. * * Side effects: * DriverThread will close listen sockets and then exit after all * outstanding connections are complete and closed. * *---------------------------------------------------------------------- */ void NsStopDrivers(void) { Driver *drvPtr; NsAsyncWriterQueueDisable(NS_TRUE); for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) { Tcl_HashEntry *hPtr; Tcl_HashSearch search; if ((drvPtr->flags & DRIVER_STARTED) == 0u) { continue; } Ns_MutexLock(&drvPtr->lock); Ns_Log(Notice, "[driver:%s]: stopping", drvPtr->threadName); drvPtr->flags |= DRIVER_SHUTDOWN; Ns_CondBroadcast(&drvPtr->cond); Ns_MutexUnlock(&drvPtr->lock); SockTrigger(drvPtr->trigger[1]); hPtr = Tcl_FirstHashEntry(&drvPtr->hosts, &search); while (hPtr != NULL) { Tcl_DeleteHashEntry(hPtr); hPtr = Tcl_NextHashEntry(&search); } } } void NsStopSpoolers(void) { const Driver *drvPtr; Ns_Log(Notice, "driver: stopping writer and spooler threads"); /* * Shutdown all spooler and writer threads */ for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) { Ns_Time timeout; if ((drvPtr->flags & DRIVER_STARTED) == 0u) { continue; } Ns_GetTime(&timeout); Ns_IncrTime(&timeout, nsconf.shutdowntimeout.sec, nsconf.shutdowntimeout.usec); SpoolerQueueStop(drvPtr->writer.firstPtr, &timeout, "writer"); SpoolerQueueStop(drvPtr->spooler.firstPtr, &timeout, "spooler"); } } /* *---------------------------------------------------------------------- * * DriverInfoObjCmd -- * * Return public info of all drivers. * Subcommand of NsTclDriverObjCmd. * * Results: * Standard Tcl Result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int DriverInfoObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { int result = TCL_OK; if (Ns_ParseObjv(NULL, NULL, interp, 2, objc, objv) != NS_OK) { result = TCL_ERROR; } else { const Driver *drvPtr; Tcl_Obj *resultObj = Tcl_NewListObj(0, NULL); Tcl_HashTable driverNames; /* names of the driver modules without duplicates */ Tcl_InitHashTable(&driverNames, TCL_STRING_KEYS); /* * Iterate over all modules, not necessarily all driver threads */ for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) { int isNew = 0; (void)Tcl_CreateHashEntry(&driverNames, drvPtr->moduleName, &isNew); if (isNew == 1) { Tcl_Obj *listObj = Tcl_NewListObj(0, NULL); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("module", 6)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj(drvPtr->moduleName, -1)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("type", 4)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj(drvPtr->type, -1)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("server", 6)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj(drvPtr->server != NULL ? drvPtr->server : NS_EMPTY_STRING, -1)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("location", 8)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj(drvPtr->location, -1)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("address", 7)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj(drvPtr->address, -1)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("protocol", 8)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj(drvPtr->protocol, -1)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("sendwait", 8)); Tcl_ListObjAppendElement(interp, listObj, Ns_TclNewTimeObj(&drvPtr->sendwait)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("recvwait", 8)); Tcl_ListObjAppendElement(interp, listObj, Ns_TclNewTimeObj(&drvPtr->sendwait)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("extraheaders", 12)); if (drvPtr->extraHeaders != NULL) { Tcl_DString ds; Tcl_DStringInit(&ds); Ns_DStringAppendSet(&ds, drvPtr->extraHeaders); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj(ds.string, ds.length)); Tcl_DStringFree(&ds); } else { Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("", 0)); } Tcl_ListObjAppendElement(interp, resultObj, listObj); } } Tcl_SetObjResult(interp, resultObj); Tcl_DeleteHashTable(&driverNames); } return result; } /* *---------------------------------------------------------------------- * * DriverStatsObjCmd -- * * Return statistics of all drivers. * Subcommand of NsTclDriverObjCmd. * * Results: * Standard Tcl Result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int DriverStatsObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { int result = TCL_OK; if (Ns_ParseObjv(NULL, NULL, interp, 2, objc, objv) != NS_OK) { result = TCL_ERROR; } else { const Driver *drvPtr; Tcl_Obj *resultObj = Tcl_NewListObj(0, NULL); /* * Iterate over all drivers and collect results. */ for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) { Tcl_Obj *listObj = Tcl_NewListObj(0, NULL); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("thread", 6)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj(drvPtr->threadName, -1)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("module", 6)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj(drvPtr->moduleName, -1)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("received", 8)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewWideIntObj(drvPtr->stats.received)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("spooled", 7)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewWideIntObj(drvPtr->stats.spooled)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("partial", 7)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewWideIntObj(drvPtr->stats.partial)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("errors", 6)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewWideIntObj(drvPtr->stats.errors)); Tcl_ListObjAppendElement(interp, resultObj, listObj); } Tcl_SetObjResult(interp, resultObj); } return result; } /* *---------------------------------------------------------------------- * * DriverThreadsObjCmd -- * * Return the names of driver threads * * Results: * Standard Tcl Result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int DriverThreadsObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { int result = TCL_OK; if (Ns_ParseObjv(NULL, NULL, interp, 2, objc, objv) != NS_OK) { result = TCL_ERROR; } else { const Driver *drvPtr; Tcl_Obj *resultObj = Tcl_NewListObj(0, NULL); /* * Iterate over all drivers and collect results. */ for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) { Tcl_ListObjAppendElement(interp, resultObj, Tcl_NewStringObj(drvPtr->threadName, -1)); } Tcl_SetObjResult(interp, resultObj); } return result; } /* *---------------------------------------------------------------------- * * DriverNamesObjCmd -- * * Return the names of drivers. * * Results: * Standard Tcl Result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int DriverNamesObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { int result = TCL_OK; if (Ns_ParseObjv(NULL, NULL, interp, 2, objc, objv) != NS_OK) { result = TCL_ERROR; } else { const Driver *drvPtr; Tcl_Obj *resultObj = Tcl_NewListObj(0, NULL); Tcl_HashTable driverNames; /* names of the drivers without duplicates */ Tcl_InitHashTable(&driverNames, TCL_STRING_KEYS); /* * Iterate over all drivers and collect results. */ for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) { int isNew; (void)Tcl_CreateHashEntry(&driverNames, drvPtr->moduleName, &isNew); if (isNew == 1) { Tcl_ListObjAppendElement(interp, resultObj, Tcl_NewStringObj(drvPtr->moduleName, -1)); } } Tcl_SetObjResult(interp, resultObj); Tcl_DeleteHashTable(&driverNames); } return result; } /* *---------------------------------------------------------------------- * * NsTclDriverObjCmd - * * Give information about drivers. Currently, just the statistics. * * Results: * Standard Tcl result. * * Side effects: * None. * *---------------------------------------------------------------------- */ int NsTclDriverObjCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { const Ns_SubCmdSpec subcmds[] = { {"info", DriverInfoObjCmd}, {"names", DriverNamesObjCmd}, {"threads", DriverThreadsObjCmd}, {"stats", DriverStatsObjCmd}, {NULL, NULL} }; return Ns_SubcmdObjv(subcmds, clientData, interp, objc, objv); } /* *---------------------------------------------------------------------- * * NsWakeupDriver -- * * Wake up the associated DriverThread. * * Results: * None. * * Side effects: * The poll waiting for this trigger will be interrupted. * *---------------------------------------------------------------------- */ void NsWakeupDriver(const Driver *drvPtr) { NS_NONNULL_ASSERT(drvPtr != NULL); SockTrigger(drvPtr->trigger[1]); } /* *---------------------------------------------------------------------- * * NsWaitDriversShutdown -- * * Wait for exit of DriverThread. This callback is invoked later * by the timed shutdown thread. * * Results: * None. * * Side effects: * Driver thread is joined and trigger pipe closed. * *---------------------------------------------------------------------- */ void NsWaitDriversShutdown(const Ns_Time *toPtr) { Driver *drvPtr; Ns_ReturnCode status = NS_OK; for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) { if ((drvPtr->flags & DRIVER_STARTED) == 0u) { continue; } Ns_MutexLock(&drvPtr->lock); while ((drvPtr->flags & DRIVER_STOPPED) == 0u && status == NS_OK) { status = Ns_CondTimedWait(&drvPtr->cond, &drvPtr->lock, toPtr); } Ns_MutexUnlock(&drvPtr->lock); if (status != NS_OK) { Ns_Log(Warning, "[driver:%s]: shutdown timeout", drvPtr->threadName); } else { Ns_Log(Notice, "[driver:%s]: stopped", drvPtr->threadName); Ns_ThreadJoin(&drvPtr->thread, NULL); drvPtr->thread = NULL; } } } /* *---------------------------------------------------------------------- * * NsGetRequest -- * * Return the request buffer, reading it if necessary (i.e., if not an * async read-ahead connection). This function is called at the start of * connection processing. * Results: * Pointer to Request structure or NULL on error. * * Side effects: * May wait for content to arrive if necessary. * *---------------------------------------------------------------------- */ Request * NsGetRequest(Sock *sockPtr, const Ns_Time *nowPtr) { Request *reqPtr; NS_NONNULL_ASSERT(sockPtr != NULL); /* * The underlying "Request" structure is allocated by RequestNew(), which * must be called for the "sockPtr" prior to calling this * function. "reqPtr" should be NULL just in error cases. */ reqPtr = sockPtr->reqPtr; if (likely(reqPtr != NULL)) { if (likely(reqPtr->request.line != NULL)) { Ns_Log(DriverDebug, "NsGetRequest got the pre-parsed request <%s> from the driver", reqPtr->request.line); } else if (sockPtr->drvPtr->requestProc == NULL) { /* * Non-HTTP driver can send the drvPtr->requestProc to perform * their own request handling. */ SockState status; Ns_Log(DriverDebug, "NsGetRequest has to read+parse the request"); /* * We have no parsed request so far. So, do it now. */ do { Ns_Log(DriverDebug, "NsGetRequest calls SockRead"); status = SockRead(sockPtr, 0, nowPtr); } while (status == SOCK_MORE); /* * If anything went wrong, clean the request provided by * SockRead() and flag the error by returning NULL. */ if (status != SOCK_READY) { if (sockPtr->reqPtr != NULL) { Ns_Log(DriverDebug, "NsGetRequest calls RequestFree"); RequestFree(sockPtr); } reqPtr = NULL; } } else { Ns_Log(DriverDebug, "NsGetRequest found driver specific request Proc, " "probably from a non-HTTP driver"); } } else { Ns_Log(DriverDebug, "NsGetRequest has reqPtr NULL"); } return reqPtr; } /* *---------------------------------------------------------------------- * * NsSockClose -- * * Return a connection to the DriverThread for closing or keepalive. * "keep" might be NS_TRUE/NS_FALSE or -1 if undecided. * * Results: * None. * * Side effects: * Socket may be reused by a keepalive connection. * *---------------------------------------------------------------------- */ void NsSockClose(Sock *sockPtr, int keep) { Driver *drvPtr; bool trigger = NS_FALSE; NS_NONNULL_ASSERT(sockPtr != NULL); drvPtr = sockPtr->drvPtr; Ns_Log(DriverDebug, "NsSockClose sockPtr %p (%d) keep %d", (void *)sockPtr, ((Ns_Sock*)sockPtr)->sock, keep); SockClose(sockPtr, keep); /* * Free the request, unless it is from a non-HTTP driver (who might not * fill out the request structure). */ if (sockPtr->reqPtr != NULL) { Ns_Log(DriverDebug, "NsSockClose calls RequestFree"); RequestFree(sockPtr); } Ns_MutexLock(&drvPtr->lock); if (drvPtr->closePtr == NULL) { trigger = NS_TRUE; } sockPtr->nextPtr = drvPtr->closePtr; drvPtr->closePtr = sockPtr; Ns_MutexUnlock(&drvPtr->lock); if (trigger) { SockTrigger(drvPtr->trigger[1]); } } /* *---------------------------------------------------------------------- * * DriverListen -- * * Open a listening socket for accepting connections. * * Results: * File description of socket, or NS_INVALID_SOCKET on error. * * Side effects: * Depends on driver. * *---------------------------------------------------------------------- */ static NS_SOCKET DriverListen(Driver *drvPtr, const char *bindaddr) { NS_SOCKET sock; NS_NONNULL_ASSERT(drvPtr != NULL); NS_NONNULL_ASSERT(bindaddr != NULL); sock = (*drvPtr->listenProc)((Ns_Driver *) drvPtr, bindaddr, drvPtr->port, drvPtr->backlog, drvPtr->reuseport); if (sock == NS_INVALID_SOCKET) { Ns_Log(Error, "%s: failed to listen on [%s]:%d: %s", drvPtr->threadName, bindaddr, drvPtr->port, ns_sockstrerror(ns_sockerrno)); } else { Ns_Log(Notice, #ifdef HAVE_IPV6 "%s: listening on [%s]:%d", #else "%s: listening on %s:%d", #endif drvPtr->threadName, bindaddr, drvPtr->port); } return sock; } /* *---------------------------------------------------------------------- * * DriverAccept -- * * Accept a new socket. It will be in non-blocking mode. * * Results: * _ACCEPT: a socket was accepted, poll for data * _ACCEPT_DATA: a socket was accepted, data present, read immediately * if in async mode, defer reading to connection thread * _ACCEPT_QUEUE: a socket was accepted, queue immediately * _ACCEPT_ERROR: no socket was accepted * * Side effects: * Depends on driver. * *---------------------------------------------------------------------- */ static NS_DRIVER_ACCEPT_STATUS DriverAccept(Sock *sockPtr, NS_SOCKET sock) { socklen_t n = (socklen_t)sizeof(struct NS_SOCKADDR_STORAGE); NS_NONNULL_ASSERT(sockPtr != NULL); return (*sockPtr->drvPtr->acceptProc)((Ns_Sock *) sockPtr, sock, (struct sockaddr *) &(sockPtr->sa), &n); } /* *---------------------------------------------------------------------- * * NsDriverRecv -- * * Read data from the socket into the given vector of buffers. * * Results: * Number of bytes read, or -1 on error. * * Side effects: * Depends on driver. * *---------------------------------------------------------------------- */ ssize_t NsDriverRecv(Sock *sockPtr, struct iovec *bufs, int nbufs, Ns_Time *timeoutPtr) { ssize_t result; const Driver *drvPtr; NS_NONNULL_ASSERT(sockPtr != NULL); drvPtr = sockPtr->drvPtr; if (likely(drvPtr->recvProc != NULL)) { result = (*drvPtr->recvProc)((Ns_Sock *) sockPtr, bufs, nbufs, timeoutPtr, 0u); } else { Ns_Log(Warning, "driver: no recvProc registered for driver %s", drvPtr->threadName); result = -1; } return result; } /* *---------------------------------------------------------------------- * * NsDriverSend -- * * Write a vector of buffers to the socket via the driver callback. * May not send all of the data. * * Results: * Number of bytes written or -1 on error. * May return 0 (zero) when socket is not writable. * * Side effects: * Depends on the driver. * *---------------------------------------------------------------------- */ ssize_t NsDriverSend(Sock *sockPtr, const struct iovec *bufs, int nbufs, unsigned int flags) { ssize_t sent = -1; const Driver *drvPtr; NS_NONNULL_ASSERT(sockPtr != NULL); drvPtr = sockPtr->drvPtr; NS_NONNULL_ASSERT(drvPtr != NULL); if (likely(drvPtr->sendProc != NULL)) { /* * TODO: The Ns_DriverSendProc signature should be modified * to omit the timeout argument. Same with recvProc(). */ sent = (*drvPtr->sendProc)((Ns_Sock *) sockPtr, bufs, nbufs, NULL, flags); } else { Ns_Log(Warning, "no sendProc registered for driver %s", drvPtr->threadName); } return sent; } /* *---------------------------------------------------------------------- * * NsDriverSendFile -- * * Write a vector of file buffers to the socket via the driver * callback. * * Results: * Number of bytes written, -1 on error. * May not send all the data. * * Side effects: * May block on disk read. * *---------------------------------------------------------------------- */ ssize_t NsDriverSendFile(Sock *sockPtr, Ns_FileVec *bufs, int nbufs, unsigned int flags) { ssize_t sent = -1; const Driver *drvPtr; NS_NONNULL_ASSERT(sockPtr != NULL); NS_NONNULL_ASSERT(bufs != NULL); drvPtr = sockPtr->drvPtr; NS_NONNULL_ASSERT(drvPtr != NULL); if (drvPtr->sendFileProc != NULL) { /* * TODO: The Ns_DriverSendFileProc signature should be modified * to omit the timeout argument. */ sent = (*drvPtr->sendFileProc)((Ns_Sock *)sockPtr, bufs, nbufs, NULL, flags); } else { sent = Ns_SockSendFileBufs((Ns_Sock *)sockPtr, bufs, nbufs, flags); } return sent; } /* *---------------------------------------------------------------------- * * DriverKeep -- * * Can the given socket be kept open in the hopes that another * request will arrive before the keepwait timeout expires? * * Results: * NS_TRUE if the socket is OK for keepalive, NS_FALSE if this is not possible. * * Side effects: * Depends on driver. * *---------------------------------------------------------------------- */ static bool DriverKeep(Sock *sockPtr) { Ns_DriverKeepProc *keepProc; bool result; NS_NONNULL_ASSERT(sockPtr != NULL); keepProc = sockPtr->drvPtr->keepProc; if (keepProc == NULL) { result = NS_FALSE; } else { result = (keepProc)((Ns_Sock *) sockPtr); } return result; } /* *---------------------------------------------------------------------- * * DriverClose -- * * Close the given socket. * * Results: * None. * * Side effects: * Depends on driver. * *---------------------------------------------------------------------- */ static void DriverClose(Sock *sockPtr) { NS_NONNULL_ASSERT(sockPtr != NULL); (*sockPtr->drvPtr->closeProc)((Ns_Sock *) sockPtr); } /* *---------------------------------------------------------------------- * * DriverThread -- * * Main listening socket driver thread. * * Results: * None. * * Side effects: * Connections are accepted on the configured listen sockets, * placed on the run queue to be serviced, and gracefully * closed when done. Async sockets have the entire request read * here before queuing as well. * *---------------------------------------------------------------------- */ static void DriverThread(void *arg) { Driver *drvPtr = (Driver*)arg; Ns_Time now, diff; char charBuffer[1], drain[1024]; int pollTimeout, accepted, nrBindaddrs = 0; bool stopping; unsigned int flags; Sock *sockPtr, *closePtr, *nextPtr, *waitPtr, *readPtr; PollData pdata; Ns_ThreadSetName("-driver:%s-", drvPtr->threadName); Ns_Log(Notice, "starting"); flags = DRIVER_STARTED; { Tcl_Obj *bindaddrsObj, **objv; int j = 0, result; bindaddrsObj = Tcl_NewStringObj(drvPtr->address, -1); Tcl_IncrRefCount(bindaddrsObj); result = Tcl_ListObjGetElements(NULL, bindaddrsObj, &nrBindaddrs, &objv); /* * "result" was ok during startup, it has still to be ok. */ assert(result == TCL_OK); if (result == TCL_OK) { int i; /* * Bind all provided addresses. */ for (i = 0; i < nrBindaddrs; i++) { drvPtr->listenfd[j] = DriverListen(drvPtr, Tcl_GetString(objv[i])); if (drvPtr->listenfd[j] != NS_INVALID_SOCKET) { j ++; } } if (j > 0 && j < nrBindaddrs) { Ns_Log(Warning, "could only bind to %d out of %d addresses", j, nrBindaddrs); } } /* * "j" refers to the number of successful listen() operations. */ nrBindaddrs = j; Tcl_DecrRefCount(bindaddrsObj); } if (nrBindaddrs > 0) { SpoolerQueueStart(drvPtr->spooler.firstPtr, SpoolerThread); SpoolerQueueStart(drvPtr->writer.firstPtr, WriterThread); } else { Ns_Log(Warning, "could no bind any of the following addresses, stopping this driver: %s", drvPtr->address); flags |= (DRIVER_FAILED | DRIVER_SHUTDOWN); } Ns_MutexLock(&drvPtr->lock); drvPtr->flags |= flags; Ns_CondBroadcast(&drvPtr->cond); Ns_MutexUnlock(&drvPtr->lock); /* * Loop forever until signaled to shut down and all * connections are complete and gracefully closed. */ PollCreate(&pdata); Ns_GetTime(&now); closePtr = waitPtr = readPtr = NULL; stopping = ((flags & DRIVER_SHUTDOWN) != 0u); if (!stopping) { Ns_Log(Notice, "driver: accepting connections"); } while (!stopping) { int n; /* * Set the bits for all active drivers if a connection * isn't already pending. */ PollReset(&pdata); (void)PollSet(&pdata, drvPtr->trigger[0], (short)POLLIN, NULL); if (likely(waitPtr == NULL)) { for (n = 0; n < nrBindaddrs; n++) { drvPtr->pidx[n] = PollSet(&pdata, drvPtr->listenfd[n], (short)POLLIN, NULL); } } /* * If there are any closing or read-ahead sockets, set the bits * and determine the minimum relative timeout. * * TODO: the various poll timeouts should probably be configurable. */ if (readPtr == NULL && closePtr == NULL) { pollTimeout = 10 * 1000; } else { for (sockPtr = readPtr; sockPtr != NULL; sockPtr = sockPtr->nextPtr) { SockPoll(sockPtr, (short)POLLIN, &pdata); } for (sockPtr = closePtr; sockPtr != NULL; sockPtr = sockPtr->nextPtr) { SockPoll(sockPtr, (short)POLLIN, &pdata); } if (Ns_DiffTime(&pdata.timeout, &now, &diff) > 0) { /* * The resolution of "pollTimeout" is ms, therefore, we round * up. If we would round down (e.g. 500 microseconds to 0 ms), * the time comparison later would determine that it is too * early. */ pollTimeout = (int)Ns_TimeToMilliseconds(&diff) + 1; } else { pollTimeout = 0; } } n = PollWait(&pdata, pollTimeout); Ns_Log(DriverDebug, "=== PollWait returned %d, trigger[0] %d", n, PollIn(&pdata, 0)); if (PollIn(&pdata, 0) && unlikely(ns_recv(drvPtr->trigger[0], charBuffer, 1u, 0) != 1)) { const char *errstr = ns_sockstrerror(ns_sockerrno); Ns_Fatal("driver: trigger ns_recv() failed: %s", errstr); } /* * Check whether we should re-animate some connection threads, * when e.g. the number of current threads dropped below the * minimal value. Perform this test on timeouts (n == 0; * just for safety reasons) or on explicit wakeup calls. */ if ((n == 0) || PollIn(&pdata, 0)) { NsServer *servPtr = drvPtr->servPtr; if (servPtr != NULL) { /* * Check if we have to reanimate the current server. */ NsEnsureRunningConnectionThreads(servPtr, NULL); } else { Ns_Set *servers = Ns_ConfigCreateSection("ns/servers"); size_t j; /* * Reanimation check on all servers. */ for (j = 0u; j < Ns_SetSize(servers); ++j) { const char *server = Ns_SetKey(servers, j); servPtr = NsGetServer(server); if (servPtr != NULL) { NsEnsureRunningConnectionThreads(servPtr, NULL); } } } } /* * Update the current time and drain and/or release any * closing sockets. */ Ns_GetTime(&now); if (closePtr != NULL) { sockPtr = closePtr; closePtr = NULL; while (sockPtr != NULL) { nextPtr = sockPtr->nextPtr; if (unlikely(PollHup(&pdata, sockPtr->pidx))) { /* * Peer has closed the connection */ SockRelease(sockPtr, SOCK_CLOSE, 0); } else if (likely(PollIn(&pdata, sockPtr->pidx))) { /* * Got some data */ ssize_t received = ns_recv(sockPtr->sock, drain, sizeof(drain), 0); if (received <= 0) { Ns_Log(DriverDebug, "poll closewait pollin; sockrelease SOCK_READERROR (sock %d)", sockPtr->sock); SockRelease(sockPtr, SOCK_READERROR, 0); } else { Push(sockPtr, closePtr); } } else if (Ns_DiffTime(&sockPtr->timeout, &now, &diff) <= 0) { /* no PollHup, no PollIn, maybe timeout */ Ns_Log(DriverDebug, "poll closewait timeout; sockrelease SOCK_CLOSETIMEOUT (sock %d)", sockPtr->sock); SockRelease(sockPtr, SOCK_CLOSETIMEOUT, 0); } else { /* too early, keep waiting */ Push(sockPtr, closePtr); } sockPtr = nextPtr; } } /* * Attempt read-ahead of any new connections. */ sockPtr = readPtr; readPtr = NULL; while (likely(sockPtr != NULL)) { nextPtr = sockPtr->nextPtr; if (unlikely(PollHup(&pdata, sockPtr->pidx))) { /* * Peer has closed the connection */ SockRelease(sockPtr, SOCK_CLOSE, 0); } else if (unlikely(!PollIn(&pdata, sockPtr->pidx)) && ((sockPtr->reqPtr == NULL) || (sockPtr->reqPtr->leftover == 0u))) { /* * Got no data for this sockPtr. */ if (Ns_DiffTime(&sockPtr->timeout, &now, &diff) <= 0) { SockRelease(sockPtr, SOCK_READTIMEOUT, 0); } else { Push(sockPtr, readPtr); } } else { /* * Got some data for this sockPtr. * If enabled, perform read-ahead now. */ assert(drvPtr == sockPtr->drvPtr); if (likely((drvPtr->opts & NS_DRIVER_ASYNC) != 0u)) { SockState s = SockRead(sockPtr, 0, &now); /* * Queue for connection processing if ready. */ switch (s) { case SOCK_SPOOL: drvPtr->stats.spooled++; if (SockSpoolerQueue(drvPtr, sockPtr) == 0) { Push(sockPtr, readPtr); } break; case SOCK_MORE: drvPtr->stats.partial++; SockTimeout(sockPtr, &now, &drvPtr->recvwait); Push(sockPtr, readPtr); break; case SOCK_READY: if (SockQueue(sockPtr, &now) == NS_TIMEOUT) { Push(sockPtr, waitPtr); } break; /* * Already handled or normal cases */ case SOCK_ENTITYTOOLARGE: NS_FALL_THROUGH; /* fall through */ case SOCK_BADREQUEST: NS_FALL_THROUGH; /* fall through */ case SOCK_BADHEADER: NS_FALL_THROUGH; /* fall through */ case SOCK_TOOMANYHEADERS: NS_FALL_THROUGH; /* fall through */ case SOCK_CLOSE: SockRelease(sockPtr, s, errno); break; /* * Exceptions */ case SOCK_READERROR: NS_FALL_THROUGH; /* fall through */ case SOCK_CLOSETIMEOUT: NS_FALL_THROUGH; /* fall through */ case SOCK_ERROR: NS_FALL_THROUGH; /* fall through */ case SOCK_READTIMEOUT: NS_FALL_THROUGH; /* fall through */ case SOCK_SHUTERROR: NS_FALL_THROUGH; /* fall through */ case SOCK_WRITEERROR: NS_FALL_THROUGH; /* fall through */ case SOCK_WRITETIMEOUT: drvPtr->stats.errors++; Ns_Log(Warning, "sockread returned unexpected result %s (err %s); close socket (%d)", GetSockStateName(s), ((errno != 0) ? strerror(errno) : NS_EMPTY_STRING), sockPtr->sock); SockRelease(sockPtr, s, errno); break; } } else { /* * Potentially blocking driver, NS_DRIVER_ASYNC is not defined */ if (Ns_DiffTime(&sockPtr->timeout, &now, &diff) <= 0) { drvPtr->stats.errors++; Ns_Log(Notice, "read-ahead has some data, no async sock read ===== diff time %ld", Ns_DiffTime(&sockPtr->timeout, &now, &diff)); sockPtr->keep = NS_FALSE; SockRelease(sockPtr, SOCK_READTIMEOUT, 0); } else { if (SockQueue(sockPtr, &now) == NS_TIMEOUT) { Push(sockPtr, waitPtr); } } } } sockPtr = nextPtr; } /* * Attempt to queue any pending connection after reversing the * list to ensure oldest connections are tried first. */ if (waitPtr != NULL) { sockPtr = NULL; while ((nextPtr = waitPtr) != NULL) { waitPtr = nextPtr->nextPtr; Push(nextPtr, sockPtr); } while (sockPtr != NULL) { nextPtr = sockPtr->nextPtr; if (SockQueue(sockPtr, &now) == NS_TIMEOUT) { Push(sockPtr, waitPtr); } sockPtr = nextPtr; } } /* * If no connections are waiting, attempt to accept more. */ if (waitPtr == NULL) { /* * If configured, try to accept more than one request, under heavy load * this helps to process more requests */ SockState s; bool acceptMore = NS_TRUE; accepted = 0; while (acceptMore && accepted < drvPtr->acceptsize && drvPtr->queuesize < drvPtr->maxqueuesize ) { bool gotRequests = NS_FALSE; /* * Check for input data on all bind addresses. Stop checking, * when one round of checking on all addresses fails. */ for (n = 0; n < nrBindaddrs; n++) { if ( PollIn(&pdata, drvPtr->pidx[n]) && (s = SockAccept(drvPtr, pdata.pfds[drvPtr->pidx[n]].fd, &sockPtr, &now)) != SOCK_ERROR) { switch (s) { case SOCK_SPOOL: drvPtr->stats.spooled++; if (SockSpoolerQueue(drvPtr, sockPtr) == 0) { Push(sockPtr, readPtr); } break; case SOCK_MORE: drvPtr->stats.partial++; SockTimeout(sockPtr, &now, &drvPtr->recvwait); Push(sockPtr, readPtr); break; case SOCK_READY: if (SockQueue(sockPtr, &now) == NS_TIMEOUT) { Push(sockPtr, waitPtr); } break; case SOCK_BADHEADER: NS_FALL_THROUGH; /* fall through */ case SOCK_BADREQUEST: NS_FALL_THROUGH; /* fall through */ case SOCK_CLOSE: NS_FALL_THROUGH; /* fall through */ case SOCK_CLOSETIMEOUT: NS_FALL_THROUGH; /* fall through */ case SOCK_ENTITYTOOLARGE: NS_FALL_THROUGH; /* fall through */ case SOCK_ERROR: NS_FALL_THROUGH; /* fall through */ case SOCK_READERROR: NS_FALL_THROUGH; /* fall through */ case SOCK_READTIMEOUT: NS_FALL_THROUGH; /* fall through */ case SOCK_SHUTERROR: NS_FALL_THROUGH; /* fall through */ case SOCK_TOOMANYHEADERS: NS_FALL_THROUGH; /* fall through */ case SOCK_WRITEERROR: NS_FALL_THROUGH; /* fall through */ case SOCK_WRITETIMEOUT: Ns_Fatal("driver: SockAccept returned: %s", GetSockStateName(s)); } accepted++; gotRequests = NS_TRUE; #ifdef __APPLE__ /* * On Darwin, the first accept() succeeds typically, but it is * useless to try, since this leads always to an EAGAIN */ acceptMore = NS_FALSE; break; #endif } } if (!gotRequests) { acceptMore = NS_FALSE; } } if (accepted > 1) { Ns_Log(Notice, "... sockAccept accepted %d connections", accepted); } } /* * Check for shut down and get the list of any closing or * keep-alive sockets. */ Ns_MutexLock(&drvPtr->lock); sockPtr = drvPtr->closePtr; drvPtr->closePtr = NULL; flags = drvPtr->flags; Ns_MutexUnlock(&drvPtr->lock); stopping = ((flags & DRIVER_SHUTDOWN) != 0u); /* * Update the timeout for each closing socket and add to the * close list if some data has been read from the socket * (i.e., it's not a closing keep-alive connection). */ while (sockPtr != NULL) { nextPtr = sockPtr->nextPtr; if (sockPtr->keep) { assert(drvPtr == sockPtr->drvPtr); Ns_Log(DriverDebug, "setting keepwait %ld.%6ld for socket %d", drvPtr->keepwait.sec, drvPtr->keepwait.usec, sockPtr->sock); SockTimeout(sockPtr, &now, &drvPtr->keepwait); Push(sockPtr, readPtr); } else { /* * Purely packet oriented drivers set on close the fd to * NS_INVALID_SOCKET. Since we cannot "shutdown" an UDP-socket * for writing, we bypass this call. */ assert(drvPtr == sockPtr->drvPtr); if (sockPtr->sock == NS_INVALID_SOCKET) { SockRelease(sockPtr, SOCK_CLOSE, errno); Ns_Log(DriverDebug, "DRIVER SockRelease: errno %d drvPtr->closewait %ld.%6ld", errno, drvPtr->closewait.sec, drvPtr->closewait.usec); } else if (shutdown(sockPtr->sock, SHUT_WR) != 0) { SockRelease(sockPtr, SOCK_SHUTERROR, errno); } else { Ns_Log(DriverDebug, "setting closewait %ld.%6ld for socket %d", drvPtr->closewait.sec, drvPtr->closewait.usec, sockPtr->sock); SockTimeout(sockPtr, &now, &drvPtr->closewait); Push(sockPtr, closePtr); } } sockPtr = nextPtr; } /* * Close the active drivers if shutdown is pending. */ if (stopping) { for (n = 0; n < nrBindaddrs; n++) { ns_sockclose(drvPtr->listenfd[n]); drvPtr->listenfd[n] = NS_INVALID_SOCKET; } } } PollFree(&pdata); Ns_Log(Notice, "exiting"); Ns_MutexLock(&drvPtr->lock); drvPtr->flags |= DRIVER_STOPPED; Ns_CondBroadcast(&drvPtr->cond); Ns_MutexUnlock(&drvPtr->lock); } static void PollCreate(PollData *pdata) { NS_NONNULL_ASSERT(pdata != NULL); memset(pdata, 0, sizeof(PollData)); } static void PollFree(PollData *pdata) { NS_NONNULL_ASSERT(pdata != NULL); ns_free(pdata->pfds); memset(pdata, 0, sizeof(PollData)); } static void PollReset(PollData *pdata) { NS_NONNULL_ASSERT(pdata != NULL); pdata->nfds = 0u; pdata->timeout.sec = TIME_T_MAX; pdata->timeout.usec = 0; } static NS_POLL_NFDS_TYPE PollSet(PollData *pdata, NS_SOCKET sock, short type, const Ns_Time *timeoutPtr) { NS_NONNULL_ASSERT(pdata != NULL); /* * Grow the pfds array if necessary. */ if (unlikely(pdata->nfds >= pdata->maxfds)) { pdata->maxfds += 100u; pdata->pfds = ns_realloc(pdata->pfds, pdata->maxfds * sizeof(struct pollfd)); } /* * Set the next pollfd struct with this socket. */ pdata->pfds[pdata->nfds].fd = sock; pdata->pfds[pdata->nfds].events = type; pdata->pfds[pdata->nfds].revents = 0; /* * Check for new minimum timeout. */ if (timeoutPtr != NULL && Ns_DiffTime(timeoutPtr, &pdata->timeout, NULL) < 0) { pdata->timeout = *timeoutPtr; } return pdata->nfds++; } static int PollWait(const PollData *pdata, int timeout) { int n; NS_NONNULL_ASSERT(pdata != NULL); do { n = ns_poll(pdata->pfds, pdata->nfds, timeout); } while (n < 0 && errno == NS_EINTR); if (n < 0) { Ns_Fatal("PollWait: ns_poll() failed: %s", ns_sockstrerror(ns_sockerrno)); } return n; } /* *---------------------------------------------------------------------- * * RequestNew * * Prepares for reading from the socket, allocates a "Request" * struct for the given socket. It might be reused from the pool * or freshly allocated. Counterpart of RequestFree(). * * Results: * None * * Side effects: * None * *---------------------------------------------------------------------- */ static void RequestNew(Sock *sockPtr) { Request *reqPtr; bool reuseRequest = NS_TRUE; NS_NONNULL_ASSERT(sockPtr != NULL); /* * Try to get a request from the pool of allocated Requests. */ Ns_MutexLock(&reqLock); reqPtr = firstReqPtr; if (likely(reqPtr != NULL)) { firstReqPtr = reqPtr->nextPtr; } else { reuseRequest = NS_FALSE; } Ns_MutexUnlock(&reqLock); if (reuseRequest) { Ns_Log(DriverDebug, "RequestNew reuses a Request"); } /* * In case we failed, allocate a new Request. */ if (reqPtr == NULL) { Ns_Log(DriverDebug, "RequestNew gets a fresh Request"); reqPtr = ns_calloc(1u, sizeof(Request)); Tcl_DStringInit(&reqPtr->buffer); reqPtr->headers = Ns_SetCreate(NULL); } sockPtr->reqPtr = reqPtr; } /* *---------------------------------------------------------------------- * * RequestFree -- * * Free/clean a socket request structure. This routine is called * at the end of connection processing or on a socket which * times out during async read-ahead. Counterpart of RequestNew(). * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------- */ static void RequestFree(Sock *sockPtr) { Request *reqPtr; bool keep; NS_NONNULL_ASSERT(sockPtr != NULL); reqPtr = sockPtr->reqPtr; assert(reqPtr != NULL); Ns_Log(DriverDebug, "=== RequestFree cleans %p (avail %" PRIuz " keep %d length %" PRIuz " contentLength %" PRIuz ")", (void *)reqPtr, reqPtr->avail, sockPtr->keep, reqPtr->length, reqPtr->contentLength); keep = (sockPtr->keep) && (reqPtr->avail > reqPtr->contentLength); if (keep) { size_t leftover = reqPtr->avail - reqPtr->contentLength; const char *offset = reqPtr->buffer.string + ((size_t)reqPtr->buffer.length - leftover); Ns_Log(DriverDebug, "setting leftover to %" PRIuz " bytes", leftover); /* * Here it is safe to move the data in the buffer, although the * reqPtr->content might point to it, since we re-init the content. In * case the terminating null character was written to the end of the * previous buffer, we have to restore the first character. */ memmove(reqPtr->buffer.string, offset, leftover); if (reqPtr->savedChar != '\0') { reqPtr->buffer.string[0] = reqPtr->savedChar; } Tcl_DStringSetLength(&reqPtr->buffer, (int)leftover); LogBuffer(DriverDebug, "KEEP BUFFER", reqPtr->buffer.string, leftover); reqPtr->leftover = leftover; } else { /* * Clean large buffers in order to avoid memory growth on huge * uploads (when maxupload is huge) */ /*fprintf(stderr, "=== reuse buffer size %d avail %d dynamic %d\n", reqPtr->buffer.length, reqPtr->buffer.spaceAvl, reqPtr->buffer.string == reqPtr->buffer.staticSpace);*/ if (Tcl_DStringLength(&reqPtr->buffer) > 65536) { Tcl_DStringFree(&reqPtr->buffer); } else { /* * Reuse buffer, but set length to 0. */ Tcl_DStringSetLength(&reqPtr->buffer, 0); } reqPtr->leftover = 0u; } reqPtr->next = NULL; reqPtr->content = NULL; reqPtr->length = 0u; reqPtr->contentLength = 0u; reqPtr->expectedLength = 0u; reqPtr->chunkStartOff = 0u; reqPtr->chunkWriteOff = 0u; reqPtr->roff = 0u; reqPtr->woff = 0u; reqPtr->coff = 0u; reqPtr->avail = 0u; reqPtr->savedChar = '\0'; Ns_SetTrunc(reqPtr->headers, 0u); if (reqPtr->auth != NULL) { Ns_SetFree(reqPtr->auth); reqPtr->auth = NULL; } if (reqPtr->request.line != NULL) { Ns_Log(DriverDebug, "RequestFree calls Ns_ResetRequest on %p", (void*)&reqPtr->request); Ns_ResetRequest(&reqPtr->request); } else { Ns_Log(DriverDebug, "RequestFree does not call Ns_ResetRequest on %p", (void*)&reqPtr->request); } if (!keep) { /* * Push the reqPtr to the pool for reuse in other connections. */ sockPtr->reqPtr = NULL; Ns_MutexLock(&reqLock); reqPtr->nextPtr = firstReqPtr; firstReqPtr = reqPtr; Ns_MutexUnlock(&reqLock); } else { /* * Keep the partly cleaned up reqPtr associated with the connection. */ Ns_Log(DriverDebug, "=== KEEP request structure in sockPtr (don't push into the pool)"); } } /* *---------------------------------------------------------------------- * * SockQueue -- * * Puts socket into connection queue * * Results: * NS_OK if queued, * NS_ERROR if socket closed because of error * NS_TIMEOUT if queue is full * * Side effects: * None. * *---------------------------------------------------------------------- */ static Ns_ReturnCode SockQueue(Sock *sockPtr, const Ns_Time *timePtr) { Ns_ReturnCode result; NS_NONNULL_ASSERT(sockPtr != NULL); /* * Verify the conditions. Request struct must exist already. */ assert(sockPtr->reqPtr != NULL); SockSetServer(sockPtr); assert(sockPtr->servPtr != NULL); /* * Actual queueing, if not ready spool to the waiting list. */ if (!NsQueueConn(sockPtr, timePtr)) { result = NS_TIMEOUT; } else { result = NS_OK; } return result; } /* *---------------------------------------------------------------------- * * SockPoll -- * * Arrange for given Sock to be monitored. * * Results: * None. * * Side effects: * Sock fd will be monitored for readability on next spin of * DriverThread. * *---------------------------------------------------------------------- */ static void SockPoll(Sock *sockPtr, short type, PollData *pdata) { NS_NONNULL_ASSERT(sockPtr != NULL); NS_NONNULL_ASSERT(pdata != NULL); sockPtr->pidx = PollSet(pdata, sockPtr->sock, type, &sockPtr->timeout); } /* *---------------------------------------------------------------------- * * SockTimeout -- * * Update socket with timeout * * Results: * None. * * Side effects: * Socket timeout will have nowPtr + timeout value * *---------------------------------------------------------------------- */ static void SockTimeout(Sock *sockPtr, const Ns_Time *nowPtr, const Ns_Time *timeout) { NS_NONNULL_ASSERT(sockPtr != NULL); sockPtr->timeout = *nowPtr; Ns_IncrTime(&sockPtr->timeout, timeout->sec, timeout->usec); } /* *---------------------------------------------------------------------- * * SockAccept -- * * Accept and initialize a new Sock in sockPtrPtr. * * Results: * SOCK_READY, SOCK_MORE, SOCK_SPOOL, * SOCK_ERROR + NULL sockPtr. * * Side effects: * Read-ahead may be attempted on new socket. * *---------------------------------------------------------------------- */ static SockState SockAccept(Driver *drvPtr, NS_SOCKET sock, Sock **sockPtrPtr, const Ns_Time *nowPtr) { Sock *sockPtr; SockState sockStatus; NS_DRIVER_ACCEPT_STATUS status; NS_NONNULL_ASSERT(drvPtr != NULL); sockPtr = SockNew(drvPtr); /* * Accept the new connection. */ status = DriverAccept(sockPtr, sock); if (unlikely(status == NS_DRIVER_ACCEPT_ERROR)) { sockStatus = SOCK_ERROR; /* * We reach the place frequently, especially on Linux, when we try to * accept multiple connection in one sweep. Usually, the errno is * EAGAIN. */ Ns_MutexLock(&drvPtr->lock); sockPtr->nextPtr = drvPtr->sockPtr; drvPtr->sockPtr = sockPtr; Ns_MutexUnlock(&drvPtr->lock); sockPtr = NULL; } else { sockPtr->acceptTime = *nowPtr; drvPtr->queuesize++; if (status == NS_DRIVER_ACCEPT_DATA) { /* * If there is already data present then read it without * polling if we're in async mode. */ if ((drvPtr->opts & NS_DRIVER_ASYNC) != 0u) { sockStatus = SockRead(sockPtr, 0, nowPtr); if ((int)sockStatus < 0) { Ns_Log(DriverDebug, "SockRead returned error %s", GetSockStateName(sockStatus)); SockRelease(sockPtr, sockStatus, errno); sockStatus = SOCK_ERROR; sockPtr = NULL; } } else { /* * Queue this socket without reading, NsGetRequest() in the * connection thread will perform actual reading of the * request. */ sockStatus = SOCK_READY; } } else if (status == NS_DRIVER_ACCEPT_QUEUE) { /* * We need to call RequestNew() to make sure socket has request * structure allocated, otherwise NsGetRequest() will call * SockRead() which is not what this driver wants. */ if (sockPtr->reqPtr == NULL) { RequestNew(sockPtr); } sockStatus = SOCK_READY; } else { sockStatus = SOCK_MORE; } } *sockPtrPtr = sockPtr; return sockStatus; } /* *---------------------------------------------------------------------- * * SockNew -- * * Allocate and/or initialize a Sock structure. Counterpart of * SockRelease(). * * Results: * SockPtr * * Side effects: * Potentially new memory is allocated. * *---------------------------------------------------------------------- */ static Sock * SockNew(Driver *drvPtr) { Sock *sockPtr; NS_NONNULL_ASSERT(drvPtr != NULL); Ns_MutexLock(&drvPtr->lock); sockPtr = drvPtr->sockPtr; if (likely(sockPtr != NULL)) { drvPtr->sockPtr = sockPtr->nextPtr; sockPtr->keep = NS_FALSE; } Ns_MutexUnlock(&drvPtr->lock); if (sockPtr == NULL) { size_t sockSize = sizeof(Sock) + (nsconf.nextSlsId * sizeof(Ns_Callback *)); sockPtr = ns_calloc(1u, sockSize); sockPtr->drvPtr = drvPtr; } else { sockPtr->tfd = 0; sockPtr->taddr = NULL; sockPtr->flags = 0u; sockPtr->arg = NULL; sockPtr->recvSockState = NS_SOCK_NONE; } return sockPtr; } /* *---------------------------------------------------------------------- * * SockRelease -- * * Close a socket and release the connection structure for * re-use. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------- */ static void SockRelease(Sock *sockPtr, SockState reason, int err) { Driver *drvPtr; NS_NONNULL_ASSERT(sockPtr != NULL); Ns_Log(DriverDebug, "SockRelease reason %s err %d (sock %d)", GetSockStateName(reason), err, sockPtr->sock); drvPtr = sockPtr->drvPtr; assert(drvPtr != NULL); SockError(sockPtr, reason, err); if (sockPtr->sock != NS_INVALID_SOCKET) { SockClose(sockPtr, (int)NS_FALSE); } else { Ns_Log(DriverDebug, "SockRelease bypasses SockClose, since we have an invalid socket"); } NsSlsCleanup(sockPtr); drvPtr->queuesize--; if (sockPtr->reqPtr != NULL) { Ns_Log(DriverDebug, "SockRelease calls RequestFree"); RequestFree(sockPtr); } Ns_MutexLock(&drvPtr->lock); sockPtr->nextPtr = drvPtr->sockPtr; drvPtr->sockPtr = sockPtr; Ns_MutexUnlock(&drvPtr->lock); } /* *---------------------------------------------------------------------- * * SockError -- * * Log error message for given socket * re-use. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------- */ static void SockError(Sock *sockPtr, SockState reason, int err) { const char *errMsg = NULL; NS_NONNULL_ASSERT(sockPtr != NULL); switch (reason) { case SOCK_READY: case SOCK_SPOOL: case SOCK_MORE: case SOCK_CLOSE: case SOCK_CLOSETIMEOUT: /* This is normal, never log. */ break; case SOCK_READTIMEOUT: /* * For this case, whether this is acceptable or not * depends upon whether this sock was a keep-alive * that we were allowing to 'linger'. */ if (!sockPtr->keep) { errMsg = "Timeout during read"; } break; case SOCK_WRITETIMEOUT: errMsg = "Timeout during write"; break; case SOCK_READERROR: errMsg = "Unable to read request"; break; case SOCK_WRITEERROR: errMsg = "Unable to write request"; break; case SOCK_SHUTERROR: errMsg = "Unable to shutdown socket"; break; case SOCK_BADREQUEST: errMsg = "Bad Request"; SockSendResponse(sockPtr, 400, errMsg); break; case SOCK_TOOMANYHEADERS: errMsg = "Too Many Request Headers"; SockSendResponse(sockPtr, 414, errMsg); break; case SOCK_BADHEADER: errMsg = "Invalid Request Header"; SockSendResponse(sockPtr, 400, errMsg); break; case SOCK_ENTITYTOOLARGE: errMsg = "Request Entity Too Large"; SockSendResponse(sockPtr, 413, errMsg); break; case SOCK_ERROR: errMsg = "Unknown Error"; SockSendResponse(sockPtr, 400, errMsg); break; } if (errMsg != NULL) { char ipString[NS_IPADDR_SIZE]; Ns_Log(DriverDebug, "SockError: %s (%d: %s), sock: %d, peer: [%s]:%d, request: %.99s", errMsg, err, (err != 0) ? strerror(err) : NS_EMPTY_STRING, sockPtr->sock, ns_inet_ntop((struct sockaddr *)&(sockPtr->sa), ipString, sizeof(ipString)), Ns_SockaddrGetPort((struct sockaddr *)&(sockPtr->sa)), (sockPtr->reqPtr != NULL) ? sockPtr->reqPtr->buffer.string : NS_EMPTY_STRING); } } /* *---------------------------------------------------------------------- * * SockSendResponse -- * * Send an HTTP response directly to the client using the * driver callback. * * Results: * None. * * Side effects: * May not sent the complete response to the client * if encountering non-writable connection socket. * *---------------------------------------------------------------------- */ static void SockSendResponse(Sock *sockPtr, int code, const char *errMsg) { struct iovec iov[3]; char header[32]; ssize_t sent, tosend; NS_NONNULL_ASSERT(sockPtr != NULL); NS_NONNULL_ASSERT(errMsg != NULL); snprintf(header, sizeof(header), "HTTP/1.0 %d ", code); iov[0].iov_base = header; iov[0].iov_len = strlen(header); iov[1].iov_base = (void *)errMsg; iov[1].iov_len = strlen(errMsg); iov[2].iov_base = (void *)"\r\n\r\n"; iov[2].iov_len = 4u; tosend = (ssize_t)(iov[0].iov_len + iov[1].iov_len + iov[2].iov_len); sent = NsDriverSend(sockPtr, iov, 3, 0u); if (sent < tosend) { Ns_Log(Warning, "Driver: partial write while sending response;" " %" PRIdz " < %" PRIdz, sent, tosend); } /* * In case we have a request structure, complain the system log about * the bad request. */ if (sockPtr->reqPtr != NULL) { Request *reqPtr = sockPtr->reqPtr; const char *requestLine = (reqPtr->request.line != NULL) ? reqPtr->request.line : NS_EMPTY_STRING; (void)ns_inet_ntop((struct sockaddr *)&(sockPtr->sa), sockPtr->reqPtr->peer, NS_IPADDR_SIZE); /* * Check, if bad request looks like a TLS handshake. If yes, there is * no need to print out the received buffer. */ if (requestLine[0] == (char)0x16 && requestLine[1] >= 3 && requestLine[2] == 1) { Ns_Log(Warning, "invalid request %d (%s) from peer %s: received TLS handshake on a non-TLS connection", code, errMsg, reqPtr->peer); } else { Tcl_DString dsReqLine; Tcl_DStringInit(&dsReqLine); Ns_Log(Warning, "invalid request: %d (%s) from peer %s request '%s' offsets: read %" PRIuz " write %" PRIuz " content %" PRIuz " avail %" PRIuz, code, errMsg, reqPtr->peer, Ns_DStringAppendPrintable(&dsReqLine, NS_FALSE, requestLine, strlen(requestLine)), reqPtr->roff, reqPtr->woff, reqPtr->coff, reqPtr->avail); Tcl_DStringFree(&dsReqLine); LogBuffer(Warning, "REQ BUFFER", reqPtr->buffer.string, (size_t)reqPtr->buffer.length); } } else { Ns_Log(Warning, "invalid request: %d (%s) - no request information available", code, errMsg); } } /* *---------------------------------------------------------------------- * * SockTrigger -- * * Wakeup DriversThread from blocking ns_poll(). * * Results: * None. * * Side effects: * DriversThread will wake up. * *---------------------------------------------------------------------- */ static void SockTrigger(NS_SOCKET sock) { if (send(sock, NS_EMPTY_STRING, 1, 0) != 1) { const char *errstr = ns_sockstrerror(ns_sockerrno); Ns_Log(Error, "driver: trigger send() failed: %s", errstr); } } /* *---------------------------------------------------------------------- * * SockClose -- * * Closes connection socket, does all cleanups. The input parameter * "keep" might be NS_TRUE/NS_FALSE or -1 if undecided. * * Results: * None. * * Side effects: * None * *---------------------------------------------------------------------- */ static void SockClose(Sock *sockPtr, int keep) { NS_NONNULL_ASSERT(sockPtr != NULL); if (keep != 0) { bool driverKeep = DriverKeep(sockPtr); keep = (int)driverKeep; } if (keep == (int)NS_FALSE) { DriverClose(sockPtr); } Ns_MutexLock(&sockPtr->drvPtr->lock); sockPtr->keep = (bool)keep; Ns_MutexUnlock(&sockPtr->drvPtr->lock); /* * Unconditionally remove temporary file, connection thread * should take care about very large uploads. */ if (sockPtr->tfile != NULL) { unlink(sockPtr->tfile); ns_free(sockPtr->tfile); sockPtr->tfile = NULL; if (sockPtr->tfd > 0) { /* * Close and reset fd. The fd should be > 0 unless we are in error * conditions. */ (void) ns_close(sockPtr->tfd); } sockPtr->tfd = 0; } else if (sockPtr->tfd > 0) { /* * This must be a fd allocated via Ns_GetTemp(); */ Ns_ReleaseTemp(sockPtr->tfd); sockPtr->tfd = 0; } #ifndef _WIN32 /* * Un-map temp file used for spooled content. */ if (sockPtr->taddr != NULL) { munmap(sockPtr->taddr, (size_t)sockPtr->tsize); sockPtr->taddr = NULL; } #endif } /* *---------------------------------------------------------------------- * * ChunkedDecode -- * * Reads the content form the incoming request buffer and tries * to decode chunked encoding parts. The function can be called * repeatedly and with incomplete input and overwrites the buffer * with the decoded data optionally. The decoded data is always * shorter than the encoded one. * * Results: * NS_TRUE when chunk was complete, NS_FALSE otherwise * * Side effects: * updates the buffer if update is true (and adjusts reqPtr->chunkWriteOff) * updates always reqPtr->chunkStartOff to allow incremental operations * *---------------------------------------------------------------------- */ static bool ChunkedDecode(Request *reqPtr, bool update) { const Tcl_DString *bufPtr; const char *end, *chunkStart; bool success = NS_TRUE; NS_NONNULL_ASSERT(reqPtr != NULL); bufPtr = &reqPtr->buffer; end = bufPtr->string + bufPtr->length; chunkStart = bufPtr->string + reqPtr->chunkStartOff; while (reqPtr->chunkStartOff < (size_t)bufPtr->length) { char *p = strstr(chunkStart, "\r\n"); size_t chunk_length; if (p == NULL) { Ns_Log(DriverDebug, "ChunkedDecode: chunk did not find end-of-line"); success = NS_FALSE; break; } *p = '\0'; chunk_length = (size_t)strtol(chunkStart, NULL, 16); *p = '\r'; if (p + 2 + chunk_length > end) { Ns_Log(DriverDebug, "ChunkedDecode: chunk length past end of buffer"); success = NS_FALSE; break; } if (update) { char *writeBuffer = bufPtr->string + reqPtr->chunkWriteOff; memmove(writeBuffer, p + 2, chunk_length); reqPtr->chunkWriteOff += chunk_length; *(writeBuffer + chunk_length) = '\0'; } reqPtr->chunkStartOff += (size_t)(p - chunkStart) + 4u + chunk_length; chunkStart = bufPtr->string + reqPtr->chunkStartOff; } return success; } /* *---------------------------------------------------------------------- * * SockRead -- * * Read content from the given Sock, processing the input as * necessary. This is the core callback routine designed to * either be called repeatedly within the DriverThread during * an async read-ahead or in a blocking loop in NsGetRequest() * at the start of connection processing. * * Results: * SOCK_READY: Request is ready for processing. * SOCK_MORE: More input is required. * SOCK_ERROR: Client drop or timeout. * SOCK_SPOOL: Pass input handling to spooler * SOCK_CLOSE: peer closed connection * SOCK_BADREQUEST * SOCK_BADHEADER * SOCK_TOOMANYHEADERS * * Side effects: * The Request structure will be built up for use by the * connection thread. Also, before returning SOCK_READY, * the next byte to read mark and bytes available are set * to the beginning of the content, just beyond the headers. * * Contents may be spooled into temp file and mmap-ed * *---------------------------------------------------------------------- */ static SockState SockRead(Sock *sockPtr, int spooler, const Ns_Time *timePtr) { const Driver *drvPtr; Request *reqPtr; Tcl_DString *bufPtr; struct iovec buf; char tbuf[16384]; size_t buflen, nread; ssize_t n; SockState resultState; NS_NONNULL_ASSERT(sockPtr != NULL); drvPtr = sockPtr->drvPtr; tbuf[0] = '\0'; /* * In case of "keepwait", the accept time is not meaningful and * reset to 0. In such cases, update "acceptTime" to the actual * begin of a request. This part is intended for async drivers. */ if (sockPtr->acceptTime.sec == 0) { assert(timePtr != NULL); sockPtr->acceptTime = *timePtr; } /* * Initialize request structure if needed. */ if (sockPtr->reqPtr == NULL) { RequestNew(sockPtr); } /* * On the first read, attempt to read-ahead "bufsize" bytes. * Otherwise, read only the number of bytes left in the * content. */ reqPtr = sockPtr->reqPtr; bufPtr = &reqPtr->buffer; if (reqPtr->length == 0u) { nread = drvPtr->bufsize; } else { nread = reqPtr->length - reqPtr->avail; } /* * Grow the buffer to include space for the next bytes. */ buflen = (size_t)bufPtr->length; n = (ssize_t)(buflen + nread); if (unlikely(n > drvPtr->maxinput)) { n = (ssize_t)drvPtr->maxinput; nread = (size_t)n - buflen; if (nread == 0u) { Ns_Log(DriverDebug, "SockRead: maxinput reached %" TCL_LL_MODIFIER "d", drvPtr->maxinput); return SOCK_ERROR; } } /* * Use temp file for content larger than "readahead" bytes. */ #ifndef _WIN32 if (reqPtr->coff > 0u /* We are in the content part (after the header) */ && !reqPtr->chunkStartOff /* Never spool chunked encoded data since we decode in memory */ && reqPtr->length > (size_t)drvPtr->readahead /* We need more data */ && sockPtr->tfd <= 0 /* We have no spool fd */ ) { const DrvSpooler *spPtr = &drvPtr->spooler; Ns_Log(DriverDebug, "SockRead: require tmp file for content spooling (length %" PRIuz" > readahead " "%" TCL_LL_MODIFIER "d)", reqPtr->length, drvPtr->readahead); /* * In driver mode send this Sock to the spooler thread if * it is running */ if (spooler == 0 && spPtr->threads > 0) { return SOCK_SPOOL; } /* * If "maxupload" is specified and content size exceeds the configured * values, spool uploads into normal temp file (not deleted). We do * not want to map such large files into memory. */ if (drvPtr->maxupload > 0 && reqPtr->length > (size_t)drvPtr->maxupload ) { size_t tfileLength = strlen(drvPtr->uploadpath) + 16u; sockPtr->tfile = ns_malloc(tfileLength); snprintf(sockPtr->tfile, tfileLength, "%s/%d.XXXXXX", drvPtr->uploadpath, sockPtr->sock); sockPtr->tfd = ns_mkstemp(sockPtr->tfile); if (sockPtr->tfd == NS_INVALID_FD) { Ns_Log(Error, "SockRead: cannot create spool file with template '%s': %s", sockPtr->tfile, strerror(errno)); } } else { /* * Get a temporary fd. These FDs are used for mmapping. */ sockPtr->tfd = Ns_GetTemp(); } if (unlikely(sockPtr->tfd == NS_INVALID_FD)) { Ns_Log(DriverDebug, "SockRead: spool fd invalid"); return SOCK_ERROR; } n = (ssize_t)((size_t)bufPtr->length - reqPtr->coff); assert(n >= 0); if (ns_write(sockPtr->tfd, bufPtr->string + reqPtr->coff, (size_t)n) != n) { return SOCK_WRITEERROR; } Tcl_DStringSetLength(bufPtr, 0); } #endif if (sockPtr->tfd > 0) { buf.iov_base = tbuf; buf.iov_len = MIN(nread, sizeof(tbuf)); } else { Tcl_DStringSetLength(bufPtr, (int)(buflen + nread)); buf.iov_base = bufPtr->string + reqPtr->woff; buf.iov_len = nread; } if (reqPtr->leftover > 0u) { /* * There is some leftover in the buffer, don't read but take the * leftover instead as input. */ n = (ssize_t)reqPtr->leftover; reqPtr->leftover = 0u; buflen = 0u; Ns_Log(DriverDebug, "SockRead receive from leftover %" PRIdz " bytes", n); } else { /* * Receive actually some data from the driver. */ n = NsDriverRecv(sockPtr, &buf, 1, NULL); Ns_Log(DriverDebug, "SockRead receive from network %" PRIdz " bytes sockState %.2x", n, (int)sockPtr->recvSockState); } { Ns_SockState nsSockState = sockPtr->recvSockState; /* * The nsSockState has one of the following values, when provided: * * NS_SOCK_READ, NS_SOCK_DONE, NS_SOCK_AGAIN, NS_SOCK_EXCEPTION, * NS_SOCK_TIMEOUT */ switch (nsSockState) { case NS_SOCK_TIMEOUT: NS_FALL_THROUGH; /* fall through */ case NS_SOCK_EXCEPTION: return SOCK_READERROR; case NS_SOCK_AGAIN: Tcl_DStringSetLength(bufPtr, (int)buflen); return SOCK_MORE; case NS_SOCK_DONE: return SOCK_CLOSE; case NS_SOCK_READ: break; case NS_SOCK_CANCEL: NS_FALL_THROUGH; /* fall through */ case NS_SOCK_EXIT: NS_FALL_THROUGH; /* fall through */ case NS_SOCK_INIT: NS_FALL_THROUGH; /* fall through */ case NS_SOCK_WRITE: Ns_Log(Warning, "SockRead received unexpected state %.2x from driver", nsSockState); return SOCK_READERROR; case NS_SOCK_NONE: /* * Old style state management based on "n" and "errno", which is * more fragile. We keep there for old-style drivers. */ if (n < 0) { Tcl_DStringSetLength(bufPtr, (int)buflen); /* * The driver returns -1 when the peer closed the connection, but * clears the errno such we can distinguish from error conditions. */ if (errno == 0) { return SOCK_CLOSE; } return SOCK_READERROR; } if (n == 0) { Tcl_DStringSetLength(bufPtr, (int)buflen); return SOCK_MORE; } break; } } if (sockPtr->tfd > 0) { if (ns_write(sockPtr->tfd, tbuf, (size_t)n) != n) { return SOCK_WRITEERROR; } } else { Tcl_DStringSetLength(bufPtr, (int)(buflen + (size_t)n)); } reqPtr->woff += (size_t)n; reqPtr->avail += (size_t)n; /* * This driver needs raw buffer, it is binary or non-HTTP request */ if ((drvPtr->opts & NS_DRIVER_NOPARSE) != 0u) { return SOCK_READY; } resultState = SockParse(sockPtr); return resultState; } /*---------------------------------------------------------------------- * * LogBuffer -- * * Debug function to output buffer content when the provided severity is * enabled. The function prints just visible characters and space as is * and prints the hex code otherwise. * * Results: * None. * * Side effects: * Writes to error.log * *---------------------------------------------------------------------- */ static void LogBuffer(Ns_LogSeverity severity, const char *msg, const char *buffer, size_t len) { Tcl_DString ds; NS_NONNULL_ASSERT(msg != NULL); NS_NONNULL_ASSERT(buffer != NULL); if (Ns_LogSeverityEnabled(severity)) { Tcl_DStringInit(&ds); Tcl_DStringAppend(&ds, msg, -1); Tcl_DStringAppend(&ds, ": ", 2); (void)Ns_DStringAppendPrintable(&ds, NS_FALSE, buffer, len); Ns_Log(severity, "%s", ds.string); Tcl_DStringFree(&ds); } } /*---------------------------------------------------------------------- * * EndOfHeader -- * * Function to be called (once), when end of header is reached. At this * time, all request header lines were parsed already correctly. * * Results: * None. * * Side effects: * Update various reqPtr fields and signal certain facts and error * conditions via sockPtr->flags. In error conditions, sockPtr->keep is * set to NS_FALSE. * *---------------------------------------------------------------------- */ static size_t EndOfHeader(Sock *sockPtr) { Request *reqPtr; const char *s; NS_NONNULL_ASSERT(sockPtr != NULL); reqPtr = sockPtr->reqPtr; assert(reqPtr != NULL); reqPtr->chunkStartOff = 0u; /* * Check for "expect: 100-continue" and clear flag in case we have * pipelining. */ sockPtr->flags &= ~(NS_CONN_CONTINUE); s = Ns_SetIGet(reqPtr->headers, "expect"); if (s != NULL) { if (*s == '1' && *(s+1) == '0' && *(s+2) == '0' && *(s+3) == '-') { char *dup = ns_strdup(s+4); Ns_StrToLower(dup); if (STREQ(dup, "continue")) { sockPtr->flags |= NS_CONN_CONTINUE; } ns_free(dup); } } /* * Handle content-length, which might be provided or not. * Clear length specific error flags. */ sockPtr->flags &= ~(NS_CONN_ENTITYTOOLARGE); s = Ns_SetIGet(reqPtr->headers, "content-length"); if (s == NULL) { s = Ns_SetIGet(reqPtr->headers, "Transfer-Encoding"); if (s != NULL) { /* Lower case is in the standard, capitalized by macOS */ if (STREQ(s, "chunked") || STREQ(s, "Chunked")) { Tcl_WideInt expected; reqPtr->chunkStartOff = reqPtr->roff; reqPtr->chunkWriteOff = reqPtr->chunkStartOff; reqPtr->contentLength = 0u; /* * We need reqPtr->expectedLength for safely terminating read loop. */ s = Ns_SetIGet(reqPtr->headers, "X-Expected-Entity-Length"); if ((s != NULL) && (Ns_StrToWideInt(s, &expected) == NS_OK) && (expected > 0) ) { reqPtr->expectedLength = (size_t)expected; } s = NULL; } } } /* * In case a valid and meaningful was provided, the string with the * content length ("s") is not NULL. */ if (s != NULL) { Tcl_WideInt length; if ((Ns_StrToWideInt(s, &length) == NS_OK) && (length > 0)) { reqPtr->length = (size_t)length; /* * Handle too large input requests. */ if (reqPtr->length > (size_t)sockPtr->drvPtr->maxinput) { Ns_Log(Warning, "SockParse: request too large, length=%" PRIdz ", maxinput=%" TCL_LL_MODIFIER "d", reqPtr->length, sockPtr->drvPtr->maxinput); sockPtr->keep = NS_FALSE; sockPtr->flags |= NS_CONN_ENTITYTOOLARGE; } reqPtr->contentLength = (size_t)length; } } /* * Compression format handling: parse information from request headers * indicating allowed compression formats for quick access. * * Clear compression accepted flag */ sockPtr->flags &= ~(NS_CONN_ZIPACCEPTED|NS_CONN_BROTLIACCEPTED); s = Ns_SetIGet(reqPtr->headers, "Accept-Encoding"); if (s != NULL) { bool gzipAccept, brotliAccept; /* * Get allowed compression formats from "accept-encoding" headers. */ NsParseAcceptEncoding(reqPtr->request.version, s, &gzipAccept, &brotliAccept); if (gzipAccept || brotliAccept) { /* * Don't allow compression formats for Range requests. */ s = Ns_SetIGet(reqPtr->headers, "Range"); if (s == NULL) { if (gzipAccept) { sockPtr->flags |= NS_CONN_ZIPACCEPTED; } if (brotliAccept) { sockPtr->flags |= NS_CONN_BROTLIACCEPTED; } } } } /* * Set up request length for spooling and further read operations */ if (reqPtr->contentLength != 0u) { /* * Content-Length was provided, use it */ reqPtr->length = reqPtr->contentLength; } return reqPtr->roff; } /*---------------------------------------------------------------------- * * SockParse -- * * Construct the given conn by parsing input buffer until end of * headers. Return SOCK_READY when finished parsing. * * Results: * SOCK_READY: Conn is ready for processing. * SOCK_MORE: More input is required. * SOCK_ERROR: Malformed request. * SOCK_BADREQUEST * SOCK_BADHEADER * SOCK_TOOMANYHEADERS * * Side effects: * An Ns_Request and/or Ns_Set may be allocated. * Ns_Conn buffer management offsets updated. * *---------------------------------------------------------------------- */ static SockState SockParse(Sock *sockPtr) { const Tcl_DString *bufPtr; const Driver *drvPtr; Request *reqPtr; char save; SockState result; NS_NONNULL_ASSERT(sockPtr != NULL); drvPtr = sockPtr->drvPtr; NsUpdateProgress((Ns_Sock *) sockPtr); reqPtr = sockPtr->reqPtr; bufPtr = &reqPtr->buffer; /* * Scan lines (header) until start of content (body-part) */ while (reqPtr->coff == 0u) { char *s, *e; size_t cnt; /* * Find the next header line. */ s = bufPtr->string + reqPtr->roff; e = memchr(s, INTCHAR('\n'), reqPtr->avail); if (unlikely(e == NULL)) { /* * Input not yet newline terminated - request more data. */ return SOCK_MORE; } /* * Check for max single line overflows. * * Previous versions if the driver returned here directly an * error code, which was handled via HTTP error message * provided via SockError(). However, the SockError() handling * closes the connection immediately. This has the * consequence, that the HTTP client might never see the error * message, since the request was not yet fully transmitted, * but it will see a "broken pipe: 13" message instead. We * read now the full request and return the message via * ConnRunRequest(). */ if (unlikely((e - s) > drvPtr->maxline)) { sockPtr->keep = NS_FALSE; if (reqPtr->request.line == NULL) { Ns_Log(DriverDebug, "SockParse: maxline reached of %d bytes", drvPtr->maxline); sockPtr->flags = NS_CONN_REQUESTURITOOLONG; Ns_Log(Warning, "request line is too long (%d bytes)", (int)(e - s)); } else { sockPtr->flags = NS_CONN_LINETOOLONG; Ns_Log(Warning, "request header line is too long (%d bytes)", (int)(e - s)); } } /* * Update next read pointer to end of this line. */ cnt = (size_t)(e - s) + 1u; reqPtr->roff += cnt; reqPtr->avail -= cnt; /* * Adjust end pointer to the last content character before the line * terminator. */ if (likely(e > s) && likely(*(e-1) == '\r')) { --e; } /* * Check for end of headers in case we have not done it yet. */ if (unlikely(e == s) && (reqPtr->coff == 0u)) { /* * We are at end of headers. */ reqPtr->coff = EndOfHeader(sockPtr); /* * In cases the client sent "expect: 100-continue", report back that * everything is fine with the headers. */ if ((sockPtr->flags & NS_CONN_CONTINUE) != 0u) { Ns_Log(Ns_LogRequestDebug, "honoring 100-continue"); /* * In case, the request entity (body) was too large, we can * return immediately the error message, when the client has * flagged this via "Expect:". Otherwise we have to read the * full request (although it is too large) to drain the * channel. Otherwise, the server might close the connection * *before* it has received full request with its body from * the client. We just keep the flag and let * Ns_ConnRunRequest() handle the error message. */ if ((sockPtr->flags & NS_CONN_ENTITYTOOLARGE) != 0u) { Ns_Log(Ns_LogRequestDebug, "100-continue: entity too large"); return SOCK_ENTITYTOOLARGE; /* * We have no other error message flagged (future ones * have to be handled here). */ } else { struct iovec iov[1]; ssize_t sent; /* * Reply with "100 continue". */ Ns_Log(Ns_LogRequestDebug, "100-continue: reply CONTINUE"); iov[0].iov_base = (char *)"HTTP/1.1 100 Continue\r\n\r\n"; iov[0].iov_len = strlen(iov[0].iov_base); sent = Ns_SockSendBufs((Ns_Sock *)sockPtr, iov, 1, NULL, 0u); if (sent != (ssize_t)iov[0].iov_len) { Ns_Log(Warning, "could not deliver response: 100 Continue"); /* * Should we bail out here? */ } } } } else { /* * We have the request-line or a header line to process. */ save = *e; *e = '\0'; if (unlikely(reqPtr->request.line == NULL)) { /* * There is no request-line set. The received line must the * the request-line. */ Ns_Log(DriverDebug, "SockParse (%d): parse request line <%s>", sockPtr->sock, s); if (Ns_ParseRequest(&reqPtr->request, s) == NS_ERROR) { /* * Invalid request. */ return SOCK_BADREQUEST; } /* * HTTP 0.9 did not have a HTTP-version number or request headers * and no empty line terminating the request header. */ if (unlikely(reqPtr->request.version < 1.0)) { /* * Pre-HTTP/1.0 request. */ reqPtr->coff = reqPtr->roff; Ns_Log(Notice, "pre-HTTP/1.0 request <%s>", reqPtr->request.line); } } else if (Ns_ParseHeader(reqPtr->headers, s, Preserve) != NS_OK) { /* * Invalid header. */ return SOCK_BADHEADER; } else { /* * Check for max number of headers */ if (unlikely(Ns_SetSize(reqPtr->headers) > (size_t)drvPtr->maxheaders)) { Ns_Log(DriverDebug, "SockParse (%d): maxheaders reached of %d bytes", sockPtr->sock, drvPtr->maxheaders); return SOCK_TOOMANYHEADERS; } } *e = save; } } if (unlikely(reqPtr->request.line == NULL)) { /* * We are at end of headers, but we have not parsed a request line * (maybe just two linefeeds). */ return SOCK_BADREQUEST; } /* * We are in the request body. */ assert(reqPtr->coff > 0u); assert(reqPtr->request.line != NULL); /* * Check if all content has arrived. */ Ns_Log(Dev, "=== length < avail (length %" PRIuz ", avail %" PRIuz ") tfd %d tfile %p chunkStartOff %" PRIuz, reqPtr->length, reqPtr->avail, sockPtr->tfd, (void *)sockPtr->tfile, reqPtr->chunkStartOff); if (reqPtr->chunkStartOff != 0u) { /* * Chunked encoding was provided. */ bool complete; size_t currentContentLength; complete = ChunkedDecode(reqPtr, NS_TRUE); currentContentLength = reqPtr->chunkWriteOff - reqPtr->coff; /* * A chunk might be complete, but it might not be the last * chunk from the client. The best thing would be to be able * to read until EOF here. In cases, where the (optional) * "expectedLength" was provided by the client, we terminate * depending on that information */ if ((!complete) || (reqPtr->expectedLength != 0u && currentContentLength < reqPtr->expectedLength)) { /* * ChunkedDecode wants more data. */ return SOCK_MORE; } /* * ChunkedDecode has enough data. */ reqPtr->length = (size_t)currentContentLength; } if (reqPtr->avail < reqPtr->length) { Ns_Log(DriverDebug, "SockRead wait for more input"); /* * Wait for more input. */ return SOCK_MORE; } Ns_Log(Dev, "=== all required data is available (avail %" PRIuz", length %" PRIuz ", " "readahead %" TCL_LL_MODIFIER "d maxupload %" TCL_LL_MODIFIER "d) tfd %d", reqPtr->avail, reqPtr->length, drvPtr->readahead, drvPtr->maxupload, sockPtr->tfd); /* * We have all required data in the receive buffer or in a temporary file. * * - Uploads > "readahead": these are put into temporary files. * * - Uploads > "maxupload": these are put into temporary files * without mmapping, no content parsing will be performed in memory. */ result = SOCK_READY; if (sockPtr->tfile != NULL) { reqPtr->content = NULL; reqPtr->next = NULL; reqPtr->avail = 0u; Ns_Log(DriverDebug, "content spooled to file: size %" PRIdz ", file %s", reqPtr->length, sockPtr->tfile); /* * Nothing more to do, return via SOCK_READY; */ } else { /* * Uploads < "maxupload" are spooled to files and mmapped in order to * provide the usual interface via [ns_conn content]. */ if (sockPtr->tfd > 0) { #ifdef _WIN32 /* * For _WIN32, tfd should never be set, since tfd-spooling is not * implemented for windows. */ assert(0); #else int prot = PROT_READ | PROT_WRITE; /* * Add a byte to make sure, the string termination with \0 below falls * always into the mmapped area. On some older OSes this might lead to * crashes when we hitting page boundaries. */ ssize_t rc = ns_write(sockPtr->tfd, "\0", 1); if (rc == -1) { Ns_Log(Error, "socket: could not append terminating 0-byte"); } sockPtr->tsize = reqPtr->length + 1; sockPtr->taddr = mmap(0, sockPtr->tsize, prot, MAP_PRIVATE, sockPtr->tfd, 0); if (sockPtr->taddr == MAP_FAILED) { sockPtr->taddr = NULL; result = SOCK_ERROR; } else { reqPtr->content = sockPtr->taddr; Ns_Log(Debug, "content spooled to mmapped file: readahead=%" TCL_LL_MODIFIER "d, filesize=%" PRIdz, drvPtr->readahead, sockPtr->tsize); } #endif } else { /* * Set the content the begin of the remaining buffer (content offset). * This happens as well when reqPtr->contentLength is 0, but it is * needed for chunked input processing. */ reqPtr->content = bufPtr->string + reqPtr->coff; } reqPtr->next = reqPtr->content; /* * Add a terminating null character. The content might be from the receive * buffer (Tcl_DString) or from the mmapped file. Non-mmapped files are handled * above. */ if (reqPtr->length > 0u) { Ns_Log(DriverDebug, "SockRead adds null terminating character at content[%" PRIuz "]", reqPtr->length); reqPtr->savedChar = reqPtr->content[reqPtr->length]; reqPtr->content[reqPtr->length] = '\0'; if (sockPtr->taddr == NULL) { LogBuffer(DriverDebug, "UPDATED BUFFER", sockPtr->reqPtr->buffer.string, (size_t)reqPtr->buffer.length); } } } return result; } /* *---------------------------------------------------------------------- * * SockSetServer -- * * Set virtual server from driver context or Host header. * * Results: * void. * * Side effects: * * Updates sockPtr->servPtr. In case an invalid server set, or the * required host field in HTTP/1.1 is missing the HTTP-method is set to * the constant "BAD". * *---------------------------------------------------------------------- */ static void SockSetServer(Sock *sockPtr) { char *host; Request *reqPtr; bool bad_request = NS_FALSE; Driver *drvPtr; NS_NONNULL_ASSERT(sockPtr != NULL); reqPtr = sockPtr->reqPtr; assert(reqPtr != NULL); drvPtr = sockPtr->drvPtr; assert(drvPtr != NULL); sockPtr->servPtr = drvPtr->servPtr; sockPtr->location = drvPtr->location; host = Ns_SetIGet(reqPtr->headers, "Host"); Ns_Log(DriverDebug, "SockSetServer host '%s' request line '%s'", host, reqPtr->request.line); if (unlikely((host == NULL) && (reqPtr->request.version >= 1.1))) { /* * HTTP/1.1 requires host header */ Ns_Log(Notice, "request header field \"Host\" is missing in HTTP/1.1 request: \"%s\"\n", reqPtr->request.line); bad_request = NS_TRUE; } if (sockPtr->servPtr == NULL) { const ServerMap *mapPtr = NULL; if (host != NULL) { const Tcl_HashEntry *hPtr; size_t hostLength = strlen(host); /* * Remove trailing dot of host header field, since RFC 2976 allows * fully qualified "absolute" DNS names in host fields (see e.g. §3.2.2). */ if (host[hostLength] == '.') { host[hostLength] = '\0'; } /* * Convert provided host header field to lower case before hash * lookup. */ Ns_StrToLower(host); hPtr = Tcl_FindHashEntry(&drvPtr->hosts, host); Ns_Log(DriverDebug, "SockSetServer driver '%s' host '%s' => %p", drvPtr->moduleName, host, (void*)hPtr); if (hPtr != NULL) { /* * Request with provided host header field could be resolved * against a certain server. */ mapPtr = Tcl_GetHashValue(hPtr); } else { /* * Host header field content is not found in the mapping table. */ Ns_Log(DriverDebug, "cannot locate host header content '%s' in virtual hosts " "table of driver '%s', fall back to default '%s'", host, drvPtr->moduleName, drvPtr->defMapPtr->location); if (Ns_LogSeverityEnabled(DriverDebug)) { Tcl_HashEntry *hPtr2; Tcl_HashSearch search; hPtr2 = Tcl_FirstHashEntry(&drvPtr->hosts, &search); while (hPtr2 != NULL) { Ns_Log(Notice, "... host entry: '%s'\n", (char *)Tcl_GetHashKey(&drvPtr->hosts, hPtr2)); hPtr2 = Tcl_NextHashEntry(&search); } } } } if (mapPtr == NULL) { /* * Could not lookup the virtual host, Get the default mapping from the driver. */ mapPtr = drvPtr->defMapPtr; } if (mapPtr != NULL) { sockPtr->servPtr = mapPtr->servPtr; sockPtr->location = mapPtr->location; } if (sockPtr->servPtr == NULL) { Ns_Log(Warning, "cannot determine server for request: \"%s\" (host \"%s\")\n", reqPtr->request.line, host); bad_request = NS_TRUE; } } if (unlikely(bad_request)) { Ns_Log(DriverDebug, "SockSetServer sets method to BAD"); ns_free((char *)reqPtr->request.method); reqPtr->request.method = ns_strdup("BAD"); } } /* *====================================================================== * Spooler Thread: Receive asynchronously from the client socket *====================================================================== */ /* *---------------------------------------------------------------------- * * SpoolerThread -- * * Spooling socket driver thread. * * Results: * None. * * Side effects: * Connections are accepted on the configured listen sockets, * placed on the run queue to be serviced, and gracefully * closed when done. Async sockets have the entire request read * here before queuing as well. * *---------------------------------------------------------------------- */ static void SpoolerThread(void *arg) { SpoolerQueue *queuePtr = (SpoolerQueue*)arg; char charBuffer[1]; int pollTimeout; bool stopping; Sock *sockPtr, *nextPtr, *waitPtr, *readPtr; Ns_Time now, diff; const Driver *drvPtr; PollData pdata; Ns_ThreadSetName("-spooler%d-", queuePtr->id); queuePtr->threadName = Ns_ThreadGetName(); /* * Loop forever until signaled to shut down and all * connections are complete and gracefully closed. */ Ns_Log(Notice, "spooler%d: accepting connections", queuePtr->id); PollCreate(&pdata); Ns_GetTime(&now); waitPtr = readPtr = NULL; stopping = NS_FALSE; while (!stopping) { /* * If there are any read sockets, set the bits * and determine the minimum relative timeout. */ PollReset(&pdata); (void)PollSet(&pdata, queuePtr->pipe[0], (short)POLLIN, NULL); if (readPtr == NULL) { pollTimeout = 30 * 1000; } else { sockPtr = readPtr; while (sockPtr != NULL) { SockPoll(sockPtr, (short)POLLIN, &pdata); sockPtr = sockPtr->nextPtr; } pollTimeout = -1; } /* * Select and drain the trigger pipe if necessary. */ /*n =*/ (void) PollWait(&pdata, pollTimeout); if (PollIn(&pdata, 0) && unlikely(ns_recv(queuePtr->pipe[0], charBuffer, 1u, 0) != 1)) { Ns_Fatal("spooler: trigger ns_recv() failed: %s", ns_sockstrerror(ns_sockerrno)); } /* * Attempt read-ahead of any new connections. */ Ns_GetTime(&now); sockPtr = readPtr; readPtr = NULL; while (sockPtr != NULL) { nextPtr = sockPtr->nextPtr; drvPtr = sockPtr->drvPtr; if (unlikely(PollHup(&pdata, sockPtr->pidx))) { /* * Peer has closed the connection */ SockRelease(sockPtr, SOCK_CLOSE, 0); } else if (!PollIn(&pdata, sockPtr->pidx)) { /* * Got no data */ if (Ns_DiffTime(&sockPtr->timeout, &now, &diff) <= 0) { SockRelease(sockPtr, SOCK_READTIMEOUT, 0); queuePtr->queuesize--; } else { Push(sockPtr, readPtr); } } else { /* * Got some data */ SockState n = SockRead(sockPtr, 1, &now); switch (n) { case SOCK_MORE: SockTimeout(sockPtr, &now, &drvPtr->recvwait); Push(sockPtr, readPtr); break; case SOCK_READY: assert(sockPtr->reqPtr != NULL); SockSetServer(sockPtr); Push(sockPtr, waitPtr); break; case SOCK_BADHEADER: NS_FALL_THROUGH; /* fall through */ case SOCK_BADREQUEST: NS_FALL_THROUGH; /* fall through */ case SOCK_CLOSE: NS_FALL_THROUGH; /* fall through */ case SOCK_CLOSETIMEOUT: NS_FALL_THROUGH; /* fall through */ case SOCK_ENTITYTOOLARGE: NS_FALL_THROUGH; /* fall through */ case SOCK_ERROR: NS_FALL_THROUGH; /* fall through */ case SOCK_READERROR: NS_FALL_THROUGH; /* fall through */ case SOCK_READTIMEOUT: NS_FALL_THROUGH; /* fall through */ case SOCK_SHUTERROR: NS_FALL_THROUGH; /* fall through */ case SOCK_SPOOL: NS_FALL_THROUGH; /* fall through */ case SOCK_TOOMANYHEADERS: NS_FALL_THROUGH; /* fall through */ case SOCK_WRITEERROR: NS_FALL_THROUGH; /* fall through */ case SOCK_WRITETIMEOUT: SockRelease(sockPtr, n, errno); queuePtr->queuesize--; break; } } sockPtr = nextPtr; } /* * Attempt to queue any pending connection * after reversing the list to ensure oldest * connections are tried first. */ if (waitPtr != NULL) { sockPtr = NULL; while ((nextPtr = waitPtr) != NULL) { waitPtr = nextPtr->nextPtr; Push(nextPtr, sockPtr); } while (sockPtr != NULL) { nextPtr = sockPtr->nextPtr; if (!NsQueueConn(sockPtr, &now)) { Push(sockPtr, waitPtr); } else { queuePtr->queuesize--; } sockPtr = nextPtr; } } /* * Add more connections from the spooler queue */ Ns_MutexLock(&queuePtr->lock); if (waitPtr == NULL) { sockPtr = (Sock*)queuePtr->sockPtr; queuePtr->sockPtr = NULL; while (sockPtr != NULL) { nextPtr = sockPtr->nextPtr; drvPtr = sockPtr->drvPtr; SockTimeout(sockPtr, &now, &drvPtr->recvwait); Push(sockPtr, readPtr); queuePtr->queuesize++; sockPtr = nextPtr; } } /* * Check for shutdown */ stopping = queuePtr->shutdown; Ns_MutexUnlock(&queuePtr->lock); } PollFree(&pdata); Ns_Log(Notice, "exiting"); Ns_MutexLock(&queuePtr->lock); queuePtr->stopped = NS_TRUE; Ns_CondBroadcast(&queuePtr->cond); Ns_MutexUnlock(&queuePtr->lock); } static void SpoolerQueueStart(SpoolerQueue *queuePtr, Ns_ThreadProc *proc) { NS_NONNULL_ASSERT(proc != NULL); while (queuePtr != NULL) { if (ns_sockpair(queuePtr->pipe) != 0) { Ns_Fatal("ns_sockpair() failed: %s", ns_sockstrerror(ns_sockerrno)); } Ns_ThreadCreate(proc, queuePtr, 0, &queuePtr->thread); queuePtr = queuePtr->nextPtr; } } static void SpoolerQueueStop(SpoolerQueue *queuePtr, const Ns_Time *timeoutPtr, const char *name) { NS_NONNULL_ASSERT(timeoutPtr != NULL); NS_NONNULL_ASSERT(name != NULL); while (queuePtr != NULL) { Ns_ReturnCode status; Ns_MutexLock(&queuePtr->lock); if (!queuePtr->stopped && !queuePtr->shutdown) { Ns_Log(Debug, "%s%d: triggering shutdown", name, queuePtr->id); queuePtr->shutdown = NS_TRUE; SockTrigger(queuePtr->pipe[1]); } status = NS_OK; while (!queuePtr->stopped && status == NS_OK) { status = Ns_CondTimedWait(&queuePtr->cond, &queuePtr->lock, timeoutPtr); } if (status != NS_OK) { Ns_Log(Warning, "%s%d: timeout waiting for shutdown", name, queuePtr->id); } else { /*Ns_Log(Notice, "%s%d: shutdown complete", name, queuePtr->id);*/ if (queuePtr->thread != NULL) { Ns_ThreadJoin(&queuePtr->thread, NULL); queuePtr->thread = NULL; } else { Ns_Log(Notice, "%s%d: shutdown: thread already gone", name, queuePtr->id); } ns_sockclose(queuePtr->pipe[0]); ns_sockclose(queuePtr->pipe[1]); } Ns_MutexUnlock(&queuePtr->lock); queuePtr = queuePtr->nextPtr; } } static int SockSpoolerQueue(Driver *drvPtr, Sock *sockPtr) { bool trigger = NS_FALSE; SpoolerQueue *queuePtr; NS_NONNULL_ASSERT(drvPtr != NULL); NS_NONNULL_ASSERT(sockPtr != NULL); /* * Get the next spooler thread from the list, all spooler requests are * rotated between all spooler threads */ Ns_MutexLock(&drvPtr->spooler.lock); if (drvPtr->spooler.curPtr == NULL) { drvPtr->spooler.curPtr = drvPtr->spooler.firstPtr; } queuePtr = drvPtr->spooler.curPtr; drvPtr->spooler.curPtr = drvPtr->spooler.curPtr->nextPtr; Ns_MutexUnlock(&drvPtr->spooler.lock); Ns_Log(Debug, "Spooler: %d: started fd=%d: %" PRIdz " bytes", queuePtr->id, sockPtr->sock, sockPtr->reqPtr->length); Ns_MutexLock(&queuePtr->lock); if (queuePtr->sockPtr == NULL) { trigger = NS_TRUE; } Push(sockPtr, queuePtr->sockPtr); Ns_MutexUnlock(&queuePtr->lock); /* * Wake up spooler thread */ if (trigger) { SockTrigger(queuePtr->pipe[1]); } return 1; } /* *====================================================================== * Writer Thread: Write asynchronously to the client socket *====================================================================== */ /* *---------------------------------------------------------------------- * * NsWriterLock, NsWriterUnlock -- * * Provide an API for locking and unlocking context information * for streaming asynchronous writer jobs. The locks are just * needed for managing linkage between "connPtr" and a writer * entry. The lock operations are rather infrequent and the * lock duration is very short, such that at a single global * appears sufficient. * * Results: * None * * Side effects: * Change Mutex state. * *---------------------------------------------------------------------- */ void NsWriterLock(void) { Ns_MutexLock(&writerlock); } void NsWriterUnlock(void) { Ns_MutexUnlock(&writerlock); } /* *---------------------------------------------------------------------- * * WriterSockFileVecCleanup -- * * Cleanup function for FileVec array in WriterSock structure. * * Results: * None. * * Side effects: * Closing potentially file descriptors, freeing Ns_FileVec memory. * *---------------------------------------------------------------------- */ static void WriterSockFileVecCleanup(WriterSock *wrSockPtr) { NS_NONNULL_ASSERT(wrSockPtr != NULL); if ( wrSockPtr->c.file.nbufs > 0) { int i; Ns_Log(DriverDebug, "WriterSockRelease nbufs %d", wrSockPtr->c.file.nbufs); for (i = 0; i < wrSockPtr->c.file.nbufs; i++) { /* * The fd of c.file.currentbuf is always the same as * wrSockPtr->fd and therefore already closed at this point. */ if ( (i != wrSockPtr->c.file.currentbuf) && (wrSockPtr->c.file.bufs[i].fd != NS_INVALID_FD) ) { Ns_Log(DriverDebug, "WriterSockRelease must close fd %d", wrSockPtr->c.file.bufs[i].fd); ns_close(wrSockPtr->c.file.bufs[i].fd); } } ns_free(wrSockPtr->c.file.bufs); } ns_free(wrSockPtr->c.file.buf); } /* *---------------------------------------------------------------------- * * WriterSockRequire, WriterSockRelease -- * * Management functions for WriterSocks. WriterSockRequire() and * WriterSockRelease() are responsible for obtaining and * freeing "WriterSock" structures. When shuch a structure is finally * released, it is removed from the queue, the socket is * closed and the memory is freed. * * Results: * WriterSockRequire() returns a WriterSock from a connection, * the other functions return nothing. * * Side effects: * Updating reference counters, closing socket, freeing memory. * *---------------------------------------------------------------------- */ static WriterSock * WriterSockRequire(const Conn *connPtr) { WriterSock *wrSockPtr; NS_NONNULL_ASSERT(connPtr != NULL); NsWriterLock(); wrSockPtr = (WriterSock *)connPtr->strWriter; if (wrSockPtr != NULL) { wrSockPtr->refCount ++; } NsWriterUnlock(); return wrSockPtr; } static void WriterSockRelease(WriterSock *wrSockPtr) { SpoolerQueue *queuePtr; NS_NONNULL_ASSERT(wrSockPtr != NULL); wrSockPtr->refCount --; Ns_Log(DriverDebug, "WriterSockRelease %p refCount %d keep %d", (void *)wrSockPtr, wrSockPtr->refCount, wrSockPtr->keep); if (wrSockPtr->refCount > 0) { return; } Ns_Log(DriverDebug, "Writer: closed sock %d, file fd %d, error %d/%d, " "sent=%" TCL_LL_MODIFIER "d, flags=%X", wrSockPtr->sockPtr->sock, wrSockPtr->fd, wrSockPtr->status, wrSockPtr->err, wrSockPtr->nsent, wrSockPtr->flags); NsPoolAddBytesSent(wrSockPtr->poolPtr, wrSockPtr->nsent); if (wrSockPtr->doStream != NS_WRITER_STREAM_NONE) { Conn *connPtr; NsWriterLock(); connPtr = wrSockPtr->connPtr; if (connPtr != NULL && connPtr->strWriter != NULL) { connPtr->strWriter = NULL; } NsWriterUnlock(); /* * In case, writer streams are activated for this wrSockPtr, make sure * to release the tmp file. See thread Naviserver Open Files on the * sourceforge mailing list (starting July 2019). */ if (wrSockPtr->doStream == NS_WRITER_STREAM_FINISH) { Ns_ReleaseTemp(wrSockPtr->fd); } } /* * Remove the entry from the queue and decrement counter */ queuePtr = wrSockPtr->queuePtr; if (queuePtr->curPtr == wrSockPtr) { queuePtr->curPtr = wrSockPtr->nextPtr; queuePtr->queuesize--; } else { WriterSock *curPtr, *lastPtr = queuePtr->curPtr; for (curPtr = (lastPtr != NULL) ? lastPtr->nextPtr : NULL; curPtr != NULL; lastPtr = curPtr, curPtr = curPtr->nextPtr ) { if (curPtr == wrSockPtr) { lastPtr->nextPtr = wrSockPtr->nextPtr; queuePtr->queuesize--; break; } } } if ((wrSockPtr->err != 0) || (wrSockPtr->status != SPOOLER_OK)) { int i; /* * Lookup the matching sockState from the spooler state. The array has * just 5 elements, on average, just 2 comparisons are needed (since * OK is at the end). */ for (i = 0; i < Ns_NrElements(spoolerStateMap); i++) { if (spoolerStateMap[i].spoolerState == wrSockPtr->status) { SockError(wrSockPtr->sockPtr, spoolerStateMap[i].sockState, wrSockPtr->err); break; } } NsSockClose(wrSockPtr->sockPtr, (int)NS_FALSE); } else { NsSockClose(wrSockPtr->sockPtr, (int)wrSockPtr->keep); } if (wrSockPtr->clientData != NULL) { ns_free(wrSockPtr->clientData); } if (wrSockPtr->fd != NS_INVALID_FD) { if (wrSockPtr->doStream != NS_WRITER_STREAM_FINISH) { (void) ns_close(wrSockPtr->fd); } WriterSockFileVecCleanup(wrSockPtr); } else if (wrSockPtr->c.mem.bufs != NULL) { if (wrSockPtr->c.mem.fmap.addr != NULL) { NsMemUmap(&wrSockPtr->c.mem.fmap); } else { int i; for (i = 0; i < wrSockPtr->c.mem.nbufs; i++) { ns_free((char *)wrSockPtr->c.mem.bufs[i].iov_base); } } if (wrSockPtr->c.mem.bufs != wrSockPtr->c.mem.preallocated_bufs) { ns_free(wrSockPtr->c.mem.bufs); } } if (wrSockPtr->headerString != NULL) { ns_free(wrSockPtr->headerString); } ns_free(wrSockPtr); } /* *---------------------------------------------------------------------- * * WriterReadFromSpool -- * * Utility function of the WriterThread to read blocks from a * file into the output buffer of the writer. It handles * left overs from previous send attempts and takes care for * locking in case simultaneous reading and writing from the * same file. * * Results: * None. * * Side effects: * Fills up curPtr->c.file.buf and updates counters/sizes. * *---------------------------------------------------------------------- */ static SpoolerState WriterReadFromSpool(WriterSock *curPtr) { NsWriterStreamState doStream; SpoolerState status = SPOOLER_OK; size_t maxsize, toRead; unsigned char *bufPtr; NS_NONNULL_ASSERT(curPtr != NULL); doStream = curPtr->doStream; if (doStream != NS_WRITER_STREAM_NONE) { Ns_MutexLock(&curPtr->c.file.fdlock); toRead = curPtr->c.file.toRead; Ns_MutexUnlock(&curPtr->c.file.fdlock); } else { toRead = curPtr->c.file.toRead; Ns_Log(DriverDebug, "### WriterReadFromSpool [%d]: fd %d tosend %lu files %d", curPtr->c.file.currentbuf, curPtr->fd, toRead, curPtr->c.file.nbufs); } maxsize = curPtr->c.file.maxsize; bufPtr = curPtr->c.file.buf; /* * When bufsize > 0 we have a leftover from previous send. In such * cases, move the leftover to the front, and fill the reminder of * the buffer with new data from curPtr->c. */ if (curPtr->c.file.bufsize > 0u) { Ns_Log(DriverDebug, "### WriterReadFromSpool %p %.6x leftover %" PRIdz " offset %ld", (void *)curPtr, curPtr->flags, curPtr->c.file.bufsize, (long)curPtr->c.file.bufoffset); if (likely(curPtr->c.file.bufoffset > 0)) { memmove(curPtr->c.file.buf, curPtr->c.file.buf + curPtr->c.file.bufoffset, curPtr->c.file.bufsize); } bufPtr = curPtr->c.file.buf + curPtr->c.file.bufsize; maxsize -= curPtr->c.file.bufsize; } if (toRead > maxsize) { toRead = maxsize; } /* * Read content from the file into the buffer. */ if (toRead > 0u) { ssize_t n; if (doStream != NS_WRITER_STREAM_NONE) { /* * In streaming mode, the connection thread writes to the * spool file and the writer thread reads from the same * file. Therefore, we have to re-adjust the current * read/writer position, which might be changed by the * other thread. These positions have to be locked, since * seeking might be subject to race conditions. Here we * set the read pointer to the position after the last * send operation. */ Ns_MutexLock(&curPtr->c.file.fdlock); (void) ns_lseek(curPtr->fd, (off_t)curPtr->nsent, SEEK_SET); } if (curPtr->c.file.nbufs == 0) { /* * Working on a single fd. */ n = ns_read(curPtr->fd, bufPtr, toRead); } else { /* * Working on a Ns_FileVec. */ int currentbuf = curPtr->c.file.currentbuf; size_t wantRead = curPtr->c.file.bufs[currentbuf].length; size_t segSize = (wantRead > toRead ? toRead : wantRead); n = ns_read(curPtr->fd, bufPtr, segSize); Ns_Log(DriverDebug, "### WriterReadFromSpool [%d] (nbufs %d): read from fd %d want %lu got %ld (remain %lu)", currentbuf, curPtr->c.file.nbufs, curPtr->fd, segSize, n, wantRead); if (n > 0) { /* * Reduce the remaining length in the Ns_FileVec for the * next iteration. */ curPtr->c.file.bufs[currentbuf].length -= (size_t)n; if ((size_t)n < wantRead) { /* * Partial read on a segment. */ Ns_Log(DriverDebug, "### WriterReadFromSpool [%d] (nbufs %d): partial read on fd %d (got %ld)", currentbuf, curPtr->c.file.nbufs, curPtr->fd, n); } else if (currentbuf < curPtr->c.file.nbufs - 1 /* && (n == wantRead) */) { /* * All read from this segment, setup next read. */ ns_close(curPtr->fd); curPtr->c.file.bufs[currentbuf].fd = NS_INVALID_FD; curPtr->c.file.currentbuf ++; curPtr->fd = curPtr->c.file.bufs[curPtr->c.file.currentbuf].fd; Ns_Log(DriverDebug, "### WriterReadFromSpool switch to [%d] fd %d", curPtr->c.file.currentbuf, curPtr->fd); } } } if (n <= 0) { status = SPOOLER_READERROR; } else { /* * curPtr->c.file.toRead is still protected by * curPtr->c.file.fdlock when needed (in streaming mode). */ curPtr->c.file.toRead -= (size_t)n; curPtr->c.file.bufsize += (size_t)n; } if (doStream != NS_WRITER_STREAM_NONE) { Ns_MutexUnlock(&curPtr->c.file.fdlock); } } return status; } /* *---------------------------------------------------------------------- * * WriterSend -- * * Utility function of the WriterThread to send content to the client. It * handles partial write operations from the lower level driver * infrastructure. * * Results: * either NS_OK or SOCK_ERROR; * * Side effects: * Sends data, might reshuffle iovec. * *---------------------------------------------------------------------- */ static SpoolerState WriterSend(WriterSock *curPtr, int *err) { const struct iovec *bufs; struct iovec vbuf; int nbufs; SpoolerState status = SPOOLER_OK; size_t toWrite; ssize_t n; NS_NONNULL_ASSERT(curPtr != NULL); NS_NONNULL_ASSERT(err != NULL); /* * Prepare send operation */ if (curPtr->fd != NS_INVALID_FD) { /* * We have a valid file descriptor, send data from file. * * Prepare sending a single buffer with curPtr->c.file.bufsize bytes * from the curPtr->c.file.buf to the client. */ vbuf.iov_len = curPtr->c.file.bufsize; vbuf.iov_base = (void *)curPtr->c.file.buf; bufs = &vbuf; nbufs = 1; toWrite = curPtr->c.file.bufsize; } else { int i; /* * Prepare sending multiple memory buffers. Get length of remaining * buffers. */ toWrite = 0u; for (i = 0; i < curPtr->c.mem.nsbufs; i ++) { toWrite += curPtr->c.mem.sbufs[i].iov_len; } Ns_Log(DriverDebug, "### Writer wants to send remainder nbufs %d len %" PRIdz, curPtr->c.mem.nsbufs, toWrite); /* * Add buffers from the source and fill structure up to max */ while (curPtr->c.mem.bufIdx < curPtr->c.mem.nbufs && curPtr->c.mem.sbufIdx < UIO_SMALLIOV) { const struct iovec *vPtr = &curPtr->c.mem.bufs[curPtr->c.mem.bufIdx]; if (vPtr->iov_len > 0u && vPtr->iov_base != NULL) { Ns_Log(DriverDebug, "### Writer copies source %d to scratch %d len %" PRIiovlen, curPtr->c.mem.bufIdx, curPtr->c.mem.sbufIdx, vPtr->iov_len); toWrite += Ns_SetVec(curPtr->c.mem.sbufs, curPtr->c.mem.sbufIdx++, vPtr->iov_base, vPtr->iov_len); curPtr->c.mem.nsbufs++; } curPtr->c.mem.bufIdx++; } bufs = curPtr->c.mem.sbufs; nbufs = curPtr->c.mem.nsbufs; Ns_Log(DriverDebug, "### Writer wants to send %d bufs size %" PRIdz, nbufs, toWrite); } /* * Perform the actual send operation. */ n = NsDriverSend(curPtr->sockPtr, bufs, nbufs, 0u); if (n == -1) { *err = ns_sockerrno; status = SPOOLER_WRITEERROR; } else { /* * We have sent zero or more bytes. */ if (curPtr->doStream != NS_WRITER_STREAM_NONE) { Ns_MutexLock(&curPtr->c.file.fdlock); curPtr->size -= (size_t)n; Ns_MutexUnlock(&curPtr->c.file.fdlock); } else { curPtr->size -= (size_t)n; } curPtr->nsent += n; curPtr->sockPtr->timeout.sec = 0; if (curPtr->fd != NS_INVALID_FD) { /* * File-descriptor based send operation. Reduce the (remainig) * buffer size the amount of data sent and adjust the buffer * offset. For partial send operations, this will lead to a * remaining buffer size > 0. */ curPtr->c.file.bufsize -= (size_t)n; curPtr->c.file.bufoffset = (off_t)n; } else { if (n < (ssize_t)toWrite) { /* * We have a partial transmit from the iovec * structure. We have to compact it to fill content in * the next round. */ curPtr->c.mem.sbufIdx = Ns_ResetVec(curPtr->c.mem.sbufs, curPtr->c.mem.nsbufs, (size_t)n); curPtr->c.mem.nsbufs -= curPtr->c.mem.sbufIdx; memmove(curPtr->c.mem.sbufs, curPtr->c.mem.sbufs + curPtr->c.mem.sbufIdx, /* move the iovecs to the start of the scratch buffers */ sizeof(struct iovec) * (size_t)curPtr->c.mem.nsbufs); } } } return status; } /* *---------------------------------------------------------------------- * * WriterGetInfoPtr -- * * Helper function to obtain ConnPoolInfo structure for a WriterSock. * * The connInfoPtr is allocated only once per pool and cached in the * WriterSock. Only the first time, a writer thread "sees" a pool, it * allocates the structure for it. * * Results: * None. * * Side effects: * Can allocate memory * *---------------------------------------------------------------------- */ static ConnPoolInfo * WriterGetInfoPtr(WriterSock *curPtr, Tcl_HashTable *pools) { NS_NONNULL_ASSERT(curPtr != NULL); NS_NONNULL_ASSERT(pools != NULL); if (curPtr->infoPtr == NULL) { int isNew; Tcl_HashEntry *hPtr; hPtr = Tcl_CreateHashEntry(pools, (void*)curPtr->poolPtr, &isNew); if (isNew == 1) { /* * This is a pool that we have not seen yet. */ curPtr->infoPtr = ns_malloc(sizeof(ConnPoolInfo)); curPtr->infoPtr->currentPoolRate = 0; curPtr->infoPtr->threadSlot = NsPoolAllocateThreadSlot(curPtr->poolPtr, Ns_ThreadId()); Tcl_SetHashValue(hPtr, curPtr->infoPtr); Ns_Log(DriverDebug, "poollimit: pool '%s' allocate infoPtr with slot %lu poolLimit %d", curPtr->poolPtr->pool, curPtr->infoPtr->threadSlot, curPtr->poolPtr->rate.poolLimit); } else { curPtr->infoPtr = (ConnPoolInfo *)Tcl_GetHashValue(hPtr); } } return curPtr->infoPtr; } /* *---------------------------------------------------------------------- * * WriterPerPoolRates -- * * Compute current bandwidths per pool and writer. * * Since we have potentially multiple writer threads running, all these * might have writer threads of the same pool. In order to minimize * locking, we compute first writer thread specific subresults and combine * these later with with the results of the other threads. * * Results: * None. * * Side effects: * Connections are accepted and their SockPtr is set to NULL * such that closing actual connection does not close the socket. * *---------------------------------------------------------------------- */ static void WriterPerPoolRates(WriterSock *writePtr, Tcl_HashTable *pools) { WriterSock *curPtr; Tcl_HashSearch search; Tcl_HashEntry *hPtr; NS_NONNULL_ASSERT(writePtr != NULL); NS_NONNULL_ASSERT(pools != NULL); /* * First reset pool total rate. We keep the bandwidth managed pools in a * thread-local memory. Before, we accumulate the data, we reset it. */ hPtr = Tcl_FirstHashEntry(pools, &search); while (hPtr != NULL) { ConnPoolInfo *infoPtr = (ConnPoolInfo *)Tcl_GetHashValue(hPtr); infoPtr->currentPoolRate = 0; hPtr = Tcl_NextHashEntry(&search); } /* * Sum the actual rates per bandwidth limited pool for all active writer * jobs. */ for (curPtr = writePtr; curPtr != NULL; curPtr = curPtr->nextPtr) { /* * Does the writer come form a badwidth limited pool? */ if (curPtr->poolPtr->rate.poolLimit > 0 && curPtr->currentRate > 0) { /* * Add the actual rate to the writer specific pool rate. */ ConnPoolInfo *infoPtr = WriterGetInfoPtr(curPtr, pools); infoPtr->currentPoolRate += curPtr->currentRate; Ns_Log(DriverDebug, "poollimit pool '%s' added rate poolLimit %d poolRate %d", curPtr->poolPtr->pool, curPtr->poolPtr->rate.poolLimit, infoPtr->currentPoolRate); } } /* * Now iterate over the pools used by this thread and sum the specific * pool rates from all writer threads. */ hPtr = Tcl_FirstHashEntry(pools, &search); while (hPtr != NULL) { ConnPool *poolPtr = (ConnPool *)Tcl_GetHashKey(pools, hPtr); int totalPoolRate, writerThreadCount, threadDeltaRate; ConnPoolInfo *infoPtr; /* * Compute the following indicators: * - totalPoolRate: accumulated pool rates from all writer threads. * * - threadDeltaRate: how much of the available bandwidth can i used * the current thread. We assume that the distribution of writers * between all writer threads is even, so we can split the * available rate by the number of writer threads working on this * pool. * * - deltaPercentage: adjust in a single iteration just a fraction * (e.g. 10 percent) of the potential change. This function is * called often enough to justify delayed adjustments. */ infoPtr = (ConnPoolInfo *)Tcl_GetHashValue(hPtr); totalPoolRate = NsPoolTotalRate(poolPtr, infoPtr->threadSlot, infoPtr->currentPoolRate, &writerThreadCount); /* * If nothing is going on, allow a thread the full rate. */ if (infoPtr->currentPoolRate == 0) { threadDeltaRate = (poolPtr->rate.poolLimit - totalPoolRate); } else { threadDeltaRate = (poolPtr->rate.poolLimit - totalPoolRate) / writerThreadCount; } infoPtr->deltaPercentage = threadDeltaRate / 10; if (infoPtr->deltaPercentage < -50) { infoPtr->deltaPercentage = -50; } if (totalPoolRate > 0) { Ns_Log(Notice, "... pool '%s' thread's pool rate %d total pool rate %d limit %d " "(#%d writer threads) -> computed rate %d (%d%%) ", NsPoolName(poolPtr->pool), infoPtr->currentPoolRate, totalPoolRate, poolPtr->rate.poolLimit, writerThreadCount, threadDeltaRate, infoPtr->deltaPercentage ); } hPtr = Tcl_NextHashEntry(&search); } } /* *---------------------------------------------------------------------- * * WriterThread -- * * Thread that writes files to clients. * * Results: * None. * * Side effects: * Connections are accepted and their SockPtr is set to NULL * such that closing actual connection does not close the socket. * *---------------------------------------------------------------------- */ static void WriterThread(void *arg) { SpoolerQueue *queuePtr = (SpoolerQueue*)arg; int err, pollTimeout; bool stopping; Ns_Time now; Sock *sockPtr; const Driver *drvPtr; WriterSock *curPtr, *nextPtr, *writePtr; PollData pdata; Tcl_HashTable pools; /* used for accumulating bandwidth per pool */ Ns_ThreadSetName("-writer%d-", queuePtr->id); queuePtr->threadName = Ns_ThreadGetName(); Tcl_InitHashTable(&pools, TCL_ONE_WORD_KEYS); /* * Loop forever until signaled to shut down and all * connections are complete and gracefully closed. */ Ns_Log(Notice, "writer%d: accepting connections", queuePtr->id); PollCreate(&pdata); writePtr = NULL; stopping = NS_FALSE; while (!stopping) { char charBuffer[1]; /* * If there are any write sockets, set the bits. */ PollReset(&pdata); (void)PollSet(&pdata, queuePtr->pipe[0], (short)POLLIN, NULL); if (writePtr == NULL) { pollTimeout = 30 * 1000; } else { /* * If per-pool bandwidth management is requested, compute the base * data for the adjustment. If there is no bandwidth management * requested, there is no slowdow. */ if (NsWriterBandwidthManagement) { WriterPerPoolRates(writePtr, &pools); } /* * There are writers active. Determine on which writers we poll * and compute the maximal poll wait time. */ pollTimeout = 1000; for (curPtr = writePtr; curPtr != NULL; curPtr = curPtr->nextPtr) { int sleepTimeMs = 0; Ns_Log(DriverDebug, "### Writer poll collect %p size %" PRIdz " streaming %d rateLimit %d", (void *)curPtr, curPtr->size, curPtr->doStream, curPtr->rateLimit); if (curPtr->rateLimit > 0 && curPtr->nsent > 0 && curPtr->currentRate > 0 ) { int currentMs, targetTimeMs; /* * Perform per-pool rate management, when * - a poolLimit is provided, * - we have performance data of thee pool, and * - changes are possible (as flagged by deltaPercentage). */ if (NsWriterBandwidthManagement && curPtr->poolPtr->rate.poolLimit > 0 && curPtr->infoPtr != NULL && curPtr->infoPtr->deltaPercentage != 0 ) { /* * Only adjust data for busy writer jobs, which * are close to their limits. */ bool onLimit = (curPtr->currentRate*100 / curPtr->rateLimit) > 90; Ns_Log(DriverDebug, "we allowed %d we use %d on limit %d (%d) , we can do %d%%", curPtr->rateLimit, curPtr->currentRate, (int)onLimit, curPtr->currentRate*100/curPtr->rateLimit, curPtr->infoPtr->deltaPercentage); if (onLimit) { /* * Compute new rate limit based on * positive/negative delta percentage. */ int newRate = curPtr->currentRate + (curPtr->currentRate * curPtr->infoPtr->deltaPercentage / 100); /* * Sanity checks: * - never allow more than poolLimit * - never kill connections completely (e.g. minRate 5KB/s) */ if (newRate > curPtr->poolPtr->rate.poolLimit) { newRate = curPtr->poolPtr->rate.poolLimit; } else if (newRate < 5) { newRate = 5; } Ns_Log(Notice, "... pool '%s' new rate limit changed from %d to %d KB/s (delta %d%%)", curPtr->poolPtr->pool, curPtr->rateLimit, newRate, curPtr->infoPtr->deltaPercentage); curPtr->rateLimit = newRate; } } /* * Adjust rate to the rate limit. */ currentMs = (int)(curPtr->nsent/(Tcl_WideInt)curPtr->currentRate); targetTimeMs = (int)(curPtr->nsent/(Tcl_WideInt)curPtr->rateLimit); sleepTimeMs = 1 + targetTimeMs - currentMs; Ns_Log(WriterDebug, "### Writer(%d)" " byte sent %" TCL_LL_MODIFIER "d msecs %d rate %d KB/s" " targetRate %d KB/s sleep %d", curPtr->sockPtr->sock, curPtr->nsent, currentMs, curPtr->currentRate, curPtr->rateLimit, sleepTimeMs); } if (likely(curPtr->size > 0u)) { if (sleepTimeMs <= 0) { SockPoll(curPtr->sockPtr, (short)POLLOUT, &pdata); pollTimeout = -1; } else { pollTimeout = MIN(sleepTimeMs, pollTimeout); } } else if (unlikely(curPtr->doStream == NS_WRITER_STREAM_FINISH)) { pollTimeout = -1; } } } Ns_Log(DriverDebug, "### Writer final pollTimeout %d", pollTimeout); /* * Select and drain the trigger pipe if necessary. */ (void) PollWait(&pdata, pollTimeout); if (PollIn(&pdata, 0) && unlikely(ns_recv(queuePtr->pipe[0], charBuffer, 1u, 0) != 1)) { Ns_Fatal("writer: trigger ns_recv() failed: %s", ns_sockstrerror(ns_sockerrno)); } /* * Write to all available sockets */ Ns_GetTime(&now); curPtr = writePtr; writePtr = NULL; while (curPtr != NULL) { NsWriterStreamState doStream; SpoolerState spoolerState = SPOOLER_OK; nextPtr = curPtr->nextPtr; sockPtr = curPtr->sockPtr; err = 0; /* * The truth value of doStream does not change through * concurrency. */ doStream = curPtr->doStream; if (unlikely(PollHup(&pdata, sockPtr->pidx))) { Ns_Log(DriverDebug, "### Writer %p reached POLLHUP fd %d", (void *)curPtr, sockPtr->sock); spoolerState = SPOOLER_CLOSE; err = 0; curPtr->infoPtr = WriterGetInfoPtr(curPtr, &pools); curPtr->infoPtr->currentPoolRate += curPtr->currentRate; } else if (likely(PollOut(&pdata, sockPtr->pidx)) || (doStream == NS_WRITER_STREAM_FINISH)) { /* * The socket is writable, we can compute the rate, when * something was sent already and some kind of rate limiting * is in place ... and we have sent enough data to make a good * estimate (just after the 2nd send, so more than driver * buffer size. */ Ns_Log(DriverDebug, "Socket of pool '%s' is writable, writer limit %d nsent %ld", curPtr->poolPtr->pool, curPtr->rateLimit, (long)curPtr->nsent); if (curPtr->rateLimit > 0 && (size_t)curPtr->nsent > curPtr->sockPtr->drvPtr->bufsize ) { Ns_Time diff; long currentMs; Ns_DiffTime(&now, &curPtr->startTime, &diff); currentMs = Ns_TimeToMilliseconds(&diff); if (currentMs > 0) { curPtr->currentRate = (int)((curPtr->nsent)/(Tcl_WideInt)currentMs); Ns_Log(DriverDebug, "Socket of pool '%s' is writable, currentMs %ld has updated current rate %d", curPtr->poolPtr->pool, currentMs,curPtr->currentRate); } } Ns_Log(DriverDebug, "### Writer %p can write to client fd %d (trigger %d) streaming %.6x" " size %" PRIdz " nsent %" TCL_LL_MODIFIER "d bufsize %" PRIdz, (void *)curPtr, sockPtr->sock, PollIn(&pdata, 0), doStream, curPtr->size, curPtr->nsent, curPtr->c.file.bufsize); if (unlikely(curPtr->size < 1u)) { /* * Size < 1 means that everything was sent. */ if (doStream != NS_WRITER_STREAM_ACTIVE) { if (doStream == NS_WRITER_STREAM_FINISH) { Ns_ReleaseTemp(curPtr->fd); } spoolerState = SPOOLER_CLOSE; } } else { /* * If size > 0, there is still something to send. * If we are spooling from a file, read some data * from the (spool) file and place it into curPtr->c.file.buf. */ if (curPtr->fd != NS_INVALID_FD) { spoolerState = WriterReadFromSpool(curPtr); } if (spoolerState == SPOOLER_OK) { spoolerState = WriterSend(curPtr, &err); } } } else { /* * Mark when first timeout occurred or check if it is already * for too long and we need to stop this socket */ if (sockPtr->timeout.sec == 0) { Ns_Log(DriverDebug, "Writer %p fd %d setting sendwait %ld.%6ld", (void *)curPtr, sockPtr->sock, curPtr->sockPtr->drvPtr->sendwait.sec, curPtr->sockPtr->drvPtr->sendwait.usec); SockTimeout(sockPtr, &now, &curPtr->sockPtr->drvPtr->sendwait); } else if (Ns_DiffTime(&sockPtr->timeout, &now, NULL) <= 0) { Ns_Log(DriverDebug, "Writer %p fd %d timeout", (void *)curPtr, sockPtr->sock); err = ETIMEDOUT; spoolerState = SPOOLER_CLOSETIMEOUT; } } /* * Check result status and close the socket in case of * timeout or completion */ Ns_MutexLock(&queuePtr->lock); if (spoolerState == SPOOLER_OK) { if (curPtr->size > 0u || doStream == NS_WRITER_STREAM_ACTIVE) { Ns_Log(DriverDebug, "Writer %p continue OK (size %" PRIdz ") => PUSH", (void *)curPtr, curPtr->size); Push(curPtr, writePtr); } else { Ns_Log(DriverDebug, "Writer %p done OK (size %" PRIdz ") => RELEASE", (void *)curPtr, curPtr->size); WriterSockRelease(curPtr); } } else { /* * spoolerState might be SPOOLER_CLOSE or SPOOLER_*TIMEOUT, or SPOOLER_*ERROR */ Ns_Log(DriverDebug, "Writer %p fd %d release, not OK (status %d) => RELEASE", (void *)curPtr, curPtr->sockPtr->sock, (int)spoolerState); curPtr->status = spoolerState; curPtr->err = err; WriterSockRelease(curPtr); } Ns_MutexUnlock(&queuePtr->lock); curPtr = nextPtr; } /* * Add more sockets to the writer queue */ if (queuePtr->sockPtr != NULL) { Ns_MutexLock(&queuePtr->lock); if (queuePtr->sockPtr != NULL) { curPtr = queuePtr->sockPtr; queuePtr->sockPtr = NULL; while (curPtr != NULL) { nextPtr = curPtr->nextPtr; sockPtr = curPtr->sockPtr; drvPtr = sockPtr->drvPtr; SockTimeout(sockPtr, &now, &drvPtr->sendwait); Push(curPtr, writePtr); queuePtr->queuesize++; curPtr = nextPtr; } queuePtr->curPtr = writePtr; } Ns_MutexUnlock(&queuePtr->lock); } /* * Check for shutdown */ stopping = queuePtr->shutdown; } PollFree(&pdata); { /* * Free ConnPoolInfo */ Tcl_HashSearch search; Tcl_HashEntry *hPtr = Tcl_FirstHashEntry(&pools, &search); while (hPtr != NULL) { ConnPoolInfo *infoPtr = (ConnPoolInfo *)Tcl_GetHashValue(hPtr); ns_free(infoPtr); hPtr = Tcl_NextHashEntry(&search); } /* * Delete the hash table for pools. */ Tcl_DeleteHashTable(&pools); } Ns_Log(Notice, "exiting"); Ns_MutexLock(&queuePtr->lock); queuePtr->stopped = NS_TRUE; Ns_CondBroadcast(&queuePtr->cond); Ns_MutexUnlock(&queuePtr->lock); } /* *---------------------------------------------------------------------- * * NsWriterFinish -- * * Finish a streaming writer job (typically called at the close * of a connection). A streaming writer job is fed typically by a * sequence of ns_write operations. After such an operation, the * WriterThread has to keep the writer job alive. * NsWriterFinish() tells the WriterThread that no more * other writer jobs will come from this connection. * * Results: * None. * * Side effects: * Change the state of the writer job and trigger the queue. * *---------------------------------------------------------------------- */ void NsWriterFinish(NsWriterSock *wrSockPtr) { WriterSock *writerSockPtr = (WriterSock *)wrSockPtr; NS_NONNULL_ASSERT(wrSockPtr != NULL); Ns_Log(DriverDebug, "NsWriterFinish: %p", (void *)writerSockPtr); writerSockPtr->doStream = NS_WRITER_STREAM_FINISH; SockTrigger(writerSockPtr->queuePtr->pipe[1]); } /* *---------------------------------------------------------------------- * * WriterSetupStreamingMode -- * * In streaming mode, setup a temporary fd which is used as input and * output. Streaming i/o will append to the file, while the write will * read from it. * * Results: * Ns_ReturnCode (NS_OK, NS_ERROR, NS_FILTER_BREAK). In the last case * signals that all processing was already performed and the caller can * stop handling more data. On success, the function returns an fd as * last argument. * * Side effects: * Potentially allocating temp file and updating connPtr members. * *---------------------------------------------------------------------- */ Ns_ReturnCode WriterSetupStreamingMode(Conn *connPtr, struct iovec *bufs, int nbufs, int *fdPtr) { bool first; size_t wrote = 0u; WriterSock *wrSockPtr1; Ns_ReturnCode status = NS_OK; NS_NONNULL_ASSERT(connPtr != NULL); NS_NONNULL_ASSERT(bufs != NULL); NS_NONNULL_ASSERT(fdPtr != NULL); Ns_Log(DriverDebug, "NsWriterQueue: streaming writer job"); if (connPtr->fd == 0) { /* * Create a new temporary spool file and provide the fd to the * connection thread via connPtr. */ first = NS_TRUE; wrSockPtr1 = NULL; *fdPtr = Ns_GetTemp(); connPtr->fd = *fdPtr; Ns_Log(DriverDebug, "NsWriterQueue: new tmp file has fd %d", *fdPtr); } else { /* * Reuse previously created spool file. */ first = NS_FALSE; wrSockPtr1 = WriterSockRequire(connPtr); if (wrSockPtr1 == NULL) { Ns_Log(Notice, "NsWriterQueue: writer job was already canceled (fd %d); maybe user dropped connection", connPtr->fd); return NS_ERROR; } else { /* * lock only, when first == NS_FALSE. */ Ns_MutexLock(&wrSockPtr1->c.file.fdlock); (void)ns_lseek(connPtr->fd, 0, SEEK_END); } } /* * For the time being, handle just "string data" in streaming * output (iovec bufs). Write the content to the spool file. */ { int i; for (i = 0; i < nbufs; i++) { ssize_t j = ns_write(connPtr->fd, bufs[i].iov_base, bufs[i].iov_len); if (j > 0) { wrote += (size_t)j; Ns_Log(Debug, "NsWriterQueue: fd %d [%d] spooled %" PRIdz " of %" PRIiovlen " OK %d", connPtr->fd, i, j, bufs[i].iov_len, (j == (ssize_t)bufs[i].iov_len)); } else { Ns_Log(Warning, "NsWriterQueue: spool to fd %d write operation failed", connPtr->fd); } } } if (first) { //bufs = NULL; connPtr->nContentSent = wrote; #ifndef _WIN32 /* * sock_set_blocking can't be used under windows, since sockets * are under windows no file descriptors. */ (void)ns_sock_set_blocking(connPtr->fd, NS_FALSE); #endif /* * Fall through to register stream writer with temp file */ } else { WriterSock *writerSockPtr; /* * This is a later streaming operation, where the writer job * (strWriter) was previously established. */ assert(wrSockPtr1 != NULL); /* * Update the controlling variables (size and toread) in the connPtr, * and the length info for the access log, and trigger the writer to * notify it about the change. */ writerSockPtr = (WriterSock *)connPtr->strWriter; writerSockPtr->size += wrote; writerSockPtr->c.file.toRead += wrote; Ns_MutexUnlock(&wrSockPtr1->c.file.fdlock); connPtr->nContentSent += wrote; if (likely(wrSockPtr1->queuePtr != NULL)) { SockTrigger(wrSockPtr1->queuePtr->pipe[1]); } WriterSockRelease(wrSockPtr1); status = NS_FILTER_BREAK; } return status; } /* *---------------------------------------------------------------------- * * NsWriterQueue -- * * Submit a new job to the writer queue. * * Results: * * NS_ERROR means that the Writer thread refuses to accept this * job and that the client (the connection thread) has to handle * this data. NS_OK means that the Writer thread cares for * transmitting the content to the client. * * Side effects: * Potentially adding a job to the writer queue. * *---------------------------------------------------------------------- */ Ns_ReturnCode NsWriterQueue(Ns_Conn *conn, size_t nsend, Tcl_Channel chan, FILE *fp, int fd, struct iovec *bufs, int nbufs, const Ns_FileVec *filebufs, int nfilebufs, bool everysize) { Conn *connPtr; WriterSock *wrSockPtr; SpoolerQueue *queuePtr; DrvWriter *wrPtr; bool trigger = NS_FALSE; size_t headerSize; Ns_ReturnCode status = NS_OK; Ns_FileVec *fbufs = NULL; int nfbufs = 0; NS_NONNULL_ASSERT(conn != NULL); connPtr = (Conn *)conn; if (unlikely(connPtr->sockPtr == NULL)) { Ns_Log(Warning, "NsWriterQueue: called without sockPtr size %" PRIdz " bufs %d flags %.6x stream %.6x chan %p fd %d", nsend, nbufs, connPtr->flags, connPtr->flags & NS_CONN_STREAM, (void *)chan, fd); status = NS_ERROR; wrPtr = NULL; } else { wrPtr = &connPtr->sockPtr->drvPtr->writer; Ns_Log(DriverDebug, "NsWriterQueue: size %" PRIdz " bufs %p (%d) flags %.6x stream %.6x chan %p fd %d thread %d", nsend, (void *)bufs, nbufs, connPtr->flags, connPtr->flags & NS_CONN_STREAM, (void *)chan, fd, wrPtr->threads); if (unlikely(wrPtr->threads == 0)) { Ns_Log(DriverDebug, "NsWriterQueue: no writer threads configured"); status = NS_ERROR; } else if (nsend < (size_t)wrPtr->writersize && !everysize && connPtr->fd == 0) { Ns_Log(DriverDebug, "NsWriterQueue: file is too small(%" PRIdz " < %" PRIdz ")", nsend, wrPtr->writersize); status = NS_ERROR; } } if (status != NS_OK) { return status; } assert(wrPtr != NULL); /* * In streaming mode, setup a temporary fd which is used as input and * output. Streaming i/o will append to the file, while the write will * read from it. */ if (((connPtr->flags & NS_CONN_STREAM) != 0u) || connPtr->fd > 0) { if (wrPtr->doStream == NS_WRITER_STREAM_NONE) { status = NS_ERROR; } else if (unlikely(fp != NULL || fd != NS_INVALID_FD)) { Ns_Log(DriverDebug, "NsWriterQueue: does not stream from this source via writer"); status = NS_ERROR; } else { status = WriterSetupStreamingMode(connPtr, bufs, nbufs, &fd); } if (unlikely(status != NS_OK)) { if (status == NS_FILTER_BREAK) { status = NS_OK; } return status; } /* * As a result of successful WriterSetupStreamingMode(), we have fd * set. */ assert(fd != NS_INVALID_FD); } else { if (fp != NULL) { /* * The client provided an open file pointer and closes it */ fd = ns_dup(fileno(fp)); } else if (fd != NS_INVALID_FD) { /* * The client provided an open file descriptor and closes it */ fd = ns_dup(fd); } else if (chan != NULL) { ClientData clientData; /* * The client provided an open Tcl channel and closes it */ if (Tcl_GetChannelHandle(chan, TCL_READABLE, &clientData) != TCL_OK) { return NS_ERROR; } fd = ns_dup(PTR2INT(clientData)); } else if (filebufs != NULL && nfilebufs > 0) { /* * The client provided Ns_FileVec with open files. The client is * responsible for closing it, like in all other cases. */ size_t i; /* * This is the only case, where fbufs will be != NULL, * i.e. keeping a duplicate of the passed-in Ns_FileVec structure * for which the client is responsible. */ fbufs = (Ns_FileVec *)ns_calloc((size_t)nfilebufs, sizeof(Ns_FileVec)); nfbufs = nfilebufs; for (i = 0u; i < (size_t)nfilebufs; i++) { fbufs[i].fd = ns_dup(filebufs[i].fd); fbufs[i].length = filebufs[i].length; fbufs[i].offset = filebufs[i].offset; } /* * Place the fd of the first Ns_FileVec to fd. */ fd = fbufs[0].fd; Ns_Log(DriverDebug, "NsWriterQueue: filevec mode, take first fd %d tosend %lu", fd, nsend); } } Ns_Log(DriverDebug, "NsWriterQueue: writer threads %d nsend %" PRIdz " writersize %" PRIdz, wrPtr->threads, nsend, wrPtr->writersize); assert(connPtr->poolPtr != NULL); connPtr->poolPtr->stats.spool++; wrSockPtr = (WriterSock *)ns_calloc(1u, sizeof(WriterSock)); wrSockPtr->sockPtr = connPtr->sockPtr; wrSockPtr->poolPtr = connPtr->poolPtr; /* just for being able to trace back the origin, e.g. list */ wrSockPtr->sockPtr->timeout.sec = 0; wrSockPtr->flags = connPtr->flags; wrSockPtr->refCount = 1; /* * Take the rate limit from the connection. */ wrSockPtr->rateLimit = connPtr->rateLimit; if (wrSockPtr->rateLimit == -1) { /* * The value was not specified via connection. Use either the pool * limit as a base for the computation or fall back to the driver * default value. */ if (connPtr->poolPtr->rate.poolLimit > 0) { /* * Very optimistic start value, but values will float through via * bandwidth management. */ wrSockPtr->rateLimit = connPtr->poolPtr->rate.poolLimit / 2; } else { wrSockPtr->rateLimit = wrPtr->rateLimit; } } Ns_Log(WriterDebug, "### Writer(%d): initial rate limit %d KB/s", wrSockPtr->sockPtr->sock, wrSockPtr->rateLimit); /* * Make sure we have proper content length header for * keep-alive/pipelining. */ Ns_ConnSetLengthHeader(conn, nsend, (wrSockPtr->flags & NS_CONN_STREAM) != 0u); /* * Flush the headers */ if ((conn->flags & NS_CONN_SENTHDRS) == 0u) { Tcl_DString ds; Ns_DStringInit(&ds); Ns_Log(DriverDebug, "### Writer(%d): add header", fd); conn->flags |= NS_CONN_SENTHDRS; (void)Ns_CompleteHeaders(conn, nsend, 0u, &ds); headerSize = (size_t)Ns_DStringLength(&ds); if (headerSize > 0u) { wrSockPtr->headerString = ns_strdup(Tcl_DStringValue(&ds)); } Ns_DStringFree(&ds); } else { headerSize = 0u; } if (fd != NS_INVALID_FD) { /* maybe add mmap support for files (fd != NS_INVALID_FD) */ wrSockPtr->fd = fd; wrSockPtr->c.file.bufs = fbufs; wrSockPtr->c.file.nbufs = nfbufs; Ns_Log(DriverDebug, "### Writer(%d) tosend %" PRIdz " files %d bufsize %" PRIdz, fd, nsend, nfbufs, wrPtr->bufsize); if (unlikely(headerSize >= wrPtr->bufsize)) { /* * We have a header which is larger than bufsize; place it * as "leftover" and use the headerString as buffer for file * reads (rather rare case) */ wrSockPtr->c.file.buf = (unsigned char *)wrSockPtr->headerString; wrSockPtr->c.file.maxsize = headerSize; wrSockPtr->c.file.bufsize = headerSize; wrSockPtr->headerString = NULL; } else if (headerSize > 0u) { /* * We have a header that fits into the bufsize; place it * as "leftover" at the end of the buffer. */ wrSockPtr->c.file.buf = ns_malloc(wrPtr->bufsize); memcpy(wrSockPtr->c.file.buf, wrSockPtr->headerString, headerSize); wrSockPtr->c.file.bufsize = headerSize; wrSockPtr->c.file.maxsize = wrPtr->bufsize; ns_free(wrSockPtr->headerString); wrSockPtr->headerString = NULL; } else { assert(wrSockPtr->headerString == NULL); wrSockPtr->c.file.buf = ns_malloc(wrPtr->bufsize); wrSockPtr->c.file.maxsize = wrPtr->bufsize; } wrSockPtr->c.file.bufoffset = 0; wrSockPtr->c.file.toRead = nsend; } else if (bufs != NULL) { int i, j, headerbufs = (headerSize > 0u ? 1 : 0); wrSockPtr->fd = NS_INVALID_FD; if (nbufs+headerbufs < UIO_SMALLIOV) { wrSockPtr->c.mem.bufs = wrSockPtr->c.mem.preallocated_bufs; } else { Ns_Log(DriverDebug, "NsWriterQueue: alloc %d iovecs", nbufs); wrSockPtr->c.mem.bufs = ns_calloc((size_t)nbufs + (size_t)headerbufs, sizeof(struct iovec)); } wrSockPtr->c.mem.nbufs = nbufs+headerbufs; if (headerbufs != 0) { wrSockPtr->c.mem.bufs[0].iov_base = wrSockPtr->headerString; wrSockPtr->c.mem.bufs[0].iov_len = headerSize; } if (connPtr->fmap.addr != NULL) { Ns_Log(DriverDebug, "NsWriterQueue: deliver fmapped %p", (void *)connPtr->fmap.addr); /* * Deliver an mmapped file, no need to copy content */ for (i = 0, j=headerbufs; i < nbufs; i++, j++) { wrSockPtr->c.mem.bufs[j].iov_base = bufs[i].iov_base; wrSockPtr->c.mem.bufs[j].iov_len = bufs[i].iov_len; } /* * Make a copy of the fmap structure and make clear that * we unmap in the writer thread. */ wrSockPtr->c.mem.fmap = connPtr->fmap; connPtr->fmap.addr = NULL; /* header string will be freed via wrSockPtr->headerString */ } else { /* * Deliver a content from iovec. The lifetime of the * source is unknown, we have to copy the c. */ for (i = 0, j=headerbufs; i < nbufs; i++, j++) { wrSockPtr->c.mem.bufs[j].iov_base = ns_malloc(bufs[i].iov_len); wrSockPtr->c.mem.bufs[j].iov_len = bufs[i].iov_len; memcpy(wrSockPtr->c.mem.bufs[j].iov_base, bufs[i].iov_base, bufs[i].iov_len); } /* header string will be freed a buf[0] */ wrSockPtr->headerString = NULL; } } else { ns_free(wrSockPtr); return NS_ERROR; } /* * Add header size to total size. */ nsend += headerSize; if (connPtr->clientData != NULL) { wrSockPtr->clientData = ns_strdup(connPtr->clientData); } wrSockPtr->startTime = *Ns_ConnStartTime(conn); /* * Setup streaming context before sending potentially headers. */ if ((wrSockPtr->flags & NS_CONN_STREAM) != 0u) { wrSockPtr->doStream = NS_WRITER_STREAM_ACTIVE; assert(connPtr->strWriter == NULL); /* * Add a reference to the stream writer to the connection such * it can efficiently append to a stream when multiple output * operations happen. The backpointer (from the stream writer * to the connection is needed to clear the reference to the * writer in case the writer is deleted. No locks are needed, * since nobody can share this structure yet. */ connPtr->strWriter = (NsWriterSock *)wrSockPtr; wrSockPtr->connPtr = connPtr; } /* * Tell connection, that writer handles the output (including * closing the connection to the client). */ connPtr->flags |= NS_CONN_SENT_VIA_WRITER; wrSockPtr->keep = connPtr->keep > 0 ? NS_TRUE : NS_FALSE; wrSockPtr->size = nsend; Ns_Log(DriverDebug, "NsWriterQueue NS_CONN_SENT_VIA_WRITER connPtr %p", (void*)connPtr); if ((wrSockPtr->flags & NS_CONN_STREAM) == 0u) { Ns_Log(DriverDebug, "NsWriterQueue NS_CONN_SENT_VIA_WRITER connPtr %p clear sockPtr %p", (void*)connPtr, (void*)connPtr->sockPtr); connPtr->sockPtr = NULL; connPtr->flags |= NS_CONN_CLOSED; connPtr->nContentSent = nsend - headerSize; } /* * Get the next writer thread from the list, all writer requests are * rotated between all writer threads */ Ns_MutexLock(&wrPtr->lock); if (wrPtr->curPtr == NULL) { wrPtr->curPtr = wrPtr->firstPtr; } queuePtr = wrPtr->curPtr; wrPtr->curPtr = wrPtr->curPtr->nextPtr; Ns_MutexUnlock(&wrPtr->lock); Ns_Log(WriterDebug, "Writer(%d): started: id=%d fd=%d, " "size=%" PRIdz ", flags=%X, rate %d KB/s: %s", wrSockPtr->sockPtr->sock, queuePtr->id, wrSockPtr->fd, nsend, wrSockPtr->flags, wrSockPtr->rateLimit, connPtr->request.line); /* * Now add new writer socket to the writer thread's queue */ wrSockPtr->queuePtr = queuePtr; Ns_MutexLock(&queuePtr->lock); if (queuePtr->sockPtr == NULL) { trigger = NS_TRUE; } Push(wrSockPtr, queuePtr->sockPtr); Ns_MutexUnlock(&queuePtr->lock); /* * Wake up writer thread */ if (trigger) { SockTrigger(queuePtr->pipe[1]); } return NS_OK; } /* *---------------------------------------------------------------------- * * DriverWriterFromObj -- * * Lookup driver by name and return its DrvWriter. When driverObj is * NULL, get the driver from the conn. * * Results: * Ns_ReturnCode * * Side effects: * Set error message in interp in case of failure. * *---------------------------------------------------------------------- */ static Ns_ReturnCode DriverWriterFromObj( Tcl_Interp *interp, Tcl_Obj *driverObj, Ns_Conn *conn, DrvWriter **wrPtrPtr) { Driver *drvPtr; const char *driverName = NULL; int driverNameLen = 0; DrvWriter *wrPtr = NULL; Ns_ReturnCode result; /* * If no driver is provided, take the current driver. The caller has * to make sure that in cases, where no driver is specified, the * command is run in a connection thread. */ if (driverObj == NULL) { if (conn != NULL) { driverName = Ns_ConnDriverName(conn); driverNameLen = (int)strlen(driverName); } } else { driverName = Tcl_GetStringFromObj(driverObj, &driverNameLen); } if (driverName != NULL) { for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) { if (strncmp(driverName, drvPtr->threadName, (size_t)driverNameLen) == 0) { if (drvPtr->writer.firstPtr != NULL) { wrPtr = &drvPtr->writer; } break; } } } if (unlikely(wrPtr == NULL)) { Ns_TclPrintfResult(interp, "no writer configured for a driver with name %s", driverName); result = NS_ERROR; } else { *wrPtrPtr = wrPtr; result = NS_OK; } return result; } /* *---------------------------------------------------------------------- * * WriterSubmitObjCmd - subcommand of NsTclWriterObjCmd -- * * Implements "ns_writer submit" command. * Send the provided data to the client. * * Results: * Standard Tcl result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int WriterSubmitObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { int result = TCL_OK; Ns_Conn *conn; Tcl_Obj *dataObj; Ns_ObjvSpec args[] = { {"data", Ns_ObjvObj, &dataObj, NULL}, {NULL, NULL, NULL, NULL} }; if (Ns_ParseObjv(NULL, args, interp, 2, objc, objv) != NS_OK || NsConnRequire(interp, NS_CONN_REQUIRE_ALL, &conn) != NS_OK) { result = TCL_ERROR; } else { int size; unsigned char *data = Tcl_GetByteArrayFromObj(dataObj, &size); if (data != NULL) { struct iovec vbuf; Ns_ReturnCode status; vbuf.iov_base = (void *)data; vbuf.iov_len = (size_t)size; status = NsWriterQueue(conn, (size_t)size, NULL, NULL, NS_INVALID_FD, &vbuf, 1, NULL, 0, NS_TRUE); Tcl_SetObjResult(interp, Tcl_NewBooleanObj(status == NS_OK ? 1 : 0)); } } return result; } /* *---------------------------------------------------------------------- * * WriterCheckInputParams - * * Helper command for WriterSubmitFileObjCmd and WriterSubmitFilesObjCmd * to check validity of filename, offset and size. * * Results: * Standard Tcl result. Returns on success also fd and nrbytes. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int WriterCheckInputParams(Tcl_Interp *interp, const char *filenameString, size_t size, off_t offset, int *fdPtr, size_t *nrbytesPtr) { int result = TCL_OK, rc; struct stat st; Ns_Log(DriverDebug, "WriterCheckInputParams %s offset %" PROTd " size %" PRIdz, filenameString, offset, size); /* * Use stat() call to obtain information about the actual file to check * later the plausibility of the parameters. */ rc = stat(filenameString, &st); if (unlikely(rc != 0)) { Ns_TclPrintfResult(interp, "file does not exist '%s'", filenameString); result = TCL_ERROR; } else { size_t nrbytes = 0u; int fd; /* * Try to open the file and check offset and size parameters. */ fd = ns_open(filenameString, O_RDONLY | O_CLOEXEC, 0); if (unlikely(fd == NS_INVALID_FD)) { Ns_TclPrintfResult(interp, "could not open file '%s'", filenameString); result = TCL_ERROR; } else if (unlikely(offset > st.st_size) || offset < 0) { Ns_TclPrintfResult(interp, "offset must be a positive value less or equal filesize"); result = TCL_ERROR; } else if (size > 0) { if (unlikely((off_t)size + offset > st.st_size)) { Ns_TclPrintfResult(interp, "offset + size must be less or equal filesize"); result = TCL_ERROR; } else { nrbytes = (size_t)size; } } else { nrbytes = (size_t)st.st_size - (size_t)offset; } /* * When an offset is provide, jump to this offset. */ if (offset > 0 && result == TCL_OK) { if (ns_lseek(fd, (off_t)offset, SEEK_SET) == -1) { Ns_TclPrintfResult(interp, "cannot seek to position %ld", (long)offset); result = TCL_ERROR; } } if (result == TCL_OK) { *fdPtr = fd; *nrbytesPtr = nrbytes; } else if (fd != NS_INVALID_FD) { /* * On invalid parameters, close the fd. */ ns_close(fd); } } return result; } /* *---------------------------------------------------------------------- * * WriterSubmitFileObjCmd - subcommand of NsTclWriterObjCmd -- * * Implements "ns_writer submitfile" command. * Send the provided file to the client. * * Results: * Standard Tcl result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int WriterSubmitFileObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { int result = TCL_OK; Ns_Conn *conn; char *fileNameString; int headers = 0; Tcl_WideInt offset = 0, size = 0; Ns_ObjvValueRange offsetRange = {0, LLONG_MAX}; Ns_ObjvValueRange sizeRange = {1, LLONG_MAX}; Ns_ObjvSpec lopts[] = { {"-headers", Ns_ObjvBool, &headers, INT2PTR(NS_TRUE)}, {"-offset", Ns_ObjvMemUnit, &offset, &offsetRange}, {"-size", Ns_ObjvMemUnit, &size, &sizeRange}, {NULL, NULL, NULL, NULL} }; Ns_ObjvSpec args[] = { {"file", Ns_ObjvString, &fileNameString, NULL}, {NULL, NULL, NULL, NULL} }; if (unlikely(Ns_ParseObjv(lopts, args, interp, 2, objc, objv) != NS_OK) || NsConnRequire(interp, NS_CONN_REQUIRE_ALL, &conn) != NS_OK) { result = TCL_ERROR; } else if (unlikely( Ns_ConnSockPtr(conn) == NULL )) { Ns_Log(Warning, "NsWriterQueue: called without valid sockPtr, maybe connection already closed"); Ns_TclPrintfResult(interp, "0"); result = TCL_OK; } else { size_t nrbytes = 0u; int fd = NS_INVALID_FD; result = WriterCheckInputParams(interp, fileNameString, (size_t)size, offset, &fd, &nrbytes); if (likely(result == TCL_OK)) { Ns_ReturnCode status; /* * The caller requested that we build required headers */ if (headers != 0) { Ns_ConnSetTypeHeader(conn, Ns_GetMimeType(fileNameString)); } status = NsWriterQueue(conn, nrbytes, NULL, NULL, fd, NULL, 0, NULL, 0, NS_TRUE); Tcl_SetObjResult(interp, Tcl_NewBooleanObj(status == NS_OK ? 1 : 0)); if (fd != NS_INVALID_FD) { (void) ns_close(fd); } else { Ns_Log(Warning, "WriterSubmitFileObjCmd called with invalid fd"); } } else if (fd != NS_INVALID_FD) { (void) ns_close(fd); } } return result; } /* *---------------------------------------------------------------------- * * WriterGetMemunitFromDict -- * * Helper function to obtain a memory unit from a dict structure, * optionally checking the value range. * * Results: * Standard Tcl result. * * Side effects: * On errors, an error message is left in the interpreter. * *---------------------------------------------------------------------- */ static int WriterGetMemunitFromDict(Tcl_Interp *interp, Tcl_Obj *dictObj, Tcl_Obj *keyObj, Ns_ObjvValueRange *rangePtr, Tcl_WideInt *valuePtr) { Tcl_Obj *intObj = NULL; int result; NS_NONNULL_ASSERT(interp != NULL); NS_NONNULL_ASSERT(dictObj != NULL); NS_NONNULL_ASSERT(keyObj != NULL); NS_NONNULL_ASSERT(valuePtr != NULL); result = Tcl_DictObjGet(interp, dictObj, keyObj, &intObj); if (result == TCL_OK && intObj != NULL) { result = Ns_TclGetMemUnitFromObj(interp, intObj, valuePtr); if (result == TCL_OK && rangePtr != NULL) { result = Ns_CheckWideRange(interp, Tcl_GetString(keyObj), rangePtr, *valuePtr); } } return result; } /* *---------------------------------------------------------------------- * * WriterSubmitFilesObjCmd - subcommand of NsTclWriterObjCmd -- * * Implements "ns_writer submitfiles" command. Send the provided files * to the client. "files" are provided as a list of dicts, where every * dict must contain a "filename" element and can contain an "-offset" * and/or a "-length" element. * * Results: * Standard Tcl result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int WriterSubmitFilesObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { int result = TCL_OK; Ns_Conn *conn; int headers = 0, nrFiles; Tcl_Obj *filesObj = NULL, **fileObjv; Ns_ObjvSpec lopts[] = { {"-headers", Ns_ObjvBool, &headers, INT2PTR(NS_TRUE)}, {NULL, NULL, NULL, NULL} }; Ns_ObjvSpec args[] = { {"files", Ns_ObjvObj, &filesObj, NULL}, {NULL, NULL, NULL, NULL} }; if (unlikely(Ns_ParseObjv(lopts, args, interp, 2, objc, objv) != NS_OK) || NsConnRequire(interp, NS_CONN_REQUIRE_ALL, &conn) != NS_OK) { result = TCL_ERROR; } else if (unlikely( Ns_ConnSockPtr(conn) == NULL )) { Ns_Log(Warning, "NsWriterQueue: called without valid sockPtr, " "maybe connection already closed"); Ns_TclPrintfResult(interp, "0"); result = TCL_OK; } else if (Tcl_ListObjGetElements(interp, filesObj, &nrFiles, &fileObjv) != TCL_OK) { Ns_TclPrintfResult(interp, "not a valid list of files: '%s'", Tcl_GetString(filesObj)); result = TCL_ERROR; } else if (nrFiles == 0) { Ns_TclPrintfResult(interp, "The provided list has to contain at least one file spec"); result = TCL_ERROR; } else { size_t totalbytes = 0u, i; Tcl_Obj *keys[3], *filenameObj = NULL; Ns_FileVec *filebufs; const char *firstFilenameString = NULL; Ns_ObjvValueRange offsetRange = {0, LLONG_MAX}; Ns_ObjvValueRange sizeRange = {1, LLONG_MAX}; filebufs = (Ns_FileVec *)ns_calloc((size_t)nrFiles, sizeof(Ns_FileVec)); keys[0] = Tcl_NewStringObj("filename", 8); keys[1] = Tcl_NewStringObj("-offset", 7); keys[2] = Tcl_NewStringObj("-size", 5); Tcl_IncrRefCount(keys[0]); Tcl_IncrRefCount(keys[1]); Tcl_IncrRefCount(keys[2]); for (i = 0u; i < (size_t)nrFiles; i++) { filebufs[i].fd = NS_INVALID_FD; } /* * Iterate over the list of dicts. */ for (i = 0u; i < (size_t)nrFiles; i++) { Tcl_WideInt offset = 0, size = 0; int rc, fd = NS_INVALID_FD; const char *filenameString; size_t nrbytes; /* * Get required "filename" element. */ filenameObj = NULL; rc = Tcl_DictObjGet(interp, fileObjv[i], keys[0], &filenameObj); if (rc != TCL_OK || filenameObj == NULL) { Ns_TclPrintfResult(interp, "missing filename in dict '%s'", Tcl_GetString(fileObjv[i])); result = TCL_ERROR; break; } filenameString = Tcl_GetString(filenameObj); if (firstFilenameString == NULL) { firstFilenameString = filenameString; } /* * Get optional "-offset" and "-size" elements. */ if (WriterGetMemunitFromDict(interp, fileObjv[i], keys[1], &offsetRange, &offset) != TCL_OK) { result = TCL_ERROR; break; } if (WriterGetMemunitFromDict(interp, fileObjv[i], keys[2], &sizeRange, &size) != TCL_OK) { result = TCL_ERROR; break; } /* * Check validity of the provided values */ result = WriterCheckInputParams(interp, Tcl_GetString(filenameObj), (size_t)size, (off_t)offset, &fd, &nrbytes); if (result != TCL_OK) { break; } filebufs[i].fd = fd; filebufs[i].offset = offset; filebufs[i].length = nrbytes; totalbytes = totalbytes + (size_t)nrbytes; } Tcl_DecrRefCount(keys[0]); Tcl_DecrRefCount(keys[1]); Tcl_DecrRefCount(keys[2]); /* * If everything is ok, submit the request to the writer queue. */ if (result == TCL_OK) { Ns_ReturnCode status; if (headers != 0 && firstFilenameString != NULL) { Ns_ConnSetTypeHeader(conn, Ns_GetMimeType(firstFilenameString)); } status = NsWriterQueue(conn, totalbytes, NULL, NULL, NS_INVALID_FD, NULL, 0, filebufs, nrFiles, NS_TRUE); /* * Provide a soft error like for "ns_writer submitfile". */ Tcl_SetObjResult(interp, Tcl_NewBooleanObj(status == NS_OK ? 1 : 0)); } /* * The NsWriterQueue() API makes the usual duplicates of the file * descriptors and the Ns_FileVec structure, so we have to cleanup * here. */ for (i = 0u; i < (size_t)nrFiles; i++) { if (filebufs[i].fd != NS_INVALID_FD) { (void) ns_close(filebufs[i].fd); } } ns_free(filebufs); } return result; } /* *---------------------------------------------------------------------- * * WriterListObjCmd - subcommand of NsTclWriterObjCmd -- * * Implements "ns_writer list" command. * List the current writer jobs. * * Results: * Standard Tcl result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int WriterListObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { int result = TCL_OK; NsServer *servPtr = NULL; Ns_ObjvSpec lopts[] = { {"-server", Ns_ObjvServer, &servPtr, NULL}, {NULL, NULL, NULL, NULL} }; if (unlikely(Ns_ParseObjv(lopts, NULL, interp, 2, objc, objv) != NS_OK)) { result = TCL_ERROR; } else { Tcl_DString ds, *dsPtr = &ds; const Driver *drvPtr; SpoolerQueue *queuePtr; Tcl_DStringInit(dsPtr); for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) { const DrvWriter *wrPtr; /* * If server was specified, list only results from this server. */ if (servPtr != NULL && servPtr != drvPtr->servPtr) { continue; } wrPtr = &drvPtr->writer; queuePtr = wrPtr->firstPtr; while (queuePtr != NULL) { const WriterSock *wrSockPtr; Ns_MutexLock(&queuePtr->lock); wrSockPtr = queuePtr->curPtr; while (wrSockPtr != NULL) { char ipString[NS_IPADDR_SIZE]; ns_inet_ntop((struct sockaddr *)&(wrSockPtr->sockPtr->sa), ipString,sizeof(ipString)); (void) Ns_DStringNAppend(dsPtr, "{", 1); (void) Ns_DStringAppendTime(dsPtr, &wrSockPtr->startTime); (void) Ns_DStringNAppend(dsPtr, " ", 1); (void) Ns_DStringAppend(dsPtr, queuePtr->threadName); (void) Ns_DStringNAppend(dsPtr, " ", 1); (void) Ns_DStringAppend(dsPtr, drvPtr->threadName); (void) Ns_DStringNAppend(dsPtr, " ", 1); (void) Ns_DStringAppend(dsPtr, NsPoolName(wrSockPtr->poolPtr->pool)); (void) Ns_DStringNAppend(dsPtr, " ", 1); (void) Ns_DStringAppend(dsPtr, ipString); (void) Ns_DStringPrintf(dsPtr, " %d %" PRIdz " %" TCL_LL_MODIFIER "d %d %d ", wrSockPtr->fd, wrSockPtr->size, wrSockPtr->nsent, wrSockPtr->currentRate, wrSockPtr->rateLimit); (void) Ns_DStringAppendElement(dsPtr, (wrSockPtr->clientData != NULL) ? wrSockPtr->clientData : NS_EMPTY_STRING); (void) Ns_DStringNAppend(dsPtr, "} ", 2); wrSockPtr = wrSockPtr->nextPtr; } Ns_MutexUnlock(&queuePtr->lock); queuePtr = queuePtr->nextPtr; } } Tcl_DStringResult(interp, &ds); } return result; } /* *---------------------------------------------------------------------- * * WriterSizeObjCmd - subcommand of NsTclWriterObjCmd -- * * Implements "ns_writer size" command. * Sets or queries size limit for sending via writer. * * Results: * Standard Tcl result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int WriterSizeObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { int result = TCL_OK; Tcl_Obj *driverObj = NULL; Ns_Conn *conn = NULL; Tcl_WideInt intValue = -1; const char *firstArgString; Ns_ObjvValueRange range = {1024, INT_MAX}; Ns_ObjvSpec *opts, optsNew[] = { {"-driver", Ns_ObjvObj, &driverObj, NULL}, {NULL, NULL, NULL, NULL} }; Ns_ObjvSpec *args, argsNew[] = { {"?value", Ns_ObjvMemUnit, &intValue, &range}, {NULL, NULL, NULL, NULL} }; Ns_ObjvSpec argsLegacy[] = { {"driver", Ns_ObjvObj, &driverObj, NULL}, {"?value", Ns_ObjvMemUnit, &intValue, &range}, {NULL, NULL, NULL, NULL} }; firstArgString = objc > 2 ? Tcl_GetString(objv[2]) : NULL; if (firstArgString != NULL) { if (*firstArgString != '-' && ((objc == 3 && CHARTYPE(digit, *firstArgString) == 0) || objc == 4)) { args = argsLegacy; opts = NULL; Ns_LogDeprecated(objv, objc, "ns_writer size ?-driver drv? ?size?", NULL); } else { args = argsNew; opts = optsNew; } } else { args = argsNew; opts = optsNew; } if (Ns_ParseObjv(opts, args, interp, 2, objc, objv) != NS_OK) { result = TCL_ERROR; } else if ((driverObj == NULL) && NsConnRequire(interp, NS_CONN_REQUIRE_ALL, &conn) != NS_OK) { result = TCL_ERROR; } else { DrvWriter *wrPtr; if (DriverWriterFromObj(interp, driverObj, conn, &wrPtr) != NS_OK) { result = TCL_ERROR; } else if (intValue != -1) { /* * The optional argument was provided. */ wrPtr->writersize = (size_t)intValue; } if (result == TCL_OK) { Tcl_SetObjResult(interp, Tcl_NewIntObj((int)wrPtr->writersize)); } } return result; } /* *---------------------------------------------------------------------- * * WriterStreamingObjCmd - subcommand of NsTclWriterObjCmd -- * * Implements "ns_writer streaming" command. * Sets or queries streaming state of the writer. * * Results: * Standard Tcl result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int WriterStreamingObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { int boolValue = -1, result = TCL_OK; Tcl_Obj *driverObj = NULL; Ns_Conn *conn = NULL; const char *firstArgString; Ns_ObjvSpec *opts, optsNew[] = { {"-driver", Ns_ObjvObj, &driverObj, NULL}, {NULL, NULL, NULL, NULL} }; Ns_ObjvSpec *args, argsNew[] = { {"?value", Ns_ObjvBool, &boolValue, NULL}, {NULL, NULL, NULL, NULL} }; Ns_ObjvSpec argsLegacy[] = { {"driver", Ns_ObjvObj, &driverObj, NULL}, {"?value", Ns_ObjvBool, &boolValue, NULL}, {NULL, NULL, NULL, NULL} }; firstArgString = objc > 2 ? Tcl_GetString(objv[2]) : NULL; if (firstArgString != NULL) { int argValue; if (*firstArgString != '-' && ((objc == 3 && Tcl_ExprBoolean(interp, firstArgString, &argValue) == TCL_OK) || objc == 4)) { args = argsLegacy; opts = NULL; Ns_LogDeprecated(objv, objc, "ns_writer streaming ?-driver drv? ?value?", NULL); } else { args = argsNew; opts = optsNew; } } else { args = argsNew; opts = optsNew; } if (Ns_ParseObjv(opts, args, interp, 2, objc, objv) != NS_OK) { result = TCL_ERROR; } else if ((driverObj == NULL) && NsConnRequire(interp, NS_CONN_REQUIRE_ALL, &conn) != NS_OK) { result = TCL_ERROR; } else { DrvWriter *wrPtr; if (DriverWriterFromObj(interp, driverObj, conn, &wrPtr) != NS_OK) { result = TCL_ERROR; } else if (boolValue != -1) { /* * The optional argument was provided. */ wrPtr->doStream = (boolValue == 1 ? NS_WRITER_STREAM_ACTIVE : NS_WRITER_STREAM_NONE); } if (result == TCL_OK) { Tcl_SetObjResult(interp, Tcl_NewIntObj(wrPtr->doStream == NS_WRITER_STREAM_ACTIVE ? 1 : 0)); } } return result; } /* *---------------------------------------------------------------------- * * NsTclWriterObjCmd -- * * Implements "ns_writer" command for submitting data to the writer * threads and to configure and query the state of the writer threads at * runtime. * * Results: * Standard Tcl result. * * Side effects: * None. * *---------------------------------------------------------------------- */ int NsTclWriterObjCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { const Ns_SubCmdSpec subcmds[] = { {"list", WriterListObjCmd}, {"size", WriterSizeObjCmd}, {"streaming", WriterStreamingObjCmd}, {"submit", WriterSubmitObjCmd}, {"submitfile", WriterSubmitFileObjCmd}, {"submitfiles",WriterSubmitFilesObjCmd}, {NULL, NULL} }; return Ns_SubcmdObjv(subcmds, clientData, interp, objc, objv); } /* *====================================================================== * Async (log) writer: Write asynchronously to a disk *====================================================================== */ /* *---------------------------------------------------------------------- * * NsAsyncWriterQueueEnable -- * * Enable async writing and start the AsyncWriterThread if * necessary * * Results: * None. * * Side effects: * Potentially starting a thread and set "stopped" to NS_FALSE. * *---------------------------------------------------------------------- */ void NsAsyncWriterQueueEnable(void) { if (Ns_ConfigBool(NS_CONFIG_PARAMETERS, "asynclogwriter", NS_FALSE) == NS_TRUE) { SpoolerQueue *queuePtr; /* * In case, the async writer has not started, the static variable * asyncWriter is NULL. */ if (asyncWriter == NULL) { Ns_MutexLock(&reqLock); if (likely(asyncWriter == NULL)) { /* * Allocate and initialize writer thread context. */ asyncWriter = ns_calloc(1u, sizeof(AsyncWriter)); Ns_MutexUnlock(&reqLock); Ns_MutexSetName2(&asyncWriter->lock, "ns:driver", "async-writer"); /* * Allocate and initialize a Spooler Queue for this thread. */ queuePtr = ns_calloc(1u, sizeof(SpoolerQueue)); Ns_MutexSetName2(&queuePtr->lock, "ns:driver:async-writer", "queue"); asyncWriter->firstPtr = queuePtr; /* * Start the spooler queue */ SpoolerQueueStart(queuePtr, AsyncWriterThread); } else { Ns_MutexUnlock(&reqLock); } } assert(asyncWriter != NULL); queuePtr = asyncWriter->firstPtr; assert(queuePtr != NULL); Ns_MutexLock(&queuePtr->lock); queuePtr->stopped = NS_FALSE; Ns_MutexUnlock(&queuePtr->lock); } } /* *---------------------------------------------------------------------- * * NsAsyncWriterQueueDisable -- * * Disable async writing but don't touch the writer thread. * * Results: * None. * * Side effects: * Disable async writing by setting stopped to 1. * *---------------------------------------------------------------------- */ void NsAsyncWriterQueueDisable(bool shutdown) { if (asyncWriter != NULL) { SpoolerQueue *queuePtr = asyncWriter->firstPtr; Ns_Time timeout; assert(queuePtr != NULL); Ns_GetTime(&timeout); Ns_IncrTime(&timeout, nsconf.shutdowntimeout.sec, nsconf.shutdowntimeout.usec); Ns_MutexLock(&queuePtr->lock); queuePtr->stopped = NS_TRUE; queuePtr->shutdown = shutdown; /* * Trigger the AsyncWriter Thread to drain the spooler queue. */ SockTrigger(queuePtr->pipe[1]); (void)Ns_CondTimedWait(&queuePtr->cond, &queuePtr->lock, &timeout); Ns_MutexUnlock(&queuePtr->lock); if (shutdown) { ns_free(queuePtr); ns_free(asyncWriter); asyncWriter = NULL; } } } /* *---------------------------------------------------------------------- * * NsAsyncWrite -- * * Perform an asynchronous write operation via a writer thread in * case a writer thread is configured and running. The intention * of the asynchronous write operations is to reduce latencies in * connection threads. * * Results: * NS_OK, when write was performed via writer thread, * NS_ERROR otherwise (but data is written). * * Side effects: * I/O Operation. * *---------------------------------------------------------------------- */ Ns_ReturnCode NsAsyncWrite(int fd, const char *buffer, size_t nbyte) { Ns_ReturnCode returnCode = NS_OK; NS_NONNULL_ASSERT(buffer != NULL); /* * If the async writer has not started or is deactivated, behave like a * ns_write() command. If the ns_write() fails, we can't do much, since * the writing of an error message to the log might bring us into an * infinite loop. So we print simple to stderr. */ if (asyncWriter == NULL || asyncWriter->firstPtr->stopped) { ssize_t written = ns_write(fd, buffer, nbyte); if (unlikely(written != (ssize_t)nbyte)) { int retries = 100; /* * Don't go into an infinite loop when multiple subsequent disk * write operations return 0 (maybe disk full). */ returnCode = NS_ERROR; do { if (written < 0) { fprintf(stderr, "error during async write (fd %d): %s\n", fd, strerror(errno)); break; } /* * All partial writes (written >= 0) */ WriteWarningRaw("partial write", fd, nbyte, written); nbyte -= (size_t)written; buffer += written; written = ns_write(fd, buffer, nbyte); if (written == (ssize_t)nbyte) { returnCode = NS_OK; break; } } while (retries-- > 0); } } else { SpoolerQueue *queuePtr; bool trigger = NS_FALSE; const AsyncWriteData *wdPtr; AsyncWriteData *newWdPtr; /* * Allocate a writer cmd and initialize it. In order to provide an * interface compatible to ns_write(), we copy the provided data, * such it can be freed by the caller. When we would give up the * interface, we could free the memory block after writing, and * save a malloc/free operation on the data. */ newWdPtr = ns_calloc(1u, sizeof(AsyncWriteData)); newWdPtr->fd = fd; newWdPtr->bufsize = nbyte; newWdPtr->data = ns_malloc(nbyte + 1u); memcpy(newWdPtr->data, buffer, newWdPtr->bufsize); newWdPtr->buf = newWdPtr->data; newWdPtr->size = newWdPtr->bufsize; /* * Now add new writer socket to the writer thread's queue. In most * cases, the queue will be empty. */ queuePtr = asyncWriter->firstPtr; assert(queuePtr != NULL); Ns_MutexLock(&queuePtr->lock); wdPtr = queuePtr->sockPtr; if (wdPtr != NULL) { newWdPtr->nextPtr = queuePtr->sockPtr; queuePtr->sockPtr = newWdPtr; } else { queuePtr->sockPtr = newWdPtr; trigger = NS_TRUE; } Ns_MutexUnlock(&queuePtr->lock); /* * Wake up writer thread if desired */ if (trigger) { SockTrigger(queuePtr->pipe[1]); } } return returnCode; } /* *---------------------------------------------------------------------- * * AsyncWriterRelease -- * * Deallocate write data. * * Results: * None * * Side effects: * free memory * *---------------------------------------------------------------------- */ static void AsyncWriterRelease(AsyncWriteData *wdPtr) { NS_NONNULL_ASSERT(wdPtr != NULL); ns_free(wdPtr->data); ns_free(wdPtr); } /* *---------------------------------------------------------------------- * * AsyncWriterThread -- * * Thread that implements non-blocking write operations to files * * Results: * None. * * Side effects: * Write to files. * *---------------------------------------------------------------------- */ static void AsyncWriterThread(void *arg) { SpoolerQueue *queuePtr = (SpoolerQueue*)arg; char charBuffer[1]; int pollTimeout; Ns_ReturnCode status; bool stopping; AsyncWriteData *curPtr, *nextPtr, *writePtr; PollData pdata; Ns_ThreadSetName("-asynclogwriter%d-", queuePtr->id); queuePtr->threadName = Ns_ThreadGetName(); /* * Allocate and initialize controlling variables */ PollCreate(&pdata); writePtr = NULL; stopping = NS_FALSE; /* * Loop forever until signaled to shutdown and all * connections are complete and gracefully closed. */ while (!stopping) { /* * Always listen to the trigger pipe. We could as well perform * in the writer thread async write operations, but for the * effect of reducing latency in connection threads, this is * not an issue. To keep things simple, we perform the * typically small write operations without testing for POLLOUT. */ PollReset(&pdata); (void)PollSet(&pdata, queuePtr->pipe[0], (short)POLLIN, NULL); if (writePtr == NULL) { pollTimeout = 30 * 1000; } else { pollTimeout = 0; } /* * Wait for data */ /*n =*/ (void) PollWait(&pdata, pollTimeout); /* * Select and drain the trigger pipe if necessary. */ if (PollIn(&pdata, 0)) { if (ns_recv(queuePtr->pipe[0], charBuffer, 1u, 0) != 1) { Ns_Fatal("asynclogwriter: trigger ns_recv() failed: %s", ns_sockstrerror(ns_sockerrno)); } if (queuePtr->stopped) { /* * Drain the queue from everything */ for (curPtr = writePtr; curPtr != NULL; curPtr = curPtr->nextPtr) { ssize_t written = ns_write(curPtr->fd, curPtr->buf, curPtr->bufsize); if (unlikely(written != (ssize_t)curPtr->bufsize)) { WriteWarningRaw("drain writer", curPtr->fd, curPtr->bufsize, written); } } writePtr = NULL; for (curPtr = queuePtr->sockPtr; curPtr != NULL; curPtr = curPtr->nextPtr) { ssize_t written = ns_write(curPtr->fd, curPtr->buf, curPtr->bufsize); if (unlikely(written != (ssize_t)curPtr->bufsize)) { WriteWarningRaw("drain queue", curPtr->fd, curPtr->bufsize, written); } } queuePtr->sockPtr = NULL; /* * Notify the caller (normally * NsAsyncWriterQueueDisable()) that we are done */ Ns_CondBroadcast(&queuePtr->cond); } } /* * Write to all available file descriptors */ curPtr = writePtr; writePtr = NULL; while (curPtr != NULL) { ssize_t written; nextPtr = curPtr->nextPtr; status = NS_OK; /* * Write the actual data and allow for partial write operations. */ written = ns_write(curPtr->fd, curPtr->buf, curPtr->bufsize); if (unlikely(written < 0)) { status = NS_ERROR; } else { curPtr->size -= (size_t)written; curPtr->nsent += written; curPtr->bufsize -= (size_t)written; if (curPtr->data != NULL) { curPtr->buf += written; } } if (unlikely(status != NS_OK)) { AsyncWriterRelease(curPtr); queuePtr->queuesize--; } else { /* * The write operation was successful. Check if there * is some remaining data to write. If not we are done * with this request can release the write buffer. */ if (curPtr->size > 0u) { Push(curPtr, writePtr); } else { AsyncWriterRelease(curPtr); queuePtr->queuesize--; } } curPtr = nextPtr; } /* * Check for shutdown */ stopping = queuePtr->shutdown; if (stopping) { curPtr = queuePtr->sockPtr; assert(writePtr == NULL); while (curPtr != NULL) { ssize_t written = ns_write(curPtr->fd, curPtr->buf, curPtr->bufsize); if (unlikely(written != (ssize_t)curPtr->bufsize)) { WriteWarningRaw("shutdown", curPtr->fd, curPtr->bufsize, written); } curPtr = curPtr->nextPtr; } } else { /* * Add fresh jobs to the writer queue. This means actually to * move jobs from queuePtr->sockPtr (kept name for being able * to use the same queue as above) to the currently active * jobs in queuePtr->curPtr. */ Ns_MutexLock(&queuePtr->lock); curPtr = queuePtr->sockPtr; queuePtr->sockPtr = NULL; while (curPtr != NULL) { nextPtr = curPtr->nextPtr; Push(curPtr, writePtr); queuePtr->queuesize++; curPtr = nextPtr; } queuePtr->curPtr = writePtr; Ns_MutexUnlock(&queuePtr->lock); } } PollFree(&pdata); queuePtr->stopped = NS_TRUE; Ns_Log(Notice, "exiting"); } /* *---------------------------------------------------------------------- * * AsyncLogfileWriteObjCmd - * * Implements "ns_asynclogfile write" command. Write to a file * descriptor via async writer thread. The command handles partial write * operations internally. * * Results: * Standard Tcl result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int AsyncLogfileWriteObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { int result = TCL_OK, binary = (int)NS_FALSE, sanitize; Tcl_Obj *stringObj; int fd = 0; Ns_ObjvValueRange fd_range = {0, INT_MAX}; Ns_ObjvValueRange sanitize_range = {0, 2}; Ns_ObjvSpec opts[] = { {"-binary", Ns_ObjvBool, &binary, INT2PTR(NS_TRUE)}, {"-sanitize", Ns_ObjvInt, &sanitize, &sanitize_range}, {NULL, NULL, NULL, NULL} }; Ns_ObjvSpec args[] = { {"fd", Ns_ObjvInt, &fd, &fd_range}, {"buffer", Ns_ObjvObj, &stringObj, NULL}, {NULL, NULL, NULL, NULL} }; /* * Take the config value as default for "-sanitize", but let the used * override it on a per-case basis. */ sanitize = nsconf.sanitize_logfiles; if (unlikely(Ns_ParseObjv(opts, args, interp, 2, objc, objv) != NS_OK)) { result = TCL_ERROR; } else { const char *buffer; int length; Ns_ReturnCode rc; if (binary == (int)NS_TRUE || NsTclObjIsByteArray(stringObj)) { buffer = (const char *) Tcl_GetByteArrayFromObj(stringObj, &length); } else { buffer = Tcl_GetStringFromObj(stringObj, &length); } if (length > 0) { if (sanitize > 0) { Tcl_DString ds; bool lastCharNewline = (buffer[length-1] == '\n'); Tcl_DStringInit(&ds); if (lastCharNewline) { length --; } Ns_DStringAppendPrintable(&ds, sanitize == 2, buffer, (size_t)length); if (lastCharNewline) { Tcl_DStringAppend(&ds, "\n", 1); } rc = NsAsyncWrite(fd, ds.string, (size_t)ds.length); Tcl_DStringFree(&ds); } else { rc = NsAsyncWrite(fd, buffer, (size_t)length); } if (rc != NS_OK) { Ns_TclPrintfResult(interp, "ns_asynclogfile: error during write operation on fd %d: %s", fd, Tcl_PosixError(interp)); result = TCL_ERROR; } } else { result = TCL_OK; } } return result; } /* *---------------------------------------------------------------------- * * AsyncLogfileOpenObjCmd - * * Implements "ns_asynclogfile open" command. The command opens a * write-only log file and return a thread-shareable handle (actually a * numeric file descriptor) which can be used in subsequent "write" or * "close" operations. * * Results: * Standard Tcl result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int AsyncLogfileOpenObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { int result = TCL_OK; unsigned int flags = O_APPEND; char *fileNameString; Tcl_Obj *flagsObj = NULL; Ns_ObjvTable flagTable[] = { {"APPEND", O_APPEND}, {"EXCL", O_EXCL}, #ifdef O_DSYNC {"DSYNC", O_DSYNC}, #endif #ifdef O_SYNC {"SYNC", O_SYNC}, #endif {"TRUNC", O_TRUNC}, {NULL, 0u} }; Ns_ObjvSpec args[] = { {"filename", Ns_ObjvString, &fileNameString, NULL}, {"?flags", Ns_ObjvObj, &flagsObj, NULL}, //{"mode", Ns_ObjvString, &mode, NULL}, {NULL, NULL, NULL, NULL} }; if (unlikely(Ns_ParseObjv(NULL, args, interp, 2, objc, objv) != NS_OK)) { result = TCL_ERROR; } else if (flagsObj != NULL) { Tcl_Obj **ov; int oc; result = Tcl_ListObjGetElements(interp, flagsObj, &oc, &ov); if (result == TCL_OK && oc > 0) { int i, opt; flags = 0u; for (i = 0; i < oc; i++) { result = Tcl_GetIndexFromObjStruct(interp, ov[i], flagTable, (int)sizeof(flagTable[0]), "flag", 0, &opt); if (result != TCL_OK) { break; } else { flags = flagTable[opt].value; } } } } if (result == TCL_OK) { int fd; fd = ns_open(fileNameString, (int)(O_CREAT | O_WRONLY | O_CLOEXEC | flags), 0644); if (unlikely(fd == NS_INVALID_FD)) { Ns_TclPrintfResult(interp, "could not open file '%s': %s", fileNameString, Tcl_PosixError(interp)); result = TCL_ERROR; } else { Tcl_SetObjResult(interp, Tcl_NewIntObj(fd)); } } return result; } /* *---------------------------------------------------------------------- * * AsyncLogfileCloseObjCmd - * * Implements "ns_asynclogfile close" command. Close the logfile * previously created via "ns_asynclogfile open". * * Results: * Standard Tcl result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int AsyncLogfileCloseObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { int fd, result = TCL_OK; Ns_ObjvValueRange range = {0, INT_MAX}; Ns_ObjvSpec args[] = { {"fd", Ns_ObjvInt, &fd, &range}, {NULL, NULL, NULL, NULL} }; if (unlikely(Ns_ParseObjv(NULL, args, interp, 2, objc, objv) != NS_OK)) { result = TCL_ERROR; } else { int rc = ns_close(fd); if (rc != 0) { Ns_TclPrintfResult(interp, "could not close fd %d: %s", fd, Tcl_PosixError(interp)); result = TCL_ERROR; } } return result; } /* *---------------------------------------------------------------------- * * NsTclAsyncLogfileObjCmd - * * Wrapper for "ns_asynclogfile open|write|close" commands. * * Results: * Standard Tcl result. * * Side effects: * None. * *---------------------------------------------------------------------- */ int NsTclAsyncLogfileObjCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { const Ns_SubCmdSpec subcmds[] = { {"open", AsyncLogfileOpenObjCmd}, {"write", AsyncLogfileWriteObjCmd}, {"close", AsyncLogfileCloseObjCmd}, {NULL, NULL} }; return Ns_SubcmdObjv(subcmds, clientData, interp, objc, objv); } /* *---------------------------------------------------------------------- * * LookupDriver -- * * Find a matching driver for the specified protocol and optionally the * specified driver name. * * Results: * Driver pointer or NULL on failure. * * Side effects: * When no driver is found, an error is left in the interp result. * *---------------------------------------------------------------------- */ static Driver * LookupDriver(Tcl_Interp *interp, const char* protocol, const char *driverName) { Driver *drvPtr; NS_NONNULL_ASSERT(interp != NULL); NS_NONNULL_ASSERT(protocol != NULL); for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) { Ns_Log(DriverDebug, "... check Driver proto <%s> server %s name %s location %s", drvPtr->protocol, drvPtr->server, drvPtr->threadName, drvPtr->location); if (STREQ(drvPtr->protocol, protocol)) { if (driverName == NULL) { /* * If there is no driver name given, take the first driver * with the matching protocol. */ break; } else if (STREQ(drvPtr->moduleName, driverName)) { /* * The driver name (name of the loaded module) is equal */ break; } } } if (drvPtr == NULL) { if (driverName != NULL) { Ns_TclPrintfResult(interp, "no driver for protocol '%s' & driver name '%s' found", protocol, driverName); } else { Ns_TclPrintfResult(interp, "no driver for protocol '%s' found", protocol); } } return drvPtr; } /* *---------------------------------------------------------------------- * * NSDriverClientOpen -- * * Open a client HTTP connection using the driver interface * * Results: * Tcl return code. * * Side effects: * Opening a connection * *---------------------------------------------------------------------- */ int NSDriverClientOpen(Tcl_Interp *interp, const char *driverName, const char *url, const char *httpMethod, const char *version, const Ns_Time *timeoutPtr, Sock **sockPtrPtr) { char *protocol, *host, *portString, *path, *tail, *url2; int result = TCL_OK; NS_NONNULL_ASSERT(interp != NULL); NS_NONNULL_ASSERT(url != NULL); NS_NONNULL_ASSERT(httpMethod != NULL); NS_NONNULL_ASSERT(version != NULL); NS_NONNULL_ASSERT(sockPtrPtr != NULL); url2 = ns_strdup(url); /* * We need here a fully qualified URL, otherwise raise an error */ if (unlikely(Ns_ParseUrl(url2, &protocol, &host, &portString, &path, &tail) != NS_OK) || protocol == NULL || host == NULL || path == NULL || tail == NULL) { Ns_Log(Notice, "driver: invalid URL '%s' passed to NSDriverClientOpen", url2); result = TCL_ERROR; } else { Driver *drvPtr; unsigned short portNr = 0u; /* make static checker happy */ assert(protocol != NULL); assert(host != NULL); assert(path != NULL); assert(tail != NULL); /* * Find a matching driver for the specified protocol and optionally * the specified driver name. */ drvPtr = LookupDriver(interp, protocol, driverName); if (drvPtr == NULL) { result = TCL_ERROR; } else if (portString != NULL) { portNr = (unsigned short) strtol(portString, NULL, 10); } else if (drvPtr->defport != 0u) { /* * Get the default port from the driver structure; */ portNr = drvPtr->defport; } else { Ns_TclPrintfResult(interp, "no default port for protocol '%s' defined", protocol); result = TCL_ERROR; } if (result == TCL_OK) { NS_SOCKET sock; Ns_ReturnCode status; sock = Ns_SockTimedConnect2(host, portNr, NULL, 0u, timeoutPtr, &status); if (sock == NS_INVALID_SOCKET) { Ns_SockConnectError(interp, host, portNr, status); result = TCL_ERROR; } else { const char *query; Tcl_DString ds, *dsPtr = &ds; Request *reqPtr; Sock *sockPtr; assert(drvPtr != NULL); sockPtr = SockNew(drvPtr); sockPtr->sock = sock; sockPtr->servPtr = drvPtr->servPtr; if (sockPtr->servPtr == NULL) { const NsInterp *itPtr = NsGetInterpData(interp); sockPtr->servPtr = itPtr->servPtr; } RequestNew(sockPtr); Ns_GetTime(&sockPtr->acceptTime); reqPtr = sockPtr->reqPtr; Tcl_DStringInit(dsPtr); Ns_DStringAppend(dsPtr, httpMethod); Ns_StrToUpper(Ns_DStringValue(dsPtr)); Tcl_DStringAppend(dsPtr, " /", 2); if (*path != '\0') { if (*path == '/') { path ++; } Tcl_DStringAppend(dsPtr, path, -1); Tcl_DStringAppend(dsPtr, "/", 1); } Tcl_DStringAppend(dsPtr, tail, -1); Tcl_DStringAppend(dsPtr, " HTTP/", 6); Tcl_DStringAppend(dsPtr, version, -1); reqPtr->request.line = Ns_DStringExport(dsPtr); reqPtr->request.method = ns_strdup(httpMethod); reqPtr->request.protocol = ns_strdup(protocol); reqPtr->request.host = ns_strdup(host); query = strchr(tail, INTCHAR('?')); if (query != NULL) { reqPtr->request.query = ns_strdup(query+1); } else { reqPtr->request.query = NULL; } /*Ns_Log(Notice, "REQUEST LINE <%s> query <%s>", reqPtr->request.line, reqPtr->request.query);*/ *sockPtrPtr = sockPtr; } } } ns_free(url2); return result; } /* *---------------------------------------------------------------------- * * NSDriverSockNew -- * * Create a Sock structure based on the driver interface * * Results: * Tcl return code. * * Side effects: * Accepting a connection * *---------------------------------------------------------------------- */ int NSDriverSockNew(Tcl_Interp *interp, NS_SOCKET sock, const char *protocol, const char *driverName, const char *methodName, Sock **sockPtrPtr) { int result = TCL_OK; Driver *drvPtr; NS_NONNULL_ASSERT(interp != NULL); NS_NONNULL_ASSERT(protocol != NULL); NS_NONNULL_ASSERT(methodName != NULL); NS_NONNULL_ASSERT(sockPtrPtr != NULL); drvPtr = LookupDriver(interp, protocol, driverName); if (drvPtr == NULL) { result = TCL_ERROR; } else { Sock *sockPtr; Tcl_DString ds, *dsPtr = &ds; Request *reqPtr; sockPtr = SockNew(drvPtr); sockPtr->servPtr = drvPtr->servPtr; sockPtr->sock = sock; RequestNew(sockPtr); // not sure if needed // peerAddr is missing Ns_GetTime(&sockPtr->acceptTime); reqPtr = sockPtr->reqPtr; Tcl_DStringInit(dsPtr); Ns_DStringAppend(dsPtr, methodName); Ns_StrToUpper(Ns_DStringValue(dsPtr)); reqPtr->request.line = Ns_DStringExport(dsPtr); reqPtr->request.method = ns_strdup(methodName); reqPtr->request.protocol = ns_strdup(protocol); reqPtr->request.host = NULL; reqPtr->request.query = NULL; /* Ns_Log(Notice, "REQUEST LINE <%s>", reqPtr->request.line);*/ *sockPtrPtr = sockPtr; } return result; } /* * Local Variables: * mode: c * c-basic-offset: 4 * fill-column: 78 * indent-tabs-mode: nil * End: */
null
/* * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://mozilla.org/. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See * the License for the specific language governing rights and limitations * under the License. * * The Original Code is AOLserver Code and related documentation * distributed by AOL. * * The Initial Developer of the Original Code is America Online, * Inc. Portions created by AOL are Copyright (C) 1999 America Online, * Inc. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms * of the GNU General Public License (the "GPL"), in which case the * provisions of GPL are applicable instead of those above. If you wish * to allow use of your version of this file only under the terms of the * GPL and not to allow others to use your version of this file under the * License, indicate your decision by deleting the provisions above and * replace them with the notice and other provisions required by the GPL. * If you do not delete the provisions above, a recipient may use your * version of this file under either the License or the GPL. */ /* * driver.c -- * * Connection I/O for loadable socket drivers. */ #include "nsd.h" /* * The following are valid driver state flags. */ #define DRIVER_STARTED 1u #define DRIVER_STOPPED 2u #define DRIVER_SHUTDOWN 4u #define DRIVER_FAILED 8u /* * Constants for SockState return and reason codes. */ typedef enum { SOCK_READY = 0, SOCK_MORE = 1, SOCK_SPOOL = 2, SOCK_ERROR = -1, SOCK_CLOSE = -2, SOCK_CLOSETIMEOUT = -3, SOCK_READTIMEOUT = -4, SOCK_WRITETIMEOUT = -5, SOCK_READERROR = -6, SOCK_WRITEERROR = -7, SOCK_SHUTERROR = -8, SOCK_BADREQUEST = -9, SOCK_ENTITYTOOLARGE = -10, SOCK_BADHEADER = -11, SOCK_TOOMANYHEADERS = -12 } SockState; /* * Subset for spooler states */ typedef enum { SPOOLER_CLOSE = SOCK_CLOSE, SPOOLER_OK = SOCK_READY, SPOOLER_READERROR = SOCK_READERROR, SPOOLER_WRITEERROR = SOCK_WRITEERROR, SPOOLER_CLOSETIMEOUT = SOCK_CLOSETIMEOUT } SpoolerState; typedef struct { SpoolerState spoolerState; SockState sockState; } SpoolerStateMap; /* * ServerMap maintains Host header to server mappings. */ typedef struct ServerMap { NsServer *servPtr; char location[1]; } ServerMap; /* * The following maintains the spooler state mapping */ static const SpoolerStateMap spoolerStateMap[] = { {SPOOLER_CLOSE, SOCK_CLOSE}, {SPOOLER_READERROR, SOCK_READERROR}, {SPOOLER_WRITEERROR, SOCK_WRITEERROR}, {SPOOLER_CLOSETIMEOUT, SOCK_CLOSETIMEOUT}, {SPOOLER_OK, SOCK_READY} }; /* * The following structure manages polling. The PollIn macro is * used for the common case of checking for readability. */ typedef struct PollData { unsigned int nfds; /* Number of fds being monitored. */ unsigned int maxfds; /* Max fds (will grow as needed). */ struct pollfd *pfds; /* Dynamic array of poll structs. */ Ns_Time timeout; /* Min timeout, if any, for next spin. */ } PollData; #define PollIn(ppd, i) (((ppd)->pfds[(i)].revents & POLLIN) == POLLIN ) #define PollOut(ppd, i) (((ppd)->pfds[(i)].revents & POLLOUT) == POLLOUT) #define PollHup(ppd, i) (((ppd)->pfds[(i)].revents & POLLHUP) == POLLHUP) /* * Collected informationof writer threads for per pool rates, necessary for * per pool bandwidth management. */ typedef struct ConnPoolInfo { size_t threadSlot; int currentPoolRate; int deltaPercentage; } ConnPoolInfo; /* * The following structure maintains writer socket */ typedef struct WriterSock { struct WriterSock *nextPtr; struct Sock *sockPtr; struct SpoolerQueue *queuePtr; struct Conn *connPtr; SpoolerState status; int err; int refCount; unsigned int flags; Tcl_WideInt nsent; size_t size; NsWriterStreamState doStream; int fd; char *headerString; struct ConnPool *poolPtr; union { struct { struct iovec *bufs; /* incoming bufs to be sent */ int nbufs; int bufIdx; struct iovec sbufs[UIO_SMALLIOV]; /* scratch bufs for handling partial sends */ int nsbufs; int sbufIdx; struct iovec preallocated_bufs[UIO_SMALLIOV]; struct FileMap fmap; } mem; struct { size_t maxsize; size_t bufsize; off_t bufoffset; size_t toRead; unsigned char *buf; Ns_FileVec *bufs; int nbufs; int currentbuf; Ns_Mutex fdlock; } file; } c; char *clientData; Ns_Time startTime; int rateLimit; int currentRate; ConnPoolInfo *infoPtr; bool keep; } WriterSock; /* * Async writer definitions */ typedef struct AsyncWriter { Ns_Mutex lock; /* Lock around writer queues */ SpoolerQueue *firstPtr; /* List of writer threads */ } AsyncWriter; /* * AsyncWriteData is similar to WriterSock */ typedef struct AsyncWriteData { struct AsyncWriteData *nextPtr; char *data; int fd; Tcl_WideInt nsent; size_t size; size_t bufsize; const char *buf; } AsyncWriteData; static AsyncWriter *asyncWriter = NULL; /* * Static functions defined in this file. */ static Ns_ThreadProc DriverThread; static Ns_ThreadProc SpoolerThread; static Ns_ThreadProc WriterThread; static Ns_ThreadProc AsyncWriterThread; static Tcl_ObjCmdProc WriterListObjCmd; static Tcl_ObjCmdProc WriterSizeObjCmd; static Tcl_ObjCmdProc WriterStreamingObjCmd; static Tcl_ObjCmdProc WriterSubmitObjCmd; static Tcl_ObjCmdProc WriterSubmitFileObjCmd; static Tcl_ObjCmdProc AsyncLogfileWriteObjCmd; static Tcl_ObjCmdProc AsyncLogfileOpenObjCmd; static Tcl_ObjCmdProc AsyncLogfileCloseObjCmd; static Ns_ReturnCode DriverWriterFromObj(Tcl_Interp *interp, Tcl_Obj *driverObj, Ns_Conn *conn, DrvWriter **wrPtrPtr) NS_GNUC_NONNULL(1) NS_GNUC_NONNULL(4); static NS_SOCKET DriverListen(Driver *drvPtr, const char *bindaddr) NS_GNUC_NONNULL(1) NS_GNUC_NONNULL(2); static NS_DRIVER_ACCEPT_STATUS DriverAccept(Sock *sockPtr, NS_SOCKET sock) NS_GNUC_NONNULL(1); static bool DriverKeep(Sock *sockPtr) NS_GNUC_NONNULL(1); static void DriverClose(Sock *sockPtr) NS_GNUC_NONNULL(1); static Ns_ReturnCode DriverInit(const char *server, const char *moduleName, const char *threadName, const Ns_DriverInitData *init, NsServer *servPtr, const char *path, const char *bindaddrs, const char *defserver, const char *host) NS_GNUC_NONNULL(2) NS_GNUC_NONNULL(3) NS_GNUC_NONNULL(4) NS_GNUC_NONNULL(6) NS_GNUC_NONNULL(7) NS_GNUC_NONNULL(9); static bool DriverModuleInitialized(const char *module) NS_GNUC_NONNULL(1); static void SockSetServer(Sock *sockPtr) NS_GNUC_NONNULL(1); static SockState SockAccept(Driver *drvPtr, NS_SOCKET sock, Sock **sockPtrPtr, const Ns_Time *nowPtr) NS_GNUC_NONNULL(1); static Ns_ReturnCode SockQueue(Sock *sockPtr, const Ns_Time *timePtr) NS_GNUC_NONNULL(1); static Sock *SockNew(Driver *drvPtr) NS_GNUC_NONNULL(1) NS_GNUC_RETURNS_NONNULL; static void SockRelease(Sock *sockPtr, SockState reason, int err) NS_GNUC_NONNULL(1); static void SockError(Sock *sockPtr, SockState reason, int err) NS_GNUC_NONNULL(1); static void SockSendResponse(Sock *sockPtr, int code, const char *errMsg) NS_GNUC_NONNULL(1) NS_GNUC_NONNULL(3); static void SockTrigger(NS_SOCKET sock); static void SockTimeout(Sock *sockPtr, const Ns_Time *nowPtr, const Ns_Time *timeout) NS_GNUC_NONNULL(1); static void SockClose(Sock *sockPtr, int keep) NS_GNUC_NONNULL(1); static SockState SockRead(Sock *sockPtr, int spooler, const Ns_Time *timePtr) NS_GNUC_NONNULL(1); static SockState SockParse(Sock *sockPtr) NS_GNUC_NONNULL(1); static void SockPoll(Sock *sockPtr, short type, PollData *pdata) NS_GNUC_NONNULL(1) NS_GNUC_NONNULL(3); static int SockSpoolerQueue(Driver *drvPtr, Sock *sockPtr) NS_GNUC_NONNULL(1) NS_GNUC_NONNULL(2); static void SpoolerQueueStart(SpoolerQueue *queuePtr, Ns_ThreadProc *proc) NS_GNUC_NONNULL(2); static void SpoolerQueueStop(SpoolerQueue *queuePtr, const Ns_Time *timeoutPtr, const char *name) NS_GNUC_NONNULL(2) NS_GNUC_NONNULL(3); static void PollCreate(PollData *pdata) NS_GNUC_NONNULL(1); static void PollFree(PollData *pdata) NS_GNUC_NONNULL(1); static void PollReset(PollData *pdata) NS_GNUC_NONNULL(1); static NS_POLL_NFDS_TYPE PollSet(PollData *pdata, NS_SOCKET sock, short type, const Ns_Time *timeoutPtr) NS_GNUC_NONNULL(1); static int PollWait(const PollData *pdata, int timeout) NS_GNUC_NONNULL(1); static SockState ChunkedDecode(Request *reqPtr, bool update) NS_GNUC_NONNULL(1); static WriterSock *WriterSockRequire(const Conn *connPtr) NS_GNUC_NONNULL(1); static void WriterSockRelease(WriterSock *wrSockPtr) NS_GNUC_NONNULL(1); static SpoolerState WriterReadFromSpool(WriterSock *curPtr) NS_GNUC_NONNULL(1); static SpoolerState WriterSend(WriterSock *curPtr, int *err) NS_GNUC_NONNULL(1) NS_GNUC_NONNULL(2); static Ns_ReturnCode WriterSetupStreamingMode(Conn *connPtr, struct iovec *bufs, int nbufs, int *fdPtr) NS_GNUC_NONNULL(1) NS_GNUC_NONNULL(2) NS_GNUC_NONNULL(4); static void WriterSockFileVecCleanup(WriterSock *wrSockPtr) NS_GNUC_NONNULL(1); static int WriterGetMemunitFromDict(Tcl_Interp *interp, Tcl_Obj *dictObj, Tcl_Obj *keyObj, Ns_ObjvValueRange *rangePtr, Tcl_WideInt *valuePtr) NS_GNUC_NONNULL(1) NS_GNUC_NONNULL(2) NS_GNUC_NONNULL(3) NS_GNUC_NONNULL(5); static void AsyncWriterRelease(AsyncWriteData *wdPtr) NS_GNUC_NONNULL(1); static void WriteWarningRaw(const char *msg, int fd, size_t wantWrite, ssize_t written) NS_GNUC_NONNULL(1); static const char *GetSockStateName(SockState sockState); static size_t EndOfHeader(Sock *sockPtr) NS_GNUC_NONNULL(1); static void RequestNew(Sock *sockPtr) NS_GNUC_NONNULL(1); static void RequestFree(Sock *sockPtr) NS_GNUC_NONNULL(1); static void LogBuffer(Ns_LogSeverity severity, const char *msg, const char *buffer, size_t len) NS_GNUC_NONNULL(2) NS_GNUC_NONNULL(3); static void ServerMapEntryAdd(Tcl_DString *dsPtr, const char *host, NsServer *servPtr, Driver *drvPtr, bool addDefaultMapEntry) NS_GNUC_NONNULL(1) NS_GNUC_NONNULL(2) NS_GNUC_NONNULL(3) NS_GNUC_NONNULL(4); static Driver *LookupDriver(Tcl_Interp *interp, const char* protocol, const char *driverName) NS_GNUC_NONNULL(1) NS_GNUC_NONNULL(2); static void WriterPerPoolRates(WriterSock *writePtr, Tcl_HashTable *pools) NS_GNUC_NONNULL(1) NS_GNUC_NONNULL(2); static ConnPoolInfo *WriterGetInfoPtr(WriterSock *curPtr, Tcl_HashTable *pools) NS_GNUC_NONNULL(1) NS_GNUC_NONNULL(2); /* * Global variables defined in this file. */ //NS_EXTERN Ns_LogSeverity Ns_LogAccessDebug; Ns_LogSeverity Ns_LogTaskDebug; Ns_LogSeverity Ns_LogRequestDebug; Ns_LogSeverity Ns_LogConnchanDebug; Ns_LogSeverity Ns_LogUrlspaceDebug; Ns_LogSeverity Ns_LogAccessDebug; Ns_LogSeverity Ns_LogTimeoutDebug; NS_EXPORT Ns_LogSeverity Ns_LogAccessDebug; bool NsWriterBandwidthManagement = NS_FALSE; static Ns_LogSeverity WriterDebug; /* Severity at which to log verbose debugging. */ static Ns_LogSeverity DriverDebug; /* Severity at which to log verbose debugging. */ static Ns_Mutex reqLock = NULL; /* Lock for allocated Request structure pool */ static Ns_Mutex writerlock = NULL; /* Lock updating streaming information in the writer */ static Request *firstReqPtr = NULL; /* Allocated request structures kept in a pool */ static Driver *firstDrvPtr = NULL; /* First in list of all drivers */ #define Push(x, xs) ((x)->nextPtr = (xs), (xs) = (x)) /* *---------------------------------------------------------------------- * * WriteWarningRaw -- * * Write a warning message to stderr. This function is for cases, where * writing to Ns_Log can't be used (e.g. in the AsyncWriter, which is * used for writing also to the system log). * * Results: * None. * * Side effects: * Line to stderr. * *---------------------------------------------------------------------- */ static void WriteWarningRaw(const char *msg, int fd, size_t wantWrite, ssize_t written) { fprintf(stderr, "%s: Warning: wanted to write %" PRIuz " bytes, wrote %ld to file descriptor %d\n", msg, wantWrite, (long)written, fd); } /* *---------------------------------------------------------------------- * * GetSockStateName -- * * Return human readable names for StockState values. * * Results: * string * * Side effects: * None. * *---------------------------------------------------------------------- */ static const char * GetSockStateName(SockState sockState) { int sockStateInt = (int)sockState; static const char *sockStateStrings[] = { "SOCK_READY", "SOCK_MORE", "SOCK_SPOOL", "SOCK_ERROR", "SOCK_CLOSE", "SOCK_CLOSETIMEOUT", "SOCK_READTIMEOUT", "SOCK_WRITETIMEOUT", "SOCK_READERROR", "SOCK_WRITEERROR", "SOCK_SHUTERROR", "SOCK_BADREQUEST", "SOCK_ENTITYTOOLARGE", "SOCK_BADHEADER", "SOCK_TOOMANYHEADERS", NULL }; if (sockStateInt < 0) { sockStateInt = (- sockStateInt) + 2; } assert(sockStateInt < Ns_NrElements(sockStateStrings)); return sockStateStrings[sockStateInt]; } /* *---------------------------------------------------------------------- * * NsInitDrivers -- * * Init drivers system. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------- */ void NsInitDrivers(void) { DriverDebug = Ns_CreateLogSeverity("Debug(ns:driver)"); WriterDebug = Ns_CreateLogSeverity("Debug(writer)"); Ns_LogTaskDebug = Ns_CreateLogSeverity("Debug(task)"); Ns_LogRequestDebug = Ns_CreateLogSeverity("Debug(request)"); Ns_LogConnchanDebug = Ns_CreateLogSeverity("Debug(connchan)"); Ns_LogUrlspaceDebug = Ns_CreateLogSeverity("Debug(urlspace)"); Ns_LogAccessDebug = Ns_CreateLogSeverity("Debug(access)"); Ns_LogTimeoutDebug = Ns_CreateLogSeverity("Debug(timeout)"); Ns_MutexInit(&reqLock); Ns_MutexInit(&writerlock); Ns_MutexSetName2(&reqLock, "ns:driver", "requestpool"); Ns_MutexSetName2(&writerlock, "ns:writer", "stream"); } /* *---------------------------------------------------------------------- * * DriverModuleInitialized -- * * Check if a driver with the specified name is already initialized. * * Results: * Boolean * * Side effects: * None. * *---------------------------------------------------------------------- */ static bool DriverModuleInitialized(const char *module) { Driver *drvPtr; bool found = NS_FALSE; NS_NONNULL_ASSERT(module != NULL); for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) { if (strcmp(drvPtr->moduleName, module) == 0) { found = NS_TRUE; Ns_Log(Notice, "Driver %s is already initialized", module); break; } } return found; } /* *---------------------------------------------------------------------- * * Ns_DriverInit -- * * Initialize a driver. * * Results: * NS_OK if initialized, NS_ERROR if config or other error. * * Side effects: * Listen socket will be opened later in NsStartDrivers. * *---------------------------------------------------------------------- */ Ns_ReturnCode Ns_DriverInit(const char *server, const char *module, const Ns_DriverInitData *init) { Ns_ReturnCode status = NS_OK; NsServer *servPtr = NULL; bool alreadyInitialized = NS_FALSE; NS_NONNULL_ASSERT(module != NULL); NS_NONNULL_ASSERT(init != NULL); /* * If a server is provided, servPtr must be set. */ if (server != NULL) { servPtr = NsGetServer(server); if (unlikely(servPtr == NULL)) { Ns_Log(Bug, "cannot lookup server structure for server: %s", module); status = NS_ERROR; } } else { alreadyInitialized = DriverModuleInitialized(module); } /* * Check versions of drivers. */ if (status == NS_OK && init->version < NS_DRIVER_VERSION_4) { Ns_Log(Warning, "%s: driver version is too old (version %d), Version 4 is recommended", module, init->version); } #ifdef HAVE_IPV6 if (status == NS_OK && init->version < NS_DRIVER_VERSION_3) { Ns_Log(Error, "%s: driver version is too old (version %d) and does not support IPv6", module, init->version); status = NS_ERROR; } #endif if (status == NS_OK && init->version < NS_DRIVER_VERSION_2) { Ns_Log(Error, "%s: version field of driver is invalid: %d", module, init->version); status = NS_ERROR; } if (!alreadyInitialized && status == NS_OK) { const char *path, *host, *address, *defserver; bool noHostNameGiven; int nrDrivers, nrBindaddrs = 0, result; Ns_Set *set; Tcl_Obj *bindaddrsObj, **objv; path = ((init->path != NULL) ? init->path : Ns_ConfigGetPath(server, module, (char *)0L)); set = Ns_ConfigCreateSection(path); /* * Determine the "defaultserver" the "hostname" / "address" for * binding to and/or the HTTP location string. */ defserver = Ns_ConfigGetValue(path, "defaultserver"); address = Ns_ConfigGetValue(path, "address"); host = Ns_ConfigGetValue(path, "hostname"); noHostNameGiven = (host == NULL); /* * If the listen address was not specified, attempt to determine it * through a DNS lookup of the specified hostname or the server's * primary hostname. */ if (address == NULL) { Tcl_DString ds; Tcl_DStringInit(&ds); if (noHostNameGiven) { host = Ns_InfoHostname(); } if (Ns_GetAllAddrByHost(&ds, host) == NS_TRUE) { address = ns_strdup(Tcl_DStringValue(&ds)); if (path != NULL) { Ns_SetUpdate(set, "address", address); } Ns_Log(Notice, "no address given, obtained address '%s' from host name %s", address, host); } Tcl_DStringFree(&ds); } if (address == NULL) { address = NS_IP_UNSPECIFIED; Ns_Log(Notice, "no address given, set address to unspecified address %s", address); } bindaddrsObj = Tcl_NewStringObj(address, -1); result = Tcl_ListObjGetElements(NULL, bindaddrsObj, &nrBindaddrs, &objv); if (result != TCL_OK || nrBindaddrs < 1 || nrBindaddrs >= MAX_LISTEN_ADDR_PER_DRIVER) { Ns_Fatal("%s: bindaddrs '%s' is not a valid Tcl list containing addresses (max %d)", module, address, MAX_LISTEN_ADDR_PER_DRIVER); } Tcl_IncrRefCount(bindaddrsObj); /* * If the hostname was not specified and not determined by the lookup * above, set it to the first specified or derived IP address string. */ if (host == NULL) { host = ns_strdup(Tcl_GetString(objv[0])); } if (noHostNameGiven && host != NULL && path != NULL) { Ns_SetUpdate(set, "hostname", host); } Tcl_DecrRefCount(bindaddrsObj); /* * Get configured number of driver threads. */ nrDrivers = Ns_ConfigIntRange(path, "driverthreads", 1, 1, 64); if (nrDrivers > 1) { #if !defined(SO_REUSEPORT) Ns_Log(Warning, "server %s module %s requests %d driverthreads, but is not supported by the operating system", server, module, nrDrivers); Ns_SetUpdate(set, "driverthreads", "1"); nrDrivers = 1; #endif } /* * The common parameters are determined, create the driver thread(s) */ { size_t maxModuleNameLength = strlen(module) + (size_t)TCL_INTEGER_SPACE + 1u; char *moduleName = ns_malloc(maxModuleNameLength); int i; if (host == NULL) { host = Ns_InfoHostname(); } for (i = 0; i < nrDrivers; i++) { snprintf(moduleName, maxModuleNameLength, "%s:%d", module, i); status = DriverInit(server, module, moduleName, init, servPtr, path, address, defserver, host); if (status != NS_OK) { break; } } ns_free(moduleName); } } return status; } /* *---------------------------------------------------------------------- * * ServerMapEntryAdd -- * * Add an entry to the virtual server map. The entry consists of the * value as provided by the host header field and location string, * containing as well the protocol. * * Results: * None * * Side effects: * Potentially adding an entry to the virtual server map. * *---------------------------------------------------------------------- */ static void ServerMapEntryAdd(Tcl_DString *dsPtr, const char *host, NsServer *servPtr, Driver *drvPtr, bool addDefaultMapEntry) { Tcl_HashEntry *hPtr; int isNew; NS_NONNULL_ASSERT(dsPtr != NULL); NS_NONNULL_ASSERT(host != NULL); NS_NONNULL_ASSERT(servPtr != NULL); NS_NONNULL_ASSERT(drvPtr != NULL); hPtr = Tcl_CreateHashEntry(&drvPtr->hosts, host, &isNew); if (isNew != 0) { ServerMap *mapPtr; (void) Ns_DStringVarAppend(dsPtr, drvPtr->protocol, "://", host, (char *)0L); mapPtr = ns_malloc(sizeof(ServerMap) + (size_t)dsPtr->length); mapPtr->servPtr = servPtr; memcpy(mapPtr->location, dsPtr->string, (size_t)dsPtr->length + 1u); Tcl_SetHashValue(hPtr, mapPtr); Ns_Log(Notice, "%s: adding virtual host entry for host <%s> location: %s mapped to server: %s", drvPtr->threadName, host, mapPtr->location, servPtr->server); if (addDefaultMapEntry) { drvPtr->defMapPtr = mapPtr; } /* * Always reset the Tcl_DString */ Ns_DStringSetLength(dsPtr, 0); } else { Ns_Log(Notice, "%s: ignore duplicate virtual host entry: %s", drvPtr->threadName, host); } } /* *---------------------------------------------------------------------- * * NsDriverMapVirtualServers -- * * Map "Host:" headers for drivers not bound to physical servers. This * function has to be called a time, when all servers are already defined * such that NsGetServer(server) can succeed. * * Results: * None. * * Side effects: * Add an entry to the virtual server map via ServerMapEntryAdd() * *---------------------------------------------------------------------- */ void NsDriverMapVirtualServers(void) { Driver *drvPtr; for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) { const Ns_Set *lset; size_t j; Tcl_DString ds, *dsPtr = &ds; const char *path, *defserver, *moduleName; moduleName = drvPtr->moduleName; defserver = drvPtr->defserver; /* * Check for a "/servers" section for this driver module. */ path = Ns_ConfigGetPath(NULL, moduleName, "servers", (char *)0L); lset = Ns_ConfigGetSection(path); if (lset == NULL || Ns_SetSize(lset) == 0u) { /* * The driver module has no (or empty) ".../servers" section. * There is no mapping from host name to virtual server defined. */ if (drvPtr->server == NULL) { /* * We have a global driver module. If there is at least a * default server configured, we can use this for the mapping * to the default server. */ if (defserver != NULL) { NsServer *servPtr = NsGetServer(defserver); Tcl_DStringInit(dsPtr); ServerMapEntryAdd(dsPtr, Ns_InfoHostname(), servPtr, drvPtr, NS_TRUE); Tcl_DStringFree(dsPtr); Ns_Log(Notice, "Global driver has no mapping from host to server (section '%s' missing)", moduleName); } else { /* * Global driver, which has no default server, and no servers section. */ Ns_Fatal("%s: virtual servers configured," " but '%s' has no defaultserver defined", moduleName, path); } } continue; } /* * We have a ".../servers" section, the driver might be global or * local. It is not clear, why we need the server map for the local * driver, but for compatibility, we keep this. * */ if (defserver == NULL) { if (drvPtr->server != NULL) { /* * We have a local (server specific) driver. Since the code * below assumes that we have a "defserver" set, we take the * actual server as defserver. */ defserver = drvPtr->server; } else { /* * We have a global driver, but no defserver. */ Ns_Fatal("%s: virtual servers configured," " but '%s' has no defaultserver defined", moduleName, path); } } assert(defserver != NULL); drvPtr->defMapPtr = NULL; Ns_DStringInit(dsPtr); for (j = 0u; j < Ns_SetSize(lset); ++j) { const char *server = Ns_SetKey(lset, j); const char *host = Ns_SetValue(lset, j); NsServer *servPtr; /* * Perform an explicit lookup of the server. */ servPtr = NsGetServer(server); if (servPtr == NULL) { Ns_Log(Error, "%s: no such server: %s", moduleName, server); } else { char *writableHost, *hostName, *portStart; writableHost = ns_strdup(host); Ns_HttpParseHost(writableHost, &hostName, &portStart); if (portStart == NULL) { Tcl_DString hostDString; /* * The provided host entry does NOT contain a port. * * Add the provided entry to the virtual server map only, * when the configured port is the default port for the * protocol. */ if (drvPtr->port == drvPtr->defport) { ServerMapEntryAdd(dsPtr, host, servPtr, drvPtr, STREQ(defserver, server)); } /* * Auto-add configured port: Add always an entry with the * explicitly configured port of the driver. */ Tcl_DStringInit(&hostDString); Tcl_DStringAppend(&hostDString, host, -1); (void) Ns_DStringPrintf(&hostDString, ":%hu", drvPtr->port); ServerMapEntryAdd(dsPtr, hostDString.string, servPtr, drvPtr, STREQ(defserver, server)); Tcl_DStringFree(&hostDString); } else { /* * The provided host entry does contain a port. * * In case, the provided port is equal to the configured port * of the driver, add an entry. */ unsigned short providedPort = (unsigned short)strtol(portStart+1, NULL, 10); if (providedPort == drvPtr->port) { ServerMapEntryAdd(dsPtr, host, servPtr, drvPtr, STREQ(defserver, server)); /* * In case, the provided port is equal to the default * port of the driver, make sure that we have an entry * without the port. */ if (providedPort == drvPtr->defport) { ServerMapEntryAdd(dsPtr, hostName, servPtr, drvPtr, STREQ(defserver, server)); } } else { Ns_Log(Warning, "%s: driver is listening on port %hu; " "virtual host entry %s ignored", moduleName, drvPtr->port, host); } } ns_free(writableHost); } } Ns_DStringFree(dsPtr); if (drvPtr->defMapPtr == NULL) { fprintf(stderr, "--- Server Map: ---\n"); Ns_SetPrint(lset); Ns_Fatal("%s: default server '%s' not defined in '%s'", moduleName, defserver, path); } } } /* *---------------------------------------------------------------------- * * DriverInit -- * * Helper function of Ns_DriverInit. This function actually allocates and * initialized the driver structure. * * Results: * NS_OK if initialized, NS_ERROR if config or other error. * * Side effects: * Listen socket will be opened later in NsStartDrivers. * *---------------------------------------------------------------------- */ static Ns_ReturnCode DriverInit(const char *server, const char *moduleName, const char *threadName, const Ns_DriverInitData *init, NsServer *servPtr, const char *path, const char *bindaddrs, const char *defserver, const char *host) { const char *defproto; Driver *drvPtr; DrvWriter *wrPtr; DrvSpooler *spPtr; int i; unsigned short defport; NS_NONNULL_ASSERT(threadName != NULL); NS_NONNULL_ASSERT(init != NULL); NS_NONNULL_ASSERT(path != NULL); NS_NONNULL_ASSERT(bindaddrs != NULL); NS_NONNULL_ASSERT(host != NULL); /* * Set the protocol and port defaults. */ if (init->protocol != NULL) { defproto = init->protocol; defport = init->defaultPort; } else { defproto = "unknown"; defport = 0u; } Ns_Log(DriverDebug, "DriverInit server <%s> threadName %s proto %s port %hu", server, threadName, defproto, defport); /* * Allocate a new driver instance and set configurable parameters. */ drvPtr = ns_calloc(1u, sizeof(Driver)); Ns_MutexInit(&drvPtr->lock); Ns_MutexSetName2(&drvPtr->lock, "ns:drv", threadName); Ns_MutexInit(&drvPtr->spooler.lock); Ns_MutexSetName2(&drvPtr->spooler.lock, "ns:drv:spool", threadName); Ns_MutexInit(&drvPtr->writer.lock); Ns_MutexSetName2(&drvPtr->writer.lock, "ns:drv:writer", threadName); if (ns_sockpair(drvPtr->trigger) != 0) { Ns_Fatal("ns_sockpair() failed: %s", ns_sockstrerror(ns_sockerrno)); } drvPtr->server = server; drvPtr->type = init->name; drvPtr->moduleName = ns_strdup(moduleName); drvPtr->threadName = ns_strdup(threadName); drvPtr->defserver = defserver; drvPtr->listenProc = init->listenProc; drvPtr->acceptProc = init->acceptProc; drvPtr->recvProc = init->recvProc; drvPtr->sendProc = init->sendProc; drvPtr->sendFileProc = init->sendFileProc; drvPtr->keepProc = init->keepProc; drvPtr->requestProc = init->requestProc; drvPtr->closeProc = init->closeProc; drvPtr->clientInitProc = init->clientInitProc; drvPtr->arg = init->arg; drvPtr->opts = init->opts; drvPtr->servPtr = servPtr; drvPtr->defport = defport; drvPtr->bufsize = (size_t)Ns_ConfigMemUnitRange(path, "bufsize", 16384, 1024, INT_MAX); drvPtr->maxinput = Ns_ConfigMemUnitRange(path, "maxinput", 1024*1024, 1024, LLONG_MAX); drvPtr->maxupload = Ns_ConfigMemUnitRange(path, "maxupload", 0, 0, (Tcl_WideInt)drvPtr->maxinput); drvPtr->readahead = Ns_ConfigMemUnitRange(path, "readahead", (Tcl_WideInt)drvPtr->bufsize, (Tcl_WideInt)drvPtr->bufsize, drvPtr->maxinput); drvPtr->maxline = Ns_ConfigIntRange(path, "maxline", 8192, 256, INT_MAX); drvPtr->maxheaders = Ns_ConfigIntRange(path, "maxheaders", 128, 8, INT_MAX); drvPtr->maxqueuesize = Ns_ConfigIntRange(path, "maxqueuesize", 1024, 1, INT_MAX); Ns_ConfigTimeUnitRange(path, "sendwait", "30s", 1, 0, INT_MAX, 0, &drvPtr->sendwait); Ns_ConfigTimeUnitRange(path, "recvwait", "30s", 1, 0, INT_MAX, 0, &drvPtr->recvwait); Ns_ConfigTimeUnitRange(path, "closewait", "2s", 0, 0, INT_MAX, 0, &drvPtr->closewait); Ns_ConfigTimeUnitRange(path, "keepwait", "5s", 0, 0, INT_MAX, 0, &drvPtr->keepwait); drvPtr->backlog = Ns_ConfigIntRange(path, "backlog", 256, 1, INT_MAX); drvPtr->driverthreads = Ns_ConfigIntRange(path, "driverthreads", 1, 1, 32); drvPtr->reuseport = Ns_ConfigBool(path, "reuseport", NS_FALSE); drvPtr->acceptsize = Ns_ConfigIntRange(path, "acceptsize", drvPtr->backlog, 1, INT_MAX); drvPtr->keepmaxuploadsize = (size_t)Ns_ConfigMemUnitRange(path, "keepalivemaxuploadsize", 0, 0, INT_MAX); drvPtr->keepmaxdownloadsize = (size_t)Ns_ConfigMemUnitRange(path, "keepalivemaxdownloadsize", 0, 0, INT_MAX); drvPtr->recvTimeout = drvPtr->recvwait; Tcl_InitHashTable(&drvPtr->hosts, TCL_STRING_KEYS); if (drvPtr->driverthreads > 1) { #if !defined(SO_REUSEPORT) drvPtr->driverthreads = 1; drvPtr->reuseport = NS_FALSE; #else /* * When driver threads > 1, "reuseport" has to be active. */ drvPtr->reuseport = NS_TRUE; #endif } if (drvPtr->reuseport) { /* * Reuseport was specified */ #if !defined(SO_REUSEPORT) Ns_Log(Warning, "parameter %s reuseport was specified, but is not supported by the operating system", path); drvPtr->reuseport = NS_FALSE; #endif } drvPtr->uploadpath = ns_strdup(Ns_ConfigString(path, "uploadpath", nsconf.tmpDir)); /* * If activated, "maxupload" has to be at least "readahead" bytes. Tell * the user in case the config values are overruled. */ if ((drvPtr->maxupload > 0) && (drvPtr->maxupload < drvPtr->readahead)) { Ns_Log(Warning, "parameter %s maxupload % " TCL_LL_MODIFIER "d invalid; can be either 0 or must be >= %" TCL_LL_MODIFIER "d (size of readahead)", path, drvPtr->maxupload, drvPtr->readahead); drvPtr->maxupload = drvPtr->readahead; } /* * Determine the port and then set the HTTP location string either * as specified in the config file or constructed from the * protocol, hostname and port. */ drvPtr->protocol = ns_strdup(defproto); drvPtr->address = ns_strdup(bindaddrs); drvPtr->port = (unsigned short)Ns_ConfigIntRange(path, "port", (int)defport, 0, 65535); drvPtr->location = Ns_ConfigGetValue(path, "location"); if (drvPtr->location != NULL && (strstr(drvPtr->location, "://") != NULL)) { drvPtr->location = ns_strdup(drvPtr->location); } else { Tcl_DString ds, *dsPtr = &ds; Ns_DStringInit(dsPtr); Ns_HttpLocationString(dsPtr, drvPtr->protocol, host, drvPtr->port, defport); drvPtr->location = Ns_DStringExport(dsPtr); } drvPtr->nextPtr = firstDrvPtr; firstDrvPtr = drvPtr; /* * Add driver specific extra headers. */ drvPtr->extraHeaders = Ns_ConfigSet(path, "extraheaders"); /* * Check if upload spooler are enabled */ spPtr = &drvPtr->spooler; spPtr->threads = Ns_ConfigIntRange(path, "spoolerthreads", 0, 0, 32); if (spPtr->threads > 0) { Ns_Log(Notice, "%s: enable %d spooler thread(s) " "for uploads >= %" TCL_LL_MODIFIER "d bytes", threadName, spPtr->threads, drvPtr->readahead); for (i = 0; i < spPtr->threads; i++) { SpoolerQueue *queuePtr = ns_calloc(1u, sizeof(SpoolerQueue)); char buffer[100]; snprintf(buffer, sizeof(buffer), "ns:driver:spooler:%d", i); Ns_MutexSetName2(&queuePtr->lock, buffer, "queue"); queuePtr->id = i; Push(queuePtr, spPtr->firstPtr); } } else { Ns_Log(Notice, "%s: enable %d spooler thread(s) ", threadName, spPtr->threads); } /* * Enable writer threads */ wrPtr = &drvPtr->writer; wrPtr->threads = Ns_ConfigIntRange(path, "writerthreads", 0, 0, 32); if (wrPtr->threads > 0) { wrPtr->writersize = (size_t)Ns_ConfigMemUnitRange(path, "writersize", 1024*1024, 1024, INT_MAX); wrPtr->bufsize = (size_t)Ns_ConfigMemUnitRange(path, "writerbufsize", 8192, 512, INT_MAX); wrPtr->rateLimit = Ns_ConfigIntRange(path, "writerratelimit", 0, 0, INT_MAX); wrPtr->doStream = Ns_ConfigBool(path, "writerstreaming", NS_FALSE) ? NS_WRITER_STREAM_ACTIVE : NS_WRITER_STREAM_NONE; Ns_Log(Notice, "%s: enable %d writer thread(s) " "for downloads >= %" PRIdz " bytes, bufsize=%" PRIdz " bytes, HTML streaming %d", threadName, wrPtr->threads, wrPtr->writersize, wrPtr->bufsize, wrPtr->doStream); for (i = 0; i < wrPtr->threads; i++) { SpoolerQueue *queuePtr = ns_calloc(1u, sizeof(SpoolerQueue)); char buffer[100]; snprintf(buffer, sizeof(buffer), "ns:driver:writer:%d", i); Ns_MutexSetName2(&queuePtr->lock, buffer, "queue"); queuePtr->id = i; Push(queuePtr, wrPtr->firstPtr); } } else { Ns_Log(Notice, "%s: enable %d writer thread(s) ", threadName, wrPtr->threads); } return NS_OK; } /* *---------------------------------------------------------------------- * * NsStartDrivers -- * * Listen on all driver address/ports and start the DriverThread. * * Results: * None. * * Side effects: * See DriverThread. * *---------------------------------------------------------------------- */ void NsStartDrivers(void) { Driver *drvPtr; /* * Signal and wait for each driver to start. */ for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) { if (drvPtr->port == 0u) { /* * Don't start a driver having port zero. */ continue; } Ns_ThreadCreate(DriverThread, drvPtr, 0, &drvPtr->thread); Ns_MutexLock(&drvPtr->lock); while ((drvPtr->flags & DRIVER_STARTED) == 0u) { Ns_CondWait(&drvPtr->cond, &drvPtr->lock); } /*if ((drvPtr->flags & DRIVER_FAILED)) { status = NS_ERROR; }*/ Ns_MutexUnlock(&drvPtr->lock); } } /* *---------------------------------------------------------------------- * * NsStopDrivers -- * * Trigger the DriverThread to begin shutdown. * * Results: * None. * * Side effects: * DriverThread will close listen sockets and then exit after all * outstanding connections are complete and closed. * *---------------------------------------------------------------------- */ void NsStopDrivers(void) { Driver *drvPtr; NsAsyncWriterQueueDisable(NS_TRUE); for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) { Tcl_HashEntry *hPtr; Tcl_HashSearch search; if ((drvPtr->flags & DRIVER_STARTED) == 0u) { continue; } Ns_MutexLock(&drvPtr->lock); Ns_Log(Notice, "[driver:%s]: stopping", drvPtr->threadName); drvPtr->flags |= DRIVER_SHUTDOWN; Ns_CondBroadcast(&drvPtr->cond); Ns_MutexUnlock(&drvPtr->lock); SockTrigger(drvPtr->trigger[1]); hPtr = Tcl_FirstHashEntry(&drvPtr->hosts, &search); while (hPtr != NULL) { Tcl_DeleteHashEntry(hPtr); hPtr = Tcl_NextHashEntry(&search); } } } void NsStopSpoolers(void) { const Driver *drvPtr; Ns_Log(Notice, "driver: stopping writer and spooler threads"); /* * Shutdown all spooler and writer threads */ for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) { Ns_Time timeout; if ((drvPtr->flags & DRIVER_STARTED) == 0u) { continue; } Ns_GetTime(&timeout); Ns_IncrTime(&timeout, nsconf.shutdowntimeout.sec, nsconf.shutdowntimeout.usec); SpoolerQueueStop(drvPtr->writer.firstPtr, &timeout, "writer"); SpoolerQueueStop(drvPtr->spooler.firstPtr, &timeout, "spooler"); } } /* *---------------------------------------------------------------------- * * DriverInfoObjCmd -- * * Return public info of all drivers. * Subcommand of NsTclDriverObjCmd. * * Results: * Standard Tcl Result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int DriverInfoObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { int result = TCL_OK; if (Ns_ParseObjv(NULL, NULL, interp, 2, objc, objv) != NS_OK) { result = TCL_ERROR; } else { const Driver *drvPtr; Tcl_Obj *resultObj = Tcl_NewListObj(0, NULL); Tcl_HashTable driverNames; /* names of the driver modules without duplicates */ Tcl_InitHashTable(&driverNames, TCL_STRING_KEYS); /* * Iterate over all modules, not necessarily all driver threads */ for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) { int isNew = 0; (void)Tcl_CreateHashEntry(&driverNames, drvPtr->moduleName, &isNew); if (isNew == 1) { Tcl_Obj *listObj = Tcl_NewListObj(0, NULL); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("module", 6)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj(drvPtr->moduleName, -1)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("type", 4)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj(drvPtr->type, -1)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("server", 6)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj(drvPtr->server != NULL ? drvPtr->server : NS_EMPTY_STRING, -1)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("location", 8)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj(drvPtr->location, -1)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("address", 7)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj(drvPtr->address, -1)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("protocol", 8)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj(drvPtr->protocol, -1)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("sendwait", 8)); Tcl_ListObjAppendElement(interp, listObj, Ns_TclNewTimeObj(&drvPtr->sendwait)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("recvwait", 8)); Tcl_ListObjAppendElement(interp, listObj, Ns_TclNewTimeObj(&drvPtr->sendwait)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("extraheaders", 12)); if (drvPtr->extraHeaders != NULL) { Tcl_DString ds; Tcl_DStringInit(&ds); Ns_DStringAppendSet(&ds, drvPtr->extraHeaders); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj(ds.string, ds.length)); Tcl_DStringFree(&ds); } else { Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("", 0)); } Tcl_ListObjAppendElement(interp, resultObj, listObj); } } Tcl_SetObjResult(interp, resultObj); Tcl_DeleteHashTable(&driverNames); } return result; } /* *---------------------------------------------------------------------- * * DriverStatsObjCmd -- * * Return statistics of all drivers. * Subcommand of NsTclDriverObjCmd. * * Results: * Standard Tcl Result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int DriverStatsObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { int result = TCL_OK; if (Ns_ParseObjv(NULL, NULL, interp, 2, objc, objv) != NS_OK) { result = TCL_ERROR; } else { const Driver *drvPtr; Tcl_Obj *resultObj = Tcl_NewListObj(0, NULL); /* * Iterate over all drivers and collect results. */ for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) { Tcl_Obj *listObj = Tcl_NewListObj(0, NULL); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("thread", 6)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj(drvPtr->threadName, -1)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("module", 6)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj(drvPtr->moduleName, -1)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("received", 8)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewWideIntObj(drvPtr->stats.received)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("spooled", 7)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewWideIntObj(drvPtr->stats.spooled)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("partial", 7)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewWideIntObj(drvPtr->stats.partial)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("errors", 6)); Tcl_ListObjAppendElement(interp, listObj, Tcl_NewWideIntObj(drvPtr->stats.errors)); Tcl_ListObjAppendElement(interp, resultObj, listObj); } Tcl_SetObjResult(interp, resultObj); } return result; } /* *---------------------------------------------------------------------- * * DriverThreadsObjCmd -- * * Return the names of driver threads * * Results: * Standard Tcl Result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int DriverThreadsObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { int result = TCL_OK; if (Ns_ParseObjv(NULL, NULL, interp, 2, objc, objv) != NS_OK) { result = TCL_ERROR; } else { const Driver *drvPtr; Tcl_Obj *resultObj = Tcl_NewListObj(0, NULL); /* * Iterate over all drivers and collect results. */ for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) { Tcl_ListObjAppendElement(interp, resultObj, Tcl_NewStringObj(drvPtr->threadName, -1)); } Tcl_SetObjResult(interp, resultObj); } return result; } /* *---------------------------------------------------------------------- * * DriverNamesObjCmd -- * * Return the names of drivers. * * Results: * Standard Tcl Result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int DriverNamesObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { int result = TCL_OK; if (Ns_ParseObjv(NULL, NULL, interp, 2, objc, objv) != NS_OK) { result = TCL_ERROR; } else { const Driver *drvPtr; Tcl_Obj *resultObj = Tcl_NewListObj(0, NULL); Tcl_HashTable driverNames; /* names of the drivers without duplicates */ Tcl_InitHashTable(&driverNames, TCL_STRING_KEYS); /* * Iterate over all drivers and collect results. */ for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) { int isNew; (void)Tcl_CreateHashEntry(&driverNames, drvPtr->moduleName, &isNew); if (isNew == 1) { Tcl_ListObjAppendElement(interp, resultObj, Tcl_NewStringObj(drvPtr->moduleName, -1)); } } Tcl_SetObjResult(interp, resultObj); Tcl_DeleteHashTable(&driverNames); } return result; } /* *---------------------------------------------------------------------- * * NsTclDriverObjCmd - * * Give information about drivers. Currently, just the statistics. * * Results: * Standard Tcl result. * * Side effects: * None. * *---------------------------------------------------------------------- */ int NsTclDriverObjCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { const Ns_SubCmdSpec subcmds[] = { {"info", DriverInfoObjCmd}, {"names", DriverNamesObjCmd}, {"threads", DriverThreadsObjCmd}, {"stats", DriverStatsObjCmd}, {NULL, NULL} }; return Ns_SubcmdObjv(subcmds, clientData, interp, objc, objv); } /* *---------------------------------------------------------------------- * * NsWakeupDriver -- * * Wake up the associated DriverThread. * * Results: * None. * * Side effects: * The poll waiting for this trigger will be interrupted. * *---------------------------------------------------------------------- */ void NsWakeupDriver(const Driver *drvPtr) { NS_NONNULL_ASSERT(drvPtr != NULL); SockTrigger(drvPtr->trigger[1]); } /* *---------------------------------------------------------------------- * * NsWaitDriversShutdown -- * * Wait for exit of DriverThread. This callback is invoked later * by the timed shutdown thread. * * Results: * None. * * Side effects: * Driver thread is joined and trigger pipe closed. * *---------------------------------------------------------------------- */ void NsWaitDriversShutdown(const Ns_Time *toPtr) { Driver *drvPtr; Ns_ReturnCode status = NS_OK; for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) { if ((drvPtr->flags & DRIVER_STARTED) == 0u) { continue; } Ns_MutexLock(&drvPtr->lock); while ((drvPtr->flags & DRIVER_STOPPED) == 0u && status == NS_OK) { status = Ns_CondTimedWait(&drvPtr->cond, &drvPtr->lock, toPtr); } Ns_MutexUnlock(&drvPtr->lock); if (status != NS_OK) { Ns_Log(Warning, "[driver:%s]: shutdown timeout", drvPtr->threadName); } else { Ns_Log(Notice, "[driver:%s]: stopped", drvPtr->threadName); Ns_ThreadJoin(&drvPtr->thread, NULL); drvPtr->thread = NULL; } } } /* *---------------------------------------------------------------------- * * NsGetRequest -- * * Return the request buffer, reading it if necessary (i.e., if not an * async read-ahead connection). This function is called at the start of * connection processing. * Results: * Pointer to Request structure or NULL on error. * * Side effects: * May wait for content to arrive if necessary. * *---------------------------------------------------------------------- */ Request * NsGetRequest(Sock *sockPtr, const Ns_Time *nowPtr) { Request *reqPtr; NS_NONNULL_ASSERT(sockPtr != NULL); /* * The underlying "Request" structure is allocated by RequestNew(), which * must be called for the "sockPtr" prior to calling this * function. "reqPtr" should be NULL just in error cases. */ reqPtr = sockPtr->reqPtr; if (likely(reqPtr != NULL)) { if (likely(reqPtr->request.line != NULL)) { Ns_Log(DriverDebug, "NsGetRequest got the pre-parsed request <%s> from the driver", reqPtr->request.line); } else if (sockPtr->drvPtr->requestProc == NULL) { /* * Non-HTTP driver can send the drvPtr->requestProc to perform * their own request handling. */ SockState status; Ns_Log(DriverDebug, "NsGetRequest has to read+parse the request"); /* * We have no parsed request so far. So, do it now. */ do { Ns_Log(DriverDebug, "NsGetRequest calls SockRead"); status = SockRead(sockPtr, 0, nowPtr); } while (status == SOCK_MORE); /* * If anything went wrong, clean the request provided by * SockRead() and flag the error by returning NULL. */ if (status != SOCK_READY) { if (sockPtr->reqPtr != NULL) { Ns_Log(DriverDebug, "NsGetRequest calls RequestFree"); RequestFree(sockPtr); } reqPtr = NULL; } } else { Ns_Log(DriverDebug, "NsGetRequest found driver specific request Proc, " "probably from a non-HTTP driver"); } } else { Ns_Log(DriverDebug, "NsGetRequest has reqPtr NULL"); } return reqPtr; } /* *---------------------------------------------------------------------- * * NsSockClose -- * * Return a connection to the DriverThread for closing or keepalive. * "keep" might be NS_TRUE/NS_FALSE or -1 if undecided. * * Results: * None. * * Side effects: * Socket may be reused by a keepalive connection. * *---------------------------------------------------------------------- */ void NsSockClose(Sock *sockPtr, int keep) { Driver *drvPtr; bool trigger = NS_FALSE; NS_NONNULL_ASSERT(sockPtr != NULL); drvPtr = sockPtr->drvPtr; Ns_Log(DriverDebug, "NsSockClose sockPtr %p (%d) keep %d", (void *)sockPtr, ((Ns_Sock*)sockPtr)->sock, keep); SockClose(sockPtr, keep); /* * Free the request, unless it is from a non-HTTP driver (who might not * fill out the request structure). */ if (sockPtr->reqPtr != NULL) { Ns_Log(DriverDebug, "NsSockClose calls RequestFree"); RequestFree(sockPtr); } Ns_MutexLock(&drvPtr->lock); if (drvPtr->closePtr == NULL) { trigger = NS_TRUE; } sockPtr->nextPtr = drvPtr->closePtr; drvPtr->closePtr = sockPtr; Ns_MutexUnlock(&drvPtr->lock); if (trigger) { SockTrigger(drvPtr->trigger[1]); } } /* *---------------------------------------------------------------------- * * DriverListen -- * * Open a listening socket for accepting connections. * * Results: * File description of socket, or NS_INVALID_SOCKET on error. * * Side effects: * Depends on driver. * *---------------------------------------------------------------------- */ static NS_SOCKET DriverListen(Driver *drvPtr, const char *bindaddr) { NS_SOCKET sock; NS_NONNULL_ASSERT(drvPtr != NULL); NS_NONNULL_ASSERT(bindaddr != NULL); sock = (*drvPtr->listenProc)((Ns_Driver *) drvPtr, bindaddr, drvPtr->port, drvPtr->backlog, drvPtr->reuseport); if (sock == NS_INVALID_SOCKET) { Ns_Log(Error, "%s: failed to listen on [%s]:%d: %s", drvPtr->threadName, bindaddr, drvPtr->port, ns_sockstrerror(ns_sockerrno)); } else { Ns_Log(Notice, #ifdef HAVE_IPV6 "%s: listening on [%s]:%d", #else "%s: listening on %s:%d", #endif drvPtr->threadName, bindaddr, drvPtr->port); } return sock; } /* *---------------------------------------------------------------------- * * DriverAccept -- * * Accept a new socket. It will be in non-blocking mode. * * Results: * _ACCEPT: a socket was accepted, poll for data * _ACCEPT_DATA: a socket was accepted, data present, read immediately * if in async mode, defer reading to connection thread * _ACCEPT_QUEUE: a socket was accepted, queue immediately * _ACCEPT_ERROR: no socket was accepted * * Side effects: * Depends on driver. * *---------------------------------------------------------------------- */ static NS_DRIVER_ACCEPT_STATUS DriverAccept(Sock *sockPtr, NS_SOCKET sock) { socklen_t n = (socklen_t)sizeof(struct NS_SOCKADDR_STORAGE); NS_NONNULL_ASSERT(sockPtr != NULL); return (*sockPtr->drvPtr->acceptProc)((Ns_Sock *) sockPtr, sock, (struct sockaddr *) &(sockPtr->sa), &n); } /* *---------------------------------------------------------------------- * * NsDriverRecv -- * * Read data from the socket into the given vector of buffers. * * Results: * Number of bytes read, or -1 on error. * * Side effects: * Depends on driver. * *---------------------------------------------------------------------- */ ssize_t NsDriverRecv(Sock *sockPtr, struct iovec *bufs, int nbufs, Ns_Time *timeoutPtr) { ssize_t result; const Driver *drvPtr; NS_NONNULL_ASSERT(sockPtr != NULL); drvPtr = sockPtr->drvPtr; if (likely(drvPtr->recvProc != NULL)) { result = (*drvPtr->recvProc)((Ns_Sock *) sockPtr, bufs, nbufs, timeoutPtr, 0u); } else { Ns_Log(Warning, "driver: no recvProc registered for driver %s", drvPtr->threadName); result = -1; } return result; } /* *---------------------------------------------------------------------- * * NsDriverSend -- * * Write a vector of buffers to the socket via the driver callback. * May not send all of the data. * * Results: * Number of bytes written or -1 on error. * May return 0 (zero) when socket is not writable. * * Side effects: * Depends on the driver. * *---------------------------------------------------------------------- */ ssize_t NsDriverSend(Sock *sockPtr, const struct iovec *bufs, int nbufs, unsigned int flags) { ssize_t sent = -1; const Driver *drvPtr; NS_NONNULL_ASSERT(sockPtr != NULL); drvPtr = sockPtr->drvPtr; NS_NONNULL_ASSERT(drvPtr != NULL); if (likely(drvPtr->sendProc != NULL)) { /* * TODO: The Ns_DriverSendProc signature should be modified * to omit the timeout argument. Same with recvProc(). */ sent = (*drvPtr->sendProc)((Ns_Sock *) sockPtr, bufs, nbufs, NULL, flags); } else { Ns_Log(Warning, "no sendProc registered for driver %s", drvPtr->threadName); } return sent; } /* *---------------------------------------------------------------------- * * NsDriverSendFile -- * * Write a vector of file buffers to the socket via the driver * callback. * * Results: * Number of bytes written, -1 on error. * May not send all the data. * * Side effects: * May block on disk read. * *---------------------------------------------------------------------- */ ssize_t NsDriverSendFile(Sock *sockPtr, Ns_FileVec *bufs, int nbufs, unsigned int flags) { ssize_t sent = -1; const Driver *drvPtr; NS_NONNULL_ASSERT(sockPtr != NULL); NS_NONNULL_ASSERT(bufs != NULL); drvPtr = sockPtr->drvPtr; NS_NONNULL_ASSERT(drvPtr != NULL); if (drvPtr->sendFileProc != NULL) { /* * TODO: The Ns_DriverSendFileProc signature should be modified * to omit the timeout argument. */ sent = (*drvPtr->sendFileProc)((Ns_Sock *)sockPtr, bufs, nbufs, NULL, flags); } else { sent = Ns_SockSendFileBufs((Ns_Sock *)sockPtr, bufs, nbufs, flags); } return sent; } /* *---------------------------------------------------------------------- * * DriverKeep -- * * Can the given socket be kept open in the hopes that another * request will arrive before the keepwait timeout expires? * * Results: * NS_TRUE if the socket is OK for keepalive, NS_FALSE if this is not possible. * * Side effects: * Depends on driver. * *---------------------------------------------------------------------- */ static bool DriverKeep(Sock *sockPtr) { Ns_DriverKeepProc *keepProc; bool result; NS_NONNULL_ASSERT(sockPtr != NULL); keepProc = sockPtr->drvPtr->keepProc; if (keepProc == NULL) { result = NS_FALSE; } else { result = (keepProc)((Ns_Sock *) sockPtr); } return result; } /* *---------------------------------------------------------------------- * * DriverClose -- * * Close the given socket. * * Results: * None. * * Side effects: * Depends on driver. * *---------------------------------------------------------------------- */ static void DriverClose(Sock *sockPtr) { NS_NONNULL_ASSERT(sockPtr != NULL); (*sockPtr->drvPtr->closeProc)((Ns_Sock *) sockPtr); } /* *---------------------------------------------------------------------- * * DriverThread -- * * Main listening socket driver thread. * * Results: * None. * * Side effects: * Connections are accepted on the configured listen sockets, * placed on the run queue to be serviced, and gracefully * closed when done. Async sockets have the entire request read * here before queuing as well. * *---------------------------------------------------------------------- */ static void DriverThread(void *arg) { Driver *drvPtr = (Driver*)arg; Ns_Time now, diff; char charBuffer[1], drain[1024]; int pollTimeout, accepted, nrBindaddrs = 0; bool stopping; unsigned int flags; Sock *sockPtr, *closePtr, *nextPtr, *waitPtr, *readPtr; PollData pdata; Ns_ThreadSetName("-driver:%s-", drvPtr->threadName); Ns_Log(Notice, "starting"); flags = DRIVER_STARTED; { Tcl_Obj *bindaddrsObj, **objv; int j = 0, result; bindaddrsObj = Tcl_NewStringObj(drvPtr->address, -1); Tcl_IncrRefCount(bindaddrsObj); result = Tcl_ListObjGetElements(NULL, bindaddrsObj, &nrBindaddrs, &objv); /* * "result" was ok during startup, it has still to be ok. */ assert(result == TCL_OK); if (result == TCL_OK) { int i; /* * Bind all provided addresses. */ for (i = 0; i < nrBindaddrs; i++) { drvPtr->listenfd[j] = DriverListen(drvPtr, Tcl_GetString(objv[i])); if (drvPtr->listenfd[j] != NS_INVALID_SOCKET) { j ++; } } if (j > 0 && j < nrBindaddrs) { Ns_Log(Warning, "could only bind to %d out of %d addresses", j, nrBindaddrs); } } /* * "j" refers to the number of successful listen() operations. */ nrBindaddrs = j; Tcl_DecrRefCount(bindaddrsObj); } if (nrBindaddrs > 0) { SpoolerQueueStart(drvPtr->spooler.firstPtr, SpoolerThread); SpoolerQueueStart(drvPtr->writer.firstPtr, WriterThread); } else { Ns_Log(Warning, "could no bind any of the following addresses, stopping this driver: %s", drvPtr->address); flags |= (DRIVER_FAILED | DRIVER_SHUTDOWN); } Ns_MutexLock(&drvPtr->lock); drvPtr->flags |= flags; Ns_CondBroadcast(&drvPtr->cond); Ns_MutexUnlock(&drvPtr->lock); /* * Loop forever until signaled to shut down and all * connections are complete and gracefully closed. */ PollCreate(&pdata); Ns_GetTime(&now); closePtr = waitPtr = readPtr = NULL; stopping = ((flags & DRIVER_SHUTDOWN) != 0u); if (!stopping) { Ns_Log(Notice, "driver: accepting connections"); } while (!stopping) { int n; /* * Set the bits for all active drivers if a connection * isn't already pending. */ PollReset(&pdata); (void)PollSet(&pdata, drvPtr->trigger[0], (short)POLLIN, NULL); if (likely(waitPtr == NULL)) { for (n = 0; n < nrBindaddrs; n++) { drvPtr->pidx[n] = PollSet(&pdata, drvPtr->listenfd[n], (short)POLLIN, NULL); } } /* * If there are any closing or read-ahead sockets, set the bits * and determine the minimum relative timeout. * * TODO: the various poll timeouts should probably be configurable. */ if (readPtr == NULL && closePtr == NULL) { pollTimeout = 10 * 1000; } else { for (sockPtr = readPtr; sockPtr != NULL; sockPtr = sockPtr->nextPtr) { SockPoll(sockPtr, (short)POLLIN, &pdata); } for (sockPtr = closePtr; sockPtr != NULL; sockPtr = sockPtr->nextPtr) { SockPoll(sockPtr, (short)POLLIN, &pdata); } if (Ns_DiffTime(&pdata.timeout, &now, &diff) > 0) { /* * The resolution of "pollTimeout" is ms, therefore, we round * up. If we would round down (e.g. 500 microseconds to 0 ms), * the time comparison later would determine that it is too * early. */ pollTimeout = (int)Ns_TimeToMilliseconds(&diff) + 1; } else { pollTimeout = 0; } } n = PollWait(&pdata, pollTimeout); Ns_Log(DriverDebug, "=== PollWait returned %d, trigger[0] %d", n, PollIn(&pdata, 0)); if (PollIn(&pdata, 0) && unlikely(ns_recv(drvPtr->trigger[0], charBuffer, 1u, 0) != 1)) { const char *errstr = ns_sockstrerror(ns_sockerrno); Ns_Fatal("driver: trigger ns_recv() failed: %s", errstr); } /* * Check whether we should re-animate some connection threads, * when e.g. the number of current threads dropped below the * minimal value. Perform this test on timeouts (n == 0; * just for safety reasons) or on explicit wakeup calls. */ if ((n == 0) || PollIn(&pdata, 0)) { NsServer *servPtr = drvPtr->servPtr; if (servPtr != NULL) { /* * Check if we have to reanimate the current server. */ NsEnsureRunningConnectionThreads(servPtr, NULL); } else { Ns_Set *servers = Ns_ConfigCreateSection("ns/servers"); size_t j; /* * Reanimation check on all servers. */ for (j = 0u; j < Ns_SetSize(servers); ++j) { const char *server = Ns_SetKey(servers, j); servPtr = NsGetServer(server); if (servPtr != NULL) { NsEnsureRunningConnectionThreads(servPtr, NULL); } } } } /* * Update the current time and drain and/or release any * closing sockets. */ Ns_GetTime(&now); if (closePtr != NULL) { sockPtr = closePtr; closePtr = NULL; while (sockPtr != NULL) { nextPtr = sockPtr->nextPtr; if (unlikely(PollHup(&pdata, sockPtr->pidx))) { /* * Peer has closed the connection */ SockRelease(sockPtr, SOCK_CLOSE, 0); } else if (likely(PollIn(&pdata, sockPtr->pidx))) { /* * Got some data */ ssize_t received = ns_recv(sockPtr->sock, drain, sizeof(drain), 0); if (received <= 0) { Ns_Log(DriverDebug, "poll closewait pollin; sockrelease SOCK_READERROR (sock %d)", sockPtr->sock); SockRelease(sockPtr, SOCK_READERROR, 0); } else { Push(sockPtr, closePtr); } } else if (Ns_DiffTime(&sockPtr->timeout, &now, &diff) <= 0) { /* no PollHup, no PollIn, maybe timeout */ Ns_Log(DriverDebug, "poll closewait timeout; sockrelease SOCK_CLOSETIMEOUT (sock %d)", sockPtr->sock); SockRelease(sockPtr, SOCK_CLOSETIMEOUT, 0); } else { /* too early, keep waiting */ Push(sockPtr, closePtr); } sockPtr = nextPtr; } } /* * Attempt read-ahead of any new connections. */ sockPtr = readPtr; readPtr = NULL; while (likely(sockPtr != NULL)) { nextPtr = sockPtr->nextPtr; if (unlikely(PollHup(&pdata, sockPtr->pidx))) { /* * Peer has closed the connection */ SockRelease(sockPtr, SOCK_CLOSE, 0); } else if (unlikely(!PollIn(&pdata, sockPtr->pidx)) && ((sockPtr->reqPtr == NULL) || (sockPtr->reqPtr->leftover == 0u))) { /* * Got no data for this sockPtr. */ if (Ns_DiffTime(&sockPtr->timeout, &now, &diff) <= 0) { SockRelease(sockPtr, SOCK_READTIMEOUT, 0); } else { Push(sockPtr, readPtr); } } else { /* * Got some data for this sockPtr. * If enabled, perform read-ahead now. */ assert(drvPtr == sockPtr->drvPtr); if (likely((drvPtr->opts & NS_DRIVER_ASYNC) != 0u)) { SockState s = SockRead(sockPtr, 0, &now); /* * Queue for connection processing if ready. */ switch (s) { case SOCK_SPOOL: drvPtr->stats.spooled++; if (SockSpoolerQueue(drvPtr, sockPtr) == 0) { Push(sockPtr, readPtr); } break; case SOCK_MORE: drvPtr->stats.partial++; SockTimeout(sockPtr, &now, &drvPtr->recvwait); Push(sockPtr, readPtr); break; case SOCK_READY: if (SockQueue(sockPtr, &now) == NS_TIMEOUT) { Push(sockPtr, waitPtr); } break; /* * Already handled or normal cases */ case SOCK_ENTITYTOOLARGE: NS_FALL_THROUGH; /* fall through */ case SOCK_BADREQUEST: NS_FALL_THROUGH; /* fall through */ case SOCK_BADHEADER: NS_FALL_THROUGH; /* fall through */ case SOCK_TOOMANYHEADERS: NS_FALL_THROUGH; /* fall through */ case SOCK_CLOSE: SockRelease(sockPtr, s, errno); break; /* * Exceptions */ case SOCK_READERROR: NS_FALL_THROUGH; /* fall through */ case SOCK_CLOSETIMEOUT: NS_FALL_THROUGH; /* fall through */ case SOCK_ERROR: NS_FALL_THROUGH; /* fall through */ case SOCK_READTIMEOUT: NS_FALL_THROUGH; /* fall through */ case SOCK_SHUTERROR: NS_FALL_THROUGH; /* fall through */ case SOCK_WRITEERROR: NS_FALL_THROUGH; /* fall through */ case SOCK_WRITETIMEOUT: drvPtr->stats.errors++; Ns_Log(Warning, "sockread returned unexpected result %s (err %s); close socket (%d)", GetSockStateName(s), ((errno != 0) ? strerror(errno) : NS_EMPTY_STRING), sockPtr->sock); SockRelease(sockPtr, s, errno); break; } } else { /* * Potentially blocking driver, NS_DRIVER_ASYNC is not defined */ if (Ns_DiffTime(&sockPtr->timeout, &now, &diff) <= 0) { drvPtr->stats.errors++; Ns_Log(Notice, "read-ahead has some data, no async sock read ===== diff time %ld", Ns_DiffTime(&sockPtr->timeout, &now, &diff)); sockPtr->keep = NS_FALSE; SockRelease(sockPtr, SOCK_READTIMEOUT, 0); } else { if (SockQueue(sockPtr, &now) == NS_TIMEOUT) { Push(sockPtr, waitPtr); } } } } sockPtr = nextPtr; } /* * Attempt to queue any pending connection after reversing the * list to ensure oldest connections are tried first. */ if (waitPtr != NULL) { sockPtr = NULL; while ((nextPtr = waitPtr) != NULL) { waitPtr = nextPtr->nextPtr; Push(nextPtr, sockPtr); } while (sockPtr != NULL) { nextPtr = sockPtr->nextPtr; if (SockQueue(sockPtr, &now) == NS_TIMEOUT) { Push(sockPtr, waitPtr); } sockPtr = nextPtr; } } /* * If no connections are waiting, attempt to accept more. */ if (waitPtr == NULL) { /* * If configured, try to accept more than one request, under heavy load * this helps to process more requests */ SockState s; bool acceptMore = NS_TRUE; accepted = 0; while (acceptMore && accepted < drvPtr->acceptsize && drvPtr->queuesize < drvPtr->maxqueuesize ) { bool gotRequests = NS_FALSE; /* * Check for input data on all bind addresses. Stop checking, * when one round of checking on all addresses fails. */ for (n = 0; n < nrBindaddrs; n++) { if ( PollIn(&pdata, drvPtr->pidx[n]) && (s = SockAccept(drvPtr, pdata.pfds[drvPtr->pidx[n]].fd, &sockPtr, &now)) != SOCK_ERROR) { switch (s) { case SOCK_SPOOL: drvPtr->stats.spooled++; if (SockSpoolerQueue(drvPtr, sockPtr) == 0) { Push(sockPtr, readPtr); } break; case SOCK_MORE: drvPtr->stats.partial++; SockTimeout(sockPtr, &now, &drvPtr->recvwait); Push(sockPtr, readPtr); break; case SOCK_READY: if (SockQueue(sockPtr, &now) == NS_TIMEOUT) { Push(sockPtr, waitPtr); } break; case SOCK_BADHEADER: NS_FALL_THROUGH; /* fall through */ case SOCK_BADREQUEST: NS_FALL_THROUGH; /* fall through */ case SOCK_CLOSE: NS_FALL_THROUGH; /* fall through */ case SOCK_CLOSETIMEOUT: NS_FALL_THROUGH; /* fall through */ case SOCK_ENTITYTOOLARGE: NS_FALL_THROUGH; /* fall through */ case SOCK_ERROR: NS_FALL_THROUGH; /* fall through */ case SOCK_READERROR: NS_FALL_THROUGH; /* fall through */ case SOCK_READTIMEOUT: NS_FALL_THROUGH; /* fall through */ case SOCK_SHUTERROR: NS_FALL_THROUGH; /* fall through */ case SOCK_TOOMANYHEADERS: NS_FALL_THROUGH; /* fall through */ case SOCK_WRITEERROR: NS_FALL_THROUGH; /* fall through */ case SOCK_WRITETIMEOUT: Ns_Fatal("driver: SockAccept returned: %s", GetSockStateName(s)); } accepted++; gotRequests = NS_TRUE; #ifdef __APPLE__ /* * On Darwin, the first accept() succeeds typically, but it is * useless to try, since this leads always to an EAGAIN */ acceptMore = NS_FALSE; break; #endif } } if (!gotRequests) { acceptMore = NS_FALSE; } } if (accepted > 1) { Ns_Log(Notice, "... sockAccept accepted %d connections", accepted); } } /* * Check for shut down and get the list of any closing or * keep-alive sockets. */ Ns_MutexLock(&drvPtr->lock); sockPtr = drvPtr->closePtr; drvPtr->closePtr = NULL; flags = drvPtr->flags; Ns_MutexUnlock(&drvPtr->lock); stopping = ((flags & DRIVER_SHUTDOWN) != 0u); /* * Update the timeout for each closing socket and add to the * close list if some data has been read from the socket * (i.e., it's not a closing keep-alive connection). */ while (sockPtr != NULL) { nextPtr = sockPtr->nextPtr; if (sockPtr->keep) { assert(drvPtr == sockPtr->drvPtr); Ns_Log(DriverDebug, "setting keepwait %ld.%6ld for socket %d", drvPtr->keepwait.sec, drvPtr->keepwait.usec, sockPtr->sock); SockTimeout(sockPtr, &now, &drvPtr->keepwait); Push(sockPtr, readPtr); } else { /* * Purely packet oriented drivers set on close the fd to * NS_INVALID_SOCKET. Since we cannot "shutdown" an UDP-socket * for writing, we bypass this call. */ assert(drvPtr == sockPtr->drvPtr); if (sockPtr->sock == NS_INVALID_SOCKET) { SockRelease(sockPtr, SOCK_CLOSE, errno); Ns_Log(DriverDebug, "DRIVER SockRelease: errno %d drvPtr->closewait %ld.%6ld", errno, drvPtr->closewait.sec, drvPtr->closewait.usec); } else if (shutdown(sockPtr->sock, SHUT_WR) != 0) { SockRelease(sockPtr, SOCK_SHUTERROR, errno); } else { Ns_Log(DriverDebug, "setting closewait %ld.%6ld for socket %d", drvPtr->closewait.sec, drvPtr->closewait.usec, sockPtr->sock); SockTimeout(sockPtr, &now, &drvPtr->closewait); Push(sockPtr, closePtr); } } sockPtr = nextPtr; } /* * Close the active drivers if shutdown is pending. */ if (stopping) { for (n = 0; n < nrBindaddrs; n++) { ns_sockclose(drvPtr->listenfd[n]); drvPtr->listenfd[n] = NS_INVALID_SOCKET; } } } PollFree(&pdata); Ns_Log(Notice, "exiting"); Ns_MutexLock(&drvPtr->lock); drvPtr->flags |= DRIVER_STOPPED; Ns_CondBroadcast(&drvPtr->cond); Ns_MutexUnlock(&drvPtr->lock); } static void PollCreate(PollData *pdata) { NS_NONNULL_ASSERT(pdata != NULL); memset(pdata, 0, sizeof(PollData)); } static void PollFree(PollData *pdata) { NS_NONNULL_ASSERT(pdata != NULL); ns_free(pdata->pfds); memset(pdata, 0, sizeof(PollData)); } static void PollReset(PollData *pdata) { NS_NONNULL_ASSERT(pdata != NULL); pdata->nfds = 0u; pdata->timeout.sec = TIME_T_MAX; pdata->timeout.usec = 0; } static NS_POLL_NFDS_TYPE PollSet(PollData *pdata, NS_SOCKET sock, short type, const Ns_Time *timeoutPtr) { NS_NONNULL_ASSERT(pdata != NULL); /* * Grow the pfds array if necessary. */ if (unlikely(pdata->nfds >= pdata->maxfds)) { pdata->maxfds += 100u; pdata->pfds = ns_realloc(pdata->pfds, pdata->maxfds * sizeof(struct pollfd)); } /* * Set the next pollfd struct with this socket. */ pdata->pfds[pdata->nfds].fd = sock; pdata->pfds[pdata->nfds].events = type; pdata->pfds[pdata->nfds].revents = 0; /* * Check for new minimum timeout. */ if (timeoutPtr != NULL && Ns_DiffTime(timeoutPtr, &pdata->timeout, NULL) < 0) { pdata->timeout = *timeoutPtr; } return pdata->nfds++; } static int PollWait(const PollData *pdata, int timeout) { int n; NS_NONNULL_ASSERT(pdata != NULL); do { n = ns_poll(pdata->pfds, pdata->nfds, timeout); } while (n < 0 && errno == NS_EINTR); if (n < 0) { Ns_Fatal("PollWait: ns_poll() failed: %s", ns_sockstrerror(ns_sockerrno)); } return n; } /* *---------------------------------------------------------------------- * * RequestNew * * Prepares for reading from the socket, allocates a "Request" * struct for the given socket. It might be reused from the pool * or freshly allocated. Counterpart of RequestFree(). * * Results: * None * * Side effects: * None * *---------------------------------------------------------------------- */ static void RequestNew(Sock *sockPtr) { Request *reqPtr; bool reuseRequest = NS_TRUE; NS_NONNULL_ASSERT(sockPtr != NULL); /* * Try to get a request from the pool of allocated Requests. */ Ns_MutexLock(&reqLock); reqPtr = firstReqPtr; if (likely(reqPtr != NULL)) { firstReqPtr = reqPtr->nextPtr; } else { reuseRequest = NS_FALSE; } Ns_MutexUnlock(&reqLock); if (reuseRequest) { Ns_Log(DriverDebug, "RequestNew reuses a Request"); } /* * In case we failed, allocate a new Request. */ if (reqPtr == NULL) { Ns_Log(DriverDebug, "RequestNew gets a fresh Request"); reqPtr = ns_calloc(1u, sizeof(Request)); Tcl_DStringInit(&reqPtr->buffer); reqPtr->headers = Ns_SetCreate(NULL); } sockPtr->reqPtr = reqPtr; } /* *---------------------------------------------------------------------- * * RequestFree -- * * Free/clean a socket request structure. This routine is called * at the end of connection processing or on a socket which * times out during async read-ahead. Counterpart of RequestNew(). * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------- */ static void RequestFree(Sock *sockPtr) { Request *reqPtr; bool keep; NS_NONNULL_ASSERT(sockPtr != NULL); reqPtr = sockPtr->reqPtr; assert(reqPtr != NULL); Ns_Log(DriverDebug, "=== RequestFree cleans %p (avail %" PRIuz " keep %d length %" PRIuz " contentLength %" PRIuz ")", (void *)reqPtr, reqPtr->avail, sockPtr->keep, reqPtr->length, reqPtr->contentLength); keep = (sockPtr->keep) && (reqPtr->avail > reqPtr->contentLength); if (keep) { size_t leftover = reqPtr->avail - reqPtr->contentLength; const char *offset = reqPtr->buffer.string + ((size_t)reqPtr->buffer.length - leftover); Ns_Log(DriverDebug, "setting leftover to %" PRIuz " bytes", leftover); /* * Here it is safe to move the data in the buffer, although the * reqPtr->content might point to it, since we re-init the content. In * case the terminating null character was written to the end of the * previous buffer, we have to restore the first character. */ memmove(reqPtr->buffer.string, offset, leftover); if (reqPtr->savedChar != '\0') { reqPtr->buffer.string[0] = reqPtr->savedChar; } Tcl_DStringSetLength(&reqPtr->buffer, (int)leftover); LogBuffer(DriverDebug, "KEEP BUFFER", reqPtr->buffer.string, leftover); reqPtr->leftover = leftover; } else { /* * Clean large buffers in order to avoid memory growth on huge * uploads (when maxupload is huge) */ /*fprintf(stderr, "=== reuse buffer size %d avail %d dynamic %d\n", reqPtr->buffer.length, reqPtr->buffer.spaceAvl, reqPtr->buffer.string == reqPtr->buffer.staticSpace);*/ if (Tcl_DStringLength(&reqPtr->buffer) > 65536) { Tcl_DStringFree(&reqPtr->buffer); } else { /* * Reuse buffer, but set length to 0. */ Tcl_DStringSetLength(&reqPtr->buffer, 0); } reqPtr->leftover = 0u; } reqPtr->next = NULL; reqPtr->content = NULL; reqPtr->length = 0u; reqPtr->contentLength = 0u; reqPtr->expectedLength = 0u; reqPtr->chunkStartOff = 0u; reqPtr->chunkWriteOff = 0u; reqPtr->roff = 0u; reqPtr->woff = 0u; reqPtr->coff = 0u; reqPtr->avail = 0u; reqPtr->savedChar = '\0'; Ns_SetTrunc(reqPtr->headers, 0u); if (reqPtr->auth != NULL) { Ns_SetFree(reqPtr->auth); reqPtr->auth = NULL; } if (reqPtr->request.line != NULL) { Ns_Log(DriverDebug, "RequestFree calls Ns_ResetRequest on %p", (void*)&reqPtr->request); Ns_ResetRequest(&reqPtr->request); } else { Ns_Log(DriverDebug, "RequestFree does not call Ns_ResetRequest on %p", (void*)&reqPtr->request); } if (!keep) { /* * Push the reqPtr to the pool for reuse in other connections. */ sockPtr->reqPtr = NULL; Ns_MutexLock(&reqLock); reqPtr->nextPtr = firstReqPtr; firstReqPtr = reqPtr; Ns_MutexUnlock(&reqLock); } else { /* * Keep the partly cleaned up reqPtr associated with the connection. */ Ns_Log(DriverDebug, "=== KEEP request structure in sockPtr (don't push into the pool)"); } } /* *---------------------------------------------------------------------- * * SockQueue -- * * Puts socket into connection queue * * Results: * NS_OK if queued, * NS_ERROR if socket closed because of error * NS_TIMEOUT if queue is full * * Side effects: * None. * *---------------------------------------------------------------------- */ static Ns_ReturnCode SockQueue(Sock *sockPtr, const Ns_Time *timePtr) { Ns_ReturnCode result; NS_NONNULL_ASSERT(sockPtr != NULL); /* * Verify the conditions. Request struct must exist already. */ assert(sockPtr->reqPtr != NULL); SockSetServer(sockPtr); assert(sockPtr->servPtr != NULL); /* * Actual queueing, if not ready spool to the waiting list. */ if (!NsQueueConn(sockPtr, timePtr)) { result = NS_TIMEOUT; } else { result = NS_OK; } return result; } /* *---------------------------------------------------------------------- * * SockPoll -- * * Arrange for given Sock to be monitored. * * Results: * None. * * Side effects: * Sock fd will be monitored for readability on next spin of * DriverThread. * *---------------------------------------------------------------------- */ static void SockPoll(Sock *sockPtr, short type, PollData *pdata) { NS_NONNULL_ASSERT(sockPtr != NULL); NS_NONNULL_ASSERT(pdata != NULL); sockPtr->pidx = PollSet(pdata, sockPtr->sock, type, &sockPtr->timeout); } /* *---------------------------------------------------------------------- * * SockTimeout -- * * Update socket with timeout * * Results: * None. * * Side effects: * Socket timeout will have nowPtr + timeout value * *---------------------------------------------------------------------- */ static void SockTimeout(Sock *sockPtr, const Ns_Time *nowPtr, const Ns_Time *timeout) { NS_NONNULL_ASSERT(sockPtr != NULL); sockPtr->timeout = *nowPtr; Ns_IncrTime(&sockPtr->timeout, timeout->sec, timeout->usec); } /* *---------------------------------------------------------------------- * * SockAccept -- * * Accept and initialize a new Sock in sockPtrPtr. * * Results: * SOCK_READY, SOCK_MORE, SOCK_SPOOL, * SOCK_ERROR + NULL sockPtr. * * Side effects: * Read-ahead may be attempted on new socket. * *---------------------------------------------------------------------- */ static SockState SockAccept(Driver *drvPtr, NS_SOCKET sock, Sock **sockPtrPtr, const Ns_Time *nowPtr) { Sock *sockPtr; SockState sockStatus; NS_DRIVER_ACCEPT_STATUS status; NS_NONNULL_ASSERT(drvPtr != NULL); sockPtr = SockNew(drvPtr); /* * Accept the new connection. */ status = DriverAccept(sockPtr, sock); if (unlikely(status == NS_DRIVER_ACCEPT_ERROR)) { sockStatus = SOCK_ERROR; /* * We reach the place frequently, especially on Linux, when we try to * accept multiple connection in one sweep. Usually, the errno is * EAGAIN. */ Ns_MutexLock(&drvPtr->lock); sockPtr->nextPtr = drvPtr->sockPtr; drvPtr->sockPtr = sockPtr; Ns_MutexUnlock(&drvPtr->lock); sockPtr = NULL; } else { sockPtr->acceptTime = *nowPtr; drvPtr->queuesize++; if (status == NS_DRIVER_ACCEPT_DATA) { /* * If there is already data present then read it without * polling if we're in async mode. */ if ((drvPtr->opts & NS_DRIVER_ASYNC) != 0u) { sockStatus = SockRead(sockPtr, 0, nowPtr); if ((int)sockStatus < 0) { Ns_Log(DriverDebug, "SockRead returned error %s", GetSockStateName(sockStatus)); SockRelease(sockPtr, sockStatus, errno); sockStatus = SOCK_ERROR; sockPtr = NULL; } } else { /* * Queue this socket without reading, NsGetRequest() in the * connection thread will perform actual reading of the * request. */ sockStatus = SOCK_READY; } } else if (status == NS_DRIVER_ACCEPT_QUEUE) { /* * We need to call RequestNew() to make sure socket has request * structure allocated, otherwise NsGetRequest() will call * SockRead() which is not what this driver wants. */ if (sockPtr->reqPtr == NULL) { RequestNew(sockPtr); } sockStatus = SOCK_READY; } else { sockStatus = SOCK_MORE; } } *sockPtrPtr = sockPtr; return sockStatus; } /* *---------------------------------------------------------------------- * * SockNew -- * * Allocate and/or initialize a Sock structure. Counterpart of * SockRelease(). * * Results: * SockPtr * * Side effects: * Potentially new memory is allocated. * *---------------------------------------------------------------------- */ static Sock * SockNew(Driver *drvPtr) { Sock *sockPtr; NS_NONNULL_ASSERT(drvPtr != NULL); Ns_MutexLock(&drvPtr->lock); sockPtr = drvPtr->sockPtr; if (likely(sockPtr != NULL)) { drvPtr->sockPtr = sockPtr->nextPtr; sockPtr->keep = NS_FALSE; } Ns_MutexUnlock(&drvPtr->lock); if (sockPtr == NULL) { size_t sockSize = sizeof(Sock) + (nsconf.nextSlsId * sizeof(Ns_Callback *)); sockPtr = ns_calloc(1u, sockSize); sockPtr->drvPtr = drvPtr; } else { sockPtr->tfd = 0; sockPtr->taddr = NULL; sockPtr->flags = 0u; sockPtr->arg = NULL; sockPtr->recvSockState = NS_SOCK_NONE; } return sockPtr; } /* *---------------------------------------------------------------------- * * SockRelease -- * * Close a socket and release the connection structure for * re-use. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------- */ static void SockRelease(Sock *sockPtr, SockState reason, int err) { Driver *drvPtr; NS_NONNULL_ASSERT(sockPtr != NULL); Ns_Log(DriverDebug, "SockRelease reason %s err %d (sock %d)", GetSockStateName(reason), err, sockPtr->sock); drvPtr = sockPtr->drvPtr; assert(drvPtr != NULL); SockError(sockPtr, reason, err); if (sockPtr->sock != NS_INVALID_SOCKET) { SockClose(sockPtr, (int)NS_FALSE); } else { Ns_Log(DriverDebug, "SockRelease bypasses SockClose, since we have an invalid socket"); } NsSlsCleanup(sockPtr); drvPtr->queuesize--; if (sockPtr->reqPtr != NULL) { Ns_Log(DriverDebug, "SockRelease calls RequestFree"); RequestFree(sockPtr); } Ns_MutexLock(&drvPtr->lock); sockPtr->nextPtr = drvPtr->sockPtr; drvPtr->sockPtr = sockPtr; Ns_MutexUnlock(&drvPtr->lock); } /* *---------------------------------------------------------------------- * * SockError -- * * Log error message for given socket * re-use. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------- */ static void SockError(Sock *sockPtr, SockState reason, int err) { const char *errMsg = NULL; NS_NONNULL_ASSERT(sockPtr != NULL); switch (reason) { case SOCK_READY: case SOCK_SPOOL: case SOCK_MORE: case SOCK_CLOSE: case SOCK_CLOSETIMEOUT: /* This is normal, never log. */ break; case SOCK_READTIMEOUT: /* * For this case, whether this is acceptable or not * depends upon whether this sock was a keep-alive * that we were allowing to 'linger'. */ if (!sockPtr->keep) { errMsg = "Timeout during read"; } break; case SOCK_WRITETIMEOUT: errMsg = "Timeout during write"; break; case SOCK_READERROR: errMsg = "Unable to read request"; break; case SOCK_WRITEERROR: errMsg = "Unable to write request"; break; case SOCK_SHUTERROR: errMsg = "Unable to shutdown socket"; break; case SOCK_BADREQUEST: errMsg = "Bad Request"; SockSendResponse(sockPtr, 400, errMsg); break; case SOCK_TOOMANYHEADERS: errMsg = "Too Many Request Headers"; SockSendResponse(sockPtr, 414, errMsg); break; case SOCK_BADHEADER: errMsg = "Invalid Request Header"; SockSendResponse(sockPtr, 400, errMsg); break; case SOCK_ENTITYTOOLARGE: errMsg = "Request Entity Too Large"; SockSendResponse(sockPtr, 413, errMsg); break; case SOCK_ERROR: errMsg = "Unknown Error"; SockSendResponse(sockPtr, 400, errMsg); break; } if (errMsg != NULL) { char ipString[NS_IPADDR_SIZE]; Ns_Log(DriverDebug, "SockError: %s (%d: %s), sock: %d, peer: [%s]:%d, request: %.99s", errMsg, err, (err != 0) ? strerror(err) : NS_EMPTY_STRING, sockPtr->sock, ns_inet_ntop((struct sockaddr *)&(sockPtr->sa), ipString, sizeof(ipString)), Ns_SockaddrGetPort((struct sockaddr *)&(sockPtr->sa)), (sockPtr->reqPtr != NULL) ? sockPtr->reqPtr->buffer.string : NS_EMPTY_STRING); } } /* *---------------------------------------------------------------------- * * SockSendResponse -- * * Send an HTTP response directly to the client using the * driver callback. * * Results: * None. * * Side effects: * May not sent the complete response to the client * if encountering non-writable connection socket. * *---------------------------------------------------------------------- */ static void SockSendResponse(Sock *sockPtr, int code, const char *errMsg) { struct iovec iov[3]; char header[32]; ssize_t sent, tosend; NS_NONNULL_ASSERT(sockPtr != NULL); NS_NONNULL_ASSERT(errMsg != NULL); snprintf(header, sizeof(header), "HTTP/1.0 %d ", code); iov[0].iov_base = header; iov[0].iov_len = strlen(header); iov[1].iov_base = (void *)errMsg; iov[1].iov_len = strlen(errMsg); iov[2].iov_base = (void *)"\r\n\r\n"; iov[2].iov_len = 4u; tosend = (ssize_t)(iov[0].iov_len + iov[1].iov_len + iov[2].iov_len); sent = NsDriverSend(sockPtr, iov, 3, 0u); if (sent < tosend) { Ns_Log(Warning, "Driver: partial write while sending response;" " %" PRIdz " < %" PRIdz, sent, tosend); } /* * In case we have a request structure, complain the system log about * the bad request. */ if (sockPtr->reqPtr != NULL) { Request *reqPtr = sockPtr->reqPtr; const char *requestLine = (reqPtr->request.line != NULL) ? reqPtr->request.line : NS_EMPTY_STRING; (void)ns_inet_ntop((struct sockaddr *)&(sockPtr->sa), sockPtr->reqPtr->peer, NS_IPADDR_SIZE); /* * Check, if bad request looks like a TLS handshake. If yes, there is * no need to print out the received buffer. */ if (requestLine[0] == (char)0x16 && requestLine[1] >= 3 && requestLine[2] == 1) { Ns_Log(Warning, "invalid request %d (%s) from peer %s: received TLS handshake on a non-TLS connection", code, errMsg, reqPtr->peer); } else { Tcl_DString dsReqLine; Tcl_DStringInit(&dsReqLine); Ns_Log(Warning, "invalid request: %d (%s) from peer %s request '%s' offsets: read %" PRIuz " write %" PRIuz " content %" PRIuz " avail %" PRIuz, code, errMsg, reqPtr->peer, Ns_DStringAppendPrintable(&dsReqLine, NS_FALSE, requestLine, strlen(requestLine)), reqPtr->roff, reqPtr->woff, reqPtr->coff, reqPtr->avail); Tcl_DStringFree(&dsReqLine); LogBuffer(Warning, "REQ BUFFER", reqPtr->buffer.string, (size_t)reqPtr->buffer.length); } } else { Ns_Log(Warning, "invalid request: %d (%s) - no request information available", code, errMsg); } } /* *---------------------------------------------------------------------- * * SockTrigger -- * * Wakeup DriversThread from blocking ns_poll(). * * Results: * None. * * Side effects: * DriversThread will wake up. * *---------------------------------------------------------------------- */ static void SockTrigger(NS_SOCKET sock) { if (send(sock, NS_EMPTY_STRING, 1, 0) != 1) { const char *errstr = ns_sockstrerror(ns_sockerrno); Ns_Log(Error, "driver: trigger send() failed: %s", errstr); } } /* *---------------------------------------------------------------------- * * SockClose -- * * Closes connection socket, does all cleanups. The input parameter * "keep" might be NS_TRUE/NS_FALSE or -1 if undecided. * * Results: * None. * * Side effects: * None * *---------------------------------------------------------------------- */ static void SockClose(Sock *sockPtr, int keep) { NS_NONNULL_ASSERT(sockPtr != NULL); if (keep != 0) { bool driverKeep = DriverKeep(sockPtr); keep = (int)driverKeep; } if (keep == (int)NS_FALSE) { DriverClose(sockPtr); } Ns_MutexLock(&sockPtr->drvPtr->lock); sockPtr->keep = (bool)keep; Ns_MutexUnlock(&sockPtr->drvPtr->lock); /* * Unconditionally remove temporary file, connection thread * should take care about very large uploads. */ if (sockPtr->tfile != NULL) { unlink(sockPtr->tfile); ns_free(sockPtr->tfile); sockPtr->tfile = NULL; if (sockPtr->tfd > 0) { /* * Close and reset fd. The fd should be > 0 unless we are in error * conditions. */ (void) ns_close(sockPtr->tfd); } sockPtr->tfd = 0; } else if (sockPtr->tfd > 0) { /* * This must be a fd allocated via Ns_GetTemp(); */ Ns_ReleaseTemp(sockPtr->tfd); sockPtr->tfd = 0; } #ifndef _WIN32 /* * Un-map temp file used for spooled content. */ if (sockPtr->taddr != NULL) { munmap(sockPtr->taddr, (size_t)sockPtr->tsize); sockPtr->taddr = NULL; } #endif } /* *---------------------------------------------------------------------- * * ChunkedDecode -- * * Reads the content form the incoming request buffer and tries * to decode chunked encoding parts. The function can be called * repeatedly and with incomplete input and overwrites the buffer * with the decoded data optionally. The decoded data is always * shorter than the encoded one. * * Results: * SOCK_READY when chunk was complete, SOCK_MORE when more data is * requried, or some error condition. * * Side effects: * Updates the buffer if update is true (and adjusts * reqPtr->chunkWriteOff). Updates always reqPtr->chunkStartOff to allow * incremental operations. * *---------------------------------------------------------------------- */ static SockState ChunkedDecode(Request *reqPtr, bool update) { const Tcl_DString *bufPtr; const char *end, *chunkStart; SockState result = SOCK_READY; NS_NONNULL_ASSERT(reqPtr != NULL); bufPtr = &reqPtr->buffer; end = bufPtr->string + bufPtr->length; chunkStart = bufPtr->string + reqPtr->chunkStartOff; while (reqPtr->chunkStartOff < (size_t)bufPtr->length) { char *p = strstr(chunkStart, "\r\n"); long chunkLength; if (p == NULL) { Ns_Log(DriverDebug, "ChunkedDecode: chunk did not find end-of-line"); result = SOCK_MORE; break; } *p = '\0'; chunkLength = strtol(chunkStart, NULL, 16); *p = '\r'; if (chunkLength < 0) { Ns_Log(Warning, "ChunkedDecode: negative chunk length"); result = SOCK_BADREQUEST; break; } *p = '\r'; if (p + 2 + chunkLength > end) { Ns_Log(DriverDebug, "ChunkedDecode: chunk length past end of buffer"); result = SOCK_MORE; break; } if (update) { char *writeBuffer = bufPtr->string + reqPtr->chunkWriteOff; memmove(writeBuffer, p + 2, (size_t)chunkLength); reqPtr->chunkWriteOff += (size_t)chunkLength; *(writeBuffer + chunkLength) = '\0'; } reqPtr->chunkStartOff += (size_t)(p - chunkStart) + 4u + (size_t)chunkLength; chunkStart = bufPtr->string + reqPtr->chunkStartOff; } return result; } /* *---------------------------------------------------------------------- * * SockRead -- * * Read content from the given Sock, processing the input as * necessary. This is the core callback routine designed to * either be called repeatedly within the DriverThread during * an async read-ahead or in a blocking loop in NsGetRequest() * at the start of connection processing. * * Results: * SOCK_READY: Request is ready for processing. * SOCK_MORE: More input is required. * SOCK_ERROR: Client drop or timeout. * SOCK_SPOOL: Pass input handling to spooler * SOCK_CLOSE: peer closed connection * SOCK_BADREQUEST * SOCK_BADHEADER * SOCK_TOOMANYHEADERS * * Side effects: * The Request structure will be built up for use by the * connection thread. Also, before returning SOCK_READY, * the next byte to read mark and bytes available are set * to the beginning of the content, just beyond the headers. * * Contents may be spooled into temp file and mmap-ed * *---------------------------------------------------------------------- */ static SockState SockRead(Sock *sockPtr, int spooler, const Ns_Time *timePtr) { const Driver *drvPtr; Request *reqPtr; Tcl_DString *bufPtr; struct iovec buf; char tbuf[16384]; size_t buflen, nread; ssize_t n; SockState resultState; NS_NONNULL_ASSERT(sockPtr != NULL); drvPtr = sockPtr->drvPtr; tbuf[0] = '\0'; /* * In case of "keepwait", the accept time is not meaningful and * reset to 0. In such cases, update "acceptTime" to the actual * begin of a request. This part is intended for async drivers. */ if (sockPtr->acceptTime.sec == 0) { assert(timePtr != NULL); sockPtr->acceptTime = *timePtr; } /* * Initialize request structure if needed. */ if (sockPtr->reqPtr == NULL) { RequestNew(sockPtr); } /* * On the first read, attempt to read-ahead "bufsize" bytes. * Otherwise, read only the number of bytes left in the * content. */ reqPtr = sockPtr->reqPtr; bufPtr = &reqPtr->buffer; if (reqPtr->length == 0u) { nread = drvPtr->bufsize; } else { nread = reqPtr->length - reqPtr->avail; } /* * Grow the buffer to include space for the next bytes. */ buflen = (size_t)bufPtr->length; n = (ssize_t)(buflen + nread); if (unlikely(n > drvPtr->maxinput)) { n = (ssize_t)drvPtr->maxinput; nread = (size_t)n - buflen; if (nread == 0u) { Ns_Log(DriverDebug, "SockRead: maxinput reached %" TCL_LL_MODIFIER "d", drvPtr->maxinput); return SOCK_ERROR; } } /* * Use temp file for content larger than "readahead" bytes. */ #ifndef _WIN32 if (reqPtr->coff > 0u /* We are in the content part (after the header) */ && !reqPtr->chunkStartOff /* Never spool chunked encoded data since we decode in memory */ && reqPtr->length > (size_t)drvPtr->readahead /* We need more data */ && sockPtr->tfd <= 0 /* We have no spool fd */ ) { const DrvSpooler *spPtr = &drvPtr->spooler; Ns_Log(DriverDebug, "SockRead: require tmp file for content spooling (length %" PRIuz" > readahead " "%" TCL_LL_MODIFIER "d)", reqPtr->length, drvPtr->readahead); /* * In driver mode send this Sock to the spooler thread if * it is running */ if (spooler == 0 && spPtr->threads > 0) { return SOCK_SPOOL; } /* * If "maxupload" is specified and content size exceeds the configured * values, spool uploads into normal temp file (not deleted). We do * not want to map such large files into memory. */ if (drvPtr->maxupload > 0 && reqPtr->length > (size_t)drvPtr->maxupload ) { size_t tfileLength = strlen(drvPtr->uploadpath) + 16u; sockPtr->tfile = ns_malloc(tfileLength); snprintf(sockPtr->tfile, tfileLength, "%s/%d.XXXXXX", drvPtr->uploadpath, sockPtr->sock); sockPtr->tfd = ns_mkstemp(sockPtr->tfile); if (sockPtr->tfd == NS_INVALID_FD) { Ns_Log(Error, "SockRead: cannot create spool file with template '%s': %s", sockPtr->tfile, strerror(errno)); } } else { /* * Get a temporary fd. These FDs are used for mmapping. */ sockPtr->tfd = Ns_GetTemp(); } if (unlikely(sockPtr->tfd == NS_INVALID_FD)) { Ns_Log(DriverDebug, "SockRead: spool fd invalid"); return SOCK_ERROR; } n = (ssize_t)((size_t)bufPtr->length - reqPtr->coff); assert(n >= 0); if (ns_write(sockPtr->tfd, bufPtr->string + reqPtr->coff, (size_t)n) != n) { return SOCK_WRITEERROR; } Tcl_DStringSetLength(bufPtr, 0); } #endif if (sockPtr->tfd > 0) { buf.iov_base = tbuf; buf.iov_len = MIN(nread, sizeof(tbuf)); } else { Tcl_DStringSetLength(bufPtr, (int)(buflen + nread)); buf.iov_base = bufPtr->string + reqPtr->woff; buf.iov_len = nread; } if (reqPtr->leftover > 0u) { /* * There is some leftover in the buffer, don't read but take the * leftover instead as input. */ n = (ssize_t)reqPtr->leftover; reqPtr->leftover = 0u; buflen = 0u; Ns_Log(DriverDebug, "SockRead receive from leftover %" PRIdz " bytes", n); } else { /* * Receive actually some data from the driver. */ n = NsDriverRecv(sockPtr, &buf, 1, NULL); Ns_Log(DriverDebug, "SockRead receive from network %" PRIdz " bytes sockState %.2x", n, (int)sockPtr->recvSockState); } { Ns_SockState nsSockState = sockPtr->recvSockState; /* * The nsSockState has one of the following values, when provided: * * NS_SOCK_READ, NS_SOCK_DONE, NS_SOCK_AGAIN, NS_SOCK_EXCEPTION, * NS_SOCK_TIMEOUT */ switch (nsSockState) { case NS_SOCK_TIMEOUT: NS_FALL_THROUGH; /* fall through */ case NS_SOCK_EXCEPTION: return SOCK_READERROR; case NS_SOCK_AGAIN: Tcl_DStringSetLength(bufPtr, (int)buflen); return SOCK_MORE; case NS_SOCK_DONE: return SOCK_CLOSE; case NS_SOCK_READ: break; case NS_SOCK_CANCEL: NS_FALL_THROUGH; /* fall through */ case NS_SOCK_EXIT: NS_FALL_THROUGH; /* fall through */ case NS_SOCK_INIT: NS_FALL_THROUGH; /* fall through */ case NS_SOCK_WRITE: Ns_Log(Warning, "SockRead received unexpected state %.2x from driver", nsSockState); return SOCK_READERROR; case NS_SOCK_NONE: /* * Old style state management based on "n" and "errno", which is * more fragile. We keep there for old-style drivers. */ if (n < 0) { Tcl_DStringSetLength(bufPtr, (int)buflen); /* * The driver returns -1 when the peer closed the connection, but * clears the errno such we can distinguish from error conditions. */ if (errno == 0) { return SOCK_CLOSE; } return SOCK_READERROR; } if (n == 0) { Tcl_DStringSetLength(bufPtr, (int)buflen); return SOCK_MORE; } break; } } if (sockPtr->tfd > 0) { if (ns_write(sockPtr->tfd, tbuf, (size_t)n) != n) { return SOCK_WRITEERROR; } } else { Tcl_DStringSetLength(bufPtr, (int)(buflen + (size_t)n)); } reqPtr->woff += (size_t)n; reqPtr->avail += (size_t)n; /* * This driver needs raw buffer, it is binary or non-HTTP request */ if ((drvPtr->opts & NS_DRIVER_NOPARSE) != 0u) { return SOCK_READY; } resultState = SockParse(sockPtr); return resultState; } /*---------------------------------------------------------------------- * * LogBuffer -- * * Debug function to output buffer content when the provided severity is * enabled. The function prints just visible characters and space as is * and prints the hex code otherwise. * * Results: * None. * * Side effects: * Writes to error.log * *---------------------------------------------------------------------- */ static void LogBuffer(Ns_LogSeverity severity, const char *msg, const char *buffer, size_t len) { Tcl_DString ds; NS_NONNULL_ASSERT(msg != NULL); NS_NONNULL_ASSERT(buffer != NULL); if (Ns_LogSeverityEnabled(severity)) { Tcl_DStringInit(&ds); Tcl_DStringAppend(&ds, msg, -1); Tcl_DStringAppend(&ds, ": ", 2); (void)Ns_DStringAppendPrintable(&ds, NS_FALSE, buffer, len); Ns_Log(severity, "%s", ds.string); Tcl_DStringFree(&ds); } } /*---------------------------------------------------------------------- * * EndOfHeader -- * * Function to be called (once), when end of header is reached. At this * time, all request header lines were parsed already correctly. * * Results: * None. * * Side effects: * Update various reqPtr fields and signal certain facts and error * conditions via sockPtr->flags. In error conditions, sockPtr->keep is * set to NS_FALSE. * *---------------------------------------------------------------------- */ static size_t EndOfHeader(Sock *sockPtr) { Request *reqPtr; const char *s; NS_NONNULL_ASSERT(sockPtr != NULL); reqPtr = sockPtr->reqPtr; assert(reqPtr != NULL); reqPtr->chunkStartOff = 0u; /* * Check for "expect: 100-continue" and clear flag in case we have * pipelining. */ sockPtr->flags &= ~(NS_CONN_CONTINUE); s = Ns_SetIGet(reqPtr->headers, "expect"); if (s != NULL) { if (*s == '1' && *(s+1) == '0' && *(s+2) == '0' && *(s+3) == '-') { char *dup = ns_strdup(s+4); Ns_StrToLower(dup); if (STREQ(dup, "continue")) { sockPtr->flags |= NS_CONN_CONTINUE; } ns_free(dup); } } /* * Handle content-length, which might be provided or not. * Clear length specific error flags. */ sockPtr->flags &= ~(NS_CONN_ENTITYTOOLARGE); s = Ns_SetIGet(reqPtr->headers, "content-length"); if (s == NULL) { s = Ns_SetIGet(reqPtr->headers, "Transfer-Encoding"); if (s != NULL) { /* Lower case is in the standard, capitalized by macOS */ if (STREQ(s, "chunked") || STREQ(s, "Chunked")) { Tcl_WideInt expected; reqPtr->chunkStartOff = reqPtr->roff; reqPtr->chunkWriteOff = reqPtr->chunkStartOff; reqPtr->contentLength = 0u; /* * We need reqPtr->expectedLength for safely terminating read loop. */ s = Ns_SetIGet(reqPtr->headers, "X-Expected-Entity-Length"); if ((s != NULL) && (Ns_StrToWideInt(s, &expected) == NS_OK) && (expected > 0) ) { reqPtr->expectedLength = (size_t)expected; } s = NULL; } } } /* * In case a valid and meaningful was provided, the string with the * content length ("s") is not NULL. */ if (s != NULL) { Tcl_WideInt length; if ((Ns_StrToWideInt(s, &length) == NS_OK) && (length > 0)) { reqPtr->length = (size_t)length; /* * Handle too large input requests. */ if (reqPtr->length > (size_t)sockPtr->drvPtr->maxinput) { Ns_Log(Warning, "SockParse: request too large, length=%" PRIdz ", maxinput=%" TCL_LL_MODIFIER "d", reqPtr->length, sockPtr->drvPtr->maxinput); sockPtr->keep = NS_FALSE; sockPtr->flags |= NS_CONN_ENTITYTOOLARGE; } reqPtr->contentLength = (size_t)length; } } /* * Compression format handling: parse information from request headers * indicating allowed compression formats for quick access. * * Clear compression accepted flag */ sockPtr->flags &= ~(NS_CONN_ZIPACCEPTED|NS_CONN_BROTLIACCEPTED); s = Ns_SetIGet(reqPtr->headers, "Accept-Encoding"); if (s != NULL) { bool gzipAccept, brotliAccept; /* * Get allowed compression formats from "accept-encoding" headers. */ NsParseAcceptEncoding(reqPtr->request.version, s, &gzipAccept, &brotliAccept); if (gzipAccept || brotliAccept) { /* * Don't allow compression formats for Range requests. */ s = Ns_SetIGet(reqPtr->headers, "Range"); if (s == NULL) { if (gzipAccept) { sockPtr->flags |= NS_CONN_ZIPACCEPTED; } if (brotliAccept) { sockPtr->flags |= NS_CONN_BROTLIACCEPTED; } } } } /* * Set up request length for spooling and further read operations */ if (reqPtr->contentLength != 0u) { /* * Content-Length was provided, use it */ reqPtr->length = reqPtr->contentLength; } return reqPtr->roff; } /*---------------------------------------------------------------------- * * SockParse -- * * Construct the given conn by parsing input buffer until end of * headers. Return SOCK_READY when finished parsing. * * Results: * SOCK_READY: Conn is ready for processing. * SOCK_MORE: More input is required. * SOCK_ERROR: Malformed request. * SOCK_BADREQUEST * SOCK_BADHEADER * SOCK_TOOMANYHEADERS * * Side effects: * An Ns_Request and/or Ns_Set may be allocated. * Ns_Conn buffer management offsets updated. * *---------------------------------------------------------------------- */ static SockState SockParse(Sock *sockPtr) { const Tcl_DString *bufPtr; const Driver *drvPtr; Request *reqPtr; char save; SockState result; NS_NONNULL_ASSERT(sockPtr != NULL); drvPtr = sockPtr->drvPtr; NsUpdateProgress((Ns_Sock *) sockPtr); reqPtr = sockPtr->reqPtr; bufPtr = &reqPtr->buffer; /* * Scan lines (header) until start of content (body-part) */ while (reqPtr->coff == 0u) { char *s, *e; size_t cnt; /* * Find the next header line. */ s = bufPtr->string + reqPtr->roff; e = memchr(s, INTCHAR('\n'), reqPtr->avail); if (unlikely(e == NULL)) { /* * Input not yet newline terminated - request more data. */ return SOCK_MORE; } /* * Check for max single line overflows. * * Previous versions if the driver returned here directly an * error code, which was handled via HTTP error message * provided via SockError(). However, the SockError() handling * closes the connection immediately. This has the * consequence, that the HTTP client might never see the error * message, since the request was not yet fully transmitted, * but it will see a "broken pipe: 13" message instead. We * read now the full request and return the message via * ConnRunRequest(). */ if (unlikely((e - s) > drvPtr->maxline)) { sockPtr->keep = NS_FALSE; if (reqPtr->request.line == NULL) { Ns_Log(DriverDebug, "SockParse: maxline reached of %d bytes", drvPtr->maxline); sockPtr->flags = NS_CONN_REQUESTURITOOLONG; Ns_Log(Warning, "request line is too long (%d bytes)", (int)(e - s)); } else { sockPtr->flags = NS_CONN_LINETOOLONG; Ns_Log(Warning, "request header line is too long (%d bytes)", (int)(e - s)); } } /* * Update next read pointer to end of this line. */ cnt = (size_t)(e - s) + 1u; reqPtr->roff += cnt; reqPtr->avail -= cnt; /* * Adjust end pointer to the last content character before the line * terminator. */ if (likely(e > s) && likely(*(e-1) == '\r')) { --e; } /* * Check for end of headers in case we have not done it yet. */ if (unlikely(e == s) && (reqPtr->coff == 0u)) { /* * We are at end of headers. */ reqPtr->coff = EndOfHeader(sockPtr); /* * In cases the client sent "expect: 100-continue", report back that * everything is fine with the headers. */ if ((sockPtr->flags & NS_CONN_CONTINUE) != 0u) { Ns_Log(Ns_LogRequestDebug, "honoring 100-continue"); /* * In case, the request entity (body) was too large, we can * return immediately the error message, when the client has * flagged this via "Expect:". Otherwise we have to read the * full request (although it is too large) to drain the * channel. Otherwise, the server might close the connection * *before* it has received full request with its body from * the client. We just keep the flag and let * Ns_ConnRunRequest() handle the error message. */ if ((sockPtr->flags & NS_CONN_ENTITYTOOLARGE) != 0u) { Ns_Log(Ns_LogRequestDebug, "100-continue: entity too large"); return SOCK_ENTITYTOOLARGE; /* * We have no other error message flagged (future ones * have to be handled here). */ } else { struct iovec iov[1]; ssize_t sent; /* * Reply with "100 continue". */ Ns_Log(Ns_LogRequestDebug, "100-continue: reply CONTINUE"); iov[0].iov_base = (char *)"HTTP/1.1 100 Continue\r\n\r\n"; iov[0].iov_len = strlen(iov[0].iov_base); sent = Ns_SockSendBufs((Ns_Sock *)sockPtr, iov, 1, NULL, 0u); if (sent != (ssize_t)iov[0].iov_len) { Ns_Log(Warning, "could not deliver response: 100 Continue"); /* * Should we bail out here? */ } } } } else { /* * We have the request-line or a header line to process. */ save = *e; *e = '\0'; if (unlikely(reqPtr->request.line == NULL)) { /* * There is no request-line set. The received line must the * the request-line. */ Ns_Log(DriverDebug, "SockParse (%d): parse request line <%s>", sockPtr->sock, s); if (Ns_ParseRequest(&reqPtr->request, s) == NS_ERROR) { /* * Invalid request. */ return SOCK_BADREQUEST; } /* * HTTP 0.9 did not have a HTTP-version number or request headers * and no empty line terminating the request header. */ if (unlikely(reqPtr->request.version < 1.0)) { /* * Pre-HTTP/1.0 request. */ reqPtr->coff = reqPtr->roff; Ns_Log(Notice, "pre-HTTP/1.0 request <%s>", reqPtr->request.line); } } else if (Ns_ParseHeader(reqPtr->headers, s, Preserve) != NS_OK) { /* * Invalid header. */ return SOCK_BADHEADER; } else { /* * Check for max number of headers */ if (unlikely(Ns_SetSize(reqPtr->headers) > (size_t)drvPtr->maxheaders)) { Ns_Log(DriverDebug, "SockParse (%d): maxheaders reached of %d bytes", sockPtr->sock, drvPtr->maxheaders); return SOCK_TOOMANYHEADERS; } } *e = save; } } if (unlikely(reqPtr->request.line == NULL)) { /* * We are at end of headers, but we have not parsed a request line * (maybe just two linefeeds). */ return SOCK_BADREQUEST; } /* * We are in the request body. */ assert(reqPtr->coff > 0u); assert(reqPtr->request.line != NULL); /* * Check if all content has arrived. */ Ns_Log(Debug, "=== length < avail (length %" PRIuz ", avail %" PRIuz ") tfd %d tfile %p chunkStartOff %" PRIuz, reqPtr->length, reqPtr->avail, sockPtr->tfd, (void *)sockPtr->tfile, reqPtr->chunkStartOff); if (reqPtr->chunkStartOff != 0u) { /* * Chunked encoding was provided. */ SockState chunkState; size_t currentContentLength; chunkState = ChunkedDecode(reqPtr, NS_TRUE); currentContentLength = reqPtr->chunkWriteOff - reqPtr->coff; /* * A chunk might be complete, but it might not be the last * chunk from the client. The best thing would be to be able * to read until EOF here. In cases, where the (optional) * "expectedLength" was provided by the client, we terminate * depending on that information */ if ((chunkState == SOCK_MORE) || (reqPtr->expectedLength != 0u && currentContentLength < reqPtr->expectedLength)) { /* * ChunkedDecode wants more data. */ return SOCK_MORE; } else if (chunkState != SOCK_READY) { return chunkState; } /* * ChunkedDecode has enough data. */ reqPtr->length = (size_t)currentContentLength; } if (reqPtr->avail < reqPtr->length) { Ns_Log(DriverDebug, "SockRead wait for more input"); /* * Wait for more input. */ return SOCK_MORE; } Ns_Log(Dev, "=== all required data is available (avail %" PRIuz", length %" PRIuz ", " "readahead %" TCL_LL_MODIFIER "d maxupload %" TCL_LL_MODIFIER "d) tfd %d", reqPtr->avail, reqPtr->length, drvPtr->readahead, drvPtr->maxupload, sockPtr->tfd); /* * We have all required data in the receive buffer or in a temporary file. * * - Uploads > "readahead": these are put into temporary files. * * - Uploads > "maxupload": these are put into temporary files * without mmapping, no content parsing will be performed in memory. */ result = SOCK_READY; if (sockPtr->tfile != NULL) { reqPtr->content = NULL; reqPtr->next = NULL; reqPtr->avail = 0u; Ns_Log(DriverDebug, "content spooled to file: size %" PRIdz ", file %s", reqPtr->length, sockPtr->tfile); /* * Nothing more to do, return via SOCK_READY; */ } else { /* * Uploads < "maxupload" are spooled to files and mmapped in order to * provide the usual interface via [ns_conn content]. */ if (sockPtr->tfd > 0) { #ifdef _WIN32 /* * For _WIN32, tfd should never be set, since tfd-spooling is not * implemented for windows. */ assert(0); #else int prot = PROT_READ | PROT_WRITE; /* * Add a byte to make sure, the string termination with \0 below falls * always into the mmapped area. On some older OSes this might lead to * crashes when we hitting page boundaries. */ ssize_t rc = ns_write(sockPtr->tfd, "\0", 1); if (rc == -1) { Ns_Log(Error, "socket: could not append terminating 0-byte"); } sockPtr->tsize = reqPtr->length + 1; sockPtr->taddr = mmap(0, sockPtr->tsize, prot, MAP_PRIVATE, sockPtr->tfd, 0); if (sockPtr->taddr == MAP_FAILED) { sockPtr->taddr = NULL; result = SOCK_ERROR; } else { reqPtr->content = sockPtr->taddr; Ns_Log(Debug, "content spooled to mmapped file: readahead=%" TCL_LL_MODIFIER "d, filesize=%" PRIdz, drvPtr->readahead, sockPtr->tsize); } #endif } else { /* * Set the content the begin of the remaining buffer (content offset). * This happens as well when reqPtr->contentLength is 0, but it is * needed for chunked input processing. */ reqPtr->content = bufPtr->string + reqPtr->coff; } reqPtr->next = reqPtr->content; /* * Add a terminating null character. The content might be from the receive * buffer (Tcl_DString) or from the mmapped file. Non-mmapped files are handled * above. */ if (reqPtr->length > 0u) { Ns_Log(DriverDebug, "SockRead adds null terminating character at content[%" PRIuz "]", reqPtr->length); reqPtr->savedChar = reqPtr->content[reqPtr->length]; reqPtr->content[reqPtr->length] = '\0'; if (sockPtr->taddr == NULL) { LogBuffer(DriverDebug, "UPDATED BUFFER", sockPtr->reqPtr->buffer.string, (size_t)reqPtr->buffer.length); } } } return result; } /* *---------------------------------------------------------------------- * * SockSetServer -- * * Set virtual server from driver context or Host header. * * Results: * void. * * Side effects: * * Updates sockPtr->servPtr. In case an invalid server set, or the * required host field in HTTP/1.1 is missing the HTTP-method is set to * the constant "BAD". * *---------------------------------------------------------------------- */ static void SockSetServer(Sock *sockPtr) { char *host; Request *reqPtr; bool bad_request = NS_FALSE; Driver *drvPtr; NS_NONNULL_ASSERT(sockPtr != NULL); reqPtr = sockPtr->reqPtr; assert(reqPtr != NULL); drvPtr = sockPtr->drvPtr; assert(drvPtr != NULL); sockPtr->servPtr = drvPtr->servPtr; sockPtr->location = drvPtr->location; host = Ns_SetIGet(reqPtr->headers, "Host"); Ns_Log(DriverDebug, "SockSetServer host '%s' request line '%s'", host, reqPtr->request.line); if (unlikely((host == NULL) && (reqPtr->request.version >= 1.1))) { /* * HTTP/1.1 requires host header */ Ns_Log(Notice, "request header field \"Host\" is missing in HTTP/1.1 request: \"%s\"\n", reqPtr->request.line); bad_request = NS_TRUE; } if (sockPtr->servPtr == NULL) { const ServerMap *mapPtr = NULL; if (host != NULL) { const Tcl_HashEntry *hPtr; size_t hostLength = strlen(host); /* * Remove trailing dot of host header field, since RFC 2976 allows * fully qualified "absolute" DNS names in host fields (see e.g. §3.2.2). */ if (host[hostLength] == '.') { host[hostLength] = '\0'; } /* * Convert provided host header field to lower case before hash * lookup. */ Ns_StrToLower(host); hPtr = Tcl_FindHashEntry(&drvPtr->hosts, host); Ns_Log(DriverDebug, "SockSetServer driver '%s' host '%s' => %p", drvPtr->moduleName, host, (void*)hPtr); if (hPtr != NULL) { /* * Request with provided host header field could be resolved * against a certain server. */ mapPtr = Tcl_GetHashValue(hPtr); } else { /* * Host header field content is not found in the mapping table. */ Ns_Log(DriverDebug, "cannot locate host header content '%s' in virtual hosts " "table of driver '%s', fall back to default '%s'", host, drvPtr->moduleName, drvPtr->defMapPtr->location); if (Ns_LogSeverityEnabled(DriverDebug)) { Tcl_HashEntry *hPtr2; Tcl_HashSearch search; hPtr2 = Tcl_FirstHashEntry(&drvPtr->hosts, &search); while (hPtr2 != NULL) { Ns_Log(Notice, "... host entry: '%s'\n", (char *)Tcl_GetHashKey(&drvPtr->hosts, hPtr2)); hPtr2 = Tcl_NextHashEntry(&search); } } } } if (mapPtr == NULL) { /* * Could not lookup the virtual host, Get the default mapping from the driver. */ mapPtr = drvPtr->defMapPtr; } if (mapPtr != NULL) { sockPtr->servPtr = mapPtr->servPtr; sockPtr->location = mapPtr->location; } if (sockPtr->servPtr == NULL) { Ns_Log(Warning, "cannot determine server for request: \"%s\" (host \"%s\")\n", reqPtr->request.line, host); bad_request = NS_TRUE; } } if (unlikely(bad_request)) { Ns_Log(DriverDebug, "SockSetServer sets method to BAD"); ns_free((char *)reqPtr->request.method); reqPtr->request.method = ns_strdup("BAD"); } } /* *====================================================================== * Spooler Thread: Receive asynchronously from the client socket *====================================================================== */ /* *---------------------------------------------------------------------- * * SpoolerThread -- * * Spooling socket driver thread. * * Results: * None. * * Side effects: * Connections are accepted on the configured listen sockets, * placed on the run queue to be serviced, and gracefully * closed when done. Async sockets have the entire request read * here before queuing as well. * *---------------------------------------------------------------------- */ static void SpoolerThread(void *arg) { SpoolerQueue *queuePtr = (SpoolerQueue*)arg; char charBuffer[1]; int pollTimeout; bool stopping; Sock *sockPtr, *nextPtr, *waitPtr, *readPtr; Ns_Time now, diff; const Driver *drvPtr; PollData pdata; Ns_ThreadSetName("-spooler%d-", queuePtr->id); queuePtr->threadName = Ns_ThreadGetName(); /* * Loop forever until signaled to shut down and all * connections are complete and gracefully closed. */ Ns_Log(Notice, "spooler%d: accepting connections", queuePtr->id); PollCreate(&pdata); Ns_GetTime(&now); waitPtr = readPtr = NULL; stopping = NS_FALSE; while (!stopping) { /* * If there are any read sockets, set the bits * and determine the minimum relative timeout. */ PollReset(&pdata); (void)PollSet(&pdata, queuePtr->pipe[0], (short)POLLIN, NULL); if (readPtr == NULL) { pollTimeout = 30 * 1000; } else { sockPtr = readPtr; while (sockPtr != NULL) { SockPoll(sockPtr, (short)POLLIN, &pdata); sockPtr = sockPtr->nextPtr; } pollTimeout = -1; } /* * Select and drain the trigger pipe if necessary. */ /*n =*/ (void) PollWait(&pdata, pollTimeout); if (PollIn(&pdata, 0) && unlikely(ns_recv(queuePtr->pipe[0], charBuffer, 1u, 0) != 1)) { Ns_Fatal("spooler: trigger ns_recv() failed: %s", ns_sockstrerror(ns_sockerrno)); } /* * Attempt read-ahead of any new connections. */ Ns_GetTime(&now); sockPtr = readPtr; readPtr = NULL; while (sockPtr != NULL) { nextPtr = sockPtr->nextPtr; drvPtr = sockPtr->drvPtr; if (unlikely(PollHup(&pdata, sockPtr->pidx))) { /* * Peer has closed the connection */ SockRelease(sockPtr, SOCK_CLOSE, 0); } else if (!PollIn(&pdata, sockPtr->pidx)) { /* * Got no data */ if (Ns_DiffTime(&sockPtr->timeout, &now, &diff) <= 0) { SockRelease(sockPtr, SOCK_READTIMEOUT, 0); queuePtr->queuesize--; } else { Push(sockPtr, readPtr); } } else { /* * Got some data */ SockState n = SockRead(sockPtr, 1, &now); switch (n) { case SOCK_MORE: SockTimeout(sockPtr, &now, &drvPtr->recvwait); Push(sockPtr, readPtr); break; case SOCK_READY: assert(sockPtr->reqPtr != NULL); SockSetServer(sockPtr); Push(sockPtr, waitPtr); break; case SOCK_BADHEADER: NS_FALL_THROUGH; /* fall through */ case SOCK_BADREQUEST: NS_FALL_THROUGH; /* fall through */ case SOCK_CLOSE: NS_FALL_THROUGH; /* fall through */ case SOCK_CLOSETIMEOUT: NS_FALL_THROUGH; /* fall through */ case SOCK_ENTITYTOOLARGE: NS_FALL_THROUGH; /* fall through */ case SOCK_ERROR: NS_FALL_THROUGH; /* fall through */ case SOCK_READERROR: NS_FALL_THROUGH; /* fall through */ case SOCK_READTIMEOUT: NS_FALL_THROUGH; /* fall through */ case SOCK_SHUTERROR: NS_FALL_THROUGH; /* fall through */ case SOCK_SPOOL: NS_FALL_THROUGH; /* fall through */ case SOCK_TOOMANYHEADERS: NS_FALL_THROUGH; /* fall through */ case SOCK_WRITEERROR: NS_FALL_THROUGH; /* fall through */ case SOCK_WRITETIMEOUT: SockRelease(sockPtr, n, errno); queuePtr->queuesize--; break; } } sockPtr = nextPtr; } /* * Attempt to queue any pending connection * after reversing the list to ensure oldest * connections are tried first. */ if (waitPtr != NULL) { sockPtr = NULL; while ((nextPtr = waitPtr) != NULL) { waitPtr = nextPtr->nextPtr; Push(nextPtr, sockPtr); } while (sockPtr != NULL) { nextPtr = sockPtr->nextPtr; if (!NsQueueConn(sockPtr, &now)) { Push(sockPtr, waitPtr); } else { queuePtr->queuesize--; } sockPtr = nextPtr; } } /* * Add more connections from the spooler queue */ Ns_MutexLock(&queuePtr->lock); if (waitPtr == NULL) { sockPtr = (Sock*)queuePtr->sockPtr; queuePtr->sockPtr = NULL; while (sockPtr != NULL) { nextPtr = sockPtr->nextPtr; drvPtr = sockPtr->drvPtr; SockTimeout(sockPtr, &now, &drvPtr->recvwait); Push(sockPtr, readPtr); queuePtr->queuesize++; sockPtr = nextPtr; } } /* * Check for shutdown */ stopping = queuePtr->shutdown; Ns_MutexUnlock(&queuePtr->lock); } PollFree(&pdata); Ns_Log(Notice, "exiting"); Ns_MutexLock(&queuePtr->lock); queuePtr->stopped = NS_TRUE; Ns_CondBroadcast(&queuePtr->cond); Ns_MutexUnlock(&queuePtr->lock); } static void SpoolerQueueStart(SpoolerQueue *queuePtr, Ns_ThreadProc *proc) { NS_NONNULL_ASSERT(proc != NULL); while (queuePtr != NULL) { if (ns_sockpair(queuePtr->pipe) != 0) { Ns_Fatal("ns_sockpair() failed: %s", ns_sockstrerror(ns_sockerrno)); } Ns_ThreadCreate(proc, queuePtr, 0, &queuePtr->thread); queuePtr = queuePtr->nextPtr; } } static void SpoolerQueueStop(SpoolerQueue *queuePtr, const Ns_Time *timeoutPtr, const char *name) { NS_NONNULL_ASSERT(timeoutPtr != NULL); NS_NONNULL_ASSERT(name != NULL); while (queuePtr != NULL) { Ns_ReturnCode status; Ns_MutexLock(&queuePtr->lock); if (!queuePtr->stopped && !queuePtr->shutdown) { Ns_Log(Debug, "%s%d: triggering shutdown", name, queuePtr->id); queuePtr->shutdown = NS_TRUE; SockTrigger(queuePtr->pipe[1]); } status = NS_OK; while (!queuePtr->stopped && status == NS_OK) { status = Ns_CondTimedWait(&queuePtr->cond, &queuePtr->lock, timeoutPtr); } if (status != NS_OK) { Ns_Log(Warning, "%s%d: timeout waiting for shutdown", name, queuePtr->id); } else { /*Ns_Log(Notice, "%s%d: shutdown complete", name, queuePtr->id);*/ if (queuePtr->thread != NULL) { Ns_ThreadJoin(&queuePtr->thread, NULL); queuePtr->thread = NULL; } else { Ns_Log(Notice, "%s%d: shutdown: thread already gone", name, queuePtr->id); } ns_sockclose(queuePtr->pipe[0]); ns_sockclose(queuePtr->pipe[1]); } Ns_MutexUnlock(&queuePtr->lock); queuePtr = queuePtr->nextPtr; } } static int SockSpoolerQueue(Driver *drvPtr, Sock *sockPtr) { bool trigger = NS_FALSE; SpoolerQueue *queuePtr; NS_NONNULL_ASSERT(drvPtr != NULL); NS_NONNULL_ASSERT(sockPtr != NULL); /* * Get the next spooler thread from the list, all spooler requests are * rotated between all spooler threads */ Ns_MutexLock(&drvPtr->spooler.lock); if (drvPtr->spooler.curPtr == NULL) { drvPtr->spooler.curPtr = drvPtr->spooler.firstPtr; } queuePtr = drvPtr->spooler.curPtr; drvPtr->spooler.curPtr = drvPtr->spooler.curPtr->nextPtr; Ns_MutexUnlock(&drvPtr->spooler.lock); Ns_Log(Debug, "Spooler: %d: started fd=%d: %" PRIdz " bytes", queuePtr->id, sockPtr->sock, sockPtr->reqPtr->length); Ns_MutexLock(&queuePtr->lock); if (queuePtr->sockPtr == NULL) { trigger = NS_TRUE; } Push(sockPtr, queuePtr->sockPtr); Ns_MutexUnlock(&queuePtr->lock); /* * Wake up spooler thread */ if (trigger) { SockTrigger(queuePtr->pipe[1]); } return 1; } /* *====================================================================== * Writer Thread: Write asynchronously to the client socket *====================================================================== */ /* *---------------------------------------------------------------------- * * NsWriterLock, NsWriterUnlock -- * * Provide an API for locking and unlocking context information * for streaming asynchronous writer jobs. The locks are just * needed for managing linkage between "connPtr" and a writer * entry. The lock operations are rather infrequent and the * lock duration is very short, such that at a single global * appears sufficient. * * Results: * None * * Side effects: * Change Mutex state. * *---------------------------------------------------------------------- */ void NsWriterLock(void) { Ns_MutexLock(&writerlock); } void NsWriterUnlock(void) { Ns_MutexUnlock(&writerlock); } /* *---------------------------------------------------------------------- * * WriterSockFileVecCleanup -- * * Cleanup function for FileVec array in WriterSock structure. * * Results: * None. * * Side effects: * Closing potentially file descriptors, freeing Ns_FileVec memory. * *---------------------------------------------------------------------- */ static void WriterSockFileVecCleanup(WriterSock *wrSockPtr) { NS_NONNULL_ASSERT(wrSockPtr != NULL); if ( wrSockPtr->c.file.nbufs > 0) { int i; Ns_Log(DriverDebug, "WriterSockRelease nbufs %d", wrSockPtr->c.file.nbufs); for (i = 0; i < wrSockPtr->c.file.nbufs; i++) { /* * The fd of c.file.currentbuf is always the same as * wrSockPtr->fd and therefore already closed at this point. */ if ( (i != wrSockPtr->c.file.currentbuf) && (wrSockPtr->c.file.bufs[i].fd != NS_INVALID_FD) ) { Ns_Log(DriverDebug, "WriterSockRelease must close fd %d", wrSockPtr->c.file.bufs[i].fd); ns_close(wrSockPtr->c.file.bufs[i].fd); } } ns_free(wrSockPtr->c.file.bufs); } ns_free(wrSockPtr->c.file.buf); } /* *---------------------------------------------------------------------- * * WriterSockRequire, WriterSockRelease -- * * Management functions for WriterSocks. WriterSockRequire() and * WriterSockRelease() are responsible for obtaining and * freeing "WriterSock" structures. When shuch a structure is finally * released, it is removed from the queue, the socket is * closed and the memory is freed. * * Results: * WriterSockRequire() returns a WriterSock from a connection, * the other functions return nothing. * * Side effects: * Updating reference counters, closing socket, freeing memory. * *---------------------------------------------------------------------- */ static WriterSock * WriterSockRequire(const Conn *connPtr) { WriterSock *wrSockPtr; NS_NONNULL_ASSERT(connPtr != NULL); NsWriterLock(); wrSockPtr = (WriterSock *)connPtr->strWriter; if (wrSockPtr != NULL) { wrSockPtr->refCount ++; } NsWriterUnlock(); return wrSockPtr; } static void WriterSockRelease(WriterSock *wrSockPtr) { SpoolerQueue *queuePtr; NS_NONNULL_ASSERT(wrSockPtr != NULL); wrSockPtr->refCount --; Ns_Log(DriverDebug, "WriterSockRelease %p refCount %d keep %d", (void *)wrSockPtr, wrSockPtr->refCount, wrSockPtr->keep); if (wrSockPtr->refCount > 0) { return; } Ns_Log(DriverDebug, "Writer: closed sock %d, file fd %d, error %d/%d, " "sent=%" TCL_LL_MODIFIER "d, flags=%X", wrSockPtr->sockPtr->sock, wrSockPtr->fd, wrSockPtr->status, wrSockPtr->err, wrSockPtr->nsent, wrSockPtr->flags); NsPoolAddBytesSent(wrSockPtr->poolPtr, wrSockPtr->nsent); if (wrSockPtr->doStream != NS_WRITER_STREAM_NONE) { Conn *connPtr; NsWriterLock(); connPtr = wrSockPtr->connPtr; if (connPtr != NULL && connPtr->strWriter != NULL) { connPtr->strWriter = NULL; } NsWriterUnlock(); /* * In case, writer streams are activated for this wrSockPtr, make sure * to release the tmp file. See thread Naviserver Open Files on the * sourceforge mailing list (starting July 2019). */ if (wrSockPtr->doStream == NS_WRITER_STREAM_FINISH) { Ns_ReleaseTemp(wrSockPtr->fd); } } /* * Remove the entry from the queue and decrement counter */ queuePtr = wrSockPtr->queuePtr; if (queuePtr->curPtr == wrSockPtr) { queuePtr->curPtr = wrSockPtr->nextPtr; queuePtr->queuesize--; } else { WriterSock *curPtr, *lastPtr = queuePtr->curPtr; for (curPtr = (lastPtr != NULL) ? lastPtr->nextPtr : NULL; curPtr != NULL; lastPtr = curPtr, curPtr = curPtr->nextPtr ) { if (curPtr == wrSockPtr) { lastPtr->nextPtr = wrSockPtr->nextPtr; queuePtr->queuesize--; break; } } } if ((wrSockPtr->err != 0) || (wrSockPtr->status != SPOOLER_OK)) { int i; /* * Lookup the matching sockState from the spooler state. The array has * just 5 elements, on average, just 2 comparisons are needed (since * OK is at the end). */ for (i = 0; i < Ns_NrElements(spoolerStateMap); i++) { if (spoolerStateMap[i].spoolerState == wrSockPtr->status) { SockError(wrSockPtr->sockPtr, spoolerStateMap[i].sockState, wrSockPtr->err); break; } } NsSockClose(wrSockPtr->sockPtr, (int)NS_FALSE); } else { NsSockClose(wrSockPtr->sockPtr, (int)wrSockPtr->keep); } if (wrSockPtr->clientData != NULL) { ns_free(wrSockPtr->clientData); } if (wrSockPtr->fd != NS_INVALID_FD) { if (wrSockPtr->doStream != NS_WRITER_STREAM_FINISH) { (void) ns_close(wrSockPtr->fd); } WriterSockFileVecCleanup(wrSockPtr); } else if (wrSockPtr->c.mem.bufs != NULL) { if (wrSockPtr->c.mem.fmap.addr != NULL) { NsMemUmap(&wrSockPtr->c.mem.fmap); } else { int i; for (i = 0; i < wrSockPtr->c.mem.nbufs; i++) { ns_free((char *)wrSockPtr->c.mem.bufs[i].iov_base); } } if (wrSockPtr->c.mem.bufs != wrSockPtr->c.mem.preallocated_bufs) { ns_free(wrSockPtr->c.mem.bufs); } } if (wrSockPtr->headerString != NULL) { ns_free(wrSockPtr->headerString); } ns_free(wrSockPtr); } /* *---------------------------------------------------------------------- * * WriterReadFromSpool -- * * Utility function of the WriterThread to read blocks from a * file into the output buffer of the writer. It handles * left overs from previous send attempts and takes care for * locking in case simultaneous reading and writing from the * same file. * * Results: * None. * * Side effects: * Fills up curPtr->c.file.buf and updates counters/sizes. * *---------------------------------------------------------------------- */ static SpoolerState WriterReadFromSpool(WriterSock *curPtr) { NsWriterStreamState doStream; SpoolerState status = SPOOLER_OK; size_t maxsize, toRead; unsigned char *bufPtr; NS_NONNULL_ASSERT(curPtr != NULL); doStream = curPtr->doStream; if (doStream != NS_WRITER_STREAM_NONE) { Ns_MutexLock(&curPtr->c.file.fdlock); toRead = curPtr->c.file.toRead; Ns_MutexUnlock(&curPtr->c.file.fdlock); } else { toRead = curPtr->c.file.toRead; Ns_Log(DriverDebug, "### WriterReadFromSpool [%d]: fd %d tosend %lu files %d", curPtr->c.file.currentbuf, curPtr->fd, toRead, curPtr->c.file.nbufs); } maxsize = curPtr->c.file.maxsize; bufPtr = curPtr->c.file.buf; /* * When bufsize > 0 we have a leftover from previous send. In such * cases, move the leftover to the front, and fill the reminder of * the buffer with new data from curPtr->c. */ if (curPtr->c.file.bufsize > 0u) { Ns_Log(DriverDebug, "### WriterReadFromSpool %p %.6x leftover %" PRIdz " offset %ld", (void *)curPtr, curPtr->flags, curPtr->c.file.bufsize, (long)curPtr->c.file.bufoffset); if (likely(curPtr->c.file.bufoffset > 0)) { memmove(curPtr->c.file.buf, curPtr->c.file.buf + curPtr->c.file.bufoffset, curPtr->c.file.bufsize); } bufPtr = curPtr->c.file.buf + curPtr->c.file.bufsize; maxsize -= curPtr->c.file.bufsize; } if (toRead > maxsize) { toRead = maxsize; } /* * Read content from the file into the buffer. */ if (toRead > 0u) { ssize_t n; if (doStream != NS_WRITER_STREAM_NONE) { /* * In streaming mode, the connection thread writes to the * spool file and the writer thread reads from the same * file. Therefore, we have to re-adjust the current * read/writer position, which might be changed by the * other thread. These positions have to be locked, since * seeking might be subject to race conditions. Here we * set the read pointer to the position after the last * send operation. */ Ns_MutexLock(&curPtr->c.file.fdlock); (void) ns_lseek(curPtr->fd, (off_t)curPtr->nsent, SEEK_SET); } if (curPtr->c.file.nbufs == 0) { /* * Working on a single fd. */ n = ns_read(curPtr->fd, bufPtr, toRead); } else { /* * Working on a Ns_FileVec. */ int currentbuf = curPtr->c.file.currentbuf; size_t wantRead = curPtr->c.file.bufs[currentbuf].length; size_t segSize = (wantRead > toRead ? toRead : wantRead); n = ns_read(curPtr->fd, bufPtr, segSize); Ns_Log(DriverDebug, "### WriterReadFromSpool [%d] (nbufs %d): read from fd %d want %lu got %ld (remain %lu)", currentbuf, curPtr->c.file.nbufs, curPtr->fd, segSize, n, wantRead); if (n > 0) { /* * Reduce the remaining length in the Ns_FileVec for the * next iteration. */ curPtr->c.file.bufs[currentbuf].length -= (size_t)n; if ((size_t)n < wantRead) { /* * Partial read on a segment. */ Ns_Log(DriverDebug, "### WriterReadFromSpool [%d] (nbufs %d): partial read on fd %d (got %ld)", currentbuf, curPtr->c.file.nbufs, curPtr->fd, n); } else if (currentbuf < curPtr->c.file.nbufs - 1 /* && (n == wantRead) */) { /* * All read from this segment, setup next read. */ ns_close(curPtr->fd); curPtr->c.file.bufs[currentbuf].fd = NS_INVALID_FD; curPtr->c.file.currentbuf ++; curPtr->fd = curPtr->c.file.bufs[curPtr->c.file.currentbuf].fd; Ns_Log(DriverDebug, "### WriterReadFromSpool switch to [%d] fd %d", curPtr->c.file.currentbuf, curPtr->fd); } } } if (n <= 0) { status = SPOOLER_READERROR; } else { /* * curPtr->c.file.toRead is still protected by * curPtr->c.file.fdlock when needed (in streaming mode). */ curPtr->c.file.toRead -= (size_t)n; curPtr->c.file.bufsize += (size_t)n; } if (doStream != NS_WRITER_STREAM_NONE) { Ns_MutexUnlock(&curPtr->c.file.fdlock); } } return status; } /* *---------------------------------------------------------------------- * * WriterSend -- * * Utility function of the WriterThread to send content to the client. It * handles partial write operations from the lower level driver * infrastructure. * * Results: * either NS_OK or SOCK_ERROR; * * Side effects: * Sends data, might reshuffle iovec. * *---------------------------------------------------------------------- */ static SpoolerState WriterSend(WriterSock *curPtr, int *err) { const struct iovec *bufs; struct iovec vbuf; int nbufs; SpoolerState status = SPOOLER_OK; size_t toWrite; ssize_t n; NS_NONNULL_ASSERT(curPtr != NULL); NS_NONNULL_ASSERT(err != NULL); /* * Prepare send operation */ if (curPtr->fd != NS_INVALID_FD) { /* * We have a valid file descriptor, send data from file. * * Prepare sending a single buffer with curPtr->c.file.bufsize bytes * from the curPtr->c.file.buf to the client. */ vbuf.iov_len = curPtr->c.file.bufsize; vbuf.iov_base = (void *)curPtr->c.file.buf; bufs = &vbuf; nbufs = 1; toWrite = curPtr->c.file.bufsize; } else { int i; /* * Prepare sending multiple memory buffers. Get length of remaining * buffers. */ toWrite = 0u; for (i = 0; i < curPtr->c.mem.nsbufs; i ++) { toWrite += curPtr->c.mem.sbufs[i].iov_len; } Ns_Log(DriverDebug, "### Writer wants to send remainder nbufs %d len %" PRIdz, curPtr->c.mem.nsbufs, toWrite); /* * Add buffers from the source and fill structure up to max */ while (curPtr->c.mem.bufIdx < curPtr->c.mem.nbufs && curPtr->c.mem.sbufIdx < UIO_SMALLIOV) { const struct iovec *vPtr = &curPtr->c.mem.bufs[curPtr->c.mem.bufIdx]; if (vPtr->iov_len > 0u && vPtr->iov_base != NULL) { Ns_Log(DriverDebug, "### Writer copies source %d to scratch %d len %" PRIiovlen, curPtr->c.mem.bufIdx, curPtr->c.mem.sbufIdx, vPtr->iov_len); toWrite += Ns_SetVec(curPtr->c.mem.sbufs, curPtr->c.mem.sbufIdx++, vPtr->iov_base, vPtr->iov_len); curPtr->c.mem.nsbufs++; } curPtr->c.mem.bufIdx++; } bufs = curPtr->c.mem.sbufs; nbufs = curPtr->c.mem.nsbufs; Ns_Log(DriverDebug, "### Writer wants to send %d bufs size %" PRIdz, nbufs, toWrite); } /* * Perform the actual send operation. */ n = NsDriverSend(curPtr->sockPtr, bufs, nbufs, 0u); if (n == -1) { *err = ns_sockerrno; status = SPOOLER_WRITEERROR; } else { /* * We have sent zero or more bytes. */ if (curPtr->doStream != NS_WRITER_STREAM_NONE) { Ns_MutexLock(&curPtr->c.file.fdlock); curPtr->size -= (size_t)n; Ns_MutexUnlock(&curPtr->c.file.fdlock); } else { curPtr->size -= (size_t)n; } curPtr->nsent += n; curPtr->sockPtr->timeout.sec = 0; if (curPtr->fd != NS_INVALID_FD) { /* * File-descriptor based send operation. Reduce the (remainig) * buffer size the amount of data sent and adjust the buffer * offset. For partial send operations, this will lead to a * remaining buffer size > 0. */ curPtr->c.file.bufsize -= (size_t)n; curPtr->c.file.bufoffset = (off_t)n; } else { if (n < (ssize_t)toWrite) { /* * We have a partial transmit from the iovec * structure. We have to compact it to fill content in * the next round. */ curPtr->c.mem.sbufIdx = Ns_ResetVec(curPtr->c.mem.sbufs, curPtr->c.mem.nsbufs, (size_t)n); curPtr->c.mem.nsbufs -= curPtr->c.mem.sbufIdx; memmove(curPtr->c.mem.sbufs, curPtr->c.mem.sbufs + curPtr->c.mem.sbufIdx, /* move the iovecs to the start of the scratch buffers */ sizeof(struct iovec) * (size_t)curPtr->c.mem.nsbufs); } } } return status; } /* *---------------------------------------------------------------------- * * WriterGetInfoPtr -- * * Helper function to obtain ConnPoolInfo structure for a WriterSock. * * The connInfoPtr is allocated only once per pool and cached in the * WriterSock. Only the first time, a writer thread "sees" a pool, it * allocates the structure for it. * * Results: * None. * * Side effects: * Can allocate memory * *---------------------------------------------------------------------- */ static ConnPoolInfo * WriterGetInfoPtr(WriterSock *curPtr, Tcl_HashTable *pools) { NS_NONNULL_ASSERT(curPtr != NULL); NS_NONNULL_ASSERT(pools != NULL); if (curPtr->infoPtr == NULL) { int isNew; Tcl_HashEntry *hPtr; hPtr = Tcl_CreateHashEntry(pools, (void*)curPtr->poolPtr, &isNew); if (isNew == 1) { /* * This is a pool that we have not seen yet. */ curPtr->infoPtr = ns_malloc(sizeof(ConnPoolInfo)); curPtr->infoPtr->currentPoolRate = 0; curPtr->infoPtr->threadSlot = NsPoolAllocateThreadSlot(curPtr->poolPtr, Ns_ThreadId()); Tcl_SetHashValue(hPtr, curPtr->infoPtr); Ns_Log(DriverDebug, "poollimit: pool '%s' allocate infoPtr with slot %lu poolLimit %d", curPtr->poolPtr->pool, curPtr->infoPtr->threadSlot, curPtr->poolPtr->rate.poolLimit); } else { curPtr->infoPtr = (ConnPoolInfo *)Tcl_GetHashValue(hPtr); } } return curPtr->infoPtr; } /* *---------------------------------------------------------------------- * * WriterPerPoolRates -- * * Compute current bandwidths per pool and writer. * * Since we have potentially multiple writer threads running, all these * might have writer threads of the same pool. In order to minimize * locking, we compute first writer thread specific subresults and combine * these later with with the results of the other threads. * * Results: * None. * * Side effects: * Connections are accepted and their SockPtr is set to NULL * such that closing actual connection does not close the socket. * *---------------------------------------------------------------------- */ static void WriterPerPoolRates(WriterSock *writePtr, Tcl_HashTable *pools) { WriterSock *curPtr; Tcl_HashSearch search; Tcl_HashEntry *hPtr; NS_NONNULL_ASSERT(writePtr != NULL); NS_NONNULL_ASSERT(pools != NULL); /* * First reset pool total rate. We keep the bandwidth managed pools in a * thread-local memory. Before, we accumulate the data, we reset it. */ hPtr = Tcl_FirstHashEntry(pools, &search); while (hPtr != NULL) { ConnPoolInfo *infoPtr = (ConnPoolInfo *)Tcl_GetHashValue(hPtr); infoPtr->currentPoolRate = 0; hPtr = Tcl_NextHashEntry(&search); } /* * Sum the actual rates per bandwidth limited pool for all active writer * jobs. */ for (curPtr = writePtr; curPtr != NULL; curPtr = curPtr->nextPtr) { /* * Does the writer come form a badwidth limited pool? */ if (curPtr->poolPtr->rate.poolLimit > 0 && curPtr->currentRate > 0) { /* * Add the actual rate to the writer specific pool rate. */ ConnPoolInfo *infoPtr = WriterGetInfoPtr(curPtr, pools); infoPtr->currentPoolRate += curPtr->currentRate; Ns_Log(DriverDebug, "poollimit pool '%s' added rate poolLimit %d poolRate %d", curPtr->poolPtr->pool, curPtr->poolPtr->rate.poolLimit, infoPtr->currentPoolRate); } } /* * Now iterate over the pools used by this thread and sum the specific * pool rates from all writer threads. */ hPtr = Tcl_FirstHashEntry(pools, &search); while (hPtr != NULL) { ConnPool *poolPtr = (ConnPool *)Tcl_GetHashKey(pools, hPtr); int totalPoolRate, writerThreadCount, threadDeltaRate; ConnPoolInfo *infoPtr; /* * Compute the following indicators: * - totalPoolRate: accumulated pool rates from all writer threads. * * - threadDeltaRate: how much of the available bandwidth can i used * the current thread. We assume that the distribution of writers * between all writer threads is even, so we can split the * available rate by the number of writer threads working on this * pool. * * - deltaPercentage: adjust in a single iteration just a fraction * (e.g. 10 percent) of the potential change. This function is * called often enough to justify delayed adjustments. */ infoPtr = (ConnPoolInfo *)Tcl_GetHashValue(hPtr); totalPoolRate = NsPoolTotalRate(poolPtr, infoPtr->threadSlot, infoPtr->currentPoolRate, &writerThreadCount); /* * If nothing is going on, allow a thread the full rate. */ if (infoPtr->currentPoolRate == 0) { threadDeltaRate = (poolPtr->rate.poolLimit - totalPoolRate); } else { threadDeltaRate = (poolPtr->rate.poolLimit - totalPoolRate) / writerThreadCount; } infoPtr->deltaPercentage = threadDeltaRate / 10; if (infoPtr->deltaPercentage < -50) { infoPtr->deltaPercentage = -50; } if (totalPoolRate > 0) { Ns_Log(Notice, "... pool '%s' thread's pool rate %d total pool rate %d limit %d " "(#%d writer threads) -> computed rate %d (%d%%) ", NsPoolName(poolPtr->pool), infoPtr->currentPoolRate, totalPoolRate, poolPtr->rate.poolLimit, writerThreadCount, threadDeltaRate, infoPtr->deltaPercentage ); } hPtr = Tcl_NextHashEntry(&search); } } /* *---------------------------------------------------------------------- * * WriterThread -- * * Thread that writes files to clients. * * Results: * None. * * Side effects: * Connections are accepted and their SockPtr is set to NULL * such that closing actual connection does not close the socket. * *---------------------------------------------------------------------- */ static void WriterThread(void *arg) { SpoolerQueue *queuePtr = (SpoolerQueue*)arg; int err, pollTimeout; bool stopping; Ns_Time now; Sock *sockPtr; const Driver *drvPtr; WriterSock *curPtr, *nextPtr, *writePtr; PollData pdata; Tcl_HashTable pools; /* used for accumulating bandwidth per pool */ Ns_ThreadSetName("-writer%d-", queuePtr->id); queuePtr->threadName = Ns_ThreadGetName(); Tcl_InitHashTable(&pools, TCL_ONE_WORD_KEYS); /* * Loop forever until signaled to shut down and all * connections are complete and gracefully closed. */ Ns_Log(Notice, "writer%d: accepting connections", queuePtr->id); PollCreate(&pdata); writePtr = NULL; stopping = NS_FALSE; while (!stopping) { char charBuffer[1]; /* * If there are any write sockets, set the bits. */ PollReset(&pdata); (void)PollSet(&pdata, queuePtr->pipe[0], (short)POLLIN, NULL); if (writePtr == NULL) { pollTimeout = 30 * 1000; } else { /* * If per-pool bandwidth management is requested, compute the base * data for the adjustment. If there is no bandwidth management * requested, there is no slowdow. */ if (NsWriterBandwidthManagement) { WriterPerPoolRates(writePtr, &pools); } /* * There are writers active. Determine on which writers we poll * and compute the maximal poll wait time. */ pollTimeout = 1000; for (curPtr = writePtr; curPtr != NULL; curPtr = curPtr->nextPtr) { int sleepTimeMs = 0; Ns_Log(DriverDebug, "### Writer poll collect %p size %" PRIdz " streaming %d rateLimit %d", (void *)curPtr, curPtr->size, curPtr->doStream, curPtr->rateLimit); if (curPtr->rateLimit > 0 && curPtr->nsent > 0 && curPtr->currentRate > 0 ) { int currentMs, targetTimeMs; /* * Perform per-pool rate management, when * - a poolLimit is provided, * - we have performance data of thee pool, and * - changes are possible (as flagged by deltaPercentage). */ if (NsWriterBandwidthManagement && curPtr->poolPtr->rate.poolLimit > 0 && curPtr->infoPtr != NULL && curPtr->infoPtr->deltaPercentage != 0 ) { /* * Only adjust data for busy writer jobs, which * are close to their limits. */ bool onLimit = (curPtr->currentRate*100 / curPtr->rateLimit) > 90; Ns_Log(DriverDebug, "we allowed %d we use %d on limit %d (%d) , we can do %d%%", curPtr->rateLimit, curPtr->currentRate, (int)onLimit, curPtr->currentRate*100/curPtr->rateLimit, curPtr->infoPtr->deltaPercentage); if (onLimit) { /* * Compute new rate limit based on * positive/negative delta percentage. */ int newRate = curPtr->currentRate + (curPtr->currentRate * curPtr->infoPtr->deltaPercentage / 100); /* * Sanity checks: * - never allow more than poolLimit * - never kill connections completely (e.g. minRate 5KB/s) */ if (newRate > curPtr->poolPtr->rate.poolLimit) { newRate = curPtr->poolPtr->rate.poolLimit; } else if (newRate < 5) { newRate = 5; } Ns_Log(Notice, "... pool '%s' new rate limit changed from %d to %d KB/s (delta %d%%)", curPtr->poolPtr->pool, curPtr->rateLimit, newRate, curPtr->infoPtr->deltaPercentage); curPtr->rateLimit = newRate; } } /* * Adjust rate to the rate limit. */ currentMs = (int)(curPtr->nsent/(Tcl_WideInt)curPtr->currentRate); targetTimeMs = (int)(curPtr->nsent/(Tcl_WideInt)curPtr->rateLimit); sleepTimeMs = 1 + targetTimeMs - currentMs; Ns_Log(WriterDebug, "### Writer(%d)" " byte sent %" TCL_LL_MODIFIER "d msecs %d rate %d KB/s" " targetRate %d KB/s sleep %d", curPtr->sockPtr->sock, curPtr->nsent, currentMs, curPtr->currentRate, curPtr->rateLimit, sleepTimeMs); } if (likely(curPtr->size > 0u)) { if (sleepTimeMs <= 0) { SockPoll(curPtr->sockPtr, (short)POLLOUT, &pdata); pollTimeout = -1; } else { pollTimeout = MIN(sleepTimeMs, pollTimeout); } } else if (unlikely(curPtr->doStream == NS_WRITER_STREAM_FINISH)) { pollTimeout = -1; } } } Ns_Log(DriverDebug, "### Writer final pollTimeout %d", pollTimeout); /* * Select and drain the trigger pipe if necessary. */ (void) PollWait(&pdata, pollTimeout); if (PollIn(&pdata, 0) && unlikely(ns_recv(queuePtr->pipe[0], charBuffer, 1u, 0) != 1)) { Ns_Fatal("writer: trigger ns_recv() failed: %s", ns_sockstrerror(ns_sockerrno)); } /* * Write to all available sockets */ Ns_GetTime(&now); curPtr = writePtr; writePtr = NULL; while (curPtr != NULL) { NsWriterStreamState doStream; SpoolerState spoolerState = SPOOLER_OK; nextPtr = curPtr->nextPtr; sockPtr = curPtr->sockPtr; err = 0; /* * The truth value of doStream does not change through * concurrency. */ doStream = curPtr->doStream; if (unlikely(PollHup(&pdata, sockPtr->pidx))) { Ns_Log(DriverDebug, "### Writer %p reached POLLHUP fd %d", (void *)curPtr, sockPtr->sock); spoolerState = SPOOLER_CLOSE; err = 0; curPtr->infoPtr = WriterGetInfoPtr(curPtr, &pools); curPtr->infoPtr->currentPoolRate += curPtr->currentRate; } else if (likely(PollOut(&pdata, sockPtr->pidx)) || (doStream == NS_WRITER_STREAM_FINISH)) { /* * The socket is writable, we can compute the rate, when * something was sent already and some kind of rate limiting * is in place ... and we have sent enough data to make a good * estimate (just after the 2nd send, so more than driver * buffer size. */ Ns_Log(DriverDebug, "Socket of pool '%s' is writable, writer limit %d nsent %ld", curPtr->poolPtr->pool, curPtr->rateLimit, (long)curPtr->nsent); if (curPtr->rateLimit > 0 && (size_t)curPtr->nsent > curPtr->sockPtr->drvPtr->bufsize ) { Ns_Time diff; long currentMs; Ns_DiffTime(&now, &curPtr->startTime, &diff); currentMs = Ns_TimeToMilliseconds(&diff); if (currentMs > 0) { curPtr->currentRate = (int)((curPtr->nsent)/(Tcl_WideInt)currentMs); Ns_Log(DriverDebug, "Socket of pool '%s' is writable, currentMs %ld has updated current rate %d", curPtr->poolPtr->pool, currentMs,curPtr->currentRate); } } Ns_Log(DriverDebug, "### Writer %p can write to client fd %d (trigger %d) streaming %.6x" " size %" PRIdz " nsent %" TCL_LL_MODIFIER "d bufsize %" PRIdz, (void *)curPtr, sockPtr->sock, PollIn(&pdata, 0), doStream, curPtr->size, curPtr->nsent, curPtr->c.file.bufsize); if (unlikely(curPtr->size < 1u)) { /* * Size < 1 means that everything was sent. */ if (doStream != NS_WRITER_STREAM_ACTIVE) { if (doStream == NS_WRITER_STREAM_FINISH) { Ns_ReleaseTemp(curPtr->fd); } spoolerState = SPOOLER_CLOSE; } } else { /* * If size > 0, there is still something to send. * If we are spooling from a file, read some data * from the (spool) file and place it into curPtr->c.file.buf. */ if (curPtr->fd != NS_INVALID_FD) { spoolerState = WriterReadFromSpool(curPtr); } if (spoolerState == SPOOLER_OK) { spoolerState = WriterSend(curPtr, &err); } } } else { /* * Mark when first timeout occurred or check if it is already * for too long and we need to stop this socket */ if (sockPtr->timeout.sec == 0) { Ns_Log(DriverDebug, "Writer %p fd %d setting sendwait %ld.%6ld", (void *)curPtr, sockPtr->sock, curPtr->sockPtr->drvPtr->sendwait.sec, curPtr->sockPtr->drvPtr->sendwait.usec); SockTimeout(sockPtr, &now, &curPtr->sockPtr->drvPtr->sendwait); } else if (Ns_DiffTime(&sockPtr->timeout, &now, NULL) <= 0) { Ns_Log(DriverDebug, "Writer %p fd %d timeout", (void *)curPtr, sockPtr->sock); err = ETIMEDOUT; spoolerState = SPOOLER_CLOSETIMEOUT; } } /* * Check result status and close the socket in case of * timeout or completion */ Ns_MutexLock(&queuePtr->lock); if (spoolerState == SPOOLER_OK) { if (curPtr->size > 0u || doStream == NS_WRITER_STREAM_ACTIVE) { Ns_Log(DriverDebug, "Writer %p continue OK (size %" PRIdz ") => PUSH", (void *)curPtr, curPtr->size); Push(curPtr, writePtr); } else { Ns_Log(DriverDebug, "Writer %p done OK (size %" PRIdz ") => RELEASE", (void *)curPtr, curPtr->size); WriterSockRelease(curPtr); } } else { /* * spoolerState might be SPOOLER_CLOSE or SPOOLER_*TIMEOUT, or SPOOLER_*ERROR */ Ns_Log(DriverDebug, "Writer %p fd %d release, not OK (status %d) => RELEASE", (void *)curPtr, curPtr->sockPtr->sock, (int)spoolerState); curPtr->status = spoolerState; curPtr->err = err; WriterSockRelease(curPtr); } Ns_MutexUnlock(&queuePtr->lock); curPtr = nextPtr; } /* * Add more sockets to the writer queue */ if (queuePtr->sockPtr != NULL) { Ns_MutexLock(&queuePtr->lock); if (queuePtr->sockPtr != NULL) { curPtr = queuePtr->sockPtr; queuePtr->sockPtr = NULL; while (curPtr != NULL) { nextPtr = curPtr->nextPtr; sockPtr = curPtr->sockPtr; drvPtr = sockPtr->drvPtr; SockTimeout(sockPtr, &now, &drvPtr->sendwait); Push(curPtr, writePtr); queuePtr->queuesize++; curPtr = nextPtr; } queuePtr->curPtr = writePtr; } Ns_MutexUnlock(&queuePtr->lock); } /* * Check for shutdown */ stopping = queuePtr->shutdown; } PollFree(&pdata); { /* * Free ConnPoolInfo */ Tcl_HashSearch search; Tcl_HashEntry *hPtr = Tcl_FirstHashEntry(&pools, &search); while (hPtr != NULL) { ConnPoolInfo *infoPtr = (ConnPoolInfo *)Tcl_GetHashValue(hPtr); ns_free(infoPtr); hPtr = Tcl_NextHashEntry(&search); } /* * Delete the hash table for pools. */ Tcl_DeleteHashTable(&pools); } Ns_Log(Notice, "exiting"); Ns_MutexLock(&queuePtr->lock); queuePtr->stopped = NS_TRUE; Ns_CondBroadcast(&queuePtr->cond); Ns_MutexUnlock(&queuePtr->lock); } /* *---------------------------------------------------------------------- * * NsWriterFinish -- * * Finish a streaming writer job (typically called at the close * of a connection). A streaming writer job is fed typically by a * sequence of ns_write operations. After such an operation, the * WriterThread has to keep the writer job alive. * NsWriterFinish() tells the WriterThread that no more * other writer jobs will come from this connection. * * Results: * None. * * Side effects: * Change the state of the writer job and trigger the queue. * *---------------------------------------------------------------------- */ void NsWriterFinish(NsWriterSock *wrSockPtr) { WriterSock *writerSockPtr = (WriterSock *)wrSockPtr; NS_NONNULL_ASSERT(wrSockPtr != NULL); Ns_Log(DriverDebug, "NsWriterFinish: %p", (void *)writerSockPtr); writerSockPtr->doStream = NS_WRITER_STREAM_FINISH; SockTrigger(writerSockPtr->queuePtr->pipe[1]); } /* *---------------------------------------------------------------------- * * WriterSetupStreamingMode -- * * In streaming mode, setup a temporary fd which is used as input and * output. Streaming i/o will append to the file, while the write will * read from it. * * Results: * Ns_ReturnCode (NS_OK, NS_ERROR, NS_FILTER_BREAK). In the last case * signals that all processing was already performed and the caller can * stop handling more data. On success, the function returns an fd as * last argument. * * Side effects: * Potentially allocating temp file and updating connPtr members. * *---------------------------------------------------------------------- */ Ns_ReturnCode WriterSetupStreamingMode(Conn *connPtr, struct iovec *bufs, int nbufs, int *fdPtr) { bool first; size_t wrote = 0u; WriterSock *wrSockPtr1; Ns_ReturnCode status = NS_OK; NS_NONNULL_ASSERT(connPtr != NULL); NS_NONNULL_ASSERT(bufs != NULL); NS_NONNULL_ASSERT(fdPtr != NULL); Ns_Log(DriverDebug, "NsWriterQueue: streaming writer job"); if (connPtr->fd == 0) { /* * Create a new temporary spool file and provide the fd to the * connection thread via connPtr. */ first = NS_TRUE; wrSockPtr1 = NULL; *fdPtr = Ns_GetTemp(); connPtr->fd = *fdPtr; Ns_Log(DriverDebug, "NsWriterQueue: new tmp file has fd %d", *fdPtr); } else { /* * Reuse previously created spool file. */ first = NS_FALSE; wrSockPtr1 = WriterSockRequire(connPtr); if (wrSockPtr1 == NULL) { Ns_Log(Notice, "NsWriterQueue: writer job was already canceled (fd %d); maybe user dropped connection", connPtr->fd); return NS_ERROR; } else { /* * lock only, when first == NS_FALSE. */ Ns_MutexLock(&wrSockPtr1->c.file.fdlock); (void)ns_lseek(connPtr->fd, 0, SEEK_END); } } /* * For the time being, handle just "string data" in streaming * output (iovec bufs). Write the content to the spool file. */ { int i; for (i = 0; i < nbufs; i++) { ssize_t j = ns_write(connPtr->fd, bufs[i].iov_base, bufs[i].iov_len); if (j > 0) { wrote += (size_t)j; Ns_Log(Debug, "NsWriterQueue: fd %d [%d] spooled %" PRIdz " of %" PRIiovlen " OK %d", connPtr->fd, i, j, bufs[i].iov_len, (j == (ssize_t)bufs[i].iov_len)); } else { Ns_Log(Warning, "NsWriterQueue: spool to fd %d write operation failed", connPtr->fd); } } } if (first) { //bufs = NULL; connPtr->nContentSent = wrote; #ifndef _WIN32 /* * sock_set_blocking can't be used under windows, since sockets * are under windows no file descriptors. */ (void)ns_sock_set_blocking(connPtr->fd, NS_FALSE); #endif /* * Fall through to register stream writer with temp file */ } else { WriterSock *writerSockPtr; /* * This is a later streaming operation, where the writer job * (strWriter) was previously established. */ assert(wrSockPtr1 != NULL); /* * Update the controlling variables (size and toread) in the connPtr, * and the length info for the access log, and trigger the writer to * notify it about the change. */ writerSockPtr = (WriterSock *)connPtr->strWriter; writerSockPtr->size += wrote; writerSockPtr->c.file.toRead += wrote; Ns_MutexUnlock(&wrSockPtr1->c.file.fdlock); connPtr->nContentSent += wrote; if (likely(wrSockPtr1->queuePtr != NULL)) { SockTrigger(wrSockPtr1->queuePtr->pipe[1]); } WriterSockRelease(wrSockPtr1); status = NS_FILTER_BREAK; } return status; } /* *---------------------------------------------------------------------- * * NsWriterQueue -- * * Submit a new job to the writer queue. * * Results: * * NS_ERROR means that the Writer thread refuses to accept this * job and that the client (the connection thread) has to handle * this data. NS_OK means that the Writer thread cares for * transmitting the content to the client. * * Side effects: * Potentially adding a job to the writer queue. * *---------------------------------------------------------------------- */ Ns_ReturnCode NsWriterQueue(Ns_Conn *conn, size_t nsend, Tcl_Channel chan, FILE *fp, int fd, struct iovec *bufs, int nbufs, const Ns_FileVec *filebufs, int nfilebufs, bool everysize) { Conn *connPtr; WriterSock *wrSockPtr; SpoolerQueue *queuePtr; DrvWriter *wrPtr; bool trigger = NS_FALSE; size_t headerSize; Ns_ReturnCode status = NS_OK; Ns_FileVec *fbufs = NULL; int nfbufs = 0; NS_NONNULL_ASSERT(conn != NULL); connPtr = (Conn *)conn; if (unlikely(connPtr->sockPtr == NULL)) { Ns_Log(Warning, "NsWriterQueue: called without sockPtr size %" PRIdz " bufs %d flags %.6x stream %.6x chan %p fd %d", nsend, nbufs, connPtr->flags, connPtr->flags & NS_CONN_STREAM, (void *)chan, fd); status = NS_ERROR; wrPtr = NULL; } else { wrPtr = &connPtr->sockPtr->drvPtr->writer; Ns_Log(DriverDebug, "NsWriterQueue: size %" PRIdz " bufs %p (%d) flags %.6x stream %.6x chan %p fd %d thread %d", nsend, (void *)bufs, nbufs, connPtr->flags, connPtr->flags & NS_CONN_STREAM, (void *)chan, fd, wrPtr->threads); if (unlikely(wrPtr->threads == 0)) { Ns_Log(DriverDebug, "NsWriterQueue: no writer threads configured"); status = NS_ERROR; } else if (nsend < (size_t)wrPtr->writersize && !everysize && connPtr->fd == 0) { Ns_Log(DriverDebug, "NsWriterQueue: file is too small(%" PRIdz " < %" PRIdz ")", nsend, wrPtr->writersize); status = NS_ERROR; } } if (status != NS_OK) { return status; } assert(wrPtr != NULL); /* * In streaming mode, setup a temporary fd which is used as input and * output. Streaming i/o will append to the file, while the write will * read from it. */ if (((connPtr->flags & NS_CONN_STREAM) != 0u) || connPtr->fd > 0) { if (wrPtr->doStream == NS_WRITER_STREAM_NONE) { status = NS_ERROR; } else if (unlikely(fp != NULL || fd != NS_INVALID_FD)) { Ns_Log(DriverDebug, "NsWriterQueue: does not stream from this source via writer"); status = NS_ERROR; } else { status = WriterSetupStreamingMode(connPtr, bufs, nbufs, &fd); } if (unlikely(status != NS_OK)) { if (status == NS_FILTER_BREAK) { status = NS_OK; } return status; } /* * As a result of successful WriterSetupStreamingMode(), we have fd * set. */ assert(fd != NS_INVALID_FD); } else { if (fp != NULL) { /* * The client provided an open file pointer and closes it */ fd = ns_dup(fileno(fp)); } else if (fd != NS_INVALID_FD) { /* * The client provided an open file descriptor and closes it */ fd = ns_dup(fd); } else if (chan != NULL) { ClientData clientData; /* * The client provided an open Tcl channel and closes it */ if (Tcl_GetChannelHandle(chan, TCL_READABLE, &clientData) != TCL_OK) { return NS_ERROR; } fd = ns_dup(PTR2INT(clientData)); } else if (filebufs != NULL && nfilebufs > 0) { /* * The client provided Ns_FileVec with open files. The client is * responsible for closing it, like in all other cases. */ size_t i; /* * This is the only case, where fbufs will be != NULL, * i.e. keeping a duplicate of the passed-in Ns_FileVec structure * for which the client is responsible. */ fbufs = (Ns_FileVec *)ns_calloc((size_t)nfilebufs, sizeof(Ns_FileVec)); nfbufs = nfilebufs; for (i = 0u; i < (size_t)nfilebufs; i++) { fbufs[i].fd = ns_dup(filebufs[i].fd); fbufs[i].length = filebufs[i].length; fbufs[i].offset = filebufs[i].offset; } /* * Place the fd of the first Ns_FileVec to fd. */ fd = fbufs[0].fd; Ns_Log(DriverDebug, "NsWriterQueue: filevec mode, take first fd %d tosend %lu", fd, nsend); } } Ns_Log(DriverDebug, "NsWriterQueue: writer threads %d nsend %" PRIdz " writersize %" PRIdz, wrPtr->threads, nsend, wrPtr->writersize); assert(connPtr->poolPtr != NULL); connPtr->poolPtr->stats.spool++; wrSockPtr = (WriterSock *)ns_calloc(1u, sizeof(WriterSock)); wrSockPtr->sockPtr = connPtr->sockPtr; wrSockPtr->poolPtr = connPtr->poolPtr; /* just for being able to trace back the origin, e.g. list */ wrSockPtr->sockPtr->timeout.sec = 0; wrSockPtr->flags = connPtr->flags; wrSockPtr->refCount = 1; /* * Take the rate limit from the connection. */ wrSockPtr->rateLimit = connPtr->rateLimit; if (wrSockPtr->rateLimit == -1) { /* * The value was not specified via connection. Use either the pool * limit as a base for the computation or fall back to the driver * default value. */ if (connPtr->poolPtr->rate.poolLimit > 0) { /* * Very optimistic start value, but values will float through via * bandwidth management. */ wrSockPtr->rateLimit = connPtr->poolPtr->rate.poolLimit / 2; } else { wrSockPtr->rateLimit = wrPtr->rateLimit; } } Ns_Log(WriterDebug, "### Writer(%d): initial rate limit %d KB/s", wrSockPtr->sockPtr->sock, wrSockPtr->rateLimit); /* * Make sure we have proper content length header for * keep-alive/pipelining. */ Ns_ConnSetLengthHeader(conn, nsend, (wrSockPtr->flags & NS_CONN_STREAM) != 0u); /* * Flush the headers */ if ((conn->flags & NS_CONN_SENTHDRS) == 0u) { Tcl_DString ds; Ns_DStringInit(&ds); Ns_Log(DriverDebug, "### Writer(%d): add header", fd); conn->flags |= NS_CONN_SENTHDRS; (void)Ns_CompleteHeaders(conn, nsend, 0u, &ds); headerSize = (size_t)Ns_DStringLength(&ds); if (headerSize > 0u) { wrSockPtr->headerString = ns_strdup(Tcl_DStringValue(&ds)); } Ns_DStringFree(&ds); } else { headerSize = 0u; } if (fd != NS_INVALID_FD) { /* maybe add mmap support for files (fd != NS_INVALID_FD) */ wrSockPtr->fd = fd; wrSockPtr->c.file.bufs = fbufs; wrSockPtr->c.file.nbufs = nfbufs; Ns_Log(DriverDebug, "### Writer(%d) tosend %" PRIdz " files %d bufsize %" PRIdz, fd, nsend, nfbufs, wrPtr->bufsize); if (unlikely(headerSize >= wrPtr->bufsize)) { /* * We have a header which is larger than bufsize; place it * as "leftover" and use the headerString as buffer for file * reads (rather rare case) */ wrSockPtr->c.file.buf = (unsigned char *)wrSockPtr->headerString; wrSockPtr->c.file.maxsize = headerSize; wrSockPtr->c.file.bufsize = headerSize; wrSockPtr->headerString = NULL; } else if (headerSize > 0u) { /* * We have a header that fits into the bufsize; place it * as "leftover" at the end of the buffer. */ wrSockPtr->c.file.buf = ns_malloc(wrPtr->bufsize); memcpy(wrSockPtr->c.file.buf, wrSockPtr->headerString, headerSize); wrSockPtr->c.file.bufsize = headerSize; wrSockPtr->c.file.maxsize = wrPtr->bufsize; ns_free(wrSockPtr->headerString); wrSockPtr->headerString = NULL; } else { assert(wrSockPtr->headerString == NULL); wrSockPtr->c.file.buf = ns_malloc(wrPtr->bufsize); wrSockPtr->c.file.maxsize = wrPtr->bufsize; } wrSockPtr->c.file.bufoffset = 0; wrSockPtr->c.file.toRead = nsend; } else if (bufs != NULL) { int i, j, headerbufs = (headerSize > 0u ? 1 : 0); wrSockPtr->fd = NS_INVALID_FD; if (nbufs+headerbufs < UIO_SMALLIOV) { wrSockPtr->c.mem.bufs = wrSockPtr->c.mem.preallocated_bufs; } else { Ns_Log(DriverDebug, "NsWriterQueue: alloc %d iovecs", nbufs); wrSockPtr->c.mem.bufs = ns_calloc((size_t)nbufs + (size_t)headerbufs, sizeof(struct iovec)); } wrSockPtr->c.mem.nbufs = nbufs+headerbufs; if (headerbufs != 0) { wrSockPtr->c.mem.bufs[0].iov_base = wrSockPtr->headerString; wrSockPtr->c.mem.bufs[0].iov_len = headerSize; } if (connPtr->fmap.addr != NULL) { Ns_Log(DriverDebug, "NsWriterQueue: deliver fmapped %p", (void *)connPtr->fmap.addr); /* * Deliver an mmapped file, no need to copy content */ for (i = 0, j=headerbufs; i < nbufs; i++, j++) { wrSockPtr->c.mem.bufs[j].iov_base = bufs[i].iov_base; wrSockPtr->c.mem.bufs[j].iov_len = bufs[i].iov_len; } /* * Make a copy of the fmap structure and make clear that * we unmap in the writer thread. */ wrSockPtr->c.mem.fmap = connPtr->fmap; connPtr->fmap.addr = NULL; /* header string will be freed via wrSockPtr->headerString */ } else { /* * Deliver a content from iovec. The lifetime of the * source is unknown, we have to copy the c. */ for (i = 0, j=headerbufs; i < nbufs; i++, j++) { wrSockPtr->c.mem.bufs[j].iov_base = ns_malloc(bufs[i].iov_len); wrSockPtr->c.mem.bufs[j].iov_len = bufs[i].iov_len; memcpy(wrSockPtr->c.mem.bufs[j].iov_base, bufs[i].iov_base, bufs[i].iov_len); } /* header string will be freed a buf[0] */ wrSockPtr->headerString = NULL; } } else { ns_free(wrSockPtr); return NS_ERROR; } /* * Add header size to total size. */ nsend += headerSize; if (connPtr->clientData != NULL) { wrSockPtr->clientData = ns_strdup(connPtr->clientData); } wrSockPtr->startTime = *Ns_ConnStartTime(conn); /* * Setup streaming context before sending potentially headers. */ if ((wrSockPtr->flags & NS_CONN_STREAM) != 0u) { wrSockPtr->doStream = NS_WRITER_STREAM_ACTIVE; assert(connPtr->strWriter == NULL); /* * Add a reference to the stream writer to the connection such * it can efficiently append to a stream when multiple output * operations happen. The backpointer (from the stream writer * to the connection is needed to clear the reference to the * writer in case the writer is deleted. No locks are needed, * since nobody can share this structure yet. */ connPtr->strWriter = (NsWriterSock *)wrSockPtr; wrSockPtr->connPtr = connPtr; } /* * Tell connection, that writer handles the output (including * closing the connection to the client). */ connPtr->flags |= NS_CONN_SENT_VIA_WRITER; wrSockPtr->keep = connPtr->keep > 0 ? NS_TRUE : NS_FALSE; wrSockPtr->size = nsend; Ns_Log(DriverDebug, "NsWriterQueue NS_CONN_SENT_VIA_WRITER connPtr %p", (void*)connPtr); if ((wrSockPtr->flags & NS_CONN_STREAM) == 0u) { Ns_Log(DriverDebug, "NsWriterQueue NS_CONN_SENT_VIA_WRITER connPtr %p clear sockPtr %p", (void*)connPtr, (void*)connPtr->sockPtr); connPtr->sockPtr = NULL; connPtr->flags |= NS_CONN_CLOSED; connPtr->nContentSent = nsend - headerSize; } /* * Get the next writer thread from the list, all writer requests are * rotated between all writer threads */ Ns_MutexLock(&wrPtr->lock); if (wrPtr->curPtr == NULL) { wrPtr->curPtr = wrPtr->firstPtr; } queuePtr = wrPtr->curPtr; wrPtr->curPtr = wrPtr->curPtr->nextPtr; Ns_MutexUnlock(&wrPtr->lock); Ns_Log(WriterDebug, "Writer(%d): started: id=%d fd=%d, " "size=%" PRIdz ", flags=%X, rate %d KB/s: %s", wrSockPtr->sockPtr->sock, queuePtr->id, wrSockPtr->fd, nsend, wrSockPtr->flags, wrSockPtr->rateLimit, connPtr->request.line); /* * Now add new writer socket to the writer thread's queue */ wrSockPtr->queuePtr = queuePtr; Ns_MutexLock(&queuePtr->lock); if (queuePtr->sockPtr == NULL) { trigger = NS_TRUE; } Push(wrSockPtr, queuePtr->sockPtr); Ns_MutexUnlock(&queuePtr->lock); /* * Wake up writer thread */ if (trigger) { SockTrigger(queuePtr->pipe[1]); } return NS_OK; } /* *---------------------------------------------------------------------- * * DriverWriterFromObj -- * * Lookup driver by name and return its DrvWriter. When driverObj is * NULL, get the driver from the conn. * * Results: * Ns_ReturnCode * * Side effects: * Set error message in interp in case of failure. * *---------------------------------------------------------------------- */ static Ns_ReturnCode DriverWriterFromObj( Tcl_Interp *interp, Tcl_Obj *driverObj, Ns_Conn *conn, DrvWriter **wrPtrPtr) { Driver *drvPtr; const char *driverName = NULL; int driverNameLen = 0; DrvWriter *wrPtr = NULL; Ns_ReturnCode result; /* * If no driver is provided, take the current driver. The caller has * to make sure that in cases, where no driver is specified, the * command is run in a connection thread. */ if (driverObj == NULL) { if (conn != NULL) { driverName = Ns_ConnDriverName(conn); driverNameLen = (int)strlen(driverName); } } else { driverName = Tcl_GetStringFromObj(driverObj, &driverNameLen); } if (driverName != NULL) { for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) { if (strncmp(driverName, drvPtr->threadName, (size_t)driverNameLen) == 0) { if (drvPtr->writer.firstPtr != NULL) { wrPtr = &drvPtr->writer; } break; } } } if (unlikely(wrPtr == NULL)) { Ns_TclPrintfResult(interp, "no writer configured for a driver with name %s", driverName); result = NS_ERROR; } else { *wrPtrPtr = wrPtr; result = NS_OK; } return result; } /* *---------------------------------------------------------------------- * * WriterSubmitObjCmd - subcommand of NsTclWriterObjCmd -- * * Implements "ns_writer submit" command. * Send the provided data to the client. * * Results: * Standard Tcl result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int WriterSubmitObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { int result = TCL_OK; Ns_Conn *conn; Tcl_Obj *dataObj; Ns_ObjvSpec args[] = { {"data", Ns_ObjvObj, &dataObj, NULL}, {NULL, NULL, NULL, NULL} }; if (Ns_ParseObjv(NULL, args, interp, 2, objc, objv) != NS_OK || NsConnRequire(interp, NS_CONN_REQUIRE_ALL, &conn) != NS_OK) { result = TCL_ERROR; } else { int size; unsigned char *data = Tcl_GetByteArrayFromObj(dataObj, &size); if (data != NULL) { struct iovec vbuf; Ns_ReturnCode status; vbuf.iov_base = (void *)data; vbuf.iov_len = (size_t)size; status = NsWriterQueue(conn, (size_t)size, NULL, NULL, NS_INVALID_FD, &vbuf, 1, NULL, 0, NS_TRUE); Tcl_SetObjResult(interp, Tcl_NewBooleanObj(status == NS_OK ? 1 : 0)); } } return result; } /* *---------------------------------------------------------------------- * * WriterCheckInputParams - * * Helper command for WriterSubmitFileObjCmd and WriterSubmitFilesObjCmd * to check validity of filename, offset and size. * * Results: * Standard Tcl result. Returns on success also fd and nrbytes. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int WriterCheckInputParams(Tcl_Interp *interp, const char *filenameString, size_t size, off_t offset, int *fdPtr, size_t *nrbytesPtr) { int result = TCL_OK, rc; struct stat st; Ns_Log(DriverDebug, "WriterCheckInputParams %s offset %" PROTd " size %" PRIdz, filenameString, offset, size); /* * Use stat() call to obtain information about the actual file to check * later the plausibility of the parameters. */ rc = stat(filenameString, &st); if (unlikely(rc != 0)) { Ns_TclPrintfResult(interp, "file does not exist '%s'", filenameString); result = TCL_ERROR; } else { size_t nrbytes = 0u; int fd; /* * Try to open the file and check offset and size parameters. */ fd = ns_open(filenameString, O_RDONLY | O_CLOEXEC, 0); if (unlikely(fd == NS_INVALID_FD)) { Ns_TclPrintfResult(interp, "could not open file '%s'", filenameString); result = TCL_ERROR; } else if (unlikely(offset > st.st_size) || offset < 0) { Ns_TclPrintfResult(interp, "offset must be a positive value less or equal filesize"); result = TCL_ERROR; } else if (size > 0) { if (unlikely((off_t)size + offset > st.st_size)) { Ns_TclPrintfResult(interp, "offset + size must be less or equal filesize"); result = TCL_ERROR; } else { nrbytes = (size_t)size; } } else { nrbytes = (size_t)st.st_size - (size_t)offset; } /* * When an offset is provide, jump to this offset. */ if (offset > 0 && result == TCL_OK) { if (ns_lseek(fd, (off_t)offset, SEEK_SET) == -1) { Ns_TclPrintfResult(interp, "cannot seek to position %ld", (long)offset); result = TCL_ERROR; } } if (result == TCL_OK) { *fdPtr = fd; *nrbytesPtr = nrbytes; } else if (fd != NS_INVALID_FD) { /* * On invalid parameters, close the fd. */ ns_close(fd); } } return result; } /* *---------------------------------------------------------------------- * * WriterSubmitFileObjCmd - subcommand of NsTclWriterObjCmd -- * * Implements "ns_writer submitfile" command. * Send the provided file to the client. * * Results: * Standard Tcl result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int WriterSubmitFileObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { int result = TCL_OK; Ns_Conn *conn; char *fileNameString; int headers = 0; Tcl_WideInt offset = 0, size = 0; Ns_ObjvValueRange offsetRange = {0, LLONG_MAX}; Ns_ObjvValueRange sizeRange = {1, LLONG_MAX}; Ns_ObjvSpec lopts[] = { {"-headers", Ns_ObjvBool, &headers, INT2PTR(NS_TRUE)}, {"-offset", Ns_ObjvMemUnit, &offset, &offsetRange}, {"-size", Ns_ObjvMemUnit, &size, &sizeRange}, {NULL, NULL, NULL, NULL} }; Ns_ObjvSpec args[] = { {"file", Ns_ObjvString, &fileNameString, NULL}, {NULL, NULL, NULL, NULL} }; if (unlikely(Ns_ParseObjv(lopts, args, interp, 2, objc, objv) != NS_OK) || NsConnRequire(interp, NS_CONN_REQUIRE_ALL, &conn) != NS_OK) { result = TCL_ERROR; } else if (unlikely( Ns_ConnSockPtr(conn) == NULL )) { Ns_Log(Warning, "NsWriterQueue: called without valid sockPtr, maybe connection already closed"); Ns_TclPrintfResult(interp, "0"); result = TCL_OK; } else { size_t nrbytes = 0u; int fd = NS_INVALID_FD; result = WriterCheckInputParams(interp, fileNameString, (size_t)size, offset, &fd, &nrbytes); if (likely(result == TCL_OK)) { Ns_ReturnCode status; /* * The caller requested that we build required headers */ if (headers != 0) { Ns_ConnSetTypeHeader(conn, Ns_GetMimeType(fileNameString)); } status = NsWriterQueue(conn, nrbytes, NULL, NULL, fd, NULL, 0, NULL, 0, NS_TRUE); Tcl_SetObjResult(interp, Tcl_NewBooleanObj(status == NS_OK ? 1 : 0)); if (fd != NS_INVALID_FD) { (void) ns_close(fd); } else { Ns_Log(Warning, "WriterSubmitFileObjCmd called with invalid fd"); } } else if (fd != NS_INVALID_FD) { (void) ns_close(fd); } } return result; } /* *---------------------------------------------------------------------- * * WriterGetMemunitFromDict -- * * Helper function to obtain a memory unit from a dict structure, * optionally checking the value range. * * Results: * Standard Tcl result. * * Side effects: * On errors, an error message is left in the interpreter. * *---------------------------------------------------------------------- */ static int WriterGetMemunitFromDict(Tcl_Interp *interp, Tcl_Obj *dictObj, Tcl_Obj *keyObj, Ns_ObjvValueRange *rangePtr, Tcl_WideInt *valuePtr) { Tcl_Obj *intObj = NULL; int result; NS_NONNULL_ASSERT(interp != NULL); NS_NONNULL_ASSERT(dictObj != NULL); NS_NONNULL_ASSERT(keyObj != NULL); NS_NONNULL_ASSERT(valuePtr != NULL); result = Tcl_DictObjGet(interp, dictObj, keyObj, &intObj); if (result == TCL_OK && intObj != NULL) { result = Ns_TclGetMemUnitFromObj(interp, intObj, valuePtr); if (result == TCL_OK && rangePtr != NULL) { result = Ns_CheckWideRange(interp, Tcl_GetString(keyObj), rangePtr, *valuePtr); } } return result; } /* *---------------------------------------------------------------------- * * WriterSubmitFilesObjCmd - subcommand of NsTclWriterObjCmd -- * * Implements "ns_writer submitfiles" command. Send the provided files * to the client. "files" are provided as a list of dicts, where every * dict must contain a "filename" element and can contain an "-offset" * and/or a "-length" element. * * Results: * Standard Tcl result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int WriterSubmitFilesObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { int result = TCL_OK; Ns_Conn *conn; int headers = 0, nrFiles; Tcl_Obj *filesObj = NULL, **fileObjv; Ns_ObjvSpec lopts[] = { {"-headers", Ns_ObjvBool, &headers, INT2PTR(NS_TRUE)}, {NULL, NULL, NULL, NULL} }; Ns_ObjvSpec args[] = { {"files", Ns_ObjvObj, &filesObj, NULL}, {NULL, NULL, NULL, NULL} }; if (unlikely(Ns_ParseObjv(lopts, args, interp, 2, objc, objv) != NS_OK) || NsConnRequire(interp, NS_CONN_REQUIRE_ALL, &conn) != NS_OK) { result = TCL_ERROR; } else if (unlikely( Ns_ConnSockPtr(conn) == NULL )) { Ns_Log(Warning, "NsWriterQueue: called without valid sockPtr, " "maybe connection already closed"); Ns_TclPrintfResult(interp, "0"); result = TCL_OK; } else if (Tcl_ListObjGetElements(interp, filesObj, &nrFiles, &fileObjv) != TCL_OK) { Ns_TclPrintfResult(interp, "not a valid list of files: '%s'", Tcl_GetString(filesObj)); result = TCL_ERROR; } else if (nrFiles == 0) { Ns_TclPrintfResult(interp, "The provided list has to contain at least one file spec"); result = TCL_ERROR; } else { size_t totalbytes = 0u, i; Tcl_Obj *keys[3], *filenameObj = NULL; Ns_FileVec *filebufs; const char *firstFilenameString = NULL; Ns_ObjvValueRange offsetRange = {0, LLONG_MAX}; Ns_ObjvValueRange sizeRange = {1, LLONG_MAX}; filebufs = (Ns_FileVec *)ns_calloc((size_t)nrFiles, sizeof(Ns_FileVec)); keys[0] = Tcl_NewStringObj("filename", 8); keys[1] = Tcl_NewStringObj("-offset", 7); keys[2] = Tcl_NewStringObj("-size", 5); Tcl_IncrRefCount(keys[0]); Tcl_IncrRefCount(keys[1]); Tcl_IncrRefCount(keys[2]); for (i = 0u; i < (size_t)nrFiles; i++) { filebufs[i].fd = NS_INVALID_FD; } /* * Iterate over the list of dicts. */ for (i = 0u; i < (size_t)nrFiles; i++) { Tcl_WideInt offset = 0, size = 0; int rc, fd = NS_INVALID_FD; const char *filenameString; size_t nrbytes; /* * Get required "filename" element. */ filenameObj = NULL; rc = Tcl_DictObjGet(interp, fileObjv[i], keys[0], &filenameObj); if (rc != TCL_OK || filenameObj == NULL) { Ns_TclPrintfResult(interp, "missing filename in dict '%s'", Tcl_GetString(fileObjv[i])); result = TCL_ERROR; break; } filenameString = Tcl_GetString(filenameObj); if (firstFilenameString == NULL) { firstFilenameString = filenameString; } /* * Get optional "-offset" and "-size" elements. */ if (WriterGetMemunitFromDict(interp, fileObjv[i], keys[1], &offsetRange, &offset) != TCL_OK) { result = TCL_ERROR; break; } if (WriterGetMemunitFromDict(interp, fileObjv[i], keys[2], &sizeRange, &size) != TCL_OK) { result = TCL_ERROR; break; } /* * Check validity of the provided values */ result = WriterCheckInputParams(interp, Tcl_GetString(filenameObj), (size_t)size, (off_t)offset, &fd, &nrbytes); if (result != TCL_OK) { break; } filebufs[i].fd = fd; filebufs[i].offset = offset; filebufs[i].length = nrbytes; totalbytes = totalbytes + (size_t)nrbytes; } Tcl_DecrRefCount(keys[0]); Tcl_DecrRefCount(keys[1]); Tcl_DecrRefCount(keys[2]); /* * If everything is ok, submit the request to the writer queue. */ if (result == TCL_OK) { Ns_ReturnCode status; if (headers != 0 && firstFilenameString != NULL) { Ns_ConnSetTypeHeader(conn, Ns_GetMimeType(firstFilenameString)); } status = NsWriterQueue(conn, totalbytes, NULL, NULL, NS_INVALID_FD, NULL, 0, filebufs, nrFiles, NS_TRUE); /* * Provide a soft error like for "ns_writer submitfile". */ Tcl_SetObjResult(interp, Tcl_NewBooleanObj(status == NS_OK ? 1 : 0)); } /* * The NsWriterQueue() API makes the usual duplicates of the file * descriptors and the Ns_FileVec structure, so we have to cleanup * here. */ for (i = 0u; i < (size_t)nrFiles; i++) { if (filebufs[i].fd != NS_INVALID_FD) { (void) ns_close(filebufs[i].fd); } } ns_free(filebufs); } return result; } /* *---------------------------------------------------------------------- * * WriterListObjCmd - subcommand of NsTclWriterObjCmd -- * * Implements "ns_writer list" command. * List the current writer jobs. * * Results: * Standard Tcl result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int WriterListObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { int result = TCL_OK; NsServer *servPtr = NULL; Ns_ObjvSpec lopts[] = { {"-server", Ns_ObjvServer, &servPtr, NULL}, {NULL, NULL, NULL, NULL} }; if (unlikely(Ns_ParseObjv(lopts, NULL, interp, 2, objc, objv) != NS_OK)) { result = TCL_ERROR; } else { Tcl_DString ds, *dsPtr = &ds; const Driver *drvPtr; SpoolerQueue *queuePtr; Tcl_DStringInit(dsPtr); for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) { const DrvWriter *wrPtr; /* * If server was specified, list only results from this server. */ if (servPtr != NULL && servPtr != drvPtr->servPtr) { continue; } wrPtr = &drvPtr->writer; queuePtr = wrPtr->firstPtr; while (queuePtr != NULL) { const WriterSock *wrSockPtr; Ns_MutexLock(&queuePtr->lock); wrSockPtr = queuePtr->curPtr; while (wrSockPtr != NULL) { char ipString[NS_IPADDR_SIZE]; ns_inet_ntop((struct sockaddr *)&(wrSockPtr->sockPtr->sa), ipString,sizeof(ipString)); (void) Ns_DStringNAppend(dsPtr, "{", 1); (void) Ns_DStringAppendTime(dsPtr, &wrSockPtr->startTime); (void) Ns_DStringNAppend(dsPtr, " ", 1); (void) Ns_DStringAppend(dsPtr, queuePtr->threadName); (void) Ns_DStringNAppend(dsPtr, " ", 1); (void) Ns_DStringAppend(dsPtr, drvPtr->threadName); (void) Ns_DStringNAppend(dsPtr, " ", 1); (void) Ns_DStringAppend(dsPtr, NsPoolName(wrSockPtr->poolPtr->pool)); (void) Ns_DStringNAppend(dsPtr, " ", 1); (void) Ns_DStringAppend(dsPtr, ipString); (void) Ns_DStringPrintf(dsPtr, " %d %" PRIdz " %" TCL_LL_MODIFIER "d %d %d ", wrSockPtr->fd, wrSockPtr->size, wrSockPtr->nsent, wrSockPtr->currentRate, wrSockPtr->rateLimit); (void) Ns_DStringAppendElement(dsPtr, (wrSockPtr->clientData != NULL) ? wrSockPtr->clientData : NS_EMPTY_STRING); (void) Ns_DStringNAppend(dsPtr, "} ", 2); wrSockPtr = wrSockPtr->nextPtr; } Ns_MutexUnlock(&queuePtr->lock); queuePtr = queuePtr->nextPtr; } } Tcl_DStringResult(interp, &ds); } return result; } /* *---------------------------------------------------------------------- * * WriterSizeObjCmd - subcommand of NsTclWriterObjCmd -- * * Implements "ns_writer size" command. * Sets or queries size limit for sending via writer. * * Results: * Standard Tcl result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int WriterSizeObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { int result = TCL_OK; Tcl_Obj *driverObj = NULL; Ns_Conn *conn = NULL; Tcl_WideInt intValue = -1; const char *firstArgString; Ns_ObjvValueRange range = {1024, INT_MAX}; Ns_ObjvSpec *opts, optsNew[] = { {"-driver", Ns_ObjvObj, &driverObj, NULL}, {NULL, NULL, NULL, NULL} }; Ns_ObjvSpec *args, argsNew[] = { {"?value", Ns_ObjvMemUnit, &intValue, &range}, {NULL, NULL, NULL, NULL} }; Ns_ObjvSpec argsLegacy[] = { {"driver", Ns_ObjvObj, &driverObj, NULL}, {"?value", Ns_ObjvMemUnit, &intValue, &range}, {NULL, NULL, NULL, NULL} }; firstArgString = objc > 2 ? Tcl_GetString(objv[2]) : NULL; if (firstArgString != NULL) { if (*firstArgString != '-' && ((objc == 3 && CHARTYPE(digit, *firstArgString) == 0) || objc == 4)) { args = argsLegacy; opts = NULL; Ns_LogDeprecated(objv, objc, "ns_writer size ?-driver drv? ?size?", NULL); } else { args = argsNew; opts = optsNew; } } else { args = argsNew; opts = optsNew; } if (Ns_ParseObjv(opts, args, interp, 2, objc, objv) != NS_OK) { result = TCL_ERROR; } else if ((driverObj == NULL) && NsConnRequire(interp, NS_CONN_REQUIRE_ALL, &conn) != NS_OK) { result = TCL_ERROR; } else { DrvWriter *wrPtr; if (DriverWriterFromObj(interp, driverObj, conn, &wrPtr) != NS_OK) { result = TCL_ERROR; } else if (intValue != -1) { /* * The optional argument was provided. */ wrPtr->writersize = (size_t)intValue; } if (result == TCL_OK) { Tcl_SetObjResult(interp, Tcl_NewIntObj((int)wrPtr->writersize)); } } return result; } /* *---------------------------------------------------------------------- * * WriterStreamingObjCmd - subcommand of NsTclWriterObjCmd -- * * Implements "ns_writer streaming" command. * Sets or queries streaming state of the writer. * * Results: * Standard Tcl result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int WriterStreamingObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { int boolValue = -1, result = TCL_OK; Tcl_Obj *driverObj = NULL; Ns_Conn *conn = NULL; const char *firstArgString; Ns_ObjvSpec *opts, optsNew[] = { {"-driver", Ns_ObjvObj, &driverObj, NULL}, {NULL, NULL, NULL, NULL} }; Ns_ObjvSpec *args, argsNew[] = { {"?value", Ns_ObjvBool, &boolValue, NULL}, {NULL, NULL, NULL, NULL} }; Ns_ObjvSpec argsLegacy[] = { {"driver", Ns_ObjvObj, &driverObj, NULL}, {"?value", Ns_ObjvBool, &boolValue, NULL}, {NULL, NULL, NULL, NULL} }; firstArgString = objc > 2 ? Tcl_GetString(objv[2]) : NULL; if (firstArgString != NULL) { int argValue; if (*firstArgString != '-' && ((objc == 3 && Tcl_ExprBoolean(interp, firstArgString, &argValue) == TCL_OK) || objc == 4)) { args = argsLegacy; opts = NULL; Ns_LogDeprecated(objv, objc, "ns_writer streaming ?-driver drv? ?value?", NULL); } else { args = argsNew; opts = optsNew; } } else { args = argsNew; opts = optsNew; } if (Ns_ParseObjv(opts, args, interp, 2, objc, objv) != NS_OK) { result = TCL_ERROR; } else if ((driverObj == NULL) && NsConnRequire(interp, NS_CONN_REQUIRE_ALL, &conn) != NS_OK) { result = TCL_ERROR; } else { DrvWriter *wrPtr; if (DriverWriterFromObj(interp, driverObj, conn, &wrPtr) != NS_OK) { result = TCL_ERROR; } else if (boolValue != -1) { /* * The optional argument was provided. */ wrPtr->doStream = (boolValue == 1 ? NS_WRITER_STREAM_ACTIVE : NS_WRITER_STREAM_NONE); } if (result == TCL_OK) { Tcl_SetObjResult(interp, Tcl_NewIntObj(wrPtr->doStream == NS_WRITER_STREAM_ACTIVE ? 1 : 0)); } } return result; } /* *---------------------------------------------------------------------- * * NsTclWriterObjCmd -- * * Implements "ns_writer" command for submitting data to the writer * threads and to configure and query the state of the writer threads at * runtime. * * Results: * Standard Tcl result. * * Side effects: * None. * *---------------------------------------------------------------------- */ int NsTclWriterObjCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { const Ns_SubCmdSpec subcmds[] = { {"list", WriterListObjCmd}, {"size", WriterSizeObjCmd}, {"streaming", WriterStreamingObjCmd}, {"submit", WriterSubmitObjCmd}, {"submitfile", WriterSubmitFileObjCmd}, {"submitfiles",WriterSubmitFilesObjCmd}, {NULL, NULL} }; return Ns_SubcmdObjv(subcmds, clientData, interp, objc, objv); } /* *====================================================================== * Async (log) writer: Write asynchronously to a disk *====================================================================== */ /* *---------------------------------------------------------------------- * * NsAsyncWriterQueueEnable -- * * Enable async writing and start the AsyncWriterThread if * necessary * * Results: * None. * * Side effects: * Potentially starting a thread and set "stopped" to NS_FALSE. * *---------------------------------------------------------------------- */ void NsAsyncWriterQueueEnable(void) { if (Ns_ConfigBool(NS_CONFIG_PARAMETERS, "asynclogwriter", NS_FALSE) == NS_TRUE) { SpoolerQueue *queuePtr; /* * In case, the async writer has not started, the static variable * asyncWriter is NULL. */ if (asyncWriter == NULL) { Ns_MutexLock(&reqLock); if (likely(asyncWriter == NULL)) { /* * Allocate and initialize writer thread context. */ asyncWriter = ns_calloc(1u, sizeof(AsyncWriter)); Ns_MutexUnlock(&reqLock); Ns_MutexSetName2(&asyncWriter->lock, "ns:driver", "async-writer"); /* * Allocate and initialize a Spooler Queue for this thread. */ queuePtr = ns_calloc(1u, sizeof(SpoolerQueue)); Ns_MutexSetName2(&queuePtr->lock, "ns:driver:async-writer", "queue"); asyncWriter->firstPtr = queuePtr; /* * Start the spooler queue */ SpoolerQueueStart(queuePtr, AsyncWriterThread); } else { Ns_MutexUnlock(&reqLock); } } assert(asyncWriter != NULL); queuePtr = asyncWriter->firstPtr; assert(queuePtr != NULL); Ns_MutexLock(&queuePtr->lock); queuePtr->stopped = NS_FALSE; Ns_MutexUnlock(&queuePtr->lock); } } /* *---------------------------------------------------------------------- * * NsAsyncWriterQueueDisable -- * * Disable async writing but don't touch the writer thread. * * Results: * None. * * Side effects: * Disable async writing by setting stopped to 1. * *---------------------------------------------------------------------- */ void NsAsyncWriterQueueDisable(bool shutdown) { if (asyncWriter != NULL) { SpoolerQueue *queuePtr = asyncWriter->firstPtr; Ns_Time timeout; assert(queuePtr != NULL); Ns_GetTime(&timeout); Ns_IncrTime(&timeout, nsconf.shutdowntimeout.sec, nsconf.shutdowntimeout.usec); Ns_MutexLock(&queuePtr->lock); queuePtr->stopped = NS_TRUE; queuePtr->shutdown = shutdown; /* * Trigger the AsyncWriter Thread to drain the spooler queue. */ SockTrigger(queuePtr->pipe[1]); (void)Ns_CondTimedWait(&queuePtr->cond, &queuePtr->lock, &timeout); Ns_MutexUnlock(&queuePtr->lock); if (shutdown) { ns_free(queuePtr); ns_free(asyncWriter); asyncWriter = NULL; } } } /* *---------------------------------------------------------------------- * * NsAsyncWrite -- * * Perform an asynchronous write operation via a writer thread in * case a writer thread is configured and running. The intention * of the asynchronous write operations is to reduce latencies in * connection threads. * * Results: * NS_OK, when write was performed via writer thread, * NS_ERROR otherwise (but data is written). * * Side effects: * I/O Operation. * *---------------------------------------------------------------------- */ Ns_ReturnCode NsAsyncWrite(int fd, const char *buffer, size_t nbyte) { Ns_ReturnCode returnCode = NS_OK; NS_NONNULL_ASSERT(buffer != NULL); /* * If the async writer has not started or is deactivated, behave like a * ns_write() command. If the ns_write() fails, we can't do much, since * the writing of an error message to the log might bring us into an * infinite loop. So we print simple to stderr. */ if (asyncWriter == NULL || asyncWriter->firstPtr->stopped) { ssize_t written = ns_write(fd, buffer, nbyte); if (unlikely(written != (ssize_t)nbyte)) { int retries = 100; /* * Don't go into an infinite loop when multiple subsequent disk * write operations return 0 (maybe disk full). */ returnCode = NS_ERROR; do { if (written < 0) { fprintf(stderr, "error during async write (fd %d): %s\n", fd, strerror(errno)); break; } /* * All partial writes (written >= 0) */ WriteWarningRaw("partial write", fd, nbyte, written); nbyte -= (size_t)written; buffer += written; written = ns_write(fd, buffer, nbyte); if (written == (ssize_t)nbyte) { returnCode = NS_OK; break; } } while (retries-- > 0); } } else { SpoolerQueue *queuePtr; bool trigger = NS_FALSE; const AsyncWriteData *wdPtr; AsyncWriteData *newWdPtr; /* * Allocate a writer cmd and initialize it. In order to provide an * interface compatible to ns_write(), we copy the provided data, * such it can be freed by the caller. When we would give up the * interface, we could free the memory block after writing, and * save a malloc/free operation on the data. */ newWdPtr = ns_calloc(1u, sizeof(AsyncWriteData)); newWdPtr->fd = fd; newWdPtr->bufsize = nbyte; newWdPtr->data = ns_malloc(nbyte + 1u); memcpy(newWdPtr->data, buffer, newWdPtr->bufsize); newWdPtr->buf = newWdPtr->data; newWdPtr->size = newWdPtr->bufsize; /* * Now add new writer socket to the writer thread's queue. In most * cases, the queue will be empty. */ queuePtr = asyncWriter->firstPtr; assert(queuePtr != NULL); Ns_MutexLock(&queuePtr->lock); wdPtr = queuePtr->sockPtr; if (wdPtr != NULL) { newWdPtr->nextPtr = queuePtr->sockPtr; queuePtr->sockPtr = newWdPtr; } else { queuePtr->sockPtr = newWdPtr; trigger = NS_TRUE; } Ns_MutexUnlock(&queuePtr->lock); /* * Wake up writer thread if desired */ if (trigger) { SockTrigger(queuePtr->pipe[1]); } } return returnCode; } /* *---------------------------------------------------------------------- * * AsyncWriterRelease -- * * Deallocate write data. * * Results: * None * * Side effects: * free memory * *---------------------------------------------------------------------- */ static void AsyncWriterRelease(AsyncWriteData *wdPtr) { NS_NONNULL_ASSERT(wdPtr != NULL); ns_free(wdPtr->data); ns_free(wdPtr); } /* *---------------------------------------------------------------------- * * AsyncWriterThread -- * * Thread that implements non-blocking write operations to files * * Results: * None. * * Side effects: * Write to files. * *---------------------------------------------------------------------- */ static void AsyncWriterThread(void *arg) { SpoolerQueue *queuePtr = (SpoolerQueue*)arg; char charBuffer[1]; int pollTimeout; Ns_ReturnCode status; bool stopping; AsyncWriteData *curPtr, *nextPtr, *writePtr; PollData pdata; Ns_ThreadSetName("-asynclogwriter%d-", queuePtr->id); queuePtr->threadName = Ns_ThreadGetName(); /* * Allocate and initialize controlling variables */ PollCreate(&pdata); writePtr = NULL; stopping = NS_FALSE; /* * Loop forever until signaled to shutdown and all * connections are complete and gracefully closed. */ while (!stopping) { /* * Always listen to the trigger pipe. We could as well perform * in the writer thread async write operations, but for the * effect of reducing latency in connection threads, this is * not an issue. To keep things simple, we perform the * typically small write operations without testing for POLLOUT. */ PollReset(&pdata); (void)PollSet(&pdata, queuePtr->pipe[0], (short)POLLIN, NULL); if (writePtr == NULL) { pollTimeout = 30 * 1000; } else { pollTimeout = 0; } /* * Wait for data */ /*n =*/ (void) PollWait(&pdata, pollTimeout); /* * Select and drain the trigger pipe if necessary. */ if (PollIn(&pdata, 0)) { if (ns_recv(queuePtr->pipe[0], charBuffer, 1u, 0) != 1) { Ns_Fatal("asynclogwriter: trigger ns_recv() failed: %s", ns_sockstrerror(ns_sockerrno)); } if (queuePtr->stopped) { /* * Drain the queue from everything */ for (curPtr = writePtr; curPtr != NULL; curPtr = curPtr->nextPtr) { ssize_t written = ns_write(curPtr->fd, curPtr->buf, curPtr->bufsize); if (unlikely(written != (ssize_t)curPtr->bufsize)) { WriteWarningRaw("drain writer", curPtr->fd, curPtr->bufsize, written); } } writePtr = NULL; for (curPtr = queuePtr->sockPtr; curPtr != NULL; curPtr = curPtr->nextPtr) { ssize_t written = ns_write(curPtr->fd, curPtr->buf, curPtr->bufsize); if (unlikely(written != (ssize_t)curPtr->bufsize)) { WriteWarningRaw("drain queue", curPtr->fd, curPtr->bufsize, written); } } queuePtr->sockPtr = NULL; /* * Notify the caller (normally * NsAsyncWriterQueueDisable()) that we are done */ Ns_CondBroadcast(&queuePtr->cond); } } /* * Write to all available file descriptors */ curPtr = writePtr; writePtr = NULL; while (curPtr != NULL) { ssize_t written; nextPtr = curPtr->nextPtr; status = NS_OK; /* * Write the actual data and allow for partial write operations. */ written = ns_write(curPtr->fd, curPtr->buf, curPtr->bufsize); if (unlikely(written < 0)) { status = NS_ERROR; } else { curPtr->size -= (size_t)written; curPtr->nsent += written; curPtr->bufsize -= (size_t)written; if (curPtr->data != NULL) { curPtr->buf += written; } } if (unlikely(status != NS_OK)) { AsyncWriterRelease(curPtr); queuePtr->queuesize--; } else { /* * The write operation was successful. Check if there * is some remaining data to write. If not we are done * with this request can release the write buffer. */ if (curPtr->size > 0u) { Push(curPtr, writePtr); } else { AsyncWriterRelease(curPtr); queuePtr->queuesize--; } } curPtr = nextPtr; } /* * Check for shutdown */ stopping = queuePtr->shutdown; if (stopping) { curPtr = queuePtr->sockPtr; assert(writePtr == NULL); while (curPtr != NULL) { ssize_t written = ns_write(curPtr->fd, curPtr->buf, curPtr->bufsize); if (unlikely(written != (ssize_t)curPtr->bufsize)) { WriteWarningRaw("shutdown", curPtr->fd, curPtr->bufsize, written); } curPtr = curPtr->nextPtr; } } else { /* * Add fresh jobs to the writer queue. This means actually to * move jobs from queuePtr->sockPtr (kept name for being able * to use the same queue as above) to the currently active * jobs in queuePtr->curPtr. */ Ns_MutexLock(&queuePtr->lock); curPtr = queuePtr->sockPtr; queuePtr->sockPtr = NULL; while (curPtr != NULL) { nextPtr = curPtr->nextPtr; Push(curPtr, writePtr); queuePtr->queuesize++; curPtr = nextPtr; } queuePtr->curPtr = writePtr; Ns_MutexUnlock(&queuePtr->lock); } } PollFree(&pdata); queuePtr->stopped = NS_TRUE; Ns_Log(Notice, "exiting"); } /* *---------------------------------------------------------------------- * * AsyncLogfileWriteObjCmd - * * Implements "ns_asynclogfile write" command. Write to a file * descriptor via async writer thread. The command handles partial write * operations internally. * * Results: * Standard Tcl result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int AsyncLogfileWriteObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { int result = TCL_OK, binary = (int)NS_FALSE, sanitize; Tcl_Obj *stringObj; int fd = 0; Ns_ObjvValueRange fd_range = {0, INT_MAX}; Ns_ObjvValueRange sanitize_range = {0, 2}; Ns_ObjvSpec opts[] = { {"-binary", Ns_ObjvBool, &binary, INT2PTR(NS_TRUE)}, {"-sanitize", Ns_ObjvInt, &sanitize, &sanitize_range}, {NULL, NULL, NULL, NULL} }; Ns_ObjvSpec args[] = { {"fd", Ns_ObjvInt, &fd, &fd_range}, {"buffer", Ns_ObjvObj, &stringObj, NULL}, {NULL, NULL, NULL, NULL} }; /* * Take the config value as default for "-sanitize", but let the used * override it on a per-case basis. */ sanitize = nsconf.sanitize_logfiles; if (unlikely(Ns_ParseObjv(opts, args, interp, 2, objc, objv) != NS_OK)) { result = TCL_ERROR; } else { const char *buffer; int length; Ns_ReturnCode rc; if (binary == (int)NS_TRUE || NsTclObjIsByteArray(stringObj)) { buffer = (const char *) Tcl_GetByteArrayFromObj(stringObj, &length); } else { buffer = Tcl_GetStringFromObj(stringObj, &length); } if (length > 0) { if (sanitize > 0) { Tcl_DString ds; bool lastCharNewline = (buffer[length-1] == '\n'); Tcl_DStringInit(&ds); if (lastCharNewline) { length --; } Ns_DStringAppendPrintable(&ds, sanitize == 2, buffer, (size_t)length); if (lastCharNewline) { Tcl_DStringAppend(&ds, "\n", 1); } rc = NsAsyncWrite(fd, ds.string, (size_t)ds.length); Tcl_DStringFree(&ds); } else { rc = NsAsyncWrite(fd, buffer, (size_t)length); } if (rc != NS_OK) { Ns_TclPrintfResult(interp, "ns_asynclogfile: error during write operation on fd %d: %s", fd, Tcl_PosixError(interp)); result = TCL_ERROR; } } else { result = TCL_OK; } } return result; } /* *---------------------------------------------------------------------- * * AsyncLogfileOpenObjCmd - * * Implements "ns_asynclogfile open" command. The command opens a * write-only log file and return a thread-shareable handle (actually a * numeric file descriptor) which can be used in subsequent "write" or * "close" operations. * * Results: * Standard Tcl result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int AsyncLogfileOpenObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { int result = TCL_OK; unsigned int flags = O_APPEND; char *fileNameString; Tcl_Obj *flagsObj = NULL; Ns_ObjvTable flagTable[] = { {"APPEND", O_APPEND}, {"EXCL", O_EXCL}, #ifdef O_DSYNC {"DSYNC", O_DSYNC}, #endif #ifdef O_SYNC {"SYNC", O_SYNC}, #endif {"TRUNC", O_TRUNC}, {NULL, 0u} }; Ns_ObjvSpec args[] = { {"filename", Ns_ObjvString, &fileNameString, NULL}, {"?flags", Ns_ObjvObj, &flagsObj, NULL}, //{"mode", Ns_ObjvString, &mode, NULL}, {NULL, NULL, NULL, NULL} }; if (unlikely(Ns_ParseObjv(NULL, args, interp, 2, objc, objv) != NS_OK)) { result = TCL_ERROR; } else if (flagsObj != NULL) { Tcl_Obj **ov; int oc; result = Tcl_ListObjGetElements(interp, flagsObj, &oc, &ov); if (result == TCL_OK && oc > 0) { int i, opt; flags = 0u; for (i = 0; i < oc; i++) { result = Tcl_GetIndexFromObjStruct(interp, ov[i], flagTable, (int)sizeof(flagTable[0]), "flag", 0, &opt); if (result != TCL_OK) { break; } else { flags = flagTable[opt].value; } } } } if (result == TCL_OK) { int fd; fd = ns_open(fileNameString, (int)(O_CREAT | O_WRONLY | O_CLOEXEC | flags), 0644); if (unlikely(fd == NS_INVALID_FD)) { Ns_TclPrintfResult(interp, "could not open file '%s': %s", fileNameString, Tcl_PosixError(interp)); result = TCL_ERROR; } else { Tcl_SetObjResult(interp, Tcl_NewIntObj(fd)); } } return result; } /* *---------------------------------------------------------------------- * * AsyncLogfileCloseObjCmd - * * Implements "ns_asynclogfile close" command. Close the logfile * previously created via "ns_asynclogfile open". * * Results: * Standard Tcl result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int AsyncLogfileCloseObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { int fd, result = TCL_OK; Ns_ObjvValueRange range = {0, INT_MAX}; Ns_ObjvSpec args[] = { {"fd", Ns_ObjvInt, &fd, &range}, {NULL, NULL, NULL, NULL} }; if (unlikely(Ns_ParseObjv(NULL, args, interp, 2, objc, objv) != NS_OK)) { result = TCL_ERROR; } else { int rc = ns_close(fd); if (rc != 0) { Ns_TclPrintfResult(interp, "could not close fd %d: %s", fd, Tcl_PosixError(interp)); result = TCL_ERROR; } } return result; } /* *---------------------------------------------------------------------- * * NsTclAsyncLogfileObjCmd - * * Wrapper for "ns_asynclogfile open|write|close" commands. * * Results: * Standard Tcl result. * * Side effects: * None. * *---------------------------------------------------------------------- */ int NsTclAsyncLogfileObjCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *const* objv) { const Ns_SubCmdSpec subcmds[] = { {"open", AsyncLogfileOpenObjCmd}, {"write", AsyncLogfileWriteObjCmd}, {"close", AsyncLogfileCloseObjCmd}, {NULL, NULL} }; return Ns_SubcmdObjv(subcmds, clientData, interp, objc, objv); } /* *---------------------------------------------------------------------- * * LookupDriver -- * * Find a matching driver for the specified protocol and optionally the * specified driver name. * * Results: * Driver pointer or NULL on failure. * * Side effects: * When no driver is found, an error is left in the interp result. * *---------------------------------------------------------------------- */ static Driver * LookupDriver(Tcl_Interp *interp, const char* protocol, const char *driverName) { Driver *drvPtr; NS_NONNULL_ASSERT(interp != NULL); NS_NONNULL_ASSERT(protocol != NULL); for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) { Ns_Log(DriverDebug, "... check Driver proto <%s> server %s name %s location %s", drvPtr->protocol, drvPtr->server, drvPtr->threadName, drvPtr->location); if (STREQ(drvPtr->protocol, protocol)) { if (driverName == NULL) { /* * If there is no driver name given, take the first driver * with the matching protocol. */ break; } else if (STREQ(drvPtr->moduleName, driverName)) { /* * The driver name (name of the loaded module) is equal */ break; } } } if (drvPtr == NULL) { if (driverName != NULL) { Ns_TclPrintfResult(interp, "no driver for protocol '%s' & driver name '%s' found", protocol, driverName); } else { Ns_TclPrintfResult(interp, "no driver for protocol '%s' found", protocol); } } return drvPtr; } /* *---------------------------------------------------------------------- * * NSDriverClientOpen -- * * Open a client HTTP connection using the driver interface * * Results: * Tcl return code. * * Side effects: * Opening a connection * *---------------------------------------------------------------------- */ int NSDriverClientOpen(Tcl_Interp *interp, const char *driverName, const char *url, const char *httpMethod, const char *version, const Ns_Time *timeoutPtr, Sock **sockPtrPtr) { char *protocol, *host, *portString, *path, *tail, *url2; int result = TCL_OK; NS_NONNULL_ASSERT(interp != NULL); NS_NONNULL_ASSERT(url != NULL); NS_NONNULL_ASSERT(httpMethod != NULL); NS_NONNULL_ASSERT(version != NULL); NS_NONNULL_ASSERT(sockPtrPtr != NULL); url2 = ns_strdup(url); /* * We need here a fully qualified URL, otherwise raise an error */ if (unlikely(Ns_ParseUrl(url2, &protocol, &host, &portString, &path, &tail) != NS_OK) || protocol == NULL || host == NULL || path == NULL || tail == NULL) { Ns_Log(Notice, "driver: invalid URL '%s' passed to NSDriverClientOpen", url2); result = TCL_ERROR; } else { Driver *drvPtr; unsigned short portNr = 0u; /* make static checker happy */ assert(protocol != NULL); assert(host != NULL); assert(path != NULL); assert(tail != NULL); /* * Find a matching driver for the specified protocol and optionally * the specified driver name. */ drvPtr = LookupDriver(interp, protocol, driverName); if (drvPtr == NULL) { result = TCL_ERROR; } else if (portString != NULL) { portNr = (unsigned short) strtol(portString, NULL, 10); } else if (drvPtr->defport != 0u) { /* * Get the default port from the driver structure; */ portNr = drvPtr->defport; } else { Ns_TclPrintfResult(interp, "no default port for protocol '%s' defined", protocol); result = TCL_ERROR; } if (result == TCL_OK) { NS_SOCKET sock; Ns_ReturnCode status; sock = Ns_SockTimedConnect2(host, portNr, NULL, 0u, timeoutPtr, &status); if (sock == NS_INVALID_SOCKET) { Ns_SockConnectError(interp, host, portNr, status); result = TCL_ERROR; } else { const char *query; Tcl_DString ds, *dsPtr = &ds; Request *reqPtr; Sock *sockPtr; assert(drvPtr != NULL); sockPtr = SockNew(drvPtr); sockPtr->sock = sock; sockPtr->servPtr = drvPtr->servPtr; if (sockPtr->servPtr == NULL) { const NsInterp *itPtr = NsGetInterpData(interp); sockPtr->servPtr = itPtr->servPtr; } RequestNew(sockPtr); Ns_GetTime(&sockPtr->acceptTime); reqPtr = sockPtr->reqPtr; Tcl_DStringInit(dsPtr); Ns_DStringAppend(dsPtr, httpMethod); Ns_StrToUpper(Ns_DStringValue(dsPtr)); Tcl_DStringAppend(dsPtr, " /", 2); if (*path != '\0') { if (*path == '/') { path ++; } Tcl_DStringAppend(dsPtr, path, -1); Tcl_DStringAppend(dsPtr, "/", 1); } Tcl_DStringAppend(dsPtr, tail, -1); Tcl_DStringAppend(dsPtr, " HTTP/", 6); Tcl_DStringAppend(dsPtr, version, -1); reqPtr->request.line = Ns_DStringExport(dsPtr); reqPtr->request.method = ns_strdup(httpMethod); reqPtr->request.protocol = ns_strdup(protocol); reqPtr->request.host = ns_strdup(host); query = strchr(tail, INTCHAR('?')); if (query != NULL) { reqPtr->request.query = ns_strdup(query+1); } else { reqPtr->request.query = NULL; } /*Ns_Log(Notice, "REQUEST LINE <%s> query <%s>", reqPtr->request.line, reqPtr->request.query);*/ *sockPtrPtr = sockPtr; } } } ns_free(url2); return result; } /* *---------------------------------------------------------------------- * * NSDriverSockNew -- * * Create a Sock structure based on the driver interface * * Results: * Tcl return code. * * Side effects: * Accepting a connection * *---------------------------------------------------------------------- */ int NSDriverSockNew(Tcl_Interp *interp, NS_SOCKET sock, const char *protocol, const char *driverName, const char *methodName, Sock **sockPtrPtr) { int result = TCL_OK; Driver *drvPtr; NS_NONNULL_ASSERT(interp != NULL); NS_NONNULL_ASSERT(protocol != NULL); NS_NONNULL_ASSERT(methodName != NULL); NS_NONNULL_ASSERT(sockPtrPtr != NULL); drvPtr = LookupDriver(interp, protocol, driverName); if (drvPtr == NULL) { result = TCL_ERROR; } else { Sock *sockPtr; Tcl_DString ds, *dsPtr = &ds; Request *reqPtr; sockPtr = SockNew(drvPtr); sockPtr->servPtr = drvPtr->servPtr; sockPtr->sock = sock; RequestNew(sockPtr); // not sure if needed // peerAddr is missing Ns_GetTime(&sockPtr->acceptTime); reqPtr = sockPtr->reqPtr; Tcl_DStringInit(dsPtr); Ns_DStringAppend(dsPtr, methodName); Ns_StrToUpper(Ns_DStringValue(dsPtr)); reqPtr->request.line = Ns_DStringExport(dsPtr); reqPtr->request.method = ns_strdup(methodName); reqPtr->request.protocol = ns_strdup(protocol); reqPtr->request.host = NULL; reqPtr->request.query = NULL; /* Ns_Log(Notice, "REQUEST LINE <%s>", reqPtr->request.line);*/ *sockPtrPtr = sockPtr; } return result; } /* * Local Variables: * mode: c * c-basic-offset: 4 * fill-column: 78 * indent-tabs-mode: nil * End: */
null
173
CWE-787
CVE-2020-13398
# 2020-05-05 Version 2.1.0 Important notes: * fix multiple CVEs: CVE-2020-11039, CVE-2020-11038, CVE-2020-11043, CVE-2020-11040, CVE-2020-11041, CVE-2020-11019, CVE-2020-11017, CVE-2020-11018 * fix multiple leak and crash issues (#6129, #6128, #6127, #6110, #6081, #6077) Noteworthy features and improvements: * Fixed sound issues (#6043) * New expert command line options /tune and /tune-list to modify all client settings in a generic way. * Fixes for smartcard cache, this improves compatibility of smartcard devices with newer smartcard channel. * Shadow server can now be instructed to listen to multiple interfaces. * Improved server certificate support (#6052) * Various fixes for wayland client (fullscreen, mouse wheel, ...) * Fixed large mouse pointer support, now mouse pointers > 96x96 pixel are visible. * USB redirection command line improvements (filter options) * Various translation improvements for android and ios clients For a complete and detailed change log since the last release candidate run: git log 2.0.0..2.1.0 # 2020-04-09 Version 2.0.0 Important notes: * fix multiple CVEs: CVE-2020-11521 CVE-2020-11522 CVE-2020-11523 CVE-2020-11524 CVE-2020-11525 CVE-2020-11526 * fix multiple other security related issues (#6005, #6006, #6007, #6008, #6009, #6010, #6011, #6012, #6013) * sha256 is now used instead of sha1 to fingerprint certificates. This will invalidate all hosts in FreeRDP known_hosts2 file and causes a prompt if a new connection is established after the update Noteworthy features and improvements: * First version of the RDP proxy was added (#5372) - thanks to @kubistika * Smartcard received some refactoring. Missing functions were added and input validation was improved (#5884) * A new option /cert that unifies all certificate related options (#5880) The old options (cert-ignore, cert-deny, cert-name, cert-tofu) are still available but marked as deprecated * Support for Remote Assistance Protocol Version 2 [MS-RA] * The DirectFB client was removed because it was unmaintained * Unified initialization of OrderSupport * Fix for licensing against Windows Server 2003 * Font smoothing is now enabled per default * Flatpack support was added * Smart scaling for Wayland using libcairo was added (#5215) * Unified update->BeginPaint and update->EndPaint * An image scaling API for software drawing was added * Rail was updated to the latest spec version 28.0 * Support for H.264 in the shadow server is now detected at runtime * Add mask=<value> option for /gfx and /gfx-h264 (#5771) * Code reformatting (#5667) * A new option /timeout was added to adjust the TCP ACK timeout (#5987) For a complete and detailed change log since the last release candidate run: git log 2.0.0-rc4..2.0.0 # 2018-11-19 Version 2.0.0-rc4 FreeRDP 2.0.0-rc4 is the fifth release candidate for 2.0.0. Although it mainly addresses security and stability there are some new features as well. Noteworthy features and improvements: * fix multiple reported CVEs (#5031) * gateway: multiple fixes and improvements (#3600, #4787, #4902, #4964, #4947, #4952, #4938) * client/X11: support for rail (remote app) icons was added (#5012) * licensing: the licensing code was re-worked. Per-device licenses are now saved on the client and used on re-connect. WARNING: this is a change in FreeRDP behavior regarding licensing. If the old behavior is required, or no licenses should be saved use the new command line option +old-license (#4979) * improve order handling - only orders that were enabled during capability exchange are accepted (#4926). WARNING and NOTE: some servers do improperly send orders that weren't negotiated, for such cases the new command line option /relax-order-checks was added to disable the strict order checking. If connecting to xrdp the options /relax-order-checks *and* +glyph-cache are required. * /smartcard has now support for substring filters (#4840) for details see https://github.com/FreeRDP/FreeRDP/wiki/smartcard-logon * add support to set tls security level (for openssl >= 1.1.0) - default level is set to 1 - the new command line option /tls-seclevel:[LEVEL] allows to set a different level if required * add new command line option /smartcard-logon to allow smartcard login (currently only with RDP security) (#4842) * new command line option: /window-position to allow positioning the window on startup (#5018) * client/X11: set window title before mapping (#5023) * rdpsnd/audin (mostly server side) add support for audio re-sampling using soxr or ffmpeg * client/Android: add Japanese translation (#4906) * client/Android: add Korean translation (#5029) For a complete and detailed change log since the last release candidate run: git log 2.0.0-rc3..2.0.0-rc4 # 2018-08-01 Version 2.0.0-rc3 FreeRDP 2.0.0-rc3 is the fourth release candidate for 2.0.0. For a complete and detailed change log since the last release candidate run: git log 2.0.0-rc2..2.0.0-rc3 Noteworthy features and improvements: * Updated and improved sound and microphone redirection format support (AAC) * Improved reliability of reconnect and redirection support * Fixed memory leaks with +async-update * Improved connection error reporting * Improved gateway support (various fixes for HTTP and RDG) * SOCKS proxy support (all clients) * More reliable resolution switching with /dynamic-resolution (MS-RDPEVOR) (xfreerdp) Fixed github issues (excerpt): * #1924, #4132, #4511 Fixed redirection * #4165 AAC and MP3 codec support for sound and microphone redirection * #4222 Gateway connections prefer IP to hostname * #4550 Fixed issues with +async-update * #4634 Comment support in known_hosts file * #4684 /drive and +drives don't work togehter * #4735 Automatically reconnect if connection timed out waiting for user interaction See https://github.com/FreeRDP/FreeRDP/milestone/9 for a complete list. # 2017-11-28 Version 2.0.0-rc2 FreeRDP 2.0.0-rc2 is the third release candidate for 2.0.0. For a complete and detailed change log since the last release candidate run: git log 2.0.0-rc1..2.0.0-rc2 Noteworthy features and improvements: * IMPORTANT: add support CredSSP v6 - this fixes KB4088776 see #4449, #4488 * basic support for the "Video Optimized Remoting Virtual Channel Extension" (MS-RDPEVOR) was added * many smart card related fixes and cleanups #4312 * fix ccache support * fix OpenSSL 1.1.0 detection on Windows * fix IPv6 handling on Windows * add support for memory and thread sanitizer * support for dynamic resloution changes was added in xfreerdp #4313 * support for gateway access token (command line option /gat) was added * initial support for travis-ci.org was added * SSE optimization version of RGB to AVC444 frame split was added * build: -msse2/-msse3 are not enabled globally anymore Fixed github issues (excerpt): * #4227 Convert settings->Password to binary blob * #4231 freerdp-2.0.0_rc0: 5 tests failed out of 184 on ppc * #4276 Big endian fixes * #4291 xfreerdp “Segmentation fault” when connecting to freerdp-shadow-cli * #4293 [X11] shadow server memory corruption with /monitors:2 #4293 * #4296 drive redirection - raise an error if the directory can't be founde * #4306 Cannot connect to shadow server with NLA auth: SEC_E_OUT_OF_SEQUENCE * #4447 Apple rpath namespace fixes * #4457 Fix /size: /w: /h: with /monitors: (Fix custom sizes) * #4527 pre-connection blob (pcb) support in .rdp files * #4552 Fix Windows 10 cursors drawing as black * smartcard related: #3521, #3431, #3474, #3488, #775, #1424 See https://github.com/FreeRDP/FreeRDP/milestone/8 for a complete list. # 2017-11-28 Version 2.0.0-rc1 FreeRDP 2.0.0-rc1 is the second release candidate for 2.0.0. For a complete and detailed change log since the last release candidate run: git log 2.0.0-rc0..master Noteworthy features and improvements: * support for FIPS mode was added (option +fipsmode) * initial client side kerberos support (run cmake with WITH_GSSAPI) * support for ssh-agent redirection (as rdp channel) * the man page(s) and /help were updated an improved * build: support for GNU/kFreeBSD * add support for ICU for unicode conversion (-DWITH_ICU=ON) * client add option to force password prompt before connection (/from-stdin[:force]) * add Samsung DeX support * extend /size to allow width or height percentages (#4146) * add support for "password is pin" * clipboard is now enabled per default (use -clipboard to disable) Fixed github issues (excerpt): * #4281: Added option to prefer IPv6 over IPv4 * #3890: Point to OpenSSL doc for private CA * #3378: support 31 static channels as described in the spec * #1536: fix clipboard on mac * #4253: Rfx decode tile width. * #3267: fix parsing of drivestoredirect * #4257: Proper error checks for /kbd argument * #4249: Corruption due to recursive parser * #4111: 15bpp color handling for brush. * #3509: Added Ctrl+Alt+Enter description * #3211: Return freerdp error from main. * #3513: add better description for drive redirection * #4199: ConvertFindDataAToW string length * #4135: client/x11: fix colors on big endian * #4089: fix h264 context leak when DeleteSurface * #4117: possible segfault * #4091: fix a regression with remote program See https://github.com/FreeRDP/FreeRDP/milestone/7 for a complete list. 2012-02-07 Version 1.0.1 FreeRDP 1.0.1 is a maintenance release to address a certain number of issues found in 1.0.0. This release also brings corrective measures to certificate validation which were required for inclusion in Ubuntu. * Certificate Validation * Improved validation logic and robustness * Added validation of certificate name against hostname * Token-based Server Redirection * Fixed redirection logic * HAProxy load-balancer support * xfreerdp-server * better event handling * capture performance improvements * wfreerdp * Fix RemoteFX support * Fix mingw64 compilation * libfreerdp-core: * Fix severe TCP sending bug * Added server-side Standard RDP security 2012-01-16 Version 1.0.0 License: FreeRDP 1.0 is the first release of FreeRDP under the Apache License 2.0. The FreeRDP 1.x series is a rewrite, meaning there is no continuity with the previous FreeRDP 0.x series which were released under GPLv2. New Features: * RemoteFX * Both encoder and decoder * SSE2 and NEON optimization * NSCodec * RemoteApp * Working, minor glitches * Multimedia Redirection * ffmpeg support * Network Level Authentication (NLA) * NTLMv2 * Certificate validation * FIPS-compliant RDP security * new build system (cmake) * added official logo and icon New Architecture: * libfreerdp-core * core protocol * highly portable * both client and server * libfreerdp-cache * caching operations * libfreerdp-codec * bitmap decompression * codec encoding/decoding * libfreerdp-kbd * keyboard mapping * libfreerdp-channels * virtual channel management * client and server side support * libfreerdp-gdi * extensively unit tested * portable software GDI implementation * libfreerdp-rail * RemoteApp library * libfreerdp-utils * shared utility library FreeRDP Clients: * client/X11 (xfreerdp) * official client * RemoteApp support * X11 GDI implementation * client/DirectFB (dfreerdp) * DirectFB support * software-based GDI (libfreerdp-gdi) * client/Windows (wfreerdp) * Native Win32 support FreeRDP Servers (experimental): * server/X11 (xfreerdp-server) * RemoteFX-only * no authentication * highly experimental * keyboard and mouse input supported Virtual Channels: * cliprdr (Clipboard Redirection) * rail (RemoteApp) * drdynvc (Dynamic Virtual Channels) * audin (Audio Input Redirection) * alsa support * pulse support * tsmf (Multimedia Redirection) * alsa support * pulse support * ffmpeg support * rdpdr (Device Redirection) * disk (Disk Redirection) * parallel (Parallel Port Redirection) * serial (Serial Port Redirection) * printer (Printer Redirection) * CUPS support * smartcard (Smartcard Redirection) * rdpsnd (Sound Redirection) * alsa support * pulse support
null
# 2020-05-20 Version 2.1.1 Important notes: * CVE: GHSL-2020-100 OOB Read in ntlm_read_ChallengeMessage * CVE: GHSL-2020-101 OOB Read in security_fips_decrypt due to uninitialized value * CVE: GHSL-2020-102 OOB Write in crypto_rsa_common * Enforce synchronous legacy RDP encryption count (#6156) * Fixed some leaks and crashes missed in 2.1.0 * Removed dynamic channel listener limits * Lots of resource cleanup fixes (clang sanitizers) * A couple of performance improvements * Various small annoyances eliminated (typos, prefilled username for windows client, ...) For a complete and detailed change log since the last release candidate run: git log 2.1.0..2.1.1 # 2020-05-05 Version 2.1.0 Important notes: * fix multiple CVEs: CVE-2020-11039, CVE-2020-11038, CVE-2020-11043, CVE-2020-11040, CVE-2020-11041, CVE-2020-11019, CVE-2020-11017, CVE-2020-11018 * fix multiple leak and crash issues (#6129, #6128, #6127, #6110, #6081, #6077) Noteworthy features and improvements: * Fixed sound issues (#6043) * New expert command line options /tune and /tune-list to modify all client settings in a generic way. * Fixes for smartcard cache, this improves compatibility of smartcard devices with newer smartcard channel. * Shadow server can now be instructed to listen to multiple interfaces. * Improved server certificate support (#6052) * Various fixes for wayland client (fullscreen, mouse wheel, ...) * Fixed large mouse pointer support, now mouse pointers > 96x96 pixel are visible. * USB redirection command line improvements (filter options) * Various translation improvements for android and ios clients For a complete and detailed change log since the last release candidate run: git log 2.0.0..2.1.0 # 2020-04-09 Version 2.0.0 Important notes: * fix multiple CVEs: CVE-2020-11521 CVE-2020-11522 CVE-2020-11523 CVE-2020-11524 CVE-2020-11525 CVE-2020-11526 * fix multiple other security related issues (#6005, #6006, #6007, #6008, #6009, #6010, #6011, #6012, #6013) * sha256 is now used instead of sha1 to fingerprint certificates. This will invalidate all hosts in FreeRDP known_hosts2 file and causes a prompt if a new connection is established after the update Noteworthy features and improvements: * First version of the RDP proxy was added (#5372) - thanks to @kubistika * Smartcard received some refactoring. Missing functions were added and input validation was improved (#5884) * A new option /cert that unifies all certificate related options (#5880) The old options (cert-ignore, cert-deny, cert-name, cert-tofu) are still available but marked as deprecated * Support for Remote Assistance Protocol Version 2 [MS-RA] * The DirectFB client was removed because it was unmaintained * Unified initialization of OrderSupport * Fix for licensing against Windows Server 2003 * Font smoothing is now enabled per default * Flatpack support was added * Smart scaling for Wayland using libcairo was added (#5215) * Unified update->BeginPaint and update->EndPaint * An image scaling API for software drawing was added * Rail was updated to the latest spec version 28.0 * Support for H.264 in the shadow server is now detected at runtime * Add mask=<value> option for /gfx and /gfx-h264 (#5771) * Code reformatting (#5667) * A new option /timeout was added to adjust the TCP ACK timeout (#5987) For a complete and detailed change log since the last release candidate run: git log 2.0.0-rc4..2.0.0 # 2018-11-19 Version 2.0.0-rc4 FreeRDP 2.0.0-rc4 is the fifth release candidate for 2.0.0. Although it mainly addresses security and stability there are some new features as well. Noteworthy features and improvements: * fix multiple reported CVEs (#5031) * gateway: multiple fixes and improvements (#3600, #4787, #4902, #4964, #4947, #4952, #4938) * client/X11: support for rail (remote app) icons was added (#5012) * licensing: the licensing code was re-worked. Per-device licenses are now saved on the client and used on re-connect. WARNING: this is a change in FreeRDP behavior regarding licensing. If the old behavior is required, or no licenses should be saved use the new command line option +old-license (#4979) * improve order handling - only orders that were enabled during capability exchange are accepted (#4926). WARNING and NOTE: some servers do improperly send orders that weren't negotiated, for such cases the new command line option /relax-order-checks was added to disable the strict order checking. If connecting to xrdp the options /relax-order-checks *and* +glyph-cache are required. * /smartcard has now support for substring filters (#4840) for details see https://github.com/FreeRDP/FreeRDP/wiki/smartcard-logon * add support to set tls security level (for openssl >= 1.1.0) - default level is set to 1 - the new command line option /tls-seclevel:[LEVEL] allows to set a different level if required * add new command line option /smartcard-logon to allow smartcard login (currently only with RDP security) (#4842) * new command line option: /window-position to allow positioning the window on startup (#5018) * client/X11: set window title before mapping (#5023) * rdpsnd/audin (mostly server side) add support for audio re-sampling using soxr or ffmpeg * client/Android: add Japanese translation (#4906) * client/Android: add Korean translation (#5029) For a complete and detailed change log since the last release candidate run: git log 2.0.0-rc3..2.0.0-rc4 # 2018-08-01 Version 2.0.0-rc3 FreeRDP 2.0.0-rc3 is the fourth release candidate for 2.0.0. For a complete and detailed change log since the last release candidate run: git log 2.0.0-rc2..2.0.0-rc3 Noteworthy features and improvements: * Updated and improved sound and microphone redirection format support (AAC) * Improved reliability of reconnect and redirection support * Fixed memory leaks with +async-update * Improved connection error reporting * Improved gateway support (various fixes for HTTP and RDG) * SOCKS proxy support (all clients) * More reliable resolution switching with /dynamic-resolution (MS-RDPEVOR) (xfreerdp) Fixed github issues (excerpt): * #1924, #4132, #4511 Fixed redirection * #4165 AAC and MP3 codec support for sound and microphone redirection * #4222 Gateway connections prefer IP to hostname * #4550 Fixed issues with +async-update * #4634 Comment support in known_hosts file * #4684 /drive and +drives don't work togehter * #4735 Automatically reconnect if connection timed out waiting for user interaction See https://github.com/FreeRDP/FreeRDP/milestone/9 for a complete list. # 2017-11-28 Version 2.0.0-rc2 FreeRDP 2.0.0-rc2 is the third release candidate for 2.0.0. For a complete and detailed change log since the last release candidate run: git log 2.0.0-rc1..2.0.0-rc2 Noteworthy features and improvements: * IMPORTANT: add support CredSSP v6 - this fixes KB4088776 see #4449, #4488 * basic support for the "Video Optimized Remoting Virtual Channel Extension" (MS-RDPEVOR) was added * many smart card related fixes and cleanups #4312 * fix ccache support * fix OpenSSL 1.1.0 detection on Windows * fix IPv6 handling on Windows * add support for memory and thread sanitizer * support for dynamic resloution changes was added in xfreerdp #4313 * support for gateway access token (command line option /gat) was added * initial support for travis-ci.org was added * SSE optimization version of RGB to AVC444 frame split was added * build: -msse2/-msse3 are not enabled globally anymore Fixed github issues (excerpt): * #4227 Convert settings->Password to binary blob * #4231 freerdp-2.0.0_rc0: 5 tests failed out of 184 on ppc * #4276 Big endian fixes * #4291 xfreerdp “Segmentation fault” when connecting to freerdp-shadow-cli * #4293 [X11] shadow server memory corruption with /monitors:2 #4293 * #4296 drive redirection - raise an error if the directory can't be founde * #4306 Cannot connect to shadow server with NLA auth: SEC_E_OUT_OF_SEQUENCE * #4447 Apple rpath namespace fixes * #4457 Fix /size: /w: /h: with /monitors: (Fix custom sizes) * #4527 pre-connection blob (pcb) support in .rdp files * #4552 Fix Windows 10 cursors drawing as black * smartcard related: #3521, #3431, #3474, #3488, #775, #1424 See https://github.com/FreeRDP/FreeRDP/milestone/8 for a complete list. # 2017-11-28 Version 2.0.0-rc1 FreeRDP 2.0.0-rc1 is the second release candidate for 2.0.0. For a complete and detailed change log since the last release candidate run: git log 2.0.0-rc0..master Noteworthy features and improvements: * support for FIPS mode was added (option +fipsmode) * initial client side kerberos support (run cmake with WITH_GSSAPI) * support for ssh-agent redirection (as rdp channel) * the man page(s) and /help were updated an improved * build: support for GNU/kFreeBSD * add support for ICU for unicode conversion (-DWITH_ICU=ON) * client add option to force password prompt before connection (/from-stdin[:force]) * add Samsung DeX support * extend /size to allow width or height percentages (#4146) * add support for "password is pin" * clipboard is now enabled per default (use -clipboard to disable) Fixed github issues (excerpt): * #4281: Added option to prefer IPv6 over IPv4 * #3890: Point to OpenSSL doc for private CA * #3378: support 31 static channels as described in the spec * #1536: fix clipboard on mac * #4253: Rfx decode tile width. * #3267: fix parsing of drivestoredirect * #4257: Proper error checks for /kbd argument * #4249: Corruption due to recursive parser * #4111: 15bpp color handling for brush. * #3509: Added Ctrl+Alt+Enter description * #3211: Return freerdp error from main. * #3513: add better description for drive redirection * #4199: ConvertFindDataAToW string length * #4135: client/x11: fix colors on big endian * #4089: fix h264 context leak when DeleteSurface * #4117: possible segfault * #4091: fix a regression with remote program See https://github.com/FreeRDP/FreeRDP/milestone/7 for a complete list. 2012-02-07 Version 1.0.1 FreeRDP 1.0.1 is a maintenance release to address a certain number of issues found in 1.0.0. This release also brings corrective measures to certificate validation which were required for inclusion in Ubuntu. * Certificate Validation * Improved validation logic and robustness * Added validation of certificate name against hostname * Token-based Server Redirection * Fixed redirection logic * HAProxy load-balancer support * xfreerdp-server * better event handling * capture performance improvements * wfreerdp * Fix RemoteFX support * Fix mingw64 compilation * libfreerdp-core: * Fix severe TCP sending bug * Added server-side Standard RDP security 2012-01-16 Version 1.0.0 License: FreeRDP 1.0 is the first release of FreeRDP under the Apache License 2.0. The FreeRDP 1.x series is a rewrite, meaning there is no continuity with the previous FreeRDP 0.x series which were released under GPLv2. New Features: * RemoteFX * Both encoder and decoder * SSE2 and NEON optimization * NSCodec * RemoteApp * Working, minor glitches * Multimedia Redirection * ffmpeg support * Network Level Authentication (NLA) * NTLMv2 * Certificate validation * FIPS-compliant RDP security * new build system (cmake) * added official logo and icon New Architecture: * libfreerdp-core * core protocol * highly portable * both client and server * libfreerdp-cache * caching operations * libfreerdp-codec * bitmap decompression * codec encoding/decoding * libfreerdp-kbd * keyboard mapping * libfreerdp-channels * virtual channel management * client and server side support * libfreerdp-gdi * extensively unit tested * portable software GDI implementation * libfreerdp-rail * RemoteApp library * libfreerdp-utils * shared utility library FreeRDP Clients: * client/X11 (xfreerdp) * official client * RemoteApp support * X11 GDI implementation * client/DirectFB (dfreerdp) * DirectFB support * software-based GDI (libfreerdp-gdi) * client/Windows (wfreerdp) * Native Win32 support FreeRDP Servers (experimental): * server/X11 (xfreerdp-server) * RemoteFX-only * no authentication * highly experimental * keyboard and mouse input supported Virtual Channels: * cliprdr (Clipboard Redirection) * rail (RemoteApp) * drdynvc (Dynamic Virtual Channels) * audin (Audio Input Redirection) * alsa support * pulse support * tsmf (Multimedia Redirection) * alsa support * pulse support * ffmpeg support * rdpdr (Device Redirection) * disk (Disk Redirection) * parallel (Parallel Port Redirection) * serial (Serial Port Redirection) * printer (Printer Redirection) * CUPS support * smartcard (Smartcard Redirection) * rdpsnd (Sound Redirection) * alsa support * pulse support
null
174
CWE-787
CVE-2020-14147
/* ** {====================================================== ** Library for packing/unpacking structures. ** $Id: struct.c,v 1.7 2018/05/11 22:04:31 roberto Exp $ ** See Copyright Notice at the end of this file ** ======================================================= */ /* ** Valid formats: ** > - big endian ** < - little endian ** ![num] - alignment ** x - pading ** b/B - signed/unsigned byte ** h/H - signed/unsigned short ** l/L - signed/unsigned long ** T - size_t ** i/In - signed/unsigned integer with size 'n' (default is size of int) ** cn - sequence of 'n' chars (from/to a string); when packing, n==0 means the whole string; when unpacking, n==0 means use the previous read number as the string length ** s - zero-terminated string ** f - float ** d - double ** ' ' - ignored */ #include <assert.h> #include <ctype.h> #include <limits.h> #include <stddef.h> #include <string.h> #include "lua.h" #include "lauxlib.h" #if (LUA_VERSION_NUM >= 502) #define luaL_register(L,n,f) luaL_newlib(L,f) #endif /* basic integer type */ #if !defined(STRUCT_INT) #define STRUCT_INT long #endif typedef STRUCT_INT Inttype; /* corresponding unsigned version */ typedef unsigned STRUCT_INT Uinttype; /* maximum size (in bytes) for integral types */ #define MAXINTSIZE 32 /* is 'x' a power of 2? */ #define isp2(x) ((x) > 0 && ((x) & ((x) - 1)) == 0) /* dummy structure to get alignment requirements */ struct cD { char c; double d; }; #define PADDING (sizeof(struct cD) - sizeof(double)) #define MAXALIGN (PADDING > sizeof(int) ? PADDING : sizeof(int)) /* endian options */ #define BIG 0 #define LITTLE 1 static union { int dummy; char endian; } const native = {1}; typedef struct Header { int endian; int align; } Header; static int getnum (const char **fmt, int df) { if (!isdigit(**fmt)) /* no number? */ return df; /* return default value */ else { int a = 0; do { a = a*10 + *((*fmt)++) - '0'; } while (isdigit(**fmt)); return a; } } #define defaultoptions(h) ((h)->endian = native.endian, (h)->align = 1) static size_t optsize (lua_State *L, char opt, const char **fmt) { switch (opt) { case 'B': case 'b': return sizeof(char); case 'H': case 'h': return sizeof(short); case 'L': case 'l': return sizeof(long); case 'T': return sizeof(size_t); case 'f': return sizeof(float); case 'd': return sizeof(double); case 'x': return 1; case 'c': return getnum(fmt, 1); case 'i': case 'I': { int sz = getnum(fmt, sizeof(int)); if (sz > MAXINTSIZE) luaL_error(L, "integral size %d is larger than limit of %d", sz, MAXINTSIZE); return sz; } default: return 0; /* other cases do not need alignment */ } } /* ** return number of bytes needed to align an element of size 'size' ** at current position 'len' */ static int gettoalign (size_t len, Header *h, int opt, size_t size) { if (size == 0 || opt == 'c') return 0; if (size > (size_t)h->align) size = h->align; /* respect max. alignment */ return (size - (len & (size - 1))) & (size - 1); } /* ** options to control endianess and alignment */ static void controloptions (lua_State *L, int opt, const char **fmt, Header *h) { switch (opt) { case ' ': return; /* ignore white spaces */ case '>': h->endian = BIG; return; case '<': h->endian = LITTLE; return; case '!': { int a = getnum(fmt, MAXALIGN); if (!isp2(a)) luaL_error(L, "alignment %d is not a power of 2", a); h->align = a; return; } default: { const char *msg = lua_pushfstring(L, "invalid format option '%c'", opt); luaL_argerror(L, 1, msg); } } } static void putinteger (lua_State *L, luaL_Buffer *b, int arg, int endian, int size) { lua_Number n = luaL_checknumber(L, arg); Uinttype value; char buff[MAXINTSIZE]; if (n < 0) value = (Uinttype)(Inttype)n; else value = (Uinttype)n; if (endian == LITTLE) { int i; for (i = 0; i < size; i++) { buff[i] = (value & 0xff); value >>= 8; } } else { int i; for (i = size - 1; i >= 0; i--) { buff[i] = (value & 0xff); value >>= 8; } } luaL_addlstring(b, buff, size); } static void correctbytes (char *b, int size, int endian) { if (endian != native.endian) { int i = 0; while (i < --size) { char temp = b[i]; b[i++] = b[size]; b[size] = temp; } } } static int b_pack (lua_State *L) { luaL_Buffer b; const char *fmt = luaL_checkstring(L, 1); Header h; int arg = 2; size_t totalsize = 0; defaultoptions(&h); lua_pushnil(L); /* mark to separate arguments from string buffer */ luaL_buffinit(L, &b); while (*fmt != '\0') { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); int toalign = gettoalign(totalsize, &h, opt, size); totalsize += toalign; while (toalign-- > 0) luaL_addchar(&b, '\0'); switch (opt) { case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */ putinteger(L, &b, arg++, h.endian, size); break; } case 'x': { luaL_addchar(&b, '\0'); break; } case 'f': { float f = (float)luaL_checknumber(L, arg++); correctbytes((char *)&f, size, h.endian); luaL_addlstring(&b, (char *)&f, size); break; } case 'd': { double d = luaL_checknumber(L, arg++); correctbytes((char *)&d, size, h.endian); luaL_addlstring(&b, (char *)&d, size); break; } case 'c': case 's': { size_t l; const char *s = luaL_checklstring(L, arg++, &l); if (size == 0) size = l; luaL_argcheck(L, l >= (size_t)size, arg, "string too short"); luaL_addlstring(&b, s, size); if (opt == 's') { luaL_addchar(&b, '\0'); /* add zero at the end */ size++; } break; } default: controloptions(L, opt, &fmt, &h); } totalsize += size; } luaL_pushresult(&b); return 1; } static lua_Number getinteger (const char *buff, int endian, int issigned, int size) { Uinttype l = 0; int i; if (endian == BIG) { for (i = 0; i < size; i++) { l <<= 8; l |= (Uinttype)(unsigned char)buff[i]; } } else { for (i = size - 1; i >= 0; i--) { l <<= 8; l |= (Uinttype)(unsigned char)buff[i]; } } if (!issigned) return (lua_Number)l; else { /* signed format */ Uinttype mask = (Uinttype)(~((Uinttype)0)) << (size*8 - 1); if (l & mask) /* negative value? */ l |= mask; /* signal extension */ return (lua_Number)(Inttype)l; } } static int b_unpack (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t ld; const char *data = luaL_checklstring(L, 2, &ld); size_t pos = luaL_optinteger(L, 3, 1); luaL_argcheck(L, pos > 0, 3, "offset must be 1 or greater"); pos--; /* Lua indexes are 1-based, but here we want 0-based for C * pointer math. */ int n = 0; /* number of results */ defaultoptions(&h); while (*fmt) { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); pos += gettoalign(pos, &h, opt, size); luaL_argcheck(L, size <= ld && pos <= ld - size, 2, "data string too short"); /* stack space for item + next position */ luaL_checkstack(L, 2, "too many results"); switch (opt) { case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */ int issigned = islower(opt); lua_Number res = getinteger(data+pos, h.endian, issigned, size); lua_pushnumber(L, res); n++; break; } case 'x': { break; } case 'f': { float f; memcpy(&f, data+pos, size); correctbytes((char *)&f, sizeof(f), h.endian); lua_pushnumber(L, f); n++; break; } case 'd': { double d; memcpy(&d, data+pos, size); correctbytes((char *)&d, sizeof(d), h.endian); lua_pushnumber(L, d); n++; break; } case 'c': { if (size == 0) { if (n == 0 || !lua_isnumber(L, -1)) luaL_error(L, "format 'c0' needs a previous size"); size = lua_tonumber(L, -1); lua_pop(L, 1); n--; luaL_argcheck(L, size <= ld && pos <= ld - size, 2, "data string too short"); } lua_pushlstring(L, data+pos, size); n++; break; } case 's': { const char *e = (const char *)memchr(data+pos, '\0', ld - pos); if (e == NULL) luaL_error(L, "unfinished string in data"); size = (e - (data+pos)) + 1; lua_pushlstring(L, data+pos, size - 1); n++; break; } default: controloptions(L, opt, &fmt, &h); } pos += size; } lua_pushinteger(L, pos + 1); /* next position */ return n + 1; } static int b_size (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t pos = 0; defaultoptions(&h); while (*fmt) { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); pos += gettoalign(pos, &h, opt, size); if (opt == 's') luaL_argerror(L, 1, "option 's' has no fixed size"); else if (opt == 'c' && size == 0) luaL_argerror(L, 1, "option 'c0' has no fixed size"); if (!isalnum(opt)) controloptions(L, opt, &fmt, &h); pos += size; } lua_pushinteger(L, pos); return 1; } /* }====================================================== */ static const struct luaL_Reg thislib[] = { {"pack", b_pack}, {"unpack", b_unpack}, {"size", b_size}, {NULL, NULL} }; LUALIB_API int luaopen_struct (lua_State *L); LUALIB_API int luaopen_struct (lua_State *L) { luaL_register(L, "struct", thislib); return 1; } /****************************************************************************** * Copyright (C) 2010-2018 Lua.org, PUC-Rio. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/
null
/* ** {====================================================== ** Library for packing/unpacking structures. ** $Id: struct.c,v 1.7 2018/05/11 22:04:31 roberto Exp $ ** See Copyright Notice at the end of this file ** ======================================================= */ /* ** Valid formats: ** > - big endian ** < - little endian ** ![num] - alignment ** x - pading ** b/B - signed/unsigned byte ** h/H - signed/unsigned short ** l/L - signed/unsigned long ** T - size_t ** i/In - signed/unsigned integer with size 'n' (default is size of int) ** cn - sequence of 'n' chars (from/to a string); when packing, n==0 means the whole string; when unpacking, n==0 means use the previous read number as the string length ** s - zero-terminated string ** f - float ** d - double ** ' ' - ignored */ #include <assert.h> #include <ctype.h> #include <limits.h> #include <stddef.h> #include <string.h> #include "lua.h" #include "lauxlib.h" #if (LUA_VERSION_NUM >= 502) #define luaL_register(L,n,f) luaL_newlib(L,f) #endif /* basic integer type */ #if !defined(STRUCT_INT) #define STRUCT_INT long #endif typedef STRUCT_INT Inttype; /* corresponding unsigned version */ typedef unsigned STRUCT_INT Uinttype; /* maximum size (in bytes) for integral types */ #define MAXINTSIZE 32 /* is 'x' a power of 2? */ #define isp2(x) ((x) > 0 && ((x) & ((x) - 1)) == 0) /* dummy structure to get alignment requirements */ struct cD { char c; double d; }; #define PADDING (sizeof(struct cD) - sizeof(double)) #define MAXALIGN (PADDING > sizeof(int) ? PADDING : sizeof(int)) /* endian options */ #define BIG 0 #define LITTLE 1 static union { int dummy; char endian; } const native = {1}; typedef struct Header { int endian; int align; } Header; static int getnum (lua_State *L, const char **fmt, int df) { if (!isdigit(**fmt)) /* no number? */ return df; /* return default value */ else { int a = 0; do { if (a > (INT_MAX / 10) || a * 10 > (INT_MAX - (**fmt - '0'))) luaL_error(L, "integral size overflow"); a = a*10 + *((*fmt)++) - '0'; } while (isdigit(**fmt)); return a; } } #define defaultoptions(h) ((h)->endian = native.endian, (h)->align = 1) static size_t optsize (lua_State *L, char opt, const char **fmt) { switch (opt) { case 'B': case 'b': return sizeof(char); case 'H': case 'h': return sizeof(short); case 'L': case 'l': return sizeof(long); case 'T': return sizeof(size_t); case 'f': return sizeof(float); case 'd': return sizeof(double); case 'x': return 1; case 'c': return getnum(L, fmt, 1); case 'i': case 'I': { int sz = getnum(L, fmt, sizeof(int)); if (sz > MAXINTSIZE) luaL_error(L, "integral size %d is larger than limit of %d", sz, MAXINTSIZE); return sz; } default: return 0; /* other cases do not need alignment */ } } /* ** return number of bytes needed to align an element of size 'size' ** at current position 'len' */ static int gettoalign (size_t len, Header *h, int opt, size_t size) { if (size == 0 || opt == 'c') return 0; if (size > (size_t)h->align) size = h->align; /* respect max. alignment */ return (size - (len & (size - 1))) & (size - 1); } /* ** options to control endianess and alignment */ static void controloptions (lua_State *L, int opt, const char **fmt, Header *h) { switch (opt) { case ' ': return; /* ignore white spaces */ case '>': h->endian = BIG; return; case '<': h->endian = LITTLE; return; case '!': { int a = getnum(L, fmt, MAXALIGN); if (!isp2(a)) luaL_error(L, "alignment %d is not a power of 2", a); h->align = a; return; } default: { const char *msg = lua_pushfstring(L, "invalid format option '%c'", opt); luaL_argerror(L, 1, msg); } } } static void putinteger (lua_State *L, luaL_Buffer *b, int arg, int endian, int size) { lua_Number n = luaL_checknumber(L, arg); Uinttype value; char buff[MAXINTSIZE]; if (n < 0) value = (Uinttype)(Inttype)n; else value = (Uinttype)n; if (endian == LITTLE) { int i; for (i = 0; i < size; i++) { buff[i] = (value & 0xff); value >>= 8; } } else { int i; for (i = size - 1; i >= 0; i--) { buff[i] = (value & 0xff); value >>= 8; } } luaL_addlstring(b, buff, size); } static void correctbytes (char *b, int size, int endian) { if (endian != native.endian) { int i = 0; while (i < --size) { char temp = b[i]; b[i++] = b[size]; b[size] = temp; } } } static int b_pack (lua_State *L) { luaL_Buffer b; const char *fmt = luaL_checkstring(L, 1); Header h; int arg = 2; size_t totalsize = 0; defaultoptions(&h); lua_pushnil(L); /* mark to separate arguments from string buffer */ luaL_buffinit(L, &b); while (*fmt != '\0') { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); int toalign = gettoalign(totalsize, &h, opt, size); totalsize += toalign; while (toalign-- > 0) luaL_addchar(&b, '\0'); switch (opt) { case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */ putinteger(L, &b, arg++, h.endian, size); break; } case 'x': { luaL_addchar(&b, '\0'); break; } case 'f': { float f = (float)luaL_checknumber(L, arg++); correctbytes((char *)&f, size, h.endian); luaL_addlstring(&b, (char *)&f, size); break; } case 'd': { double d = luaL_checknumber(L, arg++); correctbytes((char *)&d, size, h.endian); luaL_addlstring(&b, (char *)&d, size); break; } case 'c': case 's': { size_t l; const char *s = luaL_checklstring(L, arg++, &l); if (size == 0) size = l; luaL_argcheck(L, l >= (size_t)size, arg, "string too short"); luaL_addlstring(&b, s, size); if (opt == 's') { luaL_addchar(&b, '\0'); /* add zero at the end */ size++; } break; } default: controloptions(L, opt, &fmt, &h); } totalsize += size; } luaL_pushresult(&b); return 1; } static lua_Number getinteger (const char *buff, int endian, int issigned, int size) { Uinttype l = 0; int i; if (endian == BIG) { for (i = 0; i < size; i++) { l <<= 8; l |= (Uinttype)(unsigned char)buff[i]; } } else { for (i = size - 1; i >= 0; i--) { l <<= 8; l |= (Uinttype)(unsigned char)buff[i]; } } if (!issigned) return (lua_Number)l; else { /* signed format */ Uinttype mask = (Uinttype)(~((Uinttype)0)) << (size*8 - 1); if (l & mask) /* negative value? */ l |= mask; /* signal extension */ return (lua_Number)(Inttype)l; } } static int b_unpack (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t ld; const char *data = luaL_checklstring(L, 2, &ld); size_t pos = luaL_optinteger(L, 3, 1); luaL_argcheck(L, pos > 0, 3, "offset must be 1 or greater"); pos--; /* Lua indexes are 1-based, but here we want 0-based for C * pointer math. */ int n = 0; /* number of results */ defaultoptions(&h); while (*fmt) { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); pos += gettoalign(pos, &h, opt, size); luaL_argcheck(L, size <= ld && pos <= ld - size, 2, "data string too short"); /* stack space for item + next position */ luaL_checkstack(L, 2, "too many results"); switch (opt) { case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */ int issigned = islower(opt); lua_Number res = getinteger(data+pos, h.endian, issigned, size); lua_pushnumber(L, res); n++; break; } case 'x': { break; } case 'f': { float f; memcpy(&f, data+pos, size); correctbytes((char *)&f, sizeof(f), h.endian); lua_pushnumber(L, f); n++; break; } case 'd': { double d; memcpy(&d, data+pos, size); correctbytes((char *)&d, sizeof(d), h.endian); lua_pushnumber(L, d); n++; break; } case 'c': { if (size == 0) { if (n == 0 || !lua_isnumber(L, -1)) luaL_error(L, "format 'c0' needs a previous size"); size = lua_tonumber(L, -1); lua_pop(L, 1); n--; luaL_argcheck(L, size <= ld && pos <= ld - size, 2, "data string too short"); } lua_pushlstring(L, data+pos, size); n++; break; } case 's': { const char *e = (const char *)memchr(data+pos, '\0', ld - pos); if (e == NULL) luaL_error(L, "unfinished string in data"); size = (e - (data+pos)) + 1; lua_pushlstring(L, data+pos, size - 1); n++; break; } default: controloptions(L, opt, &fmt, &h); } pos += size; } lua_pushinteger(L, pos + 1); /* next position */ return n + 1; } static int b_size (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t pos = 0; defaultoptions(&h); while (*fmt) { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); pos += gettoalign(pos, &h, opt, size); if (opt == 's') luaL_argerror(L, 1, "option 's' has no fixed size"); else if (opt == 'c' && size == 0) luaL_argerror(L, 1, "option 'c0' has no fixed size"); if (!isalnum(opt)) controloptions(L, opt, &fmt, &h); pos += size; } lua_pushinteger(L, pos); return 1; } /* }====================================================== */ static const struct luaL_Reg thislib[] = { {"pack", b_pack}, {"unpack", b_unpack}, {"size", b_size}, {NULL, NULL} }; LUALIB_API int luaopen_struct (lua_State *L); LUALIB_API int luaopen_struct (lua_State *L) { luaL_register(L, "struct", thislib); return 1; } /****************************************************************************** * Copyright (C) 2010-2018 Lua.org, PUC-Rio. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/
null
175
CWE-787
CVE-2020-14402
/* * rre.c * * Routines to implement Rise-and-Run-length Encoding (RRE). This * code is based on krw's original javatel rfbserver. */ /* * OSXvnc Copyright (C) 2001 Dan McGuirk <mcguirk@incompleteness.net>. * Original Xvnc code Copyright (C) 1999 AT&T Laboratories Cambridge. * All Rights Reserved. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ #include <rfb/rfb.h> /* * cl->beforeEncBuf contains pixel data in the client's format. * cl->afterEncBuf contains the RRE encoded version. If the RRE encoded version is * larger than the raw data or if it exceeds cl->afterEncBufSize then * raw encoding is used instead. */ static int subrectEncode8(rfbClientPtr cl, uint8_t *data, int w, int h); static int subrectEncode16(rfbClientPtr cl, uint16_t *data, int w, int h); static int subrectEncode32(rfbClientPtr cl, uint32_t *data, int w, int h); static uint32_t getBgColour(char *data, int size, int bpp); /* * rfbSendRectEncodingRRE - send a given rectangle using RRE encoding. */ rfbBool rfbSendRectEncodingRRE(rfbClientPtr cl, int x, int y, int w, int h) { rfbFramebufferUpdateRectHeader rect; rfbRREHeader hdr; int nSubrects; int i; char *fbptr = (cl->scaledScreen->frameBuffer + (cl->scaledScreen->paddedWidthInBytes * y) + (x * (cl->scaledScreen->bitsPerPixel / 8))); int maxRawSize = (cl->scaledScreen->width * cl->scaledScreen->height * (cl->format.bitsPerPixel / 8)); if (cl->beforeEncBufSize < maxRawSize) { cl->beforeEncBufSize = maxRawSize; if (cl->beforeEncBuf == NULL) cl->beforeEncBuf = (char *)malloc(cl->beforeEncBufSize); else cl->beforeEncBuf = (char *)realloc(cl->beforeEncBuf, cl->beforeEncBufSize); } if (cl->afterEncBufSize < maxRawSize) { cl->afterEncBufSize = maxRawSize; if (cl->afterEncBuf == NULL) cl->afterEncBuf = (char *)malloc(cl->afterEncBufSize); else cl->afterEncBuf = (char *)realloc(cl->afterEncBuf, cl->afterEncBufSize); } (*cl->translateFn)(cl->translateLookupTable, &(cl->screen->serverFormat), &cl->format, fbptr, cl->beforeEncBuf, cl->scaledScreen->paddedWidthInBytes, w, h); switch (cl->format.bitsPerPixel) { case 8: nSubrects = subrectEncode8(cl, (uint8_t *)cl->beforeEncBuf, w, h); break; case 16: nSubrects = subrectEncode16(cl, (uint16_t *)cl->beforeEncBuf, w, h); break; case 32: nSubrects = subrectEncode32(cl, (uint32_t *)cl->beforeEncBuf, w, h); break; default: rfbLog("getBgColour: bpp %d?\n",cl->format.bitsPerPixel); return FALSE; } if (nSubrects < 0) { /* RRE encoding was too large, use raw */ return rfbSendRectEncodingRaw(cl, x, y, w, h); } rfbStatRecordEncodingSent(cl, rfbEncodingRRE, sz_rfbFramebufferUpdateRectHeader + sz_rfbRREHeader + cl->afterEncBufLen, sz_rfbFramebufferUpdateRectHeader + w * h * (cl->format.bitsPerPixel / 8)); if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + sz_rfbRREHeader > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.r.x = Swap16IfLE(x); rect.r.y = Swap16IfLE(y); rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); rect.encoding = Swap32IfLE(rfbEncodingRRE); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; hdr.nSubrects = Swap32IfLE(nSubrects); memcpy(&cl->updateBuf[cl->ublen], (char *)&hdr, sz_rfbRREHeader); cl->ublen += sz_rfbRREHeader; for (i = 0; i < cl->afterEncBufLen;) { int bytesToCopy = UPDATE_BUF_SIZE - cl->ublen; if (i + bytesToCopy > cl->afterEncBufLen) { bytesToCopy = cl->afterEncBufLen - i; } memcpy(&cl->updateBuf[cl->ublen], &cl->afterEncBuf[i], bytesToCopy); cl->ublen += bytesToCopy; i += bytesToCopy; if (cl->ublen == UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } } return TRUE; } /* * subrectEncode() encodes the given multicoloured rectangle as a background * colour overwritten by single-coloured rectangles. It returns the number * of subrectangles in the encoded buffer, or -1 if subrect encoding won't * fit in the buffer. It puts the encoded rectangles in cl->afterEncBuf. The * single-colour rectangle partition is not optimal, but does find the biggest * horizontal or vertical rectangle top-left anchored to each consecutive * coordinate position. * * The coding scheme is simply [<bgcolour><subrect><subrect>...] where each * <subrect> is [<colour><x><y><w><h>]. */ #define DEFINE_SUBRECT_ENCODE(bpp) \ static int \ subrectEncode##bpp(rfbClientPtr client, uint##bpp##_t *data, int w, int h) { \ uint##bpp##_t cl; \ rfbRectangle subrect; \ int x,y; \ int i,j; \ int hx=0,hy,vx=0,vy; \ int hyflag; \ uint##bpp##_t *seg; \ uint##bpp##_t *line; \ int hw,hh,vw,vh; \ int thex,they,thew,theh; \ int numsubs = 0; \ int newLen; \ uint##bpp##_t bg = (uint##bpp##_t)getBgColour((char*)data,w*h,bpp); \ \ *((uint##bpp##_t*)client->afterEncBuf) = bg; \ \ client->afterEncBufLen = (bpp/8); \ \ for (y=0; y<h; y++) { \ line = data+(y*w); \ for (x=0; x<w; x++) { \ if (line[x] != bg) { \ cl = line[x]; \ hy = y-1; \ hyflag = 1; \ for (j=y; j<h; j++) { \ seg = data+(j*w); \ if (seg[x] != cl) {break;} \ i = x; \ while ((seg[i] == cl) && (i < w)) i += 1; \ i -= 1; \ if (j == y) vx = hx = i; \ if (i < vx) vx = i; \ if ((hyflag > 0) && (i >= hx)) {hy += 1;} else {hyflag = 0;} \ } \ vy = j-1; \ \ /* We now have two possible subrects: (x,y,hx,hy) and (x,y,vx,vy) \ * We'll choose the bigger of the two. \ */ \ hw = hx-x+1; \ hh = hy-y+1; \ vw = vx-x+1; \ vh = vy-y+1; \ \ thex = x; \ they = y; \ \ if ((hw*hh) > (vw*vh)) { \ thew = hw; \ theh = hh; \ } else { \ thew = vw; \ theh = vh; \ } \ \ subrect.x = Swap16IfLE(thex); \ subrect.y = Swap16IfLE(they); \ subrect.w = Swap16IfLE(thew); \ subrect.h = Swap16IfLE(theh); \ \ newLen = client->afterEncBufLen + (bpp/8) + sz_rfbRectangle; \ if ((newLen > (w * h * (bpp/8))) || (newLen > client->afterEncBufSize)) \ return -1; \ \ numsubs += 1; \ *((uint##bpp##_t*)(client->afterEncBuf + client->afterEncBufLen)) = cl; \ client->afterEncBufLen += (bpp/8); \ memcpy(&client->afterEncBuf[client->afterEncBufLen],&subrect,sz_rfbRectangle); \ client->afterEncBufLen += sz_rfbRectangle; \ \ /* \ * Now mark the subrect as done. \ */ \ for (j=they; j < (they+theh); j++) { \ for (i=thex; i < (thex+thew); i++) { \ data[j*w+i] = bg; \ } \ } \ } \ } \ } \ \ return numsubs; \ } DEFINE_SUBRECT_ENCODE(8) DEFINE_SUBRECT_ENCODE(16) DEFINE_SUBRECT_ENCODE(32) /* * getBgColour() gets the most prevalent colour in a byte array. */ static uint32_t getBgColour(char *data, int size, int bpp) { #define NUMCLRS 256 static int counts[NUMCLRS]; int i,j,k; int maxcount = 0; uint8_t maxclr = 0; if (bpp != 8) { if (bpp == 16) { return ((uint16_t *)data)[0]; } else if (bpp == 32) { return ((uint32_t *)data)[0]; } else { rfbLog("getBgColour: bpp %d?\n",bpp); return 0; } } for (i=0; i<NUMCLRS; i++) { counts[i] = 0; } for (j=0; j<size; j++) { k = (int)(((uint8_t *)data)[j]); if (k >= NUMCLRS) { rfbErr("getBgColour: unusual colour = %d\n", k); return 0; } counts[k] += 1; if (counts[k] > maxcount) { maxcount = counts[k]; maxclr = ((uint8_t *)data)[j]; } } return maxclr; }
null
/* * rre.c * * Routines to implement Rise-and-Run-length Encoding (RRE). This * code is based on krw's original javatel rfbserver. */ /* * OSXvnc Copyright (C) 2001 Dan McGuirk <mcguirk@incompleteness.net>. * Original Xvnc code Copyright (C) 1999 AT&T Laboratories Cambridge. * All Rights Reserved. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ #include <rfb/rfb.h> /* * cl->beforeEncBuf contains pixel data in the client's format. * cl->afterEncBuf contains the RRE encoded version. If the RRE encoded version is * larger than the raw data or if it exceeds cl->afterEncBufSize then * raw encoding is used instead. */ static int subrectEncode8(rfbClientPtr cl, uint8_t *data, int w, int h); static int subrectEncode16(rfbClientPtr cl, uint16_t *data, int w, int h); static int subrectEncode32(rfbClientPtr cl, uint32_t *data, int w, int h); static uint32_t getBgColour(char *data, int size, int bpp); /* * rfbSendRectEncodingRRE - send a given rectangle using RRE encoding. */ rfbBool rfbSendRectEncodingRRE(rfbClientPtr cl, int x, int y, int w, int h) { rfbFramebufferUpdateRectHeader rect; rfbRREHeader hdr; int nSubrects; int i; char *fbptr = (cl->scaledScreen->frameBuffer + (cl->scaledScreen->paddedWidthInBytes * y) + (x * (cl->scaledScreen->bitsPerPixel / 8))); int maxRawSize = (cl->scaledScreen->width * cl->scaledScreen->height * (cl->format.bitsPerPixel / 8)); if (cl->beforeEncBufSize < maxRawSize) { cl->beforeEncBufSize = maxRawSize; if (cl->beforeEncBuf == NULL) cl->beforeEncBuf = (char *)malloc(cl->beforeEncBufSize); else cl->beforeEncBuf = (char *)realloc(cl->beforeEncBuf, cl->beforeEncBufSize); } if (cl->afterEncBufSize < maxRawSize) { cl->afterEncBufSize = maxRawSize; if (cl->afterEncBuf == NULL) cl->afterEncBuf = (char *)malloc(cl->afterEncBufSize); else cl->afterEncBuf = (char *)realloc(cl->afterEncBuf, cl->afterEncBufSize); } (*cl->translateFn)(cl->translateLookupTable, &(cl->screen->serverFormat), &cl->format, fbptr, cl->beforeEncBuf, cl->scaledScreen->paddedWidthInBytes, w, h); switch (cl->format.bitsPerPixel) { case 8: nSubrects = subrectEncode8(cl, (uint8_t *)cl->beforeEncBuf, w, h); break; case 16: nSubrects = subrectEncode16(cl, (uint16_t *)cl->beforeEncBuf, w, h); break; case 32: nSubrects = subrectEncode32(cl, (uint32_t *)cl->beforeEncBuf, w, h); break; default: rfbLog("getBgColour: bpp %d?\n",cl->format.bitsPerPixel); return FALSE; } if (nSubrects < 0) { /* RRE encoding was too large, use raw */ return rfbSendRectEncodingRaw(cl, x, y, w, h); } rfbStatRecordEncodingSent(cl, rfbEncodingRRE, sz_rfbFramebufferUpdateRectHeader + sz_rfbRREHeader + cl->afterEncBufLen, sz_rfbFramebufferUpdateRectHeader + w * h * (cl->format.bitsPerPixel / 8)); if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + sz_rfbRREHeader > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.r.x = Swap16IfLE(x); rect.r.y = Swap16IfLE(y); rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); rect.encoding = Swap32IfLE(rfbEncodingRRE); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; hdr.nSubrects = Swap32IfLE(nSubrects); memcpy(&cl->updateBuf[cl->ublen], (char *)&hdr, sz_rfbRREHeader); cl->ublen += sz_rfbRREHeader; for (i = 0; i < cl->afterEncBufLen;) { int bytesToCopy = UPDATE_BUF_SIZE - cl->ublen; if (i + bytesToCopy > cl->afterEncBufLen) { bytesToCopy = cl->afterEncBufLen - i; } memcpy(&cl->updateBuf[cl->ublen], &cl->afterEncBuf[i], bytesToCopy); cl->ublen += bytesToCopy; i += bytesToCopy; if (cl->ublen == UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } } return TRUE; } /* * subrectEncode() encodes the given multicoloured rectangle as a background * colour overwritten by single-coloured rectangles. It returns the number * of subrectangles in the encoded buffer, or -1 if subrect encoding won't * fit in the buffer. It puts the encoded rectangles in cl->afterEncBuf. The * single-colour rectangle partition is not optimal, but does find the biggest * horizontal or vertical rectangle top-left anchored to each consecutive * coordinate position. * * The coding scheme is simply [<bgcolour><subrect><subrect>...] where each * <subrect> is [<colour><x><y><w><h>]. */ #define DEFINE_SUBRECT_ENCODE(bpp) \ static int \ subrectEncode##bpp(rfbClientPtr client, uint##bpp##_t *data, int w, int h) { \ uint##bpp##_t cl; \ rfbRectangle subrect; \ int x,y; \ int i,j; \ int hx=0,hy,vx=0,vy; \ int hyflag; \ uint##bpp##_t *seg; \ uint##bpp##_t *line; \ int hw,hh,vw,vh; \ int thex,they,thew,theh; \ int numsubs = 0; \ int newLen; \ uint##bpp##_t bg = (uint##bpp##_t)getBgColour((char*)data,w*h,bpp); \ \ *((uint##bpp##_t*)client->afterEncBuf) = bg; \ \ client->afterEncBufLen = (bpp/8); \ \ for (y=0; y<h; y++) { \ line = data+(y*w); \ for (x=0; x<w; x++) { \ if (line[x] != bg) { \ cl = line[x]; \ hy = y-1; \ hyflag = 1; \ for (j=y; j<h; j++) { \ seg = data+(j*w); \ if (seg[x] != cl) {break;} \ i = x; \ while ((i < w) && (seg[i] == cl)) i += 1; \ i -= 1; \ if (j == y) vx = hx = i; \ if (i < vx) vx = i; \ if ((hyflag > 0) && (i >= hx)) {hy += 1;} else {hyflag = 0;} \ } \ vy = j-1; \ \ /* We now have two possible subrects: (x,y,hx,hy) and (x,y,vx,vy) \ * We'll choose the bigger of the two. \ */ \ hw = hx-x+1; \ hh = hy-y+1; \ vw = vx-x+1; \ vh = vy-y+1; \ \ thex = x; \ they = y; \ \ if ((hw*hh) > (vw*vh)) { \ thew = hw; \ theh = hh; \ } else { \ thew = vw; \ theh = vh; \ } \ \ subrect.x = Swap16IfLE(thex); \ subrect.y = Swap16IfLE(they); \ subrect.w = Swap16IfLE(thew); \ subrect.h = Swap16IfLE(theh); \ \ newLen = client->afterEncBufLen + (bpp/8) + sz_rfbRectangle; \ if ((newLen > (w * h * (bpp/8))) || (newLen > client->afterEncBufSize)) \ return -1; \ \ numsubs += 1; \ *((uint##bpp##_t*)(client->afterEncBuf + client->afterEncBufLen)) = cl; \ client->afterEncBufLen += (bpp/8); \ memcpy(&client->afterEncBuf[client->afterEncBufLen],&subrect,sz_rfbRectangle); \ client->afterEncBufLen += sz_rfbRectangle; \ \ /* \ * Now mark the subrect as done. \ */ \ for (j=they; j < (they+theh); j++) { \ for (i=thex; i < (thex+thew); i++) { \ data[j*w+i] = bg; \ } \ } \ } \ } \ } \ \ return numsubs; \ } DEFINE_SUBRECT_ENCODE(8) DEFINE_SUBRECT_ENCODE(16) DEFINE_SUBRECT_ENCODE(32) /* * getBgColour() gets the most prevalent colour in a byte array. */ static uint32_t getBgColour(char *data, int size, int bpp) { #define NUMCLRS 256 static int counts[NUMCLRS]; int i,j,k; int maxcount = 0; uint8_t maxclr = 0; if (bpp != 8) { if (bpp == 16) { return ((uint16_t *)data)[0]; } else if (bpp == 32) { return ((uint32_t *)data)[0]; } else { rfbLog("getBgColour: bpp %d?\n",bpp); return 0; } } for (i=0; i<NUMCLRS; i++) { counts[i] = 0; } for (j=0; j<size; j++) { k = (int)(((uint8_t *)data)[j]); if (k >= NUMCLRS) { rfbErr("getBgColour: unusual colour = %d\n", k); return 0; } counts[k] += 1; if (counts[k] > maxcount) { maxcount = counts[k]; maxclr = ((uint8_t *)data)[j]; } } return maxclr; }
null
176
CWE-787
CVE-2020-14403
/* * rre.c * * Routines to implement Rise-and-Run-length Encoding (RRE). This * code is based on krw's original javatel rfbserver. */ /* * OSXvnc Copyright (C) 2001 Dan McGuirk <mcguirk@incompleteness.net>. * Original Xvnc code Copyright (C) 1999 AT&T Laboratories Cambridge. * All Rights Reserved. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ #include <rfb/rfb.h> /* * cl->beforeEncBuf contains pixel data in the client's format. * cl->afterEncBuf contains the RRE encoded version. If the RRE encoded version is * larger than the raw data or if it exceeds cl->afterEncBufSize then * raw encoding is used instead. */ static int subrectEncode8(rfbClientPtr cl, uint8_t *data, int w, int h); static int subrectEncode16(rfbClientPtr cl, uint16_t *data, int w, int h); static int subrectEncode32(rfbClientPtr cl, uint32_t *data, int w, int h); static uint32_t getBgColour(char *data, int size, int bpp); /* * rfbSendRectEncodingRRE - send a given rectangle using RRE encoding. */ rfbBool rfbSendRectEncodingRRE(rfbClientPtr cl, int x, int y, int w, int h) { rfbFramebufferUpdateRectHeader rect; rfbRREHeader hdr; int nSubrects; int i; char *fbptr = (cl->scaledScreen->frameBuffer + (cl->scaledScreen->paddedWidthInBytes * y) + (x * (cl->scaledScreen->bitsPerPixel / 8))); int maxRawSize = (cl->scaledScreen->width * cl->scaledScreen->height * (cl->format.bitsPerPixel / 8)); if (cl->beforeEncBufSize < maxRawSize) { cl->beforeEncBufSize = maxRawSize; if (cl->beforeEncBuf == NULL) cl->beforeEncBuf = (char *)malloc(cl->beforeEncBufSize); else cl->beforeEncBuf = (char *)realloc(cl->beforeEncBuf, cl->beforeEncBufSize); } if (cl->afterEncBufSize < maxRawSize) { cl->afterEncBufSize = maxRawSize; if (cl->afterEncBuf == NULL) cl->afterEncBuf = (char *)malloc(cl->afterEncBufSize); else cl->afterEncBuf = (char *)realloc(cl->afterEncBuf, cl->afterEncBufSize); } (*cl->translateFn)(cl->translateLookupTable, &(cl->screen->serverFormat), &cl->format, fbptr, cl->beforeEncBuf, cl->scaledScreen->paddedWidthInBytes, w, h); switch (cl->format.bitsPerPixel) { case 8: nSubrects = subrectEncode8(cl, (uint8_t *)cl->beforeEncBuf, w, h); break; case 16: nSubrects = subrectEncode16(cl, (uint16_t *)cl->beforeEncBuf, w, h); break; case 32: nSubrects = subrectEncode32(cl, (uint32_t *)cl->beforeEncBuf, w, h); break; default: rfbLog("getBgColour: bpp %d?\n",cl->format.bitsPerPixel); return FALSE; } if (nSubrects < 0) { /* RRE encoding was too large, use raw */ return rfbSendRectEncodingRaw(cl, x, y, w, h); } rfbStatRecordEncodingSent(cl, rfbEncodingRRE, sz_rfbFramebufferUpdateRectHeader + sz_rfbRREHeader + cl->afterEncBufLen, sz_rfbFramebufferUpdateRectHeader + w * h * (cl->format.bitsPerPixel / 8)); if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + sz_rfbRREHeader > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.r.x = Swap16IfLE(x); rect.r.y = Swap16IfLE(y); rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); rect.encoding = Swap32IfLE(rfbEncodingRRE); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; hdr.nSubrects = Swap32IfLE(nSubrects); memcpy(&cl->updateBuf[cl->ublen], (char *)&hdr, sz_rfbRREHeader); cl->ublen += sz_rfbRREHeader; for (i = 0; i < cl->afterEncBufLen;) { int bytesToCopy = UPDATE_BUF_SIZE - cl->ublen; if (i + bytesToCopy > cl->afterEncBufLen) { bytesToCopy = cl->afterEncBufLen - i; } memcpy(&cl->updateBuf[cl->ublen], &cl->afterEncBuf[i], bytesToCopy); cl->ublen += bytesToCopy; i += bytesToCopy; if (cl->ublen == UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } } return TRUE; } /* * subrectEncode() encodes the given multicoloured rectangle as a background * colour overwritten by single-coloured rectangles. It returns the number * of subrectangles in the encoded buffer, or -1 if subrect encoding won't * fit in the buffer. It puts the encoded rectangles in cl->afterEncBuf. The * single-colour rectangle partition is not optimal, but does find the biggest * horizontal or vertical rectangle top-left anchored to each consecutive * coordinate position. * * The coding scheme is simply [<bgcolour><subrect><subrect>...] where each * <subrect> is [<colour><x><y><w><h>]. */ #define DEFINE_SUBRECT_ENCODE(bpp) \ static int \ subrectEncode##bpp(rfbClientPtr client, uint##bpp##_t *data, int w, int h) { \ uint##bpp##_t cl; \ rfbRectangle subrect; \ int x,y; \ int i,j; \ int hx=0,hy,vx=0,vy; \ int hyflag; \ uint##bpp##_t *seg; \ uint##bpp##_t *line; \ int hw,hh,vw,vh; \ int thex,they,thew,theh; \ int numsubs = 0; \ int newLen; \ uint##bpp##_t bg = (uint##bpp##_t)getBgColour((char*)data,w*h,bpp); \ \ *((uint##bpp##_t*)client->afterEncBuf) = bg; \ \ client->afterEncBufLen = (bpp/8); \ \ for (y=0; y<h; y++) { \ line = data+(y*w); \ for (x=0; x<w; x++) { \ if (line[x] != bg) { \ cl = line[x]; \ hy = y-1; \ hyflag = 1; \ for (j=y; j<h; j++) { \ seg = data+(j*w); \ if (seg[x] != cl) {break;} \ i = x; \ while ((seg[i] == cl) && (i < w)) i += 1; \ i -= 1; \ if (j == y) vx = hx = i; \ if (i < vx) vx = i; \ if ((hyflag > 0) && (i >= hx)) {hy += 1;} else {hyflag = 0;} \ } \ vy = j-1; \ \ /* We now have two possible subrects: (x,y,hx,hy) and (x,y,vx,vy) \ * We'll choose the bigger of the two. \ */ \ hw = hx-x+1; \ hh = hy-y+1; \ vw = vx-x+1; \ vh = vy-y+1; \ \ thex = x; \ they = y; \ \ if ((hw*hh) > (vw*vh)) { \ thew = hw; \ theh = hh; \ } else { \ thew = vw; \ theh = vh; \ } \ \ subrect.x = Swap16IfLE(thex); \ subrect.y = Swap16IfLE(they); \ subrect.w = Swap16IfLE(thew); \ subrect.h = Swap16IfLE(theh); \ \ newLen = client->afterEncBufLen + (bpp/8) + sz_rfbRectangle; \ if ((newLen > (w * h * (bpp/8))) || (newLen > client->afterEncBufSize)) \ return -1; \ \ numsubs += 1; \ *((uint##bpp##_t*)(client->afterEncBuf + client->afterEncBufLen)) = cl; \ client->afterEncBufLen += (bpp/8); \ memcpy(&client->afterEncBuf[client->afterEncBufLen],&subrect,sz_rfbRectangle); \ client->afterEncBufLen += sz_rfbRectangle; \ \ /* \ * Now mark the subrect as done. \ */ \ for (j=they; j < (they+theh); j++) { \ for (i=thex; i < (thex+thew); i++) { \ data[j*w+i] = bg; \ } \ } \ } \ } \ } \ \ return numsubs; \ } DEFINE_SUBRECT_ENCODE(8) DEFINE_SUBRECT_ENCODE(16) DEFINE_SUBRECT_ENCODE(32) /* * getBgColour() gets the most prevalent colour in a byte array. */ static uint32_t getBgColour(char *data, int size, int bpp) { #define NUMCLRS 256 static int counts[NUMCLRS]; int i,j,k; int maxcount = 0; uint8_t maxclr = 0; if (bpp != 8) { if (bpp == 16) { return ((uint16_t *)data)[0]; } else if (bpp == 32) { return ((uint32_t *)data)[0]; } else { rfbLog("getBgColour: bpp %d?\n",bpp); return 0; } } for (i=0; i<NUMCLRS; i++) { counts[i] = 0; } for (j=0; j<size; j++) { k = (int)(((uint8_t *)data)[j]); if (k >= NUMCLRS) { rfbErr("getBgColour: unusual colour = %d\n", k); return 0; } counts[k] += 1; if (counts[k] > maxcount) { maxcount = counts[k]; maxclr = ((uint8_t *)data)[j]; } } return maxclr; }
null
/* * rre.c * * Routines to implement Rise-and-Run-length Encoding (RRE). This * code is based on krw's original javatel rfbserver. */ /* * OSXvnc Copyright (C) 2001 Dan McGuirk <mcguirk@incompleteness.net>. * Original Xvnc code Copyright (C) 1999 AT&T Laboratories Cambridge. * All Rights Reserved. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ #include <rfb/rfb.h> /* * cl->beforeEncBuf contains pixel data in the client's format. * cl->afterEncBuf contains the RRE encoded version. If the RRE encoded version is * larger than the raw data or if it exceeds cl->afterEncBufSize then * raw encoding is used instead. */ static int subrectEncode8(rfbClientPtr cl, uint8_t *data, int w, int h); static int subrectEncode16(rfbClientPtr cl, uint16_t *data, int w, int h); static int subrectEncode32(rfbClientPtr cl, uint32_t *data, int w, int h); static uint32_t getBgColour(char *data, int size, int bpp); /* * rfbSendRectEncodingRRE - send a given rectangle using RRE encoding. */ rfbBool rfbSendRectEncodingRRE(rfbClientPtr cl, int x, int y, int w, int h) { rfbFramebufferUpdateRectHeader rect; rfbRREHeader hdr; int nSubrects; int i; char *fbptr = (cl->scaledScreen->frameBuffer + (cl->scaledScreen->paddedWidthInBytes * y) + (x * (cl->scaledScreen->bitsPerPixel / 8))); int maxRawSize = (cl->scaledScreen->width * cl->scaledScreen->height * (cl->format.bitsPerPixel / 8)); if (cl->beforeEncBufSize < maxRawSize) { cl->beforeEncBufSize = maxRawSize; if (cl->beforeEncBuf == NULL) cl->beforeEncBuf = (char *)malloc(cl->beforeEncBufSize); else cl->beforeEncBuf = (char *)realloc(cl->beforeEncBuf, cl->beforeEncBufSize); } if (cl->afterEncBufSize < maxRawSize) { cl->afterEncBufSize = maxRawSize; if (cl->afterEncBuf == NULL) cl->afterEncBuf = (char *)malloc(cl->afterEncBufSize); else cl->afterEncBuf = (char *)realloc(cl->afterEncBuf, cl->afterEncBufSize); } (*cl->translateFn)(cl->translateLookupTable, &(cl->screen->serverFormat), &cl->format, fbptr, cl->beforeEncBuf, cl->scaledScreen->paddedWidthInBytes, w, h); switch (cl->format.bitsPerPixel) { case 8: nSubrects = subrectEncode8(cl, (uint8_t *)cl->beforeEncBuf, w, h); break; case 16: nSubrects = subrectEncode16(cl, (uint16_t *)cl->beforeEncBuf, w, h); break; case 32: nSubrects = subrectEncode32(cl, (uint32_t *)cl->beforeEncBuf, w, h); break; default: rfbLog("getBgColour: bpp %d?\n",cl->format.bitsPerPixel); return FALSE; } if (nSubrects < 0) { /* RRE encoding was too large, use raw */ return rfbSendRectEncodingRaw(cl, x, y, w, h); } rfbStatRecordEncodingSent(cl, rfbEncodingRRE, sz_rfbFramebufferUpdateRectHeader + sz_rfbRREHeader + cl->afterEncBufLen, sz_rfbFramebufferUpdateRectHeader + w * h * (cl->format.bitsPerPixel / 8)); if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + sz_rfbRREHeader > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.r.x = Swap16IfLE(x); rect.r.y = Swap16IfLE(y); rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); rect.encoding = Swap32IfLE(rfbEncodingRRE); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; hdr.nSubrects = Swap32IfLE(nSubrects); memcpy(&cl->updateBuf[cl->ublen], (char *)&hdr, sz_rfbRREHeader); cl->ublen += sz_rfbRREHeader; for (i = 0; i < cl->afterEncBufLen;) { int bytesToCopy = UPDATE_BUF_SIZE - cl->ublen; if (i + bytesToCopy > cl->afterEncBufLen) { bytesToCopy = cl->afterEncBufLen - i; } memcpy(&cl->updateBuf[cl->ublen], &cl->afterEncBuf[i], bytesToCopy); cl->ublen += bytesToCopy; i += bytesToCopy; if (cl->ublen == UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } } return TRUE; } /* * subrectEncode() encodes the given multicoloured rectangle as a background * colour overwritten by single-coloured rectangles. It returns the number * of subrectangles in the encoded buffer, or -1 if subrect encoding won't * fit in the buffer. It puts the encoded rectangles in cl->afterEncBuf. The * single-colour rectangle partition is not optimal, but does find the biggest * horizontal or vertical rectangle top-left anchored to each consecutive * coordinate position. * * The coding scheme is simply [<bgcolour><subrect><subrect>...] where each * <subrect> is [<colour><x><y><w><h>]. */ #define DEFINE_SUBRECT_ENCODE(bpp) \ static int \ subrectEncode##bpp(rfbClientPtr client, uint##bpp##_t *data, int w, int h) { \ uint##bpp##_t cl; \ rfbRectangle subrect; \ int x,y; \ int i,j; \ int hx=0,hy,vx=0,vy; \ int hyflag; \ uint##bpp##_t *seg; \ uint##bpp##_t *line; \ int hw,hh,vw,vh; \ int thex,they,thew,theh; \ int numsubs = 0; \ int newLen; \ uint##bpp##_t bg = (uint##bpp##_t)getBgColour((char*)data,w*h,bpp); \ \ *((uint##bpp##_t*)client->afterEncBuf) = bg; \ \ client->afterEncBufLen = (bpp/8); \ \ for (y=0; y<h; y++) { \ line = data+(y*w); \ for (x=0; x<w; x++) { \ if (line[x] != bg) { \ cl = line[x]; \ hy = y-1; \ hyflag = 1; \ for (j=y; j<h; j++) { \ seg = data+(j*w); \ if (seg[x] != cl) {break;} \ i = x; \ while ((i < w) && (seg[i] == cl)) i += 1; \ i -= 1; \ if (j == y) vx = hx = i; \ if (i < vx) vx = i; \ if ((hyflag > 0) && (i >= hx)) {hy += 1;} else {hyflag = 0;} \ } \ vy = j-1; \ \ /* We now have two possible subrects: (x,y,hx,hy) and (x,y,vx,vy) \ * We'll choose the bigger of the two. \ */ \ hw = hx-x+1; \ hh = hy-y+1; \ vw = vx-x+1; \ vh = vy-y+1; \ \ thex = x; \ they = y; \ \ if ((hw*hh) > (vw*vh)) { \ thew = hw; \ theh = hh; \ } else { \ thew = vw; \ theh = vh; \ } \ \ subrect.x = Swap16IfLE(thex); \ subrect.y = Swap16IfLE(they); \ subrect.w = Swap16IfLE(thew); \ subrect.h = Swap16IfLE(theh); \ \ newLen = client->afterEncBufLen + (bpp/8) + sz_rfbRectangle; \ if ((newLen > (w * h * (bpp/8))) || (newLen > client->afterEncBufSize)) \ return -1; \ \ numsubs += 1; \ *((uint##bpp##_t*)(client->afterEncBuf + client->afterEncBufLen)) = cl; \ client->afterEncBufLen += (bpp/8); \ memcpy(&client->afterEncBuf[client->afterEncBufLen],&subrect,sz_rfbRectangle); \ client->afterEncBufLen += sz_rfbRectangle; \ \ /* \ * Now mark the subrect as done. \ */ \ for (j=they; j < (they+theh); j++) { \ for (i=thex; i < (thex+thew); i++) { \ data[j*w+i] = bg; \ } \ } \ } \ } \ } \ \ return numsubs; \ } DEFINE_SUBRECT_ENCODE(8) DEFINE_SUBRECT_ENCODE(16) DEFINE_SUBRECT_ENCODE(32) /* * getBgColour() gets the most prevalent colour in a byte array. */ static uint32_t getBgColour(char *data, int size, int bpp) { #define NUMCLRS 256 static int counts[NUMCLRS]; int i,j,k; int maxcount = 0; uint8_t maxclr = 0; if (bpp != 8) { if (bpp == 16) { return ((uint16_t *)data)[0]; } else if (bpp == 32) { return ((uint32_t *)data)[0]; } else { rfbLog("getBgColour: bpp %d?\n",bpp); return 0; } } for (i=0; i<NUMCLRS; i++) { counts[i] = 0; } for (j=0; j<size; j++) { k = (int)(((uint8_t *)data)[j]); if (k >= NUMCLRS) { rfbErr("getBgColour: unusual colour = %d\n", k); return 0; } counts[k] += 1; if (counts[k] > maxcount) { maxcount = counts[k]; maxclr = ((uint8_t *)data)[j]; } } return maxclr; }
null
177
CWE-787
CVE-2020-14404
/* * rre.c * * Routines to implement Rise-and-Run-length Encoding (RRE). This * code is based on krw's original javatel rfbserver. */ /* * OSXvnc Copyright (C) 2001 Dan McGuirk <mcguirk@incompleteness.net>. * Original Xvnc code Copyright (C) 1999 AT&T Laboratories Cambridge. * All Rights Reserved. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ #include <rfb/rfb.h> /* * cl->beforeEncBuf contains pixel data in the client's format. * cl->afterEncBuf contains the RRE encoded version. If the RRE encoded version is * larger than the raw data or if it exceeds cl->afterEncBufSize then * raw encoding is used instead. */ static int subrectEncode8(rfbClientPtr cl, uint8_t *data, int w, int h); static int subrectEncode16(rfbClientPtr cl, uint16_t *data, int w, int h); static int subrectEncode32(rfbClientPtr cl, uint32_t *data, int w, int h); static uint32_t getBgColour(char *data, int size, int bpp); /* * rfbSendRectEncodingRRE - send a given rectangle using RRE encoding. */ rfbBool rfbSendRectEncodingRRE(rfbClientPtr cl, int x, int y, int w, int h) { rfbFramebufferUpdateRectHeader rect; rfbRREHeader hdr; int nSubrects; int i; char *fbptr = (cl->scaledScreen->frameBuffer + (cl->scaledScreen->paddedWidthInBytes * y) + (x * (cl->scaledScreen->bitsPerPixel / 8))); int maxRawSize = (cl->scaledScreen->width * cl->scaledScreen->height * (cl->format.bitsPerPixel / 8)); if (cl->beforeEncBufSize < maxRawSize) { cl->beforeEncBufSize = maxRawSize; if (cl->beforeEncBuf == NULL) cl->beforeEncBuf = (char *)malloc(cl->beforeEncBufSize); else cl->beforeEncBuf = (char *)realloc(cl->beforeEncBuf, cl->beforeEncBufSize); } if (cl->afterEncBufSize < maxRawSize) { cl->afterEncBufSize = maxRawSize; if (cl->afterEncBuf == NULL) cl->afterEncBuf = (char *)malloc(cl->afterEncBufSize); else cl->afterEncBuf = (char *)realloc(cl->afterEncBuf, cl->afterEncBufSize); } (*cl->translateFn)(cl->translateLookupTable, &(cl->screen->serverFormat), &cl->format, fbptr, cl->beforeEncBuf, cl->scaledScreen->paddedWidthInBytes, w, h); switch (cl->format.bitsPerPixel) { case 8: nSubrects = subrectEncode8(cl, (uint8_t *)cl->beforeEncBuf, w, h); break; case 16: nSubrects = subrectEncode16(cl, (uint16_t *)cl->beforeEncBuf, w, h); break; case 32: nSubrects = subrectEncode32(cl, (uint32_t *)cl->beforeEncBuf, w, h); break; default: rfbLog("getBgColour: bpp %d?\n",cl->format.bitsPerPixel); return FALSE; } if (nSubrects < 0) { /* RRE encoding was too large, use raw */ return rfbSendRectEncodingRaw(cl, x, y, w, h); } rfbStatRecordEncodingSent(cl, rfbEncodingRRE, sz_rfbFramebufferUpdateRectHeader + sz_rfbRREHeader + cl->afterEncBufLen, sz_rfbFramebufferUpdateRectHeader + w * h * (cl->format.bitsPerPixel / 8)); if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + sz_rfbRREHeader > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.r.x = Swap16IfLE(x); rect.r.y = Swap16IfLE(y); rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); rect.encoding = Swap32IfLE(rfbEncodingRRE); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; hdr.nSubrects = Swap32IfLE(nSubrects); memcpy(&cl->updateBuf[cl->ublen], (char *)&hdr, sz_rfbRREHeader); cl->ublen += sz_rfbRREHeader; for (i = 0; i < cl->afterEncBufLen;) { int bytesToCopy = UPDATE_BUF_SIZE - cl->ublen; if (i + bytesToCopy > cl->afterEncBufLen) { bytesToCopy = cl->afterEncBufLen - i; } memcpy(&cl->updateBuf[cl->ublen], &cl->afterEncBuf[i], bytesToCopy); cl->ublen += bytesToCopy; i += bytesToCopy; if (cl->ublen == UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } } return TRUE; } /* * subrectEncode() encodes the given multicoloured rectangle as a background * colour overwritten by single-coloured rectangles. It returns the number * of subrectangles in the encoded buffer, or -1 if subrect encoding won't * fit in the buffer. It puts the encoded rectangles in cl->afterEncBuf. The * single-colour rectangle partition is not optimal, but does find the biggest * horizontal or vertical rectangle top-left anchored to each consecutive * coordinate position. * * The coding scheme is simply [<bgcolour><subrect><subrect>...] where each * <subrect> is [<colour><x><y><w><h>]. */ #define DEFINE_SUBRECT_ENCODE(bpp) \ static int \ subrectEncode##bpp(rfbClientPtr client, uint##bpp##_t *data, int w, int h) { \ uint##bpp##_t cl; \ rfbRectangle subrect; \ int x,y; \ int i,j; \ int hx=0,hy,vx=0,vy; \ int hyflag; \ uint##bpp##_t *seg; \ uint##bpp##_t *line; \ int hw,hh,vw,vh; \ int thex,they,thew,theh; \ int numsubs = 0; \ int newLen; \ uint##bpp##_t bg = (uint##bpp##_t)getBgColour((char*)data,w*h,bpp); \ \ *((uint##bpp##_t*)client->afterEncBuf) = bg; \ \ client->afterEncBufLen = (bpp/8); \ \ for (y=0; y<h; y++) { \ line = data+(y*w); \ for (x=0; x<w; x++) { \ if (line[x] != bg) { \ cl = line[x]; \ hy = y-1; \ hyflag = 1; \ for (j=y; j<h; j++) { \ seg = data+(j*w); \ if (seg[x] != cl) {break;} \ i = x; \ while ((seg[i] == cl) && (i < w)) i += 1; \ i -= 1; \ if (j == y) vx = hx = i; \ if (i < vx) vx = i; \ if ((hyflag > 0) && (i >= hx)) {hy += 1;} else {hyflag = 0;} \ } \ vy = j-1; \ \ /* We now have two possible subrects: (x,y,hx,hy) and (x,y,vx,vy) \ * We'll choose the bigger of the two. \ */ \ hw = hx-x+1; \ hh = hy-y+1; \ vw = vx-x+1; \ vh = vy-y+1; \ \ thex = x; \ they = y; \ \ if ((hw*hh) > (vw*vh)) { \ thew = hw; \ theh = hh; \ } else { \ thew = vw; \ theh = vh; \ } \ \ subrect.x = Swap16IfLE(thex); \ subrect.y = Swap16IfLE(they); \ subrect.w = Swap16IfLE(thew); \ subrect.h = Swap16IfLE(theh); \ \ newLen = client->afterEncBufLen + (bpp/8) + sz_rfbRectangle; \ if ((newLen > (w * h * (bpp/8))) || (newLen > client->afterEncBufSize)) \ return -1; \ \ numsubs += 1; \ *((uint##bpp##_t*)(client->afterEncBuf + client->afterEncBufLen)) = cl; \ client->afterEncBufLen += (bpp/8); \ memcpy(&client->afterEncBuf[client->afterEncBufLen],&subrect,sz_rfbRectangle); \ client->afterEncBufLen += sz_rfbRectangle; \ \ /* \ * Now mark the subrect as done. \ */ \ for (j=they; j < (they+theh); j++) { \ for (i=thex; i < (thex+thew); i++) { \ data[j*w+i] = bg; \ } \ } \ } \ } \ } \ \ return numsubs; \ } DEFINE_SUBRECT_ENCODE(8) DEFINE_SUBRECT_ENCODE(16) DEFINE_SUBRECT_ENCODE(32) /* * getBgColour() gets the most prevalent colour in a byte array. */ static uint32_t getBgColour(char *data, int size, int bpp) { #define NUMCLRS 256 static int counts[NUMCLRS]; int i,j,k; int maxcount = 0; uint8_t maxclr = 0; if (bpp != 8) { if (bpp == 16) { return ((uint16_t *)data)[0]; } else if (bpp == 32) { return ((uint32_t *)data)[0]; } else { rfbLog("getBgColour: bpp %d?\n",bpp); return 0; } } for (i=0; i<NUMCLRS; i++) { counts[i] = 0; } for (j=0; j<size; j++) { k = (int)(((uint8_t *)data)[j]); if (k >= NUMCLRS) { rfbErr("getBgColour: unusual colour = %d\n", k); return 0; } counts[k] += 1; if (counts[k] > maxcount) { maxcount = counts[k]; maxclr = ((uint8_t *)data)[j]; } } return maxclr; }
null
/* * rre.c * * Routines to implement Rise-and-Run-length Encoding (RRE). This * code is based on krw's original javatel rfbserver. */ /* * OSXvnc Copyright (C) 2001 Dan McGuirk <mcguirk@incompleteness.net>. * Original Xvnc code Copyright (C) 1999 AT&T Laboratories Cambridge. * All Rights Reserved. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ #include <rfb/rfb.h> /* * cl->beforeEncBuf contains pixel data in the client's format. * cl->afterEncBuf contains the RRE encoded version. If the RRE encoded version is * larger than the raw data or if it exceeds cl->afterEncBufSize then * raw encoding is used instead. */ static int subrectEncode8(rfbClientPtr cl, uint8_t *data, int w, int h); static int subrectEncode16(rfbClientPtr cl, uint16_t *data, int w, int h); static int subrectEncode32(rfbClientPtr cl, uint32_t *data, int w, int h); static uint32_t getBgColour(char *data, int size, int bpp); /* * rfbSendRectEncodingRRE - send a given rectangle using RRE encoding. */ rfbBool rfbSendRectEncodingRRE(rfbClientPtr cl, int x, int y, int w, int h) { rfbFramebufferUpdateRectHeader rect; rfbRREHeader hdr; int nSubrects; int i; char *fbptr = (cl->scaledScreen->frameBuffer + (cl->scaledScreen->paddedWidthInBytes * y) + (x * (cl->scaledScreen->bitsPerPixel / 8))); int maxRawSize = (cl->scaledScreen->width * cl->scaledScreen->height * (cl->format.bitsPerPixel / 8)); if (cl->beforeEncBufSize < maxRawSize) { cl->beforeEncBufSize = maxRawSize; if (cl->beforeEncBuf == NULL) cl->beforeEncBuf = (char *)malloc(cl->beforeEncBufSize); else cl->beforeEncBuf = (char *)realloc(cl->beforeEncBuf, cl->beforeEncBufSize); } if (cl->afterEncBufSize < maxRawSize) { cl->afterEncBufSize = maxRawSize; if (cl->afterEncBuf == NULL) cl->afterEncBuf = (char *)malloc(cl->afterEncBufSize); else cl->afterEncBuf = (char *)realloc(cl->afterEncBuf, cl->afterEncBufSize); } (*cl->translateFn)(cl->translateLookupTable, &(cl->screen->serverFormat), &cl->format, fbptr, cl->beforeEncBuf, cl->scaledScreen->paddedWidthInBytes, w, h); switch (cl->format.bitsPerPixel) { case 8: nSubrects = subrectEncode8(cl, (uint8_t *)cl->beforeEncBuf, w, h); break; case 16: nSubrects = subrectEncode16(cl, (uint16_t *)cl->beforeEncBuf, w, h); break; case 32: nSubrects = subrectEncode32(cl, (uint32_t *)cl->beforeEncBuf, w, h); break; default: rfbLog("getBgColour: bpp %d?\n",cl->format.bitsPerPixel); return FALSE; } if (nSubrects < 0) { /* RRE encoding was too large, use raw */ return rfbSendRectEncodingRaw(cl, x, y, w, h); } rfbStatRecordEncodingSent(cl, rfbEncodingRRE, sz_rfbFramebufferUpdateRectHeader + sz_rfbRREHeader + cl->afterEncBufLen, sz_rfbFramebufferUpdateRectHeader + w * h * (cl->format.bitsPerPixel / 8)); if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + sz_rfbRREHeader > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.r.x = Swap16IfLE(x); rect.r.y = Swap16IfLE(y); rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); rect.encoding = Swap32IfLE(rfbEncodingRRE); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; hdr.nSubrects = Swap32IfLE(nSubrects); memcpy(&cl->updateBuf[cl->ublen], (char *)&hdr, sz_rfbRREHeader); cl->ublen += sz_rfbRREHeader; for (i = 0; i < cl->afterEncBufLen;) { int bytesToCopy = UPDATE_BUF_SIZE - cl->ublen; if (i + bytesToCopy > cl->afterEncBufLen) { bytesToCopy = cl->afterEncBufLen - i; } memcpy(&cl->updateBuf[cl->ublen], &cl->afterEncBuf[i], bytesToCopy); cl->ublen += bytesToCopy; i += bytesToCopy; if (cl->ublen == UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } } return TRUE; } /* * subrectEncode() encodes the given multicoloured rectangle as a background * colour overwritten by single-coloured rectangles. It returns the number * of subrectangles in the encoded buffer, or -1 if subrect encoding won't * fit in the buffer. It puts the encoded rectangles in cl->afterEncBuf. The * single-colour rectangle partition is not optimal, but does find the biggest * horizontal or vertical rectangle top-left anchored to each consecutive * coordinate position. * * The coding scheme is simply [<bgcolour><subrect><subrect>...] where each * <subrect> is [<colour><x><y><w><h>]. */ #define DEFINE_SUBRECT_ENCODE(bpp) \ static int \ subrectEncode##bpp(rfbClientPtr client, uint##bpp##_t *data, int w, int h) { \ uint##bpp##_t cl; \ rfbRectangle subrect; \ int x,y; \ int i,j; \ int hx=0,hy,vx=0,vy; \ int hyflag; \ uint##bpp##_t *seg; \ uint##bpp##_t *line; \ int hw,hh,vw,vh; \ int thex,they,thew,theh; \ int numsubs = 0; \ int newLen; \ uint##bpp##_t bg = (uint##bpp##_t)getBgColour((char*)data,w*h,bpp); \ \ *((uint##bpp##_t*)client->afterEncBuf) = bg; \ \ client->afterEncBufLen = (bpp/8); \ \ for (y=0; y<h; y++) { \ line = data+(y*w); \ for (x=0; x<w; x++) { \ if (line[x] != bg) { \ cl = line[x]; \ hy = y-1; \ hyflag = 1; \ for (j=y; j<h; j++) { \ seg = data+(j*w); \ if (seg[x] != cl) {break;} \ i = x; \ while ((i < w) && (seg[i] == cl)) i += 1; \ i -= 1; \ if (j == y) vx = hx = i; \ if (i < vx) vx = i; \ if ((hyflag > 0) && (i >= hx)) {hy += 1;} else {hyflag = 0;} \ } \ vy = j-1; \ \ /* We now have two possible subrects: (x,y,hx,hy) and (x,y,vx,vy) \ * We'll choose the bigger of the two. \ */ \ hw = hx-x+1; \ hh = hy-y+1; \ vw = vx-x+1; \ vh = vy-y+1; \ \ thex = x; \ they = y; \ \ if ((hw*hh) > (vw*vh)) { \ thew = hw; \ theh = hh; \ } else { \ thew = vw; \ theh = vh; \ } \ \ subrect.x = Swap16IfLE(thex); \ subrect.y = Swap16IfLE(they); \ subrect.w = Swap16IfLE(thew); \ subrect.h = Swap16IfLE(theh); \ \ newLen = client->afterEncBufLen + (bpp/8) + sz_rfbRectangle; \ if ((newLen > (w * h * (bpp/8))) || (newLen > client->afterEncBufSize)) \ return -1; \ \ numsubs += 1; \ *((uint##bpp##_t*)(client->afterEncBuf + client->afterEncBufLen)) = cl; \ client->afterEncBufLen += (bpp/8); \ memcpy(&client->afterEncBuf[client->afterEncBufLen],&subrect,sz_rfbRectangle); \ client->afterEncBufLen += sz_rfbRectangle; \ \ /* \ * Now mark the subrect as done. \ */ \ for (j=they; j < (they+theh); j++) { \ for (i=thex; i < (thex+thew); i++) { \ data[j*w+i] = bg; \ } \ } \ } \ } \ } \ \ return numsubs; \ } DEFINE_SUBRECT_ENCODE(8) DEFINE_SUBRECT_ENCODE(16) DEFINE_SUBRECT_ENCODE(32) /* * getBgColour() gets the most prevalent colour in a byte array. */ static uint32_t getBgColour(char *data, int size, int bpp) { #define NUMCLRS 256 static int counts[NUMCLRS]; int i,j,k; int maxcount = 0; uint8_t maxclr = 0; if (bpp != 8) { if (bpp == 16) { return ((uint16_t *)data)[0]; } else if (bpp == 32) { return ((uint32_t *)data)[0]; } else { rfbLog("getBgColour: bpp %d?\n",bpp); return 0; } } for (i=0; i<NUMCLRS; i++) { counts[i] = 0; } for (j=0; j<size; j++) { k = (int)(((uint8_t *)data)[j]); if (k >= NUMCLRS) { rfbErr("getBgColour: unusual colour = %d\n", k); return 0; } counts[k] += 1; if (counts[k] > maxcount) { maxcount = counts[k]; maxclr = ((uint8_t *)data)[j]; } } return maxclr; }
null
178
CWE-787
CVE-2020-15195
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #define EIGEN_USE_THREADS #include <algorithm> #include <numeric> #include <unordered_map> #include <utility> #include <vector> #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_util.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/lib/gtl/inlined_vector.h" #include "tensorflow/core/util/sparse/sparse_tensor.h" namespace tensorflow { using CPUDevice = Eigen::ThreadPoolDevice; template <typename T> class SparseFillEmptyRowsOp : public OpKernel { public: explicit SparseFillEmptyRowsOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { const int kIndicesInput = 0; const int kValuesInput = 1; const int kDenseShapeInput = 2; const int kDefaultValueInput = 3; const int kOutputIndicesOutput = 0; const int kOutputValuesOutput = 1; const int kEmptyRowIndicatorOutput = 2; const int kReverseIndexMapOutput = 3; const Tensor& indices_t = context->input(kIndicesInput); const Tensor& values_t = context->input(kValuesInput); const Tensor& dense_shape_t = context->input(kDenseShapeInput); const Tensor& default_value_t = context->input(kDefaultValueInput); OP_REQUIRES(context, TensorShapeUtils::IsVector(dense_shape_t.shape()), errors::InvalidArgument("dense_shape must be a vector, saw: ", dense_shape_t.shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsMatrix(indices_t.shape()), errors::InvalidArgument("indices must be a matrix, saw: ", indices_t.shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsVector(values_t.shape()), errors::InvalidArgument("values must be a vector, saw: ", values_t.shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsScalar(default_value_t.shape()), errors::InvalidArgument("default_value must be a scalar, saw: ", default_value_t.shape().DebugString())); // TODO(ebrevdo): add shape checks between values, indices, // dense_shape. Also add check that dense rank > 0. const T& default_value = default_value_t.scalar<T>()(); const auto indices = indices_t.matrix<int64>(); const auto values = values_t.vec<T>(); const auto dense_shape = dense_shape_t.vec<int64>(); const int64 N = indices_t.shape().dim_size(0); const int64 dense_rows = dense_shape(0); bool* empty_row_indicator = nullptr; if (context->output_required(kEmptyRowIndicatorOutput)) { Tensor* empty_row_indicator_t = nullptr; OP_REQUIRES_OK(context, context->allocate_output(kEmptyRowIndicatorOutput, TensorShape({dense_rows}), &empty_row_indicator_t)); empty_row_indicator = empty_row_indicator_t->vec<bool>().data(); } int64* reverse_index_map = nullptr; if (context->output_required(kReverseIndexMapOutput)) { Tensor* reverse_index_map_t = nullptr; OP_REQUIRES_OK(context, context->allocate_output(kReverseIndexMapOutput, TensorShape({N}), &reverse_index_map_t)); reverse_index_map = reverse_index_map_t->vec<int64>().data(); } int rank = indices_t.shape().dim_size(1); if (dense_rows == 0) { OP_REQUIRES( context, N == 0, errors::InvalidArgument("Received SparseTensor with dense_shape[0] = " "0 but indices.shape[0] = ", N)); Tensor* output_indices_t; TensorShape output_indices_shape({0, rank}); OP_REQUIRES_OK(context, context->allocate_output(kOutputIndicesOutput, output_indices_shape, &output_indices_t)); Tensor* output_values_t; OP_REQUIRES_OK(context, context->allocate_output(kOutputValuesOutput, TensorShape({0}), &output_values_t)); // Exit early, nothing more to do. return; } bool rows_are_ordered = true; int64 last_indices_row = 0; std::vector<int64> csr_offset(dense_rows, 0); for (int i = 0; i < N; ++i) { const int64 row = indices(i, 0); OP_REQUIRES(context, row >= 0 && row < dense_rows, errors::InvalidArgument("indices(", i, ", 0) is invalid: ", row, " >= ", dense_rows)); ++csr_offset[row]; rows_are_ordered = rows_are_ordered & (row >= last_indices_row); last_indices_row = row; } bool all_rows_full = true; for (int row = 0; row < dense_rows; ++row) { // csr_offset here describes the number of elements in this dense row bool row_empty = (csr_offset[row] == 0); if (empty_row_indicator) { empty_row_indicator[row] = row_empty; } all_rows_full = all_rows_full & !row_empty; // In filled version, each row has at least one element. csr_offset[row] = std::max(csr_offset[row], int64{1}); // Update csr_offset to represent the number of elements up to and // including dense_row + 1: // csr_offset(0) == #{elements of row 0} // csr_offset(1) == #{elements of row 1} + #{elements of row 0} // .. // csr_offset(i) == starting index for elements in row i + 1. if (row > 0) { csr_offset[row] += csr_offset[row - 1]; } } if (all_rows_full && rows_are_ordered) { context->set_output(kOutputIndicesOutput, indices_t); context->set_output(kOutputValuesOutput, values_t); if (reverse_index_map) { for (int64 i = 0; i < N; ++i) { reverse_index_map[i] = i; } } } else { Tensor* output_indices_t; const int64 N_full = csr_offset[dense_rows - 1]; TensorShape output_indices_shape({N_full, rank}); OP_REQUIRES_OK(context, context->allocate_output(kOutputIndicesOutput, output_indices_shape, &output_indices_t)); auto output_indices = output_indices_t->matrix<int64>(); Tensor* output_values_t; OP_REQUIRES_OK(context, context->allocate_output(kOutputValuesOutput, TensorShape({N_full}), &output_values_t)); auto output_values = output_values_t->vec<T>(); std::vector<int64> filled_count(dense_rows, 0); // Fill in values for rows that are not missing for (int64 i = 0; i < N; ++i) { const int64 row = indices(i, 0); int64& offset = filled_count[row]; const int64 output_i = ((row == 0) ? 0 : csr_offset[row - 1]) + offset; offset++; // Increment the filled count for this row. std::copy_n(&indices(i, 0), rank, &output_indices(output_i, 0)); output_values(output_i) = values(i); // We'll need this reverse index map to backprop correctly. if (reverse_index_map) { reverse_index_map[i] = output_i; } } // Fill in values for rows that are missing for (int64 row = 0; row < dense_rows; ++row) { const int64 row_count = filled_count[row]; if (row_count == 0) { // We haven't filled this row const int64 starting_index = (row == 0) ? 0 : csr_offset[row - 1]; // Remaining index values were set to zero already. // Just need to set the row index in the right location. output_indices(starting_index, 0) = row; for (int64 col = 1; col < rank; ++col) { output_indices(starting_index, col) = 0; } output_values(starting_index) = default_value; } } } } }; #define REGISTER_KERNELS(type) \ REGISTER_KERNEL_BUILDER(Name("SparseFillEmptyRows") \ .Device(DEVICE_CPU) \ .TypeConstraint<type>("T"), \ SparseFillEmptyRowsOp<type>) TF_CALL_ALL_TYPES(REGISTER_KERNELS); #undef REGISTER_KERNELS template <typename T> class SparseFillEmptyRowsGradOp : public OpKernel { public: explicit SparseFillEmptyRowsGradOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { const Tensor* reverse_index_map_t; const Tensor* grad_values_t; OP_REQUIRES_OK(context, context->input("reverse_index_map", &reverse_index_map_t)); OP_REQUIRES_OK(context, context->input("grad_values", &grad_values_t)); const CPUDevice& d = context->eigen_device<CPUDevice>(); OP_REQUIRES( context, TensorShapeUtils::IsVector(reverse_index_map_t->shape()), errors::InvalidArgument("reverse_index_map must be a vector, saw: ", reverse_index_map_t->shape().DebugString())); const auto reverse_index_map = reverse_index_map_t->vec<int64>(); const auto grad_values = grad_values_t->vec<T>(); const int64 N = reverse_index_map_t->shape().dim_size(0); const int64 N_full = grad_values_t->shape().dim_size(0); Tensor* d_values_t; OP_REQUIRES_OK(context, context->allocate_output( "d_values", TensorShape({N}), &d_values_t)); auto d_values = d_values_t->vec<T>(); Tensor* d_default_value_t; OP_REQUIRES_OK(context, context->allocate_output("d_default_value", TensorShape({}), &d_default_value_t)); T& d_default_value = d_default_value_t->scalar<T>()(); d_default_value = T(); Tensor visited_t; OP_REQUIRES_OK(context, context->allocate_temp( DT_BOOL, TensorShape({N_full}), &visited_t)); auto visited = visited_t.vec<bool>(); visited.device(d) = visited.constant(false); for (int i = 0; i < N; ++i) { // Locate the index of the output of the forward prop associated // with this location in the input of the forward prop. Copy // the gradient into it. Mark it as visited. d_values(i) = grad_values(reverse_index_map(i)); visited(reverse_index_map(i)) = true; } for (int j = 0; j < N_full; ++j) { // The default value gradient gets the accumulated remainder of // the backprop values (since the default value was used to fill // in these slots in the forward calculation). if (!visited(j)) { d_default_value += grad_values(j); } } } }; #define REGISTER_KERNELS(type) \ REGISTER_KERNEL_BUILDER(Name("SparseFillEmptyRowsGrad") \ .Device(DEVICE_CPU) \ .TypeConstraint<type>("T"), \ SparseFillEmptyRowsGradOp<type>) TF_CALL_NUMBER_TYPES(REGISTER_KERNELS); #undef REGISTER_KERNELS } // namespace tensorflow
null
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #define EIGEN_USE_THREADS #include <algorithm> #include <numeric> #include <unordered_map> #include <utility> #include <vector> #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_util.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/lib/gtl/inlined_vector.h" #include "tensorflow/core/util/sparse/sparse_tensor.h" namespace tensorflow { using CPUDevice = Eigen::ThreadPoolDevice; template <typename T> class SparseFillEmptyRowsOp : public OpKernel { public: explicit SparseFillEmptyRowsOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { const int kIndicesInput = 0; const int kValuesInput = 1; const int kDenseShapeInput = 2; const int kDefaultValueInput = 3; const int kOutputIndicesOutput = 0; const int kOutputValuesOutput = 1; const int kEmptyRowIndicatorOutput = 2; const int kReverseIndexMapOutput = 3; const Tensor& indices_t = context->input(kIndicesInput); const Tensor& values_t = context->input(kValuesInput); const Tensor& dense_shape_t = context->input(kDenseShapeInput); const Tensor& default_value_t = context->input(kDefaultValueInput); OP_REQUIRES(context, TensorShapeUtils::IsVector(dense_shape_t.shape()), errors::InvalidArgument("dense_shape must be a vector, saw: ", dense_shape_t.shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsMatrix(indices_t.shape()), errors::InvalidArgument("indices must be a matrix, saw: ", indices_t.shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsVector(values_t.shape()), errors::InvalidArgument("values must be a vector, saw: ", values_t.shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsScalar(default_value_t.shape()), errors::InvalidArgument("default_value must be a scalar, saw: ", default_value_t.shape().DebugString())); // TODO(ebrevdo): add shape checks between values, indices, // dense_shape. Also add check that dense rank > 0. const T& default_value = default_value_t.scalar<T>()(); const auto indices = indices_t.matrix<int64>(); const auto values = values_t.vec<T>(); const auto dense_shape = dense_shape_t.vec<int64>(); const int64 N = indices_t.shape().dim_size(0); const int64 dense_rows = dense_shape(0); bool* empty_row_indicator = nullptr; if (context->output_required(kEmptyRowIndicatorOutput)) { Tensor* empty_row_indicator_t = nullptr; OP_REQUIRES_OK(context, context->allocate_output(kEmptyRowIndicatorOutput, TensorShape({dense_rows}), &empty_row_indicator_t)); empty_row_indicator = empty_row_indicator_t->vec<bool>().data(); } int64* reverse_index_map = nullptr; if (context->output_required(kReverseIndexMapOutput)) { Tensor* reverse_index_map_t = nullptr; OP_REQUIRES_OK(context, context->allocate_output(kReverseIndexMapOutput, TensorShape({N}), &reverse_index_map_t)); reverse_index_map = reverse_index_map_t->vec<int64>().data(); } int rank = indices_t.shape().dim_size(1); if (dense_rows == 0) { OP_REQUIRES( context, N == 0, errors::InvalidArgument("Received SparseTensor with dense_shape[0] = " "0 but indices.shape[0] = ", N)); Tensor* output_indices_t; TensorShape output_indices_shape({0, rank}); OP_REQUIRES_OK(context, context->allocate_output(kOutputIndicesOutput, output_indices_shape, &output_indices_t)); Tensor* output_values_t; OP_REQUIRES_OK(context, context->allocate_output(kOutputValuesOutput, TensorShape({0}), &output_values_t)); // Exit early, nothing more to do. return; } bool rows_are_ordered = true; int64 last_indices_row = 0; std::vector<int64> csr_offset(dense_rows, 0); for (int i = 0; i < N; ++i) { const int64 row = indices(i, 0); OP_REQUIRES(context, row >= 0 && row < dense_rows, errors::InvalidArgument("indices(", i, ", 0) is invalid: ", row, " >= ", dense_rows)); ++csr_offset[row]; rows_are_ordered = rows_are_ordered & (row >= last_indices_row); last_indices_row = row; } bool all_rows_full = true; for (int row = 0; row < dense_rows; ++row) { // csr_offset here describes the number of elements in this dense row bool row_empty = (csr_offset[row] == 0); if (empty_row_indicator) { empty_row_indicator[row] = row_empty; } all_rows_full = all_rows_full & !row_empty; // In filled version, each row has at least one element. csr_offset[row] = std::max(csr_offset[row], int64{1}); // Update csr_offset to represent the number of elements up to and // including dense_row + 1: // csr_offset(0) == #{elements of row 0} // csr_offset(1) == #{elements of row 1} + #{elements of row 0} // .. // csr_offset(i) == starting index for elements in row i + 1. if (row > 0) { csr_offset[row] += csr_offset[row - 1]; } } if (all_rows_full && rows_are_ordered) { context->set_output(kOutputIndicesOutput, indices_t); context->set_output(kOutputValuesOutput, values_t); if (reverse_index_map) { for (int64 i = 0; i < N; ++i) { reverse_index_map[i] = i; } } } else { Tensor* output_indices_t; const int64 N_full = csr_offset[dense_rows - 1]; TensorShape output_indices_shape({N_full, rank}); OP_REQUIRES_OK(context, context->allocate_output(kOutputIndicesOutput, output_indices_shape, &output_indices_t)); auto output_indices = output_indices_t->matrix<int64>(); Tensor* output_values_t; OP_REQUIRES_OK(context, context->allocate_output(kOutputValuesOutput, TensorShape({N_full}), &output_values_t)); auto output_values = output_values_t->vec<T>(); std::vector<int64> filled_count(dense_rows, 0); // Fill in values for rows that are not missing for (int64 i = 0; i < N; ++i) { const int64 row = indices(i, 0); int64& offset = filled_count[row]; const int64 output_i = ((row == 0) ? 0 : csr_offset[row - 1]) + offset; offset++; // Increment the filled count for this row. std::copy_n(&indices(i, 0), rank, &output_indices(output_i, 0)); output_values(output_i) = values(i); // We'll need this reverse index map to backprop correctly. if (reverse_index_map) { reverse_index_map[i] = output_i; } } // Fill in values for rows that are missing for (int64 row = 0; row < dense_rows; ++row) { const int64 row_count = filled_count[row]; if (row_count == 0) { // We haven't filled this row const int64 starting_index = (row == 0) ? 0 : csr_offset[row - 1]; // Remaining index values were set to zero already. // Just need to set the row index in the right location. output_indices(starting_index, 0) = row; for (int64 col = 1; col < rank; ++col) { output_indices(starting_index, col) = 0; } output_values(starting_index) = default_value; } } } } }; #define REGISTER_KERNELS(type) \ REGISTER_KERNEL_BUILDER(Name("SparseFillEmptyRows") \ .Device(DEVICE_CPU) \ .TypeConstraint<type>("T"), \ SparseFillEmptyRowsOp<type>) TF_CALL_ALL_TYPES(REGISTER_KERNELS); #undef REGISTER_KERNELS template <typename T> class SparseFillEmptyRowsGradOp : public OpKernel { public: explicit SparseFillEmptyRowsGradOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { const Tensor* reverse_index_map_t; const Tensor* grad_values_t; OP_REQUIRES_OK(context, context->input("reverse_index_map", &reverse_index_map_t)); OP_REQUIRES_OK(context, context->input("grad_values", &grad_values_t)); const CPUDevice& d = context->eigen_device<CPUDevice>(); OP_REQUIRES( context, TensorShapeUtils::IsVector(reverse_index_map_t->shape()), errors::InvalidArgument("reverse_index_map must be a vector, saw: ", reverse_index_map_t->shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsVector(grad_values_t->shape()), errors::InvalidArgument("grad_values must be a vector, saw: ", grad_values_t->shape().DebugString())); const auto reverse_index_map = reverse_index_map_t->vec<int64>(); const auto grad_values = grad_values_t->vec<T>(); const int64 N = reverse_index_map_t->shape().dim_size(0); const int64 N_full = grad_values_t->shape().dim_size(0); Tensor* d_values_t; OP_REQUIRES_OK(context, context->allocate_output( "d_values", TensorShape({N}), &d_values_t)); auto d_values = d_values_t->vec<T>(); Tensor* d_default_value_t; OP_REQUIRES_OK(context, context->allocate_output("d_default_value", TensorShape({}), &d_default_value_t)); T& d_default_value = d_default_value_t->scalar<T>()(); d_default_value = T(); Tensor visited_t; OP_REQUIRES_OK(context, context->allocate_temp( DT_BOOL, TensorShape({N_full}), &visited_t)); auto visited = visited_t.vec<bool>(); visited.device(d) = visited.constant(false); for (int i = 0; i < N; ++i) { // Locate the index of the output of the forward prop associated // with this location in the input of the forward prop. Copy // the gradient into it. Mark it as visited. int64 reverse_index = reverse_index_map(i); OP_REQUIRES( context, 0 <= reverse_index && reverse_index < N_full, errors::InvalidArgument("Elements in reverse index must be in [0, ", N_full, ") but got ", reverse_index)); d_values(i) = grad_values(reverse_index); visited(reverse_index) = true; } for (int j = 0; j < N_full; ++j) { // The default value gradient gets the accumulated remainder of // the backprop values (since the default value was used to fill // in these slots in the forward calculation). if (!visited(j)) { d_default_value += grad_values(j); } } } }; #define REGISTER_KERNELS(type) \ REGISTER_KERNEL_BUILDER(Name("SparseFillEmptyRowsGrad") \ .Device(DEVICE_CPU) \ .TypeConstraint<type>("T"), \ SparseFillEmptyRowsGradOp<type>) TF_CALL_NUMBER_TYPES(REGISTER_KERNELS); #undef REGISTER_KERNELS } // namespace tensorflow
null
179
CWE-787
CVE-2020-15200
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # maxlengthations under the License. # ============================================================================== """Tests for bincount ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import numpy as np from tensorflow.python.eager import context from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.ops import bincount_ops from tensorflow.python.ops import sparse_ops from tensorflow.python.ops.ragged import ragged_factory_ops from tensorflow.python.ops.ragged import ragged_tensor from tensorflow.python.platform import test class TestSparseCount(test.TestCase, parameterized.TestCase): @parameterized.named_parameters( { "testcase_name": "_no_maxlength", "x": np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 2], [0, 3], [1, 4], [1, 5]], "expected_values": [1, 1, 1, 2, 1], "expected_shape": [2, 6] }, { "testcase_name": "_maxlength", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "maxlength": 7, "expected_indices": [[0, 1], [0, 2], [0, 3], [1, 0], [1, 4]], "expected_values": [1, 1, 1, 1, 2], "expected_shape": [2, 7] }, { "testcase_name": "_minlength", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "minlength": 9, "expected_indices": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4], [1, 7]], "expected_values": [1, 1, 1, 1, 1, 2, 1], "expected_shape": [2, 9] }, { "testcase_name": "_minlength_larger_values", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "minlength": 3, "expected_indices": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4], [1, 7]], "expected_values": [1, 1, 1, 1, 1, 2, 1], "expected_shape": [2, 8] }, { "testcase_name": "_no_maxlength_binary", "x": np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 2], [0, 3], [1, 4], [1, 5]], "expected_values": [1, 1, 1, 1, 1], "expected_shape": [2, 6], "binary_output": True, }, { "testcase_name": "_maxlength_binary", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "maxlength": 7, "expected_indices": [[0, 1], [0, 2], [0, 3], [1, 0], [1, 4]], "expected_values": [1, 1, 1, 1, 1], "expected_shape": [2, 7], "binary_output": True, }, { "testcase_name": "_minlength_binary", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "minlength": 9, "expected_indices": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4], [1, 7]], "expected_values": [1, 1, 1, 1, 1, 1, 1], "expected_shape": [2, 9], "binary_output": True, }, { "testcase_name": "_minlength_larger_values_binary", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "minlength": 3, "expected_indices": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4], [1, 7]], "expected_values": [1, 1, 1, 1, 1, 1, 1], "expected_shape": [2, 8], "binary_output": True, }, { "testcase_name": "_no_maxlength_weights", "x": np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 2], [0, 3], [1, 4], [1, 5]], "expected_values": [2, 1, 0.5, 9, 3], "expected_shape": [2, 6], "weights": [[0.5, 1, 2], [3, 4, 5]] }, { "testcase_name": "_maxlength_weights", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "maxlength": 7, "expected_indices": [[0, 1], [0, 2], [0, 3], [1, 0], [1, 4]], "expected_values": [2, 1, 0.5, 3, 9], "expected_shape": [2, 7], "weights": [[0.5, 1, 2, 11], [7, 3, 4, 5]] }, { "testcase_name": "_minlength_weights", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "minlength": 9, "expected_indices": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4], [1, 7]], "expected_values": [2, 1, 0.5, 3, 5, 13, 4], "expected_shape": [2, 9], "weights": [[0.5, 1, 2, 3], [4, 5, 6, 7]] }, { "testcase_name": "_minlength_larger_values_weights", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "minlength": 3, "expected_indices": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4], [1, 7]], "expected_values": [2, 1, 0.5, 3, 5, 13, 4], "expected_shape": [2, 8], "weights": [[0.5, 1, 2, 3], [4, 5, 6, 7]] }, { "testcase_name": "_1d", "x": np.array([3, 2, 1, 1], dtype=np.int32), "expected_indices": [[1], [2], [3]], "expected_values": [2, 1, 1], "expected_shape": [4] }, { "testcase_name": "_all_axes", "x": np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32), "expected_indices": [[1], [2], [3], [4], [5]], "expected_values": [1, 1, 1, 2, 1], "expected_shape": [6], "axis": None }) def test_dense_input(self, x, expected_indices, expected_values, expected_shape, minlength=None, maxlength=None, binary_output=False, weights=None, axis=-1): y = bincount_ops.sparse_bincount( x, weights=weights, minlength=minlength, maxlength=maxlength, binary_output=binary_output, axis=axis) self.assertAllEqual(expected_indices, y.indices) self.assertAllEqual(expected_values, y.values) self.assertAllEqual(expected_shape, y.dense_shape) @parameterized.named_parameters( { "testcase_name": "_no_maxlength", "x": np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [2, 4], [2, 5]], "expected_values": [1, 1, 2, 1], "expected_shape": [3, 6], }, { "testcase_name": "_maxlength", "x": np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [2, 4], [2, 5]], "expected_values": [1, 1, 2, 1], "expected_shape": [3, 7], "maxlength": 7, }, { "testcase_name": "_minlength", "x": np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]], "expected_values": [1, 1, 1, 2, 1], "expected_shape": [3, 9], "minlength": 9, }, { "testcase_name": "_minlength_larger_values", "x": np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]], "expected_values": [1, 1, 1, 2, 1], "expected_shape": [3, 8], "minlength": 3, }, { "testcase_name": "_no_maxlength_binary", "x": np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [2, 4], [2, 5]], "expected_values": [1, 1, 1, 1], "expected_shape": [3, 6], "binary_output": True, }, { "testcase_name": "_maxlength_binary", "x": np.array([[3, 0, 1, 0], [0, 0, 7, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [2, 4], [2, 5]], "expected_values": [1, 1, 1, 1], "expected_shape": [3, 7], "maxlength": 7, "binary_output": True, }, { "testcase_name": "_minlength_binary", "x": np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]], "expected_values": [1, 1, 1, 1, 1], "expected_shape": [3, 9], "minlength": 9, "binary_output": True, }, { "testcase_name": "_minlength_larger_values_binary", "x": np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]], "expected_values": [1, 1, 1, 1, 1], "expected_shape": [3, 8], "minlength": 3, "binary_output": True, }, { "testcase_name": "_no_maxlength_weights", "x": np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [2, 4], [2, 5]], "expected_values": [2, 6, 7, 10], "expected_shape": [3, 6], "weights": np.array([[6, 0, 2, 0], [0, 0, 0, 0], [10, 0, 3.5, 3.5]]), }, { "testcase_name": "_maxlength_weights", "x": np.array([[3, 0, 1, 0], [0, 0, 7, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [2, 4], [2, 5]], "expected_values": [2, 6, 7, 10], "expected_shape": [3, 7], "maxlength": 7, "weights": np.array([[6, 0, 2, 0], [0, 0, 14, 0], [10, 0, 3.5, 3.5]]), }, { "testcase_name": "_minlength_weights", "x": np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]], "expected_values": [2, 6, 14, 6.5, 10], "expected_shape": [3, 9], "minlength": 9, "weights": np.array([[6, 0, 2, 0], [14, 0, 0, 0], [10, 0, 3, 3.5]]), }, { "testcase_name": "_minlength_larger_values_weights", "x": np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]], "expected_values": [2, 6, 14, 6.5, 10], "expected_shape": [3, 8], "minlength": 3, "weights": np.array([[6, 0, 2, 0], [14, 0, 0, 0], [10, 0, 3, 3.5]]), }, { "testcase_name": "_1d", "x": np.array([3, 0, 1, 1], dtype=np.int32), "expected_indices": [[1], [3]], "expected_values": [2, 1], "expected_shape": [4], }, { "testcase_name": "_all_axes", "x": np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[1], [3], [4], [5]], "expected_values": [1, 1, 2, 1], "expected_shape": [6], "axis": None, }, ) def test_sparse_input(self, x, expected_indices, expected_values, expected_shape, maxlength=None, minlength=None, binary_output=False, weights=None, axis=-1): x_sparse = sparse_ops.from_dense(x) w_sparse = sparse_ops.from_dense(weights) if weights is not None else None y = bincount_ops.sparse_bincount( x_sparse, weights=w_sparse, minlength=minlength, maxlength=maxlength, binary_output=binary_output, axis=axis) self.assertAllEqual(expected_indices, y.indices) self.assertAllEqual(expected_values, y.values) self.assertAllEqual(expected_shape, y.dense_shape) @parameterized.named_parameters( { "testcase_name": "_no_maxlength", "x": [[], [], [3, 0, 1], [], [5, 0, 4, 4]], "expected_indices": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 2, 1], "expected_shape": [5, 6], }, { "testcase_name": "_maxlength", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "maxlength": 7, "expected_indices": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 2, 1], "expected_shape": [5, 7], }, { "testcase_name": "_minlength", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "minlength": 9, "expected_indices": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 1, 2, 1], "expected_shape": [5, 9], }, { "testcase_name": "_minlength_larger_values", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "minlength": 3, "expected_indices": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 1, 2, 1], "expected_shape": [5, 8], }, { "testcase_name": "_no_maxlength_binary", "x": [[], [], [3, 0, 1], [], [5, 0, 4, 4]], "expected_indices": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 1, 1], "expected_shape": [5, 6], "binary_output": True, }, { "testcase_name": "_maxlength_binary", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "maxlength": 7, "expected_indices": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 1, 1], "expected_shape": [5, 7], "binary_output": True, }, { "testcase_name": "_minlength_binary", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "minlength": 9, "expected_indices": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 1, 1, 1], "expected_shape": [5, 9], "binary_output": True, }, { "testcase_name": "_minlength_larger_values_binary", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "minlength": 3, "binary_output": True, "expected_indices": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 1, 1, 1], "expected_shape": [5, 8], }, { "testcase_name": "_no_maxlength_weights", "x": [[], [], [3, 0, 1], [], [5, 0, 4, 4]], "expected_indices": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]], "expected_values": [0.5, 2, 6, 0.25, 8, 10], "expected_shape": [5, 6], "weights": [[], [], [6, 0.5, 2], [], [10, 0.25, 5, 3]], }, { "testcase_name": "_maxlength_weights", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "maxlength": 7, "expected_indices": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]], "expected_values": [0.5, 2, 6, 0.25, 8, 10], "expected_shape": [5, 7], "weights": [[], [], [6, 0.5, 2], [14], [10, 0.25, 5, 3]], }, { "testcase_name": "_minlength_weights", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "minlength": 9, "expected_indices": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4], [4, 5]], "expected_values": [0.5, 2, 6, 14, 0.25, 8, 10], "expected_shape": [5, 9], "weights": [[], [], [6, 0.5, 2], [14], [10, 0.25, 5, 3]], }, { "testcase_name": "_minlength_larger_values_weights", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "minlength": 3, "expected_indices": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4], [4, 5]], "expected_values": [0.5, 2, 6, 14, 0.25, 8, 10], "expected_shape": [5, 8], "weights": [[], [], [6, 0.5, 2], [14], [10, 0.25, 5, 3]], }, { "testcase_name": "_1d", "x": [3, 0, 1, 1], "expected_indices": [[0], [1], [3]], "expected_values": [1, 2, 1], "expected_shape": [4], }, { "testcase_name": "_all_axes", "x": [[], [], [3, 0, 1], [], [5, 0, 4, 4]], "expected_indices": [[0], [1], [3], [4], [5]], "expected_values": [2, 1, 1, 2, 1], "expected_shape": [6], "axis": None, }, ) def test_ragged_input(self, x, expected_indices, expected_values, expected_shape, maxlength=None, minlength=None, binary_output=False, weights=None, axis=-1): x_ragged = ragged_factory_ops.constant(x) w = ragged_factory_ops.constant(weights) if weights is not None else None y = bincount_ops.sparse_bincount( x_ragged, weights=w, minlength=minlength, maxlength=maxlength, binary_output=binary_output, axis=axis) self.assertAllEqual(expected_indices, y.indices) self.assertAllEqual(expected_values, y.values) self.assertAllEqual(expected_shape, y.dense_shape) class TestDenseBincount(test.TestCase, parameterized.TestCase): @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_sparse_input_all_count(self, dtype): np.random.seed(42) num_rows = 128 size = 1000 n_elems = 4096 inp_indices = np.random.randint(0, num_rows, (n_elems, 1)) inp_indices = np.concatenate([inp_indices, np.zeros((n_elems, 1))], axis=1) inp_vals = np.random.randint(0, size, (n_elems,), dtype=dtype) sparse_inp = sparse_tensor.SparseTensor(inp_indices, inp_vals, [num_rows, 1]) np_out = np.bincount(inp_vals, minlength=size) self.assertAllEqual( np_out, self.evaluate(bincount_ops.bincount(sparse_inp, axis=0))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_sparse_input_all_count_with_weights(self, dtype): np.random.seed(42) num_rows = 128 size = 1000 n_elems = 4096 inp_indices = np.random.randint(0, num_rows, (n_elems, 1)) inp_indices = np.concatenate([inp_indices, np.zeros((n_elems, 1))], axis=1) inp_vals = np.random.randint(0, size, (n_elems,), dtype=dtype) sparse_inp = sparse_tensor.SparseTensor(inp_indices, inp_vals, [num_rows, 1]) weight_vals = np.random.random((n_elems,)) sparse_weights = sparse_tensor.SparseTensor(inp_indices, weight_vals, [num_rows, 1]) np_out = np.bincount(inp_vals, minlength=size, weights=weight_vals) self.assertAllEqual( np_out, self.evaluate(bincount_ops.bincount( sparse_inp, sparse_weights, axis=0))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_sparse_input_all_binary(self, dtype): np.random.seed(42) num_rows = 128 size = 10 n_elems = 4096 inp_indices = np.random.randint(0, num_rows, (n_elems, 1)) inp_indices = np.concatenate([inp_indices, np.zeros((n_elems, 1))], axis=1) inp_vals = np.random.randint(0, size, (n_elems,), dtype=dtype) sparse_inp = sparse_tensor.SparseTensor(inp_indices, inp_vals, [num_rows, 1]) np_out = np.ones((size,)) self.assertAllEqual( np_out, self.evaluate(bincount_ops.bincount(sparse_inp, binary_output=True))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_sparse_input_col_reduce_count(self, dtype): num_rows = 128 num_cols = 27 size = 100 np.random.seed(42) inp = np.random.randint(0, size, (num_rows, num_cols), dtype=dtype) np_out = np.reshape( np.concatenate( [np.bincount(inp[j, :], minlength=size) for j in range(num_rows)], axis=0), (num_rows, size)) # from_dense will filter out 0s. inp = inp + 1 # from_dense will cause OOM in GPU. with ops.device("/CPU:0"): inp_sparse = sparse_ops.from_dense(inp) inp_sparse = sparse_tensor.SparseTensor(inp_sparse.indices, inp_sparse.values - 1, inp_sparse.dense_shape) self.assertAllEqual( np_out, self.evaluate(bincount_ops.bincount(arr=inp_sparse, axis=-1))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_sparse_input_col_reduce_binary(self, dtype): num_rows = 128 num_cols = 27 size = 100 np.random.seed(42) inp = np.random.randint(0, size, (num_rows, num_cols), dtype=dtype) np_out = np.reshape( np.concatenate([ np.where(np.bincount(inp[j, :], minlength=size) > 0, 1, 0) for j in range(num_rows) ], axis=0), (num_rows, size)) # from_dense will filter out 0s. inp = inp + 1 # from_dense will cause OOM in GPU. with ops.device("/CPU:0"): inp_sparse = sparse_ops.from_dense(inp) inp_sparse = sparse_tensor.SparseTensor(inp_sparse.indices, inp_sparse.values - 1, inp_sparse.dense_shape) self.assertAllEqual( np_out, self.evaluate( bincount_ops.bincount(arr=inp_sparse, axis=-1, binary_output=True))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_ragged_input_count(self, dtype): x = ragged_factory_ops.constant([[], [], [3, 0, 1], [], [5, 0, 4, 4]], dtype) # pyformat: disable expected_output = [ [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [1, 1, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 2, 1]] # pyformat: enable self.assertAllEqual(expected_output, self.evaluate(bincount_ops.bincount(arr=x, axis=-1))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_ragged_input_binary(self, dtype): x = ragged_factory_ops.constant([[], [], [3, 0, 1], [], [5, 0, 4, 4]]) # pyformat: disable expected_output = [ [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [1, 1, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 1, 1]] # pyformat: enable self.assertAllEqual( expected_output, self.evaluate( bincount_ops.bincount(arr=x, axis=-1, binary_output=True))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_ragged_input_count_with_weights(self, dtype): x = ragged_factory_ops.constant([[], [], [3, 0, 1], [], [5, 0, 4, 4]]) weights = ragged_factory_ops.constant([[], [], [.1, .2, .3], [], [.2, .5, .6, .3]]) # pyformat: disable expected_output = [ [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [.2, .3, 0, .1, 0, 0], [0, 0, 0, 0, 0, 0], [.5, 0, 0, 0, .9, .2]] # pyformat: enable self.assertAllClose( expected_output, self.evaluate(bincount_ops.bincount(arr=x, weights=weights, axis=-1))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_ragged_input_count_np(self, dtype): np.random.seed(42) num_rows = 128 num_cols = 27 size = 1000 inp = np.random.randint(0, size, (num_rows, num_cols), dtype=dtype) np_out = np.reshape( np.concatenate( [np.bincount(inp[j, :], minlength=size) for j in range(num_rows)], axis=0), (num_rows, size)) x = ragged_tensor.RaggedTensor.from_tensor(inp) self.assertAllEqual( np_out, self.evaluate(bincount_ops.bincount(arr=x, minlength=size, axis=-1))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_ragged_input_count_np_with_weights(self, dtype): np.random.seed(42) num_rows = 128 num_cols = 27 size = 1000 inp = np.random.randint(0, size, (num_rows, num_cols), dtype=dtype) np_weight = np.random.random((num_rows, num_cols)) np_out = np.reshape( np.concatenate([ np.bincount(inp[j, :], weights=np_weight[j, :], minlength=size) for j in range(num_rows) ], axis=0), (num_rows, size)) x = ragged_tensor.RaggedTensor.from_tensor(inp) weights = ragged_tensor.RaggedTensor.from_tensor(np_weight) self.assertAllEqual( np_out, self.evaluate( bincount_ops.bincount( arr=x, weights=weights, minlength=size, axis=-1))) class TestSparseCountFailureModes(test.TestCase): def test_dense_input_sparse_weights_fails(self): x = np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32) weights = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) with self.assertRaisesRegex(ValueError, "must be a tf.Tensor"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_dense_input_ragged_weights_fails(self): x = np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32) weights = ragged_factory_ops.constant([[6, 0.5, 2], [14], [10, 0.25, 5, 3]]) with self.assertRaisesRegex(ValueError, "must be a tf.Tensor"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_dense_input_wrong_shape_fails(self): x = np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32) weights = np.array([[3, 2], [5, 4], [4, 3]]) # Note: Eager mode and graph mode throw different errors here. Graph mode # will fail with a ValueError from the shape checking logic, while Eager # will fail with an InvalidArgumentError from the kernel itself. if context.executing_eagerly(): with self.assertRaisesRegex(errors.InvalidArgumentError, "must have the same shape"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) else: with self.assertRaisesRegex(ValueError, "both shapes must be equal"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_sparse_input_dense_weights_fails(self): x = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) weights = np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32) with self.assertRaisesRegex(ValueError, "must be a SparseTensor"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_sparse_input_ragged_weights_fails(self): x = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) weights = ragged_factory_ops.constant([[6, 0.5, 2], [14], [10, 0.25, 5, 3]]) with self.assertRaisesRegex(ValueError, "must be a SparseTensor"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_sparse_input_wrong_indices_fails(self): x = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) weights = sparse_ops.from_dense( np.array([[3, 1, 0, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) with self.assertRaisesRegex(errors.InvalidArgumentError, "must have the same indices"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_sparse_input_too_many_indices_fails(self): x = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) weights = sparse_ops.from_dense( np.array([[3, 1, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) with self.assertRaisesRegex(errors.InvalidArgumentError, "Incompatible shapes"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_sparse_input_wrong_shape_fails(self): x = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) weights = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4], [0, 0, 0, 0]], dtype=np.int32)) with self.assertRaisesRegex(errors.InvalidArgumentError, "must have the same dense shape"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_ragged_input_dense_weights_fails(self): x = ragged_factory_ops.constant([[6, 1, 2], [14], [10, 1, 5, 3]]) weights = np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32) with self.assertRaisesRegex(ValueError, "must be a RaggedTensor"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_ragged_input_sparse_weights_fails(self): x = ragged_factory_ops.constant([[6, 1, 2], [14], [10, 1, 5, 3]]) weights = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) with self.assertRaisesRegex(ValueError, "must be a RaggedTensor"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_ragged_input_different_shape_fails(self): x = ragged_factory_ops.constant([[6, 1, 2], [14], [10, 1, 5, 3]]) weights = ragged_factory_ops.constant([[6, 0.5, 2], [], [10, 0.25, 5, 3]]) with self.assertRaisesRegex(errors.InvalidArgumentError, "must have the same row splits"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) if __name__ == "__main__": test.main()
null
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # maxlengthations under the License. # ============================================================================== """Tests for bincount ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import numpy as np from tensorflow.python.eager import context from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.framework import test_util from tensorflow.python.ops import bincount_ops from tensorflow.python.ops import gen_count_ops from tensorflow.python.ops import sparse_ops from tensorflow.python.ops.ragged import ragged_factory_ops from tensorflow.python.ops.ragged import ragged_tensor from tensorflow.python.platform import test class TestSparseCount(test.TestCase, parameterized.TestCase): @parameterized.named_parameters( { "testcase_name": "_no_maxlength", "x": np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 2], [0, 3], [1, 4], [1, 5]], "expected_values": [1, 1, 1, 2, 1], "expected_shape": [2, 6] }, { "testcase_name": "_maxlength", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "maxlength": 7, "expected_indices": [[0, 1], [0, 2], [0, 3], [1, 0], [1, 4]], "expected_values": [1, 1, 1, 1, 2], "expected_shape": [2, 7] }, { "testcase_name": "_minlength", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "minlength": 9, "expected_indices": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4], [1, 7]], "expected_values": [1, 1, 1, 1, 1, 2, 1], "expected_shape": [2, 9] }, { "testcase_name": "_minlength_larger_values", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "minlength": 3, "expected_indices": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4], [1, 7]], "expected_values": [1, 1, 1, 1, 1, 2, 1], "expected_shape": [2, 8] }, { "testcase_name": "_no_maxlength_binary", "x": np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 2], [0, 3], [1, 4], [1, 5]], "expected_values": [1, 1, 1, 1, 1], "expected_shape": [2, 6], "binary_output": True, }, { "testcase_name": "_maxlength_binary", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "maxlength": 7, "expected_indices": [[0, 1], [0, 2], [0, 3], [1, 0], [1, 4]], "expected_values": [1, 1, 1, 1, 1], "expected_shape": [2, 7], "binary_output": True, }, { "testcase_name": "_minlength_binary", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "minlength": 9, "expected_indices": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4], [1, 7]], "expected_values": [1, 1, 1, 1, 1, 1, 1], "expected_shape": [2, 9], "binary_output": True, }, { "testcase_name": "_minlength_larger_values_binary", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "minlength": 3, "expected_indices": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4], [1, 7]], "expected_values": [1, 1, 1, 1, 1, 1, 1], "expected_shape": [2, 8], "binary_output": True, }, { "testcase_name": "_no_maxlength_weights", "x": np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 2], [0, 3], [1, 4], [1, 5]], "expected_values": [2, 1, 0.5, 9, 3], "expected_shape": [2, 6], "weights": [[0.5, 1, 2], [3, 4, 5]] }, { "testcase_name": "_maxlength_weights", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "maxlength": 7, "expected_indices": [[0, 1], [0, 2], [0, 3], [1, 0], [1, 4]], "expected_values": [2, 1, 0.5, 3, 9], "expected_shape": [2, 7], "weights": [[0.5, 1, 2, 11], [7, 3, 4, 5]] }, { "testcase_name": "_minlength_weights", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "minlength": 9, "expected_indices": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4], [1, 7]], "expected_values": [2, 1, 0.5, 3, 5, 13, 4], "expected_shape": [2, 9], "weights": [[0.5, 1, 2, 3], [4, 5, 6, 7]] }, { "testcase_name": "_minlength_larger_values_weights", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "minlength": 3, "expected_indices": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4], [1, 7]], "expected_values": [2, 1, 0.5, 3, 5, 13, 4], "expected_shape": [2, 8], "weights": [[0.5, 1, 2, 3], [4, 5, 6, 7]] }, { "testcase_name": "_1d", "x": np.array([3, 2, 1, 1], dtype=np.int32), "expected_indices": [[1], [2], [3]], "expected_values": [2, 1, 1], "expected_shape": [4] }, { "testcase_name": "_all_axes", "x": np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32), "expected_indices": [[1], [2], [3], [4], [5]], "expected_values": [1, 1, 1, 2, 1], "expected_shape": [6], "axis": None }) def test_dense_input(self, x, expected_indices, expected_values, expected_shape, minlength=None, maxlength=None, binary_output=False, weights=None, axis=-1): y = bincount_ops.sparse_bincount( x, weights=weights, minlength=minlength, maxlength=maxlength, binary_output=binary_output, axis=axis) self.assertAllEqual(expected_indices, y.indices) self.assertAllEqual(expected_values, y.values) self.assertAllEqual(expected_shape, y.dense_shape) @parameterized.named_parameters( { "testcase_name": "_no_maxlength", "x": np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [2, 4], [2, 5]], "expected_values": [1, 1, 2, 1], "expected_shape": [3, 6], }, { "testcase_name": "_maxlength", "x": np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [2, 4], [2, 5]], "expected_values": [1, 1, 2, 1], "expected_shape": [3, 7], "maxlength": 7, }, { "testcase_name": "_minlength", "x": np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]], "expected_values": [1, 1, 1, 2, 1], "expected_shape": [3, 9], "minlength": 9, }, { "testcase_name": "_minlength_larger_values", "x": np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]], "expected_values": [1, 1, 1, 2, 1], "expected_shape": [3, 8], "minlength": 3, }, { "testcase_name": "_no_maxlength_binary", "x": np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [2, 4], [2, 5]], "expected_values": [1, 1, 1, 1], "expected_shape": [3, 6], "binary_output": True, }, { "testcase_name": "_maxlength_binary", "x": np.array([[3, 0, 1, 0], [0, 0, 7, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [2, 4], [2, 5]], "expected_values": [1, 1, 1, 1], "expected_shape": [3, 7], "maxlength": 7, "binary_output": True, }, { "testcase_name": "_minlength_binary", "x": np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]], "expected_values": [1, 1, 1, 1, 1], "expected_shape": [3, 9], "minlength": 9, "binary_output": True, }, { "testcase_name": "_minlength_larger_values_binary", "x": np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]], "expected_values": [1, 1, 1, 1, 1], "expected_shape": [3, 8], "minlength": 3, "binary_output": True, }, { "testcase_name": "_no_maxlength_weights", "x": np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [2, 4], [2, 5]], "expected_values": [2, 6, 7, 10], "expected_shape": [3, 6], "weights": np.array([[6, 0, 2, 0], [0, 0, 0, 0], [10, 0, 3.5, 3.5]]), }, { "testcase_name": "_maxlength_weights", "x": np.array([[3, 0, 1, 0], [0, 0, 7, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [2, 4], [2, 5]], "expected_values": [2, 6, 7, 10], "expected_shape": [3, 7], "maxlength": 7, "weights": np.array([[6, 0, 2, 0], [0, 0, 14, 0], [10, 0, 3.5, 3.5]]), }, { "testcase_name": "_minlength_weights", "x": np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]], "expected_values": [2, 6, 14, 6.5, 10], "expected_shape": [3, 9], "minlength": 9, "weights": np.array([[6, 0, 2, 0], [14, 0, 0, 0], [10, 0, 3, 3.5]]), }, { "testcase_name": "_minlength_larger_values_weights", "x": np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]], "expected_values": [2, 6, 14, 6.5, 10], "expected_shape": [3, 8], "minlength": 3, "weights": np.array([[6, 0, 2, 0], [14, 0, 0, 0], [10, 0, 3, 3.5]]), }, { "testcase_name": "_1d", "x": np.array([3, 0, 1, 1], dtype=np.int32), "expected_indices": [[1], [3]], "expected_values": [2, 1], "expected_shape": [4], }, { "testcase_name": "_all_axes", "x": np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[1], [3], [4], [5]], "expected_values": [1, 1, 2, 1], "expected_shape": [6], "axis": None, }, ) def test_sparse_input(self, x, expected_indices, expected_values, expected_shape, maxlength=None, minlength=None, binary_output=False, weights=None, axis=-1): x_sparse = sparse_ops.from_dense(x) w_sparse = sparse_ops.from_dense(weights) if weights is not None else None y = bincount_ops.sparse_bincount( x_sparse, weights=w_sparse, minlength=minlength, maxlength=maxlength, binary_output=binary_output, axis=axis) self.assertAllEqual(expected_indices, y.indices) self.assertAllEqual(expected_values, y.values) self.assertAllEqual(expected_shape, y.dense_shape) @parameterized.named_parameters( { "testcase_name": "_no_maxlength", "x": [[], [], [3, 0, 1], [], [5, 0, 4, 4]], "expected_indices": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 2, 1], "expected_shape": [5, 6], }, { "testcase_name": "_maxlength", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "maxlength": 7, "expected_indices": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 2, 1], "expected_shape": [5, 7], }, { "testcase_name": "_minlength", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "minlength": 9, "expected_indices": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 1, 2, 1], "expected_shape": [5, 9], }, { "testcase_name": "_minlength_larger_values", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "minlength": 3, "expected_indices": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 1, 2, 1], "expected_shape": [5, 8], }, { "testcase_name": "_no_maxlength_binary", "x": [[], [], [3, 0, 1], [], [5, 0, 4, 4]], "expected_indices": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 1, 1], "expected_shape": [5, 6], "binary_output": True, }, { "testcase_name": "_maxlength_binary", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "maxlength": 7, "expected_indices": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 1, 1], "expected_shape": [5, 7], "binary_output": True, }, { "testcase_name": "_minlength_binary", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "minlength": 9, "expected_indices": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 1, 1, 1], "expected_shape": [5, 9], "binary_output": True, }, { "testcase_name": "_minlength_larger_values_binary", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "minlength": 3, "binary_output": True, "expected_indices": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 1, 1, 1], "expected_shape": [5, 8], }, { "testcase_name": "_no_maxlength_weights", "x": [[], [], [3, 0, 1], [], [5, 0, 4, 4]], "expected_indices": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]], "expected_values": [0.5, 2, 6, 0.25, 8, 10], "expected_shape": [5, 6], "weights": [[], [], [6, 0.5, 2], [], [10, 0.25, 5, 3]], }, { "testcase_name": "_maxlength_weights", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "maxlength": 7, "expected_indices": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]], "expected_values": [0.5, 2, 6, 0.25, 8, 10], "expected_shape": [5, 7], "weights": [[], [], [6, 0.5, 2], [14], [10, 0.25, 5, 3]], }, { "testcase_name": "_minlength_weights", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "minlength": 9, "expected_indices": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4], [4, 5]], "expected_values": [0.5, 2, 6, 14, 0.25, 8, 10], "expected_shape": [5, 9], "weights": [[], [], [6, 0.5, 2], [14], [10, 0.25, 5, 3]], }, { "testcase_name": "_minlength_larger_values_weights", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "minlength": 3, "expected_indices": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4], [4, 5]], "expected_values": [0.5, 2, 6, 14, 0.25, 8, 10], "expected_shape": [5, 8], "weights": [[], [], [6, 0.5, 2], [14], [10, 0.25, 5, 3]], }, { "testcase_name": "_1d", "x": [3, 0, 1, 1], "expected_indices": [[0], [1], [3]], "expected_values": [1, 2, 1], "expected_shape": [4], }, { "testcase_name": "_all_axes", "x": [[], [], [3, 0, 1], [], [5, 0, 4, 4]], "expected_indices": [[0], [1], [3], [4], [5]], "expected_values": [2, 1, 1, 2, 1], "expected_shape": [6], "axis": None, }, ) def test_ragged_input(self, x, expected_indices, expected_values, expected_shape, maxlength=None, minlength=None, binary_output=False, weights=None, axis=-1): x_ragged = ragged_factory_ops.constant(x) w = ragged_factory_ops.constant(weights) if weights is not None else None y = bincount_ops.sparse_bincount( x_ragged, weights=w, minlength=minlength, maxlength=maxlength, binary_output=binary_output, axis=axis) self.assertAllEqual(expected_indices, y.indices) self.assertAllEqual(expected_values, y.values) self.assertAllEqual(expected_shape, y.dense_shape) class TestDenseBincount(test.TestCase, parameterized.TestCase): @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_sparse_input_all_count(self, dtype): np.random.seed(42) num_rows = 128 size = 1000 n_elems = 4096 inp_indices = np.random.randint(0, num_rows, (n_elems, 1)) inp_indices = np.concatenate([inp_indices, np.zeros((n_elems, 1))], axis=1) inp_vals = np.random.randint(0, size, (n_elems,), dtype=dtype) sparse_inp = sparse_tensor.SparseTensor(inp_indices, inp_vals, [num_rows, 1]) np_out = np.bincount(inp_vals, minlength=size) self.assertAllEqual( np_out, self.evaluate(bincount_ops.bincount(sparse_inp, axis=0))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_sparse_input_all_count_with_weights(self, dtype): np.random.seed(42) num_rows = 128 size = 1000 n_elems = 4096 inp_indices = np.random.randint(0, num_rows, (n_elems, 1)) inp_indices = np.concatenate([inp_indices, np.zeros((n_elems, 1))], axis=1) inp_vals = np.random.randint(0, size, (n_elems,), dtype=dtype) sparse_inp = sparse_tensor.SparseTensor(inp_indices, inp_vals, [num_rows, 1]) weight_vals = np.random.random((n_elems,)) sparse_weights = sparse_tensor.SparseTensor(inp_indices, weight_vals, [num_rows, 1]) np_out = np.bincount(inp_vals, minlength=size, weights=weight_vals) self.assertAllEqual( np_out, self.evaluate(bincount_ops.bincount( sparse_inp, sparse_weights, axis=0))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_sparse_input_all_binary(self, dtype): np.random.seed(42) num_rows = 128 size = 10 n_elems = 4096 inp_indices = np.random.randint(0, num_rows, (n_elems, 1)) inp_indices = np.concatenate([inp_indices, np.zeros((n_elems, 1))], axis=1) inp_vals = np.random.randint(0, size, (n_elems,), dtype=dtype) sparse_inp = sparse_tensor.SparseTensor(inp_indices, inp_vals, [num_rows, 1]) np_out = np.ones((size,)) self.assertAllEqual( np_out, self.evaluate(bincount_ops.bincount(sparse_inp, binary_output=True))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_sparse_input_col_reduce_count(self, dtype): num_rows = 128 num_cols = 27 size = 100 np.random.seed(42) inp = np.random.randint(0, size, (num_rows, num_cols), dtype=dtype) np_out = np.reshape( np.concatenate( [np.bincount(inp[j, :], minlength=size) for j in range(num_rows)], axis=0), (num_rows, size)) # from_dense will filter out 0s. inp = inp + 1 # from_dense will cause OOM in GPU. with ops.device("/CPU:0"): inp_sparse = sparse_ops.from_dense(inp) inp_sparse = sparse_tensor.SparseTensor(inp_sparse.indices, inp_sparse.values - 1, inp_sparse.dense_shape) self.assertAllEqual( np_out, self.evaluate(bincount_ops.bincount(arr=inp_sparse, axis=-1))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_sparse_input_col_reduce_binary(self, dtype): num_rows = 128 num_cols = 27 size = 100 np.random.seed(42) inp = np.random.randint(0, size, (num_rows, num_cols), dtype=dtype) np_out = np.reshape( np.concatenate([ np.where(np.bincount(inp[j, :], minlength=size) > 0, 1, 0) for j in range(num_rows) ], axis=0), (num_rows, size)) # from_dense will filter out 0s. inp = inp + 1 # from_dense will cause OOM in GPU. with ops.device("/CPU:0"): inp_sparse = sparse_ops.from_dense(inp) inp_sparse = sparse_tensor.SparseTensor(inp_sparse.indices, inp_sparse.values - 1, inp_sparse.dense_shape) self.assertAllEqual( np_out, self.evaluate( bincount_ops.bincount(arr=inp_sparse, axis=-1, binary_output=True))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_ragged_input_count(self, dtype): x = ragged_factory_ops.constant([[], [], [3, 0, 1], [], [5, 0, 4, 4]], dtype) # pyformat: disable expected_output = [ [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [1, 1, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 2, 1]] # pyformat: enable self.assertAllEqual(expected_output, self.evaluate(bincount_ops.bincount(arr=x, axis=-1))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_ragged_input_binary(self, dtype): x = ragged_factory_ops.constant([[], [], [3, 0, 1], [], [5, 0, 4, 4]]) # pyformat: disable expected_output = [ [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [1, 1, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 1, 1]] # pyformat: enable self.assertAllEqual( expected_output, self.evaluate( bincount_ops.bincount(arr=x, axis=-1, binary_output=True))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_ragged_input_count_with_weights(self, dtype): x = ragged_factory_ops.constant([[], [], [3, 0, 1], [], [5, 0, 4, 4]]) weights = ragged_factory_ops.constant([[], [], [.1, .2, .3], [], [.2, .5, .6, .3]]) # pyformat: disable expected_output = [ [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [.2, .3, 0, .1, 0, 0], [0, 0, 0, 0, 0, 0], [.5, 0, 0, 0, .9, .2]] # pyformat: enable self.assertAllClose( expected_output, self.evaluate(bincount_ops.bincount(arr=x, weights=weights, axis=-1))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_ragged_input_count_np(self, dtype): np.random.seed(42) num_rows = 128 num_cols = 27 size = 1000 inp = np.random.randint(0, size, (num_rows, num_cols), dtype=dtype) np_out = np.reshape( np.concatenate( [np.bincount(inp[j, :], minlength=size) for j in range(num_rows)], axis=0), (num_rows, size)) x = ragged_tensor.RaggedTensor.from_tensor(inp) self.assertAllEqual( np_out, self.evaluate(bincount_ops.bincount(arr=x, minlength=size, axis=-1))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_ragged_input_count_np_with_weights(self, dtype): np.random.seed(42) num_rows = 128 num_cols = 27 size = 1000 inp = np.random.randint(0, size, (num_rows, num_cols), dtype=dtype) np_weight = np.random.random((num_rows, num_cols)) np_out = np.reshape( np.concatenate([ np.bincount(inp[j, :], weights=np_weight[j, :], minlength=size) for j in range(num_rows) ], axis=0), (num_rows, size)) x = ragged_tensor.RaggedTensor.from_tensor(inp) weights = ragged_tensor.RaggedTensor.from_tensor(np_weight) self.assertAllEqual( np_out, self.evaluate( bincount_ops.bincount( arr=x, weights=weights, minlength=size, axis=-1))) class TestSparseCountFailureModes(test.TestCase): def test_dense_input_sparse_weights_fails(self): x = np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32) weights = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) with self.assertRaisesRegex(ValueError, "must be a tf.Tensor"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_dense_input_ragged_weights_fails(self): x = np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32) weights = ragged_factory_ops.constant([[6, 0.5, 2], [14], [10, 0.25, 5, 3]]) with self.assertRaisesRegex(ValueError, "must be a tf.Tensor"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_dense_input_wrong_shape_fails(self): x = np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32) weights = np.array([[3, 2], [5, 4], [4, 3]]) # Note: Eager mode and graph mode throw different errors here. Graph mode # will fail with a ValueError from the shape checking logic, while Eager # will fail with an InvalidArgumentError from the kernel itself. if context.executing_eagerly(): with self.assertRaisesRegex(errors.InvalidArgumentError, "must have the same shape"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) else: with self.assertRaisesRegex(ValueError, "both shapes must be equal"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_sparse_input_dense_weights_fails(self): x = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) weights = np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32) with self.assertRaisesRegex(ValueError, "must be a SparseTensor"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_sparse_input_ragged_weights_fails(self): x = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) weights = ragged_factory_ops.constant([[6, 0.5, 2], [14], [10, 0.25, 5, 3]]) with self.assertRaisesRegex(ValueError, "must be a SparseTensor"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_sparse_input_wrong_indices_fails(self): x = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) weights = sparse_ops.from_dense( np.array([[3, 1, 0, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) with self.assertRaisesRegex(errors.InvalidArgumentError, "must have the same indices"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_sparse_input_too_many_indices_fails(self): x = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) weights = sparse_ops.from_dense( np.array([[3, 1, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) with self.assertRaisesRegex(errors.InvalidArgumentError, "Incompatible shapes"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_sparse_input_wrong_shape_fails(self): x = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) weights = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4], [0, 0, 0, 0]], dtype=np.int32)) with self.assertRaisesRegex(errors.InvalidArgumentError, "must have the same dense shape"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_ragged_input_dense_weights_fails(self): x = ragged_factory_ops.constant([[6, 1, 2], [14], [10, 1, 5, 3]]) weights = np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32) with self.assertRaisesRegex(ValueError, "must be a RaggedTensor"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_ragged_input_sparse_weights_fails(self): x = ragged_factory_ops.constant([[6, 1, 2], [14], [10, 1, 5, 3]]) weights = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) with self.assertRaisesRegex(ValueError, "must be a RaggedTensor"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_ragged_input_different_shape_fails(self): x = ragged_factory_ops.constant([[6, 1, 2], [14], [10, 1, 5, 3]]) weights = ragged_factory_ops.constant([[6, 0.5, 2], [], [10, 0.25, 5, 3]]) with self.assertRaisesRegex(errors.InvalidArgumentError, "must have the same row splits"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) @test_util.run_all_in_graph_and_eager_modes @test_util.disable_tfrt class RawOpsTest(test.TestCase, parameterized.TestCase): def testSparseCountSparseOutputBadIndicesShape(self): indices = [[[0], [0]], [[0], [1]], [[1], [0]], [[1], [2]]] values = [1, 1, 1, 10] weights = [1, 2, 4, 6] dense_shape = [2, 3] with self.assertRaisesRegex(errors.InvalidArgumentError, "Input indices must be a 2-dimensional tensor"): self.evaluate( gen_count_ops.SparseCountSparseOutput( indices=indices, values=values, dense_shape=dense_shape, weights=weights, binary_output=False)) def testSparseCountSparseOutputBadWeightsShape(self): indices = [[0, 0], [0, 1], [1, 0], [1, 2]] values = [1, 1, 1, 10] weights = [1, 2, 4] dense_shape = [2, 3] with self.assertRaisesRegex(errors.InvalidArgumentError, "Weights and values must have the same shape"): self.evaluate( gen_count_ops.SparseCountSparseOutput( indices=indices, values=values, dense_shape=dense_shape, weights=weights, binary_output=False)) def testSparseCountSparseOutputBadNumberOfValues(self): indices = [[0, 0], [0, 1], [1, 0]] values = [1, 1, 1, 10] weights = [1, 2, 4, 6] dense_shape = [2, 3] with self.assertRaisesRegex( errors.InvalidArgumentError, "Number of values must match first dimension of indices"): self.evaluate( gen_count_ops.SparseCountSparseOutput( indices=indices, values=values, dense_shape=dense_shape, weights=weights, binary_output=False)) def testRaggedCountSparseOutput(self): splits = [0, 4, 7] values = [1, 1, 2, 1, 2, 10, 5] weights = [1, 2, 3, 4, 5, 6, 7] output_indices, output_values, output_shape = self.evaluate( gen_count_ops.RaggedCountSparseOutput( splits=splits, values=values, weights=weights, binary_output=False)) self.assertAllEqual([[0, 1], [0, 2], [1, 2], [1, 5], [1, 10]], output_indices) self.assertAllEqual([7, 3, 5, 7, 6], output_values) self.assertAllEqual([2, 11], output_shape) def testRaggedCountSparseOutputBadWeightsShape(self): splits = [0, 4, 7] values = [1, 1, 2, 1, 2, 10, 5] weights = [1, 2, 3, 4, 5, 6] with self.assertRaisesRegex(errors.InvalidArgumentError, "Weights and values must have the same shape"): self.evaluate( gen_count_ops.RaggedCountSparseOutput( splits=splits, values=values, weights=weights, binary_output=False)) def testRaggedCountSparseOutputEmptySplits(self): splits = [] values = [1, 1, 2, 1, 2, 10, 5] weights = [1, 2, 3, 4, 5, 6, 7] with self.assertRaisesRegex( errors.InvalidArgumentError, "Must provide at least 2 elements for the splits argument"): self.evaluate( gen_count_ops.RaggedCountSparseOutput( splits=splits, values=values, weights=weights, binary_output=False)) def testRaggedCountSparseOutputBadSplitsStart(self): splits = [1, 7] values = [1, 1, 2, 1, 2, 10, 5] weights = [1, 2, 3, 4, 5, 6, 7] with self.assertRaisesRegex(errors.InvalidArgumentError, "Splits must start with 0"): self.evaluate( gen_count_ops.RaggedCountSparseOutput( splits=splits, values=values, weights=weights, binary_output=False)) def testRaggedCountSparseOutputBadSplitsEnd(self): splits = [0, 5] values = [1, 1, 2, 1, 2, 10, 5] weights = [1, 2, 3, 4, 5, 6, 7] with self.assertRaisesRegex(errors.InvalidArgumentError, "Splits must end with the number of values"): self.evaluate( gen_count_ops.RaggedCountSparseOutput( splits=splits, values=values, weights=weights, binary_output=False)) if __name__ == "__main__": test.main()
null
180
CWE-787
CVE-2020-15201
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # maxlengthations under the License. # ============================================================================== """Tests for bincount ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import numpy as np from tensorflow.python.eager import context from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.ops import bincount_ops from tensorflow.python.ops import sparse_ops from tensorflow.python.ops.ragged import ragged_factory_ops from tensorflow.python.ops.ragged import ragged_tensor from tensorflow.python.platform import test class TestSparseCount(test.TestCase, parameterized.TestCase): @parameterized.named_parameters( { "testcase_name": "_no_maxlength", "x": np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 2], [0, 3], [1, 4], [1, 5]], "expected_values": [1, 1, 1, 2, 1], "expected_shape": [2, 6] }, { "testcase_name": "_maxlength", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "maxlength": 7, "expected_indices": [[0, 1], [0, 2], [0, 3], [1, 0], [1, 4]], "expected_values": [1, 1, 1, 1, 2], "expected_shape": [2, 7] }, { "testcase_name": "_minlength", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "minlength": 9, "expected_indices": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4], [1, 7]], "expected_values": [1, 1, 1, 1, 1, 2, 1], "expected_shape": [2, 9] }, { "testcase_name": "_minlength_larger_values", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "minlength": 3, "expected_indices": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4], [1, 7]], "expected_values": [1, 1, 1, 1, 1, 2, 1], "expected_shape": [2, 8] }, { "testcase_name": "_no_maxlength_binary", "x": np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 2], [0, 3], [1, 4], [1, 5]], "expected_values": [1, 1, 1, 1, 1], "expected_shape": [2, 6], "binary_output": True, }, { "testcase_name": "_maxlength_binary", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "maxlength": 7, "expected_indices": [[0, 1], [0, 2], [0, 3], [1, 0], [1, 4]], "expected_values": [1, 1, 1, 1, 1], "expected_shape": [2, 7], "binary_output": True, }, { "testcase_name": "_minlength_binary", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "minlength": 9, "expected_indices": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4], [1, 7]], "expected_values": [1, 1, 1, 1, 1, 1, 1], "expected_shape": [2, 9], "binary_output": True, }, { "testcase_name": "_minlength_larger_values_binary", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "minlength": 3, "expected_indices": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4], [1, 7]], "expected_values": [1, 1, 1, 1, 1, 1, 1], "expected_shape": [2, 8], "binary_output": True, }, { "testcase_name": "_no_maxlength_weights", "x": np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 2], [0, 3], [1, 4], [1, 5]], "expected_values": [2, 1, 0.5, 9, 3], "expected_shape": [2, 6], "weights": [[0.5, 1, 2], [3, 4, 5]] }, { "testcase_name": "_maxlength_weights", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "maxlength": 7, "expected_indices": [[0, 1], [0, 2], [0, 3], [1, 0], [1, 4]], "expected_values": [2, 1, 0.5, 3, 9], "expected_shape": [2, 7], "weights": [[0.5, 1, 2, 11], [7, 3, 4, 5]] }, { "testcase_name": "_minlength_weights", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "minlength": 9, "expected_indices": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4], [1, 7]], "expected_values": [2, 1, 0.5, 3, 5, 13, 4], "expected_shape": [2, 9], "weights": [[0.5, 1, 2, 3], [4, 5, 6, 7]] }, { "testcase_name": "_minlength_larger_values_weights", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "minlength": 3, "expected_indices": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4], [1, 7]], "expected_values": [2, 1, 0.5, 3, 5, 13, 4], "expected_shape": [2, 8], "weights": [[0.5, 1, 2, 3], [4, 5, 6, 7]] }, { "testcase_name": "_1d", "x": np.array([3, 2, 1, 1], dtype=np.int32), "expected_indices": [[1], [2], [3]], "expected_values": [2, 1, 1], "expected_shape": [4] }, { "testcase_name": "_all_axes", "x": np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32), "expected_indices": [[1], [2], [3], [4], [5]], "expected_values": [1, 1, 1, 2, 1], "expected_shape": [6], "axis": None }) def test_dense_input(self, x, expected_indices, expected_values, expected_shape, minlength=None, maxlength=None, binary_output=False, weights=None, axis=-1): y = bincount_ops.sparse_bincount( x, weights=weights, minlength=minlength, maxlength=maxlength, binary_output=binary_output, axis=axis) self.assertAllEqual(expected_indices, y.indices) self.assertAllEqual(expected_values, y.values) self.assertAllEqual(expected_shape, y.dense_shape) @parameterized.named_parameters( { "testcase_name": "_no_maxlength", "x": np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [2, 4], [2, 5]], "expected_values": [1, 1, 2, 1], "expected_shape": [3, 6], }, { "testcase_name": "_maxlength", "x": np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [2, 4], [2, 5]], "expected_values": [1, 1, 2, 1], "expected_shape": [3, 7], "maxlength": 7, }, { "testcase_name": "_minlength", "x": np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]], "expected_values": [1, 1, 1, 2, 1], "expected_shape": [3, 9], "minlength": 9, }, { "testcase_name": "_minlength_larger_values", "x": np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]], "expected_values": [1, 1, 1, 2, 1], "expected_shape": [3, 8], "minlength": 3, }, { "testcase_name": "_no_maxlength_binary", "x": np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [2, 4], [2, 5]], "expected_values": [1, 1, 1, 1], "expected_shape": [3, 6], "binary_output": True, }, { "testcase_name": "_maxlength_binary", "x": np.array([[3, 0, 1, 0], [0, 0, 7, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [2, 4], [2, 5]], "expected_values": [1, 1, 1, 1], "expected_shape": [3, 7], "maxlength": 7, "binary_output": True, }, { "testcase_name": "_minlength_binary", "x": np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]], "expected_values": [1, 1, 1, 1, 1], "expected_shape": [3, 9], "minlength": 9, "binary_output": True, }, { "testcase_name": "_minlength_larger_values_binary", "x": np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]], "expected_values": [1, 1, 1, 1, 1], "expected_shape": [3, 8], "minlength": 3, "binary_output": True, }, { "testcase_name": "_no_maxlength_weights", "x": np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [2, 4], [2, 5]], "expected_values": [2, 6, 7, 10], "expected_shape": [3, 6], "weights": np.array([[6, 0, 2, 0], [0, 0, 0, 0], [10, 0, 3.5, 3.5]]), }, { "testcase_name": "_maxlength_weights", "x": np.array([[3, 0, 1, 0], [0, 0, 7, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [2, 4], [2, 5]], "expected_values": [2, 6, 7, 10], "expected_shape": [3, 7], "maxlength": 7, "weights": np.array([[6, 0, 2, 0], [0, 0, 14, 0], [10, 0, 3.5, 3.5]]), }, { "testcase_name": "_minlength_weights", "x": np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]], "expected_values": [2, 6, 14, 6.5, 10], "expected_shape": [3, 9], "minlength": 9, "weights": np.array([[6, 0, 2, 0], [14, 0, 0, 0], [10, 0, 3, 3.5]]), }, { "testcase_name": "_minlength_larger_values_weights", "x": np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]], "expected_values": [2, 6, 14, 6.5, 10], "expected_shape": [3, 8], "minlength": 3, "weights": np.array([[6, 0, 2, 0], [14, 0, 0, 0], [10, 0, 3, 3.5]]), }, { "testcase_name": "_1d", "x": np.array([3, 0, 1, 1], dtype=np.int32), "expected_indices": [[1], [3]], "expected_values": [2, 1], "expected_shape": [4], }, { "testcase_name": "_all_axes", "x": np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[1], [3], [4], [5]], "expected_values": [1, 1, 2, 1], "expected_shape": [6], "axis": None, }, ) def test_sparse_input(self, x, expected_indices, expected_values, expected_shape, maxlength=None, minlength=None, binary_output=False, weights=None, axis=-1): x_sparse = sparse_ops.from_dense(x) w_sparse = sparse_ops.from_dense(weights) if weights is not None else None y = bincount_ops.sparse_bincount( x_sparse, weights=w_sparse, minlength=minlength, maxlength=maxlength, binary_output=binary_output, axis=axis) self.assertAllEqual(expected_indices, y.indices) self.assertAllEqual(expected_values, y.values) self.assertAllEqual(expected_shape, y.dense_shape) @parameterized.named_parameters( { "testcase_name": "_no_maxlength", "x": [[], [], [3, 0, 1], [], [5, 0, 4, 4]], "expected_indices": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 2, 1], "expected_shape": [5, 6], }, { "testcase_name": "_maxlength", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "maxlength": 7, "expected_indices": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 2, 1], "expected_shape": [5, 7], }, { "testcase_name": "_minlength", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "minlength": 9, "expected_indices": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 1, 2, 1], "expected_shape": [5, 9], }, { "testcase_name": "_minlength_larger_values", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "minlength": 3, "expected_indices": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 1, 2, 1], "expected_shape": [5, 8], }, { "testcase_name": "_no_maxlength_binary", "x": [[], [], [3, 0, 1], [], [5, 0, 4, 4]], "expected_indices": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 1, 1], "expected_shape": [5, 6], "binary_output": True, }, { "testcase_name": "_maxlength_binary", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "maxlength": 7, "expected_indices": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 1, 1], "expected_shape": [5, 7], "binary_output": True, }, { "testcase_name": "_minlength_binary", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "minlength": 9, "expected_indices": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 1, 1, 1], "expected_shape": [5, 9], "binary_output": True, }, { "testcase_name": "_minlength_larger_values_binary", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "minlength": 3, "binary_output": True, "expected_indices": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 1, 1, 1], "expected_shape": [5, 8], }, { "testcase_name": "_no_maxlength_weights", "x": [[], [], [3, 0, 1], [], [5, 0, 4, 4]], "expected_indices": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]], "expected_values": [0.5, 2, 6, 0.25, 8, 10], "expected_shape": [5, 6], "weights": [[], [], [6, 0.5, 2], [], [10, 0.25, 5, 3]], }, { "testcase_name": "_maxlength_weights", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "maxlength": 7, "expected_indices": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]], "expected_values": [0.5, 2, 6, 0.25, 8, 10], "expected_shape": [5, 7], "weights": [[], [], [6, 0.5, 2], [14], [10, 0.25, 5, 3]], }, { "testcase_name": "_minlength_weights", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "minlength": 9, "expected_indices": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4], [4, 5]], "expected_values": [0.5, 2, 6, 14, 0.25, 8, 10], "expected_shape": [5, 9], "weights": [[], [], [6, 0.5, 2], [14], [10, 0.25, 5, 3]], }, { "testcase_name": "_minlength_larger_values_weights", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "minlength": 3, "expected_indices": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4], [4, 5]], "expected_values": [0.5, 2, 6, 14, 0.25, 8, 10], "expected_shape": [5, 8], "weights": [[], [], [6, 0.5, 2], [14], [10, 0.25, 5, 3]], }, { "testcase_name": "_1d", "x": [3, 0, 1, 1], "expected_indices": [[0], [1], [3]], "expected_values": [1, 2, 1], "expected_shape": [4], }, { "testcase_name": "_all_axes", "x": [[], [], [3, 0, 1], [], [5, 0, 4, 4]], "expected_indices": [[0], [1], [3], [4], [5]], "expected_values": [2, 1, 1, 2, 1], "expected_shape": [6], "axis": None, }, ) def test_ragged_input(self, x, expected_indices, expected_values, expected_shape, maxlength=None, minlength=None, binary_output=False, weights=None, axis=-1): x_ragged = ragged_factory_ops.constant(x) w = ragged_factory_ops.constant(weights) if weights is not None else None y = bincount_ops.sparse_bincount( x_ragged, weights=w, minlength=minlength, maxlength=maxlength, binary_output=binary_output, axis=axis) self.assertAllEqual(expected_indices, y.indices) self.assertAllEqual(expected_values, y.values) self.assertAllEqual(expected_shape, y.dense_shape) class TestDenseBincount(test.TestCase, parameterized.TestCase): @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_sparse_input_all_count(self, dtype): np.random.seed(42) num_rows = 128 size = 1000 n_elems = 4096 inp_indices = np.random.randint(0, num_rows, (n_elems, 1)) inp_indices = np.concatenate([inp_indices, np.zeros((n_elems, 1))], axis=1) inp_vals = np.random.randint(0, size, (n_elems,), dtype=dtype) sparse_inp = sparse_tensor.SparseTensor(inp_indices, inp_vals, [num_rows, 1]) np_out = np.bincount(inp_vals, minlength=size) self.assertAllEqual( np_out, self.evaluate(bincount_ops.bincount(sparse_inp, axis=0))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_sparse_input_all_count_with_weights(self, dtype): np.random.seed(42) num_rows = 128 size = 1000 n_elems = 4096 inp_indices = np.random.randint(0, num_rows, (n_elems, 1)) inp_indices = np.concatenate([inp_indices, np.zeros((n_elems, 1))], axis=1) inp_vals = np.random.randint(0, size, (n_elems,), dtype=dtype) sparse_inp = sparse_tensor.SparseTensor(inp_indices, inp_vals, [num_rows, 1]) weight_vals = np.random.random((n_elems,)) sparse_weights = sparse_tensor.SparseTensor(inp_indices, weight_vals, [num_rows, 1]) np_out = np.bincount(inp_vals, minlength=size, weights=weight_vals) self.assertAllEqual( np_out, self.evaluate(bincount_ops.bincount( sparse_inp, sparse_weights, axis=0))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_sparse_input_all_binary(self, dtype): np.random.seed(42) num_rows = 128 size = 10 n_elems = 4096 inp_indices = np.random.randint(0, num_rows, (n_elems, 1)) inp_indices = np.concatenate([inp_indices, np.zeros((n_elems, 1))], axis=1) inp_vals = np.random.randint(0, size, (n_elems,), dtype=dtype) sparse_inp = sparse_tensor.SparseTensor(inp_indices, inp_vals, [num_rows, 1]) np_out = np.ones((size,)) self.assertAllEqual( np_out, self.evaluate(bincount_ops.bincount(sparse_inp, binary_output=True))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_sparse_input_col_reduce_count(self, dtype): num_rows = 128 num_cols = 27 size = 100 np.random.seed(42) inp = np.random.randint(0, size, (num_rows, num_cols), dtype=dtype) np_out = np.reshape( np.concatenate( [np.bincount(inp[j, :], minlength=size) for j in range(num_rows)], axis=0), (num_rows, size)) # from_dense will filter out 0s. inp = inp + 1 # from_dense will cause OOM in GPU. with ops.device("/CPU:0"): inp_sparse = sparse_ops.from_dense(inp) inp_sparse = sparse_tensor.SparseTensor(inp_sparse.indices, inp_sparse.values - 1, inp_sparse.dense_shape) self.assertAllEqual( np_out, self.evaluate(bincount_ops.bincount(arr=inp_sparse, axis=-1))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_sparse_input_col_reduce_binary(self, dtype): num_rows = 128 num_cols = 27 size = 100 np.random.seed(42) inp = np.random.randint(0, size, (num_rows, num_cols), dtype=dtype) np_out = np.reshape( np.concatenate([ np.where(np.bincount(inp[j, :], minlength=size) > 0, 1, 0) for j in range(num_rows) ], axis=0), (num_rows, size)) # from_dense will filter out 0s. inp = inp + 1 # from_dense will cause OOM in GPU. with ops.device("/CPU:0"): inp_sparse = sparse_ops.from_dense(inp) inp_sparse = sparse_tensor.SparseTensor(inp_sparse.indices, inp_sparse.values - 1, inp_sparse.dense_shape) self.assertAllEqual( np_out, self.evaluate( bincount_ops.bincount(arr=inp_sparse, axis=-1, binary_output=True))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_ragged_input_count(self, dtype): x = ragged_factory_ops.constant([[], [], [3, 0, 1], [], [5, 0, 4, 4]], dtype) # pyformat: disable expected_output = [ [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [1, 1, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 2, 1]] # pyformat: enable self.assertAllEqual(expected_output, self.evaluate(bincount_ops.bincount(arr=x, axis=-1))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_ragged_input_binary(self, dtype): x = ragged_factory_ops.constant([[], [], [3, 0, 1], [], [5, 0, 4, 4]]) # pyformat: disable expected_output = [ [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [1, 1, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 1, 1]] # pyformat: enable self.assertAllEqual( expected_output, self.evaluate( bincount_ops.bincount(arr=x, axis=-1, binary_output=True))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_ragged_input_count_with_weights(self, dtype): x = ragged_factory_ops.constant([[], [], [3, 0, 1], [], [5, 0, 4, 4]]) weights = ragged_factory_ops.constant([[], [], [.1, .2, .3], [], [.2, .5, .6, .3]]) # pyformat: disable expected_output = [ [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [.2, .3, 0, .1, 0, 0], [0, 0, 0, 0, 0, 0], [.5, 0, 0, 0, .9, .2]] # pyformat: enable self.assertAllClose( expected_output, self.evaluate(bincount_ops.bincount(arr=x, weights=weights, axis=-1))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_ragged_input_count_np(self, dtype): np.random.seed(42) num_rows = 128 num_cols = 27 size = 1000 inp = np.random.randint(0, size, (num_rows, num_cols), dtype=dtype) np_out = np.reshape( np.concatenate( [np.bincount(inp[j, :], minlength=size) for j in range(num_rows)], axis=0), (num_rows, size)) x = ragged_tensor.RaggedTensor.from_tensor(inp) self.assertAllEqual( np_out, self.evaluate(bincount_ops.bincount(arr=x, minlength=size, axis=-1))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_ragged_input_count_np_with_weights(self, dtype): np.random.seed(42) num_rows = 128 num_cols = 27 size = 1000 inp = np.random.randint(0, size, (num_rows, num_cols), dtype=dtype) np_weight = np.random.random((num_rows, num_cols)) np_out = np.reshape( np.concatenate([ np.bincount(inp[j, :], weights=np_weight[j, :], minlength=size) for j in range(num_rows) ], axis=0), (num_rows, size)) x = ragged_tensor.RaggedTensor.from_tensor(inp) weights = ragged_tensor.RaggedTensor.from_tensor(np_weight) self.assertAllEqual( np_out, self.evaluate( bincount_ops.bincount( arr=x, weights=weights, minlength=size, axis=-1))) class TestSparseCountFailureModes(test.TestCase): def test_dense_input_sparse_weights_fails(self): x = np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32) weights = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) with self.assertRaisesRegex(ValueError, "must be a tf.Tensor"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_dense_input_ragged_weights_fails(self): x = np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32) weights = ragged_factory_ops.constant([[6, 0.5, 2], [14], [10, 0.25, 5, 3]]) with self.assertRaisesRegex(ValueError, "must be a tf.Tensor"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_dense_input_wrong_shape_fails(self): x = np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32) weights = np.array([[3, 2], [5, 4], [4, 3]]) # Note: Eager mode and graph mode throw different errors here. Graph mode # will fail with a ValueError from the shape checking logic, while Eager # will fail with an InvalidArgumentError from the kernel itself. if context.executing_eagerly(): with self.assertRaisesRegex(errors.InvalidArgumentError, "must have the same shape"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) else: with self.assertRaisesRegex(ValueError, "both shapes must be equal"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_sparse_input_dense_weights_fails(self): x = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) weights = np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32) with self.assertRaisesRegex(ValueError, "must be a SparseTensor"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_sparse_input_ragged_weights_fails(self): x = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) weights = ragged_factory_ops.constant([[6, 0.5, 2], [14], [10, 0.25, 5, 3]]) with self.assertRaisesRegex(ValueError, "must be a SparseTensor"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_sparse_input_wrong_indices_fails(self): x = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) weights = sparse_ops.from_dense( np.array([[3, 1, 0, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) with self.assertRaisesRegex(errors.InvalidArgumentError, "must have the same indices"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_sparse_input_too_many_indices_fails(self): x = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) weights = sparse_ops.from_dense( np.array([[3, 1, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) with self.assertRaisesRegex(errors.InvalidArgumentError, "Incompatible shapes"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_sparse_input_wrong_shape_fails(self): x = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) weights = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4], [0, 0, 0, 0]], dtype=np.int32)) with self.assertRaisesRegex(errors.InvalidArgumentError, "must have the same dense shape"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_ragged_input_dense_weights_fails(self): x = ragged_factory_ops.constant([[6, 1, 2], [14], [10, 1, 5, 3]]) weights = np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32) with self.assertRaisesRegex(ValueError, "must be a RaggedTensor"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_ragged_input_sparse_weights_fails(self): x = ragged_factory_ops.constant([[6, 1, 2], [14], [10, 1, 5, 3]]) weights = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) with self.assertRaisesRegex(ValueError, "must be a RaggedTensor"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_ragged_input_different_shape_fails(self): x = ragged_factory_ops.constant([[6, 1, 2], [14], [10, 1, 5, 3]]) weights = ragged_factory_ops.constant([[6, 0.5, 2], [], [10, 0.25, 5, 3]]) with self.assertRaisesRegex(errors.InvalidArgumentError, "must have the same row splits"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) if __name__ == "__main__": test.main()
null
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # maxlengthations under the License. # ============================================================================== """Tests for bincount ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import numpy as np from tensorflow.python.eager import context from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.framework import test_util from tensorflow.python.ops import bincount_ops from tensorflow.python.ops import gen_count_ops from tensorflow.python.ops import sparse_ops from tensorflow.python.ops.ragged import ragged_factory_ops from tensorflow.python.ops.ragged import ragged_tensor from tensorflow.python.platform import test class TestSparseCount(test.TestCase, parameterized.TestCase): @parameterized.named_parameters( { "testcase_name": "_no_maxlength", "x": np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 2], [0, 3], [1, 4], [1, 5]], "expected_values": [1, 1, 1, 2, 1], "expected_shape": [2, 6] }, { "testcase_name": "_maxlength", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "maxlength": 7, "expected_indices": [[0, 1], [0, 2], [0, 3], [1, 0], [1, 4]], "expected_values": [1, 1, 1, 1, 2], "expected_shape": [2, 7] }, { "testcase_name": "_minlength", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "minlength": 9, "expected_indices": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4], [1, 7]], "expected_values": [1, 1, 1, 1, 1, 2, 1], "expected_shape": [2, 9] }, { "testcase_name": "_minlength_larger_values", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "minlength": 3, "expected_indices": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4], [1, 7]], "expected_values": [1, 1, 1, 1, 1, 2, 1], "expected_shape": [2, 8] }, { "testcase_name": "_no_maxlength_binary", "x": np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 2], [0, 3], [1, 4], [1, 5]], "expected_values": [1, 1, 1, 1, 1], "expected_shape": [2, 6], "binary_output": True, }, { "testcase_name": "_maxlength_binary", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "maxlength": 7, "expected_indices": [[0, 1], [0, 2], [0, 3], [1, 0], [1, 4]], "expected_values": [1, 1, 1, 1, 1], "expected_shape": [2, 7], "binary_output": True, }, { "testcase_name": "_minlength_binary", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "minlength": 9, "expected_indices": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4], [1, 7]], "expected_values": [1, 1, 1, 1, 1, 1, 1], "expected_shape": [2, 9], "binary_output": True, }, { "testcase_name": "_minlength_larger_values_binary", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "minlength": 3, "expected_indices": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4], [1, 7]], "expected_values": [1, 1, 1, 1, 1, 1, 1], "expected_shape": [2, 8], "binary_output": True, }, { "testcase_name": "_no_maxlength_weights", "x": np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 2], [0, 3], [1, 4], [1, 5]], "expected_values": [2, 1, 0.5, 9, 3], "expected_shape": [2, 6], "weights": [[0.5, 1, 2], [3, 4, 5]] }, { "testcase_name": "_maxlength_weights", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "maxlength": 7, "expected_indices": [[0, 1], [0, 2], [0, 3], [1, 0], [1, 4]], "expected_values": [2, 1, 0.5, 3, 9], "expected_shape": [2, 7], "weights": [[0.5, 1, 2, 11], [7, 3, 4, 5]] }, { "testcase_name": "_minlength_weights", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "minlength": 9, "expected_indices": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4], [1, 7]], "expected_values": [2, 1, 0.5, 3, 5, 13, 4], "expected_shape": [2, 9], "weights": [[0.5, 1, 2, 3], [4, 5, 6, 7]] }, { "testcase_name": "_minlength_larger_values_weights", "x": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32), "minlength": 3, "expected_indices": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4], [1, 7]], "expected_values": [2, 1, 0.5, 3, 5, 13, 4], "expected_shape": [2, 8], "weights": [[0.5, 1, 2, 3], [4, 5, 6, 7]] }, { "testcase_name": "_1d", "x": np.array([3, 2, 1, 1], dtype=np.int32), "expected_indices": [[1], [2], [3]], "expected_values": [2, 1, 1], "expected_shape": [4] }, { "testcase_name": "_all_axes", "x": np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32), "expected_indices": [[1], [2], [3], [4], [5]], "expected_values": [1, 1, 1, 2, 1], "expected_shape": [6], "axis": None }) def test_dense_input(self, x, expected_indices, expected_values, expected_shape, minlength=None, maxlength=None, binary_output=False, weights=None, axis=-1): y = bincount_ops.sparse_bincount( x, weights=weights, minlength=minlength, maxlength=maxlength, binary_output=binary_output, axis=axis) self.assertAllEqual(expected_indices, y.indices) self.assertAllEqual(expected_values, y.values) self.assertAllEqual(expected_shape, y.dense_shape) @parameterized.named_parameters( { "testcase_name": "_no_maxlength", "x": np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [2, 4], [2, 5]], "expected_values": [1, 1, 2, 1], "expected_shape": [3, 6], }, { "testcase_name": "_maxlength", "x": np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [2, 4], [2, 5]], "expected_values": [1, 1, 2, 1], "expected_shape": [3, 7], "maxlength": 7, }, { "testcase_name": "_minlength", "x": np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]], "expected_values": [1, 1, 1, 2, 1], "expected_shape": [3, 9], "minlength": 9, }, { "testcase_name": "_minlength_larger_values", "x": np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]], "expected_values": [1, 1, 1, 2, 1], "expected_shape": [3, 8], "minlength": 3, }, { "testcase_name": "_no_maxlength_binary", "x": np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [2, 4], [2, 5]], "expected_values": [1, 1, 1, 1], "expected_shape": [3, 6], "binary_output": True, }, { "testcase_name": "_maxlength_binary", "x": np.array([[3, 0, 1, 0], [0, 0, 7, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [2, 4], [2, 5]], "expected_values": [1, 1, 1, 1], "expected_shape": [3, 7], "maxlength": 7, "binary_output": True, }, { "testcase_name": "_minlength_binary", "x": np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]], "expected_values": [1, 1, 1, 1, 1], "expected_shape": [3, 9], "minlength": 9, "binary_output": True, }, { "testcase_name": "_minlength_larger_values_binary", "x": np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]], "expected_values": [1, 1, 1, 1, 1], "expected_shape": [3, 8], "minlength": 3, "binary_output": True, }, { "testcase_name": "_no_maxlength_weights", "x": np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [2, 4], [2, 5]], "expected_values": [2, 6, 7, 10], "expected_shape": [3, 6], "weights": np.array([[6, 0, 2, 0], [0, 0, 0, 0], [10, 0, 3.5, 3.5]]), }, { "testcase_name": "_maxlength_weights", "x": np.array([[3, 0, 1, 0], [0, 0, 7, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [2, 4], [2, 5]], "expected_values": [2, 6, 7, 10], "expected_shape": [3, 7], "maxlength": 7, "weights": np.array([[6, 0, 2, 0], [0, 0, 14, 0], [10, 0, 3.5, 3.5]]), }, { "testcase_name": "_minlength_weights", "x": np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]], "expected_values": [2, 6, 14, 6.5, 10], "expected_shape": [3, 9], "minlength": 9, "weights": np.array([[6, 0, 2, 0], [14, 0, 0, 0], [10, 0, 3, 3.5]]), }, { "testcase_name": "_minlength_larger_values_weights", "x": np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]], "expected_values": [2, 6, 14, 6.5, 10], "expected_shape": [3, 8], "minlength": 3, "weights": np.array([[6, 0, 2, 0], [14, 0, 0, 0], [10, 0, 3, 3.5]]), }, { "testcase_name": "_1d", "x": np.array([3, 0, 1, 1], dtype=np.int32), "expected_indices": [[1], [3]], "expected_values": [2, 1], "expected_shape": [4], }, { "testcase_name": "_all_axes", "x": np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32), "expected_indices": [[1], [3], [4], [5]], "expected_values": [1, 1, 2, 1], "expected_shape": [6], "axis": None, }, ) def test_sparse_input(self, x, expected_indices, expected_values, expected_shape, maxlength=None, minlength=None, binary_output=False, weights=None, axis=-1): x_sparse = sparse_ops.from_dense(x) w_sparse = sparse_ops.from_dense(weights) if weights is not None else None y = bincount_ops.sparse_bincount( x_sparse, weights=w_sparse, minlength=minlength, maxlength=maxlength, binary_output=binary_output, axis=axis) self.assertAllEqual(expected_indices, y.indices) self.assertAllEqual(expected_values, y.values) self.assertAllEqual(expected_shape, y.dense_shape) @parameterized.named_parameters( { "testcase_name": "_no_maxlength", "x": [[], [], [3, 0, 1], [], [5, 0, 4, 4]], "expected_indices": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 2, 1], "expected_shape": [5, 6], }, { "testcase_name": "_maxlength", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "maxlength": 7, "expected_indices": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 2, 1], "expected_shape": [5, 7], }, { "testcase_name": "_minlength", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "minlength": 9, "expected_indices": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 1, 2, 1], "expected_shape": [5, 9], }, { "testcase_name": "_minlength_larger_values", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "minlength": 3, "expected_indices": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 1, 2, 1], "expected_shape": [5, 8], }, { "testcase_name": "_no_maxlength_binary", "x": [[], [], [3, 0, 1], [], [5, 0, 4, 4]], "expected_indices": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 1, 1], "expected_shape": [5, 6], "binary_output": True, }, { "testcase_name": "_maxlength_binary", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "maxlength": 7, "expected_indices": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 1, 1], "expected_shape": [5, 7], "binary_output": True, }, { "testcase_name": "_minlength_binary", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "minlength": 9, "expected_indices": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 1, 1, 1], "expected_shape": [5, 9], "binary_output": True, }, { "testcase_name": "_minlength_larger_values_binary", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "minlength": 3, "binary_output": True, "expected_indices": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4], [4, 5]], "expected_values": [1, 1, 1, 1, 1, 1, 1], "expected_shape": [5, 8], }, { "testcase_name": "_no_maxlength_weights", "x": [[], [], [3, 0, 1], [], [5, 0, 4, 4]], "expected_indices": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]], "expected_values": [0.5, 2, 6, 0.25, 8, 10], "expected_shape": [5, 6], "weights": [[], [], [6, 0.5, 2], [], [10, 0.25, 5, 3]], }, { "testcase_name": "_maxlength_weights", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "maxlength": 7, "expected_indices": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]], "expected_values": [0.5, 2, 6, 0.25, 8, 10], "expected_shape": [5, 7], "weights": [[], [], [6, 0.5, 2], [14], [10, 0.25, 5, 3]], }, { "testcase_name": "_minlength_weights", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "minlength": 9, "expected_indices": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4], [4, 5]], "expected_values": [0.5, 2, 6, 14, 0.25, 8, 10], "expected_shape": [5, 9], "weights": [[], [], [6, 0.5, 2], [14], [10, 0.25, 5, 3]], }, { "testcase_name": "_minlength_larger_values_weights", "x": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]], "minlength": 3, "expected_indices": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4], [4, 5]], "expected_values": [0.5, 2, 6, 14, 0.25, 8, 10], "expected_shape": [5, 8], "weights": [[], [], [6, 0.5, 2], [14], [10, 0.25, 5, 3]], }, { "testcase_name": "_1d", "x": [3, 0, 1, 1], "expected_indices": [[0], [1], [3]], "expected_values": [1, 2, 1], "expected_shape": [4], }, { "testcase_name": "_all_axes", "x": [[], [], [3, 0, 1], [], [5, 0, 4, 4]], "expected_indices": [[0], [1], [3], [4], [5]], "expected_values": [2, 1, 1, 2, 1], "expected_shape": [6], "axis": None, }, ) def test_ragged_input(self, x, expected_indices, expected_values, expected_shape, maxlength=None, minlength=None, binary_output=False, weights=None, axis=-1): x_ragged = ragged_factory_ops.constant(x) w = ragged_factory_ops.constant(weights) if weights is not None else None y = bincount_ops.sparse_bincount( x_ragged, weights=w, minlength=minlength, maxlength=maxlength, binary_output=binary_output, axis=axis) self.assertAllEqual(expected_indices, y.indices) self.assertAllEqual(expected_values, y.values) self.assertAllEqual(expected_shape, y.dense_shape) class TestDenseBincount(test.TestCase, parameterized.TestCase): @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_sparse_input_all_count(self, dtype): np.random.seed(42) num_rows = 128 size = 1000 n_elems = 4096 inp_indices = np.random.randint(0, num_rows, (n_elems, 1)) inp_indices = np.concatenate([inp_indices, np.zeros((n_elems, 1))], axis=1) inp_vals = np.random.randint(0, size, (n_elems,), dtype=dtype) sparse_inp = sparse_tensor.SparseTensor(inp_indices, inp_vals, [num_rows, 1]) np_out = np.bincount(inp_vals, minlength=size) self.assertAllEqual( np_out, self.evaluate(bincount_ops.bincount(sparse_inp, axis=0))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_sparse_input_all_count_with_weights(self, dtype): np.random.seed(42) num_rows = 128 size = 1000 n_elems = 4096 inp_indices = np.random.randint(0, num_rows, (n_elems, 1)) inp_indices = np.concatenate([inp_indices, np.zeros((n_elems, 1))], axis=1) inp_vals = np.random.randint(0, size, (n_elems,), dtype=dtype) sparse_inp = sparse_tensor.SparseTensor(inp_indices, inp_vals, [num_rows, 1]) weight_vals = np.random.random((n_elems,)) sparse_weights = sparse_tensor.SparseTensor(inp_indices, weight_vals, [num_rows, 1]) np_out = np.bincount(inp_vals, minlength=size, weights=weight_vals) self.assertAllEqual( np_out, self.evaluate(bincount_ops.bincount( sparse_inp, sparse_weights, axis=0))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_sparse_input_all_binary(self, dtype): np.random.seed(42) num_rows = 128 size = 10 n_elems = 4096 inp_indices = np.random.randint(0, num_rows, (n_elems, 1)) inp_indices = np.concatenate([inp_indices, np.zeros((n_elems, 1))], axis=1) inp_vals = np.random.randint(0, size, (n_elems,), dtype=dtype) sparse_inp = sparse_tensor.SparseTensor(inp_indices, inp_vals, [num_rows, 1]) np_out = np.ones((size,)) self.assertAllEqual( np_out, self.evaluate(bincount_ops.bincount(sparse_inp, binary_output=True))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_sparse_input_col_reduce_count(self, dtype): num_rows = 128 num_cols = 27 size = 100 np.random.seed(42) inp = np.random.randint(0, size, (num_rows, num_cols), dtype=dtype) np_out = np.reshape( np.concatenate( [np.bincount(inp[j, :], minlength=size) for j in range(num_rows)], axis=0), (num_rows, size)) # from_dense will filter out 0s. inp = inp + 1 # from_dense will cause OOM in GPU. with ops.device("/CPU:0"): inp_sparse = sparse_ops.from_dense(inp) inp_sparse = sparse_tensor.SparseTensor(inp_sparse.indices, inp_sparse.values - 1, inp_sparse.dense_shape) self.assertAllEqual( np_out, self.evaluate(bincount_ops.bincount(arr=inp_sparse, axis=-1))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_sparse_input_col_reduce_binary(self, dtype): num_rows = 128 num_cols = 27 size = 100 np.random.seed(42) inp = np.random.randint(0, size, (num_rows, num_cols), dtype=dtype) np_out = np.reshape( np.concatenate([ np.where(np.bincount(inp[j, :], minlength=size) > 0, 1, 0) for j in range(num_rows) ], axis=0), (num_rows, size)) # from_dense will filter out 0s. inp = inp + 1 # from_dense will cause OOM in GPU. with ops.device("/CPU:0"): inp_sparse = sparse_ops.from_dense(inp) inp_sparse = sparse_tensor.SparseTensor(inp_sparse.indices, inp_sparse.values - 1, inp_sparse.dense_shape) self.assertAllEqual( np_out, self.evaluate( bincount_ops.bincount(arr=inp_sparse, axis=-1, binary_output=True))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_ragged_input_count(self, dtype): x = ragged_factory_ops.constant([[], [], [3, 0, 1], [], [5, 0, 4, 4]], dtype) # pyformat: disable expected_output = [ [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [1, 1, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 2, 1]] # pyformat: enable self.assertAllEqual(expected_output, self.evaluate(bincount_ops.bincount(arr=x, axis=-1))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_ragged_input_binary(self, dtype): x = ragged_factory_ops.constant([[], [], [3, 0, 1], [], [5, 0, 4, 4]]) # pyformat: disable expected_output = [ [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [1, 1, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 1, 1]] # pyformat: enable self.assertAllEqual( expected_output, self.evaluate( bincount_ops.bincount(arr=x, axis=-1, binary_output=True))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_ragged_input_count_with_weights(self, dtype): x = ragged_factory_ops.constant([[], [], [3, 0, 1], [], [5, 0, 4, 4]]) weights = ragged_factory_ops.constant([[], [], [.1, .2, .3], [], [.2, .5, .6, .3]]) # pyformat: disable expected_output = [ [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [.2, .3, 0, .1, 0, 0], [0, 0, 0, 0, 0, 0], [.5, 0, 0, 0, .9, .2]] # pyformat: enable self.assertAllClose( expected_output, self.evaluate(bincount_ops.bincount(arr=x, weights=weights, axis=-1))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_ragged_input_count_np(self, dtype): np.random.seed(42) num_rows = 128 num_cols = 27 size = 1000 inp = np.random.randint(0, size, (num_rows, num_cols), dtype=dtype) np_out = np.reshape( np.concatenate( [np.bincount(inp[j, :], minlength=size) for j in range(num_rows)], axis=0), (num_rows, size)) x = ragged_tensor.RaggedTensor.from_tensor(inp) self.assertAllEqual( np_out, self.evaluate(bincount_ops.bincount(arr=x, minlength=size, axis=-1))) @parameterized.parameters([{ "dtype": np.int32, }, { "dtype": np.int64, }]) def test_ragged_input_count_np_with_weights(self, dtype): np.random.seed(42) num_rows = 128 num_cols = 27 size = 1000 inp = np.random.randint(0, size, (num_rows, num_cols), dtype=dtype) np_weight = np.random.random((num_rows, num_cols)) np_out = np.reshape( np.concatenate([ np.bincount(inp[j, :], weights=np_weight[j, :], minlength=size) for j in range(num_rows) ], axis=0), (num_rows, size)) x = ragged_tensor.RaggedTensor.from_tensor(inp) weights = ragged_tensor.RaggedTensor.from_tensor(np_weight) self.assertAllEqual( np_out, self.evaluate( bincount_ops.bincount( arr=x, weights=weights, minlength=size, axis=-1))) class TestSparseCountFailureModes(test.TestCase): def test_dense_input_sparse_weights_fails(self): x = np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32) weights = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) with self.assertRaisesRegex(ValueError, "must be a tf.Tensor"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_dense_input_ragged_weights_fails(self): x = np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32) weights = ragged_factory_ops.constant([[6, 0.5, 2], [14], [10, 0.25, 5, 3]]) with self.assertRaisesRegex(ValueError, "must be a tf.Tensor"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_dense_input_wrong_shape_fails(self): x = np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32) weights = np.array([[3, 2], [5, 4], [4, 3]]) # Note: Eager mode and graph mode throw different errors here. Graph mode # will fail with a ValueError from the shape checking logic, while Eager # will fail with an InvalidArgumentError from the kernel itself. if context.executing_eagerly(): with self.assertRaisesRegex(errors.InvalidArgumentError, "must have the same shape"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) else: with self.assertRaisesRegex(ValueError, "both shapes must be equal"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_sparse_input_dense_weights_fails(self): x = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) weights = np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32) with self.assertRaisesRegex(ValueError, "must be a SparseTensor"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_sparse_input_ragged_weights_fails(self): x = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) weights = ragged_factory_ops.constant([[6, 0.5, 2], [14], [10, 0.25, 5, 3]]) with self.assertRaisesRegex(ValueError, "must be a SparseTensor"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_sparse_input_wrong_indices_fails(self): x = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) weights = sparse_ops.from_dense( np.array([[3, 1, 0, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) with self.assertRaisesRegex(errors.InvalidArgumentError, "must have the same indices"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_sparse_input_too_many_indices_fails(self): x = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) weights = sparse_ops.from_dense( np.array([[3, 1, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) with self.assertRaisesRegex(errors.InvalidArgumentError, "Incompatible shapes"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_sparse_input_wrong_shape_fails(self): x = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) weights = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4], [0, 0, 0, 0]], dtype=np.int32)) with self.assertRaisesRegex(errors.InvalidArgumentError, "must have the same dense shape"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_ragged_input_dense_weights_fails(self): x = ragged_factory_ops.constant([[6, 1, 2], [14], [10, 1, 5, 3]]) weights = np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32) with self.assertRaisesRegex(ValueError, "must be a RaggedTensor"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_ragged_input_sparse_weights_fails(self): x = ragged_factory_ops.constant([[6, 1, 2], [14], [10, 1, 5, 3]]) weights = sparse_ops.from_dense( np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32)) with self.assertRaisesRegex(ValueError, "must be a RaggedTensor"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) def test_ragged_input_different_shape_fails(self): x = ragged_factory_ops.constant([[6, 1, 2], [14], [10, 1, 5, 3]]) weights = ragged_factory_ops.constant([[6, 0.5, 2], [], [10, 0.25, 5, 3]]) with self.assertRaisesRegex(errors.InvalidArgumentError, "must have the same row splits"): self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1)) @test_util.run_all_in_graph_and_eager_modes @test_util.disable_tfrt class RawOpsTest(test.TestCase, parameterized.TestCase): def testSparseCountSparseOutputBadIndicesShape(self): indices = [[[0], [0]], [[0], [1]], [[1], [0]], [[1], [2]]] values = [1, 1, 1, 10] weights = [1, 2, 4, 6] dense_shape = [2, 3] with self.assertRaisesRegex(errors.InvalidArgumentError, "Input indices must be a 2-dimensional tensor"): self.evaluate( gen_count_ops.SparseCountSparseOutput( indices=indices, values=values, dense_shape=dense_shape, weights=weights, binary_output=False)) def testSparseCountSparseOutputBadWeightsShape(self): indices = [[0, 0], [0, 1], [1, 0], [1, 2]] values = [1, 1, 1, 10] weights = [1, 2, 4] dense_shape = [2, 3] with self.assertRaisesRegex(errors.InvalidArgumentError, "Weights and values must have the same shape"): self.evaluate( gen_count_ops.SparseCountSparseOutput( indices=indices, values=values, dense_shape=dense_shape, weights=weights, binary_output=False)) def testSparseCountSparseOutputBadNumberOfValues(self): indices = [[0, 0], [0, 1], [1, 0]] values = [1, 1, 1, 10] weights = [1, 2, 4, 6] dense_shape = [2, 3] with self.assertRaisesRegex( errors.InvalidArgumentError, "Number of values must match first dimension of indices"): self.evaluate( gen_count_ops.SparseCountSparseOutput( indices=indices, values=values, dense_shape=dense_shape, weights=weights, binary_output=False)) def testRaggedCountSparseOutput(self): splits = [0, 4, 7] values = [1, 1, 2, 1, 2, 10, 5] weights = [1, 2, 3, 4, 5, 6, 7] output_indices, output_values, output_shape = self.evaluate( gen_count_ops.RaggedCountSparseOutput( splits=splits, values=values, weights=weights, binary_output=False)) self.assertAllEqual([[0, 1], [0, 2], [1, 2], [1, 5], [1, 10]], output_indices) self.assertAllEqual([7, 3, 5, 7, 6], output_values) self.assertAllEqual([2, 11], output_shape) def testRaggedCountSparseOutputBadWeightsShape(self): splits = [0, 4, 7] values = [1, 1, 2, 1, 2, 10, 5] weights = [1, 2, 3, 4, 5, 6] with self.assertRaisesRegex(errors.InvalidArgumentError, "Weights and values must have the same shape"): self.evaluate( gen_count_ops.RaggedCountSparseOutput( splits=splits, values=values, weights=weights, binary_output=False)) def testRaggedCountSparseOutputEmptySplits(self): splits = [] values = [1, 1, 2, 1, 2, 10, 5] weights = [1, 2, 3, 4, 5, 6, 7] with self.assertRaisesRegex( errors.InvalidArgumentError, "Must provide at least 2 elements for the splits argument"): self.evaluate( gen_count_ops.RaggedCountSparseOutput( splits=splits, values=values, weights=weights, binary_output=False)) def testRaggedCountSparseOutputBadSplitsStart(self): splits = [1, 7] values = [1, 1, 2, 1, 2, 10, 5] weights = [1, 2, 3, 4, 5, 6, 7] with self.assertRaisesRegex(errors.InvalidArgumentError, "Splits must start with 0"): self.evaluate( gen_count_ops.RaggedCountSparseOutput( splits=splits, values=values, weights=weights, binary_output=False)) def testRaggedCountSparseOutputBadSplitsEnd(self): splits = [0, 5] values = [1, 1, 2, 1, 2, 10, 5] weights = [1, 2, 3, 4, 5, 6, 7] with self.assertRaisesRegex(errors.InvalidArgumentError, "Splits must end with the number of values"): self.evaluate( gen_count_ops.RaggedCountSparseOutput( splits=splits, values=values, weights=weights, binary_output=False)) if __name__ == "__main__": test.main()
null
181
CWE-787
CVE-2020-15205
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <locale> #include <string> #include "absl/strings/ascii.h" #include "absl/strings/str_cat.h" #include "tensorflow/core/framework/op_kernel.h" namespace tensorflow { namespace text { namespace { template <typename SPLITS_TYPE> class StringNGramsOp : public tensorflow::OpKernel { public: explicit StringNGramsOp(tensorflow::OpKernelConstruction* context) : tensorflow::OpKernel(context) { OP_REQUIRES_OK(context, context->GetAttr("separator", &separator_)); OP_REQUIRES_OK(context, context->GetAttr("ngram_widths", &ngram_widths_)); OP_REQUIRES_OK(context, context->GetAttr("left_pad", &left_pad_)); OP_REQUIRES_OK(context, context->GetAttr("right_pad", &right_pad_)); OP_REQUIRES_OK(context, context->GetAttr("pad_width", &pad_width_)); OP_REQUIRES_OK(context, context->GetAttr("preserve_short_sequences", &preserve_short_)); } int get_pad_width(const int ngram_width) const { // Ngrams can be padded with either a fixed pad width or a dynamic pad // width depending on the 'pad_width' arg, but in no case should the padding // ever be wider than 'ngram_width' - 1. return std::min(pad_width_ < 0 ? ngram_width - 1 : pad_width_, ngram_width - 1); } int get_num_ngrams(const int length, const int ngram_width) const { int pad_width = get_pad_width(ngram_width); return std::max(0, ((length + 2 * pad_width) - ngram_width) + 1); } void Compute(tensorflow::OpKernelContext* context) override { const tensorflow::Tensor* data; OP_REQUIRES_OK(context, context->input("data", &data)); const auto& input_data = data->flat<tstring>().data(); const tensorflow::Tensor* splits; OP_REQUIRES_OK(context, context->input("data_splits", &splits)); const auto& splits_vec = splits->flat<SPLITS_TYPE>(); int num_batch_items = splits_vec.size() - 1; tensorflow::Tensor* ngrams_splits; OP_REQUIRES_OK( context, context->allocate_output(1, splits->shape(), &ngrams_splits)); auto ngrams_splits_data = ngrams_splits->flat<SPLITS_TYPE>().data(); // If there is no data or size, return an empty RT. if (data->flat<tstring>().size() == 0 || splits_vec.size() == 0) { tensorflow::Tensor* empty; OP_REQUIRES_OK(context, context->allocate_output(0, data->shape(), &empty)); for (int i = 0; i <= num_batch_items; ++i) { ngrams_splits_data[i] = 0; } return; } ngrams_splits_data[0] = 0; for (int i = 1; i <= num_batch_items; ++i) { int length = splits_vec(i) - splits_vec(i - 1); int num_ngrams = 0; for (int ngram_width : ngram_widths_) num_ngrams += get_num_ngrams(length, ngram_width); if (preserve_short_ && length > 0 && num_ngrams == 0) { num_ngrams = 1; } ngrams_splits_data[i] = ngrams_splits_data[i - 1] + num_ngrams; } tensorflow::Tensor* ngrams; OP_REQUIRES_OK( context, context->allocate_output( 0, TensorShape({ngrams_splits_data[num_batch_items]}), &ngrams)); auto ngrams_data = ngrams->flat<tstring>().data(); for (int i = 0; i < num_batch_items; ++i) { auto data_start = &input_data[splits_vec(i)]; int output_start_idx = ngrams_splits_data[i]; for (int ngram_width : ngram_widths_) { auto output_start = &ngrams_data[output_start_idx]; int length = splits_vec(i + 1) - splits_vec(i); int num_ngrams = get_num_ngrams(length, ngram_width); CreateNgrams(data_start, output_start, num_ngrams, ngram_width); output_start_idx += num_ngrams; } // If we're preserving short sequences, check to see if no sequence was // generated by comparing the current output start idx to the original // one (ngram_splits_data). If no ngrams were generated, then they will // be equal (since we increment output_start_idx by num_ngrams every // time we create a set of ngrams.) if (preserve_short_ && output_start_idx == ngrams_splits_data[i]) { int data_length = splits_vec(i + 1) - splits_vec(i); // One legitimate reason to not have any ngrams when preserve_short_ // is true is if the sequence itself is empty. In that case, move on. if (data_length == 0) { continue; } // We don't have to worry about dynamic padding sizes here: if padding // was dynamic, every sequence would have had sufficient padding to // generate at least one ngram. int ngram_width = data_length + 2 * pad_width_; auto output_start = &ngrams_data[output_start_idx]; int num_ngrams = 1; CreateNgrams(data_start, output_start, num_ngrams, ngram_width); } } } void CreateNgrams(const tstring* data, tstring* output, int num_ngrams, int ngram_width) const { for (int ngram_index = 0; ngram_index < num_ngrams; ++ngram_index) { int pad_width = get_pad_width(ngram_width); int left_padding = std::max(0, pad_width - ngram_index); int right_padding = std::max(0, pad_width - (num_ngrams - (ngram_index + 1))); int num_tokens = ngram_width - (left_padding + right_padding); int data_start_index = left_padding > 0 ? 0 : ngram_index - pad_width; // Calculate the total expected size of the ngram so we can reserve the // correct amount of space in the string. int ngram_size = 0; // Size of the left padding. ngram_size += left_padding * left_pad_.length(); // Size of the tokens. for (int n = 0; n < num_tokens; ++n) { ngram_size += data[data_start_index + n].length(); } // Size of the right padding. ngram_size += right_padding * right_pad_.length(); // Size of the separators. int num_separators = left_padding + right_padding + num_tokens - 1; ngram_size += num_separators * separator_.length(); // Build the ngram. tstring* ngram = &output[ngram_index]; ngram->reserve(ngram_size); for (int n = 0; n < left_padding; ++n) { ngram->append(left_pad_); ngram->append(separator_); } for (int n = 0; n < num_tokens - 1; ++n) { ngram->append(data[data_start_index + n]); ngram->append(separator_); } ngram->append(data[data_start_index + num_tokens - 1]); for (int n = 0; n < right_padding; ++n) { ngram->append(separator_); ngram->append(right_pad_); } // In debug mode only: validate that we've reserved enough space for the // ngram. DCHECK_EQ(ngram_size, ngram->size()); } } string separator_; string left_pad_; string right_pad_; bool use_pad_; bool extend_pad_; bool preserve_short_; std::vector<int> ngram_widths_; int pad_width_; }; } // namespace REGISTER_KERNEL_BUILDER(Name("StringNGrams") .Device(tensorflow::DEVICE_CPU) .TypeConstraint<int32>("Tsplits"), StringNGramsOp<int32>); REGISTER_KERNEL_BUILDER(Name("StringNGrams") .Device(tensorflow::DEVICE_CPU) .TypeConstraint<int64>("Tsplits"), StringNGramsOp<int64>); } // namespace text } // namespace tensorflow
null
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <locale> #include <string> #include "absl/strings/ascii.h" #include "absl/strings/str_cat.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/platform/errors.h" namespace tensorflow { namespace text { namespace { template <typename SPLITS_TYPE> class StringNGramsOp : public tensorflow::OpKernel { public: explicit StringNGramsOp(tensorflow::OpKernelConstruction* context) : tensorflow::OpKernel(context) { OP_REQUIRES_OK(context, context->GetAttr("separator", &separator_)); OP_REQUIRES_OK(context, context->GetAttr("ngram_widths", &ngram_widths_)); OP_REQUIRES_OK(context, context->GetAttr("left_pad", &left_pad_)); OP_REQUIRES_OK(context, context->GetAttr("right_pad", &right_pad_)); OP_REQUIRES_OK(context, context->GetAttr("pad_width", &pad_width_)); OP_REQUIRES_OK(context, context->GetAttr("preserve_short_sequences", &preserve_short_)); } int get_pad_width(const int ngram_width) const { // Ngrams can be padded with either a fixed pad width or a dynamic pad // width depending on the 'pad_width' arg, but in no case should the padding // ever be wider than 'ngram_width' - 1. return std::min(pad_width_ < 0 ? ngram_width - 1 : pad_width_, ngram_width - 1); } int get_num_ngrams(const int length, const int ngram_width) const { int pad_width = get_pad_width(ngram_width); return std::max(0, ((length + 2 * pad_width) - ngram_width) + 1); } void Compute(tensorflow::OpKernelContext* context) override { const tensorflow::Tensor* data; OP_REQUIRES_OK(context, context->input("data", &data)); const auto& input_data = data->flat<tstring>().data(); const tensorflow::Tensor* splits; OP_REQUIRES_OK(context, context->input("data_splits", &splits)); const auto& splits_vec = splits->flat<SPLITS_TYPE>(); // Validate that the splits are valid indices into data const int input_data_size = data->flat<tstring>().size(); const int splits_vec_size = splits_vec.size(); for (int i = 0; i < splits_vec_size; ++i) { bool valid_splits = splits_vec(i) >= 0; valid_splits = valid_splits && (splits_vec(i) <= input_data_size); OP_REQUIRES( context, valid_splits, errors::InvalidArgument("Invalid split value ", splits_vec(i), ", must be in [0,", input_data_size, "]")); } int num_batch_items = splits_vec.size() - 1; tensorflow::Tensor* ngrams_splits; OP_REQUIRES_OK( context, context->allocate_output(1, splits->shape(), &ngrams_splits)); auto ngrams_splits_data = ngrams_splits->flat<SPLITS_TYPE>().data(); // If there is no data or size, return an empty RT. if (data->flat<tstring>().size() == 0 || splits_vec.size() == 0) { tensorflow::Tensor* empty; OP_REQUIRES_OK(context, context->allocate_output(0, data->shape(), &empty)); for (int i = 0; i <= num_batch_items; ++i) { ngrams_splits_data[i] = 0; } return; } ngrams_splits_data[0] = 0; for (int i = 1; i <= num_batch_items; ++i) { int length = splits_vec(i) - splits_vec(i - 1); int num_ngrams = 0; for (int ngram_width : ngram_widths_) num_ngrams += get_num_ngrams(length, ngram_width); if (preserve_short_ && length > 0 && num_ngrams == 0) { num_ngrams = 1; } ngrams_splits_data[i] = ngrams_splits_data[i - 1] + num_ngrams; } tensorflow::Tensor* ngrams; OP_REQUIRES_OK( context, context->allocate_output( 0, TensorShape({ngrams_splits_data[num_batch_items]}), &ngrams)); auto ngrams_data = ngrams->flat<tstring>().data(); for (int i = 0; i < num_batch_items; ++i) { auto data_start = &input_data[splits_vec(i)]; int output_start_idx = ngrams_splits_data[i]; for (int ngram_width : ngram_widths_) { auto output_start = &ngrams_data[output_start_idx]; int length = splits_vec(i + 1) - splits_vec(i); int num_ngrams = get_num_ngrams(length, ngram_width); CreateNgrams(data_start, output_start, num_ngrams, ngram_width); output_start_idx += num_ngrams; } // If we're preserving short sequences, check to see if no sequence was // generated by comparing the current output start idx to the original // one (ngram_splits_data). If no ngrams were generated, then they will // be equal (since we increment output_start_idx by num_ngrams every // time we create a set of ngrams.) if (preserve_short_ && output_start_idx == ngrams_splits_data[i]) { int data_length = splits_vec(i + 1) - splits_vec(i); // One legitimate reason to not have any ngrams when preserve_short_ // is true is if the sequence itself is empty. In that case, move on. if (data_length == 0) { continue; } // We don't have to worry about dynamic padding sizes here: if padding // was dynamic, every sequence would have had sufficient padding to // generate at least one ngram. int ngram_width = data_length + 2 * pad_width_; auto output_start = &ngrams_data[output_start_idx]; int num_ngrams = 1; CreateNgrams(data_start, output_start, num_ngrams, ngram_width); } } } void CreateNgrams(const tstring* data, tstring* output, int num_ngrams, int ngram_width) const { for (int ngram_index = 0; ngram_index < num_ngrams; ++ngram_index) { int pad_width = get_pad_width(ngram_width); int left_padding = std::max(0, pad_width - ngram_index); int right_padding = std::max(0, pad_width - (num_ngrams - (ngram_index + 1))); int num_tokens = ngram_width - (left_padding + right_padding); int data_start_index = left_padding > 0 ? 0 : ngram_index - pad_width; // Calculate the total expected size of the ngram so we can reserve the // correct amount of space in the string. int ngram_size = 0; // Size of the left padding. ngram_size += left_padding * left_pad_.length(); // Size of the tokens. for (int n = 0; n < num_tokens; ++n) { ngram_size += data[data_start_index + n].length(); } // Size of the right padding. ngram_size += right_padding * right_pad_.length(); // Size of the separators. int num_separators = left_padding + right_padding + num_tokens - 1; ngram_size += num_separators * separator_.length(); // Build the ngram. tstring* ngram = &output[ngram_index]; ngram->reserve(ngram_size); for (int n = 0; n < left_padding; ++n) { ngram->append(left_pad_); ngram->append(separator_); } for (int n = 0; n < num_tokens - 1; ++n) { ngram->append(data[data_start_index + n]); ngram->append(separator_); } ngram->append(data[data_start_index + num_tokens - 1]); for (int n = 0; n < right_padding; ++n) { ngram->append(separator_); ngram->append(right_pad_); } // In debug mode only: validate that we've reserved enough space for the // ngram. DCHECK_EQ(ngram_size, ngram->size()); } } string separator_; string left_pad_; string right_pad_; bool use_pad_; bool extend_pad_; bool preserve_short_; std::vector<int> ngram_widths_; int pad_width_; }; } // namespace REGISTER_KERNEL_BUILDER(Name("StringNGrams") .Device(tensorflow::DEVICE_CPU) .TypeConstraint<int32>("Tsplits"), StringNGramsOp<int32>); REGISTER_KERNEL_BUILDER(Name("StringNGrams") .Device(tensorflow::DEVICE_CPU) .TypeConstraint<int64>("Tsplits"), StringNGramsOp<int64>); } // namespace text } // namespace tensorflow
null
182
CWE-787
CVE-2020-15207
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_REDUCE_H_ #define TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_REDUCE_H_ #include "ruy/profiler/instrumentation.h" // from @ruy #include "tensorflow/lite/kernels/internal/common.h" #include "tensorflow/lite/kernels/internal/cppmath.h" #include "tensorflow/lite/kernels/internal/max.h" #include "tensorflow/lite/kernels/internal/min.h" #include "tensorflow/lite/kernels/internal/quantization_util.h" #include "tensorflow/lite/kernels/internal/types.h" namespace tflite { namespace reference_ops { // A generic reduce method that can be used for reduce_sum, reduce_mean, etc. // This method iterates through input data and reduce elements along the // dimensions given in axis. template <typename In, typename Out> inline bool Reduce(const In* input_data, const int* input_dims, const int* output_dims, const int input_num_dims, const int output_num_dims, const int* axis, const int num_axis, int* input_iter, Out reducer(const Out current, const In in), Out* output_data) { // Reset input iterator. for (int idx = 0; idx < input_num_dims; ++idx) { input_iter[idx] = 0; } // Iterate through input_data. do { size_t input_offset = ReducedOutputOffset(input_num_dims, input_dims, input_iter, 0, nullptr); size_t output_offset = ReducedOutputOffset(input_num_dims, input_dims, input_iter, num_axis, axis); output_data[output_offset] = reducer(output_data[output_offset], input_data[input_offset]); } while (NextIndex(input_num_dims, input_dims, input_iter)); return true; } // This method parses the input 'axis' to remove duplicates and handle negative // values, and returns a valid 'out_axis' inline bool ResolveAxis(const int num_dims, const int* axis, const int64_t num_axis, int* out_axis, int* out_num_axis) { *out_num_axis = 0; // Just in case. // Short-circuit axis resolution for scalars; the axis will go unused. if (num_dims == 0) { return true; } // o(n^2) is fine since out_num_axis should be really small, mostly <= 4 for (int64_t idx = 0; idx < num_axis; ++idx) { // Handle negative index. A positive index 'p_idx' can be represented as a // negative index 'n_idx' as: n_idx = p_idx-num_dims // eg: For num_dims=3, [0, 1, 2] is the same as [-3, -2, -1] */ int current = axis[idx] < 0 ? (axis[idx] + num_dims) : axis[idx]; TFLITE_DCHECK(current >= 0 && current < num_dims); bool is_dup = false; for (int j = 0; j < *out_num_axis; ++j) { if (out_axis[j] == current) { is_dup = true; break; } } if (!is_dup) { out_axis[*out_num_axis] = current; *out_num_axis += 1; } } return true; } // This method expects that output_data has been initialized. template <typename In, typename Out> inline bool ReduceSumImpl(const In* input_data, const int* input_dims, const int* output_dims, const int input_num_dims, const int output_num_dims, const int* axis, const int num_axis, int* input_iter, Out* output_data) { auto reducer = [](const Out current, const In in) -> Out { const Out actual_in = static_cast<Out>(in); return current + actual_in; }; return Reduce<In, Out>(input_data, input_dims, output_dims, input_num_dims, output_num_dims, axis, num_axis, input_iter, reducer, output_data); } template <typename T> inline bool InitTensorDataForReduce(const int* dims, const int num_dims, const T init_value, T* data) { size_t num_elements = 1; for (int idx = 0; idx < num_dims; ++idx) { size_t current = static_cast<size_t>(dims[idx]); // Overflow prevention. if (num_elements > std::numeric_limits<size_t>::max() / current) { return false; } num_elements *= current; } for (size_t idx = 0; idx < num_elements; ++idx) { data[idx] = init_value; } return true; } // Computes the generic value (i.e., sum/max/min/prod) of elements across // dimensions given in axis. It needs to pass in init_value and reducer. template <typename T> inline bool ReduceGeneric(const T* input_data, const int* input_dims, const int input_num_dims, T* output_data, const int* output_dims, const int output_num_dims, const int* axis, const int64_t num_axis_dimensions, bool keep_dims, int* temp_index, int* resolved_axis, T init_value, T reducer(const T current, const T in)) { // Reset output data. if (!InitTensorDataForReduce(output_dims, output_num_dims, init_value, output_data)) { return false; } // Resolve axis. int num_resolved_axis = 0; if (!ResolveAxis(input_num_dims, axis, num_axis_dimensions, resolved_axis, &num_resolved_axis)) { return false; } return Reduce<T, T>(input_data, input_dims, output_dims, input_num_dims, output_num_dims, resolved_axis, num_resolved_axis, temp_index, reducer, output_data); } // Computes the mean of elements across dimensions given in axis. // It does so in two stages, first calculates the sum of elements along the axis // then divides it by the number of element in axis. template <typename T, typename U> inline bool Mean(const T* input_data, const int* input_dims, const int input_num_dims, T* output_data, const int* output_dims, const int output_num_dims, const int* axis, const int num_axis_dimensions, bool keep_dims, int* temp_index, int* resolved_axis, U* temp_sum) { ruy::profiler::ScopeLabel label("Mean"); // Reset output data. size_t num_outputs = 1; for (int idx = 0; idx < output_num_dims; ++idx) { size_t current = static_cast<size_t>(output_dims[idx]); // Overflow prevention. if (num_outputs > std::numeric_limits<size_t>::max() / current) { return false; } num_outputs *= current; } for (size_t idx = 0; idx < num_outputs; ++idx) { output_data[idx] = T(); temp_sum[idx] = U(); } // Resolve axis. int num_resolved_axis = 0; if (!ResolveAxis(input_num_dims, axis, num_axis_dimensions, resolved_axis, &num_resolved_axis)) { return false; } if (!ReduceSumImpl<T, U>(input_data, input_dims, output_dims, input_num_dims, output_num_dims, resolved_axis, num_resolved_axis, temp_index, temp_sum)) { return false; } // Calculate mean by dividing output_data by num of aggregated element. size_t num_elements_in_axis = 1; for (int idx = 0; idx < num_resolved_axis; ++idx) { size_t current = static_cast<size_t>(input_dims[resolved_axis[idx]]); // Overflow prevention. if (current > (std::numeric_limits<size_t>::max() / num_elements_in_axis)) { return false; } num_elements_in_axis *= current; } if (num_elements_in_axis > 0) { for (size_t idx = 0; idx < num_outputs; ++idx) { output_data[idx] = static_cast<T>(temp_sum[idx] / static_cast<U>(num_elements_in_axis)); } } return true; } template <typename T> inline void Mean(const tflite::MeanParams& op_params, const RuntimeShape& unextended_input_shape, const T* input_data, const RuntimeShape& unextended_output_shape, T* output_data) { ruy::profiler::ScopeLabel label("Mean4D"); // Current implementation only supports dimension equals 4 and simultaneous // reduction over width and height. TFLITE_CHECK_EQ(unextended_input_shape.DimensionsCount(), 4); TFLITE_CHECK_LE(unextended_output_shape.DimensionsCount(), 4); const RuntimeShape input_shape = RuntimeShape::ExtendedShape(4, unextended_input_shape); const RuntimeShape output_shape = RuntimeShape::ExtendedShape(4, unextended_output_shape); const int output_batch = output_shape.Dims(0); const int output_height = output_shape.Dims(1); const int output_width = output_shape.Dims(2); const int output_depth = output_shape.Dims(3); const int input_height = input_shape.Dims(1); const int input_width = input_shape.Dims(2); TFLITE_CHECK_EQ(op_params.axis_count, 2); TFLITE_CHECK((op_params.axis[0] == 1 && op_params.axis[1] == 2) || (op_params.axis[0] == 2 && op_params.axis[1] == 1)); TFLITE_CHECK_EQ(output_height, 1); TFLITE_CHECK_EQ(output_width, 1); for (int out_b = 0; out_b < output_batch; ++out_b) { for (int out_d = 0; out_d < output_depth; ++out_d) { float value = 0; for (int in_h = 0; in_h < input_height; ++in_h) { for (int in_w = 0; in_w < input_width; ++in_w) { value += input_data[Offset(input_shape, out_b, in_h, in_w, out_d)]; } } output_data[Offset(output_shape, out_b, 0, 0, out_d)] = value / (input_width * input_height); } } } inline void Mean(const tflite::MeanParams& op_params, const RuntimeShape& unextended_input_shape, const uint8_t* input_data, int32_t input_zero_point, float input_scale, const RuntimeShape& unextended_output_shape, uint8_t* output_data, int32_t output_zero_point, float output_scale) { ruy::profiler::ScopeLabel label("Mean4D/Uint8"); // Current implementation only supports dimension equals 4 and simultaneous // reduction over width and height. TFLITE_CHECK_EQ(unextended_input_shape.DimensionsCount(), 4); TFLITE_CHECK_LE(unextended_output_shape.DimensionsCount(), 4); const RuntimeShape input_shape = RuntimeShape::ExtendedShape(4, unextended_input_shape); const RuntimeShape output_shape = RuntimeShape::ExtendedShape(4, unextended_output_shape); const int output_batch = output_shape.Dims(0); const int output_height = output_shape.Dims(1); const int output_width = output_shape.Dims(2); const int output_depth = output_shape.Dims(3); const int input_height = input_shape.Dims(1); const int input_width = input_shape.Dims(2); const float num_elements_in_axis = input_width * input_height; TFLITE_CHECK_EQ(op_params.axis_count, 2); TFLITE_CHECK((op_params.axis[0] == 1 && op_params.axis[1] == 2) || (op_params.axis[0] == 2 && op_params.axis[1] == 1)); TFLITE_CHECK_EQ(output_height, 1); TFLITE_CHECK_EQ(output_width, 1); constexpr int32_t kMinValue = std::numeric_limits<uint8_t>::min(); constexpr int32_t kMaxValue = std::numeric_limits<uint8_t>::max(); int32_t bias = output_zero_point - static_cast<int32_t>(input_zero_point * input_scale / output_scale); double real_scale = static_cast<double>(input_scale / (num_elements_in_axis * output_scale)); int32_t multiplier; int shift; QuantizeMultiplier(real_scale, &multiplier, &shift); for (int out_b = 0; out_b < output_batch; ++out_b) { for (int out_d = 0; out_d < output_depth; ++out_d) { int32_t acc = 0; for (int in_h = 0; in_h < input_height; ++in_h) { for (int in_w = 0; in_w < input_width; ++in_w) { acc += input_data[Offset(input_shape, out_b, in_h, in_w, out_d)]; } } acc = MultiplyByQuantizedMultiplier(acc, multiplier, shift); acc += bias; acc = std::min(std::max(acc, kMinValue), kMaxValue); output_data[Offset(output_shape, out_b, 0, 0, out_d)] = static_cast<uint8_t>(acc); } } } // Computes the mean of elements across dimensions given in axis. // It does so in two stages, first calculates the sum of elements along the axis // then divides it by the number of element in axis for quantized values. template <typename T, typename U> inline bool QuantizedMeanOrSum(const T* input_data, int32_t input_zero_point, float input_scale, const int* input_dims, const int input_num_dims, T* output_data, int32_t output_zero_point, float output_scale, const int* output_dims, const int output_num_dims, const int* axis, const int num_axis_dimensions, bool keep_dims, int* temp_index, int* resolved_axis, U* temp_sum, bool compute_sum) { const bool uint8_case = std::is_same<T, uint8_t>::value; const bool int16_case = std::is_same<T, int16_t>::value; if (uint8_case) { ruy::profiler::ScopeLabel label(compute_sum ? "Sum/Uint8" : "Mean/Uint8"); } else if (int16_case) { ruy::profiler::ScopeLabel label(compute_sum ? "Sum/Int16" : "Mean/Int16"); } else { ruy::profiler::ScopeLabel label(compute_sum ? "Sum/Int8" : "Mean/Int8"); } // Reset output data. size_t num_outputs = 1; for (int idx = 0; idx < output_num_dims; ++idx) { size_t current = static_cast<size_t>(output_dims[idx]); // Overflow prevention. if (num_outputs > std::numeric_limits<size_t>::max() / current) { return false; } num_outputs *= current; } for (size_t idx = 0; idx < num_outputs; ++idx) { output_data[idx] = T(); temp_sum[idx] = U(); } // Resolve axis. int num_resolved_axis = 0; if (!ResolveAxis(input_num_dims, axis, num_axis_dimensions, resolved_axis, &num_resolved_axis)) { return false; } if (!ReduceSumImpl<T, U>(input_data, input_dims, output_dims, input_num_dims, output_num_dims, resolved_axis, num_resolved_axis, temp_index, temp_sum)) { return false; } // Calculate mean by dividing output_data by num of aggregated element. size_t num_elements_in_axis = 1; for (int idx = 0; idx < num_resolved_axis; ++idx) { size_t current = static_cast<size_t>(input_dims[resolved_axis[idx]]); // Overflow prevention. if (current > (std::numeric_limits<size_t>::max() / num_elements_in_axis)) { return false; } num_elements_in_axis *= current; } if (num_elements_in_axis > 0) { const float scale = input_scale / output_scale; if (compute_sum) { // TODO(b/116341117): Eliminate float and do this completely in 8bit. const float bias = -input_zero_point * scale * num_elements_in_axis + 0.5f; for (size_t idx = 0; idx < num_outputs; ++idx) { const U value = static_cast<U>(TfLiteRound(temp_sum[idx] * scale + bias)) + output_zero_point; output_data[idx] = static_cast<T>(value); } } else { const float bias = -input_zero_point * scale + 0.5f; for (size_t idx = 0; idx < num_outputs; ++idx) { float float_mean = static_cast<float>(temp_sum[idx]) / static_cast<float>(num_elements_in_axis); float result = TfLiteMin( TfLiteRound(float_mean * scale + bias) + output_zero_point, static_cast<float>(std::numeric_limits<T>::max())); result = TfLiteMax(result, static_cast<float>(std::numeric_limits<T>::min())); output_data[idx] = static_cast<T>(result); } } } return true; } } // namespace reference_ops } // namespace tflite #endif // TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_REDUCE_H_
null
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_REDUCE_H_ #define TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_REDUCE_H_ #include "ruy/profiler/instrumentation.h" // from @ruy #include "tensorflow/lite/kernels/internal/common.h" #include "tensorflow/lite/kernels/internal/cppmath.h" #include "tensorflow/lite/kernels/internal/max.h" #include "tensorflow/lite/kernels/internal/min.h" #include "tensorflow/lite/kernels/internal/quantization_util.h" #include "tensorflow/lite/kernels/internal/types.h" namespace tflite { namespace reference_ops { // A generic reduce method that can be used for reduce_sum, reduce_mean, etc. // This method iterates through input data and reduce elements along the // dimensions given in axis. template <typename In, typename Out> inline bool Reduce(const In* input_data, const int* input_dims, const int* output_dims, const int input_num_dims, const int output_num_dims, const int* axis, const int num_axis, int* input_iter, Out reducer(const Out current, const In in), Out* output_data) { // Reset input iterator. for (int idx = 0; idx < input_num_dims; ++idx) { input_iter[idx] = 0; } // Iterate through input_data. do { size_t input_offset = ReducedOutputOffset(input_num_dims, input_dims, input_iter, 0, nullptr); size_t output_offset = ReducedOutputOffset(input_num_dims, input_dims, input_iter, num_axis, axis); output_data[output_offset] = reducer(output_data[output_offset], input_data[input_offset]); } while (NextIndex(input_num_dims, input_dims, input_iter)); return true; } // This method parses the input 'axis' to remove duplicates and handle negative // values, and returns a valid 'out_axis' inline bool ResolveAxis(const int num_dims, const int* axis, const int64_t num_axis, int* out_axis, int* out_num_axis) { *out_num_axis = 0; // Just in case. // Short-circuit axis resolution for scalars; the axis will go unused. if (num_dims == 0) { return true; } // o(n^2) is fine since out_num_axis should be really small, mostly <= 4 for (int64_t idx = 0; idx < num_axis; ++idx) { // Handle negative index. A positive index 'p_idx' can be represented as a // negative index 'n_idx' as: n_idx = p_idx-num_dims // eg: For num_dims=3, [0, 1, 2] is the same as [-3, -2, -1] */ int current = axis[idx] < 0 ? (axis[idx] + num_dims) : axis[idx]; TFLITE_DCHECK(current >= 0 && current < num_dims); if (current < 0 || current >= num_dims) { return false; } bool is_dup = false; for (int j = 0; j < *out_num_axis; ++j) { if (out_axis[j] == current) { is_dup = true; break; } } if (!is_dup) { out_axis[*out_num_axis] = current; *out_num_axis += 1; } } return true; } // This method expects that output_data has been initialized. template <typename In, typename Out> inline bool ReduceSumImpl(const In* input_data, const int* input_dims, const int* output_dims, const int input_num_dims, const int output_num_dims, const int* axis, const int num_axis, int* input_iter, Out* output_data) { auto reducer = [](const Out current, const In in) -> Out { const Out actual_in = static_cast<Out>(in); return current + actual_in; }; return Reduce<In, Out>(input_data, input_dims, output_dims, input_num_dims, output_num_dims, axis, num_axis, input_iter, reducer, output_data); } template <typename T> inline bool InitTensorDataForReduce(const int* dims, const int num_dims, const T init_value, T* data) { size_t num_elements = 1; for (int idx = 0; idx < num_dims; ++idx) { size_t current = static_cast<size_t>(dims[idx]); // Overflow prevention. if (num_elements > std::numeric_limits<size_t>::max() / current) { return false; } num_elements *= current; } for (size_t idx = 0; idx < num_elements; ++idx) { data[idx] = init_value; } return true; } // Computes the generic value (i.e., sum/max/min/prod) of elements across // dimensions given in axis. It needs to pass in init_value and reducer. template <typename T> inline bool ReduceGeneric(const T* input_data, const int* input_dims, const int input_num_dims, T* output_data, const int* output_dims, const int output_num_dims, const int* axis, const int64_t num_axis_dimensions, bool keep_dims, int* temp_index, int* resolved_axis, T init_value, T reducer(const T current, const T in)) { // Reset output data. if (!InitTensorDataForReduce(output_dims, output_num_dims, init_value, output_data)) { return false; } // Resolve axis. int num_resolved_axis = 0; if (!ResolveAxis(input_num_dims, axis, num_axis_dimensions, resolved_axis, &num_resolved_axis)) { return false; } return Reduce<T, T>(input_data, input_dims, output_dims, input_num_dims, output_num_dims, resolved_axis, num_resolved_axis, temp_index, reducer, output_data); } // Computes the mean of elements across dimensions given in axis. // It does so in two stages, first calculates the sum of elements along the axis // then divides it by the number of element in axis. template <typename T, typename U> inline bool Mean(const T* input_data, const int* input_dims, const int input_num_dims, T* output_data, const int* output_dims, const int output_num_dims, const int* axis, const int num_axis_dimensions, bool keep_dims, int* temp_index, int* resolved_axis, U* temp_sum) { ruy::profiler::ScopeLabel label("Mean"); // Reset output data. size_t num_outputs = 1; for (int idx = 0; idx < output_num_dims; ++idx) { size_t current = static_cast<size_t>(output_dims[idx]); // Overflow prevention. if (num_outputs > std::numeric_limits<size_t>::max() / current) { return false; } num_outputs *= current; } for (size_t idx = 0; idx < num_outputs; ++idx) { output_data[idx] = T(); temp_sum[idx] = U(); } // Resolve axis. int num_resolved_axis = 0; if (!ResolveAxis(input_num_dims, axis, num_axis_dimensions, resolved_axis, &num_resolved_axis)) { return false; } if (!ReduceSumImpl<T, U>(input_data, input_dims, output_dims, input_num_dims, output_num_dims, resolved_axis, num_resolved_axis, temp_index, temp_sum)) { return false; } // Calculate mean by dividing output_data by num of aggregated element. size_t num_elements_in_axis = 1; for (int idx = 0; idx < num_resolved_axis; ++idx) { size_t current = static_cast<size_t>(input_dims[resolved_axis[idx]]); // Overflow prevention. if (current > (std::numeric_limits<size_t>::max() / num_elements_in_axis)) { return false; } num_elements_in_axis *= current; } if (num_elements_in_axis > 0) { for (size_t idx = 0; idx < num_outputs; ++idx) { output_data[idx] = static_cast<T>(temp_sum[idx] / static_cast<U>(num_elements_in_axis)); } } return true; } template <typename T> inline void Mean(const tflite::MeanParams& op_params, const RuntimeShape& unextended_input_shape, const T* input_data, const RuntimeShape& unextended_output_shape, T* output_data) { ruy::profiler::ScopeLabel label("Mean4D"); // Current implementation only supports dimension equals 4 and simultaneous // reduction over width and height. TFLITE_CHECK_EQ(unextended_input_shape.DimensionsCount(), 4); TFLITE_CHECK_LE(unextended_output_shape.DimensionsCount(), 4); const RuntimeShape input_shape = RuntimeShape::ExtendedShape(4, unextended_input_shape); const RuntimeShape output_shape = RuntimeShape::ExtendedShape(4, unextended_output_shape); const int output_batch = output_shape.Dims(0); const int output_height = output_shape.Dims(1); const int output_width = output_shape.Dims(2); const int output_depth = output_shape.Dims(3); const int input_height = input_shape.Dims(1); const int input_width = input_shape.Dims(2); TFLITE_CHECK_EQ(op_params.axis_count, 2); TFLITE_CHECK((op_params.axis[0] == 1 && op_params.axis[1] == 2) || (op_params.axis[0] == 2 && op_params.axis[1] == 1)); TFLITE_CHECK_EQ(output_height, 1); TFLITE_CHECK_EQ(output_width, 1); for (int out_b = 0; out_b < output_batch; ++out_b) { for (int out_d = 0; out_d < output_depth; ++out_d) { float value = 0; for (int in_h = 0; in_h < input_height; ++in_h) { for (int in_w = 0; in_w < input_width; ++in_w) { value += input_data[Offset(input_shape, out_b, in_h, in_w, out_d)]; } } output_data[Offset(output_shape, out_b, 0, 0, out_d)] = value / (input_width * input_height); } } } inline void Mean(const tflite::MeanParams& op_params, const RuntimeShape& unextended_input_shape, const uint8_t* input_data, int32_t input_zero_point, float input_scale, const RuntimeShape& unextended_output_shape, uint8_t* output_data, int32_t output_zero_point, float output_scale) { ruy::profiler::ScopeLabel label("Mean4D/Uint8"); // Current implementation only supports dimension equals 4 and simultaneous // reduction over width and height. TFLITE_CHECK_EQ(unextended_input_shape.DimensionsCount(), 4); TFLITE_CHECK_LE(unextended_output_shape.DimensionsCount(), 4); const RuntimeShape input_shape = RuntimeShape::ExtendedShape(4, unextended_input_shape); const RuntimeShape output_shape = RuntimeShape::ExtendedShape(4, unextended_output_shape); const int output_batch = output_shape.Dims(0); const int output_height = output_shape.Dims(1); const int output_width = output_shape.Dims(2); const int output_depth = output_shape.Dims(3); const int input_height = input_shape.Dims(1); const int input_width = input_shape.Dims(2); const float num_elements_in_axis = input_width * input_height; TFLITE_CHECK_EQ(op_params.axis_count, 2); TFLITE_CHECK((op_params.axis[0] == 1 && op_params.axis[1] == 2) || (op_params.axis[0] == 2 && op_params.axis[1] == 1)); TFLITE_CHECK_EQ(output_height, 1); TFLITE_CHECK_EQ(output_width, 1); constexpr int32_t kMinValue = std::numeric_limits<uint8_t>::min(); constexpr int32_t kMaxValue = std::numeric_limits<uint8_t>::max(); int32_t bias = output_zero_point - static_cast<int32_t>(input_zero_point * input_scale / output_scale); double real_scale = static_cast<double>(input_scale / (num_elements_in_axis * output_scale)); int32_t multiplier; int shift; QuantizeMultiplier(real_scale, &multiplier, &shift); for (int out_b = 0; out_b < output_batch; ++out_b) { for (int out_d = 0; out_d < output_depth; ++out_d) { int32_t acc = 0; for (int in_h = 0; in_h < input_height; ++in_h) { for (int in_w = 0; in_w < input_width; ++in_w) { acc += input_data[Offset(input_shape, out_b, in_h, in_w, out_d)]; } } acc = MultiplyByQuantizedMultiplier(acc, multiplier, shift); acc += bias; acc = std::min(std::max(acc, kMinValue), kMaxValue); output_data[Offset(output_shape, out_b, 0, 0, out_d)] = static_cast<uint8_t>(acc); } } } // Computes the mean of elements across dimensions given in axis. // It does so in two stages, first calculates the sum of elements along the axis // then divides it by the number of element in axis for quantized values. template <typename T, typename U> inline bool QuantizedMeanOrSum(const T* input_data, int32_t input_zero_point, float input_scale, const int* input_dims, const int input_num_dims, T* output_data, int32_t output_zero_point, float output_scale, const int* output_dims, const int output_num_dims, const int* axis, const int num_axis_dimensions, bool keep_dims, int* temp_index, int* resolved_axis, U* temp_sum, bool compute_sum) { const bool uint8_case = std::is_same<T, uint8_t>::value; const bool int16_case = std::is_same<T, int16_t>::value; if (uint8_case) { ruy::profiler::ScopeLabel label(compute_sum ? "Sum/Uint8" : "Mean/Uint8"); } else if (int16_case) { ruy::profiler::ScopeLabel label(compute_sum ? "Sum/Int16" : "Mean/Int16"); } else { ruy::profiler::ScopeLabel label(compute_sum ? "Sum/Int8" : "Mean/Int8"); } // Reset output data. size_t num_outputs = 1; for (int idx = 0; idx < output_num_dims; ++idx) { size_t current = static_cast<size_t>(output_dims[idx]); // Overflow prevention. if (num_outputs > std::numeric_limits<size_t>::max() / current) { return false; } num_outputs *= current; } for (size_t idx = 0; idx < num_outputs; ++idx) { output_data[idx] = T(); temp_sum[idx] = U(); } // Resolve axis. int num_resolved_axis = 0; if (!ResolveAxis(input_num_dims, axis, num_axis_dimensions, resolved_axis, &num_resolved_axis)) { return false; } if (!ReduceSumImpl<T, U>(input_data, input_dims, output_dims, input_num_dims, output_num_dims, resolved_axis, num_resolved_axis, temp_index, temp_sum)) { return false; } // Calculate mean by dividing output_data by num of aggregated element. size_t num_elements_in_axis = 1; for (int idx = 0; idx < num_resolved_axis; ++idx) { size_t current = static_cast<size_t>(input_dims[resolved_axis[idx]]); // Overflow prevention. if (current > (std::numeric_limits<size_t>::max() / num_elements_in_axis)) { return false; } num_elements_in_axis *= current; } if (num_elements_in_axis > 0) { const float scale = input_scale / output_scale; if (compute_sum) { // TODO(b/116341117): Eliminate float and do this completely in 8bit. const float bias = -input_zero_point * scale * num_elements_in_axis + 0.5f; for (size_t idx = 0; idx < num_outputs; ++idx) { const U value = static_cast<U>(TfLiteRound(temp_sum[idx] * scale + bias)) + output_zero_point; output_data[idx] = static_cast<T>(value); } } else { const float bias = -input_zero_point * scale + 0.5f; for (size_t idx = 0; idx < num_outputs; ++idx) { float float_mean = static_cast<float>(temp_sum[idx]) / static_cast<float>(num_elements_in_axis); float result = TfLiteMin( TfLiteRound(float_mean * scale + bias) + output_zero_point, static_cast<float>(std::numeric_limits<T>::max())); result = TfLiteMax(result, static_cast<float>(std::numeric_limits<T>::min())); output_data[idx] = static_cast<T>(result); } } } return true; } } // namespace reference_ops } // namespace tflite #endif // TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_REDUCE_H_
null
183
CWE-787
CVE-2020-15208
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_LITE_KERNELS_INTERNAL_TYPES_H_ #define TENSORFLOW_LITE_KERNELS_INTERNAL_TYPES_H_ #include <algorithm> #include <cstdint> #include <cstring> #include <initializer_list> #include "tensorflow/lite/kernels/internal/compatibility.h" namespace tflite { enum class FusedActivationFunctionType : uint8_t { kNone, kRelu6, kRelu1, kRelu }; enum class PaddingType : uint8_t { kNone, kSame, kValid }; struct PaddingValues { int16_t width; int16_t height; // offset is used for calculating "remaining" padding, for example, `width` // is 1 and `width_offset` is 1, so padding_left is 1 while padding_right is // 1 + 1 = 2. int16_t width_offset; // Same as width_offset except it's over the height dimension. int16_t height_offset; }; // This enumeration allows for non-default formats for the weights array // of a fully-connected operator, allowing the use of special optimized // runtime paths. enum class FullyConnectedWeightsFormat : uint8_t { // Default format (flat 2D layout, the inner contiguous dimension // is input_depth, the outer non-contiguous dimension is output_depth) kDefault, // Summary: optimized layout for fast CPU runtime implementation, // aimed specifically at ARM CPUs at the moment, and specialized for // 8-bit quantized layers. // // The use case we're concerned with here is: 8-bit quantization, // large weights matrix that doesn't fit in cache (e.g. 4096x2048 in // a key application that drove this), very small batch size (e.g. 1 -- 4). // // Even with 8-bit quantization of weights, the performance of memory // accesses to the weights can become the dominant issue when // the batch size is small, so each weight value is used in only a few // arithmetic ops, i.e. the fully-connected node has a low arithmetic // intensity. The specific issues that arise are of three kinds: // (1) One may, ideally, max out DRAM bandwidth, i.e. be truly memory // bound. That's the "good" issue to run into. // (2) One may run into sub-optimal pre-fetching: the data hasn't been // prefetched into the cache by the time we need it. // (3) One may run into cache aliasing: multiple values that are // pre-fetched, alias each other in the L1 cache (which typically // has only 4-way set associativity in ARM CPUs) and thus evict // each other before we get to using them. // // The point of this shuffling is to avoid issues (2) and (3) so that // we get as fast as possible given only the hard constraint (1). // This is achieved by turning the difficulty into a solution: the // difficulty, that each value loaded from memory is used only in // one kernel iteration, making this operation memory-intensive, hints at // the solution, of shuffling the weights so that they are stored in the // exact order as the kernel needs to load them, so that the memory // accesses made by the kernel are trivial. This solves (2) because the // trivial memory access pattern allows the CPU's automatic prefetching // to perform very well (no need even for preload instructions), and this // solves (3) because the values being loaded concurrently are now // contiguous in the address space, thus don't alias each other in the cache. // // On ARM, we typically want our kernel to process a 4x16 block of weights // at a time, because: // - 16 is the number of bytes in a NEON register. // - 4 is how many rows we need to handle concurrently in the kernel in // order to have sufficient mutual independence of instructions to // maximize arithmetic throughput. // // Finally, the 'Int8' part in the name refers to the fact that this // weights format has each weights value encoded as a signed int8_t value, // even if the data type of the weights buffer is uint8_t. This is intended // to save runtime kernels the effort to have to XOR the top bit of these // bytes before using them in signed arithmetic, see this file for more // explanations on the 'signed int8_t trick' in matrix multiplication kernels: // // tensorflow/lite/toco/graph_transformations/ensure_uint8_weights_safe_for_fast_int8_kernels.cc // kShuffled4x16Int8, }; // Quantization parameters, determining the mapping of quantized values // to real values (i.e. determining how quantized values are mathematically // interpreted). // // The correspondence is as follows: // // real_value = scale * (quantized_value - zero_point); // // In other words, zero_point designates which quantized value corresponds to // the real 0 value, and scale designates the difference between the real values // corresponding to consecutive quantized values differing by 1. struct QuantizationParams { int32_t zero_point = 0; double scale = 0.0; }; inline bool operator==(const QuantizationParams& qp1, const QuantizationParams& qp2) { return qp1.zero_point == qp2.zero_point && qp1.scale == qp2.scale; } template <int N> struct Dims { int sizes[N]; int strides[N]; }; class RuntimeShape { public: // Shapes with dimensions up to 5 are stored directly in the structure, while // larger shapes are separately allocated. static constexpr int kMaxSmallSize = 5; RuntimeShape& operator=(RuntimeShape const&) = delete; RuntimeShape() : size_(0) {} explicit RuntimeShape(int dimensions_count) : size_(dimensions_count) { if (dimensions_count > kMaxSmallSize) { #ifdef TF_LITE_STATIC_MEMORY TFLITE_CHECK(false && "No shape resizing supported on this platform"); #else // TF_LITE_STATIC_MEMORY dims_pointer_ = new int32_t[dimensions_count]; #endif // TF_LITE_STATIC_MEMORY } } RuntimeShape(int shape_size, int32_t value) : size_(0) { Resize(shape_size); for (int i = 0; i < shape_size; ++i) { SetDim(i, value); } } RuntimeShape(int dimensions_count, const int32_t* dims_data) : size_(0) { ReplaceWith(dimensions_count, dims_data); } RuntimeShape(const std::initializer_list<int> init_list) : size_(0) { BuildFrom(init_list); } // Avoid using this constructor. We should be able to delete it when C++17 // rolls out. RuntimeShape(RuntimeShape const& other) : size_(other.DimensionsCount()) { if (size_ > kMaxSmallSize) { dims_pointer_ = new int32_t[size_]; } std::memcpy(DimsData(), other.DimsData(), sizeof(int32_t) * size_); } bool operator==(const RuntimeShape& comp) const { return this->size_ == comp.size_ && std::memcmp(DimsData(), comp.DimsData(), size_ * sizeof(int32_t)) == 0; } ~RuntimeShape() { if (size_ > kMaxSmallSize) { #ifdef TF_LITE_STATIC_MEMORY TFLITE_CHECK(false && "No shape resizing supported on this platform"); #else // TF_LITE_STATIC_MEMORY delete[] dims_pointer_; #endif // TF_LITE_STATIC_MEMORY } } inline int32_t DimensionsCount() const { return size_; } inline int32_t Dims(int i) const { TFLITE_DCHECK_GE(i, 0); TFLITE_DCHECK_LT(i, size_); return size_ > kMaxSmallSize ? dims_pointer_[i] : dims_[i]; } inline void SetDim(int i, int32_t val) { TFLITE_DCHECK_GE(i, 0); TFLITE_DCHECK_LT(i, size_); if (size_ > kMaxSmallSize) { dims_pointer_[i] = val; } else { dims_[i] = val; } } inline int32_t* DimsData() { return size_ > kMaxSmallSize ? dims_pointer_ : dims_; } inline const int32_t* DimsData() const { return size_ > kMaxSmallSize ? dims_pointer_ : dims_; } // The caller must ensure that the shape is no bigger than 5-D. inline const int32_t* DimsDataUpTo5D() const { return dims_; } inline void Resize(int dimensions_count) { if (size_ > kMaxSmallSize) { #ifdef TF_LITE_STATIC_MEMORY TFLITE_CHECK(false && "No shape resizing supported on this platform"); #else // TF_LITE_STATIC_MEMORY delete[] dims_pointer_; #endif // TF_LITE_STATIC_MEMORY } size_ = dimensions_count; if (dimensions_count > kMaxSmallSize) { #ifdef TF_LITE_STATIC_MEMORY TFLITE_CHECK(false && "No shape resizing supported on this platform"); #else // TF_LITE_STATIC_MEMORY dims_pointer_ = new int32_t[dimensions_count]; #endif // TF_LITE_STATIC_MEMORY } } inline void ReplaceWith(int dimensions_count, const int32_t* dims_data) { Resize(dimensions_count); int32_t* dst_dims = DimsData(); std::memcpy(dst_dims, dims_data, dimensions_count * sizeof(int32_t)); } template <typename T> inline void BuildFrom(const T& src_iterable) { const int dimensions_count = std::distance(src_iterable.begin(), src_iterable.end()); Resize(dimensions_count); int32_t* data = DimsData(); for (auto it : src_iterable) { *data = it; ++data; } } // This will probably be factored out. Old code made substantial use of 4-D // shapes, and so this function is used to extend smaller shapes. Note that // (a) as Dims<4>-dependent code is eliminated, the reliance on this should be // reduced, and (b) some kernels are stricly 4-D, but then the shapes of their // inputs should already be 4-D, so this function should not be needed. inline static RuntimeShape ExtendedShape(int new_shape_size, const RuntimeShape& shape) { return RuntimeShape(new_shape_size, shape, 1); } inline void BuildFrom(const std::initializer_list<int> init_list) { BuildFrom<const std::initializer_list<int>>(init_list); } // Returns the total count of elements, that is the size when flattened into a // vector. inline int FlatSize() const { int buffer_size = 1; const int* dims_data = reinterpret_cast<const int*>(DimsData()); for (int i = 0; i < size_; i++) { buffer_size *= dims_data[i]; } return buffer_size; } bool operator!=(const RuntimeShape& comp) const { return !((*this) == comp); } private: // For use only by ExtendedShape(), written to guarantee (return-value) copy // elision in C++17. // This creates a shape padded to the desired size with the specified value. RuntimeShape(int new_shape_size, const RuntimeShape& shape, int pad_value) : size_(0) { // If the following check fails, it is likely because a 4D-only kernel is // being used with an array of larger dimension count. TFLITE_CHECK_GE(new_shape_size, shape.DimensionsCount()); Resize(new_shape_size); const int size_increase = new_shape_size - shape.DimensionsCount(); for (int i = 0; i < size_increase; ++i) { SetDim(i, pad_value); } std::memcpy(DimsData() + size_increase, shape.DimsData(), sizeof(int32_t) * shape.DimensionsCount()); } int32_t size_; union { int32_t dims_[kMaxSmallSize]; int32_t* dims_pointer_; }; }; // Converts inference-style shape to legacy tflite::Dims<4>. inline tflite::Dims<4> ToRuntimeDims(const tflite::RuntimeShape& array_shape) { tflite::Dims<4> result; const int dimensions_count = array_shape.DimensionsCount(); TFLITE_CHECK_LE(dimensions_count, 4); int cum_prod = 1; for (int i = 0; i < 4; i++) { const int new_dim = (i < dimensions_count) ? array_shape.Dims(dimensions_count - 1 - i) : 1; result.sizes[i] = new_dim; result.strides[i] = cum_prod; cum_prod *= new_dim; } return result; } // TODO(b/80418076): Move to legacy ops file, update invocations. inline RuntimeShape DimsToShape(const tflite::Dims<4>& dims) { return RuntimeShape( {dims.sizes[3], dims.sizes[2], dims.sizes[1], dims.sizes[0]}); } // Gets next index to iterate through a multidimensional array. inline bool NextIndex(const int num_dims, const int* dims, int* current) { if (num_dims == 0) { return false; } TFLITE_DCHECK(dims != nullptr); TFLITE_DCHECK(current != nullptr); int carry = 1; for (int idx = num_dims - 1; idx >= 0; --idx) { int current_val = current[idx] + carry; TFLITE_DCHECK_GE(dims[idx], current_val); if (dims[idx] == current_val) { current[idx] = 0; } else { current[idx] = current_val; carry = 0; break; } } return (carry == 0); } // Gets offset of index if reducing on axis. When reducing, the flattened offset // will not change, if the input index changes on the given axis. For example, // if you have a 3D tensor and you are reducing to 2D by eliminating axis 0, // then index (0, 1, 2) and index (1, 1, 2) will map to the same flattened // offset. // TODO(kanlig): uses Dims to represent dimensions. inline size_t ReducedOutputOffset(const int num_dims, const int* dims, const int* index, const int num_axis, const int* axis) { if (num_dims == 0) { return 0; } TFLITE_DCHECK(dims != nullptr); TFLITE_DCHECK(index != nullptr); size_t offset = 0; for (int idx = 0; idx < num_dims; ++idx) { // if we need to skip this axis bool is_axis = false; if (axis != nullptr) { for (int axis_idx = 0; axis_idx < num_axis; ++axis_idx) { if (idx == axis[axis_idx]) { is_axis = true; break; } } } if (!is_axis) { offset = offset * static_cast<size_t>(dims[idx]) + static_cast<size_t>(index[idx]); } } return offset; } inline int Offset(const RuntimeShape& shape, int i0, int i1, int i2, int i3) { TFLITE_DCHECK_EQ(shape.DimensionsCount(), 4); const int* dims_data = reinterpret_cast<const int*>(shape.DimsDataUpTo5D()); TFLITE_DCHECK(i0 >= 0 && i0 < dims_data[0]); TFLITE_DCHECK(i1 >= 0 && i1 < dims_data[1]); TFLITE_DCHECK(i2 >= 0 && i2 < dims_data[2]); TFLITE_DCHECK(i3 >= 0 && i3 < dims_data[3]); return ((i0 * dims_data[1] + i1) * dims_data[2] + i2) * dims_data[3] + i3; } inline int Offset(const Dims<4>& dims, int i0, int i1, int i2, int i3) { TFLITE_DCHECK(i0 >= 0 && i0 < dims.sizes[0]); TFLITE_DCHECK(i1 >= 0 && i1 < dims.sizes[1]); TFLITE_DCHECK(i2 >= 0 && i2 < dims.sizes[2]); TFLITE_DCHECK(i3 >= 0 && i3 < dims.sizes[3]); return i0 * dims.strides[0] + i1 * dims.strides[1] + i2 * dims.strides[2] + i3 * dims.strides[3]; } inline int Offset(const Dims<4>& dims, int* index) { return Offset(dims, index[0], index[1], index[2], index[3]); } inline int Offset(const RuntimeShape& shape, int* index) { return Offset(shape, index[0], index[1], index[2], index[3]); } // Get array size, DCHECKing that the dim index is in range. // // Note that this will be phased out with Dims<4>, since RuntimeShape::Dims() // already performs this check. template <int N> int ArraySize(const Dims<N>& array, int index) { TFLITE_DCHECK(index >= 0 && index < N); return array.sizes[index]; } // Get common array size, DCHECKing that they all agree. template <typename ArrayType1, typename ArrayType2> int MatchingArraySize(const ArrayType1& array1, int index1, const ArrayType2& array2, int index2) { TFLITE_DCHECK_EQ(ArraySize(array1, index1), ArraySize(array2, index2)); return ArraySize(array1, index1); } template <typename ArrayType1, typename ArrayType2, typename... Args> int MatchingArraySize(const ArrayType1& array1, int index1, const ArrayType2& array2, int index2, Args... args) { TFLITE_DCHECK_EQ(ArraySize(array1, index1), ArraySize(array2, index2)); return MatchingArraySize(array1, index1, args...); } // Get common shape dim, DCHECKing that they all agree. inline int MatchingDim(const RuntimeShape& shape1, int index1, const RuntimeShape& shape2, int index2) { TFLITE_DCHECK_EQ(shape1.Dims(index1), shape2.Dims(index2)); return shape1.Dims(index1); } template <typename... Args> int MatchingDim(const RuntimeShape& shape1, int index1, const RuntimeShape& shape2, int index2, Args... args) { TFLITE_DCHECK_EQ(shape1.Dims(index1), shape2.Dims(index2)); return MatchingDim(shape1, index1, args...); } // Will be phased out with Dims<4>, replaced by RuntimeShape::FlatSize(). template <int N> inline int FlatSize(const Dims<N>& dims) { int flat_size = 1; for (int i = 0; i < N; ++i) { flat_size *= dims.sizes[i]; } return flat_size; } TFLITE_DEPRECATED("Prefer FlatSize.") inline int RequiredBufferSizeForDims(const Dims<4>& dims) { return FlatSize(dims); } inline int MatchingElementsSize(const RuntimeShape& shape, const RuntimeShape& check_shape_0) { const int size_1 = shape.FlatSize(); const int size_2 = check_shape_0.FlatSize(); TFLITE_CHECK_EQ(size_1, size_2); return size_1; } inline int MatchingElementsSize(const RuntimeShape& shape, const RuntimeShape& check_shape_0, const RuntimeShape& check_shape_1) { const int size_1 = shape.FlatSize(); const int size_2 = check_shape_0.FlatSize(); const int size_3 = check_shape_1.FlatSize(); TFLITE_CHECK_EQ(size_1, size_2); TFLITE_CHECK_EQ(size_2, size_3); return size_1; } // Flat size calculation, checking that dimensions match with one or more other // arrays. inline int MatchingFlatSize(const RuntimeShape& shape, const RuntimeShape& check_shape_0) { TFLITE_DCHECK_EQ(shape.DimensionsCount(), check_shape_0.DimensionsCount()); const int dims_count = shape.DimensionsCount(); for (int i = 0; i < dims_count; ++i) { TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i)); } return shape.FlatSize(); } inline int MatchingFlatSize(const RuntimeShape& shape, const RuntimeShape& check_shape_0, const RuntimeShape& check_shape_1) { TFLITE_DCHECK_EQ(shape.DimensionsCount(), check_shape_0.DimensionsCount()); const int dims_count = shape.DimensionsCount(); for (int i = 0; i < dims_count; ++i) { TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i)); } return MatchingFlatSize(shape, check_shape_1); } inline int MatchingFlatSize(const RuntimeShape& shape, const RuntimeShape& check_shape_0, const RuntimeShape& check_shape_1, const RuntimeShape& check_shape_2) { TFLITE_DCHECK_EQ(shape.DimensionsCount(), check_shape_0.DimensionsCount()); const int dims_count = shape.DimensionsCount(); for (int i = 0; i < dims_count; ++i) { TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i)); } return MatchingFlatSize(shape, check_shape_1, check_shape_2); } inline int MatchingFlatSize(const RuntimeShape& shape, const RuntimeShape& check_shape_0, const RuntimeShape& check_shape_1, const RuntimeShape& check_shape_2, const RuntimeShape& check_shape_3) { TFLITE_DCHECK_EQ(shape.DimensionsCount(), check_shape_0.DimensionsCount()); const int dims_count = shape.DimensionsCount(); for (int i = 0; i < dims_count; ++i) { TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i)); } return MatchingFlatSize(shape, check_shape_1, check_shape_2, check_shape_3); } // Flat size calculation, checking that dimensions match with one or more other // arrays. template <int N> inline int MatchingFlatSize(const Dims<N>& dims, const Dims<N>& check_dims_0) { for (int i = 0; i < N; ++i) { TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i)); } return FlatSize(dims); } template <int N> inline int MatchingFlatSize(const Dims<N>& dims, const Dims<N>& check_dims_0, const Dims<N>& check_dims_1) { for (int i = 0; i < N; ++i) { TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i)); } return MatchingFlatSize(dims, check_dims_1); } template <int N> inline int MatchingFlatSize(const Dims<N>& dims, const Dims<N>& check_dims_0, const Dims<N>& check_dims_1, const Dims<N>& check_dims_2) { for (int i = 0; i < N; ++i) { TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i)); } return MatchingFlatSize(dims, check_dims_1, check_dims_2); } template <int N> inline int MatchingFlatSize(const Dims<N>& dims, const Dims<N>& check_dims_0, const Dims<N>& check_dims_1, const Dims<N>& check_dims_2, const Dims<N>& check_dims_3) { for (int i = 0; i < N; ++i) { TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i)); } return MatchingFlatSize(dims, check_dims_1, check_dims_2, check_dims_3); } // Data is required to be contiguous, and so many operators can use either the // full array flat size or the flat size with one dimension skipped (commonly // the depth). template <int N> inline int FlatSizeSkipDim(const Dims<N>& dims, int skip_dim) { TFLITE_DCHECK(skip_dim >= 0 && skip_dim < N); int flat_size = 1; for (int i = 0; i < N; ++i) { flat_size *= (i == skip_dim) ? 1 : dims.sizes[i]; } return flat_size; } // A combination of MatchingFlatSize() and FlatSizeSkipDim(). template <int N> inline int MatchingFlatSizeSkipDim(const Dims<N>& dims, int skip_dim, const Dims<N>& check_dims_0) { for (int i = 0; i < N; ++i) { if (i != skip_dim) { TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i)); } } return FlatSizeSkipDim(dims, skip_dim); } template <int N> inline int MatchingFlatSizeSkipDim(const Dims<N>& dims, int skip_dim, const Dims<N>& check_dims_0, const Dims<N>& check_dims_1) { for (int i = 0; i < N; ++i) { if (i != skip_dim) { TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i)); } } return MatchingFlatSizeSkipDim(dims, skip_dim, check_dims_1); } template <int N> inline int MatchingFlatSizeSkipDim(const Dims<N>& dims, int skip_dim, const Dims<N>& check_dims_0, const Dims<N>& check_dims_1, const Dims<N>& check_dims_2) { for (int i = 0; i < N; ++i) { if (i != skip_dim) { TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i)); } } return MatchingFlatSizeSkipDim(dims, skip_dim, check_dims_1, check_dims_2); } template <int N> inline int MatchingFlatSizeSkipDim(const Dims<N>& dims, int skip_dim, const Dims<N>& check_dims_0, const Dims<N>& check_dims_1, const Dims<N>& check_dims_2, const Dims<N>& check_dims_3) { for (int i = 0; i < N; ++i) { if (i != skip_dim) { TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i)); } } return MatchingFlatSizeSkipDim(dims, skip_dim, check_dims_1, check_dims_2, check_dims_3); } // Data is required to be contiguous, and so many operators can use either the // full array flat size or the flat size with one dimension skipped (commonly // the depth). inline int FlatSizeSkipDim(const RuntimeShape& shape, int skip_dim) { const int dims_count = shape.DimensionsCount(); TFLITE_DCHECK(skip_dim >= 0 && skip_dim < dims_count); const auto* dims_data = shape.DimsData(); int flat_size = 1; for (int i = 0; i < dims_count; ++i) { flat_size *= (i == skip_dim) ? 1 : dims_data[i]; } return flat_size; } // A combination of MatchingFlatSize() and FlatSizeSkipDim(). inline int MatchingFlatSizeSkipDim(const RuntimeShape& shape, int skip_dim, const RuntimeShape& check_shape_0) { const int dims_count = shape.DimensionsCount(); for (int i = 0; i < dims_count; ++i) { if (i != skip_dim) { TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i)); } } return FlatSizeSkipDim(shape, skip_dim); } inline int MatchingFlatSizeSkipDim(const RuntimeShape& shape, int skip_dim, const RuntimeShape& check_shape_0, const RuntimeShape& check_shape_1) { const int dims_count = shape.DimensionsCount(); for (int i = 0; i < dims_count; ++i) { if (i != skip_dim) { TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i)); } } return MatchingFlatSizeSkipDim(shape, skip_dim, check_shape_1); } inline int MatchingFlatSizeSkipDim(const RuntimeShape& shape, int skip_dim, const RuntimeShape& check_shape_0, const RuntimeShape& check_shape_1, const RuntimeShape& check_shape_2) { const int dims_count = shape.DimensionsCount(); for (int i = 0; i < dims_count; ++i) { if (i != skip_dim) { TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i)); } } return MatchingFlatSizeSkipDim(shape, skip_dim, check_shape_1, check_shape_2); } inline int MatchingFlatSizeSkipDim(const RuntimeShape& shape, int skip_dim, const RuntimeShape& check_shape_0, const RuntimeShape& check_shape_1, const RuntimeShape& check_shape_2, const RuntimeShape& check_shape_3) { const int dims_count = shape.DimensionsCount(); for (int i = 0; i < dims_count; ++i) { if (i != skip_dim) { TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i)); } } return MatchingFlatSizeSkipDim(shape, skip_dim, check_shape_1, check_shape_2, check_shape_3); } template <int N> bool IsPackedWithoutStrides(const Dims<N>& dims) { int expected_stride = 1; for (int d = 0; d < N; d++) { if (dims.strides[d] != expected_stride) return false; expected_stride *= dims.sizes[d]; } return true; } template <int N> void ComputeStrides(Dims<N>* dims) { dims->strides[0] = 1; for (int d = 1; d < N; d++) { dims->strides[d] = dims->strides[d - 1] * dims->sizes[d - 1]; } } enum class BroadcastableOpCategory : uint8_t { kNone, kNonBroadcast, // Matching input shapes. kFirstInputBroadcastsFast, // Fivefold nested loops. kSecondInputBroadcastsFast, // Fivefold nested loops. kGenericBroadcast, // Fall-back. }; struct MinMax { float min; float max; }; static_assert(sizeof(MinMax) == 8, ""); struct ActivationParams { FusedActivationFunctionType activation_type; // uint8_t, etc, activation params. int32_t quantized_activation_min; int32_t quantized_activation_max; }; struct ReluParams : public ActivationParams { int32_t input_offset; int32_t output_offset; int32_t output_multiplier; int output_shift; }; // Styles of resizing op usages. For example, kImageStyle can be used with a Pad // op for pattern-specific optimization. enum class ResizingCategory : uint8_t { kNone, kImageStyle, // 4D, operating on inner dimensions, say {0, a, b, 0}. kGenericResize, }; // For Add, Sub, Mul ops. struct ArithmeticParams { // Shape dependent / common to data / op types. BroadcastableOpCategory broadcast_category; // uint8_t inference params. int32_t input1_offset; int32_t input2_offset; int32_t output_offset; int32_t output_multiplier; int output_shift; // Add / Sub, not Mul, uint8_t inference params. int left_shift; int32_t input1_multiplier; int input1_shift; int32_t input2_multiplier; int input2_shift; // TODO(b/158622529): Union the following activation params. // uint8_t, etc, activation params. int32_t quantized_activation_min; int32_t quantized_activation_max; // float activation params. float float_activation_min; float float_activation_max; // int64_t activation params. int64_t int64_activation_min; int64_t int64_activation_max; // Processed output dimensions. // Let input "a" be the one that broadcasts in the faster-changing dimension. // Then, after coalescing, for shapes {a0, a1, a2, a3, a4} and // {b0, b1, b2, b3, b4}, // broadcast_shape[4] = b0 = a0. // broadcast_shape[3] = b1; a1 = 1. // broadcast_shape[2] = b2 = a2. // broadcast_shape[1] = a3; b3 = 1. // broadcast_shape[0] = b4 = a4. int broadcast_shape[5]; }; struct ConcatenationParams { int8_t axis; const int32_t* input_zeropoint; const float* input_scale; uint16_t inputs_count; int32_t output_zeropoint; float output_scale; }; struct ComparisonParams { // uint8_t inference params. int left_shift; int32_t input1_offset; int32_t input1_multiplier; int input1_shift; int32_t input2_offset; int32_t input2_multiplier; int input2_shift; // Shape dependent / common to inference types. bool is_broadcast; }; struct ConvParams { PaddingType padding_type; PaddingValues padding_values; // TODO(starka): This was just "stride", so check that width+height is OK. int16_t stride_width; int16_t stride_height; int16_t dilation_width_factor; int16_t dilation_height_factor; // uint8_t inference params. // TODO(b/65838351): Use smaller types if appropriate. int32_t input_offset; int32_t weights_offset; int32_t output_offset; int32_t output_multiplier; int output_shift; // uint8_t, etc, activation params. int32_t quantized_activation_min; int32_t quantized_activation_max; // float activation params. float float_activation_min; float float_activation_max; }; struct DepthToSpaceParams { int32_t block_size; }; struct DepthwiseParams { PaddingType padding_type; PaddingValues padding_values; int16_t stride_width; int16_t stride_height; int16_t dilation_width_factor; int16_t dilation_height_factor; int16_t depth_multiplier; // uint8_t inference params. // TODO(b/65838351): Use smaller types if appropriate. int32_t input_offset; int32_t weights_offset; int32_t output_offset; int32_t output_multiplier; int output_shift; // uint8_t, etc, activation params. int32_t quantized_activation_min; int32_t quantized_activation_max; // float activation params. float float_activation_min; float float_activation_max; const int32_t* output_multiplier_per_channel; const int32_t* output_shift_per_channel; }; struct DequantizationParams { double scale; int32_t zero_point; }; struct PerChannelDequantizationParams { const float* scale; const int32_t* zero_point; int32_t quantized_dimension; }; struct FakeQuantParams { MinMax minmax; int32_t num_bits; }; struct FullyConnectedParams { // uint8_t inference params. // TODO(b/65838351): Use smaller types if appropriate. int32_t input_offset; int32_t weights_offset; int32_t output_offset; int32_t output_multiplier; int output_shift; // uint8_t, etc, activation params. int32_t quantized_activation_min; int32_t quantized_activation_max; // float activation params. float float_activation_min; float float_activation_max; // Mark the operands as cacheable if they are unchanging, e.g. weights. bool lhs_cacheable; bool rhs_cacheable; FullyConnectedWeightsFormat weights_format; }; struct GatherParams { int16_t axis; }; struct L2NormalizationParams { // uint8_t inference params. int32_t input_zero_point; }; struct LocalResponseNormalizationParams { int32_t range; double bias; double alpha; double beta; }; struct HardSwishParams { // zero_point of the input activations. int16_t input_zero_point; // zero_point of the output activations. int16_t output_zero_point; // 16bit fixed-point component of the multiplier to apply to go from the // "high-res input scale", which is the input scale multiplied by 2^7, to the // "relu-ish scale", which 3.0/32768. // See the implementation of HardSwishPrepare. int16_t reluish_multiplier_fixedpoint_int16; // exponent/bit-shift component of the aforementioned multiplier. int reluish_multiplier_exponent; // 16bit fixed-point component of the multiplier to apply to go from the // "high-res input scale", which is the input scale multiplied by 2^7, to the // output scale. // See the implementation of HardSwishPrepare. int16_t output_multiplier_fixedpoint_int16; // exponent/bit-shift component of the aforementioned multiplier. int output_multiplier_exponent; }; struct LogisticParams { // uint8_t inference params. int32_t input_zero_point; int32_t input_range_radius; int32_t input_multiplier; int input_left_shift; }; struct LstmCellParams { int32_t weights_zero_point; int32_t accum_multiplier; int accum_shift; int state_integer_bits; }; struct MeanParams { int8_t axis_count; int16_t axis[4]; }; struct PackParams { int8_t axis; const int32_t* input_zeropoint; const float* input_scale; uint16_t inputs_count; int32_t output_zeropoint; float output_scale; }; struct PadParams { int8_t left_padding_count; int32_t left_padding[4]; int8_t right_padding_count; int32_t right_padding[4]; ResizingCategory resizing_category; }; struct PreluParams { int32_t input_offset; int32_t alpha_offset; int32_t output_offset; int32_t output_multiplier_1; int output_shift_1; int32_t output_multiplier_2; int output_shift_2; }; struct PoolParams { FusedActivationFunctionType activation; PaddingType padding_type; PaddingValues padding_values; int stride_height; int stride_width; int filter_height; int filter_width; // uint8_t, etc, activation params. int32_t quantized_activation_min; int32_t quantized_activation_max; // float activation params. float float_activation_min; float float_activation_max; }; struct ReshapeParams { int8_t shape_count; int32_t shape[4]; }; struct ResizeBilinearParams { bool align_corners; // half_pixel_centers assumes pixels are of half the actual dimensions, and // yields more accurate resizes. Corresponds to the same argument for the // original TensorFlow op in TF2.0. bool half_pixel_centers; }; struct ResizeNearestNeighborParams { bool align_corners; bool half_pixel_centers; }; struct SliceParams { int8_t begin_count; int32_t begin[4]; int8_t size_count; int32_t size[4]; }; struct SoftmaxParams { // beta is not really used (not a Tensorflow parameter) and not implemented // for LogSoftmax. double beta; // uint8_t inference params. Used even when beta defaults to 1.0. int32_t input_multiplier; int32_t input_left_shift; // Reverse scaling is only used by LogSoftmax. int32_t reverse_scaling_divisor; int32_t reverse_scaling_right_shift; int diff_min; int32_t zero_point; float scale; float* table; int16_t* exp_lut; int16_t* one_over_one_plus_x_lut; uint8_t* uint8_table1; uint8_t* uint8_table2; }; struct SpaceToBatchParams { // "Zero" padding for uint8_t means padding with the output offset. int32_t output_offset; }; struct SpaceToDepthParams { int32_t block_size; }; struct SplitParams { // Graphs that split into, say, 2000 nodes are encountered. The indices in // OperatorEdges are of type uint16_t. uint16_t num_split; int16_t axis; }; struct SqueezeParams { int8_t squeeze_dims_count; int32_t squeeze_dims[4]; }; struct StridedSliceParams { int8_t start_indices_count; int32_t start_indices[5]; int8_t stop_indices_count; int32_t stop_indices[5]; int8_t strides_count; int32_t strides[5]; int16_t begin_mask; int16_t ellipsis_mask; int16_t end_mask; int16_t new_axis_mask; int16_t shrink_axis_mask; }; struct TanhParams { int32_t input_zero_point; int32_t input_range_radius; int32_t input_multiplier; int input_left_shift; }; struct TransposeParams { int8_t perm_count; int32_t perm[5]; }; struct UnpackParams { uint16_t num_split; int16_t axis; }; struct LeakyReluParams { float alpha; int32_t input_offset; int32_t output_offset; int32_t output_multiplier_alpha; int32_t output_shift_alpha; int32_t output_multiplier_identity; int32_t output_shift_identity; }; template <typename P> inline void SetActivationParams(float min, float max, P* params) { params->float_activation_min = min; params->float_activation_max = max; } template <typename P> inline void SetActivationParams(int32_t min, int32_t max, P* params) { params->quantized_activation_min = min; params->quantized_activation_max = max; } template <typename P> inline void SetActivationParams(int64_t min, int64_t max, P* params) { params->int64_activation_min = min; params->int64_activation_max = max; } template <typename P> inline void GetActivationParams(const P& params, int32_t* min, int32_t* max) { *min = params.quantized_activation_min; *max = params.quantized_activation_max; } template <typename P> inline void GetActivationParams(const P& params, float* min, float* max) { *min = params.float_activation_min; *max = params.float_activation_max; } template <typename P> inline void GetActivationParams(const P& params, int64_t* min, int64_t* max) { *min = params.int64_activation_min; *max = params.int64_activation_max; } } // namespace tflite #endif // TENSORFLOW_LITE_KERNELS_INTERNAL_TYPES_H_
null
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_LITE_KERNELS_INTERNAL_TYPES_H_ #define TENSORFLOW_LITE_KERNELS_INTERNAL_TYPES_H_ #include <algorithm> #include <cstdint> #include <cstring> #include <initializer_list> #include "tensorflow/lite/kernels/internal/compatibility.h" namespace tflite { enum class FusedActivationFunctionType : uint8_t { kNone, kRelu6, kRelu1, kRelu }; enum class PaddingType : uint8_t { kNone, kSame, kValid }; struct PaddingValues { int16_t width; int16_t height; // offset is used for calculating "remaining" padding, for example, `width` // is 1 and `width_offset` is 1, so padding_left is 1 while padding_right is // 1 + 1 = 2. int16_t width_offset; // Same as width_offset except it's over the height dimension. int16_t height_offset; }; // This enumeration allows for non-default formats for the weights array // of a fully-connected operator, allowing the use of special optimized // runtime paths. enum class FullyConnectedWeightsFormat : uint8_t { // Default format (flat 2D layout, the inner contiguous dimension // is input_depth, the outer non-contiguous dimension is output_depth) kDefault, // Summary: optimized layout for fast CPU runtime implementation, // aimed specifically at ARM CPUs at the moment, and specialized for // 8-bit quantized layers. // // The use case we're concerned with here is: 8-bit quantization, // large weights matrix that doesn't fit in cache (e.g. 4096x2048 in // a key application that drove this), very small batch size (e.g. 1 -- 4). // // Even with 8-bit quantization of weights, the performance of memory // accesses to the weights can become the dominant issue when // the batch size is small, so each weight value is used in only a few // arithmetic ops, i.e. the fully-connected node has a low arithmetic // intensity. The specific issues that arise are of three kinds: // (1) One may, ideally, max out DRAM bandwidth, i.e. be truly memory // bound. That's the "good" issue to run into. // (2) One may run into sub-optimal pre-fetching: the data hasn't been // prefetched into the cache by the time we need it. // (3) One may run into cache aliasing: multiple values that are // pre-fetched, alias each other in the L1 cache (which typically // has only 4-way set associativity in ARM CPUs) and thus evict // each other before we get to using them. // // The point of this shuffling is to avoid issues (2) and (3) so that // we get as fast as possible given only the hard constraint (1). // This is achieved by turning the difficulty into a solution: the // difficulty, that each value loaded from memory is used only in // one kernel iteration, making this operation memory-intensive, hints at // the solution, of shuffling the weights so that they are stored in the // exact order as the kernel needs to load them, so that the memory // accesses made by the kernel are trivial. This solves (2) because the // trivial memory access pattern allows the CPU's automatic prefetching // to perform very well (no need even for preload instructions), and this // solves (3) because the values being loaded concurrently are now // contiguous in the address space, thus don't alias each other in the cache. // // On ARM, we typically want our kernel to process a 4x16 block of weights // at a time, because: // - 16 is the number of bytes in a NEON register. // - 4 is how many rows we need to handle concurrently in the kernel in // order to have sufficient mutual independence of instructions to // maximize arithmetic throughput. // // Finally, the 'Int8' part in the name refers to the fact that this // weights format has each weights value encoded as a signed int8_t value, // even if the data type of the weights buffer is uint8_t. This is intended // to save runtime kernels the effort to have to XOR the top bit of these // bytes before using them in signed arithmetic, see this file for more // explanations on the 'signed int8_t trick' in matrix multiplication kernels: // // tensorflow/lite/toco/graph_transformations/ensure_uint8_weights_safe_for_fast_int8_kernels.cc // kShuffled4x16Int8, }; // Quantization parameters, determining the mapping of quantized values // to real values (i.e. determining how quantized values are mathematically // interpreted). // // The correspondence is as follows: // // real_value = scale * (quantized_value - zero_point); // // In other words, zero_point designates which quantized value corresponds to // the real 0 value, and scale designates the difference between the real values // corresponding to consecutive quantized values differing by 1. struct QuantizationParams { int32_t zero_point = 0; double scale = 0.0; }; inline bool operator==(const QuantizationParams& qp1, const QuantizationParams& qp2) { return qp1.zero_point == qp2.zero_point && qp1.scale == qp2.scale; } template <int N> struct Dims { int sizes[N]; int strides[N]; }; class RuntimeShape { public: // Shapes with dimensions up to 5 are stored directly in the structure, while // larger shapes are separately allocated. static constexpr int kMaxSmallSize = 5; RuntimeShape& operator=(RuntimeShape const&) = delete; RuntimeShape() : size_(0) {} explicit RuntimeShape(int dimensions_count) : size_(dimensions_count) { if (dimensions_count > kMaxSmallSize) { #ifdef TF_LITE_STATIC_MEMORY TFLITE_CHECK(false && "No shape resizing supported on this platform"); #else // TF_LITE_STATIC_MEMORY dims_pointer_ = new int32_t[dimensions_count]; #endif // TF_LITE_STATIC_MEMORY } } RuntimeShape(int shape_size, int32_t value) : size_(0) { Resize(shape_size); for (int i = 0; i < shape_size; ++i) { SetDim(i, value); } } RuntimeShape(int dimensions_count, const int32_t* dims_data) : size_(0) { ReplaceWith(dimensions_count, dims_data); } RuntimeShape(const std::initializer_list<int> init_list) : size_(0) { BuildFrom(init_list); } // Avoid using this constructor. We should be able to delete it when C++17 // rolls out. RuntimeShape(RuntimeShape const& other) : size_(other.DimensionsCount()) { if (size_ > kMaxSmallSize) { dims_pointer_ = new int32_t[size_]; } std::memcpy(DimsData(), other.DimsData(), sizeof(int32_t) * size_); } bool operator==(const RuntimeShape& comp) const { return this->size_ == comp.size_ && std::memcmp(DimsData(), comp.DimsData(), size_ * sizeof(int32_t)) == 0; } ~RuntimeShape() { if (size_ > kMaxSmallSize) { #ifdef TF_LITE_STATIC_MEMORY TFLITE_CHECK(false && "No shape resizing supported on this platform"); #else // TF_LITE_STATIC_MEMORY delete[] dims_pointer_; #endif // TF_LITE_STATIC_MEMORY } } inline int32_t DimensionsCount() const { return size_; } inline int32_t Dims(int i) const { TFLITE_DCHECK_GE(i, 0); TFLITE_DCHECK_LT(i, size_); return size_ > kMaxSmallSize ? dims_pointer_[i] : dims_[i]; } inline void SetDim(int i, int32_t val) { TFLITE_DCHECK_GE(i, 0); TFLITE_DCHECK_LT(i, size_); if (size_ > kMaxSmallSize) { dims_pointer_[i] = val; } else { dims_[i] = val; } } inline int32_t* DimsData() { return size_ > kMaxSmallSize ? dims_pointer_ : dims_; } inline const int32_t* DimsData() const { return size_ > kMaxSmallSize ? dims_pointer_ : dims_; } // The caller must ensure that the shape is no bigger than 5-D. inline const int32_t* DimsDataUpTo5D() const { return dims_; } inline void Resize(int dimensions_count) { if (size_ > kMaxSmallSize) { #ifdef TF_LITE_STATIC_MEMORY TFLITE_CHECK(false && "No shape resizing supported on this platform"); #else // TF_LITE_STATIC_MEMORY delete[] dims_pointer_; #endif // TF_LITE_STATIC_MEMORY } size_ = dimensions_count; if (dimensions_count > kMaxSmallSize) { #ifdef TF_LITE_STATIC_MEMORY TFLITE_CHECK(false && "No shape resizing supported on this platform"); #else // TF_LITE_STATIC_MEMORY dims_pointer_ = new int32_t[dimensions_count]; #endif // TF_LITE_STATIC_MEMORY } } inline void ReplaceWith(int dimensions_count, const int32_t* dims_data) { Resize(dimensions_count); int32_t* dst_dims = DimsData(); std::memcpy(dst_dims, dims_data, dimensions_count * sizeof(int32_t)); } template <typename T> inline void BuildFrom(const T& src_iterable) { const int dimensions_count = std::distance(src_iterable.begin(), src_iterable.end()); Resize(dimensions_count); int32_t* data = DimsData(); for (auto it : src_iterable) { *data = it; ++data; } } // This will probably be factored out. Old code made substantial use of 4-D // shapes, and so this function is used to extend smaller shapes. Note that // (a) as Dims<4>-dependent code is eliminated, the reliance on this should be // reduced, and (b) some kernels are stricly 4-D, but then the shapes of their // inputs should already be 4-D, so this function should not be needed. inline static RuntimeShape ExtendedShape(int new_shape_size, const RuntimeShape& shape) { return RuntimeShape(new_shape_size, shape, 1); } inline void BuildFrom(const std::initializer_list<int> init_list) { BuildFrom<const std::initializer_list<int>>(init_list); } // Returns the total count of elements, that is the size when flattened into a // vector. inline int FlatSize() const { int buffer_size = 1; const int* dims_data = reinterpret_cast<const int*>(DimsData()); for (int i = 0; i < size_; i++) { buffer_size *= dims_data[i]; } return buffer_size; } bool operator!=(const RuntimeShape& comp) const { return !((*this) == comp); } private: // For use only by ExtendedShape(), written to guarantee (return-value) copy // elision in C++17. // This creates a shape padded to the desired size with the specified value. RuntimeShape(int new_shape_size, const RuntimeShape& shape, int pad_value) : size_(0) { // If the following check fails, it is likely because a 4D-only kernel is // being used with an array of larger dimension count. TFLITE_CHECK_GE(new_shape_size, shape.DimensionsCount()); Resize(new_shape_size); const int size_increase = new_shape_size - shape.DimensionsCount(); for (int i = 0; i < size_increase; ++i) { SetDim(i, pad_value); } std::memcpy(DimsData() + size_increase, shape.DimsData(), sizeof(int32_t) * shape.DimensionsCount()); } int32_t size_; union { int32_t dims_[kMaxSmallSize]; int32_t* dims_pointer_; }; }; // Converts inference-style shape to legacy tflite::Dims<4>. inline tflite::Dims<4> ToRuntimeDims(const tflite::RuntimeShape& array_shape) { tflite::Dims<4> result; const int dimensions_count = array_shape.DimensionsCount(); TFLITE_CHECK_LE(dimensions_count, 4); int cum_prod = 1; for (int i = 0; i < 4; i++) { const int new_dim = (i < dimensions_count) ? array_shape.Dims(dimensions_count - 1 - i) : 1; result.sizes[i] = new_dim; result.strides[i] = cum_prod; cum_prod *= new_dim; } return result; } // TODO(b/80418076): Move to legacy ops file, update invocations. inline RuntimeShape DimsToShape(const tflite::Dims<4>& dims) { return RuntimeShape( {dims.sizes[3], dims.sizes[2], dims.sizes[1], dims.sizes[0]}); } // Gets next index to iterate through a multidimensional array. inline bool NextIndex(const int num_dims, const int* dims, int* current) { if (num_dims == 0) { return false; } TFLITE_DCHECK(dims != nullptr); TFLITE_DCHECK(current != nullptr); int carry = 1; for (int idx = num_dims - 1; idx >= 0; --idx) { int current_val = current[idx] + carry; TFLITE_DCHECK_GE(dims[idx], current_val); if (dims[idx] == current_val) { current[idx] = 0; } else { current[idx] = current_val; carry = 0; break; } } return (carry == 0); } // Gets offset of index if reducing on axis. When reducing, the flattened offset // will not change, if the input index changes on the given axis. For example, // if you have a 3D tensor and you are reducing to 2D by eliminating axis 0, // then index (0, 1, 2) and index (1, 1, 2) will map to the same flattened // offset. // TODO(kanlig): uses Dims to represent dimensions. inline size_t ReducedOutputOffset(const int num_dims, const int* dims, const int* index, const int num_axis, const int* axis) { if (num_dims == 0) { return 0; } TFLITE_DCHECK(dims != nullptr); TFLITE_DCHECK(index != nullptr); size_t offset = 0; for (int idx = 0; idx < num_dims; ++idx) { // if we need to skip this axis bool is_axis = false; if (axis != nullptr) { for (int axis_idx = 0; axis_idx < num_axis; ++axis_idx) { if (idx == axis[axis_idx]) { is_axis = true; break; } } } if (!is_axis) { offset = offset * static_cast<size_t>(dims[idx]) + static_cast<size_t>(index[idx]); } } return offset; } inline int Offset(const RuntimeShape& shape, int i0, int i1, int i2, int i3) { TFLITE_DCHECK_EQ(shape.DimensionsCount(), 4); const int* dims_data = reinterpret_cast<const int*>(shape.DimsDataUpTo5D()); TFLITE_DCHECK(i0 >= 0 && i0 < dims_data[0]); TFLITE_DCHECK(i1 >= 0 && i1 < dims_data[1]); TFLITE_DCHECK(i2 >= 0 && i2 < dims_data[2]); TFLITE_DCHECK(i3 >= 0 && i3 < dims_data[3]); return ((i0 * dims_data[1] + i1) * dims_data[2] + i2) * dims_data[3] + i3; } inline int Offset(const Dims<4>& dims, int i0, int i1, int i2, int i3) { TFLITE_DCHECK(i0 >= 0 && i0 < dims.sizes[0]); TFLITE_DCHECK(i1 >= 0 && i1 < dims.sizes[1]); TFLITE_DCHECK(i2 >= 0 && i2 < dims.sizes[2]); TFLITE_DCHECK(i3 >= 0 && i3 < dims.sizes[3]); return i0 * dims.strides[0] + i1 * dims.strides[1] + i2 * dims.strides[2] + i3 * dims.strides[3]; } inline int Offset(const Dims<4>& dims, int* index) { return Offset(dims, index[0], index[1], index[2], index[3]); } inline int Offset(const RuntimeShape& shape, int* index) { return Offset(shape, index[0], index[1], index[2], index[3]); } // Get array size, DCHECKing that the dim index is in range. // // Note that this will be phased out with Dims<4>, since RuntimeShape::Dims() // already performs this check. template <int N> int ArraySize(const Dims<N>& array, int index) { TFLITE_DCHECK(index >= 0 && index < N); return array.sizes[index]; } // Get common array size, DCHECKing that they all agree. template <typename ArrayType1, typename ArrayType2> int MatchingArraySize(const ArrayType1& array1, int index1, const ArrayType2& array2, int index2) { TFLITE_DCHECK_EQ(ArraySize(array1, index1), ArraySize(array2, index2)); return ArraySize(array1, index1); } template <typename ArrayType1, typename ArrayType2, typename... Args> int MatchingArraySize(const ArrayType1& array1, int index1, const ArrayType2& array2, int index2, Args... args) { TFLITE_DCHECK_EQ(ArraySize(array1, index1), ArraySize(array2, index2)); return MatchingArraySize(array1, index1, args...); } // Get common shape dim, DCHECKing that they all agree. inline int MatchingDim(const RuntimeShape& shape1, int index1, const RuntimeShape& shape2, int index2) { TFLITE_DCHECK_EQ(shape1.Dims(index1), shape2.Dims(index2)); return std::min(shape1.Dims(index1), shape2.Dims(index2)); } template <typename... Args> int MatchingDim(const RuntimeShape& shape1, int index1, const RuntimeShape& shape2, int index2, Args... args) { TFLITE_DCHECK_EQ(shape1.Dims(index1), shape2.Dims(index2)); return MatchingDim(shape1, index1, args...); } // Will be phased out with Dims<4>, replaced by RuntimeShape::FlatSize(). template <int N> inline int FlatSize(const Dims<N>& dims) { int flat_size = 1; for (int i = 0; i < N; ++i) { flat_size *= dims.sizes[i]; } return flat_size; } TFLITE_DEPRECATED("Prefer FlatSize.") inline int RequiredBufferSizeForDims(const Dims<4>& dims) { return FlatSize(dims); } inline int MatchingElementsSize(const RuntimeShape& shape, const RuntimeShape& check_shape_0) { const int size_1 = shape.FlatSize(); const int size_2 = check_shape_0.FlatSize(); TFLITE_CHECK_EQ(size_1, size_2); return size_1; } inline int MatchingElementsSize(const RuntimeShape& shape, const RuntimeShape& check_shape_0, const RuntimeShape& check_shape_1) { const int size_1 = shape.FlatSize(); const int size_2 = check_shape_0.FlatSize(); const int size_3 = check_shape_1.FlatSize(); TFLITE_CHECK_EQ(size_1, size_2); TFLITE_CHECK_EQ(size_2, size_3); return size_1; } // Flat size calculation, checking that dimensions match with one or more other // arrays. inline int MatchingFlatSize(const RuntimeShape& shape, const RuntimeShape& check_shape_0) { TFLITE_DCHECK_EQ(shape.DimensionsCount(), check_shape_0.DimensionsCount()); const int dims_count = shape.DimensionsCount(); for (int i = 0; i < dims_count; ++i) { TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i)); } return shape.FlatSize(); } inline int MatchingFlatSize(const RuntimeShape& shape, const RuntimeShape& check_shape_0, const RuntimeShape& check_shape_1) { TFLITE_DCHECK_EQ(shape.DimensionsCount(), check_shape_0.DimensionsCount()); const int dims_count = shape.DimensionsCount(); for (int i = 0; i < dims_count; ++i) { TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i)); } return MatchingFlatSize(shape, check_shape_1); } inline int MatchingFlatSize(const RuntimeShape& shape, const RuntimeShape& check_shape_0, const RuntimeShape& check_shape_1, const RuntimeShape& check_shape_2) { TFLITE_DCHECK_EQ(shape.DimensionsCount(), check_shape_0.DimensionsCount()); const int dims_count = shape.DimensionsCount(); for (int i = 0; i < dims_count; ++i) { TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i)); } return MatchingFlatSize(shape, check_shape_1, check_shape_2); } inline int MatchingFlatSize(const RuntimeShape& shape, const RuntimeShape& check_shape_0, const RuntimeShape& check_shape_1, const RuntimeShape& check_shape_2, const RuntimeShape& check_shape_3) { TFLITE_DCHECK_EQ(shape.DimensionsCount(), check_shape_0.DimensionsCount()); const int dims_count = shape.DimensionsCount(); for (int i = 0; i < dims_count; ++i) { TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i)); } return MatchingFlatSize(shape, check_shape_1, check_shape_2, check_shape_3); } // Flat size calculation, checking that dimensions match with one or more other // arrays. template <int N> inline int MatchingFlatSize(const Dims<N>& dims, const Dims<N>& check_dims_0) { for (int i = 0; i < N; ++i) { TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i)); } return FlatSize(dims); } template <int N> inline int MatchingFlatSize(const Dims<N>& dims, const Dims<N>& check_dims_0, const Dims<N>& check_dims_1) { for (int i = 0; i < N; ++i) { TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i)); } return MatchingFlatSize(dims, check_dims_1); } template <int N> inline int MatchingFlatSize(const Dims<N>& dims, const Dims<N>& check_dims_0, const Dims<N>& check_dims_1, const Dims<N>& check_dims_2) { for (int i = 0; i < N; ++i) { TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i)); } return MatchingFlatSize(dims, check_dims_1, check_dims_2); } template <int N> inline int MatchingFlatSize(const Dims<N>& dims, const Dims<N>& check_dims_0, const Dims<N>& check_dims_1, const Dims<N>& check_dims_2, const Dims<N>& check_dims_3) { for (int i = 0; i < N; ++i) { TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i)); } return MatchingFlatSize(dims, check_dims_1, check_dims_2, check_dims_3); } // Data is required to be contiguous, and so many operators can use either the // full array flat size or the flat size with one dimension skipped (commonly // the depth). template <int N> inline int FlatSizeSkipDim(const Dims<N>& dims, int skip_dim) { TFLITE_DCHECK(skip_dim >= 0 && skip_dim < N); int flat_size = 1; for (int i = 0; i < N; ++i) { flat_size *= (i == skip_dim) ? 1 : dims.sizes[i]; } return flat_size; } // A combination of MatchingFlatSize() and FlatSizeSkipDim(). template <int N> inline int MatchingFlatSizeSkipDim(const Dims<N>& dims, int skip_dim, const Dims<N>& check_dims_0) { for (int i = 0; i < N; ++i) { if (i != skip_dim) { TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i)); } } return FlatSizeSkipDim(dims, skip_dim); } template <int N> inline int MatchingFlatSizeSkipDim(const Dims<N>& dims, int skip_dim, const Dims<N>& check_dims_0, const Dims<N>& check_dims_1) { for (int i = 0; i < N; ++i) { if (i != skip_dim) { TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i)); } } return MatchingFlatSizeSkipDim(dims, skip_dim, check_dims_1); } template <int N> inline int MatchingFlatSizeSkipDim(const Dims<N>& dims, int skip_dim, const Dims<N>& check_dims_0, const Dims<N>& check_dims_1, const Dims<N>& check_dims_2) { for (int i = 0; i < N; ++i) { if (i != skip_dim) { TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i)); } } return MatchingFlatSizeSkipDim(dims, skip_dim, check_dims_1, check_dims_2); } template <int N> inline int MatchingFlatSizeSkipDim(const Dims<N>& dims, int skip_dim, const Dims<N>& check_dims_0, const Dims<N>& check_dims_1, const Dims<N>& check_dims_2, const Dims<N>& check_dims_3) { for (int i = 0; i < N; ++i) { if (i != skip_dim) { TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i)); } } return MatchingFlatSizeSkipDim(dims, skip_dim, check_dims_1, check_dims_2, check_dims_3); } // Data is required to be contiguous, and so many operators can use either the // full array flat size or the flat size with one dimension skipped (commonly // the depth). inline int FlatSizeSkipDim(const RuntimeShape& shape, int skip_dim) { const int dims_count = shape.DimensionsCount(); TFLITE_DCHECK(skip_dim >= 0 && skip_dim < dims_count); const auto* dims_data = shape.DimsData(); int flat_size = 1; for (int i = 0; i < dims_count; ++i) { flat_size *= (i == skip_dim) ? 1 : dims_data[i]; } return flat_size; } // A combination of MatchingFlatSize() and FlatSizeSkipDim(). inline int MatchingFlatSizeSkipDim(const RuntimeShape& shape, int skip_dim, const RuntimeShape& check_shape_0) { const int dims_count = shape.DimensionsCount(); for (int i = 0; i < dims_count; ++i) { if (i != skip_dim) { TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i)); } } return FlatSizeSkipDim(shape, skip_dim); } inline int MatchingFlatSizeSkipDim(const RuntimeShape& shape, int skip_dim, const RuntimeShape& check_shape_0, const RuntimeShape& check_shape_1) { const int dims_count = shape.DimensionsCount(); for (int i = 0; i < dims_count; ++i) { if (i != skip_dim) { TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i)); } } return MatchingFlatSizeSkipDim(shape, skip_dim, check_shape_1); } inline int MatchingFlatSizeSkipDim(const RuntimeShape& shape, int skip_dim, const RuntimeShape& check_shape_0, const RuntimeShape& check_shape_1, const RuntimeShape& check_shape_2) { const int dims_count = shape.DimensionsCount(); for (int i = 0; i < dims_count; ++i) { if (i != skip_dim) { TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i)); } } return MatchingFlatSizeSkipDim(shape, skip_dim, check_shape_1, check_shape_2); } inline int MatchingFlatSizeSkipDim(const RuntimeShape& shape, int skip_dim, const RuntimeShape& check_shape_0, const RuntimeShape& check_shape_1, const RuntimeShape& check_shape_2, const RuntimeShape& check_shape_3) { const int dims_count = shape.DimensionsCount(); for (int i = 0; i < dims_count; ++i) { if (i != skip_dim) { TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i)); } } return MatchingFlatSizeSkipDim(shape, skip_dim, check_shape_1, check_shape_2, check_shape_3); } template <int N> bool IsPackedWithoutStrides(const Dims<N>& dims) { int expected_stride = 1; for (int d = 0; d < N; d++) { if (dims.strides[d] != expected_stride) return false; expected_stride *= dims.sizes[d]; } return true; } template <int N> void ComputeStrides(Dims<N>* dims) { dims->strides[0] = 1; for (int d = 1; d < N; d++) { dims->strides[d] = dims->strides[d - 1] * dims->sizes[d - 1]; } } enum class BroadcastableOpCategory : uint8_t { kNone, kNonBroadcast, // Matching input shapes. kFirstInputBroadcastsFast, // Fivefold nested loops. kSecondInputBroadcastsFast, // Fivefold nested loops. kGenericBroadcast, // Fall-back. }; struct MinMax { float min; float max; }; static_assert(sizeof(MinMax) == 8, ""); struct ActivationParams { FusedActivationFunctionType activation_type; // uint8_t, etc, activation params. int32_t quantized_activation_min; int32_t quantized_activation_max; }; struct ReluParams : public ActivationParams { int32_t input_offset; int32_t output_offset; int32_t output_multiplier; int output_shift; }; // Styles of resizing op usages. For example, kImageStyle can be used with a Pad // op for pattern-specific optimization. enum class ResizingCategory : uint8_t { kNone, kImageStyle, // 4D, operating on inner dimensions, say {0, a, b, 0}. kGenericResize, }; // For Add, Sub, Mul ops. struct ArithmeticParams { // Shape dependent / common to data / op types. BroadcastableOpCategory broadcast_category; // uint8_t inference params. int32_t input1_offset; int32_t input2_offset; int32_t output_offset; int32_t output_multiplier; int output_shift; // Add / Sub, not Mul, uint8_t inference params. int left_shift; int32_t input1_multiplier; int input1_shift; int32_t input2_multiplier; int input2_shift; // TODO(b/158622529): Union the following activation params. // uint8_t, etc, activation params. int32_t quantized_activation_min; int32_t quantized_activation_max; // float activation params. float float_activation_min; float float_activation_max; // int64_t activation params. int64_t int64_activation_min; int64_t int64_activation_max; // Processed output dimensions. // Let input "a" be the one that broadcasts in the faster-changing dimension. // Then, after coalescing, for shapes {a0, a1, a2, a3, a4} and // {b0, b1, b2, b3, b4}, // broadcast_shape[4] = b0 = a0. // broadcast_shape[3] = b1; a1 = 1. // broadcast_shape[2] = b2 = a2. // broadcast_shape[1] = a3; b3 = 1. // broadcast_shape[0] = b4 = a4. int broadcast_shape[5]; }; struct ConcatenationParams { int8_t axis; const int32_t* input_zeropoint; const float* input_scale; uint16_t inputs_count; int32_t output_zeropoint; float output_scale; }; struct ComparisonParams { // uint8_t inference params. int left_shift; int32_t input1_offset; int32_t input1_multiplier; int input1_shift; int32_t input2_offset; int32_t input2_multiplier; int input2_shift; // Shape dependent / common to inference types. bool is_broadcast; }; struct ConvParams { PaddingType padding_type; PaddingValues padding_values; // TODO(starka): This was just "stride", so check that width+height is OK. int16_t stride_width; int16_t stride_height; int16_t dilation_width_factor; int16_t dilation_height_factor; // uint8_t inference params. // TODO(b/65838351): Use smaller types if appropriate. int32_t input_offset; int32_t weights_offset; int32_t output_offset; int32_t output_multiplier; int output_shift; // uint8_t, etc, activation params. int32_t quantized_activation_min; int32_t quantized_activation_max; // float activation params. float float_activation_min; float float_activation_max; }; struct DepthToSpaceParams { int32_t block_size; }; struct DepthwiseParams { PaddingType padding_type; PaddingValues padding_values; int16_t stride_width; int16_t stride_height; int16_t dilation_width_factor; int16_t dilation_height_factor; int16_t depth_multiplier; // uint8_t inference params. // TODO(b/65838351): Use smaller types if appropriate. int32_t input_offset; int32_t weights_offset; int32_t output_offset; int32_t output_multiplier; int output_shift; // uint8_t, etc, activation params. int32_t quantized_activation_min; int32_t quantized_activation_max; // float activation params. float float_activation_min; float float_activation_max; const int32_t* output_multiplier_per_channel; const int32_t* output_shift_per_channel; }; struct DequantizationParams { double scale; int32_t zero_point; }; struct PerChannelDequantizationParams { const float* scale; const int32_t* zero_point; int32_t quantized_dimension; }; struct FakeQuantParams { MinMax minmax; int32_t num_bits; }; struct FullyConnectedParams { // uint8_t inference params. // TODO(b/65838351): Use smaller types if appropriate. int32_t input_offset; int32_t weights_offset; int32_t output_offset; int32_t output_multiplier; int output_shift; // uint8_t, etc, activation params. int32_t quantized_activation_min; int32_t quantized_activation_max; // float activation params. float float_activation_min; float float_activation_max; // Mark the operands as cacheable if they are unchanging, e.g. weights. bool lhs_cacheable; bool rhs_cacheable; FullyConnectedWeightsFormat weights_format; }; struct GatherParams { int16_t axis; }; struct L2NormalizationParams { // uint8_t inference params. int32_t input_zero_point; }; struct LocalResponseNormalizationParams { int32_t range; double bias; double alpha; double beta; }; struct HardSwishParams { // zero_point of the input activations. int16_t input_zero_point; // zero_point of the output activations. int16_t output_zero_point; // 16bit fixed-point component of the multiplier to apply to go from the // "high-res input scale", which is the input scale multiplied by 2^7, to the // "relu-ish scale", which 3.0/32768. // See the implementation of HardSwishPrepare. int16_t reluish_multiplier_fixedpoint_int16; // exponent/bit-shift component of the aforementioned multiplier. int reluish_multiplier_exponent; // 16bit fixed-point component of the multiplier to apply to go from the // "high-res input scale", which is the input scale multiplied by 2^7, to the // output scale. // See the implementation of HardSwishPrepare. int16_t output_multiplier_fixedpoint_int16; // exponent/bit-shift component of the aforementioned multiplier. int output_multiplier_exponent; }; struct LogisticParams { // uint8_t inference params. int32_t input_zero_point; int32_t input_range_radius; int32_t input_multiplier; int input_left_shift; }; struct LstmCellParams { int32_t weights_zero_point; int32_t accum_multiplier; int accum_shift; int state_integer_bits; }; struct MeanParams { int8_t axis_count; int16_t axis[4]; }; struct PackParams { int8_t axis; const int32_t* input_zeropoint; const float* input_scale; uint16_t inputs_count; int32_t output_zeropoint; float output_scale; }; struct PadParams { int8_t left_padding_count; int32_t left_padding[4]; int8_t right_padding_count; int32_t right_padding[4]; ResizingCategory resizing_category; }; struct PreluParams { int32_t input_offset; int32_t alpha_offset; int32_t output_offset; int32_t output_multiplier_1; int output_shift_1; int32_t output_multiplier_2; int output_shift_2; }; struct PoolParams { FusedActivationFunctionType activation; PaddingType padding_type; PaddingValues padding_values; int stride_height; int stride_width; int filter_height; int filter_width; // uint8_t, etc, activation params. int32_t quantized_activation_min; int32_t quantized_activation_max; // float activation params. float float_activation_min; float float_activation_max; }; struct ReshapeParams { int8_t shape_count; int32_t shape[4]; }; struct ResizeBilinearParams { bool align_corners; // half_pixel_centers assumes pixels are of half the actual dimensions, and // yields more accurate resizes. Corresponds to the same argument for the // original TensorFlow op in TF2.0. bool half_pixel_centers; }; struct ResizeNearestNeighborParams { bool align_corners; bool half_pixel_centers; }; struct SliceParams { int8_t begin_count; int32_t begin[4]; int8_t size_count; int32_t size[4]; }; struct SoftmaxParams { // beta is not really used (not a Tensorflow parameter) and not implemented // for LogSoftmax. double beta; // uint8_t inference params. Used even when beta defaults to 1.0. int32_t input_multiplier; int32_t input_left_shift; // Reverse scaling is only used by LogSoftmax. int32_t reverse_scaling_divisor; int32_t reverse_scaling_right_shift; int diff_min; int32_t zero_point; float scale; float* table; int16_t* exp_lut; int16_t* one_over_one_plus_x_lut; uint8_t* uint8_table1; uint8_t* uint8_table2; }; struct SpaceToBatchParams { // "Zero" padding for uint8_t means padding with the output offset. int32_t output_offset; }; struct SpaceToDepthParams { int32_t block_size; }; struct SplitParams { // Graphs that split into, say, 2000 nodes are encountered. The indices in // OperatorEdges are of type uint16_t. uint16_t num_split; int16_t axis; }; struct SqueezeParams { int8_t squeeze_dims_count; int32_t squeeze_dims[4]; }; struct StridedSliceParams { int8_t start_indices_count; int32_t start_indices[5]; int8_t stop_indices_count; int32_t stop_indices[5]; int8_t strides_count; int32_t strides[5]; int16_t begin_mask; int16_t ellipsis_mask; int16_t end_mask; int16_t new_axis_mask; int16_t shrink_axis_mask; }; struct TanhParams { int32_t input_zero_point; int32_t input_range_radius; int32_t input_multiplier; int input_left_shift; }; struct TransposeParams { int8_t perm_count; int32_t perm[5]; }; struct UnpackParams { uint16_t num_split; int16_t axis; }; struct LeakyReluParams { float alpha; int32_t input_offset; int32_t output_offset; int32_t output_multiplier_alpha; int32_t output_shift_alpha; int32_t output_multiplier_identity; int32_t output_shift_identity; }; template <typename P> inline void SetActivationParams(float min, float max, P* params) { params->float_activation_min = min; params->float_activation_max = max; } template <typename P> inline void SetActivationParams(int32_t min, int32_t max, P* params) { params->quantized_activation_min = min; params->quantized_activation_max = max; } template <typename P> inline void SetActivationParams(int64_t min, int64_t max, P* params) { params->int64_activation_min = min; params->int64_activation_max = max; } template <typename P> inline void GetActivationParams(const P& params, int32_t* min, int32_t* max) { *min = params.quantized_activation_min; *max = params.quantized_activation_max; } template <typename P> inline void GetActivationParams(const P& params, float* min, float* max) { *min = params.float_activation_min; *max = params.float_activation_max; } template <typename P> inline void GetActivationParams(const P& params, int64_t* min, int64_t* max) { *min = params.int64_activation_min; *max = params.int64_activation_max; } } // namespace tflite #endif // TENSORFLOW_LITE_KERNELS_INTERNAL_TYPES_H_
null
184
CWE-787
CVE-2020-15210
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/core/subgraph.h" #include <algorithm> #include <cstdint> #include "tensorflow/lite/arena_planner.h" #include "tensorflow/lite/c/common.h" #include "tensorflow/lite/context_util.h" #include "tensorflow/lite/core/api/tensor_utils.h" #include "tensorflow/lite/delegates/nnapi/nnapi_delegate.h" #include "tensorflow/lite/graph_info.h" #include "tensorflow/lite/minimal_logging.h" #include "tensorflow/lite/schema/schema_generated.h" #include "tensorflow/lite/util.h" namespace tflite { namespace { struct TfLiteQuantizationDeleter { void operator()(TfLiteQuantization* q) { if (q) TfLiteQuantizationFree(q); } }; using ScopedTfLiteQuantization = std::unique_ptr<TfLiteQuantization, TfLiteQuantizationDeleter>; struct TfLiteSparsityDeleter { void operator()(TfLiteSparsity* s) { if (s) TfLiteSparsityFree(s); } }; using ScopedTfLiteSparsity = std::unique_ptr<TfLiteSparsity, TfLiteSparsityDeleter>; TfLiteStatus ReportOpError(TfLiteContext* context, const TfLiteNode& node, const TfLiteRegistration& registration, int node_index, const char* message) { context->ReportError( context, "Node number %d (%s) %s.\n", node_index, registration.custom_name ? registration.custom_name : EnumNameBuiltinOperator( static_cast<BuiltinOperator>(registration.builtin_code)), message); return kTfLiteError; } // Stub method which returns kTfLiteError when the function is forbidden. // We're registering this function to several different function to save // compiled binary size. Please note the restrictions: // * The type of first parameter have to be `TfLiteContext*`. // * All parameters must be trivially destructible. (E.g. No C++ class) TfLiteStatus ForbiddenContextFunction(TfLiteContext* context, ...) { context->ReportError(context, "The function is forbidden if not calling in delegate."); return kTfLiteError; } // Set the ForbiddenContextFunction to a compatible function pointer. template <typename FunctionType> void SetForbiddenContextFunction(FunctionType* func) { *func = reinterpret_cast<FunctionType>(ForbiddenContextFunction); } // Returns true if at least one tensor in the given list is kTfLiteDynamic. template <typename TensorIntArray> bool HasDynamicTensorImpl(const TfLiteContext& context, const TensorIntArray& int_array) { for (int i : int_array) { const TfLiteTensor& tensor = context.tensors[i]; if (tensor.allocation_type == kTfLiteDynamic) { return true; } } return false; } bool HasDynamicTensor(const TfLiteContext& context, const TfLiteIntArray* int_array) { return HasDynamicTensorImpl(context, TfLiteIntArrayView{int_array}); } // Gets the legacy TfLiteQuantizationParams from the current TfLiteQuantization. TfLiteQuantizationParams GetLegacyQuantization( const TfLiteQuantization& quantization) { TfLiteQuantizationParams legacy_quantization; legacy_quantization.scale = 0; legacy_quantization.zero_point = 0; // If the quantization type isn't affine, return the empty // legacy_quantization. if (quantization.type != kTfLiteAffineQuantization) { return legacy_quantization; } auto* affine_quantization = static_cast<TfLiteAffineQuantization*>(quantization.params); if (!affine_quantization || !affine_quantization->scale || !affine_quantization->zero_point || affine_quantization->scale->size != 1 || affine_quantization->zero_point->size != 1) { return legacy_quantization; } // We know its per-layer quantization now. legacy_quantization.scale = affine_quantization->scale->data[0]; legacy_quantization.zero_point = affine_quantization->zero_point->data[0]; return legacy_quantization; } static constexpr const char kUnknownCustomOpName[] = "UnknownCustomOp"; const char* GetTFLiteOpName(const TfLiteRegistration& op_reg) { if (op_reg.builtin_code == tflite::BuiltinOperator_CUSTOM) { const char* const custom_name = op_reg.custom_name; return custom_name ? custom_name : kUnknownCustomOpName; } if (op_reg.builtin_code == tflite::BuiltinOperator_DELEGATE && op_reg.custom_name) { return op_reg.custom_name; } return tflite::EnumNamesBuiltinOperator()[op_reg.builtin_code]; } TfLiteStatus ValidateCustomAllocationForTensor( TfLiteContext* context, const TfLiteTensor* tensor, const TfLiteCustomAllocation& allocation) { TF_LITE_ENSURE(context, allocation.data != nullptr); TF_LITE_ENSURE(context, allocation.bytes >= tensor->bytes); // Ensure provided memory is aligned to what TFLite requires. const intptr_t data_ptr_value = reinterpret_cast<intptr_t>(allocation.data); TF_LITE_ENSURE(context, data_ptr_value % kDefaultTensorAlignment == 0); return kTfLiteOk; } } // namespace // A trivial implementation of GraphInfo around the Interpreter. // NOTE: this interpreter info represents the subset of the // graph that is executed according to execution plan. Thus, // the indices are execution plan indices rather than raw node // indices. class InterpreterInfo : public GraphInfo { public: explicit InterpreterInfo(Subgraph* subgraph) : subgraph_(subgraph) {} size_t num_tensors() const override { return subgraph_->tensors().size(); } TfLiteTensor* tensor(size_t index) override { return &subgraph_->tensors()[index]; } size_t num_execution_nodes() const override { return subgraph_->execution_plan().size(); } size_t num_total_nodes() const override { return subgraph_->nodes_size(); } const TfLiteNode& node(size_t index) const override { int node_index = subgraph_->execution_plan()[index]; return subgraph_->nodes_and_registration()[node_index].first; } size_t node_index(size_t index) const override { return subgraph_->execution_plan()[index]; } const std::vector<int>& inputs() const override { return subgraph_->inputs(); } const std::vector<int>& outputs() const override { return subgraph_->outputs(); } const std::vector<int>& variables() const override { return subgraph_->variables(); } public: Subgraph* subgraph_; }; Subgraph::Subgraph(ErrorReporter* error_reporter, TfLiteExternalContext** external_contexts, std::vector<std::unique_ptr<Subgraph>>* subgraphs, resource::ResourceMap* resources) : external_contexts_(external_contexts), error_reporter_(error_reporter), next_execution_plan_index_to_prepare_(0), next_execution_plan_index_to_plan_allocation_(0), subgraphs_(subgraphs), resources_(resources) { // TODO(b/161272052): Consider a better TfLiteContext initialization pattern: context_.impl_ = static_cast<void*>(this); context_.ResizeTensor = ResizeTensor; context_.ReportError = ReportErrorC; context_.AddTensors = AddTensors; context_.tensors = nullptr; context_.tensors_size = 0; context_.allow_fp32_relax_to_fp16 = false; context_.recommended_num_threads = -1; context_.GetExternalContext = GetExternalContext; context_.SetExternalContext = SetExternalContext; context_.profiler = nullptr; context_.GetTensor = nullptr; context_.GetEvalTensor = nullptr; // Reserve some space for the tensors to avoid excessive resizing. tensors_.reserve(kTensorsReservedCapacity); nodes_and_registration().reserve(kTensorsReservedCapacity); // Invalid to call these these except from TfLiteDelegate SwitchToKernelContext(); } Subgraph::~Subgraph() { for (int node_index = 0; node_index < nodes_and_registration_.size(); ++node_index) { CleanupNode(node_index); } for (size_t i = 0; i < context_.tensors_size; i++) { TfLiteTensor* tensor = &context_.tensors[i]; if (tensor->buffer_handle != kTfLiteNullBufferHandle && tensor->delegate->FreeBufferHandle != nullptr) { tensor->delegate->FreeBufferHandle(&context_, tensor->delegate, &tensor->buffer_handle); } TfLiteTensorFree(tensor); } } void Subgraph::CleanupNode(int node_index) { TfLiteNode& node = nodes_and_registration_[node_index].first; const TfLiteRegistration& registration = nodes_and_registration_[node_index].second; TfLiteIntArrayFree(node.inputs); TfLiteIntArrayFree(node.outputs); TfLiteIntArrayFree(node.temporaries); TfLiteIntArrayFree(node.intermediates); if (node.builtin_data) free(node.builtin_data); OpFree(registration, node.user_data); node.builtin_data = nullptr; } TfLiteStatus Subgraph::ReplaceNodeSubsetsWithDelegateKernels( TfLiteContext* context, TfLiteRegistration registration, const TfLiteIntArray* nodes_to_replace, TfLiteDelegate* delegate) { return static_cast<Subgraph*>(context->impl_) ->ReplaceNodeSubsetsWithDelegateKernels(registration, nodes_to_replace, delegate); } namespace { // Copy a std::vector<int> to an existing TfLiteIntArray. // This is a low-level data manipulation function, and it's caller's // responsibility to ensure TfLiteIntArray has enough size. void CopyVectorToTfLiteIntArray(const std::vector<int>& vec, TfLiteIntArray* arr) { arr->size = vec.size(); memcpy(arr->data, vec.data(), sizeof(int) * arr->size); } // This function allocates a continuous memory space that contains a // TfLiteDelegateParams followed by a several TfLiteIntArray. // When calling `free` at TfLiteDelegateParams*, all the allocated space // will be freed together. // // +-----------------------------------+ // | TfLiteDelegateParams | // | TfLiteDelegate* delegate; | // | TfLiteIntArray* nodes_to_replace; |--\ // | TfLiteIntArray* input_tensors; |--+--\ // | TfLiteIntArray* output_tensors; |--+--+--\ // +-----------------------------------+ | | | // | TfLiteIntArray (variable size) |<-/ | | // +-----------------------------------+ | | // | TfLiteIntArray (variable size) |<----/ | // +-----------------------------------+ | // | TfLiteIntArray (variable size) |<-------/ // +-----------------------------------+ TfLiteDelegateParams* CreateDelegateParams(TfLiteDelegate* delegate, const NodeSubset& node_subset) { // Step 1: Calculate the allocation size. int allocation_size = sizeof(TfLiteDelegateParams); int nodes_to_replace_size = TfLiteIntArrayGetSizeInBytes(node_subset.nodes.size()); allocation_size += nodes_to_replace_size; int input_tensors_size = TfLiteIntArrayGetSizeInBytes(node_subset.input_tensors.size()); allocation_size += input_tensors_size; int output_tensors_size = TfLiteIntArrayGetSizeInBytes(node_subset.output_tensors.size()); allocation_size += output_tensors_size; // Step 2: Allocate the memory. // Use `char*` for conveniently step through the allocated space by bytes. char* allocation = static_cast<char*>(malloc(allocation_size)); // Step 3: Fill all data structures structures. TfLiteDelegateParams* params = reinterpret_cast<TfLiteDelegateParams*>(allocation); params->delegate = delegate; allocation += sizeof(TfLiteDelegateParams); params->nodes_to_replace = reinterpret_cast<TfLiteIntArray*>(allocation); CopyVectorToTfLiteIntArray(node_subset.nodes, params->nodes_to_replace); allocation += nodes_to_replace_size; params->input_tensors = reinterpret_cast<TfLiteIntArray*>(allocation); CopyVectorToTfLiteIntArray(node_subset.input_tensors, params->input_tensors); allocation += input_tensors_size; params->output_tensors = reinterpret_cast<TfLiteIntArray*>(allocation); CopyVectorToTfLiteIntArray(node_subset.output_tensors, params->output_tensors); allocation += output_tensors_size; return params; } // Assumes that params is not nullptr. void PopulatePreviewDelegateParams(const NodeSubset& node_subset, TfLiteDelegateParams* params) { // Since these params are used for previewing partitioning, params->delegate // is not required. params->delegate = nullptr; params->nodes_to_replace = TfLiteIntArrayCreate(node_subset.nodes.size()); CopyVectorToTfLiteIntArray(node_subset.nodes, params->nodes_to_replace); params->input_tensors = TfLiteIntArrayCreate(node_subset.input_tensors.size()); CopyVectorToTfLiteIntArray(node_subset.input_tensors, params->input_tensors); params->output_tensors = TfLiteIntArrayCreate(node_subset.output_tensors.size()); CopyVectorToTfLiteIntArray(node_subset.output_tensors, params->output_tensors); } } // namespace TfLiteStatus Subgraph::ReplaceNodeSubsetsWithDelegateKernels( TfLiteRegistration registration, const TfLiteIntArray* nodes_to_replace, TfLiteDelegate* delegate) { // Ignore empty node replacement sets. if (!nodes_to_replace->size) { return kTfLiteOk; } // Annotate the registration as DELEGATE op. registration.builtin_code = BuiltinOperator_DELEGATE; // Analyze the graph to find all independent node_subsets that are either // fully not-this-delegate or this-delegate computation. InterpreterInfo info(this); std::vector<NodeSubset> node_subsets; PartitionGraphIntoIndependentNodeSubsets(&info, nodes_to_replace, &node_subsets); TFLITE_LOG( tflite::TFLITE_LOG_INFO, "Replacing %d node(s) with delegate (%s) node, yielding %zu partitions.", nodes_to_replace->size, registration.custom_name ? registration.custom_name : "unknown", node_subsets.size()); execution_plan_.clear(); for (auto& node_subset : node_subsets) { // Subsets claimed by the delegate should have a "macro" op created, the // other node_subsets (kTfNonPartition) just have their nodes added back to // the execution plan. switch (node_subset.type) { case NodeSubset::kTfNonPartition: for (auto it = node_subset.nodes.begin(); it != node_subset.nodes.end(); ++it) { execution_plan_.push_back(*it); } break; case NodeSubset::kTfPartition: { int node_index; TfLiteDelegateParams* params = CreateDelegateParams(delegate, node_subset); TF_LITE_ENSURE_STATUS(AddNodeWithParameters( node_subset.input_tensors, node_subset.output_tensors, {}, nullptr, 0, params, &registration, &node_index)); // Initialize the output tensors's delegate-related fields. for (int tensor_index : node_subset.output_tensors) { TfLiteTensor* tensor = &tensors_[tensor_index]; TF_LITE_ENSURE(&context_, tensor->delegate == nullptr || tensor->delegate == delegate); tensor->delegate = delegate; } // Associate the node with the delegate. TfLiteNode* node = &nodes_and_registration_[node_index].first; node->delegate = delegate; } break; case NodeSubset::kTfUnexplored: return kTfLiteError; break; } } return kTfLiteOk; } TfLiteExternalContext* Subgraph::GetExternalContext( TfLiteExternalContextType type) { if (static_cast<int>(type) >= 0 && type < kTfLiteMaxExternalContexts) { return external_contexts_[type]; } return nullptr; } TfLiteExternalContext* Subgraph::GetExternalContext( struct TfLiteContext* context, TfLiteExternalContextType type) { return static_cast<Subgraph*>(context->impl_)->GetExternalContext(type); } void Subgraph::SetExternalContext(TfLiteExternalContextType type, TfLiteExternalContext* ctx) { if (static_cast<int>(type) >= 0 && type < kTfLiteMaxExternalContexts) { external_contexts_[type] = ctx; } } void Subgraph::SetExternalContext(struct TfLiteContext* context, TfLiteExternalContextType type, TfLiteExternalContext* ctx) { return static_cast<Subgraph*>(context->impl_)->SetExternalContext(type, ctx); } // Gets an TfLiteIntArray* representing the execution plan. The interpreter owns // this memory and it is only guaranteed to exist during the invocation of the // delegate prepare. TfLiteStatus Subgraph::GetExecutionPlan(TfLiteIntArray** execution_plan) { // TODO(aselle): Do not make a copy here plan_cache_.reset(TfLiteIntArrayCreate(execution_plan_.size())); *execution_plan = plan_cache_.get(); static_assert(sizeof(plan_cache_->data[0]) == sizeof(execution_plan_[0]), "TfLiteIntArray and execution_plan do not contain same type."); std::memcpy(plan_cache_->data, execution_plan_.data(), sizeof(plan_cache_->data[0]) * execution_plan_.size()); return kTfLiteOk; } // WARNING: This is an experimental interface that is subject to change. // Entry point for C node plugin API to get the execution plan TfLiteStatus Subgraph::GetExecutionPlan(struct TfLiteContext* context, TfLiteIntArray** execution_plan) { return static_cast<Subgraph*>(context->impl_) ->GetExecutionPlan(execution_plan); } void Subgraph::FreeDelegatePartitioningData() { for (auto& params : partitioning_preview_cache_) { TfLiteIntArrayFree(params.nodes_to_replace); TfLiteIntArrayFree(params.input_tensors); TfLiteIntArrayFree(params.output_tensors); } partitioning_preview_cache_.clear(); } TfLiteStatus Subgraph::PreviewDelegatePartitioning( const TfLiteIntArray* nodes_to_replace, TfLiteDelegateParams** partition_params_array, int* num_partitions) { // Ensure partitioning cache is empty. FreeDelegatePartitioningData(); // Defaults. if (!partition_params_array || !num_partitions) return kTfLiteError; *partition_params_array = nullptr; *num_partitions = 0; if (!nodes_to_replace->size) { return kTfLiteOk; } // Partition the execution plan into node subsets. InterpreterInfo info(this); std::vector<NodeSubset> node_subsets; PartitionGraphIntoIndependentNodeSubsets(&info, nodes_to_replace, &node_subsets); // Create one TfLiteDelegateParams per node-subset which would be delegated. for (auto& node_subset : node_subsets) { if (node_subset.type != NodeSubset::kTfPartition) { continue; } partitioning_preview_cache_.emplace_back(); PopulatePreviewDelegateParams(node_subset, &partitioning_preview_cache_.back()); ++*num_partitions; } *partition_params_array = partitioning_preview_cache_.data(); return kTfLiteOk; } TfLiteStatus Subgraph::PreviewDelegatePartitioning( struct TfLiteContext* context, const TfLiteIntArray* nodes_to_replace, TfLiteDelegateParams** partition_params_array, int* num_partitions) { return static_cast<Subgraph*>(context->impl_) ->PreviewDelegatePartitioning(nodes_to_replace, partition_params_array, num_partitions); } TfLiteStatus Subgraph::SetInputs(std::vector<int> inputs) { TF_LITE_ENSURE_OK(&context_, CheckTensorIndices("inputs", inputs.data(), inputs.size())); inputs_ = std::move(inputs); return kTfLiteOk; } TfLiteStatus Subgraph::SetOutputs(std::vector<int> outputs) { TF_LITE_ENSURE_OK( &context_, CheckTensorIndices("outputs", outputs.data(), outputs.size())); outputs_ = std::move(outputs); return kTfLiteOk; } TfLiteStatus Subgraph::SetVariables(std::vector<int> variables) { TF_LITE_ENSURE_OK(&context_, CheckTensorIndices("variables", variables.data(), variables.size())); variables_ = std::move(variables); return kTfLiteOk; } void Subgraph::SetCancellationFunction(void* data, bool (*check_cancelled_func)(void*)) { cancellation_data_ = data; check_cancelled_func_ = check_cancelled_func; } bool Subgraph::IsCancelled() { return (check_cancelled_func_ != nullptr) && (*check_cancelled_func_)(cancellation_data_); } void Subgraph::ReserveNodes(int count) { nodes_and_registration_.reserve(count); } TfLiteStatus Subgraph::CheckTensorIndices(const char* label, const int* indices, int length) { // Making sure kTfLiteOptionalTensor is not re-defined to something other than // -1. static_assert(kTfLiteOptionalTensor == -1, "kTfLiteOptionalTensor should be defined -1"); for (int i = 0; i < length; i++) { int index = indices[i]; // Continue if index == kTfLiteOptionalTensor before additional comparisons // below, size_t(-1) is always >= context_tensors_size. if (index == kTfLiteOptionalTensor) { continue; } if (index < 0 || static_cast<size_t>(index) >= context_.tensors_size) { ReportError( "Invalid tensor index %d in %s. The subgraph has %d tensors\n", index, label, context_.tensors_size); consistent_ = false; return kTfLiteError; } } return kTfLiteOk; } namespace { // Multiply two sizes and return true if overflow occurred; // This is based off tensorflow/overflow.h but is simpler as we already // have unsigned numbers. It is also generalized to work where sizeof(size_t) // is not 8. TfLiteStatus MultiplyAndCheckOverflow(size_t a, size_t b, size_t* product) { // Multiplying a * b where a and b are size_t cannot result in overflow in a // size_t accumulator if both numbers have no non-zero bits in their upper // half. constexpr size_t size_t_bits = 8 * sizeof(size_t); constexpr size_t overflow_upper_half_bit_position = size_t_bits / 2; *product = a * b; // If neither integers have non-zero bits past 32 bits can't overflow. // Otherwise check using slow devision. if (TFLITE_EXPECT_FALSE((a | b) >> overflow_upper_half_bit_position != 0)) { if (a != 0 && *product / a != b) return kTfLiteError; } return kTfLiteOk; } } // namespace TfLiteStatus Subgraph::BytesRequired(TfLiteType type, const int* dims, size_t dims_size, size_t* bytes) { TF_LITE_ENSURE(&context_, bytes != nullptr); size_t count = 1; for (int k = 0; k < dims_size; k++) { size_t old_count = count; TF_LITE_ENSURE_MSG( &context_, MultiplyAndCheckOverflow(old_count, dims[k], &count) == kTfLiteOk, "BytesRequired number of elements overflowed.\n"); } size_t type_size = 0; TF_LITE_ENSURE_OK(&context_, GetSizeOfType(&context_, type, &type_size)); TF_LITE_ENSURE_MSG( &context_, MultiplyAndCheckOverflow(type_size, count, bytes) == kTfLiteOk, "BytesRequired number of bytes overflowed.\n"); return kTfLiteOk; } TfLiteStatus Subgraph::AllocateTensors() { TFLITE_SCOPED_TAGGED_DEFAULT_PROFILE(profiler_.get(), "AllocateTensors"); if (!consistent_) { ReportError("AllocateTensors() called on inconsistent model."); return kTfLiteError; } // Restore delegation state if applicable. TF_LITE_ENSURE_STATUS(RedoAllDelegates()); // Explicit (re)allocation is necessary if nodes have been changed or tensors // have been resized. For inputs marked as dynamic, we can't short-circuit the // allocation as the client may have done the resize manually. if (state_ != kStateUninvokable && !HasDynamicTensorImpl(context_, inputs())) { if (memory_planner_ && !memory_planner_->HasNonPersistentMemory()) { // If the only change was the release of non-persistent memory via // ReleaseNonPersistentMemory(), just re-allocate it. For any other type // of memory-planning change (for eg, ResizeInputTensor), the state would // be kStateUninvokable. memory_planner_->AcquireNonPersistentMemory(); } return kTfLiteOk; } next_execution_plan_index_to_prepare_ = 0; next_execution_plan_index_to_plan_allocation_ = 0; next_original_execution_plan_index_to_prepare_ = 0; if (memory_planner_) { TF_LITE_ENSURE_STATUS(memory_planner_->ResetAllocations()); } TF_LITE_ENSURE_STATUS(PrepareOpsAndTensors()); state_ = kStateInvokable; // Reset the variable tensors to zero after (re)allocating the tensors. // Developers shouldn't rely on the side effect of this function to reset // variable tensors. They should call `ResetVariableTensors` directly // instead. ResetVariableTensors(); return kTfLiteOk; } // TODO(ycling): Support non-zero default values. TfLiteStatus Subgraph::ResetVariableTensors() { for (auto& tensor : tensors_) { if (!tensor.is_variable) { continue; } if (tensor.allocation_type == kTfLiteArenaRwPersistent) { // If variable tensors allocation type is `kTfLiteArenaRwPersistent`, then // they must be allocated after the initial `PrepareOpsAndTensors()` is // called. TF_LITE_ENSURE(&context_, tensor.data.raw != nullptr); tflite::ResetVariableTensor(&tensor); } else { // If variable tensors allocation type is not `kTfLiteArenaRwPersistent`, // then it can only be `kTfLiteCustom` in which case, we do not reset it. TF_LITE_ENSURE_EQ(&context_, tensor.allocation_type, kTfLiteCustom); } } return kTfLiteOk; } TfLiteStatus Subgraph::AddNodeWithParameters( const std::vector<int>& inputs, const std::vector<int>& outputs, const std::vector<int>& intermediates, const char* init_data, size_t init_data_size, void* builtin_data, const TfLiteRegistration* registration, int* node_index) { std::unique_ptr<void, decltype(free)*> builtin_data_deleter(builtin_data, free); if (state_ == kStateInvokableAndImmutable) { ReportError("AddNodeWithParameters is disallowed when graph is immutable."); return kTfLiteError; } state_ = kStateUninvokable; TF_LITE_ENSURE_OK(&context_, CheckTensorIndices("node inputs", inputs.data(), inputs.size())); TF_LITE_ENSURE_OK( &context_, CheckTensorIndices("node outputs", outputs.data(), outputs.size())); int new_node_index = nodes_and_registration_.size(); if (node_index) *node_index = new_node_index; nodes_and_registration_.resize(nodes_and_registration_.size() + 1); auto& node_and_reg = nodes_and_registration_.back(); TfLiteNode& node = node_and_reg.first; if (node.inputs) TfLiteIntArrayFree(node.inputs); if (node.outputs) TfLiteIntArrayFree(node.outputs); if (node.intermediates) TfLiteIntArrayFree(node.intermediates); if (node.temporaries) TfLiteIntArrayFree(node.temporaries); // NOTE, here we are not using move semantics yet, since our internal // representation isn't std::vector, but in the future we would like to avoid // copies, so we want the interface to take r-value references now. node.inputs = ConvertVectorToTfLiteIntArray(inputs); node.outputs = ConvertVectorToTfLiteIntArray(outputs); node.intermediates = ConvertVectorToTfLiteIntArray(intermediates); node.temporaries = TfLiteIntArrayCreate(0); if (init_data) { node.user_data = OpInit(*registration, init_data, init_data_size); } else { node.user_data = OpInit( *registration, static_cast<const char*>(builtin_data_deleter.get()), 0); } node.builtin_data = builtin_data_deleter.release(); // TODO(ycling): Filling `custom_initial_data` and `custom_initial_data_size` // properly for nodes generated by ReplaceNodeSubsetsWithDelegateKernels. if (registration->builtin_code == BuiltinOperator_CUSTOM) { // When it's a CUSTOM op, the `custom_options` field in the Flatbuffer // `Operator` table is passed in. node.custom_initial_data = init_data; node.custom_initial_data_size = init_data_size; } else { node.custom_initial_data = nullptr; node.custom_initial_data_size = 0; } node.delegate = nullptr; // Copying of registration is required to support unresolved custom ops. node_and_reg.second = *registration; execution_plan_.push_back(new_node_index); return kTfLiteOk; } TfLiteStatus Subgraph::ResizeInputTensor(int tensor_index, const std::vector<int>& dims) { const bool delegates_applied = !pre_delegation_execution_plan_.empty(); const bool graph_is_immutable = state_ == kStateInvokableAndImmutable; if (graph_is_immutable && !delegates_applied) { ReportError("ResizeInputTensor is disallowed when graph is immutable."); return kTfLiteError; } // TODO(aselle): All bounds checks can be implemented as one-sided bounds // checks by casting to unsigned for efficiency. Profile before doing this. TF_LITE_ENSURE(&context_, tensor_index < context_.tensors_size && tensor_index >= 0); TfLiteTensor* tensor = &context_.tensors[tensor_index]; // Short-circuit the state change if the dimensions don't change, avoiding // unnecessary (re)allocations. // // Note that it's required to check `tensor->data.raw != nullptr`. Otherwise // the subgraph won't allocate memory for a dynamic tensor when its size // is equal to the original tensor size. if (tensor->data.raw != nullptr && EqualArrayAndTfLiteIntArray(tensor->dims, dims.size(), dims.data())) { return kTfLiteOk; } if (graph_is_immutable) { // Undo delegation if it resulted in the graph being immutable. TF_LITE_ENSURE_STATUS(UndoAllDelegates()); } state_ = kStateUninvokable; return ResizeTensorImpl(tensor, ConvertVectorToTfLiteIntArray(dims)); } TfLiteStatus Subgraph::ResizeInputTensorStrict(int tensor_index, const std::vector<int>& dims) { TF_LITE_ENSURE(&context_, tensor_index < context_.tensors_size && tensor_index >= 0); TfLiteTensor* tensor = &context_.tensors[tensor_index]; // Ensure that only unknown dimensions can be resized. TF_LITE_ENSURE_EQ(&context_, tensor->dims->size, dims.size()); for (size_t idx = 0; idx < dims.size(); idx++) { // `dims_signature` is not defined when no unknown dimensions are present. int dim_signature; if (tensor->dims_signature && tensor->dims_signature->size) { dim_signature = tensor->dims_signature->data[idx]; } else { dim_signature = tensor->dims->data[idx]; } if (dim_signature != -1 && dim_signature != dims[idx]) { ReportError( "Attempting to resize dimension %d of tensor %d with value %d to %d. " "ResizeInputTensorStrict only allows mutating unknown dimensions " "identified by -1.", idx, tensor_index, dim_signature, dims[idx]); return kTfLiteError; } } return ResizeInputTensor(tensor_index, dims); } TfLiteStatus Subgraph::ReleaseNonPersistentMemory() { if (memory_planner_) { TF_LITE_ENSURE_STATUS(memory_planner_->ReleaseNonPersistentMemory()); } return kTfLiteOk; } TfLiteStatus Subgraph::OpPrepare(const TfLiteRegistration& op_reg, TfLiteNode* node) { if (op_reg.prepare == nullptr) { // Check if it's an unresolved custom op. if (IsUnresolvedCustomOp(op_reg)) { if (IsFlexOp(op_reg.custom_name)) { ReportError( "Regular TensorFlow ops are not supported by this interpreter. " "Make sure you apply/link the Flex delegate before inference."); } else { ReportError("Encountered unresolved custom op: %s.", op_reg.custom_name ? op_reg.custom_name : "UnknownOp"); } return kTfLiteError; } // Resolved ops can have a null Prepare function. return kTfLiteOk; } return op_reg.prepare(&context_, node); } TfLiteStatus Subgraph::PrepareOpsStartingAt( int first_execution_plan_index, const std::vector<int>& execution_plan, int* last_execution_plan_index_prepared) { if (first_execution_plan_index == 0) { has_dynamic_tensors_ = false; } for (int execution_plan_index = first_execution_plan_index; execution_plan_index < execution_plan.size(); execution_plan_index++) { int node_index = execution_plan[execution_plan_index]; TfLiteNode& node = nodes_and_registration_[node_index].first; const TfLiteRegistration& registration = nodes_and_registration_[node_index].second; EnsureTensorsVectorCapacity(); if (OpPrepare(registration, &node) != kTfLiteOk) { return ReportOpError(&context_, node, registration, node_index, "failed to prepare"); } *last_execution_plan_index_prepared = execution_plan_index; // Discontinue if the node has dynamic outputs. Note that we don't // stop for dynamic temporary tensors since they won't affect the // sizes of other tensors in the graph. if (HasDynamicTensor(context_, node.outputs)) { has_dynamic_tensors_ = true; return kTfLiteOk; } } return kTfLiteOk; } TfLiteStatus Subgraph::PrepareOpsAndTensors() { if (!memory_planner_) { memory_planner_.reset(new ArenaPlanner( &context_, std::unique_ptr<GraphInfo>(new InterpreterInfo(this)), /*preserve_inputs=*/true, /*preserve_intermediates*/ false, kDefaultTensorAlignment)); memory_planner_->PlanAllocations(); } // Prepare original execution plan if any applied delegate wants it. // If any of the delegates is immutable, this won't be triggered // post-delegation (since we undo/redo delegation). For all other cases, other // delegates that do shape propagation themselves would still be able to. bool prepare_original_plan = false; if (!pre_delegation_execution_plan_.empty()) { for (int i = 0; i < delegates_applied_.size(); ++i) { if ((delegates_applied_[i]->flags & kTfLiteDelegateFlagsRequirePropagatedShapes)) { prepare_original_plan = true; break; } } } if (prepare_original_plan) { int last_original_exec_plan_index_prepared = 0; TF_LITE_ENSURE_STATUS(PrepareOpsStartingAt( next_execution_plan_index_to_prepare_, pre_delegation_execution_plan_, &last_original_exec_plan_index_prepared)); next_original_execution_plan_index_to_prepare_ = last_original_exec_plan_index_prepared + 1; } int last_exec_plan_index_prepared = 0; TF_LITE_ENSURE_STATUS( PrepareOpsStartingAt(next_execution_plan_index_to_prepare_, execution_plan_, &last_exec_plan_index_prepared)); next_execution_plan_index_to_prepare_ = last_exec_plan_index_prepared + 1; // Execute arena allocations. TF_LITE_ENSURE_STATUS(memory_planner_->ExecuteAllocations( next_execution_plan_index_to_plan_allocation_, last_exec_plan_index_prepared)); // Ensure custom allocations are still valid for applicable tensors. // This causes some extra validations for cases with dynamic tensors, but the // overhead should be minimal since the number of custom-allocated tensors // will typically be low. for (int i = 0; i < custom_allocations_.size(); ++i) { auto idx_and_alloc = custom_allocations_[i]; auto& tensor = tensors()[idx_and_alloc.first]; const auto& alloc = idx_and_alloc.second; TF_LITE_ENSURE(context(), tensor.allocation_type == kTfLiteCustom); TF_LITE_ENSURE_STATUS( ValidateCustomAllocationForTensor(context(), &tensor, alloc)); } next_execution_plan_index_to_plan_allocation_ = last_exec_plan_index_prepared + 1; return kTfLiteOk; } TfLiteStatus Subgraph::Invoke() { if (!consistent_) { ReportError("Invoke called on model that is not consistent."); return kTfLiteError; } TfLiteStatus status = kTfLiteOk; if (state_ == kStateUninvokable) { ReportError("Invoke called on model that is not ready."); return kTfLiteError; } else if (memory_planner_ && !memory_planner_->HasNonPersistentMemory()) { ReportError("Non-persistent memory is not available."); return kTfLiteError; } // This is only needed for UseNNAPI(true); if (should_apply_nnapi_delegate_ && !applied_nnapi_delegate_) { TF_LITE_ENSURE_OK(&context_, ModifyGraphWithDelegate(NnApiDelegate())); // only need to modify the graph once upon the first invocation. applied_nnapi_delegate_ = true; } // Invocations are always done in node order. // Note that calling Invoke repeatedly will cause the original memory plan to // be reused, unless either ResizeInputTensor() or AllocateTensors() has been // called. for (int execution_plan_index = 0; execution_plan_index < execution_plan_.size(); execution_plan_index++) { if (execution_plan_index == next_execution_plan_index_to_prepare_) { TF_LITE_ENSURE_STATUS(PrepareOpsAndTensors()); TF_LITE_ENSURE(&context_, next_execution_plan_index_to_prepare_ >= execution_plan_index); } int node_index = execution_plan_[execution_plan_index]; TfLiteNode& node = nodes_and_registration_[node_index].first; const TfLiteRegistration& registration = nodes_and_registration_[node_index].second; const char* op_name = nullptr; if (profiler_) op_name = GetTFLiteOpName(registration); TFLITE_SCOPED_TAGGED_OPERATOR_PROFILE(profiler_.get(), op_name, node_index); // TODO(ycling): This is an extra loop through inputs to check if the data // need to be copied from Delegate buffer to raw memory, which is often not // needed. We may want to cache this in prepare to know if this needs to be // done for a node or not. for (int i = 0; i < node.inputs->size; ++i) { int tensor_index = node.inputs->data[i]; if (tensor_index == kTfLiteOptionalTensor) { continue; } TfLiteTensor* tensor = &tensors_[tensor_index]; if (tensor->delegate && tensor->delegate != node.delegate && tensor->data_is_stale) { TF_LITE_ENSURE_STATUS(EnsureTensorDataIsReadable(tensor_index)); } } if (check_cancelled_func_ != nullptr && check_cancelled_func_(cancellation_data_)) { ReportError("Client requested cancel during Invoke()"); return kTfLiteError; } EnsureTensorsVectorCapacity(); tensor_resized_since_op_invoke_ = false; if (OpInvoke(registration, &node) != kTfLiteOk) { return ReportOpError(&context_, node, registration, node_index, "failed to invoke"); } // Force execution prep for downstream ops if the latest op triggered the // resize of a dynamic tensor. if (tensor_resized_since_op_invoke_ && HasDynamicTensor(context_, node.outputs)) { next_execution_plan_index_to_prepare_ = execution_plan_index + 1; // This happens when an intermediate dynamic tensor is resized. // We don't have to prepare all the ops, but we need to recompute // the allocation plan. if (next_execution_plan_index_to_plan_allocation_ > next_execution_plan_index_to_prepare_) { next_execution_plan_index_to_plan_allocation_ = next_execution_plan_index_to_prepare_; if (memory_planner_) { TF_LITE_ENSURE_STATUS(memory_planner_->ResetAllocationsAfter( next_execution_plan_index_to_plan_allocation_ - 1)); } } } } return status; } TfLiteStatus Subgraph::ResizeTensor(TfLiteContext* context, TfLiteTensor* tensor, TfLiteIntArray* new_size) { // If the dimensions don't change, avoiding // unnecessary (re)allocations. // // Note that it's required to check `tensor->data.raw != nullptr`. Otherwise // the subgraph won't allocate memory for a dynamic tensor when its size // is equal to the original tensor size. if (tensor->data.raw != nullptr && EqualArrayAndTfLiteIntArray(tensor->dims, new_size->size, new_size->data)) { // A number of clients assume |new_size| remains valid upon success, so // swap it in as the new (but logically identical) tensor dims. TfLiteIntArrayFree(tensor->dims); tensor->dims = new_size; return kTfLiteOk; } // Note here that context->impl_ is recovering the this pointer for an // instance of Interpreter to call into the member function ResizeTensorImpl // (this function is static). return static_cast<Subgraph*>(context->impl_) ->ResizeTensorImpl(tensor, new_size); } void Subgraph::ReportErrorImpl(const char* format, va_list args) { error_reporter_->Report(format, args); } void Subgraph::ReportErrorC(TfLiteContext* context, const char* format, ...) { va_list args; va_start(args, format); auto* f = static_cast<Subgraph*>(context->impl_); // Note here that context->impl_ is recovering the this pointer for an // instance of Subgraph to call into the member function ReportErrorImpl // (this function is static). f->ReportErrorImpl(format, args); va_end(args); } // Entry point for C node plugin API to report an error. void Subgraph::ReportError(const char* format, ...) { va_list args; va_start(args, format); auto* f = static_cast<Subgraph*>(context_.impl_); // Note here that context->impl_ is recovering the this pointer for an // instance of Subgraph to call into the member function ReportErrorImpl // (this function is static). f->ReportErrorImpl(format, args); va_end(args); } TfLiteStatus Subgraph::AddTensors(int tensors_to_add, int* first_new_tensor_index) { const size_t base_index = tensors_.size(); if (first_new_tensor_index) *first_new_tensor_index = base_index; tensors_.resize(tensors_.size() + tensors_to_add); for (size_t i = base_index; i < tensors_.size(); i++) { memset(&tensors_[i], 0, sizeof(tensors_[i])); tensors_[i].buffer_handle = kTfLiteNullBufferHandle; } context_.tensors = tensors_.data(); context_.tensors_size = tensors_.size(); return kTfLiteOk; } TfLiteStatus Subgraph::AddTensors(TfLiteContext* context, int tensors_to_add, int* first_new_tensor_index) { // Note here that context->impl_ is recovering the this pointer for an // instance of Interpreter to call into the member function AddTensors // (this function is static). return static_cast<Subgraph*>(context->impl_) ->AddTensors(tensors_to_add, first_new_tensor_index); } TfLiteStatus Subgraph::GetNodeAndRegistration( int node_index, TfLiteNode** node, TfLiteRegistration** registration) { TF_LITE_ENSURE(&context_, node_index >= 0); auto nodes_size = nodes_and_registration_.size(); TF_LITE_ENSURE(&context_, static_cast<size_t>(node_index) < nodes_size); TF_LITE_ENSURE(&context_, node != nullptr && registration != nullptr); auto& node_and_reg = nodes_and_registration_[node_index]; *node = &node_and_reg.first; *registration = &node_and_reg.second; return kTfLiteOk; } TfLiteStatus Subgraph::GetNodeAndRegistration( struct TfLiteContext* context, int node_index, TfLiteNode** node, TfLiteRegistration** registration) { return static_cast<Subgraph*>(context->impl_) ->GetNodeAndRegistration(node_index, node, registration); } TfLiteStatus Subgraph::SetTensorParametersReadOnly( int tensor_index, TfLiteType type, const char* name, const size_t rank, const int* dims, TfLiteQuantization quantization, const char* buffer, size_t bytes, const Allocation* allocation, TfLiteSparsity* sparsity) { // Ensure quantization cleanup on failure. ScopedTfLiteQuantization scoped_quantization(&quantization); ScopedTfLiteSparsity scoped_sparsity(sparsity); if (state_ == kStateInvokableAndImmutable) { ReportError( "SetTensorParametersReadOnly is disallowed when graph is immutable."); return kTfLiteError; } TF_LITE_ENSURE(&context_, tensor_index < context_.tensors_size && tensor_index >= 0); // For most tensors we know exactly how much memory is necessary so we can // ensure the buffer is large enough. However, we need to skip string tensors // and sparse tensors because their sizes change with the contents. // TODO(b/145615516): Extend BytesRequired to check sparse tensors. if (type != kTfLiteString && sparsity == nullptr) { size_t required_bytes; TF_LITE_ENSURE_OK(&context_, BytesRequired(type, dims, rank, &required_bytes)); TF_LITE_ENSURE_EQ(&context_, required_bytes, bytes); } TfLiteTensor& tensor = context_.tensors[tensor_index]; if (type == tensor.type && EqualArrayAndTfLiteIntArray(tensor.dims, rank, dims)) { // Fast path which does not invalidate the invokable property. TfLiteTensorDataFree(&tensor); TfLiteQuantizationFree(&tensor.quantization); tensor.data.raw = const_cast<char*>(buffer); if (!tensor.dims) tensor.dims = ConvertArrayToTfLiteIntArray(rank, dims); tensor.params = GetLegacyQuantization(quantization); tensor.quantization = *scoped_quantization.release(); tensor.sparsity = scoped_sparsity.release(); tensor.allocation_type = kTfLiteMmapRo; tensor.allocation = allocation; } else { state_ = kStateUninvokable; TfLiteTensorReset(type, name, ConvertArrayToTfLiteIntArray(rank, dims), GetLegacyQuantization(quantization), const_cast<char*>(buffer), bytes, kTfLiteMmapRo, allocation, false, &tensor); // TODO(suharshs): Update TfLiteTensorReset to include the new quantization // if there are other required callers. tensor.quantization = *scoped_quantization.release(); tensor.sparsity = scoped_sparsity.release(); } return kTfLiteOk; } // Set description of inputs/outputs/data/fptrs for node `node_index`. // This variant assumes an external buffer has been allocated of size // bytes. The lifetime of buffer must be ensured to be greater or equal // to Interpreter. TfLiteStatus Subgraph::SetTensorParametersReadWrite( int tensor_index, TfLiteType type, const char* name, const size_t rank, const int* dims, TfLiteQuantization quantization, bool is_variable, const size_t rank_dims_signature, const int* dims_signature) { // Ensure quantization cleanup on failure. ScopedTfLiteQuantization scoped_quantization(&quantization); if (state_ == kStateInvokableAndImmutable) { ReportError( "SetTensorParametersReadWrite is disallowed when graph is immutable."); return kTfLiteError; } TF_LITE_ENSURE(&context_, tensor_index < context_.tensors_size && tensor_index >= 0); size_t required_bytes = 0; if (type != kTfLiteString) { // These types will be allocated in our arena so we need to record how // many bytes we will need based on the dimensions. String tensors are // allocated dynamically and we can't know ahead of time how much space // they will require. TF_LITE_ENSURE_OK(&context_, BytesRequired(type, dims, rank, &required_bytes)); } TfLiteAllocationType allocation_type = kTfLiteArenaRw; if (type == kTfLiteString) { if (is_variable) { // We don't have a real use case for string variable tensor. ReportError("String variable tensor isn't supported."); return kTfLiteError; } allocation_type = kTfLiteDynamic; } else if (is_variable) { allocation_type = kTfLiteArenaRwPersistent; } TfLiteTensor& tensor = context_.tensors[tensor_index]; TfLiteTensorReset(type, name, ConvertArrayToTfLiteIntArray(rank, dims), GetLegacyQuantization(quantization), /*buffer=*/nullptr, required_bytes, allocation_type, nullptr, is_variable, &tensor); // TODO(suharshs): Update TfLiteTensorReset to include the new quantization // if there are other required callers. tensor.quantization = *scoped_quantization.release(); tensor.dims_signature = ConvertArrayToTfLiteIntArray(rank_dims_signature, dims_signature); return kTfLiteOk; } TfLiteStatus Subgraph::SetExecutionPlan(const std::vector<int>& new_plan) { for (int node_index : new_plan) { TF_LITE_ENSURE(&context_, node_index >= 0 && node_index < nodes_and_registration_.size()); } execution_plan_ = new_plan; return kTfLiteOk; } TfLiteStatus Subgraph::ResizeTensorImpl(TfLiteTensor* tensor, TfLiteIntArray* new_size) { // Note that in theory we could resize kTfLiteArenaRwPersistent tensors too. if (tensor->allocation_type == kTfLiteArenaRw || tensor->allocation_type == kTfLiteDynamic || tensor->allocation_type == kTfLiteArenaRwPersistent || tensor->allocation_type == kTfLitePersistentRo || tensor->allocation_type == kTfLiteCustom) { tensor_resized_since_op_invoke_ |= TfLiteIntArrayEqual(tensor->dims, new_size) == 0; if (tensor->type != kTfLiteString) { size_t bytesRequired; TfLiteStatus status = BytesRequired(tensor->type, new_size->data, new_size->size, &bytesRequired); if (status != kTfLiteOk) { TfLiteIntArrayFree(new_size); return kTfLiteError; } // Realloc space for heap-allocated tensors. TfLiteTensorRealloc(bytesRequired, tensor); tensor->bytes = bytesRequired; } if (tensor->dims) TfLiteIntArrayFree(tensor->dims); tensor->dims = new_size; // Reset arena-allocated tensors; they will be allocated later. if (tensor->allocation_type == kTfLiteArenaRw || tensor->allocation_type == kTfLiteArenaRwPersistent) { tensor->data.raw = nullptr; } } else { // kTfLiteMmapRo tensors are stored in the flatbuffer and are therefore // of fixed size. TfLiteIntArrayFree(new_size); ReportError("Attempting to resize a fixed-size tensor."); return kTfLiteError; } return kTfLiteOk; } void Subgraph::UseNNAPI(bool enable) { // Note that there is no way to disable the delegate once it modified the // graph. if (applied_nnapi_delegate_ && !enable) { ReportError("Attempting to disable NNAPI delegate after it's applied."); } else { should_apply_nnapi_delegate_ = enable; } } void Subgraph::SwitchToDelegateContext() { context_.GetNodeAndRegistration = GetNodeAndRegistration; context_.ReplaceNodeSubsetsWithDelegateKernels = ReplaceNodeSubsetsWithDelegateKernels; context_.GetExecutionPlan = GetExecutionPlan; context_.PreviewDelegatePartitioning = PreviewDelegatePartitioning; } void Subgraph::SwitchToKernelContext() { context_.GetNodeAndRegistration = [](struct TfLiteContext* context, int node_index, TfLiteNode** node, TfLiteRegistration** registration) { return ForbiddenContextFunction(context); }; context_.ReplaceNodeSubsetsWithDelegateKernels = [](TfLiteContext* context, TfLiteRegistration registration, const TfLiteIntArray* nodes_to_replace, TfLiteDelegate* delegate) { return ForbiddenContextFunction(context); }; context_.GetExecutionPlan = [](struct TfLiteContext* context, TfLiteIntArray**) { return ForbiddenContextFunction(context); }; context_.PreviewDelegatePartitioning = [](struct TfLiteContext* context, const TfLiteIntArray* nodes_to_replace, TfLiteDelegateParams** partition_params_array, int* num_partitions) { return ForbiddenContextFunction(context); }; // Free any memory that might have been allocated by // PreviewDelegatePartitioning. FreeDelegatePartitioningData(); } TfLiteStatus Subgraph::UndoAllDelegates() { // Return early if there is nothing to reset to. if (pre_delegation_execution_plan_.empty()) return kTfLiteOk; // First free all delegate nodes. for (int execution_plan_index = 0; execution_plan_index < execution_plan_.size(); ++execution_plan_index) { int node_index = execution_plan_[execution_plan_index]; TfLiteNode& node = nodes_and_registration_[node_index].first; if (node.delegate == nullptr) { continue; } CleanupNode(node_index); } // Reset execution plan. execution_plan_ = pre_delegation_execution_plan_; pre_delegation_execution_plan_.clear(); // Delegate nodes are appended to nodes_and_registration_. Therefore, // cleanup nodes_and_registration_ to only contain nodes from // pre_delegation_execution_plan_. int max_retained_node_index = 0; for (int execution_plan_index = 0; execution_plan_index < execution_plan_.size(); ++execution_plan_index) { max_retained_node_index = std::max(max_retained_node_index, execution_plan_[execution_plan_index]); } nodes_and_registration_.resize(max_retained_node_index + 1); // After undoing delegates, the graph is uninvokable, but mutable. state_ = kStateUninvokable; delegates_undone_ = true; return kTfLiteOk; } TfLiteStatus Subgraph::RedoAllDelegates() { if (!delegates_undone_) return kTfLiteOk; delegates_undone_ = false; std::vector<TfLiteDelegate*> delegates_to_apply; delegates_applied_.swap(delegates_to_apply); for (auto* delegate : delegates_to_apply) { TF_LITE_ENSURE_STATUS(ModifyGraphWithDelegate(delegate)); } return kTfLiteOk; } TfLiteStatus Subgraph::RemoveAllDelegates() { TF_LITE_ENSURE_STATUS(UndoAllDelegates()); delegates_applied_.clear(); delegates_undone_ = false; TF_LITE_ENSURE_STATUS(EnsureMemoryAllocations()); return kTfLiteOk; } bool Subgraph::HasDelegates() { return !delegates_applied_.empty(); } void Subgraph::EnsureTensorsVectorCapacity() { const size_t required_capacity = tensors_.size() + kTensorsCapacityHeadroom; if (required_capacity > tensors_.capacity()) { // Whenever it's required to increase the vector capacity, make it at // least twice bigger. The behavior is consistent with the default // behavior of GCC STL's `std::vector::resize()`. This avoids frequently // allocating and copying the underlying buffer. size_t reserved_capacity = std::max(required_capacity, tensors_.capacity() * 2); tensors_.reserve(reserved_capacity); context_.tensors = tensors_.data(); } } TfLiteStatus Subgraph::EnsureMemoryAllocations() { if (memory_planner_) { state_ = kStateUninvokable; TF_LITE_ENSURE_OK(&context_, memory_planner_->PlanAllocations()); } TF_LITE_ENSURE_OK(&context_, AllocateTensors()); TF_LITE_ENSURE_EQ(&context_, state_, kStateInvokable); return kTfLiteOk; } TfLiteStatus Subgraph::ModifyGraphWithDelegate(TfLiteDelegate* delegate) { TFLITE_SCOPED_TAGGED_DEFAULT_PROFILE(profiler_.get(), "ModifyGraphWithDelegate"); // Restore delegation state if applicable. TF_LITE_ENSURE_STATUS(RedoAllDelegates()); if (state_ == kStateInvokableAndImmutable) { ReportError( "ModifyGraphWithDelegate is disallowed when graph is immutable."); return kTfLiteApplicationError; } if (!(delegate->flags & kTfLiteDelegateFlagsAllowDynamicTensors)) { int last_execution_plan_index_prepared; TF_LITE_ENSURE_OK( &context_, PrepareOpsStartingAt(0, execution_plan_, &last_execution_plan_index_prepared)); if (has_dynamic_tensors_) { // Make sure that we are in a defined ready state before returning. // Plan and allocate tensors before returning. TF_LITE_ENSURE_OK(&context_, EnsureMemoryAllocations()); ReportError( "Attempting to use a delegate that only supports static-sized " "tensors with a graph that has dynamic-sized tensors."); return kTfLiteError; } } const bool was_invokable_before_delegate = state_ == kStateInvokable; if (delegates_applied_.empty()) { // This is the first delegate being applied, so remember original execution // plan. // TODO(b/119623453): Restore execution plan to this state if delegate // application fails. pre_delegation_execution_plan_ = execution_plan_; } // TODO(aselle): Consider if it is worth storing pointers to delegates. // Setup additional context interface. SwitchToDelegateContext(); auto reset_delegation_if_not_ok = [this](TfLiteStatus status) { if (status != kTfLiteOk) { TF_LITE_ENSURE_STATUS(RemoveAllDelegates()); ReportError( "Restored original execution plan after delegate application " "failure."); return kTfLiteDelegateError; } return kTfLiteOk; }; TfLiteStatus status = delegate->Prepare(&context_, delegate); // Remove additional context info. SwitchToKernelContext(); TF_LITE_ENSURE_STATUS(reset_delegation_if_not_ok(status)); if (!(delegate->flags & kTfLiteDelegateFlagsAllowDynamicTensors)) { // Reset the state to force tensor/op reallocation. state_ = kStateUninvokable; TF_LITE_ENSURE_STATUS( reset_delegation_if_not_ok(EnsureMemoryAllocations())); // After using a delegate which doesn't support dynamic tensors, make the // entire graph immutable. state_ = kStateInvokableAndImmutable; } else if (was_invokable_before_delegate) { // If the graph was invokable prior to delegate application, flush // allocation now to leave it in a consistent state. TF_LITE_ENSURE_STATUS( reset_delegation_if_not_ok(EnsureMemoryAllocations())); } delegates_applied_.push_back(delegate); return status; } TfLiteStatus Subgraph::SetCustomAllocationForTensor( int tensor_index, const TfLiteCustomAllocation& allocation) { TfLiteTensor* tensor = &context_.tensors[tensor_index]; TF_LITE_ENSURE(context(), (tensor->allocation_type == kTfLiteArenaRw || tensor->allocation_type == kTfLiteArenaRwPersistent || tensor->allocation_type == kTfLiteCustom)); TF_LITE_ENSURE_STATUS( ValidateCustomAllocationForTensor(context(), tensor, allocation)); // If tensor already has a custom alloc, just reassign. const auto alloc_it = std::find_if( custom_allocations_.begin(), custom_allocations_.end(), [tensor_index]( const std::pair<int, TfLiteCustomAllocation>& existing_alloc) { return existing_alloc.first == tensor_index; }); if (alloc_it == custom_allocations_.end()) { custom_allocations_.emplace_back(tensor_index, allocation); } else { alloc_it->second = allocation; } tensor->allocation_type = kTfLiteCustom; tensor->data.data = allocation.data; return kTfLiteOk; } } // namespace tflite
null
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/core/subgraph.h" #include <algorithm> #include <cstdint> #include "tensorflow/lite/arena_planner.h" #include "tensorflow/lite/c/common.h" #include "tensorflow/lite/context_util.h" #include "tensorflow/lite/core/api/tensor_utils.h" #include "tensorflow/lite/delegates/nnapi/nnapi_delegate.h" #include "tensorflow/lite/graph_info.h" #include "tensorflow/lite/minimal_logging.h" #include "tensorflow/lite/schema/schema_generated.h" #include "tensorflow/lite/util.h" namespace tflite { namespace { struct TfLiteQuantizationDeleter { void operator()(TfLiteQuantization* q) { if (q) TfLiteQuantizationFree(q); } }; using ScopedTfLiteQuantization = std::unique_ptr<TfLiteQuantization, TfLiteQuantizationDeleter>; struct TfLiteSparsityDeleter { void operator()(TfLiteSparsity* s) { if (s) TfLiteSparsityFree(s); } }; using ScopedTfLiteSparsity = std::unique_ptr<TfLiteSparsity, TfLiteSparsityDeleter>; TfLiteStatus ReportOpError(TfLiteContext* context, const TfLiteNode& node, const TfLiteRegistration& registration, int node_index, const char* message) { context->ReportError( context, "Node number %d (%s) %s.\n", node_index, registration.custom_name ? registration.custom_name : EnumNameBuiltinOperator( static_cast<BuiltinOperator>(registration.builtin_code)), message); return kTfLiteError; } // Stub method which returns kTfLiteError when the function is forbidden. // We're registering this function to several different function to save // compiled binary size. Please note the restrictions: // * The type of first parameter have to be `TfLiteContext*`. // * All parameters must be trivially destructible. (E.g. No C++ class) TfLiteStatus ForbiddenContextFunction(TfLiteContext* context, ...) { context->ReportError(context, "The function is forbidden if not calling in delegate."); return kTfLiteError; } // Set the ForbiddenContextFunction to a compatible function pointer. template <typename FunctionType> void SetForbiddenContextFunction(FunctionType* func) { *func = reinterpret_cast<FunctionType>(ForbiddenContextFunction); } // Returns true if at least one tensor in the given list is kTfLiteDynamic. template <typename TensorIntArray> bool HasDynamicTensorImpl(const TfLiteContext& context, const TensorIntArray& int_array) { for (int i : int_array) { const TfLiteTensor& tensor = context.tensors[i]; if (tensor.allocation_type == kTfLiteDynamic) { return true; } } return false; } bool HasDynamicTensor(const TfLiteContext& context, const TfLiteIntArray* int_array) { return HasDynamicTensorImpl(context, TfLiteIntArrayView{int_array}); } // Gets the legacy TfLiteQuantizationParams from the current TfLiteQuantization. TfLiteQuantizationParams GetLegacyQuantization( const TfLiteQuantization& quantization) { TfLiteQuantizationParams legacy_quantization; legacy_quantization.scale = 0; legacy_quantization.zero_point = 0; // If the quantization type isn't affine, return the empty // legacy_quantization. if (quantization.type != kTfLiteAffineQuantization) { return legacy_quantization; } auto* affine_quantization = static_cast<TfLiteAffineQuantization*>(quantization.params); if (!affine_quantization || !affine_quantization->scale || !affine_quantization->zero_point || affine_quantization->scale->size != 1 || affine_quantization->zero_point->size != 1) { return legacy_quantization; } // We know its per-layer quantization now. legacy_quantization.scale = affine_quantization->scale->data[0]; legacy_quantization.zero_point = affine_quantization->zero_point->data[0]; return legacy_quantization; } static constexpr const char kUnknownCustomOpName[] = "UnknownCustomOp"; const char* GetTFLiteOpName(const TfLiteRegistration& op_reg) { if (op_reg.builtin_code == tflite::BuiltinOperator_CUSTOM) { const char* const custom_name = op_reg.custom_name; return custom_name ? custom_name : kUnknownCustomOpName; } if (op_reg.builtin_code == tflite::BuiltinOperator_DELEGATE && op_reg.custom_name) { return op_reg.custom_name; } return tflite::EnumNamesBuiltinOperator()[op_reg.builtin_code]; } TfLiteStatus ValidateCustomAllocationForTensor( TfLiteContext* context, const TfLiteTensor* tensor, const TfLiteCustomAllocation& allocation) { TF_LITE_ENSURE(context, allocation.data != nullptr); TF_LITE_ENSURE(context, allocation.bytes >= tensor->bytes); // Ensure provided memory is aligned to what TFLite requires. const intptr_t data_ptr_value = reinterpret_cast<intptr_t>(allocation.data); TF_LITE_ENSURE(context, data_ptr_value % kDefaultTensorAlignment == 0); return kTfLiteOk; } } // namespace // A trivial implementation of GraphInfo around the Interpreter. // NOTE: this interpreter info represents the subset of the // graph that is executed according to execution plan. Thus, // the indices are execution plan indices rather than raw node // indices. class InterpreterInfo : public GraphInfo { public: explicit InterpreterInfo(Subgraph* subgraph) : subgraph_(subgraph) {} size_t num_tensors() const override { return subgraph_->tensors().size(); } TfLiteTensor* tensor(size_t index) override { return &subgraph_->tensors()[index]; } size_t num_execution_nodes() const override { return subgraph_->execution_plan().size(); } size_t num_total_nodes() const override { return subgraph_->nodes_size(); } const TfLiteNode& node(size_t index) const override { int node_index = subgraph_->execution_plan()[index]; return subgraph_->nodes_and_registration()[node_index].first; } size_t node_index(size_t index) const override { return subgraph_->execution_plan()[index]; } const std::vector<int>& inputs() const override { return subgraph_->inputs(); } const std::vector<int>& outputs() const override { return subgraph_->outputs(); } const std::vector<int>& variables() const override { return subgraph_->variables(); } public: Subgraph* subgraph_; }; Subgraph::Subgraph(ErrorReporter* error_reporter, TfLiteExternalContext** external_contexts, std::vector<std::unique_ptr<Subgraph>>* subgraphs, resource::ResourceMap* resources) : external_contexts_(external_contexts), error_reporter_(error_reporter), next_execution_plan_index_to_prepare_(0), next_execution_plan_index_to_plan_allocation_(0), subgraphs_(subgraphs), resources_(resources) { // TODO(b/161272052): Consider a better TfLiteContext initialization pattern: context_.impl_ = static_cast<void*>(this); context_.ResizeTensor = ResizeTensor; context_.ReportError = ReportErrorC; context_.AddTensors = AddTensors; context_.tensors = nullptr; context_.tensors_size = 0; context_.allow_fp32_relax_to_fp16 = false; context_.recommended_num_threads = -1; context_.GetExternalContext = GetExternalContext; context_.SetExternalContext = SetExternalContext; context_.profiler = nullptr; context_.GetTensor = nullptr; context_.GetEvalTensor = nullptr; // Reserve some space for the tensors to avoid excessive resizing. tensors_.reserve(kTensorsReservedCapacity); nodes_and_registration().reserve(kTensorsReservedCapacity); // Invalid to call these these except from TfLiteDelegate SwitchToKernelContext(); } Subgraph::~Subgraph() { for (int node_index = 0; node_index < nodes_and_registration_.size(); ++node_index) { CleanupNode(node_index); } for (size_t i = 0; i < context_.tensors_size; i++) { TfLiteTensor* tensor = &context_.tensors[i]; if (tensor->buffer_handle != kTfLiteNullBufferHandle && tensor->delegate->FreeBufferHandle != nullptr) { tensor->delegate->FreeBufferHandle(&context_, tensor->delegate, &tensor->buffer_handle); } TfLiteTensorFree(tensor); } } void Subgraph::CleanupNode(int node_index) { TfLiteNode& node = nodes_and_registration_[node_index].first; const TfLiteRegistration& registration = nodes_and_registration_[node_index].second; TfLiteIntArrayFree(node.inputs); TfLiteIntArrayFree(node.outputs); TfLiteIntArrayFree(node.temporaries); TfLiteIntArrayFree(node.intermediates); if (node.builtin_data) free(node.builtin_data); OpFree(registration, node.user_data); node.builtin_data = nullptr; } TfLiteStatus Subgraph::ReplaceNodeSubsetsWithDelegateKernels( TfLiteContext* context, TfLiteRegistration registration, const TfLiteIntArray* nodes_to_replace, TfLiteDelegate* delegate) { return static_cast<Subgraph*>(context->impl_) ->ReplaceNodeSubsetsWithDelegateKernels(registration, nodes_to_replace, delegate); } namespace { // Copy a std::vector<int> to an existing TfLiteIntArray. // This is a low-level data manipulation function, and it's caller's // responsibility to ensure TfLiteIntArray has enough size. void CopyVectorToTfLiteIntArray(const std::vector<int>& vec, TfLiteIntArray* arr) { arr->size = vec.size(); memcpy(arr->data, vec.data(), sizeof(int) * arr->size); } // This function allocates a continuous memory space that contains a // TfLiteDelegateParams followed by a several TfLiteIntArray. // When calling `free` at TfLiteDelegateParams*, all the allocated space // will be freed together. // // +-----------------------------------+ // | TfLiteDelegateParams | // | TfLiteDelegate* delegate; | // | TfLiteIntArray* nodes_to_replace; |--\ // | TfLiteIntArray* input_tensors; |--+--\ // | TfLiteIntArray* output_tensors; |--+--+--\ // +-----------------------------------+ | | | // | TfLiteIntArray (variable size) |<-/ | | // +-----------------------------------+ | | // | TfLiteIntArray (variable size) |<----/ | // +-----------------------------------+ | // | TfLiteIntArray (variable size) |<-------/ // +-----------------------------------+ TfLiteDelegateParams* CreateDelegateParams(TfLiteDelegate* delegate, const NodeSubset& node_subset) { // Step 1: Calculate the allocation size. int allocation_size = sizeof(TfLiteDelegateParams); int nodes_to_replace_size = TfLiteIntArrayGetSizeInBytes(node_subset.nodes.size()); allocation_size += nodes_to_replace_size; int input_tensors_size = TfLiteIntArrayGetSizeInBytes(node_subset.input_tensors.size()); allocation_size += input_tensors_size; int output_tensors_size = TfLiteIntArrayGetSizeInBytes(node_subset.output_tensors.size()); allocation_size += output_tensors_size; // Step 2: Allocate the memory. // Use `char*` for conveniently step through the allocated space by bytes. char* allocation = static_cast<char*>(malloc(allocation_size)); // Step 3: Fill all data structures structures. TfLiteDelegateParams* params = reinterpret_cast<TfLiteDelegateParams*>(allocation); params->delegate = delegate; allocation += sizeof(TfLiteDelegateParams); params->nodes_to_replace = reinterpret_cast<TfLiteIntArray*>(allocation); CopyVectorToTfLiteIntArray(node_subset.nodes, params->nodes_to_replace); allocation += nodes_to_replace_size; params->input_tensors = reinterpret_cast<TfLiteIntArray*>(allocation); CopyVectorToTfLiteIntArray(node_subset.input_tensors, params->input_tensors); allocation += input_tensors_size; params->output_tensors = reinterpret_cast<TfLiteIntArray*>(allocation); CopyVectorToTfLiteIntArray(node_subset.output_tensors, params->output_tensors); allocation += output_tensors_size; return params; } // Assumes that params is not nullptr. void PopulatePreviewDelegateParams(const NodeSubset& node_subset, TfLiteDelegateParams* params) { // Since these params are used for previewing partitioning, params->delegate // is not required. params->delegate = nullptr; params->nodes_to_replace = TfLiteIntArrayCreate(node_subset.nodes.size()); CopyVectorToTfLiteIntArray(node_subset.nodes, params->nodes_to_replace); params->input_tensors = TfLiteIntArrayCreate(node_subset.input_tensors.size()); CopyVectorToTfLiteIntArray(node_subset.input_tensors, params->input_tensors); params->output_tensors = TfLiteIntArrayCreate(node_subset.output_tensors.size()); CopyVectorToTfLiteIntArray(node_subset.output_tensors, params->output_tensors); } } // namespace TfLiteStatus Subgraph::ReplaceNodeSubsetsWithDelegateKernels( TfLiteRegistration registration, const TfLiteIntArray* nodes_to_replace, TfLiteDelegate* delegate) { // Ignore empty node replacement sets. if (!nodes_to_replace->size) { return kTfLiteOk; } // Annotate the registration as DELEGATE op. registration.builtin_code = BuiltinOperator_DELEGATE; // Analyze the graph to find all independent node_subsets that are either // fully not-this-delegate or this-delegate computation. InterpreterInfo info(this); std::vector<NodeSubset> node_subsets; PartitionGraphIntoIndependentNodeSubsets(&info, nodes_to_replace, &node_subsets); TFLITE_LOG( tflite::TFLITE_LOG_INFO, "Replacing %d node(s) with delegate (%s) node, yielding %zu partitions.", nodes_to_replace->size, registration.custom_name ? registration.custom_name : "unknown", node_subsets.size()); execution_plan_.clear(); for (auto& node_subset : node_subsets) { // Subsets claimed by the delegate should have a "macro" op created, the // other node_subsets (kTfNonPartition) just have their nodes added back to // the execution plan. switch (node_subset.type) { case NodeSubset::kTfNonPartition: for (auto it = node_subset.nodes.begin(); it != node_subset.nodes.end(); ++it) { execution_plan_.push_back(*it); } break; case NodeSubset::kTfPartition: { int node_index; TfLiteDelegateParams* params = CreateDelegateParams(delegate, node_subset); TF_LITE_ENSURE_STATUS(AddNodeWithParameters( node_subset.input_tensors, node_subset.output_tensors, {}, nullptr, 0, params, &registration, &node_index)); // Initialize the output tensors's delegate-related fields. for (int tensor_index : node_subset.output_tensors) { TfLiteTensor* tensor = &tensors_[tensor_index]; TF_LITE_ENSURE(&context_, tensor->delegate == nullptr || tensor->delegate == delegate); tensor->delegate = delegate; } // Associate the node with the delegate. TfLiteNode* node = &nodes_and_registration_[node_index].first; node->delegate = delegate; } break; case NodeSubset::kTfUnexplored: return kTfLiteError; break; } } return kTfLiteOk; } TfLiteExternalContext* Subgraph::GetExternalContext( TfLiteExternalContextType type) { if (static_cast<int>(type) >= 0 && type < kTfLiteMaxExternalContexts) { return external_contexts_[type]; } return nullptr; } TfLiteExternalContext* Subgraph::GetExternalContext( struct TfLiteContext* context, TfLiteExternalContextType type) { return static_cast<Subgraph*>(context->impl_)->GetExternalContext(type); } void Subgraph::SetExternalContext(TfLiteExternalContextType type, TfLiteExternalContext* ctx) { if (static_cast<int>(type) >= 0 && type < kTfLiteMaxExternalContexts) { external_contexts_[type] = ctx; } } void Subgraph::SetExternalContext(struct TfLiteContext* context, TfLiteExternalContextType type, TfLiteExternalContext* ctx) { return static_cast<Subgraph*>(context->impl_)->SetExternalContext(type, ctx); } // Gets an TfLiteIntArray* representing the execution plan. The interpreter owns // this memory and it is only guaranteed to exist during the invocation of the // delegate prepare. TfLiteStatus Subgraph::GetExecutionPlan(TfLiteIntArray** execution_plan) { // TODO(aselle): Do not make a copy here plan_cache_.reset(TfLiteIntArrayCreate(execution_plan_.size())); *execution_plan = plan_cache_.get(); static_assert(sizeof(plan_cache_->data[0]) == sizeof(execution_plan_[0]), "TfLiteIntArray and execution_plan do not contain same type."); std::memcpy(plan_cache_->data, execution_plan_.data(), sizeof(plan_cache_->data[0]) * execution_plan_.size()); return kTfLiteOk; } // WARNING: This is an experimental interface that is subject to change. // Entry point for C node plugin API to get the execution plan TfLiteStatus Subgraph::GetExecutionPlan(struct TfLiteContext* context, TfLiteIntArray** execution_plan) { return static_cast<Subgraph*>(context->impl_) ->GetExecutionPlan(execution_plan); } void Subgraph::FreeDelegatePartitioningData() { for (auto& params : partitioning_preview_cache_) { TfLiteIntArrayFree(params.nodes_to_replace); TfLiteIntArrayFree(params.input_tensors); TfLiteIntArrayFree(params.output_tensors); } partitioning_preview_cache_.clear(); } TfLiteStatus Subgraph::PreviewDelegatePartitioning( const TfLiteIntArray* nodes_to_replace, TfLiteDelegateParams** partition_params_array, int* num_partitions) { // Ensure partitioning cache is empty. FreeDelegatePartitioningData(); // Defaults. if (!partition_params_array || !num_partitions) return kTfLiteError; *partition_params_array = nullptr; *num_partitions = 0; if (!nodes_to_replace->size) { return kTfLiteOk; } // Partition the execution plan into node subsets. InterpreterInfo info(this); std::vector<NodeSubset> node_subsets; PartitionGraphIntoIndependentNodeSubsets(&info, nodes_to_replace, &node_subsets); // Create one TfLiteDelegateParams per node-subset which would be delegated. for (auto& node_subset : node_subsets) { if (node_subset.type != NodeSubset::kTfPartition) { continue; } partitioning_preview_cache_.emplace_back(); PopulatePreviewDelegateParams(node_subset, &partitioning_preview_cache_.back()); ++*num_partitions; } *partition_params_array = partitioning_preview_cache_.data(); return kTfLiteOk; } TfLiteStatus Subgraph::PreviewDelegatePartitioning( struct TfLiteContext* context, const TfLiteIntArray* nodes_to_replace, TfLiteDelegateParams** partition_params_array, int* num_partitions) { return static_cast<Subgraph*>(context->impl_) ->PreviewDelegatePartitioning(nodes_to_replace, partition_params_array, num_partitions); } TfLiteStatus Subgraph::SetInputs(std::vector<int> inputs) { TF_LITE_ENSURE_OK(&context_, CheckTensorIndices("inputs", inputs.data(), inputs.size())); inputs_ = std::move(inputs); return kTfLiteOk; } TfLiteStatus Subgraph::SetOutputs(std::vector<int> outputs) { TF_LITE_ENSURE_OK( &context_, CheckTensorIndices("outputs", outputs.data(), outputs.size())); outputs_ = std::move(outputs); return kTfLiteOk; } TfLiteStatus Subgraph::SetVariables(std::vector<int> variables) { TF_LITE_ENSURE_OK(&context_, CheckTensorIndices("variables", variables.data(), variables.size())); variables_ = std::move(variables); return kTfLiteOk; } void Subgraph::SetCancellationFunction(void* data, bool (*check_cancelled_func)(void*)) { cancellation_data_ = data; check_cancelled_func_ = check_cancelled_func; } bool Subgraph::IsCancelled() { return (check_cancelled_func_ != nullptr) && (*check_cancelled_func_)(cancellation_data_); } void Subgraph::ReserveNodes(int count) { nodes_and_registration_.reserve(count); } TfLiteStatus Subgraph::CheckTensorIndices(const char* label, const int* indices, int length) { // Making sure kTfLiteOptionalTensor is not re-defined to something other than // -1. static_assert(kTfLiteOptionalTensor == -1, "kTfLiteOptionalTensor should be defined -1"); for (int i = 0; i < length; i++) { int index = indices[i]; // Continue if index == kTfLiteOptionalTensor before additional comparisons // below, size_t(-1) is always >= context_tensors_size. if (index == kTfLiteOptionalTensor) { continue; } if (index < 0 || static_cast<size_t>(index) >= context_.tensors_size) { ReportError( "Invalid tensor index %d in %s. The subgraph has %d tensors\n", index, label, context_.tensors_size); consistent_ = false; return kTfLiteError; } } return kTfLiteOk; } // We have two arrays and we need to check that elements from one array don't // show up in the other. We could sort both arrays and then iterate with two // pointers from start to finish always increasing the smaller one but since // these arrays are usually short (<25 elements for inputs, usually <3 for // outputs), this might be slower than the naive approach (if arrays have size n // and m, with n >> m ~ O(1), first approach is O(nlogn) whereas the other is // O(n)). Plus, sorting the input and output arrays might not be something we // want as it destroys ordering of elements. // // If it turns out that this is an issue, we can switch to the other algorithm. TfLiteStatus Subgraph::CheckInputAndOutputForOverlap(const int* input_indices, int num_inputs, const int* output_indices, int num_outputs) { for (int i = 0; i < num_inputs; i++) { for (int j = 0; j < num_outputs; j++) { if (input_indices[i] == output_indices[j]) { ReportError("Tensor %d is both input %d and output %d\n", input_indices[i], i, j); consistent_ = false; return kTfLiteError; } } } return kTfLiteOk; } namespace { // Multiply two sizes and return true if overflow occurred; // This is based off tensorflow/overflow.h but is simpler as we already // have unsigned numbers. It is also generalized to work where sizeof(size_t) // is not 8. TfLiteStatus MultiplyAndCheckOverflow(size_t a, size_t b, size_t* product) { // Multiplying a * b where a and b are size_t cannot result in overflow in a // size_t accumulator if both numbers have no non-zero bits in their upper // half. constexpr size_t size_t_bits = 8 * sizeof(size_t); constexpr size_t overflow_upper_half_bit_position = size_t_bits / 2; *product = a * b; // If neither integers have non-zero bits past 32 bits can't overflow. // Otherwise check using slow devision. if (TFLITE_EXPECT_FALSE((a | b) >> overflow_upper_half_bit_position != 0)) { if (a != 0 && *product / a != b) return kTfLiteError; } return kTfLiteOk; } } // namespace TfLiteStatus Subgraph::BytesRequired(TfLiteType type, const int* dims, size_t dims_size, size_t* bytes) { TF_LITE_ENSURE(&context_, bytes != nullptr); size_t count = 1; for (int k = 0; k < dims_size; k++) { size_t old_count = count; TF_LITE_ENSURE_MSG( &context_, MultiplyAndCheckOverflow(old_count, dims[k], &count) == kTfLiteOk, "BytesRequired number of elements overflowed.\n"); } size_t type_size = 0; TF_LITE_ENSURE_OK(&context_, GetSizeOfType(&context_, type, &type_size)); TF_LITE_ENSURE_MSG( &context_, MultiplyAndCheckOverflow(type_size, count, bytes) == kTfLiteOk, "BytesRequired number of bytes overflowed.\n"); return kTfLiteOk; } TfLiteStatus Subgraph::AllocateTensors() { TFLITE_SCOPED_TAGGED_DEFAULT_PROFILE(profiler_.get(), "AllocateTensors"); if (!consistent_) { ReportError("AllocateTensors() called on inconsistent model."); return kTfLiteError; } // Restore delegation state if applicable. TF_LITE_ENSURE_STATUS(RedoAllDelegates()); // Explicit (re)allocation is necessary if nodes have been changed or tensors // have been resized. For inputs marked as dynamic, we can't short-circuit the // allocation as the client may have done the resize manually. if (state_ != kStateUninvokable && !HasDynamicTensorImpl(context_, inputs())) { if (memory_planner_ && !memory_planner_->HasNonPersistentMemory()) { // If the only change was the release of non-persistent memory via // ReleaseNonPersistentMemory(), just re-allocate it. For any other type // of memory-planning change (for eg, ResizeInputTensor), the state would // be kStateUninvokable. memory_planner_->AcquireNonPersistentMemory(); } return kTfLiteOk; } next_execution_plan_index_to_prepare_ = 0; next_execution_plan_index_to_plan_allocation_ = 0; next_original_execution_plan_index_to_prepare_ = 0; if (memory_planner_) { TF_LITE_ENSURE_STATUS(memory_planner_->ResetAllocations()); } TF_LITE_ENSURE_STATUS(PrepareOpsAndTensors()); state_ = kStateInvokable; // Reset the variable tensors to zero after (re)allocating the tensors. // Developers shouldn't rely on the side effect of this function to reset // variable tensors. They should call `ResetVariableTensors` directly // instead. ResetVariableTensors(); return kTfLiteOk; } // TODO(ycling): Support non-zero default values. TfLiteStatus Subgraph::ResetVariableTensors() { for (auto& tensor : tensors_) { if (!tensor.is_variable) { continue; } if (tensor.allocation_type == kTfLiteArenaRwPersistent) { // If variable tensors allocation type is `kTfLiteArenaRwPersistent`, then // they must be allocated after the initial `PrepareOpsAndTensors()` is // called. TF_LITE_ENSURE(&context_, tensor.data.raw != nullptr); tflite::ResetVariableTensor(&tensor); } else { // If variable tensors allocation type is not `kTfLiteArenaRwPersistent`, // then it can only be `kTfLiteCustom` in which case, we do not reset it. TF_LITE_ENSURE_EQ(&context_, tensor.allocation_type, kTfLiteCustom); } } return kTfLiteOk; } TfLiteStatus Subgraph::AddNodeWithParameters( const std::vector<int>& inputs, const std::vector<int>& outputs, const std::vector<int>& intermediates, const char* init_data, size_t init_data_size, void* builtin_data, const TfLiteRegistration* registration, int* node_index) { std::unique_ptr<void, decltype(free)*> builtin_data_deleter(builtin_data, free); if (state_ == kStateInvokableAndImmutable) { ReportError("AddNodeWithParameters is disallowed when graph is immutable."); return kTfLiteError; } state_ = kStateUninvokable; TF_LITE_ENSURE_OK(&context_, CheckTensorIndices("node inputs", inputs.data(), inputs.size())); TF_LITE_ENSURE_OK( &context_, CheckTensorIndices("node outputs", outputs.data(), outputs.size())); // For builtin ops, inputs and outputs must not overlap. Custom ops must do // this check by themselves if they don't support overlapping tensors. This // distinction is to allow custom ops to just forward a tensor, reusing it as // both input and output. if (builtin_data != nullptr) { TF_LITE_ENSURE_OK(&context_, CheckInputAndOutputForOverlap( inputs.data(), inputs.size(), outputs.data(), outputs.size())); } int new_node_index = nodes_and_registration_.size(); if (node_index) *node_index = new_node_index; nodes_and_registration_.resize(nodes_and_registration_.size() + 1); auto& node_and_reg = nodes_and_registration_.back(); TfLiteNode& node = node_and_reg.first; if (node.inputs) TfLiteIntArrayFree(node.inputs); if (node.outputs) TfLiteIntArrayFree(node.outputs); if (node.intermediates) TfLiteIntArrayFree(node.intermediates); if (node.temporaries) TfLiteIntArrayFree(node.temporaries); // NOTE, here we are not using move semantics yet, since our internal // representation isn't std::vector, but in the future we would like to avoid // copies, so we want the interface to take r-value references now. node.inputs = ConvertVectorToTfLiteIntArray(inputs); node.outputs = ConvertVectorToTfLiteIntArray(outputs); node.intermediates = ConvertVectorToTfLiteIntArray(intermediates); node.temporaries = TfLiteIntArrayCreate(0); if (init_data) { node.user_data = OpInit(*registration, init_data, init_data_size); } else { node.user_data = OpInit( *registration, static_cast<const char*>(builtin_data_deleter.get()), 0); } node.builtin_data = builtin_data_deleter.release(); // TODO(ycling): Filling `custom_initial_data` and `custom_initial_data_size` // properly for nodes generated by ReplaceNodeSubsetsWithDelegateKernels. if (registration->builtin_code == BuiltinOperator_CUSTOM) { // When it's a CUSTOM op, the `custom_options` field in the Flatbuffer // `Operator` table is passed in. node.custom_initial_data = init_data; node.custom_initial_data_size = init_data_size; } else { node.custom_initial_data = nullptr; node.custom_initial_data_size = 0; } node.delegate = nullptr; // Copying of registration is required to support unresolved custom ops. node_and_reg.second = *registration; execution_plan_.push_back(new_node_index); return kTfLiteOk; } TfLiteStatus Subgraph::ResizeInputTensor(int tensor_index, const std::vector<int>& dims) { const bool delegates_applied = !pre_delegation_execution_plan_.empty(); const bool graph_is_immutable = state_ == kStateInvokableAndImmutable; if (graph_is_immutable && !delegates_applied) { ReportError("ResizeInputTensor is disallowed when graph is immutable."); return kTfLiteError; } // TODO(aselle): All bounds checks can be implemented as one-sided bounds // checks by casting to unsigned for efficiency. Profile before doing this. TF_LITE_ENSURE(&context_, tensor_index < context_.tensors_size && tensor_index >= 0); TfLiteTensor* tensor = &context_.tensors[tensor_index]; // Short-circuit the state change if the dimensions don't change, avoiding // unnecessary (re)allocations. // // Note that it's required to check `tensor->data.raw != nullptr`. Otherwise // the subgraph won't allocate memory for a dynamic tensor when its size // is equal to the original tensor size. if (tensor->data.raw != nullptr && EqualArrayAndTfLiteIntArray(tensor->dims, dims.size(), dims.data())) { return kTfLiteOk; } if (graph_is_immutable) { // Undo delegation if it resulted in the graph being immutable. TF_LITE_ENSURE_STATUS(UndoAllDelegates()); } state_ = kStateUninvokable; return ResizeTensorImpl(tensor, ConvertVectorToTfLiteIntArray(dims)); } TfLiteStatus Subgraph::ResizeInputTensorStrict(int tensor_index, const std::vector<int>& dims) { TF_LITE_ENSURE(&context_, tensor_index < context_.tensors_size && tensor_index >= 0); TfLiteTensor* tensor = &context_.tensors[tensor_index]; // Ensure that only unknown dimensions can be resized. TF_LITE_ENSURE_EQ(&context_, tensor->dims->size, dims.size()); for (size_t idx = 0; idx < dims.size(); idx++) { // `dims_signature` is not defined when no unknown dimensions are present. int dim_signature; if (tensor->dims_signature && tensor->dims_signature->size) { dim_signature = tensor->dims_signature->data[idx]; } else { dim_signature = tensor->dims->data[idx]; } if (dim_signature != -1 && dim_signature != dims[idx]) { ReportError( "Attempting to resize dimension %d of tensor %d with value %d to %d. " "ResizeInputTensorStrict only allows mutating unknown dimensions " "identified by -1.", idx, tensor_index, dim_signature, dims[idx]); return kTfLiteError; } } return ResizeInputTensor(tensor_index, dims); } TfLiteStatus Subgraph::ReleaseNonPersistentMemory() { if (memory_planner_) { TF_LITE_ENSURE_STATUS(memory_planner_->ReleaseNonPersistentMemory()); } return kTfLiteOk; } TfLiteStatus Subgraph::OpPrepare(const TfLiteRegistration& op_reg, TfLiteNode* node) { if (op_reg.prepare == nullptr) { // Check if it's an unresolved custom op. if (IsUnresolvedCustomOp(op_reg)) { if (IsFlexOp(op_reg.custom_name)) { ReportError( "Regular TensorFlow ops are not supported by this interpreter. " "Make sure you apply/link the Flex delegate before inference."); } else { ReportError("Encountered unresolved custom op: %s.", op_reg.custom_name ? op_reg.custom_name : "UnknownOp"); } return kTfLiteError; } // Resolved ops can have a null Prepare function. return kTfLiteOk; } return op_reg.prepare(&context_, node); } TfLiteStatus Subgraph::PrepareOpsStartingAt( int first_execution_plan_index, const std::vector<int>& execution_plan, int* last_execution_plan_index_prepared) { if (first_execution_plan_index == 0) { has_dynamic_tensors_ = false; } for (int execution_plan_index = first_execution_plan_index; execution_plan_index < execution_plan.size(); execution_plan_index++) { int node_index = execution_plan[execution_plan_index]; TfLiteNode& node = nodes_and_registration_[node_index].first; const TfLiteRegistration& registration = nodes_and_registration_[node_index].second; EnsureTensorsVectorCapacity(); if (OpPrepare(registration, &node) != kTfLiteOk) { return ReportOpError(&context_, node, registration, node_index, "failed to prepare"); } *last_execution_plan_index_prepared = execution_plan_index; // Discontinue if the node has dynamic outputs. Note that we don't // stop for dynamic temporary tensors since they won't affect the // sizes of other tensors in the graph. if (HasDynamicTensor(context_, node.outputs)) { has_dynamic_tensors_ = true; return kTfLiteOk; } } return kTfLiteOk; } TfLiteStatus Subgraph::PrepareOpsAndTensors() { if (!memory_planner_) { memory_planner_.reset(new ArenaPlanner( &context_, std::unique_ptr<GraphInfo>(new InterpreterInfo(this)), /*preserve_inputs=*/true, /*preserve_intermediates*/ false, kDefaultTensorAlignment)); memory_planner_->PlanAllocations(); } // Prepare original execution plan if any applied delegate wants it. // If any of the delegates is immutable, this won't be triggered // post-delegation (since we undo/redo delegation). For all other cases, other // delegates that do shape propagation themselves would still be able to. bool prepare_original_plan = false; if (!pre_delegation_execution_plan_.empty()) { for (int i = 0; i < delegates_applied_.size(); ++i) { if ((delegates_applied_[i]->flags & kTfLiteDelegateFlagsRequirePropagatedShapes)) { prepare_original_plan = true; break; } } } if (prepare_original_plan) { int last_original_exec_plan_index_prepared = 0; TF_LITE_ENSURE_STATUS(PrepareOpsStartingAt( next_execution_plan_index_to_prepare_, pre_delegation_execution_plan_, &last_original_exec_plan_index_prepared)); next_original_execution_plan_index_to_prepare_ = last_original_exec_plan_index_prepared + 1; } int last_exec_plan_index_prepared = 0; TF_LITE_ENSURE_STATUS( PrepareOpsStartingAt(next_execution_plan_index_to_prepare_, execution_plan_, &last_exec_plan_index_prepared)); next_execution_plan_index_to_prepare_ = last_exec_plan_index_prepared + 1; // Execute arena allocations. TF_LITE_ENSURE_STATUS(memory_planner_->ExecuteAllocations( next_execution_plan_index_to_plan_allocation_, last_exec_plan_index_prepared)); // Ensure custom allocations are still valid for applicable tensors. // This causes some extra validations for cases with dynamic tensors, but the // overhead should be minimal since the number of custom-allocated tensors // will typically be low. for (int i = 0; i < custom_allocations_.size(); ++i) { auto idx_and_alloc = custom_allocations_[i]; auto& tensor = tensors()[idx_and_alloc.first]; const auto& alloc = idx_and_alloc.second; TF_LITE_ENSURE(context(), tensor.allocation_type == kTfLiteCustom); TF_LITE_ENSURE_STATUS( ValidateCustomAllocationForTensor(context(), &tensor, alloc)); } next_execution_plan_index_to_plan_allocation_ = last_exec_plan_index_prepared + 1; return kTfLiteOk; } TfLiteStatus Subgraph::Invoke() { if (!consistent_) { ReportError("Invoke called on model that is not consistent."); return kTfLiteError; } TfLiteStatus status = kTfLiteOk; if (state_ == kStateUninvokable) { ReportError("Invoke called on model that is not ready."); return kTfLiteError; } else if (memory_planner_ && !memory_planner_->HasNonPersistentMemory()) { ReportError("Non-persistent memory is not available."); return kTfLiteError; } // This is only needed for UseNNAPI(true); if (should_apply_nnapi_delegate_ && !applied_nnapi_delegate_) { TF_LITE_ENSURE_OK(&context_, ModifyGraphWithDelegate(NnApiDelegate())); // only need to modify the graph once upon the first invocation. applied_nnapi_delegate_ = true; } // Invocations are always done in node order. // Note that calling Invoke repeatedly will cause the original memory plan to // be reused, unless either ResizeInputTensor() or AllocateTensors() has been // called. for (int execution_plan_index = 0; execution_plan_index < execution_plan_.size(); execution_plan_index++) { if (execution_plan_index == next_execution_plan_index_to_prepare_) { TF_LITE_ENSURE_STATUS(PrepareOpsAndTensors()); TF_LITE_ENSURE(&context_, next_execution_plan_index_to_prepare_ >= execution_plan_index); } int node_index = execution_plan_[execution_plan_index]; TfLiteNode& node = nodes_and_registration_[node_index].first; const TfLiteRegistration& registration = nodes_and_registration_[node_index].second; const char* op_name = nullptr; if (profiler_) op_name = GetTFLiteOpName(registration); TFLITE_SCOPED_TAGGED_OPERATOR_PROFILE(profiler_.get(), op_name, node_index); // TODO(ycling): This is an extra loop through inputs to check if the data // need to be copied from Delegate buffer to raw memory, which is often not // needed. We may want to cache this in prepare to know if this needs to be // done for a node or not. for (int i = 0; i < node.inputs->size; ++i) { int tensor_index = node.inputs->data[i]; if (tensor_index == kTfLiteOptionalTensor) { continue; } TfLiteTensor* tensor = &tensors_[tensor_index]; if (tensor->delegate && tensor->delegate != node.delegate && tensor->data_is_stale) { TF_LITE_ENSURE_STATUS(EnsureTensorDataIsReadable(tensor_index)); } } if (check_cancelled_func_ != nullptr && check_cancelled_func_(cancellation_data_)) { ReportError("Client requested cancel during Invoke()"); return kTfLiteError; } EnsureTensorsVectorCapacity(); tensor_resized_since_op_invoke_ = false; if (OpInvoke(registration, &node) != kTfLiteOk) { return ReportOpError(&context_, node, registration, node_index, "failed to invoke"); } // Force execution prep for downstream ops if the latest op triggered the // resize of a dynamic tensor. if (tensor_resized_since_op_invoke_ && HasDynamicTensor(context_, node.outputs)) { next_execution_plan_index_to_prepare_ = execution_plan_index + 1; // This happens when an intermediate dynamic tensor is resized. // We don't have to prepare all the ops, but we need to recompute // the allocation plan. if (next_execution_plan_index_to_plan_allocation_ > next_execution_plan_index_to_prepare_) { next_execution_plan_index_to_plan_allocation_ = next_execution_plan_index_to_prepare_; if (memory_planner_) { TF_LITE_ENSURE_STATUS(memory_planner_->ResetAllocationsAfter( next_execution_plan_index_to_plan_allocation_ - 1)); } } } } return status; } TfLiteStatus Subgraph::ResizeTensor(TfLiteContext* context, TfLiteTensor* tensor, TfLiteIntArray* new_size) { // If the dimensions don't change, avoiding // unnecessary (re)allocations. // // Note that it's required to check `tensor->data.raw != nullptr`. Otherwise // the subgraph won't allocate memory for a dynamic tensor when its size // is equal to the original tensor size. if (tensor->data.raw != nullptr && EqualArrayAndTfLiteIntArray(tensor->dims, new_size->size, new_size->data)) { // A number of clients assume |new_size| remains valid upon success, so // swap it in as the new (but logically identical) tensor dims. TfLiteIntArrayFree(tensor->dims); tensor->dims = new_size; return kTfLiteOk; } // Note here that context->impl_ is recovering the this pointer for an // instance of Interpreter to call into the member function ResizeTensorImpl // (this function is static). return static_cast<Subgraph*>(context->impl_) ->ResizeTensorImpl(tensor, new_size); } void Subgraph::ReportErrorImpl(const char* format, va_list args) { error_reporter_->Report(format, args); } void Subgraph::ReportErrorC(TfLiteContext* context, const char* format, ...) { va_list args; va_start(args, format); auto* f = static_cast<Subgraph*>(context->impl_); // Note here that context->impl_ is recovering the this pointer for an // instance of Subgraph to call into the member function ReportErrorImpl // (this function is static). f->ReportErrorImpl(format, args); va_end(args); } // Entry point for C node plugin API to report an error. void Subgraph::ReportError(const char* format, ...) { va_list args; va_start(args, format); auto* f = static_cast<Subgraph*>(context_.impl_); // Note here that context->impl_ is recovering the this pointer for an // instance of Subgraph to call into the member function ReportErrorImpl // (this function is static). f->ReportErrorImpl(format, args); va_end(args); } TfLiteStatus Subgraph::AddTensors(int tensors_to_add, int* first_new_tensor_index) { const size_t base_index = tensors_.size(); if (first_new_tensor_index) *first_new_tensor_index = base_index; tensors_.resize(tensors_.size() + tensors_to_add); for (size_t i = base_index; i < tensors_.size(); i++) { memset(&tensors_[i], 0, sizeof(tensors_[i])); tensors_[i].buffer_handle = kTfLiteNullBufferHandle; } context_.tensors = tensors_.data(); context_.tensors_size = tensors_.size(); return kTfLiteOk; } TfLiteStatus Subgraph::AddTensors(TfLiteContext* context, int tensors_to_add, int* first_new_tensor_index) { // Note here that context->impl_ is recovering the this pointer for an // instance of Interpreter to call into the member function AddTensors // (this function is static). return static_cast<Subgraph*>(context->impl_) ->AddTensors(tensors_to_add, first_new_tensor_index); } TfLiteStatus Subgraph::GetNodeAndRegistration( int node_index, TfLiteNode** node, TfLiteRegistration** registration) { TF_LITE_ENSURE(&context_, node_index >= 0); auto nodes_size = nodes_and_registration_.size(); TF_LITE_ENSURE(&context_, static_cast<size_t>(node_index) < nodes_size); TF_LITE_ENSURE(&context_, node != nullptr && registration != nullptr); auto& node_and_reg = nodes_and_registration_[node_index]; *node = &node_and_reg.first; *registration = &node_and_reg.second; return kTfLiteOk; } TfLiteStatus Subgraph::GetNodeAndRegistration( struct TfLiteContext* context, int node_index, TfLiteNode** node, TfLiteRegistration** registration) { return static_cast<Subgraph*>(context->impl_) ->GetNodeAndRegistration(node_index, node, registration); } TfLiteStatus Subgraph::SetTensorParametersReadOnly( int tensor_index, TfLiteType type, const char* name, const size_t rank, const int* dims, TfLiteQuantization quantization, const char* buffer, size_t bytes, const Allocation* allocation, TfLiteSparsity* sparsity) { // Ensure quantization cleanup on failure. ScopedTfLiteQuantization scoped_quantization(&quantization); ScopedTfLiteSparsity scoped_sparsity(sparsity); if (state_ == kStateInvokableAndImmutable) { ReportError( "SetTensorParametersReadOnly is disallowed when graph is immutable."); return kTfLiteError; } TF_LITE_ENSURE(&context_, tensor_index < context_.tensors_size && tensor_index >= 0); // For most tensors we know exactly how much memory is necessary so we can // ensure the buffer is large enough. However, we need to skip string tensors // and sparse tensors because their sizes change with the contents. // TODO(b/145615516): Extend BytesRequired to check sparse tensors. if (type != kTfLiteString && sparsity == nullptr) { size_t required_bytes; TF_LITE_ENSURE_OK(&context_, BytesRequired(type, dims, rank, &required_bytes)); TF_LITE_ENSURE_EQ(&context_, required_bytes, bytes); } TfLiteTensor& tensor = context_.tensors[tensor_index]; if (type == tensor.type && EqualArrayAndTfLiteIntArray(tensor.dims, rank, dims)) { // Fast path which does not invalidate the invokable property. TfLiteTensorDataFree(&tensor); TfLiteQuantizationFree(&tensor.quantization); tensor.data.raw = const_cast<char*>(buffer); if (!tensor.dims) tensor.dims = ConvertArrayToTfLiteIntArray(rank, dims); tensor.params = GetLegacyQuantization(quantization); tensor.quantization = *scoped_quantization.release(); tensor.sparsity = scoped_sparsity.release(); tensor.allocation_type = kTfLiteMmapRo; tensor.allocation = allocation; } else { state_ = kStateUninvokable; TfLiteTensorReset(type, name, ConvertArrayToTfLiteIntArray(rank, dims), GetLegacyQuantization(quantization), const_cast<char*>(buffer), bytes, kTfLiteMmapRo, allocation, false, &tensor); // TODO(suharshs): Update TfLiteTensorReset to include the new quantization // if there are other required callers. tensor.quantization = *scoped_quantization.release(); tensor.sparsity = scoped_sparsity.release(); } return kTfLiteOk; } // Set description of inputs/outputs/data/fptrs for node `node_index`. // This variant assumes an external buffer has been allocated of size // bytes. The lifetime of buffer must be ensured to be greater or equal // to Interpreter. TfLiteStatus Subgraph::SetTensorParametersReadWrite( int tensor_index, TfLiteType type, const char* name, const size_t rank, const int* dims, TfLiteQuantization quantization, bool is_variable, const size_t rank_dims_signature, const int* dims_signature) { // Ensure quantization cleanup on failure. ScopedTfLiteQuantization scoped_quantization(&quantization); if (state_ == kStateInvokableAndImmutable) { ReportError( "SetTensorParametersReadWrite is disallowed when graph is immutable."); return kTfLiteError; } TF_LITE_ENSURE(&context_, tensor_index < context_.tensors_size && tensor_index >= 0); size_t required_bytes = 0; if (type != kTfLiteString) { // These types will be allocated in our arena so we need to record how // many bytes we will need based on the dimensions. String tensors are // allocated dynamically and we can't know ahead of time how much space // they will require. TF_LITE_ENSURE_OK(&context_, BytesRequired(type, dims, rank, &required_bytes)); } TfLiteAllocationType allocation_type = kTfLiteArenaRw; if (type == kTfLiteString) { if (is_variable) { // We don't have a real use case for string variable tensor. ReportError("String variable tensor isn't supported."); return kTfLiteError; } allocation_type = kTfLiteDynamic; } else if (is_variable) { allocation_type = kTfLiteArenaRwPersistent; } TfLiteTensor& tensor = context_.tensors[tensor_index]; TfLiteTensorReset(type, name, ConvertArrayToTfLiteIntArray(rank, dims), GetLegacyQuantization(quantization), /*buffer=*/nullptr, required_bytes, allocation_type, nullptr, is_variable, &tensor); // TODO(suharshs): Update TfLiteTensorReset to include the new quantization // if there are other required callers. tensor.quantization = *scoped_quantization.release(); tensor.dims_signature = ConvertArrayToTfLiteIntArray(rank_dims_signature, dims_signature); return kTfLiteOk; } TfLiteStatus Subgraph::SetExecutionPlan(const std::vector<int>& new_plan) { for (int node_index : new_plan) { TF_LITE_ENSURE(&context_, node_index >= 0 && node_index < nodes_and_registration_.size()); } execution_plan_ = new_plan; return kTfLiteOk; } TfLiteStatus Subgraph::ResizeTensorImpl(TfLiteTensor* tensor, TfLiteIntArray* new_size) { // Note that in theory we could resize kTfLiteArenaRwPersistent tensors too. if (tensor->allocation_type == kTfLiteArenaRw || tensor->allocation_type == kTfLiteDynamic || tensor->allocation_type == kTfLiteArenaRwPersistent || tensor->allocation_type == kTfLitePersistentRo || tensor->allocation_type == kTfLiteCustom) { tensor_resized_since_op_invoke_ |= TfLiteIntArrayEqual(tensor->dims, new_size) == 0; if (tensor->type != kTfLiteString) { size_t bytesRequired; TfLiteStatus status = BytesRequired(tensor->type, new_size->data, new_size->size, &bytesRequired); if (status != kTfLiteOk) { TfLiteIntArrayFree(new_size); return kTfLiteError; } // Realloc space for heap-allocated tensors. TfLiteTensorRealloc(bytesRequired, tensor); tensor->bytes = bytesRequired; } if (tensor->dims) TfLiteIntArrayFree(tensor->dims); tensor->dims = new_size; // Reset arena-allocated tensors; they will be allocated later. if (tensor->allocation_type == kTfLiteArenaRw || tensor->allocation_type == kTfLiteArenaRwPersistent) { tensor->data.raw = nullptr; } } else { // kTfLiteMmapRo tensors are stored in the flatbuffer and are therefore // of fixed size. TfLiteIntArrayFree(new_size); ReportError("Attempting to resize a fixed-size tensor."); return kTfLiteError; } return kTfLiteOk; } void Subgraph::UseNNAPI(bool enable) { // Note that there is no way to disable the delegate once it modified the // graph. if (applied_nnapi_delegate_ && !enable) { ReportError("Attempting to disable NNAPI delegate after it's applied."); } else { should_apply_nnapi_delegate_ = enable; } } void Subgraph::SwitchToDelegateContext() { context_.GetNodeAndRegistration = GetNodeAndRegistration; context_.ReplaceNodeSubsetsWithDelegateKernels = ReplaceNodeSubsetsWithDelegateKernels; context_.GetExecutionPlan = GetExecutionPlan; context_.PreviewDelegatePartitioning = PreviewDelegatePartitioning; } void Subgraph::SwitchToKernelContext() { context_.GetNodeAndRegistration = [](struct TfLiteContext* context, int node_index, TfLiteNode** node, TfLiteRegistration** registration) { return ForbiddenContextFunction(context); }; context_.ReplaceNodeSubsetsWithDelegateKernels = [](TfLiteContext* context, TfLiteRegistration registration, const TfLiteIntArray* nodes_to_replace, TfLiteDelegate* delegate) { return ForbiddenContextFunction(context); }; context_.GetExecutionPlan = [](struct TfLiteContext* context, TfLiteIntArray**) { return ForbiddenContextFunction(context); }; context_.PreviewDelegatePartitioning = [](struct TfLiteContext* context, const TfLiteIntArray* nodes_to_replace, TfLiteDelegateParams** partition_params_array, int* num_partitions) { return ForbiddenContextFunction(context); }; // Free any memory that might have been allocated by // PreviewDelegatePartitioning. FreeDelegatePartitioningData(); } TfLiteStatus Subgraph::UndoAllDelegates() { // Return early if there is nothing to reset to. if (pre_delegation_execution_plan_.empty()) return kTfLiteOk; // First free all delegate nodes. for (int execution_plan_index = 0; execution_plan_index < execution_plan_.size(); ++execution_plan_index) { int node_index = execution_plan_[execution_plan_index]; TfLiteNode& node = nodes_and_registration_[node_index].first; if (node.delegate == nullptr) { continue; } CleanupNode(node_index); } // Reset execution plan. execution_plan_ = pre_delegation_execution_plan_; pre_delegation_execution_plan_.clear(); // Delegate nodes are appended to nodes_and_registration_. Therefore, // cleanup nodes_and_registration_ to only contain nodes from // pre_delegation_execution_plan_. int max_retained_node_index = 0; for (int execution_plan_index = 0; execution_plan_index < execution_plan_.size(); ++execution_plan_index) { max_retained_node_index = std::max(max_retained_node_index, execution_plan_[execution_plan_index]); } nodes_and_registration_.resize(max_retained_node_index + 1); // After undoing delegates, the graph is uninvokable, but mutable. state_ = kStateUninvokable; delegates_undone_ = true; return kTfLiteOk; } TfLiteStatus Subgraph::RedoAllDelegates() { if (!delegates_undone_) return kTfLiteOk; delegates_undone_ = false; std::vector<TfLiteDelegate*> delegates_to_apply; delegates_applied_.swap(delegates_to_apply); for (auto* delegate : delegates_to_apply) { TF_LITE_ENSURE_STATUS(ModifyGraphWithDelegate(delegate)); } return kTfLiteOk; } TfLiteStatus Subgraph::RemoveAllDelegates() { TF_LITE_ENSURE_STATUS(UndoAllDelegates()); delegates_applied_.clear(); delegates_undone_ = false; TF_LITE_ENSURE_STATUS(EnsureMemoryAllocations()); return kTfLiteOk; } bool Subgraph::HasDelegates() { return !delegates_applied_.empty(); } void Subgraph::EnsureTensorsVectorCapacity() { const size_t required_capacity = tensors_.size() + kTensorsCapacityHeadroom; if (required_capacity > tensors_.capacity()) { // Whenever it's required to increase the vector capacity, make it at // least twice bigger. The behavior is consistent with the default // behavior of GCC STL's `std::vector::resize()`. This avoids frequently // allocating and copying the underlying buffer. size_t reserved_capacity = std::max(required_capacity, tensors_.capacity() * 2); tensors_.reserve(reserved_capacity); context_.tensors = tensors_.data(); } } TfLiteStatus Subgraph::EnsureMemoryAllocations() { if (memory_planner_) { state_ = kStateUninvokable; TF_LITE_ENSURE_OK(&context_, memory_planner_->PlanAllocations()); } TF_LITE_ENSURE_OK(&context_, AllocateTensors()); TF_LITE_ENSURE_EQ(&context_, state_, kStateInvokable); return kTfLiteOk; } TfLiteStatus Subgraph::ModifyGraphWithDelegate(TfLiteDelegate* delegate) { TFLITE_SCOPED_TAGGED_DEFAULT_PROFILE(profiler_.get(), "ModifyGraphWithDelegate"); // Restore delegation state if applicable. TF_LITE_ENSURE_STATUS(RedoAllDelegates()); if (state_ == kStateInvokableAndImmutable) { ReportError( "ModifyGraphWithDelegate is disallowed when graph is immutable."); return kTfLiteApplicationError; } if (!(delegate->flags & kTfLiteDelegateFlagsAllowDynamicTensors)) { int last_execution_plan_index_prepared; TF_LITE_ENSURE_OK( &context_, PrepareOpsStartingAt(0, execution_plan_, &last_execution_plan_index_prepared)); if (has_dynamic_tensors_) { // Make sure that we are in a defined ready state before returning. // Plan and allocate tensors before returning. TF_LITE_ENSURE_OK(&context_, EnsureMemoryAllocations()); ReportError( "Attempting to use a delegate that only supports static-sized " "tensors with a graph that has dynamic-sized tensors."); return kTfLiteError; } } const bool was_invokable_before_delegate = state_ == kStateInvokable; if (delegates_applied_.empty()) { // This is the first delegate being applied, so remember original execution // plan. // TODO(b/119623453): Restore execution plan to this state if delegate // application fails. pre_delegation_execution_plan_ = execution_plan_; } // TODO(aselle): Consider if it is worth storing pointers to delegates. // Setup additional context interface. SwitchToDelegateContext(); auto reset_delegation_if_not_ok = [this](TfLiteStatus status) { if (status != kTfLiteOk) { TF_LITE_ENSURE_STATUS(RemoveAllDelegates()); ReportError( "Restored original execution plan after delegate application " "failure."); return kTfLiteDelegateError; } return kTfLiteOk; }; TfLiteStatus status = delegate->Prepare(&context_, delegate); // Remove additional context info. SwitchToKernelContext(); TF_LITE_ENSURE_STATUS(reset_delegation_if_not_ok(status)); if (!(delegate->flags & kTfLiteDelegateFlagsAllowDynamicTensors)) { // Reset the state to force tensor/op reallocation. state_ = kStateUninvokable; TF_LITE_ENSURE_STATUS( reset_delegation_if_not_ok(EnsureMemoryAllocations())); // After using a delegate which doesn't support dynamic tensors, make the // entire graph immutable. state_ = kStateInvokableAndImmutable; } else if (was_invokable_before_delegate) { // If the graph was invokable prior to delegate application, flush // allocation now to leave it in a consistent state. TF_LITE_ENSURE_STATUS( reset_delegation_if_not_ok(EnsureMemoryAllocations())); } delegates_applied_.push_back(delegate); return status; } TfLiteStatus Subgraph::SetCustomAllocationForTensor( int tensor_index, const TfLiteCustomAllocation& allocation) { TfLiteTensor* tensor = &context_.tensors[tensor_index]; TF_LITE_ENSURE(context(), (tensor->allocation_type == kTfLiteArenaRw || tensor->allocation_type == kTfLiteArenaRwPersistent || tensor->allocation_type == kTfLiteCustom)); TF_LITE_ENSURE_STATUS( ValidateCustomAllocationForTensor(context(), tensor, allocation)); // If tensor already has a custom alloc, just reassign. const auto alloc_it = std::find_if( custom_allocations_.begin(), custom_allocations_.end(), [tensor_index]( const std::pair<int, TfLiteCustomAllocation>& existing_alloc) { return existing_alloc.first == tensor_index; }); if (alloc_it == custom_allocations_.end()) { custom_allocations_.emplace_back(tensor_index, allocation); } else { alloc_it->second = allocation; } tensor->allocation_type = kTfLiteCustom; tensor->data.data = allocation.data; return kTfLiteOk; } } // namespace tflite
null
185
CWE-787
CVE-2020-15211
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <stdint.h> #include "tensorflow/lite/c/common.h" #include "tensorflow/lite/kernels/internal/reference/reference_ops.h" #include "tensorflow/lite/kernels/internal/tensor.h" #include "tensorflow/lite/kernels/internal/tensor_ctypes.h" #include "tensorflow/lite/kernels/kernel_util.h" namespace tflite { namespace ops { namespace builtin { namespace add_n { constexpr int kInputTensor1 = 0; constexpr int kOutputTensor = 0; TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { int num_inputs = NumInputs(node); TF_LITE_ENSURE(context, num_inputs >= 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); output->type = input1->type; // Check that all input tensors have the same shape and type. for (int i = kInputTensor1 + 1; i < num_inputs; ++i) { const TfLiteTensor* input = GetInput(context, node, i); TF_LITE_ENSURE(context, HaveSameShapes(input1, input)); TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input->type); } // Use the first input node's dimension to be the dimension of the output // node. TfLiteIntArray* input1_dims = input1->dims; TfLiteIntArray* output_dims = TfLiteIntArrayCopy(input1_dims); return context->ResizeTensor(context, output, output_dims); } template <typename T> void EvalAddN(TfLiteContext* context, TfLiteNode* node) { // TODO(haoliang): Initialize all_inputs only once during init. VectorOfTensors<T> all_inputs(*context, *node->inputs); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); int num_inputs = NumInputs(node); const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1); reference_ops::AddN<T>(GetTensorShape(input1), num_inputs, all_inputs.data(), GetTensorData<T>(output)); } TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* output = GetOutput(context, node, kOutputTensor); if (output->type == kTfLiteFloat32) { EvalAddN<float>(context, node); } else if (output->type == kTfLiteInt32) { EvalAddN<int32_t>(context, node); } else { context->ReportError(context, "AddN only supports FLOAT32|INT32 now, got %s.", TfLiteTypeGetName(output->type)); return kTfLiteError; } return kTfLiteOk; } } // namespace add_n TfLiteRegistration* Register_ADD_N() { static TfLiteRegistration r = {/*init*/ nullptr, /*free*/ nullptr, add_n::Prepare, add_n::Eval}; return &r; } } // namespace builtin } // namespace ops } // namespace tflite
null
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <stdint.h> #include "tensorflow/lite/c/common.h" #include "tensorflow/lite/kernels/internal/reference/reference_ops.h" #include "tensorflow/lite/kernels/internal/tensor.h" #include "tensorflow/lite/kernels/internal/tensor_ctypes.h" #include "tensorflow/lite/kernels/kernel_util.h" namespace tflite { namespace ops { namespace builtin { namespace add_n { constexpr int kInputTensor1 = 0; constexpr int kOutputTensor = 0; TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { int num_inputs = NumInputs(node); TF_LITE_ENSURE(context, num_inputs >= 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input1; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor1, &input1)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); output->type = input1->type; // Check that all input tensors have the same shape and type. for (int i = kInputTensor1 + 1; i < num_inputs; ++i) { const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, i, &input)); TF_LITE_ENSURE(context, HaveSameShapes(input1, input)); TF_LITE_ENSURE_TYPES_EQ(context, input1->type, input->type); } // Use the first input node's dimension to be the dimension of the output // node. TfLiteIntArray* input1_dims = input1->dims; TfLiteIntArray* output_dims = TfLiteIntArrayCopy(input1_dims); return context->ResizeTensor(context, output, output_dims); } template <typename T> void EvalAddN(TfLiteContext* context, TfLiteNode* node) { // TODO(haoliang): Initialize all_inputs only once during init. VectorOfTensors<T> all_inputs(*context, *node->inputs); // Safe to use unchecked since caller checks that tensor is valid TfLiteTensor* output = GetOutput(context, node, kOutputTensor); int num_inputs = NumInputs(node); // Safe to use unchecked since caller checks that tensor is valid const TfLiteTensor* input1 = GetInput(context, node, kInputTensor1); reference_ops::AddN<T>(GetTensorShape(input1), num_inputs, all_inputs.data(), GetTensorData<T>(output)); } TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* input1; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor1, &input1)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); if (output->type == kTfLiteFloat32) { EvalAddN<float>(context, node); } else if (output->type == kTfLiteInt32) { EvalAddN<int32_t>(context, node); } else { context->ReportError(context, "AddN only supports FLOAT32|INT32 now, got %s.", TfLiteTypeGetName(output->type)); return kTfLiteError; } return kTfLiteOk; } } // namespace add_n TfLiteRegistration* Register_ADD_N() { static TfLiteRegistration r = {/*init*/ nullptr, /*free*/ nullptr, add_n::Prepare, add_n::Eval}; return &r; } } // namespace builtin } // namespace ops } // namespace tflite
null
186
CWE-787
CVE-2020-15212
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <stdint.h> #include <vector> #include <gtest/gtest.h> #include "tensorflow/lite/kernels/test_util.h" #include "tensorflow/lite/schema/schema_generated.h" namespace tflite { namespace { using ::testing::ElementsAreArray; template <typename T> class SegmentSumOpModel : public SingleOpModel { public: SegmentSumOpModel(const TensorData& data, const TensorData& segment_ids) { data_id_ = AddInput(data); segment_ids_id_ = AddInput(segment_ids); output_id_ = AddOutput(data.type); SetBuiltinOp(BuiltinOperator_SEGMENT_SUM, BuiltinOptions_NONE, 0); BuildInterpreter({GetShape(data_id_), GetShape(segment_ids_id_)}); } int data() const { return data_id_; } int segment_ids() const { return segment_ids_id_; } std::vector<T> GetOutput() { return ExtractVector<T>(output_id_); } std::vector<int32_t> GetOutputShape() { return GetTensorShape(output_id_); } protected: int data_id_; int segment_ids_id_; int output_id_; }; TEST(SegmentSumOpModelTest, Int32Test_Simple) { SegmentSumOpModel<int32_t> model({TensorType_INT32, {3, 4}}, {TensorType_INT32, {3}}); model.PopulateTensor<int32_t>(model.data(), {1, 2, 3, 4, 4, 3, 2, 1, 5, 6, 7, 8}); model.PopulateTensor<int32_t>(model.segment_ids(), {0, 0, 1}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({5, 5, 5, 5, 5, 6, 7, 8})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({2, 4})); } TEST(SegmentSumOpModelTest, Int32Test_OneDimension) { SegmentSumOpModel<int32_t> model({TensorType_INT32, {3}}, {TensorType_INT32, {3}}); model.PopulateTensor<int32_t>(model.data(), {1, 2, 3}); model.PopulateTensor<int32_t>(model.segment_ids(), {0, 0, 1}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({3, 3})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({2})); } TEST(SegmentSumOpModelTest, Int32Test_ThreeDimensions) { SegmentSumOpModel<int32_t> model({TensorType_INT32, {3, 2, 1}}, {TensorType_INT32, {3}}); model.PopulateTensor<int32_t>(model.data(), {1, 2, 3, 4, 5, 6}); model.PopulateTensor<int32_t>(model.segment_ids(), {0, 0, 1}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({4, 6, 5, 6})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({2, 2, 1})); } TEST(SegmentSumOpModelTest, Float32Test_Simple) { SegmentSumOpModel<float> model({TensorType_FLOAT32, {3, 4}}, {TensorType_INT32, {3}}); model.PopulateTensor<float>(model.data(), {1, 2, 3, 4, 4, 3, 2, 1, 5, 6, 7, 8}); model.PopulateTensor<int>(model.segment_ids(), {0, 0, 1}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({5.0f, 5.0f, 5.0f, 5.0f, 5.0f, 6.0f, 7.0f, 8.0f})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({2, 4})); } TEST(SegmentSumOpModelTest, Float32Test_OneDimension) { SegmentSumOpModel<float> model({TensorType_FLOAT32, {3}}, {TensorType_INT32, {3}}); model.PopulateTensor<float>(model.data(), {1, 2, 3}); model.PopulateTensor<int32_t>(model.segment_ids(), {0, 0, 1}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({3.0f, 3.0f})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({2})); } TEST(SegmentSumOpModelTest, Float32Test_ThreeDimensions) { SegmentSumOpModel<float> model({TensorType_FLOAT32, {3, 2, 1}}, {TensorType_INT32, {3}}); model.PopulateTensor<float>(model.data(), {1, 2, 3, 4, 5, 6}); model.PopulateTensor<int32_t>(model.segment_ids(), {0, 0, 1}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({4.0f, 6.0f, 5.0f, 6.0f})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({2, 2, 1})); } } // namespace } // namespace tflite
null
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <stdint.h> #include <vector> #include <gtest/gtest.h> #include "tensorflow/lite/kernels/test_util.h" #include "tensorflow/lite/schema/schema_generated.h" namespace tflite { namespace { using ::testing::ElementsAreArray; template <typename T> class SegmentSumOpModel : public SingleOpModel { public: SegmentSumOpModel(const TensorData& data, const TensorData& segment_ids) { data_id_ = AddInput(data); segment_ids_id_ = AddInput(segment_ids); output_id_ = AddOutput(data.type); SetBuiltinOp(BuiltinOperator_SEGMENT_SUM, BuiltinOptions_NONE, 0); BuildInterpreter({GetShape(data_id_), GetShape(segment_ids_id_)}); } int data() const { return data_id_; } int segment_ids() const { return segment_ids_id_; } std::vector<T> GetOutput() { return ExtractVector<T>(output_id_); } std::vector<int32_t> GetOutputShape() { return GetTensorShape(output_id_); } protected: int data_id_; int segment_ids_id_; int output_id_; }; TEST(SegmentSumOpModelTest, Int32Test_Simple) { SegmentSumOpModel<int32_t> model({TensorType_INT32, {3, 4}}, {TensorType_INT32, {3}}); model.PopulateTensor<int32_t>(model.data(), {1, 2, 3, 4, 4, 3, 2, 1, 5, 6, 7, 8}); model.PopulateTensor<int32_t>(model.segment_ids(), {0, 0, 1}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({5, 5, 5, 5, 5, 6, 7, 8})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({2, 4})); } TEST(SegmentSumOpModelTest, Int32Test_OneDimension) { SegmentSumOpModel<int32_t> model({TensorType_INT32, {3}}, {TensorType_INT32, {3}}); model.PopulateTensor<int32_t>(model.data(), {1, 2, 3}); model.PopulateTensor<int32_t>(model.segment_ids(), {0, 0, 1}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({3, 3})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({2})); } TEST(SegmentSumOpModelTest, Int32Test_ThreeDimensions) { SegmentSumOpModel<int32_t> model({TensorType_INT32, {3, 2, 1}}, {TensorType_INT32, {3}}); model.PopulateTensor<int32_t>(model.data(), {1, 2, 3, 4, 5, 6}); model.PopulateTensor<int32_t>(model.segment_ids(), {0, 0, 1}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({4, 6, 5, 6})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({2, 2, 1})); } TEST(SegmentSumOpModelTest, Float32Test_Simple) { SegmentSumOpModel<float> model({TensorType_FLOAT32, {3, 4}}, {TensorType_INT32, {3}}); model.PopulateTensor<float>(model.data(), {1, 2, 3, 4, 4, 3, 2, 1, 5, 6, 7, 8}); model.PopulateTensor<int>(model.segment_ids(), {0, 0, 1}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({5.0f, 5.0f, 5.0f, 5.0f, 5.0f, 6.0f, 7.0f, 8.0f})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({2, 4})); } TEST(SegmentSumOpModelTest, Float32Test_OneDimension) { SegmentSumOpModel<float> model({TensorType_FLOAT32, {3}}, {TensorType_INT32, {3}}); model.PopulateTensor<float>(model.data(), {1, 2, 3}); model.PopulateTensor<int32_t>(model.segment_ids(), {0, 0, 1}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({3.0f, 3.0f})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({2})); } TEST(SegmentSumOpModelTest, Float32Test_ThreeDimensions) { SegmentSumOpModel<float> model({TensorType_FLOAT32, {3, 2, 1}}, {TensorType_INT32, {3}}); model.PopulateTensor<float>(model.data(), {1, 2, 3, 4, 5, 6}); model.PopulateTensor<int32_t>(model.segment_ids(), {0, 0, 1}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({4.0f, 6.0f, 5.0f, 6.0f})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({2, 2, 1})); } TEST(SegmentSumOpModelTest, TestFailIfSegmentsAreNotSorted) { SegmentSumOpModel<int32_t> model({TensorType_INT32, {3, 2}}, {TensorType_INT32, {3}}); model.PopulateTensor<int32_t>(model.data(), {1, 2, 3, 4, 5, 6}); model.PopulateTensor<int32_t>(model.segment_ids(), {0, 3, 1}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteError); } TEST(SegmentSumOpModelTest, TestFailIfSegmentsAreNotConsecutive) { SegmentSumOpModel<int32_t> model({TensorType_INT32, {3, 2}}, {TensorType_INT32, {3}}); model.PopulateTensor<int32_t>(model.data(), {1, 2, 3, 4, 5, 6}); model.PopulateTensor<int32_t>(model.segment_ids(), {0, 3, 5}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteError); } TEST(SegmentSumOpModelTest, TestFailIfSegmentsAreNegative) { SegmentSumOpModel<int32_t> model({TensorType_INT32, {3, 2}}, {TensorType_INT32, {3}}); model.PopulateTensor<int32_t>(model.data(), {1, 2, 3, 4, 5, 6}); model.PopulateTensor<int32_t>(model.segment_ids(), {-1, 0, 1}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteError); } TEST(SegmentSumOpModelTest, TestFailIfSegmentsAreNotTheRightCardinality) { SegmentSumOpModel<int32_t> model({TensorType_INT32, {3, 2}}, {TensorType_INT32, {2}}); model.PopulateTensor<int32_t>(model.data(), {1, 2, 3, 4, 5, 6}); model.PopulateTensor<int32_t>(model.segment_ids(), {0, 1}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteError); } } // namespace } // namespace tflite
null
187
CWE-787
CVE-2020-15214
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <stdint.h> #include <vector> #include <gtest/gtest.h> #include "tensorflow/lite/kernels/test_util.h" #include "tensorflow/lite/schema/schema_generated.h" namespace tflite { namespace { using ::testing::ElementsAreArray; template <typename T> class SegmentSumOpModel : public SingleOpModel { public: SegmentSumOpModel(const TensorData& data, const TensorData& segment_ids) { data_id_ = AddInput(data); segment_ids_id_ = AddInput(segment_ids); output_id_ = AddOutput(data.type); SetBuiltinOp(BuiltinOperator_SEGMENT_SUM, BuiltinOptions_NONE, 0); BuildInterpreter({GetShape(data_id_), GetShape(segment_ids_id_)}); } int data() const { return data_id_; } int segment_ids() const { return segment_ids_id_; } std::vector<T> GetOutput() { return ExtractVector<T>(output_id_); } std::vector<int32_t> GetOutputShape() { return GetTensorShape(output_id_); } protected: int data_id_; int segment_ids_id_; int output_id_; }; TEST(SegmentSumOpModelTest, Int32Test_Simple) { SegmentSumOpModel<int32_t> model({TensorType_INT32, {3, 4}}, {TensorType_INT32, {3}}); model.PopulateTensor<int32_t>(model.data(), {1, 2, 3, 4, 4, 3, 2, 1, 5, 6, 7, 8}); model.PopulateTensor<int32_t>(model.segment_ids(), {0, 0, 1}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({5, 5, 5, 5, 5, 6, 7, 8})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({2, 4})); } TEST(SegmentSumOpModelTest, Int32Test_OneDimension) { SegmentSumOpModel<int32_t> model({TensorType_INT32, {3}}, {TensorType_INT32, {3}}); model.PopulateTensor<int32_t>(model.data(), {1, 2, 3}); model.PopulateTensor<int32_t>(model.segment_ids(), {0, 0, 1}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({3, 3})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({2})); } TEST(SegmentSumOpModelTest, Int32Test_ThreeDimensions) { SegmentSumOpModel<int32_t> model({TensorType_INT32, {3, 2, 1}}, {TensorType_INT32, {3}}); model.PopulateTensor<int32_t>(model.data(), {1, 2, 3, 4, 5, 6}); model.PopulateTensor<int32_t>(model.segment_ids(), {0, 0, 1}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({4, 6, 5, 6})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({2, 2, 1})); } TEST(SegmentSumOpModelTest, Float32Test_Simple) { SegmentSumOpModel<float> model({TensorType_FLOAT32, {3, 4}}, {TensorType_INT32, {3}}); model.PopulateTensor<float>(model.data(), {1, 2, 3, 4, 4, 3, 2, 1, 5, 6, 7, 8}); model.PopulateTensor<int>(model.segment_ids(), {0, 0, 1}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({5.0f, 5.0f, 5.0f, 5.0f, 5.0f, 6.0f, 7.0f, 8.0f})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({2, 4})); } TEST(SegmentSumOpModelTest, Float32Test_OneDimension) { SegmentSumOpModel<float> model({TensorType_FLOAT32, {3}}, {TensorType_INT32, {3}}); model.PopulateTensor<float>(model.data(), {1, 2, 3}); model.PopulateTensor<int32_t>(model.segment_ids(), {0, 0, 1}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({3.0f, 3.0f})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({2})); } TEST(SegmentSumOpModelTest, Float32Test_ThreeDimensions) { SegmentSumOpModel<float> model({TensorType_FLOAT32, {3, 2, 1}}, {TensorType_INT32, {3}}); model.PopulateTensor<float>(model.data(), {1, 2, 3, 4, 5, 6}); model.PopulateTensor<int32_t>(model.segment_ids(), {0, 0, 1}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({4.0f, 6.0f, 5.0f, 6.0f})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({2, 2, 1})); } } // namespace } // namespace tflite
null
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <stdint.h> #include <vector> #include <gtest/gtest.h> #include "tensorflow/lite/kernels/test_util.h" #include "tensorflow/lite/schema/schema_generated.h" namespace tflite { namespace { using ::testing::ElementsAreArray; template <typename T> class SegmentSumOpModel : public SingleOpModel { public: SegmentSumOpModel(const TensorData& data, const TensorData& segment_ids) { data_id_ = AddInput(data); segment_ids_id_ = AddInput(segment_ids); output_id_ = AddOutput(data.type); SetBuiltinOp(BuiltinOperator_SEGMENT_SUM, BuiltinOptions_NONE, 0); BuildInterpreter({GetShape(data_id_), GetShape(segment_ids_id_)}); } int data() const { return data_id_; } int segment_ids() const { return segment_ids_id_; } std::vector<T> GetOutput() { return ExtractVector<T>(output_id_); } std::vector<int32_t> GetOutputShape() { return GetTensorShape(output_id_); } protected: int data_id_; int segment_ids_id_; int output_id_; }; TEST(SegmentSumOpModelTest, Int32Test_Simple) { SegmentSumOpModel<int32_t> model({TensorType_INT32, {3, 4}}, {TensorType_INT32, {3}}); model.PopulateTensor<int32_t>(model.data(), {1, 2, 3, 4, 4, 3, 2, 1, 5, 6, 7, 8}); model.PopulateTensor<int32_t>(model.segment_ids(), {0, 0, 1}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({5, 5, 5, 5, 5, 6, 7, 8})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({2, 4})); } TEST(SegmentSumOpModelTest, Int32Test_OneDimension) { SegmentSumOpModel<int32_t> model({TensorType_INT32, {3}}, {TensorType_INT32, {3}}); model.PopulateTensor<int32_t>(model.data(), {1, 2, 3}); model.PopulateTensor<int32_t>(model.segment_ids(), {0, 0, 1}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({3, 3})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({2})); } TEST(SegmentSumOpModelTest, Int32Test_ThreeDimensions) { SegmentSumOpModel<int32_t> model({TensorType_INT32, {3, 2, 1}}, {TensorType_INT32, {3}}); model.PopulateTensor<int32_t>(model.data(), {1, 2, 3, 4, 5, 6}); model.PopulateTensor<int32_t>(model.segment_ids(), {0, 0, 1}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({4, 6, 5, 6})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({2, 2, 1})); } TEST(SegmentSumOpModelTest, Float32Test_Simple) { SegmentSumOpModel<float> model({TensorType_FLOAT32, {3, 4}}, {TensorType_INT32, {3}}); model.PopulateTensor<float>(model.data(), {1, 2, 3, 4, 4, 3, 2, 1, 5, 6, 7, 8}); model.PopulateTensor<int>(model.segment_ids(), {0, 0, 1}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({5.0f, 5.0f, 5.0f, 5.0f, 5.0f, 6.0f, 7.0f, 8.0f})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({2, 4})); } TEST(SegmentSumOpModelTest, Float32Test_OneDimension) { SegmentSumOpModel<float> model({TensorType_FLOAT32, {3}}, {TensorType_INT32, {3}}); model.PopulateTensor<float>(model.data(), {1, 2, 3}); model.PopulateTensor<int32_t>(model.segment_ids(), {0, 0, 1}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({3.0f, 3.0f})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({2})); } TEST(SegmentSumOpModelTest, Float32Test_ThreeDimensions) { SegmentSumOpModel<float> model({TensorType_FLOAT32, {3, 2, 1}}, {TensorType_INT32, {3}}); model.PopulateTensor<float>(model.data(), {1, 2, 3, 4, 5, 6}); model.PopulateTensor<int32_t>(model.segment_ids(), {0, 0, 1}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({4.0f, 6.0f, 5.0f, 6.0f})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({2, 2, 1})); } TEST(SegmentSumOpModelTest, TestFailIfSegmentsAreNotSorted) { SegmentSumOpModel<int32_t> model({TensorType_INT32, {3, 2}}, {TensorType_INT32, {3}}); model.PopulateTensor<int32_t>(model.data(), {1, 2, 3, 4, 5, 6}); model.PopulateTensor<int32_t>(model.segment_ids(), {0, 3, 1}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteError); } TEST(SegmentSumOpModelTest, TestFailIfSegmentsAreNotConsecutive) { SegmentSumOpModel<int32_t> model({TensorType_INT32, {3, 2}}, {TensorType_INT32, {3}}); model.PopulateTensor<int32_t>(model.data(), {1, 2, 3, 4, 5, 6}); model.PopulateTensor<int32_t>(model.segment_ids(), {0, 3, 5}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteError); } TEST(SegmentSumOpModelTest, TestFailIfSegmentsAreNegative) { SegmentSumOpModel<int32_t> model({TensorType_INT32, {3, 2}}, {TensorType_INT32, {3}}); model.PopulateTensor<int32_t>(model.data(), {1, 2, 3, 4, 5, 6}); model.PopulateTensor<int32_t>(model.segment_ids(), {-1, 0, 1}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteError); } TEST(SegmentSumOpModelTest, TestFailIfSegmentsAreNotTheRightCardinality) { SegmentSumOpModel<int32_t> model({TensorType_INT32, {3, 2}}, {TensorType_INT32, {2}}); model.PopulateTensor<int32_t>(model.data(), {1, 2, 3, 4, 5, 6}); model.PopulateTensor<int32_t>(model.segment_ids(), {0, 1}); ASSERT_EQ(model.InvokeUnchecked(), kTfLiteError); } } // namespace } // namespace tflite
null
188
CWE-787
CVE-2020-15474
/* * tls.c - SSL/TLS/DTLS dissector * * Copyright (C) 2016-20 - ntop.org * * This file is part of nDPI, an open source deep packet inspection * library based on the OpenDPI and PACE technology by ipoque GmbH * * nDPI is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * nDPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with nDPI. If not, see <http://www.gnu.org/licenses/>. * */ #include "ndpi_protocol_ids.h" #define NDPI_CURRENT_PROTO NDPI_PROTOCOL_TLS #include "ndpi_api.h" #include "ndpi_md5.h" #include "ndpi_sha1.h" extern char *strptime(const char *s, const char *format, struct tm *tm); extern int processClientServerHello(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow); // #define DEBUG_TLS_MEMORY 1 // #define DEBUG_TLS 1 // #define DEBUG_CERTIFICATE_HASH /* #define DEBUG_FINGERPRINT 1 */ /* #define DEBUG_ENCRYPTED_SNI 1 */ /* NOTE How to view the certificate fingerprint 1. Using wireshark save the certificate on certificate.bin file as explained in https://security.stackexchange.com/questions/123851/how-can-i-extract-the-certificate-from-this-pcap-file 2. openssl x509 -inform der -in certificate.bin -text > certificate.der 3. openssl x509 -noout -fingerprint -sha1 -inform pem -in certificate.der SHA1 Fingerprint=15:9A:76.... $ shasum -a 1 www.grc.com.bin 159a76..... */ #define NDPI_MAX_TLS_REQUEST_SIZE 10000 /* skype.c */ extern u_int8_t is_skype_flow(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow); /* stun.c */ extern u_int32_t get_stun_lru_key(struct ndpi_flow_struct *flow, u_int8_t rev); static void ndpi_int_tls_add_connection(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow, u_int32_t protocol); /* **************************************** */ static u_int32_t ndpi_tls_refine_master_protocol(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow, u_int32_t protocol) { struct ndpi_packet_struct *packet = &flow->packet; // protocol = NDPI_PROTOCOL_TLS; if(packet->tcp != NULL) { switch(protocol) { case NDPI_PROTOCOL_TLS: { /* In case of SSL there are probably sub-protocols such as IMAPS that can be otherwise detected */ u_int16_t sport = ntohs(packet->tcp->source); u_int16_t dport = ntohs(packet->tcp->dest); if((sport == 465) || (dport == 465) || (sport == 587) || (dport == 587)) protocol = NDPI_PROTOCOL_MAIL_SMTPS; else if((sport == 993) || (dport == 993) || (flow->l4.tcp.mail_imap_starttls) ) protocol = NDPI_PROTOCOL_MAIL_IMAPS; else if((sport == 995) || (dport == 995)) protocol = NDPI_PROTOCOL_MAIL_POPS; } break; } } return(protocol); } /* **************************************** */ void ndpi_search_tls_tcp_memory(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; /* TCP */ #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] Handling TCP/TLS flow [payload_len: %u][buffer_len: %u][direction: %u]\n", packet->payload_packet_len, flow->l4.tcp.tls.message.buffer_len, packet->packet_direction); #endif if(flow->l4.tcp.tls.message.buffer == NULL) { /* Allocate buffer */ flow->l4.tcp.tls.message.buffer_len = 2048, flow->l4.tcp.tls.message.buffer_used = 0; flow->l4.tcp.tls.message.buffer = (u_int8_t*)ndpi_malloc(flow->l4.tcp.tls.message.buffer_len); if(flow->l4.tcp.tls.message.buffer == NULL) return; #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] Allocating %u buffer\n", flow->l4.tcp.tls.message.buffer_len); #endif } u_int avail_bytes = flow->l4.tcp.tls.message.buffer_len - flow->l4.tcp.tls.message.buffer_used; if(avail_bytes < packet->payload_packet_len) { u_int new_len = flow->l4.tcp.tls.message.buffer_len + packet->payload_packet_len; void *newbuf = ndpi_realloc(flow->l4.tcp.tls.message.buffer, flow->l4.tcp.tls.message.buffer_len, new_len); if(!newbuf) return; flow->l4.tcp.tls.message.buffer = (u_int8_t*)newbuf, flow->l4.tcp.tls.message.buffer_len = new_len; avail_bytes = flow->l4.tcp.tls.message.buffer_len - flow->l4.tcp.tls.message.buffer_used; #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] Enlarging %u -> %u buffer\n", flow->l4.tcp.tls.message.buffer_len, new_len); #endif } if(avail_bytes >= packet->payload_packet_len) { memcpy(&flow->l4.tcp.tls.message.buffer[flow->l4.tcp.tls.message.buffer_used], packet->payload, packet->payload_packet_len); flow->l4.tcp.tls.message.buffer_used += packet->payload_packet_len; #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] Copied data to buffer [%u/%u bytes]\n", flow->l4.tcp.tls.message.buffer_used, flow->l4.tcp.tls.message.buffer_len); #endif } } /* **************************************** */ /* Can't call libc functions from kernel space, define some stub instead */ #define ndpi_isalpha(ch) (((ch) >= 'a' && (ch) <= 'z') || ((ch) >= 'A' && (ch) <= 'Z')) #define ndpi_isdigit(ch) ((ch) >= '0' && (ch) <= '9') #define ndpi_isspace(ch) (((ch) >= '\t' && (ch) <= '\r') || ((ch) == ' ')) #define ndpi_isprint(ch) ((ch) >= 0x20 && (ch) <= 0x7e) #define ndpi_ispunct(ch) (((ch) >= '!' && (ch) <= '/') || \ ((ch) >= ':' && (ch) <= '@') || \ ((ch) >= '[' && (ch) <= '`') || \ ((ch) >= '{' && (ch) <= '~')) /* **************************************** */ static void cleanupServerName(char *buffer, int buffer_len) { u_int i; /* Now all lowecase */ for(i=0; i<buffer_len; i++) buffer[i] = tolower(buffer[i]); } /* **************************************** */ /* Return code -1: error (buffer too short) 0: OK but buffer is not human readeable (so something went wrong) 1: OK */ static int extractRDNSequence(struct ndpi_packet_struct *packet, u_int offset, char *buffer, u_int buffer_len, char *rdnSeqBuf, u_int *rdnSeqBuf_offset, u_int rdnSeqBuf_len, const char *label) { u_int8_t str_len = packet->payload[offset+4], is_printable = 1; char *str; u_int len, j; // packet is truncated... further inspection is not needed if((offset+4+str_len) >= packet->payload_packet_len) return(-1); str = (char*)&packet->payload[offset+5]; len = (u_int)ndpi_min(str_len, buffer_len-1); strncpy(buffer, str, len); buffer[len] = '\0'; // check string is printable for(j = 0; j < len; j++) { if(!ndpi_isprint(buffer[j])) { is_printable = 0; break; } } if(is_printable) { int rc = snprintf(&rdnSeqBuf[*rdnSeqBuf_offset], rdnSeqBuf_len-(*rdnSeqBuf_offset), "%s%s=%s", (*rdnSeqBuf_offset > 0) ? ", " : "", label, buffer); if(rc > 0) (*rdnSeqBuf_offset) += rc; } return(is_printable); } /* **************************************** */ /* See https://blog.catchpoint.com/2017/05/12/dissecting-tls-using-wireshark/ */ static void processCertificateElements(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow, u_int16_t p_offset, u_int16_t certificate_len) { struct ndpi_packet_struct *packet = &flow->packet; u_int num_found = 0, i; char buffer[64] = { '\0' }, rdnSeqBuf[1024] = { '\0' }; u_int rdn_len = 0; #ifdef DEBUG_TLS printf("[TLS] %s() [offset: %u][certificate_len: %u]\n", __FUNCTION__, p_offset, certificate_len); #endif /* Check after handshake protocol header (5 bytes) and message header (4 bytes) */ for(i = p_offset; i < certificate_len; i++) { /* See https://www.ibm.com/support/knowledgecenter/SSFKSJ_7.5.0/com.ibm.mq.sec.doc/q009860_.htm for X.509 certificate labels */ if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x03)) { /* Common Name */ int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "CN"); if(rc == -1) break; #ifdef DEBUG_TLS printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "Common Name", buffer); #endif } else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x06)) { /* Country */ int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "C"); if(rc == -1) break; #ifdef DEBUG_TLS printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "Country", buffer); #endif } else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x07)) { /* Locality */ int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "L"); if(rc == -1) break; #ifdef DEBUG_TLS printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "Locality", buffer); #endif } else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x08)) { /* State or Province */ int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "ST"); if(rc == -1) break; #ifdef DEBUG_TLS printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "State or Province", buffer); #endif } else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x0a)) { /* Organization Name */ int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "O"); if(rc == -1) break; #ifdef DEBUG_TLS printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "Organization Name", buffer); #endif } else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x0b)) { /* Organization Unit */ int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "OU"); if(rc == -1) break; #ifdef DEBUG_TLS printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "Organization Unit", buffer); #endif } else if((packet->payload[i] == 0x30) && (packet->payload[i+1] == 0x1e) && (packet->payload[i+2] == 0x17)) { /* Certificate Validity */ u_int8_t len = packet->payload[i+3]; u_int offset = i+4; if(num_found == 0) { num_found++; #ifdef DEBUG_TLS printf("[TLS] %s() IssuerDN [%s]\n", __FUNCTION__, rdnSeqBuf); #endif if(rdn_len) flow->protos.stun_ssl.ssl.issuerDN = ndpi_strdup(rdnSeqBuf); rdn_len = 0; /* Reset buffer */ } if((offset+len) < packet->payload_packet_len) { char utcDate[32]; #ifdef DEBUG_TLS u_int j; printf("[CERTIFICATE] notBefore [len: %u][", len); for(j=0; j<len; j++) printf("%c", packet->payload[i+4+j]); printf("]\n"); #endif if(len < (sizeof(utcDate)-1)) { struct tm utc; utc.tm_isdst = -1; /* Not set by strptime */ strncpy(utcDate, (const char*)&packet->payload[i+4], len); utcDate[len] = '\0'; /* 141021000000Z */ if(strptime(utcDate, "%y%m%d%H%M%SZ", &utc) != NULL) { flow->protos.stun_ssl.ssl.notBefore = timegm(&utc); #ifdef DEBUG_TLS printf("[CERTIFICATE] notBefore %u [%s]\n", flow->protos.stun_ssl.ssl.notBefore, utcDate); #endif } } offset += len; if((offset+1) < packet->payload_packet_len) { len = packet->payload[offset+1]; offset += 2; if((offset+len) < packet->payload_packet_len) { u_int32_t time_sec = flow->packet.current_time_ms / 1000; #ifdef DEBUG_TLS u_int j; printf("[CERTIFICATE] notAfter [len: %u][", len); for(j=0; j<len; j++) printf("%c", packet->payload[offset+j]); printf("]\n"); #endif if(len < (sizeof(utcDate)-1)) { struct tm utc; utc.tm_isdst = -1; /* Not set by strptime */ strncpy(utcDate, (const char*)&packet->payload[offset], len); utcDate[len] = '\0'; /* 141021000000Z */ if(strptime(utcDate, "%y%m%d%H%M%SZ", &utc) != NULL) { flow->protos.stun_ssl.ssl.notAfter = timegm(&utc); #ifdef DEBUG_TLS printf("[CERTIFICATE] notAfter %u [%s]\n", flow->protos.stun_ssl.ssl.notAfter, utcDate); #endif } } if((time_sec < flow->protos.stun_ssl.ssl.notBefore) || (time_sec > flow->protos.stun_ssl.ssl.notAfter)) NDPI_SET_BIT(flow->risk, NDPI_TLS_CERTIFICATE_EXPIRED); /* Certificate expired */ } } } } else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x1d) && (packet->payload[i+2] == 0x11)) { /* Organization OID: 2.5.29.17 (subjectAltName) */ u_int8_t matched_name = 0; #ifdef DEBUG_TLS printf("******* [TLS] Found subjectAltName\n"); #endif i += 3 /* skip the initial patten 55 1D 11 */; i++; /* skip the first type, 0x04 == BIT STRING, and jump to it's length */ if(i < packet->payload_packet_len) { i += (packet->payload[i] & 0x80) ? (packet->payload[i] & 0x7F) : 0; /* skip BIT STRING length */ if(i < packet->payload_packet_len) { i += 2; /* skip the second type, 0x30 == SEQUENCE, and jump to it's length */ if(i < packet->payload_packet_len) { i += (packet->payload[i] & 0x80) ? (packet->payload[i] & 0x7F) : 0; /* skip SEQUENCE length */ i++; while(i < packet->payload_packet_len) { if(packet->payload[i] == 0x82) { if((i < (packet->payload_packet_len - 1)) && ((i + packet->payload[i + 1] + 2) < packet->payload_packet_len)) { u_int8_t len = packet->payload[i + 1]; char dNSName[256]; i += 2; /* The check "len > sizeof(dNSName) - 1" will be always false. If we add it, the compiler is smart enough to detect it and throws a warning */ if(len == 0 /* Looks something went wrong */) break; strncpy(dNSName, (const char*)&packet->payload[i], len); dNSName[len] = '\0'; cleanupServerName(dNSName, len); #if DEBUG_TLS printf("[TLS] dNSName %s [%s]\n", dNSName, flow->protos.stun_ssl.ssl.client_requested_server_name); #endif if(matched_name == 0) { if((dNSName[0] == '*') && strstr(flow->protos.stun_ssl.ssl.client_requested_server_name, &dNSName[1])) matched_name = 1; else if(strcmp(flow->protos.stun_ssl.ssl.client_requested_server_name, dNSName) == 0) matched_name = 1; } if(flow->protos.stun_ssl.ssl.server_names == NULL) flow->protos.stun_ssl.ssl.server_names = ndpi_strdup(dNSName), flow->protos.stun_ssl.ssl.server_names_len = strlen(dNSName); else { u_int16_t dNSName_len = strlen(dNSName); u_int16_t newstr_len = flow->protos.stun_ssl.ssl.server_names_len + dNSName_len + 1; char *newstr = (char*)ndpi_realloc(flow->protos.stun_ssl.ssl.server_names, flow->protos.stun_ssl.ssl.server_names_len+1, newstr_len+1); if(newstr) { flow->protos.stun_ssl.ssl.server_names = newstr; flow->protos.stun_ssl.ssl.server_names[flow->protos.stun_ssl.ssl.server_names_len] = ','; strncpy(&flow->protos.stun_ssl.ssl.server_names[flow->protos.stun_ssl.ssl.server_names_len+1], dNSName, dNSName_len+1); flow->protos.stun_ssl.ssl.server_names[newstr_len] = '\0'; flow->protos.stun_ssl.ssl.server_names_len = newstr_len; } } if(!flow->l4.tcp.tls.subprotocol_detected) if(ndpi_match_hostname_protocol(ndpi_struct, flow, NDPI_PROTOCOL_TLS, dNSName, len)) flow->l4.tcp.tls.subprotocol_detected = 1; i += len; } else { #if DEBUG_TLS printf("[TLS] Leftover %u bytes", packet->payload_packet_len - i); #endif break; } } else { break; } } /* while */ if(!matched_name) NDPI_SET_BIT(flow->risk, NDPI_TLS_CERTIFICATE_MISMATCH); /* Certificate mismatch */ } } } } } if(rdn_len) flow->protos.stun_ssl.ssl.subjectDN = ndpi_strdup(rdnSeqBuf); if(flow->protos.stun_ssl.ssl.subjectDN && flow->protos.stun_ssl.ssl.issuerDN && (!strcmp(flow->protos.stun_ssl.ssl.subjectDN, flow->protos.stun_ssl.ssl.issuerDN))) NDPI_SET_BIT(flow->risk, NDPI_TLS_SELFSIGNED_CERTIFICATE); #if DEBUG_TLS printf("[TLS] %s() SubjectDN [%s]\n", __FUNCTION__, rdnSeqBuf); #endif } /* **************************************** */ /* See https://blog.catchpoint.com/2017/05/12/dissecting-tls-using-wireshark/ */ int processCertificate(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; u_int32_t certificates_length, length = (packet->payload[1] << 16) + (packet->payload[2] << 8) + packet->payload[3]; u_int16_t certificates_offset = 7; u_int8_t num_certificates_found = 0; #ifdef DEBUG_TLS printf("[TLS] %s() [payload_packet_len=%u][direction: %u][%02X %02X %02X %02X %02X %02X...]\n", __FUNCTION__, packet->payload_packet_len, packet->packet_direction, packet->payload[0], packet->payload[1], packet->payload[2], packet->payload[3], packet->payload[4], packet->payload[5]); #endif if((packet->payload_packet_len != (length + 4)) || (packet->payload[1] != 0x0)) return(-1); /* Invalid length */ certificates_length = (packet->payload[4] << 16) + (packet->payload[5] << 8) + packet->payload[6]; if((packet->payload[4] != 0x0) || ((certificates_length+3) != length)) return(-2); /* Invalid length */ if(!flow->l4.tcp.tls.srv_cert_fingerprint_ctx) { if((flow->l4.tcp.tls.srv_cert_fingerprint_ctx = (void*)ndpi_malloc(sizeof(SHA1_CTX))) == NULL) return(-3); /* Not enough memory */ } /* Now let's process each individual certificates */ while(certificates_offset < certificates_length) { u_int32_t certificate_len = (packet->payload[certificates_offset] << 16) + (packet->payload[certificates_offset+1] << 8) + packet->payload[certificates_offset+2]; /* Invalid lenght */ if((certificate_len == 0) || (packet->payload[certificates_offset] != 0x0) || ((certificates_offset+certificate_len) > (4+certificates_length))) { #ifdef DEBUG_TLS printf("[TLS] Invalid length [certificate_len: %u][certificates_offset: %u][%u vs %u]\n", certificate_len, certificates_offset, (certificates_offset+certificate_len), certificates_length); #endif break; } certificates_offset += 3; #ifdef DEBUG_TLS printf("[TLS] Processing %u bytes certificate [%02X %02X %02X]\n", certificate_len, packet->payload[certificates_offset], packet->payload[certificates_offset+1], packet->payload[certificates_offset+2]); #endif if(num_certificates_found++ == 0) /* Dissect only the first certificate that is the one we care */ { /* For SHA-1 we take into account only the first certificate and not all of them */ SHA1Init(flow->l4.tcp.tls.srv_cert_fingerprint_ctx); #ifdef DEBUG_CERTIFICATE_HASH { int i; for(i=0;i<certificate_len;i++) printf("%02X ", packet->payload[certificates_offset+i]); printf("\n"); } #endif SHA1Update(flow->l4.tcp.tls.srv_cert_fingerprint_ctx, &packet->payload[certificates_offset], certificate_len); SHA1Final(flow->l4.tcp.tls.sha1_certificate_fingerprint, flow->l4.tcp.tls.srv_cert_fingerprint_ctx); flow->l4.tcp.tls.fingerprint_set = 1; #ifdef DEBUG_TLS { int i; printf("[TLS] SHA-1: "); for(i=0;i<20;i++) printf("%s%02X", (i > 0) ? ":" : "", flow->l4.tcp.tls.sha1_certificate_fingerprint[i]); printf("\n"); } #endif processCertificateElements(ndpi_struct, flow, certificates_offset, certificate_len); } certificates_offset += certificate_len; } flow->extra_packets_func = NULL; /* We're good now */ return(1); } /* **************************************** */ static int processTLSBlock(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; switch(packet->payload[0] /* block type */) { case 0x01: /* Client Hello */ case 0x02: /* Server Hello */ processClientServerHello(ndpi_struct, flow); flow->l4.tcp.tls.hello_processed = 1; ndpi_int_tls_add_connection(ndpi_struct, flow, NDPI_PROTOCOL_TLS); break; case 0x0b: /* Certificate */ /* Important: populate the tls union fields only after * ndpi_int_tls_add_connection has been called */ if(flow->l4.tcp.tls.hello_processed) { processCertificate(ndpi_struct, flow); flow->l4.tcp.tls.certificate_processed = 1; } break; default: return(-1); } return(0); } /* **************************************** */ static int ndpi_search_tls_tcp(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; u_int8_t something_went_wrong = 0; #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] ndpi_search_tls_tcp() [payload_packet_len: %u]\n", packet->payload_packet_len); #endif if(packet->payload_packet_len == 0) return(1); /* Keep working */ ndpi_search_tls_tcp_memory(ndpi_struct, flow); while(!something_went_wrong) { u_int16_t len, p_len; const u_int8_t *p; if(flow->l4.tcp.tls.message.buffer_used < 5) return(1); /* Keep working */ len = (flow->l4.tcp.tls.message.buffer[3] << 8) + flow->l4.tcp.tls.message.buffer[4] + 5; if(len > flow->l4.tcp.tls.message.buffer_used) { #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] Not enough TLS data [%u < %u][%02X %02X %02X %02X %02X]\n", len, flow->l4.tcp.tls.message.buffer_used, flow->l4.tcp.tls.message.buffer[0], flow->l4.tcp.tls.message.buffer[1], flow->l4.tcp.tls.message.buffer[2], flow->l4.tcp.tls.message.buffer[3], flow->l4.tcp.tls.message.buffer[4]); #endif break; } if(len == 0) { something_went_wrong = 1; break; } #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] Processing %u bytes message\n", len); #endif /* Overwriting packet payload */ p = packet->payload, p_len = packet->payload_packet_len; /* Backup */ /* Split the element in blocks */ u_int16_t processed = 5; while((processed+4) < len) { const u_int8_t *block = (const u_int8_t *)&flow->l4.tcp.tls.message.buffer[processed]; u_int32_t block_len = (block[1] << 16) + (block[2] << 8) + block[3]; if((block_len == 0) || (block_len > len) || ((block[1] != 0x0))) { something_went_wrong = 1; break; } packet->payload = block, packet->payload_packet_len = ndpi_min(block_len+4, flow->l4.tcp.tls.message.buffer_used); if((processed+packet->payload_packet_len) > len) { something_went_wrong = 1; break; } #ifdef DEBUG_TLS_MEMORY printf("*** [TLS Mem] Processing %u bytes block [%02X %02X %02X %02X %02X]\n", packet->payload_packet_len, packet->payload[0], packet->payload[1], packet->payload[2], packet->payload[3], packet->payload[4]); #endif processTLSBlock(ndpi_struct, flow); processed += packet->payload_packet_len; } packet->payload = p, packet->payload_packet_len = p_len; /* Restore */ flow->l4.tcp.tls.message.buffer_used -= len; if(flow->l4.tcp.tls.message.buffer_used > 0) memmove(flow->l4.tcp.tls.message.buffer, &flow->l4.tcp.tls.message.buffer[len], flow->l4.tcp.tls.message.buffer_used); else break; #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] Left memory buffer %u bytes\n", flow->l4.tcp.tls.message.buffer_used); #endif } if(something_went_wrong) { flow->check_extra_packets = 0, flow->extra_packets_func = NULL; return(0); /* That's all */ } else return(1); } /* **************************************** */ static int ndpi_search_tls_udp(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; // u_int8_t handshake_type; u_int32_t handshake_len; u_int16_t p_len; const u_int8_t *p; #ifdef DEBUG_TLS printf("[TLS] %s()\n", __FUNCTION__); #endif /* Consider only specific SSL packets (handshake) */ if((packet->payload_packet_len < 17) || (packet->payload[0] != 0x16) || (packet->payload[1] != 0xfe) /* We ignore old DTLS versions */ || ((packet->payload[2] != 0xff) && (packet->payload[2] != 0xfd)) || ((ntohs(*((u_int16_t*)&packet->payload[11]))+13) != packet->payload_packet_len) ) { no_dtls: #ifdef DEBUG_TLS printf("[TLS] No DTLS found\n"); #endif NDPI_EXCLUDE_PROTO(ndpi_struct, flow); return(0); /* Giveup */ } // handshake_type = packet->payload[13]; handshake_len = (packet->payload[14] << 16) + (packet->payload[15] << 8) + packet->payload[16]; if((handshake_len+25) != packet->payload_packet_len) goto no_dtls; /* Overwriting packet payload */ p = packet->payload, p_len = packet->payload_packet_len; /* Backup */ packet->payload = &packet->payload[13], packet->payload_packet_len -= 13; processTLSBlock(ndpi_struct, flow); packet->payload = p, packet->payload_packet_len = p_len; /* Restore */ ndpi_int_tls_add_connection(ndpi_struct, flow, NDPI_PROTOCOL_TLS); return(1); /* Keep working */ } /* **************************************** */ static void tlsInitExtraPacketProcessing(struct ndpi_flow_struct *flow) { flow->check_extra_packets = 1; /* At most 12 packets should almost always be enough to find the server certificate if it's there */ flow->max_extra_packets_to_check = 12; flow->extra_packets_func = (flow->packet.udp != NULL) ? ndpi_search_tls_udp : ndpi_search_tls_tcp; } /* **************************************** */ static void ndpi_int_tls_add_connection(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow, u_int32_t protocol) { #if DEBUG_TLS printf("[TLS] %s()\n", __FUNCTION__); #endif if((flow->detected_protocol_stack[0] == protocol) || (flow->detected_protocol_stack[1] == protocol)) { if(!flow->check_extra_packets) tlsInitExtraPacketProcessing(flow); return; } if(protocol != NDPI_PROTOCOL_TLS) ; else protocol = ndpi_tls_refine_master_protocol(ndpi_struct, flow, protocol); ndpi_set_detected_protocol(ndpi_struct, flow, protocol, NDPI_PROTOCOL_TLS); tlsInitExtraPacketProcessing(flow); } /* **************************************** */ /* https://engineering.salesforce.com/tls-fingerprinting-with-ja3-and-ja3s-247362855967 */ #define JA3_STR_LEN 1024 #define MAX_NUM_JA3 128 struct ja3_info { u_int16_t tls_handshake_version; u_int16_t num_cipher, cipher[MAX_NUM_JA3]; u_int16_t num_tls_extension, tls_extension[MAX_NUM_JA3]; u_int16_t num_elliptic_curve, elliptic_curve[MAX_NUM_JA3]; u_int8_t num_elliptic_curve_point_format, elliptic_curve_point_format[MAX_NUM_JA3]; }; /* **************************************** */ int processClientServerHello(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; struct ja3_info ja3; u_int8_t invalid_ja3 = 0; u_int16_t tls_version, ja3_str_len; char ja3_str[JA3_STR_LEN]; ndpi_MD5_CTX ctx; u_char md5_hash[16]; int i; u_int16_t total_len; u_int8_t handshake_type; char buffer[64] = { '\0' }; #ifdef DEBUG_TLS printf("SSL %s() called\n", __FUNCTION__); #endif memset(&ja3, 0, sizeof(ja3)); handshake_type = packet->payload[0]; total_len = (packet->payload[1] << 16) + (packet->payload[2] << 8) + packet->payload[3]; if((total_len > packet->payload_packet_len) || (packet->payload[1] != 0x0)) return(0); /* Not found */ total_len = packet->payload_packet_len; /* At least "magic" 3 bytes, null for string end, otherwise no need to waste cpu cycles */ if(total_len > 4) { u_int16_t base_offset = packet->tcp ? 38 : 46; u_int16_t version_offset = packet->tcp ? 4 : 12; u_int16_t offset = packet->tcp ? 38 : 46, extension_len, j; u_int8_t session_id_len = 0; if (base_offset < total_len) session_id_len = packet->payload[base_offset]; #ifdef DEBUG_TLS printf("SSL [len: %u][handshake_type: %02X]\n", packet->payload_packet_len, handshake_type); #endif tls_version = ntohs(*((u_int16_t*)&packet->payload[version_offset])); flow->protos.stun_ssl.ssl.ssl_version = ja3.tls_handshake_version = tls_version; if(flow->protos.stun_ssl.ssl.ssl_version < 0x0302) /* TLSv1.1 */ NDPI_SET_BIT(flow->risk, NDPI_TLS_OBSOLETE_VERSION); if(handshake_type == 0x02 /* Server Hello */) { int i, rc; #ifdef DEBUG_TLS printf("SSL Server Hello [version: 0x%04X]\n", tls_version); #endif /* The server hello decides about the SSL version of this flow https://networkengineering.stackexchange.com/questions/55752/why-does-wireshark-show-version-tls-1-2-here-instead-of-tls-1-3 */ if(packet->udp) offset += 1; else { if(tls_version < 0x7F15 /* TLS 1.3 lacks of session id */) offset += session_id_len+1; } if((offset+3) > packet->payload_packet_len) return(0); /* Not found */ ja3.num_cipher = 1, ja3.cipher[0] = ntohs(*((u_int16_t*)&packet->payload[offset])); if((flow->protos.stun_ssl.ssl.server_unsafe_cipher = ndpi_is_safe_ssl_cipher(ja3.cipher[0])) == 1) NDPI_SET_BIT(flow->risk, NDPI_TLS_WEAK_CIPHER); flow->protos.stun_ssl.ssl.server_cipher = ja3.cipher[0]; #ifdef DEBUG_TLS printf("TLS [server][session_id_len: %u][cipher: %04X]\n", session_id_len, ja3.cipher[0]); #endif offset += 2 + 1; if((offset + 1) < packet->payload_packet_len) /* +1 because we are goint to read 2 bytes */ extension_len = ntohs(*((u_int16_t*)&packet->payload[offset])); else extension_len = 0; #ifdef DEBUG_TLS printf("TLS [server][extension_len: %u]\n", extension_len); #endif offset += 2; for(i=0; i<extension_len; ) { u_int16_t extension_id, extension_len; if(offset >= (packet->payload_packet_len+4)) break; extension_id = ntohs(*((u_int16_t*)&packet->payload[offset])); extension_len = ntohs(*((u_int16_t*)&packet->payload[offset+2])); if(ja3.num_tls_extension < MAX_NUM_JA3) ja3.tls_extension[ja3.num_tls_extension++] = extension_id; #ifdef DEBUG_TLS printf("TLS [server][extension_id: %u/0x%04X][len: %u]\n", extension_id, extension_id, extension_len); #endif if(extension_id == 43 /* supported versions */) { if(extension_len >= 2) { u_int16_t tls_version = ntohs(*((u_int16_t*)&packet->payload[offset+4])); #ifdef DEBUG_TLS printf("TLS [server] [TLS version: 0x%04X]\n", tls_version); #endif flow->protos.stun_ssl.ssl.ssl_version = tls_version; } } i += 4 + extension_len, offset += 4 + extension_len; } ja3_str_len = snprintf(ja3_str, sizeof(ja3_str), "%u,", ja3.tls_handshake_version); for(i=0; i<ja3.num_cipher; i++) { rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "%s%u", (i > 0) ? "-" : "", ja3.cipher[i]); if(rc <= 0) break; else ja3_str_len += rc; } rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, ","); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; /* ********** */ for(i=0; i<ja3.num_tls_extension; i++) { int rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "%s%u", (i > 0) ? "-" : "", ja3.tls_extension[i]); if(rc <= 0) break; else ja3_str_len += rc; } #ifdef DEBUG_TLS printf("TLS [server] %s\n", ja3_str); #endif #ifdef DEBUG_TLS printf("[JA3] Server: %s \n", ja3_str); #endif ndpi_MD5Init(&ctx); ndpi_MD5Update(&ctx, (const unsigned char *)ja3_str, strlen(ja3_str)); ndpi_MD5Final(md5_hash, &ctx); for(i=0, j=0; i<16; i++) { int rc = snprintf(&flow->protos.stun_ssl.ssl.ja3_server[j], sizeof(flow->protos.stun_ssl.ssl.ja3_server)-j, "%02x", md5_hash[i]); if(rc <= 0) break; else j += rc; } #ifdef DEBUG_TLS printf("[JA3] Server: %s \n", flow->protos.stun_ssl.ssl.ja3_server); #endif } else if(handshake_type == 0x01 /* Client Hello */) { u_int16_t cipher_len, cipher_offset; if((session_id_len+base_offset+3) > packet->payload_packet_len) return(0); /* Not found */ if(packet->tcp) { cipher_len = packet->payload[session_id_len+base_offset+2] + (packet->payload[session_id_len+base_offset+1] << 8); cipher_offset = base_offset + session_id_len + 3; } else { cipher_len = ntohs(*((u_int16_t*)&packet->payload[base_offset+2])); cipher_offset = base_offset+4; } #ifdef DEBUG_TLS printf("Client SSL [client cipher_len: %u][tls_version: 0x%04X]\n", cipher_len, tls_version); #endif if((cipher_offset+cipher_len) <= total_len) { for(i=0; i<cipher_len;) { u_int16_t *id = (u_int16_t*)&packet->payload[cipher_offset+i]; #ifdef DEBUG_TLS printf("Client SSL [cipher suite: %u/0x%04X] [%d/%u]\n", ntohs(*id), ntohs(*id), i, cipher_len); #endif if((*id == 0) || (packet->payload[cipher_offset+i] != packet->payload[cipher_offset+i+1])) { /* Skip GREASE [https://tools.ietf.org/id/draft-ietf-tls-grease-01.html] https://engineering.salesforce.com/tls-fingerprinting-with-ja3-and-ja3s-247362855967 */ if(ja3.num_cipher < MAX_NUM_JA3) ja3.cipher[ja3.num_cipher++] = ntohs(*id); else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf("Client SSL Invalid cipher %u\n", ja3.num_cipher); #endif } } i += 2; } } else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf("Client SSL Invalid len %u vs %u\n", (cipher_offset+cipher_len), total_len); #endif } offset = base_offset + session_id_len + cipher_len + 2; if(offset < total_len) { u_int16_t compression_len; u_int16_t extensions_len; offset += packet->tcp ? 1 : 2; compression_len = packet->payload[offset]; offset++; #ifdef DEBUG_TLS printf("Client SSL [compression_len: %u]\n", compression_len); #endif // offset += compression_len + 3; offset += compression_len; if(offset < total_len) { extensions_len = ntohs(*((u_int16_t*)&packet->payload[offset])); offset += 2; #ifdef DEBUG_TLS printf("Client SSL [extensions_len: %u]\n", extensions_len); #endif if((extensions_len+offset) <= total_len) { /* Move to the first extension Type is u_int to avoid possible overflow on extension_len addition */ u_int extension_offset = 0; u_int32_t j; while(extension_offset < extensions_len) { u_int16_t extension_id, extension_len, extn_off = offset+extension_offset; extension_id = ntohs(*((u_int16_t*)&packet->payload[offset+extension_offset])); extension_offset += 2; extension_len = ntohs(*((u_int16_t*)&packet->payload[offset+extension_offset])); extension_offset += 2; #ifdef DEBUG_TLS printf("Client SSL [extension_id: %u][extension_len: %u]\n", extension_id, extension_len); #endif if((extension_id == 0) || (packet->payload[extn_off] != packet->payload[extn_off+1])) { /* Skip GREASE */ if(ja3.num_tls_extension < MAX_NUM_JA3) ja3.tls_extension[ja3.num_tls_extension++] = extension_id; else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf("Client SSL Invalid extensions %u\n", ja3.num_tls_extension); #endif } } if(extension_id == 0 /* server name */) { u_int16_t len; #ifdef DEBUG_TLS printf("[TLS] Extensions: found server name\n"); #endif len = (packet->payload[offset+extension_offset+3] << 8) + packet->payload[offset+extension_offset+4]; len = (u_int)ndpi_min(len, sizeof(buffer)-1); if((offset+extension_offset+5+len) <= packet->payload_packet_len) { strncpy(buffer, (char*)&packet->payload[offset+extension_offset+5], len); buffer[len] = '\0'; cleanupServerName(buffer, sizeof(buffer)); snprintf(flow->protos.stun_ssl.ssl.client_requested_server_name, sizeof(flow->protos.stun_ssl.ssl.client_requested_server_name), "%s", buffer); if(ndpi_match_hostname_protocol(ndpi_struct, flow, NDPI_PROTOCOL_TLS, buffer, strlen(buffer))) flow->l4.tcp.tls.subprotocol_detected = 1; ndpi_check_dga_name(ndpi_struct, flow, flow->protos.stun_ssl.ssl.client_requested_server_name); } else { #ifdef DEBUG_TLS printf("[TLS] Extensions server len too short: %u vs %u\n", offset+extension_offset+5+len, packet->payload_packet_len); #endif } } else if(extension_id == 10 /* supported groups */) { u_int16_t s_offset = offset+extension_offset + 2; #ifdef DEBUG_TLS printf("Client SSL [EllipticCurveGroups: len=%u]\n", extension_len); #endif if((s_offset+extension_len-2) <= total_len) { for(i=0; i<extension_len-2;) { u_int16_t s_group = ntohs(*((u_int16_t*)&packet->payload[s_offset+i])); #ifdef DEBUG_TLS printf("Client SSL [EllipticCurve: %u/0x%04X]\n", s_group, s_group); #endif if((s_group == 0) || (packet->payload[s_offset+i] != packet->payload[s_offset+i+1])) { /* Skip GREASE */ if(ja3.num_elliptic_curve < MAX_NUM_JA3) ja3.elliptic_curve[ja3.num_elliptic_curve++] = s_group; else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf("Client SSL Invalid num elliptic %u\n", ja3.num_elliptic_curve); #endif } } i += 2; } } else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf("Client SSL Invalid len %u vs %u\n", (s_offset+extension_len-1), total_len); #endif } } else if(extension_id == 11 /* ec_point_formats groups */) { u_int16_t s_offset = offset+extension_offset + 1; #ifdef DEBUG_TLS printf("Client SSL [EllipticCurveFormat: len=%u]\n", extension_len); #endif if((s_offset+extension_len) < total_len) { for(i=0; i<extension_len-1;i++) { u_int8_t s_group = packet->payload[s_offset+i]; #ifdef DEBUG_TLS printf("Client SSL [EllipticCurveFormat: %u]\n", s_group); #endif if(ja3.num_elliptic_curve_point_format < MAX_NUM_JA3) ja3.elliptic_curve_point_format[ja3.num_elliptic_curve_point_format++] = s_group; else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf("Client SSL Invalid num elliptic %u\n", ja3.num_elliptic_curve_point_format); #endif } } } else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf("Client SSL Invalid len %u vs %u\n", s_offset+extension_len, total_len); #endif } } else if(extension_id == 16 /* application_layer_protocol_negotiation */) { u_int16_t s_offset = offset+extension_offset; u_int16_t tot_alpn_len = ntohs(*((u_int16_t*)&packet->payload[s_offset])); char alpn_str[256]; u_int8_t alpn_str_len = 0; #ifdef DEBUG_TLS printf("Client SSL [ALPN: block_len=%u/len=%u]\n", extension_len, tot_alpn_len); #endif s_offset += 2; tot_alpn_len += s_offset; while(s_offset < tot_alpn_len && s_offset < total_len) { u_int8_t alpn_i, alpn_len = packet->payload[s_offset++]; if((s_offset + alpn_len) <= tot_alpn_len) { #ifdef DEBUG_TLS printf("Client SSL [ALPN: %u]\n", alpn_len); #endif if((alpn_str_len+alpn_len+1) < sizeof(alpn_str)) { if(alpn_str_len > 0) { alpn_str[alpn_str_len] = ','; alpn_str_len++; } for(alpn_i=0; alpn_i<alpn_len; alpn_i++) alpn_str[alpn_str_len+alpn_i] = packet->payload[s_offset+alpn_i]; s_offset += alpn_len, alpn_str_len += alpn_len;; } else break; } else break; } /* while */ alpn_str[alpn_str_len] = '\0'; #ifdef DEBUG_TLS printf("Client SSL [ALPN: %s][len: %u]\n", alpn_str, alpn_str_len); #endif if(flow->protos.stun_ssl.ssl.alpn == NULL) flow->protos.stun_ssl.ssl.alpn = ndpi_strdup(alpn_str); } else if(extension_id == 43 /* supported versions */) { u_int16_t s_offset = offset+extension_offset; u_int8_t version_len = packet->payload[s_offset]; char version_str[256]; u_int8_t version_str_len = 0; version_str[0] = 0; #ifdef DEBUG_TLS printf("Client SSL [TLS version len: %u]\n", version_len); #endif if(version_len == (extension_len-1)) { u_int8_t j; s_offset++; // careful not to overflow and loop forever with u_int8_t for(j=0; j+1<version_len; j += 2) { u_int16_t tls_version = ntohs(*((u_int16_t*)&packet->payload[s_offset+j])); u_int8_t unknown_tls_version; #ifdef DEBUG_TLS printf("Client SSL [TLS version: %s/0x%04X]\n", ndpi_ssl_version2str(tls_version, &unknown_tls_version), tls_version); #endif if((version_str_len+8) < sizeof(version_str)) { int rc = snprintf(&version_str[version_str_len], sizeof(version_str) - version_str_len, "%s%s", (version_str_len > 0) ? "," : "", ndpi_ssl_version2str(tls_version, &unknown_tls_version)); if(rc <= 0) break; else version_str_len += rc; } } if(flow->protos.stun_ssl.ssl.tls_supported_versions == NULL) flow->protos.stun_ssl.ssl.tls_supported_versions = ndpi_strdup(version_str); } } else if(extension_id == 65486 /* encrypted server name */) { /* - https://tools.ietf.org/html/draft-ietf-tls-esni-06 - https://blog.cloudflare.com/encrypted-sni/ */ u_int16_t e_offset = offset+extension_offset; u_int16_t initial_offset = e_offset; u_int16_t e_sni_len, cipher_suite = ntohs(*((u_int16_t*)&packet->payload[e_offset])); flow->protos.stun_ssl.ssl.encrypted_sni.cipher_suite = cipher_suite; e_offset += 2; /* Cipher suite len */ /* Key Share Entry */ e_offset += 2; /* Group */ e_offset += ntohs(*((u_int16_t*)&packet->payload[e_offset])) + 2; /* Lenght */ if((e_offset+4) < packet->payload_packet_len) { /* Record Digest */ e_offset += ntohs(*((u_int16_t*)&packet->payload[e_offset])) + 2; /* Lenght */ if((e_offset+4) < packet->payload_packet_len) { e_sni_len = ntohs(*((u_int16_t*)&packet->payload[e_offset])); e_offset += 2; if((e_offset+e_sni_len-extension_len-initial_offset) >= 0) { #ifdef DEBUG_ENCRYPTED_SNI printf("Client SSL [Encrypted Server Name len: %u]\n", e_sni_len); #endif if(flow->protos.stun_ssl.ssl.encrypted_sni.esni == NULL) { flow->protos.stun_ssl.ssl.encrypted_sni.esni = (char*)ndpi_malloc(e_sni_len*2+1); if(flow->protos.stun_ssl.ssl.encrypted_sni.esni) { u_int16_t i, off; for(i=e_offset, off=0; i<(e_offset+e_sni_len); i++) { int rc = sprintf(&flow->protos.stun_ssl.ssl.encrypted_sni.esni[off], "%02X", packet->payload[i] & 0XFF); if(rc <= 0) { flow->protos.stun_ssl.ssl.encrypted_sni.esni[off] = '\0'; break; } else off += rc; } } } } } } } extension_offset += extension_len; /* Move to the next extension */ #ifdef DEBUG_TLS printf("Client SSL [extension_offset/len: %u/%u]\n", extension_offset, extension_len); #endif } /* while */ if(!invalid_ja3) { int rc; compute_ja3c: ja3_str_len = snprintf(ja3_str, sizeof(ja3_str), "%u,", ja3.tls_handshake_version); for(i=0; i<ja3.num_cipher; i++) { rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "%s%u", (i > 0) ? "-" : "", ja3.cipher[i]); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; else break; } rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, ","); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; /* ********** */ for(i=0; i<ja3.num_tls_extension; i++) { rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "%s%u", (i > 0) ? "-" : "", ja3.tls_extension[i]); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; else break; } rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, ","); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; /* ********** */ for(i=0; i<ja3.num_elliptic_curve; i++) { rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "%s%u", (i > 0) ? "-" : "", ja3.elliptic_curve[i]); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; else break; } rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, ","); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; for(i=0; i<ja3.num_elliptic_curve_point_format; i++) { rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "%s%u", (i > 0) ? "-" : "", ja3.elliptic_curve_point_format[i]); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; else break; } #ifdef DEBUG_TLS printf("[JA3] Client: %s \n", ja3_str); #endif ndpi_MD5Init(&ctx); ndpi_MD5Update(&ctx, (const unsigned char *)ja3_str, strlen(ja3_str)); ndpi_MD5Final(md5_hash, &ctx); for(i=0, j=0; i<16; i++) { rc = snprintf(&flow->protos.stun_ssl.ssl.ja3_client[j], sizeof(flow->protos.stun_ssl.ssl.ja3_client)-j, "%02x", md5_hash[i]); if(rc > 0) j += rc; else break; } #ifdef DEBUG_TLS printf("[JA3] Client: %s \n", flow->protos.stun_ssl.ssl.ja3_client); #endif } /* Before returning to the caller we need to make a final check */ if((flow->protos.stun_ssl.ssl.ssl_version >= 0x0303) /* >= TLSv1.2 */ && (flow->protos.stun_ssl.ssl.alpn == NULL) /* No ALPN */) { NDPI_SET_BIT(flow->risk, NDPI_TLS_NOT_CARRYING_HTTPS); } return(2 /* Client Certificate */); } else { #ifdef DEBUG_TLS printf("[TLS] Client: too short [%u vs %u]\n", (extensions_len+offset), total_len); #endif } } else if(offset == total_len) { /* SSL does not have extensions etc */ goto compute_ja3c; } } else { #ifdef DEBUG_TLS printf("[JA3] Client: invalid length detected\n"); #endif } } } return(0); /* Not found */ } /* **************************************** */ static void ndpi_search_tls_wrapper(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; #ifdef DEBUG_TLS printf("==>> %s() %u [len: %u][version: %u]\n", __FUNCTION__, flow->guessed_host_protocol_id, packet->payload_packet_len, flow->protos.stun_ssl.ssl.ssl_version); #endif if(packet->udp != NULL) ndpi_search_tls_udp(ndpi_struct, flow); else ndpi_search_tls_tcp(ndpi_struct, flow); } /* **************************************** */ void init_tls_dissector(struct ndpi_detection_module_struct *ndpi_struct, u_int32_t *id, NDPI_PROTOCOL_BITMASK *detection_bitmask) { ndpi_set_bitmask_protocol_detection("TLS", ndpi_struct, detection_bitmask, *id, NDPI_PROTOCOL_TLS, ndpi_search_tls_wrapper, NDPI_SELECTION_BITMASK_PROTOCOL_V4_V6_TCP_WITH_PAYLOAD_WITHOUT_RETRANSMISSION, SAVE_DETECTION_BITMASK_AS_UNKNOWN, ADD_TO_DETECTION_BITMASK); *id += 1; /* *************************************************** */ ndpi_set_bitmask_protocol_detection("TLS", ndpi_struct, detection_bitmask, *id, NDPI_PROTOCOL_TLS, ndpi_search_tls_wrapper, NDPI_SELECTION_BITMASK_PROTOCOL_V4_V6_UDP_WITH_PAYLOAD, SAVE_DETECTION_BITMASK_AS_UNKNOWN, ADD_TO_DETECTION_BITMASK); *id += 1; }
null
/* * tls.c - SSL/TLS/DTLS dissector * * Copyright (C) 2016-20 - ntop.org * * This file is part of nDPI, an open source deep packet inspection * library based on the OpenDPI and PACE technology by ipoque GmbH * * nDPI is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * nDPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with nDPI. If not, see <http://www.gnu.org/licenses/>. * */ #include "ndpi_protocol_ids.h" #define NDPI_CURRENT_PROTO NDPI_PROTOCOL_TLS #include "ndpi_api.h" #include "ndpi_md5.h" #include "ndpi_sha1.h" extern char *strptime(const char *s, const char *format, struct tm *tm); extern int processClientServerHello(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow); // #define DEBUG_TLS_MEMORY 1 // #define DEBUG_TLS 1 // #define DEBUG_CERTIFICATE_HASH /* #define DEBUG_FINGERPRINT 1 */ /* #define DEBUG_ENCRYPTED_SNI 1 */ /* NOTE How to view the certificate fingerprint 1. Using wireshark save the certificate on certificate.bin file as explained in https://security.stackexchange.com/questions/123851/how-can-i-extract-the-certificate-from-this-pcap-file 2. openssl x509 -inform der -in certificate.bin -text > certificate.der 3. openssl x509 -noout -fingerprint -sha1 -inform pem -in certificate.der SHA1 Fingerprint=15:9A:76.... $ shasum -a 1 www.grc.com.bin 159a76..... */ #define NDPI_MAX_TLS_REQUEST_SIZE 10000 /* skype.c */ extern u_int8_t is_skype_flow(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow); /* stun.c */ extern u_int32_t get_stun_lru_key(struct ndpi_flow_struct *flow, u_int8_t rev); static void ndpi_int_tls_add_connection(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow, u_int32_t protocol); /* **************************************** */ static u_int32_t ndpi_tls_refine_master_protocol(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow, u_int32_t protocol) { struct ndpi_packet_struct *packet = &flow->packet; // protocol = NDPI_PROTOCOL_TLS; if(packet->tcp != NULL) { switch(protocol) { case NDPI_PROTOCOL_TLS: { /* In case of SSL there are probably sub-protocols such as IMAPS that can be otherwise detected */ u_int16_t sport = ntohs(packet->tcp->source); u_int16_t dport = ntohs(packet->tcp->dest); if((sport == 465) || (dport == 465) || (sport == 587) || (dport == 587)) protocol = NDPI_PROTOCOL_MAIL_SMTPS; else if((sport == 993) || (dport == 993) || (flow->l4.tcp.mail_imap_starttls) ) protocol = NDPI_PROTOCOL_MAIL_IMAPS; else if((sport == 995) || (dport == 995)) protocol = NDPI_PROTOCOL_MAIL_POPS; } break; } } return(protocol); } /* **************************************** */ void ndpi_search_tls_tcp_memory(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; /* TCP */ #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] Handling TCP/TLS flow [payload_len: %u][buffer_len: %u][direction: %u]\n", packet->payload_packet_len, flow->l4.tcp.tls.message.buffer_len, packet->packet_direction); #endif if(flow->l4.tcp.tls.message.buffer == NULL) { /* Allocate buffer */ flow->l4.tcp.tls.message.buffer_len = 2048, flow->l4.tcp.tls.message.buffer_used = 0; flow->l4.tcp.tls.message.buffer = (u_int8_t*)ndpi_malloc(flow->l4.tcp.tls.message.buffer_len); if(flow->l4.tcp.tls.message.buffer == NULL) return; #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] Allocating %u buffer\n", flow->l4.tcp.tls.message.buffer_len); #endif } u_int avail_bytes = flow->l4.tcp.tls.message.buffer_len - flow->l4.tcp.tls.message.buffer_used; if(avail_bytes < packet->payload_packet_len) { u_int new_len = flow->l4.tcp.tls.message.buffer_len + packet->payload_packet_len; void *newbuf = ndpi_realloc(flow->l4.tcp.tls.message.buffer, flow->l4.tcp.tls.message.buffer_len, new_len); if(!newbuf) return; flow->l4.tcp.tls.message.buffer = (u_int8_t*)newbuf, flow->l4.tcp.tls.message.buffer_len = new_len; avail_bytes = flow->l4.tcp.tls.message.buffer_len - flow->l4.tcp.tls.message.buffer_used; #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] Enlarging %u -> %u buffer\n", flow->l4.tcp.tls.message.buffer_len, new_len); #endif } if(avail_bytes >= packet->payload_packet_len) { memcpy(&flow->l4.tcp.tls.message.buffer[flow->l4.tcp.tls.message.buffer_used], packet->payload, packet->payload_packet_len); flow->l4.tcp.tls.message.buffer_used += packet->payload_packet_len; #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] Copied data to buffer [%u/%u bytes]\n", flow->l4.tcp.tls.message.buffer_used, flow->l4.tcp.tls.message.buffer_len); #endif } } /* **************************************** */ /* Can't call libc functions from kernel space, define some stub instead */ #define ndpi_isalpha(ch) (((ch) >= 'a' && (ch) <= 'z') || ((ch) >= 'A' && (ch) <= 'Z')) #define ndpi_isdigit(ch) ((ch) >= '0' && (ch) <= '9') #define ndpi_isspace(ch) (((ch) >= '\t' && (ch) <= '\r') || ((ch) == ' ')) #define ndpi_isprint(ch) ((ch) >= 0x20 && (ch) <= 0x7e) #define ndpi_ispunct(ch) (((ch) >= '!' && (ch) <= '/') || \ ((ch) >= ':' && (ch) <= '@') || \ ((ch) >= '[' && (ch) <= '`') || \ ((ch) >= '{' && (ch) <= '~')) /* **************************************** */ static void cleanupServerName(char *buffer, int buffer_len) { u_int i; /* Now all lowecase */ for(i=0; i<buffer_len; i++) buffer[i] = tolower(buffer[i]); } /* **************************************** */ /* Return code -1: error (buffer too short) 0: OK but buffer is not human readeable (so something went wrong) 1: OK */ static int extractRDNSequence(struct ndpi_packet_struct *packet, u_int offset, char *buffer, u_int buffer_len, char *rdnSeqBuf, u_int *rdnSeqBuf_offset, u_int rdnSeqBuf_len, const char *label) { u_int8_t str_len = packet->payload[offset+4], is_printable = 1; char *str; u_int len, j; if (*rdnSeqBuf_offset >= rdnSeqBuf_len) { #ifdef DEBUG_TLS printf("[TLS] %s() [buffer capacity reached][%u]\n", __FUNCTION__, rdnSeqBuf_len); #endif return -1; } // packet is truncated... further inspection is not needed if((offset+4+str_len) >= packet->payload_packet_len) return(-1); str = (char*)&packet->payload[offset+5]; len = (u_int)ndpi_min(str_len, buffer_len-1); strncpy(buffer, str, len); buffer[len] = '\0'; // check string is printable for(j = 0; j < len; j++) { if(!ndpi_isprint(buffer[j])) { is_printable = 0; break; } } if(is_printable) { int rc = snprintf(&rdnSeqBuf[*rdnSeqBuf_offset], rdnSeqBuf_len-(*rdnSeqBuf_offset), "%s%s=%s", (*rdnSeqBuf_offset > 0) ? ", " : "", label, buffer); if(rc > 0) (*rdnSeqBuf_offset) += rc; } return(is_printable); } /* **************************************** */ /* See https://blog.catchpoint.com/2017/05/12/dissecting-tls-using-wireshark/ */ static void processCertificateElements(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow, u_int16_t p_offset, u_int16_t certificate_len) { struct ndpi_packet_struct *packet = &flow->packet; u_int num_found = 0, i; char buffer[64] = { '\0' }, rdnSeqBuf[2048] = { '\0' }; u_int rdn_len = 0; #ifdef DEBUG_TLS printf("[TLS] %s() [offset: %u][certificate_len: %u]\n", __FUNCTION__, p_offset, certificate_len); #endif /* Check after handshake protocol header (5 bytes) and message header (4 bytes) */ for(i = p_offset; i < certificate_len; i++) { /* See https://www.ibm.com/support/knowledgecenter/SSFKSJ_7.5.0/com.ibm.mq.sec.doc/q009860_.htm for X.509 certificate labels */ if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x03)) { /* Common Name */ int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "CN"); if(rc == -1) break; #ifdef DEBUG_TLS printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "Common Name", buffer); #endif } else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x06)) { /* Country */ int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "C"); if(rc == -1) break; #ifdef DEBUG_TLS printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "Country", buffer); #endif } else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x07)) { /* Locality */ int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "L"); if(rc == -1) break; #ifdef DEBUG_TLS printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "Locality", buffer); #endif } else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x08)) { /* State or Province */ int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "ST"); if(rc == -1) break; #ifdef DEBUG_TLS printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "State or Province", buffer); #endif } else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x0a)) { /* Organization Name */ int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "O"); if(rc == -1) break; #ifdef DEBUG_TLS printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "Organization Name", buffer); #endif } else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x0b)) { /* Organization Unit */ int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "OU"); if(rc == -1) break; #ifdef DEBUG_TLS printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "Organization Unit", buffer); #endif } else if((packet->payload[i] == 0x30) && (packet->payload[i+1] == 0x1e) && (packet->payload[i+2] == 0x17)) { /* Certificate Validity */ u_int8_t len = packet->payload[i+3]; u_int offset = i+4; if(num_found == 0) { num_found++; #ifdef DEBUG_TLS printf("[TLS] %s() IssuerDN [%s]\n", __FUNCTION__, rdnSeqBuf); #endif if(rdn_len) flow->protos.stun_ssl.ssl.issuerDN = ndpi_strdup(rdnSeqBuf); rdn_len = 0; /* Reset buffer */ } if((offset+len) < packet->payload_packet_len) { char utcDate[32]; #ifdef DEBUG_TLS u_int j; printf("[CERTIFICATE] notBefore [len: %u][", len); for(j=0; j<len; j++) printf("%c", packet->payload[i+4+j]); printf("]\n"); #endif if(len < (sizeof(utcDate)-1)) { struct tm utc; utc.tm_isdst = -1; /* Not set by strptime */ strncpy(utcDate, (const char*)&packet->payload[i+4], len); utcDate[len] = '\0'; /* 141021000000Z */ if(strptime(utcDate, "%y%m%d%H%M%SZ", &utc) != NULL) { flow->protos.stun_ssl.ssl.notBefore = timegm(&utc); #ifdef DEBUG_TLS printf("[CERTIFICATE] notBefore %u [%s]\n", flow->protos.stun_ssl.ssl.notBefore, utcDate); #endif } } offset += len; if((offset+1) < packet->payload_packet_len) { len = packet->payload[offset+1]; offset += 2; if((offset+len) < packet->payload_packet_len) { u_int32_t time_sec = flow->packet.current_time_ms / 1000; #ifdef DEBUG_TLS u_int j; printf("[CERTIFICATE] notAfter [len: %u][", len); for(j=0; j<len; j++) printf("%c", packet->payload[offset+j]); printf("]\n"); #endif if(len < (sizeof(utcDate)-1)) { struct tm utc; utc.tm_isdst = -1; /* Not set by strptime */ strncpy(utcDate, (const char*)&packet->payload[offset], len); utcDate[len] = '\0'; /* 141021000000Z */ if(strptime(utcDate, "%y%m%d%H%M%SZ", &utc) != NULL) { flow->protos.stun_ssl.ssl.notAfter = timegm(&utc); #ifdef DEBUG_TLS printf("[CERTIFICATE] notAfter %u [%s]\n", flow->protos.stun_ssl.ssl.notAfter, utcDate); #endif } } if((time_sec < flow->protos.stun_ssl.ssl.notBefore) || (time_sec > flow->protos.stun_ssl.ssl.notAfter)) NDPI_SET_BIT(flow->risk, NDPI_TLS_CERTIFICATE_EXPIRED); /* Certificate expired */ } } } } else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x1d) && (packet->payload[i+2] == 0x11)) { /* Organization OID: 2.5.29.17 (subjectAltName) */ u_int8_t matched_name = 0; #ifdef DEBUG_TLS printf("******* [TLS] Found subjectAltName\n"); #endif i += 3 /* skip the initial patten 55 1D 11 */; i++; /* skip the first type, 0x04 == BIT STRING, and jump to it's length */ if(i < packet->payload_packet_len) { i += (packet->payload[i] & 0x80) ? (packet->payload[i] & 0x7F) : 0; /* skip BIT STRING length */ if(i < packet->payload_packet_len) { i += 2; /* skip the second type, 0x30 == SEQUENCE, and jump to it's length */ if(i < packet->payload_packet_len) { i += (packet->payload[i] & 0x80) ? (packet->payload[i] & 0x7F) : 0; /* skip SEQUENCE length */ i++; while(i < packet->payload_packet_len) { if(packet->payload[i] == 0x82) { if((i < (packet->payload_packet_len - 1)) && ((i + packet->payload[i + 1] + 2) < packet->payload_packet_len)) { u_int8_t len = packet->payload[i + 1]; char dNSName[256]; i += 2; /* The check "len > sizeof(dNSName) - 1" will be always false. If we add it, the compiler is smart enough to detect it and throws a warning */ if(len == 0 /* Looks something went wrong */) break; strncpy(dNSName, (const char*)&packet->payload[i], len); dNSName[len] = '\0'; cleanupServerName(dNSName, len); #if DEBUG_TLS printf("[TLS] dNSName %s [%s]\n", dNSName, flow->protos.stun_ssl.ssl.client_requested_server_name); #endif if(matched_name == 0) { if((dNSName[0] == '*') && strstr(flow->protos.stun_ssl.ssl.client_requested_server_name, &dNSName[1])) matched_name = 1; else if(strcmp(flow->protos.stun_ssl.ssl.client_requested_server_name, dNSName) == 0) matched_name = 1; } if(flow->protos.stun_ssl.ssl.server_names == NULL) flow->protos.stun_ssl.ssl.server_names = ndpi_strdup(dNSName), flow->protos.stun_ssl.ssl.server_names_len = strlen(dNSName); else { u_int16_t dNSName_len = strlen(dNSName); u_int16_t newstr_len = flow->protos.stun_ssl.ssl.server_names_len + dNSName_len + 1; char *newstr = (char*)ndpi_realloc(flow->protos.stun_ssl.ssl.server_names, flow->protos.stun_ssl.ssl.server_names_len+1, newstr_len+1); if(newstr) { flow->protos.stun_ssl.ssl.server_names = newstr; flow->protos.stun_ssl.ssl.server_names[flow->protos.stun_ssl.ssl.server_names_len] = ','; strncpy(&flow->protos.stun_ssl.ssl.server_names[flow->protos.stun_ssl.ssl.server_names_len+1], dNSName, dNSName_len+1); flow->protos.stun_ssl.ssl.server_names[newstr_len] = '\0'; flow->protos.stun_ssl.ssl.server_names_len = newstr_len; } } if(!flow->l4.tcp.tls.subprotocol_detected) if(ndpi_match_hostname_protocol(ndpi_struct, flow, NDPI_PROTOCOL_TLS, dNSName, len)) flow->l4.tcp.tls.subprotocol_detected = 1; i += len; } else { #if DEBUG_TLS printf("[TLS] Leftover %u bytes", packet->payload_packet_len - i); #endif break; } } else { break; } } /* while */ if(!matched_name) NDPI_SET_BIT(flow->risk, NDPI_TLS_CERTIFICATE_MISMATCH); /* Certificate mismatch */ } } } } } if(rdn_len) flow->protos.stun_ssl.ssl.subjectDN = ndpi_strdup(rdnSeqBuf); if(flow->protos.stun_ssl.ssl.subjectDN && flow->protos.stun_ssl.ssl.issuerDN && (!strcmp(flow->protos.stun_ssl.ssl.subjectDN, flow->protos.stun_ssl.ssl.issuerDN))) NDPI_SET_BIT(flow->risk, NDPI_TLS_SELFSIGNED_CERTIFICATE); #if DEBUG_TLS printf("[TLS] %s() SubjectDN [%s]\n", __FUNCTION__, rdnSeqBuf); #endif } /* **************************************** */ /* See https://blog.catchpoint.com/2017/05/12/dissecting-tls-using-wireshark/ */ int processCertificate(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; u_int32_t certificates_length, length = (packet->payload[1] << 16) + (packet->payload[2] << 8) + packet->payload[3]; u_int16_t certificates_offset = 7; u_int8_t num_certificates_found = 0; #ifdef DEBUG_TLS printf("[TLS] %s() [payload_packet_len=%u][direction: %u][%02X %02X %02X %02X %02X %02X...]\n", __FUNCTION__, packet->payload_packet_len, packet->packet_direction, packet->payload[0], packet->payload[1], packet->payload[2], packet->payload[3], packet->payload[4], packet->payload[5]); #endif if((packet->payload_packet_len != (length + 4)) || (packet->payload[1] != 0x0)) return(-1); /* Invalid length */ certificates_length = (packet->payload[4] << 16) + (packet->payload[5] << 8) + packet->payload[6]; if((packet->payload[4] != 0x0) || ((certificates_length+3) != length)) return(-2); /* Invalid length */ if(!flow->l4.tcp.tls.srv_cert_fingerprint_ctx) { if((flow->l4.tcp.tls.srv_cert_fingerprint_ctx = (void*)ndpi_malloc(sizeof(SHA1_CTX))) == NULL) return(-3); /* Not enough memory */ } /* Now let's process each individual certificates */ while(certificates_offset < certificates_length) { u_int32_t certificate_len = (packet->payload[certificates_offset] << 16) + (packet->payload[certificates_offset+1] << 8) + packet->payload[certificates_offset+2]; /* Invalid lenght */ if((certificate_len == 0) || (packet->payload[certificates_offset] != 0x0) || ((certificates_offset+certificate_len) > (4+certificates_length))) { #ifdef DEBUG_TLS printf("[TLS] Invalid length [certificate_len: %u][certificates_offset: %u][%u vs %u]\n", certificate_len, certificates_offset, (certificates_offset+certificate_len), certificates_length); #endif break; } certificates_offset += 3; #ifdef DEBUG_TLS printf("[TLS] Processing %u bytes certificate [%02X %02X %02X]\n", certificate_len, packet->payload[certificates_offset], packet->payload[certificates_offset+1], packet->payload[certificates_offset+2]); #endif if(num_certificates_found++ == 0) /* Dissect only the first certificate that is the one we care */ { /* For SHA-1 we take into account only the first certificate and not all of them */ SHA1Init(flow->l4.tcp.tls.srv_cert_fingerprint_ctx); #ifdef DEBUG_CERTIFICATE_HASH { int i; for(i=0;i<certificate_len;i++) printf("%02X ", packet->payload[certificates_offset+i]); printf("\n"); } #endif SHA1Update(flow->l4.tcp.tls.srv_cert_fingerprint_ctx, &packet->payload[certificates_offset], certificate_len); SHA1Final(flow->l4.tcp.tls.sha1_certificate_fingerprint, flow->l4.tcp.tls.srv_cert_fingerprint_ctx); flow->l4.tcp.tls.fingerprint_set = 1; #ifdef DEBUG_TLS { int i; printf("[TLS] SHA-1: "); for(i=0;i<20;i++) printf("%s%02X", (i > 0) ? ":" : "", flow->l4.tcp.tls.sha1_certificate_fingerprint[i]); printf("\n"); } #endif processCertificateElements(ndpi_struct, flow, certificates_offset, certificate_len); } certificates_offset += certificate_len; } flow->extra_packets_func = NULL; /* We're good now */ return(1); } /* **************************************** */ static int processTLSBlock(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; switch(packet->payload[0] /* block type */) { case 0x01: /* Client Hello */ case 0x02: /* Server Hello */ processClientServerHello(ndpi_struct, flow); flow->l4.tcp.tls.hello_processed = 1; ndpi_int_tls_add_connection(ndpi_struct, flow, NDPI_PROTOCOL_TLS); break; case 0x0b: /* Certificate */ /* Important: populate the tls union fields only after * ndpi_int_tls_add_connection has been called */ if(flow->l4.tcp.tls.hello_processed) { processCertificate(ndpi_struct, flow); flow->l4.tcp.tls.certificate_processed = 1; } break; default: return(-1); } return(0); } /* **************************************** */ static int ndpi_search_tls_tcp(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; u_int8_t something_went_wrong = 0; #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] ndpi_search_tls_tcp() [payload_packet_len: %u]\n", packet->payload_packet_len); #endif if(packet->payload_packet_len == 0) return(1); /* Keep working */ ndpi_search_tls_tcp_memory(ndpi_struct, flow); while(!something_went_wrong) { u_int16_t len, p_len; const u_int8_t *p; if(flow->l4.tcp.tls.message.buffer_used < 5) return(1); /* Keep working */ len = (flow->l4.tcp.tls.message.buffer[3] << 8) + flow->l4.tcp.tls.message.buffer[4] + 5; if(len > flow->l4.tcp.tls.message.buffer_used) { #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] Not enough TLS data [%u < %u][%02X %02X %02X %02X %02X]\n", len, flow->l4.tcp.tls.message.buffer_used, flow->l4.tcp.tls.message.buffer[0], flow->l4.tcp.tls.message.buffer[1], flow->l4.tcp.tls.message.buffer[2], flow->l4.tcp.tls.message.buffer[3], flow->l4.tcp.tls.message.buffer[4]); #endif break; } if(len == 0) { something_went_wrong = 1; break; } #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] Processing %u bytes message\n", len); #endif /* Overwriting packet payload */ p = packet->payload, p_len = packet->payload_packet_len; /* Backup */ /* Split the element in blocks */ u_int16_t processed = 5; while((processed+4) < len) { const u_int8_t *block = (const u_int8_t *)&flow->l4.tcp.tls.message.buffer[processed]; u_int32_t block_len = (block[1] << 16) + (block[2] << 8) + block[3]; if((block_len == 0) || (block_len > len) || ((block[1] != 0x0))) { something_went_wrong = 1; break; } packet->payload = block, packet->payload_packet_len = ndpi_min(block_len+4, flow->l4.tcp.tls.message.buffer_used); if((processed+packet->payload_packet_len) > len) { something_went_wrong = 1; break; } #ifdef DEBUG_TLS_MEMORY printf("*** [TLS Mem] Processing %u bytes block [%02X %02X %02X %02X %02X]\n", packet->payload_packet_len, packet->payload[0], packet->payload[1], packet->payload[2], packet->payload[3], packet->payload[4]); #endif processTLSBlock(ndpi_struct, flow); processed += packet->payload_packet_len; } packet->payload = p, packet->payload_packet_len = p_len; /* Restore */ flow->l4.tcp.tls.message.buffer_used -= len; if(flow->l4.tcp.tls.message.buffer_used > 0) memmove(flow->l4.tcp.tls.message.buffer, &flow->l4.tcp.tls.message.buffer[len], flow->l4.tcp.tls.message.buffer_used); else break; #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] Left memory buffer %u bytes\n", flow->l4.tcp.tls.message.buffer_used); #endif } if(something_went_wrong) { flow->check_extra_packets = 0, flow->extra_packets_func = NULL; return(0); /* That's all */ } else return(1); } /* **************************************** */ static int ndpi_search_tls_udp(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; // u_int8_t handshake_type; u_int32_t handshake_len; u_int16_t p_len; const u_int8_t *p; #ifdef DEBUG_TLS printf("[TLS] %s()\n", __FUNCTION__); #endif /* Consider only specific SSL packets (handshake) */ if((packet->payload_packet_len < 17) || (packet->payload[0] != 0x16) || (packet->payload[1] != 0xfe) /* We ignore old DTLS versions */ || ((packet->payload[2] != 0xff) && (packet->payload[2] != 0xfd)) || ((ntohs(*((u_int16_t*)&packet->payload[11]))+13) != packet->payload_packet_len) ) { no_dtls: #ifdef DEBUG_TLS printf("[TLS] No DTLS found\n"); #endif NDPI_EXCLUDE_PROTO(ndpi_struct, flow); return(0); /* Giveup */ } // handshake_type = packet->payload[13]; handshake_len = (packet->payload[14] << 16) + (packet->payload[15] << 8) + packet->payload[16]; if((handshake_len+25) != packet->payload_packet_len) goto no_dtls; /* Overwriting packet payload */ p = packet->payload, p_len = packet->payload_packet_len; /* Backup */ packet->payload = &packet->payload[13], packet->payload_packet_len -= 13; processTLSBlock(ndpi_struct, flow); packet->payload = p, packet->payload_packet_len = p_len; /* Restore */ ndpi_int_tls_add_connection(ndpi_struct, flow, NDPI_PROTOCOL_TLS); return(1); /* Keep working */ } /* **************************************** */ static void tlsInitExtraPacketProcessing(struct ndpi_flow_struct *flow) { flow->check_extra_packets = 1; /* At most 12 packets should almost always be enough to find the server certificate if it's there */ flow->max_extra_packets_to_check = 12; flow->extra_packets_func = (flow->packet.udp != NULL) ? ndpi_search_tls_udp : ndpi_search_tls_tcp; } /* **************************************** */ static void ndpi_int_tls_add_connection(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow, u_int32_t protocol) { #if DEBUG_TLS printf("[TLS] %s()\n", __FUNCTION__); #endif if((flow->detected_protocol_stack[0] == protocol) || (flow->detected_protocol_stack[1] == protocol)) { if(!flow->check_extra_packets) tlsInitExtraPacketProcessing(flow); return; } if(protocol != NDPI_PROTOCOL_TLS) ; else protocol = ndpi_tls_refine_master_protocol(ndpi_struct, flow, protocol); ndpi_set_detected_protocol(ndpi_struct, flow, protocol, NDPI_PROTOCOL_TLS); tlsInitExtraPacketProcessing(flow); } /* **************************************** */ /* https://engineering.salesforce.com/tls-fingerprinting-with-ja3-and-ja3s-247362855967 */ #define JA3_STR_LEN 1024 #define MAX_NUM_JA3 128 struct ja3_info { u_int16_t tls_handshake_version; u_int16_t num_cipher, cipher[MAX_NUM_JA3]; u_int16_t num_tls_extension, tls_extension[MAX_NUM_JA3]; u_int16_t num_elliptic_curve, elliptic_curve[MAX_NUM_JA3]; u_int8_t num_elliptic_curve_point_format, elliptic_curve_point_format[MAX_NUM_JA3]; }; /* **************************************** */ int processClientServerHello(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; struct ja3_info ja3; u_int8_t invalid_ja3 = 0; u_int16_t tls_version, ja3_str_len; char ja3_str[JA3_STR_LEN]; ndpi_MD5_CTX ctx; u_char md5_hash[16]; int i; u_int16_t total_len; u_int8_t handshake_type; char buffer[64] = { '\0' }; #ifdef DEBUG_TLS printf("SSL %s() called\n", __FUNCTION__); #endif memset(&ja3, 0, sizeof(ja3)); handshake_type = packet->payload[0]; total_len = (packet->payload[1] << 16) + (packet->payload[2] << 8) + packet->payload[3]; if((total_len > packet->payload_packet_len) || (packet->payload[1] != 0x0)) return(0); /* Not found */ total_len = packet->payload_packet_len; /* At least "magic" 3 bytes, null for string end, otherwise no need to waste cpu cycles */ if(total_len > 4) { u_int16_t base_offset = packet->tcp ? 38 : 46; u_int16_t version_offset = packet->tcp ? 4 : 12; u_int16_t offset = packet->tcp ? 38 : 46, extension_len, j; u_int8_t session_id_len = 0; if (base_offset < total_len) session_id_len = packet->payload[base_offset]; #ifdef DEBUG_TLS printf("SSL [len: %u][handshake_type: %02X]\n", packet->payload_packet_len, handshake_type); #endif tls_version = ntohs(*((u_int16_t*)&packet->payload[version_offset])); flow->protos.stun_ssl.ssl.ssl_version = ja3.tls_handshake_version = tls_version; if(flow->protos.stun_ssl.ssl.ssl_version < 0x0302) /* TLSv1.1 */ NDPI_SET_BIT(flow->risk, NDPI_TLS_OBSOLETE_VERSION); if(handshake_type == 0x02 /* Server Hello */) { int i, rc; #ifdef DEBUG_TLS printf("SSL Server Hello [version: 0x%04X]\n", tls_version); #endif /* The server hello decides about the SSL version of this flow https://networkengineering.stackexchange.com/questions/55752/why-does-wireshark-show-version-tls-1-2-here-instead-of-tls-1-3 */ if(packet->udp) offset += 1; else { if(tls_version < 0x7F15 /* TLS 1.3 lacks of session id */) offset += session_id_len+1; } if((offset+3) > packet->payload_packet_len) return(0); /* Not found */ ja3.num_cipher = 1, ja3.cipher[0] = ntohs(*((u_int16_t*)&packet->payload[offset])); if((flow->protos.stun_ssl.ssl.server_unsafe_cipher = ndpi_is_safe_ssl_cipher(ja3.cipher[0])) == 1) NDPI_SET_BIT(flow->risk, NDPI_TLS_WEAK_CIPHER); flow->protos.stun_ssl.ssl.server_cipher = ja3.cipher[0]; #ifdef DEBUG_TLS printf("TLS [server][session_id_len: %u][cipher: %04X]\n", session_id_len, ja3.cipher[0]); #endif offset += 2 + 1; if((offset + 1) < packet->payload_packet_len) /* +1 because we are goint to read 2 bytes */ extension_len = ntohs(*((u_int16_t*)&packet->payload[offset])); else extension_len = 0; #ifdef DEBUG_TLS printf("TLS [server][extension_len: %u]\n", extension_len); #endif offset += 2; for(i=0; i<extension_len; ) { u_int16_t extension_id, extension_len; if(offset >= (packet->payload_packet_len+4)) break; extension_id = ntohs(*((u_int16_t*)&packet->payload[offset])); extension_len = ntohs(*((u_int16_t*)&packet->payload[offset+2])); if(ja3.num_tls_extension < MAX_NUM_JA3) ja3.tls_extension[ja3.num_tls_extension++] = extension_id; #ifdef DEBUG_TLS printf("TLS [server][extension_id: %u/0x%04X][len: %u]\n", extension_id, extension_id, extension_len); #endif if(extension_id == 43 /* supported versions */) { if(extension_len >= 2) { u_int16_t tls_version = ntohs(*((u_int16_t*)&packet->payload[offset+4])); #ifdef DEBUG_TLS printf("TLS [server] [TLS version: 0x%04X]\n", tls_version); #endif flow->protos.stun_ssl.ssl.ssl_version = tls_version; } } i += 4 + extension_len, offset += 4 + extension_len; } ja3_str_len = snprintf(ja3_str, sizeof(ja3_str), "%u,", ja3.tls_handshake_version); for(i=0; i<ja3.num_cipher; i++) { rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "%s%u", (i > 0) ? "-" : "", ja3.cipher[i]); if(rc <= 0) break; else ja3_str_len += rc; } rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, ","); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; /* ********** */ for(i=0; i<ja3.num_tls_extension; i++) { int rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "%s%u", (i > 0) ? "-" : "", ja3.tls_extension[i]); if(rc <= 0) break; else ja3_str_len += rc; } #ifdef DEBUG_TLS printf("TLS [server] %s\n", ja3_str); #endif #ifdef DEBUG_TLS printf("[JA3] Server: %s \n", ja3_str); #endif ndpi_MD5Init(&ctx); ndpi_MD5Update(&ctx, (const unsigned char *)ja3_str, strlen(ja3_str)); ndpi_MD5Final(md5_hash, &ctx); for(i=0, j=0; i<16; i++) { int rc = snprintf(&flow->protos.stun_ssl.ssl.ja3_server[j], sizeof(flow->protos.stun_ssl.ssl.ja3_server)-j, "%02x", md5_hash[i]); if(rc <= 0) break; else j += rc; } #ifdef DEBUG_TLS printf("[JA3] Server: %s \n", flow->protos.stun_ssl.ssl.ja3_server); #endif } else if(handshake_type == 0x01 /* Client Hello */) { u_int16_t cipher_len, cipher_offset; if((session_id_len+base_offset+3) > packet->payload_packet_len) return(0); /* Not found */ if(packet->tcp) { cipher_len = packet->payload[session_id_len+base_offset+2] + (packet->payload[session_id_len+base_offset+1] << 8); cipher_offset = base_offset + session_id_len + 3; } else { cipher_len = ntohs(*((u_int16_t*)&packet->payload[base_offset+2])); cipher_offset = base_offset+4; } #ifdef DEBUG_TLS printf("Client SSL [client cipher_len: %u][tls_version: 0x%04X]\n", cipher_len, tls_version); #endif if((cipher_offset+cipher_len) <= total_len) { for(i=0; i<cipher_len;) { u_int16_t *id = (u_int16_t*)&packet->payload[cipher_offset+i]; #ifdef DEBUG_TLS printf("Client SSL [cipher suite: %u/0x%04X] [%d/%u]\n", ntohs(*id), ntohs(*id), i, cipher_len); #endif if((*id == 0) || (packet->payload[cipher_offset+i] != packet->payload[cipher_offset+i+1])) { /* Skip GREASE [https://tools.ietf.org/id/draft-ietf-tls-grease-01.html] https://engineering.salesforce.com/tls-fingerprinting-with-ja3-and-ja3s-247362855967 */ if(ja3.num_cipher < MAX_NUM_JA3) ja3.cipher[ja3.num_cipher++] = ntohs(*id); else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf("Client SSL Invalid cipher %u\n", ja3.num_cipher); #endif } } i += 2; } } else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf("Client SSL Invalid len %u vs %u\n", (cipher_offset+cipher_len), total_len); #endif } offset = base_offset + session_id_len + cipher_len + 2; if(offset < total_len) { u_int16_t compression_len; u_int16_t extensions_len; offset += packet->tcp ? 1 : 2; compression_len = packet->payload[offset]; offset++; #ifdef DEBUG_TLS printf("Client SSL [compression_len: %u]\n", compression_len); #endif // offset += compression_len + 3; offset += compression_len; if(offset < total_len) { extensions_len = ntohs(*((u_int16_t*)&packet->payload[offset])); offset += 2; #ifdef DEBUG_TLS printf("Client SSL [extensions_len: %u]\n", extensions_len); #endif if((extensions_len+offset) <= total_len) { /* Move to the first extension Type is u_int to avoid possible overflow on extension_len addition */ u_int extension_offset = 0; u_int32_t j; while(extension_offset < extensions_len) { u_int16_t extension_id, extension_len, extn_off = offset+extension_offset; extension_id = ntohs(*((u_int16_t*)&packet->payload[offset+extension_offset])); extension_offset += 2; extension_len = ntohs(*((u_int16_t*)&packet->payload[offset+extension_offset])); extension_offset += 2; #ifdef DEBUG_TLS printf("Client SSL [extension_id: %u][extension_len: %u]\n", extension_id, extension_len); #endif if((extension_id == 0) || (packet->payload[extn_off] != packet->payload[extn_off+1])) { /* Skip GREASE */ if(ja3.num_tls_extension < MAX_NUM_JA3) ja3.tls_extension[ja3.num_tls_extension++] = extension_id; else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf("Client SSL Invalid extensions %u\n", ja3.num_tls_extension); #endif } } if(extension_id == 0 /* server name */) { u_int16_t len; #ifdef DEBUG_TLS printf("[TLS] Extensions: found server name\n"); #endif len = (packet->payload[offset+extension_offset+3] << 8) + packet->payload[offset+extension_offset+4]; len = (u_int)ndpi_min(len, sizeof(buffer)-1); if((offset+extension_offset+5+len) <= packet->payload_packet_len) { strncpy(buffer, (char*)&packet->payload[offset+extension_offset+5], len); buffer[len] = '\0'; cleanupServerName(buffer, sizeof(buffer)); snprintf(flow->protos.stun_ssl.ssl.client_requested_server_name, sizeof(flow->protos.stun_ssl.ssl.client_requested_server_name), "%s", buffer); if(ndpi_match_hostname_protocol(ndpi_struct, flow, NDPI_PROTOCOL_TLS, buffer, strlen(buffer))) flow->l4.tcp.tls.subprotocol_detected = 1; ndpi_check_dga_name(ndpi_struct, flow, flow->protos.stun_ssl.ssl.client_requested_server_name); } else { #ifdef DEBUG_TLS printf("[TLS] Extensions server len too short: %u vs %u\n", offset+extension_offset+5+len, packet->payload_packet_len); #endif } } else if(extension_id == 10 /* supported groups */) { u_int16_t s_offset = offset+extension_offset + 2; #ifdef DEBUG_TLS printf("Client SSL [EllipticCurveGroups: len=%u]\n", extension_len); #endif if((s_offset+extension_len-2) <= total_len) { for(i=0; i<extension_len-2;) { u_int16_t s_group = ntohs(*((u_int16_t*)&packet->payload[s_offset+i])); #ifdef DEBUG_TLS printf("Client SSL [EllipticCurve: %u/0x%04X]\n", s_group, s_group); #endif if((s_group == 0) || (packet->payload[s_offset+i] != packet->payload[s_offset+i+1])) { /* Skip GREASE */ if(ja3.num_elliptic_curve < MAX_NUM_JA3) ja3.elliptic_curve[ja3.num_elliptic_curve++] = s_group; else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf("Client SSL Invalid num elliptic %u\n", ja3.num_elliptic_curve); #endif } } i += 2; } } else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf("Client SSL Invalid len %u vs %u\n", (s_offset+extension_len-1), total_len); #endif } } else if(extension_id == 11 /* ec_point_formats groups */) { u_int16_t s_offset = offset+extension_offset + 1; #ifdef DEBUG_TLS printf("Client SSL [EllipticCurveFormat: len=%u]\n", extension_len); #endif if((s_offset+extension_len) < total_len) { for(i=0; i<extension_len-1;i++) { u_int8_t s_group = packet->payload[s_offset+i]; #ifdef DEBUG_TLS printf("Client SSL [EllipticCurveFormat: %u]\n", s_group); #endif if(ja3.num_elliptic_curve_point_format < MAX_NUM_JA3) ja3.elliptic_curve_point_format[ja3.num_elliptic_curve_point_format++] = s_group; else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf("Client SSL Invalid num elliptic %u\n", ja3.num_elliptic_curve_point_format); #endif } } } else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf("Client SSL Invalid len %u vs %u\n", s_offset+extension_len, total_len); #endif } } else if(extension_id == 16 /* application_layer_protocol_negotiation */) { u_int16_t s_offset = offset+extension_offset; u_int16_t tot_alpn_len = ntohs(*((u_int16_t*)&packet->payload[s_offset])); char alpn_str[256]; u_int8_t alpn_str_len = 0; #ifdef DEBUG_TLS printf("Client SSL [ALPN: block_len=%u/len=%u]\n", extension_len, tot_alpn_len); #endif s_offset += 2; tot_alpn_len += s_offset; while(s_offset < tot_alpn_len && s_offset < total_len) { u_int8_t alpn_i, alpn_len = packet->payload[s_offset++]; if((s_offset + alpn_len) <= tot_alpn_len) { #ifdef DEBUG_TLS printf("Client SSL [ALPN: %u]\n", alpn_len); #endif if((alpn_str_len+alpn_len+1) < sizeof(alpn_str)) { if(alpn_str_len > 0) { alpn_str[alpn_str_len] = ','; alpn_str_len++; } for(alpn_i=0; alpn_i<alpn_len; alpn_i++) alpn_str[alpn_str_len+alpn_i] = packet->payload[s_offset+alpn_i]; s_offset += alpn_len, alpn_str_len += alpn_len;; } else break; } else break; } /* while */ alpn_str[alpn_str_len] = '\0'; #ifdef DEBUG_TLS printf("Client SSL [ALPN: %s][len: %u]\n", alpn_str, alpn_str_len); #endif if(flow->protos.stun_ssl.ssl.alpn == NULL) flow->protos.stun_ssl.ssl.alpn = ndpi_strdup(alpn_str); } else if(extension_id == 43 /* supported versions */) { u_int16_t s_offset = offset+extension_offset; u_int8_t version_len = packet->payload[s_offset]; char version_str[256]; u_int8_t version_str_len = 0; version_str[0] = 0; #ifdef DEBUG_TLS printf("Client SSL [TLS version len: %u]\n", version_len); #endif if(version_len == (extension_len-1)) { u_int8_t j; s_offset++; // careful not to overflow and loop forever with u_int8_t for(j=0; j+1<version_len; j += 2) { u_int16_t tls_version = ntohs(*((u_int16_t*)&packet->payload[s_offset+j])); u_int8_t unknown_tls_version; #ifdef DEBUG_TLS printf("Client SSL [TLS version: %s/0x%04X]\n", ndpi_ssl_version2str(tls_version, &unknown_tls_version), tls_version); #endif if((version_str_len+8) < sizeof(version_str)) { int rc = snprintf(&version_str[version_str_len], sizeof(version_str) - version_str_len, "%s%s", (version_str_len > 0) ? "," : "", ndpi_ssl_version2str(tls_version, &unknown_tls_version)); if(rc <= 0) break; else version_str_len += rc; } } if(flow->protos.stun_ssl.ssl.tls_supported_versions == NULL) flow->protos.stun_ssl.ssl.tls_supported_versions = ndpi_strdup(version_str); } } else if(extension_id == 65486 /* encrypted server name */) { /* - https://tools.ietf.org/html/draft-ietf-tls-esni-06 - https://blog.cloudflare.com/encrypted-sni/ */ u_int16_t e_offset = offset+extension_offset; u_int16_t initial_offset = e_offset; u_int16_t e_sni_len, cipher_suite = ntohs(*((u_int16_t*)&packet->payload[e_offset])); flow->protos.stun_ssl.ssl.encrypted_sni.cipher_suite = cipher_suite; e_offset += 2; /* Cipher suite len */ /* Key Share Entry */ e_offset += 2; /* Group */ e_offset += ntohs(*((u_int16_t*)&packet->payload[e_offset])) + 2; /* Lenght */ if((e_offset+4) < packet->payload_packet_len) { /* Record Digest */ e_offset += ntohs(*((u_int16_t*)&packet->payload[e_offset])) + 2; /* Lenght */ if((e_offset+4) < packet->payload_packet_len) { e_sni_len = ntohs(*((u_int16_t*)&packet->payload[e_offset])); e_offset += 2; if((e_offset+e_sni_len-extension_len-initial_offset) >= 0) { #ifdef DEBUG_ENCRYPTED_SNI printf("Client SSL [Encrypted Server Name len: %u]\n", e_sni_len); #endif if(flow->protos.stun_ssl.ssl.encrypted_sni.esni == NULL) { flow->protos.stun_ssl.ssl.encrypted_sni.esni = (char*)ndpi_malloc(e_sni_len*2+1); if(flow->protos.stun_ssl.ssl.encrypted_sni.esni) { u_int16_t i, off; for(i=e_offset, off=0; i<(e_offset+e_sni_len); i++) { int rc = sprintf(&flow->protos.stun_ssl.ssl.encrypted_sni.esni[off], "%02X", packet->payload[i] & 0XFF); if(rc <= 0) { flow->protos.stun_ssl.ssl.encrypted_sni.esni[off] = '\0'; break; } else off += rc; } } } } } } } extension_offset += extension_len; /* Move to the next extension */ #ifdef DEBUG_TLS printf("Client SSL [extension_offset/len: %u/%u]\n", extension_offset, extension_len); #endif } /* while */ if(!invalid_ja3) { int rc; compute_ja3c: ja3_str_len = snprintf(ja3_str, sizeof(ja3_str), "%u,", ja3.tls_handshake_version); for(i=0; i<ja3.num_cipher; i++) { rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "%s%u", (i > 0) ? "-" : "", ja3.cipher[i]); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; else break; } rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, ","); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; /* ********** */ for(i=0; i<ja3.num_tls_extension; i++) { rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "%s%u", (i > 0) ? "-" : "", ja3.tls_extension[i]); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; else break; } rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, ","); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; /* ********** */ for(i=0; i<ja3.num_elliptic_curve; i++) { rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "%s%u", (i > 0) ? "-" : "", ja3.elliptic_curve[i]); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; else break; } rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, ","); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; for(i=0; i<ja3.num_elliptic_curve_point_format; i++) { rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "%s%u", (i > 0) ? "-" : "", ja3.elliptic_curve_point_format[i]); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; else break; } #ifdef DEBUG_TLS printf("[JA3] Client: %s \n", ja3_str); #endif ndpi_MD5Init(&ctx); ndpi_MD5Update(&ctx, (const unsigned char *)ja3_str, strlen(ja3_str)); ndpi_MD5Final(md5_hash, &ctx); for(i=0, j=0; i<16; i++) { rc = snprintf(&flow->protos.stun_ssl.ssl.ja3_client[j], sizeof(flow->protos.stun_ssl.ssl.ja3_client)-j, "%02x", md5_hash[i]); if(rc > 0) j += rc; else break; } #ifdef DEBUG_TLS printf("[JA3] Client: %s \n", flow->protos.stun_ssl.ssl.ja3_client); #endif } /* Before returning to the caller we need to make a final check */ if((flow->protos.stun_ssl.ssl.ssl_version >= 0x0303) /* >= TLSv1.2 */ && (flow->protos.stun_ssl.ssl.alpn == NULL) /* No ALPN */) { NDPI_SET_BIT(flow->risk, NDPI_TLS_NOT_CARRYING_HTTPS); } return(2 /* Client Certificate */); } else { #ifdef DEBUG_TLS printf("[TLS] Client: too short [%u vs %u]\n", (extensions_len+offset), total_len); #endif } } else if(offset == total_len) { /* SSL does not have extensions etc */ goto compute_ja3c; } } else { #ifdef DEBUG_TLS printf("[JA3] Client: invalid length detected\n"); #endif } } } return(0); /* Not found */ } /* **************************************** */ static void ndpi_search_tls_wrapper(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; #ifdef DEBUG_TLS printf("==>> %s() %u [len: %u][version: %u]\n", __FUNCTION__, flow->guessed_host_protocol_id, packet->payload_packet_len, flow->protos.stun_ssl.ssl.ssl_version); #endif if(packet->udp != NULL) ndpi_search_tls_udp(ndpi_struct, flow); else ndpi_search_tls_tcp(ndpi_struct, flow); } /* **************************************** */ void init_tls_dissector(struct ndpi_detection_module_struct *ndpi_struct, u_int32_t *id, NDPI_PROTOCOL_BITMASK *detection_bitmask) { ndpi_set_bitmask_protocol_detection("TLS", ndpi_struct, detection_bitmask, *id, NDPI_PROTOCOL_TLS, ndpi_search_tls_wrapper, NDPI_SELECTION_BITMASK_PROTOCOL_V4_V6_TCP_WITH_PAYLOAD_WITHOUT_RETRANSMISSION, SAVE_DETECTION_BITMASK_AS_UNKNOWN, ADD_TO_DETECTION_BITMASK); *id += 1; /* *************************************************** */ ndpi_set_bitmask_protocol_detection("TLS", ndpi_struct, detection_bitmask, *id, NDPI_PROTOCOL_TLS, ndpi_search_tls_wrapper, NDPI_SELECTION_BITMASK_PROTOCOL_V4_V6_UDP_WITH_PAYLOAD, SAVE_DETECTION_BITMASK_AS_UNKNOWN, ADD_TO_DETECTION_BITMASK); *id += 1; }
null
189
CWE-787
CVE-2020-15888
/* ** $Id: ldo.h $ ** Stack and Call structure of Lua ** See Copyright Notice in lua.h */ #ifndef ldo_h #define ldo_h #include "lobject.h" #include "lstate.h" #include "lzio.h" /* ** Macro to check stack size and grow stack if needed. Parameters ** 'pre'/'pos' allow the macro to preserve a pointer into the ** stack across reallocations, doing the work only when needed. ** 'condmovestack' is used in heavy tests to force a stack reallocation ** at every check. */ #define luaD_checkstackaux(L,n,pre,pos) \ if (L->stack_last - L->top <= (n)) \ { pre; luaD_growstack(L, n, 1); pos; } \ else { condmovestack(L,pre,pos); } /* In general, 'pre'/'pos' are empty (nothing to save) */ #define luaD_checkstack(L,n) luaD_checkstackaux(L,n,(void)0,(void)0) #define savestack(L,p) ((char *)(p) - (char *)L->stack) #define restorestack(L,n) ((StkId)((char *)L->stack + (n))) /* macro to check stack size, preserving 'p' */ #define checkstackp(L,n,p) \ luaD_checkstackaux(L, n, \ ptrdiff_t t__ = savestack(L, p); /* save 'p' */ \ luaC_checkGC(L), /* stack grow uses memory */ \ p = restorestack(L, t__)) /* 'pos' part: restore 'p' */ /* macro to check stack size and GC */ #define checkstackGC(L,fsize) \ luaD_checkstackaux(L, (fsize), (void)0, luaC_checkGC(L)) /* type of protected functions, to be ran by 'runprotected' */ typedef void (*Pfunc) (lua_State *L, void *ud); LUAI_FUNC void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop); LUAI_FUNC int luaD_protectedparser (lua_State *L, ZIO *z, const char *name, const char *mode); LUAI_FUNC void luaD_hook (lua_State *L, int event, int line, int fTransfer, int nTransfer); LUAI_FUNC void luaD_hookcall (lua_State *L, CallInfo *ci); LUAI_FUNC void luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func, int n); LUAI_FUNC void luaD_call (lua_State *L, StkId func, int nResults); LUAI_FUNC void luaD_callnoyield (lua_State *L, StkId func, int nResults); LUAI_FUNC void luaD_tryfuncTM (lua_State *L, StkId func); LUAI_FUNC int luaD_pcall (lua_State *L, Pfunc func, void *u, ptrdiff_t oldtop, ptrdiff_t ef); LUAI_FUNC void luaD_poscall (lua_State *L, CallInfo *ci, int nres); LUAI_FUNC int luaD_reallocstack (lua_State *L, int newsize, int raiseerror); LUAI_FUNC int luaD_growstack (lua_State *L, int n, int raiseerror); LUAI_FUNC void luaD_shrinkstack (lua_State *L); LUAI_FUNC void luaD_inctop (lua_State *L); LUAI_FUNC l_noret luaD_throw (lua_State *L, int errcode); LUAI_FUNC int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud); #endif
null
/* ** $Id: ldo.h $ ** Stack and Call structure of Lua ** See Copyright Notice in lua.h */ #ifndef ldo_h #define ldo_h #include "lobject.h" #include "lstate.h" #include "lzio.h" /* ** Macro to check stack size and grow stack if needed. Parameters ** 'pre'/'pos' allow the macro to preserve a pointer into the ** stack across reallocations, doing the work only when needed. ** It also allows the running of one GC step when the stack is ** reallocated. ** 'condmovestack' is used in heavy tests to force a stack reallocation ** at every check. */ #define luaD_checkstackaux(L,n,pre,pos) \ if (L->stack_last - L->top <= (n)) \ { pre; luaD_growstack(L, n, 1); pos; } \ else { condmovestack(L,pre,pos); } /* In general, 'pre'/'pos' are empty (nothing to save) */ #define luaD_checkstack(L,n) luaD_checkstackaux(L,n,(void)0,(void)0) #define savestack(L,p) ((char *)(p) - (char *)L->stack) #define restorestack(L,n) ((StkId)((char *)L->stack + (n))) /* macro to check stack size, preserving 'p' */ #define checkstackGCp(L,n,p) \ luaD_checkstackaux(L, n, \ ptrdiff_t t__ = savestack(L, p); /* save 'p' */ \ luaC_checkGC(L), /* stack grow uses memory */ \ p = restorestack(L, t__)) /* 'pos' part: restore 'p' */ /* macro to check stack size and GC */ #define checkstackGC(L,fsize) \ luaD_checkstackaux(L, (fsize), luaC_checkGC(L), (void)0) /* type of protected functions, to be ran by 'runprotected' */ typedef void (*Pfunc) (lua_State *L, void *ud); LUAI_FUNC void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop); LUAI_FUNC int luaD_protectedparser (lua_State *L, ZIO *z, const char *name, const char *mode); LUAI_FUNC void luaD_hook (lua_State *L, int event, int line, int fTransfer, int nTransfer); LUAI_FUNC void luaD_hookcall (lua_State *L, CallInfo *ci); LUAI_FUNC void luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func, int n); LUAI_FUNC void luaD_call (lua_State *L, StkId func, int nResults); LUAI_FUNC void luaD_callnoyield (lua_State *L, StkId func, int nResults); LUAI_FUNC void luaD_tryfuncTM (lua_State *L, StkId func); LUAI_FUNC int luaD_pcall (lua_State *L, Pfunc func, void *u, ptrdiff_t oldtop, ptrdiff_t ef); LUAI_FUNC void luaD_poscall (lua_State *L, CallInfo *ci, int nres); LUAI_FUNC int luaD_reallocstack (lua_State *L, int newsize, int raiseerror); LUAI_FUNC int luaD_growstack (lua_State *L, int n, int raiseerror); LUAI_FUNC void luaD_shrinkstack (lua_State *L); LUAI_FUNC void luaD_inctop (lua_State *L); LUAI_FUNC l_noret luaD_throw (lua_State *L, int errcode); LUAI_FUNC int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud); #endif
null
190
CWE-787
CVE-2020-15900
/* Copyright (C) 2001-2020 Artifex Software, Inc. All Rights Reserved. This software is provided AS-IS with no warranty, either express or implied. This software is distributed under license and may not be copied, modified or distributed except as expressly authorized under the terms of the license contained in the file LICENSE in this distribution. Refer to licensing information at http://www.artifex.com or contact Artifex Software, Inc., 1305 Grant Avenue - Suite 200, Novato, CA 94945, U.S.A., +1(415)492-9861, for further information. */ /* String operators */ #include "memory_.h" #include "ghost.h" #include "gsutil.h" #include "ialloc.h" #include "iname.h" #include "ivmspace.h" #include "oper.h" #include "store.h" /* The generic operators (copy, get, put, getinterval, putinterval, */ /* length, and forall) are implemented in zgeneric.c. */ /* <int> .bytestring <bytestring> */ static int zbytestring(i_ctx_t *i_ctx_p) { os_ptr op = osp; byte *sbody; uint size; check_int_leu(*op, max_int); size = (uint)op->value.intval; sbody = ialloc_bytes(size, ".bytestring"); if (sbody == 0) return_error(gs_error_VMerror); make_astruct(op, a_all | icurrent_space, sbody); memset(sbody, 0, size); return 0; } /* <int> string <string> */ int zstring(i_ctx_t *i_ctx_p) { os_ptr op = osp; byte *sbody; uint size; check_type(*op, t_integer); if (op->value.intval < 0 ) return_error(gs_error_rangecheck); if (op->value.intval > max_string_size ) return_error(gs_error_limitcheck); /* to match Distiller */ size = op->value.intval; sbody = ialloc_string(size, "string"); if (sbody == 0) return_error(gs_error_VMerror); make_string(op, a_all | icurrent_space, size, sbody); memset(sbody, 0, size); return 0; } /* <name> .namestring <string> */ static int znamestring(i_ctx_t *i_ctx_p) { os_ptr op = osp; check_type(*op, t_name); name_string_ref(imemory, op, op); return 0; } /* <string> <pattern> anchorsearch <post> <match> -true- */ /* <string> <pattern> anchorsearch <string> -false- */ static int zanchorsearch(i_ctx_t *i_ctx_p) { os_ptr op = osp; os_ptr op1 = op - 1; uint size = r_size(op); check_read_type(*op, t_string); check_read_type(*op1, t_string); if (size <= r_size(op1) && !memcmp(op1->value.bytes, op->value.bytes, size)) { os_ptr op0 = op; push(1); *op0 = *op1; r_set_size(op0, size); op1->value.bytes += size; r_dec_size(op1, size); make_true(op); } else make_false(op); return 0; } /* <string> <pattern> (r)search <post> <match> <pre> -true- */ /* <string> <pattern> (r)search <string> -false- */ static int search_impl(i_ctx_t *i_ctx_p, bool forward) { os_ptr op = osp; os_ptr op1 = op - 1; uint size = r_size(op); uint count; byte *pat; byte *ptr; byte ch; int incr = forward ? 1 : -1; check_read_type(*op1, t_string); check_read_type(*op, t_string); if (size > r_size(op1)) { /* can't match */ make_false(op); return 0; } count = r_size(op1) - size; ptr = op1->value.bytes; if (size == 0) goto found; if (!forward) ptr += count; pat = op->value.bytes; ch = pat[0]; do { if (*ptr == ch && (size == 1 || !memcmp(ptr, pat, size))) goto found; ptr += incr; } while (count--); /* No match */ make_false(op); return 0; found: op->tas.type_attrs = op1->tas.type_attrs; op->value.bytes = ptr; r_set_size(op, size); push(2); op[-1] = *op1; r_set_size(op - 1, ptr - op[-1].value.bytes); op1->value.bytes = ptr + size; r_set_size(op1, count + (!forward ? (size - 1) : 0)); make_true(op); return 0; } /* Search from the start of the string */ static int zsearch(i_ctx_t *i_ctx_p) { return search_impl(i_ctx_p, true); } /* Search from the end of the string */ static int zrsearch(i_ctx_t *i_ctx_p) { return search_impl(i_ctx_p, false); } /* <string> <charstring> .stringbreak <int|null> */ static int zstringbreak(i_ctx_t *i_ctx_p) { os_ptr op = osp; uint i, j; check_read_type(op[-1], t_string); check_read_type(*op, t_string); /* We can't use strpbrk here, because C doesn't allow nulls in strings. */ for (i = 0; i < r_size(op - 1); ++i) for (j = 0; j < r_size(op); ++j) if (op[-1].value.const_bytes[i] == op->value.const_bytes[j]) { make_int(op - 1, i); goto done; } make_null(op - 1); done: pop(1); return 0; } /* <obj> <pattern> .stringmatch <bool> */ static int zstringmatch(i_ctx_t *i_ctx_p) { os_ptr op = osp; os_ptr op1 = op - 1; bool result; check_read_type(*op, t_string); switch (r_type(op1)) { case t_string: check_read(*op1); goto cmp; case t_name: name_string_ref(imemory, op1, op1); /* can't fail */ cmp: result = string_match(op1->value.const_bytes, r_size(op1), op->value.const_bytes, r_size(op), NULL); break; default: result = (r_size(op) == 1 && *op->value.bytes == '*'); } make_bool(op1, result); pop(1); return 0; } /* ------ Initialization procedure ------ */ const op_def zstring_op_defs[] = { {"1.bytestring", zbytestring}, {"2anchorsearch", zanchorsearch}, {"1.namestring", znamestring}, {"2search", zsearch}, {"2rsearch", zrsearch}, {"1string", zstring}, {"2.stringbreak", zstringbreak}, {"2.stringmatch", zstringmatch}, op_def_end(0) };
null
/* Copyright (C) 2001-2020 Artifex Software, Inc. All Rights Reserved. This software is provided AS-IS with no warranty, either express or implied. This software is distributed under license and may not be copied, modified or distributed except as expressly authorized under the terms of the license contained in the file LICENSE in this distribution. Refer to licensing information at http://www.artifex.com or contact Artifex Software, Inc., 1305 Grant Avenue - Suite 200, Novato, CA 94945, U.S.A., +1(415)492-9861, for further information. */ /* String operators */ #include "memory_.h" #include "ghost.h" #include "gsutil.h" #include "ialloc.h" #include "iname.h" #include "ivmspace.h" #include "oper.h" #include "store.h" /* The generic operators (copy, get, put, getinterval, putinterval, */ /* length, and forall) are implemented in zgeneric.c. */ /* <int> .bytestring <bytestring> */ static int zbytestring(i_ctx_t *i_ctx_p) { os_ptr op = osp; byte *sbody; uint size; check_int_leu(*op, max_int); size = (uint)op->value.intval; sbody = ialloc_bytes(size, ".bytestring"); if (sbody == 0) return_error(gs_error_VMerror); make_astruct(op, a_all | icurrent_space, sbody); memset(sbody, 0, size); return 0; } /* <int> string <string> */ int zstring(i_ctx_t *i_ctx_p) { os_ptr op = osp; byte *sbody; uint size; check_type(*op, t_integer); if (op->value.intval < 0 ) return_error(gs_error_rangecheck); if (op->value.intval > max_string_size ) return_error(gs_error_limitcheck); /* to match Distiller */ size = op->value.intval; sbody = ialloc_string(size, "string"); if (sbody == 0) return_error(gs_error_VMerror); make_string(op, a_all | icurrent_space, size, sbody); memset(sbody, 0, size); return 0; } /* <name> .namestring <string> */ static int znamestring(i_ctx_t *i_ctx_p) { os_ptr op = osp; check_type(*op, t_name); name_string_ref(imemory, op, op); return 0; } /* <string> <pattern> anchorsearch <post> <match> -true- */ /* <string> <pattern> anchorsearch <string> -false- */ static int zanchorsearch(i_ctx_t *i_ctx_p) { os_ptr op = osp; os_ptr op1 = op - 1; uint size = r_size(op); check_read_type(*op, t_string); check_read_type(*op1, t_string); if (size <= r_size(op1) && !memcmp(op1->value.bytes, op->value.bytes, size)) { os_ptr op0 = op; push(1); *op0 = *op1; r_set_size(op0, size); op1->value.bytes += size; r_dec_size(op1, size); make_true(op); } else make_false(op); return 0; } /* <string> <pattern> (r)search <post> <match> <pre> -true- */ /* <string> <pattern> (r)search <string> -false- */ static int search_impl(i_ctx_t *i_ctx_p, bool forward) { os_ptr op = osp; os_ptr op1 = op - 1; uint size = r_size(op); uint count; byte *pat; byte *ptr; byte ch; int incr = forward ? 1 : -1; check_read_type(*op1, t_string); check_read_type(*op, t_string); if (size > r_size(op1)) { /* can't match */ make_false(op); return 0; } count = r_size(op1) - size; ptr = op1->value.bytes; if (size == 0) goto found; if (!forward) ptr += count; pat = op->value.bytes; ch = pat[0]; do { if (*ptr == ch && (size == 1 || !memcmp(ptr, pat, size))) goto found; ptr += incr; } while (count--); /* No match */ make_false(op); return 0; found: op->tas.type_attrs = op1->tas.type_attrs; op->value.bytes = ptr; /* match */ op->tas.rsize = size; /* match */ push(2); op[-1] = *op1; /* pre */ op[-3].value.bytes = ptr + size; /* post */ if (forward) { op[-1].tas.rsize = ptr - op[-1].value.bytes; /* pre */ op[-3].tas.rsize = count; /* post */ } else { op[-1].tas.rsize = count; /* pre */ op[-3].tas.rsize -= count + size; /* post */ } make_true(op); return 0; } /* Search from the start of the string */ static int zsearch(i_ctx_t *i_ctx_p) { return search_impl(i_ctx_p, true); } /* Search from the end of the string */ static int zrsearch(i_ctx_t *i_ctx_p) { return search_impl(i_ctx_p, false); } /* <string> <charstring> .stringbreak <int|null> */ static int zstringbreak(i_ctx_t *i_ctx_p) { os_ptr op = osp; uint i, j; check_read_type(op[-1], t_string); check_read_type(*op, t_string); /* We can't use strpbrk here, because C doesn't allow nulls in strings. */ for (i = 0; i < r_size(op - 1); ++i) for (j = 0; j < r_size(op); ++j) if (op[-1].value.const_bytes[i] == op->value.const_bytes[j]) { make_int(op - 1, i); goto done; } make_null(op - 1); done: pop(1); return 0; } /* <obj> <pattern> .stringmatch <bool> */ static int zstringmatch(i_ctx_t *i_ctx_p) { os_ptr op = osp; os_ptr op1 = op - 1; bool result; check_read_type(*op, t_string); switch (r_type(op1)) { case t_string: check_read(*op1); goto cmp; case t_name: name_string_ref(imemory, op1, op1); /* can't fail */ cmp: result = string_match(op1->value.const_bytes, r_size(op1), op->value.const_bytes, r_size(op), NULL); break; default: result = (r_size(op) == 1 && *op->value.bytes == '*'); } make_bool(op1, result); pop(1); return 0; } /* ------ Initialization procedure ------ */ const op_def zstring_op_defs[] = { {"1.bytestring", zbytestring}, {"2anchorsearch", zanchorsearch}, {"1.namestring", znamestring}, {"2search", zsearch}, {"2rsearch", zrsearch}, {"1string", zstring}, {"2.stringbreak", zstringbreak}, {"2.stringmatch", zstringmatch}, op_def_end(0) };
null
191
CWE-787
CVE-2020-15904
/* The code below is mostly derived from cx_bsdiff (written by Anthony Tuininga, http://cx-bsdiff.sourceforge.net/). The cx_bsdiff code in turn was derived from bsdiff, the standalone utility produced for BSD which can be found at http://www.daemonology.net/bsdiff. */ #define PY_SSIZE_T_CLEAN #include <Python.h> #if PY_MAJOR_VERSION >= 3 #define IS_PY3K #endif #define MIN(x, y) (((x) < (y)) ? (x) : (y)) static void split(off_t *I, off_t *V, off_t start, off_t len, off_t h) { off_t i, j, k, x, tmp, jj, kk; if (len < 16) { for (k = start; k < start + len; k += j) { j = 1; x = V[I[k] + h]; for (i = 1; k + i < start + len; i++) { if (V[I[k + i] + h] < x) { x = V[I[k + i] + h]; j = 0; } if (V[I[k + i] + h] == x) { tmp = I[k + j]; I[k + j] = I[k + i]; I[k + i] = tmp; j++; } } for (i = 0; i < j; i++) V[I[k + i]] = k + j - 1; if (j == 1) I[k] = -1; } } else { jj = 0; kk = 0; x = V[I[start + len / 2] + h]; for (i = start; i < start + len; i++) { if (V[I[i] + h] < x) jj++; if (V[I[i] + h] == x) kk++; } jj += start; kk += jj; j = 0; k = 0; i = start; while (i < jj) { if (V[I[i] + h] < x) { i++; } else if (V[I[i] + h] == x) { tmp = I[i]; I[i] = I[jj + j]; I[jj + j] = tmp; j++; } else { tmp = I[i]; I[i] = I[kk + k]; I[kk + k] = tmp; k++; } } while (jj + j < kk) { if (V[I[jj + j] + h] == x) { j++; } else { tmp = I[jj + j]; I[jj + j] = I[kk + k]; I[kk + k] = tmp; k++; } } if (jj > start) split(I, V, start, jj - start, h); for (i = 0; i < kk - jj; i++) V[I[jj + i]] = kk - 1; if (jj == kk - 1) I[jj] = -1; if (start + len > kk) split(I, V, kk, start + len - kk, h); } } static void qsufsort(off_t *I, off_t *V, unsigned char *old, off_t oldsize) { off_t buckets[256], i, h, len; for (i = 0; i < 256; i++) buckets[i] = 0; for (i = 0; i < oldsize; i++) buckets[old[i]]++; for (i = 1; i < 256; i++) buckets[i] += buckets[i - 1]; for (i = 255; i > 0; i--) buckets[i] = buckets[i - 1]; buckets[0] = 0; for (i = 0; i < oldsize; i++) I[++buckets[old[i]]] = i; I[0] = oldsize; for (i = 0; i < oldsize; i++) V[i] = buckets[old[i]]; V[oldsize] = 0; for (i = 1; i < 256; i++) if (buckets[i] == buckets[i - 1] + 1) I[buckets[i]] = -1; I[0] = -1; for (h = 1; I[0] != -(oldsize + 1); h += h) { len = 0; for (i = 0; i < oldsize + 1;) { if (I[i] < 0) { len -= I[i]; i -= I[i]; } else { if (len) I[i - len] = -len; len = V[I[i]] + 1 - i; split(I, V, i, len, h); i += len; len=0; } } if (len) I[i - len] = -len; } for (i = 0; i < oldsize + 1; i++) I[V[i]] = i; } static off_t matchlen(unsigned char *old, off_t oldsize, unsigned char *new, off_t newsize) { off_t i; for (i = 0; (i < oldsize) && (i < newsize); i++) if (old[i] != new[i]) break; return i; } static off_t search(off_t *I, unsigned char *old, off_t oldsize, unsigned char *new, off_t newsize, off_t st, off_t en, off_t *pos) { off_t x, y; if (en - st < 2) { x = matchlen(old + I[st], oldsize - I[st], new, newsize); y = matchlen(old + I[en], oldsize - I[en], new, newsize); if (x > y) { *pos = I[st]; return x; } else { *pos = I[en]; return y; } } x = st + (en - st) / 2; if (memcmp(old + I[x], new, MIN(oldsize - I[x], newsize)) < 0) { return search(I, old, oldsize, new, newsize, x, en, pos); } else { return search(I, old, oldsize, new, newsize, st, x, pos); } } /* performs a diff between the two data streams and returns a tuple containing the control, diff and extra blocks that bsdiff produces */ static PyObject* diff(PyObject* self, PyObject* args) { off_t lastscan, lastpos, lastoffset, oldscore, scsc, overlap, Ss, lens; off_t *I, *V, dblen, eblen, scan, pos, len, s, Sf, lenf, Sb, lenb, i; PyObject *controlTuples, *tuple, *results, *temp; Py_ssize_t origDataLength, newDataLength; char *origData, *newData; unsigned char *db, *eb; if (!PyArg_ParseTuple(args, "s#s#", &origData, &origDataLength, &newData, &newDataLength)) return NULL; /* create the control tuple */ controlTuples = PyList_New(0); if (!controlTuples) return NULL; /* perform sort on original data */ I = PyMem_Malloc((origDataLength + 1) * sizeof(off_t)); if (!I) { Py_DECREF(controlTuples); return PyErr_NoMemory(); } V = PyMem_Malloc((origDataLength + 1) * sizeof(off_t)); if (!V) { Py_DECREF(controlTuples); PyMem_Free(I); return PyErr_NoMemory(); } Py_BEGIN_ALLOW_THREADS /* release GIL */ qsufsort(I, V, (unsigned char *) origData, origDataLength); Py_END_ALLOW_THREADS PyMem_Free(V); /* allocate memory for the diff and extra blocks */ db = PyMem_Malloc(newDataLength + 1); if (!db) { Py_DECREF(controlTuples); PyMem_Free(I); return PyErr_NoMemory(); } eb = PyMem_Malloc(newDataLength + 1); if (!eb) { Py_DECREF(controlTuples); PyMem_Free(I); PyMem_Free(db); return PyErr_NoMemory(); } dblen = 0; eblen = 0; /* perform the diff */ len = 0; scan = 0; lastscan = 0; lastpos = 0; lastoffset = 0; pos = 0; while (scan < newDataLength) { oldscore = 0; Py_BEGIN_ALLOW_THREADS /* release GIL */ for (scsc = scan += len; scan < newDataLength; scan++) { len = search(I, (unsigned char *) origData, origDataLength, (unsigned char *) newData + scan, newDataLength - scan, 0, origDataLength, &pos); for (; scsc < scan + len; scsc++) if ((scsc + lastoffset < origDataLength) && (origData[scsc + lastoffset] == newData[scsc])) oldscore++; if (((len == oldscore) && (len != 0)) || (len > oldscore + 8)) break; if ((scan + lastoffset < origDataLength) && (origData[scan + lastoffset] == newData[scan])) oldscore--; } Py_END_ALLOW_THREADS if ((len != oldscore) || (scan == newDataLength)) { s = 0; Sf = 0; lenf = 0; for (i = 0; (lastscan + i < scan) && (lastpos + i < origDataLength);) { if (origData[lastpos + i] == newData[lastscan + i]) s++; i++; if (s * 2 - i > Sf * 2 - lenf) { Sf = s; lenf = i; } } lenb = 0; if (scan < newDataLength) { s = 0; Sb = 0; for (i = 1; (scan >= lastscan + i) && (pos >= i); i++) { if (origData[pos - i] == newData[scan - i]) s++; if (s * 2 - i > Sb * 2 - lenb) { Sb = s; lenb = i; } } } if (lastscan + lenf > scan - lenb) { overlap = (lastscan + lenf) - (scan - lenb); s = 0; Ss = 0; lens = 0; for (i = 0; i < overlap; i++) { if (newData[lastscan + lenf - overlap + i] == origData[lastpos + lenf - overlap + i]) s++; if (newData[scan - lenb + i]== origData[pos - lenb + i]) s--; if (s > Ss) { Ss = s; lens = i + 1; } } lenf += lens - overlap; lenb -= lens; } for (i = 0; i < lenf; i++) db[dblen + i] = newData[lastscan + i] - origData[lastpos + i]; for (i = 0; i < (scan - lenb) - (lastscan + lenf); i++) eb[eblen + i] = newData[lastscan + lenf + i]; dblen += lenf; eblen += (scan - lenb) - (lastscan + lenf); tuple = PyTuple_New(3); if (!tuple) { Py_DECREF(controlTuples); PyMem_Free(I); PyMem_Free(db); PyMem_Free(eb); return NULL; } PyTuple_SET_ITEM(tuple, 0, PyLong_FromLong(lenf)); PyTuple_SET_ITEM(tuple, 1, PyLong_FromLong((scan - lenb) - (lastscan + lenf))); PyTuple_SET_ITEM(tuple, 2, PyLong_FromLong((pos - lenb) - (lastpos + lenf))); if (PyList_Append(controlTuples, tuple) < 0) { Py_DECREF(controlTuples); Py_DECREF(tuple); PyMem_Free(I); PyMem_Free(db); PyMem_Free(eb); return NULL; } Py_DECREF(tuple); lastscan = scan - lenb; lastpos = pos - lenb; lastoffset = pos - scan; } } PyMem_Free(I); results = PyTuple_New(3); if (!results) { PyMem_Free(db); PyMem_Free(eb); return NULL; } PyTuple_SET_ITEM(results, 0, controlTuples); temp = PyBytes_FromStringAndSize((char *) db, dblen); PyMem_Free(db); if (!temp) { PyMem_Free(eb); Py_DECREF(results); return NULL; } PyTuple_SET_ITEM(results, 1, temp); temp = PyBytes_FromStringAndSize((char *) eb, eblen); PyMem_Free(eb); if (!temp) { Py_DECREF(results); return NULL; } PyTuple_SET_ITEM(results, 2, temp); return results; } /* takes the original data and the control, diff and extra blocks produced by bsdiff and returns the new data */ static PyObject* patch(PyObject* self, PyObject* args) { char *origData, *newData, *diffBlock, *extraBlock, *diffPtr, *extraPtr; Py_ssize_t origDataLength, newDataLength, diffBlockLength, extraBlockLength; PyObject *controlTuples, *tuple, *results; off_t oldpos, newpos, x, y, z; int i, j, numTuples; if (!PyArg_ParseTuple(args, "s#nO!s#s#", &origData, &origDataLength, &newDataLength, &PyList_Type, &controlTuples, &diffBlock, &diffBlockLength, &extraBlock, &extraBlockLength)) return NULL; /* allocate the memory for the new data */ newData = PyMem_Malloc(newDataLength + 1); if (!newData) return PyErr_NoMemory(); oldpos = 0; newpos = 0; diffPtr = diffBlock; extraPtr = extraBlock; numTuples = PyList_GET_SIZE(controlTuples); for (i = 0; i < numTuples; i++) { tuple = PyList_GET_ITEM(controlTuples, i); if (!PyTuple_Check(tuple)) { PyMem_Free(newData); PyErr_SetString(PyExc_TypeError, "expecting tuple"); return NULL; } if (PyTuple_GET_SIZE(tuple) != 3) { PyMem_Free(newData); PyErr_SetString(PyExc_TypeError, "expecting tuple of size 3"); return NULL; } x = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 0)); y = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 1)); z = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 2)); if (newpos + x > newDataLength || diffPtr + x > diffBlock + diffBlockLength || extraPtr + y > extraBlock + extraBlockLength) { PyMem_Free(newData); PyErr_SetString(PyExc_ValueError, "corrupt patch (overflow)"); return NULL; } memcpy(newData + newpos, diffPtr, x); diffPtr += x; for (j = 0; j < x; j++) if ((oldpos + j >= 0) && (oldpos + j < origDataLength)) newData[newpos + j] += origData[oldpos + j]; newpos += x; oldpos += x; memcpy(newData + newpos, extraPtr, y); extraPtr += y; newpos += y; oldpos += z; } /* confirm that a valid patch was applied */ if (newpos != newDataLength || diffPtr != diffBlock + diffBlockLength || extraPtr != extraBlock + extraBlockLength) { PyMem_Free(newData); PyErr_SetString(PyExc_ValueError, "corrupt patch (underflow)"); return NULL; } results = PyBytes_FromStringAndSize(newData, newDataLength); PyMem_Free(newData); return results; } /* encode an integer value as 8 bytes */ static PyObject *encode_int64(PyObject *self, PyObject *value) { long long x; char bs[8], sign = 0x00; int i; if (!PyArg_Parse(value, "L", &x)) return NULL; if (x < 0) { x = -x; sign = 0x80; } for (i = 0; i < 8; i++) { bs[i] = x & 0xff; x >>= 8; /* x /= 256 */ } bs[7] |= sign; return PyBytes_FromStringAndSize(bs, 8); } /* decode an off_t value from 8 bytes */ static PyObject *decode_int64(PyObject *self, PyObject *string) { long long x; char *bs; int i; if (!PyBytes_Check(string)) { PyErr_SetString(PyExc_TypeError, "bytes expected"); return NULL; } if (PyBytes_Size(string) != 8) { PyErr_SetString(PyExc_ValueError, "8 bytes expected"); return NULL; } bs = PyBytes_AsString(string); x = bs[7] & 0x7F; for (i = 6; i >= 0; i--) { x <<= 8; /* x = x * 256 + (unsigned char) bs[i]; */ x |= (unsigned char) bs[i]; } if (bs[7] & 0x80) x = -x; return PyLong_FromLongLong(x); } /* declaration of methods supported by this module */ static PyMethodDef module_functions[] = { {"diff", diff, METH_VARARGS}, {"patch", patch, METH_VARARGS}, {"encode_int64", encode_int64, METH_O}, {"decode_int64", decode_int64, METH_O}, {NULL, NULL, 0, NULL} /* Sentinel */ }; /* initialization routine for the shared libary */ #ifdef IS_PY3K static PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "core", 0, -1, module_functions, }; PyMODINIT_FUNC PyInit_core(void) { PyObject *m; m = PyModule_Create(&moduledef); if (m == NULL) return NULL; return m; } #else PyMODINIT_FUNC initcore(void) { Py_InitModule("core", module_functions); } #endif
null
/* The code below is mostly derived from cx_bsdiff (written by Anthony Tuininga, http://cx-bsdiff.sourceforge.net/). The cx_bsdiff code in turn was derived from bsdiff, the standalone utility produced for BSD which can be found at http://www.daemonology.net/bsdiff. */ #define PY_SSIZE_T_CLEAN #include <Python.h> #if PY_MAJOR_VERSION >= 3 #define IS_PY3K #endif #define MIN(x, y) (((x) < (y)) ? (x) : (y)) static void split(off_t *I, off_t *V, off_t start, off_t len, off_t h) { off_t i, j, k, x, tmp, jj, kk; if (len < 16) { for (k = start; k < start + len; k += j) { j = 1; x = V[I[k] + h]; for (i = 1; k + i < start + len; i++) { if (V[I[k + i] + h] < x) { x = V[I[k + i] + h]; j = 0; } if (V[I[k + i] + h] == x) { tmp = I[k + j]; I[k + j] = I[k + i]; I[k + i] = tmp; j++; } } for (i = 0; i < j; i++) V[I[k + i]] = k + j - 1; if (j == 1) I[k] = -1; } } else { jj = 0; kk = 0; x = V[I[start + len / 2] + h]; for (i = start; i < start + len; i++) { if (V[I[i] + h] < x) jj++; if (V[I[i] + h] == x) kk++; } jj += start; kk += jj; j = 0; k = 0; i = start; while (i < jj) { if (V[I[i] + h] < x) { i++; } else if (V[I[i] + h] == x) { tmp = I[i]; I[i] = I[jj + j]; I[jj + j] = tmp; j++; } else { tmp = I[i]; I[i] = I[kk + k]; I[kk + k] = tmp; k++; } } while (jj + j < kk) { if (V[I[jj + j] + h] == x) { j++; } else { tmp = I[jj + j]; I[jj + j] = I[kk + k]; I[kk + k] = tmp; k++; } } if (jj > start) split(I, V, start, jj - start, h); for (i = 0; i < kk - jj; i++) V[I[jj + i]] = kk - 1; if (jj == kk - 1) I[jj] = -1; if (start + len > kk) split(I, V, kk, start + len - kk, h); } } static void qsufsort(off_t *I, off_t *V, unsigned char *old, off_t oldsize) { off_t buckets[256], i, h, len; for (i = 0; i < 256; i++) buckets[i] = 0; for (i = 0; i < oldsize; i++) buckets[old[i]]++; for (i = 1; i < 256; i++) buckets[i] += buckets[i - 1]; for (i = 255; i > 0; i--) buckets[i] = buckets[i - 1]; buckets[0] = 0; for (i = 0; i < oldsize; i++) I[++buckets[old[i]]] = i; I[0] = oldsize; for (i = 0; i < oldsize; i++) V[i] = buckets[old[i]]; V[oldsize] = 0; for (i = 1; i < 256; i++) if (buckets[i] == buckets[i - 1] + 1) I[buckets[i]] = -1; I[0] = -1; for (h = 1; I[0] != -(oldsize + 1); h += h) { len = 0; for (i = 0; i < oldsize + 1;) { if (I[i] < 0) { len -= I[i]; i -= I[i]; } else { if (len) I[i - len] = -len; len = V[I[i]] + 1 - i; split(I, V, i, len, h); i += len; len=0; } } if (len) I[i - len] = -len; } for (i = 0; i < oldsize + 1; i++) I[V[i]] = i; } static off_t matchlen(unsigned char *old, off_t oldsize, unsigned char *new, off_t newsize) { off_t i; for (i = 0; (i < oldsize) && (i < newsize); i++) if (old[i] != new[i]) break; return i; } static off_t search(off_t *I, unsigned char *old, off_t oldsize, unsigned char *new, off_t newsize, off_t st, off_t en, off_t *pos) { off_t x, y; if (en - st < 2) { x = matchlen(old + I[st], oldsize - I[st], new, newsize); y = matchlen(old + I[en], oldsize - I[en], new, newsize); if (x > y) { *pos = I[st]; return x; } else { *pos = I[en]; return y; } } x = st + (en - st) / 2; if (memcmp(old + I[x], new, MIN(oldsize - I[x], newsize)) < 0) { return search(I, old, oldsize, new, newsize, x, en, pos); } else { return search(I, old, oldsize, new, newsize, st, x, pos); } } /* performs a diff between the two data streams and returns a tuple containing the control, diff and extra blocks that bsdiff produces */ static PyObject* diff(PyObject* self, PyObject* args) { off_t lastscan, lastpos, lastoffset, oldscore, scsc, overlap, Ss, lens; off_t *I, *V, dblen, eblen, scan, pos, len, s, Sf, lenf, Sb, lenb, i; PyObject *controlTuples, *tuple, *results, *temp; Py_ssize_t origDataLength, newDataLength; char *origData, *newData; unsigned char *db, *eb; if (!PyArg_ParseTuple(args, "s#s#", &origData, &origDataLength, &newData, &newDataLength)) return NULL; /* create the control tuple */ controlTuples = PyList_New(0); if (!controlTuples) return NULL; /* perform sort on original data */ I = PyMem_Malloc((origDataLength + 1) * sizeof(off_t)); if (!I) { Py_DECREF(controlTuples); return PyErr_NoMemory(); } V = PyMem_Malloc((origDataLength + 1) * sizeof(off_t)); if (!V) { Py_DECREF(controlTuples); PyMem_Free(I); return PyErr_NoMemory(); } Py_BEGIN_ALLOW_THREADS /* release GIL */ qsufsort(I, V, (unsigned char *) origData, origDataLength); Py_END_ALLOW_THREADS PyMem_Free(V); /* allocate memory for the diff and extra blocks */ db = PyMem_Malloc(newDataLength + 1); if (!db) { Py_DECREF(controlTuples); PyMem_Free(I); return PyErr_NoMemory(); } eb = PyMem_Malloc(newDataLength + 1); if (!eb) { Py_DECREF(controlTuples); PyMem_Free(I); PyMem_Free(db); return PyErr_NoMemory(); } dblen = 0; eblen = 0; /* perform the diff */ len = 0; scan = 0; lastscan = 0; lastpos = 0; lastoffset = 0; pos = 0; while (scan < newDataLength) { oldscore = 0; Py_BEGIN_ALLOW_THREADS /* release GIL */ for (scsc = scan += len; scan < newDataLength; scan++) { len = search(I, (unsigned char *) origData, origDataLength, (unsigned char *) newData + scan, newDataLength - scan, 0, origDataLength, &pos); for (; scsc < scan + len; scsc++) if ((scsc + lastoffset < origDataLength) && (origData[scsc + lastoffset] == newData[scsc])) oldscore++; if (((len == oldscore) && (len != 0)) || (len > oldscore + 8)) break; if ((scan + lastoffset < origDataLength) && (origData[scan + lastoffset] == newData[scan])) oldscore--; } Py_END_ALLOW_THREADS if ((len != oldscore) || (scan == newDataLength)) { s = 0; Sf = 0; lenf = 0; for (i = 0; (lastscan + i < scan) && (lastpos + i < origDataLength);) { if (origData[lastpos + i] == newData[lastscan + i]) s++; i++; if (s * 2 - i > Sf * 2 - lenf) { Sf = s; lenf = i; } } lenb = 0; if (scan < newDataLength) { s = 0; Sb = 0; for (i = 1; (scan >= lastscan + i) && (pos >= i); i++) { if (origData[pos - i] == newData[scan - i]) s++; if (s * 2 - i > Sb * 2 - lenb) { Sb = s; lenb = i; } } } if (lastscan + lenf > scan - lenb) { overlap = (lastscan + lenf) - (scan - lenb); s = 0; Ss = 0; lens = 0; for (i = 0; i < overlap; i++) { if (newData[lastscan + lenf - overlap + i] == origData[lastpos + lenf - overlap + i]) s++; if (newData[scan - lenb + i]== origData[pos - lenb + i]) s--; if (s > Ss) { Ss = s; lens = i + 1; } } lenf += lens - overlap; lenb -= lens; } for (i = 0; i < lenf; i++) db[dblen + i] = newData[lastscan + i] - origData[lastpos + i]; for (i = 0; i < (scan - lenb) - (lastscan + lenf); i++) eb[eblen + i] = newData[lastscan + lenf + i]; dblen += lenf; eblen += (scan - lenb) - (lastscan + lenf); tuple = PyTuple_New(3); if (!tuple) { Py_DECREF(controlTuples); PyMem_Free(I); PyMem_Free(db); PyMem_Free(eb); return NULL; } PyTuple_SET_ITEM(tuple, 0, PyLong_FromLong(lenf)); PyTuple_SET_ITEM(tuple, 1, PyLong_FromLong((scan - lenb) - (lastscan + lenf))); PyTuple_SET_ITEM(tuple, 2, PyLong_FromLong((pos - lenb) - (lastpos + lenf))); if (PyList_Append(controlTuples, tuple) < 0) { Py_DECREF(controlTuples); Py_DECREF(tuple); PyMem_Free(I); PyMem_Free(db); PyMem_Free(eb); return NULL; } Py_DECREF(tuple); lastscan = scan - lenb; lastpos = pos - lenb; lastoffset = pos - scan; } } PyMem_Free(I); results = PyTuple_New(3); if (!results) { PyMem_Free(db); PyMem_Free(eb); return NULL; } PyTuple_SET_ITEM(results, 0, controlTuples); temp = PyBytes_FromStringAndSize((char *) db, dblen); PyMem_Free(db); if (!temp) { PyMem_Free(eb); Py_DECREF(results); return NULL; } PyTuple_SET_ITEM(results, 1, temp); temp = PyBytes_FromStringAndSize((char *) eb, eblen); PyMem_Free(eb); if (!temp) { Py_DECREF(results); return NULL; } PyTuple_SET_ITEM(results, 2, temp); return results; } /* takes the original data and the control, diff and extra blocks produced by bsdiff and returns the new data */ static PyObject* patch(PyObject* self, PyObject* args) { char *origData, *newData, *diffBlock, *extraBlock, *diffPtr, *extraPtr; Py_ssize_t origDataLength, newDataLength, diffBlockLength, extraBlockLength; PyObject *controlTuples, *tuple, *results; off_t oldpos, newpos, x, y, z; int i, j, numTuples; if (!PyArg_ParseTuple(args, "s#nO!s#s#", &origData, &origDataLength, &newDataLength, &PyList_Type, &controlTuples, &diffBlock, &diffBlockLength, &extraBlock, &extraBlockLength)) return NULL; /* allocate the memory for the new data */ newData = PyMem_Malloc(newDataLength + 1); if (!newData) return PyErr_NoMemory(); oldpos = 0; newpos = 0; diffPtr = diffBlock; extraPtr = extraBlock; numTuples = PyList_GET_SIZE(controlTuples); for (i = 0; i < numTuples; i++) { tuple = PyList_GET_ITEM(controlTuples, i); if (!PyTuple_Check(tuple)) { PyMem_Free(newData); PyErr_SetString(PyExc_TypeError, "expecting tuple"); return NULL; } if (PyTuple_GET_SIZE(tuple) != 3) { PyMem_Free(newData); PyErr_SetString(PyExc_TypeError, "expecting tuple of size 3"); return NULL; } x = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 0)); y = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 1)); z = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 2)); if (newpos + x > newDataLength || diffPtr + x > diffBlock + diffBlockLength) { PyMem_Free(newData); PyErr_SetString(PyExc_ValueError, "corrupt patch (overflow)"); return NULL; } memcpy(newData + newpos, diffPtr, x); diffPtr += x; for (j = 0; j < x; j++) if ((oldpos + j >= 0) && (oldpos + j < origDataLength)) newData[newpos + j] += origData[oldpos + j]; newpos += x; oldpos += x; if (newpos + y > newDataLength || extraPtr + y > extraBlock + extraBlockLength) { PyMem_Free(newData); PyErr_SetString(PyExc_ValueError, "corrupt patch (overflow)"); return NULL; } memcpy(newData + newpos, extraPtr, y); extraPtr += y; newpos += y; oldpos += z; } /* confirm that a valid patch was applied */ if (newpos != newDataLength || diffPtr != diffBlock + diffBlockLength || extraPtr != extraBlock + extraBlockLength) { PyMem_Free(newData); PyErr_SetString(PyExc_ValueError, "corrupt patch (underflow)"); return NULL; } results = PyBytes_FromStringAndSize(newData, newDataLength); PyMem_Free(newData); return results; } /* encode an integer value as 8 bytes */ static PyObject *encode_int64(PyObject *self, PyObject *value) { long long x; char bs[8], sign = 0x00; int i; if (!PyArg_Parse(value, "L", &x)) return NULL; if (x < 0) { x = -x; sign = 0x80; } for (i = 0; i < 8; i++) { bs[i] = x & 0xff; x >>= 8; /* x /= 256 */ } bs[7] |= sign; return PyBytes_FromStringAndSize(bs, 8); } /* decode an off_t value from 8 bytes */ static PyObject *decode_int64(PyObject *self, PyObject *string) { long long x; char *bs; int i; if (!PyBytes_Check(string)) { PyErr_SetString(PyExc_TypeError, "bytes expected"); return NULL; } if (PyBytes_Size(string) != 8) { PyErr_SetString(PyExc_ValueError, "8 bytes expected"); return NULL; } bs = PyBytes_AsString(string); x = bs[7] & 0x7F; for (i = 6; i >= 0; i--) { x <<= 8; /* x = x * 256 + (unsigned char) bs[i]; */ x |= (unsigned char) bs[i]; } if (bs[7] & 0x80) x = -x; return PyLong_FromLongLong(x); } /* declaration of methods supported by this module */ static PyMethodDef module_functions[] = { {"diff", diff, METH_VARARGS}, {"patch", patch, METH_VARARGS}, {"encode_int64", encode_int64, METH_O}, {"decode_int64", decode_int64, METH_O}, {NULL, NULL, 0, NULL} /* Sentinel */ }; /* initialization routine for the shared libary */ #ifdef IS_PY3K static PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "core", 0, -1, module_functions, }; PyMODINIT_FUNC PyInit_core(void) { PyObject *m; m = PyModule_Create(&moduledef); if (m == NULL) return NULL; return m; } #else PyMODINIT_FUNC initcore(void) { Py_InitModule("core", module_functions); } #endif
null
192
CWE-787
CVE-2020-16587
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2011, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Industrial Light & Magic nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////// #include "ImfMultiPartInputFile.h" #include "ImfTimeCodeAttribute.h" #include "ImfChromaticitiesAttribute.h" #include "ImfBoxAttribute.h" #include "ImfFloatAttribute.h" #include "ImfStdIO.h" #include "ImfTileOffsets.h" #include "ImfMisc.h" #include "ImfTiledMisc.h" #include "ImfInputStreamMutex.h" #include "ImfInputPartData.h" #include "ImfPartType.h" #include "ImfInputFile.h" #include "ImfScanLineInputFile.h" #include "ImfTiledInputFile.h" #include "ImfDeepScanLineInputFile.h" #include "ImfDeepTiledInputFile.h" #include "ImfVersion.h" #include <OpenEXRConfig.h> #include <IlmThread.h> #include <IlmThreadMutex.h> #include <Iex.h> #include <map> #include <set> OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER using ILMTHREAD_NAMESPACE::Mutex; using ILMTHREAD_NAMESPACE::Lock; using IMATH_NAMESPACE::Box2i; using std::vector; using std::map; using std::set; using std::string; namespace { // Controls whether we error out in the event of shared attribute // inconsistency in the input file static const bool strictSharedAttribute = true; } struct MultiPartInputFile::Data: public InputStreamMutex { int version; // Version of this file. bool deleteStream; // If we should delete the stream during destruction. vector<InputPartData*> parts; // Data to initialize Output files. int numThreads; // Number of threads bool reconstructChunkOffsetTable; // If we should reconstruct // the offset table if it's broken. std::map<int,GenericInputFile*> _inputFiles; std::vector<Header> _headers; void chunkOffsetReconstruction(OPENEXR_IMF_INTERNAL_NAMESPACE::IStream& is, const std::vector<InputPartData*>& parts); void readChunkOffsetTables(bool reconstructChunkOffsetTable); bool checkSharedAttributesValues(const Header & src, const Header & dst, std::vector<std::string> & conflictingAttributes) const; TileOffsets* createTileOffsets(const Header& header); InputPartData* getPart(int partNumber); Data (bool deleteStream, int numThreads, bool reconstructChunkOffsetTable): InputStreamMutex(), deleteStream (deleteStream), numThreads (numThreads), reconstructChunkOffsetTable(reconstructChunkOffsetTable) { } ~Data() { if (deleteStream) delete is; for (size_t i = 0; i < parts.size(); i++) delete parts[i]; } template <class T> T* createInputPartT(int partNumber) { } }; MultiPartInputFile::MultiPartInputFile(const char fileName[], int numThreads, bool reconstructChunkOffsetTable): _data(new Data(true, numThreads, reconstructChunkOffsetTable)) { try { _data->is = new StdIFStream (fileName); initialize(); } catch (IEX_NAMESPACE::BaseExc &e) { delete _data; REPLACE_EXC (e, "Cannot read image file " "\"" << fileName << "\". " << e.what()); throw; } catch (...) { delete _data; throw; } } MultiPartInputFile::MultiPartInputFile (OPENEXR_IMF_INTERNAL_NAMESPACE::IStream& is, int numThreads, bool reconstructChunkOffsetTable): _data(new Data(false, numThreads, reconstructChunkOffsetTable)) { try { _data->is = &is; initialize(); } catch (IEX_NAMESPACE::BaseExc &e) { delete _data; REPLACE_EXC (e, "Cannot read image file " "\"" << is.fileName() << "\". " << e.what()); throw; } catch (...) { delete _data; throw; } } template<class T> T* MultiPartInputFile::getInputPart(int partNumber) { Lock lock(*_data); if (_data->_inputFiles.find(partNumber) == _data->_inputFiles.end()) { T* file = new T(_data->getPart(partNumber)); _data->_inputFiles.insert(std::make_pair(partNumber, (GenericInputFile*) file)); return file; } else return (T*) _data->_inputFiles[partNumber]; } template InputFile* MultiPartInputFile::getInputPart<InputFile>(int); template TiledInputFile* MultiPartInputFile::getInputPart<TiledInputFile>(int); template DeepScanLineInputFile* MultiPartInputFile::getInputPart<DeepScanLineInputFile>(int); template DeepTiledInputFile* MultiPartInputFile::getInputPart<DeepTiledInputFile>(int); InputPartData* MultiPartInputFile::getPart(int partNumber) { return _data->getPart(partNumber); } const Header & MultiPartInputFile::header(int n) const { return _data->_headers[n]; } MultiPartInputFile::~MultiPartInputFile() { for (map<int, GenericInputFile*>::iterator it = _data->_inputFiles.begin(); it != _data->_inputFiles.end(); it++) { delete it->second; } delete _data; } bool MultiPartInputFile::Data::checkSharedAttributesValues(const Header & src, const Header & dst, vector<string> & conflictingAttributes) const { conflictingAttributes.clear(); bool conflict = false; // // Display Window // if (src.displayWindow() != dst.displayWindow()) { conflict = true; conflictingAttributes.push_back ("displayWindow"); } // // Pixel Aspect Ratio // if (src.pixelAspectRatio() != dst.pixelAspectRatio()) { conflict = true; conflictingAttributes.push_back ("pixelAspectRatio"); } // // Timecode // const TimeCodeAttribute * srcTimeCode = src.findTypedAttribute< TimeCodeAttribute> (TimeCodeAttribute::staticTypeName()); const TimeCodeAttribute * dstTimeCode = dst.findTypedAttribute< TimeCodeAttribute> (TimeCodeAttribute::staticTypeName()); if (dstTimeCode) { if ( (srcTimeCode && (srcTimeCode->value() != dstTimeCode->value())) || (!srcTimeCode)) { conflict = true; conflictingAttributes.push_back (TimeCodeAttribute::staticTypeName()); } } // // Chromaticities // const ChromaticitiesAttribute * srcChrom = src.findTypedAttribute< ChromaticitiesAttribute> (ChromaticitiesAttribute::staticTypeName()); const ChromaticitiesAttribute * dstChrom = dst.findTypedAttribute< ChromaticitiesAttribute> (ChromaticitiesAttribute::staticTypeName()); if (dstChrom) { if ( (srcChrom && (srcChrom->value() != dstChrom->value())) || (!srcChrom)) { conflict = true; conflictingAttributes.push_back (ChromaticitiesAttribute::staticTypeName()); } } return conflict; } void MultiPartInputFile::initialize() { readMagicNumberAndVersionField(*_data->is, _data->version); bool multipart = isMultiPart(_data->version); bool tiled = isTiled(_data->version); // // Multipart files don't have and shouldn't have the tiled bit set. // if (tiled && multipart) throw IEX_NAMESPACE::InputExc ("Multipart files cannot have the tiled bit set"); int pos = 0; while (true) { Header header; header.readFrom(*_data->is, _data->version); // // If we read nothing then we stop reading. // if (header.readsNothing()) { pos++; break; } _data->_headers.push_back(header); if(multipart == false) break; } // // Perform usual check on headers. // for (size_t i = 0; i < _data->_headers.size(); i++) { // // Silently invent a type if the file is a single part regular image. // if( _data->_headers[i].hasType() == false ) { if(multipart) throw IEX_NAMESPACE::ArgExc ("Every header in a multipart file should have a type"); _data->_headers[i].setType(tiled ? TILEDIMAGE : SCANLINEIMAGE); } else { // // Silently fix the header type if it's wrong // (happens when a regular Image file written by EXR_2.0 is rewritten by an older library, // so doesn't effect deep image types) // if(!multipart && !isNonImage(_data->version)) { _data->_headers[i].setType(tiled ? TILEDIMAGE : SCANLINEIMAGE); } } if( _data->_headers[i].hasName() == false ) { if(multipart) throw IEX_NAMESPACE::ArgExc ("Every header in a multipart file should have a name"); } if (isTiled(_data->_headers[i].type())) _data->_headers[i].sanityCheck(true, multipart); else _data->_headers[i].sanityCheck(false, multipart); } // // Check name uniqueness. // if (multipart) { set<string> names; for (size_t i = 0; i < _data->_headers.size(); i++) { if (names.find(_data->_headers[i].name()) != names.end()) { throw IEX_NAMESPACE::InputExc ("Header name " + _data->_headers[i].name() + " is not a unique name."); } names.insert(_data->_headers[i].name()); } } // // Check shared attributes compliance. // if (multipart && strictSharedAttribute) { for (size_t i = 1; i < _data->_headers.size(); i++) { vector <string> attrs; if (_data->checkSharedAttributesValues (_data->_headers[0], _data->_headers[i], attrs)) { string attrNames; for (size_t j=0; j<attrs.size(); j++) attrNames += " " + attrs[j]; throw IEX_NAMESPACE::InputExc ("Header name " + _data->_headers[i].name() + " has non-conforming shared attributes: "+ attrNames); } } } // // Create InputParts and read chunk offset tables. // for (size_t i = 0; i < _data->_headers.size(); i++) _data->parts.push_back( new InputPartData(_data, _data->_headers[i], i, _data->numThreads, _data->version)); _data->readChunkOffsetTables(_data->reconstructChunkOffsetTable); } TileOffsets* MultiPartInputFile::Data::createTileOffsets(const Header& header) { // // Get the dataWindow information // const Box2i &dataWindow = header.dataWindow(); int minX = dataWindow.min.x; int maxX = dataWindow.max.x; int minY = dataWindow.min.y; int maxY = dataWindow.max.y; // // Precompute level and tile information // int* numXTiles; int* numYTiles; int numXLevels, numYLevels; TileDescription tileDesc = header.tileDescription(); precalculateTileInfo (tileDesc, minX, maxX, minY, maxY, numXTiles, numYTiles, numXLevels, numYLevels); TileOffsets* tileOffsets = new TileOffsets (tileDesc.mode, numXLevels, numYLevels, numXTiles, numYTiles); delete [] numXTiles; delete [] numYTiles; return tileOffsets; } void MultiPartInputFile::Data::chunkOffsetReconstruction(OPENEXR_IMF_INTERNAL_NAMESPACE::IStream& is, const vector<InputPartData*>& parts) { // // Reconstruct broken chunk offset tables. Stop once we received any exception. // Int64 position = is.tellg(); // // check we understand all the parts available: if not, we cannot continue // exceptions thrown here should trickle back up to the constructor // for (size_t i = 0; i < parts.size(); i++) { Header& header=parts[i]->header; // // do we have a valid type entry? // we only need them for true multipart files or single part non-image (deep) files // if(!header.hasType() && (isMultiPart(version) || isNonImage(version))) { throw IEX_NAMESPACE::ArgExc("cannot reconstruct incomplete file: part with missing type"); } if(!isSupportedType(header.type())) { throw IEX_NAMESPACE::ArgExc("cannot reconstruct incomplete file: part with unknown type "+header.type()); } } // how many chunks should we read? We should stop when we reach the end size_t total_chunks = 0; // for tiled-based parts, array of (pointers to) tileOffsets objects // to create mapping between tile coordinates and chunk table indices vector<TileOffsets*> tileOffsets(parts.size()); // for scanline-based parts, number of scanlines in each chunk vector<int> rowsizes(parts.size()); for(size_t i = 0 ; i < parts.size() ; i++) { total_chunks += parts[i]->chunkOffsets.size(); if (isTiled(parts[i]->header.type())) { tileOffsets[i] = createTileOffsets(parts[i]->header); }else{ tileOffsets[i] = NULL; // (TODO) fix this so that it doesn't need to be revised for future compression types. switch(parts[i]->header.compression()) { case DWAB_COMPRESSION : rowsizes[i] = 256; break; case PIZ_COMPRESSION : case B44_COMPRESSION : case B44A_COMPRESSION : case DWAA_COMPRESSION : rowsizes[i]=32; break; case ZIP_COMPRESSION : case PXR24_COMPRESSION : rowsizes[i]=16; break; case ZIPS_COMPRESSION : case RLE_COMPRESSION : case NO_COMPRESSION : rowsizes[i]=1; break; default : throw(IEX_NAMESPACE::ArgExc("Unknown compression method in chunk offset reconstruction")); } } } try { // // // Int64 chunk_start = position; for (size_t i = 0; i < total_chunks ; i++) { // // do we have a part number? // int partNumber = 0; if(isMultiPart(version)) { OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, partNumber); } if(partNumber<0 || partNumber> static_cast<int>(parts.size())) { throw IEX_NAMESPACE::IoExc("part number out of range"); } Header& header = parts[partNumber]->header; // size of chunk NOT including multipart field Int64 size_of_chunk=0; if (isTiled(header.type())) { // // // int tilex,tiley,levelx,levely; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, tilex); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, tiley); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, levelx); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, levely); //std::cout << "chunk_start for " << tilex <<',' << tiley << ',' << levelx << ' ' << levely << ':' << chunk_start << std::endl; if(!tileOffsets[partNumber]) { // this shouldn't actually happen - we should have allocated a valid // tileOffsets for any part which isTiled throw IEX_NAMESPACE::IoExc("part not tiled"); } if(!tileOffsets[partNumber]->isValidTile(tilex,tiley,levelx,levely)) { throw IEX_NAMESPACE::IoExc("invalid tile coordinates"); } (*tileOffsets[partNumber])(tilex,tiley,levelx,levely)=chunk_start; // compute chunk sizes - different procedure for deep tiles and regular // ones if(header.type()==DEEPTILE) { Int64 packed_offset; Int64 packed_sample; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, packed_offset); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, packed_sample); //add 40 byte header to packed sizes (tile coordinates, packed sizes, unpacked size) size_of_chunk=packed_offset+packed_sample+40; } else { // regular image has 20 bytes of header, 4 byte chunksize; int chunksize; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, chunksize); size_of_chunk=chunksize+20; } } else { int y_coordinate; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, y_coordinate); if(y_coordinate < header.dataWindow().min.y || y_coordinate > header.dataWindow().max.y) { throw IEX_NAMESPACE::IoExc("y out of range"); } y_coordinate -= header.dataWindow().min.y; y_coordinate /= rowsizes[partNumber]; if(y_coordinate < 0 || y_coordinate >= int(parts[partNumber]->chunkOffsets.size())) { throw IEX_NAMESPACE::IoExc("chunk index out of range"); } parts[partNumber]->chunkOffsets[y_coordinate]=chunk_start; if(header.type()==DEEPSCANLINE) { Int64 packed_offset; Int64 packed_sample; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, packed_offset); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, packed_sample); size_of_chunk=packed_offset+packed_sample+28; } else { int chunksize; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, chunksize); size_of_chunk=chunksize+8; } } if(isMultiPart(version)) { chunk_start+=4; } chunk_start+=size_of_chunk; is.seekg(chunk_start); } } catch (...) { // // Suppress all exceptions. This functions is // called only to reconstruct the line offset // table for incomplete files, and exceptions // are likely. // } // copy tiled part data back to chunk offsets for(size_t partNumber=0;partNumber<parts.size();partNumber++) { if(tileOffsets[partNumber]) { size_t pos=0; vector<vector<vector <Int64> > > offsets = tileOffsets[partNumber]->getOffsets(); for (size_t l = 0; l < offsets.size(); l++) for (size_t y = 0; y < offsets[l].size(); y++) for (size_t x = 0; x < offsets[l][y].size(); x++) { parts[ partNumber ]->chunkOffsets[pos] = offsets[l][y][x]; pos++; } delete tileOffsets[partNumber]; } } is.clear(); is.seekg (position); } InputPartData* MultiPartInputFile::Data::getPart(int partNumber) { if (partNumber < 0 || partNumber >= (int) parts.size()) throw IEX_NAMESPACE::ArgExc ("Part number is not in valid range."); return parts[partNumber]; } void MultiPartInputFile::Data::readChunkOffsetTables(bool reconstructChunkOffsetTable) { bool brokenPartsExist = false; for (size_t i = 0; i < parts.size(); i++) { int chunkOffsetTableSize = getChunkOffsetTableSize(parts[i]->header,false); parts[i]->chunkOffsets.resize(chunkOffsetTableSize); for (int j = 0; j < chunkOffsetTableSize; j++) OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*is, parts[i]->chunkOffsets[j]); // // Check chunk offsets, reconstruct if broken. // At first we assume the table is complete. // parts[i]->completed = true; for (int j = 0; j < chunkOffsetTableSize; j++) { if (parts[i]->chunkOffsets[j] <= 0) { brokenPartsExist = true; parts[i]->completed = false; break; } } } if (brokenPartsExist && reconstructChunkOffsetTable) chunkOffsetReconstruction(*is, parts); } int MultiPartInputFile::version() const { return _data->version; } bool MultiPartInputFile::partComplete(int part) const { return _data->parts[part]->completed; } int MultiPartInputFile::parts() const { return int(_data->_headers.size()); } OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_EXIT
null
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2011, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Industrial Light & Magic nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////// #include "ImfMultiPartInputFile.h" #include "ImfTimeCodeAttribute.h" #include "ImfChromaticitiesAttribute.h" #include "ImfBoxAttribute.h" #include "ImfFloatAttribute.h" #include "ImfStdIO.h" #include "ImfTileOffsets.h" #include "ImfMisc.h" #include "ImfTiledMisc.h" #include "ImfInputStreamMutex.h" #include "ImfInputPartData.h" #include "ImfPartType.h" #include "ImfInputFile.h" #include "ImfScanLineInputFile.h" #include "ImfTiledInputFile.h" #include "ImfDeepScanLineInputFile.h" #include "ImfDeepTiledInputFile.h" #include "ImfVersion.h" #include <OpenEXRConfig.h> #include <IlmThread.h> #include <IlmThreadMutex.h> #include <Iex.h> #include <map> #include <set> OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER using ILMTHREAD_NAMESPACE::Mutex; using ILMTHREAD_NAMESPACE::Lock; using IMATH_NAMESPACE::Box2i; using std::vector; using std::map; using std::set; using std::string; namespace { // Controls whether we error out in the event of shared attribute // inconsistency in the input file static const bool strictSharedAttribute = true; } struct MultiPartInputFile::Data: public InputStreamMutex { int version; // Version of this file. bool deleteStream; // If we should delete the stream during destruction. vector<InputPartData*> parts; // Data to initialize Output files. int numThreads; // Number of threads bool reconstructChunkOffsetTable; // If we should reconstruct // the offset table if it's broken. std::map<int,GenericInputFile*> _inputFiles; std::vector<Header> _headers; void chunkOffsetReconstruction(OPENEXR_IMF_INTERNAL_NAMESPACE::IStream& is, const std::vector<InputPartData*>& parts); void readChunkOffsetTables(bool reconstructChunkOffsetTable); bool checkSharedAttributesValues(const Header & src, const Header & dst, std::vector<std::string> & conflictingAttributes) const; TileOffsets* createTileOffsets(const Header& header); InputPartData* getPart(int partNumber); Data (bool deleteStream, int numThreads, bool reconstructChunkOffsetTable): InputStreamMutex(), deleteStream (deleteStream), numThreads (numThreads), reconstructChunkOffsetTable(reconstructChunkOffsetTable) { } ~Data() { if (deleteStream) delete is; for (size_t i = 0; i < parts.size(); i++) delete parts[i]; } template <class T> T* createInputPartT(int partNumber) { } }; MultiPartInputFile::MultiPartInputFile(const char fileName[], int numThreads, bool reconstructChunkOffsetTable): _data(new Data(true, numThreads, reconstructChunkOffsetTable)) { try { _data->is = new StdIFStream (fileName); initialize(); } catch (IEX_NAMESPACE::BaseExc &e) { delete _data; REPLACE_EXC (e, "Cannot read image file " "\"" << fileName << "\". " << e.what()); throw; } catch (...) { delete _data; throw; } } MultiPartInputFile::MultiPartInputFile (OPENEXR_IMF_INTERNAL_NAMESPACE::IStream& is, int numThreads, bool reconstructChunkOffsetTable): _data(new Data(false, numThreads, reconstructChunkOffsetTable)) { try { _data->is = &is; initialize(); } catch (IEX_NAMESPACE::BaseExc &e) { delete _data; REPLACE_EXC (e, "Cannot read image file " "\"" << is.fileName() << "\". " << e.what()); throw; } catch (...) { delete _data; throw; } } template<class T> T* MultiPartInputFile::getInputPart(int partNumber) { Lock lock(*_data); if (_data->_inputFiles.find(partNumber) == _data->_inputFiles.end()) { T* file = new T(_data->getPart(partNumber)); _data->_inputFiles.insert(std::make_pair(partNumber, (GenericInputFile*) file)); return file; } else return (T*) _data->_inputFiles[partNumber]; } template InputFile* MultiPartInputFile::getInputPart<InputFile>(int); template TiledInputFile* MultiPartInputFile::getInputPart<TiledInputFile>(int); template DeepScanLineInputFile* MultiPartInputFile::getInputPart<DeepScanLineInputFile>(int); template DeepTiledInputFile* MultiPartInputFile::getInputPart<DeepTiledInputFile>(int); InputPartData* MultiPartInputFile::getPart(int partNumber) { return _data->getPart(partNumber); } const Header & MultiPartInputFile::header(int n) const { return _data->_headers[n]; } MultiPartInputFile::~MultiPartInputFile() { for (map<int, GenericInputFile*>::iterator it = _data->_inputFiles.begin(); it != _data->_inputFiles.end(); it++) { delete it->second; } delete _data; } bool MultiPartInputFile::Data::checkSharedAttributesValues(const Header & src, const Header & dst, vector<string> & conflictingAttributes) const { conflictingAttributes.clear(); bool conflict = false; // // Display Window // if (src.displayWindow() != dst.displayWindow()) { conflict = true; conflictingAttributes.push_back ("displayWindow"); } // // Pixel Aspect Ratio // if (src.pixelAspectRatio() != dst.pixelAspectRatio()) { conflict = true; conflictingAttributes.push_back ("pixelAspectRatio"); } // // Timecode // const TimeCodeAttribute * srcTimeCode = src.findTypedAttribute< TimeCodeAttribute> (TimeCodeAttribute::staticTypeName()); const TimeCodeAttribute * dstTimeCode = dst.findTypedAttribute< TimeCodeAttribute> (TimeCodeAttribute::staticTypeName()); if (dstTimeCode) { if ( (srcTimeCode && (srcTimeCode->value() != dstTimeCode->value())) || (!srcTimeCode)) { conflict = true; conflictingAttributes.push_back (TimeCodeAttribute::staticTypeName()); } } // // Chromaticities // const ChromaticitiesAttribute * srcChrom = src.findTypedAttribute< ChromaticitiesAttribute> (ChromaticitiesAttribute::staticTypeName()); const ChromaticitiesAttribute * dstChrom = dst.findTypedAttribute< ChromaticitiesAttribute> (ChromaticitiesAttribute::staticTypeName()); if (dstChrom) { if ( (srcChrom && (srcChrom->value() != dstChrom->value())) || (!srcChrom)) { conflict = true; conflictingAttributes.push_back (ChromaticitiesAttribute::staticTypeName()); } } return conflict; } void MultiPartInputFile::initialize() { readMagicNumberAndVersionField(*_data->is, _data->version); bool multipart = isMultiPart(_data->version); bool tiled = isTiled(_data->version); // // Multipart files don't have and shouldn't have the tiled bit set. // if (tiled && multipart) throw IEX_NAMESPACE::InputExc ("Multipart files cannot have the tiled bit set"); int pos = 0; while (true) { Header header; header.readFrom(*_data->is, _data->version); // // If we read nothing then we stop reading. // if (header.readsNothing()) { pos++; break; } _data->_headers.push_back(header); if(multipart == false) break; } // // Perform usual check on headers. // for (size_t i = 0; i < _data->_headers.size(); i++) { // // Silently invent a type if the file is a single part regular image. // if( _data->_headers[i].hasType() == false ) { if(multipart) throw IEX_NAMESPACE::ArgExc ("Every header in a multipart file should have a type"); _data->_headers[i].setType(tiled ? TILEDIMAGE : SCANLINEIMAGE); } else { // // Silently fix the header type if it's wrong // (happens when a regular Image file written by EXR_2.0 is rewritten by an older library, // so doesn't effect deep image types) // if(!multipart && !isNonImage(_data->version)) { _data->_headers[i].setType(tiled ? TILEDIMAGE : SCANLINEIMAGE); } } if( _data->_headers[i].hasName() == false ) { if(multipart) throw IEX_NAMESPACE::ArgExc ("Every header in a multipart file should have a name"); } if (isTiled(_data->_headers[i].type())) _data->_headers[i].sanityCheck(true, multipart); else _data->_headers[i].sanityCheck(false, multipart); } // // Check name uniqueness. // if (multipart) { set<string> names; for (size_t i = 0; i < _data->_headers.size(); i++) { if (names.find(_data->_headers[i].name()) != names.end()) { throw IEX_NAMESPACE::InputExc ("Header name " + _data->_headers[i].name() + " is not a unique name."); } names.insert(_data->_headers[i].name()); } } // // Check shared attributes compliance. // if (multipart && strictSharedAttribute) { for (size_t i = 1; i < _data->_headers.size(); i++) { vector <string> attrs; if (_data->checkSharedAttributesValues (_data->_headers[0], _data->_headers[i], attrs)) { string attrNames; for (size_t j=0; j<attrs.size(); j++) attrNames += " " + attrs[j]; throw IEX_NAMESPACE::InputExc ("Header name " + _data->_headers[i].name() + " has non-conforming shared attributes: "+ attrNames); } } } // // Create InputParts and read chunk offset tables. // for (size_t i = 0; i < _data->_headers.size(); i++) _data->parts.push_back( new InputPartData(_data, _data->_headers[i], i, _data->numThreads, _data->version)); _data->readChunkOffsetTables(_data->reconstructChunkOffsetTable); } TileOffsets* MultiPartInputFile::Data::createTileOffsets(const Header& header) { // // Get the dataWindow information // const Box2i &dataWindow = header.dataWindow(); int minX = dataWindow.min.x; int maxX = dataWindow.max.x; int minY = dataWindow.min.y; int maxY = dataWindow.max.y; // // Precompute level and tile information // int* numXTiles; int* numYTiles; int numXLevels, numYLevels; TileDescription tileDesc = header.tileDescription(); precalculateTileInfo (tileDesc, minX, maxX, minY, maxY, numXTiles, numYTiles, numXLevels, numYLevels); TileOffsets* tileOffsets = new TileOffsets (tileDesc.mode, numXLevels, numYLevels, numXTiles, numYTiles); delete [] numXTiles; delete [] numYTiles; return tileOffsets; } void MultiPartInputFile::Data::chunkOffsetReconstruction(OPENEXR_IMF_INTERNAL_NAMESPACE::IStream& is, const vector<InputPartData*>& parts) { // // Reconstruct broken chunk offset tables. Stop once we received any exception. // Int64 position = is.tellg(); // // check we understand all the parts available: if not, we cannot continue // exceptions thrown here should trickle back up to the constructor // for (size_t i = 0; i < parts.size(); i++) { Header& header=parts[i]->header; // // do we have a valid type entry? // we only need them for true multipart files or single part non-image (deep) files // if(!header.hasType() && (isMultiPart(version) || isNonImage(version))) { throw IEX_NAMESPACE::ArgExc("cannot reconstruct incomplete file: part with missing type"); } if(!isSupportedType(header.type())) { throw IEX_NAMESPACE::ArgExc("cannot reconstruct incomplete file: part with unknown type "+header.type()); } } // how many chunks should we read? We should stop when we reach the end size_t total_chunks = 0; // for tiled-based parts, array of (pointers to) tileOffsets objects // to create mapping between tile coordinates and chunk table indices vector<TileOffsets*> tileOffsets(parts.size()); // for scanline-based parts, number of scanlines in each chunk vector<int> rowsizes(parts.size()); for(size_t i = 0 ; i < parts.size() ; i++) { total_chunks += parts[i]->chunkOffsets.size(); if (isTiled(parts[i]->header.type())) { tileOffsets[i] = createTileOffsets(parts[i]->header); }else{ tileOffsets[i] = NULL; // (TODO) fix this so that it doesn't need to be revised for future compression types. switch(parts[i]->header.compression()) { case DWAB_COMPRESSION : rowsizes[i] = 256; break; case PIZ_COMPRESSION : case B44_COMPRESSION : case B44A_COMPRESSION : case DWAA_COMPRESSION : rowsizes[i]=32; break; case ZIP_COMPRESSION : case PXR24_COMPRESSION : rowsizes[i]=16; break; case ZIPS_COMPRESSION : case RLE_COMPRESSION : case NO_COMPRESSION : rowsizes[i]=1; break; default : throw(IEX_NAMESPACE::ArgExc("Unknown compression method in chunk offset reconstruction")); } } } try { // // // Int64 chunk_start = position; for (size_t i = 0; i < total_chunks ; i++) { // // do we have a part number? // int partNumber = 0; if(isMultiPart(version)) { OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, partNumber); } if(partNumber<0 || partNumber>= static_cast<int>(parts.size())) { throw IEX_NAMESPACE::IoExc("part number out of range"); } Header& header = parts[partNumber]->header; // size of chunk NOT including multipart field Int64 size_of_chunk=0; if (isTiled(header.type())) { // // // int tilex,tiley,levelx,levely; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, tilex); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, tiley); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, levelx); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, levely); //std::cout << "chunk_start for " << tilex <<',' << tiley << ',' << levelx << ' ' << levely << ':' << chunk_start << std::endl; if(!tileOffsets[partNumber]) { // this shouldn't actually happen - we should have allocated a valid // tileOffsets for any part which isTiled throw IEX_NAMESPACE::IoExc("part not tiled"); } if(!tileOffsets[partNumber]->isValidTile(tilex,tiley,levelx,levely)) { throw IEX_NAMESPACE::IoExc("invalid tile coordinates"); } (*tileOffsets[partNumber])(tilex,tiley,levelx,levely)=chunk_start; // compute chunk sizes - different procedure for deep tiles and regular // ones if(header.type()==DEEPTILE) { Int64 packed_offset; Int64 packed_sample; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, packed_offset); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, packed_sample); //add 40 byte header to packed sizes (tile coordinates, packed sizes, unpacked size) size_of_chunk=packed_offset+packed_sample+40; } else { // regular image has 20 bytes of header, 4 byte chunksize; int chunksize; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, chunksize); size_of_chunk=chunksize+20; } } else { int y_coordinate; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, y_coordinate); if(y_coordinate < header.dataWindow().min.y || y_coordinate > header.dataWindow().max.y) { throw IEX_NAMESPACE::IoExc("y out of range"); } y_coordinate -= header.dataWindow().min.y; y_coordinate /= rowsizes[partNumber]; if(y_coordinate < 0 || y_coordinate >= int(parts[partNumber]->chunkOffsets.size())) { throw IEX_NAMESPACE::IoExc("chunk index out of range"); } parts[partNumber]->chunkOffsets[y_coordinate]=chunk_start; if(header.type()==DEEPSCANLINE) { Int64 packed_offset; Int64 packed_sample; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, packed_offset); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, packed_sample); size_of_chunk=packed_offset+packed_sample+28; } else { int chunksize; OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (is, chunksize); size_of_chunk=chunksize+8; } } if(isMultiPart(version)) { chunk_start+=4; } chunk_start+=size_of_chunk; is.seekg(chunk_start); } } catch (...) { // // Suppress all exceptions. This functions is // called only to reconstruct the line offset // table for incomplete files, and exceptions // are likely. // } // copy tiled part data back to chunk offsets for(size_t partNumber=0;partNumber<parts.size();partNumber++) { if(tileOffsets[partNumber]) { size_t pos=0; vector<vector<vector <Int64> > > offsets = tileOffsets[partNumber]->getOffsets(); for (size_t l = 0; l < offsets.size(); l++) for (size_t y = 0; y < offsets[l].size(); y++) for (size_t x = 0; x < offsets[l][y].size(); x++) { parts[ partNumber ]->chunkOffsets[pos] = offsets[l][y][x]; pos++; } delete tileOffsets[partNumber]; } } is.clear(); is.seekg (position); } InputPartData* MultiPartInputFile::Data::getPart(int partNumber) { if (partNumber < 0 || partNumber >= (int) parts.size()) throw IEX_NAMESPACE::ArgExc ("Part number is not in valid range."); return parts[partNumber]; } void MultiPartInputFile::Data::readChunkOffsetTables(bool reconstructChunkOffsetTable) { bool brokenPartsExist = false; for (size_t i = 0; i < parts.size(); i++) { int chunkOffsetTableSize = getChunkOffsetTableSize(parts[i]->header,false); parts[i]->chunkOffsets.resize(chunkOffsetTableSize); for (int j = 0; j < chunkOffsetTableSize; j++) OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*is, parts[i]->chunkOffsets[j]); // // Check chunk offsets, reconstruct if broken. // At first we assume the table is complete. // parts[i]->completed = true; for (int j = 0; j < chunkOffsetTableSize; j++) { if (parts[i]->chunkOffsets[j] <= 0) { brokenPartsExist = true; parts[i]->completed = false; break; } } } if (brokenPartsExist && reconstructChunkOffsetTable) chunkOffsetReconstruction(*is, parts); } int MultiPartInputFile::version() const { return _data->version; } bool MultiPartInputFile::partComplete(int part) const { return _data->parts[part]->completed; } int MultiPartInputFile::parts() const { return int(_data->_headers.size()); } OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_EXIT
null
193
CWE-787
CVE-2020-16589
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Industrial Light & Magic nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- // // class TiledInputFile // //----------------------------------------------------------------------------- #include "ImfTiledInputFile.h" #include "ImfTileDescriptionAttribute.h" #include "ImfChannelList.h" #include "ImfMisc.h" #include "ImfTiledMisc.h" #include "ImfStdIO.h" #include "ImfCompressor.h" #include "ImfXdr.h" #include "ImfConvert.h" #include "ImfVersion.h" #include "ImfTileOffsets.h" #include "ImfThreading.h" #include "ImfPartType.h" #include "ImfMultiPartInputFile.h" #include "ImfInputStreamMutex.h" #include "IlmThreadPool.h" #include "IlmThreadSemaphore.h" #include "IlmThreadMutex.h" #include "ImathVec.h" #include "Iex.h" #include <string> #include <vector> #include <algorithm> #include <assert.h> #include "ImfInputPartData.h" #include "ImfNamespace.h" OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER using IMATH_NAMESPACE::Box2i; using IMATH_NAMESPACE::V2i; using std::string; using std::vector; using std::min; using std::max; using ILMTHREAD_NAMESPACE::Mutex; using ILMTHREAD_NAMESPACE::Lock; using ILMTHREAD_NAMESPACE::Semaphore; using ILMTHREAD_NAMESPACE::Task; using ILMTHREAD_NAMESPACE::TaskGroup; using ILMTHREAD_NAMESPACE::ThreadPool; namespace { struct TInSliceInfo { PixelType typeInFrameBuffer; PixelType typeInFile; char * base; size_t xStride; size_t yStride; bool fill; bool skip; double fillValue; int xTileCoords; int yTileCoords; TInSliceInfo (PixelType typeInFrameBuffer = HALF, PixelType typeInFile = HALF, char *base = 0, size_t xStride = 0, size_t yStride = 0, bool fill = false, bool skip = false, double fillValue = 0.0, int xTileCoords = 0, int yTileCoords = 0); }; TInSliceInfo::TInSliceInfo (PixelType tifb, PixelType tifl, char *b, size_t xs, size_t ys, bool f, bool s, double fv, int xtc, int ytc) : typeInFrameBuffer (tifb), typeInFile (tifl), base (b), xStride (xs), yStride (ys), fill (f), skip (s), fillValue (fv), xTileCoords (xtc), yTileCoords (ytc) { // empty } struct TileBuffer { const char * uncompressedData; char * buffer; int dataSize; Compressor * compressor; Compressor::Format format; int dx; int dy; int lx; int ly; bool hasException; string exception; TileBuffer (Compressor * const comp); ~TileBuffer (); inline void wait () {_sem.wait();} inline void post () {_sem.post();} protected: Semaphore _sem; }; TileBuffer::TileBuffer (Compressor *comp): uncompressedData (0), buffer (0), dataSize (0), compressor (comp), format (defaultFormat (compressor)), dx (-1), dy (-1), lx (-1), ly (-1), hasException (false), exception (), _sem (1) { // empty } TileBuffer::~TileBuffer () { delete compressor; } } // namespace class MultiPartInputFile; // // struct TiledInputFile::Data stores things that will be // needed between calls to readTile() // struct TiledInputFile::Data: public Mutex { Header header; // the image header TileDescription tileDesc; // describes the tile layout int version; // file's version FrameBuffer frameBuffer; // framebuffer to write into LineOrder lineOrder; // the file's lineorder int minX; // data window's min x coord int maxX; // data window's max x coord int minY; // data window's min y coord int maxY; // data window's max x coord int numXLevels; // number of x levels int numYLevels; // number of y levels int * numXTiles; // number of x tiles at a level int * numYTiles; // number of y tiles at a level TileOffsets tileOffsets; // stores offsets in file for // each tile bool fileIsComplete; // True if no tiles are missing // in the file vector<TInSliceInfo> slices; // info about channels in file size_t bytesPerPixel; // size of an uncompressed pixel size_t maxBytesPerTileLine; // combined size of a line // over all channels int partNumber; // part number bool multiPartBackwardSupport; // if we are reading a multipart file // using OpenEXR 1.7 API int numThreads; // number of threads MultiPartInputFile* multiPartFile; // the MultiPartInputFile used to // support backward compatibility vector<TileBuffer*> tileBuffers; // each holds a single tile size_t tileBufferSize; // size of the tile buffers bool memoryMapped; // if the stream is memory mapped InputStreamMutex * _streamData; bool _deleteStream; Data (int numThreads); ~Data (); inline TileBuffer * getTileBuffer (int number); // hash function from tile indices // into our vector of tile buffers }; TiledInputFile::Data::Data (int numThreads): numXTiles (0), numYTiles (0), partNumber (-1), multiPartBackwardSupport(false), numThreads(numThreads), memoryMapped(false), _streamData(NULL), _deleteStream(false) { // // We need at least one tileBuffer, but if threading is used, // to keep n threads busy we need 2*n tileBuffers // tileBuffers.resize (max (1, 2 * numThreads)); } TiledInputFile::Data::~Data () { delete [] numXTiles; delete [] numYTiles; for (size_t i = 0; i < tileBuffers.size(); i++) delete tileBuffers[i]; if (multiPartBackwardSupport) delete multiPartFile; } TileBuffer* TiledInputFile::Data::getTileBuffer (int number) { return tileBuffers[number % tileBuffers.size()]; } namespace { void readTileData (InputStreamMutex *streamData, TiledInputFile::Data *ifd, int dx, int dy, int lx, int ly, char *&buffer, int &dataSize) { // // Read a single tile block from the file and into the array pointed // to by buffer. If the file is memory-mapped, then we change where // buffer points instead of writing into the array (hence buffer needs // to be a reference to a char *). // // // Look up the location for this tile in the Index and // seek to that position if necessary // Int64 tileOffset = ifd->tileOffsets (dx, dy, lx, ly); if (tileOffset == 0) { THROW (IEX_NAMESPACE::InputExc, "Tile (" << dx << ", " << dy << ", " << lx << ", " << ly << ") is missing."); } // // In a multi-part file, the next chunk does not need to // belong to the same part, so we have to compare the // offset here. // if (!isMultiPart(ifd->version)) { if (streamData->currentPosition != tileOffset) streamData->is->seekg (tileOffset); } else { // // In a multi-part file, the file pointer may be moved by other // parts, so we have to ask tellg() where we are. // if (streamData->is->tellg() != tileOffset) streamData->is->seekg (tileOffset); } // // Read the first few bytes of the tile (the header). // Verify that the tile coordinates and the level number // are correct. // int tileXCoord, tileYCoord, levelX, levelY; if (isMultiPart(ifd->version)) { int partNumber; Xdr::read <StreamIO> (*streamData->is, partNumber); if (partNumber != ifd->partNumber) { THROW (IEX_NAMESPACE::ArgExc, "Unexpected part number " << partNumber << ", should be " << ifd->partNumber << "."); } } OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, tileXCoord); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, tileYCoord); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, levelX); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, levelY); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, dataSize); if (tileXCoord != dx) throw IEX_NAMESPACE::InputExc ("Unexpected tile x coordinate."); if (tileYCoord != dy) throw IEX_NAMESPACE::InputExc ("Unexpected tile y coordinate."); if (levelX != lx) throw IEX_NAMESPACE::InputExc ("Unexpected tile x level number coordinate."); if (levelY != ly) throw IEX_NAMESPACE::InputExc ("Unexpected tile y level number coordinate."); if (dataSize < 0 || dataSize > static_cast<int>(ifd->tileBufferSize) ) throw IEX_NAMESPACE::InputExc ("Unexpected tile block length."); // // Read the pixel data. // if (streamData->is->isMemoryMapped ()) buffer = streamData->is->readMemoryMapped (dataSize); else streamData->is->read (buffer, dataSize); // // Keep track of which tile is the next one in // the file, so that we can avoid redundant seekg() // operations (seekg() can be fairly expensive). // streamData->currentPosition = tileOffset + 5 * Xdr::size<int>() + dataSize; } void readNextTileData (InputStreamMutex *streamData, TiledInputFile::Data *ifd, int &dx, int &dy, int &lx, int &ly, char * & buffer, int &dataSize) { // // Read the next tile block from the file // if(isMultiPart(ifd->version)) { int part; Xdr::read <StreamIO> (*streamData->is, part); if(part!=ifd->partNumber) { throw IEX_NAMESPACE::InputExc("Unexpected part number in readNextTileData"); } } // // Read the first few bytes of the tile (the header). // Xdr::read <StreamIO> (*streamData->is, dx); Xdr::read <StreamIO> (*streamData->is, dy); Xdr::read <StreamIO> (*streamData->is, lx); Xdr::read <StreamIO> (*streamData->is, ly); Xdr::read <StreamIO> (*streamData->is, dataSize); if (dataSize > (int) ifd->tileBufferSize) throw IEX_NAMESPACE::InputExc ("Unexpected tile block length."); // // Read the pixel data. // streamData->is->read (buffer, dataSize); // // Keep track of which tile is the next one in // the file, so that we can avoid redundant seekg() // operations (seekg() can be fairly expensive). // streamData->currentPosition += 5 * Xdr::size<int>() + dataSize; } // // A TileBufferTask encapsulates the task of uncompressing // a single tile and copying it into the frame buffer. // class TileBufferTask : public Task { public: TileBufferTask (TaskGroup *group, TiledInputFile::Data *ifd, TileBuffer *tileBuffer); virtual ~TileBufferTask (); virtual void execute (); private: TiledInputFile::Data * _ifd; TileBuffer * _tileBuffer; }; TileBufferTask::TileBufferTask (TaskGroup *group, TiledInputFile::Data *ifd, TileBuffer *tileBuffer) : Task (group), _ifd (ifd), _tileBuffer (tileBuffer) { // empty } TileBufferTask::~TileBufferTask () { // // Signal that the tile buffer is now free // _tileBuffer->post (); } void TileBufferTask::execute () { try { // // Calculate information about the tile // Box2i tileRange = OPENEXR_IMF_INTERNAL_NAMESPACE::dataWindowForTile ( _ifd->tileDesc, _ifd->minX, _ifd->maxX, _ifd->minY, _ifd->maxY, _tileBuffer->dx, _tileBuffer->dy, _tileBuffer->lx, _tileBuffer->ly); int numPixelsPerScanLine = tileRange.max.x - tileRange.min.x + 1; int numPixelsInTile = numPixelsPerScanLine * (tileRange.max.y - tileRange.min.y + 1); int sizeOfTile = _ifd->bytesPerPixel * numPixelsInTile; // // Uncompress the data, if necessary // if (_tileBuffer->compressor && _tileBuffer->dataSize < sizeOfTile) { _tileBuffer->format = _tileBuffer->compressor->format(); _tileBuffer->dataSize = _tileBuffer->compressor->uncompressTile (_tileBuffer->buffer, _tileBuffer->dataSize, tileRange, _tileBuffer->uncompressedData); } else { // // If the line is uncompressed, it's in XDR format, // regardless of the compressor's output format. // _tileBuffer->format = Compressor::XDR; _tileBuffer->uncompressedData = _tileBuffer->buffer; } // // Convert the tile of pixel data back from the machine-independent // representation, and store the result in the frame buffer. // const char *readPtr = _tileBuffer->uncompressedData; // points to where we // read from in the // tile block // // Iterate over the scan lines in the tile. // for (int y = tileRange.min.y; y <= tileRange.max.y; ++y) { // // Iterate over all image channels. // for (unsigned int i = 0; i < _ifd->slices.size(); ++i) { const TInSliceInfo &slice = _ifd->slices[i]; // // These offsets are used to facilitate both // absolute and tile-relative pixel coordinates. // int xOffset = slice.xTileCoords * tileRange.min.x; int yOffset = slice.yTileCoords * tileRange.min.y; // // Fill the frame buffer with pixel data. // if (slice.skip) { // // The file contains data for this channel, but // the frame buffer contains no slice for this channel. // skipChannel (readPtr, slice.typeInFile, numPixelsPerScanLine); } else { // // The frame buffer contains a slice for this channel. // char *writePtr = slice.base + (y - yOffset) * slice.yStride + (tileRange.min.x - xOffset) * slice.xStride; char *endPtr = writePtr + (numPixelsPerScanLine - 1) * slice.xStride; copyIntoFrameBuffer (readPtr, writePtr, endPtr, slice.xStride, slice.fill, slice.fillValue, _tileBuffer->format, slice.typeInFrameBuffer, slice.typeInFile); } } } } catch (std::exception &e) { if (!_tileBuffer->hasException) { _tileBuffer->exception = e.what (); _tileBuffer->hasException = true; } } catch (...) { if (!_tileBuffer->hasException) { _tileBuffer->exception = "unrecognized exception"; _tileBuffer->hasException = true; } } } TileBufferTask * newTileBufferTask (TaskGroup *group, InputStreamMutex *streamData, TiledInputFile::Data *ifd, int number, int dx, int dy, int lx, int ly) { // // Wait for a tile buffer to become available, // fill the buffer with raw data from the file, // and create a new TileBufferTask whose execute() // method will uncompress the tile and copy the // tile's pixels into the frame buffer. // TileBuffer *tileBuffer = ifd->getTileBuffer (number); try { tileBuffer->wait(); tileBuffer->dx = dx; tileBuffer->dy = dy; tileBuffer->lx = lx; tileBuffer->ly = ly; tileBuffer->uncompressedData = 0; readTileData (streamData, ifd, dx, dy, lx, ly, tileBuffer->buffer, tileBuffer->dataSize); } catch (...) { // // Reading from the file caused an exception. // Signal that the tile buffer is free, and // re-throw the exception. // tileBuffer->post(); throw; } return new TileBufferTask (group, ifd, tileBuffer); } } // namespace TiledInputFile::TiledInputFile (const char fileName[], int numThreads): _data (new Data (numThreads)) { _data->_streamData=NULL; _data->_deleteStream=true; // // This constructor is called when a user // explicitly wants to read a tiled file. // IStream* is = 0; try { is = new StdIFStream (fileName); readMagicNumberAndVersionField(*is, _data->version); // // Backward compatibility to read multpart file. // if (isMultiPart(_data->version)) { compatibilityInitialize(*is); return; } _data->_streamData = new InputStreamMutex(); _data->_streamData->is = is; _data->header.readFrom (*_data->_streamData->is, _data->version); initialize(); //read tile offsets - we are not multipart or deep _data->tileOffsets.readFrom (*(_data->_streamData->is), _data->fileIsComplete,false,false); _data->_streamData->currentPosition = _data->_streamData->is->tellg(); } catch (IEX_NAMESPACE::BaseExc &e) { if (_data->_streamData != 0) { if (_data->_streamData->is != 0) { delete _data->_streamData->is; _data->_streamData->is = is = 0; } delete _data->_streamData; } if (is != 0) delete is; REPLACE_EXC (e, "Cannot open image file " "\"" << fileName << "\". " << e.what()); throw; } catch (...) { if ( _data->_streamData != 0) { if ( _data->_streamData->is != 0) { delete _data->_streamData->is; _data->_streamData->is = is = 0; } delete _data->_streamData; } if (is != 0) delete is; throw; } } TiledInputFile::TiledInputFile (OPENEXR_IMF_INTERNAL_NAMESPACE::IStream &is, int numThreads): _data (new Data (numThreads)) { _data->_deleteStream=false; // // This constructor is called when a user // explicitly wants to read a tiled file. // bool streamDataCreated = false; try { readMagicNumberAndVersionField(is, _data->version); // // Backward compatibility to read multpart file. // if (isMultiPart(_data->version)) { compatibilityInitialize(is); return; } streamDataCreated = true; _data->_streamData = new InputStreamMutex(); _data->_streamData->is = &is; _data->header.readFrom (*_data->_streamData->is, _data->version); initialize(); // file is guaranteed to be single part, regular image _data->tileOffsets.readFrom (*(_data->_streamData->is), _data->fileIsComplete,false,false); _data->memoryMapped = _data->_streamData->is->isMemoryMapped(); _data->_streamData->currentPosition = _data->_streamData->is->tellg(); } catch (IEX_NAMESPACE::BaseExc &e) { if (streamDataCreated) delete _data->_streamData; delete _data; REPLACE_EXC (e, "Cannot open image file " "\"" << is.fileName() << "\". " << e.what()); throw; } catch (...) { if (streamDataCreated) delete _data->_streamData; delete _data; throw; } } TiledInputFile::TiledInputFile (const Header &header, OPENEXR_IMF_INTERNAL_NAMESPACE::IStream *is, int version, int numThreads) : _data (new Data (numThreads)) { _data->_deleteStream=false; _data->_streamData = new InputStreamMutex(); // // This constructor called by class Imf::InputFile // when a user wants to just read an image file, and // doesn't care or know if the file is tiled. // No need to have backward compatibility here, because // we have somehow got the header. // _data->_streamData->is = is; _data->header = header; _data->version = version; initialize(); _data->tileOffsets.readFrom (*(_data->_streamData->is),_data->fileIsComplete,false,false); _data->memoryMapped = is->isMemoryMapped(); _data->_streamData->currentPosition = _data->_streamData->is->tellg(); } TiledInputFile::TiledInputFile (InputPartData* part) { _data = new Data (part->numThreads); _data->_deleteStream=false; multiPartInitialize(part); } void TiledInputFile::compatibilityInitialize(OPENEXR_IMF_INTERNAL_NAMESPACE::IStream& is) { is.seekg(0); // // Construct a MultiPartInputFile, initialize TiledInputFile // with the part 0 data. // (TODO) maybe change the third parameter of the constructor of MultiPartInputFile later. // _data->multiPartBackwardSupport = true; _data->multiPartFile = new MultiPartInputFile(is, _data->numThreads); InputPartData* part = _data->multiPartFile->getPart(0); multiPartInitialize(part); } void TiledInputFile::multiPartInitialize(InputPartData* part) { if (part->header.type() != TILEDIMAGE) throw IEX_NAMESPACE::ArgExc("Can't build a TiledInputFile from a type-mismatched part."); _data->_streamData = part->mutex; _data->header = part->header; _data->version = part->version; _data->partNumber = part->partNumber; _data->memoryMapped = _data->_streamData->is->isMemoryMapped(); initialize(); _data->tileOffsets.readFrom(part->chunkOffsets,_data->fileIsComplete); _data->_streamData->currentPosition = _data->_streamData->is->tellg(); } void TiledInputFile::initialize () { // fix bad types in header (arises when a tool built against an older version of // OpenEXR converts a scanline image to tiled) // only applies when file is a single part, regular image, tiled file // if(!isMultiPart(_data->version) && !isNonImage(_data->version) && isTiled(_data->version) && _data->header.hasType() ) { _data->header.setType(TILEDIMAGE); } if (_data->partNumber == -1) { if (!isTiled (_data->version)) throw IEX_NAMESPACE::ArgExc ("Expected a tiled file but the file is not tiled."); } else { if(_data->header.hasType() && _data->header.type()!=TILEDIMAGE) { throw IEX_NAMESPACE::ArgExc ("TiledInputFile used for non-tiledimage part."); } } _data->header.sanityCheck (true); _data->tileDesc = _data->header.tileDescription(); _data->lineOrder = _data->header.lineOrder(); // // Save the dataWindow information // const Box2i &dataWindow = _data->header.dataWindow(); _data->minX = dataWindow.min.x; _data->maxX = dataWindow.max.x; _data->minY = dataWindow.min.y; _data->maxY = dataWindow.max.y; // // Precompute level and tile information to speed up utility functions // precalculateTileInfo (_data->tileDesc, _data->minX, _data->maxX, _data->minY, _data->maxY, _data->numXTiles, _data->numYTiles, _data->numXLevels, _data->numYLevels); _data->bytesPerPixel = calculateBytesPerPixel (_data->header); _data->maxBytesPerTileLine = _data->bytesPerPixel * _data->tileDesc.xSize; _data->tileBufferSize = _data->maxBytesPerTileLine * _data->tileDesc.ySize; // // Create all the TileBuffers and allocate their internal buffers // for (size_t i = 0; i < _data->tileBuffers.size(); i++) { _data->tileBuffers[i] = new TileBuffer (newTileCompressor (_data->header.compression(), _data->maxBytesPerTileLine, _data->tileDesc.ySize, _data->header)); if (!_data->_streamData->is->isMemoryMapped ()) _data->tileBuffers[i]->buffer = new char [_data->tileBufferSize]; } _data->tileOffsets = TileOffsets (_data->tileDesc.mode, _data->numXLevels, _data->numYLevels, _data->numXTiles, _data->numYTiles); } TiledInputFile::~TiledInputFile () { if (!_data->memoryMapped) for (size_t i = 0; i < _data->tileBuffers.size(); i++) delete [] _data->tileBuffers[i]->buffer; if (_data->_deleteStream) delete _data->_streamData->is; if (_data->partNumber == -1) delete _data->_streamData; delete _data; } const char * TiledInputFile::fileName () const { return _data->_streamData->is->fileName(); } const Header & TiledInputFile::header () const { return _data->header; } int TiledInputFile::version () const { return _data->version; } void TiledInputFile::setFrameBuffer (const FrameBuffer &frameBuffer) { Lock lock (*_data->_streamData); // // Set the frame buffer // // // Check if the new frame buffer descriptor is // compatible with the image file header. // const ChannelList &channels = _data->header.channels(); for (FrameBuffer::ConstIterator j = frameBuffer.begin(); j != frameBuffer.end(); ++j) { ChannelList::ConstIterator i = channels.find (j.name()); if (i == channels.end()) continue; if (i.channel().xSampling != j.slice().xSampling || i.channel().ySampling != j.slice().ySampling) THROW (IEX_NAMESPACE::ArgExc, "X and/or y subsampling factors " "of \"" << i.name() << "\" channel " "of input file \"" << fileName() << "\" are " "not compatible with the frame buffer's " "subsampling factors."); } // // Initialize the slice table for readPixels(). // vector<TInSliceInfo> slices; ChannelList::ConstIterator i = channels.begin(); for (FrameBuffer::ConstIterator j = frameBuffer.begin(); j != frameBuffer.end(); ++j) { while (i != channels.end() && strcmp (i.name(), j.name()) < 0) { // // Channel i is present in the file but not // in the frame buffer; data for channel i // will be skipped during readPixels(). // slices.push_back (TInSliceInfo (i.channel().type, i.channel().type, 0, // base 0, // xStride 0, // yStride false, // fill true, // skip 0.0)); // fillValue ++i; } bool fill = false; if (i == channels.end() || strcmp (i.name(), j.name()) > 0) { // // Channel i is present in the frame buffer, but not in the file. // In the frame buffer, slice j will be filled with a default value. // fill = true; } slices.push_back (TInSliceInfo (j.slice().type, fill? j.slice().type: i.channel().type, j.slice().base, j.slice().xStride, j.slice().yStride, fill, false, // skip j.slice().fillValue, (j.slice().xTileCoords)? 1: 0, (j.slice().yTileCoords)? 1: 0)); if (i != channels.end() && !fill) ++i; } while (i != channels.end()) { // // Channel i is present in the file but not // in the frame buffer; data for channel i // will be skipped during readPixels(). // slices.push_back (TInSliceInfo (i.channel().type, i.channel().type, 0, // base 0, // xStride 0, // yStride false, // fill true, // skip 0.0)); // fillValue ++i; } // // Store the new frame buffer. // _data->frameBuffer = frameBuffer; _data->slices = slices; } const FrameBuffer & TiledInputFile::frameBuffer () const { Lock lock (*_data->_streamData); return _data->frameBuffer; } bool TiledInputFile::isComplete () const { return _data->fileIsComplete; } void TiledInputFile::readTiles (int dx1, int dx2, int dy1, int dy2, int lx, int ly) { // // Read a range of tiles from the file into the framebuffer // try { Lock lock (*_data->_streamData); if (_data->slices.size() == 0) throw IEX_NAMESPACE::ArgExc ("No frame buffer specified " "as pixel data destination."); if (!isValidLevel (lx, ly)) THROW (IEX_NAMESPACE::ArgExc, "Level coordinate " "(" << lx << ", " << ly << ") " "is invalid."); // // Determine the first and last tile coordinates in both dimensions. // We always attempt to read the range of tiles in the order that // they are stored in the file. // if (dx1 > dx2) std::swap (dx1, dx2); if (dy1 > dy2) std::swap (dy1, dy2); int dyStart = dy1; int dyStop = dy2 + 1; int dY = 1; if (_data->lineOrder == DECREASING_Y) { dyStart = dy2; dyStop = dy1 - 1; dY = -1; } // // Create a task group for all tile buffer tasks. When the // task group goes out of scope, the destructor waits until // all tasks are complete. // { TaskGroup taskGroup; int tileNumber = 0; for (int dy = dyStart; dy != dyStop; dy += dY) { for (int dx = dx1; dx <= dx2; dx++) { if (!isValidTile (dx, dy, lx, ly)) THROW (IEX_NAMESPACE::ArgExc, "Tile (" << dx << ", " << dy << ", " << lx << "," << ly << ") is not a valid tile."); ThreadPool::addGlobalTask (newTileBufferTask (&taskGroup, _data->_streamData, _data, tileNumber++, dx, dy, lx, ly)); } } // // finish all tasks // } // // Exeption handling: // // TileBufferTask::execute() may have encountered exceptions, but // those exceptions occurred in another thread, not in the thread // that is executing this call to TiledInputFile::readTiles(). // TileBufferTask::execute() has caught all exceptions and stored // the exceptions' what() strings in the tile buffers. // Now we check if any tile buffer contains a stored exception; if // this is the case then we re-throw the exception in this thread. // (It is possible that multiple tile buffers contain stored // exceptions. We re-throw the first exception we find and // ignore all others.) // const string *exception = 0; for (size_t i = 0; i < _data->tileBuffers.size(); ++i) { TileBuffer *tileBuffer = _data->tileBuffers[i]; if (tileBuffer->hasException && !exception) exception = &tileBuffer->exception; tileBuffer->hasException = false; } if (exception) throw IEX_NAMESPACE::IoExc (*exception); } catch (IEX_NAMESPACE::BaseExc &e) { REPLACE_EXC (e, "Error reading pixel data from image " "file \"" << fileName() << "\". " << e.what()); throw; } } void TiledInputFile::readTiles (int dx1, int dx2, int dy1, int dy2, int l) { readTiles (dx1, dx2, dy1, dy2, l, l); } void TiledInputFile::readTile (int dx, int dy, int lx, int ly) { readTiles (dx, dx, dy, dy, lx, ly); } void TiledInputFile::readTile (int dx, int dy, int l) { readTile (dx, dy, l, l); } void TiledInputFile::rawTileData (int &dx, int &dy, int &lx, int &ly, const char *&pixelData, int &pixelDataSize) { try { Lock lock (*_data->_streamData); if (!isValidTile (dx, dy, lx, ly)) throw IEX_NAMESPACE::ArgExc ("Tried to read a tile outside " "the image file's data window."); TileBuffer *tileBuffer = _data->getTileBuffer (0); // // if file is a multipart file, we have to seek to the required tile // since we don't know where the file pointer is // int old_dx=dx; int old_dy=dy; int old_lx=lx; int old_ly=ly; if(isMultiPart(version())) { _data->_streamData->is->seekg(_data->tileOffsets(dx,dy,lx,ly)); } readNextTileData (_data->_streamData, _data, dx, dy, lx, ly, tileBuffer->buffer, pixelDataSize); if(isMultiPart(version())) { if (old_dx!=dx || old_dy !=dy || old_lx!=lx || old_ly!=ly) { throw IEX_NAMESPACE::ArgExc ("rawTileData read the wrong tile"); } } pixelData = tileBuffer->buffer; } catch (IEX_NAMESPACE::BaseExc &e) { REPLACE_EXC (e, "Error reading pixel data from image " "file \"" << fileName() << "\". " << e.what()); throw; } } unsigned int TiledInputFile::tileXSize () const { return _data->tileDesc.xSize; } unsigned int TiledInputFile::tileYSize () const { return _data->tileDesc.ySize; } LevelMode TiledInputFile::levelMode () const { return _data->tileDesc.mode; } LevelRoundingMode TiledInputFile::levelRoundingMode () const { return _data->tileDesc.roundingMode; } int TiledInputFile::numLevels () const { if (levelMode() == RIPMAP_LEVELS) THROW (IEX_NAMESPACE::LogicExc, "Error calling numLevels() on image " "file \"" << fileName() << "\" " "(numLevels() is not defined for files " "with RIPMAP level mode)."); return _data->numXLevels; } int TiledInputFile::numXLevels () const { return _data->numXLevels; } int TiledInputFile::numYLevels () const { return _data->numYLevels; } bool TiledInputFile::isValidLevel (int lx, int ly) const { if (lx < 0 || ly < 0) return false; if (levelMode() == MIPMAP_LEVELS && lx != ly) return false; if (lx >= numXLevels() || ly >= numYLevels()) return false; return true; } int TiledInputFile::levelWidth (int lx) const { try { return levelSize (_data->minX, _data->maxX, lx, _data->tileDesc.roundingMode); } catch (IEX_NAMESPACE::BaseExc &e) { REPLACE_EXC (e, "Error calling levelWidth() on image " "file \"" << fileName() << "\". " << e.what()); throw; } } int TiledInputFile::levelHeight (int ly) const { try { return levelSize (_data->minY, _data->maxY, ly, _data->tileDesc.roundingMode); } catch (IEX_NAMESPACE::BaseExc &e) { REPLACE_EXC (e, "Error calling levelHeight() on image " "file \"" << fileName() << "\". " << e.what()); throw; } } int TiledInputFile::numXTiles (int lx) const { if (lx < 0 || lx >= _data->numXLevels) { THROW (IEX_NAMESPACE::ArgExc, "Error calling numXTiles() on image " "file \"" << _data->_streamData->is->fileName() << "\" " "(Argument is not in valid range)."); } return _data->numXTiles[lx]; } int TiledInputFile::numYTiles (int ly) const { if (ly < 0 || ly >= _data->numYLevels) { THROW (IEX_NAMESPACE::ArgExc, "Error calling numYTiles() on image " "file \"" << _data->_streamData->is->fileName() << "\" " "(Argument is not in valid range)."); } return _data->numYTiles[ly]; } Box2i TiledInputFile::dataWindowForLevel (int l) const { return dataWindowForLevel (l, l); } Box2i TiledInputFile::dataWindowForLevel (int lx, int ly) const { try { return OPENEXR_IMF_INTERNAL_NAMESPACE::dataWindowForLevel ( _data->tileDesc, _data->minX, _data->maxX, _data->minY, _data->maxY, lx, ly); } catch (IEX_NAMESPACE::BaseExc &e) { REPLACE_EXC (e, "Error calling dataWindowForLevel() on image " "file \"" << fileName() << "\". " << e.what()); throw; } } Box2i TiledInputFile::dataWindowForTile (int dx, int dy, int l) const { return dataWindowForTile (dx, dy, l, l); } Box2i TiledInputFile::dataWindowForTile (int dx, int dy, int lx, int ly) const { try { if (!isValidTile (dx, dy, lx, ly)) throw IEX_NAMESPACE::ArgExc ("Arguments not in valid range."); return OPENEXR_IMF_INTERNAL_NAMESPACE::dataWindowForTile ( _data->tileDesc, _data->minX, _data->maxX, _data->minY, _data->maxY, dx, dy, lx, ly); } catch (IEX_NAMESPACE::BaseExc &e) { REPLACE_EXC (e, "Error calling dataWindowForTile() on image " "file \"" << fileName() << "\". " << e.what()); throw; } } bool TiledInputFile::isValidTile (int dx, int dy, int lx, int ly) const { return ((lx < _data->numXLevels && lx >= 0) && (ly < _data->numYLevels && ly >= 0) && (dx < _data->numXTiles[lx] && dx >= 0) && (dy < _data->numYTiles[ly] && dy >= 0)); } void TiledInputFile::tileOrder(int dx[], int dy[], int lx[], int ly[]) const { return _data->tileOffsets.getTileOrder(dx,dy,lx,ly); } OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_EXIT
null
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Industrial Light & Magic nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- // // class TiledInputFile // //----------------------------------------------------------------------------- #include "ImfTiledInputFile.h" #include "ImfTileDescriptionAttribute.h" #include "ImfChannelList.h" #include "ImfMisc.h" #include "ImfTiledMisc.h" #include "ImfStdIO.h" #include "ImfCompressor.h" #include "ImfXdr.h" #include "ImfConvert.h" #include "ImfVersion.h" #include "ImfTileOffsets.h" #include "ImfThreading.h" #include "ImfPartType.h" #include "ImfMultiPartInputFile.h" #include "ImfInputStreamMutex.h" #include "IlmThreadPool.h" #include "IlmThreadSemaphore.h" #include "IlmThreadMutex.h" #include "ImathVec.h" #include "Iex.h" #include <string> #include <vector> #include <algorithm> #include <assert.h> #include "ImfInputPartData.h" #include "ImfNamespace.h" OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER using IMATH_NAMESPACE::Box2i; using IMATH_NAMESPACE::V2i; using std::string; using std::vector; using std::min; using std::max; using ILMTHREAD_NAMESPACE::Mutex; using ILMTHREAD_NAMESPACE::Lock; using ILMTHREAD_NAMESPACE::Semaphore; using ILMTHREAD_NAMESPACE::Task; using ILMTHREAD_NAMESPACE::TaskGroup; using ILMTHREAD_NAMESPACE::ThreadPool; namespace { struct TInSliceInfo { PixelType typeInFrameBuffer; PixelType typeInFile; char * base; size_t xStride; size_t yStride; bool fill; bool skip; double fillValue; int xTileCoords; int yTileCoords; TInSliceInfo (PixelType typeInFrameBuffer = HALF, PixelType typeInFile = HALF, char *base = 0, size_t xStride = 0, size_t yStride = 0, bool fill = false, bool skip = false, double fillValue = 0.0, int xTileCoords = 0, int yTileCoords = 0); }; TInSliceInfo::TInSliceInfo (PixelType tifb, PixelType tifl, char *b, size_t xs, size_t ys, bool f, bool s, double fv, int xtc, int ytc) : typeInFrameBuffer (tifb), typeInFile (tifl), base (b), xStride (xs), yStride (ys), fill (f), skip (s), fillValue (fv), xTileCoords (xtc), yTileCoords (ytc) { // empty } struct TileBuffer { const char * uncompressedData; char * buffer; int dataSize; Compressor * compressor; Compressor::Format format; int dx; int dy; int lx; int ly; bool hasException; string exception; TileBuffer (Compressor * const comp); ~TileBuffer (); inline void wait () {_sem.wait();} inline void post () {_sem.post();} protected: Semaphore _sem; }; TileBuffer::TileBuffer (Compressor *comp): uncompressedData (0), buffer (0), dataSize (0), compressor (comp), format (defaultFormat (compressor)), dx (-1), dy (-1), lx (-1), ly (-1), hasException (false), exception (), _sem (1) { // empty } TileBuffer::~TileBuffer () { delete compressor; } } // namespace class MultiPartInputFile; // // struct TiledInputFile::Data stores things that will be // needed between calls to readTile() // struct TiledInputFile::Data: public Mutex { Header header; // the image header TileDescription tileDesc; // describes the tile layout int version; // file's version FrameBuffer frameBuffer; // framebuffer to write into LineOrder lineOrder; // the file's lineorder int minX; // data window's min x coord int maxX; // data window's max x coord int minY; // data window's min y coord int maxY; // data window's max x coord int numXLevels; // number of x levels int numYLevels; // number of y levels int * numXTiles; // number of x tiles at a level int * numYTiles; // number of y tiles at a level TileOffsets tileOffsets; // stores offsets in file for // each tile bool fileIsComplete; // True if no tiles are missing // in the file vector<TInSliceInfo> slices; // info about channels in file size_t bytesPerPixel; // size of an uncompressed pixel size_t maxBytesPerTileLine; // combined size of a line // over all channels int partNumber; // part number bool multiPartBackwardSupport; // if we are reading a multipart file // using OpenEXR 1.7 API int numThreads; // number of threads MultiPartInputFile* multiPartFile; // the MultiPartInputFile used to // support backward compatibility vector<TileBuffer*> tileBuffers; // each holds a single tile size_t tileBufferSize; // size of the tile buffers bool memoryMapped; // if the stream is memory mapped InputStreamMutex * _streamData; bool _deleteStream; Data (int numThreads); ~Data (); inline TileBuffer * getTileBuffer (int number); // hash function from tile indices // into our vector of tile buffers }; TiledInputFile::Data::Data (int numThreads): numXTiles (0), numYTiles (0), partNumber (-1), multiPartBackwardSupport(false), numThreads(numThreads), memoryMapped(false), _streamData(NULL), _deleteStream(false) { // // We need at least one tileBuffer, but if threading is used, // to keep n threads busy we need 2*n tileBuffers // tileBuffers.resize (max (1, 2 * numThreads)); } TiledInputFile::Data::~Data () { delete [] numXTiles; delete [] numYTiles; for (size_t i = 0; i < tileBuffers.size(); i++) delete tileBuffers[i]; if (multiPartBackwardSupport) delete multiPartFile; } TileBuffer* TiledInputFile::Data::getTileBuffer (int number) { return tileBuffers[number % tileBuffers.size()]; } namespace { void readTileData (InputStreamMutex *streamData, TiledInputFile::Data *ifd, int dx, int dy, int lx, int ly, char *&buffer, int &dataSize) { // // Read a single tile block from the file and into the array pointed // to by buffer. If the file is memory-mapped, then we change where // buffer points instead of writing into the array (hence buffer needs // to be a reference to a char *). // // // Look up the location for this tile in the Index and // seek to that position if necessary // Int64 tileOffset = ifd->tileOffsets (dx, dy, lx, ly); if (tileOffset == 0) { THROW (IEX_NAMESPACE::InputExc, "Tile (" << dx << ", " << dy << ", " << lx << ", " << ly << ") is missing."); } // // In a multi-part file, the next chunk does not need to // belong to the same part, so we have to compare the // offset here. // if (!isMultiPart(ifd->version)) { if (streamData->currentPosition != tileOffset) streamData->is->seekg (tileOffset); } else { // // In a multi-part file, the file pointer may be moved by other // parts, so we have to ask tellg() where we are. // if (streamData->is->tellg() != tileOffset) streamData->is->seekg (tileOffset); } // // Read the first few bytes of the tile (the header). // Verify that the tile coordinates and the level number // are correct. // int tileXCoord, tileYCoord, levelX, levelY; if (isMultiPart(ifd->version)) { int partNumber; Xdr::read <StreamIO> (*streamData->is, partNumber); if (partNumber != ifd->partNumber) { THROW (IEX_NAMESPACE::ArgExc, "Unexpected part number " << partNumber << ", should be " << ifd->partNumber << "."); } } OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, tileXCoord); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, tileYCoord); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, levelX); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, levelY); OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, dataSize); if (tileXCoord != dx) throw IEX_NAMESPACE::InputExc ("Unexpected tile x coordinate."); if (tileYCoord != dy) throw IEX_NAMESPACE::InputExc ("Unexpected tile y coordinate."); if (levelX != lx) throw IEX_NAMESPACE::InputExc ("Unexpected tile x level number coordinate."); if (levelY != ly) throw IEX_NAMESPACE::InputExc ("Unexpected tile y level number coordinate."); if (dataSize < 0 || dataSize > static_cast<int>(ifd->tileBufferSize) ) throw IEX_NAMESPACE::InputExc ("Unexpected tile block length."); // // Read the pixel data. // if (streamData->is->isMemoryMapped ()) buffer = streamData->is->readMemoryMapped (dataSize); else streamData->is->read (buffer, dataSize); // // Keep track of which tile is the next one in // the file, so that we can avoid redundant seekg() // operations (seekg() can be fairly expensive). // streamData->currentPosition = tileOffset + 5 * Xdr::size<int>() + dataSize; } void readNextTileData (InputStreamMutex *streamData, TiledInputFile::Data *ifd, int &dx, int &dy, int &lx, int &ly, char * & buffer, int &dataSize) { // // Read the next tile block from the file // if(isMultiPart(ifd->version)) { int part; Xdr::read <StreamIO> (*streamData->is, part); if(part!=ifd->partNumber) { throw IEX_NAMESPACE::InputExc("Unexpected part number in readNextTileData"); } } // // Read the first few bytes of the tile (the header). // Xdr::read <StreamIO> (*streamData->is, dx); Xdr::read <StreamIO> (*streamData->is, dy); Xdr::read <StreamIO> (*streamData->is, lx); Xdr::read <StreamIO> (*streamData->is, ly); Xdr::read <StreamIO> (*streamData->is, dataSize); if (dataSize > (int) ifd->tileBufferSize) throw IEX_NAMESPACE::InputExc ("Unexpected tile block length."); // // Read the pixel data. // streamData->is->read (buffer, dataSize); // // Keep track of which tile is the next one in // the file, so that we can avoid redundant seekg() // operations (seekg() can be fairly expensive). // streamData->currentPosition += 5 * Xdr::size<int>() + dataSize; } // // A TileBufferTask encapsulates the task of uncompressing // a single tile and copying it into the frame buffer. // class TileBufferTask : public Task { public: TileBufferTask (TaskGroup *group, TiledInputFile::Data *ifd, TileBuffer *tileBuffer); virtual ~TileBufferTask (); virtual void execute (); private: TiledInputFile::Data * _ifd; TileBuffer * _tileBuffer; }; TileBufferTask::TileBufferTask (TaskGroup *group, TiledInputFile::Data *ifd, TileBuffer *tileBuffer) : Task (group), _ifd (ifd), _tileBuffer (tileBuffer) { // empty } TileBufferTask::~TileBufferTask () { // // Signal that the tile buffer is now free // _tileBuffer->post (); } void TileBufferTask::execute () { try { // // Calculate information about the tile // Box2i tileRange = OPENEXR_IMF_INTERNAL_NAMESPACE::dataWindowForTile ( _ifd->tileDesc, _ifd->minX, _ifd->maxX, _ifd->minY, _ifd->maxY, _tileBuffer->dx, _tileBuffer->dy, _tileBuffer->lx, _tileBuffer->ly); int numPixelsPerScanLine = tileRange.max.x - tileRange.min.x + 1; int numPixelsInTile = numPixelsPerScanLine * (tileRange.max.y - tileRange.min.y + 1); int sizeOfTile = _ifd->bytesPerPixel * numPixelsInTile; // // Uncompress the data, if necessary // if (_tileBuffer->compressor && _tileBuffer->dataSize < sizeOfTile) { _tileBuffer->format = _tileBuffer->compressor->format(); _tileBuffer->dataSize = _tileBuffer->compressor->uncompressTile (_tileBuffer->buffer, _tileBuffer->dataSize, tileRange, _tileBuffer->uncompressedData); } else { // // If the line is uncompressed, it's in XDR format, // regardless of the compressor's output format. // _tileBuffer->format = Compressor::XDR; _tileBuffer->uncompressedData = _tileBuffer->buffer; } // // Convert the tile of pixel data back from the machine-independent // representation, and store the result in the frame buffer. // const char *readPtr = _tileBuffer->uncompressedData; // points to where we // read from in the // tile block // // Iterate over the scan lines in the tile. // for (int y = tileRange.min.y; y <= tileRange.max.y; ++y) { // // Iterate over all image channels. // for (unsigned int i = 0; i < _ifd->slices.size(); ++i) { const TInSliceInfo &slice = _ifd->slices[i]; // // These offsets are used to facilitate both // absolute and tile-relative pixel coordinates. // int xOffset = slice.xTileCoords * tileRange.min.x; int yOffset = slice.yTileCoords * tileRange.min.y; // // Fill the frame buffer with pixel data. // if (slice.skip) { // // The file contains data for this channel, but // the frame buffer contains no slice for this channel. // skipChannel (readPtr, slice.typeInFile, numPixelsPerScanLine); } else { // // The frame buffer contains a slice for this channel. // char *writePtr = slice.base + (y - yOffset) * slice.yStride + (tileRange.min.x - xOffset) * slice.xStride; char *endPtr = writePtr + (numPixelsPerScanLine - 1) * slice.xStride; copyIntoFrameBuffer (readPtr, writePtr, endPtr, slice.xStride, slice.fill, slice.fillValue, _tileBuffer->format, slice.typeInFrameBuffer, slice.typeInFile); } } } } catch (std::exception &e) { if (!_tileBuffer->hasException) { _tileBuffer->exception = e.what (); _tileBuffer->hasException = true; } } catch (...) { if (!_tileBuffer->hasException) { _tileBuffer->exception = "unrecognized exception"; _tileBuffer->hasException = true; } } } TileBufferTask * newTileBufferTask (TaskGroup *group, InputStreamMutex *streamData, TiledInputFile::Data *ifd, int number, int dx, int dy, int lx, int ly) { // // Wait for a tile buffer to become available, // fill the buffer with raw data from the file, // and create a new TileBufferTask whose execute() // method will uncompress the tile and copy the // tile's pixels into the frame buffer. // TileBuffer *tileBuffer = ifd->getTileBuffer (number); try { tileBuffer->wait(); tileBuffer->dx = dx; tileBuffer->dy = dy; tileBuffer->lx = lx; tileBuffer->ly = ly; tileBuffer->uncompressedData = 0; readTileData (streamData, ifd, dx, dy, lx, ly, tileBuffer->buffer, tileBuffer->dataSize); } catch (...) { // // Reading from the file caused an exception. // Signal that the tile buffer is free, and // re-throw the exception. // tileBuffer->post(); throw; } return new TileBufferTask (group, ifd, tileBuffer); } } // namespace TiledInputFile::TiledInputFile (const char fileName[], int numThreads): _data (new Data (numThreads)) { _data->_streamData=NULL; _data->_deleteStream=true; // // This constructor is called when a user // explicitly wants to read a tiled file. // IStream* is = 0; try { is = new StdIFStream (fileName); readMagicNumberAndVersionField(*is, _data->version); // // Backward compatibility to read multpart file. // if (isMultiPart(_data->version)) { compatibilityInitialize(*is); return; } _data->_streamData = new InputStreamMutex(); _data->_streamData->is = is; _data->header.readFrom (*_data->_streamData->is, _data->version); initialize(); //read tile offsets - we are not multipart or deep _data->tileOffsets.readFrom (*(_data->_streamData->is), _data->fileIsComplete,false,false); _data->_streamData->currentPosition = _data->_streamData->is->tellg(); } catch (IEX_NAMESPACE::BaseExc &e) { if (_data->_streamData != 0) { if (_data->_streamData->is != 0) { delete _data->_streamData->is; _data->_streamData->is = is = 0; } delete _data->_streamData; } if (is != 0) delete is; REPLACE_EXC (e, "Cannot open image file " "\"" << fileName << "\". " << e.what()); throw; } catch (...) { if ( _data->_streamData != 0) { if ( _data->_streamData->is != 0) { delete _data->_streamData->is; _data->_streamData->is = is = 0; } delete _data->_streamData; } if (is != 0) delete is; throw; } } TiledInputFile::TiledInputFile (OPENEXR_IMF_INTERNAL_NAMESPACE::IStream &is, int numThreads): _data (new Data (numThreads)) { _data->_deleteStream=false; // // This constructor is called when a user // explicitly wants to read a tiled file. // bool streamDataCreated = false; try { readMagicNumberAndVersionField(is, _data->version); // // Backward compatibility to read multpart file. // if (isMultiPart(_data->version)) { compatibilityInitialize(is); return; } streamDataCreated = true; _data->_streamData = new InputStreamMutex(); _data->_streamData->is = &is; _data->header.readFrom (*_data->_streamData->is, _data->version); initialize(); // file is guaranteed to be single part, regular image _data->tileOffsets.readFrom (*(_data->_streamData->is), _data->fileIsComplete,false,false); _data->memoryMapped = _data->_streamData->is->isMemoryMapped(); _data->_streamData->currentPosition = _data->_streamData->is->tellg(); } catch (IEX_NAMESPACE::BaseExc &e) { if (streamDataCreated) delete _data->_streamData; delete _data; REPLACE_EXC (e, "Cannot open image file " "\"" << is.fileName() << "\". " << e.what()); throw; } catch (...) { if (streamDataCreated) delete _data->_streamData; delete _data; throw; } } TiledInputFile::TiledInputFile (const Header &header, OPENEXR_IMF_INTERNAL_NAMESPACE::IStream *is, int version, int numThreads) : _data (new Data (numThreads)) { _data->_deleteStream=false; _data->_streamData = new InputStreamMutex(); // // This constructor called by class Imf::InputFile // when a user wants to just read an image file, and // doesn't care or know if the file is tiled. // No need to have backward compatibility here, because // we have somehow got the header. // _data->_streamData->is = is; _data->header = header; _data->version = version; initialize(); _data->tileOffsets.readFrom (*(_data->_streamData->is),_data->fileIsComplete,false,false); _data->memoryMapped = is->isMemoryMapped(); _data->_streamData->currentPosition = _data->_streamData->is->tellg(); } TiledInputFile::TiledInputFile (InputPartData* part) { _data = new Data (part->numThreads); _data->_deleteStream=false; multiPartInitialize(part); } void TiledInputFile::compatibilityInitialize(OPENEXR_IMF_INTERNAL_NAMESPACE::IStream& is) { is.seekg(0); // // Construct a MultiPartInputFile, initialize TiledInputFile // with the part 0 data. // (TODO) maybe change the third parameter of the constructor of MultiPartInputFile later. // _data->multiPartBackwardSupport = true; _data->multiPartFile = new MultiPartInputFile(is, _data->numThreads); InputPartData* part = _data->multiPartFile->getPart(0); multiPartInitialize(part); } void TiledInputFile::multiPartInitialize(InputPartData* part) { if (part->header.type() != TILEDIMAGE) throw IEX_NAMESPACE::ArgExc("Can't build a TiledInputFile from a type-mismatched part."); _data->_streamData = part->mutex; _data->header = part->header; _data->version = part->version; _data->partNumber = part->partNumber; _data->memoryMapped = _data->_streamData->is->isMemoryMapped(); initialize(); _data->tileOffsets.readFrom(part->chunkOffsets,_data->fileIsComplete); _data->_streamData->currentPosition = _data->_streamData->is->tellg(); } void TiledInputFile::initialize () { // fix bad types in header (arises when a tool built against an older version of // OpenEXR converts a scanline image to tiled) // only applies when file is a single part, regular image, tiled file // if(!isMultiPart(_data->version) && !isNonImage(_data->version) && isTiled(_data->version) && _data->header.hasType() ) { _data->header.setType(TILEDIMAGE); } if (_data->partNumber == -1) { if (!isTiled (_data->version)) throw IEX_NAMESPACE::ArgExc ("Expected a tiled file but the file is not tiled."); } else { if(_data->header.hasType() && _data->header.type()!=TILEDIMAGE) { throw IEX_NAMESPACE::ArgExc ("TiledInputFile used for non-tiledimage part."); } } _data->header.sanityCheck (true); _data->tileDesc = _data->header.tileDescription(); _data->lineOrder = _data->header.lineOrder(); // // Save the dataWindow information // const Box2i &dataWindow = _data->header.dataWindow(); _data->minX = dataWindow.min.x; _data->maxX = dataWindow.max.x; _data->minY = dataWindow.min.y; _data->maxY = dataWindow.max.y; // // Precompute level and tile information to speed up utility functions // precalculateTileInfo (_data->tileDesc, _data->minX, _data->maxX, _data->minY, _data->maxY, _data->numXTiles, _data->numYTiles, _data->numXLevels, _data->numYLevels); _data->bytesPerPixel = calculateBytesPerPixel (_data->header); _data->maxBytesPerTileLine = _data->bytesPerPixel * _data->tileDesc.xSize; _data->tileBufferSize = _data->maxBytesPerTileLine * _data->tileDesc.ySize; // // Create all the TileBuffers and allocate their internal buffers // for (size_t i = 0; i < _data->tileBuffers.size(); i++) { _data->tileBuffers[i] = new TileBuffer (newTileCompressor (_data->header.compression(), _data->maxBytesPerTileLine, _data->tileDesc.ySize, _data->header)); if (!_data->_streamData->is->isMemoryMapped ()) _data->tileBuffers[i]->buffer = new char [_data->tileBufferSize]; } _data->tileOffsets = TileOffsets (_data->tileDesc.mode, _data->numXLevels, _data->numYLevels, _data->numXTiles, _data->numYTiles); } TiledInputFile::~TiledInputFile () { if (!_data->memoryMapped) for (size_t i = 0; i < _data->tileBuffers.size(); i++) delete [] _data->tileBuffers[i]->buffer; if (_data->_deleteStream) delete _data->_streamData->is; if (_data->partNumber == -1) delete _data->_streamData; delete _data; } const char * TiledInputFile::fileName () const { return _data->_streamData->is->fileName(); } const Header & TiledInputFile::header () const { return _data->header; } int TiledInputFile::version () const { return _data->version; } void TiledInputFile::setFrameBuffer (const FrameBuffer &frameBuffer) { Lock lock (*_data->_streamData); // // Set the frame buffer // // // Check if the new frame buffer descriptor is // compatible with the image file header. // const ChannelList &channels = _data->header.channels(); for (FrameBuffer::ConstIterator j = frameBuffer.begin(); j != frameBuffer.end(); ++j) { ChannelList::ConstIterator i = channels.find (j.name()); if (i == channels.end()) continue; if (i.channel().xSampling != j.slice().xSampling || i.channel().ySampling != j.slice().ySampling) THROW (IEX_NAMESPACE::ArgExc, "X and/or y subsampling factors " "of \"" << i.name() << "\" channel " "of input file \"" << fileName() << "\" are " "not compatible with the frame buffer's " "subsampling factors."); } // // Initialize the slice table for readPixels(). // vector<TInSliceInfo> slices; ChannelList::ConstIterator i = channels.begin(); for (FrameBuffer::ConstIterator j = frameBuffer.begin(); j != frameBuffer.end(); ++j) { while (i != channels.end() && strcmp (i.name(), j.name()) < 0) { // // Channel i is present in the file but not // in the frame buffer; data for channel i // will be skipped during readPixels(). // slices.push_back (TInSliceInfo (i.channel().type, i.channel().type, 0, // base 0, // xStride 0, // yStride false, // fill true, // skip 0.0)); // fillValue ++i; } bool fill = false; if (i == channels.end() || strcmp (i.name(), j.name()) > 0) { // // Channel i is present in the frame buffer, but not in the file. // In the frame buffer, slice j will be filled with a default value. // fill = true; } slices.push_back (TInSliceInfo (j.slice().type, fill? j.slice().type: i.channel().type, j.slice().base, j.slice().xStride, j.slice().yStride, fill, false, // skip j.slice().fillValue, (j.slice().xTileCoords)? 1: 0, (j.slice().yTileCoords)? 1: 0)); if (i != channels.end() && !fill) ++i; } while (i != channels.end()) { // // Channel i is present in the file but not // in the frame buffer; data for channel i // will be skipped during readPixels(). // slices.push_back (TInSliceInfo (i.channel().type, i.channel().type, 0, // base 0, // xStride 0, // yStride false, // fill true, // skip 0.0)); // fillValue ++i; } // // Store the new frame buffer. // _data->frameBuffer = frameBuffer; _data->slices = slices; } const FrameBuffer & TiledInputFile::frameBuffer () const { Lock lock (*_data->_streamData); return _data->frameBuffer; } bool TiledInputFile::isComplete () const { return _data->fileIsComplete; } void TiledInputFile::readTiles (int dx1, int dx2, int dy1, int dy2, int lx, int ly) { // // Read a range of tiles from the file into the framebuffer // try { Lock lock (*_data->_streamData); if (_data->slices.size() == 0) throw IEX_NAMESPACE::ArgExc ("No frame buffer specified " "as pixel data destination."); if (!isValidLevel (lx, ly)) THROW (IEX_NAMESPACE::ArgExc, "Level coordinate " "(" << lx << ", " << ly << ") " "is invalid."); // // Determine the first and last tile coordinates in both dimensions. // We always attempt to read the range of tiles in the order that // they are stored in the file. // if (dx1 > dx2) std::swap (dx1, dx2); if (dy1 > dy2) std::swap (dy1, dy2); int dyStart = dy1; int dyStop = dy2 + 1; int dY = 1; if (_data->lineOrder == DECREASING_Y) { dyStart = dy2; dyStop = dy1 - 1; dY = -1; } // // Create a task group for all tile buffer tasks. When the // task group goes out of scope, the destructor waits until // all tasks are complete. // { TaskGroup taskGroup; int tileNumber = 0; for (int dy = dyStart; dy != dyStop; dy += dY) { for (int dx = dx1; dx <= dx2; dx++) { if (!isValidTile (dx, dy, lx, ly)) THROW (IEX_NAMESPACE::ArgExc, "Tile (" << dx << ", " << dy << ", " << lx << "," << ly << ") is not a valid tile."); ThreadPool::addGlobalTask (newTileBufferTask (&taskGroup, _data->_streamData, _data, tileNumber++, dx, dy, lx, ly)); } } // // finish all tasks // } // // Exeption handling: // // TileBufferTask::execute() may have encountered exceptions, but // those exceptions occurred in another thread, not in the thread // that is executing this call to TiledInputFile::readTiles(). // TileBufferTask::execute() has caught all exceptions and stored // the exceptions' what() strings in the tile buffers. // Now we check if any tile buffer contains a stored exception; if // this is the case then we re-throw the exception in this thread. // (It is possible that multiple tile buffers contain stored // exceptions. We re-throw the first exception we find and // ignore all others.) // const string *exception = 0; for (size_t i = 0; i < _data->tileBuffers.size(); ++i) { TileBuffer *tileBuffer = _data->tileBuffers[i]; if (tileBuffer->hasException && !exception) exception = &tileBuffer->exception; tileBuffer->hasException = false; } if (exception) throw IEX_NAMESPACE::IoExc (*exception); } catch (IEX_NAMESPACE::BaseExc &e) { REPLACE_EXC (e, "Error reading pixel data from image " "file \"" << fileName() << "\". " << e.what()); throw; } } void TiledInputFile::readTiles (int dx1, int dx2, int dy1, int dy2, int l) { readTiles (dx1, dx2, dy1, dy2, l, l); } void TiledInputFile::readTile (int dx, int dy, int lx, int ly) { readTiles (dx, dx, dy, dy, lx, ly); } void TiledInputFile::readTile (int dx, int dy, int l) { readTile (dx, dy, l, l); } void TiledInputFile::rawTileData (int &dx, int &dy, int &lx, int &ly, const char *&pixelData, int &pixelDataSize) { try { Lock lock (*_data->_streamData); if (!isValidTile (dx, dy, lx, ly)) throw IEX_NAMESPACE::ArgExc ("Tried to read a tile outside " "the image file's data window."); TileBuffer *tileBuffer = _data->getTileBuffer (0); // // if file is a multipart file, we have to seek to the required tile // since we don't know where the file pointer is // int old_dx=dx; int old_dy=dy; int old_lx=lx; int old_ly=ly; if(isMultiPart(version())) { _data->_streamData->is->seekg(_data->tileOffsets(dx,dy,lx,ly)); } readNextTileData (_data->_streamData, _data, dx, dy, lx, ly, tileBuffer->buffer, pixelDataSize); if(isMultiPart(version())) { if (old_dx!=dx || old_dy !=dy || old_lx!=lx || old_ly!=ly) { throw IEX_NAMESPACE::ArgExc ("rawTileData read the wrong tile"); } } else { if(!isValidTile (dx, dy, lx, ly) ) { throw IEX_NAMESPACE::IoExc ("rawTileData read an invalid tile"); } } pixelData = tileBuffer->buffer; } catch (IEX_NAMESPACE::BaseExc &e) { REPLACE_EXC (e, "Error reading pixel data from image " "file \"" << fileName() << "\". " << e.what()); throw; } } unsigned int TiledInputFile::tileXSize () const { return _data->tileDesc.xSize; } unsigned int TiledInputFile::tileYSize () const { return _data->tileDesc.ySize; } LevelMode TiledInputFile::levelMode () const { return _data->tileDesc.mode; } LevelRoundingMode TiledInputFile::levelRoundingMode () const { return _data->tileDesc.roundingMode; } int TiledInputFile::numLevels () const { if (levelMode() == RIPMAP_LEVELS) THROW (IEX_NAMESPACE::LogicExc, "Error calling numLevels() on image " "file \"" << fileName() << "\" " "(numLevels() is not defined for files " "with RIPMAP level mode)."); return _data->numXLevels; } int TiledInputFile::numXLevels () const { return _data->numXLevels; } int TiledInputFile::numYLevels () const { return _data->numYLevels; } bool TiledInputFile::isValidLevel (int lx, int ly) const { if (lx < 0 || ly < 0) return false; if (levelMode() == MIPMAP_LEVELS && lx != ly) return false; if (lx >= numXLevels() || ly >= numYLevels()) return false; return true; } int TiledInputFile::levelWidth (int lx) const { try { return levelSize (_data->minX, _data->maxX, lx, _data->tileDesc.roundingMode); } catch (IEX_NAMESPACE::BaseExc &e) { REPLACE_EXC (e, "Error calling levelWidth() on image " "file \"" << fileName() << "\". " << e.what()); throw; } } int TiledInputFile::levelHeight (int ly) const { try { return levelSize (_data->minY, _data->maxY, ly, _data->tileDesc.roundingMode); } catch (IEX_NAMESPACE::BaseExc &e) { REPLACE_EXC (e, "Error calling levelHeight() on image " "file \"" << fileName() << "\". " << e.what()); throw; } } int TiledInputFile::numXTiles (int lx) const { if (lx < 0 || lx >= _data->numXLevels) { THROW (IEX_NAMESPACE::ArgExc, "Error calling numXTiles() on image " "file \"" << _data->_streamData->is->fileName() << "\" " "(Argument is not in valid range)."); } return _data->numXTiles[lx]; } int TiledInputFile::numYTiles (int ly) const { if (ly < 0 || ly >= _data->numYLevels) { THROW (IEX_NAMESPACE::ArgExc, "Error calling numYTiles() on image " "file \"" << _data->_streamData->is->fileName() << "\" " "(Argument is not in valid range)."); } return _data->numYTiles[ly]; } Box2i TiledInputFile::dataWindowForLevel (int l) const { return dataWindowForLevel (l, l); } Box2i TiledInputFile::dataWindowForLevel (int lx, int ly) const { try { return OPENEXR_IMF_INTERNAL_NAMESPACE::dataWindowForLevel ( _data->tileDesc, _data->minX, _data->maxX, _data->minY, _data->maxY, lx, ly); } catch (IEX_NAMESPACE::BaseExc &e) { REPLACE_EXC (e, "Error calling dataWindowForLevel() on image " "file \"" << fileName() << "\". " << e.what()); throw; } } Box2i TiledInputFile::dataWindowForTile (int dx, int dy, int l) const { return dataWindowForTile (dx, dy, l, l); } Box2i TiledInputFile::dataWindowForTile (int dx, int dy, int lx, int ly) const { try { if (!isValidTile (dx, dy, lx, ly)) throw IEX_NAMESPACE::ArgExc ("Arguments not in valid range."); return OPENEXR_IMF_INTERNAL_NAMESPACE::dataWindowForTile ( _data->tileDesc, _data->minX, _data->maxX, _data->minY, _data->maxY, dx, dy, lx, ly); } catch (IEX_NAMESPACE::BaseExc &e) { REPLACE_EXC (e, "Error calling dataWindowForTile() on image " "file \"" << fileName() << "\". " << e.what()); throw; } } bool TiledInputFile::isValidTile (int dx, int dy, int lx, int ly) const { return ((lx < _data->numXLevels && lx >= 0) && (ly < _data->numYLevels && ly >= 0) && (dx < _data->numXTiles[lx] && dx >= 0) && (dy < _data->numYTiles[ly] && dy >= 0)); } void TiledInputFile::tileOrder(int dx[], int dy[], int lx[], int ly[]) const { return _data->tileOffsets.getTileOrder(dx,dy,lx,ly); } OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_EXIT
null
194
CWE-787
CVE-2020-1896
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ //RUN: %hermes -O -target=HBC %s | %FileCheck --match-full-lines %s function func() { print(arguments.length); } try { var a = [] a[8*1024*1024] = 100; func.apply(null, a); } catch(e) { print("caught:", e.name, e.message); } //CHECK: caught: RangeError {{.*}} var x = []; x.length = 4294967295; for (var i = 0; i < 20; i++) { x[i] = i; } try { func.apply(99, x); } catch (e) { print("caught:", e.name, e.message); } //CHECK: caught: RangeError {{.*}}
null
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ //RUN: %hermes -O -target=HBC %s | %FileCheck --match-full-lines %s function func() { print(arguments.length); } try { var a = [] a[8*1024*1024] = 100; func.apply(null, a); } catch(e) { print("caught:", e.name, e.message); } //CHECK: caught: RangeError {{.*}} var x = []; x.length = 4294967295; for (var i = 0; i < 20; i++) { x[i] = i; } try { func.apply(99, x); } catch (e) { print("caught:", e.name, e.message); } //CHECK: caught: RangeError {{.*}} try { v0 = [1.1]; function v1() { v1(...v0); } v1(); } catch (e) { print("caught:", e.name, e.message); } //CHECK: caught: RangeError {{.*}}
null
195
CWE-787
CVE-2020-1912
null
null
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // RUN: %hermes -lazy %s | %FileCheck %s --match-full-lines // Make sure we can correctly resolve scopes through lazily compiled // functions in lazily compiled generators. function f() { var f_var = 10; function* g() { var g_var = 32; function h() { /* Some text to pad out the function so that it won't be eagerly compiled * for being too short. Lorem ipsum dolor sit amet, consectetur adipiscing * elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. */ return f_var + g_var; } yield h(); } return g().next().value; } // CHECK: 42 print(f());
null
196
CWE-787
CVE-2020-1916
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/base/string-util.h" #include <algorithm> #include <vector> #include "hphp/zend/zend-html.h" #include "hphp/runtime/base/array-init.h" #include "hphp/util/bstring.h" #include "hphp/runtime/base/zend-string.h" #include "hphp/runtime/base/zend-url.h" #include "hphp/runtime/base/runtime-error.h" #include "hphp/runtime/base/array-iterator.h" #include "hphp/runtime/base/builtin-functions.h" #include "hphp/runtime/base/container-functions.h" namespace HPHP { /////////////////////////////////////////////////////////////////////////////// // manipulations String StringUtil::Pad(const String& input, int final_length, const String& pad_string /* = " " */, PadType type /* = PadType::Right */) { int len = input.size(); return string_pad(input.data(), len, final_length, pad_string.data(), pad_string.size(), static_cast<int>(type)); } String StringUtil::StripHTMLTags(const String& input, const String& allowable_tags /* = "" */) { if (input.empty()) return input; return string_strip_tags(input.data(), input.size(), allowable_tags.data(), allowable_tags.size(), false); } /////////////////////////////////////////////////////////////////////////////// // splits/joins Variant StringUtil::Explode(const String& input, const String& delimiter, int64_t limit /* = PHP_INT_MAX */) { if (delimiter.empty()) { raise_invalid_argument_warning("delimiter: (empty)"); return false; } Array ret(Array::CreateVArray()); if (input.empty()) { if (limit >= 0) { ret.append(""); } return ret; } if (limit > 1) { int pos = input.find(delimiter); if (pos < 0) { ret.append(input); } else { int len = delimiter.size(); int pos0 = 0; do { ret.append(input.substr(pos0, pos - pos0)); pos += len; pos0 = pos; } while ((pos = input.find(delimiter, pos)) >= 0 && --limit > 1); if (pos0 <= input.size()) { ret.append(input.substr(pos0)); } } } else if (limit < 0) { int pos = input.find(delimiter); if (pos >= 0) { std::vector<int> positions; int len = delimiter.size(); int pos0 = 0; int64_t found = 0; do { positions.push_back(pos0); positions.push_back(pos - pos0); pos += len; pos0 = pos; found++; } while ((pos = input.find(delimiter, pos)) >= 0); if (pos0 <= input.size()) { positions.push_back(pos0); positions.push_back(input.size() - pos0); found++; } uint64_t nelems = std::max(found + limit, (int64_t)0); for (uint64_t i = 0; i < nelems * 2; i += 2) { ret.append(input.substr(positions[i], positions[i+1])); } } // else we have negative limit and delimiter not found } else { ret.append(input); } return ret; } String StringUtil::Implode(const Variant& items, const String& delim, const bool checkIsContainer /* = true */) { if (checkIsContainer && !isContainer(items)) { throw_param_is_not_container(); } int size = getContainerSize(items); if (size == 0) return empty_string(); req::vector<String> sitems; sitems.reserve(size); size_t len = 0; size_t lenDelim = delim.size(); for (ArrayIter iter(items); iter; ++iter) { sitems.emplace_back(iter.second().toString()); len += sitems.back().size() + lenDelim; } len -= lenDelim; // always one delimiter less than count of items assertx(sitems.size() == size); String s = String(len, ReserveString); char *buffer = s.mutableData(); const char *sdelim = delim.data(); char *p = buffer; String &init_str = sitems[0]; int init_len = init_str.size(); memcpy(p, init_str.data(), init_len); p += init_len; for (int i = 1; i < size; i++) { String &item = sitems[i]; memcpy(p, sdelim, lenDelim); p += lenDelim; int lenItem = item.size(); memcpy(p, item.data(), lenItem); p += lenItem; } assertx(p - buffer == len); s.setSize(len); return s; } Variant StringUtil::Split(const String& str, int64_t split_length /* = 1 */) { if (split_length <= 0) { raise_invalid_argument_warning( "The length of each segment must be greater than zero" ); return false; } int len = str.size(); VArrayInit ret(len / split_length + 1); if (split_length >= len) { ret.append(str); } else { for (int i = 0; i < len; i += split_length) { ret.append(str.substr(i, split_length)); } } return ret.toArray(); } Variant StringUtil::ChunkSplit(const String& body, int chunklen /* = 76 */, const String& end /* = "\r\n" */) { if (chunklen <= 0) { raise_invalid_argument_warning("chunklen: (non-positive)"); return false; } String ret; int len = body.size(); if (chunklen >= len) { ret = body; ret += end; } else { return string_chunk_split(body.data(), len, end.c_str(), end.size(), chunklen); } return ret; } /////////////////////////////////////////////////////////////////////////////// // encoding/decoding String StringUtil::HtmlEncode(const String& input, QuoteStyle quoteStyle, const char *charset, bool dEncode, bool htmlEnt) { return HtmlEncode(input, static_cast<int64_t>(quoteStyle), charset, dEncode, htmlEnt); } String StringUtil::HtmlEncode(const String& input, const int64_t qsBitmask, const char *charset, bool dEncode, bool htmlEnt) { if (input.empty()) return input; assertx(charset); bool utf8 = true; if (strcasecmp(charset, "ISO-8859-1") == 0) { utf8 = false; } else if (strcasecmp(charset, "UTF-8")) { throw_not_implemented(charset); } int len = input.size(); char *ret = string_html_encode(input.data(), len, qsBitmask, utf8, dEncode, htmlEnt); if (!ret) { return empty_string(); } return String(ret, len, AttachString); } #define A1(v, ch) ((v)|((ch) & 64 ? 0 : 1uLL<<((ch)&63))) #define A2(v, ch) ((v)|((ch) & 64 ? 1uLL<<((ch)&63) : 0)) static const AsciiMap mapNoQuotes = { { A1(A1(A1(A1(A1(A1(0, '<'), '>'), '&'), '{'), '}'), '@'), A2(A2(A2(A2(A2(A2(0, '<'), '>'), '&'), '{'), '}'), '@') } }; static const AsciiMap mapDoubleQuotes = { { A1(A1(A1(A1(A1(A1(A1(0, '<'), '>'), '&'), '{'), '}'), '@'), '"'), A2(A2(A2(A2(A2(A2(A2(0, '<'), '>'), '&'), '{'), '}'), '@'), '"') } }; static const AsciiMap mapBothQuotes = { { A1(A1(A1(A1(A1(A1(A1(A1(0, '<'), '>'), '&'), '{'), '}'), '@'), '"'), '\''), A2(A2(A2(A2(A2(A2(A2(A2(0, '<'), '>'), '&'), '{'), '}'), '@'), '"'), '\'') } }; static const AsciiMap mapNothing = {}; String StringUtil::HtmlEncodeExtra(const String& input, QuoteStyle quoteStyle, const char *charset, bool nbsp, Array extra) { if (input.empty()) return input; assertx(charset); int flags = STRING_HTML_ENCODE_UTF8; if (nbsp) { flags |= STRING_HTML_ENCODE_NBSP; } if (RuntimeOption::Utf8izeReplace) { flags |= STRING_HTML_ENCODE_UTF8IZE_REPLACE; } if (!*charset || strcasecmp(charset, "UTF-8") == 0) { } else if (strcasecmp(charset, "ISO-8859-1") == 0) { flags &= ~STRING_HTML_ENCODE_UTF8; } else { throw_not_implemented(charset); } const AsciiMap *am; AsciiMap tmp; switch (quoteStyle) { case QuoteStyle::FBUtf8Only: am = &mapNothing; flags |= STRING_HTML_ENCODE_HIGH; break; case QuoteStyle::FBUtf8: am = &mapBothQuotes; flags |= STRING_HTML_ENCODE_HIGH; break; case QuoteStyle::Both: am = &mapBothQuotes; break; case QuoteStyle::Double: am = &mapDoubleQuotes; break; case QuoteStyle::No: am = &mapNoQuotes; break; default: am = &mapNothing; raise_error("Unknown quote style: %d", (int)quoteStyle); } if (quoteStyle != QuoteStyle::FBUtf8Only && extra.toBoolean()) { tmp = *am; am = &tmp; for (ArrayIter iter(extra); iter; ++iter) { String item = iter.second().toString(); char c = item.data()[0]; tmp.map[c & 64 ? 1 : 0] |= 1uLL << (c & 63); } } int len = input.size(); char *ret = string_html_encode_extra(input.data(), len, (StringHtmlEncoding)flags, am); if (!ret) { raise_error("HtmlEncode called on too large input (%d)", len); } return String(ret, len, AttachString); } String StringUtil::HtmlDecode(const String& input, QuoteStyle quoteStyle, const char *charset, bool all) { if (input.empty()) return input; assertx(charset); int len = input.size(); char *ret = string_html_decode(input.data(), len, quoteStyle != QuoteStyle::No, quoteStyle == QuoteStyle::Both, charset, all); if (!ret) { // null iff charset was not recognized throw_not_implemented(charset); // (charset is not null, see assertion above) } return String(ret, len, AttachString); } String StringUtil::QuotedPrintableEncode(const String& input) { if (input.empty()) return input; int len = input.size(); return string_quoted_printable_encode(input.data(), len); } String StringUtil::QuotedPrintableDecode(const String& input) { if (input.empty()) return input; int len = input.size(); return string_quoted_printable_decode(input.data(), len, false); } String StringUtil::UUEncode(const String& input) { if (input.empty()) return input; return string_uuencode(input.data(), input.size()); } String StringUtil::UUDecode(const String& input) { if (!input.empty()) { return string_uudecode(input.data(), input.size()); } return String(); } String StringUtil::Base64Encode(const String& input) { int len = input.size(); return string_base64_encode(input.data(), len); } String StringUtil::Base64Decode(const String& input, bool strict /* = false */) { int len = input.size(); return string_base64_decode(input.data(), len, strict); } String StringUtil::UrlEncode(const String& input, bool encodePlus /* = true */) { return encodePlus ? url_encode(input.data(), input.size()) : url_raw_encode(input.data(), input.size()); } String StringUtil::UrlDecode(const String& input, bool decodePlus /* = true */) { return decodePlus ? url_decode(input.data(), input.size()) : url_raw_decode(input.data(), input.size()); } bool StringUtil::IsFileUrl(const String& input) { return string_strncasecmp( input.data(), input.size(), "file://", sizeof("file://") - 1, sizeof("file://") - 1) == 0; } String StringUtil::DecodeFileUrl(const String& input) { Url url; if (!url_parse(url, input.data(), input.size())) { return null_string; } if (bstrcasecmp(url.scheme.data(), url.scheme.size(), "file", sizeof("file")-1) != 0) { // Not file scheme return null_string; } if (url.host.size() > 0 && bstrcasecmp(url.host.data(), url.host.size(), "localhost", sizeof("localhost")-1) != 0) { // Not localhost or empty host return null_string; } return url_raw_decode(url.path.data(), url.path.size()); } /////////////////////////////////////////////////////////////////////////////// // formatting String StringUtil::MoneyFormat(const char *format, double value) { assertx(format); return string_money_format(format, value); } /////////////////////////////////////////////////////////////////////////////// // hashing String StringUtil::Translate(const String& input, const String& from, const String& to) { if (input.empty()) return input; int len = input.size(); String retstr(len, ReserveString); char *ret = retstr.mutableData(); memcpy(ret, input.data(), len); auto trlen = std::min(from.size(), to.size()); string_translate(ret, len, from.data(), to.data(), trlen); retstr.setSize(len); return retstr; } String StringUtil::ROT13(const String& input) { if (input.empty()) return input; return String(string_rot13(input.data(), input.size()), input.size(), AttachString); } String StringUtil::Crypt(const String& input, const char *salt /* = "" */) { if (salt && salt[0] == '\0') { raise_notice("crypt(): No salt parameter was specified." " You must use a randomly generated salt and a strong" " hash function to produce a secure hash."); } return String(string_crypt(input.c_str(), salt), AttachString); } String StringUtil::MD5(const char *data, uint32_t size, bool raw /* = false */) { Md5Digest md5(data, size); auto const rawLen = sizeof(md5.digest); if (raw) return String((char*)md5.digest, rawLen, CopyString); auto const hexLen = rawLen * 2; String hex(hexLen, ReserveString); string_bin2hex((char*)md5.digest, rawLen, hex.mutableData()); hex.setSize(hexLen); return hex; } String StringUtil::MD5(const String& input, bool raw /* = false */) { return MD5(input.data(), input.length(), raw); } String StringUtil::SHA1(const String& input, bool raw /* = false */) { int len; char *ret = string_sha1(input.data(), input.size(), raw, len); return String(ret, len, AttachString); } /////////////////////////////////////////////////////////////////////////////// // integer safety for string allocations size_t safe_address(size_t nmemb, size_t size, size_t offset) { uint64_t result = (uint64_t) nmemb * (uint64_t) size + (uint64_t) offset; if (UNLIKELY(result > StringData::MaxSize)) { raiseStringLengthExceededError(result); } return result; } /////////////////////////////////////////////////////////////////////////////// }
null
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/base/string-util.h" #include <algorithm> #include <vector> #include "hphp/zend/zend-html.h" #include "hphp/runtime/base/array-init.h" #include "hphp/util/bstring.h" #include "hphp/runtime/base/zend-string.h" #include "hphp/runtime/base/zend-url.h" #include "hphp/runtime/base/runtime-error.h" #include "hphp/runtime/base/array-iterator.h" #include "hphp/runtime/base/builtin-functions.h" #include "hphp/runtime/base/container-functions.h" namespace HPHP { /////////////////////////////////////////////////////////////////////////////// // manipulations String StringUtil::Pad(const String& input, int final_length, const String& pad_string /* = " " */, PadType type /* = PadType::Right */) { int len = input.size(); return string_pad(input.data(), len, final_length, pad_string.data(), pad_string.size(), static_cast<int>(type)); } String StringUtil::StripHTMLTags(const String& input, const String& allowable_tags /* = "" */) { if (input.empty()) return input; return string_strip_tags(input.data(), input.size(), allowable_tags.data(), allowable_tags.size(), false); } /////////////////////////////////////////////////////////////////////////////// // splits/joins Variant StringUtil::Explode(const String& input, const String& delimiter, int64_t limit /* = PHP_INT_MAX */) { if (delimiter.empty()) { raise_invalid_argument_warning("delimiter: (empty)"); return false; } Array ret(Array::CreateVArray()); if (input.empty()) { if (limit >= 0) { ret.append(""); } return ret; } if (limit > 1) { int pos = input.find(delimiter); if (pos < 0) { ret.append(input); } else { int len = delimiter.size(); int pos0 = 0; do { ret.append(input.substr(pos0, pos - pos0)); pos += len; pos0 = pos; } while ((pos = input.find(delimiter, pos)) >= 0 && --limit > 1); if (pos0 <= input.size()) { ret.append(input.substr(pos0)); } } } else if (limit < 0) { int pos = input.find(delimiter); if (pos >= 0) { std::vector<int> positions; int len = delimiter.size(); int pos0 = 0; int64_t found = 0; do { positions.push_back(pos0); positions.push_back(pos - pos0); pos += len; pos0 = pos; found++; } while ((pos = input.find(delimiter, pos)) >= 0); if (pos0 <= input.size()) { positions.push_back(pos0); positions.push_back(input.size() - pos0); found++; } uint64_t nelems = std::max(found + limit, (int64_t)0); for (uint64_t i = 0; i < nelems * 2; i += 2) { ret.append(input.substr(positions[i], positions[i+1])); } } // else we have negative limit and delimiter not found } else { ret.append(input); } return ret; } String StringUtil::Implode(const Variant& items, const String& delim, const bool checkIsContainer /* = true */) { if (checkIsContainer && !isContainer(items)) { throw_param_is_not_container(); } int size = getContainerSize(items); if (size == 0) return empty_string(); req::vector<String> sitems; sitems.reserve(size); size_t len = 0; size_t lenDelim = delim.size(); for (ArrayIter iter(items); iter; ++iter) { sitems.emplace_back(iter.second().toString()); len += sitems.back().size() + lenDelim; } len -= lenDelim; // always one delimiter less than count of items assertx(sitems.size() == size); String s = String(len, ReserveString); char *buffer = s.mutableData(); const char *sdelim = delim.data(); char *p = buffer; String &init_str = sitems[0]; int init_len = init_str.size(); memcpy(p, init_str.data(), init_len); p += init_len; for (int i = 1; i < size; i++) { String &item = sitems[i]; memcpy(p, sdelim, lenDelim); p += lenDelim; int lenItem = item.size(); memcpy(p, item.data(), lenItem); p += lenItem; } assertx(p - buffer == len); s.setSize(len); return s; } Variant StringUtil::Split(const String& str, int64_t split_length /* = 1 */) { if (split_length <= 0) { raise_invalid_argument_warning( "The length of each segment must be greater than zero" ); return false; } int len = str.size(); VArrayInit ret(len / split_length + 1); if (split_length >= len) { ret.append(str); } else { for (int i = 0; i < len; i += split_length) { ret.append(str.substr(i, split_length)); } } return ret.toArray(); } Variant StringUtil::ChunkSplit(const String& body, int chunklen /* = 76 */, const String& end /* = "\r\n" */) { if (chunklen <= 0) { raise_invalid_argument_warning("chunklen: (non-positive)"); return false; } String ret; int len = body.size(); if (chunklen >= len) { ret = body; ret += end; } else { return string_chunk_split(body.data(), len, end.c_str(), end.size(), chunklen); } return ret; } /////////////////////////////////////////////////////////////////////////////// // encoding/decoding String StringUtil::HtmlEncode(const String& input, QuoteStyle quoteStyle, const char *charset, bool dEncode, bool htmlEnt) { return HtmlEncode(input, static_cast<int64_t>(quoteStyle), charset, dEncode, htmlEnt); } String StringUtil::HtmlEncode(const String& input, const int64_t qsBitmask, const char *charset, bool dEncode, bool htmlEnt) { if (input.empty()) return input; assertx(charset); bool utf8 = true; if (strcasecmp(charset, "ISO-8859-1") == 0) { utf8 = false; } else if (strcasecmp(charset, "UTF-8")) { throw_not_implemented(charset); } int len = input.size(); char *ret = string_html_encode(input.data(), len, qsBitmask, utf8, dEncode, htmlEnt); if (!ret) { return empty_string(); } return String(ret, len, AttachString); } #define A1(v, ch) ((v)|((ch) & 64 ? 0 : 1uLL<<((ch)&63))) #define A2(v, ch) ((v)|((ch) & 64 ? 1uLL<<((ch)&63) : 0)) static const AsciiMap mapNoQuotes = { { A1(A1(A1(A1(A1(A1(0, '<'), '>'), '&'), '{'), '}'), '@'), A2(A2(A2(A2(A2(A2(0, '<'), '>'), '&'), '{'), '}'), '@') } }; static const AsciiMap mapDoubleQuotes = { { A1(A1(A1(A1(A1(A1(A1(0, '<'), '>'), '&'), '{'), '}'), '@'), '"'), A2(A2(A2(A2(A2(A2(A2(0, '<'), '>'), '&'), '{'), '}'), '@'), '"') } }; static const AsciiMap mapBothQuotes = { { A1(A1(A1(A1(A1(A1(A1(A1(0, '<'), '>'), '&'), '{'), '}'), '@'), '"'), '\''), A2(A2(A2(A2(A2(A2(A2(A2(0, '<'), '>'), '&'), '{'), '}'), '@'), '"'), '\'') } }; static const AsciiMap mapNothing = {}; String StringUtil::HtmlEncodeExtra(const String& input, QuoteStyle quoteStyle, const char *charset, bool nbsp, Array extra) { if (input.empty()) return input; assertx(charset); int flags = STRING_HTML_ENCODE_UTF8; if (nbsp) { flags |= STRING_HTML_ENCODE_NBSP; } if (RuntimeOption::Utf8izeReplace) { flags |= STRING_HTML_ENCODE_UTF8IZE_REPLACE; } if (!*charset || strcasecmp(charset, "UTF-8") == 0) { } else if (strcasecmp(charset, "ISO-8859-1") == 0) { flags &= ~STRING_HTML_ENCODE_UTF8; } else { throw_not_implemented(charset); } const AsciiMap *am; AsciiMap tmp; switch (quoteStyle) { case QuoteStyle::FBUtf8Only: am = &mapNothing; flags |= STRING_HTML_ENCODE_HIGH; break; case QuoteStyle::FBUtf8: am = &mapBothQuotes; flags |= STRING_HTML_ENCODE_HIGH; break; case QuoteStyle::Both: am = &mapBothQuotes; break; case QuoteStyle::Double: am = &mapDoubleQuotes; break; case QuoteStyle::No: am = &mapNoQuotes; break; default: am = &mapNothing; raise_error("Unknown quote style: %d", (int)quoteStyle); } if (quoteStyle != QuoteStyle::FBUtf8Only && extra.toBoolean()) { tmp = *am; am = &tmp; for (ArrayIter iter(extra); iter; ++iter) { String item = iter.second().toString(); char c = item.data()[0]; tmp.map[c & 64 ? 1 : 0] |= 1uLL << (c & 63); } } int len = input.size(); char *ret = string_html_encode_extra(input.data(), len, (StringHtmlEncoding)flags, am); if (!ret) { raise_error("HtmlEncode called on too large input (%d)", len); } return String(ret, len, AttachString); } String StringUtil::HtmlDecode(const String& input, QuoteStyle quoteStyle, const char *charset, bool all) { if (input.empty()) return input; assertx(charset); int len = input.size(); char *ret = string_html_decode(input.data(), len, quoteStyle != QuoteStyle::No, quoteStyle == QuoteStyle::Both, charset, all); if (!ret) { // null iff charset was not recognized throw_not_implemented(charset); // (charset is not null, see assertion above) } return String(ret, len, AttachString); } String StringUtil::QuotedPrintableEncode(const String& input) { if (input.empty()) return input; int len = input.size(); return string_quoted_printable_encode(input.data(), len); } String StringUtil::QuotedPrintableDecode(const String& input) { if (input.empty()) return input; int len = input.size(); return string_quoted_printable_decode(input.data(), len, false); } String StringUtil::UUEncode(const String& input) { if (input.empty()) return input; return string_uuencode(input.data(), input.size()); } String StringUtil::UUDecode(const String& input) { if (!input.empty()) { return string_uudecode(input.data(), input.size()); } return String(); } String StringUtil::Base64Encode(const String& input) { int len = input.size(); return string_base64_encode(input.data(), len); } String StringUtil::Base64Decode(const String& input, bool strict /* = false */) { int len = input.size(); return string_base64_decode(input.data(), len, strict); } String StringUtil::UrlEncode(const String& input, bool encodePlus /* = true */) { return encodePlus ? url_encode(input.data(), input.size()) : url_raw_encode(input.data(), input.size()); } String StringUtil::UrlDecode(const String& input, bool decodePlus /* = true */) { return decodePlus ? url_decode(input.data(), input.size()) : url_raw_decode(input.data(), input.size()); } bool StringUtil::IsFileUrl(const String& input) { return string_strncasecmp( input.data(), input.size(), "file://", sizeof("file://") - 1, sizeof("file://") - 1) == 0; } String StringUtil::DecodeFileUrl(const String& input) { Url url; if (!url_parse(url, input.data(), input.size())) { return null_string; } if (bstrcasecmp(url.scheme.data(), url.scheme.size(), "file", sizeof("file")-1) != 0) { // Not file scheme return null_string; } if (url.host.size() > 0 && bstrcasecmp(url.host.data(), url.host.size(), "localhost", sizeof("localhost")-1) != 0) { // Not localhost or empty host return null_string; } return url_raw_decode(url.path.data(), url.path.size()); } /////////////////////////////////////////////////////////////////////////////// // formatting String StringUtil::MoneyFormat(const char *format, double value) { assertx(format); return string_money_format(format, value); } /////////////////////////////////////////////////////////////////////////////// // hashing String StringUtil::Translate(const String& input, const String& from, const String& to) { if (input.empty()) return input; int len = input.size(); String retstr(len, ReserveString); char *ret = retstr.mutableData(); memcpy(ret, input.data(), len); auto trlen = std::min(from.size(), to.size()); string_translate(ret, len, from.data(), to.data(), trlen); retstr.setSize(len); return retstr; } String StringUtil::ROT13(const String& input) { if (input.empty()) return input; return String(string_rot13(input.data(), input.size()), input.size(), AttachString); } String StringUtil::Crypt(const String& input, const char *salt /* = "" */) { assertx(salt); if (salt[0] == '\0') { raise_notice("crypt(): No salt parameter was specified." " You must use a randomly generated salt and a strong" " hash function to produce a secure hash."); } return String(string_crypt(input.c_str(), salt), AttachString); } String StringUtil::MD5(const char *data, uint32_t size, bool raw /* = false */) { Md5Digest md5(data, size); auto const rawLen = sizeof(md5.digest); if (raw) return String((char*)md5.digest, rawLen, CopyString); auto const hexLen = rawLen * 2; String hex(hexLen, ReserveString); string_bin2hex((char*)md5.digest, rawLen, hex.mutableData()); hex.setSize(hexLen); return hex; } String StringUtil::MD5(const String& input, bool raw /* = false */) { return MD5(input.data(), input.length(), raw); } String StringUtil::SHA1(const String& input, bool raw /* = false */) { int len; char *ret = string_sha1(input.data(), input.size(), raw, len); return String(ret, len, AttachString); } /////////////////////////////////////////////////////////////////////////////// // integer safety for string allocations size_t safe_address(size_t nmemb, size_t size, size_t offset) { uint64_t result = (uint64_t) nmemb * (uint64_t) size + (uint64_t) offset; if (UNLIKELY(result > StringData::MaxSize)) { raiseStringLengthExceededError(result); } return result; } /////////////////////////////////////////////////////////////////////////////// }
null
197
CWE-787
CVE-2020-1917
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1997-2010 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/ext/openssl/ext_openssl.h" #include "hphp/runtime/base/array-init.h" #include "hphp/runtime/base/array-iterator.h" #include "hphp/runtime/base/ssl-socket.h" #include "hphp/runtime/base/string-util.h" #include "hphp/runtime/base/zend-string.h" #include "hphp/util/logger.h" #include <folly/ScopeGuard.h> #include <openssl/conf.h> #include <openssl/pem.h> #include <openssl/pkcs12.h> #include <openssl/rand.h> #include <vector> namespace HPHP { #define MIN_KEY_LENGTH 384 // bitfields const int64_t k_OPENSSL_RAW_DATA = 1; const int64_t k_OPENSSL_ZERO_PADDING = 2; const int64_t k_OPENSSL_NO_PADDING = 3; const int64_t k_OPENSSL_PKCS1_OAEP_PADDING = 4; // exported constants const int64_t k_OPENSSL_SSLV23_PADDING = 2; const int64_t k_OPENSSL_PKCS1_PADDING = 1; static char default_ssl_conf_filename[PATH_MAX]; struct OpenSSLInitializer { OpenSSLInitializer() { SSL_library_init(); OpenSSL_add_all_ciphers(); OpenSSL_add_all_digests(); OpenSSL_add_all_algorithms(); // CCM ciphers are not added by default, so let's add them! #if !defined(OPENSSL_NO_AES) && defined(EVP_CIPH_CCM_MODE) && \ OPENSSL_VERSION_NUMBER < 0x100020000 EVP_add_cipher(EVP_aes_128_ccm()); EVP_add_cipher(EVP_aes_192_ccm()); EVP_add_cipher(EVP_aes_256_ccm()); #endif ERR_load_ERR_strings(); ERR_load_crypto_strings(); ERR_load_EVP_strings(); /* Determine default SSL configuration file */ char *config_filename = getenv("OPENSSL_CONF"); if (config_filename == nullptr) { config_filename = getenv("SSLEAY_CONF"); } /* default to 'openssl.cnf' if no environment variable is set */ if (config_filename == nullptr) { snprintf(default_ssl_conf_filename, sizeof(default_ssl_conf_filename), "%s/%s", X509_get_default_cert_area(), "openssl.cnf"); } else { always_assert( strlen(config_filename) < sizeof(default_ssl_conf_filename)); strcpy(default_ssl_conf_filename, config_filename); } } ~OpenSSLInitializer() { EVP_cleanup(); } }; static OpenSSLInitializer s_openssl_initializer; /////////////////////////////////////////////////////////////////////////////// // resource classes struct Key : SweepableResourceData { EVP_PKEY *m_key; explicit Key(EVP_PKEY *key) : m_key(key) { assertx(m_key);} ~Key() override { if (m_key) EVP_PKEY_free(m_key); } CLASSNAME_IS("OpenSSL key"); // overriding ResourceData const String& o_getClassNameHook() const override { return classnameof(); } DECLARE_RESOURCE_ALLOCATION(Key) bool isPrivate() { assertx(m_key); switch (EVP_PKEY_id(m_key)) { #ifndef NO_RSA case EVP_PKEY_RSA: case EVP_PKEY_RSA2: { const auto rsa = EVP_PKEY_get0_RSA(m_key); assertx(rsa); const BIGNUM *p, *q; RSA_get0_factors(rsa, &p, &q); if (!p || !q) { return false; } break; } #endif #ifndef NO_DSA case EVP_PKEY_DSA: case EVP_PKEY_DSA1: case EVP_PKEY_DSA2: case EVP_PKEY_DSA3: case EVP_PKEY_DSA4: { const auto dsa = EVP_PKEY_get0_DSA(m_key); assertx(dsa); const BIGNUM *p, *q, *g, *pub_key, *priv_key; DSA_get0_pqg(dsa, &p, &q, &g); if (!p || !q || !g) { return false; } DSA_get0_key(dsa, &pub_key, &priv_key); if (!priv_key) { return false; } break; } #endif #ifndef NO_DH case EVP_PKEY_DH: { const auto dh = EVP_PKEY_get0_DH(m_key); assertx(dh); const BIGNUM *p, *q, *g, *pub_key, *priv_key; DH_get0_pqg(dh, &p, &q, &g); if (!p) { return false; } DH_get0_key(dh, &pub_key, &priv_key); if (!priv_key) { return false; } break; } #endif #ifdef HAVE_EVP_PKEY_EC case EVP_PKEY_EC: { const auto ec_key = EVP_PKEY_get0_EC_KEY(m_key); assertx(ec_key); if (EC_KEY_get0_private_key(ec_key) == nullptr) { return false; } break; } #endif default: raise_warning("key type not supported in this PHP build!"); break; } return true; } /** * Given a variant, coerce it into a EVP_PKEY object. It can be: * * 1. private key resource from openssl_get_privatekey() * 2. X509 resource -> public key will be extracted from it * 3. if it starts with file:// interpreted as path to key file * 4. interpreted as the data from the cert/key file and interpreted in * same way as openssl_get_privatekey() * 5. an array(0 => [items 2..4], 1 => passphrase) * 6. if val is a string (possibly starting with file:///) and it is not * an X509 certificate, then interpret as public key * * NOTE: If you are requesting a private key but have not specified a * passphrase, you should use an empty string rather than nullptr for the * passphrase - nullptr causes a passphrase prompt to be emitted in * the Apache error log! */ static req::ptr<Key> Get(const Variant& var, bool public_key, const char *passphrase = nullptr) { if (var.isArray()) { Array arr = var.toArray(); if (!arr.exists(int64_t(0)) || !arr.exists(int64_t(1))) { raise_warning("key array must be of the form " "array(0 => key, 1 => phrase)"); return nullptr; } String zphrase = arr[1].toString(); return GetHelper(arr[0], public_key, zphrase.data()); } return GetHelper(var, public_key, passphrase); } static req::ptr<Key> GetHelper(const Variant& var, bool public_key, const char *passphrase) { req::ptr<Certificate> ocert; EVP_PKEY *key = nullptr; if (var.isResource()) { auto cert = dyn_cast_or_null<Certificate>(var); auto key = dyn_cast_or_null<Key>(var); if (!cert && !key) return nullptr; if (key) { bool is_priv = key->isPrivate(); if (!public_key && !is_priv) { raise_warning("supplied key param is a public key"); return nullptr; } if (public_key && is_priv) { raise_warning("Don't know how to get public key from " "this private key"); return nullptr; } return key; } ocert = cert; } else { /* it's an X509 file/cert of some kind, and we need to extract the data from that */ if (public_key) { ocert = Certificate::Get(var); if (!ocert) { /* not a X509 certificate, try to retrieve public key */ BIO *in = Certificate::ReadData(var); if (in == nullptr) return nullptr; key = PEM_read_bio_PUBKEY(in, nullptr,nullptr, nullptr); BIO_free(in); } } else { /* we want the private key */ BIO *in = Certificate::ReadData(var); if (in == nullptr) return nullptr; key = PEM_read_bio_PrivateKey(in, nullptr,nullptr, (void*)passphrase); BIO_free(in); } } if (public_key && ocert && key == nullptr) { /* extract public key from X509 cert */ key = (EVP_PKEY *)X509_get_pubkey(ocert->get()); } if (key) { return req::make<Key>(key); } return nullptr; } }; IMPLEMENT_RESOURCE_ALLOCATION(Key) /** * Certificate Signing Request */ struct CSRequest : SweepableResourceData { private: X509_REQ *m_csr; public: explicit CSRequest(X509_REQ *csr) : m_csr(csr) { assertx(m_csr); } X509_REQ *csr() { return m_csr; } ~CSRequest() override { // X509_REQ_free(nullptr) is a no-op X509_REQ_free(m_csr); } CLASSNAME_IS("OpenSSL X.509 CSR"); // overriding ResourceData const String& o_getClassNameHook() const override { return classnameof(); } DECLARE_RESOURCE_ALLOCATION(CSRequest) static req::ptr<CSRequest> Get(const Variant& var) { auto csr = cast_or_null<CSRequest>(GetRequest(var)); if (!csr || !csr->m_csr) { raise_warning("cannot get CSR"); return nullptr; } return csr; } private: static req::ptr<CSRequest> GetRequest(const Variant& var) { if (var.isResource()) { return dyn_cast_or_null<CSRequest>(var); } if (var.isString() || var.isObject()) { BIO *in = Certificate::ReadData(var); if (in == nullptr) return nullptr; X509_REQ *csr = PEM_read_bio_X509_REQ(in, nullptr,nullptr,nullptr); BIO_free(in); if (csr) { return req::make<CSRequest>(csr); } } return nullptr; } }; IMPLEMENT_RESOURCE_ALLOCATION(CSRequest) struct php_x509_request { #if OPENSSL_VERSION_NUMBER >= 0x10000002L LHASH_OF(CONF_VALUE) * global_config; /* Global SSL config */ LHASH_OF(CONF_VALUE) * req_config; /* SSL config for this request */ #else LHASH *global_config; /* Global SSL config */ LHASH *req_config; /* SSL config for this request */ #endif const EVP_MD *md_alg; const EVP_MD *digest; const char *section_name; const char *config_filename; const char *digest_name; const char *extensions_section; const char *request_extensions_section; int priv_key_bits; int priv_key_type; int priv_key_encrypt; #ifdef HAVE_EVP_PKEY_EC int curve_name; #endif EVP_PKEY *priv_key; static bool load_rand_file(const char *file, int *egdsocket, int *seeded) { char buffer[PATH_MAX]; *egdsocket = 0; *seeded = 0; if (file == nullptr) { file = RAND_file_name(buffer, sizeof(buffer)); #if !defined(OPENSSL_NO_RAND_EGD) && !defined(OPENSSL_NO_EGD) } else if (RAND_egd(file) > 0) { /* if the given filename is an EGD socket, don't * write anything back to it */ *egdsocket = 1; return true; #endif } if (file == nullptr || !RAND_load_file(file, -1)) { if (RAND_status() == 0) { raise_warning("unable to load random state; not enough data!"); return false; } return false; } *seeded = 1; return true; } static bool write_rand_file(const char *file, int egdsocket, int seeded) { char buffer[PATH_MAX]; if (egdsocket || !seeded) { /* if we did not manage to read the seed file, we should not write * a low-entropy seed file back */ return false; } if (file == nullptr) { file = RAND_file_name(buffer, sizeof(buffer)); } if (file == nullptr || !RAND_write_file(file)) { raise_warning("unable to write random state"); return false; } return true; } bool generatePrivateKey() { assertx(priv_key == nullptr); if (priv_key_bits < MIN_KEY_LENGTH) { raise_warning("private key length is too short; it needs to be " "at least %d bits, not %d", MIN_KEY_LENGTH, priv_key_bits); return false; } char *randfile = CONF_get_string(req_config, section_name, "RANDFILE"); int egdsocket, seeded; load_rand_file(randfile, &egdsocket, &seeded); bool ret = false; if ((priv_key = EVP_PKEY_new()) != nullptr) { switch (priv_key_type) { case OPENSSL_KEYTYPE_RSA: if (EVP_PKEY_assign_RSA (priv_key, RSA_generate_key(priv_key_bits, 0x10001, nullptr, nullptr))) { ret = true; } break; #if !defined(NO_DSA) && defined(HAVE_DSA_DEFAULT_METHOD) case OPENSSL_KEYTYPE_DSA: { DSA *dsapar = DSA_generate_parameters(priv_key_bits, nullptr, 0, nullptr, nullptr, nullptr, nullptr); if (dsapar) { DSA_set_method(dsapar, DSA_get_default_method()); if (DSA_generate_key(dsapar)) { if (EVP_PKEY_assign_DSA(priv_key, dsapar)) { ret = true; } } else { DSA_free(dsapar); } } } break; #endif #ifdef HAVE_EVP_PKEY_EC case OPENSSL_KEYTYPE_EC: { if (curve_name == NID_undef) { raise_warning("Missing configuration value: 'curve_name' not set"); return false; } if (auto const eckey = EC_KEY_new_by_curve_name(curve_name)) { EC_KEY_set_asn1_flag(eckey, OPENSSL_EC_NAMED_CURVE); if (EC_KEY_generate_key(eckey) && EVP_PKEY_assign_EC_KEY(priv_key, eckey)) { ret = true; } else { EC_KEY_free(eckey); } } } break; #endif default: raise_warning("Unsupported private key type"); } } write_rand_file(randfile, egdsocket, seeded); return ret; } }; /////////////////////////////////////////////////////////////////////////////// // utilities static void add_assoc_name_entry(Array &ret, const char *key, X509_NAME *name, bool shortname) { Array subitem_data; Array &subitem = key ? subitem_data : ret; for (int i = 0; i < X509_NAME_entry_count(name); i++) { X509_NAME_ENTRY *ne = X509_NAME_get_entry(name, i); ASN1_OBJECT *obj = X509_NAME_ENTRY_get_object(ne); int nid = OBJ_obj2nid(obj); int obj_cnt = 0; char *sname; if (shortname) { sname = (char *)OBJ_nid2sn(nid); } else { sname = (char *)OBJ_nid2ln(nid); } Array subentries; int last = -1; int j; ASN1_STRING *str = nullptr; unsigned char *to_add = nullptr; int to_add_len = 0; for (;;) { j = X509_NAME_get_index_by_OBJ(name, obj, last); if (j < 0) { if (last != -1) break; } else { obj_cnt++; ne = X509_NAME_get_entry(name, j); str = X509_NAME_ENTRY_get_data(ne); if (ASN1_STRING_type(str) != V_ASN1_UTF8STRING) { to_add_len = ASN1_STRING_to_UTF8(&to_add, str); if (to_add_len != -1) { subentries.append(String((char*)to_add, to_add_len, AttachString)); } } else { to_add = ASN1_STRING_data(str); to_add_len = ASN1_STRING_length(str); subentries.append(String((char*)to_add, to_add_len, CopyString)); } } last = j; } i = last; if (obj_cnt > 1) { subitem.set(String(sname, CopyString), subentries); } else if (obj_cnt && str && to_add_len > -1) { // Use the string instance we created above. subitem.set(String(sname, CopyString), subentries[0]); } } if (key) { ret.set(String(key, CopyString), subitem); } } static const char *read_string(const Array& args, const String& key, const char *def, std::vector<String> &strings) { if (args.exists(key)) { String value = args[key].toString(); strings.push_back(value); return (char*)value.data(); } return def; } static int64_t read_integer(const Array& args, const String& key, int64_t def) { if (args.exists(key)) { return args[key].toInt64(); } return def; } static bool add_oid_section(struct php_x509_request *req) { char *str = CONF_get_string(req->req_config, nullptr, "oid_section"); if (str == nullptr) { return true; } STACK_OF(CONF_VALUE) *sktmp = CONF_get_section(req->req_config, str); if (sktmp == nullptr) { raise_warning("problem loading oid section %s", str); return false; } for (int i = 0; i < sk_CONF_VALUE_num(sktmp); i++) { CONF_VALUE *cnf = sk_CONF_VALUE_value(sktmp, i); if (OBJ_sn2nid(cnf->name) == NID_undef && OBJ_ln2nid(cnf->name) == NID_undef && OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) { raise_warning("problem creating object %s=%s", cnf->name, cnf->value); return false; } } return true; } #if OPENSSL_VERSION_NUMBER >= 0x10000002L static inline bool php_openssl_config_check_syntax (const char *section_label, const char *config_filename, const char *section, LHASH_OF(CONF_VALUE) *config) { #else static inline bool php_openssl_config_check_syntax (const char *section_label, const char *config_filename, const char *section, LHASH *config) { #endif X509V3_CTX ctx; X509V3_set_ctx_test(&ctx); X509V3_set_conf_lhash(&ctx, config); if (!X509V3_EXT_add_conf(config, &ctx, (char*)section, nullptr)) { raise_warning("Error loading %s section %s of %s", section_label, section, config_filename); return false; } return true; } const StaticString s_config("config"), s_config_section_name("config_section_name"), s_digest_alg("digest_alg"), s_x509_extensions("x509_extensions"), s_req_extensions("req_extensions"), s_private_key_bits("private_key_bits"), s_private_key_type("private_key_type"), s_encrypt_key("encrypt_key"), s_curve_name("curve_name"); static bool php_openssl_parse_config(struct php_x509_request *req, const Array& args, std::vector<String> &strings) { req->config_filename = read_string(args, s_config, default_ssl_conf_filename, strings); req->section_name = read_string(args, s_config_section_name, "req", strings); req->global_config = CONF_load(nullptr, default_ssl_conf_filename, nullptr); req->req_config = CONF_load(nullptr, req->config_filename, nullptr); if (req->req_config == nullptr) { return false; } /* read in the oids */ char *str = CONF_get_string(req->req_config, nullptr, "oid_file"); if (str) { BIO *oid_bio = BIO_new_file(str, "r"); if (oid_bio) { OBJ_create_objects(oid_bio); BIO_free(oid_bio); } } if (!add_oid_section(req)) { return false; } req->digest_name = read_string(args, s_digest_alg, CONF_get_string(req->req_config, req->section_name, "default_md"), strings); req->extensions_section = read_string(args, s_x509_extensions, CONF_get_string(req->req_config, req->section_name, "x509_extensions"), strings); req->request_extensions_section = read_string(args, s_req_extensions, CONF_get_string(req->req_config, req->section_name, "req_extensions"), strings); req->priv_key_bits = read_integer(args, s_private_key_bits, CONF_get_number(req->req_config, req->section_name, "default_bits")); req->priv_key_type = read_integer(args, s_private_key_type, OPENSSL_KEYTYPE_DEFAULT); if (args.exists(s_encrypt_key)) { bool value = args[s_encrypt_key].toBoolean(); req->priv_key_encrypt = value ? 1 : 0; } else { str = CONF_get_string(req->req_config, req->section_name, "encrypt_rsa_key"); if (str == nullptr) { str = CONF_get_string(req->req_config, req->section_name, "encrypt_key"); } if (str && strcmp(str, "no") == 0) { req->priv_key_encrypt = 0; } else { req->priv_key_encrypt = 1; } } /* digest alg */ if (req->digest_name == nullptr) { req->digest_name = CONF_get_string(req->req_config, req->section_name, "default_md"); } if (req->digest_name) { req->digest = req->md_alg = EVP_get_digestbyname(req->digest_name); } if (req->md_alg == nullptr) { req->md_alg = req->digest = EVP_sha256(); } #ifdef HAVE_EVP_PKEY_EC /* set the ec group curve name */ req->curve_name = NID_undef; if (args.exists(s_curve_name)) { auto const curve_name = args[s_curve_name].toString(); req->curve_name = OBJ_sn2nid(curve_name.data()); if (req->curve_name == NID_undef) { raise_warning( "Unknown elliptic curve (short) name %s", curve_name.data() ); return false; } } #endif if (req->extensions_section && !php_openssl_config_check_syntax ("extensions_section", req->config_filename, req->extensions_section, req->req_config)) { return false; } /* set the string mask */ str = CONF_get_string(req->req_config, req->section_name, "string_mask"); if (str && !ASN1_STRING_set_default_mask_asc(str)) { raise_warning("Invalid global string mask setting %s", str); return false; } if (req->request_extensions_section && !php_openssl_config_check_syntax ("request_extensions_section", req->config_filename, req->request_extensions_section, req->req_config)) { return false; } return true; } static void php_openssl_dispose_config(struct php_x509_request *req) { if (req->global_config) { CONF_free(req->global_config); req->global_config = nullptr; } if (req->req_config) { CONF_free(req->req_config); req->req_config = nullptr; } } static STACK_OF(X509) *load_all_certs_from_file(const char *certfile) { STACK_OF(X509_INFO) *sk = nullptr; STACK_OF(X509) *stack = nullptr, *ret = nullptr; BIO *in = nullptr; X509_INFO *xi; if (!(stack = sk_X509_new_null())) { raise_warning("memory allocation failure"); goto end; } if (!(in = BIO_new_file(certfile, "r"))) { raise_warning("error opening the file, %s", certfile); sk_X509_free(stack); goto end; } /* This loads from a file, a stack of x509/crl/pkey sets */ if (!(sk = PEM_X509_INFO_read_bio(in, nullptr, nullptr, nullptr))) { raise_warning("error reading the file, %s", certfile); sk_X509_free(stack); goto end; } /* scan over it and pull out the certs */ while (sk_X509_INFO_num(sk)) { xi = sk_X509_INFO_shift(sk); if (xi->x509 != nullptr) { sk_X509_push(stack, xi->x509); xi->x509 = nullptr; } X509_INFO_free(xi); } if (!sk_X509_num(stack)) { raise_warning("no certificates in file, %s", certfile); sk_X509_free(stack); goto end; } ret = stack; end: BIO_free(in); sk_X509_INFO_free(sk); return ret; } /** * calist is an array containing file and directory names. create a * certificate store and add those certs to it for use in verification. */ static X509_STORE *setup_verify(const Array& calist) { X509_STORE *store = X509_STORE_new(); if (store == nullptr) { return nullptr; } X509_LOOKUP *dir_lookup, *file_lookup; int ndirs = 0, nfiles = 0; for (ArrayIter iter(calist); iter; ++iter) { String item = iter.second().toString(); struct stat sb; if (stat(item.data(), &sb) == -1) { raise_warning("unable to stat %s", item.data()); continue; } if ((sb.st_mode & S_IFREG) == S_IFREG) { file_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()); if (file_lookup == nullptr || !X509_LOOKUP_load_file(file_lookup, item.data(), X509_FILETYPE_PEM)) { raise_warning("error loading file %s", item.data()); } else { nfiles++; } file_lookup = nullptr; } else { dir_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir()); if (dir_lookup == nullptr || !X509_LOOKUP_add_dir(dir_lookup, item.data(), X509_FILETYPE_PEM)) { raise_warning("error loading directory %s", item.data()); } else { ndirs++; } dir_lookup = nullptr; } } if (nfiles == 0) { file_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()); if (file_lookup) { X509_LOOKUP_load_file(file_lookup, nullptr, X509_FILETYPE_DEFAULT); } } if (ndirs == 0) { dir_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir()); if (dir_lookup) { X509_LOOKUP_add_dir(dir_lookup, nullptr, X509_FILETYPE_DEFAULT); } } return store; } /////////////////////////////////////////////////////////////////////////////// static bool add_entries(X509_NAME *subj, const Array& items) { for (ArrayIter iter(items); iter; ++iter) { auto const index = iter.first().toString(); auto const item = iter.second().toString(); int nid = OBJ_txt2nid(index.data()); if (nid != NID_undef) { if (!X509_NAME_add_entry_by_NID(subj, nid, MBSTRING_ASC, (unsigned char*)item.data(), -1, -1, 0)) { raise_warning("dn: add_entry_by_NID %d -> %s (failed)", nid, item.data()); return false; } } else { raise_warning("dn: %s is not a recognized name", index.data()); } } return true; } static bool php_openssl_make_REQ(struct php_x509_request *req, X509_REQ *csr, const Array& dn, const Array& attribs) { char *dn_sect = CONF_get_string(req->req_config, req->section_name, "distinguished_name"); if (dn_sect == nullptr) return false; STACK_OF(CONF_VALUE) *dn_sk = CONF_get_section(req->req_config, dn_sect); if (dn_sk == nullptr) return false; char *attr_sect = CONF_get_string(req->req_config, req->section_name, "attributes"); STACK_OF(CONF_VALUE) *attr_sk = nullptr; if (attr_sect) { attr_sk = CONF_get_section(req->req_config, attr_sect); if (attr_sk == nullptr) { return false; } } /* setup the version number: version 1 */ if (X509_REQ_set_version(csr, 0L)) { X509_NAME *subj = X509_REQ_get_subject_name(csr); if (!add_entries(subj, dn)) return false; /* Finally apply defaults from config file */ for (int i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) { CONF_VALUE *v = sk_CONF_VALUE_value(dn_sk, i); char *type = v->name; int len = strlen(type); if (len < (int)sizeof("_default")) { continue; } len -= sizeof("_default") - 1; if (strcmp("_default", type + len) != 0) { continue; } if (len > 200) { len = 200; } char buffer[200 + 1]; /*200 + \0 !*/ memcpy(buffer, type, len); buffer[len] = '\0'; type = buffer; /* Skip past any leading X. X: X, etc to allow for multiple instances */ for (char *str = type; *str; str++) { if (*str == ':' || *str == ',' || *str == '.') { str++; if (*str) { type = str; } break; } } /* if it is already set, skip this */ int nid = OBJ_txt2nid(type); if (X509_NAME_get_index_by_NID(subj, nid, -1) >= 0) { continue; } if (!X509_NAME_add_entry_by_txt(subj, type, MBSTRING_ASC, (unsigned char*)v->value, -1, -1, 0)) { raise_warning("add_entry_by_txt %s -> %s (failed)", type, v->value); return false; } if (!X509_NAME_entry_count(subj)) { raise_warning("no objects specified in config file"); return false; } } if (!add_entries(subj, attribs)) return false; if (attr_sk) { for (int i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) { CONF_VALUE *v = sk_CONF_VALUE_value(attr_sk, i); /* if it is already set, skip this */ int nid = OBJ_txt2nid(v->name); if (X509_REQ_get_attr_by_NID(csr, nid, -1) >= 0) { continue; } if (!X509_REQ_add1_attr_by_txt(csr, v->name, MBSTRING_ASC, (unsigned char*)v->value, -1)) { /** * hzhao: mismatched version of conf file may have attributes that * are not recognizable, and I don't think it should be treated as * fatal errors. */ Logger::Verbose("add1_attr_by_txt %s -> %s (failed)", v->name, v->value); // return false; } } } } X509_REQ_set_pubkey(csr, req->priv_key); return true; } bool HHVM_FUNCTION(openssl_csr_export_to_file, const Variant& csr, const String& outfilename, bool notext /* = true */) { auto pcsr = CSRequest::Get(csr); if (!pcsr) return false; BIO *bio_out = BIO_new_file((char*)outfilename.data(), "w"); if (bio_out == nullptr) { raise_warning("error opening file %s", outfilename.data()); return false; } if (!notext) { X509_REQ_print(bio_out, pcsr->csr()); } PEM_write_bio_X509_REQ(bio_out, pcsr->csr()); BIO_free(bio_out); return true; } bool HHVM_FUNCTION(openssl_csr_export, const Variant& csr, Variant& out, bool notext /* = true */) { auto pcsr = CSRequest::Get(csr); if (!pcsr) return false; BIO *bio_out = BIO_new(BIO_s_mem()); if (!notext) { X509_REQ_print(bio_out, pcsr->csr()); } if (PEM_write_bio_X509_REQ(bio_out, pcsr->csr())) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); out = String((char*)bio_buf->data, bio_buf->length, CopyString); BIO_free(bio_out); return true; } BIO_free(bio_out); return false; } Variant HHVM_FUNCTION(openssl_csr_get_public_key, const Variant& csr) { auto pcsr = CSRequest::Get(csr); if (!pcsr) return false; auto input_csr = pcsr->csr(); #if OPENSSL_VERSION_NUMBER >= 0x10100000 /* Due to changes in OpenSSL 1.1 related to locking when decoding CSR, * the pub key is not changed after assigning. It means if we pass * a private key, it will be returned including the private part. * If we duplicate it, then we get just the public part which is * the same behavior as for OpenSSL 1.0 */ input_csr = X509_REQ_dup(input_csr); /* We need to free the CSR as it was duplicated */ SCOPE_EXIT { X509_REQ_free(input_csr); }; #endif auto pubkey = X509_REQ_get_pubkey(input_csr); if (!pubkey) return false; return Variant(req::make<Key>(pubkey)); } Variant HHVM_FUNCTION(openssl_csr_get_subject, const Variant& csr, bool use_shortnames /* = true */) { auto pcsr = CSRequest::Get(csr); if (!pcsr) return false; X509_NAME *subject = X509_REQ_get_subject_name(pcsr->csr()); Array ret = Array::CreateDArray(); add_assoc_name_entry(ret, nullptr, subject, use_shortnames); return ret; } Variant HHVM_FUNCTION(openssl_csr_new, const Variant& dn, Variant& privkey, const Variant& configargs /* = uninit_variant */, const Variant& extraattribs /* = uninit_variant */) { Variant ret = false; struct php_x509_request req; memset(&req, 0, sizeof(req)); req::ptr<Key> okey; X509_REQ *csr = nullptr; std::vector<String> strings; if (php_openssl_parse_config(&req, configargs.toArray(), strings)) { /* Generate or use a private key */ if (!privkey.isNull()) { okey = Key::Get(privkey, false); if (okey) { req.priv_key = okey->m_key; } } if (req.priv_key == nullptr) { req.generatePrivateKey(); if (req.priv_key) { okey = req::make<Key>(req.priv_key); } } if (req.priv_key == nullptr) { raise_warning("Unable to generate a private key"); } else { csr = X509_REQ_new(); if (csr && php_openssl_make_REQ(&req, csr, dn.toArray(), extraattribs.toArray())) { X509V3_CTX ext_ctx; X509V3_set_ctx(&ext_ctx, nullptr, nullptr, csr, nullptr, 0); X509V3_set_conf_lhash(&ext_ctx, req.req_config); /* Add extensions */ if (req.request_extensions_section && !X509V3_EXT_REQ_add_conf(req.req_config, &ext_ctx, (char*)req.request_extensions_section, csr)) { raise_warning("Error loading extension section %s", req.request_extensions_section); } else { ret = true; if (X509_REQ_sign(csr, req.priv_key, req.digest)) { ret = req::make<CSRequest>(csr); csr = nullptr; } else { raise_warning("Error signing request"); } privkey = Variant(okey); } } } } if (csr) { X509_REQ_free(csr); } php_openssl_dispose_config(&req); return ret; } Variant HHVM_FUNCTION(openssl_csr_sign, const Variant& csr, const Variant& cacert, const Variant& priv_key, int days, const Variant& configargs /* = null */, int serial /* = 0 */) { auto pcsr = CSRequest::Get(csr); if (!pcsr) return false; req::ptr<Certificate> ocert; if (!cacert.isNull()) { ocert = Certificate::Get(cacert); if (!ocert) { raise_warning("cannot get cert from parameter 2"); return false; } } auto okey = Key::Get(priv_key, false); if (!okey) { raise_warning("cannot get private key from parameter 3"); return false; } X509 *cert = nullptr; if (ocert) { cert = ocert->m_cert; } EVP_PKEY *pkey = okey->m_key; if (cert && !X509_check_private_key(cert, pkey)) { raise_warning("private key does not correspond to signing cert"); return false; } req::ptr<Certificate> onewcert; struct php_x509_request req; memset(&req, 0, sizeof(req)); Variant ret = false; std::vector<String> strings; if (!php_openssl_parse_config(&req, configargs.toArray(), strings)) { goto cleanup; } /* Check that the request matches the signature */ EVP_PKEY *key; key = X509_REQ_get_pubkey(pcsr->csr()); if (key == nullptr) { raise_warning("error unpacking public key"); goto cleanup; } int i; i = X509_REQ_verify(pcsr->csr(), key); if (i < 0) { raise_warning("Signature verification problems"); goto cleanup; } if (i == 0) { raise_warning("Signature did not match the certificate request"); goto cleanup; } /* Now we can get on with it */ X509 *new_cert; new_cert = X509_new(); if (new_cert == nullptr) { raise_warning("No memory"); goto cleanup; } onewcert = req::make<Certificate>(new_cert); /* Version 3 cert */ if (!X509_set_version(new_cert, 2)) { goto cleanup; } ASN1_INTEGER_set(X509_get_serialNumber(new_cert), serial); X509_set_subject_name(new_cert, X509_REQ_get_subject_name(pcsr->csr())); if (cert == nullptr) { cert = new_cert; } if (!X509_set_issuer_name(new_cert, X509_get_subject_name(cert))) { goto cleanup; } X509_gmtime_adj(X509_get_notBefore(new_cert), 0); X509_gmtime_adj(X509_get_notAfter(new_cert), (long)60 * 60 * 24 * days); i = X509_set_pubkey(new_cert, key); if (!i) { goto cleanup; } if (req.extensions_section) { X509V3_CTX ctx; X509V3_set_ctx(&ctx, cert, new_cert, pcsr->csr(), nullptr, 0); X509V3_set_conf_lhash(&ctx, req.req_config); if (!X509V3_EXT_add_conf(req.req_config, &ctx, (char*)req.extensions_section, new_cert)) { goto cleanup; } } /* Now sign it */ if (!X509_sign(new_cert, pkey, req.digest)) { raise_warning("failed to sign it"); goto cleanup; } /* Succeeded; lets return the cert */ ret = onewcert; cleanup: php_openssl_dispose_config(&req); return ret; } Variant HHVM_FUNCTION(openssl_error_string) { char buf[512]; unsigned long val = ERR_get_error(); if (val) { return String(ERR_error_string(val, buf), CopyString); } return false; } bool HHVM_FUNCTION(openssl_open, const String& sealed_data, Variant& open_data, const String& env_key, const Variant& priv_key_id, const String& method, /* = null_string */ const String& iv /* = null_string */) { const EVP_CIPHER *cipher_type; if (method.empty()) { cipher_type = EVP_rc4(); } else { cipher_type = EVP_get_cipherbyname(method.c_str()); if (!cipher_type) { raise_warning("Unknown cipher algorithm"); return false; } } auto okey = Key::Get(priv_key_id, false); if (!okey) { raise_warning("unable to coerce parameter 4 into a private key"); return false; } EVP_PKEY *pkey = okey->m_key; const unsigned char *iv_buf = nullptr; int iv_len = EVP_CIPHER_iv_length(cipher_type); if (iv_len > 0) { if (iv.empty()) { raise_warning( "Cipher algorithm requires an IV to be supplied as a sixth parameter"); return false; } if (iv.length() != iv_len) { raise_warning("IV length is invalid"); return false; } iv_buf = reinterpret_cast<const unsigned char*>(iv.c_str()); } String s = String(sealed_data.size(), ReserveString); unsigned char *buf = (unsigned char *)s.mutableData(); EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new(); if (ctx == nullptr) { raise_warning("Failed to allocate an EVP_CIPHER_CTX object"); return false; } SCOPE_EXIT { EVP_CIPHER_CTX_free(ctx); }; int len1, len2; if (!EVP_OpenInit( ctx, cipher_type, (unsigned char*)env_key.data(), env_key.size(), iv_buf, pkey) || !EVP_OpenUpdate( ctx, buf, &len1, (unsigned char*)sealed_data.data(), sealed_data.size()) || !EVP_OpenFinal(ctx, buf + len1, &len2) || len1 + len2 == 0) { return false; } open_data = s.setSize(len1 + len2); return true; } static STACK_OF(X509) *php_array_to_X509_sk(const Variant& certs) { STACK_OF(X509) *pcerts = sk_X509_new_null(); Array arrCerts; if (certs.isArray()) { arrCerts = certs.toArray(); } else { arrCerts.append(certs); } for (ArrayIter iter(arrCerts); iter; ++iter) { auto ocert = Certificate::Get(iter.second()); if (!ocert) { break; } sk_X509_push(pcerts, ocert->m_cert); } return pcerts; } const StaticString s_friendly_name("friendly_name"), s_extracerts("extracerts"); static bool openssl_pkcs12_export_impl(const Variant& x509, BIO *bio_out, const Variant& priv_key, const String& pass, const Variant& args /* = uninit_variant */) { auto ocert = Certificate::Get(x509); if (!ocert) { raise_warning("cannot get cert from parameter 1"); return false; } auto okey = Key::Get(priv_key, false); if (!okey) { raise_warning("cannot get private key from parameter 3"); return false; } X509 *cert = ocert->m_cert; EVP_PKEY *key = okey->m_key; if (cert && !X509_check_private_key(cert, key)) { raise_warning("private key does not correspond to cert"); return false; } Array arrArgs = args.toArray(); String friendly_name; if (arrArgs.exists(s_friendly_name)) { friendly_name = arrArgs[s_friendly_name].toString(); } STACK_OF(X509) *ca = nullptr; if (arrArgs.exists(s_extracerts)) { ca = php_array_to_X509_sk(arrArgs[s_extracerts]); } PKCS12 *p12 = PKCS12_create ((char*)pass.data(), (char*)(friendly_name.empty() ? nullptr : friendly_name.data()), key, cert, ca, 0, 0, 0, 0, 0); assertx(bio_out); bool ret = i2d_PKCS12_bio(bio_out, p12); PKCS12_free(p12); sk_X509_free(ca); return ret; } bool HHVM_FUNCTION(openssl_pkcs12_export_to_file, const Variant& x509, const String& filename, const Variant& priv_key, const String& pass, const Variant& args /* = uninit_variant */) { BIO *bio_out = BIO_new_file(filename.data(), "w"); if (bio_out == nullptr) { raise_warning("error opening file %s", filename.data()); return false; } bool ret = openssl_pkcs12_export_impl(x509, bio_out, priv_key, pass, args); BIO_free(bio_out); return ret; } bool HHVM_FUNCTION(openssl_pkcs12_export, const Variant& x509, Variant& out, const Variant& priv_key, const String& pass, const Variant& args /* = uninit_variant */) { BIO *bio_out = BIO_new(BIO_s_mem()); bool ret = openssl_pkcs12_export_impl(x509, bio_out, priv_key, pass, args); if (ret) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); out = String((char*)bio_buf->data, bio_buf->length, CopyString); } BIO_free(bio_out); return ret; } const StaticString s_cert("cert"), s_pkey("pkey"); bool HHVM_FUNCTION(openssl_pkcs12_read, const String& pkcs12, Variant& certs, const String& pass) { bool ret = false; PKCS12 *p12 = nullptr; BIO *bio_in = BIO_new(BIO_s_mem()); if (!BIO_write(bio_in, pkcs12.data(), pkcs12.size())) { goto cleanup; } if (d2i_PKCS12_bio(bio_in, &p12)) { EVP_PKEY *pkey = nullptr; X509 *cert = nullptr; STACK_OF(X509) *ca = nullptr; if (PKCS12_parse(p12, pass.data(), &pkey, &cert, &ca)) { Variant vcerts = Array::CreateDArray(); SCOPE_EXIT { certs = vcerts; }; BIO *bio_out = nullptr; if (cert) { bio_out = BIO_new(BIO_s_mem()); if (PEM_write_bio_X509(bio_out, cert)) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); vcerts.asArrRef().set(s_cert, String((char*)bio_buf->data, bio_buf->length, CopyString)); } BIO_free(bio_out); } if (pkey) { bio_out = BIO_new(BIO_s_mem()); if (PEM_write_bio_PrivateKey(bio_out, pkey, nullptr, nullptr, 0, 0, nullptr)) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); vcerts.asArrRef().set(s_pkey, String((char*)bio_buf->data, bio_buf->length, CopyString)); } BIO_free(bio_out); } if (ca) { Array extracerts; for (X509 *aCA = sk_X509_pop(ca); aCA; aCA = sk_X509_pop(ca)) { bio_out = BIO_new(BIO_s_mem()); if (PEM_write_bio_X509(bio_out, aCA)) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); extracerts.append(String((char*)bio_buf->data, bio_buf->length, CopyString)); } BIO_free(bio_out); X509_free(aCA); } sk_X509_free(ca); vcerts.asArrRef().set(s_extracerts, extracerts); } ret = true; PKCS12_free(p12); } } cleanup: if (bio_in) { BIO_free(bio_in); } return ret; } bool HHVM_FUNCTION(openssl_pkcs7_decrypt, const String& infilename, const String& outfilename, const Variant& recipcert, const Variant& recipkey /* = uninit_variant */) { bool ret = false; BIO *in = nullptr, *out = nullptr, *datain = nullptr; PKCS7 *p7 = nullptr; req::ptr<Key> okey; auto ocert = Certificate::Get(recipcert); if (!ocert) { raise_warning("unable to coerce parameter 3 to x509 cert"); goto clean_exit; } okey = Key::Get(recipkey.isNull() ? recipcert : recipkey, false); if (!okey) { raise_warning("unable to get private key"); goto clean_exit; } in = BIO_new_file(infilename.data(), "r"); if (in == nullptr) { raise_warning("error opening the file, %s", infilename.data()); goto clean_exit; } out = BIO_new_file(outfilename.data(), "w"); if (out == nullptr) { raise_warning("error opening the file, %s", outfilename.data()); goto clean_exit; } p7 = SMIME_read_PKCS7(in, &datain); if (p7 == nullptr) { goto clean_exit; } assertx(okey->m_key); assertx(ocert->m_cert); if (PKCS7_decrypt(p7, okey->m_key, ocert->m_cert, out, PKCS7_DETACHED)) { ret = true; } clean_exit: PKCS7_free(p7); BIO_free(datain); BIO_free(in); BIO_free(out); return ret; } static void print_headers(BIO *outfile, const Array& headers) { if (!headers.isNull()) { if (headers->isVectorData()) { for (ArrayIter iter(headers); iter; ++iter) { BIO_printf(outfile, "%s\n", iter.second().toString().data()); } } else { for (ArrayIter iter(headers); iter; ++iter) { BIO_printf(outfile, "%s: %s\n", iter.first().toString().data(), iter.second().toString().data()); } } } } bool HHVM_FUNCTION(openssl_pkcs7_encrypt, const String& infilename, const String& outfilename, const Variant& recipcerts, const Array& headers, int flags /* = 0 */, int cipherid /* = k_OPENSSL_CIPHER_RC2_40 */) { bool ret = false; BIO *infile = nullptr, *outfile = nullptr; STACK_OF(X509) *precipcerts = nullptr; PKCS7 *p7 = nullptr; const EVP_CIPHER *cipher = nullptr; infile = BIO_new_file(infilename.data(), (flags & PKCS7_BINARY) ? "rb" : "r"); if (infile == nullptr) { raise_warning("error opening the file, %s", infilename.data()); goto clean_exit; } outfile = BIO_new_file(outfilename.data(), "w"); if (outfile == nullptr) { raise_warning("error opening the file, %s", outfilename.data()); goto clean_exit; } precipcerts = php_array_to_X509_sk(recipcerts); /* sanity check the cipher */ switch (cipherid) { #ifndef OPENSSL_NO_RC2 case PHP_OPENSSL_CIPHER_RC2_40: cipher = EVP_rc2_40_cbc(); break; case PHP_OPENSSL_CIPHER_RC2_64: cipher = EVP_rc2_64_cbc(); break; case PHP_OPENSSL_CIPHER_RC2_128: cipher = EVP_rc2_cbc(); break; #endif #ifndef OPENSSL_NO_DES case PHP_OPENSSL_CIPHER_DES: cipher = EVP_des_cbc(); break; case PHP_OPENSSL_CIPHER_3DES: cipher = EVP_des_ede3_cbc(); break; #endif default: raise_warning("Invalid cipher type `%d'", cipherid); goto clean_exit; } if (cipher == nullptr) { raise_warning("Failed to get cipher"); goto clean_exit; } p7 = PKCS7_encrypt(precipcerts, infile, (EVP_CIPHER*)cipher, flags); if (p7 == nullptr) goto clean_exit; print_headers(outfile, headers); (void)BIO_reset(infile); SMIME_write_PKCS7(outfile, p7, infile, flags); ret = true; clean_exit: PKCS7_free(p7); BIO_free(infile); BIO_free(outfile); sk_X509_free(precipcerts); return ret; } bool HHVM_FUNCTION(openssl_pkcs7_sign, const String& infilename, const String& outfilename, const Variant& signcert, const Variant& privkey, const Variant& headers, int flags /* = k_PKCS7_DETACHED */, const String& extracerts /* = null_string */) { bool ret = false; STACK_OF(X509) *others = nullptr; BIO *infile = nullptr, *outfile = nullptr; PKCS7 *p7 = nullptr; req::ptr<Key> okey; req::ptr<Certificate> ocert; if (!extracerts.empty()) { others = load_all_certs_from_file(extracerts.data()); if (others == nullptr) { goto clean_exit; } } okey = Key::Get(privkey, false); if (!okey) { raise_warning("error getting private key"); goto clean_exit; } EVP_PKEY *key; key = okey->m_key; ocert = Certificate::Get(signcert); if (!ocert) { raise_warning("error getting cert"); goto clean_exit; } X509 *cert; cert = ocert->m_cert; infile = BIO_new_file(infilename.data(), (flags & PKCS7_BINARY) ? "rb" : "r"); if (infile == nullptr) { raise_warning("error opening input file %s!", infilename.data()); goto clean_exit; } outfile = BIO_new_file(outfilename.data(), "w"); if (outfile == nullptr) { raise_warning("error opening output file %s!", outfilename.data()); goto clean_exit; } p7 = PKCS7_sign(cert, key, others, infile, flags); if (p7 == nullptr) { raise_warning("error creating PKCS7 structure!"); goto clean_exit; } print_headers(outfile, headers.toArray()); (void)BIO_reset(infile); SMIME_write_PKCS7(outfile, p7, infile, flags); ret = true; clean_exit: PKCS7_free(p7); BIO_free(infile); BIO_free(outfile); if (others) { sk_X509_pop_free(others, X509_free); } return ret; } static int pkcs7_ignore_expiration(int ok, X509_STORE_CTX *ctx) { if (ok) { return ok; } int error = X509_STORE_CTX_get_error(ctx); if (error == X509_V_ERR_CERT_HAS_EXPIRED) { // ignore cert expirations Logger::Verbose("Ignoring cert expiration"); return 1; } return ok; } /** * NOTE: when ignore_cert_expiration is true, a custom certificate validation * callback is set up. Please be aware of this if you modify the function to * allow other certificate validation behaviors */ Variant openssl_pkcs7_verify_core( const String& filename, int flags, const Variant& voutfilename /* = null_string */, const Variant& vcainfo /* = null_array */, const Variant& vextracerts /* = null_string */, const Variant& vcontent /* = null_string */, bool ignore_cert_expiration ) { Variant ret = -1; X509_STORE *store = nullptr; BIO *in = nullptr; PKCS7 *p7 = nullptr; BIO *datain = nullptr; BIO *dataout = nullptr; auto cainfo = vcainfo.toArray(); auto extracerts = vextracerts.toString(); auto content = vcontent.toString(); STACK_OF(X509) *others = nullptr; if (!extracerts.empty()) { others = load_all_certs_from_file(extracerts.data()); if (others == nullptr) { goto clean_exit; } } flags = flags & ~PKCS7_DETACHED; store = setup_verify(cainfo); if (!store) { goto clean_exit; } if (ignore_cert_expiration) { #if (OPENSSL_VERSION_NUMBER >= 0x10000000) // make sure no other callback is specified #if OPENSSL_VERSION_NUMBER >= 0x10100000L assertx(!X509_STORE_get_verify_cb(store)); #else assertx(!store->verify_cb); #endif // ignore expired certs X509_STORE_set_verify_cb(store, pkcs7_ignore_expiration); #else always_assert(false); #endif } in = BIO_new_file(filename.data(), (flags & PKCS7_BINARY) ? "rb" : "r"); if (in == nullptr) { raise_warning("error opening the file, %s", filename.data()); goto clean_exit; } p7 = SMIME_read_PKCS7(in, &datain); if (p7 == nullptr) { goto clean_exit; } if (!content.empty()) { dataout = BIO_new_file(content.data(), "w"); if (dataout == nullptr) { raise_warning("error opening the file, %s", content.data()); goto clean_exit; } } if (PKCS7_verify(p7, others, store, datain, dataout, flags)) { ret = true; auto outfilename = voutfilename.toString(); if (!outfilename.empty()) { BIO *certout = BIO_new_file(outfilename.data(), "w"); if (certout) { STACK_OF(X509) *signers = PKCS7_get0_signers(p7, nullptr, flags); for (int i = 0; i < sk_X509_num(signers); i++) { PEM_write_bio_X509(certout, sk_X509_value(signers, i)); } BIO_free(certout); sk_X509_free(signers); } else { raise_warning("signature OK, but cannot open %s for writing", outfilename.data()); ret = -1; } } goto clean_exit; } else { ret = false; } clean_exit: X509_STORE_free(store); BIO_free(datain); BIO_free(in); BIO_free(dataout); PKCS7_free(p7); sk_X509_pop_free(others, X509_free); return ret; } Variant HHVM_FUNCTION(openssl_pkcs7_verify, const String& filename, int flags, const Variant& voutfilename /* = null_string */, const Variant& vcainfo /* = null_array */, const Variant& vextracerts /* = null_string */, const Variant& vcontent /* = null_string */) { return openssl_pkcs7_verify_core(filename, flags, voutfilename, vcainfo, vextracerts, vcontent, false); } static bool openssl_pkey_export_impl(const Variant& key, BIO *bio_out, const String& passphrase /* = null_string */, const Variant& configargs /* = uninit_variant */) { auto okey = Key::Get(key, false, passphrase.data()); if (!okey) { raise_warning("cannot get key from parameter 1"); return false; } EVP_PKEY *pkey = okey->m_key; struct php_x509_request req; memset(&req, 0, sizeof(req)); std::vector<String> strings; bool ret = false; if (php_openssl_parse_config(&req, configargs.toArray(), strings)) { const EVP_CIPHER *cipher; if (!passphrase.empty() && req.priv_key_encrypt) { cipher = (EVP_CIPHER *)EVP_des_ede3_cbc(); } else { cipher = nullptr; } assertx(bio_out); switch (EVP_PKEY_id(pkey)) { #ifdef HAVE_EVP_PKEY_EC case EVP_PKEY_EC: ret = PEM_write_bio_ECPrivateKey(bio_out, EVP_PKEY_get0_EC_KEY(pkey), cipher, (unsigned char *)passphrase.data(), passphrase.size(), nullptr, nullptr); break; #endif default: ret = PEM_write_bio_PrivateKey(bio_out, pkey, cipher, (unsigned char *)passphrase.data(), passphrase.size(), nullptr, nullptr); break; } } php_openssl_dispose_config(&req); return ret; } bool HHVM_FUNCTION(openssl_pkey_export_to_file, const Variant& key, const String& outfilename, const String& passphrase /* = null_string */, const Variant& configargs /* = uninit_variant */) { BIO *bio_out = BIO_new_file(outfilename.data(), "w"); if (bio_out == nullptr) { raise_warning("error opening the file, %s", outfilename.data()); return false; } bool ret = openssl_pkey_export_impl(key, bio_out, passphrase, configargs); BIO_free(bio_out); return ret; } bool HHVM_FUNCTION(openssl_pkey_export, const Variant& key, Variant& out, const String& passphrase /* = null_string */, const Variant& configargs /* = uninit_variant */) { BIO *bio_out = BIO_new(BIO_s_mem()); bool ret = openssl_pkey_export_impl(key, bio_out, passphrase, configargs); if (ret) { char *bio_mem_ptr; long bio_mem_len = BIO_get_mem_data(bio_out, &bio_mem_ptr); out = String(bio_mem_ptr, bio_mem_len, CopyString); } BIO_free(bio_out); return ret; } const StaticString s_bits("bits"), s_key("key"), s_type("type"), s_name("name"), s_hash("hash"), s_version("version"), s_serialNumber("serialNumber"), s_signatureAlgorithm("signatureAlgorithm"), s_validFrom("validFrom"), s_validTo("validTo"), s_validFrom_time_t("validFrom_time_t"), s_validTo_time_t("validTo_time_t"), s_alias("alias"), s_purposes("purposes"), s_extensions("extensions"), s_rsa("rsa"), s_dsa("dsa"), s_dh("dh"), s_ec("ec"), s_n("n"), s_e("e"), s_d("d"), s_p("p"), s_q("q"), s_g("g"), s_x("x"), s_y("y"), s_dmp1("dmp1"), s_dmq1("dmq1"), s_iqmp("iqmp"), s_priv_key("priv_key"), s_pub_key("pub_key"), s_curve_oid("curve_oid"); static void add_bignum_as_string(Array &arr, StaticString key, const BIGNUM *bn) { if (!bn) { return; } int num_bytes = BN_num_bytes(bn); String str{size_t(num_bytes), ReserveString}; BN_bn2bin(bn, (unsigned char*)str.mutableData()); str.setSize(num_bytes); arr.set(key, std::move(str)); } Array HHVM_FUNCTION(openssl_pkey_get_details, const Resource& key) { EVP_PKEY *pkey = cast<Key>(key)->m_key; BIO *out = BIO_new(BIO_s_mem()); PEM_write_bio_PUBKEY(out, pkey); char *pbio; unsigned int pbio_len = BIO_get_mem_data(out, &pbio); auto ret = make_darray( s_bits, EVP_PKEY_bits(pkey), s_key, String(pbio, pbio_len, CopyString) ); long ktype = -1; auto details = Array::CreateDArray(); switch (EVP_PKEY_id(pkey)) { case EVP_PKEY_RSA: case EVP_PKEY_RSA2: { ktype = OPENSSL_KEYTYPE_RSA; RSA *rsa = EVP_PKEY_get0_RSA(pkey); assertx(rsa); const BIGNUM *n, *e, *d, *p, *q, *dmp1, *dmq1, *iqmp; RSA_get0_key(rsa, &n, &e, &d); RSA_get0_factors(rsa, &p, &q); RSA_get0_crt_params(rsa, &dmp1, &dmq1, &iqmp); add_bignum_as_string(details, s_n, n); add_bignum_as_string(details, s_e, e); add_bignum_as_string(details, s_d, d); add_bignum_as_string(details, s_p, p); add_bignum_as_string(details, s_q, q); add_bignum_as_string(details, s_dmp1, dmp1); add_bignum_as_string(details, s_dmq1, dmq1); add_bignum_as_string(details, s_iqmp, iqmp); ret.set(s_rsa, details); break; } case EVP_PKEY_DSA: case EVP_PKEY_DSA2: case EVP_PKEY_DSA3: case EVP_PKEY_DSA4: { ktype = OPENSSL_KEYTYPE_DSA; DSA *dsa = EVP_PKEY_get0_DSA(pkey); assertx(dsa); const BIGNUM *p, *q, *g, *pub_key, *priv_key; DSA_get0_pqg(dsa, &p, &q, &g); DSA_get0_key(dsa, &pub_key, &priv_key); add_bignum_as_string(details, s_p, p); add_bignum_as_string(details, s_q, q); add_bignum_as_string(details, s_g, g); add_bignum_as_string(details, s_priv_key, priv_key); add_bignum_as_string(details, s_pub_key, pub_key); ret.set(s_dsa, details); break; } case EVP_PKEY_DH: { ktype = OPENSSL_KEYTYPE_DH; DH *dh = EVP_PKEY_get0_DH(pkey); assertx(dh); const BIGNUM *p, *q, *g, *pub_key, *priv_key; DH_get0_pqg(dh, &p, &q, &g); DH_get0_key(dh, &pub_key, &priv_key); add_bignum_as_string(details, s_p, p); add_bignum_as_string(details, s_g, g); add_bignum_as_string(details, s_priv_key, priv_key); add_bignum_as_string(details, s_pub_key, pub_key); ret.set(s_dh, details); break; } #ifdef HAVE_EVP_PKEY_EC case EVP_PKEY_EC: { ktype = OPENSSL_KEYTYPE_EC; auto const ec = EVP_PKEY_get0_EC_KEY(pkey); assertx(ec); auto const ec_group = EC_KEY_get0_group(ec); auto const nid = EC_GROUP_get_curve_name(ec_group); if (nid == NID_undef) { break; } auto const crv_sn = OBJ_nid2sn(nid); if (crv_sn != nullptr) { details.set(s_curve_name, String(crv_sn, CopyString)); } auto const obj = OBJ_nid2obj(nid); if (obj != nullptr) { SCOPE_EXIT { ASN1_OBJECT_free(obj); }; char oir_buf[256]; OBJ_obj2txt(oir_buf, sizeof(oir_buf) - 1, obj, 1); details.set(s_curve_oid, String(oir_buf, CopyString)); } auto x = BN_new(); auto y = BN_new(); SCOPE_EXIT { BN_free(x); BN_free(y); }; auto const pub = EC_KEY_get0_public_key(ec); if (EC_POINT_get_affine_coordinates_GFp(ec_group, pub, x, y, nullptr)) { add_bignum_as_string(details, s_x, x); add_bignum_as_string(details, s_y, y); } auto d = BN_dup(EC_KEY_get0_private_key(ec)); SCOPE_EXIT { BN_free(d); }; if (d != nullptr) { add_bignum_as_string(details, s_d, d); } ret.set(s_ec, details); } break; #endif } ret.set(s_type, ktype); BIO_free(out); return ret; } Variant HHVM_FUNCTION(openssl_pkey_get_private, const Variant& key, const String& passphrase /* = null_string */) { return toVariant(Key::Get(key, false, passphrase.data())); } Variant HHVM_FUNCTION(openssl_pkey_get_public, const Variant& certificate) { return toVariant(Key::Get(certificate, true)); } Variant HHVM_FUNCTION(openssl_pkey_new, const Variant& configargs /* = uninit_variant */) { struct php_x509_request req; memset(&req, 0, sizeof(req)); SCOPE_EXIT { php_openssl_dispose_config(&req); }; std::vector<String> strings; if (php_openssl_parse_config(&req, configargs.toArray(), strings) && req.generatePrivateKey()) { return Resource(req::make<Key>(req.priv_key)); } else { return false; } } bool HHVM_FUNCTION(openssl_private_decrypt, const String& data, Variant& decrypted, const Variant& key, int padding /* = k_OPENSSL_PKCS1_PADDING */) { auto okey = Key::Get(key, false); if (!okey) { raise_warning("key parameter is not a valid private key"); return false; } EVP_PKEY *pkey = okey->m_key; int cryptedlen = EVP_PKEY_size(pkey); String s = String(cryptedlen, ReserveString); unsigned char *cryptedbuf = (unsigned char *)s.mutableData(); int successful = 0; switch (EVP_PKEY_id(pkey)) { case EVP_PKEY_RSA: case EVP_PKEY_RSA2: cryptedlen = RSA_private_decrypt(data.size(), (unsigned char *)data.data(), cryptedbuf, EVP_PKEY_get0_RSA(pkey), padding); if (cryptedlen != -1) { successful = 1; } break; default: raise_warning("key type not supported"); } if (successful) { decrypted = s.setSize(cryptedlen); return true; } return false; } bool HHVM_FUNCTION(openssl_private_encrypt, const String& data, Variant& crypted, const Variant& key, int padding /* = k_OPENSSL_PKCS1_PADDING */) { auto okey = Key::Get(key, false); if (!okey) { raise_warning("key param is not a valid private key"); return false; } EVP_PKEY *pkey = okey->m_key; int cryptedlen = EVP_PKEY_size(pkey); String s = String(cryptedlen, ReserveString); unsigned char *cryptedbuf = (unsigned char *)s.mutableData(); int successful = 0; switch (EVP_PKEY_id(pkey)) { case EVP_PKEY_RSA: case EVP_PKEY_RSA2: successful = (RSA_private_encrypt(data.size(), (unsigned char *)data.data(), cryptedbuf, EVP_PKEY_get0_RSA(pkey), padding) == cryptedlen); break; default: raise_warning("key type not supported"); } if (successful) { crypted = s.setSize(cryptedlen); return true; } return false; } bool HHVM_FUNCTION(openssl_public_decrypt, const String& data, Variant& decrypted, const Variant& key, int padding /* = k_OPENSSL_PKCS1_PADDING */) { auto okey = Key::Get(key, true); if (!okey) { raise_warning("key parameter is not a valid public key"); return false; } EVP_PKEY *pkey = okey->m_key; int cryptedlen = EVP_PKEY_size(pkey); String s = String(cryptedlen, ReserveString); unsigned char *cryptedbuf = (unsigned char *)s.mutableData(); int successful = 0; switch (EVP_PKEY_id(pkey)) { case EVP_PKEY_RSA: case EVP_PKEY_RSA2: cryptedlen = RSA_public_decrypt(data.size(), (unsigned char *)data.data(), cryptedbuf, EVP_PKEY_get0_RSA(pkey), padding); if (cryptedlen != -1) { successful = 1; } break; default: raise_warning("key type not supported"); } if (successful) { decrypted = s.setSize(cryptedlen); return true; } return false; } bool HHVM_FUNCTION(openssl_public_encrypt, const String& data, Variant& crypted, const Variant& key, int padding /* = k_OPENSSL_PKCS1_PADDING */) { auto okey = Key::Get(key, true); if (!okey) { raise_warning("key parameter is not a valid public key"); return false; } EVP_PKEY *pkey = okey->m_key; int cryptedlen = EVP_PKEY_size(pkey); String s = String(cryptedlen, ReserveString); unsigned char *cryptedbuf = (unsigned char *)s.mutableData(); int successful = 0; switch (EVP_PKEY_id(pkey)) { case EVP_PKEY_RSA: case EVP_PKEY_RSA2: successful = (RSA_public_encrypt(data.size(), (unsigned char *)data.data(), cryptedbuf, EVP_PKEY_get0_RSA(pkey), padding) == cryptedlen); break; default: raise_warning("key type not supported"); } if (successful) { crypted = s.setSize(cryptedlen); return true; } return false; } Variant HHVM_FUNCTION(openssl_seal, const String& data, Variant& sealed_data, Variant& env_keys, const Array& pub_key_ids, const String& method, Variant& iv) { int nkeys = pub_key_ids.size(); if (nkeys == 0) { raise_warning("Fourth argument to openssl_seal() must be " "a non-empty array"); return false; } const EVP_CIPHER *cipher_type; if (method.empty()) { cipher_type = EVP_rc4(); } else { cipher_type = EVP_get_cipherbyname(method.c_str()); if (!cipher_type) { raise_warning("Unknown cipher algorithm"); return false; } } int iv_len = EVP_CIPHER_iv_length(cipher_type); unsigned char *iv_buf = nullptr; String iv_s; if (iv_len > 0) { iv_s = String(iv_len, ReserveString); iv_buf = (unsigned char*)iv_s.mutableData(); if (!RAND_bytes(iv_buf, iv_len)) { raise_warning("Could not generate an IV."); return false; } } EVP_PKEY **pkeys = (EVP_PKEY**)malloc(nkeys * sizeof(*pkeys)); int *eksl = (int*)malloc(nkeys * sizeof(*eksl)); unsigned char **eks = (unsigned char **)malloc(nkeys * sizeof(*eks)); memset(eks, 0, sizeof(*eks) * nkeys); // holder is needed to make sure none of the Keys get deleted prematurely. // The pkeys array points to elements inside of Keys returned from Key::Get() // which may be newly allocated and have no other owners. std::vector<req::ptr<Key>> holder; /* get the public keys we are using to seal this data */ bool ret = true; int i = 0; String s; unsigned char* buf = nullptr; EVP_CIPHER_CTX* ctx = nullptr; for (ArrayIter iter(pub_key_ids); iter; ++iter, ++i) { auto okey = Key::Get(iter.second(), true); if (!okey) { raise_warning("not a public key (%dth member of pubkeys)", i + 1); ret = false; goto clean_exit; } holder.push_back(okey); pkeys[i] = okey->m_key; eks[i] = (unsigned char *)malloc(EVP_PKEY_size(pkeys[i]) + 1); } ctx = EVP_CIPHER_CTX_new(); if (ctx == nullptr) { raise_warning("Failed to allocate an EVP_CIPHER_CTX object"); ret = false; goto clean_exit; } if (!EVP_EncryptInit_ex(ctx, cipher_type, nullptr, nullptr, nullptr)) { ret = false; goto clean_exit; } int len1, len2; s = String(data.size() + EVP_CIPHER_CTX_block_size(ctx), ReserveString); buf = (unsigned char *)s.mutableData(); if (EVP_SealInit(ctx, cipher_type, eks, eksl, iv_buf, pkeys, nkeys) <= 0 || !EVP_SealUpdate(ctx, buf, &len1, (unsigned char*)data.data(), data.size()) || !EVP_SealFinal(ctx, buf + len1, &len2)) { ret = false; goto clean_exit; } if (len1 + len2 > 0) { sealed_data = s.setSize(len1 + len2); auto ekeys = Array::CreateVArray(); for (i = 0; i < nkeys; i++) { eks[i][eksl[i]] = '\0'; ekeys.append(String((char*)eks[i], eksl[i], AttachString)); eks[i] = nullptr; } env_keys = ekeys; } clean_exit: for (i = 0; i < nkeys; i++) { if (eks[i]) free(eks[i]); } free(eks); free(eksl); free(pkeys); if (iv_buf != nullptr) { if (ret) { iv = iv_s.setSize(iv_len); } } if (ctx != nullptr) { EVP_CIPHER_CTX_free(ctx); } if (ret) return len1 + len2; return false; } static const EVP_MD *php_openssl_get_evp_md_from_algo(long algo) { switch (algo) { case OPENSSL_ALGO_SHA1: return EVP_sha1(); case OPENSSL_ALGO_MD5: return EVP_md5(); case OPENSSL_ALGO_MD4: return EVP_md4(); #ifdef HAVE_OPENSSL_MD2_H case OPENSSL_ALGO_MD2: return EVP_md2(); #endif #if OPENSSL_VERSION_NUMBER < 0x10100000L case OPENSSL_ALGO_DSS1: return EVP_dss1(); #endif #if OPENSSL_VERSION_NUMBER >= 0x0090708fL case OPENSSL_ALGO_SHA224: return EVP_sha224(); case OPENSSL_ALGO_SHA256: return EVP_sha256(); case OPENSSL_ALGO_SHA384: return EVP_sha384(); case OPENSSL_ALGO_SHA512: return EVP_sha512(); case OPENSSL_ALGO_RMD160: return EVP_ripemd160(); #endif } return nullptr; } bool HHVM_FUNCTION(openssl_sign, const String& data, Variant& signature, const Variant& priv_key_id, const Variant& signature_alg /* = k_OPENSSL_ALGO_SHA1 */) { auto okey = Key::Get(priv_key_id, false); if (!okey) { raise_warning("supplied key param cannot be coerced into a private key"); return false; } const EVP_MD *mdtype = nullptr; if (signature_alg.isInteger()) { mdtype = php_openssl_get_evp_md_from_algo(signature_alg.toInt64Val()); } else if (signature_alg.isString()) { mdtype = EVP_get_digestbyname(signature_alg.toString().data()); } if (!mdtype) { raise_warning("Unknown signature algorithm."); return false; } EVP_PKEY *pkey = okey->m_key; int siglen = EVP_PKEY_size(pkey); String s = String(siglen, ReserveString); unsigned char *sigbuf = (unsigned char *)s.mutableData(); EVP_MD_CTX *md_ctx = EVP_MD_CTX_new(); SCOPE_EXIT { EVP_MD_CTX_free(md_ctx); }; EVP_SignInit(md_ctx, mdtype); EVP_SignUpdate(md_ctx, (unsigned char *)data.data(), data.size()); if (EVP_SignFinal(md_ctx, sigbuf, (unsigned int *)&siglen, pkey)) { signature = s.setSize(siglen); return true; } return false; } Variant HHVM_FUNCTION(openssl_verify, const String& data, const String& signature, const Variant& pub_key_id, const Variant& signature_alg /* = k_OPENSSL_ALGO_SHA1 */) { int err; const EVP_MD *mdtype = nullptr; if (signature_alg.isInteger()) { mdtype = php_openssl_get_evp_md_from_algo(signature_alg.toInt64Val()); } else if (signature_alg.isString()) { mdtype = EVP_get_digestbyname(signature_alg.toString().data()); } if (!mdtype) { raise_warning("Unknown signature algorithm."); return false; } auto okey = Key::Get(pub_key_id, true); if (!okey) { raise_warning("supplied key param cannot be coerced into a public key"); return false; } EVP_MD_CTX *md_ctx = EVP_MD_CTX_new(); SCOPE_EXIT { EVP_MD_CTX_free(md_ctx); }; EVP_VerifyInit(md_ctx, mdtype); EVP_VerifyUpdate(md_ctx, (unsigned char*)data.data(), data.size()); err = EVP_VerifyFinal(md_ctx, (unsigned char *)signature.data(), signature.size(), okey->m_key); return err; } bool HHVM_FUNCTION(openssl_x509_check_private_key, const Variant& cert, const Variant& key) { auto ocert = Certificate::Get(cert); if (!ocert) { return false; } auto okey = Key::Get(key, false); if (!okey) { return false; } return X509_check_private_key(ocert->m_cert, okey->m_key); } static int check_cert(X509_STORE *ctx, X509 *x, STACK_OF(X509) *untrustedchain, int purpose) { X509_STORE_CTX *csc = X509_STORE_CTX_new(); if (csc == nullptr) { raise_warning("memory allocation failure"); return 0; } X509_STORE_CTX_init(csc, ctx, x, untrustedchain); if (purpose >= 0) { X509_STORE_CTX_set_purpose(csc, purpose); } int ret = X509_verify_cert(csc); X509_STORE_CTX_free(csc); return ret; } Variant HHVM_FUNCTION(openssl_x509_checkpurpose, const Variant& x509cert, int purpose, const Array& cainfo /* = null_array */, const String& untrustedfile /* = null_string */) { int ret = -1; STACK_OF(X509) *untrustedchain = nullptr; X509_STORE *pcainfo = nullptr; req::ptr<Certificate> ocert; if (!untrustedfile.empty()) { untrustedchain = load_all_certs_from_file(untrustedfile.data()); if (untrustedchain == nullptr) { goto clean_exit; } } pcainfo = setup_verify(cainfo); if (pcainfo == nullptr) { goto clean_exit; } ocert = Certificate::Get(x509cert); if (!ocert) { raise_warning("cannot get cert from parameter 1"); return false; } X509 *cert; cert = ocert->m_cert; assertx(cert); ret = check_cert(pcainfo, cert, untrustedchain, purpose); clean_exit: if (pcainfo) { X509_STORE_free(pcainfo); } if (untrustedchain) { sk_X509_pop_free(untrustedchain, X509_free); } return ret == 1 ? true : ret == 0 ? false : -1; } static bool openssl_x509_export_impl(const Variant& x509, BIO *bio_out, bool notext /* = true */) { auto ocert = Certificate::Get(x509); if (!ocert) { raise_warning("cannot get cert from parameter 1"); return false; } X509 *cert = ocert->m_cert; assertx(cert); assertx(bio_out); if (!notext) { X509_print(bio_out, cert); } return PEM_write_bio_X509(bio_out, cert); } bool HHVM_FUNCTION(openssl_x509_export_to_file, const Variant& x509, const String& outfilename, bool notext /* = true */) { BIO *bio_out = BIO_new_file((char*)outfilename.data(), "w"); if (bio_out == nullptr) { raise_warning("error opening file %s", outfilename.data()); return false; } bool ret = openssl_x509_export_impl(x509, bio_out, notext); BIO_free(bio_out); return ret; } bool HHVM_FUNCTION(openssl_x509_export, const Variant& x509, Variant& output, bool notext /* = true */) { BIO *bio_out = BIO_new(BIO_s_mem()); bool ret = openssl_x509_export_impl(x509, bio_out, notext); if (ret) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); output = String(bio_buf->data, bio_buf->length, CopyString); } BIO_free(bio_out); return ret; } /** * This is how the time string is formatted: * * snprintf(p, sizeof(p), "%02d%02d%02d%02d%02d%02dZ",ts->tm_year%100, * ts->tm_mon+1,ts->tm_mday,ts->tm_hour,ts->tm_min,ts->tm_sec); */ static time_t asn1_time_to_time_t(ASN1_UTCTIME *timestr) { auto const timestr_type = ASN1_STRING_type(timestr); if (timestr_type != V_ASN1_UTCTIME && timestr_type != V_ASN1_GENERALIZEDTIME) { raise_warning("illegal ASN1 data type for timestamp"); return (time_t)-1; } auto const timestr_len = (size_t)ASN1_STRING_length(timestr); // Binary safety if (timestr_len != strlen((char*)ASN1_STRING_data(timestr))) { raise_warning("illegal length in timestamp"); return (time_t)-1; } if (timestr_len < 13 && timestr_len != 11) { raise_warning("unable to parse time string %s correctly", timestr->data); return (time_t)-1; } if (timestr_type == V_ASN1_GENERALIZEDTIME && timestr_len < 15) { raise_warning("unable to parse time string %s correctly", timestr->data); return (time_t)-1; } char *strbuf = strdup((char*)timestr->data); struct tm thetime; memset(&thetime, 0, sizeof(thetime)); /* we work backwards so that we can use atoi more easily */ char *thestr = strbuf + ASN1_STRING_length(timestr) - 3; if (ASN1_STRING_length(timestr) == 11) { thetime.tm_sec = 0; } else { thetime.tm_sec = atoi(thestr); *thestr = '\0'; thestr -= 2; } thetime.tm_min = atoi(thestr); *thestr = '\0'; thestr -= 2; thetime.tm_hour = atoi(thestr); *thestr = '\0'; thestr -= 2; thetime.tm_mday = atoi(thestr); *thestr = '\0'; thestr -= 2; thetime.tm_mon = atoi(thestr)-1; *thestr = '\0'; if (ASN1_STRING_type(timestr) == V_ASN1_UTCTIME) { thestr -= 2; thetime.tm_year = atoi(thestr); if (thetime.tm_year < 68) { thetime.tm_year += 100; } } else if (ASN1_STRING_type(timestr) == V_ASN1_GENERALIZEDTIME) { thestr -= 4; thetime.tm_year = atoi(thestr) - 1900; } thetime.tm_isdst = -1; time_t ret = mktime(&thetime); long gmadjust = 0; #if HAVE_TM_GMTOFF gmadjust = thetime.tm_gmtoff; #elif defined(_MSC_VER) TIME_ZONE_INFORMATION inf; GetTimeZoneInformation(&inf); gmadjust = thetime.tm_isdst ? inf.DaylightBias : inf.StandardBias; #else /** * If correcting for daylight savings time, we set the adjustment to * the value of timezone - 3600 seconds. Otherwise, we need to overcorrect * and set the adjustment to the main timezone + 3600 seconds. */ gmadjust = -(thetime.tm_isdst ? (long)timezone - 3600 : (long)timezone); #endif /* no adjustment for UTC */ if (timezone) ret += gmadjust; free(strbuf); return ret; } /* Special handling of subjectAltName, see CVE-2013-4073 * Christian Heimes */ static int openssl_x509v3_subjectAltName(BIO *bio, X509_EXTENSION *extension) { GENERAL_NAMES *names; const X509V3_EXT_METHOD *method = nullptr; long i, length, num; const unsigned char *p; method = X509V3_EXT_get(extension); if (method == nullptr) { return -1; } const auto data = X509_EXTENSION_get_data(extension); p = data->data; length = data->length; if (method->it) { names = (GENERAL_NAMES*)(ASN1_item_d2i(nullptr, &p, length, ASN1_ITEM_ptr(method->it))); } else { names = (GENERAL_NAMES*)(method->d2i(nullptr, &p, length)); } if (names == nullptr) { return -1; } num = sk_GENERAL_NAME_num(names); for (i = 0; i < num; i++) { GENERAL_NAME *name; ASN1_STRING *as; name = sk_GENERAL_NAME_value(names, i); switch (name->type) { case GEN_EMAIL: BIO_puts(bio, "email:"); as = name->d.rfc822Name; BIO_write(bio, ASN1_STRING_data(as), ASN1_STRING_length(as)); break; case GEN_DNS: BIO_puts(bio, "DNS:"); as = name->d.dNSName; BIO_write(bio, ASN1_STRING_data(as), ASN1_STRING_length(as)); break; case GEN_URI: BIO_puts(bio, "URI:"); as = name->d.uniformResourceIdentifier; BIO_write(bio, ASN1_STRING_data(as), ASN1_STRING_length(as)); break; default: /* use builtin print for GEN_OTHERNAME, GEN_X400, * GEN_EDIPARTY, GEN_DIRNAME, GEN_IPADD and GEN_RID */ GENERAL_NAME_print(bio, name); } /* trailing ', ' except for last element */ if (i < (num - 1)) { BIO_puts(bio, ", "); } } sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free); return 0; } Variant HHVM_FUNCTION(openssl_x509_parse, const Variant& x509cert, bool shortnames /* = true */) { auto ocert = Certificate::Get(x509cert); if (!ocert) { return false; } X509 *cert = ocert->m_cert; assertx(cert); auto ret = Array::CreateDArray(); const auto sn = X509_get_subject_name(cert); if (sn) { ret.set(s_name, String(X509_NAME_oneline(sn, nullptr, 0), CopyString)); } add_assoc_name_entry(ret, "subject", sn, shortnames); /* hash as used in CA directories to lookup cert by subject name */ { char buf[32]; snprintf(buf, sizeof(buf), "%08lx", X509_subject_name_hash(cert)); ret.set(s_hash, String(buf, CopyString)); } add_assoc_name_entry(ret, "issuer", X509_get_issuer_name(cert), shortnames); ret.set(s_version, X509_get_version(cert)); ret.set(s_serialNumber, String (i2s_ASN1_INTEGER(nullptr, X509_get_serialNumber(cert)), AttachString)); // Adding Signature Algorithm BIO *bio_out = BIO_new(BIO_s_mem()); SCOPE_EXIT { BIO_free(bio_out); }; if (i2a_ASN1_OBJECT(bio_out, X509_get0_tbs_sigalg(cert)->algorithm) > 0) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); ret.set(s_signatureAlgorithm, String((char*)bio_buf->data, bio_buf->length, CopyString)); } ASN1_STRING *str = X509_get_notBefore(cert); ret.set(s_validFrom, String((char*)str->data, str->length, CopyString)); str = X509_get_notAfter(cert); ret.set(s_validTo, String((char*)str->data, str->length, CopyString)); ret.set(s_validFrom_time_t, asn1_time_to_time_t(X509_get_notBefore(cert))); ret.set(s_validTo_time_t, asn1_time_to_time_t(X509_get_notAfter(cert))); char *tmpstr = (char *)X509_alias_get0(cert, nullptr); if (tmpstr) { ret.set(s_alias, String(tmpstr, CopyString)); } /* NOTE: the purposes are added as integer keys - the keys match up to the X509_PURPOSE_SSL_XXX defines in x509v3.h */ { Array subitem; for (int i = 0; i < X509_PURPOSE_get_count(); i++) { X509_PURPOSE *purp = X509_PURPOSE_get0(i); int id = X509_PURPOSE_get_id(purp); char * pname = shortnames ? X509_PURPOSE_get0_sname(purp) : X509_PURPOSE_get0_name(purp); auto subsub = make_varray( (bool)X509_check_purpose(cert, id, 0), (bool)X509_check_purpose(cert, id, 1), String(pname, CopyString) ); subitem.set(id, std::move(subsub)); } ret.set(s_purposes, subitem); } { auto subitem = Array::CreateDArray(); for (int i = 0; i < X509_get_ext_count(cert); i++) { int nid; X509_EXTENSION *extension = X509_get_ext(cert, i); char *extname; char buf[256]; nid = OBJ_obj2nid(X509_EXTENSION_get_object(extension)); if (nid != NID_undef) { extname = (char*)OBJ_nid2sn(OBJ_obj2nid (X509_EXTENSION_get_object(extension))); } else { OBJ_obj2txt(buf, sizeof(buf)-1, X509_EXTENSION_get_object(extension), 1); extname = buf; } BIO *bio_out = BIO_new(BIO_s_mem()); if (nid == NID_subject_alt_name) { if (openssl_x509v3_subjectAltName(bio_out, extension) == 0) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); subitem.set(String(extname, CopyString), String((char*)bio_buf->data, bio_buf->length, CopyString)); } else { BIO_free(bio_out); return false; } } else if (X509V3_EXT_print(bio_out, extension, 0, 0)) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); subitem.set(String(extname, CopyString), String((char*)bio_buf->data, bio_buf->length, CopyString)); } else { str = X509_EXTENSION_get_data(extension); subitem.set(String(extname, CopyString), String((char*)str->data, str->length, CopyString)); } BIO_free(bio_out); } ret.set(s_extensions, subitem); } return ret; } Variant HHVM_FUNCTION(openssl_x509_read, const Variant& x509certdata) { auto ocert = Certificate::Get(x509certdata); if (!ocert) { raise_warning("supplied parameter cannot be coerced into " "an X509 certificate!"); return false; } return Variant(ocert); } Variant HHVM_FUNCTION(openssl_random_pseudo_bytes, int length, bool& crypto_strong) { if (length <= 0) { return false; } unsigned char *buffer = nullptr; String s = String(length, ReserveString); buffer = (unsigned char *)s.mutableData(); if (RAND_bytes(buffer, length) <= 0) { crypto_strong = false; return false; } else { crypto_strong = true; s.setSize(length); return s; } } Variant HHVM_FUNCTION(openssl_cipher_iv_length, const String& method) { if (method.empty()) { raise_warning("Unknown cipher algorithm"); return false; } const EVP_CIPHER *cipher_type = EVP_get_cipherbyname(method.c_str()); if (!cipher_type) { raise_warning("Unknown cipher algorithm"); return false; } return EVP_CIPHER_iv_length(cipher_type); } /* Cipher mode info */ struct php_openssl_cipher_mode { /* Whether this mode uses authenticated encryption. True, for example, with the GCM and CCM modes */ bool is_aead; /* Whether this mode is a 'single run aead', meaning that DecryptFinal doesn't get called. For example, CCM mode is a single run aead mode. */ bool is_single_run_aead; /* The OpenSSL flag to get the computed tag, if this mode is aead. */ int aead_get_tag_flag; /* The OpenSSL flag to set the computed tag, if this mode is aead. */ int aead_set_tag_flag; /* The OpenSSL flag to set the IV length, if this mode is aead */ int aead_ivlen_flag; }; // initialize a php_openssl_cipher_mode corresponding to an EVP_CIPHER. static php_openssl_cipher_mode php_openssl_load_cipher_mode( const EVP_CIPHER* cipher_type) { php_openssl_cipher_mode mode = {}; switch (EVP_CIPHER_mode(cipher_type)) { #ifdef EVP_CIPH_GCM_MODE case EVP_CIPH_GCM_MODE: mode.is_aead = true; mode.is_single_run_aead = false; mode.aead_get_tag_flag = EVP_CTRL_GCM_GET_TAG; mode.aead_set_tag_flag = EVP_CTRL_GCM_SET_TAG; mode.aead_ivlen_flag = EVP_CTRL_GCM_SET_IVLEN; break; #endif #ifdef EVP_CIPH_CCM_MODE case EVP_CIPH_CCM_MODE: mode.is_aead = true; mode.is_single_run_aead = true; mode.aead_get_tag_flag = EVP_CTRL_CCM_GET_TAG; mode.aead_set_tag_flag = EVP_CTRL_CCM_SET_TAG; mode.aead_ivlen_flag = EVP_CTRL_CCM_SET_IVLEN; break; #endif default: break; } return mode; } static bool php_openssl_validate_iv( String piv, int iv_required_len, String& out, EVP_CIPHER_CTX* cipher_ctx, const php_openssl_cipher_mode* mode) { if (cipher_ctx == nullptr || mode == nullptr) { return false; } /* Best case scenario, user behaved */ if (piv.size() == iv_required_len) { out = std::move(piv); return true; } if (mode->is_aead) { if (EVP_CIPHER_CTX_ctrl( cipher_ctx, mode->aead_ivlen_flag, piv.size(), nullptr) != 1) { raise_warning( "Setting of IV length for AEAD mode failed, the expected length is " "%d bytes", iv_required_len); return false; } out = std::move(piv); return true; } String s = String(iv_required_len, ReserveString); char* iv_new = s.mutableData(); memset(iv_new, 0, iv_required_len); if (piv.size() <= 0) { /* BC behavior */ s.setSize(iv_required_len); out = std::move(s); return true; } if (piv.size() < iv_required_len) { raise_warning("IV passed is only %d bytes long, cipher " "expects an IV of precisely %d bytes, padding with \\0", piv.size(), iv_required_len); memcpy(iv_new, piv.data(), piv.size()); s.setSize(iv_required_len); out = std::move(s); return true; } raise_warning("IV passed is %d bytes long which is longer than the %d " "expected by selected cipher, truncating", piv.size(), iv_required_len); memcpy(iv_new, piv.data(), iv_required_len); s.setSize(iv_required_len); out = std::move(s); return true; } namespace { Variant openssl_encrypt_impl(const String& data, const String& method, const String& password, int options, const String& iv, Variant* tag_out, const String& aad, int tag_length) { const EVP_CIPHER *cipher_type = EVP_get_cipherbyname(method.c_str()); if (!cipher_type) { raise_warning("Unknown cipher algorithm"); return false; } EVP_CIPHER_CTX* cipher_ctx = EVP_CIPHER_CTX_new(); if (!cipher_ctx) { raise_warning("Failed to create cipher context"); return false; } SCOPE_EXIT { EVP_CIPHER_CTX_free(cipher_ctx); }; php_openssl_cipher_mode mode = php_openssl_load_cipher_mode(cipher_type); if (mode.is_aead && !tag_out) { raise_warning("Must call openssl_encrypt_with_tag when using an AEAD cipher"); return false; } int keylen = EVP_CIPHER_key_length(cipher_type); String key = password; /* * older openssl libraries can assert if the passed in password length is * less than keylen */ if (keylen > password.size()) { String s = String(keylen, ReserveString); char *keybuf = s.mutableData(); memset(keybuf, 0, keylen); memcpy(keybuf, password.data(), password.size()); key = s.setSize(keylen); } int max_iv_len = EVP_CIPHER_iv_length(cipher_type); if (iv.size() <= 0 && max_iv_len > 0 && !mode.is_aead) { raise_warning("Using an empty Initialization Vector (iv) is potentially " "insecure and not recommended"); } int result_len = 0; int outlen = data.size() + EVP_CIPHER_block_size(cipher_type); String rv = String(outlen, ReserveString); unsigned char *outbuf = (unsigned char*)rv.mutableData(); EVP_EncryptInit_ex(cipher_ctx, cipher_type, nullptr, nullptr, nullptr); String new_iv; // we do this after EncryptInit because validate_iv changes cipher_ctx for // aead modes (must be initialized first). if (!php_openssl_validate_iv( std::move(iv), max_iv_len, new_iv, cipher_ctx, &mode)) { return false; } // set the tag length for CCM mode/other modes that require tag lengths to // be set. if (mode.is_single_run_aead && !EVP_CIPHER_CTX_ctrl( cipher_ctx, mode.aead_set_tag_flag, tag_length, nullptr)) { raise_warning("Setting tag length failed"); return false; } if (password.size() > keylen) { EVP_CIPHER_CTX_set_key_length(cipher_ctx, password.size()); } EVP_EncryptInit_ex( cipher_ctx, nullptr, nullptr, (unsigned char*)key.data(), (unsigned char*)new_iv.data()); if (options & k_OPENSSL_ZERO_PADDING) { EVP_CIPHER_CTX_set_padding(cipher_ctx, 0); } // for single run aeads like CCM, we need to provide the length of the // plaintext before providing AAD or ciphertext. if (mode.is_single_run_aead && !EVP_EncryptUpdate( cipher_ctx, nullptr, &result_len, nullptr, data.size())) { raise_warning("Setting of data length failed"); return false; } // set up aad: if (mode.is_aead && !EVP_EncryptUpdate( cipher_ctx, nullptr, &result_len, (unsigned char*)aad.data(), aad.size())) { raise_warning("Setting of additional application data failed"); return false; } // OpenSSL before 0.9.8i asserts with size < 0 if (data.size() >= 0) { EVP_EncryptUpdate(cipher_ctx, outbuf, &result_len, (unsigned char *)data.data(), data.size()); } outlen = result_len; if (EVP_EncryptFinal_ex( cipher_ctx, (unsigned char*)outbuf + result_len, &result_len)) { outlen += result_len; rv.setSize(outlen); // Get tag if possible if (mode.is_aead) { String tagrv = String(tag_length, ReserveString); if (EVP_CIPHER_CTX_ctrl( cipher_ctx, mode.aead_get_tag_flag, tag_length, tagrv.mutableData()) == 1) { tagrv.setSize(tag_length); assertx(tag_out); *tag_out = tagrv; } else { raise_warning("Retrieving authentication tag failed"); return false; } } else if (tag_out) { raise_warning( "The authenticated tag cannot be provided for cipher that does not" " support AEAD"); } // Return encrypted data if (options & k_OPENSSL_RAW_DATA) { return rv; } else { return StringUtil::Base64Encode(rv); } } return false; } } // anonymous namespace Variant HHVM_FUNCTION(openssl_encrypt, const String& data, const String& method, const String& password, int options /* = 0 */, const String& iv /* = null_string */, const String& aad /* = null_string */, int tag_length /* = 16 */) { return openssl_encrypt_impl(data, method, password, options, iv, nullptr, aad, tag_length); } Variant HHVM_FUNCTION(openssl_encrypt_with_tag, const String& data, const String& method, const String& password, int options, const String& iv, Variant& tag_out, const String& aad /* = null_string */, int tag_length /* = 16 */) { return openssl_encrypt_impl(data, method, password, options, iv, &tag_out, aad, tag_length); } Variant HHVM_FUNCTION(openssl_decrypt, const String& data, const String& method, const String& password, int options /* = 0 */, const String& iv /* = null_string */, const String& tag /* = null_string */, const String& aad /* = null_string */) { const EVP_CIPHER *cipher_type = EVP_get_cipherbyname(method.c_str()); if (!cipher_type) { raise_warning("Unknown cipher algorithm"); return false; } EVP_CIPHER_CTX* cipher_ctx = EVP_CIPHER_CTX_new(); if (!cipher_ctx) { raise_warning("Failed to create cipher context"); return false; } SCOPE_EXIT { EVP_CIPHER_CTX_free(cipher_ctx); }; php_openssl_cipher_mode mode = php_openssl_load_cipher_mode(cipher_type); String decoded_data = data; if (!(options & k_OPENSSL_RAW_DATA)) { decoded_data = StringUtil::Base64Decode(data); } int keylen = EVP_CIPHER_key_length(cipher_type); String key = password; /* * older openssl libraries can assert if the passed in password length is * less than keylen */ if (keylen > password.size()) { String s = String(keylen, ReserveString); char *keybuf = s.mutableData(); memset(keybuf, 0, keylen); memcpy(keybuf, password.data(), password.size()); key = s.setSize(keylen); } int result_len = 0; int outlen = decoded_data.size() + EVP_CIPHER_block_size(cipher_type); String rv = String(outlen, ReserveString); unsigned char *outbuf = (unsigned char*)rv.mutableData(); EVP_DecryptInit_ex(cipher_ctx, cipher_type, nullptr, nullptr, nullptr); String new_iv; // we do this after DecryptInit because validate_iv changes cipher_ctx for // aead modes (must be initialized first). if (!php_openssl_validate_iv( std::move(iv), EVP_CIPHER_iv_length(cipher_type), new_iv, cipher_ctx, &mode)) { return false; } // set the tag if required: if (tag.size() > 0) { if (!mode.is_aead) { raise_warning( "The tag is being ignored because the cipher method does not" " support AEAD"); } else if (!EVP_CIPHER_CTX_ctrl( cipher_ctx, mode.aead_set_tag_flag, tag.size(), (unsigned char*)tag.data())) { raise_warning("Setting tag for AEAD cipher decryption failed"); return false; } } else { if (mode.is_aead) { raise_warning("A tag should be provided when using AEAD mode"); return false; } } if (password.size() > keylen) { EVP_CIPHER_CTX_set_key_length(cipher_ctx, password.size()); } EVP_DecryptInit_ex( cipher_ctx, nullptr, nullptr, (unsigned char*)key.data(), (unsigned char*)new_iv.data()); if (options & k_OPENSSL_ZERO_PADDING) { EVP_CIPHER_CTX_set_padding(cipher_ctx, 0); } // for single run aeads like CCM, we need to provide the length of the // ciphertext before providing AAD or ciphertext. if (mode.is_single_run_aead && !EVP_DecryptUpdate( cipher_ctx, nullptr, &result_len, nullptr, decoded_data.size())) { raise_warning("Setting of data length failed"); return false; } // set up aad: if (mode.is_aead && !EVP_DecryptUpdate( cipher_ctx, nullptr, &result_len, (unsigned char*)aad.data(), aad.size())) { raise_warning("Setting of additional application data failed"); return false; } if (!EVP_DecryptUpdate( cipher_ctx, outbuf, &result_len, (unsigned char*)decoded_data.data(), decoded_data.size())) { return false; } outlen = result_len; // if is_single_run_aead is enabled, DecryptFinal shouldn't be called. // if something went wrong in this case, we would've caught it at // DecryptUpdate. if (mode.is_single_run_aead || EVP_DecryptFinal_ex( cipher_ctx, (unsigned char*)outbuf + result_len, &result_len)) { // don't want to do this if is_single_run_aead was enabled, since we didn't // make a call to EVP_DecryptFinal. if (!mode.is_single_run_aead) { outlen += result_len; } rv.setSize(outlen); return rv; } else { return false; } } Variant HHVM_FUNCTION(openssl_digest, const String& data, const String& method, bool raw_output /* = false */) { const EVP_MD *mdtype = EVP_get_digestbyname(method.c_str()); if (!mdtype) { raise_warning("Unknown signature algorithm"); return false; } int siglen = EVP_MD_size(mdtype); String rv = String(siglen, ReserveString); unsigned char *sigbuf = (unsigned char *)rv.mutableData(); EVP_MD_CTX *md_ctx = EVP_MD_CTX_new(); SCOPE_EXIT { EVP_MD_CTX_free(md_ctx); }; EVP_DigestInit(md_ctx, mdtype); EVP_DigestUpdate(md_ctx, (unsigned char *)data.data(), data.size()); if (EVP_DigestFinal(md_ctx, (unsigned char *)sigbuf, (unsigned int *)&siglen)) { if (raw_output) { rv.setSize(siglen); return rv; } else { char* digest_str = string_bin2hex((char*)sigbuf, siglen); return String(digest_str, AttachString); } } else { return false; } } static void openssl_add_method_or_alias(const OBJ_NAME *name, void *arg) { Array *ret = (Array*)arg; ret->append(String((char *)name->name, CopyString)); } static void openssl_add_method(const OBJ_NAME *name, void *arg) { if (name->alias == 0) { Array *ret = (Array*)arg; ret->append(String((char *)name->name, CopyString)); } } Array HHVM_FUNCTION(openssl_get_cipher_methods, bool aliases /* = false */) { Array ret = Array::CreateVArray(); OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH, aliases ? openssl_add_method_or_alias: openssl_add_method, &ret); return ret; } Variant HHVM_FUNCTION(openssl_get_curve_names) { #ifdef HAVE_EVP_PKEY_EC const size_t len = EC_get_builtin_curves(nullptr, 0); std::unique_ptr<EC_builtin_curve[]> curves(new EC_builtin_curve[len]); if (!EC_get_builtin_curves(curves.get(), len)) { return false; } VArrayInit ret(len); for (size_t i = 0; i < len; ++i) { auto const sname = OBJ_nid2sn(curves[i].nid); if (sname != nullptr) { ret.append(String(sname, CopyString)); } } return ret.toArray(); #else return false; #endif } Array HHVM_FUNCTION(openssl_get_md_methods, bool aliases /* = false */) { Array ret = Array::CreateVArray(); OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_MD_METH, aliases ? openssl_add_method_or_alias: openssl_add_method, &ret); return ret; } ///////////////////////////////////////////////////////////////////////////// const StaticString s_OPENSSL_VERSION_TEXT("OPENSSL_VERSION_TEXT"); struct opensslExtension final : Extension { opensslExtension() : Extension("openssl") {} void moduleInit() override { HHVM_RC_INT(OPENSSL_RAW_DATA, k_OPENSSL_RAW_DATA); HHVM_RC_INT(OPENSSL_ZERO_PADDING, k_OPENSSL_ZERO_PADDING); HHVM_RC_INT(OPENSSL_NO_PADDING, k_OPENSSL_NO_PADDING); HHVM_RC_INT(OPENSSL_PKCS1_OAEP_PADDING, k_OPENSSL_PKCS1_OAEP_PADDING); HHVM_RC_INT(OPENSSL_SSLV23_PADDING, k_OPENSSL_SSLV23_PADDING); HHVM_RC_INT(OPENSSL_PKCS1_PADDING, k_OPENSSL_PKCS1_PADDING); HHVM_RC_INT_SAME(OPENSSL_ALGO_SHA1); HHVM_RC_INT_SAME(OPENSSL_ALGO_MD5); HHVM_RC_INT_SAME(OPENSSL_ALGO_MD4); #ifdef HAVE_OPENSSL_MD2_H HHVM_RC_INT_SAME(OPENSSL_ALGO_MD2); #endif HHVM_RC_INT_SAME(OPENSSL_ALGO_DSS1); HHVM_RC_INT_SAME(OPENSSL_ALGO_SHA224); HHVM_RC_INT_SAME(OPENSSL_ALGO_SHA256); HHVM_RC_INT_SAME(OPENSSL_ALGO_SHA384); HHVM_RC_INT_SAME(OPENSSL_ALGO_SHA512); HHVM_RC_INT_SAME(OPENSSL_ALGO_RMD160); HHVM_RC_INT(OPENSSL_CIPHER_RC2_40, PHP_OPENSSL_CIPHER_RC2_40); HHVM_RC_INT(OPENSSL_CIPHER_RC2_128, PHP_OPENSSL_CIPHER_RC2_128); HHVM_RC_INT(OPENSSL_CIPHER_RC2_64, PHP_OPENSSL_CIPHER_RC2_64); HHVM_RC_INT(OPENSSL_CIPHER_DES, PHP_OPENSSL_CIPHER_DES); HHVM_RC_INT(OPENSSL_CIPHER_3DES, PHP_OPENSSL_CIPHER_3DES); HHVM_RC_INT_SAME(OPENSSL_KEYTYPE_RSA); HHVM_RC_INT_SAME(OPENSSL_KEYTYPE_DSA); HHVM_RC_INT_SAME(OPENSSL_KEYTYPE_DH); #ifdef HAVE_EVP_PKEY_EC HHVM_RC_INT_SAME(OPENSSL_KEYTYPE_EC); #endif HHVM_RC_INT_SAME(OPENSSL_VERSION_NUMBER); HHVM_RC_INT_SAME(PKCS7_TEXT); HHVM_RC_INT_SAME(PKCS7_NOCERTS); HHVM_RC_INT_SAME(PKCS7_NOSIGS); HHVM_RC_INT_SAME(PKCS7_NOCHAIN); HHVM_RC_INT_SAME(PKCS7_NOINTERN); HHVM_RC_INT_SAME(PKCS7_NOVERIFY); HHVM_RC_INT_SAME(PKCS7_DETACHED); HHVM_RC_INT_SAME(PKCS7_BINARY); HHVM_RC_INT_SAME(PKCS7_NOATTR); HHVM_RC_STR_SAME(OPENSSL_VERSION_TEXT); HHVM_RC_INT_SAME(X509_PURPOSE_SSL_CLIENT); HHVM_RC_INT_SAME(X509_PURPOSE_SSL_SERVER); HHVM_RC_INT_SAME(X509_PURPOSE_NS_SSL_SERVER); HHVM_RC_INT_SAME(X509_PURPOSE_SMIME_SIGN); HHVM_RC_INT_SAME(X509_PURPOSE_SMIME_ENCRYPT); HHVM_RC_INT_SAME(X509_PURPOSE_CRL_SIGN); #ifdef X509_PURPOSE_ANY HHVM_RC_INT_SAME(X509_PURPOSE_ANY); #endif HHVM_FE(openssl_csr_export_to_file); HHVM_FE(openssl_csr_export); HHVM_FE(openssl_csr_get_public_key); HHVM_FE(openssl_csr_get_subject); HHVM_FE(openssl_csr_new); HHVM_FE(openssl_csr_sign); HHVM_FE(openssl_error_string); HHVM_FE(openssl_open); HHVM_FE(openssl_pkcs12_export_to_file); HHVM_FE(openssl_pkcs12_export); HHVM_FE(openssl_pkcs12_read); HHVM_FE(openssl_pkcs7_decrypt); HHVM_FE(openssl_pkcs7_encrypt); HHVM_FE(openssl_pkcs7_sign); HHVM_FE(openssl_pkcs7_verify); HHVM_FE(openssl_pkey_export_to_file); HHVM_FE(openssl_pkey_export); HHVM_FE(openssl_pkey_get_details); HHVM_FE(openssl_pkey_get_private); HHVM_FE(openssl_pkey_get_public); HHVM_FE(openssl_pkey_new); HHVM_FE(openssl_private_decrypt); HHVM_FE(openssl_private_encrypt); HHVM_FE(openssl_public_decrypt); HHVM_FE(openssl_public_encrypt); HHVM_FE(openssl_seal); HHVM_FE(openssl_sign); HHVM_FE(openssl_verify); HHVM_FE(openssl_x509_check_private_key); HHVM_FE(openssl_x509_checkpurpose); HHVM_FE(openssl_x509_export_to_file); HHVM_FE(openssl_x509_export); HHVM_FE(openssl_x509_parse); HHVM_FE(openssl_x509_read); HHVM_FE(openssl_random_pseudo_bytes); HHVM_FE(openssl_cipher_iv_length); HHVM_FE(openssl_encrypt); HHVM_FE(openssl_encrypt_with_tag); HHVM_FE(openssl_decrypt); HHVM_FE(openssl_digest); HHVM_FE(openssl_get_cipher_methods); HHVM_FE(openssl_get_curve_names); HHVM_FE(openssl_get_md_methods); loadSystemlib(); } } s_openssl_extension; /////////////////////////////////////////////////////////////////////////////// }
null
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1997-2010 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/ext/openssl/ext_openssl.h" #include "hphp/runtime/base/array-init.h" #include "hphp/runtime/base/array-iterator.h" #include "hphp/runtime/base/ssl-socket.h" #include "hphp/runtime/base/string-util.h" #include "hphp/runtime/base/zend-string.h" #include "hphp/util/logger.h" #include <folly/ScopeGuard.h> #include <openssl/conf.h> #include <openssl/pem.h> #include <openssl/pkcs12.h> #include <openssl/rand.h> #include <vector> namespace HPHP { #define MIN_KEY_LENGTH 384 // bitfields const int64_t k_OPENSSL_RAW_DATA = 1; const int64_t k_OPENSSL_ZERO_PADDING = 2; const int64_t k_OPENSSL_NO_PADDING = 3; const int64_t k_OPENSSL_PKCS1_OAEP_PADDING = 4; // exported constants const int64_t k_OPENSSL_SSLV23_PADDING = 2; const int64_t k_OPENSSL_PKCS1_PADDING = 1; static char default_ssl_conf_filename[PATH_MAX]; struct OpenSSLInitializer { OpenSSLInitializer() { SSL_library_init(); OpenSSL_add_all_ciphers(); OpenSSL_add_all_digests(); OpenSSL_add_all_algorithms(); // CCM ciphers are not added by default, so let's add them! #if !defined(OPENSSL_NO_AES) && defined(EVP_CIPH_CCM_MODE) && \ OPENSSL_VERSION_NUMBER < 0x100020000 EVP_add_cipher(EVP_aes_128_ccm()); EVP_add_cipher(EVP_aes_192_ccm()); EVP_add_cipher(EVP_aes_256_ccm()); #endif ERR_load_ERR_strings(); ERR_load_crypto_strings(); ERR_load_EVP_strings(); /* Determine default SSL configuration file */ char *config_filename = getenv("OPENSSL_CONF"); if (config_filename == nullptr) { config_filename = getenv("SSLEAY_CONF"); } /* default to 'openssl.cnf' if no environment variable is set */ if (config_filename == nullptr) { snprintf(default_ssl_conf_filename, sizeof(default_ssl_conf_filename), "%s/%s", X509_get_default_cert_area(), "openssl.cnf"); } else { always_assert( strlen(config_filename) < sizeof(default_ssl_conf_filename)); strcpy(default_ssl_conf_filename, config_filename); } } ~OpenSSLInitializer() { EVP_cleanup(); } }; static OpenSSLInitializer s_openssl_initializer; /////////////////////////////////////////////////////////////////////////////// // resource classes struct Key : SweepableResourceData { EVP_PKEY *m_key; explicit Key(EVP_PKEY *key) : m_key(key) { assertx(m_key);} ~Key() override { if (m_key) EVP_PKEY_free(m_key); } CLASSNAME_IS("OpenSSL key"); // overriding ResourceData const String& o_getClassNameHook() const override { return classnameof(); } DECLARE_RESOURCE_ALLOCATION(Key) bool isPrivate() { assertx(m_key); switch (EVP_PKEY_id(m_key)) { #ifndef NO_RSA case EVP_PKEY_RSA: case EVP_PKEY_RSA2: { const auto rsa = EVP_PKEY_get0_RSA(m_key); assertx(rsa); const BIGNUM *p, *q; RSA_get0_factors(rsa, &p, &q); if (!p || !q) { return false; } break; } #endif #ifndef NO_DSA case EVP_PKEY_DSA: case EVP_PKEY_DSA1: case EVP_PKEY_DSA2: case EVP_PKEY_DSA3: case EVP_PKEY_DSA4: { const auto dsa = EVP_PKEY_get0_DSA(m_key); assertx(dsa); const BIGNUM *p, *q, *g, *pub_key, *priv_key; DSA_get0_pqg(dsa, &p, &q, &g); if (!p || !q || !g) { return false; } DSA_get0_key(dsa, &pub_key, &priv_key); if (!priv_key) { return false; } break; } #endif #ifndef NO_DH case EVP_PKEY_DH: { const auto dh = EVP_PKEY_get0_DH(m_key); assertx(dh); const BIGNUM *p, *q, *g, *pub_key, *priv_key; DH_get0_pqg(dh, &p, &q, &g); if (!p) { return false; } DH_get0_key(dh, &pub_key, &priv_key); if (!priv_key) { return false; } break; } #endif #ifdef HAVE_EVP_PKEY_EC case EVP_PKEY_EC: { const auto ec_key = EVP_PKEY_get0_EC_KEY(m_key); assertx(ec_key); if (EC_KEY_get0_private_key(ec_key) == nullptr) { return false; } break; } #endif default: raise_warning("key type not supported in this PHP build!"); break; } return true; } /** * Given a variant, coerce it into a EVP_PKEY object. It can be: * * 1. private key resource from openssl_get_privatekey() * 2. X509 resource -> public key will be extracted from it * 3. if it starts with file:// interpreted as path to key file * 4. interpreted as the data from the cert/key file and interpreted in * same way as openssl_get_privatekey() * 5. an array(0 => [items 2..4], 1 => passphrase) * 6. if val is a string (possibly starting with file:///) and it is not * an X509 certificate, then interpret as public key * * NOTE: If you are requesting a private key but have not specified a * passphrase, you should use an empty string rather than nullptr for the * passphrase - nullptr causes a passphrase prompt to be emitted in * the Apache error log! */ static req::ptr<Key> Get(const Variant& var, bool public_key, const char *passphrase = nullptr) { if (var.isArray()) { Array arr = var.toArray(); if (!arr.exists(int64_t(0)) || !arr.exists(int64_t(1))) { raise_warning("key array must be of the form " "array(0 => key, 1 => phrase)"); return nullptr; } String zphrase = arr[1].toString(); return GetHelper(arr[0], public_key, zphrase.data()); } return GetHelper(var, public_key, passphrase); } static req::ptr<Key> GetHelper(const Variant& var, bool public_key, const char *passphrase) { req::ptr<Certificate> ocert; EVP_PKEY *key = nullptr; if (var.isResource()) { auto cert = dyn_cast_or_null<Certificate>(var); auto key = dyn_cast_or_null<Key>(var); if (!cert && !key) return nullptr; if (key) { bool is_priv = key->isPrivate(); if (!public_key && !is_priv) { raise_warning("supplied key param is a public key"); return nullptr; } if (public_key && is_priv) { raise_warning("Don't know how to get public key from " "this private key"); return nullptr; } return key; } ocert = cert; } else { /* it's an X509 file/cert of some kind, and we need to extract the data from that */ if (public_key) { ocert = Certificate::Get(var); if (!ocert) { /* not a X509 certificate, try to retrieve public key */ BIO *in = Certificate::ReadData(var); if (in == nullptr) return nullptr; key = PEM_read_bio_PUBKEY(in, nullptr,nullptr, nullptr); BIO_free(in); } } else { /* we want the private key */ BIO *in = Certificate::ReadData(var); if (in == nullptr) return nullptr; key = PEM_read_bio_PrivateKey(in, nullptr,nullptr, (void*)passphrase); BIO_free(in); } } if (public_key && ocert && key == nullptr) { /* extract public key from X509 cert */ key = (EVP_PKEY *)X509_get_pubkey(ocert->get()); } if (key) { return req::make<Key>(key); } return nullptr; } }; IMPLEMENT_RESOURCE_ALLOCATION(Key) /** * Certificate Signing Request */ struct CSRequest : SweepableResourceData { private: X509_REQ *m_csr; public: explicit CSRequest(X509_REQ *csr) : m_csr(csr) { assertx(m_csr); } X509_REQ *csr() { return m_csr; } ~CSRequest() override { // X509_REQ_free(nullptr) is a no-op X509_REQ_free(m_csr); } CLASSNAME_IS("OpenSSL X.509 CSR"); // overriding ResourceData const String& o_getClassNameHook() const override { return classnameof(); } DECLARE_RESOURCE_ALLOCATION(CSRequest) static req::ptr<CSRequest> Get(const Variant& var) { auto csr = cast_or_null<CSRequest>(GetRequest(var)); if (!csr || !csr->m_csr) { raise_warning("cannot get CSR"); return nullptr; } return csr; } private: static req::ptr<CSRequest> GetRequest(const Variant& var) { if (var.isResource()) { return dyn_cast_or_null<CSRequest>(var); } if (var.isString() || var.isObject()) { BIO *in = Certificate::ReadData(var); if (in == nullptr) return nullptr; X509_REQ *csr = PEM_read_bio_X509_REQ(in, nullptr,nullptr,nullptr); BIO_free(in); if (csr) { return req::make<CSRequest>(csr); } } return nullptr; } }; IMPLEMENT_RESOURCE_ALLOCATION(CSRequest) struct php_x509_request { #if OPENSSL_VERSION_NUMBER >= 0x10000002L LHASH_OF(CONF_VALUE) * global_config; /* Global SSL config */ LHASH_OF(CONF_VALUE) * req_config; /* SSL config for this request */ #else LHASH *global_config; /* Global SSL config */ LHASH *req_config; /* SSL config for this request */ #endif const EVP_MD *md_alg; const EVP_MD *digest; const char *section_name; const char *config_filename; const char *digest_name; const char *extensions_section; const char *request_extensions_section; int priv_key_bits; int priv_key_type; int priv_key_encrypt; #ifdef HAVE_EVP_PKEY_EC int curve_name; #endif EVP_PKEY *priv_key; static bool load_rand_file(const char *file, int *egdsocket, int *seeded) { char buffer[PATH_MAX]; *egdsocket = 0; *seeded = 0; if (file == nullptr) { file = RAND_file_name(buffer, sizeof(buffer)); #if !defined(OPENSSL_NO_RAND_EGD) && !defined(OPENSSL_NO_EGD) } else if (RAND_egd(file) > 0) { /* if the given filename is an EGD socket, don't * write anything back to it */ *egdsocket = 1; return true; #endif } if (file == nullptr || !RAND_load_file(file, -1)) { if (RAND_status() == 0) { raise_warning("unable to load random state; not enough data!"); return false; } return false; } *seeded = 1; return true; } static bool write_rand_file(const char *file, int egdsocket, int seeded) { char buffer[PATH_MAX]; if (egdsocket || !seeded) { /* if we did not manage to read the seed file, we should not write * a low-entropy seed file back */ return false; } if (file == nullptr) { file = RAND_file_name(buffer, sizeof(buffer)); } if (file == nullptr || !RAND_write_file(file)) { raise_warning("unable to write random state"); return false; } return true; } bool generatePrivateKey() { assertx(priv_key == nullptr); if (priv_key_bits < MIN_KEY_LENGTH) { raise_warning("private key length is too short; it needs to be " "at least %d bits, not %d", MIN_KEY_LENGTH, priv_key_bits); return false; } char *randfile = CONF_get_string(req_config, section_name, "RANDFILE"); int egdsocket, seeded; load_rand_file(randfile, &egdsocket, &seeded); bool ret = false; if ((priv_key = EVP_PKEY_new()) != nullptr) { switch (priv_key_type) { case OPENSSL_KEYTYPE_RSA: if (EVP_PKEY_assign_RSA (priv_key, RSA_generate_key(priv_key_bits, 0x10001, nullptr, nullptr))) { ret = true; } break; #if !defined(NO_DSA) && defined(HAVE_DSA_DEFAULT_METHOD) case OPENSSL_KEYTYPE_DSA: { DSA *dsapar = DSA_generate_parameters(priv_key_bits, nullptr, 0, nullptr, nullptr, nullptr, nullptr); if (dsapar) { DSA_set_method(dsapar, DSA_get_default_method()); if (DSA_generate_key(dsapar)) { if (EVP_PKEY_assign_DSA(priv_key, dsapar)) { ret = true; } } else { DSA_free(dsapar); } } } break; #endif #ifdef HAVE_EVP_PKEY_EC case OPENSSL_KEYTYPE_EC: { if (curve_name == NID_undef) { raise_warning("Missing configuration value: 'curve_name' not set"); return false; } if (auto const eckey = EC_KEY_new_by_curve_name(curve_name)) { EC_KEY_set_asn1_flag(eckey, OPENSSL_EC_NAMED_CURVE); if (EC_KEY_generate_key(eckey) && EVP_PKEY_assign_EC_KEY(priv_key, eckey)) { ret = true; } else { EC_KEY_free(eckey); } } } break; #endif default: raise_warning("Unsupported private key type"); } } write_rand_file(randfile, egdsocket, seeded); return ret; } }; /////////////////////////////////////////////////////////////////////////////// // utilities static void add_assoc_name_entry(Array &ret, const char *key, X509_NAME *name, bool shortname) { Array subitem_data; Array &subitem = key ? subitem_data : ret; for (int i = 0; i < X509_NAME_entry_count(name); i++) { X509_NAME_ENTRY *ne = X509_NAME_get_entry(name, i); ASN1_OBJECT *obj = X509_NAME_ENTRY_get_object(ne); int nid = OBJ_obj2nid(obj); int obj_cnt = 0; char *sname; if (shortname) { sname = (char *)OBJ_nid2sn(nid); } else { sname = (char *)OBJ_nid2ln(nid); } Array subentries; int last = -1; int j; ASN1_STRING *str = nullptr; unsigned char *to_add = nullptr; int to_add_len = 0; for (;;) { j = X509_NAME_get_index_by_OBJ(name, obj, last); if (j < 0) { if (last != -1) break; } else { obj_cnt++; ne = X509_NAME_get_entry(name, j); str = X509_NAME_ENTRY_get_data(ne); if (ASN1_STRING_type(str) != V_ASN1_UTF8STRING) { to_add_len = ASN1_STRING_to_UTF8(&to_add, str); if (to_add_len != -1) { subentries.append(String((char*)to_add, to_add_len, AttachString)); } } else { to_add = ASN1_STRING_data(str); to_add_len = ASN1_STRING_length(str); subentries.append(String((char*)to_add, to_add_len, CopyString)); } } last = j; } i = last; if (obj_cnt > 1) { subitem.set(String(sname, CopyString), subentries); } else if (obj_cnt && str && to_add_len > -1) { // Use the string instance we created above. subitem.set(String(sname, CopyString), subentries[0]); } } if (key) { ret.set(String(key, CopyString), subitem); } } static const char *read_string(const Array& args, const String& key, const char *def, std::vector<String> &strings) { if (args.exists(key)) { String value = args[key].toString(); strings.push_back(value); return (char*)value.data(); } return def; } static int64_t read_integer(const Array& args, const String& key, int64_t def) { if (args.exists(key)) { return args[key].toInt64(); } return def; } static bool add_oid_section(struct php_x509_request *req) { char *str = CONF_get_string(req->req_config, nullptr, "oid_section"); if (str == nullptr) { return true; } STACK_OF(CONF_VALUE) *sktmp = CONF_get_section(req->req_config, str); if (sktmp == nullptr) { raise_warning("problem loading oid section %s", str); return false; } for (int i = 0; i < sk_CONF_VALUE_num(sktmp); i++) { CONF_VALUE *cnf = sk_CONF_VALUE_value(sktmp, i); if (OBJ_sn2nid(cnf->name) == NID_undef && OBJ_ln2nid(cnf->name) == NID_undef && OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) { raise_warning("problem creating object %s=%s", cnf->name, cnf->value); return false; } } return true; } #if OPENSSL_VERSION_NUMBER >= 0x10000002L static inline bool php_openssl_config_check_syntax (const char *section_label, const char *config_filename, const char *section, LHASH_OF(CONF_VALUE) *config) { #else static inline bool php_openssl_config_check_syntax (const char *section_label, const char *config_filename, const char *section, LHASH *config) { #endif X509V3_CTX ctx; X509V3_set_ctx_test(&ctx); X509V3_set_conf_lhash(&ctx, config); if (!X509V3_EXT_add_conf(config, &ctx, (char*)section, nullptr)) { raise_warning("Error loading %s section %s of %s", section_label, section, config_filename); return false; } return true; } const StaticString s_config("config"), s_config_section_name("config_section_name"), s_digest_alg("digest_alg"), s_x509_extensions("x509_extensions"), s_req_extensions("req_extensions"), s_private_key_bits("private_key_bits"), s_private_key_type("private_key_type"), s_encrypt_key("encrypt_key"), s_curve_name("curve_name"); static bool php_openssl_parse_config(struct php_x509_request *req, const Array& args, std::vector<String> &strings) { req->config_filename = read_string(args, s_config, default_ssl_conf_filename, strings); req->section_name = read_string(args, s_config_section_name, "req", strings); req->global_config = CONF_load(nullptr, default_ssl_conf_filename, nullptr); req->req_config = CONF_load(nullptr, req->config_filename, nullptr); if (req->req_config == nullptr) { return false; } /* read in the oids */ char *str = CONF_get_string(req->req_config, nullptr, "oid_file"); if (str) { BIO *oid_bio = BIO_new_file(str, "r"); if (oid_bio) { OBJ_create_objects(oid_bio); BIO_free(oid_bio); } } if (!add_oid_section(req)) { return false; } req->digest_name = read_string(args, s_digest_alg, CONF_get_string(req->req_config, req->section_name, "default_md"), strings); req->extensions_section = read_string(args, s_x509_extensions, CONF_get_string(req->req_config, req->section_name, "x509_extensions"), strings); req->request_extensions_section = read_string(args, s_req_extensions, CONF_get_string(req->req_config, req->section_name, "req_extensions"), strings); req->priv_key_bits = read_integer(args, s_private_key_bits, CONF_get_number(req->req_config, req->section_name, "default_bits")); req->priv_key_type = read_integer(args, s_private_key_type, OPENSSL_KEYTYPE_DEFAULT); if (args.exists(s_encrypt_key)) { bool value = args[s_encrypt_key].toBoolean(); req->priv_key_encrypt = value ? 1 : 0; } else { str = CONF_get_string(req->req_config, req->section_name, "encrypt_rsa_key"); if (str == nullptr) { str = CONF_get_string(req->req_config, req->section_name, "encrypt_key"); } if (str && strcmp(str, "no") == 0) { req->priv_key_encrypt = 0; } else { req->priv_key_encrypt = 1; } } /* digest alg */ if (req->digest_name == nullptr) { req->digest_name = CONF_get_string(req->req_config, req->section_name, "default_md"); } if (req->digest_name) { req->digest = req->md_alg = EVP_get_digestbyname(req->digest_name); } if (req->md_alg == nullptr) { req->md_alg = req->digest = EVP_sha256(); } #ifdef HAVE_EVP_PKEY_EC /* set the ec group curve name */ req->curve_name = NID_undef; if (args.exists(s_curve_name)) { auto const curve_name = args[s_curve_name].toString(); req->curve_name = OBJ_sn2nid(curve_name.data()); if (req->curve_name == NID_undef) { raise_warning( "Unknown elliptic curve (short) name %s", curve_name.data() ); return false; } } #endif if (req->extensions_section && !php_openssl_config_check_syntax ("extensions_section", req->config_filename, req->extensions_section, req->req_config)) { return false; } /* set the string mask */ str = CONF_get_string(req->req_config, req->section_name, "string_mask"); if (str && !ASN1_STRING_set_default_mask_asc(str)) { raise_warning("Invalid global string mask setting %s", str); return false; } if (req->request_extensions_section && !php_openssl_config_check_syntax ("request_extensions_section", req->config_filename, req->request_extensions_section, req->req_config)) { return false; } return true; } static void php_openssl_dispose_config(struct php_x509_request *req) { if (req->global_config) { CONF_free(req->global_config); req->global_config = nullptr; } if (req->req_config) { CONF_free(req->req_config); req->req_config = nullptr; } } static STACK_OF(X509) *load_all_certs_from_file(const char *certfile) { STACK_OF(X509_INFO) *sk = nullptr; STACK_OF(X509) *stack = nullptr, *ret = nullptr; BIO *in = nullptr; X509_INFO *xi; if (!(stack = sk_X509_new_null())) { raise_warning("memory allocation failure"); goto end; } if (!(in = BIO_new_file(certfile, "r"))) { raise_warning("error opening the file, %s", certfile); sk_X509_free(stack); goto end; } /* This loads from a file, a stack of x509/crl/pkey sets */ if (!(sk = PEM_X509_INFO_read_bio(in, nullptr, nullptr, nullptr))) { raise_warning("error reading the file, %s", certfile); sk_X509_free(stack); goto end; } /* scan over it and pull out the certs */ while (sk_X509_INFO_num(sk)) { xi = sk_X509_INFO_shift(sk); if (xi->x509 != nullptr) { sk_X509_push(stack, xi->x509); xi->x509 = nullptr; } X509_INFO_free(xi); } if (!sk_X509_num(stack)) { raise_warning("no certificates in file, %s", certfile); sk_X509_free(stack); goto end; } ret = stack; end: BIO_free(in); sk_X509_INFO_free(sk); return ret; } /** * calist is an array containing file and directory names. create a * certificate store and add those certs to it for use in verification. */ static X509_STORE *setup_verify(const Array& calist) { X509_STORE *store = X509_STORE_new(); if (store == nullptr) { return nullptr; } X509_LOOKUP *dir_lookup, *file_lookup; int ndirs = 0, nfiles = 0; for (ArrayIter iter(calist); iter; ++iter) { String item = iter.second().toString(); struct stat sb; if (stat(item.data(), &sb) == -1) { raise_warning("unable to stat %s", item.data()); continue; } if ((sb.st_mode & S_IFREG) == S_IFREG) { file_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()); if (file_lookup == nullptr || !X509_LOOKUP_load_file(file_lookup, item.data(), X509_FILETYPE_PEM)) { raise_warning("error loading file %s", item.data()); } else { nfiles++; } file_lookup = nullptr; } else { dir_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir()); if (dir_lookup == nullptr || !X509_LOOKUP_add_dir(dir_lookup, item.data(), X509_FILETYPE_PEM)) { raise_warning("error loading directory %s", item.data()); } else { ndirs++; } dir_lookup = nullptr; } } if (nfiles == 0) { file_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()); if (file_lookup) { X509_LOOKUP_load_file(file_lookup, nullptr, X509_FILETYPE_DEFAULT); } } if (ndirs == 0) { dir_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir()); if (dir_lookup) { X509_LOOKUP_add_dir(dir_lookup, nullptr, X509_FILETYPE_DEFAULT); } } return store; } /////////////////////////////////////////////////////////////////////////////// static bool add_entries(X509_NAME *subj, const Array& items) { for (ArrayIter iter(items); iter; ++iter) { auto const index = iter.first().toString(); auto const item = iter.second().toString(); int nid = OBJ_txt2nid(index.data()); if (nid != NID_undef) { if (!X509_NAME_add_entry_by_NID(subj, nid, MBSTRING_ASC, (unsigned char*)item.data(), -1, -1, 0)) { raise_warning("dn: add_entry_by_NID %d -> %s (failed)", nid, item.data()); return false; } } else { raise_warning("dn: %s is not a recognized name", index.data()); } } return true; } static bool php_openssl_make_REQ(struct php_x509_request *req, X509_REQ *csr, const Array& dn, const Array& attribs) { char *dn_sect = CONF_get_string(req->req_config, req->section_name, "distinguished_name"); if (dn_sect == nullptr) return false; STACK_OF(CONF_VALUE) *dn_sk = CONF_get_section(req->req_config, dn_sect); if (dn_sk == nullptr) return false; char *attr_sect = CONF_get_string(req->req_config, req->section_name, "attributes"); STACK_OF(CONF_VALUE) *attr_sk = nullptr; if (attr_sect) { attr_sk = CONF_get_section(req->req_config, attr_sect); if (attr_sk == nullptr) { return false; } } /* setup the version number: version 1 */ if (X509_REQ_set_version(csr, 0L)) { X509_NAME *subj = X509_REQ_get_subject_name(csr); if (!add_entries(subj, dn)) return false; /* Finally apply defaults from config file */ for (int i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) { CONF_VALUE *v = sk_CONF_VALUE_value(dn_sk, i); char *type = v->name; int len = strlen(type); if (len < (int)sizeof("_default")) { continue; } len -= sizeof("_default") - 1; if (strcmp("_default", type + len) != 0) { continue; } if (len > 200) { len = 200; } char buffer[200 + 1]; /*200 + \0 !*/ memcpy(buffer, type, len); buffer[len] = '\0'; type = buffer; /* Skip past any leading X. X: X, etc to allow for multiple instances */ for (char *str = type; *str; str++) { if (*str == ':' || *str == ',' || *str == '.') { str++; if (*str) { type = str; } break; } } /* if it is already set, skip this */ int nid = OBJ_txt2nid(type); if (X509_NAME_get_index_by_NID(subj, nid, -1) >= 0) { continue; } if (!X509_NAME_add_entry_by_txt(subj, type, MBSTRING_ASC, (unsigned char*)v->value, -1, -1, 0)) { raise_warning("add_entry_by_txt %s -> %s (failed)", type, v->value); return false; } if (!X509_NAME_entry_count(subj)) { raise_warning("no objects specified in config file"); return false; } } if (!add_entries(subj, attribs)) return false; if (attr_sk) { for (int i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) { CONF_VALUE *v = sk_CONF_VALUE_value(attr_sk, i); /* if it is already set, skip this */ int nid = OBJ_txt2nid(v->name); if (X509_REQ_get_attr_by_NID(csr, nid, -1) >= 0) { continue; } if (!X509_REQ_add1_attr_by_txt(csr, v->name, MBSTRING_ASC, (unsigned char*)v->value, -1)) { /** * hzhao: mismatched version of conf file may have attributes that * are not recognizable, and I don't think it should be treated as * fatal errors. */ Logger::Verbose("add1_attr_by_txt %s -> %s (failed)", v->name, v->value); // return false; } } } } X509_REQ_set_pubkey(csr, req->priv_key); return true; } bool HHVM_FUNCTION(openssl_csr_export_to_file, const Variant& csr, const String& outfilename, bool notext /* = true */) { auto pcsr = CSRequest::Get(csr); if (!pcsr) return false; BIO *bio_out = BIO_new_file((char*)outfilename.data(), "w"); if (bio_out == nullptr) { raise_warning("error opening file %s", outfilename.data()); return false; } if (!notext) { X509_REQ_print(bio_out, pcsr->csr()); } PEM_write_bio_X509_REQ(bio_out, pcsr->csr()); BIO_free(bio_out); return true; } bool HHVM_FUNCTION(openssl_csr_export, const Variant& csr, Variant& out, bool notext /* = true */) { auto pcsr = CSRequest::Get(csr); if (!pcsr) return false; BIO *bio_out = BIO_new(BIO_s_mem()); if (!notext) { X509_REQ_print(bio_out, pcsr->csr()); } if (PEM_write_bio_X509_REQ(bio_out, pcsr->csr())) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); out = String((char*)bio_buf->data, bio_buf->length, CopyString); BIO_free(bio_out); return true; } BIO_free(bio_out); return false; } Variant HHVM_FUNCTION(openssl_csr_get_public_key, const Variant& csr) { auto pcsr = CSRequest::Get(csr); if (!pcsr) return false; auto input_csr = pcsr->csr(); #if OPENSSL_VERSION_NUMBER >= 0x10100000 /* Due to changes in OpenSSL 1.1 related to locking when decoding CSR, * the pub key is not changed after assigning. It means if we pass * a private key, it will be returned including the private part. * If we duplicate it, then we get just the public part which is * the same behavior as for OpenSSL 1.0 */ input_csr = X509_REQ_dup(input_csr); /* We need to free the CSR as it was duplicated */ SCOPE_EXIT { X509_REQ_free(input_csr); }; #endif auto pubkey = X509_REQ_get_pubkey(input_csr); if (!pubkey) return false; return Variant(req::make<Key>(pubkey)); } Variant HHVM_FUNCTION(openssl_csr_get_subject, const Variant& csr, bool use_shortnames /* = true */) { auto pcsr = CSRequest::Get(csr); if (!pcsr) return false; X509_NAME *subject = X509_REQ_get_subject_name(pcsr->csr()); Array ret = Array::CreateDArray(); add_assoc_name_entry(ret, nullptr, subject, use_shortnames); return ret; } Variant HHVM_FUNCTION(openssl_csr_new, const Variant& dn, Variant& privkey, const Variant& configargs /* = uninit_variant */, const Variant& extraattribs /* = uninit_variant */) { Variant ret = false; struct php_x509_request req; memset(&req, 0, sizeof(req)); req::ptr<Key> okey; X509_REQ *csr = nullptr; std::vector<String> strings; if (php_openssl_parse_config(&req, configargs.toArray(), strings)) { /* Generate or use a private key */ if (!privkey.isNull()) { okey = Key::Get(privkey, false); if (okey) { req.priv_key = okey->m_key; } } if (req.priv_key == nullptr) { req.generatePrivateKey(); if (req.priv_key) { okey = req::make<Key>(req.priv_key); } } if (req.priv_key == nullptr) { raise_warning("Unable to generate a private key"); } else { csr = X509_REQ_new(); if (csr && php_openssl_make_REQ(&req, csr, dn.toArray(), extraattribs.toArray())) { X509V3_CTX ext_ctx; X509V3_set_ctx(&ext_ctx, nullptr, nullptr, csr, nullptr, 0); X509V3_set_conf_lhash(&ext_ctx, req.req_config); /* Add extensions */ if (req.request_extensions_section && !X509V3_EXT_REQ_add_conf(req.req_config, &ext_ctx, (char*)req.request_extensions_section, csr)) { raise_warning("Error loading extension section %s", req.request_extensions_section); } else { ret = true; if (X509_REQ_sign(csr, req.priv_key, req.digest)) { ret = req::make<CSRequest>(csr); csr = nullptr; } else { raise_warning("Error signing request"); } privkey = Variant(okey); } } } } if (csr) { X509_REQ_free(csr); } php_openssl_dispose_config(&req); return ret; } Variant HHVM_FUNCTION(openssl_csr_sign, const Variant& csr, const Variant& cacert, const Variant& priv_key, int days, const Variant& configargs /* = null */, int serial /* = 0 */) { auto pcsr = CSRequest::Get(csr); if (!pcsr) return false; req::ptr<Certificate> ocert; if (!cacert.isNull()) { ocert = Certificate::Get(cacert); if (!ocert) { raise_warning("cannot get cert from parameter 2"); return false; } } auto okey = Key::Get(priv_key, false); if (!okey) { raise_warning("cannot get private key from parameter 3"); return false; } X509 *cert = nullptr; if (ocert) { cert = ocert->m_cert; } EVP_PKEY *pkey = okey->m_key; if (cert && !X509_check_private_key(cert, pkey)) { raise_warning("private key does not correspond to signing cert"); return false; } req::ptr<Certificate> onewcert; struct php_x509_request req; memset(&req, 0, sizeof(req)); Variant ret = false; std::vector<String> strings; if (!php_openssl_parse_config(&req, configargs.toArray(), strings)) { goto cleanup; } /* Check that the request matches the signature */ EVP_PKEY *key; key = X509_REQ_get_pubkey(pcsr->csr()); if (key == nullptr) { raise_warning("error unpacking public key"); goto cleanup; } int i; i = X509_REQ_verify(pcsr->csr(), key); if (i < 0) { raise_warning("Signature verification problems"); goto cleanup; } if (i == 0) { raise_warning("Signature did not match the certificate request"); goto cleanup; } /* Now we can get on with it */ X509 *new_cert; new_cert = X509_new(); if (new_cert == nullptr) { raise_warning("No memory"); goto cleanup; } onewcert = req::make<Certificate>(new_cert); /* Version 3 cert */ if (!X509_set_version(new_cert, 2)) { goto cleanup; } ASN1_INTEGER_set(X509_get_serialNumber(new_cert), serial); X509_set_subject_name(new_cert, X509_REQ_get_subject_name(pcsr->csr())); if (cert == nullptr) { cert = new_cert; } if (!X509_set_issuer_name(new_cert, X509_get_subject_name(cert))) { goto cleanup; } X509_gmtime_adj(X509_get_notBefore(new_cert), 0); X509_gmtime_adj(X509_get_notAfter(new_cert), (long)60 * 60 * 24 * days); i = X509_set_pubkey(new_cert, key); if (!i) { goto cleanup; } if (req.extensions_section) { X509V3_CTX ctx; X509V3_set_ctx(&ctx, cert, new_cert, pcsr->csr(), nullptr, 0); X509V3_set_conf_lhash(&ctx, req.req_config); if (!X509V3_EXT_add_conf(req.req_config, &ctx, (char*)req.extensions_section, new_cert)) { goto cleanup; } } /* Now sign it */ if (!X509_sign(new_cert, pkey, req.digest)) { raise_warning("failed to sign it"); goto cleanup; } /* Succeeded; lets return the cert */ ret = onewcert; cleanup: php_openssl_dispose_config(&req); return ret; } Variant HHVM_FUNCTION(openssl_error_string) { char buf[512]; unsigned long val = ERR_get_error(); if (val) { return String(ERR_error_string(val, buf), CopyString); } return false; } bool HHVM_FUNCTION(openssl_open, const String& sealed_data, Variant& open_data, const String& env_key, const Variant& priv_key_id, const String& method, /* = null_string */ const String& iv /* = null_string */) { const EVP_CIPHER *cipher_type; if (method.empty()) { cipher_type = EVP_rc4(); } else { cipher_type = EVP_get_cipherbyname(method.c_str()); if (!cipher_type) { raise_warning("Unknown cipher algorithm"); return false; } } auto okey = Key::Get(priv_key_id, false); if (!okey) { raise_warning("unable to coerce parameter 4 into a private key"); return false; } EVP_PKEY *pkey = okey->m_key; const unsigned char *iv_buf = nullptr; int iv_len = EVP_CIPHER_iv_length(cipher_type); if (iv_len > 0) { if (iv.empty()) { raise_warning( "Cipher algorithm requires an IV to be supplied as a sixth parameter"); return false; } if (iv.length() != iv_len) { raise_warning("IV length is invalid"); return false; } iv_buf = reinterpret_cast<const unsigned char*>(iv.c_str()); } String s = String(sealed_data.size(), ReserveString); unsigned char *buf = (unsigned char *)s.mutableData(); EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new(); if (ctx == nullptr) { raise_warning("Failed to allocate an EVP_CIPHER_CTX object"); return false; } SCOPE_EXIT { EVP_CIPHER_CTX_free(ctx); }; int len1, len2; if (!EVP_OpenInit( ctx, cipher_type, (unsigned char*)env_key.data(), env_key.size(), iv_buf, pkey) || !EVP_OpenUpdate( ctx, buf, &len1, (unsigned char*)sealed_data.data(), sealed_data.size()) || !EVP_OpenFinal(ctx, buf + len1, &len2) || len1 + len2 == 0) { return false; } open_data = s.setSize(len1 + len2); return true; } static STACK_OF(X509) *php_array_to_X509_sk(const Variant& certs) { STACK_OF(X509) *pcerts = sk_X509_new_null(); Array arrCerts; if (certs.isArray()) { arrCerts = certs.toArray(); } else { arrCerts.append(certs); } for (ArrayIter iter(arrCerts); iter; ++iter) { auto ocert = Certificate::Get(iter.second()); if (!ocert) { break; } sk_X509_push(pcerts, ocert->m_cert); } return pcerts; } const StaticString s_friendly_name("friendly_name"), s_extracerts("extracerts"); static bool openssl_pkcs12_export_impl(const Variant& x509, BIO *bio_out, const Variant& priv_key, const String& pass, const Variant& args /* = uninit_variant */) { auto ocert = Certificate::Get(x509); if (!ocert) { raise_warning("cannot get cert from parameter 1"); return false; } auto okey = Key::Get(priv_key, false); if (!okey) { raise_warning("cannot get private key from parameter 3"); return false; } X509 *cert = ocert->m_cert; EVP_PKEY *key = okey->m_key; if (cert && !X509_check_private_key(cert, key)) { raise_warning("private key does not correspond to cert"); return false; } Array arrArgs = args.toArray(); String friendly_name; if (arrArgs.exists(s_friendly_name)) { friendly_name = arrArgs[s_friendly_name].toString(); } STACK_OF(X509) *ca = nullptr; if (arrArgs.exists(s_extracerts)) { ca = php_array_to_X509_sk(arrArgs[s_extracerts]); } PKCS12 *p12 = PKCS12_create ((char*)pass.data(), (char*)(friendly_name.empty() ? nullptr : friendly_name.data()), key, cert, ca, 0, 0, 0, 0, 0); assertx(bio_out); bool ret = i2d_PKCS12_bio(bio_out, p12); PKCS12_free(p12); sk_X509_free(ca); return ret; } bool HHVM_FUNCTION(openssl_pkcs12_export_to_file, const Variant& x509, const String& filename, const Variant& priv_key, const String& pass, const Variant& args /* = uninit_variant */) { BIO *bio_out = BIO_new_file(filename.data(), "w"); if (bio_out == nullptr) { raise_warning("error opening file %s", filename.data()); return false; } bool ret = openssl_pkcs12_export_impl(x509, bio_out, priv_key, pass, args); BIO_free(bio_out); return ret; } bool HHVM_FUNCTION(openssl_pkcs12_export, const Variant& x509, Variant& out, const Variant& priv_key, const String& pass, const Variant& args /* = uninit_variant */) { BIO *bio_out = BIO_new(BIO_s_mem()); bool ret = openssl_pkcs12_export_impl(x509, bio_out, priv_key, pass, args); if (ret) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); out = String((char*)bio_buf->data, bio_buf->length, CopyString); } BIO_free(bio_out); return ret; } const StaticString s_cert("cert"), s_pkey("pkey"); bool HHVM_FUNCTION(openssl_pkcs12_read, const String& pkcs12, Variant& certs, const String& pass) { bool ret = false; PKCS12 *p12 = nullptr; BIO *bio_in = BIO_new(BIO_s_mem()); if (!BIO_write(bio_in, pkcs12.data(), pkcs12.size())) { goto cleanup; } if (d2i_PKCS12_bio(bio_in, &p12)) { EVP_PKEY *pkey = nullptr; X509 *cert = nullptr; STACK_OF(X509) *ca = nullptr; if (PKCS12_parse(p12, pass.data(), &pkey, &cert, &ca)) { Variant vcerts = Array::CreateDArray(); SCOPE_EXIT { certs = vcerts; }; BIO *bio_out = nullptr; if (cert) { bio_out = BIO_new(BIO_s_mem()); if (PEM_write_bio_X509(bio_out, cert)) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); vcerts.asArrRef().set(s_cert, String((char*)bio_buf->data, bio_buf->length, CopyString)); } BIO_free(bio_out); } if (pkey) { bio_out = BIO_new(BIO_s_mem()); if (PEM_write_bio_PrivateKey(bio_out, pkey, nullptr, nullptr, 0, 0, nullptr)) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); vcerts.asArrRef().set(s_pkey, String((char*)bio_buf->data, bio_buf->length, CopyString)); } BIO_free(bio_out); } if (ca) { Array extracerts; for (X509 *aCA = sk_X509_pop(ca); aCA; aCA = sk_X509_pop(ca)) { bio_out = BIO_new(BIO_s_mem()); if (PEM_write_bio_X509(bio_out, aCA)) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); extracerts.append(String((char*)bio_buf->data, bio_buf->length, CopyString)); } BIO_free(bio_out); X509_free(aCA); } sk_X509_free(ca); vcerts.asArrRef().set(s_extracerts, extracerts); } ret = true; PKCS12_free(p12); } } cleanup: if (bio_in) { BIO_free(bio_in); } return ret; } bool HHVM_FUNCTION(openssl_pkcs7_decrypt, const String& infilename, const String& outfilename, const Variant& recipcert, const Variant& recipkey /* = uninit_variant */) { bool ret = false; BIO *in = nullptr, *out = nullptr, *datain = nullptr; PKCS7 *p7 = nullptr; req::ptr<Key> okey; auto ocert = Certificate::Get(recipcert); if (!ocert) { raise_warning("unable to coerce parameter 3 to x509 cert"); goto clean_exit; } okey = Key::Get(recipkey.isNull() ? recipcert : recipkey, false); if (!okey) { raise_warning("unable to get private key"); goto clean_exit; } in = BIO_new_file(infilename.data(), "r"); if (in == nullptr) { raise_warning("error opening the file, %s", infilename.data()); goto clean_exit; } out = BIO_new_file(outfilename.data(), "w"); if (out == nullptr) { raise_warning("error opening the file, %s", outfilename.data()); goto clean_exit; } p7 = SMIME_read_PKCS7(in, &datain); if (p7 == nullptr) { goto clean_exit; } assertx(okey->m_key); assertx(ocert->m_cert); if (PKCS7_decrypt(p7, okey->m_key, ocert->m_cert, out, PKCS7_DETACHED)) { ret = true; } clean_exit: PKCS7_free(p7); BIO_free(datain); BIO_free(in); BIO_free(out); return ret; } static void print_headers(BIO *outfile, const Array& headers) { if (!headers.isNull()) { if (headers->isVectorData()) { for (ArrayIter iter(headers); iter; ++iter) { BIO_printf(outfile, "%s\n", iter.second().toString().data()); } } else { for (ArrayIter iter(headers); iter; ++iter) { BIO_printf(outfile, "%s: %s\n", iter.first().toString().data(), iter.second().toString().data()); } } } } bool HHVM_FUNCTION(openssl_pkcs7_encrypt, const String& infilename, const String& outfilename, const Variant& recipcerts, const Array& headers, int flags /* = 0 */, int cipherid /* = k_OPENSSL_CIPHER_RC2_40 */) { bool ret = false; BIO *infile = nullptr, *outfile = nullptr; STACK_OF(X509) *precipcerts = nullptr; PKCS7 *p7 = nullptr; const EVP_CIPHER *cipher = nullptr; infile = BIO_new_file(infilename.data(), (flags & PKCS7_BINARY) ? "rb" : "r"); if (infile == nullptr) { raise_warning("error opening the file, %s", infilename.data()); goto clean_exit; } outfile = BIO_new_file(outfilename.data(), "w"); if (outfile == nullptr) { raise_warning("error opening the file, %s", outfilename.data()); goto clean_exit; } precipcerts = php_array_to_X509_sk(recipcerts); /* sanity check the cipher */ switch (cipherid) { #ifndef OPENSSL_NO_RC2 case PHP_OPENSSL_CIPHER_RC2_40: cipher = EVP_rc2_40_cbc(); break; case PHP_OPENSSL_CIPHER_RC2_64: cipher = EVP_rc2_64_cbc(); break; case PHP_OPENSSL_CIPHER_RC2_128: cipher = EVP_rc2_cbc(); break; #endif #ifndef OPENSSL_NO_DES case PHP_OPENSSL_CIPHER_DES: cipher = EVP_des_cbc(); break; case PHP_OPENSSL_CIPHER_3DES: cipher = EVP_des_ede3_cbc(); break; #endif default: raise_warning("Invalid cipher type `%d'", cipherid); goto clean_exit; } if (cipher == nullptr) { raise_warning("Failed to get cipher"); goto clean_exit; } p7 = PKCS7_encrypt(precipcerts, infile, (EVP_CIPHER*)cipher, flags); if (p7 == nullptr) goto clean_exit; print_headers(outfile, headers); (void)BIO_reset(infile); SMIME_write_PKCS7(outfile, p7, infile, flags); ret = true; clean_exit: PKCS7_free(p7); BIO_free(infile); BIO_free(outfile); sk_X509_free(precipcerts); return ret; } bool HHVM_FUNCTION(openssl_pkcs7_sign, const String& infilename, const String& outfilename, const Variant& signcert, const Variant& privkey, const Variant& headers, int flags /* = k_PKCS7_DETACHED */, const String& extracerts /* = null_string */) { bool ret = false; STACK_OF(X509) *others = nullptr; BIO *infile = nullptr, *outfile = nullptr; PKCS7 *p7 = nullptr; req::ptr<Key> okey; req::ptr<Certificate> ocert; if (!extracerts.empty()) { others = load_all_certs_from_file(extracerts.data()); if (others == nullptr) { goto clean_exit; } } okey = Key::Get(privkey, false); if (!okey) { raise_warning("error getting private key"); goto clean_exit; } EVP_PKEY *key; key = okey->m_key; ocert = Certificate::Get(signcert); if (!ocert) { raise_warning("error getting cert"); goto clean_exit; } X509 *cert; cert = ocert->m_cert; infile = BIO_new_file(infilename.data(), (flags & PKCS7_BINARY) ? "rb" : "r"); if (infile == nullptr) { raise_warning("error opening input file %s!", infilename.data()); goto clean_exit; } outfile = BIO_new_file(outfilename.data(), "w"); if (outfile == nullptr) { raise_warning("error opening output file %s!", outfilename.data()); goto clean_exit; } p7 = PKCS7_sign(cert, key, others, infile, flags); if (p7 == nullptr) { raise_warning("error creating PKCS7 structure!"); goto clean_exit; } print_headers(outfile, headers.toArray()); (void)BIO_reset(infile); SMIME_write_PKCS7(outfile, p7, infile, flags); ret = true; clean_exit: PKCS7_free(p7); BIO_free(infile); BIO_free(outfile); if (others) { sk_X509_pop_free(others, X509_free); } return ret; } static int pkcs7_ignore_expiration(int ok, X509_STORE_CTX *ctx) { if (ok) { return ok; } int error = X509_STORE_CTX_get_error(ctx); if (error == X509_V_ERR_CERT_HAS_EXPIRED) { // ignore cert expirations Logger::Verbose("Ignoring cert expiration"); return 1; } return ok; } /** * NOTE: when ignore_cert_expiration is true, a custom certificate validation * callback is set up. Please be aware of this if you modify the function to * allow other certificate validation behaviors */ Variant openssl_pkcs7_verify_core( const String& filename, int flags, const Variant& voutfilename /* = null_string */, const Variant& vcainfo /* = null_array */, const Variant& vextracerts /* = null_string */, const Variant& vcontent /* = null_string */, bool ignore_cert_expiration ) { Variant ret = -1; X509_STORE *store = nullptr; BIO *in = nullptr; PKCS7 *p7 = nullptr; BIO *datain = nullptr; BIO *dataout = nullptr; auto cainfo = vcainfo.toArray(); auto extracerts = vextracerts.toString(); auto content = vcontent.toString(); STACK_OF(X509) *others = nullptr; if (!extracerts.empty()) { others = load_all_certs_from_file(extracerts.data()); if (others == nullptr) { goto clean_exit; } } flags = flags & ~PKCS7_DETACHED; store = setup_verify(cainfo); if (!store) { goto clean_exit; } if (ignore_cert_expiration) { #if (OPENSSL_VERSION_NUMBER >= 0x10000000) // make sure no other callback is specified #if OPENSSL_VERSION_NUMBER >= 0x10100000L assertx(!X509_STORE_get_verify_cb(store)); #else assertx(!store->verify_cb); #endif // ignore expired certs X509_STORE_set_verify_cb(store, pkcs7_ignore_expiration); #else always_assert(false); #endif } in = BIO_new_file(filename.data(), (flags & PKCS7_BINARY) ? "rb" : "r"); if (in == nullptr) { raise_warning("error opening the file, %s", filename.data()); goto clean_exit; } p7 = SMIME_read_PKCS7(in, &datain); if (p7 == nullptr) { goto clean_exit; } if (!content.empty()) { dataout = BIO_new_file(content.data(), "w"); if (dataout == nullptr) { raise_warning("error opening the file, %s", content.data()); goto clean_exit; } } if (PKCS7_verify(p7, others, store, datain, dataout, flags)) { ret = true; auto outfilename = voutfilename.toString(); if (!outfilename.empty()) { BIO *certout = BIO_new_file(outfilename.data(), "w"); if (certout) { STACK_OF(X509) *signers = PKCS7_get0_signers(p7, nullptr, flags); for (int i = 0; i < sk_X509_num(signers); i++) { PEM_write_bio_X509(certout, sk_X509_value(signers, i)); } BIO_free(certout); sk_X509_free(signers); } else { raise_warning("signature OK, but cannot open %s for writing", outfilename.data()); ret = -1; } } goto clean_exit; } else { ret = false; } clean_exit: X509_STORE_free(store); BIO_free(datain); BIO_free(in); BIO_free(dataout); PKCS7_free(p7); sk_X509_pop_free(others, X509_free); return ret; } Variant HHVM_FUNCTION(openssl_pkcs7_verify, const String& filename, int flags, const Variant& voutfilename /* = null_string */, const Variant& vcainfo /* = null_array */, const Variant& vextracerts /* = null_string */, const Variant& vcontent /* = null_string */) { return openssl_pkcs7_verify_core(filename, flags, voutfilename, vcainfo, vextracerts, vcontent, false); } static bool openssl_pkey_export_impl(const Variant& key, BIO *bio_out, const String& passphrase /* = null_string */, const Variant& configargs /* = uninit_variant */) { auto okey = Key::Get(key, false, passphrase.data()); if (!okey) { raise_warning("cannot get key from parameter 1"); return false; } EVP_PKEY *pkey = okey->m_key; struct php_x509_request req; memset(&req, 0, sizeof(req)); std::vector<String> strings; bool ret = false; if (php_openssl_parse_config(&req, configargs.toArray(), strings)) { const EVP_CIPHER *cipher; if (!passphrase.empty() && req.priv_key_encrypt) { cipher = (EVP_CIPHER *)EVP_des_ede3_cbc(); } else { cipher = nullptr; } assertx(bio_out); switch (EVP_PKEY_id(pkey)) { #ifdef HAVE_EVP_PKEY_EC case EVP_PKEY_EC: ret = PEM_write_bio_ECPrivateKey(bio_out, EVP_PKEY_get0_EC_KEY(pkey), cipher, (unsigned char *)passphrase.data(), passphrase.size(), nullptr, nullptr); break; #endif default: ret = PEM_write_bio_PrivateKey(bio_out, pkey, cipher, (unsigned char *)passphrase.data(), passphrase.size(), nullptr, nullptr); break; } } php_openssl_dispose_config(&req); return ret; } bool HHVM_FUNCTION(openssl_pkey_export_to_file, const Variant& key, const String& outfilename, const String& passphrase /* = null_string */, const Variant& configargs /* = uninit_variant */) { BIO *bio_out = BIO_new_file(outfilename.data(), "w"); if (bio_out == nullptr) { raise_warning("error opening the file, %s", outfilename.data()); return false; } bool ret = openssl_pkey_export_impl(key, bio_out, passphrase, configargs); BIO_free(bio_out); return ret; } bool HHVM_FUNCTION(openssl_pkey_export, const Variant& key, Variant& out, const String& passphrase /* = null_string */, const Variant& configargs /* = uninit_variant */) { BIO *bio_out = BIO_new(BIO_s_mem()); bool ret = openssl_pkey_export_impl(key, bio_out, passphrase, configargs); if (ret) { char *bio_mem_ptr; long bio_mem_len = BIO_get_mem_data(bio_out, &bio_mem_ptr); out = String(bio_mem_ptr, bio_mem_len, CopyString); } BIO_free(bio_out); return ret; } const StaticString s_bits("bits"), s_key("key"), s_type("type"), s_name("name"), s_hash("hash"), s_version("version"), s_serialNumber("serialNumber"), s_signatureAlgorithm("signatureAlgorithm"), s_validFrom("validFrom"), s_validTo("validTo"), s_validFrom_time_t("validFrom_time_t"), s_validTo_time_t("validTo_time_t"), s_alias("alias"), s_purposes("purposes"), s_extensions("extensions"), s_rsa("rsa"), s_dsa("dsa"), s_dh("dh"), s_ec("ec"), s_n("n"), s_e("e"), s_d("d"), s_p("p"), s_q("q"), s_g("g"), s_x("x"), s_y("y"), s_dmp1("dmp1"), s_dmq1("dmq1"), s_iqmp("iqmp"), s_priv_key("priv_key"), s_pub_key("pub_key"), s_curve_oid("curve_oid"); static void add_bignum_as_string(Array &arr, StaticString key, const BIGNUM *bn) { if (!bn) { return; } int num_bytes = BN_num_bytes(bn); String str{size_t(num_bytes), ReserveString}; BN_bn2bin(bn, (unsigned char*)str.mutableData()); str.setSize(num_bytes); arr.set(key, std::move(str)); } Array HHVM_FUNCTION(openssl_pkey_get_details, const Resource& key) { EVP_PKEY *pkey = cast<Key>(key)->m_key; BIO *out = BIO_new(BIO_s_mem()); PEM_write_bio_PUBKEY(out, pkey); char *pbio; unsigned int pbio_len = BIO_get_mem_data(out, &pbio); auto ret = make_darray( s_bits, EVP_PKEY_bits(pkey), s_key, String(pbio, pbio_len, CopyString) ); long ktype = -1; auto details = Array::CreateDArray(); switch (EVP_PKEY_id(pkey)) { case EVP_PKEY_RSA: case EVP_PKEY_RSA2: { ktype = OPENSSL_KEYTYPE_RSA; RSA *rsa = EVP_PKEY_get0_RSA(pkey); assertx(rsa); const BIGNUM *n, *e, *d, *p, *q, *dmp1, *dmq1, *iqmp; RSA_get0_key(rsa, &n, &e, &d); RSA_get0_factors(rsa, &p, &q); RSA_get0_crt_params(rsa, &dmp1, &dmq1, &iqmp); add_bignum_as_string(details, s_n, n); add_bignum_as_string(details, s_e, e); add_bignum_as_string(details, s_d, d); add_bignum_as_string(details, s_p, p); add_bignum_as_string(details, s_q, q); add_bignum_as_string(details, s_dmp1, dmp1); add_bignum_as_string(details, s_dmq1, dmq1); add_bignum_as_string(details, s_iqmp, iqmp); ret.set(s_rsa, details); break; } case EVP_PKEY_DSA: case EVP_PKEY_DSA2: case EVP_PKEY_DSA3: case EVP_PKEY_DSA4: { ktype = OPENSSL_KEYTYPE_DSA; DSA *dsa = EVP_PKEY_get0_DSA(pkey); assertx(dsa); const BIGNUM *p, *q, *g, *pub_key, *priv_key; DSA_get0_pqg(dsa, &p, &q, &g); DSA_get0_key(dsa, &pub_key, &priv_key); add_bignum_as_string(details, s_p, p); add_bignum_as_string(details, s_q, q); add_bignum_as_string(details, s_g, g); add_bignum_as_string(details, s_priv_key, priv_key); add_bignum_as_string(details, s_pub_key, pub_key); ret.set(s_dsa, details); break; } case EVP_PKEY_DH: { ktype = OPENSSL_KEYTYPE_DH; DH *dh = EVP_PKEY_get0_DH(pkey); assertx(dh); const BIGNUM *p, *q, *g, *pub_key, *priv_key; DH_get0_pqg(dh, &p, &q, &g); DH_get0_key(dh, &pub_key, &priv_key); add_bignum_as_string(details, s_p, p); add_bignum_as_string(details, s_g, g); add_bignum_as_string(details, s_priv_key, priv_key); add_bignum_as_string(details, s_pub_key, pub_key); ret.set(s_dh, details); break; } #ifdef HAVE_EVP_PKEY_EC case EVP_PKEY_EC: { ktype = OPENSSL_KEYTYPE_EC; auto const ec = EVP_PKEY_get0_EC_KEY(pkey); assertx(ec); auto const ec_group = EC_KEY_get0_group(ec); auto const nid = EC_GROUP_get_curve_name(ec_group); if (nid == NID_undef) { break; } auto const crv_sn = OBJ_nid2sn(nid); if (crv_sn != nullptr) { details.set(s_curve_name, String(crv_sn, CopyString)); } auto const obj = OBJ_nid2obj(nid); if (obj != nullptr) { SCOPE_EXIT { ASN1_OBJECT_free(obj); }; char oir_buf[256]; OBJ_obj2txt(oir_buf, sizeof(oir_buf) - 1, obj, 1); details.set(s_curve_oid, String(oir_buf, CopyString)); } auto x = BN_new(); auto y = BN_new(); SCOPE_EXIT { BN_free(x); BN_free(y); }; auto const pub = EC_KEY_get0_public_key(ec); if (EC_POINT_get_affine_coordinates_GFp(ec_group, pub, x, y, nullptr)) { add_bignum_as_string(details, s_x, x); add_bignum_as_string(details, s_y, y); } auto d = BN_dup(EC_KEY_get0_private_key(ec)); SCOPE_EXIT { BN_free(d); }; if (d != nullptr) { add_bignum_as_string(details, s_d, d); } ret.set(s_ec, details); } break; #endif } ret.set(s_type, ktype); BIO_free(out); return ret; } Variant HHVM_FUNCTION(openssl_pkey_get_private, const Variant& key, const String& passphrase /* = null_string */) { return toVariant(Key::Get(key, false, passphrase.data())); } Variant HHVM_FUNCTION(openssl_pkey_get_public, const Variant& certificate) { return toVariant(Key::Get(certificate, true)); } Variant HHVM_FUNCTION(openssl_pkey_new, const Variant& configargs /* = uninit_variant */) { struct php_x509_request req; memset(&req, 0, sizeof(req)); SCOPE_EXIT { php_openssl_dispose_config(&req); }; std::vector<String> strings; if (php_openssl_parse_config(&req, configargs.toArray(), strings) && req.generatePrivateKey()) { return Resource(req::make<Key>(req.priv_key)); } else { return false; } } bool HHVM_FUNCTION(openssl_private_decrypt, const String& data, Variant& decrypted, const Variant& key, int padding /* = k_OPENSSL_PKCS1_PADDING */) { auto okey = Key::Get(key, false); if (!okey) { raise_warning("key parameter is not a valid private key"); return false; } EVP_PKEY *pkey = okey->m_key; int cryptedlen = EVP_PKEY_size(pkey); String s = String(cryptedlen, ReserveString); unsigned char *cryptedbuf = (unsigned char *)s.mutableData(); int successful = 0; switch (EVP_PKEY_id(pkey)) { case EVP_PKEY_RSA: case EVP_PKEY_RSA2: cryptedlen = RSA_private_decrypt(data.size(), (unsigned char *)data.data(), cryptedbuf, EVP_PKEY_get0_RSA(pkey), padding); if (cryptedlen != -1) { successful = 1; } break; default: raise_warning("key type not supported"); } if (successful) { decrypted = s.setSize(cryptedlen); return true; } return false; } bool HHVM_FUNCTION(openssl_private_encrypt, const String& data, Variant& crypted, const Variant& key, int padding /* = k_OPENSSL_PKCS1_PADDING */) { auto okey = Key::Get(key, false); if (!okey) { raise_warning("key param is not a valid private key"); return false; } EVP_PKEY *pkey = okey->m_key; int cryptedlen = EVP_PKEY_size(pkey); String s = String(cryptedlen, ReserveString); unsigned char *cryptedbuf = (unsigned char *)s.mutableData(); int successful = 0; switch (EVP_PKEY_id(pkey)) { case EVP_PKEY_RSA: case EVP_PKEY_RSA2: successful = (RSA_private_encrypt(data.size(), (unsigned char *)data.data(), cryptedbuf, EVP_PKEY_get0_RSA(pkey), padding) == cryptedlen); break; default: raise_warning("key type not supported"); } if (successful) { crypted = s.setSize(cryptedlen); return true; } return false; } bool HHVM_FUNCTION(openssl_public_decrypt, const String& data, Variant& decrypted, const Variant& key, int padding /* = k_OPENSSL_PKCS1_PADDING */) { auto okey = Key::Get(key, true); if (!okey) { raise_warning("key parameter is not a valid public key"); return false; } EVP_PKEY *pkey = okey->m_key; int cryptedlen = EVP_PKEY_size(pkey); String s = String(cryptedlen, ReserveString); unsigned char *cryptedbuf = (unsigned char *)s.mutableData(); int successful = 0; switch (EVP_PKEY_id(pkey)) { case EVP_PKEY_RSA: case EVP_PKEY_RSA2: cryptedlen = RSA_public_decrypt(data.size(), (unsigned char *)data.data(), cryptedbuf, EVP_PKEY_get0_RSA(pkey), padding); if (cryptedlen != -1) { successful = 1; } break; default: raise_warning("key type not supported"); } if (successful) { decrypted = s.setSize(cryptedlen); return true; } return false; } bool HHVM_FUNCTION(openssl_public_encrypt, const String& data, Variant& crypted, const Variant& key, int padding /* = k_OPENSSL_PKCS1_PADDING */) { auto okey = Key::Get(key, true); if (!okey) { raise_warning("key parameter is not a valid public key"); return false; } EVP_PKEY *pkey = okey->m_key; int cryptedlen = EVP_PKEY_size(pkey); String s = String(cryptedlen, ReserveString); unsigned char *cryptedbuf = (unsigned char *)s.mutableData(); int successful = 0; switch (EVP_PKEY_id(pkey)) { case EVP_PKEY_RSA: case EVP_PKEY_RSA2: successful = (RSA_public_encrypt(data.size(), (unsigned char *)data.data(), cryptedbuf, EVP_PKEY_get0_RSA(pkey), padding) == cryptedlen); break; default: raise_warning("key type not supported"); } if (successful) { crypted = s.setSize(cryptedlen); return true; } return false; } Variant HHVM_FUNCTION(openssl_seal, const String& data, Variant& sealed_data, Variant& env_keys, const Array& pub_key_ids, const String& method, Variant& iv) { int nkeys = pub_key_ids.size(); if (nkeys == 0) { raise_warning("Fourth argument to openssl_seal() must be " "a non-empty array"); return false; } const EVP_CIPHER *cipher_type; if (method.empty()) { cipher_type = EVP_rc4(); } else { cipher_type = EVP_get_cipherbyname(method.c_str()); if (!cipher_type) { raise_warning("Unknown cipher algorithm"); return false; } } int iv_len = EVP_CIPHER_iv_length(cipher_type); unsigned char *iv_buf = nullptr; String iv_s; if (iv_len > 0) { iv_s = String(iv_len, ReserveString); iv_buf = (unsigned char*)iv_s.mutableData(); if (!RAND_bytes(iv_buf, iv_len)) { raise_warning("Could not generate an IV."); return false; } } EVP_PKEY **pkeys = (EVP_PKEY**)malloc(nkeys * sizeof(*pkeys)); int *eksl = (int*)malloc(nkeys * sizeof(*eksl)); unsigned char **eks = (unsigned char **)malloc(nkeys * sizeof(*eks)); memset(eks, 0, sizeof(*eks) * nkeys); // holder is needed to make sure none of the Keys get deleted prematurely. // The pkeys array points to elements inside of Keys returned from Key::Get() // which may be newly allocated and have no other owners. std::vector<req::ptr<Key>> holder; /* get the public keys we are using to seal this data */ bool ret = true; int i = 0; String s; unsigned char* buf = nullptr; EVP_CIPHER_CTX* ctx = nullptr; for (ArrayIter iter(pub_key_ids); iter; ++iter, ++i) { auto okey = Key::Get(iter.second(), true); if (!okey) { raise_warning("not a public key (%dth member of pubkeys)", i + 1); ret = false; goto clean_exit; } holder.push_back(okey); pkeys[i] = okey->m_key; eks[i] = (unsigned char *)malloc(EVP_PKEY_size(pkeys[i]) + 1); } ctx = EVP_CIPHER_CTX_new(); if (ctx == nullptr) { raise_warning("Failed to allocate an EVP_CIPHER_CTX object"); ret = false; goto clean_exit; } if (!EVP_EncryptInit_ex(ctx, cipher_type, nullptr, nullptr, nullptr)) { ret = false; goto clean_exit; } int len1, len2; s = String(data.size() + EVP_CIPHER_CTX_block_size(ctx), ReserveString); buf = (unsigned char *)s.mutableData(); if (EVP_SealInit(ctx, cipher_type, eks, eksl, iv_buf, pkeys, nkeys) <= 0 || !EVP_SealUpdate(ctx, buf, &len1, (unsigned char*)data.data(), data.size()) || !EVP_SealFinal(ctx, buf + len1, &len2)) { ret = false; goto clean_exit; } if (len1 + len2 > 0) { sealed_data = s.setSize(len1 + len2); auto ekeys = Array::CreateVArray(); for (i = 0; i < nkeys; i++) { eks[i][eksl[i]] = '\0'; ekeys.append(String((char*)eks[i], eksl[i], AttachString)); eks[i] = nullptr; } env_keys = ekeys; } clean_exit: for (i = 0; i < nkeys; i++) { if (eks[i]) free(eks[i]); } free(eks); free(eksl); free(pkeys); if (iv_buf != nullptr) { if (ret) { iv = iv_s.setSize(iv_len); } } if (ctx != nullptr) { EVP_CIPHER_CTX_free(ctx); } if (ret) return len1 + len2; return false; } static const EVP_MD *php_openssl_get_evp_md_from_algo(long algo) { switch (algo) { case OPENSSL_ALGO_SHA1: return EVP_sha1(); case OPENSSL_ALGO_MD5: return EVP_md5(); case OPENSSL_ALGO_MD4: return EVP_md4(); #ifdef HAVE_OPENSSL_MD2_H case OPENSSL_ALGO_MD2: return EVP_md2(); #endif #if OPENSSL_VERSION_NUMBER < 0x10100000L case OPENSSL_ALGO_DSS1: return EVP_dss1(); #endif #if OPENSSL_VERSION_NUMBER >= 0x0090708fL case OPENSSL_ALGO_SHA224: return EVP_sha224(); case OPENSSL_ALGO_SHA256: return EVP_sha256(); case OPENSSL_ALGO_SHA384: return EVP_sha384(); case OPENSSL_ALGO_SHA512: return EVP_sha512(); case OPENSSL_ALGO_RMD160: return EVP_ripemd160(); #endif } return nullptr; } bool HHVM_FUNCTION(openssl_sign, const String& data, Variant& signature, const Variant& priv_key_id, const Variant& signature_alg /* = k_OPENSSL_ALGO_SHA1 */) { auto okey = Key::Get(priv_key_id, false); if (!okey) { raise_warning("supplied key param cannot be coerced into a private key"); return false; } const EVP_MD *mdtype = nullptr; if (signature_alg.isInteger()) { mdtype = php_openssl_get_evp_md_from_algo(signature_alg.toInt64Val()); } else if (signature_alg.isString()) { mdtype = EVP_get_digestbyname(signature_alg.toString().data()); } if (!mdtype) { raise_warning("Unknown signature algorithm."); return false; } EVP_PKEY *pkey = okey->m_key; int siglen = EVP_PKEY_size(pkey); String s = String(siglen, ReserveString); unsigned char *sigbuf = (unsigned char *)s.mutableData(); EVP_MD_CTX *md_ctx = EVP_MD_CTX_new(); SCOPE_EXIT { EVP_MD_CTX_free(md_ctx); }; EVP_SignInit(md_ctx, mdtype); EVP_SignUpdate(md_ctx, (unsigned char *)data.data(), data.size()); if (EVP_SignFinal(md_ctx, sigbuf, (unsigned int *)&siglen, pkey)) { signature = s.setSize(siglen); return true; } return false; } Variant HHVM_FUNCTION(openssl_verify, const String& data, const String& signature, const Variant& pub_key_id, const Variant& signature_alg /* = k_OPENSSL_ALGO_SHA1 */) { int err; const EVP_MD *mdtype = nullptr; if (signature_alg.isInteger()) { mdtype = php_openssl_get_evp_md_from_algo(signature_alg.toInt64Val()); } else if (signature_alg.isString()) { mdtype = EVP_get_digestbyname(signature_alg.toString().data()); } if (!mdtype) { raise_warning("Unknown signature algorithm."); return false; } auto okey = Key::Get(pub_key_id, true); if (!okey) { raise_warning("supplied key param cannot be coerced into a public key"); return false; } EVP_MD_CTX *md_ctx = EVP_MD_CTX_new(); SCOPE_EXIT { EVP_MD_CTX_free(md_ctx); }; EVP_VerifyInit(md_ctx, mdtype); EVP_VerifyUpdate(md_ctx, (unsigned char*)data.data(), data.size()); err = EVP_VerifyFinal(md_ctx, (unsigned char *)signature.data(), signature.size(), okey->m_key); return err; } bool HHVM_FUNCTION(openssl_x509_check_private_key, const Variant& cert, const Variant& key) { auto ocert = Certificate::Get(cert); if (!ocert) { return false; } auto okey = Key::Get(key, false); if (!okey) { return false; } return X509_check_private_key(ocert->m_cert, okey->m_key); } static int check_cert(X509_STORE *ctx, X509 *x, STACK_OF(X509) *untrustedchain, int purpose) { X509_STORE_CTX *csc = X509_STORE_CTX_new(); if (csc == nullptr) { raise_warning("memory allocation failure"); return 0; } X509_STORE_CTX_init(csc, ctx, x, untrustedchain); if (purpose >= 0) { X509_STORE_CTX_set_purpose(csc, purpose); } int ret = X509_verify_cert(csc); X509_STORE_CTX_free(csc); return ret; } Variant HHVM_FUNCTION(openssl_x509_checkpurpose, const Variant& x509cert, int purpose, const Array& cainfo /* = null_array */, const String& untrustedfile /* = null_string */) { int ret = -1; STACK_OF(X509) *untrustedchain = nullptr; X509_STORE *pcainfo = nullptr; req::ptr<Certificate> ocert; if (!untrustedfile.empty()) { untrustedchain = load_all_certs_from_file(untrustedfile.data()); if (untrustedchain == nullptr) { goto clean_exit; } } pcainfo = setup_verify(cainfo); if (pcainfo == nullptr) { goto clean_exit; } ocert = Certificate::Get(x509cert); if (!ocert) { raise_warning("cannot get cert from parameter 1"); return false; } X509 *cert; cert = ocert->m_cert; assertx(cert); ret = check_cert(pcainfo, cert, untrustedchain, purpose); clean_exit: if (pcainfo) { X509_STORE_free(pcainfo); } if (untrustedchain) { sk_X509_pop_free(untrustedchain, X509_free); } return ret == 1 ? true : ret == 0 ? false : -1; } static bool openssl_x509_export_impl(const Variant& x509, BIO *bio_out, bool notext /* = true */) { auto ocert = Certificate::Get(x509); if (!ocert) { raise_warning("cannot get cert from parameter 1"); return false; } X509 *cert = ocert->m_cert; assertx(cert); assertx(bio_out); if (!notext) { X509_print(bio_out, cert); } return PEM_write_bio_X509(bio_out, cert); } bool HHVM_FUNCTION(openssl_x509_export_to_file, const Variant& x509, const String& outfilename, bool notext /* = true */) { BIO *bio_out = BIO_new_file((char*)outfilename.data(), "w"); if (bio_out == nullptr) { raise_warning("error opening file %s", outfilename.data()); return false; } bool ret = openssl_x509_export_impl(x509, bio_out, notext); BIO_free(bio_out); return ret; } bool HHVM_FUNCTION(openssl_x509_export, const Variant& x509, Variant& output, bool notext /* = true */) { BIO *bio_out = BIO_new(BIO_s_mem()); bool ret = openssl_x509_export_impl(x509, bio_out, notext); if (ret) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); output = String(bio_buf->data, bio_buf->length, CopyString); } BIO_free(bio_out); return ret; } /** * This is how the time string is formatted: * * snprintf(p, sizeof(p), "%02d%02d%02d%02d%02d%02dZ",ts->tm_year%100, * ts->tm_mon+1,ts->tm_mday,ts->tm_hour,ts->tm_min,ts->tm_sec); */ static time_t asn1_time_to_time_t(ASN1_UTCTIME *timestr) { auto const timestr_type = ASN1_STRING_type(timestr); if (timestr_type != V_ASN1_UTCTIME && timestr_type != V_ASN1_GENERALIZEDTIME) { raise_warning("illegal ASN1 data type for timestamp"); return (time_t)-1; } auto const timestr_len = (size_t)ASN1_STRING_length(timestr); // Binary safety if (timestr_len != strlen((char*)ASN1_STRING_data(timestr))) { raise_warning("illegal length in timestamp"); return (time_t)-1; } if (timestr_len < 13 && timestr_len != 11) { raise_warning("unable to parse time string %s correctly", timestr->data); return (time_t)-1; } if (timestr_type == V_ASN1_GENERALIZEDTIME && timestr_len < 15) { raise_warning("unable to parse time string %s correctly", timestr->data); return (time_t)-1; } char *strbuf = strdup((char*)timestr->data); struct tm thetime; memset(&thetime, 0, sizeof(thetime)); /* we work backwards so that we can use atoi more easily */ char *thestr = strbuf + ASN1_STRING_length(timestr) - 3; if (ASN1_STRING_length(timestr) == 11) { thetime.tm_sec = 0; } else { thetime.tm_sec = atoi(thestr); *thestr = '\0'; thestr -= 2; } thetime.tm_min = atoi(thestr); *thestr = '\0'; thestr -= 2; thetime.tm_hour = atoi(thestr); *thestr = '\0'; thestr -= 2; thetime.tm_mday = atoi(thestr); *thestr = '\0'; thestr -= 2; thetime.tm_mon = atoi(thestr)-1; *thestr = '\0'; if (ASN1_STRING_type(timestr) == V_ASN1_UTCTIME) { thestr -= 2; thetime.tm_year = atoi(thestr); if (thetime.tm_year < 68) { thetime.tm_year += 100; } } else if (ASN1_STRING_type(timestr) == V_ASN1_GENERALIZEDTIME) { thestr -= 4; thetime.tm_year = atoi(thestr) - 1900; } thetime.tm_isdst = -1; time_t ret = mktime(&thetime); long gmadjust = 0; #if HAVE_TM_GMTOFF gmadjust = thetime.tm_gmtoff; #elif defined(_MSC_VER) TIME_ZONE_INFORMATION inf; GetTimeZoneInformation(&inf); gmadjust = thetime.tm_isdst ? inf.DaylightBias : inf.StandardBias; #else /** * If correcting for daylight savings time, we set the adjustment to * the value of timezone - 3600 seconds. Otherwise, we need to overcorrect * and set the adjustment to the main timezone + 3600 seconds. */ gmadjust = -(thetime.tm_isdst ? (long)timezone - 3600 : (long)timezone); #endif /* no adjustment for UTC */ if (timezone) ret += gmadjust; free(strbuf); return ret; } /* Special handling of subjectAltName, see CVE-2013-4073 * Christian Heimes */ static int openssl_x509v3_subjectAltName(BIO *bio, X509_EXTENSION *extension) { GENERAL_NAMES *names; const X509V3_EXT_METHOD *method = nullptr; long i, length, num; const unsigned char *p; method = X509V3_EXT_get(extension); if (method == nullptr) { return -1; } const auto data = X509_EXTENSION_get_data(extension); p = data->data; length = data->length; if (method->it) { names = (GENERAL_NAMES*)(ASN1_item_d2i(nullptr, &p, length, ASN1_ITEM_ptr(method->it))); } else { names = (GENERAL_NAMES*)(method->d2i(nullptr, &p, length)); } if (names == nullptr) { return -1; } num = sk_GENERAL_NAME_num(names); for (i = 0; i < num; i++) { GENERAL_NAME *name; ASN1_STRING *as; name = sk_GENERAL_NAME_value(names, i); switch (name->type) { case GEN_EMAIL: BIO_puts(bio, "email:"); as = name->d.rfc822Name; BIO_write(bio, ASN1_STRING_data(as), ASN1_STRING_length(as)); break; case GEN_DNS: BIO_puts(bio, "DNS:"); as = name->d.dNSName; BIO_write(bio, ASN1_STRING_data(as), ASN1_STRING_length(as)); break; case GEN_URI: BIO_puts(bio, "URI:"); as = name->d.uniformResourceIdentifier; BIO_write(bio, ASN1_STRING_data(as), ASN1_STRING_length(as)); break; default: /* use builtin print for GEN_OTHERNAME, GEN_X400, * GEN_EDIPARTY, GEN_DIRNAME, GEN_IPADD and GEN_RID */ GENERAL_NAME_print(bio, name); } /* trailing ', ' except for last element */ if (i < (num - 1)) { BIO_puts(bio, ", "); } } sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free); return 0; } Variant HHVM_FUNCTION(openssl_x509_parse, const Variant& x509cert, bool shortnames /* = true */) { auto ocert = Certificate::Get(x509cert); if (!ocert) { return false; } X509 *cert = ocert->m_cert; assertx(cert); auto ret = Array::CreateDArray(); const auto sn = X509_get_subject_name(cert); if (sn) { ret.set(s_name, String(X509_NAME_oneline(sn, nullptr, 0), CopyString)); } add_assoc_name_entry(ret, "subject", sn, shortnames); /* hash as used in CA directories to lookup cert by subject name */ { char buf[32]; snprintf(buf, sizeof(buf), "%08lx", X509_subject_name_hash(cert)); ret.set(s_hash, String(buf, CopyString)); } add_assoc_name_entry(ret, "issuer", X509_get_issuer_name(cert), shortnames); ret.set(s_version, X509_get_version(cert)); ret.set(s_serialNumber, String (i2s_ASN1_INTEGER(nullptr, X509_get_serialNumber(cert)), AttachString)); // Adding Signature Algorithm BIO *bio_out = BIO_new(BIO_s_mem()); SCOPE_EXIT { BIO_free(bio_out); }; if (i2a_ASN1_OBJECT(bio_out, X509_get0_tbs_sigalg(cert)->algorithm) > 0) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); ret.set(s_signatureAlgorithm, String((char*)bio_buf->data, bio_buf->length, CopyString)); } ASN1_STRING *str = X509_get_notBefore(cert); ret.set(s_validFrom, String((char*)str->data, str->length, CopyString)); str = X509_get_notAfter(cert); ret.set(s_validTo, String((char*)str->data, str->length, CopyString)); ret.set(s_validFrom_time_t, asn1_time_to_time_t(X509_get_notBefore(cert))); ret.set(s_validTo_time_t, asn1_time_to_time_t(X509_get_notAfter(cert))); char *tmpstr = (char *)X509_alias_get0(cert, nullptr); if (tmpstr) { ret.set(s_alias, String(tmpstr, CopyString)); } /* NOTE: the purposes are added as integer keys - the keys match up to the X509_PURPOSE_SSL_XXX defines in x509v3.h */ { Array subitem; for (int i = 0; i < X509_PURPOSE_get_count(); i++) { X509_PURPOSE *purp = X509_PURPOSE_get0(i); int id = X509_PURPOSE_get_id(purp); char * pname = shortnames ? X509_PURPOSE_get0_sname(purp) : X509_PURPOSE_get0_name(purp); auto subsub = make_varray( (bool)X509_check_purpose(cert, id, 0), (bool)X509_check_purpose(cert, id, 1), String(pname, CopyString) ); subitem.set(id, std::move(subsub)); } ret.set(s_purposes, subitem); } { auto subitem = Array::CreateDArray(); for (int i = 0; i < X509_get_ext_count(cert); i++) { int nid; X509_EXTENSION *extension = X509_get_ext(cert, i); char *extname; char buf[256]; nid = OBJ_obj2nid(X509_EXTENSION_get_object(extension)); if (nid != NID_undef) { extname = (char*)OBJ_nid2sn(OBJ_obj2nid (X509_EXTENSION_get_object(extension))); } else { OBJ_obj2txt(buf, sizeof(buf)-1, X509_EXTENSION_get_object(extension), 1); extname = buf; } BIO *bio_out = BIO_new(BIO_s_mem()); if (nid == NID_subject_alt_name) { if (openssl_x509v3_subjectAltName(bio_out, extension) == 0) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); subitem.set(String(extname, CopyString), String((char*)bio_buf->data, bio_buf->length, CopyString)); } else { BIO_free(bio_out); return false; } } else if (X509V3_EXT_print(bio_out, extension, 0, 0)) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); subitem.set(String(extname, CopyString), String((char*)bio_buf->data, bio_buf->length, CopyString)); } else { str = X509_EXTENSION_get_data(extension); subitem.set(String(extname, CopyString), String((char*)str->data, str->length, CopyString)); } BIO_free(bio_out); } ret.set(s_extensions, subitem); } return ret; } Variant HHVM_FUNCTION(openssl_x509_read, const Variant& x509certdata) { auto ocert = Certificate::Get(x509certdata); if (!ocert) { raise_warning("supplied parameter cannot be coerced into " "an X509 certificate!"); return false; } return Variant(ocert); } Variant HHVM_FUNCTION(openssl_random_pseudo_bytes, int length, bool& crypto_strong) { if (length <= 0) { return false; } unsigned char *buffer = nullptr; String s = String(length, ReserveString); buffer = (unsigned char *)s.mutableData(); if (RAND_bytes(buffer, length) <= 0) { crypto_strong = false; return false; } else { crypto_strong = true; s.setSize(length); return s; } } Variant HHVM_FUNCTION(openssl_cipher_iv_length, const String& method) { if (method.empty()) { raise_warning("Unknown cipher algorithm"); return false; } const EVP_CIPHER *cipher_type = EVP_get_cipherbyname(method.c_str()); if (!cipher_type) { raise_warning("Unknown cipher algorithm"); return false; } return EVP_CIPHER_iv_length(cipher_type); } /* Cipher mode info */ struct php_openssl_cipher_mode { /* Whether this mode uses authenticated encryption. True, for example, with the GCM and CCM modes */ bool is_aead; /* Whether this mode is a 'single run aead', meaning that DecryptFinal doesn't get called. For example, CCM mode is a single run aead mode. */ bool is_single_run_aead; /* The OpenSSL flag to get the computed tag, if this mode is aead. */ int aead_get_tag_flag; /* The OpenSSL flag to set the computed tag, if this mode is aead. */ int aead_set_tag_flag; /* The OpenSSL flag to set the IV length, if this mode is aead */ int aead_ivlen_flag; }; // initialize a php_openssl_cipher_mode corresponding to an EVP_CIPHER. static php_openssl_cipher_mode php_openssl_load_cipher_mode( const EVP_CIPHER* cipher_type) { php_openssl_cipher_mode mode = {}; switch (EVP_CIPHER_mode(cipher_type)) { #ifdef EVP_CIPH_GCM_MODE case EVP_CIPH_GCM_MODE: mode.is_aead = true; mode.is_single_run_aead = false; mode.aead_get_tag_flag = EVP_CTRL_GCM_GET_TAG; mode.aead_set_tag_flag = EVP_CTRL_GCM_SET_TAG; mode.aead_ivlen_flag = EVP_CTRL_GCM_SET_IVLEN; break; #endif #ifdef EVP_CIPH_CCM_MODE case EVP_CIPH_CCM_MODE: mode.is_aead = true; mode.is_single_run_aead = true; mode.aead_get_tag_flag = EVP_CTRL_CCM_GET_TAG; mode.aead_set_tag_flag = EVP_CTRL_CCM_SET_TAG; mode.aead_ivlen_flag = EVP_CTRL_CCM_SET_IVLEN; break; #endif default: break; } return mode; } static bool php_openssl_validate_iv( String piv, int iv_required_len, String& out, EVP_CIPHER_CTX* cipher_ctx, const php_openssl_cipher_mode* mode) { if (cipher_ctx == nullptr || mode == nullptr) { return false; } /* Best case scenario, user behaved */ if (piv.size() == iv_required_len) { out = std::move(piv); return true; } if (mode->is_aead) { if (EVP_CIPHER_CTX_ctrl( cipher_ctx, mode->aead_ivlen_flag, piv.size(), nullptr) != 1) { raise_warning( "Setting of IV length for AEAD mode failed, the expected length is " "%d bytes", iv_required_len); return false; } out = std::move(piv); return true; } String s = String(iv_required_len, ReserveString); char* iv_new = s.mutableData(); memset(iv_new, 0, iv_required_len); if (piv.size() <= 0) { /* BC behavior */ s.setSize(iv_required_len); out = std::move(s); return true; } if (piv.size() < iv_required_len) { raise_warning("IV passed is only %ld bytes long, cipher " "expects an IV of precisely %d bytes, padding with \\0", piv.size(), iv_required_len); memcpy(iv_new, piv.data(), piv.size()); s.setSize(iv_required_len); out = std::move(s); return true; } raise_warning("IV passed is %ld bytes long which is longer than the %d " "expected by selected cipher, truncating", piv.size(), iv_required_len); memcpy(iv_new, piv.data(), iv_required_len); s.setSize(iv_required_len); out = std::move(s); return true; } namespace { Variant openssl_encrypt_impl(const String& data, const String& method, const String& password, int options, const String& iv, Variant* tag_out, const String& aad, int tag_length) { const EVP_CIPHER *cipher_type = EVP_get_cipherbyname(method.c_str()); if (!cipher_type) { raise_warning("Unknown cipher algorithm"); return false; } EVP_CIPHER_CTX* cipher_ctx = EVP_CIPHER_CTX_new(); if (!cipher_ctx) { raise_warning("Failed to create cipher context"); return false; } SCOPE_EXIT { EVP_CIPHER_CTX_free(cipher_ctx); }; php_openssl_cipher_mode mode = php_openssl_load_cipher_mode(cipher_type); if (mode.is_aead && !tag_out) { raise_warning("Must call openssl_encrypt_with_tag when using an AEAD cipher"); return false; } int keylen = EVP_CIPHER_key_length(cipher_type); String key = password; /* * older openssl libraries can assert if the passed in password length is * less than keylen */ if (keylen > password.size()) { String s = String(keylen, ReserveString); char *keybuf = s.mutableData(); memset(keybuf, 0, keylen); memcpy(keybuf, password.data(), password.size()); key = s.setSize(keylen); } int max_iv_len = EVP_CIPHER_iv_length(cipher_type); if (iv.size() <= 0 && max_iv_len > 0 && !mode.is_aead) { raise_warning("Using an empty Initialization Vector (iv) is potentially " "insecure and not recommended"); } int result_len = 0; int outlen = data.size() + EVP_CIPHER_block_size(cipher_type); String rv = String(outlen, ReserveString); unsigned char *outbuf = (unsigned char*)rv.mutableData(); EVP_EncryptInit_ex(cipher_ctx, cipher_type, nullptr, nullptr, nullptr); String new_iv; // we do this after EncryptInit because validate_iv changes cipher_ctx for // aead modes (must be initialized first). if (!php_openssl_validate_iv( std::move(iv), max_iv_len, new_iv, cipher_ctx, &mode)) { return false; } // set the tag length for CCM mode/other modes that require tag lengths to // be set. if (mode.is_single_run_aead && !EVP_CIPHER_CTX_ctrl( cipher_ctx, mode.aead_set_tag_flag, tag_length, nullptr)) { raise_warning("Setting tag length failed"); return false; } if (password.size() > keylen) { EVP_CIPHER_CTX_set_key_length(cipher_ctx, password.size()); } EVP_EncryptInit_ex( cipher_ctx, nullptr, nullptr, (unsigned char*)key.data(), (unsigned char*)new_iv.data()); if (options & k_OPENSSL_ZERO_PADDING) { EVP_CIPHER_CTX_set_padding(cipher_ctx, 0); } // for single run aeads like CCM, we need to provide the length of the // plaintext before providing AAD or ciphertext. if (mode.is_single_run_aead && !EVP_EncryptUpdate( cipher_ctx, nullptr, &result_len, nullptr, data.size())) { raise_warning("Setting of data length failed"); return false; } // set up aad: if (mode.is_aead && !EVP_EncryptUpdate( cipher_ctx, nullptr, &result_len, (unsigned char*)aad.data(), aad.size())) { raise_warning("Setting of additional application data failed"); return false; } // OpenSSL before 0.9.8i asserts with size < 0 if (data.size() >= 0) { EVP_EncryptUpdate(cipher_ctx, outbuf, &result_len, (unsigned char *)data.data(), data.size()); } outlen = result_len; if (EVP_EncryptFinal_ex( cipher_ctx, (unsigned char*)outbuf + result_len, &result_len)) { outlen += result_len; rv.setSize(outlen); // Get tag if possible if (mode.is_aead) { String tagrv = String(tag_length, ReserveString); if (EVP_CIPHER_CTX_ctrl( cipher_ctx, mode.aead_get_tag_flag, tag_length, tagrv.mutableData()) == 1) { tagrv.setSize(tag_length); assertx(tag_out); *tag_out = tagrv; } else { raise_warning("Retrieving authentication tag failed"); return false; } } else if (tag_out) { raise_warning( "The authenticated tag cannot be provided for cipher that does not" " support AEAD"); } // Return encrypted data if (options & k_OPENSSL_RAW_DATA) { return rv; } else { return StringUtil::Base64Encode(rv); } } return false; } } // anonymous namespace Variant HHVM_FUNCTION(openssl_encrypt, const String& data, const String& method, const String& password, int options /* = 0 */, const String& iv /* = null_string */, const String& aad /* = null_string */, int tag_length /* = 16 */) { return openssl_encrypt_impl(data, method, password, options, iv, nullptr, aad, tag_length); } Variant HHVM_FUNCTION(openssl_encrypt_with_tag, const String& data, const String& method, const String& password, int options, const String& iv, Variant& tag_out, const String& aad /* = null_string */, int tag_length /* = 16 */) { return openssl_encrypt_impl(data, method, password, options, iv, &tag_out, aad, tag_length); } Variant HHVM_FUNCTION(openssl_decrypt, const String& data, const String& method, const String& password, int options /* = 0 */, const String& iv /* = null_string */, const String& tag /* = null_string */, const String& aad /* = null_string */) { const EVP_CIPHER *cipher_type = EVP_get_cipherbyname(method.c_str()); if (!cipher_type) { raise_warning("Unknown cipher algorithm"); return false; } EVP_CIPHER_CTX* cipher_ctx = EVP_CIPHER_CTX_new(); if (!cipher_ctx) { raise_warning("Failed to create cipher context"); return false; } SCOPE_EXIT { EVP_CIPHER_CTX_free(cipher_ctx); }; php_openssl_cipher_mode mode = php_openssl_load_cipher_mode(cipher_type); String decoded_data = data; if (!(options & k_OPENSSL_RAW_DATA)) { decoded_data = StringUtil::Base64Decode(data); } int keylen = EVP_CIPHER_key_length(cipher_type); String key = password; /* * older openssl libraries can assert if the passed in password length is * less than keylen */ if (keylen > password.size()) { String s = String(keylen, ReserveString); char *keybuf = s.mutableData(); memset(keybuf, 0, keylen); memcpy(keybuf, password.data(), password.size()); key = s.setSize(keylen); } int result_len = 0; int outlen = decoded_data.size() + EVP_CIPHER_block_size(cipher_type); String rv = String(outlen, ReserveString); unsigned char *outbuf = (unsigned char*)rv.mutableData(); EVP_DecryptInit_ex(cipher_ctx, cipher_type, nullptr, nullptr, nullptr); String new_iv; // we do this after DecryptInit because validate_iv changes cipher_ctx for // aead modes (must be initialized first). if (!php_openssl_validate_iv( std::move(iv), EVP_CIPHER_iv_length(cipher_type), new_iv, cipher_ctx, &mode)) { return false; } // set the tag if required: if (tag.size() > 0) { if (!mode.is_aead) { raise_warning( "The tag is being ignored because the cipher method does not" " support AEAD"); } else if (!EVP_CIPHER_CTX_ctrl( cipher_ctx, mode.aead_set_tag_flag, tag.size(), (unsigned char*)tag.data())) { raise_warning("Setting tag for AEAD cipher decryption failed"); return false; } } else { if (mode.is_aead) { raise_warning("A tag should be provided when using AEAD mode"); return false; } } if (password.size() > keylen) { EVP_CIPHER_CTX_set_key_length(cipher_ctx, password.size()); } EVP_DecryptInit_ex( cipher_ctx, nullptr, nullptr, (unsigned char*)key.data(), (unsigned char*)new_iv.data()); if (options & k_OPENSSL_ZERO_PADDING) { EVP_CIPHER_CTX_set_padding(cipher_ctx, 0); } // for single run aeads like CCM, we need to provide the length of the // ciphertext before providing AAD or ciphertext. if (mode.is_single_run_aead && !EVP_DecryptUpdate( cipher_ctx, nullptr, &result_len, nullptr, decoded_data.size())) { raise_warning("Setting of data length failed"); return false; } // set up aad: if (mode.is_aead && !EVP_DecryptUpdate( cipher_ctx, nullptr, &result_len, (unsigned char*)aad.data(), aad.size())) { raise_warning("Setting of additional application data failed"); return false; } if (!EVP_DecryptUpdate( cipher_ctx, outbuf, &result_len, (unsigned char*)decoded_data.data(), decoded_data.size())) { return false; } outlen = result_len; // if is_single_run_aead is enabled, DecryptFinal shouldn't be called. // if something went wrong in this case, we would've caught it at // DecryptUpdate. if (mode.is_single_run_aead || EVP_DecryptFinal_ex( cipher_ctx, (unsigned char*)outbuf + result_len, &result_len)) { // don't want to do this if is_single_run_aead was enabled, since we didn't // make a call to EVP_DecryptFinal. if (!mode.is_single_run_aead) { outlen += result_len; } rv.setSize(outlen); return rv; } else { return false; } } Variant HHVM_FUNCTION(openssl_digest, const String& data, const String& method, bool raw_output /* = false */) { const EVP_MD *mdtype = EVP_get_digestbyname(method.c_str()); if (!mdtype) { raise_warning("Unknown signature algorithm"); return false; } int siglen = EVP_MD_size(mdtype); String rv = String(siglen, ReserveString); unsigned char *sigbuf = (unsigned char *)rv.mutableData(); EVP_MD_CTX *md_ctx = EVP_MD_CTX_new(); SCOPE_EXIT { EVP_MD_CTX_free(md_ctx); }; EVP_DigestInit(md_ctx, mdtype); EVP_DigestUpdate(md_ctx, (unsigned char *)data.data(), data.size()); if (EVP_DigestFinal(md_ctx, (unsigned char *)sigbuf, (unsigned int *)&siglen)) { if (raw_output) { rv.setSize(siglen); return rv; } else { char* digest_str = string_bin2hex((char*)sigbuf, siglen); return String(digest_str, AttachString); } } else { return false; } } static void openssl_add_method_or_alias(const OBJ_NAME *name, void *arg) { Array *ret = (Array*)arg; ret->append(String((char *)name->name, CopyString)); } static void openssl_add_method(const OBJ_NAME *name, void *arg) { if (name->alias == 0) { Array *ret = (Array*)arg; ret->append(String((char *)name->name, CopyString)); } } Array HHVM_FUNCTION(openssl_get_cipher_methods, bool aliases /* = false */) { Array ret = Array::CreateVArray(); OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH, aliases ? openssl_add_method_or_alias: openssl_add_method, &ret); return ret; } Variant HHVM_FUNCTION(openssl_get_curve_names) { #ifdef HAVE_EVP_PKEY_EC const size_t len = EC_get_builtin_curves(nullptr, 0); std::unique_ptr<EC_builtin_curve[]> curves(new EC_builtin_curve[len]); if (!EC_get_builtin_curves(curves.get(), len)) { return false; } VArrayInit ret(len); for (size_t i = 0; i < len; ++i) { auto const sname = OBJ_nid2sn(curves[i].nid); if (sname != nullptr) { ret.append(String(sname, CopyString)); } } return ret.toArray(); #else return false; #endif } Array HHVM_FUNCTION(openssl_get_md_methods, bool aliases /* = false */) { Array ret = Array::CreateVArray(); OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_MD_METH, aliases ? openssl_add_method_or_alias: openssl_add_method, &ret); return ret; } ///////////////////////////////////////////////////////////////////////////// const StaticString s_OPENSSL_VERSION_TEXT("OPENSSL_VERSION_TEXT"); struct opensslExtension final : Extension { opensslExtension() : Extension("openssl") {} void moduleInit() override { HHVM_RC_INT(OPENSSL_RAW_DATA, k_OPENSSL_RAW_DATA); HHVM_RC_INT(OPENSSL_ZERO_PADDING, k_OPENSSL_ZERO_PADDING); HHVM_RC_INT(OPENSSL_NO_PADDING, k_OPENSSL_NO_PADDING); HHVM_RC_INT(OPENSSL_PKCS1_OAEP_PADDING, k_OPENSSL_PKCS1_OAEP_PADDING); HHVM_RC_INT(OPENSSL_SSLV23_PADDING, k_OPENSSL_SSLV23_PADDING); HHVM_RC_INT(OPENSSL_PKCS1_PADDING, k_OPENSSL_PKCS1_PADDING); HHVM_RC_INT_SAME(OPENSSL_ALGO_SHA1); HHVM_RC_INT_SAME(OPENSSL_ALGO_MD5); HHVM_RC_INT_SAME(OPENSSL_ALGO_MD4); #ifdef HAVE_OPENSSL_MD2_H HHVM_RC_INT_SAME(OPENSSL_ALGO_MD2); #endif HHVM_RC_INT_SAME(OPENSSL_ALGO_DSS1); HHVM_RC_INT_SAME(OPENSSL_ALGO_SHA224); HHVM_RC_INT_SAME(OPENSSL_ALGO_SHA256); HHVM_RC_INT_SAME(OPENSSL_ALGO_SHA384); HHVM_RC_INT_SAME(OPENSSL_ALGO_SHA512); HHVM_RC_INT_SAME(OPENSSL_ALGO_RMD160); HHVM_RC_INT(OPENSSL_CIPHER_RC2_40, PHP_OPENSSL_CIPHER_RC2_40); HHVM_RC_INT(OPENSSL_CIPHER_RC2_128, PHP_OPENSSL_CIPHER_RC2_128); HHVM_RC_INT(OPENSSL_CIPHER_RC2_64, PHP_OPENSSL_CIPHER_RC2_64); HHVM_RC_INT(OPENSSL_CIPHER_DES, PHP_OPENSSL_CIPHER_DES); HHVM_RC_INT(OPENSSL_CIPHER_3DES, PHP_OPENSSL_CIPHER_3DES); HHVM_RC_INT_SAME(OPENSSL_KEYTYPE_RSA); HHVM_RC_INT_SAME(OPENSSL_KEYTYPE_DSA); HHVM_RC_INT_SAME(OPENSSL_KEYTYPE_DH); #ifdef HAVE_EVP_PKEY_EC HHVM_RC_INT_SAME(OPENSSL_KEYTYPE_EC); #endif HHVM_RC_INT_SAME(OPENSSL_VERSION_NUMBER); HHVM_RC_INT_SAME(PKCS7_TEXT); HHVM_RC_INT_SAME(PKCS7_NOCERTS); HHVM_RC_INT_SAME(PKCS7_NOSIGS); HHVM_RC_INT_SAME(PKCS7_NOCHAIN); HHVM_RC_INT_SAME(PKCS7_NOINTERN); HHVM_RC_INT_SAME(PKCS7_NOVERIFY); HHVM_RC_INT_SAME(PKCS7_DETACHED); HHVM_RC_INT_SAME(PKCS7_BINARY); HHVM_RC_INT_SAME(PKCS7_NOATTR); HHVM_RC_STR_SAME(OPENSSL_VERSION_TEXT); HHVM_RC_INT_SAME(X509_PURPOSE_SSL_CLIENT); HHVM_RC_INT_SAME(X509_PURPOSE_SSL_SERVER); HHVM_RC_INT_SAME(X509_PURPOSE_NS_SSL_SERVER); HHVM_RC_INT_SAME(X509_PURPOSE_SMIME_SIGN); HHVM_RC_INT_SAME(X509_PURPOSE_SMIME_ENCRYPT); HHVM_RC_INT_SAME(X509_PURPOSE_CRL_SIGN); #ifdef X509_PURPOSE_ANY HHVM_RC_INT_SAME(X509_PURPOSE_ANY); #endif HHVM_FE(openssl_csr_export_to_file); HHVM_FE(openssl_csr_export); HHVM_FE(openssl_csr_get_public_key); HHVM_FE(openssl_csr_get_subject); HHVM_FE(openssl_csr_new); HHVM_FE(openssl_csr_sign); HHVM_FE(openssl_error_string); HHVM_FE(openssl_open); HHVM_FE(openssl_pkcs12_export_to_file); HHVM_FE(openssl_pkcs12_export); HHVM_FE(openssl_pkcs12_read); HHVM_FE(openssl_pkcs7_decrypt); HHVM_FE(openssl_pkcs7_encrypt); HHVM_FE(openssl_pkcs7_sign); HHVM_FE(openssl_pkcs7_verify); HHVM_FE(openssl_pkey_export_to_file); HHVM_FE(openssl_pkey_export); HHVM_FE(openssl_pkey_get_details); HHVM_FE(openssl_pkey_get_private); HHVM_FE(openssl_pkey_get_public); HHVM_FE(openssl_pkey_new); HHVM_FE(openssl_private_decrypt); HHVM_FE(openssl_private_encrypt); HHVM_FE(openssl_public_decrypt); HHVM_FE(openssl_public_encrypt); HHVM_FE(openssl_seal); HHVM_FE(openssl_sign); HHVM_FE(openssl_verify); HHVM_FE(openssl_x509_check_private_key); HHVM_FE(openssl_x509_checkpurpose); HHVM_FE(openssl_x509_export_to_file); HHVM_FE(openssl_x509_export); HHVM_FE(openssl_x509_parse); HHVM_FE(openssl_x509_read); HHVM_FE(openssl_random_pseudo_bytes); HHVM_FE(openssl_cipher_iv_length); HHVM_FE(openssl_encrypt); HHVM_FE(openssl_encrypt_with_tag); HHVM_FE(openssl_decrypt); HHVM_FE(openssl_digest); HHVM_FE(openssl_get_cipher_methods); HHVM_FE(openssl_get_curve_names); HHVM_FE(openssl_get_md_methods); loadSystemlib(); } } s_openssl_extension; /////////////////////////////////////////////////////////////////////////////// }
null
198
CWE-787
CVE-2020-1921
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1997-2010 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/ext/openssl/ext_openssl.h" #include "hphp/runtime/base/array-init.h" #include "hphp/runtime/base/array-iterator.h" #include "hphp/runtime/base/ssl-socket.h" #include "hphp/runtime/base/string-util.h" #include "hphp/runtime/base/zend-string.h" #include "hphp/util/logger.h" #include <folly/ScopeGuard.h> #include <openssl/conf.h> #include <openssl/pem.h> #include <openssl/pkcs12.h> #include <openssl/rand.h> #include <vector> namespace HPHP { #define MIN_KEY_LENGTH 384 // bitfields const int64_t k_OPENSSL_RAW_DATA = 1; const int64_t k_OPENSSL_ZERO_PADDING = 2; const int64_t k_OPENSSL_NO_PADDING = 3; const int64_t k_OPENSSL_PKCS1_OAEP_PADDING = 4; // exported constants const int64_t k_OPENSSL_SSLV23_PADDING = 2; const int64_t k_OPENSSL_PKCS1_PADDING = 1; static char default_ssl_conf_filename[PATH_MAX]; struct OpenSSLInitializer { OpenSSLInitializer() { SSL_library_init(); OpenSSL_add_all_ciphers(); OpenSSL_add_all_digests(); OpenSSL_add_all_algorithms(); // CCM ciphers are not added by default, so let's add them! #if !defined(OPENSSL_NO_AES) && defined(EVP_CIPH_CCM_MODE) && \ OPENSSL_VERSION_NUMBER < 0x100020000 EVP_add_cipher(EVP_aes_128_ccm()); EVP_add_cipher(EVP_aes_192_ccm()); EVP_add_cipher(EVP_aes_256_ccm()); #endif ERR_load_ERR_strings(); ERR_load_crypto_strings(); ERR_load_EVP_strings(); /* Determine default SSL configuration file */ char *config_filename = getenv("OPENSSL_CONF"); if (config_filename == nullptr) { config_filename = getenv("SSLEAY_CONF"); } /* default to 'openssl.cnf' if no environment variable is set */ if (config_filename == nullptr) { snprintf(default_ssl_conf_filename, sizeof(default_ssl_conf_filename), "%s/%s", X509_get_default_cert_area(), "openssl.cnf"); } else { always_assert( strlen(config_filename) < sizeof(default_ssl_conf_filename)); strcpy(default_ssl_conf_filename, config_filename); } } ~OpenSSLInitializer() { EVP_cleanup(); } }; static OpenSSLInitializer s_openssl_initializer; /////////////////////////////////////////////////////////////////////////////// // resource classes struct Key : SweepableResourceData { EVP_PKEY *m_key; explicit Key(EVP_PKEY *key) : m_key(key) { assertx(m_key);} ~Key() override { if (m_key) EVP_PKEY_free(m_key); } CLASSNAME_IS("OpenSSL key"); // overriding ResourceData const String& o_getClassNameHook() const override { return classnameof(); } DECLARE_RESOURCE_ALLOCATION(Key) bool isPrivate() { assertx(m_key); switch (EVP_PKEY_id(m_key)) { #ifndef NO_RSA case EVP_PKEY_RSA: case EVP_PKEY_RSA2: { const auto rsa = EVP_PKEY_get0_RSA(m_key); assertx(rsa); const BIGNUM *p, *q; RSA_get0_factors(rsa, &p, &q); if (!p || !q) { return false; } break; } #endif #ifndef NO_DSA case EVP_PKEY_DSA: case EVP_PKEY_DSA1: case EVP_PKEY_DSA2: case EVP_PKEY_DSA3: case EVP_PKEY_DSA4: { const auto dsa = EVP_PKEY_get0_DSA(m_key); assertx(dsa); const BIGNUM *p, *q, *g, *pub_key, *priv_key; DSA_get0_pqg(dsa, &p, &q, &g); if (!p || !q || !g) { return false; } DSA_get0_key(dsa, &pub_key, &priv_key); if (!priv_key) { return false; } break; } #endif #ifndef NO_DH case EVP_PKEY_DH: { const auto dh = EVP_PKEY_get0_DH(m_key); assertx(dh); const BIGNUM *p, *q, *g, *pub_key, *priv_key; DH_get0_pqg(dh, &p, &q, &g); if (!p) { return false; } DH_get0_key(dh, &pub_key, &priv_key); if (!priv_key) { return false; } break; } #endif #ifdef HAVE_EVP_PKEY_EC case EVP_PKEY_EC: { const auto ec_key = EVP_PKEY_get0_EC_KEY(m_key); assertx(ec_key); if (EC_KEY_get0_private_key(ec_key) == nullptr) { return false; } break; } #endif default: raise_warning("key type not supported in this PHP build!"); break; } return true; } /** * Given a variant, coerce it into a EVP_PKEY object. It can be: * * 1. private key resource from openssl_get_privatekey() * 2. X509 resource -> public key will be extracted from it * 3. if it starts with file:// interpreted as path to key file * 4. interpreted as the data from the cert/key file and interpreted in * same way as openssl_get_privatekey() * 5. an array(0 => [items 2..4], 1 => passphrase) * 6. if val is a string (possibly starting with file:///) and it is not * an X509 certificate, then interpret as public key * * NOTE: If you are requesting a private key but have not specified a * passphrase, you should use an empty string rather than nullptr for the * passphrase - nullptr causes a passphrase prompt to be emitted in * the Apache error log! */ static req::ptr<Key> Get(const Variant& var, bool public_key, const char *passphrase = nullptr) { if (var.isArray()) { Array arr = var.toArray(); if (!arr.exists(int64_t(0)) || !arr.exists(int64_t(1))) { raise_warning("key array must be of the form " "array(0 => key, 1 => phrase)"); return nullptr; } String zphrase = arr[1].toString(); return GetHelper(arr[0], public_key, zphrase.data()); } return GetHelper(var, public_key, passphrase); } static req::ptr<Key> GetHelper(const Variant& var, bool public_key, const char *passphrase) { req::ptr<Certificate> ocert; EVP_PKEY *key = nullptr; if (var.isResource()) { auto cert = dyn_cast_or_null<Certificate>(var); auto key = dyn_cast_or_null<Key>(var); if (!cert && !key) return nullptr; if (key) { bool is_priv = key->isPrivate(); if (!public_key && !is_priv) { raise_warning("supplied key param is a public key"); return nullptr; } if (public_key && is_priv) { raise_warning("Don't know how to get public key from " "this private key"); return nullptr; } return key; } ocert = cert; } else { /* it's an X509 file/cert of some kind, and we need to extract the data from that */ if (public_key) { ocert = Certificate::Get(var); if (!ocert) { /* not a X509 certificate, try to retrieve public key */ BIO *in = Certificate::ReadData(var); if (in == nullptr) return nullptr; key = PEM_read_bio_PUBKEY(in, nullptr,nullptr, nullptr); BIO_free(in); } } else { /* we want the private key */ BIO *in = Certificate::ReadData(var); if (in == nullptr) return nullptr; key = PEM_read_bio_PrivateKey(in, nullptr,nullptr, (void*)passphrase); BIO_free(in); } } if (public_key && ocert && key == nullptr) { /* extract public key from X509 cert */ key = (EVP_PKEY *)X509_get_pubkey(ocert->get()); } if (key) { return req::make<Key>(key); } return nullptr; } }; IMPLEMENT_RESOURCE_ALLOCATION(Key) /** * Certificate Signing Request */ struct CSRequest : SweepableResourceData { private: X509_REQ *m_csr; public: explicit CSRequest(X509_REQ *csr) : m_csr(csr) { assertx(m_csr); } X509_REQ *csr() { return m_csr; } ~CSRequest() override { // X509_REQ_free(nullptr) is a no-op X509_REQ_free(m_csr); } CLASSNAME_IS("OpenSSL X.509 CSR"); // overriding ResourceData const String& o_getClassNameHook() const override { return classnameof(); } DECLARE_RESOURCE_ALLOCATION(CSRequest) static req::ptr<CSRequest> Get(const Variant& var) { auto csr = cast_or_null<CSRequest>(GetRequest(var)); if (!csr || !csr->m_csr) { raise_warning("cannot get CSR"); return nullptr; } return csr; } private: static req::ptr<CSRequest> GetRequest(const Variant& var) { if (var.isResource()) { return dyn_cast_or_null<CSRequest>(var); } if (var.isString() || var.isObject()) { BIO *in = Certificate::ReadData(var); if (in == nullptr) return nullptr; X509_REQ *csr = PEM_read_bio_X509_REQ(in, nullptr,nullptr,nullptr); BIO_free(in); if (csr) { return req::make<CSRequest>(csr); } } return nullptr; } }; IMPLEMENT_RESOURCE_ALLOCATION(CSRequest) struct php_x509_request { #if OPENSSL_VERSION_NUMBER >= 0x10000002L LHASH_OF(CONF_VALUE) * global_config; /* Global SSL config */ LHASH_OF(CONF_VALUE) * req_config; /* SSL config for this request */ #else LHASH *global_config; /* Global SSL config */ LHASH *req_config; /* SSL config for this request */ #endif const EVP_MD *md_alg; const EVP_MD *digest; const char *section_name; const char *config_filename; const char *digest_name; const char *extensions_section; const char *request_extensions_section; int priv_key_bits; int priv_key_type; int priv_key_encrypt; #ifdef HAVE_EVP_PKEY_EC int curve_name; #endif EVP_PKEY *priv_key; static bool load_rand_file(const char *file, int *egdsocket, int *seeded) { char buffer[PATH_MAX]; *egdsocket = 0; *seeded = 0; if (file == nullptr) { file = RAND_file_name(buffer, sizeof(buffer)); #if !defined(OPENSSL_NO_RAND_EGD) && !defined(OPENSSL_NO_EGD) } else if (RAND_egd(file) > 0) { /* if the given filename is an EGD socket, don't * write anything back to it */ *egdsocket = 1; return true; #endif } if (file == nullptr || !RAND_load_file(file, -1)) { if (RAND_status() == 0) { raise_warning("unable to load random state; not enough data!"); return false; } return false; } *seeded = 1; return true; } static bool write_rand_file(const char *file, int egdsocket, int seeded) { char buffer[PATH_MAX]; if (egdsocket || !seeded) { /* if we did not manage to read the seed file, we should not write * a low-entropy seed file back */ return false; } if (file == nullptr) { file = RAND_file_name(buffer, sizeof(buffer)); } if (file == nullptr || !RAND_write_file(file)) { raise_warning("unable to write random state"); return false; } return true; } bool generatePrivateKey() { assertx(priv_key == nullptr); if (priv_key_bits < MIN_KEY_LENGTH) { raise_warning("private key length is too short; it needs to be " "at least %d bits, not %d", MIN_KEY_LENGTH, priv_key_bits); return false; } char *randfile = CONF_get_string(req_config, section_name, "RANDFILE"); int egdsocket, seeded; load_rand_file(randfile, &egdsocket, &seeded); bool ret = false; if ((priv_key = EVP_PKEY_new()) != nullptr) { switch (priv_key_type) { case OPENSSL_KEYTYPE_RSA: if (EVP_PKEY_assign_RSA (priv_key, RSA_generate_key(priv_key_bits, 0x10001, nullptr, nullptr))) { ret = true; } break; #if !defined(NO_DSA) && defined(HAVE_DSA_DEFAULT_METHOD) case OPENSSL_KEYTYPE_DSA: { DSA *dsapar = DSA_generate_parameters(priv_key_bits, nullptr, 0, nullptr, nullptr, nullptr, nullptr); if (dsapar) { DSA_set_method(dsapar, DSA_get_default_method()); if (DSA_generate_key(dsapar)) { if (EVP_PKEY_assign_DSA(priv_key, dsapar)) { ret = true; } } else { DSA_free(dsapar); } } } break; #endif #ifdef HAVE_EVP_PKEY_EC case OPENSSL_KEYTYPE_EC: { if (curve_name == NID_undef) { raise_warning("Missing configuration value: 'curve_name' not set"); return false; } if (auto const eckey = EC_KEY_new_by_curve_name(curve_name)) { EC_KEY_set_asn1_flag(eckey, OPENSSL_EC_NAMED_CURVE); if (EC_KEY_generate_key(eckey) && EVP_PKEY_assign_EC_KEY(priv_key, eckey)) { ret = true; } else { EC_KEY_free(eckey); } } } break; #endif default: raise_warning("Unsupported private key type"); } } write_rand_file(randfile, egdsocket, seeded); return ret; } }; /////////////////////////////////////////////////////////////////////////////// // utilities static void add_assoc_name_entry(Array &ret, const char *key, X509_NAME *name, bool shortname) { Array subitem_data; Array &subitem = key ? subitem_data : ret; for (int i = 0; i < X509_NAME_entry_count(name); i++) { X509_NAME_ENTRY *ne = X509_NAME_get_entry(name, i); ASN1_OBJECT *obj = X509_NAME_ENTRY_get_object(ne); int nid = OBJ_obj2nid(obj); int obj_cnt = 0; char *sname; if (shortname) { sname = (char *)OBJ_nid2sn(nid); } else { sname = (char *)OBJ_nid2ln(nid); } Array subentries; int last = -1; int j; ASN1_STRING *str = nullptr; unsigned char *to_add = nullptr; int to_add_len = 0; for (;;) { j = X509_NAME_get_index_by_OBJ(name, obj, last); if (j < 0) { if (last != -1) break; } else { obj_cnt++; ne = X509_NAME_get_entry(name, j); str = X509_NAME_ENTRY_get_data(ne); if (ASN1_STRING_type(str) != V_ASN1_UTF8STRING) { to_add_len = ASN1_STRING_to_UTF8(&to_add, str); if (to_add_len != -1) { subentries.append(String((char*)to_add, to_add_len, AttachString)); } } else { to_add = ASN1_STRING_data(str); to_add_len = ASN1_STRING_length(str); subentries.append(String((char*)to_add, to_add_len, CopyString)); } } last = j; } i = last; if (obj_cnt > 1) { subitem.set(String(sname, CopyString), subentries); } else if (obj_cnt && str && to_add_len > -1) { // Use the string instance we created above. subitem.set(String(sname, CopyString), subentries[0]); } } if (key) { ret.set(String(key, CopyString), subitem); } } static const char *read_string(const Array& args, const String& key, const char *def, std::vector<String> &strings) { if (args.exists(key)) { String value = args[key].toString(); strings.push_back(value); return (char*)value.data(); } return def; } static int64_t read_integer(const Array& args, const String& key, int64_t def) { if (args.exists(key)) { return args[key].toInt64(); } return def; } static bool add_oid_section(struct php_x509_request *req) { char *str = CONF_get_string(req->req_config, nullptr, "oid_section"); if (str == nullptr) { return true; } STACK_OF(CONF_VALUE) *sktmp = CONF_get_section(req->req_config, str); if (sktmp == nullptr) { raise_warning("problem loading oid section %s", str); return false; } for (int i = 0; i < sk_CONF_VALUE_num(sktmp); i++) { CONF_VALUE *cnf = sk_CONF_VALUE_value(sktmp, i); if (OBJ_sn2nid(cnf->name) == NID_undef && OBJ_ln2nid(cnf->name) == NID_undef && OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) { raise_warning("problem creating object %s=%s", cnf->name, cnf->value); return false; } } return true; } #if OPENSSL_VERSION_NUMBER >= 0x10000002L static inline bool php_openssl_config_check_syntax (const char *section_label, const char *config_filename, const char *section, LHASH_OF(CONF_VALUE) *config) { #else static inline bool php_openssl_config_check_syntax (const char *section_label, const char *config_filename, const char *section, LHASH *config) { #endif X509V3_CTX ctx; X509V3_set_ctx_test(&ctx); X509V3_set_conf_lhash(&ctx, config); if (!X509V3_EXT_add_conf(config, &ctx, (char*)section, nullptr)) { raise_warning("Error loading %s section %s of %s", section_label, section, config_filename); return false; } return true; } const StaticString s_config("config"), s_config_section_name("config_section_name"), s_digest_alg("digest_alg"), s_x509_extensions("x509_extensions"), s_req_extensions("req_extensions"), s_private_key_bits("private_key_bits"), s_private_key_type("private_key_type"), s_encrypt_key("encrypt_key"), s_curve_name("curve_name"); static bool php_openssl_parse_config(struct php_x509_request *req, const Array& args, std::vector<String> &strings) { req->config_filename = read_string(args, s_config, default_ssl_conf_filename, strings); req->section_name = read_string(args, s_config_section_name, "req", strings); req->global_config = CONF_load(nullptr, default_ssl_conf_filename, nullptr); req->req_config = CONF_load(nullptr, req->config_filename, nullptr); if (req->req_config == nullptr) { return false; } /* read in the oids */ char *str = CONF_get_string(req->req_config, nullptr, "oid_file"); if (str) { BIO *oid_bio = BIO_new_file(str, "r"); if (oid_bio) { OBJ_create_objects(oid_bio); BIO_free(oid_bio); } } if (!add_oid_section(req)) { return false; } req->digest_name = read_string(args, s_digest_alg, CONF_get_string(req->req_config, req->section_name, "default_md"), strings); req->extensions_section = read_string(args, s_x509_extensions, CONF_get_string(req->req_config, req->section_name, "x509_extensions"), strings); req->request_extensions_section = read_string(args, s_req_extensions, CONF_get_string(req->req_config, req->section_name, "req_extensions"), strings); req->priv_key_bits = read_integer(args, s_private_key_bits, CONF_get_number(req->req_config, req->section_name, "default_bits")); req->priv_key_type = read_integer(args, s_private_key_type, OPENSSL_KEYTYPE_DEFAULT); if (args.exists(s_encrypt_key)) { bool value = args[s_encrypt_key].toBoolean(); req->priv_key_encrypt = value ? 1 : 0; } else { str = CONF_get_string(req->req_config, req->section_name, "encrypt_rsa_key"); if (str == nullptr) { str = CONF_get_string(req->req_config, req->section_name, "encrypt_key"); } if (str && strcmp(str, "no") == 0) { req->priv_key_encrypt = 0; } else { req->priv_key_encrypt = 1; } } /* digest alg */ if (req->digest_name == nullptr) { req->digest_name = CONF_get_string(req->req_config, req->section_name, "default_md"); } if (req->digest_name) { req->digest = req->md_alg = EVP_get_digestbyname(req->digest_name); } if (req->md_alg == nullptr) { req->md_alg = req->digest = EVP_sha256(); } #ifdef HAVE_EVP_PKEY_EC /* set the ec group curve name */ req->curve_name = NID_undef; if (args.exists(s_curve_name)) { auto const curve_name = args[s_curve_name].toString(); req->curve_name = OBJ_sn2nid(curve_name.data()); if (req->curve_name == NID_undef) { raise_warning( "Unknown elliptic curve (short) name %s", curve_name.data() ); return false; } } #endif if (req->extensions_section && !php_openssl_config_check_syntax ("extensions_section", req->config_filename, req->extensions_section, req->req_config)) { return false; } /* set the string mask */ str = CONF_get_string(req->req_config, req->section_name, "string_mask"); if (str && !ASN1_STRING_set_default_mask_asc(str)) { raise_warning("Invalid global string mask setting %s", str); return false; } if (req->request_extensions_section && !php_openssl_config_check_syntax ("request_extensions_section", req->config_filename, req->request_extensions_section, req->req_config)) { return false; } return true; } static void php_openssl_dispose_config(struct php_x509_request *req) { if (req->global_config) { CONF_free(req->global_config); req->global_config = nullptr; } if (req->req_config) { CONF_free(req->req_config); req->req_config = nullptr; } } static STACK_OF(X509) *load_all_certs_from_file(const char *certfile) { STACK_OF(X509_INFO) *sk = nullptr; STACK_OF(X509) *stack = nullptr, *ret = nullptr; BIO *in = nullptr; X509_INFO *xi; if (!(stack = sk_X509_new_null())) { raise_warning("memory allocation failure"); goto end; } if (!(in = BIO_new_file(certfile, "r"))) { raise_warning("error opening the file, %s", certfile); sk_X509_free(stack); goto end; } /* This loads from a file, a stack of x509/crl/pkey sets */ if (!(sk = PEM_X509_INFO_read_bio(in, nullptr, nullptr, nullptr))) { raise_warning("error reading the file, %s", certfile); sk_X509_free(stack); goto end; } /* scan over it and pull out the certs */ while (sk_X509_INFO_num(sk)) { xi = sk_X509_INFO_shift(sk); if (xi->x509 != nullptr) { sk_X509_push(stack, xi->x509); xi->x509 = nullptr; } X509_INFO_free(xi); } if (!sk_X509_num(stack)) { raise_warning("no certificates in file, %s", certfile); sk_X509_free(stack); goto end; } ret = stack; end: BIO_free(in); sk_X509_INFO_free(sk); return ret; } /** * calist is an array containing file and directory names. create a * certificate store and add those certs to it for use in verification. */ static X509_STORE *setup_verify(const Array& calist) { X509_STORE *store = X509_STORE_new(); if (store == nullptr) { return nullptr; } X509_LOOKUP *dir_lookup, *file_lookup; int ndirs = 0, nfiles = 0; for (ArrayIter iter(calist); iter; ++iter) { String item = iter.second().toString(); struct stat sb; if (stat(item.data(), &sb) == -1) { raise_warning("unable to stat %s", item.data()); continue; } if ((sb.st_mode & S_IFREG) == S_IFREG) { file_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()); if (file_lookup == nullptr || !X509_LOOKUP_load_file(file_lookup, item.data(), X509_FILETYPE_PEM)) { raise_warning("error loading file %s", item.data()); } else { nfiles++; } file_lookup = nullptr; } else { dir_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir()); if (dir_lookup == nullptr || !X509_LOOKUP_add_dir(dir_lookup, item.data(), X509_FILETYPE_PEM)) { raise_warning("error loading directory %s", item.data()); } else { ndirs++; } dir_lookup = nullptr; } } if (nfiles == 0) { file_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()); if (file_lookup) { X509_LOOKUP_load_file(file_lookup, nullptr, X509_FILETYPE_DEFAULT); } } if (ndirs == 0) { dir_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir()); if (dir_lookup) { X509_LOOKUP_add_dir(dir_lookup, nullptr, X509_FILETYPE_DEFAULT); } } return store; } /////////////////////////////////////////////////////////////////////////////// static bool add_entries(X509_NAME *subj, const Array& items) { for (ArrayIter iter(items); iter; ++iter) { auto const index = iter.first().toString(); auto const item = iter.second().toString(); int nid = OBJ_txt2nid(index.data()); if (nid != NID_undef) { if (!X509_NAME_add_entry_by_NID(subj, nid, MBSTRING_ASC, (unsigned char*)item.data(), -1, -1, 0)) { raise_warning("dn: add_entry_by_NID %d -> %s (failed)", nid, item.data()); return false; } } else { raise_warning("dn: %s is not a recognized name", index.data()); } } return true; } static bool php_openssl_make_REQ(struct php_x509_request *req, X509_REQ *csr, const Array& dn, const Array& attribs) { char *dn_sect = CONF_get_string(req->req_config, req->section_name, "distinguished_name"); if (dn_sect == nullptr) return false; STACK_OF(CONF_VALUE) *dn_sk = CONF_get_section(req->req_config, dn_sect); if (dn_sk == nullptr) return false; char *attr_sect = CONF_get_string(req->req_config, req->section_name, "attributes"); STACK_OF(CONF_VALUE) *attr_sk = nullptr; if (attr_sect) { attr_sk = CONF_get_section(req->req_config, attr_sect); if (attr_sk == nullptr) { return false; } } /* setup the version number: version 1 */ if (X509_REQ_set_version(csr, 0L)) { X509_NAME *subj = X509_REQ_get_subject_name(csr); if (!add_entries(subj, dn)) return false; /* Finally apply defaults from config file */ for (int i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) { CONF_VALUE *v = sk_CONF_VALUE_value(dn_sk, i); char *type = v->name; int len = strlen(type); if (len < (int)sizeof("_default")) { continue; } len -= sizeof("_default") - 1; if (strcmp("_default", type + len) != 0) { continue; } if (len > 200) { len = 200; } char buffer[200 + 1]; /*200 + \0 !*/ memcpy(buffer, type, len); buffer[len] = '\0'; type = buffer; /* Skip past any leading X. X: X, etc to allow for multiple instances */ for (char *str = type; *str; str++) { if (*str == ':' || *str == ',' || *str == '.') { str++; if (*str) { type = str; } break; } } /* if it is already set, skip this */ int nid = OBJ_txt2nid(type); if (X509_NAME_get_index_by_NID(subj, nid, -1) >= 0) { continue; } if (!X509_NAME_add_entry_by_txt(subj, type, MBSTRING_ASC, (unsigned char*)v->value, -1, -1, 0)) { raise_warning("add_entry_by_txt %s -> %s (failed)", type, v->value); return false; } if (!X509_NAME_entry_count(subj)) { raise_warning("no objects specified in config file"); return false; } } if (!add_entries(subj, attribs)) return false; if (attr_sk) { for (int i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) { CONF_VALUE *v = sk_CONF_VALUE_value(attr_sk, i); /* if it is already set, skip this */ int nid = OBJ_txt2nid(v->name); if (X509_REQ_get_attr_by_NID(csr, nid, -1) >= 0) { continue; } if (!X509_REQ_add1_attr_by_txt(csr, v->name, MBSTRING_ASC, (unsigned char*)v->value, -1)) { /** * hzhao: mismatched version of conf file may have attributes that * are not recognizable, and I don't think it should be treated as * fatal errors. */ Logger::Verbose("add1_attr_by_txt %s -> %s (failed)", v->name, v->value); // return false; } } } } X509_REQ_set_pubkey(csr, req->priv_key); return true; } bool HHVM_FUNCTION(openssl_csr_export_to_file, const Variant& csr, const String& outfilename, bool notext /* = true */) { auto pcsr = CSRequest::Get(csr); if (!pcsr) return false; BIO *bio_out = BIO_new_file((char*)outfilename.data(), "w"); if (bio_out == nullptr) { raise_warning("error opening file %s", outfilename.data()); return false; } if (!notext) { X509_REQ_print(bio_out, pcsr->csr()); } PEM_write_bio_X509_REQ(bio_out, pcsr->csr()); BIO_free(bio_out); return true; } bool HHVM_FUNCTION(openssl_csr_export, const Variant& csr, Variant& out, bool notext /* = true */) { auto pcsr = CSRequest::Get(csr); if (!pcsr) return false; BIO *bio_out = BIO_new(BIO_s_mem()); if (!notext) { X509_REQ_print(bio_out, pcsr->csr()); } if (PEM_write_bio_X509_REQ(bio_out, pcsr->csr())) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); out = String((char*)bio_buf->data, bio_buf->length, CopyString); BIO_free(bio_out); return true; } BIO_free(bio_out); return false; } Variant HHVM_FUNCTION(openssl_csr_get_public_key, const Variant& csr) { auto pcsr = CSRequest::Get(csr); if (!pcsr) return false; auto input_csr = pcsr->csr(); #if OPENSSL_VERSION_NUMBER >= 0x10100000 /* Due to changes in OpenSSL 1.1 related to locking when decoding CSR, * the pub key is not changed after assigning. It means if we pass * a private key, it will be returned including the private part. * If we duplicate it, then we get just the public part which is * the same behavior as for OpenSSL 1.0 */ input_csr = X509_REQ_dup(input_csr); /* We need to free the CSR as it was duplicated */ SCOPE_EXIT { X509_REQ_free(input_csr); }; #endif auto pubkey = X509_REQ_get_pubkey(input_csr); if (!pubkey) return false; return Variant(req::make<Key>(pubkey)); } Variant HHVM_FUNCTION(openssl_csr_get_subject, const Variant& csr, bool use_shortnames /* = true */) { auto pcsr = CSRequest::Get(csr); if (!pcsr) return false; X509_NAME *subject = X509_REQ_get_subject_name(pcsr->csr()); Array ret = Array::CreateDArray(); add_assoc_name_entry(ret, nullptr, subject, use_shortnames); return ret; } Variant HHVM_FUNCTION(openssl_csr_new, const Variant& dn, Variant& privkey, const Variant& configargs /* = uninit_variant */, const Variant& extraattribs /* = uninit_variant */) { Variant ret = false; struct php_x509_request req; memset(&req, 0, sizeof(req)); req::ptr<Key> okey; X509_REQ *csr = nullptr; std::vector<String> strings; if (php_openssl_parse_config(&req, configargs.toArray(), strings)) { /* Generate or use a private key */ if (!privkey.isNull()) { okey = Key::Get(privkey, false); if (okey) { req.priv_key = okey->m_key; } } if (req.priv_key == nullptr) { req.generatePrivateKey(); if (req.priv_key) { okey = req::make<Key>(req.priv_key); } } if (req.priv_key == nullptr) { raise_warning("Unable to generate a private key"); } else { csr = X509_REQ_new(); if (csr && php_openssl_make_REQ(&req, csr, dn.toArray(), extraattribs.toArray())) { X509V3_CTX ext_ctx; X509V3_set_ctx(&ext_ctx, nullptr, nullptr, csr, nullptr, 0); X509V3_set_conf_lhash(&ext_ctx, req.req_config); /* Add extensions */ if (req.request_extensions_section && !X509V3_EXT_REQ_add_conf(req.req_config, &ext_ctx, (char*)req.request_extensions_section, csr)) { raise_warning("Error loading extension section %s", req.request_extensions_section); } else { ret = true; if (X509_REQ_sign(csr, req.priv_key, req.digest)) { ret = req::make<CSRequest>(csr); csr = nullptr; } else { raise_warning("Error signing request"); } privkey = Variant(okey); } } } } if (csr) { X509_REQ_free(csr); } php_openssl_dispose_config(&req); return ret; } Variant HHVM_FUNCTION(openssl_csr_sign, const Variant& csr, const Variant& cacert, const Variant& priv_key, int days, const Variant& configargs /* = null */, int serial /* = 0 */) { auto pcsr = CSRequest::Get(csr); if (!pcsr) return false; req::ptr<Certificate> ocert; if (!cacert.isNull()) { ocert = Certificate::Get(cacert); if (!ocert) { raise_warning("cannot get cert from parameter 2"); return false; } } auto okey = Key::Get(priv_key, false); if (!okey) { raise_warning("cannot get private key from parameter 3"); return false; } X509 *cert = nullptr; if (ocert) { cert = ocert->m_cert; } EVP_PKEY *pkey = okey->m_key; if (cert && !X509_check_private_key(cert, pkey)) { raise_warning("private key does not correspond to signing cert"); return false; } req::ptr<Certificate> onewcert; struct php_x509_request req; memset(&req, 0, sizeof(req)); Variant ret = false; std::vector<String> strings; if (!php_openssl_parse_config(&req, configargs.toArray(), strings)) { goto cleanup; } /* Check that the request matches the signature */ EVP_PKEY *key; key = X509_REQ_get_pubkey(pcsr->csr()); if (key == nullptr) { raise_warning("error unpacking public key"); goto cleanup; } int i; i = X509_REQ_verify(pcsr->csr(), key); if (i < 0) { raise_warning("Signature verification problems"); goto cleanup; } if (i == 0) { raise_warning("Signature did not match the certificate request"); goto cleanup; } /* Now we can get on with it */ X509 *new_cert; new_cert = X509_new(); if (new_cert == nullptr) { raise_warning("No memory"); goto cleanup; } onewcert = req::make<Certificate>(new_cert); /* Version 3 cert */ if (!X509_set_version(new_cert, 2)) { goto cleanup; } ASN1_INTEGER_set(X509_get_serialNumber(new_cert), serial); X509_set_subject_name(new_cert, X509_REQ_get_subject_name(pcsr->csr())); if (cert == nullptr) { cert = new_cert; } if (!X509_set_issuer_name(new_cert, X509_get_subject_name(cert))) { goto cleanup; } X509_gmtime_adj(X509_get_notBefore(new_cert), 0); X509_gmtime_adj(X509_get_notAfter(new_cert), (long)60 * 60 * 24 * days); i = X509_set_pubkey(new_cert, key); if (!i) { goto cleanup; } if (req.extensions_section) { X509V3_CTX ctx; X509V3_set_ctx(&ctx, cert, new_cert, pcsr->csr(), nullptr, 0); X509V3_set_conf_lhash(&ctx, req.req_config); if (!X509V3_EXT_add_conf(req.req_config, &ctx, (char*)req.extensions_section, new_cert)) { goto cleanup; } } /* Now sign it */ if (!X509_sign(new_cert, pkey, req.digest)) { raise_warning("failed to sign it"); goto cleanup; } /* Succeeded; lets return the cert */ ret = onewcert; cleanup: php_openssl_dispose_config(&req); return ret; } Variant HHVM_FUNCTION(openssl_error_string) { char buf[512]; unsigned long val = ERR_get_error(); if (val) { return String(ERR_error_string(val, buf), CopyString); } return false; } bool HHVM_FUNCTION(openssl_open, const String& sealed_data, Variant& open_data, const String& env_key, const Variant& priv_key_id, const String& method, /* = null_string */ const String& iv /* = null_string */) { const EVP_CIPHER *cipher_type; if (method.empty()) { cipher_type = EVP_rc4(); } else { cipher_type = EVP_get_cipherbyname(method.c_str()); if (!cipher_type) { raise_warning("Unknown cipher algorithm"); return false; } } auto okey = Key::Get(priv_key_id, false); if (!okey) { raise_warning("unable to coerce parameter 4 into a private key"); return false; } EVP_PKEY *pkey = okey->m_key; const unsigned char *iv_buf = nullptr; int iv_len = EVP_CIPHER_iv_length(cipher_type); if (iv_len > 0) { if (iv.empty()) { raise_warning( "Cipher algorithm requires an IV to be supplied as a sixth parameter"); return false; } if (iv.length() != iv_len) { raise_warning("IV length is invalid"); return false; } iv_buf = reinterpret_cast<const unsigned char*>(iv.c_str()); } String s = String(sealed_data.size(), ReserveString); unsigned char *buf = (unsigned char *)s.mutableData(); EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new(); if (ctx == nullptr) { raise_warning("Failed to allocate an EVP_CIPHER_CTX object"); return false; } SCOPE_EXIT { EVP_CIPHER_CTX_free(ctx); }; int len1, len2; if (!EVP_OpenInit( ctx, cipher_type, (unsigned char*)env_key.data(), env_key.size(), iv_buf, pkey) || !EVP_OpenUpdate( ctx, buf, &len1, (unsigned char*)sealed_data.data(), sealed_data.size()) || !EVP_OpenFinal(ctx, buf + len1, &len2) || len1 + len2 == 0) { return false; } open_data = s.setSize(len1 + len2); return true; } static STACK_OF(X509) *php_array_to_X509_sk(const Variant& certs) { STACK_OF(X509) *pcerts = sk_X509_new_null(); Array arrCerts; if (certs.isArray()) { arrCerts = certs.toArray(); } else { arrCerts.append(certs); } for (ArrayIter iter(arrCerts); iter; ++iter) { auto ocert = Certificate::Get(iter.second()); if (!ocert) { break; } sk_X509_push(pcerts, ocert->m_cert); } return pcerts; } const StaticString s_friendly_name("friendly_name"), s_extracerts("extracerts"); static bool openssl_pkcs12_export_impl(const Variant& x509, BIO *bio_out, const Variant& priv_key, const String& pass, const Variant& args /* = uninit_variant */) { auto ocert = Certificate::Get(x509); if (!ocert) { raise_warning("cannot get cert from parameter 1"); return false; } auto okey = Key::Get(priv_key, false); if (!okey) { raise_warning("cannot get private key from parameter 3"); return false; } X509 *cert = ocert->m_cert; EVP_PKEY *key = okey->m_key; if (cert && !X509_check_private_key(cert, key)) { raise_warning("private key does not correspond to cert"); return false; } Array arrArgs = args.toArray(); String friendly_name; if (arrArgs.exists(s_friendly_name)) { friendly_name = arrArgs[s_friendly_name].toString(); } STACK_OF(X509) *ca = nullptr; if (arrArgs.exists(s_extracerts)) { ca = php_array_to_X509_sk(arrArgs[s_extracerts]); } PKCS12 *p12 = PKCS12_create ((char*)pass.data(), (char*)(friendly_name.empty() ? nullptr : friendly_name.data()), key, cert, ca, 0, 0, 0, 0, 0); assertx(bio_out); bool ret = i2d_PKCS12_bio(bio_out, p12); PKCS12_free(p12); sk_X509_free(ca); return ret; } bool HHVM_FUNCTION(openssl_pkcs12_export_to_file, const Variant& x509, const String& filename, const Variant& priv_key, const String& pass, const Variant& args /* = uninit_variant */) { BIO *bio_out = BIO_new_file(filename.data(), "w"); if (bio_out == nullptr) { raise_warning("error opening file %s", filename.data()); return false; } bool ret = openssl_pkcs12_export_impl(x509, bio_out, priv_key, pass, args); BIO_free(bio_out); return ret; } bool HHVM_FUNCTION(openssl_pkcs12_export, const Variant& x509, Variant& out, const Variant& priv_key, const String& pass, const Variant& args /* = uninit_variant */) { BIO *bio_out = BIO_new(BIO_s_mem()); bool ret = openssl_pkcs12_export_impl(x509, bio_out, priv_key, pass, args); if (ret) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); out = String((char*)bio_buf->data, bio_buf->length, CopyString); } BIO_free(bio_out); return ret; } const StaticString s_cert("cert"), s_pkey("pkey"); bool HHVM_FUNCTION(openssl_pkcs12_read, const String& pkcs12, Variant& certs, const String& pass) { bool ret = false; PKCS12 *p12 = nullptr; BIO *bio_in = BIO_new(BIO_s_mem()); if (!BIO_write(bio_in, pkcs12.data(), pkcs12.size())) { goto cleanup; } if (d2i_PKCS12_bio(bio_in, &p12)) { EVP_PKEY *pkey = nullptr; X509 *cert = nullptr; STACK_OF(X509) *ca = nullptr; if (PKCS12_parse(p12, pass.data(), &pkey, &cert, &ca)) { Variant vcerts = Array::CreateDArray(); SCOPE_EXIT { certs = vcerts; }; BIO *bio_out = nullptr; if (cert) { bio_out = BIO_new(BIO_s_mem()); if (PEM_write_bio_X509(bio_out, cert)) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); vcerts.asArrRef().set(s_cert, String((char*)bio_buf->data, bio_buf->length, CopyString)); } BIO_free(bio_out); } if (pkey) { bio_out = BIO_new(BIO_s_mem()); if (PEM_write_bio_PrivateKey(bio_out, pkey, nullptr, nullptr, 0, 0, nullptr)) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); vcerts.asArrRef().set(s_pkey, String((char*)bio_buf->data, bio_buf->length, CopyString)); } BIO_free(bio_out); } if (ca) { Array extracerts; for (X509 *aCA = sk_X509_pop(ca); aCA; aCA = sk_X509_pop(ca)) { bio_out = BIO_new(BIO_s_mem()); if (PEM_write_bio_X509(bio_out, aCA)) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); extracerts.append(String((char*)bio_buf->data, bio_buf->length, CopyString)); } BIO_free(bio_out); X509_free(aCA); } sk_X509_free(ca); vcerts.asArrRef().set(s_extracerts, extracerts); } ret = true; PKCS12_free(p12); } } cleanup: if (bio_in) { BIO_free(bio_in); } return ret; } bool HHVM_FUNCTION(openssl_pkcs7_decrypt, const String& infilename, const String& outfilename, const Variant& recipcert, const Variant& recipkey /* = uninit_variant */) { bool ret = false; BIO *in = nullptr, *out = nullptr, *datain = nullptr; PKCS7 *p7 = nullptr; req::ptr<Key> okey; auto ocert = Certificate::Get(recipcert); if (!ocert) { raise_warning("unable to coerce parameter 3 to x509 cert"); goto clean_exit; } okey = Key::Get(recipkey.isNull() ? recipcert : recipkey, false); if (!okey) { raise_warning("unable to get private key"); goto clean_exit; } in = BIO_new_file(infilename.data(), "r"); if (in == nullptr) { raise_warning("error opening the file, %s", infilename.data()); goto clean_exit; } out = BIO_new_file(outfilename.data(), "w"); if (out == nullptr) { raise_warning("error opening the file, %s", outfilename.data()); goto clean_exit; } p7 = SMIME_read_PKCS7(in, &datain); if (p7 == nullptr) { goto clean_exit; } assertx(okey->m_key); assertx(ocert->m_cert); if (PKCS7_decrypt(p7, okey->m_key, ocert->m_cert, out, PKCS7_DETACHED)) { ret = true; } clean_exit: PKCS7_free(p7); BIO_free(datain); BIO_free(in); BIO_free(out); return ret; } static void print_headers(BIO *outfile, const Array& headers) { if (!headers.isNull()) { if (headers->isVectorData()) { for (ArrayIter iter(headers); iter; ++iter) { BIO_printf(outfile, "%s\n", iter.second().toString().data()); } } else { for (ArrayIter iter(headers); iter; ++iter) { BIO_printf(outfile, "%s: %s\n", iter.first().toString().data(), iter.second().toString().data()); } } } } bool HHVM_FUNCTION(openssl_pkcs7_encrypt, const String& infilename, const String& outfilename, const Variant& recipcerts, const Array& headers, int flags /* = 0 */, int cipherid /* = k_OPENSSL_CIPHER_RC2_40 */) { bool ret = false; BIO *infile = nullptr, *outfile = nullptr; STACK_OF(X509) *precipcerts = nullptr; PKCS7 *p7 = nullptr; const EVP_CIPHER *cipher = nullptr; infile = BIO_new_file(infilename.data(), (flags & PKCS7_BINARY) ? "rb" : "r"); if (infile == nullptr) { raise_warning("error opening the file, %s", infilename.data()); goto clean_exit; } outfile = BIO_new_file(outfilename.data(), "w"); if (outfile == nullptr) { raise_warning("error opening the file, %s", outfilename.data()); goto clean_exit; } precipcerts = php_array_to_X509_sk(recipcerts); /* sanity check the cipher */ switch (cipherid) { #ifndef OPENSSL_NO_RC2 case PHP_OPENSSL_CIPHER_RC2_40: cipher = EVP_rc2_40_cbc(); break; case PHP_OPENSSL_CIPHER_RC2_64: cipher = EVP_rc2_64_cbc(); break; case PHP_OPENSSL_CIPHER_RC2_128: cipher = EVP_rc2_cbc(); break; #endif #ifndef OPENSSL_NO_DES case PHP_OPENSSL_CIPHER_DES: cipher = EVP_des_cbc(); break; case PHP_OPENSSL_CIPHER_3DES: cipher = EVP_des_ede3_cbc(); break; #endif default: raise_warning("Invalid cipher type `%d'", cipherid); goto clean_exit; } if (cipher == nullptr) { raise_warning("Failed to get cipher"); goto clean_exit; } p7 = PKCS7_encrypt(precipcerts, infile, (EVP_CIPHER*)cipher, flags); if (p7 == nullptr) goto clean_exit; print_headers(outfile, headers); (void)BIO_reset(infile); SMIME_write_PKCS7(outfile, p7, infile, flags); ret = true; clean_exit: PKCS7_free(p7); BIO_free(infile); BIO_free(outfile); sk_X509_free(precipcerts); return ret; } bool HHVM_FUNCTION(openssl_pkcs7_sign, const String& infilename, const String& outfilename, const Variant& signcert, const Variant& privkey, const Variant& headers, int flags /* = k_PKCS7_DETACHED */, const String& extracerts /* = null_string */) { bool ret = false; STACK_OF(X509) *others = nullptr; BIO *infile = nullptr, *outfile = nullptr; PKCS7 *p7 = nullptr; req::ptr<Key> okey; req::ptr<Certificate> ocert; if (!extracerts.empty()) { others = load_all_certs_from_file(extracerts.data()); if (others == nullptr) { goto clean_exit; } } okey = Key::Get(privkey, false); if (!okey) { raise_warning("error getting private key"); goto clean_exit; } EVP_PKEY *key; key = okey->m_key; ocert = Certificate::Get(signcert); if (!ocert) { raise_warning("error getting cert"); goto clean_exit; } X509 *cert; cert = ocert->m_cert; infile = BIO_new_file(infilename.data(), (flags & PKCS7_BINARY) ? "rb" : "r"); if (infile == nullptr) { raise_warning("error opening input file %s!", infilename.data()); goto clean_exit; } outfile = BIO_new_file(outfilename.data(), "w"); if (outfile == nullptr) { raise_warning("error opening output file %s!", outfilename.data()); goto clean_exit; } p7 = PKCS7_sign(cert, key, others, infile, flags); if (p7 == nullptr) { raise_warning("error creating PKCS7 structure!"); goto clean_exit; } print_headers(outfile, headers.toArray()); (void)BIO_reset(infile); SMIME_write_PKCS7(outfile, p7, infile, flags); ret = true; clean_exit: PKCS7_free(p7); BIO_free(infile); BIO_free(outfile); if (others) { sk_X509_pop_free(others, X509_free); } return ret; } static int pkcs7_ignore_expiration(int ok, X509_STORE_CTX *ctx) { if (ok) { return ok; } int error = X509_STORE_CTX_get_error(ctx); if (error == X509_V_ERR_CERT_HAS_EXPIRED) { // ignore cert expirations Logger::Verbose("Ignoring cert expiration"); return 1; } return ok; } /** * NOTE: when ignore_cert_expiration is true, a custom certificate validation * callback is set up. Please be aware of this if you modify the function to * allow other certificate validation behaviors */ Variant openssl_pkcs7_verify_core( const String& filename, int flags, const Variant& voutfilename /* = null_string */, const Variant& vcainfo /* = null_array */, const Variant& vextracerts /* = null_string */, const Variant& vcontent /* = null_string */, bool ignore_cert_expiration ) { Variant ret = -1; X509_STORE *store = nullptr; BIO *in = nullptr; PKCS7 *p7 = nullptr; BIO *datain = nullptr; BIO *dataout = nullptr; auto cainfo = vcainfo.toArray(); auto extracerts = vextracerts.toString(); auto content = vcontent.toString(); STACK_OF(X509) *others = nullptr; if (!extracerts.empty()) { others = load_all_certs_from_file(extracerts.data()); if (others == nullptr) { goto clean_exit; } } flags = flags & ~PKCS7_DETACHED; store = setup_verify(cainfo); if (!store) { goto clean_exit; } if (ignore_cert_expiration) { #if (OPENSSL_VERSION_NUMBER >= 0x10000000) // make sure no other callback is specified #if OPENSSL_VERSION_NUMBER >= 0x10100000L assertx(!X509_STORE_get_verify_cb(store)); #else assertx(!store->verify_cb); #endif // ignore expired certs X509_STORE_set_verify_cb(store, pkcs7_ignore_expiration); #else always_assert(false); #endif } in = BIO_new_file(filename.data(), (flags & PKCS7_BINARY) ? "rb" : "r"); if (in == nullptr) { raise_warning("error opening the file, %s", filename.data()); goto clean_exit; } p7 = SMIME_read_PKCS7(in, &datain); if (p7 == nullptr) { goto clean_exit; } if (!content.empty()) { dataout = BIO_new_file(content.data(), "w"); if (dataout == nullptr) { raise_warning("error opening the file, %s", content.data()); goto clean_exit; } } if (PKCS7_verify(p7, others, store, datain, dataout, flags)) { ret = true; auto outfilename = voutfilename.toString(); if (!outfilename.empty()) { BIO *certout = BIO_new_file(outfilename.data(), "w"); if (certout) { STACK_OF(X509) *signers = PKCS7_get0_signers(p7, nullptr, flags); for (int i = 0; i < sk_X509_num(signers); i++) { PEM_write_bio_X509(certout, sk_X509_value(signers, i)); } BIO_free(certout); sk_X509_free(signers); } else { raise_warning("signature OK, but cannot open %s for writing", outfilename.data()); ret = -1; } } goto clean_exit; } else { ret = false; } clean_exit: X509_STORE_free(store); BIO_free(datain); BIO_free(in); BIO_free(dataout); PKCS7_free(p7); sk_X509_pop_free(others, X509_free); return ret; } Variant HHVM_FUNCTION(openssl_pkcs7_verify, const String& filename, int flags, const Variant& voutfilename /* = null_string */, const Variant& vcainfo /* = null_array */, const Variant& vextracerts /* = null_string */, const Variant& vcontent /* = null_string */) { return openssl_pkcs7_verify_core(filename, flags, voutfilename, vcainfo, vextracerts, vcontent, false); } static bool openssl_pkey_export_impl(const Variant& key, BIO *bio_out, const String& passphrase /* = null_string */, const Variant& configargs /* = uninit_variant */) { auto okey = Key::Get(key, false, passphrase.data()); if (!okey) { raise_warning("cannot get key from parameter 1"); return false; } EVP_PKEY *pkey = okey->m_key; struct php_x509_request req; memset(&req, 0, sizeof(req)); std::vector<String> strings; bool ret = false; if (php_openssl_parse_config(&req, configargs.toArray(), strings)) { const EVP_CIPHER *cipher; if (!passphrase.empty() && req.priv_key_encrypt) { cipher = (EVP_CIPHER *)EVP_des_ede3_cbc(); } else { cipher = nullptr; } assertx(bio_out); switch (EVP_PKEY_id(pkey)) { #ifdef HAVE_EVP_PKEY_EC case EVP_PKEY_EC: ret = PEM_write_bio_ECPrivateKey(bio_out, EVP_PKEY_get0_EC_KEY(pkey), cipher, (unsigned char *)passphrase.data(), passphrase.size(), nullptr, nullptr); break; #endif default: ret = PEM_write_bio_PrivateKey(bio_out, pkey, cipher, (unsigned char *)passphrase.data(), passphrase.size(), nullptr, nullptr); break; } } php_openssl_dispose_config(&req); return ret; } bool HHVM_FUNCTION(openssl_pkey_export_to_file, const Variant& key, const String& outfilename, const String& passphrase /* = null_string */, const Variant& configargs /* = uninit_variant */) { BIO *bio_out = BIO_new_file(outfilename.data(), "w"); if (bio_out == nullptr) { raise_warning("error opening the file, %s", outfilename.data()); return false; } bool ret = openssl_pkey_export_impl(key, bio_out, passphrase, configargs); BIO_free(bio_out); return ret; } bool HHVM_FUNCTION(openssl_pkey_export, const Variant& key, Variant& out, const String& passphrase /* = null_string */, const Variant& configargs /* = uninit_variant */) { BIO *bio_out = BIO_new(BIO_s_mem()); bool ret = openssl_pkey_export_impl(key, bio_out, passphrase, configargs); if (ret) { char *bio_mem_ptr; long bio_mem_len = BIO_get_mem_data(bio_out, &bio_mem_ptr); out = String(bio_mem_ptr, bio_mem_len, CopyString); } BIO_free(bio_out); return ret; } const StaticString s_bits("bits"), s_key("key"), s_type("type"), s_name("name"), s_hash("hash"), s_version("version"), s_serialNumber("serialNumber"), s_signatureAlgorithm("signatureAlgorithm"), s_validFrom("validFrom"), s_validTo("validTo"), s_validFrom_time_t("validFrom_time_t"), s_validTo_time_t("validTo_time_t"), s_alias("alias"), s_purposes("purposes"), s_extensions("extensions"), s_rsa("rsa"), s_dsa("dsa"), s_dh("dh"), s_ec("ec"), s_n("n"), s_e("e"), s_d("d"), s_p("p"), s_q("q"), s_g("g"), s_x("x"), s_y("y"), s_dmp1("dmp1"), s_dmq1("dmq1"), s_iqmp("iqmp"), s_priv_key("priv_key"), s_pub_key("pub_key"), s_curve_oid("curve_oid"); static void add_bignum_as_string(Array &arr, StaticString key, const BIGNUM *bn) { if (!bn) { return; } int num_bytes = BN_num_bytes(bn); String str{size_t(num_bytes), ReserveString}; BN_bn2bin(bn, (unsigned char*)str.mutableData()); str.setSize(num_bytes); arr.set(key, std::move(str)); } Array HHVM_FUNCTION(openssl_pkey_get_details, const Resource& key) { EVP_PKEY *pkey = cast<Key>(key)->m_key; BIO *out = BIO_new(BIO_s_mem()); PEM_write_bio_PUBKEY(out, pkey); char *pbio; unsigned int pbio_len = BIO_get_mem_data(out, &pbio); auto ret = make_darray( s_bits, EVP_PKEY_bits(pkey), s_key, String(pbio, pbio_len, CopyString) ); long ktype = -1; auto details = Array::CreateDArray(); switch (EVP_PKEY_id(pkey)) { case EVP_PKEY_RSA: case EVP_PKEY_RSA2: { ktype = OPENSSL_KEYTYPE_RSA; RSA *rsa = EVP_PKEY_get0_RSA(pkey); assertx(rsa); const BIGNUM *n, *e, *d, *p, *q, *dmp1, *dmq1, *iqmp; RSA_get0_key(rsa, &n, &e, &d); RSA_get0_factors(rsa, &p, &q); RSA_get0_crt_params(rsa, &dmp1, &dmq1, &iqmp); add_bignum_as_string(details, s_n, n); add_bignum_as_string(details, s_e, e); add_bignum_as_string(details, s_d, d); add_bignum_as_string(details, s_p, p); add_bignum_as_string(details, s_q, q); add_bignum_as_string(details, s_dmp1, dmp1); add_bignum_as_string(details, s_dmq1, dmq1); add_bignum_as_string(details, s_iqmp, iqmp); ret.set(s_rsa, details); break; } case EVP_PKEY_DSA: case EVP_PKEY_DSA2: case EVP_PKEY_DSA3: case EVP_PKEY_DSA4: { ktype = OPENSSL_KEYTYPE_DSA; DSA *dsa = EVP_PKEY_get0_DSA(pkey); assertx(dsa); const BIGNUM *p, *q, *g, *pub_key, *priv_key; DSA_get0_pqg(dsa, &p, &q, &g); DSA_get0_key(dsa, &pub_key, &priv_key); add_bignum_as_string(details, s_p, p); add_bignum_as_string(details, s_q, q); add_bignum_as_string(details, s_g, g); add_bignum_as_string(details, s_priv_key, priv_key); add_bignum_as_string(details, s_pub_key, pub_key); ret.set(s_dsa, details); break; } case EVP_PKEY_DH: { ktype = OPENSSL_KEYTYPE_DH; DH *dh = EVP_PKEY_get0_DH(pkey); assertx(dh); const BIGNUM *p, *q, *g, *pub_key, *priv_key; DH_get0_pqg(dh, &p, &q, &g); DH_get0_key(dh, &pub_key, &priv_key); add_bignum_as_string(details, s_p, p); add_bignum_as_string(details, s_g, g); add_bignum_as_string(details, s_priv_key, priv_key); add_bignum_as_string(details, s_pub_key, pub_key); ret.set(s_dh, details); break; } #ifdef HAVE_EVP_PKEY_EC case EVP_PKEY_EC: { ktype = OPENSSL_KEYTYPE_EC; auto const ec = EVP_PKEY_get0_EC_KEY(pkey); assertx(ec); auto const ec_group = EC_KEY_get0_group(ec); auto const nid = EC_GROUP_get_curve_name(ec_group); if (nid == NID_undef) { break; } auto const crv_sn = OBJ_nid2sn(nid); if (crv_sn != nullptr) { details.set(s_curve_name, String(crv_sn, CopyString)); } auto const obj = OBJ_nid2obj(nid); if (obj != nullptr) { SCOPE_EXIT { ASN1_OBJECT_free(obj); }; char oir_buf[256]; OBJ_obj2txt(oir_buf, sizeof(oir_buf) - 1, obj, 1); details.set(s_curve_oid, String(oir_buf, CopyString)); } auto x = BN_new(); auto y = BN_new(); SCOPE_EXIT { BN_free(x); BN_free(y); }; auto const pub = EC_KEY_get0_public_key(ec); if (EC_POINT_get_affine_coordinates_GFp(ec_group, pub, x, y, nullptr)) { add_bignum_as_string(details, s_x, x); add_bignum_as_string(details, s_y, y); } auto d = BN_dup(EC_KEY_get0_private_key(ec)); SCOPE_EXIT { BN_free(d); }; if (d != nullptr) { add_bignum_as_string(details, s_d, d); } ret.set(s_ec, details); } break; #endif } ret.set(s_type, ktype); BIO_free(out); return ret; } Variant HHVM_FUNCTION(openssl_pkey_get_private, const Variant& key, const String& passphrase /* = null_string */) { return toVariant(Key::Get(key, false, passphrase.data())); } Variant HHVM_FUNCTION(openssl_pkey_get_public, const Variant& certificate) { return toVariant(Key::Get(certificate, true)); } Variant HHVM_FUNCTION(openssl_pkey_new, const Variant& configargs /* = uninit_variant */) { struct php_x509_request req; memset(&req, 0, sizeof(req)); SCOPE_EXIT { php_openssl_dispose_config(&req); }; std::vector<String> strings; if (php_openssl_parse_config(&req, configargs.toArray(), strings) && req.generatePrivateKey()) { return Resource(req::make<Key>(req.priv_key)); } else { return false; } } bool HHVM_FUNCTION(openssl_private_decrypt, const String& data, Variant& decrypted, const Variant& key, int padding /* = k_OPENSSL_PKCS1_PADDING */) { auto okey = Key::Get(key, false); if (!okey) { raise_warning("key parameter is not a valid private key"); return false; } EVP_PKEY *pkey = okey->m_key; int cryptedlen = EVP_PKEY_size(pkey); String s = String(cryptedlen, ReserveString); unsigned char *cryptedbuf = (unsigned char *)s.mutableData(); int successful = 0; switch (EVP_PKEY_id(pkey)) { case EVP_PKEY_RSA: case EVP_PKEY_RSA2: cryptedlen = RSA_private_decrypt(data.size(), (unsigned char *)data.data(), cryptedbuf, EVP_PKEY_get0_RSA(pkey), padding); if (cryptedlen != -1) { successful = 1; } break; default: raise_warning("key type not supported"); } if (successful) { decrypted = s.setSize(cryptedlen); return true; } return false; } bool HHVM_FUNCTION(openssl_private_encrypt, const String& data, Variant& crypted, const Variant& key, int padding /* = k_OPENSSL_PKCS1_PADDING */) { auto okey = Key::Get(key, false); if (!okey) { raise_warning("key param is not a valid private key"); return false; } EVP_PKEY *pkey = okey->m_key; int cryptedlen = EVP_PKEY_size(pkey); String s = String(cryptedlen, ReserveString); unsigned char *cryptedbuf = (unsigned char *)s.mutableData(); int successful = 0; switch (EVP_PKEY_id(pkey)) { case EVP_PKEY_RSA: case EVP_PKEY_RSA2: successful = (RSA_private_encrypt(data.size(), (unsigned char *)data.data(), cryptedbuf, EVP_PKEY_get0_RSA(pkey), padding) == cryptedlen); break; default: raise_warning("key type not supported"); } if (successful) { crypted = s.setSize(cryptedlen); return true; } return false; } bool HHVM_FUNCTION(openssl_public_decrypt, const String& data, Variant& decrypted, const Variant& key, int padding /* = k_OPENSSL_PKCS1_PADDING */) { auto okey = Key::Get(key, true); if (!okey) { raise_warning("key parameter is not a valid public key"); return false; } EVP_PKEY *pkey = okey->m_key; int cryptedlen = EVP_PKEY_size(pkey); String s = String(cryptedlen, ReserveString); unsigned char *cryptedbuf = (unsigned char *)s.mutableData(); int successful = 0; switch (EVP_PKEY_id(pkey)) { case EVP_PKEY_RSA: case EVP_PKEY_RSA2: cryptedlen = RSA_public_decrypt(data.size(), (unsigned char *)data.data(), cryptedbuf, EVP_PKEY_get0_RSA(pkey), padding); if (cryptedlen != -1) { successful = 1; } break; default: raise_warning("key type not supported"); } if (successful) { decrypted = s.setSize(cryptedlen); return true; } return false; } bool HHVM_FUNCTION(openssl_public_encrypt, const String& data, Variant& crypted, const Variant& key, int padding /* = k_OPENSSL_PKCS1_PADDING */) { auto okey = Key::Get(key, true); if (!okey) { raise_warning("key parameter is not a valid public key"); return false; } EVP_PKEY *pkey = okey->m_key; int cryptedlen = EVP_PKEY_size(pkey); String s = String(cryptedlen, ReserveString); unsigned char *cryptedbuf = (unsigned char *)s.mutableData(); int successful = 0; switch (EVP_PKEY_id(pkey)) { case EVP_PKEY_RSA: case EVP_PKEY_RSA2: successful = (RSA_public_encrypt(data.size(), (unsigned char *)data.data(), cryptedbuf, EVP_PKEY_get0_RSA(pkey), padding) == cryptedlen); break; default: raise_warning("key type not supported"); } if (successful) { crypted = s.setSize(cryptedlen); return true; } return false; } Variant HHVM_FUNCTION(openssl_seal, const String& data, Variant& sealed_data, Variant& env_keys, const Array& pub_key_ids, const String& method, Variant& iv) { int nkeys = pub_key_ids.size(); if (nkeys == 0) { raise_warning("Fourth argument to openssl_seal() must be " "a non-empty array"); return false; } const EVP_CIPHER *cipher_type; if (method.empty()) { cipher_type = EVP_rc4(); } else { cipher_type = EVP_get_cipherbyname(method.c_str()); if (!cipher_type) { raise_warning("Unknown cipher algorithm"); return false; } } int iv_len = EVP_CIPHER_iv_length(cipher_type); unsigned char *iv_buf = nullptr; String iv_s; if (iv_len > 0) { iv_s = String(iv_len, ReserveString); iv_buf = (unsigned char*)iv_s.mutableData(); if (!RAND_bytes(iv_buf, iv_len)) { raise_warning("Could not generate an IV."); return false; } } EVP_PKEY **pkeys = (EVP_PKEY**)malloc(nkeys * sizeof(*pkeys)); int *eksl = (int*)malloc(nkeys * sizeof(*eksl)); unsigned char **eks = (unsigned char **)malloc(nkeys * sizeof(*eks)); memset(eks, 0, sizeof(*eks) * nkeys); // holder is needed to make sure none of the Keys get deleted prematurely. // The pkeys array points to elements inside of Keys returned from Key::Get() // which may be newly allocated and have no other owners. std::vector<req::ptr<Key>> holder; /* get the public keys we are using to seal this data */ bool ret = true; int i = 0; String s; unsigned char* buf = nullptr; EVP_CIPHER_CTX* ctx = nullptr; for (ArrayIter iter(pub_key_ids); iter; ++iter, ++i) { auto okey = Key::Get(iter.second(), true); if (!okey) { raise_warning("not a public key (%dth member of pubkeys)", i + 1); ret = false; goto clean_exit; } holder.push_back(okey); pkeys[i] = okey->m_key; eks[i] = (unsigned char *)malloc(EVP_PKEY_size(pkeys[i]) + 1); } ctx = EVP_CIPHER_CTX_new(); if (ctx == nullptr) { raise_warning("Failed to allocate an EVP_CIPHER_CTX object"); ret = false; goto clean_exit; } if (!EVP_EncryptInit_ex(ctx, cipher_type, nullptr, nullptr, nullptr)) { ret = false; goto clean_exit; } int len1, len2; s = String(data.size() + EVP_CIPHER_CTX_block_size(ctx), ReserveString); buf = (unsigned char *)s.mutableData(); if (EVP_SealInit(ctx, cipher_type, eks, eksl, iv_buf, pkeys, nkeys) <= 0 || !EVP_SealUpdate(ctx, buf, &len1, (unsigned char*)data.data(), data.size()) || !EVP_SealFinal(ctx, buf + len1, &len2)) { ret = false; goto clean_exit; } if (len1 + len2 > 0) { sealed_data = s.setSize(len1 + len2); auto ekeys = Array::CreateVArray(); for (i = 0; i < nkeys; i++) { eks[i][eksl[i]] = '\0'; ekeys.append(String((char*)eks[i], eksl[i], AttachString)); eks[i] = nullptr; } env_keys = ekeys; } clean_exit: for (i = 0; i < nkeys; i++) { if (eks[i]) free(eks[i]); } free(eks); free(eksl); free(pkeys); if (iv_buf != nullptr) { if (ret) { iv = iv_s.setSize(iv_len); } } if (ctx != nullptr) { EVP_CIPHER_CTX_free(ctx); } if (ret) return len1 + len2; return false; } static const EVP_MD *php_openssl_get_evp_md_from_algo(long algo) { switch (algo) { case OPENSSL_ALGO_SHA1: return EVP_sha1(); case OPENSSL_ALGO_MD5: return EVP_md5(); case OPENSSL_ALGO_MD4: return EVP_md4(); #ifdef HAVE_OPENSSL_MD2_H case OPENSSL_ALGO_MD2: return EVP_md2(); #endif #if OPENSSL_VERSION_NUMBER < 0x10100000L case OPENSSL_ALGO_DSS1: return EVP_dss1(); #endif #if OPENSSL_VERSION_NUMBER >= 0x0090708fL case OPENSSL_ALGO_SHA224: return EVP_sha224(); case OPENSSL_ALGO_SHA256: return EVP_sha256(); case OPENSSL_ALGO_SHA384: return EVP_sha384(); case OPENSSL_ALGO_SHA512: return EVP_sha512(); case OPENSSL_ALGO_RMD160: return EVP_ripemd160(); #endif } return nullptr; } bool HHVM_FUNCTION(openssl_sign, const String& data, Variant& signature, const Variant& priv_key_id, const Variant& signature_alg /* = k_OPENSSL_ALGO_SHA1 */) { auto okey = Key::Get(priv_key_id, false); if (!okey) { raise_warning("supplied key param cannot be coerced into a private key"); return false; } const EVP_MD *mdtype = nullptr; if (signature_alg.isInteger()) { mdtype = php_openssl_get_evp_md_from_algo(signature_alg.toInt64Val()); } else if (signature_alg.isString()) { mdtype = EVP_get_digestbyname(signature_alg.toString().data()); } if (!mdtype) { raise_warning("Unknown signature algorithm."); return false; } EVP_PKEY *pkey = okey->m_key; int siglen = EVP_PKEY_size(pkey); String s = String(siglen, ReserveString); unsigned char *sigbuf = (unsigned char *)s.mutableData(); EVP_MD_CTX *md_ctx = EVP_MD_CTX_new(); SCOPE_EXIT { EVP_MD_CTX_free(md_ctx); }; EVP_SignInit(md_ctx, mdtype); EVP_SignUpdate(md_ctx, (unsigned char *)data.data(), data.size()); if (EVP_SignFinal(md_ctx, sigbuf, (unsigned int *)&siglen, pkey)) { signature = s.setSize(siglen); return true; } return false; } Variant HHVM_FUNCTION(openssl_verify, const String& data, const String& signature, const Variant& pub_key_id, const Variant& signature_alg /* = k_OPENSSL_ALGO_SHA1 */) { int err; const EVP_MD *mdtype = nullptr; if (signature_alg.isInteger()) { mdtype = php_openssl_get_evp_md_from_algo(signature_alg.toInt64Val()); } else if (signature_alg.isString()) { mdtype = EVP_get_digestbyname(signature_alg.toString().data()); } if (!mdtype) { raise_warning("Unknown signature algorithm."); return false; } auto okey = Key::Get(pub_key_id, true); if (!okey) { raise_warning("supplied key param cannot be coerced into a public key"); return false; } EVP_MD_CTX *md_ctx = EVP_MD_CTX_new(); SCOPE_EXIT { EVP_MD_CTX_free(md_ctx); }; EVP_VerifyInit(md_ctx, mdtype); EVP_VerifyUpdate(md_ctx, (unsigned char*)data.data(), data.size()); err = EVP_VerifyFinal(md_ctx, (unsigned char *)signature.data(), signature.size(), okey->m_key); return err; } bool HHVM_FUNCTION(openssl_x509_check_private_key, const Variant& cert, const Variant& key) { auto ocert = Certificate::Get(cert); if (!ocert) { return false; } auto okey = Key::Get(key, false); if (!okey) { return false; } return X509_check_private_key(ocert->m_cert, okey->m_key); } static int check_cert(X509_STORE *ctx, X509 *x, STACK_OF(X509) *untrustedchain, int purpose) { X509_STORE_CTX *csc = X509_STORE_CTX_new(); if (csc == nullptr) { raise_warning("memory allocation failure"); return 0; } X509_STORE_CTX_init(csc, ctx, x, untrustedchain); if (purpose >= 0) { X509_STORE_CTX_set_purpose(csc, purpose); } int ret = X509_verify_cert(csc); X509_STORE_CTX_free(csc); return ret; } Variant HHVM_FUNCTION(openssl_x509_checkpurpose, const Variant& x509cert, int purpose, const Array& cainfo /* = null_array */, const String& untrustedfile /* = null_string */) { int ret = -1; STACK_OF(X509) *untrustedchain = nullptr; X509_STORE *pcainfo = nullptr; req::ptr<Certificate> ocert; if (!untrustedfile.empty()) { untrustedchain = load_all_certs_from_file(untrustedfile.data()); if (untrustedchain == nullptr) { goto clean_exit; } } pcainfo = setup_verify(cainfo); if (pcainfo == nullptr) { goto clean_exit; } ocert = Certificate::Get(x509cert); if (!ocert) { raise_warning("cannot get cert from parameter 1"); return false; } X509 *cert; cert = ocert->m_cert; assertx(cert); ret = check_cert(pcainfo, cert, untrustedchain, purpose); clean_exit: if (pcainfo) { X509_STORE_free(pcainfo); } if (untrustedchain) { sk_X509_pop_free(untrustedchain, X509_free); } return ret == 1 ? true : ret == 0 ? false : -1; } static bool openssl_x509_export_impl(const Variant& x509, BIO *bio_out, bool notext /* = true */) { auto ocert = Certificate::Get(x509); if (!ocert) { raise_warning("cannot get cert from parameter 1"); return false; } X509 *cert = ocert->m_cert; assertx(cert); assertx(bio_out); if (!notext) { X509_print(bio_out, cert); } return PEM_write_bio_X509(bio_out, cert); } bool HHVM_FUNCTION(openssl_x509_export_to_file, const Variant& x509, const String& outfilename, bool notext /* = true */) { BIO *bio_out = BIO_new_file((char*)outfilename.data(), "w"); if (bio_out == nullptr) { raise_warning("error opening file %s", outfilename.data()); return false; } bool ret = openssl_x509_export_impl(x509, bio_out, notext); BIO_free(bio_out); return ret; } bool HHVM_FUNCTION(openssl_x509_export, const Variant& x509, Variant& output, bool notext /* = true */) { BIO *bio_out = BIO_new(BIO_s_mem()); bool ret = openssl_x509_export_impl(x509, bio_out, notext); if (ret) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); output = String(bio_buf->data, bio_buf->length, CopyString); } BIO_free(bio_out); return ret; } /** * This is how the time string is formatted: * * snprintf(p, sizeof(p), "%02d%02d%02d%02d%02d%02dZ",ts->tm_year%100, * ts->tm_mon+1,ts->tm_mday,ts->tm_hour,ts->tm_min,ts->tm_sec); */ static time_t asn1_time_to_time_t(ASN1_UTCTIME *timestr) { auto const timestr_type = ASN1_STRING_type(timestr); if (timestr_type != V_ASN1_UTCTIME && timestr_type != V_ASN1_GENERALIZEDTIME) { raise_warning("illegal ASN1 data type for timestamp"); return (time_t)-1; } auto const timestr_len = (size_t)ASN1_STRING_length(timestr); // Binary safety if (timestr_len != strlen((char*)ASN1_STRING_data(timestr))) { raise_warning("illegal length in timestamp"); return (time_t)-1; } if (timestr_len < 13 && timestr_len != 11) { raise_warning("unable to parse time string %s correctly", timestr->data); return (time_t)-1; } if (timestr_type == V_ASN1_GENERALIZEDTIME && timestr_len < 15) { raise_warning("unable to parse time string %s correctly", timestr->data); return (time_t)-1; } char *strbuf = strdup((char*)timestr->data); struct tm thetime; memset(&thetime, 0, sizeof(thetime)); /* we work backwards so that we can use atoi more easily */ char *thestr = strbuf + ASN1_STRING_length(timestr) - 3; if (ASN1_STRING_length(timestr) == 11) { thetime.tm_sec = 0; } else { thetime.tm_sec = atoi(thestr); *thestr = '\0'; thestr -= 2; } thetime.tm_min = atoi(thestr); *thestr = '\0'; thestr -= 2; thetime.tm_hour = atoi(thestr); *thestr = '\0'; thestr -= 2; thetime.tm_mday = atoi(thestr); *thestr = '\0'; thestr -= 2; thetime.tm_mon = atoi(thestr)-1; *thestr = '\0'; if (ASN1_STRING_type(timestr) == V_ASN1_UTCTIME) { thestr -= 2; thetime.tm_year = atoi(thestr); if (thetime.tm_year < 68) { thetime.tm_year += 100; } } else if (ASN1_STRING_type(timestr) == V_ASN1_GENERALIZEDTIME) { thestr -= 4; thetime.tm_year = atoi(thestr) - 1900; } thetime.tm_isdst = -1; time_t ret = mktime(&thetime); long gmadjust = 0; #if HAVE_TM_GMTOFF gmadjust = thetime.tm_gmtoff; #elif defined(_MSC_VER) TIME_ZONE_INFORMATION inf; GetTimeZoneInformation(&inf); gmadjust = thetime.tm_isdst ? inf.DaylightBias : inf.StandardBias; #else /** * If correcting for daylight savings time, we set the adjustment to * the value of timezone - 3600 seconds. Otherwise, we need to overcorrect * and set the adjustment to the main timezone + 3600 seconds. */ gmadjust = -(thetime.tm_isdst ? (long)timezone - 3600 : (long)timezone); #endif /* no adjustment for UTC */ if (timezone) ret += gmadjust; free(strbuf); return ret; } /* Special handling of subjectAltName, see CVE-2013-4073 * Christian Heimes */ static int openssl_x509v3_subjectAltName(BIO *bio, X509_EXTENSION *extension) { GENERAL_NAMES *names; const X509V3_EXT_METHOD *method = nullptr; long i, length, num; const unsigned char *p; method = X509V3_EXT_get(extension); if (method == nullptr) { return -1; } const auto data = X509_EXTENSION_get_data(extension); p = data->data; length = data->length; if (method->it) { names = (GENERAL_NAMES*)(ASN1_item_d2i(nullptr, &p, length, ASN1_ITEM_ptr(method->it))); } else { names = (GENERAL_NAMES*)(method->d2i(nullptr, &p, length)); } if (names == nullptr) { return -1; } num = sk_GENERAL_NAME_num(names); for (i = 0; i < num; i++) { GENERAL_NAME *name; ASN1_STRING *as; name = sk_GENERAL_NAME_value(names, i); switch (name->type) { case GEN_EMAIL: BIO_puts(bio, "email:"); as = name->d.rfc822Name; BIO_write(bio, ASN1_STRING_data(as), ASN1_STRING_length(as)); break; case GEN_DNS: BIO_puts(bio, "DNS:"); as = name->d.dNSName; BIO_write(bio, ASN1_STRING_data(as), ASN1_STRING_length(as)); break; case GEN_URI: BIO_puts(bio, "URI:"); as = name->d.uniformResourceIdentifier; BIO_write(bio, ASN1_STRING_data(as), ASN1_STRING_length(as)); break; default: /* use builtin print for GEN_OTHERNAME, GEN_X400, * GEN_EDIPARTY, GEN_DIRNAME, GEN_IPADD and GEN_RID */ GENERAL_NAME_print(bio, name); } /* trailing ', ' except for last element */ if (i < (num - 1)) { BIO_puts(bio, ", "); } } sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free); return 0; } Variant HHVM_FUNCTION(openssl_x509_parse, const Variant& x509cert, bool shortnames /* = true */) { auto ocert = Certificate::Get(x509cert); if (!ocert) { return false; } X509 *cert = ocert->m_cert; assertx(cert); auto ret = Array::CreateDArray(); const auto sn = X509_get_subject_name(cert); if (sn) { ret.set(s_name, String(X509_NAME_oneline(sn, nullptr, 0), CopyString)); } add_assoc_name_entry(ret, "subject", sn, shortnames); /* hash as used in CA directories to lookup cert by subject name */ { char buf[32]; snprintf(buf, sizeof(buf), "%08lx", X509_subject_name_hash(cert)); ret.set(s_hash, String(buf, CopyString)); } add_assoc_name_entry(ret, "issuer", X509_get_issuer_name(cert), shortnames); ret.set(s_version, X509_get_version(cert)); ret.set(s_serialNumber, String (i2s_ASN1_INTEGER(nullptr, X509_get_serialNumber(cert)), AttachString)); // Adding Signature Algorithm BIO *bio_out = BIO_new(BIO_s_mem()); SCOPE_EXIT { BIO_free(bio_out); }; if (i2a_ASN1_OBJECT(bio_out, X509_get0_tbs_sigalg(cert)->algorithm) > 0) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); ret.set(s_signatureAlgorithm, String((char*)bio_buf->data, bio_buf->length, CopyString)); } ASN1_STRING *str = X509_get_notBefore(cert); ret.set(s_validFrom, String((char*)str->data, str->length, CopyString)); str = X509_get_notAfter(cert); ret.set(s_validTo, String((char*)str->data, str->length, CopyString)); ret.set(s_validFrom_time_t, asn1_time_to_time_t(X509_get_notBefore(cert))); ret.set(s_validTo_time_t, asn1_time_to_time_t(X509_get_notAfter(cert))); char *tmpstr = (char *)X509_alias_get0(cert, nullptr); if (tmpstr) { ret.set(s_alias, String(tmpstr, CopyString)); } /* NOTE: the purposes are added as integer keys - the keys match up to the X509_PURPOSE_SSL_XXX defines in x509v3.h */ { Array subitem; for (int i = 0; i < X509_PURPOSE_get_count(); i++) { X509_PURPOSE *purp = X509_PURPOSE_get0(i); int id = X509_PURPOSE_get_id(purp); char * pname = shortnames ? X509_PURPOSE_get0_sname(purp) : X509_PURPOSE_get0_name(purp); auto subsub = make_varray( (bool)X509_check_purpose(cert, id, 0), (bool)X509_check_purpose(cert, id, 1), String(pname, CopyString) ); subitem.set(id, std::move(subsub)); } ret.set(s_purposes, subitem); } { auto subitem = Array::CreateDArray(); for (int i = 0; i < X509_get_ext_count(cert); i++) { int nid; X509_EXTENSION *extension = X509_get_ext(cert, i); char *extname; char buf[256]; nid = OBJ_obj2nid(X509_EXTENSION_get_object(extension)); if (nid != NID_undef) { extname = (char*)OBJ_nid2sn(OBJ_obj2nid (X509_EXTENSION_get_object(extension))); } else { OBJ_obj2txt(buf, sizeof(buf)-1, X509_EXTENSION_get_object(extension), 1); extname = buf; } BIO *bio_out = BIO_new(BIO_s_mem()); if (nid == NID_subject_alt_name) { if (openssl_x509v3_subjectAltName(bio_out, extension) == 0) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); subitem.set(String(extname, CopyString), String((char*)bio_buf->data, bio_buf->length, CopyString)); } else { BIO_free(bio_out); return false; } } else if (X509V3_EXT_print(bio_out, extension, 0, 0)) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); subitem.set(String(extname, CopyString), String((char*)bio_buf->data, bio_buf->length, CopyString)); } else { str = X509_EXTENSION_get_data(extension); subitem.set(String(extname, CopyString), String((char*)str->data, str->length, CopyString)); } BIO_free(bio_out); } ret.set(s_extensions, subitem); } return ret; } Variant HHVM_FUNCTION(openssl_x509_read, const Variant& x509certdata) { auto ocert = Certificate::Get(x509certdata); if (!ocert) { raise_warning("supplied parameter cannot be coerced into " "an X509 certificate!"); return false; } return Variant(ocert); } Variant HHVM_FUNCTION(openssl_random_pseudo_bytes, int length, bool& crypto_strong) { if (length <= 0) { return false; } unsigned char *buffer = nullptr; String s = String(length, ReserveString); buffer = (unsigned char *)s.mutableData(); if (RAND_bytes(buffer, length) <= 0) { crypto_strong = false; return false; } else { crypto_strong = true; s.setSize(length); return s; } } Variant HHVM_FUNCTION(openssl_cipher_iv_length, const String& method) { if (method.empty()) { raise_warning("Unknown cipher algorithm"); return false; } const EVP_CIPHER *cipher_type = EVP_get_cipherbyname(method.c_str()); if (!cipher_type) { raise_warning("Unknown cipher algorithm"); return false; } return EVP_CIPHER_iv_length(cipher_type); } /* Cipher mode info */ struct php_openssl_cipher_mode { /* Whether this mode uses authenticated encryption. True, for example, with the GCM and CCM modes */ bool is_aead; /* Whether this mode is a 'single run aead', meaning that DecryptFinal doesn't get called. For example, CCM mode is a single run aead mode. */ bool is_single_run_aead; /* The OpenSSL flag to get the computed tag, if this mode is aead. */ int aead_get_tag_flag; /* The OpenSSL flag to set the computed tag, if this mode is aead. */ int aead_set_tag_flag; /* The OpenSSL flag to set the IV length, if this mode is aead */ int aead_ivlen_flag; }; // initialize a php_openssl_cipher_mode corresponding to an EVP_CIPHER. static php_openssl_cipher_mode php_openssl_load_cipher_mode( const EVP_CIPHER* cipher_type) { php_openssl_cipher_mode mode = {}; switch (EVP_CIPHER_mode(cipher_type)) { #ifdef EVP_CIPH_GCM_MODE case EVP_CIPH_GCM_MODE: mode.is_aead = true; mode.is_single_run_aead = false; mode.aead_get_tag_flag = EVP_CTRL_GCM_GET_TAG; mode.aead_set_tag_flag = EVP_CTRL_GCM_SET_TAG; mode.aead_ivlen_flag = EVP_CTRL_GCM_SET_IVLEN; break; #endif #ifdef EVP_CIPH_CCM_MODE case EVP_CIPH_CCM_MODE: mode.is_aead = true; mode.is_single_run_aead = true; mode.aead_get_tag_flag = EVP_CTRL_CCM_GET_TAG; mode.aead_set_tag_flag = EVP_CTRL_CCM_SET_TAG; mode.aead_ivlen_flag = EVP_CTRL_CCM_SET_IVLEN; break; #endif default: break; } return mode; } static bool php_openssl_validate_iv( String piv, int iv_required_len, String& out, EVP_CIPHER_CTX* cipher_ctx, const php_openssl_cipher_mode* mode) { if (cipher_ctx == nullptr || mode == nullptr) { return false; } /* Best case scenario, user behaved */ if (piv.size() == iv_required_len) { out = std::move(piv); return true; } if (mode->is_aead) { if (EVP_CIPHER_CTX_ctrl( cipher_ctx, mode->aead_ivlen_flag, piv.size(), nullptr) != 1) { raise_warning( "Setting of IV length for AEAD mode failed, the expected length is " "%d bytes", iv_required_len); return false; } out = std::move(piv); return true; } String s = String(iv_required_len, ReserveString); char* iv_new = s.mutableData(); memset(iv_new, 0, iv_required_len); if (piv.size() <= 0) { /* BC behavior */ s.setSize(iv_required_len); out = std::move(s); return true; } if (piv.size() < iv_required_len) { raise_warning("IV passed is only %d bytes long, cipher " "expects an IV of precisely %d bytes, padding with \\0", piv.size(), iv_required_len); memcpy(iv_new, piv.data(), piv.size()); s.setSize(iv_required_len); out = std::move(s); return true; } raise_warning("IV passed is %d bytes long which is longer than the %d " "expected by selected cipher, truncating", piv.size(), iv_required_len); memcpy(iv_new, piv.data(), iv_required_len); s.setSize(iv_required_len); out = std::move(s); return true; } namespace { Variant openssl_encrypt_impl(const String& data, const String& method, const String& password, int options, const String& iv, Variant* tag_out, const String& aad, int tag_length) { const EVP_CIPHER *cipher_type = EVP_get_cipherbyname(method.c_str()); if (!cipher_type) { raise_warning("Unknown cipher algorithm"); return false; } EVP_CIPHER_CTX* cipher_ctx = EVP_CIPHER_CTX_new(); if (!cipher_ctx) { raise_warning("Failed to create cipher context"); return false; } SCOPE_EXIT { EVP_CIPHER_CTX_free(cipher_ctx); }; php_openssl_cipher_mode mode = php_openssl_load_cipher_mode(cipher_type); if (mode.is_aead && !tag_out) { raise_warning("Must call openssl_encrypt_with_tag when using an AEAD cipher"); return false; } int keylen = EVP_CIPHER_key_length(cipher_type); String key = password; /* * older openssl libraries can assert if the passed in password length is * less than keylen */ if (keylen > password.size()) { String s = String(keylen, ReserveString); char *keybuf = s.mutableData(); memset(keybuf, 0, keylen); memcpy(keybuf, password.data(), password.size()); key = s.setSize(keylen); } int max_iv_len = EVP_CIPHER_iv_length(cipher_type); if (iv.size() <= 0 && max_iv_len > 0 && !mode.is_aead) { raise_warning("Using an empty Initialization Vector (iv) is potentially " "insecure and not recommended"); } int result_len = 0; int outlen = data.size() + EVP_CIPHER_block_size(cipher_type); String rv = String(outlen, ReserveString); unsigned char *outbuf = (unsigned char*)rv.mutableData(); EVP_EncryptInit_ex(cipher_ctx, cipher_type, nullptr, nullptr, nullptr); String new_iv; // we do this after EncryptInit because validate_iv changes cipher_ctx for // aead modes (must be initialized first). if (!php_openssl_validate_iv( std::move(iv), max_iv_len, new_iv, cipher_ctx, &mode)) { return false; } // set the tag length for CCM mode/other modes that require tag lengths to // be set. if (mode.is_single_run_aead && !EVP_CIPHER_CTX_ctrl( cipher_ctx, mode.aead_set_tag_flag, tag_length, nullptr)) { raise_warning("Setting tag length failed"); return false; } if (password.size() > keylen) { EVP_CIPHER_CTX_set_key_length(cipher_ctx, password.size()); } EVP_EncryptInit_ex( cipher_ctx, nullptr, nullptr, (unsigned char*)key.data(), (unsigned char*)new_iv.data()); if (options & k_OPENSSL_ZERO_PADDING) { EVP_CIPHER_CTX_set_padding(cipher_ctx, 0); } // for single run aeads like CCM, we need to provide the length of the // plaintext before providing AAD or ciphertext. if (mode.is_single_run_aead && !EVP_EncryptUpdate( cipher_ctx, nullptr, &result_len, nullptr, data.size())) { raise_warning("Setting of data length failed"); return false; } // set up aad: if (mode.is_aead && !EVP_EncryptUpdate( cipher_ctx, nullptr, &result_len, (unsigned char*)aad.data(), aad.size())) { raise_warning("Setting of additional application data failed"); return false; } // OpenSSL before 0.9.8i asserts with size < 0 if (data.size() >= 0) { EVP_EncryptUpdate(cipher_ctx, outbuf, &result_len, (unsigned char *)data.data(), data.size()); } outlen = result_len; if (EVP_EncryptFinal_ex( cipher_ctx, (unsigned char*)outbuf + result_len, &result_len)) { outlen += result_len; rv.setSize(outlen); // Get tag if possible if (mode.is_aead) { String tagrv = String(tag_length, ReserveString); if (EVP_CIPHER_CTX_ctrl( cipher_ctx, mode.aead_get_tag_flag, tag_length, tagrv.mutableData()) == 1) { tagrv.setSize(tag_length); assertx(tag_out); *tag_out = tagrv; } else { raise_warning("Retrieving authentication tag failed"); return false; } } else if (tag_out) { raise_warning( "The authenticated tag cannot be provided for cipher that does not" " support AEAD"); } // Return encrypted data if (options & k_OPENSSL_RAW_DATA) { return rv; } else { return StringUtil::Base64Encode(rv); } } return false; } } // anonymous namespace Variant HHVM_FUNCTION(openssl_encrypt, const String& data, const String& method, const String& password, int options /* = 0 */, const String& iv /* = null_string */, const String& aad /* = null_string */, int tag_length /* = 16 */) { return openssl_encrypt_impl(data, method, password, options, iv, nullptr, aad, tag_length); } Variant HHVM_FUNCTION(openssl_encrypt_with_tag, const String& data, const String& method, const String& password, int options, const String& iv, Variant& tag_out, const String& aad /* = null_string */, int tag_length /* = 16 */) { return openssl_encrypt_impl(data, method, password, options, iv, &tag_out, aad, tag_length); } Variant HHVM_FUNCTION(openssl_decrypt, const String& data, const String& method, const String& password, int options /* = 0 */, const String& iv /* = null_string */, const String& tag /* = null_string */, const String& aad /* = null_string */) { const EVP_CIPHER *cipher_type = EVP_get_cipherbyname(method.c_str()); if (!cipher_type) { raise_warning("Unknown cipher algorithm"); return false; } EVP_CIPHER_CTX* cipher_ctx = EVP_CIPHER_CTX_new(); if (!cipher_ctx) { raise_warning("Failed to create cipher context"); return false; } SCOPE_EXIT { EVP_CIPHER_CTX_free(cipher_ctx); }; php_openssl_cipher_mode mode = php_openssl_load_cipher_mode(cipher_type); String decoded_data = data; if (!(options & k_OPENSSL_RAW_DATA)) { decoded_data = StringUtil::Base64Decode(data); } int keylen = EVP_CIPHER_key_length(cipher_type); String key = password; /* * older openssl libraries can assert if the passed in password length is * less than keylen */ if (keylen > password.size()) { String s = String(keylen, ReserveString); char *keybuf = s.mutableData(); memset(keybuf, 0, keylen); memcpy(keybuf, password.data(), password.size()); key = s.setSize(keylen); } int result_len = 0; int outlen = decoded_data.size() + EVP_CIPHER_block_size(cipher_type); String rv = String(outlen, ReserveString); unsigned char *outbuf = (unsigned char*)rv.mutableData(); EVP_DecryptInit_ex(cipher_ctx, cipher_type, nullptr, nullptr, nullptr); String new_iv; // we do this after DecryptInit because validate_iv changes cipher_ctx for // aead modes (must be initialized first). if (!php_openssl_validate_iv( std::move(iv), EVP_CIPHER_iv_length(cipher_type), new_iv, cipher_ctx, &mode)) { return false; } // set the tag if required: if (tag.size() > 0) { if (!mode.is_aead) { raise_warning( "The tag is being ignored because the cipher method does not" " support AEAD"); } else if (!EVP_CIPHER_CTX_ctrl( cipher_ctx, mode.aead_set_tag_flag, tag.size(), (unsigned char*)tag.data())) { raise_warning("Setting tag for AEAD cipher decryption failed"); return false; } } else { if (mode.is_aead) { raise_warning("A tag should be provided when using AEAD mode"); return false; } } if (password.size() > keylen) { EVP_CIPHER_CTX_set_key_length(cipher_ctx, password.size()); } EVP_DecryptInit_ex( cipher_ctx, nullptr, nullptr, (unsigned char*)key.data(), (unsigned char*)new_iv.data()); if (options & k_OPENSSL_ZERO_PADDING) { EVP_CIPHER_CTX_set_padding(cipher_ctx, 0); } // for single run aeads like CCM, we need to provide the length of the // ciphertext before providing AAD or ciphertext. if (mode.is_single_run_aead && !EVP_DecryptUpdate( cipher_ctx, nullptr, &result_len, nullptr, decoded_data.size())) { raise_warning("Setting of data length failed"); return false; } // set up aad: if (mode.is_aead && !EVP_DecryptUpdate( cipher_ctx, nullptr, &result_len, (unsigned char*)aad.data(), aad.size())) { raise_warning("Setting of additional application data failed"); return false; } if (!EVP_DecryptUpdate( cipher_ctx, outbuf, &result_len, (unsigned char*)decoded_data.data(), decoded_data.size())) { return false; } outlen = result_len; // if is_single_run_aead is enabled, DecryptFinal shouldn't be called. // if something went wrong in this case, we would've caught it at // DecryptUpdate. if (mode.is_single_run_aead || EVP_DecryptFinal_ex( cipher_ctx, (unsigned char*)outbuf + result_len, &result_len)) { // don't want to do this if is_single_run_aead was enabled, since we didn't // make a call to EVP_DecryptFinal. if (!mode.is_single_run_aead) { outlen += result_len; } rv.setSize(outlen); return rv; } else { return false; } } Variant HHVM_FUNCTION(openssl_digest, const String& data, const String& method, bool raw_output /* = false */) { const EVP_MD *mdtype = EVP_get_digestbyname(method.c_str()); if (!mdtype) { raise_warning("Unknown signature algorithm"); return false; } int siglen = EVP_MD_size(mdtype); String rv = String(siglen, ReserveString); unsigned char *sigbuf = (unsigned char *)rv.mutableData(); EVP_MD_CTX *md_ctx = EVP_MD_CTX_new(); SCOPE_EXIT { EVP_MD_CTX_free(md_ctx); }; EVP_DigestInit(md_ctx, mdtype); EVP_DigestUpdate(md_ctx, (unsigned char *)data.data(), data.size()); if (EVP_DigestFinal(md_ctx, (unsigned char *)sigbuf, (unsigned int *)&siglen)) { if (raw_output) { rv.setSize(siglen); return rv; } else { char* digest_str = string_bin2hex((char*)sigbuf, siglen); return String(digest_str, AttachString); } } else { return false; } } static void openssl_add_method_or_alias(const OBJ_NAME *name, void *arg) { Array *ret = (Array*)arg; ret->append(String((char *)name->name, CopyString)); } static void openssl_add_method(const OBJ_NAME *name, void *arg) { if (name->alias == 0) { Array *ret = (Array*)arg; ret->append(String((char *)name->name, CopyString)); } } Array HHVM_FUNCTION(openssl_get_cipher_methods, bool aliases /* = false */) { Array ret = Array::CreateVArray(); OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH, aliases ? openssl_add_method_or_alias: openssl_add_method, &ret); return ret; } Variant HHVM_FUNCTION(openssl_get_curve_names) { #ifdef HAVE_EVP_PKEY_EC const size_t len = EC_get_builtin_curves(nullptr, 0); std::unique_ptr<EC_builtin_curve[]> curves(new EC_builtin_curve[len]); if (!EC_get_builtin_curves(curves.get(), len)) { return false; } VArrayInit ret(len); for (size_t i = 0; i < len; ++i) { auto const sname = OBJ_nid2sn(curves[i].nid); if (sname != nullptr) { ret.append(String(sname, CopyString)); } } return ret.toArray(); #else return false; #endif } Array HHVM_FUNCTION(openssl_get_md_methods, bool aliases /* = false */) { Array ret = Array::CreateVArray(); OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_MD_METH, aliases ? openssl_add_method_or_alias: openssl_add_method, &ret); return ret; } ///////////////////////////////////////////////////////////////////////////// const StaticString s_OPENSSL_VERSION_TEXT("OPENSSL_VERSION_TEXT"); struct opensslExtension final : Extension { opensslExtension() : Extension("openssl") {} void moduleInit() override { HHVM_RC_INT(OPENSSL_RAW_DATA, k_OPENSSL_RAW_DATA); HHVM_RC_INT(OPENSSL_ZERO_PADDING, k_OPENSSL_ZERO_PADDING); HHVM_RC_INT(OPENSSL_NO_PADDING, k_OPENSSL_NO_PADDING); HHVM_RC_INT(OPENSSL_PKCS1_OAEP_PADDING, k_OPENSSL_PKCS1_OAEP_PADDING); HHVM_RC_INT(OPENSSL_SSLV23_PADDING, k_OPENSSL_SSLV23_PADDING); HHVM_RC_INT(OPENSSL_PKCS1_PADDING, k_OPENSSL_PKCS1_PADDING); HHVM_RC_INT_SAME(OPENSSL_ALGO_SHA1); HHVM_RC_INT_SAME(OPENSSL_ALGO_MD5); HHVM_RC_INT_SAME(OPENSSL_ALGO_MD4); #ifdef HAVE_OPENSSL_MD2_H HHVM_RC_INT_SAME(OPENSSL_ALGO_MD2); #endif HHVM_RC_INT_SAME(OPENSSL_ALGO_DSS1); HHVM_RC_INT_SAME(OPENSSL_ALGO_SHA224); HHVM_RC_INT_SAME(OPENSSL_ALGO_SHA256); HHVM_RC_INT_SAME(OPENSSL_ALGO_SHA384); HHVM_RC_INT_SAME(OPENSSL_ALGO_SHA512); HHVM_RC_INT_SAME(OPENSSL_ALGO_RMD160); HHVM_RC_INT(OPENSSL_CIPHER_RC2_40, PHP_OPENSSL_CIPHER_RC2_40); HHVM_RC_INT(OPENSSL_CIPHER_RC2_128, PHP_OPENSSL_CIPHER_RC2_128); HHVM_RC_INT(OPENSSL_CIPHER_RC2_64, PHP_OPENSSL_CIPHER_RC2_64); HHVM_RC_INT(OPENSSL_CIPHER_DES, PHP_OPENSSL_CIPHER_DES); HHVM_RC_INT(OPENSSL_CIPHER_3DES, PHP_OPENSSL_CIPHER_3DES); HHVM_RC_INT_SAME(OPENSSL_KEYTYPE_RSA); HHVM_RC_INT_SAME(OPENSSL_KEYTYPE_DSA); HHVM_RC_INT_SAME(OPENSSL_KEYTYPE_DH); #ifdef HAVE_EVP_PKEY_EC HHVM_RC_INT_SAME(OPENSSL_KEYTYPE_EC); #endif HHVM_RC_INT_SAME(OPENSSL_VERSION_NUMBER); HHVM_RC_INT_SAME(PKCS7_TEXT); HHVM_RC_INT_SAME(PKCS7_NOCERTS); HHVM_RC_INT_SAME(PKCS7_NOSIGS); HHVM_RC_INT_SAME(PKCS7_NOCHAIN); HHVM_RC_INT_SAME(PKCS7_NOINTERN); HHVM_RC_INT_SAME(PKCS7_NOVERIFY); HHVM_RC_INT_SAME(PKCS7_DETACHED); HHVM_RC_INT_SAME(PKCS7_BINARY); HHVM_RC_INT_SAME(PKCS7_NOATTR); HHVM_RC_STR_SAME(OPENSSL_VERSION_TEXT); HHVM_RC_INT_SAME(X509_PURPOSE_SSL_CLIENT); HHVM_RC_INT_SAME(X509_PURPOSE_SSL_SERVER); HHVM_RC_INT_SAME(X509_PURPOSE_NS_SSL_SERVER); HHVM_RC_INT_SAME(X509_PURPOSE_SMIME_SIGN); HHVM_RC_INT_SAME(X509_PURPOSE_SMIME_ENCRYPT); HHVM_RC_INT_SAME(X509_PURPOSE_CRL_SIGN); #ifdef X509_PURPOSE_ANY HHVM_RC_INT_SAME(X509_PURPOSE_ANY); #endif HHVM_FE(openssl_csr_export_to_file); HHVM_FE(openssl_csr_export); HHVM_FE(openssl_csr_get_public_key); HHVM_FE(openssl_csr_get_subject); HHVM_FE(openssl_csr_new); HHVM_FE(openssl_csr_sign); HHVM_FE(openssl_error_string); HHVM_FE(openssl_open); HHVM_FE(openssl_pkcs12_export_to_file); HHVM_FE(openssl_pkcs12_export); HHVM_FE(openssl_pkcs12_read); HHVM_FE(openssl_pkcs7_decrypt); HHVM_FE(openssl_pkcs7_encrypt); HHVM_FE(openssl_pkcs7_sign); HHVM_FE(openssl_pkcs7_verify); HHVM_FE(openssl_pkey_export_to_file); HHVM_FE(openssl_pkey_export); HHVM_FE(openssl_pkey_get_details); HHVM_FE(openssl_pkey_get_private); HHVM_FE(openssl_pkey_get_public); HHVM_FE(openssl_pkey_new); HHVM_FE(openssl_private_decrypt); HHVM_FE(openssl_private_encrypt); HHVM_FE(openssl_public_decrypt); HHVM_FE(openssl_public_encrypt); HHVM_FE(openssl_seal); HHVM_FE(openssl_sign); HHVM_FE(openssl_verify); HHVM_FE(openssl_x509_check_private_key); HHVM_FE(openssl_x509_checkpurpose); HHVM_FE(openssl_x509_export_to_file); HHVM_FE(openssl_x509_export); HHVM_FE(openssl_x509_parse); HHVM_FE(openssl_x509_read); HHVM_FE(openssl_random_pseudo_bytes); HHVM_FE(openssl_cipher_iv_length); HHVM_FE(openssl_encrypt); HHVM_FE(openssl_encrypt_with_tag); HHVM_FE(openssl_decrypt); HHVM_FE(openssl_digest); HHVM_FE(openssl_get_cipher_methods); HHVM_FE(openssl_get_curve_names); HHVM_FE(openssl_get_md_methods); loadSystemlib(); } } s_openssl_extension; /////////////////////////////////////////////////////////////////////////////// }
null
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1997-2010 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/ext/openssl/ext_openssl.h" #include "hphp/runtime/base/array-init.h" #include "hphp/runtime/base/array-iterator.h" #include "hphp/runtime/base/ssl-socket.h" #include "hphp/runtime/base/string-util.h" #include "hphp/runtime/base/zend-string.h" #include "hphp/util/logger.h" #include <folly/ScopeGuard.h> #include <openssl/conf.h> #include <openssl/pem.h> #include <openssl/pkcs12.h> #include <openssl/rand.h> #include <vector> namespace HPHP { #define MIN_KEY_LENGTH 384 // bitfields const int64_t k_OPENSSL_RAW_DATA = 1; const int64_t k_OPENSSL_ZERO_PADDING = 2; const int64_t k_OPENSSL_NO_PADDING = 3; const int64_t k_OPENSSL_PKCS1_OAEP_PADDING = 4; // exported constants const int64_t k_OPENSSL_SSLV23_PADDING = 2; const int64_t k_OPENSSL_PKCS1_PADDING = 1; static char default_ssl_conf_filename[PATH_MAX]; struct OpenSSLInitializer { OpenSSLInitializer() { SSL_library_init(); OpenSSL_add_all_ciphers(); OpenSSL_add_all_digests(); OpenSSL_add_all_algorithms(); // CCM ciphers are not added by default, so let's add them! #if !defined(OPENSSL_NO_AES) && defined(EVP_CIPH_CCM_MODE) && \ OPENSSL_VERSION_NUMBER < 0x100020000 EVP_add_cipher(EVP_aes_128_ccm()); EVP_add_cipher(EVP_aes_192_ccm()); EVP_add_cipher(EVP_aes_256_ccm()); #endif ERR_load_ERR_strings(); ERR_load_crypto_strings(); ERR_load_EVP_strings(); /* Determine default SSL configuration file */ char *config_filename = getenv("OPENSSL_CONF"); if (config_filename == nullptr) { config_filename = getenv("SSLEAY_CONF"); } /* default to 'openssl.cnf' if no environment variable is set */ if (config_filename == nullptr) { snprintf(default_ssl_conf_filename, sizeof(default_ssl_conf_filename), "%s/%s", X509_get_default_cert_area(), "openssl.cnf"); } else { always_assert( strlen(config_filename) < sizeof(default_ssl_conf_filename)); strcpy(default_ssl_conf_filename, config_filename); } } ~OpenSSLInitializer() { EVP_cleanup(); } }; static OpenSSLInitializer s_openssl_initializer; /////////////////////////////////////////////////////////////////////////////// // resource classes struct Key : SweepableResourceData { EVP_PKEY *m_key; explicit Key(EVP_PKEY *key) : m_key(key) { assertx(m_key);} ~Key() override { if (m_key) EVP_PKEY_free(m_key); } CLASSNAME_IS("OpenSSL key"); // overriding ResourceData const String& o_getClassNameHook() const override { return classnameof(); } DECLARE_RESOURCE_ALLOCATION(Key) bool isPrivate() { assertx(m_key); switch (EVP_PKEY_id(m_key)) { #ifndef NO_RSA case EVP_PKEY_RSA: case EVP_PKEY_RSA2: { const auto rsa = EVP_PKEY_get0_RSA(m_key); assertx(rsa); const BIGNUM *p, *q; RSA_get0_factors(rsa, &p, &q); if (!p || !q) { return false; } break; } #endif #ifndef NO_DSA case EVP_PKEY_DSA: case EVP_PKEY_DSA1: case EVP_PKEY_DSA2: case EVP_PKEY_DSA3: case EVP_PKEY_DSA4: { const auto dsa = EVP_PKEY_get0_DSA(m_key); assertx(dsa); const BIGNUM *p, *q, *g, *pub_key, *priv_key; DSA_get0_pqg(dsa, &p, &q, &g); if (!p || !q || !g) { return false; } DSA_get0_key(dsa, &pub_key, &priv_key); if (!priv_key) { return false; } break; } #endif #ifndef NO_DH case EVP_PKEY_DH: { const auto dh = EVP_PKEY_get0_DH(m_key); assertx(dh); const BIGNUM *p, *q, *g, *pub_key, *priv_key; DH_get0_pqg(dh, &p, &q, &g); if (!p) { return false; } DH_get0_key(dh, &pub_key, &priv_key); if (!priv_key) { return false; } break; } #endif #ifdef HAVE_EVP_PKEY_EC case EVP_PKEY_EC: { const auto ec_key = EVP_PKEY_get0_EC_KEY(m_key); assertx(ec_key); if (EC_KEY_get0_private_key(ec_key) == nullptr) { return false; } break; } #endif default: raise_warning("key type not supported in this PHP build!"); break; } return true; } /** * Given a variant, coerce it into a EVP_PKEY object. It can be: * * 1. private key resource from openssl_get_privatekey() * 2. X509 resource -> public key will be extracted from it * 3. if it starts with file:// interpreted as path to key file * 4. interpreted as the data from the cert/key file and interpreted in * same way as openssl_get_privatekey() * 5. an array(0 => [items 2..4], 1 => passphrase) * 6. if val is a string (possibly starting with file:///) and it is not * an X509 certificate, then interpret as public key * * NOTE: If you are requesting a private key but have not specified a * passphrase, you should use an empty string rather than nullptr for the * passphrase - nullptr causes a passphrase prompt to be emitted in * the Apache error log! */ static req::ptr<Key> Get(const Variant& var, bool public_key, const char *passphrase = nullptr) { if (var.isArray()) { Array arr = var.toArray(); if (!arr.exists(int64_t(0)) || !arr.exists(int64_t(1))) { raise_warning("key array must be of the form " "array(0 => key, 1 => phrase)"); return nullptr; } String zphrase = arr[1].toString(); return GetHelper(arr[0], public_key, zphrase.data()); } return GetHelper(var, public_key, passphrase); } static req::ptr<Key> GetHelper(const Variant& var, bool public_key, const char *passphrase) { req::ptr<Certificate> ocert; EVP_PKEY *key = nullptr; if (var.isResource()) { auto cert = dyn_cast_or_null<Certificate>(var); auto key = dyn_cast_or_null<Key>(var); if (!cert && !key) return nullptr; if (key) { bool is_priv = key->isPrivate(); if (!public_key && !is_priv) { raise_warning("supplied key param is a public key"); return nullptr; } if (public_key && is_priv) { raise_warning("Don't know how to get public key from " "this private key"); return nullptr; } return key; } ocert = cert; } else { /* it's an X509 file/cert of some kind, and we need to extract the data from that */ if (public_key) { ocert = Certificate::Get(var); if (!ocert) { /* not a X509 certificate, try to retrieve public key */ BIO *in = Certificate::ReadData(var); if (in == nullptr) return nullptr; key = PEM_read_bio_PUBKEY(in, nullptr,nullptr, nullptr); BIO_free(in); } } else { /* we want the private key */ BIO *in = Certificate::ReadData(var); if (in == nullptr) return nullptr; key = PEM_read_bio_PrivateKey(in, nullptr,nullptr, (void*)passphrase); BIO_free(in); } } if (public_key && ocert && key == nullptr) { /* extract public key from X509 cert */ key = (EVP_PKEY *)X509_get_pubkey(ocert->get()); } if (key) { return req::make<Key>(key); } return nullptr; } }; IMPLEMENT_RESOURCE_ALLOCATION(Key) /** * Certificate Signing Request */ struct CSRequest : SweepableResourceData { private: X509_REQ *m_csr; public: explicit CSRequest(X509_REQ *csr) : m_csr(csr) { assertx(m_csr); } X509_REQ *csr() { return m_csr; } ~CSRequest() override { // X509_REQ_free(nullptr) is a no-op X509_REQ_free(m_csr); } CLASSNAME_IS("OpenSSL X.509 CSR"); // overriding ResourceData const String& o_getClassNameHook() const override { return classnameof(); } DECLARE_RESOURCE_ALLOCATION(CSRequest) static req::ptr<CSRequest> Get(const Variant& var) { auto csr = cast_or_null<CSRequest>(GetRequest(var)); if (!csr || !csr->m_csr) { raise_warning("cannot get CSR"); return nullptr; } return csr; } private: static req::ptr<CSRequest> GetRequest(const Variant& var) { if (var.isResource()) { return dyn_cast_or_null<CSRequest>(var); } if (var.isString() || var.isObject()) { BIO *in = Certificate::ReadData(var); if (in == nullptr) return nullptr; X509_REQ *csr = PEM_read_bio_X509_REQ(in, nullptr,nullptr,nullptr); BIO_free(in); if (csr) { return req::make<CSRequest>(csr); } } return nullptr; } }; IMPLEMENT_RESOURCE_ALLOCATION(CSRequest) struct php_x509_request { #if OPENSSL_VERSION_NUMBER >= 0x10000002L LHASH_OF(CONF_VALUE) * global_config; /* Global SSL config */ LHASH_OF(CONF_VALUE) * req_config; /* SSL config for this request */ #else LHASH *global_config; /* Global SSL config */ LHASH *req_config; /* SSL config for this request */ #endif const EVP_MD *md_alg; const EVP_MD *digest; const char *section_name; const char *config_filename; const char *digest_name; const char *extensions_section; const char *request_extensions_section; int priv_key_bits; int priv_key_type; int priv_key_encrypt; #ifdef HAVE_EVP_PKEY_EC int curve_name; #endif EVP_PKEY *priv_key; static bool load_rand_file(const char *file, int *egdsocket, int *seeded) { char buffer[PATH_MAX]; *egdsocket = 0; *seeded = 0; if (file == nullptr) { file = RAND_file_name(buffer, sizeof(buffer)); #if !defined(OPENSSL_NO_RAND_EGD) && !defined(OPENSSL_NO_EGD) } else if (RAND_egd(file) > 0) { /* if the given filename is an EGD socket, don't * write anything back to it */ *egdsocket = 1; return true; #endif } if (file == nullptr || !RAND_load_file(file, -1)) { if (RAND_status() == 0) { raise_warning("unable to load random state; not enough data!"); return false; } return false; } *seeded = 1; return true; } static bool write_rand_file(const char *file, int egdsocket, int seeded) { char buffer[PATH_MAX]; if (egdsocket || !seeded) { /* if we did not manage to read the seed file, we should not write * a low-entropy seed file back */ return false; } if (file == nullptr) { file = RAND_file_name(buffer, sizeof(buffer)); } if (file == nullptr || !RAND_write_file(file)) { raise_warning("unable to write random state"); return false; } return true; } bool generatePrivateKey() { assertx(priv_key == nullptr); if (priv_key_bits < MIN_KEY_LENGTH) { raise_warning("private key length is too short; it needs to be " "at least %d bits, not %d", MIN_KEY_LENGTH, priv_key_bits); return false; } char *randfile = CONF_get_string(req_config, section_name, "RANDFILE"); int egdsocket, seeded; load_rand_file(randfile, &egdsocket, &seeded); bool ret = false; if ((priv_key = EVP_PKEY_new()) != nullptr) { switch (priv_key_type) { case OPENSSL_KEYTYPE_RSA: if (EVP_PKEY_assign_RSA (priv_key, RSA_generate_key(priv_key_bits, 0x10001, nullptr, nullptr))) { ret = true; } break; #if !defined(NO_DSA) && defined(HAVE_DSA_DEFAULT_METHOD) case OPENSSL_KEYTYPE_DSA: { DSA *dsapar = DSA_generate_parameters(priv_key_bits, nullptr, 0, nullptr, nullptr, nullptr, nullptr); if (dsapar) { DSA_set_method(dsapar, DSA_get_default_method()); if (DSA_generate_key(dsapar)) { if (EVP_PKEY_assign_DSA(priv_key, dsapar)) { ret = true; } } else { DSA_free(dsapar); } } } break; #endif #ifdef HAVE_EVP_PKEY_EC case OPENSSL_KEYTYPE_EC: { if (curve_name == NID_undef) { raise_warning("Missing configuration value: 'curve_name' not set"); return false; } if (auto const eckey = EC_KEY_new_by_curve_name(curve_name)) { EC_KEY_set_asn1_flag(eckey, OPENSSL_EC_NAMED_CURVE); if (EC_KEY_generate_key(eckey) && EVP_PKEY_assign_EC_KEY(priv_key, eckey)) { ret = true; } else { EC_KEY_free(eckey); } } } break; #endif default: raise_warning("Unsupported private key type"); } } write_rand_file(randfile, egdsocket, seeded); return ret; } }; /////////////////////////////////////////////////////////////////////////////// // utilities static void add_assoc_name_entry(Array &ret, const char *key, X509_NAME *name, bool shortname) { Array subitem_data; Array &subitem = key ? subitem_data : ret; for (int i = 0; i < X509_NAME_entry_count(name); i++) { X509_NAME_ENTRY *ne = X509_NAME_get_entry(name, i); ASN1_OBJECT *obj = X509_NAME_ENTRY_get_object(ne); int nid = OBJ_obj2nid(obj); int obj_cnt = 0; char *sname; if (shortname) { sname = (char *)OBJ_nid2sn(nid); } else { sname = (char *)OBJ_nid2ln(nid); } Array subentries; int last = -1; int j; ASN1_STRING *str = nullptr; unsigned char *to_add = nullptr; int to_add_len = 0; for (;;) { j = X509_NAME_get_index_by_OBJ(name, obj, last); if (j < 0) { if (last != -1) break; } else { obj_cnt++; ne = X509_NAME_get_entry(name, j); str = X509_NAME_ENTRY_get_data(ne); if (ASN1_STRING_type(str) != V_ASN1_UTF8STRING) { to_add_len = ASN1_STRING_to_UTF8(&to_add, str); if (to_add_len != -1) { subentries.append(String((char*)to_add, to_add_len, AttachString)); } } else { to_add = ASN1_STRING_data(str); to_add_len = ASN1_STRING_length(str); subentries.append(String((char*)to_add, to_add_len, CopyString)); } } last = j; } i = last; if (obj_cnt > 1) { subitem.set(String(sname, CopyString), subentries); } else if (obj_cnt && str && to_add_len > -1) { // Use the string instance we created above. subitem.set(String(sname, CopyString), subentries[0]); } } if (key) { ret.set(String(key, CopyString), subitem); } } static const char *read_string(const Array& args, const String& key, const char *def, std::vector<String> &strings) { if (args.exists(key)) { String value = args[key].toString(); strings.push_back(value); return (char*)value.data(); } return def; } static int64_t read_integer(const Array& args, const String& key, int64_t def) { if (args.exists(key)) { return args[key].toInt64(); } return def; } static bool add_oid_section(struct php_x509_request *req) { char *str = CONF_get_string(req->req_config, nullptr, "oid_section"); if (str == nullptr) { return true; } STACK_OF(CONF_VALUE) *sktmp = CONF_get_section(req->req_config, str); if (sktmp == nullptr) { raise_warning("problem loading oid section %s", str); return false; } for (int i = 0; i < sk_CONF_VALUE_num(sktmp); i++) { CONF_VALUE *cnf = sk_CONF_VALUE_value(sktmp, i); if (OBJ_sn2nid(cnf->name) == NID_undef && OBJ_ln2nid(cnf->name) == NID_undef && OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) { raise_warning("problem creating object %s=%s", cnf->name, cnf->value); return false; } } return true; } #if OPENSSL_VERSION_NUMBER >= 0x10000002L static inline bool php_openssl_config_check_syntax (const char *section_label, const char *config_filename, const char *section, LHASH_OF(CONF_VALUE) *config) { #else static inline bool php_openssl_config_check_syntax (const char *section_label, const char *config_filename, const char *section, LHASH *config) { #endif X509V3_CTX ctx; X509V3_set_ctx_test(&ctx); X509V3_set_conf_lhash(&ctx, config); if (!X509V3_EXT_add_conf(config, &ctx, (char*)section, nullptr)) { raise_warning("Error loading %s section %s of %s", section_label, section, config_filename); return false; } return true; } const StaticString s_config("config"), s_config_section_name("config_section_name"), s_digest_alg("digest_alg"), s_x509_extensions("x509_extensions"), s_req_extensions("req_extensions"), s_private_key_bits("private_key_bits"), s_private_key_type("private_key_type"), s_encrypt_key("encrypt_key"), s_curve_name("curve_name"); static bool php_openssl_parse_config(struct php_x509_request *req, const Array& args, std::vector<String> &strings) { req->config_filename = read_string(args, s_config, default_ssl_conf_filename, strings); req->section_name = read_string(args, s_config_section_name, "req", strings); req->global_config = CONF_load(nullptr, default_ssl_conf_filename, nullptr); req->req_config = CONF_load(nullptr, req->config_filename, nullptr); if (req->req_config == nullptr) { return false; } /* read in the oids */ char *str = CONF_get_string(req->req_config, nullptr, "oid_file"); if (str) { BIO *oid_bio = BIO_new_file(str, "r"); if (oid_bio) { OBJ_create_objects(oid_bio); BIO_free(oid_bio); } } if (!add_oid_section(req)) { return false; } req->digest_name = read_string(args, s_digest_alg, CONF_get_string(req->req_config, req->section_name, "default_md"), strings); req->extensions_section = read_string(args, s_x509_extensions, CONF_get_string(req->req_config, req->section_name, "x509_extensions"), strings); req->request_extensions_section = read_string(args, s_req_extensions, CONF_get_string(req->req_config, req->section_name, "req_extensions"), strings); req->priv_key_bits = read_integer(args, s_private_key_bits, CONF_get_number(req->req_config, req->section_name, "default_bits")); req->priv_key_type = read_integer(args, s_private_key_type, OPENSSL_KEYTYPE_DEFAULT); if (args.exists(s_encrypt_key)) { bool value = args[s_encrypt_key].toBoolean(); req->priv_key_encrypt = value ? 1 : 0; } else { str = CONF_get_string(req->req_config, req->section_name, "encrypt_rsa_key"); if (str == nullptr) { str = CONF_get_string(req->req_config, req->section_name, "encrypt_key"); } if (str && strcmp(str, "no") == 0) { req->priv_key_encrypt = 0; } else { req->priv_key_encrypt = 1; } } /* digest alg */ if (req->digest_name == nullptr) { req->digest_name = CONF_get_string(req->req_config, req->section_name, "default_md"); } if (req->digest_name) { req->digest = req->md_alg = EVP_get_digestbyname(req->digest_name); } if (req->md_alg == nullptr) { req->md_alg = req->digest = EVP_sha256(); } #ifdef HAVE_EVP_PKEY_EC /* set the ec group curve name */ req->curve_name = NID_undef; if (args.exists(s_curve_name)) { auto const curve_name = args[s_curve_name].toString(); req->curve_name = OBJ_sn2nid(curve_name.data()); if (req->curve_name == NID_undef) { raise_warning( "Unknown elliptic curve (short) name %s", curve_name.data() ); return false; } } #endif if (req->extensions_section && !php_openssl_config_check_syntax ("extensions_section", req->config_filename, req->extensions_section, req->req_config)) { return false; } /* set the string mask */ str = CONF_get_string(req->req_config, req->section_name, "string_mask"); if (str && !ASN1_STRING_set_default_mask_asc(str)) { raise_warning("Invalid global string mask setting %s", str); return false; } if (req->request_extensions_section && !php_openssl_config_check_syntax ("request_extensions_section", req->config_filename, req->request_extensions_section, req->req_config)) { return false; } return true; } static void php_openssl_dispose_config(struct php_x509_request *req) { if (req->global_config) { CONF_free(req->global_config); req->global_config = nullptr; } if (req->req_config) { CONF_free(req->req_config); req->req_config = nullptr; } } static STACK_OF(X509) *load_all_certs_from_file(const char *certfile) { STACK_OF(X509_INFO) *sk = nullptr; STACK_OF(X509) *stack = nullptr, *ret = nullptr; BIO *in = nullptr; X509_INFO *xi; if (!(stack = sk_X509_new_null())) { raise_warning("memory allocation failure"); goto end; } if (!(in = BIO_new_file(certfile, "r"))) { raise_warning("error opening the file, %s", certfile); sk_X509_free(stack); goto end; } /* This loads from a file, a stack of x509/crl/pkey sets */ if (!(sk = PEM_X509_INFO_read_bio(in, nullptr, nullptr, nullptr))) { raise_warning("error reading the file, %s", certfile); sk_X509_free(stack); goto end; } /* scan over it and pull out the certs */ while (sk_X509_INFO_num(sk)) { xi = sk_X509_INFO_shift(sk); if (xi->x509 != nullptr) { sk_X509_push(stack, xi->x509); xi->x509 = nullptr; } X509_INFO_free(xi); } if (!sk_X509_num(stack)) { raise_warning("no certificates in file, %s", certfile); sk_X509_free(stack); goto end; } ret = stack; end: BIO_free(in); sk_X509_INFO_free(sk); return ret; } /** * calist is an array containing file and directory names. create a * certificate store and add those certs to it for use in verification. */ static X509_STORE *setup_verify(const Array& calist) { X509_STORE *store = X509_STORE_new(); if (store == nullptr) { return nullptr; } X509_LOOKUP *dir_lookup, *file_lookup; int ndirs = 0, nfiles = 0; for (ArrayIter iter(calist); iter; ++iter) { String item = iter.second().toString(); struct stat sb; if (stat(item.data(), &sb) == -1) { raise_warning("unable to stat %s", item.data()); continue; } if ((sb.st_mode & S_IFREG) == S_IFREG) { file_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()); if (file_lookup == nullptr || !X509_LOOKUP_load_file(file_lookup, item.data(), X509_FILETYPE_PEM)) { raise_warning("error loading file %s", item.data()); } else { nfiles++; } file_lookup = nullptr; } else { dir_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir()); if (dir_lookup == nullptr || !X509_LOOKUP_add_dir(dir_lookup, item.data(), X509_FILETYPE_PEM)) { raise_warning("error loading directory %s", item.data()); } else { ndirs++; } dir_lookup = nullptr; } } if (nfiles == 0) { file_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()); if (file_lookup) { X509_LOOKUP_load_file(file_lookup, nullptr, X509_FILETYPE_DEFAULT); } } if (ndirs == 0) { dir_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir()); if (dir_lookup) { X509_LOOKUP_add_dir(dir_lookup, nullptr, X509_FILETYPE_DEFAULT); } } return store; } /////////////////////////////////////////////////////////////////////////////// static bool add_entries(X509_NAME *subj, const Array& items) { for (ArrayIter iter(items); iter; ++iter) { auto const index = iter.first().toString(); auto const item = iter.second().toString(); int nid = OBJ_txt2nid(index.data()); if (nid != NID_undef) { if (!X509_NAME_add_entry_by_NID(subj, nid, MBSTRING_ASC, (unsigned char*)item.data(), -1, -1, 0)) { raise_warning("dn: add_entry_by_NID %d -> %s (failed)", nid, item.data()); return false; } } else { raise_warning("dn: %s is not a recognized name", index.data()); } } return true; } static bool php_openssl_make_REQ(struct php_x509_request *req, X509_REQ *csr, const Array& dn, const Array& attribs) { char *dn_sect = CONF_get_string(req->req_config, req->section_name, "distinguished_name"); if (dn_sect == nullptr) return false; STACK_OF(CONF_VALUE) *dn_sk = CONF_get_section(req->req_config, dn_sect); if (dn_sk == nullptr) return false; char *attr_sect = CONF_get_string(req->req_config, req->section_name, "attributes"); STACK_OF(CONF_VALUE) *attr_sk = nullptr; if (attr_sect) { attr_sk = CONF_get_section(req->req_config, attr_sect); if (attr_sk == nullptr) { return false; } } /* setup the version number: version 1 */ if (X509_REQ_set_version(csr, 0L)) { X509_NAME *subj = X509_REQ_get_subject_name(csr); if (!add_entries(subj, dn)) return false; /* Finally apply defaults from config file */ for (int i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) { CONF_VALUE *v = sk_CONF_VALUE_value(dn_sk, i); char *type = v->name; int len = strlen(type); if (len < (int)sizeof("_default")) { continue; } len -= sizeof("_default") - 1; if (strcmp("_default", type + len) != 0) { continue; } if (len > 200) { len = 200; } char buffer[200 + 1]; /*200 + \0 !*/ memcpy(buffer, type, len); buffer[len] = '\0'; type = buffer; /* Skip past any leading X. X: X, etc to allow for multiple instances */ for (char *str = type; *str; str++) { if (*str == ':' || *str == ',' || *str == '.') { str++; if (*str) { type = str; } break; } } /* if it is already set, skip this */ int nid = OBJ_txt2nid(type); if (X509_NAME_get_index_by_NID(subj, nid, -1) >= 0) { continue; } if (!X509_NAME_add_entry_by_txt(subj, type, MBSTRING_ASC, (unsigned char*)v->value, -1, -1, 0)) { raise_warning("add_entry_by_txt %s -> %s (failed)", type, v->value); return false; } if (!X509_NAME_entry_count(subj)) { raise_warning("no objects specified in config file"); return false; } } if (!add_entries(subj, attribs)) return false; if (attr_sk) { for (int i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) { CONF_VALUE *v = sk_CONF_VALUE_value(attr_sk, i); /* if it is already set, skip this */ int nid = OBJ_txt2nid(v->name); if (X509_REQ_get_attr_by_NID(csr, nid, -1) >= 0) { continue; } if (!X509_REQ_add1_attr_by_txt(csr, v->name, MBSTRING_ASC, (unsigned char*)v->value, -1)) { /** * hzhao: mismatched version of conf file may have attributes that * are not recognizable, and I don't think it should be treated as * fatal errors. */ Logger::Verbose("add1_attr_by_txt %s -> %s (failed)", v->name, v->value); // return false; } } } } X509_REQ_set_pubkey(csr, req->priv_key); return true; } bool HHVM_FUNCTION(openssl_csr_export_to_file, const Variant& csr, const String& outfilename, bool notext /* = true */) { auto pcsr = CSRequest::Get(csr); if (!pcsr) return false; BIO *bio_out = BIO_new_file((char*)outfilename.data(), "w"); if (bio_out == nullptr) { raise_warning("error opening file %s", outfilename.data()); return false; } if (!notext) { X509_REQ_print(bio_out, pcsr->csr()); } PEM_write_bio_X509_REQ(bio_out, pcsr->csr()); BIO_free(bio_out); return true; } bool HHVM_FUNCTION(openssl_csr_export, const Variant& csr, Variant& out, bool notext /* = true */) { auto pcsr = CSRequest::Get(csr); if (!pcsr) return false; BIO *bio_out = BIO_new(BIO_s_mem()); if (!notext) { X509_REQ_print(bio_out, pcsr->csr()); } if (PEM_write_bio_X509_REQ(bio_out, pcsr->csr())) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); out = String((char*)bio_buf->data, bio_buf->length, CopyString); BIO_free(bio_out); return true; } BIO_free(bio_out); return false; } Variant HHVM_FUNCTION(openssl_csr_get_public_key, const Variant& csr) { auto pcsr = CSRequest::Get(csr); if (!pcsr) return false; auto input_csr = pcsr->csr(); #if OPENSSL_VERSION_NUMBER >= 0x10100000 /* Due to changes in OpenSSL 1.1 related to locking when decoding CSR, * the pub key is not changed after assigning. It means if we pass * a private key, it will be returned including the private part. * If we duplicate it, then we get just the public part which is * the same behavior as for OpenSSL 1.0 */ input_csr = X509_REQ_dup(input_csr); /* We need to free the CSR as it was duplicated */ SCOPE_EXIT { X509_REQ_free(input_csr); }; #endif auto pubkey = X509_REQ_get_pubkey(input_csr); if (!pubkey) return false; return Variant(req::make<Key>(pubkey)); } Variant HHVM_FUNCTION(openssl_csr_get_subject, const Variant& csr, bool use_shortnames /* = true */) { auto pcsr = CSRequest::Get(csr); if (!pcsr) return false; X509_NAME *subject = X509_REQ_get_subject_name(pcsr->csr()); Array ret = Array::CreateDArray(); add_assoc_name_entry(ret, nullptr, subject, use_shortnames); return ret; } Variant HHVM_FUNCTION(openssl_csr_new, const Variant& dn, Variant& privkey, const Variant& configargs /* = uninit_variant */, const Variant& extraattribs /* = uninit_variant */) { Variant ret = false; struct php_x509_request req; memset(&req, 0, sizeof(req)); req::ptr<Key> okey; X509_REQ *csr = nullptr; std::vector<String> strings; if (php_openssl_parse_config(&req, configargs.toArray(), strings)) { /* Generate or use a private key */ if (!privkey.isNull()) { okey = Key::Get(privkey, false); if (okey) { req.priv_key = okey->m_key; } } if (req.priv_key == nullptr) { req.generatePrivateKey(); if (req.priv_key) { okey = req::make<Key>(req.priv_key); } } if (req.priv_key == nullptr) { raise_warning("Unable to generate a private key"); } else { csr = X509_REQ_new(); if (csr && php_openssl_make_REQ(&req, csr, dn.toArray(), extraattribs.toArray())) { X509V3_CTX ext_ctx; X509V3_set_ctx(&ext_ctx, nullptr, nullptr, csr, nullptr, 0); X509V3_set_conf_lhash(&ext_ctx, req.req_config); /* Add extensions */ if (req.request_extensions_section && !X509V3_EXT_REQ_add_conf(req.req_config, &ext_ctx, (char*)req.request_extensions_section, csr)) { raise_warning("Error loading extension section %s", req.request_extensions_section); } else { ret = true; if (X509_REQ_sign(csr, req.priv_key, req.digest)) { ret = req::make<CSRequest>(csr); csr = nullptr; } else { raise_warning("Error signing request"); } privkey = Variant(okey); } } } } if (csr) { X509_REQ_free(csr); } php_openssl_dispose_config(&req); return ret; } Variant HHVM_FUNCTION(openssl_csr_sign, const Variant& csr, const Variant& cacert, const Variant& priv_key, int days, const Variant& configargs /* = null */, int serial /* = 0 */) { auto pcsr = CSRequest::Get(csr); if (!pcsr) return false; req::ptr<Certificate> ocert; if (!cacert.isNull()) { ocert = Certificate::Get(cacert); if (!ocert) { raise_warning("cannot get cert from parameter 2"); return false; } } auto okey = Key::Get(priv_key, false); if (!okey) { raise_warning("cannot get private key from parameter 3"); return false; } X509 *cert = nullptr; if (ocert) { cert = ocert->m_cert; } EVP_PKEY *pkey = okey->m_key; if (cert && !X509_check_private_key(cert, pkey)) { raise_warning("private key does not correspond to signing cert"); return false; } req::ptr<Certificate> onewcert; struct php_x509_request req; memset(&req, 0, sizeof(req)); Variant ret = false; std::vector<String> strings; if (!php_openssl_parse_config(&req, configargs.toArray(), strings)) { goto cleanup; } /* Check that the request matches the signature */ EVP_PKEY *key; key = X509_REQ_get_pubkey(pcsr->csr()); if (key == nullptr) { raise_warning("error unpacking public key"); goto cleanup; } int i; i = X509_REQ_verify(pcsr->csr(), key); if (i < 0) { raise_warning("Signature verification problems"); goto cleanup; } if (i == 0) { raise_warning("Signature did not match the certificate request"); goto cleanup; } /* Now we can get on with it */ X509 *new_cert; new_cert = X509_new(); if (new_cert == nullptr) { raise_warning("No memory"); goto cleanup; } onewcert = req::make<Certificate>(new_cert); /* Version 3 cert */ if (!X509_set_version(new_cert, 2)) { goto cleanup; } ASN1_INTEGER_set(X509_get_serialNumber(new_cert), serial); X509_set_subject_name(new_cert, X509_REQ_get_subject_name(pcsr->csr())); if (cert == nullptr) { cert = new_cert; } if (!X509_set_issuer_name(new_cert, X509_get_subject_name(cert))) { goto cleanup; } X509_gmtime_adj(X509_get_notBefore(new_cert), 0); X509_gmtime_adj(X509_get_notAfter(new_cert), (long)60 * 60 * 24 * days); i = X509_set_pubkey(new_cert, key); if (!i) { goto cleanup; } if (req.extensions_section) { X509V3_CTX ctx; X509V3_set_ctx(&ctx, cert, new_cert, pcsr->csr(), nullptr, 0); X509V3_set_conf_lhash(&ctx, req.req_config); if (!X509V3_EXT_add_conf(req.req_config, &ctx, (char*)req.extensions_section, new_cert)) { goto cleanup; } } /* Now sign it */ if (!X509_sign(new_cert, pkey, req.digest)) { raise_warning("failed to sign it"); goto cleanup; } /* Succeeded; lets return the cert */ ret = onewcert; cleanup: php_openssl_dispose_config(&req); return ret; } Variant HHVM_FUNCTION(openssl_error_string) { char buf[512]; unsigned long val = ERR_get_error(); if (val) { return String(ERR_error_string(val, buf), CopyString); } return false; } bool HHVM_FUNCTION(openssl_open, const String& sealed_data, Variant& open_data, const String& env_key, const Variant& priv_key_id, const String& method, /* = null_string */ const String& iv /* = null_string */) { const EVP_CIPHER *cipher_type; if (method.empty()) { cipher_type = EVP_rc4(); } else { cipher_type = EVP_get_cipherbyname(method.c_str()); if (!cipher_type) { raise_warning("Unknown cipher algorithm"); return false; } } auto okey = Key::Get(priv_key_id, false); if (!okey) { raise_warning("unable to coerce parameter 4 into a private key"); return false; } EVP_PKEY *pkey = okey->m_key; const unsigned char *iv_buf = nullptr; int iv_len = EVP_CIPHER_iv_length(cipher_type); if (iv_len > 0) { if (iv.empty()) { raise_warning( "Cipher algorithm requires an IV to be supplied as a sixth parameter"); return false; } if (iv.length() != iv_len) { raise_warning("IV length is invalid"); return false; } iv_buf = reinterpret_cast<const unsigned char*>(iv.c_str()); } String s = String(sealed_data.size(), ReserveString); unsigned char *buf = (unsigned char *)s.mutableData(); EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new(); if (ctx == nullptr) { raise_warning("Failed to allocate an EVP_CIPHER_CTX object"); return false; } SCOPE_EXIT { EVP_CIPHER_CTX_free(ctx); }; int len1, len2; if (!EVP_OpenInit( ctx, cipher_type, (unsigned char*)env_key.data(), env_key.size(), iv_buf, pkey) || !EVP_OpenUpdate( ctx, buf, &len1, (unsigned char*)sealed_data.data(), sealed_data.size()) || !EVP_OpenFinal(ctx, buf + len1, &len2) || len1 + len2 == 0) { return false; } open_data = s.setSize(len1 + len2); return true; } static STACK_OF(X509) *php_array_to_X509_sk(const Variant& certs) { STACK_OF(X509) *pcerts = sk_X509_new_null(); Array arrCerts; if (certs.isArray()) { arrCerts = certs.toArray(); } else { arrCerts.append(certs); } for (ArrayIter iter(arrCerts); iter; ++iter) { auto ocert = Certificate::Get(iter.second()); if (!ocert) { break; } sk_X509_push(pcerts, ocert->m_cert); } return pcerts; } const StaticString s_friendly_name("friendly_name"), s_extracerts("extracerts"); static bool openssl_pkcs12_export_impl(const Variant& x509, BIO *bio_out, const Variant& priv_key, const String& pass, const Variant& args /* = uninit_variant */) { auto ocert = Certificate::Get(x509); if (!ocert) { raise_warning("cannot get cert from parameter 1"); return false; } auto okey = Key::Get(priv_key, false); if (!okey) { raise_warning("cannot get private key from parameter 3"); return false; } X509 *cert = ocert->m_cert; EVP_PKEY *key = okey->m_key; if (cert && !X509_check_private_key(cert, key)) { raise_warning("private key does not correspond to cert"); return false; } Array arrArgs = args.toArray(); String friendly_name; if (arrArgs.exists(s_friendly_name)) { friendly_name = arrArgs[s_friendly_name].toString(); } STACK_OF(X509) *ca = nullptr; if (arrArgs.exists(s_extracerts)) { ca = php_array_to_X509_sk(arrArgs[s_extracerts]); } PKCS12 *p12 = PKCS12_create ((char*)pass.data(), (char*)(friendly_name.empty() ? nullptr : friendly_name.data()), key, cert, ca, 0, 0, 0, 0, 0); assertx(bio_out); bool ret = i2d_PKCS12_bio(bio_out, p12); PKCS12_free(p12); sk_X509_free(ca); return ret; } bool HHVM_FUNCTION(openssl_pkcs12_export_to_file, const Variant& x509, const String& filename, const Variant& priv_key, const String& pass, const Variant& args /* = uninit_variant */) { BIO *bio_out = BIO_new_file(filename.data(), "w"); if (bio_out == nullptr) { raise_warning("error opening file %s", filename.data()); return false; } bool ret = openssl_pkcs12_export_impl(x509, bio_out, priv_key, pass, args); BIO_free(bio_out); return ret; } bool HHVM_FUNCTION(openssl_pkcs12_export, const Variant& x509, Variant& out, const Variant& priv_key, const String& pass, const Variant& args /* = uninit_variant */) { BIO *bio_out = BIO_new(BIO_s_mem()); bool ret = openssl_pkcs12_export_impl(x509, bio_out, priv_key, pass, args); if (ret) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); out = String((char*)bio_buf->data, bio_buf->length, CopyString); } BIO_free(bio_out); return ret; } const StaticString s_cert("cert"), s_pkey("pkey"); bool HHVM_FUNCTION(openssl_pkcs12_read, const String& pkcs12, Variant& certs, const String& pass) { bool ret = false; PKCS12 *p12 = nullptr; BIO *bio_in = BIO_new(BIO_s_mem()); if (!BIO_write(bio_in, pkcs12.data(), pkcs12.size())) { goto cleanup; } if (d2i_PKCS12_bio(bio_in, &p12)) { EVP_PKEY *pkey = nullptr; X509 *cert = nullptr; STACK_OF(X509) *ca = nullptr; if (PKCS12_parse(p12, pass.data(), &pkey, &cert, &ca)) { Variant vcerts = Array::CreateDArray(); SCOPE_EXIT { certs = vcerts; }; BIO *bio_out = nullptr; if (cert) { bio_out = BIO_new(BIO_s_mem()); if (PEM_write_bio_X509(bio_out, cert)) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); vcerts.asArrRef().set(s_cert, String((char*)bio_buf->data, bio_buf->length, CopyString)); } BIO_free(bio_out); } if (pkey) { bio_out = BIO_new(BIO_s_mem()); if (PEM_write_bio_PrivateKey(bio_out, pkey, nullptr, nullptr, 0, 0, nullptr)) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); vcerts.asArrRef().set(s_pkey, String((char*)bio_buf->data, bio_buf->length, CopyString)); } BIO_free(bio_out); } if (ca) { Array extracerts; for (X509 *aCA = sk_X509_pop(ca); aCA; aCA = sk_X509_pop(ca)) { bio_out = BIO_new(BIO_s_mem()); if (PEM_write_bio_X509(bio_out, aCA)) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); extracerts.append(String((char*)bio_buf->data, bio_buf->length, CopyString)); } BIO_free(bio_out); X509_free(aCA); } sk_X509_free(ca); vcerts.asArrRef().set(s_extracerts, extracerts); } ret = true; PKCS12_free(p12); } } cleanup: if (bio_in) { BIO_free(bio_in); } return ret; } bool HHVM_FUNCTION(openssl_pkcs7_decrypt, const String& infilename, const String& outfilename, const Variant& recipcert, const Variant& recipkey /* = uninit_variant */) { bool ret = false; BIO *in = nullptr, *out = nullptr, *datain = nullptr; PKCS7 *p7 = nullptr; req::ptr<Key> okey; auto ocert = Certificate::Get(recipcert); if (!ocert) { raise_warning("unable to coerce parameter 3 to x509 cert"); goto clean_exit; } okey = Key::Get(recipkey.isNull() ? recipcert : recipkey, false); if (!okey) { raise_warning("unable to get private key"); goto clean_exit; } in = BIO_new_file(infilename.data(), "r"); if (in == nullptr) { raise_warning("error opening the file, %s", infilename.data()); goto clean_exit; } out = BIO_new_file(outfilename.data(), "w"); if (out == nullptr) { raise_warning("error opening the file, %s", outfilename.data()); goto clean_exit; } p7 = SMIME_read_PKCS7(in, &datain); if (p7 == nullptr) { goto clean_exit; } assertx(okey->m_key); assertx(ocert->m_cert); if (PKCS7_decrypt(p7, okey->m_key, ocert->m_cert, out, PKCS7_DETACHED)) { ret = true; } clean_exit: PKCS7_free(p7); BIO_free(datain); BIO_free(in); BIO_free(out); return ret; } static void print_headers(BIO *outfile, const Array& headers) { if (!headers.isNull()) { if (headers->isVectorData()) { for (ArrayIter iter(headers); iter; ++iter) { BIO_printf(outfile, "%s\n", iter.second().toString().data()); } } else { for (ArrayIter iter(headers); iter; ++iter) { BIO_printf(outfile, "%s: %s\n", iter.first().toString().data(), iter.second().toString().data()); } } } } bool HHVM_FUNCTION(openssl_pkcs7_encrypt, const String& infilename, const String& outfilename, const Variant& recipcerts, const Array& headers, int flags /* = 0 */, int cipherid /* = k_OPENSSL_CIPHER_RC2_40 */) { bool ret = false; BIO *infile = nullptr, *outfile = nullptr; STACK_OF(X509) *precipcerts = nullptr; PKCS7 *p7 = nullptr; const EVP_CIPHER *cipher = nullptr; infile = BIO_new_file(infilename.data(), (flags & PKCS7_BINARY) ? "rb" : "r"); if (infile == nullptr) { raise_warning("error opening the file, %s", infilename.data()); goto clean_exit; } outfile = BIO_new_file(outfilename.data(), "w"); if (outfile == nullptr) { raise_warning("error opening the file, %s", outfilename.data()); goto clean_exit; } precipcerts = php_array_to_X509_sk(recipcerts); /* sanity check the cipher */ switch (cipherid) { #ifndef OPENSSL_NO_RC2 case PHP_OPENSSL_CIPHER_RC2_40: cipher = EVP_rc2_40_cbc(); break; case PHP_OPENSSL_CIPHER_RC2_64: cipher = EVP_rc2_64_cbc(); break; case PHP_OPENSSL_CIPHER_RC2_128: cipher = EVP_rc2_cbc(); break; #endif #ifndef OPENSSL_NO_DES case PHP_OPENSSL_CIPHER_DES: cipher = EVP_des_cbc(); break; case PHP_OPENSSL_CIPHER_3DES: cipher = EVP_des_ede3_cbc(); break; #endif default: raise_warning("Invalid cipher type `%d'", cipherid); goto clean_exit; } if (cipher == nullptr) { raise_warning("Failed to get cipher"); goto clean_exit; } p7 = PKCS7_encrypt(precipcerts, infile, (EVP_CIPHER*)cipher, flags); if (p7 == nullptr) goto clean_exit; print_headers(outfile, headers); (void)BIO_reset(infile); SMIME_write_PKCS7(outfile, p7, infile, flags); ret = true; clean_exit: PKCS7_free(p7); BIO_free(infile); BIO_free(outfile); sk_X509_free(precipcerts); return ret; } bool HHVM_FUNCTION(openssl_pkcs7_sign, const String& infilename, const String& outfilename, const Variant& signcert, const Variant& privkey, const Variant& headers, int flags /* = k_PKCS7_DETACHED */, const String& extracerts /* = null_string */) { bool ret = false; STACK_OF(X509) *others = nullptr; BIO *infile = nullptr, *outfile = nullptr; PKCS7 *p7 = nullptr; req::ptr<Key> okey; req::ptr<Certificate> ocert; if (!extracerts.empty()) { others = load_all_certs_from_file(extracerts.data()); if (others == nullptr) { goto clean_exit; } } okey = Key::Get(privkey, false); if (!okey) { raise_warning("error getting private key"); goto clean_exit; } EVP_PKEY *key; key = okey->m_key; ocert = Certificate::Get(signcert); if (!ocert) { raise_warning("error getting cert"); goto clean_exit; } X509 *cert; cert = ocert->m_cert; infile = BIO_new_file(infilename.data(), (flags & PKCS7_BINARY) ? "rb" : "r"); if (infile == nullptr) { raise_warning("error opening input file %s!", infilename.data()); goto clean_exit; } outfile = BIO_new_file(outfilename.data(), "w"); if (outfile == nullptr) { raise_warning("error opening output file %s!", outfilename.data()); goto clean_exit; } p7 = PKCS7_sign(cert, key, others, infile, flags); if (p7 == nullptr) { raise_warning("error creating PKCS7 structure!"); goto clean_exit; } print_headers(outfile, headers.toArray()); (void)BIO_reset(infile); SMIME_write_PKCS7(outfile, p7, infile, flags); ret = true; clean_exit: PKCS7_free(p7); BIO_free(infile); BIO_free(outfile); if (others) { sk_X509_pop_free(others, X509_free); } return ret; } static int pkcs7_ignore_expiration(int ok, X509_STORE_CTX *ctx) { if (ok) { return ok; } int error = X509_STORE_CTX_get_error(ctx); if (error == X509_V_ERR_CERT_HAS_EXPIRED) { // ignore cert expirations Logger::Verbose("Ignoring cert expiration"); return 1; } return ok; } /** * NOTE: when ignore_cert_expiration is true, a custom certificate validation * callback is set up. Please be aware of this if you modify the function to * allow other certificate validation behaviors */ Variant openssl_pkcs7_verify_core( const String& filename, int flags, const Variant& voutfilename /* = null_string */, const Variant& vcainfo /* = null_array */, const Variant& vextracerts /* = null_string */, const Variant& vcontent /* = null_string */, bool ignore_cert_expiration ) { Variant ret = -1; X509_STORE *store = nullptr; BIO *in = nullptr; PKCS7 *p7 = nullptr; BIO *datain = nullptr; BIO *dataout = nullptr; auto cainfo = vcainfo.toArray(); auto extracerts = vextracerts.toString(); auto content = vcontent.toString(); STACK_OF(X509) *others = nullptr; if (!extracerts.empty()) { others = load_all_certs_from_file(extracerts.data()); if (others == nullptr) { goto clean_exit; } } flags = flags & ~PKCS7_DETACHED; store = setup_verify(cainfo); if (!store) { goto clean_exit; } if (ignore_cert_expiration) { #if (OPENSSL_VERSION_NUMBER >= 0x10000000) // make sure no other callback is specified #if OPENSSL_VERSION_NUMBER >= 0x10100000L assertx(!X509_STORE_get_verify_cb(store)); #else assertx(!store->verify_cb); #endif // ignore expired certs X509_STORE_set_verify_cb(store, pkcs7_ignore_expiration); #else always_assert(false); #endif } in = BIO_new_file(filename.data(), (flags & PKCS7_BINARY) ? "rb" : "r"); if (in == nullptr) { raise_warning("error opening the file, %s", filename.data()); goto clean_exit; } p7 = SMIME_read_PKCS7(in, &datain); if (p7 == nullptr) { goto clean_exit; } if (!content.empty()) { dataout = BIO_new_file(content.data(), "w"); if (dataout == nullptr) { raise_warning("error opening the file, %s", content.data()); goto clean_exit; } } if (PKCS7_verify(p7, others, store, datain, dataout, flags)) { ret = true; auto outfilename = voutfilename.toString(); if (!outfilename.empty()) { BIO *certout = BIO_new_file(outfilename.data(), "w"); if (certout) { STACK_OF(X509) *signers = PKCS7_get0_signers(p7, nullptr, flags); for (int i = 0; i < sk_X509_num(signers); i++) { PEM_write_bio_X509(certout, sk_X509_value(signers, i)); } BIO_free(certout); sk_X509_free(signers); } else { raise_warning("signature OK, but cannot open %s for writing", outfilename.data()); ret = -1; } } goto clean_exit; } else { ret = false; } clean_exit: X509_STORE_free(store); BIO_free(datain); BIO_free(in); BIO_free(dataout); PKCS7_free(p7); sk_X509_pop_free(others, X509_free); return ret; } Variant HHVM_FUNCTION(openssl_pkcs7_verify, const String& filename, int flags, const Variant& voutfilename /* = null_string */, const Variant& vcainfo /* = null_array */, const Variant& vextracerts /* = null_string */, const Variant& vcontent /* = null_string */) { return openssl_pkcs7_verify_core(filename, flags, voutfilename, vcainfo, vextracerts, vcontent, false); } static bool openssl_pkey_export_impl(const Variant& key, BIO *bio_out, const String& passphrase /* = null_string */, const Variant& configargs /* = uninit_variant */) { auto okey = Key::Get(key, false, passphrase.data()); if (!okey) { raise_warning("cannot get key from parameter 1"); return false; } EVP_PKEY *pkey = okey->m_key; struct php_x509_request req; memset(&req, 0, sizeof(req)); std::vector<String> strings; bool ret = false; if (php_openssl_parse_config(&req, configargs.toArray(), strings)) { const EVP_CIPHER *cipher; if (!passphrase.empty() && req.priv_key_encrypt) { cipher = (EVP_CIPHER *)EVP_des_ede3_cbc(); } else { cipher = nullptr; } assertx(bio_out); switch (EVP_PKEY_id(pkey)) { #ifdef HAVE_EVP_PKEY_EC case EVP_PKEY_EC: ret = PEM_write_bio_ECPrivateKey(bio_out, EVP_PKEY_get0_EC_KEY(pkey), cipher, (unsigned char *)passphrase.data(), passphrase.size(), nullptr, nullptr); break; #endif default: ret = PEM_write_bio_PrivateKey(bio_out, pkey, cipher, (unsigned char *)passphrase.data(), passphrase.size(), nullptr, nullptr); break; } } php_openssl_dispose_config(&req); return ret; } bool HHVM_FUNCTION(openssl_pkey_export_to_file, const Variant& key, const String& outfilename, const String& passphrase /* = null_string */, const Variant& configargs /* = uninit_variant */) { BIO *bio_out = BIO_new_file(outfilename.data(), "w"); if (bio_out == nullptr) { raise_warning("error opening the file, %s", outfilename.data()); return false; } bool ret = openssl_pkey_export_impl(key, bio_out, passphrase, configargs); BIO_free(bio_out); return ret; } bool HHVM_FUNCTION(openssl_pkey_export, const Variant& key, Variant& out, const String& passphrase /* = null_string */, const Variant& configargs /* = uninit_variant */) { BIO *bio_out = BIO_new(BIO_s_mem()); bool ret = openssl_pkey_export_impl(key, bio_out, passphrase, configargs); if (ret) { char *bio_mem_ptr; long bio_mem_len = BIO_get_mem_data(bio_out, &bio_mem_ptr); out = String(bio_mem_ptr, bio_mem_len, CopyString); } BIO_free(bio_out); return ret; } const StaticString s_bits("bits"), s_key("key"), s_type("type"), s_name("name"), s_hash("hash"), s_version("version"), s_serialNumber("serialNumber"), s_signatureAlgorithm("signatureAlgorithm"), s_validFrom("validFrom"), s_validTo("validTo"), s_validFrom_time_t("validFrom_time_t"), s_validTo_time_t("validTo_time_t"), s_alias("alias"), s_purposes("purposes"), s_extensions("extensions"), s_rsa("rsa"), s_dsa("dsa"), s_dh("dh"), s_ec("ec"), s_n("n"), s_e("e"), s_d("d"), s_p("p"), s_q("q"), s_g("g"), s_x("x"), s_y("y"), s_dmp1("dmp1"), s_dmq1("dmq1"), s_iqmp("iqmp"), s_priv_key("priv_key"), s_pub_key("pub_key"), s_curve_oid("curve_oid"); static void add_bignum_as_string(Array &arr, StaticString key, const BIGNUM *bn) { if (!bn) { return; } int num_bytes = BN_num_bytes(bn); String str{size_t(num_bytes), ReserveString}; BN_bn2bin(bn, (unsigned char*)str.mutableData()); str.setSize(num_bytes); arr.set(key, std::move(str)); } Array HHVM_FUNCTION(openssl_pkey_get_details, const Resource& key) { EVP_PKEY *pkey = cast<Key>(key)->m_key; BIO *out = BIO_new(BIO_s_mem()); PEM_write_bio_PUBKEY(out, pkey); char *pbio; unsigned int pbio_len = BIO_get_mem_data(out, &pbio); auto ret = make_darray( s_bits, EVP_PKEY_bits(pkey), s_key, String(pbio, pbio_len, CopyString) ); long ktype = -1; auto details = Array::CreateDArray(); switch (EVP_PKEY_id(pkey)) { case EVP_PKEY_RSA: case EVP_PKEY_RSA2: { ktype = OPENSSL_KEYTYPE_RSA; RSA *rsa = EVP_PKEY_get0_RSA(pkey); assertx(rsa); const BIGNUM *n, *e, *d, *p, *q, *dmp1, *dmq1, *iqmp; RSA_get0_key(rsa, &n, &e, &d); RSA_get0_factors(rsa, &p, &q); RSA_get0_crt_params(rsa, &dmp1, &dmq1, &iqmp); add_bignum_as_string(details, s_n, n); add_bignum_as_string(details, s_e, e); add_bignum_as_string(details, s_d, d); add_bignum_as_string(details, s_p, p); add_bignum_as_string(details, s_q, q); add_bignum_as_string(details, s_dmp1, dmp1); add_bignum_as_string(details, s_dmq1, dmq1); add_bignum_as_string(details, s_iqmp, iqmp); ret.set(s_rsa, details); break; } case EVP_PKEY_DSA: case EVP_PKEY_DSA2: case EVP_PKEY_DSA3: case EVP_PKEY_DSA4: { ktype = OPENSSL_KEYTYPE_DSA; DSA *dsa = EVP_PKEY_get0_DSA(pkey); assertx(dsa); const BIGNUM *p, *q, *g, *pub_key, *priv_key; DSA_get0_pqg(dsa, &p, &q, &g); DSA_get0_key(dsa, &pub_key, &priv_key); add_bignum_as_string(details, s_p, p); add_bignum_as_string(details, s_q, q); add_bignum_as_string(details, s_g, g); add_bignum_as_string(details, s_priv_key, priv_key); add_bignum_as_string(details, s_pub_key, pub_key); ret.set(s_dsa, details); break; } case EVP_PKEY_DH: { ktype = OPENSSL_KEYTYPE_DH; DH *dh = EVP_PKEY_get0_DH(pkey); assertx(dh); const BIGNUM *p, *q, *g, *pub_key, *priv_key; DH_get0_pqg(dh, &p, &q, &g); DH_get0_key(dh, &pub_key, &priv_key); add_bignum_as_string(details, s_p, p); add_bignum_as_string(details, s_g, g); add_bignum_as_string(details, s_priv_key, priv_key); add_bignum_as_string(details, s_pub_key, pub_key); ret.set(s_dh, details); break; } #ifdef HAVE_EVP_PKEY_EC case EVP_PKEY_EC: { ktype = OPENSSL_KEYTYPE_EC; auto const ec = EVP_PKEY_get0_EC_KEY(pkey); assertx(ec); auto const ec_group = EC_KEY_get0_group(ec); auto const nid = EC_GROUP_get_curve_name(ec_group); if (nid == NID_undef) { break; } auto const crv_sn = OBJ_nid2sn(nid); if (crv_sn != nullptr) { details.set(s_curve_name, String(crv_sn, CopyString)); } auto const obj = OBJ_nid2obj(nid); if (obj != nullptr) { SCOPE_EXIT { ASN1_OBJECT_free(obj); }; char oir_buf[256]; OBJ_obj2txt(oir_buf, sizeof(oir_buf) - 1, obj, 1); details.set(s_curve_oid, String(oir_buf, CopyString)); } auto x = BN_new(); auto y = BN_new(); SCOPE_EXIT { BN_free(x); BN_free(y); }; auto const pub = EC_KEY_get0_public_key(ec); if (EC_POINT_get_affine_coordinates_GFp(ec_group, pub, x, y, nullptr)) { add_bignum_as_string(details, s_x, x); add_bignum_as_string(details, s_y, y); } auto d = BN_dup(EC_KEY_get0_private_key(ec)); SCOPE_EXIT { BN_free(d); }; if (d != nullptr) { add_bignum_as_string(details, s_d, d); } ret.set(s_ec, details); } break; #endif } ret.set(s_type, ktype); BIO_free(out); return ret; } Variant HHVM_FUNCTION(openssl_pkey_get_private, const Variant& key, const String& passphrase /* = null_string */) { return toVariant(Key::Get(key, false, passphrase.data())); } Variant HHVM_FUNCTION(openssl_pkey_get_public, const Variant& certificate) { return toVariant(Key::Get(certificate, true)); } Variant HHVM_FUNCTION(openssl_pkey_new, const Variant& configargs /* = uninit_variant */) { struct php_x509_request req; memset(&req, 0, sizeof(req)); SCOPE_EXIT { php_openssl_dispose_config(&req); }; std::vector<String> strings; if (php_openssl_parse_config(&req, configargs.toArray(), strings) && req.generatePrivateKey()) { return Resource(req::make<Key>(req.priv_key)); } else { return false; } } bool HHVM_FUNCTION(openssl_private_decrypt, const String& data, Variant& decrypted, const Variant& key, int padding /* = k_OPENSSL_PKCS1_PADDING */) { auto okey = Key::Get(key, false); if (!okey) { raise_warning("key parameter is not a valid private key"); return false; } EVP_PKEY *pkey = okey->m_key; int cryptedlen = EVP_PKEY_size(pkey); String s = String(cryptedlen, ReserveString); unsigned char *cryptedbuf = (unsigned char *)s.mutableData(); int successful = 0; switch (EVP_PKEY_id(pkey)) { case EVP_PKEY_RSA: case EVP_PKEY_RSA2: cryptedlen = RSA_private_decrypt(data.size(), (unsigned char *)data.data(), cryptedbuf, EVP_PKEY_get0_RSA(pkey), padding); if (cryptedlen != -1) { successful = 1; } break; default: raise_warning("key type not supported"); } if (successful) { decrypted = s.setSize(cryptedlen); return true; } return false; } bool HHVM_FUNCTION(openssl_private_encrypt, const String& data, Variant& crypted, const Variant& key, int padding /* = k_OPENSSL_PKCS1_PADDING */) { auto okey = Key::Get(key, false); if (!okey) { raise_warning("key param is not a valid private key"); return false; } EVP_PKEY *pkey = okey->m_key; int cryptedlen = EVP_PKEY_size(pkey); String s = String(cryptedlen, ReserveString); unsigned char *cryptedbuf = (unsigned char *)s.mutableData(); int successful = 0; switch (EVP_PKEY_id(pkey)) { case EVP_PKEY_RSA: case EVP_PKEY_RSA2: successful = (RSA_private_encrypt(data.size(), (unsigned char *)data.data(), cryptedbuf, EVP_PKEY_get0_RSA(pkey), padding) == cryptedlen); break; default: raise_warning("key type not supported"); } if (successful) { crypted = s.setSize(cryptedlen); return true; } return false; } bool HHVM_FUNCTION(openssl_public_decrypt, const String& data, Variant& decrypted, const Variant& key, int padding /* = k_OPENSSL_PKCS1_PADDING */) { auto okey = Key::Get(key, true); if (!okey) { raise_warning("key parameter is not a valid public key"); return false; } EVP_PKEY *pkey = okey->m_key; int cryptedlen = EVP_PKEY_size(pkey); String s = String(cryptedlen, ReserveString); unsigned char *cryptedbuf = (unsigned char *)s.mutableData(); int successful = 0; switch (EVP_PKEY_id(pkey)) { case EVP_PKEY_RSA: case EVP_PKEY_RSA2: cryptedlen = RSA_public_decrypt(data.size(), (unsigned char *)data.data(), cryptedbuf, EVP_PKEY_get0_RSA(pkey), padding); if (cryptedlen != -1) { successful = 1; } break; default: raise_warning("key type not supported"); } if (successful) { decrypted = s.setSize(cryptedlen); return true; } return false; } bool HHVM_FUNCTION(openssl_public_encrypt, const String& data, Variant& crypted, const Variant& key, int padding /* = k_OPENSSL_PKCS1_PADDING */) { auto okey = Key::Get(key, true); if (!okey) { raise_warning("key parameter is not a valid public key"); return false; } EVP_PKEY *pkey = okey->m_key; int cryptedlen = EVP_PKEY_size(pkey); String s = String(cryptedlen, ReserveString); unsigned char *cryptedbuf = (unsigned char *)s.mutableData(); int successful = 0; switch (EVP_PKEY_id(pkey)) { case EVP_PKEY_RSA: case EVP_PKEY_RSA2: successful = (RSA_public_encrypt(data.size(), (unsigned char *)data.data(), cryptedbuf, EVP_PKEY_get0_RSA(pkey), padding) == cryptedlen); break; default: raise_warning("key type not supported"); } if (successful) { crypted = s.setSize(cryptedlen); return true; } return false; } Variant HHVM_FUNCTION(openssl_seal, const String& data, Variant& sealed_data, Variant& env_keys, const Array& pub_key_ids, const String& method, Variant& iv) { int nkeys = pub_key_ids.size(); if (nkeys == 0) { raise_warning("Fourth argument to openssl_seal() must be " "a non-empty array"); return false; } const EVP_CIPHER *cipher_type; if (method.empty()) { cipher_type = EVP_rc4(); } else { cipher_type = EVP_get_cipherbyname(method.c_str()); if (!cipher_type) { raise_warning("Unknown cipher algorithm"); return false; } } int iv_len = EVP_CIPHER_iv_length(cipher_type); unsigned char *iv_buf = nullptr; String iv_s; if (iv_len > 0) { iv_s = String(iv_len, ReserveString); iv_buf = (unsigned char*)iv_s.mutableData(); if (!RAND_bytes(iv_buf, iv_len)) { raise_warning("Could not generate an IV."); return false; } } EVP_PKEY **pkeys = (EVP_PKEY**)malloc(nkeys * sizeof(*pkeys)); int *eksl = (int*)malloc(nkeys * sizeof(*eksl)); unsigned char **eks = (unsigned char **)malloc(nkeys * sizeof(*eks)); memset(eks, 0, sizeof(*eks) * nkeys); // holder is needed to make sure none of the Keys get deleted prematurely. // The pkeys array points to elements inside of Keys returned from Key::Get() // which may be newly allocated and have no other owners. std::vector<req::ptr<Key>> holder; /* get the public keys we are using to seal this data */ bool ret = true; int i = 0; String s; unsigned char* buf = nullptr; EVP_CIPHER_CTX* ctx = nullptr; for (ArrayIter iter(pub_key_ids); iter; ++iter, ++i) { auto okey = Key::Get(iter.second(), true); if (!okey) { raise_warning("not a public key (%dth member of pubkeys)", i + 1); ret = false; goto clean_exit; } holder.push_back(okey); pkeys[i] = okey->m_key; eks[i] = (unsigned char *)malloc(EVP_PKEY_size(pkeys[i]) + 1); } ctx = EVP_CIPHER_CTX_new(); if (ctx == nullptr) { raise_warning("Failed to allocate an EVP_CIPHER_CTX object"); ret = false; goto clean_exit; } if (!EVP_EncryptInit_ex(ctx, cipher_type, nullptr, nullptr, nullptr)) { ret = false; goto clean_exit; } int len1, len2; s = String(data.size() + EVP_CIPHER_CTX_block_size(ctx), ReserveString); buf = (unsigned char *)s.mutableData(); if (EVP_SealInit(ctx, cipher_type, eks, eksl, iv_buf, pkeys, nkeys) <= 0 || !EVP_SealUpdate(ctx, buf, &len1, (unsigned char*)data.data(), data.size()) || !EVP_SealFinal(ctx, buf + len1, &len2)) { ret = false; goto clean_exit; } if (len1 + len2 > 0) { sealed_data = s.setSize(len1 + len2); auto ekeys = Array::CreateVArray(); for (i = 0; i < nkeys; i++) { eks[i][eksl[i]] = '\0'; ekeys.append(String((char*)eks[i], eksl[i], AttachString)); eks[i] = nullptr; } env_keys = ekeys; } clean_exit: for (i = 0; i < nkeys; i++) { if (eks[i]) free(eks[i]); } free(eks); free(eksl); free(pkeys); if (iv_buf != nullptr) { if (ret) { iv = iv_s.setSize(iv_len); } } if (ctx != nullptr) { EVP_CIPHER_CTX_free(ctx); } if (ret) return len1 + len2; return false; } static const EVP_MD *php_openssl_get_evp_md_from_algo(long algo) { switch (algo) { case OPENSSL_ALGO_SHA1: return EVP_sha1(); case OPENSSL_ALGO_MD5: return EVP_md5(); case OPENSSL_ALGO_MD4: return EVP_md4(); #ifdef HAVE_OPENSSL_MD2_H case OPENSSL_ALGO_MD2: return EVP_md2(); #endif #if OPENSSL_VERSION_NUMBER < 0x10100000L case OPENSSL_ALGO_DSS1: return EVP_dss1(); #endif #if OPENSSL_VERSION_NUMBER >= 0x0090708fL case OPENSSL_ALGO_SHA224: return EVP_sha224(); case OPENSSL_ALGO_SHA256: return EVP_sha256(); case OPENSSL_ALGO_SHA384: return EVP_sha384(); case OPENSSL_ALGO_SHA512: return EVP_sha512(); case OPENSSL_ALGO_RMD160: return EVP_ripemd160(); #endif } return nullptr; } bool HHVM_FUNCTION(openssl_sign, const String& data, Variant& signature, const Variant& priv_key_id, const Variant& signature_alg /* = k_OPENSSL_ALGO_SHA1 */) { auto okey = Key::Get(priv_key_id, false); if (!okey) { raise_warning("supplied key param cannot be coerced into a private key"); return false; } const EVP_MD *mdtype = nullptr; if (signature_alg.isInteger()) { mdtype = php_openssl_get_evp_md_from_algo(signature_alg.toInt64Val()); } else if (signature_alg.isString()) { mdtype = EVP_get_digestbyname(signature_alg.toString().data()); } if (!mdtype) { raise_warning("Unknown signature algorithm."); return false; } EVP_PKEY *pkey = okey->m_key; int siglen = EVP_PKEY_size(pkey); String s = String(siglen, ReserveString); unsigned char *sigbuf = (unsigned char *)s.mutableData(); EVP_MD_CTX *md_ctx = EVP_MD_CTX_new(); SCOPE_EXIT { EVP_MD_CTX_free(md_ctx); }; EVP_SignInit(md_ctx, mdtype); EVP_SignUpdate(md_ctx, (unsigned char *)data.data(), data.size()); if (EVP_SignFinal(md_ctx, sigbuf, (unsigned int *)&siglen, pkey)) { signature = s.setSize(siglen); return true; } return false; } Variant HHVM_FUNCTION(openssl_verify, const String& data, const String& signature, const Variant& pub_key_id, const Variant& signature_alg /* = k_OPENSSL_ALGO_SHA1 */) { int err; const EVP_MD *mdtype = nullptr; if (signature_alg.isInteger()) { mdtype = php_openssl_get_evp_md_from_algo(signature_alg.toInt64Val()); } else if (signature_alg.isString()) { mdtype = EVP_get_digestbyname(signature_alg.toString().data()); } if (!mdtype) { raise_warning("Unknown signature algorithm."); return false; } auto okey = Key::Get(pub_key_id, true); if (!okey) { raise_warning("supplied key param cannot be coerced into a public key"); return false; } EVP_MD_CTX *md_ctx = EVP_MD_CTX_new(); SCOPE_EXIT { EVP_MD_CTX_free(md_ctx); }; EVP_VerifyInit(md_ctx, mdtype); EVP_VerifyUpdate(md_ctx, (unsigned char*)data.data(), data.size()); err = EVP_VerifyFinal(md_ctx, (unsigned char *)signature.data(), signature.size(), okey->m_key); return err; } bool HHVM_FUNCTION(openssl_x509_check_private_key, const Variant& cert, const Variant& key) { auto ocert = Certificate::Get(cert); if (!ocert) { return false; } auto okey = Key::Get(key, false); if (!okey) { return false; } return X509_check_private_key(ocert->m_cert, okey->m_key); } static int check_cert(X509_STORE *ctx, X509 *x, STACK_OF(X509) *untrustedchain, int purpose) { X509_STORE_CTX *csc = X509_STORE_CTX_new(); if (csc == nullptr) { raise_warning("memory allocation failure"); return 0; } X509_STORE_CTX_init(csc, ctx, x, untrustedchain); if (purpose >= 0) { X509_STORE_CTX_set_purpose(csc, purpose); } int ret = X509_verify_cert(csc); X509_STORE_CTX_free(csc); return ret; } Variant HHVM_FUNCTION(openssl_x509_checkpurpose, const Variant& x509cert, int purpose, const Array& cainfo /* = null_array */, const String& untrustedfile /* = null_string */) { int ret = -1; STACK_OF(X509) *untrustedchain = nullptr; X509_STORE *pcainfo = nullptr; req::ptr<Certificate> ocert; if (!untrustedfile.empty()) { untrustedchain = load_all_certs_from_file(untrustedfile.data()); if (untrustedchain == nullptr) { goto clean_exit; } } pcainfo = setup_verify(cainfo); if (pcainfo == nullptr) { goto clean_exit; } ocert = Certificate::Get(x509cert); if (!ocert) { raise_warning("cannot get cert from parameter 1"); return false; } X509 *cert; cert = ocert->m_cert; assertx(cert); ret = check_cert(pcainfo, cert, untrustedchain, purpose); clean_exit: if (pcainfo) { X509_STORE_free(pcainfo); } if (untrustedchain) { sk_X509_pop_free(untrustedchain, X509_free); } return ret == 1 ? true : ret == 0 ? false : -1; } static bool openssl_x509_export_impl(const Variant& x509, BIO *bio_out, bool notext /* = true */) { auto ocert = Certificate::Get(x509); if (!ocert) { raise_warning("cannot get cert from parameter 1"); return false; } X509 *cert = ocert->m_cert; assertx(cert); assertx(bio_out); if (!notext) { X509_print(bio_out, cert); } return PEM_write_bio_X509(bio_out, cert); } bool HHVM_FUNCTION(openssl_x509_export_to_file, const Variant& x509, const String& outfilename, bool notext /* = true */) { BIO *bio_out = BIO_new_file((char*)outfilename.data(), "w"); if (bio_out == nullptr) { raise_warning("error opening file %s", outfilename.data()); return false; } bool ret = openssl_x509_export_impl(x509, bio_out, notext); BIO_free(bio_out); return ret; } bool HHVM_FUNCTION(openssl_x509_export, const Variant& x509, Variant& output, bool notext /* = true */) { BIO *bio_out = BIO_new(BIO_s_mem()); bool ret = openssl_x509_export_impl(x509, bio_out, notext); if (ret) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); output = String(bio_buf->data, bio_buf->length, CopyString); } BIO_free(bio_out); return ret; } /** * This is how the time string is formatted: * * snprintf(p, sizeof(p), "%02d%02d%02d%02d%02d%02dZ",ts->tm_year%100, * ts->tm_mon+1,ts->tm_mday,ts->tm_hour,ts->tm_min,ts->tm_sec); */ static time_t asn1_time_to_time_t(ASN1_UTCTIME *timestr) { auto const timestr_type = ASN1_STRING_type(timestr); if (timestr_type != V_ASN1_UTCTIME && timestr_type != V_ASN1_GENERALIZEDTIME) { raise_warning("illegal ASN1 data type for timestamp"); return (time_t)-1; } auto const timestr_len = (size_t)ASN1_STRING_length(timestr); // Binary safety if (timestr_len != strlen((char*)ASN1_STRING_data(timestr))) { raise_warning("illegal length in timestamp"); return (time_t)-1; } if (timestr_len < 13 && timestr_len != 11) { raise_warning("unable to parse time string %s correctly", timestr->data); return (time_t)-1; } if (timestr_type == V_ASN1_GENERALIZEDTIME && timestr_len < 15) { raise_warning("unable to parse time string %s correctly", timestr->data); return (time_t)-1; } char *strbuf = strdup((char*)timestr->data); struct tm thetime; memset(&thetime, 0, sizeof(thetime)); /* we work backwards so that we can use atoi more easily */ char *thestr = strbuf + ASN1_STRING_length(timestr) - 3; if (ASN1_STRING_length(timestr) == 11) { thetime.tm_sec = 0; } else { thetime.tm_sec = atoi(thestr); *thestr = '\0'; thestr -= 2; } thetime.tm_min = atoi(thestr); *thestr = '\0'; thestr -= 2; thetime.tm_hour = atoi(thestr); *thestr = '\0'; thestr -= 2; thetime.tm_mday = atoi(thestr); *thestr = '\0'; thestr -= 2; thetime.tm_mon = atoi(thestr)-1; *thestr = '\0'; if (ASN1_STRING_type(timestr) == V_ASN1_UTCTIME) { thestr -= 2; thetime.tm_year = atoi(thestr); if (thetime.tm_year < 68) { thetime.tm_year += 100; } } else if (ASN1_STRING_type(timestr) == V_ASN1_GENERALIZEDTIME) { thestr -= 4; thetime.tm_year = atoi(thestr) - 1900; } thetime.tm_isdst = -1; time_t ret = mktime(&thetime); long gmadjust = 0; #if HAVE_TM_GMTOFF gmadjust = thetime.tm_gmtoff; #elif defined(_MSC_VER) TIME_ZONE_INFORMATION inf; GetTimeZoneInformation(&inf); gmadjust = thetime.tm_isdst ? inf.DaylightBias : inf.StandardBias; #else /** * If correcting for daylight savings time, we set the adjustment to * the value of timezone - 3600 seconds. Otherwise, we need to overcorrect * and set the adjustment to the main timezone + 3600 seconds. */ gmadjust = -(thetime.tm_isdst ? (long)timezone - 3600 : (long)timezone); #endif /* no adjustment for UTC */ if (timezone) ret += gmadjust; free(strbuf); return ret; } /* Special handling of subjectAltName, see CVE-2013-4073 * Christian Heimes */ static int openssl_x509v3_subjectAltName(BIO *bio, X509_EXTENSION *extension) { GENERAL_NAMES *names; const X509V3_EXT_METHOD *method = nullptr; long i, length, num; const unsigned char *p; method = X509V3_EXT_get(extension); if (method == nullptr) { return -1; } const auto data = X509_EXTENSION_get_data(extension); p = data->data; length = data->length; if (method->it) { names = (GENERAL_NAMES*)(ASN1_item_d2i(nullptr, &p, length, ASN1_ITEM_ptr(method->it))); } else { names = (GENERAL_NAMES*)(method->d2i(nullptr, &p, length)); } if (names == nullptr) { return -1; } num = sk_GENERAL_NAME_num(names); for (i = 0; i < num; i++) { GENERAL_NAME *name; ASN1_STRING *as; name = sk_GENERAL_NAME_value(names, i); switch (name->type) { case GEN_EMAIL: BIO_puts(bio, "email:"); as = name->d.rfc822Name; BIO_write(bio, ASN1_STRING_data(as), ASN1_STRING_length(as)); break; case GEN_DNS: BIO_puts(bio, "DNS:"); as = name->d.dNSName; BIO_write(bio, ASN1_STRING_data(as), ASN1_STRING_length(as)); break; case GEN_URI: BIO_puts(bio, "URI:"); as = name->d.uniformResourceIdentifier; BIO_write(bio, ASN1_STRING_data(as), ASN1_STRING_length(as)); break; default: /* use builtin print for GEN_OTHERNAME, GEN_X400, * GEN_EDIPARTY, GEN_DIRNAME, GEN_IPADD and GEN_RID */ GENERAL_NAME_print(bio, name); } /* trailing ', ' except for last element */ if (i < (num - 1)) { BIO_puts(bio, ", "); } } sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free); return 0; } Variant HHVM_FUNCTION(openssl_x509_parse, const Variant& x509cert, bool shortnames /* = true */) { auto ocert = Certificate::Get(x509cert); if (!ocert) { return false; } X509 *cert = ocert->m_cert; assertx(cert); auto ret = Array::CreateDArray(); const auto sn = X509_get_subject_name(cert); if (sn) { ret.set(s_name, String(X509_NAME_oneline(sn, nullptr, 0), CopyString)); } add_assoc_name_entry(ret, "subject", sn, shortnames); /* hash as used in CA directories to lookup cert by subject name */ { char buf[32]; snprintf(buf, sizeof(buf), "%08lx", X509_subject_name_hash(cert)); ret.set(s_hash, String(buf, CopyString)); } add_assoc_name_entry(ret, "issuer", X509_get_issuer_name(cert), shortnames); ret.set(s_version, X509_get_version(cert)); ret.set(s_serialNumber, String (i2s_ASN1_INTEGER(nullptr, X509_get_serialNumber(cert)), AttachString)); // Adding Signature Algorithm BIO *bio_out = BIO_new(BIO_s_mem()); SCOPE_EXIT { BIO_free(bio_out); }; if (i2a_ASN1_OBJECT(bio_out, X509_get0_tbs_sigalg(cert)->algorithm) > 0) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); ret.set(s_signatureAlgorithm, String((char*)bio_buf->data, bio_buf->length, CopyString)); } ASN1_STRING *str = X509_get_notBefore(cert); ret.set(s_validFrom, String((char*)str->data, str->length, CopyString)); str = X509_get_notAfter(cert); ret.set(s_validTo, String((char*)str->data, str->length, CopyString)); ret.set(s_validFrom_time_t, asn1_time_to_time_t(X509_get_notBefore(cert))); ret.set(s_validTo_time_t, asn1_time_to_time_t(X509_get_notAfter(cert))); char *tmpstr = (char *)X509_alias_get0(cert, nullptr); if (tmpstr) { ret.set(s_alias, String(tmpstr, CopyString)); } /* NOTE: the purposes are added as integer keys - the keys match up to the X509_PURPOSE_SSL_XXX defines in x509v3.h */ { Array subitem; for (int i = 0; i < X509_PURPOSE_get_count(); i++) { X509_PURPOSE *purp = X509_PURPOSE_get0(i); int id = X509_PURPOSE_get_id(purp); char * pname = shortnames ? X509_PURPOSE_get0_sname(purp) : X509_PURPOSE_get0_name(purp); auto subsub = make_varray( (bool)X509_check_purpose(cert, id, 0), (bool)X509_check_purpose(cert, id, 1), String(pname, CopyString) ); subitem.set(id, std::move(subsub)); } ret.set(s_purposes, subitem); } { auto subitem = Array::CreateDArray(); for (int i = 0; i < X509_get_ext_count(cert); i++) { int nid; X509_EXTENSION *extension = X509_get_ext(cert, i); char *extname; char buf[256]; nid = OBJ_obj2nid(X509_EXTENSION_get_object(extension)); if (nid != NID_undef) { extname = (char*)OBJ_nid2sn(OBJ_obj2nid (X509_EXTENSION_get_object(extension))); } else { OBJ_obj2txt(buf, sizeof(buf)-1, X509_EXTENSION_get_object(extension), 1); extname = buf; } BIO *bio_out = BIO_new(BIO_s_mem()); if (nid == NID_subject_alt_name) { if (openssl_x509v3_subjectAltName(bio_out, extension) == 0) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); subitem.set(String(extname, CopyString), String((char*)bio_buf->data, bio_buf->length, CopyString)); } else { BIO_free(bio_out); return false; } } else if (X509V3_EXT_print(bio_out, extension, 0, 0)) { BUF_MEM *bio_buf; BIO_get_mem_ptr(bio_out, &bio_buf); subitem.set(String(extname, CopyString), String((char*)bio_buf->data, bio_buf->length, CopyString)); } else { str = X509_EXTENSION_get_data(extension); subitem.set(String(extname, CopyString), String((char*)str->data, str->length, CopyString)); } BIO_free(bio_out); } ret.set(s_extensions, subitem); } return ret; } Variant HHVM_FUNCTION(openssl_x509_read, const Variant& x509certdata) { auto ocert = Certificate::Get(x509certdata); if (!ocert) { raise_warning("supplied parameter cannot be coerced into " "an X509 certificate!"); return false; } return Variant(ocert); } Variant HHVM_FUNCTION(openssl_random_pseudo_bytes, int length, bool& crypto_strong) { if (length <= 0) { return false; } unsigned char *buffer = nullptr; String s = String(length, ReserveString); buffer = (unsigned char *)s.mutableData(); if (RAND_bytes(buffer, length) <= 0) { crypto_strong = false; return false; } else { crypto_strong = true; s.setSize(length); return s; } } Variant HHVM_FUNCTION(openssl_cipher_iv_length, const String& method) { if (method.empty()) { raise_warning("Unknown cipher algorithm"); return false; } const EVP_CIPHER *cipher_type = EVP_get_cipherbyname(method.c_str()); if (!cipher_type) { raise_warning("Unknown cipher algorithm"); return false; } return EVP_CIPHER_iv_length(cipher_type); } /* Cipher mode info */ struct php_openssl_cipher_mode { /* Whether this mode uses authenticated encryption. True, for example, with the GCM and CCM modes */ bool is_aead; /* Whether this mode is a 'single run aead', meaning that DecryptFinal doesn't get called. For example, CCM mode is a single run aead mode. */ bool is_single_run_aead; /* The OpenSSL flag to get the computed tag, if this mode is aead. */ int aead_get_tag_flag; /* The OpenSSL flag to set the computed tag, if this mode is aead. */ int aead_set_tag_flag; /* The OpenSSL flag to set the IV length, if this mode is aead */ int aead_ivlen_flag; }; // initialize a php_openssl_cipher_mode corresponding to an EVP_CIPHER. static php_openssl_cipher_mode php_openssl_load_cipher_mode( const EVP_CIPHER* cipher_type) { php_openssl_cipher_mode mode = {}; switch (EVP_CIPHER_mode(cipher_type)) { #ifdef EVP_CIPH_GCM_MODE case EVP_CIPH_GCM_MODE: mode.is_aead = true; mode.is_single_run_aead = false; mode.aead_get_tag_flag = EVP_CTRL_GCM_GET_TAG; mode.aead_set_tag_flag = EVP_CTRL_GCM_SET_TAG; mode.aead_ivlen_flag = EVP_CTRL_GCM_SET_IVLEN; break; #endif #ifdef EVP_CIPH_CCM_MODE case EVP_CIPH_CCM_MODE: mode.is_aead = true; mode.is_single_run_aead = true; mode.aead_get_tag_flag = EVP_CTRL_CCM_GET_TAG; mode.aead_set_tag_flag = EVP_CTRL_CCM_SET_TAG; mode.aead_ivlen_flag = EVP_CTRL_CCM_SET_IVLEN; break; #endif default: break; } return mode; } static bool php_openssl_validate_iv( String piv, int iv_required_len, String& out, EVP_CIPHER_CTX* cipher_ctx, const php_openssl_cipher_mode* mode) { if (cipher_ctx == nullptr || mode == nullptr) { return false; } /* Best case scenario, user behaved */ if (piv.size() == iv_required_len) { out = std::move(piv); return true; } if (mode->is_aead) { if (EVP_CIPHER_CTX_ctrl( cipher_ctx, mode->aead_ivlen_flag, piv.size(), nullptr) != 1) { raise_warning( "Setting of IV length for AEAD mode failed, the expected length is " "%d bytes", iv_required_len); return false; } out = std::move(piv); return true; } String s = String(iv_required_len, ReserveString); char* iv_new = s.mutableData(); memset(iv_new, 0, iv_required_len); if (piv.size() <= 0) { /* BC behavior */ s.setSize(iv_required_len); out = std::move(s); return true; } if (piv.size() < iv_required_len) { raise_warning("IV passed is only %ld bytes long, cipher " "expects an IV of precisely %d bytes, padding with \\0", piv.size(), iv_required_len); memcpy(iv_new, piv.data(), piv.size()); s.setSize(iv_required_len); out = std::move(s); return true; } raise_warning("IV passed is %ld bytes long which is longer than the %d " "expected by selected cipher, truncating", piv.size(), iv_required_len); memcpy(iv_new, piv.data(), iv_required_len); s.setSize(iv_required_len); out = std::move(s); return true; } namespace { Variant openssl_encrypt_impl(const String& data, const String& method, const String& password, int options, const String& iv, Variant* tag_out, const String& aad, int tag_length) { const EVP_CIPHER *cipher_type = EVP_get_cipherbyname(method.c_str()); if (!cipher_type) { raise_warning("Unknown cipher algorithm"); return false; } EVP_CIPHER_CTX* cipher_ctx = EVP_CIPHER_CTX_new(); if (!cipher_ctx) { raise_warning("Failed to create cipher context"); return false; } SCOPE_EXIT { EVP_CIPHER_CTX_free(cipher_ctx); }; php_openssl_cipher_mode mode = php_openssl_load_cipher_mode(cipher_type); if (mode.is_aead && !tag_out) { raise_warning("Must call openssl_encrypt_with_tag when using an AEAD cipher"); return false; } int keylen = EVP_CIPHER_key_length(cipher_type); String key = password; /* * older openssl libraries can assert if the passed in password length is * less than keylen */ if (keylen > password.size()) { String s = String(keylen, ReserveString); char *keybuf = s.mutableData(); memset(keybuf, 0, keylen); memcpy(keybuf, password.data(), password.size()); key = s.setSize(keylen); } int max_iv_len = EVP_CIPHER_iv_length(cipher_type); if (iv.size() <= 0 && max_iv_len > 0 && !mode.is_aead) { raise_warning("Using an empty Initialization Vector (iv) is potentially " "insecure and not recommended"); } int result_len = 0; int outlen = data.size() + EVP_CIPHER_block_size(cipher_type); String rv = String(outlen, ReserveString); unsigned char *outbuf = (unsigned char*)rv.mutableData(); EVP_EncryptInit_ex(cipher_ctx, cipher_type, nullptr, nullptr, nullptr); String new_iv; // we do this after EncryptInit because validate_iv changes cipher_ctx for // aead modes (must be initialized first). if (!php_openssl_validate_iv( std::move(iv), max_iv_len, new_iv, cipher_ctx, &mode)) { return false; } // set the tag length for CCM mode/other modes that require tag lengths to // be set. if (mode.is_single_run_aead && !EVP_CIPHER_CTX_ctrl( cipher_ctx, mode.aead_set_tag_flag, tag_length, nullptr)) { raise_warning("Setting tag length failed"); return false; } if (password.size() > keylen) { EVP_CIPHER_CTX_set_key_length(cipher_ctx, password.size()); } EVP_EncryptInit_ex( cipher_ctx, nullptr, nullptr, (unsigned char*)key.data(), (unsigned char*)new_iv.data()); if (options & k_OPENSSL_ZERO_PADDING) { EVP_CIPHER_CTX_set_padding(cipher_ctx, 0); } // for single run aeads like CCM, we need to provide the length of the // plaintext before providing AAD or ciphertext. if (mode.is_single_run_aead && !EVP_EncryptUpdate( cipher_ctx, nullptr, &result_len, nullptr, data.size())) { raise_warning("Setting of data length failed"); return false; } // set up aad: if (mode.is_aead && !EVP_EncryptUpdate( cipher_ctx, nullptr, &result_len, (unsigned char*)aad.data(), aad.size())) { raise_warning("Setting of additional application data failed"); return false; } // OpenSSL before 0.9.8i asserts with size < 0 if (data.size() >= 0) { EVP_EncryptUpdate(cipher_ctx, outbuf, &result_len, (unsigned char *)data.data(), data.size()); } outlen = result_len; if (EVP_EncryptFinal_ex( cipher_ctx, (unsigned char*)outbuf + result_len, &result_len)) { outlen += result_len; rv.setSize(outlen); // Get tag if possible if (mode.is_aead) { String tagrv = String(tag_length, ReserveString); if (EVP_CIPHER_CTX_ctrl( cipher_ctx, mode.aead_get_tag_flag, tag_length, tagrv.mutableData()) == 1) { tagrv.setSize(tag_length); assertx(tag_out); *tag_out = tagrv; } else { raise_warning("Retrieving authentication tag failed"); return false; } } else if (tag_out) { raise_warning( "The authenticated tag cannot be provided for cipher that does not" " support AEAD"); } // Return encrypted data if (options & k_OPENSSL_RAW_DATA) { return rv; } else { return StringUtil::Base64Encode(rv); } } return false; } } // anonymous namespace Variant HHVM_FUNCTION(openssl_encrypt, const String& data, const String& method, const String& password, int options /* = 0 */, const String& iv /* = null_string */, const String& aad /* = null_string */, int tag_length /* = 16 */) { return openssl_encrypt_impl(data, method, password, options, iv, nullptr, aad, tag_length); } Variant HHVM_FUNCTION(openssl_encrypt_with_tag, const String& data, const String& method, const String& password, int options, const String& iv, Variant& tag_out, const String& aad /* = null_string */, int tag_length /* = 16 */) { return openssl_encrypt_impl(data, method, password, options, iv, &tag_out, aad, tag_length); } Variant HHVM_FUNCTION(openssl_decrypt, const String& data, const String& method, const String& password, int options /* = 0 */, const String& iv /* = null_string */, const String& tag /* = null_string */, const String& aad /* = null_string */) { const EVP_CIPHER *cipher_type = EVP_get_cipherbyname(method.c_str()); if (!cipher_type) { raise_warning("Unknown cipher algorithm"); return false; } EVP_CIPHER_CTX* cipher_ctx = EVP_CIPHER_CTX_new(); if (!cipher_ctx) { raise_warning("Failed to create cipher context"); return false; } SCOPE_EXIT { EVP_CIPHER_CTX_free(cipher_ctx); }; php_openssl_cipher_mode mode = php_openssl_load_cipher_mode(cipher_type); String decoded_data = data; if (!(options & k_OPENSSL_RAW_DATA)) { decoded_data = StringUtil::Base64Decode(data); } int keylen = EVP_CIPHER_key_length(cipher_type); String key = password; /* * older openssl libraries can assert if the passed in password length is * less than keylen */ if (keylen > password.size()) { String s = String(keylen, ReserveString); char *keybuf = s.mutableData(); memset(keybuf, 0, keylen); memcpy(keybuf, password.data(), password.size()); key = s.setSize(keylen); } int result_len = 0; int outlen = decoded_data.size() + EVP_CIPHER_block_size(cipher_type); String rv = String(outlen, ReserveString); unsigned char *outbuf = (unsigned char*)rv.mutableData(); EVP_DecryptInit_ex(cipher_ctx, cipher_type, nullptr, nullptr, nullptr); String new_iv; // we do this after DecryptInit because validate_iv changes cipher_ctx for // aead modes (must be initialized first). if (!php_openssl_validate_iv( std::move(iv), EVP_CIPHER_iv_length(cipher_type), new_iv, cipher_ctx, &mode)) { return false; } // set the tag if required: if (tag.size() > 0) { if (!mode.is_aead) { raise_warning( "The tag is being ignored because the cipher method does not" " support AEAD"); } else if (!EVP_CIPHER_CTX_ctrl( cipher_ctx, mode.aead_set_tag_flag, tag.size(), (unsigned char*)tag.data())) { raise_warning("Setting tag for AEAD cipher decryption failed"); return false; } } else { if (mode.is_aead) { raise_warning("A tag should be provided when using AEAD mode"); return false; } } if (password.size() > keylen) { EVP_CIPHER_CTX_set_key_length(cipher_ctx, password.size()); } EVP_DecryptInit_ex( cipher_ctx, nullptr, nullptr, (unsigned char*)key.data(), (unsigned char*)new_iv.data()); if (options & k_OPENSSL_ZERO_PADDING) { EVP_CIPHER_CTX_set_padding(cipher_ctx, 0); } // for single run aeads like CCM, we need to provide the length of the // ciphertext before providing AAD or ciphertext. if (mode.is_single_run_aead && !EVP_DecryptUpdate( cipher_ctx, nullptr, &result_len, nullptr, decoded_data.size())) { raise_warning("Setting of data length failed"); return false; } // set up aad: if (mode.is_aead && !EVP_DecryptUpdate( cipher_ctx, nullptr, &result_len, (unsigned char*)aad.data(), aad.size())) { raise_warning("Setting of additional application data failed"); return false; } if (!EVP_DecryptUpdate( cipher_ctx, outbuf, &result_len, (unsigned char*)decoded_data.data(), decoded_data.size())) { return false; } outlen = result_len; // if is_single_run_aead is enabled, DecryptFinal shouldn't be called. // if something went wrong in this case, we would've caught it at // DecryptUpdate. if (mode.is_single_run_aead || EVP_DecryptFinal_ex( cipher_ctx, (unsigned char*)outbuf + result_len, &result_len)) { // don't want to do this if is_single_run_aead was enabled, since we didn't // make a call to EVP_DecryptFinal. if (!mode.is_single_run_aead) { outlen += result_len; } rv.setSize(outlen); return rv; } else { return false; } } Variant HHVM_FUNCTION(openssl_digest, const String& data, const String& method, bool raw_output /* = false */) { const EVP_MD *mdtype = EVP_get_digestbyname(method.c_str()); if (!mdtype) { raise_warning("Unknown signature algorithm"); return false; } int siglen = EVP_MD_size(mdtype); String rv = String(siglen, ReserveString); unsigned char *sigbuf = (unsigned char *)rv.mutableData(); EVP_MD_CTX *md_ctx = EVP_MD_CTX_new(); SCOPE_EXIT { EVP_MD_CTX_free(md_ctx); }; EVP_DigestInit(md_ctx, mdtype); EVP_DigestUpdate(md_ctx, (unsigned char *)data.data(), data.size()); if (EVP_DigestFinal(md_ctx, (unsigned char *)sigbuf, (unsigned int *)&siglen)) { if (raw_output) { rv.setSize(siglen); return rv; } else { char* digest_str = string_bin2hex((char*)sigbuf, siglen); return String(digest_str, AttachString); } } else { return false; } } static void openssl_add_method_or_alias(const OBJ_NAME *name, void *arg) { Array *ret = (Array*)arg; ret->append(String((char *)name->name, CopyString)); } static void openssl_add_method(const OBJ_NAME *name, void *arg) { if (name->alias == 0) { Array *ret = (Array*)arg; ret->append(String((char *)name->name, CopyString)); } } Array HHVM_FUNCTION(openssl_get_cipher_methods, bool aliases /* = false */) { Array ret = Array::CreateVArray(); OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH, aliases ? openssl_add_method_or_alias: openssl_add_method, &ret); return ret; } Variant HHVM_FUNCTION(openssl_get_curve_names) { #ifdef HAVE_EVP_PKEY_EC const size_t len = EC_get_builtin_curves(nullptr, 0); std::unique_ptr<EC_builtin_curve[]> curves(new EC_builtin_curve[len]); if (!EC_get_builtin_curves(curves.get(), len)) { return false; } VArrayInit ret(len); for (size_t i = 0; i < len; ++i) { auto const sname = OBJ_nid2sn(curves[i].nid); if (sname != nullptr) { ret.append(String(sname, CopyString)); } } return ret.toArray(); #else return false; #endif } Array HHVM_FUNCTION(openssl_get_md_methods, bool aliases /* = false */) { Array ret = Array::CreateVArray(); OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_MD_METH, aliases ? openssl_add_method_or_alias: openssl_add_method, &ret); return ret; } ///////////////////////////////////////////////////////////////////////////// const StaticString s_OPENSSL_VERSION_TEXT("OPENSSL_VERSION_TEXT"); struct opensslExtension final : Extension { opensslExtension() : Extension("openssl") {} void moduleInit() override { HHVM_RC_INT(OPENSSL_RAW_DATA, k_OPENSSL_RAW_DATA); HHVM_RC_INT(OPENSSL_ZERO_PADDING, k_OPENSSL_ZERO_PADDING); HHVM_RC_INT(OPENSSL_NO_PADDING, k_OPENSSL_NO_PADDING); HHVM_RC_INT(OPENSSL_PKCS1_OAEP_PADDING, k_OPENSSL_PKCS1_OAEP_PADDING); HHVM_RC_INT(OPENSSL_SSLV23_PADDING, k_OPENSSL_SSLV23_PADDING); HHVM_RC_INT(OPENSSL_PKCS1_PADDING, k_OPENSSL_PKCS1_PADDING); HHVM_RC_INT_SAME(OPENSSL_ALGO_SHA1); HHVM_RC_INT_SAME(OPENSSL_ALGO_MD5); HHVM_RC_INT_SAME(OPENSSL_ALGO_MD4); #ifdef HAVE_OPENSSL_MD2_H HHVM_RC_INT_SAME(OPENSSL_ALGO_MD2); #endif HHVM_RC_INT_SAME(OPENSSL_ALGO_DSS1); HHVM_RC_INT_SAME(OPENSSL_ALGO_SHA224); HHVM_RC_INT_SAME(OPENSSL_ALGO_SHA256); HHVM_RC_INT_SAME(OPENSSL_ALGO_SHA384); HHVM_RC_INT_SAME(OPENSSL_ALGO_SHA512); HHVM_RC_INT_SAME(OPENSSL_ALGO_RMD160); HHVM_RC_INT(OPENSSL_CIPHER_RC2_40, PHP_OPENSSL_CIPHER_RC2_40); HHVM_RC_INT(OPENSSL_CIPHER_RC2_128, PHP_OPENSSL_CIPHER_RC2_128); HHVM_RC_INT(OPENSSL_CIPHER_RC2_64, PHP_OPENSSL_CIPHER_RC2_64); HHVM_RC_INT(OPENSSL_CIPHER_DES, PHP_OPENSSL_CIPHER_DES); HHVM_RC_INT(OPENSSL_CIPHER_3DES, PHP_OPENSSL_CIPHER_3DES); HHVM_RC_INT_SAME(OPENSSL_KEYTYPE_RSA); HHVM_RC_INT_SAME(OPENSSL_KEYTYPE_DSA); HHVM_RC_INT_SAME(OPENSSL_KEYTYPE_DH); #ifdef HAVE_EVP_PKEY_EC HHVM_RC_INT_SAME(OPENSSL_KEYTYPE_EC); #endif HHVM_RC_INT_SAME(OPENSSL_VERSION_NUMBER); HHVM_RC_INT_SAME(PKCS7_TEXT); HHVM_RC_INT_SAME(PKCS7_NOCERTS); HHVM_RC_INT_SAME(PKCS7_NOSIGS); HHVM_RC_INT_SAME(PKCS7_NOCHAIN); HHVM_RC_INT_SAME(PKCS7_NOINTERN); HHVM_RC_INT_SAME(PKCS7_NOVERIFY); HHVM_RC_INT_SAME(PKCS7_DETACHED); HHVM_RC_INT_SAME(PKCS7_BINARY); HHVM_RC_INT_SAME(PKCS7_NOATTR); HHVM_RC_STR_SAME(OPENSSL_VERSION_TEXT); HHVM_RC_INT_SAME(X509_PURPOSE_SSL_CLIENT); HHVM_RC_INT_SAME(X509_PURPOSE_SSL_SERVER); HHVM_RC_INT_SAME(X509_PURPOSE_NS_SSL_SERVER); HHVM_RC_INT_SAME(X509_PURPOSE_SMIME_SIGN); HHVM_RC_INT_SAME(X509_PURPOSE_SMIME_ENCRYPT); HHVM_RC_INT_SAME(X509_PURPOSE_CRL_SIGN); #ifdef X509_PURPOSE_ANY HHVM_RC_INT_SAME(X509_PURPOSE_ANY); #endif HHVM_FE(openssl_csr_export_to_file); HHVM_FE(openssl_csr_export); HHVM_FE(openssl_csr_get_public_key); HHVM_FE(openssl_csr_get_subject); HHVM_FE(openssl_csr_new); HHVM_FE(openssl_csr_sign); HHVM_FE(openssl_error_string); HHVM_FE(openssl_open); HHVM_FE(openssl_pkcs12_export_to_file); HHVM_FE(openssl_pkcs12_export); HHVM_FE(openssl_pkcs12_read); HHVM_FE(openssl_pkcs7_decrypt); HHVM_FE(openssl_pkcs7_encrypt); HHVM_FE(openssl_pkcs7_sign); HHVM_FE(openssl_pkcs7_verify); HHVM_FE(openssl_pkey_export_to_file); HHVM_FE(openssl_pkey_export); HHVM_FE(openssl_pkey_get_details); HHVM_FE(openssl_pkey_get_private); HHVM_FE(openssl_pkey_get_public); HHVM_FE(openssl_pkey_new); HHVM_FE(openssl_private_decrypt); HHVM_FE(openssl_private_encrypt); HHVM_FE(openssl_public_decrypt); HHVM_FE(openssl_public_encrypt); HHVM_FE(openssl_seal); HHVM_FE(openssl_sign); HHVM_FE(openssl_verify); HHVM_FE(openssl_x509_check_private_key); HHVM_FE(openssl_x509_checkpurpose); HHVM_FE(openssl_x509_export_to_file); HHVM_FE(openssl_x509_export); HHVM_FE(openssl_x509_parse); HHVM_FE(openssl_x509_read); HHVM_FE(openssl_random_pseudo_bytes); HHVM_FE(openssl_cipher_iv_length); HHVM_FE(openssl_encrypt); HHVM_FE(openssl_encrypt_with_tag); HHVM_FE(openssl_decrypt); HHVM_FE(openssl_digest); HHVM_FE(openssl_get_cipher_methods); HHVM_FE(openssl_get_curve_names); HHVM_FE(openssl_get_md_methods); loadSystemlib(); } } s_openssl_extension; /////////////////////////////////////////////////////////////////////////////// }
null
199
CWE-787
CVE-2020-19491
/* cgif.c -- a merge of some GIF-decoding files from giflib by E.S.Raymond * by pts@fazekas.hu at Wed Feb 27 13:18:04 CET 2002 The GIFLIB distribution is Copyright (c) 1997 Eric S. Raymond Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*The creators of the GIF format require the following acknowledgement: The Graphics Interchange Format(c) is the Copyright property of CompuServe Incorporated. GIF(sm) is a Service Mark property of CompuServe Incorporated. */ #ifdef __GNUC__ #ifndef __clang__ #pragma implementation #endif #endif /**** pts: not an ANSI C function */ #undef EXTERN_C #ifdef __cplusplus #define EXTERN_C extern "C" #define CGIFFF CGIF:: #else #define EXTERN_C extern #define CGIFFF #endif #if OBJDEP # warning PROVIDES: cgif #endif #if 0 EXTERN_C FILE *fdopen (int fildes, const char *mode); /* GCC 3.0 SUXX */ #else #undef _POSIX_SOURCE #define _POSIX_SOURCE 1 #undef _POSIX_C_SOURCE #define _POSIX_C_SOURCE 2 #endif /* --- gifalloc.c */ /***************************************************************************** * "Gif-Lib" - Yet another gif library. * * * * Written by: Gershon Elber Ver 0.1, Jun. 1989 * * Extensively hacked by: Eric S. Raymond Ver 1.?, Sep 1992 * ****************************************************************************** * GIF construction tools * ****************************************************************************** * History: * * 15 Sep 92 - Version 1.0 by Eric Raymond. * *****************************************************************************/ // #undef __STRICT_ANSI__ /* for MINGW32 open() !! */ #include <stdio.h> #include "cgif.h" /**** pts ****/ #include <stdlib.h> /* malloc(), free(), realloc() */ #include <string.h> /* memset() */ //#include <unistd.h> #if USE_CGIF_FDOPEN #include <fcntl.h> /* open() */ #include <sys/types.h> #include <sys/stat.h> # if defined(__MINGW32__) || defined(__CYGWIN__) || defined(_MSC_VER) # undef __STRICT_ANSI__ # include <io.h> /*#define open _open*/ # endif #endif /* --- gif_err.c */ /***************************************************************************** * "Gif-Lib" - Yet another gif library. * * * * Written by: Gershon Elber IBM PC Ver 0.1, Jun. 1989 * ****************************************************************************** * Handle error reporting for the GIF library. * ****************************************************************************** * History: * * 17 Jun 89 - Version 1.0 by Gershon Elber. * *****************************************************************************/ /* #include <stdio.h> already */ /* #include "gif_lib.h" already */ /* --- dgif_lib.c */ /****************************************************************************** * "Gif-Lib" - Yet another gif library. * * * * Written by: Gershon Elber IBM PC Ver 1.1, Aug. 1990 * ******************************************************************************* * The kernel of the GIF Decoding process can be found here. * ******************************************************************************* * History: * * 16 Jun 89 - Version 1.0 by Gershon Elber. * * 3 Sep 90 - Version 1.1 by Gershon Elber (Support for Gif89, Unique names). * ******************************************************************************/ #ifdef __MSDOS__ #include <io.h> #include <alloc.h> #include <stdlib.h> #include <sys\stat.h> #else #include <sys/types.h> #include <sys/stat.h> #endif /* __MSDOS__ */ #include <fcntl.h> /* #include <stdio.h> already */ /* #include <string.h> already */ /* #include "gif_lib.h" already */ /* #include <stdlib.h> already */ /* malloc(), free() */ #include <assert.h> /* ---- */ static void *xmalloc(size_t size); static void *xrealloc(void *ptr, size_t size); /* --- gif_err.c */ /* #define PROGRAM_NAME "GIF_LIBRARY" */ int CGIFFF _GifError = 0; /***************************************************************************** * Return the last GIF error (0 if none) and reset the error. * *****************************************************************************/ int CGIFFF GifLastError(void) { int i = _GifError; _GifError = 0; return i; } /**** pts ****/ /** May return NULL. */ PTS_const char *CGIFFF GetGifError(void) { PTS_const char *Err; switch(_GifError) { #if 0 /**** pts ****/ case E_GIF_ERR_OPEN_FAILED: Err = "Failed to open given file"; break; case E_GIF_ERR_WRITE_FAILED: Err = "Failed to Write to given file"; break; case E_GIF_ERR_HAS_SCRN_DSCR: Err = "Screen Descriptor already been set"; break; case E_GIF_ERR_HAS_IMAG_DSCR: Err = "Image Descriptor is still active"; break; case E_GIF_ERR_NO_COLOR_MAP: Err = "Neither Global Nor Local color map"; break; case E_GIF_ERR_DATA_TOO_BIG: Err = "#Pixels bigger than Width * Height"; break; case E_GIF_ERR_NOT_ENOUGH_MEM: Err = "Fail to allocate required memory"; break; case E_GIF_ERR_DISK_IS_FULL: Err = "Write failed (disk full?)"; break; case E_GIF_ERR_CLOSE_FAILED: Err = "Failed to close given file"; break; case E_GIF_ERR_NOT_WRITEABLE: Err = "Given file was not opened for write"; break; #endif case D_GIF_ERR_OPEN_FAILED: Err = "Failed to open given file"; break; case D_GIF_ERR_READ_FAILED: Err = "Failed to Read from given file"; break; case D_GIF_ERR_NOT_GIF_FILE: Err = "Given file is NOT GIF file"; break; case D_GIF_ERR_NO_SCRN_DSCR: Err = "No Screen Descriptor detected"; break; case D_GIF_ERR_NO_IMAG_DSCR: Err = "No Image Descriptor detected"; break; case D_GIF_ERR_NO_COLOR_MAP: Err = "Neither Global Nor Local color map"; break; case D_GIF_ERR_WRONG_RECORD: Err = "Wrong record type detected"; break; case D_GIF_ERR_DATA_TOO_BIG: Err = "#Pixels bigger than Width * Height"; break; case D_GIF_ERR_NOT_ENOUGH_MEM: Err = "Fail to allocate required memory"; break; case D_GIF_ERR_CLOSE_FAILED: Err = "Failed to close given file"; break; case D_GIF_ERR_NOT_READABLE: Err = "Given file was not opened for read"; break; case D_GIF_ERR_IMAGE_DEFECT: Err = "Image is defective, decoding aborted"; break; case D_GIF_ERR_EOF_TOO_SOON: Err = "Image EOF detected, before image complete"; break; case D_GIF_ERR_EXT_TOO_SHORT: Err = "Extension data too short"; break; default: Err = NULL; break; } return Err; } /***************************************************************************** * Print the last GIF error to stderr. * *****************************************************************************/ void CGIFFF PrintGifError(void) { PTS_const char *Err=GetGifError(); if (Err != NULL) fprintf(stderr, "\nGIF-LIB error: %s.\n", Err); else fprintf(stderr, "\nGIF-LIB undefined error %d.\n", _GifError); } /* --- gifalloc.c */ #define MAXGIF(x, y) (((x) > (y)) ? (x) : (y)) /****************************************************************************** * Miscellaneous utility functions * ******************************************************************************/ static int BitSize(int n) /* return smallest bitfield size n will fit in */ { register int i; for (i = 1; i <= 8; i++) if ((1 << i) >= n) break; return(i); } /****************************************************************************** * Color map object functions * ******************************************************************************/ CGIFFF ColorMapObject *CGIFFF MakeMapObject(int ColorCount, GifColorType *ColorMap) /* * Allocate a color map of given size; initialize with contents of * ColorMap if that pointer is non-NULL. */ { ColorMapObject *Object; if (ColorCount != (1 << BitSize(ColorCount))) return((ColorMapObject *)NULL); Object = (ColorMapObject *)xmalloc(sizeof(ColorMapObject)); Object->Colors = (GifColorType *)xmalloc(ColorCount * sizeof(GifColorType)); memset(Object->Colors, '\0', ColorCount * sizeof(GifColorType)); Object->ColorCount = ColorCount; Object->BitsPerPixel = BitSize(ColorCount); if (ColorMap) memcpy((char *)Object->Colors, (char *)ColorMap, ColorCount * sizeof(GifColorType)); return(Object); } void CGIFFF FreeMapObject(CGIFFF ColorMapObject *Object) /* * Free a color map object */ { free(Object->Colors); free(Object); } #if 0 void DumpColorMap(ColorMapObject *Object, FILE *fp) { if (Object) { int i, j, Len = Object->ColorCount; for (i = 0; i < Len; i+=4) { for (j = 0; j < 4 && j < Len; j++) { fprintf(fp, "%3d: %02x %02x %02x ", i + j, Object->Colors[i + j].Red, Object->Colors[i + j].Green, Object->Colors[i + j].Blue); } fprintf(fp, "\n"); } } } #endif /* DEBUG */ #if 0 ColorMapObject *CGIFFF UnionColorMap( ColorMapObject *ColorIn1, ColorMapObject *ColorIn2, GifPixelType ColorTransIn2[]) /* * Compute the union of two given color maps and return it. If result can't * fit into 256 colors, NULL is returned, the allocated union otherwise. * ColorIn1 is copied as is to ColorUnion, while colors from ColorIn2 are * copied iff they didn't exist before. ColorTransIn2 maps the old * ColorIn2 into ColorUnion color map table. */ { int i, j, CrntSlot, RoundUpTo, NewBitSize; ColorMapObject *ColorUnion; /* * Allocate table which will hold the result for sure. */ ColorUnion = MakeMapObject(MAXGIF(ColorIn1->ColorCount,ColorIn2->ColorCount)*2,NULL); if (ColorUnion == NULL) return(NULL); /* Copy ColorIn1 to ColorUnionSize; */ for (i = 0; i < ColorIn1->ColorCount; i++) ColorUnion->Colors[i] = ColorIn1->Colors[i]; CrntSlot = ColorIn1->ColorCount; /* * Potentially obnoxious hack: * * Back CrntSlot down past all contiguous {0, 0, 0} slots at the end * of table 1. This is very useful if your display is limited to * 16 colors. */ while (ColorIn1->Colors[CrntSlot-1].Red == 0 && ColorIn1->Colors[CrntSlot-1].Green == 0 && ColorIn1->Colors[CrntSlot-1].Red == 0) CrntSlot--; /* Copy ColorIn2 to ColorUnionSize (use old colors if they exist): */ for (i = 0; i < ColorIn2->ColorCount && CrntSlot<=256; i++) { /* Let's see if this color already exists: */ for (j = 0; j < ColorIn1->ColorCount; j++) if (memcmp(&ColorIn1->Colors[j], &ColorIn2->Colors[i], sizeof(GifColorType)) == 0) break; if (j < ColorIn1->ColorCount) ColorTransIn2[i] = j; /* color exists in Color1 */ else { /* Color is new - copy it to a new slot: */ ColorUnion->Colors[CrntSlot] = ColorIn2->Colors[i]; ColorTransIn2[i] = CrntSlot++; } } if (CrntSlot > 256) { FreeMapObject(ColorUnion); return((ColorMapObject *)NULL); } NewBitSize = BitSize(CrntSlot); RoundUpTo = (1 << NewBitSize); if (RoundUpTo != ColorUnion->ColorCount) { register GifColorType *Map = ColorUnion->Colors; /* * Zero out slots up to next power of 2. * We know these slots exist because of the way ColorUnion's * start dimension was computed. */ for (j = CrntSlot; j < RoundUpTo; j++) Map[j].Red = Map[j].Green = Map[j].Blue = 0; /* perhaps we can shrink the map? */ if (RoundUpTo < ColorUnion->ColorCount) ColorUnion->Colors = (GifColorType *)xrealloc(Map, sizeof(GifColorType)*RoundUpTo); } ColorUnion->ColorCount = RoundUpTo; ColorUnion->BitsPerPixel = NewBitSize; return(ColorUnion); } void ApplyTranslation(SavedImage *Image, GifPixelType Translation[]) /* * Apply a given color translation to the raster bits of an image */ { register int i; register int RasterSize = Image->ImageDesc.Height * Image->ImageDesc.Width; for (i = 0; i < RasterSize; i++) Image->RasterBits[i] = Translation[Image->RasterBits[i]]; } #endif /****************************************************************************** * Extension record functions * ******************************************************************************/ #if 0 /**** pts ****/ void MakeExtension(SavedImage *New, int Function) { New->Function = Function; /* * Someday we might have to deal with multiple extensions. */ } #endif int CGIFFF AddExtensionBlock(CGIFFF SavedImage *New, int Len, CGIFFF GifByteType ExtData[]) { ExtensionBlock *ep; if (New->ExtensionBlocks == NULL) New->ExtensionBlocks = (ExtensionBlock *)xmalloc(sizeof(ExtensionBlock)); else New->ExtensionBlocks = (ExtensionBlock *)xrealloc(New->ExtensionBlocks, sizeof(ExtensionBlock) * (New->ExtensionBlockCount + 1)); if (New->ExtensionBlocks == NULL) return(GIF_ERROR); ep = &New->ExtensionBlocks[New->ExtensionBlockCount++]; ep->Bytes = (GifByteType *)xmalloc(ep->ByteCount = Len); if (ExtData) memcpy(ep->Bytes, ExtData, Len); return(GIF_OK); } void CGIFFF FreeExtension(CGIFFF SavedImage *Image) { ExtensionBlock *ep; for (ep = Image->ExtensionBlocks; ep < Image->ExtensionBlocks + Image->ExtensionBlockCount; ep++) (void) free((char *)ep->Bytes); free((char *)Image->ExtensionBlocks); Image->ExtensionBlocks = NULL; } /****************************************************************************** * Image block allocation functions * ******************************************************************************/ CGIFFF SavedImage *CGIFFF MakeSavedImage(CGIFFF GifFileType *GifFile, CGIFFF SavedImage *CopyFrom) /* * Append an image block to the SavedImages array */ { SavedImage *sp; if (GifFile->SavedImages == NULL) GifFile->SavedImages = (SavedImage *)xmalloc(sizeof(SavedImage)); else GifFile->SavedImages = (SavedImage *)xrealloc(GifFile->SavedImages, sizeof(SavedImage) * (GifFile->ImageCount+1)); { sp = &GifFile->SavedImages[GifFile->ImageCount++]; memset((char *)sp, '\0', sizeof(SavedImage)); if (CopyFrom) { memcpy((char *)sp, CopyFrom, sizeof(SavedImage)); /* * Make our own allocated copies of the heap fields in the * copied record. This guards against potential aliasing * problems. */ /* first, the local color map */ if (sp->ImageDesc.ColorMap) sp->ImageDesc.ColorMap = MakeMapObject(CopyFrom->ImageDesc.ColorMap->ColorCount, CopyFrom->ImageDesc.ColorMap->Colors); /* next, the raster */ sp->RasterBits = (GifPixelType *)xmalloc(sizeof(GifPixelType) * CopyFrom->ImageDesc.Height * CopyFrom->ImageDesc.Width); memcpy(sp->RasterBits, CopyFrom->RasterBits, sizeof(GifPixelType) * CopyFrom->ImageDesc.Height * CopyFrom->ImageDesc.Width); /* finally, the extension blocks */ if (sp->ExtensionBlocks) { sp->ExtensionBlocks = (ExtensionBlock*)xmalloc(sizeof(ExtensionBlock) * CopyFrom->ExtensionBlockCount); memcpy(sp->ExtensionBlocks, CopyFrom->ExtensionBlocks, sizeof(ExtensionBlock) * CopyFrom->ExtensionBlockCount); /* * For the moment, the actual blocks can take their * chances with free(). We'll fix this later. */ } } return(sp); } } void CGIFFF FreeSavedImages(CGIFFF GifFileType *GifFile) { SavedImage *sp; for (sp = GifFile->SavedImages; sp < GifFile->SavedImages + GifFile->ImageCount; sp++) { if (sp->ImageDesc.ColorMap) FreeMapObject(sp->ImageDesc.ColorMap); if (sp->RasterBits) free((char *)sp->RasterBits); if (sp->ExtensionBlocks) FreeExtension(sp); } free((char *) GifFile->SavedImages); } /* --- dgif_lib.c */ #define GIF_FILE_BUFFER_SIZE 16384 /* Files uses bigger buffers than usual. */ /* #define PROGRAM_NAME "GIFLIB" */ #define COMMENT_EXT_FUNC_CODE 0xfe /* Extension function code for comment. */ #define GIF_STAMP "GIFVER" /* First chars in file - GIF stamp. */ #define GIF_STAMP_LEN sizeof(GIF_STAMP) - 1 #define GIF_VERSION_POS 3 /* Version first character in stamp. */ #define LZ_MAX_CODE 4095 /* Biggest code possible in 12 bits. */ #define LZ_BITS 12 #define FILE_STATE_READ 0x01/* 1 write, 0 read - EGIF_LIB compatible.*/ #define FLUSH_OUTPUT 4096 /* Impossible code, to signal flush. */ #define FIRST_CODE 4097 /* Impossible code, to signal first. */ #define NO_SUCH_CODE 4098 /* Impossible code, to signal empty. */ #define IS_READABLE(Private) (!(Private->FileState & FILE_STATE_READ)) typedef struct GifFilePrivateType { int FileState, /*FileHandle,*/ /* Where all this data goes to! */ BitsPerPixel, /* Bits per pixel (Codes uses at list this + 1). */ ClearCode, /* The CLEAR LZ code. */ EOFCode, /* The EOF LZ code. */ RunningCode, /* The next code algorithm can generate. */ RunningBits,/* The number of bits required to represent RunningCode. */ MaxCode1, /* 1 bigger than max. possible code, in RunningBits bits. */ LastCode, /* The code before the current code. */ CrntCode, /* Current algorithm code. */ StackPtr, /* For character stack (see below). */ CrntShiftState; /* Number of bits in CrntShiftDWord. */ unsigned long CrntShiftDWord; /* For bytes decomposition into codes. */ unsigned long PixelCount; /* Number of pixels in image. */ FILE *File; /* File as stream. */ CGIFFF GifByteType Buf[256]; /* Compressed input is buffered here. */ CGIFFF GifByteType Stack[LZ_MAX_CODE]; /* Decoded pixels are stacked here. */ CGIFFF GifByteType Suffix[LZ_MAX_CODE+1]; /* So we can trace the codes. */ unsigned int Prefix[LZ_MAX_CODE+1]; } GifFilePrivateType; /* extern int _GifError; */ static int DGifGetWord(FILE *File, int *Word); static int DGifSetupDecompress(CGIFFF GifFileType *GifFile); static int DGifDecompressLine(CGIFFF GifFileType *GifFile, CGIFFF GifPixelType *Line, int LineLen); static int DGifGetPrefixChar(unsigned int *Prefix, int Code, int ClearCode); static int DGifDecompressInput(GifFilePrivateType *Private, int *Code); static int DGifBufferedInput(FILE *File, CGIFFF GifByteType *Buf, CGIFFF GifByteType *NextByte); /****************************************************************************** * Open a new gif file for read, given by its name. * * Returns GifFileType pointer dynamically allocated which serves as the gif * * info record. _GifError is cleared if succesfull. * ******************************************************************************/ CGIFFF GifFileType *CGIFFF DGifOpenFileName(const char *FileName) { #if 0 /**** pts ****/ CGIFFF GifFileType *CGIFFF DGifOpenFileName(const char *FileName) { int FileHandle; if ((FileHandle = open(FileName, O_RDONLY #ifdef __MSDOS__ | O_BINARY #endif /* __MSDOS__ */ )) == -1) { _GifError = D_GIF_ERR_OPEN_FAILED; return NULL; } return DGifOpenFileHandle(FileHandle); #else FILE *f; if (NULL==(f=fopen(FileName,"rb"))) { _GifError=D_GIF_ERR_OPEN_FAILED; return NULL; } return DGifOpenFILE(f); #endif } #if USE_CGIF_FDOPEN /****************************************************************************** * Update a new gif file, given its file handle. * * Returns GifFileType pointer dynamically allocated which serves as the gif * * info record. _GifError is cleared if succesfull. * ******************************************************************************/ CGIFFF GifFileType *CGIFFF DGifOpenFileHandle(int FileHandle) { FILE *f; #ifdef __MSDOS__ setmode(FileHandle, O_BINARY); /* Make sure it is in binary mode. */ f = fdopen(FileHandle, "rb"); /* Make it into a stream: */ setvbuf(f, NULL, _IOFBF, GIF_FILE_BUFFER_SIZE);/* And inc. stream buffer.*/ #else f = fdopen(FileHandle, "rb"); /* Make it into a stream: */ #endif /* __MSDOS__ */ return DGifOpenFILE(f); } #endif /**** pts ****/ CGIFFF GifFileType *CGIFFF DGifOpenFILE(void/*FILE*/ *f) { char Buf[GIF_STAMP_LEN+1]; GifFileType *GifFile; GifFilePrivateType *Private; GifFile = (GifFileType *) xmalloc(sizeof(GifFileType)); memset(GifFile, '\0', sizeof(GifFileType)); Private = (GifFilePrivateType *) xmalloc(sizeof(GifFilePrivateType)); GifFile->Private = (VoidPtr) Private; /* Private->FileHandle = FileHandle; */ Private->File = (FILE*)f; Private->FileState = 0; /* Make sure bit 0 = 0 (File open for read). */ /* Let's see if this is a GIF file: */ if (fread(Buf, 1, GIF_STAMP_LEN, Private->File) != GIF_STAMP_LEN) { _GifError = D_GIF_ERR_READ_FAILED; free((char *) Private); free((char *) GifFile); return NULL; } /* The GIF Version number is ignored at this time. Maybe we should do */ /* something more useful with it. */ Buf[GIF_STAMP_LEN] = 0; if (strncmp(GIF_STAMP, Buf, GIF_VERSION_POS) != 0) { _GifError = D_GIF_ERR_NOT_GIF_FILE; free((char *) Private); free((char *) GifFile); return NULL; } if (DGifGetScreenDesc(GifFile) == GIF_ERROR) { free((char *) Private); free((char *) GifFile); return NULL; } _GifError = 0; return GifFile; } /****************************************************************************** * This routine should be called before any other DGif calls. Note that * * this routine is called automatically from DGif file open routines. * ******************************************************************************/ int CGIFFF DGifGetScreenDesc(CGIFFF GifFileType *GifFile) { int i, BitsPerPixel; GifByteType Buf[3]; GifFilePrivateType *Private = (GifFilePrivateType *) GifFile->Private; if (!IS_READABLE(Private)) { /* This file was NOT open for reading: */ _GifError = D_GIF_ERR_NOT_READABLE; return GIF_ERROR; } /* Put the screen descriptor into the file: */ if (DGifGetWord(Private->File, &GifFile->SWidth) == GIF_ERROR || DGifGetWord(Private->File, &GifFile->SHeight) == GIF_ERROR) return GIF_ERROR; if (fread(Buf, 1, 3, Private->File) != 3) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } GifFile->SColorResolution = (((Buf[0] & 0x70) + 1) >> 4) + 1; BitsPerPixel = (Buf[0] & 0x07) + 1; GifFile->SBackGroundColor = Buf[1]; // fprintf(stderr, "colres=%d bpp=%d bgcol=%d\n", GifFile->SColorResolution, BitsPerPixel, GifFile->SBackGroundColor); if (Buf[0] & 0x80) { /* Do we have global color map? */ // fprintf(stderr, "have gcolormap\n"); GifFile->SColorMap = MakeMapObject(1 << BitsPerPixel, NULL); /* Get the global color map: */ for (i = 0; i < GifFile->SColorMap->ColorCount; i++) { if (fread(Buf, 1, 3, Private->File) != 3) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } GifFile->SColorMap->Colors[i].Red = Buf[0]; GifFile->SColorMap->Colors[i].Green = Buf[1]; GifFile->SColorMap->Colors[i].Blue = Buf[2]; } } return GIF_OK; } /****************************************************************************** * This routine should be called before any attemp to read an image. * ******************************************************************************/ int CGIFFF DGifGetRecordType(CGIFFF GifFileType *GifFile, CGIFFF GifRecordType *Type) { GifByteType Buf; GifFilePrivateType *Private = (GifFilePrivateType *) GifFile->Private; if (!IS_READABLE(Private)) { /* This file was NOT open for reading: */ _GifError = D_GIF_ERR_NOT_READABLE; return GIF_ERROR; } if (fread(&Buf, 1, 1, Private->File) != 1) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } // fprintf(stderr, "record %d at offset %ld\n", Buf&255, ftell(Private->File)); switch (Buf) { case ',': *Type = IMAGE_DESC_RECORD_TYPE; break; case '!': *Type = EXTENSION_RECORD_TYPE; break; case ';': *Type = TERMINATE_RECORD_TYPE; break; default: *Type = UNDEFINED_RECORD_TYPE; // fprintf(stderr, "wrong record %d at offset %ld\n", Buf&255, ftell(Private->File)); _GifError = D_GIF_ERR_WRONG_RECORD; return GIF_ERROR; } return GIF_OK; } /****************************************************************************** * This routine should be called before any attemp to read an image. * * Note it is assumed the Image desc. header (',') has been read. * ******************************************************************************/ int CGIFFF DGifGetImageDesc(CGIFFF GifFileType *GifFile) { int i, BitsPerPixel; GifByteType Buf[3]; GifImageDesc Image; GifFilePrivateType *Private = (GifFilePrivateType *) GifFile->Private; memset(&Image, 0, sizeof(Image)); if (!IS_READABLE(Private)) { /* This file was NOT open for reading: */ _GifError = D_GIF_ERR_NOT_READABLE; return GIF_ERROR; } if (DGifGetWord(Private->File, &Image.Left) == GIF_ERROR || DGifGetWord(Private->File, &Image.Top) == GIF_ERROR || DGifGetWord(Private->File, &Image.Width) == GIF_ERROR || DGifGetWord(Private->File, &Image.Height) == GIF_ERROR) return GIF_ERROR; if (fread(Buf, 1, 1, Private->File) != 1) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } BitsPerPixel = (Buf[0] & 0x07) + 1; Image.Interlace = (Buf[0] & 0x40); if (Buf[0] & 0x80) { /* Does this image have local color map? */ if (Image.ColorMap && GifFile->SavedImages == NULL) FreeMapObject(Image.ColorMap); Image.ColorMap = MakeMapObject(1 << BitsPerPixel, NULL); /* Get the image local color map: */ for (i = 0; i < Image.ColorMap->ColorCount; i++) { if (fread(Buf, 1, 3, Private->File) != 3) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } Image.ColorMap->Colors[i].Red = Buf[0]; Image.ColorMap->Colors[i].Green = Buf[1]; Image.ColorMap->Colors[i].Blue = Buf[2]; } } /**** pts ****/ if (NULL!=GifFile->SavedImages) { GifFile->SavedImages = (SavedImage *)xrealloc(GifFile->SavedImages, sizeof(SavedImage) * (GifFile->ImageCount + 1)); } else { assert(GifFile->ImageCount==0); GifFile->SavedImages = (SavedImage *)xmalloc(sizeof(SavedImage)); } { SavedImage *sp; sp = &GifFile->SavedImages[GifFile->ImageCount]; memcpy(&sp->ImageDesc, &Image, sizeof(GifImageDesc)); sp->RasterBits = (GifPixelType *)NULL; sp->ExtensionBlockCount = 0; sp->ExtensionBlocks = (ExtensionBlock *)NULL; sp->delay=0; sp->dispose=0; sp->iter=1; sp->transp=(-1); } GifFile->ImageCount++; Private->PixelCount = (long) Image.Width * (long) Image.Height; /* Reset decompress algorithm parameters. */ if (DGifSetupDecompress(GifFile)==GIF_ERROR) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } return GIF_OK; } /****************************************************************************** * Get one full scanned line (Line) of length LineLen from GIF file. * ******************************************************************************/ int CGIFFF DGifGetLine(CGIFFF GifFileType *GifFile, CGIFFF GifPixelType *Line, int LineLen) { GifByteType *Dummy; GifFilePrivateType *Private = (GifFilePrivateType *) GifFile->Private; if (!IS_READABLE(Private)) { /* This file was NOT open for reading: */ _GifError = D_GIF_ERR_NOT_READABLE; return GIF_ERROR; } /**** pts ****/ /* if (!LineLen) LineLen = GifFile->Image.Width; */ #if defined(__MSDOS__) || defined(__GNUC__) if ((Private->PixelCount -= LineLen) > 0xffff0000UL) { #else if ((Private->PixelCount -= LineLen) > 0xffff0000) { #endif /* __MSDOS__ */ _GifError = D_GIF_ERR_DATA_TOO_BIG; return GIF_ERROR; } if (DGifDecompressLine(GifFile, Line, LineLen) == GIF_OK) { if (Private->PixelCount == 0) { /* We probably would not be called any more, so lets clean */ /* everything before we return: need to flush out all rest of */ /* image until empty block (size 0) detected. We use GetCodeNext.*/ do if (DGifGetCodeNext(GifFile, &Dummy) == GIF_ERROR) return GIF_ERROR; while (Dummy != NULL); } return GIF_OK; } else return GIF_ERROR; } /****************************************************************************** * Put one pixel (Pixel) into GIF file. * ******************************************************************************/ int CGIFFF DGifGetPixel(CGIFFF GifFileType *GifFile, CGIFFF GifPixelType Pixel) { GifByteType *Dummy; GifFilePrivateType *Private = (GifFilePrivateType *) GifFile->Private; if (!IS_READABLE(Private)) { /* This file was NOT open for reading: */ _GifError = D_GIF_ERR_NOT_READABLE; return GIF_ERROR; } #if defined(__MSDOS__) || defined(__GNUC__) if (--Private->PixelCount > 0xffff0000UL) #else if (--Private->PixelCount > 0xffff0000) #endif /* __MSDOS__ */ { _GifError = D_GIF_ERR_DATA_TOO_BIG; return GIF_ERROR; } if (DGifDecompressLine(GifFile, &Pixel, 1) == GIF_OK) { if (Private->PixelCount == 0) { /* We probably would not be called any more, so lets clean */ /* everything before we return: need to flush out all rest of */ /* image until empty block (size 0) detected. We use GetCodeNext.*/ do if (DGifGetCodeNext(GifFile, &Dummy) == GIF_ERROR) return GIF_ERROR; while (Dummy != NULL); } return GIF_OK; } else return GIF_ERROR; } /****************************************************************************** * Get an extension block (see GIF manual) from gif file. This routine only * * returns the first data block, and DGifGetExtensionNext shouldbe called * * after this one until NULL extension is returned. * * The Extension should NOT be freed by the user (not dynamically allocated).* * Note it is assumed the Extension desc. header ('!') has been read. * ******************************************************************************/ int CGIFFF DGifGetExtension(CGIFFF GifFileType *GifFile, int *ExtCode, CGIFFF GifByteType **Extension) { GifByteType Buf; GifFilePrivateType *Private = (GifFilePrivateType *) GifFile->Private; if (!IS_READABLE(Private)) { /* This file was NOT open for reading: */ _GifError = D_GIF_ERR_NOT_READABLE; return GIF_ERROR; } if (fread(&Buf, 1, 1, Private->File) != 1) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } *ExtCode = Buf; return DGifGetExtensionNext(GifFile, Extension); } /****************************************************************************** * Get a following extension block (see GIF manual) from gif file. This * * routine sould be called until NULL Extension is returned. * * The Extension should NOT be freed by the user (not dynamically allocated).* ******************************************************************************/ int CGIFFF DGifGetExtensionNext(CGIFFF GifFileType *GifFile, CGIFFF GifByteType **Extension) { GifByteType Buf; GifFilePrivateType *Private = (GifFilePrivateType *) GifFile->Private; if (fread(&Buf, 1, 1, Private->File) != 1) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } if (Buf > 0) { *Extension = Private->Buf; /* Use private unused buffer. */ (*Extension)[0] = Buf; /* Pascal strings notation (pos. 0 is len.). */ if (fread(&((*Extension)[1]), 1, Buf, Private->File) != Buf) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } } else *Extension = NULL; return GIF_OK; } /****************************************************************************** * This routine should be called last, to close the GIF file. * ******************************************************************************/ int CGIFFF DGifCloseFile(CGIFFF GifFileType *GifFile) { GifFilePrivateType *Private; if (GifFile == NULL) return GIF_ERROR; Private = (GifFilePrivateType *) GifFile->Private; if (!IS_READABLE(Private)) { /* This file was NOT open for reading: */ _GifError = D_GIF_ERR_NOT_READABLE; return GIF_ERROR; } #if 0 /**** pts ****/ if (GifFile->Image.ColorMap) FreeMapObject(GifFile->Image.ColorMap); #endif if (GifFile->SColorMap) FreeMapObject(GifFile->SColorMap); if (Private) free((char *) Private); if (GifFile->SavedImages) FreeSavedImages(GifFile); free(GifFile); #if 0 /**** pts ****/ if (fclose(File) != 0) { _GifError = D_GIF_ERR_CLOSE_FAILED; return GIF_ERROR; } #endif return GIF_OK; } /****************************************************************************** * Get 2 bytes (word) from the given file: * ******************************************************************************/ static int DGifGetWord(FILE *File, int *Word) { unsigned char c[2]; if (fread(c, 1, 2, File) != 2) { CGIFFF _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } *Word = (((unsigned int) c[1]) << 8) + c[0]; return GIF_OK; } /****************************************************************************** * Get the image code in compressed form. his routine can be called if the * * information needed to be piped out as is. Obviously this is much faster * * than decoding and encoding again. This routine should be followed by calls * * to DGifGetCodeNext, until NULL block is returned. * * The block should NOT be freed by the user (not dynamically allocated). * ******************************************************************************/ int CGIFFF DGifGetCode(CGIFFF GifFileType *GifFile, int *CodeSize, CGIFFF GifByteType **CodeBlock) { GifFilePrivateType *Private = (GifFilePrivateType *) GifFile->Private; if (!IS_READABLE(Private)) { /* This file was NOT open for reading: */ _GifError = D_GIF_ERR_NOT_READABLE; return GIF_ERROR; } *CodeSize = Private->BitsPerPixel; return DGifGetCodeNext(GifFile, CodeBlock); } /****************************************************************************** * Continue to get the image code in compressed form. This routine should be * * called until NULL block is returned. * * The block should NOT be freed by the user (not dynamically allocated). * ******************************************************************************/ int CGIFFF DGifGetCodeNext(CGIFFF GifFileType *GifFile, CGIFFF GifByteType **CodeBlock) { GifByteType Buf; GifFilePrivateType *Private = (GifFilePrivateType *) GifFile->Private; if (fread(&Buf, 1, 1, Private->File) != 1) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } if (Buf > 0) { *CodeBlock = Private->Buf; /* Use private unused buffer. */ (*CodeBlock)[0] = Buf; /* Pascal strings notation (pos. 0 is len.). */ if (fread(&((*CodeBlock)[1]), 1, Buf, Private->File) != Buf) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } } else { *CodeBlock = NULL; Private->Buf[0] = 0; /* Make sure the buffer is empty! */ Private->PixelCount = 0; /* And local info. indicate image read. */ } return GIF_OK; } /****************************************************************************** * Setup the LZ decompression for this image: * ******************************************************************************/ static int DGifSetupDecompress(CGIFFF GifFileType *GifFile) { int i, BitsPerPixel; CGIFFF GifByteType CodeSize; unsigned int *Prefix; GifFilePrivateType *Private = (GifFilePrivateType *) GifFile->Private; if (fread(&CodeSize, 1, 1, Private->File) != 1) /* Read Code size from file. */ return GIF_ERROR; BitsPerPixel = CodeSize; Private->Buf[0] = 0; /* Input Buffer empty. */ Private->BitsPerPixel = BitsPerPixel; Private->ClearCode = (1 << BitsPerPixel); Private->EOFCode = Private->ClearCode + 1; Private->RunningCode = Private->EOFCode + 1; Private->RunningBits = BitsPerPixel + 1; /* Number of bits per code. */ Private->MaxCode1 = 1 << Private->RunningBits; /* Max. code + 1. */ Private->StackPtr = 0; /* No pixels on the pixel stack. */ Private->LastCode = NO_SUCH_CODE; Private->CrntShiftState = 0; /* No information in CrntShiftDWord. */ Private->CrntShiftDWord = 0; Prefix = Private->Prefix; for (i = 0; i <= LZ_MAX_CODE; i++) Prefix[i] = NO_SUCH_CODE; return GIF_OK; } /****************************************************************************** * The LZ decompression routine: * * This version decompress the given gif file into Line of length LineLen. * * This routine can be called few times (one per scan line, for example), in * * order the complete the whole image. * ******************************************************************************/ static int DGifDecompressLine(CGIFFF GifFileType *GifFile, CGIFFF GifPixelType *Line, int LineLen) { int i = 0, j, CrntCode, EOFCode, ClearCode, CrntPrefix, LastCode, StackPtr; CGIFFF GifByteType *Stack, *Suffix; unsigned int *Prefix; GifFilePrivateType *Private = (GifFilePrivateType *) GifFile->Private; StackPtr = Private->StackPtr; Prefix = Private->Prefix; Suffix = Private->Suffix; Stack = Private->Stack; EOFCode = Private->EOFCode; ClearCode = Private->ClearCode; LastCode = Private->LastCode; if (StackPtr != 0) { /* Let pop the stack off before continueing to read the gif file: */ while (StackPtr != 0 && i < LineLen) Line[i++] = Stack[--StackPtr]; } while (i < LineLen) { /* Decode LineLen items. */ if (DGifDecompressInput(Private, &CrntCode) == GIF_ERROR) return GIF_ERROR; /*fprintf(stderr,"CrntCode=0x%x\n",CrntCode);*/ if (CrntCode == EOFCode) { /* Note however that usually we will not be here as we will stop */ /* decoding as soon as we got all the pixel, or EOF code will */ /* not be read at all, and DGifGetLine/Pixel clean everything. */ if (i != LineLen - 1 || Private->PixelCount != 0) { CGIFFF _GifError = D_GIF_ERR_EOF_TOO_SOON; return GIF_ERROR; } i++; } else if (CrntCode == ClearCode) { /* We need to start over again: */ for (j = 0; j <= LZ_MAX_CODE; j++) Prefix[j] = NO_SUCH_CODE; Private->RunningCode = Private->EOFCode + 1; Private->RunningBits = Private->BitsPerPixel + 1; Private->MaxCode1 = 1 << Private->RunningBits; LastCode = Private->LastCode = NO_SUCH_CODE; } else { /* Its regular code - if in pixel range simply add it to output */ /* stream, otherwise trace to codes linked list until the prefix */ /* is in pixel range: */ if (CrntCode < ClearCode) { /* This is simple - its pixel scalar, so add it to output: */ Line[i++] = CrntCode; } else { /* Its a code to needed to be traced: trace the linked list */ /* until the prefix is a pixel, while pushing the suffix */ /* pixels on our stack. If we done, pop the stack in reverse */ /* (thats what stack is good for!) order to output. */ if (Prefix[CrntCode] == NO_SUCH_CODE) { /* Only allowed if CrntCode is exactly the running code: */ /* In that case CrntCode = XXXCode, CrntCode or the */ /* prefix code is last code and the suffix char is */ /* exactly the prefix of last code! */ if (CrntCode == Private->RunningCode - 2) { CrntPrefix = LastCode; Suffix[Private->RunningCode - 2] = Stack[StackPtr++] = DGifGetPrefixChar(Prefix, LastCode, ClearCode); } else { CGIFFF _GifError = D_GIF_ERR_IMAGE_DEFECT; return GIF_ERROR; } } else CrntPrefix = CrntCode; /* Now (if image is O.K.) we should not get an NO_SUCH_CODE */ /* During the trace. As we might loop forever, in case of */ /* defective image, we count the number of loops we trace */ /* and stop if we got LZ_MAX_CODE. obviously we can not */ /* loop more than that. */ j = 0; while (j++ <= LZ_MAX_CODE && CrntPrefix > ClearCode && CrntPrefix <= LZ_MAX_CODE) { Stack[StackPtr++] = Suffix[CrntPrefix]; CrntPrefix = Prefix[CrntPrefix]; } if (j >= LZ_MAX_CODE || CrntPrefix > LZ_MAX_CODE) { CGIFFF _GifError = D_GIF_ERR_IMAGE_DEFECT; return GIF_ERROR; } /* Push the last character on stack: */ Stack[StackPtr++] = CrntPrefix; /* Now lets pop all the stack into output: */ while (StackPtr != 0 && i < LineLen) Line[i++] = Stack[--StackPtr]; } if (LastCode != NO_SUCH_CODE) { Prefix[Private->RunningCode - 2] = LastCode; if (CrntCode == Private->RunningCode - 2) { /* Only allowed if CrntCode is exactly the running code: */ /* In that case CrntCode = XXXCode, CrntCode or the */ /* prefix code is last code and the suffix char is */ /* exactly the prefix of last code! */ Suffix[Private->RunningCode - 2] = DGifGetPrefixChar(Prefix, LastCode, ClearCode); } else { Suffix[Private->RunningCode - 2] = DGifGetPrefixChar(Prefix, CrntCode, ClearCode); } } LastCode = CrntCode; } } Private->LastCode = LastCode; Private->StackPtr = StackPtr; return GIF_OK; } /****************************************************************************** * Routine to trace the Prefixes linked list until we get a prefix which is * * not code, but a pixel value (less than ClearCode). Returns that pixel value.* * If image is defective, we might loop here forever, so we limit the loops to * * the maximum possible if image O.k. - LZ_MAX_CODE times. * ******************************************************************************/ static int DGifGetPrefixChar(unsigned int *Prefix, int Code, int ClearCode) { int i = 0; while (Code > ClearCode && i++ <= LZ_MAX_CODE) Code = Prefix[Code]; return Code; } /****************************************************************************** * Interface for accessing the LZ codes directly. Set Code to the real code * * (12bits), or to -1 if EOF code is returned. * ******************************************************************************/ int CGIFFF DGifGetLZCodes(CGIFFF GifFileType *GifFile, int *Code) { GifByteType *CodeBlock; GifFilePrivateType *Private = (GifFilePrivateType *) GifFile->Private; if (!IS_READABLE(Private)) { /* This file was NOT open for reading: */ _GifError = D_GIF_ERR_NOT_READABLE; return GIF_ERROR; } if (DGifDecompressInput(Private, Code) == GIF_ERROR) return GIF_ERROR; if (*Code == Private->EOFCode) { /* Skip rest of codes (hopefully only NULL terminating block): */ do if (DGifGetCodeNext(GifFile, &CodeBlock) == GIF_ERROR) return GIF_ERROR; while (CodeBlock != NULL); *Code = -1; } else if (*Code == Private->ClearCode) { /* We need to start over again: */ Private->RunningCode = Private->EOFCode + 1; Private->RunningBits = Private->BitsPerPixel + 1; Private->MaxCode1 = 1 << Private->RunningBits; } return GIF_OK; } /****************************************************************************** * The LZ decompression input routine: * * This routine is responsable for the decompression of the bit stream from * * 8 bits (bytes) packets, into the real codes. * * Returns GIF_OK if read succesfully. * ******************************************************************************/ static int DGifDecompressInput(GifFilePrivateType *Private, int *Code) { CGIFFF GifByteType NextByte; static unsigned int CodeMasks[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff, 0x01ff, 0x03ff, 0x07ff, 0x0fff }; /* The image can't contain more than LZ_BITS per code. */ if (Private->RunningBits > LZ_BITS) { return GIF_ERROR; } while (Private->CrntShiftState < Private->RunningBits) { /* Needs to get more bytes from input stream for next code: */ if (DGifBufferedInput(Private->File, Private->Buf, &NextByte) == GIF_ERROR) { return GIF_ERROR; } Private->CrntShiftDWord |= ((unsigned long) NextByte) << Private->CrntShiftState; Private->CrntShiftState += 8; } *Code = Private->CrntShiftDWord & CodeMasks[Private->RunningBits]; Private->CrntShiftDWord >>= Private->RunningBits; Private->CrntShiftState -= Private->RunningBits; /* If code cannt fit into RunningBits bits, must raise its size. Note */ /* however that codes above 4095 are used for special signaling. */ /* If we're using LZ_BITS bits already and we're at the max code, just */ /* keep using the table as it is, don't increment Private->RunningCode.*/ if (Private->RunningCode < LZ_MAX_CODE + 2 && ++Private->RunningCode > Private->MaxCode1 && Private->RunningBits < LZ_BITS) { Private->MaxCode1 <<= 1; Private->RunningBits++; } return GIF_OK; } /****************************************************************************** * This routines read one gif data block at a time and buffers it internally * * so that the decompression routine could access it. * * The routine returns the next byte from its internal buffer (or read next * * block in if buffer empty) and returns GIF_OK if succesful. * ******************************************************************************/ static int DGifBufferedInput(FILE *File, CGIFFF GifByteType *Buf, CGIFFF GifByteType *NextByte) { if (Buf[0] == 0) { /* Needs to read the next buffer - this one is empty: */ if (fread(Buf, 1, 1, File) != 1) { CGIFFF _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } if (fread(&Buf[1], 1, Buf[0], File) != Buf[0]) { CGIFFF _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } *NextByte = Buf[1]; Buf[1] = 2; /* We use now the second place as last char read! */ Buf[0]--; } else { *NextByte = Buf[Buf[1]++]; Buf[0]--; } return GIF_OK; } /****************************************************************************** * This routine reads an entire GIF into core, hanging all its state info off * * the GifFileType pointer. Call DGifOpenFileName() or DGifOpenFileHandle() * * first to initialize I/O. Its inverse is EGifSpew(). * ******************************************************************************/ int CGIFFF DGifSlurp(CGIFFF GifFileType *GifFile) { static unsigned InterlacedOffset[] = { 0, 4, 2, 1 }, /* The way Interlaced image should. */ InterlacedJumps[] = { 8, 8, 4, 2 }; /* be read - offsets and jumps... */ /**** pts: unused vars ****/ /* int i, j, Error, ImageSize; */ int ext_code; GifRecordType RecordType; /**** pts ****/ SavedImage *sp=0; /**** pts: avoid gcc warning */ /** Extension info of next SavedImage */ SavedImage ext; /** No-extension info */ SavedImage noext; GifByteType *ExtData; /**** pts ****/ memset(&noext, 0, sizeof(noext)); noext.delay=0; noext.dispose=0; noext.iter=1; noext.transp=(-1); noext.ExtensionBlocks=NULL; noext.ExtensionBlockCount=0; ext=noext; /**** pts ****/ GifFile->SavedImages=0; do { if (DGifGetRecordType(GifFile, &RecordType) == GIF_ERROR) return(GIF_ERROR); switch (RecordType) { case IMAGE_DESC_RECORD_TYPE: if (DGifGetImageDesc(GifFile) == GIF_ERROR) return(GIF_ERROR); /**** pts: DGifGetImageDesc has already allocated the mem ****/ sp = &GifFile->SavedImages[GifFile->ImageCount-1]; /**** pts: apply extensions to the image just read */ ext.RasterBits=sp->RasterBits; ext.ImageDesc=sp->ImageDesc; *sp=ext; ext=noext; /**** pts ****/ sp->RasterBits = (GifPixelType*) xmalloc((0L+sp->ImageDesc.Width) * sp->ImageDesc.Height * sizeof(GifPixelType)); if (sp->ImageDesc.Interlace) { unsigned i, j, Height=sp->ImageDesc.Height, Width=sp->ImageDesc.Width; /* Need to perform 4 passes on the images: */ for (i = 0; i < 4; i++) for (j = InterlacedOffset[i]; j < Height; j += InterlacedJumps[i]) if (DGifGetLine(GifFile, sp->RasterBits+Width*j, Width) != GIF_OK) return GIF_ERROR; } else { if (DGifGetLine(GifFile, sp->RasterBits, (0L+sp->ImageDesc.Width) * sp->ImageDesc.Height) == GIF_ERROR) return(GIF_ERROR); } break; case EXTENSION_RECORD_TYPE: if (DGifGetExtension(GifFile,&ext_code,&ExtData)==GIF_ERROR) return(GIF_ERROR); if (ExtData!=NULL) { #if 0 /**** pts ****/ ep = &ext.ExtensionBlocks[ext.ExtensionBlockCount++]; ep->ByteCount = ExtData[0]; ep->Bytes = (GifByteType *)xmalloc(ep->ByteCount * sizeof(GifByteType)); memcpy(ep->Bytes, ExtData, ep->ByteCount * sizeof(char)); #else /**** pts ****/ if (0xf9==(unsigned char)(ext_code)) { if (ExtData[0] < 4) { ext_too_short: _GifError = D_GIF_ERR_EXT_TOO_SHORT; return GIF_ERROR; } ext.dispose=ExtData[1]>>2; ext.delay=(ExtData[3] << 8) | ExtData[2]; if ((ExtData[1] & 0x01) == 1) { if (ExtData[0] < 5) goto ext_too_short; ext.transp=ExtData[4]; } } else if (0xff==(unsigned char)(ext_code)) { if (ExtData[0] < 4) goto ext_too_short; ext.iter=(ExtData[3] << 8) | ExtData[2]; } else { AddExtensionBlock(&ext, ExtData[0], ExtData+1); ext.ExtensionBlocks[ext.ExtensionBlockCount-1].code=ext_code; } #endif while (1) { if (DGifGetExtensionNext(GifFile, &ExtData) == GIF_ERROR) return(GIF_ERROR); #if 0 /**** pts ****/ ep = &ext.ExtensionBlocks[ext.ExtensionBlockCount++]; ep->ByteCount = ExtData[0]; ep->Bytes = (GifByteType *)xmalloc(ep->ByteCount * sizeof(GifByteType)); memcpy(ep->Bytes,ExtData,ep->ByteCount * sizeof(char)); #else if (ExtData==NULL) break; AddExtensionBlock(sp, ExtData[0], ExtData+1); #endif } } break; case TERMINATE_RECORD_TYPE: break; default: /* Should be trapped by DGifGetRecordType */ break; } } while (RecordType != TERMINATE_RECORD_TYPE); return(GIF_OK); } /* __END__ */
null
/* cgif.c -- a merge of some GIF-decoding files from giflib by E.S.Raymond * by pts@fazekas.hu at Wed Feb 27 13:18:04 CET 2002 The GIFLIB distribution is Copyright (c) 1997 Eric S. Raymond Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*The creators of the GIF format require the following acknowledgement: The Graphics Interchange Format(c) is the Copyright property of CompuServe Incorporated. GIF(sm) is a Service Mark property of CompuServe Incorporated. */ #ifdef __GNUC__ #ifndef __clang__ #pragma implementation #endif #endif /**** pts: not an ANSI C function */ #undef EXTERN_C #ifdef __cplusplus #define EXTERN_C extern "C" #define CGIFFF CGIF:: #else #define EXTERN_C extern #define CGIFFF #endif #if OBJDEP # warning PROVIDES: cgif #endif #if 0 EXTERN_C FILE *fdopen (int fildes, const char *mode); /* GCC 3.0 SUXX */ #else #undef _POSIX_SOURCE #define _POSIX_SOURCE 1 #undef _POSIX_C_SOURCE #define _POSIX_C_SOURCE 2 #endif /* --- gifalloc.c */ /***************************************************************************** * "Gif-Lib" - Yet another gif library. * * * * Written by: Gershon Elber Ver 0.1, Jun. 1989 * * Extensively hacked by: Eric S. Raymond Ver 1.?, Sep 1992 * ****************************************************************************** * GIF construction tools * ****************************************************************************** * History: * * 15 Sep 92 - Version 1.0 by Eric Raymond. * *****************************************************************************/ // #undef __STRICT_ANSI__ /* for MINGW32 open() !! */ #include <stdio.h> #include "cgif.h" /**** pts ****/ #include <stdlib.h> /* malloc(), free(), realloc() */ #include <string.h> /* memset() */ //#include <unistd.h> #if USE_CGIF_FDOPEN #include <fcntl.h> /* open() */ #include <sys/types.h> #include <sys/stat.h> # if defined(__MINGW32__) || defined(__CYGWIN__) || defined(_MSC_VER) # undef __STRICT_ANSI__ # include <io.h> /*#define open _open*/ # endif #endif /* --- gif_err.c */ /***************************************************************************** * "Gif-Lib" - Yet another gif library. * * * * Written by: Gershon Elber IBM PC Ver 0.1, Jun. 1989 * ****************************************************************************** * Handle error reporting for the GIF library. * ****************************************************************************** * History: * * 17 Jun 89 - Version 1.0 by Gershon Elber. * *****************************************************************************/ /* #include <stdio.h> already */ /* #include "gif_lib.h" already */ /* --- dgif_lib.c */ /****************************************************************************** * "Gif-Lib" - Yet another gif library. * * * * Written by: Gershon Elber IBM PC Ver 1.1, Aug. 1990 * ******************************************************************************* * The kernel of the GIF Decoding process can be found here. * ******************************************************************************* * History: * * 16 Jun 89 - Version 1.0 by Gershon Elber. * * 3 Sep 90 - Version 1.1 by Gershon Elber (Support for Gif89, Unique names). * ******************************************************************************/ #ifdef __MSDOS__ #include <io.h> #include <alloc.h> #include <stdlib.h> #include <sys\stat.h> #else #include <sys/types.h> #include <sys/stat.h> #endif /* __MSDOS__ */ #include <fcntl.h> /* #include <stdio.h> already */ /* #include <string.h> already */ /* #include "gif_lib.h" already */ /* #include <stdlib.h> already */ /* malloc(), free() */ #include <assert.h> /* ---- */ static void *xmalloc(size_t size); static void *xrealloc(void *ptr, size_t size); /* --- gif_err.c */ /* #define PROGRAM_NAME "GIF_LIBRARY" */ int CGIFFF _GifError = 0; /***************************************************************************** * Return the last GIF error (0 if none) and reset the error. * *****************************************************************************/ int CGIFFF GifLastError(void) { int i = _GifError; _GifError = 0; return i; } /**** pts ****/ /** May return NULL. */ PTS_const char *CGIFFF GetGifError(void) { PTS_const char *Err; switch(_GifError) { #if 0 /**** pts ****/ case E_GIF_ERR_OPEN_FAILED: Err = "Failed to open given file"; break; case E_GIF_ERR_WRITE_FAILED: Err = "Failed to Write to given file"; break; case E_GIF_ERR_HAS_SCRN_DSCR: Err = "Screen Descriptor already been set"; break; case E_GIF_ERR_HAS_IMAG_DSCR: Err = "Image Descriptor is still active"; break; case E_GIF_ERR_NO_COLOR_MAP: Err = "Neither Global Nor Local color map"; break; case E_GIF_ERR_DATA_TOO_BIG: Err = "#Pixels bigger than Width * Height"; break; case E_GIF_ERR_NOT_ENOUGH_MEM: Err = "Fail to allocate required memory"; break; case E_GIF_ERR_DISK_IS_FULL: Err = "Write failed (disk full?)"; break; case E_GIF_ERR_CLOSE_FAILED: Err = "Failed to close given file"; break; case E_GIF_ERR_NOT_WRITEABLE: Err = "Given file was not opened for write"; break; #endif case D_GIF_ERR_OPEN_FAILED: Err = "Failed to open given file"; break; case D_GIF_ERR_READ_FAILED: Err = "Failed to Read from given file"; break; case D_GIF_ERR_NOT_GIF_FILE: Err = "Given file is NOT GIF file"; break; case D_GIF_ERR_NO_SCRN_DSCR: Err = "No Screen Descriptor detected"; break; case D_GIF_ERR_NO_IMAG_DSCR: Err = "No Image Descriptor detected"; break; case D_GIF_ERR_NO_COLOR_MAP: Err = "Neither Global Nor Local color map"; break; case D_GIF_ERR_WRONG_RECORD: Err = "Wrong record type detected"; break; case D_GIF_ERR_DATA_TOO_BIG: Err = "#Pixels bigger than Width * Height"; break; case D_GIF_ERR_NOT_ENOUGH_MEM: Err = "Fail to allocate required memory"; break; case D_GIF_ERR_CLOSE_FAILED: Err = "Failed to close given file"; break; case D_GIF_ERR_NOT_READABLE: Err = "Given file was not opened for read"; break; case D_GIF_ERR_IMAGE_DEFECT: Err = "Image is defective, decoding aborted"; break; case D_GIF_ERR_EOF_TOO_SOON: Err = "Image EOF detected, before image complete"; break; case D_GIF_ERR_EXT_TOO_SHORT: Err = "Extension data too short"; break; default: Err = NULL; break; } return Err; } /***************************************************************************** * Print the last GIF error to stderr. * *****************************************************************************/ void CGIFFF PrintGifError(void) { PTS_const char *Err=GetGifError(); if (Err != NULL) fprintf(stderr, "\nGIF-LIB error: %s.\n", Err); else fprintf(stderr, "\nGIF-LIB undefined error %d.\n", _GifError); } /* --- gifalloc.c */ #define MAXGIF(x, y) (((x) > (y)) ? (x) : (y)) /****************************************************************************** * Miscellaneous utility functions * ******************************************************************************/ static int BitSize(int n) /* return smallest bitfield size n will fit in */ { register int i; for (i = 1; i <= 8; i++) if ((1 << i) >= n) break; return(i); } /****************************************************************************** * Color map object functions * ******************************************************************************/ CGIFFF ColorMapObject *CGIFFF MakeMapObject(int ColorCount, GifColorType *ColorMap) /* * Allocate a color map of given size; initialize with contents of * ColorMap if that pointer is non-NULL. */ { ColorMapObject *Object; if (ColorCount != (1 << BitSize(ColorCount))) return((ColorMapObject *)NULL); Object = (ColorMapObject *)xmalloc(sizeof(ColorMapObject)); Object->Colors = (GifColorType *)xmalloc(ColorCount * sizeof(GifColorType)); memset(Object->Colors, '\0', ColorCount * sizeof(GifColorType)); Object->ColorCount = ColorCount; Object->BitsPerPixel = BitSize(ColorCount); if (ColorMap) memcpy((char *)Object->Colors, (char *)ColorMap, ColorCount * sizeof(GifColorType)); return(Object); } void CGIFFF FreeMapObject(CGIFFF ColorMapObject *Object) /* * Free a color map object */ { free(Object->Colors); free(Object); } #if 0 void DumpColorMap(ColorMapObject *Object, FILE *fp) { if (Object) { int i, j, Len = Object->ColorCount; for (i = 0; i < Len; i+=4) { for (j = 0; j < 4 && j < Len; j++) { fprintf(fp, "%3d: %02x %02x %02x ", i + j, Object->Colors[i + j].Red, Object->Colors[i + j].Green, Object->Colors[i + j].Blue); } fprintf(fp, "\n"); } } } #endif /* DEBUG */ #if 0 ColorMapObject *CGIFFF UnionColorMap( ColorMapObject *ColorIn1, ColorMapObject *ColorIn2, GifPixelType ColorTransIn2[]) /* * Compute the union of two given color maps and return it. If result can't * fit into 256 colors, NULL is returned, the allocated union otherwise. * ColorIn1 is copied as is to ColorUnion, while colors from ColorIn2 are * copied iff they didn't exist before. ColorTransIn2 maps the old * ColorIn2 into ColorUnion color map table. */ { int i, j, CrntSlot, RoundUpTo, NewBitSize; ColorMapObject *ColorUnion; /* * Allocate table which will hold the result for sure. */ ColorUnion = MakeMapObject(MAXGIF(ColorIn1->ColorCount,ColorIn2->ColorCount)*2,NULL); if (ColorUnion == NULL) return(NULL); /* Copy ColorIn1 to ColorUnionSize; */ for (i = 0; i < ColorIn1->ColorCount; i++) ColorUnion->Colors[i] = ColorIn1->Colors[i]; CrntSlot = ColorIn1->ColorCount; /* * Potentially obnoxious hack: * * Back CrntSlot down past all contiguous {0, 0, 0} slots at the end * of table 1. This is very useful if your display is limited to * 16 colors. */ while (ColorIn1->Colors[CrntSlot-1].Red == 0 && ColorIn1->Colors[CrntSlot-1].Green == 0 && ColorIn1->Colors[CrntSlot-1].Red == 0) CrntSlot--; /* Copy ColorIn2 to ColorUnionSize (use old colors if they exist): */ for (i = 0; i < ColorIn2->ColorCount && CrntSlot<=256; i++) { /* Let's see if this color already exists: */ for (j = 0; j < ColorIn1->ColorCount; j++) if (memcmp(&ColorIn1->Colors[j], &ColorIn2->Colors[i], sizeof(GifColorType)) == 0) break; if (j < ColorIn1->ColorCount) ColorTransIn2[i] = j; /* color exists in Color1 */ else { /* Color is new - copy it to a new slot: */ ColorUnion->Colors[CrntSlot] = ColorIn2->Colors[i]; ColorTransIn2[i] = CrntSlot++; } } if (CrntSlot > 256) { FreeMapObject(ColorUnion); return((ColorMapObject *)NULL); } NewBitSize = BitSize(CrntSlot); RoundUpTo = (1 << NewBitSize); if (RoundUpTo != ColorUnion->ColorCount) { register GifColorType *Map = ColorUnion->Colors; /* * Zero out slots up to next power of 2. * We know these slots exist because of the way ColorUnion's * start dimension was computed. */ for (j = CrntSlot; j < RoundUpTo; j++) Map[j].Red = Map[j].Green = Map[j].Blue = 0; /* perhaps we can shrink the map? */ if (RoundUpTo < ColorUnion->ColorCount) ColorUnion->Colors = (GifColorType *)xrealloc(Map, sizeof(GifColorType)*RoundUpTo); } ColorUnion->ColorCount = RoundUpTo; ColorUnion->BitsPerPixel = NewBitSize; return(ColorUnion); } void ApplyTranslation(SavedImage *Image, GifPixelType Translation[]) /* * Apply a given color translation to the raster bits of an image */ { register int i; register int RasterSize = Image->ImageDesc.Height * Image->ImageDesc.Width; for (i = 0; i < RasterSize; i++) Image->RasterBits[i] = Translation[Image->RasterBits[i]]; } #endif /****************************************************************************** * Extension record functions * ******************************************************************************/ #if 0 /**** pts ****/ void MakeExtension(SavedImage *New, int Function) { New->Function = Function; /* * Someday we might have to deal with multiple extensions. */ } #endif int CGIFFF AddExtensionBlock(CGIFFF SavedImage *New, int Len, CGIFFF GifByteType ExtData[]) { ExtensionBlock *ep; if (New->ExtensionBlocks == NULL) New->ExtensionBlocks = (ExtensionBlock *)xmalloc(sizeof(ExtensionBlock)); else New->ExtensionBlocks = (ExtensionBlock *)xrealloc(New->ExtensionBlocks, sizeof(ExtensionBlock) * (New->ExtensionBlockCount + 1)); if (New->ExtensionBlocks == NULL) return(GIF_ERROR); ep = &New->ExtensionBlocks[New->ExtensionBlockCount++]; ep->Bytes = (GifByteType *)xmalloc(ep->ByteCount = Len); if (ExtData) memcpy(ep->Bytes, ExtData, Len); return(GIF_OK); } void CGIFFF FreeExtension(CGIFFF SavedImage *Image) { ExtensionBlock *ep; for (ep = Image->ExtensionBlocks; ep < Image->ExtensionBlocks + Image->ExtensionBlockCount; ep++) (void) free((char *)ep->Bytes); free((char *)Image->ExtensionBlocks); Image->ExtensionBlocks = NULL; } /****************************************************************************** * Image block allocation functions * ******************************************************************************/ CGIFFF SavedImage *CGIFFF MakeSavedImage(CGIFFF GifFileType *GifFile, CGIFFF SavedImage *CopyFrom) /* * Append an image block to the SavedImages array */ { SavedImage *sp; if (GifFile->SavedImages == NULL) GifFile->SavedImages = (SavedImage *)xmalloc(sizeof(SavedImage)); else GifFile->SavedImages = (SavedImage *)xrealloc(GifFile->SavedImages, sizeof(SavedImage) * (GifFile->ImageCount+1)); { sp = &GifFile->SavedImages[GifFile->ImageCount++]; memset((char *)sp, '\0', sizeof(SavedImage)); if (CopyFrom) { memcpy((char *)sp, CopyFrom, sizeof(SavedImage)); /* * Make our own allocated copies of the heap fields in the * copied record. This guards against potential aliasing * problems. */ /* first, the local color map */ if (sp->ImageDesc.ColorMap) sp->ImageDesc.ColorMap = MakeMapObject(CopyFrom->ImageDesc.ColorMap->ColorCount, CopyFrom->ImageDesc.ColorMap->Colors); /* next, the raster */ sp->RasterBits = (GifPixelType *)xmalloc(sizeof(GifPixelType) * CopyFrom->ImageDesc.Height * CopyFrom->ImageDesc.Width); memcpy(sp->RasterBits, CopyFrom->RasterBits, sizeof(GifPixelType) * CopyFrom->ImageDesc.Height * CopyFrom->ImageDesc.Width); /* finally, the extension blocks */ if (sp->ExtensionBlocks) { sp->ExtensionBlocks = (ExtensionBlock*)xmalloc(sizeof(ExtensionBlock) * CopyFrom->ExtensionBlockCount); memcpy(sp->ExtensionBlocks, CopyFrom->ExtensionBlocks, sizeof(ExtensionBlock) * CopyFrom->ExtensionBlockCount); /* * For the moment, the actual blocks can take their * chances with free(). We'll fix this later. */ } } return(sp); } } void CGIFFF FreeSavedImages(CGIFFF GifFileType *GifFile) { SavedImage *sp; for (sp = GifFile->SavedImages; sp < GifFile->SavedImages + GifFile->ImageCount; sp++) { if (sp->ImageDesc.ColorMap) FreeMapObject(sp->ImageDesc.ColorMap); if (sp->RasterBits) free((char *)sp->RasterBits); if (sp->ExtensionBlocks) FreeExtension(sp); } free((char *) GifFile->SavedImages); } /* --- dgif_lib.c */ #define GIF_FILE_BUFFER_SIZE 16384 /* Files uses bigger buffers than usual. */ /* #define PROGRAM_NAME "GIFLIB" */ #define COMMENT_EXT_FUNC_CODE 0xfe /* Extension function code for comment. */ #define GIF_STAMP "GIFVER" /* First chars in file - GIF stamp. */ #define GIF_STAMP_LEN sizeof(GIF_STAMP) - 1 #define GIF_VERSION_POS 3 /* Version first character in stamp. */ #define LZ_MAX_CODE 4095 /* Biggest code possible in 12 bits. */ #define LZ_BITS 12 #define FILE_STATE_READ 0x01/* 1 write, 0 read - EGIF_LIB compatible.*/ #define FLUSH_OUTPUT 4096 /* Impossible code, to signal flush. */ #define FIRST_CODE 4097 /* Impossible code, to signal first. */ #define NO_SUCH_CODE 4098 /* Impossible code, to signal empty. */ #define IS_READABLE(Private) (!(Private->FileState & FILE_STATE_READ)) typedef struct GifFilePrivateType { int FileState, /*FileHandle,*/ /* Where all this data goes to! */ BitsPerPixel, /* Bits per pixel (Codes uses at list this + 1). */ ClearCode, /* The CLEAR LZ code. */ EOFCode, /* The EOF LZ code. */ RunningCode, /* The next code algorithm can generate. */ RunningBits,/* The number of bits required to represent RunningCode. */ MaxCode1, /* 1 bigger than max. possible code, in RunningBits bits. */ LastCode, /* The code before the current code. */ CrntCode, /* Current algorithm code. */ StackPtr, /* For character stack (see below). */ CrntShiftState; /* Number of bits in CrntShiftDWord. */ unsigned long CrntShiftDWord; /* For bytes decomposition into codes. */ unsigned long PixelCount; /* Number of pixels in image. */ FILE *File; /* File as stream. */ CGIFFF GifByteType Buf[256]; /* Compressed input is buffered here. */ CGIFFF GifByteType Stack[LZ_MAX_CODE]; /* Decoded pixels are stacked here. */ CGIFFF GifByteType Suffix[LZ_MAX_CODE+1]; /* So we can trace the codes. */ unsigned int Prefix[LZ_MAX_CODE+1]; } GifFilePrivateType; /* extern int _GifError; */ static int DGifGetWord(FILE *File, int *Word); static int DGifSetupDecompress(CGIFFF GifFileType *GifFile); static int DGifDecompressLine(CGIFFF GifFileType *GifFile, CGIFFF GifPixelType *Line, int LineLen); static int DGifGetPrefixChar(unsigned int *Prefix, int Code, int ClearCode); static int DGifDecompressInput(GifFilePrivateType *Private, int *Code); static int DGifBufferedInput(FILE *File, CGIFFF GifByteType *Buf, CGIFFF GifByteType *NextByte); /****************************************************************************** * Open a new gif file for read, given by its name. * * Returns GifFileType pointer dynamically allocated which serves as the gif * * info record. _GifError is cleared if succesfull. * ******************************************************************************/ CGIFFF GifFileType *CGIFFF DGifOpenFileName(const char *FileName) { #if 0 /**** pts ****/ CGIFFF GifFileType *CGIFFF DGifOpenFileName(const char *FileName) { int FileHandle; if ((FileHandle = open(FileName, O_RDONLY #ifdef __MSDOS__ | O_BINARY #endif /* __MSDOS__ */ )) == -1) { _GifError = D_GIF_ERR_OPEN_FAILED; return NULL; } return DGifOpenFileHandle(FileHandle); #else FILE *f; if (NULL==(f=fopen(FileName,"rb"))) { _GifError=D_GIF_ERR_OPEN_FAILED; return NULL; } return DGifOpenFILE(f); #endif } #if USE_CGIF_FDOPEN /****************************************************************************** * Update a new gif file, given its file handle. * * Returns GifFileType pointer dynamically allocated which serves as the gif * * info record. _GifError is cleared if succesfull. * ******************************************************************************/ CGIFFF GifFileType *CGIFFF DGifOpenFileHandle(int FileHandle) { FILE *f; #ifdef __MSDOS__ setmode(FileHandle, O_BINARY); /* Make sure it is in binary mode. */ f = fdopen(FileHandle, "rb"); /* Make it into a stream: */ setvbuf(f, NULL, _IOFBF, GIF_FILE_BUFFER_SIZE);/* And inc. stream buffer.*/ #else f = fdopen(FileHandle, "rb"); /* Make it into a stream: */ #endif /* __MSDOS__ */ return DGifOpenFILE(f); } #endif /**** pts ****/ CGIFFF GifFileType *CGIFFF DGifOpenFILE(void/*FILE*/ *f) { char Buf[GIF_STAMP_LEN+1]; GifFileType *GifFile; GifFilePrivateType *Private; GifFile = (GifFileType *) xmalloc(sizeof(GifFileType)); memset(GifFile, '\0', sizeof(GifFileType)); Private = (GifFilePrivateType *) xmalloc(sizeof(GifFilePrivateType)); GifFile->Private = (VoidPtr) Private; /* Private->FileHandle = FileHandle; */ Private->File = (FILE*)f; Private->FileState = 0; /* Make sure bit 0 = 0 (File open for read). */ /* Let's see if this is a GIF file: */ if (fread(Buf, 1, GIF_STAMP_LEN, Private->File) != GIF_STAMP_LEN) { _GifError = D_GIF_ERR_READ_FAILED; free((char *) Private); free((char *) GifFile); return NULL; } /* The GIF Version number is ignored at this time. Maybe we should do */ /* something more useful with it. */ Buf[GIF_STAMP_LEN] = 0; if (strncmp(GIF_STAMP, Buf, GIF_VERSION_POS) != 0) { _GifError = D_GIF_ERR_NOT_GIF_FILE; free((char *) Private); free((char *) GifFile); return NULL; } if (DGifGetScreenDesc(GifFile) == GIF_ERROR) { free((char *) Private); free((char *) GifFile); return NULL; } _GifError = 0; return GifFile; } /****************************************************************************** * This routine should be called before any other DGif calls. Note that * * this routine is called automatically from DGif file open routines. * ******************************************************************************/ int CGIFFF DGifGetScreenDesc(CGIFFF GifFileType *GifFile) { int i, BitsPerPixel; GifByteType Buf[3]; GifFilePrivateType *Private = (GifFilePrivateType *) GifFile->Private; if (!IS_READABLE(Private)) { /* This file was NOT open for reading: */ _GifError = D_GIF_ERR_NOT_READABLE; return GIF_ERROR; } /* Put the screen descriptor into the file: */ if (DGifGetWord(Private->File, &GifFile->SWidth) == GIF_ERROR || DGifGetWord(Private->File, &GifFile->SHeight) == GIF_ERROR) return GIF_ERROR; if (fread(Buf, 1, 3, Private->File) != 3) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } GifFile->SColorResolution = (((Buf[0] & 0x70) + 1) >> 4) + 1; BitsPerPixel = (Buf[0] & 0x07) + 1; GifFile->SBackGroundColor = Buf[1]; // fprintf(stderr, "colres=%d bpp=%d bgcol=%d\n", GifFile->SColorResolution, BitsPerPixel, GifFile->SBackGroundColor); if (Buf[0] & 0x80) { /* Do we have global color map? */ // fprintf(stderr, "have gcolormap\n"); GifFile->SColorMap = MakeMapObject(1 << BitsPerPixel, NULL); /* Get the global color map: */ for (i = 0; i < GifFile->SColorMap->ColorCount; i++) { if (fread(Buf, 1, 3, Private->File) != 3) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } GifFile->SColorMap->Colors[i].Red = Buf[0]; GifFile->SColorMap->Colors[i].Green = Buf[1]; GifFile->SColorMap->Colors[i].Blue = Buf[2]; } } return GIF_OK; } /****************************************************************************** * This routine should be called before any attemp to read an image. * ******************************************************************************/ int CGIFFF DGifGetRecordType(CGIFFF GifFileType *GifFile, CGIFFF GifRecordType *Type) { GifByteType Buf; GifFilePrivateType *Private = (GifFilePrivateType *) GifFile->Private; if (!IS_READABLE(Private)) { /* This file was NOT open for reading: */ _GifError = D_GIF_ERR_NOT_READABLE; return GIF_ERROR; } if (fread(&Buf, 1, 1, Private->File) != 1) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } // fprintf(stderr, "record %d at offset %ld\n", Buf&255, ftell(Private->File)); switch (Buf) { case ',': *Type = IMAGE_DESC_RECORD_TYPE; break; case '!': *Type = EXTENSION_RECORD_TYPE; break; case ';': *Type = TERMINATE_RECORD_TYPE; break; default: *Type = UNDEFINED_RECORD_TYPE; // fprintf(stderr, "wrong record %d at offset %ld\n", Buf&255, ftell(Private->File)); _GifError = D_GIF_ERR_WRONG_RECORD; return GIF_ERROR; } return GIF_OK; } /****************************************************************************** * This routine should be called before any attemp to read an image. * * Note it is assumed the Image desc. header (',') has been read. * ******************************************************************************/ int CGIFFF DGifGetImageDesc(CGIFFF GifFileType *GifFile) { int i, BitsPerPixel; GifByteType Buf[3]; GifImageDesc Image; GifFilePrivateType *Private = (GifFilePrivateType *) GifFile->Private; memset(&Image, 0, sizeof(Image)); if (!IS_READABLE(Private)) { /* This file was NOT open for reading: */ _GifError = D_GIF_ERR_NOT_READABLE; return GIF_ERROR; } if (DGifGetWord(Private->File, &Image.Left) == GIF_ERROR || DGifGetWord(Private->File, &Image.Top) == GIF_ERROR || DGifGetWord(Private->File, &Image.Width) == GIF_ERROR || DGifGetWord(Private->File, &Image.Height) == GIF_ERROR) return GIF_ERROR; if (fread(Buf, 1, 1, Private->File) != 1) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } BitsPerPixel = (Buf[0] & 0x07) + 1; Image.Interlace = (Buf[0] & 0x40); if (Buf[0] & 0x80) { /* Does this image have local color map? */ if (Image.ColorMap && GifFile->SavedImages == NULL) FreeMapObject(Image.ColorMap); Image.ColorMap = MakeMapObject(1 << BitsPerPixel, NULL); /* Get the image local color map: */ for (i = 0; i < Image.ColorMap->ColorCount; i++) { if (fread(Buf, 1, 3, Private->File) != 3) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } Image.ColorMap->Colors[i].Red = Buf[0]; Image.ColorMap->Colors[i].Green = Buf[1]; Image.ColorMap->Colors[i].Blue = Buf[2]; } } /**** pts ****/ if (NULL!=GifFile->SavedImages) { GifFile->SavedImages = (SavedImage *)xrealloc(GifFile->SavedImages, sizeof(SavedImage) * (GifFile->ImageCount + 1)); } else { assert(GifFile->ImageCount==0); GifFile->SavedImages = (SavedImage *)xmalloc(sizeof(SavedImage)); } { SavedImage *sp; sp = &GifFile->SavedImages[GifFile->ImageCount]; memcpy(&sp->ImageDesc, &Image, sizeof(GifImageDesc)); sp->RasterBits = (GifPixelType *)NULL; sp->ExtensionBlockCount = 0; sp->ExtensionBlocks = (ExtensionBlock *)NULL; sp->delay=0; sp->dispose=0; sp->iter=1; sp->transp=(-1); } GifFile->ImageCount++; Private->PixelCount = (long) Image.Width * (long) Image.Height; /* Reset decompress algorithm parameters. */ if (DGifSetupDecompress(GifFile)==GIF_ERROR) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } return GIF_OK; } /****************************************************************************** * Get one full scanned line (Line) of length LineLen from GIF file. * ******************************************************************************/ int CGIFFF DGifGetLine(CGIFFF GifFileType *GifFile, CGIFFF GifPixelType *Line, int LineLen) { GifByteType *Dummy; GifFilePrivateType *Private = (GifFilePrivateType *) GifFile->Private; if (!IS_READABLE(Private)) { /* This file was NOT open for reading: */ _GifError = D_GIF_ERR_NOT_READABLE; return GIF_ERROR; } /**** pts ****/ /* if (!LineLen) LineLen = GifFile->Image.Width; */ #if defined(__MSDOS__) || defined(__GNUC__) if ((Private->PixelCount -= LineLen) > 0xffff0000UL) { #else if ((Private->PixelCount -= LineLen) > 0xffff0000) { #endif /* __MSDOS__ */ _GifError = D_GIF_ERR_DATA_TOO_BIG; return GIF_ERROR; } if (DGifDecompressLine(GifFile, Line, LineLen) == GIF_OK) { if (Private->PixelCount == 0) { /* We probably would not be called any more, so lets clean */ /* everything before we return: need to flush out all rest of */ /* image until empty block (size 0) detected. We use GetCodeNext.*/ do if (DGifGetCodeNext(GifFile, &Dummy) == GIF_ERROR) return GIF_ERROR; while (Dummy != NULL); } return GIF_OK; } else return GIF_ERROR; } /****************************************************************************** * Put one pixel (Pixel) into GIF file. * ******************************************************************************/ int CGIFFF DGifGetPixel(CGIFFF GifFileType *GifFile, CGIFFF GifPixelType Pixel) { GifByteType *Dummy; GifFilePrivateType *Private = (GifFilePrivateType *) GifFile->Private; if (!IS_READABLE(Private)) { /* This file was NOT open for reading: */ _GifError = D_GIF_ERR_NOT_READABLE; return GIF_ERROR; } #if defined(__MSDOS__) || defined(__GNUC__) if (--Private->PixelCount > 0xffff0000UL) #else if (--Private->PixelCount > 0xffff0000) #endif /* __MSDOS__ */ { _GifError = D_GIF_ERR_DATA_TOO_BIG; return GIF_ERROR; } if (DGifDecompressLine(GifFile, &Pixel, 1) == GIF_OK) { if (Private->PixelCount == 0) { /* We probably would not be called any more, so lets clean */ /* everything before we return: need to flush out all rest of */ /* image until empty block (size 0) detected. We use GetCodeNext.*/ do if (DGifGetCodeNext(GifFile, &Dummy) == GIF_ERROR) return GIF_ERROR; while (Dummy != NULL); } return GIF_OK; } else return GIF_ERROR; } /****************************************************************************** * Get an extension block (see GIF manual) from gif file. This routine only * * returns the first data block, and DGifGetExtensionNext shouldbe called * * after this one until NULL extension is returned. * * The Extension should NOT be freed by the user (not dynamically allocated).* * Note it is assumed the Extension desc. header ('!') has been read. * ******************************************************************************/ int CGIFFF DGifGetExtension(CGIFFF GifFileType *GifFile, int *ExtCode, CGIFFF GifByteType **Extension) { GifByteType Buf; GifFilePrivateType *Private = (GifFilePrivateType *) GifFile->Private; if (!IS_READABLE(Private)) { /* This file was NOT open for reading: */ _GifError = D_GIF_ERR_NOT_READABLE; return GIF_ERROR; } if (fread(&Buf, 1, 1, Private->File) != 1) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } *ExtCode = Buf; return DGifGetExtensionNext(GifFile, Extension); } /****************************************************************************** * Get a following extension block (see GIF manual) from gif file. This * * routine sould be called until NULL Extension is returned. * * The Extension should NOT be freed by the user (not dynamically allocated).* ******************************************************************************/ int CGIFFF DGifGetExtensionNext(CGIFFF GifFileType *GifFile, CGIFFF GifByteType **Extension) { GifByteType Buf; GifFilePrivateType *Private = (GifFilePrivateType *) GifFile->Private; if (fread(&Buf, 1, 1, Private->File) != 1) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } if (Buf > 0) { *Extension = Private->Buf; /* Use private unused buffer. */ (*Extension)[0] = Buf; /* Pascal strings notation (pos. 0 is len.). */ if (fread(&((*Extension)[1]), 1, Buf, Private->File) != Buf) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } } else *Extension = NULL; return GIF_OK; } /****************************************************************************** * This routine should be called last, to close the GIF file. * ******************************************************************************/ int CGIFFF DGifCloseFile(CGIFFF GifFileType *GifFile) { GifFilePrivateType *Private; if (GifFile == NULL) return GIF_ERROR; Private = (GifFilePrivateType *) GifFile->Private; if (!IS_READABLE(Private)) { /* This file was NOT open for reading: */ _GifError = D_GIF_ERR_NOT_READABLE; return GIF_ERROR; } #if 0 /**** pts ****/ if (GifFile->Image.ColorMap) FreeMapObject(GifFile->Image.ColorMap); #endif if (GifFile->SColorMap) FreeMapObject(GifFile->SColorMap); if (Private) free((char *) Private); if (GifFile->SavedImages) FreeSavedImages(GifFile); free(GifFile); #if 0 /**** pts ****/ if (fclose(File) != 0) { _GifError = D_GIF_ERR_CLOSE_FAILED; return GIF_ERROR; } #endif return GIF_OK; } /****************************************************************************** * Get 2 bytes (word) from the given file: * ******************************************************************************/ static int DGifGetWord(FILE *File, int *Word) { unsigned char c[2]; if (fread(c, 1, 2, File) != 2) { CGIFFF _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } *Word = (((unsigned int) c[1]) << 8) + c[0]; return GIF_OK; } /****************************************************************************** * Get the image code in compressed form. his routine can be called if the * * information needed to be piped out as is. Obviously this is much faster * * than decoding and encoding again. This routine should be followed by calls * * to DGifGetCodeNext, until NULL block is returned. * * The block should NOT be freed by the user (not dynamically allocated). * ******************************************************************************/ int CGIFFF DGifGetCode(CGIFFF GifFileType *GifFile, int *CodeSize, CGIFFF GifByteType **CodeBlock) { GifFilePrivateType *Private = (GifFilePrivateType *) GifFile->Private; if (!IS_READABLE(Private)) { /* This file was NOT open for reading: */ _GifError = D_GIF_ERR_NOT_READABLE; return GIF_ERROR; } *CodeSize = Private->BitsPerPixel; return DGifGetCodeNext(GifFile, CodeBlock); } /****************************************************************************** * Continue to get the image code in compressed form. This routine should be * * called until NULL block is returned. * * The block should NOT be freed by the user (not dynamically allocated). * ******************************************************************************/ int CGIFFF DGifGetCodeNext(CGIFFF GifFileType *GifFile, CGIFFF GifByteType **CodeBlock) { GifByteType Buf; GifFilePrivateType *Private = (GifFilePrivateType *) GifFile->Private; if (fread(&Buf, 1, 1, Private->File) != 1) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } if (Buf > 0) { *CodeBlock = Private->Buf; /* Use private unused buffer. */ (*CodeBlock)[0] = Buf; /* Pascal strings notation (pos. 0 is len.). */ if (fread(&((*CodeBlock)[1]), 1, Buf, Private->File) != Buf) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } } else { *CodeBlock = NULL; Private->Buf[0] = 0; /* Make sure the buffer is empty! */ Private->PixelCount = 0; /* And local info. indicate image read. */ } return GIF_OK; } /****************************************************************************** * Setup the LZ decompression for this image: * ******************************************************************************/ static int DGifSetupDecompress(CGIFFF GifFileType *GifFile) { int i, BitsPerPixel; CGIFFF GifByteType CodeSize; unsigned int *Prefix; GifFilePrivateType *Private = (GifFilePrivateType *) GifFile->Private; if (fread(&CodeSize, 1, 1, Private->File) != 1) /* Read Code size from file. */ return GIF_ERROR; BitsPerPixel = CodeSize; Private->Buf[0] = 0; /* Input Buffer empty. */ Private->BitsPerPixel = BitsPerPixel; Private->ClearCode = (1 << BitsPerPixel); Private->EOFCode = Private->ClearCode + 1; Private->RunningCode = Private->EOFCode + 1; Private->RunningBits = BitsPerPixel + 1; /* Number of bits per code. */ Private->MaxCode1 = 1 << Private->RunningBits; /* Max. code + 1. */ Private->StackPtr = 0; /* No pixels on the pixel stack. */ Private->LastCode = NO_SUCH_CODE; Private->CrntShiftState = 0; /* No information in CrntShiftDWord. */ Private->CrntShiftDWord = 0; Prefix = Private->Prefix; for (i = 0; i <= LZ_MAX_CODE; i++) Prefix[i] = NO_SUCH_CODE; return GIF_OK; } /****************************************************************************** * The LZ decompression routine: * * This version decompress the given gif file into Line of length LineLen. * * This routine can be called few times (one per scan line, for example), in * * order the complete the whole image. * ******************************************************************************/ static int DGifDecompressLine(CGIFFF GifFileType *GifFile, CGIFFF GifPixelType *Line, int LineLen) { int i = 0, j, CrntCode, EOFCode, ClearCode, CrntPrefix, LastCode, StackPtr; CGIFFF GifByteType *Stack, *Suffix; unsigned int *Prefix; GifFilePrivateType *Private = (GifFilePrivateType *) GifFile->Private; StackPtr = Private->StackPtr; Prefix = Private->Prefix; Suffix = Private->Suffix; Stack = Private->Stack; EOFCode = Private->EOFCode; ClearCode = Private->ClearCode; LastCode = Private->LastCode; if (StackPtr != 0) { /* Let pop the stack off before continueing to read the gif file: */ while (StackPtr != 0 && i < LineLen) Line[i++] = Stack[--StackPtr]; } while (i < LineLen) { /* Decode LineLen items. */ if (DGifDecompressInput(Private, &CrntCode) == GIF_ERROR) return GIF_ERROR; /*fprintf(stderr,"CrntCode=0x%x\n",CrntCode);*/ if (CrntCode == EOFCode) { /* Note however that usually we will not be here as we will stop */ /* decoding as soon as we got all the pixel, or EOF code will */ /* not be read at all, and DGifGetLine/Pixel clean everything. */ if (i != LineLen - 1 || Private->PixelCount != 0) { CGIFFF _GifError = D_GIF_ERR_EOF_TOO_SOON; return GIF_ERROR; } i++; } else if (CrntCode == ClearCode) { /* We need to start over again: */ for (j = 0; j <= LZ_MAX_CODE; j++) Prefix[j] = NO_SUCH_CODE; Private->RunningCode = Private->EOFCode + 1; Private->RunningBits = Private->BitsPerPixel + 1; Private->MaxCode1 = 1 << Private->RunningBits; LastCode = Private->LastCode = NO_SUCH_CODE; } else { /* Its regular code - if in pixel range simply add it to output */ /* stream, otherwise trace to codes linked list until the prefix */ /* is in pixel range: */ if (CrntCode < ClearCode) { /* This is simple - its pixel scalar, so add it to output: */ Line[i++] = CrntCode; } else { /* Its a code to needed to be traced: trace the linked list */ /* until the prefix is a pixel, while pushing the suffix */ /* pixels on our stack. If we done, pop the stack in reverse */ /* (thats what stack is good for!) order to output. */ if (Prefix[CrntCode] == NO_SUCH_CODE) { /* Only allowed if CrntCode is exactly the running code: */ /* In that case CrntCode = XXXCode, CrntCode or the */ /* prefix code is last code and the suffix char is */ /* exactly the prefix of last code! */ if (CrntCode == Private->RunningCode - 2) { CrntPrefix = LastCode; Suffix[Private->RunningCode - 2] = Stack[StackPtr++] = DGifGetPrefixChar(Prefix, LastCode, ClearCode); } else { CGIFFF _GifError = D_GIF_ERR_IMAGE_DEFECT; return GIF_ERROR; } } else CrntPrefix = CrntCode; /* Now (if image is O.K.) we should not get an NO_SUCH_CODE */ /* During the trace. As we might loop forever, in case of */ /* defective image, we count the number of loops we trace */ /* and stop if we got LZ_MAX_CODE. obviously we can not */ /* loop more than that. */ j = 0; while (j++ <= LZ_MAX_CODE && CrntPrefix > ClearCode && CrntPrefix <= LZ_MAX_CODE) { Stack[StackPtr++] = Suffix[CrntPrefix]; CrntPrefix = Prefix[CrntPrefix]; } if (j >= LZ_MAX_CODE || CrntPrefix > LZ_MAX_CODE) { CGIFFF _GifError = D_GIF_ERR_IMAGE_DEFECT; return GIF_ERROR; } /* Push the last character on stack: */ Stack[StackPtr++] = CrntPrefix; /* Now lets pop all the stack into output: */ while (StackPtr != 0 && i < LineLen) Line[i++] = Stack[--StackPtr]; } if (LastCode != NO_SUCH_CODE) { Prefix[Private->RunningCode - 2] = LastCode; if (CrntCode == Private->RunningCode - 2) { /* Only allowed if CrntCode is exactly the running code: */ /* In that case CrntCode = XXXCode, CrntCode or the */ /* prefix code is last code and the suffix char is */ /* exactly the prefix of last code! */ Suffix[Private->RunningCode - 2] = DGifGetPrefixChar(Prefix, LastCode, ClearCode); } else { Suffix[Private->RunningCode - 2] = DGifGetPrefixChar(Prefix, CrntCode, ClearCode); } } LastCode = CrntCode; } } Private->LastCode = LastCode; Private->StackPtr = StackPtr; return GIF_OK; } /****************************************************************************** * Routine to trace the Prefixes linked list until we get a prefix which is * * not code, but a pixel value (less than ClearCode). Returns that pixel value.* * If image is defective, we might loop here forever, so we limit the loops to * * the maximum possible if image O.k. - LZ_MAX_CODE times. * ******************************************************************************/ static int DGifGetPrefixChar(unsigned int *Prefix, int Code, int ClearCode) { int i = 0; while (Code > ClearCode && i++ <= LZ_MAX_CODE) Code = Prefix[Code]; return Code; } /****************************************************************************** * Interface for accessing the LZ codes directly. Set Code to the real code * * (12bits), or to -1 if EOF code is returned. * ******************************************************************************/ int CGIFFF DGifGetLZCodes(CGIFFF GifFileType *GifFile, int *Code) { GifByteType *CodeBlock; GifFilePrivateType *Private = (GifFilePrivateType *) GifFile->Private; if (!IS_READABLE(Private)) { /* This file was NOT open for reading: */ _GifError = D_GIF_ERR_NOT_READABLE; return GIF_ERROR; } if (DGifDecompressInput(Private, Code) == GIF_ERROR) return GIF_ERROR; if (*Code == Private->EOFCode) { /* Skip rest of codes (hopefully only NULL terminating block): */ do if (DGifGetCodeNext(GifFile, &CodeBlock) == GIF_ERROR) return GIF_ERROR; while (CodeBlock != NULL); *Code = -1; } else if (*Code == Private->ClearCode) { /* We need to start over again: */ Private->RunningCode = Private->EOFCode + 1; Private->RunningBits = Private->BitsPerPixel + 1; Private->MaxCode1 = 1 << Private->RunningBits; } return GIF_OK; } /****************************************************************************** * The LZ decompression input routine: * * This routine is responsable for the decompression of the bit stream from * * 8 bits (bytes) packets, into the real codes. * * Returns GIF_OK if read succesfully. * ******************************************************************************/ static int DGifDecompressInput(GifFilePrivateType *Private, int *Code) { CGIFFF GifByteType NextByte; static unsigned int CodeMasks[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff, 0x01ff, 0x03ff, 0x07ff, 0x0fff }; /* The image can't contain more than LZ_BITS per code. */ if (Private->RunningBits > LZ_BITS) { return GIF_ERROR; } while (Private->CrntShiftState < Private->RunningBits) { /* Needs to get more bytes from input stream for next code: */ if (DGifBufferedInput(Private->File, Private->Buf, &NextByte) == GIF_ERROR) { return GIF_ERROR; } Private->CrntShiftDWord |= ((unsigned long) NextByte) << Private->CrntShiftState; Private->CrntShiftState += 8; } *Code = Private->CrntShiftDWord & CodeMasks[Private->RunningBits]; Private->CrntShiftDWord >>= Private->RunningBits; Private->CrntShiftState -= Private->RunningBits; /* If code cannt fit into RunningBits bits, must raise its size. Note */ /* however that codes above 4095 are used for special signaling. */ /* If we're using LZ_BITS bits already and we're at the max code, just */ /* keep using the table as it is, don't increment Private->RunningCode.*/ if (Private->RunningCode < LZ_MAX_CODE + 2 && ++Private->RunningCode > Private->MaxCode1 && Private->RunningBits < LZ_BITS) { Private->MaxCode1 <<= 1; Private->RunningBits++; } return GIF_OK; } /****************************************************************************** * This routines read one gif data block at a time and buffers it internally * * so that the decompression routine could access it. * * The routine returns the next byte from its internal buffer (or read next * * block in if buffer empty) and returns GIF_OK if succesful. * ******************************************************************************/ static int DGifBufferedInput(FILE *File, CGIFFF GifByteType *Buf, CGIFFF GifByteType *NextByte) { if (Buf[0] == 0) { /* Needs to read the next buffer - this one is empty: */ if (fread(Buf, 1, 1, File) != 1) { CGIFFF _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } if (fread(&Buf[1], 1, Buf[0], File) != Buf[0]) { CGIFFF _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } *NextByte = Buf[1]; Buf[1] = 2; /* We use now the second place as last char read! */ Buf[0]--; } else { *NextByte = Buf[Buf[1]++]; Buf[0]--; } return GIF_OK; } /****************************************************************************** * This routine reads an entire GIF into core, hanging all its state info off * * the GifFileType pointer. Call DGifOpenFileName() or DGifOpenFileHandle() * * first to initialize I/O. Its inverse is EGifSpew(). * ******************************************************************************/ int CGIFFF DGifSlurp(CGIFFF GifFileType *GifFile) { static unsigned InterlacedOffset[] = { 0, 4, 2, 1 }, /* The way Interlaced image should. */ InterlacedJumps[] = { 8, 8, 4, 2 }; /* be read - offsets and jumps... */ /**** pts: unused vars ****/ /* int i, j, Error, ImageSize; */ int ext_code; GifRecordType RecordType; /**** pts ****/ SavedImage *sp=0; /**** pts: avoid gcc warning */ /** Extension info of next SavedImage */ SavedImage ext; /** No-extension info */ SavedImage noext; GifByteType *ExtData; /**** pts ****/ memset(&noext, 0, sizeof(noext)); noext.delay=0; noext.dispose=0; noext.iter=1; noext.transp=(-1); noext.ExtensionBlocks=NULL; noext.ExtensionBlockCount=0; ext=noext; /**** pts ****/ GifFile->SavedImages=0; do { if (DGifGetRecordType(GifFile, &RecordType) == GIF_ERROR) return(GIF_ERROR); switch (RecordType) { case IMAGE_DESC_RECORD_TYPE: if (DGifGetImageDesc(GifFile) == GIF_ERROR) return(GIF_ERROR); /**** pts: DGifGetImageDesc has already allocated the mem ****/ sp = &GifFile->SavedImages[GifFile->ImageCount-1]; /**** pts: apply extensions to the image just read */ ext.RasterBits=sp->RasterBits; ext.ImageDesc=sp->ImageDesc; *sp=ext; ext=noext; /**** pts ****/ sp->RasterBits = (GifPixelType*) xmalloc((0L+sp->ImageDesc.Width) * sp->ImageDesc.Height * sizeof(GifPixelType)); if (sp->ImageDesc.Interlace) { unsigned i, j, Height=sp->ImageDesc.Height, Width=sp->ImageDesc.Width; /* Need to perform 4 passes on the images: */ for (i = 0; i < 4; i++) for (j = InterlacedOffset[i]; j < Height; j += InterlacedJumps[i]) if (DGifGetLine(GifFile, sp->RasterBits+Width*j, Width) != GIF_OK) return GIF_ERROR; } else { if (DGifGetLine(GifFile, sp->RasterBits, (0L+sp->ImageDesc.Width) * sp->ImageDesc.Height) == GIF_ERROR) return(GIF_ERROR); } break; case EXTENSION_RECORD_TYPE: if (DGifGetExtension(GifFile,&ext_code,&ExtData)==GIF_ERROR) return(GIF_ERROR); if (ExtData!=NULL) { #if 0 /**** pts ****/ ep = &ext.ExtensionBlocks[ext.ExtensionBlockCount++]; ep->ByteCount = ExtData[0]; ep->Bytes = (GifByteType *)xmalloc(ep->ByteCount * sizeof(GifByteType)); memcpy(ep->Bytes, ExtData, ep->ByteCount * sizeof(char)); #else /**** pts ****/ if (0xf9==(unsigned char)(ext_code)) { if (ExtData[0] < 4) { ext_too_short: _GifError = D_GIF_ERR_EXT_TOO_SHORT; return GIF_ERROR; } ext.dispose=ExtData[1]>>2; ext.delay=(ExtData[3] << 8) | ExtData[2]; if ((ExtData[1] & 0x01) == 1) { if (ExtData[0] < 5) goto ext_too_short; ext.transp=ExtData[4]; } } else if (0xff==(unsigned char)(ext_code)) { if (ExtData[0] < 4) goto ext_too_short; ext.iter=(ExtData[3] << 8) | ExtData[2]; } else { AddExtensionBlock(&ext, ExtData[0], ExtData+1); ext.ExtensionBlocks[ext.ExtensionBlockCount-1].code=ext_code; } #endif while (1) { if (DGifGetExtensionNext(GifFile, &ExtData) == GIF_ERROR) return(GIF_ERROR); #if 0 /**** pts ****/ ep = &ext.ExtensionBlocks[ext.ExtensionBlockCount++]; ep->ByteCount = ExtData[0]; ep->Bytes = (GifByteType *)xmalloc(ep->ByteCount * sizeof(GifByteType)); memcpy(ep->Bytes,ExtData,ep->ByteCount * sizeof(char)); #else if (ExtData==NULL) break; AddExtensionBlock(&ext, ExtData[0], ExtData+1); ext.ExtensionBlocks[ext.ExtensionBlockCount-1].code=ext_code; #endif } } break; case TERMINATE_RECORD_TYPE: break; default: /* Should be trapped by DGifGetRecordType */ break; } } while (RecordType != TERMINATE_RECORD_TYPE); return(GIF_OK); } /* __END__ */
null